From f20980157933fa3cecc512bd4bf538d9233c7ddb Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 10:43:19 -0500 Subject: [PATCH 01/22] ws-cleanup-types: Types, api, host: honest annotations; return the full annotated value count --- src/Formats/Types.luau | 18 +++++------ src/Formats/archive/7z/init.luau | 12 +++---- src/Formats/audio/aiff/init.luau | 32 +++++++++---------- src/Formats/codecs/Jpeg/Decode.luau | 12 +++---- src/Formats/codecs/Lzma/init.luau | 4 +-- src/Formats/codecs/Raster.luau | 14 ++++---- src/Formats/codecs/Video/init.luau | 14 ++++---- src/Formats/codecs/Xml/Parse.luau | 14 ++++---- src/Formats/containers/Archive.luau | 6 ++-- src/Formats/containers/AudioWrap.luau | 4 +-- src/Formats/containers/Demux.luau | 2 +- src/Formats/containers/Ebml/init.luau | 18 +++++------ src/Formats/font/bmfont/init.luau | 2 +- src/Formats/font/woff/init.luau | 18 +++++------ src/Formats/host/Love.luau | 18 +++++------ src/Formats/host/init.luau | 8 ++--- src/Formats/image/tiff/init.luau | 10 +++--- src/Formats/init.luau | 30 ++++++++--------- src/Formats/ops/ImageOps/init.luau | 46 +++++++++++++-------------- src/Formats/vector/tiled/Data.luau | 6 ++-- src/Formats/vector/tiled/Tmj.luau | 4 +-- src/Formats/vector/tiled/Tmx.luau | 2 +- 22 files changed, 147 insertions(+), 147 deletions(-) diff --git a/src/Formats/Types.luau b/src/Formats/Types.luau index f34b569..effef54 100644 --- a/src/Formats/Types.luau +++ b/src/Formats/Types.luau @@ -672,7 +672,7 @@ local OBJECT = { __object = true } local objectMeta: { [any]: { any } } = setmetatable({}, { __mode = "k" }) :: any -- object -> its key order -- object(t?, keys?) -> t marked as an object, keys = its key order (default: none recorded; Types.set appends) function Types.object(t: { [any]: any }?, keys: { any }?): { [any]: any } - local o = t or {} + local o: { [any]: any } = t or {} if getmetatable(o) == nil then setmetatable(o, OBJECT) end @@ -746,13 +746,13 @@ local function p2(n: number): string return string.format("%02d", n) end local function fmtDate(d: any): string - local s = "" + local s: string = "" if d.year then s = string.format("%04d-%02d-%02d", d.year, d.month or 1, d.day or 1) end if d.hour then if s ~= "" then - s ..= "T" + s = s .. "T" end s ..= p2(d.hour) .. ":" .. p2(d.minute or 0) .. ":" .. p2(d.second or 0) local ns = d.nanosecond or 0 @@ -841,11 +841,11 @@ end -- "07:32:00.999", "1979-05-27 07:32:00Z", lower-case t / z accepted); out-of-range fields return nil function DateLib.parse(s: string): Date? local d: any = {} - local rest = s + local rest: string = s local y, mo, dd, r1 = string.match(rest, "^(%d%d%d%d)%-(%d%d)%-(%d%d)(.*)$") if y then d.year, d.month, d.day = tonumber(y), tonumber(mo), tonumber(dd) - rest = r1 + rest = r1 :: string if rest == "" then return if DateLib.valid(d) then DateLib.new(d) else nil end @@ -860,17 +860,17 @@ function DateLib.parse(s: string): Date? return nil end d.hour, d.minute = tonumber(h), tonumber(mi) - rest = r2 + rest = r2 :: string local sec, r3 = string.match(rest, "^:(%d%d)(.*)$") if not sec then return nil end d.second = tonumber(sec) - rest = r3 + rest = r3 :: string local frac, r4 = string.match(rest, "^%.(%d+)(.*)$") if frac then d.nanosecond = tonumber(string.sub(frac .. "000000000", 1, 9)) - rest = r4 + rest = r4 :: string else d.nanosecond = 0 end @@ -1082,6 +1082,6 @@ Types.CATEGORIES = table.freeze({ subtitle = "subtitles", music = "music", playlist = "playlist", -}) +} :: { [string]: string }) return Types diff --git a/src/Formats/archive/7z/init.luau b/src/Formats/archive/7z/init.luau index 39097fd..780f05c 100644 --- a/src/Formats/archive/7z/init.luau +++ b/src/Formats/archive/7z/init.luau @@ -169,7 +169,7 @@ local function decodeFolder(ctx: Ctx, s: Header.Streams, f: Header.Folder): (buf end local b = buffer.create(size) buffer.copy(b, 0, src, so, size) - return b + return b, nil elseif id == "\3\1\1" then if buffer.len(c.props) < 5 then return nil, Err.new(Err.CORRUPT, "bad LZMA properties") @@ -195,7 +195,7 @@ local function decodeFolder(ctx: Ctx, s: Header.Streams, f: Header.Folder): (buf if buffer.len(b) ~= size then return nil, Err.new(Err.CORRUPT, methodName(id) .. " stream decodes to the wrong size") end - return b + return b, nil elseif FILTERS[id] then if sl ~= size then return nil, Err.new(Err.CORRUPT, "filter size mismatch") @@ -206,7 +206,7 @@ local function decodeFolder(ctx: Ctx, s: Header.Streams, f: Header.Folder): (buf if not ok then return nil, e end - return b + return b, nil end return nil, Err.new(Err.UNSUPPORTED, methodName(id) .. " is not supported") end @@ -311,7 +311,7 @@ function SevenZip.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Archive? local function folderData(fi: number): (buffer?, Err.Err?) local c = cache[fi] if c then - return c + return c, nil end local f = s.folders[fi] local d, e = decodeFolder(ctx, s, f) @@ -322,7 +322,7 @@ function SevenZip.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Archive? return nil, Err.new(Err.CHECKSUM, "folder CRC-32 mismatch") end cache[fi] = d - return d + return d, nil end local si = 0 for _, file in parsed.files do @@ -376,7 +376,7 @@ function SevenZip.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Archive? if checkCrc and want and Crc32.raw(out, 0, size) ~= want then return nil, Err.new(Err.CHECKSUM, "CRC-32 mismatch in " .. file.name) end - return out + return out, nil end end Archive.put(a, e) diff --git a/src/Formats/audio/aiff/init.luau b/src/Formats/audio/aiff/init.luau index 94b02c2..dfd2a29 100644 --- a/src/Formats/audio/aiff/init.luau +++ b/src/Formats/audio/aiff/init.luau @@ -78,42 +78,42 @@ end local function sampleFormat(comp: string, bits: number): (string?, string?) if comp == "NONE" or comp == "twos" or comp == "" then if bits >= 1 and bits <= 8 then - return "s8" + return "s8", nil elseif bits <= 16 then - return "s16be" + return "s16be", nil elseif bits <= 24 then - return "s24be" + return "s24be", nil elseif bits <= 32 then - return "s32be" + return "s32be", nil end return nil, "bad sample size " .. bits elseif comp == "sowt" then if bits >= 1 and bits <= 8 then - return "s8" + return "s8", nil elseif bits <= 16 then - return "s16le" + return "s16le", nil elseif bits <= 24 then - return "s24le" + return "s24le", nil elseif bits <= 32 then - return "s32le" + return "s32le", nil end return nil, "bad sample size " .. bits elseif comp == "raw " then - return "u8" + return "u8", nil elseif comp == "in24" then - return "s24be" + return "s24be", nil elseif comp == "in32" then - return "s32be" + return "s32be", nil elseif comp == "42ni" then - return "s32le" + return "s32le", nil elseif comp == "fl32" or comp == "FL32" then - return "f32be" + return "f32be", nil elseif comp == "fl64" or comp == "FL64" then - return "f64be" + return "f64be", nil elseif comp == "ulaw" or comp == "ULAW" then - return "ulaw" + return "ulaw", nil elseif comp == "alaw" or comp == "ALAW" then - return "alaw" + return "alaw", nil end return nil, "compression " .. string.format("%q", comp) end diff --git a/src/Formats/codecs/Jpeg/Decode.luau b/src/Formats/codecs/Jpeg/Decode.luau index 05a0a7f..6cae5ff 100644 --- a/src/Formats/codecs/Jpeg/Decode.luau +++ b/src/Formats/codecs/Jpeg/Decode.luau @@ -429,7 +429,7 @@ function Decode.parse(b: buffer, base: number, n: number, opts: any, headerOnly: frame = f st.frame = f if headerOnly then - return st + return st, nil, nil end elseif SOF_REFUSED[m] then return nil, "unsupported", SOF_REFUSED[m] .. " JPEG" @@ -559,12 +559,12 @@ function Decode.parse(b: buffer, base: number, n: number, opts: any, headerOnly: st.icc = icc end if headerOnly then - return st + return st, nil, nil end if scans == 0 then return nil, "truncated", "no image data" end - return st + return st, nil, nil end local SPACE_IDS = { gray = Color.GRAY, ycbcr = Color.YCC, rgb = Color.RGB, cmyk = Color.CMYK, ycck = Color.YCCK } @@ -697,7 +697,7 @@ end function Decode.outputYuv(st: State): (number?, number?, buffer?, string?) local f: Frame = st.frame if st.scale ~= 1 or f.precision ~= 8 then - return nil + return nil, nil, nil, nil end local comps = f.comps local space = colorSpaceOf(f, st.adobe, st.jfif) @@ -721,11 +721,11 @@ function Decode.outputYuv(st: State): (number?, number?, buffer?, string?) end end if not mode then - return nil + return nil, nil, nil, nil end for _, c in comps do if c.coef and not c.quant then - return nil -- output() reports the missing table + return nil, nil, nil, nil -- output() reports the missing table end end local w, h = f.width, f.height diff --git a/src/Formats/codecs/Lzma/init.luau b/src/Formats/codecs/Lzma/init.luau index f6f2825..cbb870a 100644 --- a/src/Formats/codecs/Lzma/init.luau +++ b/src/Formats/codecs/Lzma/init.luau @@ -319,7 +319,7 @@ function Lzma.filter(id: number, b: buffer, o: number, n: number, props: any?): return nil, Err.new(Err.CORRUPT, "bad delta filter properties") end Filters.delta(b, o, n, readu8(pb :: buffer, 0) + 1) - return true + return true, nil end local f = BCJ[id] if not f then @@ -332,7 +332,7 @@ function Lzma.filter(id: number, b: buffer, o: number, n: number, props: any?): return nil, Err.new(Err.CORRUPT, "bad BCJ filter properties") end f(b, o, n, start) - return true + return true, nil end -- ------------------------------------------------------------------------------------------------ xz diff --git a/src/Formats/codecs/Raster.luau b/src/Formats/codecs/Raster.luau index 953336e..4f06477 100644 --- a/src/Formats/codecs/Raster.luau +++ b/src/Formats/codecs/Raster.luau @@ -159,12 +159,12 @@ local function flatten(path: any, transform: Transform?, tolerance: number?, min local cmds = commands(path) local polys: { { number } } = {} if not cmds then - return polys + return polys, nil, nil, nil, nil end local m = transform or Raster.IDENTITY local a, b, c, d, e, f = m[1], m[2], m[3], m[4], m[5], m[6] if type(a) ~= "number" or type(b) ~= "number" or type(c) ~= "number" or type(d) ~= "number" or type(e) ~= "number" or type(f) ~= "number" then - return polys + return polys, nil, nil, nil, nil end local tol = tolerance or 0.1 if type(tol) ~= "number" or not (tol > 0.001) then @@ -271,7 +271,7 @@ local function flatten(path: any, transform: Transform?, tolerance: number?, min table.insert(polys, cur) end if #polys == 0 or bx0 ~= bx0 or by0 ~= by0 or bx1 ~= bx1 or by1 ~= by1 then - return polys + return polys, nil, nil, nil, nil end return polys, bx0, by0, bx1, by1 end @@ -411,7 +411,7 @@ function Raster.mask(path: any, opts: Options?): (Mask?, string?) local o: Options = opts or {} local polys, bx0, by0, bx1, by1 = Raster.flatten(path, o.transform, o.tolerance) if not bx0 then - return nil + return nil, nil end if abs(bx0 :: number) > LIMIT or abs(by0 :: number) > LIMIT or abs(bx1 :: number) > LIMIT or abs(by1 :: number) > LIMIT then return nil, "coordinates out of range" @@ -427,7 +427,7 @@ function Raster.mask(path: any, opts: Options?): (Mask?, string?) end local W, H = X1 - X0, Y1 - Y0 if W <= 0 or H <= 0 then - return nil + return nil, nil end local maxPixels = if type(o.maxPixels) == "number" then o.maxPixels else 2 ^ 26 if W * H > maxPixels then @@ -464,7 +464,7 @@ function Raster.mask(path: any, opts: Options?): (Mask?, string?) writeu8(cov, os + x, floor(v * 255 + 0.5)) end end - return { x = X0, y = Y0, width = W, height = H, coverage = cov } + return { x = X0, y = Y0, width = W, height = H, coverage = cov }, nil end -- ------------------------------------------------------------------------------------------------ filling @@ -533,7 +533,7 @@ function Raster.fill(img: any, path: any, paint: any, opts: Options?): (boolean, end end end - return true + return true, nil end -- ------------------------------------------------------------------------------------------------ stroking diff --git a/src/Formats/codecs/Video/init.luau b/src/Formats/codecs/Video/init.luau index d2d09d8..7c38620 100644 --- a/src/Formats/codecs/Video/init.luau +++ b/src/Formats/codecs/Video/init.luau @@ -51,7 +51,7 @@ function Video.simpleDecoder(decodeOne: (data: buffer, packet: Types.Packet) -> if q then return q[1], q[2], q[3] end - return nil + return nil, nil, nil end function self.flush(_: any) end function self.reset(_: any) @@ -155,15 +155,15 @@ local function rawDecoder(track: Types.Track, _opts: any?): (Types.VideoCodecDec if pf == "yuv420p" and bits == 8 then local img = Types.Image.new(w, h, "yuv420p") buffer.copy(img.pixels, 0, data, 0, need) - return img + return img, nil elseif pf == "yv12" then local img = Types.Image.new(w, h, "yuv420p") buffer.copy(img.pixels, 0, data, 0, w * h) buffer.copy(img.pixels, w * h, data, w * h + cw * ch, cw * ch) buffer.copy(img.pixels, w * h + cw * ch, data, w * h, cw * ch) - return img + return img, nil end - return rawPlanar(data, pf, bits, w, h) + return rawPlanar(data, pf, bits, w, h), nil end local bpp = if pf == "bgra" or pf == "rgba" then 4 else 3 local stride = if track.stride then track.stride else w * bpp @@ -185,7 +185,7 @@ local function rawDecoder(track: Types.Track, _opts: any?): (Types.VideoCodecDec buffer.writeu32(px, o + x * 4, a + b * 256 + c * 65536 + 0xff000000) end end - return img + return img, nil end) end @@ -269,7 +269,7 @@ local function mpeg1Decoder(_track: Types.Track, opts: any?): (Types.VideoCodecD if q then return q[1], q[2], q[3] end - return nil + return nil, nil, nil end function self.flush(_: any) for _ = 1, 4 do @@ -324,7 +324,7 @@ function Video.register(entry: Entry): (boolean, Err.Err?) for _, m in entry.matroska or {} do byMatroska[m] = entry.id end - return true + return true, nil end for _, e in BUILTIN do Video.register(e) diff --git a/src/Formats/codecs/Xml/Parse.luau b/src/Formats/codecs/Xml/Parse.luau index 4a04ff3..1cff3bc 100644 --- a/src/Formats/codecs/Xml/Parse.luau +++ b/src/Formats/codecs/Xml/Parse.luau @@ -291,33 +291,33 @@ function Parse.events(s: string, opts: Options?): () -> (string?, any, any, any) if kw == "SYSTEM" then local q = match(s, "^[ \t\n]+()", p + 6) :: any if not q then - return nil + return nil, nil, nil end local sys, e = literal(q) if not sys then - return nil + return nil, nil, nil end return "", sys, e elseif kw == "PUBLIC" then local q = match(s, "^[ \t\n]+()", p + 6) :: any if not q then - return nil + return nil, nil, nil end local pub, e = literal(q) if not pub or find(pub, "[^ \r\n%w%-'()+,./:=?;!*#@$_%%]") then - return nil + return nil, nil, nil end local r = match(s, "^[ \t\n]+()", e) :: any if not r then - return nil + return nil, nil, nil end local sys, e2 = literal(r) if not sys then - return nil + return nil, nil, nil end return pub, sys, e2 end - return nil + return nil, nil, nil end -- check an entity value's references and expand its character references (the rest expand when used) local function entityValue(v: string): string? diff --git a/src/Formats/containers/Archive.luau b/src/Formats/containers/Archive.luau index 1cdd84c..ead480e 100644 --- a/src/Formats/containers/Archive.luau +++ b/src/Formats/containers/Archive.luau @@ -59,7 +59,7 @@ function Methods.read(self: any, name: string): (buffer?, Err.Err?) return nil, Err.new(Err.ARG, "no entry named " .. tostring(name)) end if e.data then - return e.data + return e.data, nil end if e.load then local ok, b, err = pcall(e.load) @@ -69,9 +69,9 @@ function Methods.read(self: any, name: string): (buffer?, Err.Err?) if not b then return nil, err or Err.new(Err.CORRUPT, "entry " .. name .. ": decode failed") end - return b + return b, nil end - return buffer.create(0) + 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 diff --git a/src/Formats/containers/AudioWrap.luau b/src/Formats/containers/AudioWrap.luau index a2fa1d4..fa82ebe 100644 --- a/src/Formats/containers/AudioWrap.luau +++ b/src/Formats/containers/AudioWrap.luau @@ -242,7 +242,7 @@ end local function vorbisModes(id: buffer, setup: buffer): ({ number }?, { boolean }?) if buffer.len(id) < 30 or buffer.len(setup) < 8 then - return nil + return nil, nil end local bs = buffer.readu8(id, 28) local sizes = { 2 ^ (bs % 16), 2 ^ (bs // 16) } @@ -278,7 +278,7 @@ local function vorbisModes(id: buffer, setup: buffer): ({ number }?, { boolean } return sizes, out end end - return nil + return nil, nil end -- ------------------------------------------------------------------------------------------------ ADTS diff --git a/src/Formats/containers/Demux.luau b/src/Formats/containers/Demux.luau index 1ceec61..953550b 100644 --- a/src/Formats/containers/Demux.luau +++ b/src/Formats/containers/Demux.luau @@ -239,7 +239,7 @@ function D.info(self: Demux, track: number, k: number): (number?, number?, numbe local list = self.byTrack[track] local i = list and list[k] if not i then - return nil + return nil, nil, nil, nil, nil end return self.pts[i], self.dts[i], self.dur[i], self.key[i], self.len[i] end diff --git a/src/Formats/containers/Ebml/init.luau b/src/Formats/containers/Ebml/init.luau index 2efc113..bfd1ce4 100644 --- a/src/Formats/containers/Ebml/init.luau +++ b/src/Formats/containers/Ebml/init.luau @@ -21,11 +21,11 @@ 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 + return nil, nil end local b = readu8(buf, pos) if b == 0 then - return nil + return nil, nil end local len = 1 local mask = 0x80 @@ -34,7 +34,7 @@ function Ebml.vint(buf: buffer, pos: number, limit: number): (number?, number?) mask = mask // 2 end if pos + len > limit then - return nil + return nil, nil end local v = bit32.band(b, mask - 1) local allOnes = v == mask - 1 @@ -55,10 +55,10 @@ end 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 + return nil, nil end if v == -1 then - return nil + return nil, nil end return v - (2 ^ (7 * len - 1) - 1), len end @@ -66,12 +66,12 @@ 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 + 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 + return nil, nil end local v = b for i = 1, len - 1 do @@ -84,11 +84,11 @@ end 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 + return nil, nil, nil end local size, sl = Ebml.vint(buf, pos + il, limit) if not size or not sl then - return nil + return nil, nil, nil end return id, size, pos + il + sl end diff --git a/src/Formats/font/bmfont/init.luau b/src/Formats/font/bmfont/init.luau index e40aa7e..f5459ae 100644 --- a/src/Formats/font/bmfont/init.luau +++ b/src/Formats/font/bmfont/init.luau @@ -93,7 +93,7 @@ function Face.loadPages(self: any, loader: any?): (boolean?, Err.Err?) pages[i] = img end self.pages = pages - return true + return true, nil end local CHANNEL = { [1] = 2, [2] = 1, [4] = 0, [8] = 3 } -- chnl bit -> byte in rgba8 diff --git a/src/Formats/font/woff/init.luau b/src/Formats/font/woff/init.luau index 6b1bb91..84d8ad9 100644 --- a/src/Formats/font/woff/init.luau +++ b/src/Formats/font/woff/init.luau @@ -34,7 +34,7 @@ function Woff.sfnt(r: Bytes.Reader, opts: DecodeOptions?): (buffer?, Err.Err?, s local maxBytes = (opts and opts.maxBytes) or 2 ^ 28 local base = r.base if not r:match("wOFF") then - return nil, Err.new(Err.CORRUPT, "bad signature", base) + return nil, Err.new(Err.CORRUPT, "bad signature", base), nil end local flavor = r:string(4) local length = r:u32be() @@ -45,16 +45,16 @@ function Woff.sfnt(r: Bytes.Reader, opts: DecodeOptions?): (buffer?, Err.Err?, s local metaOffset, metaLength, metaOrig = r:u32be(), r:u32be(), r:u32be() r:skip(8) if r.err then - return nil, r.err + return nil, r.err, nil end if flavor == "ttcf" then - return nil, Err.new(Err.UNSUPPORTED, "font collections in WOFF", base + 4) + return nil, Err.new(Err.UNSUPPORTED, "font collections in WOFF", base + 4), nil end if length > r:size() then - return nil, Err.new(Err.TRUNCATED, string.format("file is %d bytes, header says %d", r:size(), length), base + 8) + return nil, Err.new(Err.TRUNCATED, string.format("file is %d bytes, header says %d", r:size(), length), base + 8), nil end if numTables == 0 or total > maxBytes or total < 12 + 16 * numTables then - return nil, Err.new(if total > maxBytes then Err.LIMIT else Err.CORRUPT, "bad table count or sfnt size", base + 12) + return nil, Err.new(if total > maxBytes then Err.LIMIT else Err.CORRUPT, "bad table count or sfnt size", base + 12), nil end local dir = {} for i = 1, numTables do @@ -62,7 +62,7 @@ function Woff.sfnt(r: Bytes.Reader, opts: DecodeOptions?): (buffer?, Err.Err?, s dir[i] = e end if r.err then - return nil, r.err + return nil, r.err, nil end local out = buffer.create(total) local w = Bytes.writer(12) @@ -80,10 +80,10 @@ function Woff.sfnt(r: Bytes.Reader, opts: DecodeOptions?): (buffer?, Err.Err?, s local p = 12 + 16 * numTables for i, e in dir do if e.offset + e.comp > r:size() or e.comp > e.orig then - return nil, Err.new(Err.CORRUPT, "table " .. e.tag .. " out of range", base + 44 + (i - 1) * 20) + return nil, Err.new(Err.CORRUPT, "table " .. e.tag .. " out of range", base + 44 + (i - 1) * 20), nil end if p + e.orig > total then - return nil, Err.new(Err.CORRUPT, "tables larger than totalSfntSize", base + 16) + return nil, Err.new(Err.CORRUPT, "tables larger than totalSfntSize", base + 16), nil end local d = 12 + (i - 1) * 16 buffer.writestring(out, d, e.tag) @@ -93,7 +93,7 @@ function Woff.sfnt(r: Bytes.Reader, opts: DecodeOptions?): (buffer?, Err.Err?, s if e.comp < e.orig then local t, err = Deflate.zlib(r.buf, base + e.offset, e.comp, e.orig) if not t then - return nil, Err.new((err :: any).code, "table " .. e.tag .. ": " .. (err :: any).message, base + e.offset) + return nil, Err.new((err :: any).code, "table " .. e.tag .. ": " .. (err :: any).message, base + e.offset), nil end buffer.copy(out, p, t, 0, e.orig) else diff --git a/src/Formats/host/Love.luau b/src/Formats/host/Love.luau index 0ae01dc..7ee8bc0 100644 --- a/src/Formats/host/Love.luau +++ b/src/Formats/host/Love.luau @@ -31,7 +31,7 @@ function Host.readFile(path: string): (buffer?, Err.Err?) if type(s) ~= "string" then return nil, Err.new(Err.IO, "cannot read " .. path .. ": " .. tostring(msg)) end - return buffer.fromstring(s) + return buffer.fromstring(s), nil end local f, msg = io().open(path, "rb") if not f then @@ -39,7 +39,7 @@ function Host.readFile(path: string): (buffer?, Err.Err?) end local s = f:read("*a") f:close() - return buffer.fromstring(s) + return buffer.fromstring(s), nil end -- writeFile: relative paths go to the save directory (love.filesystem.write), absolute ones through io @@ -50,7 +50,7 @@ function Host.writeFile(path: string, data: buffer): (boolean, Err.Err?) if not ok then return false, Err.new(Err.IO, "cannot write " .. path .. ": " .. tostring(msg)) end - return true + return true, nil end local f, msg = io().open(path, "wb") if not f then @@ -58,7 +58,7 @@ function Host.writeFile(path: string, data: buffer): (boolean, Err.Err?) end f:write(s) f:close() - return true + return true, nil end function Host.exists(path: string): boolean @@ -79,8 +79,8 @@ function Host.toImageData(img: any): (any, Err.Err?) return nil, Err.new(Err.ARG, "toImageData: needs rgba8 pixels, got " .. tostring(img.format)) end local n = img.width * img.height * 4 - local F = ffi() - local B = buffer :: any + local F: any = ffi() + local B: { toffi: ((buffer) -> any)? } = buffer :: any if F and B.toffi then local id = love().image.newImageData(img.width, img.height, "rgba8") F.copy(id:getFFIPointer(), B.toffi(img.pixels), n) @@ -94,8 +94,8 @@ end function Host.fromImageData(id: any): Types.Image local w, h = id:getDimensions() local img = Types.Image.new(w, h, "rgba8") - local F = ffi() - local B = buffer :: any + local F: any = ffi() + local B: { toffi: ((buffer) -> any)? } = buffer :: any if F and B.toffi and id:getFormat() == "rgba8" then F.copy(B.toffi(img.pixels), id:getFFIPointer(), w * h * 4) return img @@ -131,7 +131,7 @@ function Host.toSoundData(a: any): (any, Err.Err?) end local sd = love().sound.newSoundData(math.max(frames, 1), rate, 16, channels) local count = frames * channels - local F = ffi() + local F: any = ffi() if F then local p = F.cast("int16_t*", sd:getFFIPointer()) for i = 0, count - 1 do diff --git a/src/Formats/host/init.luau b/src/Formats/host/init.luau index 3852922..bbd09f3 100644 --- a/src/Formats/host/init.luau +++ b/src/Formats/host/init.luau @@ -31,13 +31,13 @@ end local host: Host if name == "roblox" then - host = require("@formats/host/Roblox") + host = require("@formats/host/Roblox") :: any elseif name == "love" then - host = require("@formats/host/Love") + host = require("@formats/host/Love") :: any elseif name == "luajit" then - host = require("@formats/host/LuaJIT") + host = require("@formats/host/LuaJIT") :: any else - host = require("@formats/host/Luau") + host = require("@formats/host/Luau") :: any end -- LuaJIT (plain or LÖVE): the big decoders (Opus CELT, H.264, ...) outgrow the default 1000 traces / 8 MB of machine -- code and fall back to the interpreter (CELT runs about 2.5x faster with these limits). Raising the limits only diff --git a/src/Formats/image/tiff/init.luau b/src/Formats/image/tiff/init.luau index 81dca4b..008fcff 100644 --- a/src/Formats/image/tiff/init.luau +++ b/src/Formats/image/tiff/init.luau @@ -208,7 +208,7 @@ local function inflateChunk(c: Ctx, comp: number, p: number, len: number, out: b -- a chunk past the end: keep what exists (truncated files) len = math.max(0, math.min(len, c.limit - p)) if p < c.base or p >= c.limit then - return 0 + return 0, nil end end local src, sp = c.b, p @@ -221,10 +221,10 @@ local function inflateChunk(c: Ctx, comp: number, p: number, len: number, out: b if comp == 1 then local n = math.min(len, size) buffer.copy(out, o, src, sp, n) - return n + return n, nil elseif comp == 5 then local n = Lzw.decode(src, sp, len, out, o, size, "tiff") - return n + return n, nil elseif comp == 8 or comp == 32946 then local raw = Deflate.zlib(src, sp, len, size) if not raw then @@ -235,9 +235,9 @@ local function inflateChunk(c: Ctx, comp: number, p: number, len: number, out: b end local n = math.min(buffer.len(raw :: buffer), size) buffer.copy(out, o, raw :: buffer, 0, n) - return n + return n, nil elseif comp == 32773 then - return Pixels.packbits(src, sp, len, out, o, size) + return Pixels.packbits(src, sp, len, out, o, size), nil end return nil, Err.new(Err.UNSUPPORTED, "compression " .. comp) end diff --git a/src/Formats/init.luau b/src/Formats/init.luau index 57d5dcc..d28ed76 100644 --- a/src/Formats/init.luau +++ b/src/Formats/init.luau @@ -95,7 +95,7 @@ local function detect(buf: buffer, name: string?, category: string?, format: str if not e then return nil, Err.new(Err.UNKNOWN_FORMAT, "no format named " .. format .. (if category then " in " .. category else "")) end - return e + return e, nil end local ext = Input.extension(name) local best: Registry.Entry? = nil @@ -117,12 +117,12 @@ local function detect(buf: buffer, name: string?, category: string?, format: str end end if best then - return best + return best, nil end if ext then local e = find(ext, category) if e then - return e + return e, nil end end return nil, Err.new(Err.UNKNOWN_FORMAT, "unrecognised data" .. (if name then " (" .. name .. ")" else "") .. (if category then " for " .. category else "")) @@ -196,7 +196,7 @@ local function pageLoader(value: any, name: string?, o: Options) if type(value) ~= "table" or value.kind ~= "font" or type(value.meta) ~= "table" or type(value.meta.pageFiles) ~= "table" then return end - local user = o.loadPage + local user: any = o.loadPage if value.pages or (value.meta.pageLoader and type(user) ~= "function") then return end @@ -207,7 +207,7 @@ local function pageLoader(value: any, name: string?, o: Options) value.meta.pageLoader = function(file: string, page: number): (any, Err.Err?) local src: any if type(user) == "function" then - src = user(file, page) + src = (user :: any)(file, page) else src = (dir :: string) .. file end @@ -304,7 +304,7 @@ end -- load(src, opts?) -> value | nil, Err function F.load(src: any, opts: Options?): (any, Err.Err?) - local o = opts or {} + local o: Options = opts or {} local buf, ierr, name = Input.resolve(src, o, host) if not buf then return nil, ierr @@ -356,7 +356,7 @@ load = F.load -- open(src, opts?) -> a streaming decoder (audio Decoder / VideoDecoder / Demuxer) | nil, Err function F.open(src: any, opts: Options?): (any, Err.Err?) - local o = opts or {} + local o: Options = opts or {} local buf, ierr, name = Input.resolve(src, o, host) if not buf then return nil, ierr @@ -453,7 +453,7 @@ end -- save(value, dest?, opts?) -> buffer (no dest) | true (written to dest) | nil, Err function F.save(value: any, dest: string?, opts: Options?): (any, Err.Err?) - local o = opts or {} + local o: Options = opts or {} local entry, m, err, key = encoderFor(value, dest, o) if not entry then return nil, err @@ -513,12 +513,12 @@ function F.saveString(value: any, opts: Options?): (string?, Err.Err?) if not buf then return nil, err end - return buffer.tostring(buf) + return buffer.tostring(buf), nil end -- convert(src, format, opts?) -> buffer (or true with opts.out = a path) | nil, Err. opts go to both load and save. function F.convert(src: any, format: string, opts: Options?): (any, Err.Err?) - local o = opts or {} + local o: Options = opts or {} local value, err = F.load(src, o) if value == nil then return nil, err @@ -531,7 +531,7 @@ end -- detect(src, opts?) -> format name | nil, Err function F.detect(src: any, opts: Options?): (string?, Err.Err?) - local o = opts or {} + local o: Options = opts or {} local buf, ierr, name = Input.resolve(src, o, host) if not buf then return nil, ierr @@ -540,7 +540,7 @@ function F.detect(src: any, opts: Options?): (string?, Err.Err?) if not entry then return nil, err end - return entry.name + return entry.name, nil end export type FormatInfo = { name: string, category: string, extensions: { string }, mime: { string }, caps: { [string]: any } } @@ -568,7 +568,7 @@ end -- ------------------------------------------------------------------------------------------------ category facades -- F.image.load / save / open / formats, F.audio..., F.model... : the same calls restricted to one category local function with(opts: Options?, category: string): Options - local o = if opts then table.clone(opts) else {} + local o: Options = if opts then table.clone(opts) else {} o.category = category return o end @@ -597,7 +597,7 @@ F.data.null = Types.null for _, fn in { "toBodies", "fromBodies", "tessellate" } do local name: string = fn F.cad[name] = function(value: any, opts: Options?): (any, any) - local o = if opts then table.clone(opts) else {} + local o: Options = if opts then table.clone(opts) else {} if o.plugins == nil then o.plugins = F.plugins end @@ -659,7 +659,7 @@ F.model.loadTextures = function(scene: any, opts: Options?): (any, { [number]: E if type(scene) ~= "table" or type(scene.textures) ~= "table" then return scene, errs end - local resolve = opts and opts.resolve + local resolve: ((any) -> any)? = opts and opts.resolve for i, tex in scene.textures do if type(tex) == "table" and tex.image == nil then local data = tex.data diff --git a/src/Formats/ops/ImageOps/init.luau b/src/Formats/ops/ImageOps/init.luau index 6a5e976..5c6abde 100644 --- a/src/Formats/ops/ImageOps/init.luau +++ b/src/Formats/ops/ImageOps/init.luau @@ -57,7 +57,7 @@ local function check(img: any): (boolean?, Err.Err?) if buffer.len(img.pixels) < need then return arg("pixel buffer too small for " .. img.width .. " x " .. img.height .. " " .. img.format) end - return true + return true, nil end ImageOps.check = check @@ -66,7 +66,7 @@ local function limit(w: number, h: number, opts: any): (boolean?, Err.Err?) if w * h > max then return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, max)) end - return true + return true, nil end -- a new Image of the same kind with a copy of meta's plain fields (source, palette...) but no frames @@ -93,7 +93,7 @@ function ImageOps.new(w: number, h: number, format: string?): (Image?, Err.Err?) if not ok then return nil, e end - return Types.Image.new(w, h, fmt :: any) + return Types.Image.new(w, h, fmt :: any), nil end -- copy(img) -> a deep copy of the pixels (frames are shared) @@ -105,7 +105,7 @@ function ImageOps.copy(img: Image): (Image?, Err.Err?) local out = like(img, img.width, img.height) buffer.copy(out.pixels, 0, img.pixels, 0, buffer.len(out.pixels)) out.frames = img.frames - return out + return out, nil end -- ------------------------------------------------------------------------------------------------ convert @@ -127,7 +127,7 @@ function ImageOps.convert(img: Image, format: string): (Image?, Err.Err?) local rgba = like(img, w, h, "rgba8") K.yuvToRgba(img.pixels, w, h, rgba.pixels) if format == "rgba8" then - return rgba + return rgba, nil end src = rgba end @@ -139,10 +139,10 @@ function ImageOps.convert(img: Image, format: string): (Image?, Err.Err?) K.convert(src.pixels, K.ID[src.format], rgba.pixels, K.ID.rgba8, w * h) end K.rgbaToYuv(rgba.pixels, w, h, out.pixels) - return out + return out, nil end K.convert(src.pixels, K.ID[src.format], out.pixels, K.ID[format], w * h) - return out + return out, nil end -- ops on yuv420p run on rgba8 and convert back @@ -179,7 +179,7 @@ function ImageOps.crop(img: Image, x: number, y: number, w: number, h: number): local bpp = Types.BPP[im.format] :: number local out = like(im, x1 - x0, y1 - y0) K.copyRect(out.pixels, out.width, im.pixels, im.width, x0, y0, 0, 0, out.width, out.height, bpp) - return out + return out, nil end) end @@ -195,7 +195,7 @@ function ImageOps.flip(img: Image, axis: string): (Image?, Err.Err?) return viaRgba(img, function(im: Image): (Image?, Err.Err?) local out = like(im, im.width, im.height) K.flip(im.pixels, out.pixels, im.width, im.height, Types.BPP[im.format] :: number, axis == "h") - return out + return out, nil end) end @@ -216,7 +216,7 @@ function ImageOps.rotate90(img: Image, turns: number): (Image?, Err.Err?) local swap = t ~= 2 local out = like(im, if swap then im.height else im.width, if swap then im.width else im.height) K.rotate90(im.pixels, out.pixels, im.width, im.height, Types.BPP[im.format] :: number, t) - return out + return out, nil end) end @@ -245,7 +245,7 @@ function ImageOps.resize(img: Image, w: number, h: number, filter: string?, opts local out = like(im, w, h) if f == "nearest" then K.nearest(im.pixels, im.width, im.height, bpp, out.pixels, w, h) - return out + return out, nil end local kind, ch = K.KIND[fmt], K.CHANNELS[fmt] local src, sw, sh = im.pixels, im.width, im.height @@ -264,14 +264,14 @@ function ImageOps.resize(img: Image, w: number, h: number, filter: string?, opts K.resamplePass(src, sw, sh, ch, kind, out.pixels, h, K.coeffs(sh, h, f), false) elseif src == im.pixels or (w == im.width and alpha) then buffer.copy(out.pixels, 0, im.pixels, 0, w * h * bpp) - return out + return out, nil else out.pixels = src end if alpha then K.premultiply(out.pixels, w * h, alpha, kind, true) end - return out + return out, nil end) end @@ -333,7 +333,7 @@ function ImageOps.rotate(img: Image, degrees: number, opts: { expand: boolean?, if alpha then K.premultiply(out.pixels, nw * nh, alpha, kind, true) end - return out + return out, nil end) end @@ -371,7 +371,7 @@ function ImageOps.blit(dst: Image, src: Image, x: number, y: number, opts: BlitO local w = math.min(src.width - sx, dst.width - dx) local h = math.min(src.height - sy, dst.height - dy) if w <= 0 or h <= 0 then - return dst + return dst, nil end if dst.format == "yuv420p" or (blend == "over" and not RGBA[dst.format]) then -- work on an rgba copy of the region, then write it back in dst's format @@ -387,7 +387,7 @@ function ImageOps.blit(dst: Image, src: Image, x: number, y: number, opts: BlitO local back = ImageOps.convert(work, dst.format) :: Image K.copyRect(dst.pixels, dst.width, back.pixels, back.width, 0, 0, dx, dy, w, h, Types.BPP[dst.format] :: number) end - return dst + return dst, nil end local s = src if src.format ~= dst.format then @@ -400,7 +400,7 @@ function ImageOps.blit(dst: Image, src: Image, x: number, y: number, opts: BlitO else K.overFloat(dst.pixels, dst.width, s.pixels, s.width, sx, sy, dx, dy, w, h, opacity, K.KIND[dst.format]) end - return dst + return dst, nil end -- composite(dst, src, x?, y?, opts?) -> a new Image: a copy of dst with src blitted onto it @@ -423,7 +423,7 @@ local function premul(img: Image, un: boolean): (Image?, Err.Err?) if ch then K.premultiply(out.pixels, img.width * img.height, ch, K.KIND[img.format], un) end - return out + return out, nil end -- premultiply(img) / unpremultiply(img) -> a new Image (formats without alpha are copied unchanged) @@ -543,7 +543,7 @@ function ImageOps.setPixel(img: Image, x: number, y: number, r: number, g: numbe else wu8(px, i, q(al)) end - return true + return true, nil end -- fill(img, r, g, b, a?) -> img (in place) with every pixel set (values as setPixel) @@ -567,7 +567,7 @@ function ImageOps.fill(img: Image, r: number, g: number, b: number, a: number?): buffer.copy(img.pixels, filled, img.pixels, 0, c) filled += c end - return img + return img, nil end -- ------------------------------------------------------------------------------------------------ animation @@ -602,7 +602,7 @@ function ImageOps.coalesce(img: Image): ({ Image }?, Err.Err?) end local frames = img.frames if type(frames) ~= "table" or #frames == 0 then - return { img } + return { img }, nil end local fmt = if RGBA[img.format] then img.format else "rgba8" local canvas = Types.Image.new(img.width, img.height, fmt :: any) @@ -647,7 +647,7 @@ function ImageOps.coalesce(img: Image): ({ Image }?, Err.Err?) canvas.pixels = saved end end - return out + return out, nil end -- fromFrames(images, delays?) -> an animated Image: img.frames = the images as full-canvas frames (x = y = 0, @@ -683,7 +683,7 @@ function ImageOps.fromFrames(images: { Image }, delays: (number | { number })?): buffer.copy(out.pixels, 0, first.pixels, 0, buffer.len(out.pixels)) out.frames = frames :: any out.loops = 0 - return out + return out, nil end return ImageOps diff --git a/src/Formats/vector/tiled/Data.luau b/src/Formats/vector/tiled/Data.luau index 7338b74..927e7ea 100644 --- a/src/Formats/vector/tiled/Data.luau +++ b/src/Formats/vector/tiled/Data.luau @@ -23,19 +23,19 @@ end function Data.base64(text: string, compression: string?): ({ number }?, string?, boolean?) local raw, err = Base64.decode(text) if not raw then - return nil, err + return nil, err, nil end local bytes: buffer = raw if compression == "zlib" then local z, zerr = Deflate.zlib(bytes) if not z then - return nil, "zlib: " .. tostring(zerr) + return nil, "zlib: " .. tostring(zerr), nil end bytes = z elseif compression == "gzip" then local z, zerr = Deflate.gunzip(bytes) if not z then - return nil, "gzip: " .. tostring(zerr) + return nil, "gzip: " .. tostring(zerr), nil end bytes = z elseif compression ~= nil and compression ~= "" then diff --git a/src/Formats/vector/tiled/Tmj.luau b/src/Formats/vector/tiled/Tmj.luau index ce23c8a..db8eab7 100644 --- a/src/Formats/vector/tiled/Tmj.luau +++ b/src/Formats/vector/tiled/Tmj.luau @@ -87,11 +87,11 @@ local function gids(v: any, encoding: string?, compression: string?): ({ number local out = {} for _, g in list(v) do if type(g) ~= "number" or g < 0 or g >= 4294967296 then - return nil, "bad gid" + return nil, "bad gid", nil end table.insert(out, g) end - return out, nil + return out, nil, nil end local function object(o: any): any diff --git a/src/Formats/vector/tiled/Tmx.luau b/src/Formats/vector/tiled/Tmx.luau index b415329..8d9dd72 100644 --- a/src/Formats/vector/tiled/Tmx.luau +++ b/src/Formats/vector/tiled/Tmx.luau @@ -79,7 +79,7 @@ local function gids(d: Node, encoding: string?, compression: string?): ({ number for _, t in Xml.children(d, "tile") do table.insert(out, num(t, "gid", 0) :: number) end - return out, nil + return out, nil, nil end return nil, "unknown encoding " .. encoding, true end From cfe325dcf87c0b4cfa47fb38a3d5d98b0b465de9 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 10:46:15 -0500 Subject: [PATCH 02/22] ws-cleanup-types: containers, ops: type the tables and locals the solver cannot infer --- src/Formats/Types.luau | 4 ++-- src/Formats/containers/Archive.luau | 4 ++-- src/Formats/containers/AudioWrap.luau | 13 +++++++++---- src/Formats/containers/Avi/init.luau | 2 +- src/Formats/containers/IsoBmff/Demux.luau | 8 ++++---- src/Formats/containers/IsoBmff/Meta.luau | 4 ++-- src/Formats/containers/MpegPs/init.luau | 2 +- src/Formats/containers/Tar.luau | 2 +- src/Formats/ops/ImageOps/Kernels.luau | 14 +++++++------- src/Formats/ops/ImageOps/init.luau | 8 ++++---- src/Formats/ops/MeshOps/Greedy.luau | 2 +- src/Formats/ops/MeshOps/init.luau | 6 +++--- 12 files changed, 37 insertions(+), 32 deletions(-) diff --git a/src/Formats/Types.luau b/src/Formats/Types.luau index effef54..f0e3a6b 100644 --- a/src/Formats/Types.luau +++ b/src/Formats/Types.luau @@ -28,7 +28,7 @@ local BPP: { [string]: number } = { graya8 = 2, alpha8 = 1, } -Types.BPP = table.freeze(BPP) +Types.BPP = table.freeze(BPP) :: { [string]: number } export type ImageMeta = { colorSpace: string?, -- "srgb" (default), "linear", "display-p3", ... @@ -429,7 +429,7 @@ local COMPONENT_SIZE: { [string]: number } = { snorm8 = 1, snorm16 = 2, } -Types.COMPONENT_SIZE = table.freeze(COMPONENT_SIZE) +Types.COMPONENT_SIZE = table.freeze(COMPONENT_SIZE) :: { [string]: number } -- accessor(data, type, components, count) -> Accessor (data = nil allocates a zero-filled buffer) function Scene.accessor(data: buffer?, type: any, components: number, count: number): Accessor local d = data or buffer.create(count * components * (COMPONENT_SIZE[type] or 4)) diff --git a/src/Formats/containers/Archive.luau b/src/Formats/containers/Archive.luau index ead480e..ef9a63d 100644 --- a/src/Formats/containers/Archive.luau +++ b/src/Formats/containers/Archive.luau @@ -45,7 +45,7 @@ local function public(e: Entry): Types.ArchiveEntry end function Methods.list(self: any): { Types.ArchiveEntry } - local out = table.create(#self._entries) + local out = table.create(#self._entries) :: { Types.ArchiveEntry } for i, e in self._entries do out[i] = public(e) end @@ -91,7 +91,7 @@ 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 = self._encode + local enc: Encoder? = self._encode if not enc then return nil, Err.new(Err.UNSUPPORTED, self.format .. " archives are read-only") end diff --git a/src/Formats/containers/AudioWrap.luau b/src/Formats/containers/AudioWrap.luau index fa82ebe..0646754 100644 --- a/src/Formats/containers/AudioWrap.luau +++ b/src/Formats/containers/AudioWrap.luau @@ -18,8 +18,13 @@ local Mux = require("@formats/containers/Ogg/Mux") local AudioWrap = {} -local function allPackets(dmx: any, track: Types.Track): { Types.Packet } - local out = {} +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 @@ -437,11 +442,11 @@ function AudioWrap.wrap(dmx: any, track: Types.Track): (buffer?, string?, Err.Er return granule end local mb = 0 - while 2 ^ mb < #modes do + 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[m + 1] then 2 else 1] + local cur = sizes[if (modes :: { boolean })[m + 1] then 2 else 1] if prev then granule += (prev + cur) // 4 end diff --git a/src/Formats/containers/Avi/init.luau b/src/Formats/containers/Avi/init.luau index 521dbe9..081e9b9 100644 --- a/src/Formats/containers/Avi/init.luau +++ b/src/Formats/containers/Avi/init.luau @@ -491,7 +491,7 @@ function Avi.write(opts: WOptions, chunks: { { any } }): buffer w:u32le(0) local moviBase = w:tell() w:string("movi") - local index = table.create(#chunks) + 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] diff --git a/src/Formats/containers/IsoBmff/Demux.luau b/src/Formats/containers/IsoBmff/Demux.luau index 6a5a4cb..0160249 100644 --- a/src/Formats/containers/IsoBmff/Demux.luau +++ b/src/Formats/containers/IsoBmff/Demux.luau @@ -324,9 +324,9 @@ local function track(b: buffer, trak: Box.Box, movieTimescale: number, trex: { [ r:skip(3) local n = r:u32be() if n <= (elst.stop - elst.data) // 12 then - local edits = {} + local edits: { Edit } = {} for _ = 1, n do - local dur, mt + local dur: number, mt: number if v == 1 then dur, mt = r:u64be(), r:i64be() else @@ -522,7 +522,7 @@ local function track(b: buffer, trak: Box.Box, movieTimescale: number, trex: { [ if n * 12 > r:remaining() then return nil, Err.new(Err.TRUNCATED, "stsc table runs past its box", stsc.start) end - local first, per, desc = {}, {}, {} + 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 @@ -739,7 +739,7 @@ export type Movie = { -- 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 = opts or {} + local o: Options = opts or {} local b = r.buf local top, terr = Box.list(b, r.base, r.limit) if #top == 0 then diff --git a/src/Formats/containers/IsoBmff/Meta.luau b/src/Formats/containers/IsoBmff/Meta.luau index a7c44ca..7792142 100644 --- a/src/Formats/containers/IsoBmff/Meta.luau +++ b/src/Formats/containers/IsoBmff/Meta.luau @@ -187,7 +187,7 @@ function Meta.items(b: buffer, meta: Box.Box): (Items?, Err.Err?) 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 @@ -496,7 +496,7 @@ function Meta.writeIlst(w: Bytes.Writer, tags: { [string]: string }, pictures: { end if pictures and #pictures > 0 then box(w, "covr", function() - for _, p in pictures do + 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) diff --git a/src/Formats/containers/MpegPs/init.luau b/src/Formats/containers/MpegPs/init.luau index 53f75be..5229571 100644 --- a/src/Formats/containers/MpegPs/init.luau +++ b/src/Formats/containers/MpegPs/init.luau @@ -193,7 +193,7 @@ function MpegPs.read(b: buffer, base: number, limit: number): (File?, Err.Err?) 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 = {} } + s = { id = id, kind = kind, codec = codec, streamType = st, pes = {} } :: Stream file.streams[id] = s table.insert(file.order, id) end diff --git a/src/Formats/containers/Tar.luau b/src/Formats/containers/Tar.luau index 5627311..d98afda 100644 --- a/src/Formats/containers/Tar.luau +++ b/src/Formats/containers/Tar.luau @@ -350,7 +350,7 @@ function Tar.write(entries: { WriteEntry }, opts: WriteOptions?): (buffer?, Err. end local data = e.data or buffer.create(0) local typ = e.type or (if e.dir then "5" else "0") - local name = e.name + local name: string = e.name if typ == "5" and string.sub(name, -1) ~= "/" then name ..= "/" end diff --git a/src/Formats/ops/ImageOps/Kernels.luau b/src/Formats/ops/ImageOps/Kernels.luau index 68d0d58..cf14954 100644 --- a/src/Formats/ops/ImageOps/Kernels.luau +++ b/src/Formats/ops/ImageOps/Kernels.luau @@ -13,9 +13,9 @@ local floor, clamp = math.floor, math.clamp local K = {} -- format ids: rgba8 1, rgba16 2, rgbaf32 3, rgb8 4, gray8 5, gray16 6, graya8 7, alpha8 8 -K.ID = { rgba8 = 1, rgba16 = 2, rgbaf32 = 3, rgb8 = 4, gray8 = 5, gray16 = 6, graya8 = 7, alpha8 = 8 } -K.KIND = { rgba8 = 1, rgba16 = 2, rgbaf32 = 4, rgb8 = 1, gray8 = 1, gray16 = 2, graya8 = 1, alpha8 = 1 } -K.CHANNELS = { rgba8 = 4, rgba16 = 4, rgbaf32 = 4, rgb8 = 3, gray8 = 1, gray16 = 1, graya8 = 2, alpha8 = 1 } +K.ID = { rgba8 = 1, rgba16 = 2, rgbaf32 = 3, rgb8 = 4, gray8 = 5, gray16 = 6, graya8 = 7, alpha8 = 8 } :: { [string]: number } +K.KIND = { rgba8 = 1, rgba16 = 2, rgbaf32 = 4, rgb8 = 1, gray8 = 1, gray16 = 2, graya8 = 1, alpha8 = 1 } :: { [string]: number } +K.CHANNELS = { rgba8 = 4, rgba16 = 4, rgbaf32 = 4, rgb8 = 3, gray8 = 1, gray16 = 1, graya8 = 2, alpha8 = 1 } :: { [string]: number } local function rd(b: buffer, o: number, kind: number): number if kind == 1 then @@ -74,11 +74,11 @@ local function luma(r: number, g: number, b: number, depth: number): number end function K.convert(src: buffer, sf: number, dst: buffer, df: number, n: number) - local sd, dd = DEPTH[sf], DEPTH[df] + local sd, dd = DEPTH[sf] :: number, DEPTH[df] :: number local smax = if sd == 8 then 255 elseif sd == 16 then 65535 else 1 local toGray = df == 5 or df == 6 or df == 7 for i = 0, n - 1 do - local r, g, b, a + local r: number, g: number, b: number, a: number if sf == 1 then local o = i * 4 r, g, b, a = readu8(src, o), readu8(src, o + 1), readu8(src, o + 2), readu8(src, o + 3) @@ -281,7 +281,7 @@ function K.coeffs(inSize: number, outSize: number, filter: string): Coeffs local filterscale = math.max(scale, 1) local support = support0 * filterscale local ss = 1 / filterscale - local start, count, weights = table.create(outSize, 0), table.create(outSize, 0), table.create(outSize) + local start, count, weights = table.create(outSize, 0), table.create(outSize, 0), table.create(outSize) :: { { number } } for xx = 0, outSize - 1 do local center = (xx + 0.5) * scale local xmin = math.max(0, trunc(center - support + 0.5)) @@ -311,7 +311,7 @@ function K.resamplePass(src: buffer, w: number, h: number, ch: number, kind: num -- 8-bit: Pillow's 22-bit fixed-point coefficients local iw: { { number } } = weights if fixed then - iw = table.create(outN) + iw = table.create(outN) :: { { number } } for i = 1, outN do local src0 = weights[i] local t = table.create(#src0, 0) diff --git a/src/Formats/ops/ImageOps/init.luau b/src/Formats/ops/ImageOps/init.luau index 5c6abde..6ddc177 100644 --- a/src/Formats/ops/ImageOps/init.luau +++ b/src/Formats/ops/ImageOps/init.luau @@ -62,7 +62,7 @@ end ImageOps.check = check local function limit(w: number, h: number, opts: any): (boolean?, Err.Err?) - local max = (type(opts) == "table" and opts.maxPixels) or MAX_PIXELS + local max: number = (type(opts) == "table" and opts.maxPixels) or MAX_PIXELS if w * h > max then return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, max)) end @@ -159,7 +159,7 @@ local function viaRgba(img: Image, f: (Image) -> (Image?, Err.Err?)): (Image?, E end -- ------------------------------------------------------------------------------------------------ geometry -local ALPHA_CH = { rgba8 = 4, rgba16 = 4, rgbaf32 = 4, graya8 = 2 } +local ALPHA_CH: { [string]: number } = { rgba8 = 4, rgba16 = 4, rgbaf32 = 4, graya8 = 2 } -- crop(img, x, y, w, h) -> the rectangle clipped to the image | nil, Err (empty) function ImageOps.crop(img: Image, x: number, y: number, w: number, h: number): (Image?, Err.Err?) @@ -338,7 +338,7 @@ function ImageOps.rotate(img: Image, degrees: number, opts: { expand: boolean?, end -- ------------------------------------------------------------------------------------------------ compositing -local RGBA = { rgba8 = true, rgba16 = true, rgbaf32 = true } +local RGBA: { [string]: boolean } = { rgba8 = true, rgba16 = true, rgbaf32 = true } export type BlitOptions = { blend: ("over" | "source")?, opacity: number? } @@ -435,7 +435,7 @@ function ImageOps.unpremultiply(img: Image): (Image?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ pixels -local MAXV = { rgba8 = 255, rgba16 = 65535, rgbaf32 = 1, rgb8 = 255, gray8 = 255, gray16 = 65535, graya8 = 255, alpha8 = 255, yuv420p = 255 } +local MAXV: { [string]: number } = { rgba8 = 255, rgba16 = 65535, rgbaf32 = 1, rgb8 = 255, gray8 = 255, gray16 = 65535, graya8 = 255, alpha8 = 255, yuv420p = 255 } -- getPixel(img, x, y) -> r, g, b, a in the format's scale (0..255, 0..65535 or float); grey gives r = g = b; -- alpha8 gives white; yuv420p converts to RGB. nil, Err out of range. diff --git a/src/Formats/ops/MeshOps/Greedy.luau b/src/Formats/ops/MeshOps/Greedy.luau index 26ddb50..b65c507 100644 --- a/src/Formats/ops/MeshOps/Greedy.luau +++ b/src/Formats/ops/MeshOps/Greedy.luau @@ -97,7 +97,7 @@ function Greedy.run(data: buffer, sx: number, sy: number, sz: number, ox: number buffer.copy(nb, 0, b, 0, cap * per) return nb end - pos, nrm, idx, tri = grow2(pos, 48), grow2(nrm, 48), grow2(idx, 4), grow2(tri, 24) + pos, nrm, idx, tri = grow2(pos, 48), grow2(nrm, 48), grow2(idx, 4), grow2(tri, 24) :: buffer cap = ncap end corner[d + 1] = slice + 1 diff --git a/src/Formats/ops/MeshOps/init.luau b/src/Formats/ops/MeshOps/init.luau index 4bcfacd..d3763d2 100644 --- a/src/Formats/ops/MeshOps/init.luau +++ b/src/Formats/ops/MeshOps/init.luau @@ -272,7 +272,7 @@ function MeshOps.triangulate(prim: Primitive, opts: { method: string? }?): (Prim table.insert(out, readu32(ib, (at + a + 1) * 4)) end else - local poly = table.create(k) + local poly = table.create(k) :: { number } for a = 0, k - 1 do poly[a + 1] = readu32(ib, (at + a) * 4) end @@ -856,7 +856,7 @@ function MeshOps.merge(input: any, opts: { byMaterial: boolean?, method: string? end return out, nil end - local all = groups[0] or {} + local all: { Primitive } = groups[0] or {} local first = all[1] return concat(all, first and first.material), nil end @@ -1025,7 +1025,7 @@ function MeshOps.voxelsToPrimitive(v: Types.Voxels, opts: { pivot: string?, scal local col = buffer.create(nv * (if srgb then 4 else 16)) local lut: { { number } } = {} for i = 1, 255 do - local c = pal[i] or { 255, 255, 255, 255 } + local c: { number } = pal[i] or { 255, 255, 255, 255 } if srgb then lut[i] = { c[1] or 0, c[2] or 0, c[3] or 0, c[4] or 255 } else From 4f2ceec7352a17db02303b8afb5ff09aca9e7337 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 10:50:40 -0500 Subject: [PATCH 03/22] ws-cleanup: one base64 (core/Base64) core/Base64 takes over codecs/Base64's API (encode(buf | string, { url, pad, wrap }, offset, length), decode of both alphabets, decodeDataUri, dataUri) plus line wrapping (opts.wrap) for plist; codecs/Base64 is removed and glTF / DAE require core/Base64. The private copies in data/plist (Base64.luau), data/yaml (Parse / Emit) and codecs/Brotli (the static tables) are gone. tests/codecs/base64 merged into tests/core/base64. --- src/Formats/codecs/Base64/init.luau | 140 ------------ src/Formats/codecs/Brotli/init.luau | 33 +-- .../RangeCoder/Decoder.luau} | 0 .../RangeCoder/Encoder.luau} | 0 src/Formats/core/Base64.luau | 200 ++++++++++++------ src/Formats/data/plist/Base64.luau | 71 ------- src/Formats/data/plist/init.luau | 6 +- src/Formats/data/yaml/Emit.luau | 19 +- src/Formats/data/yaml/Parse.luau | 34 +-- src/Formats/data/yaml/init.luau | 2 +- src/Formats/model/dae/Read.luau | 2 +- src/Formats/model/dae/Write.luau | 2 +- src/Formats/model/dae/init.luau | 2 +- src/Formats/model/gltf/Read.luau | 2 +- src/Formats/model/gltf/init.luau | 4 +- tests/codecs/base64.luau | 46 ---- tests/core/base64.luau | 47 +++- tools/fixtures/gltf.py | 2 +- 18 files changed, 202 insertions(+), 410 deletions(-) delete mode 100644 src/Formats/codecs/Base64/init.luau rename src/Formats/{audio/opus/RangeDecoder.luau => codecs/RangeCoder/Decoder.luau} (100%) rename src/Formats/{audio/opus/RangeEncoder.luau => codecs/RangeCoder/Encoder.luau} (100%) delete mode 100644 src/Formats/data/plist/Base64.luau delete mode 100644 tests/codecs/base64.luau diff --git a/src/Formats/codecs/Base64/init.luau b/src/Formats/codecs/Base64/init.luau deleted file mode 100644 index 3d3030f..0000000 --- a/src/Formats/codecs/Base64/init.luau +++ /dev/null @@ -1,140 +0,0 @@ ---!strict ---!native --- codecs/Base64: RFC 4648 base64 (standard alphabet, and base64url with opts.url) encode / decode, for data: URIs --- (glTF, SVG, CSS), PEM-like text, YAML !!binary, ... New code. decode skips whitespace, accepts missing padding and --- both alphabets; any other character is an error. Never throws. --- --- local Base64 = require("@formats/codecs/Base64") --- local s = Base64.encode(buf) -- string ("" for an empty buffer) --- local b, err = Base64.decode(s) -- buffer | nil, "message" --- local b2 = Base64.decodeDataUri("data:application/octet-stream;base64,AAEC") -- buffer, mime | nil, message -local Base64 = {} - -local ALPHA = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" -local ALPHA_URL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_" -local ENC = buffer.fromstring(ALPHA) -local ENC_URL = buffer.fromstring(ALPHA_URL) --- the decode table: 0..63, 64 = skip (whitespace), 65 = padding, 255 = bad -local DEC = buffer.create(256) -buffer.fill(DEC, 0, 255) -for i = 1, 64 do - buffer.writeu8(DEC, string.byte(ALPHA, i), i - 1) -end -buffer.writeu8(DEC, string.byte("-"), 62) -buffer.writeu8(DEC, string.byte("_"), 63) -for _, c in { 9, 10, 13, 32 } do - buffer.writeu8(DEC, c, 64) -end -buffer.writeu8(DEC, string.byte("="), 65) - -local readu8, writeu8 = buffer.readu8, buffer.writeu8 - --- encode(buf, opts?, offset?, length?) -> string. opts.url: the URL-safe alphabet; opts.pad = false: no "=" padding. -function Base64.encode(buf: buffer, opts: { url: boolean?, pad: boolean? }?, offset: number?, length: number?): string - local o = math.clamp(offset or 0, 0, buffer.len(buf)) - local n = math.clamp(length or (buffer.len(buf) - o), 0, buffer.len(buf) - o) - local enc = if opts and opts.url then ENC_URL else ENC - local pad = not (opts and opts.pad == false) - local full = n // 3 - local rest = n - full * 3 - local outLen = full * 4 + (if rest == 0 then 0 elseif pad then 4 else rest + 1) - local out = buffer.create(outLen) - local p = 0 - for i = 0, full - 1 do - local q = o + i * 3 - local v = readu8(buf, q) * 65536 + readu8(buf, q + 1) * 256 + readu8(buf, q + 2) - writeu8(out, p, readu8(enc, v // 262144)) - writeu8(out, p + 1, readu8(enc, (v // 4096) % 64)) - writeu8(out, p + 2, readu8(enc, (v // 64) % 64)) - writeu8(out, p + 3, readu8(enc, v % 64)) - p += 4 - end - if rest > 0 then - local q = o + full * 3 - local v = readu8(buf, q) * 65536 + (if rest == 2 then readu8(buf, q + 1) * 256 else 0) - writeu8(out, p, readu8(enc, v // 262144)) - writeu8(out, p + 1, readu8(enc, (v // 4096) % 64)) - if rest == 2 then - writeu8(out, p + 2, readu8(enc, (v // 64) % 64)) - elseif pad then - writeu8(out, p + 2, 61) - end - if pad then - writeu8(out, p + 3, 61) - end - end - return buffer.tostring(out) -end - --- decode(s) -> buffer | nil, message -function Base64.decode(s: string | buffer): (buffer?, string?) - local src = if type(s) == "string" then buffer.fromstring(s) else s - local n = buffer.len(src) - local out = buffer.create((n // 4 + 1) * 3) - local acc, bits, p = 0, 0, 0 - local padded = false - for i = 0, n - 1 do - local d = readu8(DEC, readu8(src, i)) - if d < 64 then - if padded then - return nil, "data after padding" - end - acc = acc * 64 + d - bits += 6 - if bits >= 8 then - bits -= 8 - local byte = acc // (2 ^ bits) - writeu8(out, p, byte % 256) - p += 1 - acc = acc % (2 ^ bits) - end - elseif d == 65 then - padded = true - elseif d ~= 64 then - return nil, string.format("bad base64 character 0x%02x at %d", readu8(src, i), i) - end - end - if bits >= 6 then - return nil, "truncated base64 (a single character in the last group)" - end - local res = buffer.create(p) - buffer.copy(res, 0, out, 0, p) - return res, nil -end - --- decodeDataUri(uri) -> buffer, mime | nil, message: "data:[][;params][;base64]," (percent-encoded data --- when not base64) -function Base64.decodeDataUri(uri: string): (buffer?, string?) - if string.sub(uri, 1, 5) ~= "data:" then - return nil, "not a data: URI" - end - local comma = string.find(uri, ",", 6, true) - if not comma then - return nil, "data: URI without a comma" - end - local head = string.sub(uri, 6, comma - 1) - local isB64 = string.sub(head, -7) == ";base64" - local mime = string.match(head, "^([^;]*)") or "" - if mime == "" then - mime = "text/plain" - end - local body = string.sub(uri, comma + 1) - if isB64 then - local b, err = Base64.decode(body) - if not b then - return nil, err - end - return b, mime - end - local decoded = string.gsub(body, "%%(%x%x)", function(h: string): string - return string.char(tonumber(h, 16) :: number) - end) - return buffer.fromstring(decoded), mime -end - --- dataUri(buf, mime) -> "data:;base64,..." -function Base64.dataUri(buf: buffer, mime: string?): string - return "data:" .. (mime or "application/octet-stream") .. ";base64," .. Base64.encode(buf) -end - -return Base64 diff --git a/src/Formats/codecs/Brotli/init.luau b/src/Formats/codecs/Brotli/init.luau index 391ec29..fb4fb58 100644 --- a/src/Formats/codecs/Brotli/init.luau +++ b/src/Formats/codecs/Brotli/init.luau @@ -13,6 +13,7 @@ -- Never throws: bad data and bad arguments return nil, Err (TRUNCATED / CORRUPT / LIMIT / UNSUPPORTED / ARG). local Err = require("@formats/core/Err") local Crc32 = require("@formats/core/Crc32") +local Base64 = require("@formats/core/Base64") local Deflate = require("@formats/codecs/Deflate") local Decode = require("@formats/codecs/Brotli/Decode") local StaticData = require("@formats/codecs/Brotli/Static") @@ -25,37 +26,9 @@ export type Options = { } -- ------------------------------------------------------------------------------------------------ static data -local B64 = {} -do - local alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" - for i = 1, 64 do - B64[string.byte(alphabet, i)] = i - 1 - end -end - +-- the tables are base64 text (trusted, generated by tools/brotli_static.py) local function unbase64(s: string): buffer - local n = #s - local pad = 0 - if string.sub(s, -2) == "==" then - pad = 2 - elseif string.sub(s, -1) == "=" then - pad = 1 - end - local out = buffer.create(n // 4 * 3 - pad) - local o = 0 - for i = 1, n, 4 do - local a, b, c, d = string.byte(s, i, i + 3) - local v = B64[a] * 262144 + B64[b] * 4096 + (B64[c] or 0) * 64 + (B64[d] or 0) - buffer.writeu8(out, o, v // 65536) - if o + 1 < buffer.len(out) then - buffer.writeu8(out, o + 1, (v // 256) % 256) - end - if o + 2 < buffer.len(out) then - buffer.writeu8(out, o + 2, v % 256) - end - o += 3 - end - return out + return Base64.decode(s) or buffer.create(0) end local static: Decode.Static? = nil diff --git a/src/Formats/audio/opus/RangeDecoder.luau b/src/Formats/codecs/RangeCoder/Decoder.luau similarity index 100% rename from src/Formats/audio/opus/RangeDecoder.luau rename to src/Formats/codecs/RangeCoder/Decoder.luau diff --git a/src/Formats/audio/opus/RangeEncoder.luau b/src/Formats/codecs/RangeCoder/Encoder.luau similarity index 100% rename from src/Formats/audio/opus/RangeEncoder.luau rename to src/Formats/codecs/RangeCoder/Encoder.luau diff --git a/src/Formats/core/Base64.luau b/src/Formats/core/Base64.luau index 7ffbb09..8dfcc41 100644 --- a/src/Formats/core/Base64.luau +++ b/src/Formats/core/Base64.luau @@ -1,89 +1,167 @@ --!strict --!native --- core/Base64: RFC 4648 base64 (standard alphabet, and the URL-safe one on decode). Tiled map data, data: URIs, ... --- decode skips whitespace and accepts missing padding; other bad characters fail. Never throws. +-- core/Base64: RFC 4648 base64 (standard alphabet, and base64url with opts.url) encode / decode, and data: URIs. +-- Used by tiled map data, glTF / SVG / CSS data: URIs, plist , YAML !!binary, FBX, the Brotli static tables. +-- decode skips whitespace, accepts missing padding and both alphabets; any other character, data after padding or a +-- lone last character is an error. Never throws. -- --- local s = Base64.encode(buf) -- buffer | string -> string --- local b, err = Base64.decode(s) -- string -> buffer | nil, "message" +-- local s = Base64.encode(buf) -- buffer | string -> string ("" for empty input) +-- local s2 = Base64.encode(buf, { url = true, pad = false, wrap = 76 }, offset, length) +-- local b, err = Base64.decode(s) -- string | buffer -> buffer | nil, "message" +-- local b2, mime = Base64.decodeDataUri("data:application/octet-stream;base64,AAEC") -- buffer, mime | nil, msg +-- local uri = Base64.dataUri(buf, "image/png") local Base64 = {} -local ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" -local ENC = buffer.create(64) -buffer.writestring(ENC, 0, ALPHABET) +export type EncodeOptions = { + url: boolean?, -- the URL-safe alphabet (- and _); default false + pad: boolean?, -- "=" padding; default true + wrap: number?, -- a "\n" after every `wrap` output characters (rounded down to a multiple of 4); default none +} + +local ALPHA = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" +local ALPHA_URL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_" +local ENC = buffer.fromstring(ALPHA) +local ENC_URL = buffer.fromstring(ALPHA_URL) +-- the decode table: 0..63, 64 = skip (whitespace), 65 = padding, 255 = bad local DEC = buffer.create(256) buffer.fill(DEC, 0, 255) -for i = 0, 63 do - buffer.writeu8(DEC, string.byte(ALPHABET, i + 1), i) +for i = 1, 64 do + buffer.writeu8(DEC, string.byte(ALPHA, i), i - 1) end buffer.writeu8(DEC, string.byte("-"), 62) buffer.writeu8(DEC, string.byte("_"), 63) -for _, c in { 9, 10, 13, 32 } do - buffer.writeu8(DEC, c, 254) -- whitespace: skipped +for _, c in { 9, 10, 11, 12, 13, 32 } do + buffer.writeu8(DEC, c, 64) end +buffer.writeu8(DEC, string.byte("="), 65) local readu8, writeu8 = buffer.readu8, buffer.writeu8 --- encode(data) -> base64 text with padding -function Base64.encode(data: buffer | string): string - local src: buffer = if type(data) == "string" then buffer.fromstring(data) else data - local n = buffer.len(src) - local out = buffer.create((n + 2) // 3 * 4) - local o = 0 - local i = 0 - while i + 2 < n do - local v = readu8(src, i) * 65536 + readu8(src, i + 1) * 256 + readu8(src, i + 2) - writeu8(out, o, readu8(ENC, v // 262144)) - writeu8(out, o + 1, readu8(ENC, v // 4096 % 64)) - writeu8(out, o + 2, readu8(ENC, v // 64 % 64)) - writeu8(out, o + 3, readu8(ENC, v % 64)) - i += 3 - o += 4 +-- encode(data, opts?, offset?, length?) -> base64 text of data[offset, offset + length) +function Base64.encode(data: buffer | string, opts: EncodeOptions?, offset: number?, length: number?): string + local buf: buffer = if type(data) == "string" then buffer.fromstring(data) else data + local total = buffer.len(buf) + local o = math.clamp(offset or 0, 0, total) + local n = math.clamp(length or (total - o), 0, total - o) + local enc = if opts and opts.url then ENC_URL else ENC + local pad = not (opts and opts.pad == false) + local wrap = if opts and opts.wrap and opts.wrap >= 4 then opts.wrap // 4 else 0 -- groups per line + local full = n // 3 + local rest = n - full * 3 + local textLen = full * 4 + (if rest == 0 then 0 elseif pad then 4 else rest + 1) + local groups = full + (if rest > 0 then 1 else 0) + local breaks = if wrap > 0 and groups > 0 then (groups - 1) // wrap else 0 + local out = buffer.create(textLen + breaks) + local p = 0 + local col = 0 + for i = 0, full - 1 do + if wrap > 0 then + if col == wrap then + writeu8(out, p, 10) + p += 1 + col = 0 + end + col += 1 + end + local q = o + i * 3 + local v = readu8(buf, q) * 65536 + readu8(buf, q + 1) * 256 + readu8(buf, q + 2) + writeu8(out, p, readu8(enc, v // 262144)) + writeu8(out, p + 1, readu8(enc, (v // 4096) % 64)) + writeu8(out, p + 2, readu8(enc, (v // 64) % 64)) + writeu8(out, p + 3, readu8(enc, v % 64)) + p += 4 end - local rest = n - i if rest > 0 then - local v = readu8(src, i) * 65536 + (if rest == 2 then readu8(src, i + 1) * 256 else 0) - writeu8(out, o, readu8(ENC, v // 262144)) - writeu8(out, o + 1, readu8(ENC, v // 4096 % 64)) - writeu8(out, o + 2, if rest == 2 then readu8(ENC, v // 64 % 64) else 61) - writeu8(out, o + 3, 61) + if wrap > 0 and col == wrap then + writeu8(out, p, 10) + p += 1 + end + local q = o + full * 3 + local v = readu8(buf, q) * 65536 + (if rest == 2 then readu8(buf, q + 1) * 256 else 0) + writeu8(out, p, readu8(enc, v // 262144)) + writeu8(out, p + 1, readu8(enc, (v // 4096) % 64)) + if rest == 2 then + writeu8(out, p + 2, readu8(enc, (v // 64) % 64)) + elseif pad then + writeu8(out, p + 2, 61) + end + if pad then + writeu8(out, p + 3, 61) + end end return buffer.tostring(out) end --- decode(text) -> buffer | nil, message -function Base64.decode(text: string | buffer): (buffer?, string?) - local src: buffer = if type(text) == "string" then buffer.fromstring(text) else text +-- decode(s) -> buffer | nil, message +function Base64.decode(s: string | buffer): (buffer?, string?) + local src: buffer = if type(s) == "string" then buffer.fromstring(s) else s local n = buffer.len(src) - local out = buffer.create(n // 4 * 3 + 3) - local o = 0 - local acc, bits = 0, 0 - local pad = false + local out = buffer.create((n // 4 + 1) * 3) + local acc, bits, p = 0, 0, 0 + local padded = false for i = 0, n - 1 do - local c = readu8(src, i) - local v = readu8(DEC, c) - if v == 254 then - continue - end - if c == 61 then -- '=' - pad = true - continue - end - if v == 255 or pad then - return nil, string.format("bad base64 character at %d", i) - end - acc = acc * 64 + v - bits += 6 - if bits >= 8 then - bits -= 8 - local p = 2 ^ bits - writeu8(out, o, acc // p) - acc %= p - o += 1 + local d = readu8(DEC, readu8(src, i)) + if d < 64 then + if padded then + return nil, "data after padding" + end + acc = acc * 64 + d + bits += 6 + if bits >= 8 then + bits -= 8 + local scale = 2 ^ bits + local byte = acc // scale + writeu8(out, p, byte % 256) + p += 1 + acc -= byte * scale + end + elseif d == 65 then + padded = true + elseif d ~= 64 then + return nil, string.format("bad base64 character 0x%02x at %d", readu8(src, i), i) end end - local res = buffer.create(o) - buffer.copy(res, 0, out, 0, o) + if bits >= 6 then + return nil, "truncated base64 (a single character in the last group)" + end + local res = buffer.create(p) + buffer.copy(res, 0, out, 0, p) return res, nil end +-- decodeDataUri(uri) -> buffer, mime | nil, message: "data:[][;params][;base64]," (percent-encoded data +-- when not base64) +function Base64.decodeDataUri(uri: string): (buffer?, string?) + if string.sub(uri, 1, 5) ~= "data:" then + return nil, "not a data: URI" + end + local comma = string.find(uri, ",", 6, true) + if not comma then + return nil, "data: URI without a comma" + end + local head = string.sub(uri, 6, comma - 1) + local isB64 = string.sub(head, -7) == ";base64" + local mime = string.match(head, "^([^;]*)") or "" + if mime == "" then + mime = "text/plain" + end + local body = string.sub(uri, comma + 1) + if isB64 then + local b, err = Base64.decode(body) + if not b then + return nil, err + end + return b, mime + end + local decoded = string.gsub(body, "%%(%x%x)", function(h: string): string + return string.char(tonumber(h, 16) :: number) + end) + return buffer.fromstring(decoded), mime +end + +-- dataUri(buf, mime?) -> "data:;base64,..." +function Base64.dataUri(buf: buffer | string, mime: string?): string + return "data:" .. (mime or "application/octet-stream") .. ";base64," .. Base64.encode(buf) +end + return Base64 diff --git a/src/Formats/data/plist/Base64.luau b/src/Formats/data/plist/Base64.luau deleted file mode 100644 index 115cf94..0000000 --- a/src/Formats/data/plist/Base64.luau +++ /dev/null @@ -1,71 +0,0 @@ ---!strict ---!native --- data/plist/Base64: RFC 4648 base64 for plist (decode skips whitespace; encode wraps lines). Never throws. -local Base64 = {} - -local ALPHA = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" -local DEC: { [number]: number } = {} -for i = 1, 64 do - DEC[string.byte(ALPHA, i)] = i - 1 -end -local ENC: { string } = {} -for i = 1, 64 do - ENC[i - 1] = string.sub(ALPHA, i, i) -end - --- decode(s) -> buffer | nil, message (whitespace ignored; padding optional) -function Base64.decode(s: string): (buffer?, string?) - local clean = string.gsub(s, "[ \t\r\n]", "") - clean = string.gsub(clean, "=+$", "") - local n = #clean - if n % 4 == 1 then - return nil, "bad base64 length" - end - local out = buffer.create(n * 3 // 4) - local o = 0 - local acc, bits = 0, 0 - for i = 1, n do - local v = DEC[string.byte(clean, i)] - if v == nil then - return nil, "bad base64 character" - end - acc = acc * 64 + v - bits += 6 - if bits >= 8 then - bits -= 8 - local b = acc // (2 ^ bits) - buffer.writeu8(out, o, b) - o += 1 - acc -= b * 2 ^ bits - end - end - return out, nil -end - --- encode(b, lineBytes?) -> base64 text; lineBytes > 0 puts "\n" after every lineBytes input bytes (and at the end) -function Base64.encode(b: buffer, lineBytes: number?): string - local n = buffer.len(b) - local parts = table.create(n // 3 + 2) - local per = lineBytes or 0 - local k = 0 - local i = 0 - while i < n do - local a = buffer.readu8(b, i) - local c1 = if i + 1 < n then buffer.readu8(b, i + 1) else 0 - local c2 = if i + 2 < n then buffer.readu8(b, i + 2) else 0 - local v = a * 65536 + c1 * 256 + c2 - local q = ENC[v // 262144] .. ENC[(v // 4096) % 64] - q ..= if i + 1 < n then ENC[(v // 64) % 64] else "=" - q ..= if i + 2 < n then ENC[v % 64] else "=" - k += 1 - parts[k] = q - i += 3 - if per > 0 and (i % per == 0 or i >= n) then - k += 1 - parts[k] = "\n" - end - end - return table.concat(parts) -end - -return Base64 diff --git a/src/Formats/data/plist/init.luau b/src/Formats/data/plist/init.luau index e8bede1..aafd126 100644 --- a/src/Formats/data/plist/init.luau +++ b/src/Formats/data/plist/init.luau @@ -11,7 +11,7 @@ local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") local Xml = require("@formats/codecs/Xml") local Json = require("@formats/codecs/Json") -local Base64 = require("@formats/data/plist/Base64") +local Base64 = require("@formats/core/Base64") local Binary = require("@formats/data/plist/Binary") -- ------------------------------------------------------------------------------------------------ contract @@ -20,7 +20,7 @@ local Plist = { category = "data", extensions = { "plist" }, mime = { "application/x-plist", "application/x-bplist" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "codecs/Json" }, + deps = { "core/Err", "core/Bytes", "Types", "core/Base64", "codecs/Xml", "codecs/Json" }, caps = { decode = true, encode = true, binary = "read", ordered = true }, } @@ -217,7 +217,7 @@ function Plist.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) elseif tv == "buffer" then line(level, "") local maxLine = math.max(16, 76 - 8 * level) - for l in string.gmatch(Base64.encode(v, maxLine // 4 * 3), "[^\n]+") do + for l in string.gmatch(Base64.encode(v, { wrap = maxLine // 4 * 4 }), "[^\n]+") do line(level, l) end line(level, "") diff --git a/src/Formats/data/yaml/Emit.luau b/src/Formats/data/yaml/Emit.luau index 6fbacac..00970bd 100644 --- a/src/Formats/data/yaml/Emit.luau +++ b/src/Formats/data/yaml/Emit.luau @@ -5,6 +5,7 @@ -- !!binary; dates as their RFC 3339 text; tables referenced twice get an anchor and aliases. Never throws: bad -- values (cycles, functions, collection keys) return nil, message. local Types = require("@formats/Types") +local Base64 = require("@formats/core/Base64") local Parse = require("@formats/data/yaml/Parse") local Emit = {} @@ -119,22 +120,6 @@ local function str(s: string, ind: string, key: boolean): string return dquote(s) end -local function b64(b: buffer): string - local A = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" - local out = {} - local n = buffer.len(b) - for i = 0, n - 1, 3 do - local a1 = buffer.readu8(b, i) - local a2 = if i + 1 < n then buffer.readu8(b, i + 1) else 0 - local a3 = if i + 2 < n then buffer.readu8(b, i + 2) else 0 - local v = a1 * 65536 + a2 * 256 + a3 - local c1, c2, c3, c4 = v // 262144, (v // 4096) % 64, (v // 64) % 64, v % 64 - table.insert(out, string.sub(A, c1 + 1, c1 + 1) .. string.sub(A, c2 + 1, c2 + 1) - .. (if i + 1 < n then string.sub(A, c3 + 1, c3 + 1) else "=") .. (if i + 2 < n then string.sub(A, c4 + 1, c4 + 1) else "=")) - end - return table.concat(out) -end - local function isArray(t: { [any]: any }): boolean if Types.isObject(t) then return false @@ -202,7 +187,7 @@ local function scalar(st: St, v: any, ind: string, key: boolean): string? elseif tv == "string" then return str(v, ind, key) elseif tv == "buffer" then - return "!!binary " .. b64(v) + return "!!binary " .. Base64.encode(v) elseif tv == "table" and Types.Date.is(v) then return tostring(v) end diff --git a/src/Formats/data/yaml/Parse.luau b/src/Formats/data/yaml/Parse.luau index fc84c87..b34b6ad 100644 --- a/src/Formats/data/yaml/Parse.luau +++ b/src/Formats/data/yaml/Parse.luau @@ -7,6 +7,7 @@ -- schema. Not supported: complex keys ("? "), collections as keys, recursive aliases, merge keys "<<" (kept as a -- normal key). Internally raises { yamlErr } tables caught by run(); never throws past it. local Types = require("@formats/Types") +local Base64 = require("@formats/core/Base64") local Parse = {} @@ -171,39 +172,8 @@ function Parse.resolve(t: string, nullv: any): any return t end -local B64: { [number]: number } = {} -do - local alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" - for i = 1, 64 do - B64[byte(alphabet, i)] = i - 1 - end -end local function base64(t: string): buffer? - t = string.gsub(t, "[%s]", "") - t = string.gsub(t, "=+$", "") - local n = #t - if n % 4 == 1 then - return nil - end - local out = buffer.create(n * 3 // 4) - local o = 0 - local acc, bits = 0, 0 - for i = 1, n do - local v = B64[byte(t, i)] - if v == nil then - return nil - end - acc = acc * 64 + v - bits += 6 - if bits >= 8 then - bits -= 8 - local b = acc // (2 ^ bits) - buffer.writeu8(out, o, b) - o += 1 - acc -= b * 2 ^ bits - end - end - return out + return (Base64.decode(t)) end -- a scalar's value given its tag (nil = untagged, "!" = non-specific) diff --git a/src/Formats/data/yaml/init.luau b/src/Formats/data/yaml/init.luau index fd605b7..3eed2c5 100644 --- a/src/Formats/data/yaml/init.luau +++ b/src/Formats/data/yaml/init.luau @@ -20,7 +20,7 @@ local Yaml = { category = "data", extensions = { "yaml", "yml" }, mime = { "application/yaml", "application/x-yaml", "text/yaml" }, - deps = { "core/Err", "core/Bytes", "Types" }, + deps = { "core/Err", "core/Bytes", "Types", "core/Base64" }, caps = { decode = true, encode = true, ordered = true, multiDocument = true, anchors = true }, } diff --git a/src/Formats/model/dae/Read.luau b/src/Formats/model/dae/Read.luau index 82bbb59..85512a1 100644 --- a/src/Formats/model/dae/Read.luau +++ b/src/Formats/model/dae/Read.luau @@ -11,7 +11,7 @@ local Err = require("@formats/core/Err") local Types = require("@formats/Types") local Xml = require("@formats/codecs/Xml") -local Base64 = require("@formats/codecs/Base64") +local Base64 = require("@formats/core/Base64") local M = require("@formats/model/dae/Math") local Read = {} diff --git a/src/Formats/model/dae/Write.luau b/src/Formats/model/dae/Write.luau index 86e6d2a..e8bf23d 100644 --- a/src/Formats/model/dae/Write.luau +++ b/src/Formats/model/dae/Write.luau @@ -6,7 +6,7 @@ -- lights. Not written: skins, morph targets, animations. local Types = require("@formats/Types") local Xml = require("@formats/codecs/Xml") -local Base64 = require("@formats/codecs/Base64") +local Base64 = require("@formats/core/Base64") local M = require("@formats/model/dae/Math") local Write = {} diff --git a/src/Formats/model/dae/init.luau b/src/Formats/model/dae/init.luau index 1e245b1..c655256 100644 --- a/src/Formats/model/dae/init.luau +++ b/src/Formats/model/dae/init.luau @@ -37,7 +37,7 @@ local Dae = { category = "model", extensions = { "dae", "zae" }, mime = { "model/vnd.collada+xml", "model/vnd.collada+zip" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "codecs/Base64", "containers/Zip" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "core/Base64", "containers/Zip" }, caps = { decode = true, encode = true, materials = true, polygons = true, skins = true, morphTargets = true, animation = true, cameras = true, lights = true, zae = true }, } diff --git a/src/Formats/model/gltf/Read.luau b/src/Formats/model/gltf/Read.luau index ab59fe6..1121848 100644 --- a/src/Formats/model/gltf/Read.luau +++ b/src/Formats/model/gltf/Read.luau @@ -7,7 +7,7 @@ -- scenes. glTF extras and unhandled extensions are kept in .extras.gltf = { extras, extensions }. local Err = require("@formats/core/Err") local Types = require("@formats/Types") -local Base64 = require("@formats/codecs/Base64") +local Base64 = require("@formats/core/Base64") local Pack = require("@formats/model/gltf/Pack") local Read = {} diff --git a/src/Formats/model/gltf/init.luau b/src/Formats/model/gltf/init.luau index 3f533a0..425ca12 100644 --- a/src/Formats/model/gltf/init.luau +++ b/src/Formats/model/gltf/init.luau @@ -20,7 +20,7 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") local Json = require("@formats/codecs/Json") -local Base64 = require("@formats/codecs/Base64") +local Base64 = require("@formats/core/Base64") local Read = require("@formats/model/gltf/Read") local Write = require("@formats/model/gltf/Write") @@ -30,7 +30,7 @@ local Gltf = { category = "model", extensions = { "gltf", "glb" }, mime = { "model/gltf+json", "model/gltf-binary" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Json", "codecs/Base64" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Json", "core/Base64" }, caps = { decode = true, encode = true, binary = true, materials = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true }, } diff --git a/tests/codecs/base64.luau b/tests/codecs/base64.luau deleted file mode 100644 index 7d9e4b4..0000000 --- a/tests/codecs/base64.luau +++ /dev/null @@ -1,46 +0,0 @@ --- codecs/Base64 tests: encode / decode against Python's base64 (standard, URL-safe, unpadded) for every length 0..70 --- and some large inputs, whitespace and missing padding on decode, data: URIs, bad input, and the fuzz no-throw pass. --- Fixtures: tools/fixtures/base64.py. -local T = require("@tests/T") -local Base64 = require("@formats/codecs/Base64") -local Cases = require("@tests/gen/base64_cases") - -local t = T.suite("base64") - -for _, c in Cases do - local b = buffer.fromstring(c.data) - t:eq(Base64.encode(b), c.std, "encode " .. #c.data) - t:eq(Base64.encode(b, { url = true }), c.url, "encode url " .. #c.data) - t:eq(Base64.encode(b, { pad = false }), c.nopad, "encode unpadded " .. #c.data) - for _, s in { c.std, c.url, c.nopad } do - local d, err = Base64.decode(s) - t:check(d and buffer.tostring(d) == c.data, "decode " .. #c.data .. ": " .. tostring(err)) - end - -- with line breaks every 76 characters (MIME) - local wrapped = string.gsub(c.std, "(" .. string.rep(".", 76) .. ")", "%1\r\n") - local d = Base64.decode(wrapped) - t:check(d and buffer.tostring(d) == c.data, "decode wrapped " .. #c.data) -end --- a sub-range -t:eq(Base64.encode(buffer.fromstring("xxhelloyy"), nil, 2, 5), "aGVsbG8=", "encode a range") --- data URIs -local b, mime = Base64.decodeDataUri("data:application/gltf-buffer;base64,AAEC") -t:check(b and buffer.len(b) == 3 and buffer.readu8(b, 2) == 2 and mime == "application/gltf-buffer", "data URI") -local b2, m2 = Base64.decodeDataUri("data:,a%20b") -t:check(b2 and buffer.tostring(b2) == "a b" and m2 == "text/plain", "percent-encoded data URI") -t:eq(Base64.dataUri(buffer.fromstring("hi"), "text/plain"), "data:text/plain;base64,aGk=", "dataUri") --- bad input -t:check(Base64.decode("ab$d") == nil, "bad character") -t:check(Base64.decode("abcde") == nil, "a lone last character") -t:check(Base64.decode("ab==cd") == nil, "data after padding") -t:check(Base64.decodeDataUri("http://x") == nil, "not a data URI") -local samples = {} -for i, c in Cases do - if i % 10 == 0 then - table.insert(samples, c.std) - end -end -t:fuzz("decode", function(x: buffer) - return Base64.decode(x) -end, samples) -t:done() diff --git a/tests/core/base64.luau b/tests/core/base64.luau index 73c0880..df3786f 100644 --- a/tests/core/base64.luau +++ b/tests/core/base64.luau @@ -1,9 +1,26 @@ --- core/Base64 tests: the RFC 4648 vectors, whitespace / missing padding / URL-safe input, bad characters, random --- round trips. +-- core/Base64 tests: the RFC 4648 vectors, encode / decode against Python's base64 (standard, URL-safe, unpadded) for every length 0..70 +-- and some large inputs, whitespace and missing padding on decode, data: URIs, bad input, and the fuzz no-throw pass. +-- Fixtures: tools/fixtures/base64.py. local T = require("@tests/T") local Base64 = require("@formats/core/Base64") +local Cases = require("@tests/gen/base64_cases") local t = T.suite("base64") + +for _, c in Cases do + local b = buffer.fromstring(c.data) + t:eq(Base64.encode(b), c.std, "encode " .. #c.data) + t:eq(Base64.encode(b, { url = true }), c.url, "encode url " .. #c.data) + t:eq(Base64.encode(b, { pad = false }), c.nopad, "encode unpadded " .. #c.data) + for _, s in { c.std, c.url, c.nopad } do + local d, err = Base64.decode(s) + t:check(d and buffer.tostring(d) == c.data, "decode " .. #c.data .. ": " .. tostring(err)) + end + -- with line breaks every 76 characters (MIME) + local wrapped = string.gsub(c.std, "(" .. string.rep(".", 76) .. ")", "%1\r\n") + local d = Base64.decode(wrapped) + t:check(d and buffer.tostring(d) == c.data, "decode wrapped " .. #c.data) +end for _, v in { { "", "" }, { "f", "Zg==" }, { "fo", "Zm8=" }, { "foo", "Zm9v" }, { "foob", "Zm9vYg==" }, { "fooba", "Zm9vYmE=" }, { "foobar", "Zm9vYmFy" } } do t:eq(Base64.encode(v[1]), v[2], "encode " .. v[1]) t:eq(buffer.tostring(Base64.decode(v[2]) :: buffer), v[1], "decode " .. v[2]) @@ -22,4 +39,30 @@ for n = 0, 40 do end t:eq(buffer.tostring(Base64.decode(Base64.encode(s)) :: buffer), buffer.tostring(s), "round trip " .. n) end +-- line wrapping (plist / MIME) +t:eq(Base64.encode("foobarfoobarfo", { wrap = 8 }), "Zm9vYmFy\nZm9vYmFy\nZm8=", "wrap 8") +t:eq(Base64.encode("foobarfoobar", { wrap = 8 }), "Zm9vYmFy\nZm9vYmFy", "wrap at the end") +t:eq(Base64.encode("foobarfoobar", { wrap = 9 }), "Zm9vYmFy\nZm9vYmFy", "wrap rounds to groups") +-- a sub-range +t:eq(Base64.encode(buffer.fromstring("xxhelloyy"), nil, 2, 5), "aGVsbG8=", "encode a range") +-- data URIs +local b, mime = Base64.decodeDataUri("data:application/gltf-buffer;base64,AAEC") +t:check(b and buffer.len(b) == 3 and buffer.readu8(b, 2) == 2 and mime == "application/gltf-buffer", "data URI") +local b2, m2 = Base64.decodeDataUri("data:,a%20b") +t:check(b2 and buffer.tostring(b2) == "a b" and m2 == "text/plain", "percent-encoded data URI") +t:eq(Base64.dataUri(buffer.fromstring("hi"), "text/plain"), "data:text/plain;base64,aGk=", "dataUri") +-- bad input +t:check(Base64.decode("ab$d") == nil, "bad character") +t:check(Base64.decode("abcde") == nil, "a lone last character") +t:check(Base64.decode("ab==cd") == nil, "data after padding") +t:check(Base64.decodeDataUri("http://x") == nil, "not a data URI") +local samples = {} +for i, c in Cases do + if i % 10 == 0 then + table.insert(samples, c.std) + end +end +t:fuzz("decode", function(x: buffer) + return Base64.decode(x) +end, samples) t:done() diff --git a/tools/fixtures/gltf.py b/tools/fixtures/gltf.py index a424fcf..3172723 100644 --- a/tools/fixtures/gltf.py +++ b/tools/fixtures/gltf.py @@ -8,7 +8,7 @@ # by assimp and trimesh: { name, case, assimp, trimesh } import importlib.util, json, os, struct -INPUTS = ["tests/fixtures/gltf", "src/Formats/model/gltf", "src/Formats/codecs/Json", "src/Formats/codecs/Base64", +INPUTS = ["tests/fixtures/gltf", "src/Formats/model/gltf", "src/Formats/codecs/Json", "src/Formats/core/Base64", "tools/fixtures/_model_ref.py", "tools/fixtures/_gltf_encode.luau"] From 7169f2cc2ca4f1982a262fb494ca97741faf3408 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 10:50:56 -0500 Subject: [PATCH 04/22] ws-cleanup: codecs/Resample, codecs/RangeCoder; Opus / MP3 / MP2 encoders resample through it - codecs/Resample (new): Kaiser-windowed sinc resampler, polyphase (exact phases when to / gcd <= 4096, else 4096 interpolated phases), quality low / medium / high (8 / 16 / 32 zero crossings), streaming (new / process / flush), whole buffer (Resample.buffer) and a codecs/Pcm source wrapper (Resample.source). tests/codecs/resample: SNR 87 dB (44.1 -> 48 kHz, medium) .. 108 dB (high), alias rejection, streamed = whole, identity. - audio/opus/Encode: input through codecs/Pcm (Pcm.source + collect) and codecs/Resample instead of its private resampler and Decoder loop; tags through codecs/VorbisComment. - audio/mp3 encode: rates the layer cannot hold are resampled to the next rate up (opts.sampleRate picks one, opts.resampleQuality); was Err.ARG "no resampling". - codecs/RangeCoder/{Decoder,Encoder}: the RFC 6716 range coder moved out of audio/opus (same code, no speed change). - audio/opus/Mdct stays private: routing CELT through codecs/Mdct measured 2-3x slower CELT decoding and different output bits (documented in its header). - (this commit also carries the Opus side of the tags / channel order consistency: codecs/VorbisComment for OpusTags, meta.source.comments, mapping family 1 decoded to WAVE channel order with Pcm.reorder / Pcm.WAVE_FROM_VORBIS.) --- src/Formats/audio/mp3/init.luau | 41 ++- src/Formats/audio/opus/Celt.luau | 2 +- src/Formats/audio/opus/CeltEncoder.luau | 2 +- src/Formats/audio/opus/Decoder.luau | 2 +- src/Formats/audio/opus/Encode.luau | 130 ++----- src/Formats/audio/opus/Mdct.luau | 4 + src/Formats/audio/opus/Silk.luau | 2 +- src/Formats/audio/opus/init.luau | 64 ++-- src/Formats/codecs/Pcm/init.luau | 30 ++ src/Formats/codecs/RangeCoder/Decoder.luau | 5 +- src/Formats/codecs/RangeCoder/Encoder.luau | 4 +- src/Formats/codecs/RangeCoder/init.luau | 13 + src/Formats/codecs/Resample/init.luau | 378 +++++++++++++++++++++ src/Formats/codecs/VorbisComment.luau | 62 ++++ tests/audio/mp3_encode.luau | 42 ++- tests/audio/opus.luau | 13 +- tests/codecs/resample.luau | 133 ++++++++ 17 files changed, 777 insertions(+), 150 deletions(-) create mode 100644 src/Formats/codecs/RangeCoder/init.luau create mode 100644 src/Formats/codecs/Resample/init.luau create mode 100644 src/Formats/codecs/VorbisComment.luau create mode 100644 tests/codecs/resample.luau diff --git a/src/Formats/audio/mp3/init.luau b/src/Formats/audio/mp3/init.luau index e3bd87d..af05e04 100644 --- a/src/Formats/audio/mp3/init.luau +++ b/src/Formats/audio/mp3/init.luau @@ -6,7 +6,8 @@ -- past garbage, mono / stereo switches (upmixed), ID3v2.2 / 2.3 / 2.4 and ID3v1 / 1.1 tags (APEv2 skipped). -- Float output (minimp3's MINIMP3_FLOAT_OUTPUT scalar path). Encode (ws-audio, audio/mp3/Encode3 + Encode2): layer III -- (shine-style CBR, MPEG-1 / 2 / 2.5) and layer II (MPEG-1 / 2), mono / stereo / joint stereo, an ID3v2.4 tag from --- the tags. Not supported: MPEG-2 multichannel extension, CRC checks, VBR / Xing output, encoder resampling. +-- the tags; input at rates the layer cannot hold is resampled (codecs/Resample). Not supported: MPEG-2 multichannel +-- extension, CRC checks, VBR / Xing output. -- -- local dec = Mp3.open(Bytes.reader(buf)) -- the streaming Types.Decoder (+ layer, version, vbr, delay, -- local pcm, n = dec:read(4096) -- padding, mpegFrames, id3, :seekFrame(i), :readAll()) @@ -23,6 +24,7 @@ local Stream = require("@formats/audio/mp3/Stream") local Encode3 = require("@formats/audio/mp3/Encode3") local Encode2 = require("@formats/audio/mp3/Encode2") local Pcm = require("@formats/codecs/Pcm") +local Resample = require("@formats/codecs/Resample") -- ------------------------------------------------------------------------------------------------ contract local Mp3 = { @@ -30,7 +32,7 @@ local Mp3 = { category = "audio", extensions = { "mp3", "mp2", "mp1", "mpga" }, mime = { "audio/mpeg", "audio/mp3", "audio/mpa" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm", "codecs/Resample" }, caps = { decode = true, encode = true, streaming = true, seek = true, layers = { 1, 2, 3 }, channels = 2 }, } @@ -45,6 +47,9 @@ export type EncodeOptions = { mode: ("stereo" | "joint" | "mono")?, -- default "joint" (mid / side) for stereo layer III, "stereo" for layer II, -- "mono" for mono input; layer II has no joint stereo (intensity) and writes "joint" as "stereo" id3: boolean?, -- write an ID3v2.4 tag from the tags (default true when there are tags) + sampleRate: number?, -- output rate (one the layer holds); default the input rate if possible, else the nearest + -- higher one (input at other rates is resampled through codecs/Resample) + resampleQuality: ("low" | "medium" | "high")?, -- codecs/Resample quality (default "medium") } -- ------------------------------------------------------------------------------------------------ constants @@ -101,7 +106,7 @@ local ID3_FRAMES = { { "title", "TIT2" }, { "artist", "TPE1" }, { "album", "TALB" }, - { "albumArtist", "TPE2" }, + { "albumartist", "TPE2" }, { "year", "TDRC" }, { "date", "TDRC" }, { "track", "TRCK" }, @@ -170,10 +175,30 @@ function Mp3.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) return nil, Err.new(Err.ARG, "layer must be 2 or 3") end local Enc = if layer == 3 then Encode3 else Encode2 - local info = Enc.RATES[src.sampleRate] - if not info then - return nil, Err.new(Err.ARG, string.format("layer %d cannot hold %s Hz (no resampling)", layer, tostring(src.sampleRate))) + -- the output rate: opts.sampleRate, else the input's when the layer has it, else the nearest rate above it (else + -- the highest); other input rates go through codecs/Resample + local rate = o.sampleRate or src.sampleRate + if o.sampleRate and not Enc.RATES[o.sampleRate] then + return nil, Err.new(Err.ARG, string.format("layer %d cannot hold %s Hz", layer, tostring(o.sampleRate))) end + if not Enc.RATES[rate] then + local best, top = nil, 0 + for r in Enc.RATES do + top = math.max(top, r) + if r >= rate and (best == nil or r < best) then + best = r + end + end + rate = best or top + end + if rate ~= src.sampleRate then + local rs, rerr = Resample.source(src, rate, { quality = o.resampleQuality }) + if not rs then + return nil, Err.new(Err.ARG, tostring(rerr)) + end + src = rs + end + local info = Enc.RATES[rate] local mpeg1 = info[1] == 3 local mode = o.mode or (if src.channels == 1 then "mono" elseif layer == 3 then "joint" else "stereo") if mode ~= "stereo" and mode ~= "joint" and mode ~= "mono" then @@ -187,7 +212,7 @@ function Mp3.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end local bitrate = o.bitrate or (if mpeg1 then (if layer == 3 then 128 else 192) else (if layer == 3 then 64 else 96)) if not table.find(Enc.BITRATES[if mpeg1 then 1 else 2], bitrate) then - return nil, Err.new(Err.ARG, string.format("%s kbps is not a layer %d bit rate at %d Hz", tostring(bitrate), layer, src.sampleRate)) + return nil, Err.new(Err.ARG, string.format("%s kbps is not a layer %d bit rate at %d Hz", tostring(bitrate), layer, rate)) end if layer == 2 and mpeg1 then -- the standard's allowed bit rate / mode combinations @@ -206,7 +231,7 @@ function Mp3.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- the string-valued tag fields (title, artist, album, albumArtist, year, track, disc, genre, composer, comment) +-- the string-valued tag fields (title, artist, album, albumartist, date, track, disc, genre, composer, comment) local function stringTags(t: any): { [string]: string } local out: { [string]: string } = {} for k, v in t do diff --git a/src/Formats/audio/opus/Celt.luau b/src/Formats/audio/opus/Celt.luau index 7bdbc15..81a6c68 100644 --- a/src/Formats/audio/opus/Celt.luau +++ b/src/Formats/audio/opus/Celt.luau @@ -7,7 +7,7 @@ -- -- Arrays are Luau tables of numbers. All normalised-band data (X, Y, the folding memory `norm` and the scratch -- copies) lives in one table W, and the "pointers" of the C code are 0-based offsets into it. -local RD = require("@formats/audio/opus/RangeDecoder") +local RD = require("@formats/codecs/RangeCoder/Decoder") local Mdct = require("@formats/audio/opus/Mdct") local T = require("@formats/audio/opus/CeltTables") diff --git a/src/Formats/audio/opus/CeltEncoder.luau b/src/Formats/audio/opus/CeltEncoder.luau index 7c8225a..b4891a8 100644 --- a/src/Formats/audio/opus/CeltEncoder.luau +++ b/src/Formats/audio/opus/CeltEncoder.luau @@ -7,7 +7,7 @@ -- (celt_encoder.c, quant_bands.c, laplace.c, rate.c, bands.c, vq.c, cwrs.c; BSD: licenses/libopus-BSD.txt) that -- mirror audio/opus/Celt's decoder step for step; the analysis is simplified. The MDCT is codecs/Mdct. -- Never throws. -local RE = require("@formats/audio/opus/RangeEncoder") +local RE = require("@formats/codecs/RangeCoder/Encoder") local T = require("@formats/audio/opus/CeltTables") local Mdct = require("@formats/codecs/Mdct") diff --git a/src/Formats/audio/opus/Decoder.luau b/src/Formats/audio/opus/Decoder.luau index 88e1b22..c4fc928 100644 --- a/src/Formats/audio/opus/Decoder.luau +++ b/src/Formats/audio/opus/Decoder.luau @@ -4,7 +4,7 @@ -- audio/opus/Decoder: The Opus decoder proper (libopus src/opus_decoder.c and opus_multistream_decoder.c): per-frame mode switching -- between SILK, hybrid and CELT, the redundant CELT frames of mode transitions, cross-fades, PLC fallbacks, the -- multi-frame packet loop and multistream (channel mapping) decoding. Output is 48 kHz float in Luau arrays. -local RD = require("@formats/audio/opus/RangeDecoder") +local RD = require("@formats/codecs/RangeCoder/Decoder") local Packet = require("@formats/audio/opus/Packet") local Celt = require("@formats/audio/opus/Celt") local Silk = require("@formats/audio/opus/Silk") diff --git a/src/Formats/audio/opus/Encode.luau b/src/Formats/audio/opus/Encode.luau index 13e4c05..d26e4b1 100644 --- a/src/Formats/audio/opus/Encode.luau +++ b/src/Formats/audio/opus/Encode.luau @@ -2,10 +2,14 @@ -- audio/opus/Encode: Ogg Opus writing (RFC 7845) around audio/opus/CeltEncoder: CELT-only packets (TOC config 31: -- full band, 20 ms, code 0), OpusHead (mapping family 0, the pre-skip = the encoder's delay), OpusTags (vendor + -- the tags as Vorbis comments), granule positions with end trimming, pages through containers/Ogg's muxer. Input at --- other rates is resampled to 48 kHz (a Kaiser-windowed sinc; quality enough for a codec input). New in formats-luau. +-- other rates is resampled to 48 kHz (codecs/Resample); the input is a Types.Audio or a Decoder (codecs/Pcm). New in +-- formats-luau. local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Ogg = require("@formats/containers/Ogg") +local Pcm = require("@formats/codecs/Pcm") +local Resample = require("@formats/codecs/Resample") +local VorbisComment = require("@formats/codecs/VorbisComment") local CeltEncoder = require("@formats/audio/opus/CeltEncoder") local Encode = {} @@ -17,69 +21,20 @@ export type Options = { serial: number?, -- Ogg stream serial (default 0x4f707573) } -local floor, sin, pi, sqrt = math.floor, math.sin, math.pi, math.sqrt - -local function besselI0(x: number): number - local sum, term = 1, 1 - for k = 1, 60 do - term *= (x / (2 * k)) ^ 2 - sum += term - if term < sum * 1e-15 then - break - end - end - return sum -end - --- resample(src (interleaved f32 buffer), frames, channels, from, to) -> { number } interleaved, frames out -local function resample(src: buffer, frames: number, channels: number, from: number, to: number): ({ number }, number) - local outFrames = floor(frames * to / from + 0.5) - local out = table.create(outFrames * channels, 0) - local ratio = to / from - local cutoff = 0.97 * math.min(1, ratio) -- of the input Nyquist - local half = 16 -- zero crossings each side (at the cutoff) - local width = half / cutoff - local beta = 8 - local i0b = besselI0(beta) - local readf32 = buffer.readf32 - for j = 0, outFrames - 1 do - local t = j / ratio -- the input position - local first = math.max(0, floor(t - width) + 1) - local last = math.min(frames - 1, floor(t + width)) - for c = 0, channels - 1 do - local acc, wsum = 0, 0 - for i = first, last do - local d = i - t - local x = d * cutoff - local s = if x == 0 then 1 else sin(pi * x) / (pi * x) - local r = d / width - local w = besselI0(beta * sqrt(math.max(0, 1 - r * r))) / i0b - local h = s * w - acc += readf32(src, (i * channels + c) * 4) * h - wsum += h - end - out[j * channels + c + 1] = if wsum ~= 0 then acc / wsum else 0 - end - end - return out, outFrames -end - -local TAG_NAMES: { [string]: string } = { - title = "TITLE", artist = "ARTIST", album = "ALBUM", albumartist = "ALBUMARTIST", date = "DATE", genre = "GENRE", - track = "TRACKNUMBER", tracktotal = "TRACKTOTAL", disc = "DISCNUMBER", comment = "COMMENT", composer = "COMPOSER", -} +local floor = math.floor -- encode(audio | decoder, opts) -> buffer | nil, Err function Encode.encode(value: any, opts: Options?): (buffer?, Err.Err?) local o = opts or {} - if type(value) ~= "table" or type(value.sampleRate) ~= "number" or type(value.channels) ~= "number" then - return nil, Err.new(Err.ARG, "expected an Audio or a Decoder") + local src, serr = Pcm.source(value) + if not src then + return nil, serr end - local ch = value.channels + local ch = src.channels if ch ~= 1 and ch ~= 2 then return nil, Err.new(Err.UNSUPPORTED, "the CELT encoder writes mono or stereo (got " .. ch .. " channels)") end - local rate = value.sampleRate + local rate = src.sampleRate if rate < 1000 or rate > 768000 then return nil, Err.new(Err.ARG, "bad sample rate " .. tostring(rate)) end @@ -87,40 +42,24 @@ function Encode.encode(value: any, opts: Options?): (buffer?, Err.Err?) if type(bitrate) ~= "number" or bitrate < 6000 or bitrate > 510000 then return nil, Err.new(Err.ARG, "bitrate 6000 .. 510000") end - -- the whole input as an interleaved f32 buffer - local samples: buffer, frames: number - if value.kind == "audio" and type(value.samples) == "buffer" then - samples, frames = value.samples, value.frames - if buffer.len(samples) < frames * ch * 4 then - return nil, Err.new(Err.ARG, "audio.samples is shorter than frames * channels") + -- the whole input at 48 kHz (codecs/Resample for other rates), then as floats + if rate ~= 48000 then + local rs, rerr = Resample.source(src, 48000) + if not rs then + return nil, Err.new(Err.ARG, tostring(rerr)) end - elseif type(value.read) == "function" then - local w = Bytes.writer(65536) - frames = 0 - local chunk: buffer? = nil - while true do - local b, n = value:read(16384, chunk) - chunk = b - if n <= 0 then - break - end - w:bytes(b, 0, n * ch * 4) - frames += n - end - samples = w:finish() - else - return nil, Err.new(Err.ARG, "expected an Audio or a Decoder") + src = rs end - -- 48 kHz floats - local pcm: { number }, n48: number - if rate == 48000 then - n48 = frames - pcm = table.create(frames * ch, 0) - for i = 1, frames * ch do - pcm[i] = buffer.readf32(samples, (i - 1) * 4) - end - else - pcm, n48 = resample(samples, frames, ch, rate, 48000) + local all, aerr = Pcm.collect(src :: Pcm.Source) + if not all then + return nil, aerr + end + local n48 = all.frames + local samples = all.samples + local pcm: { number } = table.create(n48 * ch, 0) + local readf32 = buffer.readf32 + for i = 1, n48 * ch do + pcm[i] = readf32(samples, (i - 1) * 4) end local FRAME = CeltEncoder.FRAME local preSkip = CeltEncoder.DELAY @@ -144,22 +83,15 @@ function Encode.encode(value: any, opts: Options?): (buffer?, Err.Err?) head:u8(0) s:packet(head:finish(), 0, { flush = true }) -- OpusTags - local tags = o.tags or value.tags or {} + local tags = o.tags or src.tags or {} local tw = Bytes.writer(256) tw:string("OpusTags") local vendor = o.vendor or "formats-luau" tw:u32le(#vendor) tw:string(vendor) - local keys = {} - for k, v in tags do - if type(k) == "string" and type(v) == "string" then - table.insert(keys, k) - end - end - table.sort(keys) - tw:u32le(#keys) - for _, k in keys do - local field = (TAG_NAMES[k] or string.upper(k)) .. "=" .. tags[k] + local fields = VorbisComment.fields(tags) + tw:u32le(#fields) + for _, field in fields do tw:u32le(#field) tw:string(field) end diff --git a/src/Formats/audio/opus/Mdct.luau b/src/Formats/audio/opus/Mdct.luau index 43557fe..9143cb5 100644 --- a/src/Formats/audio/opus/Mdct.luau +++ b/src/Formats/audio/opus/Mdct.luau @@ -4,6 +4,10 @@ -- audio/opus/Mdct: CELT inverse MDCT (libopus celt/mdct.c clt_mdct_backward) over a mixed-radix complex FFT (a port of the -- kiss_fft stages used by libopus: radix 5, 3, 4 and 2). The 48 kHz mode uses N = 1920 >> shift for -- shift = 0..3 (FFT sizes 480, 240, 120, 60). Arrays are Luau tables of numbers, 1-based. +-- Why not codecs/Mdct (measured by the cleanup pass): the shared transform computes the full N-sample IMDCT through a +-- DCT-IV, of which CELT keeps the middle N / 2, so routing the decoder through it made CELT decoding 2-3x slower +-- (luau: 25 -> 54-76 ms for 3 s of 32 kbps stereo) and changed the output bits (same SNR against opusdec). This +-- fused libopus port (pre-rotation, a kiss_fft with fixed factors, post-rotation, TDAC) stays private. local Mdct = {} local sin, cos, pi = math.sin, math.cos, math.pi diff --git a/src/Formats/audio/opus/Silk.luau b/src/Formats/audio/opus/Silk.luau index 428b06b..7c76401 100644 --- a/src/Formats/audio/opus/Silk.luau +++ b/src/Formats/audio/opus/Silk.luau @@ -14,7 +14,7 @@ -- -- Fixed-point emulation: all values are Luau numbers holding C int32 / int16 values. Products of two int32 values -- (64-bit in C) are split so that every intermediate stays below 2^53 and therefore exact. -local RD = require("@formats/audio/opus/RangeDecoder") +local RD = require("@formats/codecs/RangeCoder/Decoder") local T = require("@formats/audio/opus/SilkTables") local icdf = RD.icdf diff --git a/src/Formats/audio/opus/init.luau b/src/Formats/audio/opus/init.luau index 2d80432..3dee5af 100644 --- a/src/Formats/audio/opus/init.luau +++ b/src/Formats/audio/opus/init.luau @@ -24,7 +24,9 @@ local Types = require("@formats/Types") local Ogg = require("@formats/containers/Ogg") local Decoder = require("@formats/audio/opus/Decoder") local Packet = require("@formats/audio/opus/Packet") -local RangeDecoder = require("@formats/audio/opus/RangeDecoder") +local VorbisComment = require("@formats/codecs/VorbisComment") +local Pcm = require("@formats/codecs/Pcm") +local RangeDecoder = require("@formats/codecs/RangeCoder/Decoder") local Celt = require("@formats/audio/opus/Celt") local Silk = require("@formats/audio/opus/Silk") local Encode = require("@formats/audio/opus/Encode") @@ -35,7 +37,7 @@ local Opus = { category = "audio", extensions = { "opus" }, mime = { "audio/opus", "audio/ogg" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct", "codecs/RangeCoder/Decoder", "codecs/RangeCoder/Encoder", "codecs/Pcm", "codecs/Resample", "codecs/VorbisComment" }, caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255, rates = { 48000 }, encodeModes = { "celt" } }, } @@ -124,46 +126,40 @@ local function parseHead(b: buffer, off: number, size: number): (Head?, string?) return head, nil end --- OpusTags (RFC 7845 section 5.2): vendor string and a table of lower-cased field names to values (repeated --- fields joined with "; "). -local function parseTags(b: buffer, off: number, size: number): (string, { [string]: string }) - local tags = {} +-- OpusTags (RFC 7845 section 5.2) -> vendor, tags (codecs/VorbisComment: lower-case keys, repeated fields joined +-- with "; "), the raw fields +local function parseTags(b: buffer, off: number, size: number): (string, { [string]: string }, { VorbisComment.Field }) if size < 16 or buffer.readstring(b, off, 8) ~= "OpusTags" then - return "", tags + return "", {}, {} end local p = off + 8 local e = off + size local vlen = buffer.readu32(b, p) p += 4 if p + vlen > e then - return "", tags + return "", {}, {} end local vendor = buffer.readstring(b, p, vlen) p += vlen - if p + 4 > e then - return vendor, tags - end - local n = buffer.readu32(b, p) - p += 4 - for _ = 1, n do - if p + 4 > e then - break - end - local l = buffer.readu32(b, p) + local list = {} + if p + 4 <= e then + local n = buffer.readu32(b, p) p += 4 - if p + l > e then - break - end - local s = buffer.readstring(b, p, l) - p += l - local eq = string.find(s, "=", 1, true) - if eq then - local k = string.lower(string.sub(s, 1, eq - 1)) - local v = string.sub(s, eq + 1) - tags[k] = if tags[k] then tags[k] .. "; " .. v else v + for _ = 1, n do + if p + 4 > e then + break + end + local l = buffer.readu32(b, p) + p += 4 + if p + l > e then + break + end + table.insert(list, buffer.readstring(b, p, l)) + p += l end end - return vendor, tags + local tags, raw = VorbisComment.tags(list) + return vendor, tags, raw end Opus.Decoder = Decoder @@ -213,7 +209,7 @@ function Opus.decode(r: any, opts: OpenOptions?): (Types.Audio?, Err.Err?) a.frames = total end a.tags = dec.tags - a.meta.source = { format = "opus", channels = dec.sourceChannels, preSkip = dec.preSkip, vendor = dec.vendor, mappingFamily = dec.head.mappingFamily, inputSampleRate = dec.head.inputSampleRate } + a.meta.source = { format = "opus", channels = dec.sourceChannels, preSkip = dec.preSkip, vendor = dec.vendor, comments = dec.comments, mappingFamily = dec.head.mappingFamily, inputSampleRate = dec.head.inputSampleRate } return a, nil end @@ -288,6 +284,9 @@ function Stream.read(self: any, maxFrames: number, into: buffer?): (buffer, numb Decoder.writeDownmix(self.pend, self.pendPos * self.sourceChannels, n, self.sourceChannels, self.downmix, gain, out, got * 8) else Decoder.writeF32(self.pend, self.pendPos * ch, n * ch, gain, out, got * ch * 4) + if self.order then + Pcm.reorder(out, got * ch * 4, n, ch, self.order) + end end self.pendPos += n got += n @@ -356,7 +355,7 @@ function Opus.open(r: any, opts: OpenOptions?): (any, Err.Err?) if tp == nil then return nil, Err.new(Err.TRUNCATED, "missing OpusTags") end - local vendor, tags = parseTags(tp.data, tp.offset, tp.size) + local vendor, tags, rawTags = parseTags(tp.data, tp.offset, tp.size) -- granule of the first audio sample: first page granule minus the packets that end on it local startGranule = 0 local sum = 0 @@ -391,6 +390,9 @@ function Opus.open(r: any, opts: OpenOptions?): (any, Err.Err?) head = head, vendor = vendor, tags = tags, + comments = rawTags, + -- mapping family 1 is in Vorbis channel order; the output is WAVE order (codecs/Pcm) + order = if not downmix and head.mappingFamily == 1 and head.channels > 2 then Pcm.WAVE_FROM_VORBIS[head.channels] else nil, sampleRate = SAMPLE_RATE, channels = if downmix then 2 else head.channels, sourceChannels = head.channels, diff --git a/src/Formats/codecs/Pcm/init.luau b/src/Formats/codecs/Pcm/init.luau index 8d60d05..ab98e26 100644 --- a/src/Formats/codecs/Pcm/init.luau +++ b/src/Formats/codecs/Pcm/init.luau @@ -24,6 +24,20 @@ local Convert = require("@formats/codecs/Pcm/Convert") local Pcm = {} Pcm.Convert = Convert +-- Channel order. Decoders return WAVE (WAVEFORMATEXTENSIBLE) order: FL FR C LFE BL BR (SL SR) ..., as FLAC, WAV and +-- AAC store it. Vorbis and Opus (mapping family 1) store the Vorbis order (FL C FR ... LFE last); WAVE_FROM_VORBIS[n][i] +-- is the Vorbis-order channel (1-based) that WAVE-order channel i holds, for n = 1 .. 8 channels. +Pcm.WAVE_FROM_VORBIS = { + { 1 }, + { 1, 2 }, + { 1, 3, 2 }, -- L C R -> L R C + { 1, 2, 3, 4 }, -- FL FR RL RR + { 1, 3, 2, 4, 5 }, -- FL C FR RL RR -> FL FR C RL RR + { 1, 3, 2, 6, 4, 5 }, -- FL C FR RL RR LFE -> FL FR C LFE RL RR + { 1, 3, 2, 7, 6, 4, 5 }, -- FL C FR SL SR RC LFE -> FL FR C LFE RC SL SR + { 1, 3, 2, 8, 6, 7, 4, 5 }, -- FL C FR SL SR RL RR LFE -> FL FR C LFE RL RR SL SR +} + export type Source = { sampleRate: number, channels: number, @@ -211,6 +225,22 @@ function Pcm.encode(src: Source, fmt: string, w: Bytes.Writer): (number?, Err.Er end -- ------------------------------------------------------------------------------------------------ conversions +-- reorder(buf, offset, frames, channels, map): in place, frame by frame, channel i of the result = channel map[i] +-- (1-based) of the input; for converting between channel orders (Pcm.WAVE_FROM_VORBIS) +function Pcm.reorder(buf: buffer, offset: number, frames: number, channels: number, map: { number }) + local tmp = table.create(channels, 0) + local readf32, writef32 = buffer.readf32, buffer.writef32 + for f = 0, frames - 1 do + local p = offset + f * channels * 4 + for c = 1, channels do + tmp[c] = readf32(buf, p + (map[c] - 1) * 4) + end + for c = 1, channels do + writef32(buf, p + (c - 1) * 4, tmp[c]) + end + end +end + -- toInt(x, bits) -> the nearest bits-wide signed integer to x * 2^(bits-1), clipped (NaN -> 0) function Pcm.toInt(x: number, bits: number): number local s = 2 ^ (bits - 1) diff --git a/src/Formats/codecs/RangeCoder/Decoder.luau b/src/Formats/codecs/RangeCoder/Decoder.luau index 23d96ce..2c64ec3 100644 --- a/src/Formats/codecs/RangeCoder/Decoder.luau +++ b/src/Formats/codecs/RangeCoder/Decoder.luau @@ -1,8 +1,9 @@ --!strict --!native --!optimize 2 --- audio/opus/RangeDecoder: Range decoder (RFC 6716 section 4.1, libopus celt/entdec.c). Reads one Opus frame from a `buffer` slice --- [base, base + storage). Raw bits (ec_dec_bits) are read from the end of the slice backwards. +-- codecs/RangeCoder/Decoder: the Opus range decoder (RFC 6716 section 4.1, libopus celt/entdec.c). Reads one Opus +-- frame from a `buffer` slice [base, base + storage). Raw bits (ec_dec_bits) are read from the end of the slice +-- backwards. -- All values stay below 2^32, so plain Luau numbers hold them exactly; floor division is exact below 2^52. local RangeDecoder = {} diff --git a/src/Formats/codecs/RangeCoder/Encoder.luau b/src/Formats/codecs/RangeCoder/Encoder.luau index 13bf3c6..05e9815 100644 --- a/src/Formats/codecs/RangeCoder/Encoder.luau +++ b/src/Formats/codecs/RangeCoder/Encoder.luau @@ -1,8 +1,8 @@ --!strict --!native --!optimize 2 --- audio/opus/RangeEncoder: the range encoder (RFC 6716 section 5.1), a port of libopus celt/entenc.c (BSD: --- licenses/libopus-BSD.txt), the mirror of audio/opus/RangeDecoder. Writes one fixed-size frame: the range-coded +-- codecs/RangeCoder/Encoder: the Opus range encoder (RFC 6716 section 5.1), a port of libopus celt/entenc.c (BSD: +-- licenses/libopus-BSD.txt), the mirror of codecs/RangeCoder/Decoder. Writes one fixed-size frame: the range-coded -- symbols from the front, the raw bits (ec_enc_bits) from the back, zeros between. Values stay below 2^32 as plain -- numbers. Never throws: running out of room sets `error`. local RangeEncoder = {} diff --git a/src/Formats/codecs/RangeCoder/init.luau b/src/Formats/codecs/RangeCoder/init.luau new file mode 100644 index 0000000..6affd3e --- /dev/null +++ b/src/Formats/codecs/RangeCoder/init.luau @@ -0,0 +1,13 @@ +--!strict +-- codecs/RangeCoder: the RFC 6716 range coder (libopus celt/entdec.c + entenc.c, BSD: licenses/libopus-BSD.txt): +-- symbols range-coded from the front of a frame, raw bits from its back. Opus (CELT and SILK) uses it; LZMA, VP8 and +-- CABAC have their own (different) binary coders. Moved here from audio/opus by the cleanup pass (same code). +-- +-- local RD = require("@formats/codecs/RangeCoder/Decoder") -- RD.new(buf, base, size), RD.icdf / bits / uint ... +-- local RE = require("@formats/codecs/RangeCoder/Encoder") -- RE.new(size), RE.icdf / bits / uint, RE.done +local RangeCoder = { + Decoder = require("@formats/codecs/RangeCoder/Decoder"), + Encoder = require("@formats/codecs/RangeCoder/Encoder"), +} + +return RangeCoder diff --git a/src/Formats/codecs/Resample/init.luau b/src/Formats/codecs/Resample/init.luau new file mode 100644 index 0000000..e0bfdfd --- /dev/null +++ b/src/Formats/codecs/Resample/init.luau @@ -0,0 +1,378 @@ +--!strict +--!native +--!optimize 2 +-- codecs/Resample: audio sample-rate conversion by band-limited (Kaiser-windowed sinc) interpolation, streaming or +-- whole-buffer, any channel count, interleaved f32 (the Types.Audio / Decoder layout). Used by the Opus, MP3 and MP2 +-- encoders (their input rates are fixed) and ops/AudioOps.resample. New in formats-luau (the textbook polyphase +-- filter; the kernel is the one the Opus encoder carried). +-- +-- The filter is a polyphase table: exact phases when to / gcd(from, to) <= 4096 (44100 <-> 48000: 160 phases), +-- else 4096 phases with linear interpolation between them. Each phase is normalised to unit DC gain. The cutoff is a +-- fraction (opts.cutoff, default 0.97) of the lower Nyquist frequency; quality picks the taps per side at the cutoff: +-- +-- quality zero crossings per side Kaiser beta stop band +-- "low" 8 6 ~ -60 dB +-- "medium" 16 (default) 8 ~ -80 dB +-- "high" 32 10 ~ -100 dB +-- +-- Output frame j sits at input time j * from / to (no delay: the filter is centred, the input is zero outside its +-- range); a stream of n input frames gives floor(n * to / from + 0.5) output frames. +-- +-- local out, frames = Resample.buffer(samples, frames, channels, 44100, 48000, { quality = "high" }) +-- local rs = Resample.new(44100, 48000, 2) -- nil, message for bad rates +-- local b, n = rs:process(chunk, chunkFrames) -- the output frames this input completes +-- local b2, n2 = rs:flush() -- the rest (the input end padded with zeros) +-- local src2 = Resample.source(pcmSource, 48000) -- a codecs/Pcm Source at the new rate +-- +-- Never throws: bad arguments return nil, message (the api turns them into Err.ARG). +local Resample = {} + +export type Options = { + quality: ("low" | "medium" | "high")?, -- default "medium" + cutoff: number?, -- pass band edge as a fraction of the lower Nyquist frequency, 0.5 .. 1 (default 0.97) +} + +export type Resampler = { + from: number, + to: number, + channels: number, + -- process(src, frames, out?) -> interleaved f32 buffer, output frames (out is reused when big enough) + process: (self: Resampler, src: buffer, frames: number, out: buffer?) -> (buffer, number), + -- flush(out?) -> the remaining output frames; the resampler is finished afterwards + flush: (self: Resampler, out: buffer?) -> (buffer, number), +} + +local QUALITY = { low = { 8, 6 }, medium = { 16, 8 }, high = { 32, 10 } } +local MAX_EXACT = 4096 +local INTERP_PHASES = 4096 + +local floor, sin, pi, sqrt, max, min = math.floor, math.sin, math.pi, math.sqrt, math.max, math.min +local readf32, writef32 = buffer.readf32, buffer.writef32 + +local function besselI0(x: number): number + local sum, term = 1, 1 + for k = 1, 80 do + term *= (x / (2 * k)) ^ 2 + sum += term + if term < sum * 1e-16 then + break + end + end + return sum +end + +local function gcd(a: number, b: number): number + while b ~= 0 do + a, b = b, a % b + end + return a +end + +type Filter = { + taps: number, -- per phase + half: number, -- taps on the left of the centre (taps = 2 * half) + phases: number, + exact: boolean, + h: { number }, -- phase p, tap k: h[p * taps + k + 1] +} + +-- filter(ratio, phases, exact, opts) -> the polyphase table. Phase p is the kernel for an output at fraction +-- p / phases past an input sample; tap k multiplies input (floor(t) - half + 1 + k). +local function makeFilter(ratio: number, phases: number, exact: boolean, zc: number, beta: number, cut: number): Filter + local cutoff = cut * min(1, ratio) + local width = zc / cutoff -- in input samples, each side + local half = math.ceil(width) + local taps = 2 * half + local i0b = besselI0(beta) + local n = if exact then phases else phases + 1 + local h = table.create(n * taps, 0) + for p = 0, n - 1 do + local frac = p / phases + local sum = 0 + local base = p * taps + for k = 0, taps - 1 do + local d = (k - half + 1) - frac -- input position minus output position + local r = d / width + local v = 0 + if r > -1 and r < 1 then + local x = d * cutoff + local s = if x == 0 then 1 else sin(pi * x) / (pi * x) + v = s * besselI0(beta * sqrt(1 - r * r)) / i0b + end + h[base + k + 1] = v + sum += v + end + if sum ~= 0 then + for k = 1, taps do + h[base + k] /= sum + end + end + end + return { taps = taps, half = half, phases = phases, exact = exact, h = h } +end + +-- the stream state: the input history as an interleaved Lua array; hist[1] is frame `base` (absolute) +type State = { + from: number, + to: number, + channels: number, + f: Filter, + step: number, -- M = from / g: the input advance per output frame, in units of 1 / L + L: number, -- to / g + hist: { number }, + histFrames: number, + base: number, -- the absolute input frame of hist[1] + inFrames: number, -- absolute input frames received + outPos: number, -- next output frame (absolute) + done: boolean, + process: any, + flush: any, +} + +-- run(st, lastInput) -> buffer, frames: every output frame whose taps end at or before lastInput (absolute, exclusive) +local function run(st: State, limitOut: number, out: buffer?): (buffer, number) + local f = st.f + local taps, half, h = f.taps, f.half, f.h + local ch = st.channels + local hist, base, histFrames = st.hist, st.base, st.histFrames + local L, M = st.L, st.step + local j0 = st.outPos + -- outputs j with floor(j * M / L) - half + taps <= available frames (zero beyond the end after flush) + local avail = base + histFrames + local jmax = limitOut + if not st.done then + -- the last tap must be buffered: floor(j * M / L) + half <= avail - 1, i.e. j * M < (avail - half) * L + local lim = floor(((avail - half) * L - 1) / M) + if lim + 1 < jmax then + jmax = lim + 1 + end + end + local n = jmax - j0 + if n <= 0 then + return out or buffer.create(0), 0 + end + local bytes = n * ch * 4 + local b = if out and buffer.len(out) >= bytes then out else buffer.create(bytes) + local exact = f.exact + local phases = f.phases + local o = 0 + for j = j0, jmax - 1 do + local num = j * M + local ip = num // L -- floor(t) + local first = ip - half + 1 -- absolute input frame of tap 0 + local rel = first - base -- frame index in hist + local kLo = if rel < 0 then -rel else 0 + local kHi = taps - 1 + if rel + kHi >= histFrames then + kHi = histFrames - 1 - rel + end + if exact then + local hb = (num - ip * L) * taps + 1 -- phase * taps + 1 + for c = 0, ch - 1 do + local acc = 0 + local hi = (rel + kLo) * ch + c + 1 + for k = kLo, kHi do + acc += hist[hi] * h[hb + k] + hi += ch + end + writef32(b, o, acc) + o += 4 + end + else + local fp = (num - ip * L) / L * phases + local p = floor(fp) + local a = fp - p + local hb = p * taps + 1 + local hb2 = hb + taps + for c = 0, ch - 1 do + local acc, acc2 = 0, 0 + local hi = (rel + kLo) * ch + c + 1 + for k = kLo, kHi do + local x = hist[hi] + acc += x * h[hb + k] + acc2 += x * h[hb2 + k] + hi += ch + end + writef32(b, o, acc + (acc2 - acc) * a) + o += 4 + end + end + end + st.outPos = jmax + -- drop history no future output needs (keep from the next output's first tap) + local keepFrom = (jmax * M) // L - half + 1 + local drop = keepFrom - base + if drop > 0 then + if drop >= histFrames then + st.hist = {} + st.histFrames = 0 + st.base = base + histFrames + else + local nh = table.create((histFrames - drop) * ch) + table.move(hist, drop * ch + 1, histFrames * ch, 1, nh) + st.hist = nh + st.histFrames = histFrames - drop + st.base = base + drop + end + end + return b, n +end + +local function process(self: State, src: buffer, frames: number, out: buffer?): (buffer, number) + if self.done or type(src) ~= "buffer" or type(frames) ~= "number" or frames <= 0 then + return out or buffer.create(0), 0 + end + local ch = self.channels + frames = min(floor(frames), buffer.len(src) // (ch * 4)) + local hist = self.hist + local p = self.histFrames * ch + for i = 0, frames * ch - 1 do + hist[p + i + 1] = readf32(src, i * 4) + end + self.histFrames += frames + self.inFrames += frames + return run(self, math.huge, out) +end + +local function flush(self: State, out: buffer?): (buffer, number) + if self.done then + return out or buffer.create(0), 0 + end + self.done = true + local total = floor(self.inFrames * self.to / self.from + 0.5) + return run(self, total, out) +end + +-- new(from, to, channels, opts?) -> Resampler | nil, message +function Resample.new(from: number, to: number, channels: number, opts: Options?): (Resampler?, string?) + if type(from) ~= "number" or type(to) ~= "number" or from ~= from or to ~= to or from <= 0 or to <= 0 or from > 2 ^ 24 or to > 2 ^ 24 then + return nil, "bad sample rates" + end + if type(channels) ~= "number" or channels < 1 or channels > 256 or channels ~= floor(channels) then + return nil, "bad channel count" + end + local q = QUALITY[(opts and opts.quality) or "medium"] + if not q then + return nil, "quality must be low, medium or high" + end + local cut = (opts and opts.cutoff) or 0.97 + if type(cut) ~= "number" or not (cut >= 0.5 and cut <= 1) then + return nil, "cutoff must be 0.5 .. 1" + end + -- positions are exact integers: output j sits at input j * M / L (non-integer rates: to 1 / 1000 Hz) + local fi, ti = from, to + if from ~= floor(from) or to ~= floor(to) then + fi, ti = floor(from * 1000 + 0.5), floor(to * 1000 + 0.5) + end + local g = gcd(fi, ti) + local L, M = ti // g, fi // g + local exact = L <= MAX_EXACT + local phases = if exact then L else INTERP_PHASES + local st: State = { + from = from, + to = to, + channels = channels, + -- the same rate: a pass-through (tap 0 is the input frame itself) + f = if L == 1 and M == 1 then { taps = 2, half = 1, phases = 1, exact = true, h = { 1, 0 } } else makeFilter(to / from, phases, exact, q[1], q[2], cut), + step = M, + L = L, + hist = {}, + histFrames = 0, + base = 0, + inFrames = 0, + outPos = 0, + done = false, + process = process, + flush = flush, + } + return st :: any, nil +end + +-- buffer(src, frames, channels, from, to, opts?) -> interleaved f32 buffer, frames | nil, message +function Resample.buffer(src: buffer, frames: number, channels: number, from: number, to: number, opts: Options?): (buffer?, number | string) + local rs, err = Resample.new(from, to, channels, opts) + if not rs then + return nil, err :: string + end + if type(src) ~= "buffer" or type(frames) ~= "number" or frames < 0 or buffer.len(src) < frames * channels * 4 then + return nil, "the buffer is shorter than frames * channels * 4" + end + local total = floor(frames * to / from + 0.5) + local out = buffer.create(total * channels * 4) + local got = 0 + local chunk = 65536 + local tmp: buffer? = nil + local pos = 0 + while pos < frames do + local n = min(chunk, frames - pos) + local part = buffer.create(n * channels * 4) + buffer.copy(part, 0, src, pos * channels * 4, n * channels * 4) + local b, m = rs:process(part, n, tmp) + tmp = b + if m > 0 then + buffer.copy(out, got * channels * 4, b, 0, m * channels * 4) + got += m + end + pos += n + end + local b, m = rs:flush(tmp) + if m > 0 then + buffer.copy(out, got * channels * 4, b, 0, m * channels * 4) + got += m + end + return out, got +end + +-- source(src, to, opts?) -> a pull source ({ sampleRate, channels, frames, tags, read, err }, the codecs/Pcm Source +-- shape) reading src (any such source: Pcm.source(audioOrDecoder)) at the rate `to` | nil, message +function Resample.source(src: any, to: number, opts: Options?): (any, string?) + if type(src) ~= "table" or type(src.read) ~= "function" then + return nil, "needs a source" + end + local rs, err = Resample.new(src.sampleRate, to, src.channels, opts) + if not rs then + return nil, err + end + local ch = src.channels + local pending = buffer.create(0) -- produced but not yet returned + local pendingFrames, pendingPos = 0, 0 + local ended = false + local out = { + sampleRate = to, + channels = ch, + frames = if src.frames > 0 then floor(src.frames * to / src.sampleRate + 0.5) else 0, + tags = src.tags, + err = nil :: any, + } + local inTmp: buffer? = nil + function out.read(self: any, n: number, dst: buffer?): (buffer, number) + n = floor(n) + while pendingFrames - pendingPos <= 0 and not ended do + local b, m = src:read(math.max(1024, floor(n * src.sampleRate / to) + 64), inTmp) + inTmp = b + local r: buffer, k: number + if m <= 0 then + ended = true + self.err = src.err + r, k = rs:flush() + else + r, k = rs:process(b, m) + end + if k > 0 then + pending, pendingFrames, pendingPos = r, k, 0 + end + end + local k = min(n, pendingFrames - pendingPos) + if k <= 0 then + return dst or buffer.create(0), 0 + end + local bytes = k * ch * 4 + local b = if dst and buffer.len(dst) >= bytes then dst else buffer.create(bytes) + buffer.copy(b, 0, pending, pendingPos * ch * 4, bytes) + pendingPos += k + return b, k + end + return out, nil +end + +return Resample diff --git a/src/Formats/codecs/VorbisComment.luau b/src/Formats/codecs/VorbisComment.luau new file mode 100644 index 0000000..118be05 --- /dev/null +++ b/src/Formats/codecs/VorbisComment.luau @@ -0,0 +1,62 @@ +--!strict +-- codecs/VorbisComment: Vorbis comment fields ("KEY=value", the tag block of Vorbis, Opus and FLAC) <-> Types.Tags. +-- Tag keys are lower case everywhere in formats-luau (the same names ID3 / MP4 / RIFF INFO map to): title, artist, +-- album, albumartist, date, genre, track, tracktotal, disc, disctotal, comment, composer, ...; TRACKNUMBER becomes +-- track, DISCNUMBER disc, DESCRIPTION comment, other fields their lower-cased name. Repeated fields are joined with +-- "; " in tags; the raw fields stay available (decoders put them in meta.source.comments). Shared so the three +-- formats read and write tags the same way. Never throws. +-- +-- local tags, raw = VorbisComment.tags({ "TITLE=x", "TRACKNUMBER=3" }) -- { title = "x", track = "3" }, raw list +-- local fields = VorbisComment.fields(tags) -- sorted { "TITLE=x", "TRACKNUMBER=3" } +local VorbisComment = {} + +export type Field = { key: string, value: string } -- key as written (upper-cased), value + +local TO_TAG: { [string]: string } = { tracknumber = "track", discnumber = "disc", description = "comment" } +local TO_FIELD: { [string]: string } = { track = "TRACKNUMBER", disc = "DISCNUMBER" } + +-- tagKey(fieldName) -> the Types.Tags key +function VorbisComment.tagKey(name: string): string + local k = string.lower(name) + return TO_TAG[k] or k +end + +-- fieldName(tagKey) -> the Vorbis comment field name +function VorbisComment.fieldName(key: string): string + return TO_FIELD[key] or string.upper(key) +end + +-- tags(list of "KEY=value") -> Types.Tags, { Field } (entries without "=" are skipped) +function VorbisComment.tags(comments: { string }): ({ [string]: string }, { Field }) + local tags: { [string]: string } = {} + local raw: { Field } = {} + for _, s in comments do + local eq = string.find(s, "=", 1, true) + if eq then + local name, v = string.sub(s, 1, eq - 1), string.sub(s, eq + 1) + table.insert(raw, { key = string.upper(name), value = v }) + local k = VorbisComment.tagKey(name) + local old = tags[k] + tags[k] = if old then old .. "; " .. v else v + end + end + return tags, raw +end + +-- fields(tags) -> "KEY=value" strings in key order (string keys and values only) +function VorbisComment.fields(tags: { [any]: any }): { string } + local keys = {} + for k, v in tags do + if type(k) == "string" and type(v) == "string" then + table.insert(keys, k) + end + end + table.sort(keys) + local out = table.create(#keys) + for i, k in keys do + out[i] = VorbisComment.fieldName(k) .. "=" .. tags[k] + end + return out +end + +return VorbisComment diff --git a/tests/audio/mp3_encode.luau b/tests/audio/mp3_encode.luau index f710cc9..9041576 100644 --- a/tests/audio/mp3_encode.luau +++ b/tests/audio/mp3_encode.luau @@ -121,6 +121,44 @@ do t:check(empty and buffer.len(empty) > 0, "empty input: one flush frame") end +-- other input rates are resampled (codecs/Resample) to the next rate up: 44 kHz -> 44.1 kHz, 46 kHz -> 48 kHz, +-- layer II 8 kHz -> 16 kHz, opts.sampleRate +do + local function tone(rate: number, f: number): any + local n = rate + local a = Types.Audio.new(rate, 1, n) + for i = 0, n - 1 do + buffer.writef32(a.samples, i * 4, 0.5 * math.sin(2 * math.pi * f * i / rate)) + end + return a + end + -- the share of the decoded energy at f (a DFT bin over the middle half) + local function purity(d: any, f: number): number + local pcm, n = d:read(d.frames) + local re, im, e = 0, 0, 0 + local lo, hi = n // 4, 3 * n // 4 + for i = lo, hi - 1 do + local x = buffer.readf32(pcm, i * d.channels * 4) + re += x * math.cos(2 * math.pi * f * i / d.sampleRate) + im += x * math.sin(2 * math.pi * f * i / d.sampleRate) + e += x * x + end + return 2 * (re * re + im * im) / (hi - lo) / math.max(e, 1e-30) + end + for _, c in { { 44000, nil, nil, 44100 }, { 46000, nil, nil, 48000 }, { 8000, 2, nil, 16000 }, { 44100, 3, 22050, 22050 }, { 11000, 3, nil, 11025 } } do + local f, err = Mp3.encode(tone(c[1], 600), { layer = c[2], sampleRate = c[3], bitrate = if c[4] < 32000 then 64 else 128 }) + t:check(f, c[1] .. " Hz input: " .. tostring(err)) + if f then + local d = Mp3.open(Bytes.reader(f)) :: any + t:eq(d.sampleRate, c[4], c[1] .. " Hz input: written at " .. c[4]) + -- (no LAME gapless header: the encoder delay and the last frame's padding stay) + t:check(d.frames >= c[4] and d.frames <= c[4] + 3 * 1152, c[1] .. " Hz input: length " .. d.frames) + local p = purity(d, 600) + t:check(p > 0.98, string.format("%d Hz input: tone purity %.4f", c[1], p)) + end + end +end + -- errors do local function code(v: any, o: any): string? @@ -132,8 +170,8 @@ do t:eq(code(a, { layer = 1 }), Err.ARG, "layer I") t:eq(code(a, { bitrate = 100 }), Err.ARG, "100 kbps") t:eq(code(a, { mode = "dual" }), Err.ARG, "dual mode") - t:eq(code(Types.Audio.new(44000, 2, 10), nil), Err.ARG, "44 kHz") - t:eq(code(Types.Audio.new(8000, 2, 10), { layer = 2 }), Err.ARG, "layer II at 8 kHz") + t:eq(code(a, { sampleRate = 44000 }), Err.ARG, "opts.sampleRate 44 kHz") + t:eq(code(a, { layer = 2, sampleRate = 8000 }), Err.ARG, "layer II at 8 kHz") t:eq(code(Types.Audio.new(44100, 3, 10), nil), Err.ARG, "3 channels") t:eq(code(a, { layer = 2, bitrate = 32 }), Err.ARG, "layer II stereo at 32 kbps") t:eq(code(Types.Audio.new(44100, 1, 10), { layer = 2, bitrate = 320 }), Err.ARG, "layer II mono at 320 kbps") diff --git a/tests/audio/opus.luau b/tests/audio/opus.luau index 8403251..fc86504 100644 --- a/tests/audio/opus.luau +++ b/tests/audio/opus.luau @@ -9,10 +9,11 @@ local Opus = require("@formats/audio/opus") local Packet = require("@formats/audio/opus/Packet") local Celt = require("@formats/audio/opus/Celt") local Silk = require("@formats/audio/opus/Silk") -local RD = require("@formats/audio/opus/RangeDecoder") +local RD = require("@formats/codecs/RangeCoder/Decoder") local Decoder = require("@formats/audio/opus/Decoder") local Ogg = require("@formats/containers/Ogg") local Bytes = require("@formats/core/Bytes") +local Pcm = require("@formats/codecs/Pcm") local Err = require("@formats/core/Err") local t = T.suite("opus") @@ -48,6 +49,14 @@ for _, f in do FX[f.name] = { data = buffer.fromstring(f.data), ref = buffer.fromstring(f.ref), raw = f.data } end +-- opusdec's raw output keeps the Vorbis channel order of mapping family 1; the decoder returns WAVE order +do + local fx = FX.surround51 + fx.vorbisRef = fx.ref + fx.ref = buffer.create(buffer.len(fx.vorbisRef)) + buffer.copy(fx.ref, 0, fx.vorbisRef) + Pcm.reorder(fx.ref, 0, buffer.len(fx.ref) // 24, 6, Pcm.WAVE_FROM_VORBIS[6]) +end -- SNR in dB of f32 samples against a reference over n samples; returns snr, max abs error local function snr(out: buffer, ref: buffer, n: number, outOff: number?, refOff: number?): (number, number) @@ -183,7 +192,7 @@ do for i = 0, n - 1 do local l, r = 0, 0 for c = 0, 5 do - local v = buffer.readf32(fx.ref, (i * 6 + c) * 4) + local v = buffer.readf32(fx.vorbisRef, (i * 6 + c) * 4) l += v * m[c * 2 + 1] r += v * m[c * 2 + 2] end diff --git a/tests/codecs/resample.luau b/tests/codecs/resample.luau new file mode 100644 index 0000000..41a62b4 --- /dev/null +++ b/tests/codecs/resample.luau @@ -0,0 +1,133 @@ +-- codecs/Resample tests: sines through common rate pairs (44100 <-> 48000, 8000 -> 48000, 48000 -> 22050, an inexact +-- ratio) against the analytic signal, alias rejection when downsampling, output lengths, streaming in odd chunks = +-- the whole-buffer result, multichannel, a Pcm source wrapper, bad arguments, and a no-throw pass over garbage. +local T = require("@tests/T") +local Resample = require("@formats/codecs/Resample") +local Pcm = require("@formats/codecs/Pcm") +local Types = require("@formats/Types") + +local t = T.suite("resample") + +local function sine(frames: number, ch: number, rate: number, freqs: { number }): buffer + local b = buffer.create(frames * ch * 4) + for i = 0, frames - 1 do + for c = 0, ch - 1 do + local f = freqs[c + 1] or freqs[1] + buffer.writef32(b, (i * ch + c) * 4, 0.5 * math.sin(2 * math.pi * f * i / rate)) + end + end + return b +end + +-- snr(out, frames, ch, rate, freqs, skip) -> dB of the analytic sine against the error, away from the edges +local function snr(b: buffer, frames: number, ch: number, rate: number, freqs: { number }, skip: number): number + local sig, err = 0, 0 + for i = skip, frames - 1 - skip do + for c = 0, ch - 1 do + local f = freqs[c + 1] or freqs[1] + local want = 0.5 * math.sin(2 * math.pi * f * i / rate) + local got = buffer.readf32(b, (i * ch + c) * 4) + sig += want * want + err += (got - want) ^ 2 + end + end + return 10 * math.log10(sig / math.max(err, 1e-30)) +end + +local function rms(b: buffer, frames: number, skip: number): number + local s = 0 + for i = skip, frames - 1 - skip do + s += buffer.readf32(b, i * 4) ^ 2 + end + return math.sqrt(s / math.max(1, frames - 2 * skip)) +end + +-- 1. accuracy on in-band sines +for _, c in { { 44100, 48000, 1000, "medium", 80 }, { 48000, 44100, 3000, "medium", 80 }, { 8000, 48000, 440, "medium", 80 }, { 48000, 22050, 5000, "high", 90 }, { 44100, 48000, 1000, "low", 55 }, { 44100, 47999, 1000, "medium", 75 } } do + local from, to, f, q, want = c[1], c[2], c[3], c[4], c[5] + local n = from // 4 + local out, frames = Resample.buffer(sine(n, 1, from, { f }), n, 1, from, to, { quality = q }) + t:check(out ~= nil, "resample " .. from .. " -> " .. to) + if out then + local fr = frames :: number + t:eq(fr, math.floor(n * to / from + 0.5), from .. " -> " .. to .. ": length") + local db = snr(out, fr, 1, to, { f }, to // 50) + t:note("%d -> %d (%s), %d Hz: %.1f dB", from, to, q, f, db) + t:check(db > want, string.format("%d -> %d %s: %.1f dB > %d", from, to, q, db, want)) + end +end + +-- 2. a tone above the new Nyquist is removed when downsampling (48 kHz -> 16 kHz, 10 kHz tone) +do + local n = 12000 + local out, frames = Resample.buffer(sine(n, 1, 48000, { 10000 }), n, 1, 48000, 16000) + local level = rms(out :: buffer, frames :: number, 200) / (0.5 / math.sqrt(2)) + t:check(level < 1e-3, string.format("alias rejection: %.2e", level)) +end + +-- 3. streaming in odd chunk sizes gives the whole-buffer result; stereo channels stay apart +do + local n, ch = 10007, 2 + local src = sine(n, ch, 44100, { 700, 1900 }) + local whole, wf = Resample.buffer(src, n, ch, 44100, 48000) + local rs = Resample.new(44100, 48000, ch) :: Resample.Resampler + local got = buffer.create((wf :: number) * ch * 4) + local gf = 0 + local pos = 0 + local rand = T.rng(7) + while pos < n do + local k = math.min(n - pos, 1 + rand(3000)) + local part = buffer.create(k * ch * 4) + buffer.copy(part, 0, src, pos * ch * 4, k * ch * 4) + local b, m = rs:process(part, k) + buffer.copy(got, gf * ch * 4, b, 0, m * ch * 4) + gf += m + pos += k + end + local b, m = rs:flush() + buffer.copy(got, gf * ch * 4, b, 0, m * ch * 4) + gf += m + t:eq(gf, wf, "streamed length") + t:check(buffer.tostring(got) == buffer.tostring(whole :: buffer), "streamed = whole") + t:check(snr(got, gf, ch, 48000, { 700, 1900 }, 500) > 80, "stereo accuracy") +end + +-- 4. a codecs/Pcm source at a new rate +do + local a = Types.Audio.new(22050, 1, 5000) + a.samples = sine(5000, 1, 22050, { 500 }) + local src = Resample.source(Pcm.source(a), 32000) + t:check(src and src.frames == math.floor(5000 * 32000 / 22050 + 0.5), "source frames") + local col = Pcm.collect(src) + t:check(col and col.sampleRate == 32000 and col.frames == src.frames, "source collects every frame") + t:check(col and snr(col.samples, col.frames, 1, 32000, { 500 }, 300) > 80, "source accuracy") +end + +-- 5. identity, empty input, bad arguments +do + local src = sine(1000, 1, 48000, { 1000 }) + local out = Resample.buffer(src, 1000, 1, 48000, 48000) + t:check(out and snr(out, 1000, 1, 48000, { 1000 }, 50) > 100, "identity") + local e, ef = Resample.buffer(buffer.create(0), 0, 2, 44100, 48000) + t:check(e and ef == 0, "empty input") + t:check(Resample.new(0, 48000, 1) == nil, "zero rate") + t:check(Resample.new(44100, 48000, 0) == nil, "zero channels") + t:check(Resample.new(44100, 48000, 1, { quality = "insane" :: any }) == nil, "bad quality") + t:check(Resample.buffer(buffer.create(4), 10, 1, 44100, 48000) == nil, "short buffer") +end + +-- 6. no throw on garbage (NaN / Inf samples, odd lengths, chunk sizes) +local samples = {} +for i = 1, 4 do + table.insert(samples, buffer.tostring(sine(100 * i, 1, 8000, { 300 }))) +end +t:fuzz("resample", function(b: buffer) + local rs = Resample.new(11025, 44100, 2, { quality = "low" }) + if not rs then + return nil + end + local _, n = rs:process(b, buffer.len(b) // 8) + local _, m = rs:flush() + return n + m +end, samples) +t:done() From 6a8a8abce252d700895b6035d59cb29a5a2393f8 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 10:52:04 -0500 Subject: [PATCH 05/22] ws-cleanup-types: codecs: type table.create results, string-keyed tables and multi-assigned locals --- src/Formats/codecs/Aac/Decode.luau | 4 ++-- src/Formats/codecs/Alac/Decode.luau | 4 ++-- src/Formats/codecs/Blend.luau | 6 +++--- src/Formats/codecs/Cff/init.luau | 2 +- src/Formats/codecs/Dct/init.luau | 4 ++-- src/Formats/codecs/Deflate/Inflate.luau | 8 ++++---- src/Formats/codecs/Jpeg/Decode.luau | 12 ++++++------ src/Formats/codecs/Jpeg/Encode.luau | 4 ++-- src/Formats/codecs/MeshFlatten.luau | 8 ++++---- src/Formats/codecs/Quantize/init.luau | 12 ++++++------ src/Formats/codecs/Raster.luau | 6 +++--- src/Formats/codecs/SoundFont/Parse.luau | 6 +++--- src/Formats/codecs/TrueType/Glyf.luau | 18 +++++++++--------- src/Formats/codecs/TrueType/init.luau | 2 +- src/Formats/codecs/Video/init.luau | 18 +++++++++--------- src/Formats/codecs/Vp8L/Decode.luau | 4 ++-- src/Formats/codecs/Xml/init.luau | 2 +- src/Formats/codecs/Yuv.luau | 2 +- src/Formats/codecs/Zstd/Xxh64.luau | 8 ++++---- src/Formats/containers/IsoBmff/Demux.luau | 4 ++-- src/Formats/containers/Zip/init.luau | 2 +- src/Formats/ops/ImageOps/Kernels.luau | 10 +++++----- 22 files changed, 73 insertions(+), 73 deletions(-) diff --git a/src/Formats/codecs/Aac/Decode.luau b/src/Formats/codecs/Aac/Decode.luau index ce4a88b..48ec969 100644 --- a/src/Formats/codecs/Aac/Decode.luau +++ b/src/Formats/codecs/Aac/Decode.luau @@ -132,7 +132,7 @@ export type Channel = { bandType: { number }, -- [g * maxSfb + sfb + 1] sf: { number }, -- tns - tnsFilters: { { number } }, -- per window: { length, order, direction, coefs ... } flattened per filter + tnsFilters: { { { number } } }, -- per window: { length, order, direction, coefs ... } flattened per filter } export type State = { @@ -447,7 +447,7 @@ local function spectralData(st: State, c: Channel, pulses: { number }?): string? return "bad spectral code" end -- unpack the symbol into dim values (first value most significant) - local vals1, vals2, vals3, vals4 + local vals1: number, vals2: number, vals3: number, vals4: number if dim == 4 then vals4 = sym % mod - off sym = (sym - (sym % mod)) / mod diff --git a/src/Formats/codecs/Alac/Decode.luau b/src/Formats/codecs/Alac/Decode.luau index 932d7e7..4b0a71c 100644 --- a/src/Formats/codecs/Alac/Decode.luau +++ b/src/Formats/codecs/Alac/Decode.luau @@ -267,8 +267,8 @@ function Decode.frame(st: State, buf: buffer, off: number, len: number): (number local x = bitsAt(b, pos, 8) local y = bitsAt(b, pos + 8, 8) pos += 16 - mode[c], denShift[c] = rshift(x, 4), band(x, 15) - pbFactor[c], order[c] = rshift(y, 5), band(y, 31) + mode[c], denShift[c] = rshift(x, 4), band(x, 15) :: number + pbFactor[c], order[c] = rshift(y, 5), band(y, 31) :: number if pos + order[c] * 16 > limit then return nil, "frame runs past the end" end diff --git a/src/Formats/codecs/Blend.luau b/src/Formats/codecs/Blend.luau index a3db2a9..d8b2f6a 100644 --- a/src/Formats/codecs/Blend.luau +++ b/src/Formats/codecs/Blend.luau @@ -182,11 +182,11 @@ local function composite(dst: buffer, dw: number, dh: number, src: buffer, sw: n local mbuf: buffer? = nil local mx0, my0, mw, mh, mdef = 0, 0, 0, 0, 1 if type(mask) == "table" and type(mask.pixels) == "buffer" and type(mask.width) == "number" and type(mask.height) == "number" then - mw, mh = floor(mask.width), floor(mask.height) + mw, mh = floor(mask.width), floor(mask.height) :: number if mw > 0 and mh > 0 and blen(mask.pixels) >= mw * mh then mbuf = mask.pixels end - mx0, my0 = floor(tonumber(mask.x) or 0), floor(tonumber(mask.y) or 0) + mx0, my0 = floor(tonumber(mask.x) or 0), floor(tonumber(mask.y) or 0) :: number mdef = (tonumber(mask.default) or 255) / 255 elseif type(mask) == "table" then mdef = (tonumber(mask.default) or 255) / 255 @@ -224,7 +224,7 @@ local function composite(dst: buffer, dw: number, dh: number, src: buffer, sw: n local br, bg, bb = readu8(dst, do_) / 255, readu8(dst, do_ + 1) / 255, readu8(dst, do_ + 2) / 255 local mr, mg, mb = sr, sg, sb if m >= 2 and m ~= 6 and m ~= 11 and m < 23 then - mr, mg, mb = sep(m, br, sr), sep(m, bg, sg), sep(m, bb, sb) + mr, mg, mb = sep(m, br, sr), sep(m, bg, sg), sep(m, bb, sb) :: number elseif m == 6 then if lum(sr, sg, sb) >= lum(br, bg, bb) then mr, mg, mb = br, bg, bb diff --git a/src/Formats/codecs/Cff/init.luau b/src/Formats/codecs/Cff/init.luau index bdec1dc..48d855a 100644 --- a/src/Formats/codecs/Cff/init.luau +++ b/src/Formats/codecs/Cff/init.luau @@ -297,7 +297,7 @@ function Cff.outline(f: Font, g: number): ({ any }?, string?) local cmds: { any } = {} local s: { number } = table.create(48, 0) -- operand stack, 1-based; sp = count local sp = 0 - local trans: { number } = table.create(32, 0) + local trans = table.create(32, 0) :: { number } local x, y = 0, 0 local open = false local maskbits = 0 diff --git a/src/Formats/codecs/Dct/init.luau b/src/Formats/codecs/Dct/init.luau index c46923c..cb643bb 100644 --- a/src/Formats/codecs/Dct/init.luau +++ b/src/Formats/codecs/Dct/init.luau @@ -296,8 +296,8 @@ function Dct.fdctQuantize(src: buffer, stride: number, x: number, y: number, w: local d0: number, d1: number, d2: number, d3: number, d4: number, d5: number, d6: number, d7: number if x + 7 <= lastX then local p = row + x - d0, d1, d2, d3 = readu8(src, p), readu8(src, p + 1), readu8(src, p + 2), readu8(src, p + 3) - d4, d5, d6, d7 = readu8(src, p + 4), readu8(src, p + 5), readu8(src, p + 6), readu8(src, p + 7) + d0, d1, d2, d3 = readu8(src, p), readu8(src, p + 1), readu8(src, p + 2), readu8(src, p + 3) :: number + d4, d5, d6, d7 = readu8(src, p + 4), readu8(src, p + 5), readu8(src, p + 6), readu8(src, p + 7) :: number else d0 = readu8(src, row + math.min(x, lastX)) d1 = readu8(src, row + math.min(x + 1, lastX)) diff --git a/src/Formats/codecs/Deflate/Inflate.luau b/src/Formats/codecs/Deflate/Inflate.luau index 87f3e5f..ab9a237 100644 --- a/src/Formats/codecs/Deflate/Inflate.luau +++ b/src/Formats/codecs/Deflate/Inflate.luau @@ -38,7 +38,7 @@ local CLCAP = Huffman.capacity(19, CLBITS, 7) -- fixed Huffman tables local FLIT, FDIST = bcreate(LITCAP * 4), bcreate(DISTCAP * 4) -local FLITS, FDISTS +local FLITS: number, FDISTS: number do local l = bcreate(288) bfill(l, 0, 8, 144) @@ -69,7 +69,7 @@ function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, ex local op = 0 local pos = start local bitbuf, bitcnt, over = 0, 0, 0 - local lt, dt = bcreate(LITCAP * 4), bcreate(DISTCAP * 4) + local lt, dt = bcreate(LITCAP * 4), bcreate(DISTCAP * 4) :: buffer local clt = bcreate(CLCAP * 4) local lens = bcreate(320) local final = 0 @@ -132,13 +132,13 @@ function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, ex pos += n continue end - local lsub, dsub + local lsub: number, dsub: number if btype == 1 then lt, dt = FLIT, FDIST lsub, dsub = FLITS, FDISTS elseif btype == 2 then if lt == FLIT then - lt, dt = bcreate(LITCAP * 4), bcreate(DISTCAP * 4) + lt, dt = bcreate(LITCAP * 4), bcreate(DISTCAP * 4) :: buffer end local hlit = band(bitbuf, 31) + 257 local hdist = band(rshift(bitbuf, 5), 31) + 1 diff --git a/src/Formats/codecs/Jpeg/Decode.luau b/src/Formats/codecs/Jpeg/Decode.luau index 6cae5ff..833e66f 100644 --- a/src/Formats/codecs/Jpeg/Decode.luau +++ b/src/Formats/codecs/Jpeg/Decode.luau @@ -146,12 +146,12 @@ local function parseSof(b: buffer, p: number, e: number, m: number): (Frame?, st if e - p < 6 + nf * 3 then return nil, "corrupt", "short SOF" end - local comps = {} + local comps: { Comp } = {} local hmax, vmax = 1, 1 for i = 0, nf - 1 do local q = p + 6 + i * 3 local hv = readu8(b, q + 1) - local h, v, tq = rshift(hv, 4), band(hv, 15), readu8(b, q + 2) + local h, v, tq = rshift(hv, 4), band(hv, 15), readu8(b, q + 2) :: number if h < 1 or h > 4 or v < 1 or v > 4 then return nil, "corrupt", "bad sampling factors " .. h .. "x" .. v end @@ -164,7 +164,7 @@ local function parseSof(b: buffer, p: number, e: number, m: number): (Frame?, st return nil, "corrupt", "duplicate component id " .. id end end - hmax, vmax = math.max(hmax, h), math.max(vmax, v) + hmax, vmax = math.max(hmax, h), math.max(vmax, v) :: number table.insert(comps, { id = id, h = h, v = v, tq = tq, bpl = 0, bpc = 0, bw = 0, bh = 0, dcTbl = 0, acTbl = 0, pred = 0, ctx = 0 } :: Comp) end local mcusX = math.ceil(width / (8 * hmax)) @@ -186,7 +186,7 @@ local function parseSof(b: buffer, p: number, e: number, m: number): (Frame?, st vmax = vmax, mcusX = mcusX, mcusY = mcusY, - } + }, nil, nil end local function colorSpaceOf(frame: Frame, adobe: number?, jfif: boolean): string @@ -243,7 +243,7 @@ function Decode.parse(b: buffer, base: number, n: number, opts: any, headerOnly: if scale ~= 1 and scale ~= 2 and scale ~= 4 and scale ~= 8 then return nil, "arg", "scale must be 1, 2, 4 or 8" end - local maxPixels = (opts and opts.maxPixels) or 2 ^ 26 + local maxPixels: number = (opts and opts.maxPixels) or 2 ^ 26 local quant: { [number]: buffer } = {} local dcT: { [number]: buffer } = {} local acT: { [number]: buffer } = {} @@ -445,7 +445,7 @@ function Decode.parse(b: buffer, base: number, n: number, opts: any, headerOnly: if ns < 1 or ns > 4 or e - p < 4 + ns * 2 then return nil, "corrupt", "bad SOS segment" end - local sc = {} + local sc: { Comp } = {} local blocks = 0 for i = 0, ns - 1 do local id, t = readu8(b, p + 1 + i * 2), readu8(b, p + 2 + i * 2) diff --git a/src/Formats/codecs/Jpeg/Encode.luau b/src/Formats/codecs/Jpeg/Encode.luau index 642b737..49e003e 100644 --- a/src/Formats/codecs/Jpeg/Encode.luau +++ b/src/Formats/codecs/Jpeg/Encode.luau @@ -301,7 +301,7 @@ end -- progressive state (jcphuff.c) local EOBRUN = 0 local BE = 0 -local CORR: { number } = table.create(1000, 0) +local CORR = table.create(1000, 0) :: { number } local curAc: Derived = { code = buffer.create(512), size = buffer.create(256) } local curAcFreq: { number } = {} @@ -803,7 +803,7 @@ function Encode.run(px: buffer, w: number, h: number, bpp: number, o: Options): end local driSent = false for _, sc in script do - local sComps = {} + local sComps: { Comp } = {} for _, ci in sc.comps do table.insert(sComps, comps[ci]) end diff --git a/src/Formats/codecs/MeshFlatten.luau b/src/Formats/codecs/MeshFlatten.luau index 298a577..8d2ab73 100644 --- a/src/Formats/codecs/MeshFlatten.luau +++ b/src/Formats/codecs/MeshFlatten.luau @@ -61,7 +61,7 @@ function Flatten.numbers(acc: any, raw: boolean?): ({ number }?, string?) if buffer.len(d) < n * size then return nil, "accessor data shorter than count * components" end - local out = table.create(n) + local out = table.create(n) :: { number } if t == "f32" then for i = 0, n - 1 do out[i + 1] = readf32(d, i * 4) @@ -142,7 +142,7 @@ local function localMatrix(node: any): ({ number }?, string?) if not numList(node.matrix, 16) then return nil, "node matrix is not 16 numbers" end - local m = table.create(16) + local m = table.create(16) :: { number } for i = 1, 16 do m[i] = node.matrix[i] end @@ -304,7 +304,7 @@ local function faces(prim: any, nv: number): (any, any, string?) end idx = v else - idx = table.create(nv) + idx = table.create(nv) :: { number } for i = 1, nv do idx[i] = i - 1 end @@ -318,7 +318,7 @@ local function faces(prim: any, nv: number): (any, any, string?) if mode == "triangles" then local n = #idx - #idx % 3 if n ~= #idx then - local c = table.create(n) + local c = table.create(n) :: { number } table.move(idx, 1, n, 1, c) idx = c end diff --git a/src/Formats/codecs/Quantize/init.luau b/src/Formats/codecs/Quantize/init.luau index df4dd53..3086d63 100644 --- a/src/Formats/codecs/Quantize/init.luau +++ b/src/Formats/codecs/Quantize/init.luau @@ -134,7 +134,7 @@ local function medianCut(cnt: buffer, sums: buffer, maxColors: number): { Color local box = boxes[pick] local lo, hi, c = box[1], box[2], box[3] -- sort the range by the channel, ties by bin number: unique numeric keys, no comparator - local keys = table.create(hi - lo + 1) + local keys = table.create(hi - lo + 1) :: { number } for i = lo, hi do keys[i - lo + 1] = channel(bins[i], c) * BINS + bins[i] end @@ -157,7 +157,7 @@ local function medianCut(cnt: buffer, sums: buffer, maxColors: number): { Color boxes[pick] = scored(lo, cut) table.insert(boxes, scored(cut + 1, hi)) end - local pal = table.create(#boxes) + local pal = table.create(#boxes) :: { Color } for i, box in boxes do pal[i] = mean(cnt, sums, bins, box[1], box[2]) end @@ -247,7 +247,7 @@ local function octree(cnt: buffer, sums: buffer, maxColors: number): { Color } break end local list = byLevel[lv] - local order = table.create(#list) + local order = table.create(#list) :: { { any } } for i, node in list do order[i] = { node, subtotal(node), i } end @@ -338,7 +338,7 @@ function Quantize.map(pixels: buffer, w: number, h: number, palette: { Color }, local dither = opts and opts.dither or false local tidx = opts and opts.transparentIndex -- the searchable entries (the transparent slot is excluded) - local pr, pg, pb, pi = {}, {}, {}, {} + local pr: { number }, pg: { number }, pb: { number }, pi: { number } = {}, {}, {}, {} for i, c in palette do if tidx == nil or i - 1 ~= tidx then table.insert(pr, c[1] or 0) @@ -350,12 +350,12 @@ function Quantize.map(pixels: buffer, w: number, h: number, palette: { Color }, local np = #pr -- sorted by green (the heaviest weight), so the search can stop once 4 * dg^2 alone is worse than the best do - local order = table.create(np) + local order = table.create(np) :: { number } for k = 1, np do order[k] = pg[k] * 65536 + k end table.sort(order) - local r2, g2, b2, i2 = table.create(np), table.create(np), table.create(np), table.create(np) + local r2, g2, b2, i2 = table.create(np) :: { number }, table.create(np) :: { number }, table.create(np) :: { number }, table.create(np) :: { number } for k = 1, np do local j = order[k] % 65536 r2[k], g2[k], b2[k], i2[k] = pr[j], pg[j], pb[j], pi[j] diff --git a/src/Formats/codecs/Raster.luau b/src/Formats/codecs/Raster.luau index 4f06477..ba93fda 100644 --- a/src/Formats/codecs/Raster.luau +++ b/src/Formats/codecs/Raster.luau @@ -111,7 +111,7 @@ function Builder.cubicTo(self: Builder, c1x: number, c1y: number, c2x: number, c return self end function Builder.close(self: Builder): Builder - table.insert(self.cmds, { op = "close" }) + table.insert(self.cmds, { op = "close" } :: Cmd) return self end -- rect(x, y, w, h), ellipse(cx, cy, rx, ry): closed subpaths @@ -481,7 +481,7 @@ function Raster.fill(img: any, path: any, paint: any, opts: Options?): (boolean, if buffer.len(px) < iw * ih * 4 then return false, "fill: image pixels too short" end - local o: Options = table.clone(opts or {}) + local o: Options = table.clone(opts or {} :: Options) local clip = o.clip if type(clip) == "table" and type(clip[1]) == "number" and type(clip[2]) == "number" and type(clip[3]) == "number" and type(clip[4]) == "number" then o.clip = { max(0, clip[1]), max(0, clip[2]), min(iw, clip[3]), min(ih, clip[4]) } @@ -572,7 +572,7 @@ local function polygon(out: Path, pts: { number }) table.insert(out, { op = "lineTo", pts[i], pts[i + 1] }) end end - table.insert(out, { op = "close" }) + table.insert(out, { op = "close" } :: Cmd) end local function arcPoints(cx: number, cy: number, r: number, a0: number, a1: number, tol: number, pts: { number }) diff --git a/src/Formats/codecs/SoundFont/Parse.luau b/src/Formats/codecs/SoundFont/Parse.luau index 90cdfcc..df39807 100644 --- a/src/Formats/codecs/SoundFont/Parse.luau +++ b/src/Formats/codecs/SoundFont/Parse.luau @@ -296,7 +296,7 @@ function Parse.parse(r: Bytes.Reader, opts: Options?): (SoundFont?, Err.Err?) if layout and not hydra[sid] then local rs = RECSIZE[sid] local n = sub:remaining() // rs - local recs: { { number } } = table.create(n) + local recs = table.create(n) :: { { number } } for i = 1, n do local rec = {} for _, w in layout do @@ -487,7 +487,7 @@ function Parse.parse(r: Bytes.Reader, opts: Options?): (SoundFont?, Err.Err?) for _, p in presets do (p :: any)._order = nil end - local headers: { { [string]: any } } = table.create(nShdr) + local headers = table.create(nShdr) :: { { [string]: any } } for i = 1, nShdr do local sh = shdr[i] headers[i] = { @@ -503,7 +503,7 @@ function Parse.parse(r: Bytes.Reader, opts: Options?): (SoundFont?, Err.Err?) type = sh[10], } end - local instruments: { { name: string, zones: number } } = table.create(nInst) + local instruments = table.create(nInst) :: { { name: string, zones: number } } for i = 1, nInst do instruments[i] = { name = instNames[i], zones = math.max(0, (inst[i + 1][2] or 0) - inst[i][2]) } end diff --git a/src/Formats/codecs/TrueType/Glyf.luau b/src/Formats/codecs/TrueType/Glyf.luau index 65392f6..5d598a9 100644 --- a/src/Formats/codecs/TrueType/Glyf.luau +++ b/src/Formats/codecs/TrueType/Glyf.luau @@ -54,7 +54,7 @@ function Glyf.range(f: Face, g: number): (number?, number) if (g + 2) * 4 > f.locaLen then return nil, 0 end - a, z = u32(f.buf, f.loca + g * 4), u32(f.buf, f.loca + g * 4 + 4) + a, z = u32(f.buf, f.loca + g * 4), u32(f.buf, f.loca + g * 4 + 4) :: number else if (g + 2) * 2 > f.locaLen then return nil, 0 @@ -84,7 +84,7 @@ local MAX_POINTS = 65536 local function simple(b: buffer, o: number, len: number, nc: number): ({ Contour }?, string?) local e = o + len - local ends = table.create(nc) + local ends = table.create(nc) :: { number } local p = o + 10 if p + nc * 2 + 2 > e then return nil, "glyph header past the end" @@ -175,7 +175,7 @@ local function simple(b: buffer, o: number, len: number, nc: number): ({ Contour end ys[k] = y end - local out: { Contour } = table.create(nc) + local out = table.create(nc) :: { Contour } local s = 1 for c = 1, nc do local z = ends[c] + 1 @@ -212,9 +212,9 @@ local function composite(f: Face, o: number, len: number, depth: number): ({ Con return nil, "component past the end" end if band(flags, 2) ~= 0 then - a1, a2 = i16(b, p), i16(b, p + 2) + a1, a2 = i16(b, p), i16(b, p + 2) :: number else - a1, a2 = u16(b, p), u16(b, p + 2) + a1, a2 = u16(b, p), u16(b, p + 2) :: number end p += 4 else @@ -222,9 +222,9 @@ local function composite(f: Face, o: number, len: number, depth: number): ({ Con return nil, "component past the end" end if band(flags, 2) ~= 0 then - a1, a2 = readi8(b, p), readi8(b, p + 1) + a1, a2 = readi8(b, p), readi8(b, p + 1) :: number else - a1, a2 = readu8(b, p), readu8(b, p + 1) + a1, a2 = readu8(b, p), readu8(b, p + 1) :: number end p += 2 end @@ -248,9 +248,9 @@ local function composite(f: Face, o: number, len: number, depth: number): ({ Con return nil, err end -- transform the child's points - local tc: { Contour } = table.create(#child) + local tc = table.create(#child) :: { Contour } for i, c in child do - local nx, ny = table.create(#c.x), table.create(#c.x) + local nx, ny = table.create(#c.x) :: { number }, table.create(#c.x) :: { number } for k = 1, #c.x do local x, y = c.x[k], c.y[k] nx[k] = m1 * x + m3 * y diff --git a/src/Formats/codecs/TrueType/init.luau b/src/Formats/codecs/TrueType/init.luau index 4e7948d..3752c3f 100644 --- a/src/Formats/codecs/TrueType/init.luau +++ b/src/Formats/codecs/TrueType/init.luau @@ -183,7 +183,7 @@ function Face.rasterize(self: any, g: number, px: number, opts: RasterOptions?): if not cmds then return nil end - local o = opts or {} + local o: RasterOptions = opts or {} local sx = if type(o.scaleX) == "number" then o.scaleX else px / self.unitsPerEm local sy = if type(o.scaleY) == "number" then o.scaleY else sx local tx, ty = o.shiftX or 0, o.shiftY or 0 diff --git a/src/Formats/codecs/Video/init.luau b/src/Formats/codecs/Video/init.luau index 7c38620..425ea25 100644 --- a/src/Formats/codecs/Video/init.luau +++ b/src/Formats/codecs/Video/init.luau @@ -95,7 +95,7 @@ local function rawPlanar(data: buffer, pf: string, bits: number, w: number, h: n if pf == "gray" then u, v = 128, 128 elseif pf == "yuv420p" then - u, v = sample(uo + i * bps), sample(vo + i * bps) + u, v = sample(uo + i * bps), sample(vo + i * bps) :: number elseif pf == "yuv422p" then local y0, y1 = cy * 2, math.min(cy * 2 + 1, h - 1) u = (sample(uo + (y0 * scw + cx) * bps) + sample(uo + (y1 * scw + cx) * bps) + 1) // 2 @@ -166,7 +166,7 @@ local function rawDecoder(track: Types.Track, _opts: any?): (Types.VideoCodecDec return rawPlanar(data, pf, bits, w, h), nil end local bpp = if pf == "bgra" or pf == "rgba" then 4 else 3 - local stride = if track.stride then track.stride else w * bpp + local stride: number = track.stride or w * bpp if n < stride * (h - 1) + w * bpp then return nil, Err.new(Err.TRUNCATED, "raw frame too short") end @@ -186,7 +186,7 @@ local function rawDecoder(track: Types.Track, _opts: any?): (Types.VideoCodecDec end end return img, nil - end) + end), nil end local function vp8Decoder(_track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) @@ -210,21 +210,21 @@ local function vp8Decoder(_track: Types.Track, opts: any?): (Types.VideoCodecDec else dec = Vp8.newDecoder() end - end) + end), nil end -- Motion JPEG: every packet one JPEG (or two fields), yuv420p straight from the planes (full range) when the layout -- allows, else rgba8 local function mjpegDecoder(_track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) local Jpeg = require("@formats/codecs/Jpeg") - local o = { yuv = true, maxPixels = opts and opts.maxPixels } + local o: Jpeg.DecodeOptions = { yuv = true, maxPixels = opts and opts.maxPixels } return Video.simpleDecoder(function(data: buffer): (Types.Image?, Err.Err?) local img, err = Jpeg.decode(data, 0, buffer.len(data), o) if img and img.format == "yuv420p" then img.meta.yuv = { range = "full", matrix = "bt601" } end return img, err - end) + end), nil end -- the MJPEG encoder (writers): JPEG is full-range, so limited-range yuv420p frames are remapped first @@ -444,7 +444,7 @@ function Video.open(demuxer: Types.Demuxer, opts: OpenOptions?): (Types.VideoDec end local index, flushed, skipUntil = 0, false, -math.huge local tid = if track then track.id else -1 - local scale = if track and track.timescale and track.timescale > 0 then track.timescale else 1000 + local scale: number = if track and track.timescale and track.timescale > 0 then track.timescale else 1000 local start = demuxer.startTime or 0 v.startTime = start local defaultDur = if v.frameRate > 0 then 1 / v.frameRate else 0 @@ -461,8 +461,8 @@ function Video.open(demuxer: Types.Demuxer, opts: OpenOptions?): (Types.VideoDec if t + 1e-9 >= skipUntil then index += 1 local d = defaultDur - if lastPts and t > lastPts and defaultDur == 0 then - d = t - lastPts + if lastPts and t > (lastPts :: number) and defaultDur == 0 then + d = t - (lastPts :: number) end lastPts = t if o.rgba then diff --git a/src/Formats/codecs/Vp8L/Decode.luau b/src/Formats/codecs/Vp8L/Decode.luau index 6f88783..547167c 100644 --- a/src/Formats/codecs/Vp8L/Decode.luau +++ b/src/Formats/codecs/Vp8L/Decode.luau @@ -676,7 +676,7 @@ local function readCodes(d: State, xs: number, ys: number, cacheBits: number, le end if numMax > 1000 or numMax > xs * ys then -- remap the used groups to [0, numGroups); unused ones are read and checked but not kept - local map: { number } = table.create(numMax, -1) + local map = table.create(numMax, -1) :: { number } numGroups = 0 for k = 0, n - 1 do local g = readu32(img, k * 4) @@ -695,7 +695,7 @@ local function readCodes(d: State, xs: number, ys: number, cacheBits: number, le if eos(d) then return nil, nil, 0, 0, "truncated: meta codes" end - local groups: { number } = table.create(numGroups * 5, 0) + local groups = table.create(numGroups * 5, 0) :: { number } local cacheSize = if cacheBits > 0 then lshift(1, cacheBits) else 0 for i = 0, numMax - 1 do local slot = if mapping then mapping[i + 1] else i diff --git a/src/Formats/codecs/Xml/init.luau b/src/Formats/codecs/Xml/init.luau index ac0afa9..fcb574b 100644 --- a/src/Formats/codecs/Xml/init.luau +++ b/src/Formats/codecs/Xml/init.luau @@ -219,7 +219,7 @@ function Xml.descendants(node: Node, name: string?): { Node } local function walk(n: Node) for _, ch in n.children do if type(ch) == "table" and string.byte(ch.name) ~= 35 then - if name == nil or ch.name == name or (not find(name, ":", 1, true) and match(ch.name, ":(.*)$") == name) then + if name == nil or ch.name == name or (not find(name :: string, ":", 1, true) and match(ch.name, ":(.*)$") == name) then table.insert(out, ch) end walk(ch) diff --git a/src/Formats/codecs/Yuv.luau b/src/Formats/codecs/Yuv.luau index f6926e4..cfa8258 100644 --- a/src/Formats/codecs/Yuv.luau +++ b/src/Formats/codecs/Yuv.luau @@ -20,7 +20,7 @@ local Yuv = {} -- coefficients (x 65536): r = y' + crv * v; g = y' - cgu * u - cgv * v; b = y' + cbu * u -- limited: y' = (y - 16) * 255 / 219, chroma scaled by 255 / 224 -local MATRIX = { +local MATRIX: { [string]: { kr: number, kb: number } } = { bt601 = { kr = 0.299, kb = 0.114 }, bt709 = { kr = 0.2126, kb = 0.0722 }, } diff --git a/src/Formats/codecs/Zstd/Xxh64.luau b/src/Formats/codecs/Zstd/Xxh64.luau index 5aa48e8..c189970 100644 --- a/src/Formats/codecs/Zstd/Xxh64.luau +++ b/src/Formats/codecs/Zstd/Xxh64.luau @@ -122,7 +122,7 @@ function Xxh64.hash(b: buffer, offset: number, length: number): (number, number) hh, hl = add(hh, hl, math.floor(length / T32) % T32, length % T32) while p + 8 <= e do local kh, kl = round(0, 0, readu32(b, p + 4), readu32(b, p)) - hh, hl = bxor(hh, kh), bxor(hl, kl) + hh, hl = bxor(hh, kh), bxor(hl, kl) :: number hh, hl = rotl(hh, hl, 27) hh, hl = mul(hh, hl, P1H, P1L) hh, hl = add(hh, hl, P4H, P4L) @@ -130,7 +130,7 @@ function Xxh64.hash(b: buffer, offset: number, length: number): (number, number) end if p + 4 <= e then local kh, kl = mul(0, readu32(b, p), P1H, P1L) - hh, hl = bxor(hh, kh), bxor(hl, kl) + hh, hl = bxor(hh, kh), bxor(hl, kl) :: number hh, hl = rotl(hh, hl, 23) hh, hl = mul(hh, hl, P2H, P2L) hh, hl = add(hh, hl, P3H, P3L) @@ -138,7 +138,7 @@ function Xxh64.hash(b: buffer, offset: number, length: number): (number, number) end while p < e do local kh, kl = mul(0, readu8(b, p), P5H, P5L) - hh, hl = bxor(hh, kh), bxor(hl, kl) + hh, hl = bxor(hh, kh), bxor(hl, kl) :: number hh, hl = rotl(hh, hl, 11) hh, hl = mul(hh, hl, P1H, P1L) p += 1 @@ -146,7 +146,7 @@ function Xxh64.hash(b: buffer, offset: number, length: number): (number, number) -- avalanche hl = bxor(hl, rshift(hh, 1)) -- h ^= h >> 33 hh, hl = mul(hh, hl, P2H, P2L) - hh, hl = bxor(hh, rshift(hh, 29)), bxor(hl, bor(rshift(hl, 29), lshift(hh, 3))) -- h ^= h >> 29 + hh, hl = bxor(hh, rshift(hh, 29)), bxor(hl, bor(rshift(hl, 29), lshift(hh, 3))) :: number -- h ^= h >> 29 hh, hl = mul(hh, hl, P3H, P3L) hl = bxor(hl, hh) -- h ^= h >> 32 return hh, hl diff --git a/src/Formats/containers/IsoBmff/Demux.luau b/src/Formats/containers/IsoBmff/Demux.luau index 0160249..7f8689d 100644 --- a/src/Formats/containers/IsoBmff/Demux.luau +++ b/src/Formats/containers/IsoBmff/Demux.luau @@ -328,9 +328,9 @@ local function track(b: buffer, trak: Box.Box, movieTimescale: number, trex: { [ for _ = 1, n do local dur: number, mt: number if v == 1 then - dur, mt = r:u64be(), r:i64be() + dur, mt = r:u64be(), r:i64be() :: number else - dur, mt = r:u32be(), r:i32be() + dur, mt = r:u32be(), r:i32be() :: number end local rate = r:i32be() / 65536 if r.err then diff --git a/src/Formats/containers/Zip/init.luau b/src/Formats/containers/Zip/init.luau index 1545ce2..df38c88 100644 --- a/src/Formats/containers/Zip/init.luau +++ b/src/Formats/containers/Zip/init.luau @@ -152,7 +152,7 @@ local function parse(b: buffer): (any, Err.Err?) return nil, Err.new(Err.CORRUPT, "central directory not found") end end - local entries: { any } = table.create(math.min(count, 65536)) + 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 diff --git a/src/Formats/ops/ImageOps/Kernels.luau b/src/Formats/ops/ImageOps/Kernels.luau index cf14954..c55ae9e 100644 --- a/src/Formats/ops/ImageOps/Kernels.luau +++ b/src/Formats/ops/ImageOps/Kernels.luau @@ -81,13 +81,13 @@ function K.convert(src: buffer, sf: number, dst: buffer, df: number, n: number) local r: number, g: number, b: number, a: number if sf == 1 then local o = i * 4 - r, g, b, a = readu8(src, o), readu8(src, o + 1), readu8(src, o + 2), readu8(src, o + 3) + r, g, b, a = readu8(src, o), readu8(src, o + 1), readu8(src, o + 2), readu8(src, o + 3) :: number elseif sf == 2 then local o = i * 8 - r, g, b, a = readu16(src, o), readu16(src, o + 2), readu16(src, o + 4), readu16(src, o + 6) + r, g, b, a = readu16(src, o), readu16(src, o + 2), readu16(src, o + 4), readu16(src, o + 6) :: number elseif sf == 3 then local o = i * 16 - r, g, b, a = readf32(src, o), readf32(src, o + 4), readf32(src, o + 8), readf32(src, o + 12) + r, g, b, a = readf32(src, o), readf32(src, o + 4), readf32(src, o + 8), readf32(src, o + 12) :: number elseif sf == 4 then local o = i * 3 r, g, b, a = readu8(src, o), readu8(src, o + 1), readu8(src, o + 2), 255 @@ -99,7 +99,7 @@ function K.convert(src: buffer, sf: number, dst: buffer, df: number, n: number) r, g, b, a = v, v, v, 65535 elseif sf == 7 then local v = readu8(src, i * 2) - r, g, b, a = v, v, v, readu8(src, i * 2 + 1) + r, g, b, a = v, v, v, readu8(src, i * 2 + 1) :: number else r, g, b, a = 255, 255, 255, readu8(src, i) end @@ -118,7 +118,7 @@ function K.convert(src: buffer, sf: number, dst: buffer, df: number, n: number) elseif df == 8 then writeu8(dst, i, depthConv(a, sd, 8)) else - r, g, b = depthConv(r, sd, dd), depthConv(g, sd, dd), depthConv(b, sd, dd) + r, g, b = depthConv(r, sd, dd), depthConv(g, sd, dd), depthConv(b, sd, dd) :: number if df == 1 then local o = i * 4 writeu8(dst, o, r) From 39dbde13b70068d0183a32feac0a2508780089d3 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 10:54:51 -0500 Subject: [PATCH 06/22] ws-cleanup-types: TrueType names, mp3 index, aac options, imageops test: annotations --- src/Formats/audio/aac/init.luau | 2 +- src/Formats/audio/mp3/Index.luau | 4 ++-- src/Formats/codecs/TrueType/Tables.luau | 4 ++-- tests/ops/imageops.luau | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/Formats/audio/aac/init.luau b/src/Formats/audio/aac/init.luau index 6c3e45d..84ded12 100644 --- a/src/Formats/audio/aac/init.luau +++ b/src/Formats/audio/aac/init.luau @@ -136,7 +136,7 @@ local function index(r: Bytes.Reader, maxFrames: number): ({ number }, { number end function AacFormat.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?) - local o = opts or {} + local o: DecodeOptions = opts or {} local offs, sizes, first, ierr = index(r, o.maxFrames or 2 ^ 22) if ierr then return nil, ierr diff --git a/src/Formats/audio/mp3/Index.luau b/src/Formats/audio/mp3/Index.luau index 97ca48f..ae84e7f 100644 --- a/src/Formats/audio/mp3/Index.luau +++ b/src/Formats/audio/mp3/Index.luau @@ -101,7 +101,7 @@ function Index.build(b: buffer, start: number, stop: number): Index? if first then first = false - hz, nch, layer, spf = fHz, fCh, fLayer, Header.frameSamples(h1) + hz, nch, layer, spf = fHz, fCh, fLayer, Header.frameSamples(h1) :: number version = if band(h1, 8) ~= 0 then 1 elseif band(h1, 0x10) ~= 0 then 2 else 2.5 if fLayer == 3 then local ret, frames, d, p = Core.vbrTag(b, pos, fs) @@ -150,7 +150,7 @@ function Index.build(b: buffer, start: number, stop: number): Index? end if n == cap then cap *= 2 - OFF, SIZE, FLAGS, OUT, MAIN = grow(OFF, cap * 4), grow(SIZE, cap * 2), grow(FLAGS, cap), grow(OUT, cap * 4), grow(MAIN, cap * 2) + OFF, SIZE, FLAGS, OUT, MAIN = grow(OFF, cap * 4), grow(SIZE, cap * 2), grow(FLAGS, cap), grow(OUT, cap * 4), grow(MAIN, cap * 2) :: buffer end buffer.writeu32(OFF, n * 4, pos) buffer.writeu16(SIZE, n * 2, fs) diff --git a/src/Formats/codecs/TrueType/Tables.luau b/src/Formats/codecs/TrueType/Tables.luau index 87e5833..7287007 100644 --- a/src/Formats/codecs/TrueType/Tables.luau +++ b/src/Formats/codecs/TrueType/Tables.luau @@ -452,7 +452,7 @@ local function macRoman(b: buffer, o: number, n: number): string return table.concat(out) end -local NAME_IDS = { +local NAME_IDS: { [number]: string } = { [0] = "copyright", [1] = "family", [2] = "style", @@ -486,7 +486,7 @@ function Tables.names(b: buffer, o: number, n: number): { [string]: string } local len, off = u16(b, r + 8), u16(b, r + 10) local key = NAME_IDS[nid] if key and strings + off + len <= o + n then - local rk, s = 0, nil + local rk: number, s: string? = 0, nil if pid == 3 and (eid == 1 or eid == 10 or eid == 0) then rk = if lang == 0x409 then 4 else 2 s = utf16be(b, strings + off, len) diff --git a/tests/ops/imageops.luau b/tests/ops/imageops.luau index 2662d0d..c09dec7 100644 --- a/tests/ops/imageops.luau +++ b/tests/ops/imageops.luau @@ -43,7 +43,7 @@ do local ga = Ops.convert(rgba, "gray8") :: any t:check(buffer.tostring(ga.pixels) == Fx.graya, "rgba8 -> gray8 matches Pillow (alpha ignored)") local gray = Ops.convert(rgb, "gray8") :: any - local worst = { nearest = 0, bilinear = 0, lanczos = 0 } + local worst: { [string]: number } = { nearest = 0, bilinear = 0, lanczos = 0 } for _, c in Fx.resize do local src = if c.mode == "RGB" then rgb else gray local r = Ops.resize(src, c.w, c.h, c.filter) :: any From 7c15b0235403b9a863faecb3859a8fbf922c3214 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 10:55:22 -0500 Subject: [PATCH 07/22] ws-cleanup-types: codecs/Aac: type the built Config --- src/Formats/codecs/Aac/init.luau | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Formats/codecs/Aac/init.luau b/src/Formats/codecs/Aac/init.luau index c7e5e0b..15e586e 100644 --- a/src/Formats/codecs/Aac/init.luau +++ b/src/Formats/codecs/Aac/init.luau @@ -310,7 +310,7 @@ function Aac.decoder(asc: any): (Decoder?, Err.Err?) sbr = false, ps = false, frameLength = 1024, - } + } :: Config else return nil, Err.new(Err.ARG, "decoder: expected an AudioSpecificConfig buffer") end From f784b4eb9b04ee6448c7dc457814d7ffdc35f912 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 10:58:31 -0500 Subject: [PATCH 08/22] ws-cleanup: shared helpers instead of copies (CRCs, codec arguments, utf8char, keyLess / isArray) A sweep for duplicated function bodies, CRC tables and base64 across src/Formats: - core/Crc32.msb / MSB_TABLE: the MSB-first 0x04C11DB7 CRC-32 that containers/Ogg (Page + Mux), containers/MpegTs and codecs/Bzip2 each built (test vectors CRC-32/MPEG-2 and /BZIP2 in tests/core/bytes). - audio/flac/Encode uses audio/flac/Frame's CRC-8 / CRC-16 tables (Frame.crc8 added) instead of its own copy. - core/Bytes.toBuffer / Bytes.span: the (buffer | string, offset, length) argument checking codecs/Deflate, codecs/Lzma and codecs/Brotli each carried. - codecs/Text.utf8char: one copy instead of four (codecs/Json, codecs/Xml, data/yaml, data/toml). - Types.keyLess / Types.isArray (small additions to Types, backward compatible): data/msgpack, data/cbor and data/yaml/Emit had identical copies. - playlist/pls: dead copies of m3u's attributes / extinf removed. Left on purpose: per-codec bit readers / writers in hot loops (STYLE.md: inner loops keep their own bit buffers), same-folder helpers (Alac signExtend, Vorbis ilog), Zip's DOS-date civil() (a different epoch helper). --- src/Formats/Types.luau | 22 +++++++++++ src/Formats/audio/flac/Frame.luau | 15 +++++--- src/Formats/codecs/Brotli/init.luau | 21 ++--------- src/Formats/codecs/Bzip2/Decode.luau | 16 ++------ src/Formats/codecs/Deflate/init.luau | 41 ++------------------ src/Formats/codecs/Json/Decode.luau | 12 +----- src/Formats/codecs/Lzma/init.luau | 40 ++------------------ src/Formats/codecs/Text/init.luau | 13 +++++++ src/Formats/codecs/Xml/Parse.luau | 12 +----- src/Formats/containers/MpegTs/init.luau | 20 +--------- src/Formats/containers/Ogg/Page.luau | 16 ++------ src/Formats/core/Bytes.luau | 30 +++++++++++++++ src/Formats/core/Crc32.luau | 25 ++++++++++++- src/Formats/data/cbor/Codec.luau | 26 +------------ src/Formats/data/msgpack/Codec.luau | 26 +------------ src/Formats/data/toml/Decode.luau | 12 +----- src/Formats/data/toml/init.luau | 2 +- src/Formats/data/yaml/Emit.luau | 29 +------------- src/Formats/data/yaml/Parse.luau | 12 +----- src/Formats/data/yaml/init.luau | 2 +- src/Formats/playlist/pls/init.luau | 50 ------------------------- tests/core/bytes.luau | 21 ++++++++++- 22 files changed, 152 insertions(+), 311 deletions(-) diff --git a/src/Formats/Types.luau b/src/Formats/Types.luau index f34b569..cfaf6c7 100644 --- a/src/Formats/Types.luau +++ b/src/Formats/Types.luau @@ -691,6 +691,7 @@ function Types.set(o: { [any]: any }, k: any, v: any) end o[k] = v end +-- keyLess(a, b): a total order for table keys (by type name, then value; numbers before strings) local function keyLess(a: any, b: any): boolean local ta, tb = type(a), type(b) if ta ~= tb then @@ -701,6 +702,27 @@ local function keyLess(a: any, b: any): boolean end return tostring(a) < tostring(b) end +Types.keyLess = keyLess + +-- isArray(t, emptyIsMap?) -> t is a plain array 1 .. #t (no other keys, not an ordered object); an empty table is an +-- array unless emptyIsMap +function Types.isArray(t: { [any]: any }, emptyIsMap: boolean?): boolean + if Types.isObject(t) then + return false + end + local n = #t + if n == 0 then + return next(t) == nil and not emptyIsMap + end + if next(t, n) ~= nil then + return false + end + local c = 0 + for _ in next, t do + c += 1 + end + return c == n +end -- keys(t) -> the keys in order: an object's recorded order (keys since removed are skipped), then any other keys -- sorted (numbers before strings) function Types.keys(t: { [any]: any }): { any } diff --git a/src/Formats/audio/flac/Frame.luau b/src/Formats/audio/flac/Frame.luau index d31ed05..049fee1 100644 --- a/src/Formats/audio/flac/Frame.luau +++ b/src/Formats/audio/flac/Frame.luau @@ -41,6 +41,15 @@ local function crc16(b: buffer, from: number, to: number): number end Frame.crc16 = crc16 +local function crc8(b: buffer, from: number, to: number): number + local c = 0 + for i = from, to - 1 do + c = CRC8[bxor(c, readu8(b, i)) + 1] + end + return c +end +Frame.crc8 = crc8 + local POW2 = table.create(64, 0) for i = 0, 63 do POW2[i + 1] = 2 ^ i @@ -147,11 +156,7 @@ function Frame.header(b: buffer, pos: number, len: number, si: any): Header? return nil end -- CRC-8 over the header - local c = 0 - for i = pos, p - 1 do - c = CRC8[bxor(c, readu8(b, i)) + 1] - end - if c ~= readu8(b, p) then + if crc8(b, pos, p) ~= readu8(b, p) then return nil end return { diff --git a/src/Formats/codecs/Brotli/init.luau b/src/Formats/codecs/Brotli/init.luau index fb4fb58..2fd2bb1 100644 --- a/src/Formats/codecs/Brotli/init.luau +++ b/src/Formats/codecs/Brotli/init.luau @@ -12,6 +12,7 @@ -- -- Never throws: bad data and bad arguments return nil, Err (TRUNCATED / CORRUPT / LIMIT / UNSUPPORTED / ARG). local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") local Crc32 = require("@formats/core/Crc32") local Base64 = require("@formats/core/Base64") local Deflate = require("@formats/codecs/Deflate") @@ -63,30 +64,14 @@ function Brotli.dictionary(): buffer? end -- ------------------------------------------------------------------------------------------------ decompress -local function toBuffer(b: any): buffer? - if type(b) == "string" then - return buffer.fromstring(b) - end - return if type(b) == "buffer" then b else nil -end -- decompress(buf, offset?, length?, opts?) -> buffer, consumedEnd | nil, Err. consumedEnd: the input offset just past -- the stream (trailing bytes are ignored). function Brotli.decompress(buf: buffer | string, offset: number?, length: number?, opts: Options?): (buffer?, any) - local b = toBuffer(buf) + local b, o, l, aerr = Bytes.span("Brotli.decompress", buf, offset, length) if not b then - return nil, Err.new(Err.ARG, "Brotli.decompress: expected a buffer or a string, got " .. typeof(buf)) + return nil, aerr end - local n = buffer.len(b) - local o = offset or 0 - if type(o) ~= "number" or o < 0 or o > n or o % 1 ~= 0 then - return nil, Err.new(Err.ARG, "Brotli.decompress: bad offset " .. tostring(offset)) - end - local l = length or (n - o) - if type(l) ~= "number" or l < 0 or l % 1 ~= 0 then - return nil, Err.new(Err.ARG, "Brotli.decompress: bad length " .. tostring(length)) - end - l = math.min(l, n - o) local maxBytes = if opts and opts.maxBytes then opts.maxBytes else 2 ^ 30 if type(maxBytes) ~= "number" or maxBytes < 0 then return nil, Err.new(Err.ARG, "Brotli.decompress: bad maxBytes") diff --git a/src/Formats/codecs/Bzip2/Decode.luau b/src/Formats/codecs/Bzip2/Decode.luau index 66df42e..720973d 100644 --- a/src/Formats/codecs/Bzip2/Decode.luau +++ b/src/Formats/codecs/Bzip2/Decode.luau @@ -11,25 +11,15 @@ -- -- Never throws: every buffer access is in range by construction; failures return nil, message, kind -- ("truncated" | "corrupt" | "checksum" | "limit" | "unsupported"). +local Crc32 = require("@formats/core/Crc32") local band, bor, bxor, lshift, rshift = bit32.band, bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift local readu8, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu8, buffer.writeu32 local bcreate, bcopy, bfill, blen = buffer.create, buffer.copy, buffer.fill, buffer.len local Decode = {} --- CRC-32/BZIP2 table (polynomial 0x04C11DB7, not reflected) -local CT = table.create(256, 0) -for i = 0, 255 do - local c = lshift(i, 24) - for _ = 1, 8 do - if band(c, 0x80000000) ~= 0 then - c = bxor(lshift(c, 1), 0x04C11DB7) - else - c = lshift(c, 1) - end - end - CT[i + 1] = c -end +-- CRC-32/BZIP2 table (polynomial 0x04C11DB7, not reflected: core/Crc32) +local CT = Crc32.MSB_TABLE Decode.crcTable = CT local MASK = table.create(33, 0) diff --git a/src/Formats/codecs/Deflate/init.luau b/src/Formats/codecs/Deflate/init.luau index c903ef8..8308056 100644 --- a/src/Formats/codecs/Deflate/init.luau +++ b/src/Formats/codecs/Deflate/init.luau @@ -12,6 +12,7 @@ -- -- Never throws: bad data and bad arguments return nil, Err (core/Err codes TRUNCATED / CORRUPT / CHECKSUM / ARG). local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") local Crc32 = require("@formats/core/Crc32") local Adler32 = require("@formats/core/Adler32") local Inflate = require("@formats/codecs/Deflate/Inflate") @@ -21,44 +22,8 @@ local Deflate = {} Deflate.version = "1.1.0" -local function toBuffer(b: any): buffer? - if type(b) == "string" then - return buffer.fromstring(b) - end - if type(b) ~= "buffer" then - return nil - end - return b -end - --- (offset, length) clamped to the buffer; nil for non-numbers / negative / fractional / out-of-range offsets -local function range(b: buffer, off: number?, len: number?): (number?, number) - local n = buffer.len(b) - local o = off or 0 - if type(o) ~= "number" or o < 0 or o > n or o % 1 ~= 0 then - return nil, 0 - end - local l = len or (n - o) - if type(l) ~= "number" or l < 0 or l % 1 ~= 0 then - return nil, 0 - end - if o + l > n then - l = n - o - end - return o, l -end - -local function args(what: string, buf: any, offset: number?, length: number?): (buffer?, number, number, Err.Err?) - local b = toBuffer(buf) - if not b then - return nil, 0, 0, Err.new(Err.ARG, what .. ": expected a buffer or a string, got " .. typeof(buf)) - end - local o, l = range(b, offset, length) - if not o then - return nil, 0, 0, Err.new(Err.ARG, what .. ": bad offset / length " .. tostring(offset) .. ", " .. tostring(length)) - end - return b, o, l, nil -end +local toBuffer = Bytes.toBuffer +local args = Bytes.span local function shrink(out: buffer, n: number): buffer if buffer.len(out) == n then diff --git a/src/Formats/codecs/Json/Decode.luau b/src/Formats/codecs/Json/Decode.luau index 46b9fd2..4d97f82 100644 --- a/src/Formats/codecs/Json/Decode.luau +++ b/src/Formats/codecs/Json/Decode.luau @@ -4,6 +4,7 @@ -- is a LIMIT error, never a stack overflow), strict grammar (no comments, trailing commas, leading zeros, NaN, single -- quotes or raw control characters), \u escapes with surrogate pairs (lone surrogates become WTF-8 bytes). Also the -- pull tokenizer behind Json.events. Never throws: failures return nil, message, offset (0-based byte offset). +local Text = require("@formats/codecs/Text") local Types = require("@formats/Types") local Decode = {} @@ -31,16 +32,7 @@ local ESC: { [number]: string } = { } -- utf8 bytes of a code point (surrogates too: WTF-8) -local function utf8char(c: number): string - if c < 0x80 then - return char(c) - elseif c < 0x800 then - return char(0xC0 + c // 64, 0x80 + c % 64) - elseif c < 0x10000 then - return char(0xE0 + c // 4096, 0x80 + (c // 64) % 64, 0x80 + c % 64) - end - return char(0xF0 + c // 262144, 0x80 + (c // 4096) % 64, 0x80 + (c // 64) % 64, 0x80 + c % 64) -end +local utf8char = Text.utf8char Decode.utf8char = utf8char local function hex4(s: string, i: number): number? diff --git a/src/Formats/codecs/Lzma/init.luau b/src/Formats/codecs/Lzma/init.luau index f6f2825..6f11c1d 100644 --- a/src/Formats/codecs/Lzma/init.luau +++ b/src/Formats/codecs/Lzma/init.luau @@ -17,6 +17,7 @@ -- none / CRC-32 / CRC-64 are verified, SHA-256 is skipped (not verified). xz filters: LZMA2, delta, x86, PowerPC, -- ARM, ARM-Thumb, SPARC, ARM64; IA-64 and RISC-V are Err.UNSUPPORTED. Never throws. local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") local Crc32 = require("@formats/core/Crc32") local Decode = require("@formats/codecs/Lzma/Decode") local Filters = require("@formats/codecs/Lzma/Filters") @@ -33,43 +34,8 @@ export type Options = { } export type Props = { lc: number, lp: number, pb: number, dictSize: number? } -local function toBuffer(b: any): buffer? - if type(b) == "string" then - return buffer.fromstring(b) - end - if type(b) ~= "buffer" then - return nil - end - return b -end - -local function range(b: buffer, off: number?, len: number?): (number?, number) - local n = buffer.len(b) - local o = off or 0 - if type(o) ~= "number" or o < 0 or o > n or o % 1 ~= 0 then - return nil, 0 - end - local l = len or (n - o) - if type(l) ~= "number" or l < 0 or l % 1 ~= 0 then - return nil, 0 - end - if o + l > n then - l = n - o - end - return o, l -end - -local function args(what: string, buf: any, offset: number?, length: number?): (buffer?, number, number, Err.Err?) - local b = toBuffer(buf) - if not b then - return nil, 0, 0, Err.new(Err.ARG, what .. ": expected a buffer or a string, got " .. typeof(buf)) - end - local o, l = range(b, offset, length) - if not o then - return nil, 0, 0, Err.new(Err.ARG, what .. ": bad offset / length " .. tostring(offset) .. ", " .. tostring(length)) - end - return b, o, l, nil -end +local toBuffer = Bytes.toBuffer +local args = Bytes.span local function maxOf(opts: Options?): number local m = opts and opts.maxBytes diff --git a/src/Formats/codecs/Text/init.luau b/src/Formats/codecs/Text/init.luau index 11d9da4..74f86fb 100644 --- a/src/Formats/codecs/Text/init.luau +++ b/src/Formats/codecs/Text/init.luau @@ -5,6 +5,19 @@ -- playlist-luau 3fc7fd3 (same author, no third-party code). Never throws. local Text = {} +-- utf8char(codepoint) -> its UTF-8 bytes (no validation: the parsers check ranges first; utf8.char would throw) +function Text.utf8char(c: number): string + local char = string.char + if c < 0x80 then + return char(c) + elseif c < 0x800 then + return char(0xC0 + c // 64, 0x80 + c % 64) + elseif c < 0x10000 then + return char(0xE0 + c // 4096, 0x80 + (c // 64) % 64, 0x80 + c % 64) + end + return char(0xF0 + c // 262144, 0x80 + (c // 4096) % 64, 0x80 + (c // 64) % 64, 0x80 + c % 64) +end + -- CP1252 bytes 0x80..0x9F (undefined ones map to U+FFFD) Text.CP1252 = { [0x80] = 0x20AC, [0x82] = 0x201A, [0x83] = 0x0192, [0x84] = 0x201E, [0x85] = 0x2026, [0x86] = 0x2020, diff --git a/src/Formats/codecs/Xml/Parse.luau b/src/Formats/codecs/Xml/Parse.luau index 4a04ff3..d8ca82b 100644 --- a/src/Formats/codecs/Xml/Parse.luau +++ b/src/Formats/codecs/Xml/Parse.luau @@ -7,6 +7,7 @@ -- character references and internal general entities from the DOCTYPE (with an expansion limit). Not supported: -- external entities / DTDs (references to them are errors), entity values containing markup (taken as text), -- validation. Never throws: errors are events. +local Text = require("@formats/codecs/Text") local Types = require("@formats/Types") local Parse = {} @@ -24,16 +25,7 @@ export type Options = { local NAME = "^[%a_:\128-\255][%w_:%.%-\128-\255]*" local PREDEF: { [string]: string } = { lt = "<", gt = ">", amp = "&", quot = '"', apos = "'" } -local function utf8char(c: number): string - if c < 0x80 then - return char(c) - elseif c < 0x800 then - return char(0xC0 + c // 64, 0x80 + c % 64) - elseif c < 0x10000 then - return char(0xE0 + c // 4096, 0x80 + (c // 64) % 64, 0x80 + c % 64) - end - return char(0xF0 + c // 262144, 0x80 + (c // 4096) % 64, 0x80 + (c // 64) % 64, 0x80 + c % 64) -end +local utf8char = Text.utf8char Parse.utf8char = utf8char local CP1252: { [number]: number } = { diff --git a/src/Formats/containers/MpegTs/init.luau b/src/Formats/containers/MpegTs/init.luau index 693b034..ffd1e81 100644 --- a/src/Formats/containers/MpegTs/init.luau +++ b/src/Formats/containers/MpegTs/init.luau @@ -11,6 +11,7 @@ -- -- 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("@formats/core/Crc32") local MpegTs = {} @@ -103,25 +104,8 @@ local CODECS: { [number]: { string } } = { } -- CRC-32/MPEG-2 (poly 0x04C11DB7, init 0xFFFFFFFF, MSB first, no final xor): a section including its CRC sums to 0 -local CRC = buffer.create(256 * 4) -for i = 0, 255 do - local c = lshift(i, 24) - for _ = 1, 8 do - if band(c, 0x80000000) ~= 0 then - c = bit32.bxor(lshift(c, 1), 0x04C11DB7) - else - c = lshift(c, 1) - end - end - buffer.writeu32(CRC, i * 4, c) -end - local function crc32(b: buffer, off: number, n: number): number - local c = 0xFFFFFFFF - for i = off, off + n - 1 do - c = bit32.bxor(lshift(c, 8), buffer.readu32(CRC, band(bit32.bxor(rshift(c, 24), readu8(b, i)), 255) * 4)) - end - return c + return Crc32.msb(b, off, n, 0xFFFFFFFF) end MpegTs.crc32 = crc32 diff --git a/src/Formats/containers/Ogg/Page.luau b/src/Formats/containers/Ogg/Page.luau index acf9125..bcf3938 100644 --- a/src/Formats/containers/Ogg/Page.luau +++ b/src/Formats/containers/Ogg/Page.luau @@ -8,6 +8,7 @@ -- 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("@formats/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 @@ -27,19 +28,8 @@ export type Info = { 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 +-- 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 diff --git a/src/Formats/core/Bytes.luau b/src/Formats/core/Bytes.luau index e9e921e..7ae6ee5 100644 --- a/src/Formats/core/Bytes.luau +++ b/src/Formats/core/Bytes.luau @@ -13,6 +13,8 @@ -- -- local w = Bytes.writer() -- or Bytes.writer(initialCapacity) -- w:string("abcd"); w:u32be(width); local out = w:finish() +-- +-- local b, o, n, err = Bytes.span("Deflate.inflate", input, offset?, length?) -- codec argument checking local Err = require("@formats/core/Err") local readu8, readi8, readu16, readi16, readu32, readi32 = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.readi32 @@ -534,4 +536,32 @@ end Bytes.Reader = Reader Bytes.Writer = Writer +-- ------------------------------------------------------------------------------------------------ arguments +-- toBuffer(v) -> v as a buffer (strings are copied) | nil for anything else +function Bytes.toBuffer(v: any): buffer? + if type(v) == "string" then + return buffer.fromstring(v) + end + return if type(v) == "buffer" then v else nil +end + +-- span(what, input, offset?, length?) -> buffer, offset, length | nil, 0, 0, Err.ARG: a codec's (buffer | string, +-- offset, length) arguments checked (whole numbers, offset inside the data; the length is clamped to the end) +function Bytes.span(what: string, input: any, offset: number?, length: number?): (buffer?, number, number, Err.Err?) + local b = Bytes.toBuffer(input) + if not b then + return nil, 0, 0, Err.new(Err.ARG, what .. ": expected a buffer or a string, got " .. typeof(input)) + end + local n = buffer.len(b) + local o = offset or 0 + local l = length or (n - (if type(o) == "number" then o else 0)) + if type(o) ~= "number" or o < 0 or o > n or o % 1 ~= 0 or type(l) ~= "number" or l < 0 or l % 1 ~= 0 then + return nil, 0, 0, Err.new(Err.ARG, what .. ": bad offset / length " .. tostring(offset) .. ", " .. tostring(length)) + end + if o + l > n then + l = n - o + end + return b, o, l, nil +end + return Bytes diff --git a/src/Formats/core/Crc32.luau b/src/Formats/core/Crc32.luau index b6bf6e8..bbf29ec 100644 --- a/src/Formats/core/Crc32.luau +++ b/src/Formats/core/Crc32.luau @@ -6,7 +6,10 @@ -- -- Crc32.of(buf, offset?, length?, crc?) -> u32 (pass a previous result as crc to continue it) -- Crc32.string(s, crc?) -> u32 -local band, bxor, rshift = bit32.band, bit32.bxor, bit32.rshift +-- Crc32.msb(buf, offset, length, init?) -> u32 the MSB-first (unreflected) 0x04C11DB7 CRC, raw register: no +-- inversions (Ogg: init 0; MPEG-2 sections / bzip2: 0xFFFFFFFF) +-- Crc32.MSB_TABLE its 1-based byte table, for codecs that inline it (bzip2) +local band, bxor, rshift, lshift = bit32.band, bit32.bxor, bit32.rshift, bit32.lshift local readu8, readu32 = buffer.readu8, buffer.readu32 local T0, T1, T2, T3 = table.create(256, 0), table.create(256, 0), table.create(256, 0), table.create(256, 0) @@ -95,4 +98,24 @@ end -- raw(buf, off, len, crc?): no clamping, for callers that already checked the range (hot paths) Crc32.raw = crc32 +-- the MSB-first CRC-32 (polynomial 0x04C11DB7, not reflected): Ogg pages, MPEG-2 PSI sections, bzip2 blocks +local MSB = table.create(256, 0) +for n = 0, 255 do + local c = lshift(n, 24) + for _ = 1, 8 do + c = if band(c, 0x80000000) ~= 0 then bxor(lshift(c, 1), 0x04C11DB7) else lshift(c, 1) + end + MSB[n + 1] = c +end +Crc32.MSB_TABLE = MSB + +-- msb(buf, off, len, init?) -> the register after buf[off, off + len) (no inversions; the caller checked the range) +function Crc32.msb(buf: buffer, off: number, len: number, init: number?): number + local c = init or 0 + for i = off, off + len - 1 do + c = bxor(lshift(c, 8), MSB[bxor(rshift(c, 24), readu8(buf, i)) + 1]) + end + return c +end + return Crc32 diff --git a/src/Formats/data/cbor/Codec.luau b/src/Formats/data/cbor/Codec.luau index f588c59..d17cbed 100644 --- a/src/Formats/data/cbor/Codec.luau +++ b/src/Formats/data/cbor/Codec.luau @@ -453,31 +453,9 @@ local function toHalf(x: number): number? end Codec.toHalf = toHalf -local function keyLess(a: any, b: any): boolean - local ta, tb = type(a), type(b) - if ta ~= tb then - return ta < tb - end - if ta == "number" or ta == "string" then - return a < b - end - return tostring(a) < tostring(b) -end +local keyLess = Types.keyLess -local function isArray(t: any, emptyMap: boolean): boolean - if Types.isObject(t) then - return false - end - local n = #t - if n == 0 then - return next(t) == nil and not emptyMap - end - local c = 0 - for _ in next, t do - c += 1 - end - return c == n -end +local isArray = Types.isArray local scratch = buffer.create(8) diff --git a/src/Formats/data/msgpack/Codec.luau b/src/Formats/data/msgpack/Codec.luau index fd42577..3b032f1 100644 --- a/src/Formats/data/msgpack/Codec.luau +++ b/src/Formats/data/msgpack/Codec.luau @@ -322,31 +322,9 @@ local function lenHeader(w: Bytes.Writer, n: number, fix: number?, fixMax: numbe end end -local function keyLess(a: any, b: any): boolean - local ta, tb = type(a), type(b) - if ta ~= tb then - return ta < tb - end - if ta == "number" or ta == "string" then - return a < b - end - return tostring(a) < tostring(b) -end +local keyLess = Types.keyLess -local function isArray(t: any, emptyMap: boolean): boolean - if Types.isObject(t) then - return false - end - local n = #t - if n == 0 then - return next(t) == nil and not emptyMap - end - local c = 0 - for _ in next, t do - c += 1 - end - return c == n -end +local isArray = Types.isArray Codec.isArray = isArray local function enc(st: ESt, v: any, depth: number): boolean diff --git a/src/Formats/data/toml/Decode.luau b/src/Formats/data/toml/Decode.luau index b03b941..7c2dab6 100644 --- a/src/Formats/data/toml/Decode.luau +++ b/src/Formats/data/toml/Decode.luau @@ -3,6 +3,7 @@ -- their key order; arrays are arrays; datetimes are Types.Date values. Checks the 1.0 validity rules: UTF-8, control -- characters, table / key redefinition (explicit, implicit, dotted, inline and array-of-tables), number grammar and -- 64-bit range, escapes, datetimes. Never throws: failures return nil, message, offset (0-based). +local Text = require("@formats/codecs/Text") local Types = require("@formats/Types") local Decode = {} @@ -13,16 +14,7 @@ export type Options = { bigInts: ("number" | "string")?, -- integers beyond +-2^53: "string" keeps their digits (default "number") } -local function utf8char(c: number): string - if c < 0x80 then - return char(c) - elseif c < 0x800 then - return char(0xC0 + c // 64, 0x80 + c % 64) - elseif c < 0x10000 then - return char(0xE0 + c // 4096, 0x80 + (c // 64) % 64, 0x80 + c % 64) - end - return char(0xF0 + c // 262144, 0x80 + (c // 4096) % 64, 0x80 + (c // 64) % 64, 0x80 + c % 64) -end +local utf8char = Text.utf8char local ESC: { [number]: string } = { [98] = "\b", [116] = "\t", [110] = "\n", [102] = "\f", [114] = "\r", [34] = '"', [92] = "\\" } diff --git a/src/Formats/data/toml/init.luau b/src/Formats/data/toml/init.luau index 093bca1..a019400 100644 --- a/src/Formats/data/toml/init.luau +++ b/src/Formats/data/toml/init.luau @@ -19,7 +19,7 @@ local Toml = { category = "data", extensions = { "toml" }, mime = { "application/toml" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Json" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Json", "codecs/Text" }, caps = { decode = true, encode = true, ordered = true, dates = true }, } diff --git a/src/Formats/data/yaml/Emit.luau b/src/Formats/data/yaml/Emit.luau index 00970bd..01b3ce4 100644 --- a/src/Formats/data/yaml/Emit.luau +++ b/src/Formats/data/yaml/Emit.luau @@ -120,34 +120,9 @@ local function str(s: string, ind: string, key: boolean): string return dquote(s) end -local function isArray(t: { [any]: any }): boolean - if Types.isObject(t) then - return false - end - local n = #t - if n == 0 then - return next(t) == nil - end - if next(t, n) ~= nil then - return false - end - local c = 0 - for _ in next, t do - c += 1 - end - return c == n -end +local isArray = Types.isArray -local function keyLess(a: any, b: any): boolean - local ta, tb = type(a), type(b) - if ta ~= tb then - return ta < tb - end - if ta == "number" or ta == "string" then - return a < b - end - return tostring(a) < tostring(b) -end +local keyLess = Types.keyLess type St = { out: { string }, step: number, sort: boolean, null: any, refs: { [any]: number }, anchors: { [any]: string }, nextId: number, err: string? } diff --git a/src/Formats/data/yaml/Parse.luau b/src/Formats/data/yaml/Parse.luau index b34b6ad..172ae04 100644 --- a/src/Formats/data/yaml/Parse.luau +++ b/src/Formats/data/yaml/Parse.luau @@ -6,6 +6,7 @@ -- opts.tags = "ignore"), %YAML / %TAG directives, multi-document streams, comments. Scalars resolve with the core -- schema. Not supported: complex keys ("? "), collections as keys, recursive aliases, merge keys "<<" (kept as a -- normal key). Internally raises { yamlErr } tables caught by run(); never throws past it. +local Text = require("@formats/codecs/Text") local Types = require("@formats/Types") local Base64 = require("@formats/core/Base64") @@ -116,16 +117,7 @@ local function endOfLine(s: string, p: number): boolean return c == nil or c == 10 or (c == 35 and q > p) end -local function utf8char(c: number): string - if c < 0x80 then - return char(c) - elseif c < 0x800 then - return char(0xC0 + c // 64, 0x80 + c % 64) - elseif c < 0x10000 then - return char(0xE0 + c // 4096, 0x80 + (c // 64) % 64, 0x80 + c % 64) - end - return char(0xF0 + c // 262144, 0x80 + (c // 4096) % 64, 0x80 + (c // 64) % 64, 0x80 + c % 64) -end +local utf8char = Text.utf8char -- ------------------------------------------------------------------------------------------------ resolution -- the core schema: a plain scalar's value diff --git a/src/Formats/data/yaml/init.luau b/src/Formats/data/yaml/init.luau index 3eed2c5..2b888ee 100644 --- a/src/Formats/data/yaml/init.luau +++ b/src/Formats/data/yaml/init.luau @@ -20,7 +20,7 @@ local Yaml = { category = "data", extensions = { "yaml", "yml" }, mime = { "application/yaml", "application/x-yaml", "text/yaml" }, - deps = { "core/Err", "core/Bytes", "Types", "core/Base64" }, + deps = { "core/Err", "core/Bytes", "Types", "core/Base64", "codecs/Text" }, caps = { decode = true, encode = true, ordered = true, multiDocument = true, anchors = true }, } diff --git a/src/Formats/playlist/pls/init.luau b/src/Formats/playlist/pls/init.luau index ea24213..b38abca 100644 --- a/src/Formats/playlist/pls/init.luau +++ b/src/Formats/playlist/pls/init.luau @@ -73,56 +73,6 @@ local function duration(s: string?): number? return d end --- RFC 8216 attribute list: KEY=value pairs, quoted strings may hold commas -local function attributes(s: string): { [string]: string } - local out = {} - local i, n = 1, #s - while i <= n do - local key, eq = string.match(s, "^%s*([%w%-_]+)%s*()=", i) - if not key then - break - end - i = (eq :: number) + 1 - local value - if string.sub(s, i, i) == '"' then - local j = string.find(s, '"', i + 1, true) or (n + 1) - value = string.sub(s, i + 1, j - 1) - i = j + 1 - else - local j = string.find(s, ",", i, true) or (n + 1) - value = Text.trim(string.sub(s, i, j - 1)) - i = j - end - out[string.upper(key)] = value - local c = string.find(s, ",", i, true) - if not c then - break - end - i = c + 1 - end - return out -end - --- #EXTINF:[ attr="v" ...], -local function extinf(rest: string): (number?, string?) - -- the first comma outside quoted attribute values - local comma, quoted = nil, false - for i = 1, #rest do - local c = string.byte(rest, i) - if c == 34 then - quoted = not quoted - elseif c == 44 and not quoted then - comma = i - break - end - end - local head = if comma then string.sub(rest, 1, comma - 1) else rest - local title = if comma then Text.trim(string.sub(rest, comma + 1)) else nil - local d = string.match(head, "^%s*([%-%+]?[%d%.]+)") - return duration(d), if title and title ~= "" then title else nil -end - - -- ------------------------------------------------------------------------------------------------ sniff function Pls.sniff(r: Bytes.Reader): number local s = r:peek(64) diff --git a/tests/core/bytes.luau b/tests/core/bytes.luau index 6e9cf21..7a5e85e 100644 --- a/tests/core/bytes.luau +++ b/tests/core/bytes.luau @@ -1,5 +1,6 @@ -- core/Bytes, core/Err, core/Crc32, core/Adler32, core/Input tests: every Reader / Writer method both endians, the --- sticky TRUNCATED error (never a throw), sub-readers without copies, Writer growth and patching. +-- sticky TRUNCATED error (never a throw), sub-readers without copies, Writer growth and patching, Bytes.span, the +-- MSB-first CRC-32 (MPEG-2 / bzip2 check values). local T = require("@tests/T") local Bytes = require("@formats/core/Bytes") local Err = require("@formats/core/Err") @@ -181,4 +182,22 @@ do t:check(w.code == Err.CORRUPT and w.format == "gif", "wrap a string") end +-- Bytes.span: codec argument checking +do + local b, o, n = Bytes.span("x", "hello", 1, 10) + t:check(type(b) == "buffer" and o == 1 and n == 4, "span clamps the length") + local _, _, _, e = Bytes.span("x", 5) + t:check(e and e.code == Err.ARG, "span: not a buffer") + local _, _, _, e2 = Bytes.span("x", "abc", 4) + t:check(e2 and e2.code == Err.ARG, "span: offset past the end") + local _, _, _, e3 = Bytes.span("x", "abc", 0.5) + t:check(e3 and e3.code == Err.ARG, "span: fractional offset") +end +-- the MSB-first CRC-32: CRC-32/MPEG-2 and CRC-32/BZIP2 of "123456789" +do + local nine = buffer.fromstring("123456789") + t:eq(Crc32.msb(nine, 0, 9, 0xFFFFFFFF), 0x0376E6E7, "CRC-32/MPEG-2") + t:eq(bit32.bxor(Crc32.msb(nine, 0, 9, 0xFFFFFFFF), 0xFFFFFFFF), 0xFC891918, "CRC-32/BZIP2") +end + t:done() From 139441a37bcd1106f917f257aa9fe3ed89ffdee9 Mon Sep 17 00:00:00 2001 From: 4DBug <github@bug.tools> Date: Sat, 31 Oct 2026 10:59:11 -0500 Subject: [PATCH 09/22] ws-cleanup-types: image/pnm, model/*: type lookup tables, table.create results and literals; casts for known values --- src/Formats/image/pnm/Codec.luau | 10 ++++---- src/Formats/image/pnm/init.luau | 27 +++++++++++----------- src/Formats/model/dae/Read.luau | 26 ++++++++++----------- src/Formats/model/dae/Write.luau | 4 ++-- src/Formats/model/dae/init.luau | 2 +- src/Formats/model/fbx/Ascii.luau | 12 +++++----- src/Formats/model/fbx/Binary.luau | 4 ++-- src/Formats/model/fbx/Read.luau | 12 +++++----- src/Formats/model/fbx/Write.luau | 24 +++++++++---------- src/Formats/model/fbx/init.luau | 2 +- src/Formats/model/gltf/Read.luau | 12 +++++----- src/Formats/model/gltf/Write.luau | 4 ++-- src/Formats/model/gltf/init.luau | 2 +- src/Formats/model/obj/Mtl.luau | 4 ++-- src/Formats/model/obj/init.luau | 15 ++++++------ src/Formats/model/off/init.luau | 10 ++++---- src/Formats/model/ply/init.luau | 38 +++++++++++++++---------------- src/Formats/model/stl/init.luau | 2 +- src/Formats/model/usda/Build.luau | 12 +++++----- src/Formats/model/usda/Parse.luau | 10 ++++---- src/Formats/model/usda/Write.luau | 28 +++++++++++------------ src/Formats/model/usda/init.luau | 8 +++---- src/Formats/model/vox/init.luau | 8 +++---- 23 files changed, 139 insertions(+), 137 deletions(-) diff --git a/src/Formats/image/pnm/Codec.luau b/src/Formats/image/pnm/Codec.luau index 5bc6285..846492e 100644 --- a/src/Formats/image/pnm/Codec.luau +++ b/src/Formats/image/pnm/Codec.luau @@ -123,7 +123,7 @@ function Codec.pack(s: buffer, n: number, ch: number, maxval: number, invert: bo r, g, b, a = get(q), get(q + 1), get(q + 2), get(q + 3) end if fmt == 0 then - writeu32(dst, i * 4, r + g * 256 + b * 65536 + a * 16777216) + writeu32(dst, i * 4, r + g * 256 + b * 65536 + (a :: number) * 16777216) elseif fmt == 1 then writeu8(dst, i * 3, r) writeu8(dst, i * 3 + 1, g) @@ -132,12 +132,12 @@ function Codec.pack(s: buffer, n: number, ch: number, maxval: number, invert: bo writeu8(dst, i, r) elseif fmt == 3 then writeu8(dst, i * 2, r) - writeu8(dst, i * 2 + 1, a) + writeu8(dst, i * 2 + 1, a :: number) elseif fmt == 4 then writeu16(dst, i * 8, r) writeu16(dst, i * 8 + 2, g) writeu16(dst, i * 8 + 4, b) - writeu16(dst, i * 8 + 6, a) + writeu16(dst, i * 8 + 6, a :: number) elseif fmt == 5 then writeu16(dst, i * 2, r) end @@ -217,9 +217,9 @@ function Codec.extract(px: buffer, fmt: number, n: number, ch: number, wide: boo for c = 0, vals - 1 do local v if ch <= 2 then - v = if c == 0 then gray else a + v = if c == 0 then gray else a :: number else - v = if c == 0 then r elseif c == 1 then g elseif c == 2 then b else a + v = if c == 0 then r elseif c == 1 then g elseif c == 2 then b else a :: number end if wide and not w16 then v *= 257 diff --git a/src/Formats/image/pnm/init.luau b/src/Formats/image/pnm/init.luau index 237e474..0984971 100644 --- a/src/Formats/image/pnm/init.luau +++ b/src/Formats/image/pnm/init.luau @@ -38,8 +38,8 @@ export type EncodeOptions = { } -- ------------------------------------------------------------------------------------------------ constants -local FMT_CODE = { rgba8 = 0, rgb8 = 1, gray8 = 2, graya8 = 3, rgba16 = 4, gray16 = 5, rgbaf32 = 6 } -local BPP = { rgba8 = 4, rgb8 = 3, gray8 = 1, graya8 = 2, rgba16 = 8, gray16 = 2, rgbaf32 = 16 } +local FMT_CODE: { [string]: number } = { rgba8 = 0, rgb8 = 1, gray8 = 2, graya8 = 3, rgba16 = 4, gray16 = 5, rgbaf32 = 6 } +local BPP: { [string]: number } = { rgba8 = 4, rgb8 = 3, gray8 = 1, graya8 = 2, rgba16 = 8, gray16 = 2, rgbaf32 = 16 } local readu8 = buffer.readu8 -- ------------------------------------------------------------------------------------------------ sniff @@ -106,7 +106,7 @@ function Pnm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E end local kind = string.char(readu8(b, r.base + 1)) local p = r.base + 2 - local w, h, maxval, ch, mode + local w: number?, h: number?, maxval: number?, ch: number, mode: number local bits = false -- PBM: 1 = black local bw = false -- PAM BLACKANDWHITE: 1 = white local tupl: string? = nil @@ -137,9 +137,9 @@ function Pnm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E end ch = if kind == "3" or kind == "6" or kind == "F" then 3 else 1 bits = kind == "1" or kind == "4" - mode = if kind == "1" then 4 elseif kind == "2" or kind == "3" then 3 elseif kind == "4" then 0 elseif maxval > 255 then 2 else 1 + mode = if kind == "1" then 4 elseif kind == "2" or kind == "3" then 3 elseif kind == "4" then 0 elseif (maxval :: number) > 255 then 2 else 1 elseif kind == "7" then - local depth + local depth: number? while true do local key key, p = token(b, p, limit) @@ -175,15 +175,16 @@ function Pnm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E if w == nil or h == nil or depth == nil or maxval == nil then return nil, Err.new(Err.CORRUPT, "PAM header misses WIDTH / HEIGHT / DEPTH / MAXVAL", p) end - if depth < 1 or depth > 4 then - return nil, Err.new(Err.UNSUPPORTED, "PAM depth " .. depth) + if (depth :: number) < 1 or (depth :: number) > 4 then + return nil, Err.new(Err.UNSUPPORTED, "PAM depth " .. (depth :: number)) end - ch = depth - bw = tupl ~= nil and string.sub(tupl, 1, 13) == "BLACKANDWHITE" - mode = if maxval > 255 then 2 else 1 + ch = depth :: number + bw = tupl ~= nil and string.sub(tupl :: string, 1, 13) == "BLACKANDWHITE" + mode = if (maxval :: number) > 255 then 2 else 1 else return nil, Err.new(Err.CORRUPT, "not a Netpbm file", r.base) end + local w, h, maxval = w :: number, h :: number, maxval :: number -- each branch above returns when one is nil if w < 1 or h < 1 or maxval < 1 or maxval > 65535 then return nil, Err.new(Err.CORRUPT, string.format("bad size %d x %d or maxval %d", w, h, maxval)) end @@ -221,7 +222,7 @@ function Pnm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E if not ok then return nil, Err.new(if e == "truncated" then Err.TRUNCATED else Err.CORRUPT, tostring(e)) end - local fmt = "rgba8" + local fmt: Types.PixelFormat = "rgba8" if native then local wide = maxval > 255 if bits or bw or ch == 1 then @@ -260,7 +261,7 @@ function Pnm.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) if fc == nil then return nil, Err.new(Err.ARG, "unsupported pixel format " .. tostring(img.format)) end - local w, h = img.width, img.height + local w: number, h: number = img.width, img.height if type(w) ~= "number" or type(h) ~= "number" or w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(img.pixels) < w * h * BPP[img.format] then return nil, Err.new(Err.ARG, "bad image size or pixel buffer") end @@ -301,7 +302,7 @@ function Pnm.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) end local ascii = o.ascii == true local wideSrc = img.format == "gray16" or img.format == "rgba16" or img.format == "rgbaf32" - local maxval = o.maxval or (if wideSrc then 65535 else 255) + local maxval: number = o.maxval or (if wideSrc then 65535 else 255) if type(maxval) ~= "number" or maxval < 1 or maxval > 65535 or maxval % 1 ~= 0 then return nil, Err.new(Err.ARG, "maxval must be 1..65535") end diff --git a/src/Formats/model/dae/Read.luau b/src/Formats/model/dae/Read.luau index 82bbb59..1629030 100644 --- a/src/Formats/model/dae/Read.luau +++ b/src/Formats/model/dae/Read.luau @@ -24,7 +24,7 @@ local children, child, text = Xml.children, Xml.child, Xml.text local MIME = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", tga = "image/tga", bmp = "image/bmp", gif = "image/gif", webp = "image/webp", dds = "image/vnd-ms.dds", tif = "image/tiff", tiff = "image/tiff", ktx2 = "image/ktx2", hdr = "image/vnd.radiance", exr = "image/x-exr", psd = "image/vnd.adobe.photoshop" } local WRAP = { WRAP = "repeat", MIRROR = "mirror", CLAMP = "clamp", BORDER = "clamp", MIRROR_ONCE = "mirror", NONE = "clamp" } -local PARAM_SIZE = { float2 = 2, float3 = 3, float4 = 4, float2x2 = 4, float3x3 = 9, float4x4 = 16, int2 = 2, int3 = 3, int4 = 4 } +local PARAM_SIZE: { [string]: number } = { float2 = 2, float3 = 3, float4 = 4, float2x2 = 4, float3x3 = 9, float4x4 = 16, int2 = 2, int3 = 3, int4 = 4 } local MEMBER = { X = 1, Y = 2, Z = 3, ANGLE = 4, W = 4, R = 1, G = 2, B = 3, A = 4, S = 1, T = 2, U = 1, V = 2, P = 3, Q = 4 } -- ------------------------------------------------------------------------------------------------ helpers @@ -353,7 +353,7 @@ local function texture(C: Ctx, params: { [string]: any }, samplerSid: string): n local f = upper(match(text(mag), "[%w_]+") or "") smp.filter = if f == "NEAREST" then "nearest" elseif f == "LINEAR" then "linear" else nil end - if next(smp) then + if next(smp :: any) then tex.sampler = smp end end @@ -728,7 +728,7 @@ local function buildPrim(C: Ctx, prim: any, verticesEl: any, kind: string): Buil local np = #p local keyOf: { [any]: number } = {} local tuples: { number } = {} -- the first p index of each output vertex's tuple - local corner = table.create(#starts) + local corner = table.create(#starts) :: { number } local count = 0 for ci, s in starts do local base = s * stride @@ -803,7 +803,7 @@ local function buildPrim(C: Ctx, prim: any, verticesEl: any, kind: string): Buil mode = "triangles" elseif C.triangulate then -- fan triangulation - local tri = {} + local tri: { number } = {} local at = 0 for _, f in faces do for k = 1, f - 2 do @@ -1067,13 +1067,13 @@ local function camera(C: Ctx, el: any): number? local tx, ty = math.tan(math.rad(numText(xfov, 45)) / 2), math.tan(yf / 2) ar = if ty > 0 then tx / ty else nil end - cam = { name = attr(el, "name") or attr(el, "id"), type = "perspective", yfov = yf, aspect = ar, znear = numText(child(persp, "znear"), 0.1), zfar = numText(child(persp, "zfar"), 1000) } + cam = { name = attr(el, "name") or attr(el, "id"), type = "perspective" :: "perspective", yfov = yf, aspect = ar, znear = numText(child(persp, "znear"), 0.1), zfar = numText(child(persp, "zfar"), 1000) } :: Types.Camera elseif ortho then local xm, ym = child(ortho, "xmag"), child(ortho, "ymag") local ar = numText(child(ortho, "aspect_ratio"), 1) local x = if xm then numText(xm, 1) else numText(ym, 1) * ar local y = if ym then numText(ym, 1) else numText(xm, 1) / ar - cam = { name = attr(el, "name") or attr(el, "id"), type = "orthographic", xmag = x, ymag = y, znear = numText(child(ortho, "znear"), 0.1), zfar = numText(child(ortho, "zfar"), 1000) } + cam = { name = attr(el, "name") or attr(el, "id"), type = "orthographic" :: "orthographic", xmag = x, ymag = y, znear = numText(child(ortho, "znear"), 0.1), zfar = numText(child(ortho, "zfar"), 1000) } :: Types.Camera else return nil end @@ -1091,7 +1091,7 @@ local function light(C: Ctx, el: any): (number?, { number }?) if amb then return nil, color(amb) or { 1, 1, 1, 1 } end - local kinds = { directional = "directional", point = "point", spot = "spot" } + local kinds: { [string]: string } = { directional = "directional", point = "point", spot = "spot" } for k, t in kinds do local l = child(tc, k) if l then @@ -1518,7 +1518,7 @@ local function sample(c: Curve, t: number): { number } local inp, out, st = c.input, c.output, c.stride local n = #inp local function at(i: number): { number } - local r = table.create(st) + local r = table.create(st) :: { number } for k = 1, st do r[k] = out[(i - 1) * st + k] or 0 end @@ -1561,7 +1561,7 @@ local function target(C: Ctx, s: string): ({ number }?, any, number?) if not id then return nil, nil, nil end - local spath, rest = match(sids, "^([^%.%(]*)(.*)$") + local spath, rest = match(sids :: string, "^([^%.%(]*)(.*)$") if not spath then return nil, nil, nil end @@ -1734,9 +1734,9 @@ local function bake(C: Ctx, name: string?, byNode: { [number]: { Curve } }, orde buffer.writef32(ib, (i - 1) * 4, t) end local input = Scene.accessor(ib, "f32", 1, n) - table.insert(channels, { node = ni, path = "translation", input = input, output = Scene.accessor(tb, "f32", 3, n), interpolation = "LINEAR" }) - table.insert(channels, { node = ni, path = "rotation", input = input, output = Scene.accessor(rb, "f32", 4, n), interpolation = "LINEAR" }) - table.insert(channels, { node = ni, path = "scale", input = input, output = Scene.accessor(sb, "f32", 3, n), interpolation = "LINEAR" }) + table.insert(channels, { node = ni, path = "translation", input = input, output = Scene.accessor(tb, "f32", 3, n), interpolation = "LINEAR" } :: Types.Channel) + table.insert(channels, { node = ni, path = "rotation", input = input, output = Scene.accessor(rb, "f32", 4, n), interpolation = "LINEAR" } :: Types.Channel) + table.insert(channels, { node = ni, path = "scale", input = input, output = Scene.accessor(sb, "f32", 3, n), interpolation = "LINEAR" } :: Types.Channel) -- the node is now TRS-driven local node = C.scene.nodes[ni] if node.matrix then @@ -1829,7 +1829,7 @@ function Read.scene(doc: any, fetch: Fetch, opts: any?): (Types.Scene?, Err.Err? local asset = child(root, "asset") local up = asset and child(asset, "up_axis") local upAxis = if up then upper(match(text(up), "[%w_]+") or "Y_UP") else "Y_UP" - scene.meta.up = if upAxis == "Z_UP" then "z" elseif upAxis == "X_UP" then "x" :: any else "y" + scene.meta.up = if upAxis == "Z_UP" then "z" :: "z" elseif upAxis == "X_UP" then "x" :: any else "y" :: "y" local unit = asset and child(asset, "unit") local meter = unit and attr(unit, "meter") scene.meta.unit = if meter then tonumber(meter) or tonumber((string.gsub(meter, ",", "."))) or 1 else 1 diff --git a/src/Formats/model/dae/Write.luau b/src/Formats/model/dae/Write.luau index 86e6d2a..3e77c67 100644 --- a/src/Formats/model/dae/Write.luau +++ b/src/Formats/model/dae/Write.luau @@ -157,7 +157,7 @@ function Write.build(scene: Types.Scene, opts: any?): string? table.insert(out, s) end w('<?xml version="1.0" encoding="utf-8"?>\n<COLLADA xmlns="http://www.collada.org/2005/11/COLLADASchema" version="1.4.1">\n') - local meta = scene.meta or {} + local meta: { [string]: any } = scene.meta or {} local up = if meta.up == "z" then "Z_UP" elseif meta.up == "x" then "X_UP" else "Y_UP" w(format('<asset><contributor><authoring_tool>formats-luau</authoring_tool></contributor><created>1970-01-01T00:00:00Z</created><modified>1970-01-01T00:00:00Z</modified><unit meter="%s" name="unit"/><up_axis>%s</up_axis></asset>\n', f(meta.unit or 1), up)) -- images @@ -189,7 +189,7 @@ function Write.build(scene: Types.Scene, opts: any?): string? w("<library_effects>\n") for i, mat in scene.materials do local ph: any = mat.extras and mat.extras.phong or {} - local params = {} + local params: { [any]: any } = {} -- the newparam strings, and their sids as seen-keys local function texParam(ref: Types.TextureRef?): (string?, number?) if not ref or not imageId[ref.texture] then return nil, nil diff --git a/src/Formats/model/dae/init.luau b/src/Formats/model/dae/init.luau index 1e245b1..b764198 100644 --- a/src/Formats/model/dae/init.luau +++ b/src/Formats/model/dae/init.luau @@ -117,7 +117,7 @@ local function zae(r: Bytes.Reader): (any, string?, Err.Err?) local manifest = zip:readString("manifest.xml") if manifest then local d = Xml.decode(manifest) - local rootEl = d and d.root and Xml.child(d.root, "dae_root") + local rootEl = d and d.root and Xml.child(d.root :: Xml.Node, "dae_root") if rootEl then main = string.match(Xml.text(rootEl), "^%s*(.-)%s*$") main = main and string.gsub(main, "^%./", "") diff --git a/src/Formats/model/fbx/Ascii.luau b/src/Formats/model/fbx/Ascii.luau index 318b1b7..a7c14d0 100644 --- a/src/Formats/model/fbx/Ascii.luau +++ b/src/Formats/model/fbx/Ascii.luau @@ -63,17 +63,17 @@ function Ascii.parse(text: string, opts: { maxBytes: number? }?): (Node?, any, n -- the values of one node (after the ':'), up to a new name, '{' or '}' local function values(): ({ any }?, string?) - local props = {} + local props: { any } = {} while true do skip() if i > n then - return props + return props, nil end local c = sbyte(text, i) if c == 44 then -- , i += 1 elseif c == 123 or c == 125 then - return props + return props, nil elseif c == 34 then -- " local e = sfind(text, "\"", i + 1, true) if not e then @@ -117,7 +117,7 @@ function Ascii.parse(text: string, opts: { maxBytes: number? }?): (Node?, any, n else local nm = nameAt() if nm then - return props + return props, nil end local s, e = sfind(text, "^[%w_]+", i) if not s then @@ -230,7 +230,7 @@ function Ascii.write(root: any, version: number?): string table.insert(parts, string.sub(v, 2)) else local nm, cls = string.match(v, "^(.-)%z\1(.*)$") - local sv = if nm then cls .. "::" .. nm else v + local sv = if nm then (cls :: string) .. "::" .. nm else v table.insert(parts, "\"" .. string.gsub(sv, "\"", """) .. "\"") end elseif tv == "table" and v.array then @@ -246,7 +246,7 @@ function Ascii.write(root: any, version: number?): string end end if arr then - local vals = table.create(arr.count) + local vals = table.create(arr.count) :: { string } for k = 0, arr.count - 1 do vals[k + 1] = fmt(buffer.readf64(arr.data, k * 8)) end diff --git a/src/Formats/model/fbx/Binary.luau b/src/Formats/model/fbx/Binary.luau index 9ae5683..a1ea942 100644 --- a/src/Formats/model/fbx/Binary.luau +++ b/src/Formats/model/fbx/Binary.luau @@ -38,7 +38,7 @@ local function i64(b: buffer, p: number, asString: boolean): any end Binary.i64 = i64 -local ELEM = { f = 4, d = 8, l = 8, i = 4, b = 1, c = 1 } +local ELEM: { [string]: number } = { f = 4, d = 8, l = 8, i = 4, b = 1, c = 1 } -- the elements of a raw array (n elements of type t at p) as f64s local function toF64(t: string, src: buffer, p: number, n: number): buffer @@ -170,7 +170,7 @@ function Binary.parse(b: buffer, base: number, limit: number, opts: { maxBytes: plen = readu32(b, p + 16) + readu32(b, p + 20) * 4294967296 nlen = readu8(b, p + 24) else - endOff, nprops, plen, nlen = readu32(b, p), readu32(b, p + 4), readu32(b, p + 8), readu8(b, p + 12) + endOff, nprops, plen, nlen = readu32(b, p), readu32(b, p + 4), readu32(b, p + 8), (readu8(b, p + 12)) end if endOff == 0 then return false, p + head diff --git a/src/Formats/model/fbx/Read.luau b/src/Formats/model/fbx/Read.luau index 79b515d..aa9ea4d 100644 --- a/src/Formats/model/fbx/Read.luau +++ b/src/Formats/model/fbx/Read.luau @@ -1058,7 +1058,7 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ local near, far = pnum(p, "NearPlane", 10), pnum(p, "FarPlane", 4000) if ortho then local zoom = pnum(p, "OrthoZoom", 1) - cam = { name = a.name ~= "" and a.name or o.name, type = "orthographic", xmag = zoom * aspect, ymag = zoom, znear = near, zfar = far } + cam = { name = a.name ~= "" and a.name or o.name, type = "orthographic", xmag = zoom * aspect, ymag = zoom, znear = near, zfar = far } :: Types.Camera else local focal = pnum(p, "FocalLength", 0) local hfov @@ -1068,7 +1068,7 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ hfov = pnum(p, "FieldOfView", 40) * math.pi / 180 end local yfov = 2 * math.atan(math.tan(hfov / 2) / aspect) - cam = { name = a.name ~= "" and a.name or o.name, type = "perspective", yfov = yfov, aspect = aspect, znear = near, zfar = far } + cam = { name = a.name ~= "" and a.name or o.name, type = "perspective", yfov = yfov, aspect = aspect, znear = near, zfar = far } :: Types.Camera end table.insert(scene.cameras, cam) table.insert(scene.nodes, { name = o.name .. "_camera", children = {}, camera = #scene.cameras, rotation = { 0, -orient, 0, orient }, extras = { fbx = { orientation = "camera" } } }) @@ -1317,13 +1317,13 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ return false end if tr.curves.T or varies(T, 3, nd.translation or { 0, 0, 0 }) then - table.insert(anim.channels, { node = ni, path = "translation", input = input, output = f32acc(T, 3), interpolation = interp }) + table.insert(anim.channels, { node = ni, path = "translation", input = input, output = f32acc(T, 3), interpolation = interp } :: Types.Channel) end if tr.curves.R or varies(R, 4, nd.rotation or { 0, 0, 0, 1 }) then - table.insert(anim.channels, { node = ni, path = "rotation", input = input, output = f32acc(R, 4), interpolation = interp }) + table.insert(anim.channels, { node = ni, path = "rotation", input = input, output = f32acc(R, 4), interpolation = interp } :: Types.Channel) end if tr.curves.S or varies(S, 3, nd.scale or { 1, 1, 1 }) then - table.insert(anim.channels, { node = ni, path = "scale", input = input, output = f32acc(S, 3), interpolation = interp }) + table.insert(anim.channels, { node = ni, path = "scale", input = input, output = f32acc(S, 3), interpolation = interp } :: Types.Channel) end end end @@ -1348,7 +1348,7 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ end end local acc = f32acc(out, 1) - table.insert(anim.channels, { node = ni, path = "weights", input = f32acc(times, 1), output = acc, interpolation = if allConstant(cs) then "STEP" else "LINEAR" }) + table.insert(anim.channels, { node = ni, path = "weights", input = f32acc(times, 1), output = acc, interpolation = if allConstant(cs) then "STEP" else "LINEAR" } :: Types.Channel) end end end diff --git a/src/Formats/model/fbx/Write.luau b/src/Formats/model/fbx/Write.luau index 060af47..6d16eab 100644 --- a/src/Formats/model/fbx/Write.luau +++ b/src/Formats/model/fbx/Write.luau @@ -91,7 +91,7 @@ local function faces(prim: Types.Primitive): { { number } }? if p + sz > count then break end - local poly = table.create(sz) + local poly = table.create(sz) :: { number } for q = 0, sz - 1 do poly[q + 1] = I(p + q) end @@ -148,9 +148,9 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?) local nodes = scene.nodes or {} -- ------------------------------------------------------------------------------------------ textures - local EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/bmp"] = "bmp", ["image/webp"] = "webp", ["image/x-tga"] = "tga", ["image/vnd-ms.dds"] = "dds", ["image/tiff"] = "tif" } + local EXT: { [string]: string } = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/bmp"] = "bmp", ["image/webp"] = "webp", ["image/x-tga"] = "tga", ["image/vnd-ms.dds"] = "dds", ["image/tiff"] = "tif" } local texIds: { [number]: number } = {} - local base = opts and opts.name and string.gsub(string.match(opts.name, "([^/\\]+)$") or opts.name, "%.[^.]*$", "") or "model" + local base: string = opts and opts.name and string.gsub(string.match(opts.name, "([^/\\]+)$") or opts.name, "%.[^.]*$", "") or "model" for ti, tex in scene.textures or {} do local file = tex.uri or (base .. "_" .. (tex.name or tostring(ti)) .. "." .. (EXT[tex.mime or ""] or "png")) local tname = tex.name or ("Texture" .. ti) @@ -295,14 +295,14 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?) end visiting[i] = true local nd = nodes[i] - local l = if nd.matrix and #nd.matrix == 16 then nd.matrix else Xform.compose(nd.translation, nd.rotation, nd.scale) + local l = if nd.matrix and #(nd.matrix :: Xform.M4) == 16 then nd.matrix else Xform.compose(nd.translation, nd.rotation, nd.scale) local p = parentOf[i] local w = if p then Xform.mul(world(p), l) else l worldM[i] = w return w end local function trs(nd: Types.Node): ({ number }, { number }, { number }) - if nd.matrix and #nd.matrix == 16 then + if nd.matrix and #(nd.matrix :: Xform.M4) == 16 then return Xform.decompose(nd.matrix) end return nd.translation or { 0, 0, 0 }, nd.rotation or { 0, 0, 0, 1 }, nd.scale or { 1, 1, 1 } @@ -505,7 +505,7 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?) for v = 0, n - 1 do local u, w = 0, 0 if T then - u, w = T(v, 0), T(v, 1) + u, w = T(v, 0), (T(v, 1)) end table.insert(UV[k], u) table.insert(UV[k], if flipV then 1 - w else w) @@ -647,8 +647,8 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?) end for _, l in layout do local tg = l.prim.targets and (l.prim.targets :: any)[t] - local TP = tg and accessorReader(tg.POSITION) - local TN = tg and accessorReader(tg.NORMAL) + local TP: ((i: number, c: number) -> number)? = tg and accessorReader(tg.POSITION) + local TN: ((i: number, c: number) -> number)? = tg and accessorReader(tg.NORMAL) if TP then for v = 0, l.prim.attributes.POSITION.count - 1 do local x, y, z = TP(v, 0), TP(v, 1), TP(v, 2) @@ -822,7 +822,7 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?) local PATH = { translation = { "T", "Lcl Translation", 3 }, rotation = { "R", "Lcl Rotation", 4 }, scale = { "S", "Lcl Scaling", 3 } } for ai, anim in scene.animations or {} do local stid, lid = id(), id() - local astart, astop = math.huge, -math.huge + local astart: number, astop: number = math.huge, -math.huge local layerNodes = {} for _, ch in anim.channels do local mid = modelIds[ch.node] @@ -834,7 +834,7 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?) local times = table.create(n, 0) for k = 0, n - 1 do times[k + 1] = IN(k, 0) - astart, astop = math.min(astart, times[k + 1]), math.max(astop, times[k + 1]) + astart, astop = math.min(astart, times[k + 1]), (math.max(astop, times[k + 1])) end local cubic = ch.interpolation == "CUBICSPLINE" local step = ch.interpolation == "STEP" @@ -919,8 +919,8 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?) end -- ------------------------------------------------------------------------------------------ document - local meta = scene.meta or {} - local src = type(meta.source) == "table" and meta.source or {} + local meta: { [string]: any } = scene.meta or {} + local src: { [string]: any } = type(meta.source) == "table" and meta.source or {} local up = if meta.up == "z" then 2 else 1 local upSign, front, frontSign, coord, coordSign = 1, 2, 1, 0, 1 if up == 2 then diff --git a/src/Formats/model/fbx/init.luau b/src/Formats/model/fbx/init.luau index fa47b1a..f20cd90 100644 --- a/src/Formats/model/fbx/init.luau +++ b/src/Formats/model/fbx/init.luau @@ -148,7 +148,7 @@ function Fbx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E if not scene then return nil, err end - scene.meta.source.binary = binary + (scene.meta.source :: { [string]: any }).binary = binary return scene, nil end diff --git a/src/Formats/model/gltf/Read.luau b/src/Formats/model/gltf/Read.luau index ab59fe6..101a3e5 100644 --- a/src/Formats/model/gltf/Read.luau +++ b/src/Formats/model/gltf/Read.luau @@ -24,7 +24,7 @@ local SIZE = { [5120] = 1, [5121] = 1, [5122] = 2, [5123] = 2, [5125] = 4, [5126 local TYPE_COMPONENTS = { SCALAR = 1, VEC2 = 2, VEC3 = 3, VEC4 = 4, MAT2 = 4, MAT3 = 9, MAT4 = 16 } local TYPE_COLUMNS = { MAT2 = 2, MAT3 = 3, MAT4 = 4 } local MODES = { [0] = "points", [1] = "lines", [2] = "line_loop", [3] = "line_strip", [4] = "triangles", [5] = "triangle_strip", [6] = "triangle_fan" } -local WRAP = { [33071] = "clamp", [33648] = "mirror", [10497] = "repeat" } +local WRAP: { [number]: "clamp" | "mirror" | "repeat" } = { [33071] = "clamp", [33648] = "mirror", [10497] = "repeat" } local MIN_FILTER = { [9728] = "nearest", [9729] = "linear", [9984] = "nearest_mipmap_nearest", [9985] = "linear_mipmap_nearest", [9986] = "nearest_mipmap_linear", [9987] = "linear_mipmap_linear" } -- the extensions this reader understands (everything else that is required -> UNSUPPORTED) local KNOWN = { @@ -78,7 +78,7 @@ local function numbers(v: any, n: number): { number }? return nil end end - return table.move(v, 1, n, 1, {}) + return table.move(v, 1, n, 1, {} :: { number }) end -- extras.gltf: the JSON extras and the extensions not turned into Scene fields @@ -449,13 +449,13 @@ function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Sc return nil, Err.new(Err.CORRUPT, "bad indices accessor") end -- indices must reference existing vertices - local get = Types.Scene.reader(ind) :: any + local get = Types.Scene.reader(ind :: Types.Accessor) :: any for q = 0, ind.count - 1 do if get(q, 0) >= count then return nil, Err.new(Err.CORRUPT, "index out of range") end end - prim.indices = ind + prim.indices = ind :: Types.Accessor end if type(p.targets) == "table" then local targets = {} @@ -484,10 +484,10 @@ function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Sc end if c.type == "orthographic" and type(c.orthographic) == "table" then local o = c.orthographic - table.insert(scene.cameras, { name = str(c.name), type = "orthographic", xmag = num(o.xmag, 1), ymag = num(o.ymag, 1), znear = num(o.znear, 0), zfar = num(o.zfar, 100) }) + table.insert(scene.cameras, { name = str(c.name), type = "orthographic" :: "orthographic", xmag = num(o.xmag, 1), ymag = num(o.ymag, 1), znear = num(o.znear, 0), zfar = num(o.zfar, 100) } :: Types.Camera) else local p = if type(c.perspective) == "table" then c.perspective else {} - table.insert(scene.cameras, { name = str(c.name), type = "perspective", yfov = num(p.yfov, 0.8), aspect = if type(p.aspectRatio) == "number" then p.aspectRatio else nil, znear = num(p.znear, 0.01), zfar = if type(p.zfar) == "number" then p.zfar else nil }) + table.insert(scene.cameras, { name = str(c.name), type = "perspective" :: "perspective", yfov = num(p.yfov, 0.8), aspect = if type(p.aspectRatio) == "number" then p.aspectRatio else nil, znear = num(p.znear, 0.01), zfar = if type(p.zfar) == "number" then p.zfar else nil } :: Types.Camera) end end local lp = type(doc.extensions) == "table" and doc.extensions.KHR_lights_punctual diff --git a/src/Formats/model/gltf/Write.luau b/src/Formats/model/gltf/Write.luau index 473f293..4932462 100644 --- a/src/Formats/model/gltf/Write.luau +++ b/src/Formats/model/gltf/Write.luau @@ -385,7 +385,7 @@ function Write.build(scene: Types.Scene, opts: Options?): (Out?, Err.Err?) end local gp = object() gp.attributes = object() - local names = {} + local names: { string } = {} for name in p.attributes do table.insert(names, name) end @@ -603,7 +603,7 @@ function Write.build(scene: Types.Scene, opts: Options?): (Out?, Err.Err?) return nil, failure end -- scenes: the original list (meta.gltf.scenes) when it is there, else the roots - local meta = if type(scene.meta) == "table" then scene.meta else {} + local meta: { [string]: any } = if type(scene.meta) == "table" then scene.meta else {} local mg = type(meta.gltf) == "table" and meta.gltf or {} local scenes = {} if type(mg.scenes) == "table" and #mg.scenes > 0 then diff --git a/src/Formats/model/gltf/init.luau b/src/Formats/model/gltf/init.luau index 3f533a0..215778e 100644 --- a/src/Formats/model/gltf/init.luau +++ b/src/Formats/model/gltf/init.luau @@ -158,7 +158,7 @@ function Gltf.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err. end -- ------------------------------------------------------------------------------------------------ encode -local EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/webp"] = "webp", ["image/ktx2"] = "ktx2", ["image/avif"] = "avif" } +local EXT: { [string]: string } = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/webp"] = "webp", ["image/ktx2"] = "ktx2", ["image/avif"] = "avif" } function Gltf.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) if type(scene) ~= "table" or scene.kind ~= "scene" then diff --git a/src/Formats/model/obj/Mtl.luau b/src/Formats/model/obj/Mtl.luau index 64f18de..95d29bd 100644 --- a/src/Formats/model/obj/Mtl.luau +++ b/src/Formats/model/obj/Mtl.luau @@ -104,7 +104,7 @@ function Mtl.toMaterial(e: Entry, texture: (Map) -> number): Types.Material if kd and #kd >= 3 then m.baseColor = { kd[1], kd[2], kd[3], 1 } end - local d = if v.d then v.d[1] elseif v.Tr then 1 - v.Tr[1] else 1 + local d = if v.d then (v.d :: { number })[1] elseif v.Tr then 1 - (v.Tr :: { number })[1] else 1 m.baseColor[4] = d if d < 1 then m.alphaMode = "blend" @@ -113,7 +113,7 @@ function Mtl.toMaterial(e: Entry, texture: (Map) -> number): Types.Material if ke and #ke >= 3 then m.emissive = { ke[1], ke[2], ke[3] } end - m.metallic = if v.Pm then v.Pm[1] else 0 + m.metallic = if v.Pm then (v.Pm :: { number })[1] else 0 if v.Pr then m.roughness = v.Pr[1] elseif v.Ns then diff --git a/src/Formats/model/obj/init.luau b/src/Formats/model/obj/init.luau index f39a894..1eaf272 100644 --- a/src/Formats/model/obj/init.luau +++ b/src/Formats/model/obj/init.luau @@ -192,6 +192,7 @@ function Obj.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E if key == nil or string.sub(key, 1, 1) == "#" then continue end + local rest: string = rest :: string -- both captures match together local hash = string.find(rest, "#", 1, true) if hash then rest = string.gsub(string.sub(rest, 1, hash - 1), "%s+$", "") @@ -513,14 +514,14 @@ local function nameOk(s: string): string return t end -local EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/webp"] = "webp", ["image/gif"] = "gif", ["image/bmp"] = "bmp", ["image/ktx2"] = "ktx2" } +local EXT: { [string]: string } = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/webp"] = "webp", ["image/gif"] = "gif", ["image/bmp"] = "bmp", ["image/ktx2"] = "ktx2" } function Obj.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) if type(scene) ~= "table" or scene.kind ~= "scene" or type(scene.nodes) ~= "table" or type(scene.meshes) ~= "table" then return nil, Err.new(Err.ARG, "needs a Scene") end local flipV = not (opts and opts.flipV == false) - local base = opts and opts.name and string.gsub(string.match(opts.name, "([^/\\]+)$") or opts.name, "%.[^.]*$", "") or "model" + local base: string = opts and opts.name and string.gsub(string.match(opts.name, "([^/\\]+)$") or opts.name, "%.[^.]*$", "") or "model" local mtlName = opts and opts.mtlName or (base .. ".mtl") local files = opts and opts.files local placed = Types.Scene.flatten(scene) @@ -586,9 +587,9 @@ function Obj.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err table.insert(out, "o " .. nameOk(node.name or ("node_" .. pl.node))) end local n = pos.count - local Cc = if attrs.COLOR_0 and not (opts and opts.colors == false) then Types.Scene.reader(attrs.COLOR_0) else nil - local T = if attrs.TEXCOORD_0 and not (opts and opts.texcoords == false) then Types.Scene.reader(attrs.TEXCOORD_0) else nil - local Nr = if attrs.NORMAL and not (opts and opts.normals == false) then Types.Scene.reader(attrs.NORMAL) else nil + local Cc = if attrs.COLOR_0 and not (opts and opts.colors == false) then Types.Scene.reader(attrs.COLOR_0 :: Types.Accessor) else nil + local T = if attrs.TEXCOORD_0 and not (opts and opts.texcoords == false) then Types.Scene.reader(attrs.TEXCOORD_0 :: Types.Accessor) else nil + local Nr = if attrs.NORMAL and not (opts and opts.normals == false) then Types.Scene.reader(attrs.NORMAL :: Types.Accessor) else nil for _, a in { attrs.COLOR_0, attrs.TEXCOORD_0, attrs.NORMAL } do if a and (a.count < n or buffer.len(a.data) < a.count * a.components * (Types.COMPONENT_SIZE[a.type] or 4)) then return nil, Err.new(Err.ARG, "an attribute is shorter than POSITION") @@ -692,7 +693,7 @@ function Obj.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err if o + k > count then return nil, Err.new(Err.ARG, "faces run past the indices") end - local list = table.create(k) + local list = table.create(k) :: { number } for j = 0, k - 1 do list[j + 1] = at(o + j) end @@ -747,7 +748,7 @@ function Obj.encodeMtl(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err. if type(scene) ~= "table" or type(scene.materials) ~= "table" then return nil, Err.new(Err.ARG, "needs a Scene") end - local files = {} + local files: { [string]: string } = {} local o: any = table.clone(opts or {}) o.files = files o.mtlName = "x.mtl" diff --git a/src/Formats/model/off/init.luau b/src/Formats/model/off/init.luau index 92b4107..4c3ab8c 100644 --- a/src/Formats/model/off/init.luau +++ b/src/Formats/model/off/init.luau @@ -153,13 +153,13 @@ function Off.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E local rest = kw local st, hasC, hasN = false, false, false if string.sub(rest, 1, 2) == "ST" then - st, rest = true, string.sub(rest, 3) + st, rest = true, (string.sub(rest, 3)) end if string.sub(rest, 1, 1) == "C" then - hasC, rest = true, string.sub(rest, 2) + hasC, rest = true, (string.sub(rest, 2)) end if string.sub(rest, 1, 1) == "N" then - hasN, rest = true, string.sub(rest, 2) + hasN, rest = true, (string.sub(rest, 2)) end if rest == "4OFF" or rest == "nOFF" or rest == "4nOFF" then return nil, Err.new(Err.UNSUPPORTED, kw .. " (homogeneous / n-dimensional vertices)") @@ -442,7 +442,7 @@ function Off.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err local a: Flatten.Attr = { type = acc.type, components = acc.components, raw = raw, values = vals } if acc.count == nf then fc = a - elseif ex.faceOfTriangle then + elseif (ex :: { [string]: any }).faceOfTriangle then local fot = Flatten.numbers(ex.faceOfTriangle, true) if fot and #fot == nf then fc, fcMap = a, fot @@ -468,7 +468,7 @@ function Off.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err end p += s if fc then - local src = if fcMap then fcMap[f] else f - 1 + local src = if fcMap then (fcMap :: { number })[f] else f - 1 table.insert(line, colorText(fc, fc.values, fc.components, src)) end table.insert(out, table.concat(line, " ")) diff --git a/src/Formats/model/ply/init.luau b/src/Formats/model/ply/init.luau index 8b9350e..69ea451 100644 --- a/src/Formats/model/ply/init.luau +++ b/src/Formats/model/ply/init.luau @@ -127,8 +127,8 @@ local function parseHeader(r: Bytes.Reader): (Header?, Err.Err?) if not enc or not ENCODINGS[enc] then return nil, Err.new(Err.UNSUPPORTED, "unknown format " .. tostring(enc), lineAt) end - if string.sub(ver, 1, 1) ~= "1" then - return nil, Err.new(Err.UNSUPPORTED, "version " .. ver, lineAt) + if string.sub(ver :: string, 1, 1) ~= "1" then + return nil, Err.new(Err.UNSUPPORTED, "version " .. (ver :: string), lineAt) end h.encoding = enc elseif kw == "element" then @@ -143,7 +143,7 @@ local function parseHeader(r: Bytes.Reader): (Header?, Err.Err?) if not el then return nil, Err.new(Err.CORRUPT, "property before any element", lineAt) end - local words = {} + local words: { string } = {} for w in string.gmatch(line, "%S+") do table.insert(words, w) end @@ -153,9 +153,9 @@ local function parseHeader(r: Bytes.Reader): (Header?, Err.Err?) if not cc or not ic then return nil, Err.new(Err.CORRUPT, "unknown property type in " .. line, lineAt) end - p = { name = words[5], ply = words[4], code = ic, list = true, countPly = words[3], countCode = cc } + p = { name = words[5], ply = words[4], code = ic, list = true, countPly = words[3], countCode = cc } :: Prop elseif #words == 3 and CODES[words[2]] then - p = { name = words[3], ply = words[2], code = CODES[words[2]], list = false } + p = { name = words[3], ply = words[2], code = CODES[words[2]], list = false } :: Prop else return nil, Err.new(Err.CORRUPT, "bad property line: " .. string.sub(line, 1, 60), lineAt) end @@ -195,11 +195,11 @@ local function newPlan(e: Elem): Plan code = table.create(np, 0), isList = table.create(np, false), countCode = table.create(np, 2), - dst = table.create(np), + dst = table.create(np) :: { buffer }, dOff = table.create(np, 0), dStride = table.create(np, 0), dCode = table.create(np, 0), - sizes = table.create(np), + sizes = table.create(np) :: { buffer }, bound = table.create(np, -1), totals = table.create(np, 0), } @@ -291,7 +291,7 @@ local function readAscii(nextTok: () -> string?, e: Elem, pl: Plan): Err.Err? local listItems: { [number]: { number } } = {} for k, p in e.props do if p.list then - listSizes[k] = table.create(n) + listSizes[k] = table.create(n) :: { number } listItems[k] = {} end end @@ -485,7 +485,7 @@ function Ply.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E if not h then return nil, herr end - local vi, fi, idxK + local vi: number?, fi: number?, idxK: number for i, e in h.elems do if e.name == "vertex" and vi == nil then vi = i @@ -767,7 +767,7 @@ local function bufNumbers(b: any, code: number, count: number): { number }? if type(b) ~= "buffer" or buffer.len(b) < count * SIZE[code] then return nil end - local out = table.create(count) + local out = table.create(count) :: { number } for i = 0, count - 1 do out[i + 1] = Binary.rd(b, i * SIZE[code], code, false) end @@ -940,7 +940,7 @@ function Ply.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err if count == nf then return vals elseif fot and #fot == nf then - local out = table.create(nf) + local out = table.create(nf) :: { number } for i = 1, nf do local v = vals[fot[i] + 1] if v == nil then @@ -954,19 +954,19 @@ function Ply.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err end local extraRows: { [string]: Row } = {} if type(ex) == "table" and type(ex.faceAttributes) == "table" then - for name, acc in ex.faceAttributes do + for name: string, acc: any in ex.faceAttributes do local vals = Flatten.numbers(acc, true) local code = CODE_OF_ACC[acc.type] if vals and code and acc.components == 1 then local pv = perFace(vals, acc.count) if pv then - extraRows[name] = { kind = "s", col = { name = name, ply = PLY_NAME[code], code = code, values = pv, stride = 1, offset = 0 } } + extraRows[name] = { kind = "s" :: "s", col = { name = name, ply = PLY_NAME[code], code = code, values = pv, stride = 1, offset = 0 } } end end end end if type(ex) == "table" and type(ex.faceLists) == "table" then - for name, fl in ex.faceLists do + for name: string, fl: any in ex.faceLists do local sz = type(fl) == "table" and Flatten.numbers(fl.sizes, true) local items = type(fl) == "table" and Flatten.numbers(fl.items, true) local code = type(fl) == "table" and (CODES[fl.itemType or ""] or CODE_OF_ACC[fl.items and fl.items.type or ""]) @@ -980,7 +980,7 @@ function Ply.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err if scc and scc <= 6 and SIZE[scc] >= SIZE[lcc] then lcc = scc end - extraRows[name] = { kind = "l", col = { name = name, ply = spell(fl.itemType, code), code = code, countPly = spell(fl.countType, lcc), countCode = lcc, sizes = sz, items = items } } + extraRows[name] = { kind = "l" :: "l", col = { name = name, ply = spell(fl.itemType, code), code = code, countPly = spell(fl.countType, lcc), countCode = lcc, sizes = sz, items = items } } end end end @@ -1025,7 +1025,7 @@ function Ply.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err continue end local rows: { Row } = {} - for _, pr in el.properties do + for _, pr: any in el.properties do local code = CODES[pr.type or ""] if not code then return nil, Err.new(Err.ARG, "element " .. el.name .. ": unknown property type") @@ -1043,13 +1043,13 @@ function Ply.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err if not (cc and sz and items) then return nil, Err.new(Err.ARG, "element " .. el.name .. ": bad list property " .. tostring(pr.name)) end - table.insert(rows, { kind = "l", col = { name = pr.name, ply = pr.type, code = code, countPly = pr.countType, countCode = cc, sizes = sz, items = items } }) + table.insert(rows, { kind = "l" :: "l", col = { name = pr.name, ply = pr.type, code = code, countPly = pr.countType, countCode = cc, sizes = sz, items = items } }) else local vals = bufNumbers(pr.values, code, el.count) if not vals then return nil, Err.new(Err.ARG, "element " .. el.name .. ": bad property " .. tostring(pr.name)) end - table.insert(rows, { kind = "s", col = { name = pr.name, ply = pr.type, code = code, values = vals, stride = 1, offset = 0 } }) + table.insert(rows, { kind = "s" :: "s", col = { name = pr.name, ply = pr.type, code = code, values = vals, stride = 1, offset = 0 } }) end end raws[el.name] = { name = el.name, count = el.count, rows = rows } @@ -1084,7 +1084,7 @@ function Ply.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err -- header local vrows: { Row } = {} for _, c in cols do - table.insert(vrows, { kind = "s", col = c }) + table.insert(vrows, { kind = "s" :: "s", col = c }) end local lines = { "ply", "format " .. enc .. " 1.0" } local function noNewline(s: any): string diff --git a/src/Formats/model/stl/init.luau b/src/Formats/model/stl/init.luau index 50cfe41..06147a5 100644 --- a/src/Formats/model/stl/init.luau +++ b/src/Formats/model/stl/init.luau @@ -337,7 +337,7 @@ function Stl.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err return nil, Err.new(Err.ARG, tostring(merr)) end local P = m.attrs.POSITION.values - local N = if o.normals == "attribute" and m.attrs.NORMAL then m.attrs.NORMAL.values else nil + local N = if o.normals == "attribute" and m.attrs.NORMAL then (m.attrs.NORMAL :: Flatten.Attr).values else nil local C = m.attrs.COLOR_0 local corners = m.corners local nf = #corners // 3 diff --git a/src/Formats/model/usda/Build.luau b/src/Formats/model/usda/Build.luau index 6c3615f..5e4be9f 100644 --- a/src/Formats/model/usda/Build.luau +++ b/src/Formats/model/usda/Build.luau @@ -579,7 +579,7 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) end local textureIndex: { [string]: number } = {} - local WRAP = { ["repeat"] = "repeat", clamp = "clamp", mirror = "mirror", black = "clamp", useMetadata = "repeat" } + local WRAP: { [string]: string } = { ["repeat"] = "repeat", clamp = "clamp", mirror = "mirror", black = "clamp", useMetadata = "repeat" } -- UsdUVTexture shader -> TextureRef (texture index + texCoord + transform) local function textureRef(shader: Prim): Types.TextureRef? if shaderId(shader) ~= "UsdUVTexture" then @@ -1012,7 +1012,7 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) local cnt0 = counts[f + 1] if cnt0 >= 3 and not hole[f] then local base = faceStart[f + 1] - local verts = table.create(cnt0) + local verts = table.create(cnt0) :: { number } for k = 0, cnt0 - 1 do local corner = base + k local point = indices[corner + 1] @@ -1027,7 +1027,7 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) verts[k + 1] = v end if leftHanded then - local r = table.create(cnt0) + local r = table.create(cnt0) :: { number } for k = 1, cnt0 do r[k] = verts[cnt0 - k + 1] end @@ -1267,9 +1267,9 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) buffer.writef32(ro.data, ((k - 1) * 4 + c) * 4, R[c + 1]) end end - table.insert(animation.channels, { node = ni, path = "translation", input = tin, output = tr, interpolation = "LINEAR" }) - table.insert(animation.channels, { node = ni, path = "rotation", input = tin, output = ro, interpolation = "LINEAR" }) - table.insert(animation.channels, { node = ni, path = "scale", input = tin, output = sc, interpolation = "LINEAR" }) + table.insert(animation.channels, { node = ni, path = "translation", input = tin, output = tr, interpolation = "LINEAR" } :: Types.Channel) + table.insert(animation.channels, { node = ni, path = "rotation", input = tin, output = ro, interpolation = "LINEAR" } :: Types.Channel) + table.insert(animation.channels, { node = ni, path = "scale", input = tin, output = sc, interpolation = "LINEAR" } :: Types.Channel) local T, R, S = decompose(localMatrix(ops, times[1])) n.translation, n.rotation, n.scale = T, R, S elseif #ops > 0 then diff --git a/src/Formats/model/usda/Parse.luau b/src/Formats/model/usda/Parse.luau index 99b38e1..e3ddd2e 100644 --- a/src/Formats/model/usda/Parse.luau +++ b/src/Formats/model/usda/Parse.luau @@ -501,7 +501,7 @@ local function parser(s: string, maxBytes: number) -- time samples: { time: value, ... } local function samples(i: number): ({ times: { number }, values: { Value } }, number) - local times, values = {}, {} + local times: { number }, values: { Value } = {}, {} i = expect(i, "{") while true do i = ws(i) @@ -523,7 +523,7 @@ local function parser(s: string, maxBytes: number) i = expect(i, ":") local v v, i = value(i) - table.insert(times, t) + table.insert(times, t :: number) -- fail() threw on nil table.insert(values, v) end return { times = times, values = values }, i @@ -664,7 +664,7 @@ local function parser(s: string, maxBytes: number) end local prop = p.props[name :: string] if not prop then - prop = { name = name :: string, rel = isRel } + prop = { name = name :: string, rel = isRel } :: Prop p.props[name :: string] = prop table.insert(p.order, name :: string) end @@ -806,8 +806,8 @@ function Parse.layer(text: string, maxBytes: number?): (Layer?, string?, number? if ok then return res, nil, nil end - if type(res) == "table" and res.usda then - return nil, res.usda, math.max((res.at or 1) - 1, 0) + if type(res) == "table" and (res :: any).usda then + return nil, (res :: any).usda, math.max(((res :: any).at or 1) - 1, 0) end return nil, "parse error: " .. tostring(res), nil end diff --git a/src/Formats/model/usda/Write.luau b/src/Formats/model/usda/Write.luau index a4e53f3..9ca629a 100644 --- a/src/Formats/model/usda/Write.luau +++ b/src/Formats/model/usda/Write.luau @@ -14,7 +14,7 @@ local Types = require("@formats/Types") local Write = {} -local EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/webp"] = "webp", ["image/ktx2"] = "ktx2", ["image/avif"] = "avif", ["image/bmp"] = "bmp", ["image/x-tga"] = "tga", ["image/gif"] = "gif", ["image/tiff"] = "tiff" } +local EXT: { [string]: string } = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/webp"] = "webp", ["image/ktx2"] = "ktx2", ["image/avif"] = "avif", ["image/bmp"] = "bmp", ["image/x-tga"] = "tga", ["image/gif"] = "gif", ["image/tiff"] = "tiff" } local RAD = 180 / math.pi export type Options = { files: { [string]: any }?, name: string?, upAxis: string?, metersPerUnit: number? } @@ -79,7 +79,7 @@ local function values(acc: Types.Accessor?): ({ number }?, number) return nil, 0 end local n, c = acc.count, acc.components - local out = table.create(n * c) + local out = table.create(n * c) :: { number } for i = 0, n - 1 do for k = 0, c - 1 do out[i * c + k + 1] = get(i, k) @@ -123,14 +123,14 @@ type Merged = { local function faces(p: Types.Primitive, nverts: number): ({ number }?, { number }?) local idx: { number } if p.indices then - idx = (values(p.indices)) or {} + idx = (values(p.indices)) or {} :: { number } else - idx = table.create(nverts) + idx = table.create(nverts) :: { number } for i = 1, nverts do idx[i] = i - 1 end end - local counts, out = {}, {} + local counts: { number }, out: { number } = {}, {} local mode = p.mode if mode == "triangles" or mode == nil then for k = 1, #idx - 2, 3 do @@ -180,7 +180,7 @@ end local function merge(mesh: Types.Mesh, notes: { [string]: number }): Merged? local prims: { Types.Primitive } = {} for _, p in mesh.primitives do - if p.attributes and p.attributes.POSITION and p.attributes.POSITION.components == 3 and p.mode ~= "lines" and p.mode ~= "line_strip" and p.mode ~= "line_loop" and p.mode ~= "points" then + if p.attributes and p.attributes.POSITION and (p.attributes.POSITION :: Types.Accessor).components == 3 and p.mode ~= "lines" and p.mode ~= "line_strip" and p.mode ~= "line_loop" and p.mode ~= "points" then table.insert(prims, p) else notes["lines / points primitives"] = (notes["lines / points primitives"] or 0) + 1 @@ -318,7 +318,7 @@ function Write.text(scene: Types.Scene, opts: Options?): (string, { [string]: nu local rootName = if wrap then "root" else rootNames(nodes[roots[1]].name, "root") -- texture files - local base = o.name and string.gsub(string.match(o.name, "([^/\\]+)$") or o.name, "%.[^.]*$", "") or "model" + local base: string = o.name and string.gsub(string.match(o.name, "([^/\\]+)$") or o.name, "%.[^.]*$", "") or "model" local texFile: { [number]: string } = {} for i, tex in scene.textures or {} do local uri: string? = if tex.uri then (string.gsub(tex.uri, "\\", "/")) else nil @@ -340,7 +340,7 @@ function Write.text(scene: Types.Scene, opts: Options?): (string, { [string]: nu -- animation: per node, per path -> { times, values (components) } type Track = { times: { number }, vals: { number }, comps: number } - local tracks: { [number]: { [string]: Track } } = {} + local tracks: { [number]: { [string]: Track? } } = {} local tcps = 24 local tMin, tMax = math.huge, -math.huge for _, anim in scene.animations or {} do @@ -399,7 +399,7 @@ function Write.text(scene: Types.Scene, opts: Options?): (string, { [string]: nu -- xform ops of a node (+ its animation) local function xform(depth: number, ni: number, n: Types.Node) - local tr = tracks[ni] + local tr: { [string]: Track? }? = tracks[ni] local order: { string } = {} local function samples(track: Track, f: (vals: { number }, at: number) -> string): string local parts = {} @@ -438,7 +438,7 @@ function Write.text(scene: Types.Scene, opts: Options?): (string, { [string]: nu line(depth, "double3 xformOp:translate = " .. tuple({ t[1] or 0, t[2] or 0, t[3] or 0 })) end if tr and tr.translation then - line(depth, "double3 xformOp:translate.timeSamples = " .. samples(tr.translation, vec3)) + line(depth, "double3 xformOp:translate.timeSamples = " .. samples(tr.translation :: Track, vec3)) end table.insert(order, '"xformOp:translate"') end @@ -447,7 +447,7 @@ function Write.text(scene: Types.Scene, opts: Options?): (string, { [string]: nu line(depth, "quatf xformOp:orient = " .. quat(r, 0)) end if tr and tr.rotation then - line(depth, "quatf xformOp:orient.timeSamples = " .. samples(tr.rotation, quat)) + line(depth, "quatf xformOp:orient.timeSamples = " .. samples(tr.rotation :: Track, quat)) end table.insert(order, '"xformOp:orient"') end @@ -456,7 +456,7 @@ function Write.text(scene: Types.Scene, opts: Options?): (string, { [string]: nu line(depth, "float3 xformOp:scale = " .. tuple({ s[1] or 1, s[2] or 1, s[3] or 1 })) end if tr and tr.scale then - line(depth, "float3 xformOp:scale.timeSamples = " .. samples(tr.scale, vec3)) + line(depth, "float3 xformOp:scale.timeSamples = " .. samples(tr.scale :: Track, vec3)) end table.insert(order, '"xformOp:scale"') end @@ -570,7 +570,7 @@ function Write.text(scene: Types.Scene, opts: Options?): (string, { [string]: nu line(depth, "float verticalAperture = " .. fmt(vap)) end - local LIGHT_TYPE = { directional = "DistantLight", point = "SphereLight", spot = "SphereLight" } + local LIGHT_TYPE: { [string]: string } = { directional = "DistantLight", point = "SphereLight", spot = "SphereLight" } local function lightBody(depth: number, l: Types.Light) local c = l.color or { 1, 1, 1 } line(depth, "color3f inputs:color = " .. tuple({ c[1] or 1, c[2] or 1, c[3] or 1 })) @@ -808,7 +808,7 @@ function Write._looks(out: { string }, depth: number, scene: Types.Scene, matPat stSource = path .. "/" .. tn.name .. "_Transform.outputs:result" end local tex = scene.textures[ref.texture] - local sampler = tex and tex.sampler or {} + local sampler: Types.Sampler = tex and tex.sampler or {} table.insert(out, "") line(d, 'def Shader "' .. tn.name .. '"') line(d, "{") diff --git a/src/Formats/model/usda/init.luau b/src/Formats/model/usda/init.luau index e1b8338..3e52979 100644 --- a/src/Formats/model/usda/init.luau +++ b/src/Formats/model/usda/init.luau @@ -107,11 +107,11 @@ local function fetcher(opts: DecodeOptions?, package: any): (uri: string) -> buf end end local v: any = nil - if opts and type(opts.files) == "table" then - v = opts.files[u] + if opts and type((opts :: DecodeOptions).files) == "table" then + v = ((opts :: DecodeOptions).files :: { [string]: any })[u] end - if v == nil and opts and type(opts.resolve) == "function" then - local ok, res = pcall(opts.resolve, u) + if v == nil and opts and type((opts :: DecodeOptions).resolve) == "function" then + local ok, res = pcall((opts :: DecodeOptions).resolve :: (uri: string) -> any, u) v = if ok then res else nil end if type(v) == "string" then diff --git a/src/Formats/model/vox/init.luau b/src/Formats/model/vox/init.luau index 81277aa..879094d 100644 --- a/src/Formats/model/vox/init.luau +++ b/src/Formats/model/vox/init.luau @@ -275,7 +275,7 @@ local function parse(r: Bytes.Reader, opts: DecodeOptions?): (Parsed?, Err.Err?) if n < 1024 then return nil, Err.new(Err.CORRUPT, "short RGBA chunk", at) end - local pal = table.create(255) + local pal = table.create(255) :: { { number } } for i = 1, 255 do pal[i] = { c:u8(), c:u8(), c:u8(), c:u8() } end @@ -310,7 +310,7 @@ local function parse(r: Bytes.Reader, opts: DecodeOptions?): (Parsed?, Err.Err?) if c.err or nc < 0 or nc * 4 > c:remaining() then return nil, Err.new(Err.CORRUPT, "bad nGRP chunk", at) end - local children = table.create(nc) + local children = table.create(nc) :: { number } for k = 1, nc do children[k] = c:i32le() end @@ -625,7 +625,7 @@ function Vox.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) return nil, Err.new(Err.ARG, "voxels " .. i .. ": data is smaller than the grid") end end - local meta = if type(scene.meta) == "table" and type(scene.meta.vox) == "table" then scene.meta.vox else {} + local meta: any = if type(scene.meta) == "table" and type(scene.meta.vox) == "table" then scene.meta.vox else {} local w = Bytes.writer(65536) w:string("VOX ") w:u32le(version) @@ -675,7 +675,7 @@ function Vox.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local failure: string? = nil local function shape(model: number, vx: any?): number local id = alloc() - local ms = {} + local ms: { { model: number, attributes: Dict? } } = {} local saved = vx and vx.shape if saved and type(saved.models) == "table" and saved.models[1] and saved.models[1].model == model then for _, sm in saved.models do From dc98aec2ecbec64fdc979319b75e5773a2883b24 Mon Sep 17 00:00:00 2001 From: 4DBug <github@bug.tools> Date: Sat, 31 Oct 2026 11:00:25 -0500 Subject: [PATCH 10/22] ws-cleanup-types: Types.VectorPath: declare the optional svg fields (group, clip, id, dashes, joins, caps, miter limit) --- src/Formats/Types.luau | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/Formats/Types.luau b/src/Formats/Types.luau index f0e3a6b..4d597d8 100644 --- a/src/Formats/Types.luau +++ b/src/Formats/Types.luau @@ -950,6 +950,14 @@ export type VectorPath = { strokeWidth: number, transform: { number }?, -- a, b, c, d, e, f opacity: number, + group: number?, -- index into meta.groups (svg <g> nesting: opacity / clip-path per group) + clip: number?, -- index into meta.clips (a clip-path) + id: string?, + strokeDashArray: { number }?, + strokeDashOffset: number?, + strokeLineJoin: ("miter" | "round" | "bevel")?, -- default "miter" + strokeLineCap: ("butt" | "round" | "square")?, -- default "butt" + strokeMiterLimit: number?, } export type Vector = { kind: "vector", From f459b2dcdf9293f06bcf9455d629dfbdac38e39c Mon Sep 17 00:00:00 2001 From: 4DBug <github@bug.tools> Date: Sat, 31 Oct 2026 11:00:25 -0500 Subject: [PATCH 11/22] ws-cleanup-types: archive, audio, data, font, image, layered, music, playlist, subtitle, vector, video: annotations, casts, one value per re-assignment where the solver loses the type --- src/Formats/archive/7z/Header.luau | 7 ++++--- src/Formats/archive/7z/init.luau | 16 ++++++++++------ src/Formats/archive/gzip/init.luau | 8 ++++---- src/Formats/archive/xz/init.luau | 2 +- src/Formats/audio/caf/init.luau | 4 ++-- src/Formats/audio/m4a/init.luau | 8 ++++---- src/Formats/audio/mp3/Core.luau | 19 ++++++++++++++----- src/Formats/audio/mp3/Encode2.luau | 4 +++- src/Formats/audio/mp3/Tags.luau | 8 +++++--- src/Formats/data/cbor/Codec.luau | 10 +++++----- src/Formats/data/csv/init.luau | 2 +- src/Formats/data/ini/init.luau | 4 ++-- src/Formats/data/toml/Decode.luau | 10 +++++----- src/Formats/font/bmfont/Parse.luau | 12 ++++++------ src/Formats/font/bmfont/init.luau | 14 ++++++++------ src/Formats/font/woff2/Rebuild.luau | 17 ++++++++++++----- src/Formats/image/bmp/init.luau | 11 ++++++++--- src/Formats/image/gif/init.luau | 6 +++--- src/Formats/image/hdr/init.luau | 4 ++-- src/Formats/image/ico/init.luau | 2 +- src/Formats/image/qoi/Codec.luau | 14 +++++++++++--- src/Formats/image/qoi/init.luau | 2 +- src/Formats/image/tiff/Pixels.luau | 8 ++++++-- src/Formats/image/tiff/init.luau | 8 ++++---- src/Formats/layered/psd/Channels.luau | 10 +++++++--- src/Formats/music/midi/Render.luau | 4 ++-- src/Formats/music/midi/Smf.luau | 4 ++-- src/Formats/music/s3m/init.luau | 3 ++- src/Formats/music/xm/init.luau | 6 +++++- src/Formats/playlist/pls/init.luau | 2 +- src/Formats/playlist/xspf/init.luau | 2 +- src/Formats/subtitle/ass/init.luau | 2 +- src/Formats/vector/svg/Parse.luau | 18 +++++++++--------- src/Formats/vector/svg/PathData.luau | 4 ++-- src/Formats/vector/svg/Style.luau | 6 +++--- src/Formats/vector/svg/Write.luau | 2 +- src/Formats/vector/tiled/Data.luau | 4 ++-- src/Formats/vector/tiled/init.luau | 2 +- src/Formats/video/avi/init.luau | 4 ++-- src/Formats/video/mkv/init.luau | 4 ++-- src/Formats/video/mp4/init.luau | 2 +- src/Formats/video/mpegps/init.luau | 4 ++-- src/Formats/video/mpegts/init.luau | 4 ++-- src/Formats/video/y4m/init.luau | 4 ++-- 44 files changed, 172 insertions(+), 119 deletions(-) diff --git a/src/Formats/archive/7z/Header.luau b/src/Formats/archive/7z/Header.luau index c85accc..6f5ba24 100644 --- a/src/Formats/archive/7z/Header.luau +++ b/src/Formats/archive/7z/Header.luau @@ -177,7 +177,8 @@ local function folder(r: Bytes.Reader): Folder check(r) local nin, nout = 1, 1 if bit32.band(flags, 0x10) ~= 0 then - nin, nout = number(r), number(r) + nin = number(r) + nout = number(r) if nin > 64 or nout > 64 then bad(r, "bad coder stream count") end @@ -416,11 +417,11 @@ local function filesInfo(r: Bytes.Reader): { File } if n > 1000000 then bad(r, "too many files", Err.LIMIT) end - local files: { File } = table.create(n) + local files: { File } = table.create(n) :: { File } for i = 1, n do files[i] = { name = "", emptyStream = false, emptyFile = false, anti = false } end - local empties = {} + local empties: { number } = {} while true do local t = byte(r) if t == K.End then diff --git a/src/Formats/archive/7z/init.luau b/src/Formats/archive/7z/init.luau index 780f05c..653195a 100644 --- a/src/Formats/archive/7z/init.luau +++ b/src/Formats/archive/7z/init.luau @@ -144,7 +144,9 @@ local function decodeFolder(ctx: Ctx, s: Header.Streams, f: Header.Folder): (buf if not b then return nil, e end - src, so, sl = b, 0, buffer.len(b) + src = b + so = 0 + sl = buffer.len(b) else local k = table.find(f.packed, inIdx) if not k then @@ -162,7 +164,7 @@ local function decodeFolder(ctx: Ctx, s: Header.Streams, f: Header.Folder): (buf src = ctx.buf end local id = c.id - local opts = { maxBytes = ctx.maxBytes } + local opts: { maxBytes: number?, verify: boolean? } = { maxBytes = ctx.maxBytes } if id == "\0" then if sl < size then return nil, Err.new(Err.TRUNCATED, "short stored stream") @@ -226,7 +228,7 @@ local function folderMethod(f: Header.Folder): string end function SevenZip.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Archive?, Err.Err?) - local o = opts or {} + local o: DecodeOptions = opts or {} local maxBytes = if type(o.maxBytes) == "number" then o.maxBytes else 2 ^ 30 local checkCrc = o.checkCrc ~= false local b, base, limit = r.buf, r.base, r.limit @@ -280,17 +282,19 @@ function SevenZip.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Archive? if f.crc and Crc32.raw(hb, 0, buffer.len(hb)) ~= f.crc then return nil, Err.new(Err.CHECKSUM, "encoded header CRC-32 mismatch") end - hbuf, hoff, hlen = hb, 0, buffer.len(hb) + hbuf = hb + hoff = 0 + hlen = buffer.len(hb) end if not parsed then return nil, Err.new(Err.CORRUPT, "nested encoded headers") end - local s = parsed.streams or { packPos = 0, packSizes = {}, folders = {}, subSizes = {}, subCrcs = {} } + local s: Header.Streams = parsed.streams or { packPos = 0, packSizes = {}, folders = {}, subSizes = {}, subCrcs = {} } a.meta.folders = #s.folders a.meta.solid = false -- folder caches and the substream -> folder map local cache: { [number]: buffer } = {} - local subFolder, subOffset = {}, {} + local subFolder: { number }, subOffset: { number } = {}, {} do local si = 1 for fi, f in s.folders do diff --git a/src/Formats/archive/gzip/init.luau b/src/Formats/archive/gzip/init.luau index 38ddeca..e5210ea 100644 --- a/src/Formats/archive/gzip/init.luau +++ b/src/Formats/archive/gzip/init.luau @@ -49,7 +49,7 @@ local function header(b: buffer, o: number, e: number): { [string]: any } if bit32.band(flg, 4) ~= 0 and q + 2 <= e then q += 2 + buffer.readu16(b, q) end - for _, f in { { 8, "name" }, { 16, "comment" } } do + for _, f in { { 8, "name" }, { 16, "comment" } } :: { { any } } do if bit32.band(flg, f[1]) ~= 0 then local s = q while q < e and buffer.readu8(b, q) ~= 0 do @@ -85,7 +85,7 @@ function Gzip.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) size = buffer.len(out), compressedSize = r.limit - r.base, method = "deflate", - mtime = if h.mtime and h.mtime > 0 then h.mtime else nil, + mtime = if h.mtime and h.mtime > 0 then h.mtime :: number else nil, dir = false, data = out, }) @@ -94,7 +94,7 @@ end -- ------------------------------------------------------------------------------------------------ encode function Gzip.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) - local o = opts or {} + local o: EncodeOptions = opts or {} local level = if o.level == nil then 6 else o.level if type(level) ~= "number" or level < 0 or level > 9 or level % 1 ~= 0 then return nil, Err.new(Err.ARG, "level must be 0..9") @@ -111,7 +111,7 @@ function Gzip.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) if not items then return nil, Err.new(Err.ARG, "expected an Archive, a buffer or a string") end - local files = {} + local files: typeof(items) = {} for _, it in items do if not it.entry.dir then table.insert(files, it) diff --git a/src/Formats/archive/xz/init.luau b/src/Formats/archive/xz/init.luau index 9225302..cb0a07c 100644 --- a/src/Formats/archive/xz/init.luau +++ b/src/Formats/archive/xz/init.luau @@ -70,7 +70,7 @@ end -- ------------------------------------------------------------------------------------------------ decode function Xz.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Archive?, Err.Err?) - local o = opts or {} + local o: DecodeOptions = opts or {} local n = r.limit - r.base local out, res local method diff --git a/src/Formats/audio/caf/init.luau b/src/Formats/audio/caf/init.luau index f602434..3bcbe7f 100644 --- a/src/Formats/audio/caf/init.luau +++ b/src/Formats/audio/caf/init.luau @@ -350,7 +350,7 @@ local function source(r: Bytes.Reader, p: Parsed): (Source?, Err.Err?) return nil, Err.new(Err.CORRUPT, "compressed CAF without a packet table") end end - local offsets = table.create(#sizes, 0) + local offsets = table.create(#(sizes :: { number }), 0) local o = p.dataStart for i, s in sizes :: { number } do offsets[i] = o @@ -585,7 +585,7 @@ end -- encode(audio | decoder, opts?) -> buffer | nil, Err function Caf.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) - local o = opts or {} + local o: EncodeOptions = opts or {} if type(value) ~= "table" or type(value.sampleRate) ~= "number" or type(value.channels) ~= "number" then return nil, Err.new(Err.ARG, "expected an Audio or a Decoder") end diff --git a/src/Formats/audio/m4a/init.luau b/src/Formats/audio/m4a/init.luau index bf64abb..26c48c1 100644 --- a/src/Formats/audio/m4a/init.luau +++ b/src/Formats/audio/m4a/init.luau @@ -121,7 +121,7 @@ end -- open(r, opts?) -> Types.Decoder | nil, Err function M4a.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?) - local o = opts or {} + local o: DecodeOptions = opts or {} local movie, err = IsoBmff.parse(r, { maxSamples = o.maxSamples }) if not movie then return nil, err @@ -169,9 +169,9 @@ function M4a.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.E -- iTunes gapless info (fdkaac, iTunes) when there is no edit list: " 0 <priming> <padding> <samples> ..." (hex) local smpb = tags.iTunSMPB if gapless and not t.edits and smpb then - local f = {} + local f: { number } = {} for w in string.gmatch(smpb, "%x+") do - table.insert(f, tonumber(w, 16)) + table.insert(f, tonumber(w, 16) :: number) end if #f >= 4 and f[2] and f[4] and f[4] > 0 and f[2] + f[4] <= total then skip = f[2] @@ -337,7 +337,7 @@ end -- ------------------------------------------------------------------------------------------------ encode -- encode(audio | decoder, opts?) -> buffer | nil, Err: an ALAC M4A function M4a.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) - local o = opts or {} + local o: EncodeOptions = opts or {} if type(value) ~= "table" or type(value.sampleRate) ~= "number" or type(value.channels) ~= "number" then return nil, Err.new(Err.ARG, "expected an Audio or a Decoder") end diff --git a/src/Formats/audio/mp3/Core.luau b/src/Formats/audio/mp3/Core.luau index a7bb0a7..1678548 100644 --- a/src/Formats/audio/mp3/Core.luau +++ b/src/Formats/audio/mp3/Core.luau @@ -561,7 +561,8 @@ local function intensityStereo(h1: number, h3: number, gr: number) kr = 1 end end - kl, kr = f32(kl * s), f32(kr * s) + kl = f32(kl * s) + kr = f32(kr * s) for k = left * 4, (left + n - 1) * 4, 4 do local v = rf(GRBUF, k) wf(GRBUF, k + 2304, v * kr) @@ -1183,8 +1184,14 @@ local function synth(xl: number, dstl: number, nch: number, lins: number) a3 += z3 * w0 - y3 * w1 vz -= 256 vy += 256 - z0, z1, z2, z3 = rf(SYN, vz), rf(SYN, vz + 4), rf(SYN, vz + 8), rf(SYN, vz + 12) - y0, y1, y2, y3 = rf(SYN, vy), rf(SYN, vy + 4), rf(SYN, vy + 8), rf(SYN, vy + 12) + z0 = rf(SYN, vz) + z1 = rf(SYN, vz + 4) + z2 = rf(SYN, vz + 8) + z3 = rf(SYN, vz + 12) + y0 = rf(SYN, vy) + y1 = rf(SYN, vy + 4) + y2 = rf(SYN, vy + 8) + y3 = rf(SYN, vy + 12) b0 += z0 * w3 + y0 * w2 b1 += z1 * w3 + y1 * w2 b2 += z2 * w3 + y2 * w2 @@ -1212,8 +1219,10 @@ local function synth(xl: number, dstl: number, nch: number, lins: number) a2 += z2 * w0 - y2 * w1 vz -= 256 vy += 256 - z0, z2 = rf(SYN, vz), rf(SYN, vz + 8) - y0, y2 = rf(SYN, vy), rf(SYN, vy + 8) + z0 = rf(SYN, vz) + z2 = rf(SYN, vz + 8) + y0 = rf(SYN, vy) + y2 = rf(SYN, vy + 8) b0 += z0 * w3 + y0 * w2 b2 += z2 * w3 + y2 * w2 a0 += y0 * w3 - z0 * w2 diff --git a/src/Formats/audio/mp3/Encode2.luau b/src/Formats/audio/mp3/Encode2.luau index 0a6af36..3ce1594 100644 --- a/src/Formats/audio/mp3/Encode2.luau +++ b/src/Formats/audio/mp3/Encode2.luau @@ -375,7 +375,9 @@ function Encode2.encode(src: Source, opts: Options): (buffer?, string?) local q = floor((x * inv + 1) * L / 2) return if q < 0 then 0 elseif q > L - 1 then L - 1 else q end - q0, q1, q2 = quant(sb[o + 1]), quant(sb[o + 2]), quant(sb[o + 3]) + q0 = quant(sb[o + 1]) + q1 = quant(sb[o + 2]) + q2 = quant(sb[o + 3]) end if ba >= 17 then put(w, q0 + L * (q1 + L * q2), tripleBits(ba)) diff --git a/src/Formats/audio/mp3/Tags.luau b/src/Formats/audio/mp3/Tags.luau index 329c297..a74d7b8 100644 --- a/src/Formats/audio/mp3/Tags.luau +++ b/src/Formats/audio/mp3/Tags.luau @@ -179,7 +179,8 @@ local function parseV2(b: buffer, o: number, size: number, tags: any) local p, e = o + 10, bodyEnd if band(flags, 0x80) ~= 0 and ver < 4 then body = deunsync(b, p, e) - p, e = 0, buffer.len(body) + p = 0 + e = buffer.len(body) end if band(flags, 0x40) ~= 0 and ver >= 3 and p + 4 <= e then -- extended header: v2.3 size excludes its own 4 bytes, v2.4 includes them (syncsafe) @@ -216,7 +217,8 @@ local function parseV2(b: buffer, o: number, size: number, tags: any) end if not skip and band(fflags, 0x0002) ~= 0 and fs < fe then fb = deunsync(body, fs, fe) - fs, fe = 0, buffer.len(fb) + fs = 0 + fe = buffer.len(fb) end end if not skip and fs < fe then @@ -273,7 +275,7 @@ function Tags.parse(b: buffer): (any, number, number) if size >= 128 and buffer.readstring(b, start + size - 128, 3) == "TAG" then local o = start + size - 128 tags.id3v1 = true - local v1 = { + local v1: { [string]: any } = { title = v1String(b, o + 3, 30), artist = v1String(b, o + 33, 30), album = v1String(b, o + 63, 30), diff --git a/src/Formats/data/cbor/Codec.luau b/src/Formats/data/cbor/Codec.luau index f588c59..2f80e34 100644 --- a/src/Formats/data/cbor/Codec.luau +++ b/src/Formats/data/cbor/Codec.luau @@ -60,7 +60,7 @@ local function bigText(s: string): string end -- text + 1 for a decimal string local function incText(s: string): string - local digits = table.create(#s) + local digits: { number } = table.create(#s) :: { number } for i = 1, #s do digits[i] = string.byte(s, i) - 48 end @@ -73,7 +73,7 @@ local function incText(s: string): string digits[i] = 0 i -= 1 end - local out = table.create(#digits) + local out: { string } = table.create(#digits) :: { string } for k, d in digits do out[k] = string.char(48 + d) end @@ -296,11 +296,11 @@ function item(st: St, depth: number): (any, string?) table.insert(t, v) end end - if n > r:remaining() then + if (n :: number) > r:remaining() then return nil, "array count past the end" end - local t = table.create(n) - for k = 1, n do + local t = table.create(n :: number) + for k = 1, n :: number do local v, ve = item(st, depth + 1) if ve then return nil, ve diff --git a/src/Formats/data/csv/init.luau b/src/Formats/data/csv/init.luau index e5c7d6d..0e57eea 100644 --- a/src/Formats/data/csv/init.luau +++ b/src/Formats/data/csv/init.luau @@ -57,7 +57,7 @@ function Csv.sniff(r: Bytes.Reader): number end for _, d in { ",", "\t", ";" } do local _, c1 = gsub(l1, d, "") - local _, c2 = gsub(l2, d, "") + local _, c2 = gsub(l2 :: string, d, "") if c1 > 0 and c1 == c2 then return 0.15 end diff --git a/src/Formats/data/ini/init.luau b/src/Formats/data/ini/init.luau index fe48955..816bd6a 100644 --- a/src/Formats/data/ini/init.luau +++ b/src/Formats/data/ini/init.luau @@ -137,11 +137,11 @@ function Ini.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) seenKeys[cur] = seen end if seen[key :: string] and o.strict then - return nil, Err.new(Err.CORRUPT, "duplicate key " .. key, lineStart) + return nil, Err.new(Err.CORRUPT, "duplicate key " .. (key :: string), lineStart) end seen[key :: string] = true if cur == root and type(root[key]) == "table" then - return nil, Err.new(Err.CORRUPT, "top-level key " .. key .. " has the name of a section", lineStart) + return nil, Err.new(Err.CORRUPT, "top-level key " .. (key :: string) .. " has the name of a section", lineStart) end Types.set(cur, key, value) lastKey, lastIndent, lastTable = key, indent, cur diff --git a/src/Formats/data/toml/Decode.luau b/src/Formats/data/toml/Decode.luau index b03b941..9325ca4 100644 --- a/src/Formats/data/toml/Decode.luau +++ b/src/Formats/data/toml/Decode.luau @@ -214,7 +214,7 @@ function Decode.decode(s: string, opts: Options?): (any, any, number?) -- a (dotted) key: { parts }, next | nil local function key(i: number): ({ string }?, number) - local keys = {} + local keys: { string } = {} while true do i = ws(i) local c = byte(s, i) @@ -240,7 +240,7 @@ function Decode.decode(s: string, opts: Options?): (any, any, number?) if k == nil then return nil, 0 end - table.insert(keys, k) + table.insert(keys, k :: string) i = ws(i) if byte(s, i) == 46 then i += 1 @@ -313,7 +313,7 @@ function Decode.decode(s: string, opts: Options?): (any, any, number?) end return if sign == "-" then -v else v, nexti end - local text = sign .. digits + local text: string = (sign :: string) .. digits local frac, r2 = match(rest :: string, "^%.([%d_]*)(.*)$") if frac then if not digitsOk(frac, "%d") then @@ -324,10 +324,10 @@ function Decode.decode(s: string, opts: Options?): (any, any, number?) end if rest ~= "" then local es, ed = match(rest :: string, "^[eE]([%+%-]?)([%d_]*)$") - if not es or not digitsOk(ed, "%d") then + if not es or not digitsOk(ed :: string, "%d") then return fail("bad float", i), 0 end - text ..= "e" .. es .. gsub(ed, "_", "") + text ..= "e" .. es .. gsub(ed :: string, "_", "") end local v = tonumber(text) if v == nil then diff --git a/src/Formats/font/bmfont/Parse.luau b/src/Formats/font/bmfont/Parse.luau index 13c8314..ecde34c 100644 --- a/src/Formats/font/bmfont/Parse.luau +++ b/src/Formats/font/bmfont/Parse.luau @@ -107,13 +107,13 @@ function Parse.text(s: string): (Desc?, string?) local a: { [string]: string } = {} -- key=value, key="quoted value" local i = 1 - while i <= #rest do - local k, q, e = string.match(rest, '^%s*([%w_]+)="([^"]*)"()', i) + while i <= #(rest :: string) do + local k, q, e = string.match(rest :: string, '^%s*([%w_]+)="([^"]*)"()', i) if k then a[k] = q i = e else - local k2, v2, e2 = string.match(rest, "^%s*([%w_]+)=(%S*)()", i) + local k2, v2, e2 = string.match(rest :: string, "^%s*([%w_]+)=(%S*)()", i) if not k2 then break end @@ -135,7 +135,7 @@ function Parse.text(s: string): (Desc?, string?) end -- ------------------------------------------------------------------------------------------------ XML -local ENTITIES = { quot = '"', amp = "&", lt = "<", gt = ">", apos = "'" } +local ENTITIES: { [string]: string } = { quot = '"', amp = "&", lt = "<", gt = ">", apos = "'" } local function unescape(s: string): string return ( string.gsub(s, "&(#?x?%w+);", function(e: string): string? @@ -159,8 +159,8 @@ function Parse.xml(s: string): (Desc?, string?) seenFont = true end local a: { [string]: string } = {} - for k, q, v in string.gmatch(attrs, "([%w_]+)%s*=%s*([\"'])(.-)%2") do - a[k] = unescape(v) + for k, q, v in string.gmatch(attrs :: string, "([%w_]+)%s*=%s*([\"'])(.-)%2") do + a[k] = unescape(v :: string) local _ = q end local err = apply(d, tag, a) diff --git a/src/Formats/font/bmfont/init.luau b/src/Formats/font/bmfont/init.luau index f5459ae..f70cf94 100644 --- a/src/Formats/font/bmfont/init.luau +++ b/src/Formats/font/bmfont/init.luau @@ -287,26 +287,28 @@ function Bmfont.bake(font: any, opts: BakeOptions?): (any, Err.Err?) if type(font) ~= "table" or type(font.rasterize) ~= "function" or type(font.glyphIndex) ~= "function" then return nil, Err.new(Err.ARG, "bake: expected an outline Font") end - local o = opts or {} + local o: BakeOptions = opts or {} local px = if type(o.px) == "number" and o.px > 0 and o.px <= 1024 then o.px else 32 local pad = if type(o.padding) == "number" and o.padding >= 0 then math.floor(o.padding) else 1 local scale = px / font.unitsPerEm - local glyphs = {} + local glyphs: { { cp: number, g: number, img: Types.Image } } = {} local area = 0 local seen = {} for _, cp in codepoints(o.chars) do - local g = font:glyphIndex(cp) + local g = (font :: any):glyphIndex(cp) if (g ~= 0 or cp == 0) and not seen[cp] then seen[cp] = true - local img = font:rasterize(g, px) + local img: Types.Image? = (font :: any):rasterize(g, px) if img then table.insert(glyphs, { cp = cp, g = g, img = img }) area += (img.width + pad) * (img.height + pad) end end end - local size = o.pageSize - if type(size) ~= "number" then + local size: number + if type(o.pageSize) == "number" then + size = o.pageSize + else size = 64 while size * size < area * 1.3 and size < 4096 do size *= 2 diff --git a/src/Formats/font/woff2/Rebuild.luau b/src/Formats/font/woff2/Rebuild.luau index 7cbf3b3..c2668d2 100644 --- a/src/Formats/font/woff2/Rebuild.luau +++ b/src/Formats/font/woff2/Rebuild.luau @@ -150,9 +150,11 @@ local function glyf(b: buffer, p: number, n: number, maxBytes: number): (any?, s fl = band(fl, 0x7F) local dx, dy if fl < 10 then - dx, dy = 0, withSign(fl, band(fl, 14) * 128 + su8(glyphS)) + dx = 0 + dy = withSign(fl, band(fl, 14) * 128 + su8(glyphS)) elseif fl < 20 then - dx, dy = withSign(fl, band(fl - 10, 14) * 128 + su8(glyphS)), 0 + dx = withSign(fl, band(fl - 10, 14) * 128 + su8(glyphS)) + dy = 0 elseif fl < 84 then local b0 = fl - 20 local b1 = su8(glyphS) @@ -181,12 +183,17 @@ local function glyf(b: buffer, p: number, n: number, maxBytes: number): (any?, s end local x0, y0, x1, y1 if hasBox(g) then - x0, y0, x1, y1 = si16(bboxS), si16(bboxS), si16(bboxS), si16(bboxS) + x0 = si16(bboxS) + y0 = si16(bboxS) + x1 = si16(bboxS) + y1 = si16(bboxS) else x0, y0, x1, y1 = 32767, 32767, -32768, -32768 for k = 1, total do - x0, y0 = math.min(x0, xs[k]), math.min(y0, ys[k]) - x1, y1 = math.max(x1, xs[k]), math.max(y1, ys[k]) + x0 = math.min(x0, xs[k]) + y0 = math.min(y0, ys[k]) + x1 = math.max(x1, xs[k]) + y1 = math.max(y1, ys[k]) end if total == 0 then x0, y0, x1, y1 = 0, 0, 0, 0 diff --git a/src/Formats/image/bmp/init.luau b/src/Formats/image/bmp/init.luau index 335b8e8..e21a9fa 100644 --- a/src/Formats/image/bmp/init.luau +++ b/src/Formats/image/bmp/init.luau @@ -209,7 +209,9 @@ function Bmp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E if comp == 3 or comp == 6 then hasMasks = true if hs >= 52 then - rm, gm, bm = readu32(buf, 54), readu32(buf, 58), readu32(buf, 62) + rm = readu32(buf, 54) + gm = readu32(buf, 58) + bm = readu32(buf, 62) if hs >= 56 then am = readu32(buf, 66) end @@ -218,7 +220,9 @@ function Bmp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E if palStart + count * 4 > n then return nil, Err.new(Err.TRUNCATED, "truncated bit masks") end - rm, gm, bm = readu32(buf, palStart), readu32(buf, palStart + 4), readu32(buf, palStart + 8) + rm = readu32(buf, palStart) + gm = readu32(buf, palStart + 4) + bm = readu32(buf, palStart + 8) if comp == 6 then am = readu32(buf, palStart + 12) end @@ -385,7 +389,8 @@ function Bmp.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) local dpi = img.meta and img.meta.dpi local xp: number, yp: number = 3780, 3780 -- 96 dpi, as Pillow if type(dpi) == "table" and type(dpi.x) == "number" and type(dpi.y) == "number" and dpi.x > 0 and dpi.y > 0 then - xp, yp = math.floor((dpi.x :: number) * 39.3701 + 0.5), math.floor((dpi.y :: number) * 39.3701 + 0.5) + xp = math.floor((dpi.x :: number) * 39.3701 + 0.5) + yp = math.floor((dpi.y :: number) * 39.3701 + 0.5) end o:i32le(xp) o:i32le(yp) diff --git a/src/Formats/image/gif/init.luau b/src/Formats/image/gif/init.luau index c2b84f4..fcd3bfb 100644 --- a/src/Formats/image/gif/init.luau +++ b/src/Formats/image/gif/init.luau @@ -50,7 +50,7 @@ export type EncodeOptions = { -- ------------------------------------------------------------------------------------------------ constants local readu8 = buffer.readu8 local DISPOSE = { [0] = "none", [1] = "none", [2] = "background", [3] = "previous" } -local DISPOSE_CODE = { none = 1, background = 2, previous = 3 } +local DISPOSE_CODE: { [string]: number } = { none = 1, background = 2, previous = 3 } -- ------------------------------------------------------------------------------------------------ sniff function Gif.sniff(r: Bytes.Reader): number @@ -62,7 +62,7 @@ end -- a colour table at p (n entries) -> 256 u32 rgba entries (missing ones opaque black) and the { r, g, b, a } list local function colorTable(b: buffer, p: number, n: number): (buffer, { { number } }) local t = buffer.create(1024) - local list = table.create(n) + local list: { { number } } = table.create(n) :: { { number } } for i = 0, 255 do buffer.writeu32(t, i * 4, 0xFF000000) end @@ -404,7 +404,7 @@ function Gif.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) end -- palettes local shared = (opts and opts.globalPalette) or not animated - local qopts = { method = method, dither = dither } + local qopts: Quantize.PaletteOptions = { method = method, dither = dither } local globalPal: { { number } }? = nil local globalTrans = false if shared then diff --git a/src/Formats/image/hdr/init.luau b/src/Formats/image/hdr/init.luau index ceb84a3..11ac3bd 100644 --- a/src/Formats/image/hdr/init.luau +++ b/src/Formats/image/hdr/init.luau @@ -106,7 +106,7 @@ function Hdr.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E return nil, Err.new(Err.TRUNCATED, "no resolution line", p) end local s1, a1, n1, s2, a2, n2 = string.match(res, "^%s*([%+%-])([XY])%s+(%d+)%s+([%+%-])([XY])%s+(%d+)%s*$") - if not s1 or a1 == a2 or #n1 > 9 or #n2 > 9 then + if not s1 or a1 == a2 or #(n1 :: string) > 9 or #(n2 :: string) > 9 then return nil, Err.new(Err.CORRUPT, "bad resolution line", p) end local outer, inner = tonumber(n1) :: number, tonumber(n2) :: number @@ -170,7 +170,7 @@ function Hdr.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E if truncated then img.meta.truncated = true end - img.meta.source = { format = "hdr", bitDepth = 32, colorType = "rgbe", program = string.sub(first, 3), orientation = string.format("%s%s %s%s", s1, a1, s2, a2) } + img.meta.source = { format = "hdr", bitDepth = 32, colorType = "rgbe", program = string.sub(first, 3), orientation = string.format("%s%s %s%s", s1, a1 :: string, s2 :: string, a2 :: string) } return img, nil end diff --git a/src/Formats/image/ico/init.luau b/src/Formats/image/ico/init.luau index 9fc05a1..ba4085d 100644 --- a/src/Formats/image/ico/init.luau +++ b/src/Formats/image/ico/init.luau @@ -175,7 +175,7 @@ function Ico.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E if typ == 2 then im.meta.hotspot = { x = f1, y = f2 } end - table.insert(frames, { image = im, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" }) + table.insert(frames, { image = im, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" } :: Types.Frame) local score = im.width * im.height * 64 + depth if score > bestScore then best, bestScore = im, score diff --git a/src/Formats/image/qoi/Codec.luau b/src/Formats/image/qoi/Codec.luau index 2936f07..305ce81 100644 --- a/src/Formats/image/qoi/Codec.luau +++ b/src/Formats/image/qoi/Codec.luau @@ -26,19 +26,27 @@ function Codec.decode(b: buffer, p: number, limit: number, out: buffer, n: numbe if p + 3 > limit then return false, "truncated" end - r, g, bl = readu8(b, p), readu8(b, p + 1), readu8(b, p + 2) + r = readu8(b, p) + g = readu8(b, p + 1) + bl = readu8(b, p + 2) p += 3 elseif op == 0xFF then if p + 4 > limit then return false, "truncated" end - r, g, bl, a = readu8(b, p), readu8(b, p + 1), readu8(b, p + 2), readu8(b, p + 3) + r = readu8(b, p) + g = readu8(b, p + 1) + bl = readu8(b, p + 2) + a = readu8(b, p + 3) p += 4 else local tag = op // 64 if tag == 0 then local q = op * 4 - r, g, bl, a = readu8(index, q), readu8(index, q + 1), readu8(index, q + 2), readu8(index, q + 3) + r = readu8(index, q) + g = readu8(index, q + 1) + bl = readu8(index, q + 2) + a = readu8(index, q + 3) elseif tag == 1 then r = (r + (op // 16) % 4 - 2) % 256 g = (g + (op // 4) % 4 - 2) % 256 diff --git a/src/Formats/image/qoi/init.luau b/src/Formats/image/qoi/init.luau index ef11dc6..0273308 100644 --- a/src/Formats/image/qoi/init.luau +++ b/src/Formats/image/qoi/init.luau @@ -109,7 +109,7 @@ function Qoi.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) buffer.writestring(out, 0, "qoif") buffer.writeu32(out, 4, bit32.byteswap(w)) buffer.writeu32(out, 8, bit32.byteswap(h)) - buffer.writeu8(out, 12, channels) + buffer.writeu8(out, 12, channels :: number) buffer.writeu8(out, 13, if linear then 1 else 0) local o = Codec.encode(img.pixels, n, bpp, out, 14) buffer.writestring(out, o, "\0\0\0\0\0\0\0\1") diff --git a/src/Formats/image/tiff/Pixels.luau b/src/Formats/image/tiff/Pixels.luau index 6ae16d4..68a3db9 100644 --- a/src/Formats/image/tiff/Pixels.luau +++ b/src/Formats/image/tiff/Pixels.luau @@ -384,7 +384,9 @@ function Pixels.convert(P: Params) r, g, bl = 0, 0, 0 end elseif photo == 2 then - r, g, bl = norm(0, x, y), norm(1, x, y), norm(2, x, y) + r = norm(0, x, y) + g = norm(1, x, y) + bl = norm(2, x, y) elseif photo == 5 then local c, m, ye, k = norm(0, x, y), norm(1, x, y), norm(2, x, y), norm(3, x, y) r, g, bl = (1 - c) * (1 - k), (1 - m) * (1 - k), (1 - ye) * (1 - k) @@ -399,7 +401,9 @@ function Pixels.convert(P: Params) a = norm(alpha, x, y) if assoc then if a > 0 then - r, g, bl = math.min(r / a, 1), math.min(g / a, 1), math.min(bl / a, 1) + r = math.min(r / a, 1) + g = math.min(g / a, 1) + bl = math.min(bl / a, 1) else r, g, bl = 0, 0, 0 end diff --git a/src/Formats/image/tiff/init.luau b/src/Formats/image/tiff/init.luau index 008fcff..a44f977 100644 --- a/src/Formats/image/tiff/init.luau +++ b/src/Formats/image/tiff/init.luau @@ -322,7 +322,7 @@ local function decodePage(c: Ctx, t: { [number]: Entry }, opts: DecodeOptions?): if not offs or #offs < perPlane * nplanes then return nil, Err.new(Err.CORRUPT, "missing or short strip / tile offsets") end - local planes = table.create(nplanes) + local planes: { buffer } = table.create(nplanes) :: { buffer } for i = 1, nplanes do planes[i] = buffer.create(rb * h + 8) end @@ -583,7 +583,7 @@ function Tiff.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err. end local img, perr = decodePage(c, t, opts) if img then - img.meta.source.pages = #list + (img.meta.source :: { [string]: any }).pages = #list end return img, perr end @@ -608,7 +608,7 @@ function Tiff.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err. table.insert(frames, { image = img, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" }) end local img = first :: Types.Image - img.meta.source.pages = #frames + (img.meta.source :: { [string]: any }).pages = #frames if #frames > 1 then img.frames = frames :: any end @@ -722,7 +722,7 @@ local function encodePage(img: Types.Image, o: EncodeOptions, comp: number): ({ end local text = img.meta and img.meta.text if type(text) == "table" then - for key, tag in { description = 270, software = 305, datetime = 306, artist = 315, copyright = 33432 } do + for key, tag in { description = 270, software = 305, datetime = 306, artist = 315, copyright = 33432 } :: { [string]: number } do if type(text[key]) == "string" then table.insert(tags, { tag = tag, typ = 2, data = buffer.fromstring(text[key] .. "\0") }) end diff --git a/src/Formats/layered/psd/Channels.luau b/src/Formats/layered/psd/Channels.luau index 51ce6de..b44657e 100644 --- a/src/Formats/layered/psd/Channels.luau +++ b/src/Formats/layered/psd/Channels.luau @@ -57,7 +57,7 @@ function Channels.rleCounts(src: buffer, p: number, limit: number, rows: number, if rows < 0 or p + rows * size > limit then return nil, p end - local counts = table.create(rows) + local counts: { number } = table.create(rows) :: { number } for i = 1, rows do if psb then counts[i] = byteswap(readu32(src, p)) @@ -247,11 +247,15 @@ function Channels.toRGBA(planes: { [any]: buffer }, w: number, h: number, depth: local mm = if c2 then sample8(c2, i, depth) else 255 local yy = if c3 then sample8(c3, i, depth) else 255 local kk = if c4 then sample8(c4, i, depth) else 255 - r, g, b = floor(cc * kk / 255 + 0.5), floor(mm * kk / 255 + 0.5), floor(yy * kk / 255 + 0.5) + r = floor(cc * kk / 255 + 0.5) + g = floor(mm * kk / 255 + 0.5) + b = floor(yy * kk / 255 + 0.5) elseif mode == 2 then local k = if c1 then readu8(c1, i) else 0 if palette and blen(palette) >= 768 then - r, g, b = readu8(palette, k), readu8(palette, 256 + k), readu8(palette, 512 + k) + r = readu8(palette, k) + g = readu8(palette, 256 + k) + b = readu8(palette, 512 + k) else r, g, b = k, k, k end diff --git a/src/Formats/music/midi/Render.luau b/src/Formats/music/midi/Render.luau index 657246a..a40aa56 100644 --- a/src/Formats/music/midi/Render.luau +++ b/src/Formats/music/midi/Render.luau @@ -153,7 +153,7 @@ function Render.timeline(midi: Types.Midi): Timeline end return a[3] < b[3] end) - local tl: Timeline = { time = table.create(#items), status = table.create(#items), d1 = table.create(#items), d2 = table.create(#items), length = Render.length(midi) } + local tl: Timeline = { time = table.create(#items) :: { number }, status = table.create(#items) :: { number }, d1 = table.create(#items) :: { number }, d2 = table.create(#items) :: { number }, length = Render.length(midi) } for i, it in items do tl.time[i], tl.status[i], tl.d1[i], tl.d2[i] = it[1], it[4], it[5] % 128, it[6] % 128 end @@ -192,7 +192,7 @@ function Render.decoder(midi: Types.Midi, opts: RenderOptions?): (Types.Decoder? local tail = o.tail or 1 local frames = math.max(0, math.ceil((tl.length + tail) * rate)) local nev = #tl.time - local evFrame = table.create(nev) + local evFrame: { number } = table.create(nev) :: { number } for i = 1, nev do evFrame[i] = math.floor(tl.time[i] * rate + 0.5) end diff --git a/src/Formats/music/midi/Smf.luau b/src/Formats/music/midi/Smf.luau index ed69595..b8e0e61 100644 --- a/src/Formats/music/midi/Smf.luau +++ b/src/Formats/music/midi/Smf.luau @@ -25,7 +25,7 @@ export type WriteOptions = { } local function bytesOf(b: buffer, p: number, n: number): { number } - local t: { number } = table.create(n) + local t: { number } = table.create(n) :: { number } for i = 0, n - 1 do t[i + 1] = readu8(b, p + i) end @@ -309,7 +309,7 @@ function Smf.write(midi: Types.Midi, opts: WriteOptions?): (buffer?, Err.Err?) end last = ev.tick end - local list = events + local list: { any } = events if not sorted then list = table.clone(events) local order: { [any]: number } = {} diff --git a/src/Formats/music/s3m/init.luau b/src/Formats/music/s3m/init.luau index f7a80f7..dd27e0e 100644 --- a/src/Formats/music/s3m/init.luau +++ b/src/Formats/music/s3m/init.luau @@ -204,7 +204,8 @@ function S3m.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) vol = math.min(pr:u8(), 64) + 1 end if bit32.band(what, 0x80) ~= 0 then - cmd, info = pr:u8(), pr:u8() + cmd = pr:u8() + info = pr:u8() if cmd > 26 then cmd, info = 0, 0 end diff --git a/src/Formats/music/xm/init.luau b/src/Formats/music/xm/init.luau index d2cbafa..ceddd5a 100644 --- a/src/Formats/music/xm/init.luau +++ b/src/Formats/music/xm/init.luau @@ -149,7 +149,11 @@ function Xm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) param = pr:u8() end else - note, ins, vol, fx, param = b, pr:u8(), pr:u8(), pr:u8(), pr:u8() + note = b + ins = pr:u8() + vol = pr:u8() + fx = pr:u8() + param = pr:u8() end if pr.err then break -- a short pattern: the rest stays empty diff --git a/src/Formats/playlist/pls/init.luau b/src/Formats/playlist/pls/init.luau index ea24213..61f2663 100644 --- a/src/Formats/playlist/pls/init.luau +++ b/src/Formats/playlist/pls/init.luau @@ -136,7 +136,7 @@ end -- ------------------------------------------------------------------------------------------------ decode local function parsePls(ls: { string }, base: string?, baseScheme: string?, warnings: { string }): Result local res: Result = { kind = "playlist", format = "pls", entries = {}, warnings = warnings, meta = {} } - local files, titles, lengths = {}, {}, {} + local files: { [number]: string }, titles: { [number]: string }, lengths: { [number]: string } = {}, {}, {} local declared = nil for _, line in ls do local l = Text.trim(line) diff --git a/src/Formats/playlist/xspf/init.luau b/src/Formats/playlist/xspf/init.luau index b18034c..d93c3ac 100644 --- a/src/Formats/playlist/xspf/init.luau +++ b/src/Formats/playlist/xspf/init.luau @@ -121,7 +121,7 @@ function Xspf.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Playlist?, E for _, list in elements(root, "trackList") do for i, track in elements(list, "track") do local tbase, tscheme = withXmlBase(track, pbase, pscheme) - local locs = {} + local locs: { string } = {} for _, l in elements(track, "location") do local s = trim(Xml.text(l)) if s ~= "" then diff --git a/src/Formats/subtitle/ass/init.luau b/src/Formats/subtitle/ass/init.luau index ee521f4..e0bbb6f 100644 --- a/src/Formats/subtitle/ass/init.luau +++ b/src/Formats/subtitle/ass/init.luau @@ -189,7 +189,7 @@ function Ass.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Subtitles?, E stylesName = name section = "styles" elseif section ~= "script info" and section ~= "events" then - table.insert(sections, { name = name, lines = {} }) + table.insert(sections, { name = name, lines = {} :: { string } }) end continue end diff --git a/src/Formats/vector/svg/Parse.luau b/src/Formats/vector/svg/Parse.luau index 86001c7..827670e 100644 --- a/src/Formats/vector/svg/Parse.luau +++ b/src/Formats/vector/svg/Parse.luau @@ -48,7 +48,7 @@ local LOCAL: { [string]: boolean } = { filter = true, } -local UNSUPPORTED = { text = true, image = true, pattern = true, mask = true, marker = true, filter = true, foreignObject = true, textPath = true, tspan = true } +local UNSUPPORTED: { [string]: boolean } = { text = true, image = true, pattern = true, mask = true, marker = true, filter = true, foreignObject = true, textPath = true, tspan = true } local CONTAINERS = { g = true, a = true, switch = true } local SHAPES = { path = true, rect = true, circle = true, ellipse = true, line = true, polyline = true, polygon = true } @@ -103,7 +103,7 @@ local function specified(n: Node, ctx: Ctx): { [string]: string } for c in string.gmatch(attr(n, "class") or "", "%S+") do classes[c] = true end - local hits = {} + local hits: { Style.Rule } = {} for _, r in ctx.rules do if Style.matches(r.selector, local_(n), attr(n, "id"), classes) then table.insert(hits, r) @@ -296,7 +296,7 @@ local function shape(n: Node, st: { [string]: string }, ctx: Ctx): { PathData.Cm if w <= 0 or h <= 0 then return nil end - local rx, ry = len(attr(n, "rx"), vw, st), len(attr(n, "ry"), vh, st) + local rx: number?, ry: number? = len(attr(n, "rx"), vw, st), len(attr(n, "ry"), vh, st) if rx and rx < 0 then rx = nil end @@ -305,9 +305,9 @@ local function shape(n: Node, st: { [string]: string }, ctx: Ctx): { PathData.Cm end rx = rx or ry or 0 ry = ry or rx - rx, ry = math.min(rx :: number, w / 2), math.min(ry :: number, h / 2) + local rx: number, ry: number = math.min(rx :: number, w / 2), math.min(ry :: number, h / 2) if rx <= 0 or ry <= 0 then - return { { op = "M", x, y }, { op = "L", x + w, y }, { op = "L", x + w, y + h }, { op = "L", x, y + h }, { op = "Z" } } + return { { op = "M", x, y }, { op = "L", x + w, y }, { op = "L", x + w, y + h }, { op = "L", x, y + h }, { op = "Z" } } :: { PathData.Cmd } end local out: { PathData.Cmd } = { { op = "M", x + rx, y }, { op = "L", x + w - rx, y } } PathData.arc(x + w - rx, y, rx, ry, 0, false, true, x + w, y + ry, out) @@ -317,7 +317,7 @@ local function shape(n: Node, st: { [string]: string }, ctx: Ctx): { PathData.Cm PathData.arc(x + rx, y + h, rx, ry, 0, false, true, x, y + h - ry, out) table.insert(out, { op = "L", x, y + ry }) PathData.arc(x, y + ry, rx, ry, 0, false, true, x + rx, y, out) - table.insert(out, { op = "Z" }) + table.insert(out, { op = "Z" } :: PathData.Cmd) return out elseif kind == "circle" or kind == "ellipse" then local cx, cy = len(attr(n, "cx"), vw, st, 0) :: number, len(attr(n, "cy"), vh, st, 0) :: number @@ -338,12 +338,12 @@ local function shape(n: Node, st: { [string]: string }, ctx: Ctx): { PathData.Cm PathData.arc(cx, cy + ry, rx, ry, 0, false, true, cx - rx, cy, out) PathData.arc(cx - rx, cy, rx, ry, 0, false, true, cx, cy - ry, out) PathData.arc(cx, cy - ry, rx, ry, 0, false, true, cx + rx, cy, out) - table.insert(out, { op = "Z" }) + table.insert(out, { op = "Z" } :: PathData.Cmd) return out elseif kind == "line" then local x1, y1 = len(attr(n, "x1"), vw, st, 0) :: number, len(attr(n, "y1"), vh, st, 0) :: number local x2, y2 = len(attr(n, "x2"), vw, st, 0) :: number, len(attr(n, "y2"), vh, st, 0) :: number - return { { op = "M", x1, y1 }, { op = "L", x2, y2 } } + return { { op = "M", x1, y1 }, { op = "L", x2, y2 } } :: { PathData.Cmd } elseif kind == "polyline" or kind == "polygon" then local v = Style.numbers(attr(n, "points")) if #v < 4 then @@ -354,7 +354,7 @@ local function shape(n: Node, st: { [string]: string }, ctx: Ctx): { PathData.Cm table.insert(out, { op = "L", v[i], v[i + 1] }) end if kind == "polygon" then - table.insert(out, { op = "Z" }) + table.insert(out, { op = "Z" } :: PathData.Cmd) end return out end diff --git a/src/Formats/vector/svg/PathData.luau b/src/Formats/vector/svg/PathData.luau index 5cb7887..bf680a2 100644 --- a/src/Formats/vector/svg/PathData.luau +++ b/src/Formats/vector/svg/PathData.luau @@ -91,7 +91,7 @@ function PathData.parse(d: string): ({ Cmd }, boolean) local last = "" -- previous command letter (upper case) local cmd: string? = nil local rel = false - local nums: { number } = table.create(7) + local nums: { number } = table.create(7) :: { number } local function ws() while i <= n do local c = byte(d, i) @@ -175,7 +175,7 @@ function PathData.parse(d: string): ({ Cmd }, boolean) rel = c ~= up i += 1 if up == "Z" then - table.insert(out, { op = "Z" }) + table.insert(out, { op = "Z" } :: Cmd) cx, cy = sx, sy last = "Z" cmd = nil diff --git a/src/Formats/vector/svg/Style.luau b/src/Formats/vector/svg/Style.luau index a48db64..10ff39e 100644 --- a/src/Formats/vector/svg/Style.luau +++ b/src/Formats/vector/svg/Style.luau @@ -194,7 +194,7 @@ local function scan(s: string, i: number): (number?, number) end -- length(s, ref?, fontSize?) -> number in user units | nil. ref: what 100% is (default 100) -local UNITS = { px = 1, pt = 4 / 3, pc = 16, mm = 96 / 25.4, cm = 96 / 2.54, ["in"] = 96, q = 96 / 101.6 } +local UNITS: { [string]: number } = { px = 1, pt = 4 / 3, pc = 16, mm = 96 / 25.4, cm = 96 / 2.54, ["in"] = 96, q = 96 / 101.6 } function Style.length(s: string?, ref: number?, fontSize: number?): number? if s == nil then return nil @@ -355,11 +355,11 @@ function Style.css(text: string, rules: { Rule }?): { Rule } if not s then break end - text = string.sub(text, 1, s - 1) .. string.sub(text, e + 1) + text = string.sub(text, 1, s - 1) .. string.sub(text, (e :: number) + 1) end text = string.gsub(text, "@[%w-]+[^;{]*;", "") for sels, body in string.gmatch(text, "([^{}]+)(%b{})") do - local decls = Style.declarations(string.sub(body, 2, -2)) + local decls = Style.declarations(string.sub(body :: string, 2, -2)) for one in string.gmatch(sels, "[^,]+") do local sel = selector(one) if sel then diff --git a/src/Formats/vector/svg/Write.luau b/src/Formats/vector/svg/Write.luau index 5ca891a..78fb097 100644 --- a/src/Formats/vector/svg/Write.luau +++ b/src/Formats/vector/svg/Write.luau @@ -163,7 +163,7 @@ function Write.vector(v: Types.Vector): (string?, string?) for k, d in p.strokeDashArray do parts[k] = num(tonumber(d) or 0) end - table.insert(attrs, { "stroke-dasharray", table.concat(parts, " ") }) + table.insert(attrs, { "stroke-dasharray", table.concat(parts :: { string }, " ") }) local off = tonumber(p.strokeDashOffset) table.insert(attrs, { "stroke-dashoffset", if off and off ~= 0 then off else nil }) end diff --git a/src/Formats/vector/tiled/Data.luau b/src/Formats/vector/tiled/Data.luau index 927e7ea..449b495 100644 --- a/src/Formats/vector/tiled/Data.luau +++ b/src/Formats/vector/tiled/Data.luau @@ -42,11 +42,11 @@ function Data.base64(text: string, compression: string?): ({ number }?, string?, return nil, "compression " .. compression .. " is not supported", true end local n = buffer.len(bytes) // 4 - local out = table.create(n) + local out: { number } = table.create(n) :: { number } for i = 0, n - 1 do out[i + 1] = buffer.readu32(bytes, i * 4) end - return out, nil + return out, nil, nil end -- toBase64(gids, compression?, level?) -> text | nil, message diff --git a/src/Formats/vector/tiled/init.luau b/src/Formats/vector/tiled/init.luau index 4777295..114ca33 100644 --- a/src/Formats/vector/tiled/init.luau +++ b/src/Formats/vector/tiled/init.luau @@ -144,7 +144,7 @@ function Tiled.encode(map: Types.TileMap, opts: EncodeOptions?): (buffer?, Err.E if o.compression and o.compression ~= "zlib" and o.compression ~= "gzip" then return nil, Err.new(Err.ARG, "compression must be zlib or gzip") end - local wo = { encoding = o.encoding, compression = o.compression, level = o.level } + local wo: Tmx.WriteOptions = { encoding = o.encoding :: string?, compression = o.compression, level = o.level } if fmt == "tmx" or fmt == "tsx" or fmt == "xml" then local doc: any, err: string? if tilesetOnly then diff --git a/src/Formats/video/avi/init.luau b/src/Formats/video/avi/init.luau index 80545df..996ee55 100644 --- a/src/Formats/video/avi/init.luau +++ b/src/Formats/video/avi/init.luau @@ -279,7 +279,7 @@ function AviFormat.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) for _, item in Source.interleave(streams) do table.insert(chunks, { item[1], item[2].data, true }) end - local ok, buf = pcall(Avi.write, { streams = wstreams, microSecPerFrame = usPerFrame, width = width, height = height }, chunks) + local ok, buf = pcall(Avi.write, { streams = wstreams, microSecPerFrame = usPerFrame, width = width, height = height } :: Avi.WOptions, chunks) if not ok then return nil, Err.new(Err.ARG, "internal error: " .. tostring(buf)) end @@ -293,7 +293,7 @@ function AviFormat.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecode if not dmx then return nil, err end - return Video.open(dmx, opts) + return Video.open(dmx, opts :: Video.OpenOptions?) end return AviFormat diff --git a/src/Formats/video/mkv/init.luau b/src/Formats/video/mkv/init.luau index be9766a..619a92d 100644 --- a/src/Formats/video/mkv/init.luau +++ b/src/Formats/video/mkv/init.luau @@ -127,7 +127,7 @@ function Mkv.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Er if not dmx then return nil, err end - return Video.open(dmx, opts) + return Video.open(dmx, opts :: Video.OpenOptions?) end -- ------------------------------------------------------------------------------------------------ extras @@ -151,7 +151,7 @@ function Mkv.subtitles(dmx: any, trackId: number?): Types.Subtitles? if p then local start = p.pts / track.timescale local stop = start + (p.duration or 0) / track.timescale - table.insert(subs.cues, { start = start, stop = stop, text = buffer.tostring(p.data) }) + table.insert(subs.cues, { start = start, stop = stop, text = buffer.tostring(p.data) } :: Types.Cue) end end return subs diff --git a/src/Formats/video/mp4/init.luau b/src/Formats/video/mp4/init.luau index 63d5924..5a7b6ed 100644 --- a/src/Formats/video/mp4/init.luau +++ b/src/Formats/video/mp4/init.luau @@ -318,7 +318,7 @@ function Mp4.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Er if not dmx then return nil, err end - return Video.open(dmx, opts) + return Video.open(dmx, opts :: Video.OpenOptions?) end return Mp4 diff --git a/src/Formats/video/mpegps/init.luau b/src/Formats/video/mpegps/init.luau index 5ab6dac..e26d946 100644 --- a/src/Formats/video/mpegps/init.luau +++ b/src/Formats/video/mpegps/init.luau @@ -145,7 +145,7 @@ function Ps.demux(r: Bytes.Reader, _opts: OpenOptions?): (any, Err.Err?) codecTag = string.format("0x%02x", id % 256), timescale = 90000, streamId = id, - }) + } :: Types.Track) end local dmx = Demux.new("mpegps", tracks, r.buf, { mpeg2 = file.mpeg2, errors = file.errors }) for i, id in file.order do @@ -186,7 +186,7 @@ function Ps.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err if not dmx then return nil, err end - return Video.open(dmx, opts) + return Video.open(dmx, opts :: Video.OpenOptions?) end return Ps diff --git a/src/Formats/video/mpegts/init.luau b/src/Formats/video/mpegts/init.luau index b07bf6f..d79bdeb 100644 --- a/src/Formats/video/mpegts/init.luau +++ b/src/Formats/video/mpegts/init.luau @@ -154,7 +154,7 @@ function Ts.demux(r: Bytes.Reader, _opts: OpenOptions?): (any, Err.Err?) streamType = st, } byPid[pid] = t - table.insert(tracks, t) + table.insert(tracks, t :: Types.Track) return t end for _, s in d.streams do @@ -239,7 +239,7 @@ function Ts.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err if not dmx then return nil, err end - return Video.open(dmx, opts) + return Video.open(dmx, opts :: Video.OpenOptions?) end return Ts diff --git a/src/Formats/video/y4m/init.luau b/src/Formats/video/y4m/init.luau index a5f4c06..8525b03 100644 --- a/src/Formats/video/y4m/init.luau +++ b/src/Formats/video/y4m/init.luau @@ -105,7 +105,7 @@ function Y4m.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) h = tonumber(v) or 0 elseif k == "F" then local a, b = string.match(v, "^(%d+):(%d+)$") - if a and b and tonumber(a) > 0 and tonumber(b) > 0 then + if a and b and (tonumber(a) :: number) > 0 and (tonumber(b) :: number) > 0 then fn, fd = tonumber(a) :: number, tonumber(b) :: number end elseif k == "C" then @@ -203,7 +203,7 @@ function Y4m.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Er if not dmx then return nil, err end - return Video.open(dmx, opts) + return Video.open(dmx, opts :: Video.OpenOptions?) end return Y4m From c0eafd29a54a5510d1ca29723cdcf0a2ba1d5ffb Mon Sep 17 00:00:00 2001 From: 4DBug <github@bug.tools> Date: Sat, 31 Oct 2026 11:01:22 -0500 Subject: [PATCH 12/22] ws-cleanup: consistency (lower-case tags, WAVE channel order, loops = play count, Err messages, caps) - Audio tags keys are lower case everywhere (Types.Tags): FLAC no longer returns TITLE / ARTIST (the raw fields stay in meta.source.comments; also for Vorbis and Opus); Vorbis / Opus / FLAC read and write tags through codecs/VorbisComment (TRACKNUMBER -> track, DISCNUMBER -> disc, DESCRIPTION -> comment); MP3 albumArtist -> albumartist and year -> date (ID3 TYER / TDRC, ID3v1); RIFF INFO / CAF / MP4 freeform names are lower-cased (MP4 writes iTunSMPB / iTunNORM back in their usual spelling; m4a reads tags.itunsmpb). - Channel order: Vorbis (and Opus mapping family 1) decode to WAVE order like FLAC / WAV / AAC (both used to return the Vorbis order); the Vorbis encoder takes WAVE order and writes Vorbis order. Pcm.WAVE_FROM_VORBIS / Pcm.reorder; Vorbis.packetDecoder gives pd.order. Tests reorder oggdec's / opusdec's raw (Vorbis-order) references. - img.loops is the play count in GIF, APNG and WebP (they already agreed; Types / WebP docs said "loop count"); tests/api round-trips loops 0 / 1 / 3 through all three. - Err: messages without the format name (png / midi encoders said "png encode: ..."); codecs/Bzip2 and codecs/Zstd check arguments through Bytes.span. - caps: mp3 encodeLayers = { 2, 3 }, opus encodeChannels = 2. --- docs/FORMATS.md | 8 ++-- src/Formats/Registry.luau | 22 +++++----- src/Formats/Types.luau | 3 +- src/Formats/audio/caf/init.luau | 2 +- src/Formats/audio/flac/Encode.luau | 46 +++------------------ src/Formats/audio/flac/Meta.luau | 7 +++- src/Formats/audio/flac/init.luau | 4 +- src/Formats/audio/m4a/init.luau | 2 +- src/Formats/audio/mp3/Tags.luau | 8 ++-- src/Formats/audio/mp3/init.luau | 2 +- src/Formats/audio/opus/init.luau | 2 +- src/Formats/audio/vorbis/Encode.luau | 26 ++++++------ src/Formats/audio/vorbis/init.luau | 52 +++++++++++++----------- src/Formats/audio/wav/init.luau | 5 ++- src/Formats/codecs/Bzip2/init.luau | 21 ++-------- src/Formats/codecs/Zstd/init.luau | 21 ++-------- src/Formats/containers/IsoBmff/Meta.luau | 6 ++- src/Formats/image/png/init.luau | 10 ++--- src/Formats/image/webp/init.luau | 2 +- src/Formats/music/midi/Smf.luau | 16 ++++---- tests/api.luau | 24 +++++++++++ tests/audio/flac.luau | 5 ++- tests/audio/flac_encode.luau | 6 +-- tests/audio/mp3.luau | 6 +-- tests/audio/vorbis.luau | 12 ++++++ tests/audio/wav.luau | 4 +- tools/fixtures/vorbis_enc.py | 12 +++--- 27 files changed, 164 insertions(+), 170 deletions(-) diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 55d31f1..cbd044d 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -22,8 +22,8 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | audio | caf | .caf .caff | yes | yes | codecs: "pcm", "alac", "aac", "ulaw", "alaw", encodeCodecs: "pcm", "alac", tags: true, streaming: true | `tests/audio/caf.luau` | | audio | flac | .flac .oga | yes | yes | streaming: true, depths: 4, 8, 12, 16, 20, 24, 32, ogg: true, seek: true | `tests/audio/flac.luau` | | audio | m4a | .m4a .m4b .m4r | yes | yes | codecs: "aac", "alac", encodeCodecs: "alac", tags: true, streaming: true | `tests/audio/m4a.luau` | -| audio | mp3 | .mp3 .mp2 .mp1 .mpga | yes | yes | streaming: true, seek: true, layers: 1, 2, 3, channels: 2 | `tests/audio/mp3.luau` | -| audio | opus | .opus | yes | yes | streaming: true, seek: true, lossy: true, channels: 255, rates: 48000, encodeModes: "celt" | `tests/audio/opus.luau` | +| audio | mp3 | .mp3 .mp2 .mp1 .mpga | yes | yes | streaming: true, seek: true, layers: 1, 2, 3, encodeLayers: 2, 3, channels: 2 | `tests/audio/mp3.luau` | +| audio | opus | .opus | yes | yes | streaming: true, seek: true, lossy: true, channels: 255, rates: 48000, encodeModes: "celt", encodeChannels: 2 | `tests/audio/opus.luau` | | audio | voc | .voc | yes | yes | streaming: true, depths: 8, 16, lossy: false | `tests/audio/voc.luau` | | audio | vorbis | .ogg .oga | yes | yes | streaming: true, seek: true, lossy: true, channels: 255 | `tests/audio/vorbis.luau` | | audio | wav | .wav .wave .rf64 .bw64 | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, rf64: true | `tests/audio/wav.luau` | @@ -86,7 +86,6 @@ Codecs (layer 1, shared by formats; not loadable on their own): - codecs/Aac: AAC-LC decoder (ISO/IEC 14496-3 subpart 4, ISO/IEC 13818-7): the AudioSpecificConfig (with a program - codecs/Alac: Apple Lossless (ALAC) decoder and encoder, the codec inside m4a / mov / caf. A codec (layer 1). -- codecs/Base64: RFC 4648 base64 (standard alphabet, and base64url with opts.url) encode / decode, for data: URIs - codecs/Blend: layer compositing on rgba8 buffers (straight alpha): source-over with the separable and non-separable - codecs/Brotli: Brotli (RFC 7932) decompression. A codec (layer 3): archive/br and font/woff2 build on it. Written - codecs/Bzip2: bzip2 decompressor (BWT + MTF + Huffman, the .bz2 stream format of bzip2 0.9.5 / 1.0.x). A codec @@ -102,13 +101,16 @@ Codecs (layer 1, shared by formats; not loadable on their own): - codecs/Mpeg1: an MPEG-1 video decoder (ISO/IEC 11172-2) for the MPEG-TS / MPEG-PS video formats. Absorbed from - codecs/Pcm: PCM plumbing shared by audio formats: raw sample formats, streaming Decoders, encoder input sources. - codecs/Quantize: palette quantization of rgba8 pixels. A codec (layer 1): image/gif (and later any palette +- codecs/RangeCoder: the RFC 6716 range coder (libopus celt/entdec.c + entenc.c, BSD: licenses/libopus-BSD.txt): - codecs/Raster: an antialiased scanline rasterizer for paths of lines, quadratic and cubic Béziers, under an affine +- codecs/Resample: audio sample-rate conversion by band-limited (Kaiser-windowed sinc) interpolation, streaming or - codecs/SoundFont: SoundFont 2 banks and the sample synth that plays MIDI through them. A codec (layer 1) shared by - codecs/Text: text decoding helpers for the text formats: a UTF-8 BOM is stripped, text that is not valid UTF-8 is - codecs/Tracker: the shared tracker engine behind music/mod, music/s3m, music/xm and music/it. The four loaders read - codecs/TrueType: the sfnt font container (TrueType .ttf, OpenType .otf with CFF outlines, collections .ttc) parsed - codecs/Url: RFC 3986 reference resolution (section 5.2), the classification of a playlist / manifest location (URL, - codecs/Video: the video codec registry and the generic VideoDecoder. New in formats-luau. +- codecs/VorbisComment: Vorbis comment fields ("KEY=value", the tag block of Vorbis, Opus and FLAC) <-> Types.Tags. - codecs/Vp8: the VP8 video codec (RFC 6386), decode only. A codec (layer 1): image/webp uses it for lossy frames, the - codecs/Vp8L: WebP lossless (VP8L, "WebP Lossless Bitstream Specification", RFC 9649 section 3). A codec (layer 1): - codecs/Xml: XML 1.0 parse (DOM and pull events) and serialize, the engine data/xml, SVG, DAE, 3MF, TMX, plist, ... diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 00b867a..527fc03 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -200,7 +200,7 @@ local list: { Entry } = { path = "audio/flac", extensions = { "flac", "oga" }, mime = { "audio/flac", "audio/x-flac" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "core/Md5", "codecs/Pcm" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "core/Md5", "codecs/Pcm", "codecs/VorbisComment" }, caps = { decode = true, encode = true, streaming = true, depths = { 4, 8, 12, 16, 20, 24, 32 }, ogg = true, seek = true }, load = function() return require("@formats/audio/flac") @@ -224,8 +224,8 @@ local list: { Entry } = { path = "audio/mp3", extensions = { "mp3", "mp2", "mp1", "mpga" }, mime = { "audio/mpeg", "audio/mp3", "audio/mpa" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" }, - caps = { decode = true, encode = true, streaming = true, seek = true, layers = { 1, 2, 3 }, channels = 2 }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm", "codecs/Resample" }, + caps = { decode = true, encode = true, streaming = true, seek = true, layers = { 1, 2, 3 }, encodeLayers = { 2, 3 }, channels = 2 }, load = function() return require("@formats/audio/mp3") end, @@ -236,8 +236,8 @@ local list: { Entry } = { path = "audio/opus", extensions = { "opus" }, mime = { "audio/opus", "audio/ogg" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct" }, - caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255, rates = { 48000 }, encodeModes = { "celt" } }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct", "codecs/RangeCoder/Decoder", "codecs/RangeCoder/Encoder", "codecs/Pcm", "codecs/Resample", "codecs/VorbisComment" }, + caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255, rates = { 48000 }, encodeModes = { "celt" }, encodeChannels = 2 }, load = function() return require("@formats/audio/opus") end, @@ -260,7 +260,7 @@ local list: { Entry } = { path = "audio/vorbis", extensions = { "ogg", "oga" }, mime = { "audio/ogg", "audio/vorbis" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct", "codecs/Pcm" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct", "codecs/Pcm", "codecs/VorbisComment" }, caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255 }, load = function() return require("@formats/audio/vorbis") @@ -368,7 +368,7 @@ local list: { Entry } = { path = "model/dae", extensions = { "dae", "zae" }, mime = { "model/vnd.collada+xml", "model/vnd.collada+zip" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "codecs/Base64", "containers/Zip" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "core/Base64", "containers/Zip" }, caps = { decode = true, encode = true, materials = true, polygons = true, skins = true, morphTargets = true, animation = true, cameras = true, lights = true, zae = true }, load = function() return require("@formats/model/dae") @@ -392,7 +392,7 @@ local list: { Entry } = { path = "model/gltf", extensions = { "gltf", "glb" }, mime = { "model/gltf+json", "model/gltf-binary" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Json", "codecs/Base64" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Json", "core/Base64" }, caps = { decode = true, encode = true, binary = true, materials = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true }, load = function() return require("@formats/model/gltf") @@ -692,7 +692,7 @@ local list: { Entry } = { path = "data/plist", extensions = { "plist" }, mime = { "application/x-plist", "application/x-bplist" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "codecs/Json" }, + deps = { "core/Err", "core/Bytes", "Types", "core/Base64", "codecs/Xml", "codecs/Json" }, caps = { decode = true, encode = true, binary = "read", ordered = true }, load = function() return require("@formats/data/plist") @@ -704,7 +704,7 @@ local list: { Entry } = { path = "data/toml", extensions = { "toml" }, mime = { "application/toml" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Json" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Json", "codecs/Text" }, caps = { decode = true, encode = true, ordered = true, dates = true }, load = function() return require("@formats/data/toml") @@ -728,7 +728,7 @@ local list: { Entry } = { path = "data/yaml", extensions = { "yaml", "yml" }, mime = { "application/yaml", "application/x-yaml", "text/yaml" }, - deps = { "core/Err", "core/Bytes", "Types" }, + deps = { "core/Err", "core/Bytes", "Types", "core/Base64", "codecs/Text" }, caps = { decode = true, encode = true, ordered = true, multiDocument = true, anchors = true }, load = function() return require("@formats/data/yaml") diff --git a/src/Formats/Types.luau b/src/Formats/Types.luau index cfaf6c7..bc9bf97 100644 --- a/src/Formats/Types.luau +++ b/src/Formats/Types.luau @@ -59,7 +59,8 @@ export type Image = { format: PixelFormat, pixels: buffer, frames: { Frame }?, -- animations: frame 1 is also width x height pixels (the composited first frame) - loops: number, -- 0 = forever + loops: number, -- play count: how many times the animation plays, 0 = forever (GIF stores repeats: plays - 1; APNG + -- num_plays and the WebP ANIM loop count are play counts) meta: ImageMeta, } diff --git a/src/Formats/audio/caf/init.luau b/src/Formats/audio/caf/init.luau index f602434..a2fe2c5 100644 --- a/src/Formats/audio/caf/init.luau +++ b/src/Formats/audio/caf/init.luau @@ -222,7 +222,7 @@ local function parse(r: Bytes.Reader, o: DecodeOptions): (Parsed?, Err.Err?) if c.err then break end - p.tags[INFO_TAGS[string.lower(k)] or k] = v + p.tags[INFO_TAGS[string.lower(k)] or string.lower(k)] = v end end r.pos = stop diff --git a/src/Formats/audio/flac/Encode.luau b/src/Formats/audio/flac/Encode.luau index 499f4c0..e6a0297 100644 --- a/src/Formats/audio/flac/Encode.luau +++ b/src/Formats/audio/flac/Encode.luau @@ -11,6 +11,8 @@ -- SEEKTABLE. Streams: input blocks are pulled from a codecs/Pcm Source, so a Decoder is encoded without decoding it -- whole. Never throws: bad options are rejected by audio/flac before calling in. local Md5 = require("@formats/core/Md5") +local VorbisComment = require("@formats/codecs/VorbisComment") +local Frame = require("@formats/audio/flac/Frame") local Encode = {} @@ -23,33 +25,12 @@ for i = 0, 63 do end -- ------------------------------------------------------------------------------------------------ CRCs -local CRC8 = table.create(256, 0) -local CRC16 = table.create(256, 0) -for i = 0, 255 do - local c = i - for _ = 1, 8 do - c = if c >= 128 then bit32.bxor((c * 2) % 256, 0x07) else c * 2 - end - CRC8[i + 1] = c - local d = i * 256 - for _ = 1, 8 do - d = if d >= 32768 then bit32.bxor((d * 2) % 65536, 0x8005) else d * 2 - end - CRC16[i + 1] = d -end +-- (the decoder's tables: audio/flac/Frame; (b, offset, count) here) local function crc8(b: buffer, o: number, n: number): number - local c = 0 - for i = o, o + n - 1 do - c = CRC8[bit32.bxor(c, buffer.readu8(b, i)) + 1] - end - return c + return Frame.crc8(b, o, o + n) end local function crc16(b: buffer, o: number, n: number): number - local c = 0 - for i = o, o + n - 1 do - c = bit32.bxor((c * 256) % 65536, CRC16[bit32.bxor(c // 256, buffer.readu8(b, i)) + 1]) - end - return c + return Frame.crc16(b, o, o + n) end Encode.crc8, Encode.crc16 = crc8, crc16 @@ -702,8 +683,6 @@ export type Options = { vendor: string, } -local TAG_NAMES = { track = "TRACKNUMBER" } - -- encode(src, opts) -> buffer | nil, message function Encode.encode(src: Source, opts: Options): (buffer?, string?) local cfg = PRESETS[opts.level + 1] @@ -730,20 +709,7 @@ function Encode.encode(src: Source, opts: Options): (buffer?, string?) end end -- vorbis comment - local comments = {} - local keys = {} - for k in src.tags do - if type(k) == "string" then - table.insert(keys, k) - end - end - table.sort(keys) - for _, k in keys do - local v = src.tags[k] - if type(v) == "string" then - table.insert(comments, (TAG_NAMES[k] or string.upper(k)) .. "=" .. v) - end - end + local comments = VorbisComment.fields(src.tags) local vendor = opts.vendor local vcLen = 4 + #vendor + 4 for _, c in comments do diff --git a/src/Formats/audio/flac/Meta.luau b/src/Formats/audio/flac/Meta.luau index 0c81354..1b1508b 100644 --- a/src/Formats/audio/flac/Meta.luau +++ b/src/Formats/audio/flac/Meta.luau @@ -4,6 +4,8 @@ -- audio/flac/Meta: FLAC metadata blocks: STREAMINFO, SEEKTABLE, VORBIS_COMMENT and PICTURE (its fields are listed, the image is -- left in place); every other block is skipped. Nothing throws: bad data gives nil, err. -- Absorbed from flac-luau 7083d0d (same author, no third-party code). +local VorbisComment = require("@formats/codecs/VorbisComment") + local readu8, readu32 = buffer.readu8, buffer.readu32 local Meta = {} @@ -102,8 +104,9 @@ local function vorbisComment(b: buffer, p: number, e: number, info: Info): boole p += l local eq = string.find(s, "=", 1, true) if eq then - local key, value = string.upper(string.sub(s, 1, eq - 1)), string.sub(s, eq + 1) - table.insert(info.comments, { key = key, value = value }) + local name, value = string.sub(s, 1, eq - 1), string.sub(s, eq + 1) + table.insert(info.comments, { key = string.upper(name), value = value }) + local key = VorbisComment.tagKey(name) local old = info.tags[key] info.tags[key] = if old then old .. "; " .. value else value end diff --git a/src/Formats/audio/flac/init.luau b/src/Formats/audio/flac/init.luau index 88e5f22..724774d 100644 --- a/src/Formats/audio/flac/init.luau +++ b/src/Formats/audio/flac/init.luau @@ -29,7 +29,7 @@ local Flac = { category = "audio", extensions = { "flac", "oga" }, mime = { "audio/flac", "audio/x-flac" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "core/Md5", "codecs/Pcm" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "core/Md5", "codecs/Pcm", "codecs/VorbisComment" }, caps = { decode = true, encode = true, streaming = true, depths = { 4, 8, 12, 16, 20, 24, 32 }, ogg = true, seek = true }, } @@ -115,7 +115,7 @@ function Flac.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Er o += n end a.tags = d.tags - a.meta.source = { format = "flac", bitDepth = d.bitsPerSample, container = d.container, vendor = d.vendor, md5 = d.md5, pictures = d.pictures } + a.meta.source = { format = "flac", bitDepth = d.bitsPerSample, container = d.container, vendor = d.vendor, md5 = d.md5, pictures = d.pictures, comments = d.comments } return a, nil end diff --git a/src/Formats/audio/m4a/init.luau b/src/Formats/audio/m4a/init.luau index bf64abb..6e55db0 100644 --- a/src/Formats/audio/m4a/init.luau +++ b/src/Formats/audio/m4a/init.luau @@ -167,7 +167,7 @@ function M4a.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.E end local tags, pictures = IsoBmff.tags(r, movie) -- iTunes gapless info (fdkaac, iTunes) when there is no edit list: " 0 <priming> <padding> <samples> ..." (hex) - local smpb = tags.iTunSMPB + local smpb = tags.itunsmpb if gapless and not t.edits and smpb then local f = {} for w in string.gmatch(smpb, "%x+") do diff --git a/src/Formats/audio/mp3/Tags.luau b/src/Formats/audio/mp3/Tags.luau index 329c297..45ebe26 100644 --- a/src/Formats/audio/mp3/Tags.luau +++ b/src/Formats/audio/mp3/Tags.luau @@ -35,8 +35,8 @@ local FIELDS = { TIT2 = "title", TT2 = "title", TPE1 = "artist", TP1 = "artist", TALB = "album", TAL = "album", - TPE2 = "albumArtist", TP2 = "albumArtist", - TYER = "year", TYE = "year", TDRC = "year", + TPE2 = "albumartist", TP2 = "albumartist", + TYER = "date", TYE = "date", TDRC = "date", TRCK = "track", TRK = "track", TPOS = "disc", TPA = "disc", TCON = "genre", TCO = "genre", @@ -257,7 +257,7 @@ local function v1String(b: buffer, o: number, n: number): string end -- Parses tags and returns (tags, audio start, audio end) for the buffer b. --- tags = { title?, artist?, album?, albumArtist?, year?, track?, disc?, genre?, composer?, comment?, +-- tags = { title?, artist?, album?, albumartist?, date?, track?, disc?, genre?, composer?, comment?, -- raw = { [frame id] = text }, id3v2 = "2.3"?, id3v1 = true? } function Tags.parse(b: buffer): (any, number, number) local len = buffer.len(b) @@ -277,7 +277,7 @@ function Tags.parse(b: buffer): (any, number, number) title = v1String(b, o + 3, 30), artist = v1String(b, o + 33, 30), album = v1String(b, o + 63, 30), - year = v1String(b, o + 93, 4), + date = v1String(b, o + 93, 4), } if ru8(b, o + 125) == 0 and ru8(b, o + 126) ~= 0 then v1.comment = v1String(b, o + 97, 28) diff --git a/src/Formats/audio/mp3/init.luau b/src/Formats/audio/mp3/init.luau index af05e04..9fd3a8c 100644 --- a/src/Formats/audio/mp3/init.luau +++ b/src/Formats/audio/mp3/init.luau @@ -33,7 +33,7 @@ local Mp3 = { extensions = { "mp3", "mp2", "mp1", "mpga" }, mime = { "audio/mpeg", "audio/mp3", "audio/mpa" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm", "codecs/Resample" }, - caps = { decode = true, encode = true, streaming = true, seek = true, layers = { 1, 2, 3 }, channels = 2 }, + caps = { decode = true, encode = true, streaming = true, seek = true, layers = { 1, 2, 3 }, encodeLayers = { 2, 3 }, channels = 2 }, } -- ------------------------------------------------------------------------------------------------ types diff --git a/src/Formats/audio/opus/init.luau b/src/Formats/audio/opus/init.luau index 3dee5af..9138762 100644 --- a/src/Formats/audio/opus/init.luau +++ b/src/Formats/audio/opus/init.luau @@ -38,7 +38,7 @@ local Opus = { extensions = { "opus" }, mime = { "audio/opus", "audio/ogg" }, deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct", "codecs/RangeCoder/Decoder", "codecs/RangeCoder/Encoder", "codecs/Pcm", "codecs/Resample", "codecs/VorbisComment" }, - caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255, rates = { 48000 }, encodeModes = { "celt" } }, + caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255, rates = { 48000 }, encodeModes = { "celt" }, encodeChannels = 2 }, } -- ------------------------------------------------------------------------------------------------ types diff --git a/src/Formats/audio/vorbis/Encode.luau b/src/Formats/audio/vorbis/Encode.luau index f15a212..2b1405e 100644 --- a/src/Formats/audio/vorbis/Encode.luau +++ b/src/Formats/audio/vorbis/Encode.luau @@ -11,6 +11,8 @@ -- models computed at load time (codewords assigned exactly as the spec's decoder does). Granules are sample-exact -- (frames centred on multiples of 1024 from sample 0; the last page's granule trims the end). Never throws. local Mdct = require("@formats/codecs/Mdct") +local Pcm = require("@formats/codecs/Pcm") +local VorbisComment = require("@formats/codecs/VorbisComment") local Ogg = require("@formats/containers/Ogg") local Tables = require("@formats/audio/vorbis/Tables") @@ -448,17 +450,9 @@ local function commentHeader(vendor: string, tags: { [string]: string }): buffer putString(w, "vorbis") put(w, #vendor, 32) putString(w, vendor) - local keys = {} - for k, v in tags do - if type(k) == "string" and type(v) == "string" then - table.insert(keys, k) - end - end - table.sort(keys) - put(w, #keys, 32) - for _, k in keys do - local name = if k == "track" then "TRACKNUMBER" else string.upper(k) - local s = name .. "=" .. tags[k] + local fields = VorbisComment.fields(tags) + put(w, #fields, 32) + for _, s in fields do put(w, #s, 32) putString(w, s) end @@ -614,6 +608,14 @@ function Encode.encode(src: Source, opts: Options): (buffer?, string?) for c = 1, ch do frame[c] = table.create(N, 0) end + -- the input is in WAVE channel order; input channel c goes to Vorbis channel order[c] + local order = Pcm.WAVE_FROM_VORBIS[ch] or {} + if #order ~= ch then + order = table.create(ch, 0) + for c = 1, ch do + order[c] = c + end + end local blk = table.create(N, 0) local X = table.create(ch) local R = table.create(ch) @@ -658,7 +660,7 @@ function Encode.encode(src: Source, opts: Options): (buffer?, string?) for i = 0, take - 1 do local base = (pendOff + i) * ch * 4 for c = 1, ch do - frame[c][N2 + got + i + 1] = buffer.readf32(pb, base + (c - 1) * 4) + frame[order[c]][N2 + got + i + 1] = buffer.readf32(pb, base + (c - 1) * 4) end end got += take diff --git a/src/Formats/audio/vorbis/init.luau b/src/Formats/audio/vorbis/init.luau index e432adf..0cc48bc 100644 --- a/src/Formats/audio/vorbis/init.luau +++ b/src/Formats/audio/vorbis/init.luau @@ -19,6 +19,7 @@ local Setup = require("@formats/audio/vorbis/Setup") local Packet = require("@formats/audio/vorbis/Packet") local Encode = require("@formats/audio/vorbis/Encode") local Pcm = require("@formats/codecs/Pcm") +local VorbisComment = require("@formats/codecs/VorbisComment") -- ------------------------------------------------------------------------------------------------ contract local Vorbis = { @@ -26,7 +27,7 @@ local Vorbis = { category = "audio", extensions = { "ogg", "oga" }, mime = { "audio/ogg", "audio/vorbis" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct", "codecs/Pcm" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct", "codecs/Pcm", "codecs/VorbisComment" }, caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255 }, } @@ -40,38 +41,36 @@ export type EncodeOptions = { } -- ------------------------------------------------------------------------------------------------ constants -local TAG_KEYS = { tracknumber = "track", description = "comment" } - -local function tagsOf(comments: { string }): Types.Tags - local tags: Types.Tags = {} - for _, s in comments do - local eq = string.find(s, "=", 1, true) - if eq then - local k = string.lower(string.sub(s, 1, eq - 1)) - local v = string.sub(s, eq + 1) - k = TAG_KEYS[k] or k - tags[k] = if tags[k] then tags[k] .. "; " .. v else v - end +-- waveOrder(channels) -> output channel c is Vorbis channel order[c] (codecs/Pcm; identity past 8 channels) +local function waveOrder(ch: number): { number } + local m = Pcm.WAVE_FROM_VORBIS[ch] + if m then + return m end - return tags + local id = table.create(ch, 0) + for c = 1, ch do + id[c] = c + end + return id end --- the three headers -> ident, setup, vendor, tags | nil, Err -local function headers(h1: any, h2: any, h3: any): (any, any, string?, Types.Tags?, Err.Err?) +-- the three headers -> ident, setup, vendor, tags, raw comment fields | nil, Err +local function headers(h1: any, h2: any, h3: any): (any, any, string?, Types.Tags?, { VorbisComment.Field }?, Err.Err?) local id, ierr = Setup.ident(h1.data, h1.offset, h1.size) if not id then - return nil, nil, nil, nil, Err.new(Err.CORRUPT, ierr or "bad identification header") + return nil, nil, nil, nil, nil, Err.new(Err.CORRUPT, ierr or "bad identification header") end local vendor, comments = Setup.comment(h2.data, h2.offset, h2.size) if not vendor then - return nil, nil, nil, nil, Err.new(Err.CORRUPT, "bad comment header") + return nil, nil, nil, nil, nil, Err.new(Err.CORRUPT, "bad comment header") end local setup, serr = Setup.setup(h3.data, h3.offset, h3.size, id) if not setup then local code = if serr == "floor 0" then Err.UNSUPPORTED else Err.CORRUPT - return nil, nil, nil, nil, Err.new(code, serr or "bad setup header") + return nil, nil, nil, nil, nil, Err.new(code, serr or "bad setup header") end - return id, setup, vendor, tagsOf(comments or {}), nil + local tags, raw = VorbisComment.tags(comments or {}) + return id, setup, vendor, tags, raw, nil end -- ------------------------------------------------------------------------------------------------ sniff @@ -244,8 +243,9 @@ function Stream.read(self: any, n: number, out: buffer?): (buffer, number) end local arrays, first, last = q[1], q[2], q[3] local take = math.min(n - got, last - first + 1) + local order = self.order for c = 1, ch do - local a = arrays[c] + local a = arrays[order[c]] local o = got * ch * 4 + (c - 1) * 4 for i = first, first + take - 1 do writef32(b, o, a[i]) @@ -373,7 +373,7 @@ function Vorbis.open(r: any, opts: OpenOptions?): (Types.Decoder?, Err.Err?) if h3 == nil then return nil, Err.new(Err.TRUNCATED, "missing setup header") end - local id, setup, vendor, tags, herr = headers(h1, h2copy, h3) + local id, setup, vendor, tags, raw, herr = headers(h1, h2copy, h3) if not id then return nil, herr end @@ -420,10 +420,13 @@ function Vorbis.open(r: any, opts: OpenOptions?): (Types.Decoder?, Err.Err?) tags = tags, vendor = vendor, ident = id, + -- WAVE channel order out (codecs/Pcm): output channel c is Vorbis channel order[c] + order = waveOrder(id.channels), source = { format = "vorbis", codec = "vorbis", vendor = vendor, + comments = raw, blocksizes = { id.blocksize0, id.blocksize1 }, nominalBitrate = id.bitrateNominal, }, @@ -456,7 +459,7 @@ function Vorbis.packetDecoder(h1: buffer, h2: buffer, h3: buffer): (any, Err.Err local function pk(b: buffer): any return { data = b, offset = 0, size = buffer.len(b) } end - local id, setup, vendor, tags, err = headers(pk(h1), pk(h2), pk(h3)) + local id, setup, vendor, tags, _, err = headers(pk(h1), pk(h2), pk(h3)) if not id then return nil, err end @@ -469,7 +472,8 @@ function Vorbis.packetDecoder(h1: buffer, h2: buffer, h3: buffer): (any, Err.Err channels = id.channels, vendor = vendor, tags = tags, - out = st.out, + out = st.out, -- per Vorbis channel; WAVE-order channel c is out[order[c]] + order = waveOrder(id.channels), decode = function(_self: any, b: buffer, offset: number, size: number): number if offset < 0 or size < 0 or offset + size > buffer.len(b) then return -1 diff --git a/src/Formats/audio/wav/init.luau b/src/Formats/audio/wav/init.luau index 81ef5b4..ed5d071 100644 --- a/src/Formats/audio/wav/init.luau +++ b/src/Formats/audio/wav/init.luau @@ -304,7 +304,8 @@ local function encodeParts(value: any, opts: EncodeOptions?, asParts: boolean): table.sort(keys) for _, k in keys do local v = tags[k] - local id = TAG_IDS[k] or (if #k == 4 and string.upper(k) == k then k else nil) + -- other RIFF INFO ids come back as their lower-cased id ("ixyz") and are written as such + local id = TAG_IDS[k] or (if string.match(string.lower(k), "^i[%l%d][%l%d][%l%d]$") then string.upper(k) else nil) if id and type(v) == "string" and v ~= "" then table.insert(items, { id, v }) end @@ -383,7 +384,7 @@ function Wav.open(r: Bytes.Reader, _opts: OpenOptions?): (Decoder?, Err.Err?) if sc.avail > 0 then local v = trimTag(buffer.readstring(buf, sc.offset, sc.avail)) if v ~= "" then - tags[name or sc.id] = v + tags[name or string.lower(sc.id)] = v end end end diff --git a/src/Formats/codecs/Bzip2/init.luau b/src/Formats/codecs/Bzip2/init.luau index e492aee..c9a2584 100644 --- a/src/Formats/codecs/Bzip2/init.luau +++ b/src/Formats/codecs/Bzip2/init.luau @@ -10,6 +10,7 @@ -- -- Never throws: bad data and bad arguments return nil, Err (TRUNCATED / CORRUPT / CHECKSUM / LIMIT / ARG). local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") local Decode = require("@formats/codecs/Bzip2/Decode") local Bzip2 = {} @@ -28,24 +29,10 @@ local KINDS = { -- decompress(buf, offset?, length?, opts?) -> buffer, consumedEnd | nil, Err function Bzip2.decompress(buf: buffer | string, offset: number?, length: number?, opts: Options?): (buffer?, any) - local b: buffer - if type(buf) == "string" then - b = buffer.fromstring(buf) - elseif type(buf) == "buffer" then - b = buf - else - return nil, Err.new(Err.ARG, "Bzip2.decompress: expected a buffer or a string, got " .. typeof(buf)) + local b, o, l, aerr = Bytes.span("Bzip2.decompress", buf, offset, length) + if not b then + return nil, aerr end - local n = buffer.len(b) - local o = offset or 0 - if type(o) ~= "number" or o < 0 or o > n or o % 1 ~= 0 then - return nil, Err.new(Err.ARG, "Bzip2.decompress: bad offset " .. tostring(offset)) - end - local l = length or (n - o) - if type(l) ~= "number" or l < 0 or l % 1 ~= 0 then - return nil, Err.new(Err.ARG, "Bzip2.decompress: bad length " .. tostring(length)) - end - l = math.min(l, n - o) local maxBytes = if opts and opts.maxBytes ~= nil then opts.maxBytes else 2 ^ 30 if type(maxBytes) ~= "number" or maxBytes < 0 then return nil, Err.new(Err.ARG, "Bzip2.decompress: bad maxBytes") diff --git a/src/Formats/codecs/Zstd/init.luau b/src/Formats/codecs/Zstd/init.luau index c48de03..5a1c5f3 100644 --- a/src/Formats/codecs/Zstd/init.luau +++ b/src/Formats/codecs/Zstd/init.luau @@ -11,6 +11,7 @@ -- -- Never throws: bad data and bad arguments return nil, Err (TRUNCATED / CORRUPT / CHECKSUM / UNSUPPORTED / LIMIT / ARG). local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") local Decode = require("@formats/codecs/Zstd/Decode") local Zstd = {} @@ -44,24 +45,10 @@ end -- decompress(buf, offset?, length?, opts?) -> buffer, consumedEnd | nil, Err. Every frame in the range is decoded -- and the outputs concatenated; data after the last frame that is not a frame is an error (as zstd -d does). function Zstd.decompress(buf: buffer | string, offset: number?, length: number?, opts: Options?): (buffer?, any) - local b: buffer - if type(buf) == "string" then - b = buffer.fromstring(buf) - elseif type(buf) == "buffer" then - b = buf - else - return nil, Err.new(Err.ARG, "Zstd.decompress: expected a buffer or a string, got " .. typeof(buf)) + local b, o, l, aerr = Bytes.span("Zstd.decompress", buf, offset, length) + if not b then + return nil, aerr end - local n = buffer.len(b) - local o = offset or 0 - if type(o) ~= "number" or o < 0 or o > n or o % 1 ~= 0 then - return nil, Err.new(Err.ARG, "Zstd.decompress: bad offset " .. tostring(offset)) - end - local l = length or (n - o) - if type(l) ~= "number" or l < 0 or l % 1 ~= 0 then - return nil, Err.new(Err.ARG, "Zstd.decompress: bad length " .. tostring(length)) - end - l = math.min(l, n - o) local maxBytes = if opts and opts.maxBytes ~= nil then opts.maxBytes else 2 ^ 30 if type(maxBytes) ~= "number" or maxBytes < 0 then return nil, Err.new(Err.ARG, "Zstd.decompress: bad maxBytes " .. tostring(maxBytes)) diff --git a/src/Formats/containers/IsoBmff/Meta.luau b/src/Formats/containers/IsoBmff/Meta.luau index a7c44ca..e836b64 100644 --- a/src/Formats/containers/IsoBmff/Meta.luau +++ b/src/Formats/containers/IsoBmff/Meta.luau @@ -312,6 +312,8 @@ for atom, name in TAG do 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 = { @@ -384,7 +386,7 @@ function Meta.tags(b: buffer, ilst: Box.Box?): ({ [string]: string }, { Picture table.insert(pics, { mime = mime, data = data }) elseif kind == 1 or kind == 0 then local s = readstring(b, p, n) - local key = freeName or TAG[typ] or typ + 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 @@ -487,7 +489,7 @@ function Meta.writeIlst(w: Bytes.Writer, tags: { [string]: string }, pictures: { end) box(w, "name", function() w:u32be(0) - w:string(k) + w:string(FREEFORM[k] or k) end) dataBox(w, 1, v) end) diff --git a/src/Formats/image/png/init.luau b/src/Formats/image/png/init.luau index 5c42219..117ff4f 100644 --- a/src/Formats/image/png/init.luau +++ b/src/Formats/image/png/init.luau @@ -413,7 +413,7 @@ local function animationFrames(img: Types.Image, opts: EncodeOptions?): ({ Types return nil, nil end if frames ~= nil and type(frames) ~= "table" then - return nil, Err.new(Err.ARG, "png encode: frames must be a list") + return nil, Err.new(Err.ARG, "frames must be a list") end if frames == nil or #frames == 0 then if mode then @@ -445,12 +445,12 @@ end function Png.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) if not validImage(img) then - return nil, Err.new(Err.ARG, "png encode: needs an rgba8 Image") + return nil, Err.new(Err.ARG, "needs an rgba8 Image") end local w, h = img.width, img.height local level = opts and opts.level or 6 if type(level) ~= "number" or level < 0 or level > 9 then - return nil, Err.new(Err.ARG, "png encode: level must be 0..9") + return nil, Err.new(Err.ARG, "level must be 0..9") end local frames, ferr = animationFrames(img, opts) if ferr then @@ -458,7 +458,7 @@ function Png.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) end local loops = img.loops or 0 if frames and (type(loops) ~= "number" or loops < 0 or loops > 4294967295 or loops % 1 ~= 0) then - return nil, Err.new(Err.ARG, "png encode: loops must be an integer 0..2^32-1") + return nil, Err.new(Err.ARG, "loops must be an integer 0..2^32-1") end local want = opts and opts.colorType or "auto" local ctName: string = want @@ -480,7 +480,7 @@ function Png.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) end local ct = CT_CODES[ctName] if ct == nil then - return nil, Err.new(Err.ARG, "png encode: unknown colorType " .. tostring(want)) + return nil, Err.new(Err.ARG, "unknown colorType " .. tostring(want)) end local function zdata(im: Types.Image): buffer return Deflate.zlibCompress(Encode.filter(im.pixels, im.width, im.height, ct), { level = level }) :: buffer diff --git a/src/Formats/image/webp/init.luau b/src/Formats/image/webp/init.luau index 418aaee..9834b1c 100644 --- a/src/Formats/image/webp/init.luau +++ b/src/Formats/image/webp/init.luau @@ -49,7 +49,7 @@ export type EncodeOptions = { lossless: boolean?, -- must be true or nil (lossy encoding is not supported) effort: number?, -- 0..9, default 5: VP8L encoder effort (more = smaller, slower) exact: boolean?, -- keep the RGB of fully transparent pixels (default false: they may be changed) - loops: number?, -- animations: loop count (default img.loops; 0 = forever) + loops: number?, -- animations: play count (default img.loops; 0 = forever) background: { number }?, -- animations: ANIM background colour { r, g, b, a } (default meta.background or 0) } diff --git a/src/Formats/music/midi/Smf.luau b/src/Formats/music/midi/Smf.luau index ed69595..71fd9e6 100644 --- a/src/Formats/music/midi/Smf.luau +++ b/src/Formats/music/midi/Smf.luau @@ -269,22 +269,22 @@ end -- write(midi, opts?) -> buffer | nil, Err function Smf.write(midi: Types.Midi, opts: WriteOptions?): (buffer?, Err.Err?) if type(midi) ~= "table" or type(midi.tracks) ~= "table" then - return nil, Err.new(Err.ARG, "midi encode: needs a Midi value with tracks") + return nil, Err.new(Err.ARG, "needs a Midi value with tracks") end local running = not (opts and opts.runningStatus == false) local format = midi.format or 1 local division = midi.division or 480 if type(format) ~= "number" or format < 0 or format > 2 or format % 1 ~= 0 then - return nil, Err.new(Err.ARG, "midi encode: format must be 0, 1 or 2") + return nil, Err.new(Err.ARG, "format must be 0, 1 or 2") end if type(division) ~= "number" or division == 0 or division < -32768 or division > 32767 or division % 1 ~= 0 then - return nil, Err.new(Err.ARG, "midi encode: division must be a non-zero 16-bit integer") + return nil, Err.new(Err.ARG, "division must be a non-zero 16-bit integer") end if format == 0 and #midi.tracks ~= 1 then - return nil, Err.new(Err.ARG, "midi encode: format 0 needs exactly one track") + return nil, Err.new(Err.ARG, "format 0 needs exactly one track") end if #midi.tracks > 65535 then - return nil, Err.new(Err.ARG, "midi encode: too many tracks") + return nil, Err.new(Err.ARG, "too many tracks") end local w = Bytes.writer(1024) w:string("MThd") @@ -295,7 +295,7 @@ function Smf.write(midi: Types.Midi, opts: WriteOptions?): (buffer?, Err.Err?) for ti, track in midi.tracks do local events = if type(track) == "table" then track.events else nil if type(events) ~= "table" then - return nil, Err.new(Err.ARG, "midi encode: track " .. ti .. " has no events list") + return nil, Err.new(Err.ARG, "track " .. ti .. " has no events list") end -- stable order by tick local sorted = true @@ -338,7 +338,7 @@ function Smf.write(midi: Types.Midi, opts: WriteOptions?): (buffer?, Err.Err?) end local delta = ev.tick - prev if delta > 0x0FFFFFFF then - return nil, Err.new(Err.ARG, "midi encode: a delta time over 0x0FFFFFFF ticks") + return nil, Err.new(Err.ARG, "a delta time over 0x0FFFFFFF ticks") end local base = TYPE_STATUS[t] if base then @@ -378,7 +378,7 @@ function Smf.write(midi: Types.Midi, opts: WriteOptions?): (buffer?, Err.Err?) w:u8(if t == "sysex" then 0xF0 else 0xF7) end if #d > 0x0FFFFFFF then - return nil, Err.new(Err.ARG, "midi encode: event data too long") + return nil, Err.new(Err.ARG, "event data too long") end vlq(w, #d) for _, c in d do diff --git a/tests/api.luau b/tests/api.luau index 00647cd..0089622 100644 --- a/tests/api.luau +++ b/tests/api.luau @@ -129,4 +129,28 @@ do t:check(F.data.null == F.null, "F.data.null") end +-- img.loops is a play count in every animated format (GIF stores repeats; APNG / WebP store plays) +do + local function anim(loops: number): any + local img = image(8, 8) + img.frames = {} + for k = 1, 2 do + local fr = image(8, 8) + buffer.writeu8(fr.pixels, 0, k) + table.insert(img.frames, { image = fr, delay = 0.1, x = 0, y = 0, dispose = "none", blend = "source" }) + end + img.loops = loops + return img + end + for _, fmt in { "gif", "png", "webp" } do + for _, loops in { 0, 1, 3 } do + local saved, err = F.save(anim(loops), nil, { format = fmt, lossless = true }) + t:check(saved, fmt .. " loops " .. loops .. ": " .. tostring(err)) + local back = saved and F.load(saved) + t:check(back and back.frames and #back.frames == 2, fmt .. " loops " .. loops .. ": animated") + t:eq(back and back.loops, loops, fmt .. ": loops " .. loops .. " round trip") + end + end +end + t:done() diff --git a/tests/audio/flac.luau b/tests/audio/flac.luau index 3f0f9a3..d24f59f 100644 --- a/tests/audio/flac.luau +++ b/tests/audio/flac.luau @@ -4,6 +4,7 @@ -- Reader; tags and pictures; the length from the last frame; sniff; the api; damaged frames skipped; the fuzz pass. -- Ported from flac-luau tests/flac.luau. Fixtures: tools/fixtures/flac.py. local T = require("@tests/T") +local VorbisComment = require("@formats/codecs/VorbisComment") local Flac = require("@formats/audio/flac") local Bytes = require("@formats/core/Bytes") local Crc32 = require("@formats/core/Crc32") @@ -92,8 +93,8 @@ for _, fx in Cases do t:check(math.abs(pos - fx.frames / 3) <= 1, name .. ": seek seconds") dec:seek(dec.duration + 5) t:eq(select(2, dec:read(10)), 0, name .. ": read past the end") - for key, v in fx.tags or {} do - t:eq(dec.tags[key], v, name .. ": tag " .. key) + for key, v in fx.tags or {} do -- (tags keys are lower case: codecs/VorbisComment) + t:eq(dec.tags[VorbisComment.tagKey(key)], v, name .. ": tag " .. key) end t:eq(Flac.sniff(Bytes.reader(buffer.fromstring(fx.data))), 1, name .. ": sniff") end diff --git a/tests/audio/flac_encode.luau b/tests/audio/flac_encode.luau index 7a0f204..ffd5848 100644 --- a/tests/audio/flac_encode.luau +++ b/tests/audio/flac_encode.luau @@ -80,9 +80,9 @@ do t:eq(back.meta.source.bitDepth, 8, "bit depth from meta.source") -- (the absorbed FLAC decoder keeps Vorbis comment keys upper case) local tags = back.tags :: any - t:eq(tags.title or tags.TITLE, "Tïtle", "title") - t:eq(tags.artist or tags.ARTIST, "Artist", "artist") - t:eq(tags.track or tags.TRACKNUMBER, "3", "track number") + t:eq(tags.title, "Tïtle", "title") + t:eq(tags.artist, "Artist", "artist") + t:eq(tags.track, "3", "track number") local empty = Flac.encode(Types.Audio.new(44100, 2, 0)) :: buffer local e0 = Flac.decode(Bytes.reader(empty)) t:check(e0 and e0.frames == 0, "empty audio") diff --git a/tests/audio/mp3.luau b/tests/audio/mp3.luau index 9d4412a..b03c97a 100644 --- a/tests/audio/mp3.luau +++ b/tests/audio/mp3.luau @@ -344,7 +344,7 @@ do eq(tg.title, "Test Title", "fixture title") eq(tg.artist, "Some Artist", "fixture artist") eq(tg.album, "An Album", "fixture album") - eq(tg.year, "2001", "fixture year") + eq(tg.date, "2001", "fixture year") eq(tg.track, "7", "fixture track") eq(tg.genre, "Rock", "fixture genre") eq(tg.comment, "hello", "fixture comment") @@ -405,7 +405,7 @@ do eq(dec.tags.title, "Ünïcödé ★ title", "v2.4 title") eq(dec.tags.artist, "One / Two", "v2.4 multi-value") eq(dec.tags.genre, "Rock", "v2.4 genre") - eq(dec.tags.year, "1999-05-01", "v2.4 TDRC") + eq(dec.tags.date, "1999-05-01", "v2.4 TDRC") eq(dec.tags.comment, "a comment", "v2.4 COMM") sameAudio(dec, "v2.4") t:check(Mp3.sniff(Bytes.reader(withAudio(tag))) >= 0.7, "sniff behind an ID3v2 tag") @@ -453,7 +453,7 @@ do eq(dec.tags.title, "V1 Title", "v1 title") eq(dec.tags.artist, "V1 Artist", "v1 artist") eq(dec.tags.album, "V1 Album", "v1 album") - eq(dec.tags.year, "1987", "v1 year") + eq(dec.tags.date, "1987", "v1 year") eq(dec.tags.comment, "v1 comment", "v1 comment") eq(dec.tags.track, "9", "v1.1 track") eq(dec.tags.genre, "Rock", "v1 genre") diff --git a/tests/audio/vorbis.luau b/tests/audio/vorbis.luau index 2cc5c01..3e9371e 100644 --- a/tests/audio/vorbis.luau +++ b/tests/audio/vorbis.luau @@ -7,6 +7,7 @@ local Vorbis = require("@formats/audio/vorbis") local Bytes = require("@formats/core/Bytes") local Err = require("@formats/core/Err") local Types = require("@formats/Types") +local Pcm = require("@formats/codecs/Pcm") local Ogg = require("@formats/containers/Ogg") local Cases = require("@tests/gen/vorbis_cases") @@ -57,6 +58,17 @@ for _, c in Cases do t:eq(a.frames, c.inputFrames, c.name .. ": frames = the encoder's input") local ref16 = buffer.fromstring(c.ref16) local n = c.frames * c.channels + -- oggdec -R keeps the Vorbis channel order; the decoder returns WAVE order (codecs/Pcm) + local order = Pcm.WAVE_FROM_VORBIS[c.channels] + if c.channels > 2 and order then + local w = buffer.create(buffer.len(ref16)) + for f = 0, c.frames - 1 do + for ch = 1, c.channels do + buffer.writei16(w, (f * c.channels + ch - 1) * 2, buffer.readi16(ref16, (f * c.channels + order[ch] - 1) * 2)) + end + end + ref16 = w + end local d = maxDiff16(a.samples, 0, ref16, 0, n) t:check(d <= 1, string.format("%s: within 1 LSB of oggdec (max %d)", c.name, d)) if c.ffRef then diff --git a/tests/audio/wav.luau b/tests/audio/wav.luau index dda6de4..b8d50e2 100644 --- a/tests/audio/wav.luau +++ b/tests/audio/wav.luau @@ -182,7 +182,7 @@ end do -- tags local info = "INFO" .. "INAM" .. u32(3) .. "abc\0" .. "IART" .. u32(6) .. "xy\0\0\0\0" .. "IXYZ" .. u32(2) .. "zz" .. "ITRK" .. u32(2) .. "7\0" local dec = open(riff(fmt(1, 1, 8000, 8), chunk("LIST", info), chunk("data", "\128\128\128"))) - t:check(dec and dec.tags.title == "abc" and dec.tags.artist == "xy" and dec.tags.IXYZ == "zz" and dec.tags.track == "7", "tags") + t:check(dec and dec.tags.title == "abc" and dec.tags.artist == "xy" and dec.tags.ixyz == "zz" and dec.tags.track == "7", "tags") t:check(dec and dec.frames == 3, "8-bit odd data") end do -- 8-bit, A-law and mu-law values @@ -251,7 +251,7 @@ do -- tags a.tags = { title = "Hello", artist = "Someone", IXYZ = "kept", comment = "" } local tg = Wav.decode(Bytes.reader(Wav.encode(a, { sampleFormat = "u8" }) :: buffer)) :: any - t:check(tg.tags.title == "Hello" and tg.tags.artist == "Someone" and tg.tags.IXYZ == "kept" and tg.tags.comment == nil, "tag round trip") + t:check(tg.tags.title == "Hello" and tg.tags.artist == "Someone" and tg.tags.ixyz == "kept" and tg.tags.comment == nil, "tag round trip") -- encodeParts, and RF64 chosen automatically past the threshold local big = Types.Audio.new(44100, 2, 3000) for i = 0, 3000 * 2 - 1 do diff --git a/tools/fixtures/vorbis_enc.py b/tools/fixtures/vorbis_enc.py index 8cfc69c..eab5989 100644 --- a/tools/fixtures/vorbis_enc.py +++ b/tools/fixtures/vorbis_enc.py @@ -18,11 +18,12 @@ INPUTS = ["src/Formats/audio/vorbis", "src/Formats/codecs", "src/Formats/contain WAVE_FROM_VORBIS6 = [0, 2, 1, 4, 5, 3] # vorbis channel k is WAVE channel WAVE_FROM_VORBIS6[k] -def reorder(x): +def to_wave(x): + """6-channel samples in Vorbis order -> WAVE order""" out = [0.0] * len(x) for i in range(0, len(x) - 5, 6): for k in range(6): - out[i + k] = x[i + WAVE_FROM_VORBIS6[k]] + out[i + WAVE_FROM_VORBIS6[k]] = x[i + k] return out @@ -59,11 +60,12 @@ def generate(ctx): problems = "\n".join(l for l in info.split("\n") if re.search(r"(?i)warning|error", l)) raw = A.tool(ctx, "vorbis-tools", ["oggdec", "-Q", "-R", "-o", "{out}", "{in}"], data, "ogg", "raw") od = [int.from_bytes(raw[i:i + 2], "little", signed=True) / 32768 for i in range(0, len(raw) - 1, 2)] - osnr, _ = A.snr(samples, od, ch) # (oggdec -R keeps the Vorbis channel order) + if ch == 6: # the input is in WAVE order (FL FR FC LFE RL RR); oggdec -R keeps the Vorbis order (FL FC FR RL RR LFE) + od = to_wave(od) + osnr, _ = A.snr(samples, od, ch) ffe = A.tool(ctx, "ffmpeg", ["ffmpeg", "-v", "error", "-i", "{in}", "-f", "null", "-"], data, "ogg").decode(errors="replace") _, fch, ff = A.ffdecode(ctx, data, ext="ogg") - if ch == 6: # ffmpeg reorders to WAVE order (FL FR FC LFE RL RR); Vorbis order is FL FC FR RL RR LFE - ff = reorder(ff) + # (ffmpeg decodes to WAVE order, like our decoder) fsnr, _ = A.snr(samples, ff, ch) if fch == ch else (-99.0, 0) e = {"name": name, "sig": sigmod, "quality": q, "rate": rate, "channels": ch, "frames": frames, "ogginfo": problems, "oggdecFrames": len(od) // ch, "oggdecSnr": osnr, "ffFrames": len(ff) // max(1, fch), "ffSnr": fsnr, From ec0e826cee5ee983096e37143f758587910e4243 Mon Sep 17 00:00:00 2001 From: 4DBug <github@bug.tools> Date: Sat, 31 Oct 2026 11:01:53 -0500 Subject: [PATCH 13/22] ws-cleanup: format headers say what is not supported (bz2, ass, srt) --- src/Formats/archive/bz2/init.luau | 3 ++- src/Formats/subtitle/ass/init.luau | 3 ++- src/Formats/subtitle/srt/init.luau | 1 + 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/src/Formats/archive/bz2/init.luau b/src/Formats/archive/bz2/init.luau index 7483ab0..074bdc2 100644 --- a/src/Formats/archive/bz2/init.luau +++ b/src/Formats/archive/bz2/init.luau @@ -1,7 +1,8 @@ --!strict -- archive/bz2: a .bz2 file as a single-stream archive: one entry, the decompressed data (codecs/Bzip2; concatenated -- streams are joined, as bzip2 -d does). The entry is named after the file without its .bz2 (".tbz2" -> ".tar"), --- else "data"; the api unwraps a .tar.bz2 into the tar inside (meta.stream). Read only. +-- else "data"; the api unwraps a .tar.bz2 into the tar inside (meta.stream). New in formats-luau. Not supported: +-- writing (codecs/Bzip2 has no compressor), randomised blocks (bzip2 0.9.0 and older). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") diff --git a/src/Formats/subtitle/ass/init.luau b/src/Formats/subtitle/ass/init.luau index ee521f4..dcf295d 100644 --- a/src/Formats/subtitle/ass/init.luau +++ b/src/Formats/subtitle/ass/init.luau @@ -7,7 +7,8 @@ -- Cue text: `\N` / `\n` become line breaks, `\h` a no-break space, the {\i1} / {\b1} / {\u1} / {\s1} overrides become -- the shared <i> / <b> / <u> / <s> markup and other override blocks are dropped; the original text stays in cue.raw. -- Encode: an ASS v4.00+ script (or the source's style / event formats), cue.raw when cue.text still matches it, --- otherwise the markup converted back; times rounded to the centisecond. Styles are data: nothing is rendered. +-- otherwise the markup converted back; times rounded to the centisecond. Styles are data: nothing is rendered. Not supported: +-- rendering, karaoke timing (\k overrides are dropped from text, kept in cue.raw), embedded font / graphic decoding. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") diff --git a/src/Formats/subtitle/srt/init.luau b/src/Formats/subtitle/srt/init.luau index 1354e6a..67ae65d 100644 --- a/src/Formats/subtitle/srt/init.luau +++ b/src/Formats/subtitle/srt/init.luau @@ -5,6 +5,7 @@ -- the cue only before an index / timing line), BOM, CRLF / CR line ends. Text is kept as written (its <i> / <b> / -- <u> / <s> / <font> tags included): the shared markup of Subtitles cue text. -- Encode: cues renumbered from 1 in order, times rounded to the millisecond, opts.crlf for CRLF line ends. +-- Not supported: positioning beyond keeping the coordinates; the tags are not validated. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") From 45bb5f9b95729b66da70da52e460b399dc2bc482 Mon Sep 17 00:00:00 2001 From: 4DBug <github@bug.tools> Date: Sat, 31 Oct 2026 11:06:04 -0500 Subject: [PATCH 14/22] ws-cleanup: F.ops facade (image / mesh / layers / audio / vector.rasterize) and ops/AudioOps - F.ops in init.luau, loaded on first use: F.ops.image (ImageOps), F.ops.mesh (MeshOps), F.ops.layers (LayerOps), F.ops.audio (new ops/AudioOps), F.ops.vector.rasterize (the vector/svg renderer for any Vector, through F.format). - ops/AudioOps: toAudio / fromDecoder (Audio from a Decoder via codecs/Pcm), gain / gainDb / normalize, peak / rms, remix / downmix / upmix (WAVE-layout matrices, BS.775 coefficients normalised against clipping), resample (codecs/Resample), trim, concat and mix (inputs converted to the first one's rate and channels), fade. - tests/ops/audioops (39 checks, both runtimes); docs/API.md (new): the F.* API, F.ops, hooks, host. --- docs/API.md | 96 +++++++ src/Formats/init.luau | 53 ++++ src/Formats/ops/AudioOps.luau | 481 ++++++++++++++++++++++++++++++++++ tests/ops/audioops.luau | 151 +++++++++++ 4 files changed, 781 insertions(+) create mode 100644 docs/API.md create mode 100644 src/Formats/ops/AudioOps.luau create mode 100644 tests/ops/audioops.luau diff --git a/docs/API.md b/docs/API.md new file mode 100644 index 0000000..5e6b861 --- /dev/null +++ b/docs/API.md @@ -0,0 +1,96 @@ +# formats-luau API + +`local F = require(Formats)` (Roblox: the ModuleScript; LuaJIT / LÖVE: `require("formats")`; luau CLI: +`require("@formats")`). Everything below is `src/Formats/init.luau` unless noted. Nothing throws on bad data or bad +arguments: a failing call returns `nil, err` where `err` is a `core/Err` value (`err.code`, `err.message`, +`err.offset`, `err.format`; `tostring(err)` prints `png: CORRUPT at 0x21: bad filter type 7`). + +## Sources and destinations + +A source `src` is a `buffer`, a `string` of bytes, or a file path on hosts with a file system (LuaJIT, LÖVE). A +string is a path only when `opts.path = true` or when it does not look like file data and the file exists; pass +`opts.data = true` to force bytes. Roblox and the luau CLI have no file system: pass buffers or strings. + +`F.save(value, dest?, opts?)` returns a `buffer`, or writes the file `dest` (extension = format) and returns `true`. + +## Loading and saving + +| Call | Returns | +|---|---| +| `F.load(src, opts?)` | the category's standard value (`Image`, `Audio`, `Scene`, `Font`, `Archive`, `Vector`, `Layered`, `Subtitles`, `Module` / `Midi`, `Playlist`, data values, a `VideoDecoder`) | +| `F.open(src, opts?)` | a streaming decoder: audio `Decoder`, `VideoDecoder`, or a container `Demuxer` | +| `F.save(value, dest?, opts?)` | `buffer` / `true` | +| `F.saveString(value, opts?)` | the encoded bytes as a string | +| `F.convert(src, format, opts?)` | load + save (`opts` go to both; `opts.out = path` writes a file) | +| `F.detect(src, opts?)` | the format name (content sniffing first, then the extension) | +| `F.formats(category?)` | `{ { name, category, extensions, mime, caps } }` without loading any format (also [FORMATS.md](FORMATS.md)) | +| `F.format(name)` | the format module itself (`sniff` / `decode` / `encode` / `open` and extras such as `png.info`) | + +Common options: `format` (a name or extension: what to decode as / encode to; without it, saving uses the source +format), `category`, `name` (a file name hint for detection), `path` / `data`, size limits (`maxPixels`, `maxBytes`, +`maxFrames`, ...), and each format's own options (documented in its `init.luau`: `level`, `quality`, `bitrate`, ...). + +## Category facades + +`F.image`, `F.audio`, `F.video`, `F.model`, `F.cad`, `F.font`, `F.archive`, `F.data`, `F.vector`, `F.layered`, +`F.subtitle`, `F.music`, `F.playlist` each have `load`, `open`, `save` and `formats`: the calls above restricted to +one category. Extras: + +- `F.video.open(src)` also opens animated images (GIF / APNG / WebP) as videos; `F.video.fromImage(img)`, + `F.video.fromFrames(images, delays?)` (an image sequence: `F.save(F.video.fromFrames(list, 1 / 25), "out.avi")`), + `F.video.codecs` (the codec registry `codecs/Video`). +- `F.model.loadTextures(scene, opts?)`: decodes embedded / referenced textures into `texture.image`. +- `F.cad.toBodies`, `F.cad.fromBodies`, `F.cad.tessellate`: STEP B-rep calls through the injected kernel + (`F.plugins.brep`). +- `F.data.null`: the JSON / YAML / TOML / msgpack / CBOR null. + +## Editing: `F.ops` + +Loaded on first use; every function returns a new value (or edits in place where it says so) and `nil, Err` for bad +arguments. + +| Table | Module | Functions | +|---|---|---| +| `F.ops.image` | `ops/ImageOps` | `convert` (pixel formats), `crop`, `resize` (nearest / bilinear / Lanczos-3), `flip`, `rotate90`, `rotate`, `blit`, `composite`, `premultiply` / `unpremultiply`, `getPixel` / `setPixel` / `fill`, `new` / `copy`, animations: `coalesce` (frames on full canvases), `fromFrames`, `frameCount`, `durations` | +| `F.ops.mesh` | `ops/MeshOps` | `triangulate`, `transform`, `computeNormals`, `computeTangents`, `weld` / `unweld`, `bounds`, `merge`, `scale` / `setUnit` / `setUp`, `voxelsToPrimitive`, `meshVoxels` | +| `F.ops.layers` | `ops/LayerOps` | `flatten(layered, { frame })`, `flattenFrames`, `leaves` | +| `F.ops.audio` | `ops/AudioOps` | `toAudio` (an Audio from an Audio or a Decoder), `gain`, `gainDb`, `normalize`, `peak`, `rms`, `mix`, `remix` / `downmix` / `upmix` (WAVE-layout matrices), `resample` (`codecs/Resample`), `trim`, `concat`, `fade` | +| `F.ops.vector` | `vector/svg` | `rasterize(vector, w?, h?, opts?)`: any `Vector` to an rgba8 `Image` | + +```luau +local img = F.load(png) +local thumb = F.ops.image.resize(img, 128, 128, "lanczos") +local music = F.ops.audio.toAudio(F.audio.open(mp3)) +local quiet = F.ops.audio.gainDb(F.ops.audio.resample(music, 48000), -6) +F.save(quiet, "out.flac") +local icon = F.ops.vector.rasterize(F.load(svgText), 64, 64) +``` + +## Hooks and plug-ins + +A format never requires another format, so the api passes these to decoders / encoders in `opts` (callers of +`F.format(name).decode` directly may pass their own; without them the embedded parts return `Err.UNSUPPORTED`): + +- `opts.decodeImage(buf) -> Image | nil, Err` and `opts.encodeImage(img, format) -> buffer | nil, Err`: images inside + other files (ICO PNG entries, PSD / glTF / 3MF textures, MJPEG frames, ...). +- `opts.openAudio(demuxer, track) -> Decoder | nil, Err`: audio tracks of video containers (wrapped by + `containers/AudioWrap` and opened as the matching audio format). +- `opts.plugins` (default `F.plugins`): injected optional dependencies, e.g. `F.plugins.brep` (a B-rep kernel for + `cad/step`). +- `opts.resolve(uri) -> buffer?`: files referenced by a model (OBJ `.mtl`, glTF `.bin`); filled in for paths on hosts + with files. `opts.loadPage(file, page)` for bitmap-font pages. + +## Host + +`F.host` (`src/Formats/host`): `name` (`"roblox"`, `"love"`, `"luajit"`, `"luau"`), `hasFiles`, `readFile`, +`writeFile`, `exists`; Roblox `toEditableImage(img)`; LÖVE `toImageData(img)`, `fromImageData(imageData)`, +`toSoundData(audioOrDecoder)`. + +On LuaJIT the host raises the trace limits at load (`jit.opt.start("maxtrace=8000", "maxmcode=65536")`): the big +decoders (CELT, VP8, H.264, MPEG-1) outgrow the defaults and fall back to the interpreter. Set +`_G.FORMATS_NO_JIT_TUNE = true` before requiring the library to leave the JIT settings alone. + +## Also exported + +`F.Err` (codes `TRUNCATED`, `CORRUPT`, `CHECKSUM`, `UNSUPPORTED`, `LIMIT`, `ARG`, `IO`, `UNKNOWN_FORMAT`), `F.Types` +(the standard types and their constructors), `F.Bytes` (`core/Bytes` Reader / Writer), `F.null`, `F.version`. diff --git a/src/Formats/init.luau b/src/Formats/init.luau index 57d5dcc..8cc3fb3 100644 --- a/src/Formats/init.luau +++ b/src/Formats/init.luau @@ -12,6 +12,7 @@ -- local s = F.saveString(img, { format = "png" }) -- local buf = F.convert(src, "png", opts?) -- load + save -- F.formats() -- the capability list (also docs/FORMATS.md) +-- F.ops.image.resize(img, 64, 64) -- editing: F.ops.image / mesh / layers / audio / vector.rasterize -- -- Never throws on bad data or bad arguments: every function returns nil, Err (Err.code, Err.message, tostring(err)). local Err = require("@formats/core/Err") @@ -679,4 +680,56 @@ F.model.loadTextures = function(scene: any, opts: Options?): (any, { [number]: E return scene, errs end +-- ------------------------------------------------------------------------------------------------ ops +-- F.ops: editing on the standard types, loaded on first use. +-- F.ops.image ops/ImageOps convert, crop, resize, flip, rotate, blit / composite, coalesce, ... +-- F.ops.mesh ops/MeshOps triangulate, transform, computeNormals / Tangents, weld, merge, meshVoxels, ... +-- F.ops.layers ops/LayerOps flatten / flattenFrames a Layered (PSD, Aseprite), leaves +-- F.ops.audio ops/AudioOps toAudio, gain / gainDb / normalize, mix, remix / downmix / upmix, resample, trim, +-- concat, fade, peak, rms +-- F.ops.vector.rasterize(vector, w?, h?, opts?) -> rgba8 Image: the SVG renderer (vector/svg) for any Vector +local OPS: { [string]: () -> any } = { + image = function() + return ImageOps + end, + mesh = function() + return require("@formats/ops/MeshOps") + end, + layers = function() + return require("@formats/ops/LayerOps") + end, + audio = function() + return require("@formats/ops/AudioOps") + end, + vector = function() + return { + rasterize = function(v: any, w: number?, h: number?, opts: any?): (any, Err.Err?) + local svg, err = F.format("svg") + if not svg then + return nil, err + end + local ok, img, rerr = pcall(svg.rasterize, v, w, h, opts) + if not ok then + return nil, Err.wrap(Err.new(Err.CORRUPT, "rasterize threw: " .. tostring(img)), "svg") + end + if img == nil and rerr then + return nil, Err.wrap(rerr, "svg") + end + return img, rerr + end, + } + end, +} +F.ops = setmetatable({}, { + __index = function(t: any, k: string): any + local make = OPS[k] + if not make then + return nil + end + local m = make() + rawset(t, k, m) + return m + end, +}) :: any + return F diff --git a/src/Formats/ops/AudioOps.luau b/src/Formats/ops/AudioOps.luau new file mode 100644 index 0000000..c1a5d53 --- /dev/null +++ b/src/Formats/ops/AudioOps.luau @@ -0,0 +1,481 @@ +--!strict +-- ops/AudioOps: editing on the standard Audio (layer 5.5: core, Types and codecs only): a Decoder collected into an +-- Audio, gain (linear or dB), normalize, mix, channel remixing (downmix / upmix with the usual WAVE-layout matrices), +-- resampling (codecs/Resample), trim, concat, fades, peak / RMS. New code. +-- +-- local AudioOps = require("@formats/ops/AudioOps") -- F.ops.audio in the api +-- local a = AudioOps.toAudio(F.audio.open(src)) -- an Audio from an Audio or a streaming Decoder +-- local louder = AudioOps.gainDb(a, 6) -- every call returns a new Audio | nil, Err (never throws) +-- local mono = AudioOps.downmix(a) -- or AudioOps.remix(a, 1); upmix(a, 6) +-- local a48 = AudioOps.resample(a, 48000, { quality = "high" }) +-- local mixed = AudioOps.mix({ a, b }, { 0.5, 0.5 }) -- other rates / channel counts are converted to a's +-- local clip = AudioOps.trim(a, 1.5, 4) -- seconds [1.5, 4) +-- local both = AudioOps.concat({ a, b }) +-- local peak, perChannel = AudioOps.peak(a) -- max |sample|; AudioOps.rms(a) the same shape +-- +-- Conventions: samples are the Audio's interleaved f32 (no clipping is applied: values past +-1 are kept, encoders +-- clip). Channels are in WAVE order (FL FR C LFE BL BR SL SR, as every decoder returns them). Downmixes follow the +-- ITU-R BS.775 coefficients (centre and surrounds at -3 dB, LFE dropped), scaled so a full-scale input cannot +-- exceed full scale; upmixes copy mono to FL / FR and stereo to FL / FR (other channels silent). Tags and meta are +-- copied from the (first) input. +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Pcm = require("@formats/codecs/Pcm") +local Resample = require("@formats/codecs/Resample") + +local AudioOps = {} + +local readf32, writef32 = buffer.readf32, buffer.writef32 +local floor, max, min, abs, sqrt = math.floor, math.max, math.min, math.abs, math.sqrt + +-- ------------------------------------------------------------------------------------------------ validation +local function isAudio(a: any): boolean + return type(a) == "table" + and a.kind == "audio" + and type(a.samples) == "buffer" + and type(a.frames) == "number" + and type(a.channels) == "number" + and a.channels >= 1 + and type(a.sampleRate) == "number" + and a.sampleRate > 0 + and buffer.len(a.samples) >= a.frames * a.channels * 4 +end + +local function bad(what: string): (nil, Err.Err) + return nil, Err.new(Err.ARG, what) +end + +-- a new Audio with a's rate / tags / meta and the given layout +local function like(a: Types.Audio, channels: number, frames: number, rate: number?): Types.Audio + local out = Types.Audio.new(rate or a.sampleRate, channels, frames) + out.tags = table.clone(a.tags or {}) + out.meta = table.clone(a.meta or {}) + return out +end + +-- ------------------------------------------------------------------------------------------------ conversion +-- toAudio(audioOrDecoder, opts?) -> Audio: an Audio as it is, a Decoder read to its end (opts.maxFrames: Err.LIMIT +-- past it; default 2^31) +function AudioOps.toAudio(v: any, opts: { maxFrames: number? }?): (Types.Audio?, Err.Err?) + if isAudio(v) then + return v, nil + end + local src, err = Pcm.source(v) + if not src then + return nil, err + end + return Pcm.collect(src, opts and opts.maxFrames) +end +AudioOps.fromDecoder = AudioOps.toAudio + +-- ------------------------------------------------------------------------------------------------ levels +-- gain(a, factor) -> Audio with every sample times factor +function AudioOps.gain(a: Types.Audio, factor: number): (Types.Audio?, Err.Err?) + if not isAudio(a) then + return bad("gain: expected an Audio") + end + if type(factor) ~= "number" or factor ~= factor then + return bad("gain: factor must be a number") + end + local n = a.frames * a.channels + local out = like(a, a.channels, a.frames) + local s, d = a.samples, out.samples + for i = 0, n - 1 do + writef32(d, i * 4, readf32(s, i * 4) * factor) + end + return out, nil +end + +-- gainDb(a, dB) -> Audio scaled by 10^(dB / 20) +function AudioOps.gainDb(a: Types.Audio, db: number): (Types.Audio?, Err.Err?) + if type(db) ~= "number" or db ~= db then + return bad("gainDb: dB must be a number") + end + return AudioOps.gain(a, 10 ^ (db / 20)) +end + +-- peak(a) -> the largest |sample|, { per channel } +function AudioOps.peak(a: Types.Audio): (number?, { number } | Err.Err) + if not isAudio(a) then + return nil, Err.new(Err.ARG, "peak: expected an Audio") + end + local ch = a.channels + local per = table.create(ch, 0) + local s = a.samples + for f = 0, a.frames - 1 do + local p = f * ch * 4 + for c = 1, ch do + local v = abs(readf32(s, p + (c - 1) * 4)) + if v > per[c] then + per[c] = v + end + end + end + local m = 0 + for c = 1, ch do + m = max(m, per[c]) + end + return m, per +end + +-- rms(a) -> the root mean square over every sample, { per channel } (0 for no frames) +function AudioOps.rms(a: Types.Audio): (number?, { number } | Err.Err) + if not isAudio(a) then + return nil, Err.new(Err.ARG, "rms: expected an Audio") + end + local ch = a.channels + local per = table.create(ch, 0) + local s = a.samples + for f = 0, a.frames - 1 do + local p = f * ch * 4 + for c = 1, ch do + local v = readf32(s, p + (c - 1) * 4) + per[c] += v * v + end + end + local total = 0 + local n = max(1, a.frames) + for c = 1, ch do + total += per[c] + per[c] = sqrt(per[c] / n) + end + return sqrt(total / (n * ch)), per +end + +-- normalize(a, target?) -> Audio scaled so its peak is target (default 1; silence is returned unchanged) +function AudioOps.normalize(a: Types.Audio, target: number?): (Types.Audio?, Err.Err?) + local p, perr = AudioOps.peak(a) + if not p then + return nil, perr :: Err.Err + end + local t = target or 1 + if type(t) ~= "number" or t ~= t or t < 0 then + return bad("normalize: target must be a number >= 0") + end + return AudioOps.gain(a, if p > 0 then t / p else 1) +end + +-- fade(a, inSeconds?, outSeconds?) -> Audio with linear fade-in / fade-out ramps +function AudioOps.fade(a: Types.Audio, inSec: number?, outSec: number?): (Types.Audio?, Err.Err?) + if not isAudio(a) then + return bad("fade: expected an Audio") + end + local fi = floor(max(0, (inSec or 0) * a.sampleRate) + 0.5) + local fo = floor(max(0, (outSec or 0) * a.sampleRate) + 0.5) + if fi ~= fi or fo ~= fo then + return bad("fade: bad duration") + end + local out = like(a, a.channels, a.frames) + buffer.copy(out.samples, 0, a.samples, 0, a.frames * a.channels * 4) + local ch, d, n = a.channels, out.samples, a.frames + for f = 0, min(fi, n) - 1 do + local g = f / fi + for c = 0, ch - 1 do + local p = (f * ch + c) * 4 + writef32(d, p, readf32(d, p) * g) + end + end + for k = 0, min(fo, n) - 1 do + local f = n - 1 - k + local g = k / fo + for c = 0, ch - 1 do + local p = (f * ch + c) * 4 + writef32(d, p, readf32(d, p) * g) + end + end + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ channels +-- the WAVE-order speakers of 1 .. 8 channel layouts (as FFmpeg's default layouts) +local LAYOUT: { { string } } = { + { "C" }, + { "FL", "FR" }, + { "FL", "FR", "C" }, + { "FL", "FR", "BL", "BR" }, + { "FL", "FR", "C", "BL", "BR" }, + { "FL", "FR", "C", "LFE", "BL", "BR" }, + { "FL", "FR", "C", "LFE", "BC", "SL", "SR" }, + { "FL", "FR", "C", "LFE", "BL", "BR", "SL", "SR" }, +} +local H = sqrt(0.5) -- -3 dB +-- speaker -> its contribution to (left, right) in a stereo downmix +local TO_STEREO: { [string]: { number } } = { + FL = { 1, 0 }, FR = { 0, 1 }, C = { H, H }, LFE = { 0, 0 }, BL = { H, 0 }, BR = { 0, H }, SL = { H, 0 }, + SR = { 0, H }, BC = { 0.5, 0.5 }, +} + +-- matrix(from, to) -> m[o][i]: output channel o = sum m[o][i] * input i +local function matrix(from: number, to: number): { { number } } + local m = table.create(to) + for o = 1, to do + m[o] = table.create(from, 0) + end + if from == to then + for c = 1, to do + m[c][c] = 1 + end + return m + end + local inL, outL = LAYOUT[from], LAYOUT[to] + if to < from and inL and outL and to <= 2 then + -- down to stereo (then mono = the average of the two) + local l, r = table.create(from, 0), table.create(from, 0) + local sl, sr = 0, 0 + for i, sp in inL do + local w = TO_STEREO[sp] or { 0, 0 } + l[i], r[i] = w[1], w[2] + sl += w[1] + sr += w[2] + end + local norm = 1 / max(sl, sr, 1) + for i = 1, from do + if to == 2 then + m[1][i], m[2][i] = l[i] * norm, r[i] * norm + else + m[1][i] = (l[i] + r[i]) * norm * 0.5 + end + end + return m + end + if from == 1 then + -- mono up: FL and FR (or the only channel) + if outL then + local placed = false + for o, sp in outL do + if sp == "FL" or sp == "FR" then + m[o][1] = 1 + placed = true + end + end + if not placed then + m[1][1] = 1 + end + else + m[1][1] = 1 + end + return m + end + if inL and outL then + -- same-named speakers carry over; down: missing speakers fold into the stereo pair at their weights + local outIdx: { [string]: number } = {} + for o, sp in outL do + outIdx[sp] = o + end + for i, sp in inL do + local o = outIdx[sp] + if o then + m[o][i] = 1 + elseif to < from and outIdx.FL and outIdx.FR then + local w = TO_STEREO[sp] or { 0, 0 } + m[outIdx.FL][i] += w[1] + m[outIdx.FR][i] += w[2] + end + end + if to < from then + for o = 1, to do + local s = 0 + for i = 1, from do + s += m[o][i] + end + if s > 1 then + for i = 1, from do + m[o][i] /= s + end + end + end + end + return m + end + -- unknown layouts: channel i -> i, extra outputs silent, extra inputs dropped + for c = 1, min(from, to) do + m[c][c] = 1 + end + return m +end +AudioOps.matrix = matrix + +-- remix(a, channels, m?) -> Audio with that many channels (m: an explicit m[out][in] matrix; default matrix(...)) +function AudioOps.remix(a: Types.Audio, channels: number, m: { { number } }?): (Types.Audio?, Err.Err?) + if not isAudio(a) then + return bad("remix: expected an Audio") + end + if type(channels) ~= "number" or channels < 1 or channels > 256 or channels % 1 ~= 0 then + return bad("remix: channels must be 1 .. 256") + end + local from = a.channels + local mm = m or matrix(from, channels) + if type(mm) ~= "table" or #mm ~= channels then + return bad("remix: the matrix needs one row per output channel") + end + for o = 1, channels do + if type(mm[o]) ~= "table" then + return bad("remix: matrix row " .. o .. " is not a table") + end + end + local out = like(a, channels, a.frames) + local s, d = a.samples, out.samples + local x = table.create(from, 0) + for f = 0, a.frames - 1 do + local p = f * from * 4 + for i = 1, from do + x[i] = readf32(s, p + (i - 1) * 4) + end + local q = f * channels * 4 + for o = 1, channels do + local row = mm[o] + local v = 0 + for i = 1, from do + local w = row[i] + if w and w ~= 0 then + v += w * x[i] + end + end + writef32(d, q + (o - 1) * 4, v) + end + end + return out, nil +end + +-- downmix(a, channels?) -> Audio with fewer channels (default 2; mono input stays mono) +function AudioOps.downmix(a: Types.Audio, channels: number?): (Types.Audio?, Err.Err?) + if not isAudio(a) then + return bad("downmix: expected an Audio") + end + local n = channels or min(2, a.channels) + if n > a.channels then + return bad("downmix: more output channels than input") + end + return AudioOps.remix(a, n) +end + +-- upmix(a, channels) -> Audio with more channels +function AudioOps.upmix(a: Types.Audio, channels: number): (Types.Audio?, Err.Err?) + if not isAudio(a) then + return bad("upmix: expected an Audio") + end + if type(channels) ~= "number" or channels < a.channels then + return bad("upmix: fewer output channels than input") + end + return AudioOps.remix(a, channels) +end + +-- ------------------------------------------------------------------------------------------------ time +-- resample(a, rate, opts?) -> Audio at the new rate (codecs/Resample: opts.quality "low" | "medium" | "high") +function AudioOps.resample(a: Types.Audio, rate: number, opts: Resample.Options?): (Types.Audio?, Err.Err?) + if not isAudio(a) then + return bad("resample: expected an Audio") + end + local samples, frames = Resample.buffer(a.samples, a.frames, a.channels, a.sampleRate, rate, opts) + if not samples then + return bad("resample: " .. tostring(frames)) + end + local out = like(a, a.channels, 0, rate) + out.samples = samples + out.frames = frames :: number + return out, nil +end + +-- trim(a, start, stop?) -> Audio of the seconds [start, stop) (clamped to the audio; stop default the end) +function AudioOps.trim(a: Types.Audio, start: number, stop: number?): (Types.Audio?, Err.Err?) + if not isAudio(a) then + return bad("trim: expected an Audio") + end + if type(start) ~= "number" or start ~= start or (stop ~= nil and (type(stop) ~= "number" or stop ~= stop)) then + return bad("trim: start / stop must be numbers (seconds)") + end + local f0 = math.clamp(floor(start * a.sampleRate + 0.5), 0, a.frames) + local f1 = if stop then math.clamp(floor(stop * a.sampleRate + 0.5), f0, a.frames) else a.frames + local ch = a.channels + local out = like(a, ch, f1 - f0) + buffer.copy(out.samples, 0, a.samples, f0 * ch * 4, (f1 - f0) * ch * 4) + return out, nil +end + +-- conform(list, what) -> the audios converted to the first one's rate and channel count | nil, Err +local function conform(list: { Types.Audio }, what: string): ({ Types.Audio }?, Err.Err?) + if type(list) ~= "table" or #list == 0 then + return nil, Err.new(Err.ARG, what .. ": expected a non-empty list of Audio") + end + local first = list[1] + if not isAudio(first) then + return nil, Err.new(Err.ARG, what .. ": item 1 is not an Audio") + end + local out = { first } + for i = 2, #list do + local a = list[i] + if not isAudio(a) then + return nil, Err.new(Err.ARG, what .. ": item " .. i .. " is not an Audio") + end + if a.sampleRate ~= first.sampleRate then + local r, err = AudioOps.resample(a, first.sampleRate) + if not r then + return nil, err + end + a = r + end + if a.channels ~= first.channels then + local r, err = AudioOps.remix(a, first.channels) + if not r then + return nil, err + end + a = r + end + out[i] = a + end + return out, nil +end + +-- concat(list) -> Audio: the audios one after the other (at the first one's rate and channel count) +function AudioOps.concat(list: { Types.Audio }): (Types.Audio?, Err.Err?) + local items, err = conform(list, "concat") + if not items then + return nil, err + end + local first = items[1] + local ch = first.channels + local total = 0 + for _, a in items do + total += a.frames + end + local out = like(first, ch, total) + local at = 0 + for _, a in items do + buffer.copy(out.samples, at * ch * 4, a.samples, 0, a.frames * ch * 4) + at += a.frames + end + return out, nil +end + +-- mix(list, weights?) -> Audio: the sum of the audios (times weights[i], default 1 each), as long as the longest, at +-- the first one's rate and channel count +function AudioOps.mix(list: { Types.Audio }, weights: { number }?): (Types.Audio?, Err.Err?) + local items, err = conform(list, "mix") + if not items then + return nil, err + end + if weights ~= nil and type(weights) ~= "table" then + return bad("mix: weights must be a list of numbers") + end + local first = items[1] + local ch = first.channels + local frames = 0 + for _, a in items do + frames = max(frames, a.frames) + end + local out = like(first, ch, frames) + local d = out.samples + for i, a in items do + local w = if weights then weights[i] or 1 else 1 + if type(w) ~= "number" then + return bad("mix: weight " .. i .. " is not a number") + end + local s = a.samples + for k = 0, a.frames * ch - 1 do + writef32(d, k * 4, readf32(d, k * 4) + readf32(s, k * 4) * w) + end + end + return out, nil +end + +return AudioOps diff --git a/tests/ops/audioops.luau b/tests/ops/audioops.luau new file mode 100644 index 0000000..1966ae1 --- /dev/null +++ b/tests/ops/audioops.luau @@ -0,0 +1,151 @@ +-- ops/AudioOps tests: toAudio from a Decoder, gain / gainDb / normalize, peak / RMS of known signals, remix matrices +-- (5.1 -> stereo -> mono, mono -> stereo / 5.1), resample through codecs/Resample, trim, concat and mix with rate / +-- channel conversion, fades, bad arguments (Err.ARG, never a throw), and the F.ops facade. +local T = require("@tests/T") +local AudioOps = require("@formats/ops/AudioOps") +local Types = require("@formats/Types") +local Pcm = require("@formats/codecs/Pcm") +local Err = require("@formats/core/Err") +local F = require("@formats") + +local t = T.suite("audioops") + +local function audio(rate: number, ch: number, frames: number, fn: (f: number, c: number) -> number): Types.Audio + local a = Types.Audio.new(rate, ch, frames) + for f = 0, frames - 1 do + for c = 0, ch - 1 do + buffer.writef32(a.samples, (f * ch + c) * 4, fn(f, c)) + end + end + a.tags = { title = "x" } + return a +end +local function at(a: Types.Audio, f: number, c: number): number + return buffer.readf32(a.samples, (f * a.channels + c) * 4) +end +local function near(x: number, y: number, eps: number?): boolean + return math.abs(x - y) <= (eps or 1e-6) +end + +local sine = audio(8000, 2, 8000, function(f, c) + return (if c == 0 then 0.5 else 0.25) * math.sin(2 * math.pi * 440 * f / 8000) +end) + +-- toAudio +do + local dec = Pcm.audioDecoder(sine) + local a = AudioOps.toAudio(dec) :: Types.Audio + t:check(a and a.frames == 8000 and a.channels == 2 and buffer.tostring(a.samples) == buffer.tostring(sine.samples), "toAudio(Decoder)") + t:check(AudioOps.toAudio(sine) == sine, "toAudio(Audio) is the Audio") + local _, e2 = AudioOps.toAudio(Pcm.audioDecoder(sine), { maxFrames = 10 }) + t:check(e2 and e2.code == Err.LIMIT, "maxFrames -> LIMIT") +end + +-- levels +do + local p, per = AudioOps.peak(sine) + t:check(near(p :: number, 0.5, 1e-3) and near((per :: any)[2], 0.25, 1e-3), "peak") + local r, rper = AudioOps.rms(sine) + t:check(near((rper :: any)[1], 0.5 / math.sqrt(2), 1e-3) and near((rper :: any)[2], 0.25 / math.sqrt(2), 1e-3), "rms per channel") + t:check(near(r :: number, math.sqrt((0.125 + 0.03125) / 2), 1e-3), "rms") + local g = AudioOps.gainDb(sine, -6.0206) :: Types.Audio + t:check(near(at(g, 100, 0), at(sine, 100, 0) / 2, 1e-4), "gainDb -6 dB halves") + t:eq(g.tags.title, "x", "tags copied") + local n = AudioOps.normalize(sine) :: Types.Audio + t:check(near((AudioOps.peak(n)) :: number, 1, 1e-5), "normalize to 1") + local z = AudioOps.normalize(Types.Audio.new(8000, 1, 10)) :: Types.Audio + t:check(z and z.frames == 10, "normalize silence") +end + +-- channels +do + -- 5.1 (WAVE order FL FR C LFE BL BR) with distinct constants + local five = audio(8000, 6, 4, function(_, c) + return ({ 0.1, 0.2, 0.3, 0.4, 0.5, 0.6 })[c + 1] + end) + local st = AudioOps.downmix(five) :: Types.Audio + t:check(st and st.channels == 2, "5.1 -> stereo") + local h = math.sqrt(0.5) + local norm = 1 / (1 + 2 * h) + t:check(near(at(st, 0, 0), (0.1 + h * 0.3 + h * 0.5) * norm, 1e-6), "stereo L = FL + C / sqrt2 + BL / sqrt2 (normalised)") + t:check(near(at(st, 0, 1), (0.2 + h * 0.3 + h * 0.6) * norm, 1e-6), "stereo R (LFE dropped)") + local mono = AudioOps.downmix(sine, 1) :: Types.Audio + t:check(near(at(mono, 100, 0), (at(sine, 100, 0) + at(sine, 100, 1)) / 2, 1e-6), "stereo -> mono averages") + local up = AudioOps.upmix(mono, 2) :: Types.Audio + t:check(up.channels == 2 and at(up, 100, 0) == at(mono, 100, 0) and at(up, 100, 1) == at(mono, 100, 0), "mono -> stereo copies") + local up6 = AudioOps.upmix(sine, 6) :: Types.Audio + t:check(up6.channels == 6 and at(up6, 7, 0) == at(sine, 7, 0) and at(up6, 7, 1) == at(sine, 7, 1) and at(up6, 7, 2) == 0, "stereo -> 5.1 keeps FL / FR") + local swapped = AudioOps.remix(sine, 2, { { 0, 1 }, { 1, 0 } }) :: Types.Audio + t:check(at(swapped, 9, 0) == at(sine, 9, 1), "explicit matrix") + local _, e = AudioOps.downmix(mono, 2) + t:check(e and e.code == Err.ARG, "downmix to more channels: ARG") +end + +-- time +do + local r = AudioOps.resample(sine, 16000) :: Types.Audio + t:check(r.sampleRate == 16000 and r.frames == 16000, "resample 8 -> 16 kHz") + local err = 0 + for f = 2000, 14000 do + err = math.max(err, math.abs(at(r, f, 0) - 0.5 * math.sin(2 * math.pi * 440 * f / 16000))) + end + t:check(err < 1e-3, string.format("resampled sine (max err %.1e)", err)) + local c = AudioOps.trim(sine, 0.25, 0.5) :: Types.Audio + t:check(c.frames == 2000 and at(c, 0, 0) == at(sine, 2000, 0), "trim [0.25, 0.5) s") + t:eq((AudioOps.trim(sine, 0.9, 5) :: Types.Audio).frames, 800, "trim clamps") + local cat = AudioOps.concat({ sine, c }) :: Types.Audio + t:check(cat.frames == 10000 and at(cat, 8000, 1) == at(c, 0, 1), "concat") + local monoHi = audio(16000, 1, 1600, function() + return 0.1 + end) + local cat2 = AudioOps.concat({ sine, monoHi }) :: Types.Audio + t:check(cat2.channels == 2 and cat2.sampleRate == 8000 and math.abs(cat2.frames - 8800) <= 1, "concat converts rate and channels") + local m = AudioOps.mix({ sine, sine }, { 0.5, 0.25 }) :: Types.Audio + t:check(near(at(m, 50, 0), at(sine, 50, 0) * 0.75, 1e-6), "mix with weights") + local m2 = AudioOps.mix({ c, sine }) :: Types.Audio + t:check(m2.frames == 8000, "mix is as long as the longest") + local fd = AudioOps.fade(sine, 0.5, 0.5) :: Types.Audio + t:check(at(fd, 0, 0) == 0 and near(at(fd, 2000, 0), at(sine, 2000, 0) * 0.5, 1e-6) and near(at(fd, 7999, 0), 0), "fades") +end + +-- bad arguments: Err.ARG, never a throw +do + local junk: { any } = { nil, 5, "x", {}, { kind = "audio" }, Types.Image.new(2, 2) } + local calls = { + function(v: any) return AudioOps.gain(v, 2) end, + function(v: any) return AudioOps.remix(v, 2) end, + function(v: any) return AudioOps.resample(v, 44100) end, + function(v: any) return AudioOps.trim(v, 0) end, + function(v: any) return AudioOps.concat({ v }) end, + function(v: any) return AudioOps.mix(v) end, + function(v: any) return AudioOps.peak(v) end, + function(v: any) return AudioOps.fade(v, 1) end, + } + local ok = true + for _, fn in calls do + for i = 1, #junk + 1 do + local s, r, e = pcall(fn, junk[i]) + ok = ok and s and r == nil and type(e) == "table" and e.code ~= nil + end + end + t:check(ok, "bad values return nil, Err") + t:check(AudioOps.gain(sine, 0 / 0) == nil, "NaN gain") + t:check(AudioOps.resample(sine, 0) == nil, "zero rate") + t:check(AudioOps.remix(sine, 0) == nil, "zero channels") +end + +-- the F.ops facade +do + t:check(F.ops.audio == AudioOps, "F.ops.audio") + t:check(F.ops.image ~= nil and type(F.ops.image.resize) == "function", "F.ops.image") + t:check(type(F.ops.mesh.merge) == "function", "F.ops.mesh") + t:check(type(F.ops.layers.flatten) == "function", "F.ops.layers") + local v, err = F.load('<svg xmlns="http://www.w3.org/2000/svg" width="8" height="8"><rect width="8" height="8" fill="red"/></svg>') + t:check(v, "svg loads: " .. tostring(err)) + local img, rerr = F.ops.vector.rasterize(v, 8, 8) + t:check(img and img.width == 8 and buffer.readu8(img.pixels, 0) == 255 and buffer.readu8(img.pixels, 1) == 0, "F.ops.vector.rasterize: " .. tostring(rerr)) + t:check(F.ops.nothing == nil, "unknown ops: nil") +end + +-- (no decoder here: the no-throw pass is the bad-arguments block above) +t:done() From 8baa1f138800d5c68455bdba944a9a7429ed563b Mon Sep 17 00:00:00 2001 From: 4DBug <github@bug.tools> Date: Sat, 31 Oct 2026 11:30:29 -0500 Subject: [PATCH 15/22] ws-cleanup: compat math.clamp through math.min / math.max (LuaJIT) The branchy compat clamp spawned side traces in hot loops: ~3.5x slower than min(max(x, lo), hi) in a microbenchmark (NaN still passes through, as in Luau). MPEG-1 320x240 to rgba on LuaJIT (tuned traces): 2.92 -> 2.13 ms/frame. --- compat/luajit.lua | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/compat/luajit.lua b/compat/luajit.lua index 72cb133..2a6bfc9 100644 --- a/compat/luajit.lua +++ b/compat/luajit.lua @@ -476,10 +476,14 @@ end -- ---------------------------------------------------------------------------------------------------- math do + -- math.min / math.max are LuaJIT fast functions (branch-free minsd / maxsd in a trace); the two data-dependent + -- branches of `if x < lo ... elseif x > hi` spawned side traces in hot loops (codecs/Dct, colour conversion) and + -- ran ~3.5x slower. NaN stays NaN, as in Luau (maxsd would return lo). + local mmin, mmax = math.min, math.max math.clamp = math.clamp or function(x, lo, hi) if lo > hi then error("max must be greater than or equal to min", 2) end - if x < lo then return lo elseif x > hi then return hi end - return x + if x ~= x then return x end + return mmin(mmax(x, lo), hi) end math.sign = math.sign or function(x) if x > 0 then return 1 elseif x < 0 then return -1 end From 32434043746f1e7634233121727c08140490658e Mon Sep 17 00:00:00 2001 From: 4DBug <github@bug.tools> Date: Sat, 31 Oct 2026 11:30:29 -0500 Subject: [PATCH 16/22] ws-cleanup: type diagnostics 1109 -> 94 unique; lint gate against tools/lint_types_baseline.txt ws/cleanup-types (merged before) annotated Types, init, core, codecs, containers, ops, host and the formats; this commit fixes the rest in the modules ws-cleanup added (AudioOps, Resample, Vorbis / FLAC / Opus encoders). tools/lint.sh now counts unique diagnostics (the analyzer printed every required src module twice: master's '2499' was 1109 unique) and fails when the count rises above tools/lint_types_baseline.txt (94); LINT_TYPES_UPDATE=1 lowers it. --- src/Formats/audio/flac/Encode.luau | 2 +- src/Formats/audio/opus/Encode.luau | 2 +- src/Formats/audio/vorbis/Encode.luau | 6 +++--- src/Formats/codecs/Resample/init.luau | 17 ++++++++--------- src/Formats/ops/AudioOps.luau | 11 ++++++----- tools/lint.sh | 24 +++++++++++++++++++----- tools/lint_types_baseline.txt | 1 + 7 files changed, 39 insertions(+), 24 deletions(-) create mode 100644 tools/lint_types_baseline.txt diff --git a/src/Formats/audio/flac/Encode.luau b/src/Formats/audio/flac/Encode.luau index e6a0297..09bb289 100644 --- a/src/Formats/audio/flac/Encode.luau +++ b/src/Formats/audio/flac/Encode.luau @@ -769,7 +769,7 @@ function Encode.encode(src: Source, opts: Options): (buffer?, string?) local mbuf = buffer.create(bs * ch * mbytes) local scale = POW[bps] local maxv, minv = scale - 1, -scale - local X = table.create(ch) + local X: { { number } } = table.create(ch) :: any for c = 1, ch do X[c] = table.create(bs, 0) end diff --git a/src/Formats/audio/opus/Encode.luau b/src/Formats/audio/opus/Encode.luau index d26e4b1..971d872 100644 --- a/src/Formats/audio/opus/Encode.luau +++ b/src/Formats/audio/opus/Encode.luau @@ -25,7 +25,7 @@ local floor = math.floor -- encode(audio | decoder, opts) -> buffer | nil, Err function Encode.encode(value: any, opts: Options?): (buffer?, Err.Err?) - local o = opts or {} + local o: Options = opts or {} local src, serr = Pcm.source(value) if not src then return nil, serr diff --git a/src/Formats/audio/vorbis/Encode.luau b/src/Formats/audio/vorbis/Encode.luau index 2b1405e..e1ce3ad 100644 --- a/src/Formats/audio/vorbis/Encode.luau +++ b/src/Formats/audio/vorbis/Encode.luau @@ -604,7 +604,7 @@ function Encode.encode(src: Source, opts: Options): (buffer?, string?) local plan = Mdct.new(N) :: Mdct.Plan local win = Mdct.window("vorbis", N) :: { number } -- input ring: per channel the samples of the current frame [k*1024 - 1024, k*1024 + 1024) - local frame = table.create(ch) + local frame: { { number } } = table.create(ch) :: any for c = 1, ch do frame[c] = table.create(N, 0) end @@ -617,8 +617,8 @@ function Encode.encode(src: Source, opts: Options): (buffer?, string?) end end local blk = table.create(N, 0) - local X = table.create(ch) - local R = table.create(ch) + local X: { { number } } = table.create(ch) :: any + local R: { { number } } = table.create(ch) :: any for c = 1, ch do X[c] = table.create(N2, 0) R[c] = table.create(N2, 0) diff --git a/src/Formats/codecs/Resample/init.luau b/src/Formats/codecs/Resample/init.luau index e0bfdfd..1096060 100644 --- a/src/Formats/codecs/Resample/init.luau +++ b/src/Formats/codecs/Resample/init.luau @@ -208,7 +208,7 @@ local function run(st: State, limitOut: number, out: buffer?): (buffer, number) st.histFrames = 0 st.base = base + histFrames else - local nh = table.create((histFrames - drop) * ch) + local nh: { number } = table.create((histFrames - drop) * ch) :: any table.move(hist, drop * ch + 1, histFrames * ch, 1, nh) st.hist = nh st.histFrames = histFrames - drop @@ -251,7 +251,7 @@ function Resample.new(from: number, to: number, channels: number, opts: Options? if type(channels) ~= "number" or channels < 1 or channels > 256 or channels ~= floor(channels) then return nil, "bad channel count" end - local q = QUALITY[(opts and opts.quality) or "medium"] + local q: { number }? = QUALITY[(opts and opts.quality) or "medium"] if not q then return nil, "quality must be low, medium or high" end @@ -260,12 +260,11 @@ function Resample.new(from: number, to: number, channels: number, opts: Options? return nil, "cutoff must be 0.5 .. 1" end -- positions are exact integers: output j sits at input j * M / L (non-integer rates: to 1 / 1000 Hz) - local fi, ti = from, to - if from ~= floor(from) or to ~= floor(to) then - fi, ti = floor(from * 1000 + 0.5), floor(to * 1000 + 0.5) - end - local g = gcd(fi, ti) - local L, M = ti // g, fi // g + local scale = if from ~= floor(from) or to ~= floor(to) then 1000 else 1 + local fi: number = floor(from * scale + 0.5) + local ti: number = floor(to * scale + 0.5) + local g: number = gcd(fi, ti) + local L: number, M: number = ti // g, fi // g local exact = L <= MAX_EXACT local phases = if exact then L else INTERP_PHASES local st: State = { @@ -348,7 +347,7 @@ function Resample.source(src: any, to: number, opts: Options?): (any, string?) function out.read(self: any, n: number, dst: buffer?): (buffer, number) n = floor(n) while pendingFrames - pendingPos <= 0 and not ended do - local b, m = src:read(math.max(1024, floor(n * src.sampleRate / to) + 64), inTmp) + local b: buffer, m: number = (src :: any):read(math.max(1024, floor(n * src.sampleRate / to) + 64), inTmp) inTmp = b local r: buffer, k: number if m <= 0 then diff --git a/src/Formats/ops/AudioOps.luau b/src/Formats/ops/AudioOps.luau index c1a5d53..b1803e6 100644 --- a/src/Formats/ops/AudioOps.luau +++ b/src/Formats/ops/AudioOps.luau @@ -207,7 +207,7 @@ local TO_STEREO: { [string]: { number } } = { -- matrix(from, to) -> m[o][i]: output channel o = sum m[o][i] * input i local function matrix(from: number, to: number): { { number } } - local m = table.create(to) + local m: { { number } } = table.create(to) :: any for o = 1, to do m[o] = table.create(from, 0) end @@ -220,7 +220,7 @@ local function matrix(from: number, to: number): { { number } } local inL, outL = LAYOUT[from], LAYOUT[to] if to < from and inL and outL and to <= 2 then -- down to stereo (then mono = the average of the two) - local l, r = table.create(from, 0), table.create(from, 0) + local l: { number }, r: { number } = table.create(from, 0), table.create(from, 0) local sl, sr = 0, 0 for i, sp in inL do local w = TO_STEREO[sp] or { 0, 0 } @@ -266,10 +266,11 @@ local function matrix(from: number, to: number): { { number } } local o = outIdx[sp] if o then m[o][i] = 1 - elseif to < from and outIdx.FL and outIdx.FR then + elseif to < from and outIdx.FL ~= nil and outIdx.FR ~= nil then local w = TO_STEREO[sp] or { 0, 0 } - m[outIdx.FL][i] += w[1] - m[outIdx.FR][i] += w[2] + local fl, fr = outIdx.FL :: number, outIdx.FR :: number + m[fl][i] += w[1] + m[fr][i] += w[2] end end if to < from then diff --git a/tools/lint.sh b/tools/lint.sh index 270d758..bc16885 100644 --- a/tools/lint.sh +++ b/tools/lint.sh @@ -1,8 +1,10 @@ #!/usr/bin/env bash # Lint (bash tools/lint.sh): # 1. GLOBALS: unknown globals (luau-analyze), a local used before its declaration compiles fine but reads a nil -# global at runtime. Roblox globals are allowed (the library runs in Roblox, luau and LuaJIT). Other type errors -# are counted and printed with LINT_TYPES=1, but do not fail the lint (absorbed code predates --!strict). +# global at runtime. Roblox globals are allowed (the library runs in Roblox, luau and LuaJIT). +# TYPES: the other type diagnostics are counted (unique lines: the analyzer reports a required module once per +# path spelling) and printed with LINT_TYPES=1. The count may not rise above tools/lint_types_baseline.txt; when +# it drops, lower the baseline (LINT_TYPES_UPDATE=1 writes the current count), so it only goes down. # 2. HEADER, REQUIRE, NATIVE (native code never throws: it crashes Roblox Studio), LAYERS, DEPS, CONTRACT: # tools/lint_rules.py (its header lists the rules; docs/STYLE.md explains them). # 3. The generated registry / docs/FORMATS.md are up to date (tools/gen_registry.py --check), and tools/build.py's @@ -19,12 +21,24 @@ if [ -n "$bad" ]; then echo "lint: unknown globals (a local used before it is declared?)" fail=1 fi -ntype=$(echo "$report" | grep -c "Error:") -[ -n "$LINT_TYPES" ] && echo "$report" | grep -v "Unknown global" +types=$(echo "$report" | grep "Error:" | grep -v "Unknown global" | sed "s#^$PWD/#./#" | sort -u) +ntype=$(if [ -n "$types" ]; then echo "$types" | wc -l; else echo 0; fi) +[ -n "$LINT_TYPES" ] && echo "$types" +baseline=$(cat tools/lint_types_baseline.txt 2>/dev/null || echo 0) +if [ -n "$LINT_TYPES_UPDATE" ]; then + echo "$ntype" > tools/lint_types_baseline.txt + baseline=$ntype +fi +if [ "$ntype" -gt "$baseline" ]; then + echo "lint: $ntype type diagnostics, more than the baseline $baseline (tools/lint_types_baseline.txt); LINT_TYPES=1 lists them" + fail=1 +elif [ "$ntype" -lt "$baseline" ]; then + echo "lint: $ntype type diagnostics, below the baseline $baseline: lower it (LINT_TYPES_UPDATE=1 bash tools/lint.sh)" +fi python3 -I tools/lint_rules.py || { echo "lint: structure rules failed (see tools/lint_rules.py)"; fail=1; } python3 -I tools/gen_registry.py --check > /dev/null || { python3 -I tools/gen_registry.py --check; fail=1; } python3 -I tools/build.py --test > /dev/null || { echo "lint: tools/build.py --test failed"; fail=1; } if [ $fail -eq 0 ]; then - echo "lint passed (globals, header, require, native, layers, deps, contract, registry; $ntype type diagnostics: LINT_TYPES=1 shows them)" + echo "lint passed (globals, header, require, native, layers, deps, contract, registry; $ntype type diagnostics, baseline $baseline: LINT_TYPES=1 shows them)" fi exit $fail diff --git a/tools/lint_types_baseline.txt b/tools/lint_types_baseline.txt new file mode 100644 index 0000000..49541f7 --- /dev/null +++ b/tools/lint_types_baseline.txt @@ -0,0 +1 @@ +94 From 763f4a7c04c6095bc36fa5cd6d220e18591e1b30 Mon Sep 17 00:00:00 2001 From: 4DBug <github@bug.tools> Date: Sat, 31 Oct 2026 12:00:59 -0500 Subject: [PATCH 17/22] ws-cleanup: shared plumbing: Err.from, core/Sniff, Pcm.drain, Bits.msbPut; DUP lint; tools/move.py - core/Err.from(message, offset?, kind?): the private-submodule -> Err plumbing (a kind, or a 'code: ' prefix / 'truncated' / 'past the end' in the message) that Brotli, Bzip2, Zstd, Jpeg, WOFF2, FBX, plist, msgpack and bmfont each wrote. - core/Sniff (new): Sniff.text(r, n, trim?) (the start of a text file without its BOM), Sniff.dropBom(s), Sniff.magic(r, s); 13 text formats' sniff / decode BOM handling goes through it. - codecs/Pcm.drain(dec, source?, maxFrames?): a format's decode() through its open(); the collect-the-Decoder loops of aac, aiff, au, caf, flac, m4a, mp3, opus, vorbis and wav are one call each. - core/Bits.msbPut: the MSB-first bit writer the MP3 / MP2 / FLAC encoders each copied. - tools/lint_rules.py DUP: a function body of 12+ code lines repeated token for token in another module fails. - tools/move.py: moves a module and rewrites every reference (requires, deps, headers, fixture INPUTS, docs). - tools/fixtures/zstd.py: the incompressible corpus is smaller (zstd.luau 15.1 -> 13.4 MB; every fixture module is now under 14.3 MB). - tools/bench.luau: MPEG-1 also runs with the api's LuaJIT trace limits; the sections that compare tuned / default limits set them explicitly (jitTune), so the order of sections no longer leaks the tuning. --- src/Formats/Registry.luau | 38 +++++++------- src/Formats/audio/aac/init.luau | 20 ++------ src/Formats/audio/aiff/init.luau | 7 +-- src/Formats/audio/au/init.luau | 7 +-- src/Formats/audio/caf/init.luau | 20 ++------ src/Formats/audio/flac/Encode.luau | 22 ++------ src/Formats/audio/flac/init.luau | 31 +---------- src/Formats/audio/m4a/init.luau | 30 ++--------- src/Formats/audio/mp3/Encode2.luau | 21 ++------ src/Formats/audio/mp3/Encode3.luau | 21 ++------ src/Formats/audio/mp3/init.luau | 13 ++--- src/Formats/audio/opus/init.luau | 21 +------- src/Formats/audio/vorbis/init.luau | 23 +-------- src/Formats/audio/wav/init.luau | 16 ++---- src/Formats/cad/step/init.luau | 8 ++- src/Formats/codecs/Brotli/init.luau | 13 ++--- src/Formats/codecs/Bzip2/init.luau | 10 +--- src/Formats/codecs/Jpeg/init.luau | 6 +-- src/Formats/codecs/Pcm/init.luau | 20 ++++++++ src/Formats/codecs/Zstd/init.luau | 10 +--- src/Formats/core/Bits.luau | 23 +++++++++ src/Formats/core/Err.luau | 36 +++++++++++++ src/Formats/core/Sniff.luau | 36 +++++++++++++ src/Formats/data/csv/init.luau | 7 ++- src/Formats/data/ini/init.luau | 7 ++- src/Formats/data/json/init.luau | 8 ++- src/Formats/data/msgpack/init.luau | 2 +- src/Formats/data/plist/init.luau | 2 +- src/Formats/data/xml/init.luau | 8 ++- src/Formats/font/bmfont/init.luau | 3 +- src/Formats/font/woff2/init.luau | 4 +- src/Formats/model/fbx/init.luau | 13 +---- src/Formats/model/gltf/init.luau | 5 +- src/Formats/playlist/m3u/init.luau | 8 ++- src/Formats/playlist/pls/init.luau | 8 ++- src/Formats/subtitle/ass/init.luau | 12 ++--- src/Formats/subtitle/srt/init.luau | 12 ++--- src/Formats/subtitle/vtt/init.luau | 12 ++--- src/Formats/vector/svg/init.luau | 8 ++- src/Formats/vector/tiled/init.luau | 8 ++- tools/bench.luau | 53 ++++++++++++++----- tools/fixtures/zstd.py | 2 +- tools/lint_rules.py | 31 +++++++++++ tools/move.py | 79 +++++++++++++++++++++++++++++ 44 files changed, 374 insertions(+), 370 deletions(-) create mode 100644 src/Formats/core/Sniff.luau create mode 100644 tools/move.py diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 86bd0ce..79b5789 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -152,7 +152,7 @@ local list: { Entry } = { path = "audio/aac", extensions = { "aac", "adts" }, mime = { "audio/aac", "audio/aacp", "audio/x-aac" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Aac" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Aac", "codecs/Pcm" }, caps = { decode = true, encode = false, codecs = { "aac" }, streaming = true }, load = function() return require("@formats/audio/aac") @@ -188,7 +188,7 @@ local list: { Entry } = { path = "audio/caf", extensions = { "caf", "caff" }, mime = { "audio/x-caf" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Aac", "codecs/Alac" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Aac", "codecs/Alac", "codecs/Pcm" }, caps = { decode = true, encode = true, codecs = { "pcm", "alac", "aac", "ulaw", "alaw" }, encodeCodecs = { "pcm", "alac" }, tags = true, streaming = true }, load = function() return require("@formats/audio/caf") @@ -200,7 +200,7 @@ local list: { Entry } = { path = "audio/flac", extensions = { "flac", "oga" }, mime = { "audio/flac", "audio/x-flac" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "core/Md5", "codecs/Pcm", "codecs/VorbisComment" }, + deps = { "core/Err", "core/Bytes", "core/Bits", "Types", "containers/Ogg", "core/Md5", "codecs/Pcm", "codecs/VorbisComment" }, caps = { decode = true, encode = true, streaming = true, depths = { 4, 8, 12, 16, 20, 24, 32 }, ogg = true, seek = true }, load = function() return require("@formats/audio/flac") @@ -212,7 +212,7 @@ local list: { Entry } = { path = "audio/m4a", extensions = { "m4a", "m4b", "m4r" }, mime = { "audio/mp4", "audio/x-m4a", "audio/m4a" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/IsoBmff", "codecs/Aac", "codecs/Alac" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/IsoBmff", "codecs/Aac", "codecs/Alac", "codecs/Pcm" }, caps = { decode = true, encode = true, codecs = { "aac", "alac" }, encodeCodecs = { "alac" }, tags = true, streaming = true }, load = function() return require("@formats/audio/m4a") @@ -224,7 +224,7 @@ local list: { Entry } = { path = "audio/mp3", extensions = { "mp3", "mp2", "mp1", "mpga" }, mime = { "audio/mpeg", "audio/mp3", "audio/mpa" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm", "codecs/Resample" }, + deps = { "core/Err", "core/Bytes", "core/Bits", "Types", "codecs/Pcm", "codecs/Resample" }, caps = { decode = true, encode = true, streaming = true, seek = true, layers = { 1, 2, 3 }, encodeLayers = { 2, 3 }, channels = 2 }, load = function() return require("@formats/audio/mp3") @@ -272,7 +272,7 @@ local list: { Entry } = { path = "audio/wav", extensions = { "wav", "wave", "rf64", "bw64" }, mime = { "audio/wav", "audio/x-wav", "audio/wave", "audio/vnd.wave" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Riff" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Riff", "codecs/Pcm" }, caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, rf64 = true }, load = function() return require("@formats/audio/wav") @@ -404,7 +404,7 @@ local list: { Entry } = { path = "model/gltf", extensions = { "gltf", "glb" }, mime = { "model/gltf+json", "model/gltf-binary" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Json", "core/Base64" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Json", "core/Base64", "core/Sniff" }, caps = { decode = true, encode = true, binary = true, materials = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true }, load = function() return require("@formats/model/gltf") @@ -488,7 +488,7 @@ local list: { Entry } = { path = "cad/step", extensions = { "step", "stp", "p21" }, mime = { "model/step", "application/step", "application/p21" }, - deps = { "core/Err", "core/Bytes", "Types" }, + deps = { "core/Err", "core/Bytes", "Types", "core/Sniff" }, caps = { decode = true, encode = true, complexEntities = true, sections = true, brep = "plugin", tessellate = "plugin" }, load = function() return require("@formats/cad/step") @@ -656,7 +656,7 @@ local list: { Entry } = { path = "data/csv", extensions = { "csv", "tsv" }, mime = { "text/csv", "text/tab-separated-values" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Json" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Json", "core/Sniff" }, caps = { decode = true, encode = true, header = true }, load = function() return require("@formats/data/csv") @@ -668,7 +668,7 @@ local list: { Entry } = { path = "data/ini", extensions = { "ini", "cfg", "conf", "inf", "desktop" }, mime = { "text/plain" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Json" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Json", "core/Sniff" }, caps = { decode = true, encode = true, ordered = true }, load = function() return require("@formats/data/ini") @@ -680,7 +680,7 @@ local list: { Entry } = { path = "data/json", extensions = { "json", "jsonl", "ndjson", "geojson" }, mime = { "application/json", "application/x-ndjson" }, - deps = { "core/Err", "core/Bytes", "codecs/Json" }, + deps = { "core/Err", "core/Bytes", "codecs/Json", "core/Sniff" }, caps = { decode = true, encode = true, ordered = true, streaming = true }, load = function() return require("@formats/data/json") @@ -728,7 +728,7 @@ local list: { Entry } = { path = "data/xml", extensions = { "xml", "xsd", "xsl", "xslt", "rss", "atom", "xhtml" }, mime = { "application/xml", "text/xml" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "core/Sniff" }, caps = { decode = true, encode = true, namespaces = true, streaming = true }, load = function() return require("@formats/data/xml") @@ -752,7 +752,7 @@ local list: { Entry } = { path = "vector/svg", extensions = { "svg" }, mime = { "image/svg+xml" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "codecs/Raster", "codecs/Blend" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "codecs/Raster", "codecs/Blend", "core/Sniff" }, caps = { decode = true, encode = true, rasterize = true, text = false }, load = function() return require("@formats/vector/svg") @@ -764,7 +764,7 @@ local list: { Entry } = { path = "vector/tiled", extensions = { "tmx", "tmj", "tsx", "tsj" }, mime = { "application/x-tiled-tmx", "application/x-tiled-tmj" }, - deps = { "core/Err", "core/Bytes", "core/Base64", "Types", "codecs/Xml", "codecs/Json", "codecs/Deflate" }, + deps = { "core/Err", "core/Bytes", "core/Base64", "Types", "codecs/Xml", "codecs/Json", "codecs/Deflate", "core/Sniff" }, caps = { decode = true, encode = true, tilesets = true, infinite = true }, load = function() return require("@formats/vector/tiled") @@ -800,7 +800,7 @@ local list: { Entry } = { path = "subtitle/ass", extensions = { "ass", "ssa" }, mime = { "text/x-ssa", "text/x-ass" }, - deps = { "core/Err", "core/Bytes", "Types" }, + deps = { "core/Err", "core/Bytes", "Types", "core/Sniff" }, caps = { decode = true, encode = true, styles = true }, load = function() return require("@formats/subtitle/ass") @@ -812,7 +812,7 @@ local list: { Entry } = { path = "subtitle/srt", extensions = { "srt" }, mime = { "application/x-subrip", "text/srt" }, - deps = { "core/Err", "core/Bytes", "Types" }, + deps = { "core/Err", "core/Bytes", "Types", "core/Sniff" }, caps = { decode = true, encode = true, styles = false }, load = function() return require("@formats/subtitle/srt") @@ -824,7 +824,7 @@ local list: { Entry } = { path = "subtitle/vtt", extensions = { "vtt", "webvtt" }, mime = { "text/vtt" }, - deps = { "core/Err", "core/Bytes", "Types" }, + deps = { "core/Err", "core/Bytes", "Types", "core/Sniff" }, caps = { decode = true, encode = true, styles = true }, load = function() return require("@formats/subtitle/vtt") @@ -908,7 +908,7 @@ local list: { Entry } = { path = "playlist/m3u", extensions = { "m3u", "m3u8" }, mime = { "audio/x-mpegurl", "audio/mpegurl", "application/vnd.apple.mpegurl", "application/x-mpegurl" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Url", "codecs/Text" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Url", "codecs/Text", "core/Sniff" }, caps = { decode = true, encode = true, hls = true }, load = function() return require("@formats/playlist/m3u") @@ -920,7 +920,7 @@ local list: { Entry } = { path = "playlist/pls", extensions = { "pls" }, mime = { "audio/x-scpls", "audio/scpls" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Url", "codecs/Text" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Url", "codecs/Text", "core/Sniff" }, caps = { decode = true, encode = true }, load = function() return require("@formats/playlist/pls") diff --git a/src/Formats/audio/aac/init.luau b/src/Formats/audio/aac/init.luau index 84ded12..21deaf5 100644 --- a/src/Formats/audio/aac/init.luau +++ b/src/Formats/audio/aac/init.luau @@ -8,6 +8,7 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") +local Pcm = require("@formats/codecs/Pcm") local Aac = require("@formats/codecs/Aac") -- ------------------------------------------------------------------------------------------------ contract @@ -16,7 +17,7 @@ local AacFormat = { category = "audio", extensions = { "aac", "adts" }, mime = { "audio/aac", "audio/aacp", "audio/x-aac" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Aac" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Aac", "codecs/Pcm" }, caps = { decode = true, encode = false, codecs = { "aac" }, streaming = true }, } @@ -256,22 +257,7 @@ function AacFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, return nil, err end local d: any = dec - local audio = Types.Audio.new(d.sampleRate, d.channels, d.frames) - local done = 0 - while done < d.frames do - local b, n = d:read(math.min(65536, d.frames - done)) - if n == 0 then - break - end - buffer.copy(audio.samples, done * d.channels * 4, b, 0, n * d.channels * 4) - done += n - end - if d.error then - return nil, d.error - end - audio.tags = d.tags - audio.meta.source = { format = "aac", codec = "aac", bitrate = d.bitrate } - return audio, nil + return Pcm.drain(d, { format = "aac", codec = "aac", bitrate = d.bitrate }) end return AacFormat diff --git a/src/Formats/audio/aiff/init.luau b/src/Formats/audio/aiff/init.luau index dfd2a29..baf8ad2 100644 --- a/src/Formats/audio/aiff/init.luau +++ b/src/Formats/audio/aiff/init.luau @@ -248,12 +248,7 @@ function Aiff.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err. if not dec then return nil, err end - local d = dec :: any - local a = Types.Audio.new(d.sampleRate, d.channels, d.frames) - d:read(d.frames, a.samples) - a.tags = d.tags - a.meta.source = d.source - return a, nil + return Pcm.drain(dec) end -- ------------------------------------------------------------------------------------------------ encode diff --git a/src/Formats/audio/au/init.luau b/src/Formats/audio/au/init.luau index 0215799..08a45ab 100644 --- a/src/Formats/audio/au/init.luau +++ b/src/Formats/audio/au/init.luau @@ -66,12 +66,7 @@ function Au.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Er if not dec then return nil, err end - local d = dec :: any - local a = Types.Audio.new(d.sampleRate, d.channels, d.frames) - d:read(d.frames, a.samples) - a.tags = d.tags - a.meta.source = d.source - return a, nil + return Pcm.drain(dec) end -- ------------------------------------------------------------------------------------------------ encode diff --git a/src/Formats/audio/caf/init.luau b/src/Formats/audio/caf/init.luau index f935b96..48769f9 100644 --- a/src/Formats/audio/caf/init.luau +++ b/src/Formats/audio/caf/init.luau @@ -9,6 +9,7 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") +local Pcm = require("@formats/codecs/Pcm") local Aac = require("@formats/codecs/Aac") local Alac = require("@formats/codecs/Alac") @@ -18,7 +19,7 @@ local Caf = { category = "audio", extensions = { "caf", "caff" }, mime = { "audio/x-caf" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Aac", "codecs/Alac" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Aac", "codecs/Alac", "codecs/Pcm" }, caps = { decode = true, encode = true, codecs = { "pcm", "alac", "aac", "ulaw", "alaw" }, encodeCodecs = { "pcm", "alac" }, tags = true, streaming = true }, } @@ -559,22 +560,7 @@ function Caf.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.E return nil, err end local d: any = dec - local audio = Types.Audio.new(d.sampleRate, d.channels, d.frames) - local done = 0 - while done < d.frames do - local b, n = d:read(math.min(65536, d.frames - done)) - if n == 0 then - break - end - buffer.copy(audio.samples, done * d.channels * 4, b, 0, n * d.channels * 4) - done += n - end - if d.error then - return nil, d.error - end - audio.tags = d.tags - audio.meta.source = { format = "caf", codec = d.codec, bitsPerSample = d.bitsPerSample } - return audio, nil + return Pcm.drain(d, { format = "caf", codec = d.codec, bitsPerSample = d.bitsPerSample }) end -- ------------------------------------------------------------------------------------------------ encode diff --git a/src/Formats/audio/flac/Encode.luau b/src/Formats/audio/flac/Encode.luau index 09bb289..ecc187c 100644 --- a/src/Formats/audio/flac/Encode.luau +++ b/src/Formats/audio/flac/Encode.luau @@ -10,6 +10,7 @@ -- CRC-16; STREAMINFO carries the sizes, total samples and the MD5 of the PCM; VORBIS_COMMENT from the tags; an optional -- SEEKTABLE. Streams: input blocks are pulled from a codecs/Pcm Source, so a Decoder is encoded without decoding it -- whole. Never throws: bad options are rejected by audio/flac before calling in. +local Bits = require("@formats/core/Bits") local Md5 = require("@formats/core/Md5") local VorbisComment = require("@formats/codecs/VorbisComment") local Frame = require("@formats/audio/flac/Frame") @@ -35,7 +36,7 @@ end Encode.crc8, Encode.crc16 = crc8, crc16 -- ------------------------------------------------------------------------------------------------ bit writer (MSB first) -type W = { buf: buffer, pos: number, acc: number, cnt: number } +type W = Bits.RawWriter local function ensure(w: W, n: number) local need = w.pos + n + 16 @@ -47,24 +48,7 @@ local function ensure(w: W, n: number) end end --- put(w, v, n): the low n bits (n <= 32) of the non-negative integer v -local function put(w: W, v: number, n: number) - if n == 0 then - return - end - local acc = w.acc * POW[n + 1] + v - local cnt = w.cnt + n - local b, p = w.buf, w.pos - while cnt >= 8 do - cnt -= 8 - local m = POW[cnt + 1] - local byte = floor(acc / m) - writeu8(b, p, byte) - p += 1 - acc -= byte * m - end - w.acc, w.cnt, w.pos = acc, cnt, p -end +local put = Bits.msbPut local function putSigned(w: W, v: number, n: number) put(w, if v < 0 then v + POW[n + 1] else v, n) diff --git a/src/Formats/audio/flac/init.luau b/src/Formats/audio/flac/init.luau index 724774d..26e321c 100644 --- a/src/Formats/audio/flac/init.luau +++ b/src/Formats/audio/flac/init.luau @@ -29,7 +29,7 @@ local Flac = { category = "audio", extensions = { "flac", "oga" }, mime = { "audio/flac", "audio/x-flac" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "core/Md5", "codecs/Pcm", "codecs/VorbisComment" }, + deps = { "core/Err", "core/Bytes", "core/Bits", "Types", "containers/Ogg", "core/Md5", "codecs/Pcm", "codecs/VorbisComment" }, caps = { decode = true, encode = true, streaming = true, depths = { 4, 8, 12, 16, 20, 24, 32 }, ogg = true, seek = true }, } @@ -89,34 +89,7 @@ function Flac.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Er if d.frames > limit or d.frames * d.channels > 2 ^ 28 then return nil, Err.new(Err.LIMIT, string.format("%d frames is over the limit", d.frames)) end - local ch = d.channels - local parts, total = {}, 0 - if d.frames > 0 then - local out, n = d:read(d.frames) - table.insert(parts, out) - total = n - end - while true do -- frames past what STREAMINFO / the scan said - local out, n = d:read(65536) - if n == 0 then - break - end - table.insert(parts, out) - total += n - if total > limit then - return nil, Err.new(Err.LIMIT, "stream over the frame limit") - end - end - local a = Types.Audio.new(d.sampleRate, ch, total) - local o = 0 - for _, p in parts do - local n = math.min(buffer.len(p), total * ch * 4 - o) - buffer.copy(a.samples, o, p, 0, n) - o += n - end - a.tags = d.tags - a.meta.source = { format = "flac", bitDepth = d.bitsPerSample, container = d.container, vendor = d.vendor, md5 = d.md5, pictures = d.pictures, comments = d.comments } - return a, nil + return Pcm.drain(d, { format = "flac", bitDepth = d.bitsPerSample, container = d.container, vendor = d.vendor, md5 = d.md5, pictures = d.pictures, comments = d.comments }, limit) end -- ------------------------------------------------------------------------------------------------ encode diff --git a/src/Formats/audio/m4a/init.luau b/src/Formats/audio/m4a/init.luau index c7b06b8..babc9bd 100644 --- a/src/Formats/audio/m4a/init.luau +++ b/src/Formats/audio/m4a/init.luau @@ -9,6 +9,7 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") +local Pcm = require("@formats/codecs/Pcm") local IsoBmff = require("@formats/containers/IsoBmff") local Aac = require("@formats/codecs/Aac") local Alac = require("@formats/codecs/Alac") @@ -19,7 +20,7 @@ local M4a = { category = "audio", extensions = { "m4a", "m4b", "m4r" }, mime = { "audio/mp4", "audio/x-m4a", "audio/m4a" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/IsoBmff", "codecs/Aac", "codecs/Alac" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/IsoBmff", "codecs/Aac", "codecs/Alac", "codecs/Pcm" }, caps = { decode = true, encode = true, codecs = { "aac", "alac" }, encodeCodecs = { "alac" }, tags = true, streaming = true }, } @@ -306,32 +307,11 @@ function M4a.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.E return nil, err end local d: any = dec - local audio = Types.Audio.new(d.sampleRate, d.channels, d.frames) - local done = 0 - local chunk = buffer.create(65536 * d.channels * 4) - while done < d.frames do - local b, n = d:read(math.min(65536, d.frames - done), chunk) - if n == 0 then - break - end - buffer.copy(audio.samples, done * d.channels * 4, b, 0, n * d.channels * 4) - done += n - end - if d.error then - return nil, d.error - end - if done < d.frames then - local short = buffer.create(done * d.channels * 4) - buffer.copy(short, 0, audio.samples, 0, buffer.len(short)) - audio.samples = short - audio.frames = done - end - audio.tags = d.tags - audio.meta.source = { format = "m4a", codec = d.codec, bitsPerSample = d.track.bitsPerSample, brand = d.movie.brand } - if #d.pictures > 0 then + local audio, derr = Pcm.drain(d, { format = "m4a", codec = d.codec, bitsPerSample = d.track.bitsPerSample, brand = d.movie.brand }) + if audio and #d.pictures > 0 then audio.meta.pictures = d.pictures end - return audio, nil + return audio, derr end -- ------------------------------------------------------------------------------------------------ encode diff --git a/src/Formats/audio/mp3/Encode2.luau b/src/Formats/audio/mp3/Encode2.luau index 3ce1594..5d8db97 100644 --- a/src/Formats/audio/mp3/Encode2.luau +++ b/src/Formats/audio/mp3/Encode2.luau @@ -8,6 +8,7 @@ -- in this folder reads them), a greedy allocation that always gives the next step to the band with the most noise -- (signal level minus the quantizer's SNR; no psychoacoustic model), uniform midtread quantization and grouping of -- 3 / 5 / 9-level samples. Never throws. +local Bits = require("@formats/core/Bits") local T = require("@formats/audio/mp3/Tables") local Analysis = require("@formats/audio/mp3/Analysis") @@ -87,24 +88,8 @@ local BITRATES_V1 = { 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, local BITRATES_V2 = { 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160 } Encode2.BITRATES = { [1] = BITRATES_V1, [2] = BITRATES_V2 } -type W = { buf: buffer, pos: number, acc: number, cnt: number } -local function put(w: W, v: number, n: number) - if n == 0 then - return - end - local acc = w.acc * POW[n + 1] + v - local cnt = w.cnt + n - local b, p = w.buf, w.pos - while cnt >= 8 do - cnt -= 8 - local m = POW[cnt + 1] - local byte = floor(acc / m) - writeu8(b, p, byte) - p += 1 - acc -= byte * m - end - w.acc, w.cnt, w.pos = acc, cnt, p -end +type W = Bits.RawWriter +local put = Bits.msbPut export type Source = { sampleRate: number, diff --git a/src/Formats/audio/mp3/Encode3.luau b/src/Formats/audio/mp3/Encode3.luau index 39e6dbf..e088369 100644 --- a/src/Formats/audio/mp3/Encode3.luau +++ b/src/Formats/audio/mp3/Encode3.luau @@ -8,6 +8,7 @@ -- analysis filterbank (audio/mp3/Analysis), the 36-point MDCT with the sine window, the alias-reduction butterflies, -- the x^(3/4) quantizer, big_values / count1 partitioning with per-region Huffman table choice; the Huffman codes are -- derived from the standard's decoder trees (audio/mp3/EncTables, from PDMP3, public domain). Never throws. +local Bits = require("@formats/core/Bits") local E = require("@formats/audio/mp3/EncTables") local T = require("@formats/audio/mp3/Tables") local Analysis = require("@formats/audio/mp3/Analysis") @@ -87,25 +88,9 @@ for m = 0, 15 do end -- ------------------------------------------------------------------------------------------------ bit writer -type W = { buf: buffer, pos: number, acc: number, cnt: number } +type W = Bits.RawWriter -local function put(w: W, v: number, n: number) - if n == 0 then - return - end - local acc = w.acc * POW[n + 1] + v - local cnt = w.cnt + n - local b, p = w.buf, w.pos - while cnt >= 8 do - cnt -= 8 - local m = POW[cnt + 1] - local byte = floor(acc / m) - writeu8(b, p, byte) - p += 1 - acc -= byte * m - end - w.acc, w.cnt, w.pos = acc, cnt, p -end +local put = Bits.msbPut Encode3.put = put -- ------------------------------------------------------------------------------------------------ constants diff --git a/src/Formats/audio/mp3/init.luau b/src/Formats/audio/mp3/init.luau index 9fd3a8c..5029c4e 100644 --- a/src/Formats/audio/mp3/init.luau +++ b/src/Formats/audio/mp3/init.luau @@ -32,7 +32,7 @@ local Mp3 = { category = "audio", extensions = { "mp3", "mp2", "mp1", "mpga" }, mime = { "audio/mpeg", "audio/mp3", "audio/mpa" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm", "codecs/Resample" }, + deps = { "core/Err", "core/Bytes", "core/Bits", "Types", "codecs/Pcm", "codecs/Resample" }, caps = { decode = true, encode = true, streaming = true, seek = true, layers = { 1, 2, 3 }, encodeLayers = { 2, 3 }, channels = 2 }, } @@ -91,14 +91,11 @@ function Mp3.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err if not dec then return nil, err end - local a = Types.Audio.new(dec.sampleRate, dec.channels, dec.frames) - local _, n = dec:read(dec.frames, a.samples) - if n < dec.frames then - return nil, Err.new(Err.CORRUPT, string.format("decoded %d of %d frames", n, dec.frames)) + local a, derr = Pcm.drain(dec, { format = "mp3", layer = dec.layer, version = dec.version, bitrate = dec.bitrate, vbr = dec.vbr }) + if a and a.frames < dec.frames then + return nil, Err.new(Err.CORRUPT, string.format("decoded %d of %d frames", a.frames, dec.frames)) end - a.tags = dec.tags - a.meta.source = { format = "mp3", layer = dec.layer, version = dec.version, bitrate = dec.bitrate, vbr = dec.vbr } - return a, nil + return a, derr end -- ------------------------------------------------------------------------------------------------ encode diff --git a/src/Formats/audio/opus/init.luau b/src/Formats/audio/opus/init.luau index 9138762..b1d213d 100644 --- a/src/Formats/audio/opus/init.luau +++ b/src/Formats/audio/opus/init.luau @@ -191,26 +191,7 @@ function Opus.decode(r: any, opts: OpenOptions?): (Types.Audio?, Err.Err?) if not dec then return nil, err end - local ch = dec.channels - local a = Types.Audio.new(SAMPLE_RATE, ch, dec.frames) - local total = 0 - while total < dec.frames do - local pcm, n = dec:read(math.min(65536, dec.frames - total)) - if n == 0 then - break - end - buffer.copy(a.samples, total * ch * 4, pcm, 0, n * ch * 4) - total += n - end - if total < dec.frames then -- a truncated file: keep what decoded - local s = buffer.create(total * ch * 4) - buffer.copy(s, 0, a.samples, 0, total * ch * 4) - a.samples = s - a.frames = total - end - a.tags = dec.tags - a.meta.source = { format = "opus", channels = dec.sourceChannels, preSkip = dec.preSkip, vendor = dec.vendor, comments = dec.comments, mappingFamily = dec.head.mappingFamily, inputSampleRate = dec.head.inputSampleRate } - return a, nil + return Pcm.drain(dec, { format = "opus", channels = dec.sourceChannels, preSkip = dec.preSkip, vendor = dec.vendor, comments = dec.comments, mappingFamily = dec.head.mappingFamily, inputSampleRate = dec.head.inputSampleRate }) end -- ------------------------------------------------------------------------------------------------ encode diff --git a/src/Formats/audio/vorbis/init.luau b/src/Formats/audio/vorbis/init.luau index 0cc48bc..8081e1c 100644 --- a/src/Formats/audio/vorbis/init.luau +++ b/src/Formats/audio/vorbis/init.luau @@ -93,28 +93,7 @@ function Vorbis.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err. if not dec then return nil, err end - local d = dec :: any - local ch = d.channels - local parts, total = {}, 0 - while true do - local b, n = d:read(65536) - if n == 0 then - break - end - local copy = buffer.create(n * ch * 4) - buffer.copy(copy, 0, b, 0, n * ch * 4) - table.insert(parts, copy) - total += n - end - local a = Types.Audio.new(d.sampleRate, ch, total) - local o = 0 - for _, p in parts do - buffer.copy(a.samples, o, p) - o += buffer.len(p) - end - a.tags = d.tags - a.meta.source = d.source - return a, nil + return Pcm.drain(dec) end -- ------------------------------------------------------------------------------------------------ encode diff --git a/src/Formats/audio/wav/init.luau b/src/Formats/audio/wav/init.luau index ed5d071..1c1f60b 100644 --- a/src/Formats/audio/wav/init.luau +++ b/src/Formats/audio/wav/init.luau @@ -18,6 +18,7 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") +local Pcm = require("@formats/codecs/Pcm") local Riff = require("@formats/containers/Riff") local Codecs = require("@formats/audio/wav/Codecs") @@ -27,7 +28,7 @@ local Wav = { category = "audio", extensions = { "wav", "wave", "rf64", "bw64" }, mime = { "audio/wav", "audio/x-wav", "audio/wave", "audio/vnd.wave" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Riff" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Riff", "codecs/Pcm" }, caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, rf64 = true }, } @@ -170,23 +171,14 @@ function Wav.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err if not dec then return nil, err end - local a = Types.Audio.new(dec.sampleRate, dec.channels, dec.frames) - local _, n = dec:read(dec.frames, a.samples) - if n < dec.frames then - local s = buffer.create(n * dec.channels * 4) - buffer.copy(s, 0, a.samples, 0, n * dec.channels * 4) - a.samples, a.frames = s, n - end - a.tags = dec.tags - a.meta.source = { + return Pcm.drain(dec, { format = "wav", codec = dec.format, bitDepth = dec.bitsPerSample, container = dec.container, channelMask = dec.channelMask, truncated = dec.truncated, - } - return a, nil + }) end -- ------------------------------------------------------------------------------------------------ encode diff --git a/src/Formats/cad/step/init.luau b/src/Formats/cad/step/init.luau index 1062a7a..d490f0c 100644 --- a/src/Formats/cad/step/init.luau +++ b/src/Formats/cad/step/init.luau @@ -22,6 +22,7 @@ -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") +local Sniff = require("@formats/core/Sniff") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") local Parse = require("@formats/cad/step/Parse") @@ -34,7 +35,7 @@ local Step = { category = "cad", extensions = { "step", "stp", "p21" }, mime = { "model/step", "application/step", "application/p21" }, - deps = { "core/Err", "core/Bytes", "Types" }, + deps = { "core/Err", "core/Bytes", "Types", "core/Sniff" }, caps = { decode = true, encode = true, complexEntities = true, sections = true, brep = "plugin", tessellate = "plugin" }, } @@ -83,10 +84,7 @@ Step.schemaOf = schemaOf -- ------------------------------------------------------------------------------------------------ sniff function Step.sniff(r: Bytes.Reader): number - local head = r:peek(256) - if string.sub(head, 1, 3) == "\239\187\191" then - head = string.sub(head, 4) - end + local head = Sniff.text(r, 256) head = string.gsub(head, "^%s*/%*.-%*/", "") if string.find(head, "^%s*ISO%-10303%-21%s*;") then return 1 diff --git a/src/Formats/codecs/Brotli/init.luau b/src/Formats/codecs/Brotli/init.luau index 2fd2bb1..9d50131 100644 --- a/src/Formats/codecs/Brotli/init.luau +++ b/src/Formats/codecs/Brotli/init.luau @@ -86,16 +86,9 @@ function Brotli.decompress(buf: buffer | string, offset: number?, length: number end local out, size, consumed = Decode.decompress(b, o, l, maxBytes, S, large) if not out then - local msg = tostring(size) - local code = Err.CORRUPT - if string.find(msg, "truncated", 1, true) then - code = Err.TRUNCATED - elseif string.sub(msg, 1, 6) == "limit:" then - code = Err.LIMIT - elseif string.sub(msg, 1, 12) == "unsupported:" then - code = Err.UNSUPPORTED - end - return nil, Err.new(code, "brotli: " .. msg, o) + local e = Err.from(size, o) + e.message = "brotli: " .. e.message + return nil, e end local res = out if buffer.len(out) ~= size then diff --git a/src/Formats/codecs/Bzip2/init.luau b/src/Formats/codecs/Bzip2/init.luau index c9a2584..86c72db 100644 --- a/src/Formats/codecs/Bzip2/init.luau +++ b/src/Formats/codecs/Bzip2/init.luau @@ -19,14 +19,6 @@ export type Options = { maxBytes: number?, -- refuse output larger than this (default 2^30) } -local KINDS = { - truncated = Err.TRUNCATED, - corrupt = Err.CORRUPT, - checksum = Err.CHECKSUM, - limit = Err.LIMIT, - unsupported = Err.UNSUPPORTED, -} - -- decompress(buf, offset?, length?, opts?) -> buffer, consumedEnd | nil, Err function Bzip2.decompress(buf: buffer | string, offset: number?, length: number?, opts: Options?): (buffer?, any) local b, o, l, aerr = Bytes.span("Bzip2.decompress", buf, offset, length) @@ -39,7 +31,7 @@ function Bzip2.decompress(buf: buffer | string, offset: number?, length: number? end local out, nOut, consumed = Decode.decode(b, o, o + l, maxBytes) if not out then - return nil, Err.new(KINDS[consumed] or Err.CORRUPT, "bzip2: " .. tostring(nOut), o) + return nil, Err.from("bzip2: " .. tostring(nOut), o, consumed) end local res = out if buffer.len(out) ~= nOut then diff --git a/src/Formats/codecs/Jpeg/init.luau b/src/Formats/codecs/Jpeg/init.luau index 3163222..de75b4c 100644 --- a/src/Formats/codecs/Jpeg/init.luau +++ b/src/Formats/codecs/Jpeg/init.luau @@ -72,8 +72,6 @@ export type Info = { avi1: number?, -- the AVI1 field polarity, when the segment comes before the frame header } -local CODES = { corrupt = Err.CORRUPT, unsupported = Err.UNSUPPORTED, limit = Err.LIMIT, truncated = Err.TRUNCATED, arg = Err.ARG } - local function range(buf: buffer, off: number?, len: number?): (number, number) local n = buffer.len(buf) local o = math.clamp(math.floor(tonumber(off) or 0), 0, n) @@ -87,7 +85,7 @@ local function parse(buf: buffer, o: number, l: number, opts: any, headerOnly: b return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(st)) end if not st then - return nil, Err.new(CODES[code :: string] or Err.CORRUPT, msg or "decode failed", o) + return nil, Err.from(msg or "decode failed", o, code) end return st, nil end @@ -187,7 +185,7 @@ local function decodeOne(buf: buffer, o: number, l: number, opts: DecodeOptions? return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(w)) end if not w then - return nil, Err.new(CODES[h :: string] or Err.CORRUPT, tostring(px), o) + return nil, Err.from(px, o, h) end space = sp if opts and opts.orient then diff --git a/src/Formats/codecs/Pcm/init.luau b/src/Formats/codecs/Pcm/init.luau index ab98e26..6faadec 100644 --- a/src/Formats/codecs/Pcm/init.luau +++ b/src/Formats/codecs/Pcm/init.luau @@ -150,6 +150,26 @@ function Pcm.collect(src: Source, maxFrames: number?): (Types.Audio?, Err.Err?) return a, nil end +-- drain(dec, source?, maxFrames?) -> Types.Audio | nil, Err: a format's decode() through its open(): every frame of +-- the Decoder (dec.frames is only a hint: short or long streams keep what decodes), dec.tags, meta.source = source +-- (default dec.source). A decoder that recorded a failure in dec.error (an Err) fails the drain. +function Pcm.drain(dec: any, source: { [string]: any }?, maxFrames: number?): (Types.Audio?, Err.Err?) + local src, err = Pcm.source(dec) + if not src then + return nil, err + end + local a, cerr = Pcm.collect(src, maxFrames) + if not a then + return nil, cerr + end + if Err.is(dec.error) then + return nil, dec.error + end + a.tags = dec.tags or {} + a.meta.source = source or dec.source + return a, nil +end + -- ------------------------------------------------------------------------------------------------ decoders -- rawDecoder(buf, offset, frames, channels, sampleRate, fmt, tags?) -> Types.Decoder | nil, Err.ARG: a streaming -- decoder over frames * channels samples of fmt at buf[offset] (the caller has checked the range is inside buf) diff --git a/src/Formats/codecs/Zstd/init.luau b/src/Formats/codecs/Zstd/init.luau index 5a1c5f3..2d9cb04 100644 --- a/src/Formats/codecs/Zstd/init.luau +++ b/src/Formats/codecs/Zstd/init.luau @@ -21,14 +21,6 @@ export type Options = { verify: boolean?, -- check the content checksum when a frame has one (default true) } -local CODES: { [string]: string } = { - TRUNCATED = Err.TRUNCATED, - CORRUPT = Err.CORRUPT, - CHECKSUM = Err.CHECKSUM, - UNSUPPORTED = Err.UNSUPPORTED, - LIMIT = Err.LIMIT, -} - -- magic numbers: a zstd frame, and skippable frames (0x184D2A50 .. 0x184D2A5F) Zstd.MAGIC = "\40\181\47\253" @@ -56,7 +48,7 @@ function Zstd.decompress(buf: buffer | string, offset: number?, length: number?, local verify = not (opts and opts.verify == false) local out, len, consumed, at = Decode.decompress(b, o, o + l, maxBytes, verify) if not out then - return nil, Err.new(CODES[len] or Err.CORRUPT, tostring(consumed), at) + return nil, Err.from(consumed, at, len) end if buffer.len(out) ~= len then local r = buffer.create(len) diff --git a/src/Formats/core/Bits.luau b/src/Formats/core/Bits.luau index e2d1fa1..ca79f13 100644 --- a/src/Formats/core/Bits.luau +++ b/src/Formats/core/Bits.luau @@ -12,6 +12,8 @@ -- local br = Bits.lsbReader(buf, offset?, length?) -- or Bits.msbReader -- local v = br:read(5); if br.err then return nil, br.err end -- local bw = Bits.msbWriter(); bw:write(0b101, 3); local out = bw:finish() +-- local w = { buf = buffer.create(n), pos = 0, acc = 0, cnt = 0 }; Bits.msbPut(w, v, nbits) -- encoders' fast path +-- (a plain record the caller sizes / grows itself: MP3, MP2 and FLAC frames) local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") @@ -276,6 +278,27 @@ function MsbW.finish(self: any): buffer return self.out:finish() end +-- msbPut(w, v, n): append the low n bits (n <= 32) of the non-negative integer v to the record w = { buf, pos, acc, +-- cnt }, MSB first. No growth: the caller keeps buf large enough (whole bytes go to buf[pos]; acc holds cnt < 8 bits). +export type RawWriter = { buf: buffer, pos: number, acc: number, cnt: number } +function Bits.msbPut(w: RawWriter, v: number, n: number) + if n == 0 then + return + end + local acc = w.acc * POW[n + 1] + v + local cnt = w.cnt + n + local b, p = w.buf, w.pos + while cnt >= 8 do + cnt -= 8 + local m = POW[cnt + 1] + local byte = floor(acc / m) + buffer.writeu8(b, p, byte) + p += 1 + acc -= byte * m + end + w.acc, w.cnt, w.pos = acc, cnt, p +end + -- lsbWriter(capacity?) / msbWriter(capacity?) -> BitWriter function Bits.lsbWriter(capacity: number?): BitWriter return setmetatable({ out = Bytes.writer(capacity), acc = 0, cnt = 0 }, LsbW) :: any diff --git a/src/Formats/core/Err.luau b/src/Formats/core/Err.luau index 80b8373..784a545 100644 --- a/src/Formats/core/Err.luau +++ b/src/Formats/core/Err.luau @@ -38,6 +38,42 @@ function Err.new(code: string, message: string, offset: number?): Err return setmetatable({ code = code, message = message, offset = offset, format = nil :: string? }, Meta) :: any end +-- the kinds a private submodule may report: Err codes in either case ("truncated", "CORRUPT", ...) +local KIND: { [string]: string } = {} +for _, c in { "TRUNCATED", "CORRUPT", "CHECKSUM", "UNSUPPORTED", "LIMIT", "ARG", "IO", "UNKNOWN_FORMAT" } do + KIND[c] = c + KIND[string.lower(c)] = c +end + +-- from(message, offset?, kind?) -> Err: the error plumbing between a private submodule (which returns +-- nil / false, "message"[, kind]) and the contract. kind names the code ("truncated", "LIMIT", ...); without it the +-- message decides: a "<code>: ..." prefix ("limit: ...", "unsupported: ...") names the code and is dropped; +-- "...truncated..." / "...past the end" / "...runs past..." -> TRUNCATED; "unsupported..." -> UNSUPPORTED; +-- "checksum..." -> CHECKSUM; anything else CORRUPT. An Err passes +-- through unchanged. +function Err.from(message: any, offset: number?, kind: string?): Err + if Err.is(message) then + return message + end + local msg = if message == nil then "failed" else tostring(message) + local code = kind and KIND[kind] + if not code then + local head, rest = string.match(msg, "^(%a+):%s*(.*)$") + if head and KIND[head] then + code, msg = KIND[head], rest :: string + elseif string.find(msg, "truncated", 1, true) or string.find(msg, "past the end", 1, true) or string.find(msg, "runs past", 1, true) then + code = Err.TRUNCATED + elseif string.find(msg, "^unsupported") then + code = Err.UNSUPPORTED + elseif string.find(msg, "^checksum") then + code = Err.CHECKSUM + else + code = Err.CORRUPT + end + end + return Err.new(code, msg, offset) +end + -- is(v) -> true when v is an Err function Err.is(v: any): boolean return type(v) == "table" and getmetatable(v) == Meta diff --git a/src/Formats/core/Sniff.luau b/src/Formats/core/Sniff.luau new file mode 100644 index 0000000..c849e1a --- /dev/null +++ b/src/Formats/core/Sniff.luau @@ -0,0 +1,36 @@ +--!strict +-- core/Sniff: helpers for the formats' sniff functions (which return 0..1 from the first bytes, never consuming and +-- never throwing): magic comparison and the start of a text file without its UTF-8 byte order mark. +-- +-- function Qoi.sniff(r) return Sniff.magic(r, "qoif") end -- 1 or 0 +-- function Gz.sniff(r) return Sniff.magic(r, "\31\139\8", 0, 0.9) end -- a custom score +-- local head = Sniff.text(r, 64) -- the first 64 bytes, BOM dropped +-- local head = Sniff.text(r, 512, true) -- ... and leading whitespace too +-- local text = Sniff.dropBom(whole) -- decoders: the BOM off a whole file +local Sniff = {} + +type Peeker = { peek: (any, number, number?) -> string } + +-- magic(r, s, at?, score?) -> score (default 1) when the bytes at offset at (default 0) are s, else 0 +function Sniff.magic(r: Peeker, s: string, at: number?, score: number?): number + return if r:peek(#s, at) == s then score or 1 else 0 +end + +-- dropBom(s) -> s without a leading UTF-8 byte order mark (for decoders reading a whole text file) +function Sniff.dropBom(s: string): string + return if string.sub(s, 1, 3) == "\239\187\191" then string.sub(s, 4) else s +end + +-- text(r, n, trim?) -> up to n bytes from the start without a UTF-8 BOM (and leading whitespace when trim) +function Sniff.text(r: Peeker, n: number, trim: boolean?): string + local s = r:peek(n) + if string.sub(s, 1, 3) == "\239\187\191" then + s = string.sub(s, 4) + end + if trim then + s = string.match(s, "^%s*(.*)$") :: string + end + return s +end + +return Sniff diff --git a/src/Formats/data/csv/init.luau b/src/Formats/data/csv/init.luau index 0e57eea..8bab313 100644 --- a/src/Formats/data/csv/init.luau +++ b/src/Formats/data/csv/init.luau @@ -8,6 +8,7 @@ -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") +local Sniff = require("@formats/core/Sniff") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") local Json = require("@formats/codecs/Json") @@ -18,7 +19,7 @@ local Csv = { category = "data", extensions = { "csv", "tsv" }, mime = { "text/csv", "text/tab-separated-values" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Json" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Json", "core/Sniff" }, caps = { decode = true, encode = true, header = true }, } @@ -175,9 +176,7 @@ end function Csv.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) local s = buffer.readstring(r.buf, r.base, r.limit - r.base) - if sub(s, 1, 3) == "\239\187\191" then - s = sub(s, 4) - end + s = Sniff.dropBom(s) local rows, err = Csv.parse(s, opts) if not rows then return nil, err diff --git a/src/Formats/data/ini/init.luau b/src/Formats/data/ini/init.luau index 816bd6a..14a94c8 100644 --- a/src/Formats/data/ini/init.luau +++ b/src/Formats/data/ini/init.luau @@ -9,6 +9,7 @@ -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") +local Sniff = require("@formats/core/Sniff") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") local Json = require("@formats/codecs/Json") @@ -19,7 +20,7 @@ local Ini = { category = "data", extensions = { "ini", "cfg", "conf", "inf", "desktop" }, mime = { "text/plain" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Json" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Json", "core/Sniff" }, caps = { decode = true, encode = true, ordered = true }, } @@ -73,9 +74,7 @@ end function Ini.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) local o: DecodeOptions = opts or {} local s = buffer.readstring(r.buf, r.base, r.limit - r.base) - if string.sub(s, 1, 3) == "\239\187\191" then - s = string.sub(s, 4) - end + s = Sniff.dropBom(s) local root = Types.object() local cur = root local lastKey: string? = nil diff --git a/src/Formats/data/json/init.luau b/src/Formats/data/json/init.luau index bf75d5f..78a4df7 100644 --- a/src/Formats/data/json/init.luau +++ b/src/Formats/data/json/init.luau @@ -5,6 +5,7 @@ -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") +local Sniff = require("@formats/core/Sniff") local Bytes = require("@formats/core/Bytes") local Json = require("@formats/codecs/Json") @@ -14,7 +15,7 @@ local JsonFormat = { category = "data", extensions = { "json", "jsonl", "ndjson", "geojson" }, mime = { "application/json", "application/x-ndjson" }, - deps = { "core/Err", "core/Bytes", "codecs/Json" }, + deps = { "core/Err", "core/Bytes", "codecs/Json", "core/Sniff" }, caps = { decode = true, encode = true, ordered = true, streaming = true }, } @@ -27,10 +28,7 @@ export type EncodeOptions = Json.EncodeOptions & { -- ------------------------------------------------------------------------------------------------ sniff function JsonFormat.sniff(r: Bytes.Reader): number - local head = r:peek(64) - if string.sub(head, 1, 3) == "\239\187\191" then - head = string.sub(head, 4) - end + local head = Sniff.text(r, 64) local first = string.match(head, "^[ \t\r\n]*(.)") if first == "{" then local nxt = string.match(head, "^[^{]*{[ \t\r\n]*(.)") diff --git a/src/Formats/data/msgpack/init.luau b/src/Formats/data/msgpack/init.luau index ecd96f9..aa624b8 100644 --- a/src/Formats/data/msgpack/init.luau +++ b/src/Formats/data/msgpack/init.luau @@ -40,7 +40,7 @@ function Msgpack.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) while not r:eof() do local v, e, at = Codec.decode(r, o) if e then - return nil, Err.new(if string.find(e, "truncated", 1, true) or string.find(e, "past the end", 1, true) then Err.TRUNCATED else Err.CORRUPT, e, at) + return nil, Err.from(e, at) end table.insert(out, v) end diff --git a/src/Formats/data/plist/init.luau b/src/Formats/data/plist/init.luau index aafd126..6f46277 100644 --- a/src/Formats/data/plist/init.luau +++ b/src/Formats/data/plist/init.luau @@ -143,7 +143,7 @@ function Plist.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) if len >= 8 and buffer.readstring(r.buf, r.base, 6) == "bplist" then local v, e = Binary.decode(r.buf, r.base, len, opts) if e then - return nil, Err.new(if string.find(e, "truncated", 1, true) or string.find(e, "past the end", 1, true) then Err.TRUNCATED else Err.CORRUPT, e) + return nil, Err.from(e) end return v, nil end diff --git a/src/Formats/data/xml/init.luau b/src/Formats/data/xml/init.luau index c992418..6479ec5 100644 --- a/src/Formats/data/xml/init.luau +++ b/src/Formats/data/xml/init.luau @@ -5,6 +5,7 @@ -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") +local Sniff = require("@formats/core/Sniff") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") local Xml = require("@formats/codecs/Xml") @@ -15,7 +16,7 @@ local XmlFormat = { category = "data", extensions = { "xml", "xsd", "xsl", "xslt", "rss", "atom", "xhtml" }, mime = { "application/xml", "text/xml" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "core/Sniff" }, caps = { decode = true, encode = true, namespaces = true, streaming = true }, } @@ -24,10 +25,7 @@ export type EncodeOptions = Xml.EncodeOptions -- ------------------------------------------------------------------------------------------------ sniff function XmlFormat.sniff(r: Bytes.Reader): number - local head = r:peek(64) - if string.sub(head, 1, 3) == "\239\187\191" then - head = string.sub(head, 4) - end + local head = Sniff.text(r, 64) if string.match(head, "^<%?xml[ \t\r\n]") or string.sub(head, 1, 4) == "\255\254<\0" or string.sub(head, 1, 4) == "\254\255\0<" then return 0.5 end diff --git a/src/Formats/font/bmfont/init.luau b/src/Formats/font/bmfont/init.luau index f70cf94..617033a 100644 --- a/src/Formats/font/bmfont/init.luau +++ b/src/Formats/font/bmfont/init.luau @@ -191,8 +191,7 @@ function Bmfont.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end end if not d then - local code = if err and (string.find(err, "truncated", 1, true) or string.find(err, "past the end", 1, true)) then Err.TRUNCATED elseif err and string.find(err, "unsupported", 1, true) then Err.UNSUPPORTED else Err.CORRUPT - return nil, Err.new(code, err or "bad descriptor", r.base) + return nil, Err.from(err or "bad descriptor", r.base) end local f = face(d, variant) if opts and type(opts.pages) == "table" then diff --git a/src/Formats/font/woff2/init.luau b/src/Formats/font/woff2/init.luau index 1d368b4..1e697cb 100644 --- a/src/Formats/font/woff2/init.luau +++ b/src/Formats/font/woff2/init.luau @@ -24,8 +24,6 @@ export type DecodeOptions = { } -- ------------------------------------------------------------------------------------------------ constants -local CODES = { truncated = Err.TRUNCATED, corrupt = Err.CORRUPT, unsupported = Err.UNSUPPORTED, limit = Err.LIMIT } - -- ------------------------------------------------------------------------------------------------ sniff function Woff2.sniff(r: Bytes.Reader): number return if r:peek(4) == "wOF2" then 1 else 0 @@ -38,7 +36,7 @@ function Woff2.sfnt(r: Bytes.Reader, opts: DecodeOptions?): (buffer?, Err.Err?) local at = r.base local out, msg, code = Rebuild.sfnt(r, maxBytes) if not out then - return nil, Err.new(CODES[code or "corrupt"] or Err.CORRUPT, msg or "rebuild failed", at) + return nil, Err.from(msg or "rebuild failed", at, code or "corrupt") end return out, nil end diff --git a/src/Formats/model/fbx/init.luau b/src/Formats/model/fbx/init.luau index f20cd90..bf8bfcf 100644 --- a/src/Formats/model/fbx/init.luau +++ b/src/Formats/model/fbx/init.luau @@ -98,18 +98,7 @@ local function fetcher(opts: DecodeOptions?): Read.Fetch end end -local function toErr(msg: any, offset: number?): Err.Err - local s = tostring(msg) - local code = Err.CORRUPT - if string.sub(s, 1, 12) == "unsupported:" then - code, s = Err.UNSUPPORTED, string.sub(s, 13) - elseif string.sub(s, 1, 6) == "limit:" then - code, s = Err.LIMIT, string.sub(s, 7) - elseif string.find(s, "truncated", 1, true) or string.find(s, "runs past", 1, true) then - code = Err.TRUNCATED - end - return Err.new(code, s, offset) -end +local toErr = Err.from -- tree(r, opts?) -> the node tree { name = "", children = { { name, props, children } } }, version, binary | nil, Err. -- Property values: numbers, booleans, strings, buffers (raw), Arrays { array = true, type, count, data = f64 buffer }. diff --git a/src/Formats/model/gltf/init.luau b/src/Formats/model/gltf/init.luau index cf98697..bf14547 100644 --- a/src/Formats/model/gltf/init.luau +++ b/src/Formats/model/gltf/init.luau @@ -17,6 +17,7 @@ -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") +local Sniff = require("@formats/core/Sniff") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") local Json = require("@formats/codecs/Json") @@ -30,7 +31,7 @@ local Gltf = { category = "model", extensions = { "gltf", "glb" }, mime = { "model/gltf+json", "model/gltf-binary" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Json", "core/Base64" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Json", "core/Base64", "core/Sniff" }, caps = { decode = true, encode = true, binary = true, materials = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true }, } @@ -60,7 +61,7 @@ function Gltf.sniff(r: Bytes.Reader): number return 1 end local head = r:peek(1024) - local s = string.gsub(head, "^\239\187\191", "") + local s = Sniff.dropBom(head) if string.find(s, "^%s*{") and string.find(s, "\"asset\"", 1, true) then return 0.9 end diff --git a/src/Formats/playlist/m3u/init.luau b/src/Formats/playlist/m3u/init.luau index d023619..4e3acb4 100644 --- a/src/Formats/playlist/m3u/init.luau +++ b/src/Formats/playlist/m3u/init.luau @@ -14,6 +14,7 @@ -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") +local Sniff = require("@formats/core/Sniff") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") local Url = require("@formats/codecs/Url") @@ -25,7 +26,7 @@ local M3u = { category = "playlist", extensions = { "m3u", "m3u8" }, mime = { "audio/x-mpegurl", "audio/mpegurl", "application/vnd.apple.mpegurl", "application/x-mpegurl" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Url", "codecs/Text" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Url", "codecs/Text", "core/Sniff" }, caps = { decode = true, encode = true, hls = true }, } @@ -141,10 +142,7 @@ end -- ------------------------------------------------------------------------------------------------ sniff function M3u.sniff(r: Bytes.Reader): number - local s = r:peek(512) - if string.sub(s, 1, 3) == "\239\187\191" then - s = string.sub(s, 4) - end + local s = Sniff.text(r, 512) s = (string.match(s, "^%s*(.*)$") :: string) if string.sub(s, 1, 7) == "#EXTM3U" then return 0.95 diff --git a/src/Formats/playlist/pls/init.luau b/src/Formats/playlist/pls/init.luau index 0951336..676f302 100644 --- a/src/Formats/playlist/pls/init.luau +++ b/src/Formats/playlist/pls/init.luau @@ -10,6 +10,7 @@ -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") +local Sniff = require("@formats/core/Sniff") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") local Url = require("@formats/codecs/Url") @@ -21,7 +22,7 @@ local Pls = { category = "playlist", extensions = { "pls" }, mime = { "audio/x-scpls", "audio/scpls" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Url", "codecs/Text" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Url", "codecs/Text", "core/Sniff" }, caps = { decode = true, encode = true }, } @@ -75,10 +76,7 @@ end -- ------------------------------------------------------------------------------------------------ sniff function Pls.sniff(r: Bytes.Reader): number - local s = r:peek(64) - if string.sub(s, 1, 3) == "\239\187\191" then - s = string.sub(s, 4) - end + local s = Sniff.text(r, 64) local first = string.match(s, "^%s*([^\r\n]*)") return if first and string.lower(Text.trim(first)) == "[playlist]" then 0.95 else 0 end diff --git a/src/Formats/subtitle/ass/init.luau b/src/Formats/subtitle/ass/init.luau index 2be1b4f..be7b620 100644 --- a/src/Formats/subtitle/ass/init.luau +++ b/src/Formats/subtitle/ass/init.luau @@ -12,6 +12,7 @@ -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") +local Sniff = require("@formats/core/Sniff") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") @@ -21,7 +22,7 @@ local Ass = { category = "subtitle", extensions = { "ass", "ssa" }, mime = { "text/x-ssa", "text/x-ass" }, - deps = { "core/Err", "core/Bytes", "Types" }, + deps = { "core/Err", "core/Bytes", "Types", "core/Sniff" }, caps = { decode = true, encode = true, styles = true }, } @@ -144,10 +145,7 @@ end -- ------------------------------------------------------------------------------------------------ sniff function Ass.sniff(r: Bytes.Reader): number - local head = r:peek(64) - if string.sub(head, 1, 3) == "\239\187\191" then - head = string.sub(head, 4) - end + local head = Sniff.text(r, 64) if string.match(head, "^%s*%[[Ss]cript [Ii]nfo%]") then return 1 end @@ -167,9 +165,7 @@ function Ass.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Subtitles?, E if string.find(s, "\0", 1, true) then return nil, Err.new(Err.CORRUPT, "binary data (NUL bytes) in a text format") end - if string.sub(s, 1, 3) == "\239\187\191" then - s = string.sub(s, 4) - end + s = Sniff.dropBom(s) s = string.gsub(s, "\r\n", "\n") s = string.gsub(s, "\r", "\n") local subs = Types.Subtitles.new() diff --git a/src/Formats/subtitle/srt/init.luau b/src/Formats/subtitle/srt/init.luau index 67ae65d..c3ab1fd 100644 --- a/src/Formats/subtitle/srt/init.luau +++ b/src/Formats/subtitle/srt/init.luau @@ -9,6 +9,7 @@ -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") +local Sniff = require("@formats/core/Sniff") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") @@ -18,7 +19,7 @@ local Srt = { category = "subtitle", extensions = { "srt" }, mime = { "application/x-subrip", "text/srt" }, - deps = { "core/Err", "core/Bytes", "Types" }, + deps = { "core/Err", "core/Bytes", "Types", "core/Sniff" }, caps = { decode = true, encode = true, styles = false }, } @@ -38,9 +39,7 @@ local function text(r: Bytes.Reader): string? if string.find(s, "\0", 1, true) then return nil end - if string.sub(s, 1, 3) == "\239\187\191" then - s = string.sub(s, 4) - end + s = Sniff.dropBom(s) s = string.gsub(s, "\r\n", "\n") s = string.gsub(s, "\r", "\n") return s @@ -63,10 +62,7 @@ end -- ------------------------------------------------------------------------------------------------ sniff function Srt.sniff(r: Bytes.Reader): number - local head = r:peek(512) - if string.sub(head, 1, 3) == "\239\187\191" then - head = string.sub(head, 4) - end + local head = Sniff.text(r, 512) head = string.gsub(head, "\r", "\n") local first, second = string.match(head, "^%s*([^\n]*)\n([^\n]*)") if first and string.match(first, "^%d+%s*$") and second and timing(second) then diff --git a/src/Formats/subtitle/vtt/init.luau b/src/Formats/subtitle/vtt/init.luau index 1592219..a35668f 100644 --- a/src/Formats/subtitle/vtt/init.luau +++ b/src/Formats/subtitle/vtt/init.luau @@ -8,6 +8,7 @@ -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") +local Sniff = require("@formats/core/Sniff") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") @@ -17,7 +18,7 @@ local Vtt = { category = "subtitle", extensions = { "vtt", "webvtt" }, mime = { "text/vtt" }, - deps = { "core/Err", "core/Bytes", "Types" }, + deps = { "core/Err", "core/Bytes", "Types", "core/Sniff" }, caps = { decode = true, encode = true, styles = true }, } @@ -64,10 +65,7 @@ end -- ------------------------------------------------------------------------------------------------ sniff function Vtt.sniff(r: Bytes.Reader): number - local head = r:peek(10) - if string.sub(head, 1, 3) == "\239\187\191" then - head = string.sub(head, 4) - end + local head = Sniff.text(r, 10) if string.sub(head, 1, 6) == "WEBVTT" then local c = string.sub(head, 7, 7) if c == "" or c == " " or c == "\t" or c == "\n" or c == "\r" then @@ -90,9 +88,7 @@ function Vtt.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Subtitles?, E if string.find(s, "\0", 1, true) then return nil, Err.new(Err.CORRUPT, "binary data (NUL bytes) in a text format") end - if string.sub(s, 1, 3) == "\239\187\191" then - s = string.sub(s, 4) - end + s = Sniff.dropBom(s) s = string.gsub(s, "\r\n", "\n") s = string.gsub(s, "\r", "\n") local lines = string.split(s, "\n") diff --git a/src/Formats/vector/svg/init.luau b/src/Formats/vector/svg/init.luau index 0ec3be9..811f89a 100644 --- a/src/Formats/vector/svg/init.luau +++ b/src/Formats/vector/svg/init.luau @@ -13,6 +13,7 @@ -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") +local Sniff = require("@formats/core/Sniff") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") local Xml = require("@formats/codecs/Xml") @@ -26,7 +27,7 @@ local Svg = { category = "vector", extensions = { "svg" }, mime = { "image/svg+xml" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "codecs/Raster", "codecs/Blend" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "codecs/Raster", "codecs/Blend", "core/Sniff" }, caps = { decode = true, encode = true, rasterize = true, text = false }, } @@ -38,10 +39,7 @@ export type RasterizeOptions = Render.Options -- ------------------------------------------------------------------------------------------------ sniff function Svg.sniff(r: Bytes.Reader): number - local h = r:peek(4096) - if string.sub(h, 1, 3) == "\239\187\191" then - h = string.sub(h, 4) - end + local h = Sniff.text(r, 4096) if not string.match(h, "^%s*<") then return 0 end diff --git a/src/Formats/vector/tiled/init.luau b/src/Formats/vector/tiled/init.luau index 114ca33..e3a34aa 100644 --- a/src/Formats/vector/tiled/init.luau +++ b/src/Formats/vector/tiled/init.luau @@ -12,6 +12,7 @@ -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") +local Sniff = require("@formats/core/Sniff") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") local Xml = require("@formats/codecs/Xml") @@ -25,7 +26,7 @@ local Tiled = { category = "vector", extensions = { "tmx", "tmj", "tsx", "tsj" }, mime = { "application/x-tiled-tmx", "application/x-tiled-tmj" }, - deps = { "core/Err", "core/Bytes", "core/Base64", "Types", "codecs/Xml", "codecs/Json", "codecs/Deflate" }, + deps = { "core/Err", "core/Bytes", "core/Base64", "Types", "codecs/Xml", "codecs/Json", "codecs/Deflate", "core/Sniff" }, caps = { decode = true, encode = true, tilesets = true, infinite = true }, } @@ -42,10 +43,7 @@ export type EncodeOptions = { -- ------------------------------------------------------------------------------------------------ sniff local function head(r: Bytes.Reader): string - local h = r:peek(1024) - if string.sub(h, 1, 3) == "\239\187\191" then - h = string.sub(h, 4) - end + local h = Sniff.text(r, 1024) return h end diff --git a/tools/bench.luau b/tools/bench.luau index 451d9b4..f6d624f 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -22,6 +22,19 @@ local Types = require("@formats/Types") local runtime = if (_G :: any).jit ~= nil then "luajit" else "luau" +-- jitTune(on): LuaJIT's trace limits as host/init.luau sets them for the api (on) or LuaJIT's defaults (off); the +-- codec sections that care print both +local function jitTune(on: boolean) + local jit = (_G :: any).jit + if jit and type(jit.opt) == "table" then + if on then + jit.opt.start("maxtrace=8000", "maxmcode=65536") + else + jit.opt.start("maxtrace=1000", "maxmcode=8192") + end + end +end + local function bench(label: string, n: number, bytes: number, f: () -> ()) f() local dt = math.huge -- best of n: the machine is shared, the mean is noisy @@ -935,19 +948,29 @@ do Jpeg.encode(img, { quality = 85 }) end) end - for _, s in M1 do - local file = Base64.decode(s.file) :: buffer - for _, rgba in { false, true } do - fps(string.format("mpeg1 decode %s %dx%d", if rgba then "rgba" else "yuv", s.width, s.height), 3, #s.units, function() - local dec = Mpeg1.new({ reorder = true, rgba = rgba }) - for i, u in s.units do - dec:decode(file, u[1], u[2], i) - end - while dec:flush() do - end - end) + -- (LuaJIT also with the trace limits the api sets, host/init.luau: the default 1000 traces thrash on MPEG-1) + local function mpeg1(tag: string) + for _, s in M1 do + local file = Base64.decode(s.file) :: buffer + for _, rgba in { false, true } do + fps(string.format("mpeg1 decode %s %dx%d%s", if rgba then "rgba" else "yuv", s.width, s.height, tag), 3, #s.units, function() + local dec = Mpeg1.new({ reorder = true, rgba = rgba }) + for i, u in s.units do + dec:decode(file, u[1], u[2], i) + end + while dec:flush() do + end + end) + end end end + jitTune(false) + mpeg1("") + if runtime == "luajit" then + jitTune(true) + mpeg1(" (jit tuned)") + jitTune(false) + end end -- ------------------------------------------------------------------------------------------- ws-video: containers do @@ -1024,10 +1047,12 @@ do print(string.format("%-8s %-30s %8.1f fps", runtime, " (" .. #frames .. " frames)", #frames / dt)) end end + jitTune(false) run("") if runtime == "luajit" then - require("@formats/host") + jitTune(true) run(" (jit tuned)") + jitTune(false) end end do @@ -1045,9 +1070,11 @@ do print(string.format("%-8s %-30s %8.1f fps", runtime, " (" .. #c.frames .. " frames)", #c.frames / dt)) end end + jitTune(false) run("") if runtime == "luajit" then - require("@formats/host") + jitTune(true) run(" (jit tuned)") + jitTune(false) end end diff --git a/tools/fixtures/zstd.py b/tools/fixtures/zstd.py index afaa29c..ce02d59 100644 --- a/tools/fixtures/zstd.py +++ b/tools/fixtures/zstd.py @@ -42,7 +42,7 @@ def generate(ctx): "one": b"a", "short": b"hello, hello, hello zstd world\n", "text": text[:200000], - "random": rng.randbytes(50000), + "random": rng.randbytes(16000), # incompressible: kept small (each case stores it again) "runs": b"abc" * 4000 + b"\0" * 20000 + bytes(range(256)) * 40 + b"z" * 300, "far": (lambda r: r + rng.randbytes(30000) + r)(rng.randbytes(20000)), "binary": bytes(rng.choice(b"\0\0\0\x01\x02\xff ABC") for _ in range(60000)), diff --git a/tools/lint_rules.py b/tools/lint_rules.py index 3c16eea..0131d1a 100644 --- a/tools/lint_rules.py +++ b/tools/lint_rules.py @@ -16,6 +16,9 @@ # extensions, mime, deps, caps (with decode / encode matching the functions), function <X>.sniff, at least # one of decode / encode / open, the section markers in order, and ends with return <X>; it has a test # tests/<category>/<fmt>.luau with a fuzz pass (:fuzz(). +# DUP no copy-pasted code: a function body of DUP_LINES (12) or more code lines whose tokens (comments and +# whitespace dropped, identifiers kept) equal another module's function body fails; move it down to a +# shared module (core / codecs / containers) and call it from both. import os, re, sys ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) @@ -275,5 +278,33 @@ for folder in folders: elif ":fuzz(" not in open(test).read(): bad(test, 0, "CONTRACT: a format test includes the fuzz no-throw pass (t:fuzz(...))") +# ---------------------------------------------------------------------------------------------------- DUP +DUP_LINES = 12 +TOKEN = re.compile(r'"(?:[^"\\]|\\.)*"|\'(?:[^\'\\]|\\.)*\'|\[=*\[.*?\]=*\]|[A-Za-z_][A-Za-z0-9_]*|\d[\w.]*|\S') +FUNC = re.compile(r"^(\s*)(?:local\s+)?function\b") +bodies = {} +for f, lines in text.items(): + for i, line in enumerate(lines): + m = FUNC.match(line) + if not m: + continue + end = re.compile("^" + re.escape(m.group(1)) + r"end\b") + j = i + 1 + while j < len(lines) and not end.match(lines[j]): + j += 1 + body = [code(x).strip() for x in lines[i + 1:j]] + body = [x for x in body if x] + if len(body) < DUP_LINES: + continue + key = " ".join(TOKEN.findall(" ".join(body))) + bodies.setdefault(key, []).append((f, i + 1, line.strip())) +for key, where in bodies.items(): + files_ = {w[0] for w in where} + if len(files_) > 1: + first = where[0] + for f, ln, head in where[1:]: + if f != first[0]: + bad(f, ln, "DUP: `%s` repeats %s:%d (move it to a shared module)" % (head[:60], os.path.relpath(first[0], ROOT), first[1])) + print("\n".join(out)) sys.exit(1 if out else 0) diff --git a/tools/move.py b/tools/move.py new file mode 100644 index 0000000..bcde84d --- /dev/null +++ b/tools/move.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python3 +# Module moves (python3 -I tools/move.py [--dry] old=new ...): moves src/Formats/<old>(.luau | /) to <new> with +# git mv, then rewrites every reference to the module path in the repo: requires ("@formats/old" and +# "@formats/old/Sub"), contract deps ("old"), header comment lines ("-- old: ..." / "-- old/Sub: ..."), fixture +# INPUTS ("src/Formats/old"), docs and comments ("old" as a whole path token). Paths are module paths +# (codecs/Deflate, core/Huffman). Generated files are not edited: rerun tools/gen_registry.py afterwards. +# +# python3 -I tools/move.py codecs/Deflate=codecs/compress/Deflate core/Huffman=codecs/entropy/Huffman +import os, re, subprocess, sys + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +SRC = os.path.join(ROOT, "src", "Formats") +SCAN = ["src", "tests", "tools", "docs", "examples", "README.md", "default.project.json"] +SKIP = {os.path.join("tests", "gen"), os.path.join("tools", "move.py"), "build"} +EXTS = (".luau", ".lua", ".py", ".md", ".json", ".sh") + + +def files(): + for top in SCAN: + p = os.path.join(ROOT, top) + if os.path.isfile(p): + yield p + continue + for d, dirs, fs in os.walk(p): + rel = os.path.relpath(d, ROOT) + dirs[:] = [x for x in dirs if os.path.join(rel, x) not in SKIP and x not in ("build", "__pycache__")] + for f in fs: + q = os.path.join(d, f) + if f.endswith(EXTS) and os.path.relpath(q, ROOT) not in SKIP: + yield q + + +def source(mod): + base = os.path.join(SRC, *mod.split("/")) + if os.path.isdir(base): + return base + if os.path.isfile(base + ".luau"): + return base + ".luau" + return None + + +def main(): + dry = "--dry" in sys.argv + pairs = [a.split("=", 1) for a in sys.argv[1:] if "=" in a] + if not pairs: + print(__doc__ if __doc__ else "usage: move.py old=new ...") + sys.exit(2) + for old, new in pairs: + src = source(old) + if not src: + sys.exit("move.py: no module %s" % old) + dst = os.path.join(SRC, *new.split("/")) + ("" if os.path.isdir(src) else ".luau") + if os.path.exists(dst): + sys.exit("move.py: %s exists" % os.path.relpath(dst, ROOT)) + print("move %s -> %s" % (os.path.relpath(src, ROOT), os.path.relpath(dst, ROOT))) + if not dry: + os.makedirs(os.path.dirname(dst), exist_ok=True) + subprocess.run(["git", "mv", src, dst], cwd=ROOT, check=True) + # a path token: not preceded by a word char or "."; not followed by a word char + subs = [(re.compile(r"(?<![\w.])" + re.escape(old) + r"(?![\w])"), new) for old, new in pairs] + lua_subs = [(re.compile(r"(?<![\w.])formats\." + re.escape(old.replace("/", ".")) + r"(?![\w])"), + "formats." + new.replace("/", ".")) for old, new in pairs] + changed = 0 + for f in files(): + with open(f, encoding="utf-8", errors="surrogateescape") as h: + text = h.read() + out = text + for rx, rep in subs + lua_subs: + out = rx.sub(rep, out) + if out != text: + changed += 1 + if not dry: + with open(f, "w", encoding="utf-8", errors="surrogateescape") as h: + h.write(out) + print("move.py: %d files rewritten%s" % (changed, " (dry run)" if dry else "")) + + +if __name__ == "__main__": + main() From 51b08575c45bb7af104c26cd264c73dfa3b362c0 Mon Sep 17 00:00:00 2001 From: 4DBug <github@bug.tools> Date: Sat, 31 Oct 2026 12:25:03 -0500 Subject: [PATCH 18/22] ws-cleanup: codecs/ grouped by domain; containers/Chunks, codecs/audio/Stream, codecs/image/Pixels, codecs/model/Mat4 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit C2, the hierarchy (tools/move.py, every reference rewritten mechanically): - codecs/compress: Deflate Lzma Zstd Brotli Bzip2 Lzw; codecs/entropy: Huffman (from core) RangeCoder; codecs/image: Jpeg Dct Vp8 Vp8L Yuv Quantize Raster Blend Pixels; codecs/audio: Mdct Aac Alac Pcm Resample VorbisComment Tracker SoundFont Stream; codecs/video: H264 Mpeg1 Video; codecs/text: Json Xml Text Url; codecs/font: TrueType Cff; codecs/model: MeshFlatten Mat4. containers/ stays flat; core/ keeps Bytes Bits Err Crc32 Adler32 Base64 Md5 Input Sniff. - LAYERS lint: codecs must sit in a domain folder; gen_registry lists codecs by domain (docs/FORMATS.md). - Checked: build.py both targets, rojo build of build/roblox, the full suite on both runtimes. C3, generic code out of format folders: - containers/Chunks (new): the chunked-file walker (RIFF / RIFX / IFF / PNG / CAF layouts: endianness, size first, trailer, padding, lenient missing pad, open-ended ids, size hooks). containers/Riff walks with it (RF64 ds64 through the resize hook); image/png, audio/aiff and audio/caf list their chunk handlers over it. - codecs/audio/Stream (new): Stream.packets, the packet-decoder Decoder (read / seek with pre-roll / position, priming and end trimming) that aac, caf and m4a each carried (~70 lines each). - codecs/image/Pixels: image/bmp/Pixels promoted (+ rgb555); image/ico's DIB decoder uses its row loops instead of its own (the AND mask / alpha rule stay ICO's). - codecs/model/Mat4 (new): matrices / quaternions / TRS shared by FBX (Xform keeps only the FBX transform model), Collada (Math keeps only <lookat> / <skew>) and USD (its matrix helpers and general 4x4 inverse); Mat4.mul is Types.Scene.mul. The Collada normal matrix is now the inverse transpose (it was the inverse; same result for the fixtures' bind shapes). - README rewritten (install for Rojo and LÖVE / LuaJIT, quick start per category, F.* and F.ops, host notes: FORMATS_NO_JIT_TUNE, paths, layout); docs/STYLE.md: the codec domains, "what belongs in a format folder" with the shared building blocks and the DUP rule, conventions (WAVE order, lower-case tags, loops, the api hooks decodeImage / encodeImage / openAudio / plugins / resolve, the codecs/video/Video registry), Err.from, the type baseline. New tests: tests/containers/chunks, tests/codecs/mat4. Type baseline 93. --- README.md | 152 +++++++--- docs/API.md | 4 +- docs/FORMATS.md | 80 ++--- docs/STYLE.md | 83 +++++- docs/video.md | 12 +- src/Formats/Registry.luau | 124 ++++---- src/Formats/Types.luau | 6 +- src/Formats/archive/7z/init.luau | 10 +- src/Formats/archive/br/init.luau | 6 +- src/Formats/archive/bz2/init.luau | 8 +- src/Formats/archive/gzip/init.luau | 6 +- src/Formats/archive/xz/init.luau | 6 +- src/Formats/archive/zip/init.luau | 2 +- src/Formats/archive/zst/init.luau | 6 +- src/Formats/audio/aac/init.luau | 98 ++---- src/Formats/audio/aiff/init.luau | 18 +- src/Formats/audio/au/init.luau | 4 +- src/Formats/audio/caf/init.luau | 136 ++------- src/Formats/audio/flac/Encode.luau | 4 +- src/Formats/audio/flac/Meta.luau | 2 +- src/Formats/audio/flac/init.luau | 4 +- src/Formats/audio/m4a/init.luau | 129 ++------ src/Formats/audio/mp3/init.luau | 14 +- src/Formats/audio/opus/Celt.luau | 2 +- src/Formats/audio/opus/CeltEncoder.luau | 6 +- src/Formats/audio/opus/Decoder.luau | 2 +- src/Formats/audio/opus/Encode.luau | 10 +- src/Formats/audio/opus/Mdct.luau | 2 +- src/Formats/audio/opus/Silk.luau | 2 +- src/Formats/audio/opus/init.luau | 12 +- src/Formats/audio/voc/init.luau | 4 +- src/Formats/audio/vorbis/Encode.luau | 8 +- src/Formats/audio/vorbis/Packet.luau | 4 +- src/Formats/audio/vorbis/init.luau | 12 +- src/Formats/audio/wav/init.luau | 4 +- src/Formats/codecs/RangeCoder/init.luau | 13 - .../codecs/{ => audio}/Aac/Decode.luau | 8 +- .../codecs/{ => audio}/Aac/Tables.luau | 2 +- src/Formats/codecs/{ => audio}/Aac/init.luau | 10 +- .../codecs/{ => audio}/Alac/Decode.luau | 2 +- .../codecs/{ => audio}/Alac/Encode.luau | 2 +- src/Formats/codecs/{ => audio}/Alac/init.luau | 8 +- src/Formats/codecs/{ => audio}/Mdct/Fft.luau | 2 +- src/Formats/codecs/{ => audio}/Mdct/init.luau | 8 +- .../codecs/{ => audio}/Pcm/Convert.luau | 2 +- src/Formats/codecs/{ => audio}/Pcm/init.luau | 6 +- .../codecs/{ => audio}/Resample/init.luau | 6 +- .../{ => audio}/SoundFont/Fallback.luau | 4 +- .../codecs/{ => audio}/SoundFont/Parse.luau | 2 +- .../codecs/{ => audio}/SoundFont/Synth.luau | 2 +- .../codecs/{ => audio}/SoundFont/init.luau | 10 +- src/Formats/codecs/audio/Stream.luau | 141 +++++++++ .../codecs/{ => audio}/Tracker/Mixer.luau | 4 +- .../codecs/{ => audio}/Tracker/Pcm.luau | 2 +- .../codecs/{ => audio}/Tracker/Player.luau | 10 +- .../codecs/{ => audio}/Tracker/Tables.luau | 2 +- .../codecs/{ => audio}/Tracker/init.luau | 12 +- .../codecs/{ => audio}/VorbisComment.luau | 4 +- .../codecs/{ => compress}/Brotli/Decode.luau | 2 +- .../codecs/{ => compress}/Brotli/Static.luau | 2 +- .../codecs/{ => compress}/Brotli/init.luau | 14 +- .../codecs/{ => compress}/Bzip2/Decode.luau | 2 +- .../codecs/{ => compress}/Bzip2/init.luau | 6 +- .../{ => compress}/Deflate/Compress.luau | 6 +- .../{ => compress}/Deflate/Inflate.luau | 8 +- .../codecs/{ => compress}/Deflate/init.luau | 8 +- .../codecs/{ => compress}/Lzma/Crc64.luau | 2 +- .../codecs/{ => compress}/Lzma/Decode.luau | 2 +- .../codecs/{ => compress}/Lzma/Filters.luau | 2 +- .../codecs/{ => compress}/Lzma/init.luau | 10 +- .../codecs/{ => compress}/Lzw/init.luau | 2 +- .../codecs/{ => compress}/Zstd/Decode.luau | 4 +- .../codecs/{ => compress}/Zstd/Xxh64.luau | 2 +- .../codecs/{ => compress}/Zstd/init.luau | 6 +- .../{core => codecs/entropy}/Huffman.luau | 4 +- .../{ => entropy}/RangeCoder/Decoder.luau | 2 +- .../{ => entropy}/RangeCoder/Encoder.luau | 4 +- .../codecs/entropy/RangeCoder/init.luau | 13 + src/Formats/codecs/{ => font}/Cff/init.luau | 2 +- .../codecs/{ => font}/TrueType/Glyf.luau | 4 +- .../codecs/{ => font}/TrueType/Tables.luau | 2 +- .../codecs/{ => font}/TrueType/init.luau | 16 +- src/Formats/codecs/{ => image}/Blend.luau | 2 +- src/Formats/codecs/{ => image}/Dct/init.luau | 2 +- .../codecs/{ => image}/Jpeg/Arith.luau | 2 +- .../codecs/{ => image}/Jpeg/Color.luau | 2 +- .../codecs/{ => image}/Jpeg/Decode.luau | 16 +- .../codecs/{ => image}/Jpeg/Encode.luau | 10 +- src/Formats/codecs/{ => image}/Jpeg/Scan.luau | 2 +- .../codecs/{ => image}/Jpeg/Tables.luau | 2 +- src/Formats/codecs/{ => image}/Jpeg/Yuv.luau | 4 +- src/Formats/codecs/{ => image}/Jpeg/init.luau | 10 +- .../{image/bmp => codecs/image}/Pixels.luau | 25 +- .../codecs/{ => image}/Quantize/init.luau | 2 +- src/Formats/codecs/{ => image}/Raster.luau | 4 +- .../codecs/{ => image}/Vp8/Decode.luau | 8 +- .../codecs/{ => image}/Vp8/Predict.luau | 6 +- .../codecs/{ => image}/Vp8/Tables.luau | 2 +- src/Formats/codecs/{ => image}/Vp8/Yuv.luau | 2 +- src/Formats/codecs/{ => image}/Vp8/init.luau | 8 +- .../codecs/{ => image}/Vp8L/Decode.luau | 2 +- .../codecs/{ => image}/Vp8L/Encode.luau | 8 +- src/Formats/codecs/{ => image}/Vp8L/init.luau | 8 +- src/Formats/codecs/{ => image}/Yuv.luau | 2 +- src/Formats/codecs/model/Mat4.luau | 282 ++++++++++++++++++ .../codecs/{ => model}/MeshFlatten.luau | 2 +- .../codecs/{ => text}/Json/Decode.luau | 4 +- .../codecs/{ => text}/Json/Encode.luau | 2 +- src/Formats/codecs/{ => text}/Json/init.luau | 8 +- src/Formats/codecs/{ => text}/Text/init.luau | 2 +- src/Formats/codecs/{ => text}/Url/init.luau | 2 +- src/Formats/codecs/{ => text}/Xml/Parse.luau | 4 +- src/Formats/codecs/{ => text}/Xml/init.luau | 8 +- .../codecs/{ => video}/H264/Bitstream.luau | 2 +- .../codecs/{ => video}/H264/Cabac.luau | 8 +- .../codecs/{ => video}/H264/Cavlc.luau | 8 +- .../codecs/{ => video}/H264/Deblock.luau | 4 +- .../codecs/{ => video}/H264/Decoder.luau | 20 +- .../codecs/{ => video}/H264/Inter.luau | 2 +- .../codecs/{ => video}/H264/Intra.luau | 2 +- src/Formats/codecs/{ => video}/H264/Mb.luau | 8 +- .../codecs/{ => video}/H264/Params.luau | 6 +- .../codecs/{ => video}/H264/Slice.luau | 4 +- .../codecs/{ => video}/H264/Tables.luau | 2 +- .../codecs/{ => video}/H264/Transform.luau | 2 +- src/Formats/codecs/{ => video}/H264/init.luau | 12 +- .../codecs/{ => video}/Mpeg1/Decoder.luau | 8 +- .../codecs/{ => video}/Mpeg1/Tables.luau | 2 +- src/Formats/codecs/{ => video}/Mpeg1/Vlc.luau | 4 +- .../codecs/{ => video}/Mpeg1/init.luau | 4 +- .../codecs/{ => video}/Video/Source.luau | 6 +- .../codecs/{ => video}/Video/init.luau | 18 +- src/Formats/containers/Chunks.luau | 142 +++++++++ src/Formats/containers/Riff/init.luau | 75 ++--- src/Formats/containers/Zip/init.luau | 4 +- src/Formats/core/Bits.luau | 2 +- src/Formats/core/Err.luau | 4 +- src/Formats/data/csv/init.luau | 4 +- src/Formats/data/ini/init.luau | 4 +- src/Formats/data/json/init.luau | 8 +- src/Formats/data/plist/init.luau | 8 +- src/Formats/data/toml/Decode.luau | 2 +- src/Formats/data/toml/Encode.luau | 2 +- src/Formats/data/toml/init.luau | 2 +- src/Formats/data/xml/init.luau | 6 +- src/Formats/data/yaml/Parse.luau | 2 +- src/Formats/data/yaml/init.luau | 2 +- src/Formats/font/ttf/init.luau | 10 +- src/Formats/font/woff/init.luau | 8 +- src/Formats/font/woff2/Rebuild.luau | 2 +- src/Formats/font/woff2/init.luau | 8 +- src/Formats/image/bmp/init.luau | 4 +- src/Formats/image/gif/init.luau | 8 +- src/Formats/image/ico/Dib.luau | 41 ++- src/Formats/image/ico/init.luau | 2 +- src/Formats/image/jpeg/init.luau | 6 +- src/Formats/image/png/init.luau | 18 +- src/Formats/image/tiff/init.luau | 8 +- src/Formats/image/webp/Alpha.luau | 2 +- src/Formats/image/webp/init.luau | 10 +- src/Formats/init.luau | 4 +- src/Formats/layered/aseprite/init.luau | 4 +- src/Formats/layered/psd/Channels.luau | 2 +- src/Formats/layered/psd/init.luau | 8 +- src/Formats/model/3mf/Read.luau | 2 +- src/Formats/model/3mf/Write.luau | 2 +- src/Formats/model/3mf/init.luau | 4 +- src/Formats/model/dae/Math.luau | 154 +--------- src/Formats/model/dae/Read.luau | 33 +- src/Formats/model/dae/Write.luau | 6 +- src/Formats/model/dae/init.luau | 4 +- src/Formats/model/fbx/Binary.luau | 4 +- src/Formats/model/fbx/Read.luau | 37 +-- src/Formats/model/fbx/Write.luau | 28 +- src/Formats/model/fbx/Xform.luau | 186 +----------- src/Formats/model/fbx/init.luau | 4 +- src/Formats/model/gltf/init.luau | 4 +- src/Formats/model/off/init.luau | 4 +- src/Formats/model/ply/init.luau | 4 +- src/Formats/model/stl/init.luau | 4 +- src/Formats/model/usda/Build.luau | 99 +----- src/Formats/model/usda/init.luau | 2 +- src/Formats/music/it/init.luau | 6 +- src/Formats/music/midi/Render.luau | 6 +- src/Formats/music/midi/init.luau | 4 +- src/Formats/music/mod/init.luau | 6 +- src/Formats/music/s3m/init.luau | 6 +- src/Formats/music/sf2/init.luau | 8 +- src/Formats/music/xm/init.luau | 6 +- src/Formats/ops/AudioOps.luau | 8 +- src/Formats/ops/LayerOps.luau | 4 +- src/Formats/playlist/m3u/init.luau | 8 +- src/Formats/playlist/pls/init.luau | 8 +- src/Formats/playlist/xspf/init.luau | 10 +- src/Formats/vector/svg/Parse.luau | 4 +- src/Formats/vector/svg/PathData.luau | 2 +- src/Formats/vector/svg/Render.luau | 8 +- src/Formats/vector/svg/Write.luau | 2 +- src/Formats/vector/svg/init.luau | 6 +- src/Formats/vector/tiled/Data.luau | 2 +- src/Formats/vector/tiled/Tmx.luau | 4 +- src/Formats/vector/tiled/init.luau | 6 +- src/Formats/video/avi/init.luau | 8 +- src/Formats/video/h264/init.luau | 14 +- src/Formats/video/mkv/Mux.luau | 6 +- src/Formats/video/mkv/Parse.luau | 6 +- src/Formats/video/mkv/init.luau | 8 +- src/Formats/video/mp4/init.luau | 8 +- src/Formats/video/mpegps/init.luau | 6 +- src/Formats/video/mpegts/init.luau | 6 +- src/Formats/video/y4m/init.luau | 6 +- tests/archive/gzip.luau | 2 +- tests/archive/zip.luau | 2 +- tests/audio/flac.luau | 4 +- tests/audio/flac_encode.luau | 2 +- tests/audio/mp3_encode.luau | 4 +- tests/audio/opus.luau | 4 +- tests/audio/vorbis.luau | 4 +- tests/audio/vorbis_encode.luau | 2 +- tests/codecs/aac.luau | 4 +- tests/codecs/alac.luau | 4 +- tests/codecs/brotli.luau | 4 +- tests/codecs/bzip2.luau | 4 +- tests/codecs/dct.luau | 4 +- tests/codecs/deflate.luau | 4 +- tests/codecs/h264.luau | 4 +- tests/codecs/h264_jvt.luau | 4 +- tests/codecs/jpeg.luau | 6 +- tests/codecs/json.luau | 4 +- tests/codecs/lzma.luau | 4 +- tests/codecs/lzw.luau | 4 +- tests/codecs/mat4.luau | 43 +++ tests/codecs/mdct.luau | 4 +- tests/codecs/mpeg1.luau | 6 +- tests/codecs/quantize.luau | 4 +- tests/codecs/raster.luau | 4 +- tests/codecs/resample.luau | 8 +- tests/codecs/url.luau | 6 +- tests/codecs/vp8.luau | 4 +- tests/codecs/vp8l.luau | 4 +- tests/codecs/vp8video.luau | 4 +- tests/codecs/xml.luau | 4 +- tests/codecs/zstd.luau | 4 +- tests/containers/chunks.luau | 76 +++++ tests/core/bits.luau | 4 +- tests/data/xml.luau | 2 +- tests/data/yaml.luau | 2 +- tests/font/ttf.luau | 4 +- tests/music/it.luau | 4 +- tests/music/mod.luau | 4 +- tests/music/s3m.luau | 4 +- tests/music/sf2.luau | 4 +- tests/music/xm.luau | 4 +- tests/ops/audioops.luau | 4 +- tests/ops/layerops.luau | 4 +- tests/video/_common.luau | 2 +- tools/bench.luau | 42 +-- tools/brotli_static.py | 4 +- tools/fixtures/3mf.py | 2 +- tools/fixtures/7z.py | 2 +- tools/fixtures/_audio.py | 4 +- tools/fixtures/aiff.py | 2 +- tools/fixtures/aseprite.py | 2 +- tools/fixtures/au.py | 2 +- tools/fixtures/dae.py | 2 +- tools/fixtures/fbx.py | 2 +- tools/fixtures/flac_enc.py | 2 +- tools/fixtures/gltf.py | 2 +- tools/fixtures/json.py | 2 +- tools/fixtures/m4a.py | 2 +- tools/fixtures/mjpeg.py | 8 +- tools/fixtures/mp3_enc.py | 2 +- tools/fixtures/mpeg1.py | 4 +- tools/fixtures/opus_celt.py | 2 +- tools/fixtures/playlist.py | 2 +- tools/fixtures/psd.py | 2 +- tools/fixtures/videoenc.py | 4 +- tools/fixtures/voc.py | 2 +- tools/fixtures/webp.py | 2 +- tools/fixtures/xml.py | 2 +- tools/gen_registry.py | 29 +- tools/lint_rules.py | 8 + tools/lint_types_baseline.txt | 2 +- 283 files changed, 1877 insertions(+), 1660 deletions(-) delete mode 100644 src/Formats/codecs/RangeCoder/init.luau rename src/Formats/codecs/{ => audio}/Aac/Decode.luau (98%) rename src/Formats/codecs/{ => audio}/Aac/Tables.luau (99%) rename src/Formats/codecs/{ => audio}/Aac/init.luau (95%) rename src/Formats/codecs/{ => audio}/Alac/Decode.luau (98%) rename src/Formats/codecs/{ => audio}/Alac/Encode.luau (98%) rename src/Formats/codecs/{ => audio}/Alac/init.luau (96%) rename src/Formats/codecs/{ => audio}/Mdct/Fft.luau (98%) rename src/Formats/codecs/{ => audio}/Mdct/init.luau (94%) rename src/Formats/codecs/{ => audio}/Pcm/Convert.luau (98%) rename src/Formats/codecs/{ => audio}/Pcm/init.luau (97%) rename src/Formats/codecs/{ => audio}/Resample/init.luau (98%) rename src/Formats/codecs/{ => audio}/SoundFont/Fallback.luau (97%) rename src/Formats/codecs/{ => audio}/SoundFont/Parse.luau (99%) rename src/Formats/codecs/{ => audio}/SoundFont/Synth.luau (99%) rename src/Formats/codecs/{ => audio}/SoundFont/init.luau (87%) create mode 100644 src/Formats/codecs/audio/Stream.luau rename src/Formats/codecs/{ => audio}/Tracker/Mixer.luau (95%) rename src/Formats/codecs/{ => audio}/Tracker/Pcm.luau (96%) rename src/Formats/codecs/{ => audio}/Tracker/Player.luau (99%) rename src/Formats/codecs/{ => audio}/Tracker/Tables.luau (97%) rename src/Formats/codecs/{ => audio}/Tracker/init.luau (97%) rename src/Formats/codecs/{ => audio}/VorbisComment.luau (93%) rename src/Formats/codecs/{ => compress}/Brotli/Decode.luau (99%) rename src/Formats/codecs/{ => compress}/Brotli/Static.luau (99%) rename src/Formats/codecs/{ => compress}/Brotli/init.luau (86%) rename src/Formats/codecs/{ => compress}/Bzip2/Decode.luau (99%) rename src/Formats/codecs/{ => compress}/Bzip2/init.luau (89%) rename src/Formats/codecs/{ => compress}/Deflate/Compress.luau (97%) rename src/Formats/codecs/{ => compress}/Deflate/Inflate.luau (97%) rename src/Formats/codecs/{ => compress}/Deflate/init.luau (96%) rename src/Formats/codecs/{ => compress}/Lzma/Crc64.luau (89%) rename src/Formats/codecs/{ => compress}/Lzma/Decode.luau (98%) rename src/Formats/codecs/{ => compress}/Lzma/Filters.luau (97%) rename src/Formats/codecs/{ => compress}/Lzma/init.luau (98%) rename src/Formats/codecs/{ => compress}/Lzw/init.luau (98%) rename src/Formats/codecs/{ => compress}/Zstd/Decode.luau (99%) rename src/Formats/codecs/{ => compress}/Zstd/Xxh64.luau (97%) rename src/Formats/codecs/{ => compress}/Zstd/init.luau (92%) rename src/Formats/{core => codecs/entropy}/Huffman.luau (97%) rename src/Formats/codecs/{ => entropy}/RangeCoder/Decoder.luau (97%) rename src/Formats/codecs/{ => entropy}/RangeCoder/Encoder.luau (95%) create mode 100644 src/Formats/codecs/entropy/RangeCoder/init.luau rename src/Formats/codecs/{ => font}/Cff/init.luau (99%) rename src/Formats/codecs/{ => font}/TrueType/Glyf.luau (97%) rename src/Formats/codecs/{ => font}/TrueType/Tables.luau (99%) rename src/Formats/codecs/{ => font}/TrueType/init.luau (94%) rename src/Formats/codecs/{ => image}/Blend.luau (99%) rename src/Formats/codecs/{ => image}/Dct/init.luau (99%) rename src/Formats/codecs/{ => image}/Jpeg/Arith.luau (98%) rename src/Formats/codecs/{ => image}/Jpeg/Color.luau (98%) rename src/Formats/codecs/{ => image}/Jpeg/Decode.luau (97%) rename src/Formats/codecs/{ => image}/Jpeg/Encode.luau (98%) rename src/Formats/codecs/{ => image}/Jpeg/Scan.luau (99%) rename src/Formats/codecs/{ => image}/Jpeg/Tables.luau (96%) rename src/Formats/codecs/{ => image}/Jpeg/Yuv.luau (92%) rename src/Formats/codecs/{ => image}/Jpeg/init.luau (97%) rename src/Formats/{image/bmp => codecs/image}/Pixels.luau (84%) rename src/Formats/codecs/{ => image}/Quantize/init.luau (99%) rename src/Formats/codecs/{ => image}/Raster.luau (99%) rename src/Formats/codecs/{ => image}/Vp8/Decode.luau (99%) rename src/Formats/codecs/{ => image}/Vp8/Predict.luau (97%) rename src/Formats/codecs/{ => image}/Vp8/Tables.luau (99%) rename src/Formats/codecs/{ => image}/Vp8/Yuv.luau (97%) rename src/Formats/codecs/{ => image}/Vp8/init.luau (96%) rename src/Formats/codecs/{ => image}/Vp8L/Decode.luau (99%) rename src/Formats/codecs/{ => image}/Vp8L/Encode.luau (99%) rename src/Formats/codecs/{ => image}/Vp8L/init.luau (94%) rename src/Formats/codecs/{ => image}/Yuv.luau (98%) create mode 100644 src/Formats/codecs/model/Mat4.luau rename src/Formats/codecs/{ => model}/MeshFlatten.luau (99%) rename src/Formats/codecs/{ => text}/Json/Decode.luau (98%) rename src/Formats/codecs/{ => text}/Json/Encode.luau (98%) rename src/Formats/codecs/{ => text}/Json/init.luau (96%) rename src/Formats/codecs/{ => text}/Text/init.luau (94%) rename src/Formats/codecs/{ => text}/Url/init.luau (98%) rename src/Formats/codecs/{ => text}/Xml/Parse.luau (99%) rename src/Formats/codecs/{ => text}/Xml/init.luau (97%) rename src/Formats/codecs/{ => video}/H264/Bitstream.luau (98%) rename src/Formats/codecs/{ => video}/H264/Cabac.luau (98%) rename src/Formats/codecs/{ => video}/H264/Cavlc.luau (98%) rename src/Formats/codecs/{ => video}/H264/Deblock.luau (97%) rename src/Formats/codecs/{ => video}/H264/Decoder.luau (97%) rename src/Formats/codecs/{ => video}/H264/Inter.luau (98%) rename src/Formats/codecs/{ => video}/H264/Intra.luau (98%) rename src/Formats/codecs/{ => video}/H264/Mb.luau (98%) rename src/Formats/codecs/{ => video}/H264/Params.luau (98%) rename src/Formats/codecs/{ => video}/H264/Slice.luau (97%) rename src/Formats/codecs/{ => video}/H264/Tables.luau (99%) rename src/Formats/codecs/{ => video}/H264/Transform.luau (97%) rename src/Formats/codecs/{ => video}/H264/init.luau (97%) rename src/Formats/codecs/{ => video}/Mpeg1/Decoder.luau (98%) rename src/Formats/codecs/{ => video}/Mpeg1/Tables.luau (98%) rename src/Formats/codecs/{ => video}/Mpeg1/Vlc.luau (94%) rename src/Formats/codecs/{ => video}/Mpeg1/init.luau (97%) rename src/Formats/codecs/{ => video}/Video/Source.luau (97%) rename src/Formats/codecs/{ => video}/Video/init.luau (97%) create mode 100644 src/Formats/containers/Chunks.luau create mode 100644 tests/codecs/mat4.luau create mode 100644 tests/containers/chunks.luau diff --git a/README.md b/README.md index 4c5c37e..d47d4c1 100644 --- a/README.md +++ b/README.md @@ -3,73 +3,143 @@ Read, write and convert file formats in pure Luau, from one source tree that runs on **Roblox** (Luau, native code generation) and on **LuaJIT / LÖVE** (through `tools/build.py`). Every format of a category maps onto one standard type (`src/Formats/Types.luau`): a PNG and a WebP both load as an `Image`, every audio format opens as the same streaming -`Decoder`. +`Decoder`, every model format loads as a `Scene`. -Status: foundation. Formats so far: PNG (read / write). Codecs: DEFLATE (inflate + compressor, zlib, gzip). See -[docs/FORMATS.md](docs/FORMATS.md) (generated) for the capability matrix. +About 76 formats across images, audio, video, 3D models, CAD, fonts, archives, data, vector graphics, layered images, +subtitles, music and playlists: see [docs/FORMATS.md](docs/FORMATS.md) (generated from the code) for the list and each +format's capabilities, and [docs/API.md](docs/API.md) for the whole API. ```luau -local F = require(Formats) -- LuaJIT: require("formats"); luau CLI: require("@formats") -local img, err = F.load(src) -- src: buffer | string | path (hosts with files) -if not img then print(tostring(err)) end -- errors are values: "png: CORRUPT at 0x21: bad filter type 7" -local buf = F.save(img, nil, { format = "png" }) -- a buffer; F.save(img, "out.png") writes a file -local s = F.saveString(img, { format = "png" }) +local F = require(Formats) -- LuaJIT: require("formats"); luau CLI: require("@formats") +local img, err = F.load(src) -- src: buffer | string | path (hosts with files) +if not img then print(tostring(err)) end -- errors are values: "png: CORRUPT at 0x21: bad filter type 7" +local buf = F.save(img, nil, { format = "webp" }) -- a buffer; F.save(img, "out.webp") writes a file local out = F.convert(src, "png", { level = 9 }) -local img2 = F.image.load(src) -- category facades: F.image / audio / video / model / font / ... -for _, f in F.formats() do print(f.name, f.caps.decode, f.caps.encode) end +local small = F.ops.image.resize(img, 64, 64, "lanczos") ``` Nothing throws on bad data or bad arguments: every call returns `nil, err` (`err.code` is one of the `F.Err` codes). -## Runtimes +## Install -| Runtime | How | Files | +**Roblox (Rojo).** `python3 -I tools/build.py roblox` writes `build/roblox/Formats` (requires turned into instance +paths); `default.project.json` mounts it, so `rojo build -o Formats.rbxm` (or `rojo serve`) gives a `Formats` +ModuleScript to put in ReplicatedStorage: `local F = require(game.ReplicatedStorage.Formats)`. There is no file system: +pass buffers or strings. `F.host.toEditableImage(img)` makes an EditableImage. + +**LuaJIT / LÖVE.** `python3 -I tools/build.py luajit` writes `build/luajit/formats/` (Lua 5.1 + LuaJIT FFI; the Luau +standard library pieces come from `formats/_compat.lua`). Copy the `formats` folder into the game (or put +`build/luajit/?.lua;build/luajit/?/init.lua` on `package.path`) and `local F = require("formats")`. Files load by path +(`love.filesystem` under LÖVE, else `io.open`); `F.host.toImageData(img)`, `F.host.fromImageData(imageData)` and +`F.host.toSoundData(audioOrDecoder)` bridge to LÖVE. `examples/love` is a runnable example and smoke test +(`love examples/love` from the repo root after building). + +**luau CLI.** `luau` with the `.luaurc` alias `@formats` runs `src/` directly (no file system). + +## Quick start + +```luau +-- images: PNG / APNG, JPEG, WebP, GIF, BMP, TGA, QOI, TIFF, ICO, PNM, HDR -> Image (rgba8 pixels in a buffer) +local img = F.image.load(pngBytes) +print(img.width, img.height, #(img.frames or {}), img.loops) -- animations: frames; loops = play count, 0 forever +local jpg = F.save(img, nil, { format = "jpeg", quality = 85 }) + +-- audio: WAV, FLAC, MP3 / MP2, Ogg Vorbis, Opus, AAC, M4A, AIFF, AU, CAF, VOC -> streaming Decoder or Audio +local dec = F.audio.open(flacBytes) -- dec:read(n) -> interleaved f32 buffer, frames; dec:seek(s) +local song = F.audio.load(mp3Bytes) -- Audio { sampleRate, channels, frames, samples, tags } +local mono = F.ops.audio.downmix(song, 1) -- channels are in WAVE order; tags keys are lower case +local opus = F.save(F.ops.audio.resample(mono, 48000), nil, { format = "opus", bitrate = 64000 }) + +-- video: MP4 / MOV, MKV / WebM, AVI, MPEG-TS / PS, Y4M (+ animated images) -> VideoDecoder +local v = F.video.open(mp4Bytes) -- v:nextFrame() -> frame (image yuv420p or rgba8, pts) + +-- models: glTF / GLB, OBJ, STL, PLY, FBX, Collada, 3MF, USDA, OFF, VOX -> Scene +local scene = F.model.load(glbBytes) +local prim = F.ops.mesh.merge(scene) -- one triangle primitive in world space + +-- fonts, archives, data, vector, layered, subtitles, music, playlists +local font = F.font.load(ttfBytes) -- outlines, metrics, kerning +local zip = F.archive.load(zipBytes) -- entries; F.archive.save writes zip / tar / gzip +local t = F.data.load('{"a": [1, 2]}', { format = "json" }) -- JSON, XML, YAML, TOML, CSV, INI, plist, msgpack, CBOR +local icon = F.ops.vector.rasterize(F.vector.load(svgText), 64, 64) +local flat = F.ops.layers.flatten(F.layered.load(psdBytes)) +local subs = F.subtitle.load(srtText) +local tune = F.music.load(modBytes) -- MOD / S3M / XM / IT / MIDI, rendered to audio on request +``` + +## The API in short + +`F.load`, `F.open`, `F.save`, `F.saveString`, `F.convert`, `F.detect`, `F.formats`, `F.format(name)`; the category +facades `F.image`, `F.audio`, `F.video`, `F.model`, `F.cad`, `F.font`, `F.archive`, `F.data`, `F.vector`, +`F.layered`, `F.subtitle`, `F.music`, `F.playlist`; editing in `F.ops.image`, `F.ops.mesh`, `F.ops.layers`, +`F.ops.audio`, `F.ops.vector.rasterize`; `F.host`, `F.plugins`, `F.Err`, `F.Types`. Options and the hooks the api +hands to formats (decodeImage / encodeImage / openAudio / plugins): [docs/API.md](docs/API.md). + +## Host notes + +| Host | Files | Bridges | |---|---|---| -| Roblox | `python3 -I tools/build.py roblox`, then `rojo build` / `rojo serve` (`default.project.json` mounts `build/roblox/Formats`) | none: pass buffers / strings; `F.host.toEditableImage(img)` | -| LuaJIT | `python3 -I tools/build.py luajit`; `package.path = "build/luajit/?.lua;build/luajit/?/init.lua;" .. package.path` | `io.open` | -| LÖVE | the LuaJIT build, copied into the game | `love.filesystem` (+ `io`); `F.host.toImageData(img)`, `F.host.fromImageData(id)`, `F.host.toSoundData(audio or decoder)` | -| luau CLI | `luau` with the `.luaurc` alias `@formats` (`src/` directly) | none | +| Roblox | none: pass buffers / strings | `F.host.toEditableImage(img)` | +| LÖVE | `love.filesystem`, then `io` | `toImageData`, `fromImageData`, `toSoundData` | +| LuaJIT | `io.open` | | +| luau CLI | none | | -The LuaJIT build supplies the Luau standard library pieces it needs from `compat/luajit.lua` (unsigned `bit32`, -`buffer` on FFI memory, `table.create`, `math.clamp`, `string.split`, `utf8`, ...), required by each module, without -touching globals (`require("formats._compat").install()` puts `buffer` / `bit32` / `utf8` / `typeof` in `_G` if a -game wants them). +- **Paths.** A string is read as a path only on hosts with files, when it looks like one (short, no NUL / newline) + and the file exists, or when `opts.path = true`; `opts.data = true` forces bytes. Files next to a loaded model + (OBJ `.mtl`, glTF `.bin` and textures) are found through `opts.resolve`, which the api fills in for paths. +- **LuaJIT trace tuning.** On load the host raises LuaJIT's trace limits (`jit.opt.start("maxtrace=8000", + "maxmcode=65536")`): the big decoders (Opus CELT, VP8, H.264, MPEG-1) outgrow the defaults and fall back to the + interpreter (2x or more slower). Set `_G.FORMATS_NO_JIT_TUNE = true` before requiring the library to leave the + JIT settings alone. + +## Layout + +``` +src/Formats/ + init.luau Registry.luau (generated) api: F.* + ops/ editing on the standard types (ImageOps, MeshOps, LayerOps, AudioOps) + <category>/<fmt>/ formats: only what is specific to the format (parsing, mapping, writing) + containers/ Chunks, Riff, IsoBmff, Ebml, Ogg, Zip, Tar, Avi, MpegTs, MpegPs, ... + codecs/compress/ Deflate, Lzma, Zstd, Brotli, Bzip2, Lzw + codecs/entropy/ Huffman, RangeCoder + codecs/image/ Jpeg, Dct, Vp8, Vp8L, Pixels, Yuv, Quantize, Raster, Blend + codecs/audio/ Pcm, Stream, Resample, Mdct, Aac, Alac, VorbisComment, Tracker, SoundFont + codecs/video/ H264, Mpeg1, Video (the codec registry) + codecs/text/ codecs/font/ codecs/model/ Json, Xml, Text, Url / TrueType, Cff / Mat4, MeshFlatten + host/ runtime adapters (only the api uses them) + Types.luau the standard types + constructors + core/ Bytes, Bits, Err, Crc32, Adler32, Base64, Md5, Input, Sniff +compat/luajit.lua tools/ tests/ (T.luau, <category>/<fmt>.luau, codecs/, containers/, gen/) docs/ licenses/ +examples/love/ +``` + +How the layers fit, the format contract, and what belongs in a format folder: [docs/STYLE.md](docs/STYLE.md). ## Development ```sh bash tools/test.sh # fixtures, registry, build, every test under luau --codegen -O2 and LuaJIT, lint bash tools/test.sh png # one test (both runtimes), no lint -bash tools/lint.sh # globals, headers, requires, native-throw, layers, deps, contract, registry +bash tools/lint.sh # globals, type baseline, headers, requires, native-throw, layers, deps, contract, DUP bash tools/bench.sh # throughput on both runtimes (pin it: taskset -c 2 bash tools/bench.sh) python3 -I tools/build.py # build/roblox + build/luajit python3 -I tools/gen_registry.py # src/Formats/Registry.luau + docs/FORMATS.md from the format folders -python3 -I tools/fixtures.py # tests/gen/*.luau from tools/fixtures/*.py +python3 -I tools/fixtures.py # tests/gen/*.luau from tools/fixtures/*.py (reference tools through nix) +python3 -I tools/move.py codecs/image/Foo=codecs/video/Foo # move a module, rewriting every reference ``` Tools: python3, and through nix: `luau` (+ `luau-analyze`), `luajit`, `darklua` 0.19, `rojo` (each script finds them -on PATH or runs them with `nix shell nixpkgs#<tool>`). +on PATH or runs them with `nix shell nixpkgs#<tool>`); the fixture generators run ffmpeg, ImageMagick, libwebp, flac, +lame, opus-tools, vorbis-tools, assimp, fontTools and others through nix. -Layout, layering, the format contract, how to add a format or absorb a repo: [docs/STYLE.md](docs/STYLE.md). +The type checker's diagnostics may only go down: `tools/lint.sh` fails when their count passes +`tools/lint_types_baseline.txt` (`LINT_TYPES=1` lists them, `LINT_TYPES_UPDATE=1` lowers the baseline). -``` -src/Formats/ init.luau (API) Types.luau Registry.luau (generated) core/ host/ codecs/ containers/ - <category>/<fmt>/ ops/ -compat/luajit.lua tools/ tests/ (T.luau, <category>/<fmt>.luau, fixtures/, gen/) docs/ licenses/ -``` +## Performance -## Performance (one Zen 5 core, `taskset -c 2 bash tools/bench.sh`) - -| | luau --codegen -O2 | LuaJIT 2.1 | -|---|---|---| -| inflate, 6 MB text + binary (exact size) | ~330 MB/s | ~470 MB/s | -| zlib (inflate + Adler-32) | ~170 MB/s | ~280 MB/s | -| CRC-32 | ~310 MB/s | ~520 MB/s | -| PNG decode 1024x768 RGBA | ~52 MB/s | ~30-75 MB/s | -| deflate compress -6 | ~12 MB/s | ~8-20 MB/s | - -LuaJIT numbers vary between runs: its trace recorder is randomised, and about one run in ten picks a slower trace -layout for a loop (inflate then runs at ~190 MB/s). Unpinned runs on this hybrid CPU also differ 2x between core types. +`tools/bench.luau` prints throughput per codec on both runtimes; run it pinned to one core +(`taskset -c 2 bash tools/bench.sh`: on hybrid CPUs the core types differ 2x). LuaJIT numbers vary between runs (its +trace recorder is randomised). ## Licence diff --git a/docs/API.md b/docs/API.md index 5e6b861..7c2318a 100644 --- a/docs/API.md +++ b/docs/API.md @@ -38,7 +38,7 @@ one category. Extras: - `F.video.open(src)` also opens animated images (GIF / APNG / WebP) as videos; `F.video.fromImage(img)`, `F.video.fromFrames(images, delays?)` (an image sequence: `F.save(F.video.fromFrames(list, 1 / 25), "out.avi")`), - `F.video.codecs` (the codec registry `codecs/Video`). + `F.video.codecs` (the codec registry `codecs/video/Video`). - `F.model.loadTextures(scene, opts?)`: decodes embedded / referenced textures into `texture.image`. - `F.cad.toBodies`, `F.cad.fromBodies`, `F.cad.tessellate`: STEP B-rep calls through the injected kernel (`F.plugins.brep`). @@ -54,7 +54,7 @@ arguments. | `F.ops.image` | `ops/ImageOps` | `convert` (pixel formats), `crop`, `resize` (nearest / bilinear / Lanczos-3), `flip`, `rotate90`, `rotate`, `blit`, `composite`, `premultiply` / `unpremultiply`, `getPixel` / `setPixel` / `fill`, `new` / `copy`, animations: `coalesce` (frames on full canvases), `fromFrames`, `frameCount`, `durations` | | `F.ops.mesh` | `ops/MeshOps` | `triangulate`, `transform`, `computeNormals`, `computeTangents`, `weld` / `unweld`, `bounds`, `merge`, `scale` / `setUnit` / `setUp`, `voxelsToPrimitive`, `meshVoxels` | | `F.ops.layers` | `ops/LayerOps` | `flatten(layered, { frame })`, `flattenFrames`, `leaves` | -| `F.ops.audio` | `ops/AudioOps` | `toAudio` (an Audio from an Audio or a Decoder), `gain`, `gainDb`, `normalize`, `peak`, `rms`, `mix`, `remix` / `downmix` / `upmix` (WAVE-layout matrices), `resample` (`codecs/Resample`), `trim`, `concat`, `fade` | +| `F.ops.audio` | `ops/AudioOps` | `toAudio` (an Audio from an Audio or a Decoder), `gain`, `gainDb`, `normalize`, `peak`, `rms`, `mix`, `remix` / `downmix` / `upmix` (WAVE-layout matrices), `resample` (`codecs/audio/Resample`), `trim`, `concat`, `fade` | | `F.ops.vector` | `vector/svg` | `rasterize(vector, w?, h?, opts?)`: any `Vector` to an rgba8 `Image` | ```luau diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 8a551f7..13962b1 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -83,38 +83,50 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | playlist | pls | .pls | yes | yes | | `tests/playlist/pls.luau` | | playlist | xspf | .xspf | yes | yes | | `tests/playlist/xspf.luau` | -Codecs (layer 1, shared by formats; not loadable on their own): +Codecs (layer 3, shared by formats; not loadable on their own), by domain: -- codecs/Aac: AAC-LC decoder (ISO/IEC 14496-3 subpart 4, ISO/IEC 13818-7): the AudioSpecificConfig (with a program -- codecs/Alac: Apple Lossless (ALAC) decoder and encoder, the codec inside m4a / mov / caf. A codec (layer 1). -- codecs/Blend: layer compositing on rgba8 buffers (straight alpha): source-over with the separable and non-separable -- codecs/Brotli: Brotli (RFC 7932) decompression. A codec (layer 3): archive/br and font/woff2 build on it. Written -- codecs/Bzip2: bzip2 decompressor (BWT + MTF + Huffman, the .bz2 stream format of bzip2 0.9.5 / 1.0.x). A codec -- codecs/Cff: Compact Font Format (Adobe TN #5176) and Type 2 charstrings (TN #5177): the outlines of OpenType fonts -- codecs/Dct: the 8x8 DCTs JPEG, Motion-JPEG and MPEG-1 share (native; never throws). -- codecs/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers. -- codecs/H264: an H.264 / AVC (ITU-T H.264 | ISO/IEC 14496-10) video decoder in pure Luau. A codec (layer 1): the -- codecs/Jpeg: the JPEG codec (ITU T.81) on byte ranges: image/jpeg is a thin format over it, and the Motion-JPEG -- codecs/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code. -- codecs/Lzma: LZMA and LZMA2 decoders, the .lzma ("LZMA alone") wrapper and the .xz container. A codec (layer 3): -- codecs/Lzw: LZW decoder and encoder in the two variants file formats use. A codec (layer 1): image/gif and -- codecs/Mdct: the MDCT / IMDCT of any window length N divisible by 4 (N / 2 coefficients), through an N / 4-point -- codecs/MeshFlatten: a Scene to one world-space mesh, for the writers of mesh-only formats (STL, PLY, OFF). Walks -- codecs/Mpeg1: an MPEG-1 video decoder (ISO/IEC 11172-2) for the MPEG-TS / MPEG-PS video formats. Absorbed from -- codecs/Pcm: PCM plumbing shared by audio formats: raw sample formats, streaming Decoders, encoder input sources. -- codecs/Quantize: palette quantization of rgba8 pixels. A codec (layer 1): image/gif (and later any palette -- codecs/RangeCoder: the RFC 6716 range coder (libopus celt/entdec.c + entenc.c, BSD: licenses/libopus-BSD.txt): -- codecs/Raster: an antialiased scanline rasterizer for paths of lines, quadratic and cubic Béziers, under an affine -- codecs/Resample: audio sample-rate conversion by band-limited (Kaiser-windowed sinc) interpolation, streaming or -- codecs/SoundFont: SoundFont 2 banks and the sample synth that plays MIDI through them. A codec (layer 1) shared by -- codecs/Text: text decoding helpers for the text formats: a UTF-8 BOM is stripped, text that is not valid UTF-8 is -- codecs/Tracker: the shared tracker engine behind music/mod, music/s3m, music/xm and music/it. The four loaders read -- codecs/TrueType: the sfnt font container (TrueType .ttf, OpenType .otf with CFF outlines, collections .ttc) parsed -- codecs/Url: RFC 3986 reference resolution (section 5.2), the classification of a playlist / manifest location (URL, -- codecs/Video: the video codec registry and the generic VideoDecoder. New in formats-luau. -- codecs/VorbisComment: Vorbis comment fields ("KEY=value", the tag block of Vorbis, Opus and FLAC) <-> Types.Tags. -- codecs/Vp8: the VP8 video codec (RFC 6386), decode only. A codec (layer 1): image/webp uses it for lossy frames, the -- codecs/Vp8L: WebP lossless (VP8L, "WebP Lossless Bitstream Specification", RFC 9649 section 3). A codec (layer 1): -- codecs/Xml: XML 1.0 parse (DOM and pull events) and serialize, the engine data/xml, SVG, DAE, 3MF, TMX, plist, ... -- codecs/Yuv: planar 4:2:0 Y'CbCr <-> rgba8 for the video codecs and writers (native; never throws). BT.601 or -- codecs/Zstd: Zstandard decompression (RFC 8878). A codec (layer 3): archive/zst and anything else carrying zstd +- **audio** + - codecs/audio/Aac: AAC-LC decoder (ISO/IEC 14496-3 subpart 4, ISO/IEC 13818-7): the AudioSpecificConfig (with a program + - codecs/audio/Alac: Apple Lossless (ALAC) decoder and encoder, the codec inside m4a / mov / caf. A codec (layer 1). + - codecs/audio/Mdct: the MDCT / IMDCT of any window length N divisible by 4 (N / 2 coefficients), through an N / 4-point + - codecs/audio/Pcm: PCM plumbing shared by audio formats: raw sample formats, streaming Decoders, encoder input sources. + - codecs/audio/Resample: audio sample-rate conversion by band-limited (Kaiser-windowed sinc) interpolation, streaming or + - codecs/audio/SoundFont: SoundFont 2 banks and the sample synth that plays MIDI through them. A codec (layer 1) shared by + - codecs/audio/Stream: the streaming Decoder (Types.Decoder: read / seek / position) over a packetised codec, the part + - codecs/audio/Tracker: the shared tracker engine behind music/mod, music/s3m, music/xm and music/it. The four loaders read + - codecs/audio/VorbisComment: Vorbis comment fields ("KEY=value", the tag block of Vorbis, Opus and FLAC) <-> Types.Tags. +- **compress** + - codecs/compress/Brotli: Brotli (RFC 7932) decompression. A codec (layer 3): archive/br and font/woff2 build on it. Written + - codecs/compress/Bzip2: bzip2 decompressor (BWT + MTF + Huffman, the .bz2 stream format of bzip2 0.9.5 / 1.0.x). A codec + - codecs/compress/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers. + - codecs/compress/Lzma: LZMA and LZMA2 decoders, the .lzma ("LZMA alone") wrapper and the .xz container. A codec (layer 3): + - codecs/compress/Lzw: LZW decoder and encoder in the two variants file formats use. A codec (layer 1): image/gif and + - codecs/compress/Zstd: Zstandard decompression (RFC 8878). A codec (layer 3): archive/zst and anything else carrying zstd +- **entropy** + - codecs/entropy/Huffman: canonical Huffman codes (RFC 1951 3.2.2 / JPEG Annex C order) for decoders and encoders. + - codecs/entropy/RangeCoder: the RFC 6716 range coder (libopus celt/entdec.c + entenc.c, BSD: licenses/libopus-BSD.txt): +- **font** + - codecs/font/Cff: Compact Font Format (Adobe TN #5176) and Type 2 charstrings (TN #5177): the outlines of OpenType fonts + - codecs/font/TrueType: the sfnt font container (TrueType .ttf, OpenType .otf with CFF outlines, collections .ttc) parsed +- **image** + - codecs/image/Blend: layer compositing on rgba8 buffers (straight alpha): source-over with the separable and non-separable + - codecs/image/Dct: the 8x8 DCTs JPEG, Motion-JPEG and MPEG-1 share (native; never throws). + - codecs/image/Jpeg: the JPEG codec (ITU T.81) on byte ranges: image/jpeg is a thin format over it, and the Motion-JPEG + - codecs/image/Pixels: row loops between packed pixel layouts and rgba8 (native), shared by the bitmap formats (BMP, + - codecs/image/Quantize: palette quantization of rgba8 pixels. A codec (layer 1): image/gif (and later any palette + - codecs/image/Raster: an antialiased scanline rasterizer for paths of lines, quadratic and cubic Béziers, under an affine + - codecs/image/Vp8: the VP8 video codec (RFC 6386), decode only. A codec (layer 1): image/webp uses it for lossy frames, the + - codecs/image/Vp8L: WebP lossless (VP8L, "WebP Lossless Bitstream Specification", RFC 9649 section 3). A codec (layer 1): + - codecs/image/Yuv: planar 4:2:0 Y'CbCr <-> rgba8 for the video codecs and writers (native; never throws). BT.601 or +- **model** + - codecs/model/Mat4: 4x4 matrix and quaternion helpers for the model formats: column-major flat arrays of 16 + - codecs/model/MeshFlatten: a Scene to one world-space mesh, for the writers of mesh-only formats (STL, PLY, OFF). Walks +- **text** + - codecs/text/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code. + - codecs/text/Text: text decoding helpers for the text formats: a UTF-8 BOM is stripped, text that is not valid UTF-8 is + - codecs/text/Url: RFC 3986 reference resolution (section 5.2), the classification of a playlist / manifest location (URL, + - codecs/text/Xml: XML 1.0 parse (DOM and pull events) and serialize, the engine data/xml, SVG, DAE, 3MF, TMX, plist, ... +- **video** + - codecs/video/H264: an H.264 / AVC (ITU-T H.264 | ISO/IEC 14496-10) video decoder in pure Luau. A codec (layer 1): the + - codecs/video/Mpeg1: an MPEG-1 video decoder (ISO/IEC 11172-2) for the MPEG-TS / MPEG-PS video formats. Absorbed from + - codecs/video/Video: the video codec registry and the generic VideoDecoder. New in formats-luau. diff --git a/docs/STYLE.md b/docs/STYLE.md index 9d52919..11654b8 100644 --- a/docs/STYLE.md +++ b/docs/STYLE.md @@ -1,7 +1,8 @@ # formats-luau style guide -Every format looks the same: one folder, one contract, one test, one fixture generator. `bash tools/lint.sh` enforces -most of what follows (the rule names in CAPITALS are lint rules, implemented in `tools/lint_rules.py`). +Every format looks the same: one folder, one contract, one test, one fixture generator, and the folder holds only what +is specific to the format (section 2a). `bash tools/lint.sh` enforces most of what follows (the rule names in +CAPITALS are lint rules, implemented in `tools/lint_rules.py`). The reference implementation to copy is **PNG**: @@ -11,27 +12,36 @@ The reference implementation to copy is **PNG**: | Private hot submodules (`--!native`) | `src/Formats/image/png/Decode.luau`, `src/Formats/image/png/Encode.luau` | | Test | `tests/image/png.luau` | | Fixture generator | `tools/fixtures/png.py` (a reference tool through nix: `tools/fixtures/_png_reference.py`) | -| A codec (layer 1) | `src/Formats/codecs/Deflate/` + `tests/codecs/deflate.luau` + `tools/fixtures/deflate.py` | +| A codec (layer 3) | `src/Formats/codecs/compress/Deflate/` + `tests/codecs/deflate.luau` + `tools/fixtures/deflate.py` | ## 1. Layout and layers ``` src/Formats/ init.luau Registry.luau (generated) api (layer 6) - ops/ ops (layer 5.5) editing on the standard types + ops/ ops (layer 5.5) editing on the standard types (F.ops.image / + mesh / layers / audio; ImageOps, MeshOps, ...) <category>/<fmt>/ formats (layer 5) image audio video model cad font archive data vector layered subtitle music playlist - containers/ containers (layer 4) Riff, IsoBmff, Ebml, Ogg, Zip, Tar, ... - codecs/ codecs (layer 3) Deflate, Lzw, Dct, Huffman-heavy algorithms + containers/ containers (layer 4) Chunks, Riff, IsoBmff, Ebml, Ogg, Zip, Tar, ... + codecs/<domain>/<Name> codecs (layer 3) generic algorithms, by domain: + compress/ Deflate Lzma Zstd Brotli Bzip2 Lzw entropy/ Huffman RangeCoder + image/ Jpeg Dct Vp8 Vp8L Pixels Yuv Quantize Raster Blend + audio/ Pcm Stream Resample Mdct Aac Alac VorbisComment Tracker SoundFont + video/ H264 Mpeg1 Video (the video codec registry) text/ Json Xml Text Url + font/ TrueType Cff model/ Mat4 MeshFlatten host/ host (layer 2) runtime adapters; only the api uses them Types.luau types (layer 1) standard types + constructors - core/ core (layer 0) Bytes, Bits, Err, Crc32, Adler32, Huffman, Input + core/ core (layer 0) Bytes, Bits, Err, Crc32, Adler32, Base64, Md5, + Input, Sniff (runtime-neutral primitives) ``` LAYERS: a module requires only what is below it. core requires core; Types requires core; codecs require core, Types and other codecs; containers add codecs; a format may require core, Types, codecs, containers and **its own folder**, -never another format (shared code moves down to `codecs/` or `containers/`: WebP lossy and WebM both use `codecs/Vp8`). -Nothing but the api requires `host/`: formats are pure functions of bytes. +never another format (shared code moves down to `codecs/` or `containers/`: WebP lossy and WebM both use `codecs/image/Vp8`). +Nothing but the api requires `host/`: formats are pure functions of bytes. A codec lives in a domain folder +(`codecs/<compress|entropy|image|audio|video|text|font|model>/<Name>`); `containers/` and `core/` are flat. Moving a +module: `python3 -I tools/move.py old/Path=new/Path` rewrites every reference (requires, deps, headers, docs). REQUIRE: every require is a string literal `require("@formats/<path>")` (tests and tools may also use `require("@tests/<path>")`). No `script.X`, no `@self`, no relative paths, no computed requires: `tools/build.py` turns @@ -119,6 +129,18 @@ Rules: - Extra format-specific functions (`Png.info(r)`) are fine; `F.format("png")` returns the module. - No globals, no state between calls, no host access (no files, no `game`). +### Conventions shared by every format +- Images: `rgba8` unless `opts.native`; `img.loops` is the play count (0 = forever: GIF stores repeats, APNG / WebP + play counts); animation frames per `Types.Frame`. +- Audio: interleaved f32 in **WAVE channel order** (FL FR C LFE BL BR SL SR; Vorbis / Opus streams are reordered with + `Pcm.WAVE_FROM_VORBIS`); `tags` keys are **lower case** (title, artist, album, albumartist, date, genre, track, + disc, comment, ...: `codecs/audio/VorbisComment` for Vorbis / Opus / FLAC); raw fields go in `meta.source`. +- Hooks: a format never requires another format. For embedded data in another format the api passes + `opts.decodeImage(buf)`, `opts.encodeImage(img, format)`, `opts.openAudio(demuxer, track)` (audio tracks of video + containers, through `containers/AudioWrap`), `opts.plugins` (injected optional dependencies such as the B-rep + kernel) and `opts.resolve(uri)` (sibling files); without them the embedded part is `Err.UNSUPPORTED`. Video codecs + register in `codecs/video/Video` (fourcc / Matroska id -> decoder) so every container finds them. + ### Errors (Err) Nothing throws on bad data or bad arguments. Every failure is `return nil, Err.new(code, message, offset?)`: @@ -134,7 +156,9 @@ Nothing throws on bad data or bad arguments. Every failure is `return nil, Err.n Messages are lower case, without the format name (the api adds it: `png: CORRUPT at 0x21: bad filter type 7`). The `Bytes` reader's errors are sticky: read a run of fields, then check `if r.err then return nil, r.err end` once. -Private submodules may return `false, "message"` or `nil, "message"`; `init.luau` turns that into an `Err`. +Private submodules may return `false, "message"` or `nil, "message"[, kind]`; `init.luau` turns that into an `Err` +with `Err.from(message, offset?, kind?)` (kind = "truncated" / "limit" / ...; without it a `"limit: "` / +`"unsupported: "` prefix or "truncated" / "past the end" in the message picks the code, else CORRUPT). ### Native code (NATIVE) A Luau error unwinding through a native frame crashes Roblox Studio, even inside `pcall`. So: @@ -150,12 +174,38 @@ A Luau error unwinding through a native frame crashes Roblox Studio, even inside - Bits / Bytes readers are for headers; inner loops read the buffer directly. - LuaJIT runs the same code through `compat/luajit.lua` (FFI `buffer`, unsigned `bit32`). It is fastest with straight-line code in the hottest loop: a tiny inner loop (`for k = 0, len - 1 do ... end` inside the symbol loop) - splits LuaJIT's traces; codecs/Deflate/Inflate copies short matches with four `readu32` / `writeu32` instead. + splits LuaJIT's traces; codecs/compress/Deflate/Inflate copies short matches with four `readu32` / `writeu32` instead. - Benchmark with `bash tools/bench.sh` pinned to one core (`taskset -c 2 bash tools/bench.sh`): on hybrid CPUs (this machine: Zen 5 + Zen 5c) the same run differs 2x between core types. - Avoid `string.pack` / `string.unpack` (not in LuaJIT), `\0` inside Lua patterns (LuaJIT: use `%z` or plain find), and fractional operands to `bit32` (LuaJIT rounds where Luau truncates). +## 2a. What belongs in a format folder + +A format folder holds only what is specific to the format: its header / chunk parsing, the mapping to and from the +standard type, its writer, and hot loops nothing else shares. Anything generic goes down a layer and is called: + +| Need | Use | +|---|---| +| chunked files (RIFF / IFF / PNG / CAF style: id, size, body, pad, trailer) | `containers/Chunks` (`containers/Riff` for RIFF forms) | +| a decode() that drains open() | `codecs/audio/Pcm.drain(dec, source)` | +| a streaming Decoder over packets (priming, end padding, seek pre-roll) | `codecs/audio/Stream.packets` | +| encoder input (Audio or Decoder), sample formats, channel order | `codecs/audio/Pcm` (`source`, `collect`, `Convert`, `reorder`) | +| other sample rates | `codecs/audio/Resample` | +| Vorbis comments | `codecs/audio/VorbisComment` | +| bitmap rows (indexed bits, BGR / BGRA, 5-5-5, masks, RLE4 / 8, bottom-up) | `codecs/image/Pixels` | +| 4x4 matrices, quaternions, TRS | `codecs/model/Mat4` | +| compression, entropy coding, CRCs, base64 | `codecs/compress/*`, `codecs/entropy/*`, `core/Crc32` (`.msb` too), `core/Base64` | +| bit writing for encoders | `core/Bits` (`msbWriter`, or `Bits.msbPut` on a raw record) | +| argument checking of (buffer \| string, offset, length) | `core/Bytes.span` | +| sniffing text (BOM) / magic | `core/Sniff` | +| private-submodule errors -> Err | `core/Err.from` | +| UTF-8 code points, text decoding | `codecs/text/Text` | + +DUP enforces the direction: a function body of 12 or more code lines repeated token for token in another module +fails the lint. When two formats need the same code, move it down (to `codecs/<domain>/` or `containers/`) instead of +copying. + ## 3. Tests `tests/<category>/<fmt>.luau`, run by `bash tools/test.sh [filter]` under `luau --codegen -O2` **and** LuaJIT. Template: @@ -193,14 +243,17 @@ t:done() their licence in `licenses/`). Prefer generating over committing. Keep fixture modules under ~15 MB. - Both runtimes read the same `require("@tests/gen/<name>")`; there is no second mechanism. - A fuzz pass is mandatory for every decoder (CONTRACT checks `:fuzz(`). +- Types: `luau-analyze` diagnostics are counted by the lint (TYPES) and may not rise above + `tools/lint_types_baseline.txt`; new code should add none (`LINT_TYPES=1 bash tools/lint.sh` lists them, and + `LINT_TYPES_UPDATE=1` lowers the baseline after a cleanup). ## 4. Adding a format 1. `src/Formats/<category>/<fmt>/init.luau` from the template above (copy `image/png/init.luau`), private submodules - next to it. Use `core/Bytes` for parsing, `core/Bits` / `core/Huffman` for entropy coding, `Types` constructors for - the result. -2. Shared code (a codec two formats need, a container) goes to `codecs/` or `containers/` instead, with its own test in - `tests/codecs/` / `tests/containers/`. + next to it. Use `core/Bytes` for parsing, `core/Bits` / `codecs/entropy/Huffman` for entropy coding, the shared + modules of section 2a for everything generic, `Types` constructors for the result. +2. Shared code (a codec two formats need, a container) goes to `codecs/<domain>/` or `containers/` instead, with its + own test in `tests/codecs/` / `tests/containers/`. 3. `deps = { ... }` = the requires outside the folder. 4. `python3 -I tools/gen_registry.py` (regenerates `src/Formats/Registry.luau` and `docs/FORMATS.md`; never edit those by hand; after a merge, just rerun it). diff --git a/docs/video.md b/docs/video.md index ce04b20..184ca45 100644 --- a/docs/video.md +++ b/docs/video.md @@ -24,10 +24,10 @@ F.convert(gif, "avi") -- animated images become videos (un | `containers/Demux` | the indexed Demuxer every container builds: per-track cursors, keyframe seek, `count` / `get` / `info` | | `containers/Ebml`, `Avi`, `IsoBmff`, `MpegTs`, `MpegPs`, `MpegEs` | container structures | | `containers/AudioWrap` | an audio track as a stream an audio format reads (PCM -> WAV, Opus / Vorbis -> Ogg, AAC -> ADTS, ...) | -| `codecs/Video` | the codec registry and the generic VideoDecoder (`Video.open(demuxer, opts)`, `Video.fromFrames`) | -| `codecs/Video/Source` | what writers write: copied packets or frames encoded by a registry encoder, PCM from the audio | -| `codecs/Yuv` | yuv420p <-> rgba8 (BT.601 / 709, limited / full range from `image.meta.yuv`), range remap | -| `codecs/Vp8`, `Jpeg`, `Mpeg1` | the decoders (and the JPEG encoder) | +| `codecs/video/Video` | the codec registry and the generic VideoDecoder (`Video.open(demuxer, opts)`, `Video.fromFrames`) | +| `codecs/video/Video/Source` | what writers write: copied packets or frames encoded by a registry encoder, PCM from the audio | +| `codecs/image/Yuv` | yuv420p <-> rgba8 (BT.601 / 709, limited / full range from `image.meta.yuv`), range remap | +| `codecs/image/Vp8`, `Jpeg`, `Mpeg1` | the decoders (and the JPEG encoder) | | `video/<fmt>` | the formats: demux into `containers/Demux`, `open` = `Video.open(demuxer, opts)`, `encode` via Source | Audio tracks reach the audio formats through the api hook `opts.openAudio(demuxer, track)` (a format never requires @@ -36,13 +36,13 @@ another format): `F.video.open` / `F.load` set it; calling a video format's `ope ## Adding a codec (H.264, ...) -The registry is static (Roblox has no dynamic require): add an entry to `BUILTIN` in `src/Formats/codecs/Video/init.luau` +The registry is static (Roblox has no dynamic require): add an entry to `BUILTIN` in `src/Formats/codecs/video/Video/init.luau` with a `new` constructor that requires the codec lazily, or call `Video.register(entry)` at run time (`F.video.codecs.register`). ```luau { id = "h264", name = "H.264 / AVC", fourcc = { "avc1", "avc3", "H264", ... }, matroska = { "V_MPEG4/ISO/AVC" }, - new = function(track, opts) return require("@formats/codecs/H264").newVideoDecoder(track, opts) end } + new = function(track, opts) return require("@formats/codecs/video/H264").newVideoDecoder(track, opts) end } ``` `new(track, opts)` returns a `Types.VideoCodecDecoder`: diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 79b5789..d5cf13f 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -20,7 +20,7 @@ local list: { Entry } = { path = "image/bmp", extensions = { "bmp", "dib" }, mime = { "image/bmp", "image/x-bmp", "image/x-ms-bmp" }, - deps = { "core/Err", "core/Bytes", "Types" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Pixels" }, caps = { decode = true, encode = true, alpha = true, depths = { 1, 2, 4, 8, 16, 24, 32 }, rle = true }, load = function() return require("@formats/image/bmp") @@ -32,7 +32,7 @@ local list: { Entry } = { path = "image/gif", extensions = { "gif" }, mime = { "image/gif" }, - deps = { "core/Err", "core/Bytes", "codecs/Lzw", "codecs/Quantize", "Types" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Lzw", "codecs/image/Quantize", "Types" }, caps = { decode = true, encode = true, animation = true, alpha = true, palette = true, depths = { 1, 2, 4, 8 } }, load = function() return require("@formats/image/gif") @@ -56,7 +56,7 @@ local list: { Entry } = { path = "image/ico", extensions = { "ico", "cur" }, mime = { "image/vnd.microsoft.icon", "image/x-icon" }, - deps = { "core/Err", "core/Bytes", "Types" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Pixels" }, caps = { decode = true, encode = true, alpha = true, frames = true, depths = { 1, 4, 8, 16, 24, 32 } }, load = function() return require("@formats/image/ico") @@ -68,7 +68,7 @@ local list: { Entry } = { path = "image/jpeg", extensions = { "jpg", "jpeg", "jpe", "jfif" }, mime = { "image/jpeg" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Jpeg" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Jpeg" }, caps = { decode = true, encode = true, lossy = true, alpha = false, depths = { 8, 12 }, progressive = true, arithmetic = true }, load = function() return require("@formats/image/jpeg") @@ -80,7 +80,7 @@ local list: { Entry } = { path = "image/png", extensions = { "png", "apng" }, mime = { "image/png", "image/apng" }, - deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/Deflate", "Types" }, + deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/compress/Deflate", "Types", "containers/Chunks" }, caps = { decode = true, encode = true, animation = true, alpha = true, depths = { 1, 2, 4, 8, 16 } }, load = function() return require("@formats/image/png") @@ -128,7 +128,7 @@ local list: { Entry } = { path = "image/tiff", extensions = { "tif", "tiff" }, mime = { "image/tiff" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Deflate", "codecs/Lzw" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Deflate", "codecs/compress/Lzw" }, caps = { decode = true, encode = true, alpha = true, pages = true, depths = { 1, 2, 4, 8, 16, 32 }, float = true }, load = function() return require("@formats/image/tiff") @@ -140,7 +140,7 @@ local list: { Entry } = { path = "image/webp", extensions = { "webp" }, mime = { "image/webp" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Vp8", "codecs/Vp8L", "containers/Riff" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Vp8", "codecs/image/Vp8L", "containers/Riff" }, caps = { decode = true, encode = true, animation = true, alpha = true, lossy = true, lossless = true, depths = { 8 } }, load = function() return require("@formats/image/webp") @@ -152,7 +152,7 @@ local list: { Entry } = { path = "audio/aac", extensions = { "aac", "adts" }, mime = { "audio/aac", "audio/aacp", "audio/x-aac" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Aac", "codecs/Pcm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Aac", "codecs/audio/Pcm", "codecs/audio/Stream" }, caps = { decode = true, encode = false, codecs = { "aac" }, streaming = true }, load = function() return require("@formats/audio/aac") @@ -164,7 +164,7 @@ local list: { Entry } = { path = "audio/aiff", extensions = { "aiff", "aif", "aifc", "afc" }, mime = { "audio/aiff", "audio/x-aiff" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "containers/Chunks" }, caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, lossy = false }, load = function() return require("@formats/audio/aiff") @@ -176,7 +176,7 @@ local list: { Entry } = { path = "audio/au", extensions = { "au", "snd" }, mime = { "audio/basic", "audio/x-au" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm" }, caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, lossy = false }, load = function() return require("@formats/audio/au") @@ -188,7 +188,7 @@ local list: { Entry } = { path = "audio/caf", extensions = { "caf", "caff" }, mime = { "audio/x-caf" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Aac", "codecs/Alac", "codecs/Pcm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Aac", "codecs/audio/Alac", "codecs/audio/Pcm", "codecs/audio/Stream", "containers/Chunks" }, caps = { decode = true, encode = true, codecs = { "pcm", "alac", "aac", "ulaw", "alaw" }, encodeCodecs = { "pcm", "alac" }, tags = true, streaming = true }, load = function() return require("@formats/audio/caf") @@ -200,7 +200,7 @@ local list: { Entry } = { path = "audio/flac", extensions = { "flac", "oga" }, mime = { "audio/flac", "audio/x-flac" }, - deps = { "core/Err", "core/Bytes", "core/Bits", "Types", "containers/Ogg", "core/Md5", "codecs/Pcm", "codecs/VorbisComment" }, + deps = { "core/Err", "core/Bytes", "core/Bits", "Types", "containers/Ogg", "core/Md5", "codecs/audio/Pcm", "codecs/audio/VorbisComment" }, caps = { decode = true, encode = true, streaming = true, depths = { 4, 8, 12, 16, 20, 24, 32 }, ogg = true, seek = true }, load = function() return require("@formats/audio/flac") @@ -212,7 +212,7 @@ local list: { Entry } = { path = "audio/m4a", extensions = { "m4a", "m4b", "m4r" }, mime = { "audio/mp4", "audio/x-m4a", "audio/m4a" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/IsoBmff", "codecs/Aac", "codecs/Alac", "codecs/Pcm" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/IsoBmff", "codecs/audio/Aac", "codecs/audio/Alac", "codecs/audio/Pcm", "codecs/audio/Stream" }, caps = { decode = true, encode = true, codecs = { "aac", "alac" }, encodeCodecs = { "alac" }, tags = true, streaming = true }, load = function() return require("@formats/audio/m4a") @@ -224,7 +224,7 @@ local list: { Entry } = { path = "audio/mp3", extensions = { "mp3", "mp2", "mp1", "mpga" }, mime = { "audio/mpeg", "audio/mp3", "audio/mpa" }, - deps = { "core/Err", "core/Bytes", "core/Bits", "Types", "codecs/Pcm", "codecs/Resample" }, + deps = { "core/Err", "core/Bytes", "core/Bits", "Types", "codecs/audio/Pcm", "codecs/audio/Resample" }, caps = { decode = true, encode = true, streaming = true, seek = true, layers = { 1, 2, 3 }, encodeLayers = { 2, 3 }, channels = 2 }, load = function() return require("@formats/audio/mp3") @@ -236,7 +236,7 @@ local list: { Entry } = { path = "audio/opus", extensions = { "opus" }, mime = { "audio/opus", "audio/ogg" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct", "codecs/RangeCoder/Decoder", "codecs/RangeCoder/Encoder", "codecs/Pcm", "codecs/Resample", "codecs/VorbisComment" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/audio/Mdct", "codecs/entropy/RangeCoder/Decoder", "codecs/entropy/RangeCoder/Encoder", "codecs/audio/Pcm", "codecs/audio/Resample", "codecs/audio/VorbisComment" }, caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255, rates = { 48000 }, encodeModes = { "celt" }, encodeChannels = 2 }, load = function() return require("@formats/audio/opus") @@ -248,7 +248,7 @@ local list: { Entry } = { path = "audio/voc", extensions = { "voc" }, mime = { "audio/x-voc" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm" }, caps = { decode = true, encode = true, streaming = true, depths = { 8, 16 }, lossy = false }, load = function() return require("@formats/audio/voc") @@ -260,7 +260,7 @@ local list: { Entry } = { path = "audio/vorbis", extensions = { "ogg", "oga" }, mime = { "audio/ogg", "audio/vorbis" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct", "codecs/Pcm", "codecs/VorbisComment" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/audio/Mdct", "codecs/audio/Pcm", "codecs/audio/VorbisComment" }, caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255 }, load = function() return require("@formats/audio/vorbis") @@ -272,7 +272,7 @@ local list: { Entry } = { path = "audio/wav", extensions = { "wav", "wave", "rf64", "bw64" }, mime = { "audio/wav", "audio/x-wav", "audio/wave", "audio/vnd.wave" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Riff", "codecs/Pcm" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Riff", "codecs/audio/Pcm" }, caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, rf64 = true }, load = function() return require("@formats/audio/wav") @@ -284,7 +284,7 @@ local list: { Entry } = { path = "video/avi", extensions = { "avi" }, mime = { "video/x-msvideo", "video/avi" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Avi", "containers/Demux", "codecs/Video", "codecs/Video/Source" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Avi", "containers/Demux", "codecs/video/Video", "codecs/video/Video/Source" }, caps = { decode = true, encode = true, streaming = true, video = { "mjpeg", "mpeg1", "rawvideo" }, audio = true, odml = true }, load = function() return require("@formats/video/avi") @@ -296,7 +296,7 @@ local list: { Entry } = { path = "video/h264", extensions = { "h264", "264", "avc", "jsv", "26l", "jvt" }, mime = { "video/h264" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/Video", "codecs/Video/Source", "codecs/H264" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/video/Video", "codecs/video/Video/Source", "codecs/video/H264" }, caps = { decode = true, encode = true, streaming = true, video = { "h264" }, depths = { 8 } }, load = function() return require("@formats/video/h264") @@ -308,7 +308,7 @@ local list: { Entry } = { path = "video/mkv", extensions = { "mkv", "webm", "mka", "mk3d" }, mime = { "video/x-matroska", "video/webm", "audio/x-matroska", "audio/webm" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Ebml", "containers/Demux", "codecs/Deflate", "codecs/Video", "codecs/Video/Source" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ebml", "containers/Demux", "codecs/compress/Deflate", "codecs/video/Video", "codecs/video/Video/Source" }, caps = { decode = true, encode = true, streaming = true, remux = true, video = { "vp8", "mjpeg", "mpeg1", "rawvideo" }, audio = true, subtitles = true }, load = function() return require("@formats/video/mkv") @@ -320,7 +320,7 @@ local list: { Entry } = { path = "video/mp4", extensions = { "mp4", "m4v", "mov", "qt", "3gp", "3g2", "mj2" }, mime = { "video/mp4", "video/quicktime", "video/3gpp" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/IsoBmff", "containers/Demux", "codecs/Video", "codecs/Video/Source" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/IsoBmff", "containers/Demux", "codecs/video/Video", "codecs/video/Video/Source" }, caps = { decode = true, encode = true, streaming = true, remux = true, video = { "mjpeg", "mpeg1", "h264" }, audio = true, fragments = true }, load = function() return require("@formats/video/mp4") @@ -332,7 +332,7 @@ local list: { Entry } = { path = "video/mpegps", extensions = { "mpg", "mpeg", "vob", "m1v", "mpv", "dat" }, mime = { "video/mpeg" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/MpegPs", "containers/MpegEs", "containers/Demux", "codecs/Video" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/MpegPs", "containers/MpegEs", "containers/Demux", "codecs/video/Video" }, caps = { decode = true, encode = false, streaming = true, video = { "mpeg1" }, audio = true }, load = function() return require("@formats/video/mpegps") @@ -344,7 +344,7 @@ local list: { Entry } = { path = "video/mpegts", extensions = { "ts", "m2ts", "mts", "tsv" }, mime = { "video/mp2t" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/MpegTs", "containers/MpegEs", "containers/Demux", "codecs/Video" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/MpegTs", "containers/MpegEs", "containers/Demux", "codecs/video/Video" }, caps = { decode = true, encode = false, streaming = true, video = { "mpeg1", "h264" }, audio = true }, load = function() return require("@formats/video/mpegts") @@ -356,7 +356,7 @@ local list: { Entry } = { path = "video/y4m", extensions = { "y4m" }, mime = { "video/x-yuv4mpeg" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/Video", "codecs/Video/Source" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/video/Video", "codecs/video/Video/Source" }, caps = { decode = true, encode = true, streaming = true, video = { "rawvideo" }, depths = { 8, 10, 12, 16 } }, load = function() return require("@formats/video/y4m") @@ -368,7 +368,7 @@ local list: { Entry } = { path = "model/3mf", extensions = { "3mf" }, mime = { "model/3mf" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "containers/Zip" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Xml", "containers/Zip" }, caps = { decode = true, encode = true, materials = true, vertexColors = true, textures = true, units = true }, load = function() return require("@formats/model/3mf") @@ -380,7 +380,7 @@ local list: { Entry } = { path = "model/dae", extensions = { "dae", "zae" }, mime = { "model/vnd.collada+xml", "model/vnd.collada+zip" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "core/Base64", "containers/Zip" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Xml", "core/Base64", "containers/Zip", "codecs/model/Mat4" }, caps = { decode = true, encode = true, materials = true, polygons = true, skins = true, morphTargets = true, animation = true, cameras = true, lights = true, zae = true }, load = function() return require("@formats/model/dae") @@ -392,7 +392,7 @@ local list: { Entry } = { path = "model/fbx", extensions = { "fbx" }, mime = { "application/vnd.autodesk.fbx", "model/fbx" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Deflate", "core/Base64" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Deflate", "core/Base64", "codecs/model/Mat4" }, caps = { decode = true, encode = true, binary = true, ascii = true, materials = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true, polygons = true }, load = function() return require("@formats/model/fbx") @@ -404,7 +404,7 @@ local list: { Entry } = { path = "model/gltf", extensions = { "gltf", "glb" }, mime = { "model/gltf+json", "model/gltf-binary" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Json", "core/Base64", "core/Sniff" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Json", "core/Base64", "core/Sniff" }, caps = { decode = true, encode = true, binary = true, materials = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true }, load = function() return require("@formats/model/gltf") @@ -428,7 +428,7 @@ local list: { Entry } = { path = "model/off", extensions = { "off" }, mime = { "model/off", "text/plain" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/MeshFlatten" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/MeshFlatten" }, caps = { decode = true, encode = true, polygons = true, points = true, colors = true, binary = false }, load = function() return require("@formats/model/off") @@ -440,7 +440,7 @@ local list: { Entry } = { path = "model/ply", extensions = { "ply" }, mime = { "model/ply", "application/ply" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/MeshFlatten" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/MeshFlatten" }, caps = { decode = true, encode = true, ascii = true, binary = true, polygons = true, points = true, colors = true }, load = function() return require("@formats/model/ply") @@ -452,7 +452,7 @@ local list: { Entry } = { path = "model/stl", extensions = { "stl" }, mime = { "model/stl", "application/sla" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/MeshFlatten" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/MeshFlatten" }, caps = { decode = true, encode = true, ascii = true, binary = true, colors = true, indexed = false }, load = function() return require("@formats/model/stl") @@ -464,7 +464,7 @@ local list: { Entry } = { path = "model/usda", extensions = { "usda", "usd", "usdz" }, mime = { "model/vnd.usda", "model/vnd.usdz+zip" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Zip" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Zip", "codecs/model/Mat4" }, caps = { decode = true, encode = true, materials = true, animation = true, cameras = true, lights = true, polygons = true, vertexColors = true, usdz = "read", usdc = false }, load = function() return require("@formats/model/usda") @@ -512,7 +512,7 @@ local list: { Entry } = { path = "font/ttf", extensions = { "ttf", "otf", "ttc", "otc" }, mime = { "font/ttf", "font/otf", "font/collection" }, - deps = { "core/Err", "core/Bytes", "codecs/TrueType" }, + deps = { "core/Err", "core/Bytes", "codecs/font/TrueType" }, caps = { decode = true, encode = false, outlines = { "truetype", "cff" }, collection = true, kerning = true }, load = function() return require("@formats/font/ttf") @@ -524,7 +524,7 @@ local list: { Entry } = { path = "font/woff", extensions = { "woff" }, mime = { "font/woff" }, - deps = { "core/Err", "core/Bytes", "codecs/Deflate", "codecs/TrueType" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/font/TrueType" }, caps = { decode = true, encode = false, outlines = { "truetype", "cff" } }, load = function() return require("@formats/font/woff") @@ -536,7 +536,7 @@ local list: { Entry } = { path = "font/woff2", extensions = { "woff2" }, mime = { "font/woff2" }, - deps = { "core/Err", "core/Bytes", "codecs/TrueType", "codecs/Brotli" }, + deps = { "core/Err", "core/Bytes", "codecs/font/TrueType", "codecs/compress/Brotli" }, caps = { decode = true, encode = false, outlines = { "truetype", "cff" }, transforms = { "glyf", "loca", "hmtx" } }, load = function() return require("@formats/font/woff2") @@ -548,7 +548,7 @@ local list: { Entry } = { path = "archive/7z", extensions = { "7z" }, mime = { "application/x-7z-compressed" }, - deps = { "core/Err", "core/Bytes", "core/Crc32", "Types", "codecs/Lzma", "codecs/Deflate", "codecs/Bzip2", "codecs/Zstd", "containers/Archive" }, + deps = { "core/Err", "core/Bytes", "core/Crc32", "Types", "codecs/compress/Lzma", "codecs/compress/Deflate", "codecs/compress/Bzip2", "codecs/compress/Zstd", "containers/Archive" }, caps = { decode = true, encode = false, methods = { "copy", "lzma", "lzma2", "deflate", "bcj", "delta" }, encrypted = false }, load = function() return require("@formats/archive/7z") @@ -560,7 +560,7 @@ local list: { Entry } = { path = "archive/br", extensions = { "br" }, mime = { "application/x-brotli" }, - deps = { "core/Err", "core/Bytes", "codecs/Brotli", "containers/Archive" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Brotli", "containers/Archive" }, caps = { decode = true, encode = false, stream = true }, load = function() return require("@formats/archive/br") @@ -572,7 +572,7 @@ local list: { Entry } = { path = "archive/bz2", extensions = { "bz2", "tbz2", "tbz" }, mime = { "application/x-bzip2" }, - deps = { "core/Err", "core/Bytes", "containers/Archive", "codecs/Bzip2" }, + deps = { "core/Err", "core/Bytes", "containers/Archive", "codecs/compress/Bzip2" }, caps = { decode = true, encode = false, stream = true }, load = function() return require("@formats/archive/bz2") @@ -584,7 +584,7 @@ local list: { Entry } = { path = "archive/gzip", extensions = { "gz", "tgz", "gzip" }, mime = { "application/gzip" }, - deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/Deflate", "containers/Archive", "containers/Tar" }, + deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/compress/Deflate", "containers/Archive", "containers/Tar" }, caps = { decode = true, encode = true, stream = true }, load = function() return require("@formats/archive/gzip") @@ -608,7 +608,7 @@ local list: { Entry } = { path = "archive/xz", extensions = { "xz", "txz", "lzma" }, mime = { "application/x-xz", "application/x-lzma" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Lzma", "containers/Archive" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Lzma", "containers/Archive" }, caps = { decode = true, encode = false, stream = true, filters = { "lzma2", "lzma", "delta", "x86", "powerpc", "arm", "armthumb", "sparc", "arm64" } }, load = function() return require("@formats/archive/xz") @@ -632,7 +632,7 @@ local list: { Entry } = { path = "archive/zst", extensions = { "zst", "tzst" }, mime = { "application/zstd" }, - deps = { "core/Err", "core/Bytes", "codecs/Zstd", "containers/Archive" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Zstd", "containers/Archive" }, caps = { decode = true, encode = false, stream = true }, load = function() return require("@formats/archive/zst") @@ -656,7 +656,7 @@ local list: { Entry } = { path = "data/csv", extensions = { "csv", "tsv" }, mime = { "text/csv", "text/tab-separated-values" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Json", "core/Sniff" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Json", "core/Sniff" }, caps = { decode = true, encode = true, header = true }, load = function() return require("@formats/data/csv") @@ -668,7 +668,7 @@ local list: { Entry } = { path = "data/ini", extensions = { "ini", "cfg", "conf", "inf", "desktop" }, mime = { "text/plain" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Json", "core/Sniff" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Json", "core/Sniff" }, caps = { decode = true, encode = true, ordered = true }, load = function() return require("@formats/data/ini") @@ -680,7 +680,7 @@ local list: { Entry } = { path = "data/json", extensions = { "json", "jsonl", "ndjson", "geojson" }, mime = { "application/json", "application/x-ndjson" }, - deps = { "core/Err", "core/Bytes", "codecs/Json", "core/Sniff" }, + deps = { "core/Err", "core/Bytes", "codecs/text/Json", "core/Sniff" }, caps = { decode = true, encode = true, ordered = true, streaming = true }, load = function() return require("@formats/data/json") @@ -704,7 +704,7 @@ local list: { Entry } = { path = "data/plist", extensions = { "plist" }, mime = { "application/x-plist", "application/x-bplist" }, - deps = { "core/Err", "core/Bytes", "Types", "core/Base64", "codecs/Xml", "codecs/Json" }, + deps = { "core/Err", "core/Bytes", "Types", "core/Base64", "codecs/text/Xml", "codecs/text/Json" }, caps = { decode = true, encode = true, binary = "read", ordered = true }, load = function() return require("@formats/data/plist") @@ -716,7 +716,7 @@ local list: { Entry } = { path = "data/toml", extensions = { "toml" }, mime = { "application/toml" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Json", "codecs/Text" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Json", "codecs/text/Text" }, caps = { decode = true, encode = true, ordered = true, dates = true }, load = function() return require("@formats/data/toml") @@ -728,7 +728,7 @@ local list: { Entry } = { path = "data/xml", extensions = { "xml", "xsd", "xsl", "xslt", "rss", "atom", "xhtml" }, mime = { "application/xml", "text/xml" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "core/Sniff" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Xml", "core/Sniff" }, caps = { decode = true, encode = true, namespaces = true, streaming = true }, load = function() return require("@formats/data/xml") @@ -740,7 +740,7 @@ local list: { Entry } = { path = "data/yaml", extensions = { "yaml", "yml" }, mime = { "application/yaml", "application/x-yaml", "text/yaml" }, - deps = { "core/Err", "core/Bytes", "Types", "core/Base64", "codecs/Text" }, + deps = { "core/Err", "core/Bytes", "Types", "core/Base64", "codecs/text/Text" }, caps = { decode = true, encode = true, ordered = true, multiDocument = true, anchors = true }, load = function() return require("@formats/data/yaml") @@ -752,7 +752,7 @@ local list: { Entry } = { path = "vector/svg", extensions = { "svg" }, mime = { "image/svg+xml" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "codecs/Raster", "codecs/Blend", "core/Sniff" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Xml", "codecs/image/Raster", "codecs/image/Blend", "core/Sniff" }, caps = { decode = true, encode = true, rasterize = true, text = false }, load = function() return require("@formats/vector/svg") @@ -764,7 +764,7 @@ local list: { Entry } = { path = "vector/tiled", extensions = { "tmx", "tmj", "tsx", "tsj" }, mime = { "application/x-tiled-tmx", "application/x-tiled-tmj" }, - deps = { "core/Err", "core/Bytes", "core/Base64", "Types", "codecs/Xml", "codecs/Json", "codecs/Deflate", "core/Sniff" }, + deps = { "core/Err", "core/Bytes", "core/Base64", "Types", "codecs/text/Xml", "codecs/text/Json", "codecs/compress/Deflate", "core/Sniff" }, caps = { decode = true, encode = true, tilesets = true, infinite = true }, load = function() return require("@formats/vector/tiled") @@ -776,7 +776,7 @@ local list: { Entry } = { path = "layered/aseprite", extensions = { "aseprite", "ase" }, mime = { "image/x-aseprite" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Deflate" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Deflate" }, caps = { decode = true, encode = true, layers = true, groups = true, animation = true, depths = { 8, 16, 32 } }, load = function() return require("@formats/layered/aseprite") @@ -788,7 +788,7 @@ local list: { Entry } = { path = "layered/psd", extensions = { "psd", "psb" }, mime = { "image/vnd.adobe.photoshop" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Blend", "codecs/Deflate" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Blend", "codecs/compress/Deflate" }, caps = { decode = true, encode = true, layers = true, groups = true, depths = { 1, 8, 16, 32 } }, load = function() return require("@formats/layered/psd") @@ -836,7 +836,7 @@ local list: { Entry } = { path = "music/it", extensions = { "it" }, mime = { "audio/it", "audio/x-it" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Tracker" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" }, caps = { decode = true, encode = false, render = true, channels = { 1, 64 }, compressedSamples = true }, load = function() return require("@formats/music/it") @@ -848,7 +848,7 @@ local list: { Entry } = { path = "music/midi", extensions = { "mid", "midi", "smf", "kar", "rmi" }, mime = { "audio/midi", "audio/x-midi" }, - deps = { "core/Err", "core/Bytes", "codecs/SoundFont", "Types" }, + deps = { "core/Err", "core/Bytes", "codecs/audio/SoundFont", "Types" }, caps = { decode = true, encode = true, formats = { 0, 1, 2 }, render = true, streaming = true, rmid = true }, load = function() return require("@formats/music/midi") @@ -860,7 +860,7 @@ local list: { Entry } = { path = "music/mod", extensions = { "mod", "m15", "stk", "nst" }, mime = { "audio/x-mod", "audio/mod" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Tracker" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" }, caps = { decode = true, encode = true, render = true, channels = { 1, 32 } }, load = function() return require("@formats/music/mod") @@ -872,7 +872,7 @@ local list: { Entry } = { path = "music/s3m", extensions = { "s3m" }, mime = { "audio/s3m", "audio/x-s3m" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Tracker" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" }, caps = { decode = true, encode = false, render = true, channels = { 1, 32 } }, load = function() return require("@formats/music/s3m") @@ -884,7 +884,7 @@ local list: { Entry } = { path = "music/sf2", extensions = { "sf2" }, mime = { "audio/x-soundfont" }, - deps = { "core/Err", "core/Bytes", "codecs/SoundFont" }, + deps = { "core/Err", "core/Bytes", "codecs/audio/SoundFont" }, caps = { decode = true, encode = false, sm24 = true, sf3 = false }, load = function() return require("@formats/music/sf2") @@ -896,7 +896,7 @@ local list: { Entry } = { path = "music/xm", extensions = { "xm" }, mime = { "audio/xm", "audio/x-xm" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Tracker" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" }, caps = { decode = true, encode = true, render = true, channels = { 1, 64 } }, load = function() return require("@formats/music/xm") @@ -908,7 +908,7 @@ local list: { Entry } = { path = "playlist/m3u", extensions = { "m3u", "m3u8" }, mime = { "audio/x-mpegurl", "audio/mpegurl", "application/vnd.apple.mpegurl", "application/x-mpegurl" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Url", "codecs/Text", "core/Sniff" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Url", "codecs/text/Text", "core/Sniff" }, caps = { decode = true, encode = true, hls = true }, load = function() return require("@formats/playlist/m3u") @@ -920,7 +920,7 @@ local list: { Entry } = { path = "playlist/pls", extensions = { "pls" }, mime = { "audio/x-scpls", "audio/scpls" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Url", "codecs/Text", "core/Sniff" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Url", "codecs/text/Text", "core/Sniff" }, caps = { decode = true, encode = true }, load = function() return require("@formats/playlist/pls") @@ -932,7 +932,7 @@ local list: { Entry } = { path = "playlist/xspf", extensions = { "xspf" }, mime = { "application/xspf+xml" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Url", "codecs/Xml" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Url", "codecs/text/Xml" }, caps = { decode = true, encode = true }, load = function() return require("@formats/playlist/xspf") diff --git a/src/Formats/Types.luau b/src/Formats/Types.luau index b40147b..9060244 100644 --- a/src/Formats/Types.luau +++ b/src/Formats/Types.luau @@ -166,7 +166,7 @@ Types.Midi = Midi -- ------------------------------------------------------------------------------------------------ Video -- A video file opens (F.video.open / a video format's open) as a VideoDecoder; F.load returns the same object (kind = -- "video", decoded lazily). Underneath sits a Demuxer: the container's tracks and their packets. Video tracks decode --- through the codec registry (codecs/Video: by codec id or FourCC, so other codecs can plug in), audio tracks through +-- through the codec registry (codecs/video/Video: by codec id or FourCC, so other codecs can plug in), audio tracks through -- the audio formats (the api hook opts.openAudio, since a format never requires another format). -- -- Times: Packet pts / dts / duration are integer ticks of the track's timescale (exact, for remuxing); VideoFrame pts @@ -242,7 +242,7 @@ export type VideoDecoder = { demuxer: Demuxer?, -- nil for frames-backed videos (animated images) meta: { [string]: any }, } --- a codec's decoder instance (codecs/Video registry entries create them): packets in, pictures out +-- a codec's decoder instance (codecs/video/Video registry entries create them): packets in, pictures out export type VideoCodecDecoder = { decode: (self: any, packet: Packet) -> Err?, -- feed one packet (decode order) receive: (self: any) -> (Image?, number?, boolean?), -- the next picture, the pts (ticks) it carries, keyframe | nil @@ -997,7 +997,7 @@ end Types.Vector = Vector -- ------------------------------------------------------------------------------------------------ Layered (PSD, Aseprite) --- blend: a codecs/Blend mode name ("normal", "multiply", ...; groups also "passThrough"). Optional: children (a group: +-- blend: a codecs/image/Blend mode name ("normal", "multiply", ...; groups also "passThrough"). Optional: children (a group: -- its layers bottom to top; its image is 0 x 0), clip (clipped to the alpha of the layer below), mask (a grey mask in -- canvas coordinates; outside its rectangle the mask is `default`). export type LayerMask = { image: Image, x: number, y: number, default: number, disabled: boolean? } diff --git a/src/Formats/archive/7z/init.luau b/src/Formats/archive/7z/init.luau index 653195a..4691ae7 100644 --- a/src/Formats/archive/7z/init.luau +++ b/src/Formats/archive/7z/init.luau @@ -13,10 +13,10 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Crc32 = require("@formats/core/Crc32") local Types = require("@formats/Types") -local Lzma = require("@formats/codecs/Lzma") -local Deflate = require("@formats/codecs/Deflate") -local Bzip2 = require("@formats/codecs/Bzip2") -local Zstd = require("@formats/codecs/Zstd") +local Lzma = require("@formats/codecs/compress/Lzma") +local Deflate = require("@formats/codecs/compress/Deflate") +local Bzip2 = require("@formats/codecs/compress/Bzip2") +local Zstd = require("@formats/codecs/compress/Zstd") local Archive = require("@formats/containers/Archive") local Header = require("@formats/archive/7z/Header") @@ -26,7 +26,7 @@ local SevenZip = { category = "archive", extensions = { "7z" }, mime = { "application/x-7z-compressed" }, - deps = { "core/Err", "core/Bytes", "core/Crc32", "Types", "codecs/Lzma", "codecs/Deflate", "codecs/Bzip2", "codecs/Zstd", "containers/Archive" }, + deps = { "core/Err", "core/Bytes", "core/Crc32", "Types", "codecs/compress/Lzma", "codecs/compress/Deflate", "codecs/compress/Bzip2", "codecs/compress/Zstd", "containers/Archive" }, caps = { decode = true, encode = false, methods = { "copy", "lzma", "lzma2", "deflate", "bcj", "delta" }, encrypted = false }, } diff --git a/src/Formats/archive/br/init.luau b/src/Formats/archive/br/init.luau index 6949a02..f67d16d 100644 --- a/src/Formats/archive/br/init.luau +++ b/src/Formats/archive/br/init.luau @@ -1,6 +1,6 @@ --!strict -- archive/br: a Brotli (RFC 7932) stream as a single-entry archive (meta.stream: the api unwraps a .tar.br to the tar --- inside). Decoding through codecs/Brotli. The entry is named after opts.name without ".br" (else "data"). +-- inside). Decoding through codecs/compress/Brotli. The entry is named after opts.name without ".br" (else "data"). -- Supports: read (eager decompression). Not supported: write (no Brotli compressor). Brotli has no magic number: -- sniff accepts only data that decodes cleanly (the whole stream for small files, a 64 KB prefix for big ones), at a -- low confidence, so the extension decides between candidates. @@ -8,7 +8,7 @@ -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") -local Brotli = require("@formats/codecs/Brotli") +local Brotli = require("@formats/codecs/compress/Brotli") local Archive = require("@formats/containers/Archive") -- ------------------------------------------------------------------------------------------------ contract @@ -17,7 +17,7 @@ local Br = { category = "archive", extensions = { "br" }, mime = { "application/x-brotli" }, - deps = { "core/Err", "core/Bytes", "codecs/Brotli", "containers/Archive" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Brotli", "containers/Archive" }, caps = { decode = true, encode = false, stream = true }, } diff --git a/src/Formats/archive/bz2/init.luau b/src/Formats/archive/bz2/init.luau index 074bdc2..224aa33 100644 --- a/src/Formats/archive/bz2/init.luau +++ b/src/Formats/archive/bz2/init.luau @@ -1,14 +1,14 @@ --!strict --- archive/bz2: a .bz2 file as a single-stream archive: one entry, the decompressed data (codecs/Bzip2; concatenated +-- archive/bz2: a .bz2 file as a single-stream archive: one entry, the decompressed data (codecs/compress/Bzip2; concatenated -- streams are joined, as bzip2 -d does). The entry is named after the file without its .bz2 (".tbz2" -> ".tar"), -- else "data"; the api unwraps a .tar.bz2 into the tar inside (meta.stream). New in formats-luau. Not supported: --- writing (codecs/Bzip2 has no compressor), randomised blocks (bzip2 0.9.0 and older). +-- writing (codecs/compress/Bzip2 has no compressor), randomised blocks (bzip2 0.9.0 and older). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Archive = require("@formats/containers/Archive") -local Bzip2 = require("@formats/codecs/Bzip2") +local Bzip2 = require("@formats/codecs/compress/Bzip2") -- ------------------------------------------------------------------------------------------------ contract local Bz2 = { @@ -16,7 +16,7 @@ local Bz2 = { category = "archive", extensions = { "bz2", "tbz2", "tbz" }, mime = { "application/x-bzip2" }, - deps = { "core/Err", "core/Bytes", "containers/Archive", "codecs/Bzip2" }, + deps = { "core/Err", "core/Bytes", "containers/Archive", "codecs/compress/Bzip2" }, caps = { decode = true, encode = false, stream = true }, } diff --git a/src/Formats/archive/gzip/init.luau b/src/Formats/archive/gzip/init.luau index e5210ea..848ca95 100644 --- a/src/Formats/archive/gzip/init.luau +++ b/src/Formats/archive/gzip/init.luau @@ -3,13 +3,13 @@ -- file name without .gz, else "data"), with the header's MTIME; concatenated members decode as one stream, as gzip -d -- does. Writing: an Archive with one entry (or a buffer / string) becomes one member with FNAME and MTIME; an Archive -- with several entries is written as a tar inside the gzip (a .tar.gz). The api unwraps a .tar.gz / .tgz on load (the --- inner tar, meta.compression = "gzip"). Deflate is codecs/Deflate. Not supported: FHCRC verification. +-- inner tar, meta.compression = "gzip"). Deflate is codecs/compress/Deflate. Not supported: FHCRC verification. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Crc32 = require("@formats/core/Crc32") -local Deflate = require("@formats/codecs/Deflate") +local Deflate = require("@formats/codecs/compress/Deflate") local Archive = require("@formats/containers/Archive") local Tar = require("@formats/containers/Tar") @@ -19,7 +19,7 @@ local Gzip = { category = "archive", extensions = { "gz", "tgz", "gzip" }, mime = { "application/gzip" }, - deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/Deflate", "containers/Archive", "containers/Tar" }, + deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/compress/Deflate", "containers/Archive", "containers/Tar" }, caps = { decode = true, encode = true, stream = true }, } diff --git a/src/Formats/archive/xz/init.luau b/src/Formats/archive/xz/init.luau index cb0a07c..0f86278 100644 --- a/src/Formats/archive/xz/init.luau +++ b/src/Formats/archive/xz/init.luau @@ -1,6 +1,6 @@ --!strict -- archive/xz: .xz (xz file format 1.2) and .lzma ("LZMA alone") files, read as single-stream archives holding one --- entry (the decompressed data). Built on codecs/Lzma. Supports: concatenated streams, stream padding, every block +-- entry (the decompressed data). Built on codecs/compress/Lzma. Supports: concatenated streams, stream padding, every block -- layout, checks none / CRC-32 / CRC-64 (verified; SHA-256 is not verified), filters LZMA2, delta and the BCJ filters -- x86 / PowerPC / ARM / ARM-Thumb / SPARC / ARM64. Not supported: writing, IA-64 / RISC-V filters. -- The entry is named after the file (opts.name without .xz / .lzma; .txz -> .tar), else "data". meta.stream = true: @@ -10,7 +10,7 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") -local Lzma = require("@formats/codecs/Lzma") +local Lzma = require("@formats/codecs/compress/Lzma") local Archive = require("@formats/containers/Archive") -- ------------------------------------------------------------------------------------------------ contract @@ -19,7 +19,7 @@ local Xz = { category = "archive", extensions = { "xz", "txz", "lzma" }, mime = { "application/x-xz", "application/x-lzma" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Lzma", "containers/Archive" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Lzma", "containers/Archive" }, caps = { decode = true, encode = false, stream = true, filters = { "lzma2", "lzma", "delta", "x86", "powerpc", "arm", "armthumb", "sparc", "arm64" } }, } diff --git a/src/Formats/archive/zip/init.luau b/src/Formats/archive/zip/init.luau index 081a7e0..1aa8000 100644 --- a/src/Formats/archive/zip/init.luau +++ b/src/Formats/archive/zip/init.luau @@ -3,7 +3,7 @@ -- Absorbed from zip-luau 121d4b0 (same author, no third-party code; the reader, now containers/Zip) plus a new -- writer. Supports: reading stored and deflated entries (CRC-checked), ZIP64, data descriptors, archive comments, -- prefixed archives (self-extractors), UTF-8 names, case-insensitive / basename lookup; writing stored and deflated --- entries (codecs/Deflate), unchanged entries copied without recompressing, ZIP64 when needed. +-- entries (codecs/compress/Deflate), unchanged entries copied without recompressing, ZIP64 when needed. -- Not supported: encryption (traditional PKWARE or AES), compression methods other than store / deflate (bzip2, -- LZMA, zstd entries are listed but not readable), multi-disk archives. -- diff --git a/src/Formats/archive/zst/init.luau b/src/Formats/archive/zst/init.luau index af5eef6..e336e30 100644 --- a/src/Formats/archive/zst/init.luau +++ b/src/Formats/archive/zst/init.luau @@ -1,13 +1,13 @@ --!strict -- archive/zst: a Zstandard-compressed file (.zst, RFC 8878) as a single-stream archive holding one entry, decoded --- through codecs/Zstd. The entry is named after the file without its extension (opts.name; ".tzst" -> ".tar"), else +-- through codecs/compress/Zstd. The entry is named after the file without its extension (opts.name; ".tzst" -> ".tar"), else -- "data". The api unwraps it when the entry is itself an archive (.tar.zst loads as the tar). Read-only. -- Not supported: dictionaries, writing. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") -local Zstd = require("@formats/codecs/Zstd") +local Zstd = require("@formats/codecs/compress/Zstd") local Archive = require("@formats/containers/Archive") -- ------------------------------------------------------------------------------------------------ contract @@ -16,7 +16,7 @@ local Zst = { category = "archive", extensions = { "zst", "tzst" }, mime = { "application/zstd" }, - deps = { "core/Err", "core/Bytes", "codecs/Zstd", "containers/Archive" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Zstd", "containers/Archive" }, caps = { decode = true, encode = false, stream = true }, } diff --git a/src/Formats/audio/aac/init.luau b/src/Formats/audio/aac/init.luau index 21deaf5..9219ccd 100644 --- a/src/Formats/audio/aac/init.luau +++ b/src/Formats/audio/aac/init.luau @@ -1,6 +1,6 @@ --!strict -- audio/aac: raw AAC in ADTS framing (ISO/IEC 13818-7 / 14496-3 1.A.3), the .aac files encoders and radio streams --- write. Supports: reading AAC-LC through codecs/Aac (1 - 8 channels, every rate, multi-block frames, CRC-protected +-- write. Supports: reading AAC-LC through codecs/audio/Aac (1 - 8 channels, every rate, multi-block frames, CRC-protected -- headers skipped), a leading ID3v2 tag (skipped; its text frames become tags), resync after garbage, seeking (by -- frame), HE-AAC streams play their AAC-LC core. Not supported: writing (AAC encoding is out of scope), ADIF, LATM. @@ -8,8 +8,9 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") -local Pcm = require("@formats/codecs/Pcm") -local Aac = require("@formats/codecs/Aac") +local Pcm = require("@formats/codecs/audio/Pcm") +local Stream = require("@formats/codecs/audio/Stream") +local Aac = require("@formats/codecs/audio/Aac") -- ------------------------------------------------------------------------------------------------ contract local AacFormat = { @@ -17,7 +18,7 @@ local AacFormat = { category = "audio", extensions = { "aac", "adts" }, mime = { "audio/aac", "audio/aacp", "audio/x-aac" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Aac", "codecs/Pcm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Aac", "codecs/audio/Pcm", "codecs/audio/Stream" }, caps = { decode = true, encode = false, codecs = { "aac" }, streaming = true }, } @@ -168,11 +169,6 @@ function AacFormat.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, local id3 = id3Size(r.buf, r.base, r.limit) local tags = if id3 > 0 then id3Tags(r.buf, r.base, id3) else {} local buf = r.buf - local nextFrame = 1 - local pendPos, pendN = 0, 0 - local drop = 0 - local pos = 0 - local failed: Err.Err? = nil local out: any = { sampleRate = sr, channels = channels, @@ -181,74 +177,24 @@ function AacFormat.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, bitrate = if total > 0 then math.floor(bytes * 8 * sr / total) else 0, tags = tags, codec = "aac", - error = nil, } - local function fill(): boolean - while true do - if nextFrame > nframes then - return false - end - local i = nextFrame - nextFrame += 1 - local n, e = d:decode(buf, offs[i], sizes[i]) - if not n then - failed = e - out.error = e - return false - end - if drop >= n then - drop -= n - else - pendPos, pendN = drop, n - drop = 0 - return true - end - end - end - function out.read(_self: any, n: number, ob: buffer?): (buffer, number) - local want = math.max(0, math.floor(n)) - local need = want * channels * 4 - local res = if ob and buffer.len(ob) >= need then ob else buffer.create(need) - local got = 0 - local writef32 = buffer.writef32 - while got < want do - if pendPos >= pendN then - if failed or not fill() then - break - end - end - local take = math.min(want - got, pendN - pendPos) - local src = d.pcm - local q = got * channels * 4 - local s = pendPos * channels - for k = 1, take * channels do - writef32(res, q, src[s + k]) - q += 4 - end - pendPos += take - got += take - end - pos += got - return res, got - end - function out.seek(_self: any, seconds: number) - local target = math.clamp(math.floor(seconds * sr + 0.5), 0, total) - local f = target // 1024 -- frame holding the target (0-based) - local start = math.max(0, f - 1) -- one frame of pre-roll for the overlap - d:reset() - nextFrame = start + 1 - drop = target - start * 1024 - pendPos, pendN = 0, 0 - failed = nil - pos = target - end - function out.position(_self: any): number - return pos / sr - end - if nframes > 0 and not fill() and failed then - return nil, failed - end - return out, nil + -- 1024 frames per ADTS frame; one frame of pre-roll for the overlap when seeking + return Stream.packets(out, { + count = nframes, + start = function(i: number): number + return (i - 1) * 1024 + end, + decode = function(i: number): (number?, Err.Err?) + return d:decode(buf, offs[i], sizes[i]) + end, + pcm = function(): { number } + return d.pcm + end, + reset = function() + d:reset() + end, + preroll = 1, + }) end function AacFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) diff --git a/src/Formats/audio/aiff/init.luau b/src/Formats/audio/aiff/init.luau index baf8ad2..a0a4a8c 100644 --- a/src/Formats/audio/aiff/init.luau +++ b/src/Formats/audio/aiff/init.luau @@ -10,7 +10,8 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") -local Pcm = require("@formats/codecs/Pcm") +local Chunks = require("@formats/containers/Chunks") +local Pcm = require("@formats/codecs/audio/Pcm") -- ------------------------------------------------------------------------------------------------ contract local Aiff = { @@ -18,7 +19,7 @@ local Aiff = { category = "audio", extensions = { "aiff", "aif", "aifc", "afc" }, mime = { "audio/aiff", "audio/x-aiff" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "containers/Chunks" }, caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, lossy = false }, } @@ -159,12 +160,12 @@ local function parse(r: Bytes.Reader): (Info?, Err.Err?) local ssnd: number? = nil local ssndLen = 0 local tags: Types.Tags = {} - local p = base + 12 - while p + 8 <= formEnd do - local id = buffer.readstring(b, p, 4) - local len = bit32.byteswap(buffer.readu32(b, p + 4)) - local d = p + 8 - local avail = math.min(len, limit - d) + -- (walked to the end of the data: a FORM size that undercounts still reads the last chunk's body) + for _, c in Chunks.walk(b, base + 12, limit, Chunks.IFF) do + local id, len, d, avail, p = c.id, c.declared, c.offset, c.avail, c.start + if p + 8 > formEnd then + break + end if id == "COMM" then if avail < 18 or (aifc and avail < 22) then return nil, Err.new(Err.TRUNCATED, "COMM chunk too short", p) @@ -219,7 +220,6 @@ local function parse(r: Bytes.Reader): (Info?, Err.Err?) if len > formEnd - d then break end - p = d + len + len % 2 end if not comm or not info then return nil, Err.new(Err.CORRUPT, "no COMM chunk", base) diff --git a/src/Formats/audio/au/init.luau b/src/Formats/audio/au/init.luau index 08a45ab..dd52cff 100644 --- a/src/Formats/audio/au/init.luau +++ b/src/Formats/audio/au/init.luau @@ -9,7 +9,7 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") -local Pcm = require("@formats/codecs/Pcm") +local Pcm = require("@formats/codecs/audio/Pcm") -- ------------------------------------------------------------------------------------------------ contract local Au = { @@ -17,7 +17,7 @@ local Au = { category = "audio", extensions = { "au", "snd" }, mime = { "audio/basic", "audio/x-au" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm" }, caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, lossy = false }, } diff --git a/src/Formats/audio/caf/init.luau b/src/Formats/audio/caf/init.luau index 48769f9..fd46e96 100644 --- a/src/Formats/audio/caf/init.luau +++ b/src/Formats/audio/caf/init.luau @@ -1,6 +1,6 @@ --!strict -- audio/caf: Apple Core Audio Format (CAF 1.0, Apple's "Core Audio Format Specification"). Supports reading linear --- PCM (8 / 16 / 24 / 32-bit integer, 32 / 64-bit float, big / little endian), ALAC (codecs/Alac), AAC-LC (codecs/Aac, +-- PCM (8 / 16 / 24 / 32-bit integer, 32 / 64-bit float, big / little endian), ALAC (codecs/audio/Alac), AAC-LC (codecs/audio/Aac, -- kuki esds), mu-law and A-law; the packet table (pakt) with priming / remainder trimming, a data chunk of unknown -- size (-1), info chunk tags; seeking. Writing linear PCM (16 / 24-bit big endian, 32-bit float) and ALAC (16 / 20 / -- 24-bit) with info tags. Not supported: IMA4, other compressed formats (UNSUPPORTED). @@ -9,9 +9,11 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") -local Pcm = require("@formats/codecs/Pcm") -local Aac = require("@formats/codecs/Aac") -local Alac = require("@formats/codecs/Alac") +local Chunks = require("@formats/containers/Chunks") +local Pcm = require("@formats/codecs/audio/Pcm") +local Stream = require("@formats/codecs/audio/Stream") +local Aac = require("@formats/codecs/audio/Aac") +local Alac = require("@formats/codecs/audio/Alac") -- ------------------------------------------------------------------------------------------------ contract local Caf = { @@ -19,7 +21,7 @@ local Caf = { category = "audio", extensions = { "caf", "caff" }, mime = { "audio/x-caf" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Aac", "codecs/Alac", "codecs/Pcm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Aac", "codecs/audio/Alac", "codecs/audio/Pcm", "codecs/audio/Stream", "containers/Chunks" }, caps = { decode = true, encode = true, codecs = { "pcm", "alac", "aac", "ulaw", "alaw" }, encodeCodecs = { "pcm", "alac" }, tags = true, streaming = true }, } @@ -146,26 +148,15 @@ local function parse(r: Bytes.Reader, o: DecodeOptions): (Parsed?, Err.Err?) if Caf.sniff(r) == 0 then return nil, Err.new(Err.CORRUPT, "not a CAF file", r.base) end - r:seek(8) local p: Parsed = { desc = nil :: any, dataStart = 0, dataEnd = 0, priming = 0, remainder = 0, tags = {} } local haveData = false - while r:remaining() >= 12 do - local typ = r:string(4) - local size = r:i64be() - local start = r.pos - if size == -1 and typ == "data" then - size = r.limit - start - end - if size < 0 then - return nil, Err.new(Err.CORRUPT, "bad chunk size", start - 12) - end - local stop = start + size - if stop > r.limit then - if typ ~= "data" then - return nil, Err.new(Err.TRUNCATED, "chunk '" .. typ .. "' runs past the end", start - 12) - end - stop = r.limit -- a truncated data chunk: play what is there + -- 64-bit big-endian chunk sizes; the data chunk may say -1 (= to the end) or run past a truncated file + for _, ch in Chunks.walk(r.buf, r.base + 8, r.limit, { bigEndian = true, sizeBytes = 8, openEnded = { data = true } }) do + local typ, start = ch.id, ch.offset + if ch.truncated and typ ~= "data" then + return nil, Err.new(Err.TRUNCATED, "chunk '" .. typ .. "' runs past the end", ch.start) end + local stop = start + ch.avail local c = Bytes.reader(r.buf, start, stop - start) if typ == "desc" then p.desc = { @@ -226,7 +217,6 @@ local function parse(r: Bytes.Reader, o: DecodeOptions): (Parsed?, Err.Err?) p.tags[INFO_TAGS[string.lower(k)] or string.lower(k)] = v end end - r.pos = stop if typ == "data" and stop >= r.limit then break end @@ -456,12 +446,6 @@ function Caf.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.E stopAt = math.max(skip, total - p.remainder) end local frames = math.max(0, stopAt - skip) - local nextPacket = 1 - local decoded = 0 - local pendPos, pendN = 0, 0 - local dropUntil = skip - local pos = 0 - local failed: Err.Err? = nil local dec: any = { sampleRate = rate, channels = ch, @@ -471,87 +455,21 @@ function Caf.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.E tags = p.tags, codec = src.codec, bitsPerSample = src.bits, - error = nil, } - local function fill(): boolean - while true do - if nextPacket > src.packetCount or decoded >= stopAt then - return false - end - local i = nextPacket - nextPacket += 1 - local start = starts[i] - local n, e = src.decode(i) - if not n then - failed = e - dec.error = e - return false - end - decoded = start + n - local a = math.max(start, dropUntil) - local b = math.min(decoded, stopAt) - if b > a then - pendPos, pendN = a - start, b - start - return true - end - end - end - function dec.read(_self: any, n: number, out: buffer?): (buffer, number) - local want = math.max(0, math.floor(n)) - local need = want * ch * 4 - local ob = if out and buffer.len(out) >= need then out else buffer.create(need) - local got = 0 - local writef32 = buffer.writef32 - while got < want do - if pendPos >= pendN then - if failed or not fill() then - break - end - end - local take = math.min(want - got, pendN - pendPos) - local q = got * ch * 4 - local sidx = pendPos * ch - local pcm = src.pcm - for k = 1, take * ch do - writef32(ob, q, pcm[sidx + k]) - q += 4 - end - pendPos += take - got += take - end - pos += got - return ob, got - end - function dec.seek(_self: any, seconds: number) - local target = math.clamp(math.floor(seconds * rate + 0.5), 0, frames) + skip - local lo, hi, found = 1, src.packetCount, 1 - while lo <= hi do - local mid = (lo + hi) // 2 - if starts[mid] <= target then - found = mid - lo = mid + 1 - else - hi = mid - 1 - end - end - if src.codec == "aac" then - found = math.max(1, found - 1) - end - src.reset() - nextPacket = found - decoded = starts[found] - dropUntil = target - pendPos, pendN = 0, 0 - failed = nil - pos = target - skip - end - function dec.position(_self: any): number - return pos / rate - end - if src.packetCount > 0 and frames > 0 and not fill() and failed then - return nil, failed - end - return dec, nil + return Stream.packets(dec, { + count = src.packetCount, + start = function(i: number): number + return starts[i] + end, + decode = src.decode, + pcm = function(): { number } + return src.pcm + end, + reset = src.reset, + skip = skip, + stop = stopAt, + preroll = if src.codec == "aac" then 1 else 0, + }) end function Caf.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) diff --git a/src/Formats/audio/flac/Encode.luau b/src/Formats/audio/flac/Encode.luau index ecc187c..3b3c99b 100644 --- a/src/Formats/audio/flac/Encode.luau +++ b/src/Formats/audio/flac/Encode.luau @@ -8,11 +8,11 @@ -- libFLAC's precision table, the order estimated from the prediction error or searched exhaustively at -8), wasted -- bits; Rice / Rice2 partitions with the partition order and parameters searched per subframe. Frames carry CRC-8 / -- CRC-16; STREAMINFO carries the sizes, total samples and the MD5 of the PCM; VORBIS_COMMENT from the tags; an optional --- SEEKTABLE. Streams: input blocks are pulled from a codecs/Pcm Source, so a Decoder is encoded without decoding it +-- SEEKTABLE. Streams: input blocks are pulled from a codecs/audio/Pcm Source, so a Decoder is encoded without decoding it -- whole. Never throws: bad options are rejected by audio/flac before calling in. local Bits = require("@formats/core/Bits") local Md5 = require("@formats/core/Md5") -local VorbisComment = require("@formats/codecs/VorbisComment") +local VorbisComment = require("@formats/codecs/audio/VorbisComment") local Frame = require("@formats/audio/flac/Frame") local Encode = {} diff --git a/src/Formats/audio/flac/Meta.luau b/src/Formats/audio/flac/Meta.luau index 1b1508b..ff4abdb 100644 --- a/src/Formats/audio/flac/Meta.luau +++ b/src/Formats/audio/flac/Meta.luau @@ -4,7 +4,7 @@ -- audio/flac/Meta: FLAC metadata blocks: STREAMINFO, SEEKTABLE, VORBIS_COMMENT and PICTURE (its fields are listed, the image is -- left in place); every other block is skipped. Nothing throws: bad data gives nil, err. -- Absorbed from flac-luau 7083d0d (same author, no third-party code). -local VorbisComment = require("@formats/codecs/VorbisComment") +local VorbisComment = require("@formats/codecs/audio/VorbisComment") local readu8, readu32 = buffer.readu8, buffer.readu32 diff --git a/src/Formats/audio/flac/init.luau b/src/Formats/audio/flac/init.luau index 26e321c..d3b7048 100644 --- a/src/Formats/audio/flac/init.luau +++ b/src/Formats/audio/flac/init.luau @@ -21,7 +21,7 @@ local Types = require("@formats/Types") local Ogg = require("@formats/containers/Ogg") local Stream = require("@formats/audio/flac/Stream") local Encode = require("@formats/audio/flac/Encode") -local Pcm = require("@formats/codecs/Pcm") +local Pcm = require("@formats/codecs/audio/Pcm") -- ------------------------------------------------------------------------------------------------ contract local Flac = { @@ -29,7 +29,7 @@ local Flac = { category = "audio", extensions = { "flac", "oga" }, mime = { "audio/flac", "audio/x-flac" }, - deps = { "core/Err", "core/Bytes", "core/Bits", "Types", "containers/Ogg", "core/Md5", "codecs/Pcm", "codecs/VorbisComment" }, + deps = { "core/Err", "core/Bytes", "core/Bits", "Types", "containers/Ogg", "core/Md5", "codecs/audio/Pcm", "codecs/audio/VorbisComment" }, caps = { decode = true, encode = true, streaming = true, depths = { 4, 8, 12, 16, 20, 24, 32 }, ogg = true, seek = true }, } diff --git a/src/Formats/audio/m4a/init.luau b/src/Formats/audio/m4a/init.luau index babc9bd..0a455e7 100644 --- a/src/Formats/audio/m4a/init.luau +++ b/src/Formats/audio/m4a/init.luau @@ -1,6 +1,6 @@ --!strict -- audio/m4a: MPEG-4 audio files (M4A / M4B / MP4 / MOV audio tracks) through containers/IsoBmff. Supports: reading --- AAC-LC (codecs/Aac; HE-AAC files play their AAC-LC core at the core rate) and ALAC (codecs/Alac) tracks, gapless +-- AAC-LC (codecs/audio/Aac; HE-AAC files play their AAC-LC core at the core rate) and ALAC (codecs/audio/Alac) tracks, gapless -- trimming through the edit list (encoder priming / padding), seeking, iTunes tags and cover art (dec.pictures); -- writing ALAC (16 / 20 / 24-bit, 1 - 8 channels) with tags and cover art. Not supported: writing AAC, other codecs -- inside MP4 (MP3 / Opus / FLAC / AC-3: UNSUPPORTED), encrypted files. @@ -9,10 +9,11 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") -local Pcm = require("@formats/codecs/Pcm") +local Pcm = require("@formats/codecs/audio/Pcm") +local Stream = require("@formats/codecs/audio/Stream") local IsoBmff = require("@formats/containers/IsoBmff") -local Aac = require("@formats/codecs/Aac") -local Alac = require("@formats/codecs/Alac") +local Aac = require("@formats/codecs/audio/Aac") +local Alac = require("@formats/codecs/audio/Alac") -- ------------------------------------------------------------------------------------------------ contract local M4a = { @@ -20,7 +21,7 @@ local M4a = { category = "audio", extensions = { "m4a", "m4b", "m4r" }, mime = { "audio/mp4", "audio/x-m4a", "audio/m4a" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/IsoBmff", "codecs/Aac", "codecs/Alac", "codecs/Pcm" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/IsoBmff", "codecs/audio/Aac", "codecs/audio/Alac", "codecs/audio/Pcm", "codecs/audio/Stream" }, caps = { decode = true, encode = true, codecs = { "aac", "alac" }, encodeCodecs = { "alac" }, tags = true, streaming = true }, } @@ -181,15 +182,6 @@ function M4a.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.E end local frames = math.max(0, total - skip) local buf = r.buf - -- streaming state - local nextPacket = 1 - local decoded = 0 -- frames produced by the packets decoded so far (before trimming) - local pend, pendPos, pendN = p.pcm, 0, 0 -- the current packet: frames pendPos .. pendN - 1 not yet returned - local dropUntil = skip -- absolute frame index of the first frame to return - local stopAt = total - local pos = 0 -- frames returned - local failed: Err.Err? = nil - local dec: any = { sampleRate = sr, channels = channels, @@ -201,103 +193,30 @@ function M4a.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.E codec = t.codec, track = t, movie = movie, - error = nil, } local bytes = 0 for i = 1, t.sampleCount do bytes += t.sizes[i] end dec.bitrate = if frames > 0 then math.floor(bytes * 8 * sr / frames) else (t.bitrate or 0) - - -- decode the next packet into pend; false at the end / on an error - local function fill(): boolean - while true do - if nextPacket > t.sampleCount or decoded >= stopAt then - return false - end - local i = nextPacket - nextPacket += 1 - local start = decoded - local n, e = p.decode(buf, t.offsets[i], t.sizes[i]) - if not n then - failed = e - dec.error = e - return false - end - decoded += n - -- the part of this packet inside [dropUntil, stopAt) - local a = math.max(start, dropUntil) - local b = math.min(decoded, stopAt) - if b > a then - pendPos = a - start - pendN = b - start - return true - end - end - end - - function dec.read(_self: any, n: number, out: buffer?): (buffer, number) - local want = math.max(0, math.floor(n)) - local need = want * channels * 4 - local ob = if out and buffer.len(out) >= need then out else buffer.create(need) - local got = 0 - local writef32 = buffer.writef32 - while got < want do - if pendPos >= pendN then - if failed or not fill() then - break - end - end - local take = math.min(want - got, pendN - pendPos) - local src = pend - local o = got * channels * 4 - local s = pendPos * channels - for k = 1, take * channels do - writef32(ob, o, src[s + k]) - o += 4 - end - pendPos += take - got += take - end - pos += got - return ob, got - end - - function dec.seek(_self: any, seconds: number) - local target = math.clamp(math.floor(seconds * sr + 0.5), 0, frames) + skip -- absolute frame - -- the last packet starting at or before the target, minus one for the codec's overlap (AAC) - local ticks = target / tickScale - local lo, hi, found = 1, t.sampleCount, 1 - while lo <= hi do - local mid = (lo + hi) // 2 - if t.dts[mid] <= ticks then - found = mid - lo = mid + 1 - else - hi = mid - 1 - end - end - local startPacket = if t.codec == "aac" then math.max(1, found - 1) else found - p.reset() - nextPacket = startPacket - decoded = math.floor((t.dts[startPacket] or 0) * tickScale + 0.5) - dropUntil = math.max(target, skip) - pendPos, pendN = 0, 0 - failed = nil - pos = target - skip - end - - function dec.position(_self: any): number - return pos / sr - end - - -- prime: surface a broken first packet as an open error - if t.sampleCount > 0 and frames > 0 then - if not fill() and failed then - return nil, failed - end - end - return dec, nil + -- packet start frames (media ticks -> frames); one AAC packet of pre-roll for the overlap when seeking + return Stream.packets(dec, { + count = t.sampleCount, + start = function(i: number): number + return math.floor((t.dts[i] or (t.dts[t.sampleCount] or 0) + (t.durations[t.sampleCount] or 0)) * tickScale + 0.5) + end, + decode = function(i: number): (number?, Err.Err?) + return p.decode(buf, t.offsets[i], t.sizes[i]) + end, + pcm = function(): { number } + return p.pcm + end, + reset = p.reset, + skip = skip, + stop = total, + preroll = if t.codec == "aac" then 1 else 0, + cumulative = true, + }) end -- decode(r, opts?) -> Types.Audio | nil, Err (the whole stream, tags, cover pictures in meta.pictures) diff --git a/src/Formats/audio/mp3/init.luau b/src/Formats/audio/mp3/init.luau index 5029c4e..a281cf3 100644 --- a/src/Formats/audio/mp3/init.luau +++ b/src/Formats/audio/mp3/init.luau @@ -6,7 +6,7 @@ -- past garbage, mono / stereo switches (upmixed), ID3v2.2 / 2.3 / 2.4 and ID3v1 / 1.1 tags (APEv2 skipped). -- Float output (minimp3's MINIMP3_FLOAT_OUTPUT scalar path). Encode (ws-audio, audio/mp3/Encode3 + Encode2): layer III -- (shine-style CBR, MPEG-1 / 2 / 2.5) and layer II (MPEG-1 / 2), mono / stereo / joint stereo, an ID3v2.4 tag from --- the tags; input at rates the layer cannot hold is resampled (codecs/Resample). Not supported: MPEG-2 multichannel +-- the tags; input at rates the layer cannot hold is resampled (codecs/audio/Resample). Not supported: MPEG-2 multichannel -- extension, CRC checks, VBR / Xing output. -- -- local dec = Mp3.open(Bytes.reader(buf)) -- the streaming Types.Decoder (+ layer, version, vbr, delay, @@ -23,8 +23,8 @@ local Tags = require("@formats/audio/mp3/Tags") local Stream = require("@formats/audio/mp3/Stream") local Encode3 = require("@formats/audio/mp3/Encode3") local Encode2 = require("@formats/audio/mp3/Encode2") -local Pcm = require("@formats/codecs/Pcm") -local Resample = require("@formats/codecs/Resample") +local Pcm = require("@formats/codecs/audio/Pcm") +local Resample = require("@formats/codecs/audio/Resample") -- ------------------------------------------------------------------------------------------------ contract local Mp3 = { @@ -32,7 +32,7 @@ local Mp3 = { category = "audio", extensions = { "mp3", "mp2", "mp1", "mpga" }, mime = { "audio/mpeg", "audio/mp3", "audio/mpa" }, - deps = { "core/Err", "core/Bytes", "core/Bits", "Types", "codecs/Pcm", "codecs/Resample" }, + deps = { "core/Err", "core/Bytes", "core/Bits", "Types", "codecs/audio/Pcm", "codecs/audio/Resample" }, caps = { decode = true, encode = true, streaming = true, seek = true, layers = { 1, 2, 3 }, encodeLayers = { 2, 3 }, channels = 2 }, } @@ -48,8 +48,8 @@ export type EncodeOptions = { -- "mono" for mono input; layer II has no joint stereo (intensity) and writes "joint" as "stereo" id3: boolean?, -- write an ID3v2.4 tag from the tags (default true when there are tags) sampleRate: number?, -- output rate (one the layer holds); default the input rate if possible, else the nearest - -- higher one (input at other rates is resampled through codecs/Resample) - resampleQuality: ("low" | "medium" | "high")?, -- codecs/Resample quality (default "medium") + -- higher one (input at other rates is resampled through codecs/audio/Resample) + resampleQuality: ("low" | "medium" | "high")?, -- codecs/audio/Resample quality (default "medium") } -- ------------------------------------------------------------------------------------------------ constants @@ -173,7 +173,7 @@ function Mp3.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end local Enc = if layer == 3 then Encode3 else Encode2 -- the output rate: opts.sampleRate, else the input's when the layer has it, else the nearest rate above it (else - -- the highest); other input rates go through codecs/Resample + -- the highest); other input rates go through codecs/audio/Resample local rate = o.sampleRate or src.sampleRate if o.sampleRate and not Enc.RATES[o.sampleRate] then return nil, Err.new(Err.ARG, string.format("layer %d cannot hold %s Hz", layer, tostring(o.sampleRate))) diff --git a/src/Formats/audio/opus/Celt.luau b/src/Formats/audio/opus/Celt.luau index 81a6c68..f979aca 100644 --- a/src/Formats/audio/opus/Celt.luau +++ b/src/Formats/audio/opus/Celt.luau @@ -7,7 +7,7 @@ -- -- Arrays are Luau tables of numbers. All normalised-band data (X, Y, the folding memory `norm` and the scratch -- copies) lives in one table W, and the "pointers" of the C code are 0-based offsets into it. -local RD = require("@formats/codecs/RangeCoder/Decoder") +local RD = require("@formats/codecs/entropy/RangeCoder/Decoder") local Mdct = require("@formats/audio/opus/Mdct") local T = require("@formats/audio/opus/CeltTables") diff --git a/src/Formats/audio/opus/CeltEncoder.luau b/src/Formats/audio/opus/CeltEncoder.luau index b4891a8..662bd69 100644 --- a/src/Formats/audio/opus/CeltEncoder.luau +++ b/src/Formats/audio/opus/CeltEncoder.luau @@ -5,11 +5,11 @@ -- bit rate, long MDCTs only (no transient detection), no pitch pre-filter, normal spreading, default allocation trim, -- mono, or stereo as mid / side per band (the angle, intensity when it has no bits; dual L / R stereo on request). The bitstream side is a port of the libopus 1.6 encoder paths -- (celt_encoder.c, quant_bands.c, laplace.c, rate.c, bands.c, vq.c, cwrs.c; BSD: licenses/libopus-BSD.txt) that --- mirror audio/opus/Celt's decoder step for step; the analysis is simplified. The MDCT is codecs/Mdct. +-- mirror audio/opus/Celt's decoder step for step; the analysis is simplified. The MDCT is codecs/audio/Mdct. -- Never throws. -local RE = require("@formats/codecs/RangeCoder/Encoder") +local RE = require("@formats/codecs/entropy/RangeCoder/Encoder") local T = require("@formats/audio/opus/CeltTables") -local Mdct = require("@formats/codecs/Mdct") +local Mdct = require("@formats/codecs/audio/Mdct") local CeltEncoder = {} diff --git a/src/Formats/audio/opus/Decoder.luau b/src/Formats/audio/opus/Decoder.luau index c4fc928..b93f0c1 100644 --- a/src/Formats/audio/opus/Decoder.luau +++ b/src/Formats/audio/opus/Decoder.luau @@ -4,7 +4,7 @@ -- audio/opus/Decoder: The Opus decoder proper (libopus src/opus_decoder.c and opus_multistream_decoder.c): per-frame mode switching -- between SILK, hybrid and CELT, the redundant CELT frames of mode transitions, cross-fades, PLC fallbacks, the -- multi-frame packet loop and multistream (channel mapping) decoding. Output is 48 kHz float in Luau arrays. -local RD = require("@formats/codecs/RangeCoder/Decoder") +local RD = require("@formats/codecs/entropy/RangeCoder/Decoder") local Packet = require("@formats/audio/opus/Packet") local Celt = require("@formats/audio/opus/Celt") local Silk = require("@formats/audio/opus/Silk") diff --git a/src/Formats/audio/opus/Encode.luau b/src/Formats/audio/opus/Encode.luau index 971d872..f214abd 100644 --- a/src/Formats/audio/opus/Encode.luau +++ b/src/Formats/audio/opus/Encode.luau @@ -2,14 +2,14 @@ -- audio/opus/Encode: Ogg Opus writing (RFC 7845) around audio/opus/CeltEncoder: CELT-only packets (TOC config 31: -- full band, 20 ms, code 0), OpusHead (mapping family 0, the pre-skip = the encoder's delay), OpusTags (vendor + -- the tags as Vorbis comments), granule positions with end trimming, pages through containers/Ogg's muxer. Input at --- other rates is resampled to 48 kHz (codecs/Resample); the input is a Types.Audio or a Decoder (codecs/Pcm). New in +-- other rates is resampled to 48 kHz (codecs/audio/Resample); the input is a Types.Audio or a Decoder (codecs/audio/Pcm). New in -- formats-luau. local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Ogg = require("@formats/containers/Ogg") -local Pcm = require("@formats/codecs/Pcm") -local Resample = require("@formats/codecs/Resample") -local VorbisComment = require("@formats/codecs/VorbisComment") +local Pcm = require("@formats/codecs/audio/Pcm") +local Resample = require("@formats/codecs/audio/Resample") +local VorbisComment = require("@formats/codecs/audio/VorbisComment") local CeltEncoder = require("@formats/audio/opus/CeltEncoder") local Encode = {} @@ -42,7 +42,7 @@ function Encode.encode(value: any, opts: Options?): (buffer?, Err.Err?) if type(bitrate) ~= "number" or bitrate < 6000 or bitrate > 510000 then return nil, Err.new(Err.ARG, "bitrate 6000 .. 510000") end - -- the whole input at 48 kHz (codecs/Resample for other rates), then as floats + -- the whole input at 48 kHz (codecs/audio/Resample for other rates), then as floats if rate ~= 48000 then local rs, rerr = Resample.source(src, 48000) if not rs then diff --git a/src/Formats/audio/opus/Mdct.luau b/src/Formats/audio/opus/Mdct.luau index 9143cb5..4fff2ca 100644 --- a/src/Formats/audio/opus/Mdct.luau +++ b/src/Formats/audio/opus/Mdct.luau @@ -4,7 +4,7 @@ -- audio/opus/Mdct: CELT inverse MDCT (libopus celt/mdct.c clt_mdct_backward) over a mixed-radix complex FFT (a port of the -- kiss_fft stages used by libopus: radix 5, 3, 4 and 2). The 48 kHz mode uses N = 1920 >> shift for -- shift = 0..3 (FFT sizes 480, 240, 120, 60). Arrays are Luau tables of numbers, 1-based. --- Why not codecs/Mdct (measured by the cleanup pass): the shared transform computes the full N-sample IMDCT through a +-- Why not codecs/audio/Mdct (measured by the cleanup pass): the shared transform computes the full N-sample IMDCT through a -- DCT-IV, of which CELT keeps the middle N / 2, so routing the decoder through it made CELT decoding 2-3x slower -- (luau: 25 -> 54-76 ms for 3 s of 32 kbps stereo) and changed the output bits (same SNR against opusdec). This -- fused libopus port (pre-rotation, a kiss_fft with fixed factors, post-rotation, TDAC) stays private. diff --git a/src/Formats/audio/opus/Silk.luau b/src/Formats/audio/opus/Silk.luau index 7c76401..f85d798 100644 --- a/src/Formats/audio/opus/Silk.luau +++ b/src/Formats/audio/opus/Silk.luau @@ -14,7 +14,7 @@ -- -- Fixed-point emulation: all values are Luau numbers holding C int32 / int16 values. Products of two int32 values -- (64-bit in C) are split so that every intermediate stays below 2^53 and therefore exact. -local RD = require("@formats/codecs/RangeCoder/Decoder") +local RD = require("@formats/codecs/entropy/RangeCoder/Decoder") local T = require("@formats/audio/opus/SilkTables") local icdf = RD.icdf diff --git a/src/Formats/audio/opus/init.luau b/src/Formats/audio/opus/init.luau index b1d213d..6a98cea 100644 --- a/src/Formats/audio/opus/init.luau +++ b/src/Formats/audio/opus/init.luau @@ -24,9 +24,9 @@ local Types = require("@formats/Types") local Ogg = require("@formats/containers/Ogg") local Decoder = require("@formats/audio/opus/Decoder") local Packet = require("@formats/audio/opus/Packet") -local VorbisComment = require("@formats/codecs/VorbisComment") -local Pcm = require("@formats/codecs/Pcm") -local RangeDecoder = require("@formats/codecs/RangeCoder/Decoder") +local VorbisComment = require("@formats/codecs/audio/VorbisComment") +local Pcm = require("@formats/codecs/audio/Pcm") +local RangeDecoder = require("@formats/codecs/entropy/RangeCoder/Decoder") local Celt = require("@formats/audio/opus/Celt") local Silk = require("@formats/audio/opus/Silk") local Encode = require("@formats/audio/opus/Encode") @@ -37,7 +37,7 @@ local Opus = { category = "audio", extensions = { "opus" }, mime = { "audio/opus", "audio/ogg" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct", "codecs/RangeCoder/Decoder", "codecs/RangeCoder/Encoder", "codecs/Pcm", "codecs/Resample", "codecs/VorbisComment" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/audio/Mdct", "codecs/entropy/RangeCoder/Decoder", "codecs/entropy/RangeCoder/Encoder", "codecs/audio/Pcm", "codecs/audio/Resample", "codecs/audio/VorbisComment" }, caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255, rates = { 48000 }, encodeModes = { "celt" }, encodeChannels = 2 }, } @@ -126,7 +126,7 @@ local function parseHead(b: buffer, off: number, size: number): (Head?, string?) return head, nil end --- OpusTags (RFC 7845 section 5.2) -> vendor, tags (codecs/VorbisComment: lower-case keys, repeated fields joined +-- OpusTags (RFC 7845 section 5.2) -> vendor, tags (codecs/audio/VorbisComment: lower-case keys, repeated fields joined -- with "; "), the raw fields local function parseTags(b: buffer, off: number, size: number): (string, { [string]: string }, { VorbisComment.Field }) if size < 16 or buffer.readstring(b, off, 8) ~= "OpusTags" then @@ -372,7 +372,7 @@ function Opus.open(r: any, opts: OpenOptions?): (any, Err.Err?) vendor = vendor, tags = tags, comments = rawTags, - -- mapping family 1 is in Vorbis channel order; the output is WAVE order (codecs/Pcm) + -- mapping family 1 is in Vorbis channel order; the output is WAVE order (codecs/audio/Pcm) order = if not downmix and head.mappingFamily == 1 and head.channels > 2 then Pcm.WAVE_FROM_VORBIS[head.channels] else nil, sampleRate = SAMPLE_RATE, channels = if downmix then 2 else head.channels, diff --git a/src/Formats/audio/voc/init.luau b/src/Formats/audio/voc/init.luau index 3feca49..66e72ac 100644 --- a/src/Formats/audio/voc/init.luau +++ b/src/Formats/audio/voc/init.luau @@ -11,7 +11,7 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") -local Pcm = require("@formats/codecs/Pcm") +local Pcm = require("@formats/codecs/audio/Pcm") -- ------------------------------------------------------------------------------------------------ contract local Voc = { @@ -19,7 +19,7 @@ local Voc = { category = "audio", extensions = { "voc" }, mime = { "audio/x-voc" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm" }, caps = { decode = true, encode = true, streaming = true, depths = { 8, 16 }, lossy = false }, } diff --git a/src/Formats/audio/vorbis/Encode.luau b/src/Formats/audio/vorbis/Encode.luau index e1ce3ad..5483130 100644 --- a/src/Formats/audio/vorbis/Encode.luau +++ b/src/Formats/audio/vorbis/Encode.luau @@ -3,16 +3,16 @@ --!optimize 2 -- audio/vorbis/Encode: a basic but valid Vorbis I encoder in Ogg. New code written from the Vorbis I specification -- (no libvorbis code). Design: long blocks only (2048 samples; blocksize 0 is declared as 256 but never used), the --- Vorbis window, the MDCT (codecs/Mdct, scale 4/N for the decoder's unscaled IMDCT); one floor 1 per channel with a +-- Vorbis window, the MDCT (codecs/audio/Mdct, scale 4/N for the decoder's unscaled IMDCT); one floor 1 per channel with a -- fixed post list of 30 points (bisection order, multiplier 2) fitted to the spectral envelope minus a quality- -- dependent SNR, so the residue is quantized in steps of the floor; stereo square-polar coupling of the integer -- residues (lossless); residue type 2 with 16-values-per-channel partitions and six classes (silent, |v| <= 1, 4, 15, then -- cascades of x16 / x256 books for larger values); a fixed codebook set whose Huffman lengths come from Laplacian -- models computed at load time (codewords assigned exactly as the spec's decoder does). Granules are sample-exact -- (frames centred on multiples of 1024 from sample 0; the last page's granule trims the end). Never throws. -local Mdct = require("@formats/codecs/Mdct") -local Pcm = require("@formats/codecs/Pcm") -local VorbisComment = require("@formats/codecs/VorbisComment") +local Mdct = require("@formats/codecs/audio/Mdct") +local Pcm = require("@formats/codecs/audio/Pcm") +local VorbisComment = require("@formats/codecs/audio/VorbisComment") local Ogg = require("@formats/containers/Ogg") local Tables = require("@formats/audio/vorbis/Tables") diff --git a/src/Formats/audio/vorbis/Packet.luau b/src/Formats/audio/vorbis/Packet.luau index ca69d79..791745a 100644 --- a/src/Formats/audio/vorbis/Packet.luau +++ b/src/Formats/audio/vorbis/Packet.luau @@ -2,7 +2,7 @@ --!native --!optimize 2 -- audio/vorbis/Packet: Vorbis audio packet decoding (Vorbis I spec sections 4.3, 7, 8): mode and window shape, floor 1 --- curves, residue types 0 / 1 / 2, inverse channel coupling, the IMDCT (codecs/Mdct), windowing and overlap-add. +-- curves, residue types 0 / 1 / 2, inverse channel coupling, the IMDCT (codecs/audio/Mdct), windowing and overlap-add. -- Floors, residues and coupling are ported from stb_vorbis 1.22 vorbis_decode_packet_rest / decode_residue / -- do_floor / draw_line (public domain / MIT; see licenses/stb_vorbis-LICENSE.txt). The overlap follows libvorbis: -- each packet after the first returns the n_prev/4 + n_cur/4 samples between the centres of the two windows, so @@ -16,7 +16,7 @@ local Codebook = require("@formats/audio/vorbis/Codebook") local Setup = require("@formats/audio/vorbis/Setup") local Tables = require("@formats/audio/vorbis/Tables") -local Mdct = require("@formats/codecs/Mdct") +local Mdct = require("@formats/codecs/audio/Mdct") local Packet = {} diff --git a/src/Formats/audio/vorbis/init.luau b/src/Formats/audio/vorbis/init.luau index 8081e1c..917ad9f 100644 --- a/src/Formats/audio/vorbis/init.luau +++ b/src/Formats/audio/vorbis/init.luau @@ -1,6 +1,6 @@ --!strict -- audio/vorbis: Ogg Vorbis (Vorbis I specification, Xiph.Org; RFC 5215 for the Ogg mapping). The decoder is a Luau --- port of stb_vorbis 1.22 (public domain / MIT, licenses/stb_vorbis-LICENSE.txt) on containers/Ogg and codecs/Mdct, +-- port of stb_vorbis 1.22 (public domain / MIT, licenses/stb_vorbis-LICENSE.txt) on containers/Ogg and codecs/audio/Mdct, -- with libvorbis' sample-exact timing: start trimming from the first page's granule, end trimming from the last -- page's, granule-exact seeking (bisection, then decoding forward to a page boundary to recover the position). -- Supports: decode / open of any channel count (1..255), rates, block sizes 64..8192, floor 1, residues 0 / 1 / 2, @@ -18,8 +18,8 @@ local Ogg = require("@formats/containers/Ogg") local Setup = require("@formats/audio/vorbis/Setup") local Packet = require("@formats/audio/vorbis/Packet") local Encode = require("@formats/audio/vorbis/Encode") -local Pcm = require("@formats/codecs/Pcm") -local VorbisComment = require("@formats/codecs/VorbisComment") +local Pcm = require("@formats/codecs/audio/Pcm") +local VorbisComment = require("@formats/codecs/audio/VorbisComment") -- ------------------------------------------------------------------------------------------------ contract local Vorbis = { @@ -27,7 +27,7 @@ local Vorbis = { category = "audio", extensions = { "ogg", "oga" }, mime = { "audio/ogg", "audio/vorbis" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct", "codecs/Pcm", "codecs/VorbisComment" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/audio/Mdct", "codecs/audio/Pcm", "codecs/audio/VorbisComment" }, caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255 }, } @@ -41,7 +41,7 @@ export type EncodeOptions = { } -- ------------------------------------------------------------------------------------------------ constants --- waveOrder(channels) -> output channel c is Vorbis channel order[c] (codecs/Pcm; identity past 8 channels) +-- waveOrder(channels) -> output channel c is Vorbis channel order[c] (codecs/audio/Pcm; identity past 8 channels) local function waveOrder(ch: number): { number } local m = Pcm.WAVE_FROM_VORBIS[ch] if m then @@ -399,7 +399,7 @@ function Vorbis.open(r: any, opts: OpenOptions?): (Types.Decoder?, Err.Err?) tags = tags, vendor = vendor, ident = id, - -- WAVE channel order out (codecs/Pcm): output channel c is Vorbis channel order[c] + -- WAVE channel order out (codecs/audio/Pcm): output channel c is Vorbis channel order[c] order = waveOrder(id.channels), source = { format = "vorbis", diff --git a/src/Formats/audio/wav/init.luau b/src/Formats/audio/wav/init.luau index 1c1f60b..cf5e65c 100644 --- a/src/Formats/audio/wav/init.luau +++ b/src/Formats/audio/wav/init.luau @@ -18,7 +18,7 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") -local Pcm = require("@formats/codecs/Pcm") +local Pcm = require("@formats/codecs/audio/Pcm") local Riff = require("@formats/containers/Riff") local Codecs = require("@formats/audio/wav/Codecs") @@ -28,7 +28,7 @@ local Wav = { category = "audio", extensions = { "wav", "wave", "rf64", "bw64" }, mime = { "audio/wav", "audio/x-wav", "audio/wave", "audio/vnd.wave" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Riff", "codecs/Pcm" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Riff", "codecs/audio/Pcm" }, caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, rf64 = true }, } diff --git a/src/Formats/codecs/RangeCoder/init.luau b/src/Formats/codecs/RangeCoder/init.luau deleted file mode 100644 index 6affd3e..0000000 --- a/src/Formats/codecs/RangeCoder/init.luau +++ /dev/null @@ -1,13 +0,0 @@ ---!strict --- codecs/RangeCoder: the RFC 6716 range coder (libopus celt/entdec.c + entenc.c, BSD: licenses/libopus-BSD.txt): --- symbols range-coded from the front of a frame, raw bits from its back. Opus (CELT and SILK) uses it; LZMA, VP8 and --- CABAC have their own (different) binary coders. Moved here from audio/opus by the cleanup pass (same code). --- --- local RD = require("@formats/codecs/RangeCoder/Decoder") -- RD.new(buf, base, size), RD.icdf / bits / uint ... --- local RE = require("@formats/codecs/RangeCoder/Encoder") -- RE.new(size), RE.icdf / bits / uint, RE.done -local RangeCoder = { - Decoder = require("@formats/codecs/RangeCoder/Decoder"), - Encoder = require("@formats/codecs/RangeCoder/Encoder"), -} - -return RangeCoder diff --git a/src/Formats/codecs/Aac/Decode.luau b/src/Formats/codecs/audio/Aac/Decode.luau similarity index 98% rename from src/Formats/codecs/Aac/Decode.luau rename to src/Formats/codecs/audio/Aac/Decode.luau index 48ec969..fc51318 100644 --- a/src/Formats/codecs/Aac/Decode.luau +++ b/src/Formats/codecs/audio/Aac/Decode.luau @@ -1,14 +1,14 @@ --!strict --!native --!optimize 2 --- codecs/Aac/Decode: the AAC-LC raw_data_block decoder (ISO/IEC 14496-3 subpart 4): SCE / CPE / LFE / DSE / PCE / +-- codecs/audio/Aac/Decode: the AAC-LC raw_data_block decoder (ISO/IEC 14496-3 subpart 4): SCE / CPE / LFE / DSE / PCE / -- FIL / END elements, ics_info with window grouping, section data, scalefactors (with noise energies and intensity -- positions), pulse data, TNS, the eleven spectral codebooks with escapes, dequantisation, M/S and intensity stereo, -- perceptual noise substitution (FFmpeg's LCG so the noise matches it), the filterbank (sine / KBD windows, the four --- window sequences, IMDCT through codecs/Mdct, overlap-add). FIL extension payloads (SBR / PS) are reported to a hook +-- window sequences, IMDCT through codecs/audio/Mdct, overlap-add). FIL extension payloads (SBR / PS) are reported to a hook -- and otherwise skipped. Written from the standard; no third-party code. Never throws: returns nil, message. -local Mdct = require("@formats/codecs/Mdct") -local Tables = require("@formats/codecs/Aac/Tables") +local Mdct = require("@formats/codecs/audio/Mdct") +local Tables = require("@formats/codecs/audio/Aac/Tables") local readu32, byteswap, lshift, rshift, band = buffer.readu32, bit32.byteswap, bit32.lshift, bit32.rshift, bit32.band local floor, sqrt, abs = math.floor, math.sqrt, math.abs diff --git a/src/Formats/codecs/Aac/Tables.luau b/src/Formats/codecs/audio/Aac/Tables.luau similarity index 99% rename from src/Formats/codecs/Aac/Tables.luau rename to src/Formats/codecs/audio/Aac/Tables.luau index 65305fb..71bf6bc 100644 --- a/src/Formats/codecs/Aac/Tables.luau +++ b/src/Formats/codecs/audio/Aac/Tables.luau @@ -1,5 +1,5 @@ --!strict --- codecs/Aac/Tables: the AAC-LC tables of ISO/IEC 14496-3 (subpart 4, Annex 4.A): the scalefactor and the eleven +-- codecs/audio/Aac/Tables: the AAC-LC tables of ISO/IEC 14496-3 (subpart 4, Annex 4.A): the scalefactor and the eleven -- spectral Huffman codebooks (code, length per symbol), the scalefactor band offsets per sampling rate (1024 and 128 -- lines) and the TNS band limits. Transcribed from FFmpeg libavcodec/aactab.c (tables of the standard, no code; -- see licenses/NOTICE.md). Generated; do not edit. diff --git a/src/Formats/codecs/Aac/init.luau b/src/Formats/codecs/audio/Aac/init.luau similarity index 95% rename from src/Formats/codecs/Aac/init.luau rename to src/Formats/codecs/audio/Aac/init.luau index 15e586e..f6066fb 100644 --- a/src/Formats/codecs/Aac/init.luau +++ b/src/Formats/codecs/audio/Aac/init.luau @@ -1,15 +1,15 @@ --!strict --- codecs/Aac: AAC-LC decoder (ISO/IEC 14496-3 subpart 4, ISO/IEC 13818-7): the AudioSpecificConfig (with a program +-- codecs/audio/Aac: AAC-LC decoder (ISO/IEC 14496-3 subpart 4, ISO/IEC 13818-7): the AudioSpecificConfig (with a program -- config element, explicit and backward-compatible SBR signalling), ADTS headers, and raw_data_block decoding --- (codecs/Aac/Decode). A codec (layer 1): audio/m4a, audio/aac (ADTS), and later MP4 / MKV / MPEG-TS video build on it. --- Written from the standard (tables: codecs/Aac/Tables); no third-party code. +-- (codecs/audio/Aac/Decode). A codec (layer 1): audio/m4a, audio/aac (ADTS), and later MP4 / MKV / MPEG-TS video build on it. +-- Written from the standard (tables: codecs/audio/Aac/Tables); no third-party code. -- Supports: AAC-LC (object type 2) 1 - 8 channels, all sampling rates, long / short / start / stop windows, sine and KBD -- windows, M/S, intensity stereo, PNS, TNS, pulses. HE-AAC (SBR, PS: object types 5 / 29, or implicit SBR payloads) -- decodes its AAC-LC core at the core rate; `decoder.onExtension` receives every FIL extension payload (the hook for a -- later SBR / PS module), `decoder.sbr` says whether one was seen. Not supported: AAC Main prediction, LTP, SSR gain -- control, coupling channels, 960-sample frames, ER / USAC object types (UNSUPPORTED). -- --- local Aac = require("@formats/codecs/Aac") +-- local Aac = require("@formats/codecs/audio/Aac") -- local dec, err = Aac.decoder(asc) -- an AudioSpecificConfig (buffer) or { objectType, sfIndex, channels } -- local frames, err = dec:decode(buf, offset, length) -- one raw_data_block -> dec.pcm (frames * channels floats) -- local h = Aac.adts(buf, offset, limit) -- an ADTS header: { headerSize, frameSize, objectType, sfIndex, ... } @@ -17,7 +17,7 @@ -- Never throws: bad data returns nil, Err. local Err = require("@formats/core/Err") local Bits = require("@formats/core/Bits") -local Decode = require("@formats/codecs/Aac/Decode") +local Decode = require("@formats/codecs/audio/Aac/Decode") local Aac = {} diff --git a/src/Formats/codecs/Alac/Decode.luau b/src/Formats/codecs/audio/Alac/Decode.luau similarity index 98% rename from src/Formats/codecs/Alac/Decode.luau rename to src/Formats/codecs/audio/Alac/Decode.luau index 4b0a71c..031613a 100644 --- a/src/Formats/codecs/Alac/Decode.luau +++ b/src/Formats/codecs/audio/Alac/Decode.luau @@ -1,7 +1,7 @@ --!strict --!native --!optimize 2 --- codecs/Alac/Decode: the ALAC frame decoder: elements SCE / CPE / LFE / DSE / FIL / END, the adaptive Golomb-Rice +-- codecs/audio/Alac/Decode: the ALAC frame decoder: elements SCE / CPE / LFE / DSE / FIL / END, the adaptive Golomb-Rice -- residuals with zero runs, the adaptive FIR predictor (orders 0, 31 and 1 .. 30), stereo unmixing, shifted low bytes, -- uncompressed (escape) frames, 16 / 20 / 24 / 32-bit samples. Written from the ALAC format as published by Apple -- (ALACDecoder / ag_dec / dp_dec, Apache 2.0; behaviour, not code). Never throws: returns nil, message. diff --git a/src/Formats/codecs/Alac/Encode.luau b/src/Formats/codecs/audio/Alac/Encode.luau similarity index 98% rename from src/Formats/codecs/Alac/Encode.luau rename to src/Formats/codecs/audio/Alac/Encode.luau index 4309bd5..2543e77 100644 --- a/src/Formats/codecs/Alac/Encode.luau +++ b/src/Formats/codecs/audio/Alac/Encode.luau @@ -1,7 +1,7 @@ --!strict --!native --!optimize 2 --- codecs/Alac/Encode: an ALAC frame encoder: per element (SCE / CPE) the stereo mix (mixBits 2, the best mixRes of +-- codecs/audio/Alac/Encode: an ALAC frame encoder: per element (SCE / CPE) the stereo mix (mixBits 2, the best mixRes of -- 0 .. 4 by first-difference energy), per channel LPC coefficients (Levinson-Durbin on a windowed autocorrelation, -- orders 4 and 8 tried, quantised with denShift 9), residuals through the same adaptive FIR the decoder runs, the -- adaptive Golomb-Rice code with zero runs; an uncompressed (escape) frame when that is smaller. 16 / 20 / 24-bit diff --git a/src/Formats/codecs/Alac/init.luau b/src/Formats/codecs/audio/Alac/init.luau similarity index 96% rename from src/Formats/codecs/Alac/init.luau rename to src/Formats/codecs/audio/Alac/init.luau index 7af082b..302d6b5 100644 --- a/src/Formats/codecs/Alac/init.luau +++ b/src/Formats/codecs/audio/Alac/init.luau @@ -1,10 +1,10 @@ --!strict --- codecs/Alac: Apple Lossless (ALAC) decoder and encoder, the codec inside m4a / mov / caf. A codec (layer 1). +-- codecs/audio/Alac: Apple Lossless (ALAC) decoder and encoder, the codec inside m4a / mov / caf. A codec (layer 1). -- Written from the ALAC format as Apple published it (ALACSpecificConfig, the element syntax, adaptive Golomb-Rice -- residuals, the adaptive FIR predictor); no third-party code. 1 - 8 channels, 16 / 20 / 24 / 32-bit decode, 16 / 20 / -- 24-bit encode. Channels come out (and go in) in WAV order (ALAC stores C L R ... for 3+ channels). -- --- local Alac = require("@formats/codecs/Alac") +-- local Alac = require("@formats/codecs/audio/Alac") -- local cfg, err = Alac.config(cookie) -- the 24-byte ALACSpecificConfig (frma / alac atoms skipped) -- local dec = Alac.decoder(cfg) -- local frames, err = dec:decode(buf, offset, length) -- one packet -> dec.pcm (interleaved integers, WAV order) @@ -15,8 +15,8 @@ -- Never throws: bad data returns nil, Err (CORRUPT / TRUNCATED / UNSUPPORTED), bad arguments Err.ARG. local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") -local Decode = require("@formats/codecs/Alac/Decode") -local Encode = require("@formats/codecs/Alac/Encode") +local Decode = require("@formats/codecs/audio/Alac/Decode") +local Encode = require("@formats/codecs/audio/Alac/Encode") local Alac = {} diff --git a/src/Formats/codecs/Mdct/Fft.luau b/src/Formats/codecs/audio/Mdct/Fft.luau similarity index 98% rename from src/Formats/codecs/Mdct/Fft.luau rename to src/Formats/codecs/audio/Mdct/Fft.luau index b4900df..a995706 100644 --- a/src/Formats/codecs/Mdct/Fft.luau +++ b/src/Formats/codecs/audio/Mdct/Fft.luau @@ -1,7 +1,7 @@ --!strict --!native --!optimize 2 --- codecs/Mdct/Fft: mixed-radix complex FFT of any size (radix 4, 2, 3, 5 butterflies, a generic odd-radix pass for +-- codecs/audio/Mdct/Fft: mixed-radix complex FFT of any size (radix 4, 2, 3, 5 butterflies, a generic odd-radix pass for -- other primes), self-sorting Stockham passes ping-ponging between the data and a scratch array (the FFTPACK / -- pocketfft pass structure, written from the textbook decimation-in-frequency derivation; no third-party code). -- Data are separate real / imaginary arrays, 1-based. Never throws. diff --git a/src/Formats/codecs/Mdct/init.luau b/src/Formats/codecs/audio/Mdct/init.luau similarity index 94% rename from src/Formats/codecs/Mdct/init.luau rename to src/Formats/codecs/audio/Mdct/init.luau index 316bc21..0713427 100644 --- a/src/Formats/codecs/Mdct/init.luau +++ b/src/Formats/codecs/audio/Mdct/init.luau @@ -1,8 +1,8 @@ --!strict --!native --!optimize 2 --- codecs/Mdct: the MDCT / IMDCT of any window length N divisible by 4 (N / 2 coefficients), through an N / 4-point --- complex FFT (codecs/Mdct/Fft, mixed radix: AAC 2048 / 256, Vorbis 64 .. 8192, CELT 1920 / 240 / ...), plus the +-- codecs/audio/Mdct: the MDCT / IMDCT of any window length N divisible by 4 (N / 2 coefficients), through an N / 4-point +-- complex FFT (codecs/audio/Mdct/Fft, mixed radix: AAC 2048 / 256, Vorbis 64 .. 8192, CELT 1920 / 240 / ...), plus the -- DCT-IV, a plain FFT and the sine / KBD / Vorbis windows. Shared by AAC, Vorbis and Opus (decoders and encoders). -- Written from the textbook definitions (MDCT = DCT-IV of the folded input; DCT-IV through a half-size complex FFT -- with pre / post twiddles); no third-party code. @@ -15,7 +15,7 @@ -- are Luau arrays; `xi` / `yi` are the 1-based index of element 0, coefficient arrays may be strided (CELT -- interleaves its short blocks). -- --- local Mdct = require("@formats/codecs/Mdct") +-- local Mdct = require("@formats/codecs/audio/Mdct") -- local plan = Mdct.new(2048) -- nil when N is not a multiple of 4 -- Mdct.forward(plan, x, 1, X, 1) -- 2048 samples -> 1024 coefficients -- Mdct.inverse(plan, X, 1, 1, y, 1, 2 / 2048) -- 1024 coefficients -> 2048 samples @@ -23,7 +23,7 @@ -- -- Never throws: bad sizes return nil from new(); the transforms trust the plan and the array ranges (the caller -- sizes them). -local Fft = require("@formats/codecs/Mdct/Fft") +local Fft = require("@formats/codecs/audio/Mdct/Fft") local cos, sin, pi, sqrt = math.cos, math.sin, math.pi, math.sqrt diff --git a/src/Formats/codecs/Pcm/Convert.luau b/src/Formats/codecs/audio/Pcm/Convert.luau similarity index 98% rename from src/Formats/codecs/Pcm/Convert.luau rename to src/Formats/codecs/audio/Pcm/Convert.luau index 5d88d6e..3d15128 100644 --- a/src/Formats/codecs/Pcm/Convert.luau +++ b/src/Formats/codecs/audio/Pcm/Convert.luau @@ -1,7 +1,7 @@ --!strict --!native --!optimize 2 --- codecs/Pcm/Convert: raw sample formats <-> interleaved f32 (the hot loops of codecs/Pcm). Integers map to +-- codecs/audio/Pcm/Convert: raw sample formats <-> interleaved f32 (the hot loops of codecs/audio/Pcm). Integers map to -- v / 2^(bits-1) (as ffmpeg does); encoding rounds to nearest and clips. G.711 A-law / mu-law per ITU-T G.711 (the -- classic Sun g711.c algorithm, written from the spec). -- diff --git a/src/Formats/codecs/Pcm/init.luau b/src/Formats/codecs/audio/Pcm/init.luau similarity index 97% rename from src/Formats/codecs/Pcm/init.luau rename to src/Formats/codecs/audio/Pcm/init.luau index 6faadec..3b8118c 100644 --- a/src/Formats/codecs/Pcm/init.luau +++ b/src/Formats/codecs/audio/Pcm/init.luau @@ -1,5 +1,5 @@ --!strict --- codecs/Pcm: PCM plumbing shared by audio formats: raw sample formats, streaming Decoders, encoder input sources. +-- codecs/audio/Pcm: PCM plumbing shared by audio formats: raw sample formats, streaming Decoders, encoder input sources. -- An encoder accepts a Types.Audio (fully decoded) or a Types.Decoder (streamed); Pcm.source turns either into one -- pull interface, so encoders stream in blocks without caring which they got. Uncompressed containers (aiff, au, -- voc, ...) get their Decoder from Pcm.rawDecoder (over a sample region of the file) or Pcm.audioDecoder. @@ -10,7 +10,7 @@ -- local dec = Pcm.rawDecoder(buf, offset, frames, channels, rate, "s16be", tags?) -- a Types.Decoder -- local dec = Pcm.audioDecoder(audio) -- a Types.Decoder over a decoded Audio -- local raw = Pcm.encode(src, "s24le", writer) -- every frame of src appended to a core/Bytes Writer --- Pcm.Convert.decode / encode / SIZE / BITS -- the raw sample loops (codecs/Pcm/Convert) +-- Pcm.Convert.decode / encode / SIZE / BITS -- the raw sample loops (codecs/audio/Pcm/Convert) -- local s16 = Pcm.toInt(x, 16) -- round, clip to [-32768, 32767] -- local x = Pcm.fromInt(s16, 16) -- s / 32768 -- @@ -19,7 +19,7 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") -local Convert = require("@formats/codecs/Pcm/Convert") +local Convert = require("@formats/codecs/audio/Pcm/Convert") local Pcm = {} Pcm.Convert = Convert diff --git a/src/Formats/codecs/Resample/init.luau b/src/Formats/codecs/audio/Resample/init.luau similarity index 98% rename from src/Formats/codecs/Resample/init.luau rename to src/Formats/codecs/audio/Resample/init.luau index 1096060..a2e636b 100644 --- a/src/Formats/codecs/Resample/init.luau +++ b/src/Formats/codecs/audio/Resample/init.luau @@ -1,7 +1,7 @@ --!strict --!native --!optimize 2 --- codecs/Resample: audio sample-rate conversion by band-limited (Kaiser-windowed sinc) interpolation, streaming or +-- codecs/audio/Resample: audio sample-rate conversion by band-limited (Kaiser-windowed sinc) interpolation, streaming or -- whole-buffer, any channel count, interleaved f32 (the Types.Audio / Decoder layout). Used by the Opus, MP3 and MP2 -- encoders (their input rates are fixed) and ops/AudioOps.resample. New in formats-luau (the textbook polyphase -- filter; the kernel is the one the Opus encoder carried). @@ -22,7 +22,7 @@ -- local rs = Resample.new(44100, 48000, 2) -- nil, message for bad rates -- local b, n = rs:process(chunk, chunkFrames) -- the output frames this input completes -- local b2, n2 = rs:flush() -- the rest (the input end padded with zeros) --- local src2 = Resample.source(pcmSource, 48000) -- a codecs/Pcm Source at the new rate +-- local src2 = Resample.source(pcmSource, 48000) -- a codecs/audio/Pcm Source at the new rate -- -- Never throws: bad arguments return nil, message (the api turns them into Err.ARG). local Resample = {} @@ -322,7 +322,7 @@ function Resample.buffer(src: buffer, frames: number, channels: number, from: nu return out, got end --- source(src, to, opts?) -> a pull source ({ sampleRate, channels, frames, tags, read, err }, the codecs/Pcm Source +-- source(src, to, opts?) -> a pull source ({ sampleRate, channels, frames, tags, read, err }, the codecs/audio/Pcm Source -- shape) reading src (any such source: Pcm.source(audioOrDecoder)) at the rate `to` | nil, message function Resample.source(src: any, to: number, opts: Options?): (any, string?) if type(src) ~= "table" or type(src.read) ~= "function" then diff --git a/src/Formats/codecs/SoundFont/Fallback.luau b/src/Formats/codecs/audio/SoundFont/Fallback.luau similarity index 97% rename from src/Formats/codecs/SoundFont/Fallback.luau rename to src/Formats/codecs/audio/SoundFont/Fallback.luau index ae8f8ca..2df195d 100644 --- a/src/Formats/codecs/SoundFont/Fallback.luau +++ b/src/Formats/codecs/audio/SoundFont/Fallback.luau @@ -1,11 +1,11 @@ --!strict --- codecs/SoundFont/Fallback: the built-in General MIDI set used when no SoundFont is given. A generated SoundFont +-- codecs/audio/SoundFont/Fallback: the built-in General MIDI set used when no SoundFont is given. A generated SoundFont -- (the same shape Parse returns, so the same synth plays it): single-cycle sine / triangle / square / saw waves and a -- looped noise sample, one preset per GM family of 8 programs (piano, chromatic percussion, organ, guitar, bass, -- strings, ensemble, brass, reed, pipe, lead, pad, synth fx, ethnic, percussive, sound fx) with family envelopes, -- filters and vibrato, plus a drum kit on bank 128 (pitch-swept sine kicks and toms, filtered noise snares, hats with -- an exclusive class, cymbals). Written for this library (no third-party code). -local Parse = require("@formats/codecs/SoundFont/Parse") +local Parse = require("@formats/codecs/audio/SoundFont/Parse") local Fallback = {} diff --git a/src/Formats/codecs/SoundFont/Parse.luau b/src/Formats/codecs/audio/SoundFont/Parse.luau similarity index 99% rename from src/Formats/codecs/SoundFont/Parse.luau rename to src/Formats/codecs/audio/SoundFont/Parse.luau index df39807..aab2b5f 100644 --- a/src/Formats/codecs/SoundFont/Parse.luau +++ b/src/Formats/codecs/audio/SoundFont/Parse.luau @@ -1,5 +1,5 @@ --!strict --- codecs/SoundFont/Parse: SoundFont 2.0x (sfbk RIFF) reader. The INFO list, the sdta samples (smpl 16-bit, + sm24 +-- codecs/audio/SoundFont/Parse: SoundFont 2.0x (sfbk RIFF) reader. The INFO list, the sdta samples (smpl 16-bit, + sm24 -- when present) as one f32 buffer, and the pdta "hydra" (phdr pbag pmod pgen inst ibag imod igen shdr), flattened -- into playable regions per preset: the instrument global zone, the preset global zone and the preset zone's -- generators merged the way TinySoundFont (tsf.h v0.9, MIT, (c) Bernhard Schelling; licenses/TinySoundFont-LICENSE.txt) diff --git a/src/Formats/codecs/SoundFont/Synth.luau b/src/Formats/codecs/audio/SoundFont/Synth.luau similarity index 99% rename from src/Formats/codecs/SoundFont/Synth.luau rename to src/Formats/codecs/audio/SoundFont/Synth.luau index c133423..d868f0c 100644 --- a/src/Formats/codecs/SoundFont/Synth.luau +++ b/src/Formats/codecs/audio/SoundFont/Synth.luau @@ -1,6 +1,6 @@ --!strict --!native --- codecs/SoundFont/Synth: a SoundFont 2 sample synthesizer with MIDI channels. A port of TinySoundFont (tsf.h v0.9, +-- codecs/audio/SoundFont/Synth: a SoundFont 2 sample synthesizer with MIDI channels. A port of TinySoundFont (tsf.h v0.9, -- MIT, (c) 2017-2025 Bernhard Schelling, based on SFZero (c) 2012 Steve Folta; licenses/TinySoundFont-LICENSE.txt): -- voices with the DAHDSR volume envelope (exponential decay / release), the modulation envelope to pitch and filter -- cutoff, the modulation and vibrato LFOs (triangle) to pitch / filter / volume, a resonant biquad low-pass, linear diff --git a/src/Formats/codecs/SoundFont/init.luau b/src/Formats/codecs/audio/SoundFont/init.luau similarity index 87% rename from src/Formats/codecs/SoundFont/init.luau rename to src/Formats/codecs/audio/SoundFont/init.luau index a1c8feb..e3c2a9d 100644 --- a/src/Formats/codecs/SoundFont/init.luau +++ b/src/Formats/codecs/audio/SoundFont/init.luau @@ -1,11 +1,11 @@ --!strict --- codecs/SoundFont: SoundFont 2 banks and the sample synth that plays MIDI through them. A codec (layer 1) shared by +-- codecs/audio/SoundFont: SoundFont 2 banks and the sample synth that plays MIDI through them. A codec (layer 1) shared by -- music/sf2 (the file format) and music/midi (rendering). The synth is a port of TinySoundFont (tsf.h v0.9, MIT, -- (c) 2017-2025 Bernhard Schelling; licenses/TinySoundFont-LICENSE.txt); see Parse / Synth for what is covered. -- Without a bank, fallback() is a generated General MIDI set of simple waveforms (sine / triangle / square / saw / -- noise) with a drum kit. -- --- local SoundFont = require("@formats/codecs/SoundFont") +-- local SoundFont = require("@formats/codecs/audio/SoundFont") -- local sf, err = SoundFont.parse(buf) -- buffer | string | core/Bytes Reader -> SoundFont | nil, Err -- local sf = SoundFont.fallback() -- the built-in waveform set -- local s = SoundFont.synth(sf, 44100, { gain = 0.5 }) -- a synth State; SoundFont.Synth.midi(s, 0x90, 60, 100) @@ -14,9 +14,9 @@ -- Never throws: bad data returns nil, Err. local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") -local Parse = require("@formats/codecs/SoundFont/Parse") -local Synth = require("@formats/codecs/SoundFont/Synth") -local Fallback = require("@formats/codecs/SoundFont/Fallback") +local Parse = require("@formats/codecs/audio/SoundFont/Parse") +local Synth = require("@formats/codecs/audio/SoundFont/Synth") +local Fallback = require("@formats/codecs/audio/SoundFont/Fallback") local SoundFont = {} diff --git a/src/Formats/codecs/audio/Stream.luau b/src/Formats/codecs/audio/Stream.luau new file mode 100644 index 0000000..ef69611 --- /dev/null +++ b/src/Formats/codecs/audio/Stream.luau @@ -0,0 +1,141 @@ +--!strict +-- codecs/audio/Stream: the streaming Decoder (Types.Decoder: read / seek / position) over a packetised codec, the part +-- every packet-based audio format repeated: decode packets in order into a pending float block, return frames in +-- read()-sized pieces, drop the encoder priming at the start and the padding at the end (gapless), and seek by +-- finding the packet holding the target (with codec pre-roll) and dropping up to it. AAC (ADTS), CAF and M4A use it; +-- formats with their own seeking (Opus granule bisection, FLAC, MP3, Vorbis) keep their streams. New in formats-luau +-- (the loop the three formats carried). +-- +-- local dec, err = Stream.packets(dec, { -- dec: the Decoder table with its fields (sampleRate, channels, +-- count = n, -- frames, duration, bitrate, tags, ...); read / seek / position +-- start = function(i) return ... end, -- are added. start(i): packet i's first frame (absolute, before +-- decode = function(i) return n, err end,-- trimming); decode(i) -> frames | nil, Err, the samples in pcm() +-- pcm = function() return floats end, -- (interleaved, 1-based) until the next decode +-- reset = function() end, -- forget codec state (before a seek) +-- skip = priming, stop = lastFrame, -- output = absolute frames [skip, stop) +-- preroll = 1, -- packets decoded before the one holding a seek target (AAC: 1) +-- }) +-- +-- A decode failure ends the stream and is kept in dec.error (Pcm.drain reports it); a failing first packet is +-- returned by packets() as the open error. Never throws. +local Err = require("@formats/core/Err") + +local Stream = {} + +export type Spec = { + count: number, + start: (i: number) -> number, + decode: (i: number) -> (number?, Err.Err?), + pcm: () -> { number }, + reset: () -> (), + skip: number?, -- default 0 + stop: number?, -- default start(count + 1) + preroll: number?, -- default 0 + cumulative: boolean?, -- frames after a packet = frames before + its output (default: start(i) + its output) +} + +-- packets(dec, spec) -> dec (with read / seek / position) | nil, Err (the first packet failed) +function Stream.packets(dec: any, spec: Spec): (any, Err.Err?) + local sr, ch = dec.sampleRate, dec.channels + local count = spec.count + local skip = spec.skip or 0 + local stopAt = spec.stop or spec.start(count + 1) + local frames = math.max(0, stopAt - skip) + local preroll = spec.preroll or 0 + local decodeP, pcmOf, startOf = spec.decode, spec.pcm, spec.start + local nextPacket = 1 + local decoded = 0 -- absolute frame after the packets decoded so far + local pendPos, pendN = 0, 0 + local dropUntil = skip + local pos = 0 + local failed: Err.Err? = nil + dec.error = nil + + local function fill(): boolean + while true do + if nextPacket > count or decoded >= stopAt then + return false + end + local i = nextPacket + nextPacket += 1 + local first = if spec.cumulative then decoded else startOf(i) + local n, e = decodeP(i) + if not n then + failed = e or Err.new(Err.CORRUPT, "packet " .. i .. " failed") + dec.error = failed + return false + end + decoded = first + n + local a = math.max(first, dropUntil) + local b = math.min(decoded, stopAt) + if b > a then + pendPos, pendN = a - first, b - first + return true + end + end + end + + function dec.read(_self: any, n: number, out: buffer?): (buffer, number) + local want = math.max(0, math.floor(n)) + local need = want * ch * 4 + local ob = if out and buffer.len(out) >= need then out else buffer.create(need) + local got = 0 + local writef32 = buffer.writef32 + while got < want do + if pendPos >= pendN then + if failed or not fill() then + break + end + end + local take = math.min(want - got, pendN - pendPos) + local src = pcmOf() + local q = got * ch * 4 + local s = pendPos * ch + for k = 1, take * ch do + writef32(ob, q, src[s + k]) + q += 4 + end + pendPos += take + got += take + end + pos += got + return ob, got + end + + function dec.seek(_self: any, seconds: number) + local sec = if type(seconds) == "number" and seconds == seconds then seconds else 0 + local target = math.clamp(math.floor(sec * sr + 0.5), 0, frames) + skip -- absolute frame + -- the last packet starting at or before the target, minus the codec's pre-roll + local lo, hi, found = 1, count, 1 + while lo <= hi do + local mid = (lo + hi) // 2 + if startOf(mid) <= target then + found = mid + lo = mid + 1 + else + hi = mid - 1 + end + end + found = math.max(1, found - preroll) + spec.reset() + nextPacket = found + decoded = if count > 0 then startOf(found) else 0 + dropUntil = target + pendPos, pendN = 0, 0 + failed = nil + dec.error = nil + pos = target - skip + end + + function dec.position(_self: any): number + return pos / sr + end + + -- prime: surface a broken first packet as an open error + if count > 0 and frames > 0 and not fill() and failed then + return nil, failed + end + return dec, nil +end + +return Stream diff --git a/src/Formats/codecs/Tracker/Mixer.luau b/src/Formats/codecs/audio/Tracker/Mixer.luau similarity index 95% rename from src/Formats/codecs/Tracker/Mixer.luau rename to src/Formats/codecs/audio/Tracker/Mixer.luau index 193a034..9cedf6b 100644 --- a/src/Formats/codecs/Tracker/Mixer.luau +++ b/src/Formats/codecs/audio/Tracker/Mixer.luau @@ -1,10 +1,10 @@ --!strict --!native --- codecs/Tracker/Mixer: mixes the player's active voices into an interleaved stereo f32 buffer. Per voice: sample +-- codecs/audio/Tracker/Mixer: mixes the player's active voices into an interleaved stereo f32 buffer. Per voice: sample -- loops (forward, ping-pong, IT sustain loops while the key is held), linear or no interpolation, the IT two-pole -- resonant filter, and a short gain ramp per tick against clicks. Written for this library (no third-party code). -- --- Never throws: sample indexes are clamped to the sample, every loop is bounded, and the caller (codecs/Tracker) +-- Never throws: sample indexes are clamped to the sample, every loop is bounded, and the caller (codecs/audio/Tracker) -- validates the sample buffers' sizes. local floor, ceil, min = math.floor, math.ceil, math.min local readf32, writef32 = buffer.readf32, buffer.writef32 diff --git a/src/Formats/codecs/Tracker/Pcm.luau b/src/Formats/codecs/audio/Tracker/Pcm.luau similarity index 96% rename from src/Formats/codecs/Tracker/Pcm.luau rename to src/Formats/codecs/audio/Tracker/Pcm.luau index 30c59c8..cdbc496 100644 --- a/src/Formats/codecs/Tracker/Pcm.luau +++ b/src/Formats/codecs/audio/Tracker/Pcm.luau @@ -1,6 +1,6 @@ --!strict --!native --- codecs/Tracker/Pcm: sample data conversions shared by the tracker formats. Raw 8 / 16-bit PCM (signed or unsigned, +-- codecs/audio/Tracker/Pcm: sample data conversions shared by the tracker formats. Raw 8 / 16-bit PCM (signed or unsigned, -- plain or delta coded as in XM / IT 2.15, interleaved or planar stereo) to the engine's f32 samples, and back. -- -- Never throws: reads past the source are refused up front (decode returns nil). diff --git a/src/Formats/codecs/Tracker/Player.luau b/src/Formats/codecs/audio/Tracker/Player.luau similarity index 99% rename from src/Formats/codecs/Tracker/Player.luau rename to src/Formats/codecs/audio/Tracker/Player.luau index 84d2079..62df8b3 100644 --- a/src/Formats/codecs/Tracker/Player.luau +++ b/src/Formats/codecs/audio/Tracker/Player.luau @@ -1,15 +1,15 @@ --!strict --!native --- codecs/Tracker/Player: the sequencer of the tracker engine. One player for MOD, S3M, XM and IT: rows, orders, +-- codecs/audio/Tracker/Player: the sequencer of the tracker engine. One player for MOD, S3M, XM and IT: rows, orders, -- speed / tempo, every effect of the four formats (interpreted per format family: ProTracker / FastTracker 2 numeric -- effects, ScreamTracker 3 / Impulse Tracker letter effects), instruments with volume / panning / pitch envelopes, -- fadeout and auto-vibrato, IT new note actions (background voices), duplicate checks and resonant filters, and song -- end / loop detection. Written from the format documents (ProTracker 2.3 docs, the XM spec and FT2 behaviour notes, --- ST3 TECH.DOC, ITTECH.TXT); no third-party code. Mixing is codecs/Tracker/Mixer. +-- ST3 TECH.DOC, ITTECH.TXT); no third-party code. Mixing is codecs/audio/Tracker/Mixer. -- --- Never throws: the module is validated by codecs/Tracker before a player is made, and every table lookup here is +-- Never throws: the module is validated by codecs/audio/Tracker before a player is made, and every table lookup here is -- guarded. -local Tables = require("@formats/codecs/Tracker/Tables") +local Tables = require("@formats/codecs/audio/Tracker/Tables") local wave64, autoWave = Tables.wave64, Tables.autoWave local AMIGA = Tables.AMIGA @@ -322,7 +322,7 @@ local function advanceRow(st: any) end -- ------------------------------------------------------------------------------------------------ pitch --- the period of a note for a sample (see codecs/Tracker for the two period spaces) +-- the period of a note for a sample (see codecs/audio/Tracker for the two period spaces) local function notePeriod(st: any, note: number, smp: any, ft: number?): (number, number) local base, ref, tr if st.fmt == MOD or st.fmt == XM then diff --git a/src/Formats/codecs/Tracker/Tables.luau b/src/Formats/codecs/audio/Tracker/Tables.luau similarity index 97% rename from src/Formats/codecs/Tracker/Tables.luau rename to src/Formats/codecs/audio/Tracker/Tables.luau index c621ec1..90e78d8 100644 --- a/src/Formats/codecs/Tracker/Tables.luau +++ b/src/Formats/codecs/audio/Tracker/Tables.luau @@ -1,6 +1,6 @@ --!strict --!native --- codecs/Tracker/Tables: lookup tables of the tracker engine. Waveforms for vibrato / tremolo / panbrello and the +-- codecs/audio/Tracker/Tables: lookup tables of the tracker engine. Waveforms for vibrato / tremolo / panbrello and the -- auto-vibrato, the ProTracker period table (finetune 0, used to map MOD periods to notes and back) and the IT / S3M -- volume-column tone-portamento and retrigger tables. All values are from the public format documents (ProTracker -- 2.3 effect docs, FT2 / XM spec, ST3 TECH.DOC, ITTECH.TXT). diff --git a/src/Formats/codecs/Tracker/init.luau b/src/Formats/codecs/audio/Tracker/init.luau similarity index 97% rename from src/Formats/codecs/Tracker/init.luau rename to src/Formats/codecs/audio/Tracker/init.luau index 391ea94..55056f6 100644 --- a/src/Formats/codecs/Tracker/init.luau +++ b/src/Formats/codecs/audio/Tracker/init.luau @@ -1,10 +1,10 @@ --!strict --- codecs/Tracker: the shared tracker engine behind music/mod, music/s3m, music/xm and music/it. The four loaders read +-- codecs/audio/Tracker: the shared tracker engine behind music/mod, music/s3m, music/xm and music/it. The four loaders read -- their files into one Module structure (below); render(module, opts) plays any of them through the standard audio -- Decoder (Types.Decoder: stereo f32). Written for this library from the format documents (ProTracker 2.3, the XM -- spec + FT2 behaviour, ST3 TECH.DOC, ITTECH.TXT); libxmp / OpenMPT were used only as reference players for tests. -- --- local Tracker = require("@formats/codecs/Tracker") +-- local Tracker = require("@formats/codecs/audio/Tracker") -- local dec, err = Tracker.render(module, { sampleRate = 44100 }) -- a Types.Decoder -- local seconds = Tracker.duration(module) -- one pass, song loops detected -- @@ -48,10 +48,10 @@ -- (S2x), random volume / pan variation, OPL (AdLib) instruments, MOD Amiga low-pass filter emulation. local Err = require("@formats/core/Err") local Types = require("@formats/Types") -local Player = require("@formats/codecs/Tracker/Player") -local Mixer = require("@formats/codecs/Tracker/Mixer") -local Pcm = require("@formats/codecs/Tracker/Pcm") -local Tables = require("@formats/codecs/Tracker/Tables") +local Player = require("@formats/codecs/audio/Tracker/Player") +local Mixer = require("@formats/codecs/audio/Tracker/Mixer") +local Pcm = require("@formats/codecs/audio/Tracker/Pcm") +local Tables = require("@formats/codecs/audio/Tracker/Tables") local Tracker = {} diff --git a/src/Formats/codecs/VorbisComment.luau b/src/Formats/codecs/audio/VorbisComment.luau similarity index 93% rename from src/Formats/codecs/VorbisComment.luau rename to src/Formats/codecs/audio/VorbisComment.luau index 118be05..74ca09e 100644 --- a/src/Formats/codecs/VorbisComment.luau +++ b/src/Formats/codecs/audio/VorbisComment.luau @@ -1,5 +1,5 @@ --!strict --- codecs/VorbisComment: Vorbis comment fields ("KEY=value", the tag block of Vorbis, Opus and FLAC) <-> Types.Tags. +-- codecs/audio/VorbisComment: Vorbis comment fields ("KEY=value", the tag block of Vorbis, Opus and FLAC) <-> Types.Tags. -- Tag keys are lower case everywhere in formats-luau (the same names ID3 / MP4 / RIFF INFO map to): title, artist, -- album, albumartist, date, genre, track, tracktotal, disc, disctotal, comment, composer, ...; TRACKNUMBER becomes -- track, DISCNUMBER disc, DESCRIPTION comment, other fields their lower-cased name. Repeated fields are joined with @@ -52,7 +52,7 @@ function VorbisComment.fields(tags: { [any]: any }): { string } end end table.sort(keys) - local out = table.create(#keys) + local out: { string } = table.create(#keys) :: any for i, k in keys do out[i] = VorbisComment.fieldName(k) .. "=" .. tags[k] end diff --git a/src/Formats/codecs/Brotli/Decode.luau b/src/Formats/codecs/compress/Brotli/Decode.luau similarity index 99% rename from src/Formats/codecs/Brotli/Decode.luau rename to src/Formats/codecs/compress/Brotli/Decode.luau index e17e7d8..08f7705 100644 --- a/src/Formats/codecs/Brotli/Decode.luau +++ b/src/Formats/codecs/compress/Brotli/Decode.luau @@ -1,7 +1,7 @@ --!strict --!native --!optimize 2 --- codecs/Brotli/Decode: a Brotli (RFC 7932) decoder over a whole in-memory stream. Written from the RFC, with the +-- codecs/compress/Brotli/Decode: a Brotli (RFC 7932) decoder over a whole in-memory stream. Written from the RFC, with the -- reference decoder (google/brotli c/dec/decode.c, MIT) as the authority on edge cases (simple prefix code alphabet -- widths, repeat codes, padding checks, the large-window extension). Supports every meta-block kind (compressed, -- uncompressed, metadata), block types / counts, the four literal context modes, context maps with RLE and inverse diff --git a/src/Formats/codecs/Brotli/Static.luau b/src/Formats/codecs/compress/Brotli/Static.luau similarity index 99% rename from src/Formats/codecs/Brotli/Static.luau rename to src/Formats/codecs/compress/Brotli/Static.luau index d9170fa..6cd704d 100644 --- a/src/Formats/codecs/Brotli/Static.luau +++ b/src/Formats/codecs/compress/Brotli/Static.luau @@ -1,5 +1,5 @@ --!strict --- codecs/Brotli/Static: GENERATED by tools/brotli_static.py from the brotli C sources (MIT, Google; see +-- codecs/compress/Brotli/Static: GENERATED by tools/brotli_static.py from the brotli C sources (MIT, Google; see -- licenses/brotli-LICENSE.txt) - do not edit. The RFC 7932 static dictionary (122784 bytes, deflated, base64), -- the context lookup table (Appendix B, 4 modes x 512) and the 121 word transforms (Appendix B). return { diff --git a/src/Formats/codecs/Brotli/init.luau b/src/Formats/codecs/compress/Brotli/init.luau similarity index 86% rename from src/Formats/codecs/Brotli/init.luau rename to src/Formats/codecs/compress/Brotli/init.luau index 9d50131..eebd8db 100644 --- a/src/Formats/codecs/Brotli/init.luau +++ b/src/Formats/codecs/compress/Brotli/init.luau @@ -1,12 +1,12 @@ --!strict --- codecs/Brotli: Brotli (RFC 7932) decompression. A codec (layer 3): archive/br and font/woff2 build on it. Written --- from the RFC (decoder in codecs/Brotli/Decode); the static dictionary, context table and word transforms come from --- google/brotli (MIT, licenses/brotli-LICENSE.txt) through codecs/Brotli/Static (tools/brotli_static.py). +-- codecs/compress/Brotli: Brotli (RFC 7932) decompression. A codec (layer 3): archive/br and font/woff2 build on it. Written +-- from the RFC (decoder in codecs/compress/Brotli/Decode); the static dictionary, context table and word transforms come from +-- google/brotli (MIT, licenses/brotli-LICENSE.txt) through codecs/compress/Brotli/Static (tools/brotli_static.py). -- Supports every RFC 7932 stream (window sizes 10..24, metadata / uncompressed / compressed meta-blocks, the static -- dictionary with all 121 transforms) and the large-window extension (opts.largeWindow). Not supported: compression, -- shared / compound dictionaries (draft "shared brotli"). -- --- local Brotli = require("@formats/codecs/Brotli") +-- local Brotli = require("@formats/codecs/compress/Brotli") -- local out, consumedEnd = Brotli.decompress(buf) -- buffer | string -- local out, err = Brotli.decompress(buf, offset, length, { maxBytes = 2^24 }) -- @@ -15,9 +15,9 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Crc32 = require("@formats/core/Crc32") local Base64 = require("@formats/core/Base64") -local Deflate = require("@formats/codecs/Deflate") -local Decode = require("@formats/codecs/Brotli/Decode") -local StaticData = require("@formats/codecs/Brotli/Static") +local Deflate = require("@formats/codecs/compress/Deflate") +local Decode = require("@formats/codecs/compress/Brotli/Decode") +local StaticData = require("@formats/codecs/compress/Brotli/Static") local Brotli = {} diff --git a/src/Formats/codecs/Bzip2/Decode.luau b/src/Formats/codecs/compress/Bzip2/Decode.luau similarity index 99% rename from src/Formats/codecs/Bzip2/Decode.luau rename to src/Formats/codecs/compress/Bzip2/Decode.luau index 720973d..873bd19 100644 --- a/src/Formats/codecs/Bzip2/Decode.luau +++ b/src/Formats/codecs/compress/Bzip2/Decode.luau @@ -1,7 +1,7 @@ --!strict --!native --!optimize 2 --- codecs/Bzip2/Decode: bzip2 stream decoder (Julian Seward's format, as documented by the bzip2 1.0.x sources and +-- codecs/compress/Bzip2/Decode: bzip2 stream decoder (Julian Seward's format, as documented by the bzip2 1.0.x sources and -- Joe Tsai's "bzip2 format specification"). Written from the format description; no third-party code. -- Per block: MSB-first bit reader on a local 32-bit bit buffer, Huffman groups (10-bit lookup + canonical fallback for -- codes up to 20 bits), MTF + RUNA/RUNB, inverse BWT through one u32 vector (byte in the low 8 bits, next index diff --git a/src/Formats/codecs/Bzip2/init.luau b/src/Formats/codecs/compress/Bzip2/init.luau similarity index 89% rename from src/Formats/codecs/Bzip2/init.luau rename to src/Formats/codecs/compress/Bzip2/init.luau index 86c72db..00d903e 100644 --- a/src/Formats/codecs/Bzip2/init.luau +++ b/src/Formats/codecs/compress/Bzip2/init.luau @@ -1,17 +1,17 @@ --!strict --- codecs/Bzip2: bzip2 decompressor (BWT + MTF + Huffman, the .bz2 stream format of bzip2 0.9.5 / 1.0.x). A codec +-- codecs/compress/Bzip2: bzip2 decompressor (BWT + MTF + Huffman, the .bz2 stream format of bzip2 0.9.5 / 1.0.x). A codec -- (layer 3): archive/bz2 and tar.bz2 build on it. Written from the format description (no third-party code). -- Supports: block sizes 1..9, every Huffman group layout, block and stream CRCs, concatenated streams (as bzip2 -d). -- Not supported: randomised blocks (bzip2 0.9.0 and older; Err.UNSUPPORTED), compression. -- --- local Bzip2 = require("@formats/codecs/Bzip2") +-- local Bzip2 = require("@formats/codecs/compress/Bzip2") -- local out, consumedEnd = Bzip2.decompress(buf) -- | nil, Err -- local out = Bzip2.decompress(buf, offset, length, { maxBytes = 2^24 }) -- -- Never throws: bad data and bad arguments return nil, Err (TRUNCATED / CORRUPT / CHECKSUM / LIMIT / ARG). local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") -local Decode = require("@formats/codecs/Bzip2/Decode") +local Decode = require("@formats/codecs/compress/Bzip2/Decode") local Bzip2 = {} diff --git a/src/Formats/codecs/Deflate/Compress.luau b/src/Formats/codecs/compress/Deflate/Compress.luau similarity index 97% rename from src/Formats/codecs/Deflate/Compress.luau rename to src/Formats/codecs/compress/Deflate/Compress.luau index d5d508f..f3c60f6 100644 --- a/src/Formats/codecs/Deflate/Compress.luau +++ b/src/Formats/codecs/compress/Deflate/Compress.luau @@ -1,12 +1,12 @@ --!strict --!native --!optimize 2 --- codecs/Deflate/Compress: a DEFLATE (RFC 1951) compressor. LZ77 over a 32 KB window with hash chains (chain depth --- and lazy matching by level), then per block the cheapest of stored / fixed-Huffman / dynamic-Huffman (core/Huffman +-- codecs/compress/Deflate/Compress: a DEFLATE (RFC 1951) compressor. LZ77 over a 32 KB window with hash chains (chain depth +-- and lazy matching by level), then per block the cheapest of stored / fixed-Huffman / dynamic-Huffman (codecs/entropy/Huffman -- length-limited codes). Level 0 = stored blocks only. -- -- raw(buf, off, len, level) -> buffer. Never throws (the caller validated the arguments). -local Huffman = require("@formats/core/Huffman") +local Huffman = require("@formats/codecs/entropy/Huffman") local readu8, writeu8, writeu16 = buffer.readu8, buffer.writeu8, buffer.writeu16 local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len diff --git a/src/Formats/codecs/Deflate/Inflate.luau b/src/Formats/codecs/compress/Deflate/Inflate.luau similarity index 97% rename from src/Formats/codecs/Deflate/Inflate.luau rename to src/Formats/codecs/compress/Deflate/Inflate.luau index ab9a237..449e1db 100644 --- a/src/Formats/codecs/Deflate/Inflate.luau +++ b/src/Formats/codecs/compress/Deflate/Inflate.luau @@ -1,17 +1,17 @@ --!strict --!native --!optimize 2 --- codecs/Deflate/Inflate: raw DEFLATE (RFC 1951) decoder: stored, fixed-Huffman and dynamic-Huffman blocks. --- Absorbed from deflate-luau src/Deflate/Inflate.luau (same author); the table builder moved to core/Huffman, whose +-- codecs/compress/Deflate/Inflate: raw DEFLATE (RFC 1951) decoder: stored, fixed-Huffman and dynamic-Huffman blocks. +-- Absorbed from deflate-luau src/Deflate/Inflate.luau (same author); the table builder moved to codecs/entropy/Huffman, whose -- entries are symbol * 32 + length (5 length bits instead of 4). -- -- Bits are read LSB first into a 32-bit bit buffer (refilled 4 bytes at a time with one readu32 while the input --- lasts). Huffman codes decode through a core/Huffman LSB table indexed by the next LITBITS / DISTBITS bits; a longer +-- lasts). Huffman codes decode through a codecs/entropy/Huffman LSB table indexed by the next LITBITS / DISTBITS bits; a longer -- code's primary slot links to a subtable, so a symbol is one or two table reads. -- -- Nothing in this module throws on any input: every buffer read and write is bounds-checked, and corrupt data -- returns nil, message. (Native code must never throw: it crashes Roblox Studio.) -local Huffman = require("@formats/core/Huffman") +local Huffman = require("@formats/codecs/entropy/Huffman") local band, bor, bxor, lshift, rshift = bit32.band, bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift local readu8, readu16, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu32 diff --git a/src/Formats/codecs/Deflate/init.luau b/src/Formats/codecs/compress/Deflate/init.luau similarity index 96% rename from src/Formats/codecs/Deflate/init.luau rename to src/Formats/codecs/compress/Deflate/init.luau index 8308056..37a529b 100644 --- a/src/Formats/codecs/Deflate/init.luau +++ b/src/Formats/codecs/compress/Deflate/init.luau @@ -1,9 +1,9 @@ --!strict --- codecs/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers. +-- codecs/compress/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers. -- A codec (layer 1), not a format: png, zip, gzip, woff, tiff, ... build on it. Absorbed from deflate-luau 1.0.0 -- (same author; no third-party code); the compressor is new. -- --- local Deflate = require("@formats/codecs/Deflate") +-- local Deflate = require("@formats/codecs/compress/Deflate") -- local out, err = Deflate.inflate(buf) -- raw deflate -> buffer, consumedEnd | nil, Err -- local out, err = Deflate.inflate(buf, off, len, size) -- a range, with the exact output size if known -- local out, err = Deflate.zlib(buf) -- checks the Adler-32 @@ -15,8 +15,8 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Crc32 = require("@formats/core/Crc32") local Adler32 = require("@formats/core/Adler32") -local Inflate = require("@formats/codecs/Deflate/Inflate") -local Compress = require("@formats/codecs/Deflate/Compress") +local Inflate = require("@formats/codecs/compress/Deflate/Inflate") +local Compress = require("@formats/codecs/compress/Deflate/Compress") local Deflate = {} diff --git a/src/Formats/codecs/Lzma/Crc64.luau b/src/Formats/codecs/compress/Lzma/Crc64.luau similarity index 89% rename from src/Formats/codecs/Lzma/Crc64.luau rename to src/Formats/codecs/compress/Lzma/Crc64.luau index 19f682f..bd39f30 100644 --- a/src/Formats/codecs/Lzma/Crc64.luau +++ b/src/Formats/codecs/compress/Lzma/Crc64.luau @@ -1,7 +1,7 @@ --!strict --!native --!optimize 2 --- codecs/Lzma/Crc64: CRC-64/XZ (ECMA-182 polynomial, reflected: 0xC96C5795D7870F42), the xz check type 4. The 64-bit +-- codecs/compress/Lzma/Crc64: CRC-64/XZ (ECMA-182 polynomial, reflected: 0xC96C5795D7870F42), the xz check type 4. The 64-bit -- value is kept as two u32 halves (hi, lo). Written from the xz file format specification. Never throws. local band, bxor, rshift, lshift, bor = bit32.band, bit32.bxor, bit32.rshift, bit32.lshift, bit32.bor local readu8 = buffer.readu8 diff --git a/src/Formats/codecs/Lzma/Decode.luau b/src/Formats/codecs/compress/Lzma/Decode.luau similarity index 98% rename from src/Formats/codecs/Lzma/Decode.luau rename to src/Formats/codecs/compress/Lzma/Decode.luau index 51be654..dfbb956 100644 --- a/src/Formats/codecs/Lzma/Decode.luau +++ b/src/Formats/codecs/compress/Lzma/Decode.luau @@ -1,7 +1,7 @@ --!strict --!native --!optimize 2 --- codecs/Lzma/Decode: the LZMA range decoder and LZ state machine, shared by raw LZMA (.lzma, 7z) and LZMA2 (xz, 7z). +-- codecs/compress/Lzma/Decode: the LZMA range decoder and LZ state machine, shared by raw LZMA (.lzma, 7z) and LZMA2 (xz, 7z). -- Written from the LZMA specification and its reference decoder (LzmaSpec.cpp, Igor Pavlov, public domain); the -- structure (probability model layout, state transitions, distance / length decoding) follows that document. -- diff --git a/src/Formats/codecs/Lzma/Filters.luau b/src/Formats/codecs/compress/Lzma/Filters.luau similarity index 97% rename from src/Formats/codecs/Lzma/Filters.luau rename to src/Formats/codecs/compress/Lzma/Filters.luau index 60a5d59..5cc2e2f 100644 --- a/src/Formats/codecs/Lzma/Filters.luau +++ b/src/Formats/codecs/compress/Lzma/Filters.luau @@ -1,7 +1,7 @@ --!strict --!native --!optimize 2 --- codecs/Lzma/Filters: the branch-call-jump (BCJ) and delta decoding filters of xz and 7z, run in place over a whole +-- codecs/compress/Lzma/Filters: the branch-call-jump (BCJ) and delta decoding filters of xz and 7z, run in place over a whole -- decoded buffer range. Written from the xz file format specification and xz-embedded's xz_dec_bcj.c (Lasse Collin, -- public domain): x86, ARM, ARM-Thumb, PowerPC, SPARC, ARM64 and delta. Not supported: IA-64, RISC-V. -- Never throws: every access is inside [o, o + n). diff --git a/src/Formats/codecs/Lzma/init.luau b/src/Formats/codecs/compress/Lzma/init.luau similarity index 98% rename from src/Formats/codecs/Lzma/init.luau rename to src/Formats/codecs/compress/Lzma/init.luau index f160319..667b2ad 100644 --- a/src/Formats/codecs/Lzma/init.luau +++ b/src/Formats/codecs/compress/Lzma/init.luau @@ -1,10 +1,10 @@ --!strict --- codecs/Lzma: LZMA and LZMA2 decoders, the .lzma ("LZMA alone") wrapper and the .xz container. A codec (layer 3): +-- codecs/compress/Lzma: LZMA and LZMA2 decoders, the .lzma ("LZMA alone") wrapper and the .xz container. A codec (layer 3): -- archive/xz, archive/7z (and anything else holding LZMA data) build on it. Decode only. -- Written from the LZMA specification (LzmaSpec.cpp, Igor Pavlov, public domain) and the xz file format specification -- 1.2 (Lasse Collin / Igor Pavlov, public domain); the BCJ filters follow xz-embedded (public domain). -- --- local Lzma = require("@formats/codecs/Lzma") +-- local Lzma = require("@formats/codecs/compress/Lzma") -- local out, e = Lzma.lzma(buf, off, len, props, unpackSize?, opts?) -- raw LZMA; props = 5-byte buffer / string -- -- or { lc, lp, pb, dictSize } -- local out, e = Lzma.lzma2(buf, off, len, dictSize?, unpackSize?, opts?) -- raw LZMA2 chunks @@ -19,9 +19,9 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Crc32 = require("@formats/core/Crc32") -local Decode = require("@formats/codecs/Lzma/Decode") -local Filters = require("@formats/codecs/Lzma/Filters") -local Crc64 = require("@formats/codecs/Lzma/Crc64") +local Decode = require("@formats/codecs/compress/Lzma/Decode") +local Filters = require("@formats/codecs/compress/Lzma/Filters") +local Crc64 = require("@formats/codecs/compress/Lzma/Crc64") local readu8, readu32 = buffer.readu8, buffer.readu32 diff --git a/src/Formats/codecs/Lzw/init.luau b/src/Formats/codecs/compress/Lzw/init.luau similarity index 98% rename from src/Formats/codecs/Lzw/init.luau rename to src/Formats/codecs/compress/Lzw/init.luau index 168ded4..a399b9f 100644 --- a/src/Formats/codecs/Lzw/init.luau +++ b/src/Formats/codecs/compress/Lzw/init.luau @@ -1,7 +1,7 @@ --!strict --!native --!optimize 2 --- codecs/Lzw: LZW decoder and encoder in the two variants file formats use. A codec (layer 1): image/gif and +-- codecs/compress/Lzw: LZW decoder and encoder in the two variants file formats use. A codec (layer 1): image/gif and -- image/tiff build on it. New code (no port), written from the GIF89a spec (appendix F) and TIFF 6.0 section 13. -- gif LSB-first codes, a minimum code size 1..11 (2..8 in GIF), clear = 2^min, EOI = clear + 1, the code width -- grows when the next free code reaches 2^width (max 12 bits; a full table stays frozen until a clear). diff --git a/src/Formats/codecs/Zstd/Decode.luau b/src/Formats/codecs/compress/Zstd/Decode.luau similarity index 99% rename from src/Formats/codecs/Zstd/Decode.luau rename to src/Formats/codecs/compress/Zstd/Decode.luau index 7ad77d5..71961f8 100644 --- a/src/Formats/codecs/Zstd/Decode.luau +++ b/src/Formats/codecs/compress/Zstd/Decode.luau @@ -1,7 +1,7 @@ --!strict --!native --!optimize 2 --- codecs/Zstd/Decode: Zstandard frame decoder (RFC 8878), written from the specification (no code copied from the +-- codecs/compress/Zstd/Decode: Zstandard frame decoder (RFC 8878), written from the specification (no code copied from the -- BSD reference implementation). Frames (any number, concatenated), skippable frames, raw / RLE / compressed blocks, -- Huffman literals (1 or 4 streams, new or repeated table), FSE sequence tables (predefined / RLE / compressed / -- repeat), repeat offsets, the XXH64 content checksum. Not supported: dictionaries (a non-zero dictionary ID). @@ -11,7 +11,7 @@ -- byte (o - n) / 8, bits before the stream start read as zeros. -- -- Nothing here throws on any input: every read is bounds-checked; failures return nil, code, message, offset. -local Xxh64 = require("@formats/codecs/Zstd/Xxh64") +local Xxh64 = require("@formats/codecs/compress/Zstd/Xxh64") local band, lshift, rshift = bit32.band, bit32.lshift, bit32.rshift local readu8, readu16, readu32, writeu8, writeu16, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu16, buffer.writeu32 diff --git a/src/Formats/codecs/Zstd/Xxh64.luau b/src/Formats/codecs/compress/Zstd/Xxh64.luau similarity index 97% rename from src/Formats/codecs/Zstd/Xxh64.luau rename to src/Formats/codecs/compress/Zstd/Xxh64.luau index c189970..7e29fec 100644 --- a/src/Formats/codecs/Zstd/Xxh64.luau +++ b/src/Formats/codecs/compress/Zstd/Xxh64.luau @@ -1,7 +1,7 @@ --!strict --!native --!optimize 2 --- codecs/Zstd/Xxh64: XXH64 (seed 0) of a buffer range, computed on 32-bit halves held in doubles (Luau and LuaJIT have +-- codecs/compress/Zstd/Xxh64: XXH64 (seed 0) of a buffer range, computed on 32-bit halves held in doubles (Luau and LuaJIT have -- no 64-bit integers). 64 x 64 -> 64 products split the low operand into 16-bit limbs so every partial product is -- exact below 2^53. From the xxHash specification (Yann Collet, BSD-2); no code copied. zstd stores the low 32 bits -- of the hash as the frame content checksum. Never throws (the caller passes an in-range buffer slice). diff --git a/src/Formats/codecs/Zstd/init.luau b/src/Formats/codecs/compress/Zstd/init.luau similarity index 92% rename from src/Formats/codecs/Zstd/init.luau rename to src/Formats/codecs/compress/Zstd/init.luau index 2d9cb04..a7a3e7b 100644 --- a/src/Formats/codecs/Zstd/init.luau +++ b/src/Formats/codecs/compress/Zstd/init.luau @@ -1,18 +1,18 @@ --!strict --- codecs/Zstd: Zstandard decompression (RFC 8878). A codec (layer 3): archive/zst and anything else carrying zstd +-- codecs/compress/Zstd: Zstandard decompression (RFC 8878). A codec (layer 3): archive/zst and anything else carrying zstd -- data build on it. Written from the specification. Supports every frame feature a dictionary-less stream uses: -- concatenated and skippable frames, raw / RLE / compressed blocks, Huffman literals (1 / 4 streams, repeated tables), -- predefined / RLE / compressed / repeated FSE tables, repeat offsets, the XXH64 content checksum (verified). -- Not supported: dictionaries (Err.UNSUPPORTED), compression. -- --- local Zstd = require("@formats/codecs/Zstd") +-- local Zstd = require("@formats/codecs/compress/Zstd") -- local out, err = Zstd.decompress(buf) -- -> buffer, consumedEnd | nil, Err -- local out, err = Zstd.decompress(buf, off, len, { maxBytes = 2^24, verify = false }) -- -- Never throws: bad data and bad arguments return nil, Err (TRUNCATED / CORRUPT / CHECKSUM / UNSUPPORTED / LIMIT / ARG). local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") -local Decode = require("@formats/codecs/Zstd/Decode") +local Decode = require("@formats/codecs/compress/Zstd/Decode") local Zstd = {} diff --git a/src/Formats/core/Huffman.luau b/src/Formats/codecs/entropy/Huffman.luau similarity index 97% rename from src/Formats/core/Huffman.luau rename to src/Formats/codecs/entropy/Huffman.luau index 5d200d8..4e2243c 100644 --- a/src/Formats/core/Huffman.luau +++ b/src/Formats/codecs/entropy/Huffman.luau @@ -1,6 +1,6 @@ --!strict --!native --- core/Huffman: canonical Huffman codes (RFC 1951 3.2.2 / JPEG Annex C order) for decoders and encoders. +-- codecs/entropy/Huffman: canonical Huffman codes (RFC 1951 3.2.2 / JPEG Annex C order) for decoders and encoders. -- -- Decoding tables (built by buildLsb / buildMsb) are u32 buffers, indexed by the next P bits of the stream: -- entry = symbol * 32 + length a code of `length` <= P bits @@ -8,7 +8,7 @@ -- entry = 0 no code (incomplete code set): the stream is corrupt -- so a symbol is one or two table reads. LSB tables (DEFLATE, VP8L) are indexed by bit-reversed codes, MSB tables -- (JPEG, MPEG) by the code itself. Code lengths are 1..MAXLEN (16), symbols < 2^27. --- The hot loops (codecs/Deflate/Inflate) inline the lookup on their own bit buffer; decodeLsb / decodeMsb do it on a +-- The hot loops (codecs/compress/Deflate/Inflate) inline the lookup on their own bit buffer; decodeLsb / decodeMsb do it on a -- core/Bits reader. -- -- Encoding: lengths(freqs, maxLen) -> length-limited code lengths; codes(lengths) -> canonical code values. diff --git a/src/Formats/codecs/RangeCoder/Decoder.luau b/src/Formats/codecs/entropy/RangeCoder/Decoder.luau similarity index 97% rename from src/Formats/codecs/RangeCoder/Decoder.luau rename to src/Formats/codecs/entropy/RangeCoder/Decoder.luau index 2c64ec3..6073941 100644 --- a/src/Formats/codecs/RangeCoder/Decoder.luau +++ b/src/Formats/codecs/entropy/RangeCoder/Decoder.luau @@ -1,7 +1,7 @@ --!strict --!native --!optimize 2 --- codecs/RangeCoder/Decoder: the Opus range decoder (RFC 6716 section 4.1, libopus celt/entdec.c). Reads one Opus +-- codecs/entropy/RangeCoder/Decoder: the Opus range decoder (RFC 6716 section 4.1, libopus celt/entdec.c). Reads one Opus -- frame from a `buffer` slice [base, base + storage). Raw bits (ec_dec_bits) are read from the end of the slice -- backwards. -- All values stay below 2^32, so plain Luau numbers hold them exactly; floor division is exact below 2^52. diff --git a/src/Formats/codecs/RangeCoder/Encoder.luau b/src/Formats/codecs/entropy/RangeCoder/Encoder.luau similarity index 95% rename from src/Formats/codecs/RangeCoder/Encoder.luau rename to src/Formats/codecs/entropy/RangeCoder/Encoder.luau index 05e9815..0ddb202 100644 --- a/src/Formats/codecs/RangeCoder/Encoder.luau +++ b/src/Formats/codecs/entropy/RangeCoder/Encoder.luau @@ -1,8 +1,8 @@ --!strict --!native --!optimize 2 --- codecs/RangeCoder/Encoder: the Opus range encoder (RFC 6716 section 5.1), a port of libopus celt/entenc.c (BSD: --- licenses/libopus-BSD.txt), the mirror of codecs/RangeCoder/Decoder. Writes one fixed-size frame: the range-coded +-- codecs/entropy/RangeCoder/Encoder: the Opus range encoder (RFC 6716 section 5.1), a port of libopus celt/entenc.c (BSD: +-- licenses/libopus-BSD.txt), the mirror of codecs/entropy/RangeCoder/Decoder. Writes one fixed-size frame: the range-coded -- symbols from the front, the raw bits (ec_enc_bits) from the back, zeros between. Values stay below 2^32 as plain -- numbers. Never throws: running out of room sets `error`. local RangeEncoder = {} diff --git a/src/Formats/codecs/entropy/RangeCoder/init.luau b/src/Formats/codecs/entropy/RangeCoder/init.luau new file mode 100644 index 0000000..de65aa5 --- /dev/null +++ b/src/Formats/codecs/entropy/RangeCoder/init.luau @@ -0,0 +1,13 @@ +--!strict +-- codecs/entropy/RangeCoder: the RFC 6716 range coder (libopus celt/entdec.c + entenc.c, BSD: licenses/libopus-BSD.txt): +-- symbols range-coded from the front of a frame, raw bits from its back. Opus (CELT and SILK) uses it; LZMA, VP8 and +-- CABAC have their own (different) binary coders. Moved here from audio/opus by the cleanup pass (same code). +-- +-- local RD = require("@formats/codecs/entropy/RangeCoder/Decoder") -- RD.new(buf, base, size), RD.icdf / bits / uint ... +-- local RE = require("@formats/codecs/entropy/RangeCoder/Encoder") -- RE.new(size), RE.icdf / bits / uint, RE.done +local RangeCoder = { + Decoder = require("@formats/codecs/entropy/RangeCoder/Decoder"), + Encoder = require("@formats/codecs/entropy/RangeCoder/Encoder"), +} + +return RangeCoder diff --git a/src/Formats/codecs/Cff/init.luau b/src/Formats/codecs/font/Cff/init.luau similarity index 99% rename from src/Formats/codecs/Cff/init.luau rename to src/Formats/codecs/font/Cff/init.luau index 48d855a..a4cebb6 100644 --- a/src/Formats/codecs/Cff/init.luau +++ b/src/Formats/codecs/font/Cff/init.luau @@ -1,5 +1,5 @@ --!strict --- codecs/Cff: Compact Font Format (Adobe TN #5176) and Type 2 charstrings (TN #5177): the outlines of OpenType fonts +-- codecs/font/Cff: Compact Font Format (Adobe TN #5176) and Type 2 charstrings (TN #5177): the outlines of OpenType fonts -- with a "CFF " table (.otf). Parses the header, the INDEXes, the Top / Private DICTs (name-keyed and CID-keyed -- fonts with FDArray / FDSelect formats 0 and 3), local and global subroutines, and runs charstrings to path commands -- (moveTo / lineTo / cubicTo / close, font units, y up). The charstring interpreter is ported from stb_truetype 1.26 diff --git a/src/Formats/codecs/TrueType/Glyf.luau b/src/Formats/codecs/font/TrueType/Glyf.luau similarity index 97% rename from src/Formats/codecs/TrueType/Glyf.luau rename to src/Formats/codecs/font/TrueType/Glyf.luau index 5d598a9..ce08e9f 100644 --- a/src/Formats/codecs/TrueType/Glyf.luau +++ b/src/Formats/codecs/font/TrueType/Glyf.luau @@ -1,5 +1,5 @@ --!strict --- codecs/TrueType/Glyf: TrueType glyph outlines (the glyf / loca tables): simple glyphs (contours of on- and +-- codecs/font/TrueType/Glyf: TrueType glyph outlines (the glyf / loca tables): simple glyphs (contours of on- and -- off-curve points, with the implied on-curve midpoints) and composite glyphs (offsets or point matching, scale / -- x-y scale / 2x2 transforms, SCALED_COMPONENT_OFFSET, nesting up to 8 levels). Ported from stb_truetype 1.26 -- (public domain / MIT, Sean Barrett) through imgui-luau's imstb_truetype.lua, made bounds-checked, with point @@ -320,7 +320,7 @@ contours = function(f: Face, g: number, depth: number): ({ Contour }?, string?) return composite(f, o, len, depth) end --- outline(f, g) -> path commands (codecs/Raster format, font units, y up) | nil, message +-- outline(f, g) -> path commands (codecs/image/Raster format, font units, y up) | nil, message function Glyf.outline(f: Face, g: number): ({ any }?, string?) local cs, err = contours(f, g, 0) if not cs then diff --git a/src/Formats/codecs/TrueType/Tables.luau b/src/Formats/codecs/font/TrueType/Tables.luau similarity index 99% rename from src/Formats/codecs/TrueType/Tables.luau rename to src/Formats/codecs/font/TrueType/Tables.luau index 7287007..9086053 100644 --- a/src/Formats/codecs/TrueType/Tables.luau +++ b/src/Formats/codecs/font/TrueType/Tables.luau @@ -1,5 +1,5 @@ --!strict --- codecs/TrueType/Tables: the sfnt tables besides the outlines: cmap (formats 0, 4, 6, 10, 12, 13; the best Unicode +-- codecs/font/TrueType/Tables: the sfnt tables besides the outlines: cmap (formats 0, 4, 6, 10, 12, 13; the best Unicode -- subtable, symbol fonts through U+F000), kern (Microsoft version 0 and Apple version 1, format 0 pairs), GPOS pair -- kerning (lookup type 2 formats 1 and 2, reached through the 'kern' feature, including extension lookups, type 9), -- name (UTF-16BE and Mac Roman strings) and OS/2. Written from the OpenType spec, with stb_truetype 1.26 (public diff --git a/src/Formats/codecs/TrueType/init.luau b/src/Formats/codecs/font/TrueType/init.luau similarity index 94% rename from src/Formats/codecs/TrueType/init.luau rename to src/Formats/codecs/font/TrueType/init.luau index 3752c3f..b3584fd 100644 --- a/src/Formats/codecs/TrueType/init.luau +++ b/src/Formats/codecs/font/TrueType/init.luau @@ -1,10 +1,10 @@ --!strict --- codecs/TrueType: the sfnt font container (TrueType .ttf, OpenType .otf with CFF outlines, collections .ttc) parsed +-- codecs/font/TrueType: the sfnt font container (TrueType .ttf, OpenType .otf with CFF outlines, collections .ttc) parsed -- into the standard Font value (Types.Font): metrics (head / hhea / hmtx / OS/2 / post), cmap lookups, glyph outlines --- (codecs/TrueType/Glyf for glyf, codecs/Cff for "CFF "), kerning ('kern' table and GPOS 'kern' pair adjustments), --- names, and rasterize(glyph, px) through codecs/Raster. A codec, not a format: font/ttf, font/woff and font/woff2 all +-- (codecs/font/TrueType/Glyf for glyf, codecs/font/Cff for "CFF "), kerning ('kern' table and GPOS 'kern' pair adjustments), +-- names, and rasterize(glyph, px) through codecs/image/Raster. A codec, not a format: font/ttf, font/woff and font/woff2 all -- build an sfnt and call TrueType.font(). Ported and modernised from stb_truetype 1.26 (public domain / MIT, Sean --- Barrett and contributors) through imgui-luau's imstb_truetype.lua; the rasterizer is codecs/Raster instead of stb's. +-- Barrett and contributors) through imgui-luau's imstb_truetype.lua; the rasterizer is codecs/image/Raster instead of stb's. -- Not supported: hinting, variable fonts (fvar / gvar / CFF2), vertical metrics, bitmap strikes (EBDT / CBDT / sbix), -- colour layers (COLR), GSUB substitutions. -- @@ -17,10 +17,10 @@ -- Never throws: malformed fonts return nil, Err from font(), and nil from the per-glyph methods. local Err = require("@formats/core/Err") local Types = require("@formats/Types") -local Raster = require("@formats/codecs/Raster") -local Cff = require("@formats/codecs/Cff") -local Glyf = require("@formats/codecs/TrueType/Glyf") -local Tables = require("@formats/codecs/TrueType/Tables") +local Raster = require("@formats/codecs/image/Raster") +local Cff = require("@formats/codecs/font/Cff") +local Glyf = require("@formats/codecs/font/TrueType/Glyf") +local Tables = require("@formats/codecs/font/TrueType/Tables") local TrueType = {} diff --git a/src/Formats/codecs/Blend.luau b/src/Formats/codecs/image/Blend.luau similarity index 99% rename from src/Formats/codecs/Blend.luau rename to src/Formats/codecs/image/Blend.luau index d8b2f6a..162ec6f 100644 --- a/src/Formats/codecs/Blend.luau +++ b/src/Formats/codecs/image/Blend.luau @@ -1,6 +1,6 @@ --!strict --!native --- codecs/Blend: layer compositing on rgba8 buffers (straight alpha): source-over with the separable and non-separable +-- codecs/image/Blend: layer compositing on rgba8 buffers (straight alpha): source-over with the separable and non-separable -- blend modes of the W3C Compositing and Blending Level 1 spec (the Photoshop / Aseprite set), opacity, a grey layer -- mask, clipping (source-atop: the backdrop keeps its alpha) and dissolve. Shared by ops/LayerOps (flatten) and the -- layered formats that must write a composite (layered/psd). Never throws: rectangles are clipped to both buffers. diff --git a/src/Formats/codecs/Dct/init.luau b/src/Formats/codecs/image/Dct/init.luau similarity index 99% rename from src/Formats/codecs/Dct/init.luau rename to src/Formats/codecs/image/Dct/init.luau index cb643bb..b84aed6 100644 --- a/src/Formats/codecs/Dct/init.luau +++ b/src/Formats/codecs/image/Dct/init.luau @@ -1,7 +1,7 @@ --!strict --!native --!optimize 2 --- codecs/Dct: the 8x8 DCTs JPEG, Motion-JPEG and MPEG-1 share (native; never throws). +-- codecs/image/Dct: the 8x8 DCTs JPEG, Motion-JPEG and MPEG-1 share (native; never throws). -- Inverse: libjpeg's islow (jidctint.c: the Loeffler-Ligtenberg-Moschytz algorithm, 13-bit constants, two passes with -- PASS1_BITS of scaling between them), plus the reduced 4x4 / 2x2 / 1x1 IDCTs for scaled decodes (jidctred.c); the -- results match libjpeg-turbo's djpeg bit for bit. Absorbed from jpeg-luau 1.0 src/Jpeg/Idct.luau (same author). diff --git a/src/Formats/codecs/Jpeg/Arith.luau b/src/Formats/codecs/image/Jpeg/Arith.luau similarity index 98% rename from src/Formats/codecs/Jpeg/Arith.luau rename to src/Formats/codecs/image/Jpeg/Arith.luau index 984c8a5..4dcf84f 100644 --- a/src/Formats/codecs/Jpeg/Arith.luau +++ b/src/Formats/codecs/image/Jpeg/Arith.luau @@ -1,7 +1,7 @@ --!strict --!native --!optimize 2 --- codecs/Jpeg/Arith: arithmetic-coded scans (ITU T.81 annex D / F.1.4, sequential and progressive) into quantised +-- codecs/image/Jpeg/Arith: arithmetic-coded scans (ITU T.81 annex D / F.1.4, sequential and progressive) into quantised -- DCT coefficients (native; never throws). A Luau translation of libjpeg-turbo's jdarith.c (Guido Vollbeding's -- decoder, IJG licence: licenses/libjpeg-turbo-LICENSE.md) and the jaricom.c probability table. -- diff --git a/src/Formats/codecs/Jpeg/Color.luau b/src/Formats/codecs/image/Jpeg/Color.luau similarity index 98% rename from src/Formats/codecs/Jpeg/Color.luau rename to src/Formats/codecs/image/Jpeg/Color.luau index 46e1cf8..86e7d13 100644 --- a/src/Formats/codecs/Jpeg/Color.luau +++ b/src/Formats/codecs/image/Jpeg/Color.luau @@ -1,7 +1,7 @@ --!strict --!native --!optimize 2 --- codecs/Jpeg/Color: chroma upsampling and colour conversion to RGBA8, one output row at a time (native; never +-- codecs/image/Jpeg/Color: chroma upsampling and colour conversion to RGBA8, one output row at a time (native; never -- throws). Absorbed from jpeg-luau 1.0 src/Jpeg/Color.luau (same author); a Luau translation of libjpeg-turbo's -- jdsample.c / jdcolor.c (IJG licence: licenses/libjpeg-turbo-LICENSE.md). -- diff --git a/src/Formats/codecs/Jpeg/Decode.luau b/src/Formats/codecs/image/Jpeg/Decode.luau similarity index 97% rename from src/Formats/codecs/Jpeg/Decode.luau rename to src/Formats/codecs/image/Jpeg/Decode.luau index 833e66f..efb1a64 100644 --- a/src/Formats/codecs/Jpeg/Decode.luau +++ b/src/Formats/codecs/image/Jpeg/Decode.luau @@ -1,16 +1,16 @@ --!strict --- codecs/Jpeg/Decode: the JPEG marker parser and output stage (interpreted; it validates everything the native Scan / +-- codecs/image/Jpeg/Decode: the JPEG marker parser and output stage (interpreted; it validates everything the native Scan / -- Arith / Dct / Color / Yuv loops index). Absorbed from jpeg-luau 1.0 src/Jpeg/init.luau (same author) and extended: -- arithmetic-coded frames (SOF9 / SOF10, DAC), a byte range instead of a whole buffer, APP1 EXIF / APP2 ICC / COM -- / JFIF density collected for meta, the AVI1 APP0 field polarity and the end of the image (Motion-JPEG), and a -- yuv420p output straight from the IDCT planes (outputYuv). The IDCT size choice for scaled decodes follows --- libjpeg-turbo's jdmaster.c. Moved from image/jpeg/Decode to codecs/Jpeg/Decode for the video formats. -local Scan = require("@formats/codecs/Jpeg/Scan") -local Arith = require("@formats/codecs/Jpeg/Arith") -local Color = require("@formats/codecs/Jpeg/Color") -local Tables = require("@formats/codecs/Jpeg/Tables") -local Yuv = require("@formats/codecs/Jpeg/Yuv") -local Dct = require("@formats/codecs/Dct") +-- libjpeg-turbo's jdmaster.c. Moved from image/jpeg/Decode to codecs/image/Jpeg/Decode for the video formats. +local Scan = require("@formats/codecs/image/Jpeg/Scan") +local Arith = require("@formats/codecs/image/Jpeg/Arith") +local Color = require("@formats/codecs/image/Jpeg/Color") +local Tables = require("@formats/codecs/image/Jpeg/Tables") +local Yuv = require("@formats/codecs/image/Jpeg/Yuv") +local Dct = require("@formats/codecs/image/Dct") local readu8 = buffer.readu8 local band, rshift = bit32.band, bit32.rshift diff --git a/src/Formats/codecs/Jpeg/Encode.luau b/src/Formats/codecs/image/Jpeg/Encode.luau similarity index 98% rename from src/Formats/codecs/Jpeg/Encode.luau rename to src/Formats/codecs/image/Jpeg/Encode.luau index 49e003e..4c0ef60 100644 --- a/src/Formats/codecs/Jpeg/Encode.luau +++ b/src/Formats/codecs/image/Jpeg/Encode.luau @@ -1,16 +1,16 @@ --!strict --!native --!optimize 2 --- codecs/Jpeg/Encode: the JPEG encoder (native; never throws). Baseline (SOF0) with the standard or optimised Huffman +-- codecs/image/Jpeg/Encode: the JPEG encoder (native; never throws). Baseline (SOF0) with the standard or optimised Huffman -- tables and progressive (SOF2, libjpeg's jpeg_simple_progression script, optimised tables per scan); grey or YCbCr -- 4:4:4 / 4:2:2 / 4:2:0, or yuv420p planes coded as they are (4:2:0, no colour conversion: the Motion-JPEG --- encoders); restart intervals. Moved from image/jpeg/Encode to codecs/Jpeg/Encode. It follows libjpeg-turbo's +-- encoders); restart intervals. Moved from image/jpeg/Encode to codecs/image/Jpeg/Encode. It follows libjpeg-turbo's -- encoder step for step so that its output is byte-identical to cjpeg's for the same settings: jccolor.c -- (fixed-point RGB -> YCbCr), jcsample.c (box downsampling with alternating rounding bias, right-edge replication), --- jccoefct.c (dummy edge blocks), jfdctint.c + jcdctmgr.c (codecs/Dct), jchuff.c (sequential coding, jpeg_gen_optimal_table) and jcphuff.c (progressive coding: EOB runs, +-- jccoefct.c (dummy edge blocks), jfdctint.c + jcdctmgr.c (codecs/image/Dct), jchuff.c (sequential coding, jpeg_gen_optimal_table) and jcphuff.c (progressive coding: EOB runs, -- correction-bit buffering). Luau translation of IJG code: licenses/libjpeg-turbo-LICENSE.md. -local Dct = require("@formats/codecs/Dct") -local Tables = require("@formats/codecs/Jpeg/Tables") +local Dct = require("@formats/codecs/image/Dct") +local Tables = require("@formats/codecs/image/Jpeg/Tables") local readu8, writeu8, readi16, writei16, readu16, writeu16 = buffer.readu8, buffer.writeu8, buffer.readi16, buffer.writei16, buffer.readu16, buffer.writeu16 local band, countlz = bit32.band, bit32.countlz diff --git a/src/Formats/codecs/Jpeg/Scan.luau b/src/Formats/codecs/image/Jpeg/Scan.luau similarity index 99% rename from src/Formats/codecs/Jpeg/Scan.luau rename to src/Formats/codecs/image/Jpeg/Scan.luau index f8f62eb..fe5a3d9 100644 --- a/src/Formats/codecs/Jpeg/Scan.luau +++ b/src/Formats/codecs/image/Jpeg/Scan.luau @@ -1,7 +1,7 @@ --!strict --!native --!optimize 2 --- codecs/Jpeg/Scan: Huffman-coded scan decoding into quantised DCT coefficients (native; never throws). Absorbed from +-- codecs/image/Jpeg/Scan: Huffman-coded scan decoding into quantised DCT coefficients (native; never throws). Absorbed from -- jpeg-luau 1.0 src/Jpeg/Scan.luau (same author); unchanged but for this header. -- -- `destuff` copies one scan's entropy-coded bytes into a clean buffer: it drops the stuffed 0x00 after each 0xFF, diff --git a/src/Formats/codecs/Jpeg/Tables.luau b/src/Formats/codecs/image/Jpeg/Tables.luau similarity index 96% rename from src/Formats/codecs/Jpeg/Tables.luau rename to src/Formats/codecs/image/Jpeg/Tables.luau index 9e9c4df..35c5af6 100644 --- a/src/Formats/codecs/Jpeg/Tables.luau +++ b/src/Formats/codecs/image/Jpeg/Tables.luau @@ -1,5 +1,5 @@ --!strict --- codecs/Jpeg/Tables: the standard tables of ITU T.81 annex K: the example Huffman tables (K.3, which every baseline +-- codecs/image/Jpeg/Tables: the standard tables of ITU T.81 annex K: the example Huffman tables (K.3, which every baseline -- encoder without optimisation writes and Motion-JPEG frames leave out) and the luminance / chrominance quantisation -- tables (K.1) with libjpeg's quality scaling (jcparam.c jpeg_quality_scaling / jpeg_add_quant_table). local Tables = {} diff --git a/src/Formats/codecs/Jpeg/Yuv.luau b/src/Formats/codecs/image/Jpeg/Yuv.luau similarity index 92% rename from src/Formats/codecs/Jpeg/Yuv.luau rename to src/Formats/codecs/image/Jpeg/Yuv.luau index edb2778..b9b0925 100644 --- a/src/Formats/codecs/Jpeg/Yuv.luau +++ b/src/Formats/codecs/image/Jpeg/Yuv.luau @@ -1,10 +1,10 @@ --!strict --!native --!optimize 2 --- codecs/Jpeg/Yuv: the yuv420p output of the JPEG decoder (native; never throws): the IDCT output planes (u16 +-- codecs/image/Jpeg/Yuv: the yuv420p output of the JPEG decoder (native; never throws): the IDCT output planes (u16 -- samples, block-padded) cropped into u8 yuv420p planes without colour conversion or upsampling, 4:2:2 / 4:4:4 -- chroma reduced to 4:2:0 by averaging, and the interleaving of two fields (AVI1 interlaced Motion-JPEG). --- The callers (codecs/Jpeg/Decode, codecs/Jpeg) size every buffer; each loop reads and writes inside those sizes. +-- The callers (codecs/image/Jpeg/Decode, codecs/image/Jpeg) size every buffer; each loop reads and writes inside those sizes. local readu16, writeu8, readu32, writeu32 = buffer.readu16, buffer.writeu8, buffer.readu32, buffer.writeu32 local Yuv = {} diff --git a/src/Formats/codecs/Jpeg/init.luau b/src/Formats/codecs/image/Jpeg/init.luau similarity index 97% rename from src/Formats/codecs/Jpeg/init.luau rename to src/Formats/codecs/image/Jpeg/init.luau index de75b4c..32710ae 100644 --- a/src/Formats/codecs/Jpeg/init.luau +++ b/src/Formats/codecs/image/Jpeg/init.luau @@ -1,7 +1,7 @@ --!strict --- codecs/Jpeg: the JPEG codec (ITU T.81) on byte ranges: image/jpeg is a thin format over it, and the Motion-JPEG +-- codecs/image/Jpeg: the JPEG codec (ITU T.81) on byte ranges: image/jpeg is a thin format over it, and the Motion-JPEG -- video tracks (AVI / Matroska / QuickTime) decode and encode their frames with it. The engine (Huffman and --- arithmetic scan decoding, IDCTs through codecs/Dct, libjpeg-turbo's upsampling and colour conversion, the encoder) +-- arithmetic scan decoding, IDCTs through codecs/image/Dct, libjpeg-turbo's upsampling and colour conversion, the encoder) -- was absorbed from jpeg-luau 1.0 (same author) into image/jpeg and moved down here; it is bit-exact with libjpeg-turbo's -- djpeg and byte-identical with cjpeg. IJG-derived parts: licenses/libjpeg-turbo-LICENSE.md. -- @@ -31,9 +31,9 @@ -- Never throws: bad data or arguments return nil, Err. local Err = require("@formats/core/Err") local Types = require("@formats/Types") -local Decode = require("@formats/codecs/Jpeg/Decode") -local Encode = require("@formats/codecs/Jpeg/Encode") -local Yuv = require("@formats/codecs/Jpeg/Yuv") +local Decode = require("@formats/codecs/image/Jpeg/Decode") +local Encode = require("@formats/codecs/image/Jpeg/Encode") +local Yuv = require("@formats/codecs/image/Jpeg/Yuv") local Jpeg = {} diff --git a/src/Formats/image/bmp/Pixels.luau b/src/Formats/codecs/image/Pixels.luau similarity index 84% rename from src/Formats/image/bmp/Pixels.luau rename to src/Formats/codecs/image/Pixels.luau index 331b198..49cd14f 100644 --- a/src/Formats/image/bmp/Pixels.luau +++ b/src/Formats/codecs/image/Pixels.luau @@ -1,11 +1,13 @@ --!strict --!native --!optimize 2 --- image/bmp/Pixels: the pixel loops (native), decode and encode. Absorbed from bmp-luau b86aed6 (same author, no --- third-party code); the encoder loops are new. They never throw: the caller (init.luau) validates every size first, and --- hands in a source buffer that holds every byte an uncompressed loop can read (a truncated file is copied into a --- zero-padded buffer). The RLE loop checks each read against its end offset. Output: RGBA8, top-down rows, one --- u32 per pixel (R | G << 8 | B << 16 | A << 24, little-endian = bytes R, G, B, A). +-- codecs/image/Pixels: row loops between packed pixel layouts and rgba8 (native), shared by the bitmap formats (BMP, +-- the DIBs inside ICO / CUR, ...): 1 / 2 / 4 / 8-bit indexes through a palette, BGR / BGRA, 5-5-5, bit-masked 16 / +-- 24 / 32-bit pixels, RLE4 / RLE8, rows bottom-up or top-down; and the encoder direction (rgba8 -> BGR / BGRA / +-- 8-bit indexes, bottom-up). Absorbed from bmp-luau b86aed6 (same author, no third-party code); the encoder loops +-- are new. They never throw: the caller validates every size first and hands in a source buffer that holds every +-- byte an uncompressed loop can read (a truncated file is copied into a zero-padded buffer); the RLE loop checks each +-- read against its end offset. Output: rgba8, top-down rows, one u32 per pixel (bytes R, G, B, A). local readu8, readu16, readu32, writeu32, writeu8 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu32, buffer.writeu8 local band, rshift, bor, lshift = bit32.band, bit32.rshift, bit32.bor, bit32.lshift @@ -39,6 +41,19 @@ function Pixels.indexed(src: buffer, base: number, stride: number, bpp: number, end end +-- 16 bpp X-R-G-B 1-5-5-5 (BI_RGB 16-bit), opaque; 5-bit channels scaled to 8 bits with rounding +function Pixels.rgb555(src: buffer, base: number, stride: number, dst: buffer, w: number, h: number, topDown: boolean) + for r = 0, h - 1 do + local so = base + r * stride + local d = (if topDown then r else h - 1 - r) * w * 4 + for x = 0, w - 1 do + local s = readu16(src, so + x * 2) + local cr, cg, cb = band(rshift(s, 10), 31), band(rshift(s, 5), 31), band(s, 31) + writeu32(dst, d + x * 4, (cr * 255 + 15) // 31 + ((cg * 255 + 15) // 31) * 256 + ((cb * 255 + 15) // 31) * 65536 + 0xFF000000) + end + end +end + -- 24 bpp BI_RGB: B, G, R function Pixels.bgr24(src: buffer, base: number, stride: number, dst: buffer, w: number, h: number, topDown: boolean) for r = 0, h - 1 do diff --git a/src/Formats/codecs/Quantize/init.luau b/src/Formats/codecs/image/Quantize/init.luau similarity index 99% rename from src/Formats/codecs/Quantize/init.luau rename to src/Formats/codecs/image/Quantize/init.luau index 3086d63..b9edac5 100644 --- a/src/Formats/codecs/Quantize/init.luau +++ b/src/Formats/codecs/image/Quantize/init.luau @@ -1,7 +1,7 @@ --!strict --!native --!optimize 2 --- codecs/Quantize: palette quantization of rgba8 pixels. A codec (layer 1): image/gif (and later any palette +-- codecs/image/Quantize: palette quantization of rgba8 pixels. A codec (layer 1): image/gif (and later any palette -- writer) builds on it. New code: Heckbert's median cut and Gervautz-Purgathofer octree, both over a 5-bit-per-channel -- weighted histogram (palette colours are the exact means of the pixels they cover), nearest-colour mapping with -- optional Floyd-Steinberg error diffusion. Deterministic: the same palette and indexes on every runtime (no table diff --git a/src/Formats/codecs/Raster.luau b/src/Formats/codecs/image/Raster.luau similarity index 99% rename from src/Formats/codecs/Raster.luau rename to src/Formats/codecs/image/Raster.luau index ba93fda..6f9be0d 100644 --- a/src/Formats/codecs/Raster.luau +++ b/src/Formats/codecs/image/Raster.luau @@ -1,14 +1,14 @@ --!strict --!native --!optimize 2 --- codecs/Raster: an antialiased scanline rasterizer for paths of lines, quadratic and cubic Béziers, under an affine +-- codecs/image/Raster: an antialiased scanline rasterizer for paths of lines, quadratic and cubic Béziers, under an affine -- transform, with the nonzero and even-odd fill rules, plus a polygon stroker. Used by the fonts (glyph outlines) and -- by vector/svg. New code; the coverage accumulation is the signed-area method of font-rs (Raph Levien, Apache-2.0 / -- MIT, an algorithm description, no code copied) and of stb_truetype v2: every edge adds its exact signed area to an -- accumulation row; a running sum along the row gives the winding coverage of each pixel. The rules map the summed -- coverage a as FreeType does: nonzero = min(1, |a|), even-odd = |a| folded modulo 2. -- --- local R = require("@formats/codecs/Raster") +-- local R = require("@formats/codecs/image/Raster") -- local p = R.path():moveTo(0, 0):lineTo(10, 0):quadTo(10, 10, 0, 10):close() -- or a plain command list: -- local cmds = { { op = "moveTo", 0, 0 }, { op = "lineTo", 10, 0 }, { op = "cubicTo", 12, 2, 12, 8, 10, 10 }, -- { op = "close" } } -- (the Font:outline() format) diff --git a/src/Formats/codecs/Vp8/Decode.luau b/src/Formats/codecs/image/Vp8/Decode.luau similarity index 99% rename from src/Formats/codecs/Vp8/Decode.luau rename to src/Formats/codecs/image/Vp8/Decode.luau index 88f5652..b51d8b2 100644 --- a/src/Formats/codecs/Vp8/Decode.luau +++ b/src/Formats/codecs/image/Vp8/Decode.luau @@ -1,7 +1,7 @@ --!strict --!native --!optimize 2 --- codecs/Vp8/Decode: the VP8 frame decoder (RFC 6386): the boolean entropy decoder, frame / segment / filter / +-- codecs/image/Vp8/Decode: the VP8 frame decoder (RFC 6386): the boolean entropy decoder, frame / segment / filter / -- quantizer headers, token probability updates, intra modes, residual tokens, the inverse WHT and DCT, intra -- prediction (16x16, 4x4, chroma), and the normal and simple loop filters: a port of libwebp 1.6 src/dec/vp8_dec.c, -- tree_dec.c, quant_dec.c, frame_dec.c, src/dsp/dec.c and src/utils/bit_reader* (BSD-3-Clause, @@ -9,15 +9,15 @@ -- vp8/common/findnearmv.c, vp8_loopfilter.c (BSD-3-Clause, licenses/libvpx-LICENSE.txt): reference updates and sign -- bias, the frame context saved around frames that do not refresh it, persistent segment maps and loop filter deltas, -- inter modes from the near vectors, motion vectors, split macroblocks, intra macroblocks in inter frames, per --- reference / mode loop filter levels; the prediction itself is codecs/Vp8/Predict. Bit-exact with libvpx / ffmpeg +-- reference / mode loop filter levels; the prediction itself is codecs/image/Vp8/Predict. Bit-exact with libvpx / ffmpeg -- (and with libwebp on key frames). Where libvpx and ffmpeg disagree on streams no encoder writes (an intermediate -- clamp of segment filter levels, copying golden to altref and altref to golden in one frame), this follows ffmpeg. -- -- The decoder state (Decode.new) keeps what persists between frames: the frame context, segment / filter headers, the -- segment map, the last / golden / altref frames. Never throws: bad data returns nil, "message" ("truncated: ..." when -- the data ends early). -local Tables = require("@formats/codecs/Vp8/Tables") -local Predict = require("@formats/codecs/Vp8/Predict") +local Tables = require("@formats/codecs/image/Vp8/Tables") +local Predict = require("@formats/codecs/image/Vp8/Predict") local band, bor, rshift, lshift = bit32.band, bit32.bor, bit32.rshift, bit32.lshift local readu8, writeu8, readi16, writei16 = buffer.readu8, buffer.writeu8, buffer.readi16, buffer.writei16 diff --git a/src/Formats/codecs/Vp8/Predict.luau b/src/Formats/codecs/image/Vp8/Predict.luau similarity index 97% rename from src/Formats/codecs/Vp8/Predict.luau rename to src/Formats/codecs/image/Vp8/Predict.luau index 536ddea..c6f4de8 100644 --- a/src/Formats/codecs/Vp8/Predict.luau +++ b/src/Formats/codecs/image/Vp8/Predict.luau @@ -1,14 +1,14 @@ --!strict --!native --!optimize 2 --- codecs/Vp8/Predict: VP8 inter prediction (RFC 6386 section 18): the six-tap sub-pixel filters (version 0), the +-- codecs/image/Vp8/Predict: VP8 inter prediction (RFC 6386 section 18): the six-tap sub-pixel filters (version 0), the -- bilinear ones (versions 1-3; version 3 also rounds chroma vectors to full pixels), chroma vectors derived from the -- luma ones, split macroblocks, and the reference frame borders. After libvpx 1.17 vp8/common/reconinter.c and -- filter.c (BSD-3-Clause, licenses/libvpx-LICENSE.txt). Out-of-frame motion reads the reference as if its edge pixels -- extended forever, which is exactly what libvpx computes with its 32 pixel border plus its motion vector clamping (the -- clamps only kick in once every tap is in the border). The planes keep a BORDER pixel border filled by extend(); a -- block whose taps leave it is first copied with clamped coordinates. Never throws. -local Tables = require("@formats/codecs/Vp8/Tables") +local Tables = require("@formats/codecs/image/Vp8/Tables") local readu8, writeu8, bcopy, bcreate, bfill = buffer.readu8, buffer.writeu8, buffer.copy, buffer.create, buffer.fill local readu32, writeu32 = buffer.readu32, buffer.writeu32 @@ -20,7 +20,7 @@ local Predict = {} local BORDER = 32 Predict.BORDER = BORDER --- the work buffer stride (codecs/Vp8/Decode: BPS) +-- the work buffer stride (codecs/image/Vp8/Decode: BPS) local BPS = 32 local emu = bcreate(32 * 32) -- a block with its taps, edges replicated diff --git a/src/Formats/codecs/Vp8/Tables.luau b/src/Formats/codecs/image/Vp8/Tables.luau similarity index 99% rename from src/Formats/codecs/Vp8/Tables.luau rename to src/Formats/codecs/image/Vp8/Tables.luau index 21dc1cf..7bbdb4a 100644 --- a/src/Formats/codecs/Vp8/Tables.luau +++ b/src/Formats/codecs/image/Vp8/Tables.luau @@ -1,5 +1,5 @@ --!strict --- codecs/Vp8/Tables: the constant VP8 tables of RFC 6386 (sections 13.5, 13.4, 11.5, 14.1), copied from libwebp 1.6 +-- codecs/image/Vp8/Tables: the constant VP8 tables of RFC 6386 (sections 13.5, 13.4, 11.5, 14.1), copied from libwebp 1.6 -- src/dec/tree_dec.c and src/dec/quant_dec.c (BSD-3-Clause, licenses/libwebp-LICENSE.txt); the inter frame tables -- (sections 16-18: mode / motion vector probabilities, mode contexts, split partitions, sub-pixel filters) from -- libvpx 1.17 vp8/common (entropymode.c, vp8_entropymodedata.h, entropymv.c, modecont.c, decodemv.c, filter.c; diff --git a/src/Formats/codecs/Vp8/Yuv.luau b/src/Formats/codecs/image/Vp8/Yuv.luau similarity index 97% rename from src/Formats/codecs/Vp8/Yuv.luau rename to src/Formats/codecs/image/Vp8/Yuv.luau index 5668738..720fe65 100644 --- a/src/Formats/codecs/Vp8/Yuv.luau +++ b/src/Formats/codecs/image/Vp8/Yuv.luau @@ -1,7 +1,7 @@ --!strict --!native --!optimize 2 --- codecs/Vp8/Yuv: 4:2:0 Y'CbCr (BT.601, limited range) to rgba8 the way libwebp's decoder does it, bit-exact: the +-- codecs/image/Vp8/Yuv: 4:2:0 Y'CbCr (BT.601, limited range) to rgba8 the way libwebp's decoder does it, bit-exact: the -- 14-bit fixed-point VP8YuvToRgb of src/dsp/yuv.h, with either the "fancy" upsampler (src/dsp/upsampling.c: a 9-3-3-1 -- bilinear filter on the chroma, libwebp's default) or point sampling (dwebp -nofancy). A port of libwebp 1.6 -- (BSD-3-Clause, licenses/libwebp-LICENSE.txt). diff --git a/src/Formats/codecs/Vp8/init.luau b/src/Formats/codecs/image/Vp8/init.luau similarity index 96% rename from src/Formats/codecs/Vp8/init.luau rename to src/Formats/codecs/image/Vp8/init.luau index d9a6f2a..bfff1b1 100644 --- a/src/Formats/codecs/Vp8/init.luau +++ b/src/Formats/codecs/image/Vp8/init.luau @@ -1,5 +1,5 @@ --!strict --- codecs/Vp8: the VP8 video codec (RFC 6386), decode only. A codec (layer 1): image/webp uses it for lossy frames, the +-- codecs/image/Vp8: the VP8 video codec (RFC 6386), decode only. A codec (layer 1): image/webp uses it for lossy frames, the -- WebM / Matroska and IVF video tracks use its decoder object. Key frames are a port of libwebp 1.6 (BSD-3-Clause, -- licenses/libwebp-LICENSE.txt), bit-exact with libwebp: the yuv420p planes equal `dwebp -yuv`, and toRgba equals -- `dwebp -pam` (fancy upsampling) or `dwebp -nofancy -pam`. Inter frames follow libvpx 1.17 (BSD-3-Clause, @@ -12,7 +12,7 @@ -- Speed (one Zen 5 core): 640x480 inter frames ~190 fps under luau --codegen, ~220 fps under LuaJIT with the trace -- limits the host module sets (maxtrace=8000; with LuaJIT's default 1000 traces the decoder thrashes: ~70 fps). -- --- local Vp8 = require("@formats/codecs/Vp8") +-- local Vp8 = require("@formats/codecs/image/Vp8") -- local frame, err = Vp8.decodeFrame(buf, off, len) -- one key frame: a yuv420p Types.Image -- local rgba = Vp8.toRgba(frame) -- rgba8 Image (libwebp's fancy upsampling) -- local dec = Vp8.newDecoder() -- a stream (WebM, IVF): key and inter frames @@ -22,8 +22,8 @@ -- Never throws: bad data returns nil, Err (core/Err codes TRUNCATED / CORRUPT / UNSUPPORTED / LIMIT / ARG). local Err = require("@formats/core/Err") local Types = require("@formats/Types") -local Decode = require("@formats/codecs/Vp8/Decode") -local Yuv = require("@formats/codecs/Vp8/Yuv") +local Decode = require("@formats/codecs/image/Vp8/Decode") +local Yuv = require("@formats/codecs/image/Vp8/Yuv") local Vp8 = {} diff --git a/src/Formats/codecs/Vp8L/Decode.luau b/src/Formats/codecs/image/Vp8L/Decode.luau similarity index 99% rename from src/Formats/codecs/Vp8L/Decode.luau rename to src/Formats/codecs/image/Vp8L/Decode.luau index 547167c..a8b202c 100644 --- a/src/Formats/codecs/Vp8L/Decode.luau +++ b/src/Formats/codecs/image/Vp8L/Decode.luau @@ -1,7 +1,7 @@ --!strict --!native --!optimize 2 --- codecs/Vp8L/Decode: the WebP lossless (VP8L) bitstream decoder: prefix codes (two-level tables), meta prefix codes, +-- codecs/image/Vp8L/Decode: the WebP lossless (VP8L) bitstream decoder: prefix codes (two-level tables), meta prefix codes, -- LZ77 backward references with the 2-D distance map, the colour cache, and the four inverse transforms (predictor, -- cross colour, subtract green, colour indexing with pixel bundling). A port of libwebp 1.6 src/dec/vp8l_dec.c, -- src/utils/huffman_utils.c and src/dsp/lossless.c (BSD-3-Clause, licenses/libwebp-LICENSE.txt); bit-exact with it. diff --git a/src/Formats/codecs/Vp8L/Encode.luau b/src/Formats/codecs/image/Vp8L/Encode.luau similarity index 99% rename from src/Formats/codecs/Vp8L/Encode.luau rename to src/Formats/codecs/image/Vp8L/Encode.luau index 1eff41a..9f15934 100644 --- a/src/Formats/codecs/Vp8L/Encode.luau +++ b/src/Formats/codecs/image/Vp8L/Encode.luau @@ -1,13 +1,13 @@ --!strict --!native --!optimize 2 --- codecs/Vp8L/Encode: a WebP lossless (VP8L) encoder, new code written from the specification (RFC 9649 section 3). +-- codecs/image/Vp8L/Encode: a WebP lossless (VP8L) encoder, new code written from the specification (RFC 9649 section 3). -- Transforms: colour indexing with pixel bundling (<= 256 colours), else subtract green + predictor (per-tile mode -- chosen from a residual cost) + cross colour (per-tile least-squares multipliers). Entropy coding: LZ77 with hash -- chains, the left / up run candidates and the 2-D distance codes, a colour cache whose size is chosen by an entropy --- estimate, one prefix code group per image, code lengths limited to 15 bits (core/Huffman) and run-length coded. +-- estimate, one prefix code group per image, code lengths limited to 15 bits (codecs/entropy/Huffman) and run-length coded. -- Never throws (the init module validates the arguments). -local Huffman = require("@formats/core/Huffman") +local Huffman = require("@formats/codecs/entropy/Huffman") local band, bor, bxor, lshift, rshift = bit32.band, bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift local readu32, writeu8, writeu32 = buffer.readu32, buffer.writeu8, buffer.writeu32 @@ -143,7 +143,7 @@ local function half(x: number, y: number): number return clip255(x + (if dd >= 0 then rshift(dd, 1) else -rshift(-dd, 1))) end --- predict(mode, L, T, TR, TL): the decoder's predictors (codecs/Vp8L/Decode) +-- predict(mode, L, T, TR, TL): the decoder's predictors (codecs/image/Vp8L/Decode) local function predict(mode: number, L: number, T: number, TR: number, TL: number): number if mode == 1 then return L diff --git a/src/Formats/codecs/Vp8L/init.luau b/src/Formats/codecs/image/Vp8L/init.luau similarity index 94% rename from src/Formats/codecs/Vp8L/init.luau rename to src/Formats/codecs/image/Vp8L/init.luau index d35d7e1..1edd539 100644 --- a/src/Formats/codecs/Vp8L/init.luau +++ b/src/Formats/codecs/image/Vp8L/init.luau @@ -1,20 +1,20 @@ --!strict --- codecs/Vp8L: WebP lossless (VP8L, "WebP Lossless Bitstream Specification", RFC 9649 section 3). A codec (layer 1): +-- codecs/image/Vp8L: WebP lossless (VP8L, "WebP Lossless Bitstream Specification", RFC 9649 section 3). A codec (layer 1): -- image/webp uses it for VP8L frames and for compressed ALPH planes; other containers may carry it too. -- Decoder: a port of libwebp 1.6 (BSD-3-Clause, licenses/libwebp-LICENSE.txt), bit-exact with it. Encoder: new -- (subtract green, predictor and cross-colour transforms with per-tile mode search, colour indexing with pixel -- bundling for <= 256 colours, LZ77 with hash chains and the 2-D distance codes, a colour cache chosen by entropy, -- one prefix code group per image or meta codes for big images). -- --- local Vp8L = require("@formats/codecs/Vp8L") +-- local Vp8L = require("@formats/codecs/image/Vp8L") -- local rgba, w, h, alpha = Vp8L.decode(buf, off, len) -- a VP8L bitstream (0x2f signature) -> rgba8 -- local a8 = Vp8L.decodeAlpha(buf, off, len, w, h) -- a headerless stream's green channel (ALPH) -- local bits = Vp8L.encode(rgba, w, h, { effort = 4 }) -- rgba8 -> a VP8L bitstream -- -- Never throws: bad data returns nil, Err (core/Err codes TRUNCATED / CORRUPT / LIMIT / ARG). local Err = require("@formats/core/Err") -local Decode = require("@formats/codecs/Vp8L/Decode") -local Encode = require("@formats/codecs/Vp8L/Encode") +local Decode = require("@formats/codecs/image/Vp8L/Decode") +local Encode = require("@formats/codecs/image/Vp8L/Encode") local Vp8L = {} diff --git a/src/Formats/codecs/Yuv.luau b/src/Formats/codecs/image/Yuv.luau similarity index 98% rename from src/Formats/codecs/Yuv.luau rename to src/Formats/codecs/image/Yuv.luau index cfa8258..fe331ee 100644 --- a/src/Formats/codecs/Yuv.luau +++ b/src/Formats/codecs/image/Yuv.luau @@ -1,7 +1,7 @@ --!strict --!native --!optimize 2 --- codecs/Yuv: planar 4:2:0 Y'CbCr <-> rgba8 for the video codecs and writers (native; never throws). BT.601 or +-- codecs/image/Yuv: planar 4:2:0 Y'CbCr <-> rgba8 for the video codecs and writers (native; never throws). BT.601 or -- BT.709 matrices, limited ("tv", 16..235 / 16..240: VP8, MPEG-1, H.264) or full ("pc", 0..255: MJPEG / JPEG) range. -- yuv -> rgb uses nearest chroma and 16-bit fixed point with swscale's default (non-accurate) coefficients, so the -- result is within about one level of `ffmpeg -pix_fmt rgba`; rgb -> yuv averages each 2x2 block for the chroma diff --git a/src/Formats/codecs/model/Mat4.luau b/src/Formats/codecs/model/Mat4.luau new file mode 100644 index 0000000..59b63ff --- /dev/null +++ b/src/Formats/codecs/model/Mat4.luau @@ -0,0 +1,282 @@ +--!strict +-- codecs/model/Mat4: 4x4 matrix and quaternion helpers for the model formats: column-major flat arrays of 16 +-- (glTF / FBX / Types.Scene layout: translation at 13..15), quaternions { x, y, z, w }, angles in degrees where a +-- format stores degrees. Shared by FBX, Collada, USD and MeshOps instead of a copy in each. New in formats-luau (the +-- functions come from the former model/fbx/Xform, model/dae/Math and model/usda/Build helpers). +-- +-- local m = Mat4.compose({ 1, 2, 3 }, quat, { 2, 2, 2 }) -- T * R * S +-- local t, r, s = Mat4.decompose(m) -- (decomposeStrict: nil for shear / projective / singular) +-- local w = Mat4.mul(parent, m) -- = Types.Scene.mul +-- local inv = Mat4.inverse(m) -- affine inverse | nil +-- local x, y, z = Mat4.point(m, px, py, pz) +local Types = require("@formats/Types") + +local Mat4 = {} + +export type M4 = { number } + +local sqrt, abs, sin, cos, rad = math.sqrt, math.abs, math.sin, math.cos, math.rad + +function Mat4.identity(): M4 + return { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 } +end + +-- mul(a, b) -> a * b +Mat4.mul = Types.Scene.mul + +function Mat4.translation(x: number, y: number, z: number): M4 + return { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1 } +end + +function Mat4.scaling(x: number, y: number, z: number): M4 + return { x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1 } +end + +-- rotation(axis, degrees) -> the rotation about axis 1 (X), 2 (Y) or 3 (Z) +function Mat4.rotation(axis: number, degrees: number): M4 + local a = rad(degrees) + local c, s = cos(a), sin(a) + if axis == 1 then + return { 1, 0, 0, 0, 0, c, s, 0, 0, -s, c, 0, 0, 0, 0, 1 } + elseif axis == 2 then + return { c, 0, -s, 0, 0, 1, 0, 0, s, 0, c, 0, 0, 0, 0, 1 } + end + return { c, s, 0, 0, -s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 } +end + +local AXIS = { x = 1, y = 2, z = 3 } +-- euler(x, y, z, order?) -> the rotation applying the axes in order (default "xyz": R = Rz * Ry * Rx), degrees +function Mat4.euler(x: number, y: number, z: number, order: string?): M4 + local o = order or "xyz" + local deg = { x = x, y = y, z = z } + local m = Mat4.identity() + for i = 1, 3 do + local a = string.sub(o, i, i) + m = Mat4.mul(Mat4.rotation(AXIS[a] or i, deg[a] or 0), m) + end + return m +end + +-- axisAngle(x, y, z, degrees) -> quaternion +function Mat4.axisAngle(x: number, y: number, z: number, degrees: number): { number } + local l = sqrt(x * x + y * y + z * z) + if l < 1e-12 then + return { 0, 0, 0, 1 } + end + local h = rad(degrees) / 2 + local s = sin(h) / l + return { x * s, y * s, z * s, cos(h) } +end + +-- fromQuat(q) -> the rotation matrix of a quaternion +function Mat4.fromQuat(q: { number }): M4 + local x, y, z, w = q[1], q[2], q[3], q[4] + local xx, yy, zz, xy, xz, yz, wx, wy, wz = x * x, y * y, z * z, x * y, x * z, y * z, w * x, w * y, w * z + return { + 1 - 2 * (yy + zz), 2 * (xy + wz), 2 * (xz - wy), 0, + 2 * (xy - wz), 1 - 2 * (xx + zz), 2 * (yz + wx), 0, + 2 * (xz + wy), 2 * (yz - wx), 1 - 2 * (xx + yy), 0, + 0, 0, 0, 1, + } +end + +-- quat(m) -> the unit quaternion of the rotation in m's upper 3x3 (columns assumed orthonormal) +function Mat4.quat(m: M4): { number } + local m00, m01, m02 = m[1], m[5], m[9] + local m10, m11, m12 = m[2], m[6], m[10] + local m20, m21, m22 = m[3], m[7], m[11] + local tr = m00 + m11 + m22 + local x, y, z, w + if tr > 0 then + local s = sqrt(tr + 1) * 2 + w, x, y, z = s / 4, (m21 - m12) / s, (m02 - m20) / s, (m10 - m01) / s + elseif m00 > m11 and m00 > m22 then + local s = sqrt(math.max(1 + m00 - m11 - m22, 1e-30)) * 2 + w, x, y, z = (m21 - m12) / s, s / 4, (m01 + m10) / s, (m02 + m20) / s + elseif m11 > m22 then + local s = sqrt(math.max(1 + m11 - m00 - m22, 1e-30)) * 2 + w, x, y, z = (m02 - m20) / s, (m01 + m10) / s, s / 4, (m12 + m21) / s + else + local s = sqrt(math.max(1 + m22 - m00 - m11, 1e-30)) * 2 + w, x, y, z = (m10 - m01) / s, (m02 + m20) / s, (m12 + m21) / s, s / 4 + end + local n = sqrt(x * x + y * y + z * z + w * w) + if n == 0 or n ~= n then + return { 0, 0, 0, 1 } + end + return { x / n, y / n, z / n, w / n } +end + +-- eulerXYZ(q) -> Euler XYZ degrees (R = Rz * Ry * Rx) of a quaternion +function Mat4.eulerXYZ(q: { number }): { number } + local m = Mat4.fromQuat(q) + local sy = math.clamp(-m[3], -1, 1) -- m[3] = r20 = -sin(y) + local y = math.asin(sy) + local x, z + if abs(sy) < 0.9999999 then + x = math.atan2(m[7], m[11]) + z = math.atan2(m[2], m[1]) + else + x = math.atan2(-m[10], m[6]) + z = 0 + end + return { math.deg(x), math.deg(y), math.deg(z) } +end + +-- compose(t?, r?, s?) -> T * R * S (glTF node semantics) +function Mat4.compose(t: { number }?, r: { number }?, s: { number }?): M4 + local m = if r then Mat4.fromQuat(r) else Mat4.identity() + if s then + for k = 0, 2 do + m[k * 4 + 1] *= s[k + 1] + m[k * 4 + 2] *= s[k + 1] + m[k * 4 + 3] *= s[k + 1] + end + end + if t then + m[13], m[14], m[15] = t[1], t[2], t[3] + end + return m +end + +local function det3(m: M4): number + return m[1] * (m[6] * m[11] - m[10] * m[7]) - m[5] * (m[2] * m[11] - m[10] * m[3]) + m[9] * (m[2] * m[7] - m[6] * m[3]) +end + +local function split(m: M4, strict: boolean): ({ number }?, { number }?, { number }?) + if strict and (abs(m[4]) > 1e-6 or abs(m[8]) > 1e-6 or abs(m[12]) > 1e-6 or abs(m[16] - 1) > 1e-6) then + return nil, nil, nil + end + local sx = sqrt(m[1] * m[1] + m[2] * m[2] + m[3] * m[3]) + local sy = sqrt(m[5] * m[5] + m[6] * m[6] + m[7] * m[7]) + local sz = sqrt(m[9] * m[9] + m[10] * m[10] + m[11] * m[11]) + if strict and (sx < 1e-12 or sy < 1e-12 or sz < 1e-12) then + return nil, nil, nil + end + if det3(m) < 0 then + sx = -sx + end + local ix = if sx ~= 0 then 1 / sx else 0 + local iy = if sy ~= 0 then 1 / sy else 0 + local iz = if sz ~= 0 then 1 / sz else 0 + local r = { m[1] * ix, m[2] * ix, m[3] * ix, 0, m[5] * iy, m[6] * iy, m[7] * iy, 0, m[9] * iz, m[10] * iz, m[11] * iz, 0, 0, 0, 0, 1 } + if strict then + local dxy = r[1] * r[5] + r[2] * r[6] + r[3] * r[7] + local dxz = r[1] * r[9] + r[2] * r[10] + r[3] * r[11] + local dyz = r[5] * r[9] + r[6] * r[10] + r[7] * r[11] + if abs(dxy) > 1e-4 or abs(dxz) > 1e-4 or abs(dyz) > 1e-4 then + return nil, nil, nil + end + end + return { m[13], m[14], m[15] }, Mat4.quat(r), { sx, sy, sz } +end + +-- decompose(m) -> translation, rotation (quaternion), scale (a negative determinant flips the x scale; shear is lost) +function Mat4.decompose(m: M4): ({ number }, { number }, { number }) + local t, r, s = split(m, false) + return t :: { number }, r :: { number }, s :: { number } +end + +-- decomposeStrict(m) -> translation, rotation, scale | nil for matrices TRS cannot express (a projective row, shear, +-- a zero scale) +function Mat4.decomposeStrict(m: M4): ({ number }?, { number }?, { number }?) + return split(m, true) +end + +-- inverse(m) -> the inverse of an affine matrix (general upper 3x3) | nil when singular +function Mat4.inverse(m: M4): M4? + local a, b, c = m[1], m[5], m[9] + local d, e, f = m[2], m[6], m[10] + local g, h, i = m[3], m[7], m[11] + local A, B, C = e * i - f * h, -(d * i - f * g), d * h - e * g + local det = a * A + b * B + c * C + if det == 0 or det ~= det then + return nil + end + local k = 1 / det + local r = { + A * k, B * k, C * k, 0, + -(b * i - c * h) * k, (a * i - c * g) * k, -(a * h - b * g) * k, 0, + (b * f - c * e) * k, -(a * f - c * d) * k, (a * e - b * d) * k, 0, + 0, 0, 0, 1, + } + local tx, ty, tz = m[13], m[14], m[15] + r[13] = -(r[1] * tx + r[5] * ty + r[9] * tz) + r[14] = -(r[2] * tx + r[6] * ty + r[10] * tz) + r[15] = -(r[3] * tx + r[7] * ty + r[11] * tz) + return r +end + +-- inverseFull(m) -> the inverse of any invertible 4x4 (projective rows too) | nil when singular +function Mat4.inverseFull(m: M4): M4? + local a = m + local inv = table.create(16, 0) + inv[1] = a[6] * a[11] * a[16] - a[6] * a[12] * a[15] - a[10] * a[7] * a[16] + a[10] * a[8] * a[15] + a[14] * a[7] * a[12] - a[14] * a[8] * a[11] + inv[5] = -a[5] * a[11] * a[16] + a[5] * a[12] * a[15] + a[9] * a[7] * a[16] - a[9] * a[8] * a[15] - a[13] * a[7] * a[12] + a[13] * a[8] * a[11] + inv[9] = a[5] * a[10] * a[16] - a[5] * a[12] * a[14] - a[9] * a[6] * a[16] + a[9] * a[8] * a[14] + a[13] * a[6] * a[12] - a[13] * a[8] * a[10] + inv[13] = -a[5] * a[10] * a[15] + a[5] * a[11] * a[14] + a[9] * a[6] * a[15] - a[9] * a[7] * a[14] - a[13] * a[6] * a[11] + a[13] * a[7] * a[10] + inv[2] = -a[2] * a[11] * a[16] + a[2] * a[12] * a[15] + a[10] * a[3] * a[16] - a[10] * a[4] * a[15] - a[14] * a[3] * a[12] + a[14] * a[4] * a[11] + inv[6] = a[1] * a[11] * a[16] - a[1] * a[12] * a[15] - a[9] * a[3] * a[16] + a[9] * a[4] * a[15] + a[13] * a[3] * a[12] - a[13] * a[4] * a[11] + inv[10] = -a[1] * a[10] * a[16] + a[1] * a[12] * a[14] + a[9] * a[2] * a[16] - a[9] * a[4] * a[14] - a[13] * a[2] * a[12] + a[13] * a[4] * a[10] + inv[14] = a[1] * a[10] * a[15] - a[1] * a[11] * a[14] - a[9] * a[2] * a[15] + a[9] * a[3] * a[14] + a[13] * a[2] * a[11] - a[13] * a[3] * a[10] + inv[3] = a[2] * a[7] * a[16] - a[2] * a[8] * a[15] - a[6] * a[3] * a[16] + a[6] * a[4] * a[15] + a[14] * a[3] * a[8] - a[14] * a[4] * a[7] + inv[7] = -a[1] * a[7] * a[16] + a[1] * a[8] * a[15] + a[5] * a[3] * a[16] - a[5] * a[4] * a[15] - a[13] * a[3] * a[8] + a[13] * a[4] * a[7] + inv[11] = a[1] * a[6] * a[16] - a[1] * a[8] * a[14] - a[5] * a[2] * a[16] + a[5] * a[4] * a[14] + a[13] * a[2] * a[8] - a[13] * a[4] * a[6] + inv[15] = -a[1] * a[6] * a[15] + a[1] * a[7] * a[14] + a[5] * a[2] * a[15] - a[5] * a[3] * a[14] - a[13] * a[2] * a[7] + a[13] * a[3] * a[6] + inv[4] = -a[2] * a[7] * a[12] + a[2] * a[8] * a[11] + a[6] * a[3] * a[12] - a[6] * a[4] * a[11] - a[10] * a[3] * a[8] + a[10] * a[4] * a[7] + inv[8] = a[1] * a[7] * a[12] - a[1] * a[8] * a[11] - a[5] * a[3] * a[12] + a[5] * a[4] * a[11] + a[9] * a[3] * a[8] - a[9] * a[4] * a[7] + inv[12] = -a[1] * a[6] * a[12] + a[1] * a[8] * a[10] + a[5] * a[2] * a[12] - a[5] * a[4] * a[10] - a[9] * a[2] * a[8] + a[9] * a[4] * a[6] + inv[16] = a[1] * a[6] * a[11] - a[1] * a[7] * a[10] - a[5] * a[2] * a[11] + a[5] * a[3] * a[10] + a[9] * a[2] * a[7] - a[9] * a[3] * a[6] + local det = a[1] * inv[1] + a[2] * inv[5] + a[3] * inv[9] + a[4] * inv[13] + if det == 0 or det ~= det then + return nil + end + for k = 1, 16 do + inv[k] /= det + end + return inv +end + +-- transpose3(m) -> m with its upper 3x3 transposed and no translation (the inverse of a pure rotation) +function Mat4.transpose3(m: M4): M4 + return { m[1], m[5], m[9], 0, m[2], m[6], m[10], 0, m[3], m[7], m[11], 0, 0, 0, 0, 1 } +end + +-- fromRows(v, at?) -> column-major from 16 row-major values at v[at] (default 1; missing values: identity) +function Mat4.fromRows(v: { number }, at: number?): M4 + local o = (at or 1) - 1 + local m = table.create(16, 0) + for r = 0, 3 do + for c = 0, 3 do + m[c * 4 + r + 1] = v[o + r * 4 + c + 1] or (if r == c then 1 else 0) + end + end + return m +end + +-- toRows(m) -> the 16 values row-major +function Mat4.toRows(m: M4): { number } + local v = table.create(16, 0) + for r = 0, 3 do + for c = 0, 3 do + v[r * 4 + c + 1] = m[c * 4 + r + 1] + end + end + return v +end + +-- point(m, x, y, z) -> m * (x, y, z, 1) +function Mat4.point(m: M4, x: number, y: number, z: number): (number, number, number) + return m[1] * x + m[5] * y + m[9] * z + m[13], m[2] * x + m[6] * y + m[10] * z + m[14], m[3] * x + m[7] * y + m[11] * z + m[15] +end + +-- normalMatrix(m) -> the inverse transpose of the upper 3x3 (for normals) as a 4x4 (identity when singular) +function Mat4.normalMatrix(m: M4): M4 + local inv = Mat4.inverse({ m[1], m[2], m[3], 0, m[5], m[6], m[7], 0, m[9], m[10], m[11], 0, 0, 0, 0, 1 }) + if not inv then + return Mat4.identity() + end + return Mat4.transpose3(inv) +end + +return Mat4 diff --git a/src/Formats/codecs/MeshFlatten.luau b/src/Formats/codecs/model/MeshFlatten.luau similarity index 99% rename from src/Formats/codecs/MeshFlatten.luau rename to src/Formats/codecs/model/MeshFlatten.luau index 8d2ab73..3c26fc6 100644 --- a/src/Formats/codecs/MeshFlatten.luau +++ b/src/Formats/codecs/model/MeshFlatten.luau @@ -1,5 +1,5 @@ --!strict --- codecs/MeshFlatten: a Scene to one world-space mesh, for the writers of mesh-only formats (STL, PLY, OFF). Walks +-- codecs/model/MeshFlatten: a Scene to one world-space mesh, for the writers of mesh-only formats (STL, PLY, OFF). Walks -- scene.roots recursively (TRS or column-major `matrix` per node; a scene without nodes uses its meshes as they are), -- applies the transforms to POSITION (and the inverse transpose to NORMAL), reverses the winding under mirroring -- transforms, reads every accessor type to numbers and concatenates all primitives (triangles with or without indices, diff --git a/src/Formats/codecs/Json/Decode.luau b/src/Formats/codecs/text/Json/Decode.luau similarity index 98% rename from src/Formats/codecs/Json/Decode.luau rename to src/Formats/codecs/text/Json/Decode.luau index 4d97f82..eb58b45 100644 --- a/src/Formats/codecs/Json/Decode.luau +++ b/src/Formats/codecs/text/Json/Decode.luau @@ -1,10 +1,10 @@ --!strict --!native --- codecs/Json/Decode: the RFC 8259 parser behind codecs/Json. Iterative (an explicit container stack, so deep nesting +-- codecs/text/Json/Decode: the RFC 8259 parser behind codecs/text/Json. Iterative (an explicit container stack, so deep nesting -- is a LIMIT error, never a stack overflow), strict grammar (no comments, trailing commas, leading zeros, NaN, single -- quotes or raw control characters), \u escapes with surrogate pairs (lone surrogates become WTF-8 bytes). Also the -- pull tokenizer behind Json.events. Never throws: failures return nil, message, offset (0-based byte offset). -local Text = require("@formats/codecs/Text") +local Text = require("@formats/codecs/text/Text") local Types = require("@formats/Types") local Decode = {} diff --git a/src/Formats/codecs/Json/Encode.luau b/src/Formats/codecs/text/Json/Encode.luau similarity index 98% rename from src/Formats/codecs/Json/Encode.luau rename to src/Formats/codecs/text/Json/Encode.luau index 78d0ac5..6e7fdce 100644 --- a/src/Formats/codecs/Json/Encode.luau +++ b/src/Formats/codecs/text/Json/Encode.luau @@ -1,6 +1,6 @@ --!strict --!native --- codecs/Json/Encode: the serializer behind codecs/Json. Compact or pretty (indent), objects in their Types.object key +-- codecs/text/Json/Encode: the serializer behind codecs/text/Json. Compact or pretty (indent), objects in their Types.object key -- order (plain tables: sorted keys), arrays for tables with keys 1..n, shortest round-trip number text, optional -- ASCII-only output. Never throws: bad values (cycles, NaN / inf, functions, non-string keys that are not numbers) -- return nil, message. diff --git a/src/Formats/codecs/Json/init.luau b/src/Formats/codecs/text/Json/init.luau similarity index 96% rename from src/Formats/codecs/Json/init.luau rename to src/Formats/codecs/text/Json/init.luau index f9b6204..fd50051 100644 --- a/src/Formats/codecs/Json/init.luau +++ b/src/Formats/codecs/text/Json/init.luau @@ -1,10 +1,10 @@ --!strict --- codecs/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code. +-- codecs/text/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code. -- Values are plain Luau: objects -> tables (string keys), arrays -> arrays, null -> Types.null (opts.null), numbers -- -> doubles (opts.bigInts = "string" keeps integers past 2^53 as their text). Empty objects are Types.object() so -- they write back as {}; opts.ordered makes every object a Types.object with its key order. -- --- local Json = require("@formats/codecs/Json") +-- local Json = require("@formats/codecs/text/Json") -- local v, err = Json.decode('{"a": [1, 2, null]}') -- string | buffer; nil, Err on bad input -- local s = Json.encode(v, { indent = 2 }) -- string | nil, Err -- for ev, x in Json.events(text) do ... end -- pull events without building the tree @@ -15,8 +15,8 @@ -- writer() builds output incrementally and flush() hands back the text so far. Never throws. local Err = require("@formats/core/Err") local Types = require("@formats/Types") -local Decode = require("@formats/codecs/Json/Decode") -local Encode = require("@formats/codecs/Json/Encode") +local Decode = require("@formats/codecs/text/Json/Decode") +local Encode = require("@formats/codecs/text/Json/Encode") local Json = {} diff --git a/src/Formats/codecs/Text/init.luau b/src/Formats/codecs/text/Text/init.luau similarity index 94% rename from src/Formats/codecs/Text/init.luau rename to src/Formats/codecs/text/Text/init.luau index 74f86fb..6980e96 100644 --- a/src/Formats/codecs/Text/init.luau +++ b/src/Formats/codecs/text/Text/init.luau @@ -1,6 +1,6 @@ --!strict --!optimize 2 --- codecs/Text: text decoding helpers for the text formats: a UTF-8 BOM is stripped, text that is not valid UTF-8 is +-- codecs/text/Text: text decoding helpers for the text formats: a UTF-8 BOM is stripped, text that is not valid UTF-8 is -- read as Windows-1252 (classic .m3u / .pls / .ini / .srt files), lines split on CRLF / CR / LF, trim. Absorbed from -- playlist-luau 3fc7fd3 (same author, no third-party code). Never throws. local Text = {} diff --git a/src/Formats/codecs/Url/init.luau b/src/Formats/codecs/text/Url/init.luau similarity index 98% rename from src/Formats/codecs/Url/init.luau rename to src/Formats/codecs/text/Url/init.luau index 026ecb5..19b359b 100644 --- a/src/Formats/codecs/Url/init.luau +++ b/src/Formats/codecs/text/Url/init.luau @@ -1,6 +1,6 @@ --!strict --!optimize 2 --- codecs/Url: RFC 3986 reference resolution (section 5.2), the classification of a playlist / manifest location (URL, +-- codecs/text/Url: RFC 3986 reference resolution (section 5.2), the classification of a playlist / manifest location (URL, -- Windows / UNC / POSIX local path, relative reference) and percent-encoding of bytes that may not appear in a URI -- (raw spaces and UTF-8 in playlists). Shared by the playlist formats (m3u / HLS, pls, xspf); later DASH / glTF URIs. -- Absorbed from playlist-luau 3fc7fd3 (same author, no third-party code): Url.luau, plus locate / base from its diff --git a/src/Formats/codecs/Xml/Parse.luau b/src/Formats/codecs/text/Xml/Parse.luau similarity index 99% rename from src/Formats/codecs/Xml/Parse.luau rename to src/Formats/codecs/text/Xml/Parse.luau index cf39eca..57aa477 100644 --- a/src/Formats/codecs/Xml/Parse.luau +++ b/src/Formats/codecs/text/Xml/Parse.luau @@ -1,13 +1,13 @@ --!strict --!native --- codecs/Xml/Parse: the XML 1.0 pull parser behind codecs/Xml. Input decoding (UTF-8, UTF-16 LE / BE by BOM or +-- codecs/text/Xml/Parse: the XML 1.0 pull parser behind codecs/text/Xml. Input decoding (UTF-8, UTF-16 LE / BE by BOM or -- by the first bytes, ISO-8859-1 / US-ASCII / Windows-1252 by the declaration), line-ending normalization, the -- well-formedness rules that matter (one root, matched tags, unique attributes, quoted values, no '<' in values, -- legal names, character references in range, no "--" in comments, no "]]>" in text), the five predefined entities, -- character references and internal general entities from the DOCTYPE (with an expansion limit). Not supported: -- external entities / DTDs (references to them are errors), entity values containing markup (taken as text), -- validation. Never throws: errors are events. -local Text = require("@formats/codecs/Text") +local Text = require("@formats/codecs/text/Text") local Types = require("@formats/Types") local Parse = {} diff --git a/src/Formats/codecs/Xml/init.luau b/src/Formats/codecs/text/Xml/init.luau similarity index 97% rename from src/Formats/codecs/Xml/init.luau rename to src/Formats/codecs/text/Xml/init.luau index fcb574b..3ec2855 100644 --- a/src/Formats/codecs/Xml/init.luau +++ b/src/Formats/codecs/text/Xml/init.luau @@ -1,11 +1,11 @@ --!strict --- codecs/Xml: XML 1.0 parse (DOM and pull events) and serialize, the engine data/xml, SVG, DAE, 3MF, TMX, plist, ... +-- codecs/text/Xml: XML 1.0 parse (DOM and pull events) and serialize, the engine data/xml, SVG, DAE, 3MF, TMX, plist, ... -- use. New code. Supports: UTF-8 / UTF-16 / Latin-1 input, the predefined entities, character references, internal -- DOCTYPE entities (expansion limited), CDATA, comments, processing instructions, the XML declaration, namespaces -- (names stay qualified "prefix:local"; opts.namespaces adds each element's URI as node.ns; Xml.clark gives -- "{uri}local"), xml:space. Not supported: external entities / DTDs, validation, entity values containing markup. -- --- local Xml = require("@formats/codecs/Xml") +-- local Xml = require("@formats/codecs/text/Xml") -- local doc, err = Xml.decode(text) -- a "#document" node; doc.root is the root element -- for _, item in Xml.children(doc.root, "item") do print(item.attrs.id, Xml.text(item)) end -- for ev, a, b in Xml.events(text) do ... end -- "start" name attrs / "end" name / "text" s / ... (SAX-like) @@ -18,7 +18,7 @@ -- target); otherwise CDATA merges into the text and the others are dropped. Never throws. local Err = require("@formats/core/Err") local Types = require("@formats/Types") -local Parse = require("@formats/codecs/Xml/Parse") +local Parse = require("@formats/codecs/text/Xml/Parse") local Xml = {} @@ -57,7 +57,7 @@ local function errCode(msg: string, at: number, n: number): string return Err.CORRUPT end --- events(src, opts?) -> iterator: event, a, b, c (see codecs/Xml/Parse: "decl", "doctype", "start" name attrs ns, +-- events(src, opts?) -> iterator: event, a, b, c (see codecs/text/Xml/Parse: "decl", "doctype", "start" name attrs ns, -- "end" name, "text" s, "cdata" s, "comment" s, "pi" target data, and on bad input "error" Err as the last event) function Xml.events(src: string | buffer, opts: Parse.Options?): () -> (string?, any, any, any) local s, terr = text(src) diff --git a/src/Formats/codecs/H264/Bitstream.luau b/src/Formats/codecs/video/H264/Bitstream.luau similarity index 98% rename from src/Formats/codecs/H264/Bitstream.luau rename to src/Formats/codecs/video/H264/Bitstream.luau index acdeda9..9750fde 100644 --- a/src/Formats/codecs/H264/Bitstream.luau +++ b/src/Formats/codecs/video/H264/Bitstream.luau @@ -1,7 +1,7 @@ --!strict --!native --!optimize 2 --- codecs/H264/Bitstream: NAL unit framing and the RBSP bit reader of ITU-T H.264 (7.3 / 7.4 / 9.1): Annex B start +-- codecs/video/H264/Bitstream: NAL unit framing and the RBSP bit reader of ITU-T H.264 (7.3 / 7.4 / 9.1): Annex B start -- code splitting, AVCC length-prefixed samples, avcC (AVCDecoderConfigurationRecord, ISO/IEC 14496-15 5.3.3) -- parsing, emulation-prevention removal, and the u(n) / ue(v) / se(v) / te(v) readers. Written from the spec. -- Never throws: reads past the end of an RBSP return zero bits (the buffer carries 8 zero bytes of padding and every diff --git a/src/Formats/codecs/H264/Cabac.luau b/src/Formats/codecs/video/H264/Cabac.luau similarity index 98% rename from src/Formats/codecs/H264/Cabac.luau rename to src/Formats/codecs/video/H264/Cabac.luau index ceb74d5..910ffa8 100644 --- a/src/Formats/codecs/H264/Cabac.luau +++ b/src/Formats/codecs/video/H264/Cabac.luau @@ -1,15 +1,15 @@ --!strict --!native --!optimize 2 --- codecs/H264/Cabac: slice data and macroblock layer with CABAC entropy coding (ITU-T H.264 7.3.4, 7.3.5, 9.3): the +-- codecs/video/H264/Cabac: slice data and macroblock layer with CABAC entropy coding (ITU-T H.264 7.3.4, 7.3.5, 9.3): the -- arithmetic decoding engine (9.3.1.2 / 9.3.3.2), context initialisation (9.3.1.1), the binarizations and context -- index increments of every syntax element (9.3.2 / 9.3.3.1) and residual_block_cabac for 4x4, 8x8 and DC blocks. -- Coefficients are dequantised as they are placed. Written from the spec; tables from Tables. -- The engine keeps codIOffset with `nb` look-ahead bits (low = offset * 2^nb + next bits), so renormalisation is one -- multiply and bytes are fetched one at a time. Never throws: returns false, "message" on bad data. -local Bitstream = require("@formats/codecs/H264/Bitstream") -local Tables = require("@formats/codecs/H264/Tables") -local Mb = require("@formats/codecs/H264/Mb") +local Bitstream = require("@formats/codecs/video/H264/Bitstream") +local Tables = require("@formats/codecs/video/H264/Tables") +local Mb = require("@formats/codecs/video/H264/Mb") local readu8 = buffer.readu8 local min = math.min diff --git a/src/Formats/codecs/H264/Cavlc.luau b/src/Formats/codecs/video/H264/Cavlc.luau similarity index 98% rename from src/Formats/codecs/H264/Cavlc.luau rename to src/Formats/codecs/video/H264/Cavlc.luau index f14e42e..9a6ecdb 100644 --- a/src/Formats/codecs/H264/Cavlc.luau +++ b/src/Formats/codecs/video/H264/Cavlc.luau @@ -1,14 +1,14 @@ --!strict --!native --!optimize 2 --- codecs/H264/Cavlc: slice data and macroblock layer with CAVLC entropy coding (ITU-T H.264 7.3.4, 7.3.5, 9.2): +-- codecs/video/H264/Cavlc: slice data and macroblock layer with CAVLC entropy coding (ITU-T H.264 7.3.4, 7.3.5, 9.2): -- mb_skip_run, mb_type / sub_mb_type, intra modes, ref_idx (te), mvd, coded_block_pattern (me), mb_qp_delta and -- residual_block_cavlc (coeff_token, level_prefix / suffix, total_zeros, run_before) with the 8x8 interleaving. -- Coefficients are dequantised as they are placed. Written from the spec; VLC tables from Tables. -- Never throws: returns false, "message" on bad data. -local Bitstream = require("@formats/codecs/H264/Bitstream") -local Tables = require("@formats/codecs/H264/Tables") -local Mb = require("@formats/codecs/H264/Mb") +local Bitstream = require("@formats/codecs/video/H264/Bitstream") +local Tables = require("@formats/codecs/video/H264/Tables") +local Mb = require("@formats/codecs/video/H264/Mb") local u, u1, ue, se = Bitstream.u, Bitstream.u1, Bitstream.ue, Bitstream.se diff --git a/src/Formats/codecs/H264/Deblock.luau b/src/Formats/codecs/video/H264/Deblock.luau similarity index 97% rename from src/Formats/codecs/H264/Deblock.luau rename to src/Formats/codecs/video/H264/Deblock.luau index ffc1051..519c0a2 100644 --- a/src/Formats/codecs/H264/Deblock.luau +++ b/src/Formats/codecs/video/H264/Deblock.luau @@ -1,13 +1,13 @@ --!strict --!native --!optimize 2 --- codecs/H264/Deblock: the in-loop deblocking filter of ITU-T H.264 8.7 for frame macroblocks, 8-bit 4:2:0: +-- codecs/video/H264/Deblock: the in-loop deblocking filter of ITU-T H.264 8.7 for frame macroblocks, 8-bit 4:2:0: -- boundary strengths (8.7.2.1, from the per-4x4 intra / coefficient / reference / motion grids), alpha / beta / tC0 -- (tables 8-16 / 8-17), the bS < 4 and bS = 4 luma and chroma filters, disable_deblocking_filter_idc 0 / 1 / 2 and the -- slice alpha / beta offsets. Written from the spec. Runs over the whole picture in macroblock order once all its -- slices are decoded (the result equals filtering each macroblock as it is decoded). -- Never throws. -local Tables = require("@formats/codecs/H264/Tables") +local Tables = require("@formats/codecs/video/H264/Tables") local readu8, writeu8 = buffer.readu8, buffer.writeu8 local ALPHA, BETA, TC0 = Tables.ALPHA, Tables.BETA, Tables.TC0 diff --git a/src/Formats/codecs/H264/Decoder.luau b/src/Formats/codecs/video/H264/Decoder.luau similarity index 97% rename from src/Formats/codecs/H264/Decoder.luau rename to src/Formats/codecs/video/H264/Decoder.luau index 963c91d..fb099fb 100644 --- a/src/Formats/codecs/H264/Decoder.luau +++ b/src/Formats/codecs/video/H264/Decoder.luau @@ -1,19 +1,19 @@ --!strict --- codecs/H264/Decoder: the decoding process above the macroblock layer (ITU-T H.264 8.1, 8.2, C.4): NAL unit +-- codecs/video/H264/Decoder: the decoding process above the macroblock layer (ITU-T H.264 8.1, 8.2, C.4): NAL unit -- dispatch, picture boundaries (7.4.1.2.4), picture order count types 0 / 1 / 2 (8.2.1), frame_num gaps (8.2.5.2), -- reference picture lists with modification (8.2.4), sliding window and adaptive (MMCO 1-6) marking (8.2.5), output -- in POC order through a reorder buffer (num_reorder_frames, else the DPB size), concealment of lost macroblocks, -- deblocking and border extension. Written from the spec. -- Never throws: errors are returned (a corrupt slice is skipped and its macroblocks concealed). -local Bitstream = require("@formats/codecs/H264/Bitstream") -local Params = require("@formats/codecs/H264/Params") -local Slice = require("@formats/codecs/H264/Slice") -local Tables = require("@formats/codecs/H264/Tables") -local Mb = require("@formats/codecs/H264/Mb") -local Cavlc = require("@formats/codecs/H264/Cavlc") -local Cabac = require("@formats/codecs/H264/Cabac") -local Deblock = require("@formats/codecs/H264/Deblock") -local Inter = require("@formats/codecs/H264/Inter") +local Bitstream = require("@formats/codecs/video/H264/Bitstream") +local Params = require("@formats/codecs/video/H264/Params") +local Slice = require("@formats/codecs/video/H264/Slice") +local Tables = require("@formats/codecs/video/H264/Tables") +local Mb = require("@formats/codecs/video/H264/Mb") +local Cavlc = require("@formats/codecs/video/H264/Cavlc") +local Cabac = require("@formats/codecs/video/H264/Cabac") +local Deblock = require("@formats/codecs/video/H264/Deblock") +local Inter = require("@formats/codecs/video/H264/Inter") local Types = require("@formats/Types") local PAD, PADC = Inter.PAD, Inter.PADC diff --git a/src/Formats/codecs/H264/Inter.luau b/src/Formats/codecs/video/H264/Inter.luau similarity index 98% rename from src/Formats/codecs/H264/Inter.luau rename to src/Formats/codecs/video/H264/Inter.luau index 7dbe10b..6dc0a8e 100644 --- a/src/Formats/codecs/H264/Inter.luau +++ b/src/Formats/codecs/video/H264/Inter.luau @@ -1,7 +1,7 @@ --!strict --!native --!optimize 2 --- codecs/H264/Inter: inter prediction sample interpolation and weighting (ITU-T H.264 8.4.2.2 / 8.4.2.3): the 6-tap +-- codecs/video/H264/Inter: inter prediction sample interpolation and weighting (ITU-T H.264 8.4.2.2 / 8.4.2.3): the 6-tap -- quarter-sample luma filter, eighth-sample bilinear chroma, default / explicit / implicit weighted sample -- prediction, and the picture border extension that makes out-of-picture reference reads equal to the clamped -- sample positions of 8.4.2.2.1. Written from the spec. diff --git a/src/Formats/codecs/H264/Intra.luau b/src/Formats/codecs/video/H264/Intra.luau similarity index 98% rename from src/Formats/codecs/H264/Intra.luau rename to src/Formats/codecs/video/H264/Intra.luau index 4543050..f63dead 100644 --- a/src/Formats/codecs/H264/Intra.luau +++ b/src/Formats/codecs/video/H264/Intra.luau @@ -1,7 +1,7 @@ --!strict --!native --!optimize 2 --- codecs/H264/Intra: intra prediction (ITU-T H.264 8.3): Intra_4x4 and Intra_8x8 (nine directional modes, with the +-- codecs/video/H264/Intra: intra prediction (ITU-T H.264 8.3): Intra_4x4 and Intra_8x8 (nine directional modes, with the -- 8x8 reference sample filter of 8.3.2.2.1), Intra_16x16 and chroma (DC / horizontal / vertical / plane), 8-bit. -- Written from the spec. Predictions are written straight into the picture plane (row stride `s`, block origin `o`). -- Never throws: every sample read is inside the padded plane (callers pass availability for the edges). diff --git a/src/Formats/codecs/H264/Mb.luau b/src/Formats/codecs/video/H264/Mb.luau similarity index 98% rename from src/Formats/codecs/H264/Mb.luau rename to src/Formats/codecs/video/H264/Mb.luau index 428e088..ac6d983 100644 --- a/src/Formats/codecs/H264/Mb.luau +++ b/src/Formats/codecs/video/H264/Mb.luau @@ -1,15 +1,15 @@ --!strict --!native --!optimize 2 --- codecs/H264/Mb: macroblock reconstruction shared by the CAVLC and CABAC parsers (ITU-T H.264 8.3 - 8.5): +-- codecs/video/H264/Mb: macroblock reconstruction shared by the CAVLC and CABAC parsers (ITU-T H.264 8.3 - 8.5): -- neighbour availability (6.4.11), Intra4x4 / Intra8x8 mode prediction (8.3.1.1 / 8.3.2.1), motion vector prediction -- (8.4.1.3), P_Skip (8.4.1.1), B direct spatial and temporal (8.4.1.2), motion compensation with weighting, intra -- prediction and the residual. Written from the spec; the per-4x4 motion / mode grids follow the usual decoder layout -- (picture-wide arrays, one entry per 4x4 luma block, 1-based). -- Never throws: every index is in range by construction; reference indices past the list use the first entry. -local Intra = require("@formats/codecs/H264/Intra") -local Transform = require("@formats/codecs/H264/Transform") -local Inter = require("@formats/codecs/H264/Inter") +local Intra = require("@formats/codecs/video/H264/Intra") +local Transform = require("@formats/codecs/video/H264/Transform") +local Inter = require("@formats/codecs/video/H264/Inter") local Mb = {} diff --git a/src/Formats/codecs/H264/Params.luau b/src/Formats/codecs/video/H264/Params.luau similarity index 98% rename from src/Formats/codecs/H264/Params.luau rename to src/Formats/codecs/video/H264/Params.luau index 04c2682..b97d9c4 100644 --- a/src/Formats/codecs/H264/Params.luau +++ b/src/Formats/codecs/video/H264/Params.luau @@ -1,11 +1,11 @@ --!strict --!native --- codecs/H264/Params: sequence and picture parameter sets (ITU-T H.264 7.3.2.1 / 7.3.2.2 / E.1), scaling lists with +-- codecs/video/H264/Params: sequence and picture parameter sets (ITU-T H.264 7.3.2.1 / 7.3.2.2 / E.1), scaling lists with -- the fall-back rules A and B (7.4.2.1.1 / table 7-2), and the dequantisation tables built from them (8.5.9: the -- LevelScale4x4 / LevelScale8x8 functions, premultiplied by 2^(qP / 6)). Written from the spec. -- Never throws: parse functions return nil, "message". -local Bitstream = require("@formats/codecs/H264/Bitstream") -local Tables = require("@formats/codecs/H264/Tables") +local Bitstream = require("@formats/codecs/video/H264/Bitstream") +local Tables = require("@formats/codecs/video/H264/Tables") local u, u1, ue, se = Bitstream.u, Bitstream.u1, Bitstream.ue, Bitstream.se diff --git a/src/Formats/codecs/H264/Slice.luau b/src/Formats/codecs/video/H264/Slice.luau similarity index 97% rename from src/Formats/codecs/H264/Slice.luau rename to src/Formats/codecs/video/H264/Slice.luau index 8aa9acd..a64cb93 100644 --- a/src/Formats/codecs/H264/Slice.luau +++ b/src/Formats/codecs/video/H264/Slice.luau @@ -1,10 +1,10 @@ --!strict --!native --- codecs/H264/Slice: the slice header (ITU-T H.264 7.3.3): ref_pic_list_modification, pred_weight_table and +-- codecs/video/H264/Slice: the slice header (ITU-T H.264 7.3.3): ref_pic_list_modification, pred_weight_table and -- dec_ref_pic_marking. Written from the spec. Frame coding only: field pictures (field_pic_flag = 1), MBAFF, -- SP / SI slices, separate colour planes and redundant pictures return "unsupported: ...". -- Never throws: header() returns nil, "message". -local Bitstream = require("@formats/codecs/H264/Bitstream") +local Bitstream = require("@formats/codecs/video/H264/Bitstream") local u, u1, ue, se = Bitstream.u, Bitstream.u1, Bitstream.ue, Bitstream.se diff --git a/src/Formats/codecs/H264/Tables.luau b/src/Formats/codecs/video/H264/Tables.luau similarity index 99% rename from src/Formats/codecs/H264/Tables.luau rename to src/Formats/codecs/video/H264/Tables.luau index fdcaec1..d2b1679 100644 --- a/src/Formats/codecs/H264/Tables.luau +++ b/src/Formats/codecs/video/H264/Tables.luau @@ -1,6 +1,6 @@ --!strict --!native --- codecs/H264/Tables: the constant tables of ITU-T H.264 (CAVLC code tables 9-5, 9-7, 9-8, 9-9, 9-10; CABAC context +-- codecs/video/H264/Tables: the constant tables of ITU-T H.264 (CAVLC code tables 9-5, 9-7, 9-8, 9-9, 9-10; CABAC context -- initialisation tables 9-12..9-24, rangeTabLPS 9-44 and the state transitions 9-45; the chroma QP table 8-15; the -- me(v) coded_block_pattern mapping 9-4; default scaling lists 7-3 / 7-4; zig-zag scans 8-12 / 8-13; table 9-43; the -- deblocking alpha / beta / tC0 tables 8-16 / 8-17). Values extracted from openh264 2.x (BSD-2-Clause, diff --git a/src/Formats/codecs/H264/Transform.luau b/src/Formats/codecs/video/H264/Transform.luau similarity index 97% rename from src/Formats/codecs/H264/Transform.luau rename to src/Formats/codecs/video/H264/Transform.luau index 6fd463d..b631624 100644 --- a/src/Formats/codecs/H264/Transform.luau +++ b/src/Formats/codecs/video/H264/Transform.luau @@ -1,7 +1,7 @@ --!strict --!native --!optimize 2 --- codecs/H264/Transform: the inverse transforms of ITU-T H.264 8.5: the 4x4 and 8x8 integer IDCTs with the residual +-- codecs/video/H264/Transform: the inverse transforms of ITU-T H.264 8.5: the 4x4 and 8x8 integer IDCTs with the residual -- added to the prediction in the plane (8.5.12.2 / 8.5.13.2 / 8.5.14), the 4x4 luma DC and 2x2 chroma DC Hadamard -- transforms with their scaling (8.5.10 / 8.5.11.2). Written from the spec. Coefficients are dequantised already -- (Params.dequant), raster order, in a 1-based table at `base + 1 ...`; the functions zero what they read. diff --git a/src/Formats/codecs/H264/init.luau b/src/Formats/codecs/video/H264/init.luau similarity index 97% rename from src/Formats/codecs/H264/init.luau rename to src/Formats/codecs/video/H264/init.luau index 1dcfd90..501652f 100644 --- a/src/Formats/codecs/H264/init.luau +++ b/src/Formats/codecs/video/H264/init.luau @@ -1,5 +1,5 @@ --!strict --- codecs/H264: an H.264 / AVC (ITU-T H.264 | ISO/IEC 14496-10) video decoder in pure Luau. A codec (layer 1): the +-- codecs/video/H264: an H.264 / AVC (ITU-T H.264 | ISO/IEC 14496-10) video decoder in pure Luau. A codec (layer 1): the -- video/h264 format (raw Annex B streams) and the MP4 / MKV / AVI / TS video tracks use it. Clean-room, written from the -- spec; constant tables taken from openh264 (BSD-2-Clause, licenses/openh264-LICENSE.txt). Bit-exact with the -- reference decoder (checked against ffmpeg per frame). @@ -14,7 +14,7 @@ -- lossless (transform bypass), FMO / ASO slice groups, SP / SI slices, data partitioning, SVC / MVC enhancement layers -- (their NAL units are ignored). -- --- local H264 = require("@formats/codecs/H264") +-- local H264 = require("@formats/codecs/video/H264") -- local dec = H264.newDecoder() -- or { avcC = buffer } for MP4 samples (length-prefixed) -- for _, au in accessUnits do -- local frames, err = dec:decode(au, pts) -- frames: { { image (yuv420p Types.Image), pts, poc, keyframe } } @@ -29,9 +29,9 @@ -- concealed (dec.errors counts them, dec.lastError says why). local Err = require("@formats/core/Err") local Types = require("@formats/Types") -local Bitstream = require("@formats/codecs/H264/Bitstream") -local Decoder = require("@formats/codecs/H264/Decoder") -local Params = require("@formats/codecs/H264/Params") +local Bitstream = require("@formats/codecs/video/H264/Bitstream") +local Decoder = require("@formats/codecs/video/H264/Decoder") +local Params = require("@formats/codecs/video/H264/Params") local H264 = {} @@ -201,7 +201,7 @@ function H264.parseAvcC(data: any): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ video layer --- newVideoDecoder(track, opts?) -> a Types.VideoCodecDecoder (the codecs/Video registry entry for "h264"): +-- newVideoDecoder(track, opts?) -> a Types.VideoCodecDecoder (the codecs/video/Video registry entry for "h264"): -- track.config = avcC (MP4 / Matroska; packets length-prefixed) or nil (Annex B packets: MPEG-TS, AVI, raw .h264). -- Pictures come out in display order with the packet timestamps sorted (display order); a track with -- `ptsInOutputOrder` (raw Annex B, no timestamps) numbers them in output order instead. diff --git a/src/Formats/codecs/Mpeg1/Decoder.luau b/src/Formats/codecs/video/Mpeg1/Decoder.luau similarity index 98% rename from src/Formats/codecs/Mpeg1/Decoder.luau rename to src/Formats/codecs/video/Mpeg1/Decoder.luau index c9a054c..5fcdb1f 100644 --- a/src/Formats/codecs/Mpeg1/Decoder.luau +++ b/src/Formats/codecs/video/Mpeg1/Decoder.luau @@ -1,6 +1,6 @@ --!strict --!native --- codecs/Mpeg1/Decoder: the MPEG-1 video decoding core (ISO/IEC 11172-2; native, never throws): I, P and B pictures, +-- codecs/video/Mpeg1/Decoder: the MPEG-1 video decoding core (ISO/IEC 11172-2; native, never throws): I, P and B pictures, -- half-pel motion compensation, custom quantiser matrices, sequence headers anywhere in the stream. Absorbed from -- mpeg1-luau e2e2898 (same author; src/Mpeg1/Decoder.luau, unchanged but for this header and the requires), a port -- of jsmpeg's decoder (src/mpeg1.js by Dominic Szablewski, MIT, licenses/jsmpeg-MIT.txt) with these changes for @@ -13,7 +13,7 @@ -- * motion compensation four bytes at a time (SWAR rounding averages); -- * BT.601 limited-range YCbCr -> RGBA8 (jsmpeg's canvas path treats Y as full range). -- --- The IDCT is not codecs/Dct's: it computes the same islow transform (its put mode is bit-identical to +-- The IDCT is not codecs/image/Dct's: it computes the same islow transform (its put mode is bit-identical to -- Dct.idctBlock with a unit quantiser and no level shift, checked on 20000 random blocks), but MPEG-1 adds the -- residual of P / B blocks to the prediction before clamping, dequantises into i32 coefficients itself (MPEG -- rounding and oddification, not JPEG's q multiply) and writes u8 samples four per writeu32, where Dct clamps to @@ -23,8 +23,8 @@ -- Native code must never throw (an error unwinding through native code crashes Roblox Studio): every read -- position is checked against the data end (plus a zero pad that bounds the overrun of one macroblock), motion -- vectors are clamped to the reference picture, and bad data ends the slice instead of raising. -local V = require("@formats/codecs/Mpeg1/Vlc") -local T = require("@formats/codecs/Mpeg1/Tables") +local V = require("@formats/codecs/video/Mpeg1/Vlc") +local T = require("@formats/codecs/video/Mpeg1/Tables") local readu8 = buffer.readu8 local writeu8 = buffer.writeu8 diff --git a/src/Formats/codecs/Mpeg1/Tables.luau b/src/Formats/codecs/video/Mpeg1/Tables.luau similarity index 98% rename from src/Formats/codecs/Mpeg1/Tables.luau rename to src/Formats/codecs/video/Mpeg1/Tables.luau index 3e330ef..1cad194 100644 --- a/src/Formats/codecs/Mpeg1/Tables.luau +++ b/src/Formats/codecs/video/Mpeg1/Tables.luau @@ -1,5 +1,5 @@ --!strict --- codecs/Mpeg1/Tables: the constant tables of jsmpeg's MPEG-1 video decoder (https://github.com/phoboslab/jsmpeg, +-- codecs/video/Mpeg1/Tables: the constant tables of jsmpeg's MPEG-1 video decoder (https://github.com/phoboslab/jsmpeg, -- Dominic Szablewski, MIT, licenses/jsmpeg-MIT.txt), generated by mpeg1-luau's tools/gen_tables.py (absorbed from -- mpeg1-luau e2e2898). Lists are 0-based like the JS arrays. local T = {} diff --git a/src/Formats/codecs/Mpeg1/Vlc.luau b/src/Formats/codecs/video/Mpeg1/Vlc.luau similarity index 94% rename from src/Formats/codecs/Mpeg1/Vlc.luau rename to src/Formats/codecs/video/Mpeg1/Vlc.luau index 8d34e39..b4799aa 100644 --- a/src/Formats/codecs/Mpeg1/Vlc.luau +++ b/src/Formats/codecs/video/Mpeg1/Vlc.luau @@ -1,5 +1,5 @@ --!strict --- codecs/Mpeg1/Vlc: lookup tables for the MPEG-1 variable-length codes, built at load time from jsmpeg's binary trees (Tables.luau). +-- codecs/video/Mpeg1/Vlc: lookup tables for the MPEG-1 variable-length codes, built at load time from jsmpeg's binary trees (Tables.luau). -- -- A flat table is indexed by the next K bits of the stream (K = the longest code) and holds -- len * 65536 + (value + 32768) per entry; len = 0 marks an invalid code. The DCT coefficient tables are two-level @@ -8,7 +8,7 @@ -- first one of a block, where "10" is end_of_block and "11" is run 0 / level 1 (jsmpeg reads this as "1" and one -- more bit); DCT_FIRST keeps "1" as run 0 / level 1. Absorbed from mpeg1-luau e2e2898 (same author), unchanged but -- for this header and the require. -local T = require("@formats/codecs/Mpeg1/Tables") +local T = require("@formats/codecs/video/Mpeg1/Tables") local V = {} diff --git a/src/Formats/codecs/Mpeg1/init.luau b/src/Formats/codecs/video/Mpeg1/init.luau similarity index 97% rename from src/Formats/codecs/Mpeg1/init.luau rename to src/Formats/codecs/video/Mpeg1/init.luau index 2ff3118..25c7d10 100644 --- a/src/Formats/codecs/Mpeg1/init.luau +++ b/src/Formats/codecs/video/Mpeg1/init.luau @@ -1,5 +1,5 @@ --!strict --- codecs/Mpeg1: an MPEG-1 video decoder (ISO/IEC 11172-2) for the MPEG-TS / MPEG-PS video formats. Absorbed from +-- codecs/video/Mpeg1: an MPEG-1 video decoder (ISO/IEC 11172-2) for the MPEG-TS / MPEG-PS video formats. Absorbed from -- mpeg1-luau e2e2898 (same author; README, docs/api.md and docs/performance.md there), a port of jsmpeg's decoder -- (https://github.com/phoboslab/jsmpeg, Dominic Szablewski, MIT: licenses/jsmpeg-MIT.txt) extended with B-pictures, -- an islow integer IDCT, table-driven VLC decoding and BT.601 RGBA8 output; added here: frameImage. @@ -17,7 +17,7 @@ -- -- Nothing here throws: bad arguments return nil / false, bad data is skipped (see Decoder.luau). local Types = require("@formats/Types") -local D = require("@formats/codecs/Mpeg1/Decoder") +local D = require("@formats/codecs/video/Mpeg1/Decoder") local Mpeg1 = {} diff --git a/src/Formats/codecs/Video/Source.luau b/src/Formats/codecs/video/Video/Source.luau similarity index 97% rename from src/Formats/codecs/Video/Source.luau rename to src/Formats/codecs/video/Video/Source.luau index 2779bf5..532312b 100644 --- a/src/Formats/codecs/Video/Source.luau +++ b/src/Formats/codecs/video/Video/Source.luau @@ -1,5 +1,5 @@ --!strict --- codecs/Video/Source: what a video writer (Matroska / WebM, AVI, Y4M, MP4) gets to write, from whatever it was given: +-- codecs/video/Video/Source: what a video writer (Matroska / WebM, AVI, Y4M, MP4) gets to write, from whatever it was given: -- a VideoDecoder (F.load / F.video.open of any video or animated image) or a Demuxer. Each output stream is either -- copied (the source track's packets, when the target container takes that codec: remuxing, e.g. VP8 into WebM, -- since VP8 is decode-only) or produced (decoded frames encoded with a registered encoder such as MJPEG, raw @@ -13,7 +13,7 @@ -- -- track, packets = { { pts, duration (seconds), keyframe, data } } } local Err = require("@formats/core/Err") local Types = require("@formats/Types") -local Yuv = require("@formats/codecs/Yuv") +local Yuv = require("@formats/codecs/image/Yuv") local Source = {} @@ -77,7 +77,7 @@ end local function encodeFrames(v: any, codec: string, opts: any): (Stream?, Err.Err?) local encode: ((img: Types.Image, opts: any) -> (buffer?, Err.Err?))? = nil if codec ~= "rawvideo" then - local Video = require("@formats/codecs/Video") + local Video = require("@formats/codecs/video/Video") local e = Video.entry(codec) encode = e and e.encode if not encode then diff --git a/src/Formats/codecs/Video/init.luau b/src/Formats/codecs/video/Video/init.luau similarity index 97% rename from src/Formats/codecs/Video/init.luau rename to src/Formats/codecs/video/Video/init.luau index 1c99bb2..0960b9b 100644 --- a/src/Formats/codecs/Video/init.luau +++ b/src/Formats/codecs/video/Video/init.luau @@ -1,5 +1,5 @@ --!strict --- codecs/Video: the video codec registry and the generic VideoDecoder. New in formats-luau. +-- codecs/video/Video: the video codec registry and the generic VideoDecoder. New in formats-luau. -- -- Registry: our codec ids ("vp8", "mjpeg", "mpeg1", "h264", "rawvideo", ...) with the containers' names for them -- (AVI / MOV FourCCs, Matroska CodecIDs, MPEG stream types) and, for the codecs we can decode, a constructor of a @@ -7,7 +7,7 @@ -- Video.fromMatroska so a track's codec is known even without a decoder (remuxing still works). Another codec plugs -- in with one line in BUILTIN (static: Roblox has no dynamic require) or at run time with Video.register(entry). -- --- local Video = require("@formats/codecs/Video") +-- local Video = require("@formats/codecs/video/Video") -- Video.fromFourcc("MJPG") --> "mjpeg" Video.fromMatroska("V_VP8") --> "vp8" -- local dec = Video.decoder(track, opts) -- a VideoCodecDecoder | nil, Err (UNSUPPORTED: no decoder) -- local v = Video.open(demuxer, opts) -- a Types.VideoDecoder over a Types.Demuxer (formats' open()) @@ -16,7 +16,7 @@ -- Never throws: bad data / missing codecs come back as nil, Err. local Err = require("@formats/core/Err") local Types = require("@formats/Types") -local Yuv = require("@formats/codecs/Yuv") +local Yuv = require("@formats/codecs/image/Yuv") local Video = {} @@ -190,7 +190,7 @@ local function rawDecoder(track: Types.Track, _opts: any?): (Types.VideoCodecDec end local function vp8Decoder(_track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) - local Vp8 = require("@formats/codecs/Vp8") + local Vp8 = require("@formats/codecs/image/Vp8") local dec = Vp8.newDecoder() local o = { maxPixels = opts and opts.maxPixels } return Video.simpleDecoder(function(data: buffer): (Types.Image?, Err.Err?) @@ -216,7 +216,7 @@ end -- Motion JPEG: every packet one JPEG (or two fields), yuv420p straight from the planes (full range) when the layout -- allows, else rgba8 local function mjpegDecoder(_track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) - local Jpeg = require("@formats/codecs/Jpeg") + local Jpeg = require("@formats/codecs/image/Jpeg") local o: Jpeg.DecodeOptions = { yuv = true, maxPixels = opts and opts.maxPixels } return Video.simpleDecoder(function(data: buffer): (Types.Image?, Err.Err?) local img, err = Jpeg.decode(data, 0, buffer.len(data), o) @@ -229,7 +229,7 @@ end -- the MJPEG encoder (writers): JPEG is full-range, so limited-range yuv420p frames are remapped first local function mjpegEncode(img: Types.Image, opts: any?): (buffer?, Err.Err?) - local Jpeg = require("@formats/codecs/Jpeg") + local Jpeg = require("@formats/codecs/image/Jpeg") local src = img if img.format == "yuv420p" then local range = Yuv.info(img) @@ -242,7 +242,7 @@ end -- MPEG-1 video: pictures in decode order, reordered for display (the packet's pts travels with its picture) local function mpeg1Decoder(_track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) - local Mpeg1 = require("@formats/codecs/Mpeg1") + local Mpeg1 = require("@formats/codecs/video/Mpeg1") local dec = Mpeg1.new({ reorder = true, rgba = false, maxPixels = opts and opts.maxPixels }) local queue: { any } = {} local function push(f: any) @@ -287,10 +287,10 @@ local function mpeg1Decoder(_track: Types.Track, opts: any?): (Types.VideoCodecD return self :: any, nil end --- H.264 / AVC (codecs/H264): avcC from track.config (MP4 / Matroska) or Annex B packets (MPEG-TS, AVI, raw .h264); +-- H.264 / AVC (codecs/video/H264): avcC from track.config (MP4 / Matroska) or Annex B packets (MPEG-TS, AVI, raw .h264); -- pictures in display order with the pts of their packet local function h264Decoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) - local H264 = require("@formats/codecs/H264") + local H264 = require("@formats/codecs/video/H264") return H264.newVideoDecoder(track, opts) end diff --git a/src/Formats/containers/Chunks.luau b/src/Formats/containers/Chunks.luau new file mode 100644 index 0000000..dda7836 --- /dev/null +++ b/src/Formats/containers/Chunks.luau @@ -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 formats-luau (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 diff --git a/src/Formats/containers/Riff/init.luau b/src/Formats/containers/Riff/init.luau index 63fd4d1..464e88e 100644 --- a/src/Formats/containers/Riff/init.luau +++ b/src/Formats/containers/Riff/init.luau @@ -1,7 +1,7 @@ --!strict -- containers/Riff: the RIFF chunk container (RIFF, RIFX big-endian, RF64 / BW64 with the ds64 chunk), read leniently -- and written. Shared by audio/wav and the other RIFF forms (AVI, WebP, ANI, ...). The chunk walker comes from --- wav-luau fd9a909 (same author, no third-party code); the writer is new. +-- 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 @@ -20,6 +20,7 @@ -- 0xFFFFFFFF come from the ds64 chunk (and its table). Never throws: bad data returns nil, Err. local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") +local Chunks = require("@formats/containers/Chunks") local readu8, readu16, readu32, readstring = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readstring @@ -27,6 +28,7 @@ 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 @@ -51,19 +53,6 @@ export type ReadOptions = { } -- ------------------------------------------------------------------------------------------------ read -local function printable4(b: buffer, p: number, limit: number): boolean - if p + 4 > limit then - return false - end - for i = 0, 3 do - local c = readu8(b, p + i) - if c < 32 or c > 126 then - return false - end - end - return true -end - local function u32(b: buffer, o: number, be: boolean): number local v = readu32(b, o) return if be then bit32.byteswap(v) else v @@ -79,43 +68,25 @@ function Riff.sniff(r: any): string? return if #form == 4 then form else nil end --- walk the chunks of [p, limit) into list; returns the list -local function walk(b: buffer, p: number, limit: number, be: boolean, opts: ReadOptions?, ds64: any, list: { Chunk }): { Chunk } - local openEnded = opts and opts.openEnded - local maxChunks = opts and opts.maxChunks or 100000 - while p + 8 <= limit and #list < maxChunks do - local id = readstring(b, p, 4) - local declared = u32(b, p + 4, be) - local size = declared - local body = p + 8 - local avail = limit - body - if declared == 0xFFFFFFFF and ds64 then - if id == "data" then - size = ds64.dataSize - elseif ds64.table[id] then - size = ds64.table[id] +-- 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 - end - local c: Chunk = { id = id, offset = body, size = size, declared = declared, avail = math.min(size, avail), truncated = false, streamed = false } - table.insert(list, c) - if openEnded and openEnded[id] and (size == 0 or size == 0xFFFFFFFF or size > avail) then - c.streamed = size == 0 or size == 0xFFFFFFFF - c.truncated = not c.streamed - c.size, c.avail = avail, avail - break - end - if size > avail then - c.truncated = true - break - end - local nextPos = body + size + size % 2 - -- an odd-sized chunk written without its pad byte: the next id starts right after the body - if size % 2 == 1 and not printable4(b, nextPos, limit) and printable4(b, body + size, limit) then - nextPos = body + size - end - p = nextPos - end - return list + 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. @@ -172,7 +143,7 @@ function Riff.read(src: any, opts: ReadOptions?): (File?, Err.Err?) end end end - walk(b, base + 12, limit, be, opts, f.ds64, f.chunks) + f.chunks = walk(b, base + 12, limit, be, opts, f.ds64) return f, nil end @@ -199,7 +170,7 @@ 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, {}) + 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 diff --git a/src/Formats/containers/Zip/init.luau b/src/Formats/containers/Zip/init.luau index df38c88..0fcf385 100644 --- a/src/Formats/containers/Zip/init.luau +++ b/src/Formats/containers/Zip/init.luau @@ -5,7 +5,7 @@ -- archive comment), the central directory, ZIP64 (records, locator, extra fields), a prefix shift (self-extractor -- stubs), stored and deflated entries with a CRC-32 check, data descriptors, a wrong local header fallback, -- case-insensitive / basename lookup that skips __MACOSX. The DEFLATE codec is now required directly --- (codecs/Deflate) instead of injected. The writer is new: stored / deflated entries (codecs/Deflate compress, stored +-- (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 @@ -21,7 +21,7 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Crc32 = require("@formats/core/Crc32") -local Deflate = require("@formats/codecs/Deflate") +local Deflate = require("@formats/codecs/compress/Deflate") local Zip = {} Zip.version = "1.1.0" diff --git a/src/Formats/core/Bits.luau b/src/Formats/core/Bits.luau index ca79f13..f844466 100644 --- a/src/Formats/core/Bits.luau +++ b/src/Formats/core/Bits.luau @@ -5,7 +5,7 @@ -- -- Plain arithmetic on an accumulator of at most 31 bits (no bit32 calls), exact on doubles, cheap on both runtimes. -- These are the generic, convenient readers: a codec's innermost loop usually keeps its own local bit buffer (see --- codecs/Deflate/Inflate) and uses these for headers. +-- codecs/compress/Deflate/Inflate) and uses these for headers. -- -- Never throws: reading past the end returns zero bits and sets the sticky `err` (Err.TRUNCATED). -- diff --git a/src/Formats/core/Err.luau b/src/Formats/core/Err.luau index 784a545..f5d8337 100644 --- a/src/Formats/core/Err.luau +++ b/src/Formats/core/Err.luau @@ -56,7 +56,7 @@ function Err.from(message: any, offset: number?, kind: string?): Err return message end local msg = if message == nil then "failed" else tostring(message) - local code = kind and KIND[kind] + local code: string? = kind and KIND[kind] if not code then local head, rest = string.match(msg, "^(%a+):%s*(.*)$") if head and KIND[head] then @@ -71,7 +71,7 @@ function Err.from(message: any, offset: number?, kind: string?): Err code = Err.CORRUPT end end - return Err.new(code, msg, offset) + return Err.new(code :: string, msg, offset) end -- is(v) -> true when v is an Err diff --git a/src/Formats/data/csv/init.luau b/src/Formats/data/csv/init.luau index 8bab313..8a9f4a3 100644 --- a/src/Formats/data/csv/init.luau +++ b/src/Formats/data/csv/init.luau @@ -11,7 +11,7 @@ local Err = require("@formats/core/Err") local Sniff = require("@formats/core/Sniff") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") -local Json = require("@formats/codecs/Json") +local Json = require("@formats/codecs/text/Json") -- ------------------------------------------------------------------------------------------------ contract local Csv = { @@ -19,7 +19,7 @@ local Csv = { category = "data", extensions = { "csv", "tsv" }, mime = { "text/csv", "text/tab-separated-values" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Json", "core/Sniff" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Json", "core/Sniff" }, caps = { decode = true, encode = true, header = true }, } diff --git a/src/Formats/data/ini/init.luau b/src/Formats/data/ini/init.luau index 14a94c8..bb6f788 100644 --- a/src/Formats/data/ini/init.luau +++ b/src/Formats/data/ini/init.luau @@ -12,7 +12,7 @@ local Err = require("@formats/core/Err") local Sniff = require("@formats/core/Sniff") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") -local Json = require("@formats/codecs/Json") +local Json = require("@formats/codecs/text/Json") -- ------------------------------------------------------------------------------------------------ contract local Ini = { @@ -20,7 +20,7 @@ local Ini = { category = "data", extensions = { "ini", "cfg", "conf", "inf", "desktop" }, mime = { "text/plain" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Json", "core/Sniff" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Json", "core/Sniff" }, caps = { decode = true, encode = true, ordered = true }, } diff --git a/src/Formats/data/json/init.luau b/src/Formats/data/json/init.luau index 78a4df7..e66a95a 100644 --- a/src/Formats/data/json/init.luau +++ b/src/Formats/data/json/init.luau @@ -1,13 +1,13 @@ --!strict --- data/json: JSON (RFC 8259) files, a thin wrapper over codecs/Json (which see for the value mapping and options). +-- data/json: JSON (RFC 8259) files, a thin wrapper over codecs/text/Json (which see for the value mapping and options). -- Supports: decode to plain Luau values (Types.null, ordered keys and bigInts as strings by option), encode compact or --- pretty. JSON Lines through codecs/Json.lines. Not supported: JSON5 / comments / trailing commas. +-- pretty. JSON Lines through codecs/text/Json.lines. Not supported: JSON5 / comments / trailing commas. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") local Sniff = require("@formats/core/Sniff") local Bytes = require("@formats/core/Bytes") -local Json = require("@formats/codecs/Json") +local Json = require("@formats/codecs/text/Json") -- ------------------------------------------------------------------------------------------------ contract local JsonFormat = { @@ -15,7 +15,7 @@ local JsonFormat = { category = "data", extensions = { "json", "jsonl", "ndjson", "geojson" }, mime = { "application/json", "application/x-ndjson" }, - deps = { "core/Err", "core/Bytes", "codecs/Json", "core/Sniff" }, + deps = { "core/Err", "core/Bytes", "codecs/text/Json", "core/Sniff" }, caps = { decode = true, encode = true, ordered = true, streaming = true }, } diff --git a/src/Formats/data/plist/init.luau b/src/Formats/data/plist/init.luau index 6f46277..8184dd9 100644 --- a/src/Formats/data/plist/init.luau +++ b/src/Formats/data/plist/init.luau @@ -1,5 +1,5 @@ --!strict --- data/plist: Apple property lists. New code. Supports: XML plists (read and write, through codecs/Xml; the write is +-- data/plist: Apple property lists. New code. Supports: XML plists (read and write, through codecs/text/Xml; the write is -- byte-identical to Python's plistlib for the same key order) and binary plists ("bplist00", read). Values: dict -> -- Types.object (key order kept), array, string, integer / real -> number, true / false, date -> Types.Date, data -> -- buffer, UID (binary) -> Plist.uid(n). Not supported: binary write, the old OpenStep text format, integers past @@ -9,8 +9,8 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") -local Xml = require("@formats/codecs/Xml") -local Json = require("@formats/codecs/Json") +local Xml = require("@formats/codecs/text/Xml") +local Json = require("@formats/codecs/text/Json") local Base64 = require("@formats/core/Base64") local Binary = require("@formats/data/plist/Binary") @@ -20,7 +20,7 @@ local Plist = { category = "data", extensions = { "plist" }, mime = { "application/x-plist", "application/x-bplist" }, - deps = { "core/Err", "core/Bytes", "Types", "core/Base64", "codecs/Xml", "codecs/Json" }, + deps = { "core/Err", "core/Bytes", "Types", "core/Base64", "codecs/text/Xml", "codecs/text/Json" }, caps = { decode = true, encode = true, binary = "read", ordered = true }, } diff --git a/src/Formats/data/toml/Decode.luau b/src/Formats/data/toml/Decode.luau index 8974dd2..0320afb 100644 --- a/src/Formats/data/toml/Decode.luau +++ b/src/Formats/data/toml/Decode.luau @@ -3,7 +3,7 @@ -- their key order; arrays are arrays; datetimes are Types.Date values. Checks the 1.0 validity rules: UTF-8, control -- characters, table / key redefinition (explicit, implicit, dotted, inline and array-of-tables), number grammar and -- 64-bit range, escapes, datetimes. Never throws: failures return nil, message, offset (0-based). -local Text = require("@formats/codecs/Text") +local Text = require("@formats/codecs/text/Text") local Types = require("@formats/Types") local Decode = {} diff --git a/src/Formats/data/toml/Encode.luau b/src/Formats/data/toml/Encode.luau index 664e467..6e654d7 100644 --- a/src/Formats/data/toml/Encode.luau +++ b/src/Formats/data/toml/Encode.luau @@ -5,7 +5,7 @@ -- values as datetimes. Never throws: bad values (null, buffers, functions, cycles, non-string keys) return nil, -- message. local Types = require("@formats/Types") -local Json = require("@formats/codecs/Json") +local Json = require("@formats/codecs/text/Json") local Encode = {} diff --git a/src/Formats/data/toml/init.luau b/src/Formats/data/toml/init.luau index a019400..e0d871d 100644 --- a/src/Formats/data/toml/init.luau +++ b/src/Formats/data/toml/init.luau @@ -19,7 +19,7 @@ local Toml = { category = "data", extensions = { "toml" }, mime = { "application/toml" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Json", "codecs/Text" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Json", "codecs/text/Text" }, caps = { decode = true, encode = true, ordered = true, dates = true }, } diff --git a/src/Formats/data/xml/init.luau b/src/Formats/data/xml/init.luau index 6479ec5..dc81104 100644 --- a/src/Formats/data/xml/init.luau +++ b/src/Formats/data/xml/init.luau @@ -1,5 +1,5 @@ --!strict --- data/xml: XML 1.0 files, a thin wrapper over codecs/Xml (which see for the node shape and options). Supports: +-- data/xml: XML 1.0 files, a thin wrapper over codecs/text/Xml (which see for the node shape and options). Supports: -- decode to a "#document" XmlNode tree (doc.root = the root element), encode a document or an element. Not -- supported: external entities / DTDs, validation. @@ -8,7 +8,7 @@ local Err = require("@formats/core/Err") local Sniff = require("@formats/core/Sniff") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") -local Xml = require("@formats/codecs/Xml") +local Xml = require("@formats/codecs/text/Xml") -- ------------------------------------------------------------------------------------------------ contract local XmlFormat = { @@ -16,7 +16,7 @@ local XmlFormat = { category = "data", extensions = { "xml", "xsd", "xsl", "xslt", "rss", "atom", "xhtml" }, mime = { "application/xml", "text/xml" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "core/Sniff" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Xml", "core/Sniff" }, caps = { decode = true, encode = true, namespaces = true, streaming = true }, } diff --git a/src/Formats/data/yaml/Parse.luau b/src/Formats/data/yaml/Parse.luau index 172ae04..ff9bd1a 100644 --- a/src/Formats/data/yaml/Parse.luau +++ b/src/Formats/data/yaml/Parse.luau @@ -6,7 +6,7 @@ -- opts.tags = "ignore"), %YAML / %TAG directives, multi-document streams, comments. Scalars resolve with the core -- schema. Not supported: complex keys ("? "), collections as keys, recursive aliases, merge keys "<<" (kept as a -- normal key). Internally raises { yamlErr } tables caught by run(); never throws past it. -local Text = require("@formats/codecs/Text") +local Text = require("@formats/codecs/text/Text") local Types = require("@formats/Types") local Base64 = require("@formats/core/Base64") diff --git a/src/Formats/data/yaml/init.luau b/src/Formats/data/yaml/init.luau index 2b888ee..edc5b10 100644 --- a/src/Formats/data/yaml/init.luau +++ b/src/Formats/data/yaml/init.luau @@ -20,7 +20,7 @@ local Yaml = { category = "data", extensions = { "yaml", "yml" }, mime = { "application/yaml", "application/x-yaml", "text/yaml" }, - deps = { "core/Err", "core/Bytes", "Types", "core/Base64", "codecs/Text" }, + deps = { "core/Err", "core/Bytes", "Types", "core/Base64", "codecs/text/Text" }, caps = { decode = true, encode = true, ordered = true, multiDocument = true, anchors = true }, } diff --git a/src/Formats/font/ttf/init.luau b/src/Formats/font/ttf/init.luau index 2e81f06..6df1358 100644 --- a/src/Formats/font/ttf/init.luau +++ b/src/Formats/font/ttf/init.luau @@ -1,14 +1,14 @@ --!strict -- font/ttf: TrueType and OpenType fonts (.ttf, .otf with CFF outlines) and collections (.ttc / .otc), read into the --- standard Font (Types.Font) by codecs/TrueType: metrics, names, cmap, outlines (glyf or CFF), kerning ('kern' table, --- GPOS pair kerning) and rasterize(glyph, px) through codecs/Raster. Ported from stb_truetype 1.26 (public domain / --- MIT) via imgui-luau's imstb_truetype.lua; see codecs/TrueType. opts.index picks the font of a collection. +-- standard Font (Types.Font) by codecs/font/TrueType: metrics, names, cmap, outlines (glyf or CFF), kerning ('kern' table, +-- GPOS pair kerning) and rasterize(glyph, px) through codecs/image/Raster. Ported from stb_truetype 1.26 (public domain / +-- MIT) via imgui-luau's imstb_truetype.lua; see codecs/font/TrueType. opts.index picks the font of a collection. -- Not supported: hinting, variable fonts, bitmap / colour glyphs, GSUB, writing. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") -local TrueType = require("@formats/codecs/TrueType") +local TrueType = require("@formats/codecs/font/TrueType") -- ------------------------------------------------------------------------------------------------ contract local Ttf = { @@ -16,7 +16,7 @@ local Ttf = { category = "font", extensions = { "ttf", "otf", "ttc", "otc" }, mime = { "font/ttf", "font/otf", "font/collection" }, - deps = { "core/Err", "core/Bytes", "codecs/TrueType" }, + deps = { "core/Err", "core/Bytes", "codecs/font/TrueType" }, caps = { decode = true, encode = false, outlines = { "truetype", "cff" }, collection = true, kerning = true }, } diff --git a/src/Formats/font/woff/init.luau b/src/Formats/font/woff/init.luau index 84d8ad9..c20e880 100644 --- a/src/Formats/font/woff/init.luau +++ b/src/Formats/font/woff/init.luau @@ -1,13 +1,13 @@ --!strict -- font/woff: WOFF 1.0 (W3C Recommendation, 2012): an sfnt font whose tables are zlib-compressed one by one. Decoding --- rebuilds the sfnt and reads it through codecs/TrueType (TrueType or CFF outlines, see font/ttf); the extended +-- rebuilds the sfnt and reads it through codecs/font/TrueType (TrueType or CFF outlines, see font/ttf); the extended -- metadata XML is kept in meta.woffMetadata. Written from the spec. Not supported: writing. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") -local Deflate = require("@formats/codecs/Deflate") -local TrueType = require("@formats/codecs/TrueType") +local Deflate = require("@formats/codecs/compress/Deflate") +local TrueType = require("@formats/codecs/font/TrueType") -- ------------------------------------------------------------------------------------------------ contract local Woff = { @@ -15,7 +15,7 @@ local Woff = { category = "font", extensions = { "woff" }, mime = { "font/woff" }, - deps = { "core/Err", "core/Bytes", "codecs/Deflate", "codecs/TrueType" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/font/TrueType" }, caps = { decode = true, encode = false, outlines = { "truetype", "cff" } }, } diff --git a/src/Formats/font/woff2/Rebuild.luau b/src/Formats/font/woff2/Rebuild.luau index c2668d2..914d34f 100644 --- a/src/Formats/font/woff2/Rebuild.luau +++ b/src/Formats/font/woff2/Rebuild.luau @@ -6,7 +6,7 @@ -- -- Never throws: malformed data returns nil, message. local Bytes = require("@formats/core/Bytes") -local Brotli = require("@formats/codecs/Brotli") +local Brotli = require("@formats/codecs/compress/Brotli") local Rebuild = {} diff --git a/src/Formats/font/woff2/init.luau b/src/Formats/font/woff2/init.luau index 1e697cb..61bfa80 100644 --- a/src/Formats/font/woff2/init.luau +++ b/src/Formats/font/woff2/init.luau @@ -1,12 +1,12 @@ --!strict -- font/woff2: WOFF 2.0 (W3C Recommendation): sfnt tables in one Brotli stream, with the glyf / loca and hmtx --- transforms. Decoding rebuilds the sfnt (font/woff2/Rebuild) and reads it through codecs/TrueType (TrueType or CFF --- outlines, see font/ttf). Written from the spec; Brotli is codecs/Brotli. Not supported: collections, writing. +-- transforms. Decoding rebuilds the sfnt (font/woff2/Rebuild) and reads it through codecs/font/TrueType (TrueType or CFF +-- outlines, see font/ttf). Written from the spec; Brotli is codecs/compress/Brotli. Not supported: collections, writing. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") -local TrueType = require("@formats/codecs/TrueType") +local TrueType = require("@formats/codecs/font/TrueType") local Rebuild = require("@formats/font/woff2/Rebuild") -- ------------------------------------------------------------------------------------------------ contract @@ -15,7 +15,7 @@ local Woff2 = { category = "font", extensions = { "woff2" }, mime = { "font/woff2" }, - deps = { "core/Err", "core/Bytes", "codecs/TrueType", "codecs/Brotli" }, + deps = { "core/Err", "core/Bytes", "codecs/font/TrueType", "codecs/compress/Brotli" }, caps = { decode = true, encode = false, outlines = { "truetype", "cff" }, transforms = { "glyf", "loca", "hmtx" } }, } diff --git a/src/Formats/image/bmp/init.luau b/src/Formats/image/bmp/init.luau index e21a9fa..4904706 100644 --- a/src/Formats/image/bmp/init.luau +++ b/src/Formats/image/bmp/init.luau @@ -16,7 +16,7 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") -local Pixels = require("@formats/image/bmp/Pixels") +local Pixels = require("@formats/codecs/image/Pixels") -- ------------------------------------------------------------------------------------------------ contract local Bmp = { @@ -24,7 +24,7 @@ local Bmp = { category = "image", extensions = { "bmp", "dib" }, mime = { "image/bmp", "image/x-bmp", "image/x-ms-bmp" }, - deps = { "core/Err", "core/Bytes", "Types" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Pixels" }, caps = { decode = true, encode = true, alpha = true, depths = { 1, 2, 4, 8, 16, 24, 32 }, rle = true }, } diff --git a/src/Formats/image/gif/init.luau b/src/Formats/image/gif/init.luau index fcd3bfb..a80829b 100644 --- a/src/Formats/image/gif/init.luau +++ b/src/Formats/image/gif/init.luau @@ -3,7 +3,7 @@ -- (global / local colour tables, interlaced rows, LZW minimum code sizes 2..8 and the odd 1, transparency, frames -- smaller than or outside the canvas), animation (Graphic Control Extension delays, disposal none / background / -- previous, NETSCAPE2.0 / ANIMEXTS1.0 loop counts), comments (meta.text.comment); truncated files keep the frames --- read so far (meta.truncated). Encode of rgba8 images and animations (Types.Frame lists) through codecs/Quantize +-- read so far (meta.truncated). Encode of rgba8 images and animations (Types.Frame lists) through codecs/image/Quantize -- (median cut or octree, optional Floyd-Steinberg dithering; exact palettes, so lossless, at <= 256 colours) with -- alpha < 128 as the transparent index. -- Not supported: the plain text extension (skipped), the aspect ratio (kept in meta.source.aspect), the "user input" @@ -17,8 +17,8 @@ -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") -local Lzw = require("@formats/codecs/Lzw") -local Quantize = require("@formats/codecs/Quantize") +local Lzw = require("@formats/codecs/compress/Lzw") +local Quantize = require("@formats/codecs/image/Quantize") local Types = require("@formats/Types") local Decode = require("@formats/image/gif/Decode") @@ -28,7 +28,7 @@ local Gif = { category = "image", extensions = { "gif" }, mime = { "image/gif" }, - deps = { "core/Err", "core/Bytes", "codecs/Lzw", "codecs/Quantize", "Types" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Lzw", "codecs/image/Quantize", "Types" }, caps = { decode = true, encode = true, animation = true, alpha = true, palette = true, depths = { 1, 2, 4, 8 } }, } diff --git a/src/Formats/image/ico/Dib.luau b/src/Formats/image/ico/Dib.luau index 447fa5e..7bc2f2c 100644 --- a/src/Formats/image/ico/Dib.luau +++ b/src/Formats/image/ico/Dib.luau @@ -4,8 +4,11 @@ -- image/ico/Dib: the BMP device-independent bitmaps inside ICO / CUR entries (native; never throws). Written from -- the Microsoft ICO / BITMAPINFOHEADER documentation: a colour (XOR) bitmap of 1 / 4 / 8 / 16 (5-5-5) / 24 / 32-bit -- pixels, bottom-up rows padded to 4 bytes, then a 1-bit AND mask (1 = transparent). 32-bit entries use their alpha --- channel unless it is all zero (old icons), in which case the AND mask decides. -local readu8, readu16, readu32, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu32 +-- channel unless it is all zero (old icons), in which case the AND mask decides. The row loops are +-- codecs/image/Pixels (shared with BMP); the AND mask and the alpha rule are ICO's. +local Pixels = require("@formats/codecs/image/Pixels") + +local readu8, readu32, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu32 local Dib = {} @@ -18,29 +21,19 @@ function Dib.decode(b: buffer, p: number, e: number, w: number, h: number, bpp: end local hasMask = p + stride * h + maskStride * h <= e local anyAlpha = false - for y = 0, h - 1 do - local row = p + (h - 1 - y) * stride - for x = 0, w - 1 do - local v - if bpp == 32 then - v = readu8(b, row + x * 4 + 2) + readu8(b, row + x * 4 + 1) * 256 + readu8(b, row + x * 4) * 65536 + readu8(b, row + x * 4 + 3) * 16777216 - if v >= 16777216 then - anyAlpha = true - end - elseif bpp == 24 then - v = readu8(b, row + x * 3 + 2) + readu8(b, row + x * 3 + 1) * 256 + readu8(b, row + x * 3) * 65536 + 0xFF000000 - elseif bpp == 16 then - local s = readu16(b, row + x * 2) - local r, g, bl = (s // 1024) % 32, (s // 32) % 32, s % 32 - v = (r * 255 + 15) // 31 + ((g * 255 + 15) // 31) * 256 + ((bl * 255 + 15) // 31) * 65536 + 0xFF000000 - else - local bit = x * bpp - local byte = readu8(b, row + bit // 8) - local idx = (byte // 2 ^ (8 - bpp - bit % 8)) % 2 ^ bpp - v = if idx < palN then readu32(pal, idx * 4) else 0xFF000000 - end - writeu32(out, (y * w + x) * 4, v) + if bpp == 32 then + anyAlpha = Pixels.bgra32(b, p, stride, out, w, h, false) ~= 0 + elseif bpp == 24 then + Pixels.bgr24(b, p, stride, out, w, h, false) + elseif bpp == 16 then + Pixels.rgb555(b, p, stride, out, w, h, false) + else + -- palette indexes past palN read as opaque black + local full = buffer.create(1024) + for i = 0, 255 do + writeu32(full, i * 4, if i < palN then readu32(pal, i * 4) else 0xFF000000) end + Pixels.indexed(b, p, stride, bpp, out, w, h, false, full) end if bpp == 32 and anyAlpha then return true, nil diff --git a/src/Formats/image/ico/init.luau b/src/Formats/image/ico/init.luau index ba4085d..e614446 100644 --- a/src/Formats/image/ico/init.luau +++ b/src/Formats/image/ico/init.luau @@ -22,7 +22,7 @@ local Ico = { category = "image", extensions = { "ico", "cur" }, mime = { "image/vnd.microsoft.icon", "image/x-icon" }, - deps = { "core/Err", "core/Bytes", "Types" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Pixels" }, caps = { decode = true, encode = true, alpha = true, frames = true, depths = { 1, 4, 8, 16, 24, 32 } }, } diff --git a/src/Formats/image/jpeg/init.luau b/src/Formats/image/jpeg/init.luau index aeffeea..b597f5d 100644 --- a/src/Formats/image/jpeg/init.luau +++ b/src/Formats/image/jpeg/init.luau @@ -1,5 +1,5 @@ --!strict --- image/jpeg: JPEG / JFIF / EXIF (ITU T.81), a thin format over codecs/Jpeg (the engine, shared with the Motion-JPEG +-- image/jpeg: JPEG / JFIF / EXIF (ITU T.81), a thin format over codecs/image/Jpeg (the engine, shared with the Motion-JPEG -- video tracks; absorbed from jpeg-luau 1.0, same author, bit-exact with libjpeg-turbo's djpeg and byte-identical -- with cjpeg; IJG-derived parts: licenses/libjpeg-turbo-LICENSE.md). This module is the contract, the sniff, the -- options and the meta segments: meta.exif (APP1), meta.icc (APP2 chunks), meta.text.comment (COM) and meta.dpi @@ -20,7 +20,7 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") -local Codec = require("@formats/codecs/Jpeg") +local Codec = require("@formats/codecs/image/Jpeg") -- ------------------------------------------------------------------------------------------------ contract local Jpeg = { @@ -28,7 +28,7 @@ local Jpeg = { category = "image", extensions = { "jpg", "jpeg", "jpe", "jfif" }, mime = { "image/jpeg" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Jpeg" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Jpeg" }, caps = { decode = true, encode = true, lossy = true, alpha = false, depths = { 8, 12 }, progressive = true, arithmetic = true }, } diff --git a/src/Formats/image/png/init.luau b/src/Formats/image/png/init.luau index 117ff4f..f6f2c05 100644 --- a/src/Formats/image/png/init.luau +++ b/src/Formats/image/png/init.luau @@ -14,8 +14,9 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Crc32 = require("@formats/core/Crc32") -local Deflate = require("@formats/codecs/Deflate") +local Deflate = require("@formats/codecs/compress/Deflate") local Types = require("@formats/Types") +local Chunks = require("@formats/containers/Chunks") local Decode = require("@formats/image/png/Decode") local Encode = require("@formats/image/png/Encode") local Apng = require("@formats/image/png/Apng") @@ -26,7 +27,7 @@ local Png = { category = "image", extensions = { "png", "apng" }, mime = { "image/png", "image/apng" }, - deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/Deflate", "Types" }, + deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/compress/Deflate", "Types", "containers/Chunks" }, caps = { decode = true, encode = true, animation = true, alpha = true, depths = { 1, 2, 4, 8, 16 } }, } @@ -193,13 +194,15 @@ function Png.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E local animPixels = 0 local p = r.base + 8 local first = true - while p + 12 <= n do - local len = be32(b, p) - local typ = buffer.readstring(b, p + 4, 4) - if len > n - p - 12 then + for _, c in Chunks.walk(b, p, n, Chunks.PNG) do + local len, typ, d = c.size, c.id, c.offset + p = c.start + if c.truncated then + if p + 12 > n then + break -- not even a whole chunk header + CRC left (a cut tail) + end return nil, Err.new(Err.TRUNCATED, "chunk " .. typ .. " runs past the end", p) end - local d = p + 8 if checkCrc then local want = be32(b, d + len) if Crc32.raw(b, p + 4, len + 4) ~= want then @@ -305,7 +308,6 @@ function Png.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E elseif bit32.band(readu8(b, p + 4), 0x20) == 0 and typ ~= "IHDR" then return nil, Err.new(Err.UNSUPPORTED, "unknown critical chunk " .. typ, p) end - p = d + len + 4 end if #idat == 0 then return nil, Err.new(Err.TRUNCATED, "no image data", p) diff --git a/src/Formats/image/tiff/init.luau b/src/Formats/image/tiff/init.luau index a44f977..549b166 100644 --- a/src/Formats/image/tiff/init.luau +++ b/src/Formats/image/tiff/init.luau @@ -1,7 +1,7 @@ --!strict -- image/tiff: TIFF 6.0 (+ Adobe technote 3 floating point, BigTIFF). New code from the TIFF 6.0 specification. -- Decode: both byte orders, classic and BigTIFF, strips and tiles, planar configuration 1 and 2, compression none / --- LZW (codecs/Lzw, also old-style) / Deflate (8 and 32946, codecs/Deflate) / PackBits, JPEG (7) through the api's +-- LZW (codecs/compress/Lzw, also old-style) / Deflate (8 and 32946, codecs/compress/Deflate) / PackBits, JPEG (7) through the api's -- opts.decodeImage hook (JPEGTables stitched to each strip / tile), predictors 2 (8 / 16 / 32-bit) and 3 (float), -- 1..32-bit unsigned / signed integer and 16 / 32 / 64-bit float samples, min-is-white / min-is-black, RGB, palette, -- CMYK (naive conversion), extra samples (associated alpha is un-premultiplied), fill order 2, every page as @@ -15,8 +15,8 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") -local Deflate = require("@formats/codecs/Deflate") -local Lzw = require("@formats/codecs/Lzw") +local Deflate = require("@formats/codecs/compress/Deflate") +local Lzw = require("@formats/codecs/compress/Lzw") local Pixels = require("@formats/image/tiff/Pixels") -- ------------------------------------------------------------------------------------------------ contract @@ -25,7 +25,7 @@ local Tiff = { category = "image", extensions = { "tif", "tiff" }, mime = { "image/tiff" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Deflate", "codecs/Lzw" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Deflate", "codecs/compress/Lzw" }, caps = { decode = true, encode = true, alpha = true, pages = true, depths = { 1, 2, 4, 8, 16, 32 }, float = true }, } diff --git a/src/Formats/image/webp/Alpha.luau b/src/Formats/image/webp/Alpha.luau index 5da90de..9541342 100644 --- a/src/Formats/image/webp/Alpha.luau +++ b/src/Formats/image/webp/Alpha.luau @@ -3,7 +3,7 @@ -- image/webp/Alpha: the ALPH chunk (RFC 9649 section 2.7.1.2): header byte (compression, filter, pre-processing), -- raw or VP8L-compressed alpha (the green channel of a headerless VP8L stream), and the horizontal / vertical / -- gradient unfilters of libwebp src/dsp/filters.c (BSD-3-Clause, licenses/libwebp-LICENSE.txt). Never throws. -local Vp8L = require("@formats/codecs/Vp8L") +local Vp8L = require("@formats/codecs/image/Vp8L") local readu8, writeu8 = buffer.readu8, buffer.writeu8 diff --git a/src/Formats/image/webp/init.luau b/src/Formats/image/webp/init.luau index 9834b1c..a5b09c9 100644 --- a/src/Formats/image/webp/init.luau +++ b/src/Formats/image/webp/init.luau @@ -1,6 +1,6 @@ --!strict -- image/webp: WebP (RFC 9649; Google's "WebP Container Specification"). New code: the bitstreams are ports of libwebp 1.6 --- (codecs/Vp8, codecs/Vp8L; BSD-3-Clause, licenses/libwebp-LICENSE.txt), the chunks go through containers/Riff, the +-- (codecs/image/Vp8, codecs/image/Vp8L; BSD-3-Clause, licenses/libwebp-LICENSE.txt), the chunks go through containers/Riff, the -- container rules and the compositing follow libwebp's demux / WebPAnimDecoder. -- Supports: decode of lossy (VP8 key frames: bit-exact with dwebp, fancy or point chroma upsampling, or the raw -- yuv420p planes with opts.native), lossless (VP8L, bit-exact), alpha (ALPH raw or lossless, every filter), the @@ -18,8 +18,8 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") -local Vp8 = require("@formats/codecs/Vp8") -local Vp8L = require("@formats/codecs/Vp8L") +local Vp8 = require("@formats/codecs/image/Vp8") +local Vp8L = require("@formats/codecs/image/Vp8L") local Riff = require("@formats/containers/Riff") local Alpha = require("@formats/image/webp/Alpha") local Anim = require("@formats/image/webp/Anim") @@ -30,7 +30,7 @@ local Webp = { category = "image", extensions = { "webp" }, mime = { "image/webp" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Vp8", "codecs/Vp8L", "containers/Riff" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Vp8", "codecs/image/Vp8L", "containers/Riff" }, caps = { decode = true, encode = true, animation = true, alpha = true, lossy = true, lossless = true, depths = { 8 } }, } @@ -134,7 +134,7 @@ end -- subChunks(f, c) -> the chunks inside an ANMF payload (after its 16-byte header) local function subChunks(f: Riff.File, c: Chunk): ({ Chunk }?, Err.Err?) local n = c.size - 12 - return convert(Riff.list(f, { id = c.id, offset = c.off + 12, size = n, declared = n, avail = n, truncated = false, streamed = false })) + return convert(Riff.list(f, { id = c.id, start = c.off + 4, offset = c.off + 12, size = n, declared = n, avail = n, truncated = false, streamed = false })) end type Bitstream = { rgba: buffer?, yuv: Types.Image?, w: number, h: number, hasAlpha: boolean, source: { [string]: any } } diff --git a/src/Formats/init.luau b/src/Formats/init.luau index 407aec5..4f90979 100644 --- a/src/Formats/init.luau +++ b/src/Formats/init.luau @@ -20,7 +20,7 @@ local Bytes = require("@formats/core/Bytes") local Input = require("@formats/core/Input") local Types = require("@formats/Types") local Registry = require("@formats/Registry") -local Video = require("@formats/codecs/Video") +local Video = require("@formats/codecs/video/Video") local AudioWrap = require("@formats/containers/AudioWrap") local ImageOps = require("@formats/ops/ImageOps") local host = require("@formats/host") @@ -648,7 +648,7 @@ end F.video.fromFrames = function(images: any, delays: any?, opts: Options?): (any, Err.Err?) return Video.fromFrames(images, delays, opts) end --- F.video.codecs: the video codec registry (codecs/Video: register / entry / fromFourcc / fromMatroska / decoder) +-- F.video.codecs: the video codec registry (codecs/video/Video: register / entry / fromFourcc / fromMatroska / decoder) F.video.codecs = Video -- F.model.loadTextures(scene, opts?) -> scene, { [index]: Err }: decodes each texture's encoded bytes (texture.data, or diff --git a/src/Formats/layered/aseprite/init.luau b/src/Formats/layered/aseprite/init.luau index 6799137..04f2f8b 100644 --- a/src/Formats/layered/aseprite/init.luau +++ b/src/Formats/layered/aseprite/init.luau @@ -17,7 +17,7 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") -local Deflate = require("@formats/codecs/Deflate") +local Deflate = require("@formats/codecs/compress/Deflate") -- ------------------------------------------------------------------------------------------------ contract local Aseprite = { @@ -25,7 +25,7 @@ local Aseprite = { category = "layered", extensions = { "aseprite", "ase" }, mime = { "image/x-aseprite" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Deflate" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Deflate" }, caps = { decode = true, encode = true, layers = true, groups = true, animation = true, depths = { 8, 16, 32 } }, } diff --git a/src/Formats/layered/psd/Channels.luau b/src/Formats/layered/psd/Channels.luau index b44657e..811f076 100644 --- a/src/Formats/layered/psd/Channels.luau +++ b/src/Formats/layered/psd/Channels.luau @@ -4,7 +4,7 @@ -- plane of big-endian samples, converts planes to rgba8 for every colour mode, and PackBits-encodes rows for the -- writer. Adobe Photoshop File Formats Specification (2016), "Channel image data" / "Image data section". -- Never throws: every read is range-checked first; failures return nil, "message". -local Deflate = require("@formats/codecs/Deflate") +local Deflate = require("@formats/codecs/compress/Deflate") local Channels = {} diff --git a/src/Formats/layered/psd/init.luau b/src/Formats/layered/psd/init.luau index af510e7..af83e5f 100644 --- a/src/Formats/layered/psd/init.luau +++ b/src/Formats/layered/psd/init.luau @@ -5,7 +5,7 @@ -- opacity, fill opacity (iOpa), visibility, clipping, Unicode names (luni), user masks (as grey masks), groups (lsct / -- lsdk section dividers -> group layers with children; pass-through kept as the "passThrough" blend); the merged image -- (meta.composite); image resources (meta.resources, ICC profile in meta.icc). Everything converts to rgba8. --- Encode: an 8-bit RGB PSD (PSB when a side is over 30000) with the RLE merged composite (ops-free: codecs/Blend +-- Encode: an 8-bit RGB PSD (PSB when a side is over 30000) with the RLE merged composite (ops-free: codecs/image/Blend -- flattens the tree, or opts.composite) and every layer as RLE RGBA channels, groups as section dividers, masks, -- clipping, opacity / fill, hidden flags and Unicode names. -- Not supported: adjustment / fill / type / smart-object layer contents (their pixels, if any, are used), layer @@ -15,7 +15,7 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") -local Blend = require("@formats/codecs/Blend") +local Blend = require("@formats/codecs/image/Blend") local Channels = require("@formats/layered/psd/Channels") -- ------------------------------------------------------------------------------------------------ contract @@ -24,7 +24,7 @@ local Psd = { category = "layered", extensions = { "psd", "psb" }, mime = { "image/vnd.adobe.photoshop" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Blend", "codecs/Deflate" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Blend", "codecs/compress/Deflate" }, caps = { decode = true, encode = true, layers = true, groups = true, depths = { 1, 8, 16, 32 } }, } @@ -34,7 +34,7 @@ export type DecodeOptions = { maxLayers: number?, -- default 10000 } export type EncodeOptions = { - composite: Types.Image?, -- the merged image to store (default: the layers flattened with codecs/Blend) + composite: Types.Image?, -- the merged image to store (default: the layers flattened with codecs/image/Blend) } -- ------------------------------------------------------------------------------------------------ constants diff --git a/src/Formats/model/3mf/Read.luau b/src/Formats/model/3mf/Read.luau index 710de1c..2239bf7 100644 --- a/src/Formats/model/3mf/Read.luau +++ b/src/Formats/model/3mf/Read.luau @@ -8,7 +8,7 @@ -- texture groups give per-corner COLOR_0 / TEXCOORD_0, so vertices are split where corners of one vertex differ. local Err = require("@formats/core/Err") local Types = require("@formats/Types") -local Xml = require("@formats/codecs/Xml") +local Xml = require("@formats/codecs/text/Xml") local Zip = require("@formats/containers/Zip") local Read = {} diff --git a/src/Formats/model/3mf/Write.luau b/src/Formats/model/3mf/Write.luau index a1f4f4b..80b5c64 100644 --- a/src/Formats/model/3mf/Write.luau +++ b/src/Formats/model/3mf/Write.luau @@ -7,7 +7,7 @@ -- Units: meta.unit picks the 3MF unit when it is one of them; otherwise millimetres and the build transforms scale. local Err = require("@formats/core/Err") local Types = require("@formats/Types") -local Xml = require("@formats/codecs/Xml") +local Xml = require("@formats/codecs/text/Xml") local Zip = require("@formats/containers/Zip") local Write = {} diff --git a/src/Formats/model/3mf/init.luau b/src/Formats/model/3mf/init.luau index 025a695..213c037 100644 --- a/src/Formats/model/3mf/init.luau +++ b/src/Formats/model/3mf/init.luau @@ -1,7 +1,7 @@ --!strict -- model/3mf: 3D Manufacturing Format (3MF Consortium core specification 1.3, materials and properties extension 1.2, -- production extension 1.1 part references). New code. An OPC package (containers/Zip) holding XML model parts --- (codecs/Xml). +-- (codecs/text/Xml). -- Reads: the root model part (_rels/.rels), objects (mesh vertices / triangles; components with transforms, also from -- other model parts through p:path), build items -> root nodes with their transforms (3MF's row-vector 4x3 matrices -- become column-major node.matrix), object names / types / part numbers (node / mesh extras["3mf"]), metadata @@ -31,7 +31,7 @@ local ThreeMf = { category = "model", extensions = { "3mf" }, mime = { "model/3mf" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "containers/Zip" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Xml", "containers/Zip" }, caps = { decode = true, encode = true, materials = true, vertexColors = true, textures = true, units = true }, } diff --git a/src/Formats/model/dae/Math.luau b/src/Formats/model/dae/Math.luau index 594a53b..dbc2a1c 100644 --- a/src/Formats/model/dae/Math.luau +++ b/src/Formats/model/dae/Math.luau @@ -1,79 +1,11 @@ --!strict --- model/dae/Math: the matrix helpers the Collada reader and writer share. Matrices are flat arrays of 16 in glTF's --- column-major order (Collada writes row-major: fromRows / toRows convert). Quaternions are { x, y, z, w }. +-- model/dae/Math: the Collada-specific transform elements (<lookat>, <skew>); everything else (matrices, +-- quaternions, decomposition) is codecs/model/Mat4. Matrices are flat arrays of 16 in column-major order. +local Mat4 = require("@formats/codecs/model/Mat4") + local DaeMath = {} -local sqrt, abs, rad, sin, cos = math.sqrt, math.abs, math.rad, math.sin, math.cos - -function DaeMath.identity(): { number } - return { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 } -end - --- fromRows(v, at?) -> column-major from 16 row-major values starting at v[at] (default 1) -function DaeMath.fromRows(v: { number }, at: number?): { number } - local o = (at or 1) - 1 - local m = table.create(16, 0) - for r = 0, 3 do - for c = 0, 3 do - m[c * 4 + r + 1] = v[o + r * 4 + c + 1] or (if r == c then 1 else 0) - end - end - return m -end - -function DaeMath.toRows(m: { number }): { number } - local v = table.create(16, 0) - for r = 0, 3 do - for c = 0, 3 do - v[r * 4 + c + 1] = m[c * 4 + r + 1] - end - end - return v -end - -function DaeMath.mul(a: { number }, b: { number }): { number } - local m = table.create(16, 0) - for col = 0, 3 do - for row = 0, 3 do - local s = 0 - for k = 0, 3 do - s += a[k * 4 + row + 1] * b[col * 4 + k + 1] - end - m[col * 4 + row + 1] = s - end - end - return m -end - -function DaeMath.translation(x: number, y: number, z: number): { number } - return { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1 } -end - -function DaeMath.scaling(x: number, y: number, z: number): { number } - return { x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1 } -end - --- axisAngle(x, y, z, degrees) -> quaternion -function DaeMath.axisAngle(x: number, y: number, z: number, degrees: number): { number } - local l = sqrt(x * x + y * y + z * z) - if l < 1e-12 then - return { 0, 0, 0, 1 } - end - local h = rad(degrees) / 2 - local s = sin(h) / l - return { x * s, y * s, z * s, cos(h) } -end - -function DaeMath.quatMatrix(q: { number }): { number } - local x, y, z, w = q[1], q[2], q[3], q[4] - local xx, yy, zz, xy, xz, yz, wx, wy, wz = x * x, y * y, z * z, x * y, x * z, y * z, w * x, w * y, w * z - return { - 1 - 2 * (yy + zz), 2 * (xy + wz), 2 * (xz - wy), 0, - 2 * (xy - wz), 1 - 2 * (xx + zz), 2 * (yz + wx), 0, - 2 * (xz + wy), 2 * (yz - wx), 1 - 2 * (xx + yy), 0, - 0, 0, 0, 1, - } -end +local sqrt, rad = math.sqrt, math.rad local function cross(a: { number }, b: { number }): { number } return { a[2] * b[3] - a[3] * b[2], a[3] * b[1] - a[1] * b[3], a[1] * b[2] - a[2] * b[1] } @@ -101,7 +33,7 @@ function DaeMath.skew(v: { number }): { number } local r = norm({ v[2] or 0, v[3] or 0, v[4] or 0 }) local t = norm({ v[5] or 0, v[6] or 0, v[7] or 0 }) local s = math.tan(a) - local m = DaeMath.identity() + local m = Mat4.identity() -- M = I + s * t * r^T (column-major: m[col*4 + row]) for row = 0, 2 do for col = 0, 2 do @@ -111,78 +43,4 @@ function DaeMath.skew(v: { number }): { number } return m end --- decompose(m) -> translation, rotation, scale | nil (shear, a projective row, or a singular matrix) -function DaeMath.decompose(m: { number }): ({ number }?, { number }?, { number }?) - if abs(m[4]) > 1e-6 or abs(m[8]) > 1e-6 or abs(m[12]) > 1e-6 or abs(m[16] - 1) > 1e-6 then - return nil, nil, nil - end - local c1 = { m[1], m[2], m[3] } - local c2 = { m[5], m[6], m[7] } - local c3 = { m[9], m[10], m[11] } - local sx = sqrt(c1[1] * c1[1] + c1[2] * c1[2] + c1[3] * c1[3]) - local sy = sqrt(c2[1] * c2[1] + c2[2] * c2[2] + c2[3] * c2[3]) - local sz = sqrt(c3[1] * c3[1] + c3[2] * c3[2] + c3[3] * c3[3]) - if sx < 1e-12 or sy < 1e-12 or sz < 1e-12 then - return nil, nil, nil - end - local x, y, z = { c1[1] / sx, c1[2] / sx, c1[3] / sx }, { c2[1] / sy, c2[2] / sy, c2[3] / sy }, { c3[1] / sz, c3[2] / sz, c3[3] / sz } - local dxy = x[1] * y[1] + x[2] * y[2] + x[3] * y[3] - local dxz = x[1] * z[1] + x[2] * z[2] + x[3] * z[3] - local dyz = y[1] * z[1] + y[2] * z[2] + y[3] * z[3] - if abs(dxy) > 1e-4 or abs(dxz) > 1e-4 or abs(dyz) > 1e-4 then - return nil, nil, nil - end - local cr = cross(x, y) - if cr[1] * z[1] + cr[2] * z[2] + cr[3] * z[3] < 0 then - sx = -sx - x = { -x[1], -x[2], -x[3] } - end - -- rotation matrix (columns x, y, z) -> quaternion - local m00, m01, m02 = x[1], y[1], z[1] - local m10, m11, m12 = x[2], y[2], z[2] - local m20, m21, m22 = x[3], y[3], z[3] - local tr = m00 + m11 + m22 - local qx, qy, qz, qw - if tr > 0 then - local s = sqrt(tr + 1) * 2 - qw, qx, qy, qz = s / 4, (m21 - m12) / s, (m02 - m20) / s, (m10 - m01) / s - elseif m00 > m11 and m00 > m22 then - local s = sqrt(1 + m00 - m11 - m22) * 2 - qw, qx, qy, qz = (m21 - m12) / s, s / 4, (m01 + m10) / s, (m02 + m20) / s - elseif m11 > m22 then - local s = sqrt(1 + m11 - m00 - m22) * 2 - qw, qx, qy, qz = (m02 - m20) / s, (m01 + m10) / s, s / 4, (m12 + m21) / s - else - local s = sqrt(1 + m22 - m00 - m11) * 2 - qw, qx, qy, qz = (m10 - m01) / s, (m02 + m20) / s, (m12 + m21) / s, s / 4 - end - local l = sqrt(qx * qx + qy * qy + qz * qz + qw * qw) - return { m[13], m[14], m[15] }, { qx / l, qy / l, qz / l, qw / l }, { sx, sy, sz } -end - --- transformPoint / transformDir (column-major m) -function DaeMath.point(m: { number }, x: number, y: number, z: number): (number, number, number) - return m[1] * x + m[5] * y + m[9] * z + m[13], m[2] * x + m[6] * y + m[10] * z + m[14], m[3] * x + m[7] * y + m[11] * z + m[15] -end - --- the inverse transpose of the upper 3x3 (for normals), as a column-major 4x4 -function DaeMath.normalMatrix(m: { number }): { number } - local a, b, c = m[1], m[5], m[9] - local d, e, f = m[2], m[6], m[10] - local g, h, i = m[3], m[7], m[11] - local A, B, C = e * i - f * h, -(d * i - f * g), d * h - e * g - local det = a * A + b * B + c * C - if abs(det) < 1e-30 then - return DaeMath.identity() - end - local k = 1 / det - -- inverse = adj / det; its transpose has rows = cofactors - return { - A * k, B * k, C * k, 0, - -(b * i - c * h) * k, (a * i - c * g) * k, -(a * h - b * g) * k, 0, - (b * f - c * e) * k, -(a * f - c * d) * k, (a * e - b * d) * k, 0, - 0, 0, 0, 1, - } -end - return DaeMath diff --git a/src/Formats/model/dae/Read.luau b/src/Formats/model/dae/Read.luau index 93ae05f..2d0c857 100644 --- a/src/Formats/model/dae/Read.luau +++ b/src/Formats/model/dae/Read.luau @@ -1,5 +1,5 @@ --!strict --- model/dae/Read: a parsed Collada document (codecs/Xml DOM) -> Scene. Geometry (triangles / polylist / polygons / +-- model/dae/Read: a parsed Collada document (codecs/text/Xml DOM) -> Scene. Geometry (triangles / polylist / polygons / -- lines / linestrips / tristrips / trifans with shared input offsets, de-indexed per index tuple), common-profile -- materials (phong / blinn / lambert / constant -> PBR + extras.phong) with their sampler2D / surface / image chains, -- images (kept encoded through the fetch callback, or embedded hex <data>), the visual scene's node tree (matrix / @@ -10,9 +10,10 @@ -- channels; one animation per animation clip, else one for the file). local Err = require("@formats/core/Err") local Types = require("@formats/Types") -local Xml = require("@formats/codecs/Xml") +local Xml = require("@formats/codecs/text/Xml") local Base64 = require("@formats/core/Base64") local M = require("@formats/model/dae/Math") +local Mat4 = require("@formats/codecs/model/Mat4") local Read = {} @@ -919,14 +920,14 @@ local function meshFor(C: Ctx, geomEl: any, inst: any, key: string, bindShape: { local pos = copyAccessor(attrs.POSITION) for v = 0, pos.count - 1 do local x, y, z = buffer.readf32(pos.data, v * 12), buffer.readf32(pos.data, v * 12 + 4), buffer.readf32(pos.data, v * 12 + 8) - x, y, z = M.point(bindShape, x, y, z) + x, y, z = Mat4.point(bindShape, x, y, z) buffer.writef32(pos.data, v * 12, x) buffer.writef32(pos.data, v * 12 + 4, y) buffer.writef32(pos.data, v * 12 + 8, z) end attrs.POSITION = pos if attrs.NORMAL then - local nm = M.normalMatrix(bindShape) + local nm = Mat4.normalMatrix(bindShape) local nrm = copyAccessor(attrs.NORMAL) for v = 0, nrm.count - 1 do local x, y, z = buffer.readf32(nrm.data, v * 12), buffer.readf32(nrm.data, v * 12 + 4), buffer.readf32(nrm.data, v * 12 + 8) @@ -1126,31 +1127,31 @@ local XFORMS = { matrix = 16, translate = 3, rotate = 4, scale = 3, lookat = 9, -- the matrix of one transform element's values local function xfMatrix(kind: string, v: { number }): { number } if kind == "matrix" then - return M.fromRows(v) + return Mat4.fromRows(v) elseif kind == "translate" then - return M.translation(v[1] or 0, v[2] or 0, v[3] or 0) + return Mat4.translation(v[1] or 0, v[2] or 0, v[3] or 0) elseif kind == "rotate" then - return M.quatMatrix(M.axisAngle(v[1] or 0, v[2] or 0, v[3] or 1, v[4] or 0)) + return Mat4.fromQuat(Mat4.axisAngle(v[1] or 0, v[2] or 0, v[3] or 1, v[4] or 0)) elseif kind == "scale" then - return M.scaling(v[1] or 1, v[2] or 1, v[3] or 1) + return Mat4.scaling(v[1] or 1, v[2] or 1, v[3] or 1) elseif kind == "lookat" then return M.lookat(v) elseif kind == "skew" then return M.skew(v) end - return M.identity() + return Mat4.identity() end local function compose(xf: { any }): { number } - local m = M.identity() + local m = Mat4.identity() for _, x in xf do - m = M.mul(m, xfMatrix(x.kind, x.values)) + m = Mat4.mul(m, xfMatrix(x.kind, x.values)) end return m end local function setTransform(node: Types.Node, m: { number }) - local t, r, s = M.decompose(m) + local t, r, s = Mat4.decomposeStrict(m) node.translation, node.rotation, node.scale, node.matrix = nil, nil, nil, nil if t and r and s then if t[1] ~= 0 or t[2] ~= 0 or t[3] ~= 0 then @@ -1164,7 +1165,7 @@ local function setTransform(node: Types.Node, m: { number }) end else for i = 1, 16 do - if math.abs(m[i] - M.identity()[i]) > 0 then + if math.abs(m[i] - Mat4.identity()[i]) > 0 then node.matrix = m break end @@ -1219,7 +1220,7 @@ local function instances(C: Ctx, el: any, node: Types.Node, idx: number) end if src and lname(src) == "geometry" then local bsm = child(skinEl, "bind_shape_matrix") - local bind = if bsm then M.fromRows(numbers(text(bsm), 16) or {}) else nil + local bind = if bsm then Mat4.fromRows(numbers(text(bsm), 16) or {}) else nil local mi, built = meshFor(C, src, ch, "skin:" .. (attr(ctrl, "id") or ""), bind) if C.err then return @@ -1414,7 +1415,7 @@ local function resolveSkins(C: Ctx) if ibm and ibm.comps == 16 and ibm.count >= #names then local b = buffer.create(#names * 64) for i = 0, #names - 1 do - local cm = M.fromRows(ibm.data, i * 16 + 1) + local cm = Mat4.fromRows(ibm.data, i * 16 + 1) for k = 1, 16 do buffer.writef32(b, (i * 16 + k - 1) * 4, cm[k]) end @@ -1715,7 +1716,7 @@ local function bake(C: Ctx, name: string?, byNode: { [number]: { Curve } }, orde end end end - local tr, ro, sc = M.decompose(compose(xf)) + local tr, ro, sc = Mat4.decomposeStrict(compose(xf)) tr, ro, sc = tr or { 0, 0, 0 }, ro or { 0, 0, 0, 1 }, sc or { 1, 1, 1 } if prev and prev[1] * ro[1] + prev[2] * ro[2] + prev[3] * ro[3] + prev[4] * ro[4] < 0 then ro = { -ro[1], -ro[2], -ro[3], -ro[4] } diff --git a/src/Formats/model/dae/Write.luau b/src/Formats/model/dae/Write.luau index 7d8b51c..e9a4831 100644 --- a/src/Formats/model/dae/Write.luau +++ b/src/Formats/model/dae/Write.luau @@ -5,9 +5,9 @@ -- extras.phong; images as files (opts.files), their uri, or data: URIs; the node tree as row-major <matrix>; cameras; -- lights. Not written: skins, morph targets, animations. local Types = require("@formats/Types") -local Xml = require("@formats/codecs/Xml") +local Xml = require("@formats/codecs/text/Xml") local Base64 = require("@formats/core/Base64") -local M = require("@formats/model/dae/Math") +local Mat4 = require("@formats/codecs/model/Mat4") local Write = {} @@ -325,7 +325,7 @@ function Write.build(scene: Types.Scene, opts: any?): string? return end seen[i] = true - w(format('<node id="node%d"%s type="NODE"><matrix sid="transform">%s</matrix>', i, nameAttr(n.name), list(M.toRows(Scene.nodeMatrix(n))))) + w(format('<node id="node%d"%s type="NODE"><matrix sid="transform">%s</matrix>', i, nameAttr(n.name), list(Mat4.toRows(Scene.nodeMatrix(n))))) if n.mesh and geoms[n.mesh] then for _, g in geoms[n.mesh] do if g.material then diff --git a/src/Formats/model/dae/init.luau b/src/Formats/model/dae/init.luau index 735bef9..7aae240 100644 --- a/src/Formats/model/dae/init.luau +++ b/src/Formats/model/dae/init.luau @@ -26,7 +26,7 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") -local Xml = require("@formats/codecs/Xml") +local Xml = require("@formats/codecs/text/Xml") local Zip = require("@formats/containers/Zip") local Read = require("@formats/model/dae/Read") local Write = require("@formats/model/dae/Write") @@ -37,7 +37,7 @@ local Dae = { category = "model", extensions = { "dae", "zae" }, mime = { "model/vnd.collada+xml", "model/vnd.collada+zip" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "core/Base64", "containers/Zip" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Xml", "core/Base64", "containers/Zip", "codecs/model/Mat4" }, caps = { decode = true, encode = true, materials = true, polygons = true, skins = true, morphTargets = true, animation = true, cameras = true, lights = true, zae = true }, } diff --git a/src/Formats/model/fbx/Binary.luau b/src/Formats/model/fbx/Binary.luau index a1ea942..01880f5 100644 --- a/src/Formats/model/fbx/Binary.luau +++ b/src/Formats/model/fbx/Binary.luau @@ -2,10 +2,10 @@ --!native -- model/fbx/Binary: the binary FBX node tree reader and writer (versions 7.x: 32-bit node records before 7500, 64-bit -- from 7500). From the format as documented by Blender's io_scene_fbx (encode_bin.py / parse_fbx.py) and assimp's --- FBXBinaryTokenizer. Arrays (f, d, l, i, b) are inflated with codecs/Deflate when compressed and kept as Tree.Array +-- FBXBinaryTokenizer. Arrays (f, d, l, i, b) are inflated with codecs/compress/Deflate when compressed and kept as Tree.Array -- values (every element as an f64; 64-bit integers past 2^53 lose precision there); scalar L values past 2^53 become -- the string "L<hex>" so ids stay exact. Never throws: errors are returned (nil, message, offset). -local Deflate = require("@formats/codecs/Deflate") +local Deflate = require("@formats/codecs/compress/Deflate") local Binary = {} diff --git a/src/Formats/model/fbx/Read.luau b/src/Formats/model/fbx/Read.luau index aa9ea4d..9d3aeb5 100644 --- a/src/Formats/model/fbx/Read.luau +++ b/src/Formats/model/fbx/Read.luau @@ -14,6 +14,7 @@ local Err = require("@formats/core/Err") local Types = require("@formats/Types") local Base64 = require("@formats/core/Base64") local Xform = require("@formats/model/fbx/Xform") +local Mat4 = require("@formats/codecs/model/Mat4") local Read = {} @@ -486,13 +487,13 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ order = pnum(p, "RotationOrder", 0), } end - local localM: { [number]: Xform.M4 } = {} + local localM: { [number]: Mat4.M4 } = {} for _, o in models do local ni = nodeOf[o.id] local nd = scene.nodes[ni] local m = Xform.localMatrix(xprops(o)) localM[ni] = m - local t, r, s = Xform.decompose(m) + local t, r, s = Mat4.decompose(m) if t[1] ~= 0 or t[2] ~= 0 or t[3] ~= 0 then nd.translation = t end @@ -543,9 +544,9 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ end end -- world matrices (rest pose) - local worldM: { [number]: Xform.M4 } = {} - local function world(i: number, parent: Xform.M4) - worldM[i] = Xform.mul(parent, localM[i] or Xform.identity()) + local worldM: { [number]: Mat4.M4 } = {} + local function world(i: number, parent: Mat4.M4) + worldM[i] = Mat4.mul(parent, localM[i] or Mat4.identity()) for _, c in scene.nodes[i].children do if not worldM[c] then world(c, worldM[i]) @@ -553,7 +554,7 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ end end for _, r in scene.roots do - world(r, Xform.identity()) + world(r, Mat4.identity()) end -- ------------------------------------------------------------------------------------------ meshes @@ -566,7 +567,7 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ end local perCp: { { { number } } } = {} local joints: { number } = {} - local ibms: { Xform.M4 } = {} + local ibms: { Mat4.M4 } = {} for _, cl in sources(skin.id, "Deformer", "Cluster") do local bone = sources(cl.id, "Model")[1] local bi = bone and nodeOf[bone.id] @@ -575,13 +576,13 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ joints[ji] = bi local idx, w = array(cl.node, "Indexes"), array(cl.node, "Weights") local T, TL = array(cl.node, "Transform"), array(cl.node, "TransformLink") - local tm = Xform.identity() + local tm = Mat4.identity() if T and T.count >= 16 then for k = 1, 16 do tm[k] = at(T, k - 1) end end - local tl: Xform.M4? = nil + local tl: Mat4.M4? = nil if TL and TL.count >= 16 then tl = {} for k = 1, 16 do @@ -590,8 +591,8 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ else tl = worldM[bi] end - local inv = Xform.inverse(tl :: Xform.M4) or Xform.identity() - ibms[ji] = Xform.mul(inv, tm) + local inv = Mat4.inverse(tl :: Mat4.M4) or Mat4.identity() + ibms[ji] = Mat4.mul(inv, tm) if idx and w then for k = 0, math.min(idx.count, w.count) - 1 do local cp = at(idx, k) @@ -648,7 +649,7 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ local nodeSkin: { [number]: number } = {} local skinCache: { [any]: number } = {} - local function buildMesh(geo: Obj, mats: { number }, G: Xform.M4?): (number?, Err.Err?) + local function buildMesh(geo: Obj, mats: { number }, G: Mat4.M4?): (number?, Err.Err?) local g = geo.node local verts = array(g, "Vertices") local pvi = array(g, "PolygonVertexIndex") @@ -784,15 +785,15 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ table.sort(slots) local perCp, skin = skinOf(geo) local shapes = shapesOf(geo) - local N3: Xform.M4? = nil -- normal matrix (inverse transpose of G) + local N3: Mat4.M4? = nil -- normal matrix (inverse transpose of G) if G then - local inv = Xform.inverse(G) + local inv = Mat4.inverse(G) if inv then N3 = { inv[1], inv[5], inv[9], 0, inv[2], inv[6], inv[10], 0, inv[3], inv[7], inv[11], 0, 0, 0, 0, 1 } end end local mesh: Types.Mesh = { name = geo.name, primitives = {} } - local function v3(dst: buffer, o: number, x: number, y: number, z: number, M: Xform.M4?, w: number) + local function v3(dst: buffer, o: number, x: number, y: number, z: number, M: Mat4.M4?, w: number) if M then x, y, z = M[1] * x + M[5] * y + M[9] * z + M[13] * w, M[2] * x + M[6] * y + M[10] * z + M[14] * w, M[3] * x + M[7] * y + M[11] * z + M[15] * w end @@ -1012,9 +1013,9 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ local gt = pvec(o.props, "GeometricTranslation", { 0, 0, 0 }) local gr = pvec(o.props, "GeometricRotation", { 0, 0, 0 }) local gsc = pvec(o.props, "GeometricScaling", { 1, 1, 1 }) - local G: Xform.M4? = nil + local G: Mat4.M4? = nil if gt[1] ~= 0 or gt[2] ~= 0 or gt[3] ~= 0 or gr[1] ~= 0 or gr[2] ~= 0 or gr[3] ~= 0 or gsc[1] ~= 1 or gsc[2] ~= 1 or gsc[3] ~= 1 then - G = Xform.mul(Xform.translate(gt[1], gt[2], gt[3]), Xform.mul(Xform.euler(gr[1], gr[2], gr[3], 0), Xform.scale(gsc[1], gsc[2], gsc[3]))) + G = Mat4.mul(Mat4.translation(gt[1], gt[2], gt[3]), Mat4.mul(Xform.euler(gr[1], gr[2], gr[3], 0), Mat4.scaling(gsc[1], gsc[2], gsc[3]))) end for _, geo in sources(o.id, "Geometry") do if geo.sub == "Mesh" or geo.sub == "" then @@ -1294,7 +1295,7 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ end over[key] = v end - local tt, rr, ss = Xform.decompose(Xform.localMatrix(xprops(o, over))) + local tt, rr, ss = Mat4.decompose(Xform.localMatrix(xprops(o, over))) if prevQ and rr[1] * prevQ[1] + rr[2] * prevQ[2] + rr[3] * prevQ[3] + rr[4] * prevQ[4] < 0 then rr = { -rr[1], -rr[2], -rr[3], -rr[4] } end diff --git a/src/Formats/model/fbx/Write.luau b/src/Formats/model/fbx/Write.luau index 6d16eab..82a4371 100644 --- a/src/Formats/model/fbx/Write.luau +++ b/src/Formats/model/fbx/Write.luau @@ -8,7 +8,7 @@ -- BlendShape / BlendShapeChannel / Shape; animations -> AnimationStack / Layer / CurveNode / Curve. local Err = require("@formats/core/Err") local Types = require("@formats/Types") -local Xform = require("@formats/model/fbx/Xform") +local Mat4 = require("@formats/codecs/model/Mat4") local Write = {} @@ -284,26 +284,26 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?) end end -- world matrices (rest pose) for clusters and the bind pose - local worldM: { [number]: Xform.M4 } = {} + local worldM: { [number]: Mat4.M4 } = {} local visiting: { [number]: boolean } = {} - local function world(i: number): Xform.M4 + local function world(i: number): Mat4.M4 if worldM[i] then return worldM[i] end if visiting[i] then - return Xform.identity() + return Mat4.identity() end visiting[i] = true local nd = nodes[i] - local l = if nd.matrix and #(nd.matrix :: Xform.M4) == 16 then nd.matrix else Xform.compose(nd.translation, nd.rotation, nd.scale) + local l = if nd.matrix and #(nd.matrix :: Mat4.M4) == 16 then nd.matrix else Mat4.compose(nd.translation, nd.rotation, nd.scale) local p = parentOf[i] - local w = if p then Xform.mul(world(p), l) else l + local w = if p then Mat4.mul(world(p), l) else l worldM[i] = w return w end local function trs(nd: Types.Node): ({ number }, { number }, { number }) - if nd.matrix and #(nd.matrix :: Xform.M4) == 16 then - return Xform.decompose(nd.matrix) + if nd.matrix and #(nd.matrix :: Mat4.M4) == 16 then + return Mat4.decompose(nd.matrix) end return nd.translation or { 0, 0, 0 }, nd.rotation or { 0, 0, 0, 1 }, nd.scale or { 1, 1, 1 } end @@ -387,7 +387,7 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?) for i, nd in nodes do if not skip[i] then local t, r, s = trs(nd) - local euler = Xform.eulerXYZ(r) + local euler = Mat4.eulerXYZ(r) local ftype = nd.extras and (nd.extras :: any).fbx and (nd.extras :: any).fbx.type local sub = if nd.mesh then "Mesh" elseif jointSet[i] or ftype == "LimbNode" then "LimbNode" else "Null" -- an orientation child folded into this node gives it its attribute @@ -697,7 +697,7 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?) local poseNodes: { WNode } = {} local posed: { [number]: boolean } = {} - local function pose(mid: number, m: Xform.M4) + local function pose(mid: number, m: Mat4.M4) if posed[mid] then return end @@ -752,14 +752,14 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?) for j, ji in skin.joints do local jm = modelIds[ji] if jm then - local IB = Xform.identity() + local IB = Mat4.identity() if ibm and skin.inverseBindMatrices and j <= skin.inverseBindMatrices.count then for k = 1, 16 do IB[k] = ibm(j - 1, k - 1) end end - local inv = Xform.inverse(IB) or Xform.identity() - local link = Xform.mul(meshWorld, inv) + local inv = Mat4.inverse(IB) or Mat4.identity() + local link = Mat4.mul(meshWorld, inv) local cid = id() add("Deformer", N("Deformer", "LSS", { cid, cls(nodes[ji].name, "SubDeformer"), "Cluster" }, { N("Version", "I", { 100 }), @@ -859,7 +859,7 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?) else q = { 0, 0, 0, 1 } end - v = Xform.eulerXYZ(q) + v = Mat4.eulerXYZ(q) if prev then for a = 1, 3 do while v[a] - prev[a] > 180 do diff --git a/src/Formats/model/fbx/Xform.luau b/src/Formats/model/fbx/Xform.luau index a4d734d..bec2b47 100644 --- a/src/Formats/model/fbx/Xform.luau +++ b/src/Formats/model/fbx/Xform.luau @@ -1,80 +1,15 @@ --!strict -- model/fbx/Xform: the FBX transform model (FBX SDK "Computing transformation matrix"): the local matrix of a Model --- node T * Roff * Rp * Rpre * R * Rpost^-1 * Rp^-1 * Soff * Sp * S * Sp^-1, Euler rotations in degrees in the six --- orders, column-major 4x4 matrices (flat arrays of 16, translation at 13..15 as glTF and FBX store them), inverse, --- TRS decomposition (quaternion x, y, z, w) and Euler XYZ from a quaternion (the writer). +-- node T * Roff * Rp * Rpre * R * Rpost^-1 * Rp^-1 * Soff * Sp * S * Sp^-1, with FBX's numbered Euler orders. The +-- matrix / quaternion arithmetic is codecs/model/Mat4. +local Mat4 = require("@formats/codecs/model/Mat4") + local Xform = {} -export type M4 = { number } - -local rad = math.pi / 180 - -function Xform.identity(): M4 - return { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 } -end - -function Xform.mul(a: M4, b: M4): M4 - local m = table.create(16, 0) - for col = 0, 3 do - for row = 0, 3 do - m[col * 4 + row + 1] = a[row + 1] * b[col * 4 + 1] + a[4 + row + 1] * b[col * 4 + 2] + a[8 + row + 1] * b[col * 4 + 3] + a[12 + row + 1] * b[col * 4 + 4] - end - end - return m -end - -function Xform.translate(x: number, y: number, z: number): M4 - return { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1 } -end - -function Xform.scale(x: number, y: number, z: number): M4 - return { x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1 } -end - -local function rx(a: number): M4 - local c, s = math.cos(a), math.sin(a) - return { 1, 0, 0, 0, 0, c, s, 0, 0, -s, c, 0, 0, 0, 0, 1 } -end -local function ry(a: number): M4 - local c, s = math.cos(a), math.sin(a) - return { c, 0, -s, 0, 0, 1, 0, 0, s, 0, c, 0, 0, 0, 0, 1 } -end -local function rz(a: number): M4 - local c, s = math.cos(a), math.sin(a) - return { c, s, 0, 0, -s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 } -end - -- FBX RotationOrder: 0 XYZ (R = Rz * Ry * Rx: X applied first), 1 XZY, 2 YZX, 3 YXZ, 4 ZXY, 5 ZYX, 6 spheric (= XYZ) local ORDERS = { [0] = "xyz", "xzy", "yzx", "yxz", "zxy", "zyx", "xyz" } -function Xform.euler(x: number, y: number, z: number, order: number?): M4 - local o = ORDERS[order or 0] or "xyz" - local R = { x = rx(x * rad), y = ry(y * rad), z = rz(z * rad) } - local a, b, c = string.sub(o, 1, 1), string.sub(o, 2, 2), string.sub(o, 3, 3) - return Xform.mul(R[c], Xform.mul(R[b], R[a])) -end - --- inverse of an affine matrix (general 3x3 part) | nil when singular -function Xform.inverse(m: M4): M4? - local a, b, c = m[1], m[5], m[9] - local d, e, f = m[2], m[6], m[10] - local g, h, i = m[3], m[7], m[11] - local A, B, C = e * i - f * h, -(d * i - f * g), d * h - e * g - local det = a * A + b * B + c * C - if det == 0 or det ~= det then - return nil - end - local k = 1 / det - local r = { - A * k, B * k, C * k, 0, - -(b * i - c * h) * k, (a * i - c * g) * k, -(a * h - b * g) * k, 0, - (b * f - c * e) * k, -(a * f - c * d) * k, (a * e - b * d) * k, 0, - 0, 0, 0, 1, - } - local tx, ty, tz = m[13], m[14], m[15] - r[13] = -(r[1] * tx + r[5] * ty + r[9] * tz) - r[14] = -(r[2] * tx + r[6] * ty + r[10] * tz) - r[15] = -(r[3] * tx + r[7] * ty + r[11] * tz) - return r +function Xform.euler(x: number, y: number, z: number, order: number?): Mat4.M4 + return Mat4.euler(x, y, z, ORDERS[order or 0] or "xyz") end -- the local matrix of a node from its (already defaulted) FBX properties p: vectors of 3 numbers @@ -86,113 +21,20 @@ export type Props = { local function isZero(v: { number }): boolean return v[1] == 0 and v[2] == 0 and v[3] == 0 end -function Xform.localMatrix(p: Props): M4 - local m = Xform.translate(p.T[1] + p.Roff[1] + p.Rp[1], p.T[2] + p.Roff[2] + p.Rp[2], p.T[3] + p.Roff[3] + p.Rp[3]) +function Xform.localMatrix(p: Props): Mat4.M4 + local m = Mat4.translation(p.T[1] + p.Roff[1] + p.Rp[1], p.T[2] + p.Roff[2] + p.Rp[2], p.T[3] + p.Roff[3] + p.Rp[3]) if not isZero(p.Rpre) then - m = Xform.mul(m, Xform.euler(p.Rpre[1], p.Rpre[2], p.Rpre[3], 0)) + m = Mat4.mul(m, Xform.euler(p.Rpre[1], p.Rpre[2], p.Rpre[3], 0)) end - m = Xform.mul(m, Xform.euler(p.R[1], p.R[2], p.R[3], p.order)) + m = Mat4.mul(m, Xform.euler(p.R[1], p.R[2], p.R[3], p.order)) if not isZero(p.Rpost) then - local post = Xform.euler(p.Rpost[1], p.Rpost[2], p.Rpost[3], 0) -- the inverse of a rotation is its transpose - local tr = { post[1], post[5], post[9], 0, post[2], post[6], post[10], 0, post[3], post[7], post[11], 0, 0, 0, 0, 1 } - m = Xform.mul(m, tr) + m = Mat4.mul(m, Mat4.transpose3(Xform.euler(p.Rpost[1], p.Rpost[2], p.Rpost[3], 0))) end - m = Xform.mul(m, Xform.translate(-p.Rp[1] + p.Soff[1] + p.Sp[1], -p.Rp[2] + p.Soff[2] + p.Sp[2], -p.Rp[3] + p.Soff[3] + p.Sp[3])) - m = Xform.mul(m, Xform.scale(p.S[1], p.S[2], p.S[3])) + m = Mat4.mul(m, Mat4.translation(-p.Rp[1] + p.Soff[1] + p.Sp[1], -p.Rp[2] + p.Soff[2] + p.Sp[2], -p.Rp[3] + p.Soff[3] + p.Sp[3])) + m = Mat4.mul(m, Mat4.scaling(p.S[1], p.S[2], p.S[3])) if not isZero(p.Sp) then - m = Xform.mul(m, Xform.translate(-p.Sp[1], -p.Sp[2], -p.Sp[3])) - end - return m -end - --- quaternion (x, y, z, w) of a pure rotation matrix -local function quat(m: M4): { number } - local m00, m01, m02 = m[1], m[5], m[9] - local m10, m11, m12 = m[2], m[6], m[10] - local m20, m21, m22 = m[3], m[7], m[11] - local tr = m00 + m11 + m22 - local x, y, z, w - if tr > 0 then - local s = math.sqrt(tr + 1) * 2 - w, x, y, z = s / 4, (m21 - m12) / s, (m02 - m20) / s, (m10 - m01) / s - elseif m00 > m11 and m00 > m22 then - local s = math.sqrt(math.max(1 + m00 - m11 - m22, 1e-30)) * 2 - w, x, y, z = (m21 - m12) / s, s / 4, (m01 + m10) / s, (m02 + m20) / s - elseif m11 > m22 then - local s = math.sqrt(math.max(1 + m11 - m00 - m22, 1e-30)) * 2 - w, x, y, z = (m02 - m20) / s, (m01 + m10) / s, s / 4, (m12 + m21) / s - else - local s = math.sqrt(math.max(1 + m22 - m00 - m11, 1e-30)) * 2 - w, x, y, z = (m10 - m01) / s, (m02 + m20) / s, (m12 + m21) / s, s / 4 - end - local n = math.sqrt(x * x + y * y + z * z + w * w) - if n == 0 or n ~= n then - return { 0, 0, 0, 1 } - end - return { x / n, y / n, z / n, w / n } -end -Xform.quat = quat - --- decompose(m) -> translation, rotation (quaternion), scale (a negative determinant flips the x scale) -function Xform.decompose(m: M4): ({ number }, { number }, { number }) - local t = { m[13], m[14], m[15] } - local sx = math.sqrt(m[1] * m[1] + m[2] * m[2] + m[3] * m[3]) - local sy = math.sqrt(m[5] * m[5] + m[6] * m[6] + m[7] * m[7]) - local sz = math.sqrt(m[9] * m[9] + m[10] * m[10] + m[11] * m[11]) - local det = m[1] * (m[6] * m[11] - m[10] * m[7]) - m[5] * (m[2] * m[11] - m[10] * m[3]) + m[9] * (m[2] * m[7] - m[6] * m[3]) - if det < 0 then - sx = -sx - end - local ix = if sx ~= 0 then 1 / sx else 0 - local iy = if sy ~= 0 then 1 / sy else 0 - local iz = if sz ~= 0 then 1 / sz else 0 - local r = { m[1] * ix, m[2] * ix, m[3] * ix, 0, m[5] * iy, m[6] * iy, m[7] * iy, 0, m[9] * iz, m[10] * iz, m[11] * iz, 0, 0, 0, 0, 1 } - return t, quat(r), { sx, sy, sz } -end - --- the rotation matrix of a quaternion -function Xform.fromQuat(q: { number }): M4 - local x, y, z, w = q[1], q[2], q[3], q[4] - local xx, yy, zz, xy, xz, yz, wx, wy, wz = x * x, y * y, z * z, x * y, x * z, y * z, w * x, w * y, w * z - return { - 1 - 2 * (yy + zz), 2 * (xy + wz), 2 * (xz - wy), 0, - 2 * (xy - wz), 1 - 2 * (xx + zz), 2 * (yz + wx), 0, - 2 * (xz + wy), 2 * (yz - wx), 1 - 2 * (xx + yy), 0, - 0, 0, 0, 1, - } -end - --- Euler XYZ degrees (R = Rz * Ry * Rx) of a quaternion -function Xform.eulerXYZ(q: { number }): { number } - local m = Xform.fromQuat(q) - -- m[3] = r20 = -sin(y) - local sy = -m[3] - sy = math.clamp(sy, -1, 1) - local y = math.asin(sy) - local x, z - if math.abs(sy) < 0.9999999 then - x = math.atan2(m[7], m[11]) - z = math.atan2(m[2], m[1]) - else - x = math.atan2(-m[10], m[6]) - z = 0 - end - return { x / rad, y / rad, z / rad } -end - --- TRS -> matrix (glTF semantics) -function Xform.compose(t: { number }?, r: { number }?, s: { number }?): M4 - local m = if r then Xform.fromQuat(r) else Xform.identity() - if s then - for k = 0, 2 do - m[k * 4 + 1] *= s[k + 1] - m[k * 4 + 2] *= s[k + 1] - m[k * 4 + 3] *= s[k + 1] - end - end - if t then - m[13], m[14], m[15] = t[1], t[2], t[3] + m = Mat4.mul(m, Mat4.translation(-p.Sp[1], -p.Sp[2], -p.Sp[3])) end return m end diff --git a/src/Formats/model/fbx/init.luau b/src/Formats/model/fbx/init.luau index bf8bfcf..0f615d5 100644 --- a/src/Formats/model/fbx/init.luau +++ b/src/Formats/model/fbx/init.luau @@ -1,6 +1,6 @@ --!strict -- model/fbx: Autodesk FBX 7.x, binary (7.0 - 7.7: 32-bit records before 7500, 64-bit after; zlib-compressed arrays --- through codecs/Deflate) and ASCII. New code, from the format as reverse engineered by Blender's io_scene_fbx and +-- through codecs/compress/Deflate) and ASCII. New code, from the format as reverse engineered by Blender's io_scene_fbx and -- assimp's FBX importer, and the FBX SDK's documentation of the transform model. -- Reads: the node tree (Fbx.tree), then Objects / Connections -> Scene: Model nodes with the full transform (Lcl -- T / R / S, pre / post rotation, rotation / scaling pivots and offsets, the six rotation orders; geometric transforms @@ -35,7 +35,7 @@ local Fbx = { category = "model", extensions = { "fbx" }, mime = { "application/vnd.autodesk.fbx", "model/fbx" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Deflate", "core/Base64" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Deflate", "core/Base64", "codecs/model/Mat4" }, caps = { decode = true, encode = true, binary = true, ascii = true, materials = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true, polygons = true }, } diff --git a/src/Formats/model/gltf/init.luau b/src/Formats/model/gltf/init.luau index bf14547..8af711c 100644 --- a/src/Formats/model/gltf/init.luau +++ b/src/Formats/model/gltf/init.luau @@ -20,7 +20,7 @@ local Err = require("@formats/core/Err") local Sniff = require("@formats/core/Sniff") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") -local Json = require("@formats/codecs/Json") +local Json = require("@formats/codecs/text/Json") local Base64 = require("@formats/core/Base64") local Read = require("@formats/model/gltf/Read") local Write = require("@formats/model/gltf/Write") @@ -31,7 +31,7 @@ local Gltf = { category = "model", extensions = { "gltf", "glb" }, mime = { "model/gltf+json", "model/gltf-binary" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Json", "core/Base64", "core/Sniff" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Json", "core/Base64", "core/Sniff" }, caps = { decode = true, encode = true, binary = true, materials = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true }, } diff --git a/src/Formats/model/off/init.luau b/src/Formats/model/off/init.luau index 4c3ab8c..1d2c5ba 100644 --- a/src/Formats/model/off/init.luau +++ b/src/Formats/model/off/init.luau @@ -21,7 +21,7 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") -local Flatten = require("@formats/codecs/MeshFlatten") +local Flatten = require("@formats/codecs/model/MeshFlatten") -- ------------------------------------------------------------------------------------------------ contract local Off = { @@ -29,7 +29,7 @@ local Off = { category = "model", extensions = { "off" }, mime = { "model/off", "text/plain" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/MeshFlatten" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/MeshFlatten" }, caps = { decode = true, encode = true, polygons = true, points = true, colors = true, binary = false }, } diff --git a/src/Formats/model/ply/init.luau b/src/Formats/model/ply/init.luau index 69ea451..8e118f7 100644 --- a/src/Formats/model/ply/init.luau +++ b/src/Formats/model/ply/init.luau @@ -25,7 +25,7 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") local Binary = require("@formats/model/ply/Binary") -local Flatten = require("@formats/codecs/MeshFlatten") +local Flatten = require("@formats/codecs/model/MeshFlatten") -- ------------------------------------------------------------------------------------------------ contract local Ply = { @@ -33,7 +33,7 @@ local Ply = { category = "model", extensions = { "ply" }, mime = { "model/ply", "application/ply" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/MeshFlatten" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/MeshFlatten" }, caps = { decode = true, encode = true, ascii = true, binary = true, polygons = true, points = true, colors = true }, } diff --git a/src/Formats/model/stl/init.luau b/src/Formats/model/stl/init.luau index 06147a5..5878daf 100644 --- a/src/Formats/model/stl/init.luau +++ b/src/Formats/model/stl/init.luau @@ -21,7 +21,7 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") local Decode = require("@formats/model/stl/Decode") -local Flatten = require("@formats/codecs/MeshFlatten") +local Flatten = require("@formats/codecs/model/MeshFlatten") -- ------------------------------------------------------------------------------------------------ contract local Stl = { @@ -29,7 +29,7 @@ local Stl = { category = "model", extensions = { "stl" }, mime = { "model/stl", "application/sla" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/MeshFlatten" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/MeshFlatten" }, caps = { decode = true, encode = true, ascii = true, binary = true, colors = true, indexed = false }, } diff --git a/src/Formats/model/usda/Build.luau b/src/Formats/model/usda/Build.luau index 5e4be9f..2d554bd 100644 --- a/src/Formats/model/usda/Build.luau +++ b/src/Formats/model/usda/Build.luau @@ -18,6 +18,7 @@ -- Not supported: composition arcs (references, payloads, inherits, specializes, subLayers: listed in -- meta.source.unsupported), UsdSkel, blend shapes, BasisCurves / Points / NURBS, instancing, MaterialX networks. local Types = require("@formats/Types") +local Mat4 = require("@formats/codecs/model/Mat4") local Parse = require("@formats/model/usda/Parse") local Build = {} @@ -149,95 +150,13 @@ end -- ------------------------------------------------------------------------------------------------ matrices -- column-major 4x4 (glTF layout = USD's row-major row-vector text order) local mul = Types.Scene.mul -local function translateM(x: number, y: number, z: number): { number } - return { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1 } -end -local function scaleM(x: number, y: number, z: number): { number } - return { x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1 } -end -local function rotM(axis: number, deg: number): { number } - local c, s = math.cos(deg * DEG), math.sin(deg * DEG) - if axis == 1 then - return { 1, 0, 0, 0, 0, c, s, 0, 0, -s, c, 0, 0, 0, 0, 1 } - elseif axis == 2 then - return { c, 0, -s, 0, 0, 1, 0, 0, s, 0, c, 0, 0, 0, 0, 1 } - end - return { c, s, 0, 0, -s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 } -end local function quatM(x: number, y: number, z: number, w: number): { number } local l = math.sqrt(x * x + y * y + z * z + w * w) if l > 0 then x, y, z, w = x / l, y / l, z / l, w / l end - return Types.Scene.nodeMatrix({ children = {}, rotation = { x, y, z, w } }) + return Mat4.fromQuat({ x, y, z, w }) end -local function inverse(m: { number }): { number }? - local a = m - local inv = table.create(16, 0) - inv[1] = a[6] * a[11] * a[16] - a[6] * a[12] * a[15] - a[10] * a[7] * a[16] + a[10] * a[8] * a[15] + a[14] * a[7] * a[12] - a[14] * a[8] * a[11] - inv[5] = -a[5] * a[11] * a[16] + a[5] * a[12] * a[15] + a[9] * a[7] * a[16] - a[9] * a[8] * a[15] - a[13] * a[7] * a[12] + a[13] * a[8] * a[11] - inv[9] = a[5] * a[10] * a[16] - a[5] * a[12] * a[14] - a[9] * a[6] * a[16] + a[9] * a[8] * a[14] + a[13] * a[6] * a[12] - a[13] * a[8] * a[10] - inv[13] = -a[5] * a[10] * a[15] + a[5] * a[11] * a[14] + a[9] * a[6] * a[15] - a[9] * a[7] * a[14] - a[13] * a[6] * a[11] + a[13] * a[7] * a[10] - inv[2] = -a[2] * a[11] * a[16] + a[2] * a[12] * a[15] + a[10] * a[3] * a[16] - a[10] * a[4] * a[15] - a[14] * a[3] * a[12] + a[14] * a[4] * a[11] - inv[6] = a[1] * a[11] * a[16] - a[1] * a[12] * a[15] - a[9] * a[3] * a[16] + a[9] * a[4] * a[15] + a[13] * a[3] * a[12] - a[13] * a[4] * a[11] - inv[10] = -a[1] * a[10] * a[16] + a[1] * a[12] * a[14] + a[9] * a[2] * a[16] - a[9] * a[4] * a[14] - a[13] * a[2] * a[12] + a[13] * a[4] * a[10] - inv[14] = a[1] * a[10] * a[15] - a[1] * a[11] * a[14] - a[9] * a[2] * a[15] + a[9] * a[3] * a[14] + a[13] * a[2] * a[11] - a[13] * a[3] * a[10] - inv[3] = a[2] * a[7] * a[16] - a[2] * a[8] * a[15] - a[6] * a[3] * a[16] + a[6] * a[4] * a[15] + a[14] * a[3] * a[8] - a[14] * a[4] * a[7] - inv[7] = -a[1] * a[7] * a[16] + a[1] * a[8] * a[15] + a[5] * a[3] * a[16] - a[5] * a[4] * a[15] - a[13] * a[3] * a[8] + a[13] * a[4] * a[7] - inv[11] = a[1] * a[6] * a[16] - a[1] * a[8] * a[14] - a[5] * a[2] * a[16] + a[5] * a[4] * a[14] + a[13] * a[2] * a[8] - a[13] * a[4] * a[6] - inv[15] = -a[1] * a[6] * a[15] + a[1] * a[7] * a[14] + a[5] * a[2] * a[15] - a[5] * a[3] * a[14] - a[13] * a[2] * a[7] + a[13] * a[3] * a[6] - inv[4] = -a[2] * a[7] * a[12] + a[2] * a[8] * a[11] + a[6] * a[3] * a[12] - a[6] * a[4] * a[11] - a[10] * a[3] * a[8] + a[10] * a[4] * a[7] - inv[8] = a[1] * a[7] * a[12] - a[1] * a[8] * a[11] - a[5] * a[3] * a[12] + a[5] * a[4] * a[11] + a[9] * a[3] * a[8] - a[9] * a[4] * a[7] - inv[12] = -a[1] * a[6] * a[12] + a[1] * a[8] * a[10] + a[5] * a[2] * a[12] - a[5] * a[4] * a[10] - a[9] * a[2] * a[8] + a[9] * a[4] * a[6] - inv[16] = a[1] * a[6] * a[11] - a[1] * a[7] * a[10] - a[5] * a[2] * a[11] + a[5] * a[3] * a[10] + a[9] * a[2] * a[7] - a[9] * a[3] * a[6] - local det = a[1] * inv[1] + a[2] * inv[5] + a[3] * inv[9] + a[4] * inv[13] - if det == 0 or det ~= det then - return nil - end - for k = 1, 16 do - inv[k] /= det - end - return inv -end -Build.inverse = inverse - --- decompose(m) -> translation, rotation (quaternion x y z w), scale (no shear) -local function decompose(m: { number }): ({ number }, { number }, { number }) - local sx = math.sqrt(m[1] * m[1] + m[2] * m[2] + m[3] * m[3]) - local sy = math.sqrt(m[5] * m[5] + m[6] * m[6] + m[7] * m[7]) - local sz = math.sqrt(m[9] * m[9] + m[10] * m[10] + m[11] * m[11]) - local det = m[1] * (m[6] * m[11] - m[7] * m[10]) - m[5] * (m[2] * m[11] - m[3] * m[10]) + m[9] * (m[2] * m[7] - m[3] * m[6]) - if det < 0 then - sx = -sx - end - local function d(v: number, s: number): number - return if s ~= 0 then v / s else 0 - end - local r00, r10, r20 = d(m[1], sx), d(m[2], sx), d(m[3], sx) - local r01, r11, r21 = d(m[5], sy), d(m[6], sy), d(m[7], sy) - local r02, r12, r22 = d(m[9], sz), d(m[10], sz), d(m[11], sz) - local x, y, z, w - local tr = r00 + r11 + r22 - if tr > 0 then - local s = math.sqrt(tr + 1) * 2 - w, x, y, z = 0.25 * s, (r21 - r12) / s, (r02 - r20) / s, (r10 - r01) / s - elseif r00 > r11 and r00 > r22 then - local s = math.sqrt(1 + r00 - r11 - r22) * 2 - w, x, y, z = (r21 - r12) / s, 0.25 * s, (r01 + r10) / s, (r02 + r20) / s - elseif r11 > r22 then - local s = math.sqrt(1 + r11 - r00 - r22) * 2 - w, x, y, z = (r02 - r20) / s, (r01 + r10) / s, 0.25 * s, (r12 + r21) / s - else - local s = math.sqrt(1 + r22 - r00 - r11) * 2 - w, x, y, z = (r10 - r01) / s, (r02 + r20) / s, (r12 + r21) / s, 0.25 * s - end - local l = math.sqrt(x * x + y * y + z * z + w * w) - if l > 0 then - x, y, z, w = x / l, y / l, z / l, w / l - end - return { m[13], m[14], m[15] }, { x, y, z, w }, { sx, sy, sz } -end -Build.decompose = decompose -- ------------------------------------------------------------------------------------------------ xform ops type Op = { kind: string, axes: string?, prop: Prop, invert: boolean } @@ -283,10 +202,10 @@ local function opMatrix(op: Op, v: any): { number }? local m: { number }? local k = op.kind if k == "translate" then - m = translateM(n[1] or 0, n[2] or 0, n[3] or 0) + m = Mat4.translation(n[1] or 0, n[2] or 0, n[3] or 0) elseif k == "scale" then local s1 = n[1] or 1 - m = scaleM(s1, n[2] or s1, n[3] or s1) + m = Mat4.scaling(s1, n[2] or s1, n[3] or s1) elseif k == "orient" then -- USD quaternions are written (real, i, j, k) m = quatM(n[2] or 0, n[3] or 0, n[4] or 0, n[1] or 1) @@ -302,14 +221,14 @@ local function opMatrix(op: Op, v: any): { number }? for c = 1, #axes do local a = AXIS[string.sub(axes, c, c)] local angle = if #axes == 1 then n[1] or 0 else n[a] or 0 - r = mul(rotM(a, angle), r) + r = mul(Mat4.rotation(a, angle), r) end m = r else return nil end if op.invert and m then - m = inverse(m) + m = Mat4.inverseFull(m) end return m end @@ -1253,7 +1172,7 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) local sc = Types.Scene.accessor(nil, "f32", 3, count) local prev: { number }? = nil for k = 1, count do - local T, R, S = decompose(localMatrix(ops, times[k])) + local T, R, S = Mat4.decompose(localMatrix(ops, times[k])) if prev and prev[1] * R[1] + prev[2] * R[2] + prev[3] * R[3] + prev[4] * R[4] < 0 then R = { -R[1], -R[2], -R[3], -R[4] } end @@ -1270,7 +1189,7 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) table.insert(animation.channels, { node = ni, path = "translation", input = tin, output = tr, interpolation = "LINEAR" } :: Types.Channel) table.insert(animation.channels, { node = ni, path = "rotation", input = tin, output = ro, interpolation = "LINEAR" } :: Types.Channel) table.insert(animation.channels, { node = ni, path = "scale", input = tin, output = sc, interpolation = "LINEAR" } :: Types.Channel) - local T, R, S = decompose(localMatrix(ops, times[1])) + local T, R, S = Mat4.decompose(localMatrix(ops, times[1])) n.translation, n.rotation, n.scale = T, R, S elseif #ops > 0 then -- static: TRS when the stack is translate / rotate / scale in that order, else the matrix @@ -1285,7 +1204,7 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) end local m = localMatrix(ops, nil) if simple then - local T, R, S = decompose(m) + local T, R, S = Mat4.decompose(m) local tx = ops[1].kind == "translate" if tx then n.translation = T diff --git a/src/Formats/model/usda/init.luau b/src/Formats/model/usda/init.luau index 3e52979..04439f7 100644 --- a/src/Formats/model/usda/init.luau +++ b/src/Formats/model/usda/init.luau @@ -31,7 +31,7 @@ local Usda = { category = "model", extensions = { "usda", "usd", "usdz" }, mime = { "model/vnd.usda", "model/vnd.usdz+zip" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Zip" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Zip", "codecs/model/Mat4" }, caps = { decode = true, encode = true, materials = true, animation = true, cameras = true, lights = true, polygons = true, vertexColors = true, usdz = "read", usdc = false }, } diff --git a/src/Formats/music/it/init.luau b/src/Formats/music/it/init.luau index d73cec0..0782816 100644 --- a/src/Formats/music/it/init.luau +++ b/src/Formats/music/it/init.luau @@ -1,6 +1,6 @@ --!strict -- music/it: Impulse Tracker modules (IMPM, ITTECH.TXT; also files from OpenMPT / Schism Tracker). Reads into the --- codecs/Tracker Module and plays through its engine (Module:render() / open() -> an audio Decoder). Supports: up to +-- codecs/audio/Tracker Module and plays through its engine (Module:render() / open() -> an audio Decoder). Supports: up to -- 64 channels, instrument and sample mode, new and old (pre-2.0) instrument headers, volume / panning / pitch (or -- filter) envelopes with loops and sustain loops, new note actions and duplicate checks, pitch-pan separation, -- resonant filters (instrument cutoff / resonance, default Zxx macros), 8 / 16-bit signed or unsigned mono / stereo @@ -12,7 +12,7 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") -local Tracker = require("@formats/codecs/Tracker") +local Tracker = require("@formats/codecs/audio/Tracker") local Itsex = require("@formats/music/it/Itsex") -- ------------------------------------------------------------------------------------------------ contract @@ -21,7 +21,7 @@ local It = { category = "music", extensions = { "it" }, mime = { "audio/it", "audio/x-it" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Tracker" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" }, caps = { decode = true, encode = false, render = true, channels = { 1, 64 }, compressedSamples = true }, } diff --git a/src/Formats/music/midi/Render.luau b/src/Formats/music/midi/Render.luau index a40aa56..9b4e1e5 100644 --- a/src/Formats/music/midi/Render.luau +++ b/src/Formats/music/midi/Render.luau @@ -1,11 +1,11 @@ --!strict -- music/midi/Render: the tempo map (ticks -> seconds, as python mido computes lengths), the time-ordered event list, --- and the audio Decoder that plays a Midi through codecs/SoundFont's synth (a SoundFont bank, or the built-in +-- and the audio Decoder that plays a Midi through codecs/audio/SoundFont's synth (a SoundFont bank, or the built-in -- waveform set). Format 0 / 1: one tempo map from every track's tempo events, tracks merged (ties keep track order). -- Format 2: each track is its own song with its own tempo map, played one after another. local Err = require("@formats/core/Err") local Types = require("@formats/Types") -local SoundFont = require("@formats/codecs/SoundFont") +local SoundFont = require("@formats/codecs/audio/SoundFont") local Synth = SoundFont.Synth @@ -162,7 +162,7 @@ end export type RenderOptions = { sampleRate: number?, -- default 44100 - soundfont: any?, -- a SoundFont (music/sf2 decode, codecs/SoundFont.parse) or SF2 bytes (buffer / string); default the built-in waveforms + soundfont: any?, -- a SoundFont (music/sf2 decode, codecs/audio/SoundFont.parse) or SF2 bytes (buffer / string); default the built-in waveforms gain: number?, -- linear output gain, default 0.5 tail: number?, -- seconds rendered after the last event (release tails), default 1 maxVoices: number?, -- default 256 diff --git a/src/Formats/music/midi/init.luau b/src/Formats/music/midi/init.luau index fcaeb46..ac60034 100644 --- a/src/Formats/music/midi/init.luau +++ b/src/Formats/music/midi/init.luau @@ -1,6 +1,6 @@ --!strict -- music/midi: Standard MIDI Files (SMF 1.0: formats 0, 1 and 2; PPQ and SMPTE time; RIFF RMID read). Written from the --- specification (no third-party code); rendering goes through codecs/SoundFont (a TinySoundFont port). +-- specification (no third-party code); rendering goes through codecs/audio/SoundFont (a TinySoundFont port). -- Supports: decode to a Types.Midi (absolute ticks; channel events noteOff / noteOn / aftertouch / controller / -- program / channelPressure / pitchBend with their raw data bytes, sysex / escape with the bytes after the length, -- meta events with meta = the meta type; meta.tempos / timeSignatures / keySignatures, track names), encode (running @@ -21,7 +21,7 @@ local Midi = { category = "music", extensions = { "mid", "midi", "smf", "kar", "rmi" }, mime = { "audio/midi", "audio/x-midi" }, - deps = { "core/Err", "core/Bytes", "codecs/SoundFont", "Types" }, + deps = { "core/Err", "core/Bytes", "codecs/audio/SoundFont", "Types" }, caps = { decode = true, encode = true, formats = { 0, 1, 2 }, render = true, streaming = true, rmid = true }, } diff --git a/src/Formats/music/mod/init.luau b/src/Formats/music/mod/init.luau index 7f4eb88..6b97843 100644 --- a/src/Formats/music/mod/init.luau +++ b/src/Formats/music/mod/init.luau @@ -1,7 +1,7 @@ --!strict -- music/mod: ProTracker / NoiseTracker / StarTrekker MOD modules (the 31-sample "M.K." family: M.K., M!K!, FLT4, -- 4CHN .. 9CHN, 10CH .. 32CH, xxCN, CD81, OKTA / OCTA, TDZx; 15-sample Soundtracker files when asked for by name or --- extension). Written from the ProTracker 2.3 documentation. Reads into the codecs/Tracker Module and plays through +-- extension). Written from the ProTracker 2.3 documentation. Reads into the codecs/audio/Tracker Module and plays through -- its engine (Module:render() / open() -> an audio Decoder). Writes 31-sample MODs (M.K. / xCHN / xxCH) from "mod" -- modules, and from XM modules that fit (one sample per instrument, effects 0..F, 64-row patterns). -- Not supported: FLT8's split 4 + 4 channel patterns (read as 8 plain channels), the Amiga hardware low-pass filter @@ -11,7 +11,7 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") -local Tracker = require("@formats/codecs/Tracker") +local Tracker = require("@formats/codecs/audio/Tracker") -- ------------------------------------------------------------------------------------------------ contract local Mod = { @@ -19,7 +19,7 @@ local Mod = { category = "music", extensions = { "mod", "m15", "stk", "nst" }, mime = { "audio/x-mod", "audio/mod" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Tracker" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" }, caps = { decode = true, encode = true, render = true, channels = { 1, 32 } }, } diff --git a/src/Formats/music/s3m/init.luau b/src/Formats/music/s3m/init.luau index dd27e0e..a8ff4f5 100644 --- a/src/Formats/music/s3m/init.luau +++ b/src/Formats/music/s3m/init.luau @@ -1,6 +1,6 @@ --!strict -- music/s3m: Scream Tracker 3 modules (SCRM, ST3 TECH.DOC; also files from Impulse Tracker / OpenMPT / Schism --- Tracker). Reads into the codecs/Tracker Module and plays through its engine (Module:render() / open() -> an audio +-- Tracker). Reads into the codecs/audio/Tracker Module and plays through its engine (Module:render() / open() -> an audio -- Decoder). Supports: up to 32 PCM channels, 8 / 16-bit signed or unsigned, mono or stereo samples, loops, the panning -- table, ST3.00 fast volume slides, every ST3 effect. Notes are stored one octave up (S3M C-4 = note 61 = the C5 -- speed reference, as IT shows S3M files). @@ -10,7 +10,7 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") -local Tracker = require("@formats/codecs/Tracker") +local Tracker = require("@formats/codecs/audio/Tracker") -- ------------------------------------------------------------------------------------------------ contract local S3m = { @@ -18,7 +18,7 @@ local S3m = { category = "music", extensions = { "s3m" }, mime = { "audio/s3m", "audio/x-s3m" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Tracker" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" }, caps = { decode = true, encode = false, render = true, channels = { 1, 32 } }, } diff --git a/src/Formats/music/sf2/init.luau b/src/Formats/music/sf2/init.luau index a7fcc20..b03c84f 100644 --- a/src/Formats/music/sf2/init.luau +++ b/src/Formats/music/sf2/init.luau @@ -1,5 +1,5 @@ --!strict --- music/sf2: SoundFont 2 banks (SoundFont 2.04 specification), read-only. A thin wrapper over codecs/SoundFont (the +-- music/sf2: SoundFont 2 banks (SoundFont 2.04 specification), read-only. A thin wrapper over codecs/audio/SoundFont (the -- parser and the TinySoundFont-port synth music/midi renders with). Supports: INFO, 16-bit samples (+ sm24 24-bit), -- presets / instruments / sample headers with global zones, generator merging into playable regions. -- Not supported: writing, SF3 (Ogg Vorbis samples), modulators (read past, not applied). @@ -8,7 +8,7 @@ -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") -local SoundFont = require("@formats/codecs/SoundFont") +local SoundFont = require("@formats/codecs/audio/SoundFont") -- ------------------------------------------------------------------------------------------------ contract local Sf2 = { @@ -16,7 +16,7 @@ local Sf2 = { category = "music", extensions = { "sf2" }, mime = { "audio/x-soundfont" }, - deps = { "core/Err", "core/Bytes", "codecs/SoundFont" }, + deps = { "core/Err", "core/Bytes", "codecs/audio/SoundFont" }, caps = { decode = true, encode = false, sm24 = true, sf3 = false }, } @@ -37,7 +37,7 @@ function Sf2.decode(r: Bytes.Reader, opts: DecodeOptions?): (SoundFont.SoundFont end -- ------------------------------------------------------------------------------------------------ extras --- synth(sf?, sampleRate?, opts?) -> a synth State (codecs/SoundFont.Synth drives it) +-- synth(sf?, sampleRate?, opts?) -> a synth State (codecs/audio/SoundFont.Synth drives it) Sf2.synth = SoundFont.synth Sf2.fallback = SoundFont.fallback diff --git a/src/Formats/music/xm/init.luau b/src/Formats/music/xm/init.luau index ceddd5a..080795c 100644 --- a/src/Formats/music/xm/init.luau +++ b/src/Formats/music/xm/init.luau @@ -1,6 +1,6 @@ --!strict -- music/xm: FastTracker 2 Extended Modules (XM 1.04, the "Extended Module: " format; also OpenMPT / MilkyTracker / --- Skale files). Written from the XM specification and FT2 behaviour notes. Reads into the codecs/Tracker Module and +-- Skale files). Written from the XM specification and FT2 behaviour notes. Reads into the codecs/audio/Tracker Module and -- plays through its engine (Module:render() / open() -> an audio Decoder): up to 32 channels (more are read), 8 / 16-bit -- delta samples, multi-sample instruments with volume / panning envelopes, fadeout and auto-vibrato, linear and Amiga -- frequency tables, every FT2 effect and volume-column command. Writes XM from "xm" modules (byte-identical for files @@ -11,7 +11,7 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") -local Tracker = require("@formats/codecs/Tracker") +local Tracker = require("@formats/codecs/audio/Tracker") -- ------------------------------------------------------------------------------------------------ contract local Xm = { @@ -19,7 +19,7 @@ local Xm = { category = "music", extensions = { "xm" }, mime = { "audio/xm", "audio/x-xm" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Tracker" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" }, caps = { decode = true, encode = true, render = true, channels = { 1, 64 } }, } diff --git a/src/Formats/ops/AudioOps.luau b/src/Formats/ops/AudioOps.luau index b1803e6..c0e473e 100644 --- a/src/Formats/ops/AudioOps.luau +++ b/src/Formats/ops/AudioOps.luau @@ -1,7 +1,7 @@ --!strict -- ops/AudioOps: editing on the standard Audio (layer 5.5: core, Types and codecs only): a Decoder collected into an -- Audio, gain (linear or dB), normalize, mix, channel remixing (downmix / upmix with the usual WAVE-layout matrices), --- resampling (codecs/Resample), trim, concat, fades, peak / RMS. New code. +-- resampling (codecs/audio/Resample), trim, concat, fades, peak / RMS. New code. -- -- local AudioOps = require("@formats/ops/AudioOps") -- F.ops.audio in the api -- local a = AudioOps.toAudio(F.audio.open(src)) -- an Audio from an Audio or a streaming Decoder @@ -20,8 +20,8 @@ -- copied from the (first) input. local Err = require("@formats/core/Err") local Types = require("@formats/Types") -local Pcm = require("@formats/codecs/Pcm") -local Resample = require("@formats/codecs/Resample") +local Pcm = require("@formats/codecs/audio/Pcm") +local Resample = require("@formats/codecs/audio/Resample") local AudioOps = {} @@ -362,7 +362,7 @@ function AudioOps.upmix(a: Types.Audio, channels: number): (Types.Audio?, Err.Er end -- ------------------------------------------------------------------------------------------------ time --- resample(a, rate, opts?) -> Audio at the new rate (codecs/Resample: opts.quality "low" | "medium" | "high") +-- resample(a, rate, opts?) -> Audio at the new rate (codecs/audio/Resample: opts.quality "low" | "medium" | "high") function AudioOps.resample(a: Types.Audio, rate: number, opts: Resample.Options?): (Types.Audio?, Err.Err?) if not isAudio(a) then return bad("resample: expected an Audio") diff --git a/src/Formats/ops/LayerOps.luau b/src/Formats/ops/LayerOps.luau index bf4b242..97400c7 100644 --- a/src/Formats/ops/LayerOps.luau +++ b/src/Formats/ops/LayerOps.luau @@ -1,6 +1,6 @@ --!strict -- ops/LayerOps: editing on the Layered type (PSD, Aseprite): flatten a layer tree (or one animation frame) to an --- rgba8 Image with the blend modes of codecs/Blend, opacity, groups (isolated, or pass-through), clipping layers and +-- rgba8 Image with the blend modes of codecs/image/Blend, opacity, groups (isolated, or pass-through), clipping layers and -- grey layer masks; every frame as an animated Image; walking the leaves. -- -- local LayerOps = require("@formats/ops/LayerOps") @@ -12,7 +12,7 @@ -- Never throws: bad values return nil, Err.ARG. local Err = require("@formats/core/Err") local Types = require("@formats/Types") -local Blend = require("@formats/codecs/Blend") +local Blend = require("@formats/codecs/image/Blend") local LayerOps = {} diff --git a/src/Formats/playlist/m3u/init.luau b/src/Formats/playlist/m3u/init.luau index 4e3acb4..5e32d81 100644 --- a/src/Formats/playlist/m3u/init.luau +++ b/src/Formats/playlist/m3u/init.luau @@ -4,7 +4,7 @@ -- location lists, a BOM, CRLF / CR, Windows-1252 text; HLS master playlists (variants with BANDWIDTH / CODECS / -- attributes, EXT-X-MEDIA renditions) and media playlists (segments, durations, byte ranges, target duration, media -- sequence, end list, encryption, the segment format). Locations resolve against opts.baseUrl (RFC 3986, --- codecs/Url); Windows / UNC paths stay as they are and are flagged unplayable, as are relative paths without a base +-- codecs/text/Url); Windows / UNC paths stay as they are and are flagged unplayable, as are relative paths without a base -- and non-HTTP schemes (mp3 HLS segments are playable; .ts / .aac / fMP4 are flagged). Encode: M3U8 (#EXTM3U, -- #EXTINF, #PLAYLIST). Not supported: writing HLS tags. -- @@ -17,8 +17,8 @@ local Err = require("@formats/core/Err") local Sniff = require("@formats/core/Sniff") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") -local Url = require("@formats/codecs/Url") -local Text = require("@formats/codecs/Text") +local Url = require("@formats/codecs/text/Url") +local Text = require("@formats/codecs/text/Text") -- ------------------------------------------------------------------------------------------------ contract local M3u = { @@ -26,7 +26,7 @@ local M3u = { category = "playlist", extensions = { "m3u", "m3u8" }, mime = { "audio/x-mpegurl", "audio/mpegurl", "application/vnd.apple.mpegurl", "application/x-mpegurl" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Url", "codecs/Text", "core/Sniff" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Url", "codecs/text/Text", "core/Sniff" }, caps = { decode = true, encode = true, hls = true }, } diff --git a/src/Formats/playlist/pls/init.luau b/src/Formats/playlist/pls/init.luau index 676f302..c3d4598 100644 --- a/src/Formats/playlist/pls/init.luau +++ b/src/Formats/playlist/pls/init.luau @@ -2,7 +2,7 @@ -- playlist/pls: PLS playlists ([playlist], FileN / TitleN / LengthN, NumberOfEntries, Version). Absorbed from -- playlist-luau 3fc7fd3 (same author, no third-party code; the parser), plus a new writer. Decode: keys in any case -- and order, comments, a BOM, CRLF / CR, Windows-1252 text, gaps in the numbering (entries sort by number), a --- NumberOfEntries mismatch as a warning; locations resolve against opts.baseUrl (RFC 3986, codecs/Url), local / +-- NumberOfEntries mismatch as a warning; locations resolve against opts.baseUrl (RFC 3986, codecs/text/Url), local / -- relative / non-HTTP locations are flagged unplayable. Encode: Version=2, Length -1 for unknown durations. -- -- local pl = Pls.decode(Bytes.reader(buf), { baseUrl = "https://radio.example/list.pls" }) @@ -13,8 +13,8 @@ local Err = require("@formats/core/Err") local Sniff = require("@formats/core/Sniff") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") -local Url = require("@formats/codecs/Url") -local Text = require("@formats/codecs/Text") +local Url = require("@formats/codecs/text/Url") +local Text = require("@formats/codecs/text/Text") -- ------------------------------------------------------------------------------------------------ contract local Pls = { @@ -22,7 +22,7 @@ local Pls = { category = "playlist", extensions = { "pls" }, mime = { "audio/x-scpls", "audio/scpls" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Url", "codecs/Text", "core/Sniff" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Url", "codecs/text/Text", "core/Sniff" }, caps = { decode = true, encode = true }, } diff --git a/src/Formats/playlist/xspf/init.luau b/src/Formats/playlist/xspf/init.luau index d93c3ac..325f0ac 100644 --- a/src/Formats/playlist/xspf/init.luau +++ b/src/Formats/playlist/xspf/init.luau @@ -1,9 +1,9 @@ --!strict --- playlist/xspf: XSPF 1 ("spiff", https://xspf.org/spec) playlists on codecs/Xml. New in formats-luau (playlist-luau +-- playlist/xspf: XSPF 1 ("spiff", https://xspf.org/spec) playlists on codecs/text/Xml. New in formats-luau (playlist-luau -- had no XSPF). Decode: the playlist's title / creator / annotation / info / location / identifier / image / date, -- every track's location (the first one is the entry url, all of them in entry.locations), title, creator, album, -- annotation, info, image, trackNum and duration (milliseconds -> seconds), xml:base on the playlist and on tracks; --- locations resolve against xml:base, then opts.baseUrl (RFC 3986, codecs/Url), and are classified like the other +-- locations resolve against xml:base, then opts.baseUrl (RFC 3986, codecs/text/Url), and are classified like the other -- playlist formats (local / relative / non-HTTP locations are unplayable). Encode: XSPF version 1 with those fields. -- Not supported: extension / link / meta elements (skipped), XSPF version 0 differences. -- @@ -15,8 +15,8 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") -local Url = require("@formats/codecs/Url") -local Xml = require("@formats/codecs/Xml") +local Url = require("@formats/codecs/text/Url") +local Xml = require("@formats/codecs/text/Xml") -- ------------------------------------------------------------------------------------------------ contract local Xspf = { @@ -24,7 +24,7 @@ local Xspf = { category = "playlist", extensions = { "xspf" }, mime = { "application/xspf+xml" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Url", "codecs/Xml" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Url", "codecs/text/Xml" }, caps = { decode = true, encode = true }, } diff --git a/src/Formats/vector/svg/Parse.luau b/src/Formats/vector/svg/Parse.luau index 827670e..f60199d 100644 --- a/src/Formats/vector/svg/Parse.luau +++ b/src/Formats/vector/svg/Parse.luau @@ -1,12 +1,12 @@ --!strict --- vector/svg/Parse: an SVG document (a codecs/Xml tree) to a Types.Vector: the cascade (presentation attributes, +-- vector/svg/Parse: an SVG document (a codecs/text/Xml tree) to a Types.Vector: the cascade (presentation attributes, -- <style> rules by specificity, style="", inheritance), the shapes as absolute path commands in their user space -- with the full transform to the root's viewBox space, paints (colours with fill- / stroke-opacity folded into -- alpha, linear / radial gradients with href inheritance), groups that need their own layer (opacity < 1, or a -- clip-path) in meta.groups, clip paths resolved per use in meta.clips, <use> / <symbol> / nested <svg> / <switch>. -- Unsupported elements (text, image, pattern, mask, marker, filter, foreignObject) are counted in meta.unsupported. -- Never throws. -local Xml = require("@formats/codecs/Xml") +local Xml = require("@formats/codecs/text/Xml") local Types = require("@formats/Types") local Style = require("@formats/vector/svg/Style") local PathData = require("@formats/vector/svg/PathData") diff --git a/src/Formats/vector/svg/PathData.luau b/src/Formats/vector/svg/PathData.luau index bf680a2..7f19860 100644 --- a/src/Formats/vector/svg/PathData.luau +++ b/src/Formats/vector/svg/PathData.luau @@ -360,7 +360,7 @@ function PathData.serialize(cmds: { Cmd }): string return table.concat(out, " ") end --- toRaster(cmds) -> the codecs/Raster command list (moveTo / lineTo / quadTo / cubicTo / close) +-- toRaster(cmds) -> the codecs/image/Raster command list (moveTo / lineTo / quadTo / cubicTo / close) local RASTER = { M = "moveTo", L = "lineTo", Q = "quadTo", C = "cubicTo", Z = "close" } function PathData.toRaster(cmds: { Cmd }): { any } local out = table.create(#cmds) diff --git a/src/Formats/vector/svg/Render.luau b/src/Formats/vector/svg/Render.luau index e9c90e7..d66e986 100644 --- a/src/Formats/vector/svg/Render.luau +++ b/src/Formats/vector/svg/Render.luau @@ -1,12 +1,12 @@ --!strict --- vector/svg/Render: a Types.Vector to an rgba8 Image with codecs/Raster (antialiased coverage, nonzero / even-odd, --- the stroker) and codecs/Blend (group layers with opacity and clip masks): fills and strokes with solid colours and +-- vector/svg/Render: a Types.Vector to an rgba8 Image with codecs/image/Raster (antialiased coverage, nonzero / even-odd, +-- the stroker) and codecs/image/Blend (group layers with opacity and clip masks): fills and strokes with solid colours and -- linear / radial gradients (objectBoundingBox / userSpaceOnUse units, gradientTransform, pad / reflect / repeat, -- the SVG 1.1 focal point), dashes, joins, caps, miter limits, per-path opacity, groups and clip paths. The viewBox -- maps onto the image by meta.preserveAspectRatio. Never throws. local Types = require("@formats/Types") -local Raster = require("@formats/codecs/Raster") -local Blend = require("@formats/codecs/Blend") +local Raster = require("@formats/codecs/image/Raster") +local Blend = require("@formats/codecs/image/Blend") local PathData = require("@formats/vector/svg/PathData") local Parse = require("@formats/vector/svg/Parse") diff --git a/src/Formats/vector/svg/Write.luau b/src/Formats/vector/svg/Write.luau index 78fb097..2602f1e 100644 --- a/src/Formats/vector/svg/Write.luau +++ b/src/Formats/vector/svg/Write.luau @@ -2,7 +2,7 @@ -- vector/svg/Write: a Types.Vector to SVG text: <svg> with width / height / viewBox / preserveAspectRatio, gradients -- and clip paths in <defs>, groups as nested <g opacity clip-path>, every path as <path d transform fill stroke ...> -- (colour alpha as fill- / stroke-opacity). Never throws: bad values return nil, message. -local Xml = require("@formats/codecs/Xml") +local Xml = require("@formats/codecs/text/Xml") local Types = require("@formats/Types") local PathData = require("@formats/vector/svg/PathData") diff --git a/src/Formats/vector/svg/init.luau b/src/Formats/vector/svg/init.luau index 811f89a..4889f04 100644 --- a/src/Formats/vector/svg/init.luau +++ b/src/Formats/vector/svg/init.luau @@ -7,7 +7,7 @@ -- radial gradients (units, gradientTransform, spreadMethod, href inheritance, focal point), group opacity, clip-path -- (userSpaceOnUse and objectBoundingBox, on shapes and groups), units (px pt pc mm cm in em ex %). -- Decodes to a Types.Vector (paths in their user space with the full transform to the root's viewBox space; groups and --- clips in meta); Svg.rasterize(v, w, h) renders it with codecs/Raster; encode writes SVG back from a Vector. +-- clips in meta); Svg.rasterize(v, w, h) renders it with codecs/image/Raster; encode writes SVG back from a Vector. -- Not supported (counted in meta.unsupported): text, image, pattern, mask, marker, filter, foreignObject; also -- conditional processing in switch, CSS combinators / pseudo-classes, non-scaling strokes. @@ -16,7 +16,7 @@ local Err = require("@formats/core/Err") local Sniff = require("@formats/core/Sniff") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") -local Xml = require("@formats/codecs/Xml") +local Xml = require("@formats/codecs/text/Xml") local Parse = require("@formats/vector/svg/Parse") local Render = require("@formats/vector/svg/Render") local Write = require("@formats/vector/svg/Write") @@ -27,7 +27,7 @@ local Svg = { category = "vector", extensions = { "svg" }, mime = { "image/svg+xml" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "codecs/Raster", "codecs/Blend", "core/Sniff" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Xml", "codecs/image/Raster", "codecs/image/Blend", "core/Sniff" }, caps = { decode = true, encode = true, rasterize = true, text = false }, } diff --git a/src/Formats/vector/tiled/Data.luau b/src/Formats/vector/tiled/Data.luau index 449b495..cb694d0 100644 --- a/src/Formats/vector/tiled/Data.luau +++ b/src/Formats/vector/tiled/Data.luau @@ -2,7 +2,7 @@ -- vector/tiled/Data: tile layer data shared by the TMX and TMJ halves: CSV text, base64 (uncompressed, zlib, gzip) -- to gids and back; property values and their types; number formatting. Never throws. local Base64 = require("@formats/core/Base64") -local Deflate = require("@formats/codecs/Deflate") +local Deflate = require("@formats/codecs/compress/Deflate") local Data = {} diff --git a/src/Formats/vector/tiled/Tmx.luau b/src/Formats/vector/tiled/Tmx.luau index 8d9dd72..9cd3f39 100644 --- a/src/Formats/vector/tiled/Tmx.luau +++ b/src/Formats/vector/tiled/Tmx.luau @@ -1,7 +1,7 @@ --!strict --- vector/tiled/Tmx: the TMX (XML) half of vector/tiled: a codecs/Xml tree <-> a Types.TileMap, and TSX tilesets. +-- vector/tiled/Tmx: the TMX (XML) half of vector/tiled: a codecs/text/Xml tree <-> a Types.TileMap, and TSX tilesets. -- TMX map format, Tiled 1.12 docs. Never throws: failures return nil, message, unsupported?. -local Xml = require("@formats/codecs/Xml") +local Xml = require("@formats/codecs/text/Xml") local Types = require("@formats/Types") local Data = require("@formats/vector/tiled/Data") diff --git a/src/Formats/vector/tiled/init.luau b/src/Formats/vector/tiled/init.luau index e3a34aa..5999cec 100644 --- a/src/Formats/vector/tiled/init.luau +++ b/src/Formats/vector/tiled/init.luau @@ -15,8 +15,8 @@ local Err = require("@formats/core/Err") local Sniff = require("@formats/core/Sniff") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") -local Xml = require("@formats/codecs/Xml") -local Json = require("@formats/codecs/Json") +local Xml = require("@formats/codecs/text/Xml") +local Json = require("@formats/codecs/text/Json") local Tmx = require("@formats/vector/tiled/Tmx") local Tmj = require("@formats/vector/tiled/Tmj") @@ -26,7 +26,7 @@ local Tiled = { category = "vector", extensions = { "tmx", "tmj", "tsx", "tsj" }, mime = { "application/x-tiled-tmx", "application/x-tiled-tmj" }, - deps = { "core/Err", "core/Bytes", "core/Base64", "Types", "codecs/Xml", "codecs/Json", "codecs/Deflate", "core/Sniff" }, + deps = { "core/Err", "core/Bytes", "core/Base64", "Types", "codecs/text/Xml", "codecs/text/Json", "codecs/compress/Deflate", "core/Sniff" }, caps = { decode = true, encode = true, tilesets = true, infinite = true }, } diff --git a/src/Formats/video/avi/init.luau b/src/Formats/video/avi/init.luau index 996ee55..fc46a32 100644 --- a/src/Formats/video/avi/init.luau +++ b/src/Formats/video/avi/init.luau @@ -1,7 +1,7 @@ --!strict -- video/avi: AVI (Microsoft RIFF AVI 1.0, OpenDML 1.02). New in formats-luau, on containers/Avi. -- Read: open() indexes every stream (OpenDML super / standard indexes, else idx1, else a movi scan; RIFF AVIX pieces --- of files over 1 GB) and returns a VideoDecoder: video through the codecs/Video registry by FourCC (MJPEG, MPEG-1, +-- of files over 1 GB) and returns a VideoDecoder: video through the codecs/video/Video registry by FourCC (MJPEG, MPEG-1, -- uncompressed BI_RGB 24 / 32-bit bottom-up or top-down, I420 / YV12; H.264 and others when a decoder is -- registered), audio through the api's opts.openAudio hook (PCM, A-law / mu-law, IMA / MS ADPCM with its WAVEFORMATEX, -- MP3 / MP2, AAC). Dropped frames (empty video chunks) keep their time slot. Avi.demux(r) gives the Demuxer. @@ -15,8 +15,8 @@ local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") local Avi = require("@formats/containers/Avi") local Demux = require("@formats/containers/Demux") -local Video = require("@formats/codecs/Video") -local Source = require("@formats/codecs/Video/Source") +local Video = require("@formats/codecs/video/Video") +local Source = require("@formats/codecs/video/Video/Source") -- ------------------------------------------------------------------------------------------------ contract local AviFormat = { @@ -24,7 +24,7 @@ local AviFormat = { category = "video", extensions = { "avi" }, mime = { "video/x-msvideo", "video/avi" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Avi", "containers/Demux", "codecs/Video", "codecs/Video/Source" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Avi", "containers/Demux", "codecs/video/Video", "codecs/video/Video/Source" }, caps = { decode = true, encode = true, streaming = true, video = { "mjpeg", "mpeg1", "rawvideo" }, audio = true, odml = true }, } diff --git a/src/Formats/video/h264/init.luau b/src/Formats/video/h264/init.luau index 978ad52..06c865f 100644 --- a/src/Formats/video/h264/init.luau +++ b/src/Formats/video/h264/init.luau @@ -1,21 +1,21 @@ --!strict -- video/h264: raw H.264 / AVC elementary streams (ITU-T H.264 Annex B byte stream: .h264 / .264 files, x264 / ffmpeg -- `-f h264` output, the JVT conformance bitstreams). New in formats-luau. --- Read: the stream cut into access units (codecs/H264.accessUnits) as a one-track Demuxer; open() returns a --- VideoDecoder decoding through codecs/H264 (yuv420p frames in display order, numbered in output order since a raw +-- Read: the stream cut into access units (codecs/video/H264.accessUnits) as a one-track Demuxer; open() returns a +-- VideoDecoder decoding through codecs/video/H264 (yuv420p frames in display order, numbered in output order since a raw -- stream has no timestamps; the frame rate comes from the SPS VUI timing, else opts.frameRate, else 25). -- Write: H.264 tracks copied from any video (MP4 / MKV samples are converted from length-prefixed NAL units to Annex B, -- the avcC parameter sets put in front of every keyframe). Not supported: re-encoding other codecs to H.264 (there is --- no H.264 encoder), and whatever codecs/H264 does not decode (interlaced, 4:2:2 / 4:4:4, > 8 bits: UNSUPPORTED). +-- no H.264 encoder), and whatever codecs/video/H264 does not decode (interlaced, 4:2:2 / 4:4:4, > 8 bits: UNSUPPORTED). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") local Demux = require("@formats/containers/Demux") -local Video = require("@formats/codecs/Video") -local Source = require("@formats/codecs/Video/Source") -local H264 = require("@formats/codecs/H264") +local Video = require("@formats/codecs/video/Video") +local Source = require("@formats/codecs/video/Video/Source") +local H264 = require("@formats/codecs/video/H264") -- ------------------------------------------------------------------------------------------------ contract local Format = { @@ -23,7 +23,7 @@ local Format = { category = "video", extensions = { "h264", "264", "avc", "jsv", "26l", "jvt" }, mime = { "video/h264" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/Video", "codecs/Video/Source", "codecs/H264" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/video/Video", "codecs/video/Video/Source", "codecs/video/H264" }, caps = { decode = true, encode = true, streaming = true, video = { "h264" }, depths = { 8 } }, } diff --git a/src/Formats/video/mkv/Mux.luau b/src/Formats/video/mkv/Mux.luau index 6eed3cc..dccb510 100644 --- a/src/Formats/video/mkv/Mux.luau +++ b/src/Formats/video/mkv/Mux.luau @@ -3,11 +3,11 @@ -- Tracks (CodecPrivate, DefaultDuration, Video / Audio settings, Opus CodecDelay / SeekPreRoll), Clusters of -- SimpleBlocks (a new cluster at a video keyframe once the current one spans 2 s, and before the 16-bit relative -- timestamp would overflow), and Cues (one CuePoint per cluster, on the video track when there is one). Streams come --- from codecs/Video/Source (copied packets or encoded frames). Interpreted; never throws. +-- from codecs/video/Video/Source (copied packets or encoded frames). Interpreted; never throws. local Err = require("@formats/core/Err") local Ebml = require("@formats/containers/Ebml") -local Video = require("@formats/codecs/Video") -local Source = require("@formats/codecs/Video/Source") +local Video = require("@formats/codecs/video/Video") +local Source = require("@formats/codecs/video/Video/Source") local Parse = require("@formats/video/mkv/Parse") local ID = Parse.ID diff --git a/src/Formats/video/mkv/Parse.luau b/src/Formats/video/mkv/Parse.luau index ce5b489..fd07900 100644 --- a/src/Formats/video/mkv/Parse.luau +++ b/src/Formats/video/mkv/Parse.luau @@ -8,8 +8,8 @@ local Err = require("@formats/core/Err") local Types = require("@formats/Types") local Ebml = require("@formats/containers/Ebml") local Demux = require("@formats/containers/Demux") -local Video = require("@formats/codecs/Video") -local Deflate = require("@formats/codecs/Deflate") +local Video = require("@formats/codecs/video/Video") +local Deflate = require("@formats/codecs/compress/Deflate") local Parse = {} @@ -104,7 +104,7 @@ local TOP: { [number]: boolean } = { [ID.EBML] = true, } --- Matroska audio / subtitle CodecIDs -> our codec ids (video ids come from the codecs/Video registry) +-- Matroska audio / subtitle CodecIDs -> our codec ids (video ids come from the codecs/video/Video registry) local AUDIO: { [string]: string } = { A_VORBIS = "vorbis", A_OPUS = "opus", diff --git a/src/Formats/video/mkv/init.luau b/src/Formats/video/mkv/init.luau index 619a92d..1a94272 100644 --- a/src/Formats/video/mkv/init.luau +++ b/src/Formats/video/mkv/init.luau @@ -3,7 +3,7 @@ -- formats-luau, on containers/Ebml. -- Read: open() demuxes the whole file into a packet index (SimpleBlock / BlockGroup, Xiph / EBML / fixed lacing, -- header-stripping and zlib compression, unknown-size clusters, Cues and Tags in meta) and returns a VideoDecoder: video --- through the codecs/Video registry (VP8 with inter frames, MJPEG, MPEG-1, raw; H.264 when registered), audio +-- through the codecs/video/Video registry (VP8 with inter frames, MJPEG, MPEG-1, raw; H.264 when registered), audio -- through the api's opts.openAudio hook (Opus, Vorbis, FLAC, MP3, PCM, AAC, ... reach the audio formats), text -- subtitle tracks as cues (Mkv.subtitles). Mkv.demux(r) gives the Demuxer alone. -- Write: WebM (opts.format = "webm" or a .webm destination: VP8 / VP9 / AV1 video and Opus / Vorbis audio, copied @@ -16,8 +16,8 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") -local Video = require("@formats/codecs/Video") -local Source = require("@formats/codecs/Video/Source") +local Video = require("@formats/codecs/video/Video") +local Source = require("@formats/codecs/video/Video/Source") local Parse = require("@formats/video/mkv/Parse") local Mux = require("@formats/video/mkv/Mux") @@ -27,7 +27,7 @@ local Mkv = { category = "video", extensions = { "mkv", "webm", "mka", "mk3d" }, mime = { "video/x-matroska", "video/webm", "audio/x-matroska", "audio/webm" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Ebml", "containers/Demux", "codecs/Deflate", "codecs/Video", "codecs/Video/Source" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ebml", "containers/Demux", "codecs/compress/Deflate", "codecs/video/Video", "codecs/video/Video/Source" }, caps = { decode = true, encode = true, streaming = true, remux = true, video = { "vp8", "mjpeg", "mpeg1", "rawvideo" }, audio = true, subtitles = true }, } diff --git a/src/Formats/video/mp4/init.luau b/src/Formats/video/mp4/init.luau index a511465..0dcf3e8 100644 --- a/src/Formats/video/mp4/init.luau +++ b/src/Formats/video/mp4/init.luau @@ -3,7 +3,7 @@ -- containers/IsoBmff (ws-m4a's box parser, sample tables, fragments and muxer). New in formats-luau. -- Read: every track's samples into a Demuxer (pts = dts + composition offset, moved by the edit list: the first -- edit's media time is subtracted (B-frame delay, AAC priming), an initial empty edit added; sync samples as --- keyframes; fragmented files too) and open() returns a VideoDecoder: video through the codecs/Video registry (MJPEG +-- keyframes; fragmented files too) and open() returns a VideoDecoder: video through the codecs/video/Video registry (MJPEG -- 'jpeg' / 'mjpa' / mp4v 0x6C, MPEG-1, raw; H.264 'avc1' with its avcC when a decoder is registered), audio through -- the api's opts.openAudio hook (AAC, ALAC (audio/m4a), MP3, Opus (dOps -> OpusHead), FLAC, PCM 'sowt' / 'twos' / -- 'lpcm' / 'ipcm'). @@ -20,8 +20,8 @@ local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") local IsoBmff = require("@formats/containers/IsoBmff") local Demux = require("@formats/containers/Demux") -local Video = require("@formats/codecs/Video") -local Source = require("@formats/codecs/Video/Source") +local Video = require("@formats/codecs/video/Video") +local Source = require("@formats/codecs/video/Video/Source") -- ------------------------------------------------------------------------------------------------ contract local Mp4 = { @@ -29,7 +29,7 @@ local Mp4 = { category = "video", extensions = { "mp4", "m4v", "mov", "qt", "3gp", "3g2", "mj2" }, mime = { "video/mp4", "video/quicktime", "video/3gpp" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/IsoBmff", "containers/Demux", "codecs/Video", "codecs/Video/Source" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/IsoBmff", "containers/Demux", "codecs/video/Video", "codecs/video/Video/Source" }, caps = { decode = true, encode = true, streaming = true, remux = true, video = { "mjpeg", "mpeg1", "h264" }, audio = true, fragments = true }, } diff --git a/src/Formats/video/mpegps/init.luau b/src/Formats/video/mpegps/init.luau index e26d946..8708894 100644 --- a/src/Formats/video/mpegps/init.luau +++ b/src/Formats/video/mpegps/init.luau @@ -4,7 +4,7 @@ -- stream and cut into pictures (containers/MpegEs: one packet per picture with its sequence / GOP headers); a -- picture takes the PTS of the PES it starts in, pictures without one get theirs from the GOP's temporal references. -- Audio packets are the PES payloads (MP1 / MP2 / MP3 frames, AC-3, LPCM). open() returns a VideoDecoder: MPEG-1 --- video through the codecs/Video registry (MPEG-2 detected and reported), audio through the api's opts.openAudio hook. +-- video through the codecs/video/Video registry (MPEG-2 detected and reported), audio through the api's opts.openAudio hook. -- Timescale 90 kHz. Not supported: writing, H.264 in PS (packets are whole PES payloads), DVD navigation packets. -- ------------------------------------------------------------------------------------------------ requires @@ -14,7 +14,7 @@ local Types = require("@formats/Types") local MpegPs = require("@formats/containers/MpegPs") local MpegEs = require("@formats/containers/MpegEs") local Demux = require("@formats/containers/Demux") -local Video = require("@formats/codecs/Video") +local Video = require("@formats/codecs/video/Video") -- ------------------------------------------------------------------------------------------------ contract local Ps = { @@ -22,7 +22,7 @@ local Ps = { category = "video", extensions = { "mpg", "mpeg", "vob", "m1v", "mpv", "dat" }, mime = { "video/mpeg" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/MpegPs", "containers/MpegEs", "containers/Demux", "codecs/Video" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/MpegPs", "containers/MpegEs", "containers/Demux", "codecs/video/Video" }, caps = { decode = true, encode = false, streaming = true, video = { "mpeg1" }, audio = true }, } diff --git a/src/Formats/video/mpegts/init.luau b/src/Formats/video/mpegts/init.luau index d79bdeb..1cac2a4 100644 --- a/src/Formats/video/mpegts/init.luau +++ b/src/Formats/video/mpegts/init.luau @@ -2,7 +2,7 @@ -- video/mpegts: MPEG transport streams (ISO/IEC 13818-1: .ts / .m2ts segments, HLS). The demuxer is containers/MpegTs, -- absorbed from mpegts-luau (resync, PAT / PMT with CRC, continuity checks, PES reassembly, 33-bit PTS / DTS -- unwrapped); this format turns its units into a Demuxer (timescale 90 kHz; one PES = one packet: a picture as --- muxed by ffmpeg, one or more audio frames) and returns a VideoDecoder: MPEG-1 video through the codecs/Video +-- muxed by ffmpeg, one or more audio frames) and returns a VideoDecoder: MPEG-1 video through the codecs/video/Video -- registry (stream type 0x02 checked for an MPEG-2 sequence extension), H.264 when registered, audio (MP1 / MP2 / -- MP3, AAC in ADTS) through the api's opts.openAudio hook. Keyframes: MPEG-1 / 2 I-pictures, H.264 IDR access units. -- M2TS (192-byte packets with a 4-byte timestamp prefix) is read too. Not supported: writing, scrambled streams, @@ -15,7 +15,7 @@ local Types = require("@formats/Types") local MpegTs = require("@formats/containers/MpegTs") local MpegEs = require("@formats/containers/MpegEs") local Demux = require("@formats/containers/Demux") -local Video = require("@formats/codecs/Video") +local Video = require("@formats/codecs/video/Video") -- ------------------------------------------------------------------------------------------------ contract local Ts = { @@ -23,7 +23,7 @@ local Ts = { category = "video", extensions = { "ts", "m2ts", "mts", "tsv" }, mime = { "video/mp2t" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/MpegTs", "containers/MpegEs", "containers/Demux", "codecs/Video" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/MpegTs", "containers/MpegEs", "containers/Demux", "codecs/video/Video" }, caps = { decode = true, encode = false, streaming = true, video = { "mpeg1", "h264" }, audio = true }, } diff --git a/src/Formats/video/y4m/init.luau b/src/Formats/video/y4m/init.luau index 8525b03..1a39a4b 100644 --- a/src/Formats/video/y4m/init.luau +++ b/src/Formats/video/y4m/init.luau @@ -12,8 +12,8 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") local Demux = require("@formats/containers/Demux") -local Video = require("@formats/codecs/Video") -local Source = require("@formats/codecs/Video/Source") +local Video = require("@formats/codecs/video/Video") +local Source = require("@formats/codecs/video/Video/Source") -- ------------------------------------------------------------------------------------------------ contract local Y4m = { @@ -21,7 +21,7 @@ local Y4m = { category = "video", extensions = { "y4m" }, mime = { "video/x-yuv4mpeg" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/Video", "codecs/Video/Source" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/video/Video", "codecs/video/Video/Source" }, caps = { decode = true, encode = true, streaming = true, video = { "rawvideo" }, depths = { 8, 10, 12, 16 } }, } diff --git a/tests/archive/gzip.luau b/tests/archive/gzip.luau index ff51f40..c6053bc 100644 --- a/tests/archive/gzip.luau +++ b/tests/archive/gzip.luau @@ -4,7 +4,7 @@ local T = require("@tests/T") local F = require("@formats") local Gzip = require("@formats/archive/gzip") -local Deflate = require("@formats/codecs/Deflate") +local Deflate = require("@formats/codecs/compress/Deflate") local Bytes = require("@formats/core/Bytes") local Crc32 = require("@formats/core/Crc32") local Err = require("@formats/core/Err") diff --git a/tests/archive/zip.luau b/tests/archive/zip.luau index 26efdec..53670de 100644 --- a/tests/archive/zip.luau +++ b/tests/archive/zip.luau @@ -8,7 +8,7 @@ local T = require("@tests/T") local Zip = require("@formats/containers/Zip") local ZipF = require("@formats/archive/zip") -local Deflate = require("@formats/codecs/Deflate") +local Deflate = require("@formats/codecs/compress/Deflate") local Bytes = require("@formats/core/Bytes") local Crc32 = require("@formats/core/Crc32") local Err = require("@formats/core/Err") diff --git a/tests/audio/flac.luau b/tests/audio/flac.luau index d24f59f..ecc2fb6 100644 --- a/tests/audio/flac.luau +++ b/tests/audio/flac.luau @@ -4,7 +4,7 @@ -- Reader; tags and pictures; the length from the last frame; sniff; the api; damaged frames skipped; the fuzz pass. -- Ported from flac-luau tests/flac.luau. Fixtures: tools/fixtures/flac.py. local T = require("@tests/T") -local VorbisComment = require("@formats/codecs/VorbisComment") +local VorbisComment = require("@formats/codecs/audio/VorbisComment") local Flac = require("@formats/audio/flac") local Bytes = require("@formats/core/Bytes") local Crc32 = require("@formats/core/Crc32") @@ -93,7 +93,7 @@ for _, fx in Cases do t:check(math.abs(pos - fx.frames / 3) <= 1, name .. ": seek seconds") dec:seek(dec.duration + 5) t:eq(select(2, dec:read(10)), 0, name .. ": read past the end") - for key, v in fx.tags or {} do -- (tags keys are lower case: codecs/VorbisComment) + for key, v in fx.tags or {} do -- (tags keys are lower case: codecs/audio/VorbisComment) t:eq(dec.tags[VorbisComment.tagKey(key)], v, name .. ": tag " .. key) end t:eq(Flac.sniff(Bytes.reader(buffer.fromstring(fx.data))), 1, name .. ": sniff") diff --git a/tests/audio/flac_encode.luau b/tests/audio/flac_encode.luau index ffd5848..1222da9 100644 --- a/tests/audio/flac_encode.luau +++ b/tests/audio/flac_encode.luau @@ -7,7 +7,7 @@ local Flac = require("@formats/audio/flac") local Bytes = require("@formats/core/Bytes") local Err = require("@formats/core/Err") local Types = require("@formats/Types") -local Pcm = require("@formats/codecs/Pcm") +local Pcm = require("@formats/codecs/audio/Pcm") local Enc = require("@tests/gen/flac_enc") local Sigs = require("@tests/gen/flac_enc_sigs") diff --git a/tests/audio/mp3_encode.luau b/tests/audio/mp3_encode.luau index 9041576..2403a4e 100644 --- a/tests/audio/mp3_encode.luau +++ b/tests/audio/mp3_encode.luau @@ -8,7 +8,7 @@ local Mp3 = require("@formats/audio/mp3") local Bytes = require("@formats/core/Bytes") local Err = require("@formats/core/Err") local Types = require("@formats/Types") -local Pcm = require("@formats/codecs/Pcm") +local Pcm = require("@formats/codecs/audio/Pcm") local Enc = require("@tests/gen/mp3_enc") local Sigs = require("@tests/gen/mp3_enc_sigs") @@ -121,7 +121,7 @@ do t:check(empty and buffer.len(empty) > 0, "empty input: one flush frame") end --- other input rates are resampled (codecs/Resample) to the next rate up: 44 kHz -> 44.1 kHz, 46 kHz -> 48 kHz, +-- other input rates are resampled (codecs/audio/Resample) to the next rate up: 44 kHz -> 44.1 kHz, 46 kHz -> 48 kHz, -- layer II 8 kHz -> 16 kHz, opts.sampleRate do local function tone(rate: number, f: number): any diff --git a/tests/audio/opus.luau b/tests/audio/opus.luau index fc86504..7f8518e 100644 --- a/tests/audio/opus.luau +++ b/tests/audio/opus.luau @@ -9,11 +9,11 @@ local Opus = require("@formats/audio/opus") local Packet = require("@formats/audio/opus/Packet") local Celt = require("@formats/audio/opus/Celt") local Silk = require("@formats/audio/opus/Silk") -local RD = require("@formats/codecs/RangeCoder/Decoder") +local RD = require("@formats/codecs/entropy/RangeCoder/Decoder") local Decoder = require("@formats/audio/opus/Decoder") local Ogg = require("@formats/containers/Ogg") local Bytes = require("@formats/core/Bytes") -local Pcm = require("@formats/codecs/Pcm") +local Pcm = require("@formats/codecs/audio/Pcm") local Err = require("@formats/core/Err") local t = T.suite("opus") diff --git a/tests/audio/vorbis.luau b/tests/audio/vorbis.luau index 3e9371e..9dcfc41 100644 --- a/tests/audio/vorbis.luau +++ b/tests/audio/vorbis.luau @@ -7,7 +7,7 @@ local Vorbis = require("@formats/audio/vorbis") local Bytes = require("@formats/core/Bytes") local Err = require("@formats/core/Err") local Types = require("@formats/Types") -local Pcm = require("@formats/codecs/Pcm") +local Pcm = require("@formats/codecs/audio/Pcm") local Ogg = require("@formats/containers/Ogg") local Cases = require("@tests/gen/vorbis_cases") @@ -58,7 +58,7 @@ for _, c in Cases do t:eq(a.frames, c.inputFrames, c.name .. ": frames = the encoder's input") local ref16 = buffer.fromstring(c.ref16) local n = c.frames * c.channels - -- oggdec -R keeps the Vorbis channel order; the decoder returns WAVE order (codecs/Pcm) + -- oggdec -R keeps the Vorbis channel order; the decoder returns WAVE order (codecs/audio/Pcm) local order = Pcm.WAVE_FROM_VORBIS[c.channels] if c.channels > 2 and order then local w = buffer.create(buffer.len(ref16)) diff --git a/tests/audio/vorbis_encode.luau b/tests/audio/vorbis_encode.luau index c85a39d..8424588 100644 --- a/tests/audio/vorbis_encode.luau +++ b/tests/audio/vorbis_encode.luau @@ -8,7 +8,7 @@ local VEnc = require("@formats/audio/vorbis/Encode") local Bytes = require("@formats/core/Bytes") local Err = require("@formats/core/Err") local Types = require("@formats/Types") -local Pcm = require("@formats/codecs/Pcm") +local Pcm = require("@formats/codecs/audio/Pcm") local Enc = require("@tests/gen/vorbis_enc") local Sigs = require("@tests/gen/vorbis_enc_sigs") diff --git a/tests/codecs/aac.luau b/tests/codecs/aac.luau index b340bd4..1451f57 100644 --- a/tests/codecs/aac.luau +++ b/tests/codecs/aac.luau @@ -1,9 +1,9 @@ --- codecs/Aac tests: AudioSpecificConfig parsing (every fixture's esds, explicit SBR / PS signalling from fdkaac, +-- codecs/audio/Aac tests: AudioSpecificConfig parsing (every fixture's esds, explicit SBR / PS signalling from fdkaac, -- crafted configs: PCE channel counts, 960-sample frames, Main / LTP object types), ADTS headers, raw frames decoded -- straight from ADTS against ffmpeg's float decode, the FIL extension hook on HE-AAC (implicit SBR), reset, errors, -- the fuzz no-throw pass on raw frames. Fixtures: tools/fixtures/m4a.py. local T = require("@tests/T") -local Aac = require("@formats/codecs/Aac") +local Aac = require("@formats/codecs/audio/Aac") local IsoBmff = require("@formats/containers/IsoBmff") local Bytes = require("@formats/core/Bytes") local Bits = require("@formats/core/Bits") diff --git a/tests/codecs/alac.luau b/tests/codecs/alac.luau index 8dff395..e40e90a 100644 --- a/tests/codecs/alac.luau +++ b/tests/codecs/alac.luau @@ -1,9 +1,9 @@ --- codecs/Alac tests: encoder -> decoder round trips over silence (zero runs), full-scale noise (uncompressed frames), +-- codecs/audio/Alac tests: encoder -> decoder round trips over silence (zero runs), full-scale noise (uncompressed frames), -- tones, steps, 1 - 8 channels, 16 / 20 / 24 bits, partial and tiny frames, custom frame lengths; ffmpeg's ALAC -- packets (through containers/IsoBmff) decode to the source integers; the magic cookie (plain, behind frma / alac atoms, -- bad versions / depths); errors; the fuzz no-throw pass on packets. Fixtures: tools/fixtures/m4a.py. local T = require("@tests/T") -local Alac = require("@formats/codecs/Alac") +local Alac = require("@formats/codecs/audio/Alac") local IsoBmff = require("@formats/containers/IsoBmff") local Bytes = require("@formats/core/Bytes") local Crc32 = require("@formats/core/Crc32") diff --git a/tests/codecs/brotli.luau b/tests/codecs/brotli.luau index 8a9df45..53e9ba4 100644 --- a/tests/codecs/brotli.luau +++ b/tests/codecs/brotli.luau @@ -1,9 +1,9 @@ --- codecs/Brotli tests: every fixture stream (reference encoder: qualities 0..11, windows 10..24, text / font / generic +-- codecs/compress/Brotli tests: every fixture stream (reference encoder: qualities 0..11, windows 10..24, text / font / generic -- modes, large windows) decodes to its corpus; consumedEnd; offsets inside a bigger buffer; the static dictionary; -- hand-made streams (empty, metadata, uncompressed); maxBytes; truncated / corrupted / random input returns nil, Err -- and never throws. Fixtures: tools/fixtures/brotli.py. local T = require("@tests/T") -local Brotli = require("@formats/codecs/Brotli") +local Brotli = require("@formats/codecs/compress/Brotli") local Err = require("@formats/core/Err") local Crc32 = require("@formats/core/Crc32") local Fx = require("@tests/gen/brotli") diff --git a/tests/codecs/bzip2.luau b/tests/codecs/bzip2.luau index 71a872d..e7beb46 100644 --- a/tests/codecs/bzip2.luau +++ b/tests/codecs/bzip2.luau @@ -1,9 +1,9 @@ --- codecs/Bzip2 tests: every fixture stream (Python bz2 = libbzip2, block sizes 1..9, RLE1 run edges, block-boundary +-- codecs/compress/Bzip2 tests: every fixture stream (Python bz2 = libbzip2, block sizes 1..9, RLE1 run edges, block-boundary -- runs, random / skewed data, concatenated streams with trailing garbage) decodes exactly; offsets / consumedEnd; -- maxBytes; CRC mismatches are Err.CHECKSUM; truncations are Err.TRUNCATED; the fuzz no-throw pass. -- Fixtures: tools/fixtures/bzip2.py. local T = require("@tests/T") -local Bzip2 = require("@formats/codecs/Bzip2") +local Bzip2 = require("@formats/codecs/compress/Bzip2") local Err = require("@formats/core/Err") local Fx = require("@tests/gen/bzip2") diff --git a/tests/codecs/dct.luau b/tests/codecs/dct.luau index 0e45a54..4eb7f23 100644 --- a/tests/codecs/dct.luau +++ b/tests/codecs/dct.luau @@ -1,9 +1,9 @@ --- codecs/Dct tests: the islow inverse DCT against a double-precision reference (within 1 level per sample, as T.81 +-- codecs/image/Dct tests: the islow inverse DCT against a double-precision reference (within 1 level per sample, as T.81 -- annex A accuracy needs), forward DCT + quantiser against the reference transform (round to nearest of v / (8 q)), -- fdct -> idct round trips at q = 1 within 1 level, edge replication of fdctQuantize, and garbage coefficients never -- throw (outputs stay clamped). The bit-exact djpeg / cjpeg checks are in tests/image/jpeg.luau. local T = require("@tests/T") -local Dct = require("@formats/codecs/Dct") +local Dct = require("@formats/codecs/image/Dct") local t = T.suite("dct") local rand = T.rng(11) diff --git a/tests/codecs/deflate.luau b/tests/codecs/deflate.luau index 19f9814..d9ee80a 100644 --- a/tests/codecs/deflate.luau +++ b/tests/codecs/deflate.luau @@ -1,9 +1,9 @@ --- codecs/Deflate tests: every fixture case (Python zlib, levels 0-9, every strategy, small windows, flushes, gzip +-- codecs/compress/Deflate tests: every fixture case (Python zlib, levels 0-9, every strategy, small windows, flushes, gzip -- headers, multi-member gzip) decodes; exact-size mode; checksum vectors; the compressor round-trips every corpus at -- every level (and its zlib / gzip framing); truncated / corrupted / random input returns nil, Err and never throws. -- Ported from deflate-luau tests/inflate.luau. Fixtures: tools/fixtures/deflate.py. local T = require("@tests/T") -local Deflate = require("@formats/codecs/Deflate") +local Deflate = require("@formats/codecs/compress/Deflate") local Err = require("@formats/core/Err") local Fx = require("@tests/gen/deflate") diff --git a/tests/codecs/h264.luau b/tests/codecs/h264.luau index f34ba2a..b14d105 100644 --- a/tests/codecs/h264.luau +++ b/tests/codecs/h264.luau @@ -1,11 +1,11 @@ --- codecs/H264 tests: libx264 streams at many settings (Baseline / Main / High, CAVLC / CABAC, B frames, references, +-- codecs/video/H264 tests: libx264 streams at many settings (Baseline / Main / High, CAVLC / CABAC, B frames, references, -- weighted prediction, 8x8 transforms, scaling matrices, slices, odd sizes with cropping, ...) decoded and compared -- per frame with ffmpeg's decoder (CRC-32 of the yuv420p planes, bit-exact); the AVCC (avcC + length-prefixed -- samples) and NAL-at-a-time paths; pts propagation; UNSUPPORTED streams (interlaced, 4:2:2, 4:4:4, 10-bit); error -- codes; and the fuzz no-throw pass. Fixtures: tools/fixtures/h264.py. local T = require("@tests/T") require("@formats/host") -- LuaJIT: the trace limits the api sets (host/init.luau) -local H264 = require("@formats/codecs/H264") +local H264 = require("@formats/codecs/video/H264") local Crc32 = require("@formats/core/Crc32") local Err = require("@formats/core/Err") local Cases = require("@tests/gen/h264_cases") diff --git a/tests/codecs/h264_jvt.luau b/tests/codecs/h264_jvt.luau index e44d512..b8aa2be 100644 --- a/tests/codecs/h264_jvt.luau +++ b/tests/codecs/h264_jvt.luau @@ -1,11 +1,11 @@ --- codecs/H264 conformance: a selection of the ITU-T H.264.1 (JVT) conformance bitstreams (Baseline / Main / Extended +-- codecs/video/H264 conformance: a selection of the ITU-T H.264.1 (JVT) conformance bitstreams (Baseline / Main / Extended -- without SP / High: CAVLC, CABAC, B frames, weighted prediction, multiple slices, MMCO / long-term references, -- frame_num gaps, cropping, PCM, 8x8 transforms, scaling matrices, ...) decoded bit-exact against the reference -- decoder's yuv (JM, shipped in each zip; ffmpeg where there is none), and interlaced / SP / 4:2:2 streams refused -- with UNSUPPORTED. Fixtures: tools/fixtures/h264_jvt.py (downloaded from itu.int; skipped when unreachable). local T = require("@tests/T") require("@formats/host") -- LuaJIT: the trace limits the api sets (host/init.luau) -local H264 = require("@formats/codecs/H264") +local H264 = require("@formats/codecs/video/H264") local Crc32 = require("@formats/core/Crc32") local Base64 = require("@formats/core/Base64") local Err = require("@formats/core/Err") diff --git a/tests/codecs/jpeg.luau b/tests/codecs/jpeg.luau index 5b42f8d..7cb41e9 100644 --- a/tests/codecs/jpeg.luau +++ b/tests/codecs/jpeg.luau @@ -1,16 +1,16 @@ --- codecs/Jpeg tests (the Motion-JPEG side; tests/image/jpeg.luau covers the still-image decoder and encoder through +-- codecs/image/Jpeg tests (the Motion-JPEG side; tests/image/jpeg.luau covers the still-image decoder and encoder through -- image/jpeg): ffmpeg mjpeg frames (4:2:0, 4:2:2, 4:4:4, odd sizes, stripped DHT, AVI1 + junk after EOI) decoded -- to yuv420p bit-exact with libjpeg-turbo's IDCT planes (TurboJPEG) and to rgba8 bit-exact with djpeg, and within -- PSNR thresholds of ffmpeg's own decode; an interlaced AVI1 frame (two fields) woven; the yuv420p encoder -- byte-identical to TurboJPEG's tj3CompressFromYUV8, read back by djpeg (exact) and ffmpeg (PSNR); the API's -- arguments; the fuzz no-throw pass. Fixtures: tools/fixtures/mjpeg.py. local T = require("@tests/T") -local Jpeg = require("@formats/codecs/Jpeg") +local Jpeg = require("@formats/codecs/image/Jpeg") local Crc32 = require("@formats/core/Crc32") local Err = require("@formats/core/Err") local Types = require("@formats/Types") local Base64 = require("@formats/core/Base64") -local Deflate = require("@formats/codecs/Deflate") +local Deflate = require("@formats/codecs/compress/Deflate") local Fx = require("@tests/gen/mjpeg_cases") local Enc = require("@tests/gen/mjpeg_enc") diff --git a/tests/codecs/json.luau b/tests/codecs/json.luau index dacb399..630c883 100644 --- a/tests/codecs/json.luau +++ b/tests/codecs/json.luau @@ -1,9 +1,9 @@ --- codecs/Json tests: the JSONTestSuite parsing corpus (y_ must parse to Python's value, n_ must fail, i_ must not +-- codecs/text/Json tests: the JSONTestSuite parsing corpus (y_ must parse to Python's value, n_ must fail, i_ must not -- throw), Python json.dumps output in four styles parsed and reproduced byte for byte (compact sorted, ordered, -- indent 2, ensure_ascii), events / lines / decodeAt / writer, options, error codes, and the fuzz pass. -- Fixtures: tools/fixtures/json.py. local T = require("@tests/T") -local Json = require("@formats/codecs/Json") +local Json = require("@formats/codecs/text/Json") local Types = require("@formats/Types") local Err = require("@formats/core/Err") local Canon = require("@tests/data/Canon") diff --git a/tests/codecs/lzma.luau b/tests/codecs/lzma.luau index 669b265..d4fc522 100644 --- a/tests/codecs/lzma.luau +++ b/tests/codecs/lzma.luau @@ -1,9 +1,9 @@ --- codecs/Lzma tests: every fixture (liblzma through Python's lzma module and the xz CLI: presets 0-9 and -e, lc / lp / +-- codecs/compress/Lzma tests: every fixture (liblzma through Python's lzma module and the xz CLI: presets 0-9 and -e, lc / lp / -- pb variants, raw LZMA1 / LZMA2, .lzma files, xz with every check type, BCJ and delta filters, multiple blocks, -- multiple streams and stream padding) decodes to its corpus; consumed offsets; checksum / size / truncation errors; -- maxBytes; the fuzz no-throw pass. Fixtures: tools/fixtures/lzma.py. local T = require("@tests/T") -local Lzma = require("@formats/codecs/Lzma") +local Lzma = require("@formats/codecs/compress/Lzma") local Err = require("@formats/core/Err") local Fx = require("@tests/gen/lzma") diff --git a/tests/codecs/lzw.luau b/tests/codecs/lzw.luau index 04fe064..29234aa 100644 --- a/tests/codecs/lzw.luau +++ b/tests/codecs/lzw.luau @@ -1,8 +1,8 @@ --- codecs/Lzw tests: GIF (LSB) and TIFF (MSB, early change) code streams from Pillow / libtiff decode to their data; +-- codecs/compress/Lzw tests: GIF (LSB) and TIFF (MSB, early change) code streams from Pillow / libtiff decode to their data; -- our encoder round-trips random and structured data at every GIF minimum code size and through table resets; the -- output limit, truncated and corrupt streams; the fuzz no-throw pass. Fixtures: tools/fixtures/lzw.py. local T = require("@tests/T") -local Lzw = require("@formats/codecs/Lzw") +local Lzw = require("@formats/codecs/compress/Lzw") local Fx = require("@tests/gen/lzw") local t = T.suite("lzw") diff --git a/tests/codecs/mat4.luau b/tests/codecs/mat4.luau new file mode 100644 index 0000000..c7842ec --- /dev/null +++ b/tests/codecs/mat4.luau @@ -0,0 +1,43 @@ +-- codecs/model/Mat4 tests: compose / decompose round trips (with a mirrored axis), strict decompose refusing shear, +-- quaternion <-> matrix, Euler orders, the affine inverse, row-major conversion, points, the normal matrix. +local T = require("@tests/T") +local Mat4 = require("@formats/codecs/model/Mat4") + +local t = T.suite("mat4") + +local function near(a: { number }, b: { number }, eps: number?): boolean + for i = 1, #b do + if math.abs(a[i] - b[i]) > (eps or 1e-9) then + return false + end + end + return true +end + +local q = Mat4.axisAngle(1, 2, 3, 40) +local m = Mat4.compose({ 1, 2, 3 }, q, { 2, -3, 0.5 }) +local tt, rr, ss = Mat4.decompose(m) +local back = Mat4.compose(tt, rr, ss) +t:check(near(back, m, 1e-9), "compose / decompose round trip (negative scale)") +t:check(near(Mat4.quat(Mat4.fromQuat(q)), q, 1e-12) or near(Mat4.quat(Mat4.fromQuat(q)), { -q[1], -q[2], -q[3], -q[4] }, 1e-12), "quat <-> matrix") +local shear = Mat4.identity() +shear[5] = 0.5 +t:check(Mat4.decomposeStrict(shear) == nil, "strict decompose refuses shear") +t:check(Mat4.decompose(shear) ~= nil, "lenient decompose always answers") +local inv = Mat4.inverse(m) :: { number } +t:check(near(Mat4.mul(m, inv), Mat4.identity(), 1e-9), "inverse") +t:check(Mat4.inverse(Mat4.scaling(1, 0, 1)) == nil, "singular") +t:check(near(Mat4.fromRows(Mat4.toRows(m)), m), "rows round trip") +local x, y, z = Mat4.point(Mat4.translation(1, 2, 3), 1, 1, 1) +t:check(x == 2 and y == 3 and z == 4, "point") +-- Euler: "xyz" applies X first (R = Rz * Ry * Rx) +local e = Mat4.euler(10, 20, 30) +local manual = Mat4.mul(Mat4.rotation(3, 30), Mat4.mul(Mat4.rotation(2, 20), Mat4.rotation(1, 10))) +t:check(near(e, manual, 1e-12), "euler xyz") +local ex = Mat4.eulerXYZ(Mat4.quat(e)) +t:check(near(ex, { 10, 20, 30 }, 1e-9), "eulerXYZ") +-- the normal matrix of a non-uniform scale is the inverse scale +t:check(near(Mat4.normalMatrix(Mat4.scaling(2, 4, 8)), Mat4.scaling(0.5, 0.25, 0.125)), "normal matrix") +local rot = Mat4.fromQuat(q) +t:check(near(Mat4.normalMatrix(rot), rot, 1e-12), "normal matrix of a rotation is the rotation") +t:done() diff --git a/tests/codecs/mdct.luau b/tests/codecs/mdct.luau index 82d0e25..d4125fe 100644 --- a/tests/codecs/mdct.luau +++ b/tests/codecs/mdct.luau @@ -1,8 +1,8 @@ --- codecs/Mdct tests: the FFT against a direct DFT for mixed-radix sizes, the forward / inverse MDCT and the DCT-IV +-- codecs/audio/Mdct tests: the FFT against a direct DFT for mixed-radix sizes, the forward / inverse MDCT and the DCT-IV -- against their O(N^2) definitions (AAC, Vorbis and CELT sizes), perfect reconstruction (TDAC) with the sine, KBD and -- Vorbis windows, window power complementarity, bad sizes. No fixtures (the definitions are the reference). local T = require("@tests/T") -local Mdct = require("@formats/codecs/Mdct") +local Mdct = require("@formats/codecs/audio/Mdct") local t = T.suite("mdct") local rand = T.rng(7) diff --git a/tests/codecs/mpeg1.luau b/tests/codecs/mpeg1.luau index 98b57e8..34cafb4 100644 --- a/tests/codecs/mpeg1.luau +++ b/tests/codecs/mpeg1.luau @@ -1,4 +1,4 @@ --- codecs/Mpeg1 tests, ported from mpeg1-luau tests/decode.luau and tests/robust.luau. Against ffmpeg +-- codecs/video/Mpeg1 tests, ported from mpeg1-luau tests/decode.luau and tests/robust.luau. Against ffmpeg -- (tools/fixtures/mpeg1.py): every stream decodes, one access unit at a time, to as many frames as ffmpeg's decode, -- in display order; each frame's RGBA channel means within 1.5 of ffmpeg's; whole sampled frames within 2 MAE per -- channel (IDCT and colour rounding) and, as yuv420p (frameImage), within a PSNR floor of ffmpeg -pix_fmt yuv420p; @@ -7,9 +7,9 @@ -- B-frame reordering, string input, truncated units, bit flips and garbage (never throws, recovers at an -- I-picture), an oversized sequence header; frameImage; the fuzz no-throw pass. local T = require("@tests/T") -local Mpeg1 = require("@formats/codecs/Mpeg1") +local Mpeg1 = require("@formats/codecs/video/Mpeg1") local Base64 = require("@formats/core/Base64") -local Deflate = require("@formats/codecs/Deflate") +local Deflate = require("@formats/codecs/compress/Deflate") local Types = require("@formats/Types") local STREAMS = { diff --git a/tests/codecs/quantize.luau b/tests/codecs/quantize.luau index 7569e55..6c599d1 100644 --- a/tests/codecs/quantize.luau +++ b/tests/codecs/quantize.luau @@ -1,8 +1,8 @@ --- codecs/Quantize tests: palette size bounds for every method and colour budget, the exact (lossless) palette at +-- codecs/image/Quantize tests: palette size bounds for every method and colour budget, the exact (lossless) palette at -- <= maxColors colours, transparency handling, PSNR of quantized images above thresholds, determinism of both -- methods and of Floyd-Steinberg dithering (the same CRC on both runtimes), bad arguments, and a no-throw pass. local T = require("@tests/T") -local Quantize = require("@formats/codecs/Quantize") +local Quantize = require("@formats/codecs/image/Quantize") local Crc32 = require("@formats/core/Crc32") local t = T.suite("quantize") diff --git a/tests/codecs/raster.luau b/tests/codecs/raster.luau index 8103a25..8a83164 100644 --- a/tests/codecs/raster.luau +++ b/tests/codecs/raster.luau @@ -1,9 +1,9 @@ --- codecs/Raster tests: exact coverage of axis-aligned rectangles at fractional positions; areas of circles; random +-- codecs/image/Raster tests: exact coverage of axis-aligned rectangles at fractional positions; areas of circles; random -- polygons and curves under random transforms against an independent 12 x 12 supersampled winding-number reference -- (both fill rules); clipping, the stroker (width, caps, joins against analytic areas), fill() compositing and paint -- functions; malformed paths never throw. Glyph rendering against FreeType is in tests/font/ttf.luau. local T = require("@tests/T") -local R = require("@formats/codecs/Raster") +local R = require("@formats/codecs/image/Raster") local Types = require("@formats/Types") local t = T.suite("raster") diff --git a/tests/codecs/resample.luau b/tests/codecs/resample.luau index 41a62b4..92c79e6 100644 --- a/tests/codecs/resample.luau +++ b/tests/codecs/resample.luau @@ -1,9 +1,9 @@ --- codecs/Resample tests: sines through common rate pairs (44100 <-> 48000, 8000 -> 48000, 48000 -> 22050, an inexact +-- codecs/audio/Resample tests: sines through common rate pairs (44100 <-> 48000, 8000 -> 48000, 48000 -> 22050, an inexact -- ratio) against the analytic signal, alias rejection when downsampling, output lengths, streaming in odd chunks = -- the whole-buffer result, multichannel, a Pcm source wrapper, bad arguments, and a no-throw pass over garbage. local T = require("@tests/T") -local Resample = require("@formats/codecs/Resample") -local Pcm = require("@formats/codecs/Pcm") +local Resample = require("@formats/codecs/audio/Resample") +local Pcm = require("@formats/codecs/audio/Pcm") local Types = require("@formats/Types") local t = T.suite("resample") @@ -92,7 +92,7 @@ do t:check(snr(got, gf, ch, 48000, { 700, 1900 }, 500) > 80, "stereo accuracy") end --- 4. a codecs/Pcm source at a new rate +-- 4. a codecs/audio/Pcm source at a new rate do local a = Types.Audio.new(22050, 1, 5000) a.samples = sine(5000, 1, 22050, { 500 }) diff --git a/tests/codecs/url.luau b/tests/codecs/url.luau index 82075b3..04f35bb 100644 --- a/tests/codecs/url.luau +++ b/tests/codecs/url.luau @@ -1,10 +1,10 @@ --- codecs/Url + codecs/Text tests: every example of RFC 3986 section 5.4 (normal and abnormal), dot-segment removal, +-- codecs/text/Url + codecs/text/Text tests: every example of RFC 3986 section 5.4 (normal and abnormal), dot-segment removal, -- splitting, encoding and the location helpers (ported from playlist-luau tests/url.luau); random references against -- Python's urllib.parse.urljoin; Url.locate / Url.base; Windows-1252 decoding against Python's cp1252 codec; lines, -- BOM, trim; the fuzz pass. Fixtures: tools/fixtures/playlist.py. local T = require("@tests/T") -local Url = require("@formats/codecs/Url") -local Text = require("@formats/codecs/Text") +local Url = require("@formats/codecs/text/Url") +local Text = require("@formats/codecs/text/Text") local Ref = require("@tests/gen/playlist_url") local Cp = require("@tests/gen/playlist_cp1252") diff --git a/tests/codecs/vp8.luau b/tests/codecs/vp8.luau index 8b24ae9..357b2b7 100644 --- a/tests/codecs/vp8.luau +++ b/tests/codecs/vp8.luau @@ -1,9 +1,9 @@ --- codecs/Vp8 tests: the VP8 key frames of the WebP fixtures (cwebp at many settings and libvpx through ffmpeg, with +-- codecs/image/Vp8 tests: the VP8 key frames of the WebP fixtures (cwebp at many settings and libvpx through ffmpeg, with -- 1..8 token partitions) decoded through the codec API: the yuv420p planes against dwebp -yuv, toRgba against -- dwebp -pam (fancy upsampling) and -nofancy, the decoder object over successive frames, headers, error codes and the -- fuzz no-throw pass on raw frames. Fixtures: tools/fixtures/webp.py. local T = require("@tests/T") -local Vp8 = require("@formats/codecs/Vp8") +local Vp8 = require("@formats/codecs/image/Vp8") local Crc32 = require("@formats/core/Crc32") local Err = require("@formats/core/Err") local Cases = require("@tests/gen/webp_cases") diff --git a/tests/codecs/vp8l.luau b/tests/codecs/vp8l.luau index b506cc2..9fbfffa 100644 --- a/tests/codecs/vp8l.luau +++ b/tests/codecs/vp8l.luau @@ -1,9 +1,9 @@ --- codecs/Vp8L tests: the VP8L bitstreams of the WebP fixtures (cwebp -z 0..9, -exact, near-lossless) decoded through +-- codecs/image/Vp8L tests: the VP8L bitstreams of the WebP fixtures (cwebp -z 0..9, -exact, near-lossless) decoded through -- the codec API against dwebp, the encoder at every effort on generated images (gradients, noise, palettes of 1..300 -- colours, odd sizes, alpha), headerless alpha streams, error codes, and the fuzz no-throw pass on raw bitstreams. -- Fixtures: tools/fixtures/webp.py. local T = require("@tests/T") -local Vp8L = require("@formats/codecs/Vp8L") +local Vp8L = require("@formats/codecs/image/Vp8L") local Crc32 = require("@formats/core/Crc32") local Err = require("@formats/core/Err") local Cases = require("@tests/gen/webp_cases") diff --git a/tests/codecs/vp8video.luau b/tests/codecs/vp8video.luau index 3cc2e36..c688c17 100644 --- a/tests/codecs/vp8video.luau +++ b/tests/codecs/vp8video.luau @@ -1,11 +1,11 @@ --- codecs/Vp8 video tests: whole IVF streams through one decoder object, every shown frame bit-exact against ffmpeg's +-- codecs/image/Vp8 video tests: whole IVF streams through one decoder object, every shown frame bit-exact against ffmpeg's -- native vp8 decoder (yuv420p CRC32): the official VP8 test vectors (vp80-00-comprehensive-001..018 and others) and -- libvpx clips at many settings (alt-ref / hidden frames, golden, token partitions, error resilience, profiles 1-3, -- sharpness, segmentation, q extremes, short key frame intervals, motion off the frame, odd sizes). Also hidden -- frames, reset() and inter frames without a key frame, and the fuzz no-throw pass over damaged streams. -- Fixtures: tools/fixtures/vp8video.py. local T = require("@tests/T") -local Vp8 = require("@formats/codecs/Vp8") +local Vp8 = require("@formats/codecs/image/Vp8") local Crc32 = require("@formats/core/Crc32") local Err = require("@formats/core/Err") local Cases = require("@tests/gen/vp8video_cases") diff --git a/tests/codecs/xml.luau b/tests/codecs/xml.luau index dac3f32..76b4a3c 100644 --- a/tests/codecs/xml.luau +++ b/tests/codecs/xml.luau @@ -1,9 +1,9 @@ --- codecs/Xml tests: random documents (namespaces, escapes, CDATA, comments, PIs, DOCTYPE entities, UTF-16, Latin-1) +-- codecs/text/Xml tests: random documents (namespaces, escapes, CDATA, comments, PIs, DOCTYPE entities, UTF-16, Latin-1) -- against Python's ElementTree trees; encode -> decode round trips; well-formedness verdicts against expat -- (hand-written cases and random mutations); events, helpers, options, error codes; the fuzz pass. -- Fixtures: tools/fixtures/xml.py. local T = require("@tests/T") -local Xml = require("@formats/codecs/Xml") +local Xml = require("@formats/codecs/text/Xml") local Types = require("@formats/Types") local Err = require("@formats/core/Err") local Docs = require("@tests/gen/xml_docs") diff --git a/tests/codecs/zstd.luau b/tests/codecs/zstd.luau index 8e25cf6..34978b9 100644 --- a/tests/codecs/zstd.luau +++ b/tests/codecs/zstd.luau @@ -1,9 +1,9 @@ --- codecs/Zstd tests: every fixture case (the zstd CLI at levels 1..19, --ultra -22, --fast, --long, small windows, +-- codecs/compress/Zstd tests: every fixture case (the zstd CLI at levels 1..19, --ultra -22, --fast, --long, small windows, -- with / without checksum and content size, multi-frame and skippable frames, empty input) decodes to its corpus; -- offsets / consumedEnd; XXH64 vectors; checksum, limit and error codes; truncated / corrupted / random input never -- throws. Fixtures: tools/fixtures/zstd.py. local T = require("@tests/T") -local Zstd = require("@formats/codecs/Zstd") +local Zstd = require("@formats/codecs/compress/Zstd") local Err = require("@formats/core/Err") local Fx = require("@tests/gen/zstd") diff --git a/tests/containers/chunks.luau b/tests/containers/chunks.luau new file mode 100644 index 0000000..7ae2d64 --- /dev/null +++ b/tests/containers/chunks.luau @@ -0,0 +1,76 @@ +-- containers/Chunks tests: RIFF (padding, an odd chunk without its pad byte, open-ended data), IFF big-endian, PNG +-- (size first + CRC trailer, truncation), CAF 64-bit sizes, resize hooks, find, and a no-throw pass over garbage. +local T = require("@tests/T") +local Chunks = require("@formats/containers/Chunks") + +local t = T.suite("chunks") + +local function le32(n: number): string + return string.char(n % 256, (n // 256) % 256, (n // 65536) % 256, (n // 16777216) % 256) +end +local function be32(n: number): string + return string.char((n // 16777216) % 256, (n // 65536) % 256, (n // 256) % 256, n % 256) +end + +-- RIFF: an odd chunk with its pad byte, then one without +do + local s = "abcd" .. le32(3) .. "xyz\0" .. "efgh" .. le32(1) .. "Q" .. "ijkl" .. le32(2) .. "12" + local list = Chunks.walk(buffer.fromstring(s), 0, #s, Chunks.RIFF) + t:eq(#list, 3, "riff: three chunks") + t:check(list[1].id == "abcd" and list[1].offset == 8 and list[1].size == 3, "riff: first") + t:check(list[2].id == "efgh" and list[2].size == 1, "riff: an odd chunk") + t:check(list[3].id == "ijkl" and list[3].offset == 29 and list[3].avail == 2, "riff: missing pad byte detected") + t:eq((Chunks.find(list, "efgh") :: any).start, 12, "find") + -- open-ended data with size 0, and a declared size past the end + local o = "fmt " .. le32(2) .. "ab" .. "data" .. le32(0) .. "123456" + local l2 = Chunks.walk(buffer.fromstring(o), 0, #o, { pad = 2, openEnded = { data = true } }) + t:check(l2[2].streamed and l2[2].size == 6, "open-ended data") + local tr = "data" .. le32(100) .. "abc" + local l3 = Chunks.walk(buffer.fromstring(tr), 0, #tr, Chunks.RIFF) + t:check(l3[1].truncated and l3[1].avail == 3 and l3[1].size == 100, "truncated chunk keeps what is there") + local l4 = Chunks.walk(buffer.fromstring(o), 0, #o, { pad = 2, resize = function(id: string, n: number) + return if id == "fmt " then 1 else nil + end }) + t:eq(l4[1].size, 1, "resize hook") +end + +-- IFF (big-endian sizes) +do + local s = "COMM" .. be32(2) .. "ab" .. "SSND" .. be32(3) .. "xyz\0" + local list = Chunks.walk(buffer.fromstring(s), 0, #s, Chunks.IFF) + t:check(#list == 2 and list[2].id == "SSND" and list[2].size == 3, "iff") +end + +-- PNG: size, type, data, CRC +do + local s = be32(2) .. "IHDR" .. "ab" .. "CRC!" .. be32(0) .. "IEND" .. "CRC?" + local list = Chunks.walk(buffer.fromstring(s), 0, #s, Chunks.PNG) + t:check(#list == 2 and list[1].id == "IHDR" and list[1].offset == 8 and list[2].id == "IEND" and list[2].start == 14, "png") + local cut = string.sub(s, 1, 12) + local l2 = Chunks.walk(buffer.fromstring(cut), 0, #cut, Chunks.PNG) + t:check(l2[1].truncated, "png: a missing CRC is a truncation") +end + +-- CAF: 64-bit big-endian sizes +do + local s = "desc" .. be32(0) .. be32(4) .. "abcd" .. "data" .. be32(0) .. be32(2) .. "xy" + local list = Chunks.walk(buffer.fromstring(s), 0, #s, Chunks.CAF) + t:check(#list == 2 and list[2].offset == 28 and list[2].size == 2, "caf") +end + +-- an offset range inside a bigger buffer +do + local s = "junk" .. "abcd" .. le32(1) .. "x\0" .. "tail" + local list = Chunks.walk(buffer.fromstring(s), 4, 14, Chunks.RIFF) + t:check(#list == 1 and list[1].offset == 12, "a sub-range") +end + +local samples = { "abcd" .. le32(3) .. "xyz\0efgh" .. le32(1) .. "Q", be32(2) .. "IHDRabCRC!" } +t:fuzz("walk", function(b: buffer) + local n = 0 + for _, layout in { Chunks.RIFF, Chunks.IFF, Chunks.PNG, Chunks.CAF } do + n += #Chunks.walk(b, 0, buffer.len(b), layout) + end + return n +end, samples) +t:done() diff --git a/tests/core/bits.luau b/tests/core/bits.luau index 000d7dc..6904cf7 100644 --- a/tests/core/bits.luau +++ b/tests/core/bits.luau @@ -1,9 +1,9 @@ --- core/Bits and core/Huffman tests: LSB / MSB readers and writers round-trip random fields of 1..32 bits, align / +-- core/Bits and codecs/entropy/Huffman tests: LSB / MSB readers and writers round-trip random fields of 1..32 bits, align / -- peek / bytePos, overrun is a sticky error; canonical codes, length-limited code lengths, LSB and MSB decoding tables -- (with subtables) decode what the writers wrote; invalid code sets are rejected. local T = require("@tests/T") local Bits = require("@formats/core/Bits") -local Huffman = require("@formats/core/Huffman") +local Huffman = require("@formats/codecs/entropy/Huffman") local Err = require("@formats/core/Err") local t = T.suite("bits") diff --git a/tests/data/xml.luau b/tests/data/xml.luau index 6edbe02..1db3bf7 100644 --- a/tests/data/xml.luau +++ b/tests/data/xml.luau @@ -4,7 +4,7 @@ local T = require("@tests/T") local F = require("@formats") local XmlF = require("@formats/data/xml") -local Xml = require("@formats/codecs/Xml") +local Xml = require("@formats/codecs/text/Xml") local Bytes = require("@formats/core/Bytes") local Err = require("@formats/core/Err") local Docs = require("@tests/gen/xml_docs") diff --git a/tests/data/yaml.luau b/tests/data/yaml.luau index e804e39..ddf4ee2 100644 --- a/tests/data/yaml.luau +++ b/tests/data/yaml.luau @@ -5,7 +5,7 @@ local T = require("@tests/T") local F = require("@formats") local Yaml = require("@formats/data/yaml") -local Json = require("@formats/codecs/Json") +local Json = require("@formats/codecs/text/Json") local Types = require("@formats/Types") local Bytes = require("@formats/core/Bytes") local Err = require("@formats/core/Err") diff --git a/tests/font/ttf.luau b/tests/font/ttf.luau index 5d78823..22cc530 100644 --- a/tests/font/ttf.luau +++ b/tests/font/ttf.luau @@ -1,11 +1,11 @@ --- font/ttf tests (and codecs/TrueType, codecs/Cff): for the imgui-luau TrueType fonts, Source Sans 3 (CFF), a +-- font/ttf tests (and codecs/font/TrueType, codecs/font/Cff): for the imgui-luau TrueType fonts, Source Sans 3 (CFF), a -- 'kern'-table font and a collection: metrics, names, cmap samples, advances / side bearings, outline control boxes and -- areas against fontTools; kerning against HarfBuzz (GPOS) and FreeType ('kern'); rasterize() against FreeType's -- unhinted renders (PSNR); the api; errors; the fuzz pass. Fixtures: tools/fixtures/fonts.py. local T = require("@tests/T") local F = require("@formats") local Ttf = require("@formats/font/ttf") -local Raster = require("@formats/codecs/Raster") +local Raster = require("@formats/codecs/image/Raster") local Bytes = require("@formats/core/Bytes") local Err = require("@formats/core/Err") local Fx = require("@tests/gen/fonts") diff --git a/tests/music/it.luau b/tests/music/it.luau index b06ac8b..81047f2 100644 --- a/tests/music/it.luau +++ b/tests/music/it.luau @@ -1,10 +1,10 @@ --- music/it tests: generated Impulse Tracker modules (tools/fixtures/it.py) parsed, rendered through codecs/Tracker and +-- music/it tests: generated Impulse Tracker modules (tools/fixtures/it.py) parsed, rendered through codecs/audio/Tracker and -- compared with openmpt123's render (loudness envelope, band spectrum, stereo balance, song length), the contract, -- and the fuzz no-throw pass. local T = require("@tests/T") local S = require("@tests/music/_similar") local It = require("@formats/music/it") -local Tracker = require("@formats/codecs/Tracker") +local Tracker = require("@formats/codecs/audio/Tracker") local Bytes = require("@formats/core/Bytes") local Cases = require("@tests/gen/it_cases") diff --git a/tests/music/mod.luau b/tests/music/mod.luau index 79e8941..2e3250d 100644 --- a/tests/music/mod.luau +++ b/tests/music/mod.luau @@ -1,10 +1,10 @@ --- music/mod tests: generated ProTracker modules (tools/fixtures/mod.py) parsed, rendered through codecs/Tracker and +-- music/mod tests: generated ProTracker modules (tools/fixtures/mod.py) parsed, rendered through codecs/audio/Tracker and -- compared with openmpt123's render (loudness envelope, band spectrum, stereo balance, song length), the MOD writer's -- round trip, the contract, and the fuzz no-throw pass. local T = require("@tests/T") local S = require("@tests/music/_similar") local Mod = require("@formats/music/mod") -local Tracker = require("@formats/codecs/Tracker") +local Tracker = require("@formats/codecs/audio/Tracker") local Bytes = require("@formats/core/Bytes") local Cases = require("@tests/gen/mod_cases") diff --git a/tests/music/s3m.luau b/tests/music/s3m.luau index ddff1a5..aff1f5f 100644 --- a/tests/music/s3m.luau +++ b/tests/music/s3m.luau @@ -1,10 +1,10 @@ --- music/s3m tests: generated Scream Tracker 3 modules (tools/fixtures/s3m.py) parsed, rendered through codecs/Tracker and +-- music/s3m tests: generated Scream Tracker 3 modules (tools/fixtures/s3m.py) parsed, rendered through codecs/audio/Tracker and -- compared with openmpt123's render (loudness envelope, band spectrum, stereo balance, song length), the contract, -- and the fuzz no-throw pass. local T = require("@tests/T") local S = require("@tests/music/_similar") local S3m = require("@formats/music/s3m") -local Tracker = require("@formats/codecs/Tracker") +local Tracker = require("@formats/codecs/audio/Tracker") local Bytes = require("@formats/core/Bytes") local Cases = require("@tests/gen/s3m_cases") diff --git a/tests/music/sf2.luau b/tests/music/sf2.luau index 057b30e..2059c4b 100644 --- a/tests/music/sf2.luau +++ b/tests/music/sf2.luau @@ -1,11 +1,11 @@ --- music/sf2 + codecs/SoundFont tests: a self-made SF2 parsed (INFO, presets, sample headers, instruments, generator +-- music/sf2 + codecs/audio/SoundFont tests: a self-made SF2 parsed (INFO, presets, sample headers, instruments, generator -- merging with preset / instrument global zones, 16-bit and sm24 samples), a test song rendered through it compared -- with FluidSynth's render (loudness envelope and per-segment band spectra by correlation, pitch peaks), bad files, -- the built-in fallback waveform set, and the fuzz no-throw pass. Fixtures: tools/fixtures/sf2.py. local T = require("@tests/T") local Sf2 = require("@formats/music/sf2") local Midi = require("@formats/music/midi") -local SoundFont = require("@formats/codecs/SoundFont") +local SoundFont = require("@formats/codecs/audio/SoundFont") local Bytes = require("@formats/core/Bytes") local Err = require("@formats/core/Err") local Fx = require("@tests/gen/sf2_cases") diff --git a/tests/music/xm.luau b/tests/music/xm.luau index b117848..0afd6e2 100644 --- a/tests/music/xm.luau +++ b/tests/music/xm.luau @@ -1,10 +1,10 @@ --- music/xm tests: generated FastTracker 2 modules (tools/fixtures/xm.py) parsed, rendered through codecs/Tracker and +-- music/xm tests: generated FastTracker 2 modules (tools/fixtures/xm.py) parsed, rendered through codecs/audio/Tracker and -- compared with openmpt123's render (loudness envelope, band spectrum, stereo balance, song length), the XM writer's -- round trip, the contract, and the fuzz no-throw pass. local T = require("@tests/T") local S = require("@tests/music/_similar") local Xm = require("@formats/music/xm") -local Tracker = require("@formats/codecs/Tracker") +local Tracker = require("@formats/codecs/audio/Tracker") local Bytes = require("@formats/core/Bytes") local Cases = require("@tests/gen/xm_cases") diff --git a/tests/ops/audioops.luau b/tests/ops/audioops.luau index 1966ae1..c4840b4 100644 --- a/tests/ops/audioops.luau +++ b/tests/ops/audioops.luau @@ -1,10 +1,10 @@ -- ops/AudioOps tests: toAudio from a Decoder, gain / gainDb / normalize, peak / RMS of known signals, remix matrices --- (5.1 -> stereo -> mono, mono -> stereo / 5.1), resample through codecs/Resample, trim, concat and mix with rate / +-- (5.1 -> stereo -> mono, mono -> stereo / 5.1), resample through codecs/audio/Resample, trim, concat and mix with rate / -- channel conversion, fades, bad arguments (Err.ARG, never a throw), and the F.ops facade. local T = require("@tests/T") local AudioOps = require("@formats/ops/AudioOps") local Types = require("@formats/Types") -local Pcm = require("@formats/codecs/Pcm") +local Pcm = require("@formats/codecs/audio/Pcm") local Err = require("@formats/core/Err") local F = require("@formats") diff --git a/tests/ops/layerops.luau b/tests/ops/layerops.luau index 94f4692..1a12b03 100644 --- a/tests/ops/layerops.luau +++ b/tests/ops/layerops.luau @@ -1,9 +1,9 @@ --- ops/LayerOps + codecs/Blend tests: blend mode formulas on single pixels against hand-computed W3C values, opacity, +-- ops/LayerOps + codecs/image/Blend tests: blend mode formulas on single pixels against hand-computed W3C values, opacity, -- masks, clipping, isolated vs pass-through groups, hidden layers, frames, leaves, bad arguments. (Whole-document -- flattening against psd-tools is in tests/layered/psd.luau.) local T = require("@tests/T") local LayerOps = require("@formats/ops/LayerOps") -local Blend = require("@formats/codecs/Blend") +local Blend = require("@formats/codecs/image/Blend") local Types = require("@formats/Types") local Err = require("@formats/core/Err") diff --git a/tests/video/_common.luau b/tests/video/_common.luau index e8aaae7..39902ed 100644 --- a/tests/video/_common.luau +++ b/tests/video/_common.luau @@ -4,7 +4,7 @@ local F = require("@formats") local Bytes = require("@formats/core/Bytes") local Crc32 = require("@formats/core/Crc32") -local Video = require("@formats/codecs/Video") +local Video = require("@formats/codecs/video/Video") local C = {} diff --git a/tools/bench.luau b/tools/bench.luau index f6d624f..b32ee01 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -3,7 +3,7 @@ -- tools/fixtures/opus.py (3 s stereo files; MB/s of f32 output, 48 kHz stereo f32 is 0.384 MB/s of real time), -- tools/fixtures/flac.py; wav encodes / decodes a generated tone; zstd / brotli / bzip2 / lzma (*_bench corpora), fonts -- (glyphs per second), json / xml / yaml, jpeg / gif / tiff / qoi / tga / pnm / hdr and ImageOps. -local Deflate = require("@formats/codecs/Deflate") +local Deflate = require("@formats/codecs/compress/Deflate") local Crc32 = require("@formats/core/Crc32") local Bytes = require("@formats/core/Bytes") local Png = require("@formats/image/png") @@ -189,7 +189,7 @@ do print(string.format("%-8s %-30s %8.1fx real time", runtime, "", 10 / dt)) end do - local Json = require("@formats/codecs/Json") + local Json = require("@formats/codecs/text/Json") local JB = require("@tests/gen/json_bench") local v = assert(Json.decode(JB.text)) assert(Json.encode(v) == JB.compact, "json bench mismatch") @@ -204,7 +204,7 @@ do end) end do - local Xml = require("@formats/codecs/Xml") + local Xml = require("@formats/codecs/text/Xml") local XB = require("@tests/gen/xml_bench") local doc = assert(Xml.decode(XB.text)) bench("xml decode (DOM)", 5, #XB.text, function() @@ -221,7 +221,7 @@ end -- ws-arch codecs: zstd, brotli, bzip2, xz / lzma do - local Zstd = require("@formats/codecs/Zstd") + local Zstd = require("@formats/codecs/compress/Zstd") local ZB = require("@tests/gen/zstd_bench") local z3, z19 = buffer.fromstring(ZB.data3), buffer.fromstring(ZB.data19) local zo = assert(Zstd.decompress(z3)) @@ -237,7 +237,7 @@ do end) end do - local Brotli = require("@formats/codecs/Brotli") + local Brotli = require("@formats/codecs/compress/Brotli") local BB = require("@tests/gen/brotli_bench") local bz = buffer.fromstring(BB.data) local bout = assert(Brotli.decompress(bz)) @@ -247,7 +247,7 @@ do end) end do - local Bzip2 = require("@formats/codecs/Bzip2") + local Bzip2 = require("@formats/codecs/compress/Bzip2") local BZ = require("@tests/gen/bzip2_bench") local bz = buffer.fromstring(BZ.data) bench("bzip2 decompress -9", 3, BZ.size, function() @@ -255,7 +255,7 @@ do end) end do - local Lzma = require("@formats/codecs/Lzma") + local Lzma = require("@formats/codecs/compress/Lzma") local LB = require("@tests/gen/lzma_bench") local lx, la = buffer.fromstring(LB.xz), buffer.fromstring(LB.alone) local lo = assert(Lzma.xz(lx)) @@ -332,7 +332,7 @@ end -- ---------------------------------------------------------------------------------------- ws-imgA: gif + quantize do local Gif = require("@formats/image/gif") - local Quantize = require("@formats/codecs/Quantize") + local Quantize = require("@formats/codecs/image/Quantize") local Types = require("@formats/Types") local GB = require("@tests/gen/gif_bench") local still = buffer.fromstring(GB.still) @@ -544,8 +544,8 @@ do end) end do - -- layered + vector (ws-vec): PSD decode / encode of 8 RGBA layers 1024 x 768, flatten (codecs/Blend), SVG - -- rasterize at 512 x 512 (codecs/Raster). No fixtures: the inputs are built here. + -- layered + vector (ws-vec): PSD decode / encode of 8 RGBA layers 1024 x 768, flatten (codecs/image/Blend), SVG + -- rasterize at 512 x 512 (codecs/image/Raster). No fixtures: the inputs are built here. local Types = require("@formats/Types") local Psd = require("@formats/layered/psd") local LayerOps = require("@formats/ops/LayerOps") @@ -608,7 +608,7 @@ do end) end do - local Xml = require("@formats/codecs/Xml") + local Xml = require("@formats/codecs/text/Xml") local XB = require("@tests/gen/xml_bench") local doc = assert(Xml.decode(XB.text)) bench("xml decode (DOM)", 5, #XB.text, function() @@ -626,8 +626,8 @@ end -- ws-m4a: AAC-LC / ALAC decode and ALAC encode (MB/s of 16-bit PCM equivalent: frames * channels * 2), MDCT do local M4a = require("@formats/audio/m4a") - local Alac = require("@formats/codecs/Alac") - local Mdct = require("@formats/codecs/Mdct") + local Alac = require("@formats/codecs/audio/Alac") + local Mdct = require("@formats/codecs/audio/Mdct") local MA = require("@tests/gen/m4a_aac") local ML = require("@tests/gen/m4a_alac") local aac = buffer.fromstring(MA[1].data) @@ -709,7 +709,7 @@ do end -- the synth's per-voice cost: 32 sustained, filtered, looped voices (sf2 saw preset with a mod env) for 2 s do - local SoundFont = require("@formats/codecs/SoundFont") + local SoundFont = require("@formats/codecs/audio/SoundFont") local Sf2 = require("@formats/music/sf2") local SF = require("@tests/gen/sf2_cases") local sf = assert(Sf2.decode(Bytes.reader(buffer.fromstring(SF.sf2)))) @@ -734,7 +734,7 @@ end -- the tracker engine: 32 channels of looped samples (one note each, linear interpolation, volume ramps), and an -- IT-style module with background voices (NNA continue) and resonant filters on every channel do - local Tracker = require("@formats/codecs/Tracker") + local Tracker = require("@formats/codecs/audio/Tracker") local function song(format: string, filter: boolean): any local m = Tracker.newModule(format, 32) m.order = { 0 } @@ -913,8 +913,8 @@ do end -- ------------------------------------------------------------------------------------------- ws-video-codecs: fps do - local Jpeg = require("@formats/codecs/Jpeg") - local Mpeg1 = require("@formats/codecs/Mpeg1") + local Jpeg = require("@formats/codecs/image/Jpeg") + local Mpeg1 = require("@formats/codecs/video/Mpeg1") local Base64 = require("@formats/core/Base64") local Types = require("@formats/Types") local MB = require("@tests/gen/mjpeg_bench") @@ -1023,10 +1023,10 @@ do end -- ------------------------------------------------------------------------------------------- ws-video-vp8: fps do - -- VP8 video (codecs/Vp8, tools/fixtures/vp8video.py): whole IVF streams (libvpx, panning testsrc2) through one + -- VP8 video (codecs/image/Vp8, tools/fixtures/vp8video.py): whole IVF streams (libvpx, panning testsrc2) through one -- decoder object; frames per second. On LuaJIT the library's host module raises the trace limits (maxtrace=8000, -- see src/Formats/host/init.luau): the second pair of lines runs with them, as the api does. - local Vp8 = require("@formats/codecs/Vp8") + local Vp8 = require("@formats/codecs/image/Vp8") local VB = require("@tests/gen/vp8video_bench") local function run(tag: string) for _, c in VB do @@ -1056,10 +1056,10 @@ do end end do - -- H.264 (codecs/H264): whole Annex B streams, frames per second (decode + the cropped yuv420p output copies). The + -- H.264 (codecs/video/H264): whole Annex B streams, frames per second (decode + the cropped yuv420p output copies). The -- testsrc2 clips are easy (mostly static); the mandelbrot zooms move everywhere. LuaJIT runs twice: with its default -- trace limits and with the ones host/init.luau sets (maxtrace=8000, maxmcode=65536). - local H264 = require("@formats/codecs/H264") + local H264 = require("@formats/codecs/video/H264") local HB = require("@tests/gen/h264_bench") local function run(tag: string) for _, c in HB do diff --git a/tools/brotli_static.py b/tools/brotli_static.py index f0cecb3..f2b020d 100644 --- a/tools/brotli_static.py +++ b/tools/brotli_static.py @@ -1,6 +1,6 @@ #!/usr/bin/env python3 # Brotli static data generator (python3 -I tools/brotli_static.py [brotli-source-dir]): writes -# src/Formats/codecs/Brotli/Static.luau from the official brotli C sources (MIT; licenses/brotli-LICENSE.txt): +# src/Formats/codecs/compress/Brotli/Static.luau from the official brotli C sources (MIT; licenses/brotli-LICENSE.txt): # the 122784-byte RFC 7932 static dictionary (c/common/dictionary_inc.h, stored deflated + base64), the context # lookup table (c/common/context.c) and the 121 word transforms (c/common/transform.c). # Without an argument the source comes from `nix build nixpkgs#brotli.src`. @@ -51,7 +51,7 @@ def main(): z = zlib.compress(dictionary, 9) lines = [ "--!strict", - "-- codecs/Brotli/Static: GENERATED by tools/brotli_static.py from the brotli C sources (MIT, Google; see", + "-- codecs/compress/Brotli/Static: GENERATED by tools/brotli_static.py from the brotli C sources (MIT, Google; see", "-- licenses/brotli-LICENSE.txt) - do not edit. The RFC 7932 static dictionary (122784 bytes, deflated, base64),", "-- the context lookup table (Appendix B, 4 modes x 512) and the 121 word transforms (Appendix B).", "return {", diff --git a/tools/fixtures/3mf.py b/tools/fixtures/3mf.py index d763398..4ba89b5 100644 --- a/tools/fixtures/3mf.py +++ b/tools/fixtures/3mf.py @@ -9,7 +9,7 @@ # lib3mf / assimp / trimesh: { name, case, lib3mf, assimp, trimesh } import importlib.util, json, os, subprocess, sys -INPUTS = ["src/Formats/model/3mf", "src/Formats/codecs/Xml", "src/Formats/containers/Zip", +INPUTS = ["src/Formats/model/3mf", "src/Formats/codecs/text/Xml", "src/Formats/containers/Zip", "tools/fixtures/_3mf_reference.py", "tools/fixtures/_3mf_encode.luau", "tools/fixtures/_model_ref.py"] MAX_SIZE = 500_000 diff --git a/tools/fixtures/7z.py b/tools/fixtures/7z.py index aa4d0c4..ffb62a8 100644 --- a/tools/fixtures/7z.py +++ b/tools/fixtures/7z.py @@ -1,7 +1,7 @@ # 7z fixtures (tools/fixtures.py): a small tree (text, x86 machine code, runs, an empty file, empty and nested # directories, UTF-16 names with accents and a surrogate pair) archived by 7-Zip 2x (nix _7zz) with many method chains: # LZMA / LZMA2 / copy / Deflate, solid and non-solid, BCJ / ARM64 / delta filters, plain and compressed headers; plus -# BZip2 archives (codecs/Bzip2), archives whose methods are not supported (PPMd, BCJ2, AES) and an empty archive. +# BZip2 archives (codecs/compress/Bzip2), archives whose methods are not supported (PPMd, BCJ2, AES) and an empty archive. # tests/gen/7z.luau { files = { { name, dir, data?, mtime } }, cases = { { name, data, unsupported? } } } import os, random, subprocess, sys, tempfile diff --git a/tools/fixtures/_audio.py b/tools/fixtures/_audio.py index 566ce86..53a9568 100644 --- a/tools/fixtures/_audio.py +++ b/tools/fixtures/_audio.py @@ -219,11 +219,11 @@ def emit_signal(ctx, name, samples, rate, ch): def encode_luau(ctx, module, sigmod, opts_lua="nil", source="audio"): """encode the emitted signal module `sigmod` with require("@formats/<module>").encode(audio, opts) in Luau; returns - the encoded bytes. source = "decoder" feeds a streaming Decoder (codecs/Pcm.audioDecoder) instead of the Audio.""" + the encoded bytes. source = "decoder" feeds a streaming Decoder (codecs/audio/Pcm.audioDecoder) instead of the Audio.""" code = """ local S = require("@tests/gen/%s") local Types = require("@formats/Types") -local Pcm = require("@formats/codecs/Pcm") +local Pcm = require("@formats/codecs/audio/Pcm") local M = require("@formats/%s") local a = Types.Audio.new(S.rate, S.channels, S.frames) buffer.writestring(a.samples, 0, S.data) diff --git a/tools/fixtures/aiff.py b/tools/fixtures/aiff.py index 15fbdb2..1dafc07 100644 --- a/tools/fixtures/aiff.py +++ b/tools/fixtures/aiff.py @@ -10,7 +10,7 @@ _spec = importlib.util.spec_from_file_location("_audio", os.path.join(os.path.di A = importlib.util.module_from_spec(_spec) _spec.loader.exec_module(A) -INPUTS = ["src/Formats/audio/aiff", "src/Formats/codecs/Pcm"] +INPUTS = ["src/Formats/audio/aiff", "src/Formats/codecs/audio/Pcm"] def ff(codec, src="{in}", extra=()): diff --git a/tools/fixtures/aseprite.py b/tools/fixtures/aseprite.py index 4624623..e5942f2 100644 --- a/tools/fixtures/aseprite.py +++ b/tools/fixtures/aseprite.py @@ -8,7 +8,7 @@ # rendered by LibreSprite, with our flatten of the same frames import json, os, shutil, struct, subprocess, tempfile, zlib -INPUTS = ["src/Formats/layered/aseprite", "src/Formats/codecs/Blend.luau", "tools/fixtures/_ours.luau"] +INPUTS = ["src/Formats/layered/aseprite", "src/Formats/codecs/image/Blend.luau", "tools/fixtures/_ours.luau"] def s(text): diff --git a/tools/fixtures/au.py b/tools/fixtures/au.py index eb34539..938d4a0 100644 --- a/tools/fixtures/au.py +++ b/tools/fixtures/au.py @@ -10,7 +10,7 @@ _spec = importlib.util.spec_from_file_location("_audio", os.path.join(os.path.di A = importlib.util.module_from_spec(_spec) _spec.loader.exec_module(A) -INPUTS = ["src/Formats/audio/au", "src/Formats/codecs/Pcm"] +INPUTS = ["src/Formats/audio/au", "src/Formats/codecs/audio/Pcm"] def ff(codec, src="{in}", extra=()): diff --git a/tools/fixtures/dae.py b/tools/fixtures/dae.py index e8c4430..ba527a3 100644 --- a/tools/fixtures/dae.py +++ b/tools/fixtures/dae.py @@ -8,7 +8,7 @@ # { name, case, assimp } import importlib.util, os, re, subprocess -INPUTS = ["src/Formats/model/dae", "src/Formats/codecs/Xml", "tools/fixtures/_model_ref.py", "tools/fixtures/_dae_encode.luau", +INPUTS = ["src/Formats/model/dae", "src/Formats/codecs/text/Xml", "tools/fixtures/_model_ref.py", "tools/fixtures/_dae_encode.luau", "tests/fixtures/gltf"] diff --git a/tools/fixtures/fbx.py b/tools/fixtures/fbx.py index 726ea2a..f60220f 100644 --- a/tools/fixtures/fbx.py +++ b/tools/fixtures/fbx.py @@ -10,7 +10,7 @@ # tests/gen/fbx_gltf.luau glTF sample models (tests/fixtures/gltf) for the writer round trips: { name, data, files } import importlib.util, json, os, shutil, subprocess -INPUTS = ["src/Formats/model/fbx", "tests/fixtures/gltf", "src/Formats/codecs/Deflate", "tools/fixtures/_model_ref.py", +INPUTS = ["src/Formats/model/fbx", "tests/fixtures/gltf", "src/Formats/codecs/compress/Deflate", "tools/fixtures/_model_ref.py", "tools/fixtures/_fbx_blender.py", "tools/fixtures/_fbx_blender_stats.py", "tools/fixtures/_fbx_encode.luau"] diff --git a/tools/fixtures/flac_enc.py b/tools/fixtures/flac_enc.py index 19cf672..71f9bbb 100644 --- a/tools/fixtures/flac_enc.py +++ b/tools/fixtures/flac_enc.py @@ -10,7 +10,7 @@ _spec = importlib.util.spec_from_file_location("_audio", os.path.join(os.path.di A = importlib.util.module_from_spec(_spec) _spec.loader.exec_module(A) -INPUTS = ["src/Formats/audio/flac", "src/Formats/codecs/Pcm", "src/Formats/core/Md5.luau"] +INPUTS = ["src/Formats/audio/flac", "src/Formats/codecs/audio/Pcm", "src/Formats/core/Md5.luau"] def pcm_bytes(samples, bits): diff --git a/tools/fixtures/gltf.py b/tools/fixtures/gltf.py index 3172723..95a3b60 100644 --- a/tools/fixtures/gltf.py +++ b/tools/fixtures/gltf.py @@ -8,7 +8,7 @@ # by assimp and trimesh: { name, case, assimp, trimesh } import importlib.util, json, os, struct -INPUTS = ["tests/fixtures/gltf", "src/Formats/model/gltf", "src/Formats/codecs/Json", "src/Formats/core/Base64", +INPUTS = ["tests/fixtures/gltf", "src/Formats/model/gltf", "src/Formats/codecs/text/Json", "src/Formats/core/Base64", "tools/fixtures/_model_ref.py", "tools/fixtures/_gltf_encode.luau"] diff --git a/tools/fixtures/json.py b/tools/fixtures/json.py index 52776b6..7967219 100644 --- a/tools/fixtures/json.py +++ b/tools/fixtures/json.py @@ -1,4 +1,4 @@ -# codecs/Json + data/json fixtures: the JSONTestSuite parsing corpus (nst/JSONTestSuite, pinned tarball through nix) +# codecs/text/Json + data/json fixtures: the JSONTestSuite parsing corpus (nst/JSONTestSuite, pinned tarball through nix) # with Python's json verdicts and canonical values, plus a random corpus written by Python's json.dumps in several # styles (compact sorted, insertion order, indent 2, ensure_ascii) that the tests must parse and reproduce exactly. # tests/gen/json_suite.luau { { name, expect = "y" | "n" | "i", data, canon? } } diff --git a/tools/fixtures/m4a.py b/tools/fixtures/m4a.py index 8ffe43e..582693f 100644 --- a/tools/fixtures/m4a.py +++ b/tools/fixtures/m4a.py @@ -16,7 +16,7 @@ _sig = importlib.util.module_from_spec(_spec) _spec.loader.exec_module(_sig) signal, pack, wav = _sig.signal, _sig.pack, _sig.wav -INPUTS = ["src/Formats/audio/m4a", "src/Formats/audio/caf", "src/Formats/codecs/Alac", "src/Formats/containers/IsoBmff", +INPUTS = ["src/Formats/audio/m4a", "src/Formats/audio/caf", "src/Formats/codecs/audio/Alac", "src/Formats/containers/IsoBmff", "tests/audio/_signal.luau", "tests/audio/_encode_cases.luau", "tools/fixtures/_m4a_encode.luau", "tools/fixtures/_m4a_signal.py"] PKGS = ["ffmpeg", "fdk-aac-encoder", "gpac"] diff --git a/tools/fixtures/mjpeg.py b/tools/fixtures/mjpeg.py index 258ca8a..e975e37 100644 --- a/tools/fixtures/mjpeg.py +++ b/tools/fixtures/mjpeg.py @@ -1,6 +1,6 @@ -# Motion-JPEG fixtures for codecs/Jpeg (tools/fixtures.py): ffmpeg's mjpeg encoder (testsrc2 / mandelbrot sources, +# Motion-JPEG fixtures for codecs/image/Jpeg (tools/fixtures.py): ffmpeg's mjpeg encoder (testsrc2 / mandelbrot sources, # yuvj420p / yuvj422p / yuvj444p, odd sizes) split into its JPEG frames, and references for each frame: -# yuv CRC-32 of the yuv420p planes codecs/Jpeg must produce with { yuv = true }: libjpeg-turbo's own IDCT planes +# yuv CRC-32 of the yuv420p planes codecs/image/Jpeg must produce with { yuv = true }: libjpeg-turbo's own IDCT planes # (TurboJPEG tj3DecompressToYUV8 through ctypes, the islow IDCT), cropped, 4:2:2 chroma row pairs averaged # ((a + b + 1) >> 1), 4:4:4 chroma 2 x 2 averaged ((a + b + c + d + 2) >> 2): bit-exact # rgba CRC-32 of djpeg -dct int (bit-exact) @@ -14,7 +14,7 @@ # tests/gen/mjpeg_enc.luau yuv420p sources and what tj3CompressFromYUV8 writes for them at a quality (our # encoder must write the same bytes), with djpeg's CRC and ffmpeg's PSNR of that file # tests/gen/mjpeg_bench.luau 320x240 and 640x480 frames (4:2:0, 4:2:2) and yuv420p sources -# Binary fields are base64 (JPEG data) or base64 of zlib data (raw planes / pixels, inflated with codecs/Deflate): +# Binary fields are base64 (JPEG data) or base64 of zlib data (raw planes / pixels, inflated with codecs/compress/Deflate): # Luau string literals of binary data cost ~3.7 bytes per byte, base64 1.33. import base64, ctypes, math, os, shutil, subprocess, tempfile, zlib @@ -73,7 +73,7 @@ class TurboJpeg: return w, h, ss, (raw[:pw * ph], pw), (raw[pw * ph:pw * ph + cw * ch], cw, ch), (raw[pw * ph + cw * ch:], cw, ch) def yuv420(self, jpeg): - """what codecs/Jpeg { yuv = true } must produce for this frame""" + """what codecs/image/Jpeg { yuv = true } must produce for this frame""" w, h, ss, (Y, pw), cb, cr = self.planes(jpeg) out = bytearray() for y in range(h): diff --git a/tools/fixtures/mp3_enc.py b/tools/fixtures/mp3_enc.py index 5b95717..4716ddf 100644 --- a/tools/fixtures/mp3_enc.py +++ b/tools/fixtures/mp3_enc.py @@ -11,7 +11,7 @@ _spec = importlib.util.spec_from_file_location("_audio", os.path.join(os.path.di A = importlib.util.module_from_spec(_spec) _spec.loader.exec_module(A) -INPUTS = ["src/Formats/audio/mp3", "src/Formats/codecs/Pcm"] +INPUTS = ["src/Formats/audio/mp3", "src/Formats/codecs/audio/Pcm"] def generate(ctx): diff --git a/tools/fixtures/mpeg1.py b/tools/fixtures/mpeg1.py index bf54b0a..0400555 100644 --- a/tools/fixtures/mpeg1.py +++ b/tools/fixtures/mpeg1.py @@ -1,4 +1,4 @@ -# MPEG-1 video fixtures for codecs/Mpeg1 (tools/fixtures.py), ported from mpeg1-luau tools/fixtures.py: elementary +# MPEG-1 video fixtures for codecs/video/Mpeg1 (tools/fixtures.py), ported from mpeg1-luau tools/fixtures.py: elementary # streams made by ffmpeg's mpeg1video encoder (testsrc2 / mandelbrot, several bit rates, odd sizes, custom matrices, # B-frames, a size change), their access units, and ffmpeg's own decode of each as references: # tests/gen/mpeg1_<name>.luau { name, width, height, frames, file (base64), units = { { offset, length } }, @@ -9,7 +9,7 @@ # tests/gen/mpeg1_bench.luau { { width, height, file (base64), units } }: 320x240 and 640x480 streams (with # B-frames) for tools/bench.luau # Binary fields are base64 (file, units' data) or base64 of zlib data (frames: the test inflates them with -# codecs/Deflate): Luau string literals of binary data cost ~3.7 bytes per byte, base64 1.33. With short streams and +# codecs/compress/Deflate): Luau string literals of binary data cost ~3.7 bytes per byte, base64 1.33. With short streams and # few whole frames the set stays near 10 MB. import base64, os, shutil, subprocess, tempfile, zlib diff --git a/tools/fixtures/opus_celt.py b/tools/fixtures/opus_celt.py index 5db280b..20cc26e 100644 --- a/tools/fixtures/opus_celt.py +++ b/tools/fixtures/opus_celt.py @@ -5,7 +5,7 @@ # ffmpeg (decoded), ffmpegFrames, comments (opusinfo's user comments) } } import os, re, shutil, subprocess, tempfile, zlib -INPUTS = ["src/Formats/audio/opus", "src/Formats/codecs/Mdct", "src/Formats/containers/Ogg", +INPUTS = ["src/Formats/audio/opus", "src/Formats/codecs/audio/Mdct", "src/Formats/containers/Ogg", "tests/audio/_opus_cases.luau", "tools/fixtures/_opus_encode.luau"] diff --git a/tools/fixtures/playlist.py b/tools/fixtures/playlist.py index 4af9918..4c79a8c 100644 --- a/tools/fixtures/playlist.py +++ b/tools/fixtures/playlist.py @@ -1,4 +1,4 @@ -# Playlist fixtures (tools/fixtures.py): playlist/m3u, playlist/pls, playlist/xspf, codecs/Url, codecs/Text. +# Playlist fixtures (tools/fixtures.py): playlist/m3u, playlist/pls, playlist/xspf, codecs/text/Url, codecs/text/Text. # tests/gen/playlist_url.luau random relative references resolved by Python's urllib.parse.urljoin (RFC 3986) # tests/gen/playlist_cp1252.luau every Windows-1252 byte decoded by Python's cp1252 codec (undefined bytes: U+FFFD) # tests/gen/playlist_cases.luau playlists written here (M3U8 with EXTINF, PLS via configparser-style lines, XSPF via diff --git a/tools/fixtures/psd.py b/tools/fixtures/psd.py index d134b70..e9f1efe 100644 --- a/tools/fixtures/psd.py +++ b/tools/fixtures/psd.py @@ -8,7 +8,7 @@ # luau) read by psd-tools, compared with the layers and the flattened image we wrote. import json, os, random, shutil, struct, subprocess, tempfile, zlib -INPUTS = ["src/Formats/layered/psd", "src/Formats/codecs/Blend.luau", "src/Formats/ops/LayerOps.luau", "tools/fixtures/_ours.luau"] +INPUTS = ["src/Formats/layered/psd", "src/Formats/codecs/image/Blend.luau", "src/Formats/ops/LayerOps.luau", "tools/fixtures/_ours.luau"] BLEND = ["norm", "diss", "dark", "mul ", "idiv", "lbrn", "dkCl", "lite", "scrn", "div ", "lddg", "lgCl", "over", "sLit", "hLit", "vLit", "lLit", "pLit", "hMix", "diff", "smud", "fsub", "fdiv", "hue ", "sat ", "colr", "lum "] diff --git a/tools/fixtures/videoenc.py b/tools/fixtures/videoenc.py index 20f2411..8641ed0 100644 --- a/tools/fixtures/videoenc.py +++ b/tools/fixtures/videoenc.py @@ -13,8 +13,8 @@ V = importlib.util.module_from_spec(_spec) _spec.loader.exec_module(V) INPUTS = ["tools/fixtures/_video.py", "tools/fixtures/_video_encode.luau", "tools/fixtures/mkv.py", "tools/fixtures/avi.py", "tools/fixtures/mp4.py", - "src/Formats/video", "src/Formats/codecs/Video", "src/Formats/containers/Ebml", "src/Formats/containers/Avi", "src/Formats/containers/IsoBmff", - "src/Formats/codecs/Jpeg", "src/Formats/codecs/Vp8"] + "src/Formats/video", "src/Formats/codecs/video/Video", "src/Formats/containers/Ebml", "src/Formats/containers/Avi", "src/Formats/containers/IsoBmff", + "src/Formats/codecs/image/Jpeg", "src/Formats/codecs/image/Vp8"] GIF = r""" import io, sys diff --git a/tools/fixtures/voc.py b/tools/fixtures/voc.py index b207bd8..eb15d96 100644 --- a/tools/fixtures/voc.py +++ b/tools/fixtures/voc.py @@ -10,7 +10,7 @@ _spec = importlib.util.spec_from_file_location("_audio", os.path.join(os.path.di A = importlib.util.module_from_spec(_spec) _spec.loader.exec_module(A) -INPUTS = ["src/Formats/audio/voc", "src/Formats/codecs/Pcm"] +INPUTS = ["src/Formats/audio/voc", "src/Formats/codecs/audio/Pcm"] def ff(codec, src="{in}", extra=()): diff --git a/tools/fixtures/webp.py b/tools/fixtures/webp.py index da5ea3d..8745446 100644 --- a/tools/fixtures/webp.py +++ b/tools/fixtures/webp.py @@ -10,7 +10,7 @@ # tests/gen/webp_bench.luau bigger lossy / lossless files for tools/bench.luau import json, os, random, shutil, struct, subprocess, tempfile, zlib -INPUTS = ["tools/fixtures/_webp_encode.luau", "src/Formats/codecs/Vp8L", "src/Formats/image/webp"] +INPUTS = ["tools/fixtures/_webp_encode.luau", "src/Formats/codecs/image/Vp8L", "src/Formats/image/webp"] TOOLS = ["libwebp", "imagemagick", "ffmpeg"] diff --git a/tools/fixtures/xml.py b/tools/fixtures/xml.py index 14cf720..763317b 100644 --- a/tools/fixtures/xml.py +++ b/tools/fixtures/xml.py @@ -1,4 +1,4 @@ -# codecs/Xml + data/xml fixtures: random documents (namespaces, attributes with every escape, CDATA, comments, PIs, +# codecs/text/Xml + data/xml fixtures: random documents (namespaces, attributes with every escape, CDATA, comments, PIs, # entities from an internal DOCTYPE, mixed content) written by hand, then parsed by Python's xml.etree (expat) for the # reference tree; the same documents re-encoded as UTF-16 and Latin-1; and well-formedness cases (hand-written plus # random mutations) with expat's verdict. diff --git a/tools/gen_registry.py b/tools/gen_registry.py index 802add1..f092922 100644 --- a/tools/gen_registry.py +++ b/tools/gen_registry.py @@ -134,19 +134,24 @@ def formats_md(formats): c["folder_category"], lua_strings(c["name"])[0], " ".join("." + e for e in lua_strings(c["extensions"])), "yes" if cd.get("decode") == "true" else "-", "yes" if cd.get("encode") == "true" else "-", other or "", "`%s`" % test if has else "**missing**")) - lines += ["", "Codecs (layer 1, shared by formats; not loadable on their own):", ""] + lines += ["", "Codecs (layer 3, shared by formats; not loadable on their own), by domain:", ""] cdir = os.path.join(SRC, "codecs") - for name in sorted(os.listdir(cdir)) if os.path.isdir(cdir) else []: - p = os.path.join(cdir, name) - init = os.path.join(p, "init.luau") if os.path.isdir(p) else p - if os.path.isfile(init): - first = "" - with open(init) as f: - for line in f: - if line.startswith("-- codecs/"): - first = line[3:].strip() - break - lines.append("- %s" % (first or name)) + for domain in sorted(os.listdir(cdir)) if os.path.isdir(cdir) else []: + ddir = os.path.join(cdir, domain) + if not os.path.isdir(ddir): + continue + lines.append("- **%s**" % domain) + for name in sorted(os.listdir(ddir)): + p = os.path.join(ddir, name) + init = os.path.join(p, "init.luau") if os.path.isdir(p) else p + if os.path.isfile(init) and init.endswith(".luau"): + first = "" + with open(init) as f: + for line in f: + if line.startswith("-- codecs/"): + first = line[3:].strip() + break + lines.append(" - %s" % (first or name)) lines.append("") return "\n".join(lines) diff --git a/tools/lint_rules.py b/tools/lint_rules.py index 0131d1a..9332c8c 100644 --- a/tools/lint_rules.py +++ b/tools/lint_rules.py @@ -11,6 +11,7 @@ # LAYERS requires go downward: core < Types < host; core, Types < codecs < containers < formats (<category>/<fmt>) # < ops < api (init, Registry). core / codecs / containers / ops may require their own layer; a format # may require its own folder but never another format; only the api requires host. +# codecs live in a domain folder: codecs/<domain>/<Name> (CODEC_DOMAINS). # DEPS a format folder's requires outside itself are exactly the contract's deps = { ... }. # CONTRACT a format's init.luau has the one-line fields name (= folder name), category (= folder category), # extensions, mime, deps, caps (with decode / encode matching the functions), function <X>.sniff, at least @@ -199,6 +200,13 @@ for f in files: if tgroup not in ALLOWED[group]: bad(f, i, "LAYERS: %s (%s) may not require %s (%s)" % (mod or "Formats", group, target, tgroup)) +CODEC_DOMAINS = {"compress", "entropy", "image", "audio", "video", "text", "font", "model"} +for f in files: + mod = mods[f] + parts = mod.split("/") + if parts[0] == "codecs" and (len(parts) < 3 or parts[1] not in CODEC_DOMAINS): + bad(f, 1, "LAYERS: codecs go in a domain folder codecs/<%s>/<Name> (%s)" % ("|".join(sorted(CODEC_DOMAINS)), mod)) + # ---------------------------------------------------------------------------------------------------- DEPS + CONTRACT FIELD = re.compile(r"^\t(name|category|extensions|mime|deps|caps) = (.*),\s*(--.*)?$") folders = sorted({format_folder(m) for m in mods.values() if format_folder(m)}) diff --git a/tools/lint_types_baseline.txt b/tools/lint_types_baseline.txt index 49541f7..c67f579 100644 --- a/tools/lint_types_baseline.txt +++ b/tools/lint_types_baseline.txt @@ -1 +1 @@ -94 +93 From 44a599f00c8382c1ba58067080b7bdca535cd7a5 Mon Sep 17 00:00:00 2001 From: 4DBug <github@bug.tools> Date: Sat, 31 Oct 2026 12:28:33 -0500 Subject: [PATCH 19/22] ws-cleanup: codecs/compress/PackBits; UTF-16 and half floats from one place - codecs/compress/PackBits (new, from image/tiff/Pixels): decode (lenient count + a clean flag for strict callers) and encode; image/tiff and layered/psd (which carried its own decoder) use it. tests/codecs/packbits. - codecs/text/Text.utf16(buf, offset, length, bigEndian?): the UTF-16 -> UTF-8 conversion codecs/font/TrueType, archive/7z and layered/psd each wrote (lone surrogates -> U+FFFD everywhere now). - image/tiff/Pixels and data/cbor use core/Bytes.half instead of their own float16 decoders. --- docs/FORMATS.md | 1 + src/Formats/Registry.luau | 6 +- src/Formats/archive/7z/Header.luau | 17 +--- src/Formats/archive/7z/init.luau | 2 +- src/Formats/codecs/compress/PackBits.luau | 95 ++++++++++++++++++++ src/Formats/codecs/font/TrueType/Tables.luau | 20 +---- src/Formats/codecs/text/Text/init.luau | 28 ++++++ src/Formats/data/cbor/Codec.luau | 12 +-- src/Formats/image/tiff/Pixels.luau | 80 +---------------- src/Formats/image/tiff/init.luau | 7 +- src/Formats/layered/psd/Channels.luau | 35 +------- src/Formats/layered/psd/init.luau | 21 +---- tests/codecs/packbits.luau | 45 ++++++++++ 13 files changed, 191 insertions(+), 178 deletions(-) create mode 100644 src/Formats/codecs/compress/PackBits.luau create mode 100644 tests/codecs/packbits.luau diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 13962b1..ba8eb03 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -101,6 +101,7 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain: - codecs/compress/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers. - codecs/compress/Lzma: LZMA and LZMA2 decoders, the .lzma ("LZMA alone") wrapper and the .xz container. A codec (layer 3): - codecs/compress/Lzw: LZW decoder and encoder in the two variants file formats use. A codec (layer 1): image/gif and + - codecs/compress/PackBits: the Apple PackBits run-length code (TIFF compression 32773, PSD / PSB RLE channels, IFF - codecs/compress/Zstd: Zstandard decompression (RFC 8878). A codec (layer 3): archive/zst and anything else carrying zstd - **entropy** - codecs/entropy/Huffman: canonical Huffman codes (RFC 1951 3.2.2 / JPEG Annex C order) for decoders and encoders. diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index d5cf13f..4e500fb 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -128,7 +128,7 @@ local list: { Entry } = { path = "image/tiff", extensions = { "tif", "tiff" }, mime = { "image/tiff" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Deflate", "codecs/compress/Lzw" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Deflate", "codecs/compress/Lzw", "codecs/compress/PackBits" }, caps = { decode = true, encode = true, alpha = true, pages = true, depths = { 1, 2, 4, 8, 16, 32 }, float = true }, load = function() return require("@formats/image/tiff") @@ -548,7 +548,7 @@ local list: { Entry } = { path = "archive/7z", extensions = { "7z" }, mime = { "application/x-7z-compressed" }, - deps = { "core/Err", "core/Bytes", "core/Crc32", "Types", "codecs/compress/Lzma", "codecs/compress/Deflate", "codecs/compress/Bzip2", "codecs/compress/Zstd", "containers/Archive" }, + deps = { "core/Err", "core/Bytes", "core/Crc32", "Types", "codecs/compress/Lzma", "codecs/compress/Deflate", "codecs/compress/Bzip2", "codecs/compress/Zstd", "containers/Archive", "codecs/text/Text" }, caps = { decode = true, encode = false, methods = { "copy", "lzma", "lzma2", "deflate", "bcj", "delta" }, encrypted = false }, load = function() return require("@formats/archive/7z") @@ -788,7 +788,7 @@ local list: { Entry } = { path = "layered/psd", extensions = { "psd", "psb" }, mime = { "image/vnd.adobe.photoshop" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Blend", "codecs/compress/Deflate" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Blend", "codecs/compress/Deflate", "codecs/compress/PackBits", "codecs/text/Text" }, caps = { decode = true, encode = true, layers = true, groups = true, depths = { 1, 8, 16, 32 } }, load = function() return require("@formats/layered/psd") diff --git a/src/Formats/archive/7z/Header.luau b/src/Formats/archive/7z/Header.luau index 6f5ba24..88f0e04 100644 --- a/src/Formats/archive/7z/Header.luau +++ b/src/Formats/archive/7z/Header.luau @@ -3,6 +3,7 @@ -- streams info (pack info, folders with their coders and bind pairs, substreams), files info (names, empty streams / -- files, anti items, times, attributes). Not --!native: a parse failure raises an Err value that parse() catches and -- returns; any other error is a bug and propagates (the tests' fuzz pass sees it). +local Text = require("@formats/codecs/text/Text") local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") @@ -395,21 +396,7 @@ local function streamsInfo(r: Bytes.Reader): Streams end local function utf16(b: buffer, o: number, n: number): string - local out = {} - local i = 0 - while i + 1 < n do - local u = buffer.readu16(b, o + i) - i += 2 - if u >= 0xD800 and u < 0xDC00 and i + 1 < n then - local lo = buffer.readu16(b, o + i) - if lo >= 0xDC00 and lo < 0xE000 then - u = 0x10000 + (u - 0xD800) * 1024 + (lo - 0xDC00) - i += 2 - end - end - table.insert(out, utf8.char(u)) - end - return table.concat(out) + return Text.utf16(b, o, n, false) end local function filesInfo(r: Bytes.Reader): { File } diff --git a/src/Formats/archive/7z/init.luau b/src/Formats/archive/7z/init.luau index 4691ae7..4121b34 100644 --- a/src/Formats/archive/7z/init.luau +++ b/src/Formats/archive/7z/init.luau @@ -26,7 +26,7 @@ local SevenZip = { category = "archive", extensions = { "7z" }, mime = { "application/x-7z-compressed" }, - deps = { "core/Err", "core/Bytes", "core/Crc32", "Types", "codecs/compress/Lzma", "codecs/compress/Deflate", "codecs/compress/Bzip2", "codecs/compress/Zstd", "containers/Archive" }, + deps = { "core/Err", "core/Bytes", "core/Crc32", "Types", "codecs/compress/Lzma", "codecs/compress/Deflate", "codecs/compress/Bzip2", "codecs/compress/Zstd", "containers/Archive", "codecs/text/Text" }, caps = { decode = true, encode = false, methods = { "copy", "lzma", "lzma2", "deflate", "bcj", "delta" }, encrypted = false }, } diff --git a/src/Formats/codecs/compress/PackBits.luau b/src/Formats/codecs/compress/PackBits.luau new file mode 100644 index 0000000..e3fd12f --- /dev/null +++ b/src/Formats/codecs/compress/PackBits.luau @@ -0,0 +1,95 @@ +--!strict +--!native +--!optimize 2 +-- codecs/compress/PackBits: the Apple PackBits run-length code (TIFF compression 32773, PSD / PSB RLE channels, IFF +-- ByteRun1, ...): a header byte n < 128 copies n + 1 literal bytes, n > 128 repeats the next byte 257 - n times, +-- 128 is a no-op. Decode and encode; moved here from image/tiff (TIFF and PSD both carried a decoder). Never throws. +-- +-- local written, srcEnd, clean = PackBits.decode(src, p, limit, dst, d, n) -- up to n bytes into dst at d +-- local packed = PackBits.encode(src, offset, length) -- a buffer (one row at a time) +local PackBits = {} + +local readu8, writeu8 = buffer.readu8, buffer.writeu8 + +-- decode(src, p, limit, dst, d, n) -> bytes written (<= n), the source offset after the codes used, clean (false when +-- the source ran out before n bytes or a run overflowed n: lenient callers keep what was written, strict ones fail) +function PackBits.decode(src: buffer, p: number, limit: number, dst: buffer, d: number, n: number): (number, number, boolean) + local o, lim = d, d + n + local clean = true + while o < lim do + if p >= limit then + clean = false + break + end + local h = readu8(src, p) + p += 1 + if h < 128 then + local want = h + 1 + local cnt = math.min(want, limit - p, lim - o) + if cnt < want then + clean = false + end + if cnt > 0 then + buffer.copy(dst, o, src, p, cnt) + o += cnt + end + p += want + if p > limit then + p = limit + break + end + elseif h > 128 then + if p >= limit then + clean = false + break + end + local want = 257 - h + local cnt = math.min(want, lim - o) + if cnt < want then + clean = false + end + buffer.fill(dst, o, readu8(src, p), cnt) + p += 1 + o += cnt + end + end + return o - d, p, clean +end + +-- encode(src, offset, length) -> buffer: runs of 3+ equal bytes as repeats, the rest as literals (at most 128 each) +function PackBits.encode(src: buffer, off: number, len: number): buffer + local out = buffer.create(len + (len + 127) // 128 + 8) + local o = 0 + local p, e = off, off + len + while p < e do + local run = 1 + local v = readu8(src, p) + while p + run < e and run < 128 and readu8(src, p + run) == v do + run += 1 + end + if run >= 3 then + writeu8(out, o, 257 - run) + writeu8(out, o + 1, v) + o += 2 + p += run + else + local s = p + local n = 0 + while p < e and n < 128 do + if p + 2 < e and readu8(src, p) == readu8(src, p + 1) and readu8(src, p) == readu8(src, p + 2) then + break + end + p += 1 + n += 1 + end + writeu8(out, o, n - 1) + buffer.copy(out, o + 1, src, s, n) + o += n + 1 + end + end + local r = buffer.create(o) + buffer.copy(r, 0, out, 0, o) + return r +end + +return PackBits diff --git a/src/Formats/codecs/font/TrueType/Tables.luau b/src/Formats/codecs/font/TrueType/Tables.luau index 9086053..c958a6b 100644 --- a/src/Formats/codecs/font/TrueType/Tables.luau +++ b/src/Formats/codecs/font/TrueType/Tables.luau @@ -6,6 +6,7 @@ -- domain / MIT) as a reference for cmap 4 and the GPOS walk. -- -- Never throws: every read is range-checked (out of range reads as 0). +local Text = require("@formats/codecs/text/Text") local Tables = {} local readu8 = buffer.readu8 @@ -423,24 +424,7 @@ local MAC_ROMAN_HIGH = { } local function utf16be(b: buffer, o: number, n: number): string - local out = {} - local k = 0 - while k + 1 < n do - local c = u16(b, o + k) - k += 2 - if c >= 0xD800 and c < 0xDC00 and k + 1 < n then - local lo = u16(b, o + k) - if lo >= 0xDC00 and lo < 0xE000 then - c = 0x10000 + (c - 0xD800) * 1024 + (lo - 0xDC00) - k += 2 - end - end - if c >= 0xD800 and c < 0xE000 then - c = 0xFFFD - end - table.insert(out, utf8.char(c)) - end - return table.concat(out) + return Text.utf16(b, o, n, true) end local function macRoman(b: buffer, o: number, n: number): string diff --git a/src/Formats/codecs/text/Text/init.luau b/src/Formats/codecs/text/Text/init.luau index 6980e96..fe1e2d5 100644 --- a/src/Formats/codecs/text/Text/init.luau +++ b/src/Formats/codecs/text/Text/init.luau @@ -31,6 +31,34 @@ function Text.trim(s: string): string return (string.match(s, "^%s*(.-)%s*$") :: string) end +-- utf16(buf, offset, length, bigEndian?) -> UTF-8 text of UTF-16 code units (surrogate pairs joined, lone surrogates +-- become U+FFFD; an odd last byte is ignored). Font names, 7z / PSD / Windows strings, XML in UTF-16. +function Text.utf16(b: buffer, o: number, n: number, bigEndian: boolean?): string + local out = {} + local k = 0 + local readu16 = buffer.readu16 + local function unit(at: number): number + local v = readu16(b, at) + return if bigEndian then (v % 256) * 256 + v // 256 else v + end + while k + 1 < n do + local c = unit(o + k) + k += 2 + if c >= 0xD800 and c < 0xDC00 and k + 1 < n then + local lo = unit(o + k) + if lo >= 0xDC00 and lo < 0xE000 then + c = 0x10000 + (c - 0xD800) * 1024 + (lo - 0xDC00) + k += 2 + end + end + if c >= 0xD800 and c < 0xE000 then + c = 0xFFFD + end + table.insert(out, Text.utf8char(c)) + end + return table.concat(out) +end + -- toUtf8(text, warnings?) -> text as UTF-8: strips a BOM; text that is not valid UTF-8 is read as Windows-1252 function Text.toUtf8(text: string, warnings: { string }?): string if string.sub(text, 1, 3) == "\239\187\191" then diff --git a/src/Formats/data/cbor/Codec.luau b/src/Formats/data/cbor/Codec.luau index 0bbc2eb..5c2db05 100644 --- a/src/Formats/data/cbor/Codec.luau +++ b/src/Formats/data/cbor/Codec.luau @@ -142,17 +142,7 @@ local function chunks(st: St, major: number, depth: number): (string?, string?) end end -local function half(h: number): number - local s = if h >= 32768 then -1 else 1 - local e = (h // 1024) % 32 - local m = h % 1024 - if e == 0 then - return s * m * 2 ^ -24 - elseif e == 31 then - return if m == 0 then s * math.huge else 0 / 0 - end - return s * (1 + m / 1024) * 2 ^ (e - 15) -end +local half = Bytes.half local function tag(st: St, t: number, v: any): (any, string?) if t == 0 and st.dates then diff --git a/src/Formats/image/tiff/Pixels.luau b/src/Formats/image/tiff/Pixels.luau index 68a3db9..82453b5 100644 --- a/src/Formats/image/tiff/Pixels.luau +++ b/src/Formats/image/tiff/Pixels.luau @@ -1,10 +1,11 @@ --!strict --!native --!optimize 2 --- image/tiff/Pixels: the hot loops of the TIFF codec (native; never throws): PackBits, the horizontal (2) and +-- image/tiff/Pixels: the hot loops of the TIFF codec (native; never throws): the horizontal (2) and -- floating-point (3) predictors both ways (TIFF 6.0 section 14, Adobe TIFF technote 3; predictor 3 as libtiff's -- fpAcc / fpDiff), fill-order bit reversal, and the sample converter from decoded planes to a Types.Image layout. -- Callers (image/tiff/init) size every buffer before calling: planes hold h rows of rb bytes plus 8 bytes of slack. +local Bytes = require("@formats/core/Bytes") local readu8, writeu8, readu16, writeu16, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16, buffer.readu32, buffer.writeu32 local readf32, writef32, readf64 = buffer.readf32, buffer.writef32, buffer.readf64 local band, bor, rshift, lshift, byteswap = bit32.band, bit32.bor, bit32.rshift, bit32.lshift, bit32.byteswap @@ -40,71 +41,6 @@ end Pixels.f32 = f32 Pixels.f64 = f64 --- ------------------------------------------------------------------------------------------------ PackBits --- packbits(src, off, len, out, outOff, max) -> bytes written (stops when out or src is exhausted) -function Pixels.packbits(src: buffer, off: number, len: number, out: buffer, outOff: number, max: number): number - local p, e = off, off + len - local o, lim = outOff, outOff + max - while p < e and o < lim do - local n = readu8(src, p) - p += 1 - if n < 128 then - local cnt = math.min(n + 1, e - p, lim - o) - if cnt <= 0 then - break - end - buffer.copy(out, o, src, p, cnt) - p += n + 1 - o += cnt - elseif n > 128 then - if p >= e then - break - end - local cnt = math.min(257 - n, lim - o) - buffer.fill(out, o, readu8(src, p), cnt) - p += 1 - o += cnt - end - end - return o - outOff -end - --- packbitsEncode(src, off, len) -> buffer (one row at a time is the caller's business) -function Pixels.packbitsEncode(src: buffer, off: number, len: number): buffer - local out = buffer.create(len + (len + 127) // 128 + 8) - local o = 0 - local p, e = off, off + len - while p < e do - local run = 1 - local v = readu8(src, p) - while p + run < e and run < 128 and readu8(src, p + run) == v do - run += 1 - end - if run >= 3 then - writeu8(out, o, 257 - run) - writeu8(out, o + 1, v) - o += 2 - p += run - else - local s = p - local n = 0 - while p < e and n < 128 do - if p + 2 < e and readu8(src, p) == readu8(src, p + 1) and readu8(src, p) == readu8(src, p + 2) then - break - end - p += 1 - n += 1 - end - writeu8(out, o, n - 1) - buffer.copy(out, o + 1, src, s, n) - o += n + 1 - end - end - local r = buffer.create(o) - buffer.copy(r, 0, out, 0, o) - return r -end - -- ------------------------------------------------------------------------------------------------ fill order local REV = buffer.create(256) for i = 0, 255 do @@ -212,17 +148,7 @@ function Pixels.predict3(b: buffer, off: number, rows: number, rb: number, bytes end -- ------------------------------------------------------------------------------------------------ samples -local function half(h: number): number - local s = if h >= 0x8000 then -1 else 1 - local e = band(rshift(h, 10), 31) - local m = band(h, 1023) - if e == 0 then - return s * m * 2 ^ -24 - elseif e == 31 then - return if m == 0 then s * math.huge else 0 / 0 - end - return s * (1 + m / 1024) * 2 ^ (e - 15) -end +local half = Bytes.half export type Params = { planes: { buffer }, diff --git a/src/Formats/image/tiff/init.luau b/src/Formats/image/tiff/init.luau index 549b166..e26add9 100644 --- a/src/Formats/image/tiff/init.luau +++ b/src/Formats/image/tiff/init.luau @@ -18,6 +18,7 @@ local Types = require("@formats/Types") local Deflate = require("@formats/codecs/compress/Deflate") local Lzw = require("@formats/codecs/compress/Lzw") local Pixels = require("@formats/image/tiff/Pixels") +local PackBits = require("@formats/codecs/compress/PackBits") -- ------------------------------------------------------------------------------------------------ contract local Tiff = { @@ -25,7 +26,7 @@ local Tiff = { category = "image", extensions = { "tif", "tiff" }, mime = { "image/tiff" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Deflate", "codecs/compress/Lzw" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Deflate", "codecs/compress/Lzw", "codecs/compress/PackBits" }, caps = { decode = true, encode = true, alpha = true, pages = true, depths = { 1, 2, 4, 8, 16, 32 }, float = true }, } @@ -237,7 +238,7 @@ local function inflateChunk(c: Ctx, comp: number, p: number, len: number, out: b buffer.copy(out, o, raw :: buffer, 0, n) return n, nil elseif comp == 32773 then - return Pixels.packbits(src, sp, len, out, o, size), nil + return (PackBits.decode(src, sp, sp + len, out, o, size)), nil end return nil, Err.new(Err.UNSUPPORTED, "compression " .. comp) end @@ -671,7 +672,7 @@ local function encodePage(img: Types.Image, o: EncodeOptions, comp: number): ({ else local parts, total = {}, 0 for r = 0, rows - 1 do - local p = Pixels.packbitsEncode(raw, r * rb, rb) + local p = PackBits.encode(raw, r * rb, rb) table.insert(parts, p) total += buffer.len(p) end diff --git a/src/Formats/layered/psd/Channels.luau b/src/Formats/layered/psd/Channels.luau index 811f076..cedf85b 100644 --- a/src/Formats/layered/psd/Channels.luau +++ b/src/Formats/layered/psd/Channels.luau @@ -5,6 +5,7 @@ -- writer. Adobe Photoshop File Formats Specification (2016), "Channel image data" / "Image data section". -- Never throws: every read is range-checked first; failures return nil, "message". local Deflate = require("@formats/codecs/compress/Deflate") +local PackBits = require("@formats/codecs/compress/PackBits") local Channels = {} @@ -21,36 +22,6 @@ function Channels.rowBytes(w: number, depth: number): number return w * (depth // 8) end --- packbits(src, p, limit, dst, d, n) -> the source offset after decoding n bytes into dst at d | nil -local function packbits(src: buffer, p: number, limit: number, dst: buffer, d: number, n: number): number? - local e = d + n - while d < e do - if p >= limit then - return nil - end - local h = readu8(src, p) - p += 1 - if h < 128 then - local c = h + 1 - if p + c > limit or d + c > e then - return nil - end - bcopy(dst, d, src, p, c) - p += c - d += c - elseif h > 128 then - local c = 257 - h - if p >= limit or d + c > e then - return nil - end - bfill(dst, d, readu8(src, p), c) - p += 1 - d += c - end - end - return p -end - -- rleCounts(src, p, limit, rows, psb) -> { counts }, offset after them | nil function Channels.rleCounts(src: buffer, p: number, limit: number, rows: number, psb: boolean): ({ number }?, number) local size = if psb then 4 else 2 @@ -76,8 +47,8 @@ function Channels.rle(src: buffer, p: number, limit: number, counts: { number }, if p + c > limit then return nil, "RLE row past the end" end - local q = packbits(src, p, p + c, dst, d + i * rowBytes, rowBytes) - if q == nil then + local _, _, clean = PackBits.decode(src, p, p + c, dst, d + i * rowBytes, rowBytes) + if not clean then -- a short or overlong row: keep what decoded, zero the rest (Photoshop is lenient too) return nil, "bad RLE row" end diff --git a/src/Formats/layered/psd/init.luau b/src/Formats/layered/psd/init.luau index af83e5f..4a13349 100644 --- a/src/Formats/layered/psd/init.luau +++ b/src/Formats/layered/psd/init.luau @@ -15,6 +15,7 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") +local Text = require("@formats/codecs/text/Text") local Blend = require("@formats/codecs/image/Blend") local Channels = require("@formats/layered/psd/Channels") @@ -24,7 +25,7 @@ local Psd = { category = "layered", extensions = { "psd", "psb" }, mime = { "image/vnd.adobe.photoshop" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Blend", "codecs/compress/Deflate" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Blend", "codecs/compress/Deflate", "codecs/compress/PackBits", "codecs/text/Text" }, caps = { decode = true, encode = true, layers = true, groups = true, depths = { 1, 8, 16, 32 } }, } @@ -97,23 +98,7 @@ local function len(r: Bytes.Reader, psb: boolean): number end local function utf16be(s: string): string - local out = {} - local i = 1 - while i + 1 <= #s do - local c = string.byte(s, i) * 256 + string.byte(s, i + 1) - i += 2 - if c >= 0xD800 and c < 0xDC00 and i + 1 <= #s then - local c2 = string.byte(s, i) * 256 + string.byte(s, i + 1) - if c2 >= 0xDC00 and c2 < 0xE000 then - c = 0x10000 + (c - 0xD800) * 1024 + (c2 - 0xDC00) - i += 2 - end - end - if c ~= 0 then - table.insert(out, utf8.char(c)) - end - end - return table.concat(out) + return (string.gsub(Text.utf16(buffer.fromstring(s), 0, #s, true), "%z", "")) end -- the layer records + channel data at r (a Reader over the layer info, after its length): flat records | nil, Err diff --git a/tests/codecs/packbits.luau b/tests/codecs/packbits.luau new file mode 100644 index 0000000..cc23fb6 --- /dev/null +++ b/tests/codecs/packbits.luau @@ -0,0 +1,45 @@ +-- codecs/compress/PackBits tests: the Apple technote example, encode -> decode round trips of random / runny rows, +-- the clean flag on short input and overflowing runs, and a no-throw pass over garbage. +local T = require("@tests/T") +local PackBits = require("@formats/codecs/compress/PackBits") + +local t = T.suite("packbits") + +-- Apple Technical Note TN1023 +local packed = T.bytes({ 0xFE, 0xAA, 0x02, 0x80, 0x00, 0x2A, 0xFD, 0xAA, 0x03, 0x80, 0x00, 0x2A, 0x22, 0xF7, 0xAA }) +local want = T.bytes({ 0xAA, 0xAA, 0xAA, 0x80, 0x00, 0x2A, 0xAA, 0xAA, 0xAA, 0xAA, 0x80, 0x00, 0x2A, 0x22, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA }) +local out = buffer.create(24) +local n, pEnd, clean = PackBits.decode(packed, 0, buffer.len(packed), out, 0, 24) +t:check(n == 24 and pEnd == buffer.len(packed) and clean and buffer.tostring(out) == buffer.tostring(want), "TN1023 example") + +local rand = T.rng(11) +for k = 1, 40 do + local len = rand(600) + local row = buffer.create(len) + local i = 0 + while i < len do + local v, run = rand(256) - 1, (if rand(3) == 1 then rand(200) else 1) + for _ = 1, run do + if i < len then + buffer.writeu8(row, i, v) + i += 1 + end + end + end + local enc = PackBits.encode(row, 0, len) + local dec = buffer.create(len) + local m, _, ok = PackBits.decode(enc, 0, buffer.len(enc), dec, 0, len) + t:check(m == len and ok and buffer.tostring(dec) == buffer.tostring(row), "round trip " .. k) +end + +local short = buffer.create(10) +local m1, _, ok1 = PackBits.decode(T.bytes({ 0x05, 1, 2 }), 0, 3, short, 0, 10) +t:check(m1 == 2 and not ok1, "short literal: what is there, not clean") +local m2, _, ok2 = PackBits.decode(T.bytes({ 0x81, 7 }), 0, 2, short, 0, 10) +t:check(m2 == 10 and not ok2, "a run past n is clipped, not clean") + +t:fuzz("decode", function(b: buffer) + local o = buffer.create(256) + return PackBits.decode(b, 0, buffer.len(b), o, 0, 256) +end, { buffer.tostring(packed) }) +t:done() From f5cf02026dd0f7cccbcc970cc83863ba84a56b66 Mon Sep 17 00:00:00 2001 From: 4DBug <github@bug.tools> Date: Sat, 31 Oct 2026 12:31:32 -0500 Subject: [PATCH 20/22] ws-cleanup: MeshFlatten, Zip and the SVG style parser reuse Types.Scene.mul, Types.Date.civilFromDays, Raster.multiply --- src/Formats/Types.luau | 1 + src/Formats/codecs/model/MeshFlatten.luau | 15 +-------------- src/Formats/containers/Zip/init.luau | 14 ++------------ src/Formats/vector/svg/Style.luau | 12 ++---------- 4 files changed, 6 insertions(+), 36 deletions(-) diff --git a/src/Formats/Types.luau b/src/Formats/Types.luau index 9060244..63e3d79 100644 --- a/src/Formats/Types.luau +++ b/src/Formats/Types.luau @@ -821,6 +821,7 @@ local function civilFromDays(z: number): (number, number, number) local m = if mp < 10 then mp + 3 else mp - 9 return (if m <= 2 then y + 1 else y), m, d end +DateLib.civilFromDays = civilFromDays -- days since 1970-01-01 -> year, month, day (proleptic Gregorian) local MDAYS = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } -- new(fields) -> Date (kind inferred from the fields present when not given) function DateLib.new(f: { [string]: any }): Date diff --git a/src/Formats/codecs/model/MeshFlatten.luau b/src/Formats/codecs/model/MeshFlatten.luau index 3c26fc6..cf3fb69 100644 --- a/src/Formats/codecs/model/MeshFlatten.luau +++ b/src/Formats/codecs/model/MeshFlatten.luau @@ -109,20 +109,7 @@ end -- ------------------------------------------------------------------------------------------------ transforms local IDENTITY = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 } --- column-major 4x4 product a * b -local function mul(a: { number }, b: { number }): { number } - local m = table.create(16, 0) - for c = 0, 3 do - for r = 0, 3 do - local s = 0 - for k = 0, 3 do - s += a[k * 4 + r + 1] * b[c * 4 + k + 1] - end - m[c * 4 + r + 1] = s - end - end - return m -end +local mul = Types.Scene.mul -- column-major 4x4 product a * b local function numList(v: any, n: number): boolean if type(v) ~= "table" then diff --git a/src/Formats/containers/Zip/init.luau b/src/Formats/containers/Zip/init.luau index 0fcf385..9133f94 100644 --- a/src/Formats/containers/Zip/init.luau +++ b/src/Formats/containers/Zip/init.luau @@ -19,6 +19,7 @@ -- Never throws: corrupt archives and bad arguments return nil, Err. Parsing runs interpreted (it is cold); the native -- code it reaches (Deflate, Crc32) does not throw either. local Err = require("@formats/core/Err") +local Types = require("@formats/Types") local Bytes = require("@formats/core/Bytes") local Crc32 = require("@formats/core/Crc32") local Deflate = require("@formats/codecs/compress/Deflate") @@ -421,18 +422,7 @@ function Zip.writer(): any end -- days from 1970-01-01 to y-m-d (proleptic Gregorian) -local function civil(z: number): (number, number, number) - z += 719468 - local era = (if z >= 0 then z else z - 146096) // 146097 - local doe = z - era * 146097 - local yoe = (doe - doe // 1460 + doe // 36524 - doe // 146096) // 365 - local y = yoe + era * 400 - local doy = doe - (365 * yoe + yoe // 4 - yoe // 100) - local mp = (5 * doy + 2) // 153 - local d = doy - (153 * mp + 2) // 5 + 1 - local m = if mp < 10 then mp + 3 else mp - 9 - return (if m <= 2 then y + 1 else y), m, d -end +local 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 diff --git a/src/Formats/vector/svg/Style.luau b/src/Formats/vector/svg/Style.luau index 10ff39e..da4fd36 100644 --- a/src/Formats/vector/svg/Style.luau +++ b/src/Formats/vector/svg/Style.luau @@ -4,6 +4,7 @@ -- lengths with units, transform lists, style="" declarations, and a CSS subset for <style> (rules of comma-separated -- compound selectors made of a type, .classes, #id and *, with specificity; @rules and other combinators are skipped). -- Never throws. +local Raster = require("@formats/codecs/image/Raster") local Style = {} local NAMED: { [string]: number } = { @@ -242,16 +243,7 @@ function Style.numbers(s: string?): { number } end -- transform(s) -> { a, b, c, d, e, f } (the product of the list) | nil on a syntax error -local function mul(m: { number }, n: { number }): { number } - return { - m[1] * n[1] + m[3] * n[2], - m[2] * n[1] + m[4] * n[2], - m[1] * n[3] + m[3] * n[4], - m[2] * n[3] + m[4] * n[4], - m[1] * n[5] + m[3] * n[6] + m[5], - m[2] * n[5] + m[4] * n[6] + m[6], - } -end +local mul = Raster.multiply Style.multiply = mul function Style.transform(s: string): { number }? local m = { 1, 0, 0, 1, 0, 0 } From 9941113b7b3c29fd487f721045362fa5cc05d286 Mon Sep 17 00:00:00 2001 From: 4DBug <github@bug.tools> Date: Sat, 31 Oct 2026 12:47:02 -0500 Subject: [PATCH 21/22] ws-cleanup: audio codecs out of the format folders (codecs/audio/Opus, Vorbis, Flac, Mpa) The decoders / encoders are libraries, not the file format: audio/opus/{Celt, CeltTables, CeltEncoder, Mdct, Packet, Silk, SilkTables, Decoder} -> codecs/audio/Opus; audio/vorbis/{Codebook, Packet, Setup, Tables} -> codecs/audio/Vorbis; audio/flac/{Frame, Encode} -> codecs/audio/Flac; audio/mp3/{Core, Tables, Header, Encode2, Encode3, EncTables, Analysis} -> codecs/audio/Mpa (tools/move.py; code unchanged). Each gets an index init.luau. The format folders keep the file mapping: Ogg Opus / Ogg Vorbis (headers, granules, seeking, the Vorbis encoder's Ogg writer), native / Ogg FLAC streams and metadata, ID3 / Xing / the MP3 frame index. docs: STYLE says a codec is not the format. Full suite: 248 runs pass on both runtimes, lint green. --- README.md | 3 ++- docs/FORMATS.md | 4 ++++ docs/STYLE.md | 7 +++++-- src/Formats/Registry.luau | 8 ++++---- src/Formats/audio/flac/Stream.luau | 2 +- src/Formats/audio/flac/init.luau | 7 ++++--- src/Formats/audio/mp3/Index.luau | 4 ++-- src/Formats/audio/mp3/Stream.luau | 2 +- src/Formats/audio/mp3/init.luau | 11 ++++++----- src/Formats/audio/opus/Encode.luau | 4 ++-- src/Formats/audio/opus/init.luau | 11 ++++++----- src/Formats/audio/vorbis/Encode.luau | 2 +- src/Formats/audio/vorbis/init.luau | 7 ++++--- .../{audio/flac => codecs/audio/Flac}/Encode.luau | 6 +++--- .../{audio/flac => codecs/audio/Flac}/Frame.luau | 2 +- src/Formats/codecs/audio/Flac/init.luau | 11 +++++++++++ .../{audio/mp3 => codecs/audio/Mpa}/Analysis.luau | 6 +++--- .../{audio/mp3 => codecs/audio/Mpa}/Core.luau | 4 ++-- .../mp3 => codecs/audio/Mpa}/EncTables.luau | 2 +- .../{audio/mp3 => codecs/audio/Mpa}/Encode2.luau | 8 ++++---- .../{audio/mp3 => codecs/audio/Mpa}/Encode3.luau | 12 ++++++------ .../{audio/mp3 => codecs/audio/Mpa}/Header.luau | 4 ++-- .../{audio/mp3 => codecs/audio/Mpa}/Tables.luau | 2 +- src/Formats/codecs/audio/Mpa/init.luau | 13 +++++++++++++ .../{audio/opus => codecs/audio/Opus}/Celt.luau | 6 +++--- .../opus => codecs/audio/Opus}/CeltEncoder.luau | 8 ++++---- .../opus => codecs/audio/Opus}/CeltTables.luau | 2 +- .../opus => codecs/audio/Opus}/Decoder.luau | 8 ++++---- .../{audio/opus => codecs/audio/Opus}/Mdct.luau | 2 +- .../{audio/opus => codecs/audio/Opus}/Packet.luau | 2 +- .../{audio/opus => codecs/audio/Opus}/Silk.luau | 4 ++-- .../opus => codecs/audio/Opus}/SilkTables.luau | 2 +- src/Formats/codecs/audio/Opus/init.luau | 15 +++++++++++++++ .../vorbis => codecs/audio/Vorbis}/Codebook.luau | 2 +- .../vorbis => codecs/audio/Vorbis}/Packet.luau | 8 ++++---- .../vorbis => codecs/audio/Vorbis}/Setup.luau | 4 ++-- .../vorbis => codecs/audio/Vorbis}/Tables.luau | 2 +- src/Formats/codecs/audio/Vorbis/init.luau | 13 +++++++++++++ tests/audio/opus.luau | 8 ++++---- 39 files changed, 146 insertions(+), 82 deletions(-) rename src/Formats/{audio/flac => codecs/audio/Flac}/Encode.luau (98%) rename src/Formats/{audio/flac => codecs/audio/Flac}/Frame.luau (99%) create mode 100644 src/Formats/codecs/audio/Flac/init.luau rename src/Formats/{audio/mp3 => codecs/audio/Mpa}/Analysis.luau (84%) rename src/Formats/{audio/mp3 => codecs/audio/Mpa}/Core.luau (99%) rename src/Formats/{audio/mp3 => codecs/audio/Mpa}/EncTables.luau (99%) rename src/Formats/{audio/mp3 => codecs/audio/Mpa}/Encode2.luau (96%) rename src/Formats/{audio/mp3 => codecs/audio/Mpa}/Encode3.luau (97%) rename src/Formats/{audio/mp3 => codecs/audio/Mpa}/Header.luau (95%) rename src/Formats/{audio/mp3 => codecs/audio/Mpa}/Tables.luau (99%) create mode 100644 src/Formats/codecs/audio/Mpa/init.luau rename src/Formats/{audio/opus => codecs/audio/Opus}/Celt.luau (99%) rename src/Formats/{audio/opus => codecs/audio/Opus}/CeltEncoder.luau (98%) rename src/Formats/{audio/opus => codecs/audio/Opus}/CeltTables.luau (97%) rename src/Formats/{audio/opus => codecs/audio/Opus}/Decoder.luau (97%) rename src/Formats/{audio/opus => codecs/audio/Opus}/Mdct.luau (98%) rename src/Formats/{audio/opus => codecs/audio/Opus}/Packet.luau (97%) rename src/Formats/{audio/opus => codecs/audio/Opus}/Silk.luau (99%) rename src/Formats/{audio/opus => codecs/audio/Opus}/SilkTables.luau (99%) create mode 100644 src/Formats/codecs/audio/Opus/init.luau rename src/Formats/{audio/vorbis => codecs/audio/Vorbis}/Codebook.luau (98%) rename src/Formats/{audio/vorbis => codecs/audio/Vorbis}/Packet.luau (98%) rename src/Formats/{audio/vorbis => codecs/audio/Vorbis}/Setup.luau (98%) rename src/Formats/{audio/vorbis => codecs/audio/Vorbis}/Tables.luau (96%) create mode 100644 src/Formats/codecs/audio/Vorbis/init.luau diff --git a/README.md b/README.md index d47d4c1..746ab76 100644 --- a/README.md +++ b/README.md @@ -103,7 +103,8 @@ src/Formats/ codecs/compress/ Deflate, Lzma, Zstd, Brotli, Bzip2, Lzw codecs/entropy/ Huffman, RangeCoder codecs/image/ Jpeg, Dct, Vp8, Vp8L, Pixels, Yuv, Quantize, Raster, Blend - codecs/audio/ Pcm, Stream, Resample, Mdct, Aac, Alac, VorbisComment, Tracker, SoundFont + codecs/audio/ Opus, Vorbis, Flac, Mpa (MP1-3), Aac, Alac, Mdct, Pcm, Stream, Resample, + VorbisComment, Tracker, SoundFont codecs/video/ H264, Mpeg1, Video (the codec registry) codecs/text/ codecs/font/ codecs/model/ Json, Xml, Text, Url / TrueType, Cff / Mat4, MeshFlatten host/ runtime adapters (only the api uses them) diff --git a/docs/FORMATS.md b/docs/FORMATS.md index ba8eb03..0a41a66 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -88,12 +88,16 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain: - **audio** - codecs/audio/Aac: AAC-LC decoder (ISO/IEC 14496-3 subpart 4, ISO/IEC 13818-7): the AudioSpecificConfig (with a program - codecs/audio/Alac: Apple Lossless (ALAC) decoder and encoder, the codec inside m4a / mov / caf. A codec (layer 1). + - codecs/audio/Flac: FLAC frames without the container: frame header parsing, subframe decoding (constant, verbatim, - codecs/audio/Mdct: the MDCT / IMDCT of any window length N divisible by 4 (N / 2 coefficients), through an N / 4-point + - codecs/audio/Mpa: MPEG audio layers I / II / III (ISO/IEC 11172-3, 13818-3, MPEG-2.5) without the file around it: + - codecs/audio/Opus: the Opus codec (RFC 6716) without its container: TOC / packet framing (Packet), the SILK and CELT - codecs/audio/Pcm: PCM plumbing shared by audio formats: raw sample formats, streaming Decoders, encoder input sources. - codecs/audio/Resample: audio sample-rate conversion by band-limited (Kaiser-windowed sinc) interpolation, streaming or - codecs/audio/SoundFont: SoundFont 2 banks and the sample synth that plays MIDI through them. A codec (layer 1) shared by - codecs/audio/Stream: the streaming Decoder (Types.Decoder: read / seek / position) over a packetised codec, the part - codecs/audio/Tracker: the shared tracker engine behind music/mod, music/s3m, music/xm and music/it. The four loaders read + - codecs/audio/Vorbis: the Vorbis I decoder without its container: identification / comment / setup headers (Setup), - codecs/audio/VorbisComment: Vorbis comment fields ("KEY=value", the tag block of Vorbis, Opus and FLAC) <-> Types.Tags. - **compress** - codecs/compress/Brotli: Brotli (RFC 7932) decompression. A codec (layer 3): archive/br and font/woff2 build on it. Written diff --git a/docs/STYLE.md b/docs/STYLE.md index 11654b8..1e7e242 100644 --- a/docs/STYLE.md +++ b/docs/STYLE.md @@ -27,7 +27,7 @@ src/Formats/ codecs/<domain>/<Name> codecs (layer 3) generic algorithms, by domain: compress/ Deflate Lzma Zstd Brotli Bzip2 Lzw entropy/ Huffman RangeCoder image/ Jpeg Dct Vp8 Vp8L Pixels Yuv Quantize Raster Blend - audio/ Pcm Stream Resample Mdct Aac Alac VorbisComment Tracker SoundFont + audio/ Opus Vorbis Flac Mpa Aac Alac Mdct Pcm Stream Resample VorbisComment Tracker SoundFont video/ H264 Mpeg1 Video (the video codec registry) text/ Json Xml Text Url font/ TrueType Cff model/ Mat4 MeshFlatten host/ host (layer 2) runtime adapters; only the api uses them @@ -183,7 +183,10 @@ A Luau error unwinding through a native frame crashes Roblox Studio, even inside ## 2a. What belongs in a format folder A format folder holds only what is specific to the format: its header / chunk parsing, the mapping to and from the -standard type, its writer, and hot loops nothing else shares. Anything generic goes down a layer and is called: +standard type, its writer, and hot loops nothing else shares. A codec is not the format: the Opus, Vorbis, FLAC and +MPEG audio decoders / encoders live in `codecs/audio/` (audio/opus is Ogg Opus around `codecs/audio/Opus`), as JPEG, +VP8 / VP8L, H.264 and MPEG-1 live in `codecs/image/` / `codecs/video/`, so containers and other formats can reach +them. Anything generic goes down a layer and is called: | Need | Use | |---|---| diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 4e500fb..6c0344c 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -200,7 +200,7 @@ local list: { Entry } = { path = "audio/flac", extensions = { "flac", "oga" }, mime = { "audio/flac", "audio/x-flac" }, - deps = { "core/Err", "core/Bytes", "core/Bits", "Types", "containers/Ogg", "core/Md5", "codecs/audio/Pcm", "codecs/audio/VorbisComment" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/audio/Pcm", "codecs/audio/VorbisComment", "codecs/audio/Flac/Frame", "codecs/audio/Flac/Encode" }, caps = { decode = true, encode = true, streaming = true, depths = { 4, 8, 12, 16, 20, 24, 32 }, ogg = true, seek = true }, load = function() return require("@formats/audio/flac") @@ -224,7 +224,7 @@ local list: { Entry } = { path = "audio/mp3", extensions = { "mp3", "mp2", "mp1", "mpga" }, mime = { "audio/mpeg", "audio/mp3", "audio/mpa" }, - deps = { "core/Err", "core/Bytes", "core/Bits", "Types", "codecs/audio/Pcm", "codecs/audio/Resample" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Resample", "codecs/audio/Mpa/Header", "codecs/audio/Mpa/Core", "codecs/audio/Mpa/Encode3", "codecs/audio/Mpa/Encode2" }, caps = { decode = true, encode = true, streaming = true, seek = true, layers = { 1, 2, 3 }, encodeLayers = { 2, 3 }, channels = 2 }, load = function() return require("@formats/audio/mp3") @@ -236,7 +236,7 @@ local list: { Entry } = { path = "audio/opus", extensions = { "opus" }, mime = { "audio/opus", "audio/ogg" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/audio/Mdct", "codecs/entropy/RangeCoder/Decoder", "codecs/entropy/RangeCoder/Encoder", "codecs/audio/Pcm", "codecs/audio/Resample", "codecs/audio/VorbisComment" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/entropy/RangeCoder/Decoder", "codecs/audio/Pcm", "codecs/audio/Resample", "codecs/audio/VorbisComment", "codecs/audio/Opus/CeltEncoder", "codecs/audio/Opus/Decoder", "codecs/audio/Opus/Packet", "codecs/audio/Opus/Celt", "codecs/audio/Opus/Silk" }, caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255, rates = { 48000 }, encodeModes = { "celt" }, encodeChannels = 2 }, load = function() return require("@formats/audio/opus") @@ -260,7 +260,7 @@ local list: { Entry } = { path = "audio/vorbis", extensions = { "ogg", "oga" }, mime = { "audio/ogg", "audio/vorbis" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/audio/Mdct", "codecs/audio/Pcm", "codecs/audio/VorbisComment" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/audio/Mdct", "codecs/audio/Pcm", "codecs/audio/VorbisComment", "codecs/audio/Vorbis/Tables", "codecs/audio/Vorbis/Setup", "codecs/audio/Vorbis/Packet" }, caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255 }, load = function() return require("@formats/audio/vorbis") diff --git a/src/Formats/audio/flac/Stream.luau b/src/Formats/audio/flac/Stream.luau index b6a5dc5..4f53f4b 100644 --- a/src/Formats/audio/flac/Stream.luau +++ b/src/Formats/audio/flac/Stream.luau @@ -8,7 +8,7 @@ -- injected module). Nothing throws: open returns nil, message, code. local Bytes = require("@formats/core/Bytes") local Ogg = require("@formats/containers/Ogg") -local Frame = require("@formats/audio/flac/Frame") +local Frame = require("@formats/codecs/audio/Flac/Frame") local Meta = require("@formats/audio/flac/Meta") local Stream = {} diff --git a/src/Formats/audio/flac/init.luau b/src/Formats/audio/flac/init.luau index d3b7048..49f5f32 100644 --- a/src/Formats/audio/flac/init.luau +++ b/src/Formats/audio/flac/init.luau @@ -5,9 +5,10 @@ -- with escapes, every stereo mode, 4-32 bits, 1-8 channels, any sample rate, fixed and variable block sizes, frame -- CRC-16 checks with resync past corrupt frames, sample-accurate seeking (seek table + bisection), an ID3v2 tag in -- front, STREAMINFO / SEEKTABLE / VORBIS_COMMENT / PICTURE metadata, the total length from the last frame when --- STREAMINFO has none. Encode (audio/flac/Encode, ws-audio): native FLAC from an Audio or a streamed Decoder, levels +-- STREAMINFO has none. Encode (codecs/audio/Flac/Encode, ws-audio): native FLAC from an Audio or a streamed Decoder, levels -- 0-8 like libFLAC's presets, 4-24 bits, 1-8 channels, MD5, VORBIS_COMMENT, SEEKTABLE. Not supported: MD5 -- verification on decode, chained Ogg streams, Ogg FLAC output. +-- The codec itself is codecs/audio/Flac; this folder maps it onto the file (container, tags, seeking, writing). -- -- local dec = Flac.open(Bytes.reader(buf)) -- the Types.Decoder (+ bitsPerSample, readInt, seekSample, ...) -- local f32, n = dec:read(4096) -- interleaved f32 in [-1, 1); n = 0 at the end @@ -20,7 +21,7 @@ local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") local Ogg = require("@formats/containers/Ogg") local Stream = require("@formats/audio/flac/Stream") -local Encode = require("@formats/audio/flac/Encode") +local Encode = require("@formats/codecs/audio/Flac/Encode") local Pcm = require("@formats/codecs/audio/Pcm") -- ------------------------------------------------------------------------------------------------ contract @@ -29,7 +30,7 @@ local Flac = { category = "audio", extensions = { "flac", "oga" }, mime = { "audio/flac", "audio/x-flac" }, - deps = { "core/Err", "core/Bytes", "core/Bits", "Types", "containers/Ogg", "core/Md5", "codecs/audio/Pcm", "codecs/audio/VorbisComment" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/audio/Pcm", "codecs/audio/VorbisComment", "codecs/audio/Flac/Frame", "codecs/audio/Flac/Encode" }, caps = { decode = true, encode = true, streaming = true, depths = { 4, 8, 12, 16, 20, 24, 32 }, ogg = true, seek = true }, } diff --git a/src/Formats/audio/mp3/Index.luau b/src/Formats/audio/mp3/Index.luau index ae84e7f..feb3b35 100644 --- a/src/Formats/audio/mp3/Index.luau +++ b/src/Formats/audio/mp3/Index.luau @@ -5,8 +5,8 @@ -- (same sync, resync and Xing / LAME handling), and simulates the layer III bit reservoir from the side info, so -- it knows in advance which frames give output and where each one's samples land. That makes the total length -- exact and seeking sample-accurate. Never throws. -local Header = require("@formats/audio/mp3/Header") -local Core = require("@formats/audio/mp3/Core") +local Header = require("@formats/codecs/audio/Mpa/Header") +local Core = require("@formats/codecs/audio/Mpa/Core") local band, rshift = bit32.band, bit32.rshift local ru8 = buffer.readu8 diff --git a/src/Formats/audio/mp3/Stream.luau b/src/Formats/audio/mp3/Stream.luau index 4bf0414..b080873 100644 --- a/src/Formats/audio/mp3/Stream.luau +++ b/src/Formats/audio/mp3/Stream.luau @@ -2,7 +2,7 @@ --!optimize 2 -- audio/mp3/Stream: the streaming Decoder (Types.Decoder) over a frame index: gapless (LAME delay / padding), exact -- length, sample-accurate seeking. From mp3-luau's Mp3.open / Decoder (same author). Never throws. -local Core = require("@formats/audio/mp3/Core") +local Core = require("@formats/codecs/audio/Mpa/Core") local Index = require("@formats/audio/mp3/Index") local FLAG_RESET, FLAG_OUTPUT = Index.FLAG_RESET, Index.FLAG_OUTPUT diff --git a/src/Formats/audio/mp3/init.luau b/src/Formats/audio/mp3/init.luau index a281cf3..5bcaffa 100644 --- a/src/Formats/audio/mp3/init.luau +++ b/src/Formats/audio/mp3/init.luau @@ -4,10 +4,11 @@ -- layers I / II / III, mono / stereo / joint stereo / dual channel, CBR / VBR / free format, gapless playback (Xing / -- Info + LAME delay and padding), exact length and sample-accurate seeking from a frame index built on open, resync -- past garbage, mono / stereo switches (upmixed), ID3v2.2 / 2.3 / 2.4 and ID3v1 / 1.1 tags (APEv2 skipped). --- Float output (minimp3's MINIMP3_FLOAT_OUTPUT scalar path). Encode (ws-audio, audio/mp3/Encode3 + Encode2): layer III +-- Float output (minimp3's MINIMP3_FLOAT_OUTPUT scalar path). Encode (ws-audio, codecs/audio/Mpa/Encode3 + Encode2): layer III -- (shine-style CBR, MPEG-1 / 2 / 2.5) and layer II (MPEG-1 / 2), mono / stereo / joint stereo, an ID3v2.4 tag from -- the tags; input at rates the layer cannot hold is resampled (codecs/audio/Resample). Not supported: MPEG-2 multichannel -- extension, CRC checks, VBR / Xing output. +-- The codec itself is codecs/audio/Mpa; this folder maps it onto the file (container, tags, seeking, writing). -- -- local dec = Mp3.open(Bytes.reader(buf)) -- the streaming Types.Decoder (+ layer, version, vbr, delay, -- local pcm, n = dec:read(4096) -- padding, mpegFrames, id3, :seekFrame(i), :readAll()) @@ -17,12 +18,12 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") -local Header = require("@formats/audio/mp3/Header") +local Header = require("@formats/codecs/audio/Mpa/Header") local Index = require("@formats/audio/mp3/Index") local Tags = require("@formats/audio/mp3/Tags") local Stream = require("@formats/audio/mp3/Stream") -local Encode3 = require("@formats/audio/mp3/Encode3") -local Encode2 = require("@formats/audio/mp3/Encode2") +local Encode3 = require("@formats/codecs/audio/Mpa/Encode3") +local Encode2 = require("@formats/codecs/audio/Mpa/Encode2") local Pcm = require("@formats/codecs/audio/Pcm") local Resample = require("@formats/codecs/audio/Resample") @@ -32,7 +33,7 @@ local Mp3 = { category = "audio", extensions = { "mp3", "mp2", "mp1", "mpga" }, mime = { "audio/mpeg", "audio/mp3", "audio/mpa" }, - deps = { "core/Err", "core/Bytes", "core/Bits", "Types", "codecs/audio/Pcm", "codecs/audio/Resample" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Resample", "codecs/audio/Mpa/Header", "codecs/audio/Mpa/Core", "codecs/audio/Mpa/Encode3", "codecs/audio/Mpa/Encode2" }, caps = { decode = true, encode = true, streaming = true, seek = true, layers = { 1, 2, 3 }, encodeLayers = { 2, 3 }, channels = 2 }, } diff --git a/src/Formats/audio/opus/Encode.luau b/src/Formats/audio/opus/Encode.luau index f214abd..3195ab7 100644 --- a/src/Formats/audio/opus/Encode.luau +++ b/src/Formats/audio/opus/Encode.luau @@ -1,5 +1,5 @@ --!strict --- audio/opus/Encode: Ogg Opus writing (RFC 7845) around audio/opus/CeltEncoder: CELT-only packets (TOC config 31: +-- audio/opus/Encode: Ogg Opus writing (RFC 7845) around codecs/audio/Opus/CeltEncoder: CELT-only packets (TOC config 31: -- full band, 20 ms, code 0), OpusHead (mapping family 0, the pre-skip = the encoder's delay), OpusTags (vendor + -- the tags as Vorbis comments), granule positions with end trimming, pages through containers/Ogg's muxer. Input at -- other rates is resampled to 48 kHz (codecs/audio/Resample); the input is a Types.Audio or a Decoder (codecs/audio/Pcm). New in @@ -10,7 +10,7 @@ local Ogg = require("@formats/containers/Ogg") local Pcm = require("@formats/codecs/audio/Pcm") local Resample = require("@formats/codecs/audio/Resample") local VorbisComment = require("@formats/codecs/audio/VorbisComment") -local CeltEncoder = require("@formats/audio/opus/CeltEncoder") +local CeltEncoder = require("@formats/codecs/audio/Opus/CeltEncoder") local Encode = {} diff --git a/src/Formats/audio/opus/init.luau b/src/Formats/audio/opus/init.luau index 6a98cea..7c41456 100644 --- a/src/Formats/audio/opus/init.luau +++ b/src/Formats/audio/opus/init.luau @@ -11,6 +11,7 @@ -- projection), chained streams (the first Opus stream is decoded), CELT pitch PLC (noise PLC only). -- Changes from opus-luau: the injected Ogg demuxer is containers/Ogg; errors are core/Err values; read() takes an -- optional output buffer; decode() fully decodes to an Audio. +-- The codec itself is codecs/audio/Opus; this folder maps it onto the file (container, tags, seeking, writing). -- -- local dec, err = Opus.open(Bytes.reader(buf)) -- the Types.Decoder: dec:read(n, out?), dec:seek(s), ... -- local audio = Opus.decode(Bytes.reader(buf)) -- a Types.Audio @@ -22,13 +23,13 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") local Ogg = require("@formats/containers/Ogg") -local Decoder = require("@formats/audio/opus/Decoder") -local Packet = require("@formats/audio/opus/Packet") +local Decoder = require("@formats/codecs/audio/Opus/Decoder") +local Packet = require("@formats/codecs/audio/Opus/Packet") local VorbisComment = require("@formats/codecs/audio/VorbisComment") local Pcm = require("@formats/codecs/audio/Pcm") local RangeDecoder = require("@formats/codecs/entropy/RangeCoder/Decoder") -local Celt = require("@formats/audio/opus/Celt") -local Silk = require("@formats/audio/opus/Silk") +local Celt = require("@formats/codecs/audio/Opus/Celt") +local Silk = require("@formats/codecs/audio/Opus/Silk") local Encode = require("@formats/audio/opus/Encode") -- ------------------------------------------------------------------------------------------------ contract @@ -37,7 +38,7 @@ local Opus = { category = "audio", extensions = { "opus" }, mime = { "audio/opus", "audio/ogg" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/audio/Mdct", "codecs/entropy/RangeCoder/Decoder", "codecs/entropy/RangeCoder/Encoder", "codecs/audio/Pcm", "codecs/audio/Resample", "codecs/audio/VorbisComment" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/entropy/RangeCoder/Decoder", "codecs/audio/Pcm", "codecs/audio/Resample", "codecs/audio/VorbisComment", "codecs/audio/Opus/CeltEncoder", "codecs/audio/Opus/Decoder", "codecs/audio/Opus/Packet", "codecs/audio/Opus/Celt", "codecs/audio/Opus/Silk" }, caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255, rates = { 48000 }, encodeModes = { "celt" }, encodeChannels = 2 }, } diff --git a/src/Formats/audio/vorbis/Encode.luau b/src/Formats/audio/vorbis/Encode.luau index 5483130..255d8fb 100644 --- a/src/Formats/audio/vorbis/Encode.luau +++ b/src/Formats/audio/vorbis/Encode.luau @@ -14,7 +14,7 @@ local Mdct = require("@formats/codecs/audio/Mdct") local Pcm = require("@formats/codecs/audio/Pcm") local VorbisComment = require("@formats/codecs/audio/VorbisComment") local Ogg = require("@formats/containers/Ogg") -local Tables = require("@formats/audio/vorbis/Tables") +local Tables = require("@formats/codecs/audio/Vorbis/Tables") local Encode = {} diff --git a/src/Formats/audio/vorbis/init.luau b/src/Formats/audio/vorbis/init.luau index 917ad9f..b375c5d 100644 --- a/src/Formats/audio/vorbis/init.luau +++ b/src/Formats/audio/vorbis/init.luau @@ -9,14 +9,15 @@ -- Ogg Vorbis encoder from an Audio or a streamed Decoder (long blocks, floor 1, coupled residue 2, a fixed codebook -- set, quality -1 .. 10). Not supported: floor 0 (Err.UNSUPPORTED, as in stb_vorbis; no encoder has produced it since -- 2000), chained streams (the first logical Vorbis stream is decoded), short blocks in the encoder. +-- The codec itself is codecs/audio/Vorbis; this folder maps it onto the file (container, tags, seeking, writing). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") local Ogg = require("@formats/containers/Ogg") -local Setup = require("@formats/audio/vorbis/Setup") -local Packet = require("@formats/audio/vorbis/Packet") +local Setup = require("@formats/codecs/audio/Vorbis/Setup") +local Packet = require("@formats/codecs/audio/Vorbis/Packet") local Encode = require("@formats/audio/vorbis/Encode") local Pcm = require("@formats/codecs/audio/Pcm") local VorbisComment = require("@formats/codecs/audio/VorbisComment") @@ -27,7 +28,7 @@ local Vorbis = { category = "audio", extensions = { "ogg", "oga" }, mime = { "audio/ogg", "audio/vorbis" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/audio/Mdct", "codecs/audio/Pcm", "codecs/audio/VorbisComment" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/audio/Mdct", "codecs/audio/Pcm", "codecs/audio/VorbisComment", "codecs/audio/Vorbis/Tables", "codecs/audio/Vorbis/Setup", "codecs/audio/Vorbis/Packet" }, caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255 }, } diff --git a/src/Formats/audio/flac/Encode.luau b/src/Formats/codecs/audio/Flac/Encode.luau similarity index 98% rename from src/Formats/audio/flac/Encode.luau rename to src/Formats/codecs/audio/Flac/Encode.luau index 3b3c99b..4af5125 100644 --- a/src/Formats/audio/flac/Encode.luau +++ b/src/Formats/codecs/audio/Flac/Encode.luau @@ -1,7 +1,7 @@ --!strict --!native --!optimize 2 --- audio/flac/Encode: the FLAC encoder (RFC 9639). New code, written from the RFC; the presets mirror libFLAC's -0 .. -8 +-- codecs/audio/Flac/Encode: the FLAC encoder (RFC 9639). New code, written from the RFC; the presets mirror libFLAC's -0 .. -8 -- (block size 1152 / 4096, max LPC order 0 / 6 / 8 / 12, Rice partition order 3 .. 6, independent / adaptive / -- exhaustive stereo decorrelation). Subframes: CONSTANT, VERBATIM, FIXED (order 0..4, chosen by the residual sum), -- LPC (Levinson-Durbin on the tukey(0.5)-windowed autocorrelation, error-feedback coefficient quantization with @@ -13,7 +13,7 @@ local Bits = require("@formats/core/Bits") local Md5 = require("@formats/core/Md5") local VorbisComment = require("@formats/codecs/audio/VorbisComment") -local Frame = require("@formats/audio/flac/Frame") +local Frame = require("@formats/codecs/audio/Flac/Frame") local Encode = {} @@ -26,7 +26,7 @@ for i = 0, 63 do end -- ------------------------------------------------------------------------------------------------ CRCs --- (the decoder's tables: audio/flac/Frame; (b, offset, count) here) +-- (the decoder's tables: codecs/audio/Flac/Frame; (b, offset, count) here) local function crc8(b: buffer, o: number, n: number): number return Frame.crc8(b, o, o + n) end diff --git a/src/Formats/audio/flac/Frame.luau b/src/Formats/codecs/audio/Flac/Frame.luau similarity index 99% rename from src/Formats/audio/flac/Frame.luau rename to src/Formats/codecs/audio/Flac/Frame.luau index 049fee1..e723473 100644 --- a/src/Formats/audio/flac/Frame.luau +++ b/src/Formats/codecs/audio/Flac/Frame.luau @@ -1,7 +1,7 @@ --!strict --!native --!optimize 2 --- audio/flac/Frame: FLAC frames: header parsing (CRC-8), the sync search, subframes (constant, verbatim, fixed, LPC, wasted bits), +-- codecs/audio/Flac/Frame: FLAC frames: header parsing (CRC-8), the sync search, subframes (constant, verbatim, fixed, LPC, wasted bits), -- residuals (Rice / Rice2 partitions, escapes), stereo decorrelation and the CRC-16 check. -- -- The input buffer must have at least PAD zero bytes after the data end (`len`): the bit reader reads 32-bit diff --git a/src/Formats/codecs/audio/Flac/init.luau b/src/Formats/codecs/audio/Flac/init.luau new file mode 100644 index 0000000..441aedc --- /dev/null +++ b/src/Formats/codecs/audio/Flac/init.luau @@ -0,0 +1,11 @@ +--!strict +-- codecs/audio/Flac: FLAC frames without the container: frame header parsing, subframe decoding (constant, verbatim, +-- fixed, LPC, Rice residuals, stereo decorrelation) with CRC-8 / CRC-16 (Frame), and the frame encoder (Encode). +-- Absorbed from flac-luau 7083d0d (same author); the encoder is new. Native FLAC / Ogg FLAC streams, metadata and +-- seeking are audio/flac. +local Flac = { + Frame = require("@formats/codecs/audio/Flac/Frame"), + Encode = require("@formats/codecs/audio/Flac/Encode"), +} + +return Flac diff --git a/src/Formats/audio/mp3/Analysis.luau b/src/Formats/codecs/audio/Mpa/Analysis.luau similarity index 84% rename from src/Formats/audio/mp3/Analysis.luau rename to src/Formats/codecs/audio/Mpa/Analysis.luau index 782b023..f6535f6 100644 --- a/src/Formats/audio/mp3/Analysis.luau +++ b/src/Formats/codecs/audio/Mpa/Analysis.luau @@ -1,14 +1,14 @@ --!strict --!native --!optimize 2 --- audio/mp3/Analysis: the MPEG audio polyphase analysis filterbank (ISO/IEC 11172-3 section C.1.3, figure C.4): 32 +-- codecs/audio/Mpa/Analysis: the MPEG audio polyphase analysis filterbank (ISO/IEC 11172-3 section C.1.3, figure C.4): 32 -- input samples -> one sample in each of the 32 subbands, with the standard's 512-tap window C = D / 32 (D from --- audio/mp3/EncTables) and the matrixing M[k][i] = cos((2k + 1)(i - 16) pi / 64). Shared by the layer II and layer III +-- codecs/audio/Mpa/EncTables) and the matrixing M[k][i] = cos((2k + 1)(i - 16) pi / 64). Shared by the layer II and layer III -- encoders. New code from the standard's flow chart. Never throws. -- -- local st = Analysis.new() -- Analysis.run(st, samples, start, out, outStart) -- samples[start .. start + 31] -> out[outStart .. outStart + 31] -local E = require("@formats/audio/mp3/EncTables") +local E = require("@formats/codecs/audio/Mpa/EncTables") local Analysis = {} diff --git a/src/Formats/audio/mp3/Core.luau b/src/Formats/codecs/audio/Mpa/Core.luau similarity index 99% rename from src/Formats/audio/mp3/Core.luau rename to src/Formats/codecs/audio/Mpa/Core.luau index 1678548..de290ed 100644 --- a/src/Formats/audio/mp3/Core.luau +++ b/src/Formats/codecs/audio/Mpa/Core.luau @@ -1,12 +1,12 @@ --!strict --!native --!optimize 2 --- audio/mp3/Core: a line-by-line port of minimp3's mp3dec_decode_frame (https://github.com/lieff/minimp3, +-- codecs/audio/Mpa/Core: a line-by-line port of minimp3's mp3dec_decode_frame (https://github.com/lieff/minimp3, -- CC0) for layers I, II and III, using its scalar (non-SIMD) code paths and float output. -- State that must survive between frames (MDCT overlap, polyphase history, bit reservoir) lives in a per-stream -- state from Core.newState(); everything else is module scratch, so decoding is synchronous and allocation free. -- All buffer accesses stay in bounds by construction (padded scratch, bounded loops): native code must not throw. -local T = require("@formats/audio/mp3/Tables") +local T = require("@formats/codecs/audio/Mpa/Tables") local band, bor, lshift, rshift, arshift, bswap = bit32.band, bit32.bor, bit32.lshift, bit32.rshift, bit32.arshift, bit32.byteswap local ru8, wu8, ru32, ri16 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.readi16 diff --git a/src/Formats/audio/mp3/EncTables.luau b/src/Formats/codecs/audio/Mpa/EncTables.luau similarity index 99% rename from src/Formats/audio/mp3/EncTables.luau rename to src/Formats/codecs/audio/Mpa/EncTables.luau index e730723..02d6461 100644 --- a/src/Formats/audio/mp3/EncTables.luau +++ b/src/Formats/codecs/audio/Mpa/EncTables.luau @@ -1,5 +1,5 @@ --!strict --- audio/mp3/EncTables: tables for the MPEG audio encoders, from PDMP3 (public domain / unlicense, by Krister +-- codecs/audio/Mpa/EncTables: tables for the MPEG audio encoders, from PDMP3 (public domain / unlicense, by Krister -- Lagerstrom and contributors: licenses/PDMP3-UNLICENSE.txt), which transcribes ISO/IEC 11172-3: the synthesis window D -- (the analysis window is C = D / 32) and the layer III Huffman code trees (the encoders derive codeword tables from -- them). Trees use the standard's decoder layout: an entry with a high byte is a node (high byte: left offset, low diff --git a/src/Formats/audio/mp3/Encode2.luau b/src/Formats/codecs/audio/Mpa/Encode2.luau similarity index 96% rename from src/Formats/audio/mp3/Encode2.luau rename to src/Formats/codecs/audio/Mpa/Encode2.luau index 5d8db97..a31c7dd 100644 --- a/src/Formats/audio/mp3/Encode2.luau +++ b/src/Formats/codecs/audio/Mpa/Encode2.luau @@ -1,16 +1,16 @@ --!strict --!native --!optimize 2 --- audio/mp3/Encode2: an MPEG audio layer II (MP2) encoder: constant bit rate, MPEG-1 (32 / 44.1 / 48 kHz) and MPEG-2 +-- codecs/audio/Mpa/Encode2: an MPEG audio layer II (MP2) encoder: constant bit rate, MPEG-1 (32 / 44.1 / 48 kHz) and MPEG-2 -- low sampling frequencies (16 / 22.05 / 24 kHz), mono or stereo. New code written from ISO/IEC 11172-3 (2.4.2.3, --- C.1.5.2): the polyphase analysis (audio/mp3/Analysis), one scalefactor per 12-sample part (scfsi 0: all three are +-- C.1.5.2): the polyphase analysis (codecs/audio/Mpa/Analysis), one scalefactor per 12-sample part (scfsi 0: all three are -- sent), the standard bit allocation tables (in minimp3's compact form, CC0: licenses/minimp3-CC0.txt, as the decoder -- in this folder reads them), a greedy allocation that always gives the next step to the band with the most noise -- (signal level minus the quantizer's SNR; no psychoacoustic model), uniform midtread quantization and grouping of -- 3 / 5 / 9-level samples. Never throws. local Bits = require("@formats/core/Bits") -local T = require("@formats/audio/mp3/Tables") -local Analysis = require("@formats/audio/mp3/Analysis") +local T = require("@formats/codecs/audio/Mpa/Tables") +local Analysis = require("@formats/codecs/audio/Mpa/Analysis") local Encode2 = {} diff --git a/src/Formats/audio/mp3/Encode3.luau b/src/Formats/codecs/audio/Mpa/Encode3.luau similarity index 97% rename from src/Formats/audio/mp3/Encode3.luau rename to src/Formats/codecs/audio/Mpa/Encode3.luau index e088369..58c3a44 100644 --- a/src/Formats/audio/mp3/Encode3.luau +++ b/src/Formats/codecs/audio/Mpa/Encode3.luau @@ -1,17 +1,17 @@ --!strict --!native --!optimize 2 --- audio/mp3/Encode3: an MPEG audio layer III encoder in the spirit of shine: constant bit rate, long blocks only, +-- codecs/audio/Mpa/Encode3: an MPEG audio layer III encoder in the spirit of shine: constant bit rate, long blocks only, -- global-gain rate control (no psychoacoustic model, scalefactors all zero), no bit reservoir (main_data_begin = 0), -- MPEG-1 (32 / 44.1 / 48 kHz, two granules), MPEG-2 (16 / 22.05 / 24 kHz) and MPEG-2.5 (8 / 11.025 / 12 kHz), mono, -- stereo or joint (mid / side) stereo. New code written from ISO/IEC 11172-3 / 13818-3 (no shine / LAME code): the --- analysis filterbank (audio/mp3/Analysis), the 36-point MDCT with the sine window, the alias-reduction butterflies, +-- analysis filterbank (codecs/audio/Mpa/Analysis), the 36-point MDCT with the sine window, the alias-reduction butterflies, -- the x^(3/4) quantizer, big_values / count1 partitioning with per-region Huffman table choice; the Huffman codes are --- derived from the standard's decoder trees (audio/mp3/EncTables, from PDMP3, public domain). Never throws. +-- derived from the standard's decoder trees (codecs/audio/Mpa/EncTables, from PDMP3, public domain). Never throws. local Bits = require("@formats/core/Bits") -local E = require("@formats/audio/mp3/EncTables") -local T = require("@formats/audio/mp3/Tables") -local Analysis = require("@formats/audio/mp3/Analysis") +local E = require("@formats/codecs/audio/Mpa/EncTables") +local T = require("@formats/codecs/audio/Mpa/Tables") +local Analysis = require("@formats/codecs/audio/Mpa/Analysis") local Encode3 = {} diff --git a/src/Formats/audio/mp3/Header.luau b/src/Formats/codecs/audio/Mpa/Header.luau similarity index 95% rename from src/Formats/audio/mp3/Header.luau rename to src/Formats/codecs/audio/Mpa/Header.luau index 456f171..545cb42 100644 --- a/src/Formats/audio/mp3/Header.luau +++ b/src/Formats/codecs/audio/Mpa/Header.luau @@ -1,10 +1,10 @@ --!strict --!native --!optimize 2 --- audio/mp3/Header: MPEG audio frame headers (minimp3's hdr_* macros and functions), frame sync (mp3d_find_frame / +-- codecs/audio/Mpa/Header: MPEG audio frame headers (minimp3's hdr_* macros and functions), frame sync (mp3d_find_frame / -- mp3d_match_frame). Every function reads 4 header bytes at a byte offset of a buffer; callers keep offset + 4 -- inside the buffer. Never throws. -local T = require("@formats/audio/mp3/Tables") +local T = require("@formats/codecs/audio/Mpa/Tables") local band, bxor, rshift = bit32.band, bit32.bxor, bit32.rshift local ru8 = buffer.readu8 diff --git a/src/Formats/audio/mp3/Tables.luau b/src/Formats/codecs/audio/Mpa/Tables.luau similarity index 99% rename from src/Formats/audio/mp3/Tables.luau rename to src/Formats/codecs/audio/Mpa/Tables.luau index 40d661d..9ede813 100644 --- a/src/Formats/audio/mp3/Tables.luau +++ b/src/Formats/codecs/audio/Mpa/Tables.luau @@ -1,5 +1,5 @@ --!strict --- audio/mp3/Tables: constant tables of minimp3 (https://github.com/lieff/minimp3, CC0), generated by tools/gen_tables.py. +-- codecs/audio/Mpa/Tables: constant tables of minimp3 (https://github.com/lieff/minimp3, CC0), generated by tools/gen_tables.py. -- Every list is flattened row-major and 0-based (t[0] is the first element), like the C arrays. local T = {} T.halfrate = { [0] = 0, diff --git a/src/Formats/codecs/audio/Mpa/init.luau b/src/Formats/codecs/audio/Mpa/init.luau new file mode 100644 index 0000000..ff26891 --- /dev/null +++ b/src/Formats/codecs/audio/Mpa/init.luau @@ -0,0 +1,13 @@ +--!strict +-- codecs/audio/Mpa: MPEG audio layers I / II / III (ISO/IEC 11172-3, 13818-3, MPEG-2.5) without the file around it: +-- frame headers (Header), the decoder core (Core: a port of minimp3 by lieff, CC0: licenses/minimp3-CC0.txt, +-- absorbed from mp3-luau c755bbf) with its tables, and the layer III / layer II encoders (Encode3, Encode2: shine-style +-- CBR, new) with their analysis tables. ID3 tags, Xing / LAME gapless info, the frame index and seeking are audio/mp3. +local Mpa = { + Header = require("@formats/codecs/audio/Mpa/Header"), + Core = require("@formats/codecs/audio/Mpa/Core"), + Encode3 = require("@formats/codecs/audio/Mpa/Encode3"), + Encode2 = require("@formats/codecs/audio/Mpa/Encode2"), +} + +return Mpa diff --git a/src/Formats/audio/opus/Celt.luau b/src/Formats/codecs/audio/Opus/Celt.luau similarity index 99% rename from src/Formats/audio/opus/Celt.luau rename to src/Formats/codecs/audio/Opus/Celt.luau index f979aca..602b9fd 100644 --- a/src/Formats/audio/opus/Celt.luau +++ b/src/Formats/codecs/audio/Opus/Celt.luau @@ -1,15 +1,15 @@ --!strict --!native --!optimize 2 --- audio/opus/Celt: CELT decoder (RFC 6716 section 4.3), a port of the libopus float decoder: celt/celt_decoder.c, bands.c, vq.c, +-- codecs/audio/Opus/Celt: CELT decoder (RFC 6716 section 4.3), a port of the libopus float decoder: celt/celt_decoder.c, bands.c, vq.c, -- cwrs.c, rate.c, quant_bands.c, laplace.c, celt.c (comb filter). Only the standard 48 kHz / 960-sample mode is -- needed by Opus. Packet loss concealment is the noise-based variant only (no pitch PLC). -- -- Arrays are Luau tables of numbers. All normalised-band data (X, Y, the folding memory `norm` and the scratch -- copies) lives in one table W, and the "pointers" of the C code are 0-based offsets into it. local RD = require("@formats/codecs/entropy/RangeCoder/Decoder") -local Mdct = require("@formats/audio/opus/Mdct") -local T = require("@formats/audio/opus/CeltTables") +local Mdct = require("@formats/codecs/audio/Opus/Mdct") +local T = require("@formats/codecs/audio/Opus/CeltTables") local Celt = {} diff --git a/src/Formats/audio/opus/CeltEncoder.luau b/src/Formats/codecs/audio/Opus/CeltEncoder.luau similarity index 98% rename from src/Formats/audio/opus/CeltEncoder.luau rename to src/Formats/codecs/audio/Opus/CeltEncoder.luau index 662bd69..92d5f1a 100644 --- a/src/Formats/audio/opus/CeltEncoder.luau +++ b/src/Formats/codecs/audio/Opus/CeltEncoder.luau @@ -1,14 +1,14 @@ --!strict --!native --!optimize 2 --- audio/opus/CeltEncoder: a fixed-frame CELT encoder (RFC 6716 section 5.3): 20 ms frames (LM 3), full band, constant +-- codecs/audio/Opus/CeltEncoder: a fixed-frame CELT encoder (RFC 6716 section 5.3): 20 ms frames (LM 3), full band, constant -- bit rate, long MDCTs only (no transient detection), no pitch pre-filter, normal spreading, default allocation trim, -- mono, or stereo as mid / side per band (the angle, intensity when it has no bits; dual L / R stereo on request). The bitstream side is a port of the libopus 1.6 encoder paths -- (celt_encoder.c, quant_bands.c, laplace.c, rate.c, bands.c, vq.c, cwrs.c; BSD: licenses/libopus-BSD.txt) that --- mirror audio/opus/Celt's decoder step for step; the analysis is simplified. The MDCT is codecs/audio/Mdct. +-- mirror codecs/audio/Opus/Celt's decoder step for step; the analysis is simplified. The MDCT is codecs/audio/Mdct. -- Never throws. local RE = require("@formats/codecs/entropy/RangeCoder/Encoder") -local T = require("@formats/audio/opus/CeltTables") +local T = require("@formats/codecs/audio/Opus/CeltTables") local Mdct = require("@formats/codecs/audio/Mdct") local CeltEncoder = {} @@ -74,7 +74,7 @@ for i = 0, OVERLAP - 1 do WINDOW[i + 1] = math.sin(0.5 * math.pi * s * s) end local PLAN = Mdct.new(2 * N) :: Mdct.Plan --- forward scale matching the decoder's backward MDCT (calibrated against audio/opus/Mdct: tests/audio/opus_encode) +-- forward scale matching the decoder's backward MDCT (calibrated against codecs/audio/Opus/Mdct: tests/audio/opus_encode) local MDCT_SCALE = 2 / N -- PVQ codebook sizes U(n, k), flat: U[n * UK + k + 1] diff --git a/src/Formats/audio/opus/CeltTables.luau b/src/Formats/codecs/audio/Opus/CeltTables.luau similarity index 97% rename from src/Formats/audio/opus/CeltTables.luau rename to src/Formats/codecs/audio/Opus/CeltTables.luau index 5dd247f..1685c78 100644 --- a/src/Formats/audio/opus/CeltTables.luau +++ b/src/Formats/codecs/audio/Opus/CeltTables.luau @@ -1,5 +1,5 @@ --!strict --- audio/opus/CeltTables: Generated from libopus celt/static_modes_float.h and celt/quant_bands.c (BSD, see licenses/). 1-based arrays. +-- codecs/audio/Opus/CeltTables: Generated from libopus celt/static_modes_float.h and celt/quant_bands.c (BSD, see licenses/). 1-based arrays. return { logN400 = { 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 16, 16, 16, 21, 21, 24, 29, 34, 36, diff --git a/src/Formats/audio/opus/Decoder.luau b/src/Formats/codecs/audio/Opus/Decoder.luau similarity index 97% rename from src/Formats/audio/opus/Decoder.luau rename to src/Formats/codecs/audio/Opus/Decoder.luau index b93f0c1..4ac1ad5 100644 --- a/src/Formats/audio/opus/Decoder.luau +++ b/src/Formats/codecs/audio/Opus/Decoder.luau @@ -1,13 +1,13 @@ --!strict --!native --!optimize 2 --- audio/opus/Decoder: The Opus decoder proper (libopus src/opus_decoder.c and opus_multistream_decoder.c): per-frame mode switching +-- codecs/audio/Opus/Decoder: The Opus decoder proper (libopus src/opus_decoder.c and opus_multistream_decoder.c): per-frame mode switching -- between SILK, hybrid and CELT, the redundant CELT frames of mode transitions, cross-fades, PLC fallbacks, the -- multi-frame packet loop and multistream (channel mapping) decoding. Output is 48 kHz float in Luau arrays. local RD = require("@formats/codecs/entropy/RangeCoder/Decoder") -local Packet = require("@formats/audio/opus/Packet") -local Celt = require("@formats/audio/opus/Celt") -local Silk = require("@formats/audio/opus/Silk") +local Packet = require("@formats/codecs/audio/Opus/Packet") +local Celt = require("@formats/codecs/audio/Opus/Celt") +local Silk = require("@formats/codecs/audio/Opus/Silk") local Decoder = {} diff --git a/src/Formats/audio/opus/Mdct.luau b/src/Formats/codecs/audio/Opus/Mdct.luau similarity index 98% rename from src/Formats/audio/opus/Mdct.luau rename to src/Formats/codecs/audio/Opus/Mdct.luau index 4fff2ca..30bb34a 100644 --- a/src/Formats/audio/opus/Mdct.luau +++ b/src/Formats/codecs/audio/Opus/Mdct.luau @@ -1,7 +1,7 @@ --!strict --!native --!optimize 2 --- audio/opus/Mdct: CELT inverse MDCT (libopus celt/mdct.c clt_mdct_backward) over a mixed-radix complex FFT (a port of the +-- codecs/audio/Opus/Mdct: CELT inverse MDCT (libopus celt/mdct.c clt_mdct_backward) over a mixed-radix complex FFT (a port of the -- kiss_fft stages used by libopus: radix 5, 3, 4 and 2). The 48 kHz mode uses N = 1920 >> shift for -- shift = 0..3 (FFT sizes 480, 240, 120, 60). Arrays are Luau tables of numbers, 1-based. -- Why not codecs/audio/Mdct (measured by the cleanup pass): the shared transform computes the full N-sample IMDCT through a diff --git a/src/Formats/audio/opus/Packet.luau b/src/Formats/codecs/audio/Opus/Packet.luau similarity index 97% rename from src/Formats/audio/opus/Packet.luau rename to src/Formats/codecs/audio/Opus/Packet.luau index e8b5749..ae38311 100644 --- a/src/Formats/audio/opus/Packet.luau +++ b/src/Formats/codecs/audio/Opus/Packet.luau @@ -1,7 +1,7 @@ --!strict --!native --!optimize 2 --- audio/opus/Packet: Opus packet framing (RFC 6716 section 3): the TOC byte and frame packing codes 0-3, with padding. +-- codecs/audio/Opus/Packet: Opus packet framing (RFC 6716 section 3): the TOC byte and frame packing codes 0-3, with padding. local Packet = {} local readu8 = buffer.readu8 diff --git a/src/Formats/audio/opus/Silk.luau b/src/Formats/codecs/audio/Opus/Silk.luau similarity index 99% rename from src/Formats/audio/opus/Silk.luau rename to src/Formats/codecs/audio/Opus/Silk.luau index f85d798..b84c3f8 100644 --- a/src/Formats/audio/opus/Silk.luau +++ b/src/Formats/codecs/audio/Opus/Silk.luau @@ -1,7 +1,7 @@ --!strict --!native --!optimize 2 --- audio/opus/Silk: SILK decoder: a bit-exact port of the libopus fixed-point SILK decoder (silk/dec_API.c and what it calls: +-- codecs/audio/Opus/Silk: SILK decoder: a bit-exact port of the libopus fixed-point SILK decoder (silk/dec_API.c and what it calls: -- decode_frame, decode_indices, decode_pulses, shell_coder, code_signs, decode_parameters, gain_quant, NLSF_*, -- LPC_fit, LPC_inv_pred_gain, decode_core, stereo_*, CNG, PLC, resampler_private_up2_HQ / IIR_FIR). BSD, see -- licenses/. @@ -15,7 +15,7 @@ -- Fixed-point emulation: all values are Luau numbers holding C int32 / int16 values. Products of two int32 values -- (64-bit in C) are split so that every intermediate stays below 2^53 and therefore exact. local RD = require("@formats/codecs/entropy/RangeCoder/Decoder") -local T = require("@formats/audio/opus/SilkTables") +local T = require("@formats/codecs/audio/Opus/SilkTables") local icdf = RD.icdf local bitLogp = RD.bitLogp diff --git a/src/Formats/audio/opus/SilkTables.luau b/src/Formats/codecs/audio/Opus/SilkTables.luau similarity index 99% rename from src/Formats/audio/opus/SilkTables.luau rename to src/Formats/codecs/audio/Opus/SilkTables.luau index 0322c48..5b640ff 100644 --- a/src/Formats/audio/opus/SilkTables.luau +++ b/src/Formats/codecs/audio/Opus/SilkTables.luau @@ -1,6 +1,6 @@ --!strict --!optimize 2 --- audio/opus/SilkTables: SILK decoder tables (generated from libopus silk/tables_*.c, pitch_est_tables.c, resampler_rom.c; BSD, see +-- codecs/audio/Opus/SilkTables: SILK decoder tables (generated from libopus silk/tables_*.c, pitch_est_tables.c, resampler_rom.c; BSD, see -- licenses/). Multi-dimensional C arrays are flattened row-major; every array is 1-based. local T = {} T.LTP_per_index_iCDF = { diff --git a/src/Formats/codecs/audio/Opus/init.luau b/src/Formats/codecs/audio/Opus/init.luau new file mode 100644 index 0000000..37bd188 --- /dev/null +++ b/src/Formats/codecs/audio/Opus/init.luau @@ -0,0 +1,15 @@ +--!strict +-- codecs/audio/Opus: the Opus codec (RFC 6716) without its container: TOC / packet framing (Packet), the SILK and CELT +-- decoders and the multistream / hybrid decoder that drives them (Decoder), the CELT encoder (CeltEncoder) and the +-- CELT inverse MDCT (Mdct, a fused libopus port: see its header for why it is not codecs/audio/Mdct). A port of the +-- libopus 1.6 decoder (BSD: licenses/libopus-BSD.txt), absorbed from opus-luau dd2b4e5; the encoder is new. Ogg Opus +-- (OpusHead, OpusTags, granules, seeking) is audio/opus. +local Opus = { + Packet = require("@formats/codecs/audio/Opus/Packet"), + Decoder = require("@formats/codecs/audio/Opus/Decoder"), + Celt = require("@formats/codecs/audio/Opus/Celt"), + Silk = require("@formats/codecs/audio/Opus/Silk"), + CeltEncoder = require("@formats/codecs/audio/Opus/CeltEncoder"), +} + +return Opus diff --git a/src/Formats/audio/vorbis/Codebook.luau b/src/Formats/codecs/audio/Vorbis/Codebook.luau similarity index 98% rename from src/Formats/audio/vorbis/Codebook.luau rename to src/Formats/codecs/audio/Vorbis/Codebook.luau index 19c0da5..73af31c 100644 --- a/src/Formats/audio/vorbis/Codebook.luau +++ b/src/Formats/codecs/audio/Vorbis/Codebook.luau @@ -1,7 +1,7 @@ --!strict --!native --!optimize 2 --- audio/vorbis/Codebook: the Vorbis LSB-first packet bit reader and codebooks (Vorbis I spec sections 2 and 3): +-- codecs/audio/Vorbis/Codebook: the Vorbis LSB-first packet bit reader and codebooks (Vorbis I spec sections 2 and 3): -- reading a codebook from the setup header (ordered / sparse length lists, lookup types 1 and 2, float32_unpack), -- the codeword assignment, and Huffman / VQ decoding. Ported from stb_vorbis 1.22 (public domain / MIT; see -- licenses/stb_vorbis-LICENSE.txt): compute_codewords' lowest-free-leaf assignment, lookup1_values; the decode side diff --git a/src/Formats/audio/vorbis/Packet.luau b/src/Formats/codecs/audio/Vorbis/Packet.luau similarity index 98% rename from src/Formats/audio/vorbis/Packet.luau rename to src/Formats/codecs/audio/Vorbis/Packet.luau index 791745a..e83fbcd 100644 --- a/src/Formats/audio/vorbis/Packet.luau +++ b/src/Formats/codecs/audio/Vorbis/Packet.luau @@ -1,7 +1,7 @@ --!strict --!native --!optimize 2 --- audio/vorbis/Packet: Vorbis audio packet decoding (Vorbis I spec sections 4.3, 7, 8): mode and window shape, floor 1 +-- codecs/audio/Vorbis/Packet: Vorbis audio packet decoding (Vorbis I spec sections 4.3, 7, 8): mode and window shape, floor 1 -- curves, residue types 0 / 1 / 2, inverse channel coupling, the IMDCT (codecs/audio/Mdct), windowing and overlap-add. -- Floors, residues and coupling are ported from stb_vorbis 1.22 vorbis_decode_packet_rest / decode_residue / -- do_floor / draw_line (public domain / MIT; see licenses/stb_vorbis-LICENSE.txt). The overlap follows libvorbis: @@ -13,9 +13,9 @@ -- Packet.reset(st) -- forget the overlap (after a seek / a gap) -- local bs = Packet.blocksize(st, buf, offset, size) -- the packet's block size (0 = not audio), header bits only -- Never throws: a damaged packet decodes as far as its bits go (the spec's end-of-packet rule) or returns -1. -local Codebook = require("@formats/audio/vorbis/Codebook") -local Setup = require("@formats/audio/vorbis/Setup") -local Tables = require("@formats/audio/vorbis/Tables") +local Codebook = require("@formats/codecs/audio/Vorbis/Codebook") +local Setup = require("@formats/codecs/audio/Vorbis/Setup") +local Tables = require("@formats/codecs/audio/Vorbis/Tables") local Mdct = require("@formats/codecs/audio/Mdct") local Packet = {} diff --git a/src/Formats/audio/vorbis/Setup.luau b/src/Formats/codecs/audio/Vorbis/Setup.luau similarity index 98% rename from src/Formats/audio/vorbis/Setup.luau rename to src/Formats/codecs/audio/Vorbis/Setup.luau index e5eb312..c6ea25a 100644 --- a/src/Formats/audio/vorbis/Setup.luau +++ b/src/Formats/codecs/audio/Vorbis/Setup.luau @@ -1,11 +1,11 @@ --!strict --!native --- audio/vorbis/Setup: the three Vorbis header packets (Vorbis I spec section 4.2): identification (channels, rate, +-- codecs/audio/Vorbis/Setup: the three Vorbis header packets (Vorbis I spec section 4.2): identification (channels, rate, -- bitrates, blocksizes), comment (vendor + user comments -> tags) and setup (codebooks, floors, residues, mappings, -- modes). Ported from stb_vorbis 1.22 start_decoder (public domain / MIT; see licenses/stb_vorbis-LICENSE.txt). -- Floor 0 is rejected as unsupported, as stb_vorbis does (no encoder has produced it since 2000). -- Never throws: every parser returns nil, message on bad data. -local Codebook = require("@formats/audio/vorbis/Codebook") +local Codebook = require("@formats/codecs/audio/Vorbis/Codebook") local Setup = {} diff --git a/src/Formats/audio/vorbis/Tables.luau b/src/Formats/codecs/audio/Vorbis/Tables.luau similarity index 96% rename from src/Formats/audio/vorbis/Tables.luau rename to src/Formats/codecs/audio/Vorbis/Tables.luau index 435f719..55e3ec9 100644 --- a/src/Formats/audio/vorbis/Tables.luau +++ b/src/Formats/codecs/audio/Vorbis/Tables.luau @@ -1,5 +1,5 @@ --!strict --- audio/vorbis/Tables: the floor 1 inverse dB table (Vorbis I specification, section 10.1, as in stb_vorbis 1.22, +-- codecs/audio/Vorbis/Tables: the floor 1 inverse dB table (Vorbis I specification, section 10.1, as in stb_vorbis 1.22, -- public domain / MIT, licenses/stb_vorbis-LICENSE.txt). 256 values, index = floor value (1-based here). return table.freeze({ 1.0649863e-07, 1.1341951e-07, 1.2079015e-07, 1.2863978e-07, 1.3699951e-07, 1.4590251e-07, 1.5538408e-07, 1.6548181e-07, diff --git a/src/Formats/codecs/audio/Vorbis/init.luau b/src/Formats/codecs/audio/Vorbis/init.luau new file mode 100644 index 0000000..59bef7b --- /dev/null +++ b/src/Formats/codecs/audio/Vorbis/init.luau @@ -0,0 +1,13 @@ +--!strict +-- codecs/audio/Vorbis: the Vorbis I decoder without its container: identification / comment / setup headers (Setup), +-- codebooks (Codebook), audio packets to PCM (Packet: floors 0 / 1, residues 0 / 1 / 2, coupling, the IMDCT through +-- codecs/audio/Mdct) and the shared tables. A Luau port of stb_vorbis 1.22 (public domain / MIT, +-- licenses/stb_vorbis-LICENSE.txt). Ogg Vorbis (pages, granules, seeking) and the encoder are audio/vorbis. +local Vorbis = { + Setup = require("@formats/codecs/audio/Vorbis/Setup"), + Codebook = require("@formats/codecs/audio/Vorbis/Codebook"), + Packet = require("@formats/codecs/audio/Vorbis/Packet"), + Tables = require("@formats/codecs/audio/Vorbis/Tables"), +} + +return Vorbis diff --git a/tests/audio/opus.luau b/tests/audio/opus.luau index 7f8518e..1bead97 100644 --- a/tests/audio/opus.luau +++ b/tests/audio/opus.luau @@ -6,11 +6,11 @@ -- Ported from opus-luau tests/opus.luau, celt.luau, silk.luau, fuzz.luau. Fixtures: tools/fixtures/opus.py. local T = require("@tests/T") local Opus = require("@formats/audio/opus") -local Packet = require("@formats/audio/opus/Packet") -local Celt = require("@formats/audio/opus/Celt") -local Silk = require("@formats/audio/opus/Silk") +local Packet = require("@formats/codecs/audio/Opus/Packet") +local Celt = require("@formats/codecs/audio/Opus/Celt") +local Silk = require("@formats/codecs/audio/Opus/Silk") local RD = require("@formats/codecs/entropy/RangeCoder/Decoder") -local Decoder = require("@formats/audio/opus/Decoder") +local Decoder = require("@formats/codecs/audio/Opus/Decoder") local Ogg = require("@formats/containers/Ogg") local Bytes = require("@formats/core/Bytes") local Pcm = require("@formats/codecs/audio/Pcm") From 7cfec05eeb55b3cddb3890310267be24eab6afd1 Mon Sep 17 00:00:00 2001 From: 4DBug <github@bug.tools> Date: Sat, 31 Oct 2026 13:19:43 -0500 Subject: [PATCH 22/22] ws-cleanup: Pcm.collect reads a known length in one call into the result (no copy); README links the guide Measured in an A/B of the touched paths (best of 3-4, one core): LuaJIT wav decode through Pcm.drain was ~10% slower than the old single read; now within noise. --- README.md | 3 ++- src/Formats/codecs/audio/Pcm/init.luau | 10 ++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 746ab76..0fcb581 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,8 @@ generation) and on **LuaJIT / LÖVE** (through `tools/build.py`). Every format o About 76 formats across images, audio, video, 3D models, CAD, fonts, archives, data, vector graphics, layered images, subtitles, music and playlists: see [docs/FORMATS.md](docs/FORMATS.md) (generated from the code) for the list and each -format's capabilities, and [docs/API.md](docs/API.md) for the whole API. +format's capabilities, [docs/API.md](docs/API.md) for the whole API, and the guide +([docs/guide/README.md](docs/guide/README.md)) for walkthroughs. ```luau local F = require(Formats) -- LuaJIT: require("formats"); luau CLI: require("@formats") diff --git a/src/Formats/codecs/audio/Pcm/init.luau b/src/Formats/codecs/audio/Pcm/init.luau index 3b8118c..cabb8e0 100644 --- a/src/Formats/codecs/audio/Pcm/init.luau +++ b/src/Formats/codecs/audio/Pcm/init.luau @@ -117,6 +117,16 @@ function Pcm.collect(src: Source, maxFrames: number?): (Types.Audio?, Err.Err?) local total = 0 local limit = maxFrames or 2 ^ 31 local tmp: buffer? = nil + -- a known length: one read straight into the result (decoders write into a big enough out buffer: no copy) + if src.frames > 0 and src.frames <= limit then + local b, n = src:read(src.frames, data) + if n > 0 then + if b ~= data then + buffer.copy(data, 0, b, 0, math.min(n, cap) * ch * 4) + end + total = math.min(n, cap) + end + end while true do local b, n = src:read(16384, tmp) if n <= 0 then