diff --git a/.gitignore b/.gitignore index f7b15d8..25e75c5 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,9 @@ -# build outputs (tools/build.py): the single-file bundles and their linemaps are committed, the rest is internal +# build outputs (tools/build.py): the bundles (Rosetta.luau, Rosetta.rbxm / .rbxmx, rosetta.lua) and their linemaps are committed, the rest is internal /build/* !/build/Rosetta.luau !/build/rosetta.lua +!/build/Rosetta.rbxm +!/build/Rosetta.rbxmx !/build/*.linemap.json # generated test fixtures (tools/fixtures.py) /tests/gen/ diff --git a/README.md b/README.md index 7af4b19..ec22558 100644 --- a/README.md +++ b/README.md @@ -4,9 +4,11 @@ Read, write and convert file formats in pure Luau, on Roblox, LuaJIT / LÖVE and ## Install -- **Roblox:** put [`build/Rosetta.luau`](build/Rosetta.luau) in a ModuleScript (e.g. ReplicatedStorage.Rosetta), - or mount it with Rojo (`"Rosetta": { "$path": "rosetta/build/Rosetta.luau" }`; this repo's `default.project.json` - does). Then `local F = require(ReplicatedStorage.Rosetta)`. +- **Roblox (native):** insert [`build/Rosetta.rbxm`](build/Rosetta.rbxm) (a `Rosetta` ModuleScript whose child chunks + load on first use, each compiled natively), or mount it with Rojo (`"$path": "rosetta/build/Rosetta.rbxm"`; this + repo's `default.project.json` does). Then `local F = require(ReplicatedStorage.Rosetta)`. +- **Roblox (one file, no native code):** paste [`build/Rosetta.luau`](build/Rosetta.luau) into a ModuleScript, or mount + it with Rojo (`"$path": "rosetta/build/Rosetta.luau"`). Same API; interpreted, so the codecs run slower. - **LÖVE / LuaJIT:** copy [`build/rosetta.lua`](build/rosetta.lua). `local F = require("rosetta")` with its folder on `package.path`, or `local F = dofile("rosetta.lua")`. - **Luau CLI:** alias the sources in `.luaurc` (`"rosetta": "rosetta/src/Rosetta"`), then diff --git a/build/Rosetta.luau b/build/Rosetta.luau index 7d956b2..b6b948e 100644 --- a/build/Rosetta.luau +++ b/build/Rosetta.luau @@ -1,6 +1,8 @@ --!optimize 2 --!nocheck --- rosetta (Roblox bundle): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- rosetta (Roblox bundle, no native code): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- One ModuleScript, interpreted: as one module it is over Roblox's per-module native codegen budget, so it +-- carries no --!native / @native. build/Rosetta.rbxm is the native build (chunked, loaded on demand). -- require(this) -> the API (docs/API.md); Rosetta._internal("codecs/video/Mpeg1") -> an internal module. -- Error lines map back to the sources through Rosetta.luau.linemap.json (python3 -I tools/bundle.py --where). local __FILES = {} @@ -6853,7 +6855,7 @@ end return Cab end -__FILES["archive/cab/Sum"] = @native function() +__FILES["archive/cab/Sum"] = function() @@ -6865,7 +6867,7 @@ local bxor, bor, lshift = bit32.bxor, bit32.bor, bit32.lshift local Sum = {} -@native function Sum.of(buf: buffer, off: number, len: number, seed: number): number +function Sum.of(buf: buffer, off: number, len: number, seed: number): number if off < 0 or len <= 0 or off + len > blen(buf) then return seed end @@ -6888,7 +6890,7 @@ local Sum = {} return bxor(s, tail) end -@native function Sum.block(buf: buffer, dataAt: number, cbData: number, cbUncomp: number): number +function Sum.block(buf: buffer, dataAt: number, cbData: number, cbUncomp: number): number return bxor(Sum.of(buf, dataAt, cbData, 0), cbData + cbUncomp * 65536) end @@ -9342,7 +9344,7 @@ Mpq.hash = Crypt.hash return Mpq end -__FILES["archive/mpq/Crypt"] = @native function() +__FILES["archive/mpq/Crypt"] = function() -- archive/mpq/Crypt: the MPQ encryption table, name hash (0 = table index, 1 / 2 = name check, 3 = file key) and @@ -9370,7 +9372,7 @@ do end -- name hash: ASCII upper case, '/' as '\' -@native function Crypt.hash(name: string, kind: number): number +function Crypt.hash(name: string, kind: number): number local s1, s2 = 0x7FED7FED, 0xEEEEEEEE local base = kind * 0x100 for i = 1, #name do @@ -9387,7 +9389,7 @@ end end -- whole u32s; a trailing partial word is left as is -@native function Crypt.decrypt(buf: buffer, at: number, n: number, key: number) +function Crypt.decrypt(buf: buffer, at: number, n: number, key: number) local s2 = 0xEEEEEEEE local k = key % TWO32 for i = 0, n // 4 - 1 do @@ -9401,7 +9403,7 @@ end end -- the file key uses the base name -@native function Crypt.baseName(name: string): string +function Crypt.baseName(name: string): string return string.match(name, "([^\\/]*)$") or name end @@ -11444,7 +11446,7 @@ end return Map end -__FILES["archive/wad/Picture"] = @native function() +__FILES["archive/wad/Picture"] = function() -- archive/wad/Picture: Doom picture lumps (column posts: topdelta / length / pad / pixels / pad; DeePsea tall patches: @@ -11454,7 +11456,7 @@ local readu8, readu16, readi16, readu32, writeu32 = buffer.readu8, buffer.readu1 local Picture = {} -@native function Picture.header(b: buffer, at: number, n: number): (number?, number, number, number) +function Picture.header(b: buffer, at: number, n: number): (number?, number, number, number) if n < 8 then return nil, 0, 0, 0 end @@ -11471,7 +11473,7 @@ local Picture = {} return w, h, readi16(b, at + 4), readi16(b, at + 6) end -@native function Picture.decode(b: buffer, at: number, n: number, pal: buffer, out: buffer, w: number, h: number): (boolean, string?) +function Picture.decode(b: buffer, at: number, n: number, pal: buffer, out: buffer, w: number, h: number): (boolean, string?) local stop = at + n for x = 0, w - 1 do local p = at + readu32(b, at + 8 + x * 4) @@ -11505,7 +11507,7 @@ end return true, nil end -@native function Picture.flatSize(n: number): (number?, number) +function Picture.flatSize(n: number): (number?, number) if n == 4096 then return 64, 64 elseif n == 4160 then @@ -11525,13 +11527,13 @@ end return nil, 0 end -@native function Picture.flat(b: buffer, at: number, w: number, h: number, pal: buffer, out: buffer) +function Picture.flat(b: buffer, at: number, w: number, h: number, pal: buffer, out: buffer) for i = 0, w * h - 1 do writeu32(out, i * 4, readu32(pal, readu8(b, at + i) * 4)) end end -@native function Picture.blit(src: buffer, sw: number, sh: number, dst: buffer, dw: number, dh: number, ox: number, oy: number) +function Picture.blit(src: buffer, sw: number, sh: number, dst: buffer, dw: number, dh: number, ox: number, oy: number) local x0, x1 = math.max(0, -ox), math.min(sw, dw - ox) - 1 for y = math.max(0, -oy), math.min(sh, dh - oy) - 1 do local so, d = y * sw, (y + oy) * dw + ox @@ -15002,7 +15004,7 @@ Flac.Ogg = Ogg return Flac end -__FILES["audio/flac/Meta"] = @native function() +__FILES["audio/flac/Meta"] = function() @@ -15013,13 +15015,13 @@ local readu8, readu32 = buffer.readu8, buffer.readu32 local Meta = {} -@native local function be16(b: buffer, p: number): number +local function be16(b: buffer, p: number): number return readu8(b, p) * 256 + readu8(b, p + 1) end -@native local function be24(b: buffer, p: number): number +local function be24(b: buffer, p: number): number return readu8(b, p) * 65536 + readu8(b, p + 1) * 256 + readu8(b, p + 2) end -@native local function be32(b: buffer, p: number): number +local function be32(b: buffer, p: number): number return be16(b, p) * 65536 + be16(b, p + 2) end @@ -15059,7 +15061,7 @@ type Info = { firstFrame: number, -- byte offset just after the last metadata block } -@native local function streamInfo(b: buffer, p: number): StreamInfo +local function streamInfo(b: buffer, p: number): StreamInfo local b12, b13 = readu8(b, p + 12), readu8(b, p + 13) local hex = table.create(16) for i = 0, 15 do @@ -15078,7 +15080,7 @@ type Info = { } end -@native local function vorbisComment(b: buffer, p: number, e: number, info: Info): boolean +local function vorbisComment(b: buffer, p: number, e: number, info: Info): boolean if p + 4 > e then return false end @@ -15117,7 +15119,7 @@ end return true end -@native local function picture(b: buffer, p: number, e: number): Picture? +local function picture(b: buffer, p: number, e: number): Picture? if p + 8 > e then return nil end @@ -15153,7 +15155,7 @@ end return pic end -@native function Meta.parse(b: buffer, pos: number, len: number): (Info?, string?) +function Meta.parse(b: buffer, pos: number, len: number): (Info?, string?) if pos + 4 > len or buffer.readstring(b, pos, 4) ~= "fLaC" then return nil, "Flac: no fLaC marker" end @@ -15224,7 +15226,7 @@ end return Meta end -__FILES["audio/flac/Stream"] = @native function() +__FILES["audio/flac/Stream"] = function() @@ -15264,11 +15266,11 @@ type Decoder = { local Dec = {} Dec.__index = Dec -@native local function sampleOf(self: any, h: Header): number +local function sampleOf(self: any, h: Header): number return if h.variable then h.number else h.number * self._nominal end -@native local function plausible(self: any, h: Header): boolean +local function plausible(self: any, h: Header): boolean if h.channels ~= self.channels or h.bps ~= self.bitsPerSample or h.blockSize > 65536 then return false end @@ -15278,7 +15280,7 @@ end return true end -@native local function findFrame(self: any, pos: number, limit: number): Header? +local function findFrame(self: any, pos: number, limit: number): Header? local b, len, si = self._b, self._len, self._si while true do local h = Frame.find(b, pos, limit, len, si) @@ -15292,7 +15294,7 @@ end end end -@native local function ensure(self: any, n: number) +local function ensure(self: any, n: number) if n > self._cap then for c = 1, self.channels do self._chans[c] = table.create(n, 0) @@ -15301,7 +15303,7 @@ end end end -@native local function decodeAt(self: any, pos: number): boolean +local function decodeAt(self: any, pos: number): boolean local b, len = self._b, self._len while true do local h = Frame.header(b, pos, len, self._si) @@ -15330,7 +15332,7 @@ end end end -@native local function pull(self: any, maxFrames: number, asInt: boolean, dst: buffer?): (buffer, number) +local function pull(self: any, maxFrames: number, asInt: boolean, dst: buffer?): (buffer, number) local ch = self.channels local want = math.floor(tonumber(maxFrames) or 0) if not (want >= 0) then @@ -15379,20 +15381,20 @@ end return out, got end -@native function Dec.read(self: any, maxFrames: number, out: buffer?): (buffer, number) +function Dec.read(self: any, maxFrames: number, out: buffer?): (buffer, number) return pull(self, maxFrames, false, out) end -@native function Dec.readInt(self: any, maxFrames: number, out: buffer?): (buffer, number) +function Dec.readInt(self: any, maxFrames: number, out: buffer?): (buffer, number) return pull(self, maxFrames, true, out) end -@native function Dec.position(self: any): (number, number) +function Dec.position(self: any): (number, number) local s = self._fs + self._cur return s / self.sampleRate, s end -@native function Dec.seekSample(self: any, t: number): boolean +function Dec.seekSample(self: any, t: number): boolean t = math.floor(tonumber(t) or 0) if not (t >= 0) then t = 0 @@ -15454,11 +15456,11 @@ end end end -@native function Dec.seek(self: any, seconds: number): boolean +function Dec.seek(self: any, seconds: number): boolean return self:seekSample(math.floor((tonumber(seconds) or 0) * self.sampleRate + 0.5)) end -@native local function scanLength(self: any): number +local function scanLength(self: any): number local len = self._len local step = math.max(65536, 2 * self._si.maxFrameSize) local from = len @@ -15484,7 +15486,7 @@ end return 0 end -@native local function skipId3(b: buffer, base: number, len: number): number +local function skipId3(b: buffer, base: number, len: number): number local p = 0 while p + 10 <= len and buffer.readstring(b, base + p, 3) == "ID3" do local sz = 0 @@ -15497,7 +15499,7 @@ end return p end -@native function Stream.open(buf: buffer, base: number, srcLen: number, opts: { crc16: boolean? }?): (Decoder?, string?, string?) +function Stream.open(buf: buffer, base: number, srcLen: number, opts: { crc16: boolean? }?): (Decoder?, string?, string?) local b, len, container if srcLen >= 4 and buffer.readstring(buf, base, 4) == "OggS" then local demux, err = Ogg.open(Bytes.reader(buf, base, srcLen)) @@ -16188,7 +16190,7 @@ Mp3.Tags = Tags return Mp3 end -__FILES["audio/mp3/Index"] = @native function() +__FILES["audio/mp3/Index"] = function() @@ -16230,13 +16232,13 @@ type Index = { skipped: number, -- frames with another sample rate or layer, left out } -@native local function grow(b: buffer, n: number): buffer +local function grow(b: buffer, n: number): buffer local nb = buffer.create(n) buffer.copy(nb, 0, b, 0, math.min(buffer.len(b), n)) return nb end -@native function Index.build(b: buffer, start: number, stop: number): Index? +function Index.build(b: buffer, start: number, stop: number): Index? local cap = 1024 local OFF, SIZE, FLAGS, OUT, MAIN = buffer.create(cap * 4), buffer.create(cap * 2), buffer.create(cap), buffer.create(cap * 4), buffer.create(cap * 2) local n = 0 @@ -18751,7 +18753,7 @@ end return Vorbis end -__FILES["audio/vorbis/Encode"] = @native function() +__FILES["audio/vorbis/Encode"] = function() @@ -18783,11 +18785,11 @@ local NCLASS = 6 -- ------------------------------------------------------------------------------------------------ LSB-first bit writer type W = { buf: buffer, pos: number, acc: number, cnt: number } -@native local function newW(size: number): W +local function newW(size: number): W return { buf = buffer.create(size), pos = 0, acc = 0, cnt = 0 } end -@native local function put(w: W, v: number, n: number) +local function put(w: W, v: number, n: number) if n == 0 then return end @@ -18810,7 +18812,7 @@ end w.acc, w.cnt, w.pos = acc, cnt, p end -@native local function finish(w: W): buffer +local function finish(w: W): buffer if w.cnt > 0 then put(w, 0, 8 - w.cnt) end @@ -18819,13 +18821,13 @@ end return out end -@native local function putString(w: W, s: string) +local function putString(w: W, s: string) for i = 1, #s do put(w, string.byte(s, i), 8) end end -@native local function ilog(x: number): number +local function ilog(x: number): number local n = 0 while x > 0 do n += 1 @@ -18846,7 +18848,7 @@ type Book = { values: number, -- lookup1 values per dimension } -@native local function huffmanLengths(w: { number }): { number } +local function huffmanLengths(w: { number }): { number } local n = #w local total = 0 for i = 1, n do @@ -18867,7 +18869,7 @@ type Book = { for i = 1, n do weight[i] = math.max(w[i], minw) end - table.sort(order, @native function(a: number, b: number): boolean + table.sort(order, function(a: number, b: number): boolean if weight[a] ~= weight[b] then return weight[a] < weight[b] end @@ -18876,7 +18878,7 @@ type Book = { local q1, h1 = order, 1 local q2, h2, t2 = table.create(n, 0), 1, 0 local nextId = n - @native local function pop(): number + local function pop(): number local a = if h1 <= n then q1[h1] else nil local b = if h2 <= t2 then q2[h2] else nil if a and (not b or weight[a] <= weight[b]) then @@ -18907,7 +18909,7 @@ type Book = { end -- the spec's codeword assignment (lowest free leaf, in entry order) -@native local function assign(lens: { number }): { number } +local function assign(lens: { number }): { number } local codes = table.create(#lens, 0) local available = table.create(33, 0) local first = true @@ -18944,7 +18946,7 @@ end return codes end -@native local function makeBook(dims: number, entries: number, weight: (number) -> number, lookup: number, minimum: number, delta: number, values: number): Book +local function makeBook(dims: number, entries: number, weight: (number) -> number, lookup: number, minimum: number, delta: number, values: number): Book local w = table.create(entries, 0) for e = 0, entries - 1 do w[e + 1] = weight(e) @@ -18953,10 +18955,10 @@ end return { dims = dims, entries = entries, lengths = lens, codes = assign(lens), lookup = lookup, minimum = minimum, delta = delta, values = values } end -@native local function vqBook(dims: number, h: number, scale: number, s: number, zeroBoost: number): Book +local function vqBook(dims: number, h: number, scale: number, s: number, zeroBoost: number): Book local values = 2 * h + 1 local entries = values ^ dims - return makeBook(dims, entries, @native function(e: number): number + return makeBook(dims, entries, function(e: number): number local wt = 1 local x = e for _ = 1, dims do @@ -18968,11 +18970,11 @@ end end, 1, -h * scale, scale, values) end -local BOOK_FLOOR = makeBook(1, RANGE, @native function(e: number): number +local BOOK_FLOOR = makeBook(1, RANGE, function(e: number): number return exp(-e / 7) + 0.002 end, 0, 0, 0, 0) local CLASS_W = { 0.30, 0.30, 0.20, 0.12, 0.06, 0.02 } -local BOOK_CLASS = makeBook(2, NCLASS * NCLASS, @native function(e: number): number +local BOOK_CLASS = makeBook(2, NCLASS * NCLASS, function(e: number): number return CLASS_W[e % NCLASS + 1] * CLASS_W[e // NCLASS + 1] end, 0, 0, 0, 0) local BOOK_A = vqBook(4, 1, 1, 0.6, 2.5) -- |v| <= 1, 4 at a time (mostly zeros) @@ -18994,7 +18996,7 @@ local CLASS_BOOKS = { local CLASS_MAX = { 0, 1, 4, 15, 255, 4095 } -- float32_pack (spec 9.2.2) of an integer-valued x -@native local function float32Pack(x: number): number +local function float32Pack(x: number): number local sign = if x < 0 then 2147483648 else 0 local m = abs(x) local e = 788 @@ -19005,7 +19007,7 @@ local CLASS_MAX = { 0, 1, 4, 15, 255, 4095 } return sign + e * 2097152 + floor(m) end -@native local function writeBook(w: W, b: Book) +local function writeBook(w: W, b: Book) put(w, 0x564342, 24) put(w, b.dims, 16) put(w, b.entries, 24) @@ -19027,7 +19029,7 @@ end end end -@native local function putEntry(w: W, b: Book, e: number) +local function putEntry(w: W, b: Book, e: number) put(w, b.codes[e + 1], b.lengths[e + 1]) end @@ -19065,7 +19067,7 @@ local SORTED: { number } = table.create(NPOSTS, 0) -- post indices (1-based) by for i = 1, NPOSTS do SORTED[i] = i end -table.sort(SORTED, @native function(a: number, b: number): boolean +table.sort(SORTED, function(a: number, b: number): boolean return POSTS[a] < POSTS[b] end) local LOW, HIGH = table.create(NPOSTS, 0), table.create(NPOSTS, 0) @@ -19087,12 +19089,12 @@ local DB = table.create(RANGE, 0) for y = 0, RANGE - 1 do DB[y + 1] = 20 * math.log10(Tables[y * MULT + 1]) end -@native local function yOf(db: number): number +local function yOf(db: number): number local y = floor((db - DB[1]) / (DB[RANGE] - DB[1]) * (RANGE - 1) + 0.5) return math.clamp(y, 0, RANGE - 1) end -@native local function predict(x: number, x0: number, x1: number, y0: number, y1: number): number +local function predict(x: number, x0: number, x1: number, y0: number, y1: number): number local dy = y1 - y0 local adx = x1 - x0 local off = (abs(dy) * (x - x0)) // adx @@ -19100,7 +19102,7 @@ end end -- render the decoder's floor curve for final Y values into F[1..N2] (only the posts the decoder marks used) -@native local function renderFloor(Y: { number }, used: { boolean }, F: { number }) +local function renderFloor(Y: { number }, used: { boolean }, F: { number }) local lx, ly = 0, Y[1] * MULT for q = 2, NPOSTS do local j = SORTED[q] @@ -19140,7 +19142,7 @@ end end -- the coded value for target t at post j given the final values of its neighbours (spec 7.2.4 step 1, inverted) -@native local function floorVal(Y: { number }, j: number): number +local function floorVal(Y: { number }, j: number): number local lo, hi = LOW[j], HIGH[j] local pred = predict(POSTS[j], POSTS[lo], POSTS[hi], Y[lo], Y[hi]) local t = Y[j] @@ -19171,7 +19173,7 @@ end end -- ------------------------------------------------------------------------------------------------ headers -@native local function identHeader(ch: number, rate: number, nominal: number): buffer +local function identHeader(ch: number, rate: number, nominal: number): buffer local w = newW(64) put(w, 1, 8) putString(w, "vorbis") @@ -19187,7 +19189,7 @@ end return finish(w) end -@native local function commentHeader(vendor: string, tags: { [string]: string }): buffer +local function commentHeader(vendor: string, tags: { [string]: string }): buffer local w = newW(256) put(w, 3, 8) putString(w, "vorbis") @@ -19203,7 +19205,7 @@ end return finish(w) end -@native local function setupHeader(ch: number): buffer +local function setupHeader(ch: number): buffer local w = newW(8192) put(w, 5, 8) putString(w, "vorbis") @@ -19302,7 +19304,7 @@ type Options = { serial: number, } -@native local function writePartition(w: W, v: { number }, o: number, psize: number, c: number, pass: number) +local function writePartition(w: W, v: { number }, o: number, psize: number, c: number, pass: number) local b = CLASS_BOOKS[c][pass] if b < 0 then return @@ -19333,7 +19335,7 @@ type Options = { end end -@native function Encode.encode(src: Source, opts: Options): (buffer?, string?) +function Encode.encode(src: Source, opts: Options): (buffer?, string?) local ch, rate = src.channels, src.sampleRate local q = math.clamp(opts.quality, -1, 10) local snrDb = 2 * q - 1 -- floor level below the band energy (at low frequencies; 8 dB less at the top) @@ -20185,7 +20187,7 @@ end return Wav end -__FILES["audio/wav/Codecs"] = @native function() +__FILES["audio/wav/Codecs"] = function() @@ -20199,7 +20201,7 @@ local writeu8, writeu16, writei16, writei32 = buffer.writeu8, buffer.writeu16, b local Codecs = {} -- integer PCM: 1 byte = unsigned, 2 / 3 / 4 bytes = signed -@native function Codecs.int(src: buffer, off: number, dst: buffer, d: number, count: number, bytes: number, be: boolean) +function Codecs.int(src: buffer, off: number, dst: buffer, d: number, count: number, bytes: number, be: boolean) local o = d * 4 if bytes == 1 then for i = 0, count - 1 do @@ -20248,7 +20250,7 @@ local Codecs = {} end end -@native function Codecs.float(src: buffer, off: number, dst: buffer, d: number, count: number, bytes: number, be: boolean, +function Codecs.float(src: buffer, off: number, dst: buffer, d: number, count: number, bytes: number, be: boolean, tmp: buffer) local o = d * 4 if bytes == 4 then @@ -20278,18 +20280,18 @@ end end end -@native function Codecs.law(src: buffer, off: number, dst: buffer, d: number, count: number, tbl: buffer) +function Codecs.law(src: buffer, off: number, dst: buffer, d: number, count: number, tbl: buffer) local o = d * 4 for i = 0, count - 1 do writef32(dst, o + i * 4, readf32(tbl, readu8(src, off + i) * 4)) end end -@native function Codecs.copy(src: buffer, sOff: number, dst: buffer, dOff: number, count: number) +function Codecs.copy(src: buffer, sOff: number, dst: buffer, dOff: number, count: number) buffer.copy(dst, dOff * 4, src, sOff * 4, count * 4) end -@native function Codecs.quantize(src: buffer, s: number, dst: buffer, off: number, count: number, kind: string) +function Codecs.quantize(src: buffer, s: number, dst: buffer, off: number, count: number, kind: string) local so = s * 4 if kind == "f32" then buffer.copy(dst, off, src, so, count * 4) @@ -21175,7 +21177,7 @@ end return Brep end -__FILES["cad/step/Parse"] = @native function() +__FILES["cad/step/Parse"] = function() -- cad/step/Parse: ISO 10303-21 text -> header + entity instances, one pass; never throws (nil, message, offset). @@ -21195,14 +21197,14 @@ type Ctx = { derived: any, } -@native local function fail(ctx: Ctx, msg: string, at: number): nil +local function fail(ctx: Ctx, msg: string, at: number): nil if not ctx.err then ctx.err, ctx.errAt = msg, at end return nil end -@native local function skip(ctx: Ctx, i: number): number +local function skip(ctx: Ctx, i: number): number local s, n = ctx.s, ctx.n while i <= n do local c = sbyte(s, i) @@ -21222,14 +21224,14 @@ end return i end -@native local function isAlpha(c: number): boolean +local function isAlpha(c: number): boolean return (c >= 65 and c <= 90) or (c >= 97 and c <= 122) or c == 95 end -@native local function isWord(c: number): boolean +local function isWord(c: number): boolean return (c >= 65 and c <= 90) or (c >= 97 and c <= 122) or c == 95 or (c >= 48 and c <= 57) end -@native local function keyword(ctx: Ctx, i: number): (string?, number) +local function keyword(ctx: Ctx, i: number): (string?, number) local s, n = ctx.s, ctx.n local j = i if j <= n and sbyte(s, j) == 33 then -- '!' user-defined @@ -21245,7 +21247,7 @@ end return string.upper(ssub(s, i, j - 1)), j end -@native local function utf8char(cp: number): string +local function utf8char(cp: number): string if cp < 0x80 then return schar(cp) elseif cp < 0x800 then @@ -21259,7 +21261,7 @@ end end Parse.utf8char = utf8char -@native local function hexAt(s: string, i: number, k: number): number? +local function hexAt(s: string, i: number, k: number): number? local h = ssub(s, i, i + k - 1) if #h ~= k or sfind(h, "[^%x]") then return nil @@ -21268,7 +21270,7 @@ Parse.utf8char = utf8char end -- Part 21 escapes: '' \\ \S\c \X\hh \X2\..\X0\ \X4\..\X0\; \P?\ ignored (ISO 8859-1); raw bytes >= 0x80 pass through -@native function Parse.unescape(raw: string): string +function Parse.unescape(raw: string): string if not sfind(raw, "[\\']") then return raw end @@ -21341,7 +21343,7 @@ end return table.concat(out) end -@native local function markReal(t: { [any]: any }, key: any) +local function markReal(t: { [any]: any }, key: any) local mt: any = getmetatable(t) if not mt then mt = { __reals = {} } @@ -21352,7 +21354,7 @@ end local value: (ctx: Ctx, i: number, depth: number) -> (any, number, boolean) -@native local function list(ctx: Ctx, i: number, depth: number): ({ any }?, number) +local function list(ctx: Ctx, i: number, depth: number): ({ any }?, number) local s = ctx.s local out = {} i = skip(ctx, i) @@ -21385,7 +21387,7 @@ local value: (ctx: Ctx, i: number, depth: number) -> (any, number, boolean) end Parse.list = list -value = @native function(ctx: Ctx, i: number, depth: number): (any, number, boolean) +value = function(ctx: Ctx, i: number, depth: number): (any, number, boolean) if depth > MAX_DEPTH then return fail(ctx, "lists nested too deeply", i), i, false end @@ -21472,7 +21474,7 @@ value = @native function(ctx: Ctx, i: number, depth: number): (any, number, bool end Parse.value = value -@native local function record(ctx: Ctx, i: number): (string?, { any }?, number) +local function record(ctx: Ctx, i: number): (string?, { any }?, number) local word, j = keyword(ctx, i) if not word then return fail(ctx, "expected an entity name", i), nil, i @@ -21488,7 +21490,7 @@ Parse.value = value return word, args, k end -@native local function expect(ctx: Ctx, i: number, ch: number, what: string): number? +local function expect(ctx: Ctx, i: number, ch: number, what: string): number? i = skip(ctx, i) if sbyte(ctx.s, i) ~= ch then if i > ctx.n then @@ -21499,7 +21501,7 @@ end return i + 1 end -@native local function at(s: string, i: number, word: string): boolean +local function at(s: string, i: number, word: string): boolean return ssub(s, i, i + #word - 1) == word end @@ -21514,7 +21516,7 @@ type Result = { terminated: boolean, } -@native function Parse.parse(s: string, null: any, derived: any, maxEntities: number): (Result?, string?, number?) +function Parse.parse(s: string, null: any, derived: any, maxEntities: number): (Result?, string?, number?) local ctx: Ctx = { s = s, n = #s, err = nil, errAt = nil, null = null, derived = derived } local res: Result = { header = {}, @@ -21732,7 +21734,7 @@ end return Parse end -__FILES["cad/step/Write"] = @native function() +__FILES["cad/step/Write"] = function() -- cad/step/Write: header + entity instances -> ISO 10303-21 text (escaped strings, shortest round-trip reals). @@ -21743,7 +21745,7 @@ local sformat, sbyte, ssub, sfind, floor, huge = string.format, string.byte, str local MAX_DEPTH = 100 -- Part 21 real: a '.' always, upper-case E -@native function Write.real(v: number): string? +function Write.real(v: number): string? if v ~= v or v == huge or v == -huge then return nil end @@ -21767,7 +21769,7 @@ local MAX_DEPTH = 100 end local HEX = "0123456789ABCDEF" -@native local function hex(v: number, k: number): string +local function hex(v: number, k: number): string local out = table.create(k) for i = k, 1, -1 do local d = v % 16 @@ -21777,14 +21779,14 @@ local HEX = "0123456789ABCDEF" return table.concat(out) end -@native function Write.str(s: string): string +function Write.str(s: string): string if not sfind(s, "[^ -&(-[%]^-~]") then -- printable ASCII without ' and \ return "'" .. s .. "'" end local out = { "'" } local i, n = 1, #s local wide: number? = nil -- 4 (\X2\) or 8 (\X4\) while in an extended run - @native local function close() + local function close() if wide then table.insert(out, "\\X0\\") wide = nil @@ -21848,7 +21850,7 @@ end return table.concat(out) end -@native local function isName(s: any): boolean +local function isName(s: any): boolean return type(s) == "string" and sfind(s, "^!?[%a_][%w_]*$") ~= nil end Write.isName = isName @@ -21857,12 +21859,12 @@ type Ctx = { out: { string }, null: any, derived: any, err: string? } local value: (ctx: Ctx, v: any, real: boolean, depth: number) -> boolean -@native local function reals(t: any): { [any]: boolean }? +local function reals(t: any): { [any]: boolean }? local mt = getmetatable(t) return if type(mt) == "table" and type(mt.__reals) == "table" then mt.__reals else nil end -@native local function list(ctx: Ctx, t: { any }, depth: number): boolean +local function list(ctx: Ctx, t: { any }, depth: number): boolean local out = ctx.out table.insert(out, "(") local marks = reals(t) @@ -21880,7 +21882,7 @@ end end Write.list = list -value = @native function(ctx: Ctx, v: any, real: boolean, depth: number): boolean +value = function(ctx: Ctx, v: any, real: boolean, depth: number): boolean local out = ctx.out if depth > MAX_DEPTH then ctx.err = "values nested too deeply (or a cycle)" @@ -21965,7 +21967,7 @@ value = @native function(ctx: Ctx, v: any, real: boolean, depth: number): boolea end Write.value = value -@native function Write.record(ctx: Ctx, t: any, args: any): boolean +function Write.record(ctx: Ctx, t: any, args: any): boolean if not isName(t) then ctx.err = "bad entity type " .. tostring(t) return false @@ -22299,7 +22301,7 @@ end return Aac end -__FILES["codecs/audio/Aac/Decode"] = @native function() +__FILES["codecs/audio/Aac/Decode"] = function() @@ -22322,7 +22324,7 @@ local BP = 0 local BL = 0 local OVER = false -@native local function getBits(n: number): number +local function getBits(n: number): number local p = BP BP = p + n if p > BL then @@ -22331,14 +22333,14 @@ local OVER = false end return rshift(lshift(byteswap(readu32(B, rshift(p, 3))), band(p, 7)), 32 - n) end -@native local function peekBits(n: number): number +local function peekBits(n: number): number local p = BP if p > BL then return 0 end return rshift(lshift(byteswap(readu32(B, rshift(p, 3))), band(p, 7)), 32 - n) end -@native local function getLong(n: number): number +local function getLong(n: number): number if n > 24 then local hi = getBits(n - 16) return hi * 65536 + getBits(16) @@ -22349,7 +22351,7 @@ end local PEEK = 10 type Book = { tab: { number }, map: { [number]: number }, maxLen: number } -@native local function book(codes: { number }, bits: { number }): Book +local function book(codes: { number }, bits: { number }): Book local tab = table.create(2 ^ PEEK, 0) local map = {} local maxLen = 0 @@ -22374,7 +22376,7 @@ for i = 1, 11 do SPEC_BOOK[i] = book(Tables.SPEC_CODES[i], Tables.SPEC_BITS[i]) end -@native local function huff(bk: Book): number +local function huff(bk: Book): number local e = bk.tab[peekBits(PEEK) + 1] if e > 0 then BP += band(e, 31) @@ -22440,7 +22442,7 @@ type State = { map: { number }?, } -@native local function newChannel(): Channel +local function newChannel(): Channel return { spec = table.create(1024, 0), overlap = table.create(1024, 0), @@ -22457,7 +22459,7 @@ type State = { end Decode.newChannel = newChannel -@native local function icsInfo(st: State, c: Channel): string? +local function icsInfo(st: State, c: Channel): string? if getBits(1) ~= 0 then return "reserved ics bit set" end @@ -22495,7 +22497,7 @@ Decode.newChannel = newChannel return nil end -@native local function sectionData(c: Channel): string? +local function sectionData(c: Channel): string? local long = c.windowSequence ~= EIGHT_SHORT local bits = if long then 5 else 3 local esc = 2 ^ bits - 1 @@ -22534,7 +22536,7 @@ end return nil end -@native local function scaleFactors(c: Channel, globalGain: number): string? +local function scaleFactors(c: Channel, globalGain: number): string? local sfv = globalGain local noise = globalGain - 90 local is = 0 @@ -22582,7 +22584,7 @@ end return nil end -@native local function tnsData(st: State, c: Channel): string? +local function tnsData(st: State, c: Channel): string? local short = c.windowSequence == EIGHT_SHORT local nw = if short then 8 else 1 local filters = {} @@ -22640,7 +22642,7 @@ end return nil end -@native local function applyTns(st: State, c: Channel) +local function applyTns(st: State, c: Channel) local short = c.windowSequence == EIGHT_SHORT local swb = if short then Tables.SWB_SHORT[st.sfIndex + 1] else Tables.SWB_LONG[st.sfIndex + 1] local numSwb = if short then Tables.NUM_SWB_SHORT[st.sfIndex + 1] else Tables.NUM_SWB_LONG[st.sfIndex + 1] @@ -22682,7 +22684,7 @@ end end end -@native local function spectralData(st: State, c: Channel, pulses: { number }?): string? +local function spectralData(st: State, c: Channel, pulses: { number }?): string? local short = c.windowSequence == EIGHT_SHORT local swb = if short then Tables.SWB_SHORT[st.sfIndex + 1] else Tables.SWB_LONG[st.sfIndex + 1] local spec = c.spec @@ -22844,7 +22846,7 @@ end end -- individual_channel_stream -@native local function ics(st: State, c: Channel, commonWindow: boolean): string? +local function ics(st: State, c: Channel, commonWindow: boolean): string? local globalGain = getBits(8) if not commonWindow then local e = icsInfo(st, c) @@ -22895,7 +22897,7 @@ end return spectralData(st, c, pulses) end -@native local function msStereo(st: State, l: Channel, r: Channel, mask: { number }) +local function msStereo(st: State, l: Channel, r: Channel, mask: { number }) local short = l.windowSequence == EIGHT_SHORT local swb = if short then Tables.SWB_SHORT[st.sfIndex + 1] else Tables.SWB_LONG[st.sfIndex + 1] local maxSfb = l.maxSfb @@ -22919,7 +22921,7 @@ end end end -@native local function intensity(st: State, l: Channel, r: Channel, mask: { number }, msPresent: number) +local function intensity(st: State, l: Channel, r: Channel, mask: { number }, msPresent: number) local short = r.windowSequence == EIGHT_SHORT local swb = if short then Tables.SWB_SHORT[st.sfIndex + 1] else Tables.SWB_LONG[st.sfIndex + 1] local maxSfb = r.maxSfb @@ -22948,7 +22950,7 @@ end end end -@native local function filterbank(st: State, c: Channel, out: { number }, stride: number, offset: number) +local function filterbank(st: State, c: Channel, out: { number }, stride: number, offset: number) local seq, shape, prev = c.windowSequence, c.windowShape, c.prevShape local spec, overlap = c.spec, c.overlap local frame = st.frame @@ -23016,7 +23018,7 @@ end c.prevShape = shape end -@native function Decode.frame(st: State, buf: buffer, off: number, len: number): (number?, string?) +function Decode.frame(st: State, buf: buffer, off: number, len: number): (number?, string?) if buffer.len(B) < len + 16 then B = buffer.create(len + 256) end @@ -23160,7 +23162,7 @@ end return n, nil end -@native function Decode.state(sfIndex: number): State +function Decode.state(sfIndex: number): State return { sfIndex = sfIndex, channels = 0, @@ -23676,7 +23678,7 @@ end return Ac3 end -__FILES["codecs/audio/Ac3/Decode"] = @native function() +__FILES["codecs/audio/Ac3/Decode"] = function() @@ -23703,7 +23705,7 @@ for e = 0, 31 do POW2[e + 1] = 2 ^ -e end -- symmetric quantiser values (Tables 7.19 - 7.23): Q1[code + 1] etc. -@native local function levels(n: number): { number } +local function levels(n: number): { number } local t = {} for c = 0, n - 1 do t[c + 1] = (2 * c - (n - 1)) / n @@ -23721,7 +23723,7 @@ local PLAN256 = Mdct.new(256) :: Mdct.Plan local B: buffer = buffer.create(0) local P = 0 -@native local function bits(n: number): number +local function bits(n: number): number if n <= 0 then return 0 end @@ -23785,7 +23787,7 @@ type State = { blocks: { number }, } -@native local function arrays(n: number, size: number, v: any): { any } +local function arrays(n: number, size: number, v: any): { any } local t = {} for i = 1, n do t[i] = table.create(size, v) @@ -23793,7 +23795,7 @@ type State = { return t end -@native function Decode.state(): State +function Decode.state(): State return { fscod = 0, acmod = 2, @@ -23845,7 +23847,7 @@ end } end -@native function Decode.reset(st: State) +function Decode.reset(st: State) for _, d in st.delay do for i = 1, 256 do d[i] = 0 @@ -23854,7 +23856,7 @@ end end -- grouped exponents: 7 bits = 3 deltas each after absexp, grpsize bins per delta; each exponent stays in 0 .. 24 -@native local function exponents(e: { number }, absexp: number, ngrps: number, grpsize: number, first: number): boolean +local function exponents(e: { number }, absexp: number, ngrps: number, grpsize: number, first: number): boolean local prev = absexp local k = first + 1 for _ = 1, ngrps do @@ -23880,13 +23882,13 @@ end return true end -@native local function logadd(a: number, b: number): number +local function logadd(a: number, b: number): number local c = a - b local adr = min(rshift(if c >= 0 then c else -c, 1), 255) return if c >= 0 then a + LATAB[adr + 1] else b + LATAB[adr + 1] end -@native local function lowcomp(a: number, b0: number, b1: number, bin: number): number +local function lowcomp(a: number, b0: number, b1: number, bin: number): number if bin < 7 then if b0 + 256 == b1 then a = 384 @@ -23906,7 +23908,7 @@ end end -- section 7.2.2: the bap of bins [start, stop) of channel slot ch -@native local function allocate(st: State, ch: number, start: number, stop: number, fgain: number, snroffset: number, isLfe: boolean) +local function allocate(st: State, ch: number, start: number, stop: number, fgain: number, snroffset: number, isLfe: boolean) local e, bap = st.exp[ch], st.bap[ch] local psd, bndpsd, excite, mask = st.psd, st.bndpsd, st.excite, st.mask local sdecay, fdecay = SLOWDEC[st.sdcycod + 1], FASTDEC[st.fdcycod + 1] @@ -24025,13 +24027,13 @@ end local G1, G2, G4 = table.create(3, 0), table.create(3, 0), table.create(2, 0) local n1, n2, n4 = 0, 0, 0 -@native local function dither(st: State): number +local function dither(st: State): number local s = (st.seed * 1664525 + 1013904223) % 4294967296 st.seed = s return (s / 2147483648 - 1) * 0.707 end -@native local function mantissas(st: State, ch: number, start: number, stop: number, out: { number }, dith: boolean) +local function mantissas(st: State, ch: number, start: number, stop: number, out: { number }, dith: boolean) local e, bap = st.exp[ch], st.bap[ch] for bin = start, stop - 1 do local b = bap[bin + 1] @@ -24088,7 +24090,7 @@ end end end -@native local function readDba(st: State, ch: number) +local function readDba(st: State, ch: number) local nseg = bits(3) + 1 local offs, lens, bas = st.dbaOffst[ch], st.dbaLen[ch], st.dbaBa[ch] table.clear(offs) @@ -24103,7 +24105,7 @@ end local EXPGRP = { 3, 6, 12 } -- bins per group of 3 deltas, by strategy (D15 / D25 / D45) -@native local function audblk(st: State, blk: number, limit: number): (boolean?, string?) +local function audblk(st: State, blk: number, limit: number): (boolean?, string?) local nf, acmod = st.nfchans, st.acmod for ch = 1, nf do st.blksw[ch] = bits(1) == 1 @@ -24336,7 +24338,7 @@ local EXPGRP = { 3, 6, 12 } -- bins per group of 3 deltas, by strategy (D15 / D2 zero = false end end - @native local function alloc(ch: number, start: number, stop: number, isLfe: boolean) + local function alloc(ch: number, start: number, stop: number, isLfe: boolean) if zero then for i = start + 1, stop do st.bap[ch][i] = 0 @@ -24426,7 +24428,7 @@ local EXPGRP = { 3, 6, 12 } -- bins per group of 3 deltas, by strategy (D15 / D2 return true, nil end -@native local function synth(st: State, ch: number, short: boolean, gain: number, out: { number }, base: number, step: number) +local function synth(st: State, ch: number, short: boolean, gain: number, out: { number }, base: number, step: number) local x, y, d, w = st.coef[ch], st.y, st.delay[ch], WINDOW if short then -- two 256-point transforms of the interleaved coefficients, phases alpha = -1 (n0 = 0) and +1 (n0 = N / 2) @@ -24469,7 +24471,7 @@ local ORDER: { [number]: { number } } = { } local HAS_C = { [0] = false, true, false, true, false, true, false, true } -@native function Decode.frame(st: State, buf: buffer, len: number, drc: number): (number?, string?) +function Decode.frame(st: State, buf: buffer, len: number, drc: number): (number?, string?) if len < 8 or buffer.len(buf) < len + Decode.PAD then return nil, "truncated frame" end @@ -24662,7 +24664,7 @@ end return T end -__FILES["codecs/audio/Adpcm"] = @native function() +__FILES["codecs/audio/Adpcm"] = function() @@ -24710,7 +24712,7 @@ end Adpcm.IMA_STEP = IMA_STEP -- IMA nibble q is in byte p + q // 2, the low half first unless hi -@native function Adpcm.ima(src: buffer, p: number, q0: number, qs: number, count: number, hi: boolean, st: buffer, so: number, +function Adpcm.ima(src: buffer, p: number, q0: number, qs: number, count: number, hi: boolean, st: buffer, so: number, dst: buffer, d: number, ds: number) local pred = readi32(st, so) local index = math.clamp(readi32(st, so + 4), 0, 88) @@ -24748,7 +24750,7 @@ end -- Apple ima4: 34 bytes: a big-endian header (the predictor's top 9 bits, 7-bit step index), 64 nibbles low first; -- Apple's decoders keep the full-precision predictor while the header agrees (same step index, within 127) -@native function Adpcm.imaQt(src: buffer, p: number, st: buffer, so: number, dst: buffer, d: number, ds: number) +function Adpcm.imaQt(src: buffer, p: number, st: buffer, so: number, dst: buffer, d: number, ds: number) local h = readu8(src, p) * 256 + readu8(src, p + 1) local pred = band(h, 0xFF80) if pred >= 32768 then @@ -24764,7 +24766,7 @@ end -- Microsoft IMA block: per channel s16 predictor (= the first sample), u8 step index, pad; then 4-byte groups -- (8 nibbles, low first) per channel in turn -@native function Adpcm.imaWav(src: buffer, off: number, avail: number, ch: number, spb: number, dst: buffer, d: number): number +function Adpcm.imaWav(src: buffer, off: number, avail: number, ch: number, spb: number, dst: buffer, d: number): number if avail < 4 * ch then return 0 end @@ -24812,7 +24814,7 @@ Adpcm.MS_COEF2 = { 0, -256, 0, 64, 0, -208, -232 } -- MS ADPCM block: per channel u8 predictor index, s16 delta, s16 sample 1, s16 sample 2 (each field for every channel -- in turn), then nibbles high first, channels interleaved per nibble; coefficients 256 = 1.0 -@native function Adpcm.msBlock(src: buffer, off: number, avail: number, ch: number, spb: number, dst: buffer, d: number, +function Adpcm.msBlock(src: buffer, off: number, avail: number, ch: number, spb: number, dst: buffer, d: number, coefs: buffer, ncoef: number, state: buffer): number local hdr = 7 * ch if avail < hdr or ncoef < 1 then @@ -24867,14 +24869,14 @@ Adpcm.MS_COEF2 = { 0, -256, 0, 64, 0, -208, -232 } end local F32 = buffer.create(4) -@native local function f32(x: number): number +local function f32(x: number): number writef32(F32, 0, x) return readf32(F32, 0) end -- coef1, coef2 (12 fractional bits): the 2-pole high-pass predictor from the header's cutoff, in single precision as -- CRI's decoders (and vgmstream) compute it -@native function Adpcm.adxCoefs(cutoff: number, rate: number): (number, number) +function Adpcm.adxCoefs(cutoff: number, rate: number): (number, number) if rate <= 0 then return 0, 0 end @@ -24891,7 +24893,7 @@ end -- ADX frame: s16 big-endian scale, 32 nibbles high first. v3 shifts each product on its own; scale 0x8001 (CRI's end -- marker) decodes as silence -@native function Adpcm.adx(src: buffer, p: number, pstride: number, nframes: number, c1: number, c2: number, v3: boolean, +function Adpcm.adx(src: buffer, p: number, pstride: number, nframes: number, c1: number, c2: number, v3: boolean, st: buffer, so: number, dst: buffer, d: number, ds: number) local h1, h2 = readi32(st, so), readi32(st, so + 4) local o = d * 4 @@ -24938,7 +24940,7 @@ local PSX2 = { 0, 0, -52, -55, -60 } -- the filter term (c1 * h1 + c2 * h2) / 64 * 256 truncated, as vgmstream's single-precision float code computes it: -- exact in integers while the products fit a float's 24 bits -@native local function psxPred(f: number, h1: number, h2: number): number +local function psxPred(f: number, h1: number, h2: number): number local x = PSX1[f] * h1 + PSX2[f] * h2 if h1 > -65536 and h1 < 65536 and h2 > -65536 and h2 < 65536 then return 4 * x @@ -24949,7 +24951,7 @@ end -- PS-ADPCM frame: filter << 4 | shift, flags, 28 nibbles low first. Filters past 4 decode as 0 and shifts past 12 as 9 -- (as vgmstream); flags 7 is silence; the history keeps the unclipped value -@native function Adpcm.psx(src: buffer, p: number, pstride: number, nframes: number, st: buffer, so: number, dst: buffer, +function Adpcm.psx(src: buffer, p: number, pstride: number, nframes: number, st: buffer, so: number, dst: buffer, d: number, ds: number) local h1, h2 = readi32(st, so), readi32(st, so + 4) local o = d * 4 @@ -24995,7 +24997,7 @@ end -- DSP frame: predictor << 4 | scale shift, 14 nibbles high first; coefs 8 pairs, 11 fractional bits; a predictor -- index past 7 uses pair 7 -@native function Adpcm.dsp(src: buffer, p: number, count: number, coefs: buffer, co: number, st: buffer, so: number, +function Adpcm.dsp(src: buffer, p: number, count: number, coefs: buffer, co: number, st: buffer, so: number, dst: buffer, d: number, ds: number) local h1, h2 = readi32(st, so), readi32(st, so + 4) local o = d * 4 @@ -25032,7 +25034,7 @@ end writei32(st, so + 4, h2) end -@native local function toS16(x: number): number +local function toS16(x: number): number local v = floor(x * 32768 + 0.5) if v ~= v then return 0 @@ -25045,7 +25047,7 @@ end end Adpcm.toS16 = toS16 -@native local function imaNibble(x: number, pred: number, index: number): number +local function imaNibble(x: number, pred: number, index: number): number local base = index * 8 + 1 local best, bestErr = 0, math.huge for m = 0, 7 do @@ -25064,7 +25066,7 @@ Adpcm.toS16 = toS16 return best end -@native function Adpcm.imaEncode(x: buffer, xi: number, xs: number, count: number, st: buffer, so: number, out: buffer, +function Adpcm.imaEncode(x: buffer, xi: number, xs: number, count: number, st: buffer, so: number, out: buffer, p: number, q0: number, qs: number, hi: boolean) local pred = readi32(st, so) local index = math.clamp(readi32(st, so + 4), 0, 88) @@ -25090,7 +25092,7 @@ end end -- Microsoft IMA block: spb = 1 + 8k frames, 4 * ch + (spb - 1) / 2 * ch bytes -@native function Adpcm.imaWavEncode(x: buffer, xf: number, n: number, ch: number, spb: number, st: buffer, out: buffer, off: number) +function Adpcm.imaWavEncode(x: buffer, xf: number, n: number, ch: number, spb: number, st: buffer, out: buffer, off: number) local groups = (spb - 1) // 8 for c = 0, ch - 1 do local so = c * 8 @@ -25123,7 +25125,7 @@ end end end -@native local function msTrial(xs: { number }, n: number, c1: number, c2: number, delta0: number, nibs: { number }?): number +local function msTrial(xs: { number }, n: number, c1: number, c2: number, delta0: number, nibs: { number }?): number local s1, s2 = xs[2], xs[1] local idelta = delta0 local err = 0 @@ -25146,7 +25148,7 @@ end end -- MS ADPCM block (standard 7 coefficient pairs): 7 * ch + (spb - 2) * ch / 2 bytes -@native function Adpcm.msEncode(x: buffer, xf: number, n: number, ch: number, spb: number, out: buffer, off: number) +function Adpcm.msEncode(x: buffer, xf: number, n: number, ch: number, spb: number, out: buffer, off: number) local C1, C2 = Adpcm.MS_COEF1, Adpcm.MS_COEF2 local xs = table.create(spb, 0) local nibs = table.create(spb, 0) @@ -25182,7 +25184,7 @@ end end end -@native local function adxTrial(xs: { number }, scale: number, c1: number, c2: number, h1: number, h2: number, nibs: { number }?): (number, number, number) +local function adxTrial(xs: { number }, scale: number, c1: number, c2: number, h1: number, h2: number, nibs: { number }?): (number, number, number) local err = 0 for k = 1, 32 do local pred = (c1 * h1 + c2 * h2) // 4096 @@ -25202,7 +25204,7 @@ end -- ADX v4 rounding; the scale is stored minus one as CRI's decoders add it back -- (v4 rounding, the scale stored minus one as CRI's decoders add it back) at out[p], pstride bytes apart; the frame -@native function Adpcm.adxEncode(x: buffer, xi: number, xs: number, count: number, c1: number, c2: number, st: buffer, so: number, +function Adpcm.adxEncode(x: buffer, xi: number, xs: number, count: number, c1: number, c2: number, st: buffer, so: number, out: buffer, p: number, pstride: number) local h1, h2 = readi32(st, so), readi32(st, so + 4) local v = table.create(32, 0) @@ -25240,7 +25242,7 @@ end writei32(st, so + 4, h2) end -@native function Adpcm.psxEncode(x: buffer, xi: number, xs: number, count: number, st: buffer, so: number, out: buffer, +function Adpcm.psxEncode(x: buffer, xi: number, xs: number, count: number, st: buffer, so: number, out: buffer, p: number, pstride: number) local h1, h2 = readi32(st, so), readi32(st, so + 4) local v = table.create(28, 0) @@ -25296,7 +25298,7 @@ end -- ModPlug / OpenMPT ADPCM (sample data marked 0xAD): 16 signed byte deltas, then nibbles low first, each adding its -- delta to a wrapping signed byte; value / 128 -@native function Adpcm.modplug(src: buffer, p: number, count: number, dst: buffer, d: number) +function Adpcm.modplug(src: buffer, p: number, count: number, dst: buffer, d: number) local tab = table.create(16, 0) for k = 0, 15 do tab[k + 1] = buffer.readi8(src, p + k) @@ -25322,7 +25324,7 @@ local SWF_INDEX: { { number } } = { { -1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 4, 6, 8, 10, 13, 16 }, } -@native function Adpcm.swfFrames(src: buffer, p: number, n: number, ch: number): number +function Adpcm.swfFrames(src: buffer, p: number, n: number, ch: number): number if n < 1 or ch < 1 then return 0 end @@ -25339,7 +25341,7 @@ local SWF_INDEX: { { number } } = { return frames end -@native local function msb(src: buffer, p: number, e: number, pos: number, k: number): number +local function msb(src: buffer, p: number, e: number, pos: number, k: number): number local q = p + rshift(pos, 3) local v = readu8(src, q) * 65536 if q + 1 < e then @@ -25351,7 +25353,7 @@ end return band(rshift(v, 24 - band(pos, 7) - k), lshift(1, k) - 1) end -@native function Adpcm.swf(src: buffer, p: number, n: number, ch: number, dst: buffer, d: number): number +function Adpcm.swf(src: buffer, p: number, n: number, ch: number, dst: buffer, d: number): number local frames = Adpcm.swfFrames(src, p, n, ch) if frames == 0 then return 0 @@ -25952,7 +25954,7 @@ end return Alac end -__FILES["codecs/audio/Alac/Decode"] = @native function() +__FILES["codecs/audio/Alac/Decode"] = function() @@ -25984,12 +25986,12 @@ for i = 0, 63 do POW[i + 1] = 2 ^ i end -@native local function bitsAt(b: buffer, pos: number, n: number): number +local function bitsAt(b: buffer, pos: number, n: number): number local w = byteswap(readu32(b, rshift(pos, 3))) return rshift(lshift(w, band(pos, 7)), 32 - n) end -@native local function signExtend(v: number, bits: number): number +local function signExtend(v: number, bits: number): number local m = POW[bits + 1] v = v % m if v >= m / 2 then @@ -25999,7 +26001,7 @@ end end -- the adaptive Golomb-Rice value: unary prefix (escape after 9 ones: `bps` raw bits), then k bits -@native local function scalar(b: buffer, pos: number, k: number, m: number, bps: number): (number, number) +local function scalar(b: buffer, pos: number, k: number, m: number, bps: number): (number, number) local w = lshift(byteswap(readu32(b, rshift(pos, 3))), band(pos, 7)) local pre = countlz(bnot(w)) if pre >= 9 then @@ -26024,7 +26026,7 @@ end return x, pos + k - 1 end -@native local function rice(b: buffer, pos: number, limit: number, out: { number }, n: number, bps: number, mult: number, st: State): number +local function rice(b: buffer, pos: number, limit: number, out: { number }, n: number, bps: number, mult: number, st: State): number local history = st.mb local kb = st.kb local signMod = 0 @@ -26077,7 +26079,7 @@ end return pos end -@native local function predict(err: { number }, out: { number }, n: number, bps: number, coefs: { number }, order: number, quant: number) +local function predict(err: { number }, out: { number }, n: number, bps: number, coefs: { number }, order: number, quant: number) out[1] = err[1] if n <= 1 then return @@ -26130,7 +26132,7 @@ end end end -@native function Decode.frame(st: State, buf: buffer, off: number, len: number): (number?, string?) +function Decode.frame(st: State, buf: buffer, off: number, len: number): (number?, string?) if len <= 0 then return nil, "empty packet" end @@ -26350,7 +26352,7 @@ end return frames, nil end -@native function Decode.state(cfg: any): State +function Decode.state(cfg: any): State local n = cfg.frameLength return { frameLength = n, @@ -26371,7 +26373,7 @@ end local _ = readu8 return Decode end -__FILES["codecs/audio/Alac/Encode"] = @native function() +__FILES["codecs/audio/Alac/Encode"] = function() @@ -26407,7 +26409,7 @@ type State = { work: { number }, } -@native local function put(st: State, v: number, n: number) +local function put(st: State, v: number, n: number) local pos = st.pos if pos + n > st.cap then st.pos = st.cap + 1 -- overflow: the caller falls back to an uncompressed frame @@ -26426,7 +26428,7 @@ type State = { st.pos = pos end -@native local function putBig(st: State, v: number, n: number) +local function putBig(st: State, v: number, n: number) if n > 24 then local lo = v % 65536 put(st, (v - lo) / 65536, n - 16) @@ -26436,7 +26438,7 @@ end end end -@native local function signExtend(v: number, bits: number): number +local function signExtend(v: number, bits: number): number local m = POW[bits + 1] v = v % m if v >= m / 2 then @@ -26445,7 +26447,7 @@ end return v end -@native local function scalarBits(x: number, k: number, m: number, bps: number): number +local function scalarBits(x: number, k: number, m: number, bps: number): number local pre = if k == 1 then x else floor(x / m) if pre >= 9 then return 9 + bps @@ -26457,7 +26459,7 @@ end return pre + 1 + (if r == 0 then k - 1 else k) end -@native local function scalar(st: State, x: number, k: number, m: number, bps: number) +local function scalar(st: State, x: number, k: number, m: number, bps: number) local pre = if k == 1 then x else floor(x / m) if pre >= 9 then put(st, 511, 9) @@ -26475,7 +26477,7 @@ end end end -@native local function rice(st: State, e: { number }, n: number, bps: number, mult: number, write: boolean): number +local function rice(st: State, e: { number }, n: number, bps: number, mult: number, write: boolean): number local history = st.mb local kb = st.kb local signMod = 0 @@ -26529,7 +26531,7 @@ end end -- residuals of x[1..n] under the decoder's adaptive FIR starting from coefs (adapted in place, like the decoder) -@native local function residuals(x: { number }, e: { number }, n: number, bps: number, coefs: { number }, order: number, quant: number) +local function residuals(x: { number }, e: { number }, n: number, bps: number, coefs: { number }, order: number, quant: number) e[1] = x[1] if n <= 1 then return @@ -26566,7 +26568,7 @@ end end end -@native local function lpc(x: { number }, n: number, order: number, work: { number }): { number } +local function lpc(x: { number }, n: number, order: number, work: { number }): { number } local ac = table.create(order + 1, 0) for i = 1, n do local t = (2 * (i - 1) - (n - 1)) / (n + 1) @@ -26612,7 +26614,7 @@ end return coefs end -@native local function analyse(st: State, x: { number }, n: number, bps: number): (number, { number }, number) +local function analyse(st: State, x: { number }, n: number, bps: number): (number, { number }, number) local mult = floor(st.pb * PB_FACTOR / 4) local bestOrder, bestCoefs, bestBits = 0, {}, math.huge for _, order in { 4, 8 } do @@ -26637,7 +26639,7 @@ end return bestOrder, bestCoefs, bestBits end -@native function Encode.frame(st: State, samples: { number }, first: number, frames: number, map: { number }, elements: { number }): buffer +function Encode.frame(st: State, samples: { number }, first: number, frames: number, map: { number }, elements: { number }): buffer local channels, depth = st.channels, st.bitDepth local n = frames local partial = n ~= st.frameLength @@ -26762,7 +26764,7 @@ end return pkt end -@native function Encode.state(cfg: any): State +function Encode.state(cfg: any): State local n = cfg.frameLength return { frameLength = n, @@ -26998,7 +27000,7 @@ end return Ape end -__FILES["codecs/audio/Ape/Decode"] = @native function() +__FILES["codecs/audio/Ape/Decode"] = function() @@ -27025,7 +27027,7 @@ local KMIN = { 0, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 6 -- symbol(total) lookup buffers (RangeOverflowTable), built on first use local OVT: { [number]: buffer } = {} -@native local function overflowTable(rt: { number }): buffer +local function overflowTable(rt: { number }): buffer local t = OVT[rt[2]] if t then return t @@ -27042,7 +27044,7 @@ local OVT: { [number]: buffer } = {} return t end -@native local function wrap32(v: number): number +local function wrap32(v: number): number if v >= TWO31 or v < -TWO31 then return (v + TWO31) % TWO32 - TWO31 end @@ -27050,7 +27052,7 @@ end end -- C integer division by 2 (toward zero) -@native local function half(v: number): number +local function half(v: number): number return if v >= 0 then v // 2 else -((-v) // 2) end @@ -27076,7 +27078,7 @@ local FILTERS: { [number]: { number } } = { -- level -> { order, shift, ... } in [5000] = { 1280, 15, 256, 13, 16, 11 }, } -@native function Decode.state(version: number, level: number, bits: number, channels: number): (State?, string?) +function Decode.state(version: number, level: number, bits: number, channels: number): (State?, string?) local spec = FILTERS[level] if not spec then return nil, "unsupported: compression level " .. level @@ -27113,7 +27115,7 @@ end -- the range coder as a record (the 3.95 - 3.98 model's RangeDecodeFastWithUpdate) type Rc = { q: number, low: number, range: number, prev: number } -@native local function rcBits(rc: Rc, S: buffer, nb: number): number +local function rcBits(rc: Rc, S: buffer, nb: number): number local q, low, range, prev = rc.q, rc.low, rc.range, rc.prev while range <= 8388608 do local byte = readu8(S, q) @@ -27132,7 +27134,7 @@ type Rc = { q: number, low: number, range: number, prev: number } return r end -@native local function values(st: State, q: number, lim: number, n: number, order: { number }, old: boolean): (number?, string?) +local function values(st: State, q: number, lim: number, n: number, order: { number }, old: boolean): (number?, string?) local S = st.S local V = st.V local version = st.version @@ -27293,11 +27295,11 @@ end end -- ((v >> s) & m) ~= 0 for an int64 v (s given as 2^s) -@native local function negBit(v: number, p2: number, m: number): boolean +local function negBit(v: number, p2: number, m: number): boolean return band((v // p2) % TWO32, m) ~= 0 end -@native local function dot16(M: buffer, I: buffer, b: number, span: number): number +local function dot16(M: buffer, I: buffer, b: number, span: number): number local dot = 0 for k = 0, span - 16, 16 do local bb = b + k @@ -27310,7 +27312,7 @@ end end -- the same, adapting each weight after its use: M += D * dm (int16, wrapping) -@native local function dotAdapt16(M: buffer, I: buffer, D: buffer, b: number, span: number, dm: number): number +local function dotAdapt16(M: buffer, I: buffer, D: buffer, b: number, span: number, dm: number): number local dot = 0 for k = 0, span - 8, 8 do local bb = b + k @@ -27325,7 +27327,7 @@ end end -- one CNNFilter (DecompressGeneric); weights in the C types (int16 up to 24-bit files, int32 for 32-bit) wrap as C does -@native local function nnFilter(f: Filter, v: { number }, n: number, newDelta: boolean, wide: boolean) +local function nnFilter(f: Filter, v: { number }, n: number, newDelta: boolean, wide: boolean) local order, M, I, D = f.order, f.M, f.I, f.D local es = if wide then 4 else 2 local shift = 2 ^ f.shift @@ -27413,7 +27415,7 @@ end end -- the adapt sign of a 32-bit file's int64 prediction value: ((v >> 30) & 2) - 1, or 0 -@native local function adaptWide(v: number): number +local function adaptWide(v: number): number if v == 0 then return 0 end @@ -27421,7 +27423,7 @@ end end -- CPredictorDecompress3950toCurrent, single-channel form -@native local function predictOne(st: State, v: { number }, n: number) +local function predictOne(st: State, v: { number }, n: number) local wide = st.bits >= 32 local lastA, prevA0, A1, A2, A3 = 0, 0, 0, 0, 0 local MA0, MA1, MA2, MA3 = 360, 317, -109, 98 @@ -27462,7 +27464,7 @@ end end -- the stereo predictors: Y = P1(nY, last X), X = P0(nX, Y); X into V[1], Y into V[2] -@native local function predictStereo(st: State, X: { number }, Y: { number }, n: number) +local function predictStereo(st: State, X: { number }, Y: { number }, n: number) local wide = st.bits >= 32 -- predictor 1 (Y) local yLast, yPrev, yA1, yA2, yA3 = 0, 0, 0, 0, 0 @@ -27579,7 +27581,7 @@ end end end -@native function Decode.frame(st: State, buf: buffer, at: number, rem: number, stop: number, n: number, P: { number }, float: boolean, cut: boolean): (number?, string?) +function Decode.frame(st: State, buf: buffer, at: number, rem: number, stop: number, n: number, P: { number }, float: boolean, cut: boolean): (number?, string?) local C, bits = st.channels, st.bits local len = math.max(0, stop - at) local words = (len + 3) // 4 @@ -27602,7 +27604,7 @@ end end end end - @native local function u32be(q: number): number + local function u32be(q: number): number return readu8(S, q) * 16777216 + readu8(S, q + 1) * 65536 + readu8(S, q + 2) * 256 + readu8(S, q + 3) end local q = rem @@ -27867,7 +27869,7 @@ local Flac = { return Flac end -__FILES["codecs/audio/Flac/Encode"] = @native function() +__FILES["codecs/audio/Flac/Encode"] = function() @@ -27888,17 +27890,17 @@ for i = 0, 63 do POW[i + 1] = 2 ^ i end -@native local function crc8(b: buffer, o: number, n: number): number +local function crc8(b: buffer, o: number, n: number): number return Frame.crc8(b, o, o + n) end -@native local function crc16(b: buffer, o: number, n: number): number +local function crc16(b: buffer, o: number, n: number): number return Frame.crc16(b, o, o + n) end Encode.crc8, Encode.crc16 = crc8, crc16 type W = Bits.RawWriter -@native local function ensure(w: W, n: number) +local function ensure(w: W, n: number) local need = w.pos + n + 16 local cap = buffer.len(w.buf) if need > cap then @@ -27910,17 +27912,17 @@ end local put = Bits.msbPut -@native local function putSigned(w: W, v: number, n: number) +local function putSigned(w: W, v: number, n: number) put(w, if v < 0 then v + POW[n + 1] else v, n) end -@native local function alignByte(w: W) +local function alignByte(w: W) if w.cnt > 0 then put(w, 0, 8 - w.cnt) end end -@native local function putUtf8(w: W, v: number) +local function putUtf8(w: W, v: number) if v < 0x80 then put(w, v, 8) return @@ -27970,7 +27972,7 @@ type Plan = { x: { number }, } -@native local function newPlan(n: number): Plan +local function newPlan(n: number): Plan return { kind = 1, bits = 0, @@ -28003,7 +28005,7 @@ type Scratch = { qlp: { number }, } -@native local function rice(sc: Scratch, res: { number }, n: number, order: number, maxP: number): (number, number, number) +local function rice(sc: Scratch, res: { number }, n: number, order: number, maxP: number): (number, number, number) local p = maxP while p > 0 and (n % POW[p + 1] ~= 0 or n // POW[p + 1] <= order) do p -= 1 @@ -28068,7 +28070,7 @@ type Scratch = { return bestBits, bestP, bestMethod end -@native local function keepRice(sc: Scratch, plan: Plan, porder: number, method: number) +local function keepRice(sc: Scratch, plan: Plan, porder: number, method: number) plan.porder, plan.method = porder, method local params = plan.params for j = 1, POW[porder + 1] do @@ -28076,7 +28078,7 @@ end end end -@native local function fixedResidual(x: { number }, n: number, order: number, res: { number }) +local function fixedResidual(x: { number }, n: number, order: number, res: { number }) for i = 1, order do res[i] = 0 end @@ -28104,7 +28106,7 @@ end end -- the fixed order with the smallest residual magnitude (libFLAC's estimate) -@native local function bestFixedOrder(x: { number }, n: number): (number, number) +local function bestFixedOrder(x: { number }, n: number): (number, number) if n <= 4 then return 0, 0 end @@ -28141,7 +28143,7 @@ end Encode.bestFixedOrder = bestFixedOrder -- libFLAC's default QLP coefficient precision for a block size -@native local function qlpPrecision(bps: number, n: number): number +local function qlpPrecision(bps: number, n: number): number if bps > 16 then return 15 end @@ -28161,7 +28163,7 @@ Encode.bestFixedOrder = bestFixedOrder return 13 end -@native local function quantize(lp: { number }, order: number, precision: number, qlp: { number }): number? +local function quantize(lp: { number }, order: number, precision: number, qlp: { number }): number? local cmax = 0 for i = 1, order do local a = abs(lp[i]) @@ -28208,7 +28210,7 @@ end return shift end -@native local function lpcResidual(x: { number }, n: number, order: number, qlp: { number }, shift: number, res: { number }) +local function lpcResidual(x: { number }, n: number, order: number, qlp: { number }, shift: number, res: { number }) local d = POW[shift + 1] for i = 1, order do res[i] = 0 @@ -28222,7 +28224,7 @@ end end end -@native local function levinson(sc: Scratch, maxOrder: number): number +local function levinson(sc: Scratch, maxOrder: number): number local r = sc.autoc local e = r[1] if e <= 0 then @@ -28256,7 +28258,7 @@ end return maxOrder end -@native local function analyze(sc: Scratch, cfg: Config, src: { number }, n: number, bps: number, plan: Plan) +local function analyze(sc: Scratch, cfg: Config, src: { number }, n: number, bps: number, plan: Plan) local x = plan.x local first = src[1] local constant = true @@ -28384,7 +28386,7 @@ end end end -@native local function writeResidual(w: W, plan: Plan, n: number) +local function writeResidual(w: W, plan: Plan, n: number) local method = plan.method put(w, method, 2) local porder = plan.porder @@ -28419,7 +28421,7 @@ end end end -@native local function writeSubframe(w: W, plan: Plan, n: number) +local function writeSubframe(w: W, plan: Plan, n: number) local kind = plan.kind local typ = if kind == 0 then 0 elseif kind == 1 then 1 elseif kind == 2 then 8 + plan.order else 32 + plan.order - 1 put(w, 0, 1) @@ -28470,7 +28472,7 @@ local RATE_CODES: { [number]: number } = { } local SIZE_CODES: { [number]: number } = { [8] = 1, [12] = 2, [16] = 4, [20] = 5, [24] = 6, [32] = 7 } -@native local function blockCode(n: number): (number, number) -- code, extra bits (0, 8, 16) +local function blockCode(n: number): (number, number) -- code, extra bits (0, 8, 16) if n == 192 then return 1, 0 end @@ -28507,7 +28509,7 @@ type Options = { vendor: string, } -@native function Encode.encode(src: Source, opts: Options): (buffer?, string?) +function Encode.encode(src: Source, opts: Options): (buffer?, string?) local cfg = PRESETS[opts.level + 1] local ch, rate, bps = src.channels, src.sampleRate, opts.bits local bs = opts.blockSize or cfg.blockSize @@ -28550,7 +28552,7 @@ type Options = { end end -- VORBIS_COMMENT (little-endian lengths) - @native local function le32(v: number) + local function le32(v: number) put(w, v % 256, 8) put(w, (v // 256) % 256, 8) put(w, (v // 65536) % 256, 8) @@ -28628,7 +28630,7 @@ type Options = { local tmp: buffer? = nil local pendingBuf: buffer? = nil local pendingN, pendingOff = 0, 0 - @native local function readBlock(): (buffer?, number) + local function readBlock(): (buffer?, number) local out = buffer.create(bs * ch * 4) local got = 0 while got < bs do @@ -28795,7 +28797,7 @@ type Options = { end -- STREAMINFO: 34 bytes -@native function Encode.streaminfo(bs: number, minFrame: number, maxFrame: number, rate: number, ch: number, bps: number, total: number, md5: string): buffer +function Encode.streaminfo(bs: number, minFrame: number, maxFrame: number, rate: number, ch: number, bps: number, total: number, md5: string): buffer local w: W = { buf = buffer.create(64), pos = 0, acc = 0, cnt = 0 } put(w, bs, 16) put(w, bs, 16) @@ -28816,7 +28818,7 @@ end return Encode end -__FILES["codecs/audio/Flac/Frame"] = @native function() +__FILES["codecs/audio/Flac/Frame"] = function() @@ -28847,7 +28849,7 @@ for i = 0, 255 do CRC16[i + 1] = d end -@native local function crc16(b: buffer, from: number, to: number): number +local function crc16(b: buffer, from: number, to: number): number local c = 0 for i = from, to - 1 do c = bxor(band(lshift(c, 8), 0xFFFF), CRC16[bxor(rshift(c, 8), readu8(b, i)) + 1]) @@ -28856,7 +28858,7 @@ end end Frame.crc16 = crc16 -@native local function crc8(b: buffer, from: number, to: number): number +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] @@ -28888,7 +28890,7 @@ type Header = { number: number, } -@native function Frame.header(b: buffer, pos: number, len: number, si: any): Header? +function Frame.header(b: buffer, pos: number, len: number, si: any): Header? if pos < 0 or pos + 6 > len then return nil end @@ -28984,7 +28986,7 @@ type Header = { } end -@native function Frame.find(b: buffer, pos: number, limit: number, len: number, si: any): Header? +function Frame.find(b: buffer, pos: number, limit: number, len: number, si: any): Header? local lim = math.min(limit, len - 6) if pos < 0 then pos = 0 @@ -29004,7 +29006,7 @@ end return nil end -@native local function bits(b: buffer, p: number, n: number): number +local function bits(b: buffer, p: number, n: number): number if n == 0 then return 0 elseif n <= 24 then @@ -29015,7 +29017,7 @@ end return hi * 65536 + rshift(lshift(byteswap(readu32(b, rshift(q, 3))), band(q, 7)), 16) end -@native local function sbits(b: buffer, p: number, n: number): number +local function sbits(b: buffer, p: number, n: number): number local v = bits(b, p, n) if n > 0 and v >= POW2[n] then v -= POW2[n + 1] @@ -29023,7 +29025,7 @@ end return v end -@native local function residual(b: buffer, p: number, lim: number, s: { number }, n: number, order: number): number +local function residual(b: buffer, p: number, lim: number, s: { number }, n: number, order: number): number local method = bits(b, p, 2) if method > 1 then return -1 @@ -29147,7 +29149,7 @@ end return p end -@native local function fixed(s: { number }, n: number, order: number) +local function fixed(s: { number }, n: number, order: number) if order == 1 then local a = s[1] for i = 2, n do @@ -29185,7 +29187,7 @@ end end -- LPC restoration: s[i] += floor(sum(coef[j] * s[i - j]) / 2^shift); unrolled for orders up to 12 -@native local function lpc(s: { number }, n: number, cf: { number }, order: number, shift: number) +local function lpc(s: { number }, n: number, cf: { number }, order: number, shift: number) local div = POW2[shift + 1] local inv = 1 / div if order <= 4 then @@ -29255,7 +29257,7 @@ end end end -@native local function subframe(b: buffer, p: number, lim: number, s: { number }, n: number, bps: number, cf: { number }): number +local function subframe(b: buffer, p: number, lim: number, s: { number }, n: number, bps: number, cf: { number }): number if p > lim then return -1 end @@ -29364,7 +29366,7 @@ end return p end -@native function Frame.decode(b: buffer, len: number, h: Header, chans: { { number } }, cf: { number }, checkCrc: boolean): (number?, string?) +function Frame.decode(b: buffer, len: number, h: Header, chans: { { number } }, cf: { number }, checkCrc: boolean): (number?, string?) local n = h.blockSize local lim = len * 8 local p = (h.offset + h.size) * 8 @@ -29858,7 +29860,7 @@ end return Load end -__FILES["codecs/audio/Hively/Player"] = @native function() +__FILES["codecs/audio/Hively/Player"] = function() -- codecs/audio/Hively/Player: the AHX / HivelyTracker replayer and integer mixer, as hvl2wav's replay.c 1.9 computes them. @@ -29882,21 +29884,21 @@ local TWO32 = 4294967296 local f32scratch = buffer.create(4) -@native local function s16(v: number): number +local function s16(v: number): number return (v + 32768) % 65536 - 32768 end -@native local function tdiv(a: number, b: number): number -- C integer division (truncates) +local function tdiv(a: number, b: number): number -- C integer division (truncates) local q = a / b return if q >= 0 then math.floor(q) else -math.floor(-q) end -@native local function period(i: number): number +local function period(i: number): number return PERIOD[i] or 0 end -- (3546897.f * 65536.f) / period as a float, then / mix rate as a double, truncated -@native local function deltaOf(p: number, freq: number): number +local function deltaOf(p: number, freq: number): number if p == 0 then return 1 end @@ -29937,7 +29939,7 @@ type State = { panR: { number }, } -@native local function newVoice(i: number): Voice +local function newVoice(i: number): Voice return { track = 0, nextTrack = 0, transpose = 0, nextTranspose = 0, overrideTranspose = 1000, adsrVolume = 0, aFrames = 0, aVolume = 0, dFrames = 0, dVolume = 0, sFrames = 0, rFrames = 0, rVolume = 0, @@ -29961,7 +29963,7 @@ type State = { } end -@native function Player.new(tune: Load.Tune, freq: number, stereo: number, subsong: number): State? +function Player.new(tune: Load.Tune, freq: number, stereo: number, subsong: number): State? if subsong < 0 or subsong > #tune.subsongs then return nil end @@ -29988,12 +29990,12 @@ end return st end -@native local function setPan(st: State, v: Voice, p: number) +local function setPan(st: State, v: Voice, p: number) v.pan = p v.panMultLeft, v.panMultRight = st.panL[p], st.panR[p] end -@native local function stepfx1(st: State, v: Voice, fx: number, param: number) +local function stepfx1(st: State, v: Voice, fx: number, param: number) if fx == 0x0 then local lo = band(param, 0x0f) if lo > 0 and lo <= 9 then @@ -30037,7 +30039,7 @@ end end end -@native local function stepfx2(v: Voice, fx: number, param: number, note: number): number +local function stepfx2(v: Voice, fx: number, param: number, note: number): number if fx == 0x9 then v.squarePos = rshift(param, 5 - v.waveLength) v.ignoreSquare = 1 @@ -30060,7 +30062,7 @@ end return note end -@native local function stepfx3(st: State, v: Voice, fx: number, param: number) +local function stepfx3(st: State, v: Voice, fx: number, param: number) if fx == 0x01 then v.periodSlideSpeed = -param v.periodSlideOn = true @@ -30125,7 +30127,7 @@ end end end -@native local function processStep(st: State, v: Voice) +local function processStep(st: State, v: Voice) v.volumeSlideUp, v.volumeSlideDown = 0, 0 local tune = st.tune local track = readu8(tune.positions, (st.posNr * 16 + v.voiceNum) * 2) @@ -30227,7 +30229,7 @@ end stepfx3(st, v, fxb, fxbp) end -@native local function plistCommand(st: State, v: Voice, fx: number, param: number) +local function plistCommand(st: State, v: Voice, fx: number, param: number) if fx == 0 then if param > 0 and param < 0x40 then if v.ignoreFilter ~= 0 then @@ -30320,7 +30322,7 @@ end -- the noise offset generator (vc_WNRandom, a 64-bit `long` in hvl2wav): W += 2239384; -- W = ((((W >> 8) | (W << 24)) + 782323) ^ 75) - 6735 -@native local function wnStep(v: Voice) +local function wnStep(v: Voice) local hi, lo = v.wnHi, v.wnLo + 2239384 if lo >= TWO32 then lo -= TWO32 @@ -30346,7 +30348,7 @@ end v.wnHi, v.wnLo = nhi, nlo end -@native local function processFrame(st: State, v: Voice) +local function processFrame(st: State, v: Voice) local tune = st.tune if v.noteDelayOn then if v.noteDelayWait <= 0 then @@ -30642,7 +30644,7 @@ end v.audioVolume = s16(vol) end -@native local function fillCycles(dst: buffer, src: buffer, off: number, len: number) +local function fillCycles(dst: buffer, src: buffer, off: number, len: number) if off < 0 or off + len > buffer.len(src) then buffer.fill(dst, 0, 0, 0x281) return @@ -30657,7 +30659,7 @@ end writei8(dst, 0x280, readi8(dst, 0)) end -@native local function setAudio(st: State, v: Voice) +local function setAudio(st: State, v: Voice) v.voiceVolume = v.audioVolume % 256 if v.plantPeriod then v.plantPeriod = false @@ -30678,7 +30680,7 @@ end end -- hvl_play_irq (audio = false skips the audio side) -@native function Player.irq(st: State, audio: boolean) +function Player.irq(st: State, audio: boolean) local tune = st.tune local nch = st.channels local voices = st.voices @@ -30736,7 +30738,7 @@ end end -- hvl_mixchunk: integer mixing, s16 clipping, / 32768 -@native function Player.mix(st: State, out: buffer, at: number, n: number) +function Player.mix(st: State, out: buffer, at: number, n: number) local nch = st.channels local voices = st.voices local src, rsrc, delta, rdelta, vol, pos, rpos, panl, panr = {}, {}, {}, {}, {}, {}, {}, {}, {} @@ -30816,7 +30818,7 @@ end return Player end -__FILES["codecs/audio/Hively/Tables"] = @native function() +__FILES["codecs/audio/Hively/Tables"] = function() -- codecs/audio/Hively/Tables: the AHX / HivelyTracker replayer's waveform, panning, vibrato and period tables. @@ -30866,12 +30868,12 @@ Tables.PERIOD = { Tables.STEREO_LEFT = { [0] = 128, 96, 64, 32, 0 } Tables.STEREO_RIGHT = { [0] = 128, 160, 193, 225, 255 } -@native local function i8(v: number): number +local function i8(v: number): number v = v % 256 return if v >= 128 then v - 256 else v end -@native local function genSawtooth(w: buffer, at: number, len: number) +local function genSawtooth(w: buffer, at: number, len: number) local add = 256 // (len - 1) local val = -128 for i = 0, len - 1 do @@ -30880,7 +30882,7 @@ end end end -@native local function genTriangle(w: buffer, at: number, len: number) +local function genTriangle(w: buffer, at: number, len: number) local d5 = len // 4 local d1 = 128 // d5 local d4 = -(len // 2) @@ -30910,7 +30912,7 @@ end end end -@native local function genSquare(w: buffer, at: number) +local function genSquare(w: buffer, at: number) local p = at for i = 1, 0x20 do for _ = 1, (0x40 - i) * 2 do @@ -30925,7 +30927,7 @@ end end -- hvl_GenWhiteNoise with `unsigned long` = 64 bits: (hi, lo) halves -@native local function genWhiteNoise(w: buffer, at: number, len: number) +local function genWhiteNoise(w: buffer, at: number, len: number) local hi, lo = 0, 0x41595321 for i = 0, len - 1 do local s = i8(band(lo, 0xff)) @@ -30956,7 +30958,7 @@ for _ = 1, 32 do end table.insert(LENTAB, 0x280 * 3 - 1) -@native local function clip(x: number): number +local function clip(x: number): number if x > 127 then return 127 elseif x < -128 then @@ -30965,11 +30967,11 @@ table.insert(LENTAB, 0x280 * 3 - 1) return x end -@native local function trunc8(x: number): number +local function trunc8(x: number): number return if x >= 0 then math.floor(x) else -math.floor(-x) end -@native local function genFilterWaves(w: buffer) +local function genFilterWaves(w: buffer) local low, high = WO_LOWPASSES, WO_HIGHPASSES local freq = 8 for _ = 0, 30 do @@ -31000,7 +31002,7 @@ end local cache: { waves: buffer, panL: { number }, panR: { number } }? = nil -@native function Tables.get(): { waves: buffer, panL: { number }, panR: { number } } +function Tables.get(): { waves: buffer, panL: { number }, panR: { number } } if cache then return cache end @@ -31035,7 +31037,7 @@ end return Tables end -__FILES["codecs/audio/Mdct"] = @native function() +__FILES["codecs/audio/Mdct"] = function() @@ -31065,7 +31067,7 @@ type Plan = { c: { number }, } -@native function Mdct.new(n: number): Plan? +function Mdct.new(n: number): Plan? if type(n) ~= "number" or n < 4 or n % 4 ~= 0 or n > 2 ^ 24 then return nil end @@ -31092,7 +31094,7 @@ type Plan = { } end -@native local function dct4Post(plan: Plan, out: { number }, oi: number, os: number, scale: number) +local function dct4Post(plan: Plan, out: { number }, oi: number, os: number, scale: number) local q, m = plan.n // 4, plan.m local re, im, twc, tws = plan.re, plan.im, plan.twc, plan.tws Fft.forward(plan.fft, re, im) @@ -31105,7 +31107,7 @@ end end -- C[k] = sum_{n=0}^{M-1} u[n] cos(pi / M (n + 1/2) (k + 1/2)), M = N / 2 (its own inverse up to 2 / M) -@native function Mdct.dct4(plan: Plan, u: { number }, ui: number, us: number, out: { number }, oi: number, os: number, scale: number?) +function Mdct.dct4(plan: Plan, u: { number }, ui: number, us: number, out: { number }, oi: number, os: number, scale: number?) local q, m = plan.n // 4, plan.m local re, im, twc, tws = plan.re, plan.im, plan.twc, plan.tws for p = 0, q - 1 do @@ -31117,7 +31119,7 @@ end dct4Post(plan, out, oi, os, scale or 1) end -@native function Mdct.forward(plan: Plan, x: { number }, xi: number, out: { number }, oi: number, os: number?, scale: number?) +function Mdct.forward(plan: Plan, x: { number }, xi: number, out: { number }, oi: number, os: number?, scale: number?) local q, m = plan.n // 4, plan.m local h = m // 2 local re, im, twc, tws = plan.re, plan.im, plan.twc, plan.tws @@ -31145,7 +31147,7 @@ end dct4Post(plan, out, oi, os or 1, scale or 1) end -@native function Mdct.inverse(plan: Plan, inp: { number }, ii: number, is: number?, y: { number }, yi: number, scale: number?) +function Mdct.inverse(plan: Plan, inp: { number }, ii: number, is: number?, y: { number }, yi: number, scale: number?) local m = plan.m local h = m // 2 local c = plan.c @@ -31159,7 +31161,7 @@ end end end -@native local function besselI0(x: number): number +local function besselI0(x: number): number local sum, term = 1, 1 local k = 1 while k < 200 do @@ -31176,7 +31178,7 @@ Mdct.besselI0 = besselI0 -- "sine" sin(pi (n + 1/2) / N); "kbd" Kaiser-Bessel-derived (AAC: alpha 4 long, 6 short); "vorbis" -- sin(pi / 2 sin^2(pi (n + 1/2) / N)). All satisfy w[n]^2 + w[n + N/2]^2 = 1. -@native function Mdct.window(kind: string, n: number, alpha: number?): { number }? +function Mdct.window(kind: string, n: number, alpha: number?): { number }? if type(n) ~= "number" or n < 2 or n % 2 ~= 0 then return nil end @@ -31213,13 +31215,13 @@ Mdct.besselI0 = besselI0 return w end -@native function Mdct.fft(n: number): Fft.Plan? +function Mdct.fft(n: number): Fft.Plan? return Fft.new(n) end return Mdct end -__FILES["codecs/audio/Mdct/Fft"] = @native function() +__FILES["codecs/audio/Mdct/Fft"] = function() @@ -31242,7 +31244,7 @@ type Plan = { local cos, sin, pi = math.cos, math.sin, math.pi -@native function Fft.new(n: number): Plan? +function Fft.new(n: number): Plan? if type(n) ~= "number" or n < 1 or n % 1 ~= 0 or n > 2 ^ 24 then return nil end @@ -31302,7 +31304,7 @@ local cos, sin, pi = math.cos, math.sin, math.pi end -- one pass of radix p: cc (i, v, k) = src[1 + i + ido * (v + p * k)] -> ch (i, k, u) = dst[1 + i + ido * (k + l1 * u)] -@native local function pass(p: number, ido: number, l1: number, ar: { number }, ai: { number }, br: { number }, bi: { number }, tr: { number }, ti: { number }, cr: { number }, ci: { number }) +local function pass(p: number, ido: number, l1: number, ar: { number }, ai: { number }, br: { number }, bi: { number }, tr: { number }, ti: { number }, cr: { number }, ci: { number }) local lp = ido * l1 if p == 4 then for k = 0, l1 - 1 do @@ -31409,7 +31411,7 @@ end end -- X[k] = sum x[j] exp(-2 pi i j k / n), in place; the inverse (without 1 / n) is forward(plan, im, re) -@native function Fft.forward(plan: Plan, re: { number }, im: { number }) +function Fft.forward(plan: Plan, re: { number }, im: { number }) local n = plan.n local ar, ai, br, bi = re, im, plan.sre, plan.sim local l1 = 1 @@ -31788,7 +31790,7 @@ local Mpa = { return Mpa end -__FILES["codecs/audio/Mpa/Analysis"] = @native function() +__FILES["codecs/audio/Mpa/Analysis"] = function() @@ -31811,11 +31813,11 @@ end type State = { x: { number }, off: number, y: { number } } -@native function Analysis.new(): State +function Analysis.new(): State return { x = table.create(1024, 0), off = 0, y = table.create(64, 0) } end -@native function Analysis.run(st: State, s: { number }, si: number, out: { number }, oi: number) +function Analysis.run(st: State, s: { number }, si: number, out: { number }, oi: number) -- the window X is kept twice (x[p] and x[p + 512]) so X[i] = x[off + i + 1] without a modulo local x = st.x local off = (st.off - 32) % 512 @@ -31847,7 +31849,7 @@ end return Analysis end -__FILES["codecs/audio/Mpa/Core"] = @native function() +__FILES["codecs/audio/Mpa/Core"] = function() @@ -31868,12 +31870,12 @@ local SCALE = 1 / 32768 -- tables (floats rounded to f32 like the C arrays) local F32 = bcreate(4) -@native local function f32(x: number): number +local function f32(x: number): number wf(F32, 0, x) return rf(F32, 0) end -@native local function fbuf(list: { [number]: number }, n: number): buffer +local function fbuf(list: { [number]: number }, n: number): buffer local b = bcreate(n * 4) for i = 0, n - 1 do wf(b, i * 4, list[i]) @@ -31993,7 +31995,7 @@ local bsBuf: buffer = FRAME local bsPos = 0 local bsLimit = 0 -@native local function getBits(n: number): number +local function getBits(n: number): number local pos = bsPos bsPos = pos + n if pos + n > bsLimit then @@ -32005,7 +32007,7 @@ end -- layer III side info (L3_read_side_info): fills GR_*, returns main_data_begin or -1 -@native local function readSideInfo(h1: number, h2: number, h3: number): number +local function readSideInfo(h1: number, h2: number, h3: number): number local mono = band(h3, 0xC0) == 0xC0 local mpeg1 = band(h1, 8) ~= 0 local srIdx = band(rshift(h2, 2), 3) + (band(rshift(h1, 3), 1) + band(rshift(h1, 4), 1)) * 3 @@ -32093,7 +32095,7 @@ end return mdb end -@native local function ldexpQ2(y: number, e: number): number +local function ldexpQ2(y: number, e: number): number repeat local s = if e < 120 then e else 120 y = f32(y * EXPFRAC[band(s, 3)] * lshift(1, 30 - arshift(s, 2))) @@ -32103,7 +32105,7 @@ end end -- L3_read_scalefactors + L3_decode_scalefactors -> SCF[0 .. nLong + nShort) -@native local function decodeScalefactors(h1: number, h3: number, istOff: number, gr: number, ch: number) +local function decodeScalefactors(h1: number, h3: number, istOff: number, gr: number, ch: number) local mpeg1 = band(h1, 8) ~= 0 local nLong, nShort = GR_NLONG[gr], GR_NSHORT[gr] local part = ((if nShort ~= 0 then 1 else 0) + (if nLong == 0 then 1 else 0)) * 28 @@ -32184,7 +32186,7 @@ end -- layer III Huffman decoding (L3_huffman) into GRBUF[dst ..], reads MAIN through a 32-bit cache -@native local function huffman(dst: number, gr: number, limit: number) +local function huffman(dst: number, gr: number, limit: number) local b = bsBuf local one = 0.0 local ireg = 0 @@ -32331,7 +32333,7 @@ end end -- L3_midside_stereo on GRBUF[left .. left + n) and its right channel at + 576 -@native local function midside(left: number, n: number) +local function midside(left: number, n: number) for i = left * 4, (left + n - 1) * 4, 4 do local a, c = rf(GRBUF, i), rf(GRBUF, i + 2304) wf(GRBUF, i, a + c) @@ -32339,7 +32341,7 @@ end end end -@native local function intensityStereo(h1: number, h3: number, gr: number) +local function intensityStereo(h1: number, h3: number, gr: number) local mpeg1 = band(h1, 8) ~= 0 local ms = band(h3, 0x20) ~= 0 local nLong, nShort = GR_NLONG[gr], GR_NSHORT[gr] @@ -32408,7 +32410,7 @@ end end end -@native local function reorder(g: number, sfb: number) +local function reorder(g: number, sfb: number) local src, dst = g, 0 while true do local len = ru8(SFB, sfb) @@ -32435,7 +32437,7 @@ for i = 0, 7 do AA1[i + 1] = rf(AA, 32 + i * 4) end -@native local function antialias(g: number, nbands: number) +local function antialias(g: number, nbands: number) local o = g * 4 for _ = 1, nbands do for i = 0, 7 do @@ -32452,7 +32454,7 @@ end -- BEGIN generated by tools/gen_dsp.py -- L3_dct3_9 on 9 values -@native local function dct3_9(s0: number, s1: number, s2: number, s3: number, s4: number, s5: number, s6: number, s7: number, s8: number) +local function dct3_9(s0: number, s1: number, s2: number, s3: number, s4: number, s5: number, s6: number, s7: number, s8: number) local t0 = s0 + s6 * 0.5 s0 -= s6 local t4 = (s4 + s2) * 0.939692616 @@ -32476,7 +32478,7 @@ end end -- L3_imdct36: GRBUF[g ..], OVL[ov ..] (float indices), window W (1-based, 18 values) -@native local function imdct36(g: number, ov: number, W: { number }, nbands: number) +local function imdct36(g: number, ov: number, W: { number }, nbands: number) local w0 = W[1] local w1 = W[2] local w2 = W[3] @@ -32588,7 +32590,7 @@ end end -- mp3d_DCT_II (scalar path) over the n time slots of a channel at GRBUF[g ..]: t[4][8] in locals -@native local function dctII(g: number, n: number) +local function dctII(g: number, n: number) for k = 0, n - 1 do local y = (g + k) * 4 local t0_0, t1_0, t2_0, t3_0 @@ -32838,7 +32840,7 @@ end -- L3_imdct12: x = TMP f32 index (stride 3), dst buffer + float index, ov = OVL float index -@native local function imdct12(x: number, dst: buffer, d: number, ov: number) +local function imdct12(x: number, dst: buffer, d: number, ov: number) local xb = x * 4 local x0, x3, x6, x9, x12, x15 = rf(TMP, xb), rf(TMP, xb + 12), rf(TMP, xb + 24), rf(TMP, xb + 36), rf(TMP, xb + 48), rf(TMP, xb + 60) @@ -32866,7 +32868,7 @@ end end end -@native local function imdctShort(g: number, ov: number, nbands: number) +local function imdctShort(g: number, ov: number, nbands: number) for _ = 1, nbands do bcopy(TMP, 0, GRBUF, g * 4, 72) bcopy(GRBUF, g * 4, OVL, ov * 4, 24) @@ -32878,7 +32880,7 @@ end end end -@native local function changeSign(g: number) +local function changeSign(g: number) local o = (g + 18) * 4 for _ = 0, 15 do for i = 1, 17, 2 do @@ -32888,7 +32890,7 @@ end end end -@native local function imdctGr(g: number, ov: number, bt: number, nLongBands: number) +local function imdctGr(g: number, ov: number, bt: number, nLongBands: number) if nLongBands ~= 0 then imdct36(g, ov, MDCT_WIN0, nLongBands) g += 18 * nLongBands @@ -32902,7 +32904,7 @@ end end -- L3_decode: one granule, side info at gr = grBase + ch -@native local function l3Decode(h1: number, h2: number, h3: number, grBase: number, nch: number) +local function l3Decode(h1: number, h2: number, h3: number, grBase: number, nch: number) for ch = 0, nch - 1 do local gr = grBase + ch local limit = bsPos + GR_P23[gr] @@ -32934,7 +32936,7 @@ end -- mp3d_synth_pair: z = SYN float index, dst = PCM float index -@native local function synthPair(dst: number, nch: number, z: number) +local function synthPair(dst: number, nch: number, z: number) local zb = z * 4 local a = (rf(SYN, zb + 14 * 256) - rf(SYN, zb)) * 29 a += (rf(SYN, zb + 1 * 256) + rf(SYN, zb + 13 * 256)) * 213 @@ -32958,7 +32960,7 @@ end end -- mp3d_synth: two time slots of 32 subbands -> 64 samples per channel -@native local function synth(xl: number, dstl: number, nch: number, lins: number) +local function synth(xl: number, dstl: number, nch: number, lins: number) local xr = xl + 576 * (nch - 1) local dstr = dstl + (nch - 1) local zlin = lins + 15 * 64 @@ -33065,7 +33067,7 @@ end end end -@native local function synthGranule(nbands: number, nch: number, pcm: number) +local function synthGranule(nbands: number, nch: number, pcm: number) for ch = 0, nch - 1 do dctII(576 * ch, nbands) end @@ -33090,7 +33092,7 @@ local ALLOC_L2M1_LOW = { 44, 4, 2, 44, 3, 10 } local totalBands, stereoBands = 0, 0 -@native local function l12ReadScaleInfo(h1: number, h2: number, h3: number, kbpsHdr: number) +local function l12ReadScaleInfo(h1: number, h2: number, h3: number, kbpsHdr: number) local mode = rshift(h3, 6) local sb = if mode == 3 then 0 elseif mode == 1 then band(rshift(h3, 4), 3) * 4 + 4 else 32 local layer1 = band(h1, 6) == 6 @@ -33152,7 +33154,7 @@ local totalBands, stereoBands = 0, 0 end end -@native local function l12Dequantize(g: number, groupSize: number): number +local function l12Dequantize(g: number, groupSize: number): number local choff = 576 for j = 0, 3 do local dst = g + groupSize * j @@ -33180,7 +33182,7 @@ end return groupSize * 4 end -@native local function l12ApplyScf(scfOff: number) +local function l12ApplyScf(scfOff: number) local sb, tb = stereoBands, totalBands bcopy(GRBUF, (576 + sb * 18) * 4, GRBUF, sb * 18 * 4, (tb - sb) * 18 * 4) for i = 0, tb - 1 do @@ -33207,7 +33209,7 @@ type State = { needReset: boolean, } -@native function Core.newState(): State +function Core.newState(): State return { overlap = bcreate(2 * 9 * 32 * 4), qmf = bcreate(15 * 2 * 32 * 4), @@ -33218,7 +33220,7 @@ type State = { end -- memset(dec, 0): what minimp3 does whenever it has to re-sync -@native function Core.reset(st: State) +function Core.reset(st: State) bfill(st.overlap, 0, 0) bfill(st.qmf, 0, 0) st.reservLen = 0 @@ -33227,7 +33229,7 @@ end Core.lastChannels = 0 -@native function Core.upmix(pcm: buffer, n: number) +function Core.upmix(pcm: buffer, n: number) if buffer.len(pcm) < n * 8 then return end @@ -33238,7 +33240,7 @@ Core.lastChannels = 0 end end -@native function Core.decodeFrame(st: State, b: buffer, off: number, size: number, pcm: buffer): number +function Core.decodeFrame(st: State, b: buffer, off: number, size: number, pcm: buffer): number if size < 4 or size > MAX_FRAME or off < 0 or off + size > buffer.len(b) then st.needReset = true return 0 @@ -33325,7 +33327,7 @@ end return spf end -@native function Core.probeL3(b: buffer, off: number, size: number): (number, number, number) +function Core.probeL3(b: buffer, off: number, size: number): (number, number, number) local n = min(size, 64) if size < 4 or off + n > buffer.len(b) then return -1, 0, 0 @@ -33349,7 +33351,7 @@ end end -- Layer I / II: minimp3 drops a frame that needs more bits than it has -@native function Core.probeL12(b: buffer, off: number, size: number): boolean +function Core.probeL12(b: buffer, off: number, size: number): boolean if size < 4 or size > MAX_FRAME or off + size > buffer.len(b) then return false end @@ -33382,7 +33384,7 @@ end -- mp3dec_check_vbrtag on the frame b[off, off + size): 0 = no tag, -1 = a Xing / Info tag without a frame -- count, 1 = tag; then frames, encoder delay + 529, padding - 529 (both 0 without a LAME extension) -@native function Core.vbrTag(b: buffer, off: number, size: number): (number, number, number, number) +function Core.vbrTag(b: buffer, off: number, size: number): (number, number, number, number) if size < 12 or size > MAX_FRAME or off + size > buffer.len(b) then return 0, 0, 0, 0 end @@ -33742,7 +33744,7 @@ E.TREES = { } return E end -__FILES["codecs/audio/Mpa/Encode2"] = @native function() +__FILES["codecs/audio/Mpa/Encode2"] = function() @@ -33770,13 +33772,13 @@ local ALLOC_L2M2 = { 60, 4, 4, 44, 3, 7, 44, 2, 19 } local CODE = T.g_bitalloc_code_tab -- quantizer classes (minimp3's ba): 1..16 -> 2^ba - 1 levels in ba bits; 17 / 18 / 19 -> 3 / 5 / 9 levels grouped -@native local function levels(ba: number): number +local function levels(ba: number): number if ba >= 17 then return if ba == 17 then 3 elseif ba == 18 then 5 else 9 end return POW[ba + 1] - 1 end -@native local function tripleBits(ba: number): number +local function tripleBits(ba: number): number if ba >= 17 then return if ba == 17 then 5 elseif ba == 18 then 7 else 10 end @@ -33840,7 +33842,7 @@ type Source = { } type Options = { bitrate: number, mode: string, prefix: buffer? } -@native function Encode2.encode(src: Source, opts: Options): (buffer?, string?) +function Encode2.encode(src: Source, opts: Options): (buffer?, string?) local rate = src.sampleRate local info = RATES[rate] if not info then @@ -34090,7 +34092,7 @@ type Options = { bitrate: number, mode: string, prefix: buffer? } local sb = sbs[c] local q0, q1, q2 do - @native local function quant(x: number): number + local function quant(x: number): number local q = floor((x * inv + 1) * L / 2) return if q < 0 then 0 elseif q > L - 1 then L - 1 else q end @@ -34127,7 +34129,7 @@ end return Encode2 end -__FILES["codecs/audio/Mpa/Encode3"] = @native function() +__FILES["codecs/audio/Mpa/Encode3"] = function() @@ -34155,7 +34157,7 @@ local CODE: { [number]: { number } } = {} local LEN: { [number]: { number } } = {} local XLEN: { [number]: number } = {} -@native local function walk(tree: { number }, codes: { number }, lens: { number }, p: number, code: number, len: number) +local function walk(tree: { number }, codes: { number }, lens: { number }, p: number, code: number, len: number) local v = tree[p + 1] if bit32.band(v, 0xFF00) == 0 then local idx = bit32.band(v, 0xFF) + 1 @@ -34259,11 +34261,11 @@ type Plan = { addr2: number, } -@native local function newPlan(): Plan +local function newPlan(): Plan return { bits = 0, bigValues = 0, count1 = 0, tables = { 0, 0, 0 }, region0 = 0, region1 = 0, c1table = 0, addr1 = 0, addr2 = 0 } end -@native local function pairBits(ix: { number }, a: number, b: number, t: number): number +local function pairBits(ix: { number }, a: number, b: number, t: number): number if t == 0 then return 0 end @@ -34292,7 +34294,7 @@ end return bits end -@native local function chooseTable(ix: { number }, a: number, b: number): (number, number) +local function chooseTable(ix: { number }, a: number, b: number): (number, number) if b <= a then return 0, 0 end @@ -34332,7 +34334,7 @@ end return best, bestBits end -@native local function plan(ix: { number }, bounds: { number }, p: Plan) +local function plan(ix: { number }, bounds: { number }, p: Plan) local i = 576 while i > 1 and ix[i] == 0 and ix[i - 1] == 0 do i -= 2 @@ -34376,7 +34378,7 @@ end p.bits = bits + b1 + b2 + b3 end -@native local function writePairs(w: W, ix: { number }, sign: { boolean }, a: number, b: number, t: number) +local function writePairs(w: W, ix: { number }, sign: { boolean }, a: number, b: number, t: number) if t == 0 then return end @@ -34402,7 +34404,7 @@ end end end -@native local function writeHuffman(w: W, ix: { number }, sign: { boolean }, p: Plan) +local function writeHuffman(w: W, ix: { number }, sign: { boolean }, p: Plan) local bv = p.bigValues * 2 writePairs(w, ix, sign, 0, p.addr1, p.tables[1]) writePairs(w, ix, sign, p.addr1, p.addr2, p.tables[2]) @@ -34434,7 +34436,7 @@ type Unit = { gain: number, } -@native local function newUnit(): Unit +local function newUnit(): Unit return { xr = table.create(576, 0), xa = table.create(576, 0), @@ -34446,7 +34448,7 @@ type Unit = { end -- quantize with global gain g: false when a value overflows 8206 -@native local function quantize(u: Unit, g: number): boolean +local function quantize(u: Unit, g: number): boolean local step = 2 ^ (-(g - 210) * 3 / 16) local xa, ix = u.xa, u.ix for i = 1, 576 do @@ -34459,7 +34461,7 @@ end return true end -@native local function rateLoop(u: Unit, budget: number, bounds: { number }) +local function rateLoop(u: Unit, budget: number, bounds: { number }) local xr, xa, sign = u.xr, u.xa, u.sign local maxa = 0 for i = 1, 576 do @@ -34523,7 +34525,7 @@ type Options = { prefix: buffer?, } -@native function Encode3.encode(src: Source, opts: Options): (buffer?, string?) +function Encode3.encode(src: Source, opts: Options): (buffer?, string?) local rate = src.sampleRate local info = RATES[rate] if not info then @@ -34768,7 +34770,7 @@ end return Encode3 end -__FILES["codecs/audio/Mpa/Header"] = @native function() +__FILES["codecs/audio/Mpa/Header"] = function() @@ -34788,7 +34790,7 @@ H.MAX_FREE_FORMAT_FRAME_SIZE = 2304 H.MAX_FRAME_SYNC_MATCHES = 10 -- hdr_valid -@native function H.valid(b: buffer, o: number): boolean +function H.valid(b: buffer, o: number): boolean if ru8(b, o) ~= 0xFF then return false end @@ -34801,7 +34803,7 @@ end local valid = H.valid -- hdr_compare -@native function H.compare(b: buffer, o1: number, o2: number): boolean +function H.compare(b: buffer, o1: number, o2: number): boolean if not valid(b, o2) then return false end @@ -34814,14 +34816,14 @@ end local compare = H.compare -- from the header bytes h1 = byte 1, h2 = byte 2 -@native function H.bitrateKbps(h1: number, h2: number): number +function H.bitrateKbps(h1: number, h2: number): number local mpeg1 = if band(h1, 8) ~= 0 then 1 else 0 local layer = band(rshift(h1, 1), 3) return 2 * HALFRATE[mpeg1 * 45 + (layer - 1) * 15 + rshift(h2, 4)] end local bitrateKbps = H.bitrateKbps -@native function H.sampleRate(h1: number, h2: number): number +function H.sampleRate(h1: number, h2: number): number local hz = HZ[band(rshift(h2, 2), 3)] if band(h1, 8) == 0 then hz //= 2 @@ -34833,7 +34835,7 @@ local bitrateKbps = H.bitrateKbps end local sampleRate = H.sampleRate -@native function H.frameSamples(h1: number): number +function H.frameSamples(h1: number): number if band(h1, 6) == 6 then return 384 elseif band(h1, 14) == 2 then @@ -34844,7 +34846,7 @@ end local frameSamples = H.frameSamples -- hdr_frame_bytes (without padding) -@native function H.frameBytes(b: buffer, o: number, freeSize: number): number +function H.frameBytes(b: buffer, o: number, freeSize: number): number local h1, h2 = ru8(b, o + 1), ru8(b, o + 2) local hz = sampleRate(h1, h2) local fb = frameSamples(h1) * bitrateKbps(h1, h2) * 125 // hz @@ -34855,7 +34857,7 @@ local frameSamples = H.frameSamples end local frameBytes = H.frameBytes -@native function H.padding(b: buffer, o: number): number +function H.padding(b: buffer, o: number): number if band(ru8(b, o + 2), 2) == 0 then return 0 end @@ -34864,7 +34866,7 @@ end local padding = H.padding -- mp3d_match_frame: the frames chained after o (n bytes left) keep comparing equal -@native local function matchFrame(b: buffer, o: number, n: number, fb: number): boolean +local function matchFrame(b: buffer, o: number, n: number, fb: number): boolean local i = 0 for nmatch = 0, H.MAX_FRAME_SYNC_MATCHES - 1 do i += frameBytes(b, o + i, fb) + padding(b, o + i) @@ -34879,7 +34881,7 @@ local padding = H.padding end -- mp3d_find_frame -@native function H.findFrame(b: buffer, base: number, n: number, ffb: number): (number, number, number) +function H.findFrame(b: buffer, base: number, n: number, ffb: number): (number, number, number) for i = 0, n - 5 do local o = base + i if valid(b, o) then @@ -35480,7 +35482,7 @@ end return Musepack end -__FILES["codecs/audio/Musepack/Decode"] = @native function() +__FILES["codecs/audio/Musepack/Decode"] = function() @@ -35530,7 +35532,7 @@ local CNK, CNK_LEN, CNK_LOST, LOG2, LOG2_LOST = T.CNK, T.CNK_LEN, T.CNK_LOST, T. -- the f32 rounding of the C tables (libmpcdec decodes in single precision) local F32 = buffer.create(4) -@native local function f32(x: number): number +local function f32(x: number): number buffer.writef32(F32, 0, x) return buffer.readf32(F32, 0) end @@ -35564,7 +35566,7 @@ end local B: buffer = buffer.create(0) local P = 0 -@native local function bits(n: number): number +local function bits(n: number): number if n <= 0 then return 0 end @@ -35578,12 +35580,12 @@ local P = 0 return v end -@native local function peek16(): number +local function peek16(): number local w = bswap(readu32(B, rshift(P, 3))) return extract(w, 16 - band(P, 7), 16) end -@native local function huff(t: T.Lut): number +local function huff(t: T.Lut): number local code = peek16() local k = rshift(code, 8) + 1 local n = t.len[k] @@ -35606,7 +35608,7 @@ end end -- mpc_bits_log_dec: 0 .. max -@native local function logDec(max: number): number +local function logDec(max: number): number if max <= 0 then return 0 end @@ -35622,7 +35624,7 @@ end end -- mpc_bits_enum_dec: an n-bit word with k bits set -@native local function enumDec(k: number, n: number): number +local function enumDec(k: number, n: number): number local out = 0 local code = bits(CNK_LEN[k][n] - 1) local lost = CNK_LOST[k][n] @@ -35654,7 +35656,9 @@ end -- mpc_compute_new_V: 32 subband samples Y[y .. y + 31] -> 64 V values at V[o .. o + 63] (the ISO 11172-3 matrixing -- through Byeong Gi Lee's fast DCT) -@native local function newV(Y: { number }, y: number, V: { number }, o: number) +-- (two halves: as one function, its native lowering fails register allocation and the whole function runs +-- interpreted) +local function newVEven(Y: { number }, y: number, V: { number }, o: number) local A00 = Y[y] + Y[y + 31] local A01 = Y[y + 1] + Y[y + 30] local A02 = Y[y + 2] + Y[y + 29] @@ -35756,6 +35760,12 @@ end t = -(A12 + A14 + A15) V[o + 46] = t - A08 V[o + 42] = t - A10 - A11 +end + +local function newVOdd(Y: { number }, y: number, V: { number }, o: number) + local A00, A01, A02, A03, A04, A05, A06, A07, A08, A09, A10, A11, A12, A13, A14, A15 + local B00, B01, B02, B03, B04, B05, B06, B07, B08, B09, B10, B11, B12, B13, B14, B15 + local t A00 = (Y[y] - Y[y + 31]) * 0.5006030202 A01 = (Y[y + 1] - Y[y + 30]) * 0.5054709315 A02 = (Y[y + 2] - Y[y + 29]) * 0.5154473186 @@ -35867,6 +35877,11 @@ end V[o + 96 - i] = V[o + i] end end + +local function newV(Y: { number }, y: number, V: { number }, o: number) + newVEven(Y, y, V, o) + newVOdd(Y, y, V, o) +end type State = { version: number, maxBand: number, @@ -35892,7 +35907,7 @@ type State = { lastMaxBand: number, } -@native function Decode.state(version: number, maxBand: number, ms: boolean, channels: number): State +function Decode.state(version: number, maxBand: number, ms: boolean, channels: number): State local st: State = { version = version, maxBand = maxBand, @@ -35921,7 +35936,7 @@ type State = { end -- libmpcdec assumes scf 0 at the stream start, 0x01010101 mid-SV7; the noise generator restarts, as in a fresh stream -@native function Decode.reset(st: State, scf: number) +function Decode.reset(st: State, scf: number) for i = 1, 99 do st.scfL[i] = scf st.scfR[i] = scf @@ -35938,7 +35953,7 @@ end st.r1, st.r2 = 1, 1 end -@native local function noise(st: State, q: { number }, o: number) +local function noise(st: State, q: { number }, o: number) local r1, r2 = st.r1, st.r2 for k = 0, 35 do local t1 = PARITY[band(r1, 0xF5) + 1] @@ -35952,7 +35967,7 @@ end end -- mpc_decoder_read_bitstream_sv7 -@native local function readSv7(st: State, limit: number): (boolean?, string?) +local function readSv7(st: State, limit: number): (boolean?, string?) local resL, resR, msf = st.resL, st.resR, st.msf local maxUsed = 0 local ms = st.ms @@ -36078,7 +36093,7 @@ end return true, nil end -@native local function readSv8(st: State, key: boolean, limit: number): (boolean?, string?) +local function readSv8(st: State, key: boolean, limit: number): (boolean?, string?) local resL, resR, msf = st.resL, st.resR, st.msf local maxBand = st.maxBand local maxUsed @@ -36272,7 +36287,7 @@ end return true, nil end -@native local function requant(st: State) +local function requant(st: State) local resL, resR, msf = st.resL, st.resR, st.msf local scfL, scfR, qL, qR, yL, yR = st.scfL, st.scfR, st.qL, st.qR, st.yL, st.yR for b = 1, st.maxBand + 1 do @@ -36303,7 +36318,7 @@ end -- mpc_synthese_filter_float -@native local function synth(V: { number }, Y: { number }, out: { number }, base: number, step: number) +local function synth(V: { number }, Y: { number }, out: { number }, base: number, step: number) table.move(V, 1, 960, 2305) local o = 2304 + 1 local dw = DW @@ -36323,7 +36338,7 @@ end end end -@native function Decode.frame(st: State, buf: buffer, bitPos: number, limitBits: number, key: boolean, out: { number }, base: number): (number?, string?) +function Decode.frame(st: State, buf: buffer, bitPos: number, limitBits: number, key: boolean, out: { number }, base: number): (number?, string?) if bitPos >= 0 then if rshift(limitBits, 3) + Decode.PAD > buffer.len(buf) or bitPos > limitBits then return nil, "truncated frame" @@ -36354,7 +36369,7 @@ end return if bitPos >= 0 then pos else bitPos, nil end -@native function Decode.bitsAt(buf: buffer, bitPos: number, n: number): number +function Decode.bitsAt(buf: buffer, bitPos: number, n: number): number local w = bswap(readu32(buf, rshift(bitPos, 3))) return extract(w, 32 - band(bitPos, 7) - n, n) end @@ -36753,7 +36768,7 @@ local Opus = { return Opus end -__FILES["codecs/audio/Opus/Celt"] = @native function() +__FILES["codecs/audio/Opus/Celt"] = function() @@ -36873,42 +36888,42 @@ local BITS2 = table.create(21, 0) local THRESH = table.create(21, 0) local TRIM_OFFSET = table.create(21, 0) -@native local function imin(a: number, b: number): number +local function imin(a: number, b: number): number return if a < b then a else b end -@native local function imax(a: number, b: number): number +local function imax(a: number, b: number): number return if a > b then a else b end -- C integer division (truncates toward zero) -@native local function tdiv(a: number, b: number): number +local function tdiv(a: number, b: number): number local q = a / b return if q >= 0 then floor(q) else -floor(-q) end -@native local function exp2(x: number): number +local function exp2(x: number): number return exp(0.6931471805599453094 * x) end -@native local function lcg(seed: number): number +local function lcg(seed: number): number return (1664525 * seed + 1013904223) % 4294967296 end -@native local function signed32(x: number): number +local function signed32(x: number): number return if x >= 2147483648 then x - 4294967296 else x end -@native local function fracMul16(a: number, b: number): number +local function fracMul16(a: number, b: number): number return (16384 + a * b) // 32768 end -@native local function bitexactCos(x: number): number +local function bitexactCos(x: number): number local tmp = (4096 + x * x) // 8192 local x2 = tmp x2 = (32767 - x2) + fracMul16(x2, (-7651 + fracMul16(x2, (8277 + fracMul16(-626, x2))))) return 1 + x2 end -@native local function bitexactLog2tan(isin: number, icos: number): number +local function bitexactLog2tan(isin: number, icos: number): number local lc = RD.ilog(icos) local ls = RD.ilog(isin) icos = icos * 2 ^ (15 - lc) @@ -36918,7 +36933,7 @@ end -- energy (quant_bands.c, laplace.c) -@native local function laplaceDecode(dec: RD.Dec, fs: number, decay: number): number +local function laplaceDecode(dec: RD.Dec, fs: number, decay: number): number local val = 0 local fm = decDecodeBin(dec, 15) local fl = 0 @@ -36948,7 +36963,7 @@ end return val end -@native local function unquantCoarseEnergy(st: any, start: number, endb: number, intra: boolean, dec: RD.Dec, C: number, LM: number) +local function unquantCoarseEnergy(st: any, start: number, endb: number, intra: boolean, dec: RD.Dec, C: number, LM: number) local oldE = st.oldBandE local probBase = LM * 84 + (if intra then 42 else 0) -- e_prob_model[LM][intra], 0-based local coef, beta @@ -36991,7 +37006,7 @@ end end end -@native local function unquantFineEnergy(st: any, start: number, endb: number, fineQuant: { number }, dec: RD.Dec, C: number) +local function unquantFineEnergy(st: any, start: number, endb: number, fineQuant: { number }, dec: RD.Dec, C: number) local oldE = st.oldBandE for i = start, endb - 1 do local extra = fineQuant[i + 1] @@ -37009,7 +37024,7 @@ end end end -@native local function unquantEnergyFinalise(st: any, start: number, endb: number, fineQuant: { number }, finePriority: { number }, bitsLeft: number, dec: RD.Dec, C: number) +local function unquantEnergyFinalise(st: any, start: number, endb: number, fineQuant: { number }, finePriority: { number }, bitsLeft: number, dec: RD.Dec, C: number) local oldE = st.oldBandE for prio = 0, 1 do local i = start @@ -37031,7 +37046,7 @@ end -- bit allocation (rate.c) -@native local function bits2pulses(bandI: number, LM: number, bits: number): number +local function bits2pulses(bandI: number, LM: number, bits: number): number local base = CACHE_INDEX[(LM + 1) * NB_EBANDS + bandI + 1] local lo, hi = 0, CACHE_BITS[base + 1] bits -= 1 @@ -37050,7 +37065,7 @@ end return hi end -@native local function pulses2bits(bandI: number, LM: number, pulses: number): number +local function pulses2bits(bandI: number, LM: number, pulses: number): number if pulses == 0 then return 0 end @@ -37058,7 +37073,7 @@ end return CACHE_BITS[base + pulses + 1] + 1 end -@native local function getPulses(i: number): number +local function getPulses(i: number): number if i < 8 then return i end @@ -37066,7 +37081,7 @@ end end -- clt_compute_allocation + interp_bits2pulses (decoder side) -@native local function computeAllocation(start: number, endb: number, offsets: { number }, cap: { number }, allocTrim: number, +local function computeAllocation(start: number, endb: number, offsets: { number }, cap: { number }, allocTrim: number, total: number, pulses: { number }, ebits: { number }, finePriority: { number }, C: number, LM: number, ec: RD.Dec) total = imax(total, 0) local len = NB_EBANDS @@ -37296,7 +37311,7 @@ end -- PVQ (cwrs.c, vq.c) -@native local function cwrsi(n: number, k: number, i: number, iy: { number }): number +local function cwrsi(n: number, k: number, i: number, iy: { number }): number local yy = 0 local idx = 1 local p, k0, val @@ -37373,7 +37388,7 @@ end return yy end -@native local function expRotation1(X: number, len: number, stride: number, c: number, s: number) +local function expRotation1(X: number, len: number, stride: number, c: number, s: number) local ms = -s local p = X + 1 for _ = 0, len - stride - 1 do @@ -37394,7 +37409,7 @@ end end local SPREAD_FACTOR = { 15, 10, 5 } -@native local function expRotation(X: number, len: number, dir: number, stride: number, K: number, spread: number) +local function expRotation(X: number, len: number, dir: number, stride: number, K: number, spread: number) if 2 * K >= len or spread == 0 then return end @@ -37427,7 +37442,7 @@ local SPREAD_FACTOR = { 15, 10, 5 } end end -@native local function renormaliseVector(X: number, N: number, gain: number) +local function renormaliseVector(X: number, N: number, gain: number) local E = 1e-15 for i = X + 1, X + N do local v = W[i] @@ -37439,7 +37454,7 @@ end end end -@native local function algUnquant(X: number, N: number, K: number, spread: number, B: number, dec: RD.Dec, gain: number): number +local function algUnquant(X: number, N: number, K: number, spread: number, B: number, dec: RD.Dec, gain: number): number local iy = IY local ft = U[N * UK + K + 1] + U[N * UK + K + 2] local Ryy = cwrsi(N, K, decUint(dec, ft), iy) @@ -37489,7 +37504,7 @@ local ctx: Ctx = { avoid_split_noise = false, } -@native local function haar1(X: number, N0: number, stride: number) +local function haar1(X: number, N0: number, stride: number) N0 = rshift(N0, 1) local s = 0.70710678 for i = 0, stride - 1 do @@ -37504,7 +37519,7 @@ local ctx: Ctx = { end end -@native local function deinterleaveHadamard(X: number, N0: number, stride: number, hadamard: boolean) +local function deinterleaveHadamard(X: number, N0: number, stride: number, hadamard: boolean) local N = N0 * stride local tmp = TMP if hadamard then @@ -37527,7 +37542,7 @@ end end end -@native local function interleaveHadamard(X: number, N0: number, stride: number, hadamard: boolean) +local function interleaveHadamard(X: number, N0: number, stride: number, hadamard: boolean) local N = N0 * stride local tmp = TMP if hadamard then @@ -37550,7 +37565,7 @@ end end end -@native local function computeQn(N: number, b: number, offset: number, pulseCap: number, stereo: boolean): number +local function computeQn(N: number, b: number, offset: number, pulseCap: number, stereo: boolean): number local N2 = 2 * N - 1 if stereo and N == 2 then N2 -= 1 @@ -37565,7 +37580,7 @@ end return lshift(rshift(qn + 1, 1), 1) end -@native local function computeTheta(N: number, b: number, B: number, B0: number, LM: number, stereo: boolean, fill: number) +local function computeTheta(N: number, b: number, B: number, B0: number, LM: number, stereo: boolean, fill: number) local i = ctx.i local ec = ctx.ec local pulseCap = LOGN[i + 1] + LM * 8 @@ -37644,7 +37659,7 @@ end return b, fill, inv, imid, iside, delta, itheta, qalloc end -@native local function quantBandN1(X: number, Y: number, lowbandOut: number): number +local function quantBandN1(X: number, Y: number, lowbandOut: number): number local x = X local ec = ctx.ec for _ = 0, (if Y >= 0 then 1 else 0) do @@ -37662,7 +37677,7 @@ end return 1 end -@native local function quantPartition(X: number, N: number, b: number, B: number, lowband: number, LM: number, gain: number, fill: number): number +local function quantPartition(X: number, N: number, b: number, B: number, lowband: number, LM: number, gain: number, fill: number): number local i = ctx.i local B0 = B local cm = 0 @@ -37753,7 +37768,7 @@ end return cm end -@native local function quantBand(X: number, N: number, b: number, B: number, lowband: number, LM: number, lowbandOut: number, +local function quantBand(X: number, N: number, b: number, B: number, lowband: number, LM: number, lowbandOut: number, gain: number, lowbandScratch: number, fill: number): number local N0 = N local NB = N @@ -37824,7 +37839,7 @@ end return band(cm, lshift(1, B) - 1) end -@native local function stereoMerge(X: number, Y: number, mid: number, N: number) +local function stereoMerge(X: number, Y: number, mid: number, N: number) local xp, side = 0, 0 for j = 1, N do local y = W[Y + j] @@ -37851,7 +37866,7 @@ end end end -@native local function quantBandStereo(X: number, Y: number, N: number, b: number, B: number, lowband: number, LM: number, +local function quantBandStereo(X: number, Y: number, N: number, b: number, B: number, lowband: number, LM: number, lowbandOut: number, lowbandScratch: number, fill: number): number if N == 1 then return quantBandN1(X, Y, lowbandOut) @@ -37921,7 +37936,7 @@ end return cm end -@native local function quantAllBands(start: number, endb: number, hasY: boolean, N: number, collapse: { number }, +local function quantAllBands(start: number, endb: number, hasY: boolean, N: number, collapse: { number }, pulses: { number }, shortBlocks: boolean, spread: number, dualStereo: boolean, intensity: number, tfRes: { number }, totalBits: number, balance: number, ec: RD.Dec, LM: number, codedBands: number, seed: number, disableInv: boolean): number @@ -38032,7 +38047,7 @@ end return ctx.seed end -@native local function antiCollapse(st: any, C: number, size: number, LM: number, start: number, endb: number, +local function antiCollapse(st: any, C: number, size: number, LM: number, start: number, endb: number, collapse: { number }, pulses: { number }, seed: number) local logE, prev1logE, prev2logE = st.oldBandE, st.oldLogE, st.oldLogE2 for i = start, endb - 1 do @@ -38073,7 +38088,7 @@ end end end -@native local function denormaliseBands(X: number, freq: { number }, logE: { number }, eoff: number, start: number, endb: number, M: number, silence: boolean) +local function denormaliseBands(X: number, freq: { number }, logE: { number }, eoff: number, start: number, endb: number, M: number, silence: boolean) local N = M * SHORT_MDCT local bound = M * EB[endb + 1] if silence then @@ -38104,7 +38119,7 @@ end end end -@native local function celtSynthesis(st: any, C: number, CC: number, start: number, effEnd: number, isTransient: boolean, LM: number, silence: boolean, N: number) +local function celtSynthesis(st: any, C: number, CC: number, start: number, effEnd: number, isTransient: boolean, LM: number, silence: boolean, N: number) local M = lshift(1, LM) local B, NB, shift if isTransient then @@ -38150,7 +38165,7 @@ end end -- comb_filter, in place on mem (1-based base index of sample 0) -@native local function combFilter(mem: { number }, base: number, T0: number, T1: number, N: number, g0: number, g1: number, +local function combFilter(mem: { number }, base: number, T0: number, T1: number, N: number, g0: number, g1: number, tapset0: number, tapset1: number, overlap: number) if g0 == 0 and g1 == 0 then return @@ -38202,7 +38217,7 @@ end end end -@native local function deemphasis(st: any, CC: number, N: number, pcm: { number }, pbase: number, accum: boolean) +local function deemphasis(st: any, CC: number, N: number, pcm: { number }, pbase: number, accum: boolean) local coef0 = PREEMPH local xbase = DECODE_BUFFER_SIZE - N for c = 0, CC - 1 do @@ -38228,7 +38243,7 @@ end end end -@native local function resetState(st: any) +local function resetState(st: any) st.rng = 0 st.error = 0 st.loss_duration = 0 @@ -38258,7 +38273,7 @@ end end -- celt_decoder_init(48000, channels) -@native function Celt.new(channels: number): any +function Celt.new(channels: number): any local st = { channels = channels, stream_channels = channels, @@ -38282,7 +38297,7 @@ end Celt.reset = resetState -- noise-based concealment (celt_decode_lost, FRAME_PLC_NOISE) -@native local function decodeLost(st: any, N: number, LM: number) +local function decodeLost(st: any, N: number, LM: number) local C = st.channels local start = st.start local endb = st["end"] @@ -38336,7 +38351,7 @@ Celt.reset = resetState end -- celt_decode_with_ec (buf nil or len <= 1 conceals) -@native function Celt.decode(st: any, buf: buffer?, off: number, len: number, pcm: { number }, pbase: number, frameSize: number, +function Celt.decode(st: any, buf: buffer?, off: number, len: number, pcm: { number }, pbase: number, frameSize: number, dec: RD.Dec?, accum: boolean): number local CC = st.channels local C = st.stream_channels @@ -38600,7 +38615,7 @@ end return Celt end -__FILES["codecs/audio/Opus/CeltEncoder"] = @native function() +__FILES["codecs/audio/Opus/CeltEncoder"] = function() @@ -38685,29 +38700,29 @@ for n = 1, UK - 1 do U[n * UK + k + 1] = U[(n - 1) * UK + k + 1] + U[n * UK + k] + U[(n - 1) * UK + k] end end -@native local function pvqU(n: number, k: number): number +local function pvqU(n: number, k: number): number return U[n * UK + k + 1] end -@native local function imin(a: number, b: number): number +local function imin(a: number, b: number): number return if a < b then a else b end -@native local function imax(a: number, b: number): number +local function imax(a: number, b: number): number return if a > b then a else b end -@native local function tdiv(a: number, b: number): number +local function tdiv(a: number, b: number): number local q = a / b return if q >= 0 then floor(q) else -floor(-q) end -@native local function fracMul16(a: number, b: number): number +local function fracMul16(a: number, b: number): number return (16384 + a * b) // 32768 end -@native local function bitexactCos(x: number): number +local function bitexactCos(x: number): number local x2 = (4096 + x * x) // 8192 x2 = (32767 - x2) + fracMul16(x2, (-7651 + fracMul16(x2, (8277 + fracMul16(-626, x2))))) return 1 + x2 end -@native local function bitexactLog2tan(isin: number, icos: number): number +local function bitexactLog2tan(isin: number, icos: number): number local lc = RE.ilog(icos) local ls = RE.ilog(isin) icos = icos * 2 ^ (15 - lc) @@ -38716,7 +38731,7 @@ end end -- ec_laplace_encode: returns the value actually coded (clamped in the flat tail) -@native local function laplaceEncode(enc: RE.Enc, value: number, fs: number, decay: number): number +local function laplaceEncode(enc: RE.Enc, value: number, fs: number, decay: number): number local fl = 0 local val = value if val ~= 0 then @@ -38767,7 +38782,7 @@ type State = { dual: boolean, } -@native function CeltEncoder.new(channels: number): State +function CeltEncoder.new(channels: number): State local inMem = {} local X = {} for c = 1, channels do @@ -38793,7 +38808,7 @@ type State = { } end -@native local function quantCoarseEnergy(st: State, intra: boolean, enc: RE.Enc, C: number, budget: number, nbBytes: number) +local function quantCoarseEnergy(st: State, intra: boolean, enc: RE.Enc, C: number, budget: number, nbBytes: number) local oldE, bandLogE, err = st.oldBandE, st.bandLogE, st.error local probBase = LM * 84 + (if intra then 42 else 0) local coef, beta @@ -38853,7 +38868,7 @@ end end end -@native local function quantFineEnergy(st: State, fineQuant: { number }, enc: RE.Enc, C: number) +local function quantFineEnergy(st: State, fineQuant: { number }, enc: RE.Enc, C: number) local oldE, err = st.oldBandE, st.error for i = 0, NB_EBANDS - 1 do local extra = fineQuant[i + 1] @@ -38876,7 +38891,7 @@ end end end -@native local function quantEnergyFinalise(st: State, fineQuant: { number }, finePriority: { number }, bitsLeft: number, enc: RE.Enc, C: number) +local function quantEnergyFinalise(st: State, fineQuant: { number }, finePriority: { number }, bitsLeft: number, enc: RE.Enc, C: number) local oldE, err = st.oldBandE, st.error for prio = 0, 1 do local i = 0 @@ -38899,7 +38914,7 @@ end end end -@native local function bits2pulses(bandI: number, lm: number, bits: number): number +local function bits2pulses(bandI: number, lm: number, bits: number): number local base = CACHE_INDEX[(lm + 1) * NB_EBANDS + bandI + 1] local lo, hi = 0, CACHE_BITS[base + 1] bits -= 1 @@ -38918,7 +38933,7 @@ end return hi end -@native local function pulses2bits(bandI: number, lm: number, pulses: number): number +local function pulses2bits(bandI: number, lm: number, pulses: number): number if pulses == 0 then return 0 end @@ -38926,7 +38941,7 @@ end return CACHE_BITS[base + pulses + 1] + 1 end -@native local function getPulses(i: number): number +local function getPulses(i: number): number if i < 8 then return i end @@ -38934,7 +38949,7 @@ end end -- clt_compute_allocation (encoder side): keeps every band it can, no intensity stereo, dual stereo for C == 2 -@native local function computeAllocation(offsets: { number }, cap: { number }, allocTrim: number, total: number, +local function computeAllocation(offsets: { number }, cap: { number }, allocTrim: number, total: number, pulses: { number }, ebits: { number }, finePriority: { number }, C: number, enc: RE.Enc, wantDual: boolean) local start, endb = 0, NB_EBANDS total = imax(total, 0) @@ -39163,7 +39178,7 @@ end end -- icwrs: the index of the pulse vector iy[1..n] -@native local function icwrs(n: number, iy: { number }): number +local function icwrs(n: number, iy: { number }): number local j = n -- 1-based position of _y[n - 1] local i = if iy[j] < 0 then 1 else 0 local k = math.abs(iy[j]) @@ -39179,7 +39194,7 @@ end return i end -@native local function expRotation1(X: { number }, xo: number, len: number, stride: number, c: number, s: number) +local function expRotation1(X: { number }, xo: number, len: number, stride: number, c: number, s: number) local ms = -s local p = xo + 1 for _ = 0, len - stride - 1 do @@ -39200,7 +39215,7 @@ end end -- exp_rotation(X, len, dir = 1, stride, K, spread): the encoder's spreading rotation -@native local function expRotation(X: { number }, xo: number, len: number, stride: number, K: number, spread: number) +local function expRotation(X: { number }, xo: number, len: number, stride: number, K: number, spread: number) if 2 * K >= len or spread == 0 then return end @@ -39227,7 +39242,7 @@ end end -- op_pvq_search: the K-pulse vector closest to X[xo + 1 .. xo + n] into iy[1..n] -@native local function pvqSearch(X: { number }, xo: number, n: number, K: number, iy: { number }, y: { number }, absx: { number }) +local function pvqSearch(X: { number }, xo: number, n: number, K: number, iy: { number }, y: { number }, absx: { number }) local sign = y -- reuse: y holds 2 * |pulses| during the search, signs kept in absx's sign local xy, yy = 0, 0 local pulsesLeft = K @@ -39294,7 +39309,7 @@ local SCRATCH_Y = table.create(256, 0) local SCRATCH_A = table.create(256, 0) local ROT = table.create(256, 0) -@native local function algQuant(st: State, X: { number }, xo: number, n: number, K: number, enc: RE.Enc) +local function algQuant(st: State, X: { number }, xo: number, n: number, K: number, enc: RE.Enc) for j = 1, n do ROT[j] = X[xo + j] end @@ -39304,7 +39319,7 @@ local ROT = table.create(256, 0) encUint(enc, icwrs(n, iy), pvqU(n, K) + pvqU(n, K + 1)) end -@native local function computeQn(n: number, b: number, offset: number, pulseCap: number): number +local function computeQn(n: number, b: number, offset: number, pulseCap: number): number local N2 = 2 * n - 1 local qb = tdiv(b + N2 * offset, N2) qb = imin(b - pulseCap - 32, qb) @@ -39317,7 +39332,7 @@ end end -- quant_partition (encoder, B = 1, mono): returns nothing (no resynthesis) -@native local function quantPartition(st: State, bandI: number, X: { number }, xo: number, n: number, b: number, lm: number, enc: RE.Enc) +local function quantPartition(st: State, bandI: number, X: { number }, xo: number, n: number, b: number, lm: number, enc: RE.Enc) local split = false if lm ~= -1 and n > 2 then local base = CACHE_INDEX[(lm + 1) * NB_EBANDS + bandI + 1] @@ -39397,7 +39412,7 @@ end -- quant_band_stereo (encoder, N > 2, B = 1): the mid / side angle (step pdf), then mid and side as mono bands; -- qn == 1 falls back to intensity stereo (with the inversion bit when there is room) -@native local function quantBandStereo(st: State, i: number, n: number, xo: number, b: number, enc: RE.Enc) +local function quantBandStereo(st: State, i: number, n: number, xo: number, b: number, enc: RE.Enc) local L, R = st.X[1], st.X[2] local pulseCap = LOGN[i + 1] + LM * 8 local offset = (pulseCap // 2) - QTHETA_OFFSET @@ -39412,7 +39427,7 @@ end end local itheta = floor(0.5 + 16384 * 0.63662 * atan2(sqrt(eside), sqrt(emid))) local t0 = tellFrac(enc) - @native local function intensityStereo() + local function intensityStereo() local left, right = st.bandE[i + 1], st.bandE[NB_EBANDS + i + 1] local norm = 1e-15 + sqrt(1e-15 + left * left + right * right) local a1, a2 = left / norm, right / norm @@ -39489,7 +39504,7 @@ end end -- quant_all_bands (encoder): mono, dual stereo or mid / side stereo -@native local function quantAllBands(st: State, C: number, pulses: { number }, dualStereo: boolean, totalBits: number, +local function quantAllBands(st: State, C: number, pulses: { number }, dualStereo: boolean, totalBits: number, balance: number, enc: RE.Enc, codedBands: number, intensity: number) for i = 0, NB_EBANDS - 1 do local xo = M * EB[i + 1] @@ -39522,7 +39537,7 @@ end end end -@native function CeltEncoder.encodeFrame(st: State, pcm: { number }, base: number, stride: number, nbBytes: number): buffer +function CeltEncoder.encodeFrame(st: State, pcm: { number }, base: number, stride: number, nbBytes: number): buffer local C = st.channels local work, tmp = st.work, st.tmp local silent = true @@ -39725,7 +39740,7 @@ e_prob_model = { }, } end -__FILES["codecs/audio/Opus/Decoder"] = @native function() +__FILES["codecs/audio/Opus/Decoder"] = function() @@ -39770,7 +39785,7 @@ type State = { rangeFinal: number, } -@native function Decoder.new(channels: number): State +function Decoder.new(channels: number): State return { channels = channels, celt = Celt.new(channels), @@ -39793,7 +39808,7 @@ type State = { } end -@native function Decoder.reset(st: State) +function Decoder.reset(st: State) Celt.reset(st.celt) Silk.reset(st.silk) st.stream_channels = st.channels @@ -39807,7 +39822,7 @@ end end -- out = w^2 * in2 + (1 - w^2) * in1 over `overlap` samples per channel -@native local function smoothFade(in1: { number }, b1: number, in2: { number }, b2: number, out: { number }, bo: number, overlap: number, ch: number) +local function smoothFade(in1: { number }, b1: number, in2: { number }, b2: number, out: { number }, bo: number, overlap: number, ch: number) for c = 0, ch - 1 do for i = 0, overlap - 1 do local w = WINDOW[i + 1] @@ -39818,7 +39833,7 @@ end end end -@native local function decodeFrame(st: State, buf: buffer?, off: number, len: number, pcm: { number }, pbase: number, frameSize: number): number +local function decodeFrame(st: State, buf: buffer?, off: number, len: number, pcm: { number }, pbase: number, frameSize: number): number local ch = st.channels local celt = st.celt if frameSize < F2_5 then @@ -40016,7 +40031,7 @@ end end -- opus_decode_native (buf nil or len 0: conceal frameSize samples) -@native function Decoder.decode(st: State, buf: buffer?, off: number, len: number, pcm: { number }, pbase: number, frameSize: number, selfDelimited: boolean?): (number, number) +function Decoder.decode(st: State, buf: buffer?, off: number, len: number, pcm: { number }, pbase: number, frameSize: number, selfDelimited: boolean?): (number, number) local ch = st.channels if buf == nil or len == 0 then if frameSize % 120 ~= 0 then @@ -40073,7 +40088,7 @@ type MS = { tmp: { number }, } -@native function Decoder.newMultistream(channels: number, streams: number, coupled: number, mapping: { number }): MS +function Decoder.newMultistream(channels: number, streams: number, coupled: number, mapping: { number }): MS local decs = {} for s = 0, streams - 1 do decs[s + 1] = Decoder.new(if s < coupled then 2 else 1) @@ -40088,13 +40103,13 @@ type MS = { } end -@native function Decoder.resetMultistream(ms: MS) +function Decoder.resetMultistream(ms: MS) for _, d in ms.decoders do Decoder.reset(d) end end -@native local function copyOut(ms: MS, id: number, src: { number }, sc: number, sstride: number, pcm: { number }, pbase: number, n: number) +local function copyOut(ms: MS, id: number, src: { number }, sc: number, sstride: number, pcm: { number }, pbase: number, n: number) local nch = ms.channels for c = 0, nch - 1 do if ms.mapping[c + 1] == id then @@ -40110,7 +40125,7 @@ end end -- opus_multistream_decode_native -@native function Decoder.decodeMultistream(ms: MS, buf: buffer?, off: number, len: number, pcm: { number }, pbase: number, frameSize: number): number +function Decoder.decodeMultistream(ms: MS, buf: buffer?, off: number, len: number, pcm: { number }, pbase: number, frameSize: number): number local doPlc = buf == nil or len == 0 frameSize = min(frameSize, 5760) if not doPlc and len < 2 * ms.streams - 1 then @@ -40151,7 +40166,7 @@ end return frameSize end -@native function Decoder.writeF32(src: { number }, base: number, count: number, gain: number, out: buffer, o: number) +function Decoder.writeF32(src: { number }, base: number, count: number, gain: number, out: buffer, o: number) local writef32 = buffer.writef32 if gain == 1 then for i = base + 1, base + count do @@ -40166,7 +40181,7 @@ end end end -@native function Decoder.writeDownmix(src: { number }, base: number, n: number, srcCh: number, matrix: { number }, gain: number, out: buffer, o: number) +function Decoder.writeDownmix(src: { number }, base: number, n: number, srcCh: number, matrix: { number }, gain: number, out: buffer, o: number) local writef32 = buffer.writef32 local p = base for _ = 1, n do @@ -40185,7 +40200,7 @@ end return Decoder end -__FILES["codecs/audio/Opus/Mdct"] = @native function() +__FILES["codecs/audio/Opus/Mdct"] = function() @@ -40214,7 +40229,7 @@ local FACTORS = { [3] = { 5, 12, 3, 4, 4, 1 }, } -@native local function bitrevTable(f: { number }, fout: number, fpos: number, fstride: number, factors: { number }, fi: number) +local function bitrevTable(f: { number }, fout: number, fpos: number, fstride: number, factors: { number }, fi: number) local p = factors[fi] local m = factors[fi + 1] if m == 1 then @@ -40262,7 +40277,7 @@ for shift = 0, 3 do } end -@native local function bfly2(fr: { number }, fi: { number }, N: number) +local function bfly2(fr: { number }, fi: { number }, N: number) local tw = 0.7071067812 local p = 1 for _ = 1, N do @@ -40295,7 +40310,7 @@ end end end -@native local function bfly4(fr: { number }, fi: { number }, fstride: number, twr: { number }, twi: { number }, m: number, N: number, mm: number) +local function bfly4(fr: { number }, fi: { number }, fstride: number, twr: { number }, twi: { number }, m: number, N: number, mm: number) if m == 1 then local p = 1 for _ = 1, N do @@ -40356,7 +40371,7 @@ end end end -@native local function bfly3(fr: { number }, fi: { number }, fstride: number, twr: { number }, twi: { number }, m: number, N: number, mm: number) +local function bfly3(fr: { number }, fi: { number }, fstride: number, twr: { number }, twi: { number }, m: number, N: number, mm: number) local m2 = 2 * m local epi3i = twi[fstride * m + 1] for i = 0, N - 1 do @@ -40388,7 +40403,7 @@ end end end -@native local function bfly5(fr: { number }, fi: { number }, fstride: number, twr: { number }, twi: { number }, m: number, N: number, mm: number) +local function bfly5(fr: { number }, fi: { number }, fstride: number, twr: { number }, twi: { number }, m: number, N: number, mm: number) local yar, yai = twr[fstride * m + 1], twi[fstride * m + 1] local ybr, ybi = twr[fstride * 2 * m + 1], twi[fstride * 2 * m + 1] for i = 0, N - 1 do @@ -40446,7 +40461,7 @@ end end -- opus_fft_impl (bit-reversed input) -@native local function fftImpl(pl: Plan) +local function fftImpl(pl: Plan) local factors = pl.factors local fr, fi, twr, twi = pl.fr, pl.fi, pl.twr, pl.twi local fstride = { 1 } @@ -40476,7 +40491,7 @@ end end -- clt_mdct_backward -@native function Mdct.backward(inp: { number }, inBase: number, out: { number }, outBase: number, window: { number }, overlap: number, shift: number, stride: number) +function Mdct.backward(inp: { number }, inBase: number, out: { number }, outBase: number, window: { number }, overlap: number, shift: number, stride: number) local pl = plans[shift + 1] local N4 = pl.n local N2 = N4 * 2 @@ -40522,7 +40537,7 @@ end return Mdct end -__FILES["codecs/audio/Opus/Packet"] = @native function() +__FILES["codecs/audio/Opus/Packet"] = function() @@ -40543,7 +40558,7 @@ Packet.BW_WB = 1103 Packet.BW_SWB = 1104 Packet.BW_FB = 1105 -@native function Packet.mode(toc: number): number +function Packet.mode(toc: number): number if band(toc, 0x80) ~= 0 then return Packet.MODE_CELT_ONLY elseif band(toc, 0x60) == 0x60 then @@ -40553,7 +40568,7 @@ Packet.BW_FB = 1105 end end -@native function Packet.bandwidth(toc: number): number +function Packet.bandwidth(toc: number): number if band(toc, 0x80) ~= 0 then local bw = 1102 + band(rshift(toc, 5), 3) if bw == 1102 then @@ -40567,11 +40582,11 @@ end end end -@native function Packet.channels(toc: number): number +function Packet.channels(toc: number): number return if band(toc, 4) ~= 0 then 2 else 1 end -@native function Packet.samplesPerFrame(toc: number, Fs: number): number +function Packet.samplesPerFrame(toc: number, Fs: number): number if band(toc, 0x80) ~= 0 then local a = band(rshift(toc, 3), 3) return bit32.lshift(Fs, a) // 400 @@ -40586,7 +40601,7 @@ end end end -@native function Packet.samples(buf: buffer, off: number, len: number): number +function Packet.samples(buf: buffer, off: number, len: number): number if len < 1 then return -1 end @@ -40610,7 +40625,7 @@ end return n end -@native local function parseSize(buf: buffer, p: number, len: number): (number, number) +local function parseSize(buf: buffer, p: number, len: number): (number, number) if len < 1 then return -1, -1 end @@ -40624,7 +40639,7 @@ end end -- opus_packet_parse_impl; self-delimited packets (multistream) carry an explicit size for the last frame -@native function Packet.parse(buf: buffer, off: number, len: number, offsets: { number }, sizes: { number }, selfDelimited: boolean?): (number, number, number) +function Packet.parse(buf: buffer, off: number, len: number, offsets: { number }, sizes: { number }, selfDelimited: boolean?): (number, number, number) if len < 1 then return -1, 0, 0 end @@ -40755,7 +40770,7 @@ end return Packet end -__FILES["codecs/audio/Opus/Silk"] = @native function() +__FILES["codecs/audio/Opus/Silk"] = function() @@ -40775,14 +40790,14 @@ local P2 = table.create(64, 0) for s = 1, 63 do P2[s] = 2 ^ s end -@native local function p2(s: number): number +local function p2(s: number): number if s == 0 then return 1 end return P2[s] end -@native local function s16(x: number): number +local function s16(x: number): number x = x % 65536 if x >= 32768 then return x - 65536 @@ -40790,7 +40805,7 @@ end return x end -@native local function i32(x: number): number +local function i32(x: number): number x = x % 4294967296 if x >= 2147483648 then return x - 4294967296 @@ -40798,7 +40813,7 @@ end return x end -@native local function sat16(x: number): number +local function sat16(x: number): number if x > 32767 then return 32767 elseif x < -32768 then @@ -40807,7 +40822,7 @@ end return x end -@native local function addSat32(a: number, b: number): number +local function addSat32(a: number, b: number): number local s = a + b if s > 2147483647 then return 2147483647 @@ -40817,7 +40832,7 @@ end return s end -@native local function subSat32(a: number, b: number): number +local function subSat32(a: number, b: number): number local s = a - b if s > 2147483647 then return 2147483647 @@ -40828,17 +40843,17 @@ end end -- silk_CLZ32 of a non-negative int32 -@native local function clz32(x: number): number +local function clz32(x: number): number return countlz(x) end -- silk_SMULWW (64-bit form): (a * b) >> 16, exact -@native local function mulww(a: number, b: number): number +local function mulww(a: number, b: number): number return a * (b // 65536) + (a * (b % 65536)) // 65536 end -- floor(a * b / 2^s) for int32 a, b and s >= 16, exact -@native local function mulshr(a: number, b: number, s: number): number +local function mulshr(a: number, b: number, s: number): number local t = a * (b // 65536) + (a * (b % 65536)) // 65536 if s == 16 then return t @@ -40846,16 +40861,16 @@ end return t // P2[s - 16] end -@native local function smmul(a: number, b: number): number +local function smmul(a: number, b: number): number return mulshr(a, b, 32) end -- silk_RSHIFT_ROUND (shift >= 1) -@native local function rround(a: number, s: number): number +local function rround(a: number, s: number): number return (a + p2(s - 1)) // P2[s] end -@native local function lshiftSat32(a: number, sh: number): number +local function lshiftSat32(a: number, sh: number): number if sh == 0 then return a end @@ -40870,7 +40885,7 @@ end end -- C integer division (truncation toward zero) -@native local function tdiv(a: number, b: number): number +local function tdiv(a: number, b: number): number local q = a / b if q >= 0 then return floor(q) @@ -40879,24 +40894,24 @@ end end -- low 32 bits of a * b, as int32 -@native local function imul32(a: number, b: number): number +local function imul32(a: number, b: number): number a = a % 4294967296 local ah, al = a // 65536, a % 65536 return i32(((ah * b) % 65536) * 65536 + al * b) end -@native local function silkRand(seed: number): number +local function silkRand(seed: number): number return i32(907633515 + imul32(seed, 196314165)) end -@native local function rshift(a: number, s: number): number +local function rshift(a: number, s: number): number if s == 0 then return a end return a // P2[s] end -@native local function silkINVERSE32_varQ(b32: number, Qres: number): number +local function silkINVERSE32_varQ(b32: number, Qres: number): number local b_headrm = clz32(math.abs(b32)) - 1 local b32_nrm = b32 * p2(b_headrm) local b32_inv = tdiv(536870911, b32_nrm // 65536) @@ -40912,7 +40927,7 @@ end return 0 end -@native local function silkDIV32_varQ(a32: number, b32: number, Qres: number): number +local function silkDIV32_varQ(a32: number, b32: number, Qres: number): number local a_headrm = clz32(math.abs(a32)) - 1 local a32_nrm = a32 * p2(a_headrm) local b_headrm = clz32(math.abs(b32)) - 1 @@ -40930,7 +40945,7 @@ end return 0 end -@native local function silkLog2lin(inLog_Q7: number): number +local function silkLog2lin(inLog_Q7: number): number if inLog_Q7 < 0 then return 0 elseif inLog_Q7 >= 3967 then @@ -40947,7 +40962,7 @@ end return out end -@native local function silkSQRT_APPROX(x: number): number +local function silkSQRT_APPROX(x: number): number if x <= 0 then return 0 end @@ -40969,7 +40984,7 @@ end end -- silk_sum_sqr_shift: energy, shift -@native local function sumSqrShift(x: { number }, xo: number, len: number): (number, number) +local function sumSqrShift(x: { number }, xo: number, len: number): (number, number) local shft = 31 - clz32(len) local nrg = len local i = 0 @@ -40998,7 +41013,7 @@ end end -- silk_bwexpander (int16 coefficients), ar 1-based -@native local function bwexpander(ar: { number }, d: number, chirp_Q16: number) +local function bwexpander(ar: { number }, d: number, chirp_Q16: number) local chirp_minus_one_Q16 = chirp_Q16 - 65536 for i = 1, d - 1 do ar[i] = s16((chirp_Q16 * ar[i] + 32768) // 65536) @@ -41007,7 +41022,7 @@ end ar[d] = s16((chirp_Q16 * ar[d] + 32768) // 65536) end -@native local function bwexpander32(ar: { number }, d: number, chirp_Q16: number) +local function bwexpander32(ar: { number }, d: number, chirp_Q16: number) local chirp_minus_one_Q16 = chirp_Q16 - 65536 for i = 1, d - 1 do ar[i] = i32(mulww(chirp_Q16, ar[i])) @@ -41017,7 +41032,7 @@ end end -- silk_LPC_fit: a_QIN (int32, QIN) -> a_QOUT (int16, QOUT) -@native local function lpcFit(a_QOUT: { number }, a_QIN: { number }, QOUT: number, QIN: number, d: number) +local function lpcFit(a_QOUT: { number }, a_QIN: { number }, QOUT: number, QIN: number, d: number) local sh = QIN - QOUT local idx = 0 local i = 0 @@ -41057,7 +41072,7 @@ local INV_GAIN_MIN = 107374 local Atmp_QA = table.create(16, 0) -- RSHIFT_ROUND64(SMULL(a, b), Q) -@native local function mulRound(a: number, b: number, Q: number): number +local function mulRound(a: number, b: number, Q: number): number if Q == 1 then local p = a * b return p // 2 + p % 2 @@ -41068,7 +41083,7 @@ local Atmp_QA = table.create(16, 0) return ((a * b) // P2[Q - 1] + 1) // 2 end -@native local function lpcInversePredGainQA(A_QA: { number }, order: number): number +local function lpcInversePredGainQA(A_QA: { number }, order: number): number local invGain_Q30 = 1073741824 local k = order - 1 while k > 0 do @@ -41113,7 +41128,7 @@ end return invGain_Q30 end -@native local function lpcInversePredGain(A_Q12: { number }, order: number): number +local function lpcInversePredGain(A_Q12: { number }, order: number): number local DC_resp = 0 for k = 1, order do DC_resp += A_Q12[k] @@ -41134,7 +41149,7 @@ local a32_QA1 = table.create(16, 0) local LSFCos = T.LSFCosTab_FIX_Q12 -- out[0..dd] (1-based storage), from interleaved cLSF starting at C index c0 -@native local function findPoly(out: { number }, cLSF: { number }, c0: number, dd: number) +local function findPoly(out: { number }, cLSF: { number }, c0: number, dd: number) out[1] = 65536 out[2] = -cLSF[c0 + 1] for k = 1, dd - 1 do @@ -41148,7 +41163,7 @@ local LSFCos = T.LSFCosTab_FIX_Q12 end -- silk_NLSF2A: a_Q12 (1-based, d entries) from NLSF (1-based) -@native local function nlsf2a(a_Q12: { number }, NLSF: { number }, d: number) +local function nlsf2a(a_Q12: { number }, NLSF: { number }, d: number) local ordering = if d == 16 then ordering16 else ordering10 for k = 1, d do local nl = NLSF[k] @@ -41179,7 +41194,7 @@ end end -- silk_LPC_analysis_filter: out[oo + ix] for ix in [0, len), from inp[io + ix]; B 1-based Q12 -@native local function lpcAnalysisFilter(out: { number }, oo: number, inp: { number }, io: number, B: { number }, len: number, d: number) +local function lpcAnalysisFilter(out: { number }, oo: number, inp: { number }, io: number, B: { number }, len: number, d: number) for ix = d, len - 1 do local base = io + ix - 1 local acc = 0 @@ -41223,7 +41238,7 @@ local ec_ix = table.create(16, 0) local pred_Q8 = table.create(16, 0) local res_Q10 = table.create(16, 0) -@native local function nlsfUnpack(CB: any, CB1_index: number) +local function nlsfUnpack(CB: any, CB1_index: number) local order = CB.order local sel = CB.ec_sel local pq = CB.pred_Q8 @@ -41238,7 +41253,7 @@ local res_Q10 = table.create(16, 0) end end -@native local function nlsfStabilize(NLSF: { number }, NDeltaMin: { number }, L: number) +local function nlsfStabilize(NLSF: { number }, NDeltaMin: { number }, L: number) local loops = 0 while loops < 20 do local min_diff = NLSF[1] - NDeltaMin[1] @@ -41315,7 +41330,7 @@ end end -- silk_NLSF_decode: pNLSF_Q15 (1-based) from indices (1-based: [1] = CB1 index) -@native local function nlsfDecode(pNLSF_Q15: { number }, NLSFIndices: { number }, CB: any) +local function nlsfDecode(pNLSF_Q15: { number }, NLSFIndices: { number }, CB: any) nlsfUnpack(CB, NLSFIndices[1]) local order = CB.order local step = CB.quantStepSize_Q16 @@ -41355,7 +41370,7 @@ local delay_matrix_dec = { { 0, 3, 12, 7, 7, 7 }, } -@native local function rateID(R: number): number +local function rateID(R: number): number local a = R // 4096 - (if R > 16000 then 1 else 0) if R > 24000 then a = a // 2 @@ -41363,7 +41378,7 @@ local delay_matrix_dec = { return math.min(5, a - 1) end -@native local function newResampler(): any +local function newResampler(): any return { sIIR = table.create(6, 0), sFIR = table.create(8, 0), @@ -41378,7 +41393,7 @@ end } end -@native local function copyResampler(dst: any, src: any) +local function copyResampler(dst: any, src: any) for i = 1, 6 do dst.sIIR[i] = src.sIIR[i] end @@ -41396,7 +41411,7 @@ end dst.Fs_out_kHz = src.Fs_out_kHz end -@native local function resamplerInit(S: any, Fs_Hz_in: number, Fs_Hz_out: number): number +local function resamplerInit(S: any, Fs_Hz_in: number, Fs_Hz_out: number): number table.clear(S.sIIR) table.clear(S.sFIR) table.clear(S.delayBuf) @@ -41436,7 +41451,7 @@ end end -- silk_resampler_private_up2_HQ: out[oo + 2k], out[oo + 2k + 1] from inp[io + k] -@native local function up2HQ(S: { number }, out: { number }, oo: number, inp: { number }, io: number, len: number) +local function up2HQ(S: { number }, out: { number }, oo: number, inp: { number }, io: number, len: number) local s0, s1, s2, s3, s4, s5 = S[1], S[2], S[3], S[4], S[5], S[6] local c00, c01, c02 = up2_hq_0[1], up2_hq_0[2], up2_hq_0[3] local c10, c11, c12 = up2_hq_1[1], up2_hq_1[2], up2_hq_1[3] @@ -41472,7 +41487,7 @@ end S[1], S[2], S[3], S[4], S[5], S[6] = s0, s1, s2, s3, s4, s5 end -@native local function iirFirInterpol(out: { number }, oo: number, buf: { number }, max_index_Q16: number, incr: number): number +local function iirFirInterpol(out: { number }, oo: number, buf: { number }, max_index_Q16: number, incr: number): number local index_Q16 = 0 while index_Q16 < max_index_Q16 do local ti = ((index_Q16 % 65536) * 12) // 65536 @@ -41494,7 +41509,7 @@ end return oo end -@native local function iirFir(S: any, out: { number }, oo: number, inp: { number }, io: number, inLen: number) +local function iirFir(S: any, out: { number }, oo: number, inp: { number }, io: number, inLen: number) local buf = S.buf local sFIR = S.sFIR for i = 1, 8 do @@ -41523,7 +41538,7 @@ end end end -@native local function resampleBlock(S: any, out: { number }, oo: number, inp: { number }, io: number, len: number) +local function resampleBlock(S: any, out: { number }, oo: number, inp: { number }, io: number, len: number) local f = S.resampler_function if f == RES_IIR_FIR then iirFir(S, out, oo, inp, io, len) @@ -41537,7 +41552,7 @@ end end -- silk_resampler: out[1..] from inp[io .. io + inLen - 1] -@native local function resampler(S: any, out: { number }, inp: { number }, io: number, inLen: number) +local function resampler(S: any, out: { number }, inp: { number }, io: number, inLen: number) local fin = S.Fs_in_kHz local delay = S.inputDelay local nSamples = fin - delay @@ -41552,7 +41567,7 @@ end end end -@native local function newChannel(): any +local function newChannel(): any return { prev_gain_Q16 = 65536, exc_Q14 = table.create(320, 0), @@ -41631,7 +41646,7 @@ end } end -@native local function decoderSetFs(ch: any, fs_kHz: number, fs_API_Hz: number): number +local function decoderSetFs(ch: any, fs_kHz: number, fs_API_Hz: number): number local ret = 0 ch.subfr_length = 5 * fs_kHz local frame_length = ch.nb_subfr * ch.subfr_length @@ -41683,7 +41698,7 @@ local LTP_gain_iCDF = { T.LTP_gain_iCDF_0, T.LTP_gain_iCDF_1, T.LTP_gain_iCDF_2 local LTP_vq_Q7 = { T.LTP_gain_vq_0, T.LTP_gain_vq_1, T.LTP_gain_vq_2 } local LBRR_flags_iCDF = { T.LBRR_flags_2_iCDF, T.LBRR_flags_3_iCDF } -@native local function decodeIndices(ch: any, d: any, FrameIndex: number, decode_LBRR: boolean, condCoding: number) +local function decodeIndices(ch: any, d: any, FrameIndex: number, decode_LBRR: boolean, condCoding: number) local ind = ch.indices local Ix if decode_LBRR or ch.VAD_flags[FrameIndex + 1] ~= 0 then @@ -41755,7 +41770,7 @@ end local shell0, shell1, shell2, shell3 = T.shell_code_table0, T.shell_code_table1, T.shell_code_table2, T.shell_code_table3 local shellOff = T.shell_code_table_offsets -@native local function split(d: any, p: number, tab: { number }): (number, number) +local function split(d: any, p: number, tab: { number }): (number, number) if p > 0 then local a = icdf(d, tab, shellOff[p + 1] + 1, 8) return a, p - a @@ -41763,7 +41778,7 @@ local shellOff = T.shell_code_table_offsets return 0, 0 end -@native local function shellDecoder(out: { number }, o: number, d: any, pulses4: number) +local function shellDecoder(out: { number }, o: number, d: any, pulses4: number) local p3a, p3b = split(d, pulses4, shell3) local p2a, p2b = split(d, p3a, shell2) local p1a, p1b = split(d, p2a, shell1) @@ -41786,7 +41801,7 @@ local nLshifts = table.create(20, 0) local signIcdf = { 0, 0 } -- pulses[1 .. frame_length (rounded up to 16)] -@native local function decodePulses(d: any, pulses: { number }, signalType: number, quantOffsetType: number, frame_length: number) +local function decodePulses(d: any, pulses: { number }, signalType: number, quantOffsetType: number, frame_length: number) local RateLevelIndex = icdf(d, T.rate_levels_iCDF, (signalType // 2) * 9 + 1, 8) local iter = frame_length // 16 if iter * 16 < frame_length then @@ -41852,7 +41867,7 @@ end local pNLSF_Q15 = table.create(16, 0) local pNLSF0_Q15 = table.create(16, 0) -@native local function gainsDequant(gain_Q16: { number }, ind: { number }, ch: any, conditional: boolean, nb_subfr: number) +local function gainsDequant(gain_Q16: { number }, ind: { number }, ch: any, conditional: boolean, nb_subfr: number) local prev = ch.LastGainIndex for k = 1, nb_subfr do if k == 1 and not conditional then @@ -41881,7 +41896,7 @@ local CB_lags = { [0] = { [4] = { T.CB_lags_stage3, 34 }, [2] = { T.CB_lags_stage3_10_ms, 12 } }, } -@native local function decodeParameters(ch: any, ctrl: any, condCoding: number) +local function decodeParameters(ch: any, ctrl: any, condCoding: number) local ind = ch.indices gainsDequant(ctrl.Gains_Q16, ind.GainsIndices, ch, condCoding == 2, ch.nb_subfr) local order = ch.LPC_order @@ -41954,7 +41969,7 @@ local A_Q12_tmp = table.create(16, 0) local QuantOffsets = { { 100, 240 }, { 32, 100 } } -- silk_decode_core: xq[xo .. xo + frame_length - 1] -@native local function decodeCore(ch: any, ctrl: any, xq: { number }, xo: number, pulses: { number }) +local function decodeCore(ch: any, ctrl: any, xq: { number }, xo: number, pulses: { number }) local ind = ch.indices local exc = ch.exc_Q14 local offset_Q10 = QuantOffsets[ind.signalType // 2 + 1][ind.quantOffsetType + 1] @@ -42115,7 +42130,7 @@ local HARM_ATT_Q15 = { 32440, 31130 } local PLC_RAND_ATTENUATE_V_Q15 = { 31130, 26214 } local PLC_RAND_ATTENUATE_UV_Q15 = { 32440, 29491 } -@native local function plcReset(ch: any) +local function plcReset(ch: any) local plc = ch.sPLC plc.pitchL_Q8 = ch.frame_length * 128 plc.prevGain_Q16[1] = 65536 @@ -42124,7 +42139,7 @@ local PLC_RAND_ATTENUATE_UV_Q15 = { 32440, 29491 } plc.nb_subfr = 2 end -@native local function cngReset(ch: any) +local function cngReset(ch: any) local step = tdiv(32767, ch.LPC_order + 1) local acc = 0 local cng = ch.sCNG @@ -42136,7 +42151,7 @@ end cng.rand_seed = 3176576 end -@native local function plcUpdate(ch: any, ctrl: any) +local function plcUpdate(ch: any, ctrl: any) local plc = ch.sPLC local nb = ch.nb_subfr ch.prevSignalType = ch.indices.signalType @@ -42199,7 +42214,7 @@ local plcLTP = table.create(320, 0) local plcLTP_Q14 = table.create(640, 0) local A_plc = table.create(16, 0) -@native local function plcConceal(ch: any, ctrl: any, frame: { number }, fo: number) +local function plcConceal(ch: any, ctrl: any, frame: { number }, fo: number) local plc = ch.sPLC local ltp_mem_length = ch.ltp_mem_length local order = ch.LPC_order @@ -42316,7 +42331,7 @@ local A_plc = table.create(16, 0) end end -@native local function plcGlueFrames(ch: any, frame: { number }, fo: number, length: number) +local function plcGlueFrames(ch: any, frame: { number }, fo: number, length: number) local plc = ch.sPLC if ch.lossCnt ~= 0 then plc.conc_energy, plc.conc_energy_shift = sumSqrShift(frame, fo, length) @@ -42352,7 +42367,7 @@ end local A_cng = table.create(16, 0) local CNG_sig = table.create(336, 0) -@native local function cng(ch: any, ctrl: any, frame: { number }, fo: number, length: number) +local function cng(ch: any, ctrl: any, frame: { number }, fo: number, length: number) local c = ch.sCNG if ch.fs_kHz ~= c.fs_kHz then cngReset(ch) @@ -42437,7 +42452,7 @@ local CNG_sig = table.create(336, 0) end -- silk_decode_frame: writes frame_length samples to out[fo ..] -@native local function decodeFrame(ch: any, d: any, out: { number }, fo: number, lostFlag: number, condCoding: number): number +local function decodeFrame(ch: any, d: any, out: { number }, fo: number, lostFlag: number, condCoding: number): number local L = ch.frame_length local ctrl = ch.ctrl ctrl.LTP_scale_Q14 = 0 @@ -42486,7 +42501,7 @@ end return L end -@native local function stereoDecodePred(d: any, pred_Q13: { number }) +local function stereoDecodePred(d: any, pred_Q13: { number }) local n = icdf(d, T.stereo_pred_joint_iCDF, 1, 8) local ix02 = n // 5 local ix12 = n - 5 * ix02 @@ -42506,7 +42521,7 @@ end end -- x1, x2: samplesOut1_tmp arrays (C index j at [j + 1]) -@native local function stereoMSToLR(state: any, x1: { number }, x2: { number }, pred_Q13: { number }, fs_kHz: number, frame_length: number) +local function stereoMSToLR(state: any, x1: { number }, x2: { number }, pred_Q13: { number }, fs_kHz: number, frame_length: number) x1[1], x1[2] = state.sMid[1], state.sMid[2] x2[1], x2[2] = state.sSide[1], state.sSide[2] state.sMid[1], state.sMid[2] = x1[frame_length + 1], x1[frame_length + 2] @@ -42544,7 +42559,7 @@ end type State = any -@native function Silk.new(apiChannels: number): State +function Silk.new(apiChannels: number): State return { ch = { newChannel(), newChannel() }, sStereo = { pred_prev_Q13 = { 0, 0 }, sMid = { 0, 0 }, sSide = { 0, 0 } }, @@ -42558,7 +42573,7 @@ type State = any end -- silk_ResetDecoder (keeps nChannelsAPI / nChannelsInternal, like libopus) -@native function Silk.reset(st: State) +function Silk.reset(st: State) st.ch[1] = newChannel() st.ch[2] = newChannel() for _, ch in st.ch do @@ -42569,14 +42584,14 @@ end st.prev_decode_only_middle = 0 end -@native local function initChannel(st: State, n: number) +local function initChannel(st: State, n: number) local ch = newChannel() cngReset(ch) plcReset(ch) st.ch[n] = ch end -@native function Silk.decode(st: State, ctrl: any, lostFlag: number, firstFrame: boolean, d: any, out: { number }, outBase: number): (number, number) +function Silk.decode(st: State, ctrl: any, lostFlag: number, firstFrame: boolean, d: any, out: { number }, outBase: number): (number, number) local ret = 0 local nInt = ctrl.nChannelsInternal local nAPI = ctrl.nChannelsAPI @@ -42780,7 +42795,7 @@ end end -- the pitch lag of the last frame at 48 kHz (decControl->prevPitchLag), 0 when unvoiced -@native function Silk.prevPitchLag(st: State): number +function Silk.prevPitchLag(st: State): number local ch = st.ch[1] if ch.prevSignalType == 2 then local mult = { 6, 4, 3 } @@ -43428,7 +43443,7 @@ end return Pcm end -__FILES["codecs/audio/Pcm/Convert"] = @native function() +__FILES["codecs/audio/Pcm/Convert"] = function() @@ -43498,7 +43513,7 @@ end local SEG_AEND = { 0x1F, 0x3F, 0x7F, 0xFF, 0x1FF, 0x3FF, 0x7FF, 0xFFF } local SEG_UEND = { 0x3F, 0x7F, 0xFF, 0x1FF, 0x3FF, 0x7FF, 0xFFF, 0x1FFF } -@native local function segment(v: number, ends: { number }): number +local function segment(v: number, ends: { number }): number for i = 1, 8 do if v <= ends[i] then return i - 1 @@ -43507,7 +43522,7 @@ local SEG_UEND = { 0x3F, 0x7F, 0xFF, 0x1FF, 0x3FF, 0x7FF, 0xFFF, 0x1FFF } return 8 end -@native local function alawEncode(pcm: number): number +local function alawEncode(pcm: number): number local mask local v = floor(pcm / 8) -- 13-bit magnitude domain if v >= 0 then @@ -43531,7 +43546,7 @@ end return bit32.bxor(aval, mask) end -@native local function ulawEncode(pcm: number): number +local function ulawEncode(pcm: number): number local v = floor(pcm / 4) -- 14-bit local mask if v < 0 then @@ -43558,7 +43573,7 @@ Convert.ulawEncode = ulawEncode Convert.ALAW = ALAW Convert.ULAW = ULAW -@native function Convert.decode(src: buffer, so: number, fmt: string, count: number, dst: buffer, d: number): boolean +function Convert.decode(src: buffer, so: number, fmt: string, count: number, dst: buffer, d: number): boolean if fmt == "s16le" then for i = 0, count - 1 do writef32(dst, d + i * 4, readi16(src, so + i * 2) / 32768) @@ -43636,7 +43651,7 @@ Convert.ULAW = ULAW return true end -@native local function q(x: number, s: number): number +local function q(x: number, s: number): number local v = floor(x * s + 0.5) if v ~= v then return 0 @@ -43649,7 +43664,7 @@ end return v end -@native function Convert.encode(src: buffer, so: number, count: number, fmt: string, dst: buffer, d: number): boolean +function Convert.encode(src: buffer, so: number, count: number, fmt: string, dst: buffer, d: number): boolean if fmt == "s16le" then for i = 0, count - 1 do writei16(dst, d + i * 2, q(readf32(src, so + i * 4), 32768)) @@ -43725,7 +43740,7 @@ end return Convert end -__FILES["codecs/audio/Qoa"] = @native function() +__FILES["codecs/audio/Qoa"] = function() @@ -43766,21 +43781,21 @@ local DEQ = { 1536, -1536, 5120, -5120, 9216, -9216, 14336, -14336, } -@native local function be32(b: buffer, p: number): number +local function be32(b: buffer, p: number): number return byteswap(readu32(b, p)) end -@native local function s16(v: number): number +local function s16(v: number): number return if v >= 32768 then v - 65536 else v end -@native function Qoa.frameSize(ch: number, slices: number): number +function Qoa.frameSize(ch: number, slices: number): number return 8 + 16 * ch + 8 * slices * ch end type FrameInfo = { channels: number, rate: number, samples: number, size: number } -@native function Qoa.frameInfo(b: buffer, p: number, avail: number): (FrameInfo?, string?) +function Qoa.frameInfo(b: buffer, p: number, avail: number): (FrameInfo?, string?) if avail < 8 then return nil, "truncated frame header" end @@ -43803,7 +43818,7 @@ type FrameInfo = { channels: number, rate: number, samples: number, size: number return { channels = ch, rate = rate, samples = samples, size = size }, nil end -@native function Qoa.decodeFrame(b: buffer, p: number, avail: number, dst: buffer, d: number): (number?, number | string) +function Qoa.decodeFrame(b: buffer, p: number, avail: number, dst: buffer, d: number): (number?, number | string) local info, msg = Qoa.frameInfo(b, p, avail) if not info then return nil, msg :: string @@ -43856,7 +43871,7 @@ end end -- LMS state: 8 i32 per channel (history 0..3, weights 0..3); initial weights 0, 0, -1, 2 (<< 13) -@native function Qoa.newLms(ch: number): buffer +function Qoa.newLms(ch: number): buffer local st = buffer.create(32 * ch) for c = 0, ch - 1 do writei32(st, c * 32 + 24, -8192) @@ -43865,7 +43880,7 @@ end return st end -@native local function toS16(x: number): number +local function toS16(x: number): number local v = floor(x * 32768 + 0.5) if v ~= v then return 0 @@ -43879,7 +43894,7 @@ end -- qoa.h's qoa_div: a rounding division by the scale factor through its .16 reciprocal (in 32-bit int arithmetic, which -- wraps for big residuals at scale factor 0), rounding away from zero -@native local function qdiv(v: number, sf: number): number +local function qdiv(v: number, sf: number): number local x = v * RECIP[sf + 1] + 32768 if x >= 2147483648 or x < -2147483648 then x = (x + 2147483648) % 4294967296 - 2147483648 @@ -43890,7 +43905,7 @@ end return n + sv - sn end -@native function Qoa.encodeFrame(x: buffer, xf: number, n: number, ch: number, rate: number, lms: buffer, out: buffer, p: number): number +function Qoa.encodeFrame(x: buffer, xf: number, n: number, ch: number, rate: number, lms: buffer, out: buffer, p: number): number local slices = (n + 19) // 20 local size = Qoa.frameSize(ch, slices) writeu32(out, p, byteswap(bor(lshift(ch, 24), rate))) @@ -44007,7 +44022,7 @@ end return Qoa end -__FILES["codecs/audio/Resample"] = @native function() +__FILES["codecs/audio/Resample"] = function() @@ -44047,7 +44062,7 @@ 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 -@native local function besselI0(x: number): number +local function besselI0(x: number): number local sum, term = 1, 1 for k = 1, 80 do term *= (x / (2 * k)) ^ 2 @@ -44059,7 +44074,7 @@ local readf32, writef32 = buffer.readf32, buffer.writef32 return sum end -@native local function gcd(a: number, b: number): number +local function gcd(a: number, b: number): number while b ~= 0 do a, b = b, a % b end @@ -44075,7 +44090,7 @@ type Filter = { } -- phase p: an output p / phases past an input sample; tap k multiplies input floor(t) - half + 1 + k -@native local function makeFilter(ratio: number, phases: number, exact: boolean, zc: number, beta: number, cut: number): Filter +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) @@ -44125,7 +44140,7 @@ type State = { flush: any, } -@native local function run(st: State, limitOut: number, out: buffer?): (buffer, number) +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 @@ -44212,7 +44227,7 @@ type State = { return b, n end -@native local function process(self: State, src: buffer, frames: number, out: buffer?): (buffer, number) +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 @@ -44228,7 +44243,7 @@ end return run(self, math.huge, out) end -@native local function flush(self: State, out: buffer?): (buffer, number) +local function flush(self: State, out: buffer?): (buffer, number) if self.done then return out or buffer.create(0), 0 end @@ -44237,7 +44252,7 @@ end return run(self, total, out) end -@native function Resample.new(from: number, to: number, channels: number, opts: Options?): (Resampler?, string?) +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 @@ -44280,7 +44295,7 @@ end return st :: any, nil end -@native function Resample.buffer(src: buffer, frames: number, channels: number, from: number, to: number, opts: Options?): (buffer?, number | string) +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 @@ -44314,7 +44329,7 @@ end return out, got end -@native function Resample.source(src: any, to: number, opts: Options?): (any, string?) +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 @@ -44334,7 +44349,7 @@ end err = nil :: any, } local inTmp: buffer? = nil - @native function out.read(self: any, n: number, dst: buffer?): (buffer, number) + function out.read(self: any, n: number, dst: buffer?): (buffer, number) n = floor(n) while pendingFrames - pendingPos <= 0 and not ended do local b: buffer, m: number = (src :: any):read(math.max(1024, floor(n * src.sampleRate / to) + 64), inTmp) @@ -45076,7 +45091,7 @@ end return Parse end -__FILES["codecs/audio/SoundFont/Synth"] = @native function() +__FILES["codecs/audio/SoundFont/Synth"] = function() -- codecs/audio/SoundFont/Synth: a SoundFont 2 sample synthesizer with MIDI channels. @@ -45164,24 +45179,24 @@ type State = { channels: { Channel }, } -@native local function tc2s(tc: number): number +local function tc2s(tc: number): number return 2 ^ (tc / 1200) end -@native local function cents2Hz(c: number): number +local function cents2Hz(c: number): number return 8.176 * 2 ^ (c / 1200) end -@native local function db2gain(db: number): number +local function db2gain(db: number): number return if db > -100 then 10 ^ (db * 0.05) else 0 end -@native local function gain2db(g: number): number +local function gain2db(g: number): number return if g <= 0.00001 then -100 else 20 * math.log10(g) end -@native local function releaseSamples(e: Env, rate: number): number +local function releaseSamples(e: Env, rate: number): number return floor((if e.release <= 0 then FASTRELEASE else e.release) * rate) end -@native local function nextSegment(e: Env, active: number, rate: number) +local function nextSegment(e: Env, active: number, rate: number) local seg = active if seg == NONE then e.untilNext = floor(e.delay * rate) @@ -45251,7 +45266,7 @@ end e.segment, e.isExp, e.level, e.slope, e.untilNext = DONE, false, 0, 0, 0x7FFFFFF end -@native local function envSetup(e: Env, r: { [string]: number }, p: string, key: number, vel: number, isAmp: boolean, rate: number) +local function envSetup(e: Env, r: { [string]: number }, p: string, key: number, vel: number, isAmp: boolean, rate: number) e.delay, e.attack, e.hold, e.decay = r[p .. "Delay"], r[p .. "Attack"], r[p .. "Hold"], r[p .. "Decay"] e.sustain, e.release = r[p .. "Sustain"], r[p .. "Release"] local kh, kd = r[p .. "KeyHold"], r[p .. "KeyDecay"] @@ -45267,7 +45282,7 @@ end nextSegment(e, NONE, rate) end -@native local function envProcess(e: Env, n: number, rate: number) +local function envProcess(e: Env, n: number, rate: number) local slope = e.slope if slope ~= 0 then if e.isExp then @@ -45282,11 +45297,11 @@ end end end -@native local function newEnv(): Env +local function newEnv(): Env return { segment = DONE, isExp = false, isAmp = false, vel = 0, level = 0, slope = 0, untilNext = 0, delay = 0, attack = 0, hold = 0, decay = 0, sustain = 0, release = 0 } end -@native local function lowpassSetup(v: Voice, fc: number) +local function lowpassSetup(v: Voice, fc: number) -- the biquad from earlevel.com (as tsf.h) local k = tan(PI * fc) local kk = k * k @@ -45297,13 +45312,13 @@ end v.b2 = (1 - k * v.qinv + kk) * norm end -@native local function lfoSetup(l: Lfo, delay: number, freqCents: number, rate: number) +local function lfoSetup(l: Lfo, delay: number, freqCents: number, rate: number) l.untilStart = floor(delay * rate) l.delta = 4 * cents2Hz(freqCents) / rate l.level = 0 end -@native local function lfoProcess(l: Lfo, n: number) +local function lfoProcess(l: Lfo, n: number) if l.untilStart > n then l.untilStart -= n return @@ -45318,7 +45333,7 @@ end end end -@native local function calcPitch(v: Voice, shift: number, rate: number) +local function calcPitch(v: Voice, shift: number, rate: number) local r = v.region local note = v.key + r.transpose + r.tune / 100 local adjusted = r.keycenter + (note - r.keycenter) * (r.keytrack / 100) + shift @@ -45326,7 +45341,7 @@ end v.pitchOut = r.sampleRate / (tc2s(r.keycenter * 100) * rate) end -@native local function setPan(v: Voice, pan: number) +local function setPan(v: Voice, pan: number) if pan <= -0.5 then v.panL, v.panR = 1, 0 elseif pan >= 0.5 then @@ -45336,11 +45351,11 @@ end end end -@native local function channelShift(c: Channel): number +local function channelShift(c: Channel): number return if c.pitchWheel == 8192 then c.tuning else (c.pitchWheel / 16383 * c.pitchRange * 2) - c.pitchRange + c.tuning end -@native local function voiceEnd(s: State, v: Voice) +local function voiceEnd(s: State, v: Voice) nextSegment(v.amp, SUSTAIN, s.rate) nextSegment(v.mod, SUSTAIN, s.rate) if v.region.loopMode == LOOP_SUSTAIN then @@ -45348,14 +45363,14 @@ end end end -@native local function voiceEndQuick(s: State, v: Voice) +local function voiceEndQuick(s: State, v: Voice) v.amp.release = 0 nextSegment(v.amp, SUSTAIN, s.rate) v.mod.release = 0 nextSegment(v.mod, SUSTAIN, s.rate) end -@native local function newVoice(): Voice +local function newVoice(): Voice return { preset = -1, key = 0, channel = 0, held = false, region = {}, pitchIn = 0, pitchOut = 0, pos = 0, gainDB = 0, panL = 0, panR = 0, playIndex = 0, loopStart = 0, loopEnd = 0, amp = newEnv(), mod = newEnv(), @@ -45364,14 +45379,14 @@ end } end -@native local function newChannel(): Channel +local function newChannel(): Channel return { preset = 1, bank = 0, pitchWheel = 8192, midiPan = 8192, midiVolume = 16383, midiExpression = 16383, midiRPN = 0xFFFF, midiData = 0, sustain = false, panOffset = 0, gainDB = 0, pitchRange = 2, tuning = 0, } end -@native function Synth.new(sf: any, rate: number, gain: number?, maxVoices: number?): State +function Synth.new(sf: any, rate: number, gain: number?, maxVoices: number?): State local lookup: { [number]: number } = {} for i, p in sf.presets do local k = p.bank * 128 + p.preset @@ -45399,11 +45414,11 @@ end return s end -@native local function presetIndex(s: State, bank: number, preset: number): number +local function presetIndex(s: State, bank: number, preset: number): number return s.lookup[bank * 128 + preset] or -1 end -@native function Synth.noteOn(s: State, ch: number, key: number, velocity: number) +function Synth.noteOn(s: State, ch: number, key: number, velocity: number) local c = s.channels[ch + 1] if not c then return @@ -45492,7 +45507,7 @@ end end end -@native function Synth.noteOff(s: State, ch: number, key: number) +function Synth.noteOff(s: State, ch: number, key: number) local c = s.channels[ch + 1] if not c then return @@ -45519,7 +45534,7 @@ end end end -@native local function applyPitch(s: State, ch: number, c: Channel) +local function applyPitch(s: State, ch: number, c: Channel) local shift = channelShift(c) for _, v in s.voices do if v.preset ~= -1 and v.channel == ch then @@ -45528,7 +45543,7 @@ end end end -@native local function setVolume(s: State, ch: number, c: Channel, volume: number) +local function setVolume(s: State, ch: number, c: Channel, volume: number) local db = gain2db(volume) if db == c.gainDB then return @@ -45542,7 +45557,7 @@ end c.gainDB = db end -@native local function setChannelPan(s: State, ch: number, c: Channel, pan: number) +local function setChannelPan(s: State, ch: number, c: Channel, pan: number) for _, v in s.voices do if v.preset ~= -1 and v.channel == ch then setPan(v, v.region.pan + pan - 0.5) @@ -45551,14 +45566,14 @@ end c.panOffset = pan - 0.5 end -@native local function setTuning(s: State, ch: number, c: Channel, tuning: number) +local function setTuning(s: State, ch: number, c: Channel, tuning: number) if c.tuning ~= tuning then c.tuning = tuning applyPitch(s, ch, c) end end -@native local function setPitchRange(s: State, ch: number, c: Channel, range: number) +local function setPitchRange(s: State, ch: number, c: Channel, range: number) if c.pitchRange ~= range then c.pitchRange = range if c.pitchWheel ~= 8192 then @@ -45567,7 +45582,7 @@ end end end -@native local function setSustain(s: State, ch: number, c: Channel, on: boolean) +local function setSustain(s: State, ch: number, c: Channel, on: boolean) if c.sustain == on then return end @@ -45583,7 +45598,7 @@ end end -- channel 9: drums (bank 128) -@native function Synth.program(s: State, ch: number, program: number) +function Synth.program(s: State, ch: number, program: number) local c = s.channels[ch + 1] if not c then return @@ -45612,7 +45627,7 @@ end end end -@native function Synth.pitchBend(s: State, ch: number, value: number) +function Synth.pitchBend(s: State, ch: number, value: number) local c = s.channels[ch + 1] if not c or c.pitchWheel == value then return @@ -45621,7 +45636,7 @@ end applyPitch(s, ch, c) end -@native function Synth.control(s: State, ch: number, cc: number, value: number) +function Synth.control(s: State, ch: number, cc: number, value: number) local c = s.channels[ch + 1] if not c then return @@ -45702,7 +45717,7 @@ end end end -@native function Synth.midi(s: State, status: number, d1: number, d2: number) +function Synth.midi(s: State, status: number, d1: number, d2: number) local kind, ch = status // 16, status % 16 if kind == 9 then Synth.noteOn(s, ch, d1, d2) @@ -45717,7 +45732,7 @@ end end end -@native function Synth.reset(s: State) +function Synth.reset(s: State) for _, v in s.voices do v.preset = -1 end @@ -45729,7 +45744,7 @@ end end end -@native function Synth.active(s: State): number +function Synth.active(s: State): number local n = 0 for _, v in s.voices do if v.preset ~= -1 then @@ -45739,7 +45754,7 @@ end return n end -@native local function voiceRender(s: State, v: Voice, out: buffer, frame: number, numSamples: number) +local function voiceRender(s: State, v: Voice, out: buffer, frame: number, numSamples: number) local region = v.region local input = s.samples local rate = s.rate @@ -45830,7 +45845,7 @@ end v.lpActive, v.z1, v.z2 = lpActive, z1, z2 end -@native function Synth.render(s: State, out: buffer, frame: number, n: number) +function Synth.render(s: State, out: buffer, frame: number, n: number) local room = blen(out) // 8 - frame if frame < 0 or room <= 0 then return @@ -46778,7 +46793,7 @@ end return Load end -__FILES["codecs/audio/Tracker/Mixer"] = @native function() +__FILES["codecs/audio/Tracker/Mixer"] = function() -- codecs/audio/Tracker/Mixer: tracker voice mixing (loops, IT sustain loops, IT two-pole resonant filter, click ramps). @@ -46788,7 +46803,7 @@ local readf32, writef32 = buffer.readf32, buffer.writef32 local Mixer = {} -@native local function mixVoice(v: any, out: buffer?, off: number, n: number, linear: boolean, ramp: number) +local function mixVoice(v: any, out: buffer?, off: number, n: number, linear: boolean, ramp: number) local data: buffer = v.data local nch = v.nch local inc = v.inc @@ -46937,7 +46952,7 @@ local Mixer = {} local _ = ramp end -@native function Mixer.mix(st: any, out: buffer?, off: number, n: number, linear: boolean) +function Mixer.mix(st: any, out: buffer?, off: number, n: number, linear: boolean) for _, v in st.voices do if v.active and v.data then mixVoice(v, out, off, n, linear, 0) @@ -46947,7 +46962,7 @@ end return Mixer end -__FILES["codecs/audio/Tracker/Pcm"] = @native function() +__FILES["codecs/audio/Tracker/Pcm"] = function() -- codecs/audio/Tracker/Pcm: raw 8 / 16-bit tracker sample data (signed / unsigned, XM / IT 2.15 delta coding, @@ -46967,11 +46982,11 @@ type Spec = { bigEndian: boolean?, } -@native function Pcm.bytes(frames: number, spec: Spec): number +function Pcm.bytes(frames: number, spec: Spec): number return frames * (spec.channels or 1) * (spec.bits // 8) end -@native function Pcm.decode(buf: buffer, off: number, frames: number, spec: Spec): buffer? +function Pcm.decode(buf: buffer, off: number, frames: number, spec: Spec): buffer? local nch = spec.channels or 1 local bps = spec.bits // 8 local total = frames * nch @@ -47022,7 +47037,7 @@ end return out end -@native function Pcm.encode(samples: buffer, frames: number, spec: Spec): buffer +function Pcm.encode(samples: buffer, frames: number, spec: Spec): buffer local nch = spec.channels or 1 local bps = spec.bits // 8 local out = buffer.create(frames * nch * bps) @@ -47063,7 +47078,7 @@ end return out end -@native function Pcm.bitsNeeded(samples: buffer): number +function Pcm.bitsNeeded(samples: buffer): number for i = 0, buffer.len(samples) // 4 - 1 do local x = readf32(samples, i * 4) * 128 if x ~= floor(x) then @@ -47075,7 +47090,7 @@ end return Pcm end -__FILES["codecs/audio/Tracker/Player"] = @native function() +__FILES["codecs/audio/Tracker/Player"] = function() -- codecs/audio/Tracker/Player: the tracker sequencer for the MOD, S3M, XM and IT effect families. @@ -47109,7 +47124,7 @@ Player.EXT = EXT local BG_VOICES = 64 -@native local function newVoice(): any +local function newVoice(): any return { active = false, chan = 0, @@ -47174,7 +47189,7 @@ local BG_VOICES = 64 } end -@native local function newChannel(i: number, pan: number, vol: number): any +local function newChannel(i: number, pan: number, vol: number): any return { idx = i, voice = nil :: any, @@ -47262,7 +47277,7 @@ end } end -@native function Player.new(m: any, sampleRate: number, opts: any): any +function Player.new(m: any, sampleRate: number, opts: any): any local fmt = FAMILY[m.engine or m.format] or MOD local flags = m.flags local ptPeriods = fmt == MOD or flags.periods == "amiga" @@ -47339,7 +47354,7 @@ end -- the output scale per format, calibrated against OpenMPT's default mix levels (tools/fixtures: a full-scale sine at -- volume 64 on one centred channel) -@native function Player.masterGain(m: any, fmt: number): number +function Player.masterGain(m: any, fmt: number): number if type(m.preamp) == "number" then return m.preamp / 128 -- OpenMPT's sample pre-amp, as set by the format's loader end @@ -47353,7 +47368,7 @@ end return 2 / clamp(m.channels, 2, 8) end -@native function Player.startOrder(st: any, ord: number, row: number) +function Player.startOrder(st: any, ord: number, row: number) local m = st.m local order = m.order local n = #order @@ -47390,7 +47405,7 @@ end end end -@native local function advanceRow(st: any) +local function advanceRow(st: any) if st.stopAfterRow then st.ended = true return @@ -47422,7 +47437,7 @@ end end end -@native local function notePeriod(st: any, note: number, smp: any, ft: number?): (number, number) +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 base, ref = 8363, 49 @@ -47450,7 +47465,7 @@ end return 1712 * 8363 / base * 2 ^ (plin / 768), base end -@native local function arpPeriod(st: any, period: number, semis: number): number +local function arpPeriod(st: any, period: number, semis: number): number if semis == 0 then return period end @@ -47463,7 +47478,7 @@ end return period * 2 ^ (-semis / 12) end -@native local function clampPeriod(st: any, c: any) +local function clampPeriod(st: any, c: any) if st.hz then c.period = clamp(c.period, 1, 1e6) elseif st.linear then @@ -47476,7 +47491,7 @@ end end -- pitch slides in period units (positive: down; 4 per effect unit); in Hz mode the frequency moves units * hzSlide Hz the other way -@native local function slide(st: any, c: any, units: number) +local function slide(st: any, c: any, units: number) if st.hz then c.period -= units * st.hzScale else @@ -47485,7 +47500,7 @@ end clampPeriod(st, c) end -@native local function allocVoice(st: any): any +local function allocVoice(st: any): any local best, bestScore = nil, math.huge for _, v in st.voices do if not v.active and v.owner == 0 then @@ -47514,7 +47529,7 @@ end return st.voices[1] end -@native local function keyOff(st: any, v: any) +local function keyOff(st: any, v: any) if not v or not v.active then return end @@ -47540,19 +47555,19 @@ end end end -@native local function noteFade(v: any) +local function noteFade(v: any) if v and v.active then v.fading = true end end -@native local function cutVoice(v: any) +local function cutVoice(v: any) if v then v.active = false end end -@native local function startVoice(st: any, c: any, smp: any, smpIdx: number, ins: any, insIdx: number, note: number, period: number, base: number, keepEnv: any) +local function startVoice(st: any, c: any, smp: any, smpIdx: number, ins: any, insIdx: number, note: number, period: number, base: number, keepEnv: any) local v = c.voice if v == nil or v.bg then v = allocVoice(st) @@ -47599,7 +47614,7 @@ end end -- IT new note actions on the channel's current voice (and duplicate checks on all its voices) -@native local function newNoteAction(st: any, c: any, ins: any, insIdx: number, note: number, smpIdx: number) +local function newNoteAction(st: any, c: any, ins: any, insIdx: number, note: number, smpIdx: number) if ins and ins.dct and ins.dct > 0 then for _, u in st.voices do if u.active and u.chan == c.idx and u.insIdx == insIdx then @@ -47640,7 +47655,7 @@ end end end -@native local function isPorta(st: any, fx: number, vcmd: number): boolean +local function isPorta(st: any, fx: number, vcmd: number): boolean local f = st.fmt if f == MOD then return fx == 3 or fx == 5 @@ -47651,7 +47666,7 @@ end return fx == 7 or fx == 12 or (f == IT and vcmd >= 194 and vcmd <= 203) end -@native local function resolve(st: any, insIdx: number, note: number): (any, number, any, number) +local function resolve(st: any, insIdx: number, note: number): (any, number, any, number) local m = st.m if st.insMode then local ins = m.instruments[insIdx] @@ -47667,7 +47682,7 @@ end return smp, insIdx, nil, note end -@native local function setInstrumentDefaults(st: any, c: any, smp: any, ins: any) +local function setInstrumentDefaults(st: any, c: any, smp: any, ins: any) if smp then c.vol = smp.volume end @@ -47694,7 +47709,7 @@ end end end -@native local function sampleOffset(st: any, c: any, v: any) +local function sampleOffset(st: any, c: any, v: any) local f = st.fmt local fx, param = c.fx, c.param local off = -1 @@ -47724,7 +47739,7 @@ end end end -@native local function trigger(st: any, c: any, note: number, insIdx: number, vcmd: number) +local function trigger(st: any, c: any, note: number, insIdx: number, vcmd: number) local f = st.fmt local m = st.m local porta = isPorta(st, c.fx, vcmd) @@ -47857,7 +47872,7 @@ end end end -@native local function volSlideMod(c: any, param: number) +local function volSlideMod(c: any, param: number) local x, y = param // 16, param % 16 if x > 0 then c.vol = min(64, c.vol + x) @@ -47866,7 +47881,7 @@ end end end -@native local function tonePorta(st: any, c: any, speed: number) +local function tonePorta(st: any, c: any, speed: number) if c.period == c.target then return end @@ -47880,17 +47895,17 @@ end end end -@native local function vibrato(st: any, c: any, scale: number) +local function vibrato(st: any, c: any, scale: number) c.vibDelta = wave64(c.vibWave % 4, c.vibPos) * c.vibDepth * scale c.vibPos = (c.vibPos + c.vibSpeed) % 64 end -@native local function tremolo(c: any, scale: number) +local function tremolo(c: any, scale: number) c.tremDelta = floor(wave64(c.tremWave % 4, c.tremPos) * c.tremDepth * scale) c.tremPos = (c.tremPos + c.tremSpeed) % 64 end -@native local function retrigVoice(st: any, c: any) +local function retrigVoice(st: any, c: any) local v = c.voice if v and v.smp then v.active = v.smp.length > 0 @@ -47899,7 +47914,7 @@ end end end -@native local function retrigVolume(c: any, x: number) +local function retrigVolume(c: any, x: number) if x == 0 or x == 8 then return end @@ -47913,7 +47928,7 @@ end end -- S3M / IT D-style slide: fine parts only on tick 0, normal parts on other ticks (fast: normal parts on tick 0 too) -@native local function dSlide(value: number, param: number, tick: number, fast: boolean, hi: number): number +local function dSlide(value: number, param: number, tick: number, fast: boolean, hi: number): number local x, y = param // 16, param % 16 if y == 0xF and x > 0 then if tick == 0 then @@ -47937,7 +47952,7 @@ end return value end -@native local function fxModXm(st: any, c: any, tick: number) +local function fxModXm(st: any, c: any, tick: number) local fx, param = c.fx, c.param local xm = st.fmt == XM local x, y = param // 16, param % 16 @@ -48197,7 +48212,7 @@ end end -- the XM volume column (everything but set volume / set panning, done by trigger) -@native local function volColXm(st: any, c: any, tick: number) +local function volColXm(st: any, c: any, tick: number) local v = c.vcmd if v < 0x60 then return @@ -48251,7 +48266,7 @@ end end -- the parameter after memory: IT keeps one memory per effect group, ST3 one memory for most effects -@native local function mem(st: any, c: any, field: string, param: number): number +local function mem(st: any, c: any, field: string, param: number): number if st.fmt == S3M then if param > 0 then c.mS3M = param @@ -48264,7 +48279,7 @@ end return c[field] end -@native local function portaS3m(st: any, c: any, p: number, tick: number, sign: number) +local function portaS3m(st: any, c: any, p: number, tick: number, sign: number) if p >= 0xF0 then if tick == 0 then slide(st, c, sign * (p % 16) * 4) @@ -48278,7 +48293,7 @@ end end end -@native local function fxS3mIt(st: any, c: any, tick: number) +local function fxS3mIt(st: any, c: any, tick: number) local fx, param = c.fx, c.param local it = st.fmt == IT if fx == 1 then -- A speed @@ -48580,7 +48595,7 @@ end end -- the IT volume column (value stored + 1): slides, portamento, vibrato -@native local function volColIt(st: any, c: any, tick: number) +local function volColIt(st: any, c: any, tick: number) local v = c.vcmd - 1 if v < 65 then return @@ -48657,7 +48672,7 @@ end end end -@native local function fxExt(st: any, c: any, tick: number) +local function fxExt(st: any, c: any, tick: number) local fx, param = c.fx, c.param if fx >= EXT.NOTE_SLIDE_UP and fx <= EXT.NOTE_SLIDE_DOWN_RETRIG then -- note slides (PTM, Oktalyzer): every (param >> 4) ticks by (param & 15) semitones; Oktalyzer (flags.oktSlides): @@ -48715,7 +48730,7 @@ end end end -@native local function noteDelayOf(st: any, fx: number, param: number): number +local function noteDelayOf(st: any, fx: number, param: number): number if (st.fmt == MOD or st.fmt == XM) and fx == 0xE and param // 16 == 0xD then return param % 16 elseif (st.fmt == S3M or st.fmt == IT) and fx == 19 and param // 16 == 0xD then @@ -48724,7 +48739,7 @@ end return 0 end -@native local function finetuneOf(st: any, fx: number, param: number): number? +local function finetuneOf(st: any, fx: number, param: number): number? if (st.fmt == MOD or st.fmt == XM) and fx == 0xE and param // 16 == 5 then local y = param % 16 if st.fmt == MOD then @@ -48735,7 +48750,7 @@ end return nil end -@native local function runEffects(st: any, c: any, tick: number) +local function runEffects(st: any, c: any, tick: number) c.vibDelta, c.arp = 0, 0 if (c.fx >= 0x40 and c.fx < 0x50) or c.autoPorta ~= 0 or c.autoTone then fxExt(st, c, tick) @@ -48771,7 +48786,7 @@ end end end -@native local function processRow(st: any) +local function processRow(st: any) local m = st.m local pat = st.pat local nch = st.nch @@ -48811,7 +48826,7 @@ end local _ = m end -@native local function updateEnvelope(env: any, pos: number, keyOn: boolean, it: boolean): (number, number, boolean) +local function updateEnvelope(env: any, pos: number, keyOn: boolean, it: boolean): (number, number, boolean) local ticks, values = env.ticks, env.values local n = #ticks if n == 0 then @@ -48852,7 +48867,7 @@ end return value, nextPos, ended end -@native local function updateVoice(st: any, v: any) +local function updateVoice(st: any, v: any) local ins = v.ins local it = st.fmt == IT local envVol, envPan, envPitch = 64, 0, 0 @@ -48988,7 +49003,7 @@ end end end -@native function Player.tick(st: any): number +function Player.tick(st: any): number if st.ended then return 0 end @@ -49063,7 +49078,7 @@ end return Player end -__FILES["codecs/audio/Tracker/Tables"] = @native function() +__FILES["codecs/audio/Tracker/Tables"] = function() -- codecs/audio/Tracker/Tables: tracker lookup tables, from the public format documents (ProTracker 2.3 effect docs, @@ -49081,7 +49096,7 @@ do RANDOM[i] = (s // 65536) % 511 - 255 end end -@native function Tables.wave64(kind: number, pos: number): number +function Tables.wave64(kind: number, pos: number): number local p = pos % 64 if kind == 1 then return 255 - p * 8 @@ -49098,7 +49113,7 @@ local SINE256: { number } = {} for i = 0, 255 do SINE256[i + 1] = math.floor(math.sin(i * math.pi / 128) * 64 + 0.5) end -@native function Tables.autoWave(kind: number, pos: number, it: boolean): number +function Tables.autoWave(kind: number, pos: number, it: boolean): number local p = pos % 256 if it then if kind == 1 then @@ -49132,7 +49147,7 @@ local PERIODS = { Tables.PERIODS = PERIODS Tables.PERIOD_FIRST_NOTE = 13 -- PERIODS[1] is note 13 (C-1 in FT2 numbering = ProTracker octave -1) -@native function Tables.periodToNote(period: number): number +function Tables.periodToNote(period: number): number if period <= 0 then return 0 end @@ -49145,7 +49160,7 @@ Tables.PERIOD_FIRST_NOTE = 13 -- PERIODS[1] is note 13 (C-1 in FT2 numbering = P return math.clamp(n, 1, 120) end -@native function Tables.noteToPeriod(note: number): number +function Tables.noteToPeriod(note: number): number local i = note - Tables.PERIOD_FIRST_NOTE + 1 if i >= 1 and i <= #PERIODS then return PERIODS[i] @@ -49167,7 +49182,7 @@ Tables.AMIGA_PAL = 7093789.2 / 2 * 4 -- Scream Tracker 2 tempo byte as OpenMPT plays it (ConvertST2Tempo: ST2's tick length at 23863 Hz, as a fractional BPM) local ST2_FACTOR = { 140, 50, 25, 15, 10, 7, 6, 4, 3, 3, 2, 2, 2, 2, 1, 1 } -@native function Tables.st2Tempo(byte: number): (number, number) +function Tables.st2Tempo(byte: number): (number, number) local hi, lo = byte // 16, byte % 16 local d = 50 - (ST2_FACTOR[hi + 1] * lo) // 16 -- never 0; negative at tempo 06..0F (C integer division truncates) local spt = if d > 0 then 23863 // d else -(23863 // -d) @@ -49296,7 +49311,7 @@ end return Tta end -__FILES["codecs/audio/Tta/Decode"] = @native function() +__FILES["codecs/audio/Tta/Decode"] = function() @@ -49327,7 +49342,7 @@ for b = 0, 255 do ONES[b + 1] = n end -@native local function longUnary(S: buffer, pos: number, lim: number): (number?, number) +local function longUnary(S: buffer, pos: number, lim: number): (number?, number) local unary = 0 while pos <= lim do local w = rshift(readu32(S, rshift(pos, 3)), band(pos, 7)) @@ -49354,7 +49369,7 @@ type State = { cur: { number }, } -@native function Decode.state(channels: number, bytes: number): State +function Decode.state(channels: number, bytes: number): State return { channels = channels, bytes = bytes, @@ -49369,7 +49384,7 @@ type State = { } end -@native function Decode.frame(st: State, buf: buffer, o: number, len: number, n: number, P: { number }): (number?, string?) +function Decode.frame(st: State, buf: buffer, o: number, len: number, n: number, P: { number }): (number?, string?) if len < 4 then return nil, "truncated frame" end @@ -49561,7 +49576,7 @@ local Vorbis = { return Vorbis end -__FILES["codecs/audio/Vorbis/Codebook"] = @native function() +__FILES["codecs/audio/Vorbis/Codebook"] = function() @@ -49588,11 +49603,11 @@ type Br = { eop: boolean, } -@native function Codebook.reader(buf: buffer, offset: number, size: number): Br +function Codebook.reader(buf: buffer, offset: number, size: number): Br return { buf = buf, pos = offset, limit = offset + size, acc = 0, cnt = 0, pad = 0, eop = false } end -@native local function bits(br: Br, n: number): number +local function bits(br: Br, n: number): number if n == 0 then return 0 end @@ -49624,7 +49639,7 @@ end Codebook.bits = bits -- ilog (spec 9.2.1) -@native local function ilog(x: number): number +local function ilog(x: number): number local n = 0 while x > 0 do n += 1 @@ -49635,7 +49650,7 @@ end Codebook.ilog = ilog -- float32_unpack (spec 9.2.2) -@native local function float32Unpack(x: number): number +local function float32Unpack(x: number): number local mantissa = x % 2097152 local sign = x >= 2147483648 local exp = floor((x % 2147483648) / 2097152) @@ -49660,7 +49675,7 @@ local MAX_ENTRIES = 2 ^ 20 local MAX_VQ = 2 ^ 22 -- lookup1_values(entries, dims): the largest r with r^dims <= entries -@native local function lookup1Values(entries: number, dims: number): number +local function lookup1Values(entries: number, dims: number): number local r = floor(math.exp(math.log(entries) / dims)) if floor((r + 1) ^ dims) <= entries then r += 1 @@ -49675,7 +49690,7 @@ local MAX_VQ = 2 ^ 22 end -- assign codewords (spec 3.2.1: in entry order, the lowest free leaf) and build the decode tree + fast table -@native local function build(book: Book, lengths: { number }): string? +local function build(book: Book, lengths: { number }): string? local n = book.entries local c0, c1 = book.c0, book.c1 local nodes = 1 @@ -49771,7 +49786,7 @@ end return nil end -@native function Codebook.read(br: Br): (Book?, string?) +function Codebook.read(br: Br): (Book?, string?) if bits(br, 24) ~= 0x564342 then return nil, "bad codebook sync" end @@ -49890,7 +49905,7 @@ end return book, nil end -@native local function decode(br: Br, book: Book): number +local function decode(br: Br, book: Book): number local fb = book.fastBits local acc, cnt = br.acc, br.cnt if cnt < fb then @@ -49945,7 +49960,7 @@ Codebook.decode = decode return Codebook end -__FILES["codecs/audio/Vorbis/Packet"] = @native function() +__FILES["codecs/audio/Vorbis/Packet"] = function() @@ -49986,7 +50001,7 @@ type State = { partClass: { { { number } } }, } -@native function Packet.new(id: Setup.Ident, setup: Setup.Setup): State? +function Packet.new(id: Setup.Ident, setup: Setup.Setup): State? local n0, n1, ch = id.blocksize0, id.blocksize1, id.channels local plans: { [number]: Mdct.Plan } = {} local slopes: { [number]: { number } } = {} @@ -50003,7 +50018,7 @@ type State = { end slopes[n // 2] = half end - @native local function arrays(len: number): { { number } } + local function arrays(len: number): { { number } } local t = table.create(ch) for c = 1, ch do t[c] = table.create(len, 0) @@ -50036,12 +50051,12 @@ type State = { } end -@native function Packet.reset(st: State) +function Packet.reset(st: State) st.prevN = 0 st.tailLen = 0 end -@native function Packet.blocksize(st: State, b: buffer, off: number, size: number): number +function Packet.blocksize(st: State, b: buffer, off: number, size: number): number if size < 1 then return 0 end @@ -50057,7 +50072,7 @@ end return if mode.blockflag == 1 then st.n1 else st.n0 end -@native local function predict(x: number, x0: number, x1: number, y0: number, y1: number): number +local function predict(x: number, x0: number, x1: number, y0: number, y1: number): number local dy = y1 - y0 local adx = x1 - x0 local off = ((if dy < 0 then -dy else dy) * (x - x0)) // adx @@ -50065,7 +50080,7 @@ end end -- multiply out[x0 .. x1) by the floor line from (x0, y0) to (x1, y1) (stb draw_line) -@native local function drawLine(out: { number }, x0: number, y0: number, x1: number, y1: number, n: number) +local function drawLine(out: { number }, x0: number, y0: number, x1: number, y1: number, n: number) local dy = y1 - y0 local adx = x1 - x0 local ady = if dy < 0 then -dy else dy @@ -50093,7 +50108,7 @@ end end end -@native local function floorDecode(st: State, br: Codebook.Br, g: Setup.Floor1, finalY: { number }): boolean +local function floorDecode(st: State, br: Codebook.Br, g: Setup.Floor1, finalY: { number }): boolean if bits(br, 1) == 0 then return false end @@ -50172,7 +50187,7 @@ end end -- multiply target[1 .. n2] by the floor curve (stb do_floor) -@native local function floorCurve(g: Setup.Floor1, finalY: { number }, target: { number }, n2: number) +local function floorCurve(g: Setup.Floor1, finalY: { number }, target: { number }, n2: number) local mult = g.multiplier local lx, ly = 0, finalY[1] * mult local sorted, xl = g.sorted, g.xlist @@ -50196,7 +50211,7 @@ end end end -@native local function partition(br: Codebook.Br, book: Codebook.Book, target: { number }, offset: number, psize: number, rtype: number, limit: number): boolean +local function partition(br: Codebook.Br, book: Codebook.Book, target: { number }, offset: number, psize: number, rtype: number, limit: number): boolean local vq = book.vq if not vq then br.eop = true -- a scalar book in a vector context: invalid stream @@ -50239,7 +50254,7 @@ end return true end -@native local function residue(st: State, br: Codebook.Br, r: Setup.Residue, targets: { { number } | false }, ch: number, n2: number) +local function residue(st: State, br: Codebook.Br, r: Setup.Residue, targets: { { number } | false }, ch: number, n2: number) local books = st.setup.books local rtype = r.type local cbook = books[r.classbook + 1] @@ -50361,7 +50376,7 @@ end end end -@native function Packet.decode(st: State, b: buffer, off: number, size: number): number +function Packet.decode(st: State, b: buffer, off: number, size: number): number if size < 1 then return -1 end @@ -50511,7 +50526,7 @@ end return Packet end -__FILES["codecs/audio/Vorbis/Setup"] = @native function() +__FILES["codecs/audio/Vorbis/Setup"] = function() -- codecs/audio/Vorbis/Setup: the three Vorbis header packets (Vorbis I spec section 4.2). @@ -50582,12 +50597,12 @@ type Setup = { maxFloorValues: number, } -@native local function isVorbis(b: buffer, o: number, n: number, kind: number): boolean +local function isVorbis(b: buffer, o: number, n: number, kind: number): boolean return n >= 7 and readu8(b, o) == kind and buffer.readstring(b, o + 1, 6) == "vorbis" end Setup.isVorbis = isVorbis -@native function Setup.ident(b: buffer, o: number, n: number): (Ident?, string?) +function Setup.ident(b: buffer, o: number, n: number): (Ident?, string?) if not isVorbis(b, o, n, 1) then return nil, "not a Vorbis identification header" end @@ -50622,7 +50637,7 @@ Setup.isVorbis = isVorbis nil end -@native function Setup.comment(b: buffer, o: number, n: number): (string?, { string }?) +function Setup.comment(b: buffer, o: number, n: number): (string?, { string }?) if not isVorbis(b, o, n, 3) then return nil, nil end @@ -50658,7 +50673,7 @@ end return vendor, list end -@native function Setup.setup(b: buffer, o: number, n: number, id: Ident): (Setup?, string?) +function Setup.setup(b: buffer, o: number, n: number, id: Ident): (Setup?, string?) if not isVorbis(b, o, n, 5) then return nil, "not a Vorbis setup header" end @@ -50739,7 +50754,7 @@ end for j = 1, values do order[j] = j - 1 end - table.sort(order, @native function(a: number, c: number): boolean + table.sort(order, function(a: number, c: number): boolean return xlist[a + 1] < xlist[c + 1] end) for j = 1, values - 1 do @@ -51245,7 +51260,7 @@ WavPack.meta = Block.meta return WavPack end -__FILES["codecs/audio/WavPack/Block"] = @native function() +__FILES["codecs/audio/WavPack/Block"] = function() @@ -51286,7 +51301,7 @@ local D2, D1 = 17, 9 -- the first data index of the work table (stereo / mono): type Meta = { [number]: number } -- id -> offset; id + 256 -> byte length -@native function Block.meta(buf: buffer, p: number, size: number): (Meta?, string?) +function Block.meta(buf: buffer, p: number, size: number): (Meta?, string?) local m: Meta = {} local q, stop = p + 32, p + size while stop - q >= 2 do @@ -51320,7 +51335,7 @@ type Meta = { [number]: number } -- id -> offset; id + 256 -> byte length return m, nil end -@native function Block.checksum(buf: buffer, p: number, m: Meta): boolean +function Block.checksum(buf: buffer, p: number, m: Meta): boolean local o = m[0x2F] if not o then return true @@ -51344,7 +51359,7 @@ end type Reader = { b: buffer, p: number, e: number, n: number } type State = { [string]: any } -@native function Block.state(): State +function Block.state(): State return { W = table.create(D2 + 2 * 4096, 0), term = table.create(16, 0), @@ -51368,7 +51383,7 @@ type State = { [string]: any } } end -@native local function openReader(R: Reader, buf: buffer, o: number, len: number) +local function openReader(R: Reader, buf: buffer, o: number, len: number) if buffer.len(R.b) < len + PAD then R.b = buffer.create(len + PAD + 1024) else @@ -51380,7 +51395,7 @@ end R.n = len + PAD end -@native local function bits(R: Reader, n: number): number +local function bits(R: Reader, n: number): number if n <= 0 then return 0 end @@ -51401,11 +51416,11 @@ end return lo + band(rshift(readu32(b, rshift(p, 3)), band(p, 7)), P2[n - 15] - 1) * 65536 end -@native local function bit(R: Reader): number +local function bit(R: Reader): number return bits(R, 1) end -@native local function trailing(R: Reader, max: number): number +local function trailing(R: Reader, max: number): number local c = 0 while c < max do local p = R.p @@ -51431,7 +51446,7 @@ end end -- the "Elias gamma"-like count (cbits ones, a zero, cbits - 1 bits) -> value | nil (33 ones) -@native local function gamma(R: Reader): number? +local function gamma(R: Reader): number? local c = trailing(R, 33) if c == 33 then return nil @@ -51443,7 +51458,7 @@ end end -- read_code -@native local function readCode(R: Reader, maxcode: number): number +local function readCode(R: Reader, maxcode: number): number if maxcode < 2 then return if maxcode == 1 then bits(R, 1) else 0 end @@ -51457,7 +51472,7 @@ end end -- ones(R) -> the unary count with its escape (LIMIT_ONES = 16) | nil (the end marker) -@native local function onesCount(R: Reader): number? +local function onesCount(R: Reader): number? local c = trailing(R, 17) if c == 17 then return nil @@ -51473,7 +51488,7 @@ end end -- get_words_lossless -@native local function wordsLossless(st: State, count: number, d: number): boolean +local function wordsLossless(st: State, count: number, d: number): boolean local R: Reader = st.R1 local b, pos, lim = R.b, R.p, R.e local W = st.W @@ -51637,7 +51652,7 @@ end return pos <= lim end -@native local function updateErrorLimit(st: State, flags: number, mono: boolean) +local function updateErrorLimit(st: State, flags: number, mono: boolean) local bacc, bdelta, slow, limit = st.bacc, st.bdelta, st.slow, st.limit bacc[1] = (bacc[1] + bdelta[1]) % TWO32 local br0 = bacc[1] // 65536 @@ -51677,7 +51692,7 @@ end end -- get_word -@native local function getWord(st: State, chan: number, flags: number, mono: boolean): (number?, number) +local function getWord(st: State, chan: number, flags: number, mono: boolean): (number?, number) local R: Reader = st.R1 local med = st.med local mb = chan * 3 @@ -51793,7 +51808,7 @@ end end -- the decorrelation passes over the whole block (stereo, from W[D2]): unpack.c decorr_stereo_pass -@native local function passesStereo(st: State, n: number) +local function passesStereo(st: State, n: number) local W = st.W local last = D2 + 2 * n - 2 local terms, deltas, wAs, wBs, sA, sB = st.term, st.delta, st.wA, st.wB, st.sA, st.sB @@ -51874,7 +51889,7 @@ end end -- the decorrelation passes (mono, from W[D1]): unpack.c decorr_mono_pass -@native local function passesMono(st: State, n: number) +local function passesMono(st: State, n: number) local W = st.W local last = D1 + n - 1 local terms, deltas, wAs, sA = st.term, st.delta, st.wA, st.sA @@ -51906,7 +51921,7 @@ end end end -@native local function shaped(st: State, c: number, flags: number, correction: number): number +local function shaped(st: State, c: number, flags: number, correction: number): number -- returns the value to subtract (temp) and updates the error state (noise shaping, unpack.c) local sacc, sdelta, err = st.sacc, st.sdelta, st.err sacc[c] = (sacc[c] + sdelta[c]) % TWO32 @@ -51926,7 +51941,7 @@ end return temp end -@native local function hybridMono(st: State, n: number, flags: number): boolean +local function hybridMono(st: State, n: number, flags: number): boolean local W = st.W local terms, deltas, wAs, sA = st.term, st.delta, st.wA, st.sA local nterms = st.nterms @@ -51968,7 +51983,7 @@ end return true end -@native local function hybridStereo(st: State, n: number, flags: number): boolean +local function hybridStereo(st: State, n: number, flags: number): boolean local W = st.W local terms, deltas, wAs, wBs, sA, sB = st.term, st.delta, st.wA, st.wB, st.sA, st.sB local nterms = st.nterms @@ -52098,7 +52113,7 @@ end return true end -@native local function readMeta(st: State, buf: buffer, m: Meta, flags: number, version: number): string? +local function readMeta(st: State, buf: buffer, m: Meta, flags: number, version: number): string? local mono = band(flags, MONO_FLAG + FALSE_STEREO) ~= 0 local o = m[2] if o then -- decorrelation terms @@ -52284,7 +52299,7 @@ end end -- float_values (R = the wvx stream or nil) -@native local function floatValue(st: State, v: number, R: Reader?): number +local function floatValue(st: State, v: number, R: Reader?): number local fflags, exp = st.fflags, st.fmaxexp local mant, e, sign = 0, 0, 0 if v == 0 then @@ -52385,7 +52400,7 @@ end end -- fixup_samples + false stereo + interleave -@native local function emit(st: State, flags: number, n: number, d: number, P: { number }, c0: number, C: number, lossy: boolean) +local function emit(st: State, flags: number, n: number, d: number, P: { number }, c0: number, C: number, lossy: boolean) local W = st.W local s = if d == D2 then 2 else 1 local count = n * s @@ -52519,7 +52534,7 @@ end end end -@native function Block.decode(st: State, buf: buffer, p: number, size: number, P: { number }, c0: number, C: number, cbuf: buffer?, cp: number?, csize: number?): (number?, string?) +function Block.decode(st: State, buf: buffer, p: number, size: number, P: { number }, c0: number, C: number, cbuf: buffer?, cp: number?, csize: number?): (number?, string?) local version = readu16(buf, p + 8) local n = readu32(buf, p + 20) local flags = readu32(buf, p + 24) @@ -52700,7 +52715,7 @@ Block.bit = bit return Block end -__FILES["codecs/audio/WavPack/Tables"] = @native function() +__FILES["codecs/audio/WavPack/Tables"] = function() @@ -52731,7 +52746,7 @@ local EXP2: { number } = { 214, 215, 216, 217, 219, 220, 221, 222, 224, 225, 226, 228, 229, 230, 232, 233, 234, 236, 237, 238, 240, 241, 242, 244, 245, 246, 248, 249, 250, 252, 253, 255, } -@native function Tables.exp2s(lg: number): number +function Tables.exp2s(lg: number): number if lg < 0 then local v = Tables.exp2s(-lg) v = -(if v >= 2147483648 then v - 4294967296 else v) @@ -52743,7 +52758,7 @@ local EXP2: { number } = { return if r >= 2147483648 then r - 4294967296 else r end -@native function Tables.log2(v: number): number +function Tables.log2(v: number): number v = (v + rshift(v, 9)) % 4294967296 if v < 256 then local dbits = 32 - countlz(v) @@ -52753,7 +52768,7 @@ end return dbits * 256 + LOG2[band(rshift(v, dbits - 9), 255) + 1] end -@native function Tables.restoreWeight(w: number): number +function Tables.restoreWeight(w: number): number local r = w * 8 if r > 0 then r += (r + 64) // 128 @@ -52850,7 +52865,7 @@ end return Brotli end -__FILES["codecs/compress/Brotli/Decode"] = @native function() +__FILES["codecs/compress/Brotli/Decode"] = function() @@ -52906,7 +52921,7 @@ for i = 0, 255 do end writeu8(REV8, i, r) end -@native local function reverse(code: number, len: number): number +local function reverse(code: number, len: number): number local r = readu8(REV8, band(code, 255)) * 256 + readu8(REV8, band(rshift(code, 8), 255)) return rshift(r, 16 - len) end @@ -52916,7 +52931,7 @@ local nextc = table.create(16, 0) local subBits = table.create(256, 0) local subOff = table.create(256, 0) -@native local function prepare(lens: buffer, n: number): number +local function prepare(lens: buffer, n: number): number for l = 1, 16 do count[l] = 0 end @@ -52973,7 +52988,7 @@ local subOff = table.create(256, 0) return size end -@native local function build(lens: buffer, n: number, T: buffer, at: number) +local function build(lens: buffer, n: number, T: buffer, at: number) local single = -1 local used = 0 for s = 0, n - 1 do @@ -53026,7 +53041,7 @@ end end -- largest distance alphabet under MAX_ALLOWED_DISTANCE, as the reference's BrotliCalculateDistanceCodeLimit -@native local function distanceLimit(maxDistance: number, npostfix: number, ndirect: number): number +local function distanceLimit(maxDistance: number, npostfix: number, ndirect: number): number if maxDistance <= ndirect then return maxDistance + 16 end @@ -53049,12 +53064,12 @@ end return bor(lshift(group, npostfix), postfix) + ndirect + 16 + 1 end -@native function Decode.decompress(src: buffer, off: number, len: number, maxBytes: number, S: Static, largeWindow: boolean): (buffer?, any, number?) +function Decode.decompress(src: buffer, off: number, len: number, maxBytes: number, S: Static, largeWindow: boolean): (buffer?, any, number?) local lim = off + len local ip = off local bb, bc = 0, 0 - @native local function fill() + local function fill() while bc <= 24 do local byte = 0 if ip < lim then @@ -53065,7 +53080,7 @@ end bc += 8 end end - @native local function bits(n: number): number + local function bits(n: number): number if bc < n then fill() end @@ -53074,14 +53089,14 @@ end bc -= n return v end - @native local function bitsLong(n: number): number + local function bitsLong(n: number): number if n <= 24 then return bits(n) end local lo = bits(16) return lo + bits(n - 16) * 65536 end - @native local function overrun(): boolean + local function overrun(): boolean return (ip - lim) * 8 > bc end @@ -53091,7 +53106,7 @@ end local CLL = bcreate(18) local CLT = bcreate(256 * 4) - @native local function decodeSym(base: number): number + local function decodeSym(base: number): number if bc < 15 then fill() end @@ -53106,7 +53121,7 @@ end return rshift(e, 5) end - @native local function install(n: number): number + local function install(n: number): number local size = prepare(LENS, n) if size < 0 then return -1 @@ -53123,7 +53138,7 @@ end return base end - @native local function readCode(alphabetMax: number, limit: number): number + local function readCode(alphabetMax: number, limit: number): number bfill(LENS, 0, 0, limit) local hskip = bits(2) if hskip == 1 then @@ -53262,7 +53277,7 @@ end return install(limit) end - @native local function varLen8(): number + local function varLen8(): number if bits(1) == 0 then return 0 end @@ -53273,12 +53288,12 @@ end return bits(n) + lshift(1, n) end - @native local function blockLen(base: number): number + local function blockLen(base: number): number local code = decodeSym(base) return BL_OFF[code + 1] + bits(BL_BITS[code + 1]) end - @native local function readContextMap(size: number): (number, buffer) + local function readContextMap(size: number): (number, buffer) local ntrees = varLen8() + 1 local map = bcreate(size) if ntrees < 2 then @@ -54735,7 +54750,7 @@ end return Bzip2 end -__FILES["codecs/compress/Bzip2/Decode"] = @native function() +__FILES["codecs/compress/Bzip2/Decode"] = function() @@ -54775,7 +54790,7 @@ local CFTAB = table.create(257, 0) local MTF = table.create(256, 0) local SEQ = table.create(256, 0) -@native local function buildGroup(g: number, n: number): boolean +local function buildGroup(g: number, n: number): boolean local lbase = g * MAXALPHA local cbase = g * (MAXLEN + 1) for l = 0, MAXLEN do @@ -54828,13 +54843,13 @@ local SEQ = table.create(256, 0) return true end -@native local function grow(out: buffer, op: number, need: number): buffer +local function grow(out: buffer, op: number, need: number): buffer local nb = bcreate(math.max(blen(out) * 2, need, 65536)) bcopy(nb, 0, out, 0, op) return nb end -@native function Decode.decode(b: buffer, o: number, e: number, maxBytes: number): (buffer?, any, any) +function Decode.decode(b: buffer, o: number, e: number, maxBytes: number): (buffer?, any, any) local out = bcreate(math.min(math.max(65536, (e - o) * 4), maxBytes + 1)) local op = 0 local p = o @@ -55577,7 +55592,7 @@ end return Deflate end -__FILES["codecs/compress/Deflate/Compress"] = @native function() +__FILES["codecs/compress/Deflate/Compress"] = function() @@ -55633,7 +55648,7 @@ for c = 1, 30 do end end end -@native local function dcode(d: number): number +local function dcode(d: number): number if d <= 256 then return DSMALL[d] end @@ -55648,7 +55663,7 @@ for i = 1, 288 do end local FIXDLEN = table.create(30, 5) -@native local function revCodes(lens: { number }): { number } +local function revCodes(lens: { number }): { number } local codes = Huffman.codes(lens) for i, l in lens do if l > 0 then @@ -55667,7 +55682,7 @@ end type Out = { buf: buffer, op: number, acc: number, cnt: number } -@native local function ensure(o: Out, n: number) +local function ensure(o: Out, n: number) if o.op + n > blen(o.buf) then local nb = bcreate(math.max(blen(o.buf) * 2, o.op + n)) bcopy(nb, 0, o.buf, 0, o.op) @@ -55675,7 +55690,7 @@ type Out = { buf: buffer, op: number, acc: number, cnt: number } end end -@native local function put(o: Out, v: number, n: number) +local function put(o: Out, v: number, n: number) local acc = o.acc + v * POW[o.cnt + 1] local cnt = o.cnt + n if cnt >= 8 then @@ -55693,13 +55708,13 @@ end o.acc, o.cnt = acc, cnt end -@native local function alignOut(o: Out) +local function alignOut(o: Out) if o.cnt > 0 then put(o, 0, 8 - o.cnt) end end -@native local function storedBlock(o: Out, src: buffer, s: number, e: number, final: boolean) +local function storedBlock(o: Out, src: buffer, s: number, e: number, final: boolean) local p = s repeat local n = math.min(65535, e - p) @@ -55715,7 +55730,7 @@ end until p >= e end -@native local function emitSymbols(o: Out, L: { number }, D: { number }, nsym: number, lcode: { number }, llen: { number }, dcodes: { number }, dlen: { number }) +local function emitSymbols(o: Out, L: { number }, D: { number }, nsym: number, lcode: { number }, llen: { number }, dcodes: { number }, dlen: { number }) for i = 1, nsym do local l = L[i] if l < 256 then @@ -55740,7 +55755,7 @@ end put(o, lcode[257], llen[257]) -- end of block end -@native local function block(o: Out, src: buffer, s: number, e: number, L: { number }, D: { number }, nsym: number, final: boolean) +local function block(o: Out, src: buffer, s: number, e: number, L: { number }, D: { number }, nsym: number, final: boolean) local lf = table.create(286, 0) local df = table.create(30, 0) local extra = 0 @@ -55870,7 +55885,7 @@ end local Compress = {} -@native function Compress.raw(src: buffer, off: number, len: number, level: number): buffer +function Compress.raw(src: buffer, off: number, len: number, level: number): buffer local o: Out = { buf = bcreate(math.max(64, len // 2 + 64)), op = 0, acc = 0, cnt = 0 } local e = off + len if level == 0 or len == 0 then @@ -55896,15 +55911,15 @@ local Compress = {} local nsym = 0 local blockStart = off - @native local function hash(p: number): number + local function hash(p: number): number return ((readu8(src, p) * 251 + readu8(src, p + 1)) * 251 + readu8(src, p + 2)) % HSIZE end - @native local function insert(p: number) + local function insert(p: number) local h = hash(p) + 1 prev[p % WSIZE + 1] = head[h] head[h] = p end - @native local function find(p: number, steps: number): (number, number) + local function find(p: number, steps: number): (number, number) local maxLen = math.min(MAXMATCH, e - p) if maxLen < 3 then return 0, 0 @@ -55937,7 +55952,7 @@ local Compress = {} end return best, bestDist end - @native local function flush(upto: number, final: boolean) + local function flush(upto: number, final: boolean) block(o, src, blockStart, upto, L, D, nsym, final) nsym = 0 blockStart = upto @@ -55997,7 +56012,7 @@ end return Compress end -__FILES["codecs/compress/Deflate/Inflate"] = @native function() +__FILES["codecs/compress/Deflate/Inflate"] = function() @@ -56043,14 +56058,14 @@ end local Inflate = {} -@native local function grow(out: buffer, op: number, need: number): (buffer, number) +local function grow(out: buffer, op: number, need: number): (buffer, number) local cap = math.max(blen(out) * 2, need, 1024) local nb = bcreate(cap) bcopy(nb, 0, out, 0, op) return nb, cap end -@native function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, exact: boolean, prefix: boolean?, dict: buffer?): (buffer?, any, number?) +function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, exact: boolean, prefix: boolean?, dict: buffer?): (buffer?, any, number?) local op = 0 if dict then op = blen(dict) @@ -56432,7 +56447,7 @@ end return Inflate end -__FILES["codecs/compress/Explode"] = @native function() +__FILES["codecs/compress/Explode"] = function() @@ -56460,7 +56475,7 @@ local EXTRA = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8 } type Code = { count: { number }, symbol: { number } } -@native local function construct(rep: { number }): Code +local function construct(rep: { number }): Code local lengths: { number } = {} for _, b in rep do local len = b % 16 @@ -56490,7 +56505,7 @@ local LIT = construct(LITLEN) local LEN = construct(LENLEN) local DIST = construct(DISTLEN) -@native function Explode.decompress(buf: buffer | string, offset: number?, length: number?, maxOut: number?): (buffer?, Err.Err?) +function Explode.decompress(buf: buffer | string, offset: number?, length: number?, maxOut: number?): (buffer?, Err.Err?) local b, o, l, aerr = Bytes.span("Explode.decompress", buf, offset, length) if not b then return nil, aerr @@ -56515,7 +56530,7 @@ local DIST = construct(DISTLEN) local bitbuf, bitcnt = 0, 0 local truncated = false - @native local function bits(need: number): number + local function bits(need: number): number while bitcnt < need do if p >= stop then truncated = true @@ -56531,7 +56546,7 @@ local DIST = construct(DISTLEN) return v end - @native local function decode(h: Code): number + local function decode(h: Code): number local code, first, index = 0, 0, 0 local count, symbol = h.count, h.symbol for len = 1, MAXBITS do @@ -56628,7 +56643,7 @@ end return Explode end -__FILES["codecs/compress/Lz4"] = @native function() +__FILES["codecs/compress/Lz4"] = function() @@ -56653,7 +56668,7 @@ local MAX_OFFSET = 65535 local HASH_BITS = 13 local HASH_SIZE = 2 ^ HASH_BITS -@native function Lz4.decodeInto(src: buffer, p: number, limit: number, dst: buffer, d: number, dstLimit: number, histStart: number?): (number?, string?) +function Lz4.decodeInto(src: buffer, p: number, limit: number, dst: buffer, d: number, dstLimit: number, histStart: number?): (number?, string?) local lo = histStart or d if limit > blen(src) or dstLimit > blen(dst) or p < 0 or d < 0 or lo < 0 or lo > d then return nil, "corrupt: bad ranges" @@ -56739,7 +56754,7 @@ local HASH_SIZE = 2 ^ HASH_BITS end end -@native function Lz4.decompress(src: buffer | string, offset: number?, length: number?, outSize: number?, opts: Options?): (buffer?, Err.Err?) +function Lz4.decompress(src: buffer | string, offset: number?, length: number?, outSize: number?, opts: Options?): (buffer?, Err.Err?) local b, o, l, aerr = Bytes.span("Lz4.decompress", src, offset, length) if not b then return nil, aerr @@ -56778,11 +56793,11 @@ end end end -@native function Lz4.bound(n: number): number +function Lz4.bound(n: number): number return n + n // 255 + 16 end -@native local function extend(dst: buffer, o: number, n: number): number +local function extend(dst: buffer, o: number, n: number): number while n >= 255 do writeu8(dst, o, 255) o += 1 @@ -56793,7 +56808,7 @@ end end -- Knuth's multiplicative hash (v * 2654435761 mod 2^32, top bits), exact in doubles -@native local function hash(v: number): number +local function hash(v: number): number local vl, vh = band(v, 0xFFFF), rshift(v, 16) local mid = (vh * 0x79B1 + vl * 0x9E37) % 65536 return ((vl * 0x79B1 + mid * 65536) % 4294967296) // (2 ^ (32 - HASH_BITS)) + 1 @@ -56801,7 +56816,7 @@ end local hashTable: { number } = table.create(HASH_SIZE, -1e9) -@native function Lz4.encodeInto(src: buffer, p: number, n: number, dst: buffer, d: number): number +function Lz4.encodeInto(src: buffer, p: number, n: number, dst: buffer, d: number): number local op = d local anchor = p local iend = p + n @@ -56883,7 +56898,7 @@ local hashTable: { number } = table.create(HASH_SIZE, -1e9) return op - d end -@native function Lz4.compress(src: buffer | string, offset: number?, length: number?): (buffer?, Err.Err?) +function Lz4.compress(src: buffer | string, offset: number?, length: number?): (buffer?, Err.Err?) local b, o, l, aerr = Bytes.span("Lz4.compress", src, offset, length) if not b then return nil, aerr @@ -56897,7 +56912,7 @@ end return Lz4 end -__FILES["codecs/compress/Lzh"] = @native function() +__FILES["codecs/compress/Lzh"] = function() @@ -56914,11 +56929,11 @@ local floor = math.floor type Reader = { src: buffer, pos: number, limit: number, acc: number, cnt: number, over: number } -@native local function reader(src: buffer, off: number, len: number): Reader +local function reader(src: buffer, off: number, len: number): Reader return { src = src, pos = off, limit = math.min(off + len, buffer.len(src)), acc = 0, cnt = 0, over = 0 } end -@native local function fill(r: Reader) +local function fill(r: Reader) while r.cnt <= 24 do local b = 0 if r.pos < r.limit then @@ -56932,14 +56947,14 @@ end end end -@native local function peek(r: Reader, n: number): number +local function peek(r: Reader, n: number): number if r.cnt < n then fill(r) end return floor(r.acc / 2 ^ (r.cnt - n)) % 2 ^ n end -@native local function skip(r: Reader, n: number) +local function skip(r: Reader, n: number) if r.cnt < n then fill(r) end @@ -56947,7 +56962,7 @@ end r.acc = r.acc % 2 ^ r.cnt end -@native local function bits(r: Reader, n: number): number +local function bits(r: Reader, n: number): number if n == 0 then return 0 end @@ -56958,11 +56973,11 @@ end type Table = { tab: buffer, P: number, S: number, single: number } -@native local function newTable(nsym: number, P: number): Table +local function newTable(nsym: number, P: number): Table return { tab = buffer.create(Huffman.capacity(nsym, P, 16) * 4), P = P, S = 0, single = -1 } end -@native local function build(t: Table, lens: buffer, n: number): boolean +local function build(t: Table, lens: buffer, n: number): boolean t.single = -1 local S = Huffman.buildMsb(lens, 0, n, t.tab, t.P) if S < 0 then @@ -56972,7 +56987,7 @@ end return true end -@native local function decodeSym(r: Reader, t: Table): number +local function decodeSym(r: Reader, t: Table): number if t.single >= 0 then return t.single end @@ -56996,7 +57011,7 @@ end local lens = buffer.create(512) -@native local function lengthValue(r: Reader): number +local function lengthValue(r: Reader): number local len = bits(r, 3) if len == 7 then while bits(r, 1) == 1 do @@ -57010,7 +57025,7 @@ local lens = buffer.create(512) end -- the temp (code-length code) table and the offset table share this layout; special = 2 for the temp table -@native local function readLengths(r: Reader, t: Table, nbits: number, maxN: number, special: number): boolean +local function readLengths(r: Reader, t: Table, nbits: number, maxN: number, special: number): boolean local n = bits(r, nbits) if n == 0 then t.single = bits(r, nbits) @@ -57034,7 +57049,7 @@ end return build(t, lens, math.min(i, maxN)) end -@native local function readCodes(r: Reader, temp: Table, codes: Table): boolean +local function readCodes(r: Reader, temp: Table, codes: Table): boolean local n = bits(r, 9) if n == 0 then codes.single = bits(r, 9) @@ -57064,7 +57079,7 @@ end local OFFSET_BITS = { lh4 = 4, lh5 = 4, lh6 = 5, lh7 = 5, lhx = 5 } -@native local function decodeNew(src: buffer, off: number, len: number, out: buffer, n: number, method: string): string? +local function decodeNew(src: buffer, off: number, len: number, out: buffer, n: number, method: string): string? local r = reader(src, off, len) local obits = OFFSET_BITS[method] local temp, codes, offs = newTable(19, 8), newTable(510, 10), newTable(32, 8) @@ -57140,7 +57155,7 @@ do end end -@native local function decodeLh1(src: buffer, off: number, len: number, out: buffer, n: number): string? +local function decodeLh1(src: buffer, off: number, len: number, out: buffer, n: number): string? local r = reader(src, off, len) local leaf = table.create(NUM_NODES, false) local child = table.create(NUM_NODES, 0) @@ -57151,18 +57166,18 @@ end local groups = table.create(NUM_NODES, 0) local leader = table.create(NUM_NODES, 0) local numGroups = 0 - @native local function initGroups() + local function initGroups() for i = 0, NUM_NODES - 1 do groups[i + 1] = i end numGroups = 0 end - @native local function allocGroup(): number + local function allocGroup(): number local g = groups[numGroups + 1] numGroups += 1 return g end - @native local function freeGroup(g: number) + local function freeGroup(g: number) numGroups -= 1 groups[numGroups + 1] = g end @@ -57191,7 +57206,7 @@ end c -= 2 end end - @native local function makeLeader(ni: number): number + local function makeLeader(ni: number): number local g = group[ni + 1] local li = leader[g + 1] if li == ni then @@ -57209,7 +57224,7 @@ end end return li end - @native local function incrementNode(ni: number) + local function incrementNode(ni: number) freq[ni + 1] += 1 if ni < NUM_NODES - 1 and group[ni + 1] == group[ni + 2] then leader[group[ni + 1] + 1] += 1 @@ -57224,7 +57239,7 @@ end group[ni + 1] = group[ni] end end - @native local function reconstruct() + local function reconstruct() -- leaves to the front, halved local li = 0 for i = 0, NUM_NODES - 1 do @@ -57319,7 +57334,7 @@ end end -- LArc lzs / lz5: a 2 KB / 4 KB ring (absolute ring positions, not distances) -@native local function decodeLzs(src: buffer, off: number, len: number, out: buffer, n: number): string? +local function decodeLzs(src: buffer, off: number, len: number, out: buffer, n: number): string? local r = reader(src, off, len) local ring = buffer.create(2048) buffer.fill(ring, 0, 0x20) @@ -57377,7 +57392,7 @@ do end end -@native local function decodeLz5(src: buffer, off: number, len: number, out: buffer, n: number): string? +local function decodeLz5(src: buffer, off: number, len: number, out: buffer, n: number): string? local ring = buffer.create(4096) buffer.copy(ring, 0, LZ5_INIT) local rp = 4096 - 18 @@ -57428,9 +57443,9 @@ end return nil end -@native local function decodeArj4(src: buffer, off: number, len: number, out: buffer, n: number): string? +local function decodeArj4(src: buffer, off: number, len: number, out: buffer, n: number): string? local r = reader(src, off, len) - @native local function prefixed(start: number, stop: number): number + local function prefixed(start: number, stop: number): number local plus, pwr = 0, lshift(1, start) local width = start while width < stop do @@ -57471,7 +57486,7 @@ end Lzh.METHODS = { "lh1", "lh4", "lh5", "lh6", "lh7", "lhx", "lzs", "lz5", "arj4" } -@native function Lzh.decode(src: buffer, off: number, len: number, outSize: number, method: string): (buffer?, string?) +function Lzh.decode(src: buffer, off: number, len: number, outSize: number, method: string): (buffer?, string?) if off < 0 or len < 0 or off > buffer.len(src) or outSize < 0 or outSize ~= outSize then return nil, "bad arguments" end @@ -58041,7 +58056,7 @@ end return Lzma end -__FILES["codecs/compress/Lzma/Crc64"] = @native function() +__FILES["codecs/compress/Lzma/Crc64"] = function() @@ -58067,7 +58082,7 @@ end local Crc64 = {} -@native function Crc64.of(b: buffer, o: number, n: number): (number, number) +function Crc64.of(b: buffer, o: number, n: number): (number, number) local hi, lo = 0xFFFFFFFF, 0xFFFFFFFF for i = o, o + n - 1 do local idx = band(bxor(lo, readu8(b, i)), 255) + 1 @@ -58079,7 +58094,7 @@ end return Crc64 end -__FILES["codecs/compress/Lzma/Decode"] = @native function() +__FILES["codecs/compress/Lzma/Decode"] = function() @@ -58129,7 +58144,7 @@ type State = { code: number, } -@native function Decode.new(cap: number, maxBytes: number): State +function Decode.new(cap: number, maxBytes: number): State local c = math.max(64, math.min(cap, maxBytes)) return { out = bcreate(c), @@ -58153,7 +58168,7 @@ type State = { } end -@native function Decode.setProps(st: State, lc: number, lp: number, pb: number): (boolean, string?) +function Decode.setProps(st: State, lc: number, lp: number, pb: number): (boolean, string?) if lc > 8 or lp > 4 or pb > 4 or lc < 0 or lp < 0 or pb < 0 then return false, "bad lc / lp / pb" end @@ -58167,7 +58182,7 @@ end return true, nil end -@native function Decode.resetState(st: State) +function Decode.resetState(st: State) local p = st.probs for i = 0, st.nprobs - 1 do writeu16(p, i * 2, 1024) @@ -58177,12 +58192,12 @@ end st.remLen = 0 end -@native function Decode.resetDict(st: State) +function Decode.resetDict(st: State) st.dictStart = st.op st.remLen = 0 end -@native function Decode.rcInit(st: State, b: buffer, ip: number, iend: number): (number?, string?) +function Decode.rcInit(st: State, b: buffer, ip: number, iend: number): (number?, string?) if ip + 5 > iend then return nil, "truncated range coder init" end @@ -58197,7 +58212,7 @@ end return ip + 5, nil end -@native local function ensure(st: State, need: number): boolean +local function ensure(st: State, need: number): boolean if need <= st.cap then return true end @@ -58213,7 +58228,7 @@ end end Decode.ensure = ensure -@native function Decode.copy(st: State, n: number, b: buffer, ip: number): (boolean, string?) +function Decode.copy(st: State, n: number, b: buffer, ip: number): (boolean, string?) if not ensure(st, st.op + n) then return false, "limit: output over maxBytes" end @@ -58228,7 +58243,7 @@ local probs: buffer = EMPTY local inb: buffer = EMPTY local range, code, ip, iend, over = 0, 0, 0, 0, 0 -@native local function bit(i: number): number +local function bit(i: number): number local p = i * 2 local prob = readu16(probs, p) local bound = rshift(range, 11) * prob @@ -58256,7 +58271,7 @@ local range, code, ip, iend, over = 0, 0, 0, 0, 0 return r end -@native local function tree(base: number, nbits: number): number +local function tree(base: number, nbits: number): number local m = 1 for _ = 1, nbits do m = m * 2 + bit(base + m) @@ -58264,7 +58279,7 @@ end return m - 2 ^ nbits end -@native local function reverse(base: number, nbits: number): number +local function reverse(base: number, nbits: number): number local m = 1 local sym = 0 for i = 0, nbits - 1 do @@ -58275,7 +58290,7 @@ end return sym end -@native local function direct(nbits: number): number +local function direct(nbits: number): number local res = 0 for _ = 1, nbits do range = rshift(range, 1) @@ -58299,7 +58314,7 @@ end return res end -@native local function length(base: number, posState: number): number +local function length(base: number, posState: number): number if bit(base) == 0 then return tree(base + 2 + posState * 8, 3) end @@ -58309,7 +58324,7 @@ end return 16 + tree(base + 258, 8) end -@native function Decode.run(st: State, inb0: buffer, ip0: number, iend0: number, outEnd: number): (string?, any) +function Decode.run(st: State, inb0: buffer, ip0: number, iend0: number, outEnd: number): (string?, any) probs = st.probs inb = inb0 iend = iend0 @@ -58541,7 +58556,7 @@ end return status, ip end -@native function Decode.finish(st: State): buffer +function Decode.finish(st: State): buffer if st.cap == st.op then return st.out end @@ -58552,7 +58567,7 @@ end return Decode end -__FILES["codecs/compress/Lzma/Filters"] = @native function() +__FILES["codecs/compress/Lzma/Filters"] = function() @@ -58568,11 +58583,11 @@ local Filters = {} local MASK_ALLOWED = { [0] = true, true, true, false, true, false, false, false } local MASK_BITNUM = { [0] = 0, 1, 2, 2, 3, 3, 3, 3 } -@native local function msbyte(b: number): boolean +local function msbyte(b: number): boolean return b == 0 or b == 0xFF end -@native function Filters.x86(b: buffer, o: number, n: number, start: number) +function Filters.x86(b: buffer, o: number, n: number, start: number) if n <= 4 then return end @@ -58630,7 +58645,7 @@ end end end -@native function Filters.arm(b: buffer, o: number, n: number, start: number) +function Filters.arm(b: buffer, o: number, n: number, start: number) local i = 0 while i + 4 <= n do if readu8(b, o + i + 3) == 0xEB then @@ -58645,7 +58660,7 @@ end end end -@native function Filters.armthumb(b: buffer, o: number, n: number, start: number) +function Filters.armthumb(b: buffer, o: number, n: number, start: number) local i = 0 while i + 4 <= n do local b1, b3 = readu8(b, o + i + 1), readu8(b, o + i + 3) @@ -58664,7 +58679,7 @@ end end end -@native function Filters.powerpc(b: buffer, o: number, n: number, start: number) +function Filters.powerpc(b: buffer, o: number, n: number, start: number) local i = 0 while i + 4 <= n do local instr = byteswap(readu32(b, o + i)) @@ -58678,7 +58693,7 @@ end end end -@native function Filters.sparc(b: buffer, o: number, n: number, start: number) +function Filters.sparc(b: buffer, o: number, n: number, start: number) local i = 0 while i + 4 <= n do local instr = byteswap(readu32(b, o + i)) @@ -58694,7 +58709,7 @@ end end end -@native function Filters.arm64(b: buffer, o: number, n: number, start: number) +function Filters.arm64(b: buffer, o: number, n: number, start: number) local i = 0 while i + 4 <= n do local pc = (start + i) % TWO32 @@ -58720,7 +58735,7 @@ end end -- delta filter: b[i] += b[i - dist] (1 <= dist <= 256) -@native function Filters.delta(b: buffer, o: number, n: number, dist: number) +function Filters.delta(b: buffer, o: number, n: number, dist: number) for i = dist, n - 1 do writeu8(b, o + i, band(readu8(b, o + i) + readu8(b, o + i - dist), 255)) end @@ -58728,7 +58743,7 @@ end return Filters end -__FILES["codecs/compress/Lzw"] = @native function() +__FILES["codecs/compress/Lzw"] = function() @@ -58749,7 +58764,7 @@ local suffix = buffer.create(TABLE) local first = buffer.create(TABLE) local length = buffer.create(TABLE * 2) -@native local function emit(out: buffer, o: number, c: number, l: number, lim: number) +local function emit(out: buffer, o: number, c: number, l: number, lim: number) local p = o + l - 1 if p < lim then while p >= o do @@ -58768,7 +58783,7 @@ local length = buffer.create(TABLE * 2) end end -@native function Lzw.decode(src: buffer, off: number, len: number, out: buffer, outOff: number, maxOut: number, variant: string, minCodeSize: number?): (number, string?) +function Lzw.decode(src: buffer, off: number, len: number, out: buffer, outOff: number, maxOut: number, variant: string, minCodeSize: number?): (number, string?) local n = blen(src) if off < 0 or off > n then return 0, "corrupt" @@ -58893,7 +58908,7 @@ local HASH = 8192 local hkey = buffer.create(HASH * 4) local hval = buffer.create(HASH * 2) -@native function Lzw.encode(data: buffer, off: number, len: number, variant: string, minCodeSize: number?): buffer +function Lzw.encode(data: buffer, off: number, len: number, variant: string, minCodeSize: number?): buffer local msb = variant == "tiff" local min = if msb then 8 else math.clamp(minCodeSize or 8, 1, 11) local early = if msb then 1 else 0 @@ -58908,7 +58923,7 @@ local hval = buffer.create(HASH * 2) local op = 0 local acc, nb = 0, 0 local size = min + 1 - @native local function put(code: number) + local function put(code: number) if op + 4 > cap then cap *= 2 local nbuf = buffer.create(cap) @@ -58996,7 +59011,7 @@ end return Lzw end -__FILES["codecs/compress/Lzx"] = @native function() +__FILES["codecs/compress/Lzx"] = function() @@ -59035,7 +59050,7 @@ local SLOTS: { [number]: number } = { [15] = 30, [16] = 32, [17] = 34, [18] = 36 -- 16-bit little-endian words, read most significant bit first type State = { src: buffer, pos: number, stop: number, bb: number, cnt: number, over: number } -@native local function refill(s: State) +local function refill(s: State) while s.cnt <= 16 do local p = s.pos local w = 0 @@ -59054,7 +59069,7 @@ type State = { src: buffer, pos: number, stop: number, bb: number, cnt: number, end end -@native local function bits(s: State, n: number): number +local function bits(s: State, n: number): number if s.cnt < n then refill(s) end @@ -59064,7 +59079,7 @@ end return v end -@native local function sym(s: State, tab: buffer, P: number, S: number): number +local function sym(s: State, tab: buffer, P: number, S: number): number if s.cnt < 16 then refill(s) end @@ -59086,7 +59101,7 @@ end end -- code lengths as deltas of their previous values, through a fresh 20-symbol pre-tree (runs 17 / 18 / 19) -@native local function readLens(s: State, lens: buffer, first: number, last: number, pre: buffer, preLens: buffer): boolean +local function readLens(s: State, lens: buffer, first: number, last: number, pre: buffer, preLens: buffer): boolean for i = 0, 19 do writeu8(preLens, i, bits(s, 4)) end @@ -59131,7 +59146,7 @@ end end -- E8 translation, frame by frame: absolute call targets back to relative -@native local function translate(out: buffer, n: number, size: number) +local function translate(out: buffer, n: number, size: number) local base = 0 local frame = 0 while base < n and frame < 32768 do @@ -59156,7 +59171,7 @@ end end end -@native function Lzx.decode(src: buffer, offset: number, length: number, outSize: number, windowBits: number): (buffer?, string?) +function Lzx.decode(src: buffer, offset: number, length: number, outSize: number, windowBits: number): (buffer?, string?) local nslots = SLOTS[windowBits] if not nslots then return nil, "unsupported: LZX window 2^" .. tostring(windowBits) @@ -59430,7 +59445,7 @@ end return Lzx end -__FILES["codecs/compress/PackBits"] = @native function() +__FILES["codecs/compress/PackBits"] = function() @@ -59440,7 +59455,7 @@ local PackBits = {} local readu8, writeu8 = buffer.readu8, buffer.writeu8 -@native function PackBits.decode(src: buffer, p: number, limit: number, dst: buffer, d: number, n: number): (number, number, boolean) +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 @@ -59483,7 +59498,7 @@ local readu8, writeu8 = buffer.readu8, buffer.writeu8 return o - d, p, clean end -@native function PackBits.encode(src: buffer, off: number, len: number): buffer +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 @@ -59520,7 +59535,7 @@ end return PackBits end -__FILES["codecs/compress/Quantum"] = @native function() +__FILES["codecs/compress/Quantum"] = function() @@ -59560,7 +59575,7 @@ end -- model: sym[1..n] in their current order, cumulative frequencies cum[1..n + 1] (cum[n + 1] = 0) type Model = { n: number, sym: { number }, cum: { number }, shifts: number } -@native local function model(first: number, n: number): Model +local function model(first: number, n: number): Model local sym = table.create(n, 0) local cum = table.create(n + 1, 0) for i = 1, n do @@ -59571,7 +59586,7 @@ type Model = { n: number, sym: { number }, cum: { number }, shifts: number } return { n = n, sym = sym, cum = cum, shifts = 4 } end -@native local function rescale(m: Model) +local function rescale(m: Model) local n, sym, cum = m.n, m.sym, m.cum m.shifts -= 1 if m.shifts > 0 then @@ -59605,7 +59620,7 @@ end type Coder = { src: buffer, pos: number, stop: number, acc: number, cnt: number, over: number, H: number, L: number, C: number, bad: boolean } -@native local function bit(c: Coder): number +local function bit(c: Coder): number if c.cnt == 0 then local p = c.pos if p < c.stop then @@ -59621,7 +59636,7 @@ type Coder = { src: buffer, pos: number, stop: number, acc: number, cnt: number, return band(rshift(c.acc, c.cnt), 1) end -@native local function raw(c: Coder, n: number): number +local function raw(c: Coder, n: number): number local v = 0 for _ = 1, n do v = v * 2 + bit(c) @@ -59629,7 +59644,7 @@ end return v end -@native local function symbol(c: Coder, m: Model): number +local function symbol(c: Coder, m: Model): number local cum = m.cum local H, L, C = c.H, c.L, c.C local range = H - L + 1 @@ -59673,7 +59688,7 @@ end return s end -@native function Quantum.decode(src: buffer, blocks: { { at: number, len: number, size: number } }, outSize: number, windowBits: number): (buffer?, string?) +function Quantum.decode(src: buffer, blocks: { { at: number, len: number, size: number } }, outSize: number, windowBits: number): (buffer?, string?) if type(windowBits) ~= "number" or windowBits < 10 or windowBits > 21 or windowBits % 1 ~= 0 then return nil, "unsupported: Quantum window 2^" .. tostring(windowBits) end @@ -59757,7 +59772,7 @@ end return Quantum end -__FILES["codecs/compress/UnixCompress"] = @native function() +__FILES["codecs/compress/UnixCompress"] = function() @@ -59784,7 +59799,7 @@ local suffix = bcreate(MAXCODES) local first = bcreate(MAXCODES) local length = bcreate(MAXCODES * 4) -@native function UnixCompress.decompress(buf: buffer | string, offset: number?, len: number?, opts: DecodeOptions?): (buffer?, Err.Err?) +function UnixCompress.decompress(buf: buffer | string, offset: number?, len: number?, opts: DecodeOptions?): (buffer?, Err.Err?) local b, o, n, aerr = Bytes.span("UnixCompress.decompress", buf, offset, len) if not b then return nil, aerr @@ -59909,7 +59924,7 @@ local HSIZE = 1 * 131072 local hkey = bcreate(HSIZE * 4) local hval = bcreate(HSIZE * 4) -@native function UnixCompress.compress(buf: buffer | string, offset: number?, len: number?, opts: EncodeOptions?): (buffer?, Err.Err?) +function UnixCompress.compress(buf: buffer | string, offset: number?, len: number?, opts: EncodeOptions?): (buffer?, Err.Err?) local b, o, n, aerr = Bytes.span("UnixCompress.compress", buf, offset, len) if not b then return nil, aerr @@ -59934,7 +59949,7 @@ local hval = bcreate(HSIZE * 4) local ratio = 0 local checkpoint = CHECK_GAP buffer.fill(hkey, 0, 0, HSIZE * 4) - @native local function put(code: number) + local function put(code: number) acc = bor(acc, lshift(code, nb)) nb += nbits outbits += nbits @@ -59947,7 +59962,7 @@ local hval = bcreate(HSIZE * 4) nb -= 8 end end - @native local function align() + local function align() -- round outbits up to a whole group of nbits-bit codes since boff; the skipped bits are zeros local g = nbits * 8 local nbits2 = boff + (outbits - boff + g - 1) // g * g @@ -59970,7 +59985,7 @@ local hval = bcreate(HSIZE * 4) local e = o + n local i = o + 1 -- checks happen with a one-byte current string, right after an output (and at the start) - @native local function checks(consumed: number) + local function checks(consumed: number) if freeEnt >= extcode then if nbits < maxbits then align() @@ -60054,14 +60069,14 @@ local hval = bcreate(HSIZE * 4) return res, nil end -@native function UnixCompress.isCompress(b: buffer, o: number?): boolean +function UnixCompress.isCompress(b: buffer, o: number?): boolean local p = o or 0 return p + 3 <= blen(b) and readu8(b, p) == 0x1F and readu8(b, p + 1) == 0x9D end return UnixCompress end -__FILES["codecs/compress/Xxh32"] = @native function() +__FILES["codecs/compress/Xxh32"] = function() @@ -60075,21 +60090,21 @@ local readu8, readu32 = buffer.readu8, buffer.readu32 local T32 = 4294967296 local P1, P2, P3, P4, P5 = 0x9E3779B1, 0x85EBCA77, 0xC2B2AE3D, 0x27D4EB2F, 0x165667B1 -@native local function mul(a: number, b: number): number +local function mul(a: number, b: number): number local a0 = a % 65536 local a1 = (a - a0) / 65536 return (a0 * b + ((a1 * b) % 65536) * 65536) % T32 end -@native local function rotl(x: number, r: number): number +local function rotl(x: number, r: number): number return bor(lshift(x, r), rshift(x, 32 - r)) end -@native local function round(acc: number, lane: number): number +local function round(acc: number, lane: number): number return mul(rotl((acc + mul(lane, P2)) % T32, 13), P1) end -@native function Xxh32.hash(b: buffer, offset: number?, length: number?, seed: number?): number +function Xxh32.hash(b: buffer, offset: number?, length: number?, seed: number?): number local n0 = buffer.len(b) local o = math.clamp(offset or 0, 0, n0) local n = math.clamp(length or (n0 - o), 0, n0 - o) @@ -60187,7 +60202,7 @@ end return Zstd end -__FILES["codecs/compress/Zstd/Decode"] = @native function() +__FILES["codecs/compress/Zstd/Decode"] = function() @@ -60233,7 +60248,7 @@ do end end -@native local function peek(b: buffer, s: number, o: number, n: number): number +local function peek(b: buffer, s: number, o: number, n: number): number if n <= 0 then return 0 end @@ -60260,7 +60275,7 @@ end return lshift(peek(b, s, o, o), -lo) end -@native local function streamBits(b: buffer, s: number, e: number): number +local function streamBits(b: buffer, s: number, e: number): number if e <= s then return -1 end @@ -60271,7 +60286,7 @@ end return (e - 1 - s) * 8 + HB[last] end -@native local function getF(b: buffer, p: number, e: number, bp: number, n: number): number +local function getF(b: buffer, p: number, e: number, bp: number, n: number): number local byte = p + rshift(bp, 3) local v = 0 local m = 1 @@ -60288,7 +60303,7 @@ end local symTmp = bcreate(512) -- normalized counts: { [symbol + 1] = count }, -1 = "less than 1" probability -@native local function buildFse(norm: { number }, nsym: number, al: number, t: buffer): (boolean?, string?) +local function buildFse(norm: { number }, nsym: number, al: number, t: buffer): (boolean?, string?) local size = lshift(1, al) local high = size - 1 local next = table.create(nsym, 0) @@ -60341,7 +60356,7 @@ local symTmp = bcreate(512) return true, nil end -@native local function ncount(b: buffer, p: number, e: number, maxSym: number, maxAL: number, norm: { number }): (number?, any, number?) +local function ncount(b: buffer, p: number, e: number, maxSym: number, maxAL: number, norm: { number }): (number?, any, number?) if p >= e then return nil, "truncated FSE table" end @@ -60418,7 +60433,7 @@ end return al, used, sym end -@native local function predefined(dist: { number }, al: number): buffer +local function predefined(dist: { number }, al: number): buffer local t = bcreate(lshift(1, al) * 4) buildFse(dist, #dist, al, t) return t @@ -60428,7 +60443,7 @@ local LL_PRE, ML_PRE, OF_PRE = predefined(LL_DEFAULT, 6), predefined(ML_DEFAULT, -- Huffman table entry (u16): sym | nbBits << 8 local weights = bcreate(256) local wfse = bcreate(64 * 4) -@native local function hufTable(b: buffer, p: number, e: number, st: any): (number?, string?) +local function hufTable(b: buffer, p: number, e: number, st: any): (number?, string?) if p >= e then return nil, "truncated Huffman table" end @@ -60553,7 +60568,7 @@ local wfse = bcreate(64 * 4) return used, nil end -@native local function hufStream(b: buffer, s: number, e: number, t: buffer, mb: number, lit: buffer, dp: number, cnt: number): string? +local function hufStream(b: buffer, s: number, e: number, t: buffer, mb: number, lit: buffer, dp: number, cnt: number): string? local off = streamBits(b, s, e) if off < 0 then return "bad Huffman stream" @@ -60583,7 +60598,7 @@ end return nil end -@native local function grow(st: any, need: number): boolean +local function grow(st: any, need: number): boolean if need > st.maxBytes then return false end @@ -60594,7 +60609,7 @@ end return true end -@native local function block(b: buffer, p: number, e: number, st: any): (string?, string?) +local function block(b: buffer, p: number, e: number, st: any): (string?, string?) -- literals section local b0 = readu8(b, p) local ltype = band(b0, 3) @@ -60958,7 +60973,7 @@ end return nil, nil end -@native function Decode.decompress(b: buffer, start: number, stop: number, maxBytes: number, verify: boolean): (buffer?, any, any, any) +function Decode.decompress(b: buffer, start: number, stop: number, maxBytes: number, verify: boolean): (buffer?, any, any, any) local st: any = { out = bcreate(math.min(maxBytes, math.max(4096, (stop - start) * 3))), op = 0, @@ -61145,7 +61160,7 @@ Decode.hash = Xxh64.hash return Decode end -__FILES["codecs/compress/Zstd/Xxh64"] = @native function() +__FILES["codecs/compress/Zstd/Xxh64"] = function() @@ -61162,7 +61177,7 @@ local P3H, P3L = 0x165667B1, 0x9E3779F9 local P4H, P4L = 0x85EBCA77, 0xC2B2AE63 local P5H, P5L = 0x27D4EB2F, 0x165667C5 -@native local function mul(ah: number, al: number, bh: number, bl: number): (number, number) +local function mul(ah: number, al: number, bh: number, bl: number): (number, number) local a0 = al % 65536 local a1 = (al - a0) / 65536 local b0 = bl % 65536 @@ -61176,7 +61191,7 @@ local P5H, P5L = 0x27D4EB2F, 0x165667C5 return hi % T32, lo32 end -@native local function add(ah: number, al: number, bh: number, bl: number): (number, number) +local function add(ah: number, al: number, bh: number, bl: number): (number, number) local l = al + bl local h = ah + bh if l >= T32 then @@ -61186,7 +61201,7 @@ end return h % T32, l end -@native local function rotl(h: number, l: number, r: number): (number, number) +local function rotl(h: number, l: number, r: number): (number, number) return bor(lshift(h, r), rshift(l, 32 - r)), bor(lshift(l, r), rshift(h, 32 - r)) end @@ -61194,7 +61209,7 @@ local P1L0, P1L1 = P1L % 65536, P1L // 65536 local P2L0, P2L1 = P2L % 65536, P2L // 65536 -- round: acc = rotl(acc + input * P2, 31) * P1 -@native local function round(ah: number, al: number, ih: number, il: number): (number, number) +local function round(ah: number, al: number, ih: number, il: number): (number, number) local a0 = il % 65536 local a1 = (il - a0) / 65536 local mid = a1 * P2L0 + a0 * P2L1 @@ -61222,7 +61237,7 @@ local P2L0, P2L1 = P2L % 65536, P2L // 65536 return mh % T32, ml end -@native local function merge(hh: number, hl: number, vh: number, vl: number): (number, number) +local function merge(hh: number, hl: number, vh: number, vl: number): (number, number) local rh, rl = round(0, 0, vh, vl) hh, hl = bxor(hh, rh), bxor(hl, rl) hh, hl = mul(hh, hl, P1H, P1L) @@ -61231,7 +61246,7 @@ end local Xxh64 = {} -@native function Xxh64.hash(b: buffer, offset: number, length: number): (number, number) +function Xxh64.hash(b: buffer, offset: number, length: number): (number, number) local p = offset local e = offset + length local hh, hl = 0, 0 @@ -61297,7 +61312,7 @@ end return Xxh64 end -__FILES["codecs/entropy/Huffman"] = @native function() +__FILES["codecs/entropy/Huffman"] = function() -- codecs/entropy/Huffman: canonical Huffman codes (RFC 1951 3.2.2 / JPEG Annex C order). @@ -61326,19 +61341,19 @@ for i = 0, 255 do REV[i + 1] = r end -@native local function reverse(code: number, len: number): number +local function reverse(code: number, len: number): number return rshift(bor(lshift(REV[band(code, 255) + 1], 8), REV[band(rshift(code, 8), 255) + 1]), 16 - len) end Huffman.reverse = reverse -@native function Huffman.capacity(nsym: number, P: number, maxLen: number): number +function Huffman.capacity(nsym: number, P: number, maxLen: number): number return 2 ^ P + (if maxLen > P then nsym * 2 ^ (maxLen - P) else 0) end local count = table.create(MAXLEN + 1, 0) local nextc = table.create(MAXLEN + 1, 0) -@native local function build(lens: buffer, off: number, n: number, tab: buffer, P: number, msb: boolean): number +local function build(lens: buffer, off: number, n: number, tab: buffer, P: number, msb: boolean): number for i = 1, MAXLEN + 1 do count[i] = 0 end @@ -61432,15 +61447,15 @@ local nextc = table.create(MAXLEN + 1, 0) return S end -@native function Huffman.buildLsb(lens: buffer, off: number, n: number, tab: buffer, P: number): number +function Huffman.buildLsb(lens: buffer, off: number, n: number, tab: buffer, P: number): number return build(lens, off, n, tab, P, false) end -@native function Huffman.buildMsb(lens: buffer, off: number, n: number, tab: buffer, P: number): number +function Huffman.buildMsb(lens: buffer, off: number, n: number, tab: buffer, P: number): number return build(lens, off, n, tab, P, true) end -@native function Huffman.decodeLsb(br: Bits.BitReader, tab: buffer, P: number, S: number): number +function Huffman.decodeLsb(br: Bits.BitReader, tab: buffer, P: number, S: number): number local e = readu32(tab, br:peek(P) * 4) local l = band(e, 31) if l == 0 then @@ -61458,7 +61473,7 @@ end return rshift(e, 5) end -@native function Huffman.decodeMsb(br: Bits.BitReader, tab: buffer, P: number, S: number): number +function Huffman.decodeMsb(br: Bits.BitReader, tab: buffer, P: number, S: number): number local e = readu32(tab, br:peek(P) * 4) local l = band(e, 31) if l == 0 then @@ -61476,7 +61491,7 @@ end return rshift(e, 5) end -@native function Huffman.codes(lengths: { number }): { number } +function Huffman.codes(lengths: { number }): { number } local cnt = table.create(MAXLEN + 1, 0) for _, l in lengths do if l > 0 then @@ -61499,7 +61514,7 @@ end return out end -@native function Huffman.lengths(freqs: { number }, maxLen: number): { number } +function Huffman.lengths(freqs: { number }, maxLen: number): { number } local n = #freqs local out = table.create(n, 0) local syms = {} @@ -61515,7 +61530,7 @@ end out[syms[1]] = 1 return out end - table.sort(syms, @native function(a: number, b: number): boolean + table.sort(syms, function(a: number, b: number): boolean if freqs[a] ~= freqs[b] then return freqs[a] < freqs[b] end @@ -61528,7 +61543,7 @@ end weight[i] = freqs[syms[i]] end local li, ni, nn = 1, m + 1, m + 1 - @native local function take(): number + local function take(): number if li <= m and (ni >= nn or weight[li] <= weight[ni]) then li += 1 return li - 1 @@ -61590,7 +61605,7 @@ local RangeCoder = { return RangeCoder end -__FILES["codecs/entropy/RangeCoder/Decoder"] = @native function() +__FILES["codecs/entropy/RangeCoder/Decoder"] = function() @@ -61628,12 +61643,12 @@ local countlz = bit32.countlz local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift local readu8 = buffer.readu8 -@native local function ilog(x: number): number +local function ilog(x: number): number return 32 - countlz(x) end RangeDecoder.ilog = ilog -@native local function normalize(d: Dec) +local function normalize(d: Dec) local rng, val, rem = d.rng, d.val, d.rem while rng <= CODE_BOT do d.nbits_total += SYM_BITS @@ -61652,7 +61667,7 @@ RangeDecoder.ilog = ilog d.rng, d.val, d.rem = rng, val, rem end -@native function RangeDecoder.new(buf: buffer, base: number, storage: number): Dec +function RangeDecoder.new(buf: buffer, base: number, storage: number): Dec local d: Dec = { buf = buf, base = base, @@ -61679,14 +61694,14 @@ end return d end -@native function RangeDecoder.decode(d: Dec, ft: number): number +function RangeDecoder.decode(d: Dec, ft: number): number local ext = d.rng // ft d.ext = ext local s = d.val // ext return ft - math.min(s + 1, ft) end -@native function RangeDecoder.decodeBin(d: Dec, bits: number): number +function RangeDecoder.decodeBin(d: Dec, bits: number): number local ext = rshift(d.rng, bits) d.ext = ext local s = d.val // ext @@ -61694,7 +61709,7 @@ end return ft - math.min(s + 1, ft) end -@native function RangeDecoder.update(d: Dec, fl: number, fh: number, ft: number) +function RangeDecoder.update(d: Dec, fl: number, fh: number, ft: number) local s = d.ext * (ft - fh) d.val = band(d.val - s, 0xFFFFFFFF) -- uint32 wrap (corrupt streams only) if fl > 0 then @@ -61705,7 +61720,7 @@ end normalize(d) end -@native function RangeDecoder.bitLogp(d: Dec, logp: number): boolean +function RangeDecoder.bitLogp(d: Dec, logp: number): boolean local r = d.rng local v = d.val local s = rshift(r, logp) @@ -61720,7 +61735,7 @@ end return ret end -@native function RangeDecoder.icdf(d: Dec, icdf: { number }, off: number, ftb: number): number +function RangeDecoder.icdf(d: Dec, icdf: { number }, off: number, ftb: number): number local s = d.rng local v = d.val local r = rshift(s, ftb) @@ -61737,7 +61752,7 @@ end return ret end -@native function RangeDecoder.bits(d: Dec, bits: number): number +function RangeDecoder.bits(d: Dec, bits: number): number local window = d.end_window local available = d.nend_bits if available < bits then @@ -61765,7 +61780,7 @@ end return ret end -@native function RangeDecoder.uint(d: Dec, ft0: number): number +function RangeDecoder.uint(d: Dec, ft0: number): number local ft = ft0 - 1 local ftb = ilog(ft) if ftb > UINT_BITS then @@ -61786,12 +61801,12 @@ end end end -@native function RangeDecoder.tell(d: Dec): number +function RangeDecoder.tell(d: Dec): number return d.nbits_total - ilog(d.rng) end local correction = { 35733, 38967, 42495, 46340, 50535, 55109, 60097, 65535 } -@native function RangeDecoder.tellFrac(d: Dec): number +function RangeDecoder.tellFrac(d: Dec): number local nbits = d.nbits_total * 8 local l = ilog(d.rng) local r = rshift(d.rng, l - 16) @@ -61804,7 +61819,7 @@ end return RangeDecoder end -__FILES["codecs/entropy/RangeCoder/Encoder"] = @native function() +__FILES["codecs/entropy/RangeCoder/Encoder"] = function() @@ -61837,12 +61852,12 @@ local band = bit32.band local readu8, writeu8 = buffer.readu8, buffer.writeu8 local floor = math.floor -@native local function ilog(x: number): number +local function ilog(x: number): number return 32 - countlz(x) end RangeEncoder.ilog = ilog -@native function RangeEncoder.new(storage: number): Enc +function RangeEncoder.new(storage: number): Enc return { buf = buffer.create(math.max(storage, 1)), storage = storage, @@ -61859,7 +61874,7 @@ RangeEncoder.ilog = ilog } end -@native local function writeByte(e: Enc, v: number) +local function writeByte(e: Enc, v: number) if e.offs + e.end_offs >= e.storage then e.error = -1 return @@ -61868,7 +61883,7 @@ end e.offs += 1 end -@native local function writeByteAtEnd(e: Enc, v: number) +local function writeByteAtEnd(e: Enc, v: number) if e.offs + e.end_offs >= e.storage then e.error = -1 return @@ -61877,7 +61892,7 @@ end writeu8(e.buf, e.storage - e.end_offs, band(v, 255)) end -@native local function carryOut(e: Enc, c: number) +local function carryOut(e: Enc, c: number) if c ~= SYM_MAX then local carry = if c >= 256 then 1 else 0 if e.rem >= 0 then @@ -61896,7 +61911,7 @@ end end end -@native local function normalize(e: Enc) +local function normalize(e: Enc) while e.rng <= CODE_BOT do carryOut(e, floor(e.val / 8388608)) e.val = (e.val * 256) % CODE_TOP @@ -61905,7 +61920,7 @@ end end end -@native function RangeEncoder.encode(e: Enc, fl: number, fh: number, ft: number) +function RangeEncoder.encode(e: Enc, fl: number, fh: number, ft: number) local r = floor(e.rng / ft) if fl > 0 then e.val += e.rng - r * (ft - fl) @@ -61916,7 +61931,7 @@ end normalize(e) end -@native function RangeEncoder.encodeBin(e: Enc, fl: number, fh: number, bits: number) +function RangeEncoder.encodeBin(e: Enc, fl: number, fh: number, bits: number) local ft = 2 ^ bits local r = floor(e.rng / ft) if fl > 0 then @@ -61928,7 +61943,7 @@ end normalize(e) end -@native function RangeEncoder.bitLogp(e: Enc, v: boolean, logp: number) +function RangeEncoder.bitLogp(e: Enc, v: boolean, logp: number) local r = e.rng local s = floor(r / 2 ^ logp) r -= s @@ -61941,7 +61956,7 @@ end normalize(e) end -@native function RangeEncoder.icdf(e: Enc, s: number, icdf: { number }, ftb: number) +function RangeEncoder.icdf(e: Enc, s: number, icdf: { number }, ftb: number) local r = floor(e.rng / 2 ^ ftb) if s > 0 then e.val += e.rng - r * icdf[s] @@ -61952,7 +61967,7 @@ end normalize(e) end -@native function RangeEncoder.bits(e: Enc, fl: number, n: number) +function RangeEncoder.bits(e: Enc, fl: number, n: number) local window = e.end_window local used = e.nend_bits if used + n > 32 then @@ -61969,7 +61984,7 @@ end e.nbits_total += n end -@native function RangeEncoder.uint(e: Enc, fl: number, ft: number) +function RangeEncoder.uint(e: Enc, fl: number, ft: number) ft -= 1 local ftb = ilog(ft) if ftb > 8 then @@ -61984,12 +61999,12 @@ end end end -@native function RangeEncoder.tell(e: Enc): number +function RangeEncoder.tell(e: Enc): number return e.nbits_total - ilog(e.rng) end local CORRECTION = { 35733, 38967, 42495, 46340, 50535, 55109, 60097, 65535 } -@native function RangeEncoder.tellFrac(e: Enc): number +function RangeEncoder.tellFrac(e: Enc): number local nbits = e.nbits_total * 8 local l = ilog(e.rng) local r = floor(e.rng / 2 ^ (l - 16)) @@ -62000,7 +62015,7 @@ local CORRECTION = { 35733, 38967, 42495, 46340, 50535, 55109, 60097, 65535 } return nbits - (l * 8 + b) end -@native function RangeEncoder.done(e: Enc) +function RangeEncoder.done(e: Enc) local l = 32 - ilog(e.rng) local msk = floor((CODE_TOP - 1) / 2 ^ l) local stop = floor((e.val + msk) / (msk + 1)) * (msk + 1) @@ -64248,7 +64263,7 @@ end return Tables end -__FILES["codecs/image/Bcn"] = @native function() +__FILES["codecs/image/Bcn"] = function() @@ -64273,15 +64288,15 @@ local BLOCKS: { [string]: (buffer, number, buffer) -> () } = { bc5 = Decode.bc5, bc5s = Decode.bc5s, bc7 = Decode.bc7, - bc6h = @native function(src: buffer, p: number, blk: buffer) + bc6h = function(src: buffer, p: number, blk: buffer) Decode.bc6h(src, p, blk, false) end, - bc6hs = @native function(src: buffer, p: number, blk: buffer) + bc6hs = function(src: buffer, p: number, blk: buffer) Decode.bc6h(src, p, blk, true) end, } -@native function Bcn.size(kind: string, w: number, h: number): number? +function Bcn.size(kind: string, w: number, h: number): number? local b = Bcn.BLOCK[kind] if not b then return nil @@ -64289,7 +64304,7 @@ local BLOCKS: { [string]: (buffer, number, buffer) -> () } = { return ((w + 3) // 4) * ((h + 3) // 4) * b end -@native function Bcn.decode(kind: string, src: buffer, offset: number, w: number, h: number, out: buffer?, outOffset: number?): (buffer?, string?) +function Bcn.decode(kind: string, src: buffer, offset: number, w: number, h: number, out: buffer?, outOffset: number?): (buffer?, string?) local fn = BLOCKS[kind] if not fn then return nil, "unsupported: unknown block format " .. tostring(kind) @@ -64342,7 +64357,7 @@ type EncodeOptions = { alphaThreshold: number?, } -@native function Bcn.encode(kind: string, px: buffer, w: number, h: number, opts: EncodeOptions?): (buffer?, string?) +function Bcn.encode(kind: string, px: buffer, w: number, h: number, opts: EncodeOptions?): (buffer?, string?) if kind ~= "bc1" and kind ~= "bc3" and kind ~= "bc4" and kind ~= "bc5" then return nil, "unsupported: no encoder for " .. tostring(kind) end @@ -64355,7 +64370,7 @@ end return Bcn end -__FILES["codecs/image/Bcn/Decode"] = @native function() +__FILES["codecs/image/Bcn/Decode"] = function() @@ -64372,7 +64387,7 @@ local HALF = Half.TABLE local pal = buffer.create(16) -@native local function c565(c: number): (number, number, number) +local function c565(c: number): (number, number, number) local r = rshift(band(c, 0xF800), 8) local g = rshift(band(c, 0x7E0), 3) local b = lshift(band(c, 0x1F), 3) @@ -64380,7 +64395,7 @@ local pal = buffer.create(16) end -- BC2 / BC3 colour blocks always use the 4-colour palette -@native local function colour(src: buffer, p: number, blk: buffer, fourColour: boolean) +local function colour(src: buffer, p: number, blk: buffer, fourColour: boolean) local c0, c1 = readu16(src, p), readu16(src, p + 2) local r0, g0, b0 = c565(c0) local r1, g1, b1 = c565(c1) @@ -64400,7 +64415,7 @@ end end local vals = table.create(8, 0) -@native local function ramp8(a0: number, a1: number) +local function ramp8(a0: number, a1: number) vals[1], vals[2] = a0, a1 if a0 > a1 then for i = 1, 6 do @@ -64415,7 +64430,7 @@ local vals = table.create(8, 0) end -- signed (SNORM) ramp, values -127..127 rounded to the nearest integer, biased by 128 into 1..255 -@native local function ramp8s(u0: number, u1: number) +local function ramp8s(u0: number, u1: number) local s0: number = math.max(if u0 >= 128 then u0 - 256 else u0, -127) local s1: number = math.max(if u1 >= 128 then u1 - 256 else u1, -127) vals[1], vals[2] = s0 + 128, s1 + 128 @@ -64431,7 +64446,7 @@ end end end -@native local function single(src: buffer, p: number, blk: buffer, channel: number, signed: boolean, spread: boolean) +local function single(src: buffer, p: number, blk: buffer, channel: number, signed: boolean, spread: boolean) if signed then ramp8s(readu8(src, p), readu8(src, p + 1)) else @@ -64451,11 +64466,11 @@ end end end -@native function Decode.bc1(src: buffer, p: number, blk: buffer) +function Decode.bc1(src: buffer, p: number, blk: buffer) colour(src, p, blk, false) end -@native function Decode.bc2(src: buffer, p: number, blk: buffer) +function Decode.bc2(src: buffer, p: number, blk: buffer) colour(src, p + 8, blk, true) for i = 0, 15 do local a = band(rshift(readu8(src, p + rshift(i, 1)), band(i, 1) * 4), 15) @@ -64463,30 +64478,30 @@ end end end -@native function Decode.bc3(src: buffer, p: number, blk: buffer) +function Decode.bc3(src: buffer, p: number, blk: buffer) colour(src, p + 8, blk, true) single(src, p, blk, 3, false, false) end -@native function Decode.bc4(src: buffer, p: number, blk: buffer) +function Decode.bc4(src: buffer, p: number, blk: buffer) single(src, p, blk, 0, false, true) end -@native function Decode.bc4s(src: buffer, p: number, blk: buffer) +function Decode.bc4s(src: buffer, p: number, blk: buffer) single(src, p, blk, 0, true, true) end -@native local function bc5(src: buffer, p: number, blk: buffer, signed: boolean) +local function bc5(src: buffer, p: number, blk: buffer, signed: boolean) for i = 0, 15 do writeu32(blk, i * 4, 0xFF000000) end single(src, p, blk, 0, signed, false) single(src, p + 8, blk, 1, signed, false) end -@native function Decode.bc5(src: buffer, p: number, blk: buffer) +function Decode.bc5(src: buffer, p: number, blk: buffer) bc5(src, p, blk, false) end -@native function Decode.bc5s(src: buffer, p: number, blk: buffer) +function Decode.bc5s(src: buffer, p: number, blk: buffer) bc5(src, p, blk, true) end @@ -64524,7 +64539,7 @@ local W4 = { [0] = 0, 4, 9, 13, 17, 21, 26, 30, 34, 38, 43, 47, 51, 55, 60, 64 } local WEIGHTS = { [2] = W2, [3] = W3, [4] = W4 } Decode.SI2, Decode.SI3, Decode.AI0, Decode.AI1, Decode.AI2, Decode.WEIGHTS = SI2, SI3, AI0, AI1, AI2, WEIGHTS -@native local function subset(ns: number, part: number, i: number): number +local function subset(ns: number, part: number, i: number): number if ns == 2 then return band(rshift(SI2[part + 1], i), 1) elseif ns == 3 then @@ -64534,13 +64549,13 @@ Decode.SI2, Decode.SI3, Decode.AI0, Decode.AI1, Decode.AI2, Decode.WEIGHTS = SI2 end local w0, w1, w2, w3 = 0, 0, 0, 0 -@native local function load(src: buffer, p: number) +local function load(src: buffer, p: number) w0, w1, w2, w3 = readu32(src, p), readu32(src, p + 4), readu32(src, p + 8), readu32(src, p + 12) end -@native local function word(i: number): number +local function word(i: number): number return if i == 0 then w0 elseif i == 1 then w1 elseif i == 2 then w2 else w3 end -@native local function bits(at: number, n: number): number +local function bits(at: number, n: number): number if n == 0 then return 0 end @@ -64565,12 +64580,12 @@ local MODES7 = { } local er, eg, eb, ea = table.create(6, 0), table.create(6, 0), table.create(6, 0), table.create(6, 0) -@native local function expand(v: number, n: number): number +local function expand(v: number, n: number): number v = band(lshift(v, 8 - n), 255) return bor(v, rshift(v, n)) end -@native function Decode.bc7(src: buffer, p: number, blk: buffer) +function Decode.bc7(src: buffer, p: number, blk: buffer) local m0 = readu8(src, p) if m0 == 0 then buffer.fill(blk, 0, 0, 64) @@ -64727,12 +64742,12 @@ local PACK6 = { local ep = table.create(12, 0) local uq = table.create(12, 0) -@native local function signExtend(v: number, n: number): number +local function signExtend(v: number, n: number): number v = band(v, lshift(1, n) - 1) return if v >= lshift(1, n - 1) then v - lshift(1, n) else v end -@native local function unquantize(x: number, n: number, signed: boolean): number +local function unquantize(x: number, n: number, signed: boolean): number if not signed then if n >= 15 or x == 0 then return x @@ -64758,7 +64773,7 @@ end return if neg then -x else x end -@native local function finish(v: number, signed: boolean): number +local function finish(v: number, signed: boolean): number if signed then if v < 0 then return -HALF[(-v * 31) // 32] @@ -64768,7 +64783,7 @@ end return HALF[(v * 31) // 64] end -@native function Decode.bc6h(src: buffer, p: number, blk: buffer, signed: boolean) +function Decode.bc6h(src: buffer, p: number, blk: buffer, signed: boolean) load(src, p) local m = band(w0, 31) local mode, bit, epbits, ib @@ -64844,7 +64859,7 @@ end return Decode end -__FILES["codecs/image/Bcn/Encode"] = @native function() +__FILES["codecs/image/Bcn/Encode"] = function() @@ -64855,17 +64870,17 @@ local Encode = {} local readu8, writeu8, writeu16, writeu32 = buffer.readu8, buffer.writeu8, buffer.writeu16, buffer.writeu32 local band, bor, rshift, lshift = bit32.band, bit32.bor, bit32.rshift, bit32.lshift -@native local function exp5(v: number): number +local function exp5(v: number): number return bor(lshift(v, 3), rshift(v, 2)) end -@native local function exp6(v: number): number +local function exp6(v: number): number return bor(lshift(v, 2), rshift(v, 4)) end -- OM[k][v + 1] = e0 * 256 + e1 (quantized) whose colour-2 value (4-colour: (2 e0 + e1) // 3; 3-colour: (e0 + e1) -- // 2) is closest to v; k = 1 / 2 for 5-bit (4 / 3 colour), 3 / 4 for 6-bit local OM: { { number } }? = nil -@native local function singleTables(): { { number } } +local function singleTables(): { { number } } local om = OM if om then return om @@ -64905,7 +64920,7 @@ local PR, PG, PB = table.create(4, 0), table.create(4, 0), table.create(4, 0) local IDX = table.create(16, 0) local BEST = table.create(16, 0) -@native local function palette(c0: number, c1: number, four: boolean) +local function palette(c0: number, c1: number, four: boolean) local r0, g0, b0 = exp5(rshift(c0, 11)), exp6(band(rshift(c0, 5), 63)), exp5(band(c0, 31)) local r1, g1, b1 = exp5(rshift(c1, 11)), exp6(band(rshift(c1, 5), 63)), exp5(band(c1, 31)) PR[1], PG[1], PB[1] = r0, g0, b0 @@ -64919,7 +64934,7 @@ local BEST = table.create(16, 0) end end -@native local function assign(four: boolean): number +local function assign(four: boolean): number local n = if four then 4 else 3 local total = 0 for i = 1, 16 do @@ -64942,7 +64957,7 @@ end return total end -@native local function q565(r: number, g: number, b: number): number +local function q565(r: number, g: number, b: number): number local qr = math.clamp(math.floor(r * 31 / 255 + 0.5), 0, 31) local qg = math.clamp(math.floor(g * 63 / 255 + 0.5), 0, 63) local qb = math.clamp(math.floor(b * 31 / 255 + 0.5), 0, 31) @@ -64952,7 +64967,7 @@ end local W4 = { 1, 0, 2 / 3, 1 / 3 } local W3 = { 1, 0, 0.5, 0 } -@native local function refine(four: boolean): (number?, number?) +local function refine(four: boolean): (number?, number?) local W = if four then W4 else W3 local aa, bb, ab = 0, 0, 0 local ar, ag, ab_, br, bg, bb_ = 0, 0, 0, 0, 0, 0 @@ -64981,7 +64996,7 @@ local W3 = { 1, 0, 0.5, 0 } return q565(r0, g0, b0), q565(r1, g1, b1) end -@native local function colourBlock(out: buffer, o: number, four: boolean) +local function colourBlock(out: buffer, o: number, four: boolean) local n, mr, mg, mb = 0, 0, 0, 0 for i = 1, 16 do if USE[i] then @@ -65118,7 +65133,7 @@ local RAMP = table.create(8, 0) local SEL = table.create(16, 0) local SELB = table.create(16, 0) -@native local function ramp(a0: number, a1: number) +local function ramp(a0: number, a1: number) RAMP[1], RAMP[2] = a0, a1 if a0 > a1 then for i = 1, 6 do @@ -65132,7 +65147,7 @@ local SELB = table.create(16, 0) end end -@native local function pick(): number +local function pick(): number local total = 0 for i = 1, 16 do local v = V[i] @@ -65150,7 +65165,7 @@ end return total end -@native local function channelBlock(out: buffer, o: number) +local function channelBlock(out: buffer, o: number) local lo, hi = 255, 0 local lo2, hi2 = 255, 0 for i = 1, 16 do @@ -65215,7 +65230,7 @@ end writeu8(out, o + 7, rshift(hi24, 16)) end -@native local function gather(px: buffer, w: number, h: number, bx: number, by: number) +local function gather(px: buffer, w: number, h: number, bx: number, by: number) for y = 0, 3 do local sy = math.min(by * 4 + y, h - 1) for x = 0, 3 do @@ -65227,7 +65242,7 @@ end end end -@native function Encode.run(kind: string, px: buffer, w: number, h: number, threshold: number): buffer +function Encode.run(kind: string, px: buffer, w: number, h: number, threshold: number): buffer local bw, bh = (w + 3) // 4, (h + 3) // 4 local bytes = if kind == "bc1" or kind == "bc4" then 8 else 16 local out = buffer.create(bw * bh * bytes) @@ -65273,7 +65288,7 @@ end return Encode end -__FILES["codecs/image/Blend"] = @native function() +__FILES["codecs/image/Blend"] = function() -- codecs/image/Blend: rgba8 layer compositing (straight alpha) with the W3C Compositing and Blending Level 1 modes. @@ -65319,7 +65334,7 @@ for k in IDS do end Blend.MODES = table.freeze(MODES) -@native local function burn(cb: number, cs: number): number +local function burn(cb: number, cs: number): number if cb >= 1 then return 1 elseif cs <= 0 then @@ -65327,7 +65342,7 @@ Blend.MODES = table.freeze(MODES) end return 1 - min(1, (1 - cb) / cs) end -@native local function dodge(cb: number, cs: number): number +local function dodge(cb: number, cs: number): number if cb <= 0 then return 0 elseif cs >= 1 then @@ -65337,7 +65352,7 @@ end end -- B(cb, cs) of a separable mode -@native local function sep(m: number, cb: number, cs: number): number +local function sep(m: number, cb: number, cs: number): number if m == 3 then return cb * cs elseif m == 8 then @@ -65402,10 +65417,10 @@ end end -- non-separable helpers (W3C): lum, clip, setLum, sat, setSat -@native local function lum(r: number, g: number, b: number): number +local function lum(r: number, g: number, b: number): number return 0.3 * r + 0.59 * g + 0.11 * b end -@native local function clipColor(r: number, g: number, b: number): (number, number, number) +local function clipColor(r: number, g: number, b: number): (number, number, number) local l = lum(r, g, b) local n = min(r, g, b) local x = max(r, g, b) @@ -65417,11 +65432,11 @@ end end return r, g, b end -@native local function setLum(r: number, g: number, b: number, l: number): (number, number, number) +local function setLum(r: number, g: number, b: number, l: number): (number, number, number) local d = l - lum(r, g, b) return clipColor(r + d, g + d, b + d) end -@native local function setSat(r: number, g: number, b: number, s: number): (number, number, number) +local function setSat(r: number, g: number, b: number, s: number): (number, number, number) local mx = max(r, g, b) local mn = min(r, g, b) if mx - mn <= 1e-12 then @@ -65431,7 +65446,7 @@ end return (r - mn) * k, (g - mn) * k, (b - mn) * k end -@native local function composite(dst: buffer, dw: number, dh: number, src: buffer, sw: number, sh: number, x: number, y: number, opacity: number, mode: string?, opts: { clip: boolean?, mask: any? }?) +local function composite(dst: buffer, dw: number, dh: number, src: buffer, sw: number, sh: number, x: number, y: number, opacity: number, mode: string?, opts: { clip: boolean?, mask: any? }?) x, y = floor(x), floor(y) if opacity <= 0 or dw <= 0 or dh <= 0 or sw <= 0 or sh <= 0 then return @@ -65536,7 +65551,7 @@ end end end -@native local function lerp(dst: buffer, from: buffer, t: number, n: number, w: number?, mask: any?) +local function lerp(dst: buffer, from: buffer, t: number, n: number, w: number?, mask: any?) if blen(dst) < n * 4 or blen(from) < n * 4 then return end @@ -65572,11 +65587,11 @@ end Blend.composite = composite Blend.lerp = lerp -@native local function isImage(v: any): boolean +local function isImage(v: any): boolean return type(v) == "table" and v.format == "rgba8" and type(v.pixels) == "buffer" and type(v.width) == "number" and type(v.height) == "number" and buffer.len(v.pixels) >= v.width * v.height * 4 end -@native local function maskOf(l: any): any +local function maskOf(l: any): any local m = l.mask if type(m) ~= "table" or m.disabled or type(m.image) ~= "table" or type(m.image.pixels) ~= "buffer" then return nil @@ -65594,7 +65609,7 @@ end return { pixels = px, width = img.width, height = img.height, x = m.x or 0, y = m.y or 0, default = m.default or 255 } end -@native local function compose(layers: { any }, canvas: buffer, w: number, h: number, hidden: boolean) +local function compose(layers: { any }, canvas: buffer, w: number, h: number, hidden: boolean) local i = 1 while i <= #layers do local l = layers[i] @@ -65644,7 +65659,7 @@ end end end -@native function Blend.flatten(layers: { any }, canvas: buffer, w: number, h: number, hidden: boolean) +function Blend.flatten(layers: { any }, canvas: buffer, w: number, h: number, hidden: boolean) if blen(canvas) >= w * h * 4 then compose(layers, canvas, w, h, hidden) end @@ -65652,7 +65667,7 @@ end return Blend end -__FILES["codecs/image/Dct"] = @native function() +__FILES["codecs/image/Dct"] = function() @@ -65666,7 +65681,7 @@ local Dct = {} local ws = table.create(64, 0) -@native local function idct8(coef: buffer, off: number, q: buffer, plane: buffer, out: number, stride: number, p1: number, center: number, maxv: number) +local function idct8(coef: buffer, off: number, q: buffer, plane: buffer, out: number, stride: number, p1: number, center: number, maxv: number) local s1 = 2 ^ (13 - p1) local h1 = s1 / 2 local s2 = 2 ^ (16 + p1) @@ -65782,7 +65797,7 @@ local ws = table.create(64, 0) end end -@native local function idct4(coef: buffer, off: number, q: buffer, plane: buffer, out: number, stride: number, p1: number, center: number, maxv: number) +local function idct4(coef: buffer, off: number, q: buffer, plane: buffer, out: number, stride: number, p1: number, center: number, maxv: number) local s1 = 2 ^ (14 - p1) local h1 = s1 / 2 local dcm = 2 ^ p1 @@ -65844,7 +65859,7 @@ end end end -@native local function idct2(coef: buffer, off: number, q: buffer, plane: buffer, out: number, stride: number, p1: number, center: number, maxv: number) +local function idct2(coef: buffer, off: number, q: buffer, plane: buffer, out: number, stride: number, p1: number, center: number, maxv: number) local s1 = 2 ^ (15 - p1) local h1 = s1 / 2 local dcm = 2 ^ p1 @@ -65891,7 +65906,7 @@ end end -- p1 = PASS1_BITS (2 for 8-bit, 1 for 12-bit) -@native function Dct.idctComponent(coef: buffer, q: buffer, bpl: number, bpc: number, size: number, plane: buffer, p1: number, center: number, maxv: number, hook: (() -> ())?) +function Dct.idctComponent(coef: buffer, q: buffer, bpl: number, bpc: number, size: number, plane: buffer, p1: number, center: number, maxv: number, hook: (() -> ())?) local stride = bpl * size for by = 0, bpc - 1 do if hook and by > 0 then @@ -65914,13 +65929,13 @@ end end end -@native function Dct.idctBlock(coef: buffer, off: number, q: buffer, plane: buffer, out: number, stride: number, p1: number, center: number, maxv: number) +function Dct.idctBlock(coef: buffer, off: number, q: buffer, plane: buffer, out: number, stride: number, p1: number, center: number, maxv: number) idct8(coef, off, q, plane, out, stride, p1, center, maxv) end local fw = table.create(64, 0) -@native local function quant(coef: buffer, off: number, div: buffer, v: number, i: number) +local function quant(coef: buffer, off: number, div: buffer, v: number, i: number) local qv = readu16(div, i * 2) * 8 local h = qv // 2 if v < 0 then @@ -65931,7 +65946,7 @@ local fw = table.create(64, 0) end -- quantised as jcdctmgr.c: (|v| + q * 4) // (q * 8) with the sign restored -@native function Dct.fdctQuantize(src: buffer, stride: number, x: number, y: number, w: number, h: number, div: buffer, coef: buffer, off: number) +function Dct.fdctQuantize(src: buffer, stride: number, x: number, y: number, w: number, h: number, div: buffer, coef: buffer, off: number) local lastX, lastY = w - 1, h - 1 for r = 0, 7 do local row = math.min(y + r, lastY) * stride @@ -66033,7 +66048,7 @@ end return Dct end -__FILES["codecs/image/Etc"] = @native function() +__FILES["codecs/image/Etc"] = function() @@ -66076,27 +66091,27 @@ local EAC = { { -3, -5, -7, -9, 2, 4, 6, 8 }, } -@native local function clamp8(v: number): number +local function clamp8(v: number): number return if v < 0 then 0 elseif v > 255 then 255 else v end -@native local function rgb(r: number, g: number, b: number): number +local function rgb(r: number, g: number, b: number): number return clamp8(r) + clamp8(g) * 256 + clamp8(b) * 65536 + 0xFF000000 end -- blk: 16 u32 rgba8 pixels in raster order (y * 4 + x) local P = table.create(4, 0) -@native local function be32(src: buffer, p: number): number +local function be32(src: buffer, p: number): number return byteswap(readu32(src, p)) end -- the 2-bit pixel index of pixel i (column-major: i = x * 4 + y) -@native local function pix(lo: number, i: number): number +local function pix(lo: number, i: number): number return band(rshift(lo, i + 15), 2) + band(rshift(lo, i), 1) end -- ETC1 / ETC2 colour block; the RGB A1 variant: bit 33 = opaque -@native local function colour(src: buffer, p: number, blk: buffer, etc2: boolean, punch: boolean) +local function colour(src: buffer, p: number, blk: buffer, etc2: boolean, punch: boolean) local hi, lo = be32(src, p), be32(src, p + 4) local diffBit = band(rshift(hi, 1), 1) local flip = band(hi, 1) @@ -66201,7 +66216,7 @@ end local VALS = table.create(16, 0) -@native local function eac(src: buffer, p: number, mode: string) +local function eac(src: buffer, p: number, mode: string) local base = readu8(src, p) local b1 = readu8(src, p + 1) local mult, tab = rshift(b1, 4), EAC[band(b1, 15) + 1] @@ -66233,25 +66248,25 @@ local VALS = table.create(16, 0) end end -@native local function to8(v: number, signed: boolean): number +local function to8(v: number, signed: boolean): number if signed then return math.floor(v * 127 / 1023 + 0.5) + 128 end return math.floor(v * 255 / 2047 + 0.5) end -@native local function to16(v: number, signed: boolean): number +local function to16(v: number, signed: boolean): number if signed then return math.floor((v + 1023) * 65535 / 2046 + 0.5) end return v * 32 + rshift(v, 6) end -@native function Etc.size(kind: string, w: number, h: number): number? +function Etc.size(kind: string, w: number, h: number): number? local b = Etc.BLOCK[kind] return if b then ((w + 3) // 4) * ((h + 3) // 4) * b else nil end -@native function Etc.decode(kind: string, src: buffer, offset: number, w: number, h: number, out: buffer?, outOffset: number?, wide: boolean?): (buffer?, string?) +function Etc.decode(kind: string, src: buffer, offset: number, w: number, h: number, out: buffer?, outOffset: number?, wide: boolean?): (buffer?, string?) local bytes = Etc.BLOCK[kind] if not bytes then return nil, "unsupported: unknown block format " .. tostring(kind) @@ -66331,7 +66346,7 @@ end return Etc end -__FILES["codecs/image/Half"] = @native function() +__FILES["codecs/image/Half"] = function() @@ -66340,7 +66355,7 @@ local Half = {} local band, bor, rshift, lshift = bit32.band, bit32.bor, bit32.rshift, bit32.lshift -@native local function toFloat(h: number): number +local function toFloat(h: number): number local s = if h >= 32768 then -1 else 1 local e = band(rshift(h, 10), 31) local m = band(h, 1023) @@ -66361,7 +66376,7 @@ Half.TABLE = TABLE local scratch = buffer.create(4) -@native function Half.fromFloat(f: number): number +function Half.fromFloat(f: number): number if f ~= f then return 0x7E00 end @@ -66754,7 +66769,7 @@ end return Jpeg end -__FILES["codecs/image/Jpeg/Arith"] = @native function() +__FILES["codecs/image/Jpeg/Arith"] = function() @@ -66817,7 +66832,7 @@ local OVER = 0 local C, A, CT = 0, 0, -16 local st: buffer = buffer.create(STATS) -@native local function decode(s: number): number +local function decode(s: number): number while A < 0x8000 do CT -= 1 if CT < 0 then @@ -66868,7 +66883,7 @@ local st: buffer = buffer.create(STATS) return if sv >= 0x80 then 1 else 0 end -@native local function i16(v: number): number +local function i16(v: number): number v = band(v, 0xFFFF) return if v >= 0x8000 then v - 0x10000 else v end @@ -66901,7 +66916,7 @@ type ArithParams = { } -- DC difference (F.1.4.4.1 / figures F.19, F.21 - F.24) -@native local function dcDiff(c: ArithComp, L: number, U: number): number? +local function dcDiff(c: ArithComp, L: number, U: number): number? local base = c.dcTbl * 64 local s = base + c.ctx if decode(s) == 0 then @@ -66945,7 +66960,7 @@ type ArithParams = { end -- AC coefficients k = ss..se of one block (figure F.20) -@native local function acFirst(coef: buffer, off: number, tbl: number, ss: number, se: number, K: number, mul: number): boolean +local function acFirst(coef: buffer, off: number, tbl: number, ss: number, se: number, K: number, mul: number): boolean local base = 256 + tbl * 256 local k = ss while k <= se do @@ -66995,7 +67010,7 @@ end return true end -@native local function acRefine(coef: buffer, off: number, tbl: number, ss: number, se: number, al: number): boolean +local function acRefine(coef: buffer, off: number, tbl: number, ss: number, se: number, al: number): boolean local base = 256 + tbl * 256 local p1 = 2 ^ al local m1 = -p1 @@ -67038,11 +67053,11 @@ end return true end -@native function Arith.init(zigzag: buffer) +function Arith.init(zigzag: buffer) ZZ = zigzag end -@native function Arith.run(d: buffer, cleanLen: number, rst: { number }, nrst: number, Pm: ArithParams): boolean +function Arith.run(d: buffer, cleanLen: number, rst: { number }, nrst: number, Pm: ArithParams): boolean local comps = Pm.comps local nc = #comps local mode, ss, se, al, ri = Pm.mode, Pm.ss, Pm.se, Pm.al, Pm.ri @@ -67056,7 +67071,7 @@ end end local resetDc = mode == 0 or mode == 1 local resetAc = mode == 0 or mode == 3 or mode == 4 - @native local function reset() + local function reset() for i = 1, nc do local c = comps[i] if resetDc then @@ -67162,7 +67177,7 @@ end return Arith end -__FILES["codecs/image/Jpeg/Color"] = @native function() +__FILES["codecs/image/Jpeg/Color"] = function() @@ -67218,11 +67233,11 @@ type Params = { } -- jdcolor.c build_ycc_rgb_table -@native function Color.tables(maxv: number): (buffer, buffer, buffer, buffer) +function Color.tables(maxv: number): (buffer, buffer, buffer, buffer) local n = maxv + 1 local center = n // 2 local crr, cbb, crg, cbg = buffer.create(n * 4), buffer.create(n * 4), buffer.create(n * 4), buffer.create(n * 4) - @native local function fix(x: number): number + local function fix(x: number): number return math.floor(x * 65536 + 0.5) end for i = 0, maxv do @@ -67235,7 +67250,7 @@ type Params = { return crr, cbb, crg, cbg end -@native local function fetch(c: Comp, y: number, outW: number): (buffer, number) +local function fetch(c: Comp, y: number, outW: number): (buffer, number) local method = c.method local plane, stride, row = c.plane, c.stride, c.row if method == 0 then @@ -67307,7 +67322,7 @@ end end end -@native function Color.run(P: Params) +function Color.run(P: Params) local comps = P.comps local nc = #comps local space, outW, outH, maxv, out = P.space, P.outW, P.outH, P.maxv, P.pixels @@ -68159,7 +68174,7 @@ end return Decode end -__FILES["codecs/image/Jpeg/Encode"] = @native function() +__FILES["codecs/image/Jpeg/Encode"] = function() @@ -68201,7 +68216,7 @@ local CAP = 0 local ACC, NB = 0, 0 local GATHER = false -@native local function grow(n: number) +local function grow(n: number) if OP + n > CAP then local c = math.max(CAP * 2, OP + n + 1024) local nb = buffer.create(c) @@ -68211,19 +68226,19 @@ local GATHER = false end end -@native local function byte(v: number) +local function byte(v: number) grow(1) writeu8(OUT, OP, v) OP += 1 end -@native local function u16be(v: number) +local function u16be(v: number) byte(v // 256) byte(v % 256) end -- n bits of v (n <= 16), MSB first, with 0xFF stuffing -@native local function bits(v: number, n: number) +local function bits(v: number, n: number) if GATHER or n == 0 then return end @@ -68245,21 +68260,21 @@ end end end -@native local function flushBits() +local function flushBits() if NB > 0 then bits(0x7F, 8 - NB) -- pad with ones end ACC, NB = 0, 0 end -@native local function nbits(v: number): number +local function nbits(v: number): number return if v == 0 then 0 else 32 - countlz(v) end -- a derived table: u16 code + u8 size per symbol (jpeg_make_c_derived_tbl) type Derived = { code: buffer, size: buffer } -@native local function derive(counts: { number }, symbols: { number }): Derived +local function derive(counts: { number }, symbols: { number }): Derived local code, size = buffer.create(512), buffer.create(256) local c, k = 0, 1 for l = 1, 16 do @@ -68278,7 +68293,7 @@ type Derived = { code: buffer, size: buffer } end -- jchuff.c jpeg_gen_optimal_table: freq (0..256, 1-based +1) -> counts, symbols -@native local function optimal(freqIn: { number }): ({ number }, { number }) +local function optimal(freqIn: { number }): ({ number }, { number }) local freq = table.create(257, 0) local bitsT = table.create(34, 0) local codesize = table.create(257, 0) @@ -68382,7 +68397,7 @@ local acTab: { Derived } = {} local dcFreq: { { number } } = {} local acFreq: { { number } } = {} -@native local function symbol(t: Derived, freq: { number }, s: number) +local function symbol(t: Derived, freq: { number }, s: number) if GATHER then freq[s + 1] += 1 else @@ -68405,7 +68420,7 @@ type Comp = { last: number, } -@native local function dcDiff(c: Comp, diff: number) +local function dcDiff(c: Comp, diff: number) local t = diff local t2 = diff if t < 0 then @@ -68420,7 +68435,7 @@ type Comp = { end -- jchuff.c encode_one_block -@native local function blockSeq(c: Comp, off: number) +local function blockSeq(c: Comp, off: number) local coef = c.coef local dc = readi16(coef, off) dcDiff(c, dc - c.last) @@ -68459,7 +68474,7 @@ local CORR = table.create(1000, 0) :: { number } local curAc: Derived = { code = buffer.create(512), size = buffer.create(256) } local curAcFreq: { number } = {} -@native local function emitEobrun() +local function emitEobrun() if EOBRUN > 0 then local n = nbits(EOBRUN) - 1 symbol(curAc, curAcFreq, n * 16) @@ -68476,13 +68491,13 @@ local curAcFreq: { number } = {} end end -@native local function blockDcFirst(c: Comp, off: number, al: number) +local function blockDcFirst(c: Comp, off: number, al: number) local t2 = readi16(c.coef, off) // 2 ^ al dcDiff(c, t2 - c.last) c.last = t2 end -@native local function blockAcFirst(c: Comp, off: number, ss: number, se: number, al: number) +local function blockAcFirst(c: Comp, off: number, ss: number, se: number, al: number) local coef = c.coef local d = 2 ^ al local r = 0 @@ -68520,7 +68535,7 @@ end local absv = table.create(64, 0) -@native local function blockAcRefine(c: Comp, off: number, ss: number, se: number, al: number) +local function blockAcRefine(c: Comp, off: number, ss: number, se: number, al: number) local coef = c.coef local d = 2 ^ al local eob = 0 @@ -68581,7 +68596,7 @@ end type ScanSpec = { comps: { number }, ss: number, se: number, ah: number, al: number } -@native local function walk(comps: { Comp }, mcusX: number, mcusY: number, ri: number, onRestart: (number) -> (), fn: (Comp, number) -> ()) +local function walk(comps: { Comp }, mcusX: number, mcusY: number, ri: number, onRestart: (number) -> (), fn: (Comp, number) -> ()) local nc = #comps local units, ux if nc == 1 then @@ -68613,7 +68628,7 @@ type ScanSpec = { comps: { number }, ss: number, se: number, ah: number, al: num end end -@native local function dht(class: number, slot: number, counts: { number }, symbols: { number }) +local function dht(class: number, slot: number, counts: { number }, symbols: { number }) byte(0xFF) byte(0xC4) u16be(2 + 17 + #symbols) @@ -68626,7 +68641,7 @@ end end end -@native local function sos(comps: { Comp }, ss: number, se: number, ah: number, al: number, dcOnly: boolean, acOnly: boolean) +local function sos(comps: { Comp }, ss: number, se: number, ah: number, al: number, dcOnly: boolean, acOnly: boolean) byte(0xFF) byte(0xDA) u16be(6 + 2 * #comps) @@ -68643,7 +68658,7 @@ end end -- jccolor.c rgb_ycc_start tables (16-bit fixed point) -@native local function fix(x: number): number +local function fix(x: number): number return math.floor(x * 65536 + 0.5) end local YR, YG, YB = fix(0.29900), fix(0.58700), fix(0.11400) @@ -68651,7 +68666,7 @@ local CBR, CBG, HALF = fix(0.16874), fix(0.33126), fix(0.5) local CRG, CRB = fix(0.41869), fix(0.08131) local OFF = 128 * 65536 + 32768 - 1 -@native local function planes(px: buffer, w: number, h: number, bpp: number, gray: boolean): (buffer, buffer?, buffer?) +local function planes(px: buffer, w: number, h: number, bpp: number, gray: boolean): (buffer, buffer?, buffer?) local n = w * h local Y = buffer.create(n) if bpp == 1 then @@ -68685,7 +68700,7 @@ local OFF = 128 * 65536 + 32768 - 1 end -- jcsample.c downsampling: columns past w - 1 repeat the last one, rows past h - 1 the last row -@native local function downsample(src: buffer, w: number, h: number, hf: number, vf: number, outW: number, outH: number): buffer +local function downsample(src: buffer, w: number, h: number, hf: number, vf: number, outW: number, outH: number): buffer local out = buffer.create(outW * outH) for oy = 0, outH - 1 do local r0 = math.min(oy * vf, h - 1) * w @@ -68723,7 +68738,7 @@ type Options = { density: { unit: number, x: number, y: number }?, } -@native function Encode.run(px: buffer, w: number, h: number, bpp: number, o: Options): buffer +function Encode.run(px: buffer, w: number, h: number, bpp: number, o: Options): buffer OUT = buffer.create(math.max(1024, w * h // 2)) CAP = buffer.len(OUT) OP = 0 @@ -68862,7 +68877,7 @@ type Options = { end local ntab = if o.gray then 1 else 2 - @native local function restartMarker(n: number) + local function restartMarker(n: number) flushBits() byte(0xFF) byte(0xD0 + n) @@ -68878,7 +68893,7 @@ type Options = { for _, c in comps do c.last = 0 end - walk(comps, mcusX, mcusY, o.restart, @native function() + walk(comps, mcusX, mcusY, o.restart, function() for _, c in comps do c.last = 0 end @@ -68912,7 +68927,7 @@ type Options = { for _, c in comps do c.last = 0 end - walk(comps, mcusX, mcusY, o.restart, @native function(n: number) + walk(comps, mcusX, mcusY, o.restart, function(n: number) restartMarker(n) for _, c in comps do c.last = 0 @@ -68954,23 +68969,23 @@ type Options = { local isDc = ss == 0 local blockFn: (Comp, number) -> () if isDc and ah == 0 then - blockFn = @native function(c: Comp, off: number) + blockFn = function(c: Comp, off: number) blockDcFirst(c, off, al) end elseif isDc then - blockFn = @native function(c: Comp, off: number) + blockFn = function(c: Comp, off: number) bits(band(readi16(c.coef, off) // 2 ^ al, 1), 1) end elseif ah == 0 then - blockFn = @native function(c: Comp, off: number) + blockFn = function(c: Comp, off: number) blockAcFirst(c, off, ss, se, al) end else - blockFn = @native function(c: Comp, off: number) + blockFn = function(c: Comp, off: number) blockAcRefine(c, off, ss, se, al) end end - @native local function onRestart(n: number) + local function onRestart(n: number) emitEobrun() if not GATHER then restartMarker(n) @@ -68980,7 +68995,7 @@ type Options = { end EOBRUN, BE = 0, 0 end - @native local function pass() + local function pass() for _, c in sComps do c.last = 0 end @@ -69040,7 +69055,7 @@ end return Encode end -__FILES["codecs/image/Jpeg/Scan"] = @native function() +__FILES["codecs/image/Jpeg/Scan"] = function() @@ -69094,7 +69109,7 @@ end Scan.ZIGZAG = ZZ -- an over-subscribed table keeps the codes that fit; the rest decode as invalid -@native function Scan.buildTable(counts: { number }, symbols: { number }): buffer +function Scan.buildTable(counts: { number }, symbols: { number }): buffer local t = buffer.create(Scan.TABLE_SIZE) local code, k = 0, 0 local nsym = #symbols @@ -69143,7 +69158,7 @@ Scan.ZIGZAG = ZZ return t end -@native function Scan.destuff(src: buffer, pos: number, n: number, dst: buffer, rst: { number }): (number, number, number) +function Scan.destuff(src: buffer, pos: number, n: number, dst: buffer, rst: { number }): (number, number, number) local o, nr = 0, 0 while pos < n do local b = readu8(src, pos) @@ -69179,7 +69194,7 @@ end return pos, o, nr end -@native local function huff(d: buffer, pos: number, t: buffer): (number, number) +local function huff(d: buffer, pos: number, t: buffer): (number, number) local w = lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)) local f = readu16(t, rshift(w, 23) * 2) if f ~= 0 then @@ -69200,18 +69215,18 @@ end return readu8(t, T_VAL + idx), pos + l end -@native local function bits(d: buffer, pos: number, s: number): number +local function bits(d: buffer, pos: number, s: number): number return rshift(lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)), 32 - s) end -@native local function extend(v: number, s: number): number +local function extend(v: number, s: number): number if v < lshift(1, s - 1) then return v - lshift(1, s) + 1 end return v end -@native local function blockSeq(d: buffer, pos: number, coef: buffer, off: number, dct: buffer, act: buffer, pred: number): (number, number) +local function blockSeq(d: buffer, pos: number, coef: buffer, off: number, dct: buffer, act: buffer, pred: number): (number, number) local s s, pos = huff(d, pos, dct) if s ~= 0 then @@ -69258,7 +69273,7 @@ end return pos, pred end -@native local function blockDcFirst(d: buffer, pos: number, coef: buffer, off: number, dct: buffer, pred: number, al: number): (number, number) +local function blockDcFirst(d: buffer, pos: number, coef: buffer, off: number, dct: buffer, pred: number, al: number): (number, number) local s s, pos = huff(d, pos, dct) if s ~= 0 then @@ -69272,7 +69287,7 @@ end return pos, pred end -@native local function blockAcFirst(d: buffer, pos: number, coef: buffer, off: number, act: buffer, ss: number, se: number, al: number, eobrun: number): (number, number) +local function blockAcFirst(d: buffer, pos: number, coef: buffer, off: number, act: buffer, ss: number, se: number, al: number, eobrun: number): (number, number) if eobrun > 0 then return pos, eobrun - 1 end @@ -69319,7 +69334,7 @@ end end -- successive-approximation refinement of AC coefficients ss..se (as stb_image / libjpeg decode_mcu_AC_refine) -@native local function blockAcRefine(d: buffer, pos: number, coef: buffer, off: number, act: buffer, ss: number, se: number, al: number, eobrun: number): (number, number) +local function blockAcRefine(d: buffer, pos: number, coef: buffer, off: number, act: buffer, ss: number, se: number, al: number, eobrun: number): (number, number) local bit = lshift(1, al) if eobrun > 0 then for k = ss, se do @@ -69405,7 +69420,7 @@ type ScanParams = { hook: (() -> ())?, } -@native function Scan.run(d: buffer, cleanLen: number, rst: { number }, nrst: number, P: ScanParams): (number, boolean) +function Scan.run(d: buffer, cleanLen: number, rst: { number }, nrst: number, P: ScanParams): (number, boolean) local comps = P.comps local nc = #comps local mode, ss, se, al, ri = P.mode, P.ss, P.se, P.al, P.ri @@ -69564,7 +69579,7 @@ end return Tables end -__FILES["codecs/image/Jpeg/Yuv"] = @native function() +__FILES["codecs/image/Jpeg/Yuv"] = function() @@ -69574,7 +69589,7 @@ local readu16, writeu8, readu32, writeu32 = buffer.readu16, buffer.writeu8, buff local Yuv = {} -@native function Yuv.crop(src: buffer, stride: number, w: number, h: number, dst: buffer, doff: number) +function Yuv.crop(src: buffer, stride: number, w: number, h: number, dst: buffer, doff: number) local quads = w // 4 local rest = w - quads * 4 for y = 0, h - 1 do @@ -69592,7 +69607,7 @@ local Yuv = {} end end -@native function Yuv.rows(src: buffer, stride: number, w: number, h: number, dst: buffer, doff: number) +function Yuv.rows(src: buffer, stride: number, w: number, h: number, dst: buffer, doff: number) local oh = (h + 1) // 2 for y = 0, oh - 1 do local a = 2 * y * stride * 2 @@ -69604,7 +69619,7 @@ end end end -@native function Yuv.box(src: buffer, stride: number, w: number, h: number, dst: buffer, doff: number) +function Yuv.box(src: buffer, stride: number, w: number, h: number, dst: buffer, doff: number) local ow, oh = (w + 1) // 2, (h + 1) // 2 for y = 0, oh - 1 do local a = 2 * y * stride * 2 @@ -69618,7 +69633,7 @@ end end end -@native function Yuv.weave(top: buffer, toff: number, bottom: buffer, boff: number, rowBytes: number, rows: number, dst: buffer, doff: number) +function Yuv.weave(top: buffer, toff: number, bottom: buffer, boff: number, rowBytes: number, rows: number, dst: buffer, doff: number) for y = 0, rows - 1 do local k = y // 2 if y % 2 == 0 then @@ -69631,7 +69646,7 @@ end return Yuv end -__FILES["codecs/image/Pixels"] = @native function() +__FILES["codecs/image/Pixels"] = function() @@ -69642,7 +69657,7 @@ local band, rshift, bor, lshift = bit32.band, bit32.rshift, bit32.bor, bit32.lsh local Pixels = {} -@native function Pixels.palette(src: buffer, base: number, n: number, bgr: boolean?): buffer +function Pixels.palette(src: buffer, base: number, n: number, bgr: boolean?): buffer local pal = buffer.create(1024) local m = if base >= 0 then math.clamp(math.min(n, (buffer.len(src) - base) // 3), 0, 256) else 0 for i = 0, 255 do @@ -69660,7 +69675,7 @@ local Pixels = {} return pal end -@native function Pixels.indexed(src: buffer, base: number, stride: number, bpp: number, dst: buffer, w: number, h: number, +function Pixels.indexed(src: buffer, base: number, stride: number, bpp: number, dst: buffer, w: number, h: number, topDown: boolean, pal: buffer) local mask = lshift(1, bpp) - 1 for r = 0, h - 1 do @@ -69688,7 +69703,7 @@ 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 -@native function Pixels.rgb555(src: buffer, base: number, stride: number, dst: buffer, w: number, h: number, topDown: boolean) +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 @@ -69701,7 +69716,7 @@ end end -- 24 bpp BI_RGB: B, G, R -@native function Pixels.bgr24(src: buffer, base: number, stride: number, dst: buffer, w: number, h: number, topDown: boolean) +function Pixels.bgr24(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 @@ -69714,7 +69729,7 @@ end end -- 32 bpp B, G, R, A (BI_RGB, or BITFIELDS with the standard masks) -@native function Pixels.bgra32(src: buffer, base: number, stride: number, dst: buffer, w: number, h: number, +function Pixels.bgra32(src: buffer, base: number, stride: number, dst: buffer, w: number, h: number, topDown: boolean): number local aor = 0 for r = 0, h - 1 do @@ -69729,7 +69744,7 @@ end return rshift(aor, 24) end -@native function Pixels.masked(src: buffer, base: number, stride: number, bpp: number, dst: buffer, w: number, h: number, +function Pixels.masked(src: buffer, base: number, stride: number, bpp: number, dst: buffer, w: number, h: number, topDown: boolean, shr: number, mr: number, tr: buffer, shg: number, mg: number, tg: buffer, shb: number, mb: number, tb: buffer, sha: number, ma: number, ta: buffer): number local bytes = rshift(bpp, 3) @@ -69760,14 +69775,14 @@ end end -- 32-bit images whose alpha channel is all zero are opaque -@native function Pixels.opaque(dst: buffer, n: number) +function Pixels.opaque(dst: buffer, n: number) for i = 0, n - 1 do writeu8(dst, i * 4 + 3, 255) end end -- RLE8 / RLE4: pixels skipped by a delta or an early end of line / bitmap stay transparent -@native function Pixels.rle(src: buffer, pos: number, stop: number, rle4: boolean, dst: buffer, w: number, h: number, +function Pixels.rle(src: buffer, pos: number, stop: number, rle4: boolean, dst: buffer, w: number, h: number, topDown: boolean, pal: buffer): number local x, y = 0, 0 local written = 0 @@ -69840,7 +69855,7 @@ end return written end -@native function Pixels.encode24(src: buffer, w: number, h: number, dst: buffer, base: number, stride: number) +function Pixels.encode24(src: buffer, w: number, h: number, dst: buffer, base: number, stride: number) for y = 0, h - 1 do local s = y * w * 4 local d = base + (h - 1 - y) * stride @@ -69854,7 +69869,7 @@ end end end -@native function Pixels.encode32(src: buffer, w: number, h: number, dst: buffer, base: number) +function Pixels.encode32(src: buffer, w: number, h: number, dst: buffer, base: number) for y = 0, h - 1 do local s = y * w * 4 local d = base + (h - 1 - y) * w * 4 @@ -69865,7 +69880,7 @@ end end end -@native function Pixels.encode8(src: buffer, w: number, h: number, dst: buffer, base: number, stride: number, idx: { [number]: number }) +function Pixels.encode8(src: buffer, w: number, h: number, dst: buffer, base: number, stride: number, idx: { [number]: number }) for y = 0, h - 1 do local s = y * w * 4 local d = base + (h - 1 - y) * stride @@ -69875,7 +69890,7 @@ end end end -@native function Pixels.colours(src: buffer, n: number, max: number): ({ number }, boolean) +function Pixels.colours(src: buffer, n: number, max: number): ({ number }, boolean) local seen: { [number]: boolean } = {} local list: { number } = {} local alpha = false @@ -69895,7 +69910,7 @@ end return Pixels end -__FILES["codecs/image/Quantize"] = @native function() +__FILES["codecs/image/Quantize"] = function() @@ -69920,7 +69935,7 @@ type MapOptions = { local BINS = 32768 -- 5 bits per channel -@native local function count(pixels: buffer, n: number): (buffer, buffer) +local function count(pixels: buffer, n: number): (buffer, buffer) -- per bin: u32 count; f64 sums of r, g, b local cnt = buffer.create(BINS * 4) local sums = buffer.create(BINS * 24) @@ -69939,7 +69954,7 @@ local BINS = 32768 -- 5 bits per channel return cnt, sums end -@native local function mean(cnt: buffer, sums: buffer, bins: { number }, lo: number, hi: number): Color +local function mean(cnt: buffer, sums: buffer, bins: { number }, lo: number, hi: number): Color local n, r, g, b = 0, 0, 0, 0 for i = lo, hi do local bin = bins[i] @@ -69954,7 +69969,7 @@ end return { floor(r / n + 0.5), floor(g / n + 0.5), floor(b / n + 0.5), 255 } end -@native local function medianCut(cnt: buffer, sums: buffer, maxColors: number): { Color } +local function medianCut(cnt: buffer, sums: buffer, maxColors: number): { Color } local bins: { number } = {} for bin = 0, BINS - 1 do if readu32(cnt, bin * 4) > 0 then @@ -69965,7 +69980,7 @@ end return {} end local boxes: { { number } } = {} - @native local function channel(bin: number, c: number): number + local function channel(bin: number, c: number): number if c == 0 then return bin // 1024 elseif c == 1 then @@ -69973,7 +69988,7 @@ end end return bin % 32 end - @native local function stats(box: { number }): (number, number, number) + local function stats(box: { number }): (number, number, number) local mins, maxs = { 31, 31, 31 }, { 0, 0, 0 } local n = 0 for i = box[1], box[2] do @@ -69998,7 +70013,7 @@ end end return best, range, n end - @native local function scored(lo: number, hi: number): { number } + local function scored(lo: number, hi: number): { number } local c, range, n = stats({ lo, hi }) return { lo, hi, c, if hi > lo then range * math.sqrt(n) else 0 } end @@ -70048,7 +70063,7 @@ end end -- octree over the histogram bins: 5 levels, one bit of each channel per level -@native local function octree(cnt: buffer, sums: buffer, maxColors: number): { Color } +local function octree(cnt: buffer, sums: buffer, maxColors: number): { Color } local child: { number } = {} -- node * 8 + k -> node (0 = none) local n: { number } = {} local sr: { number }, sg: { number }, sb: { number } = {}, {}, {} @@ -70096,7 +70111,7 @@ end end end -- fold the deepest inner nodes (fewest pixels first, ties by creation order) until few enough leaves remain - @native local function fold(node: number): number + local function fold(node: number): number local merged = 0 for k = 1, 8 do local slot = (node - 1) * 8 + k @@ -70113,7 +70128,7 @@ end leaf[node] = true return merged - 1 end - @native local function subtotal(node: number): number + local function subtotal(node: number): number local s = 0 for k = 1, 8 do local ch = child[(node - 1) * 8 + k] @@ -70132,7 +70147,7 @@ end for i, node in list do order[i] = { node, subtotal(node), i } end - table.sort(order, @native function(a: { number }, b: { number }): boolean + table.sort(order, function(a: { number }, b: { number }): boolean if a[2] ~= b[2] then return a[2] < b[2] end @@ -70146,7 +70161,7 @@ end end end local pal: { Color } = {} - @native local function walk(node: number) + local function walk(node: number) if leaf[node] then local c = n[node] if c > 0 then @@ -70169,7 +70184,7 @@ end return pal end -@native function Quantize.palette(pixels: buffer, w: number, h: number, maxColors: number, opts: PaletteOptions?): ({ Color }, boolean) +function Quantize.palette(pixels: buffer, w: number, h: number, maxColors: number, opts: PaletteOptions?): ({ Color }, boolean) if type(pixels) ~= "buffer" or type(w) ~= "number" or type(h) ~= "number" or w < 0 or h < 0 or blen(pixels) < w * h * 4 then return {}, false end @@ -70204,7 +70219,7 @@ end return medianCut(cnt, sums, maxc), false end -@native function Quantize.map(pixels: buffer, w: number, h: number, palette: { Color }, opts: MapOptions?): buffer +function Quantize.map(pixels: buffer, w: number, h: number, palette: { Color }, opts: MapOptions?): buffer if type(pixels) ~= "buffer" or type(w) ~= "number" or type(h) ~= "number" or w < 0 or h < 0 or blen(pixels) < w * h * 4 or type(palette) ~= "table" then return buffer.create(0) end @@ -70253,7 +70268,7 @@ end return out end local cache: { [number]: number } = {} - @native local function nearest(r: number, g: number, b: number): number + local function nearest(r: number, g: number, b: number): number local key = r * 65536 + g * 256 + b local hit = cache[key] if hit then @@ -70342,7 +70357,7 @@ end return out end -@native function Quantize.quantize(pixels: buffer, w: number, h: number, maxColors: number, opts: any?): (buffer, { Color }, boolean) +function Quantize.quantize(pixels: buffer, w: number, h: number, maxColors: number, opts: any?): (buffer, { Color }, boolean) local pal, exact = Quantize.palette(pixels, w, h, maxColors, opts) local mo = opts if exact and opts and opts.dither then @@ -70354,7 +70369,7 @@ end return Quantize end -__FILES["codecs/image/Raster"] = @native function() +__FILES["codecs/image/Raster"] = function() @@ -70385,7 +70400,7 @@ local LIMIT = 1e7 -- coordinates beyond this (device pixels) are treated as brok -- transforms { a, b, c, d, e, f } in SVG matrix order: x' = a x + c y + e, y' = b x + d y + f Raster.IDENTITY = table.freeze({ 1, 0, 0, 1, 0, 0 }) -@native function Raster.multiply(m: Transform, n: Transform): Transform +function Raster.multiply(m: Transform, n: Transform): Transform return { m[1] * n[1] + m[3] * n[2], m[2] * n[1] + m[4] * n[2], @@ -70395,17 +70410,17 @@ Raster.IDENTITY = table.freeze({ 1, 0, 0, 1, 0, 0 }) m[2] * n[5] + m[4] * n[6] + m[6], } end -@native function Raster.translate(tx: number, ty: number): Transform +function Raster.translate(tx: number, ty: number): Transform return { 1, 0, 0, 1, tx, ty } end -@native function Raster.scale(sx: number, sy: number?): Transform +function Raster.scale(sx: number, sy: number?): Transform return { sx, 0, 0, sy or sx, 0, 0 } end -@native function Raster.rotate(radians: number): Transform +function Raster.rotate(radians: number): Transform local c, s = math.cos(radians), math.sin(radians) return { c, s, -s, c, 0, 0 } end -@native function Raster.invert(m: Transform): Transform? +function Raster.invert(m: Transform): Transform? local det = m[1] * m[4] - m[2] * m[3] if det == 0 or det ~= det then return nil @@ -70414,7 +70429,7 @@ end local a, b, c, d = m[4] * id, -m[2] * id, -m[3] * id, m[1] * id return { a, b, c, d, -(a * m[5] + c * m[6]), -(b * m[5] + d * m[6]) } end -@native function Raster.apply(m: Transform, x: number, y: number): (number, number) +function Raster.apply(m: Transform, x: number, y: number): (number, number) return m[1] * x + m[3] * y + m[5], m[2] * x + m[4] * y + m[6] end @@ -70422,33 +70437,33 @@ local Builder = {} Builder.__index = Builder type Builder = typeof(setmetatable({} :: { cmds: Path }, Builder)) -@native function Raster.path(): Builder +function Raster.path(): Builder return setmetatable({ cmds = {} :: Path }, Builder) end -@native function Builder.moveTo(self: Builder, x: number, y: number): Builder +function Builder.moveTo(self: Builder, x: number, y: number): Builder table.insert(self.cmds, { op = "moveTo", x, y }) return self end -@native function Builder.lineTo(self: Builder, x: number, y: number): Builder +function Builder.lineTo(self: Builder, x: number, y: number): Builder table.insert(self.cmds, { op = "lineTo", x, y }) return self end -@native function Builder.quadTo(self: Builder, cx: number, cy: number, x: number, y: number): Builder +function Builder.quadTo(self: Builder, cx: number, cy: number, x: number, y: number): Builder table.insert(self.cmds, { op = "quadTo", cx, cy, x, y }) return self end -@native function Builder.cubicTo(self: Builder, c1x: number, c1y: number, c2x: number, c2y: number, x: number, y: number): Builder +function Builder.cubicTo(self: Builder, c1x: number, c1y: number, c2x: number, c2y: number, x: number, y: number): Builder table.insert(self.cmds, { op = "cubicTo", c1x, c1y, c2x, c2y, x, y }) return self end -@native function Builder.close(self: Builder): Builder +function Builder.close(self: Builder): Builder table.insert(self.cmds, { op = "close" } :: Cmd) return self end -@native function Builder.rect(self: Builder, x: number, y: number, w: number, h: number): Builder +function Builder.rect(self: Builder, x: number, y: number, w: number, h: number): Builder return self:moveTo(x, y):lineTo(x + w, y):lineTo(x + w, y + h):lineTo(x, y + h):close() end -@native function Builder.ellipse(self: Builder, cx: number, cy: number, rx: number, ry: number): Builder +function Builder.ellipse(self: Builder, cx: number, cy: number, rx: number, ry: number): Builder local k = 0.5522847498307936 -- 4/3 (sqrt 2 - 1): cubic quarter circle self:moveTo(cx + rx, cy) self:cubicTo(cx + rx, cy + ry * k, cx + rx * k, cy + ry, cx, cy + ry) @@ -70458,7 +70473,7 @@ end return self:close() end -@native local function commands(path: any): Path? +local function commands(path: any): Path? if type(path) ~= "table" then return nil end @@ -70468,7 +70483,7 @@ end return path end -@native local function operands(c: any, n: number): boolean +local function operands(c: any, n: number): boolean if type(c) ~= "table" then return false end @@ -70481,7 +70496,7 @@ end return true end -@native local function flatten(path: any, transform: Transform?, tolerance: number?, minLen: number): ({ { number } }, number?, number?, number?, number?) +local function flatten(path: any, transform: Transform?, tolerance: number?, minLen: number): ({ { number } }, number?, number?, number?, number?) local cmds = commands(path) local polys: { { number } } = {} if not cmds then @@ -70500,7 +70515,7 @@ end local px, py = 0, 0 local sx, sy = 0, 0 local bx0, by0, bx1, by1 = math.huge, math.huge, -math.huge, -math.huge - @native local function point(x: number, y: number) + local function point(x: number, y: number) local poly = cur :: { number } local n = #poly poly[n + 1] = x @@ -70518,7 +70533,7 @@ end by1 = y end end - @native local function start(x: number, y: number) + local function start(x: number, y: number) if cur and #cur >= minLen then table.insert(polys, cur) end @@ -70602,12 +70617,12 @@ end return polys, bx0, by0, bx1, by1 end -@native function Raster.flatten(path: any, transform: Transform?, tolerance: number?): ({ { number } }, number?, number?, number?, number?) +function Raster.flatten(path: any, transform: Transform?, tolerance: number?): ({ { number } }, number?, number?, number?, number?) return flatten(path, transform, tolerance, 6) end -- the signed area each pixel gains from one edge (font-rs draw_line) -@native local function line(acc: buffer, S: number, H: number, x0: number, y0: number, x1: number, y1: number) +local function line(acc: buffer, S: number, H: number, x0: number, y0: number, x1: number, y1: number) if y0 == y1 then return end @@ -70687,10 +70702,10 @@ end end -- edges split at x = 0 / x = W: the parts outside go onto the border, whose cover still applies to the row -@native local function clampx(x: number, W: number): number +local function clampx(x: number, W: number): number return if x < 0 then 0 elseif x > W then W else x end -@native local function edge(acc: buffer, S: number, W: number, H: number, x0: number, y0: number, x1: number, y1: number) +local function edge(acc: buffer, S: number, W: number, H: number, x0: number, y0: number, x1: number, y1: number) if y0 == y1 or not (abs(x0) < LIMIT and abs(y0) < LIMIT and abs(x1) < LIMIT and abs(y1) < LIMIT) then return -- horizontal, or non-finite (NaN fails every comparison) end @@ -70727,7 +70742,7 @@ end line(acc, S, H, clampx(px, W), py, clampx(x1, W), y1) end -@native function Raster.mask(path: any, opts: Options?): (Mask?, string?) +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 @@ -70787,7 +70802,7 @@ end return { x = X0, y = Y0, width = W, height = H, coverage = cov }, nil end -@native function Raster.fill(img: any, path: any, paint: any, opts: Options?): (boolean, string?) +function Raster.fill(img: any, path: any, paint: any, opts: Options?): (boolean, string?) if type(img) ~= "table" or type(img.pixels) ~= "buffer" or type(img.width) ~= "number" or type(img.height) ~= "number" then return false, "fill: expected an rgba8 image" end @@ -70862,7 +70877,7 @@ type StrokeOptions = { -- push a polygon (flat x, y list) as a closed subpath with positive orientation, so overlapping pieces add up -- under the nonzero rule -@native local function polygon(out: Path, pts: { number }) +local function polygon(out: Path, pts: { number }) local n = #pts if n < 6 then return @@ -70889,7 +70904,7 @@ type StrokeOptions = { table.insert(out, { op = "close" } :: Cmd) end -@native local function arcPoints(cx: number, cy: number, r: number, a0: number, a1: number, tol: number, pts: { number }) +local function arcPoints(cx: number, cy: number, r: number, a0: number, a1: number, tol: number, pts: { number }) local da = a1 - a0 local step = 2 * math.acos(math.clamp(1 - tol / max(r, 1e-9), -1, 1)) local n = max(1, min(256, ceil(abs(da) / max(step, 0.01)))) @@ -70900,7 +70915,7 @@ end end end -@native function Raster.stroke(path: any, opts: StrokeOptions?): Path +function Raster.stroke(path: any, opts: StrokeOptions?): Path local o: StrokeOptions = opts or {} local hw = (if type(o.width) == "number" and o.width > 0 then o.width else 1) / 2 local join = o.join or "miter" @@ -70980,7 +70995,7 @@ end local nx, ny = -uy * hw, ux * hw polygon(out, { x0 + nx, y0 + ny, x1 + nx, y1 + ny, x1 - nx, y1 - ny, x0 - nx, y0 - ny }) end - @native local function joinAt(k: number, s0: number, s1: number) + local function joinAt(k: number, s0: number, s1: number) local x, y = p[2 * k + 1], p[2 * k + 2] local ax, ay = dirs[2 * s0 + 1], dirs[2 * s0 + 2] local bx, by = dirs[2 * s1 + 1], dirs[2 * s1 + 2] @@ -71051,7 +71066,7 @@ end return Raster end -__FILES["codecs/image/Texel"] = @native function() +__FILES["codecs/image/Texel"] = function() @@ -71077,7 +71092,7 @@ local band, rshift, lshift = bit32.band, bit32.rshift, bit32.lshift local HALF = Half.TABLE local FORMATS: { [string]: Desc } = {} -@native local function array(name: string, size: number, typ: string, order: string) +local function array(name: string, size: number, typ: string, order: string) FORMATS[name] = { bytes = size * #order, kind = "array", size = size, type = typ, order = order } end for _, o in { "r", "rg", "rgb", "rgba" } do @@ -71105,7 +71120,7 @@ array("l16", 2, "unorm", "l") array("la16", 2, "unorm", "la") array("a16", 2, "unorm", "a") -@native local function packed(name: string, bytes: number, spec: { any }) +local function packed(name: string, bytes: number, spec: { any }) local ch: { Channel } = {} for i = 1, #spec, 3 do table.insert(ch, { c = spec[i], shift = spec[i + 1], bits = spec[i + 2] }) @@ -71135,7 +71150,7 @@ FORMATS.grgb = { bytes = 2, kind = "pair", order = "grgb" } FORMATS.ayuv = { bytes = 4, kind = "ayuv" } Texel.FORMATS = FORMATS -@native function Texel.masked(bytes: number, r: number, g: number, b: number, a: number, luminance: boolean?): Desc? +function Texel.masked(bytes: number, r: number, g: number, b: number, a: number, luminance: boolean?): Desc? if bytes < 1 or bytes > 4 then return nil end @@ -71160,7 +71175,7 @@ Texel.FORMATS = FORMATS return { bytes = bytes, kind = "packed", channels = ch } end -@native function Texel.size(fmt: string | Desc, w: number, h: number): number? +function Texel.size(fmt: string | Desc, w: number, h: number): number? local d = if type(fmt) == "string" then FORMATS[fmt] else fmt if not d then return nil @@ -71168,7 +71183,7 @@ end return if d.kind == "pair" then ((w + 1) // 2) * 4 * h else d.bytes * w * h end -@native local function nativeOf(d: Desc): string +local function nativeOf(d: Desc): string if d.kind == "array" then local t, s = d.type, d.size :: number if t == "float" or t == "snorm" or t == "sint" or (t == "uint" and s > 1) then @@ -71186,7 +71201,7 @@ end end Texel.nativeOf = nativeOf -@native local function uf11(v: number): number +local function uf11(v: number): number local e, m = rshift(v, 6), band(v, 63) if e == 0 then return m / 64 * 2 ^ -14 @@ -71195,7 +71210,7 @@ Texel.nativeOf = nativeOf end return (1 + m / 64) * 2 ^ (e - 15) end -@native local function uf10(v: number): number +local function uf10(v: number): number local e, m = rshift(v, 5), band(v, 31) if e == 0 then return m / 32 * 2 ^ -14 @@ -71205,7 +71220,7 @@ end return (1 + m / 32) * 2 ^ (e - 15) end -@native local function component(src: buffer, q: number, size: number, typ: string): (number, number) +local function component(src: buffer, q: number, size: number, typ: string): (number, number) if typ == "unorm" then if size == 1 then local v = readu8(src, q) @@ -71238,7 +71253,7 @@ end return v, math.clamp(v, 0, 255) end -@native local function ycc(y: number, u: number, v: number, a: number): number +local function ycc(y: number, u: number, v: number, a: number): number local c, d, e = 1.164 * (y - 16), u - 128, v - 128 local r = math.clamp(math.floor(c + 1.596 * e + 0.5), 0, 255) local g = math.clamp(math.floor(c - 0.392 * d - 0.813 * e + 0.5), 0, 255) @@ -71246,7 +71261,7 @@ end return r + g * 256 + b * 65536 + a * 16777216 end -@native local function yuv(d: Desc, src: buffer, offset: number, w: number, h: number, pitch: number, dst: buffer): buffer +local function yuv(d: Desc, src: buffer, offset: number, w: number, h: number, pitch: number, dst: buffer): buffer local n = 0 local order = d.order or "" for y = 0, h - 1 do @@ -71275,7 +71290,7 @@ end return dst end -@native function Texel.decode(fmt: string | Desc, src: buffer, offset: number, w: number, h: number, native: boolean?, rowPitch: number?): (buffer?, string) +function Texel.decode(fmt: string | Desc, src: buffer, offset: number, w: number, h: number, native: boolean?, rowPitch: number?): (buffer?, string) local d = if type(fmt) == "string" then FORMATS[fmt] else fmt if not d then return nil, "unsupported: unknown texel format " .. tostring(fmt) @@ -71406,7 +71421,7 @@ end local g: number = if nine then band(rshift(v, 9), 511) * sc else uf11(band(rshift(v, 11), 2047)) local b: number = if nine then band(rshift(v, 18), 511) * sc else uf10(rshift(v, 22)) if out == "rgba8" then - @native local function q(x: number): number + local function q(x: number): number return if x ~= x or x <= 0 then 0 elseif x >= 1 then 255 else math.floor(x * 255 + 0.5) end writeu32(dst, n, q(r) + q(g) * 256 + q(b) * 65536 + 0xFF000000) @@ -71699,7 +71714,7 @@ Vp8.setAlpha = Yuv.setAlpha return Vp8 end -__FILES["codecs/image/Vp8/Decode"] = @native function() +__FILES["codecs/image/Vp8/Decode"] = function() @@ -71739,7 +71754,7 @@ for r = 1, 255 do SHIFT[r + 1] = s end -@native local function load(br: Br) +local function load(br: Br) local p = br.pos if p + 3 <= br.limit then local b = br.buf @@ -71759,7 +71774,7 @@ end end end -@native local function newBr(buf: buffer, off: number, len: number): Br +local function newBr(buf: buffer, off: number, len: number): Br local br = { buf = buf, pos = off, limit = off + len, value = 0, bits = -8, range = 254, eof = false } load(br) return br @@ -71767,7 +71782,7 @@ end -- branchless getBit: bit = value >> bits > split; range = bit ? range - split : split + 1; -- value -= bit * (split + 1) << bits -@native local function getBit(br: Br, prob: number): number +local function getBit(br: Br, prob: number): number if br.bits < 0 then load(br) end @@ -71783,7 +71798,7 @@ end return bit end -@native local function getValue(br: Br, n: number): number +local function getValue(br: Br, n: number): number local v = 0 for i = n - 1, 0, -1 do v += getBit(br, 0x80) * 2 ^ i @@ -71791,7 +71806,7 @@ end return v end -@native local function getSignedValue(br: Br, n: number): number +local function getSignedValue(br: Br, n: number): number local v = getValue(br, n) return if getBit(br, 0x80) == 1 then -v else v end @@ -71837,7 +71852,7 @@ type State = { pred: buffer?, } -@native function Decode.new(): State +function Decode.new(): State return { proba = table.clone(COEFF_PROBA0), ymodeProb = table.clone(Tables.YMODE_PROB), @@ -71873,12 +71888,12 @@ type State = { } end -@native function Decode.reset(st: State) +function Decode.reset(st: State) st.hasKey = false st.last, st.golden, st.alt = nil, nil, nil end -@native function Decode.header(buf: buffer, off: number, len: number): (any, string?) +function Decode.header(buf: buffer, off: number, len: number): (any, string?) if len < 3 then return nil, "truncated: frame tag" end @@ -71911,7 +71926,7 @@ end return h, nil end -@native local function getLargeValue(br: Br, P: { number }, p: number): number +local function getLargeValue(br: Br, P: { number }, p: number): number local v if getBit(br, P[p + 4]) == 0 then if getBit(br, P[p + 5]) == 0 then @@ -71942,7 +71957,7 @@ end end -- coefficients are dequantized to int16 as libwebp stores them, in raster order -@native local function getCoeffs(br: Br, P: { number }, t: number, ctx: number, dqDc: number, dqAc: number, n: number, out: buffer, o: number): number +local function getCoeffs(br: Br, P: { number }, t: number, ctx: number, dqDc: number, dqAc: number, n: number, out: buffer, o: number): number local tb = t * 8 local p = ((tb + BANDS[n + 1]) * 3 + ctx) * 11 local buf, limit = br.buf, br.limit @@ -72082,13 +72097,13 @@ end return 16 end -@native local function nzCode(acc: number, nz: number, dcNz: number): number +local function nzCode(acc: number, nz: number, dcNz: number): number return acc * 4 + (if nz > 3 then 3 elseif nz > 1 then 2 else dcNz) end -- the inverse Walsh-Hadamard transform of the 16 Y2 coefficients into the DC of the 16 luma blocks local whtTmp = table.create(16, 0) -@native local function transformWHT(inp: buffer, out: buffer, o: number) +local function transformWHT(inp: buffer, out: buffer, o: number) for i = 0, 3 do local i0, i4, i8, i12 = readi16(inp, i * 2), readi16(inp, (4 + i) * 2), readi16(inp, (8 + i) * 2), readi16(inp, (12 + i) * 2) local a0 = i0 + i12 @@ -72121,20 +72136,20 @@ local U_OFF = Y_OFF + BPS * 16 + BPS local V_OFF = U_OFF + 16 local YUV_SIZE = BPS * 17 + BPS * 9 -@native local function clip8(v: number): number +local function clip8(v: number): number return if v < 0 then 0 elseif v > 255 then 255 else v end -- the inverse DCT of one block (libwebp TransformOne) added to dst local C1, C2 = 20091, 35468 local idctTmp = table.create(16, 0) -@native local function mul1(a: number): number +local function mul1(a: number): number return ((a * C1) // 65536) + a end -@native local function mul2(a: number): number +local function mul2(a: number): number return (a * C2) // 65536 end -@native local function transformOne(c: buffer, o: number, b: buffer, dst: number) +local function transformOne(c: buffer, o: number, b: buffer, dst: number) for i = 0, 3 do local i0, i4, i8, i12 = readi16(c, o + i * 2), readi16(c, o + (4 + i) * 2), readi16(c, o + (8 + i) * 2), readi16(c, o + (12 + i) * 2) local a = i0 + i8 @@ -72160,7 +72175,7 @@ end end end -@native local function transformDC(c: buffer, o: number, b: buffer, dst: number) +local function transformDC(c: buffer, o: number, b: buffer, dst: number) local dc = (readi16(c, o) + 4) // 8 for j = 0, 3 do local row = dst + j * BPS @@ -72171,7 +72186,7 @@ end end -- code: 3 = full transform, 2 = only the first three coefficients (the same result as the full one), 1 = DC only -@native local function doTransform(code: number, c: buffer, o: number, b: buffer, dst: number) +local function doTransform(code: number, c: buffer, o: number, b: buffer, dst: number) if code >= 2 then transformOne(c, o, b, dst) elseif code == 1 then @@ -72179,7 +72194,7 @@ end end end -@native local function doUVTransform(bits: number, c: buffer, o: number, b: buffer, dst: number) +local function doUVTransform(bits: number, c: buffer, o: number, b: buffer, dst: number) if band(bits, 0xff) ~= 0 then if band(bits, 0xaa) ~= 0 then transformOne(c, o, b, dst) @@ -72204,7 +72219,7 @@ end end -- prediction: modes 0 DC, 1 TM, 2 VE, 3 HE; 4 DC no top, 5 DC no left, 6 DC no top-left (16x16 and chroma) -@native local function fill(b: buffer, dst: number, size: number, v: number) +local function fill(b: buffer, dst: number, size: number, v: number) for j = 0, size - 1 do local o = dst + j * BPS for i = o, o + size - 4, 4 do @@ -72213,7 +72228,7 @@ end end end -@native local function trueMotion(b: buffer, dst: number, size: number) +local function trueMotion(b: buffer, dst: number, size: number) local tl = readu8(b, dst - BPS - 1) for y = 0, size - 1 do local row = dst + y * BPS @@ -72224,7 +72239,7 @@ end end end -@native local function predictBlock(b: buffer, dst: number, size: number, mode: number) +local function predictBlock(b: buffer, dst: number, size: number, mode: number) local shift = if size == 16 then 5 else 4 if mode == 0 then local dc = size @@ -72266,15 +72281,15 @@ end end end -@native local function avg3(a: number, b: number, c: number): number +local function avg3(a: number, b: number, c: number): number return rshift(a + 2 * b + c + 2, 2) end -@native local function avg2(a: number, b: number): number +local function avg2(a: number, b: number): number return rshift(a + b + 1, 1) end -- 4x4 prediction (libwebp VP8PredLuma4): 0 DC, 1 TM, 2 VE, 3 HE, 4 RD, 5 VR, 6 LD, 7 VL, 8 HD, 9 HU -@native local function predict4(b: buffer, dst: number, mode: number) +local function predict4(b: buffer, dst: number, mode: number) if mode == 0 then local dc = 4 for i = 0, 3 do @@ -72443,7 +72458,7 @@ end end end -@native local function checkMode(mbx: number, mby: number, mode: number): number +local function checkMode(mbx: number, mby: number, mode: number): number if mode == 0 then if mbx == 0 then return if mby == 0 then 6 else 5 @@ -72458,7 +72473,7 @@ end -- logical shifts of the value plus a bias: (a + 4) >> 3 = rshift(a + 4 + 1024, 3) - 128 for a >= -1024. -- SimpleVFilter16 / SimpleHFilter16; a position whose filter value a is 0 changes nothing (skipped before the mask) -@native local function simpleFilter(b: buffer, p: number, step: number, along: number, thresh: number) +local function simpleFilter(b: buffer, p: number, step: number, along: number, thresh: number) local t2 = 2 * thresh + 1 for _ = 1, 16 do local p1, p0, q0, q1 = readu8(b, p - 2 * step), readu8(b, p - step), readu8(b, p), readu8(b, p + step) @@ -72487,7 +72502,7 @@ end end -- the macroblock edge filter (FilterLoop26) -@native local function filterEdge(b: buffer, p: number, hs: number, vs: number, size: number, thresh: number, it: number, hevT: number) +local function filterEdge(b: buffer, p: number, hs: number, vs: number, size: number, thresh: number, it: number, hevT: number) local t2 = 2 * thresh + 1 for _ = 1, size do local p1, p0, q0, q1 = readu8(b, p - 2 * hs), readu8(b, p - hs), readu8(b, p), readu8(b, p + hs) @@ -72546,7 +72561,7 @@ end end -- the inner edge filter (FilterLoop24); nothing changes when q0 == p0 and p1 == q1 -@native local function filterInner(b: buffer, p: number, hs: number, vs: number, size: number, thresh: number, it: number, hevT: number) +local function filterInner(b: buffer, p: number, hs: number, vs: number, size: number, thresh: number, it: number, hevT: number) local t2 = 2 * thresh + 1 for _ = 1, size do local p1, p0, q0, q1 = readu8(b, p - 2 * hs), readu8(b, p - hs), readu8(b, p), readu8(b, p + hs) @@ -72603,7 +72618,7 @@ local MV_UPDATE = Tables.MV_UPDATE local MODE_LF = { 1, 1, 1, 1, 0, 1, 2, 2, 2, 3 } -- a 4x4 intra mode with the fixed probabilities P[o + 1 .. o + 9] (libvpx vp8_bmode_tree, libwebp's numbering) -@native local function readBMode(br: Br, P: { number }, o: number): number +local function readBMode(br: Br, P: { number }, o: number): number if getBit(br, P[o + 1]) == 0 then return 0 elseif getBit(br, P[o + 2]) == 0 then @@ -72624,7 +72639,7 @@ local MODE_LF = { 1, 1, 1, 1, 0, 1, 2, 2, 2, 3 } end -- one motion vector component (libvpx read_mvcomponent) with the probabilities P[o + 1 .. o + 19], in quarter pixels -@native local function readMvComponent(br: Br, P: { number }, o: number): number +local function readMvComponent(br: Br, P: { number }, o: number): number local x if getBit(br, P[o + 1]) == 1 then -- long: bits 0-2, then 9-4, then bit 3 (implicit when nothing above it is set) x = getBit(br, P[o + 10]) + 2 * getBit(br, P[o + 11]) + 4 * getBit(br, P[o + 12]) @@ -72663,7 +72678,7 @@ type Rows = { local nr, nc, cnt = table.create(4, 0), table.create(4, 0), table.create(4, 0) -- libvpx read_mb_modes_mv with vp8_find_near_mvs -@native local function readInterMb(st: State, br: Br, probIntra: number, probLast: number, probGf: number, mi: number, mbx: number, mby: number, rows: Rows) +local function readInterMb(st: State, br: Br, probIntra: number, probLast: number, probGf: number, mi: number, mbx: number, mby: number, rows: Rows) local miRef, miMode, miMvR, miMvC = st.miRef, st.miMode, st.miMvR, st.miMvC local x1 = mbx + 1 if getBit(br, probIntra) == 0 then @@ -72872,7 +72887,7 @@ type Frame = { local BORDER = Predict.BORDER -@native local function newRef(mbw: number, mbh: number): Ref +local function newRef(mbw: number, mbh: number): Ref local ys, uvs = mbw * 16 + 2 * BORDER, mbw * 8 + 2 * BORDER return { Y = bcreate(ys * (mbh * 16 + 2 * BORDER)), @@ -72888,7 +72903,7 @@ local BORDER = Predict.BORDER } end -@native local function freeRef(st: State): Ref +local function freeRef(st: State): Ref for _, r in st.pool do if r ~= st.last and r ~= st.golden and r ~= st.alt then return r @@ -72899,7 +72914,7 @@ end return r end -@native function Decode.cropTo(f: Frame, dy: buffer, oy: number, du: buffer, ou: number, dv: buffer, ov: number) +function Decode.cropTo(f: Frame, dy: buffer, oy: number, du: buffer, ou: number, dv: buffer, ov: number) local r = f.ref local w, h = f.width, f.height local cw, chh = (w + 1) // 2, (h + 1) // 2 @@ -72913,7 +72928,7 @@ end end end -@native function Decode.decodeFrame(st: State, buf: buffer, off: number, len: number, maxPixels: number): (Frame?, string?) +function Decode.decodeFrame(st: State, buf: buffer, off: number, len: number, maxPixels: number): (Frame?, string?) local hdr, herr = Decode.header(buf, off, len) if not hdr then return nil, herr @@ -73056,7 +73071,7 @@ end else q = baseQ end - @native local function cq(v: number, m: number): number + local function cq(v: number, m: number): number return if v < 0 then 0 elseif v > m then m else v end local y2ac = (AC_TABLE[cq(q + dqy2ac, 127) + 1] * 101581) // 65536 @@ -73120,7 +73135,7 @@ end end end end - @native local function fail(msg: string): (Frame?, string?) + local function fail(msg: string): (Frame?, string?) if saved then st.proba, st.ymodeProb, st.uvmodeProb, st.mvProb = saved[1], saved[2], saved[3], saved[4] end @@ -73655,7 +73670,7 @@ end return Decode end -__FILES["codecs/image/Vp8/Predict"] = @native function() +__FILES["codecs/image/Vp8/Predict"] = function() @@ -73680,7 +73695,7 @@ local emu = bcreate(32 * 32) local tmp = bcreate(32 * 32) -- six-tap along rows: dst[i] = clamp((sum of src[i - 2 .. i + 3] * taps + 64) >> 7) -@native local function sixH(src: buffer, so: number, ss: number, dst: buffer, d: number, ds: number, w: number, h: number, f: number) +local function sixH(src: buffer, so: number, ss: number, dst: buffer, d: number, ds: number, w: number, h: number, f: number) local k = f * 6 local t0, t1, t2, t3, t4, t5 = SIX[k + 1], SIX[k + 2], SIX[k + 3], SIX[k + 4], SIX[k + 5], SIX[k + 6] for _ = 1, h do @@ -73694,7 +73709,7 @@ local tmp = bcreate(32 * 32) end end -@native local function sixV(src: buffer, so: number, ss: number, dst: buffer, d: number, ds: number, w: number, h: number, f: number) +local function sixV(src: buffer, so: number, ss: number, dst: buffer, d: number, ds: number, w: number, h: number, f: number) local k = f * 6 local t0, t1, t2, t3, t4, t5 = SIX[k + 1], SIX[k + 2], SIX[k + 3], SIX[k + 4], SIX[k + 5], SIX[k + 6] local s1, s2, s3 = ss, 2 * ss, 3 * ss @@ -73712,7 +73727,7 @@ end end -- the bilinear filters: dst[i] = (src[i] * t0 + src[i + 1] * t1 + 64) >> 7 -@native local function bilH(src: buffer, so: number, ss: number, dst: buffer, d: number, ds: number, w: number, h: number, f: number) +local function bilH(src: buffer, so: number, ss: number, dst: buffer, d: number, ds: number, w: number, h: number, f: number) local t0, t1 = BIL[f * 2 + 1], BIL[f * 2 + 2] for _ = 1, h do for i = 0, w - 1 do @@ -73723,7 +73738,7 @@ end end end -@native local function bilV(src: buffer, so: number, ss: number, dst: buffer, d: number, ds: number, w: number, h: number, f: number) +local function bilV(src: buffer, so: number, ss: number, dst: buffer, d: number, ds: number, w: number, h: number, f: number) local t0, t1 = BIL[f * 2 + 1], BIL[f * 2 + 2] for _ = 1, h do for i = 0, w - 1 do @@ -73734,7 +73749,7 @@ end end end -@native local function block(src: buffer, stride: number, base: number, wmax: number, hmax: number, x: number, y: number, mvx: number, mvy: number, w: number, h: number, dst: buffer, d: number, bil: boolean) +local function block(src: buffer, stride: number, base: number, wmax: number, hmax: number, x: number, y: number, mvx: number, mvy: number, w: number, h: number, dst: buffer, d: number, bil: boolean) local fx, fy = band(mvx, 7), band(mvy, 7) local px, py = x + (mvx - fx) // 8, y + (mvy - fy) // 8 local sb, so, ss = src, 0, stride @@ -73791,7 +73806,7 @@ end end end -@native local function chroma16(v: number): number +local function chroma16(v: number): number -- the chroma vector of a whole macroblock: half the luma one, rounded away from zero if v < 0 then return -((1 - v) // 2) @@ -73799,7 +73814,7 @@ end return (v + 1) // 2 end -@native local function chroma4(s: number): number +local function chroma4(s: number): number -- the chroma vector of a 2x2 group of luma blocks: the sum of their 4 vectors / 8, rounded half away from zero if s < 0 then return -((4 - s) // 8) @@ -73819,7 +73834,7 @@ type Planes = { mbh: number, } -@native function Predict.mb(ref: Planes, mbx: number, mby: number, mvr: number, mvc: number, part: number, subR: { number }, subC: { number }, sb: number, dst: buffer, yo: number, uo: number, vo: number, bil: boolean, full: boolean) +function Predict.mb(ref: Planes, mbx: number, mby: number, mvr: number, mvc: number, part: number, subR: { number }, subC: { number }, sb: number, dst: buffer, yo: number, uo: number, vo: number, bil: boolean, full: boolean) local Y, U, V, ys, uvs, yb, uvb = ref.Y, ref.U, ref.V, ref.ys, ref.uvs, ref.yb, ref.uvb local wl, hl = ref.mbw * 16 - 1, ref.mbh * 16 - 1 local wc, hc = ref.mbw * 8 - 1, ref.mbh * 8 - 1 @@ -73881,7 +73896,7 @@ type Planes = { end end -@native function Predict.row(refs: { Planes }, mby: number, mbw: number, ref: { number }, part: { number }, miMvR: { number }, miMvC: { number }, miSubR: { number }, miSubC: { number }, mi0: number, pred: buffer, chunk: number, yo: number, uo: number, vo: number, bil: boolean, full: boolean) +function Predict.row(refs: { Planes }, mby: number, mbw: number, ref: { number }, part: { number }, miMvR: { number }, miMvC: { number }, miSubR: { number }, miSubC: { number }, mi0: number, pred: buffer, chunk: number, yo: number, uo: number, vo: number, bil: boolean, full: boolean) for mbx = 0, mbw - 1 do local rf = ref[mbx + 1] if rf > 0 then @@ -73892,7 +73907,7 @@ end end end -@native local function extend(P: buffer, stride: number, base: number, w: number, h: number) +local function extend(P: buffer, stride: number, base: number, w: number, h: number) for r = 0, h - 1 do local o = base + r * stride bfill(P, o - BORDER, readu8(P, o), BORDER) @@ -73906,7 +73921,7 @@ end end end -@native function Predict.extend(ref: Planes) +function Predict.extend(ref: Planes) extend(ref.Y, ref.ys, ref.yb, ref.mbw * 16, ref.mbh * 16) extend(ref.U, ref.uvs, ref.uvb, ref.mbw * 8, ref.mbh * 8) extend(ref.V, ref.uvs, ref.uvb, ref.mbw * 8, ref.mbh * 8) @@ -74163,7 +74178,7 @@ Tables.BILINEAR = { 128, 0, 112, 16, 96, 32, 80, 48, 64, 64, 48, 80, 32, 96, 16, return Tables end -__FILES["codecs/image/Vp8/Yuv"] = @native function() +__FILES["codecs/image/Vp8/Yuv"] = function() @@ -74176,7 +74191,7 @@ local bcreate = buffer.create local Yuv = {} -@native local function clip(v: number): number +local function clip(v: number): number -- VP8Clip8: v in 14-bit fixed point if v >= 0 and v < 16384 then return rshift(v, 6) @@ -74184,11 +74199,11 @@ local Yuv = {} return if v < 0 then 0 else 255 end -@native local function mulHi(v: number, c: number): number +local function mulHi(v: number, c: number): number return rshift(v * c, 8) end -@native local function rgba(y: number, u: number, v: number): number +local function rgba(y: number, u: number, v: number): number local yy = mulHi(y, 19077) local r = clip(yy + mulHi(v, 26149) - 14234) local g = clip(yy - mulHi(u, 6419) - mulHi(v, 13320) + 8708) @@ -74198,7 +74213,7 @@ end Yuv.rgba = rgba -- libwebp UPSAMPLE_FUNC for one or two output rows (by < 0: no bottom row) -@native local function upsamplePair(Y: buffer, U: buffer, V: buffer, ty: number, by: number, tu: number, cu: number, out: buffer, dt: number, db: number, len: number) +local function upsamplePair(Y: buffer, U: buffer, V: buffer, ty: number, by: number, tu: number, cu: number, out: buffer, dt: number, db: number, len: number) local last = rshift(len - 1, 1) local tlu, tlv = readu8(U, tu), readu8(V, tu) local lu, lv = readu8(U, cu), readu8(V, cu) @@ -74242,7 +74257,7 @@ Yuv.rgba = rgba end end -@native function Yuv.toRgba(Y: buffer, U: buffer, V: buffer, w: number, h: number, fancy: boolean, out: buffer?): buffer +function Yuv.toRgba(Y: buffer, U: buffer, V: buffer, w: number, h: number, fancy: boolean, out: buffer?): buffer local o = out or bcreate(w * h * 4) local cw = (w + 1) // 2 local stride = w * 4 @@ -74274,7 +74289,7 @@ end return o end -@native function Yuv.setAlpha(o: buffer, a: buffer, n: number) +function Yuv.setAlpha(o: buffer, a: buffer, n: number) for i = 0, n - 1 do writeu8(o, i * 4 + 3, readu8(a, i)) end @@ -74386,7 +74401,7 @@ end return Vp8L end -__FILES["codecs/image/Vp8L/Decode"] = @native function() +__FILES["codecs/image/Vp8L/Decode"] = function() @@ -74434,7 +74449,7 @@ type State = { maxPixels: number, } -@native local function fill(d: State) +local function fill(d: State) local bitbuf, bitcnt = d.bitbuf, d.bitcnt while bitcnt <= 24 do local p = d.pos @@ -74451,7 +74466,7 @@ type State = { d.bitbuf, d.bitcnt = bitbuf, bitcnt end -@native local function readBits(d: State, n: number): number +local function readBits(d: State, n: number): number if d.bitcnt < n then fill(d) end @@ -74461,14 +74476,14 @@ end return v end -@native local function eos(d: State): boolean +local function eos(d: State): boolean return d.bitcnt < d.over * 8 end local count = table.create(MAX_LEN + 1, 0) local offset = table.create(MAX_LEN + 2, 0) -@native local function ensure(d: State, n: number) +local function ensure(d: State, n: number) local cap = blen(d.tab) // 4 if d.tabUsed + n > cap then local nb = bcreate(math.max(cap * 2, d.tabUsed + n) * 4) @@ -74477,7 +74492,7 @@ local offset = table.create(MAX_LEN + 2, 0) end end -@native local function replicate(tab: buffer, at: number, step: number, size: number, entry: number) +local function replicate(tab: buffer, at: number, step: number, size: number, entry: number) local e = size repeat e -= step @@ -74485,7 +74500,7 @@ end until e <= 0 end -@native local function nextKey(key: number, len: number): number +local function nextKey(key: number, len: number): number local step = lshift(1, len - 1) while band(key, step) ~= 0 do step = rshift(step, 1) @@ -74495,7 +74510,7 @@ end -- libwebp BuildHuffmanTable: complete codes only, except a single used symbol, which reads 0 bits; -1 when invalid local sorted = table.create(2400, 0) -@native local function build(d: State, lens: { number }, n: number): number +local function build(d: State, lens: { number }, n: number): number for l = 0, MAX_LEN do count[l + 1] = 0 end @@ -74602,7 +74617,7 @@ local sorted = table.create(2400, 0) return root end -@native local function readSymbol(d: State, at: number): number +local function readSymbol(d: State, at: number): number if d.bitcnt < MAX_LEN then fill(d) end @@ -74625,7 +74640,7 @@ end local codeLengths = table.create(2400, 0) local clLens = table.create(19, 0) -@native local function readCode(d: State, size: number): number +local function readCode(d: State, size: number): number for i = 1, size do codeLengths[i] = 0 end @@ -74703,12 +74718,12 @@ local clLens = table.create(19, 0) return build(d, codeLengths, size) end -@native local function subSample(size: number, bits: number): number +local function subSample(size: number, bits: number): number return rshift(size + lshift(1, bits) - 1, bits) end Decode.subSample = subSample -@native local function cacheKey(argb: number, shift: number): number +local function cacheKey(argb: number, shift: number): number -- (0x1e35a7bd * argb) mod 2^32 >> shift, exact in doubles local lo = argb % 65536 local hi = (argb - lo) / 65536 @@ -74717,7 +74732,7 @@ Decode.subSample = subSample end Decode.cacheKey = cacheKey -@native local function decodeData(d: State, data: buffer, w: number, h: number, cacheBits: number, groups: { number }, himg: buffer?, hbits: number, hxs: number): (boolean, string?) +local function decodeData(d: State, data: buffer, w: number, h: number, cacheBits: number, groups: { number }, himg: buffer?, hbits: number, hxs: number): (boolean, string?) local total = w * h local cache: buffer? = if cacheBits > 0 then bcreate(lshift(1, cacheBits) * 4) else nil local cshift = 32 - cacheBits @@ -74726,7 +74741,7 @@ Decode.cacheKey = cacheKey local hmask = if himg then lshift(1, hbits) - 1 else -1 local i, col, row = 0, 0, 0 local gG, gR, gB, gA, gD = groups[1], groups[2], groups[3], groups[4], groups[5] - @native local function setGroup() + local function setGroup() if himg then local g = readu32(himg, (hxs * rshift(row, hbits) + rshift(col, hbits)) * 4) * 5 gG, gR, gB, gA, gD = groups[g + 1], groups[g + 2], groups[g + 3], groups[g + 4], groups[g + 5] @@ -74833,27 +74848,27 @@ Decode.cacheKey = cacheKey return true, nil end -@native local function addPixels(a: number, b: number): number +local function addPixels(a: number, b: number): number return band(band(a, 0xff00ff00) + band(b, 0xff00ff00), 0xff00ff00) + band(band(a, 0x00ff00ff) + band(b, 0x00ff00ff), 0x00ff00ff) end Decode.addPixels = addPixels -@native local function average2(a: number, b: number): number +local function average2(a: number, b: number): number return rshift(band(bxor(a, b), 0xfefefefe), 1) + band(a, b) end Decode.average2 = average2 -@native local function clip255(v: number): number +local function clip255(v: number): number return if v < 0 then 0 elseif v > 255 then 255 else v end -@native local function sub3(a: number, b: number, c: number): number +local function sub3(a: number, b: number, c: number): number local pb, pa = b - c, a - c return (if pb < 0 then -pb else pb) - (if pa < 0 then -pa else pa) end -- select(T, L, TL) -@native local function select3(a: number, b: number, c: number): number +local function select3(a: number, b: number, c: number): number local s = sub3(rshift(a, 24), rshift(b, 24), rshift(c, 24)) + sub3(band(rshift(a, 16), 255), band(rshift(b, 16), 255), band(rshift(c, 16), 255)) + sub3(band(rshift(a, 8), 255), band(rshift(b, 8), 255), band(rshift(c, 8), 255)) @@ -74861,7 +74876,7 @@ end return if s <= 0 then a else b end -@native local function clampedFull(c0: number, c1: number, c2: number): number +local function clampedFull(c0: number, c1: number, c2: number): number local a = clip255(rshift(c0, 24) + rshift(c1, 24) - rshift(c2, 24)) local r = clip255(band(rshift(c0, 16), 255) + band(rshift(c1, 16), 255) - band(rshift(c2, 16), 255)) local g = clip255(band(rshift(c0, 8), 255) + band(rshift(c1, 8), 255) - band(rshift(c2, 8), 255)) @@ -74869,14 +74884,14 @@ end return a * 16777216 + r * 65536 + g * 256 + b end -@native local function half(a: number, b: number): number +local function half(a: number, b: number): number local dd = a - b -- C division truncates toward zero local q = if dd >= 0 then rshift(dd, 1) else -rshift(-dd, 1) return clip255(a + q) end -@native local function clampedHalf(c0: number, c1: number, c2: number): number +local function clampedHalf(c0: number, c1: number, c2: number): number local ave = average2(c0, c1) local a = half(rshift(ave, 24), rshift(c2, 24)) local r = half(band(rshift(ave, 16), 255), band(rshift(c2, 16), 255)) @@ -74886,7 +74901,7 @@ end end -- libwebp VP8LPredictors; modes 14 and 15 are black -@native local function predict(mode: number, L: number, T: number, TR: number, TL: number): number +local function predict(mode: number, L: number, T: number, TR: number, TL: number): number if mode == 0 then return ARGB_BLACK elseif mode == 1 then @@ -74920,7 +74935,7 @@ end end Decode.predict = predict -@native local function inversePredictor(data: buffer, w: number, h: number, bits: number, sub: buffer) +local function inversePredictor(data: buffer, w: number, h: number, bits: number, sub: buffer) local tw = subSample(w, bits) -- first row: black, then L writeu32(data, 0, addPixels(readu32(data, 0), ARGB_BLACK)) @@ -74958,11 +74973,11 @@ Decode.predict = predict end end -@native local function sint8(v: number): number +local function sint8(v: number): number return if v >= 128 then v - 256 else v end -@native local function inverseCrossColor(data: buffer, w: number, h: number, bits: number, sub: buffer) +local function inverseCrossColor(data: buffer, w: number, h: number, bits: number, sub: buffer) local tw = subSample(w, bits) for y = 0, h - 1 do local trow = rshift(y, bits) * tw @@ -74985,7 +75000,7 @@ end end end -@native local function inverseSubtractGreen(data: buffer, n: number) +local function inverseSubtractGreen(data: buffer, n: number) for k = 0, n - 1 do local argb = readu32(data, k * 4) local g = band(rshift(argb, 8), 255) @@ -74993,7 +75008,7 @@ end end end -@native local function inverseColorIndexing(src: buffer, sw: number, w: number, h: number, bits: number, map: buffer): buffer +local function inverseColorIndexing(src: buffer, sw: number, w: number, h: number, bits: number, map: buffer): buffer local out = bcreate(w * h * 4) if bits == 0 then for k = 0, w * h - 1 do @@ -75024,7 +75039,7 @@ type Transform = { kind: number, xsize: number, bits: number, data: buffer? } local decodeStream: (d: State, xs: number, ys: number, level0: boolean) -> (buffer?, string?) -@native local function readCodes(d: State, xs: number, ys: number, cacheBits: number, level0: boolean): ({ number }?, buffer?, number, number, string?) +local function readCodes(d: State, xs: number, ys: number, cacheBits: number, level0: boolean): ({ number }?, buffer?, number, number, string?) local himg: buffer? = nil local hbits, hxs = 0, 0 local numGroups = 1 @@ -75089,7 +75104,7 @@ local decodeStream: (d: State, xs: number, ys: number, level0: boolean) -> (buff return groups, himg, hbits, hxs, nil end -decodeStream = @native function(d: State, xs: number, ys: number, level0: boolean): (buffer?, string?) +decodeStream = function(d: State, xs: number, ys: number, level0: boolean): (buffer?, string?) local transforms: { Transform } = {} local seen = 0 local txs = xs @@ -75166,7 +75181,7 @@ decodeStream = @native function(d: State, xs: number, ys: number, level0: boolea return data, nil end -@native local function newState(buf: buffer, off: number, len: number, maxPixels: number): State +local function newState(buf: buffer, off: number, len: number, maxPixels: number): State return { buf = buf, pos = off, @@ -75180,7 +75195,7 @@ end } end -@native function Decode.header(buf: buffer, off: number, len: number): (number?, number, boolean, string?) +function Decode.header(buf: buffer, off: number, len: number): (number?, number, boolean, string?) if len < 5 then return nil, 0, false, "truncated: header" end @@ -75197,7 +75212,7 @@ end return w, h, alpha, nil end -@native function Decode.argb(buf: buffer, off: number, len: number, maxPixels: number): (buffer?, number, number, boolean, string?) +function Decode.argb(buf: buffer, off: number, len: number, maxPixels: number): (buffer?, number, number, boolean, string?) local w, h, alpha, err = Decode.header(buf, off, len) if not w then return nil, 0, 0, false, err @@ -75213,12 +75228,12 @@ end return data, w, h, alpha, nil end -@native function Decode.stream(buf: buffer, off: number, len: number, w: number, h: number): (buffer?, string?) +function Decode.stream(buf: buffer, off: number, len: number, w: number, h: number): (buffer?, string?) local d = newState(buf, off, len, w * h) return decodeStream(d, w, h, true) end -@native function Decode.toRgba(argb: buffer, n: number, out: buffer?, outOff: number?): buffer +function Decode.toRgba(argb: buffer, n: number, out: buffer?, outOff: number?): buffer local o = out or bcreate(n * 4) local base = outOff or 0 for k = 0, n - 1 do @@ -75229,7 +75244,7 @@ end return o end -@native function Decode.green(argb: buffer, n: number): buffer +function Decode.green(argb: buffer, n: number): buffer local o = bcreate(n) for k = 0, n - 1 do writeu8(o, k, band(rshift(readu32(argb, k * 4), 8), 255)) @@ -75239,7 +75254,7 @@ end return Decode end -__FILES["codecs/image/Vp8L/Encode"] = @native function() +__FILES["codecs/image/Vp8L/Encode"] = function() @@ -75278,12 +75293,12 @@ end type W = { buf: buffer, pos: number, acc: number, cnt: number } -@native local function newWriter(cap: number): W +local function newWriter(cap: number): W return { buf = bcreate(math.max(64, cap)), pos = 0, acc = 0, cnt = 0 } end -- the n <= 24 low bits of v, LSB first -@native local function put(w: W, v: number, n: number) +local function put(w: W, v: number, n: number) local acc = w.acc + v * 2 ^ w.cnt local cnt = w.cnt + n if cnt >= 8 then @@ -75307,7 +75322,7 @@ end w.acc, w.cnt = acc, cnt end -@native local function finish(w: W): buffer +local function finish(w: W): buffer if w.cnt > 0 then put(w, 0, 8 - w.cnt) end @@ -75316,18 +75331,18 @@ end return out end -@native local function subSample(size: number, bits: number): number +local function subSample(size: number, bits: number): number return rshift(size + lshift(1, bits) - 1, bits) end -- (0x1e35a7bd * v) mod 2^32: the colour cache hash before its shift -@native local function mulHash(v: number): number +local function mulHash(v: number): number local lo = v % 65536 local hi = (v - lo) / 65536 return (lo * 0xa7bd + ((lo * 0x1e35 + hi * 0xa7bd) % 65536) * 65536) % 4294967296 end -@native local function prefix(v: number): (number, number, number) +local function prefix(v: number): (number, number, number) local d = v - 1 if d < 4 then return d, 0, 0 @@ -75344,7 +75359,7 @@ end end -- distance code value: 1..120 for the 2-D plane offsets, else dist + 120 -@native local function distCode(xs: number, dist: number): number +local function distCode(xs: number, dist: number): number local yo = dist // xs local xo = dist - yo * xs if xo <= 8 and yo < 8 then @@ -75355,29 +75370,29 @@ end return dist + 120 end -@native local function subPixels(a: number, b: number): number +local function subPixels(a: number, b: number): number return band(bor(a, 0x00ff00ff) - band(b, 0xff00ff00), 0xff00ff00) + band(bor(a, 0xff00ff00) - band(b, 0x00ff00ff), 0x00ff00ff) end -@native local function average2(a: number, b: number): number +local function average2(a: number, b: number): number return rshift(band(bxor(a, b), 0xfefefefe), 1) + band(a, b) end -@native local function clip255(v: number): number +local function clip255(v: number): number return if v < 0 then 0 elseif v > 255 then 255 else v end -@native local function sub3(a: number, b: number, c: number): number +local function sub3(a: number, b: number, c: number): number local pb, pa = b - c, a - c return (if pb < 0 then -pb else pb) - (if pa < 0 then -pa else pa) end -@native local function half(x: number, y: number): number +local function half(x: number, y: number): number local dd = x - y return clip255(x + (if dd >= 0 then rshift(dd, 1) else -rshift(-dd, 1))) end -@native local function predict(mode: number, L: number, T: number, TR: number, TL: number): number +local function predict(mode: number, L: number, T: number, TR: number, TL: number): number if mode == 1 then return L elseif mode == 2 then @@ -75427,7 +75442,7 @@ for v = 0, 255 do COST[v + 1] = log(1 + m) / log(2) end -@native local function residualCost(r: number): number +local function residualCost(r: number): number return COST[band(r, 255) + 1] + COST[band(rshift(r, 8), 255) + 1] + COST[band(rshift(r, 16), 255) + 1] + COST[rshift(r, 24) + 1] end @@ -75435,7 +75450,7 @@ local MODES_FAST = { 1, 2, 11 } local MODES_MID = { 0, 1, 2, 4, 5, 7, 10, 11, 12, 13 } local MODES_ALL = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 } -@native local function predictorTransform(px: buffer, w: number, h: number, bits: number, effort: number): buffer +local function predictorTransform(px: buffer, w: number, h: number, bits: number, effort: number): buffer local tw, th = subSample(w, bits), subSample(h, bits) local modesImg = bcreate(tw * th * 4) local modes = if effort <= 2 then MODES_FAST elseif effort <= 6 then MODES_MID else MODES_ALL @@ -75488,21 +75503,21 @@ local MODES_ALL = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 } return modesImg end -@native local function sint8(v: number): number +local function sint8(v: number): number return if v >= 128 then v - 256 else v end -@native local function clampM(v: number): number +local function clampM(v: number): number local m = math.floor(v + 0.5) return if m < -128 then -128 elseif m > 127 then 127 else m end -- cross colour per tile: least-squares r ~ g2r * g / 32, b ~ g2b * g / 32 + r2b * r / 32, kept when they lower the cost -@native local function crossColorTransform(px: buffer, w: number, h: number, bits: number): buffer +local function crossColorTransform(px: buffer, w: number, h: number, bits: number): buffer local tw, th = subSample(w, bits), subSample(h, bits) local img = bcreate(tw * th * 4) local ts = lshift(1, bits) - @native local function tileCost(x0: number, y0: number, x1: number, y1: number, g2r: number, g2b: number, r2b: number): number + local function tileCost(x0: number, y0: number, x1: number, y1: number, g2r: number, g2b: number, r2b: number): number local c = 0 for y = y0, y1 - 1 do for x = x0, x1 - 1 do @@ -75574,11 +75589,11 @@ end -- tokens: L[i] >= 0 is a literal ARGB pixel; L[i] < 0 is a copy of -L[i] pixels with the distance code value D[i] local HASH_BITS = 16 -@native local function hash2(a: number, b: number): number +local function hash2(a: number, b: number): number return rshift(mulHash(bxor(a, (b * 31) % 4294967296)), 32 - HASH_BITS) end -@native local function matchLen(px: buffer, i: number, j: number, max: number): number +local function matchLen(px: buffer, i: number, j: number, max: number): number local n = 0 while n < max and readu32(px, (i + n) * 4) == readu32(px, (j + n) * 4) do n += 1 @@ -75586,7 +75601,7 @@ end return n end -@native local function lz77(px: buffer, xs: number, n: number, effort: number): ({ number }, { number }) +local function lz77(px: buffer, xs: number, n: number, effort: number): ({ number }, { number }) local L: { number } = {} local D: { number } = {} if effort == 0 then @@ -75599,20 +75614,20 @@ end local head = table.create(lshift(1, HASH_BITS), -1) local prev = table.create(n, -1) local maxIter = if effort <= 2 then 4 elseif effort <= 5 then 16 elseif effort <= 7 then 48 else 128 - @native local function insert(i: number) + local function insert(i: number) if i + 1 < n then local h = hash2(readu32(px, i * 4), readu32(px, (i + 1) * 4)) + 1 prev[i + 1] = head[h] head[h] = i end end - @native local function best(i: number): (number, number) + local function best(i: number): (number, number) local max = math.min(MAX_LENGTH, n - i) if max < 2 then return 0, 0 end local bl, bd, bc = 0, 0, math.huge - @native local function try(j: number) + local function try(j: number) local d = i - j if d < 1 or d > WINDOW then return @@ -75709,7 +75724,7 @@ end return L, D end -@native local function entropy(h: { number }): number +local function entropy(h: { number }): number local total = 0 for _, c in h do total += c @@ -75727,7 +75742,7 @@ end return bits / log(2) end -@native local function chooseCache(px: buffer, L: { number }, effort: number): number +local function chooseCache(px: buffer, L: { number }, effort: number): number if effort < 2 then return 0 end @@ -75790,7 +75805,7 @@ end type Code = { lens: { number }, codes: { number }, single: boolean } -@native local function buildCode(freqs: { number }, maxLen: number): Code +local function buildCode(freqs: { number }, maxLen: number): Code local lens = Huffman.lengths(freqs, maxLen) local used = 0 for _, l in lens do @@ -75807,13 +75822,13 @@ type Code = { lens: { number }, codes: { number }, single: boolean } return { lens = lens, codes = codes, single = used <= 1 } end -@native local function emit(w: W, c: Code, sym: number) +local function emit(w: W, c: Code, sym: number) if not c.single then put(w, c.codes[sym + 1], c.lens[sym + 1]) end end -@native local function zeroRun(tok: { number }, ext: { number }, run: number) +local function zeroRun(tok: { number }, ext: { number }, run: number) local r = run while r > 0 do if r >= 11 then @@ -75833,7 +75848,7 @@ end end end -@native local function writeCode(w: W, c: Code, size: number) +local function writeCode(w: W, c: Code, size: number) local syms: { number } = {} for s = 0, size - 1 do if (c.lens[s + 1] or 0) > 0 then @@ -75951,7 +75966,7 @@ end end -- colour cache bits, [the meta-code bit], the five codes, the pixels -@native local function writeImage(w: W, px: buffer, xs: number, n: number, effort: number, level0: boolean) +local function writeImage(w: W, px: buffer, xs: number, n: number, effort: number, level0: boolean) local L, D = lz77(px, xs, n, effort) local cacheBits = if level0 then chooseCache(px, L, effort) else 0 if cacheBits > 0 then @@ -76037,7 +76052,7 @@ end end end -@native local function toArgb(rgba: buffer, n: number, exact: boolean): (buffer, boolean) +local function toArgb(rgba: buffer, n: number, exact: boolean): (buffer, boolean) local px = bcreate(n * 4) local alpha = false for i = 0, n - 1 do @@ -76055,7 +76070,7 @@ end return px, alpha end -@native local function palette(px: buffer, n: number): { number }? +local function palette(px: buffer, n: number): { number }? local seen: { [number]: boolean } = {} local list: { number } = {} for i = 0, n - 1 do @@ -76074,7 +76089,7 @@ end type Config = { palette: { number }?, pbits: number, cc: boolean, ccbits: number } -@native local function stream(px: buffer, w: number, h: number, effort: number, cfg: Config, bw: W) +local function stream(px: buffer, w: number, h: number, effort: number, cfg: Config, bw: W) local n = w * h local xs = w local sub = math.min(effort, 3) @@ -76141,7 +76156,7 @@ type Config = { palette: { number }?, pbits: number, cc: boolean, ccbits: number writeImage(bw, px, xs, xs * h, effort, true) end -@native function Encode.encode(rgba: buffer, w: number, h: number, effort: number, exact: boolean, alphaHint: boolean?, headerless: boolean): buffer +function Encode.encode(rgba: buffer, w: number, h: number, effort: number, exact: boolean, alphaHint: boolean?, headerless: boolean): buffer local n = w * h local px, usesAlpha = toArgb(rgba, n, exact) local pal = if effort > 0 then palette(px, n) else nil @@ -76191,7 +76206,7 @@ end return Encode end -__FILES["codecs/image/Yuv"] = @native function() +__FILES["codecs/image/Yuv"] = function() @@ -76216,7 +76231,7 @@ local MATRIX: { [string]: { kr: number, kb: number } } = { type Coeffs = { ys: number, yo: number, crv: number, cgu: number, cgv: number, cbu: number, cs: number } local cache: { [string]: Coeffs } = {} -@native local function coeffs(range: string?, matrix: string?): Coeffs +local function coeffs(range: string?, matrix: string?): Coeffs local key = (range or "limited") .. (matrix or "bt601") local c = cache[key] if c then @@ -76246,7 +76261,7 @@ for i = 0, 2303 do writeu8(CLIP, i, math.clamp(i - 1024, 0, 255)) end -@native function Yuv.toRgba(src: buffer, w: number, h: number, uo: number, vo: number, cw: number, range: string?, matrix: string?, out: buffer?): buffer +function Yuv.toRgba(src: buffer, w: number, h: number, uo: number, vo: number, cw: number, range: string?, matrix: string?, out: buffer?): buffer local dst = out or bcreate(w * h * 4) local c = coeffs(range, matrix) local ys, yo, crv, cgu, cgv, cbu = c.ys, c.yo, c.crv, c.cgu, c.cgv, c.cbu @@ -76277,7 +76292,7 @@ end return dst end -@native function Yuv.fromRgba(src: buffer, w: number, h: number, range: string?, matrix: string?, out: buffer?): buffer +function Yuv.fromRgba(src: buffer, w: number, h: number, range: string?, matrix: string?, out: buffer?): buffer local cw, ch = (w + 1) // 2, (h + 1) // 2 local uo, vo = w * h, w * h + cw * ch local dst = out or bcreate(w * h + 2 * cw * ch) @@ -76323,7 +76338,7 @@ end return dst end -@native local function info(img: Types.Image): (string, string) +local function info(img: Types.Image): (string, string) local m = img.meta local y = m and m.yuv if type(y) == "table" then @@ -76337,7 +76352,7 @@ end end Yuv.info = info -@native function Yuv.planes(w: number, h: number): (number, number, number, number) +function Yuv.planes(w: number, h: number): (number, number, number, number) local cw, ch = (w + 1) // 2, (h + 1) // 2 return w * h, w * h + cw * ch, cw, ch end @@ -76349,7 +76364,7 @@ for v = 0, 255 do writeu8(FULL_C, v, math.clamp(floor((v - 128) * 255 / 224 + 128.5), 0, 255)) end -@native function Yuv.toFullRange(img: Types.Image): Types.Image +function Yuv.toFullRange(img: Types.Image): Types.Image if img.format ~= "yuv420p" or info(img) == "full" then return img end @@ -76369,7 +76384,7 @@ end return out end -@native function Yuv.imageToRgba(img: Types.Image): Types.Image? +function Yuv.imageToRgba(img: Types.Image): Types.Image? if img.format == "rgba8" then return img end @@ -76385,7 +76400,7 @@ end return out end -@native function Yuv.imageFromRgba(img: Types.Image, range: string?, matrix: string?): Types.Image? +function Yuv.imageFromRgba(img: Types.Image, range: string?, matrix: string?): Types.Image? if img.format == "yuv420p" then return img end @@ -76399,7 +76414,7 @@ end return out end -@native local function scalePlane(src: buffer, so: number, sw: number, sh: number, dst: buffer, d0: number, dw: number, dh: number) +local function scalePlane(src: buffer, so: number, sw: number, sh: number, dst: buffer, d0: number, dw: number, dh: number) local fx, fy = sw / dw, sh / dh for y = 0, dh - 1 do local sy = (y + 0.5) * fy - 0.5 @@ -76432,7 +76447,7 @@ end end end -@native function Yuv.scale(src: buffer, w: number, h: number, width: number, height: number, out: buffer?): buffer +function Yuv.scale(src: buffer, w: number, h: number, width: number, height: number, out: buffer?): buffer local dw: number = math.max(1, floor(width)) local dh: number = math.max(1, floor(height)) local cw: number = (w + 1) // 2 @@ -76450,7 +76465,7 @@ end return dst end -@native function Yuv.imageScale(img: Types.Image, dw: number, dh: number): Types.Image +function Yuv.imageScale(img: Types.Image, dw: number, dh: number): Types.Image local out = Types.Image.new(math.max(1, floor(dw)), math.max(1, floor(dh)), "yuv420p") Yuv.scale(img.pixels, img.width, img.height, out.width, out.height, out.pixels) out.meta = table.clone(img.meta or {}) @@ -81918,7 +81933,7 @@ Legacy.MASK = { log = 4, log2 = 4, leaves = 4, leaves2 = 4, sapling = 8, wooden_ return Legacy end -__FILES["codecs/model/Minecraft/Packed"] = @native function() +__FILES["codecs/model/Minecraft/Packed"] = function() @@ -81931,7 +81946,7 @@ local readu8, readu16, readu32 = buffer.readu8, buffer.readu16, buffer.readu32 local writeu8, writeu16 = buffer.writeu8, buffer.writeu16 local extract, band, rshift, lshift, bor = bit32.extract, bit32.band, bit32.rshift, bit32.lshift, bit32.bor -@native function Packed.longsNeeded(count: number, bits: number, spanning: boolean): number +function Packed.longsNeeded(count: number, bits: number, spanning: boolean): number if spanning then return (count * bits + 63) // 64 end @@ -81939,7 +81954,7 @@ local extract, band, rshift, lshift, bor = bit32.extract, bit32.band, bit32.rshi return (count + per - 1) // per end -@native function Packed.unpack(longs: buffer, bits: number, count: number, spanning: boolean, out: buffer, max: number): (boolean, string?) +function Packed.unpack(longs: buffer, bits: number, count: number, spanning: boolean, out: buffer, max: number): (boolean, string?) if bits < 1 or bits > 16 then return false, "unsupported: " .. bits .. "-bit packed indices" end @@ -81987,7 +82002,7 @@ end return true, nil end -@native function Packed.pack(indices: buffer, count: number, bits: number, spanning: boolean): buffer +function Packed.pack(indices: buffer, count: number, bits: number, spanning: boolean): buffer local need = Packed.longsNeeded(count, bits, spanning) local out = buffer.create(need * 8 + 4) local per = 64 // bits @@ -82009,7 +82024,7 @@ end return res end -@native function Packed.bitsFor(n: number, min: number): number +function Packed.bitsFor(n: number, min: number): number local b = min while lshift(1, b) < n and b < 31 do b += 1 @@ -82018,7 +82033,7 @@ end end -- Sponge BlockData: unsigned LEB128 varints -@native function Packed.varints(src: buffer, offset: number, length: number, count: number, out: buffer, max: number): (boolean, string?) +function Packed.varints(src: buffer, offset: number, length: number, count: number, out: buffer, max: number): (boolean, string?) if buffer.len(out) < count * 2 or offset + length > buffer.len(src) then return false, "bad varint array arguments" end @@ -82048,7 +82063,7 @@ end return true, nil end -@native function Packed.toVarints(indices: buffer, count: number): buffer +function Packed.toVarints(indices: buffer, count: number): buffer local out = buffer.create(count * 3) local p = 0 for i = 0, count - 1 do @@ -82067,7 +82082,7 @@ end end -- nibble arrays: Minecraft low nibble first; WorldEdit AddBlocks high nibble first -@native function Packed.nibble(src: buffer, offset: number, i: number, highFirst: boolean): number +function Packed.nibble(src: buffer, offset: number, i: number, highFirst: boolean): number local b = readu8(src, offset + rshift(i, 1)) local odd = band(i, 1) == 1 if odd == highFirst then @@ -82076,7 +82091,7 @@ end return rshift(b, 4) end -@native function Packed.setNibble(dst: buffer, offset: number, i: number, v: number, highFirst: boolean) +function Packed.setNibble(dst: buffer, offset: number, i: number, v: number, highFirst: boolean) local at = offset + rshift(i, 1) local b = readu8(dst, at) local odd = band(i, 1) == 1 @@ -82088,7 +82103,7 @@ end end -- Minecraft order: x fastest, then z, then y (schematics, chunk sections) -@native function Packed.fromYzx(src: buffer, sx: number, sy: number, sz: number, dst: buffer?, ox: number?, oy: number?, oz: number?, dsx: number?, dsy: number?): buffer +function Packed.fromYzx(src: buffer, sx: number, sy: number, sz: number, dst: buffer?, ox: number?, oy: number?, oz: number?, dsx: number?, dsy: number?): buffer local out = dst or buffer.create(sx * sy * sz * 2) local bx, by, bz = ox or 0, oy or 0, oz or 0 local wx, wy = dsx or sx, dsy or sy @@ -82106,7 +82121,7 @@ end return out end -@native function Packed.toYzx(src: buffer, sx: number, sy: number, sz: number): buffer +function Packed.toYzx(src: buffer, sx: number, sy: number, sz: number): buffer local out = buffer.create(sx * sy * sz * 2) local i = 0 for y = 0, sy - 1 do @@ -82595,7 +82610,7 @@ Rbx.STRINGS = table.freeze({ String = true, BinaryString = true, ProtectedString return Rbx end -__FILES["codecs/model/Rbx/Binary"] = @native function() +__FILES["codecs/model/Rbx/Binary"] = function() @@ -82616,24 +82631,24 @@ local scratch = buffer.create(8) local TWO32 = 4294967296 -- the rotated float encoding: bits rotated left by one (sign in bit 0) -@native local function unrotate(x: number): number +local function unrotate(x: number): number writeu32(scratch, 0, x // 2 + (x % 2) * 2147483648) return readf32(scratch, 0) end -@native local function rotate(v: number): number +local function rotate(v: number): number writef32(scratch, 0, v) local bits = readu32(scratch, 0) return (bits * 2) % TWO32 + bits // 2147483648 end -@native local function unzigzag(x: number): number +local function unzigzag(x: number): number return if x % 2 == 0 then x // 2 else -(x + 1) // 2 end -@native local function zigzag32(v: number): number +local function zigzag32(v: number): number v = floor(v) return (if v >= 0 then v * 2 else -v * 2 - 1) % TWO32 end -@native local function u32s(b: buffer, p: number, n: number): { number } +local function u32s(b: buffer, p: number, n: number): { number } local out = table.create(n, 0) local n2, n3 = n * 2, n * 3 for i = 0, n - 1 do @@ -82641,21 +82656,21 @@ end end return out end -@native local function i32s(b: buffer, p: number, n: number): { number } +local function i32s(b: buffer, p: number, n: number): { number } local out = u32s(b, p, n) for i = 1, n do out[i] = unzigzag(out[i]) end return out end -@native local function f32s(b: buffer, p: number, n: number): { number } +local function f32s(b: buffer, p: number, n: number): { number } local out = u32s(b, p, n) for i = 1, n do out[i] = unrotate(out[i]) end return out end -@native local function i64s(b: buffer, p: number, n: number): { number } +local function i64s(b: buffer, p: number, n: number): { number } local out = table.create(n, 0) for i = 0, n - 1 do local hi = readu8(b, p + i) * 16777216 + readu8(b, p + n + i) * 65536 + readu8(b, p + 2 * n + i) * 256 + readu8(b, p + 3 * n + i) @@ -82666,7 +82681,7 @@ end return out end -@native local function putU32s(w: Bytes.Writer, vals: { number }) +local function putU32s(w: Bytes.Writer, vals: { number }) local n = #vals local p = w:reserve(4 * n) local b = w.buf @@ -82679,21 +82694,21 @@ end end w.pos = p + 4 * n end -@native local function putI32s(w: Bytes.Writer, vals: { number }) +local function putI32s(w: Bytes.Writer, vals: { number }) local t = table.create(#vals, 0) for i, v in vals do t[i] = zigzag32(v) end putU32s(w, t) end -@native local function putF32s(w: Bytes.Writer, vals: { number }) +local function putF32s(w: Bytes.Writer, vals: { number }) local t = table.create(#vals, 0) for i, v in vals do t[i] = rotate(v) end putU32s(w, t) end -@native local function putI64s(w: Bytes.Writer, vals: { number }) +local function putI64s(w: Bytes.Writer, vals: { number }) local n = #vals local p = w:reserve(8 * n) local b = w.buf @@ -82714,7 +82729,7 @@ end end -- referent arrays: zigzag i32, interleaved, each the difference from the previous one -@native function Binary.readRefs(b: buffer, p: number, limit: number, n: number): ({ number }?, number) +function Binary.readRefs(b: buffer, p: number, limit: number, n: number): ({ number }?, number) if n < 0 or p + 4 * n > limit then return nil, p end @@ -82726,7 +82741,7 @@ end end return out, p + 4 * n end -@native function Binary.writeRefs(w: Bytes.Writer, refs: { number }) +function Binary.writeRefs(w: Bytes.Writer, refs: { number }) local d = table.create(#refs, 0) local prev = 0 for i, r in refs do @@ -82743,7 +82758,7 @@ type Ctx = { sharedIndex: ((string) -> number)?, } -@native local function str(b: buffer, p: number, limit: number): (string?, number) +local function str(b: buffer, p: number, limit: number): (string?, number) if p + 4 > limit then return nil, p end @@ -82754,7 +82769,7 @@ type Ctx = { return readstring(b, p + 4, len), p + 4 + len end -@native local function cframes(b: buffer, p: number, limit: number, n: number): ({ any }?, number) +local function cframes(b: buffer, p: number, limit: number, n: number): ({ any }?, number) local rots: { { number } } = table.create(n) :: any for i = 1, n do if p >= limit then @@ -82819,7 +82834,7 @@ local FIXED: { [number]: number } = { [0x21] = 8, } -@native function Binary.decode(t: number, b: buffer, p: number, limit: number, n: number, ctx: Ctx): ({ any }?, any) +function Binary.decode(t: number, b: buffer, p: number, limit: number, n: number, ctx: Ctx): ({ any }?, any) if limit > buffer.len(b) or p < 0 or n < 0 then return nil, "corrupt: bad ranges" end @@ -83111,10 +83126,10 @@ local FIXED: { [number]: number } = { return nil, "unknown" end -@native local function num(v: any): number +local function num(v: any): number return if type(v) == "number" and v == v then v else 0 end -@native local function column(vals: { any }, n: number, c: number): { number } +local function column(vals: { any }, n: number, c: number): { number } local out = table.create(n, 0) for i = 1, n do local v = vals[i] @@ -83123,12 +83138,12 @@ end return out end -@native local function putString(w: Bytes.Writer, s: string) +local function putString(w: Bytes.Writer, s: string) w:u32le(#s) w:string(s) end -@native local function putCFrames(w: Bytes.Writer, vals: { any }, n: number) +local function putCFrames(w: Bytes.Writer, vals: { any }, n: number) for i = 1, n do local v = vals[i] local cf = if type(v) == "table" then v else { 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1 } @@ -83145,11 +83160,11 @@ end putF32s(w, column(vals, n, 3)) end -@native local function hexByte(s: string, i: number): number +local function hexByte(s: string, i: number): number return tonumber(string.sub(s, 2 * i - 1, 2 * i), 16) or 0 end -@native function Binary.encode(t: number, vals: { any }, n: number, w: Bytes.Writer, ctx: Ctx): string? +function Binary.encode(t: number, vals: { any }, n: number, w: Bytes.Writer, ctx: Ctx): string? if t == 0x01 or t == 0x1D then for i = 1, n do local v = vals[i] @@ -87136,7 +87151,7 @@ end return Json end -__FILES["codecs/text/Json/Decode"] = @native function() +__FILES["codecs/text/Json/Decode"] = function() -- codecs/text/Json/Decode: the RFC 8259 parser behind codecs/text/Json: iterative, strict grammar. @@ -87171,7 +87186,7 @@ local ESC: { [number]: string } = { local utf8char = Text.utf8char Decode.utf8char = utf8char -@native local function hex4(s: string, i: number): number? +local function hex4(s: string, i: number): number? local h = match(s, "^%x%x%x%x", i) if not h then return nil @@ -87179,7 +87194,7 @@ Decode.utf8char = utf8char return tonumber(h, 16) end -@native local function str(s: string, i: number): (string?, any, number?) +local function str(s: string, i: number): (string?, any, number?) local j = find(s, '[%z\1-\31"\\]', i + 1) if not j then return nil, "unterminated string", #s @@ -87237,7 +87252,7 @@ end end Decode.string = str -@native local function num(s: string, i: number, bigStrings: boolean): (any, any, number?) +local function num(s: string, i: number, bigStrings: boolean): (any, any, number?) local p = i if byte(s, p) == 45 then p += 1 @@ -87287,7 +87302,7 @@ Decode.string = str end Decode.number = num -@native function Decode.value(s: string, i: number, opts: Options?): (any, any, number?) +function Decode.value(s: string, i: number, opts: Options?): (any, any, number?) local o: Options = opts or {} local ordered = o.ordered == true local bigStrings = o.bigInts == "string" @@ -87434,7 +87449,7 @@ Decode.number = num end end -@native function Decode.events(s: string, i: number, opts: Options?): () -> (string?, any, number?) +function Decode.events(s: string, i: number, opts: Options?): () -> (string?, any, number?) local o: Options = opts or {} local bigStrings = o.bigInts == "string" local nullv = if o.null ~= nil then o.null else Types.null @@ -87443,11 +87458,11 @@ end local depth = 0 local state = "value" local n = #s - @native local function fail(msg: string, at: number): (string, any, number) + local function fail(msg: string, at: number): (string, any, number) state = "dead" return "error", msg, at end - return @native function(): (string?, any, number?) + return function(): (string?, any, number?) if state == "dead" then return nil end @@ -87550,7 +87565,7 @@ end return Decode end -__FILES["codecs/text/Json/Encode"] = @native function() +__FILES["codecs/text/Json/Encode"] = function() -- codecs/text/Json/Encode: the RFC 8259 serializer behind codecs/text/Json. @@ -87589,7 +87604,7 @@ for c = 0, 31 do end end -@native local function utf16(cp: number): string +local function utf16(cp: number): string if cp < 0x10000 then return format("\\u%04x", cp) end @@ -87597,7 +87612,7 @@ end return format("\\u%04x\\u%04x", 0xD800 + cp // 1024, 0xDC00 + cp % 1024) end -@native local function asciiSeq(seq: string): string +local function asciiSeq(seq: string): string local out = {} local i, n = 1, #seq while i <= n do @@ -87619,7 +87634,7 @@ end end -- ascii escapes DEL too, like Python's ensure_ascii -@native local function quote(s: string, ascii: boolean?, slash: boolean?): string +local function quote(s: string, ascii: boolean?, slash: boolean?): string local pat = if slash then '[%z\1-\31"\\/]' else '[%z\1-\31"\\]' if string.find(s, pat) then s = gsub(s, pat, ESCAPES) @@ -87634,7 +87649,7 @@ end Encode.quote = quote local FLOAT_FORMATS = { "%.15g", "%.16g", "%.17g" } -@native local function number(x: number): string? +local function number(x: number): string? if x ~= x or x == huge or x == -huge then return nil end @@ -87654,7 +87669,7 @@ local FLOAT_FORMATS = { "%.15g", "%.16g", "%.17g" } end Encode.number = number -@native local function keyLess(a: any, b: any): boolean +local function keyLess(a: any, b: any): boolean local ta, tb = type(a), type(b) if ta ~= tb then return ta == "number" @@ -87662,7 +87677,7 @@ Encode.number = number return a < b end -@native local function kind(t: { [any]: any }, emptyObject: boolean): string +local function kind(t: { [any]: any }, emptyObject: boolean): string if Types.isObject(t) then return "object" end @@ -87695,13 +87710,13 @@ type State = { err: string?, } -@native local function put(st: State, s: string) +local function put(st: State, s: string) local n = st.n + 1 st.out[n] = s st.n = n end -@native local function value(st: State, v: any, depth: number): boolean +local function value(st: State, v: any, depth: number): boolean local tv = type(v) if tv == "string" then put(st, quote(v, st.ascii, st.slash)) @@ -87817,7 +87832,7 @@ end return true end -@native local function state(opts: Options?, nullv: any?): State +local function state(opts: Options?, nullv: any?): State local o: Options = opts or {} local ind: string? = nil if type(o.indent) == "number" then @@ -87842,7 +87857,7 @@ end Encode.state = state Encode.write = value -@native function Encode.encode(v: any, opts: Options?, nullv: any?): (string?, string?) +function Encode.encode(v: any, opts: Options?, nullv: any?): (string?, string?) local st = state(opts, nullv) if not value(st, v, 0) then return nil, st.err @@ -90474,7 +90489,7 @@ end return Xml end -__FILES["codecs/text/Xml/Parse"] = @native function() +__FILES["codecs/text/Xml/Parse"] = function() -- codecs/text/Xml/Parse: the XML 1.0 pull parser behind codecs/text/Xml: input decoding, line-ending normalization, @@ -90508,7 +90523,7 @@ local CP1252: { [number]: number } = { [0x9C] = 0x0153, [0x9E] = 0x017E, [0x9F] = 0x0178, } -@native local function utf16(s: string, start: number, le: boolean): (string?, string?) +local function utf16(s: string, start: number, le: boolean): (string?, string?) local out = table.create(#s // 2) local n = 0 local i = start @@ -90540,7 +90555,7 @@ local CP1252: { [number]: number } = { return table.concat(out), nil end -@native function Parse.toUtf8(s: string): (string?, string) +function Parse.toUtf8(s: string): (string?, string) local b1, b2, b3 = byte(s, 1, 3) if b1 == 0xEF and b2 == 0xBB and b3 == 0xBF then return sub(s, 4), "utf-8" @@ -90568,7 +90583,7 @@ end return s, e elseif e == "iso-8859-1" or e == "latin1" or e == "latin-1" or e == "iso8859-1" or e == "windows-1252" or e == "cp1252" then local w = e == "windows-1252" or e == "cp1252" - return (gsub(s, "[\128-\255]", @native function(c: string): string + return (gsub(s, "[\128-\255]", function(c: string): string local v = byte(c) return utf8char(if w then CP1252[v] or v else v) end)), e @@ -90584,7 +90599,7 @@ end end -- the pseudo-attributes, strictly: version, then encoding?, then standalone?, each after whitespace -@native local function xmlDecl(data: string): { [string]: string }? +local function xmlDecl(data: string): { [string]: string }? local p = 1 local out: { [string]: string } = {} for k, key in { "version", "encoding", "standalone" } do @@ -90612,7 +90627,7 @@ end return out end -@native function Parse.events(s: string, opts: Options?): () -> (string?, any, any, any) +function Parse.events(s: string, opts: Options?): () -> (string?, any, any, any) local o: Options = opts or {} local keepWs = o.whitespace == true local nsOn = o.namespaces == true @@ -90642,13 +90657,13 @@ end local errMsg: string? = nil local errAt = 0 - @native local function fail(msg: string, at: number): (string, string, number) + local function fail(msg: string, at: number): (string, string, number) dead = true return "error", msg, at - 1 end local decode: (raw: string, at: number, level: number) -> string? - @native function decode(raw: string, at: number, level: number): string? + function decode(raw: string, at: number, level: number): string? if not find(raw, "&", 1, true) then return raw end @@ -90711,7 +90726,7 @@ end return table.concat(parts) end - @native local function lookupNs(prefix: string): string? + local function lookupNs(prefix: string): string? for d = depth, 1, -1 do local m = nsStack[d] if m and m[prefix] ~= nil then @@ -90724,7 +90739,7 @@ end return nil end - @native local function literal(p: number): (string?, number) + local function literal(p: number): (string?, number) local q = byte(s, p) if q ~= 34 and q ~= 39 then return nil, p @@ -90736,7 +90751,7 @@ end return sub(s, p + 1, e - 1), e + 1 end -- ExternalID: SYSTEM "sys" | PUBLIC "pub" "sys" - @native local function externalId(p: number): (string?, string?, number?) + local function externalId(p: number): (string?, string?, number?) local kw = sub(s, p, p + 5) if kw == "SYSTEM" then local q = match(s, "^[ \t\n]+()", p + 6) :: any @@ -90769,7 +90784,7 @@ end end return nil, nil, nil end - @native local function entityValue(v: string): string? + local function entityValue(v: string): string? if find(v, "%", 1, true) then return nil -- parameter-entity references are not allowed in the internal subset's markup end @@ -90802,7 +90817,7 @@ end end return table.concat(parts) end - @native local function doctype(): (string?, any) + local function doctype(): (string?, any) local start = i local p = match(s, "^[ \t\n]+()", i) :: any if not p then @@ -90946,7 +90961,7 @@ end return sub(s, start, q - 1), info end - return @native function(): (string?, any, any, any) + return function(): (string?, any, any, any) if dead then return nil end @@ -91195,7 +91210,7 @@ end end end -@native function Parse.resolve(node: any, prefix: string): string? +function Parse.resolve(node: any, prefix: string): string? local p = node local key = if prefix == "" then "xmlns" else "xmlns:" .. prefix while p do @@ -91214,7 +91229,7 @@ end return Parse end -__FILES["codecs/video/Dsp"] = @native function() +__FILES["codecs/video/Dsp"] = function() @@ -91245,7 +91260,7 @@ end Dsp.CLAMP = CLAMP Dsp.COFF = COFF -@native function Dsp.idct(blk: buffer, dst: buffer, off: number, stride: number, add: boolean) +function Dsp.idct(blk: buffer, dst: buffer, off: number, stride: number, add: boolean) local tmp0, tmp1, tmp2, tmp3 = 0, 0, 0, 0 local tmp10, tmp11, tmp12, tmp13 = 0, 0, 0, 0 local z1, z2, z3, z4, z5 = 0, 0, 0, 0, 0 @@ -91837,7 +91852,7 @@ Dsp.COFF = COFF end -- the IDCT of a lone DC coefficient dc is (dc + 4) >> 3 everywhere -@native function Dsp.fill(dst: buffer, off: number, stride: number, v: number, add: boolean) +function Dsp.fill(dst: buffer, off: number, stride: number, v: number, add: boolean) if not add then local c = readu8(CLAMP, v + COFF) * 0x01010101 for _ = 1, 8 do @@ -91858,7 +91873,7 @@ end -- rounding up (MPEG-1 / 2, H.263 rounding_type 0); strides are twice the plane width for field prediction. -- Four bytes at a time: avg(a, b) = (a | b) - ((a ^ b) & 0xFE..) >> 1; the 4-tap average splits each byte into its -- low 2 bits and high 6 bits so no lane overflows. -@native function Dsp.mc(src: buffer, sStride: number, sOff: number, dst: buffer, dStride: number, dOff: number, w: number, h: number, hx: number, hy: number, avg: boolean) +function Dsp.mc(src: buffer, sStride: number, sOff: number, dst: buffer, dStride: number, dOff: number, w: number, h: number, hx: number, hy: number, avg: boolean) for _ = 1, h do for i = 0, w - 4, 4 do local p @@ -91891,7 +91906,7 @@ end end -- averages rounded down, (a + b) >> 1 and (a + b + c + d + 1) >> 2 (H.263 rounding type 1, MPEG-4 rounding_control) -@native function Dsp.mcNoRound(src: buffer, sStride: number, sOff: number, dst: buffer, dStride: number, dOff: number, w: number, h: number, hx: number, hy: number) +function Dsp.mcNoRound(src: buffer, sStride: number, sOff: number, dst: buffer, dStride: number, dOff: number, w: number, h: number, hx: number, hy: number) if hx == 0 and hy == 0 then Dsp.mc(src, sStride, sOff, dst, dStride, dOff, w, h, 0, 0, false) return @@ -91921,7 +91936,7 @@ end -- edge samples (w + 1 <= EDGE_STRIDE, h + 1 <= 33) Dsp.EDGE_STRIDE = 32 Dsp.EDGE_SIZE = 32 * 34 + 4 -@native function Dsp.edge(src: buffer, stride: number, base: number, x: number, y: number, w: number, h: number, pw: number, ph: number, out: buffer) +function Dsp.edge(src: buffer, stride: number, base: number, x: number, y: number, w: number, h: number, pw: number, ph: number, out: buffer) for j = 0, h do local sy = y + j sy = if sy < 0 then 0 elseif sy >= ph then ph - 1 else sy @@ -92093,7 +92108,7 @@ end return H263 end -__FILES["codecs/video/H263/Decoder"] = @native function() +__FILES["codecs/video/H263/Decoder"] = function() @@ -92183,11 +92198,11 @@ type Store = { } -- the length of a slice's MBA field for a picture of n macroblocks (table K.2) -@native function D.mbaBits(n: number): number +function D.mbaBits(n: number): number return if n <= 48 then 6 elseif n <= 99 then 7 elseif n <= 396 then 9 elseif n <= 1584 then 11 elseif n <= 6336 then 13 else 14 end -@native local function bitsAt(buf: buffer, endByte: number, p: number, n: number): number +local function bitsAt(buf: buffer, endByte: number, p: number, n: number): number local v = 0 for k = p, p + n - 1 do local byte = rshift(k, 3) @@ -92198,7 +92213,7 @@ end end -- picture start code: H.263 22 bits 0..01 00000; Sorenson 17 bits 0..01, then version 0 / 1 -@native local function findStart(buf: buffer, off: number, len: number, flv: boolean): number +local function findStart(buf: buffer, off: number, len: number, flv: boolean): number local mask = if flv then 0xF8 else 0xFC for i = off, off + len - 3 do if readu8(buf, i) == 0 and readu8(buf, i + 1) == 0 and band(readu8(buf, i + 2), mask) == 0x80 then @@ -92209,7 +92224,7 @@ end end -- pictures with UFEP = 0 keep the previous picture's PLUSPTYPE options (opp) -@native function D.header(buf: buffer, off: number, len: number, flv: boolean, opp: Opp?): (Header?, string?) +function D.header(buf: buffer, off: number, len: number, flv: boolean, opp: Opp?): (Header?, string?) if off < 0 or len < 0 or off + len > buffer.len(buf) then return nil, "bad range" end @@ -92219,7 +92234,7 @@ end end local e = off + len local p = s * 8 - @native local function bits(n: number): number + local function bits(n: number): number local v = bitsAt(buf, e, p, n) p += n return v @@ -92425,7 +92440,7 @@ type Core = { }, } -@native function D.new(flv: boolean, maxPixels: number?): Core +function D.new(flv: boolean, maxPixels: number?): Core local state = { width = 0, height = 0, @@ -92456,7 +92471,7 @@ type Core = { local blk = buffer.create(256) local EDGE = buffer.create(Dsp.EDGE_SIZE) - @native local function read(n: number): number + local function read(n: number): number local bp = rshift(pos, 3) local w = bswap(readu32(data, bp)) local s = band(pos, 7) @@ -92467,7 +92482,7 @@ type Core = { return rshift(w, 32 - n) end - @native local function peek32(): number + local function peek32(): number local bp = rshift(pos, 3) local w = bswap(readu32(data, bp)) local s = band(pos, 7) @@ -92477,7 +92492,7 @@ type Core = { return w end - @native local function vlc(lut: buffer, k: number): number + local function vlc(lut: buffer, k: number): number local e = readu32(lut, rshift(peek32(), 32 - k) * 4) local l = rshift(e, 16) if l == 0 then @@ -92488,7 +92503,7 @@ type Core = { return band(e, 0xFFFF) end - @native local function alloc(w: number, h: number) + local function alloc(w: number, h: number) W, H = w, h mbW, mbH = (w + 15) // 16, (h + 15) // 16 ls, cs, lh, chh = mbW * 16, mbW * 8, mbH * 16, mbH * 8 @@ -92507,7 +92522,7 @@ type Core = { end -- intra blocks: INTRADC, then the coded coefficients from position 1 - @native local function block(intra: boolean, coded: boolean, dst: buffer, off: number, stride: number): boolean + local function block(intra: boolean, coded: boolean, dst: buffer, off: number, stride: number): boolean local i = 0 local dcOnly = true if intra then @@ -92618,7 +92633,7 @@ type Core = { return true end - @native local function motion(pred: number): number + local function motion(pred: number): number if umvPlus then -- reversible codes (Annex D.2): "1" = 0, else 0 x0 (1 x)* 0, the last x the sign if read(1) == 1 then @@ -92657,7 +92672,7 @@ type Core = { return (v + 32) % 64 - 32 -- the code pair's value in -16 .. 15.5 end - @native local function predict(col: number, row: number, mx: number, my: number) + local function predict(col: number, row: number, mx: number, my: number) local hx, hy = mx % 2, my % 2 local sx, sy = col * 16 + (mx - hx) // 2, row * 16 + (my - hy) // 2 local dOff = row * 16 * ls + col * 16 @@ -92684,7 +92699,7 @@ type Core = { end end - @native local function copyMb(col: number, row: number) + local function copyMb(col: number, row: number) local yo, co = row * 16 * ls + col * 16, row * 8 * cs + col * 8 if ref then mc(refY, ls, yo, curY, ls, yo, 16, 16, 0, 0, false) @@ -92700,7 +92715,7 @@ type Core = { end end - @native local function macroblock(col: number, row: number, P: boolean, top: boolean, first: boolean): boolean + local function macroblock(col: number, row: number, P: boolean, top: boolean, first: boolean): boolean if pos > endBits then return false end @@ -92780,7 +92795,7 @@ type Core = { end -- a GBSC / SSC (17 bits 0..01) next, after zero stuffing to a byte boundary or not: consumed, true - @native local function startCode(): boolean + local function startCode(): boolean local w = peek32() if rshift(w, 15) ~= 1 then local s = (8 - pos % 8) % 8 @@ -92793,7 +92808,7 @@ type Core = { return true end - @native local function gobHeader(cpm: boolean): (number?, number?) + local function gobHeader(cpm: boolean): (number?, number?) if not startCode() then return nil, nil end @@ -92805,7 +92820,7 @@ type Core = { return gn, read(5) end - @native local function sliceHeader(cpm: boolean, mbaBits: number, sepb2: boolean): (number?, number?) + local function sliceHeader(cpm: boolean, mbaBits: number, sepb2: boolean): (number?, number?) if not startCode() then return nil, nil end @@ -92822,7 +92837,7 @@ type Core = { return mba, q end - @native local function picture(hdr: Header): (Store?, string?) + local function picture(hdr: Header): (Store?, string?) if hdr.width ~= W or hdr.height ~= H then if hdr.width * hdr.height > state.maxPixels then return nil, "limit: picture size " .. hdr.width .. "x" .. hdr.height @@ -92918,7 +92933,7 @@ type Core = { local core = {} :: Core core.state = state - @native function core.decode(buf: buffer, off: number, len: number): (Store?, string?) + function core.decode(buf: buffer, off: number, len: number): (Store?, string?) local hdr, herr = D.header(buf, off, len, flv, state.opp) if not hdr then state.errors += 1 @@ -92942,7 +92957,7 @@ type Core = { return s, msg end - @native function core.reset() + function core.reset() ref = nil end @@ -93527,7 +93542,7 @@ end return H264 end -__FILES["codecs/video/H264/Bitstream"] = @native function() +__FILES["codecs/video/H264/Bitstream"] = function() @@ -93547,7 +93562,7 @@ type Reader = { } -- start codes are 00 00 01 with any leading zero bytes; trailing zero bytes of a NAL are dropped -@native function Bitstream.splitAnnexB(buf: buffer, off: number, len: number): { number } +function Bitstream.splitAnnexB(buf: buffer, off: number, len: number): { number } local out = {} local e = off + len local i = off @@ -93588,7 +93603,7 @@ type Reader = { return out end -@native function Bitstream.isAnnexB(buf: buffer, off: number, len: number): boolean +function Bitstream.isAnnexB(buf: buffer, off: number, len: number): boolean if len >= 3 and readu8(buf, off) == 0 and readu8(buf, off + 1) == 0 then local b2 = readu8(buf, off + 2) if b2 == 1 then @@ -93599,7 +93614,7 @@ end return false end -@native function Bitstream.splitLength(buf: buffer, off: number, len: number, size: number): ({ number }?, { number }) +function Bitstream.splitLength(buf: buffer, off: number, len: number, size: number): ({ number }?, { number }) local out = {} local e = off + len local p = off @@ -93621,7 +93636,7 @@ end return out, out end -@native function Bitstream.parseAvcC(buf: buffer, off: number, len: number): (any, string?) +function Bitstream.parseAvcC(buf: buffer, off: number, len: number): (any, string?) if len < 7 then return nil, "truncated: avcC shorter than 7 bytes" end @@ -93661,7 +93676,7 @@ end end -- emulation_prevention_three_byte (00 00 03) is removed -@native function Bitstream.reader(buf: buffer, off: number, len: number, skip: number): Reader +function Bitstream.reader(buf: buffer, off: number, len: number, skip: number): Reader local out = buffer.create(len + 8) local o = 0 local zeros = 0 @@ -93713,7 +93728,7 @@ for x = 0, 255 do end Bitstream.LZ8 = LZ8 -@native local function clz32(v: number): number +local function clz32(v: number): number if v >= 16777216 then return LZ8[v // 16777216 + 1] elseif v >= 65536 then @@ -93725,7 +93740,7 @@ Bitstream.LZ8 = LZ8 end Bitstream.clz32 = clz32 -@native local function peekAt(b: buffer, n: number, pos: number): number +local function peekAt(b: buffer, n: number, pos: number): number local p = pos // 8 if p + 5 > n then return 0 @@ -93739,18 +93754,18 @@ Bitstream.clz32 = clz32 end Bitstream.peekAt = peekAt -@native local function peek32(r: Reader): number +local function peek32(r: Reader): number return peekAt(r.buf, r.n, r.pos) end Bitstream.peek32 = peek32 -@native function Bitstream.u(r: Reader, n: number): number +function Bitstream.u(r: Reader, n: number): number local v = peekAt(r.buf, r.n, r.pos) r.pos += n return v // P2[33 - n] end -@native function Bitstream.u1(r: Reader): number +function Bitstream.u1(r: Reader): number local pos = r.pos r.pos = pos + 1 local p = pos // 8 @@ -93761,7 +93776,7 @@ end end -- more than 31 leading zeros returns 2^32 (out of range for every syntax element) -@native local function ue(r: Reader): number +local function ue(r: Reader): number local v = peekAt(r.buf, r.n, r.pos) if v == 0 then r.pos += 32 @@ -93780,7 +93795,7 @@ end end Bitstream.ue = ue -@native function Bitstream.se(r: Reader): number +function Bitstream.se(r: Reader): number local k = ue(r) if k % 2 == 1 then return (k + 1) // 2 @@ -93788,7 +93803,7 @@ Bitstream.ue = ue return -(k // 2) end -@native function Bitstream.te(r: Reader, range: number): number +function Bitstream.te(r: Reader, range: number): number if range == 1 then return 1 - Bitstream.u1(r) end @@ -93796,13 +93811,13 @@ end end -- more_rbsp_data() -@native function Bitstream.moreData(r: Reader): boolean +function Bitstream.moreData(r: Reader): boolean return r.pos < r.stop end return Bitstream end -__FILES["codecs/video/H264/Cabac"] = @native function() +__FILES["codecs/video/H264/Cabac"] = function() @@ -93856,7 +93871,7 @@ local ebuf: buffer = buffer.create(1) local epos, elimit = 0, 0 local erange, elow, enb = 510, 0, 0 -@native local function refill() +local function refill() local b = 0 if epos < elimit then b = readu8(ebuf, epos) @@ -93867,7 +93882,7 @@ local erange, elow, enb = 510, 0, 0 end -- decision (9.3.3.2.1): the LPS test is min(1, low // scaled) (low < 2.5 * scaled always) -@native local function decision(ctx: number): number +local function decision(ctx: number): number local s = ST[ctx + 1] local range = erange local lps = LPSR[s * 4 + (range // 64) % 4 + 1] @@ -93887,7 +93902,7 @@ end return BINS[k] end -@native local function bypass(): number +local function bypass(): number enb -= 1 local scaled = erange * POW2[enb + 1] local bin = elow // scaled @@ -93898,7 +93913,7 @@ end return bin end -@native local function terminate(): number +local function terminate(): number local r = erange - 2 local scaled = r * POW2[enb + 1] if elow >= scaled then @@ -93916,7 +93931,7 @@ end return 0 end -@native local function engineInit(b: buffer, p: number, limit: number) +local function engineInit(b: buffer, p: number, limit: number) ebuf, epos, elimit = b, p, limit elow, enb = 0, -9 refill() @@ -93926,11 +93941,11 @@ end end -- the bit position the spec's decoder is at (after a terminate bin of 1) -@native local function bitPos(): number +local function bitPos(): number return epos * 8 - enb end -@native local function initContexts(sliceQp: number, model: number) +local function initContexts(sliceQp: number, model: number) local init = Tables.CABAC_INIT local qp = math.clamp(sliceQp, 0, 51) for ctx = 0, 459 do @@ -93964,7 +93979,7 @@ do end local SIG3 = { 0, 1, 2 } -@native local function block(cat: number, out: { number }, base: number, mul: { number }?, div: number): number +local function block(cat: number, out: { number }, base: number, mul: { number }?, div: number): number local maxc = MAXC[cat + 1] local n = 0 local last = false @@ -94063,14 +94078,14 @@ local SIG3 = { 0, 1, 2 } end -- condition helpers on neighbouring macroblocks (addresses are 1-based here) -@native local function leftAddr(S: any, M: any): number +local function leftAddr(S: any, M: any): number return ((M.aL) and (M.addr) or (0)) end -@native local function topAddr(S: any, M: any): number +local function topAddr(S: any, M: any): number return ((M.aT) and (M.addr - S.mbW + 1) or (0)) end -@native local function mbSkipFlag(S: any, M: any): number +local function mbSkipFlag(S: any, M: any): number local k = S.kind local a, b = leftAddr(S, M), topAddr(S, M) local inc = 0 @@ -94084,7 +94099,7 @@ end end -- intra mb_type (I slice: prefix false, offset 3; P / B suffix: offset 17 / 32) -> 0..25 -@native local function intraType(S: any, M: any, off: number): number +local function intraType(S: any, M: any, off: number): number local b0 if off == 3 then local k = S.kind @@ -94127,7 +94142,7 @@ end return 1 + pred + 4 * chroma + 12 * luma end -@native local function pMbType(): number +local function pMbType(): number -- 0..3 inter, 5+ intra (returned as -1: the caller decodes the suffix) if decision(14) == 1 then return -1 @@ -94138,7 +94153,7 @@ end return ((decision(17) == 1) and (1) or (2)) end -@native local function bMbType(S: any, M: any): number +local function bMbType(S: any, M: any): number local k = S.kind local a, b = leftAddr(S, M), topAddr(S, M) local inc = 0 @@ -94171,7 +94186,7 @@ end return bits - 4 end -@native local function pSubType(): number +local function pSubType(): number if decision(21) == 1 then return 0 end @@ -94181,7 +94196,7 @@ end return ((decision(23) == 1) and (2) or (3)) end -@native local function bSubType(): number +local function bSubType(): number if decision(36) == 0 then return 0 end @@ -94200,7 +94215,7 @@ end return t end -@native local function refIdx(S: any, M: any, rgt: { number }, x: number, y: number): number +local function refIdx(S: any, M: any, rgt: { number }, x: number, y: number): number local g = M.g0 + y * S.w4 + x local inc = 0 if (x > 0 or M.aL) and rgt[g - 1] ~= 0 then @@ -94225,7 +94240,7 @@ end end -- the mvd grid holds |mvd| (2 per 4x4) -@native local function mvd(S: any, M: any, grid: { number }, x: number, y: number, comp: number): number +local function mvd(S: any, M: any, grid: { number }, x: number, y: number, comp: number): number local g = M.g0 + y * S.w4 + x local sum = 0 if x > 0 or M.aL then @@ -94272,7 +94287,7 @@ end return v end -@native local function fillRegion(S: any, M: any, grid: { number }, x: number, y: number, w: number, h: number, v: number) +local function fillRegion(S: any, M: any, grid: { number }, x: number, y: number, w: number, h: number, v: number) local w4 = S.w4 for j = y, y + h - 1 do local g = M.g0 + j * w4 + x @@ -94282,7 +94297,7 @@ end end end -@native local function fillMvd(S: any, M: any, grid: { number }, x: number, y: number, w: number, h: number, ax: number, ay: number) +local function fillMvd(S: any, M: any, grid: { number }, x: number, y: number, w: number, h: number, ax: number, ay: number) local w4 = S.w4 for j = y, y + h - 1 do local g = M.g0 + j * w4 + x @@ -94293,7 +94308,7 @@ end end end -@native local function cbpCabac(S: any, M: any): number +local function cbpCabac(S: any, M: any): number local cbpTab = S.cbpTab local a, b = leftAddr(S, M), topAddr(S, M) local luma = 0 @@ -94333,7 +94348,7 @@ end return luma + 16 * chroma end -@native local function qpDelta(S: any): number +local function qpDelta(S: any): number local k = 0 if decision(60 + (((S.lastQpd) and (1) or (0)))) == 1 then k = 1 @@ -94352,7 +94367,7 @@ end return -(k // 2) end -@native local function chromaPredMode(S: any, M: any): number +local function chromaPredMode(S: any, M: any): number local a, b = leftAddr(S, M), topAddr(S, M) local cpm, kind = S.cpmTab, S.kind local inc = 0 @@ -94371,7 +94386,7 @@ end return 2 + decision(67) end -@native local function t8Flag(S: any, M: any): number +local function t8Flag(S: any, M: any): number local a, b = leftAddr(S, M), topAddr(S, M) local t8 = S.t8Tab local inc = 0 @@ -94385,12 +94400,12 @@ end end -- coded_block_flag condition of a neighbour: v = the neighbour's flag when its block is available -@native local function cbf(cat: number, condA: number, condB: number): number +local function cbf(cat: number, condA: number, condB: number): number return decision(85 + CAT_CBF[cat + 1] + condA + 2 * condB) end -- luma 4x4 coded_block_flag neighbours of (bx, by) -@native local function lumaCond(S: any, M: any, bx: number, by: number, intra: boolean): (number, number) +local function lumaCond(S: any, M: any, bx: number, by: number, intra: boolean): (number, number) local g = M.g0 + by * S.w4 + bx local nzc = S.nzc local ca, cb @@ -94411,7 +94426,7 @@ end return ca, cb end -@native local function chromaCond(S: any, M: any, tab: { number }, bx: number, by: number, intra: boolean): (number, number) +local function chromaCond(S: any, M: any, tab: { number }, bx: number, by: number, intra: boolean): (number, number) local cw = S.cw4 local g = M.c0 + by * cw + bx local ca, cb @@ -94428,7 +94443,7 @@ end return ca, cb end -@native local function dcCond(S: any, M: any, bit: number, intra: boolean): (number, number) +local function dcCond(S: any, M: any, bit: number, intra: boolean): (number, number) local dc = S.dcTab local a, b = leftAddr(S, M), topAddr(S, M) local ca, cb @@ -94445,7 +94460,7 @@ end return ca, cb end -@native local function residuals(S: any, M: any): boolean +local function residuals(S: any, M: any): boolean local kind = M.kind local cbp = M.cbp local intra = kind <= K_PCM @@ -94545,7 +94560,7 @@ end return true end -@native local function setQp(S: any, M: any, delta: number): boolean +local function setQp(S: any, M: any, delta: number): boolean if delta < -26 or delta > 25 then return false end @@ -94558,7 +94573,7 @@ end return true end -@native local function clearCounts(M: any) +local function clearCounts(M: any) local nz = M.nz for i = 1, 16 do nz[i] = 0 @@ -94577,7 +94592,7 @@ local SUB_H = { 2, 1, 2, 1 } local BPAIR0 = { 1, 2, 1, 2, 1, 2, 3, 3, 3 } local BPAIR1 = { 1, 2, 2, 1, 3, 3, 1, 2, 3 } -@native local function intraMb(S: any, M: any, r: Bitstream.Reader, t: number): (boolean, string?) +local function intraMb(S: any, M: any, r: Bitstream.Reader, t: number): (boolean, string?) local addr = M.addr + 1 local w4, g0 = S.w4, M.g0 fillRegion(S, M, S.rgt0, 0, 0, 4, 4, 0) @@ -94677,7 +94692,7 @@ local BPAIR1 = { 1, 2, 2, 1, 3, 3, 1, 2, 3 } return true end -@native local function interMb(S: any, M: any, r: Bitstream.Reader, t: number, isB: boolean): (boolean, string?) +local function interMb(S: any, M: any, r: Bitstream.Reader, t: number, isB: boolean): (boolean, string?) clearCounts(M) local n0, n1 = S.n0, S.n1 local pf, sub, dir, ref0, ref1, mvd0, mvd1 = M.pf, M.sub, M.dir, M.ref0, M.ref1, M.mvd0, M.mvd1 @@ -94870,7 +94885,7 @@ end return true end -@native local function macroblock(S: any, M: any, r: Bitstream.Reader): (boolean, string?) +local function macroblock(S: any, M: any, r: Bitstream.Reader): (boolean, string?) local st = S.type if st == 2 then return intraMb(S, M, r, intraType(S, M, 3)) @@ -94888,7 +94903,7 @@ end return interMb(S, M, r, t, true) end -@native function Cabac.slice(S: any, M: any, r: Bitstream.Reader): (boolean, string?) +function Cabac.slice(S: any, M: any, r: Bitstream.Reader): (boolean, string?) local p = (r.pos + 7) // 8 local limit = r.size // 8 if p >= limit then @@ -94933,7 +94948,7 @@ end return Cabac end -__FILES["codecs/video/H264/Cavlc"] = @native function() +__FILES["codecs/video/H264/Cavlc"] = function() @@ -94952,7 +94967,7 @@ local Cavlc = {} -- build(entries) -> l1, l2: a two-level lookup on 16 peeked bits. l1[(v >> 8) + 1] = value * 32 + length, or -- -(base) of a second-level block l2[base + (v & 255)]; 0 = no code -@native local function build(entries: { { number } }): ({ number }, { number }) +local function build(entries: { { number } }): ({ number }, { number }) local l1 = table.create(256, 0) local l2 = {} local nsub = 0 @@ -94996,7 +95011,7 @@ for t = 0, 4 do end -- total_zeros by tzVlcIndex (luma 1..15, chroma DC 1..3), run_before by min(zerosLeft, 7) -@native local function group(src: { number }, n: number): ({ { number } }, { { number } }) +local function group(src: { number }, n: number): ({ { number } }, { { number } }) local per = {} for i = 1, n do per[i] = {} @@ -95040,7 +95055,7 @@ local clz32 = Bitstream.clz32 local P2 = Bitstream.P2 -- levels go to out[base + scan[i] + 1] as (level * mul[pos + 1] + div / 2) // div (mul nil: raw levels) -@native local function residual(r: Bitstream.Reader, nC: number, maxCoeff: number, out: { number }, base: number, scan: { number }, mul: { number }?, div: number): number +local function residual(r: Bitstream.Reader, nC: number, maxCoeff: number, out: { number }, base: number, scan: { number }, mul: { number }?, div: number): number local b, n = r.buf, r.n local pos = r.pos local cls @@ -95192,7 +95207,7 @@ local SUB_N = { 1, 2, 2, 4 } local BPAIR0 = { 1, 2, 1, 2, 1, 2, 3, 3, 3 } local BPAIR1 = { 1, 2, 2, 1, 3, 3, 1, 2, 3 } -@native local function refIdx(r: Bitstream.Reader, n: number): number +local function refIdx(r: Bitstream.Reader, n: number): number if n <= 1 then return 0 end @@ -95208,7 +95223,7 @@ local BPAIR1 = { 1, 2, 2, 1, 3, 3, 1, 2, 3 } return v end -@native local function residuals(S: any, M: any, r: Bitstream.Reader): (boolean, string?) +local function residuals(S: any, M: any, r: Bitstream.Reader): (boolean, string?) local kind = M.kind local cbp = M.cbp local intra = kind <= K_PCM @@ -95307,7 +95322,7 @@ end return true end -@native local function setQp(S: any, M: any, delta: number): boolean +local function setQp(S: any, M: any, delta: number): boolean if delta < -26 or delta > 25 then return false end @@ -95319,7 +95334,7 @@ end return true end -@native local function clearLumaGrids(S: any, M: any, intra: boolean) +local function clearLumaGrids(S: any, M: any, intra: boolean) -- the CABAC-only grids stay zero for CAVLC; intra modes for non-NxN macroblocks are written by Mb.recon local _ = intra local nz = M.nz @@ -95333,7 +95348,7 @@ end end -- intra macroblock types 0..25 (table 7-11) -@native local function intraMb(S: any, M: any, r: Bitstream.Reader, t: number): (boolean, string?) +local function intraMb(S: any, M: any, r: Bitstream.Reader, t: number): (boolean, string?) local addr = M.addr + 1 if t == 25 then M.kind = K_PCM @@ -95444,7 +95459,7 @@ end end -- the P (0..4) and B (0..22) inter macroblock types -@native local function interMb(S: any, M: any, r: Bitstream.Reader, t: number, isB: boolean): (boolean, string?) +local function interMb(S: any, M: any, r: Bitstream.Reader, t: number, isB: boolean): (boolean, string?) clearLumaGrids(S, M, false) local n0, n1 = S.n0, S.n1 local pf, sub, dir, ref0, ref1, mvd0, mvd1 = M.pf, M.sub, M.dir, M.ref0, M.ref1, M.mvd0, M.mvd1 @@ -95637,7 +95652,7 @@ end return true end -@native local function macroblock(S: any, M: any, r: Bitstream.Reader): (boolean, string?) +local function macroblock(S: any, M: any, r: Bitstream.Reader): (boolean, string?) local t = ue(r) local st = S.type if st == 2 then @@ -95654,7 +95669,7 @@ end return interMb(S, M, r, t, true) end -@native function Cavlc.slice(S: any, M: any, r: Bitstream.Reader): (boolean, string?) +function Cavlc.slice(S: any, M: any, r: Bitstream.Reader): (boolean, string?) local addr = S.firstMb local total = S.mbW * S.mbH local st = S.type @@ -95701,7 +95716,7 @@ end return Cavlc end -__FILES["codecs/video/H264/Deblock"] = @native function() +__FILES["codecs/video/H264/Deblock"] = function() @@ -95718,13 +95733,13 @@ local Deblock = {} local BS = table.create(4, 0) local min, max = math.min, math.max -@native local function clip3(lo: number, hi: number, v: number): number +local function clip3(lo: number, hi: number, v: number): number return min(max(v, lo), hi) end local abs = math.abs -@native local function luma(b: buffer, o: number, across: number, along: number, qp: number, aOff: number, bOff: number) +local function luma(b: buffer, o: number, across: number, along: number, qp: number, aOff: number, bOff: number) local indexA = clip3(0, 51, qp + aOff) local alpha = ALPHA[indexA + 13] local beta = BETA[clip3(0, 51, qp + bOff) + 13] @@ -95783,7 +95798,7 @@ local abs = math.abs end -- chroma: bS of luma segment i // 2 -@native local function chroma(b: buffer, o: number, across: number, along: number, qp: number, aOff: number, bOff: number) +local function chroma(b: buffer, o: number, across: number, along: number, qp: number, aOff: number, bOff: number) local indexA = clip3(0, 51, qp + aOff) local alpha = ALPHA[indexA + 13] local beta = BETA[clip3(0, 51, qp + bOff) + 13] @@ -95814,11 +95829,11 @@ end end -- the bS 1 motion test of 8.7.2.1 -@native local function mvDiff(mvA: { number }, a: number, mvB: { number }, b: number): boolean +local function mvDiff(mvA: { number }, a: number, mvB: { number }, b: number): boolean return abs(mvA[2 * a - 1] - mvB[2 * b - 1]) >= 4 or abs(mvA[2 * a] - mvB[2 * b]) >= 4 end -@native local function motionDiffers(pic: any, p: number, q: number): boolean +local function motionDiffers(pic: any, p: number, q: number): boolean local uid0, uid1, mv0, mv1 = pic.uid0, pic.uid1, pic.mv0, pic.mv1 local pa, pb, qa, qb = uid0[p], uid1[p], uid0[q], uid1[q] local np = (((pa >= 0) and (1) or (0))) + (((pb >= 0) and (1) or (0))) @@ -95854,7 +95869,7 @@ end return (mvDiff(mv0, p, mv0, q) or mvDiff(mv1, p, mv1, q)) and (mvDiff(mv0, p, mv1, q) or mvDiff(mv1, p, mv0, q)) end -@native function Deblock.picture(S: any, pic: any, params: { any }) +function Deblock.picture(S: any, pic: any, params: { any }) local mbW, mbH = S.mbW, S.mbH local w4 = S.w4 local kind, sliceTab, qpTab, qpcTab, qpc2Tab, t8Tab = S.kind, S.sliceTab, S.qpTab, S.qpcTab, S.qpc2Tab, S.t8Tab @@ -96968,7 +96983,7 @@ end return Decoder end -__FILES["codecs/video/H264/Inter"] = @native function() +__FILES["codecs/video/H264/Inter"] = function() @@ -96982,14 +96997,14 @@ Inter.PAD = 32 Inter.PADC = 16 local min, max = math.min, math.max -@native local function clip(v: number): number +local function clip(v: number): number return min(max(v, 0), 255) end local B1 = table.create(24 * 17, 0) -- one small function per six-tap case: LuaJIT keeps each loop in one trace -@native local function lumaCopy(ref: buffer, s: number, base: number, w: number, h: number, P: { number }) +local function lumaCopy(ref: buffer, s: number, base: number, w: number, h: number, P: { number }) for r = 0, h - 1 do local o = base + r * s local d = r * 16 + 1 @@ -97000,7 +97015,7 @@ local B1 = table.create(24 * 17, 0) end -- horizontal half sample b; avg 0: b, 1: (G + b + 1) >> 1, 2: (b + H + 1) >> 1 -@native local function lumaH(ref: buffer, s: number, base: number, w: number, h: number, P: { number }, avg: number) +local function lumaH(ref: buffer, s: number, base: number, w: number, h: number, P: { number }, avg: number) for r = 0, h - 1 do local o = base + r * s local d = r * 16 + 1 @@ -97020,7 +97035,7 @@ end end -- vertical half sample h; avg 0: h, 1: (G + h + 1) >> 1, 2: (h + G below + 1) >> 1 -@native local function lumaV(ref: buffer, s: number, base: number, w: number, h: number, P: { number }, avg: number) +local function lumaV(ref: buffer, s: number, base: number, w: number, h: number, P: { number }, avg: number) for c = 0, w - 1 do local o = base + c local a0, a1, a2, a3, a4 = readu8(ref, o - 2 * s), readu8(ref, o - s), readu8(ref, o), readu8(ref, o + s), readu8(ref, o + 2 * s) @@ -97040,7 +97055,7 @@ end end -- B1 rows -2 .. h + 2, columns 0 .. w (unrounded horizontal intermediates), stride 17 -@native local function horizontal1(ref: buffer, s: number, base: number, w: number, h: number) +local function horizontal1(ref: buffer, s: number, base: number, w: number, h: number) for r = -2, h + 2 do local o = base + r * s local d = (r + 2) * 17 + 1 @@ -97054,7 +97069,7 @@ end end -- centre j; with = 0: j, 1: (b + j + 1) >> 1 (b of this row), 2: (s + j + 1) >> 1 (b of the next row) -@native local function lumaJ(ref: buffer, s: number, base: number, w: number, h: number, P: { number }, with: number) +local function lumaJ(ref: buffer, s: number, base: number, w: number, h: number, P: { number }, with: number) horizontal1(ref, s, base, w, h) for c = 0, w - 1 do local k = 2 * 17 + 1 + c @@ -97075,7 +97090,7 @@ end end -- (j + h + 1) >> 1 with h at column c + co (co 0: i, 1: k) -@native local function lumaJV(ref: buffer, s: number, base: number, w: number, h: number, P: { number }, co: number) +local function lumaJV(ref: buffer, s: number, base: number, w: number, h: number, P: { number }, co: number) lumaJ(ref, s, base, w, h, P, 0) for c = 0, w - 1 do local o = base + c + co @@ -97091,7 +97106,7 @@ end end -- diagonal quarter samples e, g, p, r: (b or s) averaged with (h or m) -@native local function lumaDiag(ref: buffer, s: number, base: number, w: number, h: number, P: { number }, ro: number, co: number) +local function lumaDiag(ref: buffer, s: number, base: number, w: number, h: number, P: { number }, ro: number, co: number) lumaH(ref, s, base + ro, w, h, P, 0) for c = 0, w - 1 do local o = base + c + co @@ -97106,7 +97121,7 @@ end end end -@native function Inter.luma(ref: buffer, s: number, base: number, fx: number, fy: number, w: number, h: number, P: { number }) +function Inter.luma(ref: buffer, s: number, base: number, fx: number, fy: number, w: number, h: number, P: { number }) if fy == 0 then if fx == 0 then lumaCopy(ref, s, base, w, h, P) @@ -97124,7 +97139,7 @@ end end end -@native function Inter.chroma(ref: buffer, s: number, base: number, fx: number, fy: number, w: number, h: number, P: { number }) +function Inter.chroma(ref: buffer, s: number, base: number, fx: number, fy: number, w: number, h: number, P: { number }) if fx == 0 and fy == 0 then for r = 0, h - 1 do local o = base + r * s @@ -97149,7 +97164,7 @@ end end end -@native function Inter.put(P: { number }, w: number, h: number, b: buffer, o: number, s: number) +function Inter.put(P: { number }, w: number, h: number, b: buffer, o: number, s: number) for r = 0, h - 1 do local d = r * 16 + 1 local q = o + r * s @@ -97160,7 +97175,7 @@ end end -- default bi-prediction (P0 + P1 + 1) >> 1 -@native function Inter.avg(P0: { number }, P1: { number }, w: number, h: number, b: buffer, o: number, s: number) +function Inter.avg(P0: { number }, P1: { number }, w: number, h: number, b: buffer, o: number, s: number) for r = 0, h - 1 do local d = r * 16 + 1 local q = o + r * s @@ -97171,7 +97186,7 @@ end end -- explicit single-list weighting (8-270 / 8-271) -@native function Inter.weight1(P: { number }, w: number, h: number, b: buffer, o: number, s: number, logWD: number, wt: number, off: number) +function Inter.weight1(P: { number }, w: number, h: number, b: buffer, o: number, s: number, logWD: number, wt: number, off: number) if logWD >= 1 then local rnd = 2 ^ (logWD - 1) local div = 2 ^ logWD @@ -97194,7 +97209,7 @@ end end -- explicit / implicit bi-prediction weighting (8-272); off = (o0 + o1 + 1) >> 1 -@native function Inter.weight2(P0: { number }, P1: { number }, w: number, h: number, b: buffer, o: number, s: number, logWD: number, w0: number, w1: number, off: number) +function Inter.weight2(P0: { number }, P1: { number }, w: number, h: number, b: buffer, o: number, s: number, logWD: number, w0: number, w1: number, off: number) local rnd = 2 ^ logWD local div = 2 ^ (logWD + 1) for r = 0, h - 1 do @@ -97206,7 +97221,7 @@ end end end -@native function Inter.extend(b: buffer, o: number, s: number, w: number, h: number, pad: number) +function Inter.extend(b: buffer, o: number, s: number, w: number, h: number, pad: number) for y = 0, h - 1 do local r = o + y * s buffer.fill(b, r - pad, readu8(b, r), pad) @@ -97222,7 +97237,7 @@ end return Inter end -__FILES["codecs/video/H264/Intra"] = @native function() +__FILES["codecs/video/H264/Intra"] = function() @@ -97236,12 +97251,12 @@ local E = table.create(40, 0) -- reference samples: p[-1, y] = E[N - y], p[-1, - local F = table.create(40, 0) -- filtered 8x8 references, same layout local min, max = math.min, math.max -@native local function clip(v: number): number +local function clip(v: number): number return min(max(v, 0), 255) end -- predNxN: the directional modes 3..8 over the edge array R (N = 4 or 8) -@native local function directional(R: { number }, N: number, mode: number, b: buffer, o: number, s: number) +local function directional(R: { number }, N: number, mode: number, b: buffer, o: number, s: number) local c = N + 1 -- R[c] = p[-1, -1]; p[x, -1] = R[c + 1 + x]; p[-1, y] = R[c - 1 - y] for y = 0, N - 1 do local row = o + y * s @@ -97318,7 +97333,7 @@ end end -- unavailable top-right samples repeat p[3, -1] -@native function Intra.pred4x4(b: buffer, o: number, s: number, mode: number, left: boolean, top: boolean, topRight: boolean, topLeft: boolean) +function Intra.pred4x4(b: buffer, o: number, s: number, mode: number, left: boolean, top: boolean, topRight: boolean, topLeft: boolean) if mode == 0 then local t = o - s local a0, a1, a2, a3 = readu8(b, t), readu8(b, t + 1), readu8(b, t + 2), readu8(b, t + 3) @@ -97392,7 +97407,7 @@ end directional(E, 4, mode, b, o, s) end -@native function Intra.pred8x8(b: buffer, o: number, s: number, mode: number, left: boolean, top: boolean, topRight: boolean, topLeft: boolean) +function Intra.pred8x8(b: buffer, o: number, s: number, mode: number, left: boolean, top: boolean, topRight: boolean, topLeft: boolean) -- unfiltered edges into E: E[1..8] = p[-1, 7..0], E[9] = p[-1, -1], E[10..25] = p[0..15, -1] if left then for y = 0, 7 do @@ -97498,7 +97513,7 @@ end end end -@native function Intra.pred16x16(b: buffer, o: number, s: number, mode: number, left: boolean, top: boolean, topLeft: boolean) +function Intra.pred16x16(b: buffer, o: number, s: number, mode: number, left: boolean, top: boolean, topLeft: boolean) if mode == 0 then local t = o - s for y = 0, 15 do @@ -97553,7 +97568,7 @@ end end end -@native local function fill4(b: buffer, o: number, s: number, v: number) +local function fill4(b: buffer, o: number, s: number, v: number) for y = 0, 3 do local r = o + y * s writeu8(b, r, v) @@ -97564,7 +97579,7 @@ end end -- 8x8 chroma (4:2:0): mode 0 DC, 1 horizontal, 2 vertical, 3 plane -@native function Intra.predChroma(b: buffer, o: number, s: number, mode: number, left: boolean, top: boolean, topLeft: boolean) +function Intra.predChroma(b: buffer, o: number, s: number, mode: number, left: boolean, top: boolean, topLeft: boolean) if mode == 0 then local t = o - s local st0, st1, sl0, sl1 = 0, 0, 0, 0 @@ -97629,7 +97644,7 @@ end return Intra end -__FILES["codecs/video/H264/Mb"] = @native function() +__FILES["codecs/video/H264/Mb"] = function() @@ -97658,7 +97673,7 @@ local BLK_X = { 0, 1, 0, 1, 2, 3, 2, 3, 0, 1, 0, 1, 2, 3, 2, 3 } local BLK_Y = { 0, 0, 1, 1, 0, 0, 1, 1, 2, 2, 3, 3, 2, 2, 3, 3 } Mb.BLK_X, Mb.BLK_Y = BLK_X, BLK_Y -@native function Mb.new(): any +function Mb.new(): any return { addr = 0, x = 0, @@ -97707,7 +97722,7 @@ Mb.BLK_X, Mb.BLK_Y = BLK_X, BLK_Y } end -@native function Mb.grids(mbW: number, mbH: number): any +function Mb.grids(mbW: number, mbH: number): any local n = mbW * mbH local n4 = n * 16 local nc = n * 4 @@ -97734,7 +97749,7 @@ end } end -@native function Mb.start(S: any, M: any, addr: number) +function Mb.start(S: any, M: any, addr: number) local mbW = S.mbW local x, y = addr % mbW, addr // mbW M.addr, M.x, M.y = addr, x, y @@ -97767,7 +97782,7 @@ end end -- nC of luma block (bx, by) (9.2.1) -@native function Mb.nC(S: any, M: any, bx: number, by: number): number +function Mb.nC(S: any, M: any, bx: number, by: number): number local g = M.g0 + by * S.w4 + bx local nzc = S.nzc local la = bx > 0 or M.aL @@ -97782,7 +97797,7 @@ end return 0 end -@native function Mb.nCc(S: any, M: any, tab: { number }, bx: number, by: number): number +function Mb.nCc(S: any, M: any, tab: { number }, bx: number, by: number): number local cw = S.cw4 local g = M.c0 + by * cw + bx local la = bx > 0 or M.aL @@ -97798,7 +97813,7 @@ end end -- predIntra4x4PredMode / predIntra8x8PredMode (8.3.1.1 / 8.3.2.1) -@native function Mb.predMode(S: any, M: any, bx: number, by: number): number +function Mb.predMode(S: any, M: any, bx: number, by: number): number local la = bx > 0 or M.iL local ta = by > 0 or M.iT if not (la and ta) then @@ -97810,7 +97825,7 @@ end return ((a < b) and (a) or (b)) end -@native local function neighbour(S: any, M: any, refs: { number }, mvs: { number }, nx: number, ny: number): (number, number, number) +local function neighbour(S: any, M: any, refs: { number }, mvs: { number }, nx: number, ny: number): (number, number, number) local ok if ny < 0 then if nx < 0 then @@ -97838,12 +97853,12 @@ end return r, mvs[2 * g - 1], mvs[2 * g] end -@native local function median(a: number, b: number, c: number): number +local function median(a: number, b: number, c: number): number return max(min(a, b), min(max(a, b), c)) end -- shape: 0 generic, 1 = 16x8 upper, 2 = 16x8 lower, 3 = 8x16 left, 4 = 8x16 right (8.4.1.3) -@native local function mvp(S: any, M: any, list: number, x: number, y: number, w: number, ref: number, shape: number): (number, number) +local function mvp(S: any, M: any, list: number, x: number, y: number, w: number, ref: number, shape: number): (number, number) local pic = S.pic local refs = ((list == 0) and (pic.ref0) or (pic.ref1)) local mvs = ((list == 0) and (pic.mv0) or (pic.mv1)) @@ -97895,7 +97910,7 @@ end end Mb.mvp = mvp -@native local function set(S: any, M: any, x: number, y: number, w: number, h: number, r0: number, m0x: number, m0y: number, r1: number, m1x: number, m1y: number) +local function set(S: any, M: any, x: number, y: number, w: number, h: number, r0: number, m0x: number, m0y: number, r1: number, m1x: number, m1y: number) local pic = S.pic local ref0, ref1, mv0, mv1, uid0, uid1 = pic.ref0, pic.ref1, pic.mv0, pic.mv1, pic.uid0, pic.uid1 local u0 = ((r0 >= 0) and (S.uids0[r0 + 1] or -1) or (-1)) @@ -97921,11 +97936,11 @@ Mb.mvp = mvp M.nreg += 1 end -@native local function clip3(lo: number, hi: number, v: number): number +local function clip3(lo: number, hi: number, v: number): number return min(max(v, lo), hi) end -@native local function tdiv(a: number, b: number): number +local function tdiv(a: number, b: number): number local q = a / b if q >= 0 then return math.floor(q) @@ -97934,7 +97949,7 @@ end end -- DistScaleFactor (8-195 .. 8-198), nil when td is 0 -@native function Mb.distScale(cur: number, poc0: number, poc1: number): number? +function Mb.distScale(cur: number, poc0: number, poc1: number): number? local tb = clip3(-128, 127, cur - poc0) local td = clip3(-128, 127, poc1 - poc0) if td == 0 then @@ -97945,7 +97960,7 @@ end end -- P_Skip motion (8.4.1.1) -@native local function pskip(S: any, M: any) +local function pskip(S: any, M: any) local mx, my = 0, 0 if M.aL and M.aT then local pic = S.pic @@ -97959,7 +97974,7 @@ end end -- refIdxCol (-1: intra / none), mvCol (8.4.1.2.1) -@native local function colocated(S: any, M: any, bx: number, by: number): (number, number, number, number) +local function colocated(S: any, M: any, bx: number, by: number): (number, number, number, number) local col = S.colPic if S.direct8x8 then bx = ((bx < 2) and (0) or (3)) @@ -97980,7 +97995,7 @@ end return -1, 0, 0, -1 end -@native local function minPositive(a: number, b: number): number +local function minPositive(a: number, b: number): number if a >= 0 and b >= 0 then return ((a < b) and (a) or (b)) end @@ -97988,7 +98003,7 @@ end end -- spatial direct references and predictors (8.4.1.2.2) -@native local function spatialRefs(S: any, M: any) +local function spatialRefs(S: any, M: any) local pic = S.pic local r0, r1 = -1, -1 for l = 0, 1 do @@ -98028,7 +98043,7 @@ end M.dReady = true end -@native local function direct8(S: any, M: any, i8: number) +local function direct8(S: any, M: any, i8: number) local x0, y0 = (i8 % 2) * 2, (i8 // 2) * 2 local step = ((S.direct8x8) and (2) or (1)) if S.directSpatial then @@ -98080,7 +98095,7 @@ local SUB_N = { 1, 2, 2, 4 } local SUB_W = { 2, 2, 1, 1 } local SUB_H = { 2, 1, 2, 1 } -@native local function motion(S: any, M: any) +local function motion(S: any, M: any) local kind = M.kind M.dReady = false if kind == K_PSKIP then @@ -98166,7 +98181,7 @@ local SUB_H = { 2, 1, 2, 1 } end Mb.motion = motion -@native local function predLuma(S: any, ref: any, P: { number }, px: number, py: number, w: number, h: number, mvx: number, mvy: number) +local function predLuma(S: any, ref: any, P: { number }, px: number, py: number, w: number, h: number, mvx: number, mvy: number) local W, H = S.mbW * 16, S.mbH * 16 local ix = px + mvx // 4 local iy = py + mvy // 4 @@ -98176,7 +98191,7 @@ Mb.motion = motion Inter.luma(ref.y, s, ref.yo + iy * s + ix, mvx % 4, mvy % 4, w, h, P) end -@native local function predChroma(S: any, ref: any, P: { number }, plane: buffer, px: number, py: number, w: number, h: number, mvx: number, mvy: number) +local function predChroma(S: any, ref: any, P: { number }, plane: buffer, px: number, py: number, w: number, h: number, mvx: number, mvy: number) local W, H = S.mbW * 8, S.mbH * 8 local ix = px + mvx // 8 local iy = py + mvy // 8 @@ -98186,11 +98201,11 @@ end Inter.chroma(plane, s, ref.co + iy * s + ix, mvx % 8, mvy % 8, w, h, P) end -@native local function refPic(list: { any }, r: number): any +local function refPic(list: { any }, r: number): any return list[r + 1] or list[1] end -@native local function mc(S: any, M: any) +local function mc(S: any, M: any) local pic = S.pic local reg = M.reg local P0, P1 = M.P0, M.P1 @@ -98275,7 +98290,7 @@ end end end -@native local function lumaResidual(S: any, M: any) +local function lumaResidual(S: any, M: any) local pic = S.pic local b, s = pic.y, pic.ys local o = pic.yo + M.y * 16 * s + M.x * 16 @@ -98297,7 +98312,7 @@ end end end -@native local function chromaResidual(S: any, M: any) +local function chromaResidual(S: any, M: any) if not M.hasDcC and M.cbp < 32 then return end @@ -98326,7 +98341,7 @@ end end end -@native local function intraLuma(S: any, M: any) +local function intraLuma(S: any, M: any) local pic = S.pic local b, s = pic.y, pic.ys local o = pic.yo + M.y * 16 * s + M.x * 16 @@ -98406,7 +98421,7 @@ end end end -@native local function intraChroma(S: any, M: any) +local function intraChroma(S: any, M: any) local pic = S.pic local s = pic.cs local o = pic.co + M.y * 8 * s + M.x * 8 @@ -98414,7 +98429,7 @@ end Intra.predChroma(pic.v, o, s, M.cpm, M.iL, M.iT, M.iTL) end -@native local function pcm(S: any, M: any) +local function pcm(S: any, M: any) local pic = S.pic local src = M.pcm local s = pic.ys @@ -98430,7 +98445,7 @@ end end end -@native function Mb.recon(S: any, M: any) +function Mb.recon(S: any, M: any) local kind = M.kind local addr = M.addr + 1 local pic = S.pic @@ -98494,7 +98509,7 @@ end chromaResidual(S, M) end -@native function Mb.skip(S: any, M: any, kind: number) +function Mb.skip(S: any, M: any, kind: number) M.kind = kind M.cbp = 0 M.t8 = 0 @@ -98535,7 +98550,7 @@ end return Mb end -__FILES["codecs/video/H264/Params"] = @native function() +__FILES["codecs/video/H264/Params"] = function() -- 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 @@ -98556,7 +98571,7 @@ local MAX_DPB_MBS = { [9] = 396, [10] = 396, [11] = 900, [12] = 2376, [13] = 237 local ZIGZAG4, ZIGZAG8 = Tables.ZIGZAG4, Tables.ZIGZAG8 -- scaling_list(): raster order, or "default" (useDefaultScalingMatrixFlag) -@native local function scalingList(r: Bitstream.Reader, size: number): any +local function scalingList(r: Bitstream.Reader, size: number): any local list = table.create(size, 0) local last, nxt = 8, 8 local zz = if size == 16 then ZIGZAG4 else ZIGZAG8 @@ -98579,7 +98594,7 @@ local ZIGZAG4, ZIGZAG8 = Tables.ZIGZAG4, Tables.ZIGZAG8 end -- lists: 12 entries (false = not present, "default", or a raster list) -@native local function scalingMatrix(r: Bitstream.Reader, count: number): { any }? +local function scalingMatrix(r: Bitstream.Reader, count: number): { any }? local lists = table.create(12, false) for i = 1, count do if u1(r) == 1 then @@ -98593,7 +98608,7 @@ end return lists end -@native local function default(i: number): { number } +local function default(i: number): { number } local out = {} if i <= 6 then local base = if i <= 3 then 0 else 16 @@ -98612,7 +98627,7 @@ end local FLAT16, FLAT64 = table.create(16, 16), table.create(64, 16) -- fallback nil = rule A (defaults), else the SPS's 12 lists (rule B) -@native local function resolve(lists: { any }, fallback: { { number } }?): { { number } } +local function resolve(lists: { any }, fallback: { { number } }?): { { number } } local out = {} for i = 1, 12 do local l = lists[i] @@ -98631,7 +98646,7 @@ local FLAT16, FLAT64 = table.create(16, 16), table.create(64, 16) return out end -@native local function hrd(r: Bitstream.Reader) +local function hrd(r: Bitstream.Reader) local cnt = ue(r) if cnt > 31 then return false @@ -98646,7 +98661,7 @@ end return true end -@native local function vui(r: Bitstream.Reader, sps: any) +local function vui(r: Bitstream.Reader, sps: any) if u1(r) == 1 then local idc = u(r, 8) if idc == 255 then @@ -98703,7 +98718,7 @@ end end end -@native function Params.sps(r: Bitstream.Reader): (any, string?) +function Params.sps(r: Bitstream.Reader): (any, string?) local sps: any = {} sps.profile = u(r, 8) sps.constraints = u(r, 8) @@ -98823,7 +98838,7 @@ end return sps, nil end -@native function Params.pps(r: Bitstream.Reader, spsTable: { [number]: any }): (any, string?) +function Params.pps(r: Bitstream.Reader, spsTable: { [number]: any }): (any, string?) local pps: any = {} pps.id = ue(r) if pps.id > 255 then @@ -98893,7 +98908,7 @@ local V8 = { { 36, 32, 58, 34, 46, 43 }, } -@native local function norm4(m: number, i: number, j: number): number +local function norm4(m: number, i: number, j: number): number local v = V4[m + 1] if i % 2 == 0 and j % 2 == 0 then return v[1] @@ -98903,7 +98918,7 @@ local V8 = { return v[3] end -@native local function norm8(m: number, i: number, j: number): number +local function norm8(m: number, i: number, j: number): number local v = V8[m + 1] if i % 4 == 0 and j % 4 == 0 then return v[1] @@ -98922,7 +98937,7 @@ end -- dequant tables: dq.d4[list][qp + 1] = 16 multipliers (raster), list 1..6 = Y/Cb/Cr intra, Y/Cb/Cr inter; -- dq.d8[list][qp + 1] = 64 multipliers, list 1 = Y intra, 2 = Y inter. A 4x4 coefficient c dequantises to -- (c * m + 8) >> 4, an 8x8 one to (c * m + 32) >> 6 (8.5.12.1 / 8.5.13.1 with LevelScale * 2^(qP / 6)). -@native local function build(lists: { { number } }): any +local function build(lists: { { number } }): any local d4, d8 = {}, {} for l = 1, 6 do local w = lists[l] @@ -98955,7 +98970,7 @@ end return { d4 = d4, d8 = d8 } end -@native function Params.dequant(sps: any, pps: any, cache: { [string]: any }): any +function Params.dequant(sps: any, pps: any, cache: { [string]: any }): any local lists: { { number } } if pps.scalingLists then lists = resolve(pps.scalingLists, sps.scaling) @@ -98982,7 +98997,7 @@ end return Params end -__FILES["codecs/video/H264/Slice"] = @native function() +__FILES["codecs/video/H264/Slice"] = function() -- codecs/video/H264/Slice: the slice header (ITU-T H.264 7.3.3): ref_pic_list_modification, pred_weight_table and @@ -98996,7 +99011,7 @@ local Slice = {} Slice.P, Slice.B, Slice.I, Slice.SP, Slice.SI = 0, 1, 2, 3, 4 -@native local function modifications(r: Bitstream.Reader): { number }? +local function modifications(r: Bitstream.Reader): { number }? local ops = {} if u1(r) == 1 then for _ = 1, 100 do @@ -99018,7 +99033,7 @@ Slice.P, Slice.B, Slice.I, Slice.SP, Slice.SI = 0, 1, 2, 3, 4 return ops end -@native local function weights(r: Bitstream.Reader, n: number, lw: number, cw: number, chroma: boolean): { number }? +local function weights(r: Bitstream.Reader, n: number, lw: number, cw: number, chroma: boolean): { number }? -- per entry: lumaW, lumaO, cbW, cbO, crW, crO, lumaFlag, chromaFlag (8 numbers) local t = table.create(n * 8, 0) for i = 0, n - 1 do @@ -99046,7 +99061,7 @@ end return t end -@native function Slice.header(r: Bitstream.Reader, nalType: number, nalRefIdc: number, spsTable: { [number]: any }, ppsTable: { [number]: any }): (any, string?) +function Slice.header(r: Bitstream.Reader, nalType: number, nalRefIdc: number, spsTable: { [number]: any }, ppsTable: { [number]: any }): (any, string?) local sh: any = {} sh.nalType = nalType sh.nalRefIdc = nalRefIdc @@ -99233,7 +99248,7 @@ end return Slice end -__FILES["codecs/video/H264/Tables"] = @native function() +__FILES["codecs/video/H264/Tables"] = function() -- codecs/video/H264/Tables: the constant tables of ITU-T H.264 (CAVLC 9-5, 9-7..9-10; CABAC init 9-12..9-24, @@ -99274,7 +99289,7 @@ T.TC0 = { -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0 return T end -__FILES["codecs/video/H264/Transform"] = @native function() +__FILES["codecs/video/H264/Transform"] = function() @@ -99285,11 +99300,11 @@ local readu8, writeu8 = buffer.readu8, buffer.writeu8 local Transform = {} local min, max = math.min, math.max -@native local function clip(v: number): number +local function clip(v: number): number return min(max(v, 0), 255) end -@native function Transform.add4(c: { number }, base: number, b: buffer, o: number, s: number) +function Transform.add4(c: { number }, base: number, b: buffer, o: number, s: number) for i = 0, 3 do local k = base + i * 4 local d0, d1, d2, d3 = c[k + 1], c[k + 2], c[k + 3], c[k + 4] @@ -99321,7 +99336,7 @@ end end end -@native function Transform.addDc4(dc: number, b: buffer, o: number, s: number) +function Transform.addDc4(dc: number, b: buffer, o: number, s: number) local v = (dc + 32) // 64 if v == 0 then return @@ -99337,7 +99352,7 @@ end local T8 = table.create(64, 0) -@native function Transform.add8(c: { number }, base: number, b: buffer, o: number, s: number) +function Transform.add8(c: { number }, base: number, b: buffer, o: number, s: number) for pass = 0, 1 do for i = 0, 7 do local d0, d1, d2, d3, d4, d5, d6, d7 @@ -99397,7 +99412,7 @@ local T8 = table.create(64, 0) end -- m = LevelScale4x4(qP % 6, 0, 0) * 2^(qP / 6) -@native function Transform.lumaDc(dc: { number }, m: number, c: { number }) +function Transform.lumaDc(dc: { number }, m: number, c: { number }) for i = 0, 3 do local k = i * 4 local d0, d1, d2, d3 = dc[k + 1], dc[k + 2], dc[k + 3], dc[k + 4] @@ -99424,7 +99439,7 @@ end end end -@native function Transform.chromaDc(dc: { number }, base: number, m: number, c: { number }, cbase: number) +function Transform.chromaDc(dc: { number }, base: number, m: number, c: { number }, cbase: number) local c0, c1, c2, c3 = dc[base + 1], dc[base + 2], dc[base + 3], dc[base + 4] dc[base + 1], dc[base + 2], dc[base + 3], dc[base + 4] = 0, 0, 0, 0 local e = c0 + c1 @@ -99637,7 +99652,7 @@ end return Legacy end -__FILES["codecs/video/Legacy/Cinepak"] = @native function() +__FILES["codecs/video/Legacy/Cinepak"] = function() @@ -99662,26 +99677,26 @@ type State = { filmSkip: number, -- Sega FILM extra header bytes (-1 = not known yet) } -@native function Cinepak.state(): State +function Cinepak.state(): State return { books = buffer.create(MAX_STRIPS * 2 * BOOK), filmSkip = -1 } end -@native local function be16(d: buffer, o: number): number +local function be16(d: buffer, o: number): number return readu8(d, o) * 256 + readu8(d, o + 1) end -@native local function be24(d: buffer, o: number): number +local function be24(d: buffer, o: number): number return readu8(d, o) * 65536 + readu8(d, o + 1) * 256 + readu8(d, o + 2) end -@native local function be32(d: buffer, o: number): number +local function be32(d: buffer, o: number): number return readu8(d, o) * 16777216 + readu8(d, o + 1) * 65536 + readu8(d, o + 2) * 256 + readu8(d, o + 3) end -@native local function clip(v: number): number +local function clip(v: number): number return if v < 0 then 0 elseif v > 255 then 255 else v end -- a codebook chunk (ids 0x20..0x27): entries of 4 or 6 bytes, all of them or those whose flag bit is set -@native local function codebook(books: buffer, book: number, id: number, d: buffer, p: number, stop: number) +local function codebook(books: buffer, book: number, id: number, d: buffer, p: number, stop: number) local six = band(id, 4) == 0 local partial = band(id, 1) ~= 0 local size = if six then 6 else 4 @@ -99730,7 +99745,7 @@ end end -- the vectors of a strip (ids 0x30 intra, 0x31 inter with skip flags, 0x32 V1 only) -@native local function vectors(pic: Picture.Picture, books: buffer, v4: number, v1: number, id: number, d: buffer, p: number, +local function vectors(pic: Picture.Picture, books: buffer, v4: number, v1: number, id: number, d: buffer, p: number, stop: number, x1: number, y1: number, x2: number, y2: number): boolean local stride = pic.stride local pal = pic.idx @@ -99830,7 +99845,7 @@ end return true end -@native function Cinepak.decode(pic: Picture.Picture, d: buffer, st: State, newPalette: boolean): (boolean, string?) +function Cinepak.decode(pic: Picture.Picture, d: buffer, st: State, newPalette: boolean): (boolean, string?) local n = buffer.len(d) if n < 10 then return false, "frame too short" @@ -99934,7 +99949,7 @@ end return Cinepak end -__FILES["codecs/video/Legacy/Flic"] = @native function() +__FILES["codecs/video/Legacy/Flic"] = function() @@ -99958,7 +99973,7 @@ type State = { bpp: number, } -@native function Flic.state(w: number, h: number, depth: number): (State?, string?) +function Flic.state(w: number, h: number, depth: number): (State?, string?) local bpp = if depth == 8 then 1 elseif depth == 15 or depth == 16 then 2 elseif depth == 24 then 3 else 0 if bpp == 0 then return nil, "unsupported: " .. depth .. "-bit FLIC" @@ -99968,11 +99983,11 @@ type State = { return { pic = pic, depth = depth, bpp = bpp }, nil end -@native local function s8(v: number): number +local function s8(v: number): number return if v >= 128 then v - 256 else v end -@native function Flic.decode(st: State, d: buffer): (boolean, string?) +function Flic.decode(st: State, d: buffer): (boolean, string?) local pic = st.pic local px = pic.idx :: buffer local pal = pic.pal @@ -99986,12 +100001,12 @@ end return false, "frame too short" end local p = 0 - @native local function u8(): number + local function u8(): number local v = if p < n then readu8(d, p) else 0 p += 1 return v end - @native local function u16(): number + local function u16(): number local a = u8() return a + u8() * 256 end @@ -100267,7 +100282,7 @@ end return true, nil end -@native function Flic.image(st: State): Types.Image +function Flic.image(st: State): Types.Image local pic = st.pic if st.bpp == 1 then return Picture.image(pic) @@ -100301,7 +100316,7 @@ end return Flic end -__FILES["codecs/video/Legacy/Msvideo1"] = @native function() +__FILES["codecs/video/Legacy/Msvideo1"] = function() @@ -100317,11 +100332,11 @@ local band = bit32.band local Msvideo1 = {} -- 2-colour: bit set = c0; 8-colour: colours[quadrant * 2 + (bit clear)] -@native local function quadrant(x: number, y: number): number +local function quadrant(x: number, y: number): number return (if y >= 2 then 4 else 0) + (if x >= 2 then 2 else 0) end -@native function Msvideo1.decode(pic: Picture.Picture, d: buffer, bits: number): (boolean, string?) +function Msvideo1.decode(pic: Picture.Picture, d: buffer, bits: number): (boolean, string?) local n = buffer.len(d) local bw, bh = pic.w // 4, pic.h // 4 if n < bw * bh // 512 then @@ -100419,7 +100434,7 @@ end return Msvideo1 end -__FILES["codecs/video/Legacy/Picture"] = @native function() +__FILES["codecs/video/Legacy/Picture"] = function() @@ -100442,7 +100457,7 @@ type Picture = { pal: buffer, -- 256 u32 entries, bytes R, G, B, A } -@native function Picture.new(w: number, h: number, palettised: boolean, padW: number?, padH: number?, palette: buffer?): Picture +function Picture.new(w: number, h: number, palettised: boolean, padW: number?, padH: number?, palette: buffer?): Picture local pw, ph = padW or 1, padH or 1 local stride = ((w + pw - 1) // pw) * pw local rows = ((h + ph - 1) // ph) * ph @@ -100459,7 +100474,7 @@ type Picture = { return p end -@native function Picture.image(p: Picture): Types.Image +function Picture.image(p: Picture): Types.Image local w, h = p.w, p.h local img = Types.Image.new(w, h, "rgba8") local idx, rgba = p.idx, p.rgba @@ -100477,7 +100492,7 @@ end return img end -@native function Picture.setPalette(p: Picture, src: buffer) +function Picture.setPalette(p: Picture, src: buffer) if buffer.len(src) >= 1024 then buffer.copy(p.pal, 0, src, 0, 1024) end @@ -100486,7 +100501,7 @@ end local lut555: buffer? = nil local lut565: buffer? = nil -@native function Picture.rgb555(): buffer +function Picture.rgb555(): buffer local t = lut555 if t then return t @@ -100501,7 +100516,7 @@ local lut565: buffer? = nil return b end -@native function Picture.rgb565(): buffer +function Picture.rgb565(): buffer local t = lut565 if t then return t @@ -100516,7 +100531,7 @@ end return b end -@native function Picture.clonePlane(p: Picture): buffer +function Picture.clonePlane(p: Picture): buffer local src = (p.idx or p.rgba) :: buffer local c = buffer.create(buffer.len(src)) buffer.copy(c, 0, src, 0) @@ -100527,7 +100542,7 @@ local _ = readu32 return Picture end -__FILES["codecs/video/Legacy/QtRle"] = @native function() +__FILES["codecs/video/Legacy/QtRle"] = function() @@ -100543,12 +100558,12 @@ local band, rshift = bit32.band, bit32.rshift local QtRle = {} -@native local function s8(v: number): number +local function s8(v: number): number return if v >= 128 then v - 256 else v end -- 1-bit: (skip, code) pairs; skip bit 7 = next line (the first one starts the first line) -@native local function decode1(px: buffer, stride: number, limit: number, d: buffer, p: number, n: number, row: number, lines: number) +local function decode1(px: buffer, stride: number, limit: number, d: buffer, p: number, n: number, row: number, lines: number) row -= stride local q = row lines += 1 @@ -100609,7 +100624,7 @@ end end -- 2 / 4 / 8-bit: groups of 16 / 8 / 4 indexes (4 bytes); skips count groups -@native local function decodeIdx(px: buffer, stride: number, limit: number, d: buffer, p: number, n: number, row: number, lines: number, bpp: number) +local function decodeIdx(px: buffer, stride: number, limit: number, d: buffer, p: number, n: number, row: number, lines: number, bpp: number) local group = 32 // bpp local per = 8 // bpp local mask = 2 ^ bpp - 1 @@ -100691,7 +100706,7 @@ end end -- 16 / 24 / 32-bit: one pixel per group, into the rgba8 plane (stride in pixels) -@native local function decodeRgb(px: buffer, stride: number, limit: number, d: buffer, p: number, n: number, row: number, lines: number, depth: number) +local function decodeRgb(px: buffer, stride: number, limit: number, d: buffer, p: number, n: number, row: number, lines: number, depth: number) local bpp = depth // 8 local lut = if depth == 16 then Picture.rgb555() else nil for _ = 1, lines do @@ -100751,7 +100766,7 @@ end end end -@native function QtRle.decode(pic: Picture.Picture, d: buffer, depth: number): (boolean, string?) +function QtRle.decode(pic: Picture.Picture, d: buffer, depth: number): (boolean, string?) local n = buffer.len(d) if n < 8 then return true, nil @@ -100790,17 +100805,17 @@ end return true, nil end -@native function QtRle.palettised(depth: number): boolean +function QtRle.palettised(depth: number): boolean return depth <= 8 or depth > 32 end -@native function QtRle.pad(depth: number): number +function QtRle.pad(depth: number): number local bits = if depth > 32 then depth - 32 else depth return if bits <= 8 then 32 // math.max(1, bits) else 1 end return QtRle end -__FILES["codecs/video/Legacy/Smacker"] = @native function() +__FILES["codecs/video/Legacy/Smacker"] = function() @@ -100830,11 +100845,11 @@ RUNS[60], RUNS[61], RUNS[62], RUNS[63], RUNS[64] = 128, 256, 512, 1024, 2048 type Bits = { buf: buffer, pos: number, nbits: number } -@native function Smacker.bits(buf: buffer, offset: number, length: number): Bits +function Smacker.bits(buf: buffer, offset: number, length: number): Bits return { buf = buf, pos = offset * 8, nbits = (offset + length) * 8 } end -@native local function bit(br: Bits): number +local function bit(br: Bits): number local p = br.pos br.pos = p + 1 if p >= br.nbits then @@ -100844,7 +100859,7 @@ end end Smacker.bit = bit -@native function Smacker.read(br: Bits, n: number): number +function Smacker.read(br: Bits, n: number): number local v, m = 0, 1 for _ = 1, n do v += bit(br) * m @@ -100855,7 +100870,7 @@ end local readBits = Smacker.read -- no end-of-data check for 8-bit trees, as the reference's table lookups -@native local function walk(tree: { number }, br: Bits): number +local function walk(tree: { number }, br: Bits): number local i = 1 local e = tree[1] while e < 0 do @@ -100869,7 +100884,7 @@ local readBits = Smacker.read end Smacker.walk = walk -@native local function build(br: Bits, maxDepth: number, maxEntries: number, leaf: (number) -> (number?, string?), bigChecks: boolean): ({ number }?, string?) +local function build(br: Bits, maxDepth: number, maxEntries: number, leaf: (number) -> (number?, string?), bigChecks: boolean): ({ number }?, string?) local vals: { number } = {} local n = 0 local stack: { number } = {} @@ -100915,9 +100930,9 @@ Smacker.walk = walk end end -@native function Smacker.tree8(br: Bits): ({ number }?, string?) +function Smacker.tree8(br: Bits): ({ number }?, string?) local leaves = 0 - return build(br, MAX_DEPTH8, 511, @native function(_: number): (number?, string?) + return build(br, MAX_DEPTH8, 511, function(_: number): (number?, string?) if leaves >= 256 then return nil, "tree too big" end @@ -100932,7 +100947,7 @@ local tree8 = Smacker.tree8 type BigTree = { vals: { number }, last: { number }, lut: buffer? } -- last: the escape leaves' indexes (1-based) -@native local function bigTree(br: Bits, size: number): (BigTree?, string?) +local function bigTree(br: Bits, size: number): (BigTree?, string?) if bit(br) == 0 then return { vals = { 0, 0 }, last = { 2, 2, 2 } }, nil -- no tree: every code is 0 end @@ -100952,7 +100967,7 @@ type BigTree = { vals: { number }, last: { number }, lut: buffer? } -- last: the local esc = { readBits(br, 16), readBits(br, 16), readBits(br, 16) } local last = { -1, -1, -1 } local lo, hi = lohi[1], lohi[2] - local vals, msg = build(br, MAX_DEPTH16, (size + 3) // 4, @native function(index: number): (number?, string?) + local vals, msg = build(br, MAX_DEPTH16, (size + 3) // 4, function(index: number): (number?, string?) local v = walk(lo, br) + walk(hi, br) * 256 for k = 1, 3 do if v == esc[k] then @@ -100978,7 +100993,7 @@ end type Trees = { mmap: BigTree, mclr: BigTree, full: BigTree, type: BigTree } -- config = the four u32 tree sizes, then the tree bits -@native function Smacker.trees(config: buffer): (Trees?, string?) +function Smacker.trees(config: buffer): (Trees?, string?) local n = buffer.len(config) if n <= 16 then return nil, "no trees" @@ -101010,7 +101025,7 @@ end local LUT_BITS = 10 -- the first LUT_BITS bits of a code -> (entry index * 32 + bits used): a leaf, or the node reached after LUT_BITS bits -@native local function lut(vals: { number }): buffer +local function lut(vals: { number }): buffer local size = 2 ^ LUT_BITS local t = buffer.create(size * 4) for pat = 0, size - 1 do @@ -101029,12 +101044,12 @@ local LUT_BITS = 10 return t end -@native local function reset(t: BigTree) +local function reset(t: BigTree) local vals, last = t.vals, t.last vals[last[1]], vals[last[2]], vals[last[3]] = 0, 0, 0 end -@native function Smacker.decode(pic: Picture.Picture, d: buffer, trees: Trees, v4: boolean): (boolean, string?) +function Smacker.decode(pic: Picture.Picture, d: buffer, trees: Trees, v4: boolean): (boolean, string?) local px = pic.idx :: buffer local stride = pic.stride local mmap, mclr, full, typ = trees.mmap, trees.mclr, trees.full, trees.type @@ -101047,7 +101062,7 @@ end local n = buffer.len(d) local nbits = n * 8 local pos = 0 - @native local function code(t: BigTree): number + local function code(t: BigTree): number local vals = t.vals local i, p local byte = rshift(pos, 3) @@ -101082,7 +101097,7 @@ end end return e end - @native local function bit(): number + local function bit(): number local p = pos pos = p + 1 if p >= nbits then @@ -101195,7 +101210,7 @@ end return Smacker end -__FILES["codecs/video/Legacy/Smc"] = @native function() +__FILES["codecs/video/Legacy/Smc"] = function() @@ -101209,7 +101224,7 @@ local band, rshift = bit32.band, bit32.rshift local Smc = {} -@native function Smc.decode(pic: Picture.Picture, d: buffer, tables: buffer): (boolean, string?) +function Smc.decode(pic: Picture.Picture, d: buffer, tables: buffer): (boolean, string?) local px = pic.idx :: buffer local n = buffer.len(d) local stride = pic.stride -- a multiple of 4: the plane holds whole blocks @@ -101223,7 +101238,7 @@ local Smc = {} local bx, by = 0, 0 local pairI, quadI, octI = 0, 0, 0 -- tables: pairs at 0 (256 * 2), quads at 512 (256 * 4), octets at 1536 (256 * 8) - @native local function u8(): number + local function u8(): number if p < n then local v = readu8(d, p) p += 1 @@ -101231,7 +101246,7 @@ local Smc = {} end return 0 end - @native local function advance() + local function advance() bx += 1 if bx >= blocksWide then bx = 0 @@ -101366,7 +101381,7 @@ local Smc = {} return true, nil end -@native function Smc.tables(): buffer +function Smc.tables(): buffer return buffer.create(512 + 1024 + 2048) end @@ -101751,7 +101766,7 @@ end return Mpeg2 end -__FILES["codecs/video/Mpeg2/Decoder"] = @native function() +__FILES["codecs/video/Mpeg2/Decoder"] = function() -- codecs/video/Mpeg2/Decoder: the MPEG-1 / MPEG-2 video decoding core (ISO/IEC 11172-2, 13818-2 Main profile). @@ -101829,7 +101844,7 @@ for i = 0, 2 * COFF + 255 do end -- 4:2:0 -> RGBA8 with nearest chroma, like ffmpeg's default swscale path; hook is pcall'ed (can't throw through here) -@native local function toRgba(Y: buffer, Cb: buffer, Cr: buffer, cw: number, w: number, h: number, out: buffer, row0: number?, row1: number?, oo: number?, hook: (() -> ())?) +local function toRgba(Y: buffer, Cb: buffer, Cr: buffer, cw: number, w: number, h: number, out: buffer, row0: number?, row1: number?, oo: number?, hook: (() -> ())?) -- 2 x 2 pixels per chroma sample: the chroma terms are computed once per block of four local r0: number = row0 or 0 local r1: number = row1 or h @@ -101884,7 +101899,7 @@ end D.toRgba = toRgba -- YCbCr 4:2:2 planes -> RGBA8: chroma row y for luma row y, chroma column x // 2 -@native local function toRgba422(Y: buffer, Cb: buffer, Cr: buffer, cw: number, w: number, h: number, out: buffer) +local function toRgba422(Y: buffer, Cb: buffer, Cr: buffer, cw: number, w: number, h: number, out: buffer) local chw = cw // 2 for y = 0, h - 1 do local o = y * w * 4 @@ -101950,7 +101965,7 @@ type Core = { }, } -@native function D.new(maxPixels: number?): Core +function D.new(maxPixels: number?): Core local state = { width = 0, height = 0, @@ -102040,7 +102055,7 @@ type Core = { local blk = buffer.create(256) local yieldHook: (() -> ())? = nil - @native local function peek32(): number + local function peek32(): number local bp = rshift(pos, 3) local w = bswap(readu32(data, bp)) local s = band(pos, 7) @@ -102050,13 +102065,13 @@ type Core = { return w end - @native local function read(n: number): number + local function read(n: number): number local v = rshift(peek32(), 32 - n) pos += n return v end - @native local function vlc(lut: buffer, k: number): number + local function vlc(lut: buffer, k: number): number local e = readu32(lut, rshift(peek32(), 32 - k) * 4) local l = rshift(e, 16) if l == 0 then @@ -102067,7 +102082,7 @@ type Core = { return band(e, 0xFFFF) - 32768 end - @native local function findStart(from: number, to: number): number + local function findStart(from: number, to: number): number local i = from while i + 3 < to do local c = readu8(data, i + 2) @@ -102085,7 +102100,7 @@ type Core = { return -1 end - @native local function newStore(): Store + local function newStore(): Store local y = buffer.create(cw * lumaH) local cb = buffer.create(chw * chromaH) local cr = buffer.create(chw * chromaH) @@ -102113,14 +102128,14 @@ type Core = { } end - @native local function loadMatrix(q: buffer) + local function loadMatrix(q: buffer) for i = 0, 63 do local v = read(8) writeu8(q, readu8(ZZ, i), if v == 0 then 1 else v) end end - @native local function applySequence(): boolean + local function applySequence(): boolean local w, h = seqW, seqH if w == 0 or h == 0 or w * h > state.maxPixels then return false @@ -102151,7 +102166,7 @@ type Core = { return true end - @native local function sequenceHeader(p: number): boolean + local function sequenceHeader(p: number): boolean pos = p * 8 local w = read(12) local h = read(12) @@ -102181,7 +102196,7 @@ type Core = { return w > 0 and h > 0 end - @native local function sequenceExtension() + local function sequenceExtension() state.profileLevel = read(8) progSeq = read(1) == 1 local cf = read(2) @@ -102199,7 +102214,7 @@ type Core = { end end - @native local function quantMatrixExtension() + local function quantMatrixExtension() if read(1) == 1 then loadMatrix(intraQ) buffer.copy(chromaIntraQ, 0, intraQ, 0, 64) @@ -102216,11 +102231,11 @@ type Core = { end end - @native local function fcode(v: number): number + local function fcode(v: number): number return if v < 1 or v > 9 then 1 else v end - @native local function pictureCodingExtension() + local function pictureCodingExtension() fc00, fc01, fc10, fc11 = fcode(read(4)), fcode(read(4)), fcode(read(4)), fcode(read(4)) dcPrec = read(2) picStruct = read(2) @@ -102240,7 +102255,7 @@ type Core = { end -- an extension (00 00 01 B5) at byte p - @native local function extension(p: number) + local function extension(p: number) pos = p * 8 local id = read(4) if id == 1 then @@ -102252,7 +102267,7 @@ type Core = { end end - @native local function decodeMotion(f: number, pred: number): number + local function decodeMotion(f: number, pred: number): number local code = vlc(MOTION, MOTION_BITS) local d = code local rsize = f - 1 @@ -102268,7 +102283,7 @@ type Core = { end local EDGE = buffer.create(Dsp.EDGE_SIZE) - @native local function mcPart(rY: buffer, rCb: buffer, rCr: buffer, sp: number, dp: number, rowY: number, h: number, mvx: number, mvy: number, avg: boolean) + local function mcPart(rY: buffer, rCb: buffer, rCr: buffer, sp: number, dp: number, rowY: number, h: number, mvx: number, mvy: number, avg: boolean) local stride, sb, db, ph = cw, 0, 0, lumaH local cs, csb, cdb = chw, 0, 0 if sp >= 0 then @@ -102329,7 +102344,7 @@ type Core = { -- the reference frame for field fs of direction d in a field picture: the second field of a P frame takes the -- opposite parity from its own first field - @native local function fieldRef(d: number, fs: number): Store + local function fieldRef(d: number, fs: number): Store if d == 0 then if secondField and ptype == 2 and fs ~= parity then return cur :: Store @@ -102339,7 +102354,7 @@ type Core = { return (bwS or cur) :: Store end - @native local function predictDir(d: number, avg: boolean) + local function predictDir(d: number, avg: boolean) local o = d * 8 if not fieldPic then local r = bwS @@ -102382,7 +102397,7 @@ type Core = { end end - @native local function predictMb() + local function predictMb() if ptype == 2 then predictDir(0, false) elseif motFw then @@ -102395,7 +102410,7 @@ type Core = { end end - @native local function resetPmv() + local function resetPmv() for i = 1, 8 do PMV[i] = 0 end @@ -102403,7 +102418,7 @@ type Core = { -- a skipped macroblock's motion (13818-2 7.6.6): P a zero vector (field pictures: from the same parity); B the -- previous macroblock's directions with its first vectors as frame (or same-parity field) prediction - @native local function skipMotion() + local function skipMotion() motionType = 1 FSEL[1], FSEL[3] = parity, parity if ptype == 2 then @@ -102423,7 +102438,7 @@ type Core = { local gapType = 1 local hasRef = false local SAVE = table.create(16, 0) - @native local function conceal(from: number, to: number) + local function conceal(from: number, to: number) if from > to or not hasRef then return end @@ -102474,7 +102489,7 @@ type Core = { end -- block b: 0..3 luma, then Cb / Cr alternating - @native local function decodeBlock(b: number): boolean + local function decodeBlock(b: number): boolean local n = 0 local q: buffer local onlyDc = true @@ -102681,7 +102696,7 @@ type Core = { return true end - @native local function getQscale(code: number): number + local function getQscale(code: number): number if qScaleType == 1 then return readu8(NON_LINEAR, code) end @@ -102689,7 +102704,7 @@ type Core = { end -- motion vectors of direction d (13818-2 7.6.3; MPEG-1: frame vectors, full_pel doubled) - @native local function motionVectors(d: number) + local function motionVectors(d: number) local fh, fv = fc10, fc11 if d == 0 then fh, fv = fc00, fc01 @@ -102758,7 +102773,7 @@ type Core = { end end - @native local function decodeMacroblock(first: boolean, endBits: number): boolean + local function decodeMacroblock(first: boolean, endBits: number): boolean local inc = 0 local t = vlc(MBAI, MBAI_BITS) while t == 34 and not err and pos < endBits do -- stuffing @@ -102913,7 +102928,7 @@ type Core = { return pos <= endBits end - @native local function decodeSlice(row: number, endByte: number) + local function decodeSlice(row: number, endByte: number) if mpeg2 and lumaH > 2800 then row += lshift(read(3), 7) end @@ -102960,7 +102975,7 @@ type Core = { end -- the frame a picture completes becomes the newest reference (I / P) - @native local function finishFrame(s: Store) + local function finishFrame(s: Store) if s.ptype ~= 3 then state.refOld = state.refNew state.refNew = s @@ -102968,7 +102983,7 @@ type Core = { end -- the picture header (after 00 00 01 00) and its extensions - @native local function pictureHeader(p: number, stop: number): (number?, number) + local function pictureHeader(p: number, stop: number): (number?, number) pos = p * 8 local tref = read(10) ptype = read(3) @@ -103020,7 +103035,7 @@ type Core = { return at, tref end - @native local function selectTarget(tref: number, tag: any): boolean + local function selectTarget(tref: number, tag: any): boolean fieldPic = picStruct ~= 3 parity = if picStruct == 2 then 1 else 0 secondField = false @@ -103073,7 +103088,7 @@ type Core = { return true end - @native local function setAddressing() + local function setAddressing() local target = cur :: Store curY, curCb, curCr = target.y, target.cb, target.cr if fieldPic then @@ -103092,7 +103107,7 @@ type Core = { mbIntra = false end - @native local function decodePicture(p: number, stop: number, tag: any): Store? + local function decodePicture(p: number, stop: number, tag: any): Store? local first, tref = pictureHeader(p, stop) if first == nil or not selectTarget(tref, tag) then return nil @@ -103138,7 +103153,7 @@ type Core = { local core = {} :: Core core.state = state - @native function core.write(src: buffer, off: number, n: number) + function core.write(src: buffer, off: number, n: number) if n <= 0 then return end @@ -103166,7 +103181,7 @@ type Core = { buffer.fill(data, dataLen, 0, PAD) end - @native local function sequenceUnit(at: number, stop: number) + local function sequenceUnit(at: number, stop: number) local ok = sequenceHeader(at + 4) local s = findStart(at + 4, stop) while s >= 0 do @@ -103180,7 +103195,7 @@ type Core = { end end - @native function core.nextPicture(atEnd: boolean, tag: any): (Store?, boolean) + function core.nextPicture(atEnd: boolean, tag: any): (Store?, boolean) while true do local at = findStart(readByte, dataLen) if at < 0 then @@ -103232,7 +103247,7 @@ type Core = { end end - @native function core.toRgba(s: Store, out: buffer) + function core.toRgba(s: Store, out: buffer) if s.chroma == 2 then toRgba422(s.y, s.cb, s.cr, s.cw, s.w, s.h, out) else @@ -103240,11 +103255,11 @@ type Core = { end end - @native function core.setYield(hook: (() -> ())?) + function core.setYield(hook: (() -> ())?) yieldHook = hook end - @native function core.reset() + function core.reset() dataLen = 0 readByte = 0 scanPos = 0 @@ -103798,7 +103813,7 @@ end return Theora end -__FILES["codecs/video/Theora/Decoder"] = @native function() +__FILES["codecs/video/Theora/Decoder"] = function() @@ -103855,7 +103870,7 @@ end -- the motion vector component VLC (Theora spec table 7.23): by the next 8 bits, (value + 32) * 16 + length local MV_VLC = table.create(256, 0) do - @native local function put(code: number, len: number, v: number) + local function put(code: number, len: number, v: number) local sh = 8 - len for i = 0, 2 ^ sh - 1 do MV_VLC[code * 2 ^ sh + i + 1] = (v + 32) * 16 + len @@ -104000,7 +104015,7 @@ type State = { keyframes: number, } -@native function D.new(info: Header.Info, setup: Header.Setup): State +function D.new(info: Header.Info, setup: Header.Setup): State local pf = info.pixelFormat local hdec = if pf % 2 == 0 then 1 else 0 local vdec = if pf < 2 then 1 else 0 @@ -104171,7 +104186,7 @@ type State = { end -- the 8-point IDCT of libtheora's idct8 (the spec's), on 8 values; returns the 8 outputs -@native local function idct8(x0: number, x1: number, x2: number, x3: number, x4: number, x5: number, x6: number, x7: number): (number, number, number, number, number, number, number, number) +local function idct8(x0: number, x1: number, x2: number, x3: number, x4: number, x5: number, x6: number, x7: number): (number, number, number, number, number, number, number, number) local t0 = (C4 * (x0 + x4)) // 65536 local t1 = (C4 * (x0 - x4)) // 65536 local t2 = (C6 * x2) // 65536 - (C2 * x6) // 65536 @@ -104200,7 +104215,7 @@ end -- the first IDCT pass: the rows of blk (i16, natural order) into the columns of tmp (i16: like libtheora, the -- dequantised coefficients and these intermediate values are 16-bit, which also bounds every residual) -@native local function idctRows(blk: buffer, tmp: buffer) +local function idctRows(blk: buffer, tmp: buffer) for i = 0, 7 do local o = i * 16 local x0, x1, x2, x3 = readi16(blk, o), readi16(blk, o + 2), readi16(blk, o + 4), readi16(blk, o + 6) @@ -104231,7 +104246,7 @@ end end -- the second pass, added to the prediction already in dst: column c of the block is row c of tmp -@native local function idctAdd(tmp: buffer, dst: buffer, pos: number, stride: number) +local function idctAdd(tmp: buffer, dst: buffer, pos: number, stride: number) for c = 0, 7 do local o = c * 16 local y0, y1, y2, y3, y4, y5, y6, y7 = idct8(readi16(tmp, o), readi16(tmp, o + 2), readi16(tmp, o + 4), readi16(tmp, o + 6), readi16(tmp, o + 8), readi16(tmp, o + 10), readi16(tmp, o + 12), readi16(tmp, o + 14)) @@ -104254,13 +104269,13 @@ end end end -@native local function wrap16(v: number): number +local function wrap16(v: number): number return (v + 32768) % 65536 - 32768 end -- the motion vector offsets of one component: integer part (toward zero) and the second sample's extra step (away -- from zero) when there is a fraction. q: quarter-pel (subsampled direction) or half-pel -@native local function mvSplit(d: number, q: boolean): (number, number) +local function mvSplit(d: number, q: boolean): (number, number) local div = if q then 4 else 2 local a = if d < 0 then -((-d) // div) else d // div local frac = d - a * div @@ -104270,7 +104285,7 @@ end -- reconstruct one coded fragment into dst (the SELF reference planes): the prediction (128 for intra blocks, the -- reference block or the average of two for inter ones) goes to dst first, then the residual is added -@native local function reconFrag(st: State, fi: number, qis: { number }, dstPlanes: { buffer }) +local function reconFrag(st: State, fi: number, qis: { number }, dstPlanes: { buffer }) local pli = st.fpl[fi] local mode = st.fmode[fi] local qti = if mode == INTRA then 0 else 1 @@ -104350,7 +104365,7 @@ end end end -@native local function filterH(b: buffer, p: number, stride: number, bv: { number }) +local function filterH(b: buffer, p: number, stride: number, bv: { number }) p -= 2 for _ = 0, 7 do local p0, p1, p2, p3 = readu8(b, p), readu8(b, p + 1), readu8(b, p + 2), readu8(b, p + 3) @@ -104361,7 +104376,7 @@ end end end -@native local function filterV(b: buffer, p: number, stride: number, bv: { number }) +local function filterV(b: buffer, p: number, stride: number, bv: { number }) local q0, q1, q2 = p - 2 * stride, p - stride, p + stride for x = 0, 7 do local p0, p1, p2, p3 = readu8(b, q0 + x), readu8(b, q1 + x), readu8(b, p + x), readu8(b, q2 + x) @@ -104371,7 +104386,7 @@ end end end -@native local function loopFilter(st: State, planes: { buffer }, flimit: number) +local function loopFilter(st: State, planes: { buffer }, flimit: number) local bv = st.bv for i = -128, 128 do local a = math.abs(i) @@ -104419,7 +104434,7 @@ end end -- extend each plane's edge pixels into its padding (for unrestricted motion vectors) -@native local function borders(st: State, planes: { buffer }) +local function borders(st: State, planes: { buffer }) for pli = 1, 3 do local b = planes[pli] local stride, px, py = st.stride[pli], st.padx[pli], st.pady[pli] @@ -104439,7 +104454,7 @@ end -- DC prediction (raster order per plane): each coded block's DC adds a prediction from its left / upper neighbours -- coded from the same reference frame (or the last such DC in the plane) -@native local function dcPredict(st: State) +local function dcPredict(st: State) local coded, refi, dcv = st.coded, st.refi, st.dcv for pli = 0, 2 do local nh, nv = st.nhf[pli + 1], st.nvf[pli + 1] @@ -104519,7 +104534,7 @@ end end end -@native function D.decode(st: State, data: buffer, off: number, len: number): (string?, string?) +function D.decode(st: State, data: buffer, off: number, len: number): (string?, string?) if len <= 0 then return "dup", nil end @@ -104527,7 +104542,7 @@ end bcopy(bb, 0, data, off, len) local maxp = len * 8 local pos = 0 - @native local function bits(n: number): number + local function bits(n: number): number if pos > maxp then pos = maxp end @@ -104536,7 +104551,7 @@ end return w end local huff = st.huff - @native local function sbRun(): number + local function sbRun(): number if bits(1) == 0 then return 1 elseif bits(1) == 0 then @@ -104552,7 +104567,7 @@ end end return 34 + bits(12) end - @native local function blockRun(): number + local function blockRun(): number if bits(1) == 0 then return 1 + bits(1) elseif bits(1) == 0 then @@ -104734,7 +104749,7 @@ end end -- motion vectors local clc = bits(1) == 1 - @native local function mv(): number + local function mv(): number if clc then local v = bits(6) return if v % 2 == 1 then -(v // 2) else v // 2 @@ -105028,7 +105043,7 @@ end return if intra then "key" else "inter", nil end -@native function D.plane(st: State, pli: number, x0: number, y0: number, w: number, h: number): buffer +function D.plane(st: State, pli: number, x0: number, y0: number, w: number, h: number): buffer local src = st.refs[st.shown][pli + 1] local stride, origin, ph = st.stride[pli + 1], st.origin[pli + 1], st.ph[pli + 1] local out = buffer.create(w * h) @@ -105040,7 +105055,7 @@ end end -- 4:2:2 (rows averaged in pairs) or 4:4:4 (2x2 averages) chroma down to 4:2:0 -@native function D.downsample(src: buffer, cw: number, ch: number, hdec: number, dst: buffer, off: number, ow: number, oh: number) +function D.downsample(src: buffer, cw: number, ch: number, hdec: number, dst: buffer, off: number, ow: number, oh: number) for r = 0, oh - 1 do local r0 = math.min(2 * r, ch - 1) local r1 = math.min(2 * r + 1, ch - 1) @@ -112825,7 +112840,7 @@ end return MpegPs end -__FILES["containers/MpegTs"] = @native function() +__FILES["containers/MpegTs"] = function() -- containers/MpegTs: an MPEG transport stream demuxer (ISO/IEC 13818-1). Absorbed from mpegts-luau 6e16197 (same @@ -112924,17 +112939,17 @@ 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 -@native local function crc32(b: buffer, off: number, n: number): number +local function crc32(b: buffer, off: number, n: number): number return Crc32.msb(b, off, n, 0xFFFFFFFF) end MpegTs.crc32 = crc32 -@native local function u16(b: buffer, p: number): number +local function u16(b: buffer, p: number): number return readu8(b, p) * 256 + readu8(b, p + 1) end -- 33-bit timestamp from the 5-byte PES encoding at p -@native local function readTs(b: buffer, p: number): number +local function readTs(b: buffer, p: number): number local b0 = readu8(b, p) local hi = band(rshift(b0, 1), 7) * 1073741824 -- bits 32..30 local mid = bor(lshift(readu8(b, p + 1), 7), rshift(readu8(b, p + 2), 1)) -- bits 29..15 @@ -112963,7 +112978,7 @@ type Demuxer = typeof(setmetatable( Demuxer )) -@native function MpegTs.new(): Demuxer +function MpegTs.new(): Demuxer local self = setmetatable({ _pend = buffer.create(64 * 1024), _pendLen = 0, @@ -112993,7 +113008,7 @@ type Demuxer = typeof(setmetatable( end -@native local function addStream(self: Demuxer, pid: number, streamType: number, program: number, language: string?) +local function addStream(self: Demuxer, pid: number, streamType: number, program: number, language: string?) local info = CODECS[streamType] local s = self._streams[pid] if s == nil then @@ -113016,7 +113031,7 @@ end end end -@native local function parseSection(self: Demuxer, pid: number, b: buffer, n: number) +local function parseSection(self: Demuxer, pid: number, b: buffer, n: number) -- n >= 3 bytes: table_id, section_length (n = 3 + section_length) if n < 12 then return @@ -113066,7 +113081,7 @@ end end end -@native local function sectionBytes(self: Demuxer, pid: number, s: SectionState, src: buffer, from: number, to: number) +local function sectionBytes(self: Demuxer, pid: number, s: SectionState, src: buffer, from: number, to: number) local n = to - from if n <= 0 then return @@ -113097,7 +113112,7 @@ end end end -@native local function sectionPayload(self: Demuxer, pid: number, pusi: boolean, b: buffer, pos: number, stop: number) +local function sectionPayload(self: Demuxer, pid: number, pusi: boolean, b: buffer, pos: number, stop: number) local s = self._sections[pid] if s == nil then s = { buf = buffer.create(MAX_SECTION), len = 0, active = false } @@ -113123,7 +113138,7 @@ end end -@native local function completePes(self: Demuxer, pid: number, st: PesState) +local function completePes(self: Demuxer, pid: number, st: PesState) st.active = false local b, len = st.buf, st.len if len < 6 or readu8(b, 0) ~= 0 or readu8(b, 1) ~= 0 or readu8(b, 2) ~= 1 then @@ -113241,7 +113256,7 @@ end self._queue[tail] = unit end -@native local function pesPayload( +local function pesPayload( self: Demuxer, pid: number, pusi: boolean, @@ -113334,7 +113349,7 @@ end end -@native local function packet(self: Demuxer, b: buffer, pk: number) +local function packet(self: Demuxer, b: buffer, pk: number) local stats = self.stats stats.packets += 1 local b1 = readu8(b, pk + 1) @@ -113407,7 +113422,7 @@ end end end -@native function Demuxer.push(self: Demuxer, data: buffer | string, offset: number?, len: number?): boolean +function Demuxer.push(self: Demuxer, data: buffer | string, offset: number?, len: number?): boolean local src: buffer if type(data) == "string" then src = buffer.fromstring(data) @@ -113490,7 +113505,7 @@ end return true end -@native function Demuxer.pull(self: Demuxer): Unit? +function Demuxer.pull(self: Demuxer): Unit? local q = self._queue local h = self._qhead local u = q[h] @@ -113508,7 +113523,7 @@ end return u end -@native function Demuxer.flush(self: Demuxer) +function Demuxer.flush(self: Demuxer) local pids = {} for pid, st in self._pes do if st.active then @@ -113522,7 +113537,7 @@ end self._pendLen = 0 end -@native function Demuxer.reset(self: Demuxer) +function Demuxer.reset(self: Demuxer) self._pendLen = 0 for _, st in self._pes do st.active = false @@ -113540,7 +113555,7 @@ end self._qtail = 0 end -@native function Demuxer.streamFor(self: Demuxer, kind: string): Stream? +function Demuxer.streamFor(self: Demuxer, kind: string): Stream? for _, s in self.streams do if s.kind == kind then return s @@ -113551,7 +113566,7 @@ end type DemuxOptions = { videoPid: number?, audioPid: number? } -@native function MpegTs.demux(data: buffer | string, opts: DemuxOptions?): Demuxed +function MpegTs.demux(data: buffer | string, opts: DemuxOptions?): Demuxed local d = MpegTs.new() d:push(data) d:flush() @@ -113600,7 +113615,7 @@ type DemuxOptions = { videoPid: number?, audioPid: number? } } end -@native function MpegTs.concat(units: { Unit }): buffer +function MpegTs.concat(units: { Unit }): buffer local n = 0 for _, u in units do n += buffer.len(u.data) @@ -113617,7 +113632,7 @@ end return MpegTs end -__FILES["containers/Ogg"] = @native function() +__FILES["containers/Ogg"] = function() @@ -113659,7 +113674,7 @@ type Stream = { local Reader = {} Reader.__index = Reader -@native local function newReader(d: any, serial: number, start: number): any +local function newReader(d: any, serial: number, start: number): any return setmetatable({ demux = d, buf = d.buf, @@ -113680,7 +113695,7 @@ Reader.__index = Reader }, Reader) end -@native function Reader._nextPage(self: any): boolean +function Reader._nextPage(self: any): boolean local b, d = self.buf, self.demux while true do local p = Page.find(b, self.pagePos, nil, d.verify) @@ -113732,7 +113747,7 @@ end end end -@native function Reader.nextPacket(self: any): Packet? +function Reader.nextPacket(self: any): Packet? if self.ended then return nil end @@ -113809,7 +113824,7 @@ end end end -@native function Reader.rewind(self: any) +function Reader.rewind(self: any) self.pagePos = self.start self.page = nil self.seg = 0 @@ -113819,7 +113834,7 @@ end self.ended = false end -@native function Reader._at(self: any, p: PageInfo) +function Reader._at(self: any, p: PageInfo) self:rewind() self.pagePos = p.offset self:_nextPage() -- loads p (it is a valid page of this serial) @@ -113838,11 +113853,11 @@ end end -- seekGranule: after the last page with granule <= g (bisection, then a short scan); before every granule rewinds (-1) -@native function Reader.seekGranule(self: any, g: number): (number?, Err.Err?) +function Reader.seekGranule(self: any, g: number): (number?, Err.Err?) local b, d = self.buf, self.demux local serial = self.serial local verify = d.verify - @native local function nextOf(pos: number, limit: number?): PageInfo? + local function nextOf(pos: number, limit: number?): PageInfo? while true do local p = Page.find(b, pos, limit, verify) if not p then @@ -113886,7 +113901,7 @@ end local Demux = {} Demux.__index = Demux -@native function Ogg.open(src: any, opts: { verify: boolean?, scanAll: boolean? }?): (any, Err.Err?) +function Ogg.open(src: any, opts: { verify: boolean?, scanAll: boolean? }?): (any, Err.Err?) local buf: buffer if type(src) == "buffer" then buf = src @@ -113952,7 +113967,7 @@ Demux.__index = Demux return d, nil end -@native function Demux._scanLast(self: any) +function Demux._scanLast(self: any) if self._lastDone then return end @@ -113974,17 +113989,17 @@ end end end -@native function Demux.streams(self: any): { Stream } +function Demux.streams(self: any): { Stream } self:_scanLast() return self._streams end -@native function Demux.stream(self: any, serial: number): Stream? +function Demux.stream(self: any, serial: number): Stream? self:_scanLast() return self._bySerial[serial] end -@native function Demux.find(self: any, codec: string): number? +function Demux.find(self: any, codec: string): number? for _, s in self._streams do if s.codec == codec then return s.serial @@ -113993,7 +114008,7 @@ end return nil end -@native function Demux.reader(self: any, serial: number): (any, Err.Err?) +function Demux.reader(self: any, serial: number): (any, Err.Err?) local r = self._readers[serial] if r then return r, nil @@ -114007,12 +114022,12 @@ end return r, nil end -@native function Demux.nextPacket(self: any, serial: number): Packet? +function Demux.nextPacket(self: any, serial: number): Packet? local r = self:reader(serial) return if r then r:nextPacket() else nil end -@native function Demux.seekGranule(self: any, serial: number, g: number): (number?, Err.Err?) +function Demux.seekGranule(self: any, serial: number, g: number): (number?, Err.Err?) local r, err = self:reader(serial) if not r then return nil, err @@ -114020,21 +114035,21 @@ end return r:seekGranule(g) end -@native function Demux.rewind(self: any, serial: number) +function Demux.rewind(self: any, serial: number) local r = self:reader(serial) if r then r:rewind() end end -@native function Demux.packets(self: any, serial: number): () -> Packet? +function Demux.packets(self: any, serial: number): () -> Packet? local r = self:reader(serial) - return @native function() + return function() return if r then r:nextPacket() else nil end end -@native function Ogg.copy(p: Packet): buffer +function Ogg.copy(p: Packet): buffer local c = buffer.create(p.size) buffer.copy(c, 0, p.data, p.offset, p.size) return c @@ -114042,7 +114057,7 @@ end return Ogg end -__FILES["containers/Ogg/Mux"] = @native function() +__FILES["containers/Ogg/Mux"] = function() @@ -114072,7 +114087,7 @@ type PacketOptions = { eos: boolean?, -- this is the stream's last packet (default false: finish() writes an empty eos page if needed) } -@native function Mux.new(opts: Options?): any +function Mux.new(opts: Options?): any local size = opts and opts.pageSize or 4096 if type(size) ~= "number" or size < 1 then size = 4096 @@ -114086,7 +114101,7 @@ type PacketOptions = { }, Mux) end -@native function Mux.stream(self: any, serial: number?): any +function Mux.stream(self: any, serial: number?): any local sr = serial or self.nextSerial self.nextSerial = math.max(self.nextSerial, sr + 1) local s = setmetatable({ @@ -114107,7 +114122,7 @@ end end -- the CRC of a page (the crc field written as zero) -@native local function crc(b: buffer, n: number): number +local function crc(b: buffer, n: number): number local c = 0 for i = 0, n - 1 do c = bxor(lshift(c, 8), CRC[bxor(rshift(c, 24), readu8(b, i)) + 1]) @@ -114115,7 +114130,7 @@ end return c end -@native function Stream._flush(self: any, eos: boolean) +function Stream._flush(self: any, eos: boolean) local nseg = #self.lacing local n = 27 + nseg + self.dataLen local b = buffer.create(n) @@ -114155,7 +114170,7 @@ end end end -@native function Stream.packet(self: any, data: any, granule: number, opts: PacketOptions?, offset: number?, length: number?): (boolean, Err.Err?) +function Stream.packet(self: any, data: any, granule: number, opts: PacketOptions?, offset: number?, length: number?): (boolean, Err.Err?) if self.ended then return false, Err.new(Err.ARG, "packet after the end of stream " .. self.serial) end @@ -114211,13 +114226,13 @@ end return true, nil end -@native function Stream.flush(self: any) +function Stream.flush(self: any) if not self.ended and #self.lacing > 0 then self:_flush(false) end end -@native function Mux.finish(self: any): buffer +function Mux.finish(self: any): buffer for _, s in self.streams do if not s.ended then if #s.lacing == 0 then @@ -114237,7 +114252,7 @@ end return Mux end -__FILES["containers/Ogg/Page"] = @native function() +__FILES["containers/Ogg/Page"] = function() @@ -114271,7 +114286,7 @@ type Info = { local CRC = Crc32.MSB_TABLE Page.CRC_TABLE = CRC -@native local function crcRange(b: buffer, from: number, to: number, crc: number): number +local function crcRange(b: buffer, from: number, to: number, crc: number): number for i = from, to - 1 do crc = bxor(lshift(crc, 8), CRC[bxor(rshift(crc, 24), readu8(b, i)) + 1]) end @@ -114279,7 +114294,7 @@ Page.CRC_TABLE = CRC end -- the Ogg CRC-32 of arbitrary data (the crc field is not zeroed) -@native function Page.crc32(b: buffer, offset: number?, len: number?): number +function Page.crc32(b: buffer, offset: number?, len: number?): number local o = offset or 0 local n = len or (buffer.len(b) - o) if o < 0 or n < 0 or o + n > buffer.len(b) then @@ -114288,7 +114303,7 @@ end return crcRange(b, o, o + n, 0) end -@native function Page.parse(b: buffer, pos: number, verify: boolean?): (Info?, string?) +function Page.parse(b: buffer, pos: number, verify: boolean?): (Info?, string?) local size = buffer.len(b) if pos < 0 or pos + 27 > size then return nil, "short" @@ -114338,7 +114353,7 @@ end }, nil end -@native function Page.find(b: buffer, pos: number, limit: number?, verify: boolean?): Info? +function Page.find(b: buffer, pos: number, limit: number?, verify: boolean?): Info? local size = buffer.len(b) local lim = math.min(limit or size, size - 27 + 1) if pos < 0 then @@ -114356,7 +114371,7 @@ end return nil end -@native function Page.findBack(b: buffer, pos: number, floor: number?, verify: boolean?): Info? +function Page.findBack(b: buffer, pos: number, floor: number?, verify: boolean?): Info? local size = buffer.len(b) local lo = math.max(floor or 0, 0) if pos > size - 27 then @@ -114374,8 +114389,8 @@ end return nil end -@native function Page.codec(b: buffer, off: number, len: number): string - @native local function is(s: string, at: number): boolean +function Page.codec(b: buffer, off: number, len: number): string + local function is(s: string, at: number): boolean if at + #s > len then return false end @@ -115769,14 +115784,14 @@ end return Zip end -__FILES["core/Adler32"] = @native function() +__FILES["core/Adler32"] = function() -- core/Adler32: Adler-32 (RFC 1950, the zlib checksum). Absorbed from deflate-luau src/Deflate/Checksum.luau (same author; -- no third-party code). Never throws: the range is clamped. local readu8 = buffer.readu8 -@native local function adler32(buf: buffer, off: number, len: number, adler: number?): number +local function adler32(buf: buffer, off: number, len: number, adler: number?): number local a0 = adler or 1 local a, b = a0 % 65536, a0 // 65536 local i, e = off, off + len @@ -115794,7 +115809,7 @@ local readu8 = buffer.readu8 return b * 65536 + a end -@native local function range(buf: buffer, offset: number?, length: number?): (number, number) +local function range(buf: buffer, offset: number?, length: number?): (number, number) local n = buffer.len(buf) local o = math.clamp(offset or 0, 0, n) return o, math.clamp(length or (n - o), 0, n - o) @@ -115802,12 +115817,12 @@ end local Adler32 = {} -@native function Adler32.of(buf: buffer, offset: number?, length: number?, adler: number?): number +function Adler32.of(buf: buffer, offset: number?, length: number?, adler: number?): number local o, l = range(buf, offset, length) return adler32(buf, o, l, adler) end -@native function Adler32.string(s: string, adler: number?): number +function Adler32.string(s: string, adler: number?): number return adler32(buffer.fromstring(s), 0, #s, adler) end @@ -115815,7 +115830,7 @@ Adler32.raw = adler32 return Adler32 end -__FILES["core/Base64"] = @native function() +__FILES["core/Base64"] = function() -- core/Base64: RFC 4648 base64 (standard alphabet, and base64url with opts.url) encode / decode, and data: URIs. @@ -115849,7 +115864,7 @@ buffer.writeu8(DEC, string.byte("="), 65) local readu8, writeu8 = buffer.readu8, buffer.writeu8 -@native function Base64.encode(data: buffer | string, opts: EncodeOptions?, offset: number?, length: number?): string +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) @@ -115903,7 +115918,7 @@ local readu8, writeu8 = buffer.readu8, buffer.writeu8 return buffer.tostring(out) end -@native function Base64.decode(s: string | buffer): (buffer?, string?) +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 + 1) * 3) @@ -115940,7 +115955,7 @@ end end -- RFC 2397: data:[][;params][;base64], (percent-encoded data when not base64) -@native function Base64.decodeDataUri(uri: string): (buffer?, string?) +function Base64.decodeDataUri(uri: string): (buffer?, string?) if string.sub(uri, 1, 5) ~= "data:" then return nil, "not a data: URI" end @@ -115962,19 +115977,19 @@ end end return b, mime end - local decoded = string.gsub(body, "%%(%x%x)", @native function(h: string): string + 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 -@native function Base64.dataUri(buf: buffer | string, mime: string?): string +function Base64.dataUri(buf: buffer | string, mime: string?): string return "data:" .. (mime or "application/octet-stream") .. ";base64," .. Base64.encode(buf) end return Base64 end -__FILES["core/Bits"] = @native function() +__FILES["core/Bits"] = function() -- core/Bits: bit readers and writers, LSB-first (DEFLATE, GIF LZW, VP8L, ...) and MSB-first (JPEG entropy data @@ -116010,7 +116025,7 @@ type BitReader = { bitsLeft: (BitReader) -> number, } -@native local function overrun(self: any) +local function overrun(self: any) if not self.err then self.err = Err.new(Err.TRUNCATED, "bit stream ends early", self.limit) end @@ -116020,7 +116035,7 @@ end local Lsb = {} Lsb.__index = Lsb -@native local function lsbFill(self: any, n: number) +local function lsbFill(self: any, n: number) local acc, cnt, pos = self.acc, self.cnt, self.pos while cnt < n do if pos < self.limit then @@ -116034,7 +116049,7 @@ Lsb.__index = Lsb self.acc, self.cnt, self.pos = acc, cnt, pos end -@native function Lsb.read(self: any, n: number): number +function Lsb.read(self: any, n: number): number if n > 24 then local lo = Lsb.read(self, 16) return lo + Lsb.read(self, n - 16) * 65536 @@ -116048,7 +116063,7 @@ end self.cnt -= n return v end -@native function Lsb.peek(self: any, n: number): number +function Lsb.peek(self: any, n: number): number if self.cnt < n then local acc, cnt, pos = self.acc, self.cnt, self.pos while cnt < n do -- no error for peeking past the end: the bits are zeros @@ -116066,23 +116081,23 @@ end end return self.acc % POW[n + 1] end -@native function Lsb.skip(self: any, n: number) +function Lsb.skip(self: any, n: number) while n > 24 do Lsb.read(self, 24) n -= 24 end Lsb.read(self, n) end -@native function Lsb.align(self: any) +function Lsb.align(self: any) local k = self.cnt % 8 if k > 0 then Lsb.read(self, k) end end -@native function Lsb.bytePos(self: any): number +function Lsb.bytePos(self: any): number return self.pos - floor(self.cnt / 8) end -@native function Lsb.bitsLeft(self: any): number +function Lsb.bitsLeft(self: any): number return (self.limit - self.pos) * 8 + self.cnt end @@ -116090,7 +116105,7 @@ end local Msb = {} Msb.__index = Msb -@native local function msbFill(self: any, n: number) +local function msbFill(self: any, n: number) local acc, cnt, pos = self.acc, self.cnt, self.pos while cnt < n do if pos < self.limit then @@ -116105,7 +116120,7 @@ Msb.__index = Msb self.acc, self.cnt, self.pos = acc, cnt, pos end -@native function Msb.read(self: any, n: number): number +function Msb.read(self: any, n: number): number if n > 24 then local hi = Msb.read(self, n - 16) return hi * 65536 + Msb.read(self, 16) @@ -116119,7 +116134,7 @@ end self.cnt -= n return v end -@native function Msb.peek(self: any, n: number): number +function Msb.peek(self: any, n: number): number local acc, cnt, pos = self.acc, self.cnt, self.pos while cnt < n do if pos < self.limit then @@ -116136,14 +116151,14 @@ end end return floor(acc / POW[cnt - n + 1]) end -@native function Msb.skip(self: any, n: number) +function Msb.skip(self: any, n: number) while n > 24 do Msb.read(self, 24) n -= 24 end Msb.read(self, n) end -@native function Msb.align(self: any) +function Msb.align(self: any) local k = self.cnt % 8 if k > 0 then Msb.read(self, k) @@ -116152,17 +116167,17 @@ end Msb.bytePos = Lsb.bytePos Msb.bitsLeft = Lsb.bitsLeft -@native local function reader(meta: any, buf: buffer, offset: number?, length: number?): BitReader +local function reader(meta: any, buf: buffer, offset: number?, length: number?): BitReader local n = blen(buf) local o = math.clamp(offset or 0, 0, n) local l = math.clamp(length or (n - o), 0, n - o) return setmetatable({ buf = buf, pos = o, limit = o + l, acc = 0, cnt = 0, err = nil }, meta) :: any end -@native function Bits.lsbReader(buf: buffer, offset: number?, length: number?): BitReader +function Bits.lsbReader(buf: buffer, offset: number?, length: number?): BitReader return reader(Lsb, buf, offset, length) end -@native function Bits.msbReader(buf: buffer, offset: number?, length: number?): BitReader +function Bits.msbReader(buf: buffer, offset: number?, length: number?): BitReader return reader(Msb, buf, offset, length) end @@ -116177,7 +116192,7 @@ type BitWriter = { local LsbW = {} LsbW.__index = LsbW -@native function LsbW.write(self: any, v: number, n: number) +function LsbW.write(self: any, v: number, n: number) if n > 24 then local lo = v % 65536 LsbW.write(self, lo, 16) @@ -116195,20 +116210,20 @@ LsbW.__index = LsbW end self.acc, self.cnt = acc, cnt end -@native function LsbW.align(self: any) +function LsbW.align(self: any) if self.cnt > 0 then self.out:u8(self.acc) self.acc, self.cnt = 0, 0 end end -@native function LsbW.finish(self: any): buffer +function LsbW.finish(self: any): buffer LsbW.align(self) return self.out:finish() end local MsbW = {} MsbW.__index = MsbW -@native function MsbW.write(self: any, v: number, n: number) +function MsbW.write(self: any, v: number, n: number) if n > 24 then local lo = v % 65536 MsbW.write(self, (v - lo) / 65536, n - 16) @@ -116227,20 +116242,20 @@ MsbW.__index = MsbW end self.acc, self.cnt = acc, cnt end -@native function MsbW.align(self: any) +function MsbW.align(self: any) if self.cnt > 0 then self.out:u8(self.acc * POW[8 - self.cnt + 1]) self.acc, self.cnt = 0, 0 end end -@native function MsbW.finish(self: any): buffer +function MsbW.finish(self: any): buffer MsbW.align(self) return self.out:finish() end -- w = { buf, pos, acc, cnt }: no growth (the caller keeps buf large enough); acc holds cnt < 8 bits type RawWriter = { buf: buffer, pos: number, acc: number, cnt: number } -@native function Bits.msbPut(w: RawWriter, v: number, n: number) +function Bits.msbPut(w: RawWriter, v: number, n: number) if n == 0 then return end @@ -116258,16 +116273,16 @@ type RawWriter = { buf: buffer, pos: number, acc: number, cnt: number } w.acc, w.cnt, w.pos = acc, cnt, p end -@native function Bits.lsbWriter(capacity: number?): BitWriter +function Bits.lsbWriter(capacity: number?): BitWriter return setmetatable({ out = Bytes.writer(capacity), acc = 0, cnt = 0 }, LsbW) :: any end -@native function Bits.msbWriter(capacity: number?): BitWriter +function Bits.msbWriter(capacity: number?): BitWriter return setmetatable({ out = Bytes.writer(capacity), acc = 0, cnt = 0 }, MsbW) :: any end return Bits end -__FILES["core/Bytes"] = @native function() +__FILES["core/Bytes"] = function() -- core/Bytes: a cursor Reader over a buffer range and a growable Writer. Little / big endian integers up to u64 (as a @@ -116301,21 +116316,21 @@ type Reader = typeof(setmetatable( Reader )) -@native function Bytes.reader(buf: buffer, offset: number?, length: number?): Reader +function Bytes.reader(buf: buffer, offset: number?, length: number?): Reader local n = blen(buf) local o = math.clamp(offset or 0, 0, n) local l = math.clamp(length or (n - o), 0, n - o) return setmetatable({ buf = buf, pos = o, base = o, limit = o + l, err = nil :: Err.Err? }, Reader) end -@native function Reader.fail(self: Reader, code: string, message: string): (nil, Err.Err) +function Reader.fail(self: Reader, code: string, message: string): (nil, Err.Err) if not self.err then self.err = Err.new(code, message, self.pos) end return nil, self.err :: Err.Err end -@native function Reader.need(self: Reader, n: number): boolean +function Reader.need(self: Reader, n: number): boolean if self.pos + n <= self.limit and n >= 0 then return true end @@ -116326,20 +116341,20 @@ end return false end -@native function Reader.tell(self: Reader): number +function Reader.tell(self: Reader): number return self.pos - self.base end -@native function Reader.size(self: Reader): number +function Reader.size(self: Reader): number return self.limit - self.base end -@native function Reader.remaining(self: Reader): number +function Reader.remaining(self: Reader): number return self.limit - self.pos end -@native function Reader.eof(self: Reader): boolean +function Reader.eof(self: Reader): boolean return self.pos >= self.limit end -@native function Reader.seek(self: Reader, offset: number): boolean +function Reader.seek(self: Reader, offset: number): boolean if offset < 0 or self.base + offset > self.limit then self.pos = self.limit if not self.err then @@ -116351,7 +116366,7 @@ end return true end -@native function Reader.skip(self: Reader, n: number): boolean +function Reader.skip(self: Reader, n: number): boolean if self:need(n) then self.pos += n return true @@ -116359,7 +116374,7 @@ end return false end -@native function Reader.align(self: Reader, n: number): boolean +function Reader.align(self: Reader, n: number): boolean local r = (self.pos - self.base) % n if r == 0 then return true @@ -116367,7 +116382,7 @@ end return self:skip(n - r) end -@native function Reader.u8(self: Reader): number +function Reader.u8(self: Reader): number local p = self.pos if p + 1 > self.limit then self:need(1) @@ -116376,7 +116391,7 @@ end self.pos = p + 1 return readu8(self.buf, p) end -@native function Reader.i8(self: Reader): number +function Reader.i8(self: Reader): number local p = self.pos if p + 1 > self.limit then self:need(1) @@ -116385,7 +116400,7 @@ end self.pos = p + 1 return readi8(self.buf, p) end -@native function Reader.u16le(self: Reader): number +function Reader.u16le(self: Reader): number local p = self.pos if p + 2 > self.limit then self:need(2) @@ -116394,7 +116409,7 @@ end self.pos = p + 2 return readu16(self.buf, p) end -@native function Reader.u16be(self: Reader): number +function Reader.u16be(self: Reader): number local p = self.pos if p + 2 > self.limit then self:need(2) @@ -116403,7 +116418,7 @@ end self.pos = p + 2 return readu8(self.buf, p) * 256 + readu8(self.buf, p + 1) end -@native function Reader.i16le(self: Reader): number +function Reader.i16le(self: Reader): number local p = self.pos if p + 2 > self.limit then self:need(2) @@ -116412,11 +116427,11 @@ end self.pos = p + 2 return readi16(self.buf, p) end -@native function Reader.i16be(self: Reader): number +function Reader.i16be(self: Reader): number local v = self:u16be() return if v >= 32768 then v - 65536 else v end -@native function Reader.u24le(self: Reader): number +function Reader.u24le(self: Reader): number local p = self.pos if p + 3 > self.limit then self:need(3) @@ -116425,7 +116440,7 @@ end self.pos = p + 3 return readu16(self.buf, p) + readu8(self.buf, p + 2) * 65536 end -@native function Reader.u24be(self: Reader): number +function Reader.u24be(self: Reader): number local p = self.pos if p + 3 > self.limit then self:need(3) @@ -116434,7 +116449,7 @@ end self.pos = p + 3 return readu8(self.buf, p) * 65536 + readu8(self.buf, p + 1) * 256 + readu8(self.buf, p + 2) end -@native function Reader.u32le(self: Reader): number +function Reader.u32le(self: Reader): number local p = self.pos if p + 4 > self.limit then self:need(4) @@ -116443,7 +116458,7 @@ end self.pos = p + 4 return readu32(self.buf, p) end -@native function Reader.u32be(self: Reader): number +function Reader.u32be(self: Reader): number local p = self.pos if p + 4 > self.limit then self:need(4) @@ -116452,7 +116467,7 @@ end self.pos = p + 4 return byteswap(readu32(self.buf, p)) end -@native function Reader.i32le(self: Reader): number +function Reader.i32le(self: Reader): number local p = self.pos if p + 4 > self.limit then self:need(4) @@ -116461,28 +116476,28 @@ end self.pos = p + 4 return readi32(self.buf, p) end -@native function Reader.i32be(self: Reader): number +function Reader.i32be(self: Reader): number local v = self:u32be() return if v >= 2147483648 then v - TWO32 else v end -@native function Reader.u64le(self: Reader): number +function Reader.u64le(self: Reader): number local lo = self:u32le() return lo + self:u32le() * TWO32 end -@native function Reader.u64be(self: Reader): number +function Reader.u64be(self: Reader): number local hi = self:u32be() return hi * TWO32 + self:u32be() end -@native function Reader.i64le(self: Reader): number +function Reader.i64le(self: Reader): number local lo = self:u32le() return lo + self:i32le() * TWO32 end -@native function Reader.i64be(self: Reader): number +function Reader.i64be(self: Reader): number local hi = self:i32be() return hi * TWO32 + self:u32be() end -@native local function half(h: number): number +local function half(h: number): number local s = if h >= 32768 then -1 else 1 local e = bit32.band(bit32.rshift(h, 10), 31) local m = bit32.band(h, 1023) @@ -116495,13 +116510,13 @@ end end Bytes.half = half -@native function Reader.f16le(self: Reader): number +function Reader.f16le(self: Reader): number return half(self:u16le()) end -@native function Reader.f16be(self: Reader): number +function Reader.f16be(self: Reader): number return half(self:u16be()) end -@native function Reader.f32le(self: Reader): number +function Reader.f32le(self: Reader): number local p = self.pos if p + 4 > self.limit then self:need(4) @@ -116510,12 +116525,12 @@ end self.pos = p + 4 return readf32(self.buf, p) end -@native function Reader.f32be(self: Reader): number +function Reader.f32be(self: Reader): number local v = self:u32be() writeu32(scratch, 0, v) return readf32(scratch, 0) end -@native function Reader.f64le(self: Reader): number +function Reader.f64le(self: Reader): number local p = self.pos if p + 8 > self.limit then self:need(8) @@ -116524,7 +116539,7 @@ end self.pos = p + 8 return readf64(self.buf, p) end -@native function Reader.f64be(self: Reader): number +function Reader.f64be(self: Reader): number local hi = self:u32be() local lo = self:u32be() writeu32(scratch, 0, lo) @@ -116532,7 +116547,7 @@ end return readf64(scratch, 0) end -@native function Reader.string(self: Reader, n: number): string +function Reader.string(self: Reader, n: number): string local p = self.pos if n < 0 or p + n > self.limit then self:need(n) @@ -116542,13 +116557,13 @@ end return readstring(self.buf, p, n) end -@native function Reader.fixed(self: Reader, n: number): string +function Reader.fixed(self: Reader, n: number): string local s = self:string(n) local z = string.find(s, "\0", 1, true) return if z then string.sub(s, 1, z - 1) else s end -@native function Reader.cstring(self: Reader, max: number?): string +function Reader.cstring(self: Reader, max: number?): string local p = self.pos local e = if max then math.min(self.limit, p + max) else self.limit local q = p @@ -116565,7 +116580,7 @@ end return readstring(buf, p, q - p) end -@native function Reader.match(self: Reader, s: string): boolean +function Reader.match(self: Reader, s: string): boolean local p, n = self.pos, #s if p + n > self.limit or readstring(self.buf, p, n) ~= s then return false @@ -116574,7 +116589,7 @@ end return true end -@native function Reader.peek(self: Reader, n: number, at: number?): string +function Reader.peek(self: Reader, n: number, at: number?): string local p = self.pos + (at or 0) if p < self.base or p >= self.limit then return "" @@ -116582,7 +116597,7 @@ end return readstring(self.buf, p, math.min(n, self.limit - p)) end -@native function Reader.peekU8(self: Reader, at: number?): number +function Reader.peekU8(self: Reader, at: number?): number local p = self.pos + (at or 0) if p < self.base or p >= self.limit then return -1 @@ -116590,7 +116605,7 @@ end return readu8(self.buf, p) end -@native function Reader.bytes(self: Reader, n: number): buffer +function Reader.bytes(self: Reader, n: number): buffer local p = self.pos if n < 0 or p + n > self.limit then self:need(n) @@ -116602,7 +116617,7 @@ end return b end -@native function Reader.slice(self: Reader, n: number): Reader +function Reader.slice(self: Reader, n: number): Reader local p = self.pos local l = math.max(0, math.min(n, self.limit - p)) if l < n then @@ -116613,7 +116628,7 @@ end return setmetatable({ buf = self.buf, pos = p, base = p, limit = p + l, err = nil :: Err.Err? }, Reader) end -@native function Reader.sub(self: Reader, offset: number, length: number?): Reader +function Reader.sub(self: Reader, offset: number, length: number?): Reader local o = math.clamp(self.base + offset, self.base, self.limit) local l = math.clamp(length or (self.limit - o), 0, self.limit - o) return setmetatable({ buf = self.buf, pos = o, base = o, limit = o + l, err = nil :: Err.Err? }, Reader) @@ -116630,11 +116645,11 @@ type Writer = typeof(setmetatable( Writer )) -@native function Bytes.writer(capacity: number?): Writer +function Bytes.writer(capacity: number?): Writer return setmetatable({ buf = bcreate(math.max(16, capacity or 256)), pos = 0 }, Writer) end -@native function Writer.reserve(self: Writer, n: number): number +function Writer.reserve(self: Writer, n: number): number local p = self.pos local cap = blen(self.buf) if p + n > cap then @@ -116645,45 +116660,45 @@ end return p end -@native function Writer.tell(self: Writer): number +function Writer.tell(self: Writer): number return self.pos end -@native function Writer.u8(self: Writer, v: number) +function Writer.u8(self: Writer, v: number) local p = self:reserve(1) writeu8(self.buf, p, v) self.pos = p + 1 end -@native function Writer.u16le(self: Writer, v: number) +function Writer.u16le(self: Writer, v: number) local p = self:reserve(2) writeu16(self.buf, p, v) self.pos = p + 2 end -@native function Writer.u16be(self: Writer, v: number) +function Writer.u16be(self: Writer, v: number) local p = self:reserve(2) writeu8(self.buf, p, bit32.rshift(v, 8)) writeu8(self.buf, p + 1, v) self.pos = p + 2 end -@native function Writer.u24le(self: Writer, v: number) +function Writer.u24le(self: Writer, v: number) local p = self:reserve(3) writeu16(self.buf, p, v) writeu8(self.buf, p + 2, bit32.rshift(v, 16)) self.pos = p + 3 end -@native function Writer.u24be(self: Writer, v: number) +function Writer.u24be(self: Writer, v: number) local p = self:reserve(3) writeu8(self.buf, p, bit32.rshift(v, 16)) writeu8(self.buf, p + 1, bit32.rshift(v, 8)) writeu8(self.buf, p + 2, v) self.pos = p + 3 end -@native function Writer.u32le(self: Writer, v: number) +function Writer.u32le(self: Writer, v: number) local p = self:reserve(4) writeu32(self.buf, p, v) self.pos = p + 4 end -@native function Writer.u32be(self: Writer, v: number) +function Writer.u32be(self: Writer, v: number) local p = self:reserve(4) writeu32(self.buf, p, byteswap(v % TWO32)) self.pos = p + 4 @@ -116693,73 +116708,73 @@ Writer.i16le = Writer.u16le Writer.i16be = Writer.u16be Writer.i32le = Writer.u32le Writer.i32be = Writer.u32be -@native function Writer.u64le(self: Writer, v: number) +function Writer.u64le(self: Writer, v: number) self:u32le(v % TWO32) self:u32le(math.floor(v / TWO32) % TWO32) end -@native function Writer.u64be(self: Writer, v: number) +function Writer.u64be(self: Writer, v: number) self:u32be(math.floor(v / TWO32) % TWO32) self:u32be(v % TWO32) end Writer.i64le = Writer.u64le Writer.i64be = Writer.u64be -@native function Writer.f32le(self: Writer, v: number) +function Writer.f32le(self: Writer, v: number) local p = self:reserve(4) writef32(self.buf, p, v) self.pos = p + 4 end -@native function Writer.f32be(self: Writer, v: number) +function Writer.f32be(self: Writer, v: number) writef32(scratch, 0, v) self:u32be(readu32(scratch, 0)) end -@native function Writer.f64le(self: Writer, v: number) +function Writer.f64le(self: Writer, v: number) local p = self:reserve(8) writef64(self.buf, p, v) self.pos = p + 8 end -@native function Writer.f64be(self: Writer, v: number) +function Writer.f64be(self: Writer, v: number) writef64(scratch, 0, v) self:u32be(readu32(scratch, 4)) self:u32be(readu32(scratch, 0)) end -@native function Writer.string(self: Writer, s: string) +function Writer.string(self: Writer, s: string) local n = #s local p = self:reserve(n) writestring(self.buf, p, s) self.pos = p + n end -@native function Writer.cstring(self: Writer, s: string) +function Writer.cstring(self: Writer, s: string) self:string(s) self:u8(0) end -@native function Writer.bytes(self: Writer, b: buffer, offset: number?, length: number?) +function Writer.bytes(self: Writer, b: buffer, offset: number?, length: number?) local o = offset or 0 local n = length or (blen(b) - o) local p = self:reserve(n) bcopy(self.buf, p, b, o, n) self.pos = p + n end -@native function Writer.fill(self: Writer, v: number, n: number) +function Writer.fill(self: Writer, v: number, n: number) local p = self:reserve(n) bfill(self.buf, p, v, n) self.pos = p + n end -@native function Writer.setU32le(self: Writer, at: number, v: number) +function Writer.setU32le(self: Writer, at: number, v: number) writeu32(self.buf, at, v) end -@native function Writer.setU32be(self: Writer, at: number, v: number) +function Writer.setU32be(self: Writer, at: number, v: number) writeu32(self.buf, at, byteswap(v % TWO32)) end -@native function Writer.setU16le(self: Writer, at: number, v: number) +function Writer.setU16le(self: Writer, at: number, v: number) writeu16(self.buf, at, v) end -@native function Writer.setU8(self: Writer, at: number, v: number) +function Writer.setU8(self: Writer, at: number, v: number) writeu8(self.buf, at, v) end -@native function Writer.finish(self: Writer): buffer +function Writer.finish(self: Writer): buffer local b = bcreate(self.pos) bcopy(b, 0, self.buf, 0, self.pos) return b @@ -116768,14 +116783,14 @@ end Bytes.Reader = Reader Bytes.Writer = Writer -@native function Bytes.toBuffer(v: any): buffer? +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 -@native function Bytes.span(what: string, input: any, offset: number?, length: number?): (buffer?, number, number, Err.Err?) +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)) @@ -116794,7 +116809,7 @@ end return Bytes end -__FILES["core/Crc16"] = @native function() +__FILES["core/Crc16"] = function() -- core/Crc16: the 16-bit CRCs old archive formats use, table driven. New code. ccitt: CRC-16/XMODEM (0x1021, MSB first, @@ -116820,13 +116835,13 @@ end local Crc16 = {} -@native local function clamp(buf: buffer, off: number, len: number): (number, number) +local function clamp(buf: buffer, off: number, len: number): (number, number) local n = buffer.len(buf) local o = math.clamp(math.floor(off), 0, n) return o, math.clamp(math.floor(len), 0, n - o) end -@native function Crc16.ccitt(buf: buffer, off: number, len: number, crc: number?): number +function Crc16.ccitt(buf: buffer, off: number, len: number, crc: number?): number local o, l = clamp(buf, off, len) local c = crc or 0 for i = o, o + l - 1 do @@ -116835,7 +116850,7 @@ end return c end -@native function Crc16.arc(buf: buffer, off: number, len: number, crc: number?): number +function Crc16.arc(buf: buffer, off: number, len: number, crc: number?): number local o, l = clamp(buf, off, len) local c = crc or 0 for i = o, o + l - 1 do @@ -116846,7 +116861,7 @@ end return Crc16 end -__FILES["core/Crc32"] = @native function() +__FILES["core/Crc32"] = function() -- core/Crc32: CRC-32 (IEEE 802.3, the zlib / gzip / zip / PNG polynomial 0xEDB88320, reflected), slice-by-8. @@ -116885,7 +116900,7 @@ for n = 0, 255 do T7[n + 1] = c end -@native local function crc32(buf: buffer, off: number, len: number, crc: number?): number +local function crc32(buf: buffer, off: number, len: number, crc: number?): number local c = bxor(crc or 0, 0xFFFFFFFF) local i, e = off, off + len local e8 = e - 8 @@ -116917,7 +116932,7 @@ end return bxor(c, 0xFFFFFFFF) end -@native local function range(buf: buffer, offset: number?, length: number?): (number, number) +local function range(buf: buffer, offset: number?, length: number?): (number, number) local n = buffer.len(buf) local o = math.clamp(offset or 0, 0, n) return o, math.clamp(length or (n - o), 0, n - o) @@ -116925,12 +116940,12 @@ end local Crc32 = {} -@native function Crc32.of(buf: buffer, offset: number?, length: number?, crc: number?): number +function Crc32.of(buf: buffer, offset: number?, length: number?, crc: number?): number local o, l = range(buf, offset, length) return crc32(buf, o, l, crc) end -@native function Crc32.string(s: string, crc: number?): number +function Crc32.string(s: string, crc: number?): number return crc32(buffer.fromstring(s), 0, #s, crc) end @@ -116948,7 +116963,7 @@ for n = 0, 255 do end Crc32.MSB_TABLE = MSB -@native function Crc32.msb(buf: buffer, off: number, len: number, init: number?): number +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]) @@ -117116,7 +117131,7 @@ end return Input end -__FILES["core/Md5"] = @native function() +__FILES["core/Md5"] = function() @@ -117165,7 +117180,7 @@ type State = { local M = table.create(16, 0) -@native local function compress(st: State, blk: buffer, o: number) +local function compress(st: State, blk: buffer, o: number) for i = 0, 15 do M[i + 1] = readu32(blk, o + i * 4) end @@ -117193,7 +117208,7 @@ local M = table.create(16, 0) st.d = (st.d + d) % 4294967296 end -@native local function update(self: State, buf: buffer, offset: number?, length: number?) +local function update(self: State, buf: buffer, offset: number?, length: number?) local n = buffer.len(buf) local o = math.clamp(offset or 0, 0, n) local len = math.clamp(length or (n - o), 0, n - o) @@ -117221,7 +117236,7 @@ end end end -@native local function digest(self: State): string +local function digest(self: State): string local bits = self.total * 8 local blk = self.block local f = self.fill @@ -117245,7 +117260,7 @@ end return buffer.tostring(out) end -@native function Md5.new(): State +function Md5.new(): State return { a = 0x67452301, b = 0xEFCDAB89, @@ -117259,7 +117274,7 @@ end } end -@native function Md5.hex(d: string): string +function Md5.hex(d: string): string local out = table.create(#d) for i = 1, #d do out[i] = string.format("%02x", string.byte(d, i)) @@ -117267,7 +117282,7 @@ end return table.concat(out) end -@native function Md5.of(buf: buffer, offset: number?, length: number?): string +function Md5.of(buf: buffer, offset: number?, length: number?): string local h = Md5.new() h:update(buf, offset, length) return Md5.hex(h:digest()) @@ -117403,7 +117418,7 @@ Cbor.undefined = Codec.undefined return Cbor end -__FILES["data/cbor/Codec"] = @native function() +__FILES["data/cbor/Codec"] = function() -- data/cbor/Codec: CBOR (RFC 8949) decoder and encoder; never throws (errors return nil, message, offset). @@ -117415,30 +117430,30 @@ local Codec = {} local TWO32 = 4294967296 -- ------------------------------------------------------------------------------------------------ value types -local TaggedMeta = { __tostring = @native function(t: any): string +local TaggedMeta = { __tostring = function(t: any): string return "cbor.tag(" .. t.tag .. ")" end } -local SimpleMeta = { __tostring = @native function(s: any): string +local SimpleMeta = { __tostring = function(s: any): string return "cbor.simple(" .. s.value .. ")" end } -@native function Codec.tagged(tag: number, value: any): { tag: number, value: any } +function Codec.tagged(tag: number, value: any): { tag: number, value: any } return setmetatable({ tag = tag, value = value }, TaggedMeta) :: any end -@native function Codec.isTagged(v: any): boolean +function Codec.isTagged(v: any): boolean return type(v) == "table" and getmetatable(v) == TaggedMeta end -- unassigned simple values: 0..19, 32..255 -@native function Codec.simple(n: number): { value: number } +function Codec.simple(n: number): { value: number } return setmetatable({ value = n }, SimpleMeta) :: any end -@native function Codec.isSimple(v: any): boolean +function Codec.isSimple(v: any): boolean return type(v) == "table" and getmetatable(v) == SimpleMeta end -Codec.undefined = table.freeze(setmetatable({}, { __tostring = @native function() +Codec.undefined = table.freeze(setmetatable({}, { __tostring = function() return "undefined" end })) -@native local function bigText(s: string): string +local function bigText(s: string): string local limbs = {} -- base 1e7, little-endian for i = 1, #s do local carry = string.byte(s, i) @@ -117461,7 +117476,7 @@ end })) end return table.concat(out) end -@native local function incText(s: string): string +local function incText(s: string): string local digits: { number } = table.create(#s) :: { number } for i = 1, #s do digits[i] = string.byte(s, i) - 48 @@ -117495,7 +117510,7 @@ type St = { r: Bytes.Reader, big: boolean, null: any, undef: any, maxDepth: numb local BREAK = {} -- 0xFF break stop code -- additional information 31: indefinite length -@native local function arg(st: St, ai: number): (number?, string?, string?) +local function arg(st: St, ai: number): (number?, string?, string?) local r = st.r if ai < 24 then return ai, nil, nil @@ -117519,7 +117534,7 @@ end local item: (st: St, depth: number) -> (any, string?) -@native local function chunks(st: St, major: number, depth: number): (string?, string?) +local function chunks(st: St, major: number, depth: number): (string?, string?) local parts = {} while true do local r = st.r @@ -117546,7 +117561,7 @@ end local half = Bytes.half -@native local function tag(st: St, t: number, v: any): (any, string?) +local function tag(st: St, t: number, v: any): (any, string?) if t == 0 and st.dates then if type(v) ~= "string" then return nil, "tag 0 needs a text string" @@ -117589,7 +117604,7 @@ local half = Bytes.half return Codec.tagged(t, v), nil end -@native function item(st: St, depth: number): (any, string?) +function item(st: St, depth: number): (any, string?) if depth > st.maxDepth then return nil, "nested deeper than " .. st.maxDepth end @@ -117756,7 +117771,7 @@ end end end -@native function Codec.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, string?, number?) +function Codec.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, string?, number?) local o: DecodeOptions = opts or {} local st: St = { r = r, @@ -117787,7 +117802,7 @@ type EncodeOptions = { type ESt = { w: Bytes.Writer, compact: boolean, sort: boolean, emptyMap: boolean, epoch: boolean, maxDepth: number, err: string? } -@native local function head(w: Bytes.Writer, major: number, n: number) +local function head(w: Bytes.Writer, major: number, n: number) local m = major * 32 if n < 24 then w:u8(m + n) @@ -117810,7 +117825,7 @@ type ESt = { w: Bytes.Writer, compact: boolean, sort: boolean, emptyMap: boolean end end -@native local function toHalf(x: number): number? +local function toHalf(x: number): number? if x ~= x then return 0x7E00 end @@ -117848,7 +117863,7 @@ local isArray = Types.isArray local scratch = buffer.create(8) -@native local function enc(st: ESt, v: any, depth: number): boolean +local function enc(st: ESt, v: any, depth: number): boolean local w = st.w local tv = type(v) if v == nil or v == Types.null then @@ -117953,7 +117968,7 @@ local scratch = buffer.create(8) return true end -@native function Codec.encode(v: any, opts: EncodeOptions?): (buffer?, string?) +function Codec.encode(v: any, opts: EncodeOptions?): (buffer?, string?) local o: EncodeOptions = opts or {} local st: ESt = { w = Bytes.writer(256), @@ -118711,7 +118726,7 @@ Msgpack.isExt = Codec.isExt return Msgpack end -__FILES["data/msgpack/Codec"] = @native function() +__FILES["data/msgpack/Codec"] = function() -- data/msgpack/Codec: MessagePack (2017 spec: str8 / bin / ext, timestamp ext -1) decoder and encoder; never throws. @@ -118723,17 +118738,17 @@ local Codec = {} local TWO32 = 4294967296 -- ext type: -128..127 -local ExtMeta = { __tostring = @native function(e: any): string +local ExtMeta = { __tostring = function(e: any): string return "msgpack.ext(" .. e.type .. ", " .. buffer.len(e.data) .. " bytes)" end } -@native function Codec.ext(t: number, data: buffer): { type: number, data: buffer } +function Codec.ext(t: number, data: buffer): { type: number, data: buffer } return setmetatable({ type = t, data = data }, ExtMeta) :: any end -@native function Codec.isExt(v: any): boolean +function Codec.isExt(v: any): boolean return type(v) == "table" and getmetatable(v) == ExtMeta end -@native local function u64text(hi: number, lo: number): string +local function u64text(hi: number, lo: number): string if hi == 0 then return string.format("%d", lo) end @@ -118762,7 +118777,7 @@ type DecodeOptions = { type St = { r: Bytes.Reader, big: boolean, null: any, maxDepth: number, ts: boolean, ordered: boolean } -@native local function int64(st: St, signed: boolean): any +local function int64(st: St, signed: boolean): any local r = st.r local hi, lo = r:u32be(), r:u32be() if signed and hi >= 0x80000000 then @@ -118784,7 +118799,7 @@ end local value: (st: St, depth: number) -> (any, string?) -@native local function ext(st: St, n: number): (any, string?) +local function ext(st: St, n: number): (any, string?) local r = st.r local t = r:i8() if r.err or not r:need(n) then @@ -118814,7 +118829,7 @@ local value: (st: St, depth: number) -> (any, string?) return Codec.ext(t, r:bytes(n)), nil end -@native local function array(st: St, n: number, depth: number): (any, string?) +local function array(st: St, n: number, depth: number): (any, string?) if n > st.r:remaining() then return nil, "array count past the end" end @@ -118829,7 +118844,7 @@ end return t, nil end -@native local function map(st: St, n: number, depth: number): (any, string?) +local function map(st: St, n: number, depth: number): (any, string?) if n * 2 > st.r:remaining() then return nil, "map count past the end" end @@ -118855,7 +118870,7 @@ end return Types.object(t, order or {}), nil end -@native function value(st: St, depth: number): (any, string?) +function value(st: St, depth: number): (any, string?) if depth > st.maxDepth then return nil, "nested deeper than " .. st.maxDepth end @@ -118949,7 +118964,7 @@ end return nil, string.format("reserved type byte 0x%02x", b) end -@native function Codec.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, string?, number?) +function Codec.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, string?, number?) local o: DecodeOptions = opts or {} local st: St = { r = r, @@ -118977,7 +118992,7 @@ type EncodeOptions = { type ESt = { w: Bytes.Writer, f32: boolean, sort: boolean, emptyMap: boolean, maxDepth: number, bin: boolean, err: string? } -@native local function writeInt(w: Bytes.Writer, v: number) +local function writeInt(w: Bytes.Writer, v: number) if v >= 0 then if v < 128 then w:u8(v) @@ -119016,7 +119031,7 @@ type ESt = { w: Bytes.Writer, f32: boolean, sort: boolean, emptyMap: boolean, ma end end -@native local function lenHeader(w: Bytes.Writer, n: number, fix: number?, fixMax: number, b8: number?, b16: number, b32: number) +local function lenHeader(w: Bytes.Writer, n: number, fix: number?, fixMax: number, b8: number?, b16: number, b32: number) if fix and n <= fixMax then w:u8(fix + n) elseif b8 and n < 256 then @@ -119036,7 +119051,7 @@ local keyLess = Types.keyLess local isArray = Types.isArray Codec.isArray = isArray -@native local function enc(st: ESt, v: any, depth: number): boolean +local function enc(st: ESt, v: any, depth: number): boolean local w = st.w local tv = type(v) if v == nil or v == Types.null then @@ -119134,7 +119149,7 @@ Codec.isArray = isArray return true end -@native function Codec.encode(v: any, opts: EncodeOptions?): (buffer?, string?) +function Codec.encode(v: any, opts: EncodeOptions?): (buffer?, string?) local o: EncodeOptions = opts or {} local st: ESt = { w = Bytes.writer(256), @@ -119518,7 +119533,7 @@ Plist.isUid = Binary.isUid return Plist end -__FILES["data/plist/Binary"] = @native function() +__FILES["data/plist/Binary"] = function() -- data/plist/Binary: binary plist reader ("bplist00", CFBinaryPList.c / Python's plistlib); 16-byte ints: low 8 bytes. @@ -119530,17 +119545,17 @@ local readu8 = buffer.readu8 local TWO32 = 4294967296 local EPOCH_2001 = 978307200 -local UidMeta = { __tostring = @native function(u: any): string +local UidMeta = { __tostring = function(u: any): string return "UID(" .. u.uid .. ")" end } -@native function Binary.uid(n: number): { uid: number } +function Binary.uid(n: number): { uid: number } return setmetatable({ uid = n }, UidMeta) :: any end -@native function Binary.isUid(v: any): boolean +function Binary.isUid(v: any): boolean return type(v) == "table" and getmetatable(v) == UidMeta end -@native local function be(b: buffer, o: number, n: number): number +local function be(b: buffer, o: number, n: number): number local v = 0 for k = 0, n - 1 do v = v * 256 + readu8(b, o + k) @@ -119548,7 +119563,7 @@ end return v end -@native local function utf8char(c: number): string +local function utf8char(c: number): string if c < 0x80 then return string.char(c) elseif c < 0x800 then @@ -119561,7 +119576,7 @@ end type Options = { bigInts: ("number" | "string")?, maxDepth: number? } -@native function Binary.decode(b: buffer, base: number, len: number, opts: Options?): (any, string?) +function Binary.decode(b: buffer, base: number, len: number, opts: Options?): (any, string?) if len < 40 then return nil, "truncated: shorter than header + trailer" end @@ -119583,7 +119598,7 @@ type Options = { bigInts: ("number" | "string")?, maxDepth: number? } local object: (idx: number, depth: number) -> (any, string?) -- a length nibble: 0..14, or 15 = an int object follows - @native local function count(o: number, nib: number): (number?, number) + local function count(o: number, nib: number): (number?, number) if nib < 15 then return nib, o + 1 end @@ -119601,11 +119616,11 @@ type Options = { bigInts: ("number" | "string")?, maxDepth: number? } return be(b, base + o + 2, w), o + 2 + w end - @native local function ref(at: number): number + local function ref(at: number): number return be(b, base + at, refSize) end - @native function object(idx: number, depth: number): (any, string?) + function object(idx: number, depth: number): (any, string?) local cached = cache[idx] if cached ~= nil then return cached, nil @@ -129076,7 +129091,7 @@ end return Exr end -__FILES["image/exr/Codec"] = @native function() +__FILES["image/exr/Codec"] = function() @@ -129089,7 +129104,7 @@ local Codec = {} local readu8, writeu8, readi8, readu16, readu32, readf32, writef32 = buffer.readu8, buffer.writeu8, buffer.readi8, buffer.readu16, buffer.readu32, buffer.readf32, buffer.writef32 local HALF = Half.TABLE -@native local function reconstruct(t: buffer, n: number): buffer +local function reconstruct(t: buffer, n: number): buffer local prev = if n > 0 then readu8(t, 0) else 0 for i = 1, n - 1 do prev = (prev + readu8(t, i) - 128) % 256 @@ -129106,7 +129121,7 @@ local HALF = Half.TABLE return out end -@native function Codec.rle(src: buffer, p: number, n: number, outSize: number): (buffer?, string?) +function Codec.rle(src: buffer, p: number, n: number, outSize: number): (buffer?, string?) local t = buffer.create(outSize) local o, stop = 0, p + n while p < stop do @@ -129135,7 +129150,7 @@ end return reconstruct(t, outSize), nil end -@native function Codec.unzip(src: buffer, p: number, n: number, outSize: number): (buffer?, string?) +function Codec.unzip(src: buffer, p: number, n: number, outSize: number): (buffer?, string?) local t, err = Deflate.zlib(src, p, n, outSize) if not t then return nil, tostring(err) @@ -129146,7 +129161,7 @@ end return reconstruct(t, outSize), nil end -@native function Codec.zip(raw: buffer, level: number): buffer +function Codec.zip(raw: buffer, level: number): buffer local n = buffer.len(raw) local t = buffer.create(n) local half = (n + 1) // 2 @@ -129167,7 +129182,7 @@ end return Deflate.zlibCompress(t, { level = level }) :: buffer end -@native function Codec.samples(src: buffer, p: number, count: number, kind: number, dst: buffer, d: number, step: number): number +function Codec.samples(src: buffer, p: number, count: number, kind: number, dst: buffer, d: number, step: number): number if kind == 1 then for i = 0, count - 1 do writef32(dst, d + i * step, HALF[readu16(src, p + i * 2)]) @@ -129187,7 +129202,7 @@ end return Codec end -__FILES["image/exr/Piz"] = @native function() +__FILES["image/exr/Piz"] = function() @@ -129203,9 +129218,9 @@ local DECBITS = 14 local SHORT_ZEROCODE_RUN, LONG_ZEROCODE_RUN, SHORTEST_LONG_RUN = 59, 63, 6 -- ------------------------------------------------------------------------------------------------ Huffman -@native local function unpackTable(src: buffer, p: number, limit: number, im: number, iM: number, len: { number }): number? +local function unpackTable(src: buffer, p: number, limit: number, im: number, iM: number, len: { number }): number? local c, lc = 0, 0 - @native local function bits(n: number): number? + local function bits(n: number): number? while lc < n do if p >= limit then return nil @@ -129255,7 +129270,7 @@ local SHORT_ZEROCODE_RUN, LONG_ZEROCODE_RUN, SHORTEST_LONG_RUN = 59, 63, 6 return p end -@native local function huffman(src: buffer, p: number, n: number, out: buffer, nRaw: number): string? +local function huffman(src: buffer, p: number, n: number, out: buffer, nRaw: number): string? if n == 0 then return if nRaw == 0 then nil else "empty Huffman data" end @@ -129395,7 +129410,7 @@ end end -- ------------------------------------------------------------------------------------------------ wavelet -@native local function wav2Decode(t: buffer, base: number, nx: number, ox: number, ny: number, oy: number, mx: number) +local function wav2Decode(t: buffer, base: number, nx: number, ox: number, ny: number, oy: number, mx: number) local w14 = mx < 16384 local n = math.min(nx, ny) local p = 1 @@ -129405,7 +129420,7 @@ end p //= 2 local p2 = p p //= 2 - @native local function dec(l: number, h: number): (number, number) + local function dec(l: number, h: number): (number, number) if w14 then local ls = if l >= 32768 then l - 65536 else l local hs = if h >= 32768 then h - 65536 else h @@ -129463,7 +129478,7 @@ end -- ------------------------------------------------------------------------------------------------ decode type Chan = { nx: number, ny: number, size: number, ys: number } -@native function Piz.decode(src: buffer, p: number, n: number, chans: { Chan }, minY: number, maxY: number, outSize: number): (buffer?, string?) +function Piz.decode(src: buffer, p: number, n: number, chans: { Chan }, minY: number, maxY: number, outSize: number): (buffer?, string?) local total = 0 for _, c in chans do total += c.nx * c.ny * c.size @@ -130060,7 +130075,7 @@ end return Gif end -__FILES["image/gif/Decode"] = @native function() +__FILES["image/gif/Decode"] = function() @@ -130070,7 +130085,7 @@ local readu8, readu32, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu32 local Decode = {} -- interlace passes: every 8th row from 0, every 8th from 4, every 4th from 2, every 2nd from 1 -@native local function interlacedRow(fh: number): { number } +local function interlacedRow(fh: number): { number } local map = table.create(fh, 0) local r = 0 for _, pass in { { 0, 8 }, { 4, 8 }, { 2, 4 }, { 1, 2 } } do @@ -130084,7 +130099,7 @@ local Decode = {} return map end -@native function Decode.toRgba(indexes: buffer, fw: number, fh: number, interlaced: boolean, palette: buffer, out: buffer) +function Decode.toRgba(indexes: buffer, fw: number, fh: number, interlaced: boolean, palette: buffer, out: buffer) local rows = if interlaced then interlacedRow(fh) else nil for y = 0, fh - 1 do local src = (if rows then rows[y + 1] else y) * fw @@ -130095,7 +130110,7 @@ end end end -@native function Decode.draw(canvas: buffer, cw: number, ch: number, frame: buffer, fx: number, fy: number, fw: number, fh: number) +function Decode.draw(canvas: buffer, cw: number, ch: number, frame: buffer, fx: number, fy: number, fw: number, fh: number) local x0, y0 = math.max(0, fx), math.max(0, fy) local x1, y1 = math.min(cw, fx + fw), math.min(ch, fy + fh) for y = y0, y1 - 1 do @@ -130110,7 +130125,7 @@ end end end -@native function Decode.clear(canvas: buffer, cw: number, ch: number, fx: number, fy: number, fw: number, fh: number) +function Decode.clear(canvas: buffer, cw: number, ch: number, fx: number, fy: number, fw: number, fh: number) local x0, y0 = math.max(0, fx), math.max(0, fy) local x1, y1 = math.min(cw, fx + fw), math.min(ch, fy + fh) if x1 <= x0 then @@ -130352,7 +130367,7 @@ end return Hdr end -__FILES["image/hdr/Codec"] = @native function() +__FILES["image/hdr/Codec"] = function() @@ -130363,7 +130378,7 @@ local frexp = math.frexp local Codec = {} -- old-style RLE: 1, 1, 1, n repeats the previous pixel (n << 8 for consecutive markers); new-style: 2, 2, width, planes -@native function Codec.readLine(b: buffer, p: number, limit: number, w: number, row: buffer): (number?, string?) +function Codec.readLine(b: buffer, p: number, limit: number, w: number, row: buffer): (number?, string?) if w >= 8 and w <= 32767 and p + 4 <= limit and readu8(b, p) == 2 and readu8(b, p + 1) == 2 and readu8(b, p + 2) < 128 then if readu8(b, p + 2) * 256 + readu8(b, p + 3) ~= w then return nil, "scanline width mismatch" @@ -130446,7 +130461,7 @@ local Codec = {} return p, nil end -@native function Codec.toFloat(row: buffer, n: number, out: buffer, base: number, step: number) +function Codec.toFloat(row: buffer, n: number, out: buffer, base: number, step: number) for i = 0, n - 1 do local q = i * 4 local e = readu8(row, q + 3) @@ -130465,7 +130480,7 @@ end end end -@native function Codec.fromFloat(px: buffer, y: number, w: number, row: buffer) +function Codec.fromFloat(px: buffer, y: number, w: number, row: buffer) for x = 0, w - 1 do local q = (y * w + x) * 16 local r, g, b = readf32(px, q), readf32(px, q + 4), readf32(px, q + 8) @@ -130511,7 +130526,7 @@ end end end -@native function Codec.writeLine(row: buffer, w: number, out: buffer, o: number): number +function Codec.writeLine(row: buffer, w: number, out: buffer, o: number): number writeu8(out, o, 2) writeu8(out, o + 1, 2) writeu8(out, o + 2, w // 256) @@ -131171,7 +131186,7 @@ end return Ico end -__FILES["image/ico/Dib"] = @native function() +__FILES["image/ico/Dib"] = function() @@ -131183,7 +131198,7 @@ local readu8, readu32, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu32 local Dib = {} -- 32-bit entries use their alpha unless it is all zero (old icons); then the AND mask decides -@native function Dib.decode(b: buffer, p: number, e: number, w: number, h: number, bpp: number, pal: buffer, palN: number, out: buffer): (boolean, string?) +function Dib.decode(b: buffer, p: number, e: number, w: number, h: number, bpp: number, pal: buffer, palN: number, out: buffer): (boolean, string?) local stride = ((w * bpp + 31) // 32) * 4 local maskStride = ((w + 31) // 32) * 4 if p + stride * h > e then @@ -131231,7 +131246,7 @@ local Dib = {} return true, nil end -@native function Dib.encode(px: buffer, w: number, h: number, out: buffer, o: number): number +function Dib.encode(px: buffer, w: number, h: number, out: buffer, o: number): number for y = h - 1, 0, -1 do for x = 0, w - 1 do local q = (y * w + x) * 4 @@ -133225,7 +133240,7 @@ end return Png end -__FILES["image/png/Apng"] = @native function() +__FILES["image/png/Apng"] = function() @@ -133235,11 +133250,11 @@ local bcreate, bcopy, bfill = buffer.create, buffer.copy, buffer.fill local Apng = {} -@native local function div255(x: number): number +local function div255(x: number): number return (x + 128) * 257 // 65536 end -@native local function blend(canvas: buffer, cw: number, src: buffer, fw: number, fh: number, fx: number, fy: number, over: boolean) +local function blend(canvas: buffer, cw: number, src: buffer, fw: number, fh: number, fx: number, fy: number, over: boolean) for y = 0, fh - 1 do local so = y * fw * 4 local co = ((fy + y) * cw + fx) * 4 @@ -133271,7 +133286,7 @@ end end end -@native function Apng.composite(w: number, h: number, frames: { any }): { buffer } +function Apng.composite(w: number, h: number, frames: { any }): { buffer } local canvas = bcreate(w * h * 4) local saved = bcreate(w * h * 4) local out: { buffer } = {} @@ -133305,7 +133320,7 @@ end return Apng end -__FILES["image/png/Decode"] = @native function() +__FILES["image/png/Decode"] = function() @@ -133331,11 +133346,11 @@ Decode.PASSES = PASSES local CHANNELS = { [0] = 1, [2] = 3, [3] = 1, [4] = 2, [6] = 4 } Decode.CHANNELS = CHANNELS -@native function Decode.rowBytes(pw: number, channels: number, depth: number): number +function Decode.rowBytes(pw: number, channels: number, depth: number): number return (pw * channels * depth + 7) // 8 end -@native local function unfilter(raw: buffer, p: number, ph: number, rb: number, bpp: number): (boolean, number) +local function unfilter(raw: buffer, p: number, ph: number, rb: number, bpp: number): (boolean, number) local stride = rb + 1 for r = 0, ph - 1 do local f = readu8(raw, p) @@ -133410,7 +133425,7 @@ end return true, 0 end -@native local function convert(raw: buffer, ro: number, pw: number, out: buffer, oo: number, ostep: number, ct: number, depth: number, pal: buffer, tr: number) +local function convert(raw: buffer, ro: number, pw: number, out: buffer, oo: number, ostep: number, ct: number, depth: number, pal: buffer, tr: number) if ct == 6 then if depth == 8 then if ostep == 4 then @@ -133508,7 +133523,7 @@ end end end -@native function Decode.run(raw: buffer, w: number, h: number, depth: number, ct: number, interlace: number, pal: buffer, tr: number, out: buffer): (boolean, string?) +function Decode.run(raw: buffer, w: number, h: number, depth: number, ct: number, interlace: number, pal: buffer, tr: number, out: buffer): (boolean, string?) local channels = CHANNELS[ct] local bpp = math.max(1, (channels * depth) // 8) local p = 0 @@ -133545,7 +133560,7 @@ end return Decode end -__FILES["image/png/Encode"] = @native function() +__FILES["image/png/Encode"] = function() @@ -133557,7 +133572,7 @@ local Encode = {} local CHANNELS = { [0] = 1, [2] = 3, [4] = 2, [6] = 4 } -@native function Encode.pickColorType(px: buffer, w: number, h: number): string +function Encode.pickColorType(px: buffer, w: number, h: number): string local opaque, gray = true, true for i = 0, w * h - 1 do local o = i * 4 @@ -133578,7 +133593,7 @@ local CHANNELS = { [0] = 1, [2] = 3, [4] = 2, [6] = 4 } return "rgb" end -@native local function pack(px: buffer, w: number, h: number, ct: number): buffer +local function pack(px: buffer, w: number, h: number, ct: number): buffer local ch = CHANNELS[ct] if ch == 4 then return px @@ -133602,7 +133617,7 @@ end return out end -@native local function paeth(a: number, b: number, c: number): number +local function paeth(a: number, b: number, c: number): number local pa = math.abs(b - c) local pb = math.abs(a - c) local pc = math.abs(a + b - c - c) @@ -133614,7 +133629,7 @@ end return c end -@native local function costs(src: buffer, s: number, rb: number, bpp: number, first: boolean): (number, number, number, number, number) +local function costs(src: buffer, s: number, rb: number, bpp: number, first: boolean): (number, number, number, number, number) local c0, c1, c2, c3, c4 = 0, 0, 0, 0, 0 local p = s - rb for i = 0, rb - 1 do @@ -133643,7 +133658,7 @@ end return c0, c1, c2, c3, c4 end -@native local function apply(src: buffer, s: number, rb: number, bpp: number, first: boolean, f: number, out: buffer, o: number) +local function apply(src: buffer, s: number, rb: number, bpp: number, first: boolean, f: number, out: buffer, o: number) writeu8(out, o, f) o += 1 if f == 0 or (f == 2 and first) then @@ -133671,7 +133686,7 @@ end end end -@native function Encode.filter(px: buffer, w: number, h: number, ct: number): buffer +function Encode.filter(px: buffer, w: number, h: number, ct: number): buffer local ch = CHANNELS[ct] local src = pack(px, w, h, ct) local rb = w * ch @@ -134078,7 +134093,7 @@ end return Pnm end -__FILES["image/pnm/Codec"] = @native function() +__FILES["image/pnm/Codec"] = function() @@ -134090,7 +134105,7 @@ local byteswap = bit32.byteswap local Codec = {} -- mode 1 = binary 8-bit, 2 = binary 16-bit big-endian, 3 = ASCII decimal, 4 = ASCII P1 (single digits) -@native function Codec.readSamples(b: buffer, p: number, limit: number, count: number, mode: number, out: buffer): (boolean, string?) +function Codec.readSamples(b: buffer, p: number, limit: number, count: number, mode: number, out: buffer): (boolean, string?) if mode == 1 then if p + count > limit then return false, "truncated" @@ -134149,7 +134164,7 @@ local Codec = {} return true, nil end -@native function Codec.readBits(b: buffer, p: number, limit: number, w: number, h: number, out: buffer): (boolean, string?) +function Codec.readBits(b: buffer, p: number, limit: number, w: number, h: number, out: buffer): (boolean, string?) local rowBytes = (w + 7) // 8 if p + rowBytes * h > limit then return false, "truncated" @@ -134167,11 +134182,11 @@ end Codec.RGBA8, Codec.RGB8, Codec.GRAY8, Codec.GRAYA8, Codec.RGBA16, Codec.GRAY16, Codec.RGBAF32 = 0, 1, 2, 3, 4, 5, 6 -- 8-bit: round(v * 255 / maxval) -@native function Codec.pack(s: buffer, n: number, ch: number, maxval: number, invert: boolean, fmt: number, dst: buffer) +function Codec.pack(s: buffer, n: number, ch: number, maxval: number, invert: boolean, fmt: number, dst: buffer) local wide = fmt == 4 or fmt == 5 local top = if wide then 65535 else 255 local half = maxval // 2 - @native local function get(i: number): number + local function get(i: number): number local v = math.min(readu16(s, i * 2), maxval) if invert then v = maxval - v @@ -134217,7 +134232,7 @@ Codec.RGBA8, Codec.RGB8, Codec.GRAY8, Codec.GRAYA8, Codec.RGBA16, Codec.GRAY16, end end -@native function Codec.readFloats(b: buffer, p: number, limit: number, w: number, h: number, ch: number, le: boolean, dst: buffer): (boolean, string?) +function Codec.readFloats(b: buffer, p: number, limit: number, w: number, h: number, ch: number, le: boolean, dst: buffer): (boolean, string?) if p + w * h * ch * 4 > limit then return false, "truncated" end @@ -134247,7 +134262,7 @@ end return true, nil end -@native local function f(v: number): number +local function f(v: number): number if v ~= v then return 0 end @@ -134255,7 +134270,7 @@ end end -- grey from colour: Pillow's L = (299 R + 587 G + 114 B) / 1000 -@native function Codec.extract(px: buffer, fmt: number, n: number, ch: number, wide: boolean): buffer +function Codec.extract(px: buffer, fmt: number, n: number, ch: number, wide: boolean): buffer local out = buffer.create(n * ch * 2) local srcWide = fmt == 4 or fmt == 5 local isGray = fmt == 2 or fmt == 3 or fmt == 5 @@ -134303,7 +134318,7 @@ end return out end -@native function Codec.writeSamples(s: buffer, count: number, wide: boolean, out: buffer, o: number): number +function Codec.writeSamples(s: buffer, count: number, wide: boolean, out: buffer, o: number): number if wide then for i = 0, count - 1 do local v = readu16(s, i * 2) @@ -134320,7 +134335,7 @@ end return o end -@native function Codec.writeBits(s: buffer, w: number, h: number, threshold: number, out: buffer, o: number): number +function Codec.writeBits(s: buffer, w: number, h: number, threshold: number, out: buffer, o: number): number for y = 0, h - 1 do local acc, nb = 0, 0 for x = 0, w - 1 do @@ -134340,7 +134355,7 @@ end return o end -@native function Codec.writeFloats(px: buffer, w: number, h: number, ch: number, out: buffer, o: number): number +function Codec.writeFloats(px: buffer, w: number, h: number, ch: number, out: buffer, o: number): number for y = h - 1, 0, -1 do for x = 0, w - 1 do local q = (y * w + x) * 16 @@ -134477,7 +134492,7 @@ end return Qoi end -__FILES["image/qoi/Codec"] = @native function() +__FILES["image/qoi/Codec"] = function() @@ -134488,7 +134503,7 @@ local Codec = {} local index = buffer.create(256) -@native function Codec.decode(b: buffer, p: number, limit: number, out: buffer, n: number): (boolean, string?) +function Codec.decode(b: buffer, p: number, limit: number, out: buffer, n: number): (boolean, string?) buffer.fill(index, 0, 0, 256) local r, g, bl, a = 0, 0, 0, 255 local o = 0 @@ -134559,7 +134574,7 @@ local index = buffer.create(256) return true, nil end -@native function Codec.encode(px: buffer, n: number, bpp: number, out: buffer, o: number): number +function Codec.encode(px: buffer, n: number, bpp: number, out: buffer, o: number): number buffer.fill(index, 0, 0, 256) local pr, pg, pb, pa = 0, 0, 0, 255 local run = 0 @@ -135428,7 +135443,7 @@ end return Tga end -__FILES["image/tga/Codec"] = @native function() +__FILES["image/tga/Codec"] = function() @@ -135438,7 +135453,7 @@ local readu8, readu16, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu1 local Codec = {} -- kind: 0 grey 8, 1 grey + alpha 16, 2 = 15/16-bit ARGB1555, 3 = BGR 24, 4 = BGRA 32, 5 = index 8, 6 = index 16 -@native local function pixel(b: buffer, p: number, kind: number, alpha1: boolean, pal: buffer, palN: number): number +local function pixel(b: buffer, p: number, kind: number, alpha1: boolean, pal: buffer, palN: number): number if kind == 0 then return readu8(b, p) * 0x10101 + 0xFF000000 elseif kind == 1 then @@ -135461,10 +135476,10 @@ local Codec = {} end Codec.pixel = pixel -@native function Codec.decode(b: buffer, p: number, limit: number, w: number, h: number, bpp: number, kind: number, alpha1: boolean, rle: boolean, bottomUp: boolean, rtl: boolean, pal: buffer, palN: number, out: buffer): (number, boolean) +function Codec.decode(b: buffer, p: number, limit: number, w: number, h: number, bpp: number, kind: number, alpha1: boolean, rle: boolean, bottomUp: boolean, rtl: boolean, pal: buffer, palN: number, out: buffer): (number, boolean) local n = w * h local i = 0 - @native local function put(v: number) + local function put(v: number) local row, col = i // w, i % w if bottomUp then row = h - 1 - row @@ -135512,8 +135527,8 @@ Codec.pixel = pixel return i, false end -@native function Codec.encode(px: buffer, w: number, h: number, srcBpp: number, outBpp: number, rle: boolean, topDown: boolean, out: buffer, o: number): number - @native local function get(q: number): number +function Codec.encode(px: buffer, w: number, h: number, srcBpp: number, outBpp: number, rle: boolean, topDown: boolean, out: buffer, o: number): number + local function get(q: number): number if srcBpp == 1 then return readu8(px, q) elseif srcBpp == 3 then @@ -135521,7 +135536,7 @@ end end return readu32(px, q) end - @native local function emit(v: number) + local function emit(v: number) if outBpp == 1 then writeu8(out, o, v % 256) else @@ -136407,7 +136422,7 @@ end return Tiff end -__FILES["image/tiff/Pixels"] = @native function() +__FILES["image/tiff/Pixels"] = function() @@ -136423,7 +136438,7 @@ local Pixels = {} local scratch = buffer.create(8) -- floats read through their bits: LuaJIT's FFI can hand back a NaN with a payload its NaN-tagging misreads -@native local function f32(bits: number): number +local function f32(bits: number): number if band(bits, 0x7F800000) == 0x7F800000 then if band(bits, 0x7FFFFF) ~= 0 then return 0 / 0 @@ -136433,7 +136448,7 @@ local scratch = buffer.create(8) writeu32(scratch, 0, bits) return readf32(scratch, 0) end -@native local function f64(lo: number, hi: number): number +local function f64(lo: number, hi: number): number if band(hi, 0x7FF00000) == 0x7FF00000 then if band(hi, 0xFFFFF) ~= 0 or lo ~= 0 then return 0 / 0 @@ -136458,14 +136473,14 @@ for i = 0, 255 do end writeu8(REV, i, r) end -@native function Pixels.reverseBits(b: buffer, off: number, len: number) +function Pixels.reverseBits(b: buffer, off: number, len: number) for i = off, off + len - 1 do writeu8(b, i, readu8(REV, readu8(b, i))) end end -- ------------------------------------------------------------------------------------------------ predictors -@native function Pixels.unpredict2(b: buffer, off: number, rows: number, rb: number, stride: number, bps: number, le: boolean) +function Pixels.unpredict2(b: buffer, off: number, rows: number, rb: number, stride: number, bps: number, le: boolean) for r = 0, rows - 1 do local base = off + r * rb if bps == 8 then @@ -136500,7 +136515,7 @@ end end end -@native function Pixels.predict2(b: buffer, off: number, rows: number, rb: number, stride: number, bps: number) +function Pixels.predict2(b: buffer, off: number, rows: number, rb: number, stride: number, bps: number) for r = 0, rows - 1 do local base = off + r * rb if bps == 8 then @@ -136517,7 +136532,7 @@ end end -- the samples come out little endian whatever the file's byte order (libtiff fpAcc) -@native function Pixels.unpredict3(b: buffer, off: number, rows: number, rb: number, bytes: number, stride: number, tmp: buffer) +function Pixels.unpredict3(b: buffer, off: number, rows: number, rb: number, bytes: number, stride: number, tmp: buffer) local wc = rb // bytes for r = 0, rows - 1 do local base = off + r * rb @@ -136533,7 +136548,7 @@ end end end -@native function Pixels.predict3(b: buffer, off: number, rows: number, rb: number, bytes: number, stride: number, tmp: buffer) +function Pixels.predict3(b: buffer, off: number, rows: number, rb: number, bytes: number, stride: number, tmp: buffer) local wc = rb // bytes for r = 0, rows - 1 do local base = off + r * rb @@ -136570,7 +136585,7 @@ type Params = { out: buffer, } -@native local function fast(P: Params): boolean +local function fast(P: Params): boolean if not P.chunky or P.bps ~= 8 or P.sfmt ~= 1 or P.assoc then return false end @@ -136619,7 +136634,7 @@ type Params = { return false end -@native function Pixels.convert(P: Params) +function Pixels.convert(P: Params) if fast(P) then return end @@ -136629,7 +136644,7 @@ end local float = sfmt == 3 local signed = sfmt == 2 local cmapN = 2 ^ math.min(bps, 16) - @native local function raw(s: number, x: number, row: number): number + local function raw(s: number, x: number, row: number): number local b, i if chunky then b, i = planes[1], x * spp + s @@ -136685,7 +136700,7 @@ end end end -- normalised 0..1 (floats as stored) - @native local function norm(s: number, x: number, row: number): number + local function norm(s: number, x: number, row: number): number local v = raw(s, x, row) if float then return v @@ -137884,7 +137899,7 @@ end return Webp end -__FILES["image/webp/Alpha"] = @native function() +__FILES["image/webp/Alpha"] = function() -- image/webp/Alpha: the ALPH chunk (RFC 9649 section 2.7.1.2); unfilters of libwebp src/dsp/filters.c (BSD-3-Clause, @@ -137895,7 +137910,7 @@ local readu8, writeu8 = buffer.readu8, buffer.writeu8 local Alpha = {} -@native local function unfilter(a: buffer, w: number, h: number, filter: number) +local function unfilter(a: buffer, w: number, h: number, filter: number) if filter == 0 then return end @@ -137928,7 +137943,7 @@ local Alpha = {} end end -@native function Alpha.decode(buf: buffer, off: number, len: number, w: number, h: number): (buffer?, any) +function Alpha.decode(buf: buffer, off: number, len: number, w: number, h: number): (buffer?, any) if len <= 1 then return nil, "truncated: ALPH chunk" end @@ -137960,7 +137975,7 @@ end return Alpha end -__FILES["image/webp/Anim"] = @native function() +__FILES["image/webp/Anim"] = function() -- image/webp/Anim: WebP animation compositing; coalesce() matches libwebp's WebPAnimDecoder (src/demux/anim_decode.c, @@ -137984,7 +137999,7 @@ type Frame = { } -- non-premultiplied 0xAABBGGRR, as libwebp BlendPixelNonPremult -@native local function blendPixel(src: number, dst: number): number +local function blendPixel(src: number, dst: number): number local sa = rshift(src, 24) if sa == 0 then return dst @@ -138000,7 +138015,7 @@ type Frame = { end Anim.blendPixel = blendPixel -@native local function blendRow(cur: buffer, prev: buffer, o: number, n: number) +local function blendRow(cur: buffer, prev: buffer, o: number, n: number) for i = o, o + n - 1 do local s = readu32(cur, i * 4) if s < 0xff000000 then @@ -138009,19 +138024,19 @@ Anim.blendPixel = blendPixel end end -@native local function draw(canvas: buffer, cw: number, f: Frame) +local function draw(canvas: buffer, cw: number, f: Frame) for j = 0, f.h - 1 do bcopy(canvas, ((f.y + j) * cw + f.x) * 4, f.rgba, j * f.w * 4, f.w * 4) end end -@native local function clearRect(canvas: buffer, cw: number, x: number, y: number, w: number, h: number) +local function clearRect(canvas: buffer, cw: number, x: number, y: number, w: number, h: number) for j = 0, h - 1 do bfill(canvas, ((y + j) * cw + x) * 4, 0, w * 4) end end -@native function Anim.coalesce(cw: number, ch: number, frames: { Frame }): { buffer } +function Anim.coalesce(cw: number, ch: number, frames: { Frame }): { buffer } local size = cw * ch * 4 local out: { buffer } = {} local disposed = bcreate(size) @@ -138079,7 +138094,7 @@ end return out end -@native function Anim.composite(cw: number, ch: number, frames: { Frame }): { buffer } +function Anim.composite(cw: number, ch: number, frames: { Frame }): { buffer } local size = cw * ch * 4 local canvas = bcreate(size) local out: { buffer } = {} @@ -140360,7 +140375,7 @@ end return Psd end -__FILES["layered/psd/Channels"] = @native function() +__FILES["layered/psd/Channels"] = function() -- layered/psd/Channels: PSD / PSB channel data (Photoshop File Formats Specification 2016, "Channel image data" / @@ -140375,14 +140390,14 @@ local readf32, writef32, bcreate, bcopy, blen, bfill = buffer.readf32, buffer.wr local floor, min, max = math.floor, math.min, math.max local byteswap = bit32.byteswap -@native function Channels.rowBytes(w: number, depth: number): number +function Channels.rowBytes(w: number, depth: number): number if depth == 1 then return (w + 7) // 8 end return w * (depth // 8) end -@native function Channels.rleCounts(src: buffer, p: number, limit: number, rows: number, psb: boolean): ({ number }?, number) +function Channels.rleCounts(src: buffer, p: number, limit: number, rows: number, psb: boolean): ({ number }?, number) local size = if psb then 4 else 2 if rows < 0 or p + rows * size > limit then return nil, p @@ -140399,7 +140414,7 @@ end return counts, p end -@native function Channels.rle(src: buffer, p: number, limit: number, counts: { number }, first: number, rows: number, rowBytes: number, dst: buffer, d: number): (number?, string?) +function Channels.rle(src: buffer, p: number, limit: number, counts: { number }, first: number, rows: number, rowBytes: number, dst: buffer, d: number): (number?, string?) for i = 0, rows - 1 do local c = counts[first + i] or 0 if p + c > limit then @@ -140415,7 +140430,7 @@ end return p, nil end -@native local function unpredict(plane: buffer, w: number, h: number, depth: number) +local function unpredict(plane: buffer, w: number, h: number, depth: number) if depth == 8 then for y = 0, h - 1 do local o = y * w @@ -140458,7 +140473,7 @@ end end end -@native function Channels.channel(src: buffer, p: number, limit: number, w: number, h: number, depth: number, psb: boolean): (buffer?, string?) +function Channels.channel(src: buffer, p: number, limit: number, w: number, h: number, depth: number, psb: boolean): (buffer?, string?) local rb = Channels.rowBytes(w, depth) local plane = bcreate(rb * h) if w == 0 or h == 0 then @@ -140498,7 +140513,7 @@ end return plane, nil end -@native local function sample8(plane: buffer, i: number, depth: number): number +local function sample8(plane: buffer, i: number, depth: number): number if depth == 8 then return readu8(plane, i) elseif depth == 16 then @@ -140514,24 +140529,24 @@ end return if readu8(plane, i // 8) // 2 ^ (7 - i % 8) % 2 == 1 then 0 else 255 end -@native function Channels.swap32(plane: buffer) +function Channels.swap32(plane: buffer) for i = 0, blen(plane) // 4 - 1 do writeu32(plane, i * 4, byteswap(readu32(plane, i * 4))) end end -- PSD Lab (0..255 each) to sRGB, the D50 white approximated by D65 -@native local function srgb(c: number): number +local function srgb(c: number): number c = if c <= 0.0031308 then 12.92 * c else 1.055 * c ^ (1 / 2.4) - 0.055 return floor(max(0, min(1, c)) * 255 + 0.5) end -@native local function lab(l8: number, a8: number, b8: number): (number, number, number) +local function lab(l8: number, a8: number, b8: number): (number, number, number) local L = l8 * 100 / 255 local a, b = a8 - 128, b8 - 128 local fy = (L + 16) / 116 local fx = fy + a / 500 local fz = fy - b / 200 - @native local function f(t: number): number + local function f(t: number): number return if t > 6 / 29 then t * t * t else 3 * (6 / 29) ^ 2 * (t - 4 / 29) end local X, Y, Z = 0.95047 * f(fx), f(fy), 1.08883 * f(fz) @@ -140542,7 +140557,7 @@ end end -- PSD colour modes: 0 bitmap, 1 grey, 2 indexed, 3 RGB, 4 CMYK, 7 multichannel, 8 duotone, 9 Lab -@native function Channels.toRGBA(planes: { [any]: buffer }, w: number, h: number, depth: number, mode: number, palette: buffer?): buffer +function Channels.toRGBA(planes: { [any]: buffer }, w: number, h: number, depth: number, mode: number, palette: buffer?): buffer local n = w * h local out = bcreate(n * 4) local c1, c2, c3, c4 = planes[1], planes[2], planes[3], planes[4] @@ -140601,7 +140616,7 @@ end return out end -@native function Channels.gray8(plane: buffer, w: number, h: number, depth: number): buffer +function Channels.gray8(plane: buffer, w: number, h: number, depth: number): buffer local n = w * h local out = bcreate(n) for i = 0, n - 1 do @@ -140611,7 +140626,7 @@ end end -- unmatte(rgba, n): Photoshop stores a transparent merged image matted with white (C * a + 255 * (1 - a)): undo it -@native function Channels.unmatte(rgba: buffer, n: number) +function Channels.unmatte(rgba: buffer, n: number) for i = 0, n - 1 do local o = i * 4 local a = readu8(rgba, o + 3) @@ -140627,7 +140642,7 @@ end end end -@native function Channels.matte(rgba: buffer, n: number): buffer +function Channels.matte(rgba: buffer, n: number): buffer local out = bcreate(n * 4) bcopy(out, 0, rgba, 0, n * 4) for i = 0, n - 1 do @@ -140644,7 +140659,7 @@ end end -- ------------------------------------------------------------------------------------------------ writer helpers -@native function Channels.packRow(src: buffer, o: number, n: number, out: buffer, d: number): number +function Channels.packRow(src: buffer, o: number, n: number, out: buffer, d: number): number local start = d local i = 0 while i < n do @@ -140676,7 +140691,7 @@ end return d - start end -@native function Channels.planes8(rgba: buffer, w: number, h: number): (buffer, buffer, buffer, buffer) +function Channels.planes8(rgba: buffer, w: number, h: number): (buffer, buffer, buffer, buffer) local n = w * h local r, g, b, a = bcreate(n), bcreate(n), bcreate(n), bcreate(n) if blen(rgba) < n * 4 then @@ -140692,7 +140707,7 @@ end return r, g, b, a end -@native function Channels.rleChannel(plane: buffer, w: number, h: number, psb: boolean): buffer +function Channels.rleChannel(plane: buffer, w: number, h: number, psb: boolean): buffer local cs = if psb then 4 else 2 local out = bcreate(h * cs + h * (w + w // 128 + 2)) local d = h * cs @@ -147995,7 +148010,7 @@ end return Ascii end -__FILES["model/fbx/Binary"] = @native function() +__FILES["model/fbx/Binary"] = function() -- model/fbx/Binary: the binary FBX 7.x node tree (32-bit node records before 7500, 64-bit from 7500), as documented by @@ -148017,7 +148032,7 @@ local readu8, readu32, readi32, readf32, readf64, readi16 = buffer.readu8, buffe local writef64 = buffer.writef64 -- signed 64-bit: a number when |v| < 2^53, else "L<16 hex digits>" -@native local function i64(b: buffer, p: number, asString: boolean): any +local function i64(b: buffer, p: number, asString: boolean): any local lo, hi = readu32(b, p), readu32(b, p + 4) if hi >= 0x80000000 then local v = (hi - 4294967296) * 4294967296 + lo @@ -148035,7 +148050,7 @@ Binary.i64 = i64 local ELEM: { [string]: number } = { f = 4, d = 8, l = 8, i = 4, b = 1, c = 1 } -@native local function toF64(t: string, src: buffer, p: number, n: number): buffer +local function toF64(t: string, src: buffer, p: number, n: number): buffer local out = buffer.create(n * 8) if t == "d" then buffer.copy(out, 0, src, p, n * 8) @@ -148060,7 +148075,7 @@ local ELEM: { [string]: number } = { f = 4, d = 8, l = 8, i = 4, b = 1, c = 1 } return out end -@native function Binary.parse(b: buffer, base: number, limit: number, opts: { maxBytes: number? }?): (Node?, any, number?) +function Binary.parse(b: buffer, base: number, limit: number, opts: { maxBytes: number? }?): (Node?, any, number?) local maxBytes = opts and opts.maxBytes or 2 ^ 30 if limit - base < 27 or buffer.readstring(b, base, 21) ~= MAGIC then return nil, "not a binary FBX", base @@ -148073,7 +148088,7 @@ end local head = if wide then 25 else 13 local total = 0 - @native local function props(p: number, n: number, stop: number): ({ any }?, any) + local function props(p: number, n: number, stop: number): ({ any }?, any) local out = table.create(math.min(n, 64)) for k = 1, n do if p >= stop then @@ -148151,7 +148166,7 @@ end return out, p end - @native local function node(p: number, stop: number, depth: number): (any, any, number?) + local function node(p: number, stop: number, depth: number): (any, any, number?) if p + head > stop then return nil, "truncated node record", p end @@ -148226,7 +148241,7 @@ end -- property; arrays over 32 elements are zlib-compressed type WNode = { name: string, props: { any }, children: { WNode }?, types: string? } -@native local function sizeHint(n: WNode): number +local function sizeHint(n: WNode): number local s = 32 + #n.name for _, v in n.props do if type(v) == "string" then @@ -148245,7 +148260,7 @@ type WNode = { name: string, props: { any }, children: { WNode }?, types: string return s end -@native function Binary.write(root: WNode, version: number?, compress: boolean?): buffer +function Binary.write(root: WNode, version: number?, compress: boolean?): buffer local zip = compress ~= false local ver = version or 7400 local wide = ver >= 7500 @@ -148253,7 +148268,7 @@ end local cap = sizeHint(root) + 256 local out = buffer.create(cap) local pos = 0 - @native local function ensure(n: number) + local function ensure(n: number) if pos + n > cap then while pos + n > cap do cap *= 2 @@ -148263,17 +148278,17 @@ end out = nb end end - @native local function u8(v: number) + local function u8(v: number) ensure(1) buffer.writeu8(out, pos, v) pos += 1 end - @native local function u32(v: number) + local function u32(v: number) ensure(4) buffer.writeu32(out, pos, v) pos += 4 end - @native local function i64w(v: number) + local function i64w(v: number) ensure(8) local hi = math.floor(v / 4294967296) local lo = v - hi * 4294967296 @@ -148281,18 +148296,18 @@ end buffer.writeu32(out, pos + 4, hi % 4294967296) pos += 8 end - @native local function str(s: string) + local function str(s: string) ensure(#s) buffer.writestring(out, pos, s) pos += #s end - @native local function bytes(src: buffer) + local function bytes(src: buffer) local n = buffer.len(src) ensure(n) buffer.copy(out, pos, src, 0, n) pos += n end - @native local function array(a: any) + local function array(a: any) local t, n, d = a.type, a.count, a.data local es = ELEM[t] or 8 local raw = buffer.create(n * es) @@ -148331,7 +148346,7 @@ end u32(n * es) bytes(raw) end - @native local function setOff(at: number, v: number) + local function setOff(at: number, v: number) if wide then buffer.writeu32(out, at, v % 4294967296) buffer.writeu32(out, at + 4, math.floor(v / 4294967296)) @@ -148339,12 +148354,12 @@ end buffer.writeu32(out, at, v) end end - @native local function nullRecord() + local function nullRecord() ensure(head) buffer.fill(out, pos, 0, head) pos += head end - @native local function node(n: WNode) + local function node(n: WNode) local start = pos ensure(head) buffer.fill(out, pos, 0, head) @@ -151075,7 +151090,7 @@ end return Gltf end -__FILES["model/gltf/Pack"] = @native function() +__FILES["model/gltf/Pack"] = function() -- model/gltf/Pack: the byte loops of glTF accessors (gather strided elements, scatter, sparse substitution); callers @@ -151084,7 +151099,7 @@ local Pack = {} local bcopy, readu8, readu16, readu32 = buffer.copy, buffer.readu8, buffer.readu16, buffer.readu32 -@native function Pack.gather(dst: buffer, src: buffer, off: number, count: number, elem: number, stride: number, cols: number, colBytes: number, colStride: number) +function Pack.gather(dst: buffer, src: buffer, off: number, count: number, elem: number, stride: number, cols: number, colBytes: number, colStride: number) if cols == 1 or colBytes == colStride then if stride == elem then bcopy(dst, 0, src, off, count * elem) @@ -151104,7 +151119,7 @@ local bcopy, readu8, readu16, readu32 = buffer.copy, buffer.readu8, buffer.readu end end -@native function Pack.scatter(dst: buffer, at: number, src: buffer, count: number, elem: number, stride: number, cols: number, colBytes: number, colStride: number) +function Pack.scatter(dst: buffer, at: number, src: buffer, count: number, elem: number, stride: number, cols: number, colBytes: number, colStride: number) if cols == 1 or colBytes == colStride then if stride == elem then bcopy(dst, at, src, 0, count * elem) @@ -151124,7 +151139,7 @@ end end end -@native function Pack.sparse(dst: buffer, count: number, elem: number, idx: buffer, idxOff: number, idxSize: number, values: buffer, valOff: number, n: number): boolean +function Pack.sparse(dst: buffer, count: number, elem: number, idx: buffer, idxOff: number, idxSize: number, values: buffer, valOff: number, n: number): boolean for k = 0, n - 1 do local i if idxSize == 1 then @@ -161424,7 +161439,7 @@ end return Ply end -__FILES["model/ply/Binary"] = @native function() +__FILES["model/ply/Binary"] = function() @@ -161442,11 +161457,11 @@ Binary.SIZE = { 1, 1, 2, 2, 4, 4, 4, 8 } local SIZE = Binary.SIZE local scratch = buffer.create(8) -@native local function swap16(v: number): number +local function swap16(v: number): number return rshift(v, 8) + band(v, 255) * 256 end -@native local function rd(b: buffer, q: number, code: number, be: boolean): number +local function rd(b: buffer, q: number, code: number, be: boolean): number if not be then if code == 7 then return readf32(b, q) @@ -161486,7 +161501,7 @@ end end Binary.rd = rd -@native local function wr(d: buffer, o: number, code: number, v: number) +local function wr(d: buffer, o: number, code: number, v: number) if code == 7 then writef32(d, o, v) elseif code == 6 then @@ -161507,7 +161522,7 @@ Binary.rd = rd end Binary.wr = wr -@native function Binary.put(d: buffer, o: number, code: number, v: number, be: boolean) +function Binary.put(d: buffer, o: number, code: number, v: number, be: boolean) if not be or code <= 2 then wr(d, o, code, v) return @@ -161523,7 +161538,7 @@ Binary.wr = wr end end -@native function Binary.fixed(b: buffer, p: number, n: number, rowSize: number, np: number, srcOff: { number }, code: { number }, be: boolean, dst: { buffer }, dOff: { number }, dStride: { number }, dCode: { number }) +function Binary.fixed(b: buffer, p: number, n: number, rowSize: number, np: number, srcOff: { number }, code: { number }, be: boolean, dst: { buffer }, dOff: { number }, dStride: { number }, dCode: { number }) for k = 1, np do local sc, dc, d = code[k], dCode[k], dst[k] local q0, o0, st = p + srcOff[k], dOff[k], dStride[k] @@ -161555,7 +161570,7 @@ end end end -@native function Binary.scan(b: buffer, p: number, limit: number, n: number, np: number, code: { number }, isList: { boolean }, countCode: { number }, be: boolean): (number, any) +function Binary.scan(b: buffer, p: number, limit: number, n: number, np: number, code: { number }, isList: { boolean }, countCode: { number }, be: boolean): (number, any) local totals = table.create(np, 0) local q = p for _ = 1, n do @@ -161586,7 +161601,7 @@ end return q, totals end -@native function Binary.rows(b: buffer, p: number, n: number, np: number, code: { number }, isList: { boolean }, countCode: { number }, be: boolean, dst: { buffer }, dOff: { number }, dStride: { number }, dCode: { number }, sizes: { buffer }, bound: { number }): (boolean, string?) +function Binary.rows(b: buffer, p: number, n: number, np: number, code: { number }, isList: { boolean }, countCode: { number }, be: boolean, dst: { buffer }, dOff: { number }, dStride: { number }, dCode: { number }, sizes: { buffer }, bound: { number }): (boolean, string?) local at = table.create(np, 0) local q = p for i = 0, n - 1 do @@ -165026,7 +165041,7 @@ end return RobloxMesh end -__FILES["model/robloxmesh/Parse"] = @native function() +__FILES["model/robloxmesh/Parse"] = function() @@ -165064,7 +165079,7 @@ type Record = { type Core = { numVerts: number, pos: buffer, nrm: buffer, uv: buffer, tan: buffer?, col: buffer?, numFaces: number, faces: buffer } type Limits = { maxVertices: number, maxFaces: number, core: ((b: buffer, off: number, len: number) -> (Core?, string?))? } -@native local function record(version: string): Record +local function record(version: string): Record return { version = version, numVerts = 0, @@ -165089,7 +165104,7 @@ type Limits = { maxVertices: number, maxFaces: number, core: ((b: buffer, off: n end -- ------------------------------------------------------------------------------------------------ version 1 -@native local function ascii(text: string, version: string, lim: Limits): (Record?, string?) +local function ascii(text: string, version: string, lim: Limits): (Record?, string?) local nf = tonumber(string.match(text, "^[^\n]*\n%s*(%d+)")) if not nf then return nil, "corrupt: no face count" @@ -165142,7 +165157,7 @@ end -- ------------------------------------------------------------------------------------------------ binary parts -- vertices of 36 / 40 bytes -@native local function vertices(b: buffer, p: number, n: number, vs: number, r: Record) +local function vertices(b: buffer, p: number, n: number, vs: number, r: Record) local pos, nrm, uv, tan = buffer.create(n * 12), buffer.create(n * 12), buffer.create(n * 8), buffer.create(n * 4) local col = if vs >= 40 then buffer.create(n * 4) else nil for i = 0, n - 1 do @@ -165159,7 +165174,7 @@ end r.numVerts = n end -@native local function faces(b: buffer, p: number, n: number, fs: number, r: Record): string? +local function faces(b: buffer, p: number, n: number, fs: number, r: Record): string? local out = buffer.create(n * 12) local nv = r.numVerts for i = 0, n - 1 do @@ -165175,7 +165190,7 @@ end return nil end -@native local function bones(b: buffer, p: number, n: number, names: string, r: Record) +local function bones(b: buffer, p: number, n: number, names: string, r: Record) for i = 0, n - 1 do local q = p + i * 60 local ni = readu32(b, q) @@ -165189,7 +165204,7 @@ end end end -@native local function subsets(b: buffer, p: number, n: number, r: Record) +local function subsets(b: buffer, p: number, n: number, r: Record) for i = 0, n - 1 do local q = p + i * 72 local count = math.min(readu32(b, q + 16), 26) @@ -165201,7 +165216,7 @@ end end end -@native local function lods(b: buffer, p: number, n: number, r: Record) +local function lods(b: buffer, p: number, n: number, r: Record) local out = table.create(n, 0) for i = 0, n - 1 do out[i + 1] = readu32(b, p + 4 * i) @@ -165210,7 +165225,7 @@ end end -- ------------------------------------------------------------------------------------------------ versions 2 .. 5 -@native local function classic(b: buffer, p: number, e: number, version: string, lim: Limits): (Record?, string?) +local function classic(b: buffer, p: number, e: number, version: string, lim: Limits): (Record?, string?) local r = record(version) local major = tonumber(string.sub(version, 1, 1)) or 0 if p + 12 > e then @@ -165312,7 +165327,7 @@ end end -- ------------------------------------------------------------------------------------------------ versions 6 / 7 -@native local function chunked(b: buffer, p: number, e: number, version: string, lim: Limits): (Record?, string?) +local function chunked(b: buffer, p: number, e: number, version: string, lim: Limits): (Record?, string?) local r = record(version) local core = false while p < e do @@ -165448,7 +165463,7 @@ end return r, nil end -@native function Parse.parse(b: buffer, p: number, e: number, lim: Limits): (Record?, string?) +function Parse.parse(b: buffer, p: number, e: number, lim: Limits): (Record?, string?) if e - p < 13 then return nil, "truncated: no version line" end @@ -165473,17 +165488,17 @@ end end -- packed tangent: signed bytes / 127 -@native local function snorm(v: number): number +local function snorm(v: number): number local x = if v >= 128 then v - 256 else v return math.clamp(x / 127, -1, 1) end -@native function Parse.tangent(tan: buffer, i: number): (number, number, number, number) +function Parse.tangent(tan: buffer, i: number): (number, number, number, number) return snorm(readu8(tan, i * 4)), snorm(readu8(tan, i * 4 + 1)), snorm(readu8(tan, i * 4 + 2)), snorm(readu8(tan, i * 4 + 3)) end return Parse end -__FILES["model/robloxmesh/Write"] = @native function() +__FILES["model/robloxmesh/Write"] = function() @@ -165494,7 +165509,7 @@ local Bytes = __include("core/Bytes") local Write = {} -@native local function vertex(w: Bytes.Writer, r: Parse.Record, i: number, colors: boolean) +local function vertex(w: Bytes.Writer, r: Parse.Record, i: number, colors: boolean) local p = w:reserve(if colors then 40 else 36) local b = w.buf buffer.copy(b, p, r.pos, i * 12, 12) @@ -165515,7 +165530,7 @@ local Write = {} w.pos = p + (if colors then 40 else 36) end -@native function Write.write(r: Parse.Record, version: string): buffer +function Write.write(r: Parse.Record, version: string): buffer local nv, nf = r.numVerts, r.numFaces local w = Bytes.writer(64 + nv * 48 + nf * 12) w:string("version " .. version .. "\n") @@ -167646,7 +167661,7 @@ end return Stl end -__FILES["model/stl/Decode"] = @native function() +__FILES["model/stl/Decode"] = function() @@ -167657,7 +167672,7 @@ local band, bor, rshift = bit32.band, bit32.bor, bit32.rshift local Decode = {} -@native function Decode.binary(b: buffer, p: number, n: number, pos: buffer, nrm: buffer, attr: buffer): number +function Decode.binary(b: buffer, p: number, n: number, pos: buffer, nrm: buffer, attr: buffer): number local any = 0 for i = 0, n - 1 do local q = p + i * 50 @@ -167688,13 +167703,13 @@ local Decode = {} return any end -@native local function x8(v: number): number +local function x8(v: number): number return (v * 255 + 15) // 31 end -- VisCAM: bit 15 set = valid, red in bits 10..14, blue in 0..4. Magics: bit 15 clear = the facet's own colour, -- red in bits 0..4, blue in 10..14. -@native function Decode.colors(attr: buffer, n: number, magics: boolean, dr: number, dg: number, db: number, da: number, out: buffer) +function Decode.colors(attr: buffer, n: number, magics: boolean, dr: number, dg: number, db: number, da: number, out: buffer) for i = 0, n - 1 do local w = readu16(attr, i * 2) local r, g, bl, al = dr, dg, db, da @@ -171708,7 +171723,7 @@ end return Vox end -__FILES["model/vox/Grid"] = @native function() +__FILES["model/vox/Grid"] = function() -- model/vox/Grid: XYZI records to and from a dense grid (cell x + sx * (y + sy * z); index 0 = empty). Never throws. @@ -171716,7 +171731,7 @@ local Grid = {} local readu8, writeu8 = buffer.readu8, buffer.writeu8 -@native function Grid.fill(dst: buffer, sx: number, sy: number, sz: number, src: buffer, off: number, n: number): number +function Grid.fill(dst: buffer, sx: number, sy: number, sz: number, src: buffer, off: number, n: number): number local skipped = 0 local sxy = sx * sy for k = 0, n - 1 do @@ -171731,7 +171746,7 @@ local readu8, writeu8 = buffer.readu8, buffer.writeu8 return skipped end -@native function Grid.count(data: buffer, cells: number): number +function Grid.count(data: buffer, cells: number): number local n = 0 for k = 0, cells - 1 do if readu8(data, k) ~= 0 then @@ -171742,7 +171757,7 @@ end end -- one XYZI record per non-empty cell (x fastest; sx, sy, sz <= 256) -@native function Grid.write(dst: buffer, at: number, data: buffer, sx: number, sy: number, sz: number): number +function Grid.write(dst: buffer, at: number, data: buffer, sx: number, sy: number, sz: number): number local p = at local k = 0 for z = 0, sz - 1 do @@ -174118,7 +174133,7 @@ end return It end -__FILES["music/it/Itsex"] = @native function() +__FILES["music/it/Itsex"] = function() -- music/it/Itsex: IT 2.14 / 2.15 (double-delta) sample decompression, from ITTECH.TXT: 0x8000-byte output blocks, each @@ -174127,7 +174142,7 @@ local readu8, readu16, writef32 = buffer.readu8, buffer.readu16, buffer.writef32 local Itsex = {} -@native function Itsex.decompress(buf: buffer, off: number, limit: number, frames: number, bits: number, it215: boolean): (buffer?, number | string) +function Itsex.decompress(buf: buffer, off: number, limit: number, frames: number, bits: number, it215: boolean): (buffer?, number | string) local out = buffer.create(frames * 4) local blockLen = if bits == 16 then 0x4000 else 0x8000 local topWidth = if bits == 16 then 17 else 9 @@ -174154,7 +174169,7 @@ local Itsex = {} local bytePos = bstart local bitBuf = 0 local bitCount = 0 - @native local function readBits(n: number): number + local function readBits(n: number): number while bitCount < n do if bytePos >= bend then return -1 @@ -179562,7 +179577,7 @@ end return ImageOps end -__FILES["ops/ImageOps/Kernels"] = @native function() +__FILES["ops/ImageOps/Kernels"] = function() @@ -179579,7 +179594,7 @@ K.ID = { rgba8 = 1, rgba16 = 2, rgbaf32 = 3, rgb8 = 4, gray8 = 5, gray16 = 6, gr 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 } -@native local function rd(b: buffer, o: number, kind: number): number +local function rd(b: buffer, o: number, kind: number): number if kind == 1 then return readu8(b, o) elseif kind == 2 then @@ -179588,7 +179603,7 @@ K.CHANNELS = { rgba8 = 4, rgba16 = 4, rgbaf32 = 4, rgb8 = 3, gray8 = 1, gray16 = return readf32(b, o) end -@native local function wr(b: buffer, o: number, kind: number, v: number) +local function wr(b: buffer, o: number, kind: number, v: number) if kind == 1 then writeu8(b, o, clamp(floor(v + 0.5), 0, 255)) elseif kind == 2 then @@ -179601,7 +179616,7 @@ end -- depth: 8 -> 0..255, 16 -> 0..65535, 0 -> float 0..1 local DEPTH = { 8, 16, 0, 8, 8, 16, 8, 8 } -@native local function depthConv(v: number, from: number, to: number): number +local function depthConv(v: number, from: number, to: number): number if from == to then return v end @@ -179626,14 +179641,14 @@ local DEPTH = { 8, 16, 0, 8, 8, 16, 8, 8 } end -- Pillow's L24 luma (19595 R + 38470 G + 7471 B + 0x8000) >> 16, in the source depth -@native local function luma(r: number, g: number, b: number, depth: number): number +local function luma(r: number, g: number, b: number, depth: number): number if depth == 0 then return (r * 19595 + g * 38470 + b * 7471) / 65536 end return (r * 19595 + g * 38470 + b * 7471 + 32768) // 65536 end -@native function K.convert(src: buffer, sf: number, dst: buffer, df: number, n: number) +function K.convert(src: buffer, sf: number, dst: buffer, df: number, n: number) 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 @@ -179708,7 +179723,7 @@ end end -- JPEG-style BT.601 full range -@native function K.rgbaToYuv(src: buffer, w: number, h: number, dst: buffer) +function K.rgbaToYuv(src: buffer, w: number, h: number, dst: buffer) local cw, ch = (w + 1) // 2, (h + 1) // 2 local uo, vo = w * h, w * h + cw * ch for i = 0, w * h - 1 do @@ -179742,7 +179757,7 @@ end end end -@native function K.yuvToRgba(src: buffer, w: number, h: number, dst: buffer) +function K.yuvToRgba(src: buffer, w: number, h: number, dst: buffer) local cw, ch = (w + 1) // 2, (h + 1) // 2 local uo, vo = w * h, w * h + cw * ch for y = 0, h - 1 do @@ -179761,7 +179776,7 @@ end local _ = ch end -@native function K.flip(src: buffer, dst: buffer, w: number, h: number, bpp: number, horizontal: boolean) +function K.flip(src: buffer, dst: buffer, w: number, h: number, bpp: number, horizontal: boolean) local stride = w * bpp if not horizontal then for y = 0, h - 1 do @@ -179778,7 +179793,7 @@ end end -- counter-clockwise quarter turns 1..3 -@native function K.rotate90(src: buffer, dst: buffer, w: number, h: number, bpp: number, turns: number) +function K.rotate90(src: buffer, dst: buffer, w: number, h: number, bpp: number, turns: number) for y = 0, h - 1 do for x = 0, w - 1 do local ox, oy, ow @@ -179799,7 +179814,7 @@ end end end -@native local function bilinearF(x: number): number +local function bilinearF(x: number): number if x < 0 then x = -x end @@ -179809,7 +179824,7 @@ end return 0 end -@native local function sinc(x: number): number +local function sinc(x: number): number if x == 0 then return 1 end @@ -179817,21 +179832,21 @@ end return math.sin(x) / x end -@native local function lanczosF(x: number): number +local function lanczosF(x: number): number if x > -3 and x < 3 then return sinc(x) * sinc(x / 3) end return 0 end -@native local function trunc(x: number): number +local function trunc(x: number): number return if x < 0 then math.ceil(x) else floor(x) end -- Pillow precompute_coeffs: per output index its first input index, tap count and weights (normalised) type Coeffs = { start: { number }, count: { number }, weights: { { number } } } -@native function K.coeffs(inSize: number, outSize: number, filter: string): Coeffs +function K.coeffs(inSize: number, outSize: number, filter: string): Coeffs local support0 = if filter == "lanczos" then 3 else 1 local f = if filter == "lanczos" then lanczosF else bilinearF local scale = inSize / outSize @@ -179860,7 +179875,7 @@ type Coeffs = { start: { number }, count: { number }, weights: { { number } } } return { start = start, count = count, weights = weights } end -@native function K.resamplePass(src: buffer, w: number, h: number, ch: number, kind: number, dst: buffer, outN: number, c: Coeffs, horizontal: boolean) +function K.resamplePass(src: buffer, w: number, h: number, ch: number, kind: number, dst: buffer, outN: number, c: Coeffs, horizontal: boolean) local start, count, weights = c.start, c.count, c.weights local size = kind local fixed = kind == 1 @@ -179928,7 +179943,7 @@ end end -- nearest: dst pixel (x, y) = src pixel (floor((x + 0.5) * w / ow), ...) -@native function K.nearest(src: buffer, w: number, h: number, bpp: number, dst: buffer, ow: number, oh: number) +function K.nearest(src: buffer, w: number, h: number, bpp: number, dst: buffer, ow: number, oh: number) local sx, sy = w / ow, h / oh for y = 0, oh - 1 do local iy = math.min(floor((y + 0.5) * sy), h - 1) @@ -179941,7 +179956,7 @@ end -- affine: dst pixel centres through m = { a, b, c, d, e, f } (xin = a x + b y + c), bilinear with clamped -- neighbours; centres outside the source -> zeros (Pillow) -@native function K.affine(src: buffer, w: number, h: number, ch: number, kind: number, dst: buffer, ow: number, oh: number, m: { number }) +function K.affine(src: buffer, w: number, h: number, ch: number, kind: number, dst: buffer, ow: number, oh: number, m: { number }) local a, b, c, d, e, f = m[1], m[2], m[3], m[4], m[5], m[6] local size = kind for y = 0, oh - 1 do @@ -179978,7 +179993,7 @@ end end -- Pillow's alpha_composite of src onto dst, in place -@native function K.overRgba8(dst: buffer, dw: number, src: buffer, sw: number, sx: number, sy: number, dx: number, dy: number, w: number, h: number, opacity: number) +function K.overRgba8(dst: buffer, dw: number, src: buffer, sw: number, sx: number, sy: number, dx: number, dy: number, w: number, h: number, opacity: number) for y = 0, h - 1 do for x = 0, w - 1 do local so = ((sy + y) * sw + sx + x) * 4 @@ -180007,7 +180022,7 @@ end end -- overFloat: straight-alpha "over" for rgba16 (kind 2) / rgbaf32 (kind 4); max = 65535 or 1 -@native function K.overFloat(dst: buffer, dw: number, src: buffer, sw: number, sx: number, sy: number, dx: number, dy: number, w: number, h: number, opacity: number, kind: number) +function K.overFloat(dst: buffer, dw: number, src: buffer, sw: number, sx: number, sy: number, dx: number, dy: number, w: number, h: number, opacity: number, kind: number) local max = if kind == 2 then 65535 else 1 local px = 4 * kind for y = 0, h - 1 do @@ -180030,13 +180045,13 @@ end end end -@native function K.copyRect(dst: buffer, dw: number, src: buffer, sw: number, sx: number, sy: number, dx: number, dy: number, w: number, h: number, bpp: number) +function K.copyRect(dst: buffer, dw: number, src: buffer, sw: number, sx: number, sy: number, dx: number, dy: number, w: number, h: number, bpp: number) for y = 0, h - 1 do buffer.copy(dst, ((dy + y) * dw + dx) * bpp, src, ((sy + y) * sw + sx) * bpp, w * bpp) end end -@native function K.premultiply(b: buffer, n: number, ch: number, kind: number, un: boolean) +function K.premultiply(b: buffer, n: number, ch: number, kind: number, un: boolean) local max = if kind == 1 then 255 elseif kind == 2 then 65535 else 1 local px = ch * kind for i = 0, n - 1 do @@ -181201,7 +181216,7 @@ end return MeshOps end -__FILES["ops/MeshOps/Greedy"] = @native function() +__FILES["ops/MeshOps/Greedy"] = function() -- ops/MeshOps/Greedy: greedy meshing of a dense voxel grid (one byte per cell, 0 = empty): for each axis and each @@ -181224,7 +181239,7 @@ type Out = { } -- vertex position = (cell corner + (ox, oy, oz)) * scale -@native function Greedy.run(data: buffer, sx: number, sy: number, sz: number, ox: number, oy: number, oz: number, scale: number): Out +function Greedy.run(data: buffer, sx: number, sy: number, sz: number, ox: number, oy: number, oz: number, scale: number): Out local cap = 1024 local pos = buffer.create(cap * 48) local nrm = buffer.create(cap * 48) @@ -181295,7 +181310,7 @@ type Out = { end if quads == cap then local ncap = cap * 2 - @native local function grow2(b: buffer, per: number): buffer + local function grow2(b: buffer, per: number): buffer local nb = buffer.create(ncap * per) buffer.copy(nb, 0, b, 0, cap * per) return nb @@ -191053,7 +191068,7 @@ end return Smk end -__FILES["video/smk/Audio"] = @native function() +__FILES["video/smk/Audio"] = function() @@ -191066,7 +191081,7 @@ local readu8, readi16 = buffer.readu8, buffer.readi16 local Audio = {} -@native function Audio.decode(d: buffer, channels: number, bits: number, packed: boolean): (number?, { number } | string) +function Audio.decode(d: buffer, channels: number, bits: number, packed: boolean): (number?, { number } | string) local n = buffer.len(d) if not packed then local bps = bits // 8 diff --git a/build/Rosetta.luau.linemap.json b/build/Rosetta.luau.linemap.json index f0d926f..f87d009 100644 --- a/build/Rosetta.luau.linemap.json +++ b/build/Rosetta.luau.linemap.json @@ -1,539 +1,539 @@ [ -[27, "src/Rosetta/init.luau"], -[871, "src/Rosetta/Registry.luau"], -[2980, "src/Rosetta/Types.luau"], -[4063, "src/Rosetta/archive/7z/init.luau"], -[4448, "src/Rosetta/archive/7z/Header.luau"], -[4975, "src/Rosetta/archive/adf/init.luau"], -[5257, "src/Rosetta/archive/applesingle/init.luau"], -[5443, "src/Rosetta/archive/ar/init.luau"], -[5846, "src/Rosetta/archive/arj/init.luau"], -[6056, "src/Rosetta/archive/binhex/init.luau"], -[6305, "src/Rosetta/archive/br/init.luau"], -[6380, "src/Rosetta/archive/bz2/init.luau"], -[6444, "src/Rosetta/archive/cab/init.luau"], -[6857, "src/Rosetta/archive/cab/Sum.luau"], -[6898, "src/Rosetta/archive/cpio/init.luau"], -[7066, "src/Rosetta/archive/d64/init.luau"], -[7480, "src/Rosetta/archive/fat/init.luau"], -[7602, "src/Rosetta/archive/grp/init.luau"], -[7716, "src/Rosetta/archive/gzip/init.luau"], -[7901, "src/Rosetta/archive/iso/init.luau"], -[7973, "src/Rosetta/archive/lha/init.luau"], -[8398, "src/Rosetta/archive/lz4/init.luau"], -[8742, "src/Rosetta/archive/macbinary/init.luau"], -[8940, "src/Rosetta/archive/mpq/init.luau"], -[9346, "src/Rosetta/archive/mpq/Crypt.luau"], -[9411, "src/Rosetta/archive/pak/init.luau"], -[9545, "src/Rosetta/archive/rpm/init.luau"], -[9869, "src/Rosetta/archive/tar/init.luau"], -[9987, "src/Rosetta/archive/uu/init.luau"], -[10257, "src/Rosetta/archive/vpk/init.luau"], -[10568, "src/Rosetta/archive/wad/init.luau"], -[11018, "src/Rosetta/archive/wad/Map.luau"], -[11448, "src/Rosetta/archive/wad/Picture.luau"], -[11550, "src/Rosetta/archive/xz/init.luau"], -[11650, "src/Rosetta/archive/yenc/init.luau"], -[11922, "src/Rosetta/archive/z/init.luau"], -[12018, "src/Rosetta/archive/zip/init.luau"], -[12237, "src/Rosetta/archive/zoo/init.luau"], -[12433, "src/Rosetta/archive/zst/init.luau"], -[12497, "src/Rosetta/audio/aac/init.luau"], -[12703, "src/Rosetta/audio/ac3/init.luau"], -[12849, "src/Rosetta/audio/adpcm/init.luau"], -[12994, "src/Rosetta/audio/adx/init.luau"], -[13225, "src/Rosetta/audio/aiff/init.luau"], -[13616, "src/Rosetta/audio/ape/init.luau"], -[13744, "src/Rosetta/audio/au/init.luau"], -[13905, "src/Rosetta/audio/brstm/init.luau"], -[14196, "src/Rosetta/audio/caf/init.luau"], -[14858, "src/Rosetta/audio/flac/init.luau"], -[15006, "src/Rosetta/audio/flac/Meta.luau"], -[15228, "src/Rosetta/audio/flac/Stream.luau"], -[15598, "src/Rosetta/audio/m4a/init.luau"], -[15932, "src/Rosetta/audio/mp3/init.luau"], -[16192, "src/Rosetta/audio/mp3/Index.luau"], -[16383, "src/Rosetta/audio/mp3/Stream.luau"], -[16610, "src/Rosetta/audio/mp3/Tags.luau"], -[16922, "src/Rosetta/audio/mpc/init.luau"], -[17016, "src/Rosetta/audio/opus/init.luau"], -[17394, "src/Rosetta/audio/opus/Encode.luau"], -[17505, "src/Rosetta/audio/qoa/init.luau"], -[17685, "src/Rosetta/audio/tta/init.luau"], -[17803, "src/Rosetta/audio/vag/init.luau"], -[18026, "src/Rosetta/audio/voc/init.luau"], -[18301, "src/Rosetta/audio/vorbis/init.luau"], -[18755, "src/Rosetta/audio/vorbis/Encode.luau"], -[19568, "src/Rosetta/audio/wav/init.luau"], -[20189, "src/Rosetta/audio/wav/Codecs.luau"], -[20355, "src/Rosetta/audio/wavpack/init.luau"], -[20562, "src/Rosetta/cad/step/init.luau"], -[20944, "src/Rosetta/cad/step/Brep.luau"], -[21179, "src/Rosetta/cad/step/Parse.luau"], -[21736, "src/Rosetta/cad/step/Write.luau"], -[21984, "src/Rosetta/codecs/audio/Aac/init.luau"], -[22303, "src/Rosetta/codecs/audio/Aac/Decode.luau"], -[23186, "src/Rosetta/codecs/audio/Aac/Tables.luau"], -[23521, "src/Rosetta/codecs/audio/Ac3/init.luau"], -[23680, "src/Rosetta/codecs/audio/Ac3/Decode.luau"], -[24565, "src/Rosetta/codecs/audio/Ac3/Tables.luau"], -[24666, "src/Rosetta/codecs/audio/Adpcm/init.luau"], -[25420, "src/Rosetta/codecs/audio/Adpcm/Decoder.luau"], -[25722, "src/Rosetta/codecs/audio/Alac/init.luau"], -[25956, "src/Rosetta/codecs/audio/Alac/Decode.luau"], -[26375, "src/Rosetta/codecs/audio/Alac/Encode.luau"], -[26787, "src/Rosetta/codecs/audio/Ape/init.luau"], -[27002, "src/Rosetta/codecs/audio/Ape/Decode.luau"], -[27763, "src/Rosetta/codecs/audio/ApeTag.luau"], -[27860, "src/Rosetta/codecs/audio/Flac/init.luau"], -[27871, "src/Rosetta/codecs/audio/Flac/Encode.luau"], -[28820, "src/Rosetta/codecs/audio/Flac/Frame.luau"], -[29417, "src/Rosetta/codecs/audio/Hively/init.luau"], -[29613, "src/Rosetta/codecs/audio/Hively/Load.luau"], -[29862, "src/Rosetta/codecs/audio/Hively/Player.luau"], -[30820, "src/Rosetta/codecs/audio/Hively/Tables.luau"], -[31039, "src/Rosetta/codecs/audio/Mdct/init.luau"], -[31223, "src/Rosetta/codecs/audio/Mdct/Fft.luau"], -[31432, "src/Rosetta/codecs/audio/MidiRender.luau"], -[31778, "src/Rosetta/codecs/audio/Mpa/init.luau"], -[31792, "src/Rosetta/codecs/audio/Mpa/Analysis.luau"], -[31851, "src/Rosetta/codecs/audio/Mpa/Core.luau"], -[33454, "src/Rosetta/codecs/audio/Mpa/EncTables.luau"], -[33746, "src/Rosetta/codecs/audio/Mpa/Encode2.luau"], -[34131, "src/Rosetta/codecs/audio/Mpa/Encode3.luau"], -[34772, "src/Rosetta/codecs/audio/Mpa/Header.luau"], -[34913, "src/Rosetta/codecs/audio/Mpa/Tables.luau"], -[35139, "src/Rosetta/codecs/audio/Musepack/init.luau"], -[35484, "src/Rosetta/codecs/audio/Musepack/Decode.luau"], -[36365, "src/Rosetta/codecs/audio/Musepack/Tables.luau"], -[36743, "src/Rosetta/codecs/audio/Opus/init.luau"], -[36757, "src/Rosetta/codecs/audio/Opus/Celt.luau"], -[38604, "src/Rosetta/codecs/audio/Opus/CeltEncoder.luau"], -[39669, "src/Rosetta/codecs/audio/Opus/CeltTables.luau"], -[39729, "src/Rosetta/codecs/audio/Opus/Decoder.luau"], -[40189, "src/Rosetta/codecs/audio/Opus/Mdct.luau"], -[40526, "src/Rosetta/codecs/audio/Opus/Packet.luau"], -[40759, "src/Rosetta/codecs/audio/Opus/Silk.luau"], -[42795, "src/Rosetta/codecs/audio/Opus/SilkTables.luau"], -[43169, "src/Rosetta/codecs/audio/Pcm/init.luau"], -[43432, "src/Rosetta/codecs/audio/Pcm/Convert.luau"], -[43729, "src/Rosetta/codecs/audio/Qoa/init.luau"], -[44011, "src/Rosetta/codecs/audio/Resample/init.luau"], -[44370, "src/Rosetta/codecs/audio/SoundFont/init.luau"], -[44424, "src/Rosetta/codecs/audio/SoundFont/Fallback.luau"], -[44567, "src/Rosetta/codecs/audio/SoundFont/Parse.luau"], -[45080, "src/Rosetta/codecs/audio/SoundFont/Synth.luau"], -[45861, "src/Rosetta/codecs/audio/Stream.luau"], -[46022, "src/Rosetta/codecs/audio/Tracker/init.luau"], -[46504, "src/Rosetta/codecs/audio/Tracker/Load.luau"], -[46782, "src/Rosetta/codecs/audio/Tracker/Mixer.luau"], -[46951, "src/Rosetta/codecs/audio/Tracker/Pcm.luau"], -[47079, "src/Rosetta/codecs/audio/Tracker/Player.luau"], -[49067, "src/Rosetta/codecs/audio/Tracker/Tables.luau"], -[49183, "src/Rosetta/codecs/audio/Tta/init.luau"], -[49300, "src/Rosetta/codecs/audio/Tta/Decode.luau"], -[49552, "src/Rosetta/codecs/audio/Vorbis/init.luau"], -[49565, "src/Rosetta/codecs/audio/Vorbis/Codebook.luau"], -[49949, "src/Rosetta/codecs/audio/Vorbis/Packet.luau"], -[50515, "src/Rosetta/codecs/audio/Vorbis/Setup.luau"], -[50936, "src/Rosetta/codecs/audio/Vorbis/Tables.luau"], -[50975, "src/Rosetta/codecs/audio/VorbisComment.luau"], -[51027, "src/Rosetta/codecs/audio/WavPack/init.luau"], -[51249, "src/Rosetta/codecs/audio/WavPack/Block.luau"], -[52704, "src/Rosetta/codecs/audio/WavPack/Tables.luau"], -[52767, "src/Rosetta/codecs/compress/Brotli/init.luau"], -[52854, "src/Rosetta/codecs/compress/Brotli/Decode.luau"], -[53823, "src/Rosetta/codecs/compress/Brotli/Static.luau"], -[54691, "src/Rosetta/codecs/compress/Bzip2/init.luau"], -[54739, "src/Rosetta/codecs/compress/Bzip2/Decode.luau"], -[55255, "src/Rosetta/codecs/compress/Deflate/init.luau"], -[55581, "src/Rosetta/codecs/compress/Deflate/Compress.luau"], -[56001, "src/Rosetta/codecs/compress/Deflate/Inflate.luau"], -[56436, "src/Rosetta/codecs/compress/Explode.luau"], -[56632, "src/Rosetta/codecs/compress/Lz4.luau"], -[56901, "src/Rosetta/codecs/compress/Lzh/init.luau"], -[57505, "src/Rosetta/codecs/compress/Lzma/init.luau"], -[58045, "src/Rosetta/codecs/compress/Lzma/Crc64.luau"], -[58083, "src/Rosetta/codecs/compress/Lzma/Decode.luau"], -[58556, "src/Rosetta/codecs/compress/Lzma/Filters.luau"], -[58732, "src/Rosetta/codecs/compress/Lzw/init.luau"], -[59000, "src/Rosetta/codecs/compress/Lzx.luau"], -[59434, "src/Rosetta/codecs/compress/PackBits.luau"], -[59524, "src/Rosetta/codecs/compress/Quantum.luau"], -[59761, "src/Rosetta/codecs/compress/UnixCompress.luau"], -[60065, "src/Rosetta/codecs/compress/Xxh32.luau"], -[60134, "src/Rosetta/codecs/compress/Zstd/init.luau"], -[60191, "src/Rosetta/codecs/compress/Zstd/Decode.luau"], -[61149, "src/Rosetta/codecs/compress/Zstd/Xxh64.luau"], -[61301, "src/Rosetta/codecs/entropy/Huffman.luau"], -[61583, "src/Rosetta/codecs/entropy/RangeCoder/init.luau"], -[61594, "src/Rosetta/codecs/entropy/RangeCoder/Decoder.luau"], -[61808, "src/Rosetta/codecs/entropy/RangeCoder/Encoder.luau"], -[62052, "src/Rosetta/codecs/font/Bitmap.luau"], -[62253, "src/Rosetta/codecs/font/Cff/init.luau"], -[62894, "src/Rosetta/codecs/font/GlyphNames.luau"], -[63044, "src/Rosetta/codecs/font/TrueType/init.luau"], -[63358, "src/Rosetta/codecs/font/TrueType/Glyf.luau"], -[63750, "src/Rosetta/codecs/font/TrueType/Tables.luau"], -[64252, "src/Rosetta/codecs/image/Bcn/init.luau"], -[64359, "src/Rosetta/codecs/image/Bcn/Decode.luau"], -[64848, "src/Rosetta/codecs/image/Bcn/Encode.luau"], -[65277, "src/Rosetta/codecs/image/Blend.luau"], -[65656, "src/Rosetta/codecs/image/Dct/init.luau"], -[66037, "src/Rosetta/codecs/image/Etc.luau"], -[66335, "src/Rosetta/codecs/image/Half.luau"], -[66404, "src/Rosetta/codecs/image/Jpeg/init.luau"], -[66758, "src/Rosetta/codecs/image/Jpeg/Arith.luau"], -[67166, "src/Rosetta/codecs/image/Jpeg/Color.luau"], -[67403, "src/Rosetta/codecs/image/Jpeg/Decode.luau"], -[68163, "src/Rosetta/codecs/image/Jpeg/Encode.luau"], -[69044, "src/Rosetta/codecs/image/Jpeg/Scan.luau"], -[69490, "src/Rosetta/codecs/image/Jpeg/Tables.luau"], -[69568, "src/Rosetta/codecs/image/Jpeg/Yuv.luau"], -[69635, "src/Rosetta/codecs/image/Pixels.luau"], -[69899, "src/Rosetta/codecs/image/Quantize/init.luau"], -[70358, "src/Rosetta/codecs/image/Raster.luau"], -[71055, "src/Rosetta/codecs/image/Texel.luau"], -[71428, "src/Rosetta/codecs/image/Texture.luau"], -[71573, "src/Rosetta/codecs/image/Vp8/init.luau"], -[71703, "src/Rosetta/codecs/image/Vp8/Decode.luau"], -[73659, "src/Rosetta/codecs/image/Vp8/Predict.luau"], -[73918, "src/Rosetta/codecs/image/Vp8/Tables.luau"], -[74167, "src/Rosetta/codecs/image/Vp8/Yuv.luau"], -[74286, "src/Rosetta/codecs/image/Vp8L/init.luau"], -[74390, "src/Rosetta/codecs/image/Vp8L/Decode.luau"], -[75243, "src/Rosetta/codecs/image/Vp8L/Encode.luau"], -[76195, "src/Rosetta/codecs/image/Yuv.luau"], -[76463, "src/Rosetta/codecs/model/Draco/init.luau"], -[76795, "src/Rosetta/codecs/model/Draco/Attributes.luau"], -[77264, "src/Rosetta/codecs/model/Draco/Connectivity.luau"], -[78453, "src/Rosetta/codecs/model/Draco/Int64.luau"], -[78602, "src/Rosetta/codecs/model/Draco/KdTree.luau"], -[78961, "src/Rosetta/codecs/model/Draco/Predict.luau"], -[79923, "src/Rosetta/codecs/model/Draco/Reader.luau"], -[80397, "src/Rosetta/codecs/model/Mat4.luau"], -[80656, "src/Rosetta/codecs/model/MeshFlatten.luau"], -[81184, "src/Rosetta/codecs/model/Minecraft/init.luau"], -[81736, "src/Rosetta/codecs/model/Minecraft/Colors.luau"], -[81815, "src/Rosetta/codecs/model/Minecraft/Legacy.luau"], -[81922, "src/Rosetta/codecs/model/Minecraft/Packed.luau"], -[82128, "src/Rosetta/codecs/model/Polygon.luau"], -[82362, "src/Rosetta/codecs/model/Rbx/init.luau"], -[82599, "src/Rosetta/codecs/model/Rbx/Binary.luau"], -[83353, "src/Rosetta/codecs/model/Rig.luau"], -[83596, "src/Rosetta/codecs/model/Sampler.luau"], -[83756, "src/Rosetta/codecs/model/Vrml/init.luau"], -[83904, "src/Rosetta/codecs/model/Vrml/Build.luau"], -[84478, "src/Rosetta/codecs/model/Vrml/Fields.luau"], -[84641, "src/Rosetta/codecs/model/Vrml/Geometry.luau"], -[85390, "src/Rosetta/codecs/model/Vrml/Parse.luau"], -[85912, "src/Rosetta/codecs/model/Vrml/Write.luau"], -[86639, "src/Rosetta/codecs/model/Vrml/Xml.luau"], -[86871, "src/Rosetta/codecs/text/Json/init.luau"], -[87140, "src/Rosetta/codecs/text/Json/Decode.luau"], -[87554, "src/Rosetta/codecs/text/Json/Encode.luau"], -[87856, "src/Rosetta/codecs/text/Nbt/init.luau"], -[88209, "src/Rosetta/codecs/text/Nbt/Binary.luau"], -[88901, "src/Rosetta/codecs/text/Nbt/Snbt.luau"], -[89541, "src/Rosetta/codecs/text/Nbt/Value.luau"], -[89779, "src/Rosetta/codecs/text/Text/init.luau"], -[89870, "src/Rosetta/codecs/text/Url/init.luau"], -[90075, "src/Rosetta/codecs/text/Xml/init.luau"], -[90478, "src/Rosetta/codecs/text/Xml/Parse.luau"], -[91218, "src/Rosetta/codecs/video/Dsp.luau"], -[91941, "src/Rosetta/codecs/video/H263/init.luau"], -[92097, "src/Rosetta/codecs/video/H263/Decoder.luau"], -[92955, "src/Rosetta/codecs/video/H263/Tables.luau"], -[93158, "src/Rosetta/codecs/video/H264/init.luau"], -[93531, "src/Rosetta/codecs/video/H264/Bitstream.luau"], -[93806, "src/Rosetta/codecs/video/H264/Cabac.luau"], -[94937, "src/Rosetta/codecs/video/H264/Cavlc.luau"], -[95705, "src/Rosetta/codecs/video/H264/Deblock.luau"], -[95963, "src/Rosetta/codecs/video/H264/Decoder.luau"], -[96972, "src/Rosetta/codecs/video/H264/Inter.luau"], -[97226, "src/Rosetta/codecs/video/H264/Intra.luau"], -[97633, "src/Rosetta/codecs/video/H264/Mb.luau"], -[98539, "src/Rosetta/codecs/video/H264/Params.luau"], -[98986, "src/Rosetta/codecs/video/H264/Slice.luau"], -[99237, "src/Rosetta/codecs/video/H264/Tables.luau"], -[99278, "src/Rosetta/codecs/video/H264/Transform.luau"], -[99443, "src/Rosetta/codecs/video/Legacy/init.luau"], -[99641, "src/Rosetta/codecs/video/Legacy/Cinepak.luau"], -[99938, "src/Rosetta/codecs/video/Legacy/Flic.luau"], -[100305, "src/Rosetta/codecs/video/Legacy/Msvideo1.luau"], -[100423, "src/Rosetta/codecs/video/Legacy/Picture.luau"], -[100531, "src/Rosetta/codecs/video/Legacy/QtRle.luau"], -[100804, "src/Rosetta/codecs/video/Legacy/Smacker.luau"], -[101199, "src/Rosetta/codecs/video/Legacy/Smc.luau"], -[101376, "src/Rosetta/codecs/video/Mpeg1/init.luau"], -[101388, "src/Rosetta/codecs/video/Mpeg2/init.luau"], -[101755, "src/Rosetta/codecs/video/Mpeg2/Decoder.luau"], -[103262, "src/Rosetta/codecs/video/Mpeg2/Tables.luau"], -[103401, "src/Rosetta/codecs/video/Mpeg2/Vlc.luau"], -[103539, "src/Rosetta/codecs/video/Theora/init.luau"], -[103802, "src/Rosetta/codecs/video/Theora/Decoder.luau"], -[105066, "src/Rosetta/codecs/video/Theora/Header.luau"], -[105429, "src/Rosetta/codecs/video/Video/init.luau"], -[105986, "src/Rosetta/codecs/video/Video/Source.luau"], -[106271, "src/Rosetta/containers/Archive.luau"], -[106538, "src/Rosetta/containers/AudioWrap.luau"], -[107041, "src/Rosetta/containers/Avi/init.luau"], -[107593, "src/Rosetta/containers/Chunks.luau"], -[107728, "src/Rosetta/containers/Cpio.luau"], -[108156, "src/Rosetta/containers/Demux.luau"], -[108431, "src/Rosetta/containers/Ebml/init.luau"], -[108744, "src/Rosetta/containers/Fat.luau"], -[109432, "src/Rosetta/containers/Iso9660.luau"], -[109937, "src/Rosetta/containers/IsoBmff/init.luau"], -[110107, "src/Rosetta/containers/IsoBmff/Box.luau"], -[110295, "src/Rosetta/containers/IsoBmff/Demux.luau"], -[111140, "src/Rosetta/containers/IsoBmff/Meta.luau"], -[111661, "src/Rosetta/containers/IsoBmff/Mux.luau"], -[112177, "src/Rosetta/containers/IsoBmff/QtPalette.luau"], -[112294, "src/Rosetta/containers/MacFile.luau"], -[112443, "src/Rosetta/containers/MpegEs.luau"], -[112609, "src/Rosetta/containers/MpegPs/init.luau"], -[112829, "src/Rosetta/containers/MpegTs/init.luau"], -[113621, "src/Rosetta/containers/Ogg/init.luau"], -[114046, "src/Rosetta/containers/Ogg/Mux.luau"], -[114241, "src/Rosetta/containers/Ogg/Page.luau"], -[114410, "src/Rosetta/containers/Riff/init.luau"], -[114727, "src/Rosetta/containers/Tar.luau"], -[115141, "src/Rosetta/containers/Zip/init.luau"], -[115773, "src/Rosetta/core/Adler32.luau"], -[115819, "src/Rosetta/core/Base64.luau"], -[115978, "src/Rosetta/core/Bits.luau"], -[116271, "src/Rosetta/core/Bytes.luau"], -[116798, "src/Rosetta/core/Crc16.luau"], -[116850, "src/Rosetta/core/Crc32.luau"], -[116962, "src/Rosetta/core/Err.luau"], -[117044, "src/Rosetta/core/Input.luau"], -[117120, "src/Rosetta/core/Md5.luau"], -[117279, "src/Rosetta/core/Sniff.luau"], -[117308, "src/Rosetta/data/cbor/init.luau"], -[117407, "src/Rosetta/data/cbor/Codec.luau"], -[117976, "src/Rosetta/data/csv/init.luau"], -[118288, "src/Rosetta/data/ini/init.luau"], -[118534, "src/Rosetta/data/json/init.luau"], -[118626, "src/Rosetta/data/msgpack/init.luau"], -[118715, "src/Rosetta/data/msgpack/Codec.luau"], -[119157, "src/Rosetta/data/nbt/init.luau"], -[119216, "src/Rosetta/data/plist/init.luau"], -[119522, "src/Rosetta/data/plist/Binary.luau"], -[119789, "src/Rosetta/data/snbt/init.luau"], -[119852, "src/Rosetta/data/toml/init.luau"], -[119919, "src/Rosetta/data/toml/Decode.luau"], -[120547, "src/Rosetta/data/toml/Encode.luau"], -[120756, "src/Rosetta/data/xml/init.luau"], -[120812, "src/Rosetta/data/yaml/init.luau"], -[120885, "src/Rosetta/data/yaml/Emit.luau"], -[121175, "src/Rosetta/data/yaml/Parse.luau"], -[122468, "src/Rosetta/font/bdf/init.luau"], -[122757, "src/Rosetta/font/bmfont/init.luau"], -[123184, "src/Rosetta/font/bmfont/Parse.luau"], -[123637, "src/Rosetta/font/eot/init.luau"], -[123869, "src/Rosetta/font/fon/init.luau"], -[124152, "src/Rosetta/font/hershey/init.luau"], -[124347, "src/Rosetta/font/pcf/init.luau"], -[124627, "src/Rosetta/font/psf/init.luau"], -[124947, "src/Rosetta/font/ttf/init.luau"], -[124998, "src/Rosetta/font/type1/init.luau"], -[125357, "src/Rosetta/font/type1/Charstring.luau"], -[125635, "src/Rosetta/font/woff/init.luau"], -[125767, "src/Rosetta/font/woff2/init.luau"], -[125824, "src/Rosetta/font/woff2/Rebuild.luau"], -[126364, "src/Rosetta/host/init.luau"], -[126409, "src/Rosetta/host/Love.luau"], -[126552, "src/Rosetta/host/LuaJIT.luau"], -[126602, "src/Rosetta/host/Luau.luau"], -[126625, "src/Rosetta/host/Roblox.luau"], -[126984, "src/Rosetta/image/ani/init.luau"], -[127164, "src/Rosetta/image/blp/init.luau"], -[127422, "src/Rosetta/image/bmp/init.luau"], -[127837, "src/Rosetta/image/dds/init.luau"], -[128320, "src/Rosetta/image/exr/init.luau"], -[129080, "src/Rosetta/image/exr/Codec.luau"], -[129191, "src/Rosetta/image/exr/Piz.luau"], -[129548, "src/Rosetta/image/gif/init.luau"], -[130064, "src/Rosetta/image/gif/Decode.luau"], -[130127, "src/Rosetta/image/hdr/init.luau"], -[130356, "src/Rosetta/image/hdr/Codec.luau"], -[130567, "src/Rosetta/image/icns/init.luau"], -[130898, "src/Rosetta/image/ico/init.luau"], -[131175, "src/Rosetta/image/ico/Dib.luau"], -[131270, "src/Rosetta/image/ilbm/init.luau"], -[131589, "src/Rosetta/image/jpeg/init.luau"], -[131725, "src/Rosetta/image/ktx/init.luau"], -[132385, "src/Rosetta/image/pcx/init.luau"], -[132649, "src/Rosetta/image/png/init.luau"], -[133229, "src/Rosetta/image/png/Apng.luau"], -[133309, "src/Rosetta/image/png/Decode.luau"], -[133549, "src/Rosetta/image/png/Encode.luau"], -[133704, "src/Rosetta/image/pnm/init.luau"], -[134082, "src/Rosetta/image/pnm/Codec.luau"], -[134359, "src/Rosetta/image/qoi/init.luau"], -[134481, "src/Rosetta/image/qoi/Codec.luau"], -[134631, "src/Rosetta/image/sgi/init.luau"], -[134916, "src/Rosetta/image/sunras/init.luau"], -[135162, "src/Rosetta/image/tga/init.luau"], -[135432, "src/Rosetta/image/tga/Codec.luau"], -[135584, "src/Rosetta/image/tiff/init.luau"], -[136411, "src/Rosetta/image/tiff/Pixels.luau"], -[136801, "src/Rosetta/image/tim/init.luau"], -[137043, "src/Rosetta/image/vtf/init.luau"], -[137278, "src/Rosetta/image/webp/init.luau"], -[137888, "src/Rosetta/image/webp/Alpha.luau"], -[137964, "src/Rosetta/image/webp/Anim.luau"], -[138119, "src/Rosetta/image/xbm/init.luau"], -[138280, "src/Rosetta/image/xpm/init.luau"], -[138548, "src/Rosetta/image/xpm/Names.luau"], -[138604, "src/Rosetta/layered/aseprite/init.luau"], -[139342, "src/Rosetta/layered/ora/init.luau"], -[139629, "src/Rosetta/layered/psd/init.luau"], -[140364, "src/Rosetta/layered/psd/Channels.luau"], -[140716, "src/Rosetta/model/3ds/init.luau"], -[140799, "src/Rosetta/model/3ds/Build.luau"], -[141446, "src/Rosetta/model/3ds/Read.luau"], -[141942, "src/Rosetta/model/3ds/Write.luau"], -[142747, "src/Rosetta/model/3mf/init.luau"], -[142829, "src/Rosetta/model/3mf/Read.luau"], -[143417, "src/Rosetta/model/3mf/Write.luau"], -[143822, "src/Rosetta/model/b3d/init.luau"], -[143877, "src/Rosetta/model/b3d/Read.luau"], -[144448, "src/Rosetta/model/bsp/init.luau"], -[144593, "src/Rosetta/model/bsp/Brush.luau"], -[144871, "src/Rosetta/model/bsp/Quake3.luau"], -[145126, "src/Rosetta/model/dae/init.luau"], -[145315, "src/Rosetta/model/dae/Math.luau"], -[145362, "src/Rosetta/model/dae/Read.luau"], -[147212, "src/Rosetta/model/dae/Write.luau"], -[147581, "src/Rosetta/model/fbx/init.luau"], -[147729, "src/Rosetta/model/fbx/Ascii.luau"], -[147999, "src/Rosetta/model/fbx/Binary.luau"], -[148454, "src/Rosetta/model/fbx/Read.luau"], -[149816, "src/Rosetta/model/fbx/Write.luau"], -[150801, "src/Rosetta/model/fbx/Xform.luau"], -[150842, "src/Rosetta/model/gltf/init.luau"], -[151079, "src/Rosetta/model/gltf/Pack.luau"], -[151148, "src/Rosetta/model/gltf/Read.luau"], -[151879, "src/Rosetta/model/gltf/Write.luau"], -[152559, "src/Rosetta/model/iqm/init.luau"], -[152635, "src/Rosetta/model/iqm/Read.luau"], -[152990, "src/Rosetta/model/iqm/Write.luau"], -[153677, "src/Rosetta/model/ldraw/init.luau"], -[153755, "src/Rosetta/model/ldraw/Colors.luau"], -[154073, "src/Rosetta/model/ldraw/Read.luau"], -[154650, "src/Rosetta/model/lwo/init.luau"], -[154726, "src/Rosetta/model/lwo/Build.luau"], -[155188, "src/Rosetta/model/lwo/Parse.luau"], -[155731, "src/Rosetta/model/mca/init.luau"], -[156073, "src/Rosetta/model/mca/Chunk.luau"], -[156206, "src/Rosetta/model/mca/Lz4Block.luau"], -[156276, "src/Rosetta/model/md2/init.luau"], -[156475, "src/Rosetta/model/md3/init.luau"], -[156703, "src/Rosetta/model/md5/init.luau"], -[156784, "src/Rosetta/model/md5/Read.luau"], -[157217, "src/Rosetta/model/mdl/init.luau"], -[157299, "src/Rosetta/model/mdl/HalfLife.luau"], -[157627, "src/Rosetta/model/mdl/Quake.luau"], -[157845, "src/Rosetta/model/ms3d/init.luau"], -[157917, "src/Rosetta/model/ms3d/Read.luau"], -[158363, "src/Rosetta/model/ms3d/Write.luau"], -[158832, "src/Rosetta/model/obj/init.luau"], -[159574, "src/Rosetta/model/obj/Mtl.luau"], -[159861, "src/Rosetta/model/off/init.luau"], -[160323, "src/Rosetta/model/ply/init.luau"], -[161428, "src/Rosetta/model/ply/Binary.luau"], -[161629, "src/Rosetta/model/pmx/init.luau"], -[161698, "src/Rosetta/model/pmx/Build.luau"], -[161994, "src/Rosetta/model/pmx/Pmd.luau"], -[162329, "src/Rosetta/model/pmx/Read.luau"], -[162733, "src/Rosetta/model/qb/init.luau"], -[163126, "src/Rosetta/model/rbxm/init.luau"], -[163718, "src/Rosetta/model/rbxmx/init.luau"], -[164371, "src/Rosetta/model/robloxmesh/init.luau"], -[165030, "src/Rosetta/model/robloxmesh/Parse.luau"], -[165487, "src/Rosetta/model/robloxmesh/Write.luau"], -[165596, "src/Rosetta/model/schematic/init.luau"], -[165917, "src/Rosetta/model/schematic/Common.luau"], -[166037, "src/Rosetta/model/schematic/Litematic.luau"], -[166248, "src/Rosetta/model/schematic/Mcedit.luau"], -[166492, "src/Rosetta/model/schematic/Sponge.luau"], -[166621, "src/Rosetta/model/smd/init.luau"], -[166688, "src/Rosetta/model/smd/Read.luau"], -[166957, "src/Rosetta/model/smd/Write.luau"], -[167200, "src/Rosetta/model/stl/init.luau"], -[167650, "src/Rosetta/model/stl/Decode.luau"], -[167724, "src/Rosetta/model/usda/init.luau"], -[167933, "src/Rosetta/model/usda/Build.luau"], -[169211, "src/Rosetta/model/usda/Parse.luau"], -[170009, "src/Rosetta/model/usda/Write.luau"], -[170826, "src/Rosetta/model/vox/init.luau"], -[171712, "src/Rosetta/model/vox/Grid.luau"], -[171769, "src/Rosetta/model/vrml/init.luau"], -[171835, "src/Rosetta/model/x/init.luau"], -[171965, "src/Rosetta/model/x/Build.luau"], -[172528, "src/Rosetta/model/x/Parse.luau"], -[172825, "src/Rosetta/model/x3d/init.luau"], -[172903, "src/Rosetta/music/669/init.luau"], -[173109, "src/Rosetta/music/ahx/init.luau"], -[173160, "src/Rosetta/music/far/init.luau"], -[173389, "src/Rosetta/music/hmp/init.luau"], -[173653, "src/Rosetta/music/hvl/init.luau"], -[173704, "src/Rosetta/music/it/init.luau"], -[174122, "src/Rosetta/music/it/Itsex.luau"], -[174238, "src/Rosetta/music/med/init.luau"], -[174885, "src/Rosetta/music/midi/init.luau"], -[175028, "src/Rosetta/music/midi/Smf.luau"], -[175439, "src/Rosetta/music/mod/init.luau"], -[175792, "src/Rosetta/music/mtm/init.luau"], -[176014, "src/Rosetta/music/mus/init.luau"], -[176171, "src/Rosetta/music/okt/init.luau"], -[176452, "src/Rosetta/music/ptm/init.luau"], -[176674, "src/Rosetta/music/s3m/init.luau"], -[176910, "src/Rosetta/music/sf2/init.luau"], -[176953, "src/Rosetta/music/stm/init.luau"], -[177184, "src/Rosetta/music/ult/init.luau"], -[177488, "src/Rosetta/music/umx/init.luau"], -[177704, "src/Rosetta/music/xm/init.luau"], -[178265, "src/Rosetta/music/xmi/init.luau"], -[178473, "src/Rosetta/ops/AudioOps.luau"], -[178922, "src/Rosetta/ops/ImageOps/init.luau"], -[179566, "src/Rosetta/ops/ImageOps/Kernels.luau"], -[180076, "src/Rosetta/ops/LayerOps.luau"], -[180169, "src/Rosetta/ops/MeshOps/init.luau"], -[181205, "src/Rosetta/ops/MeshOps/Greedy.luau"], -[181372, "src/Rosetta/ops/MusicOps.luau"], -[181720, "src/Rosetta/playlist/m3u/init.luau"], -[182073, "src/Rosetta/playlist/pls/init.luau"], -[182251, "src/Rosetta/playlist/xspf/init.luau"], -[182454, "src/Rosetta/subtitle/ass/init.luau"], -[182898, "src/Rosetta/subtitle/srt/init.luau"], -[183071, "src/Rosetta/subtitle/vtt/init.luau"], -[183274, "src/Rosetta/vector/svg/init.luau"], -[183360, "src/Rosetta/vector/svg/Parse.luau"], -[184106, "src/Rosetta/vector/svg/PathData.luau"], -[184474, "src/Rosetta/vector/svg/Render.luau"], -[184891, "src/Rosetta/vector/svg/Style.luau"], -[185263, "src/Rosetta/vector/svg/Write.luau"], -[185463, "src/Rosetta/vector/tiled/init.luau"], -[185643, "src/Rosetta/vector/tiled/Data.luau"], -[185794, "src/Rosetta/vector/tiled/Tmj.luau"], -[186425, "src/Rosetta/vector/tiled/Tmx.luau"], -[187037, "src/Rosetta/video/avi/init.luau"], -[187331, "src/Rosetta/video/fli/init.luau"], -[187482, "src/Rosetta/video/flv/init.luau"], -[187866, "src/Rosetta/video/flv/Amf.luau"], -[188024, "src/Rosetta/video/flv/Mux.luau"], -[188305, "src/Rosetta/video/h264/init.luau"], -[188444, "src/Rosetta/video/mkv/init.luau"], -[188600, "src/Rosetta/video/mkv/Mux.luau"], -[188879, "src/Rosetta/video/mkv/Parse.luau"], -[189600, "src/Rosetta/video/mp4/init.luau"], -[189928, "src/Rosetta/video/mpegps/init.luau"], -[190115, "src/Rosetta/video/mpegts/init.luau"], -[190353, "src/Rosetta/video/ogv/init.luau"], -[190748, "src/Rosetta/video/smk/init.luau"], -[191057, "src/Rosetta/video/smk/Audio.luau"], -[191177, "src/Rosetta/video/y4m/init.luau"] +[29, "src/Rosetta/init.luau"], +[873, "src/Rosetta/Registry.luau"], +[2982, "src/Rosetta/Types.luau"], +[4065, "src/Rosetta/archive/7z/init.luau"], +[4450, "src/Rosetta/archive/7z/Header.luau"], +[4977, "src/Rosetta/archive/adf/init.luau"], +[5259, "src/Rosetta/archive/applesingle/init.luau"], +[5445, "src/Rosetta/archive/ar/init.luau"], +[5848, "src/Rosetta/archive/arj/init.luau"], +[6058, "src/Rosetta/archive/binhex/init.luau"], +[6307, "src/Rosetta/archive/br/init.luau"], +[6382, "src/Rosetta/archive/bz2/init.luau"], +[6446, "src/Rosetta/archive/cab/init.luau"], +[6859, "src/Rosetta/archive/cab/Sum.luau"], +[6900, "src/Rosetta/archive/cpio/init.luau"], +[7068, "src/Rosetta/archive/d64/init.luau"], +[7482, "src/Rosetta/archive/fat/init.luau"], +[7604, "src/Rosetta/archive/grp/init.luau"], +[7718, "src/Rosetta/archive/gzip/init.luau"], +[7903, "src/Rosetta/archive/iso/init.luau"], +[7975, "src/Rosetta/archive/lha/init.luau"], +[8400, "src/Rosetta/archive/lz4/init.luau"], +[8744, "src/Rosetta/archive/macbinary/init.luau"], +[8942, "src/Rosetta/archive/mpq/init.luau"], +[9348, "src/Rosetta/archive/mpq/Crypt.luau"], +[9413, "src/Rosetta/archive/pak/init.luau"], +[9547, "src/Rosetta/archive/rpm/init.luau"], +[9871, "src/Rosetta/archive/tar/init.luau"], +[9989, "src/Rosetta/archive/uu/init.luau"], +[10259, "src/Rosetta/archive/vpk/init.luau"], +[10570, "src/Rosetta/archive/wad/init.luau"], +[11020, "src/Rosetta/archive/wad/Map.luau"], +[11450, "src/Rosetta/archive/wad/Picture.luau"], +[11552, "src/Rosetta/archive/xz/init.luau"], +[11652, "src/Rosetta/archive/yenc/init.luau"], +[11924, "src/Rosetta/archive/z/init.luau"], +[12020, "src/Rosetta/archive/zip/init.luau"], +[12239, "src/Rosetta/archive/zoo/init.luau"], +[12435, "src/Rosetta/archive/zst/init.luau"], +[12499, "src/Rosetta/audio/aac/init.luau"], +[12705, "src/Rosetta/audio/ac3/init.luau"], +[12851, "src/Rosetta/audio/adpcm/init.luau"], +[12996, "src/Rosetta/audio/adx/init.luau"], +[13227, "src/Rosetta/audio/aiff/init.luau"], +[13618, "src/Rosetta/audio/ape/init.luau"], +[13746, "src/Rosetta/audio/au/init.luau"], +[13907, "src/Rosetta/audio/brstm/init.luau"], +[14198, "src/Rosetta/audio/caf/init.luau"], +[14860, "src/Rosetta/audio/flac/init.luau"], +[15008, "src/Rosetta/audio/flac/Meta.luau"], +[15230, "src/Rosetta/audio/flac/Stream.luau"], +[15600, "src/Rosetta/audio/m4a/init.luau"], +[15934, "src/Rosetta/audio/mp3/init.luau"], +[16194, "src/Rosetta/audio/mp3/Index.luau"], +[16385, "src/Rosetta/audio/mp3/Stream.luau"], +[16612, "src/Rosetta/audio/mp3/Tags.luau"], +[16924, "src/Rosetta/audio/mpc/init.luau"], +[17018, "src/Rosetta/audio/opus/init.luau"], +[17396, "src/Rosetta/audio/opus/Encode.luau"], +[17507, "src/Rosetta/audio/qoa/init.luau"], +[17687, "src/Rosetta/audio/tta/init.luau"], +[17805, "src/Rosetta/audio/vag/init.luau"], +[18028, "src/Rosetta/audio/voc/init.luau"], +[18303, "src/Rosetta/audio/vorbis/init.luau"], +[18757, "src/Rosetta/audio/vorbis/Encode.luau"], +[19570, "src/Rosetta/audio/wav/init.luau"], +[20191, "src/Rosetta/audio/wav/Codecs.luau"], +[20357, "src/Rosetta/audio/wavpack/init.luau"], +[20564, "src/Rosetta/cad/step/init.luau"], +[20946, "src/Rosetta/cad/step/Brep.luau"], +[21181, "src/Rosetta/cad/step/Parse.luau"], +[21738, "src/Rosetta/cad/step/Write.luau"], +[21986, "src/Rosetta/codecs/audio/Aac/init.luau"], +[22305, "src/Rosetta/codecs/audio/Aac/Decode.luau"], +[23188, "src/Rosetta/codecs/audio/Aac/Tables.luau"], +[23523, "src/Rosetta/codecs/audio/Ac3/init.luau"], +[23682, "src/Rosetta/codecs/audio/Ac3/Decode.luau"], +[24567, "src/Rosetta/codecs/audio/Ac3/Tables.luau"], +[24668, "src/Rosetta/codecs/audio/Adpcm/init.luau"], +[25422, "src/Rosetta/codecs/audio/Adpcm/Decoder.luau"], +[25724, "src/Rosetta/codecs/audio/Alac/init.luau"], +[25958, "src/Rosetta/codecs/audio/Alac/Decode.luau"], +[26377, "src/Rosetta/codecs/audio/Alac/Encode.luau"], +[26789, "src/Rosetta/codecs/audio/Ape/init.luau"], +[27004, "src/Rosetta/codecs/audio/Ape/Decode.luau"], +[27765, "src/Rosetta/codecs/audio/ApeTag.luau"], +[27862, "src/Rosetta/codecs/audio/Flac/init.luau"], +[27873, "src/Rosetta/codecs/audio/Flac/Encode.luau"], +[28822, "src/Rosetta/codecs/audio/Flac/Frame.luau"], +[29419, "src/Rosetta/codecs/audio/Hively/init.luau"], +[29615, "src/Rosetta/codecs/audio/Hively/Load.luau"], +[29864, "src/Rosetta/codecs/audio/Hively/Player.luau"], +[30822, "src/Rosetta/codecs/audio/Hively/Tables.luau"], +[31041, "src/Rosetta/codecs/audio/Mdct/init.luau"], +[31225, "src/Rosetta/codecs/audio/Mdct/Fft.luau"], +[31434, "src/Rosetta/codecs/audio/MidiRender.luau"], +[31780, "src/Rosetta/codecs/audio/Mpa/init.luau"], +[31794, "src/Rosetta/codecs/audio/Mpa/Analysis.luau"], +[31853, "src/Rosetta/codecs/audio/Mpa/Core.luau"], +[33456, "src/Rosetta/codecs/audio/Mpa/EncTables.luau"], +[33748, "src/Rosetta/codecs/audio/Mpa/Encode2.luau"], +[34133, "src/Rosetta/codecs/audio/Mpa/Encode3.luau"], +[34774, "src/Rosetta/codecs/audio/Mpa/Header.luau"], +[34915, "src/Rosetta/codecs/audio/Mpa/Tables.luau"], +[35141, "src/Rosetta/codecs/audio/Musepack/init.luau"], +[35486, "src/Rosetta/codecs/audio/Musepack/Decode.luau"], +[36380, "src/Rosetta/codecs/audio/Musepack/Tables.luau"], +[36758, "src/Rosetta/codecs/audio/Opus/init.luau"], +[36772, "src/Rosetta/codecs/audio/Opus/Celt.luau"], +[38619, "src/Rosetta/codecs/audio/Opus/CeltEncoder.luau"], +[39684, "src/Rosetta/codecs/audio/Opus/CeltTables.luau"], +[39744, "src/Rosetta/codecs/audio/Opus/Decoder.luau"], +[40204, "src/Rosetta/codecs/audio/Opus/Mdct.luau"], +[40541, "src/Rosetta/codecs/audio/Opus/Packet.luau"], +[40774, "src/Rosetta/codecs/audio/Opus/Silk.luau"], +[42810, "src/Rosetta/codecs/audio/Opus/SilkTables.luau"], +[43184, "src/Rosetta/codecs/audio/Pcm/init.luau"], +[43447, "src/Rosetta/codecs/audio/Pcm/Convert.luau"], +[43744, "src/Rosetta/codecs/audio/Qoa/init.luau"], +[44026, "src/Rosetta/codecs/audio/Resample/init.luau"], +[44385, "src/Rosetta/codecs/audio/SoundFont/init.luau"], +[44439, "src/Rosetta/codecs/audio/SoundFont/Fallback.luau"], +[44582, "src/Rosetta/codecs/audio/SoundFont/Parse.luau"], +[45095, "src/Rosetta/codecs/audio/SoundFont/Synth.luau"], +[45876, "src/Rosetta/codecs/audio/Stream.luau"], +[46037, "src/Rosetta/codecs/audio/Tracker/init.luau"], +[46519, "src/Rosetta/codecs/audio/Tracker/Load.luau"], +[46797, "src/Rosetta/codecs/audio/Tracker/Mixer.luau"], +[46966, "src/Rosetta/codecs/audio/Tracker/Pcm.luau"], +[47094, "src/Rosetta/codecs/audio/Tracker/Player.luau"], +[49082, "src/Rosetta/codecs/audio/Tracker/Tables.luau"], +[49198, "src/Rosetta/codecs/audio/Tta/init.luau"], +[49315, "src/Rosetta/codecs/audio/Tta/Decode.luau"], +[49567, "src/Rosetta/codecs/audio/Vorbis/init.luau"], +[49580, "src/Rosetta/codecs/audio/Vorbis/Codebook.luau"], +[49964, "src/Rosetta/codecs/audio/Vorbis/Packet.luau"], +[50530, "src/Rosetta/codecs/audio/Vorbis/Setup.luau"], +[50951, "src/Rosetta/codecs/audio/Vorbis/Tables.luau"], +[50990, "src/Rosetta/codecs/audio/VorbisComment.luau"], +[51042, "src/Rosetta/codecs/audio/WavPack/init.luau"], +[51264, "src/Rosetta/codecs/audio/WavPack/Block.luau"], +[52719, "src/Rosetta/codecs/audio/WavPack/Tables.luau"], +[52782, "src/Rosetta/codecs/compress/Brotli/init.luau"], +[52869, "src/Rosetta/codecs/compress/Brotli/Decode.luau"], +[53838, "src/Rosetta/codecs/compress/Brotli/Static.luau"], +[54706, "src/Rosetta/codecs/compress/Bzip2/init.luau"], +[54754, "src/Rosetta/codecs/compress/Bzip2/Decode.luau"], +[55270, "src/Rosetta/codecs/compress/Deflate/init.luau"], +[55596, "src/Rosetta/codecs/compress/Deflate/Compress.luau"], +[56016, "src/Rosetta/codecs/compress/Deflate/Inflate.luau"], +[56451, "src/Rosetta/codecs/compress/Explode.luau"], +[56647, "src/Rosetta/codecs/compress/Lz4.luau"], +[56916, "src/Rosetta/codecs/compress/Lzh/init.luau"], +[57520, "src/Rosetta/codecs/compress/Lzma/init.luau"], +[58060, "src/Rosetta/codecs/compress/Lzma/Crc64.luau"], +[58098, "src/Rosetta/codecs/compress/Lzma/Decode.luau"], +[58571, "src/Rosetta/codecs/compress/Lzma/Filters.luau"], +[58747, "src/Rosetta/codecs/compress/Lzw/init.luau"], +[59015, "src/Rosetta/codecs/compress/Lzx.luau"], +[59449, "src/Rosetta/codecs/compress/PackBits.luau"], +[59539, "src/Rosetta/codecs/compress/Quantum.luau"], +[59776, "src/Rosetta/codecs/compress/UnixCompress.luau"], +[60080, "src/Rosetta/codecs/compress/Xxh32.luau"], +[60149, "src/Rosetta/codecs/compress/Zstd/init.luau"], +[60206, "src/Rosetta/codecs/compress/Zstd/Decode.luau"], +[61164, "src/Rosetta/codecs/compress/Zstd/Xxh64.luau"], +[61316, "src/Rosetta/codecs/entropy/Huffman.luau"], +[61598, "src/Rosetta/codecs/entropy/RangeCoder/init.luau"], +[61609, "src/Rosetta/codecs/entropy/RangeCoder/Decoder.luau"], +[61823, "src/Rosetta/codecs/entropy/RangeCoder/Encoder.luau"], +[62067, "src/Rosetta/codecs/font/Bitmap.luau"], +[62268, "src/Rosetta/codecs/font/Cff/init.luau"], +[62909, "src/Rosetta/codecs/font/GlyphNames.luau"], +[63059, "src/Rosetta/codecs/font/TrueType/init.luau"], +[63373, "src/Rosetta/codecs/font/TrueType/Glyf.luau"], +[63765, "src/Rosetta/codecs/font/TrueType/Tables.luau"], +[64267, "src/Rosetta/codecs/image/Bcn/init.luau"], +[64374, "src/Rosetta/codecs/image/Bcn/Decode.luau"], +[64863, "src/Rosetta/codecs/image/Bcn/Encode.luau"], +[65292, "src/Rosetta/codecs/image/Blend.luau"], +[65671, "src/Rosetta/codecs/image/Dct/init.luau"], +[66052, "src/Rosetta/codecs/image/Etc.luau"], +[66350, "src/Rosetta/codecs/image/Half.luau"], +[66419, "src/Rosetta/codecs/image/Jpeg/init.luau"], +[66773, "src/Rosetta/codecs/image/Jpeg/Arith.luau"], +[67181, "src/Rosetta/codecs/image/Jpeg/Color.luau"], +[67418, "src/Rosetta/codecs/image/Jpeg/Decode.luau"], +[68178, "src/Rosetta/codecs/image/Jpeg/Encode.luau"], +[69059, "src/Rosetta/codecs/image/Jpeg/Scan.luau"], +[69505, "src/Rosetta/codecs/image/Jpeg/Tables.luau"], +[69583, "src/Rosetta/codecs/image/Jpeg/Yuv.luau"], +[69650, "src/Rosetta/codecs/image/Pixels.luau"], +[69914, "src/Rosetta/codecs/image/Quantize/init.luau"], +[70373, "src/Rosetta/codecs/image/Raster.luau"], +[71070, "src/Rosetta/codecs/image/Texel.luau"], +[71443, "src/Rosetta/codecs/image/Texture.luau"], +[71588, "src/Rosetta/codecs/image/Vp8/init.luau"], +[71718, "src/Rosetta/codecs/image/Vp8/Decode.luau"], +[73674, "src/Rosetta/codecs/image/Vp8/Predict.luau"], +[73933, "src/Rosetta/codecs/image/Vp8/Tables.luau"], +[74182, "src/Rosetta/codecs/image/Vp8/Yuv.luau"], +[74301, "src/Rosetta/codecs/image/Vp8L/init.luau"], +[74405, "src/Rosetta/codecs/image/Vp8L/Decode.luau"], +[75258, "src/Rosetta/codecs/image/Vp8L/Encode.luau"], +[76210, "src/Rosetta/codecs/image/Yuv.luau"], +[76478, "src/Rosetta/codecs/model/Draco/init.luau"], +[76810, "src/Rosetta/codecs/model/Draco/Attributes.luau"], +[77279, "src/Rosetta/codecs/model/Draco/Connectivity.luau"], +[78468, "src/Rosetta/codecs/model/Draco/Int64.luau"], +[78617, "src/Rosetta/codecs/model/Draco/KdTree.luau"], +[78976, "src/Rosetta/codecs/model/Draco/Predict.luau"], +[79938, "src/Rosetta/codecs/model/Draco/Reader.luau"], +[80412, "src/Rosetta/codecs/model/Mat4.luau"], +[80671, "src/Rosetta/codecs/model/MeshFlatten.luau"], +[81199, "src/Rosetta/codecs/model/Minecraft/init.luau"], +[81751, "src/Rosetta/codecs/model/Minecraft/Colors.luau"], +[81830, "src/Rosetta/codecs/model/Minecraft/Legacy.luau"], +[81937, "src/Rosetta/codecs/model/Minecraft/Packed.luau"], +[82143, "src/Rosetta/codecs/model/Polygon.luau"], +[82377, "src/Rosetta/codecs/model/Rbx/init.luau"], +[82614, "src/Rosetta/codecs/model/Rbx/Binary.luau"], +[83368, "src/Rosetta/codecs/model/Rig.luau"], +[83611, "src/Rosetta/codecs/model/Sampler.luau"], +[83771, "src/Rosetta/codecs/model/Vrml/init.luau"], +[83919, "src/Rosetta/codecs/model/Vrml/Build.luau"], +[84493, "src/Rosetta/codecs/model/Vrml/Fields.luau"], +[84656, "src/Rosetta/codecs/model/Vrml/Geometry.luau"], +[85405, "src/Rosetta/codecs/model/Vrml/Parse.luau"], +[85927, "src/Rosetta/codecs/model/Vrml/Write.luau"], +[86654, "src/Rosetta/codecs/model/Vrml/Xml.luau"], +[86886, "src/Rosetta/codecs/text/Json/init.luau"], +[87155, "src/Rosetta/codecs/text/Json/Decode.luau"], +[87569, "src/Rosetta/codecs/text/Json/Encode.luau"], +[87871, "src/Rosetta/codecs/text/Nbt/init.luau"], +[88224, "src/Rosetta/codecs/text/Nbt/Binary.luau"], +[88916, "src/Rosetta/codecs/text/Nbt/Snbt.luau"], +[89556, "src/Rosetta/codecs/text/Nbt/Value.luau"], +[89794, "src/Rosetta/codecs/text/Text/init.luau"], +[89885, "src/Rosetta/codecs/text/Url/init.luau"], +[90090, "src/Rosetta/codecs/text/Xml/init.luau"], +[90493, "src/Rosetta/codecs/text/Xml/Parse.luau"], +[91233, "src/Rosetta/codecs/video/Dsp.luau"], +[91956, "src/Rosetta/codecs/video/H263/init.luau"], +[92112, "src/Rosetta/codecs/video/H263/Decoder.luau"], +[92970, "src/Rosetta/codecs/video/H263/Tables.luau"], +[93173, "src/Rosetta/codecs/video/H264/init.luau"], +[93546, "src/Rosetta/codecs/video/H264/Bitstream.luau"], +[93821, "src/Rosetta/codecs/video/H264/Cabac.luau"], +[94952, "src/Rosetta/codecs/video/H264/Cavlc.luau"], +[95720, "src/Rosetta/codecs/video/H264/Deblock.luau"], +[95978, "src/Rosetta/codecs/video/H264/Decoder.luau"], +[96987, "src/Rosetta/codecs/video/H264/Inter.luau"], +[97241, "src/Rosetta/codecs/video/H264/Intra.luau"], +[97648, "src/Rosetta/codecs/video/H264/Mb.luau"], +[98554, "src/Rosetta/codecs/video/H264/Params.luau"], +[99001, "src/Rosetta/codecs/video/H264/Slice.luau"], +[99252, "src/Rosetta/codecs/video/H264/Tables.luau"], +[99293, "src/Rosetta/codecs/video/H264/Transform.luau"], +[99458, "src/Rosetta/codecs/video/Legacy/init.luau"], +[99656, "src/Rosetta/codecs/video/Legacy/Cinepak.luau"], +[99953, "src/Rosetta/codecs/video/Legacy/Flic.luau"], +[100320, "src/Rosetta/codecs/video/Legacy/Msvideo1.luau"], +[100438, "src/Rosetta/codecs/video/Legacy/Picture.luau"], +[100546, "src/Rosetta/codecs/video/Legacy/QtRle.luau"], +[100819, "src/Rosetta/codecs/video/Legacy/Smacker.luau"], +[101214, "src/Rosetta/codecs/video/Legacy/Smc.luau"], +[101391, "src/Rosetta/codecs/video/Mpeg1/init.luau"], +[101403, "src/Rosetta/codecs/video/Mpeg2/init.luau"], +[101770, "src/Rosetta/codecs/video/Mpeg2/Decoder.luau"], +[103277, "src/Rosetta/codecs/video/Mpeg2/Tables.luau"], +[103416, "src/Rosetta/codecs/video/Mpeg2/Vlc.luau"], +[103554, "src/Rosetta/codecs/video/Theora/init.luau"], +[103817, "src/Rosetta/codecs/video/Theora/Decoder.luau"], +[105081, "src/Rosetta/codecs/video/Theora/Header.luau"], +[105444, "src/Rosetta/codecs/video/Video/init.luau"], +[106001, "src/Rosetta/codecs/video/Video/Source.luau"], +[106286, "src/Rosetta/containers/Archive.luau"], +[106553, "src/Rosetta/containers/AudioWrap.luau"], +[107056, "src/Rosetta/containers/Avi/init.luau"], +[107608, "src/Rosetta/containers/Chunks.luau"], +[107743, "src/Rosetta/containers/Cpio.luau"], +[108171, "src/Rosetta/containers/Demux.luau"], +[108446, "src/Rosetta/containers/Ebml/init.luau"], +[108759, "src/Rosetta/containers/Fat.luau"], +[109447, "src/Rosetta/containers/Iso9660.luau"], +[109952, "src/Rosetta/containers/IsoBmff/init.luau"], +[110122, "src/Rosetta/containers/IsoBmff/Box.luau"], +[110310, "src/Rosetta/containers/IsoBmff/Demux.luau"], +[111155, "src/Rosetta/containers/IsoBmff/Meta.luau"], +[111676, "src/Rosetta/containers/IsoBmff/Mux.luau"], +[112192, "src/Rosetta/containers/IsoBmff/QtPalette.luau"], +[112309, "src/Rosetta/containers/MacFile.luau"], +[112458, "src/Rosetta/containers/MpegEs.luau"], +[112624, "src/Rosetta/containers/MpegPs/init.luau"], +[112844, "src/Rosetta/containers/MpegTs/init.luau"], +[113636, "src/Rosetta/containers/Ogg/init.luau"], +[114061, "src/Rosetta/containers/Ogg/Mux.luau"], +[114256, "src/Rosetta/containers/Ogg/Page.luau"], +[114425, "src/Rosetta/containers/Riff/init.luau"], +[114742, "src/Rosetta/containers/Tar.luau"], +[115156, "src/Rosetta/containers/Zip/init.luau"], +[115788, "src/Rosetta/core/Adler32.luau"], +[115834, "src/Rosetta/core/Base64.luau"], +[115993, "src/Rosetta/core/Bits.luau"], +[116286, "src/Rosetta/core/Bytes.luau"], +[116813, "src/Rosetta/core/Crc16.luau"], +[116865, "src/Rosetta/core/Crc32.luau"], +[116977, "src/Rosetta/core/Err.luau"], +[117059, "src/Rosetta/core/Input.luau"], +[117135, "src/Rosetta/core/Md5.luau"], +[117294, "src/Rosetta/core/Sniff.luau"], +[117323, "src/Rosetta/data/cbor/init.luau"], +[117422, "src/Rosetta/data/cbor/Codec.luau"], +[117991, "src/Rosetta/data/csv/init.luau"], +[118303, "src/Rosetta/data/ini/init.luau"], +[118549, "src/Rosetta/data/json/init.luau"], +[118641, "src/Rosetta/data/msgpack/init.luau"], +[118730, "src/Rosetta/data/msgpack/Codec.luau"], +[119172, "src/Rosetta/data/nbt/init.luau"], +[119231, "src/Rosetta/data/plist/init.luau"], +[119537, "src/Rosetta/data/plist/Binary.luau"], +[119804, "src/Rosetta/data/snbt/init.luau"], +[119867, "src/Rosetta/data/toml/init.luau"], +[119934, "src/Rosetta/data/toml/Decode.luau"], +[120562, "src/Rosetta/data/toml/Encode.luau"], +[120771, "src/Rosetta/data/xml/init.luau"], +[120827, "src/Rosetta/data/yaml/init.luau"], +[120900, "src/Rosetta/data/yaml/Emit.luau"], +[121190, "src/Rosetta/data/yaml/Parse.luau"], +[122483, "src/Rosetta/font/bdf/init.luau"], +[122772, "src/Rosetta/font/bmfont/init.luau"], +[123199, "src/Rosetta/font/bmfont/Parse.luau"], +[123652, "src/Rosetta/font/eot/init.luau"], +[123884, "src/Rosetta/font/fon/init.luau"], +[124167, "src/Rosetta/font/hershey/init.luau"], +[124362, "src/Rosetta/font/pcf/init.luau"], +[124642, "src/Rosetta/font/psf/init.luau"], +[124962, "src/Rosetta/font/ttf/init.luau"], +[125013, "src/Rosetta/font/type1/init.luau"], +[125372, "src/Rosetta/font/type1/Charstring.luau"], +[125650, "src/Rosetta/font/woff/init.luau"], +[125782, "src/Rosetta/font/woff2/init.luau"], +[125839, "src/Rosetta/font/woff2/Rebuild.luau"], +[126379, "src/Rosetta/host/init.luau"], +[126424, "src/Rosetta/host/Love.luau"], +[126567, "src/Rosetta/host/LuaJIT.luau"], +[126617, "src/Rosetta/host/Luau.luau"], +[126640, "src/Rosetta/host/Roblox.luau"], +[126999, "src/Rosetta/image/ani/init.luau"], +[127179, "src/Rosetta/image/blp/init.luau"], +[127437, "src/Rosetta/image/bmp/init.luau"], +[127852, "src/Rosetta/image/dds/init.luau"], +[128335, "src/Rosetta/image/exr/init.luau"], +[129095, "src/Rosetta/image/exr/Codec.luau"], +[129206, "src/Rosetta/image/exr/Piz.luau"], +[129563, "src/Rosetta/image/gif/init.luau"], +[130079, "src/Rosetta/image/gif/Decode.luau"], +[130142, "src/Rosetta/image/hdr/init.luau"], +[130371, "src/Rosetta/image/hdr/Codec.luau"], +[130582, "src/Rosetta/image/icns/init.luau"], +[130913, "src/Rosetta/image/ico/init.luau"], +[131190, "src/Rosetta/image/ico/Dib.luau"], +[131285, "src/Rosetta/image/ilbm/init.luau"], +[131604, "src/Rosetta/image/jpeg/init.luau"], +[131740, "src/Rosetta/image/ktx/init.luau"], +[132400, "src/Rosetta/image/pcx/init.luau"], +[132664, "src/Rosetta/image/png/init.luau"], +[133244, "src/Rosetta/image/png/Apng.luau"], +[133324, "src/Rosetta/image/png/Decode.luau"], +[133564, "src/Rosetta/image/png/Encode.luau"], +[133719, "src/Rosetta/image/pnm/init.luau"], +[134097, "src/Rosetta/image/pnm/Codec.luau"], +[134374, "src/Rosetta/image/qoi/init.luau"], +[134496, "src/Rosetta/image/qoi/Codec.luau"], +[134646, "src/Rosetta/image/sgi/init.luau"], +[134931, "src/Rosetta/image/sunras/init.luau"], +[135177, "src/Rosetta/image/tga/init.luau"], +[135447, "src/Rosetta/image/tga/Codec.luau"], +[135599, "src/Rosetta/image/tiff/init.luau"], +[136426, "src/Rosetta/image/tiff/Pixels.luau"], +[136816, "src/Rosetta/image/tim/init.luau"], +[137058, "src/Rosetta/image/vtf/init.luau"], +[137293, "src/Rosetta/image/webp/init.luau"], +[137903, "src/Rosetta/image/webp/Alpha.luau"], +[137979, "src/Rosetta/image/webp/Anim.luau"], +[138134, "src/Rosetta/image/xbm/init.luau"], +[138295, "src/Rosetta/image/xpm/init.luau"], +[138563, "src/Rosetta/image/xpm/Names.luau"], +[138619, "src/Rosetta/layered/aseprite/init.luau"], +[139357, "src/Rosetta/layered/ora/init.luau"], +[139644, "src/Rosetta/layered/psd/init.luau"], +[140379, "src/Rosetta/layered/psd/Channels.luau"], +[140731, "src/Rosetta/model/3ds/init.luau"], +[140814, "src/Rosetta/model/3ds/Build.luau"], +[141461, "src/Rosetta/model/3ds/Read.luau"], +[141957, "src/Rosetta/model/3ds/Write.luau"], +[142762, "src/Rosetta/model/3mf/init.luau"], +[142844, "src/Rosetta/model/3mf/Read.luau"], +[143432, "src/Rosetta/model/3mf/Write.luau"], +[143837, "src/Rosetta/model/b3d/init.luau"], +[143892, "src/Rosetta/model/b3d/Read.luau"], +[144463, "src/Rosetta/model/bsp/init.luau"], +[144608, "src/Rosetta/model/bsp/Brush.luau"], +[144886, "src/Rosetta/model/bsp/Quake3.luau"], +[145141, "src/Rosetta/model/dae/init.luau"], +[145330, "src/Rosetta/model/dae/Math.luau"], +[145377, "src/Rosetta/model/dae/Read.luau"], +[147227, "src/Rosetta/model/dae/Write.luau"], +[147596, "src/Rosetta/model/fbx/init.luau"], +[147744, "src/Rosetta/model/fbx/Ascii.luau"], +[148014, "src/Rosetta/model/fbx/Binary.luau"], +[148469, "src/Rosetta/model/fbx/Read.luau"], +[149831, "src/Rosetta/model/fbx/Write.luau"], +[150816, "src/Rosetta/model/fbx/Xform.luau"], +[150857, "src/Rosetta/model/gltf/init.luau"], +[151094, "src/Rosetta/model/gltf/Pack.luau"], +[151163, "src/Rosetta/model/gltf/Read.luau"], +[151894, "src/Rosetta/model/gltf/Write.luau"], +[152574, "src/Rosetta/model/iqm/init.luau"], +[152650, "src/Rosetta/model/iqm/Read.luau"], +[153005, "src/Rosetta/model/iqm/Write.luau"], +[153692, "src/Rosetta/model/ldraw/init.luau"], +[153770, "src/Rosetta/model/ldraw/Colors.luau"], +[154088, "src/Rosetta/model/ldraw/Read.luau"], +[154665, "src/Rosetta/model/lwo/init.luau"], +[154741, "src/Rosetta/model/lwo/Build.luau"], +[155203, "src/Rosetta/model/lwo/Parse.luau"], +[155746, "src/Rosetta/model/mca/init.luau"], +[156088, "src/Rosetta/model/mca/Chunk.luau"], +[156221, "src/Rosetta/model/mca/Lz4Block.luau"], +[156291, "src/Rosetta/model/md2/init.luau"], +[156490, "src/Rosetta/model/md3/init.luau"], +[156718, "src/Rosetta/model/md5/init.luau"], +[156799, "src/Rosetta/model/md5/Read.luau"], +[157232, "src/Rosetta/model/mdl/init.luau"], +[157314, "src/Rosetta/model/mdl/HalfLife.luau"], +[157642, "src/Rosetta/model/mdl/Quake.luau"], +[157860, "src/Rosetta/model/ms3d/init.luau"], +[157932, "src/Rosetta/model/ms3d/Read.luau"], +[158378, "src/Rosetta/model/ms3d/Write.luau"], +[158847, "src/Rosetta/model/obj/init.luau"], +[159589, "src/Rosetta/model/obj/Mtl.luau"], +[159876, "src/Rosetta/model/off/init.luau"], +[160338, "src/Rosetta/model/ply/init.luau"], +[161443, "src/Rosetta/model/ply/Binary.luau"], +[161644, "src/Rosetta/model/pmx/init.luau"], +[161713, "src/Rosetta/model/pmx/Build.luau"], +[162009, "src/Rosetta/model/pmx/Pmd.luau"], +[162344, "src/Rosetta/model/pmx/Read.luau"], +[162748, "src/Rosetta/model/qb/init.luau"], +[163141, "src/Rosetta/model/rbxm/init.luau"], +[163733, "src/Rosetta/model/rbxmx/init.luau"], +[164386, "src/Rosetta/model/robloxmesh/init.luau"], +[165045, "src/Rosetta/model/robloxmesh/Parse.luau"], +[165502, "src/Rosetta/model/robloxmesh/Write.luau"], +[165611, "src/Rosetta/model/schematic/init.luau"], +[165932, "src/Rosetta/model/schematic/Common.luau"], +[166052, "src/Rosetta/model/schematic/Litematic.luau"], +[166263, "src/Rosetta/model/schematic/Mcedit.luau"], +[166507, "src/Rosetta/model/schematic/Sponge.luau"], +[166636, "src/Rosetta/model/smd/init.luau"], +[166703, "src/Rosetta/model/smd/Read.luau"], +[166972, "src/Rosetta/model/smd/Write.luau"], +[167215, "src/Rosetta/model/stl/init.luau"], +[167665, "src/Rosetta/model/stl/Decode.luau"], +[167739, "src/Rosetta/model/usda/init.luau"], +[167948, "src/Rosetta/model/usda/Build.luau"], +[169226, "src/Rosetta/model/usda/Parse.luau"], +[170024, "src/Rosetta/model/usda/Write.luau"], +[170841, "src/Rosetta/model/vox/init.luau"], +[171727, "src/Rosetta/model/vox/Grid.luau"], +[171784, "src/Rosetta/model/vrml/init.luau"], +[171850, "src/Rosetta/model/x/init.luau"], +[171980, "src/Rosetta/model/x/Build.luau"], +[172543, "src/Rosetta/model/x/Parse.luau"], +[172840, "src/Rosetta/model/x3d/init.luau"], +[172918, "src/Rosetta/music/669/init.luau"], +[173124, "src/Rosetta/music/ahx/init.luau"], +[173175, "src/Rosetta/music/far/init.luau"], +[173404, "src/Rosetta/music/hmp/init.luau"], +[173668, "src/Rosetta/music/hvl/init.luau"], +[173719, "src/Rosetta/music/it/init.luau"], +[174137, "src/Rosetta/music/it/Itsex.luau"], +[174253, "src/Rosetta/music/med/init.luau"], +[174900, "src/Rosetta/music/midi/init.luau"], +[175043, "src/Rosetta/music/midi/Smf.luau"], +[175454, "src/Rosetta/music/mod/init.luau"], +[175807, "src/Rosetta/music/mtm/init.luau"], +[176029, "src/Rosetta/music/mus/init.luau"], +[176186, "src/Rosetta/music/okt/init.luau"], +[176467, "src/Rosetta/music/ptm/init.luau"], +[176689, "src/Rosetta/music/s3m/init.luau"], +[176925, "src/Rosetta/music/sf2/init.luau"], +[176968, "src/Rosetta/music/stm/init.luau"], +[177199, "src/Rosetta/music/ult/init.luau"], +[177503, "src/Rosetta/music/umx/init.luau"], +[177719, "src/Rosetta/music/xm/init.luau"], +[178280, "src/Rosetta/music/xmi/init.luau"], +[178488, "src/Rosetta/ops/AudioOps.luau"], +[178937, "src/Rosetta/ops/ImageOps/init.luau"], +[179581, "src/Rosetta/ops/ImageOps/Kernels.luau"], +[180091, "src/Rosetta/ops/LayerOps.luau"], +[180184, "src/Rosetta/ops/MeshOps/init.luau"], +[181220, "src/Rosetta/ops/MeshOps/Greedy.luau"], +[181387, "src/Rosetta/ops/MusicOps.luau"], +[181735, "src/Rosetta/playlist/m3u/init.luau"], +[182088, "src/Rosetta/playlist/pls/init.luau"], +[182266, "src/Rosetta/playlist/xspf/init.luau"], +[182469, "src/Rosetta/subtitle/ass/init.luau"], +[182913, "src/Rosetta/subtitle/srt/init.luau"], +[183086, "src/Rosetta/subtitle/vtt/init.luau"], +[183289, "src/Rosetta/vector/svg/init.luau"], +[183375, "src/Rosetta/vector/svg/Parse.luau"], +[184121, "src/Rosetta/vector/svg/PathData.luau"], +[184489, "src/Rosetta/vector/svg/Render.luau"], +[184906, "src/Rosetta/vector/svg/Style.luau"], +[185278, "src/Rosetta/vector/svg/Write.luau"], +[185478, "src/Rosetta/vector/tiled/init.luau"], +[185658, "src/Rosetta/vector/tiled/Data.luau"], +[185809, "src/Rosetta/vector/tiled/Tmj.luau"], +[186440, "src/Rosetta/vector/tiled/Tmx.luau"], +[187052, "src/Rosetta/video/avi/init.luau"], +[187346, "src/Rosetta/video/fli/init.luau"], +[187497, "src/Rosetta/video/flv/init.luau"], +[187881, "src/Rosetta/video/flv/Amf.luau"], +[188039, "src/Rosetta/video/flv/Mux.luau"], +[188320, "src/Rosetta/video/h264/init.luau"], +[188459, "src/Rosetta/video/mkv/init.luau"], +[188615, "src/Rosetta/video/mkv/Mux.luau"], +[188894, "src/Rosetta/video/mkv/Parse.luau"], +[189615, "src/Rosetta/video/mp4/init.luau"], +[189943, "src/Rosetta/video/mpegps/init.luau"], +[190130, "src/Rosetta/video/mpegts/init.luau"], +[190368, "src/Rosetta/video/ogv/init.luau"], +[190763, "src/Rosetta/video/smk/init.luau"], +[191072, "src/Rosetta/video/smk/Audio.luau"], +[191192, "src/Rosetta/video/y4m/init.luau"] ] diff --git a/build/Rosetta.rbxm b/build/Rosetta.rbxm new file mode 100644 index 0000000..12ed8f5 Binary files /dev/null and b/build/Rosetta.rbxm differ diff --git a/build/Rosetta.rbxm.linemap.json b/build/Rosetta.rbxm.linemap.json new file mode 100644 index 0000000..57a34f2 --- /dev/null +++ b/build/Rosetta.rbxm.linemap.json @@ -0,0 +1,61 @@ +{ +"Core_1": [[8, "src/Rosetta/init.luau"], [852, "src/Rosetta/Registry.luau"], [2961, "src/Rosetta/Types.luau"], [4044, "src/Rosetta/codecs/audio/Adpcm/init.luau"], [4798, "src/Rosetta/codecs/image/Yuv.luau"], [5066, "src/Rosetta/codecs/model/Rbx/init.luau"], [5303, "src/Rosetta/codecs/video/Video/init.luau"], [5860, "src/Rosetta/containers/AudioWrap.luau"], [6363, "src/Rosetta/containers/Ogg/Mux.luau"], [6558, "src/Rosetta/containers/Ogg/Page.luau"], [6727, "src/Rosetta/core/Bytes.luau"], [7254, "src/Rosetta/core/Crc32.luau"], [7366, "src/Rosetta/core/Err.luau"], [7448, "src/Rosetta/core/Input.luau"], [7524, "src/Rosetta/host/init.luau"]], +"Core_2": [[8, "src/Rosetta/ops/ImageOps/init.luau"], [652, "src/Rosetta/ops/ImageOps/Kernels.luau"]], +"Mpeg2": [[8, "src/Rosetta/codecs/video/Dsp.luau"], [731, "src/Rosetta/codecs/video/Mpeg1/init.luau"], [743, "src/Rosetta/codecs/video/Mpeg2/init.luau"], [1110, "src/Rosetta/codecs/video/Mpeg2/Decoder.luau"], [2617, "src/Rosetta/codecs/video/Mpeg2/Tables.luau"], [2756, "src/Rosetta/codecs/video/Mpeg2/Vlc.luau"]], +"H263": [[8, "src/Rosetta/codecs/video/H263/init.luau"], [164, "src/Rosetta/codecs/video/H263/Decoder.luau"], [1022, "src/Rosetta/codecs/video/H263/Tables.luau"]], +"H264": [[8, "src/Rosetta/codecs/video/H264/init.luau"], [381, "src/Rosetta/codecs/video/H264/Bitstream.luau"], [656, "src/Rosetta/codecs/video/H264/Cabac.luau"], [1787, "src/Rosetta/codecs/video/H264/Cavlc.luau"], [2555, "src/Rosetta/codecs/video/H264/Deblock.luau"], [2813, "src/Rosetta/codecs/video/H264/Decoder.luau"], [3822, "src/Rosetta/codecs/video/H264/Inter.luau"], [4076, "src/Rosetta/codecs/video/H264/Intra.luau"], [4483, "src/Rosetta/codecs/video/H264/Mb.luau"], [5389, "src/Rosetta/codecs/video/H264/Params.luau"], [5836, "src/Rosetta/codecs/video/H264/Slice.luau"], [6087, "src/Rosetta/codecs/video/H264/Tables.luau"], [6128, "src/Rosetta/codecs/video/H264/Transform.luau"]], +"Theora": [[8, "src/Rosetta/codecs/video/Theora/init.luau"], [271, "src/Rosetta/codecs/video/Theora/Decoder.luau"], [1535, "src/Rosetta/codecs/video/Theora/Header.luau"]], +"Legacy": [[8, "src/Rosetta/codecs/video/Legacy/init.luau"], [206, "src/Rosetta/codecs/video/Legacy/Cinepak.luau"], [503, "src/Rosetta/codecs/video/Legacy/Flic.luau"], [870, "src/Rosetta/codecs/video/Legacy/Msvideo1.luau"], [988, "src/Rosetta/codecs/video/Legacy/Picture.luau"], [1096, "src/Rosetta/codecs/video/Legacy/QtRle.luau"], [1369, "src/Rosetta/codecs/video/Legacy/Smacker.luau"], [1764, "src/Rosetta/codecs/video/Legacy/Smc.luau"]], +"MpegTs": [[8, "src/Rosetta/containers/MpegEs.luau"], [174, "src/Rosetta/containers/MpegPs/init.luau"], [394, "src/Rosetta/containers/MpegTs/init.luau"]], +"Dct": [[8, "src/Rosetta/codecs/image/Dct/init.luau"]], +"Jpeg": [[8, "src/Rosetta/codecs/image/Jpeg/init.luau"], [362, "src/Rosetta/codecs/image/Jpeg/Arith.luau"], [770, "src/Rosetta/codecs/image/Jpeg/Color.luau"], [1007, "src/Rosetta/codecs/image/Jpeg/Decode.luau"], [1767, "src/Rosetta/codecs/image/Jpeg/Encode.luau"], [2648, "src/Rosetta/codecs/image/Jpeg/Scan.luau"], [3094, "src/Rosetta/codecs/image/Jpeg/Tables.luau"], [3172, "src/Rosetta/codecs/image/Jpeg/Yuv.luau"]], +"Vp8": [[8, "src/Rosetta/codecs/image/Vp8/init.luau"], [138, "src/Rosetta/codecs/image/Vp8/Decode.luau"], [2094, "src/Rosetta/codecs/image/Vp8/Predict.luau"], [2353, "src/Rosetta/codecs/image/Vp8/Tables.luau"], [2602, "src/Rosetta/codecs/image/Vp8/Yuv.luau"], [2721, "src/Rosetta/codecs/image/Vp8L/init.luau"], [2825, "src/Rosetta/codecs/image/Vp8L/Decode.luau"], [3678, "src/Rosetta/codecs/image/Vp8L/Encode.luau"]], +"Bcn": [[8, "src/Rosetta/codecs/image/Bcn/init.luau"], [115, "src/Rosetta/codecs/image/Bcn/Decode.luau"], [604, "src/Rosetta/codecs/image/Bcn/Encode.luau"]], +"Png": [[8, "src/Rosetta/image/png/init.luau"], [588, "src/Rosetta/image/png/Apng.luau"], [668, "src/Rosetta/image/png/Decode.luau"], [908, "src/Rosetta/image/png/Encode.luau"]], +"Deflate": [[8, "src/Rosetta/codecs/compress/Deflate/init.luau"], [334, "src/Rosetta/codecs/compress/Deflate/Compress.luau"], [754, "src/Rosetta/codecs/compress/Deflate/Inflate.luau"]], +"Brotli": [[8, "src/Rosetta/codecs/compress/Brotli/init.luau"], [95, "src/Rosetta/codecs/compress/Brotli/Decode.luau"], [1064, "src/Rosetta/codecs/compress/Brotli/Static.luau"]], +"Lzma": [[8, "src/Rosetta/codecs/compress/Lzma/init.luau"], [548, "src/Rosetta/codecs/compress/Lzma/Crc64.luau"], [586, "src/Rosetta/codecs/compress/Lzma/Decode.luau"], [1059, "src/Rosetta/codecs/compress/Lzma/Filters.luau"]], +"Zstd": [[8, "src/Rosetta/codecs/compress/Zstd/init.luau"], [65, "src/Rosetta/codecs/compress/Zstd/Decode.luau"], [1023, "src/Rosetta/codecs/compress/Zstd/Xxh64.luau"]], +"Mpa": [[8, "src/Rosetta/codecs/audio/Mpa/init.luau"], [22, "src/Rosetta/codecs/audio/Mpa/Analysis.luau"], [81, "src/Rosetta/codecs/audio/Mpa/Core.luau"], [1684, "src/Rosetta/codecs/audio/Mpa/EncTables.luau"], [1976, "src/Rosetta/codecs/audio/Mpa/Encode2.luau"], [2361, "src/Rosetta/codecs/audio/Mpa/Encode3.luau"], [3002, "src/Rosetta/codecs/audio/Mpa/Header.luau"], [3143, "src/Rosetta/codecs/audio/Mpa/Tables.luau"]], +"Opus": [[8, "src/Rosetta/codecs/audio/Opus/init.luau"], [22, "src/Rosetta/codecs/audio/Opus/Celt.luau"], [1869, "src/Rosetta/codecs/audio/Opus/CeltEncoder.luau"], [2934, "src/Rosetta/codecs/audio/Opus/CeltTables.luau"], [2994, "src/Rosetta/codecs/audio/Opus/Decoder.luau"], [3454, "src/Rosetta/codecs/audio/Opus/Mdct.luau"], [3791, "src/Rosetta/codecs/audio/Opus/Packet.luau"], [4024, "src/Rosetta/codecs/audio/Opus/Silk.luau"], [6060, "src/Rosetta/codecs/audio/Opus/SilkTables.luau"]], +"Vorbis": [[8, "src/Rosetta/codecs/audio/Vorbis/init.luau"], [21, "src/Rosetta/codecs/audio/Vorbis/Codebook.luau"], [405, "src/Rosetta/codecs/audio/Vorbis/Packet.luau"], [971, "src/Rosetta/codecs/audio/Vorbis/Setup.luau"], [1392, "src/Rosetta/codecs/audio/Vorbis/Tables.luau"]], +"Aac": [[8, "src/Rosetta/codecs/audio/Aac/init.luau"], [327, "src/Rosetta/codecs/audio/Aac/Decode.luau"], [1210, "src/Rosetta/codecs/audio/Aac/Tables.luau"]], +"Flac": [[8, "src/Rosetta/codecs/audio/Flac/init.luau"], [19, "src/Rosetta/codecs/audio/Flac/Encode.luau"], [968, "src/Rosetta/codecs/audio/Flac/Frame.luau"]], +"Musepack": [[8, "src/Rosetta/codecs/audio/Musepack/init.luau"], [353, "src/Rosetta/codecs/audio/Musepack/Decode.luau"], [1247, "src/Rosetta/codecs/audio/Musepack/Tables.luau"]], +"WavPack": [[8, "src/Rosetta/codecs/audio/WavPack/init.luau"], [230, "src/Rosetta/codecs/audio/WavPack/Block.luau"], [1685, "src/Rosetta/codecs/audio/WavPack/Tables.luau"]], +"Tracker": [[8, "src/Rosetta/codecs/audio/Tracker/init.luau"], [490, "src/Rosetta/codecs/audio/Tracker/Load.luau"], [768, "src/Rosetta/codecs/audio/Tracker/Mixer.luau"], [937, "src/Rosetta/codecs/audio/Tracker/Pcm.luau"], [1065, "src/Rosetta/codecs/audio/Tracker/Player.luau"], [3053, "src/Rosetta/codecs/audio/Tracker/Tables.luau"]], +"Hively": [[8, "src/Rosetta/codecs/audio/Hively/init.luau"], [204, "src/Rosetta/codecs/audio/Hively/Load.luau"], [453, "src/Rosetta/codecs/audio/Hively/Player.luau"], [1411, "src/Rosetta/codecs/audio/Hively/Tables.luau"]], +"SoundFont": [[8, "src/Rosetta/codecs/audio/SoundFont/init.luau"], [62, "src/Rosetta/codecs/audio/SoundFont/Fallback.luau"], [205, "src/Rosetta/codecs/audio/SoundFont/Parse.luau"], [718, "src/Rosetta/codecs/audio/SoundFont/Synth.luau"]], +"Draco": [[8, "src/Rosetta/codecs/model/Draco/init.luau"], [340, "src/Rosetta/codecs/model/Draco/Attributes.luau"], [809, "src/Rosetta/codecs/model/Draco/Connectivity.luau"], [1998, "src/Rosetta/codecs/model/Draco/Int64.luau"], [2147, "src/Rosetta/codecs/model/Draco/KdTree.luau"], [2506, "src/Rosetta/codecs/model/Draco/Predict.luau"], [3468, "src/Rosetta/codecs/model/Draco/Reader.luau"]], +"archive_1": [[8, "src/Rosetta/archive/7z/init.luau"], [393, "src/Rosetta/archive/7z/Header.luau"], [920, "src/Rosetta/archive/adf/init.luau"], [1202, "src/Rosetta/archive/applesingle/init.luau"], [1388, "src/Rosetta/archive/ar/init.luau"], [1791, "src/Rosetta/archive/arj/init.luau"], [2001, "src/Rosetta/archive/binhex/init.luau"], [2250, "src/Rosetta/archive/br/init.luau"], [2325, "src/Rosetta/archive/bz2/init.luau"], [2389, "src/Rosetta/archive/cab/init.luau"], [2802, "src/Rosetta/archive/cab/Sum.luau"], [2843, "src/Rosetta/archive/cpio/init.luau"], [3011, "src/Rosetta/archive/d64/init.luau"], [3425, "src/Rosetta/archive/fat/init.luau"], [3547, "src/Rosetta/archive/grp/init.luau"], [3661, "src/Rosetta/archive/gzip/init.luau"], [3846, "src/Rosetta/archive/iso/init.luau"], [3918, "src/Rosetta/archive/lha/init.luau"], [4343, "src/Rosetta/archive/lz4/init.luau"], [4687, "src/Rosetta/archive/macbinary/init.luau"], [4885, "src/Rosetta/archive/mpq/init.luau"], [5291, "src/Rosetta/archive/mpq/Crypt.luau"], [5356, "src/Rosetta/archive/pak/init.luau"], [5490, "src/Rosetta/archive/rpm/init.luau"], [5814, "src/Rosetta/archive/tar/init.luau"], [5932, "src/Rosetta/archive/uu/init.luau"], [6202, "src/Rosetta/archive/vpk/init.luau"], [6513, "src/Rosetta/archive/wad/init.luau"], [6963, "src/Rosetta/archive/wad/Map.luau"], [7393, "src/Rosetta/archive/wad/Picture.luau"], [7495, "src/Rosetta/archive/xz/init.luau"], [7595, "src/Rosetta/archive/yenc/init.luau"], [7867, "src/Rosetta/archive/z/init.luau"]], +"archive_2": [[8, "src/Rosetta/archive/zip/init.luau"], [227, "src/Rosetta/archive/zoo/init.luau"], [423, "src/Rosetta/archive/zst/init.luau"]], +"audio": [[8, "src/Rosetta/audio/aac/init.luau"], [214, "src/Rosetta/audio/ac3/init.luau"], [360, "src/Rosetta/audio/adpcm/init.luau"], [505, "src/Rosetta/audio/adx/init.luau"], [736, "src/Rosetta/audio/aiff/init.luau"], [1127, "src/Rosetta/audio/ape/init.luau"], [1255, "src/Rosetta/audio/au/init.luau"], [1416, "src/Rosetta/audio/brstm/init.luau"], [1707, "src/Rosetta/audio/caf/init.luau"], [2369, "src/Rosetta/audio/flac/init.luau"], [2517, "src/Rosetta/audio/flac/Meta.luau"], [2739, "src/Rosetta/audio/flac/Stream.luau"], [3109, "src/Rosetta/audio/m4a/init.luau"], [3443, "src/Rosetta/audio/mp3/init.luau"], [3703, "src/Rosetta/audio/mp3/Index.luau"], [3894, "src/Rosetta/audio/mp3/Stream.luau"], [4121, "src/Rosetta/audio/mp3/Tags.luau"], [4433, "src/Rosetta/audio/mpc/init.luau"], [4527, "src/Rosetta/audio/opus/init.luau"], [4905, "src/Rosetta/audio/opus/Encode.luau"], [5016, "src/Rosetta/audio/qoa/init.luau"], [5196, "src/Rosetta/audio/tta/init.luau"], [5314, "src/Rosetta/audio/vag/init.luau"], [5537, "src/Rosetta/audio/voc/init.luau"], [5812, "src/Rosetta/audio/vorbis/init.luau"], [6266, "src/Rosetta/audio/vorbis/Encode.luau"], [7079, "src/Rosetta/audio/wav/init.luau"], [7700, "src/Rosetta/audio/wav/Codecs.luau"], [7866, "src/Rosetta/audio/wavpack/init.luau"]], +"cad": [[8, "src/Rosetta/cad/step/init.luau"], [390, "src/Rosetta/cad/step/Brep.luau"], [625, "src/Rosetta/cad/step/Parse.luau"], [1182, "src/Rosetta/cad/step/Write.luau"]], +"codecs_audio": [[8, "src/Rosetta/codecs/audio/Ac3/init.luau"], [167, "src/Rosetta/codecs/audio/Ac3/Decode.luau"], [1052, "src/Rosetta/codecs/audio/Ac3/Tables.luau"], [1153, "src/Rosetta/codecs/audio/Adpcm/Decoder.luau"], [1455, "src/Rosetta/codecs/audio/Alac/init.luau"], [1689, "src/Rosetta/codecs/audio/Alac/Decode.luau"], [2108, "src/Rosetta/codecs/audio/Alac/Encode.luau"], [2520, "src/Rosetta/codecs/audio/Ape/init.luau"], [2735, "src/Rosetta/codecs/audio/Ape/Decode.luau"], [3496, "src/Rosetta/codecs/audio/ApeTag.luau"], [3593, "src/Rosetta/codecs/audio/Mdct/init.luau"], [3777, "src/Rosetta/codecs/audio/Mdct/Fft.luau"], [3986, "src/Rosetta/codecs/audio/MidiRender.luau"], [4332, "src/Rosetta/codecs/audio/Pcm/init.luau"], [4595, "src/Rosetta/codecs/audio/Pcm/Convert.luau"], [4892, "src/Rosetta/codecs/audio/Qoa/init.luau"], [5174, "src/Rosetta/codecs/audio/Resample/init.luau"], [5533, "src/Rosetta/codecs/audio/Stream.luau"], [5694, "src/Rosetta/codecs/audio/Tta/init.luau"], [5811, "src/Rosetta/codecs/audio/Tta/Decode.luau"], [6063, "src/Rosetta/codecs/audio/VorbisComment.luau"]], +"codecs_compress": [[8, "src/Rosetta/codecs/compress/Bzip2/init.luau"], [56, "src/Rosetta/codecs/compress/Bzip2/Decode.luau"], [572, "src/Rosetta/codecs/compress/Explode.luau"], [768, "src/Rosetta/codecs/compress/Lz4.luau"], [1037, "src/Rosetta/codecs/compress/Lzh/init.luau"], [1641, "src/Rosetta/codecs/compress/Lzw/init.luau"], [1909, "src/Rosetta/codecs/compress/Lzx.luau"], [2343, "src/Rosetta/codecs/compress/PackBits.luau"], [2433, "src/Rosetta/codecs/compress/Quantum.luau"], [2670, "src/Rosetta/codecs/compress/UnixCompress.luau"], [2974, "src/Rosetta/codecs/compress/Xxh32.luau"]], +"codecs_entropy": [[8, "src/Rosetta/codecs/entropy/Huffman.luau"], [290, "src/Rosetta/codecs/entropy/RangeCoder/init.luau"], [301, "src/Rosetta/codecs/entropy/RangeCoder/Decoder.luau"], [515, "src/Rosetta/codecs/entropy/RangeCoder/Encoder.luau"]], +"codecs_font": [[8, "src/Rosetta/codecs/font/Bitmap.luau"], [209, "src/Rosetta/codecs/font/Cff/init.luau"], [850, "src/Rosetta/codecs/font/GlyphNames.luau"], [1000, "src/Rosetta/codecs/font/TrueType/init.luau"], [1314, "src/Rosetta/codecs/font/TrueType/Glyf.luau"], [1706, "src/Rosetta/codecs/font/TrueType/Tables.luau"]], +"codecs_image": [[8, "src/Rosetta/codecs/image/Blend.luau"], [387, "src/Rosetta/codecs/image/Etc.luau"], [685, "src/Rosetta/codecs/image/Half.luau"], [754, "src/Rosetta/codecs/image/Pixels.luau"], [1018, "src/Rosetta/codecs/image/Quantize/init.luau"], [1477, "src/Rosetta/codecs/image/Raster.luau"], [2174, "src/Rosetta/codecs/image/Texel.luau"], [2547, "src/Rosetta/codecs/image/Texture.luau"]], +"codecs_model": [[8, "src/Rosetta/codecs/model/Mat4.luau"], [267, "src/Rosetta/codecs/model/MeshFlatten.luau"], [795, "src/Rosetta/codecs/model/Minecraft/init.luau"], [1347, "src/Rosetta/codecs/model/Minecraft/Colors.luau"], [1426, "src/Rosetta/codecs/model/Minecraft/Legacy.luau"], [1533, "src/Rosetta/codecs/model/Minecraft/Packed.luau"], [1739, "src/Rosetta/codecs/model/Polygon.luau"], [1973, "src/Rosetta/codecs/model/Rbx/Binary.luau"], [2727, "src/Rosetta/codecs/model/Rig.luau"], [2970, "src/Rosetta/codecs/model/Sampler.luau"], [3130, "src/Rosetta/codecs/model/Vrml/init.luau"], [3278, "src/Rosetta/codecs/model/Vrml/Build.luau"], [3852, "src/Rosetta/codecs/model/Vrml/Fields.luau"], [4015, "src/Rosetta/codecs/model/Vrml/Geometry.luau"], [4764, "src/Rosetta/codecs/model/Vrml/Parse.luau"], [5286, "src/Rosetta/codecs/model/Vrml/Write.luau"], [6013, "src/Rosetta/codecs/model/Vrml/Xml.luau"]], +"codecs_text": [[8, "src/Rosetta/codecs/text/Json/init.luau"], [277, "src/Rosetta/codecs/text/Json/Decode.luau"], [691, "src/Rosetta/codecs/text/Json/Encode.luau"], [993, "src/Rosetta/codecs/text/Nbt/init.luau"], [1346, "src/Rosetta/codecs/text/Nbt/Binary.luau"], [2038, "src/Rosetta/codecs/text/Nbt/Snbt.luau"], [2678, "src/Rosetta/codecs/text/Nbt/Value.luau"], [2916, "src/Rosetta/codecs/text/Text/init.luau"], [3007, "src/Rosetta/codecs/text/Url/init.luau"], [3212, "src/Rosetta/codecs/text/Xml/init.luau"], [3615, "src/Rosetta/codecs/text/Xml/Parse.luau"]], +"codecs_video": [[8, "src/Rosetta/codecs/video/Video/Source.luau"]], +"containers": [[8, "src/Rosetta/containers/Archive.luau"], [275, "src/Rosetta/containers/Avi/init.luau"], [827, "src/Rosetta/containers/Chunks.luau"], [962, "src/Rosetta/containers/Cpio.luau"], [1390, "src/Rosetta/containers/Demux.luau"], [1665, "src/Rosetta/containers/Ebml/init.luau"], [1978, "src/Rosetta/containers/Fat.luau"], [2666, "src/Rosetta/containers/Iso9660.luau"], [3171, "src/Rosetta/containers/IsoBmff/init.luau"], [3341, "src/Rosetta/containers/IsoBmff/Box.luau"], [3529, "src/Rosetta/containers/IsoBmff/Demux.luau"], [4374, "src/Rosetta/containers/IsoBmff/Meta.luau"], [4895, "src/Rosetta/containers/IsoBmff/Mux.luau"], [5411, "src/Rosetta/containers/IsoBmff/QtPalette.luau"], [5528, "src/Rosetta/containers/MacFile.luau"], [5677, "src/Rosetta/containers/Ogg/init.luau"], [6102, "src/Rosetta/containers/Riff/init.luau"], [6419, "src/Rosetta/containers/Tar.luau"], [6833, "src/Rosetta/containers/Zip/init.luau"]], +"core": [[8, "src/Rosetta/core/Adler32.luau"], [54, "src/Rosetta/core/Base64.luau"], [213, "src/Rosetta/core/Bits.luau"], [506, "src/Rosetta/core/Crc16.luau"], [558, "src/Rosetta/core/Md5.luau"], [717, "src/Rosetta/core/Sniff.luau"]], +"data": [[8, "src/Rosetta/data/cbor/init.luau"], [107, "src/Rosetta/data/cbor/Codec.luau"], [676, "src/Rosetta/data/csv/init.luau"], [988, "src/Rosetta/data/ini/init.luau"], [1234, "src/Rosetta/data/json/init.luau"], [1326, "src/Rosetta/data/msgpack/init.luau"], [1415, "src/Rosetta/data/msgpack/Codec.luau"], [1857, "src/Rosetta/data/nbt/init.luau"], [1916, "src/Rosetta/data/plist/init.luau"], [2222, "src/Rosetta/data/plist/Binary.luau"], [2489, "src/Rosetta/data/snbt/init.luau"], [2552, "src/Rosetta/data/toml/init.luau"], [2619, "src/Rosetta/data/toml/Decode.luau"], [3247, "src/Rosetta/data/toml/Encode.luau"], [3456, "src/Rosetta/data/xml/init.luau"], [3512, "src/Rosetta/data/yaml/init.luau"], [3585, "src/Rosetta/data/yaml/Emit.luau"], [3875, "src/Rosetta/data/yaml/Parse.luau"]], +"font": [[8, "src/Rosetta/font/bdf/init.luau"], [297, "src/Rosetta/font/bmfont/init.luau"], [724, "src/Rosetta/font/bmfont/Parse.luau"], [1177, "src/Rosetta/font/eot/init.luau"], [1409, "src/Rosetta/font/fon/init.luau"], [1692, "src/Rosetta/font/hershey/init.luau"], [1887, "src/Rosetta/font/pcf/init.luau"], [2167, "src/Rosetta/font/psf/init.luau"], [2487, "src/Rosetta/font/ttf/init.luau"], [2538, "src/Rosetta/font/type1/init.luau"], [2897, "src/Rosetta/font/type1/Charstring.luau"], [3175, "src/Rosetta/font/woff/init.luau"], [3307, "src/Rosetta/font/woff2/init.luau"], [3364, "src/Rosetta/font/woff2/Rebuild.luau"]], +"host": [[8, "src/Rosetta/host/Love.luau"], [151, "src/Rosetta/host/LuaJIT.luau"], [201, "src/Rosetta/host/Luau.luau"], [224, "src/Rosetta/host/Roblox.luau"]], +"image_1": [[8, "src/Rosetta/image/ani/init.luau"], [188, "src/Rosetta/image/blp/init.luau"], [446, "src/Rosetta/image/bmp/init.luau"], [861, "src/Rosetta/image/dds/init.luau"], [1344, "src/Rosetta/image/exr/init.luau"], [2104, "src/Rosetta/image/exr/Codec.luau"], [2215, "src/Rosetta/image/exr/Piz.luau"], [2572, "src/Rosetta/image/gif/init.luau"], [3088, "src/Rosetta/image/gif/Decode.luau"], [3151, "src/Rosetta/image/hdr/init.luau"], [3380, "src/Rosetta/image/hdr/Codec.luau"], [3591, "src/Rosetta/image/icns/init.luau"], [3922, "src/Rosetta/image/ico/init.luau"], [4199, "src/Rosetta/image/ico/Dib.luau"], [4294, "src/Rosetta/image/ilbm/init.luau"], [4613, "src/Rosetta/image/jpeg/init.luau"], [4749, "src/Rosetta/image/ktx/init.luau"], [5409, "src/Rosetta/image/pcx/init.luau"], [5673, "src/Rosetta/image/pnm/init.luau"], [6051, "src/Rosetta/image/pnm/Codec.luau"], [6328, "src/Rosetta/image/qoi/init.luau"], [6450, "src/Rosetta/image/qoi/Codec.luau"], [6600, "src/Rosetta/image/sgi/init.luau"], [6885, "src/Rosetta/image/sunras/init.luau"], [7131, "src/Rosetta/image/tga/init.luau"], [7401, "src/Rosetta/image/tga/Codec.luau"]], +"image_2": [[8, "src/Rosetta/image/tiff/init.luau"], [835, "src/Rosetta/image/tiff/Pixels.luau"], [1225, "src/Rosetta/image/tim/init.luau"], [1467, "src/Rosetta/image/vtf/init.luau"], [1702, "src/Rosetta/image/webp/init.luau"], [2312, "src/Rosetta/image/webp/Alpha.luau"], [2388, "src/Rosetta/image/webp/Anim.luau"], [2543, "src/Rosetta/image/xbm/init.luau"], [2704, "src/Rosetta/image/xpm/init.luau"], [2972, "src/Rosetta/image/xpm/Names.luau"]], +"layered": [[8, "src/Rosetta/layered/aseprite/init.luau"], [746, "src/Rosetta/layered/ora/init.luau"], [1033, "src/Rosetta/layered/psd/init.luau"], [1768, "src/Rosetta/layered/psd/Channels.luau"]], +"model_1": [[8, "src/Rosetta/model/3ds/init.luau"], [91, "src/Rosetta/model/3ds/Build.luau"], [738, "src/Rosetta/model/3ds/Read.luau"], [1234, "src/Rosetta/model/3ds/Write.luau"], [2039, "src/Rosetta/model/3mf/init.luau"], [2121, "src/Rosetta/model/3mf/Read.luau"], [2709, "src/Rosetta/model/3mf/Write.luau"], [3114, "src/Rosetta/model/b3d/init.luau"], [3169, "src/Rosetta/model/b3d/Read.luau"], [3740, "src/Rosetta/model/bsp/init.luau"], [3885, "src/Rosetta/model/bsp/Brush.luau"], [4163, "src/Rosetta/model/bsp/Quake3.luau"], [4418, "src/Rosetta/model/dae/init.luau"], [4607, "src/Rosetta/model/dae/Math.luau"], [4654, "src/Rosetta/model/dae/Read.luau"], [6504, "src/Rosetta/model/dae/Write.luau"], [6873, "src/Rosetta/model/fbx/init.luau"], [7021, "src/Rosetta/model/fbx/Ascii.luau"], [7291, "src/Rosetta/model/fbx/Binary.luau"]], +"model_2": [[8, "src/Rosetta/model/fbx/Read.luau"], [1370, "src/Rosetta/model/fbx/Write.luau"], [2355, "src/Rosetta/model/fbx/Xform.luau"], [2396, "src/Rosetta/model/gltf/init.luau"], [2633, "src/Rosetta/model/gltf/Pack.luau"], [2702, "src/Rosetta/model/gltf/Read.luau"], [3433, "src/Rosetta/model/gltf/Write.luau"], [4113, "src/Rosetta/model/iqm/init.luau"], [4189, "src/Rosetta/model/iqm/Read.luau"], [4544, "src/Rosetta/model/iqm/Write.luau"], [5231, "src/Rosetta/model/ldraw/init.luau"], [5309, "src/Rosetta/model/ldraw/Colors.luau"], [5627, "src/Rosetta/model/ldraw/Read.luau"], [6204, "src/Rosetta/model/lwo/init.luau"], [6280, "src/Rosetta/model/lwo/Build.luau"], [6742, "src/Rosetta/model/lwo/Parse.luau"]], +"model_3": [[8, "src/Rosetta/model/mca/init.luau"], [350, "src/Rosetta/model/mca/Chunk.luau"], [483, "src/Rosetta/model/mca/Lz4Block.luau"], [553, "src/Rosetta/model/md2/init.luau"], [752, "src/Rosetta/model/md3/init.luau"], [980, "src/Rosetta/model/md5/init.luau"], [1061, "src/Rosetta/model/md5/Read.luau"], [1494, "src/Rosetta/model/mdl/init.luau"], [1576, "src/Rosetta/model/mdl/HalfLife.luau"], [1904, "src/Rosetta/model/mdl/Quake.luau"], [2122, "src/Rosetta/model/ms3d/init.luau"], [2194, "src/Rosetta/model/ms3d/Read.luau"], [2640, "src/Rosetta/model/ms3d/Write.luau"], [3109, "src/Rosetta/model/obj/init.luau"], [3851, "src/Rosetta/model/obj/Mtl.luau"], [4138, "src/Rosetta/model/off/init.luau"], [4600, "src/Rosetta/model/ply/init.luau"], [5705, "src/Rosetta/model/ply/Binary.luau"], [5906, "src/Rosetta/model/pmx/init.luau"], [5975, "src/Rosetta/model/pmx/Build.luau"], [6271, "src/Rosetta/model/pmx/Pmd.luau"], [6606, "src/Rosetta/model/pmx/Read.luau"], [7010, "src/Rosetta/model/qb/init.luau"]], +"model_4": [[8, "src/Rosetta/model/rbxm/init.luau"], [600, "src/Rosetta/model/rbxmx/init.luau"], [1253, "src/Rosetta/model/robloxmesh/init.luau"], [1912, "src/Rosetta/model/robloxmesh/Parse.luau"], [2369, "src/Rosetta/model/robloxmesh/Write.luau"], [2478, "src/Rosetta/model/schematic/init.luau"], [2799, "src/Rosetta/model/schematic/Common.luau"], [2919, "src/Rosetta/model/schematic/Litematic.luau"], [3130, "src/Rosetta/model/schematic/Mcedit.luau"], [3374, "src/Rosetta/model/schematic/Sponge.luau"], [3503, "src/Rosetta/model/smd/init.luau"], [3570, "src/Rosetta/model/smd/Read.luau"], [3839, "src/Rosetta/model/smd/Write.luau"], [4082, "src/Rosetta/model/stl/init.luau"], [4532, "src/Rosetta/model/stl/Decode.luau"], [4606, "src/Rosetta/model/usda/init.luau"], [4815, "src/Rosetta/model/usda/Build.luau"], [6093, "src/Rosetta/model/usda/Parse.luau"], [6891, "src/Rosetta/model/usda/Write.luau"]], +"model_5": [[8, "src/Rosetta/model/vox/init.luau"], [894, "src/Rosetta/model/vox/Grid.luau"], [951, "src/Rosetta/model/vrml/init.luau"], [1017, "src/Rosetta/model/x/init.luau"], [1147, "src/Rosetta/model/x/Build.luau"], [1710, "src/Rosetta/model/x/Parse.luau"], [2007, "src/Rosetta/model/x3d/init.luau"]], +"music": [[8, "src/Rosetta/music/669/init.luau"], [214, "src/Rosetta/music/ahx/init.luau"], [265, "src/Rosetta/music/far/init.luau"], [494, "src/Rosetta/music/hmp/init.luau"], [758, "src/Rosetta/music/hvl/init.luau"], [809, "src/Rosetta/music/it/init.luau"], [1227, "src/Rosetta/music/it/Itsex.luau"], [1343, "src/Rosetta/music/med/init.luau"], [1990, "src/Rosetta/music/midi/init.luau"], [2133, "src/Rosetta/music/midi/Smf.luau"], [2544, "src/Rosetta/music/mod/init.luau"], [2897, "src/Rosetta/music/mtm/init.luau"], [3119, "src/Rosetta/music/mus/init.luau"], [3276, "src/Rosetta/music/okt/init.luau"], [3557, "src/Rosetta/music/ptm/init.luau"], [3779, "src/Rosetta/music/s3m/init.luau"], [4015, "src/Rosetta/music/sf2/init.luau"], [4058, "src/Rosetta/music/stm/init.luau"], [4289, "src/Rosetta/music/ult/init.luau"], [4593, "src/Rosetta/music/umx/init.luau"], [4809, "src/Rosetta/music/xm/init.luau"], [5370, "src/Rosetta/music/xmi/init.luau"]], +"ops": [[8, "src/Rosetta/ops/AudioOps.luau"], [457, "src/Rosetta/ops/LayerOps.luau"], [550, "src/Rosetta/ops/MeshOps/init.luau"], [1586, "src/Rosetta/ops/MeshOps/Greedy.luau"], [1753, "src/Rosetta/ops/MusicOps.luau"]], +"playlist": [[8, "src/Rosetta/playlist/m3u/init.luau"], [361, "src/Rosetta/playlist/pls/init.luau"], [539, "src/Rosetta/playlist/xspf/init.luau"]], +"subtitle": [[8, "src/Rosetta/subtitle/ass/init.luau"], [452, "src/Rosetta/subtitle/srt/init.luau"], [625, "src/Rosetta/subtitle/vtt/init.luau"]], +"vector": [[8, "src/Rosetta/vector/svg/init.luau"], [94, "src/Rosetta/vector/svg/Parse.luau"], [840, "src/Rosetta/vector/svg/PathData.luau"], [1208, "src/Rosetta/vector/svg/Render.luau"], [1625, "src/Rosetta/vector/svg/Style.luau"], [1997, "src/Rosetta/vector/svg/Write.luau"], [2197, "src/Rosetta/vector/tiled/init.luau"], [2377, "src/Rosetta/vector/tiled/Data.luau"], [2528, "src/Rosetta/vector/tiled/Tmj.luau"], [3159, "src/Rosetta/vector/tiled/Tmx.luau"]], +"video": [[8, "src/Rosetta/video/avi/init.luau"], [302, "src/Rosetta/video/fli/init.luau"], [453, "src/Rosetta/video/flv/init.luau"], [837, "src/Rosetta/video/flv/Amf.luau"], [995, "src/Rosetta/video/flv/Mux.luau"], [1276, "src/Rosetta/video/h264/init.luau"], [1415, "src/Rosetta/video/mkv/init.luau"], [1571, "src/Rosetta/video/mkv/Mux.luau"], [1850, "src/Rosetta/video/mkv/Parse.luau"], [2571, "src/Rosetta/video/mp4/init.luau"], [2899, "src/Rosetta/video/mpegps/init.luau"], [3086, "src/Rosetta/video/mpegts/init.luau"], [3324, "src/Rosetta/video/ogv/init.luau"], [3719, "src/Rosetta/video/smk/init.luau"], [4028, "src/Rosetta/video/smk/Audio.luau"], [4148, "src/Rosetta/video/y4m/init.luau"]] +} diff --git a/build/Rosetta.rbxmx b/build/Rosetta.rbxmx new file mode 100644 index 0000000..8d8c01e --- /dev/null +++ b/build/Rosetta.rbxmx @@ -0,0 +1,192732 @@ + + + + Rosetta + --!optimize 2 +--!nocheck +-- rosetta (Roblox, native build): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- The root of build/Rosetta.rbxm: the module registry; each child ModuleScript is a chunk of modules, +-- required on the first include of one of them. require(this) -> the API (docs/API.md); +-- Rosetta._internal("codecs/video/Mpeg1") -> an internal module. +local __CHUNK = { + [""] = "Core_1", + ["Registry"] = "Core_1", + ["Types"] = "Core_1", + ["codecs/audio/Adpcm"] = "Core_1", + ["codecs/image/Yuv"] = "Core_1", + ["codecs/model/Rbx"] = "Core_1", + ["codecs/video/Video"] = "Core_1", + ["containers/AudioWrap"] = "Core_1", + ["containers/Ogg/Mux"] = "Core_1", + ["containers/Ogg/Page"] = "Core_1", + ["core/Bytes"] = "Core_1", + ["core/Crc32"] = "Core_1", + ["core/Err"] = "Core_1", + ["core/Input"] = "Core_1", + ["host"] = "Core_1", + ["ops/ImageOps"] = "Core_2", + ["ops/ImageOps/Kernels"] = "Core_2", + ["codecs/video/Dsp"] = "Mpeg2", + ["codecs/video/Mpeg1"] = "Mpeg2", + ["codecs/video/Mpeg2"] = "Mpeg2", + ["codecs/video/Mpeg2/Decoder"] = "Mpeg2", + ["codecs/video/Mpeg2/Tables"] = "Mpeg2", + ["codecs/video/Mpeg2/Vlc"] = "Mpeg2", + ["codecs/video/H263"] = "H263", + ["codecs/video/H263/Decoder"] = "H263", + ["codecs/video/H263/Tables"] = "H263", + ["codecs/video/H264"] = "H264", + ["codecs/video/H264/Bitstream"] = "H264", + ["codecs/video/H264/Cabac"] = "H264", + ["codecs/video/H264/Cavlc"] = "H264", + ["codecs/video/H264/Deblock"] = "H264", + ["codecs/video/H264/Decoder"] = "H264", + ["codecs/video/H264/Inter"] = "H264", + ["codecs/video/H264/Intra"] = "H264", + ["codecs/video/H264/Mb"] = "H264", + ["codecs/video/H264/Params"] = "H264", + ["codecs/video/H264/Slice"] = "H264", + ["codecs/video/H264/Tables"] = "H264", + ["codecs/video/H264/Transform"] = "H264", + ["codecs/video/Theora"] = "Theora", + ["codecs/video/Theora/Decoder"] = "Theora", + ["codecs/video/Theora/Header"] = "Theora", + ["codecs/video/Legacy"] = "Legacy", + ["codecs/video/Legacy/Cinepak"] = "Legacy", + ["codecs/video/Legacy/Flic"] = "Legacy", + ["codecs/video/Legacy/Msvideo1"] = "Legacy", + ["codecs/video/Legacy/Picture"] = "Legacy", + ["codecs/video/Legacy/QtRle"] = "Legacy", + ["codecs/video/Legacy/Smacker"] = "Legacy", + ["codecs/video/Legacy/Smc"] = "Legacy", + ["containers/MpegEs"] = "MpegTs", + ["containers/MpegPs"] = "MpegTs", + ["containers/MpegTs"] = "MpegTs", + ["codecs/image/Dct"] = "Dct", + ["codecs/image/Jpeg"] = "Jpeg", + ["codecs/image/Jpeg/Arith"] = "Jpeg", + ["codecs/image/Jpeg/Color"] = "Jpeg", + ["codecs/image/Jpeg/Decode"] = "Jpeg", + ["codecs/image/Jpeg/Encode"] = "Jpeg", + ["codecs/image/Jpeg/Scan"] = "Jpeg", + ["codecs/image/Jpeg/Tables"] = "Jpeg", + ["codecs/image/Jpeg/Yuv"] = "Jpeg", + ["codecs/image/Vp8"] = "Vp8", + ["codecs/image/Vp8/Decode"] = "Vp8", + ["codecs/image/Vp8/Predict"] = "Vp8", + ["codecs/image/Vp8/Tables"] = "Vp8", + ["codecs/image/Vp8/Yuv"] = "Vp8", + ["codecs/image/Vp8L"] = "Vp8", + ["codecs/image/Vp8L/Decode"] = "Vp8", + ["codecs/image/Vp8L/Encode"] = "Vp8", + ["codecs/image/Bcn"] = "Bcn", + ["codecs/image/Bcn/Decode"] = "Bcn", + ["codecs/image/Bcn/Encode"] = "Bcn", + ["image/png"] = "Png", + ["image/png/Apng"] = "Png", + ["image/png/Decode"] = "Png", + ["image/png/Encode"] = "Png", + ["codecs/compress/Deflate"] = "Deflate", + ["codecs/compress/Deflate/Compress"] = "Deflate", + ["codecs/compress/Deflate/Inflate"] = "Deflate", + ["codecs/compress/Brotli"] = "Brotli", + ["codecs/compress/Brotli/Decode"] = "Brotli", + ["codecs/compress/Brotli/Static"] = "Brotli", + ["codecs/compress/Lzma"] = "Lzma", + ["codecs/compress/Lzma/Crc64"] = "Lzma", + ["codecs/compress/Lzma/Decode"] = "Lzma", + ["codecs/compress/Lzma/Filters"] = "Lzma", + ["codecs/compress/Zstd"] = "Zstd", + ["codecs/compress/Zstd/Decode"] = "Zstd", + ["codecs/compress/Zstd/Xxh64"] = "Zstd", + ["codecs/audio/Mpa"] = "Mpa", + ["codecs/audio/Mpa/Analysis"] = "Mpa", + ["codecs/audio/Mpa/Core"] = "Mpa", + ["codecs/audio/Mpa/EncTables"] = "Mpa", + ["codecs/audio/Mpa/Encode2"] = "Mpa", + ["codecs/audio/Mpa/Encode3"] = "Mpa", + ["codecs/audio/Mpa/Header"] = "Mpa", + ["codecs/audio/Mpa/Tables"] = "Mpa", + ["codecs/audio/Opus"] = "Opus", + ["codecs/audio/Opus/Celt"] = "Opus", + ["codecs/audio/Opus/CeltEncoder"] = "Opus", + ["codecs/audio/Opus/CeltTables"] = "Opus", + ["codecs/audio/Opus/Decoder"] = "Opus", + ["codecs/audio/Opus/Mdct"] = "Opus", + ["codecs/audio/Opus/Packet"] = "Opus", + ["codecs/audio/Opus/Silk"] = "Opus", + ["codecs/audio/Opus/SilkTables"] = "Opus", + ["codecs/audio/Vorbis"] = "Vorbis", + ["codecs/audio/Vorbis/Codebook"] = "Vorbis", + ["codecs/audio/Vorbis/Packet"] = "Vorbis", + ["codecs/audio/Vorbis/Setup"] = "Vorbis", + ["codecs/audio/Vorbis/Tables"] = "Vorbis", + ["codecs/audio/Aac"] = "Aac", + ["codecs/audio/Aac/Decode"] = "Aac", + ["codecs/audio/Aac/Tables"] = "Aac", + ["codecs/audio/Flac"] = "Flac", + ["codecs/audio/Flac/Encode"] = "Flac", + ["codecs/audio/Flac/Frame"] = "Flac", + ["codecs/audio/Musepack"] = "Musepack", + ["codecs/audio/Musepack/Decode"] = "Musepack", + ["codecs/audio/Musepack/Tables"] = "Musepack", + ["codecs/audio/WavPack"] = "WavPack", + ["codecs/audio/WavPack/Block"] = "WavPack", + ["codecs/audio/WavPack/Tables"] = "WavPack", + ["codecs/audio/Tracker"] = "Tracker", + ["codecs/audio/Tracker/Load"] = "Tracker", + ["codecs/audio/Tracker/Mixer"] = "Tracker", + ["codecs/audio/Tracker/Pcm"] = "Tracker", + ["codecs/audio/Tracker/Player"] = "Tracker", + ["codecs/audio/Tracker/Tables"] = "Tracker", + ["codecs/audio/Hively"] = "Hively", + ["codecs/audio/Hively/Load"] = "Hively", + ["codecs/audio/Hively/Player"] = "Hively", + ["codecs/audio/Hively/Tables"] = "Hively", + ["codecs/audio/SoundFont"] = "SoundFont", + ["codecs/audio/SoundFont/Fallback"] = "SoundFont", + ["codecs/audio/SoundFont/Parse"] = "SoundFont", + ["codecs/audio/SoundFont/Synth"] = "SoundFont", + ["codecs/model/Draco"] = "Draco", + ["codecs/model/Draco/Attributes"] = "Draco", + ["codecs/model/Draco/Connectivity"] = "Draco", + ["codecs/model/Draco/Int64"] = "Draco", + ["codecs/model/Draco/KdTree"] = "Draco", + ["codecs/model/Draco/Predict"] = "Draco", + ["codecs/model/Draco/Reader"] = "Draco", + ["archive/7z"] = "archive_1", + ["archive/7z/Header"] = "archive_1", + ["archive/adf"] = "archive_1", + ["archive/applesingle"] = "archive_1", + ["archive/ar"] = "archive_1", + ["archive/arj"] = "archive_1", + ["archive/binhex"] = "archive_1", + ["archive/br"] = "archive_1", + ["archive/bz2"] = "archive_1", + ["archive/cab"] = "archive_1", + ["archive/cab/Sum"] = "archive_1", + ["archive/cpio"] = "archive_1", + ["archive/d64"] = "archive_1", + ["archive/fat"] = "archive_1", + ["archive/grp"] = "archive_1", + ["archive/gzip"] = "archive_1", + ["archive/iso"] = "archive_1", + ["archive/lha"] = "archive_1", + ["archive/lz4"] = "archive_1", + ["archive/macbinary"] = "archive_1", + ["archive/mpq"] = "archive_1", + ["archive/mpq/Crypt"] = "archive_1", + ["archive/pak"] = "archive_1", + ["archive/rpm"] = "archive_1", + ["archive/tar"] = "archive_1", + ["archive/uu"] = "archive_1", + ["archive/vpk"] = "archive_1", + ["archive/wad"] = "archive_1", + ["archive/wad/Map"] = "archive_1", + ["archive/wad/Picture"] = "archive_1", + ["archive/xz"] = "archive_1", + ["archive/yenc"] = "archive_1", + ["archive/z"] = "archive_1", + ["archive/zip"] = "archive_2", + ["archive/zoo"] = "archive_2", + ["archive/zst"] = "archive_2", + ["audio/aac"] = "audio", + ["audio/ac3"] = "audio", + ["audio/adpcm"] = "audio", + ["audio/adx"] = "audio", + ["audio/aiff"] = "audio", + ["audio/ape"] = "audio", + ["audio/au"] = "audio", + ["audio/brstm"] = "audio", + ["audio/caf"] = "audio", + ["audio/flac"] = "audio", + ["audio/flac/Meta"] = "audio", + ["audio/flac/Stream"] = "audio", + ["audio/m4a"] = "audio", + ["audio/mp3"] = "audio", + ["audio/mp3/Index"] = "audio", + ["audio/mp3/Stream"] = "audio", + ["audio/mp3/Tags"] = "audio", + ["audio/mpc"] = "audio", + ["audio/opus"] = "audio", + ["audio/opus/Encode"] = "audio", + ["audio/qoa"] = "audio", + ["audio/tta"] = "audio", + ["audio/vag"] = "audio", + ["audio/voc"] = "audio", + ["audio/vorbis"] = "audio", + ["audio/vorbis/Encode"] = "audio", + ["audio/wav"] = "audio", + ["audio/wav/Codecs"] = "audio", + ["audio/wavpack"] = "audio", + ["cad/step"] = "cad", + ["cad/step/Brep"] = "cad", + ["cad/step/Parse"] = "cad", + ["cad/step/Write"] = "cad", + ["codecs/audio/Ac3"] = "codecs_audio", + ["codecs/audio/Ac3/Decode"] = "codecs_audio", + ["codecs/audio/Ac3/Tables"] = "codecs_audio", + ["codecs/audio/Adpcm/Decoder"] = "codecs_audio", + ["codecs/audio/Alac"] = "codecs_audio", + ["codecs/audio/Alac/Decode"] = "codecs_audio", + ["codecs/audio/Alac/Encode"] = "codecs_audio", + ["codecs/audio/Ape"] = "codecs_audio", + ["codecs/audio/Ape/Decode"] = "codecs_audio", + ["codecs/audio/ApeTag"] = "codecs_audio", + ["codecs/audio/Mdct"] = "codecs_audio", + ["codecs/audio/Mdct/Fft"] = "codecs_audio", + ["codecs/audio/MidiRender"] = "codecs_audio", + ["codecs/audio/Pcm"] = "codecs_audio", + ["codecs/audio/Pcm/Convert"] = "codecs_audio", + ["codecs/audio/Qoa"] = "codecs_audio", + ["codecs/audio/Resample"] = "codecs_audio", + ["codecs/audio/Stream"] = "codecs_audio", + ["codecs/audio/Tta"] = "codecs_audio", + ["codecs/audio/Tta/Decode"] = "codecs_audio", + ["codecs/audio/VorbisComment"] = "codecs_audio", + ["codecs/compress/Bzip2"] = "codecs_compress", + ["codecs/compress/Bzip2/Decode"] = "codecs_compress", + ["codecs/compress/Explode"] = "codecs_compress", + ["codecs/compress/Lz4"] = "codecs_compress", + ["codecs/compress/Lzh"] = "codecs_compress", + ["codecs/compress/Lzw"] = "codecs_compress", + ["codecs/compress/Lzx"] = "codecs_compress", + ["codecs/compress/PackBits"] = "codecs_compress", + ["codecs/compress/Quantum"] = "codecs_compress", + ["codecs/compress/UnixCompress"] = "codecs_compress", + ["codecs/compress/Xxh32"] = "codecs_compress", + ["codecs/entropy/Huffman"] = "codecs_entropy", + ["codecs/entropy/RangeCoder"] = "codecs_entropy", + ["codecs/entropy/RangeCoder/Decoder"] = "codecs_entropy", + ["codecs/entropy/RangeCoder/Encoder"] = "codecs_entropy", + ["codecs/font/Bitmap"] = "codecs_font", + ["codecs/font/Cff"] = "codecs_font", + ["codecs/font/GlyphNames"] = "codecs_font", + ["codecs/font/TrueType"] = "codecs_font", + ["codecs/font/TrueType/Glyf"] = "codecs_font", + ["codecs/font/TrueType/Tables"] = "codecs_font", + ["codecs/image/Blend"] = "codecs_image", + ["codecs/image/Etc"] = "codecs_image", + ["codecs/image/Half"] = "codecs_image", + ["codecs/image/Pixels"] = "codecs_image", + ["codecs/image/Quantize"] = "codecs_image", + ["codecs/image/Raster"] = "codecs_image", + ["codecs/image/Texel"] = "codecs_image", + ["codecs/image/Texture"] = "codecs_image", + ["codecs/model/Mat4"] = "codecs_model", + ["codecs/model/MeshFlatten"] = "codecs_model", + ["codecs/model/Minecraft"] = "codecs_model", + ["codecs/model/Minecraft/Colors"] = "codecs_model", + ["codecs/model/Minecraft/Legacy"] = "codecs_model", + ["codecs/model/Minecraft/Packed"] = "codecs_model", + ["codecs/model/Polygon"] = "codecs_model", + ["codecs/model/Rbx/Binary"] = "codecs_model", + ["codecs/model/Rig"] = "codecs_model", + ["codecs/model/Sampler"] = "codecs_model", + ["codecs/model/Vrml"] = "codecs_model", + ["codecs/model/Vrml/Build"] = "codecs_model", + ["codecs/model/Vrml/Fields"] = "codecs_model", + ["codecs/model/Vrml/Geometry"] = "codecs_model", + ["codecs/model/Vrml/Parse"] = "codecs_model", + ["codecs/model/Vrml/Write"] = "codecs_model", + ["codecs/model/Vrml/Xml"] = "codecs_model", + ["codecs/text/Json"] = "codecs_text", + ["codecs/text/Json/Decode"] = "codecs_text", + ["codecs/text/Json/Encode"] = "codecs_text", + ["codecs/text/Nbt"] = "codecs_text", + ["codecs/text/Nbt/Binary"] = "codecs_text", + ["codecs/text/Nbt/Snbt"] = "codecs_text", + ["codecs/text/Nbt/Value"] = "codecs_text", + ["codecs/text/Text"] = "codecs_text", + ["codecs/text/Url"] = "codecs_text", + ["codecs/text/Xml"] = "codecs_text", + ["codecs/text/Xml/Parse"] = "codecs_text", + ["codecs/video/Video/Source"] = "codecs_video", + ["containers/Archive"] = "containers", + ["containers/Avi"] = "containers", + ["containers/Chunks"] = "containers", + ["containers/Cpio"] = "containers", + ["containers/Demux"] = "containers", + ["containers/Ebml"] = "containers", + ["containers/Fat"] = "containers", + ["containers/Iso9660"] = "containers", + ["containers/IsoBmff"] = "containers", + ["containers/IsoBmff/Box"] = "containers", + ["containers/IsoBmff/Demux"] = "containers", + ["containers/IsoBmff/Meta"] = "containers", + ["containers/IsoBmff/Mux"] = "containers", + ["containers/IsoBmff/QtPalette"] = "containers", + ["containers/MacFile"] = "containers", + ["containers/Ogg"] = "containers", + ["containers/Riff"] = "containers", + ["containers/Tar"] = "containers", + ["containers/Zip"] = "containers", + ["core/Adler32"] = "core", + ["core/Base64"] = "core", + ["core/Bits"] = "core", + ["core/Crc16"] = "core", + ["core/Md5"] = "core", + ["core/Sniff"] = "core", + ["data/cbor"] = "data", + ["data/cbor/Codec"] = "data", + ["data/csv"] = "data", + ["data/ini"] = "data", + ["data/json"] = "data", + ["data/msgpack"] = "data", + ["data/msgpack/Codec"] = "data", + ["data/nbt"] = "data", + ["data/plist"] = "data", + ["data/plist/Binary"] = "data", + ["data/snbt"] = "data", + ["data/toml"] = "data", + ["data/toml/Decode"] = "data", + ["data/toml/Encode"] = "data", + ["data/xml"] = "data", + ["data/yaml"] = "data", + ["data/yaml/Emit"] = "data", + ["data/yaml/Parse"] = "data", + ["font/bdf"] = "font", + ["font/bmfont"] = "font", + ["font/bmfont/Parse"] = "font", + ["font/eot"] = "font", + ["font/fon"] = "font", + ["font/hershey"] = "font", + ["font/pcf"] = "font", + ["font/psf"] = "font", + ["font/ttf"] = "font", + ["font/type1"] = "font", + ["font/type1/Charstring"] = "font", + ["font/woff"] = "font", + ["font/woff2"] = "font", + ["font/woff2/Rebuild"] = "font", + ["host/Love"] = "host", + ["host/LuaJIT"] = "host", + ["host/Luau"] = "host", + ["host/Roblox"] = "host", + ["image/ani"] = "image_1", + ["image/blp"] = "image_1", + ["image/bmp"] = "image_1", + ["image/dds"] = "image_1", + ["image/exr"] = "image_1", + ["image/exr/Codec"] = "image_1", + ["image/exr/Piz"] = "image_1", + ["image/gif"] = "image_1", + ["image/gif/Decode"] = "image_1", + ["image/hdr"] = "image_1", + ["image/hdr/Codec"] = "image_1", + ["image/icns"] = "image_1", + ["image/ico"] = "image_1", + ["image/ico/Dib"] = "image_1", + ["image/ilbm"] = "image_1", + ["image/jpeg"] = "image_1", + ["image/ktx"] = "image_1", + ["image/pcx"] = "image_1", + ["image/pnm"] = "image_1", + ["image/pnm/Codec"] = "image_1", + ["image/qoi"] = "image_1", + ["image/qoi/Codec"] = "image_1", + ["image/sgi"] = "image_1", + ["image/sunras"] = "image_1", + ["image/tga"] = "image_1", + ["image/tga/Codec"] = "image_1", + ["image/tiff"] = "image_2", + ["image/tiff/Pixels"] = "image_2", + ["image/tim"] = "image_2", + ["image/vtf"] = "image_2", + ["image/webp"] = "image_2", + ["image/webp/Alpha"] = "image_2", + ["image/webp/Anim"] = "image_2", + ["image/xbm"] = "image_2", + ["image/xpm"] = "image_2", + ["image/xpm/Names"] = "image_2", + ["layered/aseprite"] = "layered", + ["layered/ora"] = "layered", + ["layered/psd"] = "layered", + ["layered/psd/Channels"] = "layered", + ["model/3ds"] = "model_1", + ["model/3ds/Build"] = "model_1", + ["model/3ds/Read"] = "model_1", + ["model/3ds/Write"] = "model_1", + ["model/3mf"] = "model_1", + ["model/3mf/Read"] = "model_1", + ["model/3mf/Write"] = "model_1", + ["model/b3d"] = "model_1", + ["model/b3d/Read"] = "model_1", + ["model/bsp"] = "model_1", + ["model/bsp/Brush"] = "model_1", + ["model/bsp/Quake3"] = "model_1", + ["model/dae"] = "model_1", + ["model/dae/Math"] = "model_1", + ["model/dae/Read"] = "model_1", + ["model/dae/Write"] = "model_1", + ["model/fbx"] = "model_1", + ["model/fbx/Ascii"] = "model_1", + ["model/fbx/Binary"] = "model_1", + ["model/fbx/Read"] = "model_2", + ["model/fbx/Write"] = "model_2", + ["model/fbx/Xform"] = "model_2", + ["model/gltf"] = "model_2", + ["model/gltf/Pack"] = "model_2", + ["model/gltf/Read"] = "model_2", + ["model/gltf/Write"] = "model_2", + ["model/iqm"] = "model_2", + ["model/iqm/Read"] = "model_2", + ["model/iqm/Write"] = "model_2", + ["model/ldraw"] = "model_2", + ["model/ldraw/Colors"] = "model_2", + ["model/ldraw/Read"] = "model_2", + ["model/lwo"] = "model_2", + ["model/lwo/Build"] = "model_2", + ["model/lwo/Parse"] = "model_2", + ["model/mca"] = "model_3", + ["model/mca/Chunk"] = "model_3", + ["model/mca/Lz4Block"] = "model_3", + ["model/md2"] = "model_3", + ["model/md3"] = "model_3", + ["model/md5"] = "model_3", + ["model/md5/Read"] = "model_3", + ["model/mdl"] = "model_3", + ["model/mdl/HalfLife"] = "model_3", + ["model/mdl/Quake"] = "model_3", + ["model/ms3d"] = "model_3", + ["model/ms3d/Read"] = "model_3", + ["model/ms3d/Write"] = "model_3", + ["model/obj"] = "model_3", + ["model/obj/Mtl"] = "model_3", + ["model/off"] = "model_3", + ["model/ply"] = "model_3", + ["model/ply/Binary"] = "model_3", + ["model/pmx"] = "model_3", + ["model/pmx/Build"] = "model_3", + ["model/pmx/Pmd"] = "model_3", + ["model/pmx/Read"] = "model_3", + ["model/qb"] = "model_3", + ["model/rbxm"] = "model_4", + ["model/rbxmx"] = "model_4", + ["model/robloxmesh"] = "model_4", + ["model/robloxmesh/Parse"] = "model_4", + ["model/robloxmesh/Write"] = "model_4", + ["model/schematic"] = "model_4", + ["model/schematic/Common"] = "model_4", + ["model/schematic/Litematic"] = "model_4", + ["model/schematic/Mcedit"] = "model_4", + ["model/schematic/Sponge"] = "model_4", + ["model/smd"] = "model_4", + ["model/smd/Read"] = "model_4", + ["model/smd/Write"] = "model_4", + ["model/stl"] = "model_4", + ["model/stl/Decode"] = "model_4", + ["model/usda"] = "model_4", + ["model/usda/Build"] = "model_4", + ["model/usda/Parse"] = "model_4", + ["model/usda/Write"] = "model_4", + ["model/vox"] = "model_5", + ["model/vox/Grid"] = "model_5", + ["model/vrml"] = "model_5", + ["model/x"] = "model_5", + ["model/x/Build"] = "model_5", + ["model/x/Parse"] = "model_5", + ["model/x3d"] = "model_5", + ["music/669"] = "music", + ["music/ahx"] = "music", + ["music/far"] = "music", + ["music/hmp"] = "music", + ["music/hvl"] = "music", + ["music/it"] = "music", + ["music/it/Itsex"] = "music", + ["music/med"] = "music", + ["music/midi"] = "music", + ["music/midi/Smf"] = "music", + ["music/mod"] = "music", + ["music/mtm"] = "music", + ["music/mus"] = "music", + ["music/okt"] = "music", + ["music/ptm"] = "music", + ["music/s3m"] = "music", + ["music/sf2"] = "music", + ["music/stm"] = "music", + ["music/ult"] = "music", + ["music/umx"] = "music", + ["music/xm"] = "music", + ["music/xmi"] = "music", + ["ops/AudioOps"] = "ops", + ["ops/LayerOps"] = "ops", + ["ops/MeshOps"] = "ops", + ["ops/MeshOps/Greedy"] = "ops", + ["ops/MusicOps"] = "ops", + ["playlist/m3u"] = "playlist", + ["playlist/pls"] = "playlist", + ["playlist/xspf"] = "playlist", + ["subtitle/ass"] = "subtitle", + ["subtitle/srt"] = "subtitle", + ["subtitle/vtt"] = "subtitle", + ["vector/svg"] = "vector", + ["vector/svg/Parse"] = "vector", + ["vector/svg/PathData"] = "vector", + ["vector/svg/Render"] = "vector", + ["vector/svg/Style"] = "vector", + ["vector/svg/Write"] = "vector", + ["vector/tiled"] = "vector", + ["vector/tiled/Data"] = "vector", + ["vector/tiled/Tmj"] = "vector", + ["vector/tiled/Tmx"] = "vector", + ["video/avi"] = "video", + ["video/fli"] = "video", + ["video/flv"] = "video", + ["video/flv/Amf"] = "video", + ["video/flv/Mux"] = "video", + ["video/h264"] = "video", + ["video/mkv"] = "video", + ["video/mkv/Mux"] = "video", + ["video/mkv/Parse"] = "video", + ["video/mp4"] = "video", + ["video/mpegps"] = "video", + ["video/mpegts"] = "video", + ["video/ogv"] = "video", + ["video/smk"] = "video", + ["video/smk/Audio"] = "video", + ["video/y4m"] = "video", +} +local __FILES = {} +local __LOADED = {} +local __DONE = {} +local __script = script +local __include +local function __chunk(path) + local name = __CHUNK[path] + if name == nil or __DONE[name] then + return nil + end + __DONE[name] = true + local m + if __script ~= nil then + m = __script:FindFirstChild(name) + if m == nil then + error("rosetta: the chunk ModuleScript '" .. name .. "' is missing under " .. __script:GetFullName(), 3) + end + else + m = "@self/" .. name -- the luau CLI: the same tree as files (Rosetta/init.luau, Rosetta/<chunk>.luau) + end + require(m)(__FILES, __include) + return __FILES[path] +end +__include = function(path) + local r = __LOADED[path] + if r == nil then + local f = __FILES[path] or __chunk(path) + if f == nil then + error("rosetta: no module '" .. tostring(path) .. "'", 2) + end + __LOADED[path] = false -- while it runs (a cycle, or a module that threw) + r = f() + if r == nil then + r = true + end + __LOADED[path] = r + elseif r == false then + error("rosetta: module '" .. path .. "' is required in a cycle or failed to load", 2) + end + return r +end +local Rosetta = __include("") +Rosetta._internal = function(path) + return __include(path) +end +return Rosetta + + + + + Core_1 + --!optimize 2 +--!nocheck +-- rosetta chunk Core_1 (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 15 modules (6 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES[""] = function() + +-- Rosetta: read, write and convert file formats in pure Luau, on Roblox and on LuaJIT / LÖVE (through tools/build.py). +-- Formats are found through the generated Registry: by content (each format's sniff), then by extension. Never throws +-- on bad data or bad arguments: every function returns nil, Err. +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Input = __include("core/Input") +local Types = __include("Types") +local Registry = __include("Registry") +local Video = __include("codecs/video/Video") +local AudioWrap = __include("containers/AudioWrap") +local Rbx = __include("codecs/model/Rbx") +local ImageOps = __include("ops/ImageOps") +local host = __include("host") + +local F = {} + +F.version = "0.1.0" +F.Err = Err +F.Types = Types +F.Bytes = Bytes +F.Rbx = Rbx +F.null = Types.null +F.host = host +F.plugins = {} :: { [string]: any } -- injected optional dependencies (plugins.brep for cad/step) + +local KIND_CATEGORY: { [string]: string } = { + image = "image", + audio = "audio", + video = "video", + scene = "model", + rbxtree = "model", -- codecs/model/Rbx trees (model/rbxm, model/rbxmx) + cad = "cad", + font = "font", + archive = "archive", + vector = "vector", + tilemap = "vector", + layered = "layered", + subtitles = "subtitle", + music = "music", + midi = "music", + playlist = "playlist", +} + +local loaded: { [string]: any } = {} + +local function module(entry: Registry.Entry): (any, Err.Err?) + local m = loaded[entry.path] + if m then + return m + end + local ok, res = pcall(entry.load) + if not ok then + return nil, Err.new(Err.UNSUPPORTED, "format " .. entry.name .. " failed to load: " .. tostring(res)) + end + loaded[entry.path] = res + return res +end + +local function inCategory(entry: Registry.Entry, category: string?): boolean + return category == nil or entry.category == category +end + +local function find(key: string, category: string?): Registry.Entry? + local k = string.lower(key) + for _, e in Registry do + if e.name == k and inCategory(e, category) then + return e + end + end + for _, e in Registry do + if inCategory(e, category) and table.find(e.extensions, k) then + return e + end + end + return nil +end + +local function detect(buf: buffer, name: string?, category: string?, format: string?): (Registry.Entry?, Err.Err?) + if format then + local e = find(format, category) + if not e then + return nil, Err.new(Err.UNKNOWN_FORMAT, "no format named " .. format .. (if category then " in " .. category else "")) + end + return e, nil + end + local ext = Input.extension(name) + local best: Registry.Entry? = nil + local bestScore = 0 + for _, e in Registry do + if inCategory(e, category) and (e.caps.decode or e.caps.open) then + local m = module(e) + if m and m.sniff then + local ok, score = pcall(m.sniff, Bytes.reader(buf)) + if ok and type(score) == "number" and score > 0 then + if ext and table.find(e.extensions, ext) then + score += 0.01 -- ties go to the extension + end + if score > bestScore then + best, bestScore = e, score + end + end + end + end + end + if best then + return best, nil + end + if ext then + local e = find(ext, category) + if e then + 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 "")) +end + +-- music that renders (MOD, S3M, XM, IT, MIDI) is also audio: an audio lookup falls back to it (rendered = true) +local function detectFor(buf: buffer, name: string?, o: { [string]: any }): (Registry.Entry?, Err.Err?, boolean) + local entry, err = detect(buf, name, o.category, o.format) + if not entry and o.category == "audio" then + local e = detect(buf, name, "music", o.format) + if e and e.caps.render then + return e, nil, true + end + end + return entry, err, false +end + +local function tag(value: any, formatName: string) + if type(value) == "table" then + local meta = value.meta + if type(meta) == "table" then + if meta.source == nil then + meta.source = { format = formatName } + elseif type(meta.source) == "table" and meta.source.format == nil then + meta.source.format = formatName + end + end + end +end + +local function drain(dec: any): any + local channels = dec.channels + local parts, total = {}, 0 + while true do + local out, n = dec:read(65536) + if not out or n == 0 then + break + end + local copy = buffer.create(n * channels * 4) + buffer.copy(copy, 0, out, 0, n * channels * 4) + table.insert(parts, copy) + total += n + end + local a = Types.Audio.new(dec.sampleRate, channels, total) + local o = 0 + for _, p in parts do + buffer.copy(a.samples, o, p) + o += buffer.len(p) + end + a.tags = dec.tags or {} + return a +end + +-- siblings resolve relative to path's directory only (no absolute paths, no "..", no URLs) +local function siblings(path: string): (uri: string) -> buffer? + local dir = string.match(path, "^(.*[/\\])") or "" + return function(uri: string): buffer? + if type(uri) ~= "string" or uri == "" or string.find(uri, "^%a[%w+.-]*:") or string.sub(uri, 1, 1) == "/" then + return nil + end + local u = string.gsub(uri, "%%(%x%x)", function(h: string): string + return string.char(tonumber(h, 16) :: number) + end) + for part in string.gmatch(u, "[^/\\]+") do + if part == ".." then + return nil + end + end + local b = host.readFile(dir .. u) + return b + end +end + +type Options = { [string]: any } -- format (name or extension), category, path, data, name, + format options + +local load: (src: any, opts: Options?) -> (any, Err.Err?) + +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: any = o.loadPage + if value.pages or (value.meta.pageLoader and type(user) ~= "function") then + return + end + local dir = if name then string.match(name, "^(.*[/\\])") or "" else nil + if type(user) ~= "function" and not (dir and host.hasFiles) then + return + end + value.meta.pageLoader = function(file: string, page: number): (any, Err.Err?) + local src: any + if type(user) == "function" then + src = (user :: any)(file, page) + else + src = (dir :: string) .. file + end + if type(src) == "table" then + return src + end + if src == nil then + return nil, Err.new(Err.IO, "no data for page " .. file) + end + return load(src, { category = "image", name = file, path = type(user) ~= "function" }) + end +end + +-- a single-stream archive (meta.stream) holding another archive or a .pcf / .psf(u) / .bdf font loads as that, with +-- meta.compression = the outer format; package archives load as meta.payload (meta.container / meta.outer) +local function unwrap(value: any, formatName: string, o: Options): any + if o.unwrap == false or o.format ~= nil or (o._depth or 0) >= 3 then + return value + end + if type(value) ~= "table" or value.kind ~= "archive" or type(value.meta) ~= "table" then + return value + end + local payload = value.meta.payload + if not value.meta.stream and type(payload) ~= "string" then + return value + end + local ok, list = pcall(value.list, value) + if not ok or type(list) ~= "table" or (#list ~= 1 and type(payload) ~= "string") or #list == 0 then + return value + end + local entryName = if type(payload) == "string" then payload else list[1].name + local rok, inner = pcall(value.read, value, entryName) + if not rok or type(inner) ~= "buffer" then + return value + end + local category = "archive" + local e = detect(inner, nil, "archive", nil) + local innerExt = Input.extension(entryName) or "" + if not e and value.meta.stream and (innerExt == "pcf" or innerExt == "psf" or innerExt == "psfu" or innerExt == "bdf") then + -- compressed bitmap fonts (.pcf.gz, .psf.gz, .bdf.gz: X11 and console font directories) load as the font + e = detect(inner, entryName, "font", nil) + category = "font" + end + if not e then + return value + end + local io = table.clone(o) + io.category = category + io.name = entryName + io._depth = (o._depth or 0) + 1 + local v = load(inner, io) + if type(v) ~= "table" or type(v.meta) ~= "table" then + return value + end + if type(payload) == "string" then + v.meta.container = formatName + v.meta.outer = value + else + v.meta.compression = formatName + end + return v +end + +-- api hooks (a format never requires another format): opts.decodeImage / encodeImage, opts.plugins, opts.decodeModule, +-- opts.openAudio (containers/AudioWrap: PCM -> WAV, Opus / Vorbis -> Ogg, AAC -> ADTS, MP3 / FLAC / AC-3 as they are) +local function openAudio(demuxer: any, track: any): (any, Err.Err?) + local buf, fmt, err = AudioWrap.wrap(demuxer, track) + if not buf then + return nil, err + end + local dec, oerr = F.open(buf, { format = fmt, category = "audio" }) + -- Matroska CodecDelay: ffmpeg drops it for MPEG audio / AAC; Opus has its own pre-skip and Vorbis's delay is + -- already the decoder's own (its first packet returns nothing) + -- MP4 edit lists add the play length (the encoder's end padding is cut, as ffmpeg does) + if dec and fmt ~= "opus" and fmt ~= "vorbis" then + local skip = if type(track.codecDelay) == "number" and track.codecDelay > 0 then math.floor(track.codecDelay * dec.sampleRate + 0.5) else 0 + local length = if type(track.playDuration) == "number" and track.playDuration > 0 then math.floor(track.playDuration * dec.sampleRate + 0.5) else nil + if skip > 0 or length then + dec = AudioWrap.trim(dec, skip, length) + end + end + return dec, oerr +end + +local function withHooks(o: Options): Options + if o.decodeImage ~= nil and o.encodeImage ~= nil and o.plugins ~= nil and o.openAudio ~= nil and o.decodeModule ~= nil then + return o + end + local c = table.clone(o) + if c.plugins == nil then + c.plugins = F.plugins + end + if c.openAudio == nil then + c.openAudio = openAudio + end + if c.decodeImage == nil then + c.decodeImage = function(b: buffer): (any, Err.Err?) + return F.load(b, { category = "image" }) + end + end + if c.encodeImage == nil then + c.encodeImage = function(img: any, format: string): (any, Err.Err?) + return F.save(img, nil, { format = format, category = "image" }) + end + end + if c.decodeModule == nil then + c.decodeModule = function(b: buffer, format: string?): (any, Err.Err?) + return F.load(b, { category = "music", format = format }) + end + end + return c +end + +function F.load(src: any, opts: Options?): (any, Err.Err?) + local o: Options = opts or {} + local buf, ierr, name = Input.resolve(src, o, host) + if not buf then + return nil, ierr + end + if name and o.name == nil then + o = table.clone(o) + o.name = name -- formats may use the file name (single-stream archives name their entry after it) + end + local entry, derr, rendered = detectFor(buf, name, o) + if not entry then + return nil, derr + end + local m, merr = module(entry) + if not m then + return nil, merr + end + if o.resolve == nil and name and name == (type(src) == "string" and src or nil) and host.hasFiles then + o = table.clone(o) + o.resolve = siblings(name) + end + local value, err + if m.decode and not rendered then + local ok, v, e = pcall(m.decode, Bytes.reader(buf), withHooks(o)) + if not ok then + return nil, Err.wrap(Err.new(Err.CORRUPT, "decoder threw: " .. tostring(v)), entry.name) + end + value, err = v, e + elseif m.open then + local ok, dec, e = pcall(m.open, Bytes.reader(buf), withHooks(o)) + if not ok then + return nil, Err.wrap(Err.new(Err.CORRUPT, "decoder threw: " .. tostring(dec)), entry.name) + end + if dec then + value = if type(dec) == "table" and dec.kind == "video" then dec else drain(dec) + end + err = e + else + return nil, Err.wrap(Err.new(Err.UNSUPPORTED, "no decoder"), entry.name) + end + if value == nil then + return nil, Err.wrap(err or Err.new(Err.CORRUPT, "decode failed"), entry.name) + end + tag(value, entry.name) + pageLoader(value, name, o) + return unwrap(value, entry.name, o) +end +load = F.load + +function F.open(src: any, opts: Options?): (any, Err.Err?) + local o: Options = opts or {} + local buf, ierr, name = Input.resolve(src, o, host) + if not buf then + return nil, ierr + end + local entry, derr = detectFor(buf, name, o) + if not entry and o.category == "video" and o.format == nil then + entry = detect(buf, name, "image", nil) -- animated images open as frames-backed videos + end + if not entry then + return nil, derr + end + local m, merr = module(entry) + if not m then + return nil, merr + end + if not m.open and entry.category == "image" and o.category == "video" then + local io = table.clone(o) + io.category = "image" + io.format = entry.name + local img, lerr = F.load(buf, io) + if not img then + return nil, lerr + end + return F.video.fromImage(img, o) + end + if not m.open then + return nil, Err.wrap(Err.new(Err.UNSUPPORTED, "no streaming decoder (use load)"), entry.name) + end + local ok, dec, e = pcall(m.open, Bytes.reader(buf), withHooks(o)) + if not ok then + return nil, Err.wrap(Err.new(Err.CORRUPT, "decoder threw: " .. tostring(dec)), entry.name) + end + if dec == nil then + return nil, Err.wrap(e or Err.new(Err.CORRUPT, "open failed"), entry.name) + end + return dec +end + +local encodeTextures: (scene: any) -> Err.Err? + +local function videoToImage(v: any, o: Options): (any, Err.Err?) + if type(v.nextFrame) ~= "function" or type(v.toRGBA) ~= "function" then + return nil, Err.new(Err.ARG, "save: not a VideoDecoder") + end + local cap = o.maxFrames or 300 + local want = o.frames + local fps = o.fps + if type(cap) ~= "number" or cap < 1 or (want ~= nil and (type(want) ~= "number" or want < 1)) or (fps ~= nil and (type(fps) ~= "number" or fps <= 0 or fps > 1000)) then + return nil, Err.new(Err.ARG, "save: frames / maxFrames must be >= 1 and fps 0..1000") + end + local limit = math.floor(if want then math.min(want, cap) else cap) + local w, h = math.max(1, tonumber(v.width) or 1), math.max(1, tonumber(v.height) or 1) + limit = math.max(1, math.min(limit, math.floor((o.maxPixels or 2 ^ 25) / (w * h)))) + local defaultDur = if type(v.frameRate) == "number" and v.frameRate > 0 then 1 / v.frameRate else 0.1 + local images: { any }, delays: { number } = {}, {} + local t0: number? = nil + local taken = 0 -- output slots used (fps mode) + while #images < limit do + local ok, f, ferr = pcall(v.nextFrame, v) + if not ok then + return nil, Err.new(Err.CORRUPT, "video decoder threw: " .. tostring(f)) + end + if f == nil then + if ferr then + return nil, ferr + end + break + end + local dur = if type(f.duration) == "number" and f.duration > 0 then f.duration else defaultDur + local delay = dur + if fps then + local start: number = t0 or f.pts + t0 = start + local slots = math.ceil((f.pts - start + dur) * fps - 1e-6) - taken + delay = slots / fps + taken += math.max(0, slots) + end + if delay > 0 then + local rok, img = pcall(v.toRGBA, v, f) + if not rok or type(img) ~= "table" then + return nil, Err.new(Err.CORRUPT, "frame " .. tostring(f.index) .. " did not convert to rgba8") + end + table.insert(images, img) + table.insert(delays, delay) + end + end + if #images == 0 then + return nil, Err.new(Err.ARG, "save: the video has no frames") + end + local img, ierr = ImageOps.fromFrames(images, delays) + if not img then + return nil, ierr + end + img.loops = if type(v.loops) == "number" then v.loops else 0 + img.meta.source = { format = v.format } + return img, nil +end + +local TRACKER_FAMILY = { mod = true, s3m = true, xm = true, it = true } +local function renderMusic(value: any, o: Options): (any, Err.Err?) + local ok, dec, err + if value.kind == "midi" then + local m, merr = F.format("midi") + if not m then + return nil, merr + end + ok, dec, err = pcall(m.render, value, o) + elseif TRACKER_FAMILY[value.engine or value.format] == nil and type(value.render) == "function" then + -- AHX / HVL render through the Module's own method (a failed render is an empty Decoder carrying .err) + ok, dec = pcall(value.render, value, o) + if ok and type(dec) == "table" and dec.err then + return nil, dec.err + end + else + local Tracker: any = __include("codecs/audio/Tracker") + ok, dec, err = pcall(Tracker.render, value, o) + end + if not ok then + return nil, Err.new(Err.ARG, "render threw: " .. tostring(dec)) + end + if dec == nil then + return nil, err or Err.new(Err.ARG, "render failed") + end + return dec, nil +end + +local function encoderFor(value: any, dest: string?, o: Options): (Registry.Entry?, any, Err.Err?, string?) + local category = o.category + if category == nil and type(value) == "table" and type(value.kind) == "string" then + category = KIND_CATEGORY[value.kind] + end + local key = o.format or Input.extension(dest) + if key == nil and type(value) == "table" and type(value.meta) == "table" and type(value.meta.source) == "table" then + key = value.meta.source.format + end + if key == nil then + return nil, nil, Err.new(Err.ARG, "save: no format (pass opts.format or a destination with an extension)") + end + local entry = find(key, category) + if not entry and category == "image" and type(value) == "table" and value.kind == "image" then + entry = find(key, "video") -- an (animated) image written as a video: F.convert(gif, "avi") + end + if not entry and category == "video" and type(value) == "table" and value.kind == "video" then + entry = find(key, "image") -- a video written as an animated image (F.save): F.convert(avi, "gif") + end + if not entry and category == "music" and type(value) == "table" and (value.kind == "music" or value.kind == "midi") then + entry = find(key, "audio") -- a Module / Midi saved as audio is rendered first (F.save): F.convert(mod, "wav") + end + if not entry then + return nil, nil, Err.new(Err.UNKNOWN_FORMAT, "no format named " .. key .. (if category then " for " .. category else "")) + end + local m, merr = module(entry) + if not m then + return nil, nil, merr + end + if not m.encode then + local alt = nil + for _, e in Registry do + if e.category == entry.category and e.caps.encode then + alt = e.name + break + end + end + return nil, nil, Err.wrap(Err.new(Err.UNSUPPORTED, "read-only format" .. (if alt then "; try " .. alt else "")), entry.name) + end + return entry, m, nil, key +end + +-- scene textures with only a decoded image get PNG bytes before a model writer sees them (writers never encode images) +function encodeTextures(scene: any): Err.Err? + if type(scene.textures) ~= "table" then + return nil + end + for _, tex in scene.textures do + if type(tex) == "table" and tex.data == nil and type(tex.image) == "table" and tex.uri == nil then + local png, err = F.save(tex.image, nil, { format = "png" }) + if not png then + return err + end + tex.data, tex.mime = png, "image/png" + end + end + return nil +end + +function F.save(value: any, dest: string?, opts: Options?): (any, Err.Err?, { [string]: any }?) + local o: Options = opts or {} + local entry, m, err, key = encoderFor(value, dest, o) + if not entry then + return nil, err + end + o = table.clone(o) + o.format = o.format or key + if dest then + o.name = o.name or string.match(dest, "([^/\\]+)$") + if o.files == nil then + o.files = {} + end + elseif o.files == nil and entry.caps.extraFiles then + o.files = {} + end + if entry.category == "video" and type(value) == "table" and value.kind == "image" then + local v, verr = F.video.fromImage(value) + if not v then + return nil, verr + end + value = v + end + if entry.category == "image" and type(value) == "table" and value.kind == "video" then + local img, ierr = videoToImage(value, o) + if not img then + return nil, ierr + end + value = img + end + if entry.category == "audio" and type(value) == "table" and (value.kind == "music" or value.kind == "midi") then + local dec, rerr = renderMusic(value, o) + if not dec then + return nil, rerr + end + value = dec + end + if type(value) == "table" and value.kind == "scene" then + local terr = encodeTextures(value) + if terr then + return nil, terr + end + end + local ok, buf, e = pcall(m.encode, value, withHooks(o)) + if not ok then + return nil, Err.wrap(Err.new(Err.ARG, "encoder threw: " .. tostring(buf)), entry.name) + end + if buf == nil then + return nil, Err.wrap(e or Err.new(Err.ARG, "encode failed"), entry.name) + end + if dest then + local wok, werr = host.writeFile(dest, buf) + if not wok then + return nil, werr + end + if type(o.files) == "table" and o.files ~= (opts and opts.files) then + local dir = string.match(dest, "^(.*[/\\])") or "" + for fname, data in o.files do + local fok, ferr = host.writeFile(dir .. fname, if type(data) == "string" then buffer.fromstring(data) else data) + if not fok then + return nil, ferr + end + end + end + return true + end + if type(o.files) == "table" and o.files ~= (opts and opts.files) and next(o.files) ~= nil then + return buf, nil, o.files + end + return buf +end + +function F.saveString(value: any, opts: Options?): (string?, Err.Err?) + local buf, err = F.save(value, nil, opts) + if not buf then + return nil, err + end + return buffer.tostring(buf), nil +end + +function F.convert(src: any, format: string, opts: Options?): (any, Err.Err?, { [string]: any }?) + local o: Options = opts or {} + local value, err = F.load(src, o) + if value == nil then + return nil, err + end + local so = table.clone(o) + so.format = format + so.category = nil + return F.save(value, o.out, so) +end + +function F.detect(src: any, opts: Options?): (string?, Err.Err?) + local o: Options = opts or {} + local buf, ierr, name = Input.resolve(src, o, host) + if not buf then + return nil, ierr + end + local entry, err = detect(buf, name, o.category, o.format) + if not entry then + return nil, err + end + -- a format may name the file's flavour more precisely (video/mkv: "webm" for DocType webm) + local m = module(entry) + if m and type(m.variant) == "function" then + local ok, v = pcall(m.variant, Bytes.reader(buf)) + if ok and type(v) == "string" then + return v, nil + end + end + return entry.name, nil +end + +type FormatInfo = { name: string, category: string, extensions: { string }, mime: { string }, caps: { [string]: any } } + +function F.formats(category: string?): { FormatInfo } + local out = {} + for _, e in Registry do + if inCategory(e, category) then + table.insert(out, { name = e.name, category = e.category, extensions = e.extensions, mime = e.mime, caps = e.caps }) + end + end + return out +end + +function F.format(name: string): (any, Err.Err?) + local e = find(name) + if not e then + return nil, Err.new(Err.UNKNOWN_FORMAT, "no format named " .. name) + end + return module(e) +end + +local function with(opts: Options?, category: string): Options + local o: Options = if opts then table.clone(opts) else {} + o.category = category + return o +end +for category in Types.CATEGORIES do + local cat: string = category + F[cat] = { + load = function(src: any, opts: Options?): (any, Err.Err?) + return F.load(src, with(opts, cat)) + end, + open = function(src: any, opts: Options?): (any, Err.Err?) + return F.open(src, with(opts, cat)) + end, + save = function(value: any, dest: string?, opts: Options?): (any, Err.Err?) + return F.save(value, dest, with(opts, cat)) + end, + formats = function(): { FormatInfo } + return F.formats(cat) + end, + } +end +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: Options = if opts then table.clone(opts) else {} + if o.plugins == nil then + o.plugins = F.plugins + end + local m, err = F.format("step") + if not m then + return nil, err + end + local ok, a, b = pcall(m[name], value, o) + if not ok then + return nil, Err.wrap(Err.new(Err.CORRUPT, name .. " threw: " .. tostring(a)), "step") + end + if a == nil and type(b) == "table" and b.code then + return nil, Err.wrap(b, "step") + end + return a, b + end +end +for _, fn in { "new", "addPattern", "setCell", "getCell", "addSample", "addInstrument", "note" } do + local name: string = fn + F.music[name] = function(...: any): (any, Err.Err?) + return (F.ops.music :: any)[name](...) + end +end +F.video.fromImage = function(img: any, opts: Options?): (any, Err.Err?) + if type(img) ~= "table" or img.kind ~= "image" then + return nil, Err.new(Err.ARG, "fromImage: expected an Image") + end + local frames, delays = { img }, { 0.1 } + if type(img.frames) == "table" and #img.frames > 0 then + local list, cerr = ImageOps.coalesce(img) + if not list then + return nil, cerr + end + frames = list + delays = {} + for i, f in img.frames do + delays[i] = if type(f.delay) == "number" and f.delay > 0 then f.delay else 0.1 + end + elseif img.format ~= "rgba8" and img.format ~= "yuv420p" then + local c, cerr = ImageOps.convert(img, "rgba8") + if not c then + return nil, cerr + end + frames = { c } + end + local src = type(img.meta) == "table" and img.meta.source + return Video.fromFrames(frames, delays, { format = type(src) == "table" and src.format or "image", loops = img.loops, meta = img.meta }) +end +F.video.fromFrames = function(images: any, delays: any?, opts: Options?): (any, Err.Err?) + return Video.fromFrames(images, delays, opts) +end +F.video.codecs = Video + +F.model.loadTextures = function(scene: any, opts: Options?): (any, { [number]: Err.Err }) + local errs: { [number]: Err.Err } = {} + if type(scene) ~= "table" or type(scene.textures) ~= "table" then + return scene, errs + end + 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 + if data == nil and tex.uri and resolve then + data = resolve(tex.uri) + end + if data ~= nil then + local img, err = F.load(data, { category = "image", name = tex.uri, data = true }) + if img then + tex.image = img + elseif err then + errs[i] = err + end + end + end + end + return scene, errs +end + +local OPS: { [string]: () -> any } = { + image = function() + return ImageOps + end, + mesh = function() + return __include("ops/MeshOps") + end, + layers = function() + return __include("ops/LayerOps") + end, + audio = function() + return __include("ops/AudioOps") + end, + music = function() + return __include("ops/MusicOps") + 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 +end +__FILES["Registry"] = function() + +-- Registry: GENERATED by tools/gen_registry.py from the format folders - do not edit. +-- One entry per format: the contract metadata (copied from its init.luau) and load(), which requires the format +-- module on first use (a static require, as Roblox needs). Order: category, then name. +type Entry = { + name: string, + category: string, + path: string, + extensions: { string }, + mime: { string }, + deps: { string }, + caps: { [string]: any }, + load: () -> any, +} + +local list: { Entry } = { + { + name = "ani", + category = "image", + path = "image/ani", + extensions = { "ani" }, + mime = { "application/x-navi-animation" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Riff" }, + caps = { decode = true, encode = true, alpha = true, animation = true, frames = true }, + load = function() + return __include("image/ani") + end, + }, + { + name = "blp", + category = "image", + path = "image/blp", + extensions = { "blp" }, + mime = { "image/x-blp" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Jpeg", "codecs/image/Bcn" }, + caps = { decode = true, encode = true, alpha = true, variants = { "blp1", "blp2" }, compressions = { "jpeg", "palette", "dxt1", "dxt3", "dxt5", "bgra" } }, + load = function() + return __include("image/blp") + end, + }, + { + name = "bmp", + category = "image", + path = "image/bmp", + extensions = { "bmp", "dib" }, + mime = { "image/bmp", "image/x-bmp", "image/x-ms-bmp" }, + 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 __include("image/bmp") + end, + }, + { + name = "dds", + category = "image", + path = "image/dds", + extensions = { "dds" }, + mime = { "image/vnd-ms.dds", "image/x-dds" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/image/Bcn", "codecs/image/Texel", "codecs/image/Texture" }, + caps = { decode = true, encode = true, alpha = true, float = true, mipmaps = true, cubemap = true, compressed = { "bc1", "bc2", "bc3", "bc4", "bc5", "bc6h", "bc7" } }, + load = function() + return __include("image/dds") + end, + }, + { + name = "exr", + category = "image", + path = "image/exr", + extensions = { "exr" }, + mime = { "image/x-exr", "image/aces" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/image/Half", "codecs/compress/Deflate" }, + caps = { decode = true, encode = true, alpha = true, float = true, hdr = true, depths = { 16, 32 }, multipart = true, tiled = true }, + load = function() + return __include("image/exr") + end, + }, + { + name = "gif", + category = "image", + path = "image/gif", + extensions = { "gif" }, + mime = { "image/gif" }, + 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 __include("image/gif") + end, + }, + { + name = "hdr", + category = "image", + path = "image/hdr", + extensions = { "hdr", "pic", "rgbe" }, + mime = { "image/vnd.radiance", "image/x-hdr" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, alpha = false, float = true, depths = { 32 } }, + load = function() + return __include("image/hdr") + end, + }, + { + name = "icns", + category = "image", + path = "image/icns", + extensions = { "icns" }, + mime = { "image/icns", "image/x-icns" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "containers/Chunks" }, + caps = { decode = true, encode = true, alpha = true, frames = true, depths = { 1, 24, 32 } }, + load = function() + return __include("image/icns") + end, + }, + { + name = "ico", + category = "image", + path = "image/ico", + extensions = { "ico", "cur" }, + mime = { "image/vnd.microsoft.icon", "image/x-icon" }, + 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 __include("image/ico") + end, + }, + { + name = "ilbm", + category = "image", + path = "image/ilbm", + extensions = { "iff", "ilbm", "lbm", "pbm" }, + mime = { "image/x-ilbm", "image/x-iff" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/compress/PackBits", "codecs/image/Pixels" }, + caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 1, 2, 3, 4, 5, 6, 7, 8, 24, 32 } }, + load = function() + return __include("image/ilbm") + end, + }, + { + name = "jpeg", + category = "image", + path = "image/jpeg", + extensions = { "jpg", "jpeg", "jpe", "jfif" }, + mime = { "image/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 __include("image/jpeg") + end, + }, + { + name = "ktx", + category = "image", + path = "image/ktx", + extensions = { "ktx2", "ktx" }, + mime = { "image/ktx2", "image/ktx" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/compress/Deflate", "codecs/compress/Zstd", "codecs/image/Texel", "codecs/image/Texture" }, + caps = { decode = true, encode = true, alpha = true, float = true, mipmaps = true, cubemap = true, compressed = { "bc1", "bc2", "bc3", "bc4", "bc5", "bc6h", "bc7", "etc1", "etc2", "eac" } }, + load = function() + return __include("image/ktx") + end, + }, + { + name = "pcx", + category = "image", + path = "image/pcx", + extensions = { "pcx", "pcc", "dcx" }, + mime = { "image/vnd.zbrush.pcx", "image/x-pcx" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Pixels" }, + caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 1, 2, 4, 8, 24, 32 } }, + load = function() + return __include("image/pcx") + end, + }, + { + name = "png", + category = "image", + path = "image/png", + extensions = { "png", "apng" }, + mime = { "image/png", "image/apng" }, + 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 __include("image/png") + end, + }, + { + name = "pnm", + category = "image", + path = "image/pnm", + extensions = { "pnm", "pbm", "pgm", "ppm", "pam", "pfm" }, + mime = { "image/x-portable-anymap", "image/x-portable-bitmap", "image/x-portable-graymap", "image/x-portable-pixmap", "image/x-portable-arbitrarymap", "image/x-portable-floatmap" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, alpha = true, depths = { 1, 8, 16, 32 }, float = true }, + load = function() + return __include("image/pnm") + end, + }, + { + name = "qoi", + category = "image", + path = "image/qoi", + extensions = { "qoi" }, + mime = { "image/qoi", "image/x-qoi" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, alpha = true, depths = { 8 } }, + load = function() + return __include("image/qoi") + end, + }, + { + name = "sgi", + category = "image", + path = "image/sgi", + extensions = { "sgi", "rgb", "rgba", "bw", "int", "inta" }, + mime = { "image/sgi", "image/x-rgb" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" }, + caps = { decode = true, encode = true, alpha = true, depths = { 8, 16 } }, + load = function() + return __include("image/sgi") + end, + }, + { + name = "sunras", + category = "image", + path = "image/sunras", + extensions = { "ras", "sun", "rs", "im1", "im8", "im24", "im32" }, + mime = { "image/x-sun-raster", "image/x-cmu-raster" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/image/Pixels" }, + caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 1, 8, 24, 32 } }, + load = function() + return __include("image/sunras") + end, + }, + { + name = "tga", + category = "image", + path = "image/tga", + extensions = { "tga", "icb", "vda", "vst", "tpic" }, + mime = { "image/x-tga", "image/x-targa" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 8, 15, 16, 24, 32 } }, + load = function() + return __include("image/tga") + end, + }, + { + name = "tiff", + category = "image", + path = "image/tiff", + extensions = { "tif", "tiff" }, + mime = { "image/tiff" }, + 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 __include("image/tiff") + end, + }, + { + name = "tim", + category = "image", + path = "image/tim", + extensions = { "tim" }, + mime = { "image/x-tim" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 4, 8, 16, 24 } }, + load = function() + return __include("image/tim") + end, + }, + { + name = "vtf", + category = "image", + path = "image/vtf", + extensions = { "vtf" }, + mime = { "image/x-vtf" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Bcn", "codecs/image/Texel" }, + caps = { decode = true, encode = false, alpha = true, animation = true, versions = { "7.0", "7.1", "7.2", "7.3", "7.4", "7.5" } }, + load = function() + return __include("image/vtf") + end, + }, + { + name = "webp", + category = "image", + path = "image/webp", + extensions = { "webp" }, + mime = { "image/webp" }, + 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 __include("image/webp") + end, + }, + { + name = "xbm", + category = "image", + path = "image/xbm", + extensions = { "xbm", "bm" }, + mime = { "image/x-xbitmap", "image/x-xbm" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" }, + caps = { decode = true, encode = true, depths = { 1 } }, + load = function() + return __include("image/xbm") + end, + }, + { + name = "xpm", + category = "image", + path = "image/xpm", + extensions = { "xpm", "pm" }, + mime = { "image/x-xpixmap", "image/x-xpm" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" }, + caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 8 } }, + load = function() + return __include("image/xpm") + end, + }, + { + name = "aac", + category = "audio", + path = "audio/aac", + extensions = { "aac", "adts" }, + mime = { "audio/aac", "audio/aacp", "audio/x-aac" }, + 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 __include("audio/aac") + end, + }, + { + name = "ac3", + category = "audio", + path = "audio/ac3", + extensions = { "ac3", "a52" }, + mime = { "audio/ac3", "audio/x-ac3" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/Ac3" }, + caps = { decode = true, encode = false, codecs = { "ac3" }, channels = 6, streaming = true, lossy = true }, + load = function() + return __include("audio/ac3") + end, + }, + { + name = "adpcm", + category = "audio", + path = "audio/adpcm", + extensions = { "adpcm", "ima" }, + mime = { "audio/x-adpcm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm", "codecs/audio/Adpcm/Decoder" }, + caps = { decode = true, encode = true, streaming = true, lossy = true, headerless = true, codecs = { "ima", "ima_wav", "ms", "ima_qt", "psx" } }, + load = function() + return __include("audio/adpcm") + end, + }, + { + name = "adx", + category = "audio", + path = "audio/adx", + extensions = { "adx" }, + mime = { "audio/x-adx" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm", "codecs/audio/Adpcm/Decoder" }, + caps = { decode = true, encode = true, streaming = true, lossy = true, loops = true, channels = 8 }, + load = function() + return __include("audio/adx") + end, + }, + { + name = "aiff", + category = "audio", + path = "audio/aiff", + extensions = { "aiff", "aif", "aifc", "afc" }, + mime = { "audio/aiff", "audio/x-aiff" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm/Decoder", "containers/Chunks" }, + caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, lossy = false }, + load = function() + return __include("audio/aiff") + end, + }, + { + name = "ape", + category = "audio", + path = "audio/ape", + extensions = { "ape" }, + mime = { "audio/ape", "audio/x-ape", "audio/x-monkeys-audio" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/Ape" }, + caps = { decode = true, encode = false, streaming = true, seek = true, lossless = true, float = true, depths = { 8, 16, 24, 32 } }, + load = function() + return __include("audio/ape") + end, + }, + { + name = "au", + category = "audio", + path = "audio/au", + extensions = { "au", "snd" }, + mime = { "audio/basic", "audio/x-au" }, + 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 __include("audio/au") + end, + }, + { + name = "brstm", + category = "audio", + path = "audio/brstm", + extensions = { "brstm", "bcstm", "bfstm" }, + mime = { "audio/x-brstm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm/Decoder" }, + caps = { decode = true, encode = false, streaming = true, lossy = true, loops = true, containers = { "RSTM", "CSTM", "FSTM" } }, + load = function() + return __include("audio/brstm") + end, + }, + { + name = "caf", + category = "audio", + path = "audio/caf", + extensions = { "caf", "caff" }, + mime = { "audio/x-caf" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Aac", "codecs/audio/Adpcm/Decoder", "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 __include("audio/caf") + end, + }, + { + name = "flac", + category = "audio", + path = "audio/flac", + extensions = { "flac", "oga" }, + mime = { "audio/flac", "audio/x-flac" }, + 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 __include("audio/flac") + end, + }, + { + name = "m4a", + category = "audio", + path = "audio/m4a", + extensions = { "m4a", "m4b", "m4r" }, + mime = { "audio/mp4", "audio/x-m4a", "audio/m4a" }, + 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 __include("audio/m4a") + end, + }, + { + name = "mp3", + category = "audio", + path = "audio/mp3", + extensions = { "mp3", "mp2", "mp1", "mpga" }, + mime = { "audio/mpeg", "audio/mp3", "audio/mpa" }, + 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 __include("audio/mp3") + end, + }, + { + name = "mpc", + category = "audio", + path = "audio/mpc", + extensions = { "mpc", "mp+", "mpp" }, + mime = { "audio/x-musepack", "audio/musepack" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/Musepack" }, + caps = { decode = true, encode = false, codecs = { "musepack" }, versions = { 7, 8 }, streaming = true, lossy = true }, + load = function() + return __include("audio/mpc") + end, + }, + { + name = "opus", + category = "audio", + path = "audio/opus", + extensions = { "opus" }, + mime = { "audio/opus", "audio/ogg" }, + 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 __include("audio/opus") + end, + }, + { + name = "qoa", + category = "audio", + path = "audio/qoa", + extensions = { "qoa" }, + mime = { "audio/qoa" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/Qoa" }, + caps = { decode = true, encode = true, streaming = true, lossy = true, seek = true, channels = 8 }, + load = function() + return __include("audio/qoa") + end, + }, + { + name = "tta", + category = "audio", + path = "audio/tta", + extensions = { "tta" }, + mime = { "audio/x-tta", "audio/tta" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/Tta" }, + caps = { decode = true, encode = false, streaming = true, seek = true, lossless = true, depths = { 8, 16, 24 } }, + load = function() + return __include("audio/tta") + end, + }, + { + name = "vag", + category = "audio", + path = "audio/vag", + extensions = { "vag" }, + mime = { "audio/x-vag" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm", "codecs/audio/Adpcm/Decoder" }, + caps = { decode = true, encode = true, streaming = true, lossy = true, loops = true, channels = 2 }, + load = function() + return __include("audio/vag") + end, + }, + { + name = "voc", + category = "audio", + path = "audio/voc", + extensions = { "voc" }, + mime = { "audio/x-voc" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm" }, + caps = { decode = true, encode = true, streaming = true, depths = { 8, 16 }, lossy = false }, + load = function() + return __include("audio/voc") + end, + }, + { + name = "vorbis", + category = "audio", + 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", "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 __include("audio/vorbis") + end, + }, + { + name = "wav", + category = "audio", + 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/audio/Pcm", "codecs/audio/Adpcm" }, + caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, rf64 = true }, + load = function() + return __include("audio/wav") + end, + }, + { + name = "wavpack", + category = "audio", + path = "audio/wavpack", + extensions = { "wv" }, + mime = { "audio/x-wavpack", "audio/wavpack" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/WavPack" }, + caps = { decode = true, encode = false, streaming = true, seek = true, lossless = true, hybrid = true, float = true, depths = { 8, 12, 16, 20, 24, 32 } }, + load = function() + return __include("audio/wavpack") + end, + }, + { + name = "avi", + category = "video", + path = "video/avi", + extensions = { "avi" }, + mime = { "video/x-msvideo", "video/avi" }, + 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", "mpeg2", "rawvideo" }, audio = true, odml = true }, + load = function() + return __include("video/avi") + end, + }, + { + name = "fli", + category = "video", + path = "video/fli", + extensions = { "fli", "flc", "flx" }, + mime = { "video/x-fli", "video/fli", "video/x-flc" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/video/Video" }, + caps = { decode = true, encode = false, streaming = true, video = { "flic" }, depths = { 8, 15, 16, 24 } }, + load = function() + return __include("video/fli") + end, + }, + { + name = "flv", + category = "video", + path = "video/flv", + extensions = { "flv" }, + mime = { "video/x-flv", "video/flv" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/video/Video", "codecs/video/Video/Source", "codecs/video/H263", "codecs/video/H264", "codecs/audio/Aac" }, + caps = { decode = true, encode = true, streaming = true, remux = true, video = { "flv1", "h264" }, audio = true, metadata = true }, + load = function() + return __include("video/flv") + end, + }, + { + name = "h264", + category = "video", + path = "video/h264", + extensions = { "h264", "264", "avc", "jsv", "26l", "jvt" }, + mime = { "video/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 __include("video/h264") + end, + }, + { + name = "mkv", + category = "video", + 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", "containers/Avi", "containers/IsoBmff/QtPalette", "codecs/compress/Deflate", "codecs/video/Video", "codecs/video/Video/Source" }, + caps = { decode = true, encode = true, streaming = true, remux = true, video = { "vp8", "mjpeg", "mpeg1", "mpeg2", "theora", "rawvideo" }, audio = true, subtitles = true }, + load = function() + return __include("video/mkv") + end, + }, + { + name = "mp4", + category = "video", + 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/Video", "codecs/video/Video/Source" }, + caps = { decode = true, encode = true, streaming = true, remux = true, video = { "mjpeg", "mpeg1", "mpeg2", "h264" }, audio = true, fragments = true }, + load = function() + return __include("video/mp4") + end, + }, + { + name = "mpegps", + category = "video", + 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/Video" }, + caps = { decode = true, encode = false, streaming = true, video = { "mpeg1", "mpeg2" }, audio = true }, + load = function() + return __include("video/mpegps") + end, + }, + { + name = "mpegts", + category = "video", + 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/Video" }, + caps = { decode = true, encode = false, streaming = true, video = { "mpeg1", "mpeg2", "h264" }, audio = true }, + load = function() + return __include("video/mpegts") + end, + }, + { + name = "ogv", + category = "video", + path = "video/ogv", + extensions = { "ogv", "ogg" }, + mime = { "video/ogg" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "containers/Demux", "containers/AudioWrap", "codecs/video/Theora", "codecs/video/Video", "codecs/video/Video/Source" }, + caps = { decode = true, encode = true, streaming = true, remux = true, video = { "theora" }, audio = true }, + load = function() + return __include("video/ogv") + end, + }, + { + name = "smk", + category = "video", + path = "video/smk", + extensions = { "smk" }, + mime = { "video/vnd.radgamettools.smacker" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/video/Video", "codecs/audio/Stream", "codecs/video/Legacy/Smacker" }, + caps = { decode = true, encode = false, streaming = true, video = { "smackvid" }, audio = { "smackaudio", "pcm_u8", "pcm_s16le" } }, + load = function() + return __include("video/smk") + end, + }, + { + name = "y4m", + category = "video", + path = "video/y4m", + extensions = { "y4m" }, + mime = { "video/x-yuv4mpeg" }, + 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 __include("video/y4m") + end, + }, + { + name = "3ds", + category = "model", + path = "model/3ds", + extensions = { "3ds" }, + mime = { "application/x-3ds", "image/x-3ds" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten", "codecs/model/Sampler" }, + caps = { decode = true, encode = true, materials = true, textures = true, animation = true, cameras = true, lights = true, instancing = true }, + load = function() + return __include("model/3ds") + end, + }, + { + name = "3mf", + category = "model", + path = "model/3mf", + extensions = { "3mf" }, + mime = { "model/3mf" }, + 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 __include("model/3mf") + end, + }, + { + name = "b3d", + category = "model", + path = "model/b3d", + extensions = { "b3d" }, + mime = { "model/x-b3d" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/model/Mat4" }, + caps = { decode = true, encode = false, materials = true, textures = true, skins = true, animation = true, colors = true }, + load = function() + return __include("model/b3d") + end, + }, + { + name = "bsp", + category = "model", + path = "model/bsp", + extensions = { "bsp" }, + mime = { "model/x-bsp" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels" }, + caps = { decode = true, encode = false, variants = { "quake", "halflife", "quake2", "quake3" }, lightmaps = "quake3" }, + load = function() + return __include("model/bsp") + end, + }, + { + name = "dae", + category = "model", + path = "model/dae", + extensions = { "dae", "zae" }, + mime = { "model/vnd.collada+xml", "model/vnd.collada+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 __include("model/dae") + end, + }, + { + name = "fbx", + category = "model", + path = "model/fbx", + extensions = { "fbx" }, + mime = { "application/vnd.autodesk.fbx", "model/fbx" }, + 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 __include("model/fbx") + end, + }, + { + name = "gltf", + category = "model", + path = "model/gltf", + extensions = { "gltf", "glb" }, + mime = { "model/gltf+json", "model/gltf-binary" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Json", "core/Base64", "core/Sniff", "codecs/model/Draco" }, + caps = { decode = true, encode = true, binary = true, materials = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true, draco = true }, + load = function() + return __include("model/gltf") + end, + }, + { + name = "iqm", + category = "model", + path = "model/iqm", + extensions = { "iqm" }, + mime = { "model/x-iqm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/Rig", "codecs/model/Sampler" }, + caps = { decode = true, encode = true, materials = true, skins = true, animation = true, vertexColors = true }, + load = function() + return __include("model/iqm") + end, + }, + { + name = "ldraw", + category = "model", + path = "model/ldraw", + extensions = { "ldr", "mpd", "dat" }, + mime = { "application/x-ldraw", "application/x-multi-part-ldraw" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" }, + caps = { decode = true, encode = false, materials = true, lines = true, instancing = true }, + load = function() + return __include("model/ldraw") + end, + }, + { + name = "lwo", + category = "model", + path = "model/lwo", + extensions = { "lwo", "lxo" }, + mime = { "image/x-lwo", "model/x-lwo" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks" }, + caps = { decode = true, encode = false, materials = true, polygons = true, vertexColors = true, morphTargets = true }, + load = function() + return __include("model/lwo") + end, + }, + { + name = "mca", + category = "model", + path = "model/mca", + extensions = { "mca", "mcr" }, + mime = { "application/x-minecraft-region" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Deflate", "codecs/text/Nbt", "codecs/model/Minecraft", "codecs/compress/Lz4" }, + caps = { decode = true, encode = false, voxels = true, blocks = true }, + load = function() + return __include("model/mca") + end, + }, + { + name = "md2", + category = "model", + path = "model/md2", + extensions = { "md2" }, + mime = { "model/x-md2" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/model/Rig" }, + caps = { decode = true, encode = false, morph = true, animation = true }, + load = function() + return __include("model/md2") + end, + }, + { + name = "md3", + category = "model", + path = "model/md3", + extensions = { "md3" }, + mime = { "model/x-md3" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/model/Mat4", "codecs/model/Rig" }, + caps = { decode = true, encode = false, morph = true, animation = true, tags = true }, + load = function() + return __include("model/md3") + end, + }, + { + name = "md5", + category = "model", + path = "model/md5", + extensions = { "md5mesh", "md5anim" }, + mime = { "model/x-md5mesh", "model/x-md5anim" }, + deps = { "core/Err", "core/Bytes", "core/Input", "core/Sniff", "Types", "codecs/model/Rig" }, + caps = { decode = true, encode = false, skins = true, animation = true }, + load = function() + return __include("model/md5") + end, + }, + { + name = "mdl", + category = "model", + path = "model/mdl", + extensions = { "mdl" }, + mime = { "model/x-mdl" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/model/Mat4", "codecs/model/Rig" }, + caps = { decode = true, encode = false, variants = { "quake", "halflife" }, morph = true, skins = true, animation = true }, + load = function() + return __include("model/mdl") + end, + }, + { + name = "ms3d", + category = "model", + path = "model/ms3d", + extensions = { "ms3d" }, + mime = { "application/x-ms3d" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten" }, + caps = { decode = true, encode = true, materials = true, skins = true, animation = true }, + load = function() + return __include("model/ms3d") + end, + }, + { + name = "obj", + category = "model", + path = "model/obj", + extensions = { "obj" }, + mime = { "model/obj" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, materials = true, polygons = true, vertexColors = true }, + load = function() + return __include("model/obj") + end, + }, + { + name = "off", + category = "model", + path = "model/off", + extensions = { "off" }, + mime = { "model/off", "text/plain" }, + 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 __include("model/off") + end, + }, + { + name = "ply", + category = "model", + path = "model/ply", + extensions = { "ply" }, + mime = { "model/ply", "application/ply" }, + 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 __include("model/ply") + end, + }, + { + name = "pmx", + category = "model", + path = "model/pmx", + extensions = { "pmx", "pmd" }, + mime = { "model/x-pmx", "model/x-pmd" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Text" }, + caps = { decode = true, encode = false, materials = true, skins = true, morphTargets = true, pmd = true }, + load = function() + return __include("model/pmx") + end, + }, + { + name = "qb", + category = "model", + path = "model/qb", + extensions = { "qb" }, + mime = { "model/x-qubicle" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, voxels = true, truecolor = true }, + load = function() + return __include("model/qb") + end, + }, + { + name = "rbxm", + category = "model", + path = "model/rbxm", + extensions = { "rbxm", "rbxl" }, + mime = { "application/x-roblox-rbxm", "application/x-roblox-rbxl" }, + deps = { "core/Err", "core/Bytes", "core/Md5", "codecs/compress/Lz4", "codecs/compress/Zstd", "codecs/model/Rbx", "codecs/model/Rbx/Binary" }, + caps = { decode = true, encode = true, tree = true, compression = { "none", "lz4", "zstd" } }, + load = function() + return __include("model/rbxm") + end, + }, + { + name = "rbxmx", + category = "model", + path = "model/rbxmx", + extensions = { "rbxmx", "rbxlx" }, + mime = { "application/x-roblox-rbxmx", "application/x-roblox-rbxlx" }, + deps = { "core/Err", "core/Bytes", "core/Base64", "core/Md5", "codecs/text/Xml", "codecs/model/Rbx" }, + caps = { decode = true, encode = true, tree = true }, + load = function() + return __include("model/rbxmx") + end, + }, + { + name = "robloxmesh", + category = "model", + path = "model/robloxmesh", + extensions = { "mesh" }, + mime = { "application/x-roblox-mesh" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten", "codecs/model/Draco" }, + caps = { decode = true, encode = true, skinning = true, lods = true, versions = { "1.00", "1.01", "2.00", "3.00", "3.01", "4.00", "4.01", "5.00", "6.00", "7.00" } }, + load = function() + return __include("model/robloxmesh") + end, + }, + { + name = "schematic", + category = "model", + path = "model/schematic", + extensions = { "schem", "schematic", "litematic" }, + mime = { "application/x-minecraft-schematic" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Nbt", "codecs/model/Minecraft" }, + caps = { decode = true, encode = true, voxels = true, blocks = true, variants = { "schem", "schematic", "litematic" } }, + load = function() + return __include("model/schematic") + end, + }, + { + name = "smd", + category = "model", + path = "model/smd", + extensions = { "smd" }, + mime = { "model/x-smd", "text/plain" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten", "codecs/model/Rig" }, + caps = { decode = true, encode = true, skins = true, animation = true }, + load = function() + return __include("model/smd") + end, + }, + { + name = "stl", + category = "model", + path = "model/stl", + extensions = { "stl" }, + mime = { "model/stl", "application/sla" }, + 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 __include("model/stl") + end, + }, + { + name = "usda", + category = "model", + path = "model/usda", + extensions = { "usda", "usd", "usdz" }, + mime = { "model/vnd.usda", "model/vnd.usdz+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 __include("model/usda") + end, + }, + { + name = "vox", + category = "model", + path = "model/vox", + extensions = { "vox" }, + mime = { "model/x-vox" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, voxels = true, sceneGraph = true, materials = true }, + load = function() + return __include("model/vox") + end, + }, + { + name = "vrml", + category = "model", + path = "model/vrml", + extensions = { "wrl", "wrz", "vrml" }, + mime = { "model/vrml", "x-world/x-vrml" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Vrml" }, + caps = { decode = true, encode = true, materials = true, polygons = true, animation = true, cameras = true, lights = true, lines = true, points = true }, + load = function() + return __include("model/vrml") + end, + }, + { + name = "x", + category = "model", + path = "model/x", + extensions = { "x" }, + mime = { "model/x-directx", "text/x-directx" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Deflate", "codecs/model/Mat4", "codecs/model/Rig" }, + caps = { decode = true, encode = false, text = true, binary = true, compressed = true, materials = true, skins = true, animation = true, polygons = true, vertexColors = true }, + load = function() + return __include("model/x") + end, + }, + { + name = "x3d", + category = "model", + path = "model/x3d", + extensions = { "x3d", "x3dv", "x3dz", "x3dvz", "x3db" }, + mime = { "model/x3d+xml", "model/x3d-vrml", "model/x3d+fastinfoset" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Vrml" }, + caps = { decode = true, encode = true, materials = true, polygons = true, animation = true, cameras = true, lights = true, lines = true, points = true, xml = true, classic = true }, + load = function() + return __include("model/x3d") + end, + }, + { + name = "step", + category = "cad", + path = "cad/step", + extensions = { "step", "stp", "p21" }, + mime = { "model/step", "application/step", "application/p21" }, + deps = { "core/Err", "core/Bytes", "Types", "core/Sniff" }, + caps = { decode = true, encode = true, complexEntities = true, sections = true, brep = "plugin", tessellate = "plugin" }, + load = function() + return __include("cad/step") + end, + }, + { + name = "bdf", + category = "font", + path = "font/bdf", + extensions = { "bdf" }, + mime = { "application/x-font-bdf" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/font/Bitmap" }, + caps = { decode = true, encode = true, bitmap = true }, + load = function() + return __include("font/bdf") + end, + }, + { + name = "bmfont", + category = "font", + path = "font/bmfont", + extensions = { "fnt" }, + mime = { "application/x-bmfont" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, bitmap = true, variants = { "text", "xml", "binary" }, extraFiles = true }, + load = function() + return __include("font/bmfont") + end, + }, + { + name = "eot", + category = "font", + path = "font/eot", + extensions = { "eot" }, + mime = { "application/vnd.ms-fontobject" }, + deps = { "core/Err", "core/Bytes", "codecs/text/Text", "codecs/font/TrueType" }, + caps = { decode = true, encode = true, variants = { "1.0", "2.1", "2.2" } }, + load = function() + return __include("font/eot") + end, + }, + { + name = "fon", + category = "font", + path = "font/fon", + extensions = { "fon", "fnt" }, + mime = { "application/x-font-fnt" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Text", "codecs/font/Bitmap" }, + caps = { decode = true, encode = false, bitmap = true, variants = { "fnt2", "fnt3", "ne", "pe" } }, + load = function() + return __include("font/fon") + end, + }, + { + name = "hershey", + category = "font", + path = "font/hershey", + extensions = { "jhf" }, + mime = { "application/x-hershey-font" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Raster" }, + caps = { decode = true, encode = false, strokes = true }, + load = function() + return __include("font/hershey") + end, + }, + { + name = "pcf", + category = "font", + path = "font/pcf", + extensions = { "pcf" }, + mime = { "application/x-font-pcf" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/font/Bitmap" }, + caps = { decode = true, encode = false, bitmap = true }, + load = function() + return __include("font/pcf") + end, + }, + { + name = "psf", + category = "font", + path = "font/psf", + extensions = { "psf", "psfu" }, + mime = { "application/x-font-linux-psf" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/font/Bitmap" }, + caps = { decode = true, encode = true, bitmap = true, variants = { "psf1", "psf2" } }, + load = function() + return __include("font/psf") + end, + }, + { + name = "ttf", + category = "font", + path = "font/ttf", + extensions = { "ttf", "otf", "ttc", "otc" }, + mime = { "font/ttf", "font/otf", "font/collection" }, + deps = { "core/Err", "core/Bytes", "codecs/font/TrueType" }, + caps = { decode = true, encode = false, outlines = { "truetype", "cff" }, collection = true, kerning = true }, + load = function() + return __include("font/ttf") + end, + }, + { + name = "type1", + category = "font", + path = "font/type1", + extensions = { "pfb", "pfa", "t1" }, + mime = { "application/x-font-type1" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Raster", "codecs/font/GlyphNames" }, + caps = { decode = true, encode = false, outlines = { "type1" }, variants = { "pfb", "pfa" } }, + load = function() + return __include("font/type1") + end, + }, + { + name = "woff", + category = "font", + path = "font/woff", + extensions = { "woff" }, + mime = { "font/woff" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/font/TrueType" }, + caps = { decode = true, encode = false, outlines = { "truetype", "cff" } }, + load = function() + return __include("font/woff") + end, + }, + { + name = "woff2", + category = "font", + path = "font/woff2", + extensions = { "woff2" }, + mime = { "font/woff2" }, + 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 __include("font/woff2") + end, + }, + { + name = "7z", + category = "archive", + 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", "codecs/text/Text" }, + caps = { decode = true, encode = false, methods = { "copy", "lzma", "lzma2", "deflate", "bcj", "delta" }, encrypted = false }, + load = function() + return __include("archive/7z") + end, + }, + { + name = "adf", + category = "archive", + path = "archive/adf", + extensions = { "adf" }, + mime = { "application/x-amiga-disk-format" }, + deps = { "core/Err", "core/Bytes", "containers/Archive" }, + caps = { decode = true, encode = false, variants = { "ofs", "ffs" } }, + load = function() + return __include("archive/adf") + end, + }, + { + name = "applesingle", + category = "archive", + path = "archive/applesingle", + extensions = { "as", "applesingle", "appledouble" }, + mime = { "application/applefile", "multipart/appledouble" }, + deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/MacFile" }, + caps = { decode = true, encode = true, forks = true, variants = { "applesingle", "appledouble" } }, + load = function() + return __include("archive/applesingle") + end, + }, + { + name = "ar", + category = "archive", + path = "archive/ar", + extensions = { "a", "ar", "deb", "lib" }, + mime = { "application/x-archive", "application/vnd.debian.binary-package" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/compress/Lzma", "codecs/compress/Zstd", "codecs/compress/Bzip2", "containers/Archive", "containers/Tar" }, + caps = { decode = true, encode = true, variants = { "gnu", "bsd" }, deb = true }, + load = function() + return __include("archive/ar") + end, + }, + { + name = "arj", + category = "archive", + path = "archive/arj", + extensions = { "arj" }, + mime = { "application/x-arj" }, + deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/compress/Lzh", "containers/Archive" }, + caps = { decode = true, encode = false, methods = { "store", "arj1", "arj2", "arj3", "arj4" } }, + load = function() + return __include("archive/arj") + end, + }, + { + name = "binhex", + category = "archive", + path = "archive/binhex", + extensions = { "hqx", "hcx" }, + mime = { "application/mac-binhex40" }, + deps = { "core/Err", "core/Bytes", "core/Crc16", "containers/Archive", "containers/MacFile" }, + caps = { decode = true, encode = true, forks = true }, + load = function() + return __include("archive/binhex") + end, + }, + { + name = "br", + category = "archive", + path = "archive/br", + extensions = { "br" }, + mime = { "application/x-brotli" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Brotli", "containers/Archive" }, + caps = { decode = true, encode = false, stream = true }, + load = function() + return __include("archive/br") + end, + }, + { + name = "bz2", + category = "archive", + path = "archive/bz2", + extensions = { "bz2", "tbz2", "tbz" }, + mime = { "application/x-bzip2" }, + deps = { "core/Err", "core/Bytes", "containers/Archive", "codecs/compress/Bzip2" }, + caps = { decode = true, encode = false, stream = true }, + load = function() + return __include("archive/bz2") + end, + }, + { + name = "cab", + category = "archive", + path = "archive/cab", + extensions = { "cab" }, + mime = { "application/vnd.ms-cab-compressed" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/compress/Lzx", "codecs/compress/Quantum", "containers/Archive" }, + caps = { decode = true, encode = true, methods = { "store", "mszip", "lzx", "quantum" } }, + load = function() + return __include("archive/cab") + end, + }, + { + name = "cpio", + category = "archive", + path = "archive/cpio", + extensions = { "cpio" }, + mime = { "application/x-cpio" }, + deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Cpio" }, + caps = { decode = true, encode = true, variants = { "newc", "crc", "odc", "bin" } }, + load = function() + return __include("archive/cpio") + end, + }, + { + name = "d64", + category = "archive", + path = "archive/d64", + extensions = { "d64", "d71", "d81" }, + mime = { "application/x-d64" }, + deps = { "core/Err", "core/Bytes", "containers/Archive" }, + caps = { decode = true, encode = true, variants = { "d64", "d71", "d81" } }, + load = function() + return __include("archive/d64") + end, + }, + { + name = "fat", + category = "archive", + path = "archive/fat", + extensions = { "img", "ima", "vfd", "flp", "fat" }, + mime = { "application/x-fat-image" }, + deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Fat" }, + caps = { decode = true, encode = true, variants = { "fat12", "fat16", "fat32" } }, + load = function() + return __include("archive/fat") + end, + }, + { + name = "grp", + category = "archive", + path = "archive/grp", + extensions = { "grp" }, + mime = { "application/x-build-grp" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "containers/Archive" }, + caps = { decode = true, encode = true }, + load = function() + return __include("archive/grp") + end, + }, + { + name = "gzip", + category = "archive", + path = "archive/gzip", + extensions = { "gz", "tgz", "gzip" }, + mime = { "application/gzip" }, + deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/compress/Deflate", "containers/Archive", "containers/Tar" }, + caps = { decode = true, encode = true, stream = true }, + load = function() + return __include("archive/gzip") + end, + }, + { + name = "iso", + category = "archive", + path = "archive/iso", + extensions = { "iso" }, + mime = { "application/x-iso9660-image" }, + deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Iso9660" }, + caps = { decode = true, encode = false, extensions = { "joliet", "rockridge", "eltorito" } }, + load = function() + return __include("archive/iso") + end, + }, + { + name = "lha", + category = "archive", + path = "archive/lha", + extensions = { "lzh", "lha", "lzs" }, + mime = { "application/x-lzh-compressed" }, + deps = { "core/Err", "core/Bytes", "core/Crc16", "codecs/compress/Lzh", "containers/Archive" }, + caps = { decode = true, encode = true, methods = { "lh0", "lh1", "lh4", "lh5", "lh6", "lh7", "lhx", "lzs", "lz5", "lz4", "lhd" } }, + load = function() + return __include("archive/lha") + end, + }, + { + name = "lz4", + category = "archive", + path = "archive/lz4", + extensions = { "lz4", "tlz4" }, + mime = { "application/x-lz4" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Lz4", "codecs/compress/Xxh32", "containers/Archive" }, + caps = { decode = true, encode = true, stream = true, legacy = true }, + load = function() + return __include("archive/lz4") + end, + }, + { + name = "macbinary", + category = "archive", + path = "archive/macbinary", + extensions = { "bin", "macbin" }, + mime = { "application/x-macbinary" }, + deps = { "core/Err", "core/Bytes", "core/Crc16", "containers/Archive", "containers/MacFile" }, + caps = { decode = true, encode = true, forks = true, variants = { "I", "II", "III" } }, + load = function() + return __include("archive/macbinary") + end, + }, + { + name = "mpq", + category = "archive", + path = "archive/mpq", + extensions = { "mpq", "w3x", "w3m", "sc2map", "sc2data", "s2ma", "scm", "scx" }, + mime = { "application/x-mpq" }, + deps = { "core/Err", "core/Bytes", "containers/Archive", "codecs/compress/Deflate", "codecs/compress/Bzip2", "codecs/compress/Lzma", "codecs/compress/Explode" }, + caps = { decode = true, encode = false, versions = { 1, 2, 3, 4 }, methods = { "zlib", "implode", "bzip2", "lzma", "sparse" }, encryption = true }, + load = function() + return __include("archive/mpq") + end, + }, + { + name = "pak", + category = "archive", + path = "archive/pak", + extensions = { "pak", "sin" }, + mime = { "application/x-pak" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "containers/Archive" }, + caps = { decode = true, encode = true, variants = { "quake", "sin" } }, + load = function() + return __include("archive/pak") + end, + }, + { + name = "rpm", + category = "archive", + path = "archive/rpm", + extensions = { "rpm" }, + mime = { "application/x-rpm" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/compress/Lzma", "codecs/compress/Zstd", "codecs/compress/Bzip2", "containers/Archive", "containers/Cpio" }, + caps = { decode = true, encode = false, compressors = { "gzip", "bzip2", "xz", "lzma", "zstd" } }, + load = function() + return __include("archive/rpm") + end, + }, + { + name = "tar", + category = "archive", + path = "archive/tar", + extensions = { "tar" }, + mime = { "application/x-tar" }, + deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Tar" }, + caps = { decode = true, encode = true, variants = { "ustar", "pax", "gnu" } }, + load = function() + return __include("archive/tar") + end, + }, + { + name = "uu", + category = "archive", + path = "archive/uu", + extensions = { "uu", "uue", "xxe", "b64" }, + mime = { "text/x-uuencode" }, + deps = { "core/Err", "core/Bytes", "core/Base64", "containers/Archive" }, + caps = { decode = true, encode = true, variants = { "uu", "xx", "base64" } }, + load = function() + return __include("archive/uu") + end, + }, + { + name = "vpk", + category = "archive", + path = "archive/vpk", + extensions = { "vpk" }, + mime = { "application/x-vpk" }, + deps = { "core/Err", "core/Bytes", "core/Input", "core/Crc32", "core/Md5", "containers/Archive" }, + caps = { decode = true, encode = true, versions = { 1, 2 }, multipart = true }, + load = function() + return __include("archive/vpk") + end, + }, + { + name = "wad", + category = "archive", + path = "archive/wad", + extensions = { "wad" }, + mime = { "application/x-doom" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Archive", "codecs/image/Pixels", "codecs/model/Polygon" }, + caps = { decode = true, encode = true, images = true, maps = true, variants = { "iwad", "pwad" } }, + load = function() + return __include("archive/wad") + end, + }, + { + name = "xz", + category = "archive", + path = "archive/xz", + extensions = { "xz", "txz", "lzma" }, + mime = { "application/x-xz", "application/x-lzma" }, + 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 __include("archive/xz") + end, + }, + { + name = "yenc", + category = "archive", + path = "archive/yenc", + extensions = { "yenc", "ync" }, + mime = { "application/x-yenc" }, + deps = { "core/Err", "core/Bytes", "core/Crc32", "containers/Archive" }, + caps = { decode = true, encode = true, multipart = true }, + load = function() + return __include("archive/yenc") + end, + }, + { + name = "z", + category = "archive", + path = "archive/z", + extensions = { "z", "taz", "tz" }, + mime = { "application/x-compress" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/UnixCompress", "containers/Archive" }, + caps = { decode = true, encode = true, stream = true, bits = { 9, 16 } }, + load = function() + return __include("archive/z") + end, + }, + { + name = "zip", + category = "archive", + path = "archive/zip", + extensions = { "zip", "wsz" }, + mime = { "application/zip", "application/x-zip-compressed" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Zip" }, + caps = { decode = true, encode = true, methods = { "store", "deflate" }, zip64 = true }, + load = function() + return __include("archive/zip") + end, + }, + { + name = "zoo", + category = "archive", + path = "archive/zoo", + extensions = { "zoo" }, + mime = { "application/x-zoo" }, + deps = { "core/Err", "core/Bytes", "core/Crc16", "codecs/compress/Lzw", "codecs/compress/Lzh", "containers/Archive" }, + caps = { decode = true, encode = false, methods = { "store", "lzw", "lzh" } }, + load = function() + return __include("archive/zoo") + end, + }, + { + name = "zst", + category = "archive", + path = "archive/zst", + extensions = { "zst", "tzst" }, + mime = { "application/zstd" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Zstd", "containers/Archive" }, + caps = { decode = true, encode = false, stream = true }, + load = function() + return __include("archive/zst") + end, + }, + { + name = "cbor", + category = "data", + path = "data/cbor", + extensions = { "cbor" }, + mime = { "application/cbor", "application/cbor-seq" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, binary = true, ordered = true, tags = true }, + load = function() + return __include("data/cbor") + end, + }, + { + name = "csv", + category = "data", + path = "data/csv", + extensions = { "csv", "tsv" }, + mime = { "text/csv", "text/tab-separated-values" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Json", "core/Sniff" }, + caps = { decode = true, encode = true, header = true }, + load = function() + return __include("data/csv") + end, + }, + { + name = "ini", + category = "data", + path = "data/ini", + extensions = { "ini", "cfg", "conf", "inf", "desktop" }, + mime = { "text/plain" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Json", "core/Sniff" }, + caps = { decode = true, encode = true, ordered = true }, + load = function() + return __include("data/ini") + end, + }, + { + name = "json", + category = "data", + path = "data/json", + extensions = { "json", "jsonl", "ndjson", "geojson" }, + mime = { "application/json", "application/x-ndjson" }, + deps = { "core/Err", "core/Bytes", "codecs/text/Json", "core/Sniff" }, + caps = { decode = true, encode = true, ordered = true, streaming = true }, + load = function() + return __include("data/json") + end, + }, + { + name = "msgpack", + category = "data", + path = "data/msgpack", + extensions = { "msgpack", "mpk" }, + mime = { "application/msgpack", "application/x-msgpack" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, binary = true, ordered = true }, + load = function() + return __include("data/msgpack") + end, + }, + { + name = "nbt", + category = "data", + path = "data/nbt", + extensions = { "nbt", "dat", "mcstructure", "dat_old" }, + mime = { "application/x-minecraft-nbt" }, + deps = { "core/Err", "core/Bytes", "codecs/text/Nbt" }, + caps = { decode = true, encode = true, binary = true, ordered = true, typed = true }, + load = function() + return __include("data/nbt") + end, + }, + { + name = "plist", + category = "data", + path = "data/plist", + extensions = { "plist" }, + mime = { "application/x-plist", "application/x-bplist" }, + 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 __include("data/plist") + end, + }, + { + name = "snbt", + category = "data", + path = "data/snbt", + extensions = { "snbt" }, + mime = { "text/x-minecraft-snbt" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "codecs/text/Nbt" }, + caps = { decode = true, encode = true, ordered = true, typed = true }, + load = function() + return __include("data/snbt") + end, + }, + { + name = "toml", + category = "data", + path = "data/toml", + extensions = { "toml" }, + mime = { "application/toml" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Json", "codecs/text/Text" }, + caps = { decode = true, encode = true, ordered = true, dates = true }, + load = function() + return __include("data/toml") + end, + }, + { + name = "xml", + category = "data", + path = "data/xml", + extensions = { "xml", "xsd", "xsl", "xslt", "rss", "atom", "xhtml" }, + mime = { "application/xml", "text/xml" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Xml", "core/Sniff" }, + caps = { decode = true, encode = true, namespaces = true, streaming = true }, + load = function() + return __include("data/xml") + end, + }, + { + name = "yaml", + category = "data", + path = "data/yaml", + extensions = { "yaml", "yml" }, + mime = { "application/yaml", "application/x-yaml", "text/yaml" }, + 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 __include("data/yaml") + end, + }, + { + name = "svg", + category = "vector", + path = "vector/svg", + extensions = { "svg" }, + mime = { "image/svg+xml" }, + 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 __include("vector/svg") + end, + }, + { + name = "tiled", + category = "vector", + 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/text/Xml", "codecs/text/Json", "codecs/compress/Deflate", "core/Sniff" }, + caps = { decode = true, encode = true, tilesets = true, infinite = true }, + load = function() + return __include("vector/tiled") + end, + }, + { + name = "aseprite", + category = "layered", + path = "layered/aseprite", + extensions = { "aseprite", "ase" }, + mime = { "image/x-aseprite" }, + 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 __include("layered/aseprite") + end, + }, + { + name = "ora", + category = "layered", + path = "layered/ora", + extensions = { "ora" }, + mime = { "image/openraster" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Zip", "codecs/text/Xml", "codecs/image/Blend" }, + caps = { decode = true, encode = true, layers = true, groups = true, depths = { 8 } }, + load = function() + return __include("layered/ora") + end, + }, + { + name = "psd", + category = "layered", + path = "layered/psd", + extensions = { "psd", "psb" }, + mime = { "image/vnd.adobe.photoshop" }, + 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 __include("layered/psd") + end, + }, + { + name = "ass", + category = "subtitle", + path = "subtitle/ass", + extensions = { "ass", "ssa" }, + mime = { "text/x-ssa", "text/x-ass" }, + deps = { "core/Err", "core/Bytes", "Types", "core/Sniff" }, + caps = { decode = true, encode = true, styles = true }, + load = function() + return __include("subtitle/ass") + end, + }, + { + name = "srt", + category = "subtitle", + path = "subtitle/srt", + extensions = { "srt" }, + mime = { "application/x-subrip", "text/srt" }, + deps = { "core/Err", "core/Bytes", "Types", "core/Sniff" }, + caps = { decode = true, encode = true, styles = false }, + load = function() + return __include("subtitle/srt") + end, + }, + { + name = "vtt", + category = "subtitle", + path = "subtitle/vtt", + extensions = { "vtt", "webvtt" }, + mime = { "text/vtt" }, + deps = { "core/Err", "core/Bytes", "Types", "core/Sniff" }, + caps = { decode = true, encode = true, styles = true }, + load = function() + return __include("subtitle/vtt") + end, + }, + { + name = "669", + category = "music", + path = "music/669", + extensions = { "669" }, + mime = { "audio/x-669" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 8, 8 } }, + load = function() + return __include("music/669") + end, + }, + { + name = "ahx", + category = "music", + path = "music/ahx", + extensions = { "ahx", "thx" }, + mime = { "audio/x-ahx" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Hively" }, + caps = { decode = true, encode = false, render = true, channels = { 4, 4 }, subsongs = true }, + load = function() + return __include("music/ahx") + end, + }, + { + name = "far", + category = "music", + path = "music/far", + extensions = { "far" }, + mime = { "audio/x-far" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 16, 16 } }, + load = function() + return __include("music/far") + end, + }, + { + name = "hmp", + category = "music", + path = "music/hmp", + extensions = { "hmp", "hmi" }, + mime = { "audio/x-hmp" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/MidiRender" }, + caps = { decode = true, encode = false, render = true, hmi = true }, + load = function() + return __include("music/hmp") + end, + }, + { + name = "hvl", + category = "music", + path = "music/hvl", + extensions = { "hvl" }, + mime = { "audio/x-hvl" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Hively" }, + caps = { decode = true, encode = false, render = true, channels = { 4, 16 }, subsongs = true }, + load = function() + return __include("music/hvl") + end, + }, + { + name = "it", + category = "music", + path = "music/it", + extensions = { "it" }, + mime = { "audio/it", "audio/x-it" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 64 }, compressedSamples = true }, + load = function() + return __include("music/it") + end, + }, + { + name = "med", + category = "music", + path = "music/med", + extensions = { "med", "mmd0", "mmd1", "mmd2", "mmd3", "omed" }, + mime = { "audio/x-med" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 64 } }, + load = function() + return __include("music/med") + end, + }, + { + name = "midi", + category = "music", + path = "music/midi", + extensions = { "mid", "midi", "smf", "kar", "rmi" }, + mime = { "audio/midi", "audio/x-midi" }, + deps = { "core/Err", "core/Bytes", "codecs/audio/MidiRender", "Types" }, + caps = { decode = true, encode = true, formats = { 0, 1, 2 }, render = true, streaming = true, rmid = true }, + load = function() + return __include("music/midi") + end, + }, + { + name = "mod", + category = "music", + path = "music/mod", + extensions = { "mod", "m15", "stk", "nst" }, + mime = { "audio/x-mod", "audio/mod" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" }, + caps = { decode = true, encode = true, render = true, channels = { 1, 32 } }, + load = function() + return __include("music/mod") + end, + }, + { + name = "mtm", + category = "music", + path = "music/mtm", + extensions = { "mtm" }, + mime = { "audio/x-mtm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 32 } }, + load = function() + return __include("music/mtm") + end, + }, + { + name = "mus", + category = "music", + path = "music/mus", + extensions = { "mus" }, + mime = { "audio/x-mus" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/MidiRender" }, + caps = { decode = true, encode = false, render = true }, + load = function() + return __include("music/mus") + end, + }, + { + name = "okt", + category = "music", + path = "music/okt", + extensions = { "okt", "okta" }, + mime = { "audio/x-okt" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 4, 8 } }, + load = function() + return __include("music/okt") + end, + }, + { + name = "ptm", + category = "music", + path = "music/ptm", + extensions = { "ptm" }, + mime = { "audio/x-ptm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 32 } }, + load = function() + return __include("music/ptm") + end, + }, + { + name = "s3m", + category = "music", + path = "music/s3m", + extensions = { "s3m" }, + mime = { "audio/s3m", "audio/x-s3m" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 32 } }, + load = function() + return __include("music/s3m") + end, + }, + { + name = "sf2", + category = "music", + path = "music/sf2", + extensions = { "sf2" }, + mime = { "audio/x-soundfont" }, + deps = { "core/Err", "core/Bytes", "codecs/audio/SoundFont" }, + caps = { decode = true, encode = false, sm24 = true, sf3 = false }, + load = function() + return __include("music/sf2") + end, + }, + { + name = "stm", + category = "music", + path = "music/stm", + extensions = { "stm" }, + mime = { "audio/x-stm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 4, 4 } }, + load = function() + return __include("music/stm") + end, + }, + { + name = "ult", + category = "music", + path = "music/ult", + extensions = { "ult" }, + mime = { "audio/x-ult" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 32 } }, + load = function() + return __include("music/ult") + end, + }, + { + name = "umx", + category = "music", + path = "music/umx", + extensions = { "umx" }, + mime = { "audio/x-umx" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" }, + caps = { decode = true, encode = false, render = true, container = true }, + load = function() + return __include("music/umx") + end, + }, + { + name = "xm", + category = "music", + path = "music/xm", + extensions = { "xm" }, + mime = { "audio/xm", "audio/x-xm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Adpcm" }, + caps = { decode = true, encode = true, render = true, channels = { 1, 64 } }, + load = function() + return __include("music/xm") + end, + }, + { + name = "xmi", + category = "music", + path = "music/xmi", + extensions = { "xmi", "xmidi" }, + mime = { "audio/x-xmidi" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/audio/MidiRender" }, + caps = { decode = true, encode = false, render = true, songs = true }, + load = function() + return __include("music/xmi") + end, + }, + { + name = "m3u", + category = "playlist", + 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/text/Url", "codecs/text/Text", "core/Sniff" }, + caps = { decode = true, encode = true, hls = true }, + load = function() + return __include("playlist/m3u") + end, + }, + { + name = "pls", + category = "playlist", + path = "playlist/pls", + extensions = { "pls" }, + mime = { "audio/x-scpls", "audio/scpls" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Url", "codecs/text/Text", "core/Sniff" }, + caps = { decode = true, encode = true }, + load = function() + return __include("playlist/pls") + end, + }, + { + name = "xspf", + category = "playlist", + path = "playlist/xspf", + extensions = { "xspf" }, + mime = { "application/xspf+xml" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Url", "codecs/text/Xml" }, + caps = { decode = true, encode = true }, + load = function() + return __include("playlist/xspf") + end, + }, +} + +return list +end +__FILES["Types"] = function() + +-- Types: the standard value types each category decodes to and encodes from, plus small constructors. Every +-- top-level value has a `kind` ("image", "audio", "scene", ...). Shared enums are plain strings; buffers are tightly +-- packed, rows top to bottom, channels interleaved. +local Err = __include("core/Err") + +local Types = {} + +type Err = Err.Err + +-- pixel formats: bytes per pixel. rgba8 is the default every decoder produces unless opts.native asks to keep the +-- source layout. yuv420p: Y plane (w*h) then U and V planes (ceil(w/2) * ceil(h/2) each). +type PixelFormat = "rgba8" | "rgba16" | "rgbaf32" | "rgb8" | "gray8" | "gray16" | "graya8" | "alpha8" | "yuv420p" +local BPP: { [string]: number } = { + rgba8 = 4, + rgba16 = 8, + rgbaf32 = 16, + rgb8 = 3, + gray8 = 1, + gray16 = 2, + graya8 = 2, + alpha8 = 1, +} +Types.BPP = table.freeze(BPP) :: { [string]: number } + +type ImageMeta = { + colorSpace: string?, -- "srgb" (default), "linear", "display-p3", ... + gamma: number?, + icc: buffer?, -- the raw ICC profile + exif: buffer?, -- the raw EXIF block (TIFF header onwards) + dpi: { x: number, y: number }?, + palette: { { number } }?, -- { r, g, b, a } 0..255 per entry, for palette sources + text: { [string]: string }?, -- tEXt / comments + source: { format: string, bitDepth: number?, colorType: string?, [string]: any }?, + [string]: any, +} + +-- one frame of an animation (GIF, APNG, WebP): the image is the frame's own rectangle, composited at x, y +type Frame = { + image: Image, + delay: number, -- seconds + x: number, + y: number, + dispose: "none" | "background" | "previous", + blend: "source" | "over", +} + +type Image = { + kind: "image", + width: number, + height: number, + format: PixelFormat, + pixels: buffer, + frames: { Frame }?, -- animations: frame 1 is also width x height pixels (the composited first frame) + 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, +} + +local Image = {} +function Image.new(width: number, height: number, format: PixelFormat?): Image + local f: PixelFormat = format or "rgba8" + local size + if f == "yuv420p" then + local cw, ch = (width + 1) // 2, (height + 1) // 2 + size = width * height + 2 * cw * ch + else + size = width * height * (BPP[f] or 4) + end + return { + kind = "image", + width = width, + height = height, + format = f, + pixels = buffer.create(size), + frames = nil, + loops = 0, + meta = {}, + } +end +function Image.bpp(format: string): number? + return BPP[format] +end +Types.Image = Image + +type Tags = { [string]: string } -- title, artist, album, date, genre, track, comment, ... + +type Decoder = { + sampleRate: number, + channels: number, + frames: number, -- total sample frames (estimate for VBR streams without an index), 0 = unknown + duration: number, -- seconds + bitrate: number, -- bits per second (average) + tags: Tags, + -- read: interleaved f32, frames read (0 at the end); out is reused when big enough + read: (self: any, n: number, out: buffer?) -> (buffer, number), + seek: (self: any, seconds: number) -> (), + position: (self: any) -> number, -- seconds +} + +type Audio = { + kind: "audio", + sampleRate: number, + channels: number, + frames: number, + samples: buffer, -- interleaved f32, frames * channels * 4 bytes + tags: Tags, + meta: { source: { format: string, [string]: any }?, [string]: any }, +} + +local Audio = {} +function Audio.new(sampleRate: number, channels: number, frames: number): Audio + return { + kind = "audio", + sampleRate = sampleRate, + channels = channels, + frames = frames, + samples = buffer.create(frames * channels * 4), + tags = {}, + meta = {}, + } +end +Types.Audio = Audio + +type Module = { + kind: "music", + title: string, + format: string, -- "mod", "s3m", "xm", "it" (codecs/audio/Tracker); "ahx", "hvl" (codecs/audio/Hively, own render) + channels: number, + patterns: { any }, + order: { number }, + instruments: { any }, + samples: { any }, + render: (self: any, opts: any?) -> Decoder, -- every music file is also audio + meta: { [string]: any }, +} + +type MidiEvent = { tick: number, type: string, channel: number?, data: { number }?, meta: any? } +type Midi = { + kind: "midi", + format: number, -- SMF 0 / 1 / 2 + division: number, -- ticks per quarter note (or SMPTE, negative) + tracks: { { events: { MidiEvent }, name: string? } }, + meta: { [string]: any }, + render: ((self: any, opts: any?) -> Decoder)?, -- set by music/midi decode: the SoundFont synth as an audio Decoder +} +local Midi = {} +function Midi.new(division: number?): Midi + return { kind = "midi", format = 1, division = division or 480, tracks = {}, meta = {} } +end +Types.Midi = Midi + +-- Times: Packet pts / dts / duration are integer ticks of the track's timescale (exact, for remuxing); VideoFrame pts +-- / duration and every `duration` / `seek` argument are seconds. +type Track = { + id: number, -- the container's track number (Matroska TrackNumber, AVI stream index + 1, TS PID, ...) + kind: "video" | "audio" | "subtitle" | "data", + codec: string, -- our codec id: "vp8", "mjpeg", "mpeg1", "h264", "rawvideo"; "pcm_s16le", "mp3", "opus", "vorbis", ... + codecTag: string?, -- the container's own id ("V_VP8", "MJPG", stream_type "0x01", "avc1", ...) + timescale: number, -- ticks per second for pts / dts / duration + duration: number?, -- seconds + default: boolean?, + language: string?, + name: string?, + -- video + width: number?, + height: number?, + frameRate: number?, -- frames per second (nominal; 0 / nil when unknown) + pixelFormat: string?, -- raw video: "yuv420p", "rgb24", "bgr24", ... + -- audio + sampleRate: number?, + channels: number?, + bitsPerSample: number?, + codecDelay: number?, -- seconds of decoder output to drop at the start (encoder priming: Matroska CodecDelay, the + -- first edit's media time of an MP4 audio track) + playDuration: number?, -- seconds to play after the codec delay (an MP4 edit list's length: the end padding cut) + config: buffer?, -- codec configuration (CodecPrivate, avcC, OpusHead, Vorbis headers, AVI strf extra, ...) + [string]: any, +} +type Packet = { + track: number, -- Track.id + pts: number, -- presentation time, ticks + dts: number?, -- decode time, ticks (nil = pts) + duration: number?, -- ticks + keyframe: boolean, + data: buffer, -- the packet's bytes (its own buffer) +} +type Demuxer = { + kind: "demuxer", + format: string, -- the container format name + tracks: { Track }, + duration: number, -- seconds (0 = unknown) + startTime: number, -- seconds: the first video / audio packet's presentation time (VideoFrame times count from it) + meta: { [string]: any }, -- title, tags, ... + packets: (self: any, track: number?) -> () -> Packet?, + read: (self: any, track: number?) -> Packet?, + -- seek: every track to its last keyframe at or before the time + seek: (self: any, seconds: number) -> (), + track: (self: any, kind: string) -> Track?, -- the first (default) track of a kind +} +type VideoFrame = { + image: Image, -- yuv420p (the codecs' native output) or rgba8 (opts.rgba = true, MJPEG without yuv, frames-backed) + pts: number, -- seconds from the start of the stream (the demuxer's startTime) + duration: number, -- seconds + keyframe: boolean?, + index: number, -- 1-based, in output order +} +type VideoDecoder = { + kind: "video", + format: string, -- the container format name ("mkv", "avi", "gif", ...) + codec: string, -- the video codec id ("vp8", "mjpeg", "frames" for animated images) + width: number, + height: number, + frameRate: number, -- frames per second (nominal) + frames: number, -- frame count when known (0 = unknown) + duration: number, -- seconds + track: Track?, -- the video track decoded + nextFrame: (self: any) -> (VideoFrame?, Err?), -- nil, nil at the end + toRGBA: (self: any, frame: VideoFrame | Image) -> Image, -- an rgba8 Image (the frame's own image if already rgba8) + seek: (self: any, seconds: number) -> (), -- the next frame is the first at or after the time (decoded from the keyframe before it) + reset: (self: any) -> (), -- back to the start + audio: Decoder?, -- the first audio track, decoded (nil if none or its codec is unavailable: see audioError) + audioError: Err?, + demuxer: Demuxer?, -- nil for frames-backed videos (animated images) + meta: { [string]: any }, +} +-- a codec's decoder instance (codecs/video/Video registry entries create them): packets in, pictures out +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 + flush: (self: any) -> (), -- end of stream: pictures held for reordering become available to receive() + reset: (self: any) -> (), -- after a seek: drop references / held pictures +} + +-- Indices are 1-based everywhere (node, mesh, material, texture, ...). Accessor data is tightly packed (no stride, no +-- padding, sparse accessors already applied). unorm / snorm types are glTF's normalized integers (value / 255, +-- max(value / 127, -1), ...). Positions are in scene units (meta.unit = metres per unit when known), meta.up is the +-- source's up axis ("y" for glTF / OBJ, "z" for STL / VOX / most CAD) - no format rotates the data on load. +type Accessor = { + data: buffer, -- tightly packed, little endian + type: "f32" | "f64" | "u8" | "u16" | "u32" | "i8" | "i16" | "i32" | "unorm8" | "unorm16" | "snorm8" | "snorm16", + components: number, -- 1 (SCALAR) .. 4 (VEC4), 4 (MAT2), 9 (MAT3), 16 (MAT4) + count: number, + matrix: boolean?, -- components 4 / 9 / 16 are MAT2 / MAT3 / MAT4 (glTF), not VEC4 + name: string?, +} +type Primitive = { + attributes: { [string]: Accessor }, -- POSITION, NORMAL, TANGENT, TEXCOORD_n, COLOR_n, JOINTS_n, WEIGHTS_n; custom + -- attributes start with "_" (glTF convention: PLY extra vertex properties, ...) + indices: Accessor?, + -- "polygons": faces (u32, one size per face) splits indices into n-gons (OBJ / PLY / OFF with triangulate = false; + -- MeshOps.triangulate turns them into triangles) + mode: "triangles" | "lines" | "points" | "triangle_strip" | "triangle_fan" | "line_strip" | "line_loop" | "polygons", + faces: Accessor?, + material: number?, -- index into scene.materials (1-based) + targets: { { [string]: Accessor } }?, -- morph targets (POSITION / NORMAL / TANGENT deltas) + extras: { [string]: any }?, +} +type Mesh = { name: string?, primitives: { Primitive }, weights: { number }?, extras: { [string]: any }? } +type Sampler = { + wrapS: ("repeat" | "clamp" | "mirror")?, -- default "repeat" + wrapT: ("repeat" | "clamp" | "mirror")?, + filter: ("linear" | "nearest")?, -- magnification + minFilter: string?, -- "nearest" | "linear" | "nearest_mipmap_nearest" | ... (glTF names, lower case) +} +type Texture = { + name: string?, + image: Image?, -- decoded (F.model.loadTextures or the caller), never by a model format + data: buffer?, -- the encoded image bytes (embedded / GLB / data: URI / resolved external file) + mime: string?, -- "image/png", "image/jpeg", "image/webp", "image/ktx2", ... + uri: string?, -- the external file name (relative to the model) when the data was not available or not embedded + sampler: Sampler?, + extras: { [string]: any }?, +} +type TextureRef = { + texture: number, -- index into scene.textures (1-based) + texCoord: number?, -- TEXCOORD_n set (default 0) + scale: number?, -- normalTexture scale + strength: number?, -- occlusionTexture strength + -- KHR_texture_transform (texCoord overrides the ref's texCoord) + transform: { offset: { number }?, scale: { number }?, rotation: number?, texCoord: number? }?, +} +type Material = { + name: string?, + baseColor: { number }, -- r, g, b, a linear 0..1 + baseColorTexture: TextureRef?, + metallic: number, + roughness: number, + metallicRoughnessTexture: TextureRef?, + normalTexture: TextureRef?, + occlusionTexture: TextureRef?, + emissive: { number }, + emissiveTexture: TextureRef?, + alphaMode: "opaque" | "mask" | "blend", + alphaCutoff: number, + doubleSided: boolean, + -- glTF material extensions by name (KHR_materials_emissive_strength = { emissiveStrength = 5 }, KHR_materials_unlit + -- = {}, ...), their fields as in glTF except textureInfo objects, which are TextureRefs + extensions: { [string]: any }?, + extras: { [string]: any }?, -- classic Phong (OBJ / FBX): ambient, diffuse, specular, shininess, ... +} +type Node = { + name: string?, + children: { number }, -- node indices (1-based) + mesh: number?, + camera: number?, + light: number?, + skin: number?, + voxels: number?, -- index into scene.voxels (MagicaVoxel shapes; MeshOps.meshVoxels gives them meshes) + translation: { number }?, -- TRS, or matrix (column-major 4x4), not both + rotation: { number }?, -- quaternion x, y, z, w + scale: { number }?, + matrix: { number }?, + weights: { number }?, -- morph target weights + extras: { [string]: any }?, +} +type Camera = { name: string?, type: "perspective" | "orthographic", yfov: number?, aspect: number?, xmag: number?, ymag: number?, znear: number, zfar: number? } +type Light = { name: string?, type: "directional" | "point" | "spot", color: { number }, intensity: number, range: number?, innerCone: number?, outerCone: number? } +type Skin = { name: string?, joints: { number }, inverseBindMatrices: Accessor?, skeleton: number? } +type Channel = { node: number, path: "translation" | "rotation" | "scale" | "weights", input: Accessor, output: Accessor, interpolation: "LINEAR" | "STEP" | "CUBICSPLINE" } +type Animation = { name: string?, channels: { Channel } } + +-- a voxel grid (MagicaVoxel): one byte per cell, 0 = empty, 1..255 = palette index +type VoxelMaterial = { type: string, [string]: any } -- "diffuse" | "metal" | "glass" | "emit" | "blend" | "media" | ..., MATL properties (numbers when numeric) +type Voxels = { + kind: "voxels", + name: string?, + size: { number }, -- x, y, z cells + data: buffer, -- size x * y * z bytes, cell (x, y, z) at x + sx * (y + sy * z) + palette: { { number } }, -- palette[i] = { r, g, b, a } 0..255 (sRGB) for i = 1 .. 255 (shared between a file's models) + materials: { [number]: VoxelMaterial }?, -- by palette index + -- block grids (Minecraft schematics / regions): the exact block state of every cell, data / palette being its + -- colour view (block colours from a default table) + blocks: VoxelBlocks?, + -- true-colour grids (Qubicle): the exact 32-bit colour of every cell as r, g, b, a bytes (u32 little-endian, + -- a = 0 empty), data / palette being an indexed view of it + colors: buffer?, +} +type VoxelBlocks = { + palette: { string }, -- block states ("minecraft:oak_stairs[facing=east,half=bottom]"), palette[1] is index 0 + data: buffer, -- u16 little-endian per cell (same cell order as Voxels.data): 0-based index into palette + blockEntities: { any }?, -- the format's block entity records (NBT compounds; positions relative to the grid) + entities: { any }?, -- entity records (NBT compounds) +} +local Voxels = {} +function Voxels.new(sx: number, sy: number, sz: number, palette: { { number } }?): Voxels + local pal = palette + if not pal then + local p = table.create(255) + for i = 1, 255 do + p[i] = { i, i, i, 255 } + end + pal = p + end + return { kind = "voxels", size = { sx, sy, sz }, data = buffer.create(sx * sy * sz), palette = pal :: { { number } }, materials = nil } +end +function Voxels.get(v: Voxels, x: number, y: number, z: number): number + return buffer.readu8(v.data, x + v.size[1] * (y + v.size[2] * z)) +end +function Voxels.set(v: Voxels, x: number, y: number, z: number, index: number) + buffer.writeu8(v.data, x + v.size[1] * (y + v.size[2] * z), index) +end +Types.Voxels = Voxels + +type Scene = { + kind: "scene", + nodes: { Node }, + roots: { number }, -- top-level node indices + meshes: { Mesh }, + materials: { Material }, + textures: { Texture }, + cameras: { Camera }, + lights: { Light }, + skins: { Skin }, + animations: { Animation }, + voxels: { Voxels }?, -- voxel grids (VOX), referenced by node.voxels + meta: { up: "y" | "z"?, unit: number?, source: { format: string, [string]: any }?, [string]: any }, +} + +local Scene = {} +function Scene.new(): Scene + return { + kind = "scene", + nodes = {}, + roots = {}, + meshes = {}, + materials = {}, + textures = {}, + cameras = {}, + lights = {}, + skins = {}, + animations = {}, + voxels = nil, + meta = {}, + } +end +local COMPONENT_SIZE: { [string]: number } = { + f32 = 4, + f64 = 8, + u8 = 1, + u16 = 2, + u32 = 4, + i8 = 1, + i16 = 2, + i32 = 4, + unorm8 = 1, + unorm16 = 2, + snorm8 = 1, + snorm16 = 2, +} +Types.COMPONENT_SIZE = table.freeze(COMPONENT_SIZE) :: { [string]: number } +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)) + return { data = d, type = type, components = components, count = count } +end +function Scene.material(name: string?): Material + return { + name = name, + baseColor = { 1, 1, 1, 1 }, + metallic = 1, + roughness = 1, + emissive = { 0, 0, 0 }, + alphaMode = "opaque", + alphaCutoff = 0.5, + doubleSided = false, + } +end +function Scene.fromPrimitive(prim: Primitive, name: string?): Scene + local s = Scene.new() + s.meshes[1] = { name = name, primitives = { prim } } + s.nodes[1] = { name = name, children = {}, mesh = 1 } + s.roots[1] = 1 + return s +end +Types.Scene = Scene + +function Scene.reader(acc: Accessor): ((i: number, c: number) -> number)? + local d, n, t = acc.data, acc.components, acc.type + local size = COMPONENT_SIZE[t] + if not size or type(d) ~= "buffer" then + return nil + end + local stride = n * size + local rb = buffer + if t == "f32" then + local f = rb.readf32 + return function(i: number, c: number): number + return f(d, i * stride + c * 4) + end + elseif t == "f64" then + local f = rb.readf64 + return function(i: number, c: number): number + return f(d, i * stride + c * 8) + end + elseif t == "u8" or t == "unorm8" then + local f, k = rb.readu8, if t == "unorm8" then 1 / 255 else 1 + return function(i: number, c: number): number + return f(d, i * stride + c) * k + end + elseif t == "u16" or t == "unorm16" then + local f, k = rb.readu16, if t == "unorm16" then 1 / 65535 else 1 + return function(i: number, c: number): number + return f(d, i * stride + c * 2) * k + end + elseif t == "u32" then + local f = rb.readu32 + return function(i: number, c: number): number + return f(d, i * stride + c * 4) + end + elseif t == "i8" then + local f = rb.readi8 + return function(i: number, c: number): number + return f(d, i * stride + c) + end + elseif t == "snorm8" then + local f = rb.readi8 + return function(i: number, c: number): number + return math.max(f(d, i * stride + c) / 127, -1) + end + elseif t == "i16" then + local f = rb.readi16 + return function(i: number, c: number): number + return f(d, i * stride + c * 2) + end + elseif t == "snorm16" then + local f = rb.readi16 + return function(i: number, c: number): number + return math.max(f(d, i * stride + c * 2) / 32767, -1) + end + elseif t == "i32" then + local f = rb.readi32 + return function(i: number, c: number): number + return f(d, i * stride + c * 4) + end + end + return nil +end + +local IDENTITY = table.freeze({ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }) +Scene.IDENTITY = IDENTITY +function Scene.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 Scene.nodeMatrix(node: Node): { number } + if node.matrix and #node.matrix == 16 then + return node.matrix + end + local t, r, sc = node.translation, node.rotation, node.scale + if not t and not r and not sc then + return IDENTITY + end + local tx, ty, tz = 0, 0, 0 + if t then + tx, ty, tz = t[1] or 0, t[2] or 0, t[3] or 0 + end + local x, y, z, w = 0, 0, 0, 1 + if r then + x, y, z, w = r[1] or 0, r[2] or 0, r[3] or 0, r[4] or 1 + end + local sx, sy, sz = 1, 1, 1 + if sc then + sx, sy, sz = sc[1] or 1, sc[2] or 1, sc[3] or 1 + end + 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)) * sx, (2 * (xy + wz)) * sx, (2 * (xz - wy)) * sx, 0, + (2 * (xy - wz)) * sy, (1 - 2 * (xx + zz)) * sy, (2 * (yz + wx)) * sy, 0, + (2 * (xz + wy)) * sz, (2 * (yz - wx)) * sz, (1 - 2 * (xx + yy)) * sz, 0, + tx, ty, tz, 1, + } +end +type Placed = { primitive: Primitive, matrix: { number }, node: number, mesh: number } +function Scene.flatten(scene: Scene): { Placed } + local out: { Placed } = {} + local nodes = scene.nodes or {} + local roots = scene.roots + if not roots or #roots == 0 then + local child = {} + for _, n in nodes do + for _, c in n.children or {} do + child[c] = true + end + end + roots = {} + for i in nodes do + if not child[i] then + table.insert(roots, i) + end + end + end + local seen: { [number]: boolean } = {} + local function visit(i: number, parent: { number }) + local node = nodes[i] + if not node or seen[i] then + return + end + seen[i] = true + local m = Scene.nodeMatrix(node) + local world = if parent == IDENTITY then m elseif m == IDENTITY then parent else Scene.mul(parent, m) + local mesh = node.mesh and scene.meshes[node.mesh] + if mesh then + for _, p in mesh.primitives do + table.insert(out, { primitive = p, matrix = world, node = i, mesh = node.mesh :: number }) + end + end + for _, c in node.children or {} do + visit(c, world) + end + end + for _, r in roots do + visit(r, IDENTITY) + end + return out +end + +-- the STEP entity graph; B-rep bodies and tessellation come from the injected brep plug-in (Rosetta.plugins.brep) +-- complex (external mapping) instances: type = "COMPLEX", args = {}, parts = { { type, args } } in file order; +-- section = the DATA section index when a file has more than one (edition 3) +type StepEntity = { id: number, type: string, args: { any }, parts: { { type: string, args: { any } } }?, section: number? } +type Cad = { + kind: "cad", + schema: string, -- "AP203", "AP214", "AP242", ... + header: { [string]: any }, + entities: { [number]: StepEntity }, + meta: { [string]: any }, +} + +type Font = { + kind: "font", + info: { family: string?, style: string?, fullName: string?, [string]: any }, + unitsPerEm: number, + ascent: number, + descent: number, + lineGap: number, + glyphIndex: (self: any, codepoint: number) -> number, -- 0 = .notdef + advance: (self: any, glyph: number) -> number, -- font units + kern: (self: any, a: number, b: number) -> number, + outline: (self: any, glyph: number) -> { { op: string, [number]: number } }?, -- moveTo / lineTo / quadTo / cubicTo + rasterize: (self: any, glyph: number, px: number) -> Image?, -- alpha8 + pages: { Image }?, -- bitmap fonts (BMFont) + bitmap: BitmapStrike?, -- bitmap fonts with per-glyph bitmaps (BDF, PCF, PSF, FON): codecs/font/Bitmap + meta: { [string]: any }, +} +-- one bitmap glyph: a 1-bit (or grey) image in pixels with y down, placed relative to the pen on the baseline +type BitmapGlyph = { + codepoint: number?, -- Unicode (nil for unencoded glyphs) + name: string?, -- glyph name (BDF STARTCHAR, PCF glyph names, PostScript names) + width: number, -- bitmap width / height in pixels + height: number, + left: number, -- x of the bitmap's left column relative to the pen + top: number, -- y of the bitmap's top row above the baseline (BDF: BBXoff + BBh) + advance: number, -- pen advance in pixels + pixels: buffer, -- u8 per pixel (width * height, rows top down): 0 = off, 255 = on (grey fonts use 1..254) +} +type BitmapStrike = { + size: number, -- pixel size (em height in pixels) + ascent: number, -- pixels above the baseline + descent: number, -- pixels below the baseline (positive) + glyphs: { BitmapGlyph }, -- glyph index i + 1 is font glyph i (glyph 0 = the default / .notdef glyph) + default: number?, -- glyph index (0-based) used for unmapped code points + map: { [number]: number }?, -- extra code point -> glyph index (0-based) mappings (several code points on one glyph) +} + +type ArchiveEntry = { name: string, size: number, compressedSize: number?, method: string?, mtime: number?, dir: boolean } +type Archive = { + kind: "archive", + format: string, + list: (self: any) -> { ArchiveEntry }, + read: (self: any, name: string) -> (buffer?, Err?), + add: (self: any, name: string, data: buffer | string, opts: any?) -> (), + write: (self: any, opts: any?) -> (buffer?, Err?), + meta: { [string]: any }, +} + +-- data formats decode to plain Luau values; JSON null / YAML ~ / CBOR null is this sentinel (nil cannot sit in a +-- table). XML decodes to XmlNode trees. Byte strings (msgpack bin, CBOR bytes, plist data) are buffers. +local nullMeta = { __tostring = function() + return "null" +end } +Types.null = table.freeze(setmetatable({}, nullMeta)) + +-- Objects (maps) whose key order matters, and empty objects (which would otherwise read back as empty arrays), carry +-- an "object" metatable with their key order. Decoders mark empty objects always and every object when asked +-- (opts.ordered); encoders write an object's keys in that order (keys added later, or plain tables: sorted). +local OBJECT = { __object = true } +local objectMeta: { [any]: { any } } = setmetatable({}, { __mode = "k" }) :: any -- object -> its key order +function Types.object(t: { [any]: any }?, keys: { any }?): { [any]: any } + local o: { [any]: any } = t or {} + if getmetatable(o) == nil then + setmetatable(o, OBJECT) + end + objectMeta[o] = keys or {} + return o +end +function Types.isObject(v: any): boolean + return type(v) == "table" and objectMeta[v] ~= nil +end +function Types.set(o: { [any]: any }, k: any, v: any) + local order = objectMeta[o] + if order and o[k] == nil and v ~= nil then + table.insert(order, k) + end + o[k] = v +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 +Types.keyLess = keyLess + +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 +function Types.keys(t: { [any]: any }): { any } + local order = objectMeta[t] + local out, seen = {}, {} + if order then + for _, k in order do + if t[k] ~= nil and not seen[k] then + seen[k] = true + table.insert(out, k) + end + end + end + local rest = {} + for k in next, t do + if not seen[k] then + table.insert(rest, k) + end + end + if #rest > 0 then + table.sort(rest, keyLess) + table.move(rest, 1, #rest, #out + 1, out) + end + return out +end + +-- Dates and times (TOML datetimes, plist <date>, CBOR tags 0 / 1, msgpack timestamps). Fields present depend on the +-- kind: "datetime" (with offset: an instant), "datetime-local", "date-local", "time-local". offset is in minutes +-- east of UTC (nil = local time). tostring gives RFC 3339 ("1979-05-27T07:32:00.5-07:00", "07:32:00", ...). +type Date = { + kind: "datetime" | "datetime-local" | "date-local" | "time-local", + year: number?, + month: number?, + day: number?, + hour: number?, + minute: number?, + second: number?, + nanosecond: number?, -- 0 .. 999999999 + offset: number?, -- minutes east of UTC +} +local DateMeta = {} +local function p2(n: number): string + return string.format("%02d", n) +end +local function fmtDate(d: any): string + 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 = s .. "T" + end + s ..= p2(d.hour) .. ":" .. p2(d.minute or 0) .. ":" .. p2(d.second or 0) + local ns = d.nanosecond or 0 + if ns > 0 then + local f = string.format("%09d", ns) + s ..= "." .. (string.gsub(f, "0+$", "")) + end + if d.offset then + if d.offset == 0 then + s ..= "Z" + else + local o = math.abs(d.offset) + s ..= (if d.offset < 0 then "-" else "+") .. p2(o // 60) .. ":" .. p2(o % 60) + end + end + end + return s +end +DateMeta.__tostring = fmtDate +DateMeta.__eq = function(a: any, b: any): boolean + return fmtDate(a) == fmtDate(b) and a.kind == b.kind +end +local DateLib = {} +-- days since 1970-01-01 of a civil date (proleptic Gregorian; Howard Hinnant's algorithm) +local function daysFromCivil(y: number, m: number, d: number): number + y = if m <= 2 then y - 1 else y + local era = (if y >= 0 then y else y - 399) // 400 + local yoe = y - era * 400 + local mp = (m + 9) % 12 + local doy = (153 * mp + 2) // 5 + d - 1 + local doe = yoe * 365 + yoe // 4 - yoe // 100 + doy + return era * 146097 + doe - 719468 +end +local function civilFromDays(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 +DateLib.civilFromDays = civilFromDays -- days since 1970-01-01 -> year, month, day (proleptic Gregorian) +DateLib.daysFromCivil = daysFromCivil -- year, month, day -> days since 1970-01-01 +local MDAYS = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } +function DateLib.new(f: { [string]: any }): Date + local d: any = {} + for k, v in f do + d[k] = v + end + if d.kind == nil then + d.kind = if d.year and d.hour then (if d.offset then "datetime" else "datetime-local") + elseif d.year then "date-local" + else "time-local" + end + return setmetatable(d, DateMeta) :: any +end +function DateLib.is(v: any): boolean + return type(v) == "table" and getmetatable(v) == DateMeta +end +function DateLib.valid(d: Date): boolean + if d.year then + local y, m, dd = d.year, d.month or 0, d.day or 0 + if y < 0 or y > 9999 or m < 1 or m > 12 or dd < 1 or dd > MDAYS[m] then + return false + end + if m == 2 and dd == 29 and not (y % 4 == 0 and (y % 100 ~= 0 or y % 400 == 0)) then + return false + end + end + if d.hour then + if d.hour > 23 or (d.minute or 0) > 59 or (d.second or 0) > 60 then + return false + end + end + if d.offset and math.abs(d.offset) >= 24 * 60 then + return false + end + return true +end +-- parse: RFC 3339 / ISO 8601 date-times and the TOML partial forms; lower-case t / z accepted +function DateLib.parse(s: string): Date? + local d: any = {} + 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 :: string + if rest == "" then + return if DateLib.valid(d) then DateLib.new(d) else nil + end + local sep = string.sub(rest, 1, 1) + if sep ~= "T" and sep ~= "t" and sep ~= " " then + return nil + end + rest = string.sub(rest, 2) + end + local h, mi, r2 = string.match(rest, "^(%d%d):(%d%d)(.*)$") + if not h then + return nil + end + d.hour, d.minute = tonumber(h), tonumber(mi) + rest = r2 :: string + local sec, r3 = string.match(rest, "^:(%d%d)(.*)$") + if not sec then + return nil + end + d.second = tonumber(sec) + rest = r3 :: string + local frac, r4 = string.match(rest, "^%.(%d+)(.*)$") + if frac then + d.nanosecond = tonumber(string.sub(frac .. "000000000", 1, 9)) + rest = r4 :: string + else + d.nanosecond = 0 + end + if rest ~= "" then + if not d.year then + return nil + end + if rest == "Z" or rest == "z" then + d.offset = 0 + else + local sign, oh, om = string.match(rest, "^([%+%-])(%d%d):(%d%d)$") + if not sign then + return nil + end + local oh_n, om_n = tonumber(oh) :: number, tonumber(om) :: number + if oh_n > 23 or om_n > 59 then + return nil + end + d.offset = (oh_n * 60 + om_n) * (if sign == "-" then -1 else 1) + end + end + return if DateLib.valid(d) then DateLib.new(d) else nil +end +function DateLib.toUnix(d: Date): number + local days = if d.year then daysFromCivil(d.year, d.month or 1, d.day or 1) else 0 + local s = days * 86400 + (d.hour or 0) * 3600 + (d.minute or 0) * 60 + (d.second or 0) - (d.offset or 0) * 60 + return s + (d.nanosecond or 0) / 1e9 +end +function DateLib.fromUnix(t: number, offset: number?): Date + local off = offset or 0 + local whole = math.floor(t) + local ns = math.floor((t - whole) * 1e9 + 0.5) + if ns >= 1e9 then + whole += 1 + ns -= 1e9 + end + local lt = whole + off * 60 + local days = lt // 86400 + local secs = lt - days * 86400 + local y, m, dd = civilFromDays(days) + return DateLib.new({ + kind = "datetime", + year = y, + month = m, + day = dd, + hour = secs // 3600, + minute = (secs // 60) % 60, + second = secs % 60, + nanosecond = ns, + offset = off, + }) +end +Types.Date = table.freeze(DateLib) + +-- XML: an element, or (name starting with "#") a "#document" / "#comment" / "#cdata" / "#pi" / "#doctype" node with +-- its content in text. attrs is a Types.object (attribute order kept). Text children are plain strings. +type XmlNode = { + name: string, + attrs: { [string]: string }, + children: { XmlNode | string }, + parent: XmlNode?, + text: string?, -- "#comment" / "#cdata" / "#pi" (the data after the target) / "#doctype" content + target: string?, -- "#pi": the target + ns: string?, -- the namespace URI (opts.namespaces) + [string]: any, +} + +type Paint = { type: "color", color: { number } } | { type: "linear" | "radial", stops: { { number } }, [string]: any } +type VectorPath = { + d: { { op: string, [number]: number } }, -- absolute M / L / C / Q / Z commands + fill: Paint?, + fillRule: "nonzero" | "evenodd", + stroke: Paint?, + 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?, +} +type Vector = { + kind: "vector", + width: number, + height: number, + viewBox: { number }, -- x, y, w, h + paths: { VectorPath }, + meta: { [string]: any }, +} +local Vector = {} +function Vector.new(width: number, height: number): Vector + return { kind = "vector", width = width, height = height, viewBox = { 0, 0, width, height }, paths = {}, meta = {} } +end +Types.Vector = Vector + +-- 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`). +type LayerMask = { image: Image, x: number, y: number, default: number, disabled: boolean? } +type Layer = { name: string, image: Image, x: number, y: number, opacity: number, blend: string, visible: boolean, children: { Layer }?, clip: boolean?, mask: LayerMask? } +type Layered = { + kind: "layered", + width: number, + height: number, + layers: { Layer }, -- bottom to top (a tree: groups have children); animations: frame 1's layers + frames: { { layers: { Layer }, delay: number } }?, -- animations (Aseprite): every frame's layers, delay in seconds + meta: { [string]: any }, +} +local Layered = {} +function Layered.new(width: number, height: number): Layered + return { kind = "layered", width = width, height = height, layers = {}, frames = nil, meta = {} } +end +function Layered.layer(name: string, image: Image, x: number?, y: number?): Layer + return { name = name, image = image, x = x or 0, y = y or 0, opacity = 1, blend = "normal", visible = true } +end +function Layered.group(name: string, children: { Layer }): Layer + return { name = name, image = Image.new(0, 0), x = 0, y = 0, opacity = 1, blend = "passThrough", visible = true, children = children } +end +Types.Layered = Layered + +-- gids are Tiled's: 0 = empty, the tile's firstGid-relative index, flip / rotation flags in the top bits (kept). +-- Tilesets keep their image as a reference (imageSource: the path as written; image: an Image only if a caller +-- loads it). Extra Tiled fields sit next to these (offsetX / offsetY, parallax, tintColor, class, chunks of infinite +-- maps, objects' shapes, per-tile data, ...: see vector/tiled). +type Tileset = { name: string, firstGid: number, tileWidth: number, tileHeight: number, columns: number, count: number, image: Image?, source: string?, [string]: any } +type TileLayer = { name: string, type: "tiles" | "objects" | "image" | "group", width: number?, height: number?, data: { number }?, objects: { any }?, visible: boolean, opacity: number, properties: { [string]: any }, [string]: any } +type TileMap = { + kind: "tilemap", + width: number, + height: number, + tileWidth: number, + tileHeight: number, + orientation: string, + tilesets: { Tileset }, + layers: { TileLayer }, + properties: { [string]: any }, + meta: { [string]: any }, + [string]: any, +} +local TileMap = {} +function TileMap.new(width: number, height: number, tileWidth: number, tileHeight: number): TileMap + return { kind = "tilemap", width = width, height = height, tileWidth = tileWidth, tileHeight = tileHeight, orientation = "orthogonal", tilesets = {}, layers = {}, properties = {}, meta = {} } +end +Types.TileMap = TileMap + +type Cue = { start: number, stop: number, text: string, style: string?, id: string?, [string]: any } -- seconds +type Subtitles = { kind: "subtitles", cues: { Cue }, styles: { [string]: any }, meta: { [string]: any } } +local Subtitles = {} +function Subtitles.new(): Subtitles + return { kind = "subtitles", cues = {}, styles = {}, meta = {} } +end +Types.Subtitles = Subtitles + +-- the playlist-luau shape +type PlaylistEntry = { + url: string, + title: string?, + duration: number?, + playable: boolean, + reason: string?, + bandwidth: number?, + codecs: string?, + attributes: { [string]: string }?, + byteRange: { length: number, offset: number? }?, +} +type Playlist = { + kind: "playlist", + format: string, -- "m3u", "pls", "hls", "xspf" + entries: { PlaylistEntry }, + warnings: { string }, + title: string?, + hls: { [string]: any }?, + meta: { [string]: any }, +} + +-- what every format folder's init.luau returns (checked by tools/lint.sh CONTRACT; see docs/STYLE.md) +type Caps = { decode: boolean, encode: boolean, [string]: any } +type Format = { + name: string, + category: string, + extensions: { string }, + mime: { string }, + deps: { string }, + sniff: (r: any) -> number, -- confidence 0..1 from the first bytes (a core/Bytes Reader); must not consume / throw + decode: ((r: any, opts: any?) -> (any, Err?))?, + encode: ((value: any, opts: any?) -> (buffer?, Err?))?, + open: ((r: any, opts: any?) -> (any, Err?))?, -- streaming categories (audio / video) + caps: Caps, +} + +-- the categories, in the order F.formats() lists them; kind = the `kind` of the values they decode to +Types.CATEGORIES = table.freeze({ + image = "image", + audio = "audio", + video = "video", + model = "scene", + cad = "cad", + font = "font", + archive = "archive", + data = "data", + vector = "vector", + layered = "layered", + subtitle = "subtitles", + music = "music", + playlist = "playlist", +} :: { [string]: string }) + +return Types +end +__FILES["codecs/audio/Adpcm"] = @native function() + + + +-- codecs/audio/Adpcm: the 4-bit ADPCM family, decode (and encode where it is cheap). +-- ADX, PS-ADPCM and Nintendo DSP decoding follow vgmstream r2117 (ISC, licenses/vgmstream-LICENSE.txt) bit-exactly: the +-- ADX scale + 1 and version 3 rounding, PS-ADPCM's float filter (exact in integers below 2^17), DSP's 1024 rounding. +local readu8, readi16, readu16, readi32 = buffer.readu8, buffer.readi16, buffer.readu16, buffer.readi32 +local writef32, readf32, writei32, writeu8, writeu16 = buffer.writef32, buffer.readf32, buffer.writei32, buffer.writeu8, buffer.writeu16 +local band, rshift, bor, lshift = bit32.band, bit32.rshift, bit32.bor, bit32.lshift +local floor = math.floor + +local Adpcm = {} + +local IMA_STEP = { + 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, 50, 55, 60, 66, 73, 80, 88, 97, 107, 118, + 130, 143, 157, 173, 190, 209, 230, 253, 279, 307, 337, 371, 408, 449, 494, 544, 598, 658, 724, 796, 876, 963, 1060, + 1166, 1282, 1411, 1552, 1707, 1878, 2066, 2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358, 5894, 6484, + 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899, 15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767, +} +local IMA_ADJ = { -1, -1, -1, -1, 2, 4, 6, 8, -1, -1, -1, -1, 2, 4, 6, 8 } +-- IMA_DIFF[index * 8 + (nibble & 7) + 1]: the shift-and-add difference (step/8 + bits of step/4, step/2, step), as +-- the IMA reference computes it (not (2n + 1) * step / 8, which rounds differently) +local IMA_DIFF = table.create(89 * 8, 0) +-- IMA_NEXT[index * 16 + nibble + 1]: the next step index +local IMA_NEXT = table.create(89 * 16, 0) +for i = 0, 88 do + local step = IMA_STEP[i + 1] + for n = 0, 7 do + local d = rshift(step, 3) + if band(n, 1) ~= 0 then + d += rshift(step, 2) + end + if band(n, 2) ~= 0 then + d += rshift(step, 1) + end + if band(n, 4) ~= 0 then + d += step + end + IMA_DIFF[i * 8 + n + 1] = d + end + for n = 0, 15 do + IMA_NEXT[i * 16 + n + 1] = math.clamp(i + IMA_ADJ[n + 1], 0, 88) + end +end +Adpcm.IMA_STEP = IMA_STEP + +-- IMA nibble q is in byte p + q // 2, the low half first unless hi +@native function Adpcm.ima(src: buffer, p: number, q0: number, qs: number, count: number, hi: boolean, st: buffer, so: number, + dst: buffer, d: number, ds: number) + local pred = readi32(st, so) + local index = math.clamp(readi32(st, so + 4), 0, 88) + local q = q0 + local o = d * 4 + local os = ds * 4 + for _ = 1, count do + local b = readu8(src, p + rshift(q, 1)) + local nib + if (band(q, 1) == 0) == hi then + nib = rshift(b, 4) + else + nib = band(b, 15) + end + local diff = IMA_DIFF[index * 8 + band(nib, 7) + 1] + if nib >= 8 then + pred -= diff + if pred < -32768 then + pred = -32768 + end + else + pred += diff + if pred > 32767 then + pred = 32767 + end + end + index = IMA_NEXT[index * 16 + nib + 1] + writef32(dst, o, pred / 32768) + o += os + q += qs + end + writei32(st, so, pred) + writei32(st, so + 4, index) +end + +-- Apple ima4: 34 bytes: a big-endian header (the predictor's top 9 bits, 7-bit step index), 64 nibbles low first; +-- Apple's decoders keep the full-precision predictor while the header agrees (same step index, within 127) +@native function Adpcm.imaQt(src: buffer, p: number, st: buffer, so: number, dst: buffer, d: number, ds: number) + local h = readu8(src, p) * 256 + readu8(src, p + 1) + local pred = band(h, 0xFF80) + if pred >= 32768 then + pred -= 65536 + end + local index = band(h, 0x7F) + if index ~= readi32(st, so + 4) or math.abs(pred - readi32(st, so)) > 0x7F then + writei32(st, so, pred) + writei32(st, so + 4, index) + end + Adpcm.ima(src, p + 2, 0, 1, 64, false, st, so, dst, d, ds) +end + +-- Microsoft IMA block: per channel s16 predictor (= the first sample), u8 step index, pad; then 4-byte groups +-- (8 nibbles, low first) per channel in turn +@native function Adpcm.imaWav(src: buffer, off: number, avail: number, ch: number, spb: number, dst: buffer, d: number): number + if avail < 4 * ch then + return 0 + end + local groups = (avail - 4 * ch) // (4 * ch) + local frames = math.min(spb, 1 + groups * 8) + local o = d * 4 + for c = 0, ch - 1 do + local pred = readi16(src, off + c * 4) + local index = math.min(readu8(src, off + c * 4 + 2), 88) + writef32(dst, o + c * 4, pred / 32768) + local f = 1 + local g = 0 + while f < frames do + local p = off + 4 * ch + (g * ch + c) * 4 + local k = 0 + while k < 8 and f < frames do + local b = readu8(src, p + rshift(k, 1)) + local nib = if band(k, 1) == 0 then band(b, 15) else rshift(b, 4) + local diff = IMA_DIFF[index * 8 + band(nib, 7) + 1] + if nib >= 8 then + pred -= diff + if pred < -32768 then + pred = -32768 + end + else + pred += diff + if pred > 32767 then + pred = 32767 + end + end + index = IMA_NEXT[index * 16 + nib + 1] + writef32(dst, o + (f * ch + c) * 4, pred / 32768) + f += 1 + k += 1 + end + g += 1 + end + end + return frames +end + +local MS_ADAPT = { 230, 230, 230, 230, 307, 409, 512, 614, 768, 614, 512, 409, 307, 230, 230, 230 } +Adpcm.MS_COEF1 = { 256, 512, 0, 192, 240, 460, 392 } +Adpcm.MS_COEF2 = { 0, -256, 0, 64, 0, -208, -232 } + +-- MS ADPCM block: per channel u8 predictor index, s16 delta, s16 sample 1, s16 sample 2 (each field for every channel +-- in turn), then nibbles high first, channels interleaved per nibble; coefficients 256 = 1.0 +@native function Adpcm.msBlock(src: buffer, off: number, avail: number, ch: number, spb: number, dst: buffer, d: number, + coefs: buffer, ncoef: number, state: buffer): number + local hdr = 7 * ch + if avail < hdr or ncoef < 1 then + return 0 + end + local frames = math.min(spb, 2 + ((avail - hdr) * 2) // ch) + local o = d * 4 + for c = 0, ch - 1 do + local pi = math.min(readu8(src, off + c), ncoef - 1) + local idelta = readi16(src, off + ch + c * 2) + local s1 = readi16(src, off + 3 * ch + c * 2) + local s2 = readi16(src, off + 5 * ch + c * 2) + local so = c * 20 + writei32(state, so, readi32(coefs, pi * 8)) + writei32(state, so + 4, readi32(coefs, pi * 8 + 4)) + writei32(state, so + 8, idelta) + writei32(state, so + 12, s1) + writei32(state, so + 16, s2) + writef32(dst, o + c * 4, s2 / 32768) + if frames > 1 then + writef32(dst, o + (ch + c) * 4, s1 / 32768) + end + end + local total = (frames - 2) * ch + for k = 0, total - 1 do + local b = readu8(src, off + hdr + rshift(k, 1)) + local nib = if band(k, 1) == 0 then rshift(b, 4) else band(b, 15) + local so = (k % ch) * 20 + local c1, c2 = readi32(state, so), readi32(state, so + 4) + local idelta = readi32(state, so + 8) + local s1, s2 = readi32(state, so + 12), readi32(state, so + 16) + local p = s1 * c1 + s2 * c2 + p = if p >= 0 then p // 256 else -((-p) // 256) + p += (if nib >= 8 then nib - 16 else nib) * idelta + if p > 32767 then + p = 32767 + elseif p < -32768 then + p = -32768 + end + idelta = (MS_ADAPT[nib + 1] * idelta) // 256 + if idelta < 16 then + idelta = 16 + elseif idelta > 2796202 then -- INT_MAX / 768 + idelta = 2796202 + end + writei32(state, so + 8, idelta) + writei32(state, so + 12, p) + writei32(state, so + 16, s1) + writef32(dst, o + (2 * ch + k) * 4, p / 32768) + end + return frames +end + +local F32 = buffer.create(4) +@native local function f32(x: number): number + writef32(F32, 0, x) + return readf32(F32, 0) +end + +-- coef1, coef2 (12 fractional bits): the 2-pole high-pass predictor from the header's cutoff, in single precision as +-- CRI's decoders (and vgmstream) compute it +@native function Adpcm.adxCoefs(cutoff: number, rate: number): (number, number) + if rate <= 0 then + return 0, 0 + end + local z = f32(math.cos(f32(2 * math.pi * cutoff / rate))) + local a = f32(math.sqrt(2) - z) + local b = f32(math.sqrt(2) - 1) + local c = f32(f32(a - f32(math.sqrt(f32(f32(a + b) * f32(a - b))))) / b) + local c1 = c * 8192 + local c2 = f32(c * c) * -4096 + c1 = if c1 >= 0 then floor(c1) else -floor(-c1) + c2 = if c2 >= 0 then floor(c2) else -floor(-c2) + return c1, c2 +end + +-- ADX frame: s16 big-endian scale, 32 nibbles high first. v3 shifts each product on its own; scale 0x8001 (CRI's end +-- marker) decodes as silence +@native function Adpcm.adx(src: buffer, p: number, pstride: number, nframes: number, c1: number, c2: number, v3: boolean, + st: buffer, so: number, dst: buffer, d: number, ds: number) + local h1, h2 = readi32(st, so), readi32(st, so + 4) + local o = d * 4 + local os = ds * 4 + for f = 0, nframes - 1 do + local fp = p + f * pstride + local scale = readu8(src, fp) * 256 + readu8(src, fp + 1) + if scale == 0x8001 then + scale = 0 + elseif scale >= 32768 then + scale -= 65535 -- the signed value + 1 + else + scale += 1 + end + for k = 0, 31 do + local b = readu8(src, fp + 2 + rshift(k, 1)) + local n = if band(k, 1) == 0 then rshift(b, 4) else band(b, 15) + if n >= 8 then + n -= 16 + end + local s + if v3 then + s = n * scale + (c1 * h1) // 4096 + (c2 * h2) // 4096 + else + s = n * scale + (c1 * h1 + c2 * h2) // 4096 + end + if s > 32767 then + s = 32767 + elseif s < -32768 then + s = -32768 + end + h2 = h1 + h1 = s + writef32(dst, o, s / 32768) + o += os + end + end + writei32(st, so, h1) + writei32(st, so + 4, h2) +end + +local PSX1 = { 0, 60, 115, 98, 122 } +local PSX2 = { 0, 0, -52, -55, -60 } + +-- the filter term (c1 * h1 + c2 * h2) / 64 * 256 truncated, as vgmstream's single-precision float code computes it: +-- exact in integers while the products fit a float's 24 bits +@native local function psxPred(f: number, h1: number, h2: number): number + local x = PSX1[f] * h1 + PSX2[f] * h2 + if h1 > -65536 and h1 < 65536 and h2 > -65536 and h2 < 65536 then + return 4 * x + end + local v = f32(f32(f32(PSX1[f] / 64) * h1) + f32(f32(PSX2[f] / 64) * h2)) * 256 + return if v >= 0 then floor(v) else -floor(-v) +end + +-- PS-ADPCM frame: filter << 4 | shift, flags, 28 nibbles low first. Filters past 4 decode as 0 and shifts past 12 as 9 +-- (as vgmstream); flags 7 is silence; the history keeps the unclipped value +@native function Adpcm.psx(src: buffer, p: number, pstride: number, nframes: number, st: buffer, so: number, dst: buffer, + d: number, ds: number) + local h1, h2 = readi32(st, so), readi32(st, so + 4) + local o = d * 4 + local os = ds * 4 + for f = 0, nframes - 1 do + local fp = p + f * pstride + local head = readu8(src, fp) + local filter = rshift(head, 4) + local shift = band(head, 15) + if filter > 4 then + filter = 0 + end + if shift > 12 then + shift = 9 + end + local mul = 2 ^ (20 - shift) + local fi = filter + 1 + local silent = band(readu8(src, fp + 1), 15) == 7 + for k = 0, 27 do + local s = 0 + if not silent then + local b = readu8(src, fp + 2 + rshift(k, 1)) + local n = if band(k, 1) == 0 then band(b, 15) else rshift(b, 4) + if n >= 8 then + n -= 16 + end + s = (n * mul + psxPred(fi, h1, h2)) // 256 + end + h2 = h1 + h1 = s + if s > 32767 then + s = 32767 + elseif s < -32768 then + s = -32768 + end + writef32(dst, o, s / 32768) + o += os + end + end + writei32(st, so, h1) + writei32(st, so + 4, h2) +end + +-- DSP frame: predictor << 4 | scale shift, 14 nibbles high first; coefs 8 pairs, 11 fractional bits; a predictor +-- index past 7 uses pair 7 +@native function Adpcm.dsp(src: buffer, p: number, count: number, coefs: buffer, co: number, st: buffer, so: number, + dst: buffer, d: number, ds: number) + local h1, h2 = readi32(st, so), readi32(st, so + 4) + local o = d * 4 + local os = ds * 4 + local done = 0 + local fp = p + while done < count do + local head = readu8(src, fp) + local pi = math.min(rshift(head, 4), 7) + local scale = 2 ^ band(head, 15) * 2048 + local c1, c2 = readi32(coefs, co + pi * 8), readi32(coefs, co + pi * 8 + 4) + local n14 = math.min(14, count - done) + for k = 0, n14 - 1 do + local b = readu8(src, fp + 1 + rshift(k, 1)) + local n = if band(k, 1) == 0 then rshift(b, 4) else band(b, 15) + if n >= 8 then + n -= 16 + end + local s = (n * scale + 1024 + c1 * h1 + c2 * h2) // 2048 + if s > 32767 then + s = 32767 + elseif s < -32768 then + s = -32768 + end + h2 = h1 + h1 = s + writef32(dst, o, s / 32768) + o += os + end + done += n14 + fp += 8 + end + writei32(st, so, h1) + writei32(st, so + 4, h2) +end + +@native local function toS16(x: number): number + local v = floor(x * 32768 + 0.5) + if v ~= v then + return 0 + elseif v > 32767 then + return 32767 + elseif v < -32768 then + return -32768 + end + return v +end +Adpcm.toS16 = toS16 + +@native local function imaNibble(x: number, pred: number, index: number): number + local base = index * 8 + 1 + local best, bestErr = 0, math.huge + for m = 0, 7 do + local diff = IMA_DIFF[base + m] + local up = math.min(pred + diff, 32767) + local e = math.abs(x - up) + if e < bestErr then + best, bestErr = m, e + end + local down = math.max(pred - diff, -32768) + e = math.abs(x - down) + if e < bestErr then + best, bestErr = m + 8, e + end + end + return best +end + +@native function Adpcm.imaEncode(x: buffer, xi: number, xs: number, count: number, st: buffer, so: number, out: buffer, + p: number, q0: number, qs: number, hi: boolean) + local pred = readi32(st, so) + local index = math.clamp(readi32(st, so + 4), 0, 88) + local q = q0 + for i = 0, count - 1 do + local v = toS16(readf32(x, (xi + i * xs) * 4)) + local nib = imaNibble(v, pred, index) + local diff = IMA_DIFF[index * 8 + band(nib, 7) + 1] + pred = if nib >= 8 then math.max(pred - diff, -32768) else math.min(pred + diff, 32767) + index = IMA_NEXT[index * 16 + nib + 1] + local bp = p + rshift(q, 1) + local b = readu8(out, bp) + if (band(q, 1) == 0) == hi then + b = bor(band(b, 0x0F), lshift(nib, 4)) + else + b = bor(band(b, 0xF0), nib) + end + writeu8(out, bp, b) + q += qs + end + writei32(st, so, pred) + writei32(st, so + 4, index) +end + +-- Microsoft IMA block: spb = 1 + 8k frames, 4 * ch + (spb - 1) / 2 * ch bytes +@native function Adpcm.imaWavEncode(x: buffer, xf: number, n: number, ch: number, spb: number, st: buffer, out: buffer, off: number) + local groups = (spb - 1) // 8 + for c = 0, ch - 1 do + local so = c * 8 + local first = if n > 0 then toS16(readf32(x, (xf * ch + c) * 4)) else 0 + writei32(st, so, first) + local index = math.clamp(readi32(st, so + 4), 0, 88) + writei32(st, so + 4, index) + buffer.writei16(out, off + c * 4, first) + writeu8(out, off + c * 4 + 2, index) + writeu8(out, off + c * 4 + 3, 0) + local pred = first + for g = 0, groups - 1 do + local gp = off + 4 * ch + (g * ch + c) * 4 + for k = 0, 7 do + local f = 1 + g * 8 + k + local v = if f < n then toS16(readf32(x, ((xf + f) * ch + c) * 4)) else pred + local nib = imaNibble(v, pred, index) + local diff = IMA_DIFF[index * 8 + band(nib, 7) + 1] + pred = if nib >= 8 then math.max(pred - diff, -32768) else math.min(pred + diff, 32767) + index = IMA_NEXT[index * 16 + nib + 1] + local bp = gp + rshift(k, 1) + if band(k, 1) == 0 then + writeu8(out, bp, nib) + else + writeu8(out, bp, bor(readu8(out, bp), lshift(nib, 4))) + end + end + end + writei32(st, so + 4, index) + end +end + +@native local function msTrial(xs: { number }, n: number, c1: number, c2: number, delta0: number, nibs: { number }?): number + local s1, s2 = xs[2], xs[1] + local idelta = delta0 + local err = 0 + for i = 3, n do + local p = s1 * c1 + s2 * c2 + p = if p >= 0 then p // 256 else -((-p) // 256) + local e = xs[i] - p + local nib = if e >= 0 then (e + idelta // 2) // idelta else -((-e + idelta // 2) // idelta) + nib = math.clamp(nib, -8, 7) + local v = math.clamp(p + nib * idelta, -32768, 32767) + err += (xs[i] - v) * (xs[i] - v) + if nibs then + nibs[i] = band(nib, 15) + end + idelta = math.clamp((MS_ADAPT[band(nib, 15) + 1] * idelta) // 256, 16, 2796202) + s2 = s1 + s1 = v + end + return err +end + +-- MS ADPCM block (standard 7 coefficient pairs): 7 * ch + (spb - 2) * ch / 2 bytes +@native function Adpcm.msEncode(x: buffer, xf: number, n: number, ch: number, spb: number, out: buffer, off: number) + local C1, C2 = Adpcm.MS_COEF1, Adpcm.MS_COEF2 + local xs = table.create(spb, 0) + local nibs = table.create(spb, 0) + local all = table.create(spb * ch, 0) + for c = 0, ch - 1 do + for i = 1, spb do + xs[i] = if i <= n then toS16(readf32(x, ((xf + i - 1) * ch + c) * 4)) else 0 + end + local sum = 0 + for i = 3, math.min(spb, 10) do + sum += math.abs(xs[i] - xs[i - 1]) + end + local delta0 = math.clamp(sum // 16, 16, 32767) + local best, bestErr = 1, math.huge + for k = 1, 7 do + local e = msTrial(xs, spb, C1[k], C2[k], delta0, nil) + if e < bestErr then + best, bestErr = k, e + end + end + msTrial(xs, spb, C1[best], C2[best], delta0, nibs) + writeu8(out, off + c, best - 1) + writeu16(out, off + ch + c * 2, delta0) + buffer.writei16(out, off + 3 * ch + c * 2, xs[2] or 0) + buffer.writei16(out, off + 5 * ch + c * 2, xs[1]) + for i = 3, spb do + all[(i - 3) * ch + c + 1] = nibs[i] + end + end + local total = (spb - 2) * ch + for k = 0, total - 1, 2 do + writeu8(out, off + 7 * ch + k // 2, all[k + 1] * 16 + (all[k + 2] or 0)) + end +end + +@native local function adxTrial(xs: { number }, scale: number, c1: number, c2: number, h1: number, h2: number, nibs: { number }?): (number, number, number) + local err = 0 + for k = 1, 32 do + local pred = (c1 * h1 + c2 * h2) // 4096 + local e = xs[k] - pred + local n = if e >= 0 then (e + scale // 2) // scale else -((-e + scale // 2) // scale) + n = math.clamp(n, -8, 7) + local s = math.clamp(n * scale + pred, -32768, 32767) + err += (xs[k] - s) * (xs[k] - s) + if nibs then + nibs[k] = band(n, 15) + end + h2 = h1 + h1 = s + end + return err, h1, h2 +end + +-- ADX v4 rounding; the scale is stored minus one as CRI's decoders add it back +-- (v4 rounding, the scale stored minus one as CRI's decoders add it back) at out[p], pstride bytes apart; the frame +@native function Adpcm.adxEncode(x: buffer, xi: number, xs: number, count: number, c1: number, c2: number, st: buffer, so: number, + out: buffer, p: number, pstride: number) + local h1, h2 = readi32(st, so), readi32(st, so + 4) + local v = table.create(32, 0) + local nibs = table.create(32, 0) + for f = 0, (count + 31) // 32 - 1 do + local peak = 0 + local a, b = h1, h2 + for k = 1, 32 do + local i = f * 32 + k - 1 + local s = if i < count then toS16(readf32(x, (xi + i * xs) * 4)) else 0 + v[k] = s + peak = math.max(peak, math.abs(s - (c1 * a + c2 * b) // 4096)) + b = a + a = s + end + local base = math.max(1, (peak + 6) // 7) + local best, bestErr = base, math.huge + for _, m in { 1, 0.75, 1.25, 0.5, 1.6 } do + local sc = math.clamp(floor(base * m + 0.5), 1, 0x7FFF) + local e = adxTrial(v, sc, c1, c2, h1, h2, nil) + if e < bestErr then + best, bestErr = sc, e + end + end + local _, n1, n2 = adxTrial(v, best, c1, c2, h1, h2, nibs) + h1, h2 = n1, n2 + local fp = p + f * pstride + writeu8(out, fp, rshift(best - 1, 8)) + writeu8(out, fp + 1, band(best - 1, 255)) + for k = 0, 15 do + writeu8(out, fp + 2 + k, nibs[k * 2 + 1] * 16 + nibs[k * 2 + 2]) + end + end + writei32(st, so, h1) + writei32(st, so + 4, h2) +end + +@native function Adpcm.psxEncode(x: buffer, xi: number, xs: number, count: number, st: buffer, so: number, out: buffer, + p: number, pstride: number) + local h1, h2 = readi32(st, so), readi32(st, so + 4) + local v = table.create(28, 0) + local nibs = table.create(28, 0) + for f = 0, (count + 27) // 28 - 1 do + for k = 1, 28 do + local i = f * 28 + k - 1 + v[k] = if i < count then toS16(readf32(x, (xi + i * xs) * 4)) else 0 + end + local bestErr, bestHead = math.huge, 0 + for fi = 1, 5 do + for shift = 0, 12 do + local mul = 2 ^ (20 - shift) + local a, b = h1, h2 + local err = 0 + for k = 1, 28 do + local pred = psxPred(fi, a, b) + local n = floor((v[k] * 256 - pred) / mul + 0.5) + n = if n > 7 then 7 elseif n < -8 then -8 else n + local s = (n * mul + pred) // 256 + local c = if s > 32767 then 32767 elseif s < -32768 then -32768 else s + err += (v[k] - c) * (v[k] - c) + if err >= bestErr then + break + end + b = a + a = s + end + if err < bestErr then + bestErr, bestHead = err, (fi - 1) * 16 + shift + end + end + end + local fi, shift = rshift(bestHead, 4) + 1, band(bestHead, 15) + local mul = 2 ^ (20 - shift) + for k = 1, 28 do + local pred = psxPred(fi, h1, h2) + local n = math.clamp(floor((v[k] * 256 - pred) / mul + 0.5), -8, 7) + nibs[k] = band(n, 15) + h2 = h1 + h1 = (n * mul + pred) // 256 + end + local fp = p + f * pstride + writeu8(out, fp, bestHead) + writeu8(out, fp + 1, 0) + for k = 0, 13 do + writeu8(out, fp + 2 + k, nibs[k * 2 + 1] + nibs[k * 2 + 2] * 16) + end + end + writei32(st, so, h1) + writei32(st, so + 4, h2) +end + +-- ModPlug / OpenMPT ADPCM (sample data marked 0xAD): 16 signed byte deltas, then nibbles low first, each adding its +-- delta to a wrapping signed byte; value / 128 +@native function Adpcm.modplug(src: buffer, p: number, count: number, dst: buffer, d: number) + local tab = table.create(16, 0) + for k = 0, 15 do + tab[k + 1] = buffer.readi8(src, p + k) + end + local v = 0 + for i = 0, count - 1 do + local b = readu8(src, p + 16 + rshift(i, 1)) + local nib = if band(i, 1) == 0 then band(b, 15) else rshift(b, 4) + v = (v + tab[nib + 1] + 128) % 256 - 128 + writef32(dst, (d + i) * 4, v / 128) + end +end + +-- The SWF / FLV ADPCM (SoundFormat 1, Adobe's SWF specification, "ADPCM compression"): an MSB-first bit stream of +-- 2 bits (code size - 2), then blocks of 4096 frames: per channel a signed 16-bit first sample and a 6-bit step +-- index, then 4095 frames of `bits`-bit codes, channels interleaved. A code is IMA generalised to 2..5 bits: sign in +-- the top bit, the magnitude bits adding step, step/2, ... and the final step/2^(bits-1) (as ffmpeg's adpcm_swf and +-- the spec's reference decoder do); the step index moves by SWF_INDEX[bits]. The last block may be short. +local SWF_INDEX: { { number } } = { + { -1, 2 }, + { -1, -1, 2, 4 }, + { -1, -1, -1, -1, 2, 4, 6, 8 }, + { -1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 4, 6, 8, 10, 13, 16 }, +} + +@native function Adpcm.swfFrames(src: buffer, p: number, n: number, ch: number): number + if n < 1 or ch < 1 then + return 0 + end + local bits = rshift(readu8(src, p), 6) + 2 + local total = n * 8 - 2 + local hdr = 22 * ch + local block = hdr + bits * ch * 4095 + local blocks = total // block + local left = total - blocks * block + local frames = blocks * 4096 + if left >= hdr then + frames += 1 + (left - hdr) // (bits * ch) + end + return frames +end + +@native local function msb(src: buffer, p: number, e: number, pos: number, k: number): number + local q = p + rshift(pos, 3) + local v = readu8(src, q) * 65536 + if q + 1 < e then + v += readu8(src, q + 1) * 256 + end + if q + 2 < e then + v += readu8(src, q + 2) + end + return band(rshift(v, 24 - band(pos, 7) - k), lshift(1, k) - 1) +end + +@native function Adpcm.swf(src: buffer, p: number, n: number, ch: number, dst: buffer, d: number): number + local frames = Adpcm.swfFrames(src, p, n, ch) + if frames == 0 then + return 0 + end + local e = p + n + local bits = rshift(readu8(src, p), 6) + 2 + local tab = SWF_INDEX[bits - 1] + local k0 = lshift(1, bits - 2) + local sign = lshift(1, bits - 1) + local mask = sign - 1 + local pred = table.create(ch, 0) + local index = table.create(ch, 0) + local pos = 2 + local o = d * 4 + local done = 0 + while done < frames do + for c = 1, ch do + local v = msb(src, p, e, pos, 16) + if v >= 32768 then + v -= 65536 + end + pred[c] = v + index[c] = msb(src, p, e, pos + 16, 6) + pos += 22 + writef32(dst, o, v / 32768) + o += 4 + end + done += 1 + local m = math.min(4095, frames - done) + for _ = 1, m do + for c = 1, ch do + local code = msb(src, p, e, pos, bits) + pos += bits + local step = IMA_STEP[math.clamp(index[c], 0, 88) + 1] + local diff = 0 + local k = k0 + while k > 0 do + if band(code, k) ~= 0 then + diff += step + end + step = rshift(step, 1) + k = rshift(k, 1) + end + diff += step + local v = pred[c] + if band(code, sign) ~= 0 then + v -= diff + else + v += diff + end + v = math.clamp(v, -32768, 32767) + pred[c] = v + index[c] = math.clamp(index[c] + tab[band(code, mask) + 1], 0, 88) + writef32(dst, o, v / 32768) + o += 4 + end + end + done += m + end + return frames +end + +return Adpcm +end +__FILES["codecs/image/Yuv"] = @native function() + + + +-- codecs/image/Yuv: planar 4:2:0 Y'CbCr <-> rgba8, BT.601 / BT.709, limited or full range. +-- yuv -> rgb: nearest chroma, swscale's default 16-bit coefficients (within about one level of ffmpeg -pix_fmt rgba); +-- rgb -> yuv: each 2x2 block averaged for the chroma. +local Types = __include("Types") + +local readu8, writeu8, writeu32 = buffer.readu8, buffer.writeu8, buffer.writeu32 +local bcreate = buffer.create +local floor = math.floor + +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: { [string]: { kr: number, kb: number } } = { + bt601 = { kr = 0.299, kb = 0.114 }, + bt709 = { kr = 0.2126, kb = 0.0722 }, +} + +type Coeffs = { ys: number, yo: number, crv: number, cgu: number, cgv: number, cbu: number, cs: number } + +local cache: { [string]: Coeffs } = {} +@native local function coeffs(range: string?, matrix: string?): Coeffs + local key = (range or "limited") .. (matrix or "bt601") + local c = cache[key] + if c then + return c + end + local m = MATRIX[matrix or "bt601"] or MATRIX.bt601 + local kr, kb = m.kr, m.kb + local kg = 1 - kr - kb + local full = range == "full" + local ys = if full then 1 else 255 / 219 + local cs = if full then 1 else 255 / 224 + c = { + ys = floor(ys * 65536 + 0.5), + yo = if full then 0 else 16, + crv = floor(2 * (1 - kr) * cs * 65536 + 0.5), + cbu = floor(2 * (1 - kb) * cs * 65536 + 0.5), + cgu = floor(2 * (1 - kb) * kb / kg * cs * 65536 + 0.5), + cgv = floor(2 * (1 - kr) * kr / kg * cs * 65536 + 0.5), + cs = cs, + } + cache[key] = c + return c +end + +local CLIP = bcreate(2304) +for i = 0, 2303 do + writeu8(CLIP, i, math.clamp(i - 1024, 0, 255)) +end + +@native function Yuv.toRgba(src: buffer, w: number, h: number, uo: number, vo: number, cw: number, range: string?, matrix: string?, out: buffer?): buffer + local dst = out or bcreate(w * h * 4) + local c = coeffs(range, matrix) + local ys, yo, crv, cgu, cgv, cbu = c.ys, c.yo, c.crv, c.cgu, c.cgv, c.cbu + local ch = (h + 1) // 2 + if buffer.len(src) < vo + cw * ch or buffer.len(dst) < w * h * 4 or uo + cw * ch > buffer.len(src) then + return dst + end + for y = 0, h - 1 do + local yrow = y * w + local crow = (y // 2) * cw + local o = yrow * 4 + for x = 0, w - 1, 2 do + local ci = crow + (x // 2) + local u = readu8(src, uo + ci) - 128 + local v = readu8(src, vo + ci) - 128 + local rv = (crv * v + 32768) // 65536 + local gv = (cgu * u + cgv * v + 32768) // 65536 + local bu = (cbu * u + 32768) // 65536 + local yy = (ys * (readu8(src, yrow + x) - yo) + 32768) // 65536 + 1024 + writeu32(dst, o, readu8(CLIP, yy + rv) + readu8(CLIP, yy - gv) * 256 + readu8(CLIP, yy + bu) * 65536 + 0xff000000) + if x + 1 < w then + yy = (ys * (readu8(src, yrow + x + 1) - yo) + 32768) // 65536 + 1024 + writeu32(dst, o + 4, readu8(CLIP, yy + rv) + readu8(CLIP, yy - gv) * 256 + readu8(CLIP, yy + bu) * 65536 + 0xff000000) + end + o += 8 + end + end + return dst +end + +@native function Yuv.fromRgba(src: buffer, w: number, h: number, range: string?, matrix: string?, out: buffer?): buffer + local cw, ch = (w + 1) // 2, (h + 1) // 2 + local uo, vo = w * h, w * h + cw * ch + local dst = out or bcreate(w * h + 2 * cw * ch) + if buffer.len(src) < w * h * 4 or buffer.len(dst) < w * h + 2 * cw * ch then + return dst + end + local m = MATRIX[matrix or "bt601"] or MATRIX.bt601 + local kr, kb = m.kr, m.kb + local kg = 1 - kr - kb + local full = range == "full" + local ysc = if full then 1 else 219 / 255 + local csc = if full then 1 else 224 / 255 + local yof = if full then 0.5 else 16.5 + local yr, yg, yb = floor(kr * ysc * 65536 + 0.5), floor(kg * ysc * 65536 + 0.5), floor(kb * ysc * 65536 + 0.5) + local yoff = floor(yof * 65536) + local ur = floor(-kr / (2 * (1 - kb)) * csc * 65536 + 0.5) + local ug = floor(-kg / (2 * (1 - kb)) * csc * 65536 + 0.5) + local ub = floor(0.5 * csc * 65536 + 0.5) + local vr = ub + local vg = floor(-kg / (2 * (1 - kr)) * csc * 65536 + 0.5) + local vb = floor(-kb / (2 * (1 - kr)) * csc * 65536 + 0.5) + local coff4 = floor(128.5 * 65536) * 4 + for i = 0, w * h - 1 do + local o = i * 4 + local r, g, b = readu8(src, o), readu8(src, o + 1), readu8(src, o + 2) + writeu8(dst, i, readu8(CLIP, (yr * r + yg * g + yb * b + yoff) // 65536 + 1024)) + end + for cy = 0, ch - 1 do + local y0 = cy * 2 + local y1 = if y0 + 1 < h then y0 + 1 else y0 + for cx = 0, cw - 1 do + local x0 = cx * 2 + local x1 = if x0 + 1 < w then x0 + 1 else x0 + local a, b2, c2, d = (y0 * w + x0) * 4, (y0 * w + x1) * 4, (y1 * w + x0) * 4, (y1 * w + x1) * 4 + local r = readu8(src, a) + readu8(src, b2) + readu8(src, c2) + readu8(src, d) + local g = readu8(src, a + 1) + readu8(src, b2 + 1) + readu8(src, c2 + 1) + readu8(src, d + 1) + local b = readu8(src, a + 2) + readu8(src, b2 + 2) + readu8(src, c2 + 2) + readu8(src, d + 2) + local i = cy * cw + cx + writeu8(dst, uo + i, readu8(CLIP, (ur * r + ug * g + ub * b + coff4) // 262144 + 1024)) + writeu8(dst, vo + i, readu8(CLIP, (vr * r + vg * g + vb * b + coff4) // 262144 + 1024)) + end + end + return dst +end + +@native local function info(img: Types.Image): (string, string) + local m = img.meta + local y = m and m.yuv + if type(y) == "table" then + return y.range or "limited", y.matrix or "bt601" + end + local src = m and m.source + if type(src) == "table" and src.range == "full" then + return "full", "bt601" + end + return "limited", "bt601" +end +Yuv.info = info + +@native function Yuv.planes(w: number, h: number): (number, number, number, number) + local cw, ch = (w + 1) // 2, (h + 1) // 2 + return w * h, w * h + cw * ch, cw, ch +end + +local FULL_Y = bcreate(256) +local FULL_C = bcreate(256) +for v = 0, 255 do + writeu8(FULL_Y, v, math.clamp(floor((v - 16) * 255 / 219 + 0.5), 0, 255)) + writeu8(FULL_C, v, math.clamp(floor((v - 128) * 255 / 224 + 128.5), 0, 255)) +end + +@native function Yuv.toFullRange(img: Types.Image): Types.Image + if img.format ~= "yuv420p" or info(img) == "full" then + return img + end + local w, h = img.width, img.height + local out = Types.Image.new(w, h, "yuv420p") + local src, dst = img.pixels, out.pixels + local ny = w * h + local n = math.min(buffer.len(src), buffer.len(dst)) + for i = 0, math.min(ny, n) - 1 do + writeu8(dst, i, readu8(FULL_Y, readu8(src, i))) + end + for i = ny, n - 1 do + writeu8(dst, i, readu8(FULL_C, readu8(src, i))) + end + out.meta.yuv = { range = "full", matrix = select(2, info(img)) } + out.meta.source = img.meta.source + return out +end + +@native function Yuv.imageToRgba(img: Types.Image): Types.Image? + if img.format == "rgba8" then + return img + end + if img.format ~= "yuv420p" then + return nil + end + local w, h = img.width, img.height + local uo, vo, cw = Yuv.planes(w, h) + local range, matrix = info(img) + local out = Types.Image.new(w, h, "rgba8") + Yuv.toRgba(img.pixels, w, h, uo, vo, cw, range, matrix, out.pixels) + out.meta.source = img.meta.source + return out +end + +@native function Yuv.imageFromRgba(img: Types.Image, range: string?, matrix: string?): Types.Image? + if img.format == "yuv420p" then + return img + end + if img.format ~= "rgba8" then + return nil + end + local out = Types.Image.new(img.width, img.height, "yuv420p") + Yuv.fromRgba(img.pixels, img.width, img.height, range, matrix, out.pixels) + out.meta.yuv = { range = range or "limited", matrix = matrix or "bt601" } + out.meta.source = img.meta.source + return out +end + +@native local function scalePlane(src: buffer, so: number, sw: number, sh: number, dst: buffer, d0: number, dw: number, dh: number) + local fx, fy = sw / dw, sh / dh + for y = 0, dh - 1 do + local sy = (y + 0.5) * fy - 0.5 + if sy < 0 then + sy = 0 + end + local y0 = floor(sy) + if y0 > sh - 1 then + y0 = sh - 1 + end + local y1 = if y0 < sh - 1 then y0 + 1 else y0 + local wy = floor((sy - y0) * 256) + local r0, r1 = so + y0 * sw, so + y1 * sw + local o = d0 + y * dw + for x = 0, dw - 1 do + local sx = (x + 0.5) * fx - 0.5 + if sx < 0 then + sx = 0 + end + local x0 = floor(sx) + if x0 > sw - 1 then + x0 = sw - 1 + end + local x1 = if x0 < sw - 1 then x0 + 1 else x0 + local wx = floor((sx - x0) * 256) + local a = readu8(src, r0 + x0) * (256 - wx) + readu8(src, r0 + x1) * wx + local b = readu8(src, r1 + x0) * (256 - wx) + readu8(src, r1 + x1) * wx + writeu8(dst, o + x, (a * (256 - wy) + b * wy + 32768) // 65536) + end + end +end + +@native function Yuv.scale(src: buffer, w: number, h: number, width: number, height: number, out: buffer?): buffer + local dw: number = math.max(1, floor(width)) + local dh: number = math.max(1, floor(height)) + local cw: number = (w + 1) // 2 + local ch: number = (h + 1) // 2 + local dcw: number = (dw + 1) // 2 + local dch: number = (dh + 1) // 2 + local size = dw * dh + 2 * dcw * dch + local dst = if out and buffer.len(out) >= size then out else bcreate(size) + if w < 1 or h < 1 or buffer.len(src) < w * h + 2 * cw * ch then + return dst + end + scalePlane(src, 0, w, h, dst, 0, dw, dh) + scalePlane(src, w * h, cw, ch, dst, dw * dh, dcw, dch) + scalePlane(src, w * h + cw * ch, cw, ch, dst, dw * dh + dcw * dch, dcw, dch) + return dst +end + +@native function Yuv.imageScale(img: Types.Image, dw: number, dh: number): Types.Image + local out = Types.Image.new(math.max(1, floor(dw)), math.max(1, floor(dh)), "yuv420p") + Yuv.scale(img.pixels, img.width, img.height, out.width, out.height, out.pixels) + out.meta = table.clone(img.meta or {}) + return out +end + +return Yuv +end +__FILES["codecs/model/Rbx"] = function() + +-- codecs/model/Rbx: the Roblox instance tree and property values shared by model/rbxm and model/rbxmx. +-- Written from the rbx-dom format notes (docs/binary.md, docs/xml.md); checked against rbx-dom through rojo / lune. +-- Faces: bits Right 1, Top 2, Back 4, Left 8, Bottom 16, Front 32 +-- Axes: bits X 1, Y 2, Z 4 +-- UniqueId: 32 hex digits: random (16), time (8), index (8) + +local Rbx = {} + +type Value = { type: string, value: any } +type Instance = { + className: string, + name: string, + properties: { [string]: Value }, + children: { Instance }, + parent: Instance?, + referent: string?, + service: boolean?, -- a service (binary INST object format 1; rbxl roots) +} +type Tree = { + kind: "rbxtree", + roots: { Instance }, + place: boolean, + metadata: { [string]: string }, -- binary META / XML <Meta> entries (ExplicitAutoJoints, ...) + extra: { any }, + meta: { source: { format: string, [string]: any }?, [string]: any }, +} + +function Rbx.tree(place: boolean?): Tree + return { kind = "rbxtree", roots = {}, place = place == true, metadata = {}, extra = {}, meta = {} } +end + +function Rbx.instance(className: string, name: string?): Instance + return { className = className, name = name or className, properties = {}, children = {} } +end + +function Rbx.add(parent: any, child: Instance): Instance + if parent.kind == "rbxtree" then + child.parent = nil + table.insert(parent.roots, child) + else + child.parent = parent + table.insert(parent.children, child) + end + return child +end + +function Rbx.set(inst: Instance, name: string, typ: string, value: any) + inst.properties[name] = { type = typ, value = value } +end + +function Rbx.get(inst: Instance, name: string): any + local v = inst.properties[name] + return if v then v.value else nil +end + +function Rbx.descendants(root: any): () -> (Instance?, number?) + local stack: { any } = {} + local list = if root.kind == "rbxtree" then root.roots else root.children + for i = #list, 1, -1 do + table.insert(stack, { list[i], 1 }) + end + return function(): (Instance?, number?) + local top = table.remove(stack) + if not top then + return nil, nil + end + local inst, depth = top[1], top[2] + for i = #inst.children, 1, -1 do + table.insert(stack, { inst.children[i], depth + 1 }) + end + return inst, depth + end +end + +function Rbx.list(tree: any): { Instance } + local out = {} + for inst in Rbx.descendants(tree) do + table.insert(out, inst :: Instance) + end + return out +end + +function Rbx.find(root: any, path: string): Instance? + local cur: any = root + for part in string.gmatch(path, "[^/]+") do + local list = if cur.kind == "rbxtree" then cur.roots else cur.children + local found = nil + for _, c in list do + if c.name == part then + found = c + break + end + end + if not found then + return nil + end + cur = found + end + return if cur.kind == "rbxtree" then nil else cur +end + +function Rbx.fullName(inst: Instance): string + local parts = {} + local cur: Instance? = inst + while cur do + table.insert(parts, 1, cur.name) + cur = cur.parent + end + return table.concat(parts, ".") +end + +-- The binary format stores axis-aligned rotations as one byte: id = 6 * n(RightVector) + n(UpVector) + 1, where n is +-- the NormalId of a unit axis (+X 0, +Y 1, +Z 2, -X 3, -Y 4, -Z 5) and the third column is their cross product. +local AXES = { { 1, 0, 0 }, { 0, 1, 0 }, { 0, 0, 1 }, { -1, 0, 0 }, { 0, -1, 0 }, { 0, 0, -1 } } + +local ROTATIONS: { [number]: { number } } = {} +for a = 0, 5 do + for b = 0, 5 do + if a % 3 ~= b % 3 then + local r, u = AXES[a + 1], AXES[b + 1] + local k = { r[2] * u[3] - r[3] * u[2], r[3] * u[1] - r[1] * u[3], r[1] * u[2] - r[2] * u[1] } + -- columns: right, up, back (= right x up) + ROTATIONS[6 * a + b + 1] = { r[1], u[1], k[1] + 0, r[2], u[2], k[2] + 0, r[3], u[3], k[3] + 0 } + end + end +end +Rbx.ROTATIONS = ROTATIONS + +local function axisIndex(x: number, y: number, z: number): number? + for i, a in AXES do + if a[1] == x and a[2] == y and a[3] == z then + return i - 1 + end + end + return nil +end + +function Rbx.rotationId(cf: { number }): number + local a = axisIndex(cf[4], cf[7], cf[10]) + local b = axisIndex(cf[5], cf[8], cf[11]) + if not a or not b then + return 0 + end + local id = 6 * a + b + 1 + local rot = ROTATIONS[id] + if not rot or rot[3] ~= cf[6] or rot[6] ~= cf[9] or rot[9] ~= cf[12] then + return 0 + end + return id +end + +-- binary type ids (rbx-dom docs/binary.md) by type name, and back +Rbx.TYPE_IDS = table.freeze({ + String = 0x01, + BinaryString = 0x01, + ProtectedString = 0x01, + ContentId = 0x01, + Bool = 0x02, + Int32 = 0x03, + Float32 = 0x04, + Float64 = 0x05, + UDim = 0x06, + UDim2 = 0x07, + Ray = 0x08, + Faces = 0x09, + Axes = 0x0A, + BrickColor = 0x0B, + Color3 = 0x0C, + Vector2 = 0x0D, + Vector3 = 0x0E, + Vector2int16 = 0x0F, + CFrame = 0x10, + Enum = 0x12, + Ref = 0x13, + Vector3int16 = 0x14, + NumberSequence = 0x15, + ColorSequence = 0x16, + NumberRange = 0x17, + Rect = 0x18, + PhysicalProperties = 0x19, + Color3uint8 = 0x1A, + Int64 = 0x1B, + SharedString = 0x1C, + Bytecode = 0x1D, + OptionalCFrame = 0x1E, + UniqueId = 0x1F, + Font = 0x20, + SecurityCapabilities = 0x21, + Content = 0x22, +} :: { [string]: number }) +local NAMES: { [number]: string } = {} +for name, id in Rbx.TYPE_IDS do + if NAMES[id] == nil or name == "String" then + NAMES[id] = name + end +end +Rbx.TYPE_NAMES = table.freeze(NAMES) + +-- BrickColor 194 (Medium stone grey) is Roblox's default +local IDENTITY_CF = { 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1 } +function Rbx.default(typ: string): any + if typ == "String" or typ == "BinaryString" or typ == "ProtectedString" or typ == "ContentId" or typ == "Bytecode" or typ == "SharedString" then + return "" + elseif typ == "Bool" then + return false + elseif typ == "BrickColor" then + return 194 + elseif typ == "UDim" or typ == "NumberRange" or typ == "Vector2" or typ == "Vector2int16" then + return { 0, 0 } + elseif typ == "UDim2" or typ == "Rect" then + return { 0, 0, 0, 0 } + elseif typ == "Vector3" or typ == "Vector3int16" or typ == "Color3" or typ == "Color3uint8" then + return { 0, 0, 0 } + elseif typ == "Ray" then + return { 0, 0, 0, 0, 0, 0 } + elseif typ == "CFrame" then + return table.clone(IDENTITY_CF) + elseif typ == "NumberSequence" then + return { { 0, 0, 0 }, { 1, 0, 0 } } + elseif typ == "ColorSequence" then + return { { 0, 0, 0, 0, 0 }, { 1, 0, 0, 0, 0 } } + elseif typ == "UniqueId" then + return string.rep("0", 32) + elseif typ == "Font" then + return { family = "rbxasset://fonts/families/SourceSansPro.json", weight = 400, style = "Normal" } + elseif typ == "PhysicalProperties" or typ == "Ref" or typ == "OptionalCFrame" or typ == "Content" then + return nil + end + return 0 +end + +Rbx.STRINGS = table.freeze({ String = true, BinaryString = true, ProtectedString = true, ContentId = true, Bytecode = true } :: { [string]: boolean }) + +return Rbx +end +__FILES["codecs/video/Video"] = function() + +-- codecs/video/Video: the video codec registry and the generic VideoDecoder. New in rosetta. +local Err = __include("core/Err") +local Types = __include("Types") +local Yuv = __include("codecs/image/Yuv") + +local Video = {} + +type Entry = { + id: string, + name: string, + fourcc: { string }?, -- AVI biCompression / MOV sample entry FourCCs + matroska: { string }?, -- Matroska / WebM CodecIDs + new: ((track: Types.Track, opts: any?) -> (Types.VideoCodecDecoder?, Err.Err?))?, + [string]: any, +} + +-- decodeOne -> nil, nil: a packet with no picture to show (a hidden VP8 altref frame) +function Video.simpleDecoder(decodeOne: (data: buffer, packet: Types.Packet) -> (Types.Image?, Err.Err?), resetFn: (() -> ())?): Types.VideoCodecDecoder + local queue: { any } = {} + local self = {} + function self.decode(_: any, packet: Types.Packet): Err.Err? + local ok, img, err = pcall(decodeOne, packet.data, packet) + if not ok then + return Err.new(Err.CORRUPT, "decoder threw: " .. tostring(img)) + end + if img then + table.insert(queue, { img, packet.pts, packet.keyframe }) + end + return err + end + function self.receive(_: any): (Types.Image?, number?, boolean?) + local q = table.remove(queue, 1) + if q then + return q[1], q[2], q[3] + end + return nil, nil, nil + end + function self.flush(_: any) end + function self.reset(_: any) + table.clear(queue) + if resetFn then + resetFn() + end + end + return self :: any +end + +-- raw video: yuv420p (I420 / IYUV / y4m), yv12 (V before U), yuv422p / yuv444p / yuva444p / gray (chroma averaged +-- down to 4:2:0, alpha dropped), track.bitDepth 9..16 (little-endian 16-bit samples scaled to 8 bits), rgb24 / bgr24 / +-- bgra / rgba (AVI DIBs: track.flip = bottom-up rows, track.stride = padded rows) +local function rawPlanar(data: buffer, pf: string, bits: number, w: number, h: number): Types.Image + local img = Types.Image.new(w, h, "yuv420p") + local px = img.pixels + local cw, ch = (w + 1) // 2, (h + 1) // 2 + local bps = if bits > 8 then 2 else 1 + local shift = 2 ^ (bits - 8) + local function sample(o: number): number + if bps == 1 then + return buffer.readu8(data, o) + end + return math.min(255, buffer.readu16(data, o) // shift) + end + for i = 0, w * h - 1 do + buffer.writeu8(px, i, sample(i * bps)) + end + local scw, sch = w, h -- source chroma plane size + if pf == "yuv420p" then + scw, sch = cw, ch + elseif pf == "yuv422p" then + scw, sch = cw, h + end + local uo, vo = w * h * bps, (w * h + scw * sch) * bps + for cy = 0, ch - 1 do + for cx = 0, cw - 1 do + local i = cy * cw + cx + local u, v + if pf == "gray" then + u, v = 128, 128 + elseif pf == "yuv420p" then + 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 + v = (sample(vo + (y0 * scw + cx) * bps) + sample(vo + (y1 * scw + cx) * bps) + 1) // 2 + else + local x0, x1 = cx * 2, math.min(cx * 2 + 1, w - 1) + local y0, y1 = cy * 2, math.min(cy * 2 + 1, h - 1) + local a, b, c, d = (y0 * w + x0) * bps, (y0 * w + x1) * bps, (y1 * w + x0) * bps, (y1 * w + x1) * bps + u = (sample(uo + a) + sample(uo + b) + sample(uo + c) + sample(uo + d) + 2) // 4 + v = (sample(vo + a) + sample(vo + b) + sample(vo + c) + sample(vo + d) + 2) // 4 + end + buffer.writeu8(px, w * h + i, u) + buffer.writeu8(px, w * h + cw * ch + i, v) + end + end + return img +end + +local PLANAR_SIZE: { [string]: (w: number, h: number, cw: number, ch: number) -> number } = { + yuv420p = function(w, h, cw, ch) + return w * h + 2 * cw * ch + end, + yv12 = function(w, h, cw, ch) + return w * h + 2 * cw * ch + end, + yuv422p = function(w, h, cw, _ch) + return w * h + 2 * cw * h + end, + yuv444p = function(w, h) + return w * h * 3 + end, + yuva444p = function(w, h) + return w * h * 4 + end, + gray = function(w, h) + return w * h + end, +} + +local function rawDecoder(track: Types.Track, _opts: any?): (Types.VideoCodecDecoder?, Err.Err?) + local w, h = track.width or 0, track.height or 0 + if w <= 0 or h <= 0 or w * h > 2 ^ 26 then + return nil, Err.new(Err.CORRUPT, "raw video without a valid size") + end + local pf = track.pixelFormat or "yuv420p" + local bits = track.bitDepth or 8 + local cw, ch = (w + 1) // 2, (h + 1) // 2 + local flip = track.flip == true + local planar = PLANAR_SIZE[pf] + return Video.simpleDecoder(function(data: buffer): (Types.Image?, Err.Err?) + local n = buffer.len(data) + if planar then + local need = planar(w, h, cw, ch) * (if bits > 8 then 2 else 1) + if n < need then + return nil, Err.new(Err.TRUNCATED, "raw frame: " .. n .. " of " .. need .. " bytes") + end + 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, 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, nil + end + return rawPlanar(data, pf, bits, w, h), nil + end + local bpp = if pf == "bgra" or pf == "rgba" then 4 else 3 + 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 + local img = Types.Image.new(w, h, "rgba8") + local px = img.pixels + local bgr = pf == "bgr24" or pf == "bgra" + for y = 0, h - 1 do + local s = (if flip then h - 1 - y else y) * stride + local o = y * w * 4 + for x = 0, w - 1 do + local p = s + x * bpp + local a, b, c = buffer.readu8(data, p), buffer.readu8(data, p + 1), buffer.readu8(data, p + 2) + if bgr then + a, c = c, a + end + buffer.writeu32(px, o + x * 4, a + b * 256 + c * 65536 + 0xff000000) + end + end + return img, nil + end), nil +end + +local function vp8Decoder(_track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) + local Vp8 = __include("codecs/image/Vp8") + local dec = Vp8.newDecoder() + local o = { maxPixels = opts and opts.maxPixels } + return Video.simpleDecoder(function(data: buffer): (Types.Image?, Err.Err?) + local img, err = dec:decodeFrame(data, 0, buffer.len(data), o) + if not img then + return nil, err + end + local src = img.meta.source + if type(src) == "table" and src.show == false then + return nil, nil + end + img.meta.yuv = { range = "limited", matrix = "bt601" } + return img, nil + end, function() + if dec.reset then + dec:reset() + else + dec = Vp8.newDecoder() + end + end), nil +end + +-- Motion JPEG: 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 = __include("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) + if img and img.format == "yuv420p" then + img.meta.yuv = { range = "full", matrix = "bt601" } + end + return img, err + end), nil +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 = __include("codecs/image/Jpeg") + local src = img + if img.format == "yuv420p" then + local range = Yuv.info(img) + if range ~= "full" then + src = Yuv.toFullRange(img) + end + end + return Jpeg.encode(src, { quality = opts and opts.quality or 90 }) +end + +local function mpeg2Decoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) + local Mpeg2 = __include("codecs/video/Mpeg2") + return Mpeg2.newVideoDecoder(track, opts) +end + +local function h264Decoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) + local H264 = __include("codecs/video/H264") + return H264.newVideoDecoder(track, opts) +end + +local function h263Decoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) + local H263 = __include("codecs/video/H263") + local dec = H263.new({ flv = track.codec == "flv1", maxPixels = opts and opts.maxPixels }) + return Video.simpleDecoder(function(data: buffer): (Types.Image?, Err.Err?) + return dec:image(data) + end, function() + dec:reset() + end), nil +end + +local function theoraDecoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) + local Theora = __include("codecs/video/Theora") + return Theora.newVideoDecoder(track, opts) +end + +local function legacyDecoder(id: string): (track: Types.Track, opts: any?) -> (Types.VideoCodecDecoder?, Err.Err?) + return function(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) + return __include("codecs/video/Legacy").newDecoder(id, track, opts) + end +end + +-- FourCCs compare case-sensitively first, then upper-cased +local BUILTIN: { Entry } = { + { id = "vp8", name = "VP8", fourcc = { "VP80", "vp08" }, matroska = { "V_VP8" }, new = vp8Decoder }, + { id = "mjpeg", name = "Motion JPEG", fourcc = { "MJPG", "mjpa", "mjpb", "jpeg", "AVRn", "AVDJ", "dmb1", "LJPG", "JPGL", "MJLS", "ijpg" }, matroska = { "V_MJPEG" }, new = mjpegDecoder, encode = mjpegEncode }, + { id = "mpeg1", name = "MPEG-1 video", fourcc = { "mpg1", "MPG1", "PIM1", "m1v " }, matroska = { "V_MPEG1" }, new = mpeg2Decoder }, + { id = "rawvideo", name = "raw video", fourcc = { "\0\0\0\0", "I420", "IYUV", "YV12", "raw ", "DIB " }, matroska = { "V_UNCOMPRESSED" }, new = rawDecoder }, + { id = "mpeg2", name = "MPEG-2 video", fourcc = { "mpg2", "MPG2", "MPEG", "mp2v", "hdv1", "hdv2", "hdv3", "hdv5", "hdv6", "hdv7", "hdv8", "hdv9", "hdva", "xdv1", "xdv2", "xdv3", "xdv4", "xdv5", "xdv6", "xdv7", "xdv8", "xdv9", "xdva", "xdvb", "xdvc", "xdvd", "xdve", "xdvf", "xd54", "xd55", "xd59", "xd5a", "xd5b", "xd5c", "xd5d", "xd5e", "xd5f", "xdhd", "xdh2", "AVmp", "mx3n", "mx3p", "mx4n", "mx4p", "mx5n", "mx5p", "mmes", "MMES", "M701", "M702", "M703", "M704", "M705", "mpgv", "m2v1", "M2V1" }, matroska = { "V_MPEG2" }, new = mpeg2Decoder }, + { id = "mpeg4", name = "MPEG-4 part 2", fourcc = { "mp4v", "FMP4", "XVID", "DIVX", "DX50", "MP4V" }, matroska = { "V_MPEG4/ISO/SP", "V_MPEG4/ISO/ASP", "V_MPEG4/ISO/AP" } }, + { id = "h264", name = "H.264 / AVC", fourcc = { "avc1", "avc3", "H264", "h264", "X264", "x264", "AVC1", "DAVC", "VSSH" }, matroska = { "V_MPEG4/ISO/AVC" }, new = h264Decoder }, + { id = "hevc", name = "H.265 / HEVC", fourcc = { "hvc1", "hev1", "HEVC", "H265" }, matroska = { "V_MPEGH/ISO/HEVC" } }, + { id = "vp9", name = "VP9", fourcc = { "VP90", "vp09" }, matroska = { "V_VP9" } }, + { id = "av1", name = "AV1", fourcc = { "AV01", "av01" }, matroska = { "V_AV1" } }, + { id = "theora", name = "Theora", matroska = { "V_THEORA" }, new = theoraDecoder }, + { id = "h263", name = "H.263", fourcc = { "H263", "h263", "s263", "U263" }, new = h263Decoder }, + { id = "flv1", name = "Sorenson Spark (FLV1)", fourcc = { "FLV1" }, new = h263Decoder }, + { id = "vp6f", name = "On2 VP6 (Flash)", fourcc = { "VP6F", "FLV4" } }, + { id = "vp6a", name = "On2 VP6 with alpha (Flash)", fourcc = { "VP6A" } }, + { id = "flashsv", name = "Flash Screen Video", fourcc = { "FSV1" } }, + { id = "flashsv2", name = "Flash Screen Video 2" }, + { id = "png", name = "PNG", fourcc = { "png ", "MPNG" }, matroska = { "V_PNG" } }, + { id = "cinepak", name = "Cinepak", fourcc = { "cvid" }, new = legacyDecoder("cinepak") }, + { id = "msvideo1", name = "Microsoft Video 1", fourcc = { "CRAM", "MSVC", "WHAM" }, new = legacyDecoder("msvideo1") }, + { id = "qtrle", name = "QuickTime Animation (RLE)", fourcc = { "rle " }, new = legacyDecoder("qtrle") }, + { id = "smc", name = "QuickTime Graphics (SMC)", fourcc = { "smc " }, new = legacyDecoder("smc") }, + { id = "flic", name = "Autodesk Animator FLIC", fourcc = { "AFLC" }, new = legacyDecoder("flic") }, + { id = "smackvid", name = "Smacker video", fourcc = { "SMK2", "SMK4" }, new = legacyDecoder("smackvid") }, +} + +local byId: { [string]: Entry } = {} +local byFourcc: { [string]: string } = {} +local byMatroska: { [string]: string } = {} + +function Video.register(entry: Entry): (boolean, Err.Err?) + if type(entry) ~= "table" or type(entry.id) ~= "string" then + return false, Err.new(Err.ARG, "register: needs an entry with an id") + end + local old = byId[entry.id] + if old and entry.new == nil then + entry.new = old.new + end + byId[entry.id] = entry + for _, f in entry.fourcc or {} do + byFourcc[f] = entry.id + end + for _, m in entry.matroska or {} do + byMatroska[m] = entry.id + end + return true, nil +end +for _, e in BUILTIN do + Video.register(e) +end + +Video.codecs = byId + +function Video.fromFourcc(fcc: string): string? + return byFourcc[fcc] or byFourcc[string.upper(fcc)] or byFourcc[string.lower(fcc)] +end + +function Video.fromMatroska(id: string): string? + return byMatroska[id] +end + +function Video.entry(id: string): Entry? + return byId[id] +end + +function Video.canDecode(id: string): boolean + local e = byId[id] + return e ~= nil and e.new ~= nil +end + +function Video.decoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) + local e = byId[track.codec] + if not e or not e.new then + return nil, Err.new(Err.UNSUPPORTED, "no decoder for video codec " .. tostring(track.codec)) + end + local ok, dec, err = pcall(e.new :: any, track, opts) + if not ok then + return nil, Err.new(Err.CORRUPT, "codec " .. track.codec .. " failed to start: " .. tostring(dec)) + end + return dec, err +end + +local function toRGBA(_self: any, f: any): Types.Image + local img = if type(f) == "table" and f.image then f.image else f + local out = Yuv.imageToRgba(img) + return out or img +end + +type OpenOptions = { + rgba: boolean?, + track: number?, + maxPixels: number?, + openAudio: ((demuxer: Types.Demuxer, track: Types.Track) -> (Types.Decoder?, Err.Err?))?, + audio: boolean?, + maxSide: number?, + yield: (() -> ())?, + [string]: any, +} + +function Video.open(demuxer: Types.Demuxer, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) + local o: OpenOptions = opts or {} + local track: Types.Track? = nil + if o.track then + for _, t in demuxer.tracks do + if t.id == o.track then + track = t + end + end + if not track then + return nil, Err.new(Err.ARG, "no track " .. tostring(o.track)) + end + else + track = demuxer:track("video") + end + local codec: Types.VideoCodecDecoder? = nil + local codecErr: Err.Err? = nil + if track then + codec, codecErr = Video.decoder(track, o) + else + codecErr = Err.new(Err.UNSUPPORTED, "no video track") + end + local v: any = { + kind = "video", + format = demuxer.format, + codec = if track then track.codec else "none", + width = if track then track.width or 0 else 0, + height = if track then track.height or 0 else 0, + frameRate = if track then track.frameRate or 0 else 0, + frames = if track then track.frames or 0 else 0, + duration = if track and track.duration and track.duration > 0 then track.duration else demuxer.duration, + track = track, + demuxer = demuxer, + meta = demuxer.meta or {}, + decodeError = codecErr, + toRGBA = toRGBA, + } + if v.frames == 0 and v.frameRate > 0 and v.duration > 0 then + v.frames = math.floor(v.duration * v.frameRate + 0.5) + end + if o.audio ~= false then + local at = demuxer:track("audio") + if at then + if o.openAudio then + local ok, dec, err = pcall(o.openAudio, demuxer, at) + if ok and dec then + v.audio = dec + else + v.audioError = if ok then err else Err.new(Err.CORRUPT, "audio: " .. tostring(dec)) + end + else + v.audioError = Err.new(Err.UNSUPPORTED, "no audio hook (open through the api: F.video.open)") + end + end + end + local index, flushed, skipUntil = 0, false, -math.huge + local tid = if track then track.id else -1 + 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 + local lastPts = nil :: number? + function v.nextFrame(self: any): (Types.VideoFrame?, Err.Err?) + if not codec then + return nil, codecErr + end + local dec = codec :: Types.VideoCodecDecoder + while true do + local img, pts, key = dec:receive() + if img then + local t = (pts or 0) / scale - start + if t + 1e-9 >= skipUntil then + if index < 0 then + -- after a seek: constant-rate index = round(pts * fps), else counted from the seek + index = if v.frameRate > 0 then math.max(0, math.floor(t * v.frameRate + 0.5)) else 0 + end + index += 1 + local d = defaultDur + if lastPts and t > (lastPts :: number) and defaultDur == 0 then + d = t - (lastPts :: number) + end + lastPts = t + local maxSide = o.maxSide + if maxSide and maxSide >= 1 and img.format == "yuv420p" and math.max(img.width, img.height) > maxSide then + local hook: any = o.yield + if hook then + pcall(hook) + end + local s = maxSide / math.max(img.width, img.height) + img = Yuv.imageScale(img, math.max(1, math.floor(img.width * s + 0.5)), math.max(1, math.floor(img.height * s + 0.5))) + end + if o.rgba then + img = Yuv.imageToRgba(img) or img + end + return { image = img, pts = t, duration = d, keyframe = key, index = index }, nil + end + else + local p = demuxer:read(tid) + if p == nil then + if flushed then + return nil, nil + end + flushed = true + dec:flush() + else + local err = dec:decode(p) + if err then + return nil, err + end + end + end + end + end + function v.seek(self: any, seconds: number) + demuxer:seek(seconds + start) + if codec then + codec:reset() + end + flushed = false + skipUntil = seconds + lastPts = nil + index = -1 -- recomputed from the first frame's time + if self.audio then + pcall(self.audio.seek, self.audio, seconds) + end + end + function v.reset(self: any) + self:seek(0) + skipUntil = -math.huge + index = 0 + end + return v, nil +end + +function Video.fromFrames(images: { Types.Image }, delays: (number | { number })?, opts: any?): (Types.VideoDecoder?, Err.Err?) + if type(images) ~= "table" or #images == 0 or type(images[1]) ~= "table" then + return nil, Err.new(Err.ARG, "fromFrames: needs a list of Images") + end + local w, h = images[1].width, images[1].height + local pts: { number } = {} + local durs: { number } = {} + local t = 0 + for i, img in images do + if type(img) ~= "table" or img.width ~= w or img.height ~= h then + return nil, Err.new(Err.ARG, "fromFrames: frame " .. i .. " is not a " .. w .. "x" .. h .. " Image") + end + local d = if type(delays) == "table" then delays[i] or 0.1 else (delays or 0.1) + if type(d) ~= "number" or d ~= d or d < 0 then + d = 0.1 + end + pts[i] = t + durs[i] = d + t += d + end + local n = #images + local o = opts or {} + local v: any = { + kind = "video", + format = o.format or "frames", + codec = "frames", + width = w, + height = h, + frameRate = if t > 0 then n / t else 10, + frames = n, + duration = t, + loops = o.loops, + meta = o.meta or {}, + toRGBA = toRGBA, + images = images, + } + local i = 0 + function v.nextFrame(self: any): (Types.VideoFrame?, Err.Err?) + i += 1 + if i > n then + i = n + return nil, nil + end + local img = images[i] + if o.rgba then + img = Yuv.imageToRgba(img) or img + end + return { image = img, pts = pts[i], duration = durs[i], keyframe = true, index = i }, nil + end + function v.seek(self: any, seconds: number) + local k = 0 + for j = 1, n do + if pts[j] <= seconds + 1e-9 then + k = j - 1 + end + end + i = k + end + function v.reset(self: any) + i = 0 + end + return v, nil +end + +return Video +end +__FILES["containers/AudioWrap"] = function() + +-- containers/AudioWrap: a video container's audio track as a stream an audio format reads (a format never requires +-- another). New in rosetta. PCM / WAVEFORMATEX -> WAV, adpcm_swf -> f32 WAV, mp1-3 / ac3 -> frames back to back, +-- flac -> fLaC + metadata blocks, opus / vorbis -> Ogg, aac -> ADTS. E-AC-3 is UNSUPPORTED. +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Mux = __include("containers/Ogg/Mux") +local Adpcm = __include("codecs/audio/Adpcm") + +local AudioWrap = {} + +type PacketSource = { + count: ((self: any, track: number) -> number)?, + get: ((self: any, track: number, k: number) -> Types.Packet?)?, +} + +local function allPackets(dmx: PacketSource, track: Types.Track): { Types.Packet } + local out: { Types.Packet } = {} + local n = if dmx.count then dmx:count(track.id) else 0 + if n > 0 and dmx.get then + for k = 1, n do + local p = dmx:get(track.id, k) + if p then + table.insert(out, p) + end + end + end + return out +end + +local function concat(packets: { Types.Packet }, prefix: buffer?): buffer + local total = if prefix then buffer.len(prefix) else 0 + for _, p in packets do + total += buffer.len(p.data) + end + local out = buffer.create(total) + local o = 0 + if prefix then + buffer.copy(out, 0, prefix) + o = buffer.len(prefix) + end + for _, p in packets do + buffer.copy(out, o, p.data) + o += buffer.len(p.data) + end + return out +end + +local PCM: { [string]: { number } } = { -- tag, bits, bytes swapped (big-endian source) + pcm_u8 = { 1, 8, 0 }, + pcm_s8 = { 1, 8, 0 }, + pcm_s16le = { 1, 16, 0 }, + pcm_s24le = { 1, 24, 0 }, + pcm_s32le = { 1, 32, 0 }, + pcm_s16be = { 1, 16, 1 }, + pcm_s24be = { 1, 24, 1 }, + pcm_s32be = { 1, 32, 1 }, + pcm_f32le = { 3, 32, 0 }, + pcm_f64le = { 3, 64, 0 }, + pcm_f32be = { 3, 32, 1 }, + pcm_f64be = { 3, 64, 1 }, + pcm_alaw = { 6, 8, 0 }, + pcm_mulaw = { 7, 8, 0 }, +} + +local function wav(fmt: buffer, data: buffer): buffer + local w = Bytes.writer(buffer.len(data) + buffer.len(fmt) + 64) + local fl = buffer.len(fmt) + local dl = buffer.len(data) + w:string("RIFF") + w:u32le(4 + 8 + fl + (fl % 2) + 8 + dl + (dl % 2)) + w:string("WAVE") + w:string("fmt ") + w:u32le(fl) + w:bytes(fmt) + if fl % 2 == 1 then + w:u8(0) + end + w:string("data") + w:u32le(dl) + w:bytes(data) + if dl % 2 == 1 then + w:u8(0) + end + return w:finish() +end + +local function pcmWav(track: Types.Track, packets: { Types.Packet }): (buffer?, Err.Err?) + local spec = PCM[track.codec] + local ch = track.channels or 1 + local rate = math.floor((track.sampleRate or 0) + 0.5) + if ch < 1 or rate <= 0 then + return nil, Err.new(Err.CORRUPT, "PCM track without channels / sample rate") + end + local bits = spec[2] + local data = concat(packets) + if spec[3] == 1 then + local bps = bits // 8 + for i = 0, buffer.len(data) - bps, bps do + for k = 0, bps // 2 - 1 do + local a, b = buffer.readu8(data, i + k), buffer.readu8(data, i + bps - 1 - k) + buffer.writeu8(data, i + k, b) + buffer.writeu8(data, i + bps - 1 - k, a) + end + end + end + if track.codec == "pcm_s8" then + for i = 0, buffer.len(data) - 1 do + buffer.writeu8(data, i, (buffer.readu8(data, i) + 128) % 256) + end + end + local f = Bytes.writer(16) + local align = ch * bits // 8 + f:u16le(spec[1]) + f:u16le(ch) + f:u32le(rate) + f:u32le(rate * align) + f:u16le(align) + f:u16le(bits) + return wav(f:finish(), data), nil +end + +-- Flash ADPCM packets decode on their own (each starts with its code size and block headers): f32 samples in a WAV +local function swfWav(track: Types.Track, packets: { Types.Packet }): (buffer?, Err.Err?) + local ch = track.channels or 1 + local rate = math.floor((track.sampleRate or 0) + 0.5) + if ch < 1 or ch > 2 or rate <= 0 then + return nil, Err.new(Err.CORRUPT, "Flash ADPCM track without channels / sample rate") + end + local frames = 0 + for _, pk in packets do + frames += Adpcm.swfFrames(pk.data, 0, buffer.len(pk.data), ch) + end + local data = buffer.create(frames * ch * 4) + local d = 0 + for _, pk in packets do + d += Adpcm.swf(pk.data, 0, buffer.len(pk.data), ch, data, d) * ch + end + local f = Bytes.writer(16) + f:u16le(3) + f:u16le(ch) + f:u32le(rate) + f:u32le(rate * ch * 4) + f:u16le(ch * 4) + f:u16le(32) + return wav(f:finish(), data), nil +end + +-- the number of 48 kHz samples in an Opus packet (RFC 6716 section 3.1) +local function opusSamples(b: buffer): number + local n = buffer.len(b) + if n < 1 then + return 0 + end + local toc = buffer.readu8(b, 0) + local config = toc // 8 + local fs: number + if config < 12 then + fs = ({ 480, 960, 1920, 2880 })[config % 4 + 1] + elseif config < 16 then + fs = if config % 2 == 0 then 480 else 960 + else + fs = ({ 120, 240, 480, 960 })[config % 4 + 1] + end + local c = toc % 4 + local frames = if c == 0 then 1 elseif c == 3 then (if n >= 2 then buffer.readu8(b, 1) % 64 else 0) else 2 + return fs * frames +end + +local function opusHead(track: Types.Track): buffer + local c = track.config + if c and buffer.len(c) >= 19 and buffer.readstring(c, 0, 8) == "OpusHead" then + return c + end + local w = Bytes.writer(19) + w:string("OpusHead") + w:u8(1) + w:u8(math.clamp(track.channels or 2, 1, 2)) + w:u16le(math.floor((track.codecDelay or 0) * 48000 + 0.5)) + w:u32le(math.floor(track.sampleRate or 48000)) + w:u16le(0) + w:u8(0) + return w:finish() +end + +local function opusTags(): buffer + local w = Bytes.writer(32) + w:string("OpusTags") + local vendor = "rosetta" + w:u32le(#vendor) + w:string(vendor) + w:u32le(0) + return w:finish() +end + +local function ogg(headers: { buffer }, packets: { Types.Packet }, granuleOf: (p: Types.Packet, i: number) -> number): buffer + local mux = Mux.new({ pageSize = 4096 }) + local s = mux:stream(1) + for i, h in headers do + s:packet(h, 0, { flush = i == 1 or i == #headers }) + end + for i, p in packets do + s:packet(p.data, granuleOf(p, i), { eos = i == #packets }) + end + return mux:finish() +end + +-- Matroska's Vorbis CodecPrivate: Xiph-laced headers (count - 1, sizes, data) +local function xiphHeaders(c: buffer): { buffer }? + local n = buffer.len(c) + if n < 3 then + return nil + end + local count = buffer.readu8(c, 0) + 1 + local p = 1 + local sizes = {} + local total = 0 + for k = 1, count - 1 do + local s = 0 + while true do + if p >= n then + return nil + end + local b = buffer.readu8(c, p) + p += 1 + s += b + if b ~= 255 then + break + end + end + sizes[k] = s + total += s + end + sizes[count] = n - p - total + if sizes[count] < 0 then + return nil + end + local out = {} + for k = 1, count do + local b = buffer.create(sizes[k]) + buffer.copy(b, 0, c, p, sizes[k]) + p += sizes[k] + out[k] = b + end + return out +end + +-- Vorbis packet sizes: the block sizes from the identification header and each mode's block flag from the end of the +-- setup header (read backwards from its framing bit: mode entries are 41 bits whose window / transform types are 0, +-- preceded by the 6-bit mode count), so the Ogg granules are exact: a packet yields (previous + current block) / 4 +-- samples (the first one as if its previous block had its own size, as ffmpeg times it). +local function bit(b: buffer, k: number): number + return bit32.extract(buffer.readu8(b, k // 8), k % 8, 1) +end +local function bits(b: buffer, k: number, n: number): number + local v = 0 + for i = n - 1, 0, -1 do + v = v * 2 + bit(b, k + i) + end + return v +end + +local function vorbisModes(id: buffer, setup: buffer): ({ number }?, { boolean }?) + if buffer.len(id) < 30 or buffer.len(setup) < 8 then + return nil, nil + end + local bs = buffer.readu8(id, 28) + local sizes = { 2 ^ (bs % 16), 2 ^ (bs // 16) } + -- the framing bit: the highest set bit of the last non-zero byte + local last = buffer.len(setup) - 1 + while last > 0 and buffer.readu8(setup, last) == 0 do + last -= 1 + end + local v = buffer.readu8(setup, last) + local hb = 7 + while hb > 0 and bit32.extract(v, hb, 1) == 0 do + hb -= 1 + end + local f = last * 8 + hb + local flags: { boolean } = {} + local pos = f + while #flags < 64 and pos - 41 >= 7 * 8 do + local s0 = pos - 41 + if bits(setup, s0 + 1, 16) ~= 0 or bits(setup, s0 + 17, 16) ~= 0 then + break + end + table.insert(flags, 1, bit(setup, s0) == 1) + pos = s0 + end + -- the largest count whose 6-bit field matches + for n = #flags, 1, -1 do + local start = f - 41 * n + if start - 6 >= 0 and bits(setup, start - 6, 6) == n - 1 then + local out = {} + for i = #flags - n + 1, #flags do + table.insert(out, flags[i]) + end + return sizes, out + end + end + return nil, nil +end + +local function adts(track: Types.Track, packets: { Types.Packet }): (buffer?, Err.Err?) + local c = track.config + local profile, rateIndex, chanConfig + if c and buffer.len(c) >= 2 then + local b0, b1 = buffer.readu8(c, 0), buffer.readu8(c, 1) + profile = b0 // 8 -- audio object type + rateIndex = (b0 % 8) * 2 + b1 // 128 + chanConfig = (b1 // 8) % 16 + else + local rates = { 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350 } + profile = 2 + rateIndex = 4 + for i, r in rates do + if r == math.floor((track.sampleRate or 44100) + 0.5) then + rateIndex = i - 1 + end + end + chanConfig = track.channels or 2 + end + if profile < 1 or profile > 4 or rateIndex > 12 then + return nil, Err.new(Err.UNSUPPORTED, "AAC object type " .. tostring(profile) .. " in ADTS") + end + local w = Bytes.writer(64) + for _, p in packets do + local len = buffer.len(p.data) + 7 + w:u8(0xFF) + w:u8(0xF1) + w:u8((profile - 1) * 64 + rateIndex * 4 + chanConfig // 4) + w:u8((chanConfig % 4) * 64 + (len // 2048) % 4) + w:u8((len // 8) % 256) + w:u8((len % 8) * 32 + 0x1F) + w:u8(0xFC) + w:bytes(p.data) + end + return w:finish(), nil +end + +-- trim: a container's codec delay (Matroska CodecDelay, an MP4 edit's media time for MP2 / MP3 / AAC, as ffmpeg) +-- and end padding +function AudioWrap.trim(dec: any, skip: number, length: number?): any + if skip <= 0 and length == nil then + return dec + end + skip = math.max(0, skip) + local rate = dec.sampleRate + local w: any = setmetatable({}, { __index = dec }) + w.frames = math.max(0, (dec.frames or 0) - skip) + if length then + w.frames = if (dec.frames or 0) > 0 then math.min(w.frames, length) else length + end + w.duration = w.frames / rate + local cap = length or math.huge + local delivered = 0 + local function drop() + local left = skip + while left > 0 do + local _, n = dec:read(math.min(left, 4096)) + if not n or n <= 0 then + break + end + left -= n + end + end + local started = false + function w.read(_: any, n: number, out: buffer?): (buffer, number) + if not started then + started = true + drop() + end + local want = math.min(n, cap - delivered) + if want <= 0 then + return out or buffer.create(0), 0 + end + local b, got = dec:read(want, out) + delivered += got + return b, got + end + function w.seek(_: any, seconds: number) + started = true + if seconds <= 0 then + dec:seek(0) + drop() + delivered = 0 + else + dec:seek(seconds + skip / rate) + delivered = math.floor(seconds * rate + 0.5) + end + end + function w.position(_: any): number + return math.max(0, dec:position() - skip / rate) + end + return w +end + +function AudioWrap.wrap(dmx: any, track: Types.Track): (buffer?, string?, Err.Err?) + if type(track) ~= "table" or track.kind ~= "audio" then + return nil, nil, Err.new(Err.ARG, "not an audio track") + end + if track.unsupported then + return nil, nil, Err.new(Err.UNSUPPORTED, track.unsupported) + end + local codec = track.codec + local packets = allPackets(dmx, track) + if #packets == 0 then + return nil, nil, Err.new(Err.CORRUPT, "audio track without packets") + end + if track.waveFormat and string.sub(codec, 1, 6) == "adpcm_" then + return wav(track.waveFormat, concat(packets)), "wav", nil + end + if codec == "adpcm_swf" then + local b, err = swfWav(track, packets) + return b, if b then "wav" else nil, err + end + if PCM[codec] then + local b, err = pcmWav(track, packets) + return b, if b then "wav" else nil, err + end + if codec == "mp3" or codec == "mp2" or codec == "mp1" then + return concat(packets), "mp3", nil + end + if codec == "ac3" then + return concat(packets), "ac3", nil + end + if codec == "flac" then + local c = track.config + local prefix: buffer? = nil + if c and buffer.len(c) >= 4 and buffer.readstring(c, 0, 4) == "fLaC" then + prefix = c + elseif c and buffer.len(c) >= 34 then + -- metadata blocks without the marker (MP4 dfLa payload after version / flags) + local start = if buffer.len(c) >= 38 and buffer.readu8(c, 0) == 0 and buffer.readu8(c, 4) % 128 == 0 then 4 else 0 + local b = buffer.create(4 + buffer.len(c) - start) + buffer.writestring(b, 0, "fLaC") + buffer.copy(b, 4, c, start) + prefix = b + else + return nil, nil, Err.new(Err.CORRUPT, "FLAC track without its STREAMINFO") + end + return concat(packets, prefix), "flac", nil + end + if codec == "opus" then + local head = opusHead(track) + local pre = buffer.readu16(head, 10) + local g = pre + local out = ogg({ head, opusTags() }, packets, function(p: Types.Packet): number + g += opusSamples(p.data) + local d = (p :: any).discardPadding + if type(d) == "number" and d > 0 then + return g - math.floor(d * 48000 + 0.5) -- the end trimming (WebM DiscardPadding) + end + return g + end) + return out, "opus", nil + end + if codec == "vorbis" then + local c = track.config + local headers = c and xiphHeaders(c) + if not headers or #headers ~= 3 then + return nil, nil, Err.new(Err.CORRUPT, "Vorbis track without its three headers") + end + local sizes, modes = vorbisModes(headers[1], headers[3]) + local granule, prev = 0, nil :: number? + local rate = track.sampleRate or 44100 + local scale = track.timescale + local out = ogg(headers, packets, function(p: Types.Packet): number + if not sizes or not modes then + return math.floor((p.pts + (p.duration or 0)) / scale * rate + 0.5) -- from the container's times + end + local d = p.data + if buffer.len(d) == 0 or buffer.readu8(d, 0) % 2 ~= 0 then + return granule + end + local mb = 0 + while 2 ^ mb < #(modes :: { boolean }) do + mb += 1 + end + local m = if mb > 0 and buffer.len(d) * 8 > mb then bits(d, 1, mb) else 0 + local cur = sizes[if (modes :: { boolean })[m + 1] then 2 else 1] + if prev then + granule += (prev + cur) // 4 + end + prev = cur + return granule + end) + return out, "vorbis", nil + end + if codec == "aac" then + if track.adts then + return concat(packets), "aac", nil -- already ADTS (MPEG-TS) + end + local b, err = adts(track, packets) + return b, if b then "aac" else nil, err + end + return nil, nil, Err.new(Err.UNSUPPORTED, "no audio format for codec " .. tostring(codec)) +end + +return AudioWrap +end +__FILES["containers/Ogg/Mux"] = @native function() + + + +-- containers/Ogg/Mux: the Ogg page writer (RFC 3533), for Ogg Opus / Vorbis / FLAC output. New in rosetta. +-- Packets are laced into pages per logical stream; a page is closed when it reaches opts.pageSize bytes of data (or +-- 255 lacing values), when a packet asks for flush, and at the end (eos). The page granule is the granule of the last +-- packet that finishes on it (-1 when none does). Pages go to the output in the order they close, so the bos pages +-- of a multiplexed file come first when every stream's first packet is written (with flush) before any other. +-- Never throws: a bad argument returns false, Err. +local Err = __include("core/Err") +local Page = __include("containers/Ogg/Page") + +local CRC = Page.CRC_TABLE +local readu8, writeu8, writeu32, writei32 = buffer.readu8, buffer.writeu8, buffer.writeu32, buffer.writei32 +local bxor, lshift, rshift = bit32.bxor, bit32.lshift, bit32.rshift + +local Mux = {} +Mux.__index = Mux +local Stream = {} +Stream.__index = Stream + +type Options = { + pageSize: number?, -- close a page once its data reaches this many bytes (default 4096; at most 255 * 255) +} +type PacketOptions = { + flush: boolean?, -- close the page after this packet (headers; default false) + eos: boolean?, -- this is the stream's last packet (default false: finish() writes an empty eos page if needed) +} + +@native function Mux.new(opts: Options?): any + local size = opts and opts.pageSize or 4096 + if type(size) ~= "number" or size < 1 then + size = 4096 + end + return setmetatable({ + pageSize = math.min(size, 255 * 255), + chunks = {} :: { buffer }, + total = 0, + streams = {} :: { any }, + nextSerial = 1, + }, Mux) +end + +@native function Mux.stream(self: any, serial: number?): any + local sr = serial or self.nextSerial + self.nextSerial = math.max(self.nextSerial, sr + 1) + local s = setmetatable({ + mux = self, + serial = sr % 4294967296, + seq = 0, + lacing = {} :: { number }, + parts = {} :: { any }, -- buffer, offset, length triples of the page data + dataLen = 0, + granule = -1, + continued = false, -- the page being built starts with the tail of a packet + first = true, + ended = false, + lastGranule = -1, + }, Stream) + table.insert(self.streams, s) + return s +end + +-- the CRC of a page (the crc field written as zero) +@native local function crc(b: buffer, n: number): number + local c = 0 + for i = 0, n - 1 do + c = bxor(lshift(c, 8), CRC[bxor(rshift(c, 24), readu8(b, i)) + 1]) + end + return c +end + +@native function Stream._flush(self: any, eos: boolean) + local nseg = #self.lacing + local n = 27 + nseg + self.dataLen + local b = buffer.create(n) + buffer.writestring(b, 0, "OggS") + local flags = (if self.continued then 1 else 0) + (if self.first then 2 else 0) + (if eos then 4 else 0) + writeu8(b, 5, flags) + local g = self.granule + if g < 0 then + writeu32(b, 6, 0xFFFFFFFF) + writei32(b, 10, -1) + else + writeu32(b, 6, g % 4294967296) + writeu32(b, 10, (g // 4294967296) % 4294967296) + end + writeu32(b, 14, self.serial) + writeu32(b, 18, self.seq % 4294967296) + writeu8(b, 26, nseg) + for i = 1, nseg do + writeu8(b, 26 + i, self.lacing[i]) + end + local o = 27 + nseg + local parts = self.parts + for i = 1, #parts, 3 do + buffer.copy(b, o, parts[i], parts[i + 1], parts[i + 2]) + o += parts[i + 2] + end + writeu32(b, 22, crc(b, n)) + local m = self.mux + table.insert(m.chunks, b) + m.total += n + self.seq += 1 + self.first = false + self.lacing, self.parts, self.dataLen, self.granule = {}, {}, 0, -1 + self.continued = false + if eos then + self.ended = true + end +end + +@native function Stream.packet(self: any, data: any, granule: number, opts: PacketOptions?, offset: number?, length: number?): (boolean, Err.Err?) + if self.ended then + return false, Err.new(Err.ARG, "packet after the end of stream " .. self.serial) + end + local b: buffer + if type(data) == "string" then + b = buffer.fromstring(data) + elseif type(data) == "buffer" then + b = data + else + return false, Err.new(Err.ARG, "packet: data must be a buffer or a string") + end + if type(granule) ~= "number" then + return false, Err.new(Err.ARG, "packet: granule must be a number") + end + local off = offset or 0 + local len = length or (buffer.len(b) - off) + if off < 0 or len < 0 or off + len > buffer.len(b) then + return false, Err.new(Err.ARG, "packet: range outside the buffer") + end + local pageSize = self.mux.pageSize + local left = len + local pos = off + -- lacing: 255-byte segments then one < 255 (0 when the size is a multiple of 255) + while true do + if #self.lacing == 255 or (self.dataLen >= pageSize and #self.lacing > 0) then + self:_flush(false) + self.continued = pos > off -- the next page starts inside this packet + end + local seg = math.min(left, 255) + table.insert(self.lacing, seg) + if seg > 0 then + table.insert(self.parts, b) + table.insert(self.parts, pos) + table.insert(self.parts, seg) + end + self.dataLen += seg + pos += seg + left -= seg + if seg < 255 then + break + end + end + if granule >= 0 then -- -1 (unknown) keeps the granule of an earlier packet finishing on this page + self.granule = granule + self.lastGranule = granule + end + local eos = opts and opts.eos or false + if eos then + self:_flush(true) + elseif (opts and opts.flush) or self.dataLen >= pageSize or #self.lacing == 255 then + self:_flush(false) + end + return true, nil +end + +@native function Stream.flush(self: any) + if not self.ended and #self.lacing > 0 then + self:_flush(false) + end +end + +@native function Mux.finish(self: any): buffer + for _, s in self.streams do + if not s.ended then + if #s.lacing == 0 then + s.granule = s.lastGranule + end + s:_flush(true) + end + end + local out = buffer.create(self.total) + local o = 0 + for _, c in self.chunks do + buffer.copy(out, o, c, 0, buffer.len(c)) + o += buffer.len(c) + end + return out +end + +return Mux +end +__FILES["containers/Ogg/Page"] = @native function() + + + +-- containers/Ogg/Page: Ogg pages (RFC 3533): the CRC-32 (poly 0x04C11DB7, MSB first, init 0, the crc field read as +-- zero), header parsing and the capture-pattern resync. Absorbed from ogg-luau be9f604 (same author, no third-party +-- code). Never throws: invalid or truncated data gives nil. +-- A page header (27 bytes + segment table): +-- 0 "OggS" | 4 version (0) | 5 flags (1 continued, 2 bos, 4 eos) | 6 granule (i64 LE) | 14 serial (u32) +-- 18 sequence (u32) | 22 crc (u32) | 26 segment count | 27 lacing values | data +local Crc32 = __include("core/Crc32") +local readu8, readu32, readi32 = buffer.readu8, buffer.readu32, buffer.readi32 +local band, bxor, lshift, rshift = bit32.band, bit32.bxor, bit32.lshift, bit32.rshift + +local Page = {} + +type Info = { + offset: number, -- byte offset of "OggS" + size: number, -- header + segment table + data + headerSize: number, -- 27 + segment count + nsegs: number, + flags: number, + continued: boolean, + bos: boolean, + eos: boolean, + granule: number, -- -1 when no packet finishes on this page + serial: number, + sequence: number, +} + +-- CRC table, MSB-first (core/Crc32) +local CRC = Crc32.MSB_TABLE +Page.CRC_TABLE = CRC + +@native local function crcRange(b: buffer, from: number, to: number, crc: number): number + for i = from, to - 1 do + crc = bxor(lshift(crc, 8), CRC[bxor(rshift(crc, 24), readu8(b, i)) + 1]) + end + return crc +end + +-- the Ogg CRC-32 of arbitrary data (the crc field is not zeroed) +@native function Page.crc32(b: buffer, offset: number?, len: number?): number + local o = offset or 0 + local n = len or (buffer.len(b) - o) + if o < 0 or n < 0 or o + n > buffer.len(b) then + return 0 + end + return crcRange(b, o, o + n, 0) +end + +@native function Page.parse(b: buffer, pos: number, verify: boolean?): (Info?, string?) + local size = buffer.len(b) + if pos < 0 or pos + 27 > size then + return nil, "short" + end + if readu32(b, pos) ~= 0x5367674F then -- "OggS" + return nil, "magic" + end + if readu8(b, pos + 4) ~= 0 then + return nil, "version" + end + local nsegs = readu8(b, pos + 26) + local hsize = 27 + nsegs + if pos + hsize > size then + return nil, "short" + end + local dlen = 0 + for i = pos + 27, pos + hsize - 1 do + dlen += readu8(b, i) + end + local total = hsize + dlen + if pos + total > size then + return nil, "short" + end + if verify ~= false then + local c = crcRange(b, pos, pos + 22, 0) + for _ = 1, 4 do + c = bxor(lshift(c, 8), CRC[rshift(c, 24) + 1]) + end + c = crcRange(b, pos + 26, pos + total, c) + if c ~= readu32(b, pos + 22) then + return nil, "crc" + end + end + local flags = readu8(b, pos + 5) + return { + offset = pos, + size = total, + headerSize = hsize, + nsegs = nsegs, + flags = flags, + continued = band(flags, 1) ~= 0, + bos = band(flags, 2) ~= 0, + eos = band(flags, 4) ~= 0, + granule = readi32(b, pos + 10) * 4294967296 + readu32(b, pos + 6), + serial = readu32(b, pos + 14), + sequence = readu32(b, pos + 18), + }, nil +end + +@native function Page.find(b: buffer, pos: number, limit: number?, verify: boolean?): Info? + local size = buffer.len(b) + local lim = math.min(limit or size, size - 27 + 1) + if pos < 0 then + pos = 0 + end + while pos < lim do + if readu8(b, pos) == 0x4F and readu32(b, pos) == 0x5367674F then + local p = Page.parse(b, pos, verify) + if p then + return p + end + end + pos += 1 + end + return nil +end + +@native function Page.findBack(b: buffer, pos: number, floor: number?, verify: boolean?): Info? + local size = buffer.len(b) + local lo = math.max(floor or 0, 0) + if pos > size - 27 then + pos = size - 27 + end + while pos >= lo do + if readu8(b, pos) == 0x4F and readu32(b, pos) == 0x5367674F then + local p = Page.parse(b, pos, verify) + if p then + return p + end + end + pos -= 1 + end + return nil +end + +@native function Page.codec(b: buffer, off: number, len: number): string + @native local function is(s: string, at: number): boolean + if at + #s > len then + return false + end + for i = 1, #s do + if readu8(b, off + at + i - 1) ~= string.byte(s, i) then + return false + end + end + return true + end + if is("OpusHead", 0) then + return "opus" + elseif len >= 5 and readu8(b, off) == 0x7F and is("FLAC", 1) then + return "flac" + elseif len >= 7 and readu8(b, off) == 1 and is("vorbis", 1) then + return "vorbis" + elseif len >= 7 and readu8(b, off) == 0x80 and is("theora", 1) then + return "theora" + elseif is("Speex ", 0) then + return "speex" + elseif is("fishead", 0) then + return "skeleton" + elseif is("fLaC", 0) then + return "flac-old" -- pre-1.1.1 Ogg FLAC mapping + end + return "unknown" +end + +return Page +end +__FILES["core/Bytes"] = @native function() + + +-- core/Bytes: a cursor Reader over a buffer range and a growable Writer. Little / big endian integers up to u64 (as a +-- double: exact to 2^53), f16 / f32 / f64, C strings, fixed strings, and zero-copy sub-readers. +-- Never throws. A read past the end (or a failed seek) sets the reader's sticky `err` (Err.TRUNCATED), moves the cursor +-- to the end and returns 0 / "" (a zero-length buffer for bytes()); check `r.err` once after a run of reads. +local Err = __include("core/Err") + +local readu8, readi8, readu16, readi16, readu32, readi32 = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.readi32 +local readf32, readf64, readstring = buffer.readf32, buffer.readf64, buffer.readstring +local writeu8, writeu16, writeu32, writef32, writef64, writestring = buffer.writeu8, buffer.writeu16, buffer.writeu32, buffer.writef32, buffer.writef64, buffer.writestring +local bcreate, bcopy, bfill, blen = buffer.create, buffer.copy, buffer.fill, buffer.len +local byteswap = bit32.byteswap + +local TWO32 = 4294967296 +local scratch = bcreate(8) -- reinterpret casts for big-endian floats + +local Bytes = {} + +local Reader = {} +Reader.__index = Reader + +type Reader = typeof(setmetatable( + {} :: { + buf: buffer, + pos: number, -- absolute offset of the next byte in buf + base: number, -- absolute offset of the reader's first byte + limit: number, -- absolute offset just past the reader's last byte + err: Err.Err?, -- sticky: the first failure + }, + Reader +)) + +@native function Bytes.reader(buf: buffer, offset: number?, length: number?): Reader + local n = blen(buf) + local o = math.clamp(offset or 0, 0, n) + local l = math.clamp(length or (n - o), 0, n - o) + return setmetatable({ buf = buf, pos = o, base = o, limit = o + l, err = nil :: Err.Err? }, Reader) +end + +@native function Reader.fail(self: Reader, code: string, message: string): (nil, Err.Err) + if not self.err then + self.err = Err.new(code, message, self.pos) + end + return nil, self.err :: Err.Err +end + +@native function Reader.need(self: Reader, n: number): boolean + if self.pos + n <= self.limit and n >= 0 then + return true + end + if not self.err then + self.err = Err.new(Err.TRUNCATED, string.format("need %d bytes, %d left", n, self.limit - self.pos), self.pos) + end + self.pos = self.limit + return false +end + +@native function Reader.tell(self: Reader): number + return self.pos - self.base +end +@native function Reader.size(self: Reader): number + return self.limit - self.base +end +@native function Reader.remaining(self: Reader): number + return self.limit - self.pos +end +@native function Reader.eof(self: Reader): boolean + return self.pos >= self.limit +end + +@native function Reader.seek(self: Reader, offset: number): boolean + if offset < 0 or self.base + offset > self.limit then + self.pos = self.limit + if not self.err then + self.err = Err.new(Err.TRUNCATED, "seek to " .. offset .. " past the end", self.base + offset) + end + return false + end + self.pos = self.base + offset + return true +end + +@native function Reader.skip(self: Reader, n: number): boolean + if self:need(n) then + self.pos += n + return true + end + return false +end + +@native function Reader.align(self: Reader, n: number): boolean + local r = (self.pos - self.base) % n + if r == 0 then + return true + end + return self:skip(n - r) +end + +@native function Reader.u8(self: Reader): number + local p = self.pos + if p + 1 > self.limit then + self:need(1) + return 0 + end + self.pos = p + 1 + return readu8(self.buf, p) +end +@native function Reader.i8(self: Reader): number + local p = self.pos + if p + 1 > self.limit then + self:need(1) + return 0 + end + self.pos = p + 1 + return readi8(self.buf, p) +end +@native function Reader.u16le(self: Reader): number + local p = self.pos + if p + 2 > self.limit then + self:need(2) + return 0 + end + self.pos = p + 2 + return readu16(self.buf, p) +end +@native function Reader.u16be(self: Reader): number + local p = self.pos + if p + 2 > self.limit then + self:need(2) + return 0 + end + self.pos = p + 2 + return readu8(self.buf, p) * 256 + readu8(self.buf, p + 1) +end +@native function Reader.i16le(self: Reader): number + local p = self.pos + if p + 2 > self.limit then + self:need(2) + return 0 + end + self.pos = p + 2 + return readi16(self.buf, p) +end +@native function Reader.i16be(self: Reader): number + local v = self:u16be() + return if v >= 32768 then v - 65536 else v +end +@native function Reader.u24le(self: Reader): number + local p = self.pos + if p + 3 > self.limit then + self:need(3) + return 0 + end + self.pos = p + 3 + return readu16(self.buf, p) + readu8(self.buf, p + 2) * 65536 +end +@native function Reader.u24be(self: Reader): number + local p = self.pos + if p + 3 > self.limit then + self:need(3) + return 0 + end + self.pos = p + 3 + return readu8(self.buf, p) * 65536 + readu8(self.buf, p + 1) * 256 + readu8(self.buf, p + 2) +end +@native function Reader.u32le(self: Reader): number + local p = self.pos + if p + 4 > self.limit then + self:need(4) + return 0 + end + self.pos = p + 4 + return readu32(self.buf, p) +end +@native function Reader.u32be(self: Reader): number + local p = self.pos + if p + 4 > self.limit then + self:need(4) + return 0 + end + self.pos = p + 4 + return byteswap(readu32(self.buf, p)) +end +@native function Reader.i32le(self: Reader): number + local p = self.pos + if p + 4 > self.limit then + self:need(4) + return 0 + end + self.pos = p + 4 + return readi32(self.buf, p) +end +@native function Reader.i32be(self: Reader): number + local v = self:u32be() + return if v >= 2147483648 then v - TWO32 else v +end +@native function Reader.u64le(self: Reader): number + local lo = self:u32le() + return lo + self:u32le() * TWO32 +end +@native function Reader.u64be(self: Reader): number + local hi = self:u32be() + return hi * TWO32 + self:u32be() +end +@native function Reader.i64le(self: Reader): number + local lo = self:u32le() + return lo + self:i32le() * TWO32 +end +@native function Reader.i64be(self: Reader): number + local hi = self:i32be() + return hi * TWO32 + self:u32be() +end + +@native local function half(h: number): number + local s = if h >= 32768 then -1 else 1 + local e = bit32.band(bit32.rshift(h, 10), 31) + local m = bit32.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 +Bytes.half = half + +@native function Reader.f16le(self: Reader): number + return half(self:u16le()) +end +@native function Reader.f16be(self: Reader): number + return half(self:u16be()) +end +@native function Reader.f32le(self: Reader): number + local p = self.pos + if p + 4 > self.limit then + self:need(4) + return 0 + end + self.pos = p + 4 + return readf32(self.buf, p) +end +@native function Reader.f32be(self: Reader): number + local v = self:u32be() + writeu32(scratch, 0, v) + return readf32(scratch, 0) +end +@native function Reader.f64le(self: Reader): number + local p = self.pos + if p + 8 > self.limit then + self:need(8) + return 0 + end + self.pos = p + 8 + return readf64(self.buf, p) +end +@native function Reader.f64be(self: Reader): number + local hi = self:u32be() + local lo = self:u32be() + writeu32(scratch, 0, lo) + writeu32(scratch, 4, hi) + return readf64(scratch, 0) +end + +@native function Reader.string(self: Reader, n: number): string + local p = self.pos + if n < 0 or p + n > self.limit then + self:need(n) + return "" + end + self.pos = p + n + return readstring(self.buf, p, n) +end + +@native function Reader.fixed(self: Reader, n: number): string + local s = self:string(n) + local z = string.find(s, "\0", 1, true) + return if z then string.sub(s, 1, z - 1) else s +end + +@native function Reader.cstring(self: Reader, max: number?): string + local p = self.pos + local e = if max then math.min(self.limit, p + max) else self.limit + local q = p + local buf = self.buf + while q < e and readu8(buf, q) ~= 0 do + q += 1 + end + if q >= e then + self.pos = e + self:need(1) + return readstring(buf, p, e - p) + end + self.pos = q + 1 + return readstring(buf, p, q - p) +end + +@native function Reader.match(self: Reader, s: string): boolean + local p, n = self.pos, #s + if p + n > self.limit or readstring(self.buf, p, n) ~= s then + return false + end + self.pos = p + n + return true +end + +@native function Reader.peek(self: Reader, n: number, at: number?): string + local p = self.pos + (at or 0) + if p < self.base or p >= self.limit then + return "" + end + return readstring(self.buf, p, math.min(n, self.limit - p)) +end + +@native function Reader.peekU8(self: Reader, at: number?): number + local p = self.pos + (at or 0) + if p < self.base or p >= self.limit then + return -1 + end + return readu8(self.buf, p) +end + +@native function Reader.bytes(self: Reader, n: number): buffer + local p = self.pos + if n < 0 or p + n > self.limit then + self:need(n) + return bcreate(0) + end + local b = bcreate(n) + bcopy(b, 0, self.buf, p, n) + self.pos = p + n + return b +end + +@native function Reader.slice(self: Reader, n: number): Reader + local p = self.pos + local l = math.max(0, math.min(n, self.limit - p)) + if l < n then + self:need(n) + else + self.pos = p + n + end + return setmetatable({ buf = self.buf, pos = p, base = p, limit = p + l, err = nil :: Err.Err? }, Reader) +end + +@native function Reader.sub(self: Reader, offset: number, length: number?): Reader + local o = math.clamp(self.base + offset, self.base, self.limit) + local l = math.clamp(length or (self.limit - o), 0, self.limit - o) + return setmetatable({ buf = self.buf, pos = o, base = o, limit = o + l, err = nil :: Err.Err? }, Reader) +end + +local Writer = {} +Writer.__index = Writer + +type Writer = typeof(setmetatable( + {} :: { + buf: buffer, + pos: number, -- bytes written (the next write offset) + }, + Writer +)) + +@native function Bytes.writer(capacity: number?): Writer + return setmetatable({ buf = bcreate(math.max(16, capacity or 256)), pos = 0 }, Writer) +end + +@native function Writer.reserve(self: Writer, n: number): number + local p = self.pos + local cap = blen(self.buf) + if p + n > cap then + local nb = bcreate(math.max(cap * 2, p + n)) + bcopy(nb, 0, self.buf, 0, p) + self.buf = nb + end + return p +end + +@native function Writer.tell(self: Writer): number + return self.pos +end + +@native function Writer.u8(self: Writer, v: number) + local p = self:reserve(1) + writeu8(self.buf, p, v) + self.pos = p + 1 +end +@native function Writer.u16le(self: Writer, v: number) + local p = self:reserve(2) + writeu16(self.buf, p, v) + self.pos = p + 2 +end +@native function Writer.u16be(self: Writer, v: number) + local p = self:reserve(2) + writeu8(self.buf, p, bit32.rshift(v, 8)) + writeu8(self.buf, p + 1, v) + self.pos = p + 2 +end +@native function Writer.u24le(self: Writer, v: number) + local p = self:reserve(3) + writeu16(self.buf, p, v) + writeu8(self.buf, p + 2, bit32.rshift(v, 16)) + self.pos = p + 3 +end +@native function Writer.u24be(self: Writer, v: number) + local p = self:reserve(3) + writeu8(self.buf, p, bit32.rshift(v, 16)) + writeu8(self.buf, p + 1, bit32.rshift(v, 8)) + writeu8(self.buf, p + 2, v) + self.pos = p + 3 +end +@native function Writer.u32le(self: Writer, v: number) + local p = self:reserve(4) + writeu32(self.buf, p, v) + self.pos = p + 4 +end +@native function Writer.u32be(self: Writer, v: number) + local p = self:reserve(4) + writeu32(self.buf, p, byteswap(v % TWO32)) + self.pos = p + 4 +end +Writer.i8 = Writer.u8 +Writer.i16le = Writer.u16le +Writer.i16be = Writer.u16be +Writer.i32le = Writer.u32le +Writer.i32be = Writer.u32be +@native function Writer.u64le(self: Writer, v: number) + self:u32le(v % TWO32) + self:u32le(math.floor(v / TWO32) % TWO32) +end +@native function Writer.u64be(self: Writer, v: number) + self:u32be(math.floor(v / TWO32) % TWO32) + self:u32be(v % TWO32) +end +Writer.i64le = Writer.u64le +Writer.i64be = Writer.u64be +@native function Writer.f32le(self: Writer, v: number) + local p = self:reserve(4) + writef32(self.buf, p, v) + self.pos = p + 4 +end +@native function Writer.f32be(self: Writer, v: number) + writef32(scratch, 0, v) + self:u32be(readu32(scratch, 0)) +end +@native function Writer.f64le(self: Writer, v: number) + local p = self:reserve(8) + writef64(self.buf, p, v) + self.pos = p + 8 +end +@native function Writer.f64be(self: Writer, v: number) + writef64(scratch, 0, v) + self:u32be(readu32(scratch, 4)) + self:u32be(readu32(scratch, 0)) +end + +@native function Writer.string(self: Writer, s: string) + local n = #s + local p = self:reserve(n) + writestring(self.buf, p, s) + self.pos = p + n +end +@native function Writer.cstring(self: Writer, s: string) + self:string(s) + self:u8(0) +end +@native function Writer.bytes(self: Writer, b: buffer, offset: number?, length: number?) + local o = offset or 0 + local n = length or (blen(b) - o) + local p = self:reserve(n) + bcopy(self.buf, p, b, o, n) + self.pos = p + n +end +@native function Writer.fill(self: Writer, v: number, n: number) + local p = self:reserve(n) + bfill(self.buf, p, v, n) + self.pos = p + n +end + +@native function Writer.setU32le(self: Writer, at: number, v: number) + writeu32(self.buf, at, v) +end +@native function Writer.setU32be(self: Writer, at: number, v: number) + writeu32(self.buf, at, byteswap(v % TWO32)) +end +@native function Writer.setU16le(self: Writer, at: number, v: number) + writeu16(self.buf, at, v) +end +@native function Writer.setU8(self: Writer, at: number, v: number) + writeu8(self.buf, at, v) +end + +@native function Writer.finish(self: Writer): buffer + local b = bcreate(self.pos) + bcopy(b, 0, self.buf, 0, self.pos) + return b +end + +Bytes.Reader = Reader +Bytes.Writer = Writer + +@native 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 + +@native 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 +end +__FILES["core/Crc32"] = @native function() + + +-- core/Crc32: CRC-32 (IEEE 802.3, the zlib / gzip / zip / PNG polynomial 0xEDB88320, reflected), slice-by-8. +-- Absorbed from deflate-luau src/Deflate/Checksum.luau (same author; no third-party code). Never throws. +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) +local T4, T5, T6, T7 = table.create(256, 0), table.create(256, 0), table.create(256, 0), table.create(256, 0) +for n = 0, 255 do + local c = n + for _ = 1, 8 do + if band(c, 1) ~= 0 then + c = bxor(0xEDB88320, rshift(c, 1)) + else + c = rshift(c, 1) + end + end + T0[n + 1] = c +end +for n = 0, 255 do + local c = T0[n + 1] + c = bxor(T0[band(c, 255) + 1], rshift(c, 8)) + T1[n + 1] = c + c = bxor(T0[band(c, 255) + 1], rshift(c, 8)) + T2[n + 1] = c + c = bxor(T0[band(c, 255) + 1], rshift(c, 8)) + T3[n + 1] = c + c = bxor(T0[band(c, 255) + 1], rshift(c, 8)) + T4[n + 1] = c + c = bxor(T0[band(c, 255) + 1], rshift(c, 8)) + T5[n + 1] = c + c = bxor(T0[band(c, 255) + 1], rshift(c, 8)) + T6[n + 1] = c + c = bxor(T0[band(c, 255) + 1], rshift(c, 8)) + T7[n + 1] = c +end + +@native local function crc32(buf: buffer, off: number, len: number, crc: number?): number + local c = bxor(crc or 0, 0xFFFFFFFF) + local i, e = off, off + len + local e8 = e - 8 + while i <= e8 do + c = bxor(c, readu32(buf, i)) + local d = readu32(buf, i + 4) + c = bxor( + T7[band(c, 255) + 1], + T6[band(rshift(c, 8), 255) + 1], + T5[band(rshift(c, 16), 255) + 1], + T4[rshift(c, 24) + 1], + T3[band(d, 255) + 1], + T2[band(rshift(d, 8), 255) + 1], + T1[band(rshift(d, 16), 255) + 1], + T0[rshift(d, 24) + 1] + ) + i += 8 + end + local e4 = e - 4 + while i <= e4 do + c = bxor(c, readu32(buf, i)) + c = bxor(T3[band(c, 255) + 1], T2[band(rshift(c, 8), 255) + 1], T1[band(rshift(c, 16), 255) + 1], T0[rshift(c, 24) + 1]) + i += 4 + end + while i < e do + c = bxor(T0[band(bxor(c, readu8(buf, i)), 255) + 1], rshift(c, 8)) + i += 1 + end + return bxor(c, 0xFFFFFFFF) +end + +@native local function range(buf: buffer, offset: number?, length: number?): (number, number) + local n = buffer.len(buf) + local o = math.clamp(offset or 0, 0, n) + return o, math.clamp(length or (n - o), 0, n - o) +end + +local Crc32 = {} + +@native function Crc32.of(buf: buffer, offset: number?, length: number?, crc: number?): number + local o, l = range(buf, offset, length) + return crc32(buf, o, l, crc) +end + +@native function Crc32.string(s: string, crc: number?): number + return crc32(buffer.fromstring(s), 0, #s, crc) +end + +Crc32.raw = crc32 + +-- MSB-first CRC-32 (polynomial 0x04C11DB7, not reflected, raw register, no inversions): Ogg pages (init 0), +-- MPEG-2 PSI sections and bzip2 blocks (init 0xFFFFFFFF) +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 + +@native 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 +end +__FILES["core/Err"] = function() + +-- core/Err: the error values every decoder / encoder returns (`nil, err`; nothing in the library throws on bad data). +-- An Err is a table { code, message, offset?, format? } that prints as "png: CORRUPT at 0x1234: bad filter type 7". +-- Never throws: --!native modules may require it. +local Err = {} + +-- codes +Err.TRUNCATED = "TRUNCATED" -- the data ends early +Err.CORRUPT = "CORRUPT" -- the data is malformed (bad magic inside, bad table, out-of-range field) +Err.CHECKSUM = "CHECKSUM" -- a CRC / Adler / hash mismatch +Err.UNSUPPORTED = "UNSUPPORTED" -- valid data using a feature this library does not implement, or no encoder +Err.UNKNOWN_FORMAT = "UNKNOWN_FORMAT" -- no format recognised the data / name +Err.LIMIT = "LIMIT" -- over a size limit (opts.maxPixels, opts.maxBytes, ...) +Err.ARG = "ARG" -- a bad argument (wrong type, out-of-range option) +Err.IO = "IO" -- reading or writing a file failed, or the host has no file system + +type Err = { + code: string, + message: string, + offset: number?, + format: string?, +} + +local Meta = {} +Meta.__tostring = function(e: Err): string + local s = if e.format then e.format .. ": " .. e.code else e.code + if e.offset then + s ..= string.format(" at 0x%x", e.offset) + end + return s .. ": " .. e.message +end + +function Err.new(code: string, message: string, offset: number?): Err + return setmetatable({ code = code, message = message, offset = offset, format = nil :: string? }, Meta) :: any +end + +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 + +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: string? = 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 :: string, msg, offset) +end + +function Err.is(v: any): boolean + return type(v) == "table" and getmetatable(v) == Meta +end + +function Err.wrap(e: any, format: string?): Err + if not Err.is(e) then + e = Err.new(Err.CORRUPT, tostring(e)) + end + if e.format == nil then + e.format = format + end + return e +end + +return table.freeze(Err) +end +__FILES["core/Input"] = function() + +-- core/Input: turns what the caller passed (a buffer, a string of bytes, or a file path) into a buffer, reading files +-- through the host adapter the API passes in (core never requires host itself). +-- A string is a path when opts.path is true, or when the host has a file system and the string looks like a path +-- (under 4 KB, no NUL / newline) and the file exists; otherwise it is the data itself (opts.data = true forces that). +-- name: the path (for the extension fallback) or opts.name. Never throws. +local Err = __include("core/Err") + +local Input = {} + +type HostLike = { + hasFiles: boolean, + readFile: (path: string) -> (buffer?, Err.Err?), + exists: (path: string) -> boolean, +} + +function Input.looksLikePath(s: string): boolean + return #s > 0 and #s < 4096 and not string.find(s, "\0", 1, true) and not string.find(s, "[\n\r]") +end + +function Input.resolve(src: any, opts: any?, host: HostLike?): (buffer?, Err.Err?, string?) + local o = opts or {} + local t = type(src) + if t == "buffer" then + return src, nil, o.name + elseif t == "string" then + local isPath = false + if o.path == true then + isPath = true + elseif o.data ~= true and host and host.hasFiles and Input.looksLikePath(src) then + isPath = host.exists(src) + end + if isPath then + if not host then + return nil, Err.new(Err.IO, "no host to read " .. src), nil + end + local b, err = host.readFile(src) + if not b then + return nil, err, nil + end + return b, nil, src + end + return buffer.fromstring(src), nil, o.name + end + return nil, Err.new(Err.ARG, "expected a buffer, a string or a path, got " .. typeof(src)), nil +end + +function Input.extension(name: string?): string? + if not name then + return nil + end + local ext = string.match(name, "%.([%w_]+)$") + return if ext then string.lower(ext) else nil +end + +function Input.sibling(opts: any?, uri: string): buffer? + if type(opts) ~= "table" then + return nil + end + local v: any = nil + if type(opts.files) == "table" then + v = opts.files[uri] + end + if v == nil and type(opts.resolve) == "function" then + local ok, got = pcall(opts.resolve, uri) + v = if ok then got else nil + end + if type(v) == "string" then + return buffer.fromstring(v) + end + return if type(v) == "buffer" then v else nil +end + +return Input +end +__FILES["host"] = function() + +-- host: the runtime adapter, detected once at load time. Roblox (no file system; toEditableImage), LÖVE +-- (love.filesystem + io; toImageData / toSoundData), plain LuaJIT (io), the Luau CLI (no file system). +local Err = __include("core/Err") + +type Host = { + name: string, + hasFiles: boolean, + readFile: (path: string) -> (buffer?, Err.Err?), + writeFile: (path: string, data: buffer) -> (boolean, Err.Err?), + exists: (path: string) -> boolean, + [string]: any, +} + +local G = _G :: any +local name +if typeof(game) == "Instance" then + name = "roblox" +elseif G.love ~= nil and type(G.love) == "table" and G.love.filesystem ~= nil then + name = "love" +elseif G.jit ~= nil or G.io ~= nil then + name = "luajit" +else + name = "luau" +end + +local host: Host +if name == "roblox" then + host = __include("host/Roblox") :: any +elseif name == "love" then + host = __include("host/Love") :: any +elseif name == "luajit" then + host = __include("host/LuaJIT") :: any +else + host = __include("host/Luau") :: any +end +-- LuaJIT: the big decoders outgrow the default 1000 traces / 8 MB of mcode; _G.ROSETTA_NO_JIT_TUNE = true skips this. +if G.jit ~= nil and type(G.jit.opt) == "table" and not G.ROSETTA_NO_JIT_TUNE then + pcall(G.jit.opt.start, "maxtrace=8000", "maxmcode=65536") +end + +local _ = Err +return host +end +end + + + + + + Core_2 + --!optimize 2 +--!nocheck +-- rosetta chunk Core_2 (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 2 modules (1 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["ops/ImageOps"] = function() + +-- ops/ImageOps: editing on the standard Image: conversion, crop, resize, flips, rotation, compositing, pixel access, +-- animation helpers. New code; the resampling and compositing follow Pillow's C sources. +-- Conventions: angles are degrees counter-clockwise and rotate90 turns are counter-clockwise quarter turns (as +-- Pillow). Resizing and rotating filter premultiplied alpha (as Pillow does for RGBA / LA). Grey is Pillow's +-- L = (19595 R + 38470 G + 7471 B + 32768) >> 16. 8 <-> 16 bit is * 257 and +-- (v * 255 + 32767) // 65535; float <-> integer clamps to 0..1 and rounds (no gamma). alpha8 converts to white with +-- that alpha. yuv420p is JPEG-style BT.601 full range (2x2 box chroma); geometric ops on yuv420p go through rgba8. +local Err = __include("core/Err") +local Types = __include("Types") +local K = __include("ops/ImageOps/Kernels") + +local ImageOps = {} + +local MAX_PIXELS = 2 ^ 26 + +type Image = Types.Image + +local function arg(msg: string): (nil, Err.Err) + return nil, Err.new(Err.ARG, msg) +end + +local function isInt(v: any): boolean + return type(v) == "number" and v == v and v % 1 == 0 and v > -2 ^ 31 and v < 2 ^ 31 +end + +local function bytesOf(fmt: string, w: number, h: number): number? + if fmt == "yuv420p" then + return w * h + 2 * ((w + 1) // 2) * ((h + 1) // 2) + end + local bpp = Types.BPP[fmt] + return if bpp then w * h * bpp else nil +end + +local function check(img: any): (boolean?, Err.Err?) + if type(img) ~= "table" or type(img.pixels) ~= "buffer" then + return arg("expected an Image") + end + if not isInt(img.width) or not isInt(img.height) or img.width < 1 or img.height < 1 then + return arg("bad image size") + end + local need = bytesOf(img.format, img.width, img.height) + if not need then + return arg("unknown pixel format " .. tostring(img.format)) + end + if buffer.len(img.pixels) < need then + return arg("pixel buffer too small for " .. img.width .. " x " .. img.height .. " " .. img.format) + end + return true, nil +end +ImageOps.check = check + +local function limit(w: number, h: number, opts: any): (boolean?, Err.Err?) + 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 + return true, nil +end + +local function like(img: Image, w: number, h: number, fmt: string?): Image + local out = Types.Image.new(w, h, (fmt or img.format) :: any) + for k, v in img.meta do + out.meta[k] = v + end + out.loops = img.loops + return out +end + +function ImageOps.new(w: number, h: number, format: string?): (Image?, Err.Err?) + local fmt = format or "rgba8" + if not isInt(w) or not isInt(h) or w < 1 or h < 1 then + return arg("bad image size") + end + if not bytesOf(fmt, 1, 1) then + return arg("unknown pixel format " .. tostring(fmt)) + end + local ok, e = limit(w, h, nil) + if not ok then + return nil, e + end + return Types.Image.new(w, h, fmt :: any), nil +end + +function ImageOps.copy(img: Image): (Image?, Err.Err?) + local ok, e = check(img) + if not ok then + return nil, e + end + 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, nil +end + +function ImageOps.convert(img: Image, format: string): (Image?, Err.Err?) + local ok, e = check(img) + if not ok then + return nil, e + end + if not bytesOf(format, 1, 1) then + return arg("unknown pixel format " .. tostring(format)) + end + local w, h = img.width, img.height + if img.format == format then + return ImageOps.copy(img) + end + local src = img + if img.format == "yuv420p" then + local rgba = like(img, w, h, "rgba8") + K.yuvToRgba(img.pixels, w, h, rgba.pixels) + if format == "rgba8" then + return rgba, nil + end + src = rgba + end + local out = like(img, w, h, format) + if format == "yuv420p" then + local rgba = src + if src.format ~= "rgba8" then + rgba = like(img, w, h, "rgba8") + 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, nil + end + K.convert(src.pixels, K.ID[src.format], out.pixels, K.ID[format], w * h) + return out, nil +end + +-- ops on yuv420p run on rgba8 and convert back +local function viaRgba(img: Image, f: (Image) -> (Image?, Err.Err?)): (Image?, Err.Err?) + if img.format ~= "yuv420p" then + return f(img) + end + local rgba = ImageOps.convert(img, "rgba8") :: Image + local res, e = f(rgba) + if not res then + return nil, e + end + return ImageOps.convert(res, "yuv420p") +end + +local ALPHA_CH: { [string]: number } = { rgba8 = 4, rgba16 = 4, rgbaf32 = 4, graya8 = 2 } + +function ImageOps.crop(img: Image, x: number, y: number, w: number, h: number): (Image?, Err.Err?) + local ok, e = check(img) + if not ok then + return nil, e + end + if not (isInt(x) and isInt(y) and isInt(w) and isInt(h)) then + return arg("crop: integer x, y, w, h") + end + local x0, y0 = math.max(0, x), math.max(0, y) + local x1, y1 = math.min(img.width, x + w), math.min(img.height, y + h) + if x1 <= x0 or y1 <= y0 then + return arg("crop: the rectangle is outside the image or empty") + end + return viaRgba(img, function(im: Image): (Image?, Err.Err?) + 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, nil + end) +end + +function ImageOps.flip(img: Image, axis: string): (Image?, Err.Err?) + local ok, e = check(img) + if not ok then + return nil, e + end + if axis ~= "h" and axis ~= "v" then + return arg("flip: axis must be \"h\" or \"v\"") + end + 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, nil + end) +end + +function ImageOps.rotate90(img: Image, turns: number): (Image?, Err.Err?) + local ok, e = check(img) + if not ok then + return nil, e + end + if not isInt(turns) then + return arg("rotate90: integer turns") + end + local t = turns % 4 + if t == 0 then + return ImageOps.copy(img) + end + return viaRgba(img, function(im: Image): (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, nil + end) +end + +type ResizeFilter = "nearest" | "bilinear" | "lanczos" + +function ImageOps.resize(img: Image, w: number, h: number, filter: string?, opts: any?): (Image?, Err.Err?) + local ok, e = check(img) + if not ok then + return nil, e + end + if not isInt(w) or not isInt(h) or w < 1 or h < 1 then + return arg("resize: bad target size") + end + local f = filter or "bilinear" + if f ~= "nearest" and f ~= "bilinear" and f ~= "lanczos" then + return arg("resize: filter must be nearest, bilinear or lanczos") + end + local lok, le = limit(w, h, opts) + if not lok then + return nil, le + end + return viaRgba(img, function(im: Image): (Image?, Err.Err?) + local fmt = im.format + local bpp = Types.BPP[fmt] :: number + 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, nil + end + local kind, ch = K.KIND[fmt], K.CHANNELS[fmt] + local src, sw, sh = im.pixels, im.width, im.height + local alpha = ALPHA_CH[fmt] + if alpha then + src = buffer.create(buffer.len(im.pixels)) + buffer.copy(src, 0, im.pixels) + K.premultiply(src, sw * sh, alpha, kind, false) + end + if w ~= sw then + local tmp = buffer.create(w * sh * bpp) + K.resamplePass(src, sw, sh, ch, kind, tmp, w, K.coeffs(sw, w, f), true) + src, sw = tmp, w + end + if h ~= sh then + 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, nil + else + out.pixels = src + end + if alpha then + K.premultiply(out.pixels, w * h, alpha, kind, true) + end + return out, nil + end) +end + +function ImageOps.rotate(img: Image, degrees: number, opts: { expand: boolean?, maxPixels: number? }?): (Image?, Err.Err?) + local ok, e = check(img) + if not ok then + return nil, e + end + if type(degrees) ~= "number" or degrees ~= degrees or degrees == math.huge or degrees == -math.huge then + return arg("rotate: degrees must be a finite number") + end + local expand = not (opts and opts.expand == false) + if degrees % 90 == 0 and (expand or degrees % 180 == 0 or img.width == img.height) then + return ImageOps.rotate90(img, (degrees // 90) % 4) + end + local w, h = img.width, img.height + local ang = -math.rad(degrees) + local function r15(v: number): number + return math.floor(v * 1e15 + 0.5) / 1e15 + end + local m = { r15(math.cos(ang)), r15(math.sin(ang)), 0, r15(-math.sin(ang)), r15(math.cos(ang)), 0 } + local function tr(x: number, y: number): (number, number) + return m[1] * x + m[2] * y + m[3], m[4] * x + m[5] * y + m[6] + end + local cx, cy = w / 2, h / 2 + m[3], m[6] = tr(-cx, -cy) + m[3] += cx + m[6] += cy + local nw, nh = w, h + if expand then + local xs, ys = {}, {} + for _, p in { { 0, 0 }, { w, 0 }, { w, h }, { 0, h } } do + local x, y = tr(p[1], p[2]) + table.insert(xs, x) + table.insert(ys, y) + end + nw = math.ceil(math.max(xs[1], xs[2], xs[3], xs[4])) - math.floor(math.min(xs[1], xs[2], xs[3], xs[4])) + nh = math.ceil(math.max(ys[1], ys[2], ys[3], ys[4])) - math.floor(math.min(ys[1], ys[2], ys[3], ys[4])) + m[3], m[6] = tr(-(nw - w) / 2, -(nh - h) / 2) + end + local lok, le = limit(nw, nh, opts) + if not lok then + return nil, le + end + return viaRgba(img, function(im: Image): (Image?, Err.Err?) + local out = like(im, nw, nh) + local kind = K.KIND[im.format] + local alpha = ALPHA_CH[im.format] + local src = im.pixels + if alpha then + src = buffer.create(buffer.len(im.pixels)) + buffer.copy(src, 0, im.pixels) + K.premultiply(src, w * h, alpha, kind, false) + end + K.affine(src, w, h, K.CHANNELS[im.format], kind, out.pixels, nw, nh, m) + if alpha then + K.premultiply(out.pixels, nw * nh, alpha, kind, true) + end + return out, nil + end) +end + +local RGBA: { [string]: boolean } = { rgba8 = true, rgba16 = true, rgbaf32 = true } + +type BlitOptions = { blend: ("over" | "source")?, opacity: number? } + +function ImageOps.blit(dst: Image, src: Image, x: number, y: number, opts: BlitOptions?): (Image?, Err.Err?) + local ok, e = check(dst) + if not ok then + return nil, e + end + local ok2, e2 = check(src) + if not ok2 then + return nil, e2 + end + if not isInt(x) or not isInt(y) then + return arg("blit: integer x, y") + end + local blend = (opts and opts.blend) or "over" + if blend ~= "over" and blend ~= "source" then + return arg("blit: blend must be \"over\" or \"source\"") + end + local opacity = (opts and opts.opacity) or 1 + if type(opacity) ~= "number" or not (opacity >= 0 and opacity <= 1) then + return arg("blit: opacity must be 0..1") + end + local sx, sy = math.max(0, -x), math.max(0, -y) + local dx, dy = math.max(0, x), math.max(0, y) + 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, 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 + local region = ImageOps.crop(dst, dx, dy, w, h) :: Image + local work = if region.format == "rgba8" then region else ImageOps.convert(region, "rgba8") :: Image + ImageOps.blit(work, src, x - dx, y - dy, opts) + if dst.format == "yuv420p" then + local full = ImageOps.convert(dst, "rgba8") :: Image + ImageOps.blit(full, work, dx, dy, { blend = "source" }) + local back = ImageOps.convert(full, "yuv420p") :: Image + buffer.copy(dst.pixels, 0, back.pixels, 0, buffer.len(back.pixels)) + else + 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, nil + end + local s = src + if src.format ~= dst.format then + s = ImageOps.convert(src, dst.format) :: Image + end + if blend == "source" then + K.copyRect(dst.pixels, dst.width, s.pixels, s.width, sx, sy, dx, dy, w, h, Types.BPP[dst.format] :: number) + elseif dst.format == "rgba8" then + K.overRgba8(dst.pixels, dst.width, s.pixels, s.width, sx, sy, dx, dy, w, h, math.floor(opacity * 255 + 0.5)) + 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, nil +end + +function ImageOps.composite(dst: Image, src: Image, x: number?, y: number?, opts: BlitOptions?): (Image?, Err.Err?) + local out, e = ImageOps.copy(dst) + if not out then + return nil, e + end + out.frames = nil + return ImageOps.blit(out, src, x or 0, y or 0, opts) +end + +local function premul(img: Image, un: boolean): (Image?, Err.Err?) + local out, e = ImageOps.copy(img) + if not out then + return nil, e + end + out.frames = nil + local ch = ALPHA_CH[img.format] + if ch then + K.premultiply(out.pixels, img.width * img.height, ch, K.KIND[img.format], un) + end + return out, nil +end + +function ImageOps.premultiply(img: Image): (Image?, Err.Err?) + return premul(img, false) +end +function ImageOps.unpremultiply(img: Image): (Image?, Err.Err?) + return premul(img, true) +end + +local MAXV: { [string]: number } = { rgba8 = 255, rgba16 = 65535, rgbaf32 = 1, rgb8 = 255, gray8 = 255, gray16 = 65535, graya8 = 255, alpha8 = 255, yuv420p = 255 } + +function ImageOps.getPixel(img: Image, x: number, y: number): (any, any, number?, number?) + local ok, e = check(img) + if not ok then + return nil, e + end + if not isInt(x) or not isInt(y) or x < 0 or y < 0 or x >= img.width or y >= img.height then + return arg("getPixel: coordinates out of range") + end + local b, f, i = img.pixels, img.format, y * img.width + x + local ru8, ru16, rf = buffer.readu8, buffer.readu16, buffer.readf32 + if f == "rgba8" then + return ru8(b, i * 4), ru8(b, i * 4 + 1), ru8(b, i * 4 + 2), ru8(b, i * 4 + 3) + elseif f == "rgba16" then + return ru16(b, i * 8), ru16(b, i * 8 + 2), ru16(b, i * 8 + 4), ru16(b, i * 8 + 6) + elseif f == "rgbaf32" then + return rf(b, i * 16), rf(b, i * 16 + 4), rf(b, i * 16 + 8), rf(b, i * 16 + 12) + elseif f == "rgb8" then + return ru8(b, i * 3), ru8(b, i * 3 + 1), ru8(b, i * 3 + 2), 255 + elseif f == "gray8" then + local v = ru8(b, i) + return v, v, v, 255 + elseif f == "gray16" then + local v = ru16(b, i * 2) + return v, v, v, 65535 + elseif f == "graya8" then + local v = ru8(b, i * 2) + return v, v, v, ru8(b, i * 2 + 1) + elseif f == "alpha8" then + return 255, 255, 255, ru8(b, i) + end + local one = ImageOps.crop(img, x - x % 2, y - y % 2, 2, 2) :: Image + local rgba = ImageOps.convert(one, "rgba8") :: Image + local j = ((y % 2) * rgba.width + (x % 2)) * 4 + if j + 4 > buffer.len(rgba.pixels) then + j = 0 + end + return ru8(rgba.pixels, j), ru8(rgba.pixels, j + 1), ru8(rgba.pixels, j + 2), 255 +end + +function ImageOps.setPixel(img: Image, x: number, y: number, r: number, g: number, b: number, a: number?): (boolean?, Err.Err?) + local ok, e = check(img) + if not ok then + return nil, e + end + if not isInt(x) or not isInt(y) or x < 0 or y < 0 or x >= img.width or y >= img.height then + return arg("setPixel: coordinates out of range") + end + if type(r) ~= "number" or type(g) ~= "number" or type(b) ~= "number" or (a ~= nil and type(a) ~= "number") then + return arg("setPixel: numeric channels") + end + local f = img.format + if f == "yuv420p" then + return arg("setPixel: not supported on yuv420p (convert to rgba8 first)") + end + local max = MAXV[f] + local al = if a == nil then max else a + local function q(v: number): number + if max == 1 then + return v + end + if v ~= v then + return 0 + end + return math.clamp(math.floor(v + 0.5), 0, max) + end + local px, i = img.pixels, y * img.width + x + local wu8, wu16, wf = buffer.writeu8, buffer.writeu16, buffer.writef32 + local function grey(): number + if max == 1 then + return (r * 19595 + g * 38470 + b * 7471) / 65536 + end + return (q(r) * 19595 + q(g) * 38470 + q(b) * 7471 + 32768) // 65536 + end + if f == "rgba8" then + wu8(px, i * 4, q(r)) + wu8(px, i * 4 + 1, q(g)) + wu8(px, i * 4 + 2, q(b)) + wu8(px, i * 4 + 3, q(al)) + elseif f == "rgba16" then + wu16(px, i * 8, q(r)) + wu16(px, i * 8 + 2, q(g)) + wu16(px, i * 8 + 4, q(b)) + wu16(px, i * 8 + 6, q(al)) + elseif f == "rgbaf32" then + wf(px, i * 16, r) + wf(px, i * 16 + 4, g) + wf(px, i * 16 + 8, b) + wf(px, i * 16 + 12, al) + elseif f == "rgb8" then + wu8(px, i * 3, q(r)) + wu8(px, i * 3 + 1, q(g)) + wu8(px, i * 3 + 2, q(b)) + elseif f == "gray8" then + wu8(px, i, grey()) + elseif f == "gray16" then + wu16(px, i * 2, grey()) + elseif f == "graya8" then + wu8(px, i * 2, grey()) + wu8(px, i * 2 + 1, q(al)) + else + wu8(px, i, q(al)) + end + return true, nil +end + +function ImageOps.fill(img: Image, r: number, g: number, b: number, a: number?): (Image?, Err.Err?) + local ok, e = check(img) + if not ok then + return nil, e + end + if img.format == "yuv420p" then + return arg("fill: not supported on yuv420p") + end + local sok, se = ImageOps.setPixel(img, 0, 0, r, g, b, a) + if not sok then + return nil, se + end + local bpp = Types.BPP[img.format] :: number + local n = img.width * img.height * bpp + local filled = bpp + while filled < n do + local c = math.min(filled, n - filled) + buffer.copy(img.pixels, filled, img.pixels, 0, c) + filled += c + end + return img, nil +end + +function ImageOps.frameCount(img: Image): number + if type(img) == "table" and type(img.frames) == "table" and #img.frames > 0 then + return #img.frames + end + return 1 +end + +function ImageOps.durations(img: Image): { number } + local out = {} + if type(img) == "table" and type(img.frames) == "table" and #img.frames > 0 then + for i, f in img.frames do + out[i] = if type(f.delay) == "number" then f.delay else 0 + end + return out + end + return { 0 } +end + +-- coalesce: dispose "none" keeps the canvas, "background" clears the frame's rectangle, "previous" restores it +function ImageOps.coalesce(img: Image): ({ Image }?, Err.Err?) + local ok, e = check(img) + if not ok then + return nil, e + end + local frames = img.frames + if type(frames) ~= "table" or #frames == 0 then + 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) + local bpp = Types.BPP[fmt] :: number + local out = {} + for i, f in frames do + if type(f) ~= "table" then + return arg("coalesce: frame " .. i .. " is not a Frame") + end + local fi = f.image + local fok, fe = check(fi) + if not fok then + return nil, Err.new(Err.ARG, "coalesce: frame " .. i .. ": " .. (fe :: Err.Err).message) + end + local fx, fy = if isInt(f.x) then f.x else 0, if isInt(f.y) then f.y else 0 + local saved: buffer? = nil + if f.dispose == "previous" then + local sb = buffer.create(buffer.len(canvas.pixels)) + buffer.copy(sb, 0, canvas.pixels) + saved = sb + end + local bok, be = ImageOps.blit(canvas, fi, fx, fy, { blend = if f.blend == "source" then "source" else "over" }) + if not bok then + return nil, be + end + local snap = Types.Image.new(img.width, img.height, fmt :: any) + buffer.copy(snap.pixels, 0, canvas.pixels) + for k, v in img.meta do + snap.meta[k] = v + end + snap.meta.delay = f.delay + out[i] = snap + if f.dispose == "background" then + local x0, y0 = math.max(0, fx), math.max(0, fy) + local x1, y1 = math.min(img.width, fx + fi.width), math.min(img.height, fy + fi.height) + for y = y0, y1 - 1 do + if x1 > x0 then + buffer.fill(canvas.pixels, (y * img.width + x0) * bpp, 0, (x1 - x0) * bpp) + end + end + elseif saved then + canvas.pixels = saved + end + end + return out, nil +end + +function ImageOps.fromFrames(images: { Image }, delays: (number | { number })?): (Image?, Err.Err?) + if type(images) ~= "table" or #images == 0 then + return arg("fromFrames: a non-empty list of Images") + end + local first = images[1] + local ok, e = check(first) + if not ok then + return nil, e + end + local frames = {} + for i, im in images do + local iok, ie = check(im) + if not iok then + return nil, ie + end + if im.width ~= first.width or im.height ~= first.height or im.format ~= first.format then + return arg("fromFrames: frame " .. i .. " differs in size or format from frame 1") + end + local d = 0.1 + if type(delays) == "number" then + d = delays + elseif type(delays) == "table" and type(delays[i]) == "number" then + d = delays[i] + end + frames[i] = { image = im, delay = d, x = 0, y = 0, dispose = "none", blend = "source" } + end + local out = like(first, first.width, first.height) + buffer.copy(out.pixels, 0, first.pixels, 0, buffer.len(out.pixels)) + out.frames = frames :: any + out.loops = 0 + return out, nil +end + +return ImageOps +end +__FILES["ops/ImageOps/Kernels"] = @native function() + + + +-- ops/ImageOps/Kernels: the hot loops behind ops/ImageOps; callers validate, so indexes are in range by construction. +-- Sample kinds: 1 = u8, 2 = u16, 4 = f32 (little endian). Resampling follows Pillow's Resample.c (separable, 22-bit +-- fixed point for 8-bit) and Geometry.c (affine through pixel centres); compositing is Pillow's AlphaComposite.c. +local readu8, writeu8, readu16, writeu16, readf32, writef32 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16, buffer.readf32, buffer.writef32 +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 } :: { [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 } + +@native local function rd(b: buffer, o: number, kind: number): number + if kind == 1 then + return readu8(b, o) + elseif kind == 2 then + return readu16(b, o) + end + return readf32(b, o) +end + +@native local function wr(b: buffer, o: number, kind: number, v: number) + if kind == 1 then + writeu8(b, o, clamp(floor(v + 0.5), 0, 255)) + elseif kind == 2 then + writeu16(b, o, clamp(floor(v + 0.5), 0, 65535)) + else + writef32(b, o, v) + end +end + +-- depth: 8 -> 0..255, 16 -> 0..65535, 0 -> float 0..1 +local DEPTH = { 8, 16, 0, 8, 8, 16, 8, 8 } + +@native local function depthConv(v: number, from: number, to: number): number + if from == to then + return v + end + if from == 8 then + if to == 16 then + return v * 257 + end + return v / 255 + elseif from == 16 then + if to == 8 then + return (v * 255 + 32767) // 65535 + end + return v / 65535 + end + if v ~= v then + v = 0 + end + if to == 8 then + return clamp(floor(v * 255 + 0.5), 0, 255) + end + return clamp(floor(v * 65535 + 0.5), 0, 65535) +end + +-- Pillow's L24 luma (19595 R + 38470 G + 7471 B + 0x8000) >> 16, in the source depth +@native local function luma(r: number, g: number, b: number, depth: number): number + if depth == 0 then + return (r * 19595 + g * 38470 + b * 7471) / 65536 + end + return (r * 19595 + g * 38470 + b * 7471 + 32768) // 65536 +end + +@native function K.convert(src: buffer, sf: number, dst: buffer, df: number, n: number) + 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: 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) :: 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) :: 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) :: 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 + elseif sf == 5 then + local v = readu8(src, i) + r, g, b, a = v, v, v, 255 + elseif sf == 6 then + local v = readu16(src, i * 2) + 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) :: number + else + r, g, b, a = 255, 255, 255, readu8(src, i) + end + if toGray then + local isGray = sf == 5 or sf == 6 or sf == 7 + local l = if isGray then r else luma(r, g, b, sd) + l = depthConv(l, sd, dd) + if df == 5 then + writeu8(dst, i, l) + elseif df == 6 then + writeu16(dst, i * 2, l) + else + writeu8(dst, i * 2, l) + writeu8(dst, i * 2 + 1, depthConv(a, sd, dd)) + end + 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) :: number + if df == 1 then + local o = i * 4 + writeu8(dst, o, r) + writeu8(dst, o + 1, g) + writeu8(dst, o + 2, b) + writeu8(dst, o + 3, depthConv(a, sd, dd)) + elseif df == 2 then + local o = i * 8 + writeu16(dst, o, r) + writeu16(dst, o + 2, g) + writeu16(dst, o + 4, b) + writeu16(dst, o + 6, depthConv(a, sd, dd)) + elseif df == 3 then + local o = i * 16 + writef32(dst, o, r) + writef32(dst, o + 4, g) + writef32(dst, o + 8, b) + writef32(dst, o + 12, if a == smax and sd ~= 0 then 1 else depthConv(a, sd, dd)) + else -- rgb8 + local o = i * 3 + writeu8(dst, o, r) + writeu8(dst, o + 1, g) + writeu8(dst, o + 2, b) + end + end + end +end + +-- JPEG-style BT.601 full range +@native function K.rgbaToYuv(src: buffer, w: number, h: number, dst: buffer) + local cw, ch = (w + 1) // 2, (h + 1) // 2 + local uo, vo = w * h, w * h + cw * ch + for i = 0, w * h - 1 do + local o = i * 4 + local r, g, b = readu8(src, o), readu8(src, o + 1), readu8(src, o + 2) + writeu8(dst, i, clamp(floor(0.299 * r + 0.587 * g + 0.114 * b + 0.5), 0, 255)) + end + for cy = 0, ch - 1 do + for cx = 0, cw - 1 do + local sr, sg, sb, n = 0, 0, 0, 0 + for dy = 0, 1 do + local y = cy * 2 + dy + if y < h then + for dx = 0, 1 do + local x = cx * 2 + dx + if x < w then + local o = (y * w + x) * 4 + sr += readu8(src, o) + sg += readu8(src, o + 1) + sb += readu8(src, o + 2) + n += 1 + end + end + end + end + sr, sg, sb = sr / n, sg / n, sb / n + local i = cy * cw + cx + writeu8(dst, uo + i, clamp(floor(128 - 0.168736 * sr - 0.331264 * sg + 0.5 * sb + 0.5), 0, 255)) + writeu8(dst, vo + i, clamp(floor(128 + 0.5 * sr - 0.418688 * sg - 0.081312 * sb + 0.5), 0, 255)) + end + end +end + +@native function K.yuvToRgba(src: buffer, w: number, h: number, dst: buffer) + local cw, ch = (w + 1) // 2, (h + 1) // 2 + local uo, vo = w * h, w * h + cw * ch + for y = 0, h - 1 do + local crow = (y // 2) * cw + for x = 0, w - 1 do + local yy = readu8(src, y * w + x) + local ci = crow + x // 2 + local u, v = readu8(src, uo + ci) - 128, readu8(src, vo + ci) - 128 + local o = (y * w + x) * 4 + writeu8(dst, o, clamp(floor(yy + 1.402 * v + 0.5), 0, 255)) + writeu8(dst, o + 1, clamp(floor(yy - 0.344136 * u - 0.714136 * v + 0.5), 0, 255)) + writeu8(dst, o + 2, clamp(floor(yy + 1.772 * u + 0.5), 0, 255)) + writeu8(dst, o + 3, 255) + end + end + local _ = ch +end + +@native function K.flip(src: buffer, dst: buffer, w: number, h: number, bpp: number, horizontal: boolean) + local stride = w * bpp + if not horizontal then + for y = 0, h - 1 do + buffer.copy(dst, (h - 1 - y) * stride, src, y * stride, stride) + end + return + end + for y = 0, h - 1 do + local row = y * stride + for x = 0, w - 1 do + buffer.copy(dst, row + (w - 1 - x) * bpp, src, row + x * bpp, bpp) + end + end +end + +-- counter-clockwise quarter turns 1..3 +@native function K.rotate90(src: buffer, dst: buffer, w: number, h: number, bpp: number, turns: number) + for y = 0, h - 1 do + for x = 0, w - 1 do + local ox, oy, ow + if turns == 1 then + ox, oy, ow = y, w - 1 - x, h + elseif turns == 2 then + ox, oy, ow = w - 1 - x, h - 1 - y, w + else + ox, oy, ow = h - 1 - y, x, h + end + local so, d = (y * w + x) * bpp, (oy * ow + ox) * bpp + if bpp == 4 then + buffer.writeu32(dst, d, buffer.readu32(src, so)) + else + buffer.copy(dst, d, src, so, bpp) + end + end + end +end + +@native local function bilinearF(x: number): number + if x < 0 then + x = -x + end + if x < 1 then + return 1 - x + end + return 0 +end + +@native local function sinc(x: number): number + if x == 0 then + return 1 + end + x *= math.pi + return math.sin(x) / x +end + +@native local function lanczosF(x: number): number + if x > -3 and x < 3 then + return sinc(x) * sinc(x / 3) + end + return 0 +end + +@native local function trunc(x: number): number + return if x < 0 then math.ceil(x) else floor(x) +end + +-- Pillow precompute_coeffs: per output index its first input index, tap count and weights (normalised) +type Coeffs = { start: { number }, count: { number }, weights: { { number } } } + +@native function K.coeffs(inSize: number, outSize: number, filter: string): Coeffs + local support0 = if filter == "lanczos" then 3 else 1 + local f = if filter == "lanczos" then lanczosF else bilinearF + local scale = inSize / outSize + 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) :: { { number } } + for xx = 0, outSize - 1 do + local center = (xx + 0.5) * scale + local xmin = math.max(0, trunc(center - support + 0.5)) + local xmax = math.min(inSize, trunc(center + support + 0.5)) - xmin + local w = table.create(math.max(xmax, 0), 0) + local ww = 0 + for x = 0, xmax - 1 do + local v = f((x + xmin - center + 0.5) * ss) + w[x + 1] = v + ww += v + end + if ww ~= 0 then + for x = 1, xmax do + w[x] /= ww + end + end + start[xx + 1], count[xx + 1], weights[xx + 1] = xmin, math.max(xmax, 0), w + end + return { start = start, count = count, weights = weights } +end + +@native function K.resamplePass(src: buffer, w: number, h: number, ch: number, kind: number, dst: buffer, outN: number, c: Coeffs, horizontal: boolean) + local start, count, weights = c.start, c.count, c.weights + local size = kind + local fixed = kind == 1 + -- 8-bit: Pillow's 22-bit fixed-point coefficients + local iw: { { number } } = weights + if fixed then + iw = table.create(outN) :: { { number } } + for i = 1, outN do + local src0 = weights[i] + local t = table.create(#src0, 0) + for k = 1, #src0 do + local v = src0[k] * 4194304 + t[k] = if v < 0 then math.ceil(v - 0.5) else floor(v + 0.5) + end + iw[i] = t + end + end + if horizontal then + for y = 0, h - 1 do + local row = y * w + for xx = 0, outN - 1 do + local s0, n, wt = start[xx + 1], count[xx + 1], iw[xx + 1] + local o = ((y * outN) + xx) * ch * size + for cc = 0, ch - 1 do + if fixed then + local acc = 2097152 + for k = 0, n - 1 do + acc += readu8(src, (row + s0 + k) * ch + cc) * wt[k + 1] + end + writeu8(dst, o + cc, clamp(acc // 4194304, 0, 255)) + else + local acc = 0 + for k = 0, n - 1 do + acc += rd(src, ((row + s0 + k) * ch + cc) * size, kind) * wt[k + 1] + end + wr(dst, o + cc * size, kind, acc) + end + end + end + end + else + for yy = 0, outN - 1 do + local s0, n, wt = start[yy + 1], count[yy + 1], iw[yy + 1] + for x = 0, w - 1 do + local o = (yy * w + x) * ch * size + for cc = 0, ch - 1 do + if fixed then + local acc = 2097152 + for k = 0, n - 1 do + acc += readu8(src, ((s0 + k) * w + x) * ch + cc) * wt[k + 1] + end + writeu8(dst, o + cc, clamp(acc // 4194304, 0, 255)) + else + local acc = 0 + for k = 0, n - 1 do + acc += rd(src, (((s0 + k) * w + x) * ch + cc) * size, kind) * wt[k + 1] + end + wr(dst, o + cc * size, kind, acc) + end + end + end + end + end + local _ = h +end + +-- nearest: dst pixel (x, y) = src pixel (floor((x + 0.5) * w / ow), ...) +@native function K.nearest(src: buffer, w: number, h: number, bpp: number, dst: buffer, ow: number, oh: number) + local sx, sy = w / ow, h / oh + for y = 0, oh - 1 do + local iy = math.min(floor((y + 0.5) * sy), h - 1) + for x = 0, ow - 1 do + local ix = math.min(floor((x + 0.5) * sx), w - 1) + buffer.copy(dst, (y * ow + x) * bpp, src, (iy * w + ix) * bpp, bpp) + end + end +end + +-- affine: dst pixel centres through m = { a, b, c, d, e, f } (xin = a x + b y + c), bilinear with clamped +-- neighbours; centres outside the source -> zeros (Pillow) +@native function K.affine(src: buffer, w: number, h: number, ch: number, kind: number, dst: buffer, ow: number, oh: number, m: { number }) + local a, b, c, d, e, f = m[1], m[2], m[3], m[4], m[5], m[6] + local size = kind + for y = 0, oh - 1 do + local py = y + 0.5 + for x = 0, ow - 1 do + local px = x + 0.5 + local xin = a * px + b * py + c - 0.5 + local yin = d * px + e * py + f - 0.5 + local o = (y * ow + x) * ch * size + local x0 = floor(xin) + local y0 = floor(yin) + if xin < -0.5 or xin >= w - 0.5 or yin < -0.5 or yin >= h - 0.5 then + continue -- dst starts zeroed + end + local dx, dy = xin - x0, yin - y0 + local xa, xb = clamp(x0, 0, w - 1), clamp(x0 + 1, 0, w - 1) + local ya, yb = clamp(y0, 0, h - 1), clamp(y0 + 1, 0, h - 1) + for cc = 0, ch - 1 do + local p00 = rd(src, ((ya * w + xa) * ch + cc) * size, kind) + local p01 = rd(src, ((ya * w + xb) * ch + cc) * size, kind) + local p10 = rd(src, ((yb * w + xa) * ch + cc) * size, kind) + local p11 = rd(src, ((yb * w + xb) * ch + cc) * size, kind) + local top = p00 + (p01 - p00) * dx + local bot = p10 + (p11 - p10) * dx + local v = top + (bot - top) * dy + if kind == 1 then + writeu8(dst, o + cc, clamp(floor(v), 0, 255)) -- Pillow truncates + else + wr(dst, o + cc * size, kind, v) + end + end + end + end +end + +-- Pillow's alpha_composite of src onto dst, in place +@native function K.overRgba8(dst: buffer, dw: number, src: buffer, sw: number, sx: number, sy: number, dx: number, dy: number, w: number, h: number, opacity: number) + for y = 0, h - 1 do + for x = 0, w - 1 do + local so = ((sy + y) * sw + sx + x) * 4 + local doff = ((dy + y) * dw + dx + x) * 4 + local sa = readu8(src, so + 3) + if opacity < 255 then + sa = (sa * opacity + 127) // 255 + end + if sa == 0 then + continue + end + local da = readu8(dst, doff + 3) + local blend = da * (255 - sa) + local outa255 = sa * 255 + blend + local coef1 = (sa * 255 * 255 * 128) // outa255 + local coef2 = 255 * 128 - coef1 + for cc = 0, 2 do + local t = readu8(src, so + cc) * coef1 + readu8(dst, doff + cc) * coef2 + 0x80 * 128 + t = ((t // 256) + t) // 256 + writeu8(dst, doff + cc, t // 128) + end + local t = outa255 + 0x80 + writeu8(dst, doff + 3, ((t // 256) + t) // 256) + end + end +end + +-- overFloat: straight-alpha "over" for rgba16 (kind 2) / rgbaf32 (kind 4); max = 65535 or 1 +@native function K.overFloat(dst: buffer, dw: number, src: buffer, sw: number, sx: number, sy: number, dx: number, dy: number, w: number, h: number, opacity: number, kind: number) + local max = if kind == 2 then 65535 else 1 + local px = 4 * kind + for y = 0, h - 1 do + for x = 0, w - 1 do + local so = ((sy + y) * sw + sx + x) * px + local doff = ((dy + y) * dw + dx + x) * px + local sa = rd(src, so + 3 * kind, kind) / max * opacity + if sa <= 0 then + continue + end + local da = rd(dst, doff + 3 * kind, kind) / max + local oa = sa + da * (1 - sa) + for cc = 0, 2 do + local s = rd(src, so + cc * kind, kind) + local d = rd(dst, doff + cc * kind, kind) + wr(dst, doff + cc * kind, kind, if oa > 0 then (s * sa + d * da * (1 - sa)) / oa else 0) + end + wr(dst, doff + 3 * kind, kind, oa * max) + end + end +end + +@native function K.copyRect(dst: buffer, dw: number, src: buffer, sw: number, sx: number, sy: number, dx: number, dy: number, w: number, h: number, bpp: number) + for y = 0, h - 1 do + buffer.copy(dst, ((dy + y) * dw + dx) * bpp, src, ((sy + y) * sw + sx) * bpp, w * bpp) + end +end + +@native function K.premultiply(b: buffer, n: number, ch: number, kind: number, un: boolean) + local max = if kind == 1 then 255 elseif kind == 2 then 65535 else 1 + local px = ch * kind + for i = 0, n - 1 do + local o = i * px + local a = rd(b, o + (ch - 1) * kind, kind) + for cc = 0, ch - 2 do + local v = rd(b, o + cc * kind, kind) + local r + if un then + if a <= 0 then + r = 0 + elseif kind == 4 then + r = v / a + elseif kind == 1 then + r = math.min(255, (v * 255) // a) -- Pillow's rgbA2rgba + else + r = math.min(max, (v * max + a // 2) // a) + end + else + if kind == 4 then + r = v * a + elseif kind == 1 then + local t = v * a + 128 -- Pillow's MULDIV255 + r = ((t // 256) + t) // 256 + else + r = (v * a + max // 2) // max + end + end + wr(b, o + cc * kind, kind, r) + end + end +end + +return K +end +end + + + + + + Mpeg2 + --!optimize 2 +--!nocheck +-- rosetta chunk Mpeg2 (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 6 modules (2 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["codecs/video/Dsp"] = @native function() + + + +-- codecs/video/Dsp: the 8x8 IDCT (bit-exact with ffmpeg -idct int) and half-pel motion compensation of MPEG codecs. +-- The IDCT is IJG's jrevdct.c (LL&M, CONST_BITS 13, PASS1_BITS 2) as ffmpeg ships it (libavcodec/jrevdct.c, IJG +-- licence: licenses/libjpeg-README.ijg), translated mechanically: its sparse-input special cases stay because their +-- merged constants round differently. Natural-order i32 coefficients, no int16 wrap, put / add clamping in pass 2. +local Dsp = {} + +local readu8 = buffer.readu8 +local writeu8 = buffer.writeu8 +local readu32 = buffer.readu32 +local writeu32 = buffer.writeu32 +local readi32 = buffer.readi32 +local writei32 = buffer.writei32 +local band = bit32.band +local bor = bit32.bor +local bxor = bit32.bxor +local rshift = bit32.rshift + +-- clamp to 0..255 by lookup: CLAMP[v + COFF] for v in [-COFF, COFF + 255]; the IDCT output of MPEG-range +-- coefficients is bounded by 64 * 2048 / 8 * sqrt(2)^2 < COFF, plus a prediction of up to 255 +local COFF = 40000 +local CLAMP = buffer.create(2 * COFF + 256) +for i = 0, 2 * COFF + 255 do + buffer.writeu8(CLAMP, i, math.clamp(i - COFF, 0, 255)) +end +Dsp.CLAMP = CLAMP +Dsp.COFF = COFF + +@native function Dsp.idct(blk: buffer, dst: buffer, off: number, stride: number, add: boolean) + local tmp0, tmp1, tmp2, tmp3 = 0, 0, 0, 0 + local tmp10, tmp11, tmp12, tmp13 = 0, 0, 0, 0 + local z1, z2, z3, z4, z5 = 0, 0, 0, 0, 0 + -- pass 1: rows, scaled up by 2^PASS1_BITS + for r = 0, 224, 32 do + local d0 = readi32(blk, r) + local d1 = readi32(blk, r + 4) + local d2 = readi32(blk, r + 8) + local d3 = readi32(blk, r + 12) + local d4 = readi32(blk, r + 16) + local d5 = readi32(blk, r + 20) + local d6 = readi32(blk, r + 24) + local d7 = readi32(blk, r + 28) + if d1 == 0 and d2 == 0 and d3 == 0 and d4 == 0 and d5 == 0 and d6 == 0 and d7 == 0 then + if d0 ~= 0 then + local v = d0 * 4 + writei32(blk, r, v) + writei32(blk, r + 4, v) + writei32(blk, r + 8, v) + writei32(blk, r + 12, v) + writei32(blk, r + 16, v) + writei32(blk, r + 20, v) + writei32(blk, r + 24, v) + writei32(blk, r + 28, v) + end + else + if d6 ~= 0 then + if d2 ~= 0 then + z1 = (d2 + d6) * 4433 + tmp2 = z1 + (-d6) * 15137 + tmp3 = z1 + (d2) * 6270 + tmp0 = (d0 + d4) * 8192 + tmp1 = (d0 - d4) * 8192 + tmp10 = tmp0 + tmp3 + tmp13 = tmp0 - tmp3 + tmp11 = tmp1 + tmp2 + tmp12 = tmp1 - tmp2 + else + tmp2 = (-d6) * 10703 + tmp3 = (d6) * 4433 + tmp0 = (d0 + d4) * 8192 + tmp1 = (d0 - d4) * 8192 + tmp10 = tmp0 + tmp3 + tmp13 = tmp0 - tmp3 + tmp11 = tmp1 + tmp2 + tmp12 = tmp1 - tmp2 + end + else + if d2 ~= 0 then + tmp2 = (d2) * 4433 + tmp3 = (d2) * 10703 + tmp0 = (d0 + d4) * 8192 + tmp1 = (d0 - d4) * 8192 + tmp10 = tmp0 + tmp3 + tmp13 = tmp0 - tmp3 + tmp11 = tmp1 + tmp2 + tmp12 = tmp1 - tmp2 + else + tmp13 = (d0 + d4) * 8192 + tmp10 = tmp13 + tmp12 = (d0 - d4) * 8192 + tmp11 = tmp12 + end + end + if d7 ~= 0 then + if d5 ~= 0 then + if d3 ~= 0 then + if d1 ~= 0 then + z1 = d7 + d1 + z2 = d5 + d3 + z3 = d7 + d3 + z4 = d5 + d1 + z5 = (z3 + z4) * 9633 + tmp0 = (d7) * 2446 + tmp1 = (d5) * 16819 + tmp2 = (d3) * 25172 + tmp3 = (d1) * 12299 + z1 = (-z1) * 7373 + z2 = (-z2) * 20995 + z3 = (-z3) * 16069 + z4 = (-z4) * 3196 + z3 += z5 + z4 += z5 + tmp0 += z1 + z3 + tmp1 += z2 + z4 + tmp2 += z2 + z3 + tmp3 += z1 + z4 + else + z2 = d5 + d3 + z3 = d7 + d3 + z5 = (z3 + d5) * 9633 + tmp0 = (d7) * 2446 + tmp1 = (d5) * 16819 + tmp2 = (d3) * 25172 + z1 = (-d7) * 7373 + z2 = (-z2) * 20995 + z3 = (-z3) * 16069 + z4 = (-d5) * 3196 + z3 += z5 + z4 += z5 + tmp0 += z1 + z3 + tmp1 += z2 + z4 + tmp2 += z2 + z3 + tmp3 = z1 + z4 + end + else + if d1 ~= 0 then + z1 = d7 + d1 + z4 = d5 + d1 + z5 = (d7 + z4) * 9633 + tmp0 = (d7) * 2446 + tmp1 = (d5) * 16819 + tmp3 = (d1) * 12299 + z1 = (-z1) * 7373 + z2 = (-d5) * 20995 + z3 = (-d7) * 16069 + z4 = (-z4) * 3196 + z3 += z5 + z4 += z5 + tmp0 += z1 + z3 + tmp1 += z2 + z4 + tmp2 = z2 + z3 + tmp3 += z1 + z4 + else + tmp0 = (-d7) * 4926 + z1 = (-d7) * 7373 + z3 = (-d7) * 16069 + tmp1 = (-d5) * 4176 + z2 = (-d5) * 20995 + z4 = (-d5) * 3196 + z5 = (d5 + d7) * 9633 + z3 += z5 + z4 += z5 + tmp0 += z3 + tmp1 += z4 + tmp2 = z2 + z3 + tmp3 = z1 + z4 + end + end + else + if d3 ~= 0 then + if d1 ~= 0 then + z1 = d7 + d1 + z3 = d7 + d3 + z5 = (z3 + d1) * 9633 + tmp0 = (d7) * 2446 + tmp2 = (d3) * 25172 + tmp3 = (d1) * 12299 + z1 = (-z1) * 7373 + z2 = (-d3) * 20995 + z3 = (-z3) * 16069 + z4 = (-d1) * 3196 + z3 += z5 + z4 += z5 + tmp0 += z1 + z3 + tmp1 = z2 + z4 + tmp2 += z2 + z3 + tmp3 += z1 + z4 + else + z3 = d7 + d3 + tmp0 = (-d7) * 4926 + z1 = (-d7) * 7373 + tmp2 = (d3) * 4176 + z2 = (-d3) * 20995 + z5 = (z3) * 9633 + z3 = (-z3) * 6436 + tmp0 += z3 + tmp1 = z2 + z5 + tmp2 += z3 + tmp3 = z1 + z5 + end + else + if d1 ~= 0 then + z1 = d7 + d1 + z5 = (z1) * 9633 + z1 = (z1) * 2260 + z3 = (-d7) * 16069 + tmp0 = (-d7) * 13623 + z4 = (-d1) * 3196 + tmp3 = (d1) * 9102 + tmp0 += z1 + tmp1 = z4 + z5 + tmp2 = z3 + z5 + tmp3 += z1 + else + tmp0 = (-d7) * 11363 + tmp1 = (d7) * 9633 + tmp2 = (-d7) * 6436 + tmp3 = (d7) * 2260 + end + end + end + else + if d5 ~= 0 then + if d3 ~= 0 then + if d1 ~= 0 then + z2 = d5 + d3 + z4 = d5 + d1 + z5 = (d3 + z4) * 9633 + tmp1 = (d5) * 16819 + tmp2 = (d3) * 25172 + tmp3 = (d1) * 12299 + z1 = (-d1) * 7373 + z2 = (-z2) * 20995 + z3 = (-d3) * 16069 + z4 = (-z4) * 3196 + z3 += z5 + z4 += z5 + tmp0 = z1 + z3 + tmp1 += z2 + z4 + tmp2 += z2 + z3 + tmp3 += z1 + z4 + else + z2 = d5 + d3 + z5 = (z2) * 9633 + tmp1 = (d5) * 13623 + z4 = (-d5) * 3196 + z2 = (-z2) * 11363 + tmp2 = (d3) * 9102 + z3 = (-d3) * 16069 + tmp0 = z3 + z5 + tmp1 += z2 + tmp2 += z2 + tmp3 = z4 + z5 + end + else + if d1 ~= 0 then + z4 = d5 + d1 + z5 = (z4) * 9633 + z1 = (-d1) * 7373 + tmp3 = (d1) * 4926 + tmp1 = (-d5) * 4176 + z2 = (-d5) * 20995 + z4 = (z4) * 6436 + tmp0 = z1 + z5 + tmp1 += z4 + tmp2 = z2 + z5 + tmp3 += z4 + else + tmp0 = (d5) * 9633 + tmp1 = (d5) * 2260 + tmp2 = (-d5) * 11363 + tmp3 = (d5) * 6436 + end + end + else + if d3 ~= 0 then + if d1 ~= 0 then + z5 = d1 + d3 + tmp3 = (d1) * 1730 + tmp2 = (-d3) * 11893 + z1 = (d1) * 8697 + z2 = (-d3) * 17799 + z4 = (z5) * 6436 + z5 = (z5) * 9633 + tmp0 = z1 - z4 + tmp1 = z2 + z4 + tmp2 += z5 + tmp3 += z5 + else + tmp0 = (-d3) * 6436 + tmp1 = (-d3) * 11363 + tmp2 = (-d3) * 2260 + tmp3 = (d3) * 9633 + end + else + if d1 ~= 0 then + tmp0 = (d1) * 2260 + tmp1 = (d1) * 6436 + tmp2 = (d1) * 9633 + tmp3 = (d1) * 11363 + else + tmp3 = 0 + tmp0 = tmp3 + tmp1 = tmp3 + tmp2 = tmp3 + end + end + end + end + writei32(blk, r, (tmp10 + tmp3 + 1024) // 2048) + writei32(blk, r + 28, (tmp10 - tmp3 + 1024) // 2048) + writei32(blk, r + 4, (tmp11 + tmp2 + 1024) // 2048) + writei32(blk, r + 24, (tmp11 - tmp2 + 1024) // 2048) + writei32(blk, r + 8, (tmp12 + tmp1 + 1024) // 2048) + writei32(blk, r + 20, (tmp12 - tmp1 + 1024) // 2048) + writei32(blk, r + 12, (tmp13 + tmp0 + 1024) // 2048) + writei32(blk, r + 16, (tmp13 - tmp0 + 1024) // 2048) + end + end + -- pass 2: columns, descaled by 2^(CONST_BITS + PASS1_BITS + 3) + for c = 0, 28, 4 do + local d0 = readi32(blk, c) + local d1 = readi32(blk, c + 32) + local d2 = readi32(blk, c + 64) + local d3 = readi32(blk, c + 96) + local d4 = readi32(blk, c + 128) + local d5 = readi32(blk, c + 160) + local d6 = readi32(blk, c + 192) + local d7 = readi32(blk, c + 224) + if d6 ~= 0 then + if d2 ~= 0 then + z1 = (d2 + d6) * 4433 + tmp2 = z1 + (-d6) * 15137 + tmp3 = z1 + (d2) * 6270 + tmp0 = (d0 + d4) * 8192 + tmp1 = (d0 - d4) * 8192 + tmp10 = tmp0 + tmp3 + tmp13 = tmp0 - tmp3 + tmp11 = tmp1 + tmp2 + tmp12 = tmp1 - tmp2 + else + tmp2 = (-d6) * 10703 + tmp3 = (d6) * 4433 + tmp0 = (d0 + d4) * 8192 + tmp1 = (d0 - d4) * 8192 + tmp10 = tmp0 + tmp3 + tmp13 = tmp0 - tmp3 + tmp11 = tmp1 + tmp2 + tmp12 = tmp1 - tmp2 + end + else + if d2 ~= 0 then + tmp2 = (d2) * 4433 + tmp3 = (d2) * 10703 + tmp0 = (d0 + d4) * 8192 + tmp1 = (d0 - d4) * 8192 + tmp10 = tmp0 + tmp3 + tmp13 = tmp0 - tmp3 + tmp11 = tmp1 + tmp2 + tmp12 = tmp1 - tmp2 + else + tmp13 = (d0 + d4) * 8192 + tmp10 = tmp13 + tmp12 = (d0 - d4) * 8192 + tmp11 = tmp12 + end + end + if d7 ~= 0 then + if d5 ~= 0 then + if d3 ~= 0 then + if d1 ~= 0 then + z1 = d7 + d1 + z2 = d5 + d3 + z3 = d7 + d3 + z4 = d5 + d1 + z5 = (z3 + z4) * 9633 + tmp0 = (d7) * 2446 + tmp1 = (d5) * 16819 + tmp2 = (d3) * 25172 + tmp3 = (d1) * 12299 + z1 = (-z1) * 7373 + z2 = (-z2) * 20995 + z3 = (-z3) * 16069 + z4 = (-z4) * 3196 + z3 += z5 + z4 += z5 + tmp0 += z1 + z3 + tmp1 += z2 + z4 + tmp2 += z2 + z3 + tmp3 += z1 + z4 + else + z2 = d5 + d3 + z3 = d7 + d3 + z5 = (z3 + d5) * 9633 + tmp0 = (d7) * 2446 + tmp1 = (d5) * 16819 + tmp2 = (d3) * 25172 + z1 = (-d7) * 7373 + z2 = (-z2) * 20995 + z3 = (-z3) * 16069 + z4 = (-d5) * 3196 + z3 += z5 + z4 += z5 + tmp0 += z1 + z3 + tmp1 += z2 + z4 + tmp2 += z2 + z3 + tmp3 = z1 + z4 + end + else + if d1 ~= 0 then + z1 = d7 + d1 + z3 = d7 + z4 = d5 + d1 + z5 = (z3 + z4) * 9633 + tmp0 = (d7) * 2446 + tmp1 = (d5) * 16819 + tmp3 = (d1) * 12299 + z1 = (-z1) * 7373 + z2 = (-d5) * 20995 + z3 = (-d7) * 16069 + z4 = (-z4) * 3196 + z3 += z5 + z4 += z5 + tmp0 += z1 + z3 + tmp1 += z2 + z4 + tmp2 = z2 + z3 + tmp3 += z1 + z4 + else + tmp0 = (-d7) * 4926 + z1 = (-d7) * 7373 + z3 = (-d7) * 16069 + tmp1 = (-d5) * 4176 + z2 = (-d5) * 20995 + z4 = (-d5) * 3196 + z5 = (d5 + d7) * 9633 + z3 += z5 + z4 += z5 + tmp0 += z3 + tmp1 += z4 + tmp2 = z2 + z3 + tmp3 = z1 + z4 + end + end + else + if d3 ~= 0 then + if d1 ~= 0 then + z1 = d7 + d1 + z3 = d7 + d3 + z5 = (z3 + d1) * 9633 + tmp0 = (d7) * 2446 + tmp2 = (d3) * 25172 + tmp3 = (d1) * 12299 + z1 = (-z1) * 7373 + z2 = (-d3) * 20995 + z3 = (-z3) * 16069 + z4 = (-d1) * 3196 + z3 += z5 + z4 += z5 + tmp0 += z1 + z3 + tmp1 = z2 + z4 + tmp2 += z2 + z3 + tmp3 += z1 + z4 + else + z3 = d7 + d3 + tmp0 = (-d7) * 4926 + z1 = (-d7) * 7373 + tmp2 = (d3) * 4176 + z2 = (-d3) * 20995 + z5 = (z3) * 9633 + z3 = (-z3) * 6436 + tmp0 += z3 + tmp1 = z2 + z5 + tmp2 += z3 + tmp3 = z1 + z5 + end + else + if d1 ~= 0 then + z1 = d7 + d1 + z5 = (z1) * 9633 + z1 = (z1) * 2260 + z3 = (-d7) * 16069 + tmp0 = (-d7) * 13623 + z4 = (-d1) * 3196 + tmp3 = (d1) * 9102 + tmp0 += z1 + tmp1 = z4 + z5 + tmp2 = z3 + z5 + tmp3 += z1 + else + tmp0 = (-d7) * 11363 + tmp1 = (d7) * 9633 + tmp2 = (-d7) * 6436 + tmp3 = (d7) * 2260 + end + end + end + else + if d5 ~= 0 then + if d3 ~= 0 then + if d1 ~= 0 then + z2 = d5 + d3 + z4 = d5 + d1 + z5 = (d3 + z4) * 9633 + tmp1 = (d5) * 16819 + tmp2 = (d3) * 25172 + tmp3 = (d1) * 12299 + z1 = (-d1) * 7373 + z2 = (-z2) * 20995 + z3 = (-d3) * 16069 + z4 = (-z4) * 3196 + z3 += z5 + z4 += z5 + tmp0 = z1 + z3 + tmp1 += z2 + z4 + tmp2 += z2 + z3 + tmp3 += z1 + z4 + else + z2 = d5 + d3 + z5 = (z2) * 9633 + tmp1 = (d5) * 13623 + z4 = (-d5) * 3196 + z2 = (-z2) * 11363 + tmp2 = (d3) * 9102 + z3 = (-d3) * 16069 + tmp0 = z3 + z5 + tmp1 += z2 + tmp2 += z2 + tmp3 = z4 + z5 + end + else + if d1 ~= 0 then + z4 = d5 + d1 + z5 = (z4) * 9633 + z1 = (-d1) * 7373 + tmp3 = (d1) * 4926 + tmp1 = (-d5) * 4176 + z2 = (-d5) * 20995 + z4 = (z4) * 6436 + tmp0 = z1 + z5 + tmp1 += z4 + tmp2 = z2 + z5 + tmp3 += z4 + else + tmp0 = (d5) * 9633 + tmp1 = (d5) * 2260 + tmp2 = (-d5) * 11363 + tmp3 = (d5) * 6436 + end + end + else + if d3 ~= 0 then + if d1 ~= 0 then + z5 = d1 + d3 + tmp3 = (d1) * 1730 + tmp2 = (-d3) * 11893 + z1 = (d1) * 8697 + z2 = (-d3) * 17799 + z4 = (z5) * 6436 + z5 = (z5) * 9633 + tmp0 = z1 - z4 + tmp1 = z2 + z4 + tmp2 += z5 + tmp3 += z5 + else + tmp0 = (-d3) * 6436 + tmp1 = (-d3) * 11363 + tmp2 = (-d3) * 2260 + tmp3 = (d3) * 9633 + end + else + if d1 ~= 0 then + tmp0 = (d1) * 2260 + tmp1 = (d1) * 6436 + tmp2 = (d1) * 9633 + tmp3 = (d1) * 11363 + else + tmp3 = 0 + tmp0 = tmp3 + tmp1 = tmp3 + tmp2 = tmp3 + end + end + end + end + writei32(blk, c, (tmp10 + tmp3 + 131072) // 262144) + writei32(blk, c + 224, (tmp10 - tmp3 + 131072) // 262144) + writei32(blk, c + 32, (tmp11 + tmp2 + 131072) // 262144) + writei32(blk, c + 192, (tmp11 - tmp2 + 131072) // 262144) + writei32(blk, c + 64, (tmp12 + tmp1 + 131072) // 262144) + writei32(blk, c + 160, (tmp12 - tmp1 + 131072) // 262144) + writei32(blk, c + 96, (tmp13 + tmp0 + 131072) // 262144) + writei32(blk, c + 128, (tmp13 - tmp0 + 131072) // 262144) + end + -- put / add, clamped + for r = 0, 224, 32 do + local p0 = readi32(blk, r) + COFF + local p1 = readi32(blk, r + 4) + COFF + local p2 = readi32(blk, r + 8) + COFF + local p3 = readi32(blk, r + 12) + COFF + local p4 = readi32(blk, r + 16) + COFF + local p5 = readi32(blk, r + 20) + COFF + local p6 = readi32(blk, r + 24) + COFF + local p7 = readi32(blk, r + 28) + COFF + if add then + p0 += readu8(dst, off) + p1 += readu8(dst, off + 1) + p2 += readu8(dst, off + 2) + p3 += readu8(dst, off + 3) + p4 += readu8(dst, off + 4) + p5 += readu8(dst, off + 5) + p6 += readu8(dst, off + 6) + p7 += readu8(dst, off + 7) + end + writeu32(dst, off, readu8(CLAMP, p0) + readu8(CLAMP, p1) * 256 + readu8(CLAMP, p2) * 65536 + readu8(CLAMP, p3) * 16777216) + writeu32(dst, off + 4, readu8(CLAMP, p4) + readu8(CLAMP, p5) * 256 + readu8(CLAMP, p6) * 65536 + readu8(CLAMP, p7) * 16777216) + off += stride + end +end + +-- the IDCT of a lone DC coefficient dc is (dc + 4) >> 3 everywhere +@native function Dsp.fill(dst: buffer, off: number, stride: number, v: number, add: boolean) + if not add then + local c = readu8(CLAMP, v + COFF) * 0x01010101 + for _ = 1, 8 do + writeu32(dst, off, c) + writeu32(dst, off + 4, c) + off += stride + end + else + for _ = 1, 8 do + for i = off, off + 7 do + writeu8(dst, i, readu8(CLAMP, readu8(dst, i) + v + COFF)) + end + off += stride + end + end +end + +-- rounding up (MPEG-1 / 2, H.263 rounding_type 0); strides are twice the plane width for field prediction. +-- Four bytes at a time: avg(a, b) = (a | b) - ((a ^ b) & 0xFE..) >> 1; the 4-tap average splits each byte into its +-- low 2 bits and high 6 bits so no lane overflows. +@native function Dsp.mc(src: buffer, sStride: number, sOff: number, dst: buffer, dStride: number, dOff: number, w: number, h: number, hx: number, hy: number, avg: boolean) + for _ = 1, h do + for i = 0, w - 4, 4 do + local p + if hx == 0 then + if hy == 0 then + p = readu32(src, sOff + i) + else + local a, b = readu32(src, sOff + i), readu32(src, sOff + i + sStride) + p = bor(a, b) - rshift(band(bxor(a, b), 0xFEFEFEFE), 1) + end + elseif hy == 0 then + local a, b = readu32(src, sOff + i), readu32(src, sOff + i + 1) + p = bor(a, b) - rshift(band(bxor(a, b), 0xFEFEFEFE), 1) + else + local a, b = readu32(src, sOff + i), readu32(src, sOff + i + 1) + local c, d = readu32(src, sOff + i + sStride), readu32(src, sOff + i + sStride + 1) + local l = band(a, 0x03030303) + band(b, 0x03030303) + band(c, 0x03030303) + band(d, 0x03030303) + 0x02020202 + local hi = rshift(band(a, 0xFCFCFCFC), 2) + rshift(band(b, 0xFCFCFCFC), 2) + rshift(band(c, 0xFCFCFCFC), 2) + rshift(band(d, 0xFCFCFCFC), 2) + p = hi + band(rshift(l, 2), 0x0F0F0F0F) + end + if avg then + local q = readu32(dst, dOff + i) + p = bor(p, q) - rshift(band(bxor(p, q), 0xFEFEFEFE), 1) + end + writeu32(dst, dOff + i, p) + end + sOff += sStride + dOff += dStride + end +end + +-- averages rounded down, (a + b) >> 1 and (a + b + c + d + 1) >> 2 (H.263 rounding type 1, MPEG-4 rounding_control) +@native function Dsp.mcNoRound(src: buffer, sStride: number, sOff: number, dst: buffer, dStride: number, dOff: number, w: number, h: number, hx: number, hy: number) + if hx == 0 and hy == 0 then + Dsp.mc(src, sStride, sOff, dst, dStride, dOff, w, h, 0, 0, false) + return + end + local dx = if hx == 0 then sStride else 1 -- the second sample of a two-tap average + for _ = 1, h do + for i = 0, w - 4, 4 do + local p + if hx == 0 or hy == 0 then + local a, b = readu32(src, sOff + i), readu32(src, sOff + i + dx) + p = band(a, b) + rshift(band(bxor(a, b), 0xFEFEFEFE), 1) + else + local a, b = readu32(src, sOff + i), readu32(src, sOff + i + 1) + local c, d = readu32(src, sOff + i + sStride), readu32(src, sOff + i + sStride + 1) + local l = band(a, 0x03030303) + band(b, 0x03030303) + band(c, 0x03030303) + band(d, 0x03030303) + 0x01010101 + local hi = rshift(band(a, 0xFCFCFCFC), 2) + rshift(band(b, 0xFCFCFCFC), 2) + rshift(band(c, 0xFCFCFCFC), 2) + rshift(band(d, 0xFCFCFCFC), 2) + p = hi + band(rshift(l, 2), 0x0F0F0F0F) + end + writeu32(dst, dOff + i, p) + end + sOff += sStride + dOff += dStride + end +end + +-- edge emulation: coordinates clamped into the plane, so a vector pointing outside the picture predicts from repeated +-- edge samples (w + 1 <= EDGE_STRIDE, h + 1 <= 33) +Dsp.EDGE_STRIDE = 32 +Dsp.EDGE_SIZE = 32 * 34 + 4 +@native function Dsp.edge(src: buffer, stride: number, base: number, x: number, y: number, w: number, h: number, pw: number, ph: number, out: buffer) + for j = 0, h do + local sy = y + j + sy = if sy < 0 then 0 elseif sy >= ph then ph - 1 else sy + local row = base + sy * stride + local o = j * 32 + for i = 0, w do + local sx = x + i + sx = if sx < 0 then 0 elseif sx >= pw then pw - 1 else sx + writeu8(out, o + i, readu8(src, row + sx)) + end + end +end + +return Dsp +end +__FILES["codecs/video/Mpeg1"] = function() + +-- codecs/video/Mpeg1: the MPEG-1 video decoder (ISO/IEC 11172-2), the old name and API over codecs/video/Mpeg2. +-- From mpeg1-luau e2e2898 (same author). +local Mpeg2 = __include("codecs/video/Mpeg2") + +type Frame = Mpeg2.Frame +type Options = Mpeg2.Options +type Decoder = Mpeg2.Decoder + +return Mpeg2 +end +__FILES["codecs/video/Mpeg2"] = function() + +-- codecs/video/Mpeg2: an MPEG-1 / MPEG-2 video decoder (ISO/IEC 11172-2, ISO/IEC 13818-2 Main profile). +-- Bit-exact with `ffmpeg -idct int`. Grown from mpeg1-luau e2e2898 (same author), a port of jsmpeg's decoder +-- (https://github.com/phoboslab/jsmpeg, Dominic Szablewski, MIT: licenses/jsmpeg-MIT.txt). Frames come out woven (top +-- field on even lines). Not supported: 4:4:4, the scalable / multiview extensions, D-pictures (skipped). +local Types = __include("Types") +local Err = __include("core/Err") +local D = __include("codecs/video/Mpeg2/Decoder") + +local Mpeg2 = {} + +Mpeg2.PICTURE_I = 1 +Mpeg2.PICTURE_P = 2 +Mpeg2.PICTURE_B = 3 + +type Frame = { + width: number, + height: number, + pixels: buffer?, -- RGBA8, width * height * 4 bytes, row-major, alpha 255; nil with { rgba = false } + pictureType: number, -- 1 I, 2 P, 3 B + temporalReference: number, -- the picture's 10-bit display index within its GOP + index: number, + tag: any, + -- luma stride codedWidth, chroma stride codedWidth / 2; chroma rows half the luma rows (4:2:0) or as many (4:2:2) + y: buffer, + cb: buffer, + cr: buffer, + codedWidth: number, + chroma: number, -- 1 = 4:2:0, 2 = 4:2:2 + mpeg2: boolean, + progressive: boolean, -- progressive_frame (MPEG-1 and progressive MPEG-2: true) + fields: boolean, + topFieldFirst: boolean, + repeatFirstField: boolean, + clamped: number, + concealed: { [number]: boolean }, +} + +type Options = { + reorder: boolean?, + rgba: boolean?, + maxPixels: number?, + yield: (() -> ())?, +} + +local Decoder = {} +Decoder.__index = Decoder + +type Decoder = typeof(setmetatable( + {} :: { + _core: D.Core, + _reorder: boolean, + _rgba: boolean, + _held: D.Store?, + _pixels: buffer?, + _count: number, + width: number, + height: number, + frameRate: number, + bitRate: number, + stats: { pictures: number, errors: number, skipped: number }, + }, + Decoder +)) + +function Mpeg2.new(opts: Options?): Decoder + local o: Options = if type(opts) == "table" then opts else {} + local core = D.new(o.maxPixels) + if type(o.yield) == "function" then + core.setYield(o.yield) + end + return setmetatable({ + _core = core, + _reorder = o.reorder == true, + _rgba = o.rgba ~= false, + _held = nil, + _pixels = nil, + _count = 0, + width = 0, + height = 0, + frameRate = 0, + bitRate = 0, + stats = { pictures = 0, errors = 0, skipped = 0 }, + }, Decoder) +end + +local function emit(self: Decoder, s: D.Store): Frame + local core = self._core + local pixels: buffer? = nil + if self._rgba then + local need = s.w * s.h * 4 + local px = self._pixels + if px == nil or buffer.len(px) ~= need then + px = buffer.create(need) + self._pixels = px + end + core.toRgba(s, px :: buffer) + pixels = px + end + self._count += 1 + return { + width = s.w, + height = s.h, + pixels = pixels, + pictureType = s.ptype, + temporalReference = s.tref, + index = self._count, + tag = s.tag, + y = s.y, + cb = s.cb, + cr = s.cr, + codedWidth = s.cw, + chroma = s.chroma, + mpeg2 = s.mpeg2, + progressive = s.progressive, + fields = s.fields, + topFieldFirst = s.tff, + repeatFirstField = s.rff, + clamped = s.clamped, + concealed = s.concealed, + } +end + +local function sync(self: Decoder) + local st = self._core.state + self.width = st.width + self.height = st.height + self.frameRate = st.frameRate + self.bitRate = st.bitRate + self.stats.pictures = st.pictures + self.stats.errors = st.errors + self.stats.skipped = st.skipped +end + +local function handle(self: Decoder, s: D.Store): Frame? + if not self._reorder or s.ptype == D.PICTURE_B then + return emit(self, s) + end + local prev = self._held + self._held = s + if prev then + return emit(self, prev) + end + return nil +end + +local function run(self: Decoder, atEnd: boolean, tag: any): Frame? + local core = self._core + while true do + local s, needData = core.nextPicture(atEnd, tag) + sync(self) + if s then + local f = handle(self, s) + if f then + return f + end + elseif needData then + return nil + end + end +end + +local function append(self: Decoder, data: any, offset: number?, len: number?): boolean + local src: buffer + if type(data) == "string" then + src = buffer.fromstring(data) + elseif type(data) == "buffer" then + src = data + else + return false + end + local total = buffer.len(src) + local off = math.floor(tonumber(offset) or 0) + if off < 0 or off > total then + return false + end + local n = math.floor(tonumber(len) or (total - off)) + if n < 0 or off + n > total then + return false + end + self._core.write(src, off, n) + return true +end + +function Decoder.write(self: Decoder, data: buffer | string, offset: number?, len: number?): boolean + return append(self, data, offset, len) +end + +function Decoder.decodeFrame(self: Decoder): Frame? + return run(self, false, nil) +end + +function Decoder.decode(self: Decoder, data: buffer | string, offset: number?, len: number?, tag: any): Frame? + if not append(self, data, offset, len) then + return nil + end + return run(self, true, tag) +end + +function Decoder.flush(self: Decoder): Frame? + local f = run(self, true, nil) + if f then + return f + end + local held = self._held + if held then + self._held = nil + return emit(self, held) + end + return nil +end + +function Decoder.setYield(self: Decoder, hook: (() -> ())?) + self._core.setYield(if type(hook) == "function" then hook else nil) +end + +function Decoder.reset(self: Decoder) + self._core.reset() + self._held = nil +end + +function Mpeg2.toRgba(y: buffer, cb: buffer, cr: buffer, codedWidth: number, width: number, height: number, out: buffer, row0: number?, row1: number?, outOffset: number?, planeRow0: number?, hook: (() -> ())?): boolean + if type(y) ~= "buffer" or type(cb) ~= "buffer" or type(cr) ~= "buffer" or type(out) ~= "buffer" then + return false + end + local cw, w, h = tonumber(codedWidth), tonumber(width), tonumber(height) + if not cw or not w or not h or cw % 2 ~= 0 or w < 1 or h < 1 or w > cw or cw ~= math.floor(cw) or w ~= math.floor(w) or h ~= math.floor(h) then + return false + end + local r0 = math.floor(tonumber(row0) or 0) + r0 -= r0 % 2 + local r1 = math.floor(tonumber(row1) or h) + local pr = math.floor(tonumber(planeRow0) or 0) + local oo = math.floor(tonumber(outOffset) or 0) + if r0 < 0 or r1 > h or r1 <= r0 or pr < 0 or pr % 2 ~= 0 or pr > r0 or oo < 0 or oo % 4 ~= 0 then + return false + end + local lumaRows = r1 - pr + local chromaRows = (r1 + 1) // 2 - pr // 2 + if buffer.len(y) < lumaRows * cw or buffer.len(cb) < chromaRows * (cw // 2) or buffer.len(cr) < chromaRows * (cw // 2) then + return false + end + if buffer.len(out) < oo + (r1 - r0) * w * 4 then + return false + end + D.toRgba(y, cb, cr, cw, w, h, out, r0 - pr, r1 - pr, oo, if type(hook) == "function" then hook else nil) + return true +end + +function Mpeg2.frameImage(frame: Frame, rgba: boolean?): Types.Image? + if type(frame) ~= "table" or type(frame.y) ~= "buffer" or type(frame.cb) ~= "buffer" or type(frame.cr) ~= "buffer" then + return nil + end + local w, h, cw = frame.width, frame.height, frame.codedWidth + if type(w) ~= "number" or type(h) ~= "number" or type(cw) ~= "number" or w < 1 or h < 1 or cw < w then + return nil + end + local c422 = frame.chroma == 2 + local chw, ow, oh = cw // 2, (w + 1) // 2, (h + 1) // 2 + local crows = if c422 then h else oh + if buffer.len(frame.y) < cw * h or buffer.len(frame.cb) < chw * crows or buffer.len(frame.cr) < chw * crows then + return nil + end + local img + if rgba then + img = Types.Image.new(w, h) + if c422 then + D.toRgba422(frame.y, frame.cb, frame.cr, cw, w, h, img.pixels) + else + D.toRgba(frame.y, frame.cb, frame.cr, cw, w, h, img.pixels) + end + else + img = Types.Image.new(w, h, "yuv420p") + local px = img.pixels + for y = 0, h - 1 do + buffer.copy(px, y * w, frame.y, y * cw, w) + end + local o = w * h + if not c422 then + for y = 0, oh - 1 do + buffer.copy(px, o + y * ow, frame.cb, y * chw, ow) + buffer.copy(px, o + ow * oh + y * ow, frame.cr, y * chw, ow) + end + else + -- 4:2:2 -> 4:2:0: progressive frames average lines 2k, 2k + 1; interlaced ones lines of the same field + -- (4k + j and 4k + j + 2), so the fields do not mix + local inter = not frame.progressive + for y = 0, oh - 1 do + local a, b + if inter then + local base = (y // 2) * 4 + y % 2 + a, b = base, base + 2 + else + a, b = 2 * y, 2 * y + 1 + end + if b >= h then + b = a + end + for x = 0, ow - 1 do + buffer.writeu8(px, o + y * ow + x, (buffer.readu8(frame.cb, a * chw + x) + buffer.readu8(frame.cb, b * chw + x) + 1) // 2) + buffer.writeu8(px, o + ow * oh + y * ow + x, (buffer.readu8(frame.cr, a * chw + x) + buffer.readu8(frame.cr, b * chw + x) + 1) // 2) + end + end + end + end + img.meta.source = { + format = if frame.mpeg2 then "mpeg2" else "mpeg1", + pictureType = frame.pictureType, + temporalReference = frame.temporalReference, + chroma = if c422 then "422" else "420", + interlaced = not frame.progressive, + topFieldFirst = frame.topFieldFirst, + range = if rgba then nil else "limited", + } + return img +end + +function Mpeg2.newVideoDecoder(_track: any, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) + local dec = Mpeg2.new({ reorder = true, rgba = false, maxPixels = opts and opts.maxPixels }) + local queue: { any } = {} + local function push(f: Frame) + local img = Mpeg2.frameImage(f) + if img then + img.meta.yuv = { range = "limited", matrix = "bt601" } + local tag = f.tag + table.insert(queue, { img, if type(tag) == "table" then tag[1] else nil, f.pictureType == 1 }) + end + end + local self = {} + function self.decode(_: any, packet: Types.Packet): Err.Err? + local tag = { packet.pts } + local ok, f = pcall(dec.decode, dec, packet.data, 0, buffer.len(packet.data), tag) + if not ok then + return Err.new(Err.CORRUPT, "decoder threw: " .. tostring(f)) + end + while f do + push(f) + f = dec:decode(packet.data, 0, 0, tag) + end + return nil + end + function self.receive(_: any): (Types.Image?, number?, boolean?) + local q = table.remove(queue, 1) + if q then + return q[1], q[2], q[3] + end + return nil, nil, nil + end + function self.flush(_: any) + for _ = 1, 8 do + local f = dec:flush() + if not f then + break + end + push(f) + end + end + function self.reset(_: any) + dec:reset() + table.clear(queue) + end + return self :: any, nil +end + +return Mpeg2 +end +__FILES["codecs/video/Mpeg2/Decoder"] = @native function() + + +-- codecs/video/Mpeg2/Decoder: the MPEG-1 / MPEG-2 video decoding core (ISO/IEC 11172-2, 13818-2 Main profile). +-- From mpeg1-luau e2e2898 (same author; a port of jsmpeg's src/mpeg1.js by Dominic Szablewski, MIT, +-- licenses/jsmpeg-MIT.txt). Dequantisation follows ffmpeg's arithmetic; coefficients are saturated to -2048..2047 +-- (13818-2 7.4.3; ffmpeg omits it) and vectors outside the reference are clamped (ffmpeg skips the prediction). +local V = __include("codecs/video/Mpeg2/Vlc") +local T = __include("codecs/video/Mpeg2/Tables") +local Dsp = __include("codecs/video/Dsp") + +local readu8 = buffer.readu8 +local writeu8 = buffer.writeu8 +local readu32 = buffer.readu32 +local writeu32 = buffer.writeu32 +local readi32 = buffer.readi32 +local writei32 = buffer.writei32 +local band = bit32.band +local bor = bit32.bor +local bxor = bit32.bxor +local lshift = bit32.lshift +local rshift = bit32.rshift +local bswap = bit32.byteswap +local idct = Dsp.idct +local fillBlock = Dsp.fill +local mc = Dsp.mc + +local PAD = 4096 -- zero bytes after the data: a macroblock reads at most ~2 KB, the pos check runs per macroblock + +local D = {} + +D.PICTURE_I = 1 +D.PICTURE_P = 2 +D.PICTURE_B = 3 + +-- scan index -> natural position (zigzag, alternate); default matrices in natural order +local ZZ = buffer.create(64) +local ALT = buffer.create(64) +local DEF_INTRA = buffer.create(64) +local DEF_NON_INTRA = buffer.create(64) +for i = 0, 63 do + buffer.writeu8(ZZ, i, T.ZIG_ZAG[i]) + buffer.writeu8(ALT, i, T.ALTERNATE_SCAN[i]) + buffer.writeu8(DEF_INTRA, i, T.DEFAULT_INTRA_QUANT_MATRIX[i]) + buffer.writeu8(DEF_NON_INTRA, i, T.DEFAULT_NON_INTRA_QUANT_MATRIX[i]) +end +local NON_LINEAR = buffer.create(32) +for i = 0, 31 do + buffer.writeu8(NON_LINEAR, i, T.NON_LINEAR_QSCALE[i]) +end + +local COFF = 40000 + +local MBAI, MBAI_BITS = V.MBAI, V.MBAI_BITS +local CBP, CBP_BITS = V.CBP, V.CBP_BITS +local MOTION, MOTION_BITS = V.MOTION, V.MOTION_BITS +local DC_LUMA, DC_LUMA_BITS = V.DC_LUMA, V.DC_LUMA_BITS +local DC_CHROMA, DC_CHROMA_BITS = V.DC_CHROMA, V.DC_CHROMA_BITS +local DCT_FIRST, DCT_NEXT, DCT_B15 = V.DCT_FIRST, V.DCT_NEXT, V.DCT_B15 +local SUB, ESC, EOB = V.SUB, V.ESC, V.EOB +local MBTYPE = { V.MBTYPE_I, V.MBTYPE_P, V.MBTYPE_B } +local MBTYPE_BITS = { V.MBTYPE_I_BITS, V.MBTYPE_P_BITS, V.MBTYPE_B_BITS } + +-- BT.601 limited range: R = 1.164 (Y - 16) + 1.596 (Cr - 128), G = 1.164 (Y - 16) - 0.392 (Cb - 128) - 0.813 (Cr - +-- 128), B = 1.164 (Y - 16) + 2.017 (Cb - 128), in 8-bit fixed point. The rounding offsets (-128, -160, -72 / 256) +-- are fitted to ffmpeg's swscale output, which lands about half a level below round-to-nearest. +-- the constant terms, plus COFF * 256 so the sums stay positive for rshift +local RBIAS = COFF * 256 - 298 * 16 - 409 * 128 - 128 +local GBIAS = COFF * 256 - 298 * 16 + 100 * 128 + 208 * 128 - 160 +local BBIAS = COFF * 256 - 298 * 16 - 516 * 128 - 72 + +-- clamp by lookup: RGB_CLAMP[v + COFF] for v in [-COFF, COFF + 255]; the colour biases include COFF * 256 +local RGB_CLAMP = buffer.create(2 * COFF + 256) +for i = 0, 2 * COFF + 255 do + buffer.writeu8(RGB_CLAMP, i, math.clamp(i - COFF, 0, 255)) +end + +-- 4:2:0 -> RGBA8 with nearest chroma, like ffmpeg's default swscale path; hook is pcall'ed (can't throw through here) +@native local function toRgba(Y: buffer, Cb: buffer, Cr: buffer, cw: number, w: number, h: number, out: buffer, row0: number?, row1: number?, oo: number?, hook: (() -> ())?) + -- 2 x 2 pixels per chroma sample: the chroma terms are computed once per block of four + local r0: number = row0 or 0 + local r1: number = row1 or h + local base: number = oo or 0 + local chw = cw // 2 + local w2 = w // 2 -- whole pixel pairs per row + local stride = w * 4 + local C = RGB_CLAMP + local n = 0 + for y = r0, r1 - 1, 2 do + local yo = y * cw + local co = (y // 2) * chw + local o = base + (y - r0) * stride + local two = y + 1 < r1 + for _ = 1, w2 do + local cb, cr = readu8(Cb, co), readu8(Cr, co) + co += 1 + local rr = cr * 409 + RBIAS + local gg = GBIAS - cb * 100 - cr * 208 + local bb = cb * 516 + BBIAS + local yv = readu8(Y, yo) * 298 + writeu32(out, o, readu8(C, rshift(yv + rr, 8)) + readu8(C, rshift(yv + gg, 8)) * 256 + readu8(C, rshift(yv + bb, 8)) * 65536 + 0xFF000000) + yv = readu8(Y, yo + 1) * 298 + writeu32(out, o + 4, readu8(C, rshift(yv + rr, 8)) + readu8(C, rshift(yv + gg, 8)) * 256 + readu8(C, rshift(yv + bb, 8)) * 65536 + 0xFF000000) + if two then + yv = readu8(Y, yo + cw) * 298 + writeu32(out, o + stride, readu8(C, rshift(yv + rr, 8)) + readu8(C, rshift(yv + gg, 8)) * 256 + readu8(C, rshift(yv + bb, 8)) * 65536 + 0xFF000000) + yv = readu8(Y, yo + cw + 1) * 298 + writeu32(out, o + stride + 4, readu8(C, rshift(yv + rr, 8)) + readu8(C, rshift(yv + gg, 8)) * 256 + readu8(C, rshift(yv + bb, 8)) * 65536 + 0xFF000000) + end + yo += 2 + o += 8 + end + if w % 2 == 1 then + -- the last column of an odd width + local cb, cr = readu8(Cb, co), readu8(Cr, co) + local rr = cr * 409 + RBIAS + local gg = GBIAS - cb * 100 - cr * 208 + local bb = cb * 516 + BBIAS + for k = 0, if two then 1 else 0 do + local yv = readu8(Y, yo + k * cw) * 298 + writeu32(out, o + k * stride, readu8(C, rshift(yv + rr, 8)) + readu8(C, rshift(yv + gg, 8)) * 256 + readu8(C, rshift(yv + bb, 8)) * 65536 + 0xFF000000) + end + end + n += 2 + if hook and n >= 16 then + n = 0 + pcall(hook) + end + end +end +D.toRgba = toRgba + +-- YCbCr 4:2:2 planes -> RGBA8: chroma row y for luma row y, chroma column x // 2 +@native local function toRgba422(Y: buffer, Cb: buffer, Cr: buffer, cw: number, w: number, h: number, out: buffer) + local chw = cw // 2 + for y = 0, h - 1 do + local o = y * w * 4 + for x = 0, w - 1 do + local c = y * chw + x // 2 + local cb, cr = readu8(Cb, c), readu8(Cr, c) + local yv = readu8(Y, y * cw + x) * 298 + local r = math.clamp(rshift(yv + cr * 409 + RBIAS, 8) - COFF, 0, 255) + local g = math.clamp(rshift(yv + GBIAS - cb * 100 - cr * 208, 8) - COFF, 0, 255) + local b = math.clamp(rshift(yv + cb * 516 + BBIAS, 8) - COFF, 0, 255) + writeu32(out, o + x * 4, r + g * 256 + b * 65536 + 0xFF000000) + end + end +end +D.toRgba422 = toRgba422 + +type Store = { + y: buffer, + cb: buffer, + cr: buffer, + w: number, + h: number, + cw: number, -- luma stride (coded width); chroma stride cw / 2 + chroma: number, -- 1 = 4:2:0, 2 = 4:2:2 + tref: number, + ptype: number, + tag: any, + mpeg2: boolean, + progressive: boolean, -- progressive_frame (MPEG-1: true) + fields: boolean, -- coded as two field pictures + tff: boolean, -- top_field_first + rff: boolean, -- repeat_first_field + clamped: number, -- predictions from outside the reference (edge-emulated) in the last picture decoded into it + concealed: { [number]: boolean }, -- macroblock rows (of the frame) with macroblocks no slice covered (concealed) +} + +type Core = { + write: (src: buffer, off: number, n: number) -> (), + nextPicture: (atEnd: boolean, tag: any) -> (Store?, boolean), + toRgba: (s: Store, out: buffer) -> (), + reset: () -> (), + setYield: (hook: (() -> ())?) -> (), + state: { + width: number, + height: number, + codedWidth: number, + codedHeight: number, + frameRate: number, + aspect: number, + bitRate: number, + mpeg2: boolean, + chroma: number, + progressive: boolean, -- progressive_sequence + profileLevel: number, + sizeChanged: boolean, + pictures: number, + errors: number, + skipped: number, + clamped: number, -- motion vectors pointing outside the reference (clamped) + maxPixels: number, + refOld: Store?, + refNew: Store?, + }, +} + +@native function D.new(maxPixels: number?): Core + local state = { + width = 0, + height = 0, + codedWidth = 0, + codedHeight = 0, + frameRate = 0, + aspect = 0, + bitRate = 0, + mpeg2 = false, + chroma = 1, + progressive = true, + profileLevel = 0, + sizeChanged = false, + pictures = 0, + errors = 0, + skipped = 0, + clamped = 0, + maxPixels = maxPixels or 4096 * 2304, + refOld = nil :: Store?, + refNew = nil :: Store?, + } + + local data = buffer.create(64 * 1024 + PAD) + local dataLen = 0 + local readByte = 0 -- next byte to look at for a start code + local scanPos = 0 -- resume point of the picture-end scan + local pos = 0 -- bit position inside data + local err = false + + local hasSeq = false + local mpeg2 = false + local chroma = 1 -- 1 = 4:2:0, 2 = 4:2:2 + local progSeq = true + local mbW, mbH = 0, 0 -- frame size in macroblocks + local cw, chw = 0, 0 -- luma / chroma strides (coded widths) + local lumaH, chromaH = 0, 0 -- plane heights (coded) + local intraQ = buffer.create(64) -- natural order + local nonIntraQ = buffer.create(64) + local chromaIntraQ = buffer.create(64) + local chromaNonIntraQ = buffer.create(64) + buffer.copy(intraQ, 0, DEF_INTRA, 0, 64) + buffer.copy(nonIntraQ, 0, DEF_NON_INTRA, 0, 64) + buffer.copy(chromaIntraQ, 0, DEF_INTRA, 0, 64) + buffer.copy(chromaNonIntraQ, 0, DEF_NON_INTRA, 0, 64) + local stores: { Store } = {} + local bStore: Store? = nil + -- the sequence header's values, applied (and the stores allocated) once its extension has been seen + local seqW, seqH = 0, 0 + + local ptype = 0 + local fc00, fc01, fc10, fc11 = 1, 1, 1, 1 -- f_code[s][t] + local fullPelFw, fullPelBw = false, false + local dcPrec = 0 + local picStruct = 3 -- 1 top field, 2 bottom field, 3 frame + local fpfd = true -- frame_pred_frame_dct + local concealMv = false + local qScaleType = 0 + local intraVlc = false + local scan = ZZ + local tff, rff, progFrame = true, false, true + local fieldPic = false + local secondField = false + local parity = 0 -- the current field (0 top, 1 bottom) + local mbRows, mbSize = 0, 0 -- of the current picture (field pictures: half the frame's rows) + local lstride, lbase, cstride, cbase = 0, 0, 0, 0 -- plane addressing of the current picture + local cur: Store? = nil + local curY, curCb, curCr = data, data, data + local fwS: Store? = nil + local bwS: Store? = nil + local pending: Store? = nil -- a first field waiting for its second + local pendingStruct = 0 + local pendingFw: Store? = nil + local pendingBw: Store? = nil + + local qscale = 2 + local mbAddr, mbRow, mbCol = 0, 0, 0 + local dcY, dcCb, dcCr = 128, 128, 128 + local mbIntra = false + local motFw, motBw = false, false + local motionType = 1 -- 1 frame (field pictures: field 16x16), 2 field (frame pictures), 3 16x8, 4 dual prime + local dctType = 0 + -- vectors: MV[(d * 4 + k) * 2 + c + 1] (direction d, vector k: 0 / 1 the two fields or halves, 2 / 3 dual-prime + -- opposite-parity vectors; component c); PMV[(d * 2 + r) * 2 + c + 1]; FSEL[d * 2 + r + 1] + local MV = table.create(16, 0) + local PMV = table.create(8, 0) + local FSEL = table.create(4, 0) + local blk = buffer.create(256) + local yieldHook: (() -> ())? = nil + + @native local function peek32(): number + local bp = rshift(pos, 3) + local w = bswap(readu32(data, bp)) + local s = band(pos, 7) + if s ~= 0 then + w = bor(lshift(w, s), rshift(readu8(data, bp + 4), 8 - s)) + end + return w + end + + @native local function read(n: number): number + local v = rshift(peek32(), 32 - n) + pos += n + return v + end + + @native local function vlc(lut: buffer, k: number): number + local e = readu32(lut, rshift(peek32(), 32 - k) * 4) + local l = rshift(e, 16) + if l == 0 then + err = true + return 0 + end + pos += l + return band(e, 0xFFFF) - 32768 + end + + @native local function findStart(from: number, to: number): number + local i = from + while i + 3 < to do + local c = readu8(data, i + 2) + if c > 1 then + i += 3 + elseif c == 1 then + if readu8(data, i) == 0 and readu8(data, i + 1) == 0 then + return i + end + i += 3 + else + i += 1 + end + end + return -1 + end + + @native local function newStore(): Store + local y = buffer.create(cw * lumaH) + local cb = buffer.create(chw * chromaH) + local cr = buffer.create(chw * chromaH) + buffer.fill(y, 0, 16) -- black until a picture is decoded into it + buffer.fill(cb, 0, 128) + buffer.fill(cr, 0, 128) + return { + y = y, + cb = cb, + cr = cr, + w = state.width, + h = state.height, + cw = cw, + chroma = chroma, + tref = 0, + ptype = 0, + tag = nil, + mpeg2 = mpeg2, + progressive = true, + fields = false, + tff = true, + rff = false, + clamped = 0, + concealed = {}, + } + end + + @native local function loadMatrix(q: buffer) + for i = 0, 63 do + local v = read(8) + writeu8(q, readu8(ZZ, i), if v == 0 then 1 else v) + end + end + + @native local function applySequence(): boolean + local w, h = seqW, seqH + if w == 0 or h == 0 or w * h > state.maxPixels then + return false + end + local mh = if mpeg2 and not progSeq then 2 * ((h + 31) // 32) else (h + 15) // 16 + if w ~= state.width or h ~= state.height or mh ~= mbH or chroma ~= state.chroma or mpeg2 ~= state.mpeg2 then + state.width = w + state.height = h + state.chroma = chroma + state.mpeg2 = mpeg2 + mbW = (w + 15) // 16 + mbH = mh + cw = mbW * 16 + chw = mbW * 8 + lumaH = mbH * 16 + chromaH = if chroma == 2 then lumaH else lumaH // 2 + state.codedWidth = cw + state.codedHeight = lumaH + stores = { newStore(), newStore() } + bStore = newStore() + state.refOld = nil + state.refNew = nil + pending = nil + state.sizeChanged = true + end + state.progressive = progSeq + hasSeq = true + return true + end + + @native local function sequenceHeader(p: number): boolean + pos = p * 8 + local w = read(12) + local h = read(12) + local aspect = read(4) + local rate = read(4) + local bitRate = read(18) + pos += 1 + 10 + 1 -- marker, vbv_buffer_size, constrained_parameters_flag + if read(1) == 1 then + loadMatrix(intraQ) + else + buffer.copy(intraQ, 0, DEF_INTRA, 0, 64) + end + if read(1) == 1 then + loadMatrix(nonIntraQ) + else + buffer.copy(nonIntraQ, 0, DEF_NON_INTRA, 0, 64) + end + buffer.copy(chromaIntraQ, 0, intraQ, 0, 64) + buffer.copy(chromaNonIntraQ, 0, nonIntraQ, 0, 64) + state.frameRate = T.PICTURE_RATE[rate] or 0 + state.aspect = aspect + state.bitRate = bitRate * 400 + seqW, seqH = w, h + mpeg2 = false -- until a sequence extension follows + chroma = 1 + progSeq = true + return w > 0 and h > 0 + end + + @native local function sequenceExtension() + state.profileLevel = read(8) + progSeq = read(1) == 1 + local cf = read(2) + seqW += lshift(read(2), 12) + seqH += lshift(read(2), 12) + state.bitRate += lshift(read(12), 18) * 400 + pos += 1 + 8 + 1 -- marker, vbv_buffer_size_extension, low_delay + local n = read(2) + local d = read(5) + state.frameRate = state.frameRate * (n + 1) / (d + 1) + mpeg2 = true + chroma = if cf == 2 then 2 else 1 -- 4:4:4 (3) is not supported: decoded as 4:2:0 (wrong but safe) + if cf == 3 then + state.errors += 1 + end + end + + @native local function quantMatrixExtension() + if read(1) == 1 then + loadMatrix(intraQ) + buffer.copy(chromaIntraQ, 0, intraQ, 0, 64) + end + if read(1) == 1 then + loadMatrix(nonIntraQ) + buffer.copy(chromaNonIntraQ, 0, nonIntraQ, 0, 64) + end + if read(1) == 1 then + loadMatrix(chromaIntraQ) + end + if read(1) == 1 then + loadMatrix(chromaNonIntraQ) + end + end + + @native local function fcode(v: number): number + return if v < 1 or v > 9 then 1 else v + end + + @native local function pictureCodingExtension() + fc00, fc01, fc10, fc11 = fcode(read(4)), fcode(read(4)), fcode(read(4)), fcode(read(4)) + dcPrec = read(2) + picStruct = read(2) + tff = read(1) == 1 + fpfd = read(1) == 1 + concealMv = read(1) == 1 + qScaleType = read(1) + intraVlc = read(1) == 1 + scan = if read(1) == 1 then ALT else ZZ + rff = read(1) == 1 + pos += 1 -- chroma_420_type + progFrame = read(1) == 1 + if picStruct == 0 then + picStruct = 3 + err = true + end + end + + -- an extension (00 00 01 B5) at byte p + @native local function extension(p: number) + pos = p * 8 + local id = read(4) + if id == 1 then + sequenceExtension() + elseif id == 3 then + quantMatrixExtension() + elseif id == 8 then + pictureCodingExtension() + end + end + + @native local function decodeMotion(f: number, pred: number): number + local code = vlc(MOTION, MOTION_BITS) + local d = code + local rsize = f - 1 + if code ~= 0 and rsize > 0 then + local r = read(rsize) + d = lshift(math.abs(code) - 1, rsize) + r + 1 + if code < 0 then + d = -d + end + end + local range = lshift(16, rsize) + return (pred + d + range) % (2 * range) - range + end + + local EDGE = buffer.create(Dsp.EDGE_SIZE) + @native local function mcPart(rY: buffer, rCb: buffer, rCr: buffer, sp: number, dp: number, rowY: number, h: number, mvx: number, mvy: number, avg: boolean) + local stride, sb, db, ph = cw, 0, 0, lumaH + local cs, csb, cdb = chw, 0, 0 + if sp >= 0 then + stride, sb, db, ph = 2 * cw, sp * cw, dp * cw, lumaH // 2 + cs, csb, cdb = 2 * chw, sp * chw, dp * chw + end + local hx, hy = band(mvx, 1), band(mvy, 1) + local sx = mbCol * 16 + (mvx - hx) // 2 + local sy = rowY + (mvy - hy) // 2 + local dOff = db + rowY * stride + mbCol * 16 + if sx < 0 or sy < 0 or sx + 16 + hx > cw or sy + h + hy > ph then + -- outside the reference (invalid in MPEG; ffmpeg's encoder writes such half-sample vectors at the right / + -- bottom edge): predicted from repeated edge samples, as the encoder meant (ffmpeg's decoder skips it) + Dsp.edge(rY, stride, sb, sx, sy, 16, h, cw, ph, EDGE) + mc(EDGE, 32, 0, curY, stride, dOff, 16, h, hx, hy, avg) + state.clamped += 1; + (cur :: Store).clamped += 1 + else + mc(rY, stride, sb + sy * stride + sx, curY, stride, dOff, 16, h, hx, hy, avg) + end + -- chroma: horizontal vector / 2 truncated toward zero; vertical too in 4:2:0 + local mx = mvx // 2 + if mvx < 0 then + mx = -((-mvx) // 2) + end + local cx, cy, chh, cph, chx, chy + chx = band(mx, 1) + cx = mbCol * 8 + (mx - chx) // 2 + if chroma == 1 then + local my = mvy // 2 + if mvy < 0 then + my = -((-mvy) // 2) + end + chy = band(my, 1) + cy = rowY // 2 + (my - chy) // 2 + chh, cph = h // 2, ph // 2 + else + chy = band(mvy, 1) + cy = rowY + (mvy - chy) // 2 + chh, cph = h, ph + end + local crow = rowY + if chroma == 1 then + crow = rowY // 2 + end + local cdOff = cdb + crow * cs + mbCol * 8 + if cx < 0 or cy < 0 or cx + 8 + chx > chw or cy + chh + chy > cph then + Dsp.edge(rCb, cs, csb, cx, cy, 8, chh, chw, cph, EDGE) + mc(EDGE, 32, 0, curCb, cs, cdOff, 8, chh, chx, chy, avg) + Dsp.edge(rCr, cs, csb, cx, cy, 8, chh, chw, cph, EDGE) + mc(EDGE, 32, 0, curCr, cs, cdOff, 8, chh, chx, chy, avg) + else + local so = csb + cy * cs + cx + mc(rCb, cs, so, curCb, cs, cdOff, 8, chh, chx, chy, avg) + mc(rCr, cs, so, curCr, cs, cdOff, 8, chh, chx, chy, avg) + end + end + + -- the reference frame for field fs of direction d in a field picture: the second field of a P frame takes the + -- opposite parity from its own first field + @native local function fieldRef(d: number, fs: number): Store + if d == 0 then + if secondField and ptype == 2 and fs ~= parity then + return cur :: Store + end + return (fwS or cur) :: Store + end + return (bwS or cur) :: Store + end + + @native local function predictDir(d: number, avg: boolean) + local o = d * 8 + if not fieldPic then + local r = bwS + if d == 0 then + r = fwS + end + if r == nil then + r = cur + end + local ref = r :: Store + local ry, rcb, rcr = ref.y, ref.cb, ref.cr + if motionType == 1 then + mcPart(ry, rcb, rcr, -1, -1, mbRow * 16, 16, MV[o + 1], MV[o + 2], avg) + elseif motionType == 2 then + mcPart(ry, rcb, rcr, FSEL[d * 2 + 1], 0, mbRow * 8, 8, MV[o + 1], MV[o + 2], avg) + mcPart(ry, rcb, rcr, FSEL[d * 2 + 2], 1, mbRow * 8, 8, MV[o + 3], MV[o + 4], avg) + else -- dual prime: each field from the same parity (MV 0 / 1), averaged with the opposite parity (MV 2 / 3) + mcPart(ry, rcb, rcr, 0, 0, mbRow * 8, 8, MV[o + 1], MV[o + 2], avg) + mcPart(ry, rcb, rcr, 1, 1, mbRow * 8, 8, MV[o + 3], MV[o + 4], avg) + mcPart(ry, rcb, rcr, 1, 0, mbRow * 8, 8, MV[o + 5], MV[o + 6], true) + mcPart(ry, rcb, rcr, 0, 1, mbRow * 8, 8, MV[o + 7], MV[o + 8], true) + end + return + end + if motionType == 1 then + local fs = FSEL[d * 2 + 1] + local r = fieldRef(d, fs) + mcPart(r.y, r.cb, r.cr, fs, parity, mbRow * 16, 16, MV[o + 1], MV[o + 2], avg) + elseif motionType == 3 then + for k = 0, 1 do + local fs = FSEL[d * 2 + k + 1] + local r = fieldRef(d, fs) + mcPart(r.y, r.cb, r.cr, fs, parity, mbRow * 16 + k * 8, 8, MV[o + k * 2 + 1], MV[o + k * 2 + 2], avg) + end + else -- dual prime: same parity, then the opposite one (the first field of this frame for a second field) + local r = (fwS or cur) :: Store + mcPart(r.y, r.cb, r.cr, parity, parity, mbRow * 16, 16, MV[o + 1], MV[o + 2], avg) + local q = if secondField then cur :: Store else r + mcPart(q.y, q.cb, q.cr, 1 - parity, parity, mbRow * 16, 16, MV[o + 5], MV[o + 6], true) + end + end + + @native local function predictMb() + if ptype == 2 then + predictDir(0, false) + elseif motFw then + predictDir(0, false) + if motBw then + predictDir(1, true) + end + elseif motBw then + predictDir(1, false) + end + end + + @native local function resetPmv() + for i = 1, 8 do + PMV[i] = 0 + end + end + + -- a skipped macroblock's motion (13818-2 7.6.6): P a zero vector (field pictures: from the same parity); B the + -- previous macroblock's directions with its first vectors as frame (or same-parity field) prediction + @native local function skipMotion() + motionType = 1 + FSEL[1], FSEL[3] = parity, parity + if ptype == 2 then + resetPmv() + MV[1], MV[2] = 0, 0 + else + MV[1], MV[2] = PMV[1], PMV[2] + MV[9], MV[10] = PMV[5], PMV[6] + end + end + + -- macroblocks no slice covers: ffmpeg's encoder skips a row's last macroblock at an MPEG-1 slice end and its decoder + -- conceals it as skipped; so do we (P / damaged I: zero-vector copy, B: the prediction before the gap) + local covered = 0 + local gapFw, gapBw = false, false + local GAP = table.create(16, 0) + local gapType = 1 + local hasRef = false + local SAVE = table.create(16, 0) + @native local function conceal(from: number, to: number) + if from > to or not hasRef then + return + end + local sFw, sBw, sType = motFw, motBw, motionType + table.move(MV, 1, 16, 1, SAVE) + local f1, f2, f3, f4 = FSEL[1], FSEL[2], FSEL[3], FSEL[4] + if ptype == 3 and mpeg2 then + -- both references, zero vectors (ffmpeg's error concealment of B macroblocks, without its deblocking) + motFw, motBw, motionType = true, true, 1 + MV[1], MV[2], MV[9], MV[10] = 0, 0, 0, 0 + elseif ptype == 3 then + motFw, motBw, motionType = gapFw, gapBw, gapType + table.move(GAP, 1, 16, 1, MV) + if not motFw and not motBw then + motFw = true + motionType = 1 + MV[1], MV[2] = 0, 0 + end + else + motionType = 1 + if not (ptype == 2 and gapFw) then + MV[1], MV[2] = 0, 0 + else + MV[1], MV[2] = GAP[1], GAP[2] + end + end + FSEL[1], FSEL[2], FSEL[3], FSEL[4] = parity, parity, parity, parity + local pt = ptype + if pt == 1 then + ptype = 2 -- a damaged I picture: copy the previous reference + end + local c = (cur :: Store).concealed + for a = from, to do + mbRow = a // mbW + mbCol = a % mbW + predictMb() + if fieldPic then + c[mbRow * 2] = true + c[mbRow * 2 + 1] = true + else + c[mbRow] = true + end + end + ptype = pt + motFw, motBw, motionType = sFw, sBw, sType + table.move(SAVE, 1, 16, 1, MV) + FSEL[1], FSEL[2], FSEL[3], FSEL[4] = f1, f2, f3, f4 + end + + -- block b: 0..3 luma, then Cb / Cr alternating + @native local function decodeBlock(b: number): boolean + local n = 0 + local q: buffer + local onlyDc = true + local luma = b < 4 + local parityOdd = 1 -- MPEG-2 mismatch control: 1 while the coefficient sum is even + if mbIntra then + local dc + local size + if luma then + size = vlc(DC_LUMA, DC_LUMA_BITS) + dc = dcY + else + size = vlc(DC_CHROMA, DC_CHROMA_BITS) + dc = dcCr + if b % 2 == 0 then + dc = dcCb + end + end + if size > 0 then + local diff = read(size) + if band(diff, lshift(1, size - 1)) == 0 then + diff = diff + 1 - lshift(1, size) + end + dc += diff + end + if err then + return false + end + local top = lshift(256, dcPrec) - 1 + if dc < 0 or dc > top then + dc = if dc < 0 then 0 else top -- corrupt data: clamped, which also bounds the IDCT input + end + if luma then + dcY = dc + elseif b % 2 == 0 then + dcCb = dc + else + dcCr = dc + end + local v = lshift(dc, 3 - dcPrec) + writei32(blk, 0, v) + parityOdd = bxor(1, band(v, 1)) + q = chromaIntraQ + if luma then + q = intraQ + end + n = 1 + else + q = chromaNonIntraQ + if luma then + q = nonIntraQ + end + end + local lut, nextLut = DCT_NEXT, DCT_NEXT + if mbIntra and intraVlc then + lut, nextLut = DCT_B15, DCT_B15 + elseif n == 0 then + lut = DCT_FIRST + end + local intra = mbIntra + local qs = qscale + local m2 = mpeg2 + while true do + local bp = rshift(pos, 3) + local w = bswap(readu32(data, bp)) + local s = band(pos, 7) + if s ~= 0 then + w = bor(lshift(w, s), rshift(readu8(data, bp + 4), 8 - s)) + end + local e = readu32(lut, rshift(w, 24) * 4) + if e >= SUB then + e = readu32(lut, (band(e, 0xFFFF) * 256 + band(rshift(w, 16), 255)) * 4) + end + local l = rshift(e, 16) + if l == 0 then + err = true + return false + end + local v = band(e, 0xFFFF) + lut = nextLut + if v == EOB then + pos += l + break + end + local run, level, neg + if v == ESC then + pos += l + run = read(6) + if m2 then + -- a 12-bit signed level + level = read(12) + if level >= 2048 then + level -= 4096 + end + else + -- an 8-bit level or 0x00 / 0x80 and 8 more bits + level = read(8) + if level == 0 then + level = read(8) + elseif level == 128 then + level = read(8) - 256 + elseif level > 128 then + level -= 256 + end + end + neg = level < 0 + if neg then + level = -level + end + if level == 0 then + err = true + return false + end + else + run = rshift(v, 8) + level = band(v, 255) + neg = band(lshift(w, l), 0x80000000) ~= 0 -- the sign bit follows the code + pos += l + 1 + end + n += run + if n > 63 then + err = true + return false + end + local zz = readu8(scan, n) + -- dequantise the magnitude (ffmpeg's arithmetic); MPEG-1 makes it odd toward zero + local m + if intra then + m = (level * qs * readu8(q, zz)) // 16 + else + m = ((level * 2 + 1) * qs * readu8(q, zz)) // 32 + end + if not m2 then + if m == 0 then + m = -1 + elseif band(m, 1) == 0 then + m -= 1 + end + end + if neg then + m = -m + end + if m2 then + parityOdd = bxor(parityOdd, band(m, 1)) + end + -- saturation (13818-2 7.4.3) + if m > 2047 then + m = 2047 + elseif m < -2048 then + m = -2048 + end + if zz ~= 0 then + onlyDc = false + end + writei32(blk, zz * 4, m) + n += 1 + end + if m2 and parityOdd == 1 then + -- mismatch control: toggle the last coefficient's lowest bit + local v = readi32(blk, 252) + writei32(blk, 252, if v % 2 ~= 0 then v - 1 else v + 1) + onlyDc = false + end + local dst, off, stride + if luma then + dst = curY + if fieldPic then + stride = lstride + off = lbase + (mbRow * 16 + (if b >= 2 then 8 else 0)) * stride + mbCol * 16 + (if b % 2 == 1 then 8 else 0) + elseif dctType == 1 then + stride = 2 * cw + off = (mbRow * 16 + (if b >= 2 then 1 else 0)) * cw + mbCol * 16 + (if b % 2 == 1 then 8 else 0) + else + stride = cw + off = (mbRow * 16 + (if b >= 2 then 8 else 0)) * cw + mbCol * 16 + (if b % 2 == 1 then 8 else 0) + end + else + dst = curCr + if b % 2 == 0 then + dst = curCb + end + local k = (b - 4) // 2 -- the vertical chroma block of a 4:2:2 macroblock + if chroma == 1 then + stride = cstride + off = cbase + mbRow * 8 * stride + mbCol * 8 + elseif fieldPic then + stride = cstride + off = cbase + (mbRow * 16 + k * 8) * stride + mbCol * 8 + elseif dctType == 1 then + stride = 2 * chw + off = (mbRow * 16 + k) * chw + mbCol * 8 + else + stride = chw + off = (mbRow * 16 + k * 8) * chw + mbCol * 8 + end + end + if onlyDc then + fillBlock(dst, off, stride, (readi32(blk, 0) + 4) // 8, not intra) + writei32(blk, 0, 0) + else + idct(blk, dst, off, stride, not intra) + buffer.fill(blk, 0, 0, 256) + end + return true + end + + @native local function getQscale(code: number): number + if qScaleType == 1 then + return readu8(NON_LINEAR, code) + end + return code * 2 + end + + -- motion vectors of direction d (13818-2 7.6.3; MPEG-1: frame vectors, full_pel doubled) + @native local function motionVectors(d: number) + local fh, fv = fc10, fc11 + if d == 0 then + fh, fv = fc00, fc01 + end + local o, p, f = d * 8, d * 4, d * 2 + if motionType == 1 and not fieldPic then + local x = decodeMotion(fh, PMV[p + 1]) + local y = decodeMotion(fv, PMV[p + 2]) + PMV[p + 1], PMV[p + 3] = x, x + PMV[p + 2], PMV[p + 4] = y, y + if (d == 0 and fullPelFw) or (d == 1 and fullPelBw) then + x *= 2 + y *= 2 + end + MV[o + 1], MV[o + 2] = x, y + elseif motionType == 2 then + -- field prediction in a frame picture: vertical predictors in frame units + for r = 0, 1 do + FSEL[f + r + 1] = read(1) + local x = decodeMotion(fh, PMV[p + r * 2 + 1]) + local y = decodeMotion(fv, PMV[p + r * 2 + 2] // 2) + PMV[p + r * 2 + 1] = x + PMV[p + r * 2 + 2] = y * 2 + MV[o + r * 2 + 1], MV[o + r * 2 + 2] = x, y + end + elseif motionType == 1 then + -- field picture, 16x16 + FSEL[f + 1] = read(1) + local x = decodeMotion(fh, PMV[p + 1]) + local y = decodeMotion(fv, PMV[p + 2]) + PMV[p + 1], PMV[p + 3] = x, x + PMV[p + 2], PMV[p + 4] = y, y + MV[o + 1], MV[o + 2] = x, y + elseif motionType == 3 then + -- 16x8 (field pictures) + for r = 0, 1 do + FSEL[f + r + 1] = read(1) + local x = decodeMotion(fh, PMV[p + r * 2 + 1]) + local y = decodeMotion(fv, PMV[p + r * 2 + 2]) + PMV[p + r * 2 + 1], PMV[p + r * 2 + 2] = x, y + MV[o + r * 2 + 1], MV[o + r * 2 + 2] = x, y + end + else + -- dual prime + local shift = if fieldPic then 0 else 1 + local x = decodeMotion(fh, PMV[p + 1]) + local dmx = if read(1) == 1 then 1 - 2 * read(1) else 0 + local y = decodeMotion(fv, if shift == 1 then PMV[p + 2] // 2 else PMV[p + 2]) + local dmy = if read(1) == 1 then 1 - 2 * read(1) else 0 + PMV[p + 1], PMV[p + 3] = x, x + PMV[p + 2], PMV[p + 4] = y * (shift + 1), y * (shift + 1) + MV[o + 1], MV[o + 2], MV[o + 3], MV[o + 4] = x, y, x, y + -- the opposite-parity vectors: scaled by the field distance, rounded away from zero + local xp, yp = if x > 0 then 1 else 0, if y > 0 then 1 else 0 + if not fieldPic then + local m = if tff then 1 else 3 + MV[o + 5] = (x * m + xp) // 2 + dmx + MV[o + 6] = (y * m + yp) // 2 + dmy - 1 + m = 4 - m + MV[o + 7] = (x * m + xp) // 2 + dmx + MV[o + 8] = (y * m + yp) // 2 + dmy + 1 + else + MV[o + 5] = (x + xp) // 2 + dmx + MV[o + 6] = (y + yp) // 2 + dmy + (if parity == 0 then -1 else 1) + end + end + end + + @native local function decodeMacroblock(first: boolean, endBits: number): boolean + local inc = 0 + local t = vlc(MBAI, MBAI_BITS) + while t == 34 and not err and pos < endBits do -- stuffing + t = vlc(MBAI, MBAI_BITS) + end + while t == 35 and not err and pos < endBits do -- escape + inc += 33 + t = vlc(MBAI, MBAI_BITS) + end + if err or t < 1 or t > 33 then + err = true + return false + end + inc += t + if first then + mbAddr += inc + if mbAddr > covered and mbAddr <= mbSize then + conceal(covered, mbAddr - 1) + end + else + if mbAddr + inc >= mbSize then + err = true + return false + end + if inc > 1 then + if ptype == 1 then + err = true -- no skipped macroblocks in I pictures + return false + end + dcY, dcCb, dcCr = lshift(128, dcPrec), lshift(128, dcPrec), lshift(128, dcPrec) + skipMotion() + for _ = 2, inc do + mbAddr += 1 + mbRow = mbAddr // mbW + mbCol = mbAddr % mbW + predictMb() + end + end + mbAddr += 1 + end + if mbAddr < 0 or mbAddr >= mbSize then + err = true + return false + end + mbRow = mbAddr // mbW + mbCol = mbAddr % mbW + covered = mbAddr + 1 + + local mt = vlc(MBTYPE[ptype], MBTYPE_BITS[ptype]) + if err then + return false + end + mbIntra = band(mt, 1) ~= 0 + local pattern = band(mt, 2) ~= 0 + local fw = band(mt, 8) ~= 0 + local bw = band(mt, 4) ~= 0 + dctType = 0 + if mpeg2 then + if mbIntra or not (fw or bw) then + motionType = 1 + if not fieldPic and not fpfd and (mbIntra or pattern) then + dctType = read(1) + end + else + if not fieldPic and fpfd then + motionType = 1 + else + local mtc = read(2) + if fieldPic then + motionType = if mtc == 1 then 1 elseif mtc == 2 then 3 else 4 + else + motionType = if mtc == 1 then 2 elseif mtc == 2 then 1 else 4 + end + if mtc == 0 then + err = true + return false + end + if not fieldPic and pattern then + dctType = read(1) + end + end + end + else + motionType = 1 + end + if band(mt, 0x10) ~= 0 then + local code = read(5) + if code == 0 then + err = true + return false + end + qscale = getQscale(code) + end + if mbIntra then + if concealMv then + -- concealment vectors: parsed, kept as predictors + if fieldPic then + pos += 1 + end + local x = decodeMotion(fc00, PMV[1]) + local y = decodeMotion(fc01, PMV[2]) + PMV[1], PMV[3] = x, x + PMV[2], PMV[4] = y, y + pos += 1 -- marker + else + resetPmv() + end + else + dcY, dcCb, dcCr = lshift(128, dcPrec), lshift(128, dcPrec), lshift(128, dcPrec) + motFw = fw + motBw = bw + if fw then + motionVectors(0) + elseif ptype == 2 then + -- P without motion: a zero vector (field pictures: from the same parity) + resetPmv() + motFw = true + motionType = 1 + MV[1], MV[2] = 0, 0 + FSEL[1] = parity + end + if bw then + motionVectors(1) + end + if err then + return false + end + predictMb() + end + local nb = if chroma == 2 then 8 else 6 + local cbp + if pattern then + cbp = vlc(CBP, CBP_BITS) + if nb == 8 then + cbp = cbp * 4 + read(2) + end + if err then + return false + end + else + cbp = if mbIntra then lshift(1, nb) - 1 else 0 + end + if cbp ~= 0 then + for b = 0, nb - 1 do + if band(cbp, lshift(1, nb - 1 - b)) ~= 0 then + if not decodeBlock(b) then + return false + end + end + end + end + return pos <= endBits + end + + @native local function decodeSlice(row: number, endByte: number) + if mpeg2 and lumaH > 2800 then + row += lshift(read(3), 7) + end + if row > mbRows then + return + end + mbAddr = (row - 1) * mbW - 1 + resetPmv() + dcY, dcCb, dcCr = lshift(128, dcPrec), lshift(128, dcPrec), lshift(128, dcPrec) + motFw, motBw = false, false + local code = read(5) + local endBits = endByte * 8 + while read(1) == 1 and pos < endBits do + pos += 8 + end + if code == 0 then + return + end + qscale = getQscale(code) + local first = true + while true do + if not decodeMacroblock(first, endBits) then + state.errors += 1 + buffer.fill(blk, 0, 0, 256) -- a block may have stopped half decoded + break + end + first = false + -- the slice ends at a start code (byte aligned) or at the end of the picture data + local i = rshift(pos + 7, 3) + if i >= endByte then + break + end + if readu8(data, i) == 0 and readu8(data, i + 1) == 0 and readu8(data, i + 2) == 1 then + break + end + end + -- the motion state a gap after this slice repeats (B pictures) + if mbIntra then + gapFw, gapBw = false, false + else + gapFw, gapBw, gapType = motFw, motBw, motionType + table.move(MV, 1, 16, 1, GAP) + end + end + + -- the frame a picture completes becomes the newest reference (I / P) + @native local function finishFrame(s: Store) + if s.ptype ~= 3 then + state.refOld = state.refNew + state.refNew = s + end + end + + -- the picture header (after 00 00 01 00) and its extensions + @native local function pictureHeader(p: number, stop: number): (number?, number) + pos = p * 8 + local tref = read(10) + ptype = read(3) + pos += 16 -- vbv_delay + if ptype < 1 or ptype > 3 then + state.skipped += 1 -- D pictures and invalid types + return nil, 0 + end + fullPelFw, fullPelBw = false, false + if ptype >= 2 then + fullPelFw = read(1) == 1 + local c = read(3) + if c == 0 then + state.skipped += 1 + return nil, 0 + end + fc00, fc01 = c, c + end + if ptype == 3 then + fullPelBw = read(1) == 1 + local c = read(3) + if c == 0 then + state.skipped += 1 + return nil, 0 + end + fc10, fc11 = c, c + end + -- MPEG-1 semantics unless a picture coding extension follows + dcPrec, picStruct, fpfd, concealMv, qScaleType, intraVlc, scan = 0, 3, true, false, 0, false, ZZ + tff, rff, progFrame = true, false, true + err = false + local at = findStart(rshift(pos + 7, 3), stop) + while at >= 0 do + local code = readu8(data, at + 3) + if code == 0xB5 then + extension(at + 4) + elseif code ~= 0xB2 then + break + end + at = findStart(at + 4, stop) + end + if mpeg2 then + fullPelFw, fullPelBw = false, false + end + if err then + state.errors += 1 + err = false + end + return at, tref + end + + @native local function selectTarget(tref: number, tag: any): boolean + fieldPic = picStruct ~= 3 + parity = if picStruct == 2 then 1 else 0 + secondField = false + local target: Store + if fieldPic and pending and pendingStruct ~= picStruct then + secondField = true + target = pending :: Store + fwS, bwS = pendingFw, pendingBw + if ptype == 3 and (fwS == nil or bwS == nil) then + state.skipped += 1 + return false + end + else + if pending then + -- an unpaired field: its frame is done as it is + finishFrame(pending :: Store) + pending = nil + end + local refOld, refNew = state.refOld, state.refNew + if ptype == 1 then + target = if stores[1] == refNew then stores[2] else stores[1] + fwS, bwS = refNew, nil + elseif ptype == 2 then + if refNew == nil and not fieldPic then + state.skipped += 1 + return false + end + target = if stores[1] == refNew then stores[2] else stores[1] + fwS, bwS = refNew, nil + else + if refOld == nil or refNew == nil or bStore == nil then + state.skipped += 1 + return false + end + target = bStore :: Store + fwS, bwS = refOld, refNew + end + target.ptype = ptype + target.tref = tref + target.tag = tag + target.mpeg2 = mpeg2 + target.progressive = progFrame + target.fields = fieldPic + target.tff = if fieldPic then picStruct == 1 else tff + target.rff = rff + target.clamped = 0 + target.concealed = {} + end + cur = target + return true + end + + @native local function setAddressing() + local target = cur :: Store + curY, curCb, curCr = target.y, target.cb, target.cr + if fieldPic then + mbRows = mbH // 2 + lstride, lbase = 2 * cw, parity * cw + cstride, cbase = 2 * chw, parity * chw + else + mbRows = mbH + lstride, lbase = cw, 0 + cstride, cbase = chw, 0 + end + mbSize = mbW * mbRows + covered = 0 + hasRef = fwS ~= nil + gapFw, gapBw = false, false + mbIntra = false + end + + @native local function decodePicture(p: number, stop: number, tag: any): Store? + local first, tref = pictureHeader(p, stop) + if first == nil or not selectTarget(tref, tag) then + return nil + end + setAddressing() + local at = first :: number + while at >= 0 do + local code = readu8(data, at + 3) + if code >= 0x01 and code <= 0xAF then + pos = (at + 4) * 8 + err = false + decodeSlice(code, stop) + local hook = yieldHook + if hook then + -- the hook may suspend this coroutine: the picture state is all upvalues of this core + pcall(hook) + end + local nb = rshift(pos + 7, 3) + if nb >= stop then + break + end + at = findStart(nb, stop) + elseif code == 0xB2 or code == 0xB5 then + at = findStart(at + 4, stop) + else + break + end + end + conceal(covered, mbSize - 1) + state.pictures += 1 + local target = cur :: Store + if fieldPic and not secondField then + pending = target + pendingStruct = picStruct + pendingFw, pendingBw = fwS, bwS + return nil + end + pending = nil + finishFrame(target) + return target + end + + local core = {} :: Core + core.state = state + + @native function core.write(src: buffer, off: number, n: number) + if n <= 0 then + return + end + if readByte > 0 then + local keep = dataLen - readByte + if keep > 0 then + buffer.copy(data, 0, data, readByte, keep) + end + scanPos = math.max(0, scanPos - readByte) + dataLen = keep + readByte = 0 + end + local need = dataLen + n + PAD + if need > buffer.len(data) then + local cap = buffer.len(data) + while cap < need do + cap *= 2 + end + local nb = buffer.create(cap) + buffer.copy(nb, 0, data, 0, dataLen) + data = nb + end + buffer.copy(data, dataLen, src, off, n) + dataLen += n + buffer.fill(data, dataLen, 0, PAD) + end + + @native local function sequenceUnit(at: number, stop: number) + local ok = sequenceHeader(at + 4) + local s = findStart(at + 4, stop) + while s >= 0 do + if readu8(data, s + 3) == 0xB5 then + extension(s + 4) + end + s = findStart(s + 4, stop) + end + if not ok or not applySequence() then + state.errors += 1 + end + end + + @native function core.nextPicture(atEnd: boolean, tag: any): (Store?, boolean) + while true do + local at = findStart(readByte, dataLen) + if at < 0 then + -- keep the last 3 bytes: a start code may straddle the next write + readByte = math.max(readByte, dataLen - 3) + if atEnd then + readByte = dataLen + end + return nil, true + end + local code = readu8(data, at + 3) + if code == 0xB3 or code == 0x00 then + -- a unit is complete when the next unit start (or the end of the data) follows it + local stop = dataLen + do + local s = findStart(math.max(at + 4, scanPos), dataLen) + while s >= 0 do + local c = readu8(data, s + 3) + if c == 0x00 or c == 0xB3 or c == 0xB7 or c == 0xB8 then + break + end + s = findStart(s + 4, dataLen) + end + if s < 0 then + if not atEnd then + scanPos = math.max(at + 4, dataLen - 3) + readByte = at + return nil, true + end + else + stop = s + end + end + scanPos = 0 + readByte = stop + if code == 0xB3 then + sequenceUnit(at, stop) + elseif hasSeq then + local s = decodePicture(at + 4, stop, tag) + if s then + return s, false + end + else + state.skipped += 1 + end + else + readByte = at + 4 -- GOP header, sequence end, user data, stray slices + end + end + end + + @native function core.toRgba(s: Store, out: buffer) + if s.chroma == 2 then + toRgba422(s.y, s.cb, s.cr, s.cw, s.w, s.h, out) + else + toRgba(s.y, s.cb, s.cr, s.cw, s.w, s.h, out, 0, s.h, 0, yieldHook) + end + end + + @native function core.setYield(hook: (() -> ())?) + yieldHook = hook + end + + @native function core.reset() + dataLen = 0 + readByte = 0 + scanPos = 0 + state.refOld = nil + state.refNew = nil + pending = nil + end + + return core +end + +return D +end +__FILES["codecs/video/Mpeg2/Tables"] = function() + +-- codecs/video/Mpeg2/Tables: MPEG-1 / MPEG-2 video constant tables. +-- MPEG-1: jsmpeg's (https://github.com/phoboslab/jsmpeg, Dominic Szablewski, MIT, licenses/jsmpeg-MIT.txt), 0-based, via +-- mpeg1-luau e2e2898. MPEG-2 (DC sizes to 11, B-15, non-linear quantiser scale, alternate scan): ISO/IEC 13818-2 annex B / 7. +local T = {} +T.PICTURE_RATE = { [0] = 0.0, + 23.976, 24.0, 25.0, 29.97, 30.0, 50.0, 59.94, 60.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, +} +T.ZIG_ZAG = { [0] = 0, + 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, + 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, + 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63, +} +T.DEFAULT_INTRA_QUANT_MATRIX = { [0] = 8, + 16, 19, 22, 26, 27, 29, 34, 16, 16, 22, 24, 27, 29, 34, 37, 19, 22, 26, 27, 29, 34, 34, 38, 22, + 22, 26, 27, 29, 34, 37, 40, 22, 26, 27, 29, 32, 35, 40, 48, 26, 27, 29, 32, 35, 40, 48, 58, 26, + 27, 29, 34, 38, 46, 56, 69, 27, 29, 35, 38, 46, 56, 69, 83, +} +T.DEFAULT_NON_INTRA_QUANT_MATRIX = { [0] = 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, +} +T.MACROBLOCK_ADDRESS_INCREMENT = { [0] = 3, + 6, 0, 9, 12, 0, 0, 0, 1, 15, 18, 0, 21, 24, 0, 27, 30, 0, 33, 36, 0, 0, 0, 3, 0, + 0, 2, 39, 42, 0, 45, 48, 0, 0, 0, 5, 0, 0, 4, 51, 54, 0, 57, 60, 0, 0, 0, 7, 0, + 0, 6, 63, 66, 0, 69, 72, 0, 75, 78, 0, 81, 84, 0, -1, 87, 0, -1, 90, 0, 93, 96, 0, 99, + 102, 0, 105, 108, 0, 111, 114, 0, 0, 0, 9, 0, 0, 8, 117, 120, 0, 123, 126, 0, 129, 132, 0, 135, + 138, 0, 0, 0, 15, 0, 0, 14, 0, 0, 13, 0, 0, 12, 0, 0, 11, 0, 0, 10, 141, -1, 0, -1, + 144, 0, 147, 150, 0, 153, 156, 0, 159, 162, 0, 165, 168, 0, 171, 174, 0, 177, 180, 0, 183, -1, 0, -1, + 186, 0, 189, 192, 0, 195, 198, 0, 201, 204, 0, 207, 210, 0, 213, 216, 0, 219, 222, 0, 0, 0, 21, 0, + 0, 20, 0, 0, 19, 0, 0, 18, 0, 0, 17, 0, 0, 16, 0, 0, 35, 0, 0, 34, 0, 0, 33, 0, + 0, 32, 0, 0, 31, 0, 0, 30, 0, 0, 29, 0, 0, 28, 0, 0, 27, 0, 0, 26, 0, 0, 25, 0, + 0, 24, 0, 0, 23, 0, 0, 22, +} +T.MACROBLOCK_TYPE_INTRA = { [0] = 3, + 6, 0, -1, 9, 0, 0, 0, 1, 0, 0, 17, +} +T.MACROBLOCK_TYPE_PREDICTIVE = { [0] = 3, + 6, 0, 9, 12, 0, 0, 0, 10, 15, 18, 0, 0, 0, 2, 21, 24, 0, 0, 0, 8, 27, 30, 0, 33, + 36, 0, -1, 39, 0, 0, 0, 18, 0, 0, 26, 0, 0, 1, 0, 0, 17, +} +T.MACROBLOCK_TYPE_B = { [0] = 3, + 6, 0, 9, 15, 0, 12, 18, 0, 24, 21, 0, 0, 0, 12, 27, 30, 0, 0, 0, 14, 39, 42, 0, 36, + 33, 0, 0, 0, 4, 0, 0, 6, 54, 48, 0, 45, 51, 0, 0, 0, 8, 0, 0, 10, -1, 57, 0, 0, + 0, 1, 60, 63, 0, 0, 0, 30, 0, 0, 17, 0, 0, 22, 0, 0, 26, +} +T.CODE_BLOCK_PATTERN = { [0] = 6, + 3, 0, 9, 18, 0, 12, 15, 0, 24, 33, 0, 36, 39, 0, 27, 21, 0, 30, 42, 0, 60, 57, 0, 54, + 48, 0, 69, 51, 0, 81, 75, 0, 63, 84, 0, 45, 66, 0, 72, 78, 0, 0, 0, 60, 105, 120, 0, 132, + 144, 0, 114, 108, 0, 126, 141, 0, 87, 93, 0, 117, 96, 0, 0, 0, 32, 135, 138, 0, 99, 123, 0, 129, + 102, 0, 0, 0, 4, 90, 111, 0, 0, 0, 8, 0, 0, 16, 0, 0, 44, 150, 168, 0, 0, 0, 28, 0, + 0, 52, 0, 0, 62, 183, 177, 0, 156, 180, 0, 0, 0, 1, 165, 162, 0, 0, 0, 61, 0, 0, 56, 171, + 174, 0, 0, 0, 2, 0, 0, 40, 153, 186, 0, 0, 0, 48, 192, 189, 0, 147, 159, 0, 0, 0, 20, 0, + 0, 12, 240, 249, 0, 0, 0, 63, 231, 225, 0, 195, 219, 0, 252, 198, 0, 0, 0, 24, 0, 0, 36, 0, + 0, 3, 207, 261, 0, 243, 237, 0, 204, 213, 0, 210, 234, 0, 201, 228, 0, 216, 222, 0, 258, 255, 0, 264, + 246, 0, -1, 282, 0, 285, 291, 0, 0, 0, 33, 0, 0, 9, 318, 330, 0, 306, 348, 0, 0, 0, 5, 0, + 0, 10, 279, 267, 0, 0, 0, 6, 0, 0, 18, 0, 0, 17, 0, 0, 34, 339, 357, 0, 309, 312, 0, 270, + 276, 0, 327, 321, 0, 351, 354, 0, 303, 297, 0, 294, 288, 0, 300, 273, 0, 342, 345, 0, 315, 324, 0, 336, + 333, 0, 363, 375, 0, 0, 0, 41, 0, 0, 14, 0, 0, 21, 372, 366, 0, 360, 369, 0, 0, 0, 11, 0, + 0, 19, 0, 0, 7, 0, 0, 35, 0, 0, 13, 0, 0, 50, 0, 0, 49, 0, 0, 58, 0, 0, 37, 0, + 0, 25, 0, 0, 45, 0, 0, 57, 0, 0, 26, 0, 0, 29, 0, 0, 38, 0, 0, 53, 0, 0, 23, 0, + 0, 43, 0, 0, 46, 0, 0, 42, 0, 0, 22, 0, 0, 54, 0, 0, 51, 0, 0, 15, 0, 0, 30, 0, + 0, 39, 0, 0, 47, 0, 0, 55, 0, 0, 27, 0, 0, 59, 0, 0, 31, +} +T.MOTION = { [0] = 3, + 6, 0, 12, 9, 0, 0, 0, 0, 18, 15, 0, 24, 21, 0, 0, 0, -1, 0, 0, 1, 27, 30, 0, 36, + 33, 0, 0, 0, 2, 0, 0, -2, 42, 45, 0, 48, 39, 0, 60, 54, 0, 0, 0, 3, 0, 0, -3, 51, + 57, 0, -1, 69, 0, 81, 75, 0, 78, 63, 0, 72, 66, 0, 96, 84, 0, 87, 93, 0, -1, 99, 0, 108, + 105, 0, 0, 0, -4, 90, 102, 0, 0, 0, 4, 0, 0, -7, 0, 0, 5, 111, 123, 0, 0, 0, -5, 0, + 0, 7, 114, 120, 0, 126, 117, 0, 0, 0, -6, 0, 0, 6, 153, 162, 0, 150, 147, 0, 135, 138, 0, 156, + 141, 0, 129, 159, 0, 132, 144, 0, 0, 0, 10, 0, 0, 9, 0, 0, 8, 0, 0, -8, 171, 198, 0, 0, + 0, -9, 180, 192, 0, 168, 183, 0, 165, 186, 0, 174, 189, 0, 0, 0, -10, 177, 195, 0, 0, 0, 12, 0, + 0, 16, 0, 0, 13, 0, 0, 14, 0, 0, 11, 0, 0, 15, 0, 0, -16, 0, 0, -12, 0, 0, -14, 0, + 0, -15, 0, 0, -11, 0, 0, -13, +} +T.DCT_COEFF = { [0] = 3, + 6, 0, 12, 9, 0, 0, 0, 1, 21, 24, 0, 18, 15, 0, 39, 27, 0, 33, 30, 0, 42, 36, 0, 0, + 0, 257, 60, 66, 0, 54, 63, 0, 48, 57, 0, 0, 0, 513, 51, 45, 0, 0, 0, 2, 0, 0, 3, 81, + 75, 0, 87, 93, 0, 72, 78, 0, 96, 90, 0, 0, 0, 1025, 69, 84, 0, 0, 0, 769, 0, 0, 258, 0, + 0, 1793, 0, 0, 65535, 0, 0, 1537, 111, 108, 0, 0, 0, 1281, 105, 102, 0, 117, 114, 0, 99, 126, 0, 120, + 123, 0, 156, 150, 0, 162, 159, 0, 144, 147, 0, 129, 135, 0, 138, 132, 0, 0, 0, 2049, 0, 0, 4, 0, + 0, 514, 0, 0, 2305, 153, 141, 0, 165, 171, 0, 180, 168, 0, 177, 174, 0, 183, 186, 0, 0, 0, 2561, 0, + 0, 3329, 0, 0, 6, 0, 0, 259, 0, 0, 5, 0, 0, 770, 0, 0, 2817, 0, 0, 3073, 228, 225, 0, 201, + 210, 0, 219, 213, 0, 234, 222, 0, 216, 231, 0, 207, 192, 0, 204, 189, 0, 198, 195, 0, 243, 261, 0, 273, + 240, 0, 246, 237, 0, 249, 258, 0, 279, 276, 0, 252, 255, 0, 270, 282, 0, 264, 267, 0, 0, 0, 515, 0, + 0, 260, 0, 0, 7, 0, 0, 1026, 0, 0, 1282, 0, 0, 4097, 0, 0, 3841, 0, 0, 3585, 315, 321, 0, 333, + 342, 0, 312, 291, 0, 375, 357, 0, 288, 294, 0, -1, 369, 0, 285, 303, 0, 318, 363, 0, 297, 306, 0, 339, + 309, 0, 336, 348, 0, 330, 300, 0, 372, 345, 0, 351, 366, 0, 327, 354, 0, 360, 324, 0, 381, 408, 0, 417, + 420, 0, 390, 378, 0, 435, 438, 0, 384, 387, 0, 0, 0, 2050, 396, 402, 0, 465, 462, 0, 0, 0, 8, 411, + 399, 0, 429, 432, 0, 453, 414, 0, 426, 423, 0, 0, 0, 10, 0, 0, 9, 0, 0, 11, 0, 0, 5377, 0, + 0, 1538, 0, 0, 771, 0, 0, 5121, 0, 0, 1794, 0, 0, 4353, 0, 0, 4609, 0, 0, 4865, 444, 456, 0, 0, + 0, 1027, 459, 450, 0, 0, 0, 261, 393, 405, 0, 0, 0, 516, 447, 441, 0, 516, 519, 0, 486, 474, 0, 510, + 483, 0, 504, 498, 0, 471, 537, 0, 507, 501, 0, 522, 513, 0, 534, 531, 0, 468, 477, 0, 492, 495, 0, 549, + 546, 0, 525, 528, 0, 0, 0, 263, 0, 0, 2562, 0, 0, 2306, 0, 0, 5633, 0, 0, 5889, 0, 0, 6401, 0, + 0, 6145, 0, 0, 1283, 0, 0, 772, 0, 0, 13, 0, 0, 12, 0, 0, 14, 0, 0, 15, 0, 0, 517, 0, + 0, 6657, 0, 0, 262, 540, 543, 0, 480, 489, 0, 588, 597, 0, 0, 0, 27, 609, 555, 0, 606, 603, 0, 0, + 0, 19, 0, 0, 22, 591, 621, 0, 0, 0, 18, 573, 576, 0, 564, 570, 0, 0, 0, 20, 552, 582, 0, 0, + 0, 21, 558, 579, 0, 0, 0, 23, 612, 594, 0, 0, 0, 25, 0, 0, 24, 600, 615, 0, 0, 0, 31, 0, + 0, 30, 0, 0, 28, 0, 0, 29, 0, 0, 26, 0, 0, 17, 0, 0, 16, 567, 618, 0, 561, 585, 0, 654, + 633, 0, 0, 0, 37, 645, 648, 0, 0, 0, 36, 630, 636, 0, 0, 0, 34, 639, 627, 0, 663, 666, 0, 657, + 624, 0, 651, 642, 0, 669, 660, 0, 0, 0, 35, 0, 0, 267, 0, 0, 40, 0, 0, 268, 0, 0, 266, 0, + 0, 32, 0, 0, 264, 0, 0, 265, 0, 0, 38, 0, 0, 269, 0, 0, 270, 0, 0, 33, 0, 0, 39, 0, + 0, 7937, 0, 0, 6913, 0, 0, 7681, 0, 0, 4098, 0, 0, 7425, 0, 0, 7169, 0, 0, 271, 0, 0, 274, 0, + 0, 273, 0, 0, 272, 0, 0, 1539, 0, 0, 2818, 0, 0, 3586, 0, 0, 3330, 0, 0, 3074, 0, 0, 3842, +} +-- dct_dc_size_luminance / chrominance (Tables B-12 / B-13, sizes 0..11): { code, length } per size +T.DC_SIZE_LUMA = { { 4, 3 }, { 0, 2 }, { 1, 2 }, { 5, 3 }, { 6, 3 }, { 14, 4 }, { 30, 5 }, { 62, 6 }, { 126, 7 }, { 254, 8 }, { 510, 9 }, { 511, 9 } } +T.DC_SIZE_CHROMA = { { 0, 2 }, { 1, 2 }, { 2, 2 }, { 6, 3 }, { 14, 4 }, { 30, 5 }, { 62, 6 }, { 126, 7 }, { 254, 8 }, { 510, 9 }, { 1022, 10 }, { 1023, 10 } } +-- Table B-15 (intra_vlc_format = 1), ISO/IEC 13818-2: { code, length, run * 256 + level } (the sign bit follows) +T.DCT_COEFF_B15 = { + 2,2,1, 6,3,2, 7,4,3, 28,5,4, 29,5,5, 5,6,6, 4,6,7, 123,7,8, + 124,7,9, 35,8,10, 34,8,11, 250,8,12, 251,8,13, 254,8,14, 255,8,15, 31,14,16, + 30,14,17, 29,14,18, 28,14,19, 27,14,20, 26,14,21, 25,14,22, 24,14,23, 23,14,24, + 22,14,25, 21,14,26, 20,14,27, 19,14,28, 18,14,29, 17,14,30, 16,14,31, 24,15,32, + 23,15,33, 22,15,34, 21,15,35, 20,15,36, 19,15,37, 18,15,38, 17,15,39, 16,15,40, + 2,3,257, 6,5,258, 121,7,259, 39,8,260, 32,8,261, 22,13,262, 21,13,263, 31,15,264, + 30,15,265, 29,15,266, 28,15,267, 27,15,268, 26,15,269, 25,15,270, 19,16,271, 18,16,272, + 17,16,273, 16,16,274, 5,5,513, 7,7,514, 252,8,515, 12,10,516, 20,13,517, 7,5,769, + 38,8,770, 28,12,771, 19,13,772, 6,6,1025, 253,8,1026, 18,12,1027, 7,6,1281, 4,9,1282, + 18,13,1283, 6,7,1537, 30,12,1538, 20,16,1539, 4,7,1793, 21,12,1794, 5,7,2049, 17,12,2050, + 120,7,2305, 17,13,2306, 122,7,2561, 16,13,2562, 33,8,2817, 26,16,2818, 37,8,3073, 25,16,3074, + 36,8,3329, 24,16,3330, 5,9,3585, 23,16,3586, 7,9,3841, 22,16,3842, 13,10,4097, 21,16,4098, + 31,12,4353, 26,12,4609, 25,12,4865, 23,12,5121, 22,12,5377, 31,13,5633, 30,13,5889, 29,13,6145, + 28,13,6401, 27,13,6657, 31,16,6913, 30,16,7169, 29,16,7425, 28,16,7681, 27,16,7937, +} +-- quantiser_scale for q_scale_type = 1 (Table 7-6), indexed by quantiser_scale_code +T.NON_LINEAR_QSCALE = { [0] = 0, + 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 18, 20, 22, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64, 72, 80, 88, 96, 104, 112, +} +-- the alternate scan (Figure 7-3): scan index -> natural position +T.ALTERNATE_SCAN = { [0] = 0, + 8, 16, 24, 1, 9, 2, 10, 17, 25, 32, 40, 48, 56, 57, 49, 41, 33, 26, 18, 3, 11, 4, 12, 19, 27, 34, 42, 50, 58, + 35, 43, 51, 59, 20, 28, 5, 13, 6, 14, 21, 29, 36, 44, 52, 60, 37, 45, 53, 61, 22, 30, 7, 15, 23, 31, 38, 46, + 54, 62, 39, 47, 55, 63, +} +return T +end +__FILES["codecs/video/Mpeg2/Vlc"] = function() + +-- codecs/video/Mpeg2/Vlc: lookup tables for the MPEG-1 / MPEG-2 variable-length codes, built at load time (Tables.luau). +-- Flat: indexed by the next K bits, len * 65536 + (value + 32768), len 0 = invalid. DCT: two-level (8 + 8 bits), +-- len * 65536 + run * 256 + level, ESC = 0xFFFF, EOB = 0xFFFE, or SUB + subtable for a long-code prefix. +-- DCT_NEXT: "10" = end_of_block, "11" = run 0 / level 1 (jsmpeg reads "1" + one bit); DCT_FIRST: "1" = run 0 / level 1. +local T = __include("codecs/video/Mpeg2/Tables") + +local V = {} + +type Leaf = { code: number, len: number, value: number } + +local function leaves(tree: { [number]: number }): { Leaf } + local out: { Leaf } = {} + local function walk(state: number, code: number, len: number) + if tree[state] == 0 and len > 0 then + table.insert(out, { code = code, len = len, value = tree[state + 2] }) + return + end + for bit = 0, 1 do + local nxt = tree[state + bit] + if nxt ~= nil and nxt > 0 then + walk(nxt, code * 2 + bit, len + 1) + end + end + end + walk(0, 0, 0) + return out +end + +local function flatLeaves(ls: { Leaf }): (buffer, number) + local k = 0 + for _, l in ls do + k = math.max(k, l.len) + end + local lut = buffer.create(4 * 2 ^ k) + for _, l in ls do + local shift = k - l.len + local first = l.code * 2 ^ shift + for i = first, first + 2 ^ shift - 1 do + buffer.writeu32(lut, i * 4, l.len * 65536 + l.value + 32768) + end + end + return lut, k +end + +local function flat(tree: { [number]: number }): (buffer, number) + return flatLeaves(leaves(tree)) +end + +local function codeLeaves(codes: { { number } }): { Leaf } + local out: { Leaf } = {} + for i, c in codes do + table.insert(out, { code = c[1], len = c[2], value = i - 1 }) + end + return out +end + +V.SUB = 0x1000000 +V.ESC = 0xFFFF +V.EOB = 0xFFFE + +local function twoLevel(ls: { Leaf }): buffer + local subs: { [number]: number } = {} + local nsub = 0 + for _, l in ls do + if l.len > 8 then + local prefix = l.code // 2 ^ (l.len - 8) + if subs[prefix] == nil then + nsub += 1 + subs[prefix] = nsub + end + end + end + local lut = buffer.create(4 * 256 * (1 + nsub)) + for _, l in ls do + if l.len <= 8 then + local shift = 8 - l.len + local first = l.code * 2 ^ shift + for i = first, first + 2 ^ shift - 1 do + buffer.writeu32(lut, i * 4, l.len * 65536 + l.value) + end + else + local prefix = l.code // 2 ^ (l.len - 8) + local s = subs[prefix] + buffer.writeu32(lut, prefix * 4, V.SUB + s) + local rest = l.code % 2 ^ (l.len - 8) + local shift = 16 - l.len + local first = rest * 2 ^ shift + for i = first, first + 2 ^ shift - 1 do + buffer.writeu32(lut, (s * 256 + i) * 4, l.len * 65536 + l.value) + end + end + end + return lut +end + +V.MBAI, V.MBAI_BITS = flat(T.MACROBLOCK_ADDRESS_INCREMENT) -- 34 = stuffing, 35 = escape +V.MBTYPE_I, V.MBTYPE_I_BITS = flat(T.MACROBLOCK_TYPE_INTRA) +V.MBTYPE_P, V.MBTYPE_P_BITS = flat(T.MACROBLOCK_TYPE_PREDICTIVE) +V.MBTYPE_B, V.MBTYPE_B_BITS = flat(T.MACROBLOCK_TYPE_B) +do + -- MPEG-2 adds "0000 0000 1" = 0 (Table B-9: a 4:2:2 macroblock whose coded blocks are all in the extra chroma + -- pattern bits) + local ls = leaves(T.CODE_BLOCK_PATTERN) + table.insert(ls, { code = 1, len = 9, value = 0 }) + V.CBP, V.CBP_BITS = flatLeaves(ls) +end +V.MOTION, V.MOTION_BITS = flat(T.MOTION) +V.DC_LUMA, V.DC_LUMA_BITS = flatLeaves(codeLeaves(T.DC_SIZE_LUMA)) +V.DC_CHROMA, V.DC_CHROMA_BITS = flatLeaves(codeLeaves(T.DC_SIZE_CHROMA)) + +do + local ls = leaves(T.DCT_COEFF) + V.DCT_FIRST = twoLevel(ls) + local nextLs: { Leaf } = {} + for _, l in ls do + if l.len == 1 and l.code == 1 then + table.insert(nextLs, { code = 2, len = 2, value = V.EOB }) -- "10" + table.insert(nextLs, { code = 3, len = 2, value = 0x0001 }) -- "11" + else + table.insert(nextLs, l) + end + end + V.DCT_NEXT = twoLevel(nextLs) +end + +do + local ls: { Leaf } = { { code = 1, len = 6, value = V.ESC }, { code = 6, len = 4, value = V.EOB } } + local b = T.DCT_COEFF_B15 + for i = 1, #b, 3 do + table.insert(ls, { code = b[i], len = b[i + 1], value = b[i + 2] }) + end + V.DCT_B15 = twoLevel(ls) +end + +return V +end +end + + + + + + H263 + --!optimize 2 +--!nocheck +-- rosetta chunk H263 (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 3 modules (1 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["codecs/video/H263"] = function() + +-- codecs/video/H263: an H.263 / H.263+ and Sorenson Spark (FLV1) video decoder, bit-exact with ffmpeg -idct int. +-- From ITU-T H.263 (01/2005) and Adobe's Video File Format Specification v10. Annex D UMV, GOB headers and Sorenson +-- escapes are supported; arithmetic coding, advanced prediction, PB / B / EI / EP and other H.263+ options are not. +local Err = __include("core/Err") +local Types = __include("Types") +local D = __include("codecs/video/H263/Decoder") + +local H263 = {} + +H263.PICTURE_I = 1 +H263.PICTURE_P = 2 + +type Header = D.Header + +type Frame = { + width: number, + height: number, + y: buffer, + cb: buffer, + cr: buffer, + stride: number, + pictureType: number, -- 1 I, 2 P + keyframe: boolean, + disposable: boolean, + temporalReference: number, + index: number, + flv: boolean, +} + +type Options = { + flv: boolean?, + maxPixels: number?, +} + +local Decoder = {} +Decoder.__index = Decoder + +type Decoder = typeof(setmetatable({} :: { _core: D.Core, _flv: boolean, _count: number, stats: { pictures: number, errors: number } }, Decoder)) + +function H263.new(opts: Options?): Decoder + local o: Options = if type(opts) == "table" then opts else {} + local flv = o.flv == true + local maxPixels = if type(o.maxPixels) == "number" and o.maxPixels > 0 then o.maxPixels else nil + return setmetatable({ _core = D.new(flv, maxPixels), _flv = flv, _count = 0, stats = { pictures = 0, errors = 0 } }, Decoder) +end + +local function span(data: any, off: number?, len: number?): (buffer?, number, number) + local b: buffer + if type(data) == "string" then + b = buffer.fromstring(data) + elseif type(data) == "buffer" then + b = data + else + return nil, 0, 0 + end + local total = buffer.len(b) + local o = math.floor(tonumber(off) or 0) + if o < 0 or o > total then + return nil, 0, 0 + end + local n = math.floor(tonumber(len) or (total - o)) + if n < 0 or o + n > total then + return nil, 0, 0 + end + return b, o, n +end + +function Decoder.decode(self: Decoder, data: buffer | string, off: number?, len: number?): (Frame?, Err.Err?) + local b, o, n = span(data, off, len) + if not b then + return nil, Err.new(Err.ARG, "decode: expected a buffer or string and a valid range") + end + local core = self._core + local s, msg = core.decode(b, o, n) + self.stats.pictures = core.state.pictures + self.stats.errors = core.state.errors + if not s then + return nil, Err.from(msg or "bad picture") + end + self._count += 1 + return { + width = s.w, + height = s.h, + y = s.y, + cb = s.cb, + cr = s.cr, + stride = s.ls, + pictureType = s.ptype, + keyframe = s.ptype == 1, + disposable = s.disposable, + temporalReference = s.tr, + index = self._count, + flv = self._flv, + }, nil +end + +function Decoder.image(self: Decoder, data: buffer | string, off: number?, len: number?): (Types.Image?, Err.Err?) + local f, err = self:decode(data, off, len) + if not f then + return nil, err + end + return H263.frameImage(f), nil +end + +function Decoder.reset(self: Decoder) + self._core.reset() +end + +function H263.frameImage(frame: Frame): Types.Image? + if type(frame) ~= "table" or type(frame.y) ~= "buffer" or type(frame.cb) ~= "buffer" or type(frame.cr) ~= "buffer" then + return nil + end + local w, h, ls = frame.width, frame.height, frame.stride + if type(w) ~= "number" or type(h) ~= "number" or type(ls) ~= "number" or w < 1 or h < 1 or ls < w then + return nil + end + local cw, ch, cs = (w + 1) // 2, (h + 1) // 2, ls // 2 + if buffer.len(frame.y) < ls * h or buffer.len(frame.cb) < cs * ch or buffer.len(frame.cr) < cs * ch then + return nil + end + local img = Types.Image.new(w, h, "yuv420p") + local px = img.pixels + for y = 0, h - 1 do + buffer.copy(px, y * w, frame.y, y * ls, w) + end + local o = w * h + for y = 0, ch - 1 do + buffer.copy(px, o + y * cw, frame.cb, y * cs, cw) + buffer.copy(px, o + cw * ch + y * cw, frame.cr, y * cs, cw) + end + img.meta.yuv = { range = "limited", matrix = "bt601" } + img.meta.source = { + format = if frame.flv then "flv1" else "h263", + pictureType = frame.pictureType, + temporalReference = frame.temporalReference, + disposable = frame.disposable, + } + return img +end + +function H263.header(data: buffer | string, off: number?, len: number?, flv: boolean?): (Header?, Err.Err?) + local b, o, n = span(data, off, len) + if not b then + return nil, Err.new(Err.ARG, "header: expected a buffer or string and a valid range") + end + local h, msg = D.header(b, o, n, flv == true, nil) + if not h then + return nil, Err.from(msg or "bad picture header") + end + return h, nil +end + +return H263 +end +__FILES["codecs/video/H263/Decoder"] = @native function() + + + +-- codecs/video/H263/Decoder: the H.263 / Sorenson Spark decoding core, from ITU-T H.263 (01/2005) and Adobe's Video +-- File Format Specification v10 (H.263VIDEOPACKET). Dequantiser |REC| = QUANT * (2 |LEVEL| + 1), minus 1 for an even +-- QUANT; vectors outside the reference read repeated edge samples of the macroblock-aligned picture, as ffmpeg. +local Tb = __include("codecs/video/H263/Tables") +local Dsp = __include("codecs/video/Dsp") + +local readu8 = buffer.readu8 +local readu32 = buffer.readu32 +local readi32 = buffer.readi32 +local writei32 = buffer.writei32 +local bfill = buffer.fill +local band = bit32.band +local bor = bit32.bor +local lshift = bit32.lshift +local rshift = bit32.rshift +local bswap = bit32.byteswap +local idct = Dsp.idct +local fillBlock = Dsp.fill +local mc = Dsp.mc +local mcNoRound = Dsp.mcNoRound +local edge = Dsp.edge + +local MCBPC_I = Tb.MCBPC_I +local MCBPC_P = Tb.MCBPC_P +local CBPY = Tb.CBPY +local MVD = Tb.MVD +local TCOEF = Tb.TCOEF +local ZIGZAG = Tb.ZIGZAG +local DQUANT = Tb.DQUANT +local STUFFING = Tb.STUFFING +local ESCAPE = Tb.ESCAPE + +local PAD = 4096 -- zero bytes after the data: a macroblock reads at most ~2.5 KB, the end check runs per macroblock + +local D = {} + +D.PICTURE_I = 1 +D.PICTURE_P = 2 + +-- the PLUSPTYPE options that persist while UFEP = 0 +type Opp = { + format: number, + customPcf: boolean, + umv: boolean, + ss: boolean, -- slice structured (Annex K) + options: string?, + width: number, + height: number, +} + +type Header = { + flv: boolean, + version: number, -- Sorenson Spark: 0 (H.263 escapes) or 1 (7 / 11-bit escapes) + tr: number, -- temporal reference + width: number, + height: number, + ptype: number, -- 1 I, 2 P + disposable: boolean, -- Sorenson: a P picture nothing predicts from + quant: number, + umv: boolean, -- unrestricted vectors, baseline form (long vectors) + umvPlus: boolean, -- unrestricted vectors, PLUSPTYPE form + rounding: number, -- RTYPE (0: half-sample averages round up) + plus: boolean, + ss: boolean, -- slice structured (Annex K) + cpm: boolean, + deblock: boolean, -- Sorenson's deblocking hint (not applied, as ffmpeg) + aspect: number?, -- PLUSPTYPE pixel aspect ratio code (15: aspectNum / aspectDen) + aspectNum: number?, + aspectDen: number?, + opp: Opp?, + bitPos: number, +} + +type Store = { + y: buffer, + cb: buffer, + cr: buffer, + ls: number, -- luma stride (16 * macroblock columns); chroma stride ls / 2 + w: number, + h: number, + ptype: number, + tr: number, + disposable: boolean, +} + +-- the length of a slice's MBA field for a picture of n macroblocks (table K.2) +@native function D.mbaBits(n: number): number + return if n <= 48 then 6 elseif n <= 99 then 7 elseif n <= 396 then 9 elseif n <= 1584 then 11 elseif n <= 6336 then 13 else 14 +end + +@native local function bitsAt(buf: buffer, endByte: number, p: number, n: number): number + local v = 0 + for k = p, p + n - 1 do + local byte = rshift(k, 3) + local b = if byte < endByte then readu8(buf, byte) else 0 + v = v * 2 + band(rshift(b, 7 - band(k, 7)), 1) + end + return v +end + +-- picture start code: H.263 22 bits 0..01 00000; Sorenson 17 bits 0..01, then version 0 / 1 +@native local function findStart(buf: buffer, off: number, len: number, flv: boolean): number + local mask = if flv then 0xF8 else 0xFC + for i = off, off + len - 3 do + if readu8(buf, i) == 0 and readu8(buf, i + 1) == 0 and band(readu8(buf, i + 2), mask) == 0x80 then + return i + end + end + return -1 +end + +-- pictures with UFEP = 0 keep the previous picture's PLUSPTYPE options (opp) +@native function D.header(buf: buffer, off: number, len: number, flv: boolean, opp: Opp?): (Header?, string?) + if off < 0 or len < 0 or off + len > buffer.len(buf) then + return nil, "bad range" + end + local s = findStart(buf, off, len, flv) + if s < 0 then + return nil, "no picture start code" + end + local e = off + len + local p = s * 8 + @native local function bits(n: number): number + local v = bitsAt(buf, e, p, n) + p += n + return v + end + local h: Header = { + flv = flv, + version = 0, + tr = 0, + width = 0, + height = 0, + ptype = 1, + disposable = false, + quant = 1, + umv = false, + umvPlus = false, + rounding = 0, + plus = false, + ss = false, + cpm = false, + deblock = false, + bitPos = 0, + } + if flv then + bits(17) + h.version = bits(5) + h.tr = bits(8) + local size = bits(3) + if size == 0 then + h.width, h.height = bits(8), bits(8) + elseif size == 1 then + h.width, h.height = bits(16), bits(16) + elseif size <= 6 then + local d = Tb.FLV_SIZES[size] + h.width, h.height = d[1], d[2] + else + return nil, "reserved picture size" + end + local t = bits(2) + if t == 3 then + return nil, "reserved picture type" + end + h.ptype = if t == 0 then 1 else 2 + h.disposable = t == 2 + h.deblock = bits(1) == 1 + h.quant = bits(5) + else + bits(22) + h.tr = bits(8) + if bits(1) ~= 1 or bits(1) ~= 0 then + return nil, "bad PTYPE" + end + bits(3) -- split screen, document camera, freeze picture release + local format = bits(3) + if format >= 1 and format <= 5 then + local d = Tb.FORMATS[format] + h.width, h.height = d[1], d[2] + h.ptype = bits(1) + 1 + h.umv = bits(1) == 1 + local sac, ap, pb = bits(1), bits(1), bits(1) + if sac == 1 then + return nil, "unsupported: syntax-based arithmetic coding" + elseif ap == 1 then + return nil, "unsupported: advanced prediction mode" + elseif pb == 1 then + return nil, "unsupported: PB-frames" + end + h.quant = bits(5) + h.cpm = bits(1) == 1 + if h.cpm then + bits(2) + end + elseif format == 7 then + h.plus = true + local ufep = bits(3) + local o: Opp + if ufep == 1 then + local f = bits(3) + local pcf, umv = bits(1) == 1, bits(1) == 1 + local names: { string } = { "syntax-based arithmetic coding", "advanced prediction", "advanced intra coding", + "deblocking filter", "slice structure", "reference picture selection", "independent segment decoding", + "alternative inter VLC", "modified quantisation" } + local unsup: string? = nil + local ss = false + for i = 1, 9 do + if bits(1) == 1 then + if i == 5 then + ss = true + elseif not unsup then + unsup = names[i] + end + end + end + bits(4) -- 1 000 + o = { format = f, customPcf = pcf, umv = umv, ss = ss, options = unsup, width = 0, height = 0 } + elseif ufep == 0 and opp then + o = opp + else + return nil, if ufep == 0 then "PLUSPTYPE without the options (UFEP 0 first)" else "bad UFEP" + end + local t = bits(3) + if t ~= 0 and t ~= 1 then + return nil, "unsupported: " .. ({ "", "improved PB-frames", "B-pictures", "EI-pictures", "EP-pictures", "reserved", "reserved" })[t] .. " picture type" + end + h.ptype = t + 1 + local rpr, rru = bits(1), bits(1) + h.rounding = bits(1) + bits(3) -- 0 0 1 + if rpr == 1 then + return nil, "unsupported: reference picture resampling" + elseif rru == 1 then + return nil, "unsupported: reduced-resolution update" + end + local unsupported = o.options + if unsupported ~= nil then + return nil, "unsupported: " .. unsupported + end + h.cpm = bits(1) == 1 + if h.cpm then + bits(2) + end + if ufep == 1 then + if o.format == 6 then + local par = bits(4) + o.width = (bits(9) + 1) * 4 + bits(1) + o.height = bits(9) * 4 + h.aspect = par + if par == 15 then + h.aspectNum, h.aspectDen = bits(8), bits(8) + end + elseif o.format >= 1 and o.format <= 5 then + local d = Tb.FORMATS[o.format] + o.width, o.height = d[1], d[2] + else + return nil, "bad source format " .. o.format + end + if o.customPcf then + bits(8) -- clock conversion code, clock divisor + end + end + if o.customPcf then + bits(2) -- ETR + end + if ufep == 1 and o.umv then + if bits(1) == 0 then + bits(1) + end + end + if ufep == 1 and o.ss then + if bits(1) == 1 then + return nil, "unsupported: rectangular slices" + end + bits(1) -- arbitrary slice ordering (slices carry their address) + end + h.width, h.height = o.width, o.height + h.umvPlus = o.umv + h.ss = o.ss + h.opp = o + else + return nil, "bad source format " .. format + end + h.quant = if h.plus then bits(5) else h.quant + end + -- PEI / PSPARE + local guard = 0 + while bits(1) == 1 do + bits(8) + guard += 1 + if guard > 256 then + return nil, "PSPARE without end" + end + end + if h.quant == 0 then + return nil, "QUANT 0" + end + if h.width < 1 or h.height < 1 then + return nil, "empty picture size" + end + if h.ss then + -- the first slice's SEPB1, MBA and SEPB2 + bits(1) + bits(D.mbaBits((h.width + 15) // 16 * ((h.height + 15) // 16))) + bits(1) + end + if p > e * 8 then + return nil, "truncated picture header" + end + h.bitPos = p + return h, nil +end + +type Core = { + decode: (buf: buffer, off: number, len: number) -> (Store?, string?), + reset: () -> (), + state: { + width: number, + height: number, + pictures: number, + errors: number, + header: Header?, + opp: Opp?, + maxPixels: number, + }, +} + +@native function D.new(flv: boolean, maxPixels: number?): Core + local state = { + width = 0, + height = 0, + pictures = 0, + errors = 0, + header = nil :: Header?, + opp = nil :: Opp?, + maxPixels = maxPixels or 4096 * 2304, + } + local data = buffer.create(64 * 1024 + PAD) + local endBits = 0 + local pos = 0 + local err = false + local W, H = 0, 0 + local mbW, mbH = 0, 0 + local ls, cs, lh, chh = 0, 0, 0, 0 -- luma / chroma strides, plane heights + local stores: { Store } = {} + local ref: Store? = nil + local curY, curCb, curCr = data, data, data + local refY, refCb, refCr = data, data, data + local quant = 1 + local escFlv = false -- Sorenson version 1 escapes + local longMv = false + local umvPlus = false + local mcf = mc + local mvX, mvY = {} :: { number }, {} :: { number } -- the current row's vectors (half samples) + local upX, upY = {} :: { number }, {} :: { number } -- the row above + local blk = buffer.create(256) + local EDGE = buffer.create(Dsp.EDGE_SIZE) + + @native local function read(n: number): number + local bp = rshift(pos, 3) + local w = bswap(readu32(data, bp)) + local s = band(pos, 7) + if s ~= 0 then + w = bor(lshift(w, s), rshift(readu8(data, bp + 4), 8 - s)) + end + pos += n + return rshift(w, 32 - n) + end + + @native local function peek32(): number + local bp = rshift(pos, 3) + local w = bswap(readu32(data, bp)) + local s = band(pos, 7) + if s ~= 0 then + w = bor(lshift(w, s), rshift(readu8(data, bp + 4), 8 - s)) + end + return w + end + + @native local function vlc(lut: buffer, k: number): number + local e = readu32(lut, rshift(peek32(), 32 - k) * 4) + local l = rshift(e, 16) + if l == 0 then + err = true + return 0 + end + pos += l + return band(e, 0xFFFF) + end + + @native local function alloc(w: number, h: number) + W, H = w, h + mbW, mbH = (w + 15) // 16, (h + 15) // 16 + ls, cs, lh, chh = mbW * 16, mbW * 8, mbH * 16, mbH * 8 + stores = {} + for i = 1, 2 do + local y = buffer.create(ls * lh) + local cb = buffer.create(cs * chh) + local cr = buffer.create(cs * chh) + bfill(cb, 0, 128) + bfill(cr, 0, 128) + stores[i] = { y = y, cb = cb, cr = cr, ls = ls, w = w, h = h, ptype = 0, tr = 0, disposable = false } + end + mvX, mvY, upX, upY = table.create(mbW, 0), table.create(mbW, 0), table.create(mbW, 0), table.create(mbW, 0) + ref = nil + state.width, state.height = w, h + end + + -- intra blocks: INTRADC, then the coded coefficients from position 1 + @native local function block(intra: boolean, coded: boolean, dst: buffer, off: number, stride: number): boolean + local i = 0 + local dcOnly = true + if intra then + local v = read(8) + if v == 255 then + v = 128 + end + writei32(blk, 0, v * 8) + i = 1 + end + if coded then + local q2 = quant * 2 + local qadd = if quant % 2 == 1 then quant else quant - 1 + while true do + local bp = rshift(pos, 3) + local w = bswap(readu32(data, bp)) + local s = band(pos, 7) + if s ~= 0 then + w = bor(lshift(w, s), rshift(readu8(data, bp + 4), 8 - s)) + end + local e = readu32(TCOEF, rshift(w, 20) * 4) + local l = rshift(e, 16) + if l == 0 then + err = true + return false + end + local v = band(e, 0xFFFF) + local last, run, level + if v == ESCAPE then + -- the escape and the 25 (H.263) / 22 or 26 (Sorenson v1) bits after it, all inside w's next bits + if escFlv then + local is11 = band(rshift(w, 24), 1) + last = band(rshift(w, 23), 1) + run = band(rshift(w, 17), 63) + if is11 == 1 then + level = band(rshift(w, 6), 2047) + if level >= 1024 then + level -= 2048 + end + pos += 7 + 1 + 7 + 11 + else + level = band(rshift(w, 10), 127) + if level >= 64 then + level -= 128 + end + pos += 7 + 1 + 7 + 7 + end + else + last = band(rshift(w, 24), 1) + run = band(rshift(w, 18), 63) + level = band(rshift(w, 10), 255) + pos += 7 + 1 + 6 + 8 + if level == 128 then + -- the extended escape (Annex T): 5 low bits, then 6 signed high bits + local x = read(11) + level = band(x, 31) + (rshift(x, 5) - (if x >= 1024 then 64 else 0)) * 32 + elseif level > 128 then + level -= 256 + end + end + if level == 0 then + err = true + return false + end + else + last = rshift(v, 10) + run = band(rshift(v, 4), 63) + level = band(v, 15) + if band(w, lshift(1, 31 - l)) ~= 0 then + level = -level + end + pos += l + 1 + end + i += run + if i > 63 then + err = true + return false + end + local rec = if level > 0 then level * q2 + qadd else level * q2 - qadd + -- not the -2048..2047 saturation of H.263 6.2.1: ffmpeg does not saturate, and encoders write values + -- slightly past it (2055 = 68 * 30 + 15). +-2400 bounds the IDCT output to Dsp's clamp table. + if rec > 2400 then + rec = 2400 + elseif rec < -2400 then + rec = -2400 + end + local z = readu8(ZIGZAG, i) + if z ~= 0 then + dcOnly = false + end + writei32(blk, z * 4, rec) + i += 1 + if last ~= 0 then + break + end + end + elseif not intra then + return true + end + if dcOnly then + local dc = readi32(blk, 0) + writei32(blk, 0, 0) + fillBlock(dst, off, stride, (dc + 4) // 8, not intra) + else + idct(blk, dst, off, stride, not intra) + bfill(blk, 0, 0, 256) + end + return true + end + + @native local function motion(pred: number): number + if umvPlus then + -- reversible codes (Annex D.2): "1" = 0, else 0 x0 (1 x)* 0, the last x the sign + if read(1) == 1 then + return pred + end + local code = 2 + read(1) + local guard = 0 + while read(1) == 1 do + code = code * 2 + read(1) + guard += 1 + if guard > 14 then + err = true + return pred + end + end + local mag = code // 2 + return if code % 2 == 1 then pred - mag else pred + mag + end + local d = vlc(MVD, 12) + if d == 0 then + return pred + end + if read(1) == 1 then + d = -d + end + local v = pred + d + if longMv then + -- Annex D (baseline header): vectors up to +-31.5; the other value of a code pair only past +-16 + if pred < -31 and v < -63 then + v += 64 + elseif pred > 32 and v > 63 then + v -= 64 + end + return v + end + return (v + 32) % 64 - 32 -- the code pair's value in -16 .. 15.5 + end + + @native local function predict(col: number, row: number, mx: number, my: number) + local hx, hy = mx % 2, my % 2 + local sx, sy = col * 16 + (mx - hx) // 2, row * 16 + (my - hy) // 2 + local dOff = row * 16 * ls + col * 16 + if sx < 0 or sy < 0 or sx + 16 + hx > ls or sy + 16 + hy > lh then + edge(refY, ls, 0, sx, sy, 16, 16, ls, lh, EDGE) + mcf(EDGE, 32, 0, curY, ls, dOff, 16, 16, hx, hy, false) + else + mcf(refY, ls, sy * ls + sx, curY, ls, dOff, 16, 16, hx, hy, false) + end + -- chroma: the luma position halved, half-sample flags from the quarter positions rounded to halves + local cx, cy = sx // 2, sy // 2 + local chx = if hx == 1 or (mx // 2) % 2 == 1 then 1 else 0 + local chy = if hy == 1 or (my // 2) % 2 == 1 then 1 else 0 + local cOff = row * 8 * cs + col * 8 + if cx < 0 or cy < 0 or cx + 8 + chx > cs or cy + 8 + chy > chh then + edge(refCb, cs, 0, cx, cy, 8, 8, cs, chh, EDGE) + mcf(EDGE, 32, 0, curCb, cs, cOff, 8, 8, chx, chy, false) + edge(refCr, cs, 0, cx, cy, 8, 8, cs, chh, EDGE) + mcf(EDGE, 32, 0, curCr, cs, cOff, 8, 8, chx, chy, false) + else + local so = cy * cs + cx + mcf(refCb, cs, so, curCb, cs, cOff, 8, 8, chx, chy, false) + mcf(refCr, cs, so, curCr, cs, cOff, 8, 8, chx, chy, false) + end + end + + @native local function copyMb(col: number, row: number) + local yo, co = row * 16 * ls + col * 16, row * 8 * cs + col * 8 + if ref then + mc(refY, ls, yo, curY, ls, yo, 16, 16, 0, 0, false) + mc(refCb, cs, co, curCb, cs, co, 8, 8, 0, 0, false) + mc(refCr, cs, co, curCr, cs, co, 8, 8, 0, 0, false) + else + fillBlock(curY, yo, ls, 128, false) + fillBlock(curY, yo + 8, ls, 128, false) + fillBlock(curY, yo + 8 * ls, ls, 128, false) + fillBlock(curY, yo + 8 * ls + 8, ls, 128, false) + fillBlock(curCb, co, cs, 128, false) + fillBlock(curCr, co, cs, 128, false) + end + end + + @native local function macroblock(col: number, row: number, P: boolean, top: boolean, first: boolean): boolean + if pos > endBits then + return false + end + if P and read(1) == 1 then + copyMb(col, row) + mvX[col + 1], mvY[col + 1] = 0, 0 + return true + end + local lut = if P then MCBPC_P else MCBPC_I + local m = vlc(lut, 9) + while m == STUFFING and not err do + if P and read(1) == 1 then -- stuffing is followed by a new COD in P-pictures + copyMb(col, row) + mvX[col + 1], mvY[col + 1] = 0, 0 + return pos <= endBits + end + if pos > endBits then + return false + end + m = vlc(lut, 9) + end + if err then + return false + end + local mtype, cbpc = m // 4, m % 4 + if mtype == 2 then + err = true -- INTER4V needs advanced prediction (Annex F), which the header refused + return false + end + local intra = mtype >= 3 + local cbpy = vlc(CBPY, 6) + if err then + return false + end + if mtype == 1 or mtype == 4 then + quant = math.clamp(quant + DQUANT[read(2)], 1, 31) + end + local yo, co = row * 16 * ls + col * 16, row * 8 * cs + col * 8 + if intra then + mvX[col + 1], mvY[col + 1] = 0, 0 + if not block(true, cbpy >= 8, curY, yo, ls) or not block(true, cbpy % 8 >= 4, curY, yo + 8, ls) + or not block(true, cbpy % 4 >= 2, curY, yo + 8 * ls, ls) or not block(true, cbpy % 2 == 1, curY, yo + 8 * ls + 8, ls) + or not block(true, cbpc >= 2, curCb, co, cs) or not block(true, cbpc % 2 == 1, curCr, co, cs) then + return false + end + return pos <= endBits + end + cbpy = 15 - cbpy + -- the vector prediction: the median of left, above and above right (outside or past the right edge: 0; the + -- first row of a picture / GOB: the left vector) + local ax = if col > 0 and not first then mvX[col] else 0 + local ay = if col > 0 and not first then mvY[col] else 0 + local px, py = ax, ay + if not top then + local bx, by = upX[col + 1], upY[col + 1] + local cx = if col + 1 < mbW then upX[col + 2] else 0 + local cy = if col + 1 < mbW then upY[col + 2] else 0 + px = math.max(math.min(ax, bx), math.min(math.max(ax, bx), cx)) + py = math.max(math.min(ay, by), math.min(math.max(ay, by), cy)) + end + local mx = motion(px) + local my = motion(py) + if umvPlus and mx - px == 1 and my - py == 1 then + pos += 1 -- start code emulation prevention bit + end + if err then + return false + end + mvX[col + 1], mvY[col + 1] = mx, my + predict(col, row, mx, my) + if not block(false, cbpy >= 8, curY, yo, ls) or not block(false, cbpy % 8 >= 4, curY, yo + 8, ls) + or not block(false, cbpy % 4 >= 2, curY, yo + 8 * ls, ls) or not block(false, cbpy % 2 == 1, curY, yo + 8 * ls + 8, ls) + or not block(false, cbpc >= 2, curCb, co, cs) or not block(false, cbpc % 2 == 1, curCr, co, cs) then + return false + end + return pos <= endBits + end + + -- a GBSC / SSC (17 bits 0..01) next, after zero stuffing to a byte boundary or not: consumed, true + @native local function startCode(): boolean + local w = peek32() + if rshift(w, 15) ~= 1 then + local s = (8 - pos % 8) % 8 + if s == 0 or rshift(w, 32 - s) ~= 0 or rshift(lshift(w, s), 15) ~= 1 then + return false + end + pos += s + end + pos += 17 + return true + end + + @native local function gobHeader(cpm: boolean): (number?, number?) + if not startCode() then + return nil, nil + end + local gn = read(5) + if cpm then + read(2) + end + read(2) -- GFID + return gn, read(5) + end + + @native local function sliceHeader(cpm: boolean, mbaBits: number, sepb2: boolean): (number?, number?) + if not startCode() then + return nil, nil + end + read(1) -- SEPB1 + if cpm then + read(2) + end + local mba = read(mbaBits) + if sepb2 then + read(1) + end + local q = read(5) + read(3) -- SEPB3, GFID + return mba, q + end + + @native local function picture(hdr: Header): (Store?, string?) + if hdr.width ~= W or hdr.height ~= H then + if hdr.width * hdr.height > state.maxPixels then + return nil, "limit: picture size " .. hdr.width .. "x" .. hdr.height + end + alloc(hdr.width, hdr.height) + end + local P = hdr.ptype == 2 + local r = ref + if P and not r then + return nil, "a P picture without a reference picture" + end + local cur = if stores[1] == r then stores[2] else stores[1] + curY, curCb, curCr = cur.y, cur.cb, cur.cr + if r then + refY, refCb, refCr = r.y, r.cb, r.cr + end + quant = hdr.quant + escFlv = hdr.flv and hdr.version == 1 + longMv = hdr.umv + umvPlus = hdr.umvPlus + mcf = if hdr.rounding == 1 then mcNoRound :: any else mc + pos = hdr.bitPos + err = false + local gobRows = if hdr.flv then 0 elseif H <= 400 then 1 elseif H <= 800 then 2 else 4 + local ss = hdr.ss + local total = mbW * mbH + local mbaBits = D.mbaBits(total) + local resync = 0 -- the first macroblock of the current GOB with a header / slice + local k = 0 + local failAt = -1 + mvX, upX = upX, mvX + mvY, upY = upY, mvY + while k < total do + local col, row = k % mbW, k // mbW + if k > 0 and (ss or (gobRows > 0 and col == 0 and row % gobRows == 0)) then + local at, q + if ss then + at, q = sliceHeader(hdr.cpm, mbaBits, total > 1584) + else + local gn, gq = gobHeader(hdr.cpm) + if gn then + at, q = if gn == 0 then -1 else gn * gobRows * mbW, gq + end + end + if at and q then + if at < k or at >= total or q == 0 then + failAt = k + break + end + while k < at do -- macroblocks missing in between: copied + copyMb(k % mbW, k // mbW) + mvX[k % mbW + 1], mvY[k % mbW + 1] = 0, 0 + k += 1 + if k % mbW == 0 then + mvX, upX = upX, mvX + mvY, upY = upY, mvY + end + end + col, row = k % mbW, k // mbW + resync, quant = k, q + end + end + -- above is outside for the slice's first mbW macroblocks (ffmpeg's first_slice_line: also the start of the + -- next row for a slice starting mid-row) + if not macroblock(col, row, P, k < resync + mbW, k == resync) then + failAt = k + break + end + k += 1 + if k % mbW == 0 then + mvX, upX = upX, mvX + mvY, upY = upY, mvY + end + end + local msg: string? = nil + if failAt >= 0 then + state.errors += 1 + msg = "bad macroblock data at macroblock " .. failAt + for k = failAt, mbW * mbH - 1 do + copyMb(k % mbW, k // mbW) + end + end + cur.ptype = hdr.ptype + cur.tr = hdr.tr + cur.disposable = hdr.disposable + if not hdr.disposable then + ref = cur + end + state.pictures += 1 + return cur, msg + end + + local core = {} :: Core + core.state = state + + @native function core.decode(buf: buffer, off: number, len: number): (Store?, string?) + local hdr, herr = D.header(buf, off, len, flv, state.opp) + if not hdr then + state.errors += 1 + return nil, herr + end + state.header = hdr + if hdr.opp then + state.opp = hdr.opp + end + local need = len + PAD + if buffer.len(data) < need then + data = buffer.create(need) + else + bfill(data, len, 0, PAD) + end + buffer.copy(data, 0, buf, off, len) + endBits = len * 8 + hdr.bitPos -= off * 8 + local s, msg = picture(hdr) + hdr.bitPos += off * 8 + return s, msg + end + + @native function core.reset() + ref = nil + end + + return core +end + +return D +end +__FILES["codecs/video/H263/Tables"] = function() + +-- codecs/video/H263/Tables: the H.263 variable-length codes (ITU-T H.263 (01/2005) tables 7 / 8 MCBPC, 12 DQUANT, +-- 13 CBPY, 14 MVD, 16 TCOEF, figure 14 zigzag). Flat tables indexed by the next K bits: len * 65536 + value (len 0: none). +-- MCBPC_I / MCBPC_P (K = 9): type * 4 + CBPC (0 INTER, 1 INTER+Q, 2 INTER4V, 3 INTRA, 4 INTRA+Q), STUFFING +-- CBPY (K = 6): the intra CBPY, Y1 the MSB (inter macroblocks use 15 - value) +-- MVD (K = 12): magnitude 0..32 in half samples (a sign bit follows every code but "1") +-- TCOEF (K = 12): last * 1024 + run * 16 + level (a sign bit follows), ESCAPE +local T = {} + +T.STUFFING = 255 +T.ESCAPE = 0xFFFF + +local function flat(codes: { { any } }, k: number): buffer + local lut = buffer.create(4 * 2 ^ k) + for _, c in codes do + local bits: string = c[1] + local len = #bits + local code = tonumber(bits, 2) :: number + local shift = k - len + local first = code * 2 ^ shift + for i = first, first + 2 ^ shift - 1 do + buffer.writeu32(lut, i * 4, len * 65536 + c[2]) + end + end + return lut +end + +-- table 7: MCBPC for I-pictures (type 3 INTRA, 4 INTRA+Q; CBPC = Cb Cr) +T.MCBPC_I = flat({ + { "1", 3 * 4 + 0 }, + { "001", 3 * 4 + 1 }, + { "010", 3 * 4 + 2 }, + { "011", 3 * 4 + 3 }, + { "0001", 4 * 4 + 0 }, + { "000001", 4 * 4 + 1 }, + { "000010", 4 * 4 + 2 }, + { "000011", 4 * 4 + 3 }, + { "000000001", T.STUFFING }, +}, 9) + +-- table 8: MCBPC for P-pictures +T.MCBPC_P = flat({ + { "1", 0 * 4 + 0 }, + { "0011", 0 * 4 + 1 }, + { "0010", 0 * 4 + 2 }, + { "000101", 0 * 4 + 3 }, + { "011", 1 * 4 + 0 }, + { "0000111", 1 * 4 + 1 }, + { "0000110", 1 * 4 + 2 }, + { "000000101", 1 * 4 + 3 }, + { "010", 2 * 4 + 0 }, + { "0000101", 2 * 4 + 1 }, + { "0000100", 2 * 4 + 2 }, + { "00000101", 2 * 4 + 3 }, + { "00011", 3 * 4 + 0 }, + { "00000100", 3 * 4 + 1 }, + { "00000011", 3 * 4 + 2 }, + { "0000011", 3 * 4 + 3 }, + { "000100", 4 * 4 + 0 }, + { "000000100", 4 * 4 + 1 }, + { "000000011", 4 * 4 + 2 }, + { "000000010", 4 * 4 + 3 }, + { "000000001", T.STUFFING }, +}, 9) + +-- table 13: CBPY (intra values 0..15) +do + local codes = { "0011", "00101", "00100", "1001", "00011", "0111", "000010", "1011", "00010", "000011", "0101", + "1010", "0100", "1000", "0110", "11" } + local list = {} + for i, c in codes do + list[i] = { c, i - 1 } + end + T.CBPY = flat(list, 6) +end + +-- table 14: MVD magnitudes 0, 0.5, 1, ... 16 (in half samples 0..32); the sign bit is not part of these +do + local codes = { "1", "01", "001", "0001", "000011", "0000101", "0000100", "0000011", "000001011", "000001010", + "000001001", "0000010001", "0000010000", "0000001111", "0000001110", "0000001101", "0000001100", "0000001011", + "0000001010", "0000001001", "0000001000", "0000000111", "0000000110", "0000000101", "0000000100", "00000000111", + "00000000110", "00000000101", "00000000100", "00000000011", "00000000010", "000000000011", "000000000010" } + local list = {} + for i, c in codes do + list[i] = { c, i - 1 } + end + T.MVD = flat(list, 12) +end + +-- table 16: TCOEF, per LAST and RUN the codes of levels 1, 2, ... (without the sign bit) +local TCOEF_LAST0: { [number]: { string } } = { + [0] = { "10", "1111", "010101", "0010111", "00011111", "000100101", "000100100", "0000100001", "0000100000", + "00000000111", "00000000110", "00000100000" }, + [1] = { "110", "010100", "00011110", "0000001111", "00000100001", "000001010000" }, + [2] = { "1110", "00011101", "0000001110", "000001010001" }, + [3] = { "01101", "000100011", "0000001101" }, + [4] = { "01100", "000100010", "000001010010" }, + [5] = { "01011", "0000001100", "000001010011" }, + [6] = { "010011", "0000001011", "000001010100" }, + [7] = { "010010", "0000001010" }, + [8] = { "010001", "0000001001" }, + [9] = { "010000", "0000001000" }, + [10] = { "0010110", "000001010101" }, + [11] = { "0010101" }, + [12] = { "0010100" }, + [13] = { "00011100" }, + [14] = { "00011011" }, + [15] = { "000100001" }, + [16] = { "000100000" }, + [17] = { "000011111" }, + [18] = { "000011110" }, + [19] = { "000011101" }, + [20] = { "000011100" }, + [21] = { "000011011" }, + [22] = { "000011010" }, + [23] = { "00000100010" }, + [24] = { "00000100011" }, + [25] = { "000001010110" }, + [26] = { "000001010111" }, +} +local TCOEF_LAST1: { [number]: { string } } = { + [0] = { "0111", "000011001", "00000000101" }, + [1] = { "001111", "00000000100" }, + [2] = { "001110" }, + [3] = { "001101" }, + [4] = { "001100" }, + [5] = { "0010011" }, + [6] = { "0010010" }, + [7] = { "0010001" }, + [8] = { "0010000" }, + [9] = { "00011010" }, + [10] = { "00011001" }, + [11] = { "00011000" }, + [12] = { "00010111" }, + [13] = { "00010110" }, + [14] = { "00010101" }, + [15] = { "00010100" }, + [16] = { "00010011" }, + [17] = { "000011000" }, + [18] = { "000010111" }, + [19] = { "000010110" }, + [20] = { "000010101" }, + [21] = { "000010100" }, + [22] = { "000010011" }, + [23] = { "000010010" }, + [24] = { "000010001" }, + [25] = { "0000000111" }, + [26] = { "0000000110" }, + [27] = { "0000000101" }, + [28] = { "0000000100" }, + [29] = { "00000100100" }, + [30] = { "00000100101" }, + [31] = { "00000100110" }, + [32] = { "00000100111" }, + [33] = { "000001011000" }, + [34] = { "000001011001" }, + [35] = { "000001011010" }, + [36] = { "000001011011" }, + [37] = { "000001011100" }, + [38] = { "000001011101" }, + [39] = { "000001011110" }, + [40] = { "000001011111" }, +} +do + local list = { { "0000011", T.ESCAPE } } + for last = 0, 1 do + local byRun = if last == 0 then TCOEF_LAST0 else TCOEF_LAST1 + for run = 0, 40 do + local levels = byRun[run] + if levels then + for level, c in levels do + table.insert(list, { c, last * 1024 + run * 16 + level }) + end + end + end + end + T.TCOEF = flat(list, 12) + T.TCOEF_COUNT = #list - 1 +end + +-- figure 14: the zigzag scan (scan index -> natural position) +T.ZIGZAG = buffer.create(64) +do + local zz = { 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, + 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, + 60, 61, 54, 47, 55, 62, 63 } + for i, v in zz do + buffer.writeu8(T.ZIGZAG, i - 1, v) + end +end + +-- table 12: DQUANT (2 bits) -> the change of QUANT +T.DQUANT = { [0] = -1, -2, 1, 2 } + +-- source formats 1..5 (sub-QCIF, QCIF, CIF, 4CIF, 16CIF): width, height +T.FORMATS = { { 128, 96 }, { 176, 144 }, { 352, 288 }, { 704, 576 }, { 1408, 1152 } } + +-- Sorenson Spark picture sizes 2..6 +T.FLV_SIZES = { [2] = { 352, 288 }, [3] = { 176, 144 }, [4] = { 128, 96 }, [5] = { 320, 240 }, [6] = { 160, 120 } } + +return T +end +end + + + + + + H264 + --!optimize 2 +--!nocheck +-- rosetta chunk H264 (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 13 modules (11 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["codecs/video/H264"] = function() + +-- codecs/video/H264: an H.264 / AVC (ITU-T H.264 | ISO/IEC 14496-10) video decoder in pure Luau, bit-exact with ffmpeg. +-- Clean-room from the spec; constant tables from openh264 (BSD-2-Clause, licenses/openh264-LICENSE.txt). 8-bit 4:2:0 +-- Constrained Baseline, Main and High. UNSUPPORTED: interlaced coding (field pictures, MBAFF), 4:0:0 / 4:2:2 / 4:4:4, +-- bit depths above 8, lossless, FMO / ASO, SP / SI slices, data partitioning, SVC / MVC (their NAL units are ignored). +local Err = __include("core/Err") +local Types = __include("Types") +local Bitstream = __include("codecs/video/H264/Bitstream") +local Decoder = __include("codecs/video/H264/Decoder") +local Params = __include("codecs/video/H264/Params") + +local H264 = {} + +type Options = { + avcC: buffer?, -- AVCDecoderConfigurationRecord (MP4 'avcC', Matroska CodecPrivate): samples are length-prefixed + lengthSize: number?, -- NAL length field size for length-prefixed input without avcC (1, 2 or 4) + maxPixels: number?, + lowDelay: boolean?, + deblock: boolean?, + yield: (() -> ())?, +} + +type Frame = { + image: Types.Image, + pts: number, + duration: number, + poc: number, + keyframe: boolean, +} + +local DecoderMeta = {} +DecoderMeta.__index = DecoderMeta + +type H264Decoder = typeof(setmetatable({} :: { state: any, lengthSize: number?, errors: number, lastError: string? }, DecoderMeta)) + +local function toBuffer(data: any): buffer? + if type(data) == "buffer" then + return data + elseif type(data) == "string" then + return buffer.fromstring(data) + end + return nil +end + +local function status(self: H264Decoder): Err.Err? + local st = self.state + self.errors = st.errors + self.lastError = st.lastError + if st.fatal then + local m = st.fatal + if string.sub(m, 1, 7) == "limit: " then + return Err.new(Err.LIMIT, string.sub(m, 8)) + end + return Err.new(Err.CORRUPT, m) + end + if st.unsupported then + return Err.new(Err.UNSUPPORTED, st.unsupported) + end + return nil +end + +function H264.newDecoder(opts: Options?): (H264Decoder?, Err.Err?) + local o = opts or {} + if type(o) ~= "table" then + return nil, Err.new(Err.ARG, "newDecoder: options must be a table") + end + local st = Decoder.new(o :: any) + local self = setmetatable({ state = st, lengthSize = o.lengthSize, errors = 0, lastError = nil :: string? }, DecoderMeta) + if o.avcC then + local ok, err = self:configure(o.avcC) + if not ok then + return nil, err + end + end + return self, nil +end + +function DecoderMeta.configure(self: H264Decoder, avcC: any): (boolean?, Err.Err?) + local b = toBuffer(avcC) + if not b then + return nil, Err.new(Err.ARG, "configure: expected a buffer or string") + end + local cfg, err = Bitstream.parseAvcC(b, 0, buffer.len(b)) + if not cfg then + local m = err or "bad avcC" + if string.sub(m, 1, 11) == "truncated: " then + return nil, Err.new(Err.TRUNCATED, string.sub(m, 12)) + end + return nil, Err.new(Err.CORRUPT, m) + end + self.lengthSize = cfg.lengthSize + local nals = cfg.nals + for i = 1, #nals, 2 do + Decoder.nal(self.state, b, nals[i], nals[i + 1], nil) + end + local e = status(self) + if e and e.code ~= Err.CORRUPT then + return nil, e + end + return true, nil +end + +function DecoderMeta.decode(self: H264Decoder, data: any, pts: number?, off: number?, len: number?): ({ Frame }?, Err.Err?) + local b = toBuffer(data) + if not b then + return nil, Err.new(Err.ARG, "decode: expected a buffer or string") + end + local n = buffer.len(b) + local o = math.clamp(off or 0, 0, n) + local l = math.clamp(len or (n - o), 0, n - o) + local st = self.state + local nals + if self.lengthSize then + local all, partial = Bitstream.splitLength(b, o, l, self.lengthSize) + nals = all or partial + if not all then + st.errors += 1 + st.lastError = "NAL length past the end of the sample" + end + elseif Bitstream.isAnnexB(b, o, l) then + nals = Bitstream.splitAnnexB(b, o, l) + else + nals = { o, l } + end + for i = 1, #nals, 2 do + Decoder.nal(st, b, nals[i], nals[i + 1], pts) + if st.fatal or st.unsupported then + break + end + end + local frames = Decoder.take(st) + local e = status(self) + if e then + return nil, e + end + return frames, nil +end + +function DecoderMeta.flush(self: H264Decoder): { Frame } + Decoder.flush(self.state) + status(self) + return Decoder.take(self.state) +end + +function H264.decodeAll(data: any, opts: Options?): ({ Frame }?, Err.Err?) + local dec, err = H264.newDecoder(opts) + if not dec then + return nil, err + end + local frames, e = dec:decode(data) + if not frames then + return nil, e + end + for _, f in dec:flush() do + table.insert(frames, f) + end + return frames, nil +end + +function H264.parseAvcC(data: any): (any, Err.Err?) + local b = toBuffer(data) + if not b then + return nil, Err.new(Err.ARG, "parseAvcC: expected a buffer or string") + end + local cfg, err = Bitstream.parseAvcC(b, 0, buffer.len(b)) + if not cfg then + return nil, Err.new(Err.CORRUPT, err or "bad avcC") + end + return cfg, nil +end + +function H264.newVideoDecoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) + local o: Options = { maxPixels = opts and opts.maxPixels, deblock = opts and opts.deblock, lowDelay = opts and opts.lowDelay, + yield = opts and opts.yield } + local function make(): (H264Decoder?, Err.Err?) + local d, err = H264.newDecoder(o) + if d and track.config then + local ok, e = d:configure(track.config) + if not ok then + return nil, e + end + end + return d, err + end + local dec, err = make() + if not dec then + return nil, err + end + local queue: { any } = {} + local pool: { number } = {} + local outIndex: number? = if track.ptsInOutputOrder then 0 else nil + local self: any = {} + local function push(frames: { Frame }) + for _, f in frames do + local pts = f.pts + if track.ptsInOutputOrder then + pts = outIndex or 0 + outIndex = pts + 1 + elseif #pool > 0 then + -- pictures take the packet timestamps in increasing order (right for MP4 / MKV / TS pts and AVI's decode-order times) + pts = table.remove(pool, 1) + end + table.insert(queue, { f.image, pts, f.keyframe }) + end + end + function self.decode(_: any, packet: Types.Packet): Err.Err? + if not dec then + return Err.new(Err.CORRUPT, "decoder not available") + end + if outIndex == nil and track.ptsInOutputOrder then + outIndex = packet.pts + end + if packet.pts ~= nil and not track.ptsInOutputOrder then + local i = #pool + while i > 0 and pool[i] > packet.pts do + i -= 1 + end + table.insert(pool, i + 1, packet.pts) + end + local frames, e = (dec :: H264Decoder):decode(packet.data, packet.pts) + if not frames then + return e + end + push(frames) + return nil + end + function self.receive(_: any): (Types.Image?, number?, boolean?) + local q = table.remove(queue, 1) + if q then + return q[1], q[2], q[3] + end + return nil + end + function self.flush(_: any) + if dec then + push((dec :: H264Decoder):flush()) + end + end + function self.reset(_: any) + dec = make() + table.clear(queue) + table.clear(pool) + if track.ptsInOutputOrder then + outIndex = nil + end + end + return self, nil +end + +-- 7.4.1.2.3: a new access unit starts at an AUD, SPS, PPS or SEI after a slice, or at a slice with first_mb_in_slice 0 +-- after a slice +function H264.accessUnits(data: any, off: number?, len: number?): { any } + local b = toBuffer(data) + local out = {} + if not b then + return out + end + local n = buffer.len(b) + local o = math.clamp(off or 0, 0, n) + local l = math.clamp(len or (n - o), 0, n - o) + local nals = Bitstream.splitAnnexB(b, o, l) + local start, hasSlice, key = o, false, false + for i = 1, #nals, 2 do + local p, nl = nals[i], nals[i + 1] + local t = buffer.readu8(b, p) % 32 + local isSlice = t == 1 or t == 5 + local boundary = false + if hasSlice then + if t == 9 or t == 7 or t == 8 or t == 6 or (t >= 14 and t <= 18) then + boundary = true + elseif isSlice and nl > 1 and buffer.readu8(b, p + 1) >= 128 then + boundary = true + end + end + if boundary then + local s = p + while s > start and buffer.readu8(b, s - 1) ~= 1 do + s -= 1 + end + s -= 1 + while s > start and buffer.readu8(b, s - 1) == 0 do + s -= 1 + end + table.insert(out, start) + table.insert(out, s - start) + table.insert(out, key) + start, hasSlice, key = s, false, false + end + if isSlice then + hasSlice = true + if t == 5 then + key = true + end + end + end + if hasSlice and o + l > start then + table.insert(out, start) + table.insert(out, o + l - start) + table.insert(out, key) + end + return out +end + +function H264.toAnnexB(config: buffer?, sample: buffer): (buffer?, Err.Err?) + local parts = {} + local lengthSize = 4 + if config then + local cfg, err = Bitstream.parseAvcC(config, 0, buffer.len(config)) + if not cfg then + return nil, Err.new(Err.CORRUPT, err or "bad avcC") + end + lengthSize = cfg.lengthSize + for i = 1, #cfg.nals, 2 do + table.insert(parts, "\0\0\0\1" .. buffer.readstring(config, cfg.nals[i], cfg.nals[i + 1])) + end + end + local nals = Bitstream.splitLength(sample, 0, buffer.len(sample), lengthSize) + if not nals then + return nil, Err.new(Err.CORRUPT, "NAL length past the end of the sample") + end + for i = 1, #nals, 2 do + table.insert(parts, "\0\0\0\1" .. buffer.readstring(sample, nals[i], nals[i + 1])) + end + return buffer.fromstring(table.concat(parts)), nil +end + +function H264.info(data: any): any + local b = toBuffer(data) + if not b then + return nil + end + local nals + if buffer.len(b) > 6 and buffer.readu8(b, 0) == 1 then + local cfg = Bitstream.parseAvcC(b, 0, buffer.len(b)) + nals = if cfg then cfg.nals else {} + else + nals = Bitstream.splitAnnexB(b, 0, buffer.len(b)) + end + for i = 1, #nals, 2 do + if buffer.readu8(b, nals[i]) % 32 == 7 then + local sps = Params.sps(Bitstream.reader(b, nals[i], nals[i + 1], 1)) + if sps then + local fps = nil + if sps.unitsInTick and sps.timeScale and sps.unitsInTick > 0 then + fps = sps.timeScale / (2 * sps.unitsInTick) + end + return { + width = sps.width, + height = sps.height, + profile = sps.profile, + level = sps.level, + chromaFormat = sps.chromaFormat, + bitDepth = sps.bitDepth, + interlaced = not sps.frameMbsOnly, + frameRate = fps, + maxRefFrames = sps.maxRefFrames, + numReorderFrames = sps.numReorderFrames, + } + end + end + end + return nil +end + +function H264.planes(img: Types.Image): (number, number, number, number, number) + local cw, ch = (img.width + 1) // 2, (img.height + 1) // 2 + local ny = img.width * img.height + return 0, ny, ny + cw * ch, cw, ch +end + +return H264 +end +__FILES["codecs/video/H264/Bitstream"] = @native function() + + + +-- 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, +-- AVCC, avcC (AVCDecoderConfigurationRecord, ISO/IEC 14496-15 5.3.3), emulation prevention, u(n) / ue(v) / se(v) / te(v). +local Bitstream = {} + +local readu8 = buffer.readu8 +local band, lshift = bit32.band, bit32.lshift + +type Reader = { + buf: buffer, -- the RBSP (emulation prevention removed) followed by 8 zero bytes + pos: number, + size: number, -- RBSP length in bits (up to the end of the data, trailing bits included) + stop: number, -- bit position of the rbsp_stop_one_bit (size when there is none) + n: number, +} + +-- start codes are 00 00 01 with any leading zero bytes; trailing zero bytes of a NAL are dropped +@native function Bitstream.splitAnnexB(buf: buffer, off: number, len: number): { number } + local out = {} + local e = off + len + local i = off + local start = -1 + while i + 2 < e do + local b2 = readu8(buf, i + 2) + if b2 > 1 then + i += 3 + elseif readu8(buf, i + 1) ~= 0 then + i += 2 + elseif b2 == 1 and readu8(buf, i) == 0 then + if start >= 0 then + local j = i + while j > start and readu8(buf, j - 1) == 0 do + j -= 1 + end + if j > start then + table.insert(out, start) + table.insert(out, j - start) + end + end + start = i + 3 + i += 3 + else + i += 1 + end + end + if start >= 0 then + local j = e + while j > start and readu8(buf, j - 1) == 0 do + j -= 1 + end + if j > start then + table.insert(out, start) + table.insert(out, j - start) + end + end + return out +end + +@native function Bitstream.isAnnexB(buf: buffer, off: number, len: number): boolean + if len >= 3 and readu8(buf, off) == 0 and readu8(buf, off + 1) == 0 then + local b2 = readu8(buf, off + 2) + if b2 == 1 then + return true + end + return b2 == 0 and len >= 4 and readu8(buf, off + 3) == 1 + end + return false +end + +@native function Bitstream.splitLength(buf: buffer, off: number, len: number, size: number): ({ number }?, { number }) + local out = {} + local e = off + len + local p = off + while p + size <= e do + local n = 0 + for k = 0, size - 1 do + n = n * 256 + readu8(buf, p + k) + end + p += size + if n > e - p then + return nil, out + end + if n > 0 then + table.insert(out, p) + table.insert(out, n) + end + p += n + end + return out, out +end + +@native function Bitstream.parseAvcC(buf: buffer, off: number, len: number): (any, string?) + if len < 7 then + return nil, "truncated: avcC shorter than 7 bytes" + end + if readu8(buf, off) ~= 1 then + return nil, "avcC configurationVersion is not 1" + end + local cfg = { + profile = readu8(buf, off + 1), + compat = readu8(buf, off + 2), + level = readu8(buf, off + 3), + lengthSize = band(readu8(buf, off + 4), 3) + 1, + nals = {} :: { number }, + } + local p = off + 5 + local e = off + len + for pass = 1, 2 do + if p >= e then + return nil, "truncated: avcC parameter set count" + end + local count = if pass == 1 then band(readu8(buf, p), 31) else readu8(buf, p) + p += 1 + for _ = 1, count do + if p + 2 > e then + return nil, "truncated: avcC parameter set length" + end + local n = readu8(buf, p) * 256 + readu8(buf, p + 1) + p += 2 + if p + n > e then + return nil, "truncated: avcC parameter set" + end + table.insert(cfg.nals, p) + table.insert(cfg.nals, n) + p += n + end + end + return cfg, nil +end + +-- emulation_prevention_three_byte (00 00 03) is removed +@native function Bitstream.reader(buf: buffer, off: number, len: number, skip: number): Reader + local out = buffer.create(len + 8) + local o = 0 + local zeros = 0 + for i = off + skip, off + len - 1 do + local b = readu8(buf, i) + if zeros >= 2 and b == 3 then + zeros = 0 + else + buffer.writeu8(out, o, b) + o += 1 + if b == 0 then + zeros += 1 + else + zeros = 0 + end + end + end + -- the rbsp_stop_one_bit: the last set bit of the last non-zero byte + local stop = o * 8 + local j = o - 1 + while j >= 0 and readu8(out, j) == 0 do + j -= 1 + end + if j >= 0 then + local b = readu8(out, j) + local k = 0 + while band(b, lshift(1, k)) == 0 do + k += 1 + end + stop = j * 8 + 7 - k + end + return { buf = out, pos = 0, size = o * 8, stop = stop, n = o + 8 } +end + +-- Plain arithmetic instead of bit32 (LuaJIT runs bit32 through compat wrappers whose sign fix-ups split traces). +local P2 = table.create(33, 1) -- P2[k + 1] = 2^k +for k = 0, 32 do + P2[k + 1] = 2 ^ k +end +Bitstream.P2 = P2 +local LZ8 = table.create(256, 0) -- LZ8[x + 1] = leading zero bits of the byte x (8 for 0) +for x = 0, 255 do + local n, v = 0, x + while n < 8 and v < 128 do + v *= 2 + n += 1 + end + LZ8[x + 1] = n +end +Bitstream.LZ8 = LZ8 + +@native local function clz32(v: number): number + if v >= 16777216 then + return LZ8[v // 16777216 + 1] + elseif v >= 65536 then + return 8 + LZ8[v // 65536 + 1] + elseif v >= 256 then + return 16 + LZ8[v // 256 + 1] + end + return 24 + LZ8[v + 1] +end +Bitstream.clz32 = clz32 + +@native local function peekAt(b: buffer, n: number, pos: number): number + local p = pos // 8 + if p + 5 > n then + return 0 + end + local s = pos - p * 8 + local w = readu8(b, p) * 16777216 + readu8(b, p + 1) * 65536 + readu8(b, p + 2) * 256 + readu8(b, p + 3) + if s == 0 then + return w + end + return (w * P2[s + 1]) % 4294967296 + readu8(b, p + 4) // P2[9 - s] +end +Bitstream.peekAt = peekAt + +@native local function peek32(r: Reader): number + return peekAt(r.buf, r.n, r.pos) +end +Bitstream.peek32 = peek32 + +@native function Bitstream.u(r: Reader, n: number): number + local v = peekAt(r.buf, r.n, r.pos) + r.pos += n + return v // P2[33 - n] +end + +@native function Bitstream.u1(r: Reader): number + local pos = r.pos + r.pos = pos + 1 + local p = pos // 8 + if p >= r.n then + return 0 + end + return (readu8(r.buf, p) // P2[8 - (pos - p * 8)]) % 2 +end + +-- more than 31 leading zeros returns 2^32 (out of range for every syntax element) +@native local function ue(r: Reader): number + local v = peekAt(r.buf, r.n, r.pos) + if v == 0 then + r.pos += 32 + return 4294967296 + end + local lz = clz32(v) + if lz < 16 then + local n = 2 * lz + 1 + r.pos += n + return v // P2[33 - n] - 1 + end + r.pos += lz + v = peekAt(r.buf, r.n, r.pos) + r.pos += lz + 1 + return v // P2[32 - lz] - 1 +end +Bitstream.ue = ue + +@native function Bitstream.se(r: Reader): number + local k = ue(r) + if k % 2 == 1 then + return (k + 1) // 2 + end + return -(k // 2) +end + +@native function Bitstream.te(r: Reader, range: number): number + if range == 1 then + return 1 - Bitstream.u1(r) + end + return ue(r) +end + +-- more_rbsp_data() +@native function Bitstream.moreData(r: Reader): boolean + return r.pos < r.stop +end + +return Bitstream +end +__FILES["codecs/video/H264/Cabac"] = @native function() + + + +-- 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): +-- engine (9.3.1.2 / 9.3.3.2), context init (9.3.1.1), binarizations and ctxIdxInc (9.3.2 / 9.3.3.1), residual_block_cabac. +-- codIOffset is kept with `nb` look-ahead bits (low = offset * 2^nb + next bits), so renormalisation is one multiply. +local Bitstream = __include("codecs/video/H264/Bitstream") +local Tables = __include("codecs/video/H264/Tables") +local Mb = __include("codecs/video/H264/Mb") + +local readu8 = buffer.readu8 +local min = math.min + +local K_I4, K_I8, K_I16, K_PCM, K_P, K_PSKIP, K_B, K_BSKIP, K_BDIRECT = Mb.K_I4, Mb.K_I8, Mb.K_I16, Mb.K_PCM, Mb.K_P, Mb.K_PSKIP, Mb.K_B, Mb.K_BSKIP, Mb.K_BDIRECT +local BLK_X, BLK_Y = Mb.BLK_X, Mb.BLK_Y + +local Cabac = {} + +local RANGE_LPS = Tables.RANGE_LPS +local TRANS = Tables.TRANS +local POW2 = table.create(40, 1) +for i = 0, 39 do + POW2[i + 1] = 2 ^ i +end +local NORM = table.create(512, 0) -- NORM[r + 1] = renormalisation shift of range r (r < 512) +for r = 1, 511 do + local s, v = 0, r + while v < 256 do + v *= 2 + s += 1 + end + NORM[r + 1] = s +end +-- state per context: pStateIdx * 2 + valMPS, at ST[ctxIdx + 1] +local ST = table.create(460, 0) +-- per packed state s (pStateIdx * 2 + valMPS) and LPS bit: the next state and the bin; rangeTabLPS by packed state +local NEXTS, BINS = table.create(256, 0), table.create(256, 0) +local LPSR = table.create(512, 0) +for st = 0, 127 do + local p, mps = st // 2, st % 2 + NEXTS[st * 2 + 1] = TRANS[p * 2 + 2] * 2 + mps + BINS[st * 2 + 1] = mps + NEXTS[st * 2 + 2] = TRANS[p * 2 + 1] * 2 + (if p == 0 then 1 - mps else mps) + BINS[st * 2 + 2] = 1 - mps + for q = 0, 3 do + LPSR[st * 4 + q + 1] = RANGE_LPS[p * 4 + q + 1] + end +end + +local ebuf: buffer = buffer.create(1) +local epos, elimit = 0, 0 +local erange, elow, enb = 510, 0, 0 + +@native local function refill() + local b = 0 + if epos < elimit then + b = readu8(ebuf, epos) + end + epos += 1 + elow = elow * 256 + b + enb += 8 +end + +-- decision (9.3.3.2.1): the LPS test is min(1, low // scaled) (low < 2.5 * scaled always) +@native local function decision(ctx: number): number + local s = ST[ctx + 1] + local range = erange + local lps = LPSR[s * 4 + (range // 64) % 4 + 1] + local r = range - lps + local scaled = r * POW2[enb + 1] + local bit = min(1, elow // scaled) + elow -= bit * scaled + r += bit * (lps - r) + local k = s * 2 + bit + 1 + ST[ctx + 1] = NEXTS[k] + local sh = NORM[r + 1] + erange = r * POW2[sh + 1] + enb -= sh + if enb < 8 then + refill() + end + return BINS[k] +end + +@native local function bypass(): number + enb -= 1 + local scaled = erange * POW2[enb + 1] + local bin = elow // scaled + elow -= bin * scaled + if enb < 8 then + refill() + end + return bin +end + +@native local function terminate(): number + local r = erange - 2 + local scaled = r * POW2[enb + 1] + if elow >= scaled then + erange = r + return 1 + end + if r < 256 then + r *= 2 + enb -= 1 + if enb < 8 then + refill() + end + end + erange = r + return 0 +end + +@native local function engineInit(b: buffer, p: number, limit: number) + ebuf, epos, elimit = b, p, limit + elow, enb = 0, -9 + refill() + refill() + refill() + erange = 510 +end + +-- the bit position the spec's decoder is at (after a terminate bin of 1) +@native local function bitPos(): number + return epos * 8 - enb +end + +@native local function initContexts(sliceQp: number, model: number) + local init = Tables.CABAC_INIT + local qp = math.clamp(sliceQp, 0, 51) + for ctx = 0, 459 do + local m = init[ctx * 8 + model * 2 + 1] + local n = init[ctx * 8 + model * 2 + 2] + local pre = math.clamp((m * qp) // 16 + n, 1, 126) + if pre <= 63 then + ST[ctx + 1] = (63 - pre) * 2 + else + ST[ctx + 1] = (pre - 64) * 2 + 1 + end + end +end + +local ZZ4, ZZ8 = Tables.ZIGZAG4, Tables.ZIGZAG8 +local SIG8, LAST8 = Tables.SIG8, Tables.LAST8 +local CAT_CBF = { 0, 4, 8, 12, 16 } +local CAT_SIG = { 0, 15, 29, 44, 47 } +local CAT_ABS = { 0, 10, 20, 30, 39 } +local MAXC = { 16, 15, 16, 4, 15, 64 } +local SIGPOS = table.create(64, 0) + +-- positions: cat 0 / 2 zig-zag, 1 / 4 zig-zag from 1, 3 raster 0..3, 5 the 8x8 zig-zag +local SCAN = {} +do + local ac = table.create(15, 0) + for i = 1, 15 do + ac[i] = ZZ4[i + 1] + end + SCAN[1], SCAN[2], SCAN[3], SCAN[4], SCAN[5], SCAN[6] = ZZ4, ac, ZZ4, { 0, 1, 2, 3 }, ac, ZZ8 +end +local SIG3 = { 0, 1, 2 } + +@native local function block(cat: number, out: { number }, base: number, mul: { number }?, div: number): number + local maxc = MAXC[cat + 1] + local n = 0 + local last = false + -- significance map + if cat == 5 then + for i = 0, 62 do + if decision(402 + SIG8[i + 1]) == 1 then + n += 1 + SIGPOS[n] = i + if decision(417 + LAST8[i + 1]) == 1 then + last = true + break + end + end + end + elseif cat == 3 then + local sb, lb = 105 + 44, 166 + 44 + for i = 0, 2 do + if decision(sb + SIG3[i + 1]) == 1 then + n += 1 + SIGPOS[n] = i + if decision(lb + SIG3[i + 1]) == 1 then + last = true + break + end + end + end + else + local sb = 105 + CAT_SIG[cat + 1] + local lb = 166 + CAT_SIG[cat + 1] + for i = 0, maxc - 2 do + if decision(sb + i) == 1 then + n += 1 + SIGPOS[n] = i + if decision(lb + i) == 1 then + last = true + break + end + end + end + end + if not last then + n += 1 + SIGPOS[n] = maxc - 1 + end + -- levels, highest frequency first + local absBase = if cat == 5 then 426 else 227 + CAT_ABS[cat + 1] + local gt1, eq1 = 0, 0 + local half = div // 2 + local catMax = if cat == 3 then 3 else 4 + local scan = SCAN[cat + 1] + for k = n, 1, -1 do + local v + local inc = 0 + if gt1 == 0 then + inc = min(eq1 + 1, 4) + end + if decision(absBase + inc) == 0 then + v = 1 + eq1 += 1 + else + local ctx = absBase + 5 + min(gt1, catMax) + local prefix = 1 + while prefix < 14 and decision(ctx) == 1 do + prefix += 1 + end + v = prefix + 1 + if prefix == 14 then + -- Exp-Golomb (k = 0) suffix + local kk = 0 + while bypass() == 1 do + v += POW2[kk + 1] + kk += 1 + if kk > 24 then + return -1 + end + end + while kk > 0 do + kk -= 1 + v += bypass() * POW2[kk + 1] + end + end + gt1 += 1 + end + if bypass() == 1 then + v = -v + end + local p = scan[SIGPOS[k] + 1] + if mul then + out[base + p + 1] = (v * mul[p + 1] + half) // div + else + out[base + p + 1] = v + end + end + return n +end + +-- condition helpers on neighbouring macroblocks (addresses are 1-based here) +@native local function leftAddr(S: any, M: any): number + return ((M.aL) and (M.addr) or (0)) +end +@native local function topAddr(S: any, M: any): number + return ((M.aT) and (M.addr - S.mbW + 1) or (0)) +end + +@native local function mbSkipFlag(S: any, M: any): number + local k = S.kind + local a, b = leftAddr(S, M), topAddr(S, M) + local inc = 0 + if a > 0 and k[a] ~= K_PSKIP and k[a] ~= K_BSKIP then + inc += 1 + end + if b > 0 and k[b] ~= K_PSKIP and k[b] ~= K_BSKIP then + inc += 1 + end + return decision((((S.type == 1) and (24) or (11))) + inc) +end + +-- intra mb_type (I slice: prefix false, offset 3; P / B suffix: offset 17 / 32) -> 0..25 +@native local function intraType(S: any, M: any, off: number): number + local b0 + if off == 3 then + local k = S.kind + local a, b = leftAddr(S, M), topAddr(S, M) + local inc = 0 + if a > 0 and k[a] ~= K_I4 and k[a] ~= K_I8 then + inc += 1 + end + if b > 0 and k[b] ~= K_I4 and k[b] ~= K_I8 then + inc += 1 + end + b0 = decision(3 + inc) + else + b0 = decision(off) + end + if b0 == 0 then + return 0 + end + if terminate() == 1 then + return 25 + end + local luma, chroma, pred + if off == 3 then + luma = decision(6) + chroma = decision(7) + if chroma == 1 then + chroma += decision(8) + end + pred = decision(9) * 2 + pred += decision(10) + else + luma = decision(off + 1) + chroma = decision(off + 2) + if chroma == 1 then + chroma += decision(off + 2) + end + pred = decision(off + 3) * 2 + pred += decision(off + 3) + end + return 1 + pred + 4 * chroma + 12 * luma +end + +@native local function pMbType(): number + -- 0..3 inter, 5+ intra (returned as -1: the caller decodes the suffix) + if decision(14) == 1 then + return -1 + end + if decision(15) == 0 then + return ((decision(16) == 0) and (0) or (3)) + end + return ((decision(17) == 1) and (1) or (2)) +end + +@native local function bMbType(S: any, M: any): number + local k = S.kind + local a, b = leftAddr(S, M), topAddr(S, M) + local inc = 0 + if a > 0 and k[a] ~= K_BSKIP and k[a] ~= K_BDIRECT then + inc += 1 + end + if b > 0 and k[b] ~= K_BSKIP and k[b] ~= K_BDIRECT then + inc += 1 + end + if decision(27 + inc) == 0 then + return 0 + end + if decision(30) == 0 then + return 1 + decision(32) + end + local bits = decision(31) * 8 + bits += decision(32) * 4 + bits += decision(32) * 2 + bits += decision(32) + if bits < 8 then + return bits + 3 + elseif bits == 13 then + return -1 -- intra + elseif bits == 14 then + return 11 + elseif bits == 15 then + return 22 + end + bits = bits * 2 + decision(32) + return bits - 4 +end + +@native local function pSubType(): number + if decision(21) == 1 then + return 0 + end + if decision(22) == 0 then + return 1 + end + return ((decision(23) == 1) and (2) or (3)) +end + +@native local function bSubType(): number + if decision(36) == 0 then + return 0 + end + if decision(37) == 0 then + return 1 + decision(39) + end + local t = 3 + if decision(38) == 1 then + if decision(39) == 1 then + return 11 + decision(39) + end + t += 4 + end + t += 2 * decision(39) + t += decision(39) + return t +end + +@native local function refIdx(S: any, M: any, rgt: { number }, x: number, y: number): number + local g = M.g0 + y * S.w4 + x + local inc = 0 + if (x > 0 or M.aL) and rgt[g - 1] ~= 0 then + inc += 1 + end + if (y > 0 or M.aT) and rgt[g - S.w4] ~= 0 then + inc += 2 + end + if decision(54 + inc) == 0 then + return 0 + end + local v = 1 + local ctx = 58 + while decision(ctx) == 1 do + v += 1 + ctx = 59 + if v > 32 then + return -1 + end + end + return v +end + +-- the mvd grid holds |mvd| (2 per 4x4) +@native local function mvd(S: any, M: any, grid: { number }, x: number, y: number, comp: number): number + local g = M.g0 + y * S.w4 + x + local sum = 0 + if x > 0 or M.aL then + sum += grid[2 * (g - 1) - 1 + comp] + end + if y > 0 or M.aT then + sum += grid[2 * (g - S.w4) - 1 + comp] + end + local base = ((comp == 0) and (40) or (47)) + local inc = 0 + if sum > 32 then + inc = 2 + elseif sum >= 3 then + inc = 1 + end + if decision(base + inc) == 0 then + return 0 + end + local v = 1 + local ctx = base + 3 + while v < 9 and decision(ctx) == 1 do + v += 1 + if ctx < base + 6 then + ctx += 1 + end + end + if v >= 9 then + local k = 3 + while bypass() == 1 do + v += POW2[k + 1] + k += 1 + if k > 24 then + return 0 + end + end + while k > 0 do + k -= 1 + v += bypass() * POW2[k + 1] + end + end + if bypass() == 1 then + return -v + end + return v +end + +@native local function fillRegion(S: any, M: any, grid: { number }, x: number, y: number, w: number, h: number, v: number) + local w4 = S.w4 + for j = y, y + h - 1 do + local g = M.g0 + j * w4 + x + for i = 0, w - 1 do + grid[g + i] = v + end + end +end + +@native local function fillMvd(S: any, M: any, grid: { number }, x: number, y: number, w: number, h: number, ax: number, ay: number) + local w4 = S.w4 + for j = y, y + h - 1 do + local g = M.g0 + j * w4 + x + for i = 0, w - 1 do + grid[2 * (g + i) - 1] = ax + grid[2 * (g + i)] = ay + end + end +end + +@native local function cbpCabac(S: any, M: any): number + local cbpTab = S.cbpTab + local a, b = leftAddr(S, M), topAddr(S, M) + local luma = 0 + for b8 = 0, 3 do + local bx, by = b8 % 2, b8 // 2 + local condA, condB = 0, 0 + if bx == 1 then + if (luma // POW2[b8 - 1 + 1]) % 2 == 0 then + condA = 1 + end + elseif a > 0 then + if (cbpTab[a] // POW2[b8 + 1 + 1]) % 2 == 0 then + condA = 1 + end + end + if by == 1 then + if (luma // POW2[b8 - 2 + 1]) % 2 == 0 then + condB = 1 + end + elseif b > 0 then + if (cbpTab[b] // POW2[b8 + 2 + 1]) % 2 == 0 then + condB = 1 + end + end + if decision(73 + condA + 2 * condB) == 1 then + luma += POW2[b8 + 1] + end + end + local ca = ((a > 0) and (cbpTab[a] // 16) or (0)) + local cb = ((b > 0) and (cbpTab[b] // 16) or (0)) + local inc = (((ca ~= 0) and (1) or (0))) + (((cb ~= 0) and (2) or (0))) + local chroma = 0 + if decision(77 + inc) == 1 then + inc = (((ca == 2) and (1) or (0))) + (((cb == 2) and (2) or (0))) + chroma = 1 + decision(81 + inc) + end + return luma + 16 * chroma +end + +@native local function qpDelta(S: any): number + local k = 0 + if decision(60 + (((S.lastQpd) and (1) or (0)))) == 1 then + k = 1 + local ctx = 62 + while decision(ctx) == 1 do + k += 1 + ctx = 63 + if k > 104 then + return 999 + end + end + end + if k % 2 == 1 then + return (k + 1) // 2 + end + return -(k // 2) +end + +@native local function chromaPredMode(S: any, M: any): number + local a, b = leftAddr(S, M), topAddr(S, M) + local cpm, kind = S.cpmTab, S.kind + local inc = 0 + if a > 0 and kind[a] <= K_I16 and cpm[a] ~= 0 then + inc += 1 + end + if b > 0 and kind[b] <= K_I16 and cpm[b] ~= 0 then + inc += 1 + end + if decision(64 + inc) == 0 then + return 0 + end + if decision(67) == 0 then + return 1 + end + return 2 + decision(67) +end + +@native local function t8Flag(S: any, M: any): number + local a, b = leftAddr(S, M), topAddr(S, M) + local t8 = S.t8Tab + local inc = 0 + if a > 0 and t8[a] == 1 then + inc += 1 + end + if b > 0 and t8[b] == 1 then + inc += 1 + end + return decision(399 + inc) +end + +-- coded_block_flag condition of a neighbour: v = the neighbour's flag when its block is available +@native local function cbf(cat: number, condA: number, condB: number): number + return decision(85 + CAT_CBF[cat + 1] + condA + 2 * condB) +end + +-- luma 4x4 coded_block_flag neighbours of (bx, by) +@native local function lumaCond(S: any, M: any, bx: number, by: number, intra: boolean): (number, number) + local g = M.g0 + by * S.w4 + bx + local nzc = S.nzc + local ca, cb + if bx > 0 then + ca = ((nzc[g - 1] ~= 0) and (1) or (0)) + elseif M.aL then + ca = ((nzc[g - 1] ~= 0) and (1) or (0)) + else + ca = ((intra) and (1) or (0)) + end + if by > 0 then + cb = ((nzc[g - S.w4] ~= 0) and (1) or (0)) + elseif M.aT then + cb = ((nzc[g - S.w4] ~= 0) and (1) or (0)) + else + cb = ((intra) and (1) or (0)) + end + return ca, cb +end + +@native local function chromaCond(S: any, M: any, tab: { number }, bx: number, by: number, intra: boolean): (number, number) + local cw = S.cw4 + local g = M.c0 + by * cw + bx + local ca, cb + if bx > 0 or M.aL then + ca = ((tab[g - 1] ~= 0) and (1) or (0)) + else + ca = ((intra) and (1) or (0)) + end + if by > 0 or M.aT then + cb = ((tab[g - cw] ~= 0) and (1) or (0)) + else + cb = ((intra) and (1) or (0)) + end + return ca, cb +end + +@native local function dcCond(S: any, M: any, bit: number, intra: boolean): (number, number) + local dc = S.dcTab + local a, b = leftAddr(S, M), topAddr(S, M) + local ca, cb + if a > 0 then + ca = (((dc[a] // bit) % 2 ~= 0) and (1) or (0)) + else + ca = ((intra) and (1) or (0)) + end + if b > 0 then + cb = (((dc[b] // bit) % 2 ~= 0) and (1) or (0)) + else + cb = ((intra) and (1) or (0)) + end + return ca, cb +end + +@native local function residuals(S: any, M: any): boolean + local kind = M.kind + local cbp = M.cbp + local intra = kind <= K_PCM + local dq = S.dq + local qp = M.qp + local w4, g0 = S.w4, M.g0 + local grid = S.nzc + local nz = M.nz + local c4 = M.c4 + local dcBits = 0 + if kind == K_I16 then + local ca, cb = dcCond(S, M, 1, intra) + if cbf(0, ca, cb) == 1 then + local n = block(0, M.dcY, 0, nil, 1) + if n < 0 then + return false + end + M.hasDcY = true + dcBits += 1 + end + end + local mul4 = dq.d4[((intra) and (1) or (4))][qp + 1] + if M.t8 == 1 then + local mul8 = dq.d8[((intra) and (1) or (2))][qp + 1] + for i8 = 0, 3 do + local bx, by = (i8 % 2) * 2, (i8 // 2) * 2 + local n = 0 + if (cbp // POW2[i8 + 1]) % 2 ~= 0 then + n = block(5, M.c8, i8 * 64, mul8, 64) + if n < 0 then + return false + end + end + local f = ((n > 0) and (1) or (0)) + local g = g0 + by * w4 + bx + grid[g], grid[g + 1], grid[g + w4], grid[g + w4 + 1] = f, f, f, f + nz[by * 4 + bx + 1], nz[by * 4 + bx + 2], nz[by * 4 + bx + 5], nz[by * 4 + bx + 6] = n, n, n, n + end + else + local ac = kind == K_I16 + local cat = ((ac) and (1) or (2)) + for i = 0, 15 do + local bx, by = BLK_X[i + 1], BLK_Y[i + 1] + local blk = by * 4 + bx + local n = 0 + if (cbp // POW2[i // 4 + 1]) % 2 ~= 0 then + local ca, cb = lumaCond(S, M, bx, by, intra) + if cbf(cat, ca, cb) == 1 then + n = block(cat, c4, blk * 16, mul4, 16) + if n < 0 then + return false + end + end + end + grid[g0 + by * w4 + bx] = ((n > 0) and (1) or (0)) + nz[blk + 1] = n + end + end + local chroma = cbp // 16 + local cw, c0 = S.cw4, M.c0 + local nzc = M.nzc + if chroma ~= 0 then + for plane = 0, 1 do + local bit = ((plane == 0) and (2) or (4)) + local ca, cb = dcCond(S, M, bit, intra) + if cbf(3, ca, cb) == 1 then + local n = block(3, M.dcC, plane * 4, nil, 1) + if n < 0 then + return false + end + M.hasDcC = true + dcBits += bit + end + end + end + local cc = M.cc + for plane = 0, 1 do + local tab = ((plane == 0) and (S.nzcCb) or (S.nzcCr)) + local mulc = dq.d4[(((intra) and (2) or (5))) + plane][(((plane == 0) and (M.qpc) or (M.qpc2))) + 1] + for blk = 0, 3 do + local bx, by = blk % 2, blk // 2 + local n = 0 + if chroma == 2 then + local ca, cb = chromaCond(S, M, tab, bx, by, intra) + if cbf(4, ca, cb) == 1 then + n = block(4, cc, (plane * 4 + blk) * 16, mulc, 16) + if n < 0 then + return false + end + end + end + tab[c0 + by * cw + bx] = ((n > 0) and (1) or (0)) + nzc[plane * 4 + blk + 1] = n + end + end + S.dcTab[M.addr + 1] = dcBits + return true +end + +@native local function setQp(S: any, M: any, delta: number): boolean + if delta < -26 or delta > 25 then + return false + end + local qp = (S.qp + delta + 52) % 52 + S.qp = qp + M.qp = qp + M.qpc = S.qpcOf[qp + 1] + M.qpc2 = S.qpc2Of[qp + 1] + S.lastQpd = delta ~= 0 + return true +end + +@native local function clearCounts(M: any) + local nz = M.nz + for i = 1, 16 do + nz[i] = 0 + end + local nzc = M.nzc + for i = 1, 8 do + nzc[i] = 0 + end +end + +local SUBB_PF = { 0, 1, 2, 3, 1, 1, 2, 2, 3, 3, 1, 2, 3 } +local SUBB_SHAPE = { 0, 0, 0, 0, 1, 2, 1, 2, 1, 2, 3, 3, 3 } +local SUB_N = { 1, 2, 2, 4 } +local SUB_W = { 2, 2, 1, 1 } +local SUB_H = { 2, 1, 2, 1 } +local BPAIR0 = { 1, 2, 1, 2, 1, 2, 3, 3, 3 } +local BPAIR1 = { 1, 2, 2, 1, 3, 3, 1, 2, 3 } + +@native local function intraMb(S: any, M: any, r: Bitstream.Reader, t: number): (boolean, string?) + local addr = M.addr + 1 + local w4, g0 = S.w4, M.g0 + fillRegion(S, M, S.rgt0, 0, 0, 4, 4, 0) + fillRegion(S, M, S.rgt1, 0, 0, 4, 4, 0) + fillMvd(S, M, S.mvd0, 0, 0, 4, 4, 0, 0) + fillMvd(S, M, S.mvd1, 0, 0, 4, 4, 0, 0) + clearCounts(M) + if t == 25 then + M.kind = K_PCM + -- pcm_alignment_zero_bit and the samples follow the terminate bin + local p = (bitPos() + 7) // 8 + if p + 384 > elimit then + return false, "truncated: I_PCM samples" + end + buffer.copy(M.pcm, 0, ebuf, p, 384) + engineInit(ebuf, p + 384, elimit) + M.qp = S.qp + M.qpc, M.qpc2 = 0, 0 + M.cbp = 0x2f + fillRegion(S, M, S.nzc, 0, 0, 4, 4, 16) + local cw, c0 = S.cw4, M.c0 + for j = 0, 1 do + for i = 0, 1 do + S.nzcCb[c0 + j * cw + i] = 16 + S.nzcCr[c0 + j * cw + i] = 16 + end + end + S.cbpTab[addr] = 0x2f + S.dcTab[addr] = 7 + S.cpmTab[addr] = 0 + S.lastQpd = false + Mb.recon(S, M) + return true + end + if t == 0 then + M.kind = K_I4 + if S.t8mode and t8Flag(S, M) == 1 then + M.kind = K_I8 + M.t8 = 1 + end + local ipm = M.ipm + local grid = S.ipm + if M.t8 == 1 then + for i8 = 0, 3 do + local bx, by = (i8 % 2) * 2, (i8 // 2) * 2 + local pred = Mb.predMode(S, M, bx, by) + local mode = pred + if decision(68) == 0 then + local rem = decision(69) + rem += decision(69) * 2 + rem += decision(69) * 4 + mode = ((rem < pred) and (rem) or (rem + 1)) + end + ipm[by * 4 + bx + 1] = mode + local g = g0 + by * w4 + bx + grid[g], grid[g + 1], grid[g + w4], grid[g + w4 + 1] = mode, mode, mode, mode + end + else + for i = 0, 15 do + local bx, by = BLK_X[i + 1], BLK_Y[i + 1] + local pred = Mb.predMode(S, M, bx, by) + local mode = pred + if decision(68) == 0 then + local rem = decision(69) + rem += decision(69) * 2 + rem += decision(69) * 4 + mode = ((rem < pred) and (rem) or (rem + 1)) + end + ipm[by * 4 + bx + 1] = mode + grid[g0 + by * w4 + bx] = mode + end + end + M.cpm = chromaPredMode(S, M) + S.cpmTab[addr] = M.cpm + M.cbp = cbpCabac(S, M) + else + M.kind = K_I16 + M.i16 = (t - 1) % 4 + M.cbp = ((t - 1) // 4) % 3 * 16 + (((t >= 13) and (15) or (0))) + M.cpm = chromaPredMode(S, M) + S.cpmTab[addr] = M.cpm + end + S.cbpTab[addr] = M.cbp + S.kind[addr] = M.kind + if M.cbp > 0 or M.kind == K_I16 then + if not setQp(S, M, qpDelta(S)) then + return false, "mb_qp_delta out of range" + end + else + setQp(S, M, 0) + end + S.t8Tab[addr] = M.t8 + if not residuals(S, M) then + return false, "bad residual" + end + Mb.recon(S, M) + return true +end + +@native local function interMb(S: any, M: any, r: Bitstream.Reader, t: number, isB: boolean): (boolean, string?) + clearCounts(M) + local n0, n1 = S.n0, S.n1 + local pf, sub, dir, ref0, ref1, mvd0, mvd1 = M.pf, M.sub, M.dir, M.ref0, M.ref1, M.mvd0, M.mvd1 + local rgt0, rgt1, g0, g1 = S.rgt0, S.rgt1, S.mvd0, S.mvd1 + for i = 1, 4 do + dir[i] = false + ref0[i], ref1[i] = 0, 0 + pf[i] = 0 + end + for i = 1, 32 do + mvd0[i], mvd1[i] = 0, 0 + end + local noSmall = true + local addr = M.addr + 1 + if isB and t == 0 then + M.kind = K_BDIRECT + M.part = 0 + noSmall = S.direct8x8 + fillRegion(S, M, rgt0, 0, 0, 4, 4, 0) + fillRegion(S, M, rgt1, 0, 0, 4, 4, 0) + fillMvd(S, M, g0, 0, 0, 4, 4, 0, 0) + fillMvd(S, M, g1, 0, 0, 4, 4, 0, 0) + elseif (not isB and t < 3) or (isB and t <= 21) then + M.kind = ((isB) and (K_B) or (K_P)) + if not isB then + M.part = t + pf[1], pf[2] = 1, 1 + elseif t <= 3 then + M.part = 0 + pf[1] = t + else + M.part = ((t % 2 == 0) and (1) or (2)) + local k = (t - 4) // 2 + 1 + pf[1], pf[2] = BPAIR0[k], BPAIR1[k] + end + local part = M.part + local n = ((part == 0) and (1) or (2)) + for l = 0, 1 do + local rgt = ((l == 0) and (rgt0) or (rgt1)) + local nr = ((l == 0) and (n0) or (n1)) + local refs = ((l == 0) and (ref0) or (ref1)) + for p = 1, n do + local x, y, w, h = 0, 0, 4, 4 + if part == 1 then + y, h = (p - 1) * 2, 2 + elseif part == 2 then + x, w = (p - 1) * 2, 2 + end + local uses = pf[p] >= 2 + if l == 0 then + uses = pf[p] % 2 == 1 + end + local v = 0 + if uses and nr > 1 then + v = refIdx(S, M, rgt, x, y) + if v < 0 or v >= nr then + return false, "ref_idx out of range" + end + end + refs[p] = v + fillRegion(S, M, rgt, x, y, w, h, ((uses and v > 0) and (1) or (0))) + end + end + for l = 0, 1 do + local grid = ((l == 0) and (g0) or (g1)) + local md = ((l == 0) and (mvd0) or (mvd1)) + for p = 1, n do + local x, y, w, h = 0, 0, 4, 4 + if part == 1 then + y, h = (p - 1) * 2, 2 + elseif part == 2 then + x, w = (p - 1) * 2, 2 + end + local uses = pf[p] >= 2 + if l == 0 then + uses = pf[p] % 2 == 1 + end + local mx, my = 0, 0 + if uses then + mx = mvd(S, M, grid, x, y, 0) + my = mvd(S, M, grid, x, y, 1) + end + md[2 * p - 1], md[2 * p] = mx, my + fillMvd(S, M, grid, x, y, w, h, ((mx < 0) and (-mx) or (mx)), ((my < 0) and (-my) or (my))) + end + end + else + -- P_8x8 (3) / P_8x8ref0 (4) / B_8x8 (22) + M.kind = ((isB) and (K_B) or (K_P)) + M.part = 3 + for i = 1, 4 do + if isB then + local s = bSubType() + pf[i] = SUBB_PF[s + 1] + sub[i] = SUBB_SHAPE[s + 1] + dir[i] = s == 0 + if s == 0 then + if not S.direct8x8 then + noSmall = false + end + elseif SUB_N[sub[i] + 1] > 1 then + noSmall = false + end + else + local s = pSubType() + pf[i] = 1 + sub[i] = s + if s > 0 then + noSmall = false + end + end + end + for l = 0, 1 do + local rgt = ((l == 0) and (rgt0) or (rgt1)) + local nr = ((l == 0) and (n0) or (n1)) + local refs = ((l == 0) and (ref0) or (ref1)) + for i = 1, 4 do + local x, y = ((i - 1) % 2) * 2, ((i - 1) // 2) * 2 + local uses = pf[i] >= 2 + if l == 0 then + uses = pf[i] % 2 == 1 + end + uses = uses and not dir[i] + local v = 0 + if uses and nr > 1 then + v = refIdx(S, M, rgt, x, y) + if v < 0 or v >= nr then + return false, "ref_idx out of range" + end + end + refs[i] = v + fillRegion(S, M, rgt, x, y, 2, 2, ((uses and v > 0) and (1) or (0))) + end + end + for l = 0, 1 do + local grid = ((l == 0) and (g0) or (g1)) + local md = ((l == 0) and (mvd0) or (mvd1)) + for i = 1, 4 do + local x0, y0 = ((i - 1) % 2) * 2, ((i - 1) // 2) * 2 + local uses = pf[i] >= 2 + if l == 0 then + uses = pf[i] % 2 == 1 + end + uses = uses and not dir[i] + if not uses then + fillMvd(S, M, grid, x0, y0, 2, 2, 0, 0) + else + local s = sub[i] + local w, h = SUB_W[s + 1], SUB_H[s + 1] + for k = 0, SUB_N[s + 1] - 1 do + local x, y = x0, y0 + if s == 1 then + y += k + elseif s == 2 then + x += k + elseif s == 3 then + x += k % 2 + y += k // 2 + end + local mx = mvd(S, M, grid, x, y, 0) + local my = mvd(S, M, grid, x, y, 1) + local p = (i - 1) * 4 + k + 1 + md[2 * p - 1], md[2 * p] = mx, my + fillMvd(S, M, grid, x, y, w, h, ((mx < 0) and (-mx) or (mx)), ((my < 0) and (-my) or (my))) + end + end + end + end + end + S.kind[addr] = M.kind + M.cbp = cbpCabac(S, M) + S.cbpTab[addr] = M.cbp + S.cpmTab[addr] = 0 + M.t8 = 0 + if M.cbp % 16 ~= 0 and S.t8mode and noSmall then + M.t8 = t8Flag(S, M) + end + S.t8Tab[addr] = M.t8 + if M.cbp > 0 then + if not setQp(S, M, qpDelta(S)) then + return false, "mb_qp_delta out of range" + end + else + setQp(S, M, 0) + end + if not residuals(S, M) then + return false, "bad residual" + end + Mb.recon(S, M) + return true +end + +@native local function macroblock(S: any, M: any, r: Bitstream.Reader): (boolean, string?) + local st = S.type + if st == 2 then + return intraMb(S, M, r, intraType(S, M, 3)) + elseif st == 0 then + local t = pMbType() + if t < 0 then + return intraMb(S, M, r, intraType(S, M, 17)) + end + return interMb(S, M, r, t, false) + end + local t = bMbType(S, M) + if t < 0 then + return intraMb(S, M, r, intraType(S, M, 32)) + end + return interMb(S, M, r, t, true) +end + +@native function Cabac.slice(S: any, M: any, r: Bitstream.Reader): (boolean, string?) + local p = (r.pos + 7) // 8 + local limit = r.size // 8 + if p >= limit then + return false, "truncated: slice data" + end + engineInit(r.buf, p, limit) + initContexts(S.qp, ((S.type == 2) and (0) or (S.cabacInit + 1))) + S.lastQpd = false + local addr = S.firstMb + local total = S.mbW * S.mbH + local st = S.type + local skipKind = ((st == 1) and (K_BSKIP) or (K_PSKIP)) + local hook = S.hook + local every = Mb.YIELD_MBS + while true do + if addr >= total then + return false, "slice data past the end of the picture" + end + Mb.start(S, M, addr) + if st ~= 2 and mbSkipFlag(S, M) == 1 then + Mb.skip(S, M, skipKind) + S.lastQpd = false + else + local ok, err = macroblock(S, M, r) + if not ok then + return false, err + end + end + addr += 1 + if hook and addr % every == 0 then + pcall(hook) -- (may yield: the engine state lives in this module's locals, see Decoder Options.yield) + end + if epos > elimit + 8 then + return false, "truncated: slice data" + end + if terminate() == 1 then + break + end + end + return true +end + +return Cabac +end +__FILES["codecs/video/H264/Cavlc"] = @native function() + + + +-- 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), +-- residual_block_cavlc with the 8x8 interleaving; coefficients are dequantised as they are placed. +local Bitstream = __include("codecs/video/H264/Bitstream") +local Tables = __include("codecs/video/H264/Tables") +local Mb = __include("codecs/video/H264/Mb") + +local u, u1, ue, se = Bitstream.u, Bitstream.u1, Bitstream.ue, Bitstream.se + +local K_I4, K_I8, K_I16, K_PCM, K_P, K_PSKIP, K_B, K_BSKIP, K_BDIRECT = Mb.K_I4, Mb.K_I8, Mb.K_I16, Mb.K_PCM, Mb.K_P, Mb.K_PSKIP, Mb.K_B, Mb.K_BSKIP, Mb.K_BDIRECT +local BLK_X, BLK_Y = Mb.BLK_X, Mb.BLK_Y + +local Cavlc = {} + +-- build(entries) -> l1, l2: a two-level lookup on 16 peeked bits. l1[(v >> 8) + 1] = value * 32 + length, or +-- -(base) of a second-level block l2[base + (v & 255)]; 0 = no code +@native local function build(entries: { { number } }): ({ number }, { number }) + local l1 = table.create(256, 0) + local l2 = {} + local nsub = 0 + for _, e in entries do + local code, len, val = e[1], e[2], e[3] + local packed = val * 32 + len + if len <= 8 then + local s = code * 2 ^ (8 - len) + for k = 0, 2 ^ (8 - len) - 1 do + l1[s + k + 1] = packed + end + else + local prefix = code // 2 ^ (len - 8) + local base = -l1[prefix + 1] + if base <= 0 then + base = nsub * 256 + 1 + nsub += 1 + for k = 0, 255 do + l2[base + k] = 0 + end + l1[prefix + 1] = -base + end + local s = (code % 2 ^ (len - 8)) * 2 ^ (16 - len) + for k = 0, 2 ^ (16 - len) - 1 do + l2[base + s + k] = packed + end + end + end + return l1, l2 +end + +-- coeff_token: CT1[class + 1], CT2[class + 1]; value = TotalCoeff * 4 + TrailingOnes +local CT1, CT2 = {}, {} +for t = 0, 4 do + local src = (Tables :: any)["COEFF_TOKEN_" .. t] + local entries = {} + for i = 1, #src, 4 do + table.insert(entries, { src[i], src[i + 1], src[i + 2] * 4 + src[i + 3] }) + end + CT1[t + 1], CT2[t + 1] = build(entries) +end + +-- total_zeros by tzVlcIndex (luma 1..15, chroma DC 1..3), run_before by min(zerosLeft, 7) +@native local function group(src: { number }, n: number): ({ { number } }, { { number } }) + local per = {} + for i = 1, n do + per[i] = {} + end + for i = 1, #src, 4 do + table.insert(per[src[i]], { src[i + 1], src[i + 2], src[i + 3] }) + end + local a, b = {}, {} + for i = 1, n do + a[i], b[i] = build(per[i]) + end + return a, b +end +local TZ1, TZ2 = group(Tables.TOTAL_ZEROS, 15) +local TZC1, TZC2 = group(Tables.TOTAL_ZEROS_CDC, 3) +local RB1, RB2 = group(Tables.RUN_BEFORE, 7) + +-- scans: coefficient index (1-based) -> raster position (0-based) +local ZZ4 = Tables.ZIGZAG4 +local ZZAC = table.create(15, 0) +for i = 1, 15 do + ZZAC[i] = ZZ4[i + 1] +end +local ZZ8I = {} -- [i4 + 1][k + 1] = raster position in the 8x8 block of the k-th coefficient of interleaved list i4 +for i4 = 0, 3 do + local t = table.create(16, 0) + for k = 0, 15 do + t[k + 1] = Tables.ZIGZAG8[4 * k + i4 + 1] + end + ZZ8I[i4 + 1] = t +end +local IDENT = { 0, 1, 2, 3 } + +local INTRA_CBP, INTER_CBP = Tables.INTRA_CBP, Tables.INTER_CBP + +local LEVEL = table.create(16, 0) +local RUN = table.create(16, 0) + +local peek = Bitstream.peekAt +local clz32 = Bitstream.clz32 +local P2 = Bitstream.P2 + +-- levels go to out[base + scan[i] + 1] as (level * mul[pos + 1] + div / 2) // div (mul nil: raw levels) +@native local function residual(r: Bitstream.Reader, nC: number, maxCoeff: number, out: { number }, base: number, scan: { number }, mul: { number }?, div: number): number + local b, n = r.buf, r.n + local pos = r.pos + local cls + if nC < 0 then + cls = 5 + elseif nC < 2 then + cls = 1 + elseif nC < 4 then + cls = 2 + elseif nC < 8 then + cls = 3 + else + cls = 4 + end + local v = peek(b, n, pos) // 65536 + local e = CT1[cls][v // 256 + 1] + if e < 0 then + e = CT2[cls][-e + v % 256] + end + if e == 0 then + return -1 + end + pos += e % 32 + local tok = e // 32 + local tc = tok // 4 + local t1 = tok % 4 + if tc == 0 then + r.pos = pos + return 0 + end + if tc > maxCoeff then + return -1 + end + -- levels + local w = peek(b, n, pos) + for i = 0, t1 - 1 do + LEVEL[i + 1] = 1 - 2 * ((w // P2[32 - i]) % 2) + end + pos += t1 + local suffixLength = ((tc > 10 and t1 < 3) and (1) or (0)) + for i = t1, tc - 1 do + w = peek(b, n, pos) + local prefix = if w == 0 then 32 else clz32(w) + if prefix > 28 then + return -1 + end + pos += prefix + 1 + local size = suffixLength + if prefix == 14 and suffixLength == 0 then + size = 4 + elseif prefix >= 15 then + size = prefix - 3 + end + local levelCode = (((prefix < 15) and (prefix) or (15))) * 2 ^ suffixLength + if size > 0 then + levelCode += peek(b, n, pos) // P2[33 - size] + pos += size + end + if prefix >= 15 and suffixLength == 0 then + levelCode += 15 + end + if prefix >= 16 then + levelCode += 2 ^ (prefix - 3) - 4096 + end + if i == t1 and t1 < 3 then + levelCode += 2 + end + local level + if levelCode % 2 == 0 then + level = (levelCode + 2) // 2 + else + level = -((levelCode + 1) // 2) + end + LEVEL[i + 1] = level + if suffixLength == 0 then + suffixLength = 1 + end + local a = ((level < 0) and (-level) or (level)) + if a > 3 * 2 ^ (suffixLength - 1) and suffixLength < 6 then + suffixLength += 1 + end + end + -- total_zeros + local zerosLeft = 0 + if tc < maxCoeff then + v = peek(b, n, pos) // 65536 + local l1, l2 + if maxCoeff == 4 then + l1, l2 = TZC1[tc], TZC2[tc] + else + l1, l2 = TZ1[tc], TZ2[tc] + end + e = l1[v // 256 + 1] + if e < 0 then + e = l2[-e + v % 256] + end + if e == 0 then + return -1 + end + pos += e % 32 + zerosLeft = e // 32 + if zerosLeft + tc > maxCoeff then + return -1 + end + end + -- run_before + for i = 0, tc - 2 do + local run = 0 + if zerosLeft > 0 then + local t = ((zerosLeft > 7) and (7) or (zerosLeft)) + v = peek(b, n, pos) // 65536 + e = RB1[t][v // 256 + 1] + if e < 0 then + e = RB2[t][-e + v % 256] + end + if e == 0 then + return -1 + end + pos += e % 32 + run = e // 32 + if run > zerosLeft then + return -1 + end + end + RUN[i + 1] = run + zerosLeft -= run + end + RUN[tc] = zerosLeft + r.pos = pos + -- place (highest frequency first) + local k = -1 + local half = div // 2 + for i = tc - 1, 0, -1 do + k += RUN[i + 1] + 1 + local p = scan[k + 1] + if mul then + out[base + p + 1] = (LEVEL[i + 1] * mul[p + 1] + half) // div + else + out[base + p + 1] = LEVEL[i + 1] + end + end + return tc +end +Cavlc.residual = residual + +local SUBB_PF = { 0, 1, 2, 3, 1, 1, 2, 2, 3, 3, 1, 2, 3 } +local SUBB_SHAPE = { 0, 0, 0, 0, 1, 2, 1, 2, 1, 2, 3, 3, 3 } +local SUB_N = { 1, 2, 2, 4 } +local BPAIR0 = { 1, 2, 1, 2, 1, 2, 3, 3, 3 } +local BPAIR1 = { 1, 2, 2, 1, 3, 3, 1, 2, 3 } + +@native local function refIdx(r: Bitstream.Reader, n: number): number + if n <= 1 then + return 0 + end + local v + if n == 2 then + v = 1 - u1(r) + else + v = ue(r) + end + if v >= n then + return -1 + end + return v +end + +@native local function residuals(S: any, M: any, r: Bitstream.Reader): (boolean, string?) + local kind = M.kind + local cbp = M.cbp + local intra = kind <= K_PCM + local dq = S.dq + local qp = M.qp + local w4, g0 = S.w4, M.g0 + local grid = S.nzc + local nz = M.nz + local c4 = M.c4 + if kind == K_I16 then + local tc = residual(r, Mb.nC(S, M, 0, 0), 16, M.dcY, 0, ZZ4, nil, 1) + if tc < 0 then + return false, "bad Intra16x16 DC residual" + end + M.hasDcY = tc > 0 + end + local mul4 = dq.d4[((intra) and (1) or (4))][qp + 1] + if M.t8 == 1 then + local mul8 = dq.d8[((intra) and (1) or (2))][qp + 1] + local c8 = M.c8 + for i8 = 0, 3 do + local bx0, by0 = (i8 % 2) * 2, (i8 // 2) * 2 + local sum = 0 + for i4 = 0, 3 do + local bx, by = bx0 + i4 % 2, by0 + i4 // 2 + local tc = 0 + if (cbp // P2[i8 + 1]) % 2 ~= 0 then + tc = residual(r, Mb.nC(S, M, bx, by), 16, c8, i8 * 64, ZZ8I[i4 + 1], mul8, 64) + if tc < 0 then + return false, "bad 8x8 luma residual" + end + end + grid[g0 + by * w4 + bx] = tc + sum += tc + end + nz[by0 * 4 + bx0 + 1] = sum + nz[by0 * 4 + bx0 + 2] = sum + nz[by0 * 4 + bx0 + 5] = sum + nz[by0 * 4 + bx0 + 6] = sum + end + else + local ac = kind == K_I16 + for i = 0, 15 do + local bx, by = BLK_X[i + 1], BLK_Y[i + 1] + local blk = by * 4 + bx + local tc = 0 + if (cbp // P2[i // 4 + 1]) % 2 ~= 0 then + if ac then + tc = residual(r, Mb.nC(S, M, bx, by), 15, c4, blk * 16, ZZAC, mul4, 16) + else + tc = residual(r, Mb.nC(S, M, bx, by), 16, c4, blk * 16, ZZ4, mul4, 16) + end + if tc < 0 then + return false, "bad luma residual" + end + end + grid[g0 + by * w4 + bx] = tc + nz[blk + 1] = tc + end + end + -- chroma + local chroma = cbp // 16 + local cw, c0 = S.cw4, M.c0 + local nzcCb, nzcCr = S.nzcCb, S.nzcCr + local nzc = M.nzc + if chroma ~= 0 then + local any = false + for plane = 0, 1 do + local tc = residual(r, -1, 4, M.dcC, plane * 4, IDENT, nil, 1) + if tc < 0 then + return false, "bad chroma DC residual" + end + if tc > 0 then + any = true + end + end + M.hasDcC = any + end + local cc = M.cc + for plane = 0, 1 do + local tab = ((plane == 0) and (nzcCb) or (nzcCr)) + local mulc = dq.d4[(((intra) and (2) or (5))) + plane][(((plane == 0) and (M.qpc) or (M.qpc2))) + 1] + for blk = 0, 3 do + local bx, by = blk % 2, blk // 2 + local tc = 0 + if chroma == 2 then + tc = residual(r, Mb.nCc(S, M, tab, bx, by), 15, cc, (plane * 4 + blk) * 16, ZZAC, mulc, 16) + if tc < 0 then + return false, "bad chroma AC residual" + end + end + tab[c0 + by * cw + bx] = tc + nzc[plane * 4 + blk + 1] = tc + end + end + return true +end + +@native local function setQp(S: any, M: any, delta: number): boolean + if delta < -26 or delta > 25 then + return false + end + local qp = (S.qp + delta + 52) % 52 + S.qp = qp + M.qp = qp + M.qpc = S.qpcOf[qp + 1] + M.qpc2 = S.qpc2Of[qp + 1] + return true +end + +@native local function clearLumaGrids(S: any, M: any, intra: boolean) + -- the CABAC-only grids stay zero for CAVLC; intra modes for non-NxN macroblocks are written by Mb.recon + local _ = intra + local nz = M.nz + for i = 1, 16 do + nz[i] = 0 + end + local nzc = M.nzc + for i = 1, 8 do + nzc[i] = 0 + end +end + +-- intra macroblock types 0..25 (table 7-11) +@native local function intraMb(S: any, M: any, r: Bitstream.Reader, t: number): (boolean, string?) + local addr = M.addr + 1 + if t == 25 then + M.kind = K_PCM + r.pos = (r.pos + 7) // 8 * 8 + local p = r.pos // 8 + if p + 384 > r.size // 8 then + return false, "truncated: I_PCM samples" + end + buffer.copy(M.pcm, 0, r.buf, p, 384) + r.pos += 3072 + M.qp = S.qp + M.qpc, M.qpc2 = 0, 0 + M.cbp = 0x2f + local w4, g0 = S.w4, M.g0 + for j = 0, 3 do + for i = 0, 3 do + S.nzc[g0 + j * w4 + i] = 16 + end + end + local cw, c0 = S.cw4, M.c0 + for j = 0, 1 do + for i = 0, 1 do + S.nzcCb[c0 + j * cw + i] = 16 + S.nzcCr[c0 + j * cw + i] = 16 + end + end + S.cbpTab[addr] = 0x2f + S.dcTab[addr] = 7 + S.cpmTab[addr] = 0 + S.qpdTab[addr] = 0 + Mb.recon(S, M) + return true + end + clearLumaGrids(S, M, true) + if t == 0 then + M.kind = K_I4 + if S.t8mode and u1(r) == 1 then + M.kind = K_I8 + M.t8 = 1 + end + local ipm = M.ipm + local grid = S.ipm + local w4, g0 = S.w4, M.g0 + if M.t8 == 1 then + for i8 = 0, 3 do + local bx, by = (i8 % 2) * 2, (i8 // 2) * 2 + local pred = Mb.predMode(S, M, bx, by) + local mode = pred + if u1(r) == 0 then + local rem = u(r, 3) + mode = ((rem < pred) and (rem) or (rem + 1)) + end + ipm[by * 4 + bx + 1] = mode + local g = g0 + by * w4 + bx + grid[g], grid[g + 1], grid[g + w4], grid[g + w4 + 1] = mode, mode, mode, mode + end + else + for i = 0, 15 do + local bx, by = BLK_X[i + 1], BLK_Y[i + 1] + local pred = Mb.predMode(S, M, bx, by) + local mode = pred + if u1(r) == 0 then + local rem = u(r, 3) + mode = ((rem < pred) and (rem) or (rem + 1)) + end + ipm[by * 4 + bx + 1] = mode + grid[g0 + by * w4 + bx] = mode + end + end + M.cpm = ue(r) + if M.cpm > 3 then + return false, "intra_chroma_pred_mode out of range" + end + local code = ue(r) + if code > 47 then + return false, "coded_block_pattern out of range" + end + M.cbp = INTRA_CBP[code + 1] + elseif t <= 24 then + M.kind = K_I16 + M.i16 = (t - 1) % 4 + M.cbp = ((t - 1) // 4) % 3 * 16 + (((t >= 13) and (15) or (0))) + M.cpm = ue(r) + if M.cpm > 3 then + return false, "intra_chroma_pred_mode out of range" + end + else + return false, "mb_type out of range" + end + S.cpmTab[addr] = M.cpm + S.cbpTab[addr] = M.cbp + if M.cbp > 0 or M.kind == K_I16 then + if not setQp(S, M, Bitstream.se(r)) then + return false, "mb_qp_delta out of range" + end + else + setQp(S, M, 0) + end + if r.pos > r.size then + return false, "truncated: macroblock" + end + local ok, err = residuals(S, M, r) + if not ok then + return false, err + end + Mb.recon(S, M) + return true +end + +-- the P (0..4) and B (0..22) inter macroblock types +@native local function interMb(S: any, M: any, r: Bitstream.Reader, t: number, isB: boolean): (boolean, string?) + clearLumaGrids(S, M, false) + local n0, n1 = S.n0, S.n1 + local pf, sub, dir, ref0, ref1, mvd0, mvd1 = M.pf, M.sub, M.dir, M.ref0, M.ref1, M.mvd0, M.mvd1 + for i = 1, 4 do + dir[i] = false + ref0[i], ref1[i] = 0, 0 + end + for i = 1, 32 do + mvd0[i], mvd1[i] = 0, 0 + end + local noSmall = true + if not isB then + M.kind = K_P + if t > 4 then + return false, "mb_type out of range" + end + M.part = ((t >= 3) and (3) or (t)) + pf[1], pf[2], pf[3], pf[4] = 1, 1, 1, 1 + if M.part == 3 then + for i = 1, 4 do + local s = ue(r) + if s > 3 then + return false, "sub_mb_type out of range" + end + sub[i] = s + if s > 0 then + noSmall = false + end + end + for i = 1, 4 do + local v = ((t == 4) and (0) or (refIdx(r, n0))) + if v < 0 then + return false, "ref_idx_l0 out of range" + end + ref0[i] = v + end + for i = 0, 3 do + for k = 0, SUB_N[sub[i + 1] + 1] - 1 do + local p = i * 4 + k + 1 + mvd0[2 * p - 1] = se(r) + mvd0[2 * p] = se(r) + end + end + else + local n = ((M.part == 0) and (1) or (2)) + for p = 1, n do + local v = refIdx(r, n0) + if v < 0 then + return false, "ref_idx_l0 out of range" + end + ref0[p] = v + end + for p = 1, n do + mvd0[2 * p - 1] = se(r) + mvd0[2 * p] = se(r) + end + end + else + if t == 0 then + M.kind = K_BDIRECT + M.part = 0 + if not S.direct8x8 then + noSmall = false + end + elseif t <= 21 then + M.kind = K_B + if t <= 3 then + M.part = 0 + pf[1] = t + else + M.part = ((t % 2 == 0) and (1) or (2)) + local k = (t - 4) // 2 + 1 + pf[1], pf[2] = BPAIR0[k], BPAIR1[k] + end + local n = ((M.part == 0) and (1) or (2)) + for p = 1, n do + if pf[p] % 2 == 1 then + local v = refIdx(r, n0) + if v < 0 then + return false, "ref_idx_l0 out of range" + end + ref0[p] = v + end + end + for p = 1, n do + if pf[p] >= 2 then + local v = refIdx(r, n1) + if v < 0 then + return false, "ref_idx_l1 out of range" + end + ref1[p] = v + end + end + for p = 1, n do + if pf[p] % 2 == 1 then + mvd0[2 * p - 1] = se(r) + mvd0[2 * p] = se(r) + end + end + for p = 1, n do + if pf[p] >= 2 then + mvd1[2 * p - 1] = se(r) + mvd1[2 * p] = se(r) + end + end + elseif t == 22 then + M.kind = K_B + M.part = 3 + for i = 1, 4 do + local s = ue(r) + if s > 12 then + return false, "sub_mb_type out of range" + end + pf[i] = SUBB_PF[s + 1] + sub[i] = SUBB_SHAPE[s + 1] + dir[i] = s == 0 + if s == 0 then + if not S.direct8x8 then + noSmall = false + end + elseif SUB_N[sub[i] + 1] > 1 then + noSmall = false + end + end + for i = 1, 4 do + if not dir[i] and pf[i] % 2 == 1 then + local v = refIdx(r, n0) + if v < 0 then + return false, "ref_idx_l0 out of range" + end + ref0[i] = v + end + end + for i = 1, 4 do + if not dir[i] and pf[i] >= 2 then + local v = refIdx(r, n1) + if v < 0 then + return false, "ref_idx_l1 out of range" + end + ref1[i] = v + end + end + for l = 0, 1 do + local mvd = ((l == 0) and (mvd0) or (mvd1)) + for i = 0, 3 do + local uses = pf[i + 1] >= 2 + if l == 0 then + uses = pf[i + 1] % 2 == 1 + end + if uses and not dir[i + 1] then + for k = 0, SUB_N[sub[i + 1] + 1] - 1 do + local p = i * 4 + k + 1 + mvd[2 * p - 1] = se(r) + mvd[2 * p] = se(r) + end + end + end + end + else + return false, "mb_type out of range" + end + end + local code = ue(r) + if code > 47 then + return false, "coded_block_pattern out of range" + end + M.cbp = INTER_CBP[code + 1] + M.t8 = 0 + if M.cbp % 16 ~= 0 and S.t8mode and noSmall then + M.t8 = u1(r) + end + local addr = M.addr + 1 + S.cbpTab[addr] = M.cbp + S.cpmTab[addr] = 0 + if M.cbp > 0 then + if not setQp(S, M, se(r)) then + return false, "mb_qp_delta out of range" + end + else + setQp(S, M, 0) + end + if r.pos > r.size then + return false, "truncated: macroblock" + end + local ok, err = residuals(S, M, r) + if not ok then + return false, err + end + Mb.recon(S, M) + return true +end + +@native local function macroblock(S: any, M: any, r: Bitstream.Reader): (boolean, string?) + local t = ue(r) + local st = S.type + if st == 2 then + return intraMb(S, M, r, t) + elseif st == 0 then + if t >= 5 then + return intraMb(S, M, r, t - 5) + end + return interMb(S, M, r, t, false) + end + if t >= 23 then + return intraMb(S, M, r, t - 23) + end + return interMb(S, M, r, t, true) +end + +@native function Cavlc.slice(S: any, M: any, r: Bitstream.Reader): (boolean, string?) + local addr = S.firstMb + local total = S.mbW * S.mbH + local st = S.type + local skipKind = ((st == 1) and (K_BSKIP) or (K_PSKIP)) + local more = true + local hook = S.hook + local every = Mb.YIELD_MBS + repeat + if st ~= 2 then + local run = ue(r) + if run > total - addr then + return false, "mb_skip_run past the end of the picture" + end + for _ = 1, run do + Mb.start(S, M, addr) + Mb.skip(S, M, skipKind) + addr += 1 + end + if run > 0 then + more = Bitstream.moreData(r) + end + end + if more then + if addr >= total then + return false, "slice data past the end of the picture" + end + Mb.start(S, M, addr) + local ok, err = macroblock(S, M, r) + if not ok then + return false, err + end + addr += 1 + if hook and addr % every == 0 then + pcall(hook) + end + if r.pos > r.size then + return false, "truncated: slice data" + end + more = Bitstream.moreData(r) + end + until not more + return true +end + +return Cavlc +end +__FILES["codecs/video/H264/Deblock"] = @native function() + + + +-- codecs/video/H264/Deblock: the in-loop deblocking filter of ITU-T H.264 8.7 for frame macroblocks, 8-bit 4:2:0 +-- (bS 8.7.2.1, alpha / beta / tC0 tables 8-16 / 8-17). Runs over the whole picture once its slices are decoded, which +-- equals filtering each macroblock as it is decoded. +local Tables = __include("codecs/video/H264/Tables") + +local readu8, writeu8 = buffer.readu8, buffer.writeu8 +local ALPHA, BETA, TC0 = Tables.ALPHA, Tables.BETA, Tables.TC0 + +local Deblock = {} + +local BS = table.create(4, 0) + +local min, max = math.min, math.max +@native local function clip3(lo: number, hi: number, v: number): number + return min(max(v, lo), hi) +end + +local abs = math.abs + +@native local function luma(b: buffer, o: number, across: number, along: number, qp: number, aOff: number, bOff: number) + local indexA = clip3(0, 51, qp + aOff) + local alpha = ALPHA[indexA + 13] + local beta = BETA[clip3(0, 51, qp + bOff) + 13] + if alpha == 0 or beta == 0 then + return + end + for seg = 0, 3 do + local bS = BS[seg + 1] + if bS > 0 then + local tc0 = TC0[(indexA + 12) * 4 + bS + 1] + for k = 0, 3 do + local q = o + (seg * 4 + k) * along + local p0 = readu8(b, q - across) + local q0 = readu8(b, q) + local p1 = readu8(b, q - 2 * across) + local q1 = readu8(b, q + across) + if abs(p0 - q0) < alpha and abs(p1 - p0) < beta and abs(q1 - q0) < beta then + local p2 = readu8(b, q - 3 * across) + local q2 = readu8(b, q + 2 * across) + local ap = abs(p2 - p0) + local aq = abs(q2 - q0) + if bS < 4 then + local tc = tc0 + (((ap < beta) and (1) or (0))) + (((aq < beta) and (1) or (0))) + local delta = clip3(-tc, tc, ((q0 - p0) * 4 + (p1 - q1) + 4) // 8) + writeu8(b, q - across, clip3(0, 255, p0 + delta)) + writeu8(b, q, clip3(0, 255, q0 - delta)) + if ap < beta then + writeu8(b, q - 2 * across, p1 + clip3(-tc0, tc0, (p2 + (p0 + q0 + 1) // 2 - 2 * p1) // 2)) + end + if aq < beta then + writeu8(b, q + across, q1 + clip3(-tc0, tc0, (q2 + (p0 + q0 + 1) // 2 - 2 * q1) // 2)) + end + else + local strong = abs(p0 - q0) < alpha // 4 + 2 + if ap < beta and strong then + local p3 = readu8(b, q - 4 * across) + writeu8(b, q - across, (p2 + 2 * p1 + 2 * p0 + 2 * q0 + q1 + 4) // 8) + writeu8(b, q - 2 * across, (p2 + p1 + p0 + q0 + 2) // 4) + writeu8(b, q - 3 * across, (2 * p3 + 3 * p2 + p1 + p0 + q0 + 4) // 8) + else + writeu8(b, q - across, (2 * p1 + p0 + q1 + 2) // 4) + end + if aq < beta and strong then + local q3 = readu8(b, q + 3 * across) + writeu8(b, q, (p1 + 2 * p0 + 2 * q0 + 2 * q1 + q2 + 4) // 8) + writeu8(b, q + across, (p0 + q0 + q1 + q2 + 2) // 4) + writeu8(b, q + 2 * across, (2 * q3 + 3 * q2 + q1 + q0 + p0 + 4) // 8) + else + writeu8(b, q, (2 * q1 + q0 + p1 + 2) // 4) + end + end + end + end + end + end +end + +-- chroma: bS of luma segment i // 2 +@native local function chroma(b: buffer, o: number, across: number, along: number, qp: number, aOff: number, bOff: number) + local indexA = clip3(0, 51, qp + aOff) + local alpha = ALPHA[indexA + 13] + local beta = BETA[clip3(0, 51, qp + bOff) + 13] + if alpha == 0 or beta == 0 then + return + end + for i = 0, 7 do + local bS = BS[i // 2 + 1] + if bS > 0 then + local q = o + i * along + local p0 = readu8(b, q - across) + local q0 = readu8(b, q) + local p1 = readu8(b, q - 2 * across) + local q1 = readu8(b, q + across) + if abs(p0 - q0) < alpha and abs(p1 - p0) < beta and abs(q1 - q0) < beta then + if bS < 4 then + local tc = TC0[(indexA + 12) * 4 + bS + 1] + 1 + local delta = clip3(-tc, tc, ((q0 - p0) * 4 + (p1 - q1) + 4) // 8) + writeu8(b, q - across, clip3(0, 255, p0 + delta)) + writeu8(b, q, clip3(0, 255, q0 - delta)) + else + writeu8(b, q - across, (2 * p1 + p0 + q1 + 2) // 4) + writeu8(b, q, (2 * q1 + q0 + p1 + 2) // 4) + end + end + end + end +end + +-- the bS 1 motion test of 8.7.2.1 +@native local function mvDiff(mvA: { number }, a: number, mvB: { number }, b: number): boolean + return abs(mvA[2 * a - 1] - mvB[2 * b - 1]) >= 4 or abs(mvA[2 * a] - mvB[2 * b]) >= 4 +end + +@native local function motionDiffers(pic: any, p: number, q: number): boolean + local uid0, uid1, mv0, mv1 = pic.uid0, pic.uid1, pic.mv0, pic.mv1 + local pa, pb, qa, qb = uid0[p], uid1[p], uid0[q], uid1[q] + local np = (((pa >= 0) and (1) or (0))) + (((pb >= 0) and (1) or (0))) + local nq = (((qa >= 0) and (1) or (0))) + (((qb >= 0) and (1) or (0))) + if np ~= nq then + return true + end + if np == 1 then + local pr, pm = pa, mv0 + if pa < 0 then + pr, pm = pb, mv1 + end + local qr, qm = qa, mv0 + if qa < 0 then + qr, qm = qb, mv1 + end + if pr ~= qr then + return true + end + return mvDiff(pm, p, qm, q) + elseif np == 0 then + return false + end + if not ((pa == qa and pb == qb) or (pa == qb and pb == qa)) then + return true + end + if pa ~= pb then + if pa == qa then + return mvDiff(mv0, p, mv0, q) or mvDiff(mv1, p, mv1, q) + end + return mvDiff(mv0, p, mv1, q) or mvDiff(mv1, p, mv0, q) + end + return (mvDiff(mv0, p, mv0, q) or mvDiff(mv1, p, mv1, q)) and (mvDiff(mv0, p, mv1, q) or mvDiff(mv1, p, mv0, q)) +end + +@native function Deblock.picture(S: any, pic: any, params: { any }) + local mbW, mbH = S.mbW, S.mbH + local w4 = S.w4 + local kind, sliceTab, qpTab, qpcTab, qpc2Tab, t8Tab = S.kind, S.sliceTab, S.qpTab, S.qpcTab, S.qpc2Tab, S.t8Tab + local nzDb = S.nzDb + local ys, cs = pic.ys, pic.cs + local Y, U, V = pic.y, pic.u, pic.v + local hook = S.hook + for my = 0, mbH - 1 do + if hook and my > 0 then + pcall(hook) + end + for mx = 0, mbW - 1 do + local addr = my * mbW + mx + 1 + local sn = sliceTab[addr] + local prm = params[sn] + if sn == 0 or not prm or prm[1] == 1 then + continue + end + local idc, aOff, bOff = prm[1], prm[2], prm[3] + local intraQ = kind[addr] <= 4 + local t8 = t8Tab[addr] == 1 + local qpQ, qpcQ, qpc2Q = qpTab[addr], qpcTab[addr], qpc2Tab[addr] + local g0 = my * 4 * w4 + mx * 4 + 1 + local lo = pic.yo + my * 16 * ys + mx * 16 + local co = pic.co + my * 8 * cs + mx * 8 + for dir = 0, 1 do + -- dir 0: vertical edges (left neighbour), dir 1: horizontal edges (top neighbour) + local nAddr = ((dir == 0) and (addr - 1) or (addr - mbW)) + local edgeOk = my > 0 + if dir == 0 then + edgeOk = mx > 0 + end + if edgeOk and idc == 2 and sliceTab[nAddr] ~= sn then + edgeOk = false + end + if edgeOk and sliceTab[nAddr] == 0 then + edgeOk = false + end + for e = 0, 3 do + if e == 0 and not edgeOk then + continue + end + if t8 and (e == 1 or e == 3) then + continue + end + local intraP = intraQ + local qpP, qpcP, qpc2P = qpQ, qpcQ, qpc2Q + if e == 0 then + intraP = kind[nAddr] <= 4 + qpP, qpcP, qpc2P = qpTab[nAddr], qpcTab[nAddr], qpc2Tab[nAddr] + end + local any = false + for k = 0, 3 do + local qg, pg + if dir == 0 then + qg = g0 + k * w4 + e + pg = qg - 1 + else + qg = g0 + e * w4 + k + pg = qg - w4 + end + local bS + if intraP or intraQ then + bS = ((e == 0) and (4) or (3)) + elseif nzDb[qg] ~= 0 or nzDb[pg] ~= 0 then + bS = 2 + elseif motionDiffers(pic, pg, qg) then + bS = 1 + else + bS = 0 + end + BS[k + 1] = bS + if bS > 0 then + any = true + end + end + if not any then + continue + end + local qpav = (qpP + qpQ + 1) // 2 + if dir == 0 then + luma(Y, lo + e * 4, 1, ys, qpav, aOff, bOff) + else + luma(Y, lo + e * 4 * ys, ys, 1, qpav, aOff, bOff) + end + if e % 2 == 0 then + local qc = (qpcP + qpcQ + 1) // 2 + local qc2 = (qpc2P + qpc2Q + 1) // 2 + if dir == 0 then + chroma(U, co + e * 2, 1, cs, qc, aOff, bOff) + chroma(V, co + e * 2, 1, cs, qc2, aOff, bOff) + else + chroma(U, co + e * 2 * cs, cs, 1, qc, aOff, bOff) + chroma(V, co + e * 2 * cs, cs, 1, qc2, aOff, bOff) + end + end + end + end + end + end +end + +return Deblock +end +__FILES["codecs/video/H264/Decoder"] = function() + +-- codecs/video/H264/Decoder: the decoding process above the macroblock layer (ITU-T H.264 8.1, 8.2, C.4): picture +-- boundaries (7.4.1.2.4), POC types 0 / 1 / 2 (8.2.1), frame_num gaps (8.2.5.2), list modification (8.2.4), marking +-- (8.2.5), output in POC order (num_reorder_frames, else the DPB size). +local Bitstream = __include("codecs/video/H264/Bitstream") +local Params = __include("codecs/video/H264/Params") +local Slice = __include("codecs/video/H264/Slice") +local Tables = __include("codecs/video/H264/Tables") +local Mb = __include("codecs/video/H264/Mb") +local Cavlc = __include("codecs/video/H264/Cavlc") +local Cabac = __include("codecs/video/H264/Cabac") +local Deblock = __include("codecs/video/H264/Deblock") +local Inter = __include("codecs/video/H264/Inter") +local Types = __include("Types") + +local PAD, PADC = Inter.PAD, Inter.PADC +local CHROMA_QP = Tables.CHROMA_QP + +local Decoder = {} +Decoder.__index = Decoder + +type Options = { + maxPixels: number?, + lowDelay: boolean?, + deblock: boolean?, + -- yield is pcall'ed (it can't throw through native code); the entropy decoders keep state in module locals, so no + -- other H.264 decode may run in the VM while one is suspended + yield: (() -> ())?, +} + +function Decoder.new(opts: Options?): any + local o = opts or {} + return setmetatable({ + opts = o, + maxPixels = o.maxPixels or 2 ^ 22, + spsTab = {}, + ppsTab = {}, + dqCache = {}, + cur = nil, + curSh = nil, + S = nil, + M = Mb.new(), + refs = {}, -- reference pictures (short and long term) + waiting = {}, -- decoded pictures not output yet + out = {}, + uid = 0, + prevRefFrameNum = 0, + prevPocMsb = 0, + prevPocLsb = 0, + prevFrameNumOffset = 0, + prevFrameNum = 0, + maxLongTermIdx = -1, + pool = {}, + gray = nil, + frames = 0, + errors = 0, + lastError = nil, + fatal = nil, + seqW = 0, + seqH = 0, + }, Decoder) +end + +local function newPicture(self: any, sps: any): any + local mbW, mbH = sps.mbWidth, sps.mbHeight + local pool = self.pool + for i = #pool, 1, -1 do + local p = pool[i] + if p.mbW == mbW and p.mbH == mbH then + table.remove(pool, i) + return p + end + end + local w, h = mbW * 16, mbH * 16 + local ys = w + 2 * PAD + local cs = w // 2 + 2 * PADC + local n4 = mbW * mbH * 16 + return { + mbW = mbW, + mbH = mbH, + ys = ys, + cs = cs, + yo = PAD * ys + PAD, + co = PADC * cs + PADC, + y = buffer.create(ys * (h + 2 * PAD)), + u = buffer.create(cs * (h // 2 + 2 * PADC)), + v = buffer.create(cs * (h // 2 + 2 * PADC)), + mbIntra = table.create(mbW * mbH, true), + ref0 = table.create(n4, -1), + ref1 = table.create(n4, -1), + uid0 = table.create(n4, -1), + uid1 = table.create(n4, -1), + mv0 = table.create(n4 * 2, 0), + mv1 = table.create(n4 * 2, 0), + uid = 0, + poc = 0, + frameNum = 0, + long = false, + short = false, + longIdx = 0, + waiting = false, + pts = 0, + } +end + +local function release(self: any, p: any) + if not p.short and not p.long and not p.waiting and p ~= self.cur and p ~= self.gray then + for _, q in self.pool do + if q == p then + return + end + end + table.insert(self.pool, p) + end +end + +local function grayPicture(self: any, sps: any): any + local g = self.gray + if g and g.mbW == sps.mbWidth and g.mbH == sps.mbHeight then + return g + end + g = newPicture(self, sps) + buffer.fill(g.y, 0, 128) + buffer.fill(g.u, 0, 128) + buffer.fill(g.v, 0, 128) + self.uid += 1 + g.uid = self.uid + self.gray = g + return g +end + +local function emit(self: any, p: any) + p.waiting = false + local sps = p.sps + local W, H = sps.width, sps.height + local img = Types.Image.new(W, H, "yuv420p") + local px = img.pixels + local cx, cy = sps.cropX, sps.cropY + for y = 0, H - 1 do + buffer.copy(px, y * W, p.y, p.yo + (cy + y) * p.ys + cx, W) + end + local cw, ch = (W + 1) // 2, (H + 1) // 2 + local ub, vb = W * H, W * H + cw * ch + for y = 0, ch - 1 do + buffer.copy(px, ub + y * cw, p.u, p.co + (cy // 2 + y) * p.cs + cx // 2, cw) + buffer.copy(px, vb + y * cw, p.v, p.co + (cy // 2 + y) * p.cs + cx // 2, cw) + end + img.meta.source = { format = "h264", bitDepth = 8, profile = sps.profile, level = sps.level, poc = p.poc, keyframe = p.idr } + if sps.sarW and sps.sarH then + img.meta.sar = { sps.sarW, sps.sarH } + end + img.meta.yuv = { range = if sps.fullRange then "full" else "limited", matrix = if sps.matrix == 1 then "bt709" else "bt601" } + table.insert(self.out, { image = img, pts = p.pts, duration = 0, poc = p.poc, keyframe = p.idr }) + release(self, p) +end + +local function bump(self: any, keep: number) + local w = self.waiting + while #w > keep do + local best = 1 + for i = 2, #w do + if w[i].poc < w[best].poc then + best = i + end + end + local p = table.remove(w, best) + emit(self, p) + end +end + +local function reorderDepth(self: any, sps: any): number + if self.opts.lowDelay then + return 0 + end + if sps.numReorderFrames then + return sps.numReorderFrames + end + if sps.pocType == 2 then + return 0 + end + return sps.maxDecFrameBuffering or sps.maxDpbFrames +end + +local function shortRefs(self: any): { any } + local t = {} + for _, p in self.refs do + if p.short then + table.insert(t, p) + end + end + return t +end + +local function longRefs(self: any): { any } + local t = {} + for _, p in self.refs do + if p.long then + table.insert(t, p) + end + end + table.sort(t, function(a, b) + return a.longIdx < b.longIdx + end) + return t +end + +local function picNums(self: any, sh: any) + local maxFrameNum = 2 ^ sh.sps.log2MaxFrameNum + for _, p in self.refs do + if p.short then + p.picNum = if p.frameNum > sh.frameNum then p.frameNum - maxFrameNum else p.frameNum + end + end +end + +local function modify(self: any, list: { any }, ops: { number }, n: number, sh: any): boolean + if #ops == 0 then + return true + end + local maxPicNum = 2 ^ sh.sps.log2MaxFrameNum + local curr = sh.frameNum + local pred = curr + local idx = 0 + for i = 1, #ops, 2 do + local idc, v = ops[i], ops[i + 1] + local pic = nil + if idc == 0 or idc == 1 then + local absDiff = v + 1 + if absDiff > maxPicNum then + return false + end + local noWrap + if idc == 0 then + noWrap = pred - absDiff + if noWrap < 0 then + noWrap += maxPicNum + end + else + noWrap = pred + absDiff + if noWrap >= maxPicNum then + noWrap -= maxPicNum + end + end + pred = noWrap + local picNum = if noWrap > curr then noWrap - maxPicNum else noWrap + for _, p in self.refs do + if p.short and p.picNum == picNum then + pic = p + break + end + end + elseif idc == 2 then + for _, p in self.refs do + if p.long and p.longIdx == v then + pic = p + break + end + end + else + return false + end + if not pic then + return false + end + if idx >= n then + return false + end + table.insert(list, idx + 1, pic) + local k = idx + 2 + while k <= #list do + if list[k] == pic then + table.remove(list, k) + else + k += 1 + end + end + idx += 1 + end + return true +end + +local function buildLists(self: any, sh: any, cur: any): ({ any }, { any }, boolean) + picNums(self, sh) + local list0, list1 = {}, {} + local shorts = shortRefs(self) + local longs = longRefs(self) + if sh.type == Slice.P then + table.sort(shorts, function(a, b) + return a.picNum > b.picNum + end) + for _, p in shorts do + table.insert(list0, p) + end + for _, p in longs do + table.insert(list0, p) + end + else + local before, after = {}, {} + for _, p in shorts do + if p.poc < cur.poc then + table.insert(before, p) + else + table.insert(after, p) + end + end + table.sort(before, function(a, b) + return a.poc > b.poc + end) + table.sort(after, function(a, b) + return a.poc < b.poc + end) + for _, p in before do + table.insert(list0, p) + end + for _, p in after do + table.insert(list0, p) + end + for _, p in after do + table.insert(list1, p) + end + for _, p in before do + table.insert(list1, p) + end + for _, p in longs do + table.insert(list0, p) + table.insert(list1, p) + end + if #list1 > 1 and #list0 == #list1 then + local same = true + for i = 1, #list0 do + if list0[i] ~= list1[i] then + same = false + break + end + end + if same then + list1[1], list1[2] = list1[2], list1[1] + end + end + end + local n0, n1 = sh.numRefIdxL0, sh.numRefIdxL1 + for i = #list0, n0 + 1, -1 do + list0[i] = nil + end + for i = #list1, n1 + 1, -1 do + list1[i] = nil + end + local ok = modify(self, list0, sh.mod0 or {}, n0, sh) + if sh.type == Slice.B then + ok = modify(self, list1, sh.mod1 or {}, n1, sh) and ok + end + for i = #list0, n0 + 1, -1 do + list0[i] = nil + end + for i = #list1, n1 + 1, -1 do + list1[i] = nil + end + return list0, list1, ok +end + +local function unmark(self: any, p: any) + p.short = false + p.long = false + for i, q in self.refs do + if q == p then + table.remove(self.refs, i) + break + end + end + release(self, p) +end + +local function slidingWindow(self: any, sps: any, frameNum: number) + local maxRefs = math.max(sps.maxRefFrames, 1) + local maxFrameNum = 2 ^ sps.log2MaxFrameNum + while #self.refs >= maxRefs do + local oldest, ow = nil, math.huge + for _, p in self.refs do + if p.short then + local w = if p.frameNum > frameNum then p.frameNum - maxFrameNum else p.frameNum + if w < ow then + oldest, ow = p, w + end + end + end + if not oldest then + -- only long-term references left: drop the lowest index (bad stream) + oldest = self.refs[1] + end + unmark(self, oldest) + end +end + +local function addRef(self: any, p: any) + for _, q in self.refs do + if q == p then + return + end + end + table.insert(self.refs, p) +end + +-- 8.2.5 marking after a reference picture; true when MMCO 5 was present +local function mark(self: any, cur: any, sh: any): boolean + local sps = sh.sps + if sh.idr then + while #self.refs > 0 do + unmark(self, self.refs[1]) + end + if sh.longTermReference then + cur.long = true + cur.longIdx = 0 + self.maxLongTermIdx = 0 + else + cur.short = true + self.maxLongTermIdx = -1 + end + addRef(self, cur) + return false + end + local mmco5 = false + local becameLong = false + if sh.adaptive and sh.mmco then + picNums(self, sh) + local ops = sh.mmco + for i = 1, #ops, 3 do + local op, a, b = ops[i], ops[i + 1], ops[i + 2] + if op == 1 then + local picNum = sh.frameNum - a + for _, p in self.refs do + if p.short and p.picNum == picNum then + unmark(self, p) + break + end + end + elseif op == 2 then + for _, p in self.refs do + if p.long and p.longIdx == a then + unmark(self, p) + break + end + end + elseif op == 3 then + local picNum = sh.frameNum - a + for _, p in self.refs do + if p.long and p.longIdx == b then + unmark(self, p) + break + end + end + for _, p in self.refs do + if p.short and p.picNum == picNum then + p.short = false + p.long = true + p.longIdx = b + break + end + end + elseif op == 4 then + self.maxLongTermIdx = a - 1 + local drop = {} + for _, p in self.refs do + if p.long and p.longIdx > self.maxLongTermIdx then + table.insert(drop, p) + end + end + for _, p in drop do + unmark(self, p) + end + elseif op == 5 then + while #self.refs > 0 do + unmark(self, self.refs[1]) + end + self.maxLongTermIdx = -1 + mmco5 = true + elseif op == 6 then + for _, p in self.refs do + if p.long and p.longIdx == b then + unmark(self, p) + break + end + end + cur.long = true + cur.longIdx = b + becameLong = true + end + end + else + slidingWindow(self, sps, sh.frameNum) + end + if not becameLong then + cur.short = true + end + -- a bad stream may leave too many references + local maxRefs = math.max(sps.maxRefFrames, 1) + if #self.refs >= maxRefs and not becameLong then + slidingWindow(self, sps, sh.frameNum) + end + addRef(self, cur) + return mmco5 +end + +local function computePoc(self: any, sh: any): (number, number) + local sps = sh.sps + local maxFrameNum = 2 ^ sps.log2MaxFrameNum + if sps.pocType == 0 then + local prevMsb, prevLsb = self.prevPocMsb, self.prevPocLsb + if sh.idr then + prevMsb, prevLsb = 0, 0 + end + local maxLsb = 2 ^ sps.log2MaxPocLsb + local lsb = sh.pocLsb + local msb + if lsb < prevLsb and prevLsb - lsb >= maxLsb / 2 then + msb = prevMsb + maxLsb + elseif lsb > prevLsb and lsb - prevLsb > maxLsb / 2 then + msb = prevMsb - maxLsb + else + msb = prevMsb + end + local top = msb + lsb + local bottom = top + sh.deltaPocBottom + sh.pocMsb = msb + return math.min(top, bottom), top + end + local offset + if sh.idr then + offset = 0 + elseif self.prevFrameNum > sh.frameNum then + offset = self.prevFrameNumOffset + maxFrameNum + else + offset = self.prevFrameNumOffset + end + sh.frameNumOffset = offset + if sps.pocType == 1 then + local n = #sps.offsetsForRefFrame + local absFrameNum = if n ~= 0 then offset + sh.frameNum else 0 + if sh.nalRefIdc == 0 and absFrameNum > 0 then + absFrameNum -= 1 + end + local expected = 0 + if absFrameNum > 0 then + local cycle = (absFrameNum - 1) // n + local inCycle = (absFrameNum - 1) % n + expected = cycle * sps.expectedDeltaPerCycle + for i = 1, inCycle + 1 do + expected += sps.offsetsForRefFrame[i] + end + end + if sh.nalRefIdc == 0 then + expected += sps.offsetNonRef + end + local top = expected + sh.deltaPoc0 + local bottom = top + sps.offsetTopToBottom + sh.deltaPoc1 + return math.min(top, bottom), top + end + local t + if sh.idr then + t = 0 + elseif sh.nalRefIdc == 0 then + t = 2 * (offset + sh.frameNum) - 1 + else + t = 2 * (offset + sh.frameNum) + end + return t, t +end + +local function setupGrids(self: any, sps: any) + local mbW, mbH = sps.mbWidth, sps.mbHeight + if self.S and self.S.mbW == mbW and self.S.mbH == mbH then + return + end + local S = Mb.grids(mbW, mbH) + S.mbW, S.mbH = mbW, mbH + S.w4 = mbW * 4 + S.cw4 = mbW * 2 + S.qpcOf = table.create(52, 0) + S.qpc2Of = table.create(52, 0) + self.S = S +end + +-- fill a frame_num gap with "non-existing" frames (8.2.5.2), concealed as copies of the latest reference +local function fillGap(self: any, sh: any) + local sps = sh.sps + local maxFrameNum = 2 ^ sps.log2MaxFrameNum + local fn = (self.prevRefFrameNum + 1) % maxFrameNum + local guard = 0 + while fn ~= sh.frameNum and guard < 32 do + guard += 1 + local src = nil + for _, p in self.refs do + if p.short and (src == nil or p.decodeOrder > src.decodeOrder) then + src = p + end + end + local p = newPicture(self, sps) + if src then + buffer.copy(p.y, 0, src.y) + buffer.copy(p.u, 0, src.u) + buffer.copy(p.v, 0, src.v) + else + local g = grayPicture(self, sps) + buffer.copy(p.y, 0, g.y) + buffer.copy(p.u, 0, g.u) + buffer.copy(p.v, 0, g.v) + end + for i = 1, #p.mbIntra do + p.mbIntra[i] = true + end + self.uid += 1 + p.uid = self.uid + p.frameNum = fn + p.poc = if src then src.poc else 0 + p.sps = sps + p.idr = false + p.decodeOrder = self.frames + p.long = false + slidingWindow(self, sps, fn) + p.short = true + addRef(self, p) + self.prevRefFrameNum = fn + self.prevFrameNum = fn + fn = (fn + 1) % maxFrameNum + end +end + +local function startPicture(self: any, sh: any, pts: number?) + local sps = sh.sps + if sps.mbWidth ~= self.seqW or sps.mbHeight ~= self.seqH then + -- a new sequence size: output everything, drop the references + bump(self, 0) + while #self.refs > 0 do + unmark(self, self.refs[1]) + end + self.pool = {} + self.seqW, self.seqH = sps.mbWidth, sps.mbHeight + end + setupGrids(self, sps) + if not sh.idr then + local maxFrameNum = 2 ^ sps.log2MaxFrameNum + if sh.frameNum ~= self.prevRefFrameNum and sh.frameNum ~= (self.prevRefFrameNum + 1) % maxFrameNum then + fillGap(self, sh) + end + end + local p = newPicture(self, sps) + self.uid += 1 + p.uid = self.uid + p.sps = sps + p.frameNum = sh.frameNum + p.idr = sh.idr + p.refIdc = sh.nalRefIdc + p.short, p.long, p.waiting = false, false, false + p.poc, p.topPoc = computePoc(self, sh) + p.pts = pts or self.frames + p.decodeOrder = self.frames + self.frames += 1 + self.cur = p + self.curSh = sh + self.decoded = 0 + self.sliceNum = 0 + self.sliceParams = {} + local S = self.S + local st = S.sliceTab + for i = 1, #st do + st[i] = 0 + end + S.pic = p + S.hook = self.opts.yield +end + +local function conceal(self: any, p: any) + local S = self.S + local st = S.sliceTab + local src = nil + for _, q in self.refs do + if q ~= p and (src == nil or q.decodeOrder > src.decodeOrder) then + src = q + end + end + local mbW = S.mbW + for addr = 1, #st do + if st[addr] == 0 then + local mx, my = (addr - 1) % mbW, (addr - 1) // mbW + for y = 0, 15 do + local o = p.yo + (my * 16 + y) * p.ys + mx * 16 + if src then + buffer.copy(p.y, o, src.y, o, 16) + else + buffer.fill(p.y, o, 128, 16) + end + end + for y = 0, 7 do + local o = p.co + (my * 8 + y) * p.cs + mx * 8 + if src then + buffer.copy(p.u, o, src.u, o, 8) + buffer.copy(p.v, o, src.v, o, 8) + else + buffer.fill(p.u, o, 128, 8) + buffer.fill(p.v, o, 128, 8) + end + end + p.mbIntra[addr] = true + local g0 = my * 4 * S.w4 + mx * 4 + 1 + for j = 0, 3 do + for i = 0, 3 do + local g = g0 + j * S.w4 + i + p.ref0[g], p.ref1[g], p.uid0[g], p.uid1[g] = -1, -1, -1, -1 + end + end + S.kind[addr] = 0 + end + end +end + +local function finishPicture(self: any) + local p = self.cur + if not p then + return + end + local sh = self.curSh + local S = self.S + if self.decoded < S.mbW * S.mbH then + conceal(self, p) + end + local hook = self.opts.yield + if self.opts.deblock ~= false then + Deblock.picture(S, p, self.sliceParams) + end + if hook then + pcall(hook) + end + local w, h = S.mbW * 16, S.mbH * 16 + Inter.extend(p.y, p.yo, p.ys, w, h, PAD) + Inter.extend(p.u, p.co, p.cs, w // 2, h // 2, PADC) + Inter.extend(p.v, p.co, p.cs, w // 2, h // 2, PADC) + local mmco5 = false + if sh.nalRefIdc ~= 0 then + mmco5 = mark(self, p, sh) + end + if sh.idr or mmco5 then + bump(self, 0) + end + if mmco5 then + -- 8.2.1: after MMCO 5 the picture counts as frame_num 0 with its POC moved to 0 + local t = p.poc + p.topPoc -= t + p.poc = 0 + p.frameNum = 0 + end + if sh.nalRefIdc ~= 0 then + if mmco5 then + self.prevPocMsb = 0 + self.prevPocLsb = p.topPoc + self.prevRefFrameNum = 0 + else + self.prevPocMsb = sh.pocMsb or 0 + self.prevPocLsb = sh.pocLsb + self.prevRefFrameNum = sh.frameNum + end + end + if mmco5 then + self.prevFrameNumOffset = 0 + self.prevFrameNum = 0 + else + self.prevFrameNumOffset = sh.frameNumOffset or 0 + self.prevFrameNum = sh.frameNum + end + self.cur = nil + self.curSh = nil + p.waiting = true + table.insert(self.waiting, p) + bump(self, reorderDepth(self, sh.sps)) + release(self, p) +end + +local function sameNewPicture(a: any, b: any): boolean + -- 7.4.1.2.4: true when slice header b starts a new primary picture after a + if a.frameNum ~= b.frameNum or a.ppsId ~= b.ppsId or a.idr ~= b.idr then + return true + end + if (a.nalRefIdc == 0) ~= (b.nalRefIdc == 0) then + return true + end + local sps = b.sps + if sps.pocType == 0 and (a.pocLsb ~= b.pocLsb or a.deltaPocBottom ~= b.deltaPocBottom) then + return true + end + if sps.pocType == 1 and (a.deltaPoc0 ~= b.deltaPoc0 or a.deltaPoc1 ~= b.deltaPoc1) then + return true + end + if a.idr and b.idr and a.idrPicId ~= b.idrPicId then + return true + end + return false +end + +local function fail(self: any, msg: string) + self.errors += 1 + self.lastError = msg +end + +local function decodeSlice(self: any, sh: any, r: Bitstream.Reader) + local S = self.S + local cur = self.cur + local sps, pps = sh.sps, sh.pps + self.sliceNum += 1 + S.slice = self.sliceNum + self.sliceParams[self.sliceNum] = { sh.deblock, sh.alphaOffset, sh.betaOffset } + S.type = sh.type + S.firstMb = sh.firstMb + if sh.firstMb >= S.mbW * S.mbH then + fail(self, "first_mb_in_slice out of range") + return + end + S.qp = sh.qp + for q = 0, 51 do + S.qpcOf[q + 1] = CHROMA_QP[math.clamp(q + pps.chromaQpOffset, 0, 51) + 1] + S.qpc2Of[q + 1] = CHROMA_QP[math.clamp(q + pps.chromaQpOffset2, 0, 51) + 1] + end + S.dq = Params.dequant(sps, pps, self.dqCache) + S.t8mode = pps.transform8x8 + S.constrainedIntra = pps.constrainedIntra + S.direct8x8 = sps.direct8x8 + S.directSpatial = sh.directSpatial + S.n0, S.n1 = sh.numRefIdxL0, sh.numRefIdxL1 + S.cabacInit = sh.cabacInit + local list0, list1 = {}, {} + if sh.type ~= Slice.I then + local ok + list0, list1, ok = buildLists(self, sh, cur) + if not ok then + fail(self, "bad ref_pic_list_modification") + end + if #list0 == 0 then + list0 = { grayPicture(self, sps) } + end + if sh.type == Slice.B and #list1 == 0 then + list1 = { list0[1] } + end + end + S.list0, S.list1 = list0, list1 + local uids0, uids1 = {}, {} + local uidToRef0 = {} + for i, p in list0 do + uids0[i] = p.uid + if uidToRef0[p.uid] == nil then + uidToRef0[p.uid] = i - 1 + end + end + for i, p in list1 do + uids1[i] = p.uid + end + S.uids0, S.uids1, S.uidToRef0 = uids0, uids1, uidToRef0 + S.weightMode = sh.weightMode + S.weights0, S.weights1 = sh.weights0 or {}, sh.weights1 or {} + S.lumaDenom, S.chromaDenom = sh.lumaDenom or 0, sh.chromaDenom or 0 + if sh.type == Slice.B then + local col = list1[1] + S.colPic = col + S.colShort = not col.long + local dsf = {} + for i, p in list0 do + local d = nil + if not p.long then + d = Mb.distScale(cur.poc, p.poc, col.poc) + end + dsf[i] = d or false + end + S.dsf = dsf + if sh.weightMode == 2 then + local imp = table.create(32 * 32, 32) + for i0, p0 in list0 do + for i1, p1 in list1 do + local w1 = 32 + if not p0.long and not p1.long and p1.poc ~= p0.poc then + local d = Mb.distScale(cur.poc, p0.poc, p1.poc) + if d and d // 4 >= -64 and d // 4 <= 128 then + w1 = d // 4 + end + end + imp[(i0 - 1) * 32 + i1] = w1 + end + end + S.implicit = imp + end + end + local before = 0 + local st = S.sliceTab + local ok, err + if pps.cabac then + ok, err = Cabac.slice(S, self.M, r) + else + ok, err = Cavlc.slice(S, self.M, r) + end + for i = 1, #st do + if st[i] ~= 0 then + before += 1 + end + end + self.decoded = before + if not ok then + fail(self, err or "bad slice data") + end +end + +function Decoder.nal(self: any, buf: buffer, off: number, len: number, pts: number?) + if len < 1 then + return + end + local hdr = buffer.readu8(buf, off) + if hdr >= 128 then + fail(self, "forbidden_zero_bit set") + return + end + local refIdc = bit32.rshift(hdr, 5) + local t = bit32.band(hdr, 31) + if t == 7 then + local sps, err = Params.sps(Bitstream.reader(buf, off, len, 1)) + if not sps then + if err and string.sub(err, 1, 6) == "limit:" then + self.fatal = err + end + fail(self, err or "bad sps") + return + end + if sps.chromaFormat ~= 1 then + self.unsupported = "chroma format " .. ({ [0] = "4:0:0 (monochrome)", [2] = "4:2:2", [3] = "4:4:4" })[sps.chromaFormat] + elseif sps.bitDepth ~= 8 or sps.bitDepthC ~= 8 then + self.unsupported = "bit depth " .. sps.bitDepth + elseif not sps.frameMbsOnly then + self.unsupported = "interlaced coding (PAFF / MBAFF)" + end + if sps.mbWidth * sps.mbHeight * 256 > self.maxPixels then + self.fatal = "limit: picture of " .. sps.mbWidth * 16 .. " x " .. sps.mbHeight * 16 .. " over maxPixels" + end + self.spsTab[sps.id] = sps + return + elseif t == 8 then + local pps, err = Params.pps(Bitstream.reader(buf, off, len, 1), self.spsTab) + if not pps then + if err and string.sub(err, 1, 12) == "unsupported:" then + self.unsupported = string.sub(err, 14) + end + fail(self, err or "bad pps") + return + end + self.ppsTab[pps.id] = pps + return + elseif t == 1 or t == 5 then + local r = Bitstream.reader(buf, off, len, 1) + local sh, err = Slice.header(r, t, refIdc, self.spsTab, self.ppsTab) + if not sh then + if err and string.sub(err, 1, 12) == "unsupported:" then + self.unsupported = string.sub(err, 14) + end + fail(self, err or "bad slice header") + return + end + local sps = sh.sps + if sps.chromaFormat ~= 1 or sps.bitDepth ~= 8 or sps.bitDepthC ~= 8 or sps.bypass or not sps.frameMbsOnly then + self.unsupported = self.unsupported or "profile features (chroma format / bit depth / lossless)" + return + end + if sps.mbWidth * sps.mbHeight * 256 > self.maxPixels then + self.fatal = "limit: picture over maxPixels" + return + end + if sh.redundantPicCnt and sh.redundantPicCnt > 0 then + return + end + if self.cur and (sameNewPicture(self.curSh, sh) or (sh.firstMb == 0 and self.decoded > 0)) then + finishPicture(self) + end + if not self.cur then + if not sh.idr and #self.refs == 0 and self.frames == 0 and sh.type ~= Slice.I then + -- a stream starting without an intra picture: decode against gray + self.lastError = "stream starts with an inter picture" + end + startPicture(self, sh, pts) + end + decodeSlice(self, sh, r) + if self.decoded >= self.S.mbW * self.S.mbH then + finishPicture(self) + end + return + elseif t == 9 or t == 10 or t == 11 then + finishPicture(self) + return + elseif t >= 2 and t <= 4 then + self.unsupported = "data partitioning (Extended profile)" + return + end + -- SEI (6), filler (12), SPS extension (13), prefix / SVC / MVC (14, 15, 20) and reserved types are ignored +end + +function Decoder.flush(self: any) + finishPicture(self) + bump(self, 0) +end + +function Decoder.take(self: any): { any } + local out = self.out + self.out = {} + return out +end + +return Decoder +end +__FILES["codecs/video/H264/Inter"] = @native function() + + + +-- codecs/video/H264/Inter: inter prediction sample interpolation and weighting (ITU-T H.264 8.4.2.2 / 8.4.2.3). +-- Reference planes carry a border of PAD / PADC replicated samples, so reads equal the clamped positions of 8.4.2.2.1. +local readu8, writeu8 = buffer.readu8, buffer.writeu8 + +local Inter = {} + +Inter.PAD = 32 +Inter.PADC = 16 + +local min, max = math.min, math.max +@native local function clip(v: number): number + return min(max(v, 0), 255) +end + +local B1 = table.create(24 * 17, 0) + +-- one small function per six-tap case: LuaJIT keeps each loop in one trace +@native local function lumaCopy(ref: buffer, s: number, base: number, w: number, h: number, P: { number }) + for r = 0, h - 1 do + local o = base + r * s + local d = r * 16 + 1 + for c = 0, w - 1 do + P[d + c] = readu8(ref, o + c) + end + end +end + +-- horizontal half sample b; avg 0: b, 1: (G + b + 1) >> 1, 2: (b + H + 1) >> 1 +@native local function lumaH(ref: buffer, s: number, base: number, w: number, h: number, P: { number }, avg: number) + for r = 0, h - 1 do + local o = base + r * s + local d = r * 16 + 1 + local a0, a1, a2, a3, a4 = readu8(ref, o - 2), readu8(ref, o - 1), readu8(ref, o), readu8(ref, o + 1), readu8(ref, o + 2) + for c = 0, w - 1 do + local a5 = readu8(ref, o + c + 3) + local v = min(max((a0 - 5 * a1 + 20 * a2 + 20 * a3 - 5 * a4 + a5 + 16) // 32, 0), 255) + if avg == 1 then + v = (v + a2 + 1) // 2 + elseif avg == 2 then + v = (v + a3 + 1) // 2 + end + P[d + c] = v + a0, a1, a2, a3, a4 = a1, a2, a3, a4, a5 + end + end +end + +-- vertical half sample h; avg 0: h, 1: (G + h + 1) >> 1, 2: (h + G below + 1) >> 1 +@native local function lumaV(ref: buffer, s: number, base: number, w: number, h: number, P: { number }, avg: number) + for c = 0, w - 1 do + local o = base + c + local a0, a1, a2, a3, a4 = readu8(ref, o - 2 * s), readu8(ref, o - s), readu8(ref, o), readu8(ref, o + s), readu8(ref, o + 2 * s) + local d = c + 1 + for r = 0, h - 1 do + local a5 = readu8(ref, o + (r + 3) * s) + local v = min(max((a0 - 5 * a1 + 20 * a2 + 20 * a3 - 5 * a4 + a5 + 16) // 32, 0), 255) + if avg == 1 then + v = (v + a2 + 1) // 2 + elseif avg == 2 then + v = (v + a3 + 1) // 2 + end + P[d + r * 16] = v + a0, a1, a2, a3, a4 = a1, a2, a3, a4, a5 + end + end +end + +-- B1 rows -2 .. h + 2, columns 0 .. w (unrounded horizontal intermediates), stride 17 +@native local function horizontal1(ref: buffer, s: number, base: number, w: number, h: number) + for r = -2, h + 2 do + local o = base + r * s + local d = (r + 2) * 17 + 1 + local a0, a1, a2, a3, a4 = readu8(ref, o - 2), readu8(ref, o - 1), readu8(ref, o), readu8(ref, o + 1), readu8(ref, o + 2) + for c = 0, w do + local a5 = readu8(ref, o + c + 3) + B1[d + c] = a0 - 5 * a1 + 20 * a2 + 20 * a3 - 5 * a4 + a5 + a0, a1, a2, a3, a4 = a1, a2, a3, a4, a5 + end + end +end + +-- centre j; with = 0: j, 1: (b + j + 1) >> 1 (b of this row), 2: (s + j + 1) >> 1 (b of the next row) +@native local function lumaJ(ref: buffer, s: number, base: number, w: number, h: number, P: { number }, with: number) + horizontal1(ref, s, base, w, h) + for c = 0, w - 1 do + local k = 2 * 17 + 1 + c + local a0, a1, a2, a3, a4 = B1[k - 34], B1[k - 17], B1[k], B1[k + 17], B1[k + 34] + for r = 0, h - 1 do + local a5 = B1[k + 51] + local v = min(max((a0 - 5 * a1 + 20 * a2 + 20 * a3 - 5 * a4 + a5 + 512) // 1024, 0), 255) + if with == 1 then + v = (v + min(max((a2 + 16) // 32, 0), 255) + 1) // 2 + elseif with == 2 then + v = (v + min(max((a3 + 16) // 32, 0), 255) + 1) // 2 + end + P[r * 16 + c + 1] = v + a0, a1, a2, a3, a4 = a1, a2, a3, a4, a5 + k += 17 + end + end +end + +-- (j + h + 1) >> 1 with h at column c + co (co 0: i, 1: k) +@native local function lumaJV(ref: buffer, s: number, base: number, w: number, h: number, P: { number }, co: number) + lumaJ(ref, s, base, w, h, P, 0) + for c = 0, w - 1 do + local o = base + c + co + local a0, a1, a2, a3, a4 = readu8(ref, o - 2 * s), readu8(ref, o - s), readu8(ref, o), readu8(ref, o + s), readu8(ref, o + 2 * s) + for r = 0, h - 1 do + local a5 = readu8(ref, o + (r + 3) * s) + local hv = min(max((a0 - 5 * a1 + 20 * a2 + 20 * a3 - 5 * a4 + a5 + 16) // 32, 0), 255) + local d = r * 16 + c + 1 + P[d] = (P[d] + hv + 1) // 2 + a0, a1, a2, a3, a4 = a1, a2, a3, a4, a5 + end + end +end + +-- diagonal quarter samples e, g, p, r: (b or s) averaged with (h or m) +@native local function lumaDiag(ref: buffer, s: number, base: number, w: number, h: number, P: { number }, ro: number, co: number) + lumaH(ref, s, base + ro, w, h, P, 0) + for c = 0, w - 1 do + local o = base + c + co + local a0, a1, a2, a3, a4 = readu8(ref, o - 2 * s), readu8(ref, o - s), readu8(ref, o), readu8(ref, o + s), readu8(ref, o + 2 * s) + for r = 0, h - 1 do + local a5 = readu8(ref, o + (r + 3) * s) + local vb = min(max((a0 - 5 * a1 + 20 * a2 + 20 * a3 - 5 * a4 + a5 + 16) // 32, 0), 255) + local d = r * 16 + c + 1 + P[d] = (P[d] + vb + 1) // 2 + a0, a1, a2, a3, a4 = a1, a2, a3, a4, a5 + end + end +end + +@native function Inter.luma(ref: buffer, s: number, base: number, fx: number, fy: number, w: number, h: number, P: { number }) + if fy == 0 then + if fx == 0 then + lumaCopy(ref, s, base, w, h, P) + else + lumaH(ref, s, base, w, h, P, if fx == 2 then 0 elseif fx == 1 then 1 else 2) + end + elseif fx == 0 then + lumaV(ref, s, base, w, h, P, if fy == 2 then 0 elseif fy == 1 then 1 else 2) + elseif fx == 2 then + lumaJ(ref, s, base, w, h, P, if fy == 2 then 0 elseif fy == 1 then 1 else 2) + elseif fy == 2 then + lumaJV(ref, s, base, w, h, P, if fx == 3 then 1 else 0) + else + lumaDiag(ref, s, base, w, h, P, if fy == 3 then s else 0, if fx == 3 then 1 else 0) + end +end + +@native function Inter.chroma(ref: buffer, s: number, base: number, fx: number, fy: number, w: number, h: number, P: { number }) + if fx == 0 and fy == 0 then + for r = 0, h - 1 do + local o = base + r * s + local d = r * 16 + 1 + for c = 0, w - 1 do + P[d + c] = readu8(ref, o + c) + end + end + return + end + local wa = (8 - fx) * (8 - fy) + local wb = fx * (8 - fy) + local wc = (8 - fx) * fy + local wd = fx * fy + for r = 0, h - 1 do + local o = base + r * s + local d = r * 16 + 1 + for c = 0, w - 1 do + local p = o + c + P[d + c] = (wa * readu8(ref, p) + wb * readu8(ref, p + 1) + wc * readu8(ref, p + s) + wd * readu8(ref, p + s + 1) + 32) // 64 + end + end +end + +@native function Inter.put(P: { number }, w: number, h: number, b: buffer, o: number, s: number) + for r = 0, h - 1 do + local d = r * 16 + 1 + local q = o + r * s + for c = 0, w - 1 do + writeu8(b, q + c, P[d + c]) + end + end +end + +-- default bi-prediction (P0 + P1 + 1) >> 1 +@native function Inter.avg(P0: { number }, P1: { number }, w: number, h: number, b: buffer, o: number, s: number) + for r = 0, h - 1 do + local d = r * 16 + 1 + local q = o + r * s + for c = 0, w - 1 do + writeu8(b, q + c, (P0[d + c] + P1[d + c] + 1) // 2) + end + end +end + +-- explicit single-list weighting (8-270 / 8-271) +@native function Inter.weight1(P: { number }, w: number, h: number, b: buffer, o: number, s: number, logWD: number, wt: number, off: number) + if logWD >= 1 then + local rnd = 2 ^ (logWD - 1) + local div = 2 ^ logWD + for r = 0, h - 1 do + local d = r * 16 + 1 + local q = o + r * s + for c = 0, w - 1 do + writeu8(b, q + c, clip((P[d + c] * wt + rnd) // div + off)) + end + end + else + for r = 0, h - 1 do + local d = r * 16 + 1 + local q = o + r * s + for c = 0, w - 1 do + writeu8(b, q + c, clip(P[d + c] * wt + off)) + end + end + end +end + +-- explicit / implicit bi-prediction weighting (8-272); off = (o0 + o1 + 1) >> 1 +@native function Inter.weight2(P0: { number }, P1: { number }, w: number, h: number, b: buffer, o: number, s: number, logWD: number, w0: number, w1: number, off: number) + local rnd = 2 ^ logWD + local div = 2 ^ (logWD + 1) + for r = 0, h - 1 do + local d = r * 16 + 1 + local q = o + r * s + for c = 0, w - 1 do + writeu8(b, q + c, clip((P0[d + c] * w0 + P1[d + c] * w1 + rnd) // div + off)) + end + end +end + +@native function Inter.extend(b: buffer, o: number, s: number, w: number, h: number, pad: number) + for y = 0, h - 1 do + local r = o + y * s + buffer.fill(b, r - pad, readu8(b, r), pad) + buffer.fill(b, r + w, readu8(b, r + w - 1), pad) + end + local top = o - pad + local bottom = o + (h - 1) * s - pad + for y = 1, pad do + buffer.copy(b, top - y * s, b, top, w + 2 * pad) + buffer.copy(b, bottom + y * s, b, bottom, w + 2 * pad) + end +end + +return Inter +end +__FILES["codecs/video/H264/Intra"] = @native function() + + + +-- codecs/video/H264/Intra: intra prediction (ITU-T H.264 8.3): Intra_4x4 and Intra_8x8 (with the 8x8 reference sample +-- filter of 8.3.2.2.1), Intra_16x16 and chroma, 8-bit. +local readu8, writeu8 = buffer.readu8, buffer.writeu8 + +local Intra = {} + +local E = table.create(40, 0) -- reference samples: p[-1, y] = E[N - y], p[-1, -1] = E[N + 1], p[x, -1] = E[N + 2 + x] +local F = table.create(40, 0) -- filtered 8x8 references, same layout + +local min, max = math.min, math.max +@native local function clip(v: number): number + return min(max(v, 0), 255) +end + +-- predNxN: the directional modes 3..8 over the edge array R (N = 4 or 8) +@native local function directional(R: { number }, N: number, mode: number, b: buffer, o: number, s: number) + local c = N + 1 -- R[c] = p[-1, -1]; p[x, -1] = R[c + 1 + x]; p[-1, y] = R[c - 1 - y] + for y = 0, N - 1 do + local row = o + y * s + for x = 0, N - 1 do + local v + if mode == 3 then -- diagonal down left + if x == N - 1 and y == N - 1 then + v = (R[c + 2 * N - 1] + 3 * R[c + 2 * N] + 2) // 4 + else + local i = c + 1 + x + y + v = (R[i] + 2 * R[i + 1] + R[i + 2] + 2) // 4 + end + elseif mode == 4 then -- diagonal down right + if x > y then + local i = c + 1 + x - y + v = (R[i - 2] + 2 * R[i - 1] + R[i] + 2) // 4 + elseif x < y then + local i = c - 1 - (y - x) + v = (R[i + 2] + 2 * R[i + 1] + R[i] + 2) // 4 + else + v = (R[c + 1] + 2 * R[c] + R[c - 1] + 2) // 4 + end + elseif mode == 5 then -- vertical right + local z = 2 * x - y + if z >= 0 and z % 2 == 0 then + local i = c + 1 + x - y // 2 + v = (R[i - 1] + R[i] + 1) // 2 + elseif z > 0 then + local i = c + 1 + x - y // 2 + v = (R[i - 2] + 2 * R[i - 1] + R[i] + 2) // 4 + elseif z == -1 then + v = (R[c - 1] + 2 * R[c] + R[c + 1] + 2) // 4 + else + local i = c - 1 - (y - 2 * x - 1) -- p[-1, y - 2x - 1] + v = (R[i] + 2 * R[i + 1] + R[i + 2] + 2) // 4 + end + elseif mode == 6 then -- horizontal down + local z = 2 * y - x + if z >= 0 and z % 2 == 0 then + local i = c - 1 - (y - x // 2) -- p[-1, y - (x >> 1)] + v = (R[i + 1] + R[i] + 1) // 2 + elseif z > 0 then + local i = c - 1 - (y - x // 2) + v = (R[i + 2] + 2 * R[i + 1] + R[i] + 2) // 4 + elseif z == -1 then + v = (R[c - 1] + 2 * R[c] + R[c + 1] + 2) // 4 + else + local i = c + 1 + (x - 2 * y - 1) -- p[x - 2y - 1, -1] + v = (R[i] + 2 * R[i - 1] + R[i - 2] + 2) // 4 + end + elseif mode == 7 then -- vertical left + local i = c + 1 + x + y // 2 + if y % 2 == 0 then + v = (R[i] + R[i + 1] + 1) // 2 + else + v = (R[i] + 2 * R[i + 1] + R[i + 2] + 2) // 4 + end + else -- horizontal up + local z = x + 2 * y + local i = c - 1 - (y + x // 2) -- p[-1, y + (x >> 1)] + if z > 2 * N - 3 then + v = R[c - N] + elseif z == 2 * N - 3 then + v = (R[c - N + 1] + 3 * R[c - N] + 2) // 4 + elseif z % 2 == 0 then + v = (R[i] + R[i - 1] + 1) // 2 + else + v = (R[i] + 2 * R[i - 1] + R[i - 2] + 2) // 4 + end + end + writeu8(b, row + x, v) + end + end +end + +-- unavailable top-right samples repeat p[3, -1] +@native function Intra.pred4x4(b: buffer, o: number, s: number, mode: number, left: boolean, top: boolean, topRight: boolean, topLeft: boolean) + if mode == 0 then + local t = o - s + local a0, a1, a2, a3 = readu8(b, t), readu8(b, t + 1), readu8(b, t + 2), readu8(b, t + 3) + for y = 0, 3 do + local r = o + y * s + writeu8(b, r, a0) + writeu8(b, r + 1, a1) + writeu8(b, r + 2, a2) + writeu8(b, r + 3, a3) + end + return + elseif mode == 1 then + for y = 0, 3 do + local r = o + y * s + local v = readu8(b, r - 1) + writeu8(b, r, v) + writeu8(b, r + 1, v) + writeu8(b, r + 2, v) + writeu8(b, r + 3, v) + end + return + elseif mode == 2 then + local sum, n = 0, 0 + if top then + local t = o - s + sum += readu8(b, t) + readu8(b, t + 1) + readu8(b, t + 2) + readu8(b, t + 3) + n += 1 + end + if left then + sum += readu8(b, o - 1) + readu8(b, o + s - 1) + readu8(b, o + 2 * s - 1) + readu8(b, o + 3 * s - 1) + n += 1 + end + local v = 128 + if n == 2 then + v = (sum + 4) // 8 + elseif n == 1 then + v = (sum + 2) // 4 + end + for y = 0, 3 do + local r = o + y * s + writeu8(b, r, v) + writeu8(b, r + 1, v) + writeu8(b, r + 2, v) + writeu8(b, r + 3, v) + end + return + end + -- edges: E[1..4] = p[-1, 3..0], E[5] = p[-1, -1], E[6..13] = p[0..7, -1] + if left then + for y = 0, 3 do + E[4 - y] = readu8(b, o + y * s - 1) + end + end + if topLeft then + E[5] = readu8(b, o - s - 1) + end + if top then + local t = o - s + for x = 0, 3 do + E[6 + x] = readu8(b, t + x) + end + if topRight then + for x = 4, 7 do + E[6 + x] = readu8(b, t + x) + end + else + local v = E[9] + E[10], E[11], E[12], E[13] = v, v, v, v + end + end + directional(E, 4, mode, b, o, s) +end + +@native function Intra.pred8x8(b: buffer, o: number, s: number, mode: number, left: boolean, top: boolean, topRight: boolean, topLeft: boolean) + -- unfiltered edges into E: E[1..8] = p[-1, 7..0], E[9] = p[-1, -1], E[10..25] = p[0..15, -1] + if left then + for y = 0, 7 do + E[8 - y] = readu8(b, o + y * s - 1) + end + end + local tl = 0 + if topLeft then + tl = readu8(b, o - s - 1) + E[9] = tl + end + if top then + local t = o - s + for x = 0, 7 do + E[10 + x] = readu8(b, t + x) + end + if topRight then + for x = 8, 15 do + E[10 + x] = readu8(b, t + x) + end + else + local v = E[17] + for x = 8, 15 do + E[10 + x] = v + end + end + -- filtered top + if topLeft then + F[10] = (tl + 2 * E[10] + E[11] + 2) // 4 + else + F[10] = (3 * E[10] + E[11] + 2) // 4 + end + for x = 1, 14 do + F[10 + x] = (E[9 + x] + 2 * E[10 + x] + E[11 + x] + 2) // 4 + end + F[25] = (E[24] + 3 * E[25] + 2) // 4 + end + if topLeft then + if top and left then + F[9] = (E[10] + 2 * tl + E[8] + 2) // 4 + elseif top then + F[9] = (3 * tl + E[10] + 2) // 4 + elseif left then + F[9] = (3 * tl + E[8] + 2) // 4 + else + F[9] = tl + end + end + if left then + if topLeft then + F[8] = (tl + 2 * E[8] + E[7] + 2) // 4 + else + F[8] = (3 * E[8] + E[7] + 2) // 4 + end + for y = 1, 6 do + F[8 - y] = (E[9 - y] + 2 * E[8 - y] + E[7 - y] + 2) // 4 + end + F[1] = (E[2] + 3 * E[1] + 2) // 4 + end + if mode == 0 then + for y = 0, 7 do + local r = o + y * s + for x = 0, 7 do + writeu8(b, r + x, F[10 + x]) + end + end + elseif mode == 1 then + for y = 0, 7 do + local r = o + y * s + local v = F[8 - y] + for x = 0, 7 do + writeu8(b, r + x, v) + end + end + elseif mode == 2 then + local sum, n = 0, 0 + if top then + for x = 0, 7 do + sum += F[10 + x] + end + n += 1 + end + if left then + for y = 0, 7 do + sum += F[8 - y] + end + n += 1 + end + local v = 128 + if n == 2 then + v = (sum + 8) // 16 + elseif n == 1 then + v = (sum + 4) // 8 + end + for y = 0, 7 do + local r = o + y * s + for x = 0, 7 do + writeu8(b, r + x, v) + end + end + else + directional(F, 8, mode, b, o, s) + end +end + +@native function Intra.pred16x16(b: buffer, o: number, s: number, mode: number, left: boolean, top: boolean, topLeft: boolean) + if mode == 0 then + local t = o - s + for y = 0, 15 do + buffer.copy(b, o + y * s, b, t, 16) + end + elseif mode == 1 then + for y = 0, 15 do + local r = o + y * s + buffer.fill(b, r, readu8(b, r - 1), 16) + end + elseif mode == 2 then + local sum, n = 0, 0 + if top then + local t = o - s + for x = 0, 15 do + sum += readu8(b, t + x) + end + n += 1 + end + if left then + for y = 0, 15 do + sum += readu8(b, o + y * s - 1) + end + n += 1 + end + local v = 128 + if n == 2 then + v = (sum + 16) // 32 + elseif n == 1 then + v = (sum + 8) // 16 + end + for y = 0, 15 do + buffer.fill(b, o + y * s, v, 16) + end + else + local t = o - s + local H, V = 0, 0 + for i = 0, 7 do + H += (i + 1) * (readu8(b, t + 8 + i) - readu8(b, t + 6 - i)) + V += (i + 1) * (readu8(b, o + (8 + i) * s - 1) - readu8(b, o + (6 - i) * s - 1)) + end + local a = 16 * (readu8(b, o + 15 * s - 1) + readu8(b, t + 15)) + local bb = (5 * H + 32) // 64 + local cc = (5 * V + 32) // 64 + for y = 0, 15 do + local r = o + y * s + local base = a + cc * (y - 7) + 16 - 7 * bb + for x = 0, 15 do + writeu8(b, r + x, clip((base + bb * x) // 32)) + end + end + end +end + +@native local function fill4(b: buffer, o: number, s: number, v: number) + for y = 0, 3 do + local r = o + y * s + writeu8(b, r, v) + writeu8(b, r + 1, v) + writeu8(b, r + 2, v) + writeu8(b, r + 3, v) + end +end + +-- 8x8 chroma (4:2:0): mode 0 DC, 1 horizontal, 2 vertical, 3 plane +@native function Intra.predChroma(b: buffer, o: number, s: number, mode: number, left: boolean, top: boolean, topLeft: boolean) + if mode == 0 then + local t = o - s + local st0, st1, sl0, sl1 = 0, 0, 0, 0 + if top then + st0 = readu8(b, t) + readu8(b, t + 1) + readu8(b, t + 2) + readu8(b, t + 3) + st1 = readu8(b, t + 4) + readu8(b, t + 5) + readu8(b, t + 6) + readu8(b, t + 7) + end + if left then + sl0 = readu8(b, o - 1) + readu8(b, o + s - 1) + readu8(b, o + 2 * s - 1) + readu8(b, o + 3 * s - 1) + sl1 = readu8(b, o + 4 * s - 1) + readu8(b, o + 5 * s - 1) + readu8(b, o + 6 * s - 1) + readu8(b, o + 7 * s - 1) + end + local v00, v10, v01, v11 = 128, 128, 128, 128 + if top and left then + v00 = (st0 + sl0 + 4) // 8 + v11 = (st1 + sl1 + 4) // 8 + v10 = (st1 + 2) // 4 + v01 = (sl1 + 2) // 4 + elseif left then + v00 = (sl0 + 2) // 4 + v11 = (sl1 + 2) // 4 + v10 = v00 + v01 = v11 + elseif top then + v00 = (st0 + 2) // 4 + v11 = (st1 + 2) // 4 + v10 = v11 + v01 = v00 + end + fill4(b, o, s, v00) + fill4(b, o + 4, s, v10) + fill4(b, o + 4 * s, s, v01) + fill4(b, o + 4 * s + 4, s, v11) + elseif mode == 1 then + for y = 0, 7 do + local r = o + y * s + buffer.fill(b, r, readu8(b, r - 1), 8) + end + elseif mode == 2 then + local t = o - s + for y = 0, 7 do + buffer.copy(b, o + y * s, b, t, 8) + end + else + local t = o - s + local H, V = 0, 0 + for i = 0, 3 do + H += (i + 1) * (readu8(b, t + 4 + i) - readu8(b, t + 2 - i)) + V += (i + 1) * (readu8(b, o + (4 + i) * s - 1) - readu8(b, o + (2 - i) * s - 1)) + end + local a = 16 * (readu8(b, o + 7 * s - 1) + readu8(b, t + 7)) + local bb = (34 * H + 32) // 64 + local cc = (34 * V + 32) // 64 + for y = 0, 7 do + local r = o + y * s + local base = a + cc * (y - 3) + 16 - 3 * bb + for x = 0, 7 do + writeu8(b, r + x, clip((base + bb * x) // 32)) + end + end + end +end + +return Intra +end +__FILES["codecs/video/H264/Mb"] = @native function() + + + +-- 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), intra 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 (8.4.1.2). Reference indices past the list use the first entry. +local Intra = __include("codecs/video/H264/Intra") +local Transform = __include("codecs/video/H264/Transform") +local Inter = __include("codecs/video/H264/Inter") + +local Mb = {} +Mb.YIELD_MBS = 16 -- macroblocks between calls of the cooperative yield hook (S.hook: Decoder Options.yield) + +-- macroblock kinds (S.kind per macroblock) +local K_I4, K_I8, K_I16, K_PCM, K_P, K_PSKIP, K_B, K_BSKIP, K_BDIRECT = 1, 2, 3, 4, 5, 6, 7, 8, 9 +Mb.K_I4, Mb.K_I8, Mb.K_I16, Mb.K_PCM, Mb.K_P, Mb.K_PSKIP, Mb.K_B, Mb.K_BSKIP, Mb.K_BDIRECT = K_I4, K_I8, K_I16, K_PCM, K_P, K_PSKIP, K_B, K_BSKIP, K_BDIRECT + +local UNAVAIL = -2 +local min, max = math.min, math.max + +local add4, addDc4, add8 = Transform.add4, Transform.addDc4, Transform.add8 +local PAD, PADC = Inter.PAD, Inter.PADC + +-- raster 4x4 block (bx + 4 by) of the decoding-order block index 0..15 (6.4.3) +local BLK_X = { 0, 1, 0, 1, 2, 3, 2, 3, 0, 1, 0, 1, 2, 3, 2, 3 } +local BLK_Y = { 0, 0, 1, 1, 0, 0, 1, 1, 2, 2, 3, 3, 2, 2, 3, 3 } +Mb.BLK_X, Mb.BLK_Y = BLK_X, BLK_Y + +@native function Mb.new(): any + return { + addr = 0, + x = 0, + y = 0, + g0 = 1, -- grid index of the macroblock's 4x4 block (0, 0) + c0 = 1, -- chroma 4x4 grid index of its block (0, 0) + aL = false, + aT = false, + aTR = false, + aTL = false, + iL = false, -- intra sample availability (constrained_intra_pred aware) + iT = false, + iTR = false, + iTL = false, + kind = 0, + t8 = 0, + i16 = 0, + cpm = 0, + cbp = 0, + qp = 0, + qpd = 0, -- mb_qp_delta + part = 0, -- 0 16x16, 1 16x8, 2 8x16, 3 8x8 + pf = { 0, 0, 0, 0 }, -- prediction flags per partition: 1 L0, 2 L1, 3 Bi + sub = { 0, 0, 0, 0 }, -- sub-macroblock shape: 0 8x8, 1 8x4, 2 4x8, 3 4x4 + dir = { false, false, false, false }, -- B_Direct_8x8 sub-macroblocks + ref0 = { 0, 0, 0, 0 }, + ref1 = { 0, 0, 0, 0 }, + mvd0 = table.create(32, 0), + mvd1 = table.create(32, 0), + ipm = table.create(16, 2), -- intra 4x4 / 8x8 modes by raster block + c4 = table.create(256, 0), -- luma 4x4 coefficients (dequantised), raster block * 16 + raster position + c8 = table.create(256, 0), -- luma 8x8 coefficients, 8x8 block * 64 + raster position + cc = table.create(128, 0), -- chroma: (plane * 4 + block) * 16 + position + dcY = table.create(16, 0), + dcC = table.create(8, 0), + nz = table.create(16, 0), -- coefficients per luma 4x4 block (raster) + nzc = table.create(8, 0), -- coefficients per chroma AC block (plane * 4 + block) + hasDcY = false, + hasDcC = false, + done = table.create(16, false), + reg = table.create(64, 0), -- motion compensation regions: x, y, w, h (4x4 units) + nreg = 0, + P0 = table.create(256, 0), + P1 = table.create(256, 0), + pcm = buffer.create(384), + } +end + +@native function Mb.grids(mbW: number, mbH: number): any + local n = mbW * mbH + local n4 = n * 16 + local nc = n * 4 + return { + sliceTab = table.create(n, 0), + kind = table.create(n, 0), + cbpTab = table.create(n, 0), + qpTab = table.create(n, 0), -- QPY for deblocking (0 for I_PCM) + qpcTab = table.create(n, 0), -- QPc (Cb) + qpc2Tab = table.create(n, 0), -- QPc (Cr) + t8Tab = table.create(n, 0), + cpmTab = table.create(n, 0), + dcTab = table.create(n, 0), -- CABAC coded_block_flag of the DC blocks: 1 luma, 2 Cb, 4 Cr + qpdTab = table.create(n, 0), -- mb_qp_delta ~= 0 + nzc = table.create(n4, 0), + nzcCb = table.create(nc, 0), + nzcCr = table.create(nc, 0), + nzDb = table.create(n4, 0), + ipm = table.create(n4, 2), + mvd0 = table.create(n4 * 2, 0), + mvd1 = table.create(n4 * 2, 0), + rgt0 = table.create(n4, 0), + rgt1 = table.create(n4, 0), + } +end + +@native function Mb.start(S: any, M: any, addr: number) + local mbW = S.mbW + local x, y = addr % mbW, addr // mbW + M.addr, M.x, M.y = addr, x, y + local w4 = S.w4 + M.g0 = y * 4 * w4 + x * 4 + 1 + M.c0 = y * 2 * S.cw4 + x * 2 + 1 + local st, sl = S.sliceTab, S.slice + local aL = x > 0 and st[addr] == sl -- addr is 0-based: st[addr] is macroblock addr - 1 + local aT = y > 0 and st[addr - mbW + 1] == sl + local aTR = y > 0 and x < mbW - 1 and st[addr - mbW + 2] == sl + local aTL = y > 0 and x > 0 and st[addr - mbW] == sl + M.aL, M.aT, M.aTR, M.aTL = aL, aT, aTR, aTL + if S.constrainedIntra then + local k = S.kind + M.iL = aL and k[addr] <= K_PCM + M.iT = aT and k[addr - mbW + 1] <= K_PCM + M.iTR = aTR and k[addr - mbW + 2] <= K_PCM + M.iTL = aTL and k[addr - mbW] <= K_PCM + else + M.iL, M.iT, M.iTR, M.iTL = aL, aT, aTR, aTL + end + local done = M.done + for i = 1, 16 do + done[i] = false + end + M.nreg = 0 + M.hasDcY, M.hasDcC = false, false + M.t8 = 0 + M.qpd = 0 +end + +-- nC of luma block (bx, by) (9.2.1) +@native function Mb.nC(S: any, M: any, bx: number, by: number): number + local g = M.g0 + by * S.w4 + bx + local nzc = S.nzc + local la = bx > 0 or M.aL + local ta = by > 0 or M.aT + if la and ta then + return (nzc[g - 1] + nzc[g - S.w4] + 1) // 2 + elseif la then + return nzc[g - 1] + elseif ta then + return nzc[g - S.w4] + end + return 0 +end + +@native function Mb.nCc(S: any, M: any, tab: { number }, bx: number, by: number): number + local cw = S.cw4 + local g = M.c0 + by * cw + bx + local la = bx > 0 or M.aL + local ta = by > 0 or M.aT + if la and ta then + return (tab[g - 1] + tab[g - cw] + 1) // 2 + elseif la then + return tab[g - 1] + elseif ta then + return tab[g - cw] + end + return 0 +end + +-- predIntra4x4PredMode / predIntra8x8PredMode (8.3.1.1 / 8.3.2.1) +@native function Mb.predMode(S: any, M: any, bx: number, by: number): number + local la = bx > 0 or M.iL + local ta = by > 0 or M.iT + if not (la and ta) then + return 2 + end + local ipm = S.ipm + local g = M.g0 + by * S.w4 + bx + local a, b = ipm[g - 1], ipm[g - S.w4] + return ((a < b) and (a) or (b)) +end + +@native local function neighbour(S: any, M: any, refs: { number }, mvs: { number }, nx: number, ny: number): (number, number, number) + local ok + if ny < 0 then + if nx < 0 then + ok = M.aTL + elseif nx < 4 then + ok = M.aT + else + ok = M.aTR + end + elseif nx < 0 then + ok = M.aL + elseif nx >= 4 then + ok = false + else + ok = M.done[ny * 4 + nx + 1] + end + if not ok then + return UNAVAIL, 0, 0 + end + local g = M.g0 + ny * S.w4 + nx + local r = refs[g] + if r < 0 then + return -1, 0, 0 + end + return r, mvs[2 * g - 1], mvs[2 * g] +end + +@native local function median(a: number, b: number, c: number): number + return max(min(a, b), min(max(a, b), c)) +end + +-- shape: 0 generic, 1 = 16x8 upper, 2 = 16x8 lower, 3 = 8x16 left, 4 = 8x16 right (8.4.1.3) +@native local function mvp(S: any, M: any, list: number, x: number, y: number, w: number, ref: number, shape: number): (number, number) + local pic = S.pic + local refs = ((list == 0) and (pic.ref0) or (pic.ref1)) + local mvs = ((list == 0) and (pic.mv0) or (pic.mv1)) + local rA, ax, ay = neighbour(S, M, refs, mvs, x - 1, y) + local rB, bx, by = neighbour(S, M, refs, mvs, x, y - 1) + local rC, cx, cy = neighbour(S, M, refs, mvs, x + w, y - 1) + if rC == UNAVAIL then + rC, cx, cy = neighbour(S, M, refs, mvs, x - 1, y - 1) + end + if shape == 1 then + if rB == ref then + return bx, by + end + elseif shape == 2 then + if rA == ref then + return ax, ay + end + elseif shape == 3 then + if rA == ref then + return ax, ay + end + elseif shape == 4 then + if rC == ref then + return cx, cy + end + end + if rB == UNAVAIL and rC == UNAVAIL and rA ~= UNAVAIL then + rB, bx, by = rA, ax, ay + rC, cx, cy = rA, ax, ay + end + local n = 0 + if rA == ref then + n += 1 + end + if rB == ref then + n += 2 + end + if rC == ref then + n += 4 + end + if n == 1 then + return ax, ay + elseif n == 2 then + return bx, by + elseif n == 4 then + return cx, cy + end + return median(ax, bx, cx), median(ay, by, cy) +end +Mb.mvp = mvp + +@native local function set(S: any, M: any, x: number, y: number, w: number, h: number, r0: number, m0x: number, m0y: number, r1: number, m1x: number, m1y: number) + local pic = S.pic + local ref0, ref1, mv0, mv1, uid0, uid1 = pic.ref0, pic.ref1, pic.mv0, pic.mv1, pic.uid0, pic.uid1 + local u0 = ((r0 >= 0) and (S.uids0[r0 + 1] or -1) or (-1)) + local u1 = ((r1 >= 0) and (S.uids1[r1 + 1] or -1) or (-1)) + local w4 = S.w4 + local done = M.done + for j = y, y + h - 1 do + local g = M.g0 + j * w4 + x + for i = x, x + w - 1 do + ref0[g] = r0 + ref1[g] = r1 + mv0[2 * g - 1], mv0[2 * g] = m0x, m0y + mv1[2 * g - 1], mv1[2 * g] = m1x, m1y + uid0[g] = u0 + uid1[g] = u1 + done[j * 4 + i + 1] = true + g += 1 + end + end + local k = M.nreg * 4 + local reg = M.reg + reg[k + 1], reg[k + 2], reg[k + 3], reg[k + 4] = x, y, w, h + M.nreg += 1 +end + +@native local function clip3(lo: number, hi: number, v: number): number + return min(max(v, lo), hi) +end + +@native local function tdiv(a: number, b: number): number + local q = a / b + if q >= 0 then + return math.floor(q) + end + return -math.floor(-q) +end + +-- DistScaleFactor (8-195 .. 8-198), nil when td is 0 +@native function Mb.distScale(cur: number, poc0: number, poc1: number): number? + local tb = clip3(-128, 127, cur - poc0) + local td = clip3(-128, 127, poc1 - poc0) + if td == 0 then + return nil + end + local tx = tdiv(16384 + math.abs(tdiv(td, 2)), td) + return clip3(-1024, 1023, (tb * tx + 32) // 64) +end + +-- P_Skip motion (8.4.1.1) +@native local function pskip(S: any, M: any) + local mx, my = 0, 0 + if M.aL and M.aT then + local pic = S.pic + local rA, ax, ay = neighbour(S, M, pic.ref0, pic.mv0, -1, 0) + local rB, bx, by = neighbour(S, M, pic.ref0, pic.mv0, 0, -1) + if not ((rA == 0 and ax == 0 and ay == 0) or (rB == 0 and bx == 0 and by == 0)) then + mx, my = mvp(S, M, 0, 0, 0, 4, 0, 0) + end + end + set(S, M, 0, 0, 4, 4, 0, mx, my, -1, 0, 0) +end + +-- refIdxCol (-1: intra / none), mvCol (8.4.1.2.1) +@native local function colocated(S: any, M: any, bx: number, by: number): (number, number, number, number) + local col = S.colPic + if S.direct8x8 then + bx = ((bx < 2) and (0) or (3)) + by = ((by < 2) and (0) or (3)) + end + if col.mbIntra[M.addr + 1] then + return -1, 0, 0, -1 + end + local g = M.g0 + by * S.w4 + bx + local r = col.ref0[g] + if r >= 0 then + return r, col.mv0[2 * g - 1], col.mv0[2 * g], col.uid0[g] + end + r = col.ref1[g] + if r >= 0 then + return r, col.mv1[2 * g - 1], col.mv1[2 * g], col.uid1[g] + end + return -1, 0, 0, -1 +end + +@native local function minPositive(a: number, b: number): number + if a >= 0 and b >= 0 then + return ((a < b) and (a) or (b)) + end + return ((a > b) and (a) or (b)) +end + +-- spatial direct references and predictors (8.4.1.2.2) +@native local function spatialRefs(S: any, M: any) + local pic = S.pic + local r0, r1 = -1, -1 + for l = 0, 1 do + local refs = ((l == 0) and (pic.ref0) or (pic.ref1)) + local mvs = ((l == 0) and (pic.mv0) or (pic.mv1)) + local rA = neighbour(S, M, refs, mvs, -1, 0) + local rB = neighbour(S, M, refs, mvs, 0, -1) + local rC = neighbour(S, M, refs, mvs, 4, -1) + if rC == UNAVAIL then + rC = neighbour(S, M, refs, mvs, -1, -1) + end + local r = minPositive(rA, minPositive(rB, rC)) + if r < -1 then + r = -1 + end + if l == 0 then + r0 = r + else + r1 = r + end + end + M.dZero = false + if r0 < 0 and r1 < 0 then + r0, r1 = 0, 0 + M.dZero = true + end + M.dr0, M.dr1 = r0, r1 + M.d0x, M.d0y, M.d1x, M.d1y = 0, 0, 0, 0 + if not M.dZero then + if r0 >= 0 then + M.d0x, M.d0y = mvp(S, M, 0, 0, 0, 4, r0, 0) + end + if r1 >= 0 then + M.d1x, M.d1y = mvp(S, M, 1, 0, 0, 4, r1, 0) + end + end + M.dReady = true +end + +@native local function direct8(S: any, M: any, i8: number) + local x0, y0 = (i8 % 2) * 2, (i8 // 2) * 2 + local step = ((S.direct8x8) and (2) or (1)) + if S.directSpatial then + if not M.dReady then + spatialRefs(S, M) + end + local r0, r1 = M.dr0, M.dr1 + local l1short = S.colShort + for y = y0, y0 + 1, step do + for x = x0, x0 + 1, step do + local m0x, m0y, m1x, m1y = M.d0x, M.d0y, M.d1x, M.d1y + if not M.dZero and l1short then + local rc, cx, cy = colocated(S, M, x, y) + if rc == 0 and cx >= -1 and cx <= 1 and cy >= -1 and cy <= 1 then + if r0 == 0 then + m0x, m0y = 0, 0 + end + if r1 == 0 then + m1x, m1y = 0, 0 + end + end + end + set(S, M, x, y, step, step, r0, m0x, m0y, r1, m1x, m1y) + end + end + else + for y = y0, y0 + 1, step do + for x = x0, x0 + 1, step do + local rc, cx, cy, cu = colocated(S, M, x, y) + local r0 = 0 + if rc >= 0 then + r0 = S.uidToRef0[cu] or 0 + end + local m0x, m0y, m1x, m1y = cx, cy, 0, 0 + local dsf = S.dsf[r0 + 1] + if dsf then + m0x = (dsf * cx + 128) // 256 + m0y = (dsf * cy + 128) // 256 + m1x = m0x - cx + m1y = m0y - cy + end + set(S, M, x, y, step, step, r0, m0x, m0y, 0, m1x, m1y) + end + end + end +end + +local SUB_N = { 1, 2, 2, 4 } +local SUB_W = { 2, 2, 1, 1 } +local SUB_H = { 2, 1, 2, 1 } + +@native local function motion(S: any, M: any) + local kind = M.kind + M.dReady = false + if kind == K_PSKIP then + pskip(S, M) + return + end + if kind == K_BSKIP or kind == K_BDIRECT then + for i8 = 0, 3 do + direct8(S, M, i8) + end + return + end + local part = M.part + local mvd0, mvd1 = M.mvd0, M.mvd1 + if part < 3 then + local n = ((part == 0) and (1) or (2)) + for p = 1, n do + local x, y, w, h = 0, 0, 4, 4 + local shape = 0 + if part == 1 then + y, h = (p - 1) * 2, 2 + shape = p + elseif part == 2 then + x, w = (p - 1) * 2, 2 + shape = 2 + p + end + local pf = M.pf[p] + local r0, r1 = -1, -1 + local m0x, m0y, m1x, m1y = 0, 0, 0, 0 + if pf % 2 == 1 then + r0 = M.ref0[p] + m0x, m0y = mvp(S, M, 0, x, y, w, r0, shape) + m0x += mvd0[2 * p - 1] + m0y += mvd0[2 * p] + end + if pf >= 2 then + r1 = M.ref1[p] + m1x, m1y = mvp(S, M, 1, x, y, w, r1, shape) + m1x += mvd1[2 * p - 1] + m1y += mvd1[2 * p] + end + set(S, M, x, y, w, h, r0, m0x, m0y, r1, m1x, m1y) + end + return + end + for i8 = 0, 3 do + if M.dir[i8 + 1] then + direct8(S, M, i8) + else + local x0, y0 = (i8 % 2) * 2, (i8 // 2) * 2 + local sub = M.sub[i8 + 1] + local pf = M.pf[i8 + 1] + local w, h = SUB_W[sub + 1], SUB_H[sub + 1] + for k = 0, SUB_N[sub + 1] - 1 do + local x, y = x0, y0 + if sub == 1 then + y += k + elseif sub == 2 then + x += k + elseif sub == 3 then + x += k % 2 + y += k // 2 + end + local p = i8 * 4 + k + 1 + local r0, r1 = -1, -1 + local m0x, m0y, m1x, m1y = 0, 0, 0, 0 + if pf % 2 == 1 then + r0 = M.ref0[i8 + 1] + m0x, m0y = mvp(S, M, 0, x, y, w, r0, 0) + m0x += mvd0[2 * p - 1] + m0y += mvd0[2 * p] + end + if pf >= 2 then + r1 = M.ref1[i8 + 1] + m1x, m1y = mvp(S, M, 1, x, y, w, r1, 0) + m1x += mvd1[2 * p - 1] + m1y += mvd1[2 * p] + end + set(S, M, x, y, w, h, r0, m0x, m0y, r1, m1x, m1y) + end + end + end +end +Mb.motion = motion + +@native local function predLuma(S: any, ref: any, P: { number }, px: number, py: number, w: number, h: number, mvx: number, mvy: number) + local W, H = S.mbW * 16, S.mbH * 16 + local ix = px + mvx // 4 + local iy = py + mvy // 4 + ix = clip3(2 - PAD, W + PAD - w - 4, ix) + iy = clip3(2 - PAD, H + PAD - h - 4, iy) + local s = ref.ys + Inter.luma(ref.y, s, ref.yo + iy * s + ix, mvx % 4, mvy % 4, w, h, P) +end + +@native local function predChroma(S: any, ref: any, P: { number }, plane: buffer, px: number, py: number, w: number, h: number, mvx: number, mvy: number) + local W, H = S.mbW * 8, S.mbH * 8 + local ix = px + mvx // 8 + local iy = py + mvy // 8 + ix = clip3(-PADC, W + PADC - 1 - w, ix) + iy = clip3(-PADC, H + PADC - 1 - h, iy) + local s = ref.cs + Inter.chroma(plane, s, ref.co + iy * s + ix, mvx % 8, mvy % 8, w, h, P) +end + +@native local function refPic(list: { any }, r: number): any + return list[r + 1] or list[1] +end + +@native local function mc(S: any, M: any) + local pic = S.pic + local reg = M.reg + local P0, P1 = M.P0, M.P1 + local ys, cs = pic.ys, pic.cs + local wm = S.weightMode + local list0, list1 = S.list0, S.list1 + for k = 0, M.nreg - 1 do + local x, y, w, h = reg[k * 4 + 1], reg[k * 4 + 2], reg[k * 4 + 3], reg[k * 4 + 4] + local g = M.g0 + y * S.w4 + x + local r0, r1 = pic.ref0[g], pic.ref1[g] + local m0x, m0y, m1x, m1y = pic.mv0[2 * g - 1], pic.mv0[2 * g], pic.mv1[2 * g - 1], pic.mv1[2 * g] + local ref0 = ((r0 >= 0) and (refPic(list0, r0)) or (nil)) + local ref1 = ((r1 >= 0) and (refPic(list1, r1)) or (nil)) + if ref0 == nil and ref1 == nil then + ref0 = list0[1] or list1[1] + r0 = 0 + if ref0 == nil then + continue + end + end + local px, py = M.x * 16 + x * 4, M.y * 16 + y * 4 + local lw, lh = w * 4, h * 4 + local lo = pic.yo + py * ys + px + local cx, cy, cw, ch = M.x * 8 + x * 2, M.y * 8 + y * 2, w * 2, h * 2 + local co = pic.co + cy * cs + cx + local bi = ref0 ~= nil and ref1 ~= nil + local explicit = wm == 1 + local implicitW0, implicitW1 = 32, 32 + if wm == 2 then + if bi then + local iw = S.implicit[r0 * 32 + r1 + 1] + implicitW0, implicitW1 = 64 - iw, iw + else + explicit = false + end + end + local W0, W1 = S.weights0, S.weights1 + for plane = 0, 2 do + local dst, o, s, bw, bh = pic.y, lo, ys, lw, lh + if plane == 1 then + dst, o, s, bw, bh = pic.u, co, cs, cw, ch + elseif plane == 2 then + dst, o, s, bw, bh = pic.v, co, cs, cw, ch + end + if ref0 then + if plane == 0 then + predLuma(S, ref0, P0, px, py, lw, lh, m0x, m0y) + else + predChroma(S, ref0, P0, ((plane == 1) and (ref0.u) or (ref0.v)), cx, cy, cw, ch, m0x, m0y) + end + end + if ref1 then + if plane == 0 then + predLuma(S, ref1, P1, px, py, lw, lh, m1x, m1y) + else + predChroma(S, ref1, P1, ((plane == 1) and (ref1.u) or (ref1.v)), cx, cy, cw, ch, m1x, m1y) + end + end + if wm == 2 and bi then + Inter.weight2(P0, P1, bw, bh, dst, o, s, 5, implicitW0, implicitW1, 0) + elseif explicit then + local logWD = ((plane == 0) and (S.lumaDenom) or (S.chromaDenom)) + local wi = plane * 2 + 1 + if bi then + local b0, b1 = r0 * 8, r1 * 8 + Inter.weight2(P0, P1, bw, bh, dst, o, s, logWD, W0[b0 + wi] or 1, W1[b1 + wi] or 1, ((W0[b0 + wi + 1] or 0) + (W1[b1 + wi + 1] or 0) + 1) // 2) + elseif ref0 then + local b0 = r0 * 8 + Inter.weight1(P0, bw, bh, dst, o, s, logWD, W0[b0 + wi] or 1, W0[b0 + wi + 1] or 0) + else + local b1 = r1 * 8 + Inter.weight1(P1, bw, bh, dst, o, s, logWD, W1[b1 + wi] or 1, W1[b1 + wi + 1] or 0) + end + elseif bi then + Inter.avg(P0, P1, bw, bh, dst, o, s) + elseif ref0 then + Inter.put(P0, bw, bh, dst, o, s) + else + Inter.put(P1, bw, bh, dst, o, s) + end + end + end +end + +@native local function lumaResidual(S: any, M: any) + local pic = S.pic + local b, s = pic.y, pic.ys + local o = pic.yo + M.y * 16 * s + M.x * 16 + local nz, c4, c8 = M.nz, M.c4, M.c8 + if M.t8 == 1 then + for i8 = 0, 3 do + local bx, by = (i8 % 2) * 2, (i8 // 2) * 2 + if nz[by * 4 + bx + 1] > 0 then + add8(c8, i8 * 64, b, o + by * 4 * s + bx * 4, s) + end + end + return + end + for blk = 0, 15 do + if nz[blk + 1] > 0 then + local bx, by = blk % 4, blk // 4 + add4(c4, blk * 16, b, o + by * 4 * s + bx * 4, s) + end + end +end + +@native local function chromaResidual(S: any, M: any) + if not M.hasDcC and M.cbp < 32 then + return + end + local pic = S.pic + local s = pic.cs + local o = pic.co + M.y * 8 * s + M.x * 8 + local cc, nzc = M.cc, M.nzc + if M.hasDcC then + local dq = S.dq.d4 + local intra = M.kind <= K_PCM + Transform.chromaDc(M.dcC, 0, dq[((intra) and (2) or (5))][M.qpc + 1][1], cc, 0) + Transform.chromaDc(M.dcC, 4, dq[((intra) and (3) or (6))][M.qpc2 + 1][1], cc, 64) + end + for plane = 0, 1 do + local b = ((plane == 0) and (pic.u) or (pic.v)) + for blk = 0, 3 do + local base = (plane * 4 + blk) * 16 + local q = o + (blk // 2) * 4 * s + (blk % 2) * 4 + if nzc[plane * 4 + blk + 1] > 0 then + add4(cc, base, b, q, s) + elseif cc[base + 1] ~= 0 then + addDc4(cc[base + 1], b, q, s) + cc[base + 1] = 0 + end + end + end +end + +@native local function intraLuma(S: any, M: any) + local pic = S.pic + local b, s = pic.y, pic.ys + local o = pic.yo + M.y * 16 * s + M.x * 16 + local kind = M.kind + local ipm = M.ipm + if kind == K_I16 then + Intra.pred16x16(b, o, s, M.i16, M.iL, M.iT, M.iTL) + local c4, nz = M.c4, M.nz + if M.hasDcY then + Transform.lumaDc(M.dcY, S.dq.d4[1][M.qp + 1][1], c4) + end + for blk = 0, 15 do + local bx, by = blk % 4, blk // 4 + local q = o + by * 4 * s + bx * 4 + if nz[blk + 1] > 0 then + add4(c4, blk * 16, b, q, s) + elseif c4[blk * 16 + 1] ~= 0 then + addDc4(c4[blk * 16 + 1], b, q, s) + c4[blk * 16 + 1] = 0 + end + end + elseif kind == K_I8 then + local nz, c8 = M.nz, M.c8 + for i8 = 0, 3 do + local bx, by = (i8 % 2) * 2, (i8 // 2) * 2 + local left = bx > 0 or M.iL + local top = by > 0 or M.iT + local tr, tl + if i8 == 0 then + tr, tl = M.iT, M.iTL + elseif i8 == 1 then + tr, tl = M.iTR, M.iT + elseif i8 == 2 then + tr, tl = true, M.iL + else + tr, tl = false, true + end + local q = o + by * 4 * s + bx * 4 + Intra.pred8x8(b, q, s, ipm[by * 4 + bx + 1], left, top, tr, tl) + if nz[by * 4 + bx + 1] > 0 then + add8(c8, i8 * 64, b, q, s) + end + end + else + local nz, c4 = M.nz, M.c4 + for i = 0, 15 do + local bx, by = BLK_X[i + 1], BLK_Y[i + 1] + local blk = by * 4 + bx + local left = bx > 0 or M.iL + local top = by > 0 or M.iT + local tl + if bx > 0 and by > 0 then + tl = true + elseif bx > 0 then + tl = M.iT + elseif by > 0 then + tl = M.iL + else + tl = M.iTL + end + local tr + if by == 0 then + if bx < 3 then + tr = M.iT + else + tr = M.iTR + end + else + tr = not (bx == 3 or (bx == 1 and (by == 1 or by == 3))) + end + local q = o + by * 4 * s + bx * 4 + Intra.pred4x4(b, q, s, ipm[blk + 1], left, top, tr, tl) + if nz[blk + 1] > 0 then + add4(c4, blk * 16, b, q, s) + end + end + end +end + +@native local function intraChroma(S: any, M: any) + local pic = S.pic + local s = pic.cs + local o = pic.co + M.y * 8 * s + M.x * 8 + Intra.predChroma(pic.u, o, s, M.cpm, M.iL, M.iT, M.iTL) + Intra.predChroma(pic.v, o, s, M.cpm, M.iL, M.iT, M.iTL) +end + +@native local function pcm(S: any, M: any) + local pic = S.pic + local src = M.pcm + local s = pic.ys + local o = pic.yo + M.y * 16 * s + M.x * 16 + for y = 0, 15 do + buffer.copy(pic.y, o + y * s, src, y * 16, 16) + end + s = pic.cs + o = pic.co + M.y * 8 * s + M.x * 8 + for y = 0, 7 do + buffer.copy(pic.u, o + y * s, src, 256 + y * 8, 8) + buffer.copy(pic.v, o + y * s, src, 320 + y * 8, 8) + end +end + +@native function Mb.recon(S: any, M: any) + local kind = M.kind + local addr = M.addr + 1 + local pic = S.pic + local w4 = S.w4 + S.kind[addr] = kind + S.sliceTab[addr] = S.slice + S.t8Tab[addr] = M.t8 + S.qpTab[addr] = ((kind == K_PCM) and (0) or (M.qp)) + S.qpcTab[addr] = ((kind == K_PCM) and (S.qpcOf[1]) or (M.qpc)) + S.qpc2Tab[addr] = ((kind == K_PCM) and (S.qpc2Of[1]) or (M.qpc2)) + pic.mbIntra[addr] = kind <= K_PCM + local nzDb = S.nzDb + local g0 = M.g0 + if kind <= K_PCM then + local ref0, ref1, uid0, uid1 = pic.ref0, pic.ref1, pic.uid0, pic.uid1 + for j = 0, 3 do + local g = g0 + j * w4 + for i = 0, 3 do + ref0[g + i], ref1[g + i], uid0[g + i], uid1[g + i] = -1, -1, -1, -1 + end + end + if kind == K_PCM or kind == K_I16 then + local ipm = S.ipm + for j = 0, 3 do + local g = g0 + j * w4 + ipm[g], ipm[g + 1], ipm[g + 2], ipm[g + 3] = 2, 2, 2, 2 + end + end + if kind == K_PCM then + pcm(S, M) + return + end + intraLuma(S, M) + intraChroma(S, M) + chromaResidual(S, M) + return + end + local ipm = S.ipm + for j = 0, 3 do + local g = g0 + j * w4 + ipm[g], ipm[g + 1], ipm[g + 2], ipm[g + 3] = 2, 2, 2, 2 + end + motion(S, M) + mc(S, M) + local nz = M.nz + if M.t8 == 1 then + for i8 = 0, 3 do + local bx, by = (i8 % 2) * 2, (i8 // 2) * 2 + local v = ((nz[by * 4 + bx + 1] > 0) and (1) or (0)) + local g = g0 + by * w4 + bx + nzDb[g], nzDb[g + 1], nzDb[g + w4], nzDb[g + w4 + 1] = v, v, v, v + end + else + for blk = 0, 15 do + nzDb[g0 + (blk // 4) * w4 + blk % 4] = ((nz[blk + 1] > 0) and (1) or (0)) + end + end + if M.cbp % 16 ~= 0 then + lumaResidual(S, M) + end + chromaResidual(S, M) +end + +@native function Mb.skip(S: any, M: any, kind: number) + M.kind = kind + M.cbp = 0 + M.t8 = 0 + M.qp = S.qp + M.qpc = S.qpcOf[S.qp + 1] + M.qpc2 = S.qpc2Of[S.qp + 1] + local addr = M.addr + 1 + S.cbpTab[addr] = 0 + S.dcTab[addr] = 0 + S.cpmTab[addr] = 0 + S.qpdTab[addr] = 0 + local nz = M.nz + for i = 1, 16 do + nz[i] = 0 + end + local nzc = M.nzc + for i = 1, 8 do + nzc[i] = 0 + end + local w4, g0 = S.w4, M.g0 + local grid, mvd0, mvd1, rgt0, rgt1 = S.nzc, S.mvd0, S.mvd1, S.rgt0, S.rgt1 + for j = 0, 3 do + local g = g0 + j * w4 + for i = 0, 3 do + grid[g + i] = 0 + mvd0[2 * (g + i) - 1], mvd0[2 * (g + i)] = 0, 0 + mvd1[2 * (g + i) - 1], mvd1[2 * (g + i)] = 0, 0 + rgt0[g + i], rgt1[g + i] = 0, 0 + end + end + local cw, c0 = S.cw4, M.c0 + local cb, cr = S.nzcCb, S.nzcCr + cb[c0], cb[c0 + 1], cb[c0 + cw], cb[c0 + cw + 1] = 0, 0, 0, 0 + cr[c0], cr[c0 + 1], cr[c0 + cw], cr[c0 + cw + 1] = 0, 0, 0, 0 + M.hasDcC = false + Mb.recon(S, M) +end + +return Mb +end +__FILES["codecs/video/H264/Params"] = @native function() + + +-- 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)). +local Bitstream = __include("codecs/video/H264/Bitstream") +local Tables = __include("codecs/video/H264/Tables") + +local u, u1, ue, se = Bitstream.u, Bitstream.u1, Bitstream.ue, Bitstream.se + +local Params = {} + +local HIGH_PROFILES = { [100] = true, [110] = true, [122] = true, [244] = true, [44] = true, [83] = true, [86] = true, [118] = true, [128] = true, [138] = true, [139] = true, [134] = true, [135] = true } + +-- MaxDpbMbs by level_idc (table A-1); level 9 is level 1b +local MAX_DPB_MBS = { [9] = 396, [10] = 396, [11] = 900, [12] = 2376, [13] = 2376, [20] = 2376, [21] = 4752, [22] = 8100, [30] = 8100, [31] = 18000, [32] = 20480, [40] = 32768, [41] = 32768, [42] = 34816, [50] = 110400, [51] = 184320, [52] = 184320, [60] = 696320, [61] = 696320, [62] = 696320 } + +local ZIGZAG4, ZIGZAG8 = Tables.ZIGZAG4, Tables.ZIGZAG8 + +-- scaling_list(): raster order, or "default" (useDefaultScalingMatrixFlag) +@native local function scalingList(r: Bitstream.Reader, size: number): any + local list = table.create(size, 0) + local last, nxt = 8, 8 + local zz = if size == 16 then ZIGZAG4 else ZIGZAG8 + for j = 0, size - 1 do + if nxt ~= 0 then + local d = se(r) + if d < -128 or d > 127 then + return nil + end + nxt = (last + d + 256) % 256 + if j == 0 and nxt == 0 then + return "default" + end + end + local v = if nxt == 0 then last else nxt + list[zz[j + 1] + 1] = v + last = v + end + return list +end + +-- lists: 12 entries (false = not present, "default", or a raster list) +@native local function scalingMatrix(r: Bitstream.Reader, count: number): { any }? + local lists = table.create(12, false) + for i = 1, count do + if u1(r) == 1 then + local l = scalingList(r, if i <= 6 then 16 else 64) + if l == nil then + return nil + end + lists[i] = l + end + end + return lists +end + +@native local function default(i: number): { number } + local out = {} + if i <= 6 then + local base = if i <= 3 then 0 else 16 + for k = 1, 16 do + out[k] = Tables.DEFAULT_4x4[base + k] + end + else + local base = if (i - 7) % 2 == 0 then 0 else 64 + for k = 1, 64 do + out[k] = Tables.DEFAULT_8x8[base + k] + end + end + return out +end + +local FLAT16, FLAT64 = table.create(16, 16), table.create(64, 16) + +-- fallback nil = rule A (defaults), else the SPS's 12 lists (rule B) +@native local function resolve(lists: { any }, fallback: { { number } }?): { { number } } + local out = {} + for i = 1, 12 do + local l = lists[i] + if l == "default" then + out[i] = default(i) + elseif l then + out[i] = l + elseif i == 1 or i == 4 or i == 7 or i == 8 then + out[i] = if fallback then fallback[i] else default(i) + elseif i <= 6 then + out[i] = out[i - 1] + else + out[i] = out[i - 2] + end + end + return out +end + +@native local function hrd(r: Bitstream.Reader) + local cnt = ue(r) + if cnt > 31 then + return false + end + u(r, 8) + for _ = 0, cnt do + ue(r) + ue(r) + u1(r) + end + u(r, 20) + return true +end + +@native local function vui(r: Bitstream.Reader, sps: any) + if u1(r) == 1 then + local idc = u(r, 8) + if idc == 255 then + sps.sarW = u(r, 16) + sps.sarH = u(r, 16) + end + sps.aspectIdc = idc + end + if u1(r) == 1 then + u1(r) + end + if u1(r) == 1 then + u(r, 3) + sps.fullRange = u1(r) == 1 + if u1(r) == 1 then + sps.colourPrimaries = u(r, 8) + sps.transfer = u(r, 8) + sps.matrix = u(r, 8) + end + end + if u1(r) == 1 then + ue(r) + ue(r) + end + if u1(r) == 1 then + sps.unitsInTick = u(r, 32) + sps.timeScale = u(r, 32) + sps.fixedRate = u1(r) == 1 + end + local nal = u1(r) == 1 + if nal and not hrd(r) then + return + end + local vcl = u1(r) == 1 + if vcl and not hrd(r) then + return + end + if nal or vcl then + u1(r) + end + u1(r) + if u1(r) == 1 then + u1(r) + ue(r) + ue(r) + ue(r) + ue(r) + local reorder = ue(r) + local dpb = ue(r) + if r.pos <= r.size and reorder <= 16 and dpb <= 16 then + sps.numReorderFrames = reorder + sps.maxDecFrameBuffering = dpb + end + end +end + +@native function Params.sps(r: Bitstream.Reader): (any, string?) + local sps: any = {} + sps.profile = u(r, 8) + sps.constraints = u(r, 8) + sps.level = u(r, 8) + sps.id = ue(r) + if sps.id > 31 then + return nil, "seq_parameter_set_id out of range" + end + sps.chromaFormat = 1 + sps.bitDepth = 8 + sps.bitDepthC = 8 + sps.bypass = false + sps.scaling = nil + if HIGH_PROFILES[sps.profile] then + sps.chromaFormat = ue(r) + if sps.chromaFormat > 3 then + return nil, "chroma_format_idc out of range" + end + if sps.chromaFormat == 3 then + sps.separatePlanes = u1(r) == 1 + end + sps.bitDepth = ue(r) + 8 + sps.bitDepthC = ue(r) + 8 + if sps.bitDepth > 14 or sps.bitDepthC > 14 then + return nil, "bit depth out of range" + end + sps.bypass = u1(r) == 1 + if u1(r) == 1 then + local lists = scalingMatrix(r, if sps.chromaFormat ~= 3 then 8 else 12) + if not lists then + return nil, "bad scaling list" + end + sps.scaling = resolve(lists, nil) + end + end + sps.log2MaxFrameNum = ue(r) + 4 + if sps.log2MaxFrameNum > 16 then + return nil, "log2_max_frame_num out of range" + end + sps.pocType = ue(r) + if sps.pocType == 0 then + sps.log2MaxPocLsb = ue(r) + 4 + if sps.log2MaxPocLsb > 16 then + return nil, "log2_max_pic_order_cnt_lsb out of range" + end + elseif sps.pocType == 1 then + sps.deltaPocAlwaysZero = u1(r) == 1 + sps.offsetNonRef = se(r) + sps.offsetTopToBottom = se(r) + local n = ue(r) + if n > 255 then + return nil, "num_ref_frames_in_pic_order_cnt_cycle out of range" + end + sps.offsetsForRefFrame = {} + local expected = 0 + for i = 1, n do + sps.offsetsForRefFrame[i] = se(r) + expected += sps.offsetsForRefFrame[i] + end + sps.expectedDeltaPerCycle = expected + elseif sps.pocType ~= 2 then + return nil, "pic_order_cnt_type out of range" + end + sps.maxRefFrames = ue(r) + if sps.maxRefFrames > 16 then + return nil, "max_num_ref_frames out of range" + end + sps.gapsAllowed = u1(r) == 1 + sps.mbWidth = ue(r) + 1 + sps.mbHeightMap = ue(r) + 1 + sps.frameMbsOnly = u1(r) == 1 + if not sps.frameMbsOnly then + sps.mbaff = u1(r) == 1 + end + sps.mbHeight = if sps.frameMbsOnly then sps.mbHeightMap else sps.mbHeightMap * 2 + if sps.mbWidth > 1024 or sps.mbHeight > 1024 then + return nil, "limit: picture too large" + end + sps.direct8x8 = u1(r) == 1 + sps.cropLeft, sps.cropRight, sps.cropTop, sps.cropBottom = 0, 0, 0, 0 + if u1(r) == 1 then + sps.cropLeft = ue(r) + sps.cropRight = ue(r) + sps.cropTop = ue(r) + sps.cropBottom = ue(r) + end + if r.pos > r.size then + return nil, "truncated: sequence parameter set" + end + if u1(r) == 1 then + local save = r.pos + vui(r, sps) + if r.pos > r.size then + r.pos = save + end + end + -- derived sizes (4:2:0 crop units: 2 x 2; monochrome / 4:4:4 are rejected later) + local cux, cuy = 2, 2 * (if sps.frameMbsOnly then 1 else 2) + if sps.chromaFormat == 0 or sps.chromaFormat == 3 then + cux, cuy = 1, (if sps.frameMbsOnly then 1 else 2) + elseif sps.chromaFormat == 2 then + cux, cuy = 2, (if sps.frameMbsOnly then 1 else 2) + end + local w, h = sps.mbWidth * 16, sps.mbHeight * 16 + sps.width = w - cux * (sps.cropLeft + sps.cropRight) + sps.height = h - cuy * (sps.cropTop + sps.cropBottom) + sps.cropX = cux * sps.cropLeft + sps.cropY = cuy * sps.cropTop + if sps.width <= 0 or sps.height <= 0 then + return nil, "cropping larger than the picture" + end + local maxMbs = MAX_DPB_MBS[sps.level] or 696320 + if sps.level == 11 and sps.constraints % 32 >= 16 and sps.profile ~= 100 then + maxMbs = 396 -- level 1b + end + sps.maxDpbFrames = math.clamp(maxMbs // (sps.mbWidth * sps.mbHeight), 1, 16) + return sps, nil +end + +@native function Params.pps(r: Bitstream.Reader, spsTable: { [number]: any }): (any, string?) + local pps: any = {} + pps.id = ue(r) + if pps.id > 255 then + return nil, "pic_parameter_set_id out of range" + end + pps.spsId = ue(r) + local sps = spsTable[pps.spsId] + if not sps then + return nil, "pps refers to a missing sps" + end + pps.cabac = u1(r) == 1 + pps.bottomFieldPocPresent = u1(r) == 1 + pps.sliceGroups = ue(r) + 1 + if pps.sliceGroups > 1 then + return nil, "unsupported: slice groups (FMO)" + end + pps.numRefIdxL0 = ue(r) + 1 + pps.numRefIdxL1 = ue(r) + 1 + if pps.numRefIdxL0 > 32 or pps.numRefIdxL1 > 32 then + return nil, "num_ref_idx_default_active out of range" + end + pps.weightedPred = u1(r) == 1 + pps.weightedBipred = u(r, 2) + pps.initQp = 26 + se(r) + pps.initQs = 26 + se(r) + pps.chromaQpOffset = se(r) + if pps.initQp < 0 or pps.initQp > 51 or pps.chromaQpOffset < -12 or pps.chromaQpOffset > 12 then + return nil, "pic_init_qp / chroma_qp_index_offset out of range" + end + pps.deblockingControl = u1(r) == 1 + pps.constrainedIntra = u1(r) == 1 + pps.redundantPicCnt = u1(r) == 1 + pps.transform8x8 = false + pps.chromaQpOffset2 = pps.chromaQpOffset + pps.scalingLists = nil + if r.pos > r.size then + return nil, "truncated: picture parameter set" + end + if Bitstream.moreData(r) then + pps.transform8x8 = u1(r) == 1 + if u1(r) == 1 then + local n = 6 + (if pps.transform8x8 then (if sps.chromaFormat ~= 3 then 2 else 6) else 0) + local lists = scalingMatrix(r, n) + if not lists then + return nil, "bad scaling list" + end + pps.scalingLists = lists + end + pps.chromaQpOffset2 = se(r) + if pps.chromaQpOffset2 < -12 or pps.chromaQpOffset2 > 12 then + return nil, "second_chroma_qp_index_offset out of range" + end + if r.pos > r.size then + return nil, "truncated: picture parameter set" + end + end + return pps, nil +end + +local V4 = { { 10, 16, 13 }, { 11, 18, 14 }, { 13, 20, 16 }, { 14, 23, 18 }, { 16, 25, 20 }, { 18, 29, 23 } } +local V8 = { + { 20, 18, 32, 19, 25, 24 }, + { 22, 19, 35, 21, 28, 26 }, + { 26, 23, 42, 24, 33, 31 }, + { 28, 25, 45, 26, 35, 33 }, + { 32, 28, 51, 30, 40, 38 }, + { 36, 32, 58, 34, 46, 43 }, +} + +@native local function norm4(m: number, i: number, j: number): number + local v = V4[m + 1] + if i % 2 == 0 and j % 2 == 0 then + return v[1] + elseif i % 2 == 1 and j % 2 == 1 then + return v[2] + end + return v[3] +end + +@native local function norm8(m: number, i: number, j: number): number + local v = V8[m + 1] + if i % 4 == 0 and j % 4 == 0 then + return v[1] + elseif i % 2 == 1 and j % 2 == 1 then + return v[2] + elseif i % 4 == 2 and j % 4 == 2 then + return v[3] + elseif (i % 4 == 0 and j % 2 == 1) or (i % 2 == 1 and j % 4 == 0) then + return v[4] + elseif (i % 4 == 0 and j % 4 == 2) or (i % 4 == 2 and j % 4 == 0) then + return v[5] + end + return v[6] +end + +-- dequant tables: dq.d4[list][qp + 1] = 16 multipliers (raster), list 1..6 = Y/Cb/Cr intra, Y/Cb/Cr inter; +-- dq.d8[list][qp + 1] = 64 multipliers, list 1 = Y intra, 2 = Y inter. A 4x4 coefficient c dequantises to +-- (c * m + 8) >> 4, an 8x8 one to (c * m + 32) >> 6 (8.5.12.1 / 8.5.13.1 with LevelScale * 2^(qP / 6)). +@native local function build(lists: { { number } }): any + local d4, d8 = {}, {} + for l = 1, 6 do + local w = lists[l] + local per = {} + for qp = 0, 51 do + local m, sh = qp % 6, 2 ^ (qp // 6) + local t = table.create(16, 0) + for k = 0, 15 do + local i, j = k % 4, k // 4 + t[k + 1] = w[k + 1] * norm4(m, i, j) * sh + end + per[qp + 1] = t + end + d4[l] = per + end + for l = 1, 2 do + local w = lists[6 + l] + local per = {} + for qp = 0, 51 do + local m, sh = qp % 6, 2 ^ (qp // 6) + local t = table.create(64, 0) + for k = 0, 63 do + local i, j = k % 8, k // 8 + t[k + 1] = w[k + 1] * norm8(m, i, j) * sh + end + per[qp + 1] = t + end + d8[l] = per + end + return { d4 = d4, d8 = d8 } +end + +@native function Params.dequant(sps: any, pps: any, cache: { [string]: any }): any + local lists: { { number } } + if pps.scalingLists then + lists = resolve(pps.scalingLists, sps.scaling) + elseif sps.scaling then + lists = sps.scaling + else + lists = {} + for i = 1, 12 do + lists[i] = if i <= 6 then FLAT16 else FLAT64 + end + end + local parts = {} + for i = 1, 8 do + parts[i] = table.concat(lists[i], ",") + end + local key = table.concat(parts, ";") + local dq = cache[key] + if not dq then + dq = build(lists) + cache[key] = dq + end + return dq +end + +return Params +end +__FILES["codecs/video/H264/Slice"] = @native function() + + +-- 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. Frame coding only: field pictures, MBAFF, SP / SI, separate colour planes and redundant +-- pictures return "unsupported: ...". +local Bitstream = __include("codecs/video/H264/Bitstream") + +local u, u1, ue, se = Bitstream.u, Bitstream.u1, Bitstream.ue, Bitstream.se + +local Slice = {} + +Slice.P, Slice.B, Slice.I, Slice.SP, Slice.SI = 0, 1, 2, 3, 4 + +@native local function modifications(r: Bitstream.Reader): { number }? + local ops = {} + if u1(r) == 1 then + for _ = 1, 100 do + local idc = ue(r) + if idc == 3 then + return ops + end + if idc > 5 then + return nil + end + table.insert(ops, idc) + table.insert(ops, ue(r)) + if r.pos > r.size then + return nil + end + end + return nil + end + return ops +end + +@native local function weights(r: Bitstream.Reader, n: number, lw: number, cw: number, chroma: boolean): { number }? + -- per entry: lumaW, lumaO, cbW, cbO, crW, crO, lumaFlag, chromaFlag (8 numbers) + local t = table.create(n * 8, 0) + for i = 0, n - 1 do + local b = i * 8 + t[b + 1], t[b + 2], t[b + 3], t[b + 4], t[b + 5], t[b + 6] = lw, 0, cw, 0, cw, 0 + if u1(r) == 1 then + t[b + 1] = se(r) + t[b + 2] = se(r) + t[b + 7] = 1 + if t[b + 1] < -128 or t[b + 1] > 127 or t[b + 2] < -128 or t[b + 2] > 127 then + return nil + end + end + if chroma and u1(r) == 1 then + for k = 0, 1 do + t[b + 3 + k * 2] = se(r) + t[b + 4 + k * 2] = se(r) + if t[b + 3 + k * 2] < -128 or t[b + 3 + k * 2] > 127 or t[b + 4 + k * 2] < -128 or t[b + 4 + k * 2] > 127 then + return nil + end + end + t[b + 8] = 1 + end + end + return t +end + +@native function Slice.header(r: Bitstream.Reader, nalType: number, nalRefIdc: number, spsTable: { [number]: any }, ppsTable: { [number]: any }): (any, string?) + local sh: any = {} + sh.nalType = nalType + sh.nalRefIdc = nalRefIdc + sh.idr = nalType == 5 + sh.firstMb = ue(r) + local st = ue(r) + if st > 9 then + return nil, "slice_type out of range" + end + sh.type = st % 5 + if sh.type == Slice.SP or sh.type == Slice.SI then + return nil, "unsupported: SP / SI slices (Extended profile)" + end + sh.ppsId = ue(r) + local pps = ppsTable[sh.ppsId] + if not pps then + return nil, "slice refers to a missing pps" + end + local sps = spsTable[pps.spsId] + if not sps then + return nil, "slice refers to a missing sps" + end + sh.pps, sh.sps = pps, sps + if sps.separatePlanes then + return nil, "unsupported: separate colour planes" + end + sh.frameNum = u(r, sps.log2MaxFrameNum) + if not sps.frameMbsOnly then + if u1(r) == 1 then + return nil, "unsupported: field pictures (PAFF)" + end + if sps.mbaff then + return nil, "unsupported: MBAFF" + end + end + if sh.idr then + sh.idrPicId = ue(r) + end + sh.pocLsb, sh.deltaPocBottom, sh.deltaPoc0, sh.deltaPoc1 = 0, 0, 0, 0 + if sps.pocType == 0 then + sh.pocLsb = u(r, sps.log2MaxPocLsb) + if pps.bottomFieldPocPresent then + sh.deltaPocBottom = se(r) + end + elseif sps.pocType == 1 and not sps.deltaPocAlwaysZero then + sh.deltaPoc0 = se(r) + if pps.bottomFieldPocPresent then + sh.deltaPoc1 = se(r) + end + end + if pps.redundantPicCnt then + sh.redundantPicCnt = ue(r) + end + sh.numRefIdxL0, sh.numRefIdxL1 = 0, 0 + if sh.type == Slice.B then + sh.directSpatial = u1(r) == 1 + end + if sh.type ~= Slice.I then + sh.numRefIdxL0 = pps.numRefIdxL0 + sh.numRefIdxL1 = if sh.type == Slice.B then pps.numRefIdxL1 else 0 + if u1(r) == 1 then + sh.numRefIdxL0 = ue(r) + 1 + if sh.type == Slice.B then + sh.numRefIdxL1 = ue(r) + 1 + end + end + if sh.numRefIdxL0 > 32 or sh.numRefIdxL1 > 32 then + return nil, "num_ref_idx_active out of range" + end + local m = modifications(r) + if not m then + return nil, "bad ref_pic_list_modification" + end + sh.mod0 = m + if sh.type == Slice.B then + m = modifications(r) + if not m then + return nil, "bad ref_pic_list_modification" + end + sh.mod1 = m + end + end + sh.weightMode = 0 -- 0 default, 1 explicit, 2 implicit + if (pps.weightedPred and sh.type == Slice.P) or (pps.weightedBipred == 1 and sh.type == Slice.B) then + sh.weightMode = 1 + sh.lumaDenom = ue(r) + if sh.lumaDenom > 7 then + return nil, "luma_log2_weight_denom out of range" + end + local chroma = sps.chromaFormat ~= 0 + sh.chromaDenom = 0 + if chroma then + sh.chromaDenom = ue(r) + if sh.chromaDenom > 7 then + return nil, "chroma_log2_weight_denom out of range" + end + end + local w = weights(r, sh.numRefIdxL0, 2 ^ sh.lumaDenom, 2 ^ sh.chromaDenom, chroma) + if not w then + return nil, "bad pred_weight_table" + end + sh.weights0 = w + if sh.type == Slice.B then + w = weights(r, sh.numRefIdxL1, 2 ^ sh.lumaDenom, 2 ^ sh.chromaDenom, chroma) + if not w then + return nil, "bad pred_weight_table" + end + sh.weights1 = w + end + elseif pps.weightedBipred == 2 and sh.type == Slice.B then + sh.weightMode = 2 + end + if nalRefIdc ~= 0 then + if sh.idr then + sh.noOutputOfPriorPics = u1(r) == 1 + sh.longTermReference = u1(r) == 1 + else + sh.adaptive = u1(r) == 1 + if sh.adaptive then + local ops = {} + for _ = 1, 100 do + local op = ue(r) + if op == 0 then + break + end + if op > 6 then + return nil, "bad memory_management_control_operation" + end + local a, b = 0, 0 + if op == 1 or op == 3 then + a = ue(r) + 1 -- difference_of_pic_nums + end + if op == 2 then + a = ue(r) -- long_term_pic_num + end + if op == 3 or op == 6 then + b = ue(r) -- long_term_frame_idx + end + if op == 4 then + a = ue(r) -- max_long_term_frame_idx_plus1 + end + if r.pos > r.size then + return nil, "truncated: dec_ref_pic_marking" + end + table.insert(ops, op) + table.insert(ops, a) + table.insert(ops, b) + end + sh.mmco = ops + end + end + end + sh.cabacInit = 0 + if pps.cabac and sh.type ~= Slice.I then + sh.cabacInit = ue(r) + if sh.cabacInit > 2 then + return nil, "cabac_init_idc out of range" + end + end + sh.qp = pps.initQp + se(r) + if sh.qp < 0 or sh.qp > 51 then + return nil, "slice QP out of range" + end + sh.deblock = 0 + sh.alphaOffset, sh.betaOffset = 0, 0 + if pps.deblockingControl then + sh.deblock = ue(r) + if sh.deblock > 2 then + return nil, "disable_deblocking_filter_idc out of range" + end + if sh.deblock ~= 1 then + sh.alphaOffset = se(r) * 2 + sh.betaOffset = se(r) * 2 + if sh.alphaOffset < -12 or sh.alphaOffset > 12 or sh.betaOffset < -12 or sh.betaOffset > 12 then + return nil, "slice_alpha / beta_offset out of range" + end + end + end + if r.pos > r.size then + return nil, "truncated: slice header" + end + return sh, nil +end + +return Slice +end +__FILES["codecs/video/H264/Tables"] = @native function() + + +-- codecs/video/H264/Tables: the constant tables of ITU-T H.264 (CAVLC 9-5, 9-7..9-10; CABAC init 9-12..9-24, +-- rangeTabLPS 9-44, transitions 9-45; chroma QP 8-15; me(v) CBP 9-4; scaling lists 7-3 / 7-4; zig-zag 8-12 / 8-13; +-- 9-43; deblocking 8-16 / 8-17). Values from openh264 2.x (BSD-2-Clause, licenses/openh264-LICENSE.txt). +local T = {} + +-- coeff_token per nC class (0: 0<=nC<2, 1: 2<=nC<4, 2: 4<=nC<8, 3: 8<=nC, 4: nC=-1 chroma DC): { code, len, TotalCoeff, +-- TrailingOnes } quads. TOTAL_ZEROS / TOTAL_ZEROS_CDC / RUN_BEFORE: { tzVlcIndex | zerosLeft, code, len, value } quads. +-- CABAC_INIT: [ctxIdx * 8 + model * 2 + 1] = m, [... + 2] = n; model 0 = I slices, 1..3 = cabac_init_idc 0..2. +-- RANGE_LPS: [pStateIdx * 4 + qCodIRangeIdx + 1]. TRANS: [pStateIdx * 2 + 1] = transIdxLPS, [+ 2] = transIdxMPS. +-- DEFAULT_4x4 / DEFAULT_8x8: intra list then inter list, raster order. ZIGZAG4 / ZIGZAG8: scan index -> raster index. +-- SIG8 / LAST8: 8x8 significant / last ctxIdxInc by scan index (frame coded). ALPHA / BETA: [indexA + 13] (index +-- -12..63); TC0: [(indexA + 12) * 4 + bS + 1] (bS 0..3; bS 0 is unused). +T.COEFF_TOKEN_0 = { 1, 1, 0, 0, 5, 6, 1, 0, 1, 2, 1, 1, 7, 8, 2, 0, 4, 6, 2, 1, 1, 3, 2, 2, 7, 9, 3, 0, 6, 8, 3, 1, 5, 7, 3, 2, 3, 5, 3, 3, 7, 10, 4, 0, 6, 9, 4, 1, 5, 8, 4, 2, 3, 6, 4, 3, 7, 11, 5, 0, 6, 10, 5, 1, 5, 9, 5, 2, 4, 7, 5, 3, 15, 13, 6, 0, 6, 11, 6, 1, 5, 10, 6, 2, 4, 8, 6, 3, 11, 13, 7, 0, 14, 13, 7, 1, 5, 11, 7, 2, 4, 9, 7, 3, 8, 13, 8, 0, 10, 13, 8, 1, 13, 13, 8, 2, 4, 10, 8, 3, 15, 14, 9, 0, 14, 14, 9, 1, 9, 13, 9, 2, 4, 11, 9, 3, 11, 14, 10, 0, 10, 14, 10, 1, 13, 14, 10, 2, 12, 13, 10, 3, 15, 15, 11, 0, 14, 15, 11, 1, 9, 14, 11, 2, 12, 14, 11, 3, 11, 15, 12, 0, 10, 15, 12, 1, 13, 15, 12, 2, 8, 14, 12, 3, 15, 16, 13, 0, 1, 15, 13, 1, 9, 15, 13, 2, 12, 15, 13, 3, 11, 16, 14, 0, 14, 16, 14, 1, 13, 16, 14, 2, 8, 15, 14, 3, 7, 16, 15, 0, 10, 16, 15, 1, 9, 16, 15, 2, 12, 16, 15, 3, 4, 16, 16, 0, 6, 16, 16, 1, 5, 16, 16, 2, 8, 16, 16, 3 } +T.COEFF_TOKEN_1 = { 3, 2, 0, 0, 11, 6, 1, 0, 2, 2, 1, 1, 7, 6, 2, 0, 7, 5, 2, 1, 3, 3, 2, 2, 7, 7, 3, 0, 10, 6, 3, 1, 9, 6, 3, 2, 5, 4, 3, 3, 7, 8, 4, 0, 6, 6, 4, 1, 5, 6, 4, 2, 4, 4, 4, 3, 4, 8, 5, 0, 6, 7, 5, 1, 5, 7, 5, 2, 6, 5, 5, 3, 7, 9, 6, 0, 6, 8, 6, 1, 5, 8, 6, 2, 8, 6, 6, 3, 15, 11, 7, 0, 6, 9, 7, 1, 5, 9, 7, 2, 4, 6, 7, 3, 11, 11, 8, 0, 14, 11, 8, 1, 13, 11, 8, 2, 4, 7, 8, 3, 15, 12, 9, 0, 10, 11, 9, 1, 9, 11, 9, 2, 4, 9, 9, 3, 11, 12, 10, 0, 14, 12, 10, 1, 13, 12, 10, 2, 12, 11, 10, 3, 8, 12, 11, 0, 10, 12, 11, 1, 9, 12, 11, 2, 8, 11, 11, 3, 15, 13, 12, 0, 14, 13, 12, 1, 13, 13, 12, 2, 12, 12, 12, 3, 11, 13, 13, 0, 10, 13, 13, 1, 9, 13, 13, 2, 12, 13, 13, 3, 7, 13, 14, 0, 11, 14, 14, 1, 6, 13, 14, 2, 8, 13, 14, 3, 9, 14, 15, 0, 8, 14, 15, 1, 10, 14, 15, 2, 1, 13, 15, 3, 7, 14, 16, 0, 6, 14, 16, 1, 5, 14, 16, 2, 4, 14, 16, 3 } +T.COEFF_TOKEN_2 = { 15, 4, 0, 0, 15, 6, 1, 0, 14, 4, 1, 1, 11, 6, 2, 0, 15, 5, 2, 1, 13, 4, 2, 2, 8, 6, 3, 0, 12, 5, 3, 1, 14, 5, 3, 2, 12, 4, 3, 3, 15, 7, 4, 0, 10, 5, 4, 1, 11, 5, 4, 2, 11, 4, 4, 3, 11, 7, 5, 0, 8, 5, 5, 1, 9, 5, 5, 2, 10, 4, 5, 3, 9, 7, 6, 0, 14, 6, 6, 1, 13, 6, 6, 2, 9, 4, 6, 3, 8, 7, 7, 0, 10, 6, 7, 1, 9, 6, 7, 2, 8, 4, 7, 3, 15, 8, 8, 0, 14, 7, 8, 1, 13, 7, 8, 2, 13, 5, 8, 3, 11, 8, 9, 0, 14, 8, 9, 1, 10, 7, 9, 2, 12, 6, 9, 3, 15, 9, 10, 0, 10, 8, 10, 1, 13, 8, 10, 2, 12, 7, 10, 3, 11, 9, 11, 0, 14, 9, 11, 1, 9, 8, 11, 2, 12, 8, 11, 3, 8, 9, 12, 0, 10, 9, 12, 1, 13, 9, 12, 2, 8, 8, 12, 3, 13, 10, 13, 0, 7, 9, 13, 1, 9, 9, 13, 2, 12, 9, 13, 3, 9, 10, 14, 0, 12, 10, 14, 1, 11, 10, 14, 2, 10, 10, 14, 3, 5, 10, 15, 0, 8, 10, 15, 1, 7, 10, 15, 2, 6, 10, 15, 3, 1, 10, 16, 0, 4, 10, 16, 1, 3, 10, 16, 2, 2, 10, 16, 3 } +T.COEFF_TOKEN_3 = { 3, 6, 0, 0, 0, 6, 1, 0, 1, 6, 1, 1, 4, 6, 2, 0, 5, 6, 2, 1, 6, 6, 2, 2, 8, 6, 3, 0, 9, 6, 3, 1, 10, 6, 3, 2, 11, 6, 3, 3, 12, 6, 4, 0, 13, 6, 4, 1, 14, 6, 4, 2, 15, 6, 4, 3, 16, 6, 5, 0, 17, 6, 5, 1, 18, 6, 5, 2, 19, 6, 5, 3, 20, 6, 6, 0, 21, 6, 6, 1, 22, 6, 6, 2, 23, 6, 6, 3, 24, 6, 7, 0, 25, 6, 7, 1, 26, 6, 7, 2, 27, 6, 7, 3, 28, 6, 8, 0, 29, 6, 8, 1, 30, 6, 8, 2, 31, 6, 8, 3, 32, 6, 9, 0, 33, 6, 9, 1, 34, 6, 9, 2, 35, 6, 9, 3, 36, 6, 10, 0, 37, 6, 10, 1, 38, 6, 10, 2, 39, 6, 10, 3, 40, 6, 11, 0, 41, 6, 11, 1, 42, 6, 11, 2, 43, 6, 11, 3, 44, 6, 12, 0, 45, 6, 12, 1, 46, 6, 12, 2, 47, 6, 12, 3, 48, 6, 13, 0, 49, 6, 13, 1, 50, 6, 13, 2, 51, 6, 13, 3, 52, 6, 14, 0, 53, 6, 14, 1, 54, 6, 14, 2, 55, 6, 14, 3, 56, 6, 15, 0, 57, 6, 15, 1, 58, 6, 15, 2, 59, 6, 15, 3, 60, 6, 16, 0, 61, 6, 16, 1, 62, 6, 16, 2, 63, 6, 16, 3 } +T.COEFF_TOKEN_4 = { 1, 2, 0, 0, 7, 6, 1, 0, 1, 1, 1, 1, 4, 6, 2, 0, 6, 6, 2, 1, 1, 3, 2, 2, 3, 6, 3, 0, 3, 7, 3, 1, 2, 7, 3, 2, 5, 6, 3, 3, 2, 6, 4, 0, 3, 8, 4, 1, 2, 8, 4, 2, 0, 7, 4, 3 } +T.TOTAL_ZEROS = { 1, 1, 1, 0, 1, 3, 3, 1, 1, 2, 3, 2, 1, 3, 4, 3, 1, 2, 4, 4, 1, 3, 5, 5, 1, 2, 5, 6, 1, 3, 6, 7, 1, 2, 6, 8, 1, 3, 7, 9, 1, 2, 7, 10, 1, 3, 8, 11, 1, 2, 8, 12, 1, 3, 9, 13, 1, 2, 9, 14, 1, 1, 9, 15, 2, 7, 3, 0, 2, 6, 3, 1, 2, 5, 3, 2, 2, 4, 3, 3, 2, 3, 3, 4, 2, 5, 4, 5, 2, 4, 4, 6, 2, 3, 4, 7, 2, 2, 4, 8, 2, 3, 5, 9, 2, 2, 5, 10, 2, 3, 6, 11, 2, 2, 6, 12, 2, 1, 6, 13, 2, 0, 6, 14, 3, 5, 4, 0, 3, 7, 3, 1, 3, 6, 3, 2, 3, 5, 3, 3, 3, 4, 4, 4, 3, 3, 4, 5, 3, 4, 3, 6, 3, 3, 3, 7, 3, 2, 4, 8, 3, 3, 5, 9, 3, 2, 5, 10, 3, 1, 6, 11, 3, 1, 5, 12, 3, 0, 6, 13, 4, 3, 5, 0, 4, 7, 3, 1, 4, 5, 4, 2, 4, 4, 4, 3, 4, 6, 3, 4, 4, 5, 3, 5, 4, 4, 3, 6, 4, 3, 4, 7, 4, 3, 3, 8, 4, 2, 4, 9, 4, 2, 5, 10, 4, 1, 5, 11, 4, 0, 5, 12, 5, 5, 4, 0, 5, 4, 4, 1, 5, 3, 4, 2, 5, 7, 3, 3, 5, 6, 3, 4, 5, 5, 3, 5, 5, 4, 3, 6, 5, 3, 3, 7, 5, 2, 4, 8, 5, 1, 5, 9, 5, 1, 4, 10, 5, 0, 5, 11, 6, 1, 6, 0, 6, 1, 5, 1, 6, 7, 3, 2, 6, 6, 3, 3, 6, 5, 3, 4, 6, 4, 3, 5, 6, 3, 3, 6, 6, 2, 3, 7, 6, 1, 4, 8, 6, 1, 3, 9, 6, 0, 6, 10, 7, 1, 6, 0, 7, 1, 5, 1, 7, 5, 3, 2, 7, 4, 3, 3, 7, 3, 3, 4, 7, 3, 2, 5, 7, 2, 3, 6, 7, 1, 4, 7, 7, 1, 3, 8, 7, 0, 6, 9, 8, 1, 6, 0, 8, 1, 4, 1, 8, 1, 5, 2, 8, 3, 3, 3, 8, 3, 2, 4, 8, 2, 2, 5, 8, 2, 3, 6, 8, 1, 3, 7, 8, 0, 6, 8, 9, 1, 6, 0, 9, 0, 6, 1, 9, 1, 4, 2, 9, 3, 2, 3, 9, 2, 2, 4, 9, 1, 3, 5, 9, 1, 2, 6, 9, 1, 5, 7, 10, 1, 5, 0, 10, 0, 5, 1, 10, 1, 3, 2, 10, 3, 2, 3, 10, 2, 2, 4, 10, 1, 2, 5, 10, 1, 4, 6, 11, 0, 4, 0, 11, 1, 4, 1, 11, 1, 3, 2, 11, 2, 3, 3, 11, 1, 1, 4, 11, 3, 3, 5, 12, 0, 4, 0, 12, 1, 4, 1, 12, 1, 2, 2, 12, 1, 1, 3, 12, 1, 3, 4, 13, 0, 3, 0, 13, 1, 3, 1, 13, 1, 1, 2, 13, 1, 2, 3, 14, 0, 2, 0, 14, 1, 2, 1, 14, 1, 1, 2, 15, 0, 1, 0, 15, 1, 1, 1 } +T.TOTAL_ZEROS_CDC = { 1, 1, 1, 0, 1, 1, 2, 1, 1, 1, 3, 2, 1, 0, 3, 3, 2, 1, 1, 0, 2, 1, 2, 1, 2, 0, 2, 2, 3, 1, 1, 0, 3, 0, 1, 1 } +T.RUN_BEFORE = { 1, 1, 1, 0, 1, 0, 1, 1, 2, 1, 1, 0, 2, 1, 2, 1, 2, 0, 2, 2, 3, 3, 2, 0, 3, 2, 2, 1, 3, 1, 2, 2, 3, 0, 2, 3, 4, 3, 2, 0, 4, 2, 2, 1, 4, 1, 2, 2, 4, 1, 3, 3, 4, 0, 3, 4, 5, 3, 2, 0, 5, 2, 2, 1, 5, 3, 3, 2, 5, 2, 3, 3, 5, 1, 3, 4, 5, 0, 3, 5, 6, 3, 2, 0, 6, 0, 3, 1, 6, 1, 3, 2, 6, 3, 3, 3, 6, 2, 3, 4, 6, 5, 3, 5, 6, 4, 3, 6, 7, 7, 3, 0, 7, 6, 3, 1, 7, 5, 3, 2, 7, 4, 3, 3, 7, 3, 3, 4, 7, 2, 3, 5, 7, 1, 3, 6, 7, 1, 4, 7, 7, 1, 5, 8, 7, 1, 6, 9, 7, 1, 7, 10, 7, 1, 8, 11, 7, 1, 9, 12, 7, 1, 10, 13, 7, 1, 11, 14 } +T.CABAC_INIT = { 20, -15, 20, -15, 20, -15, 20, -15, 2, 54, 2, 54, 2, 54, 2, 54, 3, 74, 3, 74, 3, 74, 3, 74, 20, -15, 20, -15, 20, -15, 20, -15, 2, 54, 2, 54, 2, 54, 2, 54, 3, 74, 3, 74, 3, 74, 3, 74, -28, 127, -28, 127, -28, 127, -28, 127, -23, 104, -23, 104, -23, 104, -23, 104, -6, 53, -6, 53, -6, 53, -6, 53, -1, 54, -1, 54, -1, 54, -1, 54, 7, 51, 7, 51, 7, 51, 7, 51, 0, 0, 23, 33, 22, 25, 29, 16, 0, 0, 23, 2, 34, 0, 25, 0, 0, 0, 21, 0, 16, 0, 14, 0, 0, 0, 1, 9, -2, 9, -10, 51, 0, 0, 0, 49, 4, 41, -3, 62, 0, 0, -37, 118, -29, 118, -27, 99, 0, 0, 5, 57, 2, 65, 26, 16, 0, 0, -13, 78, -6, 71, -4, 85, 0, 0, -11, 65, -13, 79, -24, 102, 0, 0, 1, 62, 5, 52, 5, 57, 0, 0, 12, 49, 9, 50, 6, 57, 0, 0, -4, 73, -3, 70, -17, 73, 0, 0, 17, 50, 10, 54, 14, 57, 0, 0, 18, 64, 26, 34, 20, 40, 0, 0, 9, 43, 19, 22, 20, 10, 0, 0, 29, 0, 40, 0, 29, 0, 0, 0, 26, 67, 57, 2, 54, 0, 0, 0, 16, 90, 41, 36, 37, 42, 0, 0, 9, 104, 26, 69, 12, 97, 0, 0, -46, 127, -45, 127, -32, 127, 0, 0, -20, 104, -15, 101, -22, 117, 0, 0, 1, 67, -4, 76, -2, 74, 0, 0, -13, 78, -6, 71, -4, 85, 0, 0, -11, 65, -13, 79, -24, 102, 0, 0, 1, 62, 5, 52, 5, 57, 0, 0, -6, 86, 6, 69, -6, 93, 0, 0, -17, 95, -13, 90, -14, 88, 0, 0, -6, 61, 0, 52, -6, 44, 0, 0, 9, 45, 8, 43, 4, 55, 0, 0, -3, 69, -2, 69, -11, 89, 0, 0, -6, 81, -5, 82, -15, 103, 0, 0, -11, 96, -10, 96, -21, 116, 0, 0, 6, 55, 2, 59, 19, 57, 0, 0, 7, 67, 2, 75, 20, 58, 0, 0, -5, 86, -3, 87, 4, 84, 0, 0, 2, 88, -3, 100, 6, 96, 0, 0, 0, 58, 1, 56, 1, 63, 0, 0, -3, 76, -3, 74, -5, 85, 0, 0, -10, 94, -6, 85, -13, 106, 0, 0, 5, 54, 0, 59, 5, 63, 0, 0, 4, 69, -3, 81, 6, 75, 0, 0, -3, 81, -7, 86, -3, 90, 0, 0, 0, 88, -5, 95, -1, 101, 0, 0, -7, 67, -1, 66, 3, 55, 0, 0, -5, 74, -1, 77, -4, 79, 0, 0, -4, 74, 1, 70, -2, 75, 0, 0, -5, 80, -2, 86, -12, 97, 0, 0, -7, 72, -5, 72, -7, 50, 0, 0, 1, 58, 0, 61, 1, 60, 0, 41, 0, 41, 0, 41, 0, 41, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, -9, 83, -9, 83, -9, 83, -9, 83, 4, 86, 4, 86, 4, 86, 4, 86, 0, 97, 0, 97, 0, 97, 0, 97, -7, 72, -7, 72, -7, 72, -7, 72, 13, 41, 13, 41, 13, 41, 13, 41, 3, 62, 3, 62, 3, 62, 3, 62, 0, 11, 0, 45, 13, 15, 7, 34, 1, 55, -4, 78, 7, 51, -9, 88, 0, 69, -3, 96, 2, 80, -20, 127, -17, 127, -27, 126, -39, 127, -36, 127, -13, 102, -28, 98, -18, 91, -17, 91, 0, 82, -25, 101, -17, 96, -14, 95, -7, 74, -23, 67, -26, 81, -25, 84, -21, 107, -28, 82, -35, 98, -25, 86, -27, 127, -20, 94, -24, 102, -12, 89, -31, 127, -16, 83, -23, 97, -17, 91, -24, 127, -22, 110, -27, 119, -31, 127, -18, 95, -21, 91, -24, 99, -14, 76, -27, 127, -18, 102, -21, 110, -18, 103, -21, 114, -13, 93, -18, 102, -13, 90, -30, 127, -29, 127, -36, 127, -37, 127, -17, 123, -7, 92, 0, 80, 11, 80, -12, 115, -5, 89, -5, 89, 5, 76, -16, 122, -7, 96, -7, 94, 2, 84, -11, 115, -13, 108, -4, 92, 5, 78, -12, 63, -3, 46, 0, 39, -6, 55, -2, 68, -1, 65, 0, 65, 4, 61, -15, 84, -1, 57, -15, 84, -14, 83, -13, 104, -9, 93, -35, 127, -37, 127, -3, 70, -3, 74, -2, 73, -5, 79, -8, 93, -9, 92, -12, 104, -11, 104, -10, 90, -8, 87, -9, 91, -11, 91, -30, 127, -23, 126, -31, 127, -30, 127, -1, 74, 5, 54, 3, 55, 0, 65, -6, 97, 6, 60, 7, 56, -2, 79, -7, 91, 6, 59, 7, 55, 0, 72, -20, 127, 6, 69, 8, 61, -4, 92, -4, 56, -1, 48, -3, 53, -6, 56, -5, 82, 0, 68, 0, 68, 3, 68, -7, 76, -4, 69, -7, 74, -8, 71, -22, 125, -8, 88, -9, 88, -13, 98, -7, 93, -2, 85, -13, 103, -4, 86, -11, 87, -6, 78, -13, 91, -12, 88, -3, 77, -1, 75, -9, 89, -5, 82, -5, 71, -7, 77, -14, 92, -3, 72, -4, 63, 2, 54, -8, 76, -4, 67, -4, 68, 5, 50, -12, 87, -8, 72, -12, 84, -3, 68, -23, 110, -16, 89, -7, 62, 1, 50, -24, 105, -9, 69, -7, 65, 6, 42, -10, 78, -1, 59, 8, 61, -4, 81, -20, 112, 5, 66, 5, 56, 1, 63, -17, 99, 4, 57, -2, 66, -4, 70, -78, 127, -4, 71, 1, 64, 0, 67, -70, 127, -2, 71, 0, 61, 2, 57, -50, 127, 2, 58, -2, 78, -2, 76, -46, 127, -1, 74, 1, 50, 11, 35, -4, 66, -4, 44, 7, 52, 4, 64, -5, 78, -1, 69, 10, 35, 1, 61, -4, 71, 0, 62, 0, 44, 11, 35, -8, 72, -7, 51, 11, 38, 18, 25, 2, 59, -4, 47, 1, 45, 12, 24, -1, 55, -6, 42, 0, 46, 13, 29, -7, 70, -3, 41, 5, 44, 13, 36, -6, 75, -6, 53, 31, 17, -10, 93, -8, 89, 8, 76, 1, 51, -7, 73, -34, 119, -9, 78, 7, 50, -2, 73, -3, 75, -11, 83, 28, 19, 13, 46, 32, 20, 9, 52, 16, 33, 9, 49, 30, 22, 0, 67, 14, 62, -7, 100, -44, 127, -5, 90, -13, 108, 9, 53, 0, 54, 1, 67, -15, 100, 2, 53, -5, 61, -15, 72, -13, 101, 5, 53, 0, 58, -5, 75, -13, 91, -2, 61, -1, 60, -8, 80, -12, 94, 0, 56, -3, 61, -21, 83, -10, 88, 0, 56, -8, 67, -21, 64, -16, 84, -13, 63, -25, 84, -13, 31, -10, 86, -5, 60, -14, 74, -25, 64, -7, 83, -1, 62, -5, 65, -29, 94, -13, 87, 4, 57, 5, 52, 9, 75, -19, 94, -6, 69, 2, 57, 17, 63, 1, 70, 4, 57, 0, 61, -8, 74, 0, 72, 14, 39, -9, 69, -5, 35, -5, 74, 4, 51, -11, 70, -2, 27, 18, 59, 13, 68, 18, 55, 13, 91, -8, 102, 3, 64, -4, 71, 3, 65, -15, 100, 1, 61, 0, 58, -7, 69, 0, 95, 9, 63, 7, 61, 8, 77, -4, 75, 7, 50, 9, 41, -10, 66, 2, 72, 16, 39, 18, 25, 3, 62, -11, 75, 5, 44, 9, 32, -3, 68, -3, 71, 4, 52, 5, 43, -20, 81, 15, 46, 11, 48, 9, 47, 0, 30, -13, 69, -5, 60, 0, 44, 1, 7, 0, 62, -1, 59, 0, 51, -3, 23, 0, 65, 0, 59, 2, 46, -21, 74, 21, 37, 22, 33, 19, 38, 16, 66, -15, 72, 5, 44, -4, 66, -23, 124, 9, 57, 14, 43, 15, 38, 17, 37, 16, 54, -1, 78, 12, 42, 44, -18, 0, 62, 0, 60, 9, 34, 50, -34, 12, 72, 9, 69, 0, 89, -22, 127, 24, 0, 11, 28, 4, 45, 4, 39, 15, 9, 2, 40, 10, 28, 0, 42, 8, 25, 3, 44, 10, 31, 7, 34, 13, 18, 0, 49, 33, -11, 11, 29, 15, 9, 0, 46, 52, -43, 8, 31, 13, 19, 2, 44, 18, 15, 6, 37, 10, 37, 2, 51, 28, 0, 7, 42, 12, 18, 0, 47, 35, -22, 3, 40, 6, 29, 4, 39, 38, -25, 8, 33, 20, 33, 2, 62, 34, 0, 13, 43, 15, 30, 6, 46, 39, -18, 13, 36, 4, 45, 0, 54, 32, -12, 4, 47, 1, 58, 3, 54, 102, -94, 3, 55, 0, 62, 2, 58, 0, 0, 2, 58, 7, 61, 4, 63, 56, -15, 6, 60, 12, 38, 6, 51, 33, -4, 8, 44, 11, 45, 6, 57, 29, 10, 11, 44, 15, 39, 7, 53, 37, -5, 14, 42, 11, 42, 6, 52, 51, -29, 7, 48, 13, 44, 6, 55, 39, -9, 4, 56, 16, 45, 11, 45, 52, -34, 4, 52, 12, 41, 14, 36, 69, -58, 13, 37, 10, 49, 8, 53, 67, -63, 9, 49, 30, 34, -1, 82, 44, -5, 19, 58, 18, 42, 7, 55, 32, 7, 10, 48, 10, 55, -3, 78, 55, -29, 12, 45, 17, 51, 15, 46, 32, 1, 0, 69, 17, 46, 22, 31, 0, 0, 20, 33, 0, 89, -1, 84, 27, 36, 8, 63, 26, -19, 25, 7, 33, -25, 35, -18, 22, -17, 30, -7, 34, -30, 33, -25, 26, -17, 28, 3, 36, -28, 28, -3, 30, -25, 28, 4, 38, -28, 24, 10, 28, -20, 32, 0, 38, -27, 27, 0, 33, -23, 34, -1, 34, -18, 34, -14, 37, -27, 30, 6, 35, -16, 52, -44, 33, -23, 30, 6, 34, -14, 39, -24, 40, -28, 32, 9, 32, -8, 19, 17, 38, -17, 31, 19, 37, -6, 31, 25, 33, -11, 26, 27, 35, 0, 36, 29, 40, -15, 26, 30, 30, 10, 24, 33, 41, -6, 37, 20, 28, 18, 34, 15, 38, 1, 28, 34, 26, 25, 30, 20, 41, 17, 17, 70, 29, 41, 22, 73, 30, -6, 1, 67, 0, 75, 20, 34, 27, 3, 5, 59, 2, 72, 19, 31, 26, 22, 9, 67, 8, 77, 27, 44, 37, -16, 16, 30, 14, 35, 19, 16, 35, -4, 18, 32, 18, 31, 15, 36, 38, -8, 18, 35, 17, 35, 15, 36, 38, -3, 22, 29, 21, 30, 21, 28, 37, 3, 24, 31, 17, 45, 25, 21, 38, 5, 23, 38, 20, 42, 30, 20, 42, 0, 18, 43, 18, 45, 31, 12, 35, 16, 20, 41, 27, 26, 27, 16, 39, 22, 11, 63, 16, 54, 24, 42, 14, 48, 9, 59, 7, 66, 0, 93, 27, 37, 9, 64, 16, 56, 14, 56, 21, 60, -1, 94, 11, 73, 15, 57, 12, 68, -2, 89, 10, 67, 26, 38, 2, 97, -9, 108, -10, 116, -24, 127, -3, 71, -6, 76, -23, 112, -24, 115, -6, 42, -2, 44, -15, 71, -22, 82, -5, 50, 0, 45, -7, 61, -9, 62, -3, 54, 0, 52, 0, 53, 0, 53, -2, 62, -3, 64, -5, 66, 0, 59, 0, 58, -2, 59, -11, 77, -14, 85, 1, 63, -4, 70, -9, 80, -13, 89, -2, 72, -4, 75, -9, 84, -13, 94, -1, 74, -8, 82, -10, 87, -11, 92, -9, 91, -17, 102, -34, 127, -29, 127, -5, 67, -9, 77, -21, 101, -21, 100, -5, 27, 3, 24, -3, 39, -14, 57, -3, 39, 0, 42, -5, 53, -12, 67, -2, 44, 0, 48, -7, 61, -11, 71, 0, 46, 0, 55, -11, 75, -10, 77, -16, 64, -6, 59, -15, 77, -21, 85, -8, 68, -7, 71, -17, 91, -16, 88, -10, 78, -12, 83, -25, 107, -23, 104, -6, 77, -11, 87, -25, 111, -15, 98, -10, 86, -30, 119, -28, 122, -37, 127, -12, 92, 1, 58, -11, 76, -10, 82, -15, 55, -3, 29, -10, 44, -8, 48, -10, 60, -1, 36, -10, 52, -8, 61, -6, 62, 1, 38, -10, 57, -8, 66, -4, 65, 2, 43, -9, 58, -7, 70, -12, 73, -6, 55, -16, 72, -14, 75, -8, 76, 0, 58, -7, 69, -10, 79, -7, 80, 0, 64, -4, 69, -9, 83, -9, 88, -3, 74, -5, 74, -12, 92, -17, 110, -10, 90, -9, 86, -18, 108, -11, 97, 0, 70, 2, 66, -4, 79, -20, 84, -4, 29, -9, 34, -22, 69, -11, 79, 5, 31, 1, 32, -16, 75, -6, 73, 7, 42, 11, 31, -2, 58, -4, 74, 1, 59, 5, 52, 1, 58, -13, 86, -2, 58, -2, 55, -13, 78, -13, 96, -3, 72, -2, 67, -9, 83, -11, 97, -3, 81, 0, 73, -4, 81, -19, 117, -11, 97, -8, 89, -13, 99, -8, 78, 0, 58, 3, 52, -13, 81, -5, 33, 8, 5, 7, 4, -6, 38, -4, 48, 10, 14, 10, 8, -13, 62, -2, 53, 14, 18, 17, 8, -6, 58, -3, 62, 13, 27, 16, 19, -2, 59, -13, 71, 2, 40, 3, 37, -16, 73, -10, 79, 0, 58, -1, 61, -10, 76, -12, 86, -3, 70, -5, 73, -13, 86, -13, 90, -6, 79, -1, 70, -9, 83, -14, 97, -8, 85, -4, 78, -10, 87, 0, 0, 0, 0, 0, 0, 0, 0, -6, 93, -13, 106, -21, 126, -22, 127, -6, 84, -16, 106, -23, 124, -25, 127, -8, 79, -10, 87, -20, 110, -25, 120, 0, 66, -21, 114, -26, 126, -27, 127, -1, 71, -18, 110, -25, 124, -19, 114, 0, 62, -14, 98, -17, 105, -23, 117, -2, 60, -22, 110, -27, 121, -25, 118, -2, 59, -21, 106, -27, 117, -26, 117, -5, 75, -18, 103, -17, 102, -24, 113, -3, 62, -21, 107, -26, 117, -28, 118, -4, 58, -23, 108, -27, 116, -31, 120, -9, 66, -26, 112, -33, 122, -37, 124, -1, 79, -10, 96, -10, 95, -10, 94, 0, 71, -12, 95, -14, 100, -15, 102, 3, 68, -5, 91, -8, 95, -10, 99, 10, 44, -9, 93, -17, 111, -13, 106, -7, 62, -22, 94, -28, 114, -50, 127, 15, 36, -5, 86, -6, 89, -5, 92, 14, 40, 9, 67, -2, 80, 17, 57, 16, 27, -4, 80, -4, 82, -5, 86, 12, 29, -10, 85, -9, 85, -13, 94, 1, 44, -1, 70, -8, 81, -12, 91, 20, 36, 7, 60, -1, 72, -2, 77, 18, 32, 9, 58, 5, 64, 0, 71, 5, 42, 5, 61, 1, 67, -1, 73, 1, 48, 12, 50, 9, 56, 4, 64, 10, 62, 15, 50, 0, 69, -7, 81, 17, 46, 18, 49, 1, 69, 5, 64, 9, 64, 17, 54, 7, 69, 15, 57, -12, 104, 10, 41, -7, 69, 1, 67, -11, 97, 7, 46, -6, 67, 0, 68, -16, 96, -1, 51, -16, 77, -10, 67, -7, 88, 7, 49, -2, 64, 1, 68, -8, 85, 8, 52, 2, 61, 0, 77, -7, 85, 9, 41, -6, 67, 2, 64, -9, 85, 6, 47, -3, 64, 0, 68, -13, 88, 2, 55, 2, 57, -5, 78, 4, 66, 13, 41, -3, 65, 7, 55, -3, 77, 10, 44, -3, 66, 5, 59, -3, 76, 6, 50, 0, 62, 2, 65, -6, 76, 5, 53, 9, 51, 14, 54, 10, 58, 13, 49, -1, 66, 15, 44, -1, 76, 4, 63, -2, 71, 5, 60, -1, 83, 6, 64, -2, 75, 2, 70, -7, 99, -2, 69, -1, 70, -2, 76, -14, 95, -2, 59, -9, 72, -18, 86, 2, 95, 6, 70, 14, 60, 12, 70, 0, 76, 10, 44, 16, 37, 5, 64, -5, 74, 9, 31, 0, 47, -12, 70, 0, 70, 12, 43, 18, 35, 11, 55, -11, 75, 3, 53, 11, 37, 5, 56, 1, 68, 14, 34, 12, 41, 0, 69, 0, 65, 10, 38, 10, 41, 2, 65, -14, 73, -3, 52, 2, 48, -6, 74, 3, 62, 13, 40, 12, 41, 5, 54, 4, 62, 17, 32, 13, 41, 7, 54, -1, 68, 7, 44, 0, 59, -6, 76, -13, 75, 7, 38, 3, 50, -11, 82, 11, 55, 13, 50, 19, 40, -2, 77, 5, 64, 10, 57, 3, 66, -2, 77, 12, 70, 26, 43, 18, 50, 25, 42, 15, 6, 14, 11, 19, -6, 17, -13, 6, 19, 11, 14, 18, -6, 16, -9, 7, 16, 9, 11, 14, 0, 17, -12, 12, 14, 18, 11, 26, -12, 27, -21, 18, 13, 21, 9, 31, -16, 37, -30, 13, 11, 23, -2, 33, -25, 41, -40, 13, 15, 32, -15, 33, -22, 42, -41, 15, 16, 32, -15, 37, -28, 48, -47, 12, 23, 34, -21, 39, -30, 39, -32, 13, 23, 39, -23, 42, -30, 46, -40, 15, 20, 42, -33, 47, -42, 52, -51, 14, 26, 41, -31, 45, -36, 46, -41, 14, 44, 46, -28, 49, -34, 52, -39, 17, 40, 38, -12, 41, -17, 43, -19, 17, 47, 21, 29, 32, 9, 32, 11, 24, 17, 45, -24, 69, -71, 61, -55, 21, 21, 53, -45, 63, -63, 56, -46, 25, 22, 48, -26, 66, -64, 62, -50, 31, 27, 65, -43, 77, -74, 81, -67, 22, 29, 43, -19, 54, -39, 45, -20, 19, 35, 39, -10, 52, -35, 35, -2, 14, 50, 30, 9, 41, -10, 28, 15, 10, 57, 18, 26, 36, 0, 34, 1, 7, 63, 20, 27, 40, -1, 39, 1, -2, 77, 0, 57, 30, 14, 30, 17, -4, 82, -14, 82, 28, 26, 20, 38, -3, 94, -5, 75, 23, 37, 18, 45, 9, 69, -19, 97, 12, 55, 15, 54, -12, 109, -35, 125, 11, 65, 0, 79, 36, -35, 27, 0, 37, -33, 36, -16, 36, -34, 28, 0, 39, -36, 37, -14, 32, -26, 31, -4, 40, -37, 37, -17, 37, -30, 27, 6, 38, -30, 32, 1, 44, -32, 34, 8, 46, -33, 34, 15, 34, -18, 30, 10, 42, -30, 29, 15, 34, -15, 24, 22, 40, -24, 24, 25, 40, -15, 33, 19, 49, -29, 34, 22, 33, -7, 22, 32, 38, -12, 31, 16, 35, -5, 26, 31, 40, -10, 35, 18, 33, 0, 21, 41, 38, -3, 31, 28, 38, 2, 26, 44, 46, -5, 33, 41, 33, 13, 23, 47, 31, 20, 36, 28, 23, 35, 16, 65, 29, 30, 27, 47, 13, 58, 14, 71, 25, 44, 21, 62, 29, -3, 8, 60, 12, 48, 18, 31, 26, 0, 6, 63, 11, 49, 19, 26, 22, 30, 17, 65, 26, 45, 36, 24, 31, -7, 21, 24, 22, 22, 24, 23, 35, -15, 23, 20, 23, 22, 27, 16, 34, -3, 26, 23, 27, 21, 24, 30, 34, 3, 27, 32, 33, 20, 31, 29, 36, -1, 28, 23, 26, 28, 22, 41, 34, 5, 28, 24, 30, 24, 22, 42, 32, 11, 23, 40, 27, 34, 16, 60, 35, 5, 24, 32, 18, 42, 15, 52, 34, 12, 28, 29, 25, 39, 14, 60, 39, 11, 23, 42, 18, 50, 3, 78, 30, 29, 19, 57, 12, 70, -16, 123, 34, 26, 22, 53, 21, 54, 21, 53, 29, 39, 22, 61, 14, 71, 22, 56, 19, 66, 11, 86, 11, 83, 25, 61, 31, 21, 12, 40, 25, 32, 21, 33, 31, 31, 11, 51, 21, 49, 19, 50, 25, 50, 14, 59, 21, 54, 17, 61, -17, 120, -4, 79, -5, 85, -3, 78, -20, 112, -7, 71, -6, 81, -8, 74, -18, 114, -5, 69, -10, 77, -9, 72, -11, 85, -9, 70, -7, 81, -10, 72, -15, 92, -8, 66, -17, 80, -18, 75, -14, 89, -10, 68, -18, 73, -12, 71, -26, 71, -19, 73, -4, 74, -11, 63, -15, 81, -12, 69, -10, 83, -5, 70, -14, 80, -16, 70, -9, 71, -17, 75, 0, 68, -15, 67, -9, 67, -14, 72, -14, 70, -20, 62, -1, 61, -16, 67, -24, 56, -19, 70, -8, 66, -8, 53, -23, 68, -16, 66, -14, 66, -14, 59, -24, 50, -22, 65, 0, 59, -9, 52, -11, 74, -20, 63, 2, 59, -11, 68, 23, -13, 9, -2, 17, -10, 9, -2, 26, -13, 26, -9, 32, -13, 30, -10, 40, -15, 33, -9, 42, -9, 31, -4, 49, -14, 39, -7, 49, -5, 33, -1, 44, 3, 41, -2, 53, 0, 33, 7, 45, 6, 45, 3, 64, 3, 31, 12, 44, 34, 49, 9, 68, 10, 37, 23, 33, 54, 45, 27, 66, 27, 31, 38, 19, 82, 36, 59, 47, 57, 20, 64, -3, 75, -6, 66, -5, 71, -9, 71, -1, 23, -7, 35, 0, 24, -7, 37, 1, 34, -7, 42, -1, 36, -8, 44, 1, 43, -8, 45, -2, 42, -11, 49, 0, 54, -5, 48, -2, 52, -10, 56, -2, 55, -12, 56, -9, 57, -12, 59, 0, 61, -6, 60, -6, 63, -8, 63, 1, 64, -5, 62, -4, 65, -9, 67, 0, 68, -8, 66, -4, 67, -6, 68, -9, 92, -8, 76, -7, 82, -10, 79, -14, 106, -5, 85, -3, 81, -3, 78, -13, 97, -6, 81, -3, 76, -8, 74, -15, 90, -10, 77, -7, 72, -9, 72, -12, 90, -7, 81, -6, 78, -10, 72, -18, 88, -17, 80, -12, 72, -18, 75, -10, 73, -18, 73, -14, 68, -12, 71, -9, 79, -4, 74, -3, 70, -11, 63, -14, 86, -10, 83, -6, 76, -5, 70, -10, 73, -9, 71, -5, 66, -17, 75, -10, 70, -9, 67, -5, 62, -14, 72, -10, 69, -1, 61, 0, 57, -16, 67, -5, 66, -8, 66, -4, 61, -8, 53, -9, 64, -14, 66, -9, 60, -14, 59, -5, 58, 0, 59, 1, 54, -9, 52, 2, 59, 2, 59, 2, 58, -11, 68, 21, -10, 21, -13, 17, -10, 9, -2, 24, -11, 33, -14, 32, -13, 30, -10, 28, -8, 39, -7, 42, -9, 31, -4, 28, -1, 46, -2, 49, -5, 33, -1, 29, 3, 51, 2, 53, 0, 33, 7, 29, 9, 60, 6, 64, 3, 31, 12, 35, 20, 61, 17, 68, 10, 37, 23, 29, 36, 55, 34, 66, 27, 31, 38, 14, 67, 42, 62, 47, 57, 20, 64 } +T.RANGE_LPS = { 128, 176, 208, 240, 128, 167, 197, 227, 128, 158, 187, 216, 123, 150, 178, 205, 116, 142, 169, 195, 111, 135, 160, 185, 105, 128, 152, 175, 100, 122, 144, 166, 95, 116, 137, 158, 90, 110, 130, 150, 85, 104, 123, 142, 81, 99, 117, 135, 77, 94, 111, 128, 73, 89, 105, 122, 69, 85, 100, 116, 66, 80, 95, 110, 62, 76, 90, 104, 59, 72, 86, 99, 56, 69, 81, 94, 53, 65, 77, 89, 51, 62, 73, 85, 48, 59, 69, 80, 46, 56, 66, 76, 43, 53, 63, 72, 41, 50, 59, 69, 39, 48, 56, 65, 37, 45, 54, 62, 35, 43, 51, 59, 33, 41, 48, 56, 32, 39, 46, 53, 30, 37, 43, 50, 29, 35, 41, 48, 27, 33, 39, 45, 26, 31, 37, 43, 24, 30, 35, 41, 23, 28, 33, 39, 22, 27, 32, 37, 21, 26, 30, 35, 20, 24, 29, 33, 19, 23, 27, 31, 18, 22, 26, 30, 17, 21, 25, 28, 16, 20, 23, 27, 15, 19, 22, 25, 14, 18, 21, 24, 14, 17, 20, 23, 13, 16, 19, 22, 12, 15, 18, 21, 12, 14, 17, 20, 11, 14, 16, 19, 11, 13, 15, 18, 10, 12, 15, 17, 10, 12, 14, 16, 9, 11, 13, 15, 9, 11, 12, 14, 8, 10, 12, 14, 8, 9, 11, 13, 7, 9, 11, 12, 7, 9, 10, 12, 7, 8, 10, 11, 6, 8, 9, 11, 6, 7, 9, 10, 6, 7, 8, 9, 2, 2, 2, 2 } +T.TRANS = { 0, 1, 0, 2, 1, 3, 2, 4, 2, 5, 4, 6, 4, 7, 5, 8, 6, 9, 7, 10, 8, 11, 9, 12, 9, 13, 11, 14, 11, 15, 12, 16, 13, 17, 13, 18, 15, 19, 15, 20, 16, 21, 16, 22, 18, 23, 18, 24, 19, 25, 19, 26, 21, 27, 21, 28, 22, 29, 22, 30, 23, 31, 24, 32, 24, 33, 25, 34, 26, 35, 26, 36, 27, 37, 27, 38, 28, 39, 29, 40, 29, 41, 30, 42, 30, 43, 30, 44, 31, 45, 32, 46, 32, 47, 33, 48, 33, 49, 33, 50, 34, 51, 34, 52, 35, 53, 35, 54, 35, 55, 36, 56, 36, 57, 36, 58, 37, 59, 37, 60, 37, 61, 38, 62, 38, 62, 63, 63 } +T.CHROMA_QP = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 29, 30, 31, 32, 32, 33, 34, 34, 35, 35, 36, 36, 37, 37, 37, 38, 38, 38, 39, 39, 39, 39 } +T.INTRA_CBP = { 47, 31, 15, 0, 23, 27, 29, 30, 7, 11, 13, 14, 39, 43, 45, 46, 16, 3, 5, 10, 12, 19, 21, 26, 28, 35, 37, 42, 44, 1, 2, 4, 8, 17, 18, 20, 24, 6, 9, 22, 25, 32, 33, 34, 36, 40, 38, 41 } +T.INTER_CBP = { 0, 16, 1, 2, 4, 8, 32, 3, 5, 10, 12, 15, 47, 7, 11, 13, 14, 6, 9, 31, 35, 37, 42, 44, 33, 34, 36, 40, 39, 43, 45, 46, 17, 18, 20, 24, 19, 21, 26, 28, 23, 27, 29, 30, 22, 25, 38, 41 } +T.DEFAULT_4x4 = { 6, 13, 20, 28, 13, 20, 28, 32, 20, 28, 32, 37, 28, 32, 37, 42, 10, 14, 20, 24, 14, 20, 24, 27, 20, 24, 27, 30, 24, 27, 30, 34 } +T.DEFAULT_8x8 = { 6, 10, 13, 16, 18, 23, 25, 27, 10, 11, 16, 18, 23, 25, 27, 29, 13, 16, 18, 23, 25, 27, 29, 31, 16, 18, 23, 25, 27, 29, 31, 33, 18, 23, 25, 27, 29, 31, 33, 36, 23, 25, 27, 29, 31, 33, 36, 38, 25, 27, 29, 31, 33, 36, 38, 40, 27, 29, 31, 33, 36, 38, 40, 42, 9, 13, 15, 17, 19, 21, 22, 24, 13, 13, 17, 19, 21, 22, 24, 25, 15, 17, 19, 21, 22, 24, 25, 27, 17, 19, 21, 22, 24, 25, 27, 28, 19, 21, 22, 24, 25, 27, 28, 30, 21, 22, 24, 25, 27, 28, 30, 32, 22, 24, 25, 27, 28, 30, 32, 33, 24, 25, 27, 28, 30, 32, 33, 35 } +T.ZIGZAG4 = { 0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15 } +T.ZIGZAG8 = { 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63 } +T.SIG8 = { 0, 1, 2, 3, 4, 5, 5, 4, 4, 3, 3, 4, 4, 4, 5, 5, 4, 4, 4, 4, 3, 3, 6, 7, 7, 7, 8, 9, 10, 9, 8, 7, 7, 6, 11, 12, 13, 11, 6, 7, 8, 9, 14, 10, 9, 8, 6, 11, 12, 13, 11, 6, 9, 14, 10, 9, 11, 12, 13, 11, 14, 10, 12, 14 } +T.LAST8 = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8 } +T.ALPHA = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 5, 6, 7, 8, 9, 10, 12, 13, 15, 17, 20, 22, 25, 28, 32, 36, 40, 45, 50, 56, 63, 71, 80, 90, 101, 113, 127, 144, 162, 182, 203, 226, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 } +T.BETA = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18 } +T.TC0 = { -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 1, -1, 0, 0, 1, -1, 0, 0, 1, -1, 0, 0, 1, -1, 0, 1, 1, -1, 0, 1, 1, -1, 1, 1, 1, -1, 1, 1, 1, -1, 1, 1, 1, -1, 1, 1, 1, -1, 1, 1, 2, -1, 1, 1, 2, -1, 1, 1, 2, -1, 1, 1, 2, -1, 1, 2, 3, -1, 1, 2, 3, -1, 2, 2, 3, -1, 2, 2, 4, -1, 2, 3, 4, -1, 2, 3, 4, -1, 3, 3, 5, -1, 3, 4, 6, -1, 3, 4, 6, -1, 4, 5, 7, -1, 4, 5, 8, -1, 4, 6, 9, -1, 5, 7, 10, -1, 6, 8, 11, -1, 6, 8, 13, -1, 7, 10, 14, -1, 8, 11, 16, -1, 9, 12, 18, -1, 10, 13, 20, -1, 11, 15, 23, -1, 13, 17, 25, -1, 13, 17, 25, -1, 13, 17, 25, -1, 13, 17, 25, -1, 13, 17, 25, -1, 13, 17, 25, -1, 13, 17, 25, -1, 13, 17, 25, -1, 13, 17, 25, -1, 13, 17, 25, -1, 13, 17, 25, -1, 13, 17, 25, -1, 13, 17, 25 } + +return T +end +__FILES["codecs/video/H264/Transform"] = @native function() + + + +-- codecs/video/H264/Transform: the inverse transforms of ITU-T H.264 8.5 (4x4 / 8x8 IDCT 8.5.12.2 / 8.5.13.2 / 8.5.14, +-- luma DC / chroma DC Hadamard 8.5.10 / 8.5.11.2). Coefficients come dequantised, raster order, at base + 1; zeroed after use. +local readu8, writeu8 = buffer.readu8, buffer.writeu8 + +local Transform = {} + +local min, max = math.min, math.max +@native local function clip(v: number): number + return min(max(v, 0), 255) +end + +@native function Transform.add4(c: { number }, base: number, b: buffer, o: number, s: number) + for i = 0, 3 do + local k = base + i * 4 + local d0, d1, d2, d3 = c[k + 1], c[k + 2], c[k + 3], c[k + 4] + local e = d0 + d2 + local f = d0 - d2 + local g = d1 // 2 - d3 + local h = d1 + d3 // 2 + c[k + 1] = e + h + c[k + 2] = f + g + c[k + 3] = f - g + c[k + 4] = e - h + end + for j = 0, 3 do + local k = base + j + local d0, d1, d2, d3 = c[k + 1], c[k + 5], c[k + 9], c[k + 13] + local e = d0 + d2 + local f = d0 - d2 + local g = d1 // 2 - d3 + local h = d1 + d3 // 2 + c[k + 1], c[k + 5], c[k + 9], c[k + 13] = 0, 0, 0, 0 + local p = o + j + writeu8(b, p, clip(readu8(b, p) + (e + h + 32) // 64)) + p += s + writeu8(b, p, clip(readu8(b, p) + (f + g + 32) // 64)) + p += s + writeu8(b, p, clip(readu8(b, p) + (f - g + 32) // 64)) + p += s + writeu8(b, p, clip(readu8(b, p) + (e - h + 32) // 64)) + end +end + +@native function Transform.addDc4(dc: number, b: buffer, o: number, s: number) + local v = (dc + 32) // 64 + if v == 0 then + return + end + for y = 0, 3 do + local p = o + y * s + writeu8(b, p, clip(readu8(b, p) + v)) + writeu8(b, p + 1, clip(readu8(b, p + 1) + v)) + writeu8(b, p + 2, clip(readu8(b, p + 2) + v)) + writeu8(b, p + 3, clip(readu8(b, p + 3) + v)) + end +end + +local T8 = table.create(64, 0) + +@native function Transform.add8(c: { number }, base: number, b: buffer, o: number, s: number) + for pass = 0, 1 do + for i = 0, 7 do + local d0, d1, d2, d3, d4, d5, d6, d7 + if pass == 0 then + local k = base + i * 8 + d0, d1, d2, d3, d4, d5, d6, d7 = c[k + 1], c[k + 2], c[k + 3], c[k + 4], c[k + 5], c[k + 6], c[k + 7], c[k + 8] + c[k + 1], c[k + 2], c[k + 3], c[k + 4], c[k + 5], c[k + 6], c[k + 7], c[k + 8] = 0, 0, 0, 0, 0, 0, 0, 0 + else + d0, d1, d2, d3, d4, d5, d6, d7 = T8[i + 1], T8[i + 9], T8[i + 17], T8[i + 25], T8[i + 33], T8[i + 41], T8[i + 49], T8[i + 57] + end + local a0 = d0 + d4 + local a4 = d0 - d4 + local a2 = d2 // 2 - d6 + local a6 = d2 + d6 // 2 + local b0 = a0 + a6 + local b2 = a4 + a2 + local b4 = a4 - a2 + local b6 = a0 - a6 + local a1 = -d3 + d5 - d7 - d7 // 2 + local a3 = d1 + d7 - d3 - d3 // 2 + local a5 = -d1 + d7 + d5 + d5 // 2 + local a7 = d3 + d5 + d1 + d1 // 2 + local b1 = a1 + a7 // 4 + local b7 = a7 - a1 // 4 + local b3 = a3 + a5 // 4 + local b5 = a3 // 4 - a5 + if pass == 0 then + local k = i * 8 + T8[k + 1] = b0 + b7 + T8[k + 2] = b2 + b5 + T8[k + 3] = b4 + b3 + T8[k + 4] = b6 + b1 + T8[k + 5] = b6 - b1 + T8[k + 6] = b4 - b3 + T8[k + 7] = b2 - b5 + T8[k + 8] = b0 - b7 + else + local p = o + i + writeu8(b, p, clip(readu8(b, p) + (b0 + b7 + 32) // 64)) + p += s + writeu8(b, p, clip(readu8(b, p) + (b2 + b5 + 32) // 64)) + p += s + writeu8(b, p, clip(readu8(b, p) + (b4 + b3 + 32) // 64)) + p += s + writeu8(b, p, clip(readu8(b, p) + (b6 + b1 + 32) // 64)) + p += s + writeu8(b, p, clip(readu8(b, p) + (b6 - b1 + 32) // 64)) + p += s + writeu8(b, p, clip(readu8(b, p) + (b4 - b3 + 32) // 64)) + p += s + writeu8(b, p, clip(readu8(b, p) + (b2 - b5 + 32) // 64)) + p += s + writeu8(b, p, clip(readu8(b, p) + (b0 - b7 + 32) // 64)) + end + end + end +end + +-- m = LevelScale4x4(qP % 6, 0, 0) * 2^(qP / 6) +@native function Transform.lumaDc(dc: { number }, m: number, c: { number }) + for i = 0, 3 do + local k = i * 4 + local d0, d1, d2, d3 = dc[k + 1], dc[k + 2], dc[k + 3], dc[k + 4] + local e = d0 + d1 + local f = d0 - d1 + local g = d2 + d3 + local h = d2 - d3 + dc[k + 1] = e + g + dc[k + 2] = e - g + dc[k + 3] = f - h + dc[k + 4] = f + h + end + for j = 0, 3 do + local d0, d1, d2, d3 = dc[j + 1], dc[j + 5], dc[j + 9], dc[j + 13] + local e = d0 + d1 + local f = d0 - d1 + local g = d2 + d3 + local h = d2 - d3 + dc[j + 1], dc[j + 5], dc[j + 9], dc[j + 13] = 0, 0, 0, 0 + c[j * 16 + 1] = ((e + g) * m + 32) // 64 + c[(4 + j) * 16 + 1] = ((e - g) * m + 32) // 64 + c[(8 + j) * 16 + 1] = ((f - h) * m + 32) // 64 + c[(12 + j) * 16 + 1] = ((f + h) * m + 32) // 64 + end +end + +@native function Transform.chromaDc(dc: { number }, base: number, m: number, c: { number }, cbase: number) + local c0, c1, c2, c3 = dc[base + 1], dc[base + 2], dc[base + 3], dc[base + 4] + dc[base + 1], dc[base + 2], dc[base + 3], dc[base + 4] = 0, 0, 0, 0 + local e = c0 + c1 + local f = c0 - c1 + local g = c2 + c3 + local h = c2 - c3 + c[cbase + 1] = ((e + g) * m) // 32 + c[cbase + 17] = ((f + h) * m) // 32 + c[cbase + 33] = ((e - g) * m) // 32 + c[cbase + 49] = ((f - h) * m) // 32 +end + +return Transform +end +end + + + + + + Theora + --!optimize 2 +--!nocheck +-- rosetta chunk Theora (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 3 modules (1 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["codecs/video/Theora"] = function() + +-- codecs/video/Theora: a Theora video decoder (the Theora I specification, Xiph.Org), for Ogg and Matroska (V_THEORA). +-- A Luau port of the libtheora 1.2.0 decoder (BSD 3-clause, licenses/libtheora-BSD.txt), bit-exact with libtheora / +-- ffmpeg; libtheora's optional post-processing is not supported. +local Err = __include("core/Err") +local Types = __include("Types") +local VorbisComment = __include("codecs/audio/VorbisComment") +local Header = __include("codecs/video/Theora/Header") +local Decoder = __include("codecs/video/Theora/Decoder") + +local Theora = {} + +type Info = Header.Info + +type Options = { + maxPixels: number?, +} + +local PIXEL_FORMATS = { [0] = "yuv420p", "reserved", "yuv422p", "yuv444p" } + +function Theora.isHeader(b: buffer, off: number?, len: number?): number? + local o = off or 0 + local n = len or (buffer.len(b) - o) + if n < 7 then + return nil + end + local t = buffer.readu8(b, o) + if t >= 0x80 and t <= 0x82 and buffer.readstring(b, o + 1, 6) == "theora" then + return t - 0x7F + end + return nil +end + +function Theora.splitConfig(c: buffer): { buffer }? + local n = buffer.len(c) + if n < 3 or buffer.readu8(c, 0) ~= 2 then + return nil + end + local p, lens = 1, {} + for k = 1, 2 do + local size = 0 + repeat + if p >= n then + return nil + end + local b = buffer.readu8(c, p) + size += b + p += 1 + until b < 255 + lens[k] = size + end + lens[3] = n - p - lens[1] - lens[2] + if lens[3] < 0 then + return nil + end + local out = {} + for k = 1, 3 do + out[k] = buffer.create(lens[k]) + buffer.copy(out[k], 0, c, p, lens[k]) + p += lens[k] + end + return out +end + +function Theora.info(h: buffer): (Header.Info?, Err.Err?) + local ok, info, err = pcall(Header.info, h, 0, buffer.len(h)) + if not ok or not info then + return nil, Err.from(if ok then err else tostring(info)) + end + return info, nil +end + +function Theora.comment(h: buffer): (string?, { string }?, { [string]: string }?, Err.Err?) + local ok, vendor, list, err = pcall(Header.comment, h, 0, buffer.len(h)) + if not ok or not vendor or not list then + return nil, nil, nil, Err.from(if ok then err else tostring(vendor)) + end + return vendor, list, (VorbisComment.tags(list)), nil +end + +function Theora.granuleFrame(info: Header.Info, g: number): number + if g < 0 then + return -1 + end + local shift = 2 ^ info.granuleShift + local key = g // shift + local f = key + g % shift + -- since bitstream 3.2.1 the first frame is granule 1 + local v = info.versionMajor * 65536 + info.versionMinor * 256 + info.versionSub + if v >= 0x030201 then + f -= 1 + end + return f +end + +local Dec = {} +Dec.__index = Dec + +type TheoraDecoder = typeof(setmetatable( + {} :: { + info: Header.Info, + vendor: string, + comments: { string }, + tags: { [string]: string }, + width: number, -- the picture region + height: number, + frameRate: number, + pixelFormat: string, -- "yuv420p" | "yuv422p" | "yuv444p" + aspect: number, -- pixel aspect ratio (1 when unknown) + frames: number, + _st: Decoder.State, + _any: boolean, + }, + Dec +)) + +function Theora.new(headers: { buffer } | buffer, opts: Options?): (TheoraDecoder?, Err.Err?) + local list: { buffer }? = nil + if type(headers) == "buffer" then + list = Theora.splitConfig(headers) + elseif type(headers) == "table" then + list = headers + end + if not list or #list < 3 or type(list[1]) ~= "buffer" or type(list[2]) ~= "buffer" or type(list[3]) ~= "buffer" then + return nil, Err.new(Err.CORRUPT, "missing Theora headers") + end + local info, ierr = Theora.info(list[1]) + if not info then + return nil, ierr + end + local maxPixels = opts and opts.maxPixels or 4096 * 2304 + if info.frameWidth * info.frameHeight > maxPixels then + return nil, Err.new(Err.LIMIT, "frame of " .. info.frameWidth .. "x" .. info.frameHeight .. " is over maxPixels") + end + local vendor, comments, tags, cerr = Theora.comment(list[2]) + if not vendor or not comments or not tags then + return nil, cerr + end + local ok3, setup, serr = pcall(Header.setup, list[3], 0, buffer.len(list[3])) + if not ok3 or not setup then + return nil, Err.from(if ok3 then serr else tostring(setup)) + end + local st = Decoder.new(info, setup) + return setmetatable({ + info = info, + vendor = vendor, + comments = comments, + tags = tags, + width = info.picWidth, + height = info.picHeight, + frameRate = info.fpsNum / info.fpsDen, + pixelFormat = PIXEL_FORMATS[info.pixelFormat], + aspect = if info.aspectNum > 0 and info.aspectDen > 0 then info.aspectNum / info.aspectDen else 1, + frames = 0, + _st = st, + _any = false, + }, Dec), nil +end + +function Dec.decode(self: TheoraDecoder, data: buffer, off: number?, len: number?): (string?, Err.Err?) + local o = off or 0 + local n = len or (buffer.len(data) - o) + if o < 0 or n < 0 or o + n > buffer.len(data) then + return nil, Err.new(Err.ARG, "decode: range outside the buffer") + end + if n > 0 and buffer.readu8(data, o) >= 0x80 then + return nil, nil + end + local kind, msg = Decoder.decode(self._st, data, o, n) + if not kind then + return nil, Err.from(msg) + end + self.frames += 1 + if kind ~= "dup" then + self._any = true + end + return kind, nil +end + +function Dec.reset(self: TheoraDecoder) + local st = self._st + st.shown = st.prev +end + +local function window(self: TheoraDecoder): (number, number, number, number) + local info = self.info + -- the picture's top-left corner counted from the top of the frame (the header counts y from the bottom) + return info.picX, info.frameHeight - info.picHeight - info.picY, info.picWidth, info.picHeight +end + +function Dec.planes(self: TheoraDecoder): (buffer, buffer, buffer, number, number) + local st = self._st + local x0, y0, w, h = window(self) + local hd, vd = st.hdec, st.vdec + local cx0, cy0 = x0 // 2 ^ hd, y0 // 2 ^ vd + local cw, ch = (w + hd) // 2 ^ hd, (h + vd) // 2 ^ vd + cw = math.min(cw, st.pw[2] - cx0) + ch = math.min(ch, st.ph[2] - cy0) + return Decoder.plane(st, 0, x0, y0, w, h), Decoder.plane(st, 1, cx0, cy0, cw, ch), Decoder.plane(st, 2, cx0, cy0, cw, ch), cw, ch +end + +function Dec.image(self: TheoraDecoder): Types.Image + local y, u, v, cw, ch = self:planes() + local w, h = self.width, self.height + local img = Types.Image.new(w, h, "yuv420p") + local px = img.pixels + local ow, oh = (w + 1) // 2, (h + 1) // 2 + buffer.copy(px, 0, y, 0, w * h) + local st = self._st + if st.hdec == 1 and st.vdec == 1 then + for r = 0, oh - 1 do + local sr = math.min(r, ch - 1) + buffer.copy(px, w * h + r * ow, u, sr * cw, math.min(ow, cw)) + buffer.copy(px, w * h + ow * oh + r * ow, v, sr * cw, math.min(ow, cw)) + end + else + Decoder.downsample(u, cw, ch, st.hdec, px, w * h, ow, oh) + Decoder.downsample(v, cw, ch, st.hdec, px, w * h + ow * oh, ow, oh) + end + img.meta.yuv = { range = "limited", matrix = "bt601" } + img.meta.source = { format = "theora", pixelFormat = self.pixelFormat, colorspace = self.info.colorspace } + return img +end + +function Theora.newVideoDecoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) + if not track.config then + return nil, Err.new(Err.CORRUPT, "Theora track without its headers") + end + local dec, err = Theora.new(track.config :: buffer, { maxPixels = opts and opts.maxPixels }) + if not dec then + return nil, err + end + local d = dec :: TheoraDecoder + local pending: { any } = {} + local self: any = {} + function self.decode(_: any, packet: Types.Packet): Err.Err? + local kind, e = d:decode(packet.data) + if not kind then + return e + end + if d._any then + table.insert(pending, { d:image(), packet.pts, kind == "key" }) + end + return nil + end + function self.receive(_: any): (Types.Image?, number?, boolean?) + local p = table.remove(pending, 1) + if not p then + return nil, nil, nil + end + return p[1], p[2], p[3] + end + function self.flush(_: any) end + function self.reset(_: any) + table.clear(pending) + d:reset() + end + return self, nil +end + +return Theora +end +__FILES["codecs/video/Theora/Decoder"] = @native function() + + + +-- codecs/video/Theora/Decoder: the Theora frame decoder (Theora I specification, section 7). A Luau port of libtheora +-- 1.2.0's decoder (Xiph.Org, BSD 3-clause: licenses/libtheora-BSD.txt; decode.c, state.c, idct.c, fragment.c). +-- DC-only blocks as libtheora: (dc * q + 15) >> 5; IDCT sums are not wrapped to 16 bits (only out-of-range streams differ). +-- Planes are in Theora's orientation (row 0 = bottom) with 16 (luma) / 8 (subsampled chroma) pixels of edge padding. +local Header = __include("codecs/video/Theora/Header") + +local readu8 = buffer.readu8 +local writeu8 = buffer.writeu8 +local readu16 = buffer.readu16 +local readi16 = buffer.readi16 +local writei16 = buffer.writei16 +local readu32 = buffer.readu32 +local writeu32 = buffer.writeu32 +local band = bit32.band +local bxor = bit32.bxor +local bcopy = buffer.copy +local bfill = buffer.fill +local lshift = bit32.lshift +local rshift = bit32.rshift +local bswap = bit32.byteswap + +local D = {} + +-- macro block modes (libtheora's numbering) +local NOMV, INTRA, INTER_MV, MV_LAST, MV_LAST2, GOLD_NOMV, GOLD_MV, FOURMV = 0, 1, 2, 3, 4, 5, 6, 7 +-- reference frames of a fragment (refi) +local GOLD, PREV, SELF, NONE = 0, 1, 2, 3 +local FRAME_FOR_MODE = { [0] = PREV, SELF, PREV, PREV, PREV, GOLD, GOLD, PREV } + +-- the mode alphabets of schemes 1..7 (scheme 0 sends its own) +local ALPHABETS = { + { MV_LAST, MV_LAST2, INTER_MV, NOMV, INTRA, GOLD_NOMV, GOLD_MV, FOURMV }, + { MV_LAST, MV_LAST2, NOMV, INTER_MV, INTRA, GOLD_NOMV, GOLD_MV, FOURMV }, + { MV_LAST, INTER_MV, MV_LAST2, NOMV, INTRA, GOLD_NOMV, GOLD_MV, FOURMV }, + { MV_LAST, INTER_MV, NOMV, MV_LAST2, INTRA, GOLD_NOMV, GOLD_MV, FOURMV }, + { NOMV, MV_LAST, MV_LAST2, INTER_MV, INTRA, GOLD_NOMV, GOLD_MV, FOURMV }, + { NOMV, GOLD_NOMV, MV_LAST, MV_LAST2, INTER_MV, INTRA, GOLD_MV, FOURMV }, + { NOMV, INTRA, INTER_MV, MV_LAST, MV_LAST2, GOLD_NOMV, GOLD_MV, FOURMV }, +} + +-- the macro block mode VLC (0, 10, 110, ..., 1111110, 1111111): by the next 7 bits, index * 8 + length +local MODE_VLC = table.create(128, 0) +for w = 0, 127 do + local n = 0 + while n < 7 and bit32.extract(w, 6 - n, 1) == 1 do + n += 1 + end + MODE_VLC[w + 1] = n * 8 + (if n < 7 then n + 1 else 7) +end + +-- the motion vector component VLC (Theora spec table 7.23): by the next 8 bits, (value + 32) * 16 + length +local MV_VLC = table.create(256, 0) +do + @native local function put(code: number, len: number, v: number) + local sh = 8 - len + for i = 0, 2 ^ sh - 1 do + MV_VLC[code * 2 ^ sh + i + 1] = (v + 32) * 16 + len + end + end + put(0, 3, 0) + put(1, 3, 1) + put(2, 3, -1) + put(6, 4, 2) + put(7, 4, -2) + put(8, 4, 3) + put(9, 4, -3) + for m = 4, 7 do + put(0x28 + (m - 4) * 2, 6, m) + put(0x29 + (m - 4) * 2, 6, -m) + end + for m = 8, 15 do + put(0x60 + (m - 8) * 2, 7, m) + put(0x61 + (m - 8) * 2, 7, -m) + end + for m = 16, 31 do + put(0xE0 + (m - 16) * 2, 8, m) + put(0xE1 + (m - 16) * 2, 8, -m) + end +end + +-- DCT tokens: extra bits per token +local TOKEN_EXTRA = { -- [token + 1] + 0, 0, 0, 2, 3, 4, 12, 3, 6, 0, 0, 0, 0, 1, 1, 1, 1, 2, 3, 4, 5, 6, 10, 1, 1, 1, 1, 1, 3, 4, 2, 3, +} + +-- the zero-run / coefficient tokens (7..31) by token * 1024 + extra bits + 1: run * 4096 + value + 2048, where run is +-- the zeros before the value (value 0: a pure zero run of run + 1) +local TOKEN_VALUE = table.create(32 * 1024, 2048) +for tok = 7, 31 do + local ex = TOKEN_EXTRA[tok + 1] + for eb = 0, 2 ^ ex - 1 do + local v, r = 0, 0 + if tok < 9 then + r = eb -- zero runs: eb + 1 zeros + elseif tok < 13 then + v = if tok == 9 then 1 elseif tok == 10 then -1 elseif tok == 11 then 2 else -2 + elseif tok < 17 then + v = if eb == 1 then -(tok - 10) else tok - 10 + elseif tok < 23 then + local half = 2 ^ (ex - 1) -- the top extra bit is the sign + local base = if tok == 17 then 7 elseif tok == 18 then 9 elseif tok == 19 then 13 elseif tok == 20 then 21 elseif tok == 21 then 37 else 69 + v = base + eb % half + if eb >= half then + v = -v + end + elseif tok < 28 then + r = tok - 22 + v = if eb == 1 then -1 else 1 + elseif tok == 28 then + r = 6 + eb % 4 + v = if eb >= 4 then -1 else 1 + elseif tok == 29 then + r = 10 + eb % 8 + v = if eb >= 8 then -1 else 1 + elseif tok == 30 then + r = 1 + v = 2 + eb % 2 + if eb >= 2 then + v = -v + end + else + r = 2 + eb % 2 + v = 2 + (eb // 2) % 2 + if eb >= 4 then + v = -v + end + end + TOKEN_VALUE[tok * 1024 + eb + 1] = r * 4096 + v + 2048 + end +end + +-- natural index of zig-zag position (1-based by position + 1) +local ZIGZAG = Header.ZIGZAG + +-- clamp to 0..255 by lookup: CLAMP[v + COFF], v in [-COFF, COFF + 255] +local COFF = 70000 +local CLAMP = buffer.create(2 * COFF + 512) +for i = 0, 2 * COFF + 511 do + buffer.writeu8(CLAMP, i, math.clamp(i - COFF, 0, 255)) +end + +local C1, C2, C3, C4, C5, C6, C7 = 64277, 60547, 54491, 46341, 36410, 25080, 12785 + +type State = { + pf: number, + hdec: number, + vdec: number, + fw: number, + fh: number, + pw: { number }, -- plane sizes in pixels, [pli + 1] + ph: { number }, + nhf: { number }, -- plane sizes in fragments + nvf: { number }, + foff: { number }, -- first fragment id - 1 of each plane + stride: { number }, + padx: { number }, + pady: { number }, + origin: { number }, -- byte offset of pixel (0, 0) + planeSize: { number }, + nfrags: number, + nsbs: number, + sbPlane: { number }, -- [pli + 1]: the first super block (0-based) of each plane, and [4] = nsbs + sbFr: { number }, -- [sbi * 16 + quad * 4 + bi + 1]: fragment id (1-based) or 0 + sbQuadValid: { boolean }, -- [sbi * 4 + quad + 1] + nmbs: number, + mbMode: { number }, -- [mbi + 1]: -1 outside the frame + mbFr: { number }, -- [mbi * 12 + pli * 4 + bi + 1]: fragment id or 0 + mapIdx: { number }, -- the valid (pli * 4 + bi) slots of a macro block for this pixel format + -- per fragment [fi] + coded: { number }, + refi: { number }, + fmode: { number }, + mvx: { number }, + mvy: { number }, + qii: { number }, + dcv: { number }, + tis: { number }, + last: { number }, + fpos: { number }, -- byte offset of the fragment's first pixel in its plane + fpl: { number }, -- plane (0..2) + coef: buffer, -- i16 [(fi - 1) * 64 + zzi] + clist: { { number } }, -- coded fragments per plane, coded order + ncl: { number }, + act: { { number } }, + refs: { { buffer } }, -- [r][pli + 1] + gold: number, + prev: number, + shown: number, -- the reference holding the last decoded picture + dequant: buffer, + lflim: { number }, + huff: { number }, + roots: { number }, + blk: buffer, -- i16 x 64 work blocks + tmp: buffer, + bv: { number }, -- the loop filter's bounding values for the frame, [(f + 4) >> 3 + 129] + keyframes: number, +} + +@native function D.new(info: Header.Info, setup: Header.Setup): State + local pf = info.pixelFormat + local hdec = if pf % 2 == 0 then 1 else 0 + local vdec = if pf < 2 then 1 else 0 + local fw, fh = info.frameWidth, info.frameHeight + local st: any = { + pf = pf, + hdec = hdec, + vdec = vdec, + fw = fw, + fh = fh, + pw = {}, + ph = {}, + nhf = {}, + nvf = {}, + foff = {}, + stride = {}, + padx = {}, + pady = {}, + origin = {}, + planeSize = {}, + dequant = setup.dequant, + lflim = setup.lflim, + huff = setup.huff, + roots = setup.roots, + blk = buffer.create(128), + tmp = buffer.create(128), + bv = table.create(257, 0), + keyframes = 0, + } + local nfr = 0 + for pli = 0, 2 do + local hd, vd = if pli > 0 then hdec else 0, if pli > 0 then vdec else 0 + local w, h = fw // 2 ^ hd, fh // 2 ^ vd + local px, py = 16 // 2 ^ hd, 16 // 2 ^ vd + st.pw[pli + 1], st.ph[pli + 1] = w, h + st.nhf[pli + 1], st.nvf[pli + 1] = w // 8, h // 8 + st.foff[pli + 1] = nfr + nfr += (w // 8) * (h // 8) + st.padx[pli + 1], st.pady[pli + 1] = px, py + local stride = w + 2 * px + st.stride[pli + 1] = stride + st.origin[pli + 1] = py * stride + px + st.planeSize[pli + 1] = stride * (h + 2 * py) + end + st.nfrags = nfr + st.coded = table.create(nfr, 0) + st.refi = table.create(nfr, NONE) + st.fmode = table.create(nfr, 0) + st.mvx = table.create(nfr, 0) + st.mvy = table.create(nfr, 0) + st.qii = table.create(nfr, 0) + st.dcv = table.create(nfr, 0) + st.tis = table.create(nfr, 0) + st.last = table.create(nfr, 0) + st.fpos = table.create(nfr, 0) + st.fpl = table.create(nfr, 0) + st.coef = buffer.create(nfr * 128) + for pli = 0, 2 do + local nh, nv = st.nhf[pli + 1], st.nvf[pli + 1] + local stride, origin = st.stride[pli + 1], st.origin[pli + 1] + for fy = 0, nv - 1 do + for fx = 0, nh - 1 do + local fi = st.foff[pli + 1] + fy * nh + fx + 1 + st.fpos[fi] = origin + fy * 8 * stride + fx * 8 + st.fpl[fi] = pli + end + end + end + -- super blocks: 4x4 fragments in Hilbert order (oc_sb_create_plane_mapping) + local SB_MAP = { + { { 0, 0 }, { 0, 1 }, { 3, 2 }, { 3, 3 } }, + { { 0, 3 }, { 0, 2 }, { 3, 1 }, { 3, 0 } }, + { { 1, 0 }, { 1, 3 }, { 2, 0 }, { 2, 3 } }, + { { 1, 1 }, { 1, 2 }, { 2, 1 }, { 2, 2 } }, + } + local sbFr: { number } = {} + local sbQuadValid: { boolean } = {} + local sbPlane: { number } = {} + local sbi = 0 + for pli = 0, 2 do + sbPlane[pli + 1] = sbi + local nh, nv = st.nhf[pli + 1], st.nvf[pli + 1] + for y = 0, nv - 1, 4 do + for x = 0, nh - 1, 4 do + for k = 1, 16 do + sbFr[sbi * 16 + k] = 0 + end + for i = 0, math.min(4, nv - y) - 1 do + for j = 0, math.min(4, nh - x) - 1 do + local m = SB_MAP[i + 1][j + 1] + sbFr[sbi * 16 + m[1] * 4 + m[2] + 1] = st.foff[pli + 1] + (y + i) * nh + x + j + 1 + end + end + for q = 0, 3 do + -- the upper left block of each quadrant: index 0, but 2 in quadrant 3 + local tl = if q == 3 then 2 else 0 + sbQuadValid[sbi * 4 + q + 1] = sbFr[sbi * 16 + q * 4 + tl + 1] ~= 0 + end + sbi += 1 + end + end + end + sbPlane[4] = sbi + st.nsbs = sbi + st.sbFr, st.sbQuadValid, st.sbPlane = sbFr, sbQuadValid, sbPlane + -- macro blocks: 4 per luma super block (oc_mb_create_mapping) + local nsbl = sbPlane[2] + local nmbs = nsbl * 4 + local mbMode = table.create(nmbs, 0) + local mbFr = table.create(nmbs * 12, 0) + local MB_MAP = { { 0, 3 }, { 1, 2 } } + local nhl, nvl = st.nhf[1], st.nvf[1] + local nhc = st.nhf[2] + sbi = 0 + for y = 0, nvl - 1, 4 do + for x = 0, nhl - 1, 4 do + for ymb = 0, 1 do + for xmb = 0, 1 do + local mbi = sbi * 4 + MB_MAP[ymb + 1][xmb + 1] + local mbx, mby = x + xmb * 2, y + ymb * 2 + if mbx >= nhl or mby >= nvl then + mbMode[mbi + 1] = -1 + else + local o = mbi * 12 + for i = 0, 1 do + for j = 0, 1 do + mbFr[o + i * 2 + j + 1] = (mby + i) * nhl + mbx + j + 1 + end + end + for pli = 1, 2 do + local base = st.foff[pli + 1] + 1 + if pf == 0 then + mbFr[o + pli * 4 + 1] = base + (mby // 2) * nhc + mbx // 2 + elseif pf == 2 then + for i = 0, 1 do + mbFr[o + pli * 4 + i * 2 + 1] = base + (mby + i) * nhc + mbx // 2 + end + else + for k = 0, 3 do + mbFr[o + pli * 4 + k + 1] = mbFr[o + k + 1] + st.foff[pli + 1] + end + end + end + end + end + end + sbi += 1 + end + end + st.nmbs, st.mbMode, st.mbFr = nmbs, mbMode, mbFr + st.mapIdx = if pf == 0 then { 0, 1, 2, 3, 4, 8 } elseif pf == 2 then { 0, 1, 2, 3, 4, 6, 8, 10 } else { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 } + st.clist = { table.create(st.nhf[1] * st.nvf[1], 0), table.create(st.nhf[2] * st.nvf[2], 0), table.create(st.nhf[3] * st.nvf[3], 0) } + st.act = { table.create(st.nhf[1] * st.nvf[1], 0), table.create(st.nhf[2] * st.nvf[2], 0), table.create(st.nhf[3] * st.nvf[3], 0) } + st.ncl = { 0, 0, 0 } + -- three reference frames, grey until the first keyframe + st.refs = {} + for r = 1, 3 do + local planes = {} + for pli = 1, 3 do + local b = buffer.create(st.planeSize[pli]) + bfill(b, 0, 128) + planes[pli] = b + end + st.refs[r] = planes + end + st.gold, st.prev, st.shown = 1, 1, 1 + return st :: State +end + +-- the 8-point IDCT of libtheora's idct8 (the spec's), on 8 values; returns the 8 outputs +@native local function idct8(x0: number, x1: number, x2: number, x3: number, x4: number, x5: number, x6: number, x7: number): (number, number, number, number, number, number, number, number) + local t0 = (C4 * (x0 + x4)) // 65536 + local t1 = (C4 * (x0 - x4)) // 65536 + local t2 = (C6 * x2) // 65536 - (C2 * x6) // 65536 + local t3 = (C2 * x2) // 65536 + (C6 * x6) // 65536 + local t4 = (C7 * x1) // 65536 - (C1 * x7) // 65536 + local t5 = (C3 * x5) // 65536 - (C5 * x3) // 65536 + local t6 = (C5 * x5) // 65536 + (C3 * x3) // 65536 + local t7 = (C1 * x1) // 65536 + (C7 * x7) // 65536 + local r = t4 + t5 + t5 = (C4 * (t4 - t5)) // 65536 + t4 = r + r = t7 + t6 + t6 = (C4 * (t7 - t6)) // 65536 + t7 = r + r = t0 + t3 + t3 = t0 - t3 + t0 = r + r = t1 + t2 + t2 = t1 - t2 + t1 = r + r = t6 + t5 + t5 = t6 - t5 + t6 = r + return t0 + t7, t1 + t6, t2 + t5, t3 + t4, t3 - t4, t2 - t5, t1 - t6, t0 - t7 +end + +-- the first IDCT pass: the rows of blk (i16, natural order) into the columns of tmp (i16: like libtheora, the +-- dequantised coefficients and these intermediate values are 16-bit, which also bounds every residual) +@native local function idctRows(blk: buffer, tmp: buffer) + for i = 0, 7 do + local o = i * 16 + local x0, x1, x2, x3 = readi16(blk, o), readi16(blk, o + 2), readi16(blk, o + 4), readi16(blk, o + 6) + local x4, x5, x6, x7 = readi16(blk, o + 8), readi16(blk, o + 10), readi16(blk, o + 12), readi16(blk, o + 14) + local c = i * 2 + if x1 == 0 and x2 == 0 and x3 == 0 and x4 == 0 and x5 == 0 and x6 == 0 and x7 == 0 then + local y = (C4 * x0) // 65536 + writei16(tmp, c, y) + writei16(tmp, c + 16, y) + writei16(tmp, c + 32, y) + writei16(tmp, c + 48, y) + writei16(tmp, c + 64, y) + writei16(tmp, c + 80, y) + writei16(tmp, c + 96, y) + writei16(tmp, c + 112, y) + else + local y0, y1, y2, y3, y4, y5, y6, y7 = idct8(x0, x1, x2, x3, x4, x5, x6, x7) + writei16(tmp, c, y0) + writei16(tmp, c + 16, y1) + writei16(tmp, c + 32, y2) + writei16(tmp, c + 48, y3) + writei16(tmp, c + 64, y4) + writei16(tmp, c + 80, y5) + writei16(tmp, c + 96, y6) + writei16(tmp, c + 112, y7) + end + end +end + +-- the second pass, added to the prediction already in dst: column c of the block is row c of tmp +@native local function idctAdd(tmp: buffer, dst: buffer, pos: number, stride: number) + for c = 0, 7 do + local o = c * 16 + local y0, y1, y2, y3, y4, y5, y6, y7 = idct8(readi16(tmp, o), readi16(tmp, o + 2), readi16(tmp, o + 4), readi16(tmp, o + 6), readi16(tmp, o + 8), readi16(tmp, o + 10), readi16(tmp, o + 12), readi16(tmp, o + 14)) + local p = pos + c + writeu8(dst, p, readu8(CLAMP, readu8(dst, p) + (y0 + 8) // 16 + COFF)) + p += stride + writeu8(dst, p, readu8(CLAMP, readu8(dst, p) + (y1 + 8) // 16 + COFF)) + p += stride + writeu8(dst, p, readu8(CLAMP, readu8(dst, p) + (y2 + 8) // 16 + COFF)) + p += stride + writeu8(dst, p, readu8(CLAMP, readu8(dst, p) + (y3 + 8) // 16 + COFF)) + p += stride + writeu8(dst, p, readu8(CLAMP, readu8(dst, p) + (y4 + 8) // 16 + COFF)) + p += stride + writeu8(dst, p, readu8(CLAMP, readu8(dst, p) + (y5 + 8) // 16 + COFF)) + p += stride + writeu8(dst, p, readu8(CLAMP, readu8(dst, p) + (y6 + 8) // 16 + COFF)) + p += stride + writeu8(dst, p, readu8(CLAMP, readu8(dst, p) + (y7 + 8) // 16 + COFF)) + end +end + +@native local function wrap16(v: number): number + return (v + 32768) % 65536 - 32768 +end + +-- the motion vector offsets of one component: integer part (toward zero) and the second sample's extra step (away +-- from zero) when there is a fraction. q: quarter-pel (subsampled direction) or half-pel +@native local function mvSplit(d: number, q: boolean): (number, number) + local div = if q then 4 else 2 + local a = if d < 0 then -((-d) // div) else d // div + local frac = d - a * div + local b = if frac > 0 then 1 elseif frac < 0 then -1 else 0 + return a, b +end + +-- reconstruct one coded fragment into dst (the SELF reference planes): the prediction (128 for intra blocks, the +-- reference block or the average of two for inter ones) goes to dst first, then the residual is added +@native local function reconFrag(st: State, fi: number, qis: { number }, dstPlanes: { buffer }) + local pli = st.fpl[fi] + local mode = st.fmode[fi] + local qti = if mode == INTRA then 0 else 1 + local dq = st.dequant + local dcq = readu16(dq, (((qis[1] * 3 + pli) * 2 + qti) * 64) * 2) + local dc = st.dcv[fi] + local last = st.last[fi] + local stride = st.stride[pli + 1] + local dst = dstPlanes[pli + 1] + local pos = st.fpos[fi] + local ri = st.refi[fi] + local fv = 0 + if last == 0 then + fv = wrap16((dc * dcq + 15) // 32) + if ri == SELF then + local v = readu8(CLAMP, fv + 128 + COFF) + for y = 0, 7 do + bfill(dst, pos + y * stride, v, 8) + end + return + end + else + local blk = st.blk + bfill(blk, 0, 0, 128) + writei16(blk, 0, wrap16(dc * dcq)) + local coef = st.coef + local co = (fi - 1) * 128 + local ao = (((qis[st.qii[fi] + 1] * 3 + pli) * 2 + qti) * 64) * 2 + for z = 1, last do + local c = readi16(coef, co + z * 2) + if c ~= 0 then + writei16(coef, co + z * 2, 0) + writei16(blk, ZIGZAG[z + 1] * 2, wrap16(c * readu16(dq, ao + z * 2))) + end + end + st.last[fi] = 0 + idctRows(blk, st.tmp) + end + if ri == SELF then + for y = 0, 7 do + bfill(dst, pos + y * stride, 128, 8) + end + else + local ref = st.refs[if ri == GOLD then st.gold else st.prev][pli + 1] + local mx, mx2 = mvSplit(st.mvx[fi], pli > 0 and st.hdec == 1) + local my, my2 = mvSplit(st.mvy[fi], pli > 0 and st.vdec == 1) + local s1 = pos + my * stride + mx + if mx2 ~= 0 or my2 ~= 0 then + -- (a + b) >> 1 per byte, four at a time + local s2 = s1 + my2 * stride + mx2 + for y = 0, 7 do + local d, a, b = pos + y * stride, s1 + y * stride, s2 + y * stride + local u: number = readu32(ref, a) + local v: number = readu32(ref, b) + writeu32(dst, d, band(u, v) + rshift(band(bxor(u, v), 0xFEFEFEFE), 1)) + local u2: number = readu32(ref, a + 4) + local v2: number = readu32(ref, b + 4) + writeu32(dst, d + 4, band(u2, v2) + rshift(band(bxor(u2, v2), 0xFEFEFEFE), 1)) + end + else + for y = 0, 7 do + local d, a = pos + y * stride, s1 + y * stride + writeu32(dst, d, readu32(ref, a)) + writeu32(dst, d + 4, readu32(ref, a + 4)) + end + end + end + if last ~= 0 then + idctAdd(st.tmp, dst, pos, stride) + elseif fv ~= 0 then + for y = 0, 7 do + local d = pos + y * stride + for x = d, d + 7 do + writeu8(dst, x, readu8(CLAMP, readu8(dst, x) + fv + COFF)) + end + end + end +end + +@native local function filterH(b: buffer, p: number, stride: number, bv: { number }) + p -= 2 + for _ = 0, 7 do + local p0, p1, p2, p3 = readu8(b, p), readu8(b, p + 1), readu8(b, p + 2), readu8(b, p + 3) + local f = bv[(p0 - p3 + 3 * (p2 - p1) + 4) // 8 + 129] + writeu8(b, p + 1, readu8(CLAMP, p1 + f + COFF)) + writeu8(b, p + 2, readu8(CLAMP, p2 - f + COFF)) + p += stride + end +end + +@native local function filterV(b: buffer, p: number, stride: number, bv: { number }) + local q0, q1, q2 = p - 2 * stride, p - stride, p + stride + for x = 0, 7 do + local p0, p1, p2, p3 = readu8(b, q0 + x), readu8(b, q1 + x), readu8(b, p + x), readu8(b, q2 + x) + local f = bv[(p0 - p3 + 3 * (p2 - p1) + 4) // 8 + 129] + writeu8(b, q1 + x, readu8(CLAMP, p1 + f + COFF)) + writeu8(b, p + x, readu8(CLAMP, p2 - f + COFF)) + end +end + +@native local function loopFilter(st: State, planes: { buffer }, flimit: number) + local bv = st.bv + for i = -128, 128 do + local a = math.abs(i) + local v = 0 + if a < flimit then + v = i + elseif a < 2 * flimit then + v = if i > 0 then 2 * flimit - a else a - 2 * flimit + end + -- libtheora's table stops at index -127 (127 - i - flimit >= 0) + if i < -127 then + v = 0 + end + bv[i + 129] = v + end + local coded = st.coded + for pli = 0, 2 do + local b = planes[pli + 1] + local nh, nv = st.nhf[pli + 1], st.nvf[pli + 1] + local stride = st.stride[pli + 1] + local base = st.foff[pli + 1] + local fpos = st.fpos + for fy = 0, nv - 1 do + local row = base + fy * nh + for fx = 0, nh - 1 do + local fi = row + fx + 1 + if coded[fi] ~= 0 then + local p = fpos[fi] + if fx > 0 then + filterH(b, p, stride, bv) + end + if fy > 0 then + filterV(b, p, stride, bv) + end + if fx + 1 < nh and coded[fi + 1] == 0 then + filterH(b, p + 8, stride, bv) + end + if fy + 1 < nv and coded[fi + nh] == 0 then + filterV(b, p + 8 * stride, stride, bv) + end + end + end + end + end +end + +-- extend each plane's edge pixels into its padding (for unrestricted motion vectors) +@native local function borders(st: State, planes: { buffer }) + for pli = 1, 3 do + local b = planes[pli] + local stride, px, py = st.stride[pli], st.padx[pli], st.pady[pli] + local w, h = st.pw[pli], st.ph[pli] + for y = 0, h - 1 do + local o = (y + py) * stride + bfill(b, o, readu8(b, o + px), px) + bfill(b, o + px + w, readu8(b, o + px + w - 1), px) + end + local top, bot = py * stride, (py + h - 1) * stride + for k = 1, py do + bcopy(b, top - k * stride, b, top, stride) + bcopy(b, bot + k * stride, b, bot, stride) + end + end +end + +-- DC prediction (raster order per plane): each coded block's DC adds a prediction from its left / upper neighbours +-- coded from the same reference frame (or the last such DC in the plane) +@native local function dcPredict(st: State) + local coded, refi, dcv = st.coded, st.refi, st.dcv + for pli = 0, 2 do + local nh, nv = st.nhf[pli + 1], st.nvf[pli + 1] + local base = st.foff[pli + 1] + local pl0, pl1, pl2 = 0, 0, 0 -- the last DC of each reference frame (GOLD, PREV, SELF) + for fy = 0, nv - 1 do + local row = base + fy * nh + local lref, ulref, uref = -1, -1, -1 + if fy > 0 then + uref = refi[row - nh + 1] + end + for fx = 0, nh - 1 do + local fi = row + fx + 1 + local urref = -1 + if fy > 0 and fx + 1 < nh then + urref = refi[fi - nh + 1] + end + if coded[fi] ~= 0 then + local r = refi[fi] + local pred: number + if fy == 0 then + pred = if r == 0 then pl0 elseif r == 1 then pl1 else pl2 + else + local m = (if lref == r then 1 else 0) + (if ulref == r then 2 else 0) + (if uref == r then 4 else 0) + (if urref == r then 8 else 0) + if m == 0 then + pred = if r == 0 then pl0 elseif r == 1 then pl1 else pl2 + elseif m == 1 or m == 3 then + pred = dcv[fi - 1] + elseif m == 2 then + pred = dcv[fi - nh - 1] + elseif m == 4 or m == 6 or m == 12 then + pred = dcv[fi - nh] + elseif m == 5 then + local s = dcv[fi - 1] + dcv[fi - nh] + pred = if s < 0 then -((-s) // 2) else s // 2 + elseif m == 8 then + pred = dcv[fi - nh + 1] + elseif m == 9 or m == 11 or m == 13 then + local s = 75 * dcv[fi - 1] + 53 * dcv[fi - nh + 1] + pred = if s < 0 then -((-s) // 128) else s // 128 + elseif m == 10 then + local s = dcv[fi - nh - 1] + dcv[fi - nh + 1] + pred = if s < 0 then -((-s) // 2) else s // 2 + elseif m == 14 then + local s = 3 * (dcv[fi - nh - 1] + dcv[fi - nh + 1]) + 10 * dcv[fi - nh] + pred = if s < 0 then -((-s) // 16) else s // 16 + else + local p0, p1, p2 = dcv[fi - 1], dcv[fi - nh - 1], dcv[fi - nh] + local s = 29 * (p0 + p2) - 26 * p1 + pred = if s < 0 then -((-s) // 32) else s // 32 + if math.abs(pred - p2) > 128 then + pred = p2 + elseif math.abs(pred - p0) > 128 then + pred = p0 + elseif math.abs(pred - p1) > 128 then + pred = p1 + end + end + end + local v = wrap16(dcv[fi] + pred) + dcv[fi] = v + if r == 0 then + pl0 = v + elseif r == 1 then + pl1 = v + else + pl2 = v + end + lref = r + else + lref = -1 + end + ulref = uref + uref = urref + end + end + end +end + +@native function D.decode(st: State, data: buffer, off: number, len: number): (string?, string?) + if len <= 0 then + return "dup", nil + end + local bb = buffer.create(len + 24) + bcopy(bb, 0, data, off, len) + local maxp = len * 8 + local pos = 0 + @native local function bits(n: number): number + if pos > maxp then + pos = maxp + end + local w = rshift(lshift(bswap(readu32(bb, rshift(pos, 3))), band(pos, 7)), 32 - n) + pos += n + return w + end + local huff = st.huff + @native local function sbRun(): number + if bits(1) == 0 then + return 1 + elseif bits(1) == 0 then + return 2 + bits(1) + elseif bits(1) == 0 then + return 4 + bits(1) + elseif bits(1) == 0 then + return 6 + bits(2) + elseif bits(1) == 0 then + return 10 + bits(3) + elseif bits(1) == 0 then + return 18 + bits(4) + end + return 34 + bits(12) + end + @native local function blockRun(): number + if bits(1) == 0 then + return 1 + bits(1) + elseif bits(1) == 0 then + return 3 + bits(1) + elseif bits(1) == 0 then + return 5 + bits(1) + elseif bits(1) == 0 then + return 7 + bits(2) + elseif bits(1) == 0 then + return 11 + bits(2) + end + return 15 + bits(4) + end + + -- frame header + if bits(1) ~= 0 then + return nil, "not a data packet" + end + local intra = bits(1) == 0 + local qis = { bits(6) } + if bits(1) == 1 then + table.insert(qis, bits(6)) + if bits(1) == 1 then + table.insert(qis, bits(6)) + end + end + if intra then + if bits(3) ~= 0 then + return nil, "unsupported: reserved keyframe bits set" + end + end + local coded, refi, fmode, dcv, tis, qii = st.coded, st.refi, st.fmode, st.dcv, st.tis, st.qii + local mvx, mvy = st.mvx, st.mvy + local sbFr, sbQuadValid, sbPlane = st.sbFr, st.sbQuadValid, st.sbPlane + local clist, ncl = st.clist, st.ncl + local mbMode = st.mbMode + local nsbs = st.nsbs + local total = 0 + if intra then + for pli = 0, 2 do + local list, n = clist[pli + 1], 0 + for sbi = sbPlane[pli + 1], sbPlane[pli + 2] - 1 do + for q = 0, 3 do + if sbQuadValid[sbi * 4 + q + 1] then + for bi = 0, 3 do + local fi = sbFr[sbi * 16 + q * 4 + bi + 1] + if fi ~= 0 then + coded[fi] = 1 + refi[fi] = SELF + fmode[fi] = INTRA + n += 1 + list[n] = fi + end + end + end + end + end + ncl[pli + 1] = n + total += n + end + else + -- partially coded super blocks, then fully coded ones among the rest + local partial, full = table.create(nsbs, false), table.create(nsbs, false) + local npartial = 0 + local flag = bits(1) + local sbi = 0 + while sbi < nsbs do + local run = sbRun() + local fullRun = run >= 4129 + repeat + partial[sbi + 1] = flag == 1 + npartial += flag + sbi += 1 + run -= 1 + until run <= 0 or sbi >= nsbs + if fullRun and sbi < nsbs then + flag = bits(1) + else + flag = 1 - flag + end + end + if npartial < nsbs then + sbi = 0 + while partial[sbi + 1] do + sbi += 1 + end + flag = bits(1) + repeat + local run = sbRun() + local fullRun = run >= 4129 + while sbi < nsbs do + if not partial[sbi + 1] then + if run <= 0 then + break + end + run -= 1 + full[sbi + 1] = flag == 1 + end + sbi += 1 + end + if fullRun and sbi < nsbs then + flag = bits(1) + else + flag = 1 - flag + end + until sbi >= nsbs + end + -- block flags + local bflag = 0 + if npartial > 0 then + bflag = 1 - bits(1) + end + local run = 0 + for pli = 0, 2 do + local list, n = clist[pli + 1], 0 + for s = sbPlane[pli + 1], sbPlane[pli + 2] - 1 do + local isFull, isPartial = full[s + 1], partial[s + 1] + for q = 0, 3 do + if sbQuadValid[s * 4 + q + 1] then + local quadCoded = 0 + for bi = 0, 3 do + local fi = sbFr[s * 16 + q * 4 + bi + 1] + if fi ~= 0 then + local c = 0 + if isFull then + c = 1 + elseif isPartial then + if run <= 0 then + run = blockRun() + bflag = 1 - bflag + end + run -= 1 + c = bflag + end + coded[fi] = c + refi[fi] = NONE + if c == 1 then + n += 1 + list[n] = fi + quadCoded = 1 + end + end + end + if pli == 0 then + mbMode[s * 4 + q + 1] = quadCoded + end + end + end + end + ncl[pli + 1] = n + total += n + end + if total == 0 then + return "dup", nil + end + -- macro block modes + local scheme = bits(3) + local alphabet: { number } + if scheme == 0 then + alphabet = table.create(8, NOMV) + for mi = 1, 8 do + alphabet[bits(3) + 1] = ALPHABETS[7][mi] + end + else + alphabet = ALPHABETS[scheme] + end + for mbi = 1, st.nmbs do + if mbMode[mbi] > 0 then + local idx: number + if scheme == 7 then + idx = bits(3) + else + local e = MODE_VLC[bits(7) + 1] + pos -= 7 - e % 8 + idx = e // 8 + end + mbMode[mbi] = alphabet[idx + 1] + end + end + -- motion vectors + local clc = bits(1) == 1 + @native local function mv(): number + if clc then + local v = bits(6) + return if v % 2 == 1 then -(v // 2) else v // 2 + end + local e = MV_VLC[bits(8) + 1] + pos -= 8 - e % 16 + return e // 16 - 32 + end + local mbFr, mapIdx = st.mbFr, st.mapIdx + local nmap = #mapIdx + local lastX, lastY, priorX, priorY = 0, 0, 0, 0 + local lx, ly = { 0, 0, 0, 0 }, { 0, 0, 0, 0 } + local cx, cy = { 0, 0, 0, 0 }, { 0, 0, 0, 0 } + local pf = st.pf + for mbi = 0, st.nmbs - 1 do + local mode = mbMode[mbi + 1] + if mode >= 0 then + local o = mbi * 12 + if mode == FOURMV then + priorX, priorY = lastX, lastY + for bi = 1, 4 do + local fi = mbFr[o + bi] + if coded[fi] ~= 0 then + refi[fi] = PREV + fmode[fi] = FOURMV + local x = mv() + local y = mv() + lx[bi], ly[bi] = x, y + lastX, lastY = x, y + mvx[fi], mvy[fi] = x, y + else + lx[bi], ly[bi] = 0, 0 + end + end + if pf == 0 then + local sx, sy = lx[1] + lx[2] + lx[3] + lx[4], ly[1] + ly[2] + ly[3] + ly[4] + cx[1] = (sx + 2 - (if sx < 0 then 1 else 0)) // 4 + cy[1] = (sy + 2 - (if sy < 0 then 1 else 0)) // 4 + elseif pf == 2 then + local sx, sy = lx[1] + lx[2], ly[1] + ly[2] + cx[1] = (sx + 1 - (if sx < 0 then 1 else 0)) // 2 + cy[1] = (sy + 1 - (if sy < 0 then 1 else 0)) // 2 + sx, sy = lx[3] + lx[4], ly[3] + ly[4] + cx[3] = (sx + 1 - (if sx < 0 then 1 else 0)) // 2 + cy[3] = (sy + 1 - (if sy < 0 then 1 else 0)) // 2 + else + for k = 1, 4 do + cx[k], cy[k] = lx[k], ly[k] + end + end + for m = 5, nmap do + local mi = mapIdx[m] + local fi = mbFr[o + mi + 1] + if coded[fi] ~= 0 then + local bi = mi % 4 + 1 + refi[fi] = PREV + fmode[fi] = FOURMV + mvx[fi], mvy[fi] = cx[bi], cy[bi] + end + end + else + local x, y = 0, 0 + if mode == INTER_MV then + priorX, priorY = lastX, lastY + x = mv() + y = mv() + lastX, lastY = x, y + elseif mode == MV_LAST then + x, y = lastX, lastY + elseif mode == MV_LAST2 then + x, y = priorX, priorY + priorX, priorY = lastX, lastY + lastX, lastY = x, y + elseif mode == GOLD_MV then + x = mv() + y = mv() + end + local r = FRAME_FOR_MODE[mode] + for m = 1, nmap do + local fi = mbFr[o + mapIdx[m] + 1] + if coded[fi] ~= 0 then + refi[fi] = r + fmode[fi] = mode + mvx[fi], mvy[fi] = x, y + end + end + end + end + end + end + + -- block qi indices (over every coded fragment, planes in order) + local nqis = #qis + for pli = 1, 3 do + local list = clist[pli] + for k = 1, ncl[pli] do + local fi = list[k] + qii[fi] = 0 + dcv[fi] = 0 + tis[fi] = 0 + end + end + if nqis > 1 then + local all = table.create(total, 0) + local n = 0 + for pli = 1, 3 do + local list = clist[pli] + for k = 1, ncl[pli] do + n += 1 + all[n] = list[k] + end + end + local flag = bits(1) + local nqi1 = 0 + local k = 1 + while k <= total do + local run = sbRun() + local fullRun = run >= 4129 + repeat + qii[all[k]] = flag + nqi1 += flag + k += 1 + run -= 1 + until run <= 0 or k > total + if fullRun and k <= total then + flag = bits(1) + else + flag = 1 - flag + end + end + if nqis == 3 and nqi1 > 0 then + k = 1 + while qii[all[k]] == 0 do + k += 1 + end + flag = bits(1) + repeat + local run = sbRun() + local fullRun = run >= 4129 + while k <= total do + local fi = all[k] + if qii[fi] ~= 0 then + if run <= 0 then + break + end + run -= 1 + qii[fi] += flag + end + k += 1 + end + if fullRun and k <= total then + flag = bits(1) + else + flag = 1 - flag + end + until k > total + end + end + + -- DCT tokens: coefficient by coefficient, plane by plane, block by block in coded order; an EOB run ends the + -- next blocks that still wait for a token at their position + local coef, last = st.coef, st.last + local act = st.act + local nact = { 0, 0, 0 } + for pli = 1, 3 do + local src, dstl = clist[pli], act[pli] + for k = 1, ncl[pli] do + dstl[k] = src[k] + end + nact[pli] = ncl[pli] + end + local roots = st.roots + local hy: number = bits(4) + local hc: number = bits(4) + local eobs = 0 + for zzi = 0, 63 do + if zzi == 1 then + hy = bits(4) + hc = bits(4) + end + local grp: number = if zzi == 0 then 0 elseif zzi < 6 then 16 elseif zzi < 15 then 32 elseif zzi < 28 then 48 else 64 + for pli = 1, 3 do + local sel: number = if pli == 1 then hy else hc + local root = roots[sel + grp + 1] + local list = act[pli] + local n = nact[pli] + local w = 0 + for k = 1, n do + local fi = list[k] + local t = tis[fi] + if t == zzi then + if eobs > 0 then + eobs -= 1 + t = 64 + else + -- the token (inlined: the hottest loop), then its extra bits + if pos > maxp then + pos = maxp + end + local o, tok = root, 0 + while true do + local nb = huff[o] + local e = huff[o + 1 + rshift(lshift(bswap(readu32(bb, rshift(pos, 3))), band(pos, 7)), 32 - nb)] + if e >= 0 then + pos += rshift(e, 6) + tok = band(e, 63) + break + end + pos += nb + o = -e + end + local ex = TOKEN_EXTRA[tok + 1] + local eb = 0 + if ex > 0 then + eb = rshift(lshift(bswap(readu32(bb, rshift(pos, 3))), band(pos, 7)), 32 - ex) + pos += ex + end + if tok < 7 then + local run: number + if tok < 3 then + run = tok + 1 + elseif tok == 3 then + run = 4 + eb + elseif tok == 4 then + run = 8 + eb + elseif tok == 5 then + run = 16 + eb + else + run = if eb == 0 then 2 ^ 31 else eb + end + eobs = run - 1 + t = 64 + else + -- zero runs and coefficients: run * 4096 + value + 2048 (value 0: a zero run) + local e = TOKEN_VALUE[tok * 1024 + eb + 1] + local p = zzi + rshift(e, 12) + local v = band(e, 4095) - 2048 + if v ~= 0 then + if p == 0 then + dcv[fi] = v + elseif p < 64 then + writei16(coef, (fi - 1) * 128 + p * 2, v) + last[fi] = p + end + end + t = p + 1 + end + end + tis[fi] = t + end + if t < 64 then + w += 1 + list[w] = fi + end + end + nact[pli] = w + end + end + + dcPredict(st) + + local self = 1 + while self == st.gold or self == st.prev do + self += 1 + end + local dst = st.refs[self] + if not intra then + local src = st.refs[st.prev] + for pli = 1, 3 do + bcopy(dst[pli], 0, src[pli], 0, st.planeSize[pli]) + end + end + for pli = 1, 3 do + local list = clist[pli] + for k = 1, ncl[pli] do + reconFrag(st, list[k], qis, dst) + end + end + local flimit = st.lflim[qis[1] + 1] + if flimit ~= 0 then + loopFilter(st, dst, flimit) + end + borders(st, dst) + if intra then + st.gold, st.prev = self, self + st.keyframes += 1 + else + st.prev = self + end + st.shown = self + return if intra then "key" else "inter", nil +end + +@native function D.plane(st: State, pli: number, x0: number, y0: number, w: number, h: number): buffer + local src = st.refs[st.shown][pli + 1] + local stride, origin, ph = st.stride[pli + 1], st.origin[pli + 1], st.ph[pli + 1] + local out = buffer.create(w * h) + for y = 0, h - 1 do + local row = ph - 1 - (y0 + y) -- Theora rows count from the bottom + bcopy(out, y * w, src, origin + row * stride + x0, w) + end + return out +end + +-- 4:2:2 (rows averaged in pairs) or 4:4:4 (2x2 averages) chroma down to 4:2:0 +@native function D.downsample(src: buffer, cw: number, ch: number, hdec: number, dst: buffer, off: number, ow: number, oh: number) + for r = 0, oh - 1 do + local r0 = math.min(2 * r, ch - 1) + local r1 = math.min(2 * r + 1, ch - 1) + local a, b = r0 * cw, r1 * cw + local o = off + r * ow + if hdec == 1 then + for c = 0, math.min(ow, cw) - 1 do + writeu8(dst, o + c, (readu8(src, a + c) + readu8(src, b + c) + 1) // 2) + end + else + for c = 0, ow - 1 do + local c0 = math.min(2 * c, cw - 1) + local c1 = math.min(2 * c + 1, cw - 1) + writeu8(dst, o + c, (readu8(src, a + c0) + readu8(src, a + c1) + readu8(src, b + c0) + readu8(src, b + c1) + 2) // 4) + end + end + end +end + +return D +end +__FILES["codecs/video/Theora/Header"] = function() + +-- codecs/video/Theora/Header: the three Theora headers (Theora I specification, section 6) and the dequantisation and +-- Huffman lookup tables derived from them. A Luau port of libtheora 1.2.0 (Xiph.Org, BSD 3-clause, +-- licenses/libtheora-BSD.txt): decinfo.c, dequant.c, quant.c (oc_dequant_tables_init), huffdec.c. +local Bits = __include("core/Bits") + +local H = {} + +type Info = { + versionMajor: number, + versionMinor: number, + versionSub: number, + frameWidth: number, -- coded frame size (multiples of 16) + frameHeight: number, + picWidth: number, -- the picture region (the displayed part) + picHeight: number, + picX: number, + picY: number, -- from the bottom, as stored + fpsNum: number, + fpsDen: number, + aspectNum: number, + aspectDen: number, + colorspace: number, -- 0 unspecified, 1 Rec. 470M, 2 Rec. 470BG + bitrate: number, + quality: number, + granuleShift: number, + pixelFormat: number, -- 0 4:2:0, 2 4:2:2, 3 4:4:4 (1 is reserved) +} + +type Setup = { + lflim: { number }, -- [qi + 1]: loop filter limit + dequant: buffer, -- u16 [((qi * 3 + pli) * 2 + qti) * 64 + zzi], zig-zag order, scaled by 4 like libtheora + huff: { number }, -- the 80 collapsed trees, one flat array (see buildTable) + roots: { number }, -- [table + 1]: the root node offset in huff +} + +-- the zig-zag scan: natural index of the coefficient at scan position zzi +H.ZIGZAG = { + 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, + 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63, +} + +local function ilog(v: number): number + local n = 0 + while v > 0 do + n += 1 + v = v // 2 + end + return n +end + +-- identification header: 0x80 "theora" +function H.info(b: buffer, off: number, len: number): (Info?, string?) + if len < 42 or buffer.readu8(b, off) ~= 0x80 or buffer.readstring(b, off + 1, 6) ~= "theora" then + return nil, "not a Theora identification header" + end + local br = Bits.msbReader(b, off + 7, len - 7) + local info: Info = { + versionMajor = br:read(8), + versionMinor = br:read(8), + versionSub = br:read(8), + frameWidth = br:read(16) * 16, + frameHeight = br:read(16) * 16, + picWidth = br:read(24), + picHeight = br:read(24), + picX = br:read(8), + picY = br:read(8), + fpsNum = br:read(32), + fpsDen = br:read(32), + aspectNum = br:read(24), + aspectDen = br:read(24), + colorspace = br:read(8), + bitrate = br:read(24), + quality = br:read(6), + granuleShift = br:read(5), + pixelFormat = br:read(2), + } + local reserved = br:read(3) + if br.err then + return nil, "truncated identification header" + end + if info.versionMajor > 3 or (info.versionMajor == 3 and info.versionMinor > 2) then + return nil, "unsupported: Theora bitstream version " .. info.versionMajor .. "." .. info.versionMinor + end + if info.frameWidth == 0 or info.frameHeight == 0 or info.picWidth + info.picX > info.frameWidth or info.picHeight + info.picY > info.frameHeight then + return nil, "bad frame / picture size" + end + if info.fpsNum == 0 or info.fpsDen == 0 then + return nil, "bad frame rate" + end + if info.pixelFormat == 1 or reserved ~= 0 then + return nil, "reserved pixel format" + end + return info, nil +end + +-- comment header: 0x81 "theora" +function H.comment(b: buffer, off: number, len: number): (string?, { string }?, string?) + if len < 7 or buffer.readu8(b, off) ~= 0x81 or buffer.readstring(b, off + 1, 6) ~= "theora" then + return nil, nil, "not a Theora comment header" + end + local p, e = off + 7, off + len + local function str(): string? + if p + 4 > e then + return nil + end + local n = buffer.readu32(b, p) + p += 4 + if n > e - p then + return nil + end + local s = buffer.readstring(b, p, n) + p += n + return s + end + local vendor = str() + if not vendor or p + 4 > e then + return nil, nil, "truncated comment header" + end + local count = buffer.readu32(b, p) + p += 4 + if count * 4 > e - p then + return nil, nil, "bad comment count" + end + local list: { string } = {} + for _ = 1, count do + local s = str() + if not s then + return nil, nil, "truncated comment header" + end + table.insert(list, s) + end + return vendor, list, nil +end + +-- A tree is read depth first (0: an internal node, 1 then 5 bits: a leaf with that token). It becomes lookup tables in +-- one flat array: a node is huff[o] = n (bits to peek) followed by 2^n entries, entry = length * 64 + token (a leaf +-- reached after `length` <= n of the peeked bits) or -offset (another node, after all n bits). +local MAXBITS = 8 + +local function readTree(br: any): ({ number }?, { number }?, { number }?) + -- the trie: kid0 / kid1 child ids (0 = none), tok = token or -1 (node 1 is the root) + local kid0, kid1, tok = { 0 }, { 0 }, { -1 } + -- as libtheora's oc_huff_tree_unpack: code is the current codeword left-aligned in 32 bits, len its length + local code, len, nleaves = 0, 0, 0 + while true do + local bit = br:read(1) + if br.err then + return nil, nil, nil + end + if bit == 0 then + len += 1 + if len > 32 then + return nil, nil, nil + end + else + nleaves += 1 + if nleaves > 32 then + return nil, nil, nil + end + local t = br:read(5) + local n = 1 + for d = 1, len do + local k = (code // 2 ^ (32 - d)) % 2 + local kids = if k == 0 then kid0 else kid1 + local nx = kids[n] + if nx == 0 then + nx = #tok + 1 + kid0[nx], kid1[nx], tok[nx] = 0, 0, -1 + kids[n] = nx + end + n = nx + end + tok[n] = t + if len <= 0 then + break + end + -- the next codeword: clear the trailing 1 bits, then set the last 0 bit + local cb = 2 ^ (32 - len) + while len > 0 and (code // cb) % 2 == 1 do + code -= cb + cb *= 2 + len -= 1 + end + if len <= 0 then + break + end + code += cb + end + end + return kid0, kid1, tok +end + +local function buildTable(out: { number }, kid0: { number }, kid1: { number }, tok: { number }): number + local heights: { [number]: number } = {} + local function height(n: number): number + local h = heights[n] + if h then + return h + end + h = 0 + if tok[n] < 0 then + local a = if kid0[n] ~= 0 then height(kid0[n]) else 0 + local c = if kid1[n] ~= 0 then height(kid1[n]) else 0 + h = 1 + math.max(a, c) + end + heights[n] = h + return h + end + local function node(n: number): number + local nb = math.clamp(height(n), 1, MAXBITS) + local off = #out + 1 + out[off] = nb + local size = 2 ^ nb + for i = 1, size do + out[off + i] = 0 + end + for i = 0, size - 1 do + local cur, d = n, 0 + while d < nb and tok[cur] < 0 do + local bit = bit32.extract(i, nb - 1 - d, 1) + local nx = if bit == 0 then kid0[cur] else kid1[cur] + d += 1 + cur = nx + if nx == 0 then + break + end + end + if cur == 0 then + out[off + 1 + i] = d * 64 -- no code here (a corrupt tree): token 0 + elseif tok[cur] >= 0 then + out[off + 1 + i] = d * 64 + tok[cur] + else + out[off + 1 + i] = -node(cur) + end + end + return off + end + return node(1) +end + +local DC_MIN = { 16, 32 } +local AC_MIN = { 8, 16 } + +-- setup header: 0x82 "theora" +function H.setup(b: buffer, off: number, len: number): (Setup?, string?) + if len < 7 or buffer.readu8(b, off) ~= 0x82 or buffer.readstring(b, off + 1, 6) ~= "theora" then + return nil, "not a Theora setup header" + end + local br = Bits.msbReader(b, off + 7, len - 7) + -- loop filter limits, AC / DC scales + local lflim, acScale, dcScale = table.create(64, 0), table.create(64, 0), table.create(64, 0) + local nb = br:read(3) + for qi = 1, 64 do + lflim[qi] = br:read(nb) + end + nb = br:read(4) + 1 + for qi = 1, 64 do + acScale[qi] = br:read(nb) + end + nb = br:read(4) + 1 + for qi = 1, 64 do + dcScale[qi] = br:read(nb) + end + local nbms = br:read(9) + 1 + local bms: { { number } } = {} + for m = 1, nbms do + local mat = table.create(64, 0) + for ci = 1, 64 do + mat[ci] = br:read(8) + end + bms[m] = mat + end + if br.err then + return nil, "truncated setup header" + end + -- the quant ranges of the 6 (qti, pli) pairs: sizes and base matrix indices (0-based) + local ranges: { { sizes: { number }, idx: { number } } } = {} + local mb = ilog(nbms - 1) + for i = 0, 5 do + local qti, pli = i // 3, i % 3 + local copy = false + if i > 0 and br:read(1) == 0 then + copy = true + local from = i - 1 + if qti > 0 and br:read(1) == 1 then + from = pli -- the same plane of the intra set + end + ranges[i + 1] = ranges[from + 1] + end + if not copy then + local sizes, idx = {}, { br:read(mb) } + local qi = 0 + while qi < 63 do + local s = br:read(ilog(62 - qi)) + 1 + table.insert(sizes, s) + qi += s + table.insert(idx, br:read(mb)) + end + if qi > 63 then + return nil, "bad quant ranges" + end + for _, m in idx do + if m >= nbms then + return nil, "bad base matrix index" + end + end + ranges[i + 1] = { sizes = sizes, idx = idx } + end + end + if br.err then + return nil, "truncated setup header" + end + -- the dequantisation tables (oc_dequant_tables_init) + local dequant = buffer.create(64 * 6 * 64 * 2) + local base = table.create(64, 0) + for qti = 0, 1 do + for pli = 0, 2 do + local r = ranges[qti * 3 + pli + 1] + local qi = 0 + for qri = 0, #r.sizes do + local m0 = bms[r.idx[qri + 1] + 1] + table.move(m0, 1, 64, 1, base) + local qiStart = qi + local qiEnd = if qri == #r.sizes then qi + 1 else qi + r.sizes[qri + 1] + while true do + local o = ((qi * 3 + pli) * 2 + qti) * 64 + local q = (dcScale[qi + 1] * base[1] // 100) * 4 + buffer.writeu16(dequant, o * 2, math.clamp(q, DC_MIN[qti + 1], 4096)) + for zzi = 1, 63 do + q = (acScale[qi + 1] * base[H.ZIGZAG[zzi + 1] + 1] // 100) * 4 + buffer.writeu16(dequant, (o + zzi) * 2, math.clamp(q, AC_MIN[qti + 1], 4096)) + end + qi += 1 + if qi >= qiEnd then + break + end + -- interpolate the next base matrix + local m1 = bms[r.idx[qri + 2] + 1] + local sz = r.sizes[qri + 1] + for ci = 1, 64 do + base[ci] = (2 * ((qiEnd - qi) * m0[ci] + (qi - qiStart) * m1[ci]) + sz) // (2 * sz) + end + end + end + end + end + -- the 80 Huffman trees + local huff: { number } = {} + local roots: { number } = {} + for t = 1, 80 do + local k0, k1, tk = readTree(br) + if not k0 or not k1 or not tk then + return nil, "bad Huffman tree " .. (t - 1) + end + roots[t] = buildTable(huff, k0, k1, tk) + end + return { lflim = lflim, dequant = dequant, huff = huff, roots = roots }, nil +end + +return H +end +end + + + + + + Legacy + --!optimize 2 +--!nocheck +-- rosetta chunk Legacy (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 8 modules (7 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["codecs/video/Legacy"] = function() + +-- codecs/video/Legacy: FLI / FLC, Cinepak, Microsoft Video 1, QuickTime RLE / SMC and Smacker video decoders. +-- From the format descriptions (see each submodule), bit-exact with ffmpeg. Palette: track.palette, replaced by a +-- packet's palette (256 u32 entries R, G, B, A); depth: track.bitsPerPixel (AVI biBitCount, QuickTime depth). +local Err = __include("core/Err") +local Types = __include("Types") +local Picture = __include("codecs/video/Legacy/Picture") +local Flic = __include("codecs/video/Legacy/Flic") +local Cinepak = __include("codecs/video/Legacy/Cinepak") +local Msvideo1 = __include("codecs/video/Legacy/Msvideo1") +local QtRle = __include("codecs/video/Legacy/QtRle") +local Smc = __include("codecs/video/Legacy/Smc") +local Smacker = __include("codecs/video/Legacy/Smacker") + +local Legacy = {} + +Legacy.Picture = Picture +Legacy.Flic = Flic +Legacy.Cinepak = Cinepak +Legacy.Msvideo1 = Msvideo1 +Legacy.QtRle = QtRle +Legacy.Smc = Smc +Legacy.Smacker = Smacker +Legacy.CODECS = { "flic", "cinepak", "msvideo1", "qtrle", "smc", "smackvid" } + +type Options = { + maxPixels: number?, + [string]: any, +} + +type Codec = { + make: (track: Types.Track) -> (any, string?), + step: (st: any, data: buffer, packet: Types.Packet) -> (Types.Image?, Err.Err?), +} + +local function fail(msg: string?): Err.Err + return Err.from(msg or "corrupt frame") +end + +local function packetPalette(pic: Picture.Picture, packet: Types.Packet): boolean + local pal = (packet :: any).palette + if type(pal) == "buffer" then + Picture.setPalette(pic, pal) + return true + end + return false +end + +local CODECS: { [string]: Codec } = { + qtrle = { + make = function(t) + local depth = t.bitsPerPixel or 24 + local bits = if depth > 32 then depth - 32 else depth + if not (bits == 1 or bits == 2 or bits == 4 or bits == 8 or bits == 16 or bits == 24 or bits == 32) then + return nil, "unsupported: depth " .. depth + end + return { pic = Picture.new(t.width :: number, t.height :: number, QtRle.palettised(depth), QtRle.pad(depth), 1, t.palette), depth = depth }, nil + end, + step = function(st, data, packet) + packetPalette(st.pic, packet) + local ok, msg = QtRle.decode(st.pic, data, st.depth) + if not ok then + return nil, fail(msg) + end + return Picture.image(st.pic), nil + end, + }, + smc = { + make = function(t) + return { pic = Picture.new(t.width :: number, t.height :: number, true, 4, 4, t.palette), tables = Smc.tables() }, nil + end, + step = function(st, data, packet) + packetPalette(st.pic, packet) + local ok, msg = Smc.decode(st.pic, data, st.tables) + if not ok then + return nil, fail(msg) + end + return Picture.image(st.pic), nil + end, + }, + msvideo1 = { + make = function(t) + if (t.width :: number) < 4 or (t.height :: number) < 4 then + return nil, "smaller than one block" + end + local bits = if t.bitsPerPixel == 8 then 8 else 16 + return { pic = Picture.new(t.width :: number, t.height :: number, bits == 8, 4, 4, t.palette), bits = bits }, nil + end, + step = function(st, data, packet) + if st.bits == 8 then + packetPalette(st.pic, packet) + end + local ok, msg = Msvideo1.decode(st.pic, data, st.bits) + if not ok then + return nil, fail(msg) + end + return Picture.image(st.pic), nil + end, + }, + cinepak = { + make = function(t) + local pal = t.bitsPerPixel == 8 + return { pic = Picture.new(t.width :: number, t.height :: number, pal, 4, 4, t.palette), cp = Cinepak.state() }, nil + end, + step = function(st, data, packet) + local newPal = st.pic.idx ~= nil and packetPalette(st.pic, packet) + local ok, msg = Cinepak.decode(st.pic, data, st.cp, newPal) + if not ok then + return nil, if msg then fail(msg) else nil + end + return Picture.image(st.pic), nil + end, + }, + smackvid = { + make = function(t) + local cfg = t.config + if type(cfg) ~= "buffer" then + return nil, "no Smacker trees" + end + local trees, msg = Smacker.trees(cfg) + if not trees then + return nil, msg + end + return { pic = Picture.new(t.width :: number, t.height :: number, true, 4, 4, t.palette), trees = trees, v4 = t.codecTag == "SMK4" }, nil + end, + step = function(st, data, packet) + packetPalette(st.pic, packet) + if buffer.len(data) == 0 then + return nil, fail("empty frame") + end + local ok, msg = Smacker.decode(st.pic, data, st.trees, st.v4) + if not ok then + return nil, fail(msg) + end + return Picture.image(st.pic), nil + end, + }, + flic = { + make = function(t) + return Flic.state(t.width :: number, t.height :: number, t.bitsPerPixel or 8) + end, + step = function(st, data, _packet) + local ok, msg = Flic.decode(st, data) + if not ok then + return nil, fail(msg) + end + return Flic.image(st), nil + end, + }, +} + +function Legacy.newDecoder(id: string, track: Types.Track, opts: Options?): (Types.VideoCodecDecoder?, Err.Err?) + local codec = CODECS[id] + if not codec then + return nil, Err.new(Err.UNSUPPORTED, "no legacy codec " .. tostring(id)) + end + local w, h = track.width or 0, track.height or 0 + if type(w) ~= "number" or type(h) ~= "number" or w <= 0 or h <= 0 or w ~= w // 1 or h ~= h // 1 then + return nil, Err.new(Err.CORRUPT, "video track without a valid size") + end + local max = (opts and opts.maxPixels) or 2 ^ 26 + if w * h > max or w > 32768 or h > 32768 then + return nil, Err.new(Err.LIMIT, "picture of " .. w .. " x " .. h .. " over the limit") + end + local st, msg = codec.make(track) + if not st then + return nil, fail(msg) + end + local queue: { any } = {} + local self = {} + function self.decode(_: any, packet: Types.Packet): Err.Err? + local ok, img, err = pcall(codec.step, st, packet.data, packet) + if not ok then + return Err.new(Err.CORRUPT, "decoder failed: " .. tostring(img)) + end + if img then + table.insert(queue, { img, packet.pts, packet.keyframe }) + end + return err + end + function self.receive(_: any): (Types.Image?, number?, boolean?) + local q = table.remove(queue, 1) + if q then + return q[1], q[2], q[3] + end + return nil, nil, nil + end + function self.flush(_: any) end + function self.reset(_: any) + table.clear(queue) + st = codec.make(track) or st + end + return self :: any, nil +end + +return Legacy +end +__FILES["codecs/video/Legacy/Cinepak"] = @native function() + + + +-- codecs/video/Legacy/Cinepak: Cinepak ('cvid') frames, 24-bit colour and 8-bit palettised. +-- From MultimediaWiki "Cinepak", bit-exact with ffmpeg: a frame header (flags, size, width, height, strip count), strips +-- with V1 / V4 codebooks (inherited from the strip above unless the flags say otherwise) and vector chunks. +-- Colour entries: r = y + 2v, g = y - u/2 - v, b = y + 2u, clamped. +local Picture = __include("codecs/video/Legacy/Picture") + +local readu8, readu32, writeu32, writeu8 = buffer.readu8, buffer.readu32, buffer.writeu32, buffer.writeu8 +local band = bit32.band + +local Cinepak = {} + +local MAX_STRIPS = 32 +-- a codebook: 256 entries of 4 u32 rgba pixels (16 bytes); palettised streams use the low byte (the index) +local ENTRY = 16 +local BOOK = 256 * ENTRY + +type State = { + books: buffer, -- MAX_STRIPS * 2 codebooks (V4 then V1 per strip) + filmSkip: number, -- Sega FILM extra header bytes (-1 = not known yet) +} + +@native function Cinepak.state(): State + return { books = buffer.create(MAX_STRIPS * 2 * BOOK), filmSkip = -1 } +end + +@native local function be16(d: buffer, o: number): number + return readu8(d, o) * 256 + readu8(d, o + 1) +end +@native local function be24(d: buffer, o: number): number + return readu8(d, o) * 65536 + readu8(d, o + 1) * 256 + readu8(d, o + 2) +end +@native local function be32(d: buffer, o: number): number + return readu8(d, o) * 16777216 + readu8(d, o + 1) * 65536 + readu8(d, o + 2) * 256 + readu8(d, o + 3) +end + +@native local function clip(v: number): number + return if v < 0 then 0 elseif v > 255 then 255 else v +end + +-- a codebook chunk (ids 0x20..0x27): entries of 4 or 6 bytes, all of them or those whose flag bit is set +@native local function codebook(books: buffer, book: number, id: number, d: buffer, p: number, stop: number) + local six = band(id, 4) == 0 + local partial = band(id, 1) ~= 0 + local size = if six then 6 else 4 + local flag, mask = 0, 0 + for i = 0, 255 do + if partial then + mask //= 2 + if mask == 0 then + if p + 4 > stop then + return + end + flag = be32(d, p) + p += 4 + mask = 0x80000000 + end + end + if not partial or band(flag, mask) ~= 0 then + if p + size > stop then + return + end + local e = book + i * ENTRY + local y0, y1, y2, y3 = readu8(d, p), readu8(d, p + 1), readu8(d, p + 2), readu8(d, p + 3) + if six then + local u, v = readu8(d, p + 4), readu8(d, p + 5) + if u >= 128 then + u -= 256 + end + if v >= 128 then + v -= 256 + end + local uh = if u < 0 then -((-u) // 2) else u // 2 -- C division (towards zero) + local dr, dg, db = 2 * v, -uh - v, 2 * u + writeu32(books, e, clip(y0 + dr) + clip(y0 + dg) * 256 + clip(y0 + db) * 65536 + 0xFF000000) + writeu32(books, e + 4, clip(y1 + dr) + clip(y1 + dg) * 256 + clip(y1 + db) * 65536 + 0xFF000000) + writeu32(books, e + 8, clip(y2 + dr) + clip(y2 + dg) * 256 + clip(y2 + db) * 65536 + 0xFF000000) + writeu32(books, e + 12, clip(y3 + dr) + clip(y3 + dg) * 256 + clip(y3 + db) * 65536 + 0xFF000000) + else + writeu32(books, e, y0 * 0x10101 + 0xFF000000) + writeu32(books, e + 4, y1 * 0x10101 + 0xFF000000) + writeu32(books, e + 8, y2 * 0x10101 + 0xFF000000) + writeu32(books, e + 12, y3 * 0x10101 + 0xFF000000) + end + p += size + end + end +end + +-- the vectors of a strip (ids 0x30 intra, 0x31 inter with skip flags, 0x32 V1 only) +@native local function vectors(pic: Picture.Picture, books: buffer, v4: number, v1: number, id: number, d: buffer, p: number, + stop: number, x1: number, y1: number, x2: number, y2: number): boolean + local stride = pic.stride + local pal = pic.idx + local px = (pal or pic.rgba) :: buffer + local flag, mask = 0, 0 + local inter = band(id, 1) ~= 0 + local v1only = band(id, 2) ~= 0 + for y = y1, y2 - 1, 4 do + for x = x1, x2 - 1, 4 do + local paint = true + if inter then + mask //= 2 + if mask == 0 then + if p + 4 > stop then + return false + end + flag = be32(d, p) + p += 4 + mask = 0x80000000 + end + paint = band(flag, mask) ~= 0 + end + if paint then + local useV1 = v1only + if not v1only then + mask //= 2 + if mask == 0 then + if p + 4 > stop then + return false + end + flag = be32(d, p) + p += 4 + mask = 0x80000000 + end + useV1 = band(flag, mask) == 0 + end + local o = y * stride + x + if useV1 then + if p >= stop then + return false + end + local e = v1 + readu8(d, p) * ENTRY + p += 1 + -- each of the 4 entries fills a 2x2 square + local a, b, c, e4 = readu32(books, e), readu32(books, e + 4), readu32(books, e + 8), readu32(books, e + 12) + if pal then + a, b, c, e4 = a % 256, b % 256, c % 256, e4 % 256 + writeu32(px, o, a * 0x0101 + b * 0x01010000) + writeu32(px, o + stride, a * 0x0101 + b * 0x01010000) + writeu32(px, o + 2 * stride, c * 0x0101 + e4 * 0x01010000) + writeu32(px, o + 3 * stride, c * 0x0101 + e4 * 0x01010000) + else + for r = 0, 3 do + local q = (o + r * stride) * 4 + local l, rr = if r < 2 then a else c, if r < 2 then b else e4 + writeu32(px, q, l) + writeu32(px, q + 4, l) + writeu32(px, q + 8, rr) + writeu32(px, q + 12, rr) + end + end + else + if p + 4 > stop then + return false + end + local e0 = v4 + readu8(d, p) * ENTRY + local e1 = v4 + readu8(d, p + 1) * ENTRY + local e2 = v4 + readu8(d, p + 2) * ENTRY + local e3 = v4 + readu8(d, p + 3) * ENTRY + p += 4 + -- entry k covers the 2x2 square k (top-left, top-right, bottom-left, bottom-right) + if pal then + for r = 0, 3 do + local l, rr = if r < 2 then e0 else e2, if r < 2 then e1 else e3 + local off = (r % 2) * 8 + local q = o + r * stride + writeu8(px, q, readu8(books, l + off)) + writeu8(px, q + 1, readu8(books, l + off + 4)) + writeu8(px, q + 2, readu8(books, rr + off)) + writeu8(px, q + 3, readu8(books, rr + off + 4)) + end + else + for r = 0, 3 do + local l, rr = if r < 2 then e0 else e2, if r < 2 then e1 else e3 + local off = (r % 2) * 8 + local q = (o + r * stride) * 4 + writeu32(px, q, readu32(books, l + off)) + writeu32(px, q + 4, readu32(books, l + off + 4)) + writeu32(px, q + 8, readu32(books, rr + off)) + writeu32(px, q + 12, readu32(books, rr + off + 4)) + end + end + end + end + end + end + return true +end + +@native function Cinepak.decode(pic: Picture.Picture, d: buffer, st: State, newPalette: boolean): (boolean, string?) + local n = buffer.len(d) + if n < 10 then + return false, "frame too short" + end + local strips = be16(d, 8) + if strips == 0 and not (pic.idx and newPalette) then + return false, nil + end + local size = be24(d, 1) + if n < size * 5 // 100 then + return false, "frame shorter than its header says" + end + if st.filmSkip < 0 then + if size == 0 then + return false, "unsupported: a zero frame size" + end + if size ~= n and n % size ~= 0 then + if n >= 16 and readu8(d, 10) == 0xFE and readu8(d, 11) == 0 and readu8(d, 12) == 0 and readu8(d, 13) == 6 + and readu8(d, 14) == 0 and readu8(d, 15) == 0 then + st.filmSkip = 6 + else + st.filmSkip = 2 + end + else + st.filmSkip = 0 + end + end + local skip = st.filmSkip + if n < 10 + skip + strips * 12 then + return false, "truncated strip headers" + end + if strips > 0 then + local ss = be24(d, 10 + skip + 1) + if ss < 12 or ss > size then + return false, "bad strip size" + end + end + local flags = readu8(d, 0) + local p = 10 + skip + strips = math.min(strips, MAX_STRIPS) + local books = st.books + local cw, ch = pic.stride, pic.rows + local y0 = 0 + for i = 0, strips - 1 do + if p + 12 > n then + return true, nil + end + local sy1 = be16(d, p + 4) + local sx1 = be16(d, p + 6) + local sy2, sx2 = be16(d, p + 8), be16(d, p + 10) + if sy1 == 0 then + sy1 = y0 + sy2 = y0 + sy2 + end + local ssize = be24(d, p + 1) - 12 + if ssize < 0 then + return true, nil + end + p += 12 + local stop = math.min(n, p + ssize) + local v4 = i * 2 * BOOK + local v1 = v4 + BOOK + if i > 0 and band(flags, 1) == 0 then + buffer.copy(books, v4, books, v4 - 2 * BOOK, 2 * BOOK) + end + -- (strips start on block boundaries in every known stream: the plane holds whole blocks only) + if sx2 > cw or sy2 > ch or sx1 >= sx2 or sy1 >= sy2 or band(sx1, 3) ~= 0 or band(sy1, 3) ~= 0 then + return true, nil + end + local q = p + local done = false + while q + 4 <= stop do + local id = readu8(d, q) + local csize = be24(d, q + 1) - 4 + if csize < 0 then + return true, nil + end + q += 4 + local cstop = math.min(stop, q + csize) + if id == 0x20 or id == 0x21 or id == 0x24 or id == 0x25 then + codebook(books, v4, id, d, q, cstop) + elseif id == 0x22 or id == 0x23 or id == 0x26 or id == 0x27 then + codebook(books, v1, id, d, q, cstop) + elseif id == 0x30 or id == 0x31 or id == 0x32 then + if not vectors(pic, books, v4, v1, id, d, q, cstop, sx1, sy1, sx2, sy2) then + return true, nil + end + done = true + break + end + q = cstop + end + if not done then + return true, nil + end + p = stop + y0 = sy2 + end + return true, nil +end + +return Cinepak +end +__FILES["codecs/video/Legacy/Flic"] = @native function() + + + +-- codecs/video/Legacy/Flic: Autodesk Animator FLI / FLC frames (the F1FA frame chunks; the file format is video/fli). +-- From Jim Kent's "FLC - Animator Pro Flic Files" (Dr. Dobb's 1993) and MultimediaWiki "Flic Video", bit-exact with +-- ffmpeg. 8-bit: COLOR_256 (4), COLOR_64 (11), DELTA_FLC / SS2 (7), DELTA_FLI / LC (12), BLACK (13), BYTE_RUN / BRUN +-- (15), FLI_COPY (16, rows padded to 4), PSTAMP (18). 15 / 16 / 24-bit FLC and FLX (DTA): DELTA / DTA_LC, BLACK, BRUN, +-- DTA_BRUN (25), COPY / DTA_COPY (16 / 26); 5-5-5 / 5-6-5 little-endian words or B, G, R bytes. +-- Not supported: 1-bit FLICs, the Magic Carpet 6-bit COLOR_256 variant. +local Types = __include("Types") +local Picture = __include("codecs/video/Legacy/Picture") + +local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32 +local bfill = buffer.fill + +local Flic = {} + +type State = { + pic: Picture.Picture, + depth: number, -- 8, 15, 16, 24 + bpp: number, +} + +@native function Flic.state(w: number, h: number, depth: number): (State?, string?) + local bpp = if depth == 8 then 1 elseif depth == 15 or depth == 16 then 2 elseif depth == 24 then 3 else 0 + if bpp == 0 then + return nil, "unsupported: " .. depth .. "-bit FLIC" + end + local pic = Picture.new(w * bpp, h, true) + pic.w = w + return { pic = pic, depth = depth, bpp = bpp }, nil +end + +@native local function s8(v: number): number + return if v >= 128 then v - 256 else v +end + +@native function Flic.decode(st: State, d: buffer): (boolean, string?) + local pic = st.pic + local px = pic.idx :: buffer + local pal = pic.pal + local w, h = pic.w, pic.h + local bpp = st.bpp + local deep = bpp > 1 + local stride = pic.stride + local limit = stride * h + local n = buffer.len(d) + if n < 16 then + return false, "frame too short" + end + local p = 0 + @native local function u8(): number + local v = if p < n then readu8(d, p) else 0 + p += 1 + return v + end + @native local function u16(): number + local a = u8() + return a + u8() * 256 + end + local frameSize = math.min(readu32(d, 0), n) + local chunks = readu8(d, 6) + readu8(d, 7) * 256 + if frameSize < 16 then + return false, "bad frame size" + end + frameSize -= 16 + p = 16 + while frameSize >= 6 and chunks > 0 and n - p >= 4 do + local size = readu32(d, p) + if size > frameSize then + size = frameSize + end + local after = p + size + p += 4 + local typ = u16() + if typ == 4 or typ == 11 then + if not deep then + -- palette packets: skip count, change count (0 = 256), r g b + local shift = typ == 11 + local packets = u16() + local at = 0 + for _ = 1, packets do + at += u8() + local count = u8() + if count == 0 then + count = 256 + end + if p + count * 3 > after then + break + end + for _ = 1, count do + if at >= 256 then + at = 0 + end + local r, g, b = u8(), u8(), u8() + if shift then + -- 6-bit entries: v << 2 (kept to 8 bits), the top two bits repeated below + r, g, b = r * 4 % 256, g * 4 % 256, b * 4 % 256 + r, g, b = r + r // 64, g + g // 64, b + b // 64 + end + writeu32(pal, at * 4, r + g * 256 + b * 65536 + 0xFF000000) + at += 1 + end + end + end + elseif typ == 7 or (deep and typ == 27) then + -- word-oriented delta: per line a count of packets (or a line skip / last-byte opcode) + local y = 0 + local lines = u16() + while lines > 0 do + if p + 2 > after then + break + end + if y > limit then + return false, "delta past the picture" + end + local lp = u16() + if lp >= 0x8000 then + lp -= 0x10000 + end + if deep then + if lp < 0 then + if -lp > h then + return false, "bad line skip" + end + y += -lp * stride + continue + end + elseif lp < 0 and lp >= -0x4000 then + -- 0xC000 .. 0xFFFF: skip lines + if -lp > h then + return false, "bad line skip" + end + y += -lp * stride + continue + elseif lp < 0 then + -- 0x8000 .. 0xBFFF: the low byte goes into the line's last pixel (ffmpeg writes the last byte of its + -- padded row instead: the same pixel when rows are not padded) + local q = y + w - 1 + if q < 0 or q >= limit then + return false, "delta past the picture" + end + writeu8(px, q, lp % 256) + continue + elseif lp >= 0x4000 then + continue -- undefined opcode + end + lines -= 1 + local q = y + for _ = 1, lp do + if p + 2 > after then + break + end + q += u8() * bpp + local run = s8(u8()) + if deep then + local cnt = if run < 0 then -run else run + if q + cnt * bpp > limit then + return false, "delta past the picture" + end + if run < 0 then + local a, b, c = u8(), u8(), if bpp == 3 then u8() else 0 + for _ = 1, cnt do + writeu8(px, q, a) + writeu8(px, q + 1, b) + if bpp == 3 then + writeu8(px, q + 2, c) + end + q += bpp + end + else + if p + cnt * bpp > after then + break + end + buffer.copy(px, q, d, p, cnt * bpp) + p += cnt * bpp + q += cnt * bpp + end + elseif run < 0 then + local cnt = -run + local a, b = u8(), u8() + if q + cnt * 2 > limit then + return false, "delta past the picture" + end + for _ = 1, cnt do + writeu8(px, q, a) + writeu8(px, q + 1, b) + q += 2 + end + else + if q + run * 2 > limit then + return false, "delta past the picture" + end + if p + run * 2 > after then + break + end + buffer.copy(px, q, d, p, run * 2) + p += run * 2 + q += run * 2 + end + end + y += stride + end + elseif typ == 12 and not deep then + -- byte-oriented delta (LC): first line, line count, per line packets of (skip, run) + local first = u16() + if first >= h then + return false, "bad first line" + end + local y = first * stride + local lines = u16() + while lines > 0 do + local q = y + if q > limit then + return false, "delta past the picture" + end + if p + 1 > after then + break + end + local packets = u8() + for _ = 1, packets do + if p + 1 > after then + break + end + q += u8() + local run = s8(u8()) + if run > 0 then + if q + run > limit then + return false, "delta past the picture" + end + if p + run > after then + break + end + buffer.copy(px, q, d, p, run) + p += run + q += run + elseif run < 0 then + local v = u8() + if q - run > limit then + return false, "delta past the picture" + end + bfill(px, q, v, -run) + q -= run + end + end + y += stride + lines -= 1 + end + elseif typ == 13 then + bfill(px, 0, 0, limit) + elseif typ == 15 or (deep and typ == 25) then + -- byte run (BRUN: bytes; DTA_BRUN: pixels of a deep FLIC): > 0 a run of one value, < 0 literals + local unit = if typ == 25 then bpp else 1 + local y = 0 + for _ = 1, h do + local q = y + p += 1 -- the packet count (unused) + local left = if typ == 25 then w else w * bpp + while left > 0 do + if p + 1 > after then + break + end + local run = s8(u8()) + if run == 0 and not deep then + return false, "zero byte run" + end + if run > 0 then + if q + run * unit > limit then + return false, "run past the picture" + end + if unit == 1 then + bfill(px, q, u8(), run) + q += run + else + local a, b, c = u8(), u8(), if bpp == 3 then u8() else 0 + for _ = 1, run do + writeu8(px, q, a) + writeu8(px, q + 1, b) + if bpp == 3 then + writeu8(px, q + 2, c) + end + q += bpp + end + end + left -= run + else + local cnt = -run + if q + cnt * unit > limit then + return false, "run past the picture" + end + if p + cnt * unit > after then + break + end + buffer.copy(px, q, d, p, cnt * unit) + p += cnt * unit + q += cnt * unit + left -= cnt + end + end + y += stride + end + elseif typ == 16 or (deep and typ == 26) then + -- uncompressed rows (8-bit rows padded to 4 bytes; deep rows of an odd width carry one pixel more) + local row = w * bpp + local padded = if deep then row + (w % 2) * bpp else ((w + 3) // 4) * 4 + local ok = if deep then size - 6 <= ((w + 1) // 2) * 2 * h * bpp else size - 6 == padded * h + if ok then + if deep and n - p < row * h then + return false, "truncated copy chunk" + end + for y = 0, h - 1 do + local s = p + y * padded + local cnt = math.max(0, math.min(row, n - s)) + if cnt > 0 then + buffer.copy(px, y * stride, d, s, cnt) + end + end + p += padded * h + end + end + -- typ 18 (PSTAMP) and unknown chunks are skipped + if after - p >= 0 then + p = after + else + break + end + frameSize -= size + chunks -= 1 + end + return true, nil +end + +@native function Flic.image(st: State): Types.Image + local pic = st.pic + if st.bpp == 1 then + return Picture.image(pic) + end + local w, h = pic.w, pic.h + local img = Types.Image.new(w, h, "rgba8") + local out = img.pixels + local px = pic.idx :: buffer + local stride = pic.stride + if st.bpp == 3 then + for y = 0, h - 1 do + local s, o = y * stride, y * w * 4 + for x = 0, w - 1 do + local q = s + x * 3 + writeu32(out, o + x * 4, readu8(px, q + 2) + readu8(px, q + 1) * 256 + readu8(px, q) * 65536 + 0xFF000000) + end + end + else + local lut = if st.depth == 15 then Picture.rgb555() else Picture.rgb565() + local mask = if st.depth == 15 then 32768 else 65536 + for y = 0, h - 1 do + local s, o = y * stride, y * w * 4 + for x = 0, w - 1 do + local q = s + x * 2 + writeu32(out, o + x * 4, readu32(lut, ((readu8(px, q) + readu8(px, q + 1) * 256) % mask) * 4)) + end + end + end + return img +end + +return Flic +end +__FILES["codecs/video/Legacy/Msvideo1"] = @native function() + + + +-- codecs/video/Legacy/Msvideo1: Microsoft Video 1 (CRAM / MSVC / WHAM), 8-bit palettised and 16-bit X-R-G-B 1-5-5-5. +-- From MultimediaWiki "Microsoft Video 1", bit-exact with ffmpeg: 4x4 blocks, block rows (and rows in a block) bottom-up; +-- a 16-bit code per block: skip (0x84xx - 0x87xx), 2-colour (16 flag bits + 2 colours; at 16 bits c0 bit 15 set = 8-colour, +-- a pair per quadrant; at 8 bits codes >= 0x9000 are 8-colour), else 1-colour. +local Picture = __include("codecs/video/Legacy/Picture") + +local readu8, readu16, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu32 +local band = bit32.band + +local Msvideo1 = {} + +-- 2-colour: bit set = c0; 8-colour: colours[quadrant * 2 + (bit clear)] +@native local function quadrant(x: number, y: number): number + return (if y >= 2 then 4 else 0) + (if x >= 2 then 2 else 0) +end + +@native function Msvideo1.decode(pic: Picture.Picture, d: buffer, bits: number): (boolean, string?) + local n = buffer.len(d) + local bw, bh = pic.w // 4, pic.h // 4 + if n < bw * bh // 512 then + return false, "frame too small" + end + local stride = pic.stride + local total = bw * bh + local skip = 0 + local p = 0 + local wide = bits ~= 8 + local px = (if wide then pic.rgba else pic.idx) :: buffer + local lut = if wide then Picture.rgb555() else nil + local c = table.create(8, 0) + for by = bh - 1, 0, -1 do + for bx = 0, bw - 1 do + if skip ~= 0 then + skip -= 1 + total -= 1 + continue + end + if p + 2 > n then + return true, nil + end + local a, b = readu8(d, p), readu8(d, p + 1) + p += 2 + if a == 0 and b == 0 and total == 0 then + return true, nil + end + local o = (by * 4 + 3) * stride + bx * 4 + if band(b, 0xFC) == 0x84 then + skip = (b - 0x84) * 256 + a - 1 + elseif b < 0x80 or (not wide and b >= 0x90) then + local flags = b * 256 + a + local eight + if wide then + if p + 4 > n then + return true, nil + end + c[1], c[2] = readu16(d, p), readu16(d, p + 2) + p += 4 + eight = c[1] >= 0x8000 + if eight then + if p + 12 > n then + return true, nil + end + for k = 3, 8 do + c[k] = readu16(d, p) + p += 2 + end + end + else + eight = b >= 0x90 + local cnt = if eight then 8 else 2 + if p + cnt > n then + return true, nil + end + for k = 1, cnt do + c[k] = readu8(d, p) + p += 1 + end + end + for y = 0, 3 do + local row = o - y * stride + for x = 0, 3 do + local k = (if band(flags, 1) == 1 then 1 else 2) + if eight then + k += quadrant(x, y) + end + flags = flags // 2 + if lut then + writeu32(px, (row + x) * 4, readu32(lut, (c[k] % 32768) * 4)) + else + writeu8(px, row + x, c[k]) + end + end + end + else + local v = if wide then readu32(lut :: buffer, ((b * 256 + a) % 32768) * 4) else a + for y = 0, 3 do + local row = o - y * stride + if lut then + for x = 0, 3 do + writeu32(px, (row + x) * 4, v) + end + else + writeu32(px, row, v * 0x01010101) + end + end + end + total -= 1 + end + end + return true, nil +end + +return Msvideo1 +end +__FILES["codecs/video/Legacy/Picture"] = @native function() + + + +-- codecs/video/Legacy/Picture: the picture the legacy inter-frame decoders paint over (u8 index plane + palette or rgba8). +-- 5-5-5 / 5-6-5 widen by bit replication (c << 3 | c >> 2), as ffmpeg's swscale does. +local Types = __include("Types") +local Pixels = __include("codecs/image/Pixels") + +local readu32, writeu32 = buffer.readu32, buffer.writeu32 + +local Picture = {} + +type Picture = { + w: number, + h: number, + stride: number, -- index plane: bytes per row; rgba plane: pixels per row + rows: number, + idx: buffer?, -- u8 index plane, stride * rows bytes (palettised) + rgba: buffer?, -- u32 rgba8 plane, stride * rows * 4 bytes (direct colour) + pal: buffer, -- 256 u32 entries, bytes R, G, B, A +} + +@native function Picture.new(w: number, h: number, palettised: boolean, padW: number?, padH: number?, palette: buffer?): Picture + local pw, ph = padW or 1, padH or 1 + local stride = ((w + pw - 1) // pw) * pw + local rows = ((h + ph - 1) // ph) * ph + local pal = buffer.create(1024) + if palette and buffer.len(palette) >= 1024 then + buffer.copy(pal, 0, palette, 0, 1024) + end + local p: Picture = { w = w, h = h, stride = stride, rows = rows, pal = pal } + if palettised then + p.idx = buffer.create(stride * rows) + else + p.rgba = buffer.create(stride * rows * 4) + end + return p +end + +@native function Picture.image(p: Picture): Types.Image + local w, h = p.w, p.h + local img = Types.Image.new(w, h, "rgba8") + local idx, rgba = p.idx, p.rgba + if idx then + Pixels.indexed(idx, 0, p.stride, 8, img.pixels, w, h, true, p.pal) + elseif rgba then + if p.stride == w then + buffer.copy(img.pixels, 0, rgba, 0, w * h * 4) + else + for y = 0, h - 1 do + buffer.copy(img.pixels, y * w * 4, rgba, y * p.stride * 4, w * 4) + end + end + end + return img +end + +@native function Picture.setPalette(p: Picture, src: buffer) + if buffer.len(src) >= 1024 then + buffer.copy(p.pal, 0, src, 0, 1024) + end +end + +local lut555: buffer? = nil +local lut565: buffer? = nil + +@native function Picture.rgb555(): buffer + local t = lut555 + if t then + return t + end + local b = buffer.create(32768 * 4) + for v = 0, 32767 do + local r, g, bl = v // 1024, (v // 32) % 32, v % 32 + r, g, bl = r * 8 + r // 4, g * 8 + g // 4, bl * 8 + bl // 4 + writeu32(b, v * 4, r + g * 256 + bl * 65536 + 0xFF000000) + end + lut555 = b + return b +end + +@native function Picture.rgb565(): buffer + local t = lut565 + if t then + return t + end + local b = buffer.create(65536 * 4) + for v = 0, 65535 do + local r, g, bl = v // 2048, (v // 32) % 64, v % 32 + r, g, bl = r * 8 + r // 4, g * 4 + g // 16, bl * 8 + bl // 4 + writeu32(b, v * 4, r + g * 256 + bl * 65536 + 0xFF000000) + end + lut565 = b + return b +end + +@native function Picture.clonePlane(p: Picture): buffer + local src = (p.idx or p.rgba) :: buffer + local c = buffer.create(buffer.len(src)) + buffer.copy(c, 0, src, 0) + return c +end + +local _ = readu32 + +return Picture +end +__FILES["codecs/video/Legacy/QtRle"] = @native function() + + + +-- codecs/video/Legacy/QtRle: QuickTime Animation ('rle ') frames, depths 1, 2, 4, 8 (palettised; 33..40 = grey), +-- 16 (X-R-G-B 1-5-5-5), 24 (R, G, B), 32 (A, R, G, B). From Apple QuickTime File Format and MultimediaWiki "Apple +-- QuickTime RLE", bit-exact with ffmpeg on valid streams: chunk size, header (0x0008: start line + line count), per line +-- a skip byte and codes until -1 (0: another skip; < 0: one group repeated; > 0: literal groups). Groups are 4 pixels at +-- 8 bits, 8 at 4, 16 at 2, 1 at 16 / 24 / 32. Frames shorter than 8 bytes repeat the picture. +local Picture = __include("codecs/video/Legacy/Picture") + +local readu8, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu8, buffer.writeu32 +local band, rshift = bit32.band, bit32.rshift + +local QtRle = {} + +@native local function s8(v: number): number + return if v >= 128 then v - 256 else v +end + +-- 1-bit: (skip, code) pairs; skip bit 7 = next line (the first one starts the first line) +@native local function decode1(px: buffer, stride: number, limit: number, d: buffer, p: number, n: number, row: number, lines: number) + row -= stride + local q = row + lines += 1 + while lines > 0 do + if p + 2 > n then + return + end + local skip = readu8(d, p) + local code = s8(readu8(d, p + 1)) + p += 2 + if code == 0 then + return + end + if skip >= 128 then + lines -= 1 + row += stride + q = row + 16 * (skip - 128) + else + q += 16 * skip + end + if q < 0 or q > limit then + return + end + if code ~= -1 then + if code < 0 then + local cnt = -code + if p + 2 > n or q + cnt * 16 > limit then + return + end + local a, b = readu8(d, p), readu8(d, p + 1) + p += 2 + for _ = 1, cnt do + for k = 7, 0, -1 do + writeu8(px, q, band(rshift(a, k), 1)) + q += 1 + end + for k = 7, 0, -1 do + writeu8(px, q, band(rshift(b, k), 1)) + q += 1 + end + end + else + local cnt = code * 2 + if p + cnt > n or q + cnt * 8 > limit then + return + end + for _ = 1, cnt do + local a = readu8(d, p) + p += 1 + for k = 7, 0, -1 do + writeu8(px, q, band(rshift(a, k), 1)) + q += 1 + end + end + end + end + end +end + +-- 2 / 4 / 8-bit: groups of 16 / 8 / 4 indexes (4 bytes); skips count groups +@native local function decodeIdx(px: buffer, stride: number, limit: number, d: buffer, p: number, n: number, row: number, lines: number, bpp: number) + local group = 32 // bpp + local per = 8 // bpp + local mask = 2 ^ bpp - 1 + for _ = 1, lines do + if p >= n then + return + end + local q = row + group * (readu8(d, p) - 1) + p += 1 + if q < 0 or q > limit then + return + end + while true do + if p >= n then + return + end + local code = s8(readu8(d, p)) + p += 1 + if code == -1 then + break + end + if p >= n then + return + end + if code == 0 then + q += group * (readu8(d, p) - 1) + p += 1 + if q < 0 or q > limit then + return + end + elseif code < 0 then + local cnt = -code + if p + 4 > n or q + cnt * group > limit then + return + end + if bpp == 8 then + local v = readu32(d, p) + for _ = 1, cnt do + writeu32(px, q, v) + q += 4 + end + else + local v0 = q + for b = 0, 3 do + local byte = readu8(d, p + b) + for k = per - 1, 0, -1 do + writeu8(px, q, band(rshift(byte, k * bpp), mask)) + q += 1 + end + end + for _ = 2, cnt do + buffer.copy(px, q, px, v0, group) + q += group + end + end + p += 4 + else + local bytes = code * 4 + if p + bytes > n or q + bytes * per > limit then + return + end + if bpp == 8 then + buffer.copy(px, q, d, p, bytes) + q += bytes + else + for b = 0, bytes - 1 do + local byte = readu8(d, p + b) + for k = per - 1, 0, -1 do + writeu8(px, q, band(rshift(byte, k * bpp), mask)) + q += 1 + end + end + end + p += bytes + end + end + row += stride + end +end + +-- 16 / 24 / 32-bit: one pixel per group, into the rgba8 plane (stride in pixels) +@native local function decodeRgb(px: buffer, stride: number, limit: number, d: buffer, p: number, n: number, row: number, lines: number, depth: number) + local bpp = depth // 8 + local lut = if depth == 16 then Picture.rgb555() else nil + for _ = 1, lines do + if p >= n then + return + end + local q = row + (readu8(d, p) - 1) + p += 1 + if q < 0 or q > limit then + return + end + while true do + if p >= n then + return + end + local code = s8(readu8(d, p)) + p += 1 + if code == -1 then + break + end + if p >= n then + return + end + if code == 0 then + q += readu8(d, p) - 1 + p += 1 + if q < 0 or q > limit then + return + end + else + local cnt = if code < 0 then -code else code + local need = if code < 0 then bpp else bpp * cnt + if p + need > n or q + cnt > limit then + return + end + for _ = 1, cnt do + local v + if lut then + v = readu32(lut, (readu8(d, p) * 256 + readu8(d, p + 1)) % 32768 * 4) + elseif bpp == 3 then + v = readu8(d, p) + readu8(d, p + 1) * 256 + readu8(d, p + 2) * 65536 + 0xFF000000 + else + v = readu8(d, p + 1) + readu8(d, p + 2) * 256 + readu8(d, p + 3) * 65536 + readu8(d, p) * 16777216 + end + writeu32(px, q * 4, v) + q += 1 + if code > 0 then + p += bpp + end + end + if code < 0 then + p += bpp + end + end + end + row += stride + end +end + +@native function QtRle.decode(pic: Picture.Picture, d: buffer, depth: number): (boolean, string?) + local n = buffer.len(d) + if n < 8 then + return true, nil + end + local p = 4 + local header = readu8(d, p) * 256 + readu8(d, p + 1) + p += 2 + local h = pic.h + local start, lines = 0, h + if band(header, 8) ~= 0 then + if n < 14 then + return true, nil + end + start = readu8(d, p) * 256 + readu8(d, p + 1) + lines = readu8(d, p + 4) * 256 + readu8(d, p + 5) + p += 8 + if lines > h - start then + return true, nil + end + end + local stride = pic.stride + local bits = if depth > 32 then depth - 32 else depth + local idx, rgba = pic.idx, pic.rgba + if idx and bits <= 8 then + local limit = stride * h + if bits == 1 then + decode1(idx, stride, limit, d, p, n, start * stride, lines) + else + decodeIdx(idx, stride, limit, d, p, n, start * stride, lines, bits) + end + elseif rgba and (bits == 16 or bits == 24 or bits == 32) then + decodeRgb(rgba, stride, stride * h, d, p, n, start * stride, lines, bits) + else + return false, "unsupported: depth " .. depth + end + return true, nil +end + +@native function QtRle.palettised(depth: number): boolean + return depth <= 8 or depth > 32 +end +@native function QtRle.pad(depth: number): number + local bits = if depth > 32 then depth - 32 else depth + return if bits <= 8 then 32 // math.max(1, bits) else 1 +end + +return QtRle +end +__FILES["codecs/video/Legacy/Smacker"] = @native function() + + + +-- codecs/video/Legacy/Smacker: RAD Game Tools' Smacker video (SMK2 / SMK4 frames; the file format is video/smk) and +-- the Huffman trees Smacker audio shares. From MultimediaWiki "Smacker", bit-exact with ffmpeg's smackvid. +-- Bits LSB first. A tree is a pre-order bit string (1 = node: left subtree then right; 0 = leaf). A big tree's 16-bit +-- leaves pair a low-byte and a high-byte 8-bit tree; three escape leaves return the three most recently decoded values +-- (reset each frame). The header holds the MMAP, MCLR, FULL and TYPE big trees; a frame is 4x4 blocks in raster order, +-- each TYPE code a block type and run length: MONO (two colours + 16-bit mask), FULL (16 pixels as 8 codes; SMK4 adds +-- 2x2- and 2x1-doubled modes), SKIP, FILL. +local Picture = __include("codecs/video/Legacy/Picture") + +local readu8, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu8, buffer.writeu32 +local band, rshift = bit32.band, bit32.rshift + +local Smacker = {} + +local MAX_DEPTH8 = 27 -- 8-bit trees (3 x 9-bit lookups in the reference decoder) +local MAX_DEPTH16 = 500 + +-- block runs (TYPE code bits 2..7) +local RUNS = table.create(64, 0) +for i = 1, 59 do + RUNS[i] = i +end +RUNS[60], RUNS[61], RUNS[62], RUNS[63], RUNS[64] = 128, 256, 512, 1024, 2048 + +type Bits = { buf: buffer, pos: number, nbits: number } + +@native function Smacker.bits(buf: buffer, offset: number, length: number): Bits + return { buf = buf, pos = offset * 8, nbits = (offset + length) * 8 } +end + +@native local function bit(br: Bits): number + local p = br.pos + br.pos = p + 1 + if p >= br.nbits then + return 0 + end + return band(rshift(readu8(br.buf, rshift(p, 3)), band(p, 7)), 1) +end +Smacker.bit = bit + +@native function Smacker.read(br: Bits, n: number): number + local v, m = 0, 1 + for _ = 1, n do + v += bit(br) * m + m *= 2 + end + return v +end +local readBits = Smacker.read + +-- no end-of-data check for 8-bit trees, as the reference's table lookups +@native local function walk(tree: { number }, br: Bits): number + local i = 1 + local e = tree[1] + while e < 0 do + if bit(br) == 1 then + i += -e - 1 + end + i += 1 + e = tree[i] + end + return e +end +Smacker.walk = walk + +@native local function build(br: Bits, maxDepth: number, maxEntries: number, leaf: (number) -> (number?, string?), bigChecks: boolean): ({ number }?, string?) + local vals: { number } = {} + local n = 0 + local stack: { number } = {} + local state: { number } = {} + local sp = 0 + while true do + if sp > maxDepth then + return nil, "tree too deep" + end + if n >= maxEntries then + return nil, "tree too big" + end + if bigChecks and br.pos >= br.nbits then + return nil, "truncated tree" + end + if bit(br) == 1 then + n += 1 + vals[n] = -1 + sp += 1 + stack[sp], state[sp] = n, 0 + else + local v, msg = leaf(n) + if not v then + return nil, msg + end + n += 1 + vals[n] = v + local more = false + while sp > 0 do + if state[sp] == 0 then + local at = stack[sp] + vals[at] = -(n - at) - 1 -- the left subtree holds n - at entries + state[sp] = 1 + more = true + break + end + sp -= 1 + end + if not more then + return vals, nil + end + end + end +end + +@native function Smacker.tree8(br: Bits): ({ number }?, string?) + local leaves = 0 + return build(br, MAX_DEPTH8, 511, @native function(_: number): (number?, string?) + if leaves >= 256 then + return nil, "tree too big" + end + leaves += 1 + if br.nbits - br.pos < 8 then + return nil, "truncated tree" + end + return readBits(br, 8), nil + end, false) +end +local tree8 = Smacker.tree8 + +type BigTree = { vals: { number }, last: { number }, lut: buffer? } -- last: the escape leaves' indexes (1-based) + +@native local function bigTree(br: Bits, size: number): (BigTree?, string?) + if bit(br) == 0 then + return { vals = { 0, 0 }, last = { 2, 2, 2 } }, nil -- no tree: every code is 0 + end + local lohi: { { number } } = {} + for k = 1, 2 do + if bit(br) == 0 then + lohi[k] = { 0 } + else + local t, msg = tree8(br) + if not t then + return nil, msg + end + bit(br) + lohi[k] = t + end + end + local esc = { readBits(br, 16), readBits(br, 16), readBits(br, 16) } + local last = { -1, -1, -1 } + local lo, hi = lohi[1], lohi[2] + local vals, msg = build(br, MAX_DEPTH16, (size + 3) // 4, @native function(index: number): (number?, string?) + local v = walk(lo, br) + walk(hi, br) * 256 + for k = 1, 3 do + if v == esc[k] then + last[k] = index + 1 + return 0, nil + end + end + return v, nil + end, true) + if not vals then + return nil, msg + end + bit(br) + for k = 1, 3 do + if last[k] == -1 then + table.insert(vals, 0) + last[k] = #vals + end + end + return { vals = vals, last = last }, nil +end + +type Trees = { mmap: BigTree, mclr: BigTree, full: BigTree, type: BigTree } + +-- config = the four u32 tree sizes, then the tree bits +@native function Smacker.trees(config: buffer): (Trees?, string?) + local n = buffer.len(config) + if n <= 16 then + return nil, "no trees" + end + local br = Smacker.bits(config, 16, n - 16) + local out: { BigTree } = {} + local present = 0 + for k = 1, 4 do + local size = buffer.readu32(config, (k - 1) * 4) + if size >= 2 ^ 28 then + return nil, "tree size too large" + end + local here = br.pos < br.nbits and band(rshift(readu8(config, rshift(br.pos, 3)), band(br.pos, 7)), 1) == 1 + local t, msg = bigTree(br, size) + if not t then + return nil, msg + end + if here then + present += 1 + end + out[k] = t + end + if present == 0 or br.pos > br.nbits then + return nil, "bad trees" + end + return { mmap = out[1], mclr = out[2], full = out[3], type = out[4] }, nil +end + +local LUT_BITS = 10 + +-- the first LUT_BITS bits of a code -> (entry index * 32 + bits used): a leaf, or the node reached after LUT_BITS bits +@native local function lut(vals: { number }): buffer + local size = 2 ^ LUT_BITS + local t = buffer.create(size * 4) + for pat = 0, size - 1 do + local i, len = 1, 0 + local e = vals[1] + while e < 0 and len < LUT_BITS do + if band(rshift(pat, len), 1) == 1 then + i += -e - 1 + end + i += 1 + len += 1 + e = vals[i] + end + writeu32(t, pat * 4, i * 32 + len) + end + return t +end + +@native local function reset(t: BigTree) + local vals, last = t.vals, t.last + vals[last[1]], vals[last[2]], vals[last[3]] = 0, 0, 0 +end + +@native function Smacker.decode(pic: Picture.Picture, d: buffer, trees: Trees, v4: boolean): (boolean, string?) + local px = pic.idx :: buffer + local stride = pic.stride + local mmap, mclr, full, typ = trees.mmap, trees.mclr, trees.full, trees.type + for _, t in { mmap, mclr, full, typ } do + reset(t) + if not t.lut then + t.lut = lut(t.vals) + end + end + local n = buffer.len(d) + local nbits = n * 8 + local pos = 0 + @native local function code(t: BigTree): number + local vals = t.vals + local i, p + local byte = rshift(pos, 3) + if byte + 3 <= n then + local v = band(rshift(readu8(d, byte) + readu8(d, byte + 1) * 256 + readu8(d, byte + 2) * 65536, band(pos, 7)), 1023) + local ent = readu32(t.lut :: buffer, v * 4) + i = rshift(ent, 5) + p = pos + band(ent, 31) + else + i, p = 1, pos + end + local e = vals[i] + while e < 0 do + if p >= nbits then + return -1 + end + if band(rshift(readu8(d, rshift(p, 3)), band(p, 7)), 1) == 1 then + i += -e - 1 + end + p += 1 + i += 1 + e = vals[i] + end + pos = p + local last = t.last + local l0 = last[1] + if e ~= vals[l0] then + local l1 = last[2] + vals[last[3]] = vals[l1] + vals[l1] = vals[l0] + vals[l0] = e + end + return e + end + @native local function bit(): number + local p = pos + pos = p + 1 + if p >= nbits then + return 0 + end + return band(rshift(readu8(d, rshift(p, 3)), band(p, 7)), 1) + end + local bw, bh = pic.w // 4, pic.h // 4 + local blocks = bw * bh + local blk = 0 + while blk < blocks do + local ty = code(typ) + if ty < 0 then + return false, "truncated frame" + end + local run = RUNS[band(rshift(ty, 2), 63) + 1] + local kind = band(ty, 3) + if kind == 2 then + blk = math.min(blocks, blk + run) + elseif kind == 3 then + local v = rshift(ty, 8) * 0x01010101 + for _ = 1, run do + if blk >= blocks then + break + end + local o = (blk // bw) * stride * 4 + (blk % bw) * 4 + writeu32(px, o, v) + writeu32(px, o + stride, v) + writeu32(px, o + 2 * stride, v) + writeu32(px, o + 3 * stride, v) + blk += 1 + end + elseif kind == 0 then + for _ = 1, run do + if blk >= blocks then + break + end + local clr = code(mclr) + local map = code(mmap) + if clr < 0 or map < 0 then + return false, "truncated frame" + end + local hi, lo = rshift(clr, 8), band(clr, 255) + local o = (blk // bw) * stride * 4 + (blk % bw) * 4 + for r = 0, 3 do + local q = o + r * stride + writeu8(px, q, if band(map, 1) ~= 0 then hi else lo) + writeu8(px, q + 1, if band(map, 2) ~= 0 then hi else lo) + writeu8(px, q + 2, if band(map, 4) ~= 0 then hi else lo) + writeu8(px, q + 3, if band(map, 8) ~= 0 then hi else lo) + map = rshift(map, 4) + end + blk += 1 + end + else + local mode = 0 + if v4 then + if pos >= nbits then + return false, "truncated frame" + end + if bit() == 1 then + mode = 1 + elseif bit() == 1 then + mode = 2 + end + end + for _ = 1, run do + if blk >= blocks then + break + end + local o = (blk // bw) * stride * 4 + (blk % bw) * 4 + if mode == 0 then + for r = 0, 3 do + local a = code(full) + local b = code(full) + if a < 0 or b < 0 then + return false, "truncated frame" + end + -- the first code is the right pixel pair, the second the left one + writeu32(px, o + r * stride, b + a * 65536) + end + elseif mode == 1 then + for half = 0, 1 do + local a = code(full) + if a < 0 then + return false, "truncated frame" + end + local v = band(a, 255) * 0x0101 + rshift(a, 8) * 0x01010000 + writeu32(px, o + half * 2 * stride, v) + writeu32(px, o + (half * 2 + 1) * stride, v) + end + else + for half = 0, 1 do + local p2 = code(full) + local p1 = code(full) + if p1 < 0 or p2 < 0 then + return false, "truncated frame" + end + local v = p1 + p2 * 65536 + writeu32(px, o + half * 2 * stride, v) + writeu32(px, o + (half * 2 + 1) * stride, v) + end + end + blk += 1 + end + end + end + return true, nil +end + +return Smacker +end +__FILES["codecs/video/Legacy/Smc"] = @native function() + + + +-- codecs/video/Legacy/Smc: QuickTime Graphics ('smc ') frames, 8-bit palettised; from MultimediaWiki "Apple SMC", +-- bit-exact with ffmpeg. 4x4 blocks in raster order; opcode in the high nibble, count = low nibble + 1 (bit 4: next +-- byte + 1); the colour-group tables restart every frame. As ffmpeg: a row start's previous block ends the row above. +local Picture = __include("codecs/video/Legacy/Picture") + +local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32 +local band, rshift = bit32.band, bit32.rshift + +local Smc = {} + +@native function Smc.decode(pic: Picture.Picture, d: buffer, tables: buffer): (boolean, string?) + local px = pic.idx :: buffer + local n = buffer.len(d) + local stride = pic.stride -- a multiple of 4: the plane holds whole blocks + local bh = pic.rows // 4 + local total = ((pic.w + 3) // 4) * ((pic.h + 3) // 4) + if total // 1024 > n then + return false, "frame too small" + end + local blocksWide = (pic.w + 3) // 4 + local p = 4 -- flags byte + 24-bit chunk size + local bx, by = 0, 0 + local pairI, quadI, octI = 0, 0, 0 + -- tables: pairs at 0 (256 * 2), quads at 512 (256 * 4), octets at 1536 (256 * 8) + @native local function u8(): number + if p < n then + local v = readu8(d, p) + p += 1 + return v + end + return 0 + end + @native local function advance() + bx += 1 + if bx >= blocksWide then + bx = 0 + by += 1 + end + total -= 1 + end + while total > 0 do + if p >= n then + return false, "truncated" + end + local op = readu8(d, p) + p += 1 + local kind = rshift(op, 4) + local count: number + if kind < 8 then + count = if band(op, 0x10) ~= 0 then 1 + u8() else 1 + band(op, 15) + else + count = band(op, 15) + 1 + end + if kind <= 1 then + for _ = 1, count do + if total <= 0 then + break + end + advance() + end + elseif kind <= 5 then + -- repeat the last block (2, 3) or the last pair of blocks (4, 5) + local pair = kind >= 4 + local back = if pair then 2 else 1 + local pos = by * blocksWide + bx + if pos < back then + return false, "repeat before any block" + end + local reps = if pair then count * 2 else count + local srcA = pos - back + local srcB = pos - 1 + for k = 0, reps - 1 do + if total <= 0 or by >= bh then + break + end + local s = if pair and k % 2 == 1 then srcB else srcA + local sx, sy = (s % blocksWide) * 4, (s // blocksWide) * 4 + local o, so = by * 4 * stride + bx * 4, sy * stride + sx + for r = 0, 3 do + writeu32(px, o + r * stride, readu32(px, so + r * stride)) + end + advance() + end + elseif kind <= 7 then + local c = u8() + local v = c * 0x01010101 + for _ = 1, count do + if total <= 0 or by >= bh then + break + end + local o = by * 4 * stride + bx * 4 + for r = 0, 3 do + writeu32(px, o + r * stride, v) + end + advance() + end + elseif kind <= 13 then + -- 2 / 4 / 8-colour blocks: a new colour group (even kinds) or one from the table (odd kinds) + local size = if kind <= 9 then 2 elseif kind <= 11 then 4 else 8 + local base = if size == 2 then 0 elseif size == 4 then 512 else 1536 + local entry: number + if kind % 2 == 0 then + local i = if size == 2 then pairI elseif size == 4 then quadI else octI + for k = 0, size - 1 do + writeu8(tables, base + i * size + k, u8()) + end + entry = i + i = (i + 1) % 256 + if size == 2 then + pairI = i + elseif size == 4 then + quadI = i + else + octI = i + end + else + entry = u8() + end + local t = base + entry * size + for _ = 1, count do + if total <= 0 or by >= bh then + break + end + local o = by * 4 * stride + bx * 4 + if size == 2 then + local f = u8() * 256 + u8() + for k = 0, 15 do + local bit = band(rshift(f, 15 - k), 1) + writeu8(px, o + (k // 4) * stride + k % 4, readu8(tables, t + bit)) + end + elseif size == 4 then + local f = u8() * 16777216 + u8() * 65536 + u8() * 256 + u8() + for k = 0, 15 do + local i = band(rshift(f, 30 - 2 * k), 3) + writeu8(px, o + (k // 4) * stride + k % 4, readu8(tables, t + i)) + end + else + -- 6 bytes 01 23 45 67 89 AB -> rows 0-1 flags 012456, rows 2-3 flags 89A37B (3 bits per pixel) + local v1 = u8() * 256 + u8() + local v2 = u8() * 256 + u8() + local v3 = u8() * 256 + u8() + local fa = band(v1, 0xFFF0) * 256 + rshift(v2, 4) + local fb = band(v3, 0xFFF0) * 256 + band(v1, 15) * 256 + band(v2, 15) * 16 + band(v3, 15) + for k = 0, 15 do + local f = if k < 8 then fa else fb + local i = band(rshift(f, 21 - 3 * (k % 8)), 7) + writeu8(px, o + (k // 4) * stride + k % 4, readu8(tables, t + i)) + end + end + advance() + end + else + for _ = 1, count do + if total <= 0 or by >= bh then + break + end + local o = by * 4 * stride + bx * 4 + for k = 0, 15 do + writeu8(px, o + (k // 4) * stride + k % 4, u8()) + end + advance() + end + end + end + return true, nil +end + +@native function Smc.tables(): buffer + return buffer.create(512 + 1024 + 2048) +end + +return Smc +end +end + + + + + + MpegTs + --!optimize 2 +--!nocheck +-- rosetta chunk MpegTs (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 3 modules (1 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["containers/MpegEs"] = function() + +-- containers/MpegEs: helpers over MPEG video elementary streams for the MPEG-TS / PS demuxers. New in rosetta. +-- Start-code scanning, MPEG-1 / MPEG-2 video access units (a picture with the sequence / GOP headers before it, +-- picture type and temporal reference, the sequence's frame rate and size, MPEG-2 detection by its sequence +-- extension) and H.264 Annex B keyframes (an IDR slice, or a recovery-point SEI). Interpreted; never throws. +local readu8 = buffer.readu8 + +local MpegEs = {} + +function MpegEs.findStart(b: buffer, p: number, limit: number): number? + local i = p + while i + 3 <= limit do + local c = readu8(b, i + 2) + if c > 1 then + i += 3 + elseif c == 1 then + if readu8(b, i) == 0 and readu8(b, i + 1) == 0 then + return i + end + i += 3 + else -- c == 0: the start code may begin at i + 1 or i + 2 + i += 1 + end + end + return nil +end + +local FRAME_RATES = { 24000 / 1001, 24, 25, 30000 / 1001, 30, 50, 60000 / 1001, 60 } + +type Picture = { + offset: number, -- start of the access unit (its first header's start code) + size: number, + type: number, -- 1 I, 2 P, 3 B, 4 D (0 unknown) + temporal: number, -- temporal_reference + gop: boolean, -- a GOP header precedes the picture + sequence: boolean, -- a sequence header precedes the picture + structure: number, -- MPEG-2 picture_structure: 1 top field, 2 bottom field, 3 frame (MPEG-1: 3) + fields: number?, -- 2: a frame coded as two field pictures (both in this unit) +} +type Info = { width: number, height: number, frameRate: number, mpeg2: boolean } + +function MpegEs.info(b: buffer, off: number, limit: number): Info? + local p = MpegEs.findStart(b, off, limit) + local info: Info? = nil + local count = 0 + while p and count < 64 do + count += 1 + local code = if p + 3 < limit then readu8(b, p + 3) else -1 + if code == 0xB3 and p + 11 < limit and not info then + local w = readu8(b, p + 4) * 16 + readu8(b, p + 5) // 16 + local h = (readu8(b, p + 5) % 16) * 256 + readu8(b, p + 6) + local fr = readu8(b, p + 7) % 16 + info = { width = w, height = h, frameRate = FRAME_RATES[fr] or 0, mpeg2 = false } + elseif code == 0xB5 and info then + info.mpeg2 = true + return info + elseif code == 0x00 and info then + return info + end + p = MpegEs.findStart(b, p + 4, limit) + end + return info +end + +function MpegEs.pictureType(b: buffer, off: number, limit: number): (number, number) + local p = MpegEs.findStart(b, off, limit) + local count = 0 + while p and count < 32 do + count += 1 + if p + 5 < limit and readu8(b, p + 3) == 0x00 then + local x = readu8(b, p + 4) * 256 + readu8(b, p + 5) + return (x // 8) % 8, x // 64 + end + p = MpegEs.findStart(b, p + 4, limit) + end + return 0, 0 +end + +function MpegEs.pictureStructure(b: buffer, p: number, limit: number): number + local q = MpegEs.findStart(b, p + 4, limit) + local count = 0 + while q and count < 8 do + count += 1 + local code = if q + 6 < limit then readu8(b, q + 3) else -1 + if code == 0xB5 then + if readu8(b, q + 4) // 16 == 8 then + local st = readu8(b, q + 6) % 4 + return if st == 0 then 3 else st + end + elseif code ~= 0xB2 then + break + end + q = MpegEs.findStart(b, q + 4, limit) + end + return 3 +end + +function MpegEs.pictures(b: buffer, off: number, limit: number): { Picture } + local out: { Picture } = {} + local unitStart: number? = nil + local seq, gop = false, false + local cur: Picture? = nil + local p = MpegEs.findStart(b, off, limit) + while p do + local code = if p + 3 < limit then readu8(b, p + 3) else -1 + local st = if code == 0x00 then MpegEs.pictureStructure(b, p, limit) else 3 + if code == 0x00 and cur and cur.structure ~= 3 and cur.fields == nil and st ~= 3 and st ~= cur.structure then + -- the second field of the current frame: same unit + cur.fields = 2 + elseif code == 0xB3 or code == 0xB8 or code == 0x00 or code == 0xB7 then + -- a sequence / GOP header or a picture after a picture closes it + if cur and (code ~= 0xB7) then + cur.size = p - cur.offset + table.insert(out, cur) + cur = nil + end + if code == 0xB3 then + unitStart = unitStart or p + seq = true + elseif code == 0xB8 then + unitStart = unitStart or p + gop = true + elseif code == 0x00 then + local t, tr = 0, 0 + if p + 5 < limit then + local x = readu8(b, p + 4) * 256 + readu8(b, p + 5) + t, tr = (x // 8) % 8, x // 64 + end + cur = { offset = unitStart or p, size = 0, type = t, temporal = tr, gop = gop, sequence = seq, structure = st } :: Picture + unitStart, seq, gop = nil, false, false + elseif code == 0xB7 and cur then + cur.size = p + 4 - cur.offset + table.insert(out, cur) + cur = nil + end + end + p = MpegEs.findStart(b, p + 4, limit) + end + if cur then + cur.size = limit - cur.offset + table.insert(out, cur) + end + return out +end + +function MpegEs.h264Key(b: buffer, off: number, limit: number): boolean + local p = MpegEs.findStart(b, off, limit) + local count = 0 + while p and count < 64 do + count += 1 + if p + 3 < limit then + local t = readu8(b, p + 3) % 32 + if t == 5 then + return true + elseif t == 1 then + return false + end + end + p = MpegEs.findStart(b, p + 3, limit) + end + return false +end + +return MpegEs +end +__FILES["containers/MpegPs"] = function() + +-- containers/MpegPs: the MPEG program stream (ISO/IEC 11172-1 system streams and ISO/IEC 13818-1 program streams: +-- .mpg / .mpeg / .vob). New in rosetta. Pack headers (MPEG-1 and MPEG-2 layouts), system headers, the program +-- stream map (stream types), padding, and PES packets of the video (0xE0..0xEF), audio (0xC0..0xDF) and private +-- stream 1 (0xBD: AC-3 / DTS / LPCM / subpicture sub-streams) ids with their PTS / DTS (both PES header layouts, +-- 33-bit timestamps unwrapped). Data between packs that is not a start code is skipped (resync). +-- Never throws: malformed packets are skipped (ps.errors). Private stream 1 sub-streams are keyed 0xBD00 + their id. +local Err = __include("core/Err") +local MpegEs = __include("containers/MpegEs") + +local readu8 = buffer.readu8 + +local MpegPs = {} + +type Pes = { pts: number?, dts: number?, offset: number, size: number } +type Stream = { id: number, kind: string, codec: string, streamType: number?, pes: { Pes } } +type File = { streams: { [number]: Stream }, order: { number }, mpeg2: boolean, errors: number } + +local WRAP = 8589934592 -- 2^33 + +-- PSM stream_type -> kind, codec +local TYPES: { [number]: { string } } = { + [0x01] = { "video", "mpeg1" }, + [0x02] = { "video", "mpeg2" }, + [0x03] = { "audio", "mp2" }, + [0x04] = { "audio", "mp2" }, + [0x0F] = { "audio", "aac" }, + [0x10] = { "video", "mpeg4" }, + [0x1B] = { "video", "h264" }, + [0x24] = { "video", "hevc" }, + [0x81] = { "audio", "ac3" }, +} + +local function ts(b: buffer, p: number): number + local a = readu8(b, p) + local v = (a // 2) % 8 + v = v * 32768 + (readu8(b, p + 1) * 256 + readu8(b, p + 2)) // 2 + v = v * 32768 + (readu8(b, p + 3) * 256 + readu8(b, p + 4)) // 2 + return v +end + +function MpegPs.read(b: buffer, base: number, limit: number): (File?, Err.Err?) + local file: File = { streams = {}, order = {}, mpeg2 = false, errors = 0 } + local types: { [number]: number } = {} + local last: { [number]: number } = {} + local wrap: { [number]: number } = {} + local packs = 0 + local p = MpegEs.findStart(b, base, limit) + local function unwrap(id: number, v: number): number + local off = wrap[id] or 0 + local prev = last[id] + local t = v + off + if prev and t < prev - WRAP / 2 then + off += WRAP + wrap[id] = off + t = v + off + end + last[id] = t + return t + end + while p do + if p + 4 > limit then + break + end + local code = readu8(b, p + 3) + local nextP = p + 4 + if code == 0xBA then + packs += 1 + if p + 5 > limit then + break + end + local m = readu8(b, p + 4) + if m // 64 == 1 then -- MPEG-2 pack: 14 bytes + stuffing + file.mpeg2 = true + if p + 14 > limit then + break + end + nextP = p + 14 + readu8(b, p + 13) % 8 + else + nextP = p + 12 + end + elseif code == 0xB9 then + nextP = p + 4 + elseif code >= 0xBB then + if p + 6 > limit then + break + end + local len = readu8(b, p + 4) * 256 + readu8(b, p + 5) + local stop = p + 6 + len + if stop > limit then + stop = limit + end + nextP = stop + if code == 0xBC and len >= 10 then -- program stream map + local infoLen = readu8(b, p + 8) * 256 + readu8(b, p + 9) + local q = p + 10 + infoLen + if q + 2 <= stop then + local mapLen = readu8(b, q) * 256 + readu8(b, q + 1) + q += 2 + local e = math.min(stop, q + mapLen) + while q + 4 <= e do + local st, sid = readu8(b, q), readu8(b, q + 1) + local il = readu8(b, q + 2) * 256 + readu8(b, q + 3) + types[sid] = st + q += 4 + il + end + end + elseif code == 0xBD or (code >= 0xC0 and code <= 0xEF) then + -- a PES packet + local q = p + 6 + local pts, dts: number? = nil, nil + local ok = true + if q < stop and readu8(b, q) // 64 == 2 then -- MPEG-2 PES header + if q + 3 > stop then + ok = false + else + local flags = readu8(b, q + 1) + local hlen = readu8(b, q + 2) + local h = q + 3 + if flags >= 0x80 and h + 5 <= stop then + pts = ts(b, h) + if flags // 64 == 3 and h + 10 <= stop then + dts = ts(b, h + 5) + end + end + q = h + hlen + end + else -- MPEG-1 packet header + local n = 0 + while q < stop and readu8(b, q) == 0xFF and n < 16 do + q += 1 + n += 1 + end + if q < stop and readu8(b, q) // 64 == 1 then + q += 2 + end + if q < stop then + local c = readu8(b, q) // 16 + if c == 2 and q + 5 <= stop then + pts = ts(b, q) + q += 5 + elseif c == 3 and q + 10 <= stop then + pts = ts(b, q) + dts = ts(b, q + 5) + q += 10 + elseif readu8(b, q) == 0x0F then + q += 1 + else + ok = false + end + end + end + if ok and q <= stop then + local id = code + local kind, codec = "other", "unknown" + if code == 0xBD then + if q >= stop then + ok = false + else + local sub = readu8(b, q) + id = 0xBD00 + sub + if sub >= 0x80 and sub <= 0x87 then + kind, codec = "audio", "ac3" + q += 4 + elseif sub >= 0x88 and sub <= 0x8F then + kind, codec = "audio", "dts" + q += 4 + elseif sub >= 0xA0 and sub <= 0xA7 then + kind, codec = "audio", "pcm_dvd" + q += 7 + elseif sub >= 0x20 and sub <= 0x3F then + kind, codec = "subtitle", "dvdsub" + q += 1 + else + q += 1 + end + end + elseif code >= 0xE0 then + kind, codec = "video", "mpeg1" + else + kind, codec = "audio", "mp2" + end + local st = types[code] + if st and TYPES[st] then + kind, codec = TYPES[st][1], TYPES[st][2] + end + if ok and q <= stop then + local s = file.streams[id] + if not s then + s = { id = id, kind = kind, codec = codec, streamType = st, pes = {} } :: Stream + file.streams[id] = s + table.insert(file.order, id) + end + table.insert(s.pes, { + pts = if pts then unwrap(id, pts) else nil, + dts = if dts then unwrap(id + 0x10000, dts) else nil, + offset = q, + size = stop - q, + }) + end + end + if not ok then + file.errors += 1 + end + end + else + -- a start code that is not a system one (stray ES data between packets): resync + file.errors += 1 + end + p = MpegEs.findStart(b, nextP, limit) + end + if packs == 0 and #file.order == 0 then + return nil, Err.new(Err.CORRUPT, "no MPEG pack or PES packet", base) + end + return file, nil +end + +return MpegPs +end +__FILES["containers/MpegTs"] = @native function() + + +-- containers/MpegTs: an MPEG transport stream demuxer (ISO/IEC 13818-1). Absorbed from mpegts-luau 6e16197 (same +-- author; no third-party code); changed: the unit queue keeps an explicit tail (#q on a table with holes at its front +-- loses units under LuaJIT's border rule). Never throws: bad input is skipped and counted in `stats`. +local Crc32 = __include("core/Crc32") + +local MpegTs = {} + +type Stream = { + pid: number, + streamType: number, -- PMT stream_type (0 when the stream was found without a PMT) + kind: string, -- "video" | "audio" | "other" + codec: string, -- "mpeg1video" | "mpeg2video" | "mpegaudio" | "aac" | "h264" | "hevc" | "ac3" | "unknown" ... + program: number, -- program_number (0 without a PMT) + language: string?, -- ISO 639 language descriptor, when present +} + +type Unit = { + pid: number, + kind: string, + codec: string, + streamType: number, + streamId: number, -- PES stream_id (0xE0.. video, 0xC0.. audio) + pts: number?, -- seconds (33-bit 90 kHz clock, unwrapped per PID) + dts: number?, -- seconds; equals pts when the PES carries no DTS + pts90: number?, -- the same in 90 kHz ticks + dts90: number?, + data: buffer, -- the PES payload (one access unit for video as muxed by ffmpeg; one or more frames for audio) + ccError: boolean, -- a continuity counter gap (lost packets) happened inside this unit + randomAccess: boolean, -- the first packet's adaptation field had random_access_indicator set + discontinuity: boolean, -- the first packet's adaptation field had discontinuity_indicator set +} + +type Stats = { + packets: number, + syncLosses: number, -- resyncs (bytes skipped to find 0x47 again) + skippedBytes: number, + teiErrors: number, -- transport_error_indicator packets (dropped) + ccErrors: number, -- continuity counter gaps + duplicates: number, -- duplicate packets (same CC), dropped + crcErrors: number, -- PSI sections with a bad CRC (ignored) + pesErrors: number, -- PES units without a valid header (dropped) + scrambled: number, -- scrambled packets (dropped) + pcr: number?, -- last PCR seen, seconds +} + +type Demuxed = { + video: { Unit }, -- units of the selected video PID (first video stream of the PMT), in stream order + audio: { Unit }, -- units of the selected audio PID + streams: { Stream }, -- every elementary stream, PMT order + units: { Unit }, -- every unit of every PID, in completion order + videoPid: number?, + audioPid: number?, + stats: Stats, +} + +type PesState = { + buf: buffer, + len: number, + active: boolean, + expected: number, -- total PES bytes when PES_packet_length is set, else 0 (ends at the next unit start) + hdrChecked: boolean, + ccError: boolean, + randomAccess: boolean, + discontinuity: boolean, + lastPts: number, -- for 33-bit wrap unwrapping + wrapOffset: number, +} + +type SectionState = { buf: buffer, len: number, active: boolean } + +local TS_SIZE = 188 +local SYNC = 0x47 +local MAX_SECTION = 4096 + 188 +local WRAP = 8589934592 -- 2^33 + +local readu8 = buffer.readu8 +local band = bit32.band +local bor = bit32.bor +local lshift = bit32.lshift +local rshift = bit32.rshift + +local CODECS: { [number]: { string } } = { + [0x01] = { "video", "mpeg1video" }, + [0x02] = { "video", "mpeg2video" }, + [0x03] = { "audio", "mpegaudio" }, + [0x04] = { "audio", "mpegaudio" }, + [0x0F] = { "audio", "aac" }, + [0x10] = { "video", "mpeg4" }, + [0x11] = { "audio", "aac_latm" }, + [0x1B] = { "video", "h264" }, + [0x24] = { "video", "hevc" }, + [0x81] = { "audio", "ac3" }, + [0x87] = { "audio", "eac3" }, +} + +-- CRC-32/MPEG-2 (poly 0x04C11DB7, init 0xFFFFFFFF, MSB first, no final xor): a section including its CRC sums to 0 +@native local function crc32(b: buffer, off: number, n: number): number + return Crc32.msb(b, off, n, 0xFFFFFFFF) +end +MpegTs.crc32 = crc32 + +@native local function u16(b: buffer, p: number): number + return readu8(b, p) * 256 + readu8(b, p + 1) +end + +-- 33-bit timestamp from the 5-byte PES encoding at p +@native local function readTs(b: buffer, p: number): number + local b0 = readu8(b, p) + local hi = band(rshift(b0, 1), 7) * 1073741824 -- bits 32..30 + local mid = bor(lshift(readu8(b, p + 1), 7), rshift(readu8(b, p + 2), 1)) -- bits 29..15 + local lo = bor(lshift(readu8(b, p + 3), 7), rshift(readu8(b, p + 4), 1)) -- bits 14..0 + return hi + mid * 32768 + lo +end + +local Demuxer = {} +Demuxer.__index = Demuxer + +type Demuxer = typeof(setmetatable( + {} :: { + _pend: buffer, + _pendLen: number, + _pmtPids: { [number]: number }, + _streams: { [number]: Stream }, + _pes: { [number]: PesState }, + _sections: { [number]: SectionState }, + _cc: { [number]: number }, + _queue: { Unit }, + _qhead: number, + _qtail: number, + streams: { Stream }, + stats: Stats, + }, + Demuxer +)) + +@native function MpegTs.new(): Demuxer + local self = setmetatable({ + _pend = buffer.create(64 * 1024), + _pendLen = 0, + _pmtPids = {}, + _streams = {}, + _pes = {}, + _sections = {}, + _cc = {}, + _queue = {}, + _qhead = 1, + _qtail = 0, + streams = {}, + stats = { + packets = 0, + syncLosses = 0, + skippedBytes = 0, + teiErrors = 0, + ccErrors = 0, + duplicates = 0, + crcErrors = 0, + pesErrors = 0, + scrambled = 0, + pcr = nil, + } :: Stats, + }, Demuxer) + return self +end + + +@native local function addStream(self: Demuxer, pid: number, streamType: number, program: number, language: string?) + local info = CODECS[streamType] + local s = self._streams[pid] + if s == nil then + s = { + pid = pid, + streamType = streamType, + kind = if info then info[1] else "other", + codec = if info then info[2] else "unknown", + program = program, + language = language, + } + self._streams[pid] = s + table.insert(self.streams, s) + else + s.streamType = streamType + s.kind = if info then info[1] else "other" + s.codec = if info then info[2] else "unknown" + s.program = program + s.language = language + end +end + +@native local function parseSection(self: Demuxer, pid: number, b: buffer, n: number) + -- n >= 3 bytes: table_id, section_length (n = 3 + section_length) + if n < 12 then + return + end + if band(readu8(b, 1), 0x80) == 0 then + return -- no section_syntax_indicator: not a PAT / PMT + end + if crc32(b, 0, n) ~= 0 then + self.stats.crcErrors += 1 + return + end + if band(readu8(b, 5), 1) == 0 then + return -- current_next_indicator = 0: a future table + end + local tid = readu8(b, 0) + local stop = n - 4 + if tid == 0x00 and pid == 0 then + local p = 8 + while p + 4 <= stop do + local prog = u16(b, p) + local pmt = band(u16(b, p + 2), 0x1FFF) + if prog ~= 0 then + self._pmtPids[pmt] = prog + end + p += 4 + end + elseif tid == 0x02 and self._pmtPids[pid] ~= nil then + local program = u16(b, 3) + local p = 12 + band(u16(b, 10), 0x0FFF) + while p + 5 <= stop do + local st = readu8(b, p) + local epid = band(u16(b, p + 1), 0x1FFF) + local esl = band(u16(b, p + 3), 0x0FFF) + local d = p + 5 + local dend = math.min(d + esl, stop) + local language: string? = nil + while d + 2 <= dend do + local tag, len = readu8(b, d), readu8(b, d + 1) + if tag == 0x0A and len >= 3 and d + 5 <= dend then + language = buffer.readstring(b, d + 2, 3) + end + d += 2 + len + end + addStream(self, epid, st, program, language) + p += 5 + esl + end + end +end + +@native local function sectionBytes(self: Demuxer, pid: number, s: SectionState, src: buffer, from: number, to: number) + local n = to - from + if n <= 0 then + return + end + if s.len + n > MAX_SECTION then + s.active = false + s.len = 0 + return + end + buffer.copy(s.buf, s.len, src, from, n) + s.len += n + while s.active and s.len >= 3 do + if readu8(s.buf, 0) == 0xFF then + s.active = false -- stuffing: no more sections until the next unit start + s.len = 0 + return + end + local need = 3 + band(u16(s.buf, 1), 0x0FFF) + if s.len < need then + return + end + parseSection(self, pid, s.buf, need) + local rest = s.len - need + if rest > 0 then + buffer.copy(s.buf, 0, s.buf, need, rest) + end + s.len = rest + end +end + +@native local function sectionPayload(self: Demuxer, pid: number, pusi: boolean, b: buffer, pos: number, stop: number) + local s = self._sections[pid] + if s == nil then + s = { buf = buffer.create(MAX_SECTION), len = 0, active = false } + self._sections[pid] = s + end + if pusi then + if pos >= stop then + return + end + local ptr = readu8(b, pos) + pos += 1 + local tail = math.min(pos + ptr, stop) + if s.active then + sectionBytes(self, pid, s, b, pos, tail) -- the end of the previous section + end + s.active = true + s.len = 0 + pos = tail + elseif not s.active then + return + end + sectionBytes(self, pid, s, b, pos, stop) +end + + +@native local function completePes(self: Demuxer, pid: number, st: PesState) + st.active = false + local b, len = st.buf, st.len + if len < 6 or readu8(b, 0) ~= 0 or readu8(b, 1) ~= 0 or readu8(b, 2) ~= 1 then + self.stats.pesErrors += 1 + return + end + local sid = readu8(b, 3) + local stop = if st.expected > 0 then math.min(st.expected, len) else len + local start = 6 + local pts: number?, dts: number? = nil, nil + if not (sid == 0xBC or sid == 0xBE or sid == 0xBF or sid == 0xF0 or sid == 0xF1 or sid == 0xF2 or sid == 0xF8 or sid == 0xFF) then + if stop < 9 then + self.stats.pesErrors += 1 + return + end + if band(readu8(b, 6), 0xC0) == 0x80 then + -- MPEG-2 PES header + local flags = readu8(b, 7) + local hl = readu8(b, 8) + start = 9 + hl + if band(flags, 0x80) ~= 0 and hl >= 5 and 14 <= stop then + pts = readTs(b, 9) + if band(flags, 0x40) ~= 0 and hl >= 10 and 19 <= stop then + dts = readTs(b, 14) + end + end + else + -- MPEG-1 (ISO 11172-1) packet header: stuffing, STD buffer, PTS / DTS + local p = 6 + local k = 0 + while p < stop and readu8(b, p) == 0xFF and k < 16 do + p += 1 + k += 1 + end + if p < stop and band(readu8(b, p), 0xC0) == 0x40 then + p += 2 + end + if p < stop then + local c = band(readu8(b, p), 0xF0) + if c == 0x20 and p + 5 <= stop then + pts = readTs(b, p) + p += 5 + elseif c == 0x30 and p + 10 <= stop then + pts = readTs(b, p) + dts = readTs(b, p + 5) + p += 10 + else + p += 1 + end + end + start = p + end + end + if start > stop then + self.stats.pesErrors += 1 + return + end + -- unwrap the 33-bit clock (per PID) + if pts ~= nil then + pts += st.wrapOffset + if st.lastPts >= 0 then + if pts < st.lastPts - WRAP / 2 then + st.wrapOffset += WRAP + pts += WRAP + elseif pts > st.lastPts + WRAP / 2 and st.wrapOffset >= WRAP then + st.wrapOffset -= WRAP + pts -= WRAP + end + end + st.lastPts = pts + if dts ~= nil then + dts += st.wrapOffset + if dts > pts + WRAP / 2 then + dts -= WRAP + elseif dts < pts - WRAP / 2 then + dts += WRAP + end + else + dts = pts + end + end + local n = stop - start + local data = buffer.create(n) + if n > 0 then + buffer.copy(data, 0, b, start, n) + end + local s = self._streams[pid] + local kind, codec, streamType + if s then + kind, codec, streamType = s.kind, s.codec, s.streamType + elseif sid >= 0xE0 and sid <= 0xEF then + kind, codec, streamType = "video", "unknown", 0 + elseif sid >= 0xC0 and sid <= 0xDF then + kind, codec, streamType = "audio", "mpegaudio", 0 + else + kind, codec, streamType = "other", "unknown", 0 + end + local unit: Unit = { + pid = pid, + kind = kind, + codec = codec, + streamType = streamType, + streamId = sid, + pts = if pts then pts / 90000 else nil, + dts = if dts then dts / 90000 else nil, + pts90 = pts, + dts90 = dts, + data = data, + ccError = st.ccError, + randomAccess = st.randomAccess, + discontinuity = st.discontinuity, + } + local tail = self._qtail + 1 + self._qtail = tail + self._queue[tail] = unit +end + +@native local function pesPayload( + self: Demuxer, + pid: number, + pusi: boolean, + b: buffer, + pos: number, + stop: number, + ccError: boolean, + randomAccess: boolean, + discontinuity: boolean +) + local st = self._pes[pid] + -- a unit starts with a PES start code; anything else on a PID outside the PMT (SDT, EIT ...) is ignored + local startCode = pusi + and stop - pos >= 3 + and readu8(b, pos) == 0 + and readu8(b, pos + 1) == 0 + and readu8(b, pos + 2) == 1 + if st == nil then + if not startCode then + return + end + st = { + buf = buffer.create(16 * 1024), + len = 0, + active = false, + expected = 0, + hdrChecked = false, + ccError = false, + randomAccess = false, + discontinuity = false, + lastPts = -1, + wrapOffset = 0, + } + self._pes[pid] = st + end + if ccError and st.active then + st.ccError = true -- packets of the unit in progress were lost + end + if pusi then + if st.active then + completePes(self, pid, st) + end + if not startCode then + if self._streams[pid] ~= nil then + self.stats.pesErrors += 1 + end + return + end + st.active = true + st.len = 0 + st.expected = 0 + st.hdrChecked = false + st.ccError = false + st.randomAccess = randomAccess + st.discontinuity = discontinuity + elseif not st.active then + return + end + local n = stop - pos + if n <= 0 then + return + end + if st.len + n > buffer.len(st.buf) then + local cap = buffer.len(st.buf) * 2 + while cap < st.len + n do + cap *= 2 + end + if cap > 64 * 1024 * 1024 then + st.active = false -- runaway unit (no unit start for 64 MB): drop it + st.len = 0 + self.stats.pesErrors += 1 + return + end + local nb = buffer.create(cap) + buffer.copy(nb, 0, st.buf, 0, st.len) + st.buf = nb + end + buffer.copy(st.buf, st.len, b, pos, n) + st.len += n + if not st.hdrChecked and st.len >= 6 then + st.hdrChecked = true + local plen = u16(st.buf, 4) + if plen > 0 then + st.expected = 6 + plen + end + end + if st.expected > 0 and st.len >= st.expected then + completePes(self, pid, st) + end +end + + +@native local function packet(self: Demuxer, b: buffer, pk: number) + local stats = self.stats + stats.packets += 1 + local b1 = readu8(b, pk + 1) + if band(b1, 0x80) ~= 0 then + stats.teiErrors += 1 + return + end + local pusi = band(b1, 0x40) ~= 0 + local pid = band(b1, 0x1F) * 256 + readu8(b, pk + 2) + if pid == 0x1FFF then + return + end + local b3 = readu8(b, pk + 3) + if band(b3, 0xC0) ~= 0 then + stats.scrambled += 1 + return + end + local afc = band(rshift(b3, 4), 3) + local cc = band(b3, 15) + if afc == 0 then + return + end + local pos = pk + 4 + local stop = pk + TS_SIZE + local discontinuity, randomAccess = false, false + if afc >= 2 then + local afl = readu8(b, pos) + pos += 1 + if afl > 183 then + return + end + if afl > 0 then + local flags = readu8(b, pos) + discontinuity = band(flags, 0x80) ~= 0 + randomAccess = band(flags, 0x40) ~= 0 + if band(flags, 0x10) ~= 0 and afl >= 7 then + local base = readu8(b, pos + 1) * 33554432 + + readu8(b, pos + 2) * 131072 + + readu8(b, pos + 3) * 512 + + readu8(b, pos + 4) * 2 + + rshift(readu8(b, pos + 5), 7) + local ext = band(readu8(b, pos + 5), 1) * 256 + readu8(b, pos + 6) + stats.pcr = base / 90000 + ext / 27000000 + end + end + pos += afl + if afc == 2 then + if discontinuity then + self._cc[pid] = nil + end + return -- adaptation field only: the counter does not advance + end + end + local ccError = false + local last = self._cc[pid] + if last ~= nil and not discontinuity then + if cc == last then + stats.duplicates += 1 + return + elseif cc ~= band(last + 1, 15) then + ccError = true + stats.ccErrors += 1 + end + end + self._cc[pid] = cc + if pid == 0 or self._pmtPids[pid] ~= nil then + sectionPayload(self, pid, pusi, b, pos, stop) + elseif pid >= 0x10 then + pesPayload(self, pid, pusi, b, pos, stop, ccError, randomAccess, discontinuity) + end +end + +@native function Demuxer.push(self: Demuxer, data: buffer | string, offset: number?, len: number?): boolean + local src: buffer + if type(data) == "string" then + src = buffer.fromstring(data) + elseif type(data) == "buffer" then + src = data + else + return false + end + local off = math.max(0, math.floor(offset or 0)) + local total = buffer.len(src) + if off > total then + return false + end + local n = math.min(math.floor(len or (total - off)), total - off) + if n < 0 then + return false + end + local need = self._pendLen + n + if need > buffer.len(self._pend) then + local cap = buffer.len(self._pend) + while cap < need do + cap *= 2 + end + local nb = buffer.create(cap) + buffer.copy(nb, 0, self._pend, 0, self._pendLen) + self._pend = nb + end + if n > 0 then + buffer.copy(self._pend, self._pendLen, src, off, n) + end + self._pendLen = need + local b, avail = self._pend, self._pendLen + local p = 0 + while p + TS_SIZE <= avail do + if readu8(b, p) ~= SYNC then + -- resync: the next 0x47 that is followed by another one 188 bytes later (or by the end of the data) + self.stats.syncLosses += 1 + local q = p + 1 + local found = -1 + local waitAt = -1 + while q < avail do + if readu8(b, q) == SYNC then + if q + TS_SIZE < avail then + if readu8(b, q + TS_SIZE) == SYNC then + found = q + break + end + elseif q + TS_SIZE == avail then + found = q + break + else + waitAt = q -- not enough bytes to confirm: wait for more + break + end + end + q += 1 + end + if found >= 0 then + self.stats.skippedBytes += found - p + p = found + elseif waitAt >= 0 then + self.stats.skippedBytes += waitAt - p + p = waitAt + break + else + self.stats.skippedBytes += avail - p + p = avail + break + end + else + packet(self, b, p) + p += TS_SIZE + end + end + local rest = avail - p + if rest > 0 and p > 0 then + buffer.copy(b, 0, b, p, rest) + end + self._pendLen = rest + return true +end + +@native function Demuxer.pull(self: Demuxer): Unit? + local q = self._queue + local h = self._qhead + local u = q[h] + if u == nil then + return nil + end + q[h] = nil :: any + h += 1 + if h > self._qtail then + table.clear(q) + h = 1 + self._qtail = 0 + end + self._qhead = h + return u +end + +@native function Demuxer.flush(self: Demuxer) + local pids = {} + for pid, st in self._pes do + if st.active then + table.insert(pids, pid) + end + end + table.sort(pids) + for _, pid in pids do + completePes(self, pid, self._pes[pid]) + end + self._pendLen = 0 +end + +@native function Demuxer.reset(self: Demuxer) + self._pendLen = 0 + for _, st in self._pes do + st.active = false + st.len = 0 + st.lastPts = -1 + st.wrapOffset = 0 + end + for _, s in self._sections do + s.active = false + s.len = 0 + end + table.clear(self._cc) + table.clear(self._queue) + self._qhead = 1 + self._qtail = 0 +end + +@native function Demuxer.streamFor(self: Demuxer, kind: string): Stream? + for _, s in self.streams do + if s.kind == kind then + return s + end + end + return nil +end + +type DemuxOptions = { videoPid: number?, audioPid: number? } + +@native function MpegTs.demux(data: buffer | string, opts: DemuxOptions?): Demuxed + local d = MpegTs.new() + d:push(data) + d:flush() + local units = {} + while true do + local u = d:pull() + if u == nil then + break + end + table.insert(units, u) + end + local videoPid = opts and opts.videoPid + local audioPid = opts and opts.audioPid + if videoPid == nil then + local s = d:streamFor("video") + videoPid = if s then s.pid else nil + end + if audioPid == nil then + local s = d:streamFor("audio") + audioPid = if s then s.pid else nil + end + for _, u in units do + if videoPid == nil and u.kind == "video" then + videoPid = u.pid + end + if audioPid == nil and u.kind == "audio" then + audioPid = u.pid + end + end + local video, audio = {}, {} + for _, u in units do + if u.pid == videoPid then + table.insert(video, u) + elseif u.pid == audioPid then + table.insert(audio, u) + end + end + return { + video = video, + audio = audio, + streams = d.streams, + units = units, + videoPid = videoPid, + audioPid = audioPid, + stats = d.stats, + } +end + +@native function MpegTs.concat(units: { Unit }): buffer + local n = 0 + for _, u in units do + n += buffer.len(u.data) + end + local out = buffer.create(n) + local p = 0 + for _, u in units do + local l = buffer.len(u.data) + buffer.copy(out, p, u.data, 0, l) + p += l + end + return out +end + +return MpegTs +end +end + + + + + + Dct + --!optimize 2 +--!nocheck +-- rosetta chunk Dct (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 1 modules (1 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["codecs/image/Dct"] = @native function() + + + +-- codecs/image/Dct: the 8x8 DCTs JPEG, Motion-JPEG and MPEG-1 share (native; never throws). +-- libjpeg's islow (jidctint.c / jfdctint.c), the reduced IDCTs (jidctred.c) and jcdctmgr.c's rounding quantiser, bit-exact +-- with libjpeg-turbo. From jpeg-luau 1.0 (same author); IJG code: licenses/libjpeg-turbo-LICENSE.md. +local readi16, readu16, writeu16, readu8, writei16 = buffer.readi16, buffer.readu16, buffer.writeu16, buffer.readu8, buffer.writei16 +local clamp = math.clamp + +local Dct = {} + +local ws = table.create(64, 0) + +@native local function idct8(coef: buffer, off: number, q: buffer, plane: buffer, out: number, stride: number, p1: number, center: number, maxv: number) + local s1 = 2 ^ (13 - p1) + local h1 = s1 / 2 + local s2 = 2 ^ (16 + p1) + local h2 = s2 / 2 + center * s2 + local dcm = 2 ^ p1 + for c = 0, 7 do + local o = off + c * 2 + local qo = c * 2 + local c1, c2, c3 = readi16(coef, o + 16), readi16(coef, o + 32), readi16(coef, o + 48) + local c4, c5, c6, c7 = readi16(coef, o + 64), readi16(coef, o + 80), readi16(coef, o + 96), readi16(coef, o + 112) + if c1 == 0 and c2 == 0 and c3 == 0 and c4 == 0 and c5 == 0 and c6 == 0 and c7 == 0 then + local dc = readi16(coef, o) * readu16(q, qo) * dcm + ws[c + 1] = dc + ws[c + 9] = dc + ws[c + 17] = dc + ws[c + 25] = dc + ws[c + 33] = dc + ws[c + 41] = dc + ws[c + 49] = dc + ws[c + 57] = dc + else + -- even part + local z2 = c2 * readu16(q, qo + 32) + local z3 = c6 * readu16(q, qo + 96) + local z1 = (z2 + z3) * 4433 + local tmp2 = z1 - z3 * 15137 + local tmp3 = z1 + z2 * 6270 + z2 = readi16(coef, o) * readu16(q, qo) + z3 = c4 * readu16(q, qo + 64) + local tmp0 = (z2 + z3) * 8192 + local tmp1 = (z2 - z3) * 8192 + local tmp10, tmp13 = tmp0 + tmp3, tmp0 - tmp3 + local tmp11, tmp12 = tmp1 + tmp2, tmp1 - tmp2 + -- odd part + local t0 = c7 * readu16(q, qo + 112) + local t1 = c5 * readu16(q, qo + 80) + local t2 = c3 * readu16(q, qo + 48) + local t3 = c1 * readu16(q, qo + 16) + z1 = t0 + t3 + z2 = t1 + t2 + z3 = t0 + t2 + local z4 = t1 + t3 + local z5 = (z3 + z4) * 9633 + t0 *= 2446 + t1 *= 16819 + t2 *= 25172 + t3 *= 12299 + z1 *= -7373 + z2 *= -20995 + z3 = z3 * -16069 + z5 + z4 = z4 * -3196 + z5 + t0 += z1 + z3 + t1 += z2 + z4 + t2 += z2 + z3 + t3 += z1 + z4 + ws[c + 1] = (tmp10 + t3 + h1) // s1 + ws[c + 57] = (tmp10 - t3 + h1) // s1 + ws[c + 9] = (tmp11 + t2 + h1) // s1 + ws[c + 49] = (tmp11 - t2 + h1) // s1 + ws[c + 17] = (tmp12 + t1 + h1) // s1 + ws[c + 41] = (tmp12 - t1 + h1) // s1 + ws[c + 25] = (tmp13 + t0 + h1) // s1 + ws[c + 33] = (tmp13 - t0 + h1) // s1 + end + end + local sd = 2 ^ (p1 + 3) + local hd = sd / 2 + center * sd + for r = 0, 7 do + local b = r * 8 + local w0, w1, w2, w3 = ws[b + 1], ws[b + 2], ws[b + 3], ws[b + 4] + local w4, w5, w6, w7 = ws[b + 5], ws[b + 6], ws[b + 7], ws[b + 8] + local o = (out + r * stride) * 2 + if w1 == 0 and w2 == 0 and w3 == 0 and w4 == 0 and w5 == 0 and w6 == 0 and w7 == 0 then + local v = clamp((w0 + hd) // sd, 0, maxv) + for i = 0, 14, 2 do + writeu16(plane, o + i, v) + end + else + local z1 = (w2 + w6) * 4433 + local tmp2 = z1 - w6 * 15137 + local tmp3 = z1 + w2 * 6270 + local tmp0 = (w0 + w4) * 8192 + local tmp1 = (w0 - w4) * 8192 + local tmp10, tmp13 = tmp0 + tmp3, tmp0 - tmp3 + local tmp11, tmp12 = tmp1 + tmp2, tmp1 - tmp2 + local t0, t1, t2, t3 = w7, w5, w3, w1 + z1 = t0 + t3 + local z2 = t1 + t2 + local z3 = t0 + t2 + local z4 = t1 + t3 + local z5 = (z3 + z4) * 9633 + t0 *= 2446 + t1 *= 16819 + t2 *= 25172 + t3 *= 12299 + z1 *= -7373 + z2 *= -20995 + z3 = z3 * -16069 + z5 + z4 = z4 * -3196 + z5 + t0 += z1 + z3 + t1 += z2 + z4 + t2 += z2 + z3 + t3 += z1 + z4 + writeu16(plane, o, clamp((tmp10 + t3 + h2) // s2, 0, maxv)) + writeu16(plane, o + 14, clamp((tmp10 - t3 + h2) // s2, 0, maxv)) + writeu16(plane, o + 2, clamp((tmp11 + t2 + h2) // s2, 0, maxv)) + writeu16(plane, o + 12, clamp((tmp11 - t2 + h2) // s2, 0, maxv)) + writeu16(plane, o + 4, clamp((tmp12 + t1 + h2) // s2, 0, maxv)) + writeu16(plane, o + 10, clamp((tmp12 - t1 + h2) // s2, 0, maxv)) + writeu16(plane, o + 6, clamp((tmp13 + t0 + h2) // s2, 0, maxv)) + writeu16(plane, o + 8, clamp((tmp13 - t0 + h2) // s2, 0, maxv)) + end + end +end + +@native local function idct4(coef: buffer, off: number, q: buffer, plane: buffer, out: number, stride: number, p1: number, center: number, maxv: number) + local s1 = 2 ^ (14 - p1) + local h1 = s1 / 2 + local dcm = 2 ^ p1 + for c = 0, 7 do + if c ~= 4 then + local o = off + c * 2 + local qo = c * 2 + local c1, c2, c3 = readi16(coef, o + 16), readi16(coef, o + 32), readi16(coef, o + 48) + local c5, c6, c7 = readi16(coef, o + 80), readi16(coef, o + 96), readi16(coef, o + 112) + if c1 == 0 and c2 == 0 and c3 == 0 and c5 == 0 and c6 == 0 and c7 == 0 then + local dc = readi16(coef, o) * readu16(q, qo) * dcm + ws[c + 1] = dc + ws[c + 9] = dc + ws[c + 17] = dc + ws[c + 25] = dc + else + local tmp0 = readi16(coef, o) * readu16(q, qo) * 16384 + local tmp2 = c2 * readu16(q, qo + 32) * 15137 - c6 * readu16(q, qo + 96) * 6270 + local tmp10, tmp12 = tmp0 + tmp2, tmp0 - tmp2 + local z1 = c7 * readu16(q, qo + 112) + local z2 = c5 * readu16(q, qo + 80) + local z3 = c3 * readu16(q, qo + 48) + local z4 = c1 * readu16(q, qo + 16) + tmp0 = z1 * -1730 + z2 * 11893 + z3 * -17799 + z4 * 8697 + tmp2 = z1 * -4176 + z2 * -4926 + z3 * 7373 + z4 * 20995 + ws[c + 1] = (tmp10 + tmp2 + h1) // s1 + ws[c + 25] = (tmp10 - tmp2 + h1) // s1 + ws[c + 9] = (tmp12 + tmp0 + h1) // s1 + ws[c + 17] = (tmp12 - tmp0 + h1) // s1 + end + end + end + local s2 = 2 ^ (17 + p1) + local h2 = s2 / 2 + center * s2 + local sd = 2 ^ (p1 + 3) + local hd = sd / 2 + center * sd + for r = 0, 3 do + local b = r * 8 + local w0, w1, w2, w3 = ws[b + 1], ws[b + 2], ws[b + 3], ws[b + 4] + local w5, w6, w7 = ws[b + 6], ws[b + 7], ws[b + 8] + local o = (out + r * stride) * 2 + if w1 == 0 and w2 == 0 and w3 == 0 and w5 == 0 and w6 == 0 and w7 == 0 then + local v = clamp((w0 + hd) // sd, 0, maxv) + writeu16(plane, o, v) + writeu16(plane, o + 2, v) + writeu16(plane, o + 4, v) + writeu16(plane, o + 6, v) + else + local tmp0 = w0 * 16384 + local tmp2 = w2 * 15137 - w6 * 6270 + local tmp10, tmp12 = tmp0 + tmp2, tmp0 - tmp2 + tmp0 = w7 * -1730 + w5 * 11893 + w3 * -17799 + w1 * 8697 + tmp2 = w7 * -4176 + w5 * -4926 + w3 * 7373 + w1 * 20995 + writeu16(plane, o, clamp((tmp10 + tmp2 + h2) // s2, 0, maxv)) + writeu16(plane, o + 6, clamp((tmp10 - tmp2 + h2) // s2, 0, maxv)) + writeu16(plane, o + 2, clamp((tmp12 + tmp0 + h2) // s2, 0, maxv)) + writeu16(plane, o + 4, clamp((tmp12 - tmp0 + h2) // s2, 0, maxv)) + end + end +end + +@native local function idct2(coef: buffer, off: number, q: buffer, plane: buffer, out: number, stride: number, p1: number, center: number, maxv: number) + local s1 = 2 ^ (15 - p1) + local h1 = s1 / 2 + local dcm = 2 ^ p1 + for c = 0, 7 do + if c ~= 2 and c ~= 4 and c ~= 6 then + local o = off + c * 2 + local qo = c * 2 + local c1, c3 = readi16(coef, o + 16), readi16(coef, o + 48) + local c5, c7 = readi16(coef, o + 80), readi16(coef, o + 112) + if c1 == 0 and c3 == 0 and c5 == 0 and c7 == 0 then + local dc = readi16(coef, o) * readu16(q, qo) * dcm + ws[c + 1] = dc + ws[c + 9] = dc + else + local tmp10 = readi16(coef, o) * readu16(q, qo) * 32768 + local tmp0 = c7 * readu16(q, qo + 112) * -5906 + + c5 * readu16(q, qo + 80) * 6967 + + c3 * readu16(q, qo + 48) * -10426 + + c1 * readu16(q, qo + 16) * 29692 + ws[c + 1] = (tmp10 + tmp0 + h1) // s1 + ws[c + 9] = (tmp10 - tmp0 + h1) // s1 + end + end + end + local s2 = 2 ^ (18 + p1) + local h2 = s2 / 2 + center * s2 + local sd = 2 ^ (p1 + 3) + local hd = sd / 2 + center * sd + for r = 0, 1 do + local b = r * 8 + local w0, w1, w3, w5, w7 = ws[b + 1], ws[b + 2], ws[b + 4], ws[b + 6], ws[b + 8] + local o = (out + r * stride) * 2 + if w1 == 0 and w3 == 0 and w5 == 0 and w7 == 0 then + local v = clamp((w0 + hd) // sd, 0, maxv) + writeu16(plane, o, v) + writeu16(plane, o + 2, v) + else + local tmp10 = w0 * 32768 + local tmp0 = w7 * -5906 + w5 * 6967 + w3 * -10426 + w1 * 29692 + writeu16(plane, o, clamp((tmp10 + tmp0 + h2) // s2, 0, maxv)) + writeu16(plane, o + 2, clamp((tmp10 - tmp0 + h2) // s2, 0, maxv)) + end + end +end + +-- p1 = PASS1_BITS (2 for 8-bit, 1 for 12-bit) +@native function Dct.idctComponent(coef: buffer, q: buffer, bpl: number, bpc: number, size: number, plane: buffer, p1: number, center: number, maxv: number, hook: (() -> ())?) + local stride = bpl * size + for by = 0, bpc - 1 do + if hook and by > 0 then + pcall(hook) + end + for bx = 0, bpl - 1 do + local off = (by * bpl + bx) * 128 + local out = by * size * stride + bx * size + if size == 8 then + idct8(coef, off, q, plane, out, stride, p1, center, maxv) + elseif size == 4 then + idct4(coef, off, q, plane, out, stride, p1, center, maxv) + elseif size == 2 then + idct2(coef, off, q, plane, out, stride, p1, center, maxv) + else + local v = (readi16(coef, off) * readu16(q, 0) + 4) // 8 + center + writeu16(plane, out * 2, clamp(v, 0, maxv)) + end + end + end +end + +@native function Dct.idctBlock(coef: buffer, off: number, q: buffer, plane: buffer, out: number, stride: number, p1: number, center: number, maxv: number) + idct8(coef, off, q, plane, out, stride, p1, center, maxv) +end + +local fw = table.create(64, 0) + +@native local function quant(coef: buffer, off: number, div: buffer, v: number, i: number) + local qv = readu16(div, i * 2) * 8 + local h = qv // 2 + if v < 0 then + writei16(coef, off + i * 2, -((h - v) // qv)) + else + writei16(coef, off + i * 2, (v + h) // qv) + end +end + +-- quantised as jcdctmgr.c: (|v| + q * 4) // (q * 8) with the sign restored +@native function Dct.fdctQuantize(src: buffer, stride: number, x: number, y: number, w: number, h: number, div: buffer, coef: buffer, off: number) + local lastX, lastY = w - 1, h - 1 + for r = 0, 7 do + local row = math.min(y + r, lastY) * stride + 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) :: 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)) + d2 = readu8(src, row + math.min(x + 2, lastX)) + d3 = readu8(src, row + math.min(x + 3, lastX)) + d4 = readu8(src, row + math.min(x + 4, lastX)) + d5 = readu8(src, row + math.min(x + 5, lastX)) + d6 = readu8(src, row + math.min(x + 6, lastX)) + d7 = readu8(src, row + math.min(x + 7, lastX)) + end + d0 -= 128 + d1 -= 128 + d2 -= 128 + d3 -= 128 + d4 -= 128 + d5 -= 128 + d6 -= 128 + d7 -= 128 + local tmp0, tmp7 = d0 + d7, d0 - d7 + local tmp1, tmp6 = d1 + d6, d1 - d6 + local tmp2, tmp5 = d2 + d5, d2 - d5 + local tmp3, tmp4 = d3 + d4, d3 - d4 + local tmp10, tmp13 = tmp0 + tmp3, tmp0 - tmp3 + local tmp11, tmp12 = tmp1 + tmp2, tmp1 - tmp2 + local b = r * 8 + 1 + fw[b] = (tmp10 + tmp11) * 4 + fw[b + 4] = (tmp10 - tmp11) * 4 + local z1 = (tmp12 + tmp13) * 4433 + fw[b + 2] = (z1 + tmp13 * 6270 + 1024) // 2048 + fw[b + 6] = (z1 - tmp12 * 15137 + 1024) // 2048 + z1 = tmp4 + tmp7 + local z2 = tmp5 + tmp6 + local z3 = tmp4 + tmp6 + local z4 = tmp5 + tmp7 + local z5 = (z3 + z4) * 9633 + tmp4 *= 2446 + tmp5 *= 16819 + tmp6 *= 25172 + tmp7 *= 12299 + z1 *= -7373 + z2 *= -20995 + z3 = z3 * -16069 + z5 + z4 = z4 * -3196 + z5 + fw[b + 7] = (tmp4 + z1 + z3 + 1024) // 2048 + fw[b + 5] = (tmp5 + z2 + z4 + 1024) // 2048 + fw[b + 3] = (tmp6 + z2 + z3 + 1024) // 2048 + fw[b + 1] = (tmp7 + z1 + z4 + 1024) // 2048 + end + for c = 1, 8 do + local d0, d1, d2, d3 = fw[c], fw[c + 8], fw[c + 16], fw[c + 24] + local d4, d5, d6, d7 = fw[c + 32], fw[c + 40], fw[c + 48], fw[c + 56] + local tmp0, tmp7 = d0 + d7, d0 - d7 + local tmp1, tmp6 = d1 + d6, d1 - d6 + local tmp2, tmp5 = d2 + d5, d2 - d5 + local tmp3, tmp4 = d3 + d4, d3 - d4 + local tmp10, tmp13 = tmp0 + tmp3, tmp0 - tmp3 + local tmp11, tmp12 = tmp1 + tmp2, tmp1 - tmp2 + local o0 = (tmp10 + tmp11 + 2) // 4 + local o4 = (tmp10 - tmp11 + 2) // 4 + local z1 = (tmp12 + tmp13) * 4433 + local o2 = (z1 + tmp13 * 6270 + 16384) // 32768 + local o6 = (z1 - tmp12 * 15137 + 16384) // 32768 + z1 = tmp4 + tmp7 + local z2 = tmp5 + tmp6 + local z3 = tmp4 + tmp6 + local z4 = tmp5 + tmp7 + local z5 = (z3 + z4) * 9633 + tmp4 *= 2446 + tmp5 *= 16819 + tmp6 *= 25172 + tmp7 *= 12299 + z1 *= -7373 + z2 *= -20995 + z3 = z3 * -16069 + z5 + z4 = z4 * -3196 + z5 + local o7 = (tmp4 + z1 + z3 + 16384) // 32768 + local o5 = (tmp5 + z2 + z4 + 16384) // 32768 + local o3 = (tmp6 + z2 + z3 + 16384) // 32768 + local o1 = (tmp7 + z1 + z4 + 16384) // 32768 + local cc = c - 1 + quant(coef, off, div, o0, cc) + quant(coef, off, div, o1, cc + 8) + quant(coef, off, div, o2, cc + 16) + quant(coef, off, div, o3, cc + 24) + quant(coef, off, div, o4, cc + 32) + quant(coef, off, div, o5, cc + 40) + quant(coef, off, div, o6, cc + 48) + quant(coef, off, div, o7, cc + 56) + end +end + +return Dct +end +end + + + + + + Jpeg + --!optimize 2 +--!nocheck +-- rosetta chunk Jpeg (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 8 modules (5 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["codecs/image/Jpeg"] = function() + +-- codecs/image/Jpeg: the JPEG codec (ITU T.81), bit-exact with libjpeg-turbo's djpeg and byte-identical with cjpeg. +-- From jpeg-luau 1.0 (same author); IJG-derived parts: licenses/libjpeg-turbo-LICENSE.md. Motion-JPEG: frames without +-- DHT use the T.81 annex K tables; AVI1 fields are woven top field first, as ffmpeg does (it ignores the polarity). +local Err = __include("core/Err") +local Types = __include("Types") +local Decode = __include("codecs/image/Jpeg/Decode") +local Encode = __include("codecs/image/Jpeg/Encode") +local Yuv = __include("codecs/image/Jpeg/Yuv") + +local Jpeg = {} + +type DecodeOptions = { + scale: number?, + orient: boolean?, + native: boolean?, + yuv: boolean?, + fields: boolean?, + raw: boolean?, + maxPixels: number?, + yield: (() -> ())?, +} +type EncodeOptions = { + quality: number?, + subsampling: ("420" | "422" | "444")?, + progressive: boolean?, + optimize: boolean?, + gray: boolean?, + restart: number?, + jfif: boolean?, + density: { unit: number, x: number, y: number }?, + segments: { { marker: number, data: buffer } }?, +} + +type Info = { + width: number, + height: number, + components: number, + progressive: boolean, + arithmetic: boolean, + precision: number, + colorSpace: string, + sampling: { { number } }, + orientation: number, + adobe: number?, + jfif: boolean, + avi1: number?, +} + +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) + return o, math.clamp(math.floor(tonumber(len) or (n - o)), 0, n - o) +end + +local function parse(buf: buffer, o: number, l: number, opts: any, headerOnly: boolean): (Decode.State?, Err.Err?) + local ok, st, code, msg = pcall(Decode.parse, buf, o, o + l, opts, headerOnly) + if not ok then + return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(st)) + end + if not st then + return nil, Err.from(msg or "decode failed", o, code) + end + return st, nil +end + +local function samplingOf(f: any): { { number } } + local sampling = {} + for _, c in f.comps do + table.insert(sampling, { c.h, c.v }) + end + return sampling +end + +function Jpeg.info(buf: buffer, off: number?, len: number?): (Info?, Err.Err?) + if type(buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "expected a buffer") + end + local o, l = range(buf, off, len) + local st, err = parse(buf, o, l, nil, true) + if not st then + return nil, err + end + local f = st.frame + return { + width = f.width, + height = f.height, + components = #f.comps, + progressive = f.progressive, + arithmetic = f.arithmetic, + precision = f.precision, + colorSpace = Decode.colorSpaceOf(f, st.adobe, st.jfif), + sampling = samplingOf(f), + orientation = st.orientation, + adobe = st.adobe, + jfif = st.jfif, + avi1 = st.avi1, + }, + nil +end + +local function orient(px: buffer, w: number, h: number, o: number): (buffer, number, number) + if o <= 1 or o > 8 then + return px, w, h + end + local swap = o >= 5 + local ow, oh = if swap then h else w, if swap then w else h + local out = buffer.create(ow * oh * 4) + local readu32, writeu32 = buffer.readu32, buffer.writeu32 + for y = 0, oh - 1 do + for x = 0, ow - 1 do + local col, row + if o == 2 then + col, row = w - 1 - x, y + elseif o == 3 then + col, row = w - 1 - x, h - 1 - y + elseif o == 4 then + col, row = x, h - 1 - y + elseif o == 5 then + col, row = y, x + elseif o == 6 then + col, row = y, h - 1 - x + elseif o == 7 then + col, row = w - 1 - y, h - 1 - x + else + col, row = w - 1 - y, x + end + writeu32(out, (y * ow + x) * 4, readu32(px, (row * w + col) * 4)) + end + end + return out, ow, oh +end + +local function decodeOne(buf: buffer, o: number, l: number, opts: DecodeOptions?): (Types.Image?, any) + local st, err = parse(buf, o, l, opts, false) + if not st then + return nil, err + end + local s = st :: Decode.State + local img = Types.Image.new(0, 0) + local space, mode = nil, nil + if opts and opts.yuv then + local ok, w, h, px, m = pcall(Decode.outputYuv, s) + if not ok then + return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(w)) + end + if w then + img.width, img.height, img.pixels, img.format = w, h :: number, px :: buffer, "yuv420p" + mode = m + space = Decode.colorSpaceOf(s.frame, s.adobe, s.jfif) + end + end + if not mode then + local ok, w, h, px, sp = pcall(Decode.output, s) + if not ok then + return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(w)) + end + if not w then + return nil, Err.from(px, o, h) + end + space = sp + if opts and opts.orient then + px, w, h = orient(px, w, h, s.orientation) + end + img.width, img.height, img.pixels = w, h, px + if opts and opts.native and space == "gray" then + local g = buffer.create(w * h) + for i = 0, w * h - 1 do + buffer.writeu8(g, i, buffer.readu8(px, i * 4)) + end + img.pixels, img.format = g, "gray8" + end + end + local f = s.frame + local meta = img.meta + meta.orientation = s.orientation + meta.oriented = (opts and opts.orient and not mode) or false + meta.exif = s.exif + meta.icc = s.icc + if #s.comments > 0 then + meta.text = { comment = table.concat(s.comments, "\n") } + end + if s.density and s.density.unit > 0 and s.density.x > 0 and s.density.y > 0 then + local k = if s.density.unit == 2 then 2.54 else 1 + meta.dpi = { x = s.density.x * k, y = s.density.y * k } + end + meta.truncated = s.truncated + meta.source = { + format = "jpeg", + bitDepth = f.precision, + colorType = space, + components = #f.comps, + progressive = f.progressive, + arithmetic = f.arithmetic, + sampling = samplingOf(f), + scale = s.scale, + adobe = s.adobe, + jfif = s.jfif, + avi1 = s.avi1, + yuv = mode, + range = if mode then "full" else nil, + fields = 1, + } + return img, s +end + +-- the start of a second JPEG: FF D8 FF +local function nextSoi(buf: buffer, p: number, e: number): number + local readu8 = buffer.readu8 + while p + 3 <= e do + if readu8(buf, p) == 0xFF and readu8(buf, p + 1) == 0xD8 and readu8(buf, p + 2) == 0xFF then + return p + end + p += 1 + end + return -1 +end + +local function weave(a: Types.Image, b: Types.Image): Types.Image + local w, hf = a.width, a.height + local h = hf * 2 + local out = Types.Image.new(w, h, a.format) + local dst = out.pixels + if a.format == "yuv420p" then + local cw, chf = (w + 1) // 2, (hf + 1) // 2 + local ch = (h + 1) // 2 + Yuv.weave(a.pixels, 0, b.pixels, 0, w, h, dst, 0) + for k = 0, 1 do + Yuv.weave(a.pixels, w * hf + k * cw * chf, b.pixels, w * hf + k * cw * chf, cw, ch, dst, w * h + k * cw * ch) + end + else + local bpp = Types.Image.bpp(a.format) or 4 + Yuv.weave(a.pixels, 0, b.pixels, 0, w * bpp, h, dst, 0) + end + out.meta = a.meta + return out +end + +function Jpeg.decode(buf: buffer, off: number?, len: number?, opts: DecodeOptions?): (Types.Image?, Err.Err?) + if type(buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "expected a buffer") + end + if opts ~= nil and type(opts) ~= "table" then + return nil, Err.new(Err.ARG, "options must be a table") + end + local o, l = range(buf, off, len) + local img, st = decodeOne(buf, o, l, opts) + if not img then + return nil, st + end + local s = st :: Decode.State + local wantFields = if opts and opts.fields ~= nil then opts.fields else (s.avi1 == 1 or s.avi1 == 2) + if wantFields and not (opts and opts.orient) then + local e = o + l + local p = nextSoi(buf, s.endPos, e) + if p >= 0 then + local o2 = table.clone(opts or {}) :: any + if o2.maxPixels then + o2.maxPixels = math.max(0, o2.maxPixels - img.width * img.height) + end + local b = decodeOne(buf, p, e - p, o2) + if b and b.width == img.width and b.height == img.height and b.format == img.format then + local truncated = img.meta.truncated or b.meta.truncated + img = weave(img, b) + img.meta.truncated = truncated + local source: any = img.meta.source + source.fields = 2 + end + end + end + return img, nil +end + +local BPP = { rgba8 = 4, rgb8 = 3, gray8 = 1, yuv420p = 0 } + +function Jpeg.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or type(img.pixels) ~= "buffer" or type(img.width) ~= "number" or type(img.height) ~= "number" then + return nil, Err.new(Err.ARG, "needs an Image") + end + local bpp = BPP[img.format] + if not bpp then + return nil, Err.new(Err.ARG, "needs an rgba8, rgb8, gray8 or yuv420p Image (got " .. tostring(img.format) .. ")") + end + local w, h = img.width, img.height + local need = if bpp == 0 then w * h + 2 * ((w + 1) // 2) * ((h + 1) // 2) else w * h * bpp + if w < 1 or h < 1 or w > 65535 or h > 65535 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(img.pixels) < need then + return nil, Err.new(Err.ARG, "bad image size or pixel buffer (1..65535 per side)") + end + if opts ~= nil and type(opts) ~= "table" then + return nil, Err.new(Err.ARG, "options must be a table") + end + local o: any = opts or {} + local quality = o.quality or 90 + if type(quality) ~= "number" or quality < 1 or quality > 100 then + return nil, Err.new(Err.ARG, "quality must be 1..100") + end + local sub = o.subsampling or "420" + if sub ~= "420" and sub ~= "422" and sub ~= "444" then + return nil, Err.new(Err.ARG, "subsampling must be \"420\", \"422\" or \"444\"") + end + if bpp == 0 then + sub = "420" + end + local restart = o.restart or 0 + if type(restart) ~= "number" or restart < 0 or restart > 65535 or restart % 1 ~= 0 then + return nil, Err.new(Err.ARG, "restart must be 0..65535 MCUs") + end + local gray = o.gray + if gray == nil then + gray = img.format == "gray8" + end + local segments = {} + if o.segments ~= nil then + if type(o.segments) ~= "table" then + return nil, Err.new(Err.ARG, "segments must be a list of { marker, data }") + end + for _, sg in o.segments do + if type(sg) ~= "table" or type(sg.data) ~= "buffer" or buffer.len(sg.data) > 65533 or type(sg.marker) ~= "number" then + return nil, Err.new(Err.ARG, "bad segment (marker 0xE0..0xEF / 0xFE, at most 65533 bytes)") + end + if not ((sg.marker >= 0xE0 and sg.marker <= 0xEF) or sg.marker == 0xFE) then + return nil, Err.new(Err.ARG, "bad segment marker (0xE0..0xEF / 0xFE)") + end + table.insert(segments, sg) + end + end + local density = o.density + if density ~= nil then + if type(density) ~= "table" or type(density.unit) ~= "number" or type(density.x) ~= "number" or type(density.y) ~= "number" then + return nil, Err.new(Err.ARG, "bad density") + end + density = { + unit = math.clamp(math.floor(density.unit), 0, 2), + x = math.clamp(math.floor(density.x), 1, 65535), + y = math.clamp(math.floor(density.y), 1, 65535), + } + end + local out = Encode.run(img.pixels, w, h, bpp, { + quality = quality, + sampling = sub, + progressive = o.progressive == true, + optimize = o.optimize == true, + gray = gray, + restart = restart, + segments = segments, + jfif = o.jfif ~= false, + density = density, + }) + return out, nil +end + +return Jpeg +end +__FILES["codecs/image/Jpeg/Arith"] = @native function() + + + +-- codecs/image/Jpeg/Arith: arithmetic-coded scans (ITU T.81 annex D / F.1.4, sequential and progressive). +-- A Luau translation of libjpeg-turbo's jdarith.c / jaricom.c (IJG licence: licenses/libjpeg-turbo-LICENSE.md); past the +-- end of a restart segment it reads zero bytes, as libjpeg does. Bins: DC [t * 64], AC [256 + t * 256], fixed 0.5 [1280]. +local readu8, writeu8, readi16, writei16 = buffer.readu8, buffer.writeu8, buffer.readi16, buffer.writei16 +local band, bxor = bit32.band, bit32.bxor + +local Arith = {} + +-- jaricom.c: Qe << 16 | Next_Index_MPS << 8 | Switch_MPS << 7 | Next_Index_LPS +local TAB = buffer.create(114 * 4) +do + local raw = { + { 0x5a1d, 1, 1, 1 }, { 0x2586, 14, 2, 0 }, { 0x1114, 16, 3, 0 }, { 0x080b, 18, 4, 0 }, { 0x03d8, 20, 5, 0 }, + { 0x01da, 23, 6, 0 }, { 0x00e5, 25, 7, 0 }, { 0x006f, 28, 8, 0 }, { 0x0036, 30, 9, 0 }, { 0x001a, 33, 10, 0 }, + { 0x000d, 35, 11, 0 }, { 0x0006, 9, 12, 0 }, { 0x0003, 10, 13, 0 }, { 0x0001, 12, 13, 0 }, { 0x5a7f, 15, 15, 1 }, + { 0x3f25, 36, 16, 0 }, { 0x2cf2, 38, 17, 0 }, { 0x207c, 39, 18, 0 }, { 0x17b9, 40, 19, 0 }, { 0x1182, 42, 20, 0 }, + { 0x0cef, 43, 21, 0 }, { 0x09a1, 45, 22, 0 }, { 0x072f, 46, 23, 0 }, { 0x055c, 48, 24, 0 }, { 0x0406, 49, 25, 0 }, + { 0x0303, 51, 26, 0 }, { 0x0240, 52, 27, 0 }, { 0x01b1, 54, 28, 0 }, { 0x0144, 56, 29, 0 }, { 0x00f5, 57, 30, 0 }, + { 0x00b7, 59, 31, 0 }, { 0x008a, 60, 32, 0 }, { 0x0068, 62, 33, 0 }, { 0x004e, 63, 34, 0 }, { 0x003b, 32, 35, 0 }, + { 0x002c, 33, 9, 0 }, { 0x5ae1, 37, 37, 1 }, { 0x484c, 64, 38, 0 }, { 0x3a0d, 65, 39, 0 }, { 0x2ef1, 67, 40, 0 }, + { 0x261f, 68, 41, 0 }, { 0x1f33, 69, 42, 0 }, { 0x19a8, 70, 43, 0 }, { 0x1518, 72, 44, 0 }, { 0x1177, 73, 45, 0 }, + { 0x0e74, 74, 46, 0 }, { 0x0bfb, 75, 47, 0 }, { 0x09f8, 77, 48, 0 }, { 0x0861, 78, 49, 0 }, { 0x0706, 79, 50, 0 }, + { 0x05cd, 48, 51, 0 }, { 0x04de, 50, 52, 0 }, { 0x040f, 50, 53, 0 }, { 0x0363, 51, 54, 0 }, { 0x02d4, 52, 55, 0 }, + { 0x025c, 53, 56, 0 }, { 0x01f8, 54, 57, 0 }, { 0x01a4, 55, 58, 0 }, { 0x0160, 56, 59, 0 }, { 0x0125, 57, 60, 0 }, + { 0x00f6, 58, 61, 0 }, { 0x00cb, 59, 62, 0 }, { 0x00ab, 61, 63, 0 }, { 0x008f, 61, 32, 0 }, { 0x5b12, 65, 65, 1 }, + { 0x4d04, 80, 66, 0 }, { 0x412c, 81, 67, 0 }, { 0x37d8, 82, 68, 0 }, { 0x2fe8, 83, 69, 0 }, { 0x293c, 84, 70, 0 }, + { 0x2379, 86, 71, 0 }, { 0x1edf, 87, 72, 0 }, { 0x1aa9, 87, 73, 0 }, { 0x174e, 72, 74, 0 }, { 0x1424, 72, 75, 0 }, + { 0x119c, 74, 76, 0 }, { 0x0f6b, 74, 77, 0 }, { 0x0d51, 75, 78, 0 }, { 0x0bb6, 77, 79, 0 }, { 0x0a40, 77, 48, 0 }, + { 0x5832, 80, 81, 1 }, { 0x4d1c, 88, 82, 0 }, { 0x438e, 89, 83, 0 }, { 0x3bdd, 90, 84, 0 }, { 0x34ee, 91, 85, 0 }, + { 0x2eae, 92, 86, 0 }, { 0x299a, 93, 87, 0 }, { 0x2516, 86, 71, 0 }, { 0x5570, 88, 89, 1 }, { 0x4ca9, 95, 90, 0 }, + { 0x44d9, 96, 91, 0 }, { 0x3e22, 97, 92, 0 }, { 0x3824, 99, 93, 0 }, { 0x32b4, 99, 94, 0 }, { 0x2e17, 93, 86, 0 }, + { 0x56a8, 95, 96, 1 }, { 0x4f46, 101, 97, 0 }, { 0x47e5, 102, 98, 0 }, { 0x41cf, 103, 99, 0 }, { 0x3c3d, 104, 100, 0 }, + { 0x375e, 99, 93, 0 }, { 0x5231, 105, 102, 0 }, { 0x4c0f, 106, 103, 0 }, { 0x4639, 107, 104, 0 }, { 0x415e, 103, 99, 0 }, + { 0x5627, 105, 106, 1 }, { 0x50e7, 108, 107, 0 }, { 0x4b85, 109, 103, 0 }, { 0x5597, 110, 109, 0 }, { 0x504f, 111, 107, 0 }, + { 0x5a10, 110, 111, 1 }, { 0x5522, 112, 109, 0 }, { 0x59eb, 112, 111, 1 }, { 0x5a1d, 113, 113, 0 }, + } + for i, e in raw do + buffer.writeu16(TAB, (i - 1) * 4, e[1]) -- Qe + writeu8(TAB, (i - 1) * 4 + 2, e[4] * 128 + e[2]) -- Switch_MPS << 7 | Next_Index_LPS + writeu8(TAB, (i - 1) * 4 + 3, e[3]) -- Next_Index_MPS + end +end + +local ZZ: buffer = buffer.create(80) + +local STATS = 1281 +local POW2 = buffer.create(8) +for i = 0, 7 do + writeu8(POW2, i, 2 ^ i) +end +local FIXED = 1280 + +local D: buffer = buffer.create(0) +local P = 0 +local SEGEND = 0 +local OVER = 0 +local C, A, CT = 0, 0, -16 +local st: buffer = buffer.create(STATS) + +@native local function decode(s: number): number + while A < 0x8000 do + CT -= 1 + if CT < 0 then + local data = 0 + if P < SEGEND then + data = readu8(D, P) + P += 1 + else + OVER += 1 + end + C = C * 256 + data + CT += 8 + if CT < 0 then + CT += 1 + if CT == 0 then + A = 0x8000 + end + end + end + A *= 2 + end + local sv = readu8(st, s) + local t = band(sv, 0x7F) * 4 + local qe = buffer.readu16(TAB, t) + local nl = readu8(TAB, t + 2) + local nm = readu8(TAB, t + 3) + local temp = A - qe + A = temp + temp *= readu8(POW2, CT) + if C >= temp then + C -= temp + if A < qe then + A = qe + writeu8(st, s, bxor(band(sv, 0x80), nm)) + else + A = qe + writeu8(st, s, bxor(band(sv, 0x80), nl)) + sv = bxor(sv, 0x80) + end + elseif A < 0x8000 then + if A < qe then + writeu8(st, s, bxor(band(sv, 0x80), nl)) + sv = bxor(sv, 0x80) + else + writeu8(st, s, bxor(band(sv, 0x80), nm)) + end + end + return if sv >= 0x80 then 1 else 0 +end + +@native local function i16(v: number): number + v = band(v, 0xFFFF) + return if v >= 0x8000 then v - 0x10000 else v +end + +type ArithComp = { + coef: buffer, + bpl: number, + h: number, + v: number, + bw: number, + bh: number, + dcTbl: number, + acTbl: number, + pred: number, + ctx: number, +} + +type ArithParams = { + comps: { ArithComp }, + mcusX: number, + mcusY: number, + ri: number, + mode: number, + ss: number, + se: number, + al: number, + dcL: { number }, + dcU: { number }, + acK: { number }, +} + +-- DC difference (F.1.4.4.1 / figures F.19, F.21 - F.24) +@native local function dcDiff(c: ArithComp, L: number, U: number): number? + local base = c.dcTbl * 64 + local s = base + c.ctx + if decode(s) == 0 then + c.ctx = 0 + return c.pred + end + local sign = decode(s + 1) + s = s + 2 + sign + local m = decode(s) + if m ~= 0 then + s = base + 20 + while decode(s) ~= 0 do + m *= 2 + if m == 0x8000 then + return nil + end + s += 1 + end + end + if m < 2 ^ L // 2 then + c.ctx = 0 + elseif m > 2 ^ U // 2 then + c.ctx = 12 + sign * 4 + else + c.ctx = 4 + sign * 4 + end + local v = m + s += 14 + m = m // 2 + while m > 0 do + if decode(s) ~= 0 then + v += m + end + m = m // 2 + end + v += 1 + if sign ~= 0 then + v = -v + end + return band(c.pred + v, 0xFFFF) +end + +-- AC coefficients k = ss..se of one block (figure F.20) +@native local function acFirst(coef: buffer, off: number, tbl: number, ss: number, se: number, K: number, mul: number): boolean + local base = 256 + tbl * 256 + local k = ss + while k <= se do + local s = base + 3 * (k - 1) + if decode(s) ~= 0 then + break -- EOB + end + while decode(s + 1) == 0 do + s += 3 + k += 1 + if k > se then + return false + end + end + local sign = decode(FIXED) + s += 2 + local m = decode(s) + if m ~= 0 then + if decode(s) ~= 0 then + m *= 2 + s = base + (if k <= K then 189 else 217) + while decode(s) ~= 0 do + m *= 2 + if m == 0x8000 then + return false + end + s += 1 + end + end + end + local v = m + s += 14 + m = m // 2 + while m > 0 do + if decode(s) ~= 0 then + v += m + end + m = m // 2 + end + v += 1 + if sign ~= 0 then + v = -v + end + writei16(coef, off + readu8(ZZ, k) * 2, i16(v * mul)) + k += 1 + end + return true +end + +@native local function acRefine(coef: buffer, off: number, tbl: number, ss: number, se: number, al: number): boolean + local base = 256 + tbl * 256 + local p1 = 2 ^ al + local m1 = -p1 + local kex = se + while kex > 0 do + if readi16(coef, off + readu8(ZZ, kex) * 2) ~= 0 then + break + end + kex -= 1 + end + local k = ss + while k <= se do + local s = base + 3 * (k - 1) + if k > kex then + if decode(s) ~= 0 then + break + end + end + while true do + local o = off + readu8(ZZ, k) * 2 + local cv = readi16(coef, o) + if cv ~= 0 then + if decode(s + 2) ~= 0 then + writei16(coef, o, i16(if cv < 0 then cv + m1 else cv + p1)) + end + break + end + if decode(s + 1) ~= 0 then + writei16(coef, o, i16(if decode(FIXED) ~= 0 then m1 else p1)) + break + end + s += 3 + k += 1 + if k > se then + return false + end + end + k += 1 + end + return true +end + +@native function Arith.init(zigzag: buffer) + ZZ = zigzag +end + +@native function Arith.run(d: buffer, cleanLen: number, rst: { number }, nrst: number, Pm: ArithParams): boolean + local comps = Pm.comps + local nc = #comps + local mode, ss, se, al, ri = Pm.mode, Pm.ss, Pm.se, Pm.al, Pm.ri + local units, ux + if nc == 1 then + ux = comps[1].bw + units = ux * comps[1].bh + else + ux = Pm.mcusX + units = ux * Pm.mcusY + end + local resetDc = mode == 0 or mode == 1 + local resetAc = mode == 0 or mode == 3 or mode == 4 + @native local function reset() + for i = 1, nc do + local c = comps[i] + if resetDc then + buffer.fill(st, c.dcTbl * 64, 0, 64) + c.pred = 0 + c.ctx = 0 + end + if resetAc then + buffer.fill(st, 256 + c.acTbl * 256, 0, 256) + end + end + C, A, CT = 0, 0, -16 + end + D = d + P = 0 + SEGEND = if nrst >= 1 then math.min(rst[1], cleanLen) else cleanLen + OVER = 0 + writeu8(st, FIXED, 113) + reset() + local rstIdx = 0 + local bad = false + local truncated = false + local mul = 2 ^ al + for u = 0, units - 1 do + if ri > 0 and u > 0 and u % ri == 0 then + rstIdx += 1 + if rstIdx <= nrst then + P = math.min(rst[rstIdx], cleanLen) + SEGEND = if rstIdx + 1 <= nrst then math.min(rst[rstIdx + 1], cleanLen) else cleanLen + bad = false + else + truncated = true + break + end + reset() + end + if not bad then + local my, mx = u // ux, u % ux + for ci = 1, nc do + local c = comps[ci] + local bh, bw, by0, bx0 + if nc == 1 then + bh, bw, by0, bx0 = 1, 1, my, mx + else + bh, bw, by0, bx0 = c.v, c.h, my * c.v, mx * c.h + end + local coef, bpl = c.coef, c.bpl + for by = by0, by0 + bh - 1 do + for bx = bx0, bx0 + bw - 1 do + local off = (by * bpl + bx) * 128 + if mode == 0 then + local pred = dcDiff(c, Pm.dcL[c.dcTbl + 1], Pm.dcU[c.dcTbl + 1]) + if not pred then + bad = true + else + c.pred = pred + writei16(coef, off, i16(pred)) + if not acFirst(coef, off, c.acTbl, 1, 63, Pm.acK[c.acTbl + 1], 1) then + bad = true + end + end + elseif mode == 1 then + local pred = dcDiff(c, Pm.dcL[c.dcTbl + 1], Pm.dcU[c.dcTbl + 1]) + if not pred then + bad = true + else + c.pred = pred + writei16(coef, off, i16(pred * mul)) + end + elseif mode == 2 then + if decode(FIXED) ~= 0 then + local cv = readi16(coef, off) + if band(cv, mul) == 0 then + writei16(coef, off, i16(cv + mul)) + end + end + elseif mode == 3 then + if not acFirst(coef, off, c.acTbl, ss, se, Pm.acK[c.acTbl + 1], mul) then + bad = true + end + else + if not acRefine(coef, off, c.acTbl, ss, se, al) then + bad = true + end + end + if bad then + break + end + end + if bad then + break + end + end + if bad then + break + end + end + end + end + D = buffer.create(0) + return truncated +end + +return Arith +end +__FILES["codecs/image/Jpeg/Color"] = @native function() + + + +-- codecs/image/Jpeg/Color: chroma upsampling (libjpeg-turbo jdsample.c: fancy H2V1 / H2V2 / H1V2, else replicate) and +-- colour conversion (jdcolor.c; YCCK = Adobe inverted CMYK), matching djpeg's defaults. From jpeg-luau 1.0, a Luau +-- translation of libjpeg-turbo (IJG licence: licenses/libjpeg-turbo-LICENSE.md). +local readu16, readi32, readu8, writeu16, writeu32 = buffer.readu16, buffer.readi32, buffer.readu8, buffer.writeu16, buffer.writeu32 +local clamp, min, max = math.clamp, math.min, math.max + +local Color = {} + +Color.FULL = 0 +Color.REPLICATE = 1 +Color.H2V1 = 2 +Color.H2V2 = 3 +Color.H1V2 = 4 + +Color.GRAY = 0 +Color.YCC = 1 +Color.RGB = 2 +Color.CMYK = 3 +Color.YCCK = 4 +Color.CMYK_PLAIN = 5 -- CMYK without an Adobe marker: not inverted +Color.RAW = 6 + +type Comp = { + plane: buffer, + stride: number, + rows: number, + downW: number, + downH: number, + method: number, + hIn: number, + hOut: number, + vIn: number, + vOut: number, + row: buffer, +} + +type Params = { + comps: { Comp }, + space: number, + outW: number, + outH: number, + maxv: number, + pixels: buffer, + crr: buffer, + cbb: buffer, + crg: buffer, + cbg: buffer, + toByte: buffer?, + hook: (() -> ())?, +} + +-- jdcolor.c build_ycc_rgb_table +@native function Color.tables(maxv: number): (buffer, buffer, buffer, buffer) + local n = maxv + 1 + local center = n // 2 + local crr, cbb, crg, cbg = buffer.create(n * 4), buffer.create(n * 4), buffer.create(n * 4), buffer.create(n * 4) + @native local function fix(x: number): number + return math.floor(x * 65536 + 0.5) + end + for i = 0, maxv do + local x = i - center + buffer.writei32(crr, i * 4, (fix(1.40200) * x + 32768) // 65536) + buffer.writei32(cbb, i * 4, (fix(1.77200) * x + 32768) // 65536) + buffer.writei32(crg, i * 4, -fix(0.71414) * x) + buffer.writei32(cbg, i * 4, -fix(0.34414) * x + 32768) + end + return crr, cbb, crg, cbg +end + +@native local function fetch(c: Comp, y: number, outW: number): (buffer, number) + local method = c.method + local plane, stride, row = c.plane, c.stride, c.row + if method == 0 then + return plane, min(y, c.rows - 1) * stride * 2 + elseif method == 2 then + local w = c.downW + local b = min(y, c.rows - 1) * stride * 2 + local cur = readu16(plane, b) + writeu16(row, 0, cur) + local nxt = readu16(plane, b + 2) + writeu16(row, 2, (cur * 3 + nxt + 2) // 4) + local prev = cur + cur = nxt + for i = 1, w - 2 do + nxt = readu16(plane, b + (i + 1) * 2) + local v3 = cur * 3 + writeu16(row, i * 4, (v3 + prev + 1) // 4) + writeu16(row, i * 4 + 2, (v3 + nxt + 2) // 4) + prev = cur + cur = nxt + end + writeu16(row, (w - 1) * 4, (cur * 3 + prev + 1) // 4) + writeu16(row, (w - 1) * 4 + 2, cur) + return row, 0 + elseif method == 3 then + local w = c.downW + local iy = min(y // 2, c.downH - 1) + local oy = if y % 2 == 0 then max(iy - 1, 0) else min(iy + 1, c.downH - 1) + local b0, b1 = iy * stride * 2, oy * stride * 2 + local this = readu16(plane, b0) * 3 + readu16(plane, b1) + local nxt = readu16(plane, b0 + 2) * 3 + readu16(plane, b1 + 2) + writeu16(row, 0, (this * 4 + 8) // 16) + writeu16(row, 2, (this * 3 + nxt + 7) // 16) + local last = this + this = nxt + for i = 1, w - 2 do + nxt = readu16(plane, b0 + (i + 1) * 2) * 3 + readu16(plane, b1 + (i + 1) * 2) + local t3 = this * 3 + writeu16(row, i * 4, (t3 + last + 8) // 16) + writeu16(row, i * 4 + 2, (t3 + nxt + 7) // 16) + last = this + this = nxt + end + writeu16(row, (w - 1) * 4, (this * 3 + last + 8) // 16) + writeu16(row, (w - 1) * 4 + 2, (this * 4 + 7) // 16) + return row, 0 + elseif method == 4 then + local iy = min(y // 2, c.downH - 1) + local oy, bias + if y % 2 == 0 then + oy, bias = max(iy - 1, 0), 1 + else + oy, bias = min(iy + 1, c.downH - 1), 2 + end + local b0, b1 = iy * stride * 2, oy * stride * 2 + for x = 0, outW - 1 do + writeu16(row, x * 2, (readu16(plane, b0 + x * 2) * 3 + readu16(plane, b1 + x * 2) + bias) // 4) + end + return row, 0 + else + local hIn, hOut = c.hIn, c.hOut + local iy = min((y * c.vIn) // c.vOut, c.rows - 1) + local b = iy * stride * 2 + local last = stride - 1 + for x = 0, outW - 1 do + writeu16(row, x * 2, readu16(plane, b + min((x * hIn) // hOut, last) * 2)) + end + return row, 0 + end +end + +@native function Color.run(P: Params) + local comps = P.comps + local nc = #comps + local space, outW, outH, maxv, out = P.space, P.outW, P.outH, P.maxv, P.pixels + local crr, cbb, crg, cbg = P.crr, P.cbb, P.crg, P.cbg + local toByte = P.toByte + local o = 0 + local hook = P.hook + for y = 0, outH - 1 do + if hook and y > 0 and y % 8 == 0 then + pcall(hook) + end + local s0, b0 = fetch(comps[1], y, outW) + if space == 0 or nc < 3 then + for x = 0, outW - 1 do + local v = readu16(s0, b0 + x * 2) + if toByte then + v = readu8(toByte, v) + end + writeu32(out, o, 0xFF000000 + v * 0x10101) + o += 4 + end + else + local s1, b1 = fetch(comps[2], y, outW) + local s2, b2 = fetch(comps[3], y, outW) + local s3, b3 = s0, b0 + if nc >= 4 then + s3, b3 = fetch(comps[4], y, outW) + end + if space == 6 then + for x = 0, outW - 1 do + local i = x * 2 + local c0, c1, c2 = readu16(s0, b0 + i), readu16(s1, b1 + i), readu16(s2, b2 + i) + local c3 = if nc >= 4 then readu16(s3, b3 + i) else maxv + if toByte then + c0, c1, c2, c3 = readu8(toByte, c0), readu8(toByte, c1), readu8(toByte, c2), readu8(toByte, c3) + end + writeu32(out, o, c0 + c1 * 256 + c2 * 65536 + c3 * 16777216) + o += 4 + end + continue + end + if space == 1 and not toByte then + for x = 0, outW - 1 do + local i = x * 2 + local yv, cb, cr = readu16(s0, b0 + i), readu16(s1, b1 + i), readu16(s2, b2 + i) + local r = clamp(yv + readi32(crr, cr * 4), 0, 255) + local g = clamp(yv + (readi32(cbg, cb * 4) + readi32(crg, cr * 4)) // 65536, 0, 255) + local b = clamp(yv + readi32(cbb, cb * 4), 0, 255) + writeu32(out, o, 0xFF000000 + r + g * 256 + b * 65536) + o += 4 + end + continue + end + for x = 0, outW - 1 do + local i = x * 2 + local c0, c1, c2 = readu16(s0, b0 + i), readu16(s1, b1 + i), readu16(s2, b2 + i) + local r, g, b + if space == 2 then + r, g, b = c0, c1, c2 + elseif space == 3 or space == 5 then + local k = readu16(s3, b3 + i) + if space == 5 then + c0, c1, c2, k = maxv - c0, maxv - c1, maxv - c2, maxv - k + end + r = (c0 * k + maxv // 2) // maxv + g = (c1 * k + maxv // 2) // maxv + b = (c2 * k + maxv // 2) // maxv + else + r = clamp(c0 + readi32(crr, c2 * 4), 0, maxv) + g = clamp(c0 + (readi32(cbg, c1 * 4) + readi32(crg, c2 * 4)) // 65536, 0, maxv) + b = clamp(c0 + readi32(cbb, c1 * 4), 0, maxv) + if space == 4 then + -- YCCK: the YCC part decodes to inverted C, M, Y (libjpeg ycck_cmyk_convert), K as stored + local k = readu16(s3, b3 + i) + r = ((maxv - r) * k + maxv // 2) // maxv + g = ((maxv - g) * k + maxv // 2) // maxv + b = ((maxv - b) * k + maxv // 2) // maxv + end + end + if toByte then + r, g, b = readu8(toByte, r), readu8(toByte, g), readu8(toByte, b) + end + writeu32(out, o, 0xFF000000 + r + g * 256 + b * 65536) + o += 4 + end + end + end +end + +return Color +end +__FILES["codecs/image/Jpeg/Decode"] = function() + +-- codecs/image/Jpeg/Decode: the JPEG marker parser and output stage (it validates everything the native loops index). +-- From jpeg-luau 1.0 (same author), extended with SOF9 / SOF10 / DAC, EXIF / ICC / AVI1 segments and yuv420p output; +-- the IDCT size choice for scaled decodes follows libjpeg-turbo's jdmaster.c. +local Scan = __include("codecs/image/Jpeg/Scan") +local Arith = __include("codecs/image/Jpeg/Arith") +local Color = __include("codecs/image/Jpeg/Color") +local Tables = __include("codecs/image/Jpeg/Tables") +local Yuv = __include("codecs/image/Jpeg/Yuv") +local Dct = __include("codecs/image/Dct") + +local readu8 = buffer.readu8 +local band, rshift = bit32.band, bit32.rshift + +local Decode = {} + +Arith.init(Scan.ZIGZAG) + +local function be16(b: buffer, p: number): number + return readu8(b, p) * 256 + readu8(b, p + 1) +end + +local stdBuilt: { [string]: buffer } = {} +local function stdTable(class: string, slot: number): buffer? + local key = class .. slot + if not stdBuilt[key] then + local def = (if class == "dc" then Tables.DC else Tables.AC)[slot + 1] + if not def then + return nil + end + stdBuilt[key] = Scan.buildTable(def.counts, def.symbols) + end + return stdBuilt[key] +end + +-- the EXIF TIFF block (after "Exif\0\0") and its orientation tag +local function exif(b: buffer, p: number, e: number): (number?, number?) + if e - p < 14 or buffer.readstring(b, p, 6) ~= "Exif\0\0" then + return nil, nil + end + local t = p + 6 + local le + local bo = buffer.readstring(b, t, 2) + if bo == "II" then + le = true + elseif bo == "MM" then + le = false + else + return nil, nil + end + local function r16(at: number): number + if le then + return readu8(b, at) + readu8(b, at + 1) * 256 + end + return readu8(b, at) * 256 + readu8(b, at + 1) + end + local function r32(at: number): number + if le then + return r16(at) + r16(at + 2) * 65536 + end + return r16(at) * 65536 + r16(at + 2) + end + local ifd = t + r32(t + 4) + if ifd + 2 > e then + return t, nil + end + local count = r16(ifd) + for i = 0, count - 1 do + local en = ifd + 2 + i * 12 + if en + 12 > e then + return t, nil + end + if r16(en) == 0x0112 then + local v = r16(en + 8) + return t, if v >= 1 and v <= 8 then v else nil + end + end + return t, nil +end + +type Comp = { + id: number, + h: number, + v: number, + tq: number, + bpl: number, + bpc: number, + bw: number, + bh: number, + coef: buffer?, + quant: buffer?, + dct: buffer?, + act: buffer?, + dcTbl: number, + acTbl: number, + pred: number, + ctx: number, +} + +type Frame = { + width: number, + height: number, + precision: number, + progressive: boolean, + arithmetic: boolean, + comps: { Comp }, + hmax: number, + vmax: number, + mcusX: number, + mcusY: number, +} + +local SOF_REFUSED = { + [0xC3] = "lossless", + [0xC5] = "hierarchical", + [0xC6] = "hierarchical", + [0xC7] = "hierarchical", + [0xCB] = "lossless arithmetic-coded", + [0xCD] = "hierarchical arithmetic-coded", + [0xCE] = "hierarchical arithmetic-coded", + [0xCF] = "hierarchical arithmetic-coded", +} + +local function parseSof(b: buffer, p: number, e: number, m: number): (Frame?, string?, string?) + if e - p < 6 then + return nil, "corrupt", "short SOF" + end + local prec = readu8(b, p) + local height, width, nf = be16(b, p + 1), be16(b, p + 3), readu8(b, p + 5) + if prec ~= 8 and prec ~= 12 then + return nil, "unsupported", "sample precision " .. prec + end + if width == 0 or height == 0 then + if height == 0 and width > 0 then + return nil, "unsupported", "DNL (height 0 in the frame header)" + end + return nil, "corrupt", "bad size " .. width .. "x" .. height + end + if nf ~= 1 and nf ~= 3 and nf ~= 4 then + return nil, "unsupported", "component count " .. nf + end + if e - p < 6 + nf * 3 then + return nil, "corrupt", "short SOF" + end + 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) :: number + if h < 1 or h > 4 or v < 1 or v > 4 then + return nil, "corrupt", "bad sampling factors " .. h .. "x" .. v + end + if tq > 3 then + return nil, "corrupt", "bad quantisation table selector " .. tq + end + local id = readu8(b, q) + for _, c in comps do + if c.id == id then + return nil, "corrupt", "duplicate component id " .. id + end + end + 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)) + local mcusY = math.ceil(height / (8 * vmax)) + for _, c in comps do + c.bpl = mcusX * c.h + c.bpc = mcusY * c.v + c.bw = math.ceil(math.ceil(width * c.h / hmax) / 8) + c.bh = math.ceil(math.ceil(height * c.v / vmax) / 8) + end + return { + width = width, + height = height, + precision = prec, + progressive = m == 0xC2 or m == 0xCA, + arithmetic = m == 0xC9 or m == 0xCA, + comps = comps, + hmax = hmax, + vmax = vmax, + mcusX = mcusX, + mcusY = mcusY, + }, nil, nil +end + +local function colorSpaceOf(frame: Frame, adobe: number?, jfif: boolean): string + local n = #frame.comps + if n == 1 then + return "gray" + elseif n == 3 then + if adobe ~= nil then + return if adobe == 0 then "rgb" else "ycbcr" + end + local c = frame.comps + if not jfif and c[1].id == 82 and c[2].id == 71 and c[3].id == 66 then + return "rgb" + end + return "ycbcr" + end + return if adobe == 2 then "ycck" else "cmyk" +end +Decode.colorSpaceOf = colorSpaceOf + +-- The IDCT size (8, 4, 2 or 1) for a component at a scale. libjpeg-turbo scales chroma up through a bigger IDCT +-- instead of upsampling it, when the sampling ratios allow (jdmaster.c jpeg_calc_output_dimensions). +local function idctSize(f: Frame, c: Comp, scale: number): number + local minSize = 8 // scale + local ssize = minSize + while ssize < 8 and (f.hmax * minSize) % (c.h * ssize * 2) == 0 and (f.vmax * minSize) % (c.v * ssize * 2) == 0 do + ssize *= 2 + end + return ssize +end + +type State = { + frame: any, + adobe: number?, + jfif: boolean, + density: { unit: number, x: number, y: number }?, + orientation: number, + exif: buffer?, + icc: buffer?, + comments: { string }, + truncated: boolean, + raw: boolean, + scale: number, + avi1: number?, -- the AVI1 APP0 field polarity (0 = progressive, 1 / 2 = interlaced: two fields back to back) + endPos: number, + hook: (() -> ())?, +} + +function Decode.parse(b: buffer, base: number, n: number, opts: any, headerOnly: boolean): (State?, string?, string?) + if n - base < 4 or readu8(b, base) ~= 0xFF or readu8(b, base + 1) ~= 0xD8 then + return nil, "corrupt", "not a JPEG file (no SOI marker)" + end + local scale = (opts and opts.scale) or 1 + 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: number = (opts and opts.maxPixels) or 2 ^ 26 + local quant: { [number]: buffer } = {} + local dcT: { [number]: buffer } = {} + local acT: { [number]: buffer } = {} + local dcL, dcU, acK = { 0, 0, 0, 0 }, { 1, 1, 1, 1 }, { 5, 5, 5, 5 } + local frame: Frame? = nil + local st: State = { + frame = nil, + adobe = nil, + jfif = false, + density = nil, + orientation = 1, + exif = nil, + icc = nil, + comments = {}, + truncated = false, + raw = opts ~= nil and opts.raw == true, + scale = scale, + avi1 = nil, + endPos = n, + hook = if opts and type(opts.yield) == "function" then opts.yield else nil, + } + local iccChunks: { buffer } = {} + local ri = 0 + local scans = 0 + local clean: buffer? = nil + local rst = {} + local pos = base + 2 + while pos < n do + -- find the next marker (tolerate garbage and fill bytes) + if readu8(b, pos) ~= 0xFF then + pos += 1 + continue + end + while pos < n and readu8(b, pos) == 0xFF do + pos += 1 + end + if pos >= n then + break + end + local m = readu8(b, pos) + pos += 1 + if m == 0xD9 then + st.endPos = pos + break -- EOI + elseif m == 0 or m == 0x01 or m == 0xD8 or (m >= 0xD0 and m <= 0xD7) then + continue -- standalone markers (or stray stuffing) + end + if pos + 2 > n then + st.truncated = true + break + end + local len = be16(b, pos) + if len < 2 then + return nil, "corrupt", string.format("bad segment length for marker %02X", m) + end + local p, e = pos + 2, pos + len + if e > n then + if m == 0xDA and frame and not headerOnly then + e = n -- a truncated SOS header still fails below + else + st.truncated = true + break + end + end + pos = e + if m == 0xE0 then + if e - p >= 12 and buffer.readstring(b, p, 5) == "JFIF\0" then + st.jfif = true + st.density = { unit = readu8(b, p + 7), x = be16(b, p + 8), y = be16(b, p + 10) } + elseif e - p >= 5 and buffer.readstring(b, p, 4) == "AVI1" then + st.avi1 = readu8(b, p + 4) + end + elseif m == 0xE1 then + local t, o = exif(b, p, e) + if t and not st.exif then + local x = buffer.create(e - t) + buffer.copy(x, 0, b, t, e - t) + st.exif = x + end + if o then + st.orientation = o + end + elseif m == 0xE2 then + -- ICC_PROFILE\0, sequence number, count, data + if e - p >= 14 and buffer.readstring(b, p, 12) == "ICC_PROFILE\0" then + local seq = readu8(b, p + 12) + local x = buffer.create(e - p - 14) + buffer.copy(x, 0, b, p + 14, e - p - 14) + if seq >= 1 then + iccChunks[seq] = x + end + end + elseif m == 0xEE then + if e - p >= 12 and buffer.readstring(b, p, 5) == "Adobe" then + st.adobe = readu8(b, p + 11) + end + elseif m == 0xFE then + table.insert(st.comments, buffer.readstring(b, p, e - p)) + elseif m == 0xDB then + -- DQT + while p < e do + local pt = readu8(b, p) + local pq, tq = rshift(pt, 4), band(pt, 15) + local size = if pq == 0 then 64 else 128 + if tq > 3 or pq > 1 or p + 1 + size > e then + return nil, "corrupt", "bad DQT segment" + end + local q = buffer.create(128) + for k = 0, 63 do + local v = if pq == 0 then readu8(b, p + 1 + k) else be16(b, p + 1 + k * 2) + buffer.writeu16(q, readu8(Scan.ZIGZAG, k) * 2, v) + end + quant[tq] = q + p += 1 + size + end + elseif m == 0xC4 then + -- DHT + while p < e do + if p + 17 > e then + return nil, "corrupt", "bad DHT segment" + end + local tc = readu8(b, p) + local class, slot = rshift(tc, 4), band(tc, 15) + if class > 1 or slot > 3 then + return nil, "corrupt", "bad DHT table class / slot" + end + local counts, total = {}, 0 + for l = 1, 16 do + counts[l] = readu8(b, p + l) + total += counts[l] + end + if total > 256 or p + 17 + total > e then + return nil, "corrupt", "bad DHT segment" + end + local syms = {} + for i = 1, total do + syms[i] = readu8(b, p + 16 + i) + end + local t = Scan.buildTable(counts, syms) + if class == 0 then + dcT[slot] = t + else + acT[slot] = t + end + p += 17 + total + end + elseif m == 0xCC then + -- DAC: arithmetic conditioning + while p + 2 <= e do + local tc, v = readu8(b, p), readu8(b, p + 1) + local class, slot = rshift(tc, 4), band(tc, 15) + if class > 1 or slot > 3 then + return nil, "corrupt", "bad DAC segment" + end + if class == 0 then + local L, U = band(v, 15), rshift(v, 4) + if L > U then + return nil, "corrupt", "bad DAC value" + end + dcL[slot + 1], dcU[slot + 1] = L, U + else + if v < 1 or v > 63 then + return nil, "corrupt", "bad DAC value" + end + acK[slot + 1] = v + end + p += 2 + end + elseif m == 0xDD then + if e - p < 2 then + return nil, "corrupt", "bad DRI segment" + end + ri = be16(b, p) + elseif m == 0xC0 or m == 0xC1 or m == 0xC2 or m == 0xC9 or m == 0xCA then + if frame then + return nil, "corrupt", "more than one frame header" + end + local f, code, err = parseSof(b, p, e, m) + if not f then + return nil, code, err + end + if f.width * f.height > maxPixels then + return nil, "limit", string.format("%d x %d is over the %d pixel limit", f.width, f.height, maxPixels) + end + frame = f + st.frame = f + if headerOnly then + return st, nil, nil + end + elseif SOF_REFUSED[m] then + return nil, "unsupported", SOF_REFUSED[m] .. " JPEG" + elseif m == 0xDA then + if headerOnly then + break + end + if not frame then + return nil, "corrupt", "scan before the frame header" + end + local f = frame :: Frame + local ns = if p < e then readu8(b, p) else 0 + if ns < 1 or ns > 4 or e - p < 4 + ns * 2 then + return nil, "corrupt", "bad SOS segment" + end + 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) + local comp = nil + for _, c in f.comps do + if c.id == id then + comp = c + end + end + if not comp or table.find(sc, comp) then + return nil, "corrupt", "scan names an unknown component " .. id + end + local td, ta = rshift(t, 4), band(t, 15) + if td > 3 or ta > 3 then + return nil, "corrupt", "bad entropy table selector" + end + comp.dcTbl, comp.acTbl = td, ta + if not f.arithmetic then + comp.dct = dcT[td] or stdTable("dc", td) + comp.act = acT[ta] or stdTable("ac", ta) + end + blocks += comp.h * comp.v + table.insert(sc, comp) + end + local q = p + 1 + ns * 2 + local ss, se, a = readu8(b, q), readu8(b, q + 1), readu8(b, q + 2) + local ah, al = rshift(a, 4), band(a, 15) + if ns > 1 and blocks > 10 then + return nil, "corrupt", "more than 10 blocks per MCU" + end + local mode + if not f.progressive then + mode = 0 + ss, se, ah, al = 0, 63, 0, 0 + else + if se > 63 or ss > se or ah > 13 or al > 13 or (ss == 0 and se ~= 0) or (ss > 0 and ns ~= 1) then + return nil, "corrupt", "bad progressive scan parameters" + end + if ss == 0 then + mode = if ah == 0 then 1 else 2 + else + mode = if ah == 0 then 3 else 4 + end + end + for _, c in sc do + if not f.arithmetic then + if (mode == 0 or mode == 1) and not c.dct then + return nil, "corrupt", "missing DC Huffman table" + end + if (mode == 0 or mode == 3 or mode == 4) and not c.act then + return nil, "corrupt", "missing AC Huffman table" + end + end + if not c.coef then + c.coef = buffer.create(c.bpl * c.bpc * 128) + end + if not c.quant then + c.quant = quant[c.tq] + end + end + if not clean then + clean = buffer.create(n - base + Scan.PAD) + end + local cb = clean :: buffer + local nextPos, cleanLen, nrst = Scan.destuff(b, pos, n, cb, rst) + if nextPos >= n then + st.truncated = true -- no EOI + end + -- a component decoded through the 1x1 IDCT only needs its DC coefficient: skip its AC scans + if not (mode >= 3 and idctSize(f, sc[1], scale) == 1) then + local params = { + comps = sc :: any, + mcusX = f.mcusX, + mcusY = f.mcusY, + ri = ri, + mode = mode, + ss = ss, + se = se, + al = al, + hook = st.hook, + dcL = dcL, + dcU = dcU, + acK = acK, + } + local short + if f.arithmetic then + short = Arith.run(cb, cleanLen, rst, nrst, params) + else + local _ + _, short = Scan.run(cb, cleanLen, rst, nrst, params) + end + st.truncated = st.truncated or short + end + scans += 1 + pos = nextPos + end + end + if not frame then + return nil, if st.truncated then "truncated" else "corrupt", "no frame header" + end + if #iccChunks > 0 then + local total = 0 + for _, c in iccChunks do + total += buffer.len(c) + end + local icc = buffer.create(total) + local o = 0 + for _, c in iccChunks do + buffer.copy(icc, o, c) + o += buffer.len(c) + end + st.icc = icc + end + if headerOnly then + return st, nil, nil + end + if scans == 0 then + return nil, "truncated", "no image data" + end + return st, nil, nil +end + +local SPACE_IDS = { gray = Color.GRAY, ycbcr = Color.YCC, rgb = Color.RGB, cmyk = Color.CMYK, ycck = Color.YCCK } + +local tableCache: { [number]: { buffer } } = {} +local function yccTables(maxv: number): { buffer } + local t = tableCache[maxv] + if not t then + local a, b, c, d = Color.tables(maxv) + t = { a, b, c, d } + tableCache[maxv] = t + end + return t +end + +local toByte12: buffer? = nil + +function Decode.output(st: State): (number?, any, any, string?) + local f: Frame = st.frame + local scale = st.scale + local minSize = 8 // scale + local maxv = if f.precision == 12 then 4095 else 255 + local center = (maxv + 1) // 2 + local p1 = if f.precision == 12 then 1 else 2 + local outW = math.ceil(f.width * minSize / 8) + local outH = math.ceil(f.height * minSize / 8) + local fancy = minSize > 1 + local ccomps = {} + local zeroQ = buffer.create(128) + for _, c in f.comps do + local ssize = idctSize(f, c, scale) + local stride, rows = c.bpl * ssize, c.bpc * ssize + local plane = buffer.create(stride * rows * 2) + local coef = c.coef or buffer.create(c.bpl * c.bpc * 128) + local q = c.quant + if not q then + if c.coef then + return nil, "corrupt", "missing quantisation table " .. c.tq + end + q = zeroQ -- the component never appeared in a scan: mid grey + end + Dct.idctComponent(coef, q :: buffer, c.bpl, c.bpc, ssize, plane, p1, center, maxv, st.hook) + local hIn, hOut = c.h * ssize // minSize, f.hmax + local vIn, vOut = c.v * ssize // minSize, f.vmax + local downW = math.ceil(f.width * c.h * ssize / (f.hmax * 8)) + local downH = math.ceil(f.height * c.v * ssize / (f.vmax * 8)) + local method + if hIn == hOut and vIn == vOut then + method = Color.FULL + elseif hIn * 2 == hOut and vIn * 2 == vOut and fancy and downW > 2 then + method = Color.H2V2 + elseif hIn * 2 == hOut and vIn == vOut and fancy and downW > 2 then + method = Color.H2V1 + elseif hIn == hOut and vIn * 2 == vOut and fancy then + method = Color.H1V2 + else + method = Color.REPLICATE + end + table.insert(ccomps, { + plane = plane, + stride = stride, + rows = rows, + downW = downW, + downH = downH, + method = method, + hIn = hIn, + hOut = hOut, + vIn = vIn, + vOut = vOut, + row = buffer.create((math.max(outW, 2 * stride) + 8) * 2), + }) + c.coef = nil + end + local space = colorSpaceOf(f, st.adobe, st.jfif) + local spaceId = SPACE_IDS[space] + if space == "cmyk" and st.adobe == nil then + spaceId = Color.CMYK_PLAIN + end + if st.raw then + spaceId = Color.RAW + end + local t = yccTables(maxv) + local tb = nil + if maxv == 4095 then + if not toByte12 then + local tbuf = buffer.create(4096) + for v = 0, 4095 do + buffer.writeu8(tbuf, v, (v * 255 + 2047) // 4095) + end + toByte12 = tbuf + end + tb = toByte12 + end + local pixels = buffer.create(outW * outH * 4) + Color.run({ + comps = ccomps, + space = spaceId, + outW = outW, + outH = outH, + maxv = maxv, + pixels = pixels, + crr = t[1], + cbb = t[2], + crg = t[3], + cbg = t[4], + toByte = tb, + hook = st.hook, + }) + return outW, outH, pixels, space +end + +-- outputYuv: 4:2:0, 4:2:2 (chroma row pairs averaged, rounding up), 4:4:4 (2 x 2 averaged, rounding to nearest) or grey +-- (chroma 128) straight from the IDCT planes; full scale only +local scratch: buffer? = nil +local function scratchPlane(n: number): buffer + local sc = scratch + if sc and buffer.len(sc) >= n then + return sc + end + local b = buffer.create(n) + if n <= 4 * 1024 * 1024 then + scratch = b + end + return b +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, nil, nil, nil + end + local comps = f.comps + local space = colorSpaceOf(f, st.adobe, st.jfif) + local mode = nil + if space == "gray" then + mode = "gray" + elseif space == "ycbcr" then + -- the ratios of luma to chroma sampling (ffmpeg writes 4:2:2 as 2x2 / 1x2 and 4:4:4 as 1x2 everywhere) + local l, cb, cr = comps[1], comps[2], comps[3] + if l.h == f.hmax and l.v == f.vmax and cb.h == cr.h and cb.v == cr.v then + local rh, rv = f.hmax // cb.h, f.vmax // cb.v + if rh * cb.h ~= f.hmax or rv * cb.v ~= f.vmax then + mode = nil + elseif rh == 2 and rv == 2 then + mode = "420" + elseif rh == 2 and rv == 1 then + mode = "422" + elseif rh == 1 and rv == 1 then + mode = "444" + end + end + end + if not mode then + return nil, nil, nil, nil + end + for _, c in comps do + if c.coef and not c.quant then + return nil, nil, nil, nil + end + end + local w, h = f.width, f.height + local cw, ch = (w + 1) // 2, (h + 1) // 2 + local out = buffer.create(w * h + 2 * cw * ch) + local zeroQ: buffer? = nil + for i, c in comps do + local stride, rows = c.bpl * 8, c.bpc * 8 + local plane = scratchPlane(stride * rows * 2) + local coef = c.coef or buffer.create(c.bpl * c.bpc * 128) + local q = c.quant + if not q then + zeroQ = zeroQ or buffer.create(128) -- the component never appeared in a scan: mid grey + q = zeroQ + end + Dct.idctComponent(coef, q :: buffer, c.bpl, c.bpc, 8, plane, 2, 128, 255, st.hook) + if i == 1 then + Yuv.crop(plane, stride, w, h, out, 0) + elseif mode == "420" then + Yuv.crop(plane, stride, cw, ch, out, w * h + (i - 2) * cw * ch) + elseif mode == "422" then + Yuv.rows(plane, stride, cw, h, out, w * h + (i - 2) * cw * ch) + else + Yuv.box(plane, stride, w, h, out, w * h + (i - 2) * cw * ch) + end + c.coef = nil + end + if mode == "gray" then + buffer.fill(out, w * h, 128, 2 * cw * ch) + end + return w, h, out, mode +end + +return Decode +end +__FILES["codecs/image/Jpeg/Encode"] = @native function() + + + +-- codecs/image/Jpeg/Encode: the JPEG encoder, baseline (SOF0) and progressive (SOF2, jpeg_simple_progression). +-- Follows libjpeg-turbo step for step (jccolor.c, jcsample.c, jccoefct.c, jfdctint.c / jcdctmgr.c, jchuff.c, jcphuff.c) +-- so its output is byte-identical to cjpeg's; Luau translation of IJG code: licenses/libjpeg-turbo-LICENSE.md. +local Dct = __include("codecs/image/Dct") +local Tables = __include("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 + +local Encode = {} + +-- natural order index of zigzag position k +local ZZ = buffer.create(64) +do + local i = 0 + for s = 0, 14 do + local lo, hi = math.max(0, s - 7), math.min(s, 7) + if s % 2 == 0 then + for r = hi, lo, -1 do + writeu8(ZZ, i, r * 8 + (s - r)) + i += 1 + end + else + for r = lo, hi do + writeu8(ZZ, i, r * 8 + (s - r)) + i += 1 + end + end + end +end +Encode.ZIGZAG = ZZ + +local OUT = buffer.create(0) +local OP = 0 +local CAP = 0 +local ACC, NB = 0, 0 +local GATHER = false + +@native local function grow(n: number) + if OP + n > CAP then + local c = math.max(CAP * 2, OP + n + 1024) + local nb = buffer.create(c) + buffer.copy(nb, 0, OUT, 0, OP) + OUT = nb + CAP = c + end +end + +@native local function byte(v: number) + grow(1) + writeu8(OUT, OP, v) + OP += 1 +end + +@native local function u16be(v: number) + byte(v // 256) + byte(v % 256) +end + +-- n bits of v (n <= 16), MSB first, with 0xFF stuffing +@native local function bits(v: number, n: number) + if GATHER or n == 0 then + return + end + local p = 2 ^ n + ACC = ACC * p + band(v, p - 1) + NB += n + while NB >= 8 do + NB -= 8 + local d = 2 ^ NB + local b = ACC // d + ACC -= b * d + grow(2) + writeu8(OUT, OP, b) + OP += 1 + if b == 0xFF then + writeu8(OUT, OP, 0) + OP += 1 + end + end +end + +@native local function flushBits() + if NB > 0 then + bits(0x7F, 8 - NB) -- pad with ones + end + ACC, NB = 0, 0 +end + +@native local function nbits(v: number): number + return if v == 0 then 0 else 32 - countlz(v) +end + +-- a derived table: u16 code + u8 size per symbol (jpeg_make_c_derived_tbl) +type Derived = { code: buffer, size: buffer } + +@native local function derive(counts: { number }, symbols: { number }): Derived + local code, size = buffer.create(512), buffer.create(256) + local c, k = 0, 1 + for l = 1, 16 do + for _ = 1, counts[l] or 0 do + local s = symbols[k] + if s then + writeu16(code, s * 2, c) + writeu8(size, s, l) + end + k += 1 + c += 1 + end + c *= 2 + end + return { code = code, size = size } +end + +-- jchuff.c jpeg_gen_optimal_table: freq (0..256, 1-based +1) -> counts, symbols +@native local function optimal(freqIn: { number }): ({ number }, { number }) + local freq = table.create(257, 0) + local bitsT = table.create(34, 0) + local codesize = table.create(257, 0) + local others = table.create(257, -1) + local nz = table.create(257, 0) + local n = 0 + for i = 0, 256 do + local f = if i == 256 then 1 else freqIn[i + 1] + if f > 0 then + n += 1 + nz[n] = i + freq[n] = f + end + end + while true do + local c1, c2 = -1, -1 + local v, v2 = 1e9, 1e9 + for i = 1, n do + local f = freq[i] + if f <= v2 then + if f <= v then + c2 = c1 + v2 = v + v = f + c1 = i + else + v2 = f + c2 = i + end + end + end + if c2 < 0 then + break + end + freq[c1] += freq[c2] + freq[c2] = 1000000001 + codesize[c1] += 1 + while others[c1] >= 0 do + c1 = others[c1] + codesize[c1] += 1 + end + others[c1] = c2 + codesize[c2] += 1 + while others[c2] >= 0 do + c2 = others[c2] + codesize[c2] += 1 + end + end + for i = 1, n do + local cs = math.min(codesize[i], 32) + bitsT[cs + 1] += 1 + end + local bitPos = table.create(34, 0) + local p = 0 + for i = 1, 32 do + bitPos[i + 1] = p + p += bitsT[i + 1] + end + local i = 32 + while i > 16 do + while bitsT[i + 1] > 0 do + local j = i - 2 + while bitsT[j + 1] == 0 do + j -= 1 + end + bitsT[i + 1] -= 2 + bitsT[i] += 1 + bitsT[j + 2] += 2 + bitsT[j + 1] -= 1 + end + i -= 1 + end + while bitsT[i + 1] == 0 do + i -= 1 + end + bitsT[i + 1] -= 1 + local counts = table.create(16, 0) + for l = 1, 16 do + counts[l] = bitsT[l + 1] + end + local symbols = table.create(n, 0) + for k = 1, n - 1 do + local cs = math.min(codesize[k], 32) + symbols[bitPos[cs + 1] + 1] = nz[k] + bitPos[cs + 1] += 1 + end + local total = 0 + for l = 1, 16 do + total += counts[l] + end + local out = table.create(total, 0) + for k = 1, total do + out[k] = symbols[k] + end + return counts, out +end +Encode.optimal = optimal + +local dcTab: { Derived } = {} +local acTab: { Derived } = {} +local dcFreq: { { number } } = {} +local acFreq: { { number } } = {} + +@native local function symbol(t: Derived, freq: { number }, s: number) + if GATHER then + freq[s + 1] += 1 + else + bits(readu16(t.code, s * 2), readu8(t.size, s)) + end +end + +type Comp = { + id: number, + h: number, + v: number, + tq: number, + td: number, + ta: number, + bw: number, + bh: number, + bpl: number, + bpc: number, + coef: buffer, + last: number, +} + +@native local function dcDiff(c: Comp, diff: number) + local t = diff + local t2 = diff + if t < 0 then + t = -t + t2 -= 1 + end + local n = nbits(t) + symbol(dcTab[c.td + 1], dcFreq[c.td + 1], n) + if n > 0 then + bits(t2, n) + end +end + +-- jchuff.c encode_one_block +@native local function blockSeq(c: Comp, off: number) + local coef = c.coef + local dc = readi16(coef, off) + dcDiff(c, dc - c.last) + c.last = dc + local at, af = acTab[c.ta + 1], acFreq[c.ta + 1] + local r = 0 + for k = 1, 63 do + local v = readi16(coef, off + readu8(ZZ, k) * 2) + if v == 0 then + r += 1 + else + while r > 15 do + symbol(at, af, 0xF0) + r -= 16 + end + local t, t2 = v, v + if t < 0 then + t = -t + t2 -= 1 + end + local n = nbits(t) + symbol(at, af, r * 16 + n) + bits(t2, n) + r = 0 + end + end + if r > 0 then + symbol(at, af, 0) + end +end + +-- progressive state (jcphuff.c) +local EOBRUN = 0 +local BE = 0 +local CORR = table.create(1000, 0) :: { number } +local curAc: Derived = { code = buffer.create(512), size = buffer.create(256) } +local curAcFreq: { number } = {} + +@native local function emitEobrun() + if EOBRUN > 0 then + local n = nbits(EOBRUN) - 1 + symbol(curAc, curAcFreq, n * 16) + if n > 0 then + bits(EOBRUN, n) + end + EOBRUN = 0 + if not GATHER then + for i = 1, BE do + bits(CORR[i], 1) + end + end + BE = 0 + end +end + +@native local function blockDcFirst(c: Comp, off: number, al: number) + local t2 = readi16(c.coef, off) // 2 ^ al + dcDiff(c, t2 - c.last) + c.last = t2 +end + +@native local function blockAcFirst(c: Comp, off: number, ss: number, se: number, al: number) + local coef = c.coef + local d = 2 ^ al + local r = 0 + for k = ss, se do + local v = readi16(coef, off + readu8(ZZ, k) * 2) + local t, t2 + if v < 0 then + t = (-v) // d + t2 = -t - 1 -- ~t + else + t = v // d + t2 = t + end + if t == 0 then + r += 1 + else + emitEobrun() + while r > 15 do + symbol(curAc, curAcFreq, 0xF0) + r -= 16 + end + local n = nbits(t) + symbol(curAc, curAcFreq, r * 16 + n) + bits(t2, n) + r = 0 + end + end + if r > 0 then + EOBRUN += 1 + if EOBRUN == 0x7FFF then + emitEobrun() + end + end +end + +local absv = table.create(64, 0) + +@native local function blockAcRefine(c: Comp, off: number, ss: number, se: number, al: number) + local coef = c.coef + local d = 2 ^ al + local eob = 0 + for k = ss, se do + local v = readi16(coef, off + readu8(ZZ, k) * 2) + local t = (if v < 0 then -v else v) // d + absv[k + 1] = t + if t == 1 then + eob = k + end + end + local r = 0 + local br = 0 + local brStart = BE + for k = ss, se do + local t = absv[k + 1] + if t == 0 then + r += 1 + continue + end + while r > 15 and k <= eob do + emitEobrun() + symbol(curAc, curAcFreq, 0xF0) + r -= 16 + if not GATHER then + for i = 1, br do + bits(CORR[brStart + i], 1) + end + end + brStart = 0 + br = 0 + end + if t > 1 then + br += 1 + CORR[brStart + br] = t % 2 + continue + end + emitEobrun() + symbol(curAc, curAcFreq, r * 16 + 1) + bits(if readi16(coef, off + readu8(ZZ, k) * 2) < 0 then 0 else 1, 1) + if not GATHER then + for i = 1, br do + bits(CORR[brStart + i], 1) + end + end + brStart = 0 + br = 0 + r = 0 + end + if r > 0 or br > 0 then + EOBRUN += 1 + BE += br + if EOBRUN == 0x7FFF or BE > 1000 - 64 + 1 then + emitEobrun() + end + end +end + +type ScanSpec = { comps: { number }, ss: number, se: number, ah: number, al: number } + +@native local function walk(comps: { Comp }, mcusX: number, mcusY: number, ri: number, onRestart: (number) -> (), fn: (Comp, number) -> ()) + local nc = #comps + local units, ux + if nc == 1 then + ux = comps[1].bw + units = ux * comps[1].bh + else + ux = mcusX + units = ux * mcusY + end + local rn = 0 + for u = 0, units - 1 do + if ri > 0 and u > 0 and u % ri == 0 then + onRestart(rn) + rn = (rn + 1) % 8 + end + local my, mx = u // ux, u % ux + for ci = 1, nc do + local c = comps[ci] + if nc == 1 then + fn(c, (my * c.bpl + mx) * 128) + else + for by = my * c.v, my * c.v + c.v - 1 do + for bx = mx * c.h, mx * c.h + c.h - 1 do + fn(c, (by * c.bpl + bx) * 128) + end + end + end + end + end +end + +@native local function dht(class: number, slot: number, counts: { number }, symbols: { number }) + byte(0xFF) + byte(0xC4) + u16be(2 + 17 + #symbols) + byte(class * 16 + slot) + for l = 1, 16 do + byte(counts[l]) + end + for _, s in symbols do + byte(s) + end +end + +@native local function sos(comps: { Comp }, ss: number, se: number, ah: number, al: number, dcOnly: boolean, acOnly: boolean) + byte(0xFF) + byte(0xDA) + u16be(6 + 2 * #comps) + byte(#comps) + for _, c in comps do + byte(c.id) + local td = if acOnly then 0 else c.td + local ta = if dcOnly then 0 else c.ta + byte(td * 16 + ta) + end + byte(ss) + byte(se) + byte(ah * 16 + al) +end + +-- jccolor.c rgb_ycc_start tables (16-bit fixed point) +@native local function fix(x: number): number + return math.floor(x * 65536 + 0.5) +end +local YR, YG, YB = fix(0.29900), fix(0.58700), fix(0.11400) +local CBR, CBG, HALF = fix(0.16874), fix(0.33126), fix(0.5) +local CRG, CRB = fix(0.41869), fix(0.08131) +local OFF = 128 * 65536 + 32768 - 1 + +@native local function planes(px: buffer, w: number, h: number, bpp: number, gray: boolean): (buffer, buffer?, buffer?) + local n = w * h + local Y = buffer.create(n) + if bpp == 1 then + buffer.copy(Y, 0, px, 0, n) + if gray then + return Y, nil, nil + end + local Cb = buffer.create(n) + buffer.fill(Cb, 0, 128, n) + local Cr = buffer.create(n) + buffer.fill(Cr, 0, 128, n) + return Y, Cb, Cr + end + if gray then + for i = 0, n - 1 do + local o = i * bpp + local r, g, b = readu8(px, o), readu8(px, o + 1), readu8(px, o + 2) + writeu8(Y, i, (YR * r + YG * g + YB * b + 32768) // 65536) + end + return Y, nil, nil + end + local Cb, Cr = buffer.create(n), buffer.create(n) + for i = 0, n - 1 do + local o = i * bpp + local r, g, b = readu8(px, o), readu8(px, o + 1), readu8(px, o + 2) + writeu8(Y, i, (YR * r + YG * g + YB * b + 32768) // 65536) + writeu8(Cb, i, (-CBR * r - CBG * g + HALF * b + OFF) // 65536) + writeu8(Cr, i, (HALF * r - CRG * g - CRB * b + OFF) // 65536) + end + return Y, Cb, Cr +end + +-- jcsample.c downsampling: columns past w - 1 repeat the last one, rows past h - 1 the last row +@native local function downsample(src: buffer, w: number, h: number, hf: number, vf: number, outW: number, outH: number): buffer + local out = buffer.create(outW * outH) + for oy = 0, outH - 1 do + local r0 = math.min(oy * vf, h - 1) * w + local r1 = math.min(oy * vf + vf - 1, h - 1) * w + local bias = if hf == 2 and vf == 2 then 1 elseif hf == 2 then 0 else (if vf == 2 then 1 else 0) + for ox = 0, outW - 1 do + local x0 = math.min(ox * hf, w - 1) + local x1 = math.min(ox * hf + hf - 1, w - 1) + local v + if hf == 2 and vf == 2 then + v = (readu8(src, r0 + x0) + readu8(src, r0 + x1) + readu8(src, r1 + x0) + readu8(src, r1 + x1) + bias) // 4 + bias = 3 - bias + elseif hf == 2 then + v = (readu8(src, r0 + x0) + readu8(src, r0 + x1) + bias) // 2 + bias = 1 - bias + else + v = (readu8(src, r0 + x0) + readu8(src, r1 + x0) + bias) // 2 + bias = 1 - bias + end + writeu8(out, oy * outW + ox, v) + end + end + return out +end + +type Options = { + quality: number, + sampling: string, + progressive: boolean, + optimize: boolean, + gray: boolean, + restart: number, + segments: { { marker: number, data: buffer } }, + jfif: boolean, + density: { unit: number, x: number, y: number }?, +} + +@native function Encode.run(px: buffer, w: number, h: number, bpp: number, o: Options): buffer + OUT = buffer.create(math.max(1024, w * h // 2)) + CAP = buffer.len(OUT) + OP = 0 + ACC, NB = 0, 0 + GATHER = false + EOBRUN, BE = 0, 0 + + local yuv = bpp == 0 + local Y, Cb, Cr + if yuv then + local n, cn = w * h, ((w + 1) // 2) * ((h + 1) // 2) + Y = px + if not o.gray then + Cb, Cr = buffer.create(cn), buffer.create(cn) + buffer.copy(Cb :: buffer, 0, px, n, cn) + buffer.copy(Cr :: buffer, 0, px, n + cn, cn) + end + else + Y, Cb, Cr = planes(px, w, h, bpp, o.gray) + end + local hs, vs = 1, 1 + if not o.gray then + if o.sampling == "420" then + hs, vs = 2, 2 + elseif o.sampling == "422" then + hs, vs = 2, 1 + end + end + local mcusX = math.ceil(w / (8 * hs)) + local mcusY = math.ceil(h / (8 * vs)) + local qt = { Tables.quant(Tables.LUMA, o.quality), Tables.quant(Tables.CHROMA, o.quality) } + local qdiv = {} + for t = 1, 2 do + local b = buffer.create(128) + for i = 1, 64 do + writeu16(b, (i - 1) * 2, qt[t][i]) + end + qdiv[t] = b + end + + local comps: { Comp } = {} + local srcs = if o.gray then { Y } else { Y, Cb :: buffer, Cr :: buffer } + for i, src in srcs do + local ch, cv = if i == 1 then hs else 1, if i == 1 then vs else 1 + local cw = math.ceil(w * ch / hs) + local chh = math.ceil(h * cv / vs) + local bw, bh = math.ceil(cw / 8), math.ceil(chh / 8) + local bpl, bpc = mcusX * ch, mcusY * cv + local plane, pw, ph = src, w, h + if yuv and i > 1 then + pw, ph = (w + 1) // 2, (h + 1) // 2 -- already 4:2:0: fdctQuantize repeats the edges as jcsample.c does + elseif ch < hs or cv < vs then + pw, ph = bw * 8, chh + plane = downsample(src, w, h, hs // ch, vs // cv, pw, ph) + end + local coef = buffer.create(bpl * bpc * 128) + local c: Comp = { + id = i, + h = ch, + v = cv, + tq = if i == 1 then 0 else 1, + td = if i == 1 then 0 else 1, + ta = if i == 1 then 0 else 1, + bw = bw, + bh = bh, + bpl = bpl, + bpc = bpc, + coef = coef, + last = 0, + } + local div = qdiv[c.tq + 1] + for by = 0, bpc - 1 do + for bx = 0, bpl - 1 do + local off = (by * bpl + bx) * 128 + if by < bh and bx < bw then + Dct.fdctQuantize(plane, pw, bx * 8, by * 8, pw, ph, div, coef, off) + elseif by < bh then + writei16(coef, off, readi16(coef, off - 128)) -- right edge: the previous block's DC + else + -- bottom: the DC of the MCU's last block in the row above + local lb = (bx // ch) * ch + ch - 1 + writei16(coef, off, readi16(coef, ((by - 1) * bpl + lb) * 128)) + end + end + end + comps[i] = c + end + + byte(0xFF) + byte(0xD8) + if o.jfif then + local d = o.density or { unit = 0, x = 1, y = 1 } + byte(0xFF) + byte(0xE0) + u16be(16) + for _, ch in { 0x4A, 0x46, 0x49, 0x46, 0 } do + byte(ch) + end + byte(1) + byte(1) + byte(d.unit) + u16be(d.x) + u16be(d.y) + byte(0) + byte(0) + end + for _, s in o.segments do + local n = buffer.len(s.data) + byte(0xFF) + byte(s.marker) + u16be(n + 2) + grow(n) + buffer.copy(OUT, OP, s.data, 0, n) + OP += n + end + for t = 1, (if o.gray then 1 else 2) do + byte(0xFF) + byte(0xDB) + u16be(67) + byte(t - 1) + for k = 0, 63 do + byte(qt[t][readu8(ZZ, k) + 1]) + end + end + byte(0xFF) + byte(if o.progressive then 0xC2 else 0xC0) + u16be(8 + 3 * #comps) + byte(8) + u16be(h) + u16be(w) + byte(#comps) + for _, c in comps do + byte(c.id) + byte(c.h * 16 + c.v) + byte(c.tq) + end + local ntab = if o.gray then 1 else 2 + + @native local function restartMarker(n: number) + flushBits() + byte(0xFF) + byte(0xD0 + n) + end + + if not o.progressive then + if o.optimize then + GATHER = true + for t = 1, ntab do + dcFreq[t] = table.create(257, 0) + acFreq[t] = table.create(257, 0) + end + for _, c in comps do + c.last = 0 + end + walk(comps, mcusX, mcusY, o.restart, @native function() + for _, c in comps do + c.last = 0 + end + end, blockSeq) + GATHER = false + end + for t = 1, ntab do + local dcC, dcS, acC, acS + if o.optimize then + dcC, dcS = optimal(dcFreq[t]) + acC, acS = optimal(acFreq[t]) + else + local d, a = Tables.DC[t], Tables.AC[t] + dcC, dcS, acC, acS = d.counts, d.symbols, a.counts, a.symbols + end + dcTab[t] = derive(dcC, dcS) + acTab[t] = derive(acC, acS) + dcFreq[t] = table.create(257, 0) + acFreq[t] = table.create(257, 0) + -- libjpeg emits each table before the scan in component order: DC0, AC0, DC1, AC1 + dht(0, t - 1, dcC, dcS) + dht(1, t - 1, acC, acS) + end + if o.restart > 0 then + byte(0xFF) + byte(0xDD) + u16be(4) + u16be(o.restart) + end + sos(comps, 0, 63, 0, 0, false, false) + for _, c in comps do + c.last = 0 + end + walk(comps, mcusX, mcusY, o.restart, @native function(n: number) + restartMarker(n) + for _, c in comps do + c.last = 0 + end + end, blockSeq) + flushBits() + else + local script: { ScanSpec } + if o.gray then + script = { + { comps = { 1 }, ss = 0, se = 0, ah = 0, al = 1 }, + { comps = { 1 }, ss = 1, se = 5, ah = 0, al = 2 }, + { comps = { 1 }, ss = 6, se = 63, ah = 0, al = 2 }, + { comps = { 1 }, ss = 1, se = 63, ah = 2, al = 1 }, + { comps = { 1 }, ss = 0, se = 0, ah = 1, al = 0 }, + { comps = { 1 }, ss = 1, se = 63, ah = 1, al = 0 }, + } + else + script = { + { comps = { 1, 2, 3 }, ss = 0, se = 0, ah = 0, al = 1 }, + { comps = { 1 }, ss = 1, se = 5, ah = 0, al = 2 }, + { comps = { 3 }, ss = 1, se = 63, ah = 0, al = 1 }, + { comps = { 2 }, ss = 1, se = 63, ah = 0, al = 1 }, + { comps = { 1 }, ss = 6, se = 63, ah = 0, al = 2 }, + { comps = { 1 }, ss = 1, se = 63, ah = 2, al = 1 }, + { comps = { 1, 2, 3 }, ss = 0, se = 0, ah = 1, al = 0 }, + { comps = { 3 }, ss = 1, se = 63, ah = 1, al = 0 }, + { comps = { 2 }, ss = 1, se = 63, ah = 1, al = 0 }, + { comps = { 1 }, ss = 1, se = 63, ah = 1, al = 0 }, + } + end + local driSent = false + for _, sc in script do + local sComps: { Comp } = {} + for _, ci in sc.comps do + table.insert(sComps, comps[ci]) + end + local ss, se, ah, al = sc.ss, sc.se, sc.ah, sc.al + local isDc = ss == 0 + local blockFn: (Comp, number) -> () + if isDc and ah == 0 then + blockFn = @native function(c: Comp, off: number) + blockDcFirst(c, off, al) + end + elseif isDc then + blockFn = @native function(c: Comp, off: number) + bits(band(readi16(c.coef, off) // 2 ^ al, 1), 1) + end + elseif ah == 0 then + blockFn = @native function(c: Comp, off: number) + blockAcFirst(c, off, ss, se, al) + end + else + blockFn = @native function(c: Comp, off: number) + blockAcRefine(c, off, ss, se, al) + end + end + @native local function onRestart(n: number) + emitEobrun() + if not GATHER then + restartMarker(n) + end + for _, c in sComps do + c.last = 0 + end + EOBRUN, BE = 0, 0 + end + @native local function pass() + for _, c in sComps do + c.last = 0 + end + EOBRUN, BE = 0, 0 + walk(sComps, mcusX, mcusY, o.restart, onRestart, blockFn) + emitEobrun() + end + if not (isDc and ah > 0) then + GATHER = true + for t = 1, ntab do + dcFreq[t] = table.create(257, 0) + acFreq[t] = table.create(257, 0) + end + if not isDc then + curAcFreq = acFreq[sComps[1].ta + 1] + end + pass() + GATHER = false + local sent = {} + for _, c in sComps do + local slot = if isDc then c.td else c.ta + if not sent[slot] then + sent[slot] = true + local counts, syms = optimal(if isDc then dcFreq[slot + 1] else acFreq[slot + 1]) + dht(if isDc then 0 else 1, slot, counts, syms) + if isDc then + dcTab[slot + 1] = derive(counts, syms) + else + acTab[slot + 1] = derive(counts, syms) + end + end + end + if not isDc then + curAc = acTab[sComps[1].ta + 1] + end + end + if o.restart > 0 and not driSent then + driSent = true + byte(0xFF) + byte(0xDD) + u16be(4) + u16be(o.restart) + end + sos(sComps, ss, se, ah, al, isDc, not isDc or ah > 0) -- DC refinement uses no table: td = 0 (as libjpeg) + pass() + flushBits() + end + end + byte(0xFF) + byte(0xD9) + local res = buffer.create(OP) + buffer.copy(res, 0, OUT, 0, OP) + OUT = buffer.create(0) + CAP = 0 + return res +end + +return Encode +end +__FILES["codecs/image/Jpeg/Scan"] = @native function() + + + +-- codecs/image/Jpeg/Scan: Huffman-coded scan decoding into quantised DCT coefficients. From jpeg-luau 1.0 (same author). +-- The clean scan data is followed by PAD zero bytes, so the 32-bit big-endian bit reader needs no bounds check. +-- Huffman tables (built by `buildTable`) are buffers: +-- [0, 1024) fast lookup by the next 9 bits: u16 (length << 8) | symbol, 0 = longer code +-- [1024, 1096) maxcode[l], l = 0..17: u32, one past the last code of length l, left-aligned to 16 bits +-- [1096, 1168) delta[l]: i32, symbol index = code + delta[l] +-- [1168, 1424) symbols +-- [1424, 1426) symbol count +-- [1428, 3476) fast AC lookup by the next 9 bits: i32 value * 256 + run * 16 + total length, when the code +-- and its extra bits fit in 9 bits (0 otherwise) +local readu8, readu16, readu32, readi32, readi16 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi32, buffer.readi16 +local writeu8, writeu16, writeu32, writei32, writei16 = buffer.writeu8, buffer.writeu16, buffer.writeu32, buffer.writei32, buffer.writei16 +local band, bor, lshift, rshift, byteswap = bit32.band, bit32.bor, bit32.lshift, bit32.rshift, bit32.byteswap + +local Scan = {} + +Scan.PAD = 4096 +Scan.TABLE_SIZE = 3476 + +local T_MAX = 1024 +local T_DELTA = 1096 +local T_VAL = 1168 +local T_COUNT = 1424 +local T_FASTAC = 1428 + +-- zigzag index -> natural (row-major) index, padded with 63s so a run past the end stays in range +local ZZ = buffer.create(80) +do + local i = 0 + for s = 0, 14 do + local lo, hi = math.max(0, s - 7), math.min(s, 7) + if s % 2 == 0 then + for r = hi, lo, -1 do + writeu8(ZZ, i, r * 8 + (s - r)) + i += 1 + end + else + for r = lo, hi do + writeu8(ZZ, i, r * 8 + (s - r)) + i += 1 + end + end + end + for j = 64, 79 do + writeu8(ZZ, j, 63) + end +end +Scan.ZIGZAG = ZZ + +-- an over-subscribed table keeps the codes that fit; the rest decode as invalid +@native function Scan.buildTable(counts: { number }, symbols: { number }): buffer + local t = buffer.create(Scan.TABLE_SIZE) + local code, k = 0, 0 + local nsym = #symbols + local codes, sizes = {}, {} + local broken = false + for l = 1, 16 do + writei32(t, T_DELTA + l * 4, k - code) + local n = counts[l] or 0 + for _ = 1, n do + if broken or code >= lshift(1, l) or k >= nsym or k >= 256 then + broken = true + break + end + k += 1 + codes[k] = code + sizes[k] = l + code += 1 + end + writeu32(t, T_MAX + l * 4, if broken then 0 else lshift(code, 16 - l)) + code *= 2 + end + writeu32(t, T_MAX + 17 * 4, 0xFFFFFFFF) + for i = 1, k do + writeu8(t, T_VAL + i - 1, symbols[i]) + end + writeu16(t, T_COUNT, k) + for i = 1, k do + local l = sizes[i] + if l <= 9 then + local sym = symbols[i] + local base = lshift(codes[i], 9 - l) + for j = 0, lshift(1, 9 - l) - 1 do + local idx = base + j + writeu16(t, idx * 2, l * 256 + sym) + local r, s = rshift(sym, 4), band(sym, 15) + if s ~= 0 and l + s <= 9 then + local v = band(rshift(idx, 9 - l - s), lshift(1, s) - 1) + if v < lshift(1, s - 1) then + v = v - lshift(1, s) + 1 + end + writei32(t, T_FASTAC + idx * 4, v * 256 + r * 16 + l + s) + end + end + end + end + return t +end + +@native function Scan.destuff(src: buffer, pos: number, n: number, dst: buffer, rst: { number }): (number, number, number) + local o, nr = 0, 0 + while pos < n do + local b = readu8(src, pos) + if b ~= 0xFF then + writeu8(dst, o, b) + o += 1 + pos += 1 + else + local q = pos + 1 + while q < n and readu8(src, q) == 0xFF do + q += 1 + end + if q >= n then + pos = n + break + end + local m = readu8(src, q) + if m == 0 then + writeu8(dst, o, 0xFF) + o += 1 + pos = q + 1 + elseif m >= 0xD0 and m <= 0xD7 then + nr += 1 + rst[nr] = o + pos = q + 1 + else + pos = q - 1 + break + end + end + end + buffer.fill(dst, o, 0, Scan.PAD) + return pos, o, nr +end + +@native local function huff(d: buffer, pos: number, t: buffer): (number, number) + local w = lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)) + local f = readu16(t, rshift(w, 23) * 2) + if f ~= 0 then + return band(f, 255), pos + rshift(f, 8) + end + local c = rshift(w, 16) + local l = 10 + while c >= readu32(t, T_MAX + l * 4) do + l += 1 + end + if l > 16 then + return 0, pos + 16 -- invalid code + end + local idx = rshift(c, 16 - l) + readi32(t, T_DELTA + l * 4) + if idx < 0 or idx >= readu16(t, T_COUNT) then + return 0, pos + l + end + return readu8(t, T_VAL + idx), pos + l +end + +@native local function bits(d: buffer, pos: number, s: number): number + return rshift(lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)), 32 - s) +end + +@native local function extend(v: number, s: number): number + if v < lshift(1, s - 1) then + return v - lshift(1, s) + 1 + end + return v +end + +@native local function blockSeq(d: buffer, pos: number, coef: buffer, off: number, dct: buffer, act: buffer, pred: number): (number, number) + local s + s, pos = huff(d, pos, dct) + if s ~= 0 then + if s > 16 then + s = 16 + end + pred += extend(bits(d, pos, s), s) + pos += s + end + writei16(coef, off, pred) + local k = 1 + while k < 64 do + local w = lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)) + local fa = readi32(act, T_FASTAC + rshift(w, 23) * 4) + if fa ~= 0 then + local low = fa % 256 + k += low // 16 + pos += low % 16 + if k > 63 then + break + end + writei16(coef, off + readu8(ZZ, k) * 2, fa // 256) + k += 1 + else + local rs + rs, pos = huff(d, pos, act) + local r, sz = rshift(rs, 4), band(rs, 15) + if sz == 0 then + if r ~= 15 then + break + end + k += 16 + else + k += r + if k > 63 then + break + end + writei16(coef, off + readu8(ZZ, k) * 2, extend(bits(d, pos, sz), sz)) + pos += sz + k += 1 + end + end + end + return pos, pred +end + +@native local function blockDcFirst(d: buffer, pos: number, coef: buffer, off: number, dct: buffer, pred: number, al: number): (number, number) + local s + s, pos = huff(d, pos, dct) + if s ~= 0 then + if s > 16 then + s = 16 + end + pred += extend(bits(d, pos, s), s) + pos += s + end + writei16(coef, off, pred * lshift(1, al)) + return pos, pred +end + +@native local function blockAcFirst(d: buffer, pos: number, coef: buffer, off: number, act: buffer, ss: number, se: number, al: number, eobrun: number): (number, number) + if eobrun > 0 then + return pos, eobrun - 1 + end + local mul = lshift(1, al) + local k = ss + while k <= se do + local w = lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)) + local fa = readi32(act, T_FASTAC + rshift(w, 23) * 4) + if fa ~= 0 then + local low = fa % 256 + k += low // 16 + pos += low % 16 + if k > se then + break + end + writei16(coef, off + readu8(ZZ, k) * 2, (fa // 256) * mul) + k += 1 + else + local rs + rs, pos = huff(d, pos, act) + local r, s = rshift(rs, 4), band(rs, 15) + if s == 0 then + if r < 15 then + eobrun = lshift(1, r) - 1 + if r > 0 then + eobrun += bits(d, pos, r) + pos += r + end + break + end + k += 16 + else + k += r + if k > se then + break + end + writei16(coef, off + readu8(ZZ, k) * 2, extend(bits(d, pos, s), s) * mul) + pos += s + k += 1 + end + end + end + return pos, eobrun +end + +-- successive-approximation refinement of AC coefficients ss..se (as stb_image / libjpeg decode_mcu_AC_refine) +@native local function blockAcRefine(d: buffer, pos: number, coef: buffer, off: number, act: buffer, ss: number, se: number, al: number, eobrun: number): (number, number) + local bit = lshift(1, al) + if eobrun > 0 then + for k = ss, se do + local o = off + readu8(ZZ, k) * 2 + local p = readi16(coef, o) + if p ~= 0 then + local b = rshift(lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)), 31) + pos += 1 + if b ~= 0 and band(p, bit) == 0 then + writei16(coef, o, if p > 0 then p + bit else p - bit) + end + end + end + return pos, eobrun - 1 + end + local k = ss + while k <= se do + local rs + rs, pos = huff(d, pos, act) + local s, r = band(rs, 15), rshift(rs, 4) + local val = 0 + if s == 0 then + if r < 15 then + eobrun = lshift(1, r) - 1 + if r > 0 then + eobrun += bits(d, pos, r) + pos += r + end + r = 64 -- the rest of the block only refines + end + else + -- s must be 1; anything else is corrupt and treated as 1 + local b = rshift(lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)), 31) + pos += 1 + val = if b ~= 0 then bit else -bit + end + while k <= se do + local o = off + readu8(ZZ, k) * 2 + k += 1 + local p = readi16(coef, o) + if p ~= 0 then + local b = rshift(lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)), 31) + pos += 1 + if b ~= 0 and band(p, bit) == 0 then + writei16(coef, o, if p > 0 then p + bit else p - bit) + end + else + if r == 0 then + if val ~= 0 then + writei16(coef, o, val) + end + break + end + r -= 1 + end + end + end + -- an EOB run that started in this block counts it already (eobrun = run length - 1) + return pos, eobrun +end + +type ScanComp = { + coef: buffer, + bpl: number, + h: number, + v: number, + bw: number, + bh: number, + dct: buffer?, + act: buffer?, + pred: number, +} + +type ScanParams = { + comps: { ScanComp }, + mcusX: number, + mcusY: number, + ri: number, + mode: number, + ss: number, + se: number, + al: number, + hook: (() -> ())?, +} + +@native function Scan.run(d: buffer, cleanLen: number, rst: { number }, nrst: number, P: ScanParams): (number, boolean) + local comps = P.comps + local nc = #comps + local mode, ss, se, al, ri = P.mode, P.ss, P.se, P.al, P.ri + local endBits = cleanLen * 8 + local units, ux + if nc == 1 then + ux = comps[1].bw + units = ux * comps[1].bh + else + ux = P.mcusX + units = ux * P.mcusY + end + for i = 1, nc do + comps[i].pred = 0 + end + local pos, eobrun, rstIdx = 0, 0, 0 + local truncated, skipping = false, false + local bit = lshift(1, al) + local hook = P.hook + for u = 0, units - 1 do + if hook and u > 0 and u % ux == 0 then + pcall(hook) + end + if ri > 0 and u > 0 and u % ri == 0 then + rstIdx += 1 + if rstIdx <= nrst then + pos = rst[rstIdx] * 8 + skipping = false + end + for i = 1, nc do + comps[i].pred = 0 + end + eobrun = 0 + end + if pos > endBits then + truncated = true + if ri == 0 or rstIdx >= nrst then + break + end + skipping = true + end + if not skipping then + local my, mx = u // ux, u % ux + for ci = 1, nc do + local c = comps[ci] + local bh, bw, by0, bx0 + if nc == 1 then + bh, bw, by0, bx0 = 1, 1, my, mx + else + bh, bw, by0, bx0 = c.v, c.h, my * c.v, mx * c.h + end + local coef, bpl = c.coef, c.bpl + for by = by0, by0 + bh - 1 do + for bx = bx0, bx0 + bw - 1 do + local off = (by * bpl + bx) * 128 + if mode == 0 then + pos, c.pred = blockSeq(d, pos, coef, off, c.dct :: buffer, c.act :: buffer, c.pred) + elseif mode == 1 then + pos, c.pred = blockDcFirst(d, pos, coef, off, c.dct :: buffer, c.pred, al) + elseif mode == 2 then + local b = rshift(lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)), 31) + pos += 1 + if b ~= 0 then + writei16(coef, off, bor(readi16(coef, off), bit)) + end + elseif mode == 3 then + pos, eobrun = blockAcFirst(d, pos, coef, off, c.act :: buffer, ss, se, al, eobrun) + else + pos, eobrun = blockAcRefine(d, pos, coef, off, c.act :: buffer, ss, se, al, eobrun) + end + end + end + end + end + end + return pos, truncated +end + +return Scan +end +__FILES["codecs/image/Jpeg/Tables"] = function() + +-- 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 = {} + +local function range(t: { number }, a: number, b: number) + for v = a, b do + table.insert(t, v) + end +end + +-- { counts (16 code-length counts), symbols } per table: dc[1] luma, dc[2] chroma, ac[1], ac[2] +local dcl = { 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 } +local dcc = { 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 } +local dcv = {} +range(dcv, 0, 11) +local acl = { 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d } +local aclv = { + 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07, + 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08, 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0, + 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28, + 0x29, 0x2a, +} +range(aclv, 0x34, 0x3a) +for hi = 4, 8 do + range(aclv, hi * 16 + 3, hi * 16 + 10) +end +for hi = 9, 13 do + range(aclv, hi * 16 + 2, hi * 16 + 10) +end +range(aclv, 0xe1, 0xea) +range(aclv, 0xf1, 0xfa) +local acc = { 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 } +local accv = { + 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71, + 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0, + 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34, 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26, + 0x27, 0x28, 0x29, 0x2a, +} +range(accv, 0x35, 0x3a) +for hi = 4, 7 do + range(accv, hi * 16 + 3, hi * 16 + 10) +end +for hi = 8, 14 do + range(accv, hi * 16 + 2, hi * 16 + 10) +end +range(accv, 0xf2, 0xfa) + +type Spec = { counts: { number }, symbols: { number } } +Tables.DC = { { counts = dcl, symbols = dcv }, { counts = dcc, symbols = dcv } } :: { Spec } +Tables.AC = { { counts = acl, symbols = aclv }, { counts = acc, symbols = accv } } :: { Spec } + +-- K.1, natural (row-major) order +Tables.LUMA = { + 16, 11, 10, 16, 24, 40, 51, 61, 12, 12, 14, 19, 26, 58, 60, 55, 14, 13, 16, 24, 40, 57, 69, 56, 14, 17, 22, 29, + 51, 87, 80, 62, 18, 22, 37, 56, 68, 109, 103, 77, 24, 35, 55, 64, 81, 104, 113, 92, 49, 64, 78, 87, 103, 121, + 120, 101, 72, 92, 95, 98, 112, 100, 103, 99, +} +Tables.CHROMA = { + 17, 18, 24, 47, 99, 99, 99, 99, 18, 21, 26, 66, 99, 99, 99, 99, 24, 26, 56, 99, 99, 99, 99, 99, 47, 66, 99, 99, + 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, + 99, 99, 99, 99, 99, 99, 99, 99, +} + +function Tables.quant(base: { number }, quality: number): { number } + local q = math.clamp(math.floor(quality), 1, 100) + local scale = if q < 50 then 5000 // q else 200 - q * 2 + local out = table.create(64, 1) + for i = 1, 64 do + out[i] = math.clamp((base[i] * scale + 50) // 100, 1, 255) + end + return out +end + +return Tables +end +__FILES["codecs/image/Jpeg/Yuv"] = @native function() + + + +-- codecs/image/Jpeg/Yuv: the JPEG decoder's u16 IDCT planes -> u8 yuv420p; 4:2:2 / 4:4:4 chroma averaged to 4:2:0, +-- the two fields of AVI1 interlaced Motion-JPEG woven. +local readu16, writeu8, readu32, writeu32 = buffer.readu16, buffer.writeu8, buffer.readu32, buffer.writeu32 + +local Yuv = {} + +@native function Yuv.crop(src: buffer, stride: number, w: number, h: number, dst: buffer, doff: number) + local quads = w // 4 + local rest = w - quads * 4 + for y = 0, h - 1 do + local s = y * stride * 2 + local d = doff + y * w + for _ = 1, quads do + local a, b = readu32(src, s), readu32(src, s + 4) + writeu32(dst, d, a % 65536 + (a // 65536) * 256 + (b % 65536) * 65536 + (b // 65536) * 16777216) + s += 8 + d += 4 + end + for k = 0, rest - 1 do + writeu8(dst, d + k, readu16(src, s + k * 2)) + end + end +end + +@native function Yuv.rows(src: buffer, stride: number, w: number, h: number, dst: buffer, doff: number) + local oh = (h + 1) // 2 + for y = 0, oh - 1 do + local a = 2 * y * stride * 2 + local b = if 2 * y + 1 < h then a + stride * 2 else a + local d = doff + y * w + for x = 0, w - 1 do + writeu8(dst, d + x, (readu16(src, a + x * 2) + readu16(src, b + x * 2) + 1) // 2) + end + end +end + +@native function Yuv.box(src: buffer, stride: number, w: number, h: number, dst: buffer, doff: number) + local ow, oh = (w + 1) // 2, (h + 1) // 2 + for y = 0, oh - 1 do + local a = 2 * y * stride * 2 + local b = if 2 * y + 1 < h then a + stride * 2 else a + local d = doff + y * ow + for x = 0, ow - 1 do + local x0 = 2 * x * 2 + local x1 = if 2 * x + 1 < w then x0 + 2 else x0 + writeu8(dst, d + x, (readu16(src, a + x0) + readu16(src, a + x1) + readu16(src, b + x0) + readu16(src, b + x1) + 2) // 4) + end + end +end + +@native function Yuv.weave(top: buffer, toff: number, bottom: buffer, boff: number, rowBytes: number, rows: number, dst: buffer, doff: number) + for y = 0, rows - 1 do + local k = y // 2 + if y % 2 == 0 then + buffer.copy(dst, doff + y * rowBytes, top, toff + k * rowBytes, rowBytes) + else + buffer.copy(dst, doff + y * rowBytes, bottom, boff + k * rowBytes, rowBytes) + end + end +end + +return Yuv +end +end + + + + + + Vp8 + --!optimize 2 +--!nocheck +-- rosetta chunk Vp8 (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 8 modules (5 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["codecs/image/Vp8"] = function() + +-- codecs/image/Vp8: the VP8 video codec (RFC 6386), decode only. +-- Key frames ported from libwebp 1.6 (BSD-3-Clause, licenses/libwebp-LICENSE.txt), inter frames after libvpx 1.17 +-- (BSD-3-Clause, licenses/libvpx-LICENSE.txt); bit-exact with both. Scale bits are ignored, as libwebp and ffmpeg do. +local Err = __include("core/Err") +local Types = __include("Types") +local Decode = __include("codecs/image/Vp8/Decode") +local Yuv = __include("codecs/image/Vp8/Yuv") + +local Vp8 = {} + +local DEFAULT_MAX_PIXELS = 2 ^ 28 + +type Options = { + maxPixels: number?, +} + +local function fail(msg: string?, offset: number?): Err.Err + local m = msg or "bad data" + if string.sub(m, 1, 11) == "truncated: " then + return Err.new(Err.TRUNCATED, string.sub(m, 12), offset) + elseif string.sub(m, 1, 7) == "limit: " then + return Err.new(Err.LIMIT, string.sub(m, 8), offset) + elseif string.sub(m, 1, 13) == "unsupported: " then + return Err.new(Err.UNSUPPORTED, string.sub(m, 14), offset) + end + return Err.new(Err.CORRUPT, m, offset) +end + +local function range(buf: buffer, off: number?, len: number?): (number, number) + local n = buffer.len(buf) + local o = math.clamp(off or 0, 0, n) + return o, math.clamp(len or (n - o), 0, n - o) +end + +function Vp8.info(buf: buffer, off: number?, len: number?): (any, Err.Err?) + if type(buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "info: expected a buffer") + end + local o, l = range(buf, off, len) + local h, err = Decode.header(buf, o, l) + if not h then + return nil, fail(err, o) + end + return h, nil +end + +local DecoderMeta = {} +DecoderMeta.__index = DecoderMeta + +type Decoder = typeof(setmetatable({} :: { state: Decode.State }, DecoderMeta)) + +function Vp8.newDecoder(): Decoder + return setmetatable({ state = Decode.new() }, DecoderMeta) +end + +function DecoderMeta.decodeFrame(self: Decoder, buf: buffer, off: number?, len: number?, opts: Options?): (Types.Image?, Err.Err?) + if type(buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "decodeFrame: expected a buffer") + end + local o, l = range(buf, off, len) + local f, err = Decode.decodeFrame(self.state, buf, o, l, opts and opts.maxPixels or DEFAULT_MAX_PIXELS) + if not f then + return nil, fail(err, o) + end + local img = Types.Image.new(f.width, f.height, "yuv420p") + local ny = f.width * f.height + local nc = ((f.width + 1) // 2) * ((f.height + 1) // 2) + Decode.cropTo(f, img.pixels, 0, img.pixels, ny, img.pixels, ny + nc) + local h = f.header + img.meta.source = { format = "vp8", keyFrame = h.keyFrame, show = h.show, profile = h.profile, width = f.width, height = f.height } + return img, nil +end + +function DecoderMeta.reset(self: Decoder) + Decode.reset(self.state) +end + +function Vp8.decodeFrame(buf: buffer, off: number?, len: number?, opts: Options?): (Types.Image?, Err.Err?) + return Vp8.newDecoder():decodeFrame(buf, off, len, opts) +end + +function Vp8.decodePlanes(buf: buffer, off: number?, len: number?, opts: Options?): (buffer?, any, buffer?, number?, number?) + if type(buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "decodePlanes: expected a buffer") + end + local o, l = range(buf, off, len) + local f, err = Decode.decodeFrame(Decode.new(), buf, o, l, opts and opts.maxPixels or DEFAULT_MAX_PIXELS) + if not f then + return nil, fail(err, o) + end + local nc = ((f.width + 1) // 2) * ((f.height + 1) // 2) + local y, u, v = buffer.create(f.width * f.height), buffer.create(nc), buffer.create(nc) + Decode.cropTo(f, y, 0, u, 0, v, 0) + return y, u, v, f.width, f.height +end + +function Vp8.planes(img: Types.Image): (number, number, number, number, number) + local cw, ch = (img.width + 1) // 2, (img.height + 1) // 2 + local ny = img.width * img.height + return 0, ny, ny + cw * ch, cw, ch +end + +function Vp8.toRgba(img: Types.Image, fancy: boolean?): (Types.Image?, Err.Err?) + if type(img) ~= "table" or img.format ~= "yuv420p" then + return nil, Err.new(Err.ARG, "toRgba: needs a yuv420p Image") + end + local w, h = img.width, img.height + local _, uo, vo, cw, ch = Vp8.planes(img) + local y = buffer.create(w * h) + local u = buffer.create(cw * ch) + local v = buffer.create(cw * ch) + buffer.copy(y, 0, img.pixels, 0, w * h) + buffer.copy(u, 0, img.pixels, uo, cw * ch) + buffer.copy(v, 0, img.pixels, vo, cw * ch) + local out = Types.Image.new(w, h, "rgba8") + Yuv.toRgba(y, u, v, w, h, fancy ~= false, out.pixels) + out.meta.source = img.meta.source + return out, nil +end + +function Vp8.yuvToRgba(y: buffer, u: buffer, v: buffer, w: number, h: number, fancy: boolean?): buffer + return Yuv.toRgba(y, u, v, w, h, fancy ~= false) +end + +Vp8.setAlpha = Yuv.setAlpha + +return Vp8 +end +__FILES["codecs/image/Vp8/Decode"] = @native function() + + + +-- codecs/image/Vp8/Decode: the VP8 frame decoder (RFC 6386), key frames a port of libwebp 1.6 src/dec + src/dsp/dec.c +-- (BSD-3-Clause, licenses/libwebp-LICENSE.txt), inter frames after libvpx 1.17 vp8/decoder + vp8/common (BSD-3-Clause, +-- licenses/libvpx-LICENSE.txt). Where libvpx and ffmpeg disagree on streams no encoder writes, this follows ffmpeg. +local Tables = __include("codecs/image/Vp8/Tables") +local Predict = __include("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 +local readu32, writeu32 = buffer.readu32, buffer.writeu32 +local bfill, bcopy, bcreate = buffer.fill, buffer.copy, buffer.create +local abs = math.abs + +local COEFF_PROBA0 = Tables.COEFF_PROBA0 +local COEFF_UPDATE_PROBA = Tables.COEFF_UPDATE_PROBA +local BMODES_PROBA = Tables.BMODES_PROBA +local DC_TABLE, AC_TABLE = Tables.DC_TABLE, Tables.AC_TABLE +local BANDS, ZIGZAG = Tables.BANDS, Tables.ZIGZAG +local CAT = { Tables.CAT3, Tables.CAT4, Tables.CAT5, Tables.CAT6 } + +local Decode = {} + +-- libwebp's VP8BitReader: `range` is the range minus one (127..254), `value` holds the unread bits, `bits` is the +-- position of the 8-bit window in `value` (< 0: load more). Bytes past the end read as zero once and set eof. +type Br = { buf: buffer, pos: number, limit: number, value: number, bits: number, range: number, eof: boolean } + +-- SHIFT[r + 1]: the normalisation shift of a range r (1..255) = 7 - floor(log2 r) +local SHIFT = table.create(256, 0) +for r = 1, 255 do + local s, v = 0, r + while v < 128 do + v *= 2 + s += 1 + end + SHIFT[r + 1] = s +end + +@native local function load(br: Br) + local p = br.pos + if p + 3 <= br.limit then + local b = br.buf + br.value = br.value * 16777216 + readu8(b, p) * 65536 + readu8(b, p + 1) * 256 + readu8(b, p + 2) + br.pos = p + 3 + br.bits += 24 + elseif p < br.limit then + br.value = br.value * 256 + readu8(br.buf, p) + br.pos = p + 1 + br.bits += 8 + elseif not br.eof then + br.value *= 256 + br.bits += 8 + br.eof = true + else + br.bits = 0 + end +end + +@native local function newBr(buf: buffer, off: number, len: number): Br + local br = { buf = buf, pos = off, limit = off + len, value = 0, bits = -8, range = 254, eof = false } + load(br) + return br +end + +-- branchless getBit: bit = value >> bits > split; range = bit ? range - split : split + 1; +-- value -= bit * (split + 1) << bits +@native local function getBit(br: Br, prob: number): number + if br.bits < 0 then + load(br) + end + local range = br.range + local pos = br.bits + local split = rshift(range * prob, 8) + local bit = rshift(split - rshift(br.value, pos), 31) + local r = split + 1 + bit * (range - split - split - 1) + br.value -= bit * lshift(split + 1, pos) + local shift = SHIFT[r + 1] + br.range = lshift(r, shift) - 1 + br.bits = pos - shift + return bit +end + +@native local function getValue(br: Br, n: number): number + local v = 0 + for i = n - 1, 0, -1 do + v += getBit(br, 0x80) * 2 ^ i + end + return v +end + +@native local function getSignedValue(br: Br, n: number): number + local v = getValue(br, n) + return if getBit(br, 0x80) == 1 then -v else v +end + +type Quant = { y1dc: number, y1ac: number, y2dc: number, y2ac: number, uvdc: number, uvac: number } + +type Ref = Predict.Planes & { extended: boolean } + +type State = { + -- the frame context (saved and restored around frames that do not refresh it) + proba: { number }, -- 4 * 8 * 3 * 11 token probabilities + ymodeProb: { number }, -- 4 + uvmodeProb: { number }, -- 3 + mvProb: { number }, -- 2 * 19 + -- persistent between frames (reset by key frames) + segProba: { number }, -- 3 + useSegment: boolean, + updateMap: boolean, + absoluteDelta: boolean, + segQuant: { number }, -- 4 + segFilter: { number }, -- 4 + refLfDelta: { number }, -- 4: intra, last, golden, altref + modeLfDelta: { number }, -- 4: B_PRED, zero, nearest / near / new, split + signBias: { number }, -- 4 (by reference frame + 1) + segMap: { number }, + width: number, + height: number, + mbw: number, + mbh: number, + hasKey: boolean, + last: Ref?, + golden: Ref?, + alt: Ref?, + pool: { Ref }, + -- the mode info of the current inter frame, (mbw + 1) x (mbh + 1) with a zero top row and left column + miRef: { number }, + miMode: { number }, + miMvR: { number }, + miMvC: { number }, + miSubR: { number }, -- 16 per macroblock + miSubC: { number }, + miN: number, + pred: buffer?, +} + +@native function Decode.new(): State + return { + proba = table.clone(COEFF_PROBA0), + ymodeProb = table.clone(Tables.YMODE_PROB), + uvmodeProb = table.clone(Tables.UVMODE_PROB), + mvProb = table.clone(Tables.MV_DEFAULT), + segProba = { 255, 255, 255 }, + useSegment = false, + updateMap = false, + absoluteDelta = false, + segQuant = { 0, 0, 0, 0 }, + segFilter = { 0, 0, 0, 0 }, + refLfDelta = { 0, 0, 0, 0 }, + modeLfDelta = { 0, 0, 0, 0 }, + signBias = { 0, 0, 0, 0 }, + segMap = {}, + width = 0, + height = 0, + mbw = 0, + mbh = 0, + hasKey = false, + last = nil, + golden = nil, + alt = nil, + pool = {}, + miRef = {}, + miMode = {}, + miMvR = {}, + miMvC = {}, + miSubR = {}, + miSubC = {}, + miN = 0, + pred = nil, + } +end + +@native function Decode.reset(st: State) + st.hasKey = false + st.last, st.golden, st.alt = nil, nil, nil +end + +@native function Decode.header(buf: buffer, off: number, len: number): (any, string?) + if len < 3 then + return nil, "truncated: frame tag" + end + local bits = readu8(buf, off) + readu8(buf, off + 1) * 256 + readu8(buf, off + 2) * 65536 + local h = { + keyFrame = band(bits, 1) == 0, + profile = band(rshift(bits, 1), 7), + show = band(rshift(bits, 4), 1) == 1, + partitionLength = rshift(bits, 5), + width = 0, + height = 0, + xscale = 0, + yscale = 0, + } + if h.profile > 3 then + return nil, "bad profile " .. h.profile + end + if h.keyFrame then + if len < 10 then + return nil, "truncated: key frame header" + end + if readu8(buf, off + 3) ~= 0x9d or readu8(buf, off + 4) ~= 0x01 or readu8(buf, off + 5) ~= 0x2a then + return nil, "bad VP8 start code" + end + local w = readu8(buf, off + 6) + readu8(buf, off + 7) * 256 + local ht = readu8(buf, off + 8) + readu8(buf, off + 9) * 256 + h.width, h.xscale = band(w, 0x3fff), rshift(w, 14) + h.height, h.yscale = band(ht, 0x3fff), rshift(ht, 14) + end + return h, nil +end + +@native local function getLargeValue(br: Br, P: { number }, p: number): number + local v + if getBit(br, P[p + 4]) == 0 then + if getBit(br, P[p + 5]) == 0 then + v = 2 + else + v = 3 + getBit(br, P[p + 6]) + end + else + if getBit(br, P[p + 7]) == 0 then + if getBit(br, P[p + 8]) == 0 then + v = 5 + getBit(br, 159) + else + v = 7 + 2 * getBit(br, 165) + v += getBit(br, 145) + end + else + local bit1 = getBit(br, P[p + 9]) + local bit0 = getBit(br, P[p + 10 + bit1]) + local cat = 2 * bit1 + bit0 + v = 0 + for _, pr in CAT[cat + 1] do + v = v + v + getBit(br, pr) + end + v += 3 + lshift(8, cat) + end + end + return v +end + +-- coefficients are dequantized to int16 as libwebp stores them, in raster order +@native local function getCoeffs(br: Br, P: { number }, t: number, ctx: number, dqDc: number, dqAc: number, n: number, out: buffer, o: number): number + local tb = t * 8 + local p = ((tb + BANDS[n + 1]) * 3 + ctx) * 11 + local buf, limit = br.buf, br.limit + local value, bits, range, pos = br.value, br.bits, br.range, br.pos + while n < 16 do + do + if bits < 0 then + if pos + 3 <= limit then + value = value * 16777216 + readu8(buf, pos) * 65536 + readu8(buf, pos + 1) * 256 + readu8(buf, pos + 2) + pos += 3 + bits += 24 + else + br.value, br.bits, br.pos = value, bits, pos + load(br) + value, bits, pos = br.value, br.bits, br.pos + end + end + local split = rshift(range * P[p + 1], 8) + local more = rshift(value, bits) > split + if more then + range -= split + value -= lshift(split + 1, bits) + else + range = split + 1 + end + local sh = SHIFT[range + 1] + range = lshift(range, sh) - 1 + bits -= sh + if not more then + br.value, br.bits, br.range, br.pos = value, bits, range, pos + return n + end + end + while true do + if bits < 0 then + if pos + 3 <= limit then + value = value * 16777216 + readu8(buf, pos) * 65536 + readu8(buf, pos + 1) * 256 + readu8(buf, pos + 2) + pos += 3 + bits += 24 + else + br.value, br.bits, br.pos = value, bits, pos + load(br) + value, bits, pos = br.value, br.bits, br.pos + end + end + local split = rshift(range * P[p + 2], 8) + local nonzero = rshift(value, bits) > split + if nonzero then + range -= split + value -= lshift(split + 1, bits) + else + range = split + 1 + end + local sh = SHIFT[range + 1] + range = lshift(range, sh) - 1 + bits -= sh + if nonzero then + break + end + n += 1 + if n == 16 then + br.value, br.bits, br.range, br.pos = value, bits, range, pos + return 16 + end + p = (tb + BANDS[n + 1]) * 33 + end + local nb = (tb + BANDS[n + 2]) * 3 + local v + do + if bits < 0 then + if pos + 3 <= limit then + value = value * 16777216 + readu8(buf, pos) * 65536 + readu8(buf, pos + 1) * 256 + readu8(buf, pos + 2) + pos += 3 + bits += 24 + else + br.value, br.bits, br.pos = value, bits, pos + load(br) + value, bits, pos = br.value, br.bits, br.pos + end + end + local split = rshift(range * P[p + 3], 8) + local large = rshift(value, bits) > split + if large then + range -= split + value -= lshift(split + 1, bits) + else + range = split + 1 + end + local sh = SHIFT[range + 1] + range = lshift(range, sh) - 1 + bits -= sh + if not large then + v = 1 + p = (nb + 1) * 11 + else + br.value, br.bits, br.range, br.pos = value, bits, range, pos + v = getLargeValue(br, P, p) + value, bits, range, pos = br.value, br.bits, br.range, br.pos + p = (nb + 2) * 11 + end + end + do + if bits < 0 then + if pos + 3 <= limit then + value = value * 16777216 + readu8(buf, pos) * 65536 + readu8(buf, pos + 1) * 256 + readu8(buf, pos + 2) + pos += 3 + bits += 24 + else + br.value, br.bits, br.pos = value, bits, pos + load(br) + value, bits, pos = br.value, br.bits, br.pos + end + end + local split = rshift(range * 0x80, 8) + local neg = rshift(value, bits) > split + if neg then + range -= split + value -= lshift(split + 1, bits) + else + range = split + 1 + end + local sh = SHIFT[range + 1] + range = lshift(range, sh) - 1 + bits -= sh + if neg then + v = -v + end + end + if n > 0 then + writei16(out, o + ZIGZAG[n + 1] * 2, v * dqAc) + else + writei16(out, o + ZIGZAG[n + 1] * 2, v * dqDc) + end + n += 1 + end + br.value, br.bits, br.range, br.pos = value, bits, range, pos + return 16 +end + +@native local function nzCode(acc: number, nz: number, dcNz: number): number + return acc * 4 + (if nz > 3 then 3 elseif nz > 1 then 2 else dcNz) +end + +-- the inverse Walsh-Hadamard transform of the 16 Y2 coefficients into the DC of the 16 luma blocks +local whtTmp = table.create(16, 0) +@native local function transformWHT(inp: buffer, out: buffer, o: number) + for i = 0, 3 do + local i0, i4, i8, i12 = readi16(inp, i * 2), readi16(inp, (4 + i) * 2), readi16(inp, (8 + i) * 2), readi16(inp, (12 + i) * 2) + local a0 = i0 + i12 + local a1 = i4 + i8 + local a2 = i4 - i8 + local a3 = i0 - i12 + whtTmp[1 + i] = a0 + a1 + whtTmp[9 + i] = a0 - a1 + whtTmp[5 + i] = a3 + a2 + whtTmp[13 + i] = a3 - a2 + end + for i = 0, 3 do + local dc = whtTmp[1 + i * 4] + 3 + local a0 = dc + whtTmp[4 + i * 4] + local a1 = whtTmp[2 + i * 4] + whtTmp[3 + i * 4] + local a2 = whtTmp[2 + i * 4] - whtTmp[3 + i * 4] + local a3 = dc - whtTmp[4 + i * 4] + local base = o + i * 128 + writei16(out, base, (a0 + a1) // 8) + writei16(out, base + 32, (a3 + a2) // 8) + writei16(out, base + 64, (a0 - a1) // 8) + writei16(out, base + 96, (a3 - a2) // 8) + end +end + +-- the work buffer of libwebp (yuv_b): BPS = 32, Y at row 1 column 8, U and V below it side by side +local BPS = 32 +local Y_OFF = BPS + 8 +local U_OFF = Y_OFF + BPS * 16 + BPS +local V_OFF = U_OFF + 16 +local YUV_SIZE = BPS * 17 + BPS * 9 + +@native local function clip8(v: number): number + return if v < 0 then 0 elseif v > 255 then 255 else v +end + +-- the inverse DCT of one block (libwebp TransformOne) added to dst +local C1, C2 = 20091, 35468 +local idctTmp = table.create(16, 0) +@native local function mul1(a: number): number + return ((a * C1) // 65536) + a +end +@native local function mul2(a: number): number + return (a * C2) // 65536 +end +@native local function transformOne(c: buffer, o: number, b: buffer, dst: number) + for i = 0, 3 do + local i0, i4, i8, i12 = readi16(c, o + i * 2), readi16(c, o + (4 + i) * 2), readi16(c, o + (8 + i) * 2), readi16(c, o + (12 + i) * 2) + local a = i0 + i8 + local bb = i0 - i8 + local cc = mul2(i4) - mul1(i12) + local d = mul1(i4) + mul2(i12) + idctTmp[i * 4 + 1] = a + d + idctTmp[i * 4 + 2] = bb + cc + idctTmp[i * 4 + 3] = bb - cc + idctTmp[i * 4 + 4] = a - d + end + for i = 0, 3 do + local dc = idctTmp[i + 1] + 4 + local a = dc + idctTmp[i + 9] + local bb = dc - idctTmp[i + 9] + local cc = mul2(idctTmp[i + 5]) - mul1(idctTmp[i + 13]) + local d = mul1(idctTmp[i + 5]) + mul2(idctTmp[i + 13]) + local row = dst + i * BPS + writeu8(b, row, clip8(readu8(b, row) + (a + d) // 8)) + writeu8(b, row + 1, clip8(readu8(b, row + 1) + (bb + cc) // 8)) + writeu8(b, row + 2, clip8(readu8(b, row + 2) + (bb - cc) // 8)) + writeu8(b, row + 3, clip8(readu8(b, row + 3) + (a - d) // 8)) + end +end + +@native local function transformDC(c: buffer, o: number, b: buffer, dst: number) + local dc = (readi16(c, o) + 4) // 8 + for j = 0, 3 do + local row = dst + j * BPS + for i = row, row + 3 do + writeu8(b, i, clip8(readu8(b, i) + dc)) + end + end +end + +-- code: 3 = full transform, 2 = only the first three coefficients (the same result as the full one), 1 = DC only +@native local function doTransform(code: number, c: buffer, o: number, b: buffer, dst: number) + if code >= 2 then + transformOne(c, o, b, dst) + elseif code == 1 then + transformDC(c, o, b, dst) + end +end + +@native local function doUVTransform(bits: number, c: buffer, o: number, b: buffer, dst: number) + if band(bits, 0xff) ~= 0 then + if band(bits, 0xaa) ~= 0 then + transformOne(c, o, b, dst) + transformOne(c, o + 32, b, dst + 4) + transformOne(c, o + 64, b, dst + 4 * BPS) + transformOne(c, o + 96, b, dst + 4 * BPS + 4) + else + if readi16(c, o) ~= 0 then + transformDC(c, o, b, dst) + end + if readi16(c, o + 32) ~= 0 then + transformDC(c, o + 32, b, dst + 4) + end + if readi16(c, o + 64) ~= 0 then + transformDC(c, o + 64, b, dst + 4 * BPS) + end + if readi16(c, o + 96) ~= 0 then + transformDC(c, o + 96, b, dst + 4 * BPS + 4) + end + end + end +end + +-- prediction: modes 0 DC, 1 TM, 2 VE, 3 HE; 4 DC no top, 5 DC no left, 6 DC no top-left (16x16 and chroma) +@native local function fill(b: buffer, dst: number, size: number, v: number) + for j = 0, size - 1 do + local o = dst + j * BPS + for i = o, o + size - 4, 4 do + writeu32(b, i, v * 0x01010101) + end + end +end + +@native local function trueMotion(b: buffer, dst: number, size: number) + local tl = readu8(b, dst - BPS - 1) + for y = 0, size - 1 do + local row = dst + y * BPS + local l = readu8(b, row - 1) - tl + for x = 0, size - 1 do + writeu8(b, row + x, clip8(readu8(b, dst - BPS + x) + l)) + end + end +end + +@native local function predictBlock(b: buffer, dst: number, size: number, mode: number) + local shift = if size == 16 then 5 else 4 + if mode == 0 then + local dc = size + for j = 0, size - 1 do + dc += readu8(b, dst - 1 + j * BPS) + readu8(b, dst + j - BPS) + end + fill(b, dst, size, rshift(dc, shift)) + elseif mode == 1 then + trueMotion(b, dst, size) + elseif mode == 2 then + for j = 0, size - 1 do + local o = dst + j * BPS + for i = 0, size - 4, 4 do + writeu32(b, o + i, readu32(b, dst - BPS + i)) + end + end + elseif mode == 3 then + for j = 0, size - 1 do + local o = dst + j * BPS + local v = readu8(b, o - 1) * 0x01010101 + for i = o, o + size - 4, 4 do + writeu32(b, i, v) + end + end + elseif mode == 4 then -- no top: left samples + local dc = size // 2 + for j = 0, size - 1 do + dc += readu8(b, dst - 1 + j * BPS) + end + fill(b, dst, size, rshift(dc, shift - 1)) + elseif mode == 5 then -- no left: top samples + local dc = size // 2 + for j = 0, size - 1 do + dc += readu8(b, dst + j - BPS) + end + fill(b, dst, size, rshift(dc, shift - 1)) + else + fill(b, dst, size, 0x80) + end +end + +@native local function avg3(a: number, b: number, c: number): number + return rshift(a + 2 * b + c + 2, 2) +end +@native local function avg2(a: number, b: number): number + return rshift(a + b + 1, 1) +end + +-- 4x4 prediction (libwebp VP8PredLuma4): 0 DC, 1 TM, 2 VE, 3 HE, 4 RD, 5 VR, 6 LD, 7 VL, 8 HD, 9 HU +@native local function predict4(b: buffer, dst: number, mode: number) + if mode == 0 then + local dc = 4 + for i = 0, 3 do + dc += readu8(b, dst + i - BPS) + readu8(b, dst - 1 + i * BPS) + end + fill(b, dst, 4, rshift(dc, 3)) + elseif mode == 1 then + trueMotion(b, dst, 4) + elseif mode == 2 then + local t = dst - BPS + local x, a, bb, c, d, e = readu8(b, t - 1), readu8(b, t), readu8(b, t + 1), readu8(b, t + 2), readu8(b, t + 3), readu8(b, t + 4) + local v0, v1, v2, v3 = avg3(x, a, bb), avg3(a, bb, c), avg3(bb, c, d), avg3(c, d, e) + for j = 0, 3 do + writeu8(b, dst + j * BPS + 0, v0) + writeu8(b, dst + j * BPS + 1, v1) + writeu8(b, dst + j * BPS + 2, v2) + writeu8(b, dst + j * BPS + 3, v3) + end + elseif mode == 3 then + local A, B, C, D = readu8(b, dst - 1 - BPS), readu8(b, dst - 1), readu8(b, dst - 1 + BPS), readu8(b, dst - 1 + 2 * BPS) + local E = readu8(b, dst - 1 + 3 * BPS) + writeu32(b, dst, avg3(A, B, C) * 0x01010101) + writeu32(b, dst + BPS, avg3(B, C, D) * 0x01010101) + writeu32(b, dst + 2 * BPS, avg3(C, D, E) * 0x01010101) + writeu32(b, dst + 3 * BPS, avg3(D, E, E) * 0x01010101) + else + local I, J, K, L = readu8(b, dst - 1), readu8(b, dst - 1 + BPS), readu8(b, dst - 1 + 2 * BPS), readu8(b, dst - 1 + 3 * BPS) + local t = dst - BPS + local X, A, B, C, D = readu8(b, t - 1), readu8(b, t), readu8(b, t + 1), readu8(b, t + 2), readu8(b, t + 3) + local E, F, G, H = readu8(b, t + 4), readu8(b, t + 5), readu8(b, t + 6), readu8(b, t + 7) + if mode == 4 then -- RD + writeu8(b, dst + 96, avg3(J, K, L)) + local v = avg3(I, J, K) + writeu8(b, dst + 97, v) + writeu8(b, dst + 64, v) + v = avg3(X, I, J) + writeu8(b, dst + 98, v) + writeu8(b, dst + 65, v) + writeu8(b, dst + 32, v) + v = avg3(A, X, I) + writeu8(b, dst + 99, v) + writeu8(b, dst + 66, v) + writeu8(b, dst + 33, v) + writeu8(b, dst + 0, v) + v = avg3(B, A, X) + writeu8(b, dst + 67, v) + writeu8(b, dst + 34, v) + writeu8(b, dst + 1, v) + v = avg3(C, B, A) + writeu8(b, dst + 35, v) + writeu8(b, dst + 2, v) + writeu8(b, dst + 3, avg3(D, C, B)) + elseif mode == 5 then -- VR + local v = avg2(X, A) + writeu8(b, dst + 0, v) + writeu8(b, dst + 65, v) + v = avg2(A, B) + writeu8(b, dst + 1, v) + writeu8(b, dst + 66, v) + v = avg2(B, C) + writeu8(b, dst + 2, v) + writeu8(b, dst + 67, v) + writeu8(b, dst + 3, avg2(C, D)) + writeu8(b, dst + 96, avg3(K, J, I)) + writeu8(b, dst + 64, avg3(J, I, X)) + v = avg3(I, X, A) + writeu8(b, dst + 32, v) + writeu8(b, dst + 97, v) + v = avg3(X, A, B) + writeu8(b, dst + 33, v) + writeu8(b, dst + 98, v) + v = avg3(A, B, C) + writeu8(b, dst + 34, v) + writeu8(b, dst + 99, v) + writeu8(b, dst + 35, avg3(B, C, D)) + elseif mode == 6 then -- LD + writeu8(b, dst + 0, avg3(A, B, C)) + local v = avg3(B, C, D) + writeu8(b, dst + 1, v) + writeu8(b, dst + 32, v) + v = avg3(C, D, E) + writeu8(b, dst + 2, v) + writeu8(b, dst + 33, v) + writeu8(b, dst + 64, v) + v = avg3(D, E, F) + writeu8(b, dst + 3, v) + writeu8(b, dst + 34, v) + writeu8(b, dst + 65, v) + writeu8(b, dst + 96, v) + v = avg3(E, F, G) + writeu8(b, dst + 35, v) + writeu8(b, dst + 66, v) + writeu8(b, dst + 97, v) + v = avg3(F, G, H) + writeu8(b, dst + 67, v) + writeu8(b, dst + 98, v) + writeu8(b, dst + 99, avg3(G, H, H)) + elseif mode == 7 then -- VL + writeu8(b, dst + 0, avg2(A, B)) + local v = avg2(B, C) + writeu8(b, dst + 1, v) + writeu8(b, dst + 64, v) + v = avg2(C, D) + writeu8(b, dst + 2, v) + writeu8(b, dst + 65, v) + v = avg2(D, E) + writeu8(b, dst + 3, v) + writeu8(b, dst + 66, v) + writeu8(b, dst + 32, avg3(A, B, C)) + v = avg3(B, C, D) + writeu8(b, dst + 33, v) + writeu8(b, dst + 96, v) + v = avg3(C, D, E) + writeu8(b, dst + 34, v) + writeu8(b, dst + 97, v) + v = avg3(D, E, F) + writeu8(b, dst + 35, v) + writeu8(b, dst + 98, v) + writeu8(b, dst + 67, avg3(E, F, G)) + writeu8(b, dst + 99, avg3(F, G, H)) + elseif mode == 8 then -- HD + local v = avg2(I, X) + writeu8(b, dst + 0, v) + writeu8(b, dst + 34, v) + v = avg2(J, I) + writeu8(b, dst + 32, v) + writeu8(b, dst + 66, v) + v = avg2(K, J) + writeu8(b, dst + 64, v) + writeu8(b, dst + 98, v) + writeu8(b, dst + 96, avg2(L, K)) + writeu8(b, dst + 3, avg3(A, B, C)) + writeu8(b, dst + 2, avg3(X, A, B)) + v = avg3(I, X, A) + writeu8(b, dst + 1, v) + writeu8(b, dst + 35, v) + v = avg3(J, I, X) + writeu8(b, dst + 33, v) + writeu8(b, dst + 67, v) + v = avg3(K, J, I) + writeu8(b, dst + 65, v) + writeu8(b, dst + 99, v) + writeu8(b, dst + 97, avg3(L, K, J)) + else -- HU + writeu8(b, dst + 0, avg2(I, J)) + local v = avg2(J, K) + writeu8(b, dst + 2, v) + writeu8(b, dst + 32, v) + v = avg2(K, L) + writeu8(b, dst + 34, v) + writeu8(b, dst + 64, v) + writeu8(b, dst + 1, avg3(I, J, K)) + v = avg3(J, K, L) + writeu8(b, dst + 3, v) + writeu8(b, dst + 33, v) + v = avg3(K, L, L) + writeu8(b, dst + 35, v) + writeu8(b, dst + 65, v) + writeu8(b, dst + 67, L) + writeu8(b, dst + 66, L) + writeu8(b, dst + 96, L) + writeu8(b, dst + 97, L) + writeu8(b, dst + 98, L) + writeu8(b, dst + 99, L) + end + end +end + +@native local function checkMode(mbx: number, mby: number, mode: number): number + if mode == 0 then + if mbx == 0 then + return if mby == 0 then 6 else 5 + end + return if mby == 0 then 4 else 0 + end + return mode +end + +-- the filters are libwebp's DoFilter2 / DoFilter4 / DoFilter6 inlined into their loops (VP8ksclip1 clamps to +-- [-128, 127], VP8ksclip2 to [-16, 15], VP8kclip1 to [0, 255]). Arithmetic shifts of small signed values are +-- logical shifts of the value plus a bias: (a + 4) >> 3 = rshift(a + 4 + 1024, 3) - 128 for a >= -1024. + +-- SimpleVFilter16 / SimpleHFilter16; a position whose filter value a is 0 changes nothing (skipped before the mask) +@native local function simpleFilter(b: buffer, p: number, step: number, along: number, thresh: number) + local t2 = 2 * thresh + 1 + for _ = 1, 16 do + local p1, p0, q0, q1 = readu8(b, p - 2 * step), readu8(b, p - step), readu8(b, p), readu8(b, p + step) + local w = p1 - q1 + local a = 3 * (q0 - p0) + (if w < -128 then -128 elseif w > 127 then 127 else w) + if a ~= 0 and 4 * abs(p0 - q0) + abs(w) <= t2 then + local a1 = rshift(a + 1028, 3) - 128 + if a1 < -16 then + a1 = -16 + elseif a1 > 15 then + a1 = 15 + end + local a2 = rshift(a + 1027, 3) - 128 + if a2 < -16 then + a2 = -16 + elseif a2 > 15 then + a2 = 15 + end + local v = p0 + a2 + writeu8(b, p - step, if v < 0 then 0 elseif v > 255 then 255 else v) + v = q0 - a1 + writeu8(b, p, if v < 0 then 0 elseif v > 255 then 255 else v) + end + p += along + end +end + +-- the macroblock edge filter (FilterLoop26) +@native local function filterEdge(b: buffer, p: number, hs: number, vs: number, size: number, thresh: number, it: number, hevT: number) + local t2 = 2 * thresh + 1 + for _ = 1, size do + local p1, p0, q0, q1 = readu8(b, p - 2 * hs), readu8(b, p - hs), readu8(b, p), readu8(b, p + hs) + local w = p1 - q1 + local a = 3 * (q0 - p0) + (if w < -128 then -128 elseif w > 127 then 127 else w) + if a ~= 0 then + local dp, dq = abs(p1 - p0), abs(q1 - q0) + if 4 * abs(p0 - q0) + abs(w) <= t2 and dp <= it and dq <= it then + local p3, p2 = readu8(b, p - 4 * hs), readu8(b, p - 3 * hs) + local q2, q3 = readu8(b, p + 2 * hs), readu8(b, p + 3 * hs) + if abs(p3 - p2) <= it and abs(p2 - p1) <= it and abs(q3 - q2) <= it and abs(q2 - q1) <= it then + if dp > hevT or dq > hevT then + local a1 = rshift(a + 1028, 3) - 128 + if a1 < -16 then + a1 = -16 + elseif a1 > 15 then + a1 = 15 + end + local a2 = rshift(a + 1027, 3) - 128 + if a2 < -16 then + a2 = -16 + elseif a2 > 15 then + a2 = 15 + end + local v = p0 + a2 + writeu8(b, p - hs, if v < 0 then 0 elseif v > 255 then 255 else v) + v = q0 - a1 + writeu8(b, p, if v < 0 then 0 elseif v > 255 then 255 else v) + else + if a < -128 then + a = -128 + elseif a > 127 then + a = 127 + end + local a1 = rshift(27 * a + 4159, 7) - 32 + local a2 = rshift(18 * a + 4159, 7) - 32 + local a3 = rshift(9 * a + 4159, 7) - 32 + local v = p2 + a3 + writeu8(b, p - 3 * hs, if v < 0 then 0 elseif v > 255 then 255 else v) + v = p1 + a2 + writeu8(b, p - 2 * hs, if v < 0 then 0 elseif v > 255 then 255 else v) + v = p0 + a1 + writeu8(b, p - hs, if v < 0 then 0 elseif v > 255 then 255 else v) + v = q0 - a1 + writeu8(b, p, if v < 0 then 0 elseif v > 255 then 255 else v) + v = q1 - a2 + writeu8(b, p + hs, if v < 0 then 0 elseif v > 255 then 255 else v) + v = q2 - a3 + writeu8(b, p + 2 * hs, if v < 0 then 0 elseif v > 255 then 255 else v) + end + end + end + end + p += vs + end +end + +-- the inner edge filter (FilterLoop24); nothing changes when q0 == p0 and p1 == q1 +@native local function filterInner(b: buffer, p: number, hs: number, vs: number, size: number, thresh: number, it: number, hevT: number) + local t2 = 2 * thresh + 1 + for _ = 1, size do + local p1, p0, q0, q1 = readu8(b, p - 2 * hs), readu8(b, p - hs), readu8(b, p), readu8(b, p + hs) + local w = p1 - q1 + if q0 ~= p0 or w ~= 0 then + local dp, dq = abs(p1 - p0), abs(q1 - q0) + if 4 * abs(p0 - q0) + abs(w) <= t2 and dp <= it and dq <= it then + local p3, p2 = readu8(b, p - 4 * hs), readu8(b, p - 3 * hs) + local q2, q3 = readu8(b, p + 2 * hs), readu8(b, p + 3 * hs) + if abs(p3 - p2) <= it and abs(p2 - p1) <= it and abs(q3 - q2) <= it and abs(q2 - q1) <= it then + local hev = dp > hevT or dq > hevT + local a = 3 * (q0 - p0) + if hev then + a += if w < -128 then -128 elseif w > 127 then 127 else w + end + local a1 = rshift(a + 1028, 3) - 128 + if a1 < -16 then + a1 = -16 + elseif a1 > 15 then + a1 = 15 + end + local a2 = rshift(a + 1027, 3) - 128 + if a2 < -16 then + a2 = -16 + elseif a2 > 15 then + a2 = 15 + end + local v = p0 + a2 + writeu8(b, p - hs, if v < 0 then 0 elseif v > 255 then 255 else v) + v = q0 - a1 + writeu8(b, p, if v < 0 then 0 elseif v > 255 then 255 else v) + if not hev then + local a3 = rshift(a1 + 17, 1) - 8 + v = p1 + a3 + writeu8(b, p - 2 * hs, if v < 0 then 0 elseif v > 255 then 255 else v) + v = q1 - a3 + writeu8(b, p + hs, if v < 0 then 0 elseif v > 255 then 255 else v) + end + end + end + end + p += vs + end +end + +local MODE_CTX = Tables.MODE_CONTEXTS +local SUB_MV_REF_PROB = Tables.SUB_MV_REF_PROB +local SPLIT_OFFSET, SPLIT_FILL, SPLIT_COUNT = Tables.SPLIT_OFFSET, Tables.SPLIT_FILL, Tables.SPLIT_COUNT +local BMODE_PROB = Tables.BMODE_PROB +local MV_UPDATE = Tables.MV_UPDATE + +-- macroblock modes (the row arrays and miMode): 0 DC, 1 TM, 2 V, 3 H (16x16 intra, libwebp's numbering), 4 B_PRED, +-- 5 ZEROMV, 6 NEARESTMV, 7 NEARMV, 8 NEWMV, 9 SPLITMV. Their loop filter mode delta index: +local MODE_LF = { 1, 1, 1, 1, 0, 1, 2, 2, 2, 3 } + +-- a 4x4 intra mode with the fixed probabilities P[o + 1 .. o + 9] (libvpx vp8_bmode_tree, libwebp's numbering) +@native local function readBMode(br: Br, P: { number }, o: number): number + if getBit(br, P[o + 1]) == 0 then + return 0 + elseif getBit(br, P[o + 2]) == 0 then + return 1 + elseif getBit(br, P[o + 3]) == 0 then + return 2 + elseif getBit(br, P[o + 4]) == 0 then + if getBit(br, P[o + 5]) == 0 then + return 3 + end + return if getBit(br, P[o + 6]) == 0 then 4 else 5 + elseif getBit(br, P[o + 7]) == 0 then + return 6 + elseif getBit(br, P[o + 8]) == 0 then + return 7 + end + return if getBit(br, P[o + 9]) == 0 then 8 else 9 +end + +-- one motion vector component (libvpx read_mvcomponent) with the probabilities P[o + 1 .. o + 19], in quarter pixels +@native local function readMvComponent(br: Br, P: { number }, o: number): number + local x + if getBit(br, P[o + 1]) == 1 then -- long: bits 0-2, then 9-4, then bit 3 (implicit when nothing above it is set) + x = getBit(br, P[o + 10]) + 2 * getBit(br, P[o + 11]) + 4 * getBit(br, P[o + 12]) + for i = 9, 4, -1 do + x += getBit(br, P[o + 10 + i]) * lshift(1, i) + end + if x < 16 or getBit(br, P[o + 13]) == 1 then + x += 8 + end + elseif getBit(br, P[o + 3]) == 0 then -- short tree + if getBit(br, P[o + 4]) == 0 then + x = getBit(br, P[o + 5]) + else + x = 2 + getBit(br, P[o + 6]) + end + elseif getBit(br, P[o + 7]) == 0 then + x = 4 + getBit(br, P[o + 8]) + else + x = 6 + getBit(br, P[o + 9]) + end + if x ~= 0 and getBit(br, P[o + 2]) == 1 then + x = -x + end + return x +end + +type Rows = { + i4: { boolean }, -- no Y2 block (B_PRED or SPLITMV) + modes: { number }, + uv: { number }, + ref: { number }, -- 0 intra, 1 last, 2 golden, 3 altref + mode: { number }, + part: { number }, -- SPLITMV partitioning (0 16x8, 1 8x16, 2 8x8, 3 4x4) or -1 +} + +local nr, nc, cnt = table.create(4, 0), table.create(4, 0), table.create(4, 0) + +-- libvpx read_mb_modes_mv with vp8_find_near_mvs +@native local function readInterMb(st: State, br: Br, probIntra: number, probLast: number, probGf: number, mi: number, mbx: number, mby: number, rows: Rows) + local miRef, miMode, miMvR, miMvC = st.miRef, st.miMode, st.miMvR, st.miMvC + local x1 = mbx + 1 + if getBit(br, probIntra) == 0 then + local P = st.ymodeProb + local ymode + if getBit(br, P[1]) == 0 then + ymode = 0 + elseif getBit(br, P[2]) == 0 then + ymode = if getBit(br, P[3]) == 0 then 2 else 3 + else + ymode = if getBit(br, P[4]) == 0 then 1 else 4 + end + local modes = rows.modes + if ymode == 4 then + for k = mbx * 16 + 1, mbx * 16 + 16 do + modes[k] = readBMode(br, BMODE_PROB, 0) + end + else + modes[mbx * 16 + 1] = ymode + end + local U = st.uvmodeProb + if getBit(br, U[1]) == 0 then + rows.uv[x1] = 0 + elseif getBit(br, U[2]) == 0 then + rows.uv[x1] = 2 + else + rows.uv[x1] = if getBit(br, U[3]) == 0 then 3 else 1 + end + rows.i4[x1] = ymode == 4 + rows.ref[x1] = 0 + rows.mode[x1] = ymode + rows.part[x1] = -1 + miRef[mi], miMode[mi], miMvR[mi], miMvC[mi] = 0, ymode, 0, 0 + return + end + local ref = 1 + if getBit(br, probLast) == 1 then + ref = 2 + getBit(br, probGf) + end + -- the near motion vectors of the above, left and above-left macroblocks, sign corrected + local bias = st.signBias + local sb = bias[ref + 1] + local a = mi - (st.mbw + 1) + local l = mi - 1 + local al = a - 1 + for k = 1, 4 do + nr[k], nc[k], cnt[k] = 0, 0, 0 + end + local n = 1 + local rf = miRef[a] + if rf ~= 0 then + local r, c = miMvR[a], miMvC[a] + if r ~= 0 or c ~= 0 then + if bias[rf + 1] ~= sb then + r, c = -r, -c + end + n = 2 + nr[2], nc[2] = r, c + end + cnt[n] += 2 + end + rf = miRef[l] + if rf ~= 0 then + local r, c = miMvR[l], miMvC[l] + if r ~= 0 or c ~= 0 then + if bias[rf + 1] ~= sb then + r, c = -r, -c + end + if r ~= nr[n] or c ~= nc[n] then + n += 1 + nr[n], nc[n] = r, c + end + cnt[n] += 2 + else + cnt[1] += 2 + end + end + rf = miRef[al] + if rf ~= 0 then + local r, c = miMvR[al], miMvC[al] + if r ~= 0 or c ~= 0 then + if bias[rf + 1] ~= sb then + r, c = -r, -c + end + if r ~= nr[n] or c ~= nc[n] then + n += 1 + nr[n], nc[n] = r, c + end + cnt[n] += 1 + else + cnt[1] += 1 + end + end + -- clamping bounds (vp8_clamp_mv2), in eighth pixels + local mbw, mbh = st.mbw, st.mbh + local toL, toR = -mbx * 128 - 128, (mbw - 1 - mbx) * 128 + 128 + local toT, toB = -mby * 128 - 128, (mbh - 1 - mby) * 128 + 128 + local mode, mvr, mvc, part = 5, 0, 0, -1 + if getBit(br, MODE_CTX[cnt[1] * 4 + 1]) == 1 then + if cnt[4] > 0 and nr[n] == nr[2] and nc[n] == nc[2] then + cnt[2] += 1 + end + if cnt[3] > cnt[2] then + cnt[2], cnt[3] = cnt[3], cnt[2] + nr[2], nr[3] = nr[3], nr[2] + nc[2], nc[3] = nc[3], nc[2] + end + local k + if getBit(br, MODE_CTX[cnt[2] * 4 + 2]) == 0 then + mode, k = 6, 2 + elseif getBit(br, MODE_CTX[cnt[3] * 4 + 3]) == 0 then + mode, k = 7, 3 + else + k = if cnt[2] >= cnt[1] then 2 else 1 + end + mvr, mvc = nr[k], nc[k] + if mvc < toL then + mvc = toL + elseif mvc > toR then + mvc = toR + end + if mvr < toT then + mvr = toT + elseif mvr > toB then + mvr = toB + end + if mode == 5 then + -- mvr, mvc: the best vector; new or split + local P = st.mvProb + local sc = (if miMode[a] == 9 then 2 else 0) + (if miMode[l] == 9 then 2 else 0) + (if miMode[al] == 9 then 1 else 0) + if getBit(br, MODE_CTX[sc * 4 + 4]) == 0 then + mode = 8 + mvr += readMvComponent(br, P, 0) * 2 + mvc += readMvComponent(br, P, 19) * 2 + else + mode = 9 + local bestR, bestC = mvr, mvc + local s, nump + if getBit(br, 110) == 1 then + if getBit(br, 111) == 1 then + s, nump = getBit(br, 150), 2 + else + s, nump = 2, 4 + end + else + s, nump = 3, 16 + end + part = s + local subR, subC = st.miSubR, st.miSubC + local sb0 = (mi - 1) * 16 + local lb, ab = (l - 1) * 16, (a - 1) * 16 + local splitL, splitA = miMode[l] == 9, miMode[a] == 9 + local count = SPLIT_COUNT[s + 1] + for j = 0, nump - 1 do + local b = SPLIT_OFFSET[s * 16 + j + 1] + local lr, lc, ar, ac + if b % 4 ~= 0 then + lr, lc = subR[sb0 + b], subC[sb0 + b] + elseif splitL then + lr, lc = subR[lb + b + 4], subC[lb + b + 4] + else + lr, lc = miMvR[l], miMvC[l] + end + if b >= 4 then + ar, ac = subR[sb0 + b - 3], subC[sb0 + b - 3] + elseif splitA then + ar, ac = subR[ab + b + 13], subC[ab + b + 13] + else + ar, ac = miMvR[a], miMvC[a] + end + local pi = ((if ar == 0 and ac == 0 then 4 else 0) + (if lr == 0 and lc == 0 then 2 else 0) + (if lr == ar and lc == ac then 1 else 0)) * 3 + local r, c + if getBit(br, SUB_MV_REF_PROB[pi + 1]) == 0 then + r, c = lr, lc + elseif getBit(br, SUB_MV_REF_PROB[pi + 2]) == 0 then + r, c = ar, ac + elseif getBit(br, SUB_MV_REF_PROB[pi + 3]) == 0 then + r, c = 0, 0 + else + r = bestR + readMvComponent(br, P, 0) * 2 + c = bestC + readMvComponent(br, P, 19) * 2 + end + local fo = s * 16 + j * count + for i = fo + 1, fo + count do + local q = sb0 + SPLIT_FILL[i] + 1 + subR[q], subC[q] = r, c + end + end + mvr, mvc = subR[sb0 + 16], subC[sb0 + 16] + end + end + end + rows.i4[x1] = mode == 9 + rows.ref[x1] = ref + rows.mode[x1] = mode + rows.part[x1] = part + miRef[mi], miMode[mi], miMvR[mi], miMvC[mi] = ref, mode, mvr, mvc +end + +type Frame = { + width: number, + height: number, + ref: Ref, + header: any, +} + +local BORDER = Predict.BORDER + +@native local function newRef(mbw: number, mbh: number): Ref + local ys, uvs = mbw * 16 + 2 * BORDER, mbw * 8 + 2 * BORDER + return { + Y = bcreate(ys * (mbh * 16 + 2 * BORDER)), + U = bcreate(uvs * (mbh * 8 + 2 * BORDER)), + V = bcreate(uvs * (mbh * 8 + 2 * BORDER)), + ys = ys, + uvs = uvs, + yb = BORDER * ys + BORDER, + uvb = BORDER * uvs + BORDER, + mbw = mbw, + mbh = mbh, + extended = false, + } +end + +@native local function freeRef(st: State): Ref + for _, r in st.pool do + if r ~= st.last and r ~= st.golden and r ~= st.alt then + return r + end + end + local r = newRef(st.mbw, st.mbh) + table.insert(st.pool, r) + return r +end + +@native function Decode.cropTo(f: Frame, dy: buffer, oy: number, du: buffer, ou: number, dv: buffer, ov: number) + local r = f.ref + local w, h = f.width, f.height + local cw, chh = (w + 1) // 2, (h + 1) // 2 + local Y, U, V, ys, uvs, yb, uvb = r.Y, r.U, r.V, r.ys, r.uvs, r.yb, r.uvb + for j = 0, h - 1 do + bcopy(dy, oy + j * w, Y, yb + j * ys, w) + end + for j = 0, chh - 1 do + bcopy(du, ou + j * cw, U, uvb + j * uvs, cw) + bcopy(dv, ov + j * cw, V, uvb + j * uvs, cw) + end +end + +@native function Decode.decodeFrame(st: State, buf: buffer, off: number, len: number, maxPixels: number): (Frame?, string?) + local hdr, herr = Decode.header(buf, off, len) + if not hdr then + return nil, herr + end + local key = hdr.keyFrame + local width, height, p, left + if key then + width, height = hdr.width, hdr.height + if width == 0 or height == 0 then + return nil, "zero frame size" + end + if width * height > maxPixels then + return nil, "limit: " .. width .. " x " .. height .. " is over maxPixels" + end + p, left = off + 10, len - 10 + else + if not st.hasKey then + return nil, "inter frame without a key frame" + end + width, height = st.width, st.height + p, left = off + 3, len - 3 + end + if hdr.partitionLength > left then + return nil, "truncated: first partition" + end + local mbw, mbh = (width + 15) // 16, (height + 15) // 16 + if key then + st.hasKey = false + if width ~= st.width or height ~= st.height then + st.width, st.height, st.mbw, st.mbh = width, height, mbw, mbh + st.last, st.golden, st.alt, st.pool = nil, nil, nil, {} + st.miN, st.pred = 0, nil + st.segMap = table.create(mbw * mbh, 0) + end + -- key frames reset the frame context, the segment and loop filter deltas + st.proba = table.clone(COEFF_PROBA0) + st.ymodeProb = table.clone(Tables.YMODE_PROB) + st.uvmodeProb = table.clone(Tables.UVMODE_PROB) + st.mvProb = table.clone(Tables.MV_DEFAULT) + st.segProba = { 255, 255, 255 } + st.useSegment, st.updateMap, st.absoluteDelta = false, false, false + st.segQuant = { 0, 0, 0, 0 } + st.segFilter = { 0, 0, 0, 0 } + st.refLfDelta = { 0, 0, 0, 0 } + st.modeLfDelta = { 0, 0, 0, 0 } + st.signBias = { 0, 0, 0, 0 } + end + local br = newBr(buf, p, hdr.partitionLength) + p += hdr.partitionLength + left -= hdr.partitionLength + if key then + getValue(br, 1) -- colour space + getValue(br, 1) -- clamping type + end + -- segment header + st.useSegment = getValue(br, 1) == 1 + if st.useSegment then + st.updateMap = getValue(br, 1) == 1 + if getValue(br, 1) == 1 then + st.absoluteDelta = getValue(br, 1) == 1 + for s = 1, 4 do + st.segQuant[s] = if getValue(br, 1) == 1 then getSignedValue(br, 7) else 0 + end + for s = 1, 4 do + st.segFilter[s] = if getValue(br, 1) == 1 then getSignedValue(br, 6) else 0 + end + end + if st.updateMap then + for s = 1, 3 do + st.segProba[s] = if getValue(br, 1) == 1 then getValue(br, 8) else 255 + end + end + else + st.updateMap = false + end + if br.eof then + return nil, "truncated: segment header" + end + -- filter header + local simple = getValue(br, 1) == 1 + local level = getValue(br, 6) + local sharpness = getValue(br, 3) + local useLfDelta = getValue(br, 1) == 1 + if useLfDelta then + if getValue(br, 1) == 1 then + for i = 1, 4 do + if getValue(br, 1) == 1 then + st.refLfDelta[i] = getSignedValue(br, 6) + end + end + for i = 1, 4 do + if getValue(br, 1) == 1 then + st.modeLfDelta[i] = getSignedValue(br, 6) + end + end + end + end + local filterType = if level == 0 then 0 elseif simple then 1 else 2 + if br.eof then + return nil, "truncated: filter header" + end + -- partitions + local numParts = lshift(1, getValue(br, 2)) + local lastPart = numParts - 1 + if left < 3 * lastPart then + return nil, "truncated: partition sizes" + end + local parts: { Br } = {} + local partStart = p + lastPart * 3 + local sizeLeft = left - lastPart * 3 + for k = 0, lastPart - 1 do + local q = p + k * 3 + local psize = readu8(buf, q) + readu8(buf, q + 1) * 256 + readu8(buf, q + 2) * 65536 + if psize > sizeLeft then + psize = sizeLeft + end + parts[k + 1] = newBr(buf, partStart, psize) + partStart += psize + sizeLeft -= psize + end + parts[numParts] = newBr(buf, partStart, sizeLeft) + if partStart >= off + len then + return nil, "truncated: partitions" + end + -- quantizers + local baseQ = getValue(br, 7) + local dqy1dc = if getValue(br, 1) == 1 then getSignedValue(br, 4) else 0 + local dqy2dc = if getValue(br, 1) == 1 then getSignedValue(br, 4) else 0 + local dqy2ac = if getValue(br, 1) == 1 then getSignedValue(br, 4) else 0 + local dquvdc = if getValue(br, 1) == 1 then getSignedValue(br, 4) else 0 + local dquvac = if getValue(br, 1) == 1 then getSignedValue(br, 4) else 0 + local quants: { Quant } = {} + for s = 1, 4 do + local q + if st.useSegment then + q = st.segQuant[s] + if not st.absoluteDelta then + q += baseQ + end + else + q = baseQ + end + @native local function cq(v: number, m: number): number + return if v < 0 then 0 elseif v > m then m else v + end + local y2ac = (AC_TABLE[cq(q + dqy2ac, 127) + 1] * 101581) // 65536 + if y2ac < 8 then + y2ac = 8 + end + quants[s] = { + y1dc = DC_TABLE[cq(q + dqy1dc, 127) + 1], + y1ac = AC_TABLE[cq(q, 127) + 1], + y2dc = DC_TABLE[cq(q + dqy2dc, 127) + 1] * 2, + y2ac = y2ac, + uvdc = DC_TABLE[cq(q + dquvdc, 117) + 1], + uvac = AC_TABLE[cq(q + dquvac, 127) + 1], + } + end + -- reference updates (inter frames) + local refreshGolden, refreshAlt, copyToGolden, copyToAlt = true, true, 0, 0 + if not key then + refreshGolden = getValue(br, 1) == 1 + refreshAlt = getValue(br, 1) == 1 + copyToGolden = if refreshGolden then 0 else getValue(br, 2) + copyToAlt = if refreshAlt then 0 else getValue(br, 2) + st.signBias[3] = getValue(br, 1) + st.signBias[4] = getValue(br, 1) + end + -- a frame that does not refresh the context decodes with the updates below, then the context comes back + local saved: { { number } }? = nil + if getValue(br, 1) == 0 then + saved = { table.clone(st.proba), table.clone(st.ymodeProb), table.clone(st.uvmodeProb), table.clone(st.mvProb) } + end + local refreshLast = key or getValue(br, 1) == 1 + -- token probabilities + local P = st.proba + for i = 1, 1056 do + if getBit(br, COEFF_UPDATE_PROBA[i]) == 1 then + P[i] = getValue(br, 8) + end + end + local useSkip = getValue(br, 1) == 1 + local skipP = if useSkip then getValue(br, 8) else 0 + local probIntra, probLast, probGf = 0, 0, 0 + if not key then + probIntra = getValue(br, 8) + probLast = getValue(br, 8) + probGf = getValue(br, 8) + if getValue(br, 1) == 1 then + for i = 1, 4 do + st.ymodeProb[i] = getValue(br, 8) + end + end + if getValue(br, 1) == 1 then + for i = 1, 3 do + st.uvmodeProb[i] = getValue(br, 8) + end + end + local M = st.mvProb + for i = 1, 38 do + if getBit(br, MV_UPDATE[i]) == 1 then + local x = getValue(br, 7) + M[i] = if x == 0 then 1 else x * 2 + end + end + end + @native local function fail(msg: string): (Frame?, string?) + if saved then + st.proba, st.ymodeProb, st.uvmodeProb, st.mvProb = saved[1], saved[2], saved[3], saved[4] + end + return nil, msg + end + if br.eof then + return fail("truncated: frame header") + end + + -- loop filter levels [segment][reference][mode delta index] and, per level, the interior limit and hev threshold + local lvlTab = table.create(64, 0) + local ilTab, hevTab = table.create(64, 0), table.create(64, 0) + if filterType > 0 then + for s = 0, 3 do + local base + if st.useSegment then + base = st.segFilter[s + 1] + if not st.absoluteDelta then + base += level + end + else + base = level + end + for rf = 0, 3 do + for m = 0, 3 do + local lv = base + if useLfDelta then + lv += st.refLfDelta[rf + 1] + if rf > 0 or m == 0 then + lv += st.modeLfDelta[m + 1] + end + end + lvlTab[s * 16 + rf * 4 + m + 1] = if lv < 0 then 0 elseif lv > 63 then 63 else lv + end + end + end + for lv = 1, 63 do + local il = lv + if sharpness > 0 then + il = rshift(il, if sharpness > 4 then 2 else 1) + if il > 9 - sharpness then + il = 9 - sharpness + end + end + ilTab[lv] = if il < 1 then 1 else il + if key then + hevTab[lv] = if lv >= 40 then 2 elseif lv >= 15 then 1 else 0 + else + hevTab[lv] = if lv >= 40 then 3 elseif lv >= 20 then 2 elseif lv >= 15 then 1 else 0 + end + end + end + + local cur = freeRef(st) + cur.extended = false + local Y, U, V, ys, uvs, yb, uvb = cur.Y, cur.U, cur.V, cur.ys, cur.uvs, cur.yb, cur.uvb + local refs: { Ref } = {} + local bil, full = hdr.profile > 0, hdr.profile == 3 + if not key then + local rl, rg, ra = st.last :: Ref, st.golden :: Ref, st.alt :: Ref + refs[1], refs[2], refs[3] = rl, rg, ra + for k = 1, 3 do + local r = refs[k] + if not r.extended then + Predict.extend(r) + r.extended = true + end + end + end + local topY, topU, topV = bcreate(mbw * 16), bcreate(mbw * 8), bcreate(mbw * 8) + local yuv = bcreate(YUV_SIZE) + local pred = yuv + if not key then + local nmi = (mbw + 1) * (mbh + 1) + if st.miN ~= nmi then + -- zero top row and left column: never written, they read as intra macroblocks without motion + st.miRef, st.miMode = table.create(nmi, 0), table.create(nmi, 0) + st.miMvR, st.miMvC = table.create(nmi, 0), table.create(nmi, 0) + st.miSubR, st.miSubC = table.create(nmi * 16, 0), table.create(nmi * 16, 0) + st.miN = nmi + st.pred = bcreate(YUV_SIZE * mbw) + end + pred = st.pred :: buffer + end + local coeffs = bcreate(mbw * 768) + local dcb = bcreate(32) + local intraT = table.create(mbw * 4, 0) + local intraL = table.create(4, 0) + local topNz = table.create(mbw, 0) + local topNzDc = table.create(mbw, 0) + local rows: Rows = { + i4 = table.create(mbw, false), + modes = table.create(mbw * 16, 0), + uv = table.create(mbw, 0), + ref = table.create(mbw, 0), + mode = table.create(mbw, 0), + part = table.create(mbw, -1), + } + local mbI4, mbModes, mbUv, mbRef, mbMode, mbPart = rows.i4, rows.modes, rows.uv, rows.ref, rows.mode, rows.part + local mbSeg = table.create(mbw, 0) + local mbSkip = table.create(mbw, 0) + local mbNzY = table.create(mbw, 0) + local mbNzUv = table.create(mbw, 0) + local fLimit = table.create(mbw * mbh, 0) + local fIlevel = table.create(mbw * mbh, 0) + local fInner = table.create(mbw * mbh, 0) + local fHev = table.create(mbw * mbh, 0) + local segProba = st.segProba + local segMap = st.segMap + local updateMap = st.updateMap + local miMvR, miMvC, miSubR, miSubC = st.miMvR, st.miMvC, st.miSubR, st.miSubC + + for mby = 0, mbh - 1 do + local tbr = parts[band(mby, lastPart) + 1] + -- modes of the row (first partition) + for k = 1, 4 do + intraL[k] = 0 + end + for mbx = 0, mbw - 1 do + local x1 = mbx + 1 + local si = mby * mbw + x1 + local seg + if updateMap then + if getBit(br, segProba[1]) == 0 then + seg = getBit(br, segProba[2]) + else + seg = getBit(br, segProba[3]) + 2 + end + segMap[si] = seg + elseif key then + seg = 0 + segMap[si] = 0 + else + seg = segMap[si] + end + mbSeg[x1] = seg + mbSkip[x1] = 0 + if useSkip then + mbSkip[x1] = getBit(br, skipP) + end + if not key then + readInterMb(st, br, probIntra, probLast, probGf, (mby + 1) * (mbw + 1) + x1 + 1, mbx, mby, rows) + continue + end + mbRef[x1] = 0 + mbPart[x1] = -1 + local i4 = getBit(br, 145) == 0 + mbI4[x1] = i4 + local t0 = mbx * 4 + if not i4 then + local ymode + if getBit(br, 156) == 1 then + ymode = if getBit(br, 128) == 1 then 1 else 3 + else + ymode = if getBit(br, 163) == 1 then 2 else 0 + end + mbModes[mbx * 16 + 1] = ymode + mbMode[x1] = ymode + for k = 1, 4 do + intraT[t0 + k] = ymode + intraL[k] = ymode + end + else + mbMode[x1] = 4 + for y = 0, 3 do + local ymode = intraL[y + 1] + for x = 0, 3 do + local pr = (intraT[t0 + x + 1] * 10 + ymode) * 9 + if getBit(br, BMODES_PROBA[pr + 1]) == 0 then + ymode = 0 + elseif getBit(br, BMODES_PROBA[pr + 2]) == 0 then + ymode = 1 + elseif getBit(br, BMODES_PROBA[pr + 3]) == 0 then + ymode = 2 + elseif getBit(br, BMODES_PROBA[pr + 4]) == 0 then + if getBit(br, BMODES_PROBA[pr + 5]) == 0 then + ymode = 3 + elseif getBit(br, BMODES_PROBA[pr + 6]) == 0 then + ymode = 4 + else + ymode = 5 + end + elseif getBit(br, BMODES_PROBA[pr + 7]) == 0 then + ymode = 6 + elseif getBit(br, BMODES_PROBA[pr + 8]) == 0 then + ymode = 7 + elseif getBit(br, BMODES_PROBA[pr + 9]) == 0 then + ymode = 8 + else + ymode = 9 + end + intraT[t0 + x + 1] = ymode + mbModes[mbx * 16 + y * 4 + x + 1] = ymode + end + intraL[y + 1] = ymode + end + end + if getBit(br, 142) == 0 then + mbUv[x1] = 0 + elseif getBit(br, 114) == 0 then + mbUv[x1] = 2 + else + mbUv[x1] = if getBit(br, 183) == 1 then 1 else 3 + end + end + if br.eof then + return fail("truncated: first partition (modes)") + end + + -- residuals (token partition) + local leftNz, leftNzDc = 0, 0 + for mbx = 0, mbw - 1 do + local x1 = mbx + 1 + local q = quants[mbSeg[x1] + 1] + local skip = mbSkip[x1] + local i4 = mbI4[x1] + if skip == 0 then + local co = mbx * 768 + bfill(coeffs, co, 0, 768) + local first, acType + local dcNz = 0 + if not i4 then + bfill(dcb, 0, 0, 32) + local ctx = topNzDc[x1] + leftNzDc + local nz = getCoeffs(tbr, P, 1, ctx, q.y2dc, q.y2ac, 0, dcb, 0) + dcNz = if nz > 0 then 1 else 0 + topNzDc[x1] = dcNz + leftNzDc = dcNz + if nz > 1 then + transformWHT(dcb, coeffs, co) + else + local dc0 = (readi16(dcb, 0) + 3) // 8 + for i = 0, 15 do + writei16(coeffs, co + i * 32, dc0) + end + end + first, acType = 1, 0 + else + first, acType = 0, 3 + end + local tnz = band(topNz[x1], 0x0f) + local lnz = band(leftNz, 0x0f) + local nzY = 0 + local dst = co + for _ = 0, 3 do + local l = band(lnz, 1) + local acc = 0 + for _ = 0, 3 do + local ctx = l + band(tnz, 1) + local nz = getCoeffs(tbr, P, acType, ctx, q.y1dc, q.y1ac, first, coeffs, dst) + l = if nz > first then 1 else 0 + tnz = bor(rshift(tnz, 1), l * 128) + acc = nzCode(acc, nz, if readi16(coeffs, dst) ~= 0 then 1 else 0) + dst += 32 + end + tnz = rshift(tnz, 4) + lnz = bor(rshift(lnz, 1), l * 128) + nzY = nzY * 256 + acc + end + local outT = tnz + local outL = rshift(lnz, 4) + local nzUv = 0 + for ch = 0, 2, 2 do + local acc = 0 + tnz = band(rshift(topNz[x1], 4 + ch), 255) + lnz = band(rshift(leftNz, 4 + ch), 255) + for _ = 0, 1 do + local l = band(lnz, 1) + for _ = 0, 1 do + local ctx = l + band(tnz, 1) + local nz = getCoeffs(tbr, P, 2, ctx, q.uvdc, q.uvac, 0, coeffs, dst) + l = if nz > 0 then 1 else 0 + tnz = bor(rshift(tnz, 1), l * 8) + acc = nzCode(acc, nz, if readi16(coeffs, dst) ~= 0 then 1 else 0) + dst += 32 + end + tnz = rshift(tnz, 2) + lnz = bor(rshift(lnz, 1), l * 32) + end + nzUv = bor(nzUv, lshift(acc, 4 * ch)) + outT = bor(outT, lshift(lshift(tnz, 4), ch)) + outL = bor(outL, lshift(band(lnz, 0xf0), ch)) + end + topNz[x1] = band(outT, 255) + leftNz = band(outL, 255) + mbNzY[x1] = nzY + mbNzUv[x1] = nzUv + -- no coefficient at all (libvpx: eobtotal == 0) skips the inner edges of the loop filter + skip = if nzY == 0 and nzUv == 0 and dcNz == 0 then 1 else 0 + else + topNz[x1] = 0 + leftNz = 0 + if not i4 then + topNzDc[x1] = 0 + leftNzDc = 0 + end + mbNzY[x1] = 0 + mbNzUv[x1] = 0 + end + if filterType > 0 then + local lv = lvlTab[mbSeg[x1] * 16 + mbRef[x1] * 4 + MODE_LF[mbMode[x1] + 1] + 1] + local fi = mby * mbw + x1 + if lv > 0 then + local il = ilTab[lv] + fLimit[fi] = 2 * lv + il + fIlevel[fi] = il + fHev[fi] = hevTab[lv] + else + fLimit[fi] = 0 + end + fInner[fi] = if i4 or skip == 0 then 1 else 0 + end + if tbr.eof then + return fail("truncated: token partition") + end + end + + -- reconstruct the row (libwebp ReconstructRow; inter macroblocks predict from the references) + if not key then + Predict.row(refs :: any, mby, mbw, mbRef, mbPart, miMvR, miMvC, miSubR, miSubC, (mby + 1) * (mbw + 1) + 1, pred, YUV_SIZE, Y_OFF, U_OFF, V_OFF, bil, full) + end + for j = 0, 15 do + writeu8(yuv, Y_OFF + j * BPS - 1, 129) + end + for j = 0, 7 do + writeu8(yuv, U_OFF + j * BPS - 1, 129) + writeu8(yuv, V_OFF + j * BPS - 1, 129) + end + if mby > 0 then + writeu8(yuv, Y_OFF - 1 - BPS, 129) + writeu8(yuv, U_OFF - 1 - BPS, 129) + writeu8(yuv, V_OFF - 1 - BPS, 129) + else + bfill(yuv, Y_OFF - BPS - 1, 127, 16 + 4 + 1) + bfill(yuv, U_OFF - BPS - 1, 127, 8 + 1) + bfill(yuv, V_OFF - BPS - 1, 127, 8 + 1) + end + for mbx = 0, mbw - 1 do + local x1 = mbx + 1 + local co = mbx * 768 + local bits = mbNzY[x1] + local rf = mbRef[x1] + if rf == 0 and mbx > 0 then + -- the left context of an intra macroblock: the previous macroblock's last columns + for j = -1, 15 do + writeu32(yuv, Y_OFF + j * BPS - 4, readu32(yuv, Y_OFF + j * BPS + 12)) + end + for j = -1, 7 do + writeu32(yuv, U_OFF + j * BPS - 4, readu32(yuv, U_OFF + j * BPS + 4)) + writeu32(yuv, V_OFF + j * BPS - 4, readu32(yuv, V_OFF + j * BPS + 4)) + end + end + if mby > 0 then + local t = mbx * 16 + writeu32(yuv, Y_OFF - BPS, readu32(topY, t)) + writeu32(yuv, Y_OFF - BPS + 4, readu32(topY, t + 4)) + writeu32(yuv, Y_OFF - BPS + 8, readu32(topY, t + 8)) + writeu32(yuv, Y_OFF - BPS + 12, readu32(topY, t + 12)) + t = mbx * 8 + writeu32(yuv, U_OFF - BPS, readu32(topU, t)) + writeu32(yuv, U_OFF - BPS + 4, readu32(topU, t + 4)) + writeu32(yuv, V_OFF - BPS, readu32(topV, t)) + writeu32(yuv, V_OFF - BPS + 4, readu32(topV, t + 4)) + end + if rf > 0 then + -- the prediction (Predict.row): luma rows 0..15, then the chroma rows (U and V side by side) + local o = mbx * YUV_SIZE + bcopy(yuv, Y_OFF, pred, o + Y_OFF, 15 * BPS + 16) + bcopy(yuv, U_OFF, pred, o + U_OFF, 7 * BPS + 24) + if bits ~= 0 then + for n = 0, 15 do + local dst = Y_OFF + (n % 4) * 4 + (n // 4) * 4 * BPS + doTransform(band(rshift(bits, 30 - 2 * n), 3), coeffs, co + n * 32, yuv, dst) + end + end + else + if mbI4[x1] then + local tr = Y_OFF - BPS + 16 + if mby > 0 then + if mbx >= mbw - 1 then + writeu32(yuv, tr, readu8(topY, mbx * 16 + 15) * 0x01010101) + else + writeu32(yuv, tr, readu32(topY, mbx * 16 + 16)) + end + end + local trv = readu32(yuv, tr) + writeu32(yuv, tr + 4 * BPS, trv) + writeu32(yuv, tr + 8 * BPS, trv) + writeu32(yuv, tr + 12 * BPS, trv) + for n = 0, 15 do + local dst = Y_OFF + (n % 4) * 4 + (n // 4) * 4 * BPS + predict4(yuv, dst, mbModes[mbx * 16 + n + 1]) + doTransform(band(rshift(bits, 30 - 2 * n), 3), coeffs, co + n * 32, yuv, dst) + end + else + predictBlock(yuv, Y_OFF, 16, checkMode(mbx, mby, mbModes[mbx * 16 + 1])) + if bits ~= 0 then + for n = 0, 15 do + local dst = Y_OFF + (n % 4) * 4 + (n // 4) * 4 * BPS + doTransform(band(rshift(bits, 30 - 2 * n), 3), coeffs, co + n * 32, yuv, dst) + end + end + end + local uvm = checkMode(mbx, mby, mbUv[x1]) + predictBlock(yuv, U_OFF, 8, uvm) + predictBlock(yuv, V_OFF, 8, uvm) + end + local buv = mbNzUv[x1] + doUVTransform(buv, coeffs, co + 16 * 32, yuv, U_OFF) + doUVTransform(rshift(buv, 8), coeffs, co + 20 * 32, yuv, V_OFF) + if mby < mbh - 1 then + local t = mbx * 16 + local r = Y_OFF + 15 * BPS + writeu32(topY, t, readu32(yuv, r)) + writeu32(topY, t + 4, readu32(yuv, r + 4)) + writeu32(topY, t + 8, readu32(yuv, r + 8)) + writeu32(topY, t + 12, readu32(yuv, r + 12)) + t = mbx * 8 + r = U_OFF + 7 * BPS + writeu32(topU, t, readu32(yuv, r)) + writeu32(topU, t + 4, readu32(yuv, r + 4)) + writeu32(topV, t, readu32(yuv, r + 16)) + writeu32(topV, t + 4, readu32(yuv, r + 20)) + end + local yo = yb + mby * 16 * ys + mbx * 16 + for j = 0, 15 do + local d, r = yo + j * ys, Y_OFF + j * BPS + writeu32(Y, d, readu32(yuv, r)) + writeu32(Y, d + 4, readu32(yuv, r + 4)) + writeu32(Y, d + 8, readu32(yuv, r + 8)) + writeu32(Y, d + 12, readu32(yuv, r + 12)) + end + local uo = uvb + mby * 8 * uvs + mbx * 8 + for j = 0, 7 do + local d, r = uo + j * uvs, U_OFF + j * BPS + writeu32(U, d, readu32(yuv, r)) + writeu32(U, d + 4, readu32(yuv, r + 4)) + writeu32(V, d, readu32(yuv, r + 16)) + writeu32(V, d + 4, readu32(yuv, r + 20)) + end + end + end + + -- loop filter over the whole frame, macroblocks in raster order (libwebp DoFilter) + if filterType > 0 then + for mby = 0, mbh - 1 do + for mbx = 0, mbw - 1 do + local fi = mby * mbw + mbx + 1 + local limit = fLimit[fi] + if limit ~= 0 then + local inner = fInner[fi] == 1 + local yp = yb + mby * 16 * ys + mbx * 16 + if filterType == 1 then + if mbx > 0 then + simpleFilter(Y, yp, 1, ys, limit + 4) + end + if inner then + for k = 1, 3 do + simpleFilter(Y, yp + 4 * k, 1, ys, limit) + end + end + if mby > 0 then + simpleFilter(Y, yp, ys, 1, limit + 4) + end + if inner then + for k = 1, 3 do + simpleFilter(Y, yp + 4 * k * ys, ys, 1, limit) + end + end + else + local il, hev = fIlevel[fi], fHev[fi] + local up = uvb + mby * 8 * uvs + mbx * 8 + if mbx > 0 then + filterEdge(Y, yp, 1, ys, 16, limit + 4, il, hev) + filterEdge(U, up, 1, uvs, 8, limit + 4, il, hev) + filterEdge(V, up, 1, uvs, 8, limit + 4, il, hev) + end + if inner then + for k = 1, 3 do + filterInner(Y, yp + 4 * k, 1, ys, 16, limit, il, hev) + end + filterInner(U, up + 4, 1, uvs, 8, limit, il, hev) + filterInner(V, up + 4, 1, uvs, 8, limit, il, hev) + end + if mby > 0 then + filterEdge(Y, yp, ys, 1, 16, limit + 4, il, hev) + filterEdge(U, up, uvs, 1, 8, limit + 4, il, hev) + filterEdge(V, up, uvs, 1, 8, limit + 4, il, hev) + end + if inner then + for k = 1, 3 do + filterInner(Y, yp + 4 * k * ys, ys, 1, 16, limit, il, hev) + end + filterInner(U, up + 4 * uvs, uvs, 1, 8, limit, il, hev) + filterInner(V, up + 4 * uvs, uvs, 1, 8, limit, il, hev) + end + end + end + end + end + end + + -- the references (libvpx swap_frame_buffers; copies read the references of the previous frame, as ffmpeg does) + if key then + st.last, st.golden, st.alt = cur, cur, cur + st.hasKey = true + else + local oldLast, oldGolden, oldAlt = st.last, st.golden, st.alt + if refreshGolden then + st.golden = cur + elseif copyToGolden == 1 then + st.golden = oldLast + elseif copyToGolden == 2 then + st.golden = oldAlt + end + if refreshAlt then + st.alt = cur + elseif copyToAlt == 1 then + st.alt = oldLast + elseif copyToAlt == 2 then + st.alt = oldGolden + end + if refreshLast then + st.last = cur + end + end + if saved then + st.proba, st.ymodeProb, st.uvmodeProb, st.mvProb = saved[1], saved[2], saved[3], saved[4] + end + return { width = width, height = height, ref = cur, header = hdr }, nil +end + +return Decode +end +__FILES["codecs/image/Vp8/Predict"] = @native function() + + + +-- codecs/image/Vp8/Predict: VP8 inter prediction (RFC 6386 section 18), after libvpx 1.17 vp8/common/reconinter.c and +-- filter.c (BSD-3-Clause, licenses/libvpx-LICENSE.txt). Out-of-frame motion reads the edge pixels extended forever, +-- which equals libvpx's 32 pixel border plus its motion vector clamping. +local Tables = __include("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 +local rshift, band = bit32.rshift, bit32.band +local SIX, BIL = Tables.SIXTAP, Tables.BILINEAR + +local Predict = {} + +local BORDER = 32 +Predict.BORDER = BORDER + +local BPS = 32 + +local emu = bcreate(32 * 32) +local tmp = bcreate(32 * 32) + +-- six-tap along rows: dst[i] = clamp((sum of src[i - 2 .. i + 3] * taps + 64) >> 7) +@native local function sixH(src: buffer, so: number, ss: number, dst: buffer, d: number, ds: number, w: number, h: number, f: number) + local k = f * 6 + local t0, t1, t2, t3, t4, t5 = SIX[k + 1], SIX[k + 2], SIX[k + 3], SIX[k + 4], SIX[k + 5], SIX[k + 6] + for _ = 1, h do + for i = so - 2, so + w - 3 do + local v = readu8(src, i) * t0 + readu8(src, i + 1) * t1 + readu8(src, i + 2) * t2 + readu8(src, i + 3) * t3 + + readu8(src, i + 4) * t4 + readu8(src, i + 5) * t5 + 64 + writeu8(dst, d + i - so + 2, if v < 0 then 0 elseif v >= 32768 then 255 else rshift(v, 7)) + end + so += ss + d += ds + end +end + +@native local function sixV(src: buffer, so: number, ss: number, dst: buffer, d: number, ds: number, w: number, h: number, f: number) + local k = f * 6 + local t0, t1, t2, t3, t4, t5 = SIX[k + 1], SIX[k + 2], SIX[k + 3], SIX[k + 4], SIX[k + 5], SIX[k + 6] + local s1, s2, s3 = ss, 2 * ss, 3 * ss + for _ = 1, h do + local p = so - s2 + for i = 0, w - 1 do + local q = p + i + local v = readu8(src, q) * t0 + readu8(src, q + s1) * t1 + readu8(src, q + s2) * t2 + readu8(src, q + s3) * t3 + + readu8(src, q + s2 + s2) * t4 + readu8(src, q + s2 + s3) * t5 + 64 + writeu8(dst, d + i, if v < 0 then 0 elseif v >= 32768 then 255 else rshift(v, 7)) + end + so += ss + d += ds + end +end + +-- the bilinear filters: dst[i] = (src[i] * t0 + src[i + 1] * t1 + 64) >> 7 +@native local function bilH(src: buffer, so: number, ss: number, dst: buffer, d: number, ds: number, w: number, h: number, f: number) + local t0, t1 = BIL[f * 2 + 1], BIL[f * 2 + 2] + for _ = 1, h do + for i = 0, w - 1 do + writeu8(dst, d + i, rshift(readu8(src, so + i) * t0 + readu8(src, so + i + 1) * t1 + 64, 7)) + end + so += ss + d += ds + end +end + +@native local function bilV(src: buffer, so: number, ss: number, dst: buffer, d: number, ds: number, w: number, h: number, f: number) + local t0, t1 = BIL[f * 2 + 1], BIL[f * 2 + 2] + for _ = 1, h do + for i = 0, w - 1 do + writeu8(dst, d + i, rshift(readu8(src, so + i) * t0 + readu8(src, so + ss + i) * t1 + 64, 7)) + end + so += ss + d += ds + end +end + +@native local function block(src: buffer, stride: number, base: number, wmax: number, hmax: number, x: number, y: number, mvx: number, mvy: number, w: number, h: number, dst: buffer, d: number, bil: boolean) + local fx, fy = band(mvx, 7), band(mvy, 7) + local px, py = x + (mvx - fx) // 8, y + (mvy - fy) // 8 + local sb, so, ss = src, 0, stride + if px >= 2 - BORDER and py >= 2 - BORDER and px + w + 3 <= wmax + 1 + BORDER and py + h + 3 <= hmax + 1 + BORDER then + so = base + py * stride + px + else + for r = 0, h + 4 do + local sy = py - 2 + r + if sy < 0 then + sy = 0 + elseif sy > hmax then + sy = hmax + end + local row = base + sy * stride + local o = r * 32 + for c = 0, w + 4 do + local sx = px - 2 + c + if sx < 0 then + sx = 0 + elseif sx > wmax then + sx = wmax + end + writeu8(emu, o + c, readu8(src, row + sx)) + end + end + sb, so, ss = emu, 66, 32 + end + if fx == 0 then + if fy == 0 then + for _ = 1, h do + for i = 0, w - 4, 4 do + writeu32(dst, d + i, readu32(sb, so + i)) + end + so += ss + d += BPS + end + elseif bil then + bilV(sb, so, ss, dst, d, BPS, w, h, fy) + else + sixV(sb, so, ss, dst, d, BPS, w, h, fy) + end + elseif fy == 0 then + if bil then + bilH(sb, so, ss, dst, d, BPS, w, h, fx) + else + sixH(sb, so, ss, dst, d, BPS, w, h, fx) + end + elseif bil then + bilH(sb, so, ss, tmp, 0, 32, w, h + 1, fx) + bilV(tmp, 0, 32, dst, d, BPS, w, h, fy) + else + sixH(sb, so - 2 * ss, ss, tmp, 0, 32, w, h + 5, fx) + sixV(tmp, 64, 32, dst, d, BPS, w, h, fy) + end +end + +@native local function chroma16(v: number): number + -- the chroma vector of a whole macroblock: half the luma one, rounded away from zero + if v < 0 then + return -((1 - v) // 2) + end + return (v + 1) // 2 +end + +@native local function chroma4(s: number): number + -- the chroma vector of a 2x2 group of luma blocks: the sum of their 4 vectors / 8, rounded half away from zero + if s < 0 then + return -((4 - s) // 8) + end + return (s + 4) // 8 +end + +type Planes = { + Y: buffer, + U: buffer, + V: buffer, + ys: number, + uvs: number, + yb: number, + uvb: number, + mbw: number, + mbh: number, +} + +@native function Predict.mb(ref: Planes, mbx: number, mby: number, mvr: number, mvc: number, part: number, subR: { number }, subC: { number }, sb: number, dst: buffer, yo: number, uo: number, vo: number, bil: boolean, full: boolean) + local Y, U, V, ys, uvs, yb, uvb = ref.Y, ref.U, ref.V, ref.ys, ref.uvs, ref.yb, ref.uvb + local wl, hl = ref.mbw * 16 - 1, ref.mbh * 16 - 1 + local wc, hc = ref.mbw * 8 - 1, ref.mbh * 8 - 1 + local x, y = mbx * 16, mby * 16 + local cx, cy = mbx * 8, mby * 8 + if part < 0 then + block(Y, ys, yb, wl, hl, x, y, mvc, mvr, 16, 16, dst, yo, bil) + local cr, cc = chroma16(mvr), chroma16(mvc) + if full then + cr -= band(cr, 7) + cc -= band(cc, 7) + end + block(U, uvs, uvb, wc, hc, cx, cy, cc, cr, 8, 8, dst, uo, bil) + block(V, uvs, uvb, wc, hc, cx, cy, cc, cr, 8, 8, dst, vo, bil) + return + end + if part < 3 then + for q = 0, 3 do + local bx, by = (q % 2) * 8, (q // 2) * 8 + local k = sb + by + bx // 4 + 1 + block(Y, ys, yb, wl, hl, x + bx, y + by, subC[k], subR[k], 8, 8, dst, yo + by * BPS + bx, bil) + end + else + for b = 0, 15, 2 do + local k = sb + b + 1 + local bx, by = (b % 4) * 4, (b // 4) * 4 + local r0, c0 = subR[k], subC[k] + if r0 == subR[k + 1] and c0 == subC[k + 1] then + block(Y, ys, yb, wl, hl, x + bx, y + by, c0, r0, 8, 4, dst, yo + by * BPS + bx, bil) + else + block(Y, ys, yb, wl, hl, x + bx, y + by, c0, r0, 4, 4, dst, yo + by * BPS + bx, bil) + block(Y, ys, yb, wl, hl, x + bx + 4, y + by, subC[k + 1], subR[k + 1], 4, 4, dst, yo + by * BPS + bx + 4, bil) + end + end + end + for i = 0, 1 do + local rr, rc = 0, 0 + for j = 0, 1 do + local k = sb + i * 8 + j * 2 + 1 + local cr = chroma4(subR[k] + subR[k + 1] + subR[k + 4] + subR[k + 5]) + local cc = chroma4(subC[k] + subC[k + 1] + subC[k + 4] + subC[k + 5]) + if full then + cr -= band(cr, 7) + cc -= band(cc, 7) + end + if j == 0 then + rr, rc = cr, cc + elseif cr == rr and cc == rc then + -- both 4x4 chroma blocks of the row share one vector: one 8x4 block + block(U, uvs, uvb, wc, hc, cx, cy + i * 4, cc, cr, 8, 4, dst, uo + i * 4 * BPS, bil) + block(V, uvs, uvb, wc, hc, cx, cy + i * 4, cc, cr, 8, 4, dst, vo + i * 4 * BPS, bil) + else + block(U, uvs, uvb, wc, hc, cx, cy + i * 4, rc, rr, 4, 4, dst, uo + i * 4 * BPS, bil) + block(V, uvs, uvb, wc, hc, cx, cy + i * 4, rc, rr, 4, 4, dst, vo + i * 4 * BPS, bil) + block(U, uvs, uvb, wc, hc, cx + 4, cy + i * 4, cc, cr, 4, 4, dst, uo + i * 4 * BPS + 4, bil) + block(V, uvs, uvb, wc, hc, cx + 4, cy + i * 4, cc, cr, 4, 4, dst, vo + i * 4 * BPS + 4, bil) + end + end + end +end + +@native function Predict.row(refs: { Planes }, mby: number, mbw: number, ref: { number }, part: { number }, miMvR: { number }, miMvC: { number }, miSubR: { number }, miSubC: { number }, mi0: number, pred: buffer, chunk: number, yo: number, uo: number, vo: number, bil: boolean, full: boolean) + for mbx = 0, mbw - 1 do + local rf = ref[mbx + 1] + if rf > 0 then + local mi = mi0 + mbx + 1 + local o = mbx * chunk + Predict.mb(refs[rf], mbx, mby, miMvR[mi], miMvC[mi], part[mbx + 1], miSubR, miSubC, (mi - 1) * 16, pred, o + yo, o + uo, o + vo, bil, full) + end + end +end + +@native local function extend(P: buffer, stride: number, base: number, w: number, h: number) + for r = 0, h - 1 do + local o = base + r * stride + bfill(P, o - BORDER, readu8(P, o), BORDER) + bfill(P, o + w, readu8(P, o + w - 1), BORDER) + end + local top = base - BORDER + local bottom = base + (h - 1) * stride - BORDER + for r = 1, BORDER do + bcopy(P, top - r * stride, P, top, stride) + bcopy(P, bottom + r * stride, P, bottom, stride) + end +end + +@native function Predict.extend(ref: Planes) + extend(ref.Y, ref.ys, ref.yb, ref.mbw * 16, ref.mbh * 16) + extend(ref.U, ref.uvs, ref.uvb, ref.mbw * 8, ref.mbh * 8) + extend(ref.V, ref.uvs, ref.uvb, ref.mbw * 8, ref.mbh * 8) +end + +return Predict +end +__FILES["codecs/image/Vp8/Tables"] = function() + +-- codecs/image/Vp8/Tables: the VP8 tables of RFC 6386 (sections 11.5, 13.4, 13.5, 14.1, 16-18), from libwebp 1.6 src/dec +-- (BSD-3-Clause, licenses/libwebp-LICENSE.txt) and libvpx 1.17 vp8/common (BSD-3-Clause, licenses/libvpx-LICENSE.txt). +-- Flat 1-based arrays. +local Tables = {} + +-- default token probabilities [type 4][band 8][ctx 3][proba 11]: index ((t * 8 + b) * 3 + c) * 11 + p + 1 +Tables.COEFF_PROBA0 = { + 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, + 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 253, 136, 254, 255, 228, 219, 128, 128, 128, 128, 128, + 189, 129, 242, 255, 227, 213, 255, 219, 128, 128, 128, 106, 126, 227, 252, 214, 209, 255, 255, 128, 128, 128, + 1, 98, 248, 255, 236, 226, 255, 255, 128, 128, 128, 181, 133, 238, 254, 221, 234, 255, 154, 128, 128, 128, + 78, 134, 202, 247, 198, 180, 255, 219, 128, 128, 128, 1, 185, 249, 255, 243, 255, 128, 128, 128, 128, 128, + 184, 150, 247, 255, 236, 224, 128, 128, 128, 128, 128, 77, 110, 216, 255, 236, 230, 128, 128, 128, 128, 128, + 1, 101, 251, 255, 241, 255, 128, 128, 128, 128, 128, 170, 139, 241, 252, 236, 209, 255, 255, 128, 128, 128, + 37, 116, 196, 243, 228, 255, 255, 255, 128, 128, 128, 1, 204, 254, 255, 245, 255, 128, 128, 128, 128, 128, + 207, 160, 250, 255, 238, 128, 128, 128, 128, 128, 128, 102, 103, 231, 255, 211, 171, 128, 128, 128, 128, 128, + 1, 152, 252, 255, 240, 255, 128, 128, 128, 128, 128, 177, 135, 243, 255, 234, 225, 128, 128, 128, 128, 128, + 80, 129, 211, 255, 194, 224, 128, 128, 128, 128, 128, 1, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128, + 246, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128, 255, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, + 198, 35, 237, 223, 193, 187, 162, 160, 145, 155, 62, 131, 45, 198, 221, 172, 176, 220, 157, 252, 221, 1, + 68, 47, 146, 208, 149, 167, 221, 162, 255, 223, 128, 1, 149, 241, 255, 221, 224, 255, 255, 128, 128, 128, + 184, 141, 234, 253, 222, 220, 255, 199, 128, 128, 128, 81, 99, 181, 242, 176, 190, 249, 202, 255, 255, 128, + 1, 129, 232, 253, 214, 197, 242, 196, 255, 255, 128, 99, 121, 210, 250, 201, 198, 255, 202, 128, 128, 128, + 23, 91, 163, 242, 170, 187, 247, 210, 255, 255, 128, 1, 200, 246, 255, 234, 255, 128, 128, 128, 128, 128, + 109, 178, 241, 255, 231, 245, 255, 255, 128, 128, 128, 44, 130, 201, 253, 205, 192, 255, 255, 128, 128, 128, + 1, 132, 239, 251, 219, 209, 255, 165, 128, 128, 128, 94, 136, 225, 251, 218, 190, 255, 255, 128, 128, 128, + 22, 100, 174, 245, 186, 161, 255, 199, 128, 128, 128, 1, 182, 249, 255, 232, 235, 128, 128, 128, 128, 128, + 124, 143, 241, 255, 227, 234, 128, 128, 128, 128, 128, 35, 77, 181, 251, 193, 211, 255, 205, 128, 128, 128, + 1, 157, 247, 255, 236, 231, 255, 255, 128, 128, 128, 121, 141, 235, 255, 225, 227, 255, 255, 128, 128, 128, + 45, 99, 188, 251, 195, 217, 255, 224, 128, 128, 128, 1, 1, 251, 255, 213, 255, 128, 128, 128, 128, 128, + 203, 1, 248, 255, 255, 128, 128, 128, 128, 128, 128, 137, 1, 177, 255, 224, 255, 128, 128, 128, 128, 128, + 253, 9, 248, 251, 207, 208, 255, 192, 128, 128, 128, 175, 13, 224, 243, 193, 185, 249, 198, 255, 255, 128, + 73, 17, 171, 221, 161, 179, 236, 167, 255, 234, 128, 1, 95, 247, 253, 212, 183, 255, 255, 128, 128, 128, + 239, 90, 244, 250, 211, 209, 255, 255, 128, 128, 128, 155, 77, 195, 248, 188, 195, 255, 255, 128, 128, 128, + 1, 24, 239, 251, 218, 219, 255, 205, 128, 128, 128, 201, 51, 219, 255, 196, 186, 128, 128, 128, 128, 128, + 69, 46, 190, 239, 201, 218, 255, 228, 128, 128, 128, 1, 191, 251, 255, 255, 128, 128, 128, 128, 128, 128, + 223, 165, 249, 255, 213, 255, 128, 128, 128, 128, 128, 141, 124, 248, 255, 255, 128, 128, 128, 128, 128, 128, + 1, 16, 248, 255, 255, 128, 128, 128, 128, 128, 128, 190, 36, 230, 255, 236, 255, 128, 128, 128, 128, 128, + 149, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128, 1, 226, 255, 128, 128, 128, 128, 128, 128, 128, 128, + 247, 192, 255, 128, 128, 128, 128, 128, 128, 128, 128, 240, 128, 255, 128, 128, 128, 128, 128, 128, 128, 128, + 1, 134, 252, 255, 255, 128, 128, 128, 128, 128, 128, 213, 62, 250, 255, 255, 128, 128, 128, 128, 128, 128, + 55, 93, 255, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, + 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, + 202, 24, 213, 235, 186, 191, 220, 160, 240, 175, 255, 126, 38, 182, 232, 169, 184, 228, 174, 255, 187, 128, + 61, 46, 138, 219, 151, 178, 240, 170, 255, 216, 128, 1, 112, 230, 250, 199, 191, 247, 159, 255, 255, 128, + 166, 109, 228, 252, 211, 215, 255, 174, 128, 128, 128, 39, 77, 162, 232, 172, 180, 245, 178, 255, 255, 128, + 1, 52, 220, 246, 198, 199, 249, 220, 255, 255, 128, 124, 74, 191, 243, 183, 193, 250, 221, 255, 255, 128, + 24, 71, 130, 219, 154, 170, 243, 182, 255, 255, 128, 1, 182, 225, 249, 219, 240, 255, 224, 128, 128, 128, + 149, 150, 226, 252, 216, 205, 255, 171, 128, 128, 128, 28, 108, 170, 242, 183, 194, 254, 223, 255, 255, 128, + 1, 81, 230, 252, 204, 203, 255, 192, 128, 128, 128, 123, 102, 209, 247, 188, 196, 255, 233, 128, 128, 128, + 20, 95, 153, 243, 164, 173, 255, 203, 128, 128, 128, 1, 222, 248, 255, 216, 213, 128, 128, 128, 128, 128, + 168, 175, 246, 252, 235, 205, 255, 255, 128, 128, 128, 47, 116, 215, 255, 211, 212, 255, 255, 128, 128, 128, + 1, 121, 236, 253, 212, 214, 255, 255, 128, 128, 128, 141, 84, 213, 252, 201, 202, 255, 219, 128, 128, 128, + 42, 80, 160, 240, 162, 185, 255, 205, 128, 128, 128, 1, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128, + 244, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128, 238, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128, +} +-- token probability update probabilities, same layout +Tables.COEFF_UPDATE_PROBA = { + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 176, 246, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 223, 241, 252, 255, 255, 255, 255, 255, 255, 255, 255, 249, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 244, 252, 255, 255, 255, 255, 255, 255, 255, 255, 234, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, + 253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 246, 254, 255, 255, 255, 255, 255, 255, 255, 255, + 239, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 248, 254, 255, 255, 255, 255, 255, 255, 255, 255, 251, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255, + 251, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 254, 253, 255, 254, 255, 255, 255, 255, 255, 255, 250, 255, 254, 255, 254, 255, 255, 255, 255, 255, 255, + 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 217, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 225, 252, 241, 253, 255, 255, 254, 255, 255, 255, 255, + 234, 250, 241, 250, 253, 255, 253, 254, 255, 255, 255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 223, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 238, 253, 254, 254, 255, 255, 255, 255, 255, 255, 255, + 255, 248, 254, 255, 255, 255, 255, 255, 255, 255, 255, 249, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 253, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 247, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255, 252, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, + 253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 254, 253, 255, 255, 255, 255, 255, 255, 255, 255, 250, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 186, 251, 250, 255, 255, 255, 255, 255, 255, 255, 255, 234, 251, 244, 254, 255, 255, 255, 255, 255, 255, 255, + 251, 251, 243, 253, 254, 255, 254, 255, 255, 255, 255, 255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255, + 236, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255, 251, 253, 253, 254, 254, 255, 255, 255, 255, 255, 255, + 255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 254, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 248, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 250, 254, 252, 254, 255, 255, 255, 255, 255, 255, 255, + 248, 254, 249, 253, 255, 255, 255, 255, 255, 255, 255, 255, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255, + 246, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255, 252, 254, 251, 254, 254, 255, 255, 255, 255, 255, 255, + 255, 254, 252, 255, 255, 255, 255, 255, 255, 255, 255, 248, 254, 253, 255, 255, 255, 255, 255, 255, 255, 255, + 253, 255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 251, 254, 255, 255, 255, 255, 255, 255, 255, 255, + 245, 251, 254, 255, 255, 255, 255, 255, 255, 255, 255, 253, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 251, 253, 255, 255, 255, 255, 255, 255, 255, 255, 252, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 252, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 249, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 253, 255, 255, 255, 255, 255, 255, 255, 255, 250, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, +} +-- 4x4 intra mode probabilities [top 10][left 10][9]: index (top * 10 + left) * 9 + i + 1 +Tables.BMODES_PROBA = { + 231, 120, 48, 89, 115, 113, 120, 152, 112, 152, 179, 64, 126, 170, 118, 46, 70, 95, 175, 69, 143, 80, + 85, 82, 72, 155, 103, 56, 58, 10, 171, 218, 189, 17, 13, 152, 114, 26, 17, 163, 44, 195, 21, 10, + 173, 121, 24, 80, 195, 26, 62, 44, 64, 85, 144, 71, 10, 38, 171, 213, 144, 34, 26, 170, 46, 55, + 19, 136, 160, 33, 206, 71, 63, 20, 8, 114, 114, 208, 12, 9, 226, 81, 40, 11, 96, 182, 84, 29, + 16, 36, 134, 183, 89, 137, 98, 101, 106, 165, 148, 72, 187, 100, 130, 157, 111, 32, 75, 80, 66, 102, + 167, 99, 74, 62, 40, 234, 128, 41, 53, 9, 178, 241, 141, 26, 8, 107, 74, 43, 26, 146, 73, 166, + 49, 23, 157, 65, 38, 105, 160, 51, 52, 31, 115, 128, 104, 79, 12, 27, 217, 255, 87, 17, 7, 87, + 68, 71, 44, 114, 51, 15, 186, 23, 47, 41, 14, 110, 182, 183, 21, 17, 194, 66, 45, 25, 102, 197, + 189, 23, 18, 22, 88, 88, 147, 150, 42, 46, 45, 196, 205, 43, 97, 183, 117, 85, 38, 35, 179, 61, + 39, 53, 200, 87, 26, 21, 43, 232, 171, 56, 34, 51, 104, 114, 102, 29, 93, 77, 39, 28, 85, 171, + 58, 165, 90, 98, 64, 34, 22, 116, 206, 23, 34, 43, 166, 73, 107, 54, 32, 26, 51, 1, 81, 43, + 31, 68, 25, 106, 22, 64, 171, 36, 225, 114, 34, 19, 21, 102, 132, 188, 16, 76, 124, 62, 18, 78, + 95, 85, 57, 50, 48, 51, 193, 101, 35, 159, 215, 111, 89, 46, 111, 60, 148, 31, 172, 219, 228, 21, + 18, 111, 112, 113, 77, 85, 179, 255, 38, 120, 114, 40, 42, 1, 196, 245, 209, 10, 25, 109, 88, 43, + 29, 140, 166, 213, 37, 43, 154, 61, 63, 30, 155, 67, 45, 68, 1, 209, 100, 80, 8, 43, 154, 1, + 51, 26, 71, 142, 78, 78, 16, 255, 128, 34, 197, 171, 41, 40, 5, 102, 211, 183, 4, 1, 221, 51, + 50, 17, 168, 209, 192, 23, 25, 82, 138, 31, 36, 171, 27, 166, 38, 44, 229, 67, 87, 58, 169, 82, + 115, 26, 59, 179, 63, 59, 90, 180, 59, 166, 93, 73, 154, 40, 40, 21, 116, 143, 209, 34, 39, 175, + 47, 15, 16, 183, 34, 223, 49, 45, 183, 46, 17, 33, 183, 6, 98, 15, 32, 183, 57, 46, 22, 24, + 128, 1, 54, 17, 37, 65, 32, 73, 115, 28, 128, 23, 128, 205, 40, 3, 9, 115, 51, 192, 18, 6, + 223, 87, 37, 9, 115, 59, 77, 64, 21, 47, 104, 55, 44, 218, 9, 54, 53, 130, 226, 64, 90, 70, + 205, 40, 41, 23, 26, 57, 54, 57, 112, 184, 5, 41, 38, 166, 213, 30, 34, 26, 133, 152, 116, 10, + 32, 134, 39, 19, 53, 221, 26, 114, 32, 73, 255, 31, 9, 65, 234, 2, 15, 1, 118, 73, 75, 32, + 12, 51, 192, 255, 160, 43, 51, 88, 31, 35, 67, 102, 85, 55, 186, 85, 56, 21, 23, 111, 59, 205, + 45, 37, 192, 55, 38, 70, 124, 73, 102, 1, 34, 98, 125, 98, 42, 88, 104, 85, 117, 175, 82, 95, + 84, 53, 89, 128, 100, 113, 101, 45, 75, 79, 123, 47, 51, 128, 81, 171, 1, 57, 17, 5, 71, 102, + 57, 53, 41, 49, 38, 33, 13, 121, 57, 73, 26, 1, 85, 41, 10, 67, 138, 77, 110, 90, 47, 114, + 115, 21, 2, 10, 102, 255, 166, 23, 6, 101, 29, 16, 10, 85, 128, 101, 196, 26, 57, 18, 10, 102, + 102, 213, 34, 20, 43, 117, 20, 15, 36, 163, 128, 68, 1, 26, 102, 61, 71, 37, 34, 53, 31, 243, + 192, 69, 60, 71, 38, 73, 119, 28, 222, 37, 68, 45, 128, 34, 1, 47, 11, 245, 171, 62, 17, 19, + 70, 146, 85, 55, 62, 70, 37, 43, 37, 154, 100, 163, 85, 160, 1, 63, 9, 92, 136, 28, 64, 32, + 201, 85, 75, 15, 9, 9, 64, 255, 184, 119, 16, 86, 6, 28, 5, 64, 255, 25, 248, 1, 56, 8, + 17, 132, 137, 255, 55, 116, 128, 58, 15, 20, 82, 135, 57, 26, 121, 40, 164, 50, 31, 137, 154, 133, + 25, 35, 218, 51, 103, 44, 131, 131, 123, 31, 6, 158, 86, 40, 64, 135, 148, 224, 45, 183, 128, 22, + 26, 17, 131, 240, 154, 14, 1, 209, 45, 16, 21, 91, 64, 222, 7, 1, 197, 56, 21, 39, 155, 60, + 138, 23, 102, 213, 83, 12, 13, 54, 192, 255, 68, 47, 28, 85, 26, 85, 85, 128, 128, 32, 146, 171, + 18, 11, 7, 63, 144, 171, 4, 4, 246, 35, 27, 10, 146, 174, 171, 12, 26, 128, 190, 80, 35, 99, + 180, 80, 126, 54, 45, 85, 126, 47, 87, 176, 51, 41, 20, 32, 101, 75, 128, 139, 118, 146, 116, 128, + 85, 56, 41, 15, 176, 236, 85, 37, 9, 62, 71, 30, 17, 119, 118, 255, 17, 18, 138, 101, 38, 60, + 138, 55, 70, 43, 26, 142, 146, 36, 19, 30, 171, 255, 97, 27, 20, 138, 45, 61, 62, 219, 1, 81, + 188, 64, 32, 41, 20, 117, 151, 142, 20, 21, 163, 112, 19, 12, 61, 195, 128, 48, 4, 24, +} +-- DC dequantization factors, index q + 1 (q 0..127) +Tables.DC_TABLE = { + 4, 5, 6, 7, 8, 9, 10, 10, 11, 12, 13, 14, 15, 16, 17, 17, 18, 19, 20, 20, 21, 21, + 22, 22, 23, 23, 24, 25, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 37, 38, 39, + 40, 41, 42, 43, 44, 45, 46, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, + 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 76, 77, 78, 79, 80, 81, + 82, 83, 84, 85, 86, 87, 88, 89, 91, 93, 95, 96, 98, 100, 101, 102, 104, 106, 108, 110, 112, 114, + 116, 118, 122, 124, 126, 128, 130, 132, 134, 136, 138, 140, 143, 145, 148, 151, 154, 157, +} +-- AC dequantization factors, index q + 1 +Tables.AC_TABLE = { + 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, + 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, + 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, + 82, 84, 86, 88, 90, 92, 94, 96, 98, 100, 102, 104, 106, 108, 110, 112, 114, 116, 119, 122, 125, 128, + 131, 134, 137, 140, 143, 146, 149, 152, 155, 158, 161, 164, 167, 170, 173, 177, 181, 185, 189, 193, 197, 201, + 205, 209, 213, 217, 221, 225, 229, 234, 239, 245, 249, 254, 259, 264, 269, 274, 279, 284, +} +-- coefficient band of each position (with a sentinel for position 16) +Tables.BANDS = { 0, 1, 2, 3, 6, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7, 0 } +-- zigzag scan: coefficient n goes to position ZIGZAG[n + 1] +Tables.ZIGZAG = { 0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15 } +-- extra bits probabilities for the DCT_CAT3..6 tokens +Tables.CAT3 = { 173, 148, 140 } +Tables.CAT4 = { 176, 155, 140, 135 } +Tables.CAT5 = { 180, 157, 141, 134, 130 } +Tables.CAT6 = { 254, 254, 243, 230, 196, 177, 153, 140, 133, 130, 129 } + +-- inter frames: default intra mode probabilities (16x16 / chroma, kept in the frame context) and the fixed 4x4 ones +Tables.YMODE_PROB = { 112, 86, 140, 37 } +Tables.UVMODE_PROB = { 162, 101, 204 } +Tables.BMODE_PROB = { 120, 90, 79, 133, 87, 85, 80, 111, 151 } + +-- motion vector probabilities, row then column (19 each): is short, sign, short tree (7), long bits (10) +Tables.MV_DEFAULT = { + 162, 128, 225, 146, 172, 147, 214, 39, 156, 128, 129, 132, 75, 145, 178, 206, 239, 254, 254, + 164, 128, 204, 170, 119, 235, 140, 230, 228, 128, 130, 130, 74, 148, 180, 203, 236, 254, 254, +} +Tables.MV_UPDATE = { + 237, 246, 253, 253, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 250, 250, 252, 254, 254, + 231, 243, 245, 253, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 251, 251, 254, 254, 254, +} + +-- mode contexts [count 0..5][tree node 0..3]: index count * 4 + node + 1 +Tables.MODE_CONTEXTS = { + 7, 1, 1, 143, + 14, 18, 14, 107, + 135, 64, 57, 68, + 60, 56, 128, 65, + 159, 134, 128, 34, + 234, 188, 128, 28, +} + +-- sub-block motion vector reference probabilities [(above zero << 2) | (left zero << 1) | (left == above)][3] +Tables.SUB_MV_REF_PROB = { + 147, 136, 18, + 223, 1, 34, + 106, 145, 1, + 208, 1, 1, + 179, 121, 1, + 223, 1, 34, + 179, 121, 1, + 208, 1, 1, +} + +-- split partitions (16x8, 8x16, 8x8, 4x4): the first block of each partition [s * 16 + j + 1], the blocks of each +-- partition in order [s * 16 + j * count + i + 1], and the number of blocks per partition +Tables.SPLIT_OFFSET = { + 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 2, 8, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, +} +Tables.SPLIT_FILL = { + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 0, 1, 4, 5, 8, 9, 12, 13, 2, 3, 6, 7, 10, 11, 14, 15, + 0, 1, 4, 5, 2, 3, 6, 7, 8, 9, 12, 13, 10, 11, 14, 15, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, +} +Tables.SPLIT_COUNT = { 8, 8, 4, 1 } + +-- the six-tap sub-pixel filters [fraction 0..7][tap 0..5] and the bilinear ones [fraction][2] (versions 1-3) +Tables.SIXTAP = { + 0, 0, 128, 0, 0, 0, + 0, -6, 123, 12, -1, 0, + 2, -11, 108, 36, -8, 1, + 0, -9, 93, 50, -6, 0, + 3, -16, 77, 77, -16, 3, + 0, -6, 50, 93, -9, 0, + 1, -8, 36, 108, -11, 2, + 0, -1, 12, 123, -6, 0, +} +Tables.BILINEAR = { 128, 0, 112, 16, 96, 32, 80, 48, 64, 64, 48, 80, 32, 96, 16, 112 } + +return Tables +end +__FILES["codecs/image/Vp8/Yuv"] = @native function() + + + +-- codecs/image/Vp8/Yuv: 4:2:0 BT.601 limited-range Y'CbCr -> rgba8, bit-exact with libwebp (src/dsp/yuv.h VP8YuvToRgb; +-- src/dsp/upsampling.c "fancy" 9-3-3-1 upsampler, or point sampling as dwebp -nofancy). A port of libwebp 1.6 +-- (BSD-3-Clause, licenses/libwebp-LICENSE.txt). +local rshift = bit32.rshift +local readu8, writeu8, writeu32 = buffer.readu8, buffer.writeu8, buffer.writeu32 +local bcreate = buffer.create + +local Yuv = {} + +@native local function clip(v: number): number + -- VP8Clip8: v in 14-bit fixed point + if v >= 0 and v < 16384 then + return rshift(v, 6) + end + return if v < 0 then 0 else 255 +end + +@native local function mulHi(v: number, c: number): number + return rshift(v * c, 8) +end + +@native local function rgba(y: number, u: number, v: number): number + local yy = mulHi(y, 19077) + local r = clip(yy + mulHi(v, 26149) - 14234) + local g = clip(yy - mulHi(u, 6419) - mulHi(v, 13320) + 8708) + local b = clip(yy + mulHi(u, 33050) - 17685) + return r + g * 256 + b * 65536 + 0xff000000 +end +Yuv.rgba = rgba + +-- libwebp UPSAMPLE_FUNC for one or two output rows (by < 0: no bottom row) +@native local function upsamplePair(Y: buffer, U: buffer, V: buffer, ty: number, by: number, tu: number, cu: number, out: buffer, dt: number, db: number, len: number) + local last = rshift(len - 1, 1) + local tlu, tlv = readu8(U, tu), readu8(V, tu) + local lu, lv = readu8(U, cu), readu8(V, cu) + do + local u0 = rshift(3 * tlu + lu + 2, 2) + local v0 = rshift(3 * tlv + lv + 2, 2) + writeu32(out, dt, rgba(readu8(Y, ty), u0, v0)) + end + if by >= 0 then + local u0 = rshift(3 * lu + tlu + 2, 2) + local v0 = rshift(3 * lv + tlv + 2, 2) + writeu32(out, db, rgba(readu8(Y, by), u0, v0)) + end + for x = 1, last do + local tu1, tv1 = readu8(U, tu + x), readu8(V, tu + x) + local u1, v1 = readu8(U, cu + x), readu8(V, cu + x) + local avgU = tlu + tu1 + lu + u1 + 8 + local avgV = tlv + tv1 + lv + v1 + 8 + local d12u = rshift(avgU + 2 * (tu1 + lu), 3) + local d03u = rshift(avgU + 2 * (tlu + u1), 3) + local d12v = rshift(avgV + 2 * (tv1 + lv), 3) + local d03v = rshift(avgV + 2 * (tlv + v1), 3) + local px = 2 * x + writeu32(out, dt + (px - 1) * 4, rgba(readu8(Y, ty + px - 1), rshift(d12u + tlu, 1), rshift(d12v + tlv, 1))) + writeu32(out, dt + px * 4, rgba(readu8(Y, ty + px), rshift(d03u + tu1, 1), rshift(d03v + tv1, 1))) + if by >= 0 then + writeu32(out, db + (px - 1) * 4, rgba(readu8(Y, by + px - 1), rshift(d03u + lu, 1), rshift(d03v + lv, 1))) + writeu32(out, db + px * 4, rgba(readu8(Y, by + px), rshift(d12u + u1, 1), rshift(d12v + v1, 1))) + end + tlu, tlv, lu, lv = tu1, tv1, u1, v1 + end + if len % 2 == 0 then + local u0 = rshift(3 * tlu + lu + 2, 2) + local v0 = rshift(3 * tlv + lv + 2, 2) + writeu32(out, dt + (len - 1) * 4, rgba(readu8(Y, ty + len - 1), u0, v0)) + if by >= 0 then + u0 = rshift(3 * lu + tlu + 2, 2) + v0 = rshift(3 * lv + tlv + 2, 2) + writeu32(out, db + (len - 1) * 4, rgba(readu8(Y, by + len - 1), u0, v0)) + end + end +end + +@native function Yuv.toRgba(Y: buffer, U: buffer, V: buffer, w: number, h: number, fancy: boolean, out: buffer?): buffer + local o = out or bcreate(w * h * 4) + local cw = (w + 1) // 2 + local stride = w * 4 + if fancy then + -- libwebp EmitFancyRGB over the whole picture: row 0 alone (chroma mirrored), then pairs of rows between two + -- chroma rows, then the last row of an even height alone + upsamplePair(Y, U, V, 0, -1, 0, 0, o, 0, -1, w) + local y = 1 + local cu = 0 + while y + 1 < h do + upsamplePair(Y, U, V, y * w, (y + 1) * w, cu, cu + cw, o, y * stride, (y + 1) * stride, w) + cu += cw + y += 2 + end + if h % 2 == 0 and h > 1 then + upsamplePair(Y, U, V, (h - 1) * w, -1, cu, cu, o, (h - 1) * stride, -1, w) + end + else + for y = 0, h - 1 do + local cu = (y // 2) * cw + local yo = y * w + local oo = y * stride + for x = 0, w - 1 do + local c = cu + x // 2 + writeu32(o, oo + x * 4, rgba(readu8(Y, yo + x), readu8(U, c), readu8(V, c))) + end + end + end + return o +end + +@native function Yuv.setAlpha(o: buffer, a: buffer, n: number) + for i = 0, n - 1 do + writeu8(o, i * 4 + 3, readu8(a, i)) + end +end + +return Yuv +end +__FILES["codecs/image/Vp8L"] = function() + +-- codecs/image/Vp8L: WebP lossless (VP8L, RFC 9649 section 3). +-- Decoder ported from libwebp 1.6 (BSD-3-Clause, licenses/libwebp-LICENSE.txt), bit-exact with it; encoder new. +local Err = __include("core/Err") +local Decode = __include("codecs/image/Vp8L/Decode") +local Encode = __include("codecs/image/Vp8L/Encode") + +local Vp8L = {} + +local DEFAULT_MAX_PIXELS = 2 ^ 28 + +local function fail(msg: string?, offset: number?): Err.Err + local m = msg or "bad data" + if string.sub(m, 1, 11) == "truncated: " then + return Err.new(Err.TRUNCATED, string.sub(m, 12), offset) + elseif string.sub(m, 1, 7) == "limit: " then + return Err.new(Err.LIMIT, string.sub(m, 8), offset) + end + return Err.new(Err.CORRUPT, m, offset) +end +Vp8L.fail = fail + +local function range(buf: buffer, off: number?, len: number?): (number, number) + local n = buffer.len(buf) + local o = math.clamp(off or 0, 0, n) + return o, math.clamp(len or (n - o), 0, n - o) +end + +function Vp8L.info(buf: buffer, off: number?, len: number?): ({ width: number, height: number, alpha: boolean }?, Err.Err?) + local o, l = range(buf, off, len) + local w, h, alpha, err = Decode.header(buf, o, l) + if not w then + return nil, fail(err, o) + end + return { width = w, height = h, alpha = alpha }, nil +end + +function Vp8L.decodeArgb(buf: buffer, off: number?, len: number?, maxPixels: number?): (buffer?, any, number?, boolean?) + local o, l = range(buf, off, len) + local px, w, h, alpha, err = Decode.argb(buf, o, l, maxPixels or DEFAULT_MAX_PIXELS) + if not px then + return nil, fail(err, o) + end + return px, w, h, alpha +end + +function Vp8L.decode(buf: buffer, off: number?, len: number?, maxPixels: number?): (buffer?, any, number?, boolean?) + local px, w, h, alpha = Vp8L.decodeArgb(buf, off, len, maxPixels) + if not px then + return nil, w + end + return Decode.toRgba(px, w * (h :: number)), w, h, alpha +end + +function Vp8L.decodeAlpha(buf: buffer, off: number?, len: number?, width: number, height: number): (buffer?, Err.Err?) + local o, l = range(buf, off, len) + local px, err = Decode.stream(buf, o, l, width, height) + if not px then + return nil, fail(err, o) + end + return Decode.green(px, width * height), nil +end + +Vp8L.toRgba = Decode.toRgba + +type EncodeOptions = { + effort: number?, + exact: boolean?, + alphaHint: boolean?, +} + +function Vp8L.encode(rgba: buffer, width: number, height: number, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(rgba) ~= "buffer" or type(width) ~= "number" or type(height) ~= "number" then + return nil, Err.new(Err.ARG, "encode: needs rgba8 pixels, width, height") + end + if width < 1 or height < 1 or width > 16384 or height > 16384 or width % 1 ~= 0 or height % 1 ~= 0 then + return nil, Err.new(Err.ARG, "encode: size must be 1..16384") + end + if buffer.len(rgba) < width * height * 4 then + return nil, Err.new(Err.ARG, "encode: pixel buffer too small") + end + local o: EncodeOptions = opts or {} :: EncodeOptions + local effort = o.effort or 5 + if type(effort) ~= "number" or effort < 0 or effort > 9 then + return nil, Err.new(Err.ARG, "encode: effort must be 0..9") + end + return Encode.encode(rgba, width, height, effort, o.exact == true, o.alphaHint, false), nil +end + +function Vp8L.encodeAlpha(a8: buffer, width: number, height: number, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(a8) ~= "buffer" or buffer.len(a8) < width * height then + return nil, Err.new(Err.ARG, "encodeAlpha: plane too small") + end + local rgba = buffer.create(width * height * 4) + for i = 0, width * height - 1 do + buffer.writeu32(rgba, i * 4, 0xff000000 + buffer.readu8(a8, i) * 256) + end + local effort = opts and opts.effort or 5 + return Encode.encode(rgba, width, height, effort, true, false, true), nil +end + +return Vp8L +end +__FILES["codecs/image/Vp8L/Decode"] = @native function() + + + +-- codecs/image/Vp8L/Decode: the WebP lossless (VP8L) bitstream decoder, 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. +-- Pixels are ARGB u32 values (0xAARRGGBB). +local band, bor, bxor, lshift, rshift = bit32.band, bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift +local readu8, readu32, writeu32, writeu8 = buffer.readu8, buffer.readu32, buffer.writeu32, buffer.writeu8 +local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len + +local Decode = {} + +local ROOT_BITS = 8 +local MAX_LEN = 15 +local NUM_LITERAL = 256 +local NUM_LENGTH = 24 +local NUM_DISTANCE = 40 +local MAX_CACHE_BITS = 11 +local ARGB_BLACK = 0xff000000 + +local CODE_LENGTH_ORDER = { 17, 18, 0, 1, 2, 3, 4, 5, 16, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 } +local CODE_TO_PLANE = { + 0x18, 0x07, 0x17, 0x19, 0x28, 0x06, 0x27, 0x29, 0x16, 0x1a, 0x26, 0x2a, 0x38, 0x05, 0x37, 0x39, 0x15, 0x1b, 0x36, + 0x3a, 0x25, 0x2b, 0x48, 0x04, 0x47, 0x49, 0x14, 0x1c, 0x35, 0x3b, 0x46, 0x4a, 0x24, 0x2c, 0x58, 0x45, 0x4b, 0x34, + 0x3c, 0x03, 0x57, 0x59, 0x13, 0x1d, 0x56, 0x5a, 0x23, 0x2d, 0x44, 0x4c, 0x55, 0x5b, 0x33, 0x3d, 0x68, 0x02, 0x67, + 0x69, 0x12, 0x1e, 0x66, 0x6a, 0x22, 0x2e, 0x54, 0x5c, 0x43, 0x4d, 0x65, 0x6b, 0x32, 0x3e, 0x78, 0x01, 0x77, 0x79, + 0x53, 0x5d, 0x11, 0x1f, 0x64, 0x6c, 0x42, 0x4e, 0x76, 0x7a, 0x21, 0x2f, 0x75, 0x7b, 0x31, 0x3f, 0x63, 0x6d, 0x52, + 0x5e, 0x00, 0x74, 0x7c, 0x41, 0x4f, 0x10, 0x20, 0x62, 0x6e, 0x30, 0x73, 0x7d, 0x51, 0x5f, 0x40, 0x72, 0x7e, 0x61, + 0x6f, 0x50, 0x71, 0x7f, 0x60, 0x70, +} +-- distance map (x offset 8 - (v & 15), y offset v >> 4) as a plain distance for a row width: done per image +Decode.CODE_TO_PLANE = CODE_TO_PLANE + +-- LSB-first; bytes past the end read as zero and count in `over`: the stream is overrun when bitcnt < over * 8 +type State = { + buf: buffer, + pos: number, + limit: number, + bitbuf: number, + bitcnt: number, + over: number, + -- prefix code tables (u32 entries value * 32 + bits), shared by every group of every level + tab: buffer, + tabUsed: number, + maxPixels: number, +} + +@native local function fill(d: State) + local bitbuf, bitcnt = d.bitbuf, d.bitcnt + while bitcnt <= 24 do + local p = d.pos + local b = 0 + if p < d.limit then + b = readu8(d.buf, p) + d.pos = p + 1 + else + d.over += 1 + end + bitbuf += lshift(b, bitcnt) + bitcnt += 8 + end + d.bitbuf, d.bitcnt = bitbuf, bitcnt +end + +@native local function readBits(d: State, n: number): number + if d.bitcnt < n then + fill(d) + end + local v = band(d.bitbuf, lshift(1, n) - 1) + d.bitbuf = rshift(d.bitbuf, n) + d.bitcnt -= n + return v +end + +@native local function eos(d: State): boolean + return d.bitcnt < d.over * 8 +end + +local count = table.create(MAX_LEN + 1, 0) +local offset = table.create(MAX_LEN + 2, 0) + +@native local function ensure(d: State, n: number) + local cap = blen(d.tab) // 4 + if d.tabUsed + n > cap then + local nb = bcreate(math.max(cap * 2, d.tabUsed + n) * 4) + bcopy(nb, 0, d.tab, 0, d.tabUsed * 4) + d.tab = nb + end +end + +@native local function replicate(tab: buffer, at: number, step: number, size: number, entry: number) + local e = size + repeat + e -= step + writeu32(tab, (at + e) * 4, entry) + until e <= 0 +end + +@native local function nextKey(key: number, len: number): number + local step = lshift(1, len - 1) + while band(key, step) ~= 0 do + step = rshift(step, 1) + end + return if step ~= 0 then band(key, step - 1) + step else key +end + +-- libwebp BuildHuffmanTable: complete codes only, except a single used symbol, which reads 0 bits; -1 when invalid +local sorted = table.create(2400, 0) +@native local function build(d: State, lens: { number }, n: number): number + for l = 0, MAX_LEN do + count[l + 1] = 0 + end + for s = 0, n - 1 do + local l = lens[s + 1] + if l > MAX_LEN then + return -1 + end + count[l + 1] += 1 + end + if count[1] == n then + return -1 + end + offset[2] = 0 + for len = 1, MAX_LEN - 1 do + if count[len + 1] > lshift(1, len) then + return -1 + end + offset[len + 2] = offset[len + 1] + count[len + 1] + end + for s = 0, n - 1 do + local l = lens[s + 1] + if l > 0 then + sorted[offset[l + 1] + 1] = s + offset[l + 1] += 1 + end + end + local long = 0 + for len = ROOT_BITS + 1, MAX_LEN do + long += count[len + 1] + end + ensure(d, lshift(1, ROOT_BITS) + long * lshift(1, MAX_LEN - ROOT_BITS)) + local tab = d.tab + local root = d.tabUsed + local totalSize = lshift(1, ROOT_BITS) + if offset[MAX_LEN + 1] == 1 then + replicate(tab, root, 1, totalSize, sorted[1] * 32) + d.tabUsed = root + totalSize + return root + end + local key = 0 + local numNodes, numOpen = 1, 1 + local tableBits = ROOT_BITS + local tableSize = lshift(1, tableBits) + local tableAt = root + local low = -1 + local mask = totalSize - 1 + local symbol = 1 + local step = 2 + for len = 1, ROOT_BITS do + numOpen *= 2 + numNodes += numOpen + numOpen -= count[len + 1] + if numOpen < 0 then + return -1 + end + while count[len + 1] > 0 do + replicate(tab, root + key, step, tableSize, sorted[symbol] * 32 + len) + symbol += 1 + key = nextKey(key, len) + count[len + 1] -= 1 + end + step *= 2 + end + step = 2 + for len = ROOT_BITS + 1, MAX_LEN do + numOpen *= 2 + numNodes += numOpen + numOpen -= count[len + 1] + if numOpen < 0 then + return -1 + end + while count[len + 1] > 0 do + if band(key, mask) ~= low then + tableAt += tableSize + -- NextTableBitSize + local l2 = len + local left = lshift(1, l2 - ROOT_BITS) + while l2 < MAX_LEN do + left -= count[l2 + 1] + if left <= 0 then + break + end + l2 += 1 + left *= 2 + end + tableBits = l2 - ROOT_BITS + tableSize = lshift(1, tableBits) + totalSize += tableSize + low = band(key, mask) + writeu32(tab, (root + low) * 4, (tableAt - root - low) * 32 + tableBits + ROOT_BITS) + end + replicate(tab, tableAt + rshift(key, ROOT_BITS), step, tableSize, sorted[symbol] * 32 + len - ROOT_BITS) + symbol += 1 + key = nextKey(key, len) + count[len + 1] -= 1 + end + step *= 2 + end + if numNodes ~= 2 * offset[MAX_LEN + 1] - 1 then + return -1 + end + d.tabUsed = root + totalSize + return root +end + +@native local function readSymbol(d: State, at: number): number + if d.bitcnt < MAX_LEN then + fill(d) + end + local tab = d.tab + local bitbuf = d.bitbuf + local idx = at + band(bitbuf, 255) + local e = readu32(tab, idx * 4) + local nb = band(e, 31) + if nb > ROOT_BITS then + bitbuf = rshift(bitbuf, ROOT_BITS) + d.bitcnt -= ROOT_BITS + e = readu32(tab, (idx + rshift(e, 5) + band(bitbuf, lshift(1, nb - ROOT_BITS) - 1)) * 4) + nb = band(e, 31) + end + d.bitbuf = rshift(bitbuf, nb) + d.bitcnt -= nb + return rshift(e, 5) +end + +local codeLengths = table.create(2400, 0) +local clLens = table.create(19, 0) + +@native local function readCode(d: State, size: number): number + for i = 1, size do + codeLengths[i] = 0 + end + if readBits(d, 1) == 1 then + local numSymbols = readBits(d, 1) + 1 + local first = readBits(d, 1) + local s = readBits(d, if first == 0 then 1 else 8) + if s < size then + codeLengths[s + 1] = 1 + end + if numSymbols == 2 then + s = readBits(d, 8) + if s < size then + codeLengths[s + 1] = 1 + end + end + else + for i = 1, 19 do + clLens[i] = 0 + end + local numCodes = readBits(d, 4) + 4 + for i = 1, numCodes do + clLens[CODE_LENGTH_ORDER[i] + 1] = readBits(d, 3) + end + local mark = d.tabUsed + local clt = build(d, clLens, 19) + if clt < 0 then + return -1 + end + local maxSymbol = size + if readBits(d, 1) == 1 then + local nbits = 2 + 2 * readBits(d, 3) + maxSymbol = 2 + readBits(d, nbits) + if maxSymbol > size then + return -1 + end + end + local prev = 8 + local s = 0 + while s < size do + if maxSymbol == 0 then + break + end + maxSymbol -= 1 + local cl = readSymbol(d, clt) + if cl < 16 then + codeLengths[s + 1] = cl + s += 1 + if cl ~= 0 then + prev = cl + end + else + local rep, len + if cl == 16 then + rep, len = readBits(d, 2) + 3, prev + elseif cl == 17 then + rep, len = readBits(d, 3) + 3, 0 + else + rep, len = readBits(d, 7) + 11, 0 + end + if s + rep > size then + return -1 + end + for k = s + 1, s + rep do + codeLengths[k] = len + end + s += rep + end + end + d.tabUsed = mark -- the code length table is temporary + end + if eos(d) then + return -1 + end + return build(d, codeLengths, size) +end + +@native local function subSample(size: number, bits: number): number + return rshift(size + lshift(1, bits) - 1, bits) +end +Decode.subSample = subSample + +@native local function cacheKey(argb: number, shift: number): number + -- (0x1e35a7bd * argb) mod 2^32 >> shift, exact in doubles + local lo = argb % 65536 + local hi = (argb - lo) / 65536 + local m = (lo * 0xa7bd + ((lo * 0x1e35 + hi * 0xa7bd) % 65536) * 65536) % 4294967296 + return rshift(m, shift) +end +Decode.cacheKey = cacheKey + +@native local function decodeData(d: State, data: buffer, w: number, h: number, cacheBits: number, groups: { number }, himg: buffer?, hbits: number, hxs: number): (boolean, string?) + local total = w * h + local cache: buffer? = if cacheBits > 0 then bcreate(lshift(1, cacheBits) * 4) else nil + local cshift = 32 - cacheBits + local lenLimit = NUM_LITERAL + NUM_LENGTH + local cacheLimit = lenLimit + (if cacheBits > 0 then lshift(1, cacheBits) else 0) + local hmask = if himg then lshift(1, hbits) - 1 else -1 + local i, col, row = 0, 0, 0 + local gG, gR, gB, gA, gD = groups[1], groups[2], groups[3], groups[4], groups[5] + @native local function setGroup() + if himg then + local g = readu32(himg, (hxs * rshift(row, hbits) + rshift(col, hbits)) * 4) * 5 + gG, gR, gB, gA, gD = groups[g + 1], groups[g + 2], groups[g + 3], groups[g + 4], groups[g + 5] + end + end + while i < total do + if band(col, hmask) == 0 then + setGroup() + end + local code = readSymbol(d, gG) + if code < NUM_LITERAL then + local r = readSymbol(d, gR) + local b = readSymbol(d, gB) + local a = readSymbol(d, gA) + if d.bitcnt < d.over * 8 then + break + end + local argb = a * 16777216 + r * 65536 + code * 256 + b + writeu32(data, i * 4, argb) + if cache then + writeu32(cache, cacheKey(argb, cshift) * 4, argb) + end + i += 1 + col += 1 + if col >= w then + col = 0 + row += 1 + end + elseif code < lenLimit then + local ls = code - NUM_LITERAL + local length + if ls < 4 then + length = ls + 1 + else + local eb = rshift(ls - 2, 1) + length = lshift(2 + band(ls, 1), eb) + readBits(d, eb) + 1 + end + local ds = readSymbol(d, gD) + local dc + if ds < 4 then + dc = ds + 1 + else + local eb = rshift(ds - 2, 1) + dc = lshift(2 + band(ds, 1), eb) + readBits(d, eb) + 1 + end + local dist + if dc > 120 then + dist = dc - 120 + else + local v = CODE_TO_PLANE[dc] + dist = rshift(v, 4) * w + 8 - band(v, 15) + if dist < 1 then + dist = 1 + end + end + if d.bitcnt < d.over * 8 then + break + end + if i < dist or total - i < length then + return false, "bad backward reference" + end + if dist >= length then + bcopy(data, i * 4, data, (i - dist) * 4, length * 4) + else + for k = i, i + length - 1 do + writeu32(data, k * 4, readu32(data, (k - dist) * 4)) + end + end + if cache then + for k = i, i + length - 1 do + local argb = readu32(data, k * 4) + writeu32(cache, cacheKey(argb, cshift) * 4, argb) + end + end + i += length + col += length + while col >= w do + col -= w + row += 1 + end + if band(col, hmask) ~= 0 then + setGroup() + end + elseif code < cacheLimit and cache then + if d.bitcnt < d.over * 8 then + break + end + local argb = readu32(cache, (code - lenLimit) * 4) + writeu32(data, i * 4, argb) + writeu32(cache, cacheKey(argb, cshift) * 4, argb) + i += 1 + col += 1 + if col >= w then + col = 0 + row += 1 + end + else + return false, "bad symbol" + end + end + if eos(d) then + return false, "truncated: pixel data" + end + return true, nil +end + +@native local function addPixels(a: number, b: number): number + return band(band(a, 0xff00ff00) + band(b, 0xff00ff00), 0xff00ff00) + band(band(a, 0x00ff00ff) + band(b, 0x00ff00ff), 0x00ff00ff) +end +Decode.addPixels = addPixels + +@native local function average2(a: number, b: number): number + return rshift(band(bxor(a, b), 0xfefefefe), 1) + band(a, b) +end +Decode.average2 = average2 + +@native local function clip255(v: number): number + return if v < 0 then 0 elseif v > 255 then 255 else v +end + +@native local function sub3(a: number, b: number, c: number): number + local pb, pa = b - c, a - c + return (if pb < 0 then -pb else pb) - (if pa < 0 then -pa else pa) +end + +-- select(T, L, TL) +@native local function select3(a: number, b: number, c: number): number + local s = sub3(rshift(a, 24), rshift(b, 24), rshift(c, 24)) + + sub3(band(rshift(a, 16), 255), band(rshift(b, 16), 255), band(rshift(c, 16), 255)) + + sub3(band(rshift(a, 8), 255), band(rshift(b, 8), 255), band(rshift(c, 8), 255)) + + sub3(band(a, 255), band(b, 255), band(c, 255)) + return if s <= 0 then a else b +end + +@native local function clampedFull(c0: number, c1: number, c2: number): number + local a = clip255(rshift(c0, 24) + rshift(c1, 24) - rshift(c2, 24)) + local r = clip255(band(rshift(c0, 16), 255) + band(rshift(c1, 16), 255) - band(rshift(c2, 16), 255)) + local g = clip255(band(rshift(c0, 8), 255) + band(rshift(c1, 8), 255) - band(rshift(c2, 8), 255)) + local b = clip255(band(c0, 255) + band(c1, 255) - band(c2, 255)) + return a * 16777216 + r * 65536 + g * 256 + b +end + +@native local function half(a: number, b: number): number + local dd = a - b + -- C division truncates toward zero + local q = if dd >= 0 then rshift(dd, 1) else -rshift(-dd, 1) + return clip255(a + q) +end + +@native local function clampedHalf(c0: number, c1: number, c2: number): number + local ave = average2(c0, c1) + local a = half(rshift(ave, 24), rshift(c2, 24)) + local r = half(band(rshift(ave, 16), 255), band(rshift(c2, 16), 255)) + local g = half(band(rshift(ave, 8), 255), band(rshift(c2, 8), 255)) + local b = half(band(ave, 255), band(c2, 255)) + return a * 16777216 + r * 65536 + g * 256 + b +end + +-- libwebp VP8LPredictors; modes 14 and 15 are black +@native local function predict(mode: number, L: number, T: number, TR: number, TL: number): number + if mode == 0 then + return ARGB_BLACK + elseif mode == 1 then + return L + elseif mode == 2 then + return T + elseif mode == 3 then + return TR + elseif mode == 4 then + return TL + elseif mode == 5 then + return average2(average2(L, TR), T) + elseif mode == 6 then + return average2(L, TL) + elseif mode == 7 then + return average2(L, T) + elseif mode == 8 then + return average2(TL, T) + elseif mode == 9 then + return average2(T, TR) + elseif mode == 10 then + return average2(average2(L, TL), average2(T, TR)) + elseif mode == 11 then + return select3(T, L, TL) + elseif mode == 12 then + return clampedFull(L, T, TL) + elseif mode == 13 then + return clampedHalf(L, T, TL) + end + return ARGB_BLACK +end +Decode.predict = predict + +@native local function inversePredictor(data: buffer, w: number, h: number, bits: number, sub: buffer) + local tw = subSample(w, bits) + -- first row: black, then L + writeu32(data, 0, addPixels(readu32(data, 0), ARGB_BLACK)) + for x = 1, w - 1 do + writeu32(data, x * 4, addPixels(readu32(data, x * 4), readu32(data, (x - 1) * 4))) + end + for y = 1, h - 1 do + local row = y * w + local up = row - w + writeu32(data, row * 4, addPixels(readu32(data, row * 4), readu32(data, up * 4))) + local trow = rshift(y, bits) * tw + local x = 1 + while x < w do + local mode = band(rshift(readu32(sub, (trow + rshift(x, bits)) * 4), 8), 15) + local xe = math.min(w, lshift(rshift(x, bits) + 1, bits)) + local L = readu32(data, (row + x - 1) * 4) + if mode == 1 then + for k = x, xe - 1 do + L = addPixels(readu32(data, (row + k) * 4), L) + writeu32(data, (row + k) * 4, L) + end + elseif mode == 2 then + for k = x, xe - 1 do + writeu32(data, (row + k) * 4, addPixels(readu32(data, (row + k) * 4), readu32(data, (up + k) * 4))) + end + else + for k = x, xe - 1 do + local p = predict(mode, L, readu32(data, (up + k) * 4), readu32(data, (up + k + 1) * 4), readu32(data, (up + k - 1) * 4)) + L = addPixels(readu32(data, (row + k) * 4), p) + writeu32(data, (row + k) * 4, L) + end + end + x = xe + end + end +end + +@native local function sint8(v: number): number + return if v >= 128 then v - 256 else v +end + +@native local function inverseCrossColor(data: buffer, w: number, h: number, bits: number, sub: buffer) + local tw = subSample(w, bits) + for y = 0, h - 1 do + local trow = rshift(y, bits) * tw + local x = 0 + while x < w do + local m = readu32(sub, (trow + rshift(x, bits)) * 4) + local g2r = sint8(band(m, 255)) + local g2b = sint8(band(rshift(m, 8), 255)) + local r2b = sint8(band(rshift(m, 16), 255)) + local xe = math.min(w, lshift(rshift(x, bits) + 1, bits)) + for k = y * w + x, y * w + xe - 1 do + local argb = readu32(data, k * 4) + local g = sint8(band(rshift(argb, 8), 255)) + local r = band(band(rshift(argb, 16), 255) + ((g2r * g) // 32), 255) + local b = band(band(argb, 255) + ((g2b * g) // 32) + ((r2b * sint8(r)) // 32), 255) + writeu32(data, k * 4, band(argb, 0xff00ff00) + r * 65536 + b) + end + x = xe + end + end +end + +@native local function inverseSubtractGreen(data: buffer, n: number) + for k = 0, n - 1 do + local argb = readu32(data, k * 4) + local g = band(rshift(argb, 8), 255) + writeu32(data, k * 4, band(argb, 0xff00ff00) + band(band(argb, 0x00ff00ff) + g * 65537, 0x00ff00ff)) + end +end + +@native local function inverseColorIndexing(src: buffer, sw: number, w: number, h: number, bits: number, map: buffer): buffer + local out = bcreate(w * h * 4) + if bits == 0 then + for k = 0, w * h - 1 do + writeu32(out, k * 4, readu32(map, band(rshift(readu32(src, k * 4), 8), 255) * 4)) + end + return out + end + local bpp = rshift(8, bits) + local cmask = lshift(1, bits) - 1 + local vmask = lshift(1, bpp) - 1 + for y = 0, h - 1 do + local packed = 0 + local s = y * sw + local o = y * w + for x = 0, w - 1 do + if band(x, cmask) == 0 then + packed = band(rshift(readu32(src, s * 4), 8), 255) + s += 1 + end + writeu32(out, (o + x) * 4, readu32(map, band(packed, vmask) * 4)) + packed = rshift(packed, bpp) + end + end + return out +end + +type Transform = { kind: number, xsize: number, bits: number, data: buffer? } + +local decodeStream: (d: State, xs: number, ys: number, level0: boolean) -> (buffer?, string?) + +@native local function readCodes(d: State, xs: number, ys: number, cacheBits: number, level0: boolean): ({ number }?, buffer?, number, number, string?) + local himg: buffer? = nil + local hbits, hxs = 0, 0 + local numGroups = 1 + local mapping: { number }? = nil + local numMax = 1 + if level0 and readBits(d, 1) == 1 then + hbits = readBits(d, 3) + 2 + hxs = subSample(xs, hbits) + local hys = subSample(ys, hbits) + local img, err = decodeStream(d, hxs, hys, false) + if not img then + return nil, nil, 0, 0, err + end + local n = hxs * hys + for k = 0, n - 1 do + local g = band(rshift(readu32(img, k * 4), 8), 0xffff) + writeu32(img, k * 4, g) + if g >= numMax then + numMax = g + 1 + end + 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 = table.create(numMax, -1) :: { number } + numGroups = 0 + for k = 0, n - 1 do + local g = readu32(img, k * 4) + if map[g + 1] == -1 then + map[g + 1] = numGroups + numGroups += 1 + end + writeu32(img, k * 4, map[g + 1]) + end + mapping = map + else + numGroups = numMax + end + himg = img + end + if eos(d) then + return nil, nil, 0, 0, "truncated: meta codes" + end + 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 + local mark = d.tabUsed + for j = 0, 4 do + local size = if j == 0 then NUM_LITERAL + NUM_LENGTH + cacheSize elseif j == 4 then NUM_DISTANCE else NUM_LITERAL + local at = readCode(d, size) + if at < 0 then + return nil, nil, 0, 0, if eos(d) then "truncated: prefix code" else "bad prefix code" + end + if slot >= 0 then + groups[slot * 5 + j + 1] = at + end + end + if slot < 0 then + d.tabUsed = mark + end + end + return groups, himg, hbits, hxs, nil +end + +decodeStream = @native function(d: State, xs: number, ys: number, level0: boolean): (buffer?, string?) + local transforms: { Transform } = {} + local seen = 0 + local txs = xs + if level0 then + while readBits(d, 1) == 1 do + local kind = readBits(d, 2) + if band(seen, lshift(1, kind)) ~= 0 then + return nil, "repeated transform" + end + seen = bor(seen, lshift(1, kind)) + local t: Transform = { kind = kind, xsize = txs, bits = 0, data = nil } + if kind == 0 or kind == 1 then + t.bits = readBits(d, 3) + 2 + local sub, err = decodeStream(d, subSample(txs, t.bits), subSample(ys, t.bits), false) + if not sub then + return nil, err + end + t.data = sub + elseif kind == 3 then + local num = readBits(d, 8) + 1 + local bits = if num > 16 then 0 elseif num > 4 then 1 elseif num > 2 then 2 else 3 + t.bits = bits + local pal, err = decodeStream(d, num, 1, false) + if not pal then + return nil, err + end + local final = lshift(1, rshift(8, bits)) + local map = bcreate(final * 4) + local prev = 0 + for k = 0, num - 1 do + prev = addPixels(readu32(pal, k * 4), prev) + writeu32(map, k * 4, prev) + end + t.data = map + txs = subSample(txs, bits) + end + table.insert(transforms, t) + if eos(d) then + return nil, "truncated: transforms" + end + end + end + local cacheBits = 0 + if readBits(d, 1) == 1 then + cacheBits = readBits(d, 4) + if cacheBits < 1 or cacheBits > MAX_CACHE_BITS then + return nil, "bad colour cache size" + end + end + local mark = d.tabUsed + local groups, himg, hbits, hxs, err = readCodes(d, txs, ys, cacheBits, level0) + if not groups then + return nil, err + end + local data = bcreate(txs * ys * 4) + local ok, derr = decodeData(d, data, txs, ys, cacheBits, groups, himg, hbits, hxs) + if not ok then + return nil, derr + end + d.tabUsed = mark + -- inverse transforms, last read first + for k = #transforms, 1, -1 do + local t = transforms[k] + if t.kind == 0 then + inversePredictor(data, t.xsize, ys, t.bits, t.data :: buffer) + elseif t.kind == 1 then + inverseCrossColor(data, t.xsize, ys, t.bits, t.data :: buffer) + elseif t.kind == 2 then + inverseSubtractGreen(data, t.xsize * ys) + else + data = inverseColorIndexing(data, subSample(t.xsize, t.bits), t.xsize, ys, t.bits, t.data :: buffer) + end + end + return data, nil +end + +@native local function newState(buf: buffer, off: number, len: number, maxPixels: number): State + return { + buf = buf, + pos = off, + limit = off + len, + bitbuf = 0, + bitcnt = 0, + over = 0, + tab = bcreate(4096 * 4), + tabUsed = 0, + maxPixels = maxPixels, + } +end + +@native function Decode.header(buf: buffer, off: number, len: number): (number?, number, boolean, string?) + if len < 5 then + return nil, 0, false, "truncated: header" + end + if readu8(buf, off) ~= 0x2f then + return nil, 0, false, "bad VP8L signature" + end + local v = readu32(buf, off + 1) + local w = band(v, 0x3fff) + 1 + local h = band(rshift(v, 14), 0x3fff) + 1 + local alpha = band(rshift(v, 28), 1) == 1 + if rshift(v, 29) ~= 0 then + return nil, 0, false, "bad VP8L version" + end + return w, h, alpha, nil +end + +@native function Decode.argb(buf: buffer, off: number, len: number, maxPixels: number): (buffer?, number, number, boolean, string?) + local w, h, alpha, err = Decode.header(buf, off, len) + if not w then + return nil, 0, 0, false, err + end + if w * h > maxPixels then + return nil, w, h, alpha, "limit: " .. w .. " x " .. h .. " is over maxPixels" + end + local d = newState(buf, off + 5, len - 5, maxPixels) + local data, derr = decodeStream(d, w, h, true) + if not data then + return nil, w, h, alpha, derr + end + return data, w, h, alpha, nil +end + +@native function Decode.stream(buf: buffer, off: number, len: number, w: number, h: number): (buffer?, string?) + local d = newState(buf, off, len, w * h) + return decodeStream(d, w, h, true) +end + +@native function Decode.toRgba(argb: buffer, n: number, out: buffer?, outOff: number?): buffer + local o = out or bcreate(n * 4) + local base = outOff or 0 + for k = 0, n - 1 do + local v = readu32(argb, k * 4) + -- 0xAARRGGBB (bytes B G R A) -> bytes R G B A + writeu32(o, base + k * 4, band(v, 0xff00ff00) + band(rshift(v, 16), 255) + band(v, 255) * 65536) + end + return o +end + +@native function Decode.green(argb: buffer, n: number): buffer + local o = bcreate(n) + for k = 0, n - 1 do + writeu8(o, k, band(rshift(readu32(argb, k * 4), 8), 255)) + end + return o +end + +return Decode +end +__FILES["codecs/image/Vp8L/Encode"] = @native function() + + + +-- codecs/image/Vp8L/Encode: a WebP lossless (VP8L) encoder, new code written from RFC 9649 section 3. +local Huffman = __include("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 +local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len +local log = math.log + +local Encode = {} + +local NUM_LITERAL = 256 +local NUM_LENGTH = 24 +local NUM_DISTANCE = 40 +local MAX_LENGTH = 4096 +local WINDOW = 1048576 - 120 +local ARGB_BLACK = 0xff000000 + +local CODE_LENGTH_ORDER = { 17, 18, 0, 1, 2, 3, 4, 5, 16, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 } +local CODE_TO_PLANE = { + 0x18, 0x07, 0x17, 0x19, 0x28, 0x06, 0x27, 0x29, 0x16, 0x1a, 0x26, 0x2a, 0x38, 0x05, 0x37, 0x39, 0x15, 0x1b, 0x36, + 0x3a, 0x25, 0x2b, 0x48, 0x04, 0x47, 0x49, 0x14, 0x1c, 0x35, 0x3b, 0x46, 0x4a, 0x24, 0x2c, 0x58, 0x45, 0x4b, 0x34, + 0x3c, 0x03, 0x57, 0x59, 0x13, 0x1d, 0x56, 0x5a, 0x23, 0x2d, 0x44, 0x4c, 0x55, 0x5b, 0x33, 0x3d, 0x68, 0x02, 0x67, + 0x69, 0x12, 0x1e, 0x66, 0x6a, 0x22, 0x2e, 0x54, 0x5c, 0x43, 0x4d, 0x65, 0x6b, 0x32, 0x3e, 0x78, 0x01, 0x77, 0x79, + 0x53, 0x5d, 0x11, 0x1f, 0x64, 0x6c, 0x42, 0x4e, 0x76, 0x7a, 0x21, 0x2f, 0x75, 0x7b, 0x31, 0x3f, 0x63, 0x6d, 0x52, + 0x5e, 0x00, 0x74, 0x7c, 0x41, 0x4f, 0x10, 0x20, 0x62, 0x6e, 0x30, 0x73, 0x7d, 0x51, 0x5f, 0x40, 0x72, 0x7e, 0x61, + 0x6f, 0x50, 0x71, 0x7f, 0x60, 0x70, +} +-- PLANE_TO_CODE[v + 1] = the distance code (1..120) of the plane offset v = yoffset * 16 + 8 - xoffset +local PLANE_TO_CODE = table.create(128, 0) +for i, v in CODE_TO_PLANE do + PLANE_TO_CODE[v + 1] = i +end + +type W = { buf: buffer, pos: number, acc: number, cnt: number } + +@native local function newWriter(cap: number): W + return { buf = bcreate(math.max(64, cap)), pos = 0, acc = 0, cnt = 0 } +end + +-- the n <= 24 low bits of v, LSB first +@native local function put(w: W, v: number, n: number) + local acc = w.acc + v * 2 ^ w.cnt + local cnt = w.cnt + n + if cnt >= 8 then + local pos = w.pos + local buf = w.buf + if pos + 8 > blen(buf) then + local nb = bcreate(blen(buf) * 2) + bcopy(nb, 0, buf, 0, pos) + buf = nb + w.buf = nb + end + repeat + local byte = acc % 256 + writeu8(buf, pos, byte) + pos += 1 + acc = (acc - byte) / 256 + cnt -= 8 + until cnt < 8 + w.pos = pos + end + w.acc, w.cnt = acc, cnt +end + +@native local function finish(w: W): buffer + if w.cnt > 0 then + put(w, 0, 8 - w.cnt) + end + local out = bcreate(w.pos) + bcopy(out, 0, w.buf, 0, w.pos) + return out +end + +@native local function subSample(size: number, bits: number): number + return rshift(size + lshift(1, bits) - 1, bits) +end + +-- (0x1e35a7bd * v) mod 2^32: the colour cache hash before its shift +@native local function mulHash(v: number): number + local lo = v % 65536 + local hi = (v - lo) / 65536 + return (lo * 0xa7bd + ((lo * 0x1e35 + hi * 0xa7bd) % 65536) * 65536) % 4294967296 +end + +@native local function prefix(v: number): (number, number, number) + local d = v - 1 + if d < 4 then + return d, 0, 0 + end + local hb = 0 + local t = d + while t >= 2 do + t = rshift(t, 1) + hb += 1 + end + local second = band(rshift(d, hb - 1), 1) + local eb = hb - 1 + return 2 * hb + second, eb, band(d, lshift(1, eb) - 1) +end + +-- distance code value: 1..120 for the 2-D plane offsets, else dist + 120 +@native local function distCode(xs: number, dist: number): number + local yo = dist // xs + local xo = dist - yo * xs + if xo <= 8 and yo < 8 then + return PLANE_TO_CODE[yo * 16 + 8 - xo + 1] + elseif xo > xs - 8 and yo < 7 then + return PLANE_TO_CODE[(yo + 1) * 16 + 8 + (xs - xo) + 1] + end + return dist + 120 +end + +@native local function subPixels(a: number, b: number): number + return band(bor(a, 0x00ff00ff) - band(b, 0xff00ff00), 0xff00ff00) + band(bor(a, 0xff00ff00) - band(b, 0x00ff00ff), 0x00ff00ff) +end + +@native local function average2(a: number, b: number): number + return rshift(band(bxor(a, b), 0xfefefefe), 1) + band(a, b) +end + +@native local function clip255(v: number): number + return if v < 0 then 0 elseif v > 255 then 255 else v +end + +@native local function sub3(a: number, b: number, c: number): number + local pb, pa = b - c, a - c + return (if pb < 0 then -pb else pb) - (if pa < 0 then -pa else pa) +end + +@native local function half(x: number, y: number): number + local dd = x - y + return clip255(x + (if dd >= 0 then rshift(dd, 1) else -rshift(-dd, 1))) +end + +@native local function predict(mode: number, L: number, T: number, TR: number, TL: number): number + if mode == 1 then + return L + elseif mode == 2 then + return T + elseif mode == 3 then + return TR + elseif mode == 4 then + return TL + elseif mode == 5 then + return average2(average2(L, TR), T) + elseif mode == 6 then + return average2(L, TL) + elseif mode == 7 then + return average2(L, T) + elseif mode == 8 then + return average2(TL, T) + elseif mode == 9 then + return average2(T, TR) + elseif mode == 10 then + return average2(average2(L, TL), average2(T, TR)) + elseif mode == 11 then + local s = sub3(rshift(T, 24), rshift(L, 24), rshift(TL, 24)) + + sub3(band(rshift(T, 16), 255), band(rshift(L, 16), 255), band(rshift(TL, 16), 255)) + + sub3(band(rshift(T, 8), 255), band(rshift(L, 8), 255), band(rshift(TL, 8), 255)) + + sub3(band(T, 255), band(L, 255), band(TL, 255)) + return if s <= 0 then T else L + elseif mode == 12 then + local a = clip255(rshift(L, 24) + rshift(T, 24) - rshift(TL, 24)) + local r = clip255(band(rshift(L, 16), 255) + band(rshift(T, 16), 255) - band(rshift(TL, 16), 255)) + local g = clip255(band(rshift(L, 8), 255) + band(rshift(T, 8), 255) - band(rshift(TL, 8), 255)) + local b = clip255(band(L, 255) + band(T, 255) - band(TL, 255)) + return a * 16777216 + r * 65536 + g * 256 + b + elseif mode == 13 then + local ave = average2(L, T) + local a = half(rshift(ave, 24), rshift(TL, 24)) + local r = half(band(rshift(ave, 16), 255), band(rshift(TL, 16), 255)) + local g = half(band(rshift(ave, 8), 255), band(rshift(TL, 8), 255)) + local b = half(band(ave, 255), band(TL, 255)) + return a * 16777216 + r * 65536 + g * 256 + b + end + return ARGB_BLACK +end + +local COST = table.create(256, 0) +for v = 0, 255 do + local m = math.min(v, 256 - v) + COST[v + 1] = log(1 + m) / log(2) +end + +@native local function residualCost(r: number): number + return COST[band(r, 255) + 1] + COST[band(rshift(r, 8), 255) + 1] + COST[band(rshift(r, 16), 255) + 1] + COST[rshift(r, 24) + 1] +end + +local MODES_FAST = { 1, 2, 11 } +local MODES_MID = { 0, 1, 2, 4, 5, 7, 10, 11, 12, 13 } +local MODES_ALL = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 } + +@native local function predictorTransform(px: buffer, w: number, h: number, bits: number, effort: number): buffer + local tw, th = subSample(w, bits), subSample(h, bits) + local modesImg = bcreate(tw * th * 4) + local modes = if effort <= 2 then MODES_FAST elseif effort <= 6 then MODES_MID else MODES_ALL + local ts = lshift(1, bits) + for ty = 0, th - 1 do + for tx = 0, tw - 1 do + local x0, y0 = tx * ts, ty * ts + local x1, y1 = math.min(w, x0 + ts), math.min(h, y0 + ts) + local best, bestCost = 1, math.huge + for _, m in modes do + local cost = 0 + for y = math.max(y0, 1), y1 - 1 do + local row = y * w + for x = math.max(x0, 1), x1 - 1 do + local i = row + x + local up = i - w + local p = predict(m, readu32(px, (i - 1) * 4), readu32(px, up * 4), readu32(px, (up + 1) * 4), readu32(px, (up - 1) * 4)) + cost += residualCost(subPixels(readu32(px, i * 4), p)) + end + if cost >= bestCost then + break + end + end + if cost < bestCost then + best, bestCost = m, cost + end + end + writeu32(modesImg, (ty * tw + tx) * 4, ARGB_BLACK + best * 256) + end + end + -- residuals with the chosen modes (and the decoder's fixed first row and column) + local res = bcreate(w * h * 4) + writeu32(res, 0, subPixels(readu32(px, 0), ARGB_BLACK)) + for x = 1, w - 1 do + writeu32(res, x * 4, subPixels(readu32(px, x * 4), readu32(px, (x - 1) * 4))) + end + for y = 1, h - 1 do + local row = y * w + writeu32(res, row * 4, subPixels(readu32(px, row * 4), readu32(px, (row - w) * 4))) + local trow = rshift(y, bits) * tw + for x = 1, w - 1 do + local m = band(rshift(readu32(modesImg, (trow + rshift(x, bits)) * 4), 8), 15) + local i = row + x + local up = i - w + local p = predict(m, readu32(px, (i - 1) * 4), readu32(px, up * 4), readu32(px, (up + 1) * 4), readu32(px, (up - 1) * 4)) + writeu32(res, i * 4, subPixels(readu32(px, i * 4), p)) + end + end + bcopy(px, 0, res, 0, w * h * 4) + return modesImg +end + +@native local function sint8(v: number): number + return if v >= 128 then v - 256 else v +end + +@native local function clampM(v: number): number + local m = math.floor(v + 0.5) + return if m < -128 then -128 elseif m > 127 then 127 else m +end + +-- cross colour per tile: least-squares r ~ g2r * g / 32, b ~ g2b * g / 32 + r2b * r / 32, kept when they lower the cost +@native local function crossColorTransform(px: buffer, w: number, h: number, bits: number): buffer + local tw, th = subSample(w, bits), subSample(h, bits) + local img = bcreate(tw * th * 4) + local ts = lshift(1, bits) + @native local function tileCost(x0: number, y0: number, x1: number, y1: number, g2r: number, g2b: number, r2b: number): number + local c = 0 + for y = y0, y1 - 1 do + for x = x0, x1 - 1 do + local argb = readu32(px, (y * w + x) * 4) + local g = sint8(band(rshift(argb, 8), 255)) + local r = band(rshift(argb, 16), 255) + local b = band(argb, 255) + local nr = band(r - ((g2r * g) // 32), 255) + local nb = band(b - ((g2b * g) // 32) - ((r2b * sint8(r)) // 32), 255) + c += COST[nr + 1] + COST[nb + 1] + end + end + return c + end + for ty = 0, th - 1 do + for tx = 0, tw - 1 do + local x0, y0 = tx * ts, ty * ts + local x1, y1 = math.min(w, x0 + ts), math.min(h, y0 + ts) + local sgg, sgr, sgb, srr, srb = 0, 0, 0, 0, 0 + for y = y0, y1 - 1 do + for x = x0, x1 - 1 do + local argb = readu32(px, (y * w + x) * 4) + local g = sint8(band(rshift(argb, 8), 255)) + local r = sint8(band(rshift(argb, 16), 255)) + local b = sint8(band(argb, 255)) + sgg += g * g + sgr += g * r + sgb += g * b + srr += r * r + srb += r * b + end + end + local g2r, g2b, r2b = 0, 0, 0 + if sgg > 0 then + g2r = clampM(32 * sgr / sgg) + local det = sgg * srr - sgr * sgr + if det > 0 then + g2b = clampM(32 * (sgb * srr - srb * sgr) / det) + r2b = clampM(32 * (srb * sgg - sgb * sgr) / det) + else + g2b = clampM(32 * sgb / sgg) + end + end + if g2r ~= 0 or g2b ~= 0 or r2b ~= 0 then + if tileCost(x0, y0, x1, y1, g2r, g2b, r2b) >= tileCost(x0, y0, x1, y1, 0, 0, 0) then + g2r, g2b, r2b = 0, 0, 0 + end + end + writeu32(img, (ty * tw + tx) * 4, ARGB_BLACK + band(r2b, 255) * 65536 + band(g2b, 255) * 256 + band(g2r, 255)) + if g2r ~= 0 or g2b ~= 0 or r2b ~= 0 then + for y = y0, y1 - 1 do + for x = x0, x1 - 1 do + local k = (y * w + x) * 4 + local argb = readu32(px, k) + local g = sint8(band(rshift(argb, 8), 255)) + local r = band(rshift(argb, 16), 255) + local b = band(argb, 255) + local nr = band(r - ((g2r * g) // 32), 255) + local nb = band(b - ((g2b * g) // 32) - ((r2b * sint8(r)) // 32), 255) + writeu32(px, k, band(argb, 0xff00ff00) + nr * 65536 + nb) + end + end + end + end + end + return img +end + +-- tokens: L[i] >= 0 is a literal ARGB pixel; L[i] < 0 is a copy of -L[i] pixels with the distance code value D[i] +local HASH_BITS = 16 + +@native local function hash2(a: number, b: number): number + return rshift(mulHash(bxor(a, (b * 31) % 4294967296)), 32 - HASH_BITS) +end + +@native local function matchLen(px: buffer, i: number, j: number, max: number): number + local n = 0 + while n < max and readu32(px, (i + n) * 4) == readu32(px, (j + n) * 4) do + n += 1 + end + return n +end + +@native local function lz77(px: buffer, xs: number, n: number, effort: number): ({ number }, { number }) + local L: { number } = {} + local D: { number } = {} + if effort == 0 then + for i = 0, n - 1 do + L[i + 1] = readu32(px, i * 4) + D[i + 1] = 0 + end + return L, D + end + local head = table.create(lshift(1, HASH_BITS), -1) + local prev = table.create(n, -1) + local maxIter = if effort <= 2 then 4 elseif effort <= 5 then 16 elseif effort <= 7 then 48 else 128 + @native local function insert(i: number) + if i + 1 < n then + local h = hash2(readu32(px, i * 4), readu32(px, (i + 1) * 4)) + 1 + prev[i + 1] = head[h] + head[h] = i + end + end + @native local function best(i: number): (number, number) + local max = math.min(MAX_LENGTH, n - i) + if max < 2 then + return 0, 0 + end + local bl, bd, bc = 0, 0, math.huge + @native local function try(j: number) + local d = i - j + if d < 1 or d > WINDOW then + return + end + local l = matchLen(px, i, j, max) + if l >= 2 then + local c = distCode(xs, d) + if l > bl or (l == bl and c < bc) then + bl, bd, bc = l, d, c + end + end + end + if i >= 1 then + try(i - 1) + end + if i >= xs then + try(i - xs) + end + if bl < max then + local h = hash2(readu32(px, i * 4), readu32(px, (i + 1) * 4)) + 1 + local j = head[h] + local it = 0 + while j >= 0 and it < maxIter and i - j <= WINDOW do + if j ~= i - 1 and j ~= i - xs then + try(j) + if bl >= max then + break + end + end + j = prev[j + 1] + it += 1 + end + end + -- a 2-pixel copy only pays with a short 2-D distance code + if bl == 2 and bc > 120 then + return 0, 0 + end + return bl, bd + end + local i = 0 + local k = 0 + local lazy = effort >= 4 + local nl, nd = 0, 0 + local haveNext = false + while i < n do + local l, d + if haveNext then + l, d = nl, nd + haveNext = false + else + l, d = best(i) + end + if l >= 2 and lazy and l < 64 and i + 1 < n then + insert(i) + nl, nd = best(i + 1) + if nl > l + 1 then + -- a literal now, the longer match next + k += 1 + L[k] = readu32(px, i * 4) + D[k] = 0 + i += 1 + haveNext = true + else + k += 1 + L[k] = -l + D[k] = distCode(xs, d) + for t = i + 1, i + l - 1 do + insert(t) + end + i += l + end + elseif l >= 2 then + k += 1 + L[k] = -l + D[k] = distCode(xs, d) + local stop = i + l + if effort <= 2 and l > 16 then + insert(i) + insert(stop - 1) + else + for t = i, stop - 1 do + insert(t) + end + end + i = stop + else + insert(i) + k += 1 + L[k] = readu32(px, i * 4) + D[k] = 0 + i += 1 + end + end + return L, D +end + +@native local function entropy(h: { number }): number + local total = 0 + for _, c in h do + total += c + end + if total == 0 then + return 0 + end + local bits = 0 + local lt = log(total) + for _, c in h do + if c > 0 then + bits += c * (lt - log(c)) + end + end + return bits / log(2) +end + +@native local function chooseCache(px: buffer, L: { number }, effort: number): number + if effort < 2 then + return 0 + end + local cands = if effort < 5 then { 0, 4, 7, 10 } else { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 } + local caches: { { number } } = {} + local hg: { { number } } = {} + local hr: { { number } } = {} + local hb: { { number } } = {} + local ha: { { number } } = {} + for c, bits in cands do + caches[c] = table.create(lshift(1, bits), -1) + hg[c] = table.create(256 + lshift(1, bits), 0) + hr[c] = table.create(256, 0) + hb[c] = table.create(256, 0) + ha[c] = table.create(256, 0) + end + local pos = 0 + for _, t in L do + if t >= 0 then + local hsh = mulHash(t) + for c, bits in cands do + local cache = caches[c] + local key = if bits > 0 then rshift(hsh, 32 - bits) else 0 + if bits > 0 and cache[key + 1] == t then + hg[c][257 + key] += 1 + else + hg[c][band(rshift(t, 8), 255) + 1] += 1 + hr[c][band(rshift(t, 16), 255) + 1] += 1 + hb[c][band(t, 255) + 1] += 1 + ha[c][rshift(t, 24) + 1] += 1 + end + if bits > 0 then + cache[key + 1] = t + end + end + pos += 1 + else + for p = pos, pos - t - 1 do + local v = readu32(px, p * 4) + local hsh = mulHash(v) + for c, bits in cands do + if bits > 0 then + caches[c][rshift(hsh, 32 - bits) + 1] = v + end + end + end + pos -= t + end + end + local bestBits, bestCost = 0, math.huge + for c, bits in cands do + -- + a rough price for the longer green code lengths + local cost = entropy(hg[c]) + entropy(hr[c]) + entropy(hb[c]) + entropy(ha[c]) + lshift(1, bits) * 0.5 + if cost < bestCost then + bestBits, bestCost = bits, cost + end + end + return bestBits +end + +type Code = { lens: { number }, codes: { number }, single: boolean } + +@native local function buildCode(freqs: { number }, maxLen: number): Code + local lens = Huffman.lengths(freqs, maxLen) + local used = 0 + for _, l in lens do + if l > 0 then + used += 1 + end + end + local codes = Huffman.codes(lens) + for i, l in lens do + if l > 0 then + codes[i] = Huffman.reverse(codes[i], l) + end + end + return { lens = lens, codes = codes, single = used <= 1 } +end + +@native local function emit(w: W, c: Code, sym: number) + if not c.single then + put(w, c.codes[sym + 1], c.lens[sym + 1]) + end +end + +@native local function zeroRun(tok: { number }, ext: { number }, run: number) + local r = run + while r > 0 do + if r >= 11 then + local k = math.min(r, 138) + table.insert(tok, 18) + table.insert(ext, k - 11) + r -= k + elseif r >= 3 then + table.insert(tok, 17) + table.insert(ext, r - 3) + r = 0 + else + table.insert(tok, 0) + table.insert(ext, 0) + r -= 1 + end + end +end + +@native local function writeCode(w: W, c: Code, size: number) + local syms: { number } = {} + for s = 0, size - 1 do + if (c.lens[s + 1] or 0) > 0 then + table.insert(syms, s) + if #syms > 2 then + break + end + end + end + if #syms == 0 then + -- an unused alphabet: the simple code of symbol 0 + put(w, 1, 1) + put(w, 0, 1) + put(w, 0, 1) + put(w, 0, 1) + return + end + if #syms <= 2 and syms[#syms] < 256 then + put(w, 1, 1) + put(w, #syms - 1, 1) + if syms[1] <= 1 then + put(w, 0, 1) + put(w, syms[1], 1) + else + put(w, 1, 1) + put(w, syms[1], 8) + end + if #syms == 2 then + put(w, syms[2], 8) + end + return + end + -- run-length tokens of every length: 0..15 literal, 16 repeats the previous non-zero length (3..6 times; the + -- decoder's "previous" starts at 8), 17 zeros (3..10), 18 zeros (11..138) + local tok: { number } = {} + local ext: { number } = {} + local keep = 0 + local prev = 8 + local s = 1 + while s <= size do + local l = c.lens[s] or 0 + local run = 1 + while s + run <= size and (c.lens[s + run] or 0) == l do + run += 1 + end + if l == 0 then + zeroRun(tok, ext, run) + else + local r = run + if l ~= prev then + table.insert(tok, l) + table.insert(ext, 0) + r -= 1 + prev = l + end + while r > 0 do + if r >= 3 then + local k = math.min(r, 6) + table.insert(tok, 16) + table.insert(ext, k - 3) + r -= k + else + table.insert(tok, l) + table.insert(ext, 0) + r -= 1 + end + end + keep = #tok + end + s += run + end + local ntok = #tok + local trim = keep < ntok and keep >= 2 + if trim then + ntok = keep + end + local hist = table.create(19, 0) + for i = 1, ntok do + hist[tok[i] + 1] += 1 + end + local cl = buildCode(hist, 7) + local nc = 19 + while nc > 4 and (cl.lens[CODE_LENGTH_ORDER[nc] + 1] or 0) == 0 do + nc -= 1 + end + put(w, 0, 1) + put(w, nc - 4, 4) + for i = 1, nc do + put(w, cl.lens[CODE_LENGTH_ORDER[i] + 1] or 0, 3) + end + if trim then + put(w, 1, 1) + local v = ntok - 2 + local nbits = 0 + while lshift(1, nbits) <= v do + nbits += 1 + end + local pairs = math.max(1, (nbits + 1) // 2) + put(w, pairs - 1, 3) + put(w, v, pairs * 2) + else + put(w, 0, 1) + end + for i = 1, ntok do + local t = tok[i] + emit(w, cl, t) + if t == 16 then + put(w, ext[i], 2) + elseif t == 17 then + put(w, ext[i], 3) + elseif t == 18 then + put(w, ext[i], 7) + end + end +end + +-- colour cache bits, [the meta-code bit], the five codes, the pixels +@native local function writeImage(w: W, px: buffer, xs: number, n: number, effort: number, level0: boolean) + local L, D = lz77(px, xs, n, effort) + local cacheBits = if level0 then chooseCache(px, L, effort) else 0 + if cacheBits > 0 then + put(w, 1, 1) + put(w, cacheBits, 4) + else + put(w, 0, 1) + end + if level0 then + put(w, 0, 1) -- no meta prefix codes + end + local cacheSize = if cacheBits > 0 then lshift(1, cacheBits) else 0 + local cshift = 32 - cacheBits + local hg = table.create(NUM_LITERAL + NUM_LENGTH + cacheSize, 0) + local hr = table.create(256, 0) + local hb = table.create(256, 0) + local ha = table.create(256, 0) + local hd = table.create(NUM_DISTANCE, 0) + -- token kinds after the cache: 0 literal, 1 cache hit, 2 copy + local cache: { number }? = if cacheBits > 0 then table.create(cacheSize, -1) else nil + local K = table.create(#L, 0) + local pos = 0 + for i, t in L do + if t >= 0 then + local hit = false + if cache then + local key = rshift(mulHash(t), cshift) + if cache[key + 1] == t then + hit = true + hg[NUM_LITERAL + NUM_LENGTH + key + 1] += 1 + end + cache[key + 1] = t + end + if hit then + K[i] = 1 + else + hg[band(rshift(t, 8), 255) + 1] += 1 + hr[band(rshift(t, 16), 255) + 1] += 1 + hb[band(t, 255) + 1] += 1 + ha[rshift(t, 24) + 1] += 1 + end + pos += 1 + else + K[i] = 2 + hg[NUM_LITERAL + prefix(-t) + 1] += 1 + hd[prefix(D[i]) + 1] += 1 + if cache then + for p = pos, pos - t - 1 do + local v = readu32(px, p * 4) + cache[rshift(mulHash(v), cshift) + 1] = v + end + end + pos -= t + end + end + local cg, cr, cb, ca, cd = buildCode(hg, 15), buildCode(hr, 15), buildCode(hb, 15), buildCode(ha, 15), buildCode(hd, 15) + writeCode(w, cg, NUM_LITERAL + NUM_LENGTH + cacheSize) + writeCode(w, cr, 256) + writeCode(w, cb, 256) + writeCode(w, ca, 256) + writeCode(w, cd, NUM_DISTANCE) + for i, t in L do + local k = K[i] + if k == 0 then + emit(w, cg, band(rshift(t, 8), 255)) + emit(w, cr, band(rshift(t, 16), 255)) + emit(w, cb, band(t, 255)) + emit(w, ca, rshift(t, 24)) + elseif k == 1 then + emit(w, cg, NUM_LITERAL + NUM_LENGTH + rshift(mulHash(t), cshift)) + else + local lc, leb, lev = prefix(-t) + emit(w, cg, NUM_LITERAL + lc) + if leb > 0 then + put(w, lev, leb) + end + local dc, deb, dev = prefix(D[i]) + emit(w, cd, dc) + if deb > 0 then + put(w, dev, deb) + end + end + end +end + +@native local function toArgb(rgba: buffer, n: number, exact: boolean): (buffer, boolean) + local px = bcreate(n * 4) + local alpha = false + for i = 0, n - 1 do + local v = readu32(rgba, i * 4) + local a = rshift(v, 24) + if a ~= 255 then + alpha = true + end + if a == 0 and not exact then + v = 0 + end + -- bytes R G B A (0xAABBGGRR) -> 0xAARRGGBB + writeu32(px, i * 4, band(v, 0xff00ff00) + band(rshift(v, 16), 255) + band(v, 255) * 65536) + end + return px, alpha +end + +@native local function palette(px: buffer, n: number): { number }? + local seen: { [number]: boolean } = {} + local list: { number } = {} + for i = 0, n - 1 do + local v = readu32(px, i * 4) + if not seen[v] then + if #list == 256 then + return nil + end + seen[v] = true + table.insert(list, v) + end + end + table.sort(list) + return list +end + +type Config = { palette: { number }?, pbits: number, cc: boolean, ccbits: number } + +@native local function stream(px: buffer, w: number, h: number, effort: number, cfg: Config, bw: W) + local n = w * h + local xs = w + local sub = math.min(effort, 3) + local pal = cfg.palette + if pal then + local num = #pal + local bits = if num > 16 then 0 elseif num > 4 then 1 elseif num > 2 then 2 else 3 + put(bw, 1, 1) + put(bw, 3, 2) + put(bw, num - 1, 8) + local pimg = bcreate(num * 4) + local prevc = 0 + local index: { [number]: number } = {} + for i, c in pal do + writeu32(pimg, (i - 1) * 4, subPixels(c, prevc)) + prevc = c + index[c] = i - 1 + end + writeImage(bw, pimg, num, num, sub, false) + xs = subSample(w, bits) + local packed = bcreate(xs * h * 4) + local bpp = rshift(8, bits) + local cmask = lshift(1, bits) - 1 + for y = 0, h - 1 do + local acc = 0 + local o = y * xs + for x = 0, w - 1 do + local sh = band(x, cmask) + acc += index[readu32(px, (y * w + x) * 4)] * 2 ^ (bpp * sh) + if sh == cmask or x == w - 1 then + writeu32(packed, (o + rshift(x, bits)) * 4, ARGB_BLACK + acc * 256) + acc = 0 + end + end + end + px = packed + elseif cfg.pbits > 0 then + -- subtract green + put(bw, 1, 1) + put(bw, 2, 2) + for i = 0, n - 1 do + local v = readu32(px, i * 4) + local g = band(rshift(v, 8), 255) + writeu32(px, i * 4, band(v, 0xff00ff00) + band(band(v, 0x00ff00ff) + 0x01000100 - g * 65537, 0x00ff00ff)) + end + -- predictor + local pbits = cfg.pbits + local modes = predictorTransform(px, w, h, pbits, effort) + put(bw, 1, 1) + put(bw, 0, 2) + put(bw, pbits - 2, 3) + writeImage(bw, modes, subSample(w, pbits), subSample(w, pbits) * subSample(h, pbits), sub, false) + -- cross colour + if cfg.cc then + local cbits = cfg.ccbits + local cimg = crossColorTransform(px, w, h, cbits) + put(bw, 1, 1) + put(bw, 1, 2) + put(bw, cbits - 2, 3) + writeImage(bw, cimg, subSample(w, cbits), subSample(w, cbits) * subSample(h, cbits), sub, false) + end + end + put(bw, 0, 1) -- no more transforms + writeImage(bw, px, xs, xs * h, effort, true) +end + +@native function Encode.encode(rgba: buffer, w: number, h: number, effort: number, exact: boolean, alphaHint: boolean?, headerless: boolean): buffer + local n = w * h + local px, usesAlpha = toArgb(rgba, n, exact) + local pal = if effort > 0 then palette(px, n) else nil + local configs: { Config } = {} + if effort == 0 then + table.insert(configs, { palette = nil, pbits = 0, cc = false, ccbits = 0 }) + else + local pbits = if effort >= 5 then 4 else 5 + local plain: Config = { palette = nil, pbits = pbits, cc = effort >= 3, ccbits = if effort >= 6 then 4 else 5 } + if pal then + table.insert(configs, { palette = pal, pbits = 0, cc = false, ccbits = 0 }) + if effort >= 6 then + table.insert(configs, plain) + end + else + table.insert(configs, plain) + end + if effort >= 9 then + table.insert(configs, { palette = nil, pbits = 3, cc = true, ccbits = 3 }) + table.insert(configs, { palette = nil, pbits = 5, cc = false, ccbits = 0 }) + end + end + local best: buffer? = nil + for k, cfg in configs do + local bw = newWriter(n + 256) + if not headerless then + put(bw, 0x2f, 8) + put(bw, w - 1, 14) + put(bw, h - 1, 14) + local hint = if alphaHint == nil then usesAlpha else alphaHint + put(bw, if hint then 1 else 0, 1) + put(bw, 0, 3) + end + local work = px + if k < #configs then + work = bcreate(n * 4) + bcopy(work, 0, px, 0, n * 4) + end + stream(work, w, h, effort, cfg, bw) + local out = finish(bw) + if not best or blen(out) < blen(best) then + best = out + end + end + return best :: buffer +end + +return Encode +end +end + + + + + + Bcn + --!optimize 2 +--!nocheck +-- rosetta chunk Bcn (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 3 modules (3 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["codecs/image/Bcn"] = @native function() + + + +-- codecs/image/Bcn: BC1-BC7 block-compressed textures with the D3D11 rules. +-- Decoders ported from Pillow's BcnDecode.c (CC0); encoders new (stb_dxt-style). SNORM is biased by 128 into rgba8. +local Decode = __include("codecs/image/Bcn/Decode") +local Encode = __include("codecs/image/Bcn/Encode") + +local Bcn = {} + +Bcn.BLOCK = table.freeze({ bc1 = 8, bc2 = 16, bc3 = 16, bc4 = 8, bc4s = 8, bc5 = 16, bc5s = 16, bc6h = 16, bc6hs = 16, bc7 = 16 }) :: { [string]: number } +Bcn.FLOAT = table.freeze({ bc6h = true, bc6hs = true }) :: { [string]: boolean } + +local readu32, writeu32 = buffer.readu32, buffer.writeu32 + +local BLOCKS: { [string]: (buffer, number, buffer) -> () } = { + bc1 = Decode.bc1, + bc2 = Decode.bc2, + bc3 = Decode.bc3, + bc4 = Decode.bc4, + bc4s = Decode.bc4s, + bc5 = Decode.bc5, + bc5s = Decode.bc5s, + bc7 = Decode.bc7, + bc6h = @native function(src: buffer, p: number, blk: buffer) + Decode.bc6h(src, p, blk, false) + end, + bc6hs = @native function(src: buffer, p: number, blk: buffer) + Decode.bc6h(src, p, blk, true) + end, +} + +@native function Bcn.size(kind: string, w: number, h: number): number? + local b = Bcn.BLOCK[kind] + if not b then + return nil + end + return ((w + 3) // 4) * ((h + 3) // 4) * b +end + +@native function Bcn.decode(kind: string, src: buffer, offset: number, w: number, h: number, out: buffer?, outOffset: number?): (buffer?, string?) + local fn = BLOCKS[kind] + if not fn then + return nil, "unsupported: unknown block format " .. tostring(kind) + end + if w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 then + return nil, "bad image size" + end + local need = Bcn.size(kind, w, h) :: number + if offset < 0 or offset + need > buffer.len(src) then + return nil, "truncated: block data runs past the end" + end + local float = Bcn.FLOAT[kind] == true + local bpp = if float then 16 else 4 + local oo = outOffset or 0 + local dst = out or buffer.create(w * h * bpp) + if oo + w * h * bpp > buffer.len(dst) then + return nil, "output buffer too small" + end + local bytes = Bcn.BLOCK[kind] + local blk = buffer.create(16 * bpp) + local bw, bh = (w + 3) // 4, (h + 3) // 4 + local p = offset + local rowBytes = w * bpp + for by = 0, bh - 1 do + local rows = math.min(4, h - by * 4) + for bx = 0, bw - 1 do + fn(src, p, blk) + p += bytes + local cols = math.min(4, w - bx * 4) + local base = oo + (by * 4) * rowBytes + bx * 4 * bpp + if cols == 4 and not float then + for y = 0, rows - 1 do + local d, s = base + y * rowBytes, y * 16 + writeu32(dst, d, readu32(blk, s)) + writeu32(dst, d + 4, readu32(blk, s + 4)) + writeu32(dst, d + 8, readu32(blk, s + 8)) + writeu32(dst, d + 12, readu32(blk, s + 12)) + end + else + for y = 0, rows - 1 do + buffer.copy(dst, base + y * rowBytes, blk, y * 4 * bpp, cols * bpp) + end + end + end + end + return dst, nil +end + +type EncodeOptions = { + alphaThreshold: number?, +} + +@native function Bcn.encode(kind: string, px: buffer, w: number, h: number, opts: EncodeOptions?): (buffer?, string?) + if kind ~= "bc1" and kind ~= "bc3" and kind ~= "bc4" and kind ~= "bc5" then + return nil, "unsupported: no encoder for " .. tostring(kind) + end + 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(px) < w * h * 4 then + return nil, "needs w x h rgba8 pixels" + end + local t = opts and opts.alphaThreshold or 128 + return Encode.run(kind, px, w, h, t), nil +end + +return Bcn +end +__FILES["codecs/image/Bcn/Decode"] = @native function() + + + +-- codecs/image/Bcn/Decode: BC1..BC7 block decoders (S3TC / DXT1-5, RGTC, BPTC), ported from Pillow's BcnDecode.c +-- (CC0, licenses/pillow-bcn-CC0.txt). Follows the D3D11 functional spec where Pillow does not: BC6H rounds +-- (a * (64 - w) + b * w + 32) >> 6 and keeps floats, reserved modes decode to zero, SNORM -128 reads as -127. +local Half = __include("codecs/image/Half") + +local Decode = {} + +local readu8, readu16, readu32, writeu8, writeu32, writef32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu32, buffer.writef32 +local band, bor, rshift, lshift = bit32.band, bit32.bor, bit32.rshift, bit32.lshift +local HALF = Half.TABLE + +local pal = buffer.create(16) + +@native local function c565(c: number): (number, number, number) + local r = rshift(band(c, 0xF800), 8) + local g = rshift(band(c, 0x7E0), 3) + local b = lshift(band(c, 0x1F), 3) + return bor(r, rshift(r, 5)), bor(g, rshift(g, 6)), bor(b, rshift(b, 5)) +end + +-- BC2 / BC3 colour blocks always use the 4-colour palette +@native local function colour(src: buffer, p: number, blk: buffer, fourColour: boolean) + local c0, c1 = readu16(src, p), readu16(src, p + 2) + local r0, g0, b0 = c565(c0) + local r1, g1, b1 = c565(c1) + writeu32(pal, 0, r0 + g0 * 256 + b0 * 65536 + 0xFF000000) + writeu32(pal, 4, r1 + g1 * 256 + b1 * 65536 + 0xFF000000) + if c0 > c1 or fourColour then + writeu32(pal, 8, (2 * r0 + r1) // 3 + ((2 * g0 + g1) // 3) * 256 + ((2 * b0 + b1) // 3) * 65536 + 0xFF000000) + writeu32(pal, 12, (r0 + 2 * r1) // 3 + ((g0 + 2 * g1) // 3) * 256 + ((b0 + 2 * b1) // 3) * 65536 + 0xFF000000) + else + writeu32(pal, 8, (r0 + r1) // 2 + ((g0 + g1) // 2) * 256 + ((b0 + b1) // 2) * 65536 + 0xFF000000) + writeu32(pal, 12, 0) + end + local idx = readu32(src, p + 4) + for i = 0, 15 do + writeu32(blk, i * 4, readu32(pal, band(rshift(idx, i * 2), 3) * 4)) + end +end + +local vals = table.create(8, 0) +@native local function ramp8(a0: number, a1: number) + vals[1], vals[2] = a0, a1 + if a0 > a1 then + for i = 1, 6 do + vals[i + 2] = ((7 - i) * a0 + i * a1) // 7 + end + else + for i = 1, 4 do + vals[i + 2] = ((5 - i) * a0 + i * a1) // 5 + end + vals[7], vals[8] = 0, 255 + end +end + +-- signed (SNORM) ramp, values -127..127 rounded to the nearest integer, biased by 128 into 1..255 +@native local function ramp8s(u0: number, u1: number) + local s0: number = math.max(if u0 >= 128 then u0 - 256 else u0, -127) + local s1: number = math.max(if u1 >= 128 then u1 - 256 else u1, -127) + vals[1], vals[2] = s0 + 128, s1 + 128 + if s0 > s1 then + for i = 1, 6 do + vals[i + 2] = math.floor(((7 - i) * s0 + i * s1) / 7 + 0.5) + 128 + end + else + for i = 1, 4 do + vals[i + 2] = math.floor(((5 - i) * s0 + i * s1) / 5 + 0.5) + 128 + end + vals[7], vals[8] = 1, 255 + end +end + +@native local function single(src: buffer, p: number, blk: buffer, channel: number, signed: boolean, spread: boolean) + if signed then + ramp8s(readu8(src, p), readu8(src, p + 1)) + else + ramp8(readu8(src, p), readu8(src, p + 1)) + end + local lo = readu8(src, p + 2) + readu8(src, p + 3) * 256 + readu8(src, p + 4) * 65536 + local hi = readu8(src, p + 5) + readu8(src, p + 6) * 256 + readu8(src, p + 7) * 65536 + for i = 0, 15 do + local sel = if i < 8 then band(rshift(lo, i * 3), 7) else band(rshift(hi, (i - 8) * 3), 7) + local v = vals[sel + 1] + local o = i * 4 + if spread then + writeu32(blk, o, v + v * 256 + v * 65536 + 0xFF000000) + else + writeu8(blk, o + channel, v) + end + end +end + +@native function Decode.bc1(src: buffer, p: number, blk: buffer) + colour(src, p, blk, false) +end + +@native function Decode.bc2(src: buffer, p: number, blk: buffer) + colour(src, p + 8, blk, true) + for i = 0, 15 do + local a = band(rshift(readu8(src, p + rshift(i, 1)), band(i, 1) * 4), 15) + writeu8(blk, i * 4 + 3, a * 17) + end +end + +@native function Decode.bc3(src: buffer, p: number, blk: buffer) + colour(src, p + 8, blk, true) + single(src, p, blk, 3, false, false) +end + +@native function Decode.bc4(src: buffer, p: number, blk: buffer) + single(src, p, blk, 0, false, true) +end + +@native function Decode.bc4s(src: buffer, p: number, blk: buffer) + single(src, p, blk, 0, true, true) +end + +@native local function bc5(src: buffer, p: number, blk: buffer, signed: boolean) + for i = 0, 15 do + writeu32(blk, i * 4, 0xFF000000) + end + single(src, p, blk, 0, signed, false) + single(src, p + 8, blk, 1, signed, false) +end +@native function Decode.bc5(src: buffer, p: number, blk: buffer) + bc5(src, p, blk, false) +end +@native function Decode.bc5s(src: buffer, p: number, blk: buffer) + bc5(src, p, blk, true) +end + +-- partition tables (BC7 Table.P2 1 bit per pixel, Table.P3 2 bits per pixel) and the anchor indices +local SI2 = { + 0xcccc, 0x8888, 0xeeee, 0xecc8, 0xc880, 0xfeec, 0xfec8, 0xec80, 0xc800, 0xffec, 0xfe80, 0xe800, 0xffe8, 0xff00, 0xfff0, 0xf000, + 0xf710, 0x008e, 0x7100, 0x08ce, 0x008c, 0x7310, 0x3100, 0x8cce, 0x088c, 0x3110, 0x6666, 0x366c, 0x17e8, 0x0ff0, 0x718e, 0x399c, + 0xaaaa, 0xf0f0, 0x5a5a, 0x33cc, 0x3c3c, 0x55aa, 0x9696, 0xa55a, 0x73ce, 0x13c8, 0x324c, 0x3bdc, 0x6996, 0xc33c, 0x9966, 0x0660, + 0x0272, 0x04e4, 0x4e40, 0x2720, 0xc936, 0x936c, 0x39c6, 0x639c, 0x9336, 0x9cc6, 0x817e, 0xe718, 0xccf0, 0x0fcc, 0x7744, 0xee22, +} +local SI3 = { + 0xaa685050, 0x6a5a5040, 0x5a5a4200, 0x5450a0a8, 0xa5a50000, 0xa0a05050, 0x5555a0a0, 0x5a5a5050, 0xaa550000, 0xaa555500, + 0xaaaa5500, 0x90909090, 0x94949494, 0xa4a4a4a4, 0xa9a59450, 0x2a0a4250, 0xa5945040, 0x0a425054, 0xa5a5a500, 0x55a0a0a0, + 0xa8a85454, 0x6a6a4040, 0xa4a45000, 0x1a1a0500, 0x0050a4a4, 0xaaa59090, 0x14696914, 0x69691400, 0xa08585a0, 0xaa821414, + 0x50a4a450, 0x6a5a0200, 0xa9a58000, 0x5090a0a8, 0xa8a09050, 0x24242424, 0x00aa5500, 0x24924924, 0x24499224, 0x50a50a50, + 0x500aa550, 0xaaaa4444, 0x66660000, 0xa5a0a5a0, 0x50a050a0, 0x69286928, 0x44aaaa44, 0x66666600, 0xaa444444, 0x54a854a8, + 0x95809580, 0x96969600, 0xa85454a8, 0x80959580, 0xaa141414, 0x96960000, 0xaaaa1414, 0xa05050a0, 0xa0a5a5a0, 0x96000000, + 0x40804080, 0xa9a8a9a8, 0xaaaaaa44, 0x2a4a5254, +} +local AI0 = { + 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 2, 8, 2, 2, 8, 8, 15, 2, 8, 2, 2, 8, 8, 2, 2, + 15, 15, 6, 8, 2, 8, 15, 15, 2, 8, 2, 2, 2, 15, 15, 6, 6, 2, 6, 8, 15, 15, 2, 2, 15, 15, 15, 15, 15, 2, 2, 15, +} +local AI1 = { + 3, 3, 15, 15, 8, 3, 15, 15, 8, 8, 6, 6, 6, 5, 3, 3, 3, 3, 8, 15, 3, 3, 6, 10, 5, 8, 8, 6, 8, 5, 15, 15, + 8, 15, 3, 5, 6, 10, 8, 15, 15, 3, 15, 5, 15, 15, 15, 15, 3, 15, 5, 5, 5, 8, 5, 10, 5, 10, 8, 13, 15, 12, 3, 3, +} +local AI2 = { + 15, 8, 8, 3, 15, 15, 3, 8, 15, 15, 15, 15, 15, 15, 15, 8, 15, 8, 15, 3, 15, 8, 15, 8, 3, 15, 6, 10, 15, 15, 10, 8, + 15, 3, 15, 10, 10, 8, 9, 10, 6, 15, 8, 15, 3, 6, 6, 8, 15, 3, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 3, 15, 15, 8, +} +local W2 = { [0] = 0, 21, 43, 64 } +local W3 = { [0] = 0, 9, 18, 27, 37, 46, 55, 64 } +local W4 = { [0] = 0, 4, 9, 13, 17, 21, 26, 30, 34, 38, 43, 47, 51, 55, 60, 64 } +local WEIGHTS = { [2] = W2, [3] = W3, [4] = W4 } +Decode.SI2, Decode.SI3, Decode.AI0, Decode.AI1, Decode.AI2, Decode.WEIGHTS = SI2, SI3, AI0, AI1, AI2, WEIGHTS + +@native local function subset(ns: number, part: number, i: number): number + if ns == 2 then + return band(rshift(SI2[part + 1], i), 1) + elseif ns == 3 then + return band(rshift(SI3[part + 1], 2 * i), 3) + end + return 0 +end + +local w0, w1, w2, w3 = 0, 0, 0, 0 +@native local function load(src: buffer, p: number) + w0, w1, w2, w3 = readu32(src, p), readu32(src, p + 4), readu32(src, p + 8), readu32(src, p + 12) +end +@native local function word(i: number): number + return if i == 0 then w0 elseif i == 1 then w1 elseif i == 2 then w2 else w3 +end +@native local function bits(at: number, n: number): number + if n == 0 then + return 0 + end + local wi, sh = rshift(at, 5), band(at, 31) + local v = rshift(word(wi), sh) + if sh + n > 32 and wi < 3 then + v = bor(v, lshift(word(wi + 1), 32 - sh)) + end + return band(v, lshift(1, n) - 1) +end + +-- ns, pb, rb, isb, cb, ab, epb, spb, ib, ib2 +local MODES7 = { + { 3, 4, 0, 0, 4, 0, 1, 0, 3, 0 }, + { 2, 6, 0, 0, 6, 0, 0, 1, 3, 0 }, + { 3, 6, 0, 0, 5, 0, 0, 0, 2, 0 }, + { 2, 6, 0, 0, 7, 0, 1, 0, 2, 0 }, + { 1, 0, 2, 1, 5, 6, 0, 0, 2, 3 }, + { 1, 0, 2, 0, 7, 8, 0, 0, 2, 2 }, + { 1, 0, 0, 0, 7, 7, 1, 0, 4, 0 }, + { 2, 6, 0, 0, 5, 5, 1, 0, 2, 0 }, +} +local er, eg, eb, ea = table.create(6, 0), table.create(6, 0), table.create(6, 0), table.create(6, 0) + +@native local function expand(v: number, n: number): number + v = band(lshift(v, 8 - n), 255) + return bor(v, rshift(v, n)) +end + +@native function Decode.bc7(src: buffer, p: number, blk: buffer) + local m0 = readu8(src, p) + if m0 == 0 then + buffer.fill(blk, 0, 0, 64) + return + end + load(src, p) + local mode = 0 + while band(m0, lshift(1, mode)) == 0 do + mode += 1 + end + local info = MODES7[mode + 1] + local ns, pb, rb, isb, cb, ab, epb, spb, ib, ib2 = info[1], info[2], info[3], info[4], info[5], info[6], info[7], info[8], info[9], info[10] + local bit = mode + 1 + local part = bits(bit, pb) + bit += pb + local rot = bits(bit, rb) + bit += rb + local sel = bits(bit, isb) + bit += isb + local nep = ns * 2 + for i = 1, nep do + er[i] = bits(bit, cb) + bit += cb + end + for i = 1, nep do + eg[i] = bits(bit, cb) + bit += cb + end + for i = 1, nep do + eb[i] = bits(bit, cb) + bit += cb + end + for i = 1, nep do + if ab > 0 then + ea[i] = bits(bit, ab) + bit += ab + else + ea[i] = 255 + end + end + if epb == 1 then + cb += 1 + if ab > 0 then + ab += 1 + end + for i = 1, nep do + local v = bits(bit, 1) + bit += 1 + er[i], eg[i], eb[i] = er[i] * 2 + v, eg[i] * 2 + v, eb[i] * 2 + v + if ab > 0 then + ea[i] = ea[i] * 2 + v + end + end + end + if spb == 1 then + cb += 1 + if ab > 0 then + ab += 1 + end + for i = 1, nep, 2 do + local v = bits(bit, 1) + bit += 1 + for j = i, i + 1 do + er[j], eg[j], eb[j] = er[j] * 2 + v, eg[j] * 2 + v, eb[j] * 2 + v + if ab > 0 then + ea[j] = ea[j] * 2 + v + end + end + end + end + for i = 1, nep do + er[i], eg[i], eb[i] = expand(er[i], cb), expand(eg[i], cb), expand(eb[i], cb) + if ab > 0 then + ea[i] = expand(ea[i], ab) + end + end + local cw = WEIGHTS[ib] + local aw = if ab > 0 and ib2 > 0 then WEIGHTS[ib2] else cw + local cbit = bit + local abit = cbit + 16 * ib - ns + local a1 = if ns == 2 then AI0[part + 1] elseif ns == 3 then AI1[part + 1] else -1 + local a2 = if ns == 3 then AI2[part + 1] else -1 + for i = 0, 15 do + local s = subset(ns, part, i) * 2 + 1 + local n = ib + if i == 0 or i == a1 or i == a2 then + n -= 1 + end + local i0 = bits(cbit, n) + cbit += n + local wc, wa + if ab > 0 and ib2 > 0 then + local n2 = if i == 0 then ib2 - 1 else ib2 + local i1 = bits(abit, n2) + abit += n2 + if sel == 1 then + wc, wa = aw[i1], cw[i0] + else + wc, wa = cw[i0], aw[i1] + end + else + wc, wa = cw[i0], cw[i0] + end + local tc, ta = 64 - wc, 64 - wa + local r = rshift(tc * er[s] + wc * er[s + 1] + 32, 6) + local g = rshift(tc * eg[s] + wc * eg[s + 1] + 32, 6) + local b = rshift(tc * eb[s] + wc * eb[s + 1] + 32, 6) + local a = rshift(ta * ea[s] + wa * ea[s + 1] + 32, 6) + if rot == 1 then + r, a = a, r + elseif rot == 2 then + g, a = a, g + elseif rot == 3 then + b, a = a, b + end + writeu32(blk, i * 4, r + g * 256 + b * 65536 + a * 16777216) + end +end + +-- ns, transformed, pb, epb, rb, gb, bb +local MODES6 = { + { 2, 1, 5, 10, 5, 5, 5 }, + { 2, 1, 5, 7, 6, 6, 6 }, + { 2, 1, 5, 11, 5, 4, 4 }, + { 2, 1, 5, 11, 4, 5, 4 }, + { 2, 1, 5, 11, 4, 4, 5 }, + { 2, 1, 5, 9, 5, 5, 5 }, + { 2, 1, 5, 8, 6, 5, 5 }, + { 2, 1, 5, 8, 5, 6, 5 }, + { 2, 1, 5, 8, 5, 5, 6 }, + { 2, 0, 5, 6, 6, 6, 6 }, + { 1, 0, 0, 10, 10, 10, 10 }, + { 1, 1, 0, 11, 9, 9, 9 }, + { 1, 1, 0, 12, 8, 8, 8 }, + { 1, 1, 0, 16, 4, 4, 4 }, +} +-- Table.F: for each endpoint bit in stream order, endpoint * 16 + bit (endpoints r0 g0 b0 r1 g1 b1 r2 ... b3) +local PACK6 = { + { 116, 132, 180, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52, 164, 112, 113, 114, 115, 64, 65, 66, 67, 68, 176, 160, 161, 162, 163, 80, 81, 82, 83, 84, 177, 128, 129, 130, 131, 96, 97, 98, 99, 100, 178, 144, 145, 146, 147, 148, 179 }, + { 117, 164, 165, 0, 1, 2, 3, 4, 5, 6, 176, 177, 132, 16, 17, 18, 19, 20, 21, 22, 133, 178, 116, 32, 33, 34, 35, 36, 37, 38, 179, 181, 180, 48, 49, 50, 51, 52, 53, 112, 113, 114, 115, 64, 65, 66, 67, 68, 69, 160, 161, 162, 163, 80, 81, 82, 83, 84, 85, 128, 129, 130, 131, 96, 97, 98, 99, 100, 101, 144, 145, 146, 147, 148, 149 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52, 10, 112, 113, 114, 115, 64, 65, 66, 67, 26, 176, 160, 161, 162, 163, 80, 81, 82, 83, 42, 177, 128, 129, 130, 131, 96, 97, 98, 99, 100, 178, 144, 145, 146, 147, 148, 179 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 10, 164, 112, 113, 114, 115, 64, 65, 66, 67, 68, 26, 160, 161, 162, 163, 80, 81, 82, 83, 42, 177, 128, 129, 130, 131, 96, 97, 98, 99, 176, 178, 144, 145, 146, 147, 116, 179 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 10, 132, 112, 113, 114, 115, 64, 65, 66, 67, 26, 176, 160, 161, 162, 163, 80, 81, 82, 83, 84, 42, 128, 129, 130, 131, 96, 97, 98, 99, 177, 178, 144, 145, 146, 147, 180, 179 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 132, 16, 17, 18, 19, 20, 21, 22, 23, 24, 116, 32, 33, 34, 35, 36, 37, 38, 39, 40, 180, 48, 49, 50, 51, 52, 164, 112, 113, 114, 115, 64, 65, 66, 67, 68, 176, 160, 161, 162, 163, 80, 81, 82, 83, 84, 177, 128, 129, 130, 131, 96, 97, 98, 99, 100, 178, 144, 145, 146, 147, 148, 179 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 164, 132, 16, 17, 18, 19, 20, 21, 22, 23, 178, 116, 32, 33, 34, 35, 36, 37, 38, 39, 179, 180, 48, 49, 50, 51, 52, 53, 112, 113, 114, 115, 64, 65, 66, 67, 68, 176, 160, 161, 162, 163, 80, 81, 82, 83, 84, 177, 128, 129, 130, 131, 96, 97, 98, 99, 100, 101, 144, 145, 146, 147, 148, 149 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 176, 132, 16, 17, 18, 19, 20, 21, 22, 23, 117, 116, 32, 33, 34, 35, 36, 37, 38, 39, 165, 180, 48, 49, 50, 51, 52, 164, 112, 113, 114, 115, 64, 65, 66, 67, 68, 69, 160, 161, 162, 163, 80, 81, 82, 83, 84, 177, 128, 129, 130, 131, 96, 97, 98, 99, 100, 178, 144, 145, 146, 147, 148, 179 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 177, 132, 16, 17, 18, 19, 20, 21, 22, 23, 133, 116, 32, 33, 34, 35, 36, 37, 38, 39, 181, 180, 48, 49, 50, 51, 52, 164, 112, 113, 114, 115, 64, 65, 66, 67, 68, 176, 160, 161, 162, 163, 80, 81, 82, 83, 84, 85, 128, 129, 130, 131, 96, 97, 98, 99, 100, 178, 144, 145, 146, 147, 148, 179 }, + { 0, 1, 2, 3, 4, 5, 164, 176, 177, 132, 16, 17, 18, 19, 20, 21, 117, 133, 178, 116, 32, 33, 34, 35, 36, 37, 165, 179, 181, 180, 48, 49, 50, 51, 52, 53, 112, 113, 114, 115, 64, 65, 66, 67, 68, 69, 160, 161, 162, 163, 80, 81, 82, 83, 84, 85, 128, 129, 130, 131, 96, 97, 98, 99, 100, 101, 144, 145, 146, 147, 148, 149 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52, 53, 54, 55, 56, 10, 64, 65, 66, 67, 68, 69, 70, 71, 72, 26, 80, 81, 82, 83, 84, 85, 86, 87, 88, 42 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52, 53, 54, 55, 11, 10, 64, 65, 66, 67, 68, 69, 70, 71, 27, 26, 80, 81, 82, 83, 84, 85, 86, 87, 43, 42 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 15, 14, 13, 12, 11, 10, 64, 65, 66, 67, 31, 30, 29, 28, 27, 26, 80, 81, 82, 83, 47, 46, 45, 44, 43, 42 }, +} +local ep = table.create(12, 0) +local uq = table.create(12, 0) + +@native local function signExtend(v: number, n: number): number + v = band(v, lshift(1, n) - 1) + return if v >= lshift(1, n - 1) then v - lshift(1, n) else v +end + +@native local function unquantize(x: number, n: number, signed: boolean): number + if not signed then + if n >= 15 or x == 0 then + return x + elseif x == lshift(1, n) - 1 then + return 0xFFFF + end + return rshift(x * 32768 + 0x4000, n - 1) + end + if n >= 16 then + return x + end + local neg = x < 0 + if neg then + x = -x + end + if x ~= 0 then + if x >= lshift(1, n - 1) - 1 then + x = 0x7FFF + else + x = rshift(x * 32768 + 0x4000, n - 1) + end + end + return if neg then -x else x +end + +@native local function finish(v: number, signed: boolean): number + if signed then + if v < 0 then + return -HALF[(-v * 31) // 32] + end + return HALF[(v * 31) // 32] + end + return HALF[(v * 31) // 64] +end + +@native function Decode.bc6h(src: buffer, p: number, blk: buffer, signed: boolean) + load(src, p) + local m = band(w0, 31) + local mode, bit, epbits, ib + local low = band(m, 3) + if low < 2 then + mode, bit, epbits, ib = low, 2, 75, 3 + elseif low == 2 then + mode, bit, epbits, ib = 2 + rshift(m, 2), 5, 72, 3 + else + mode, bit, epbits, ib = 10 + rshift(m, 2), 5, 60, 4 + end + if mode >= 14 then + for i = 0, 15 do + local o = i * 16 + writef32(blk, o, 0) + writef32(blk, o + 4, 0) + writef32(blk, o + 8, 0) + writef32(blk, o + 12, 1) + end + return + end + local info = MODES6[mode + 1] + local ns, tr, pb, epb, rbits, gbits, bbits = info[1], info[2], info[3], info[4], info[5], info[6], info[7] + local nep = if ns == 2 then 12 else 6 + for i = 1, 12 do + ep[i] = 0 + end + local pack = PACK6[mode + 1] + for i = 1, epbits do + local d = pack[i] + local e = rshift(d, 4) + 1 + ep[e] = bor(ep[e], lshift(bits(bit + i - 1, 1), band(d, 15))) + end + bit += epbits + local part = bits(bit, pb) + bit += pb + local mask = lshift(1, epb) - 1 + if signed then + ep[1], ep[2], ep[3] = signExtend(ep[1], epb), signExtend(ep[2], epb), signExtend(ep[3], epb) + end + if signed or tr == 1 then + for i = 4, nep, 3 do + ep[i], ep[i + 1], ep[i + 2] = signExtend(ep[i], rbits), signExtend(ep[i + 1], gbits), signExtend(ep[i + 2], bbits) + end + end + if tr == 1 then + for i = 4, nep, 3 do + for c = 0, 2 do + local v = band(ep[i + c] + ep[1 + c], mask) + ep[i + c] = if signed then signExtend(v, epb) else v + end + end + end + for i = 1, nep do + uq[i] = unquantize(ep[i], epb, signed) + end + local w = WEIGHTS[ib] + local a1 = if ns == 2 then AI0[part + 1] else -1 + for i = 0, 15 do + local s = subset(ns, part, i) * 6 + 1 + local n = if i == 0 or i == a1 then ib - 1 else ib + local wt = w[bits(bit, n)] + bit += n + local t = 64 - wt + local o = i * 16 + -- floor((a * t + b * w + 32) / 64): the products may be negative (signed) - // floors like >> would + writef32(blk, o, finish((uq[s] * t + uq[s + 3] * wt + 32) // 64, signed)) + writef32(blk, o + 4, finish((uq[s + 1] * t + uq[s + 4] * wt + 32) // 64, signed)) + writef32(blk, o + 8, finish((uq[s + 2] * t + uq[s + 5] * wt + 32) // 64, signed)) + writef32(blk, o + 12, 1) + end +end + +return Decode +end +__FILES["codecs/image/Bcn/Encode"] = @native function() + + + +-- codecs/image/Bcn/Encode: BC1 / BC3 / BC4 / BC5 block encoders, new in rosetta; the approach follows stb_dxt (Fabian +-- Giesen / Sean Barrett, public domain): principal axis endpoints, least-squares refinement, exact single-colour tables. +local Encode = {} + +local readu8, writeu8, writeu16, writeu32 = buffer.readu8, buffer.writeu8, buffer.writeu16, buffer.writeu32 +local band, bor, rshift, lshift = bit32.band, bit32.bor, bit32.rshift, bit32.lshift + +@native local function exp5(v: number): number + return bor(lshift(v, 3), rshift(v, 2)) +end +@native local function exp6(v: number): number + return bor(lshift(v, 2), rshift(v, 4)) +end + +-- OM[k][v + 1] = e0 * 256 + e1 (quantized) whose colour-2 value (4-colour: (2 e0 + e1) // 3; 3-colour: (e0 + e1) +-- // 2) is closest to v; k = 1 / 2 for 5-bit (4 / 3 colour), 3 / 4 for 6-bit +local OM: { { number } }? = nil +@native local function singleTables(): { { number } } + local om = OM + if om then + return om + end + local t: { { number } } = {} + for k = 1, 4 do + local bitsN = if k <= 2 then 5 else 6 + local maxq = lshift(1, bitsN) - 1 + local exp: (number) -> number = if bitsN == 5 then exp5 else exp6 + local best = table.create(256, 1e9) + local pick = table.create(256, 0) + for a = 0, maxq do + local ea = exp(a) + for b = 0, maxq do + local eb = exp(b) + local v: number = if k % 2 == 1 then (2 * ea + eb) // 3 else (ea + eb) // 2 + -- prefer endpoints close to each other (less error if the colour shifts) + local e = math.abs(ea - eb) * 0.01 + for target = math.max(0, v - 8), math.min(255, v + 8) do + local err = (target - v) ^ 2 + e + if err < best[target + 1] then + best[target + 1] = err + pick[target + 1] = a * 256 + b + end + end + end + end + t[k] = pick + end + OM = t + return t +end + +local R, G, B, A = table.create(16, 0), table.create(16, 0), table.create(16, 0), table.create(16, 0) +local USE = table.create(16, true) +local PR, PG, PB = table.create(4, 0), table.create(4, 0), table.create(4, 0) +local IDX = table.create(16, 0) +local BEST = table.create(16, 0) + +@native local function palette(c0: number, c1: number, four: boolean) + local r0, g0, b0 = exp5(rshift(c0, 11)), exp6(band(rshift(c0, 5), 63)), exp5(band(c0, 31)) + local r1, g1, b1 = exp5(rshift(c1, 11)), exp6(band(rshift(c1, 5), 63)), exp5(band(c1, 31)) + PR[1], PG[1], PB[1] = r0, g0, b0 + PR[2], PG[2], PB[2] = r1, g1, b1 + if four then + PR[3], PG[3], PB[3] = (2 * r0 + r1) // 3, (2 * g0 + g1) // 3, (2 * b0 + b1) // 3 + PR[4], PG[4], PB[4] = (r0 + 2 * r1) // 3, (g0 + 2 * g1) // 3, (b0 + 2 * b1) // 3 + else + PR[3], PG[3], PB[3] = (r0 + r1) // 2, (g0 + g1) // 2, (b0 + b1) // 2 + PR[4], PG[4], PB[4] = 0, 0, 0 + end +end + +@native local function assign(four: boolean): number + local n = if four then 4 else 3 + local total = 0 + for i = 1, 16 do + if USE[i] then + local r, g, b = R[i], G[i], B[i] + local bi, be = 0, math.huge + for k = 1, n do + local dr, dg, db = r - PR[k], g - PG[k], b - PB[k] + local e = dr * dr + dg * dg + db * db + if e < be then + be, bi = e, k - 1 + end + end + IDX[i] = bi + total += be + else + IDX[i] = 3 + end + end + return total +end + +@native local function q565(r: number, g: number, b: number): number + local qr = math.clamp(math.floor(r * 31 / 255 + 0.5), 0, 31) + local qg = math.clamp(math.floor(g * 63 / 255 + 0.5), 0, 63) + local qb = math.clamp(math.floor(b * 31 / 255 + 0.5), 0, 31) + return qr * 2048 + qg * 32 + qb +end + +local W4 = { 1, 0, 2 / 3, 1 / 3 } +local W3 = { 1, 0, 0.5, 0 } + +@native local function refine(four: boolean): (number?, number?) + local W = if four then W4 else W3 + local aa, bb, ab = 0, 0, 0 + local ar, ag, ab_, br, bg, bb_ = 0, 0, 0, 0, 0, 0 + for i = 1, 16 do + if USE[i] then + local w = W[IDX[i] + 1] + local v = 1 - w + aa += w * w + bb += v * v + ab += w * v + ar += w * R[i] + ag += w * G[i] + ab_ += w * B[i] + br += v * R[i] + bg += v * G[i] + bb_ += v * B[i] + end + end + local det = aa * bb - ab * ab + if math.abs(det) < 1e-9 then + return nil, nil + end + local f = 1 / det + local r0, g0, b0 = (ar * bb - br * ab) * f, (ag * bb - bg * ab) * f, (ab_ * bb - bb_ * ab) * f + local r1, g1, b1 = (br * aa - ar * ab) * f, (bg * aa - ag * ab) * f, (bb_ * aa - ab_ * ab) * f + return q565(r0, g0, b0), q565(r1, g1, b1) +end + +@native local function colourBlock(out: buffer, o: number, four: boolean) + local n, mr, mg, mb = 0, 0, 0, 0 + for i = 1, 16 do + if USE[i] then + n += 1 + mr += R[i] + mg += G[i] + mb += B[i] + end + end + if n == 0 then + writeu16(out, o, 0) + writeu16(out, o + 2, 0) + writeu32(out, o + 4, 0xFFFFFFFF) + return + end + mr, mg, mb = mr / n, mg / n, mb / n + local crr, cgg, cbb, crg, crb, cgb = 0, 0, 0, 0, 0, 0 + local same = true + local fr, fg, fb = -1, -1, -1 + for i = 1, 16 do + if USE[i] then + if fr < 0 then + fr, fg, fb = R[i], G[i], B[i] + elseif R[i] ~= fr or G[i] ~= fg or B[i] ~= fb then + same = false + end + local dr, dg, db = R[i] - mr, G[i] - mg, B[i] - mb + crr += dr * dr + cgg += dg * dg + cbb += db * db + crg += dr * dg + crb += dr * db + cgb += dg * db + end + end + local c0, c1 + if same then + local t = singleTables() + local k = if four then 0 else 1 + local pr, pg, pb = t[1 + k][fr + 1], t[3 + k][fg + 1], t[1 + k][fb + 1] + c0 = rshift(pr, 8) * 2048 + rshift(pg, 8) * 32 + rshift(pb, 8) + c1 = band(pr, 255) * 2048 + band(pg, 255) * 32 + band(pb, 255) + local i2 = 2 + if c0 == c1 then + i2 = 0 + end + -- index 2 everywhere (or 0 for an exact endpoint); order fixed below + for i = 1, 16 do + IDX[i] = if USE[i] then i2 else 3 + end + else + -- principal axis + local vr, vg, vb = 1, 1, 1 + for _ = 1, 8 do + local nr = crr * vr + crg * vg + crb * vb + local ng = crg * vr + cgg * vg + cgb * vb + local nb = crb * vr + cgb * vg + cbb * vb + local m = math.max(math.abs(nr), math.abs(ng), math.abs(nb)) + if m < 1e-9 then + break + end + vr, vg, vb = nr / m, ng / m, nb / m + end + local lo, hi, li, hi_ = math.huge, -math.huge, 1, 1 + for i = 1, 16 do + if USE[i] then + local d = R[i] * vr + G[i] * vg + B[i] * vb + if d < lo then + lo, li = d, i + end + if d > hi then + hi, hi_ = d, i + end + end + end + c0 = q565(R[hi_], G[hi_], B[hi_]) + c1 = q565(R[li], G[li], B[li]) + palette(c0, c1, four) + local err = assign(four) + for i = 1, 16 do + BEST[i] = IDX[i] + end + for _ = 1, 2 do + local n0, n1 = refine(four) + if not n0 or not n1 then + break + end + palette(n0, n1, four) + local e2 = assign(four) + if e2 < err then + err, c0, c1 = e2, n0, n1 + for i = 1, 16 do + BEST[i] = IDX[i] + end + else + break + end + end + for i = 1, 16 do + IDX[i] = BEST[i] + end + end + -- the mode is set by the endpoint order: 4-colour c0 > c1, 3-colour c0 <= c1 + if four then + if c0 < c1 then + c0, c1 = c1, c0 + for i = 1, 16 do + local v = IDX[i] + IDX[i] = if v == 0 then 1 elseif v == 1 then 0 elseif v == 2 then 3 else 2 + end + elseif c0 == c1 then + for i = 1, 16 do + IDX[i] = 0 + end + end + elseif c0 > c1 then + c0, c1 = c1, c0 + for i = 1, 16 do + local v = IDX[i] + IDX[i] = if v == 0 then 1 elseif v == 1 then 0 else v + end + end + writeu16(out, o, c0) + writeu16(out, o + 2, c1) + local bitsv = 0 + for i = 16, 1, -1 do + bitsv = bitsv * 4 + IDX[i] + end + writeu32(out, o + 4, bitsv) +end + +local V = table.create(16, 0) +local RAMP = table.create(8, 0) +local SEL = table.create(16, 0) +local SELB = table.create(16, 0) + +@native local function ramp(a0: number, a1: number) + RAMP[1], RAMP[2] = a0, a1 + if a0 > a1 then + for i = 1, 6 do + RAMP[i + 2] = ((7 - i) * a0 + i * a1) // 7 + end + else + for i = 1, 4 do + RAMP[i + 2] = ((5 - i) * a0 + i * a1) // 5 + end + RAMP[7], RAMP[8] = 0, 255 + end +end + +@native local function pick(): number + local total = 0 + for i = 1, 16 do + local v = V[i] + local bi, be = 0, math.huge + for k = 1, 8 do + local d = v - RAMP[k] + local e = d * d + if e < be then + be, bi = e, k - 1 + end + end + SEL[i] = bi + total += be + end + return total +end + +@native local function channelBlock(out: buffer, o: number) + local lo, hi = 255, 0 + local lo2, hi2 = 255, 0 + for i = 1, 16 do + local v = V[i] + lo, hi = math.min(lo, v), math.max(hi, v) + if v > 0 and v < 255 then + lo2, hi2 = math.min(lo2, v), math.max(hi2, v) + end + end + local a0, a1 + if lo == hi then + a0, a1 = lo, lo + ramp(a0, a1) + pick() + else + -- 8-value ramp, then a few nudged endpoints + local bestErr, b0, b1 = math.huge, hi, lo + for d0 = 0, 1 do + for d1 = 0, 1 do + local x0, x1 = hi - d0, lo + d1 + if x0 > x1 then + ramp(x0, x1) + local e = pick() + if e < bestErr then + bestErr, b0, b1 = e, x0, x1 + for i = 1, 16 do + SELB[i] = SEL[i] + end + end + end + end + end + -- 6-value ramp with the 0 / 255 extremes + if lo2 > hi2 then + lo2, hi2 = lo, lo + end + ramp(lo2, hi2) + local e = pick() + if e < bestErr then + bestErr, b0, b1 = e, lo2, hi2 + for i = 1, 16 do + SELB[i] = SEL[i] + end + end + a0, a1 = b0, b1 + for i = 1, 16 do + SEL[i] = SELB[i] + end + end + writeu8(out, o, a0) + writeu8(out, o + 1, a1) + local lo24, hi24 = 0, 0 + for i = 8, 1, -1 do + lo24 = lo24 * 8 + SEL[i] + hi24 = hi24 * 8 + SEL[i + 8] + end + writeu8(out, o + 2, band(lo24, 255)) + writeu8(out, o + 3, band(rshift(lo24, 8), 255)) + writeu8(out, o + 4, rshift(lo24, 16)) + writeu8(out, o + 5, band(hi24, 255)) + writeu8(out, o + 6, band(rshift(hi24, 8), 255)) + writeu8(out, o + 7, rshift(hi24, 16)) +end + +@native local function gather(px: buffer, w: number, h: number, bx: number, by: number) + for y = 0, 3 do + local sy = math.min(by * 4 + y, h - 1) + for x = 0, 3 do + local sx = math.min(bx * 4 + x, w - 1) + local s = (sy * w + sx) * 4 + local i = y * 4 + x + 1 + R[i], G[i], B[i], A[i] = readu8(px, s), readu8(px, s + 1), readu8(px, s + 2), readu8(px, s + 3) + end + end +end + +@native function Encode.run(kind: string, px: buffer, w: number, h: number, threshold: number): buffer + local bw, bh = (w + 3) // 4, (h + 3) // 4 + local bytes = if kind == "bc1" or kind == "bc4" then 8 else 16 + local out = buffer.create(bw * bh * bytes) + local o = 0 + for by = 0, bh - 1 do + for bx = 0, bw - 1 do + gather(px, w, h, bx, by) + if kind == "bc1" then + local any = false + for i = 1, 16 do + local u = A[i] >= threshold + USE[i] = u + any = any or not u + end + colourBlock(out, o, not any) + elseif kind == "bc3" then + for i = 1, 16 do + USE[i] = true + V[i] = A[i] + end + channelBlock(out, o) + colourBlock(out, o + 8, true) + elseif kind == "bc4" then + for i = 1, 16 do + V[i] = R[i] + end + channelBlock(out, o) + else + for i = 1, 16 do + V[i] = R[i] + end + channelBlock(out, o) + for i = 1, 16 do + V[i] = G[i] + end + channelBlock(out, o + 8) + end + o += bytes + end + end + return out +end + +return Encode +end +end + + + + + + Png + --!optimize 2 +--!nocheck +-- rosetta chunk Png (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 4 modules (3 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["image/png"] = function() + +-- image/png: PNG (ISO/IEC 15948, W3C PNG 3rd ed.) and APNG 1.0; from png-luau 1.0.0 (same author). Supports: every +-- colour type and bit depth, tRNS, Adam7, tEXt, acTL / fcTL / fdAT; writes RGBA / RGB / grey(+alpha) and APNG. Not +-- supported: colour management (iCCP kept raw), palette / 16-bit / interlaced output. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Crc32 = __include("core/Crc32") +local Deflate = __include("codecs/compress/Deflate") +local Types = __include("Types") +local Chunks = __include("containers/Chunks") +local Decode = __include("image/png/Decode") +local Encode = __include("image/png/Encode") +local Apng = __include("image/png/Apng") + +-- ------------------------------------------------------------------------------------------------ contract +local Png = { + name = "png", + category = "image", + extensions = { "png", "apng" }, + mime = { "image/png", "image/apng" }, + 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 } }, +} + +type DecodeOptions = { + checkCrc: boolean?, -- default false + maxPixels: number?, -- default 2^26 +} +type EncodeOptions = { + level: number?, -- 0..9, default 6 + colorType: ("auto" | "rgba" | "rgb" | "gray" | "graya")?, -- default "auto": the smallest lossless one + apng: boolean?, -- default: APNG when img.frames is a non-empty list +} + +-- ------------------------------------------------------------------------------------------------ constants +local SIGNATURE = "\137PNG\r\n\26\n" +local VALID = { + [0] = { [1] = true, [2] = true, [4] = true, [8] = true, [16] = true }, + [2] = { [8] = true, [16] = true }, + [3] = { [1] = true, [2] = true, [4] = true, [8] = true }, + [4] = { [8] = true, [16] = true }, + [6] = { [8] = true, [16] = true }, +} +local COLOR_NAMES = { [0] = "gray", [2] = "rgb", [3] = "palette", [4] = "graya", [6] = "rgba" } + +local readu8, readu32 = buffer.readu8, buffer.readu32 +local function be32(b: buffer, o: number): number + return bit32.byteswap(readu32(b, o)) +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Png.sniff(r: Bytes.Reader): number + return if r:peek(8) == SIGNATURE then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +type Header = { width: number, height: number, bitDepth: number, colorType: number, interlace: number } + +local function header(r: Bytes.Reader): (Header?, Err.Err?) + local b, o, n = r.buf, r.base, r.limit - r.base + if n < 8 or readu8(b, o) ~= 137 or buffer.readstring(b, o, 8) ~= SIGNATURE then + return nil, Err.new(Err.CORRUPT, "bad signature", o) + end + if n < 33 or buffer.readstring(b, o + 12, 4) ~= "IHDR" or be32(b, o + 8) ~= 13 then + return nil, Err.new(Err.CORRUPT, "missing IHDR", o + 8) + end + local h = { + width = be32(b, o + 16), + height = be32(b, o + 20), + bitDepth = readu8(b, o + 24), + colorType = readu8(b, o + 25), + interlace = readu8(b, o + 28), + } + if h.width == 0 or h.height == 0 or h.width >= 2 ^ 31 or h.height >= 2 ^ 31 then + return nil, Err.new(Err.CORRUPT, "bad image size", o + 16) + end + local depths = VALID[h.colorType] + if not depths then + return nil, Err.new(Err.CORRUPT, "bad colour type " .. h.colorType, o + 25) + end + if not depths[h.bitDepth] then + return nil, Err.new(Err.CORRUPT, string.format("bad bit depth %d for colour type %d", h.bitDepth, h.colorType), o + 24) + end + if readu8(b, o + 26) ~= 0 or readu8(b, o + 27) ~= 0 or h.interlace > 1 then + return nil, Err.new(Err.UNSUPPORTED, "unknown compression, filter or interlace method", o + 26) + end + return h, nil +end + +function Png.info(r: Bytes.Reader): (Header?, Err.Err?) + return header(r) +end + +type FrameControl = { + width: number, + height: number, + x: number, + y: number, + num: number, + den: number, + dispose: number, + blend: number, + chunks: { { number } }, -- fdAT payloads: offset, length + len: number, +} +local DISPOSE: { [number]: "none" | "background" | "previous" } = { [0] = "none", [1] = "background", [2] = "previous" } + +local function pixels(b: buffer, chunks: { { number } }, total: number, w: number, ht: number, depth: number, ct: number, interlace: number, pal: buffer, tr: number, out: buffer): Err.Err? + -- the inflated size: every (pass) row has a filter byte + local channels = Decode.CHANNELS[ct] + local expected = 0 + if interlace == 0 then + expected = ht * (Decode.rowBytes(w, channels, depth) + 1) + else + for _, pass in Decode.PASSES do + local x0, y0, dx, dy = pass[1], pass[2], pass[3], pass[4] + local pw = if w > x0 then (w - x0 + dx - 1) // dx else 0 + local ph = if ht > y0 then (ht - y0 + dy - 1) // dy else 0 + if pw > 0 and ph > 0 then + expected += ph * (Decode.rowBytes(pw, channels, depth) + 1) + end + end + end + local z: buffer + if #chunks == 1 then + z = b + else + z = buffer.create(total) + local w0 = 0 + for _, c in chunks do + buffer.copy(z, w0, b, c[1], c[2]) + w0 += c[2] + end + end + local zo = if #chunks == 1 then chunks[1][1] else 0 + local raw, zerr = Deflate.zlib(z, zo, total, expected) + if not raw then + -- some encoders leave extra bytes after the rows: inflate without the exact size, keep the rows + local loose = Deflate.zlib(z, zo, total) + if not loose or buffer.len(loose) < expected then + return zerr or Err.new(Err.CORRUPT, "bad image data") + end + raw = loose + end + local ok, derr = Decode.run(raw :: buffer, w, ht, depth, ct, interlace, pal, tr, out) + if not ok then + return Err.new(Err.CORRUPT, tostring(derr)) + end + return nil +end + +function Png.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local checkCrc = opts and opts.checkCrc or false + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + local h, herr = header(r) + if not h then + return nil, herr + end + local w, ht, depth, ct = h.width, h.height, h.bitDepth, h.colorType + if w * ht > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, ht, maxPixels)) + end + local b, n = r.buf, r.limit + local pal = buffer.create(1024) + for i = 0, 255 do + buffer.writeu32(pal, i * 4, 0xFF000000) -- out-of-range indexes: opaque black + end + local palCount = 0 + local tr = -1 + local idat: { { number } } = {} + local idatLen = 0 + local text: { [string]: string } = {} + local iccCompressed: buffer? = nil + -- APNG: acTL, then fcTL (+ IDAT for frame 1 when it is the default image) / fdAT, one sequence counter + local plays: number? = nil + local fctls: { FrameControl } = {} + local seq = 0 + local idatInAnim = false + local animPixels = 0 + local p = r.base + 8 + local first = true + 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 + if checkCrc then + local want = be32(b, d + len) + if Crc32.raw(b, p + 4, len + 4) ~= want then + return nil, Err.new(Err.CHECKSUM, "CRC mismatch in chunk " .. typ, d + len) + end + end + if first and typ ~= "IHDR" then + return nil, Err.new(Err.CORRUPT, "IHDR is not the first chunk", p) + end + first = false + if typ == "PLTE" then + if len % 3 ~= 0 or len > 768 or len == 0 then + return nil, Err.new(Err.CORRUPT, "bad PLTE length", p) + end + palCount = len // 3 + for i = 0, palCount - 1 do + local q = d + i * 3 + buffer.writeu32(pal, i * 4, readu8(b, q) + readu8(b, q + 1) * 256 + readu8(b, q + 2) * 65536 + 0xFF000000) + end + elseif typ == "tRNS" then + if ct == 3 then + for i = 0, math.min(len, 256) - 1 do + buffer.writeu8(pal, i * 4 + 3, readu8(b, d + i)) + end + elseif ct == 0 and len >= 2 then + tr = readu8(b, d) * 256 + readu8(b, d + 1) + elseif ct == 2 and len >= 6 then + local function u16(q: number): number + return readu8(b, d + q) * 256 + readu8(b, d + q + 1) + end + tr = u16(0) * 4294967296 + u16(2) * 65536 + u16(4) + end + elseif typ == "IDAT" then + table.insert(idat, { d, len }) + idatLen += len + if #fctls == 1 and #idat == 1 then + idatInAnim = true + end + elseif typ == "tEXt" then + local s = buffer.readstring(b, d, len) + local z = string.find(s, "\0", 1, true) + if z then + text[string.sub(s, 1, z - 1)] = string.sub(s, z + 1) + end + elseif typ == "iCCP" then + local cb = buffer.create(len) + buffer.copy(cb, 0, b, d, len) + iccCompressed = cb + elseif typ == "acTL" then + if len >= 8 and plays == nil and #idat == 0 then + plays = be32(b, d + 4) + end + elseif typ == "fcTL" and plays ~= nil then + if len < 26 then + return nil, Err.new(Err.CORRUPT, "short fcTL", p) + end + if be32(b, d) ~= seq then + return nil, Err.new(Err.CORRUPT, string.format("fcTL sequence %d, expected %d", be32(b, d), seq), p) + end + seq += 1 + local f: FrameControl = { + width = be32(b, d + 4), + height = be32(b, d + 8), + x = be32(b, d + 12), + y = be32(b, d + 16), + num = readu8(b, d + 20) * 256 + readu8(b, d + 21), + den = readu8(b, d + 22) * 256 + readu8(b, d + 23), + dispose = readu8(b, d + 24), + blend = readu8(b, d + 25), + chunks = {}, + len = 0, + } + if f.width == 0 or f.height == 0 or f.x + f.width > w or f.y + f.height > ht then + return nil, Err.new(Err.CORRUPT, "fcTL frame outside the image", p) + end + if f.dispose > 2 or f.blend > 1 then + return nil, Err.new(Err.CORRUPT, "bad fcTL dispose / blend op", p) + end + if #idat == 0 and (f.width ~= w or f.height ~= ht or f.x ~= 0 or f.y ~= 0) then + return nil, Err.new(Err.CORRUPT, "the fcTL before IDAT must cover the image", p) + end + animPixels += f.width * f.height + if animPixels > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("the animation frames are over the %d pixel limit", maxPixels)) + end + table.insert(fctls, f) + elseif typ == "fdAT" and plays ~= nil then + if len < 4 then + return nil, Err.new(Err.CORRUPT, "short fdAT", p) + end + if be32(b, d) ~= seq then + return nil, Err.new(Err.CORRUPT, string.format("fdAT sequence %d, expected %d", be32(b, d), seq), p) + end + seq += 1 + local f = fctls[#fctls] + if not f or (#fctls == 1 and idatInAnim) then + return nil, Err.new(Err.CORRUPT, "fdAT without its fcTL", p) + end + table.insert(f.chunks, { d + 4, len - 4 }) + f.len += len - 4 + elseif typ == "IEND" then + break -- a missing IEND is tolerated (truncated tail after the data) + 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 + end + if #idat == 0 then + return nil, Err.new(Err.TRUNCATED, "no image data", p) + end + if ct == 3 and palCount == 0 then + return nil, Err.new(Err.CORRUPT, "palette image without PLTE") + end + local img = Types.Image.new(w, ht, "rgba8") + local ierr = pixels(b, idat, idatLen, w, ht, h.bitDepth, ct, h.interlace, pal, tr, img.pixels) + if ierr then + return nil, ierr + end + if plays ~= nil and #fctls > 0 then + local last = fctls[#fctls] + if #fctls > 1 and #last.chunks == 0 then + fctls[#fctls] = nil -- a truncated file: the last frame never got its data + end + local frames: { Types.Frame } = {} + for i, f in fctls do + local fimg: Types.Image + if i == 1 and idatInAnim then + fimg = Types.Image.new(w, ht, "rgba8") + buffer.copy(fimg.pixels, 0, img.pixels) + else + if #f.chunks == 0 then + return nil, Err.new(Err.CORRUPT, "APNG frame " .. i .. " has no data") + end + fimg = Types.Image.new(f.width, f.height, "rgba8") + local ferr = pixels(b, f.chunks, f.len, f.width, f.height, h.bitDepth, ct, h.interlace, pal, tr, fimg.pixels) + if ferr then + ferr.message = "frame " .. i .. ": " .. ferr.message + return nil, ferr + end + end + frames[i] = { + image = fimg, + delay = f.num / (if f.den == 0 then 100 else f.den), + x = f.x, + y = f.y, + dispose = DISPOSE[f.dispose] :: any, + blend = if f.blend == 1 then "over" :: "over" else "source" :: "source", + } + end + img.frames = frames + img.loops = plays + img.meta.apngDefaultHidden = not idatInAnim + end + if ct == 3 then + local palette: { { number } } = {} + for i = 0, palCount - 1 do + palette[i + 1] = { readu8(pal, i * 4), readu8(pal, i * 4 + 1), readu8(pal, i * 4 + 2), readu8(pal, i * 4 + 3) } + end + img.meta.palette = palette + end + if next(text) then + img.meta.text = text + end + img.meta.iccCompressed = iccCompressed + img.meta.source = { format = "png", bitDepth = depth, colorType = COLOR_NAMES[ct], interlace = h.interlace } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local CT_CODES = { gray = 0, rgb = 2, graya = 4, rgba = 6 } +local DISPOSE_CODES: { [string]: number } = { none = 0, background = 1, previous = 2 } +local BLEND_CODES: { [string]: number } = { source = 0, over = 1 } + +local function delayFraction(delay: number): (number, number) + for den = 1, 1000 do + local num = math.floor(delay * den + 0.5) + if num > 65535 then + break + end + if math.abs(num / den - delay) < 1e-9 then + return num, den + end + end + if delay * 1000 <= 65535 then + return math.floor(delay * 1000 + 0.5), 1000 + elseif delay * 100 <= 65535 then + return math.floor(delay * 100 + 0.5), 100 + end + return math.min(65535, math.floor(delay + 0.5)), 1 +end + +local function validImage(im: any): boolean + return type(im) == "table" + and im.format == "rgba8" + and type(im.pixels) == "buffer" + and type(im.width) == "number" + and type(im.height) == "number" + and im.width >= 1 + and im.height >= 1 + and im.width % 1 == 0 + and im.height % 1 == 0 + and buffer.len(im.pixels) >= im.width * im.height * 4 +end + +local function animationFrames(img: Types.Image, opts: EncodeOptions?): ({ Types.Frame }?, Err.Err?) + local frames = img.frames + local mode = if opts then opts.apng else nil + if mode == false then + return nil, nil + end + if frames ~= nil and type(frames) ~= "table" then + return nil, Err.new(Err.ARG, "frames must be a list") + end + if frames == nil or #frames == 0 then + if mode then + return { { image = img, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" } :: any }, nil + end + return nil, nil + end + for i, f in frames do + local label = "png encode: frame " .. i + if type(f) ~= "table" or not validImage(f.image) then + return nil, Err.new(Err.ARG, label .. ": needs an rgba8 image") + end + local x, y = f.x or 0, f.y or 0 + if type(x) ~= "number" or type(y) ~= "number" or x < 0 or y < 0 or x % 1 ~= 0 or y % 1 ~= 0 or x + f.image.width > img.width or y + f.image.height > img.height then + return nil, Err.new(Err.ARG, label .. ": rectangle outside the image") + end + if f.delay ~= nil and (type(f.delay) ~= "number" or not (f.delay >= 0)) then + return nil, Err.new(Err.ARG, label .. ": bad delay") + end + if f.dispose ~= nil and DISPOSE_CODES[f.dispose] == nil then + return nil, Err.new(Err.ARG, label .. ": bad dispose " .. tostring(f.dispose)) + end + if f.blend ~= nil and BLEND_CODES[f.blend] == nil then + return nil, Err.new(Err.ARG, label .. ": bad blend " .. tostring(f.blend)) + end + end + return frames, nil +end + +function Png.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if not validImage(img) then + 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, "level must be 0..9") + end + local frames, ferr = animationFrames(img, opts) + if ferr then + return nil, ferr + 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, "loops must be an integer 0..2^32-1") + end + local want = opts and opts.colorType or "auto" + local ctName: string = want + if want == "auto" then + local alpha, color = false, false + local function scan(im: Types.Image) + local c = Encode.pickColorType(im.pixels, im.width, im.height) + alpha = alpha or c == "rgba" or c == "graya" + color = color or c == "rgba" or c == "rgb" + end + scan(img) + if frames then + for _, f in frames do + scan(f.image) + end + end + ctName = if color then (if alpha then "rgba" else "rgb") else (if alpha then "graya" else "gray") + end + local ct = CT_CODES[ctName] + if ct == nil then + 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 + end + + local out = Bytes.writer(w * h + 128) + local function chunk(typ: string, data: buffer?, prefix: number?) + local len = (if data then buffer.len(data) else 0) + (if prefix then 4 else 0) + out:u32be(len) + local start = out:tell() + out:string(typ) + if prefix then + out:u32be(prefix) + end + if data then + out:bytes(data) + end + out:u32be(Crc32.raw(out.buf, start, len + 4)) + end + out:string(SIGNATURE) + local ihdr = Bytes.writer(13) + ihdr:u32be(w) + ihdr:u32be(h) + ihdr:u8(8) + ihdr:u8(ct) + ihdr:u8(0) + ihdr:u8(0) + ihdr:u8(0) + chunk("IHDR", ihdr:finish()) + if frames then + local actl = Bytes.writer(8) + actl:u32be(#frames) + actl:u32be(loops) + chunk("acTL", actl:finish()) + end + if img.meta and img.meta.text then + for k, v in img.meta.text do + local t = Bytes.writer() + t:string(k) + t:u8(0) + t:string(v) + chunk("tEXt", t:finish()) + end + end + if not frames then + chunk("IDAT", zdata(img)) + chunk("IEND", nil) + return out:finish(), nil + end + -- frame 1 is the default image when it covers the canvas with the same pixels; otherwise the default image is + -- written first, outside the animation + local f1 = frames[1] + local f1i = f1.image + local inAnim = f1i == img + or ((f1.x or 0) == 0 and (f1.y or 0) == 0 and f1i.width == w and f1i.height == h and buffer.len(f1i.pixels) >= w * h * 4 and buffer.readstring(f1i.pixels, 0, w * h * 4) == buffer.readstring(img.pixels, 0, w * h * 4)) + local seq = 0 + if not inAnim then + chunk("IDAT", zdata(img)) + end + for i, f in frames do + local fi = f.image + local num, den = delayFraction(f.delay or 0) + local fc = Bytes.writer(26) + fc:u32be(seq) + fc:u32be(fi.width) + fc:u32be(fi.height) + fc:u32be(f.x or 0) + fc:u32be(f.y or 0) + fc:u16be(num) + fc:u16be(den) + fc:u8(DISPOSE_CODES[f.dispose or "none"]) + fc:u8(BLEND_CODES[f.blend or "source"]) + chunk("fcTL", fc:finish()) + seq += 1 + if i == 1 and inAnim then + chunk("IDAT", zdata(img)) + else + chunk("fdAT", zdata(fi), seq) + seq += 1 + end + end + chunk("IEND", nil) + return out:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +function Png.composite(img: Types.Image): ({ Types.Image }?, Err.Err?) + if not validImage(img) then + return nil, Err.new(Err.ARG, "composite: needs an rgba8 Image") + end + local frames, ferr = animationFrames(img, { apng = true }) + if not frames then + return nil, ferr + end + local w, h = img.width, img.height + local list = {} + for i, f in frames do + list[i] = { image = f.image, x = f.x or 0, y = f.y or 0, dispose = f.dispose or "none", blend = f.blend or "source" } + end + local out = {} + for i, b in Apng.composite(w, h, list) do + local im = Types.Image.new(w, h, "rgba8") + im.pixels = b + out[i] = im + end + return out, nil +end + +return Png +end +__FILES["image/png/Apng"] = @native function() + + + +-- image/png/Apng: APNG 1.0 dispose / blend compositing; "over" uses ffmpeg pngdec.c's integer arithmetic (byte-exact). +local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32 +local bcreate, bcopy, bfill = buffer.create, buffer.copy, buffer.fill + +local Apng = {} + +@native local function div255(x: number): number + return (x + 128) * 257 // 65536 +end + +@native local function blend(canvas: buffer, cw: number, src: buffer, fw: number, fh: number, fx: number, fy: number, over: boolean) + for y = 0, fh - 1 do + local so = y * fw * 4 + local co = ((fy + y) * cw + fx) * 4 + if not over then + bcopy(canvas, co, src, so, fw * 4) + else + for x = 0, fw - 1 do + local s, c = so + x * 4, co + x * 4 + local fa = readu8(src, s + 3) + if fa == 255 then + writeu32(canvas, c, readu32(src, s)) + elseif fa ~= 0 then + local ba = readu8(canvas, c + 3) + local oa = fa + div255((255 - fa) * ba) + if ba == 255 then + for k = 0, 2 do + writeu8(canvas, c + k, div255(fa * readu8(src, s + k) + (255 - fa) * readu8(canvas, c + k))) + end + else + local den = 255 * oa + for k = 0, 2 do + writeu8(canvas, c + k, (255 * fa * readu8(src, s + k) + (255 - fa) * ba * readu8(canvas, c + k)) // den) + end + end + writeu8(canvas, c + 3, oa) + end + end + end + end +end + +@native function Apng.composite(w: number, h: number, frames: { any }): { buffer } + local canvas = bcreate(w * h * 4) + local saved = bcreate(w * h * 4) + local out: { buffer } = {} + for i, f in frames do + local fi = f.image + local fw, fh = fi.width, fi.height + local dispose, over = f.dispose, f.blend == "over" + if i == 1 then + over = false -- the canvas starts transparent black: source and over differ only in hidden colour + if dispose == "previous" then + dispose = "background" + end + end + if dispose == "previous" then + bcopy(saved, 0, canvas, 0) + end + blend(canvas, w, fi.pixels, fw, fh, f.x, f.y, over) + local snap = bcreate(w * h * 4) + bcopy(snap, 0, canvas, 0) + out[i] = snap + if dispose == "background" then + for y = 0, fh - 1 do + bfill(canvas, ((f.y + y) * w + f.x) * 4, 0, fw * 4) + end + elseif dispose == "previous" then + bcopy(canvas, 0, saved, 0) + end + end + return out +end + +return Apng +end +__FILES["image/png/Decode"] = @native function() + + + +-- image/png/Decode: PNG unfiltering and expansion to RGBA8 (absorbed from png-luau src/Png/Decode.luau, same author). +local band, rshift, lshift = bit32.band, bit32.rshift, bit32.lshift +local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32 +local bcopy = buffer.copy + +local Decode = {} + +-- Adam7: x0, y0, dx, dy per pass +local PASSES = { + { 0, 0, 8, 8 }, + { 4, 0, 8, 8 }, + { 0, 4, 4, 8 }, + { 2, 0, 4, 4 }, + { 0, 2, 2, 4 }, + { 1, 0, 2, 2 }, + { 0, 1, 1, 2 }, +} +Decode.PASSES = PASSES + +local CHANNELS = { [0] = 1, [2] = 3, [3] = 1, [4] = 2, [6] = 4 } +Decode.CHANNELS = CHANNELS + +@native function Decode.rowBytes(pw: number, channels: number, depth: number): number + return (pw * channels * depth + 7) // 8 +end + +@native local function unfilter(raw: buffer, p: number, ph: number, rb: number, bpp: number): (boolean, number) + local stride = rb + 1 + for r = 0, ph - 1 do + local f = readu8(raw, p) + local cur = p + 1 + if f == 0 then + elseif f == 1 then + for i = cur + bpp, cur + rb - 1 do + writeu8(raw, i, readu8(raw, i) + readu8(raw, i - bpp)) + end + elseif f == 2 then + if r > 0 then + local i = cur + local e4 = cur + rb - 4 + while i <= e4 do + local x, y = readu32(raw, i), readu32(raw, i - stride) + local lo = band(x, 0x7F7F7F7F) + band(y, 0x7F7F7F7F) + writeu32(raw, i, bit32.bxor(lo, band(bit32.bxor(x, y), 0x80808080))) + i += 4 + end + while i < cur + rb do + writeu8(raw, i, readu8(raw, i) + readu8(raw, i - stride)) + i += 1 + end + end + elseif f == 3 then + if r > 0 then + for i = cur, cur + bpp - 1 do + writeu8(raw, i, readu8(raw, i) + rshift(readu8(raw, i - stride), 1)) + end + for i = cur + bpp, cur + rb - 1 do + writeu8(raw, i, readu8(raw, i) + rshift(readu8(raw, i - bpp) + readu8(raw, i - stride), 1)) + end + else + for i = cur + bpp, cur + rb - 1 do + writeu8(raw, i, readu8(raw, i) + rshift(readu8(raw, i - bpp), 1)) + end + end + elseif f == 4 then + if r > 0 then + -- the first pixel: a = c = 0, so Paeth picks b + for i = cur, cur + bpp - 1 do + writeu8(raw, i, readu8(raw, i) + readu8(raw, i - stride)) + end + for i = cur + bpp, cur + rb - 1 do + local a = readu8(raw, i - bpp) + local b = readu8(raw, i - stride) + local c = readu8(raw, i - stride - bpp) + local pa = math.abs(b - c) + local pb = math.abs(a - c) + local pc = math.abs(a + b - c - c) + local v + if pa <= pb and pa <= pc then + v = a + elseif pb <= pc then + v = b + else + v = c + end + writeu8(raw, i, readu8(raw, i) + v) + end + else + -- no previous row: Paeth is sub + for i = cur + bpp, cur + rb - 1 do + writeu8(raw, i, readu8(raw, i) + readu8(raw, i - bpp)) + end + end + else + return false, f + end + p += stride + end + return true, 0 +end + +@native local function convert(raw: buffer, ro: number, pw: number, out: buffer, oo: number, ostep: number, ct: number, depth: number, pal: buffer, tr: number) + if ct == 6 then + if depth == 8 then + if ostep == 4 then + bcopy(out, oo, raw, ro, pw * 4) + else + for x = 0, pw - 1 do + writeu32(out, oo + x * ostep, readu32(raw, ro + x * 4)) + end + end + else + for x = 0, pw - 1 do + local s = ro + x * 8 + local o = oo + x * ostep + writeu8(out, o, readu8(raw, s)) + writeu8(out, o + 1, readu8(raw, s + 2)) + writeu8(out, o + 2, readu8(raw, s + 4)) + writeu8(out, o + 3, readu8(raw, s + 6)) + end + end + elseif ct == 2 then + if depth == 8 then + for x = 0, pw - 1 do + local s = ro + x * 3 + local r, g, b = readu8(raw, s), readu8(raw, s + 1), readu8(raw, s + 2) + local a = 255 + if tr >= 0 and r * 4294967296 + g * 65536 + b == tr then + a = 0 + end + writeu32(out, oo + x * ostep, r + g * 256 + b * 65536 + a * 16777216) + end + else + for x = 0, pw - 1 do + local s = ro + x * 6 + local r = readu8(raw, s) * 256 + readu8(raw, s + 1) + local g = readu8(raw, s + 2) * 256 + readu8(raw, s + 3) + local b = readu8(raw, s + 4) * 256 + readu8(raw, s + 5) + local a = 255 + if tr >= 0 and r * 4294967296 + g * 65536 + b == tr then + a = 0 + end + writeu32(out, oo + x * ostep, rshift(r, 8) + band(g, 0xFF00) + lshift(rshift(b, 8), 16) + a * 16777216) + end + end + elseif ct == 3 then + if depth == 8 then + for x = 0, pw - 1 do + writeu32(out, oo + x * ostep, readu32(pal, readu8(raw, ro + x) * 4)) + end + else + local per = 8 // depth + local mask = lshift(1, depth) - 1 + for x = 0, pw - 1 do + local byte = readu8(raw, ro + x // per) + local idx = band(rshift(byte, 8 - depth - (x % per) * depth), mask) + writeu32(out, oo + x * ostep, readu32(pal, idx * 4)) + end + end + elseif ct == 0 then + if depth == 8 then + for x = 0, pw - 1 do + local v = readu8(raw, ro + x) + local a = if v == tr then 0 else 255 + writeu32(out, oo + x * ostep, v * 0x10101 + a * 16777216) + end + elseif depth == 16 then + for x = 0, pw - 1 do + local hi = readu8(raw, ro + x * 2) + local v = hi * 256 + readu8(raw, ro + x * 2 + 1) + local a = if v == tr then 0 else 255 + writeu32(out, oo + x * ostep, hi * 0x10101 + a * 16777216) + end + else + local per = 8 // depth + local mask = lshift(1, depth) - 1 + local scale = 255 // mask + for x = 0, pw - 1 do + local byte = readu8(raw, ro + x // per) + local v = band(rshift(byte, 8 - depth - (x % per) * depth), mask) + local a = if v == tr then 0 else 255 + writeu32(out, oo + x * ostep, v * scale * 0x10101 + a * 16777216) + end + end + else -- ct == 4: grey + alpha + if depth == 8 then + for x = 0, pw - 1 do + local v, a = readu8(raw, ro + x * 2), readu8(raw, ro + x * 2 + 1) + writeu32(out, oo + x * ostep, v * 0x10101 + a * 16777216) + end + else + for x = 0, pw - 1 do + local v, a = readu8(raw, ro + x * 4), readu8(raw, ro + x * 4 + 2) + writeu32(out, oo + x * ostep, v * 0x10101 + a * 16777216) + end + end + end +end + +@native function Decode.run(raw: buffer, w: number, h: number, depth: number, ct: number, interlace: number, pal: buffer, tr: number, out: buffer): (boolean, string?) + local channels = CHANNELS[ct] + local bpp = math.max(1, (channels * depth) // 8) + local p = 0 + if interlace == 0 then + local rb = Decode.rowBytes(w, channels, depth) + local ok, f = unfilter(raw, 0, h, rb, bpp) + if not ok then + return false, "bad filter type " .. f + end + for y = 0, h - 1 do + convert(raw, y * (rb + 1) + 1, w, out, y * w * 4, 4, ct, depth, pal, tr) + end + return true, nil + end + for _, pass in PASSES do + local x0, y0, dx, dy = pass[1], pass[2], pass[3], pass[4] + local pw = if w > x0 then (w - x0 + dx - 1) // dx else 0 + local ph = if h > y0 then (h - y0 + dy - 1) // dy else 0 + if pw > 0 and ph > 0 then + local rb = Decode.rowBytes(pw, channels, depth) + local ok, f = unfilter(raw, p, ph, rb, bpp) + if not ok then + return false, "bad filter type " .. f + end + for r = 0, ph - 1 do + local y = y0 + r * dy + convert(raw, p + r * (rb + 1) + 1, pw, out, (y * w + x0) * 4, dx * 4, ct, depth, pal, tr) + end + p += ph * (rb + 1) + end + end + return true, nil +end + +return Decode +end +__FILES["image/png/Encode"] = @native function() + + + +-- image/png/Encode: PNG colour type choice and filtering (per-row minimum sum of |signed residuals|, as libpng). +local readu8, writeu8 = buffer.readu8, buffer.writeu8 +local bcreate, bcopy = buffer.create, buffer.copy + +local Encode = {} + +local CHANNELS = { [0] = 1, [2] = 3, [4] = 2, [6] = 4 } + +@native function Encode.pickColorType(px: buffer, w: number, h: number): string + local opaque, gray = true, true + for i = 0, w * h - 1 do + local o = i * 4 + local r, g, b, a = readu8(px, o), readu8(px, o + 1), readu8(px, o + 2), readu8(px, o + 3) + if a ~= 255 then + opaque = false + end + if r ~= g or g ~= b then + gray = false + end + if not opaque and not gray then + return "rgba" + end + end + if gray then + return if opaque then "gray" else "graya" + end + return "rgb" +end + +@native local function pack(px: buffer, w: number, h: number, ct: number): buffer + local ch = CHANNELS[ct] + if ch == 4 then + return px + end + local out = bcreate(w * h * ch) + local n = w * h + if ct == 2 then + for i = 0, n - 1 do + bcopy(out, i * 3, px, i * 4, 3) + end + elseif ct == 0 then + for i = 0, n - 1 do + writeu8(out, i, readu8(px, i * 4)) + end + else -- graya + for i = 0, n - 1 do + writeu8(out, i * 2, readu8(px, i * 4)) + writeu8(out, i * 2 + 1, readu8(px, i * 4 + 3)) + end + end + return out +end + +@native local function paeth(a: number, b: number, c: number): number + local pa = math.abs(b - c) + local pb = math.abs(a - c) + local pc = math.abs(a + b - c - c) + if pa <= pb and pa <= pc then + return a + elseif pb <= pc then + return b + end + return c +end + +@native local function costs(src: buffer, s: number, rb: number, bpp: number, first: boolean): (number, number, number, number, number) + local c0, c1, c2, c3, c4 = 0, 0, 0, 0, 0 + local p = s - rb + for i = 0, rb - 1 do + local x = readu8(src, s + i) + local a = if i >= bpp then readu8(src, s + i - bpp) else 0 + local b, c = 0, 0 + if not first then + b = readu8(src, p + i) + if i >= bpp then + c = readu8(src, p + i - bpp) + end + end + local d = if x < 128 then x else 256 - x + c0 += d + d = (x - a) % 256 + c1 += if d < 128 then d else 256 - d + d = (x - b) % 256 + c2 += if d < 128 then d else 256 - d + d = (x - (a + b) // 2) % 256 + c3 += if d < 128 then d else 256 - d + local pa, pb, pc = math.abs(b - c), math.abs(a - c), math.abs(a + b - c - c) + local pr = if pa <= pb and pa <= pc then a elseif pb <= pc then b else c + d = (x - pr) % 256 + c4 += if d < 128 then d else 256 - d + end + return c0, c1, c2, c3, c4 +end + +@native local function apply(src: buffer, s: number, rb: number, bpp: number, first: boolean, f: number, out: buffer, o: number) + writeu8(out, o, f) + o += 1 + if f == 0 or (f == 2 and first) then + bcopy(out, o, src, s, rb) + return + end + local p = s - rb + for i = 0, rb - 1 do + local x = readu8(src, s + i) + local a = if i >= bpp then readu8(src, s + i - bpp) else 0 + local pred + if f == 1 then + pred = a + elseif f == 2 then + pred = readu8(src, p + i) + elseif f == 3 then + pred = (a + (if first then 0 else readu8(src, p + i))) // 2 + elseif first then + pred = a + else + local c = if i >= bpp then readu8(src, p + i - bpp) else 0 + pred = paeth(a, readu8(src, p + i), c) + end + writeu8(out, o + i, x - pred) + end +end + +@native function Encode.filter(px: buffer, w: number, h: number, ct: number): buffer + local ch = CHANNELS[ct] + local src = pack(px, w, h, ct) + local rb = w * ch + local out = bcreate(h * (rb + 1)) + for y = 0, h - 1 do + local s = y * rb + local first = y == 0 + local c0, c1, c2, c3, c4 = costs(src, s, rb, ch, first) + local best, bc = 0, c0 + if c1 < bc then + best, bc = 1, c1 + end + if c2 < bc then + best, bc = 2, c2 + end + if c3 < bc then + best, bc = 3, c3 + end + if c4 < bc then + best = 4 + end + apply(src, s, rb, ch, first, best, out, y * (rb + 1)) + end + return out +end + +return Encode +end +end + + + + + + Deflate + --!optimize 2 +--!nocheck +-- rosetta chunk Deflate (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 3 modules (2 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["codecs/compress/Deflate"] = function() + +-- codecs/compress/Deflate: DEFLATE (RFC 1951) decoder and compressor, with zlib (RFC 1950) and gzip (RFC 1952). +-- Absorbed from deflate-luau 1.0.0 (same author; no third-party code); the compressor is new. +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Crc32 = __include("core/Crc32") +local Adler32 = __include("core/Adler32") +local Inflate = __include("codecs/compress/Deflate/Inflate") +local Compress = __include("codecs/compress/Deflate/Compress") + +local Deflate = {} + +Deflate.version = "1.1.0" + +local toBuffer = Bytes.toBuffer +local args = Bytes.span + +local function shrink(out: buffer, n: number): buffer + if buffer.len(out) == n then + return out + end + local b = buffer.create(n) + buffer.copy(b, 0, out, 0, n) + return b +end + +local function inflateErr(msg: string, at: number?): Err.Err + local code = if string.find(msg, "truncated", 1, true) then Err.TRUNCATED else Err.CORRUPT + return Err.new(code, "inflate: " .. msg, at) +end + +function Deflate.inflate(buf: buffer | string, offset: number?, length: number?, expectedSize: number?, dict: buffer?): (buffer?, any) + local b, o, l, aerr = args("Deflate.inflate", buf, offset, length) + if not b then + return nil, aerr + end + local exact = expectedSize ~= nil + local cap + if exact then + if type(expectedSize) ~= "number" or expectedSize < 0 or expectedSize % 1 ~= 0 then + return nil, Err.new(Err.ARG, "Deflate.inflate: bad expectedSize " .. tostring(expectedSize)) + end + cap = expectedSize + else + cap = math.max(1024, l * 4) + end + if dict ~= nil and type(dict) ~= "buffer" then + return nil, Err.new(Err.ARG, "Deflate.inflate: dict must be a buffer") + end + local out, n, consumed = Inflate.raw(b, o, o + l, cap :: number, exact, false, dict) + if not out then + return nil, inflateErr(tostring(n), o) + end + if dict then + local d = buffer.len(dict) + n -= d + local res = buffer.create(n) + buffer.copy(res, 0, out, d, n) + out = res + end + if exact and n ~= expectedSize then + return nil, Err.new(Err.CORRUPT, string.format("inflate: output is %d bytes, expected %d", n, expectedSize :: number)) + end + return shrink(out, n), consumed +end + +function Deflate.zlib(buf: buffer | string, offset: number?, length: number?, expectedSize: number?): (buffer?, any) + local b, o, l, aerr = args("Deflate.zlib", buf, offset, length) + if not b then + return nil, aerr + end + if l < 6 then + return nil, Err.new(Err.TRUNCATED, "zlib: truncated header", o) + end + local cmf, flg = buffer.readu8(b, o), buffer.readu8(b, o + 1) + if cmf % 16 ~= 8 or cmf // 16 > 7 then + return nil, Err.new(Err.CORRUPT, "zlib: not a deflate stream (CMF " .. cmf .. ")", o) + end + if (cmf * 256 + flg) % 31 ~= 0 then + return nil, Err.new(Err.CORRUPT, "zlib: header check failed", o) + end + if bit32.band(flg, 0x20) ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "zlib: preset dictionaries are not supported", o) + end + local out, consumed = Deflate.inflate(b, o + 2, l - 2, expectedSize) + if not out then + return nil, consumed + end + if consumed + 4 > o + l then + return nil, Err.new(Err.TRUNCATED, "zlib: missing Adler-32", consumed) + end + local want = bit32.byteswap(buffer.readu32(b, consumed)) + local got = Adler32.raw(out, 0, buffer.len(out)) + if got ~= want then + return nil, Err.new(Err.CHECKSUM, string.format("zlib: Adler-32 mismatch (%08x, expected %08x)", got, want), consumed) + end + return out, consumed + 4 +end + +local function gzipBody(b: buffer, p: number, e: number): (number?, Err.Err?) + local flg = buffer.readu8(b, p + 3) + if flg >= 0x20 then + return nil, Err.new(Err.CORRUPT, "gzip: reserved flags set", p + 3) + end + local q = p + 10 + if bit32.band(flg, 4) ~= 0 then -- FEXTRA + if q + 2 > e then + return nil, Err.new(Err.TRUNCATED, "gzip: truncated header", q) + end + q += 2 + buffer.readu16(b, q) + end + for _, bit in { 8, 16 } do -- FNAME, FCOMMENT: zero-terminated + if bit32.band(flg, bit) ~= 0 then + while q < e and buffer.readu8(b, q) ~= 0 do + q += 1 + end + q += 1 + end + end + if bit32.band(flg, 2) ~= 0 then -- FHCRC + q += 2 + end + if q >= e then + return nil, Err.new(Err.TRUNCATED, "gzip: truncated header", q) + end + return q, nil +end + +function Deflate.gunzip(buf: buffer | string, offset: number?, length: number?): (buffer?, Err.Err?) + local b, o, l, aerr = args("Deflate.gunzip", buf, offset, length) + if not b then + return nil, aerr + end + local e = o + l + local parts, total = {}, 0 + local p = o + repeat + if p + 18 > e then + if #parts > 0 then + break + end + return nil, Err.new(Err.TRUNCATED, "gzip: truncated member", p) + end + if buffer.readu8(b, p) ~= 0x1f or buffer.readu8(b, p + 1) ~= 0x8b then + if #parts > 0 then + break -- trailing garbage after a member: ignored, as gzip -d does + end + return nil, Err.new(Err.CORRUPT, "gzip: bad magic", p) + end + if buffer.readu8(b, p + 2) ~= 8 then + return nil, Err.new(Err.UNSUPPORTED, "gzip: unknown compression method", p + 2) + end + local q, herr = gzipBody(b, p, e) + if not q then + return nil, herr + end + local out, consumed = Deflate.inflate(b, q, e - q) + if not out then + return nil, consumed + end + if consumed + 8 > e then + return nil, Err.new(Err.TRUNCATED, "gzip: missing trailer", consumed) + end + local want, isize = buffer.readu32(b, consumed), buffer.readu32(b, consumed + 4) + local got = Crc32.raw(out, 0, buffer.len(out)) + if got ~= want then + return nil, Err.new(Err.CHECKSUM, string.format("gzip: CRC-32 mismatch (%08x, expected %08x)", got, want), consumed) + end + if buffer.len(out) % 4294967296 ~= isize then + return nil, Err.new(Err.CORRUPT, "gzip: length mismatch", consumed + 4) + end + table.insert(parts, out) + total += buffer.len(out) + p = consumed + 8 + local z = p + while z < e and buffer.readu8(b, z) == 0 do + z += 1 + end + if z == e then + break + end + until p >= e + if #parts == 1 then + return parts[1], nil + end + local res = buffer.create(total) + local w = 0 + for _, part in parts do + buffer.copy(res, w, part) + w += buffer.len(part) + end + return res, nil +end + +function Deflate.peek(buf: buffer | string, offset: number?, length: number?, n: number): (buffer?, Err.Err?) + local b, o, l, aerr = args("Deflate.peek", buf, offset, length) + if not b then + return nil, aerr + end + if type(n) ~= "number" or n < 1 then + return nil, Err.new(Err.ARG, "Deflate.peek: bad size " .. tostring(n)) + end + local e = o + l + local q = o + if l >= 18 and buffer.readu8(b, o) == 0x1f and buffer.readu8(b, o + 1) == 0x8b and buffer.readu8(b, o + 2) == 8 then + local herr + q, herr = gzipBody(b, o, e) + if not q then + return nil, herr + end + elseif l >= 6 then + local cmf, flg = buffer.readu8(b, o), buffer.readu8(b, o + 1) + if cmf % 16 == 8 and cmf // 16 <= 7 and (cmf * 256 + flg) % 31 == 0 and bit32.band(flg, 0x20) == 0 then + q = o + 2 + end + end + local out, k = Inflate.raw(b, q :: number, e, n, true, true) + if not out then + return nil, inflateErr(tostring(k), q) + end + return shrink(out, k), nil +end + +type CompressOptions = { + level: number?, +} + +local function level(opts: CompressOptions?): number? + local lv = if opts and opts.level ~= nil then opts.level else 6 + if type(lv) ~= "number" or lv < 0 or lv > 9 or lv % 1 ~= 0 then + return nil + end + return lv +end + +function Deflate.compress(buf: buffer | string, opts: CompressOptions?): (buffer?, Err.Err?) + local b = toBuffer(buf) + local lv = level(opts) + if not b or not lv then + return nil, Err.new(Err.ARG, "Deflate.compress: expected a buffer or a string and opts.level 0..9") + end + return Compress.raw(b, 0, buffer.len(b), lv), nil +end + +function Deflate.zlibCompress(buf: buffer | string, opts: CompressOptions?): (buffer?, Err.Err?) + local b = toBuffer(buf) + local lv = level(opts) + if not b or not lv then + return nil, Err.new(Err.ARG, "Deflate.zlibCompress: expected a buffer or a string and opts.level 0..9") + end + local raw = Compress.raw(b, 0, buffer.len(b), lv) + local n = buffer.len(raw) + local out = buffer.create(n + 6) + local flevel = if lv < 2 then 0 elseif lv < 6 then 1 elseif lv == 6 then 2 else 3 + local cmf = 0x78 + local flg = flevel * 64 + flg += 31 - (cmf * 256 + flg) % 31 + buffer.writeu8(out, 0, cmf) + buffer.writeu8(out, 1, flg) + buffer.copy(out, 2, raw, 0, n) + buffer.writeu32(out, n + 2, bit32.byteswap(Adler32.raw(b, 0, buffer.len(b)))) + return out, nil +end + +function Deflate.gzip(buf: buffer | string, opts: CompressOptions?): (buffer?, Err.Err?) + local b = toBuffer(buf) + local lv = level(opts) + if not b or not lv then + return nil, Err.new(Err.ARG, "Deflate.gzip: expected a buffer or a string and opts.level 0..9") + end + local raw = Compress.raw(b, 0, buffer.len(b), lv) + local n = buffer.len(raw) + local out = buffer.create(n + 18) + buffer.writestring(out, 0, "\31\139\8\0\0\0\0\0") + buffer.writeu8(out, 8, if lv >= 9 then 2 elseif lv <= 1 then 4 else 0) + buffer.writeu8(out, 9, 255) + buffer.copy(out, 10, raw, 0, n) + buffer.writeu32(out, n + 10, Crc32.raw(b, 0, buffer.len(b))) + buffer.writeu32(out, n + 14, buffer.len(b) % 4294967296) + return out, nil +end + +-- MSZIP (CAB folders, DirectX .x): each block is "CK" + a raw deflate stream using the previous block's output (up to +-- 32 KB) as its dictionary. +function Deflate.mszip(buf: buffer, blocks: { { offset: number, length: number, size: number } }): (buffer?, Err.Err?) + local total = 0 + for _, b in blocks do + if b.offset < 0 or b.length < 0 or b.offset + b.length > buffer.len(buf) or b.size < 0 then + return nil, Err.new(Err.ARG, "Deflate.mszip: block out of range") + end + total += b.size + end + local out = buffer.create(total) + local o = 0 + for _, b in blocks do + if b.length < 2 or buffer.readu16(buf, b.offset) ~= 0x4B43 then + return nil, Err.new(Err.CORRUPT, "mszip: block without its CK signature", b.offset) + end + local dict: buffer? = nil + if o > 0 then + local d = math.min(o, 32768) + dict = buffer.create(d) + buffer.copy(dict :: buffer, 0, out, o - d, d) + end + local part, err = Deflate.inflate(buf, b.offset + 2, b.length - 2, b.size, dict) + if not part then + return nil, err + end + buffer.copy(out, o, part, 0, b.size) + o += b.size + end + return out, nil +end + +Deflate.crc32 = function(buf: buffer | string, offset: number?, length: number?, crc: number?): number + local b = toBuffer(buf) or buffer.create(0) + return Crc32.of(b, offset, length, crc) +end +Deflate.adler32 = function(buf: buffer | string, offset: number?, length: number?, adler: number?): number + local b = toBuffer(buf) or buffer.create(0) + return Adler32.of(b, offset, length, adler) +end + +return Deflate +end +__FILES["codecs/compress/Deflate/Compress"] = @native function() + + + +-- codecs/compress/Deflate/Compress: a DEFLATE (RFC 1951) compressor: hash-chain LZ77 over a 32 KB window, then per +-- block the cheapest of stored / fixed / dynamic Huffman, as zlib's levels. +local Huffman = __include("codecs/entropy/Huffman") + +local readu8, writeu8, writeu16 = buffer.readu8, buffer.writeu8, buffer.writeu16 +local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len +local floor = math.floor + +local WSIZE = 32768 +local HSIZE = 65536 +local MAXMATCH = 258 +local BLOCKSYMS = 16384 + +-- zlib's configuration_table: GOOD quarters the chain for the lazy search, LAZY = no lazy search after a match this +-- long, NICE = stop searching at this length, CHAIN = max chain steps; levels 1-3 are greedy. +local GOOD = { 4, 4, 4, 4, 8, 8, 8, 32, 32 } +local LAZY = { 0, 0, 0, 4, 16, 16, 32, 128, 258 } +local NICE = { 8, 16, 32, 16, 32, 128, 128, 258, 258 } +local CHAIN = { 4, 8, 32, 16, 32, 128, 256, 1024, 4096 } + +-- length 3..258 -> code 257..285 (index len), its extra bits and base +local LCODE, LEXTRA, LBASEOF = table.create(259, 0), table.create(259, 0), table.create(259, 0) +local LBASE = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258 } +local LEXT = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 } +for c = 1, 29 do + local base = LBASE[c] + local top = if c == 29 then 258 elseif c == 28 then 257 else LBASE[c + 1] - 1 + for len = base, top do + LCODE[len] = 256 + c + LEXTRA[len] = LEXT[c] + LBASEOF[len] = base + end +end +local DBASE = { + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, + 6145, 8193, 12289, 16385, 24577, +} +local DEXT = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 } +-- distance -> code (0..29): direct for 1..256, by (d - 1) // 128 above +local DSMALL, DLARGE = table.create(257, 0), table.create(257, 0) +for c = 1, 30 do + local base = DBASE[c] + local top = if c == 30 then 32768 else DBASE[c + 1] - 1 + for d = base, math.min(top, 256) do + DSMALL[d] = c - 1 + end + if top > 256 then + for k = math.max(base, 257), top, 128 do + DLARGE[(k - 1) // 128 + 1] = c - 1 + end + end +end +@native local function dcode(d: number): number + if d <= 256 then + return DSMALL[d] + end + return DLARGE[(d - 1) // 128 + 1] +end + +local CLORDER = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 } + +local FIXLEN = table.create(288, 0) +for i = 1, 288 do + FIXLEN[i] = if i <= 144 then 8 elseif i <= 256 then 9 elseif i <= 280 then 7 else 8 +end +local FIXDLEN = table.create(30, 5) + +@native local function revCodes(lens: { number }): { number } + local codes = Huffman.codes(lens) + for i, l in lens do + if l > 0 then + codes[i] = Huffman.reverse(codes[i], l) + end + end + return codes +end +local FIXCODE = revCodes(FIXLEN) +local FIXDCODE = revCodes(FIXDLEN) + +local POW = table.create(33, 0) +for i = 0, 32 do + POW[i + 1] = 2 ^ i +end + +type Out = { buf: buffer, op: number, acc: number, cnt: number } + +@native local function ensure(o: Out, n: number) + if o.op + n > blen(o.buf) then + local nb = bcreate(math.max(blen(o.buf) * 2, o.op + n)) + bcopy(nb, 0, o.buf, 0, o.op) + o.buf = nb + end +end + +@native local function put(o: Out, v: number, n: number) + local acc = o.acc + v * POW[o.cnt + 1] + local cnt = o.cnt + n + if cnt >= 8 then + ensure(o, 4) + local buf, op = o.buf, o.op + while cnt >= 8 do + local byte = acc % 256 + writeu8(buf, op, byte) + op += 1 + acc = (acc - byte) / 256 + cnt -= 8 + end + o.op = op + end + o.acc, o.cnt = acc, cnt +end + +@native local function alignOut(o: Out) + if o.cnt > 0 then + put(o, 0, 8 - o.cnt) + end +end + +@native local function storedBlock(o: Out, src: buffer, s: number, e: number, final: boolean) + local p = s + repeat + local n = math.min(65535, e - p) + local last = final and p + n >= e + put(o, if last then 1 else 0, 3) + alignOut(o) + ensure(o, 4 + n) + writeu16(o.buf, o.op, n) + writeu16(o.buf, o.op + 2, 65535 - n) + bcopy(o.buf, o.op + 4, src, p, n) + o.op += 4 + n + p += n + until p >= e +end + +@native local function emitSymbols(o: Out, L: { number }, D: { number }, nsym: number, lcode: { number }, llen: { number }, dcodes: { number }, dlen: { number }) + for i = 1, nsym do + local l = L[i] + if l < 256 then + put(o, lcode[l + 1], llen[l + 1]) + else + local len = l - 256 + local c = LCODE[len] + put(o, lcode[c + 1], llen[c + 1]) + local xb = LEXTRA[len] + if xb > 0 then + put(o, len - LBASEOF[len], xb) + end + local d = D[i] + local dc = dcode(d) + put(o, dcodes[dc + 1], dlen[dc + 1]) + xb = DEXT[dc + 1] + if xb > 0 then + put(o, d - DBASE[dc + 1], xb) + end + end + end + put(o, lcode[257], llen[257]) -- end of block +end + +@native local function block(o: Out, src: buffer, s: number, e: number, L: { number }, D: { number }, nsym: number, final: boolean) + local lf = table.create(286, 0) + local df = table.create(30, 0) + local extra = 0 + for i = 1, nsym do + local l = L[i] + if l < 256 then + lf[l + 1] += 1 + else + local len = l - 256 + lf[LCODE[len] + 1] += 1 + extra += LEXTRA[len] + local dc = dcode(D[i]) + df[dc + 1] += 1 + extra += DEXT[dc + 1] + end + end + lf[257] = 1 + local llen = Huffman.lengths(lf, 15) + local dlen = Huffman.lengths(df, 15) + local hlit = 286 + while hlit > 257 and llen[hlit] == 0 do + hlit -= 1 + end + local hdist = 30 + while hdist > 1 and dlen[hdist] == 0 do + hdist -= 1 + end + if dlen[1] == 0 and hdist == 1 then + dlen[1] = 1 -- at least one distance code (a lone 1-bit code, as zlib writes) + end + -- code-length symbols: RLE of the hlit + hdist lengths + local all = table.create(hlit + hdist, 0) + for i = 1, hlit do + all[i] = llen[i] + end + for i = 1, hdist do + all[hlit + i] = dlen[i] + end + local cs, cx = {}, {} + local cf = table.create(19, 0) + local i = 1 + local total = hlit + hdist + while i <= total do + local v = all[i] + local run = 1 + while i + run <= total and all[i + run] == v do + run += 1 + end + if v == 0 and run >= 3 then + local r = math.min(run, 138) + if r >= 11 then + table.insert(cs, 18) + table.insert(cx, r - 11) + cf[19] += 1 + else + table.insert(cs, 17) + table.insert(cx, r - 3) + cf[18] += 1 + end + i += r + elseif v ~= 0 and run >= 4 then + table.insert(cs, v) + table.insert(cx, 0) + cf[v + 1] += 1 + local r = math.min(run - 1, 6) + table.insert(cs, 16) + table.insert(cx, r - 3) + cf[17] += 1 + i += 1 + r + else + table.insert(cs, v) + table.insert(cx, 0) + cf[v + 1] += 1 + i += 1 + end + end + local clen = Huffman.lengths(cf, 7) + local hclen = 19 + while hclen > 4 and clen[CLORDER[hclen] + 1] == 0 do + hclen -= 1 + end + local dyn = 17 + 3 * hclen + extra + for k = 1, 19 do + dyn += cf[k] * clen[k] + end + dyn += cf[17] * 2 + cf[18] * 3 + cf[19] * 7 + local fix = 3 + extra + for k = 1, 286 do + dyn += lf[k] * llen[k] + fix += lf[k] * FIXLEN[k] + end + for k = 1, 30 do + dyn += df[k] * dlen[k] + fix += df[k] * 5 + end + local stored = (e - s) * 8 + 40 * (floor((e - s) / 65535) + 1) + 7 + if stored <= dyn and stored <= fix then + storedBlock(o, src, s, e, final) + return + end + if fix <= dyn then + put(o, if final then 3 else 2, 3) + emitSymbols(o, L, D, nsym, FIXCODE, FIXLEN, FIXDCODE, FIXDLEN) + return + end + put(o, if final then 5 else 4, 3) + put(o, hlit - 257, 5) + put(o, hdist - 1, 5) + put(o, hclen - 4, 4) + for k = 1, hclen do + put(o, clen[CLORDER[k] + 1], 3) + end + local ccode = revCodes(clen) + for k = 1, #cs do + local c = cs[k] + put(o, ccode[c + 1], clen[c + 1]) + if c == 16 then + put(o, cx[k], 2) + elseif c == 17 then + put(o, cx[k], 3) + elseif c == 18 then + put(o, cx[k], 7) + end + end + emitSymbols(o, L, D, nsym, revCodes(llen), llen, revCodes(dlen), dlen) +end + +local Compress = {} + +@native function Compress.raw(src: buffer, off: number, len: number, level: number): buffer + local o: Out = { buf = bcreate(math.max(64, len // 2 + 64)), op = 0, acc = 0, cnt = 0 } + local e = off + len + if level == 0 or len == 0 then + if len == 0 then + put(o, 3, 3) -- one empty fixed block + put(o, 0, 7) + else + storedBlock(o, src, off, e, true) + end + alignOut(o) + local out = bcreate(o.op) + bcopy(out, 0, o.buf, 0, o.op) + return out + end + local maxChain = CHAIN[level] + local nice = NICE[level] + local good = GOOD[level] + local lazyMax = LAZY[level] + local head = table.create(HSIZE, -1) + local prev = table.create(WSIZE, -1) + local L = table.create(BLOCKSYMS, 0) + local D = table.create(BLOCKSYMS, 0) + local nsym = 0 + local blockStart = off + + @native local function hash(p: number): number + return ((readu8(src, p) * 251 + readu8(src, p + 1)) * 251 + readu8(src, p + 2)) % HSIZE + end + @native local function insert(p: number) + local h = hash(p) + 1 + prev[p % WSIZE + 1] = head[h] + head[h] = p + end + @native local function find(p: number, steps: number): (number, number) + local maxLen = math.min(MAXMATCH, e - p) + if maxLen < 3 then + return 0, 0 + end + local best, bestDist = 2, 0 + local c = head[hash(p) + 1] + local limit = p - WSIZE + while c >= 0 and c > limit and steps > 0 do + if readu8(src, c + best) == readu8(src, p + best) and readu8(src, c) == readu8(src, p) then + local k = 1 + while k < maxLen and readu8(src, c + k) == readu8(src, p + k) do + k += 1 + end + if k > best then + best, bestDist = k, p - c + if k >= nice or k >= maxLen then + break + end + end + end + local nc = prev[c % WSIZE + 1] + if nc >= c then + break + end + c = nc + steps -= 1 + end + if best < 3 then + return 0, 0 + end + return best, bestDist + end + @native local function flush(upto: number, final: boolean) + block(o, src, blockStart, upto, L, D, nsym, final) + nsym = 0 + blockStart = upto + end + + local p = off + local stop3 = e - 3 + while p < e do + local mlen, mdist = 0, 0 + if p <= stop3 then + mlen, mdist = find(p, maxChain) + insert(p) + if mlen >= 3 and mlen < lazyMax and p + 1 <= stop3 then + local l2, d2 = find(p + 1, if mlen >= good then maxChain // 4 else maxChain) + if l2 > mlen then + nsym += 1 + L[nsym] = readu8(src, p) + D[nsym] = 0 + p += 1 + insert(p) + mlen, mdist = l2, d2 + end + end + end + if mlen >= 3 then + nsym += 1 + L[nsym] = 256 + mlen + D[nsym] = mdist + local q = p + 1 + local qe = math.min(p + mlen, stop3 + 1) + while q < qe do + insert(q) + q += 1 + end + p += mlen + else + nsym += 1 + L[nsym] = readu8(src, p) + D[nsym] = 0 + p += 1 + end + if nsym >= BLOCKSYMS - 2 then + flush(p, p >= e) + end + end + if nsym > 0 or blockStart < e then + flush(e, true) + elseif blockStart == e and o.op == 0 and o.cnt == 0 then + put(o, 3, 3) + put(o, 0, 7) + end + alignOut(o) + local out = bcreate(o.op) + bcopy(out, 0, o.buf, 0, o.op) + return out +end + +return Compress +end +__FILES["codecs/compress/Deflate/Inflate"] = @native function() + + + +-- 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). +local Huffman = __include("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 +local bcreate, bcopy, bfill, blen = buffer.create, buffer.copy, buffer.fill, buffer.len + +local LITBITS, DISTBITS, CLBITS = 10, 8, 7 +local LITMASK, DISTMASK, CLMASK = 1023, 255, 127 + +-- RFC 1951 3.2.5: length codes 257..285 and distance codes 0..29: base value, extra bits +local LBASE = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258 } +local LEXT = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 } +local DBASE = { + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, + 6145, 8193, 12289, 16385, 24577, +} +local DEXT = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 } +-- RFC 1951 3.2.7: the order the code-length code lengths are sent in +local CLORDER = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 } + +local LITCAP = Huffman.capacity(288, LITBITS, 15) +local DISTCAP = Huffman.capacity(32, DISTBITS, 15) +local CLCAP = Huffman.capacity(19, CLBITS, 7) + +local FLIT, FDIST = bcreate(LITCAP * 4), bcreate(DISTCAP * 4) +local FLITS: number, FDISTS: number +do + local l = bcreate(288) + bfill(l, 0, 8, 144) + bfill(l, 144, 9, 112) + bfill(l, 256, 7, 24) + bfill(l, 280, 8, 8) + FLITS = Huffman.buildLsb(l, 0, 288, FLIT, LITBITS) + local d = bcreate(30) + bfill(d, 0, 5, 30) + FDISTS = Huffman.buildLsb(d, 0, 30, FDIST, DISTBITS) +end + +local Inflate = {} + +@native local function grow(out: buffer, op: number, need: number): (buffer, number) + local cap = math.max(blen(out) * 2, need, 1024) + local nb = bcreate(cap) + bcopy(nb, 0, out, 0, op) + return nb, cap +end + +@native function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, exact: boolean, prefix: boolean?, dict: buffer?): (buffer?, any, number?) + local op = 0 + if dict then + op = blen(dict) + cap += op + end + local out = bcreate(cap) + if dict then + bcopy(out, 0, dict, 0, op) + end + local pos = start + local bitbuf, bitcnt, over = 0, 0, 0 + local lt, dt = bcreate(LITCAP * 4), bcreate(DISTCAP * 4) :: buffer + local clt = bcreate(CLCAP * 4) + local lens = bcreate(320) + local final = 0 + repeat + -- block header (3 bits); also up to 14 bits of a dynamic header + if bitcnt < 17 then + if pos + 4 <= endpos then + bitbuf = bor(bitbuf, lshift(readu32(src, pos), bitcnt)) + local nb = rshift(32 - bitcnt, 3) + pos += nb + bitcnt += nb * 8 + else + while bitcnt <= 24 do + if pos < endpos then + bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt)) + pos += 1 + else + over += 1 + if over > 4 then + return nil, "truncated input" + end + end + bitcnt += 8 + end + end + end + final = band(bitbuf, 1) + local btype = band(rshift(bitbuf, 1), 3) + bitbuf = rshift(bitbuf, 3) + bitcnt -= 3 + if btype == 0 then + -- stored: skip to the byte boundary, give back the whole bytes still in the bit buffer + local k = band(bitcnt, 7) + bitcnt -= k + local real = rshift(bitcnt, 3) - over + if real < 0 then + return nil, "truncated input" + end + pos -= real + bitbuf, bitcnt, over = 0, 0, 0 + if pos + 4 > endpos then + return nil, "truncated input" + end + local n = readu16(src, pos) + if n ~= bxor(readu16(src, pos + 2), 0xFFFF) then + return nil, "stored block length mismatch" + end + pos += 4 + if pos + n > endpos then + return nil, "truncated input" + end + if op + n > cap then + if exact then + if prefix then + return out, op, pos + end + return nil, "output larger than expected" + end + out, cap = grow(out, op, op + n) + end + bcopy(out, op, src, pos, n) + op += n + pos += n + continue + end + 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) :: buffer + end + local hlit = band(bitbuf, 31) + 257 + local hdist = band(rshift(bitbuf, 5), 31) + 1 + local hclen = band(rshift(bitbuf, 10), 15) + 4 + bitbuf = rshift(bitbuf, 14) + bitcnt -= 14 + if hlit > 286 or hdist > 30 then + return nil, "too many length or distance symbols" + end + bfill(lens, 0, 0, 19) + for i = 1, hclen do + if bitcnt < 3 then + if pos + 4 <= endpos then + bitbuf = bor(bitbuf, lshift(readu32(src, pos), bitcnt)) + local nb = rshift(32 - bitcnt, 3) + pos += nb + bitcnt += nb * 8 + else + while bitcnt <= 24 do + if pos < endpos then + bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt)) + pos += 1 + else + over += 1 + if over > 4 then + return nil, "truncated input" + end + end + bitcnt += 8 + end + end + end + writeu8(lens, CLORDER[i], band(bitbuf, 7)) + bitbuf = rshift(bitbuf, 3) + bitcnt -= 3 + end + if Huffman.buildLsb(lens, 0, 19, clt, CLBITS) < 0 then + return nil, "invalid code lengths set" + end + local total = hlit + hdist + local i = 0 + while i < total do + if bitcnt < 14 then + if pos + 4 <= endpos then + bitbuf = bor(bitbuf, lshift(readu32(src, pos), bitcnt)) + local nb = rshift(32 - bitcnt, 3) + pos += nb + bitcnt += nb * 8 + else + while bitcnt <= 24 do + if pos < endpos then + bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt)) + pos += 1 + else + over += 1 + if over > 4 then + return nil, "truncated input" + end + end + bitcnt += 8 + end + end + end + local e = readu32(clt, band(bitbuf, CLMASK) * 4) + local l = band(e, 31) + if l == 0 then + return nil, "invalid code lengths set" + end + bitbuf = rshift(bitbuf, l) + bitcnt -= l + local sym = rshift(e, 5) + if sym < 16 then + writeu8(lens, i, sym) + i += 1 + else + local rep, val + if sym == 16 then + if i == 0 then + return nil, "repeat with no first length" + end + val = readu8(lens, i - 1) + rep = 3 + band(bitbuf, 3) + bitbuf = rshift(bitbuf, 2) + bitcnt -= 2 + elseif sym == 17 then + val = 0 + rep = 3 + band(bitbuf, 7) + bitbuf = rshift(bitbuf, 3) + bitcnt -= 3 + else + val = 0 + rep = 11 + band(bitbuf, 127) + bitbuf = rshift(bitbuf, 7) + bitcnt -= 7 + end + if i + rep > total then + return nil, "too many code lengths" + end + bfill(lens, i, val, rep) + i += rep + end + end + if readu8(lens, 256) == 0 then + return nil, "missing end-of-block code" + end + lsub = Huffman.buildLsb(lens, 0, hlit, lt, LITBITS) + dsub = Huffman.buildLsb(lens, hlit, hdist, dt, DISTBITS) + if lsub < 0 or dsub < 0 then + return nil, "invalid literal/length or distance code set" + end + else + return nil, "invalid block type" + end + local lsmask = lshift(1, lsub) - 1 + local dsmask = lshift(1, dsub) - 1 + while true do + if bitcnt < 15 then + if pos + 4 <= endpos then + bitbuf = bor(bitbuf, lshift(readu32(src, pos), bitcnt)) + local nb = rshift(32 - bitcnt, 3) + pos += nb + bitcnt += nb * 8 + else + while bitcnt <= 24 do + if pos < endpos then + bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt)) + pos += 1 + else + over += 1 + if over > 4 then + return nil, "truncated input" + end + end + bitcnt += 8 + end + end + end + local e = readu32(lt, band(bitbuf, LITMASK) * 4) + local l = band(e, 31) + if l == 0 then + if e == 0 then + return nil, "invalid literal/length code" + end + e = readu32(lt, (rshift(e, 5) + band(rshift(bitbuf, LITBITS), lsmask)) * 4) + l = band(e, 31) + if l == 0 then + return nil, "invalid literal/length code" + end + end + bitbuf = rshift(bitbuf, l) + bitcnt -= l + local sym = rshift(e, 5) + if sym < 256 then + if op >= cap then + if exact then + if prefix then + return out, op, pos + end + return nil, "output larger than expected" + end + out, cap = grow(out, op, op + 1) + end + writeu8(out, op, sym) + op += 1 + elseif sym == 256 then + break + else + sym -= 256 + if sym > 29 then + return nil, "invalid literal/length code" + end + if bitcnt < 20 then + if pos + 4 <= endpos then + bitbuf = bor(bitbuf, lshift(readu32(src, pos), bitcnt)) + local nb = rshift(32 - bitcnt, 3) + pos += nb + bitcnt += nb * 8 + else + while bitcnt <= 24 do + if pos < endpos then + bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt)) + pos += 1 + else + over += 1 + if over > 4 then + return nil, "truncated input" + end + end + bitcnt += 8 + end + end + end + local len = LBASE[sym] + local xb = LEXT[sym] + if xb > 0 then + len += band(bitbuf, lshift(1, xb) - 1) + bitbuf = rshift(bitbuf, xb) + bitcnt -= xb + end + e = readu32(dt, band(bitbuf, DISTMASK) * 4) + l = band(e, 31) + if l == 0 then + if e == 0 then + return nil, "invalid distance code" + end + e = readu32(dt, (rshift(e, 5) + band(rshift(bitbuf, DISTBITS), dsmask)) * 4) + l = band(e, 31) + if l == 0 then + return nil, "invalid distance code" + end + end + bitbuf = rshift(bitbuf, l) + bitcnt -= l + local dsym = rshift(e, 5) + 1 + if dsym > 30 then + return nil, "invalid distance code" + end + local dist = DBASE[dsym] + xb = DEXT[dsym] + if xb > 0 then + if bitcnt < 13 then + if pos + 4 <= endpos then + bitbuf = bor(bitbuf, lshift(readu32(src, pos), bitcnt)) + local nb = rshift(32 - bitcnt, 3) + pos += nb + bitcnt += nb * 8 + else + while bitcnt <= 24 do + if pos < endpos then + bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt)) + pos += 1 + else + over += 1 + if over > 4 then + return nil, "truncated input" + end + end + bitcnt += 8 + end + end + end + dist += band(bitbuf, lshift(1, xb) - 1) + bitbuf = rshift(bitbuf, xb) + bitcnt -= xb + end + if dist > op then + return nil, "invalid distance too far back" + end + if op + len > cap then + if exact then + if prefix then + return out, op, pos + end + return nil, "output larger than expected" + end + out, cap = grow(out, op, op + len) + end + local s = op - dist + if dist >= len then + if len <= 16 and op + 16 <= cap then + -- straight-line 16-byte copy for simple LuaJIT traces; it reads only bytes before op or already copied ones + writeu32(out, op, readu32(out, s)) + writeu32(out, op + 4, readu32(out, s + 4)) + writeu32(out, op + 8, readu32(out, s + 8)) + writeu32(out, op + 12, readu32(out, s + 12)) + elseif len <= 16 then + for k = 0, len - 1 do + writeu8(out, op + k, readu8(out, s + k)) + end + else + bcopy(out, op, out, s, len) + end + op += len + elseif dist == 1 then + bfill(out, op, readu8(out, s), len) + op += len + else + local rem = len + while rem > 0 do + local k = math.min(op - s, rem) + bcopy(out, op, out, s, k) + op += k + rem -= k + end + end + end + end + until final == 1 + local consumed = pos + over - rshift(bitcnt, 3) + if consumed > endpos then + return nil, "truncated input" + end + return out, op, consumed +end + +return Inflate +end +end + + + + + + Brotli + --!optimize 2 +--!nocheck +-- rosetta chunk Brotli (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 3 modules (1 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["codecs/compress/Brotli"] = function() + +-- codecs/compress/Brotli: Brotli (RFC 7932) decompression, with the large-window extension. +-- 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). +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Crc32 = __include("core/Crc32") +local Base64 = __include("core/Base64") +local Deflate = __include("codecs/compress/Deflate") +local Decode = __include("codecs/compress/Brotli/Decode") +local StaticData = __include("codecs/compress/Brotli/Static") + +local Brotli = {} + +type Options = { + maxBytes: number?, + largeWindow: boolean?, +} + +-- the tables are base64 text (trusted, generated by tools/brotli_static.py) +local function unbase64(s: string): buffer + return Base64.decode(s) or buffer.create(0) +end + +local static: Decode.Static? = nil + +local function tables(): (Decode.Static?, Err.Err?) + if static then + return static, nil + end + local z = unbase64(table.concat(StaticData.dictionary)) + local dict, err = Deflate.zlib(z, 0, nil, StaticData.dictionarySize) + if not dict then + return nil, err + end + if Crc32.of(dict) ~= StaticData.dictionaryCrc then + return nil, Err.new(Err.CHECKSUM, "brotli: static dictionary damaged") + end + static = { + dictionary = dict, + context = unbase64(table.concat(StaticData.context)), + prefixSuffix = unbase64(StaticData.prefixSuffix), + prefixSuffixMap = StaticData.prefixSuffixMap, + transforms = StaticData.transforms, + } + return static, nil +end + +function Brotli.dictionary(): buffer? + local s = tables() + return if s then s.dictionary else nil +end + +function Brotli.decompress(buf: buffer | string, offset: number?, length: number?, opts: Options?): (buffer?, any) + local b, o, l, aerr = Bytes.span("Brotli.decompress", buf, offset, length) + if not b then + return nil, aerr + end + 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") + end + local large = not (opts and opts.largeWindow == false) + if l == 0 then + return nil, Err.new(Err.TRUNCATED, "brotli: empty input", o) + end + local S, serr = tables() + if not S then + return nil, serr + end + local out, size, consumed = Decode.decompress(b, o, l, maxBytes, S, large) + if not out then + local e = Err.from(size, o) + e.message = "brotli: " .. e.message + return nil, e + end + local res = out + if buffer.len(out) ~= size then + res = buffer.create(size) + buffer.copy(res, 0, out, 0, size) + end + return res, consumed +end + +return Brotli +end +__FILES["codecs/compress/Brotli/Decode"] = @native function() + + + +-- codecs/compress/Brotli/Decode: a Brotli (RFC 7932) decoder, with the large-window extension (windows 10..30). +-- Written from the RFC, with google/brotli c/dec/decode.c (MIT) as the authority on edge cases. +-- Prefix table entry: symbol * 32 + length (length < 16), or a link offset * 32 + 16 + subtable bits (8-bit primary). +local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift +local readu8, readu16, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu32 +local bcreate, bcopy, blen, bfill = buffer.create, buffer.copy, buffer.len, buffer.fill + +local Decode = {} + +type Static = { + dictionary: buffer, -- 122784 bytes + context: buffer, -- 2048 bytes: 4 modes x (256 for p1, 256 for p2) + prefixSuffix: buffer, -- length-prefixed strings + prefixSuffixMap: { number }, + transforms: { number }, -- 121 x (prefix id, type, suffix id) +} + +local CL_ORDER = { 1, 2, 3, 4, 0, 5, 17, 6, 16, 7, 8, 9, 10, 11, 12, 13, 14, 15 } +local CLP_LEN = { 2, 2, 2, 3, 2, 2, 2, 4, 2, 2, 2, 3, 2, 2, 2, 4 } +local CLP_VAL = { 0, 4, 3, 2, 0, 4, 3, 1, 0, 4, 3, 2, 0, 4, 3, 5 } +local BL_OFF = { + 1, 5, 9, 13, 17, 25, 33, 41, 49, 65, 81, 97, 113, 145, 177, 209, 241, 305, 369, 497, 753, 1265, 2289, 4337, 8433, 16625, +} +local BL_BITS = { 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 7, 8, 9, 10, 11, 12, 13, 24 } +local INS_BASE = { 0, 1, 2, 3, 4, 5, 6, 8, 10, 14, 18, 26, 34, 50, 66, 98, 130, 194, 322, 578, 1090, 2114, 6210, 22594 } +local INS_EXTRA = { 0, 0, 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 7, 8, 9, 10, 12, 14, 24 } +local CPY_BASE = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 18, 22, 30, 38, 54, 70, 102, 134, 198, 326, 582, 1094, 2118 } +local CPY_EXTRA = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 7, 8, 9, 10, 24 } +local CELL_INS = { 0, 0, 0, 0, 8, 8, 0, 16, 8, 16, 16 } +local CELL_CPY = { 0, 8, 0, 8, 0, 8, 16, 0, 16, 8, 16 } +-- static dictionary: bits of the word index per word length 0..24 (index + 1), and the offsets +local NDBITS = { 0, 0, 0, 0, 10, 10, 11, 11, 10, 10, 10, 10, 10, 9, 9, 8, 7, 7, 8, 7, 7, 6, 6, 5, 5 } +local DOFF = table.create(25, 0) +do + local o = 0 + for l = 4, 24 do + DOFF[l + 1] = o + o += l * 2 ^ NDBITS[l + 1] + end +end +local NTRANSFORMS = 121 +local MAX_ALLOWED_DISTANCE = 0x7FFFFFFC + +local REV8 = bcreate(256) +for i = 0, 255 do + local r, v = 0, i + for _ = 1, 8 do + r = r * 2 + v % 2 + v = v // 2 + end + writeu8(REV8, i, r) +end +@native local function reverse(code: number, len: number): number + local r = readu8(REV8, band(code, 255)) * 256 + readu8(REV8, band(rshift(code, 8), 255)) + return rshift(r, 16 - len) +end + +local count = table.create(16, 0) +local nextc = table.create(16, 0) +local subBits = table.create(256, 0) +local subOff = table.create(256, 0) + +@native local function prepare(lens: buffer, n: number): number + for l = 1, 16 do + count[l] = 0 + end + local used = 0 + for s = 0, n - 1 do + local l = readu8(lens, s) + if l > 0 then + count[l] += 1 + used += 1 + end + end + if used <= 1 then + return 256 + end + local left = 1 + for l = 1, 15 do + left = left * 2 - count[l] + if left < 0 then + return -1 + end + end + -- canonical codes: the first code of length l is (first(l - 1) + count(l - 1)) * 2 + local code = 0 + for l = 1, 15 do + nextc[l] = code + code = (code + count[l]) * 2 + end + for i = 1, 256 do + subBits[i] = 0 + end + local nc = table.clone(nextc) + for s = 0, n - 1 do + local l = readu8(lens, s) + if l > 8 then + local c = nc[l] + nc[l] = c + 1 + local pre = band(reverse(c, l), 255) + local k = l - 8 + if k > subBits[pre + 1] then + subBits[pre + 1] = k + end + elseif l > 0 then + nc[l] += 1 + end + end + local size = 256 + for i = 1, 256 do + local k = subBits[i] + if k > 0 then + subOff[i] = size + size += lshift(1, k) + end + end + return size +end + +@native local function build(lens: buffer, n: number, T: buffer, at: number) + local single = -1 + local used = 0 + for s = 0, n - 1 do + if readu8(lens, s) > 0 then + used += 1 + single = s + end + end + if used <= 1 then + local e = (if single < 0 then 0 else single) * 32 + for i = 0, 255 do + writeu32(T, (at + i) * 4, e) + end + return + end + for i = 1, 256 do + local k = subBits[i] + if k > 0 then + writeu32(T, (at + i - 1) * 4, subOff[i] * 32 + 16 + k) + end + end + for s = 0, n - 1 do + local l = readu8(lens, s) + if l > 0 then + local c = nextc[l] + nextc[l] = c + 1 + local rev = reverse(c, l) + local e = s * 32 + l + if l <= 8 then + local step = lshift(1, l) + local i = rev + while i < 256 do + writeu32(T, (at + i) * 4, e) + i += step + end + else + local pre = band(rev, 255) + local sb = subBits[pre + 1] + local base = at + subOff[pre + 1] + local step = lshift(1, l - 8) + local i = rshift(rev, 8) + local lim = lshift(1, sb) + while i < lim do + writeu32(T, (base + i) * 4, e) + i += step + end + end + end + end +end + +-- largest distance alphabet under MAX_ALLOWED_DISTANCE, as the reference's BrotliCalculateDistanceCodeLimit +@native local function distanceLimit(maxDistance: number, npostfix: number, ndirect: number): number + if maxDistance <= ndirect then + return maxDistance + 16 + end + local offset = maxDistance + 1 - ndirect - 1 + offset = rshift(offset, npostfix) + 4 + local ndistbits = 0 + local tmp = offset // 2 + while tmp ~= 0 do + ndistbits += 1 + tmp = rshift(tmp, 1) + end + ndistbits -= 1 + local half = band(rshift(offset, ndistbits), 1) + local group = bor(lshift(ndistbits - 1, 1), half) + if group == 0 then + return ndirect + 16 + end + group -= 1 + local postfix = lshift(1, npostfix) - 1 + return bor(lshift(group, npostfix), postfix) + ndirect + 16 + 1 +end + +@native function Decode.decompress(src: buffer, off: number, len: number, maxBytes: number, S: Static, largeWindow: boolean): (buffer?, any, number?) + local lim = off + len + local ip = off + local bb, bc = 0, 0 + + @native local function fill() + while bc <= 24 do + local byte = 0 + if ip < lim then + byte = readu8(src, ip) + end + ip += 1 + bb = bor(bb, lshift(byte, bc)) + bc += 8 + end + end + @native local function bits(n: number): number + if bc < n then + fill() + end + local v = band(bb, lshift(1, n) - 1) + bb = rshift(bb, n) + bc -= n + return v + end + @native local function bitsLong(n: number): number + if n <= 24 then + return bits(n) + end + local lo = bits(16) + return lo + bits(n - 16) * 65536 + end + @native local function overrun(): boolean + return (ip - lim) * 8 > bc + end + + local T = bcreate(4096 * 4) + local tpos = 0 + local LENS = bcreate(1128) + local CLL = bcreate(18) + local CLT = bcreate(256 * 4) + + @native local function decodeSym(base: number): number + if bc < 15 then + fill() + end + local e = readu32(T, (base + band(bb, 255)) * 4) + local l = band(e, 31) + if l >= 16 then + e = readu32(T, (base + rshift(e, 5) + band(rshift(bb, 8), lshift(1, l - 16) - 1)) * 4) + l = band(e, 31) + end + bb = rshift(bb, l) + bc -= l + return rshift(e, 5) + end + + @native local function install(n: number): number + local size = prepare(LENS, n) + if size < 0 then + return -1 + end + local need = (tpos + size) * 4 + if need > blen(T) then + local nt = bcreate(math.max(blen(T) * 2, need)) + bcopy(nt, 0, T, 0, tpos * 4) + T = nt + end + build(LENS, n, T, tpos) + local base = tpos + tpos += size + return base + end + + @native local function readCode(alphabetMax: number, limit: number): number + bfill(LENS, 0, 0, limit) + local hskip = bits(2) + if hskip == 1 then + local nsym = bits(2) + 1 + local maxBits = 0 + local x = alphabetMax - 1 + while x > 0 do + maxBits += 1 + x = rshift(x, 1) + end + local s1, s2, s3, s4 = -1, -1, -1, -1 + for i = 1, nsym do + local v = bits(maxBits) + if v >= limit then + return -1 + end + if i == 1 then + s1 = v + elseif i == 2 then + s2 = v + elseif i == 3 then + s3 = v + else + s4 = v + end + end + if nsym >= 2 and (s1 == s2 or s1 == s3 or s1 == s4 or (nsym >= 3 and (s2 == s3 or s2 == s4)) or (nsym == 4 and s3 == s4)) then + return -1 + end + if nsym == 1 then + writeu8(LENS, s1, 1) + elseif nsym == 2 then + writeu8(LENS, s1, 1) + writeu8(LENS, s2, 1) + elseif nsym == 3 then + writeu8(LENS, s1, 1) + writeu8(LENS, s2, 2) + writeu8(LENS, s3, 2) + else + if bits(1) == 0 then + writeu8(LENS, s1, 2) + writeu8(LENS, s2, 2) + writeu8(LENS, s3, 2) + writeu8(LENS, s4, 2) + else + writeu8(LENS, s1, 1) + writeu8(LENS, s2, 2) + writeu8(LENS, s3, 3) + writeu8(LENS, s4, 3) + end + end + return install(limit) + end + -- complex: the code length code + bfill(CLL, 0, 0, 18) + local space, num = 32, 0 + for i = hskip + 1, 18 do + if bc < 4 then + fill() + end + local ix = band(bb, 15) + local v = CLP_VAL[ix + 1] + local dl = CLP_LEN[ix + 1] + bb = rshift(bb, dl) + bc -= dl + writeu8(CLL, CL_ORDER[i], v) + if v ~= 0 then + space -= rshift(32, v) + num += 1 + if space <= 0 then + break + end + end + end + if not (num == 1 or space == 0) then + return -1 + end + -- its table (lengths <= 5) + do + local size = prepare(CLL, 18) + if size ~= 256 then + return -1 + end + build(CLL, 18, CLT, 0) + end + -- the symbol code lengths + local sym, prev, rep, repLen = 0, 8, 0, 0 + space = 32768 + while sym < limit and space > 0 do + if bc < 15 then + fill() + end + local e = readu32(CLT, band(bb, 255) * 4) + local l = band(e, 31) + bb = rshift(bb, l) + bc -= l + local cl = rshift(e, 5) + if cl < 16 then + rep = 0 + writeu8(LENS, sym, cl) + if cl ~= 0 then + prev = cl + space -= rshift(32768, cl) + end + sym += 1 + else + local extra = if cl == 16 then 2 else 3 + local d = bits(extra) + local newLen = if cl == 16 then prev else 0 + if repLen ~= newLen then + rep = 0 + repLen = newLen + end + local old = rep + if rep > 0 then + rep = (rep - 2) * lshift(1, extra) + end + rep += d + 3 + local delta = rep - old + if sym + delta > limit then + return -1 + end + if repLen ~= 0 then + bfill(LENS, sym, repLen, delta) + space -= delta * rshift(32768, repLen) + end + sym += delta + end + if overrun() then + return -1 + end + end + if space ~= 0 then + return -1 + end + return install(limit) + end + + @native local function varLen8(): number + if bits(1) == 0 then + return 0 + end + local n = bits(3) + if n == 0 then + return 1 + end + return bits(n) + lshift(1, n) + end + + @native local function blockLen(base: number): number + local code = decodeSym(base) + return BL_OFF[code + 1] + bits(BL_BITS[code + 1]) + end + + @native local function readContextMap(size: number): (number, buffer) + local ntrees = varLen8() + 1 + local map = bcreate(size) + if ntrees < 2 then + return ntrees, map + end + local rleMax = 0 + if bits(1) == 1 then + rleMax = bits(4) + 1 + end + local base = readCode(ntrees + rleMax, ntrees + rleMax) + if base < 0 then + return -1, map + end + local i = 0 + while i < size do + local code = decodeSym(base) + if code == 0 then + i += 1 + elseif code > rleMax then + writeu8(map, i, code - rleMax) + i += 1 + else + local reps = lshift(1, code) + bits(code) + if i + reps > size then + return -1, map + end + i += reps + end + if overrun() then + return -1, map + end + end + if bits(1) == 1 then -- inverse move-to-front + local mtf = table.create(256, 0) + for k = 1, 256 do + mtf[k] = k - 1 + end + for k = 0, size - 1 do + local idx = readu8(map, k) + local v = mtf[idx + 1] + writeu8(map, k, v) + if idx > 0 then + table.move(mtf, 1, idx, 2) + mtf[1] = v + end + end + end + return ntrees, map + end + + -- RFC 7932 9.1: stream header + fill() + local wbits + local large = false + if bits(1) == 0 then + wbits = 16 + else + local n = bits(3) + if n ~= 0 then + wbits = 17 + n + else + local m = bits(3) + if m == 1 then + if not largeWindow then + return nil, "unsupported: large-window brotli (pass opts.largeWindow = true)" + end + if bits(1) == 1 then + return nil, "bad window bits" + end + large = true + wbits = bits(6) + if wbits < 10 or wbits > 30 then + return nil, "bad large window bits" + end + elseif m ~= 0 then + wbits = 8 + m + else + wbits = 17 + end + end + end + local maxBackward = 2 ^ wbits - 16 + + local dict = S.dictionary + local LUT = S.context + local PS = S.prefixSuffix + local PSMAP = S.prefixSuffixMap + local TRANS = S.transforms + local WORD = bcreate(64) + + local out = bcreate(math.max(256, math.min(len * 4, maxBytes))) + local op = 0 + -- distance ring buffer: last, second, third, fourth + local d0, d1, d2, d3 = 4, 11, 15, 16 + + while true do + -- RFC 7932 9.2: meta-block header + if overrun() then + return nil, "truncated stream" + end + local isLast = bits(1) == 1 + if isLast and bits(1) == 1 then + break -- ISLASTEMPTY + end + local mn = bits(2) + local mlen = 0 + if mn == 3 then + -- metadata + if bits(1) ~= 0 then + return nil, "reserved bit set" + end + local nbytes = bits(2) + for i = 0, nbytes - 1 do + local b = bits(8) + if i + 1 == nbytes and nbytes > 1 and b == 0 then + return nil, "exuberant metadata length byte" + end + mlen += b * 2 ^ (8 * i) + end + if nbytes > 0 then + mlen += 1 + end + local pad = band(bc, 7) + if pad > 0 and bits(pad) ~= 0 then + return nil, "nonzero padding" + end + ip -= rshift(bc, 3) + bb, bc = 0, 0 + if ip + mlen > lim then + return nil, "truncated metadata" + end + ip += mlen + if isLast then + break + end + continue + end + local nib = mn + 4 + for i = 0, nib - 1 do + local v = bits(4) + if i + 1 == nib and nib > 4 and v == 0 then + return nil, "exuberant nibble" + end + mlen += v * 2 ^ (4 * i) + end + mlen += 1 + local uncompressed = false + if not isLast then + uncompressed = bits(1) == 1 + end + if op + mlen > maxBytes then + return nil, "limit: output over " .. maxBytes .. " bytes" + end + if op + mlen + 8 > blen(out) then + local nb = bcreate(math.min(math.max(blen(out) * 2, op + mlen + 8), maxBytes + 8)) + bcopy(nb, 0, out, 0, op) + out = nb + end + if uncompressed then + local pad = band(bc, 7) + if pad > 0 and bits(pad) ~= 0 then + return nil, "nonzero padding" + end + ip -= rshift(bc, 3) + bb, bc = 0, 0 + if ip + mlen > lim then + return nil, "truncated uncompressed block" + end + bcopy(out, op, src, ip, mlen) + ip += mlen + op += mlen + if isLast then + break + end + continue + end + + -- RFC 7932 9.3: compressed meta-block data + tpos = 0 + -- block types / counts: 1 = literals, 2 = commands, 3 = distances + local nbtL, nbtI, nbtD = 1, 1, 1 + local btTreeL, btTreeI, btTreeD = 0, 0, 0 + local blTreeL, blTreeI, blTreeD = 0, 0, 0 + local cntL, cntI, cntD = 1073741824, 1073741824, 1073741824 + for c = 1, 3 do + local nbt = varLen8() + 1 + local btt, blt, cnt = 0, 0, 1073741824 + if nbt >= 2 then + btt = readCode(nbt + 2, nbt + 2) + if btt < 0 then + return nil, "bad block type code" + end + blt = readCode(26, 26) + if blt < 0 then + return nil, "bad block count code" + end + cnt = blockLen(blt) + end + if c == 1 then + nbtL, btTreeL, blTreeL, cntL = nbt, btt, blt, cnt + elseif c == 2 then + nbtI, btTreeI, blTreeI, cntI = nbt, btt, blt, cnt + else + nbtD, btTreeD, blTreeD, cntD = nbt, btt, blt, cnt + end + end + if overrun() then + return nil, "truncated meta-block header" + end + local npostfix = bits(2) + local ndirect = lshift(bits(4), npostfix) + local postMask = lshift(1, npostfix) - 1 + local modes = table.create(nbtL, 0) + for i = 1, nbtL do + modes[i] = bits(2) + end + local ntreesL, cmapL = readContextMap(64 * nbtL) + if ntreesL < 0 then + return nil, "bad literal context map" + end + local ntreesD, cmapD = readContextMap(4 * nbtD) + if ntreesD < 0 then + return nil, "bad distance context map" + end + local litBase = table.create(ntreesL, 0) + for i = 1, ntreesL do + local b = readCode(256, 256) + if b < 0 then + return nil, "bad literal code" + end + litBase[i] = b + end + local cmdBase = table.create(nbtI, 0) + for i = 1, nbtI do + local b = readCode(704, 704) + if b < 0 then + return nil, "bad insert-and-copy code" + end + cmdBase[i] = b + end + local distMax = 16 + ndirect + lshift(if large then 62 else 24, npostfix + 1) + local distLimit = if large then distanceLimit(MAX_ALLOWED_DISTANCE, npostfix, ndirect) else distMax + local distBase = table.create(ntreesD, 0) + for i = 1, ntreesD do + local b = readCode(distMax, distLimit) + if b < 0 then + return nil, "bad distance code" + end + distBase[i] = b + end + if overrun() then + return nil, "truncated meta-block header" + end + local litMap = table.create(64 * nbtL, 0) + for i = 0, 64 * nbtL - 1 do + litMap[i + 1] = litBase[readu8(cmapL, i) + 1] + end + local distMap = table.create(4 * nbtD, 0) + for i = 0, 4 * nbtD - 1 do + distMap[i + 1] = distBase[readu8(cmapD, i) + 1] + end + + local typeL, prevL = 0, 1 + local typeI, prevI = 0, 1 + local typeD, prevD = 0, 1 + local lutBase = modes[1] * 512 + local litSlice = 0 + local cmdTree = cmdBase[1] + local distSlice = 0 + + local remaining = mlen + while remaining > 0 do + if ip > lim + 4 then + return nil, "truncated stream" + end + if cntI == 0 then + local t = decodeSym(btTreeI) + if t == 1 then + t = typeI + 1 + elseif t == 0 then + t = prevI + else + t -= 2 + end + if t >= nbtI then + t -= nbtI + end + prevI, typeI = typeI, t + cntI = blockLen(blTreeI) + cmdTree = cmdBase[t + 1] + end + cntI -= 1 + local cmd = decodeSym(cmdTree) + local cell = rshift(cmd, 6) + local insCode = CELL_INS[cell + 1] + band(rshift(cmd, 3), 7) + local cpyCode = CELL_CPY[cell + 1] + band(cmd, 7) + local insLen = INS_BASE[insCode + 1] + local ie = INS_EXTRA[insCode + 1] + if ie > 0 then + insLen += bits(ie) + end + local cpyLen = CPY_BASE[cpyCode + 1] + local ce = CPY_EXTRA[cpyCode + 1] + if ce > 0 then + cpyLen += bits(ce) + end + if insLen > remaining then + return nil, "insert past the meta-block end" + end + if insLen > 0 then + local p1 = if op > 0 then readu8(out, op - 1) else 0 + local p2 = if op > 1 then readu8(out, op - 2) else 0 + for _ = 1, insLen do + if cntL == 0 then + local t = decodeSym(btTreeL) + if t == 1 then + t = typeL + 1 + elseif t == 0 then + t = prevL + else + t -= 2 + end + if t >= nbtL then + t -= nbtL + end + prevL, typeL = typeL, t + cntL = blockLen(blTreeL) + lutBase = modes[t + 1] * 512 + litSlice = t * 64 + end + cntL -= 1 + local ctx = bor(readu8(LUT, lutBase + p1), readu8(LUT, lutBase + 256 + p2)) + local base = litMap[litSlice + ctx + 1] + if bc < 16 then + if ip + 2 <= lim then + bb = bor(bb, lshift(readu16(src, ip), bc)) + ip += 2 + bc += 16 + else + fill() + end + end + local e = readu32(T, (base + band(bb, 255)) * 4) + local l = band(e, 31) + if l >= 16 then + e = readu32(T, (base + rshift(e, 5) + band(rshift(bb, 8), lshift(1, l - 16) - 1)) * 4) + l = band(e, 31) + end + bb = rshift(bb, l) + bc -= l + local lit = rshift(e, 5) + writeu8(out, op, lit) + op += 1 + p2 = p1 + p1 = lit + end + remaining -= insLen + if remaining == 0 then + break + end + end + local dist + local push = true + if cell < 2 then + dist = d0 + push = false + else + if cntD == 0 then + local t = decodeSym(btTreeD) + if t == 1 then + t = typeD + 1 + elseif t == 0 then + t = prevD + else + t -= 2 + end + if t >= nbtD then + t -= nbtD + end + prevD, typeD = typeD, t + cntD = blockLen(blTreeD) + distSlice = t * 4 + end + cntD -= 1 + local dctx = if cpyLen > 4 then 3 else cpyLen - 2 + local dcode = decodeSym(distMap[distSlice + dctx + 1]) + if dcode < 16 then + if dcode == 0 then + dist = d0 + push = false + elseif dcode == 1 then + dist = d1 + elseif dcode == 2 then + dist = d2 + elseif dcode == 3 then + dist = d3 + elseif dcode < 10 then + local k = (dcode - 2) // 2 -- 4,5 -> 1; 6,7 -> 2; 8,9 -> 3 + dist = if dcode % 2 == 0 then d0 - k else d0 + k + else + local k = (dcode - 8) // 2 -- 10,11 -> 1; ... + dist = if dcode % 2 == 0 then d1 - k else d1 + k + end + if dist <= 0 then + return nil, "bad distance" + end + elseif dcode < 16 + ndirect then + dist = dcode - 15 + else + local x = dcode - ndirect - 16 + local ndistbits = 1 + rshift(x, npostfix + 1) + local hcode = rshift(x, npostfix) + local lcode = band(x, postMask) + local offset = (2 + band(hcode, 1)) * 2 ^ ndistbits - 4 + dist = (offset + bitsLong(ndistbits)) * 2 ^ npostfix + lcode + ndirect + 1 + end + end + local maxDist = if op < maxBackward then op else maxBackward + if dist > maxDist then + -- a static dictionary word + if dist > MAX_ALLOWED_DISTANCE or cpyLen < 4 or cpyLen > 24 then + return nil, "bad dictionary reference" + end + local nb = NDBITS[cpyLen + 1] + local addr = dist - maxDist - 1 + local widx = band(addr, lshift(1, nb) - 1) + local tidx = rshift(addr, nb) + if tidx >= NTRANSFORMS then + return nil, "bad dictionary transform" + end + local woff = DOFF[cpyLen + 1] + widx * cpyLen + -- transform into WORD + local pfx = PSMAP[TRANS[tidx * 3 + 1] + 1] + local ttype = TRANS[tidx * 3 + 2] + local sfx = PSMAP[TRANS[tidx * 3 + 3] + 1] + local w = 0 + local pl = readu8(PS, pfx) + for k = 1, pl do + writeu8(WORD, w, readu8(PS, pfx + k)) + w += 1 + end + local wl = cpyLen + local wo = woff + if ttype <= 9 then + wl -= ttype + elseif ttype >= 12 and ttype <= 20 then + local skip = ttype - 11 + wo += skip + wl -= skip + end + local ws = w + if wl > 0 then + bcopy(WORD, w, dict, wo, wl) + w += wl + end + if ttype == 10 then + -- uppercase the first character + local c = readu8(WORD, ws) + if c < 0xC0 then + if c >= 97 and c <= 122 then + writeu8(WORD, ws, c - 32) + end + elseif c < 0xE0 then + writeu8(WORD, ws + 1, bit32.bxor(readu8(WORD, ws + 1), 32)) + else + writeu8(WORD, ws + 2, bit32.bxor(readu8(WORD, ws + 2), 5)) + end + elseif ttype == 11 then + local p = ws + local left = wl + while left > 0 do + local c = readu8(WORD, p) + local step + if c < 0xC0 then + if c >= 97 and c <= 122 then + writeu8(WORD, p, c - 32) + end + step = 1 + elseif c < 0xE0 then + writeu8(WORD, p + 1, bit32.bxor(readu8(WORD, p + 1), 32)) + step = 2 + else + writeu8(WORD, p + 2, bit32.bxor(readu8(WORD, p + 2), 5)) + step = 3 + end + p += step + left -= step + end + end + local sl = readu8(PS, sfx) + for k = 1, sl do + writeu8(WORD, w, readu8(PS, sfx + k)) + w += 1 + end + if w == 0 and dist <= 120 then + return nil, "empty dictionary word" + end + if w > remaining then + return nil, "dictionary word past the meta-block end" + end + bcopy(out, op, WORD, 0, w) + op += w + remaining -= w + else + if cpyLen > remaining then + return nil, "copy past the meta-block end" + end + if push then + d3, d2, d1, d0 = d2, d1, d0, dist + end + local from = op - dist + if dist >= cpyLen then + bcopy(out, op, out, from, cpyLen) + else + for k = 0, cpyLen - 1 do + writeu8(out, op + k, readu8(out, from + k)) + end + end + op += cpyLen + remaining -= cpyLen + end + end + if isLast then + break + end + end + -- the final byte's padding bits must be zero + local pad = band(bc, 7) + if pad > 0 and bits(pad) ~= 0 then + return nil, "nonzero padding at the end" + end + ip -= rshift(bc, 3) + if ip > lim then + return nil, "truncated stream" + end + return out, op, ip +end + +return Decode +end +__FILES["codecs/compress/Brotli/Static"] = function() + +-- 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 { + dictionarySize = 122784, + dictionaryCrc = 1362545412, + dictionary = { + "eNo8velyHMe1LvrbiOA7lNpni8Q20QBJTSYGB0dJ3hq4Bcq+2z4ORXZVdncB1VWtyiqATUkR4ICB4ABSnAXOMyUCIDhiIIGI", + "wxeg/pH/FOeiuhsR9yHu962EbBkS0J2VlcMavrVyrZWJX9FeNBgGflEHupgUlNvvRp72VKJMORqMwqBm/ES7flKLqjrsS00S", + "+P26GGs9GMX9id6X1LSKowEdFyKvFuCXYhRXClHUXw1ULfAHdOCHuqyDajmqaON7uhLFfNYLorCUlHVlwNeDRT/0qqqE99ZM", + "MQ2CslZeouOKVm5ZxVoV46iSxKmuqLhfFQKdVqOw7JfKGKcOVOiFetDoAR2GGI+rjC5ESbkamSQ12qsoT5fRpqzx3rJKQlXR", + "n/lhfyGISsbfrwtoj/GhXT/690M8E69vdf5UjgJPh54Z9JPyF+gfw/AG0YfxS2GCtmU1oEvoy2gduioIqiopD2r8N0hNRYdp", + "0Q8qVRUnfZEfJmXfBL5JSlGEsWpvEPMc1AbfFUwFc1eBiTCcKPbdMt5vAmWSRCtMt1Ir4pl+PywN+kGg8fmgir0Cni36sd6D", + "NesPo0GFDvPVsFTB+ieYbBApr4S1NzoohlGiK6lbLmquRViLI7ffd6MwCl0dYJ/K2BPP194n2J84DXQZ66b61D4/LEZukBYC", + "NWgCbUxZBUXDPURf+6NQb+ro+A/8x7jYoL2go1i5uhCk2P80HtS6v4i/yyCaEtYJm4j9xtjLOsSa9PfralJVBp361TiKKp/s", + "/fwz0Eu4t1YFPaJTPNOvdbUYqBLopx+r4xUxnwTjjbHnCWi2L61UE6yWh/4wBnwPCgYtYvS1fqwV1iEpYl9UmkSgjTjvgoZU", + "0A+6rg5gTTz0XwGtY0eTJI3DQoQf0Ak4IYgjo9M42GCw8HEUaDwKUkwMlht7q7GPgZfvq5bAGpUBFdfwTAJaDg0Ixouj6t9A", + "025UrW3Kd+S62lWPSbAQAXbDx8uwPlXwWb7kF7EGiWvMX0qxquEN4bulpDPGfmCMSYB5GuWjO+XhHQ72L+iLyiFopL8axZib", + "SdZ/va3NA112tRd6qlEUFzhvrOHX+d78IOimAn7dXN3X+Sn2MlZh/yD6HlQhaCggMXn/7PhXZ1WlwSDW26Sx/l8b1v9xUPlJ", + "BXsD2jOlSJsSeAJbU6piLO+0tTkB6CcN/QT7xn76QYeVQciPfZUgZ8jTmOLmjuo+LB3GPoj5RkExCtGnHxhVxLfoWVWNCzkQ", + "o+9iEA0WVKFmqio04Iv3MN4P8APWMaD9BHwXDPr9PmRCYhIQTuxj+qX2ADw4qFV/gr3YDZkDvseahAZ72I/trsVpaPrSoAZJ", + "1r8J/ZUiFZQgAgzep72S9r3unNGJeR/f5fvMX97DmP2is8FEEfYRcgJ0mKQFvV+TGkKMQ3ug6QTcHGHrQF5xZdNH1X0uZEAZ", + "617AOPaDlgciLLIytRg8C5oMqhijj/VyQf9b8K4+7H2iSqbgJwa0FYD5kn4IsBC024UFLmHR/tr75RdemtS+oHxRga5FKdY9", + "wRL5YZ/av9+lbKppU/RNeXBwMB/7Bn0WTDXWA5swD/ytN2Ni28GPHsaxpaNjYwF7DirA2OIQssQrRPvyReXHAcaD9WLfcV+K", + "OWu37Bc3vFMFnekBP/hfG3KgibgS4FkP9FCFfN7Y0dHBWXqxGiynYIpqlBTT0CuAj8qxLkKyBP26ZhL0UQa9g/ch13WwCcRo", + "Uj/Bo8FXvb05inzsSe3jXXtzWDOtfNAch+R7BkvbGaqBWgkMkfhV88c///nPGAdko1cDv5vWTueHarn6F8juAHwdDELB7C9v", + "zf6zfV2LA+EEeRXkW1q2fYh+qqkpQ5MkWJpOFzTwn+1d7WVouA+xRpAxSQwZ5rz7rgNtEmA/oV1AVRhExYeM6verCfYfOgr6", + "IdAl0EwVm/Ee1nRdy7oWl/QNmZDHYLoKcY8Gg1aw16XUh5wOsFEGrwaTKEqkqNLuV0rv/vGjzUEKXYt+sZSdIKpaCfRWTiqU", + "EoEXp6XdX+3aFUI+hVjDv4BYA1Ih1n6AOgC8hfVzQP9xrINaATrIgFa8tF+HyihXVfUgaKOUBsW9m7dsLYPWQPdJCTIFwh+6", + "L40hr2qbMP/161s7WztzPRUDoeWDf/zYM5AvBQ3OgRzfu+mjrdh6QwbA/IMPsIhF0MP/HbpoClHNQIbk0UVuz5e9ewsYTz/2", + "rrXzhx+gvGpYN2/D1//V+m2qPOxNvQ0Ktw3/g9Cv4pl1wB3J3k1/3jrgu5B+Xs3ThaQHE4MsC0LNcUaDezd9sNWDbNMDKti7", + "6cOtAdYfdAtyVEEV/BNGAwr8YEo61M7/HTpjoiJkU0Unvshx01XeAtmYxkXggCp0SVcS90Dn+q3fv7MB/9UYV7MAeoJ8iTs6", + "WjsrftDvtLX1+HEUAud4HnhrEPtkIj+opolp7zPtwAa1vZs3b/20d/sXezd3bFWeqmCt8K7NPX0Qgus3OuuhYpO9mzdtdTAf", + "6FmIel9VIFu62qs9JkqDzz79Yhf4EXglxhq8t7WrvKnnI6wtREDXn0Gnezve21oB1tr63gf/AA1oP3TL/wPMBfLimFfWt7aC", + "rmPsSUlDp4K0QuCe0Nu65cN/fBMVv1n/r9ZO0NZGtG0kkIk14oZoMCiAF7a+/8E//qoG1Ba8r+X7H1r+Y8eW/9i65b1/9Oli", + "cdf/s+dTyNLygA91B9I2wBfoY/XblDoU/AD6ga5KsHb5AujQA72WgUUgL4CRwmTrlg/+8cnevXvaNndsKkbQ1Ohj1xc7nX0Q", + "OFvff+8f27/c+T8e+uhs+aFF7/PR/v1/QL8Z0E6y/ofWTmCRBKzeqYDmfvihq/2f/r/yn0H/9Ff+z6NBvCcBzSnPM5AWAdhx", + "X2fLH36AyIpC7GUeiqGj4/1WrEWtD6LegKjAsZCzURFr0eps7ugAjYOHsRiAf8Cp4Im45mJfkxooSwNT+FGYhzJzoedKeC90", + "Yv59rNOecn4n5AGgnuCrEHzdD1qBplEh9OE+0IkLum/xoHPdwK+2Qvh8iOewDh07/7bTfPivnq4EfEkE7P/pT62D2DeAjKgK", + "5RFVE6j8QO/e9t8GdBK2bf5gb0B5Dlr/+qvPnEIaAJdH/Z0/rGv5ZNe2neC5VlUoQF6rcMOmP38EfFamUOhq90FbkCUpcTRw", + "gl/V37e1vNPRsbk1BND/56Z/df7zX50tn0UlB3olWdfyhz9AX5agUysFyKfW79a1dJAmsA/90db/D3INa92zzmxtb3fwIKQi", + "8W1pQ+t3LWjqQG+ux/SqXqqg/1SS/+uej1uxsd+mUYL/toDHISF/WAdSeA8/7+PnA/x8iJ+P8PPnzR3yzyb8bMbPFvyg3Wa0", + "24x2m9FuM9ptRrstaLcF7bag3Ra024J2W9BuC9ptYX/4bBO+24Q2m9C2A8904NkOfNeBNh1o24Fn0AEWAz9oh3+B0PDzEX4+", + "xM8H+HkfP+/hZwt+NuNnE37Q7iO0+wjtPkK7j9DuI7T7CO0+QruP0O4jtPsI7T5Euw/R7kO0+xDtPkS7D9HuQ7T7EO0+RLsP", + "0e4DtPsA7T5Auw/Q7gO0+wDtPkC7D9DuA7T7AO3eR7v30e59tHsf7d5Hu/fR7n20ex/t3ke79zHjDs76vU1b/gy1hMnjf8Cs", + "UeXVdVgTiSboqgLHJJEXlYHLXQgs9Wo2KvgQ0K+mlDKvpgZ8D3rDEHFFkEsRLRL8rlzsref3RbDdIuDUELqYFgWkKTg2KEXf", + "pq/uE9WG6BM6AlAAnAMdVFB9fB/JOVKlVFVTQMwwAksCe0OGBalPVQcjpxbBnlAQjnHVx/sLeGfABkHk+RH4Iua4/NfPXz98", + "/RI/S69f/Dr0+uGvQ78e+vWgfPb09TI+XcJfc2j1Er8/kb+WXj/Dd0v4ZO7X4deX0fYp/pn99Sh6OPr6x1+P/noA3z7C74/w", + "38vs4/Xs66v49yJ6wlOvr72+hc+fvr6EtgfR7op8+gL9P3x9Hj9n8HP510P4fBbve/r6At7/9PX865f47AX+uYHnDr1+9vbA", + "2/E3N9+OvB1+cxc/828PvT2Mv8fezL6ZwTd38f2Rt6Nvx94efjuMn0P4hL+Pvrn35jF+P/zmNp4dlT7G3x7EM6P47Bf0dI+/", + "Sdtx/H4YbfnfQ2+eSK/DaD/8duTNz/hsHG1G3kzJE8P45gne/gTY3STYeB0FsKYTmOWwg7E7QHW0+gk5CsSHMb811P607AF/", + "QEOwLXy36MNyJqiMqzRzoaKB8mBtAZHBTIdIiD3gP6MBatMqPQaG7gIDcqQRB3N/EL/QZIutAAYwpOUOO7sKiQ7sg/fqOIZh", + "HEL3qkKUJvQLAFgmAa3BQMz+BDYJpBmMUKDDuCTuBSO2OamHsNmFWeqmxoXRE9PoCwo0YwjRYIMIlSl6JWC3K9o7Fby75lOz", + "0ltgAL9D2qHsHq8H2oCeARwCPoCSfxeAsRPzgIkdxa6uUkHTkIZGK/mhKuIJ6FI/AZZMNb0Z+AK4BqpT70siQFciZPSMT/Fs", + "mADEG1NI/SAR0xdKQAN9pV4NzOjRvA49Q1MT/8XSlWEK0+ViwJpQa1DHaAzoQ1eARz9FiFUb0EC5plz098G8xoDCCOgvpucF", + "2BQ4CzpSBTEM7JgWrfk2hX7GklR1Oa2oEFqargtf/AvQztD2XgEc6cK0cSlasOLA6OUAdlEoxs8gRI2mQ8fQm2I8dg0REesC", + "pg9rPk3KMJPwLF5nsNhJeZDuGU7aA+m5xGIJlzOtJLAnKFTihM6U2g5Ihn5acDF9S9hQWKqBqmkij7jGd9RSMdO5TC4WNsHm", + "xQ5ALemqmlZpHhtVrQa1T7m/BeCqUlqFcKSfhNSEXrCmhua4wQbFEFDYWgrCfrpaaKYRcAMamBSPVZU8i+5JWyG9LiGJhr4j", + "7e0lsXLg5mNyAERbCHxAb06EhS0q0C/9SjWVggi5WwbTDzR9Fe2coEdvlvEAd2uwygIaSyrpS2G+JmX6KGBXmpCDLtBN4Eb0", + "J9AZxwlqekSMW3P5b4BjOlgMJWv/ILcZeE6HVV+7hPV+UMRENc1Kch70vF+ByapIHT6MQMIeNAcp02WnST1gv9QtF7jOcVQD", + "KjL9GpsHFIP5kSzAYA5XAmA9KcuOEl3VomIRJOFGVc3FhIkFFgd64E5brxzEQkx/CPRHnMREUwq2OKYahdhQETIwMQh3eyky", + "PiPVgVartch1YWrqYrIVuN2UQcUJ1wAmJRmHfjeTxoA7Rb6SBIyN5lqlSdSJ3Ul0nvZXhUwCY08F/0PKMXgZpgp0iyUexKd4", + "L83eEFLQp3PCLX/F/uiKhISM3TLBj6anz9DNaLwoLcCSqoVuAm6iFR4NYi91sUY2gPUCs5h2KShhABsK3qW30uwgX/ZSchF4", + "1/rE0wg7KgDOc3UHLfBeis0q+DOg3wUglxJBJDUMeApz6wQ19PQYuuSMonMCm2c0kSvleCiDxgZUsYT4M6GL1dDHxm9rZDDY", + "5Nh8Q18vBXdM7g5LMKC39HDLSgTd7ZUU8peb7O0hc6Jd6CURpA9ghO9toAO0QI8IPX7spQgjzSd5B4F4fGvFNf8ajCa0ddrb", + "YYIpjwZaqVZNdlHK01rt3EVipS8459K6g3QME3HlwrzI9ZCJgfjVAJ0YsIT9/dqUADwSDPe9njiiYxjf1tjBRtEdhDSeG1N3", + "+CUY0YOQ0J4CAWNBjO6hR0aH33zd++4ft/y5k1h33zckaigCDC3sA+X3qX15RavBgGXKdL059B0TvEOehtCmoRrI9dAJEIrX", + "i95EkAVWA/I+inupe4gysYMQCvQTmz5VFfEQwOz2QXPglFhR5WAem3sUbDhgLzAjuChWubb29r/TBWrohzJ0HJs9ZGLMMilT", + "54V0TvzFYAAJmJckCPBFCZfQ/VrEzmiossFcD9YfjB2nlLFQ9H+jPt9NyZAPdcItaYH5XHO+a6FHkh5zQ7cWSQWr7YEGvuVi", + "J7H4DAtRTMc/ZAeGC2FLv0hCqtR+vJkmlfiz6dMzO8jY4G5IOEp0nhMYOpToCMVa0+ddIbtQq1Ge+kbc215K0az3KVOMwe10", + "j2z8/nsxVKo5jBWbR7dELqJ7oasQt/cUMa/Y0Cfn6WpSduwJANjUpZTnaYM4LzshY0oh3VRmkKPiaDshXLpzdF9DZWFGn2Pm", + "Tj6f72oHdA1LBU6ahyAOPYedPFYAecdxDdICxK6L1BUl/Q3PQfIV0gZgiMK32K4qT1DkoKCrPYl76P4xHLyjQCEUQDR1A4iw", + "feASOg3KPKUxVLgufc2OgRA3gGqhuIaNswGUSie69w0xBF2fRrA7SahfTmKEGcnnHp0AnYNUJ5ib0RtaO3POdsIjPJru66M7", + "vgqZGNDJ09Pa6Rc3tFHIegrAEfDK6N2EVpg9z132abOXqhJKgpPRlZ6CinM9eRO73QklAwRYd84lOiyD1mqb3xPRl6RVH3RZ", + "Iw6rgukxCZCG+KoNZUceAl3z+EAH9A+adteYdp5AdPKIAgIlLRYLPjqlZ9/Q/dfRD05TsGPXtdCrD0yjU93tfPdD50fiBeSR", + "yne0fxUPm1zO1wdZlXm85cTkZ4JUQ89yrqbKUdRKZ/k2IlCeVhkw4qYe2EBpiQ5msdK7abOYH1qxgnR0dlYpVehSNDxfMB37", + "Pujo4KlBTvy4BaqORGHBKj5EGdFbAAbraqdzGTOCcGrj5pGk8phHyx8qZBIH9v6fd2/77672OCrpuEi3/g7yzGY6THnIY+hJ", + "6gJjJgl98WYzxwIIFva3Ot9/7wT0DPI0J/hjB0SaA3JyeG7nDXLFKeA6+9TW//eg8UHVXfTcx4AONR57wH4j/MWCVRPqme2U", + "na3OO92OR8xKrwddLRWoo35dq8C8DHiilqcb26kSO4Onwxo9iYYIJ7eJyzFIQE4PVqV377av9pK2HB84NtzowJanO6GFADc/", + "4AMMiCsV8iUEX0LL8ACM0DoKq+Rf8kxL1AbcwlMJOWox1JQOnW8hvS7fKS8q6PXcTN/r3tRBhdDJ4zonvzlf8XmIlqPbG1AD", + "27ODmKsAcag3c6TY5NY/8Zfv6cQG/0ETl8nimzZ35ByqWIi+nnUtVBDdng8QQI7HF1hwys6WPxaLRTARIAsRXo7wAcoaj7XS", + "+7xJeAE4qxpahzPsIW7FIR5VuFzEHCctp0OmDbzW5tHQank3SDrpeTVb3/voH108u22LUzAaT54cKkig9X4xFaqm28nlOqEM", + "oI+4apt4IgHxr0K60SNKw+6o+z8273YojWCaF3SXXyk5+Mn1bHSKfYa/OTmu3+d7o+p2ntjlQj0Y1HZiT/rd/Vqwsh8QK5NJ", + "3u8pqm9zPfvLbW64qQO72bYp19pJFN7N00LotzSoUZYYOpM6sXpd79BjETg89ICyWye77/TRliDHO9ytPDh3XcsgcQnPPkxK", + "cePxqKMApulPyFvgo5zDM1rgZwyNThDw97eg0TSq+CaCLQIZ6mk526FnxFRTGqCvZiM6TV5dT3xIXKCARNEnIjCep5OgzBRy", + "hn6UmENT6KwCkQq4WoHKitS36aspelWMefU4iFQt9VRR8/iB3hAAo4R2ZoRRJZGhh8UIBfOMNlL0dgRpiUdktYhHk9YBghUh", + "AgBdGPpUOT6FAb2aMhyLAkBLPXHa0HqPgHx1SLwIu8kjwxLs6fjVdcAiztj1477IiNtGxURWgBZpNSrTjSpkgLdBZwCaR1Dv", + "yoQ8xic005yqAgdqHq354geCKHF9VQS05PGRD7iHha1CUkSFFNMkuo4VSCzgn4ooEign3o9+CzTiMASQAV706nEl4iSjPv4J", + "XPNqocwmXIMa4L+rKmkfMDLQUFxMqUjwoqgE+0D5JeDiAa4LHVgAfFh87iWWt4L3gLagr7F3dFmFYQQBBgDlYszgHrpgDRbH", + "p1OqDE0WmwigFyuFVQUzvnocQnLtj+hYEN+UGeCYVTWqYaQhQRYYjp9FLtg5luMj2EgYC4WIy8fo1jL0koQkmvDVddp8vthA", + "sJ1ARq4MV9GWDEgbmDvsAAwDqwF0rQmTdRWaGGqR3eBpxkLQLQZ0Sy8aaKgU0PPGV2MhKgoimdaxXcDQB1V/a99hFI0gNyrT", + "qTfgqz4IXyDoV/epc0jyMWxi0E2fAnmDnmF+qYAaWQeaZjDQnJI9BFiNTJDyuB6bjK4CrhueoIUd008ohMQwBpcHnQN4OUYF", + "IvGiAWAmQ7efUZVCxENbj+18RWwrvKBMCqsdALkPqwvZTyMO0/NdhcV4NdUX8VXYMqWFpygKwAZ+bFIdcASRKYrHhh5GbrdM", + "kOsIy53+KO6qgkUWEZYp0m5C3RBon+EXhSigCxOrBiIE+OKAXh2QfXMZB4MnYGuAGNgjB3SdO40OeC5F1yclyH1SJ5mdfIKZ", + "UCkpAmb85oq9lYDh0RUlC2ithnXDJgUVoMuIAFKcqTQrgFB8TIvTh+wCZWMSEPiUJcDzVXHGisGmRKgZn8e43DLaGwDmEDz4", + "WNN900fkqBVdsuZd2qqdXkQtjY6h8Al6UutUAw0ZOudqhsMXdVHgoUwca4HhLk+v0yoNX5AeDFvKnrQCtYWnQpi6lDyENaBA", + "WAbVtAB9iacYLwM8ZUjnFbBgrBgkROeYAZ/GLiYUyyFrLB4nWBVaoIRmKI5bFvcE9odOx1iXMCo/YZwL2BaWEscJ3o2CtBLS", + "0oohFmlxi8OwR/v0XABIl5JyEfINZmdMFzgWDrgOVAxZSy7GBLR4x9JKBStAyzzm6mqvap1N+2CeeVXIOrcmKiChlU8WBYS3", + "0gR6F5IE1hywRMkT41IcXUachEBSPnZ6UMz1qgYxajJeqQYJmRLr0pFQBHPHjDNCD65QUlQsAgaDDTFAOhChYtNChW4I+gLF", + "yWrSKqN/gNECmEt0E3ni4AU8K/OkOpX+y6DUQRANZio+W/NloU+7ibgFjfX2gqwhW9xyLHFbFYwQBE+fXVloLKSyxTgxR4h7", + "kBrnCn77NlV05CWUOXSwGToguYOchcS08KAK44dZSSsbaxXxcBkWFPrB0n9GmYPpJHRKYW0ptitE8BqyWTNqSHtJVCoFWtzQ", + "oGueHpNufdeFIgUVEVdVatRkgypJYI3I4XVSFCd3WbAlo5tyPYxp0x7ovZgGwsk1sVXFY8J9By2AtlwMh9KpZP2QRu9zGYZC", + "D0CJ+4rxlGUxilDzibjErYfbYL8wNigH6CfGeUTxAClTfyUrRjYHgZEpCS6oh13MxDB6AIBbNiPnEPzRKaOTknh4yFMkINAk", + "0FmRIKEGERpURNDQW+zCTCa3+qHE2ylSyw5x3kWyy+LPhVTxvEDv4gkkxeEgHZgl5dYqwuPY7LRUZmyXFrCt6YMv+SHHraCZ", + "fL4LCsElFocAkbMCT/xkhPaMfVEcfyTnqUI/NTERGQ4BNefS3oQcAL+XPU1JHQstgWOJAVKIi6TCWMGaL55J4TUtrnvzhcgW", + "L6V8sN5EOTswjPrSHiGFdSzBFPIDcC5Wr0RvO893C8I7dOUxGgusYz4W2UWfLC0jelZdWauCeFmBYmNVBR1g96wvDMKDdA5I", + "l9QwC9JeFZZj0mYHUaW8rTDkp0SPIxR8CnEMWc/4FoAf9N3rxn41wRjonCeR0qqByPN8ciodYSR7zrFNvAhYR6wDqBACQQkN", + "8CRFe3SuaG+HrCEWmA60Mp0VKmB8IeMJcw7sG8gNrgls9+/otcEAi/6+SI4LPhE6zzM8ZoML4UEKIL4AXMPkAwXUVf5KJGEi", + "M+I5Bvk8gQzyhP63C6fD+kiTmriGKd9KUdIrEkxR0gOpCUVDKnG0ViOIRZxwB2PNbz4XCS9aCLRN93yv6AIR84Yj0N67YcFU", + "O+nUN1oMcYeqOvS66LZ1eD7uy3lNdw7MCmwh0X3ASgMSPUFraKuzt6wdjx61kpxLme27Pv70C+dzsAT1Mh31rtgDZZHMSkyK", + "T+UtFDyJ2VXBZutekaXgd3CDh7/dxB4LgHfA6b3CF/mWli9DcepojyZLrmcPcLhfFWeWKUtkAnYNPXwpUiKWtRciNqH4E3tF", + "2niaThu6b4Oas0HnS/mCLjPuIiKdYCIgHJ4DaIkCxA9PncS1mxjCQpmVb+zxk7eFBv73hHSeorfVrfEECEpOYl9h0O9nlB6l", + "vdBPT0HXIP3axP9P6VRNRBt6xDOh3h1FdAgoRn+KQ6TlG4rsnHhgRQ4bk3PaYcPlxRqLJDJVKCH+ch+j0Tg+bDCkmT8gnBsW", + "Jcpqp3XH0h7NqWqV2gzMk+uRw0XDGNd+wwhgMcFcemyhbTBnjFZvg1IHSuSyEQRjP/eIhu0qxBjLIJVLLKd04pfR3vff0y3E", + "+ed6fKvFwGOqRs7P9TDWCPJEh7A/IddSyhCAuFDc/GYTPYPfi/rhGuIjOU3J0XODt5OIOjkTJbpMBZvkjIGfgMhjHpQUsRzJ", + "VnE8OHLild8mWkAOloyxx32UG94n1rlPf2D89d7dbR/l5OjR2S5aIO/8HeiGB4V+JP5i4LeQsUEx0GbS99+pRKqQPsXXAgQF", + "AZ8ABYEPYNmUuONkTXpJnO98EysstKoJenHxSnoNcz1lkRhcDB7mkb/lCMnIeWqnLIMnztcuWArC3dzDtjZGtkJC+UkNk2G0", + "CJ5XqXjDnE1ymhEVEvqnidOMElfXRufT0KWjRHs14SAHOgT6RQ6O85To2pMTodo3JNb8bkF0dFxr73PRmIHRjl/cI5gNe92v", + "a62dEksrpnVJsJkcL5udgoF/YJDud2AfNN+OPrvai0LhcrKZLwoeljMK0yWeXh7cOB1VfFZRIDoMS0zgGGYAbDfBJ56cxxlG", + "zfjh++KMolMInEU7IMwTEG1QAyoRGwCr941MSSjBCG8qOSneWBTtJuhLYtFpAWOYG4Q74l7BgaRd9uzVcj0t/0lht7fMbYbm", + "wUz7CGlqjGXvaudRb7EGHIsufNgzcU2OcLt3iBQVR5yj5ITlG4FxPIZVHuXSAHSxi7WV85aWXrEOnJ10BrsEJrGc/BvxaHvb", + "6L52GMEb1Lx/ny/nepgDwHFS4MlpuqHZnBqJR6CT8p//6pQ4hHwphfETAx8w0pUj3MrTWe19SXDh8Fgj50DKpTyRwSbDROBh", + "mJw1Y5UAU4rALtBoO6wlBoMZUlSOhHtF+7S0/B1SOVEgm1iiA7biQUZXx0QniaxertX5k5OTHe8ppOQIOcc1n4uOpsYhkqwK", + "BKRM5jFVrmdAwg7EBo7lLBMaCmCFlmBC11oi2B6bB80UqoGefoY/G8qNXI8cTZtuOR+WA2GnLL11WIZvafk0dBwJk9gDO7Xf", + "b5NFxDsgB7eLxpezQadNaGmzyBzmSOR6OsTl+qVIuTYRTxXSFQiDdMt4RqdD2NGR4Agj1kGrFuuP6NuPGRuXcxxrJEjPbcL8", + "0F+79lW3ypEqcyb8kEY7ECMDOYyca6yTo2+n5Q/kwR4Gh/0Bn3s9LfJtS0GVGTcUc5NKjLQFT5Zg0VZljiau4t8SMTO2MjdV", + "PzfamB5aeXm6MX9g9ZczK8vX6wdm8Hk2+bI+dmpl8cHK3NDK3M/Z8INsYq4xfb1xcqQ5vZBdnswmZlYWb9cvHc/Gr9fPP1s9", + "/wTNVhYWVhbuZqcPNEd/zp7Prrw4sDL3U/3q7calo9nz2ysvLzUPnGk8Xqw/ul6/dKTx8lTjl4v1I0P4vTlzGN3yvcuHOKRf", + "rjXO3KuPPV+9c271+lM+ODRcH0fLmdXz06s3LjQm57LhxytzR5svX9ZPXmo8ubHychmPNF9iVM+yS/caC8src4to2Xx6uH7u", + "YvPuyOqNU9nklezW8frje9nIMb598VL9zLPm+YlsZDibnq+fuNc8fjKbO5hdWqg/G8M6NO4vYF7ZxKls7tDK4tDK/Fh2+2U2", + "cbRx5mr9yWI2udQ4MspvZ89mdw7Wr1yqHzlax7PnHq6eX6xfGsIv9XPz2YuJ7Nj5lYUH9YmTK0uTHPbCifrkk+zWT83li1g0", + "LEhj8Wrj6u3VA6frc3P1sYlsfjk7NZ4NP1tZPIf+m9fvZdNHsuF7jQeyHS9+yk5daC5PNq8faxycz0YXG0fG6pcPNc48zaZO", + "rsyda5w91pxeak5fz4aPN5/M189ebB58lI1fy4Zvc9jj99AtdjY7O4Kdyo7/lE3faJx4iEVbmRuvP32Ouay8PJs9f9RYnGjg", + "2XtDzZk7jcWRxq2l7NhC4+Ji9vJs/dID7N3qpaHmnQMri8/r117Uz8zUjx0A2axeHF49vVQ/cRu/Z9PPssUFDKYOApg4unph", + "uDmzWH98Nls6uvLyeOPlNF5Rf3pidehI/eh9rEb92vPs5ensyPFsbKQxu1g/8SPmmE1eW5kDXd2qXziNVc1Onli9+nhlHjM9", + "3jz0cnUIyziKZqC0xt1TIBJQJj7HS7Nbo9nJMRBPdusuRoLxY+ka18407j9bmTuN9ljS1UP3Vq/PNyan8fbV0WPN5Qv1CzPZ", + "i6Hs7tH6oeFs5ClWtXn4FGiSdHX6QOPIsWxuOhu/j0+yY+dIXQsn2f/UHfx/Zf5adulhdnmo/nSieXesPn4WDUD5jXtHsVD1", + "2YP1oROgIvBLNnQxG7+KcYJK8RUGgFmjcXN6Jrt6AkQIysFCcU9fztaPTjYPXMhuPqxfOLGyuMjdOXA7W3heP/uwfny6sXSC", + "3Dr7svnyzsri0cbi8ZWXI5gFV+zpAdAqWBJcBm7lXGYu1y8sNW4tkJAWJrPjZ7ERYFtQFNa8fuUkxz+5VD8/DFLEyLPh55gX", + "OgGVZmPnwTXYx2zuHCgtmxlpXDsAtiLdnribjT3js8cWsqsLIA+sLUaF9iCq1dHjnCOod+FYdu5S/cENUC+oEV1hkckFC5PN", + "oUPNmbOgdpLi1fnm9BQGTII8s5wtXKqPYbsXGidmshuHVu9crM/NZCePcRnvzYIS8NTqEETNUDb9E/du4hQ3/fSB+rXRbHRE", + "XneiefdmNvIYI8TCikw7iv6zifHmk5tY0vrYOUgYMAJkzsriTXBc4+4MFiS7DW5dwDpzpmeGsjPT2SiG8bBxZxESJls4A5mD", + "ZUF7UCOG1HhxrrkEwXIV3Ae515y5QSrF1l8C/z6mcLhyOFsaA+/Xf5yqn1lqLB5uLI5ijo2pc43JJ+AakEQ2Plm/fBt0Vb94", + "cPXcaQrPsYeNQ1Or5++hk9Uz06BerPPq5SvZ3Fzz6GxzZqpxcSlbuJPNHatfmiQ93H5cnznTXDrU4BhGmncPc2XIidMk+PP3", + "6odBnwcaj5ayl/fr5yHGKZ1Wf7lAaXMPgmt+9fIN7OPq6Kns1mHIfIiX1YsnQYqQeKunn4HdyCmY1NjIysIvjSP3yRqLE82T", + "t+vPIWGucYTTz7CzjbvHQXIih59jUmS68evUJqfGm9MPIUmofRaPNp/cWx2daJx5TlJ8OZudPp69OEsVMH4bLTFm7sXyL6tD", + "V7Mf72FVufUPf4Ikx0QaZx43Z0il9WvXsSPNmdvZiZFs4lE28TO4oLl8BmK/+WRqZf5hdvJ44+5DESYjoCgy4MwT8hTE8sKZ", + "bOq+yM/T1C/3jmYLE6CT5tiD+qVD2enr7I2b+CybPrSyfLk+fqs5BJlzZmVxPLt1v/Hz+WziJkRrfehAY/wZ/31kPhv7pTl9", + "C6/LlodXry9C5kMjZA8n+NKxU9kQqZTf/vwj9G92bLh+9MHqwZuQD3gvJSHk58gwxdFJTG2enA7+vTuCma5evAHGpN5cHsVQ", + "G2dmoVNIqJCcowuyzsfxVX3qJqQ6Jli/cLV+dnhl4Sjoh/r32ijmSPk/fr25dBqciDeC/LDjjetD0BcUZQsjZJnFhcYU6Pk0", + "tBsV0MlDkLckKiiXsR+zmXm8t3kE/D5DjTxyjPwLWXHpauOnw3z2l6ONqSONhbsQ5tkViKaJ1Z+PZdNXyONjzzB9DBVQAeNp", + "TC0Jvx/NTlzNxibr569RTUADAhIMHSWuAHePjdaPjWbHz5MLzk+tTo5kkzdEJwpzQa1PXqtP3WoM3wWV1p/PZpceY44kOejT", + "51eEzq+CyDEe6JHmMub1AgqCzE55eBqcK3qEuoZqZeYwVFvz7pFs6Tw55fgJqrOFqWz6GIinfvgqv5o+0rw5jAbg0NWD09QR", + "EIMLd1ZvXiUKuviycfhZ8+UDopTx2+xt+iGRDGT7dbz3GBifu/bwFMXIaUiwS83by+BEbOLq8I/Zwnk8Dn23snih/mAJEgDq", + "nlILuzx9jAKWyOQcNB006eqNkWzmBVEW5ntsERQCucH/L05kw3Nc1clr2fzjbAJccBhcmd24Aj6tXz4JdESyvHFlZf4o3tU8", + "QE1aPzuGHSdtzz8BMIOyI8WCIMG2M0eAN6C2Vpan62fms4mDK3Mn6kdOZ8cfgkMhjSnlbjxs3j1IcDJ1gWDs0VLj9pXmieey", + "UPcx2cbi3cbi1MrLa8AhlP/QifeuAylBlBFvQAbeuro6Ody8eKJ+Gurs0urNE8AY5Menz6HlSZ8vTwPVNK5OEbJevo6Vrz9a", + "bJw731w+SYSzcBezgLqHxMOyNMeAYMdAmcSfk1eBEMhWZydWgaBI24fxCqLHh4cotB+PEjECwY7faz65CgWRjYBP0dUywCeo", + "t37uJeHNxPnm9D0sDnkWCHni+OqdMaKsFwsUv0N3m8cOZWB5IOSjF1denFo9/wjrCSKklrl0vHl3iIJ94iAeAbNASJIHsb/L", + "l5szwFFLK/N3wODciKdHoRkbd4ncwOBcHCiy6Z+aB683blPv1M9NAYkBXVAHYYXHr4B3sJvArqujo5zXydtQXkQj2LvJabLb", + "2Cw0b/3UYaKLS0eof2+NNm++JKqBIL20gKWD1sumzoO8sdGQnxTyI2DYU0RNl2+QI4AeKQ+vQLCwt4dPQGCgXuGmcWCY5sMb", + "+H/94jS4iVJlDmQzvvLiGqXB2C/1qWP1yUf1o7dFj0wSNg8fJwdN/EyNef4ZFfHj0ea98ebSEvgLnMIdnL5BGDl0AL0BeONd", + "MBlolTx5AundePYIuJTIHxpq9GewD5gd74KWAdQBua5evs/9WqCGpRwG3b6AAroJ/Z6NXVu9eIuLPzbXHD+IhQJuwY7UH1yv", + "n52Dys4enqImHfsROA2asX5ERgV+PHmCCHD4nrz3KWTLysvHUDqNqTNQDUQay5dXf7oEoYcX1W8OgcawF9g76AJMs/7oR240", + "ZPXcXOPMT83RxxzPyRFiQiA96EpAmluAxM/w0uaV49n8XOPOBDE/UNbLG1RkoyPAupQngKywccYe1ocu1w+BCE9QjxyfABdA", + "E2FqxM+3X4I7aMIcOwJRSVKEBJuHuXSJBPbiF9AMtpvGyxFIj8MgRWx3/fIyaBUgDSILjEZz6cJpzI6QbxycMkkRDZvi+CgW", + "nGp64Q7368h98tTZJwCiGN7q0DVKTtLY+dWr9yFPmk/m2A8miK2cnFs9f4nSGNrh5Sw1HawqyHPgmel5rjCWa1yspMvXIQ9p", + "KgI9TnNrQPACcp5ls8NgHEjO5vIVMCkUUHYcduISHqRp8Pxudvs2RAStGGg9GLCXb1uTFjQM2iPNQJlC6UDaj1/h4oOp74xB", + "o2GDwF+rZy5iozmFk2PAexDp2dALEBgnO3mqcfkm9DJEE62whZ+hnlYvUJ1Roh5Zrh8dhphdPbssHLdAFAGLCVoYtsniE3AZ", + "hHN9fil7fiebeAzuXll8CRKCpgCLwaqC9oeso1EG2jhzNTsF8+omuAnwlTY46OcFqGK+eeQRSA7zwr7TVAQ3QWLAwD8M+jlO", + "UT98l9sHTQrBuHySZAOhtHy++fgmMdszAPLR7NJVQuWnF+uzV2HZUQGduEfoC6MP4788RX165C6tM5Dl0DVIG4IWtJlfFlty", + "oT4x0Vx+mE1cgJVEll+8Sn4/Irxw8X5zZokQ6xglNnEjLDi89MQiddCR47DKaR3MPwEV1S8fxNhAAytzL0G9VN8Xod1G6pd+", + "5hwhb2mkwM69CQlDLHRkLLt8vrnwC3YB880WRjBs4HYSnvAL7fFLV5uz8vkh2AKXCHcPTjemZwEtaKfPHoQSzCbOQZZSG8JQ", + "nZzDyoO1iYrHRlZ/vAq7Bn82rk8TV0NWLx2lZXR5CFZD/QoshYvNGSCiaaKg6cvNJ5chUQlabp7A3OsnxFqHhTXzYzZ9DTwC", + "sUO4df9s85dzjXNL+AqGCSUDRgLB+8tFatLDy41fbtdnJkSkTGW3LEeP4BNqn1v3609ug62IJCceNg7cBEUBo2LK9J/M/Qx9", + "lE1foDsCJgOQ/+Qc1fTYhcbZ24S+eGoJZt0YjaOlZQLpySlQIO3QseVs9mj92gTFEYxErDbIZvRJ4+cDpKgDpwWIPhB3ymkw", + "Rf36TVLs+GMIk2ziTnbrHPl3+BDwPE0AAoYLwGzZ5KRo5+vNn4HST6z+dLJx9wDWist19zBUZ/3ZWPPJfDY8Cy7Lli8AONFJ", + "BSN07g73/eRxTLZx8QV9Iy+GYElRjVKznxdNQUqDxIBNQctRLDj8jt5grYiJehU6moCfaJM+KKIUIIHLV6GqsNfgAsqxYfoo", + "sDhURi8uNO4OYRkB/LAmEKGrB8brY49IRRM36dtZuJU9nCXqWL4M81wsCDDyQbyasoWYii6ybHaWJAd1efgquLU+PU6Kun6l", + "fvJS9vBoNgtleoIG2tjz5pMbtJVuPly9CthGdxA+IZy7/BPlxvwjmEWYHUUcMNXkOC3oi6fwySr4/dgwpLr40J7REnw6SQgH", + "Q+DopAicYxgMZdqFmcalF43L2AtAlCfZPSiISSJJrM/xX+g6eHGhfugayDK7OUphODzbPDJDJ9jwMF00D+5gx1cvAic/w1yI", + "XoBAJmZgk+J10JL0PMBygXVJG2SJHoMbL9DPyovzAL318xP0g8FaxKZg47DRU+hwBpSzOnSQAvbEVew1QBfFIDo5NwpaArRu", + "LC5DyjXuEQU1FsewYjQ6jtyHHUcfy8lLjaMAgZPY8ZW52xR6D+eay5eykYuc8qUjsGQbv2Cdj8B+ac5eB5lhoTjy2y8bi5fx", + "YXb8AA3b5UPN5UlMCoYA9BGdTi8uZOPLbInBP7jZfDqRzcNCOUNnJnACmOvkKdEODymogbuml4AVIXP4lqeHgWDJNdeerP40", + "0bg8ROl06y6dgRdm6jNnSSEXFyirj50jl00fI+Ngs66egPCk+QPxC6V/5DTkbePMDfo37hwUD9U9Wn/LlxuAWJPXGk+uUT4A", + "WwJ7H7xHXDS5RG/k4UlRPeCRm1BbAplo41ODTx+pn/ixDuA3e2R19JhIuUmYbzRs7y+s3jkH8EyL49zh1fuzRNdzR9GG6zAC", + "6578AjN8Zf7I6oXH2fAR7D79US8OrixMZyMABkcbJ+5Txy3dwr4TQz48BaUMOqE9fm+WWnv4ObptnFkEaCF6eUyjFeqeWBRA", + "+tBL0DYdd9cfUEfDsrh0tD43XL/9U/3klcaDU/QSXzuwukhUBsoh2c9ebR6dwHYTnc4tNqavr154Vp9+2ry3mI2MN5YXmzOn", + "IITBONmBn4iIXrxYmT9Bo296hlv2/Hbj6FB9+OjKPADnXOPEDJn6KsTRItd8+SnRyBU6e4HiuJKwlI8tYzpuyjAOHQ74jOvz", + "Yt+TEMnYD33XjxJfV6pRNYq/TbWbMlCFJ55eJAGzoQRsGtY7iJUEzoZhVCnEWuJnw6qOmYSlGL8qIaXG9VNPeXLOHqk0RJ/S", + "j/HkE4maj6uxxnuNLr1aCCWO1AxEjOWQwFLDdJJQlVWBucslOUhjSK6R0EIOm9Eo36Z+1QY+GomtNSoopaFyozjWkU3uZEiv", + "H6s49guMPkRvZRm55gE4DzI4TlUp+GsRiYw7Zai5YaDfq6lQK8btuNoG4UrsqITmFhRDcGOJhcV4UsbpSWxPVGHAZjDAaEB+", + "jvnKKhkJwDUSpBtKVQAlkbyG51CMZuYpu6eZzx0VecYmkZ5G4mEiZk74SoIzOUesmBtVqjZzWxuJ9uGuxXiBL+GZPL+1kZCx", + "xH8aj/E3mGPs+qoaeRgEs7WTyPM5UPxeCCSomFECmGvA+h1+5Ma+8bGbzEPCTqXsAb/rIikEqxJjZSW9SmsGRkUSQC0Ryp6S", + "HlRU5OphBdBUt/HgnCujjJyVG4lVixizZPtnNChWKpK4QSNR1waT9Rlly5wRCaM2sdr/6jHeWfA505QxblGgvSjRIfYXk321", + "YCQ6j9GyfqgY14TxcmWUy7CmyH113fP3S9wnY//wlGR7Ke7+flK4H0TYRY6ZJB+/ur/PxztePa7q/aQqTw28mvJ0pAd4dllV", + "zAKuaIaQM5SVaUBMlyi+uu76gasKeEgigiV81UOfeDrqU1XMQoJhTUEoRCKnjYTRxhItHBZltbHX3HGG+hpJ1+VMMfeCHxRU", + "RI4A4ZArDWOYlMQ3etHrJ68Xf534dVSy5BdeP8TPHLPefz0unzz69YDkyj/G78u/DuHzg9Lm6a9H8HNI8up/kk9m8dtzyalf", + "tJn2r3+UZ5clC3+KvUmPL34dxacvmK2Pvxf5b2bx49klyep/jNZr378+w7G9vsr38jv0Jxn8kmH/4vWC9PdY+n/E3mVsL15f", + "f33v9Un89yGevWtnIc8+km/xJMZ9Q8b8RD7jW1/IfGXW+PZH+QRv+XVYZs2+WWOALZ/gn5fo+Uf7xrWxMdf/x99HiGcPrPXA", + "NkPocfbfFQPm8MRLWdMr8g/XekTe/lDa2DoGrCywJJUDltAzx2nrFyz9egC9Pfnt1tnfbo/+dmv+t9tj8vvQb7fm5JOzv91a", + "kk+O/nbrzG+3Hv5262f59z35dkIa4P/Lv92akqdG+SA/QZtb8tS8/HtEHpyXNjP8hf9eYhs2vo3f+xR5Wlpe4v/51PBvtx78", + "duuO/H7+t1tj8tWS/D4hnUzLG+/9duvpWp8c1e3f/413XZCRXPq9nyF5nfTD359Ky3vyyb3f+0T7IzKL6d9XYFpaYgyP5JM5", + "6W1anrojn5yWp0bkwwfSYEo+eSDd/sQH+dU9aXNe1nZIeht6M//28Nsjb27z329H3zx8c/fNjTfTb2bfzL+ZwT93f/8cP0+l", + "rsPC2/E3s1LJYYT1GdCeNRhG0H72zTO0O/z20NtR/H0Xn469HX57UOo8zEslh7vyOVuwYsPP6Pkgqzug36k399ET3vv2AD57", + "jt7u4e2z0vI2R4XfhtHiLlrOcLRSW2JcKknMv3mGb8ffHsDvU29+kbdybKPo9ybf+ObB2kxG8ftj1qLAeEbezMiYHsu7ZjE7", + "zpRVJR6ylgRa3pTaFMPo0Y74Z5kJRoCnWKPiKZ56gp8pfDIm1SpYDeOujJZP8D2znNfvz2KEN9H3GOZ5F0/fXPt8hG+TsXAm", + "Y/jnIMeLliNvprna8tvP0ucw3nj3zXWZ3bi0Yeun3BtZn9m3B1kdg6vENZZ9mZFx3JT2WGfs3c9cXTwxgs8eoI9hGcPP3JM3", + "D/DbfazSCFqO463DaM9ZLLx5hE9GMIfH3HEZz2Gp0sEVtqM7iPW5J/O+yxVGTzeFRli14zr3RMYxvLZ3h1jRA9+S5n7GNxzV", + "vX+v+mNZmUPyrnmhihmMD+OSt3Id5qW3Uel/lDMH3cy+ec4xSGyY5AYxRpKxp2mQlBnkGhRtBLbAOgY8pVWJRpQwJY+VNaS6", + "g0SqFZUp+1HYZWPsJeQkrgHuSE6vRNMzXZ+622YCmDgNQ8l+jvg4qxEwkldik5ldwzzOQR1I0UXgMzfQaSilF0LNrPZ+ohsV", + "1rwa1KpNyzcS0Deg3Br6ZLR5r50Ry9GgU8+X3IhYS3ZyLPPFGwosP1H2pWiEzQMwa+HKfAvDXXXMeFdGyLD4QJmR0YGNu88r", + "T3IepbKH9ga1RDsLtnSZVO2lLsvc8C+AGYZ8Mp3NVaFNnvBMKtMV0MzcIrfMtIU0ljoWzDJhwZECwEVNopSldKdivqcUbouZ", + "mIDvKopp7tqGJRpZAgKCkFgBgygxzg8gRyc1m48ha81UMonJ9xJAnxLTFBhpaxiWyXi4QHJ3CdZCQneGKNcI4jFcpowzzEmC", + "vphSV5XUhICxTDaXZGMfOsMjeLtsJ+uuoW/7pd7H4FmzlltRYLymq3dxpqa8w9JZUo4ZcrVHwqUdYERb9oGh8YkakOg7GgiY", + "u6QblXQvSIGV7ohn45qnXUY2MVmVySO+4f6x7geWmMUT/IR1Nhm8WJKEuoD0wZQBLS2NDXSS+hisUSH5rizeCHhtsxyMTcow", + "Nj6bRbu4ZiQw7ABjgH3JDiFpeH6JyLzqu1yebbbmSoXGBldeMeg3sDtt02SsRaQCEC4p0mZPtNuweCNxnQCNWuLGGCnL+aUm", + "cQraZnaYv1lqTZlsENQ0k8485kgwYI0B/sJjA34ESImFxOccpSQdCM13tadBz7oWBr2yqEAgdUkkns8PGcHH0E2m8pW0slNh", + "ATSAeonA115V0gzC1L5/p527qySt+++W1RhJmzIpB2zkgsrBI9rbxvIhTMmgfQPSKHGrHBvnZoN6GcdHatiWMussKelE5i6p", + "LYZDwV977Ba7SvjXJsgwz0CSXYjqXc38AW6wrLUh1cEy6d4kb/rECgGn2wn1oLPD7oNNbfJ6SSEq+MLKHsoQX0o4kEnA1+SH", + "HcxuK0k9ogILMjJk0xS05JJILLj2duo0MUzpCUnzEr8f2zo7LCaTDOq15P6gZuz8QFKcdK9lX8iXKslzX9kv+AkTft9pa9th", + "hYfUwGFC9QD3IUolCnQt72UtOWaDFVrVlDagFjndnbMh9w4DzqUwh1DIp2JLck9ABcwiApvVbGKLadvEmoItkogQV3ZYYcXi", + "tKHNCiKBVZlaU2KBFIZJWsEpMfza+5jUH0IKMwvIY2htXOnxYbmknh4sa0tSzATxeu2OuSphoP42qwNsTpEt8ARuCH0+L9JG", + "15jngpXfwezAUlRmyRFV+9hyODOGQLQbrQgSkgIpatalLpEZB0i7hoGJknsFwqcACmr5lhYmC+C1DojMA+2AA7ZDMmBzd1Dq", + "QkliiR2Wm/TRSn8aSy3qnCMZ2DaNw9C+9aUoM7MVPrMivZxKwqMfOmwFSaD82OzACjKdmRmGKijENjzblzyrQFqXtrIOb3fO", + "Zk84a0lKjPTHmoGZK37KLJB+zHZbhWVI1S5PcuP/Zef+udXaTEtxkkgiO7tzVKaB3seoaVJBIpkHBUbODmip+KXjNpt+Z9Pp", + "DGsy4HGW98Xcd4MZitE+KjcGJkNX0WgWYQWVtc+vpJWyFXKQK74X1CCfK1KFFFQCBY9xsuy3xHsbqW2FqWAE2uZWp6z2GiqT", + "1ECeeKvTa3FIzAzFVFOWRJXaVxZWYM1EN1ImU8ChZ7xPCXnn7RJss6hkl0eN7BhdIhd/FUGUJ45N5zB7lOtb0czcgLTqDEr5", + "Ioa7bh3UDst+bxMtuZalYb6x2XosuYRJK1cEBCsoY9+l6Ib2tjoSyptYMFSg1jVJATtR9BPGRWOAvVbAszIp1gwSGB2aSiTy", + "hXXy8B/fOCxozrnHRounBFvB+tTdOVF1IGhWFhpgzD9TEbgPUrm0ormi+/D+is0HjrVNDNqqxa3mYZEc1gVieLYCD4tKHlQ1", + "LrmzLWUeq80yMzss+LJZZUaKwEGPs2iakdQQDEIqYKxrqbKmNTR6LKmRLuuNVxPBbgwkjiVZzQZt2zROFgJjipyzfj0ZDwKE", + "c4cyDSSHFcIcMsSqeQuwtAJZgimZVi3igslqpjUvST6Sceyu5SFBk4hrx/rCPBvU79gcnFiKrjFOn7WK9C4J8ocwFm2/lmS5", + "w0I/X3xmQQhZTuiQyjZ+Y1MimNJBOmNAdK6HQjwgLJTOqAjwXRsgZ/9aGpn2/pqyPDL1UVUqxEELV8zeMlSccSrRfqIbbqMv", + "ZVmY1qgtM0PAU9xtFYraWGb5Le19GdQqABrfWCFpE1mNFKfCxACpQt9dy6K06YyMzwdSFB9uIsJDdsTmx0qRsaBWsomwUiIL", + "9GeL1FDxsRurFC3l51mVouxXWbDHZ2qtiC7JziFMYUEiL01kq5gdymxECxkT+b4kvBYwGYE5hNstngf65Xt/cKQwzx4LJ6Ei", + "Ka1Ysh4kthuEAUFv0xONZNJpbxd5hxqnSG3PVFwAHt5XAGnTq2UubXaVdlsozTyyqMgiJiwfJKWLqK5D5lyyXNaGjtZ2lpLu", + "k+raFBfWjOhNdLWsQyYQ6NCJCmJUSHmmdS2fS+aZwxXDUHOOFL2xKcsGemU3iLyl5XOwkWNzs4zE8mMfrNQr+gLJWCQDQ6PD", + "VMobMusCFoqsEgsmuT6MEYB0Y/osLX2sWSzA2c4iOWnFlibqSQZ9QWYREzNqrO7O8nMKuDzWjk2jYA0Z2mPlmE5EMi3ZUXKy", + "BFxClLJq8boWZ4c17kDr4EmW9DcYIN/uKCNv98E+klrYRbbo6WLlewAJQQ7rWmy+nrFj0XZBthLMohfXIuNNNv1Ayou1OMbu", + "WMHWzLIJp86glrS8jg5brw30DiIEDKUEk8ofEJ4+VbhT8HmtQo3XWzgsaupwA1kcHX+9GyuohE5e18DK26y8FpY2WOLdiX8B", + "VTF5j/TpMzWEpYD4hm1WlPwNsAz25wCIkV+mFDLGZQlCFYhqdbr/boWHVAmDiHVEndpkFa9LSWIvE5GwmM42yN/YFx1X1jt/", + "N1cTKBKP6S4DnBHTljsLioLFsDA3RwYJSKMYIgNrSh3uKNqUtD6BR9nZX5mSCMghmSaS8EY1YdM0bBqIs1tyXRyiGbJvrUpy", + "k9KHLm3Fii91EUPHL1qjKbEJYR4JCK9tt1KgYLNt2sRu2cqKnGL3My07L/lTuR6MDG9NYIMEWqw90rzk/OA7LHLqJ7vlsgGP", + "eU/kC+oBZaQ+Xq4Hs+Q62zRZAEjeGNDDazGcgtwygk1VjkitCg3UuNYumVP5ooUAHvYE6ozFaaDZXIvZpeSB2DK0vvxEtH2Y", + "ikj6q9RQd0RUmoTQD38WpfgkZQG4kmW9WHvTChRnsBxxuCTSlEU0pDCFAcjHeGXpWDJT8t1tQrfplZoFDsv4czejCreTSAlE", + "Rf2HF9mkxa5CjZvpfGEh6h7r7LApryynSfZg4hJ0eS/YA/1JTbegtoeaCRIycniCRcsmpZVMo9TYKgnMGaZ2MpKVbHiFCpaJ", + "9YRoZSnJa6LFDqFjkwg3tNlELDEjcj20ehK/2mtNZ1vpwOxN434MQgqn6jgvJTQ3CC5oaSlYGpTSdbyGg3maa5Ufur9iXYzY", + "k2zyoFblPSi+mMX+7ylELZLqtPWPaSAMJIdmRi5SEAkGU8CV8vACHbSbrvlDjBRTxcR2WieXXdaWrY5UApS6bzzGSiEcKmJQ", + "YavonsL49kl1O0lvXddiqxzk/7KvEjgDcq+N2GqsAMc6Atwk3qmANhr4uK2tpzUPjo032Iw9w8tV8ADrQOF/Ylbv139jGigI", + "RdJEQeOx251r32N9SB6zy+lJEsyXWCC4R0ppOLy1xvHDv7JyW1neTIBpbbUuyUbvUY7AYN7bEK6XK0Xijc4u6+EpwrYjKiPD", + "RPEnKc2h2jY/tjUOZCogG1oun0uZlcDm+pk9a46ljUBVnuPYvME19w9L1EomfREs3WJLYJiP5SYdZ5u1c/hsRYmes5UxABBr", + "LHEnOkBEM9sbSi8gXt+wdhwsc9bJj5iEBhycxDtstZLPUwNkYv5uzSsYVBXBpuK9o7bGen4qeaIbpXZmUGunnfuNAsvInQJS", + "i2DDtlTKLJJFQW7Wu7Xx01A4DpCYO/aJdnhJj00FN9vkMLbW8oc/sOLYThiVGkLI2mqSDJfrYWo3WEZwz369DXZfWVU22NIR", + "31kGqqbSdauosQ0267Fl57a92/7p/CdxInCF2EU0KhKMXhLX6YVjdcWa843U+1svYgayTFI5jV/cQNjwaSLDfZeX0HQ6uR6p", + "Q8sbbkAvX1ofp7ZAl1fiiOxh7mZYEvTjRKGU+xVYUay5lHzkKuuXSqDzB0Na1az5GQ6QPIVRwxI3DN/xChCQcM6BRdyd85iy", + "HVXtGxLMgRRgM2QNjH+OgtUpwc0qcGm8t3aKpLDJggoYgnJ+QNS/+A6hXrdZ7ytr8+o0VtaHJEfaYJUgICYaXJuYqBkjzr9i", + "TQSRVF8p+mRtDNpNdlqsSJMVy9Mie+rYgiuSj4lePpOSB852atioSG0o7sWQF8dQDYJS+umk7E8kOXm9TYzMObaUTfeglabU", + "8l/5pc4WmR/LYXCG27BRGx03TqV+Desa5Hrox0S/UnDTsJgdjWwaBunvhqaxWcEO2JAuCsGK3U7LOil6mURSZOAra7HvsX7h", + "3RZr7KGjgKV5pHTF3/yYpLVWkGGHdWvtsWjU5sJ3VgkVWOtC0eX5mVirjq1jYraFAExhzep35yvr2tllrXJrfhjXUjk2HZRi", + "oRgdKGL1tNlCNF9YPCi5oACZv1eHUCwnZEtyGN6yRHAixYKMSL5CjfpW6nbH/egT9AmCrAF80hXI79C5svKMF0Zh41paeqEo", + "nfVSBXm9rbph+nWNBcNF9wcBU9TRUirWtnbSO6kHHVutx5Fa2RCmscMEZiml0Lk22k7xvUIfSZ63sQmwDr0ROij2Wq/Kbi1J", + "2wOihLXUQzJlemChlhL6l4BkXamZQHXusEoUtafZmfZTKtoyQRvFIPaTQSvyeAsRNkA5kmKc25orJ0mVbwYn2qoTLVJ2KKjZ", + "WjSxaw0HMjp7F1wX9trjBPo78aKA5ZyTWtHaFhTyADXa2lUmpaNJ94oV6ZQtXX8lJU5CqR9gkm0B3SlKlI14PWheCfbN9eQF", + "hnpeJDiraBeE9VfRhv4QlZR3Wo23w7qObc0b02qVDYawBtN4IxxRghVd9Ml9ag3Nol9MNC/BcXgZW15Kd+blWoLQK9py8rDV", + "WEoIPBVIvnYJ8tvtdj7Hy/NiZEP6WWRctQVAlCN1rVl/DUvACvYUAuL/cgpitsS82cyh9Uw177BWgsPgFsH6sVQlWStyxAoK", + "iWinROoBB1HqFWO6WtDZ5+Ks2MTDLvp7YEFC6W237mGi/kgeYIjRgOVbqRAP8Cw17DxeswKRYWs6OFJoRHufWb/3J1IQypEb", + "n2q8OAh/1cTbBGkqBTMkaogQg5Xocz1GRlDiVT+gwe2Sld3KqnXY7NjWXvoYyphnZ9gAB5omZe01z9YjMCwO7IBYrEuPZTa5", + "xdSNWAkldo6lSCkAgEehubzITWUhy6ytL8X0WZmmmFoPlGOLXvTsZrk3U6O2FzjVh830vrbHHhyuuBQiHvLYM0VHnAGuTgVc", + "OJ9be9rm87doGhNhUtDiW4Ms2MH6aP4+EhG1fcV3/9gh/yPhxfRLeYCmji005oi2BWIBscgKAps63VJfmOdArNph9lhQynsM", + "iCMTeW8xFef0gNy5VLK1mKADxMZnbBQsWanirdfqvBjymKaXTjSKuNFc8gercNjSZ228JYb+AhWSWWxmPZbSIRprzUNrbmgV", + "p1FrpxQOtoxHrW2lDU9TqY5in3X5bMkjw/Kr+LGeWfC6Q2G3Q9C2sdWnnO2pGJprNYz2WqsA7Cv0XdWsWlGKPFal26tKpM9t", + "wlRbqbYgWL6SCi2gdIZgyQ2UEEi29MG7n7EgUBAOaocsscOex/01hVQ3FWuv0LVCXSUnEw4kvuFYIOJowEnV8PUbhfhgTUVs", + "HbSIhmQ5WtYnobVBq3ANJkBVEIba8la2apjZzhoPsdT/4QE4+R6i2dIgL890WH4+ht6Od1s3Ux9Pr2F9ii7P5615TGgSstyN", + "w6tTbGki1sMB34fyn8TGJOYcOb6JHdYIpgTF68JIbigTqoMMqVVAgWIQ8HYLHXfYshCEB0C/Fo/n2v/T6XrnnzvESHO6I3GO", + "OLRdwUdytZvnWPRLs8X8W70YxxoXEIZ4YFAOB11jq5/x2kqWTuGNkBSAmD+Xbs1HKtLNcWypuB/Ea7fBFhIss9haIdo3aFWd", + "nZjHWm37wWOOF8E0ia1zPO+Igh4czOewnwUxiEtS8T3aynXDWucdcZxZd5H5/vvvfugc9AUCREVTC+3y8JzUSE1STQ8niZ1V", + "V/bGKhVB6hhbwM4aKl1gp15ApW3WC27N3Ly1BpMd1hoUgsw5f/cDgI+KSWHFFnjnWIrdKvhSWzcvVwJssMUQHVt30EidmKgY", + "siaaCnbYk2zWsguU3FWABZHbAIJam3XxtNkii13tgd/T0pJ3xL0IxiMVQ/zS0b9rzScudb6cAV+JrVZltcoApEfPXpwGgp5j", + "cca5lhsJClivLw0oCMtk+qjfVk/c2G2JaMNa4TTxswIBS5F31mrG8n0ulUuc/+I9q15trRoUi/ezM/Gle9vlilcj1fu72gnq", + "iG1sPUcCeEjhsl8h1dCMKGAbxY7Ls84/S4PD3uS1jpxWEpm8vefRE+dDlcXSkpqlr62+EHTtM3vSqxxhhU90XBAejf1+ULKt", + "h5hfK/coxf/Wjr6rvAQS7CSetNix8tOhjxMmHdAF73ikUxRMEltMJGfjjsNTjwrvLvVjkbTQcX7yXxb5AwtHoR/Zeo3OWnnA", + "NT1hSxLSNUpvaK6VF6ltEGdAwMNtShRbVW1t0Bv32KgBLCPvGHToE+/OOVaf+aE4A7rsMYatbPO3nq7/3Q6RSBcQT6QtWDcs", + "yBoD3ooSljtWlHmn21mPv+kOlWtr4wQrYWvBbN0WqwKQHKUw5u5adxGri3G2cgrYZisGbgQpUW+w+jK+o8oEq+0IuHIhS6nR", + "GVcSfWudt1IVn2Jm7SzSajxMnbW4d1gL0xavMj3WbJWVoNcP2LMQ2JJ6jkRWYCpiFeSrZmvO+Ytjb45JQE486mLJdmyqrbdo", + "pMg+RsY7ROjG8Eg3hBWCEtB5d46KyJ5JMc5juyrAngnt+diamBF3A89gEzmC22YEvtpKdIbc58dkXfoJaXaDfj5hxeEo3Lzm", + "uXRdogtbJNRhOX4enVqY1iq36G2oUpqhe+uTBZv9NQ1qWMY/OTkiXB5w0u0KtEanE+hRLGG6+hy57XT9n9ZDHVpE7NgaalQ2", + "HI6ts2d4uTJ3hWfeaq0QqNNlSYpgSw4h2XIDS7aBEUguMDHAtLwSOu/IuZpcYCIlOvF7rd3yb6EkyAeKgRv+qb3zQi4bAfSz", + "8GBzdZ+zpbqvT24zycutSI6yFVTzMFSIWCw9t3WLT66T9EnVJAVj87ZPR1Sk021rt26krcOb6WxhQFtgik4yBiDxOkxHGVuz", + "1JMCgrGtzd/iUAlHUmWViLpo6YX6MaTH16Hbg0tOdWXPDwctrBgsixeWZ13g4kLcw/s+rS/HsSfE3aKkgCBS2vbaN+I/U7JF", + "zjav4sfi7t2nvU5b/db53MYo7SFdb3QoSWI/IpbiEWIsChb8ztKJ3Tm59oSFoOxhMNGvkpmIkBX0K8JYbj1wsFgVIn/ei+Ww", + "phl4Mk0M5JIp1tBtUYoIAr9A9kRipNlCaUaIL6TDDOxfIWziwYovINHzxam9m4ezMF7FM7fBFs+kP7KKbmych0NioFKgNcEj", + "V547G3ctzIDFrH4vJtdGQw1bBSsZurlma0+adqtGd8QRBqwcW++RVzBwYomYgyIgsA9aNF3rd4wdg4wTgBVYU4+XVUGj7Zb/", + "5SxP5+SKB+UwySOqGSIph3fF8BKN0B4GxxUrwdKCXMEQa4llIxQDRVqY1iPBj5iYlht2v7BHBn5oywFHshh/Z0nW9eYLe6wq", + "RSZVKMcJtANEO0JmEbTZcr01Iiu5Hlc0nq3L+R1hPysBSg1V8KBEhuSt79+RSmEb5N6mXE/KGvq5HqeXDmU6LQZEBUD7QltB", + "f2L/CH1Z8BjCBpO2p3KOY48j6DIBWW3I7fzy8x2RDTgUPmdchJg5zn/ZsA1bU5CHyBJPFFH9DloI3WlhWuKtCWqRIWEFBhV9", + "HszqIR4Wz5elnvWiRaHBpb6vt50hXLBvo8SWCpNaYdYu3lwSX0x1hw0hya/VobZlXyVYocwDWJ47MuiQss6VXkS38aTCsSFc", + "jB0wNBXKUsyQ8VmcAGSDjYXrLlg/Hw0paMzubodulS5Lri1SbpRnWXJUK8y4Vnw0Lxg9CqnYoT7z1ofIMyxaNqDfYhTbArGO", + "rVWIacs9Y5GVkbboX55yUEhMIrR2WG+9sZWAOWjMhkQKjibKwo5acc+9IwmTTnzMyJ7/YWFZlJG0C/gnJQwZeiIwzR5bfVOw", + "8AA4mFc9fGrBui0BvlE5cobDx7EUX0j9P0duANExb31n2Wx2rX6vizsYid98gy1ibFGFiBrMtc0y4B6peylLK7Ai5lZZK+kb", + "W/96o8RZSNipH3kb6XO357fWryaBg3K4vhbjydqVBK61bTYQJZFzw1q/xRqigte1kJuwK4qhV1EYpixaGuywAY7i7GdCkVBr", + "FAuQoNcGi4rmG/GhG8t9ZbZEXpuNazZfujwq42UNNNIsBzj0fOGBndbroOnUI2IxZZ6r8Z62gCd3gXUz4c9uP5GYFQZYDVBO", + "2NBSUShrxQ2NJboWa6TlfZqO0IPW9LJ68xvl8NIxgKF+lry3oVAbiagxsW8sgcplYbx/hCuw0UbbQcHKwhSE8SpyhxzUp9SB", + "d+wZn0M+EzVhiI1tDWXH0pkRNBHXbJF049hDoj02fglChltnY8i9otx6yIN1coccw/sho/QAVKig6TGzLnFeZ8TFYolfWD72", + "YFpigoJAbthzlC3e6diK33l2TQ32mRJcwSPhNPkECwgqEOu6UOPxmrV6eBrm+VI4uiBhTDUxfQJl9ZiRWpeJIY+VSB70voax", + "Lqbm97rSTvfXvXym1x6T2bKYRs5oQY6yAnlKC7zPnrRv5HWQPIdNpV6ksFMQWPDUbuXKN9/YuqyfqBgiz2uXO5esjBNMSe8q", + "Y70YcMEy80CH/TVsnvqaGXCelgPNdS3bElb+VXKEndp7tWobeU90QGMLf+V61qpgym2LjgJcpzcc1MOFlQr22Ly1gG0RAg6r", + "ojrftdj4I94HzUlvFGak9qJ3lJba33n/tOaOu0po4hPWWqYkkqCFtbqS31miZRwdfR5FiU3lgvCOcswPI6vYtzMgaZCxOEnM", + "HEdesoWVFV3KAVTouObaR/HXhpEuXdROBNasS+ubNhslVraePZbDxFtofcodjJoHCLyOjf7dRGwZam3aS3KKYXwbXFa0KmF7", + "WgS4imx5zi5xvkNex9z/aIc9MhArxw9tDdC14HFRnwDesG4HAPZtdXznB16ixRM2hx3JjToq4NFZyPBfysH2JOW1jyxmy4Pw", + "XrBeReJ/eQzY5nQppxzb6xagrJ0vvtzr2HL6G2VPFIRf7Nia+XTTJ1bDiim5rsUq+3zZcoeMkKdgPo9ncmTOXE9UAH5i+WKe", + "aEc5qoeiL4oda7SLwVowxKSaux+KJU/ZDNJXLCKf6L/yNi8d/w997+84hFNYbYYgSPgv5bRjbJQeRkqg8RcbjGrzJdbUtVPw", + "5e5KUbDdOSyGzCgRu/orSbfYaCtAO7aAtmPjUQblHlhQJ/0myqlan1VkBXyb3cBOG3pki6k7tiqyja/Qg1Wri+WCJkfKnmPS", + "ypF4ig2+KLc1x0KnPfvW4f4ag5PEMUF5RfL5zh4LcZSqWsMwyFf07IhXnT77FrlojTpQfOn/O+3o2LJDic/QURLp8Ic/2GhV", + "4UxI0q7eHV99umfvVzaAxVZbb5eg82jf9tqn3obcPkkANRsH7TEnxmKEKIsOuMyW5XcsQDXO13ToytlhWUk5cuyRbHGhxvLa", + "PFCzBx3WsPXabSF+ez1XOBAFxCh4A0/5lGXYgj2+/9Qew4vHuBTxwB4DtWzk2DiyLuuzUJ0sC93VbsugG4mvUolFDjYFINaO", + "rQEu/N1eVo7Y7FUbXfsJ9VE3PWRcZ+ZFAwn8TUnIX/c//9W5oZja2uSmvUfc4XS9QaN+atdF+KHrHXsAZBwbErJd+30SWQUl", + "+OqaZ8P2JSNbpxCo/ZDRJaX9ACYKhCP+to43RVNL9WlmP+D9ib0EpsLUYDeqvrpektsoYXIwSFouVIncJOUVVKmECLMLkr80", + "UPYuBya1m39nxCuefb66z/gJ11fGfqdsDlVk0/FZpZ3pvjbuQoWvFvBcpJj77TFLmLG6FQyiwEsfqdlsSnxkb5KCPdwnNpFg", + "4nK0lm8uWUVexHLqJcaIyqUbTCXnFX68nZE4f8CGq3Kc0asFXsUcie6IjE1timySkL3CSbJOYhag57VOfoQB8ZakiuS4RzZj", + "3GjrDJJrtZj3gqWKaX3qV7NRImE6vDLK80uRXEnhyT6gM3EN+EpZZxxWgtlTpZQO/NgWADBrtQX4l6/FzOeFREzkgvB7NZWk", + "vEgp5L1MzDrnDUgUvX1RUfSKkmwrnrfxOyURchDSkuFusGAMhsbo/VePQwmbSiRfFgO0Sfn2ygPDW39cVi9wXbaE7YOpx3Jx", + "l9yfy6hEXuoTv7pOWyf21yoTmMravjNLfwo4D3QTKrvkUpQBY+HtQj7vtqowc5wS59VCKFeERXIhWIXXhGFZlVQEkHh/xlrI", + "bdkVe20zbTGe1vMwnX8T5DMuCzypgKPW0pB4aaacAPKki04XuaM45h2i9paA32+y0fts2o145LEfdKJSSnKrEjnZ9xiCU1tL", + "RDRrUw7WEunM/jaJdti6lnYDnFBk7o22yQsJ78di2j0rrici32zKiFnL1vGIX/mgBO7KfH3J26L/iY5HRpGRnplZxVB0G0em", + "Ahr3RJ826EjHa7lcQI9GEuhoy4M6Al7fTKy/lrsjwo7qdC2XzkgyAYFGWJN0JVUwEl0pOXo81x2wt3HDmFf7GTsmERSML7TH", + "9OL1xIsHrGxzutbOkmmAMzaDxw8MREuikojCtaQcryC3B7Ee/aBYGmv7Jp42OvLMWnbSZ2v7bL07zJu0+W1y6zXfD3nLGIkK", + "OJCBM78nFliFHdTkYJ0ZNHK7a0y2UFQGRS73ALNZtLhvJSpUbqaRGPuEaUb/P1tv2iTXeV4JyrtR3eh9X69T7WZhXKgC5OkJ", + "N6pQDhAkRcgkxRAgq2c8PYpblbeqLpmVWZ03s4CkpAgQJLiJFGVbpGSZNkURJCEIAEGAAAFw+wD7q4L8ZDDmizuCpKiJmd8w", + "85xznue9b6JHC6oql3vf+67Pcp5z0DaQVSBOp2TsKmQieVywWq6kghTLn7y6s+nbVkQmeoeiQaHMRiwqxbpKoXSWtyCNYi8w", + "zsj6U4yuzVMY+PZ923aoHAh/H2YRVVqHlLjcxPgDaoroHKx+zANi8W1uRnUjggB25RGyiJiPfC57Zs/PTQjfsiGUtkHV3a86", + "EMQ2ZxHXUA4FXoW0ETCfx5j6XaIcJmU9XIV6rEJVnG9ElaFyBshIr55qHGje3Rg0RE0AsIP2A+QKN6zc2sI5sOFFndKGWV6y", + "TWnMMJkKBjqF79I9baJmXXgRosfgJ4Spr9mHKhaerouXH3BsxJhXR0KK2X3X690rdX/BC85iHWq6sb5Ixoi329YLDhubAMes", + "7xEgIt4NoqNdPCSWg0TeVlfZNff6OgFggAuMGif9dQ/wLTsav7uviMLTEeXYgeDHAjoc+4dUAYaIrLP+E0pa66MN1T7bPGcY", + "kUBU7qOoq0XYQoW6qxPKxYPeHgvVPklh0rXK91XOT8YqNiB8gJ5E5Fjrf9DDQKs6rIt5ayt2pIBMpxBCGqLFEyZtvFSokSJP", + "qJr0JgCAYL0q12j7HBB5W6iVMy91hK2D86NLZXQiurRP/wfBm+YdhbS6vGQG59IINTDcj1TqVUHQmaE2thYl3o66pXihPfvd", + "1nmwzLyWuvEC7QbBTEQpBZnAOG4OsJ9H3TgCAnaKVkqOdZZhjcEVUulrXX5NdTNF4aWK9/i+IY6h1REPa6p2aF+D1wO72QN9", + "M17j29A+NwuRtVKQ9uur3EnKBNZ1jMH3HB0PnCUN7obnnSoCuV98JfZ/1cl0vWy7QV4H+8FKbfse8itQBavWhbWqgV4ilBtQ", + "BaZ//ZyZMKFj8+5+GWo9AkZQcE77TavL5lZX+igLy17n3bC8ZKYoHLLWuHrdJCrfHEHelVYX1r9QqACHYp+3VWYeqO1fdjc8", + "o+aNzTczDoTAY7h+mS6wjQwl2/k/7Jhm8WDQrdMc5bZwj0o3CulIdZY7hfSXilmtO2g24n4elZ3h+T1cRbjSOqsudX5gEGru", + "k4teZweTG7p/tBqwroEKAUrD3D5s5V5sLO2QfcXnVarUkKWAMSnbf/U84x4yWUteOeKYA4CoeA7TT7KfS72a85plTTZ01O1m", + "4R0CV6vVkiJ7y5p/iC8KFiqUQ7ULAVycew6ULjYlfThahYdp93Yc2T6uPzuPHSnQ6dUPcYZ5GLHY5W6jF1t1pZszM8PFZguH", + "6sebkHPvc144i0DjsHmGE7An4ZxEtY9HFCc4i3HePzDusuLRS7DnkYbGdQpfwKpxh+IeQfIduE2luUkSeqO024jlGTw/oYFU", + "8pyaLxQW7dYEqxQqfVitdsv8290pVLnqwCgWEWL7c+ieOwmqfiRQqpK7yH3GFqRXJYNxioahzJ/eZF9xG3OAtwkMdBufNlTh", + "sM8Si4aaMtZuFDpX1yZ3mQ+DM59BYBuhqOJxFHTj5bN9ohoI8N/m/PgaCprLzSjsGn7d2TG0D6xOnD8AgQqu7LVedQx25UG3", + "k3vl0SHnk9q7LN1JKlxxvIusZBbryZxWTONlp7MwN30TUJi+E0UU1PHCCaD6xGbBgwILbgCLzgL7znA0XvfCpP2dDueh/XEU", + "uzNxGdxou1QEs/WjrGen8H20i921Udkf98X/CLXoemsR1fJ32LN13EuH7wCdauHZOgXmFmaQkC0oizQLXKqP3PcwXAjdOs9D", + "w1L0Qd04rHFmh3OKOBGHHR62OmyfRUgJ+xvKVWkDM/dAxUaGKFWFwnWwBUdvf0fwnTsdJON2YiP1zE5RDb06vOsxzsnmFtDf", + "IC1BFA8OG+pT/HxZopofDhgBexsnEZmH7hliLIXiS/uDPEXbR2d53gHI2vfAAlKrEm7cW8cRNe9pKG9/10vYCy+ebe5U/SNU", + "jjAPmy/7Pt9xkLyWG3Uth4iLOuNJU7odxBpJa+AdbjfRQbUHmC9U7D4hoqG35jClwkyyjdq8FufoKFgxtFLD04cfN2G2lPX+", + "2g+RDUPQVLsYqhT5/IVjjxsHChdeR1bt/r3f+0//effeDion4Eu68z4sgquDyo379ngGYQQfCXPZCUGa3V6DxBCA9aNjfQq6", + "ce15b9MGQXFUuzDf0vH9bd7Pi66XKjfrqGg0f3Rm5gABCtBAwj7G4NESSABWB92E1+wsI7qEc8kJZgDcHmGjecAmN4JoBGXb", + "cziIfR7kJKzltH0c+6hXKzYqlpzZoeIdzAux7Xg0fnE0EDJjaYE46uXBgz3EA0ovfkM8jlXde7zU1BkQmq/4vHXui24xe9Q2", + "uo1ivtDzwQ7BPkZ7qi22HjrFSuHzqfACi44TVhTOr4IgDe3DRackWPTirEBDaF8re3M+/wJBP6/SiY55Fyy5WfbwHlACq7a7", + "A/UGborRhs1He5AuHZqm+o8wve125tMRlkfxWrs/VxvbL2IUB5MGmqZgs8ruwEtfOohjmJ3TW/J0uNcSLi15EuXroIzZar7p", + "1CGNk0fEtCy8srOg7HYf9r3ynEsrik/2vByq8A238Kp5r19ulhRLLYJnwZlYUBZoe7xAWbCr5N/3JrucjGJUHmNpBcpA8L63", + "e8Y5Jxrs8uMbZxppMx8ZFO6oan7tnDGzCfqqE9s1rQvrhl612dFrNsknQGgOhr3ubUA39bqo1PDh2h/0OO5vb24dWwToe3fh", + "ddlO+tP483S3S9nrdm5sblEFWfEBpHlYVKXy8dgm9/A+nN9CRy95QeXBiO8ggLJWH5vxheLHW7HkG77TZDTMjwE2LzqYonDD", + "ys2bgiXmtm8z/QNqA2eDiVpEZsIwj8T7sx7V7oJ12HecRqmwnjebYFl2EPK40t/DoqF9pOJSxSXQVE3Lxveteal2HqI2qfX/", + "BE5BvG/37jhf0i5mSeqmcFaPhv1k4+TUA5g35qP04fTaZm8zUtig/djpYCM+UCLjiywQ+FEa51DpLK+Xm7qhypYLZEuw3nw+", + "FUiqE/2KXYhxpa19e7eOFfP+Aa9WaRxr/IVe+dAEO2sfcTbrIPYv61+4DXRo7dh5LqDW0oK7m/7+vi8seKDPucMK91sLZbY7", + "hRPeeDradgqHkTmJzMyspOB2zUoMbteGGTej5sG6drtxONi88eP+Xz0yuvHO8MEbr1VggAOzG0OkN37SJ0rMzEoP4rt2NzTT", + "GQlv+ogsY4LTDqsHPo4Dj/bHuijXBys1HCQP4zce4IaKHgyrEvsQzk+EbMY3fmLXp72N70/IkKpuGGzduA633NZ6MwBvqOwL", + "nLvcJxA37SHsQI3EPuJRCEaPEPWmf4HIBrhoPV6Ghoxqa50nFBraWzcu0c8wz9SMKUbkm3Lzxk9g+G4zWmIbA9iHuqQr3aKj", + "xoLVcuhFmIMtFKyhMgT3tedh0gJhUF/gnmxo+D1w6d64NOyaa/IQsiiDh8pIjAiASxVRG1gx/KB9Zc9OHICflDLRdmzj5HFf", + "Kmvic/536UmDxvuvJHdsvT0o8Ye1kZzG9lz4g7yoykPAjwfnTCQrzC4k8gS4jgHC7CU6sV+XiEvifp7isL16lYy6pbW6RwXs", + "mu+vIcqC1xmBh10T/gZDRY0KDDjuyN40KyXDW1UwcskPK4cejxkoSoO/4Vlq/sHAe+DGpW0kDBR/Gw1GN36yCgPD3n8ARMnU", + "lLf2Kx1VwnUdw31CAgQNUHUqihes926cQ5Jgm/0jHjv/HuYRMzuIuw4wn0nOAXXkiqWn2BPwi83PG5fMgRkg0sN+Y3kRROGx", + "yuBfiZ3XdiT2E8fD+mmwpf5nHqHG/WnvDlBMuW3XgRokrgewSr1SDz0uWNKu4boiQLYsNU3tUzfOIRDZvXEJZZTOj4F1x4wK", + "OKlvnBsg9b0Kzhtbudh3ze6BvWwOAvpnBZEYMDsBds7ifTsPS40//C70I8XMh+ulyrMHNM4wuxjvBPpQ4+GZnHPmHGyTZ5g0", + "YA+BRhqUUSPGu1n9p0QT0Ck3zoEdmEzZFZfv+tg+v42vWbtsmYLxONh9G3smOxseYn7mxhsl8iOAO3sCSvG2iicBlVE9v9io", + "ZNLWpS1ewKX1HIAcif9ZJb+V57psHqh/SmffvfDB5Q8fBpMtfn544sOnEw+w/cTfzib8zgfP6XOJuRd8vGDTJc/whyf9c9d4", + "TXAL6zpXdR8w3/Lzfj37v96/QKbhN+w6aM1V+wT/xmfJ2Pse+XivWUsedRbid8VpTFbg96w9+nkNd/rwONpsf+H+4j9+R+9/", + "+B22/Qm//1WwAztr8pvOASzW3gvO83uBbX+D9yTvsH0DjMDPgtEXf/GpT4Bx2a6NluP53uY18P3L/J49l7fP2qPPkEMZ7Wc7", + "0D68QgZk3OfbHz7Gfvo2RoOtAH/wm9ZuMSdf5tXe5HOqny7a7094f73D8blqz3bBGZsfIQvyBfsW2Yrtt/f4xBd8XL79wVvk", + "Z/4O+YovYZzIenzJ+++at/oE2aXftc/o++/5817wn5g9x9mjV+1anBd87WnMG84jMUWTs9nae5U8sI+KD/bmGbCzfnSSvLBi", + "jP0JX79ARtRHyX571k77p8Rue/PHYteFBQAuV7LFXv7oYed8bVlo8c2n7N0n7JU3wcFq74tLV5yzr/HbT4Bn9ubL9u5P7Yrn", + "ybir/58jeyyu8ig5ep8AV+vNKzev33zL2szrOgPwI3wH98dVXycD8KP2qdPe/kduvkl2WXAFnwTHrjPRvgZeXbTL3nsVHL1o", + "qf18i8yy4Islm67aj1Zbi8Xi+4a1/KQ/78NgsP3oBLl5T/J6F52V9ydgyLWfrztj7VPsUbDhiuP4J2CSxXfJtotvnkV/2Gdf", + "Jkfxk84g/Brvfc566Br74Yr99abf45J951H1J3h8+e3Xyb37mnhv7W4/CR5esvNeEWcyx/Rh3d+5es/Y+w/fvMLrovfOs28x", + "Lqe9fa/pfbITg8eYPL3k30Wfn5RVaKP1svfv6+Rsfs3H9DE8D/mbz3BkTpJ/+Dx+07h8zv/zS/7fX/b//qr/93O/9Mu/8qu/", + "9uu/8Ru//mu/+iu//Euf+80dM3/n7+78e3//7/+9nX/378zs+M1/8A//0T/+J//0n/3zf/7P/uk/+cf/6B/+g3/xL//Vv/43", + "//bf/ft//+/+7b/51//qX/6L/9f+E/fA779kP3/Z//9L/v9f4Xvxp//2m/7fz7FRv2JN+bXP/frnfiPiWoqyogIlMuSST1Cs", + "eHMTFUATO3zqHqIsJFeC4X7HkTsWjpGDiZAycxRQpol6TygdVKONtjq7GirmRWKpFR7j5sm5W4/gNUCyw044zOZnMOa8TGoO", + "GPGdwqt17LweKy3DpCUgegMPaylsUfcm8ufE2dtDTKhyEgrQ5qNCEJxgnmMu4pdGvMJggx0Nx0z0A/TCDH4nMlFbqNRHmRBA", + "5GqG55CdWc08QFQvMVKY4BPVMQA6wPCLmDYzafJcds4QnY3vI6VB4q3b6wHzRpNvBfAy0m8NMW1woA+4Y9kEkqLpwpFFLLsp", + "yRIzapOjzjRgFgxxVmZMELcASL85tj1GZJ0Na2lBXJ+gLlTs0W7DpKa11kbMmoH0L17BpQSdeqjqxi26pKzro27MnoWYutGG", + "+cx9mzr3eTKtmF+zljWzuxZhv/NxNut1jVfZh1GzGhR95jKKMYWkrg2raUDNB/dzuxKSDe4/gilIPCJ1gMTgRPHEOkXKwTtp", + "swexaeWo62aTXDX4TEWVdTPXDvSqYwzdl1uKvHUDiNIQt43QlLOj2URaW0OsEskthdmXWcGK9wUutl8WItCI8h4mHxxtu7+z", + "EqPMzN1R0PyxbsY+AyjnjdfKurnbJvbk6GCA/F0pj9uBOI0tEBL8zLCaAbe/w2xZ+N4okSOKoXvQ3A8W04AzDhdubnecDwJ/", + "a2NccHnGQ+zhWgbfEUAGFWnFCkaFUPZON29NqvaOBa4Qc9hCuaoyFTMBeWhYZYPB9fxC2RP5LWkDHQfg5RadBQflV907Y1lt", + "oQLqUH80CzkVBpXHfa8ntXuxyTNKU1oz7rPJQuxgxcQr6KvFpFd1R0cHBRgbGhXFjIQVZOW6Ux13lllD3i9RlqM8Z/d2IpZZ", + "FT1Uin7EhCDK5OEzIEhMHlLUFsbTNHfCmVqxGyw5WHI5EuX23WZMhG7Uoy6qINyu88XKZwJcIaZ/zU2yizPvvsnCqyaAUfN1", + "n1gC0p8JA3Qw9mcHL42bQNmQzgXkf1XgnRoWRmA4+wKUo2B2XUSbnDWi3WWp/ArgzUzXTJwSrjdBdSfHNBLEi0IKOERJ6TXR", + "Zdu+Yfs6eVPwBc7ymhkru7J4OEHJgNWGEC25nvCoABRubQxARVltWudtVQEOaohqAoxiV8SbQcnHKyshRz6pzcEqUnEs+uf0", + "OzbSdtGMPSvo0XWk8ZWGbNIZ4PdC+WDd5YyyNqO6YyV4ym3jti1OUUzPUncDXtVE/nymGTfKuHsGo9jTbNVDnFy9yIXPbNag", + "7TBPTVly6zFn10A8GVWzNoFEYWaN94DXA2Rrq0A77jTM2HsFcupi0+eO7aRaZK/VgBEAgQcUOTVS+mCPiaKVMY7+L3mwsCDS", + "npQOHn7tlr11nLQbmwFwaoBJIbmzsOH9irmR8VBgLSyDyL4ojS48jJekEdinzNNsQEUETZPBIPL8XYxKrm4UgRbp7o686F3V", + "yhCshkUkcIvIJO4j5AGbnS1A5rpx+KKCDpZMD5GK/R3NzFUwuZY6gA44YK6QPQR2g2Neanw3OuMP8E9kjQNlU2wSoGBHCeE7", + "JGddW9Nki8jkDg+xk8eDx/G8zVknS2OBbYkixYF1+9GNQeAUPTDUqE6lhpOuVCVzkUJBYgJsY0/riu23BiTAA7LzTtAy61R2", + "QIIgc2EtxDoj5WLCPOETDD9FFq4LUmAaHLtji6z6GCMA4Xs+NxziBozCskinImleOLds1b3Pw8FFnFZLawA3wLI65AjAohj0", + "V3rjodl1Y2aX+YD1lrhAGnKRFfda/7GKplwZyMxwdl+vLwRsvUIXwLwQpbTtWn2QHxDl190mG2WzdcyB/6u+MXbNKN3fMXum", + "4wg7SlSI1LYIcKSrXAyGgRZrPN1XdQ8DvYcnLLtdJqRmY44UHqKvWNpCLiQ3SsEdbc+B7f1wbO/gLrJuoWjWiOxuwerWdWjX", + "sPkSwup4PPAesFBF2xe4tTyd6jVx1loAnhFYskdZqUEeQijIOmy1o2SkBg/HsUUnctyoQH4PBibCRcfDyL5VkeDr2jFR9sXb", + "4FsTcnc1cKBUIUB7VIlsK+IOh/VMfO+lsAIIj8wwE4GlmeiEpBHzJGxWo8IuVOc7inc+ttOlNaLxQJWB1Q1CKNCPNySWIkF+", + "jcJ71AfZEVQEaoaoHBCe8MSCQQ6LrxSwVF1YjPvOAWjr9EESbXQKp6+LZFclehZySm9WZJ4K3NJkBTsnUh1l4dznHB3MSuwA", + "/dHy0sJ9g+FRO2RhMhNdxGGyLc5xtfBOhrOBpIA9D2T2xDmAQc40kpVM6BbRDX7czLtaAjZ8eTdDm1jbHDggKDTK5jKwllG1", + "lKCrF2EnKphXBNMppaxgi5enln3mQHsEECkEeT6HAh6ohzh3bZKxzg11mWKl2K5QcI4OrpysoR6R68UzWzjBRBoL2oset7gu", + "lDiGg6Nkh+LujrIsUUzYfAv8bbM56IEypWqIwbc9jLYoLXHQa7LCkuDzDbOWWS5HvoXKNzRSo29hFybbKPAILCBi1ZYgvKog", + "AwMIk/oYZe4tuE4/zEvhNe1id8a5TAI1THzK+zWaopt0Iu4XuLzskSQd4489cxUWmjmqIB0ewqQRPkLUVoDL/NYfHSQHZGfZ", + "URiHHVxWOMuCbZUVzmv71nxxiBxKyLWp01TwMEIKVlDCeWGgBIoiKLFxUuzeZHc4qLLZaPyPnBjHxn+3YDZrbmQjV4hOWK9G", + "B1lNSq8f47W0oMTiMkugNr3YuRYlpyzqRkwDNB2BBaapxv2+PyLLIdJ7giXV1dGv1W68mf2nJxUfg50ReFqyffyhbXoPjW0v", + "nRWBQ29CmwzutNJ38OuExwR7z7ZtawUY9bY1bb5WP1hvYbbKuiC4RJRqE1kdR1EoYs3HSR95aAeQwT4UV3M5YgKNpwzZkYYo", + "6eyJ3ser3WnXkZq3q5or2GOV8wUuR0r0EO0xPMIR0Z6y2JWblBcobTYs5sKBcRd2HTtsSUzB05w2NvYphOzZMPSKKHIxazGm", + "R8LsUXkDcorYhDF7+rbvrwMx5Al12xy2UAMGTCTZ3EkJ3FPlp5jBQfQf5zpa3AV5n6Yi9o3SSyydVQX07kqCF+L1BJ2GfZqb", + "flk4B3gP+1hDuiSGZgZrX/ZJWzj1ka1l+ne1dJw2cXCYmdvjOid8paFZ4moo5MMgpz2FA2wufSOwmCqlJkvfuu7lkk5I3DIh", + "af7g5roANeSaA2UX7G9wT1bSn+HXI0mOk3xUbm5BYIN7Lwbli0PS8q6X9JJQ2Cz1DRCSdIsSVYMYsUGfFLgYOHzra/DRvAKc", + "tqjwyEc2aJ8PQykKCCQUJgMq7xDaRjxs9q2DYfvFc3WdtLrCWqxI2b8UyEZHtu2ccTduFQg5HSUBSlguWahvvxdFSDw4zhQ4", + "kDXaSLsDwu6Ui6CSmogFhdw7A+s6mqY4NMU5jJ1R1eZgARiy1LH5angK7gHZPr/OCrRRRR4ALFFUKOqQxKaOiztX+lwAQDrL", + "fi9CxxXWq0T6aEuYghbcE4A2ECcjvEqzcpEHhg17cAMUYDVYO1Q5YDOVCD9wtDU1FjOS9nr2mYApKIZGAgkP05FApjQDg3Em", + "RiFIMbENBxy86XZBsDA+CDUDrGkUh4TggFm5oDcDyL0M6MyS2RE9cDyohZvg0UMA1zaZmRmnLnYuvdFAZTkIXnndRLMcFURh", + "CTu0W1JR4y2OBVJ/GCYq2sLuLh2412PJr287YMI66hpbNHedpeqgjezKSoUu8H0jqkSao4iKmF3Yj0hFlNLuI5feCuIboka3", + "bziBfbEXBhWCgstuafUm4rDFnMTOj2M7ANxFVLSxyphNjbhLIa4qcNlUtq+gV5sIDdmeNTywLoC0wj5ikN/aMEstaklszq4D", + "ZRRFGHNrZrsxxESDAdZH4JSWQELFbRBrhxp2IiyAxUiD4cEKxQBmRCOiCLsFG35Ee+bEc2QPeJgSXzoHETQ3m4SVXLCA4xAP", + "8LRZMhqB5ZEzOKEMWgsiALhN+ETdI2GvglSPW2UMyn6xWQBSjKMfRo5TpoJtpSHUP1Ua2C08ShQx6kkC5a5yywSJoYeIrKO6", + "fda3Y+DInlVEqV8M9xdYY4/rlEWrQqY4m3vHg6FopICOAbmhTfAi0g1gMyFEa0Z23ai7LHujIPU1UbIzZlusunUB5lPUlUcQ", + "bASSO8gsyBjAwRZndoCklpacuWFZ9dnWhsDp9ANovRynzR4SXHB79xq9OQa+UcHMQ5xejRnkpMuVehd2LS+onGM8WjSNgk4X", + "EYPd57TXvclBHp92UuCCot9FdTv6CNOPRy3eovktiKAY2MWMAR6eJg03wu3h0UOzRG6Ik01vVPfaUhlvkiwYVFe2ymcjLrYJ", + "4YJmMCq3ogyzLHzE7kByAFcUfTRPT5ekkGCLNRGsyt/EccRidBlUdjNsT52C5obZJLDy0BuOZ61TRVHj5A+rg4h5FlEcVJIb", + "QaVGYAKySVmyGp66EQ65dE7TesTFCmxcEeD7WBeF2Ghshgge77hGmruMhWPf5QRAC3dGgH2/E2XOdyvZ1VWgzgsFE7BL2HWo", + "hbO04BUn3qma4SAmqViDhzbY0tf3KRRx95F77yEtBHzXyT7n7j64geCg75A8TMhEhgxeuAPF7kCv+kFvrm/U76HkhqU1ZZxN", + "xMahuHotkhQ9lG1Vf/3S2I6x0Xi7/utLf/W0/QnB7L96xn/522uP/u3V7//t1R9/+v1XPn3h7Gdn/lKAvU/OfV+IPfvl/3nu", + "hf/r8rn/+/k3P756/eO3j3987YnPzr/08/Pfh1b92e99dv4Cvnj6O5/99PlPnjn+6QvPfPLUS5/82emPr//JZw9/7+fv/vGn", + "T7z/yQsXPr7+2sfvv/Hxte/+4pHTnzx+/edPPvHzU+99+p0/+eylpz999QV78bPvvvvpj9757P0///jq8U/PvfLp917/+O0f", + "fHL+L35x5unPXn/45z96+JPXvvfJH//g43d++OlzFz595vwn1//00ytPfPbmtc+On/zkqb/85OTZT86f+uz86c/OX//k6euf", + "vvXGJy9c+uTqiU//5Nyn33vP2vPJ09//+PpZe+WTU699cu7Vn3/vxc+uPPXpX7xi//7cHue7j+Hi77/06cOvW5sDTtjY3Ltx", + "znyGAUw3TORypQRsGxmSMUFw1dAxYN0EEjT7qieYE2wt5G1thrtTY0t6TITXyo3ryOmy+lxoISq1kyVA3g2CsUIPOvy07g7C", + "eBtuh5OVkIQAXgHUR5oUgqH6MGZZm65zuYUzJlxkU3uAa6DKaELvVseE36nW+ca5st688RLsi0DJlsOAVw2ZcwHSEuX2vKmZ", + "cTd+soYqfUhkOSZLIDIV0+oWxMlhpr7Ug1a915/bpusAqsYjZnVp2z9SFWXjNduDxkFZoVprPW+NufHS6kh1JQRGeh/WjiSz", + "V9DL7FUsHDY1nsJR3oSrEcZX9rzuhcwL9gK4EMhaCS+9BItTH3qG/Yes+dVDEUA2L7/H2VIGjK9xswxTYAhkZR9IvJeYyQAk", + "lxgxtJmTZKv0bwVasAmYZPT8oAlR7ROUxH7fJbchOn6CwtgSBb/Kf1/hu5f51gV+7PFQIpdI+cN/e+rP/S18/iz/fZWK3dfi", + "OlIlv8YPPxvXOc5m6Kavshmn4+unujWYKgarjUuAo0kX/vaVE9QvP83PnOfvp/j7T/n1CxRHv8oXT0WTLoZsue7+WNziQqiG", + "X4m3rCXP85WLvJ2a9FzcSyLlZ6mnftybil9+yKd4mndUj10MhfLnKXD+ZOiUv8r/nZLOOq+gTrgSeucn+d3v86bn4i7fD7l3", + "9eSFTK9dA/dkiMRz4LyfraMedplzvPWi9zYe8NsUYn8uOuFk3Ov7Idx+ir2R1NZfjI46wQ+rPd+Nm56PHlPL34tBtz+fCpX6", + "H8a9vhtdpAtKEv59vqjevsi+0nw4GwOtx9FcfS969Tg74Sybd5qt1dcfj4Y9htddV17zWXNVo/MkW3suZOwvxFO84FPF+/m8", + "PxfePcN/X4gHfCXudZztvxaq9mrkj+JPffhhPrJW0Cm+mGbLqWjeq2yzfj/jDUabn+YjXIn2vBpT6/W4qZr6OgeXN/I2H3f+", + "Dgh8QT6GxS6RXd85czBwLMUD5XapksUEYKEym9gslrYCm8PEGiXXYANJu2GpjHfFKIktzHVpvrBnL658WFcOEFADtoju6nC8", + "uQJr0jZks66B9HkIu1NPjiquchCSLlDILJ1voyYS2kM/9ymkVfMI6MtW9mi2/dZP7yo+WmZPvrQZdRadIiWxQzFR3ygFKnGV", + "CTMTxyCaL2776oHdw1Qtn1BIDYIOimSzLXSUv1aSg3g0aINv80UyEmtWEOAbCCqsDJHRUH6XPJrytuvEvLu/8/nA3JPnzQ05", + "NxXwvNXRRrLIzhmCvkLitha2RupU9daRNIL3Q8y6dATYVsmI9bgXYzlPx/jLa7MduMo9Ykk8fc1+9iRsIwU++IVfSVnFrydM", + "GNP/5jINuv2Bl8QuMYLNq6A4Ti4pSaG26M2CdtPusr+zlAU46VxQerJu5ml6e0rMrnJw0Hefju4V/N8RBm03LfyUGIemxVjl", + "nJEy0RPZOWNNBWOGqq5n4xyeI29m6atnGAriAI7g7dvTCnCFSaRw+hyAuqlmKdQC+uqUgeoEy0qncBSDnd/JpF9IaJWZ0B5n", + "y8zOA7Z969iiu5pb5jKiwmNjEond1ci7i84OYBrWyHtCsLuVoB8gChPTa4QTK8YJVmBsTDYmWwOKxDbzykbP7lokSxdD2ESN", + "uHowODrxvHexh9ingUHrkNByy1lgnB8D9QZj1eZFdBd9imzJSLlQkSl2603PJ9o8OCggVdQwIt0DJ44m0urqeEvDOoDDtsZy", + "LtRIUtp+OHCUmdeD12JIQJEDuEVil1p3YE692kmVTFSRo6xVyrEvdKsY/dU017bGYEbBVaoeuR9URezjQTVbAQa2wo/nRsI5", + "yapUtiC5it2NvbHywCguVInDD1bF1slp0CBuu8Jc8BfTPjkzcwe91GKU8oTwOGr5f0jHsD5p5LGcEep2N30NMhLB51hKGQGF", + "lRAzug8CPlREW6kmA415cCVVXa8KtL8cSSTGEl8LYgSo+p2EDtg5E7woi4VjdFjTSdliVJ2S2xVE+gn8FHEtcC0xg8+WOhZt", + "50yRIB+BxygKRdD4bCvOu0tWOoWLSPrJ/gvOgqp/P6vnxyhrQsaUiXpgJcyPQT3oZrBHERfCDGjZY2AHlZzHigbFuMXnGQ5h", + "PMNZG8B+2S8cVuSoxIcwEwF4RGAC1ccUtmwiygZGB2Td8HiMeRJQuvGFmBu2WzhOdTYFtckqinmEE4zy8eAh6jh3etfTzMMJ", + "kW5bwgjFTr3Wrt9jiZtDcIi1cS9wVMMG9WhgGhtvEl7C3Crap/hEf2CHoh2yo0Xn/0BgV4xfNQvjhBtyFXBMj3E/ohMB6Fud", + "pNAcSMSRTMEg2f5MNeUh1q8ME5/jZOforSooTW5GrvOezU5PZGMsSXe/J2GLA/Bke06vN1b2cA2MxwzvcvZx679fu5l9eW/6", + "7laDeDROTiKzmENRuSieyGY2XkDmeUAtANvAQONacc0kwHETeYbeZDmBCAdkSwazMYJvQ/ZuvUnMLMS91woJEcyVEo+we9yT", + "LIWv9gOHiTioko0zCfpcK/ho7x4cRGKUYABKPdwv4VNi7kgLhCxnoBGKwxGFnxPLA+thBcuxq+xMN4HdIwDnSFSs1j7ML6BT", + "bB9S9t6BZLqy+HfBx/M/pWx4QJdXQTnp7q6CvrBpYnUvLSS75LbajKk9i0VdLAUcd5XIJoFfEvi3UTQY6y3YjnqT0UA8vURl", + "owZshHDzbif//dZM7Fhefw5bRRXVD5FDqNJ+ABA7H23Z1wzxHAMPSd5blX1W3c7FWqiEQWANOgLOEs4QJgOhxCPJigSUUTjX", + "lbJ5sCKXGwGPpPX2WCjjkoXHYJdSKlOQA8w1asTRvkKgYaMSw5GnvBtFb7G5Ouue7RFKbDUkBaUEMNhhUy4pnfHNl7Tz88R2", + "/FpYHmQ3wkZDzA96kSQ0O9o5iYAS+3Q5OSAJ898wbMskSWR4quaOtIclMH2jPOWYujEqH0WfFJ5dIBUjqaYTlngHAwpEwbh5", + "ir2zCp3SFsnkXN8cHVYpYnknWLfS+MjkJLRz4WgY6+h7xsfMdrPOWQ+mkRJRnEITS5klZNw6MoY7uxYdSHG0FBqNSu4soTDz", + "a39HsIk7ETV2hh6bX75z9iYOQYPXMdjyU3ec9oNUWdH/cna6xB474zBVJIRpJ5Lrl8hem+QwabSOHDJvG7nkqtH5B9IMWwPo", + "gnvnTEqOOiKEIX/UgxKU+Luxi+qka4gq6rmHJpgT/TemtLGPz8Z8mU2o4EZCENgVUh6mWSInLUxoHUHIk5A9hVhueTakcmQW", + "BO9LqYmnn98CpxWBZbRuth107vp/2L1Jf4z7eknKQ7D11pxkgOTLtBSxs9rVbXfn/EPgstoKkFBBNhmSwQKyrisnnOsXgnli", + "sNYcdcDVvHtP1v19Jg1gbxwdIpvbL1YmCUzTJFjoXuw73WF5tOyt9QblaB/IfGtI2hD3kvDnLay/kZI2TqQ7knW9Ag0xWqpb", + "yUeELSCQAe2rPgvKnUUSMEsviCgEGsMqww4nUB880hI5lNJ51XqYa16Y0pCN0qY9QcM67bv3J1+8V8fMOSzPAexdesHMDuzy", + "NJiahE2kfp9EGO5BFbMiBEjGCyogIUamy4mQF0RDeK3ugbRqU4Z38x6BOQfDSYK7fiEVrUB92O0ceJoVR1B9D1m+sMtxN3Bs", + "oCcJS1wxVxGImp6Uhg4n+96Z/KxjQG3mp66zY3SQ8C2UJwABsyelhWaqBKElfGjOddI4Ex3cMbNFtUqgOWTDIfOc8uE214JD", + "LhmWRVtcVRYIpg9ZpOFw8A7gQhDA0gro0/K1HdgZOVL2shDSHriQVMBQSCmVx4FYLcyCJ7qpLNaqo+DPF8ZJ8wf9JxQy0CwJ", + "GbF8AKr0lGYr0pTQHkFCeOfErMhwXJOvI0UhZhTzR55e6H/c404qJhfV+noCfoPZAOlY20HuTzGZg8kKCghxZzldeedCCymQ", + "EpPNiN0PNE33wdt27Vp01RX6Bi27LdYnfHZ/BfcIYEqTMMhFSYg++HQSttIsc8TvMKfuT7EgO09cpPP+FCsQkyBjChUlvK0F", + "LrFAsMpR6iRuVAlYnPDsBGOD9GfPnj0gRRsU66iySh6kYwZgj5NsxWe7AFbdxp5gNwCJa4P+g9WEe8hi6K7uu7sK+1SFIpQA", + "jmKUQpqw9IOGqy5qHpbWdpVAHUXCbBXOTwnLSEyPiJ9IFRQeKTOr2CSA7hNoKRh2duxg3yMqEvaVTVTnvwP6mDYQ8joQmBAN", + "XndcudKdJJsxqrDIxOVnthQonhwmJjkul5ez145EkdIc0lmyn7/ibJ1lX4gBFH/cmayCB20o5eeldRmVf4yMVfrGEJ7rOvD8", + "TVuRCV+oNr91SGbKrRoFNOJApWJYv+uovhJt7tJyC+ywrwBcfDX5EKjdQRzJrE336GGNbJGLUj4sPZ8yrP/tSsLO5KRxjt3e", + "RJ4SQj2ek7P2sSdX0QL6phwjWpFmd1YjWz1jrTMeizqYk/s5m8qpDmZ+aOEoB84wblUQaRjRbbPRcsqmgF1gCvry/f0Ee51x", + "XWIbVZyNiiwGN1BRdoooM7inrqwvwNgzk5B3AowTjaBhJhSjC/FcASErPSV3ecmJDdfHlWNJbAnQgg+gyG2Nc+7S0xxuyv9V", + "JcV4C4xMQOCuqwz3AaHUEgqdPNjyU+YTiux2ISI4+tYrFBZPVZUUJGVdZtW0529UpM2vSsQZ0M1+IV0wGfS7j/qclD1wmCB+", + "PLnbQzVMEZ+d+6gbCgGHgauhYL3eVx0t/lfA4sowS5o6VX1207k6jrrRwObY1gEgIg/YMiLg2xXRfyDxVh0uWd8OCgBljx9V", + "rbBFyu7kMOEnji2mjFKsjyZwJIQbqqQDJotOq2Qp0O4cwUdEZYNwXHNFsDGp1gLnfoLKYh9x0knn8Mb4AhvC430hRSHWq4i3", + "M0EjH6zqydKpUgFwgQoy7XCgc0xkZWYD7zeDjMBVDhcU42pK2oH7RSBx2AcAHYBvkWsVKx5I4aSVJ39Ge854CH8+GEMHrt4i", + "RKV2i6NRbVKkouq5yNRwpx5rPyC8jthv3EOyX6lCu0kgteIO7btAGAtUuHfPHkKneXOXMAtMDBmKXTEbG/Kg8FunqgZCb+6C", + "zbXhmGFoFTqTemcZqlsyYSKKU/bcj+qON11IDou+iJ0NcHet/iLBm1ON7TwSErtZ90JrrlfaoeX4InvsbiqR70lKryhHYofG", + "ZUrKVxGEhU14ILEBFTsKHy8Usx+CxUDgTJ5MCZmaPPDtStg52JgNdlvSwWuUIbLpUsgFbCqopmAOgItTKjzwZ4a1WIcHW46C", + "FBJZa58TtewLSI1zhrkYBgCTdSPhRErYKS5FVuIJ8bFMDMGgwDqg+DhlSlUwhXdXhgFd9zgrXAzWf3AXXfU4HIV7Gl3F56QY", + "XwU2w2yHug3Y8DHTuuAOkNCz1vmqcLN7ir3VJv6/eHuKySykAAdOEjhLdCA9I7GQWAUgNiO7cJRiBbZzjmxrGa5vJBt9Z/DG", + "zq6JXxOCjq43ywgfbZWdM4V5CaWiTStC4sMIAUe6lwRJ3YAxRmIkC4d5YYwOxt4+1xacoAQbrSPzN02dcZMoCArHrdovy+lU", + "S/XpSx40g/Qd4iiErs1L+q+zsACmc8+RkugOMMdge7ezFj7YaulVj0LQd4sAGvZT9kH8tmA+/Jsf/80f/83pv/mzvznz0cNk", + "ebv0fz4NAqUh3Er4+5UUNrnTEJ7TwFNzRBNZzWy68uzhu+OV2j8n26t2NjQiaVpkUJN21kraF3gtobpQxUn3F3PfgVnINzpL", + "GaNbvEdAeOsBVVd4t6g1qwfkO1BbBisOvkpl11UCbzWMQOILjfLx2KHDfkmaHWTTUsaYWXOzDXAeiXlfT6lYUA0tr549j726", + "Ap5CuN6l0F+CW0l7w9oceLQmeOhQ9uOgpcYr/6qHyiBVqKJfAL+y5t+4BNGFRC4BvRdrptk6DykWWTPt7rAxzzZTPCVtvGtI", + "V4iBDTUS4lgLWoWKIql0WchXdIVMRG+IXerDE/4afrsIDqYP3vnwWbIoXeerj5MTCbxTb9jPt+39yx+8Rz6mxEtFVqTr/Ake", + "q/fJM/V2YpO61PJRicmJd3kruJM+PJHeBQfWVXIrXSVr0xVyYLGl+NwHLzp31XX7zJvOlOQMUeK2+vBZewd8WI/oKROP1DVn", + "nMJvaN9x9sE7/FecXuKeupYYsk4mDqgL3hvgy3pHjF/4BFuIb3mbrS3B8oS7PWI9B4ap9/1537Qnv8DvXo3fnN9JfFn4Hlip", + "2vui9e+x19VmMYqRQYx3fpx98Tb/5nfttUfwCpmoNCJvk/tLHFJvpue47KMWo/U4+a9ejHHzz13NrnwtnpqcW3wXbF7ip7L7", + "vUSOquvOOAYurHc++GG6x3WO6CVv73voU2e0wni866MfrGRXxT+GsbQ+xbixD1L/vcf7XiZ/2A/Jn4U+ORX3BZ8Z2uIjJU6y", + "92PmWAvBEvasXU1j+eyHjzl72An75gle400yrF0gs9jJdL0LH/xF6g22hU8SM+KCPTl4zZ7mGF3AtXyUj/Np43OaZ9f5u7N6", + "2Zi/o1krdjP2+1X99uF3fG68w3l0iXMXHGRsH9nKnkmsZRjbd/E0ad6/w3Zr7n7X2nTSrnoRLFo3z9x8/aMnb76Ck8JZwfRT", + "HGLXwAoldinxfpGF6+TNs2TWeuqjJ8C0ZZ8TH1awjMV3r9irr5Cv6mG99tGJm5f8G9ecj+scmMvIIPUoT6wz+M3+PWGtAlvX", + "6+QPwzfeJPcUmLXIZmXvvmX3f8p+c5Ywu7I9B65i93kLrFrkKCOX2c3r1oIz+JZ94zRfA6+VnhWcYedTbzzl7XvDP3fi5mX7", + "rz0D23EycaqR/4yf/2nwscWz8Wm838guJtayR8RrhiuBSY3Phh56nc/zE3J+vYG2qE/BiGavgSHM+8Ce9wS5tx6z755ka8TQ", + "hc9dZk+etB56A0/EfiALnL3PpxGTGBnbToPbLI0CPneJXGInwWQG1jH2Pe74pPjMwI7mn8PdzqonfKStpX43tsaZzbzvnZPu", + "tTTGL2NmgDUuWM78Kuc5lpx/N1/15z2hUSSj2uvW9pP2/K/dfAs9jJlorXmU4/aWva4Zpj7XTD5LprM3Me7qe/vU686U9xZm", + "THP75Ei5DlakWUmNMEO4twUtzK/Xa/6qzmUC30LlWli4njvdnTYLlirGYPyL5MtMN+GneLGqv10PB0SneI6NsBiEZLcAyKqI", + "K9rsls3GYqoqR1mEpxqXFpQGpyeJmJmnuz35H6i1asQgMyP7GxTJbrPR+xJNV2d5TwvwqURCAM/BAT4C4qB21aO7IudxORz3", + "uw94RJOwpoCGkEd4y73IauR6ybPjYW/W4RebeAqmQxphenaDaplOCFMyKFajyW/X3dVGsto8ezP/pfu/+E1ybH0zWUmjSsm7", + "JZBpt5mexaU2W7JhlpJ1F9yumZm7o2xSejGCSiLctA9J5cXVQUIySn+5UObdXFSY9fs7ItVg0xGW+d+qElZ5Iiqpulsbg5GT", + "HAWDDMIOvdFiM94CtFGJH+ByJvexOopmffAyWfdtlsdUv7e/01gjHtIn7miHO7FM9cDe76QyxdJCSDYtjzYY4Vuph91hldiu", + "hF/jPMNIRZ7RI1h11QAw0njGL8Vam5kdydNpkSLdqHijUpSYyBAadp66Onh6ASfo/i/tlGtj4IsM9rIqGQXPIV/CPlOcNLz+", + "NVxRYUPzvw+srTMfMVJo2J25e21yQRl5MJxtzKmDB09UTF8e20olmSwnxCChQknBamnX2o2XWmgRIysqeawpGcoQWt3fpqNp", + "Dd41v64pPruLZjg9rd4dFRTJGFfotN5hrSAzO/VYGflWqSv5qwh8aJG1wQWFI+jkhiIIy3cDltOspFhlAWV5X2R3tGsoeKts", + "Zc23ACABTYXQTDjAxlOQTHk7Kowd1Z8UigN1U5ypkPCSYo8DwgOQcrmXMhEF8kZLLcC13XfsOpTJxiWiQoYbSBFkbijn6AuN", + "yEiSAlXhzEExzuNqqMRDUl6+dOIb7E2oLWgTrT+a7G6TfSBf94GVTCtnB3rfNpYeamMHgBP0MRMJpqwZGxAakSCnr9hkqRHX", + "sG27SDgnh4RhekpLwhP4hBD4GHcrFW8SktIMV/d3FpZaeKOnOIKkxWeqe6rIrC8tpARfyCdif6jJRqW6ZRYHkg4OB9Wq5w48", + "X1AVEqlmMHBeB9p9qAVeH9bSv6sOtPtOUrAETJmxb1Y/KqrHQFuqmy1mWwg2+teT7k6ys3fPnt9GDMU5L5ZayAPLPDHK+zu7", + "5hORUFrzg/6X+5GhKkKwD7kJZyVCAHoo/I7KDbPEgiJn5HrqlcNbwBTNofYYD1g65688dspyFtzZifJJGe9249rbRv8LSeXw", + "CrsWbZFqsidCEGgcgvkN0u59B5AiYgSkc1/bZ0KFd5ZbnD6Dry7fhC84vuG3UrxlcevYYuFnZ8jgIdLouRTGczedH6Lb5gUK", + "B9Apm98MPGS9tPE/x7B0SVexqj5zGoGVSVt90NaDYgsqIvl/VASDisdtAZKGCFu5+t/GtR+siocxuEvForFQi8Kf2K/foLQG", + "sGT74gAogEZCJBqImKqt1ehyUwCiB6iWLrY18t4kIH7UnHECJeT6fOLE600OZZv5qAjORy+cmzB2yop8QA1dloxPD6xjSRC6", + "xOwc0a1QDKGjw8idYb3ZXzhBMFie3OW2qVgjQuPOaFOScoe2T4h5IBaaUJEFhF4UnG5CLVQMGd4l0oQDNR/ZOFL2rBLgmXyd", + "ZYp7RoLeDCKb0mD0G0AdSmqjAgitubYQo9gabtbhCl2hzZ+qFdbUwOs0A96UTVfKACXHodIJxhyicllCH5o/hOxQLJ39IAZS", + "dPWhw18OnSSS3wyGAMm16axC7CJkE3HBLpKU2keDQI0Vy5yW+xLV4SwmHLvEbGVHjcdOIAqhhQeaENqwi0VBNNnCKmGW2rgw", + "qB3dGGmPuhmPTWNy7ZwJEZolhwUf0bm5VWvfAWzLE3Mhmwn6mEAoUCzOGTxoEPUFPxRZoXKgRHMJdDUomnLCQbizNcrKIgGR", + "giMVR12ChzbOxUFen2SyNqEaZ1e4W0JfWE2RjWdqTJSgdW8iRhTBXYNupzcJXTCkSeEPlMRVrvn+jvnr8D372oZKHQQ2C0hY", + "E8qttt5CvMcGlstfRlmzgaWjEvdSVKUgAWKSjC+HphiWNEGKzEp1WpgxMQXYQJt9pNDT12yui/pvo2rR24XT4yL/MOCJz3wv", + "OQ6i6VR8FRuuQKvI7jqlmjVvQ9YkODbsKD/kgnSdsO+sVf2U423BkpwwXmwxM5PZk4kytT17llS7cOc2IWuS6rK7dgok0Cs7", + "vr4OmcdaT0FZNofzSfQJi4aZ15rvHGxPp6iNsadQoorT895xMiJxSCFVYX+2h+UXsKP7B9x6xV+b9bEg8lipRkcrkWeE0Bum", + "RiKa7iWXdhtGTIBAI0FAtK2fWdvVwh1H7ij+C1gBnKyVkB4um/7qRKg7cgXa1xwihvXbbe31NqFfhBNkDZ1PbAMFiSdkShxo", + "jSfsUa7/ExArniJkpQaWjPum+CnmWtcnSl2snfdPRQS8OK8JNtDayTJ043JlBWeD0tLrERFoUo6oaL3xItRQw04VPpP5eZmL", + "Afbm8RVn8N4Q8bav3d1uushWueyqNnpOFMgEk7do6JYCNzEOgKBqLcY8Azo3WpDk5YCZRKjbStXW59ldv3jvEWnAHWitbRjQ", + "bq3cmUIGc/QAaVAm3V/cC9NwhRlhzRIUjm2QrGWDtlhUY7nzWgm1eC/NWwEiATvxjkqomb6I/WgOt8hKwg09Q2+rkVgLO4IO", + "tfZkoAlJwwN9xC52OWxhnvBLfvd2VsvXFG1dKfc+na6aUcypJsob2vckuqjy+iMyyhTy0fhADiHaUBachG5I7daU1dpIaIqV", + "SRrjKDjDCjfHfrQbRKhJQs6MC7d0sQiUvq5REzhorXiccwAJlF2FQ+yWYiMmeQBqToQuwJRrDc65pYV0slbyz+lWpx3mdw+1", + "/kVbIdrQB9jNPN18kSIjIdFFKtdktamUicdXaGqDQQqAZBlwWaWj7T9Rh8NbaOm5FCbGOxGjo5TYSfasEV4PB/ldMNwJSx8k", + "zzKmbfUSB0DRtiidhGETqCdFOIqSGEP739ZWnZj5e9BUDQXnFda8smUkFOLMOKp6AnbAZmXmp1SLj0RNiDkECTrfHGldowDR", + "kaHHK1KREk6zpK3vbKL4CDnvMnmLdiJiYpHIRxrKkExtIaG/n7BxdT/x7lddx0HCUdFPzp1U9UcYG7kt7Lr3ModMGyXohDMs", + "GIz0xjkYbdK25YzBOshyuFR0GuV1D8HmknY29nXnxSSesVs40oigNa0T0Nw1gobIOeG43U+GCupukzvK6zJHye7jksYyACK7", + "oIkG3kEW6bF1ZIEU8WYQpZrNdShVBM21EMRmRDojOm42U8MISXG5speCmmUv5YjNjSJ3kk1nTiOUoj+oOUmHzUYyqU0UZXFs", + "s9dv9g3W95vdksrcUy38sdHBVGvoJOLsNqAUQdMIwCfLqQhKblHcMyHCgT3VmuM+CruTFLRloDrIf7tZ+TaoqBpPnLZID8Rc", + "sGCw0zOGp/6l2dzw4MKB4zCkNlSx2Jbyz8lRJ4bH2vBgVW1pjKPSucEGWFADvdFMhiZI56A78TZeoZNpo8mAK0GYi47BxZIS", + "8oxRMQ+nQS7TGgTyQEyNUJSlKcGJyBpr7wey+gM+Qo7bUCH/bx3qHKjIblAWQmsQaCR2rmIB6C1BHnqTO9ucxM62/MWH0KbD", + "3HJrcO5paypwW6dBdOg+xigqGdzRdfqc0B+fAjoCQQsmeQcQeilHs69vJ8YiKQKX6IAWoDEnratAorL7sLYG8AQws8xDE4yL", + "BgUPd8HGvGQcEyZEE9AlhGoOqDif6tKKQxHfH7HG1AtUE3ctqgy0VdjOrWdjLL1e09mKYLttCmuqKCpt4o8UsNo5s0Nu984Z", + "9K+fZGsC1edqudheuS5o8HmNDtf8oEi2t0IR7LOj8n5xSAwTEJI+jRITQ2rjem6mCK5AcjM28oPIYkiWwLYio1htz6ygzcNC", + "Cfd5VxanKUjQOOg7Csu93yVqK6iCo2XQ2BfQUPAQBPObncFQOqxXhvV4kxXyOupqZ0i1JQ1WUd9T2wJYxh+Am4M+97AK9CkN", + "SD1rSGJjEwMRoG+vcOIVcQnGjLrlPaW+yXryh8xZpqoyJq1iWHZtH/Xd3XKSWP1ROKkDEui7sXTgweXRpszkk2kdN94YIMKB", + "IRdcO3Hju1YE2d25BUn9Q14Axo/AW8faD/r3YgV8GScRYGSqwAxdV+s+8EQhb2J+gSYtFY7Ds9QJGSeZTl7GB8oi8Wajf70N", + "iWe0HnlxAfnPyZtHUwhT3adBoB8ZxiL1Rrt42bKkuKPDx1GLAei2z97fes3S7PDVkrDuR8EWus7q+JWJusZh+w4/dWYuRxFv", + "oRDJHj7q/V29Y6TiG96KZOC9Nqo2z6WnwkGnnIYxEr5YoWIV+KaE+XH9fHX+cHAkTKExQQ7ci0zbWksIgO/4OZ5kOAC3LzZA", + "YEpEKVXbu+Te9KgMM406BAdrwrS6oeWxldFgr3XBnbapAq0pFxXGaWI/Q1bZa0AL7WCad2RPVXrHLw+fLxSESRJbBem7G4Xc", + "jbrdu8QyVsVuv1FvcV16LNMDgsqkht0r3DEpDJX6tt/shKR+NmcJu5RbVJEwuxvaaVV8GBsTRrMXEaDERYNJ626CnV3oVPiv", + "ELNIhXGlR384Qg4HVexVEeS6H1zVo+5y3y2nWtTTJC8GjWJi8aEHyOxLyjStjPoQJfeOCgQ1NokNGVRMgyk9zIi3rDds0KDl", + "bWeJh8jusV3QX01llDiEGyxLkNLe2YZOQokci6EN9bQMM3OufTD0heMWFgk0lSpKsXjls3jk1H3gMB/UlgULz4WLk8zObdA3", + "LRA8ZvXCGs5gFG248DXGonXwwP3T936QrSIXrcXHt5xBZA/1Eg5EDX1yLccJu2OH112pfKuIWjIPhJHM1bwd8fHZ3R6I3Six", + "ZfYnLZfDXAixjKE7sxURARQ3uWYIGGZ9CNysa6aqIEBs86CHFFGvjxB8r17WoiqgNU5jhPprXcnjfg0GliOyWTzdRgRSGBcn", + "juhUyRzcxA6ONeHjBjs8ppyOWo68bB3OXY9XYbIqbCIqYAEwpEexSgN6KJkwVaQtt24SrX/92jJWzYWyTYFJW4b00ah1Mpng", + "SMWmYZ+yxqU6iO0/hWxtWKrkQx5uLf6W32nOqzSEiw6up8ZJ2Onlk4Cf+5kK8PkOTXcvXlHxGSZoVH2gz1wEysyDBBPB6e/a", + "GGBwwPzmiuUiO8b4Vnr4mkaO2yVYTm6tiJ6G642V06IpcCMfpNVtny6wUIM0kRP3UHGuiTuXWS/hIBLlrafV4Yf7EzvRPSxi", + "8Uy4aRlkZvNcsWRA6LsciptfkYugQSLjVEsSrMBwdPveffwAocm9RD2LSi7Fz2yWwzD2EfKngOmzeWsqOe1yX1NzjrQRLakz", + "0Hg63Pr+wXHzheKbjEcVDMCECcRkyFYEKEQzw20w6kLoGqWCi1AFkn0GyZGeYsVwX0hCoeqfPinwuWDMgCQnuz9Jf1BEYs4Z", + "WRolOBREtVOEuyWU7SuWPWyidn/BzTo47e4wwYFVOKSRoklwmszRkJVLw88qSMFp1Jf6W7QX6iNpt1ftFKc9gFGx9IrE373Z", + "hvB9B4fv39LMzZGeHnk2M7fStj3vPBBNHnGp+zsyiNCordpxsm4shiY5TCnhhdhNSh26Ep+o07cjZ+mrkF2icwW/7siIwiCr", + "wCLdrtsaEguidUF9C+6TiMk2WC0enWZloHYk2IgD7RwesURZY3tYzh/0Cg1zj/wWUsUpe04PwvCNIi64m23VCPiUrbyWQvNS", + "iivHfboE3Fa2fd9xYA3WZKpMkmfpNlfKlhwdOOMGEyfyVmHhtat7jj3qNBp9Gnsuz+B79bwX8mJOJJjj6iTRytv2NihA16M0", + "GNO9yg+loBnXRc+XU+IhUR4dcZYB6MkPiZwmcmob4KQtYpdnfLkCp12jfYfJYqcd5L6+ns7NI23ynI1UnNSLcilPmkz3OTfH", + "vyYhpImXQzc9m6r9v3oGRPSpKqYJorhuqe5TiUdL2tvyRCLlssoA0Y1zpeavl8n0o5qlJOxCgunqB2iHt/UnTRTcoI6QIgo8", + "FgEGKTdrEpJVdnWhQ0JBindz0z1IGXmLtgInFeNYI+GxIp7dLbtuWuITq2DO1S0Sca/tNmOXl2/gjoKnl/S9qTamEd3Pqtec", + "jLt1qUIewgXgGor7kR+wVd41W+iBEtzrUVfUDDxXyv71ZCpoUphqXrNnQ5XbUM1B5NisITxx8EeyJ+FncQDo3WqEBLgFJw9L", + "kRxzo8gWf+3bFrCexoKkNnYTkIsF/TejGaJ92Ncp9iWGsAzh2yBcHPpYIbWAHWVhIRE1zXxZmrDCEgXe0X4Hb52nKvYl4U5z", + "jboV2NV3M5zGHTO4zDKAafSglHNbfMFCFm504kwUIM4WGT4oa/9CC8BarRYWjh49Or8+GKz3XGHnoZAVHoS1nGWxFXseel0k", + "HT5FGZXZrNTVwiEBbLtv7++ZfSlxxQmI86JBGdCvzV4S59hm81zxR1hUkFN42/b+5+yaoVFiJ2KW/+5+YU/7md0ZporHM7Je", + "KzZeyy0IBlI7a95BtyX6jtt23TVmMg2ewhxxEdsekkr53/2IogyGfgJ1QfTtPpjQFaGXqrphDrcdWF5d31DWqoDoCWrv24D1", + "/VW/30x629YB5YHWLJ5bwig7Jx+QwwsOHQZLStD8Ay1iS6dnP8sWINObZIi0GYcfCWid0J5lz9yIA0H2leGYmhQIr8WJFUm8", + "/Vkk0CWtpVM83x11oaRjDW4ZJMvewUE78LfNZTCcUCMFai2l0WHWtY3IQJFNFnXcWxYtq8xSW7LaudMOr1XKXdel0B0CWmZo", + "u678LYH0Ez+oPeMd9hlvdJP121ISU7MxTTLfOHRgiK4p2tJyhiGq0hotcSrPfvXwLvjR/S79m1kHGymfOF9kDkagBVarToYy", + "EpadaYLFg4wdHqWnAZBsRPeSdU6Xxn0TiK1l3lKV9c9ilup/YGxmcFAijtwQs/mRp3cOgTdAhsVchs7/HeeVdPw4edQV5GmK", + "JKU97LTcvAmE7kh4lAJgPvurqpZPdbzWn9gfPOnQshcDK7kJPeyQO9/c8n2VRRP7O/ZVMz6jypZ2v6OdGJGQ4NFwXC0eZrX2", + "wsKd91mPY1xcbEU8UkqqIUwce0WGHi0Sy5vNn4NZGxJ3CbjtfuuPIC239l93717+Vhv/n0muB5XcE2hwziWl5Cl7LbnSzkzN", + "cnBkWyoqOBv0CUqzwocmkHbcb5lBKfUaoibBuWh9kp0jRZIyL5id7ce4Z07+QmAlxHaLoKzziYmeSohDnBeutrOUZZm/OKaF", + "K7d0m4DRHkK7HsCN1INcSVtuczPzfeRD6Zu0gH1yBTq6dCbHdiq0ZJvD1rEiS1HsTerk9rxZvcveTQDg0pi25yNhM+6LrzMc", + "qLizeQE4CyStG3U+1v4vJSbvTtHHMqaD0jQtzHC1uj1U1O3zy1k0MTumZrJhLBILWJJo0e6CzSzQ/dlaMEentxb7c2YMF3Er", + "QnGDLy7LfUyU2ImiBfMtR3CBeoS9wlEXS6/tRcc2e/t0BrWsGmC1RfpSki2JPJWOVJUGLAfPJtFte8Iv2fHWuAN+f7bPo/4j", + "yC0Qw9rNm+wbZkfHLneFuL7g0tp2izmMrGaiaIHcH0TJCRNoisSBI34eet8LWeShoIryRt21SbBoQ2rXXyEOV3udmLCSfjfG", + "BQF8d0jx/VD23ZFVR7mabSkmcgGRqNQJcIOixA2F7OukOio1H1sn9w2gDs6pNJdVejUzO1qf1/byFOqpWugcqRiD5HfWXN6C", + "Goa75jtFy1eyle0z+Hw8Msfd8+I72nTOzEzm2COQ1gsOuRYoWdztWY274PW2Z0STwey1r6atGINxG4Z5QXDOYJwtUiiZ09RD", + "Hd9oYVD7soBikYW2i6TcKrRVb+DFIaGPXOXxWXv9QNGCWzNocJGhFbpCban9y3lJizJ1jK+utDl5IsuF76li3JlfjSAzQzbd", + "btVGMdoKtbasp+wdhsTMqPgqxFLsycP66HpYmnfvU7ZVuRBy+ESSuw1rFll5YHOoT63MOeZs29uW9Wbr74BShNOf8JkUHAKt", + "9CD8ha0sF8VNrnf7eAXfyQ7ILMhXyOPnUuoO26iuqGus+T0SpBSJ1u1QZgvRiPN9L3On2klbQMg3jddwY2x/SfqYvlucX/55", + "4rwY7BlqAmVx3yIYzciYxOsQptKwn73N5bBKCUD8HoDzZpNymzovCpUrAQJPIUtHvgJ9FzBlG9CEL3f4AWEQXCNe/UngfyX2", + "j8OkqsTOX/ZbT2bnTEDzHNaS1Ktxwfs8E5QW7xa2V7gW2odbxjqIGJYg/B83nuYLvBQ4F+PMZa7WnzcyRggV6azRv23cr1OI", + "F2mL66g/KFLebVhFiWhvEvse5upyhphnMs1zcvxi6DBmNljkMJRFS0BAduYhbJu1AMTUZVCIDm9RG9LTVnzhYOZ3ZEkFrzXU", + "asZtuKeTj9mNQ4Y/BTCy/fdY1KjiubLtqsjOMuXpnH0WdkbhuSOBeRQCJgebl6ukvLvOGsZOJSzo+SumLomraZCQ9XofbhNJ", + "qzTAQp5ymM38uEOjliwQGdE4f61ZXOKww5V7EsL4QOaDO9KQ0zgr22syG6YvbjG1M0kJgzmKvrCnMktWVPEwMWsjcQQd1Vpf", + "GfS6i4lbTqqayPcSLpQKlbCnteV1tbQmFPGgtGzxtXJYHDo04gohuWoT6zhD73NbLp1ljzn8FqHO+RyhS667hpHfItYg+rq1", + "pVcmwhQp+n0wxVIkzAprohu+iZ8FWf69AEN04Q7N/W3AOdv3Bn3PlBMgk8E3WTMTe4u8ZeFeApjoqDqiNrtZCaPOL1eZV9h3", + "K2op/Gxl37i9TbRWVssetajcNJmZ8h0iAz84S7UqwpI4JtaRzb7YG5ezwylVPHl9pZfINlk5fdPJYjs6H4kXsH219VlCB4Ix", + "B+bQCk7YATZ5N6KdDa4zGmx1Eis4ka8JCZ0jkncGjyuSDW63EK6g7DXzBo0riIwkQp0qexppGkY/u/AI8gHqTy+Oamv6uB96", + "KSB9NI97qFRYfhYaEEDKVC9kV9Ne4XV7OOur4MGT1m7YsUQQl0OKacbewTPUF0GS/WVGMBVrNswh+9o0fwokZl9erVo/EnmA", + "4F/DXAo/BmtTQHbNHCYUjoY/G3W+jjH262flXr5PSiqDh06Cb7VBq8ztnsHnSUEqrlmqtGeJF25JDbTi4Ozs6Sy3nPNikpPe", + "PAsApEhL/9cewGkOHJgVyacmEPjBld3Hrh6s6sgQrsrawKJK2WOWHVQpCYv1Fnn7OmPBD4ycP+8o1g7sVSSB4C9kAP0ZXV0x", + "hEGIJdsuBISlxwf30zNKaCJXKWVfpTN3Lhj9uI4a4OckS9FkcZ4o/58wN2qHraeZQ54W5kgnWTDUJyGpWM5DMPGMWULdZOdU", + "Yn3A1uFrFgFowqloMkBMp5fmvO1vLG5GjLG1EggL39RBTtn0hMg5Sk13rY3AaABd5HhbFqK3+zDYWMcpt+p9y8WfhLxRR0N7", + "8iu0S6PiMecFlh6TKzNgD0Z0uFLpZMriBvzJK31cmJY2AfqtZJ7fy8H9+lpfkONY9zWutmauaiO0h3YwZR512GXb8JqqTGR8", + "aI/V3h702zjyvFLCIyhtTDKzM4cMz/jBHsj0CctZQ22gs/wVWPTFnZuAdkc+XntLEdnFuWQXMRtfJIpk9A+3kXqtms3KnJez", + "B87gh0WVIP5mk5jpE/t5qrzS3ujF2/0B9xwsGtlGseNUycGx8TrUgtzmVrL4j3TqtZ6TrjSsSoGauJ9sUjHCc63al1R5uBqe", + "SW8CYhUW9CGGhlFxOPd2varetI6ZzQLZLXsz8hRu52DDjbhNyXxN6hauWX+yqEEjbtdrVDjPh5rjR1H5MdhMVSIobAj/16uY", + "/CxLe8g89c5Go+D8hh3eCK2QfNW5KPfBuDjkmvXQYTsxzhMK46rRLciSwH1DMwJrQPukelKH+KjncYBR4CzCrm/asgd2Qct2", + "UVNOurX9ErhXMvduK7b1Tk1FvyAkyNNarvuJLkJx+wTrUgHWyNe7g6Csy+zpVAPrWCIHuUzirJbygqq3j9gi0t6lsz+qTX2f", + "GUectiSgy21vooJrgqfTodD2g9lZTZXgbaDCRlx64NrNkWuw0122MTgX0D+t33TYk9gTVXhXguSuVBn3z96F/+N/b37nm/b/", + "/7CwXu36BjyBo0X1rUW3SXiWoyAr8WQHogTC3xuDVEyTylvIAFymOTyE6r1KCJsdWQFQqk5P9o/2ooxHCSzRnsf5g11VltP5", + "4AXy610i095LHx7/4H2yE14lQ93/+Pt7wS8GRq5Pz738i59+7+Or5z59/nGpQvvv1x5Ov3/6wpO/+LPvQnz52asfX7/+6YU/", + "/vR7739y/YVf/OD9Xzz+9CdvvWn/+/mp9z5+54cfX33742tPfvqnz3z87gs/v/T2z99+0T7583PPf3rpuc9ee9TXHdPg1hND", + "wQxCWwUggtWBx+uUKrctknGwLrVxBwEa8HwcPxNMmGUXNZS4/o2XJMocrw8aKdMxugzloZXygZIiy0KBl0rWT6DBrOsDGWCf", + "uKdeGdIepuqwmdpiYnDezTGM18BJRKG4c3k2daT6G/JggmGzfcYykBm4jgSD0IzuQHHaeC7wreh32xfT77hY5M4qyN1tVg5X", + "iHjdIEeJhPSzwCEpgg+0xUrIj5Zk7gNnIBj6fkRmw4fB/NfyQgbv5odPi00S7H/OxdjydoJd8jhZH8nKKPZJu8Jl8m8GW2Gw", + "cYKRMd3rw2cxhzk7L+bXcd5Ocg2KjTLuzb/f/eBdclW+yZl/BX8l5kKwFaZr2qdwxTfIU3ktu1fGjUh+xavkFNU9gxPzcrr+", + "ZbIjBrflVb5HZk3ru78k66ZYDhNPpn267cNHwHNJzsi37XnxLGA0fRKsoc7YeSnjCr3kPXwBDJ1gF/U+AQdly2552Z6e/WPj", + "En0D9saL6Fd7oredefECWUy/bc9+0V5zBtAPLvEq79v3vp1xSF7Onv0C+0nMnW87iyi5J8li+ra37k3xsHLE9JmrfKY3nEcV", + "MwBPRh5P8kGKLfNdu8N1tuCqX8fHEcyVZJa0e9sT4u/H2QLMz9S2D37czlvxYHJuvWM/T/isuZZ9F8/yPvk33wPzJUfxCjhl", + "OQP55Pbd98lpeoH9o/aKm/V9zXUbr6uJKRbvvu88tO/wOfwzU8/yXjYWV3U/zrn32jnMO2sGXI31RX7OEx+8lK2dd8QRCy7R", + "xKJ6ifPoXTwfn7ZdL5fR1zbCXF8ZB+jlliPU2vIIP33RWvGseFR9TYnhVuP7LtcA5u13bOa+y3Vz3H57x/l3n8jbz/V4wVfg", + "NY7/BbLEnuB1cN+37F7tHMY4tuso8aFq1rG/sf/8uXPZWv9k2twnqMJ8IbSkT7r+uDTQITkd0tIuIS2NbPvAM3zrufjlvVDH", + "ts+81EqQt9eRkPSr2TXPhHw5Zabx+gm+ci7UtE9l7TlOifb32s/j38tt2yDqndS6dd9rVPc+Hdd/Lj5zNvTQk0Q1BcT983qK", + "F1zBXNd06fYX23u195WE95P85Tl+/vVMFPsqb6fW6rne4r+P8bmeC1Xu90Oa/AobJiH4aDZe/wE758XpZzzePpe0s11zPPXS", + "cyGA/lpIvZ/M9OWlO6+HPc/7/kV8S/3/cvRJel4b2Xd43/SMJ+IzL/JBrlA1/pkQ6U5j/UKM4Ono27jmK09kguZn4u5prI+H", + "IPjp0Cg/Ec9+JsbouGvEe1/FOOL1s7z+j3jZ1OdqyQW2860Y8RN8MX3m2yHdfnFqPni/XWPXnfJffF2kOXA8nlrC7q/GvV7g", + "k56AXry3/2powV9tHznNW78C+x+ffyHrq8uxgq7ysqejP0+7wH3bZvXVD0JC/WL7XN6rx9mex+PzbB6ufIptvsCePMFeutiO", + "na+j90JK/rFs37gcr59u57D6DXPsbHzlWnxen7ka6/Qam3eKn9R80/x/MfrkVAzKlZgDavMVb7DGvZ2rqQ8fj/X+BK92Jfrk", + "1Wx/OJ49Y7bn+BNFl+K+qT0XqFaf9hneF1c7n82fND+Pxyy9zLcoZO/j9Xw2x07GnHmFN01rTWvh+en98zi/pbV2ns/+flxH", + "81+b/HPTe/61+Myr2ZzRxL6Y7QM/jT45Gzv5Kd+j8JXz0bDv84nS9S/ECnqn7Qe89Vi8dSZG/HSMAluibmnX+/NTe0U7uLHW", + "fJ5f9odN+4P/qbHQ3Hua1+e08V36QnvG+fOmfj7JP6/yM2ejkc/6M/pnrsYAXcye8fH493le4TJffys7Ky/4d7Fv6Lx7JY07", + "2aLBi/0UGZLfJJ/0I4n1+dLNt4Kx+aOHwS790Um+foWMyC1Xs5iUT968SDbvxAOeGJZfyziWX7crvA5ecPBpBzM4Xp3iEH9U", + "zNi430cn/F7hAZNVmrzXev0s2uRs0xecdRy/n8Nn/ZrnPjrBK6k9b5D3Oq75mr13EozUdp2r/nkwdD/GT4Hf+vHgKCeL9MuJ", + "m/yNmz/mU4Br/HR23yfIz822OcO5GKkvkbVbjN/g5j6J52efBjP2G+Q3f0x84+KuJo/4JfJP6/VHyGJ+xvvtMT7laTFW3zyD", + "58d1+OoV8qU/xdfBYn4GfZC+S45u5+s+zW+87tcXb7nag2u/5c943ubBUzcv8YpvJL7un2b/XiaDtvd5y3VuM6Ptk/PgQ/dx", + "P+vs2i13/OPxehpT8Htfw9yLsYhnvPkqWqN+sKs647j112NkLg927xgXzLw3fP68br89wStj/l+3v8CTfpktiLlxmozvZ7xt", + "V/E644qI/MFtb+VEEfnfn8HMxA3u2FNSaqyPhx697LfvkG46wsokH0Y13mBzdheTIeJrmQDFg8ieRLRW6+HqeNMjjvM5NjjH", + "5DdLtyAx29x2RmYFnAd4EDxn2/IpBZ11J4m8B5cmK9C3Iak7b/90gkh0qFR70CciHHYv8jurG2PQnqjYwjO/+5n8i8wMg+wR", + "ht0aQtbaExoZBuLzawFCZ6XAXRnqtdhUFqrsV/YoxLknYHAIjDvhTxZMQZ6kIxBZh6FniSrt7yCymZjODo+3kB4sDkKTK4cW", + "F62uaW8ydx8D3g6T3Tq22Da8pfqrq+bOfO7Mjwb3ICt70LpstkUgkVmghdc5TbIH/e/KQCRzHslW0STGIdF9O0Z5DSwc4Alv", + "yEIC5ed7UV+IKF6/KpFNHJaixRhmuTgJ3aXkYyHFPu8qxraDTM1JbIlFcZrBDaFO2rpt0ntkGKCUw2Yqwvlg55HOYNY4UkGH", + "be7eBRY7wE1zvElLKMMyR1yINZ2A+SRmeGtOkNFwhTm4QZH2xNbrUAqHDSeqa+GwKVqdhGVnc5j1kQwKg6wX0xc2NVTs0CTi", + "4cRFZ698EWlFsvKiPDFPmiKfss0cNapGW9r9/Z3FIitceGDctEUnXlziRGxjpgCU1nPonlAdKHZsQQLCGWsLyHq0+AZTQJGO", + "nMkD3EWOGg6egUrcFYFhsr52hQKJ2pct1krMAs5H7VxVntKw6TJU2oEE60POS6fPJC7BMSIZf/nSgqQVYuvMqzSc7SdgkCzS", + "WrHZ9SAZk4auzlqkynfcJyu97k1aWWZbC8y9iAtkOAUWWsyQoyAuTbR3vYnQa9/MoWzebo52wAKWcrzFIC9uaPn8pdtM2hP7", + "zPq+hWO7mw17lqM2G3e39Shcp+KoZzblvgxBPucoCOFJMnxR1dLZOSrTJRY57bO8S4txRLI3R4zEVh1CsUOKWoJ9KMe4zbUJ", + "TfvoghNh87hLNHki9Aht854TdpSrQhm0lMyA94gX3nPe/YyjMhVSkKoFqU58CryqG4NNxNUlA64C/lIg3jSjsCXl6M9G21nC", + "1Yhrh0DBVCFJFHzVap43OVTv870g/lFCUgydOumKDCPcKVo+i+WpRGoCDjn/UAxe1VWKzGFIh+xs2R2Aku1xr+/DK21wIhaD", + "HDrh14n5DrBYUgM9CLCEJqTgA8HpKXyKnXxJ7rfdYeuy7wQrEnV3iJP+yB+uaIvBbFuez8tMxMEevCKB08LQZ3UvO2cOBSEG", + "4emEPBacL1WOA513YWNJAPv6qaMTnSETs9Px3sxKJ6IA7FGBJBWEL7Go4sOZ5EVCIjeOvNLK8jLIjUFstxmetDfBHr+1FazC", + "ThjO04X7W8Lkm2lFTCo+tjSFPnbgt6rglQZVhvUIksVBoiJaa8q3IgvpEs68pBaviARC55STIhVVERGCiogZL4lIkB9s3y07", + "pkitnPOyplqcK/kmiv0gzbBtIskzt6Vk9jFxZDtVNlKzKY+t2qAoTIhimU3yT+N0DAhnWyLQKWKZidssAWtsIhzId/8WtGct", + "2JEXzmYsf71JXknaxDnJPYR4ZK9z7RaZ3k7R6sg452Ui9Snb2jdS6hBOwx5NG11Ar2VeTNcSWHNEVIeTwU7FtlIAhHeTPjQh", + "WYuW+BswdxKZJKaY9Iudx6/I8fAsXa5LHYetkHFG2VbAPhgNBg8WgfEJ7ijOnaxgqDdZ8j2VP4IsW1snuGxjKhBgVaAE1T6R", + "EQiCQTQKWm3Ltdddz8f+yQt053LzuAke8YlqFXweOHsZBYMJgGw1PW213+HVik742dZyNUfIVupILhiAga7ddzCD480dmnZf", + "/Dxlr2A4Q2LG6Yz8DMZMszvxPFwZmEkd9FezeQlohkbrFBm5JwDhTd0k5qpE5+xQlCgZb4J+lAA4lVe11EMsGOLsycs2m9YS", + "4gV9wo3NKMEhcQSrUMwMvRYTl2EDSTxO+jK6qWt1b7MIhu3dqkJUgW+oJnBSRCGldorWKKkbF70PMj7XZMbe7oA1AcnGqCNZ", + "rajkCQhXy9jWiorYRRwrVhAFXofQsh/vZosFPtBZmbgiWyFeu9qOvBQR52nCimG/7tVetHp3BrQvDuTLOZHs42NOm6GTKVPk", + "KkpWFlWp5CvmNfG3wTsDcz9IBEQ+7AxSMFenbM9Us9qItkOsHEDzfbFlzxqstUTRxF5tVwl8FR1PACAReCqFtA7J69S2a7A+", + "/f8U288JwkZ0JEQfbGFESQT2kHTaUisnqYI0hVfT2yqhY1Zl7DJQ8mGrl/PK7cyBQnminyOofwn+PBa05UQDBZWRo/Q+zjmA", + "HJuc1b6ayQ8JWe7+Ryob8HrlFrqVyOeJLIxKBnGax3Sz+8xMzarEKkq2BqFc+YPciMEF1VpCACETcbzbp3NeCstyIM70phIT", + "7ZaLD6RiW5w/2YS1PbEKTXj360UjBEINovo8ppNvVdrDA1s8kw9J2ePWJTJaLJlUWtmSYcOMiFjAxMkkU4VPzuDQeDgJTGb9", + "bsiPkBcGZWx+tNX9rHBoYVlwrChXzskbMnr2RqdC0H25365dLI+ebXqxHsS8udW07PRewqThx/6caNN79baqpHz2hgJIb3LX", + "IMMKfyW3/TNiO9IatQeacJy+2KOW2gGBAel2Yvgwi5ZbaqsaqNoQCnMeJeBr6QzLn6PvNmoE/xPJ0CRcX3rSsJLTruZ8oOKU", + "yUtZSheueogreCGvsC3z+mKCtEKbJPQ7iDtGUYdcSGujK22VXXCPH0kQYrMY7cXtOjZvB1fK3yR6MXz0ln4KG74L+TEs4gXK", + "qnjMKpntsROU0vHSCZBt79ZsGWa9mGjJ1kg4WXJF5oSzTINVBGbTZrwqcTQpcquG7kuKfvUGZfegWZBmDZO7vY0zi8JLPZXX", + "sJQ9EV16JYoIl3DIEOWZSq6gbp55lMlKxXgx3huqIgHBJ3fLXVW3PSRIhRWA1OR0kcO4yAr40Wf3R4EOQ0Duo3ShBF+gjuco", + "MG2y+QJzGTU2DqJPYNHSNpIEW1/MajKW8rqHSaZmhcOCCNqj1dAsypwcsvxqcHdgI0jbICq6g5yZrU7vwLIjkjv8IevcuhcO", + "L3fYft9eRLkF/Mngrckfu1n20A/jqMF8J+Psji8X9335SHHgniN3fsVJ4mV5sl6lWfj9xq63X0eoQ1VbqK1NwY08MBDA2zGV", + "Z1om6N6kjchg70ucAYMmcxFsVwI/12Zw4Tn1oKZ/zj/Tp7EQhkUL/VYpblQZN9ViXr3Y7sg2cRYzZYp98lyDgTXxu4j4r80Q", + "+Pmis1w9699ZKa0XyuJe25kn4/5g2DxoFt+Dmzde6emP/oQ/xeH11y+RxcvTEKtSigFnXUu+pTxIgoSi4fzDJRlbxbNyc6Ve", + "H3N13DHAmQlt2NvmitvKrrTpPbhWb6JEhTkKMzlCsd05JDJ/IhIq8hH2OTbb/ZicEcRWwXJuRCQSK6ftXkOdg/d3cvIVPpb4", + "qN9hKQ/OLe+Hb/jbv3vgt79wl/1vaSo1Ej9tcph3sjCVBvrWrnxZzjcZNdDsgame2F/0zas4MByWExQZTMV6pk6cxa8CGzwa", + "Uy5jMtdZzjkppu6+vP82zgzbO6vRbYWrT7mNPFfkwfulXp2xklDYMykXZpSi2KtHlFbyJ1L6QwJCnWJmKoCeZFtLl3HbLFTZ", + "BiLOkKRIso5trfA8Gz3vD11MBStEJxG8/BnXPHlJE3FJdzI/FccuDuYpvEYjFY2JGklFgXbvzvv+fpA6FVLCIEmlHwxIrsB4", + "KhKdj0RikqjXVHyCFVTJiFEnp0rasq1cFqNia8eEd7zqvdTO1m1Ws7VH1tQKmFGMrXHrdGpfx06fcQkWU6kV3ySxQUUtYlp/", + "OcOD7Tx5OmJ3pgVn4357qylhV5tydWeWplISGVMv6h5cxUHfW9IU88wMy8xSBbkkD8NmqNtYEiqgdy0WDzTzdbfYbzO+VVfY", + "s+e3O1PbaaF6qIPmbA4AYmf0PIKTa7kxWkxlWPaO8nAI1HWtoSmajTmSVFy2OHs2ffbMP9BkSycTeqV6F7e3yIyz2u5O7Vuz", + "R+cz/bFZmeyjLv4ZLqe4FaZSeSjP5c4VU1GTgw9VdvaE1pynzv8AIk6DzTbrBBsFyT+aJHSsxYkXteOzUyEwMA+2ClkZP15K", + "jkQtXJuaY9KLz3WbeuI25x+yHWhmCSzCtoCSv7o8dRnXTXSHZnYqRb5jagtbnsootdWVaGum2IejPi9PXhaxc8SGPDbne89q", + "OVwhRZVtK91qZsoLjudkpmD3wlTAONO1kxBkthMtTSVkw1GUesqR+r9ff99u/Yf1f3/78ZHCP40byb7wKFG57/N7plILU2mc", + "JRqMzk5UdSO3D+ujU0wdTjNTzm5RrZrl29SlqIFlzUakqmW7QH8uTfkzZGohr2wYZDLBERmt6ZeGJOZUtKFw/94T2Yopx+7m", + "sXQflc6U4zoVfitcAsxHumnfSGTVu7GJA3uBiVhEbsEdCN9fAlQh9EbGtRO7InS29AKnW6q8dslWO1j7g1HrmGGitpWesKjN", + "6wOziYMGpKgZafLWzMSsS5z3xBu0GRs0NCO6c5+sFXw/kKeeikznx9zZdJLQ/1uaOpqLKXNGenLRHvoOie6AO6aXe9cyfFNS", + "u91RyHwSfoDq5LTepFy9TMao5Jgx3IFXGF8DdUsNZhsu8ixabdNjyg7ZObWKi0xpliGU2Ktx0Z1T69bVnv00mUo2izttGDz6", + "1HhLiYksJAFXssi58DLRjxR7WImjxFe4Fm7upYH3I54UplnYVNrBYCXXaXttpRYQYclEsSkvCaBQL4Xd6mwFFEVuGU/hboop", + "X7JYnMIvZUwNXAEZ6Klp2aGIHgA8IAlZZ9ztNo1arjJabFM7eybdd+vZURdTE2bKLgc0yomi0ULy9lOKEnMw0sBiexpWPId9", + "H2EPphz5H0IvLrnlUneMfgOLCicuo6b8XvJkM1K8vVvHMh4NjxY6nzfCA6KY8HW7Y/oB8zgpNkjbi3oe6fEgn9zBJsQTVGM7", + "5eilALGCdhnPp7OAZPW0zs3k0b4UhRHXSx7OnWrmaHYKiSfYCsttUWfbRtgkceqs3lhV5NhIQZx89TVVpP7UL3szNkHP86S+", + "9spxDxs4bb67/ZnuoPd8m5edmUppZrKELuDBjB1TL20dLfYyD8GkvHUizCcKRKlhz8X4kkagaN9KpkgFvqVWl4lCJAgjQdsW", + "K+DrME9boEu5VY/KWLc7ZzK8UePMlEmihGiOsdKkx+695247fb5SkaKEecgEU2uwo3VDu52WVerPqYRJ04yHa1JISZZc4lID", + "csAWIGN3q5Ov29nZevQpFR2U85mhd2jKLg8vK+kWZMp9UhMKdnJGkr2Lq+4dreJ8rNsqQrsHp/wjnaI4zDBqXEpJ6m1qJq9m", + "7Dr2ySmndWe9JpFrCl+tgS9augNBk1+nNHzCxXE03aK+z/tTc8Jp1QZtPgvxuK0qG/cDLVOF3WVmanuL0167APslnSuzU8t/", + "CrDXTMvVStg6xC6UVYsdemE5n2jFFESS62g8BOgztDUSb86iW55ra2vfmpmfmd4oWkEZRi+T9ixSVFMTm4mXtC/RgkgBO/cU", + "wyNqdcXtKlOpAqa4W+zuVFNWMu1G6xHZ9uI/sUNvEMlDCd7kLvRURG23q4+1e0HkGTwD5wRjPBsDtyVGrSQIbndPJHJilGmz", + "sfZJ2eqB4aRWY7Lk/OjBgkeAYaMqsusyux4sNTnUwH7keIkiM5Zmds5Mxcil5pXkcRK8k7ti1k5bM23I3WckUiiOdDjq4goy", + "+F2ZxPee9poQYetM4S0y5doChy33rIjYu/Th/k5/0Ckk9BbSy4cOzZn9a+2iI4+2tFLAEYath5BvapOnHLEcrSgwa/I3SwYZ", + "AqFh/ZKpxSYSt2Ducunu4BZqk1w5m54d7Z7yrptWj8lzYGXSYSAaONHCDAYuQNP2vvw2eQGZj8cfU2cjNo/Mymu9KAmmJaFy", + "sxRammzZZ0zaeVaVvloSeAx8aqZQk84rRrCc39RmgZ/MTfL/WjbQLKgIyzg6XVp6gyIjTHNosq+VEE31ZVbkJ7qiMYH7yPyc", + "Daq8rko6WwL0VZH4ySctmj09EbZkSjxN7SFb8pVDCXTHjlvv3sqbZ8eW9e4ULDAStG6fedbCF8VU8Hw1dgEl5Kbw+XMtRxYg", + "f1P++9IUhtxW2Fbz4GAD3HjNgzbd81jCBz9C7b/YND64htrl9q9k3Wc8C/WW/mJ1OuvRWef9HlkIogI/f+8a68jf9hr563lV", + "ur37F6pF/x+/BwaA9pofPv3BRXIMiAUh+6S9/6xzL5BvgH9dV3W8V3nnd3jZWoB68KusT8+YF+yv9ppgI3h4igsgq4H/8Dtk", + "HQGfA655kXwHqjEHN8LD6Rrvsg798dQrZJNgb7zLevg/ZXX7RVaSP+u98h5ZBq5O1e6DNeAyq9HfJafES1PPh0r9ZxIvw8Pk", + "gnjzw0dwt5blAJ/0yv4LXhl/nfX1aM+7vGu6A0Yp64nL/HmJte/+vfTeOx/8iJ9+m6wGF7wa7bGbZ26+/tGT6benokKIVVxX", + "WMnl9VRtdZuq5lId2xusO3qV1WRRcRd1Ri/bZ67YXy9NVXGpnurMzctZddJr+SfZGrumV1W9rGoqr3tCjd9Z+96j/t4J1kzp", + "KlduXkd1lz/Dw6gBs08+4d97g9Vjp6cq2aItqGCLtrx88zzr397wmq2Hswqyl6f+OsPnfQp1g/jroxNtrVbUgPn9zrNi7C1d", + "kz15xv695pVcT6EKzu+nerRzdpVr9l3VsD3qNWJngjXH+/OJrJ7tZdQhtnfPn8HudAb1a+m966oHhCia2YMC1AwXkxCmTqJQ", + "evEDvzMd1c0khUkHKvmVKILBdocNzXOlyLl8sxXMW/qt7mCVnFQMPjqzp22JFbJES9MB46nMnFm+01v5dHKnaQNh6xXSelMh", + "3RmCSFYhTLtKqG2knuDnA7qo+GFKVuaJmyYiO94qj24o790pMmsvHS7g6RQocWb68ItLRXy8DSPQeZ4KbdMXzfy1XYtTruqU", + "6d9Z3jWdhVuZyum0z7s6GDxY3xJBXPgW+uobsp337VnMNURAB+o65n6p+elkB47ZzDuaQn3NzOTJYzs7l6ZHJUu/4cqdKWxB", + "p63bcFbqIhdh8SRqzCt5bCks2VmeihpOW19L5ujq80cHw24zF9naQulaF/BOrN0ZeyoEI6atNWvV0arXa2ULipzFfed0MMN7", + "xcWwZzLV9jBpPPqblNBH9Yorxrqxl6pWphyefdOpqqViOhUfyQC3Xr5IzftEyTsd4vy8Z15tNt5v3T1piebUjDZtgXogT4NF", + "EIgTudXy7hRTa6WFm2nGw6ltbcovD7F6B8eKgxvj4epGJlyMD0/7vcR3ZYtHQJYNQs3MiPvWrtnc0tJYx+M2CceqS/s0azKA", + "5n3MChCml5am8MsZ1GM87M0yxty6pM0t3k+k5WQOT1VX9pNXmwWs2jQF75v5PRklID7fei4KhBVTSRXGjdr+i+oq93xaQC8R", + "k9O72fLRpGnNqUIq1K+DvByX3p9peGdGf3izwf3rkshmmAanpPueOZF7Fk0Sp2W2ykRrFrIviKZM5dlCHnzcugNFsOQy5JSH", + "IYvct7MRzRFUjMP0euVW2ihZE9lGX5N2pd6V6IwjZlcmmY680yfactaNiHZelzq9tga2qi0NSOtYIIZyuu707umNUSTwyS/M", + "wmThymZxpq/2JbVoT4jBW57egnKQI0Ohg637h4Otcr0MtmTXYM5qUCL6mpV9YIKIVs5c+fU+IKFVH/Gfw4iX2jO2eWfd6BDz", + "UmlU2q2KW2FWGLttc1Z+7HawTk7jWZwLNMX7p2qord3T6B7FcxOcLi92CTR2mwWf2kR3zpiDn0tZpbmqTYY5EcdLYpVphrol", + "sa9uihxkHEeMajoXi2kYDpZGprkj5sNiVpyIu5LKoMQM2yNV4oc5+AubW6pHxYom3ccZ0nSIoCmxAD0TjBznM76pi8H/821n", + "hgFdyemgFbqYcVKdDoqP51peF3z4ojNWnXreaUyc4eeHwZHyPslAzjltjr97xVmYnPUlb1Vilfl+ECslUpHg2sJ94/POoWRN", + "fZJfOR8sNO8Hscy1jFvG2vwIOEbwlR/xyj8m7cmpjHXqhaDKec6v7Jd6MThzxMTyfHbZn5IZ5ulgUzkdzUj8MGJAejXePTtF", + "OuTMJ8H8k4jC0qB4T55yWien5HqYb50NypfX4+snguPl1YwDJyihcKM/j1bpvuJ4eSsa/0LQlD0ZvEan+JZor07wjk/wymIM", + "+3YQOp0JEq2X+fuPg48op38RW9FPgwHmGfaMrvx83Pck5+EzbOd7+PcV0nk5y9BVp9DB76eiD58NZio90bmYPz9AY3ApsYG9", + "yktdjUF81Se2P8K1eN7oSZ9sz/ArifnqtSA7ej9olC5H152K532VVEIvxndPx3WuxBhpbiQeuVdj0p4KSqIXggXoTMZy9lZM", + "Zt3ieKygRD+VWHROxWp6OHaDx7NReC8YgcQv9JJTD+HDz8WIvx6sRKdjLTzil/J19O244Ivs57SfnGi3CO9MNemHMduD18uv", + "LG6fi/HhmLHek4k0LLoOH3vOv4K3RNkUXF748/W40QuxNYFFatg0v5NrbOweTWd5+HLO5T5KIGGm1acN7pmlW2AYxVRdWa9e", + "vsUrHnnN6Lzt5bzU/KodQg+2ma1i+jzZfYtJOxPXT351Oe2y71q8JTcE9HLXzB0ZKPuKW2zVFp9Ec2hf8LF7KLa4XbhklGv3", + "gTIKXcewqpcYiYVGGigCqv1C4LXewi2e3wzgGLneWKJ1Ce3ZbpfwuXvoe1TDhB9WQWzR3DIAC7fECpwD2SzTZmJX2OxMm5B7", + "RyQO39/5OjL3D3aWyUlTtMjLDO0NON7izC0Rg7liOptf0sRuNbtucdaX0v09w7h4SwcIp9CaqsTq5OWZxTTiKXN+VJeZ6XDB", + "CgpXM3zN5OOS/6Gz3LnFo5opiqm0Ki689z9lhR2eb7qjWivNDptVQVeiUClunzwkVXDnqwdx0DdHG/b+N9F/39wGfDVzDbNf", + "BXS5xQ/JMLDAeTQ5Lzi+cFhZpyRpk+sNqwZHy8ftxH2O1EgG5FTJCK7JXugPZCt2luWqtFjJvMSR411M40GnZ9eePb4+dpt5", + "WELwQ0WaKHlRfCjzo0k6Quc/09aDFusqZvCq3PDOtMO/+y4W0DLDXDaD/twty2FHc/vkSLmOjP9ss+uP9vzXW0zbpflbXmhn", + "ggJkt7FZt93mfsNtWX6MHehBoRQEbPF9jmvfou9RFEv65RYfZOThjDR/V27ZXxLHuEStd/3suZ+9bf9962fv/uzaz67/7Oz/", + "V9e19UZ1XeHnjMR/OJkosq16ZqBEVYPHExmbNFRJQKlRUvWhGs+MzcDYQ+eMsa2oUoyBkqSERAolQlVCCgmOG6gDcRgIxlL7", + "B/Abj/BSqf+ie932XvvCiy8z57ova6+91re+b/ccsAFjzJzyIA8w0r2DEfABRuDvINcxRtjN788xUwGRfOT79fMdzPl7j77F", + "s79AhmDgE97GnMCXmEXYwm8pY0GMysj5jL/943UEnvmUmQN3sHse8xiQHdji7MQWZwUe4RNc2j3HPLzEGg05mB3kG14jNlvz", + "/Px+u5/w+21jvgSZss0ZW3574NHb+KzUPltBdmTTRfcVJx7zkqm49nmIdHNcWUX84aeNX/+gMglrwNT2ZJ3Pv/vkPnDm0fWe", + "3AKWMryD4yajsz6yXH0XkO9Nvsf7I9/ehuQRPJ6zb8wTnKVPgmd0nHd8v153ptvXYi02l0+53GLN1VAyYVk1XKPQxiHIjS1d", + "OKmqlhgK0DJds7gi14+a+znZYRVQDCdSVSuFYPE3RQwQ9EJ/EggesToLHFnjSK7sRouBeXPYOYvQX4KUaMsZfFSd7y7gFMbJ", + "LOqe2SGQlOwZi1j2mBv2FLxIC9QqV/3MKKw6EnPmJvTcFoDE21O4Y4oij2N/6yASmR7pF0H1+lxJ5ohC6H2wLXVwQK5dEG9m", + "vDgBonmj2Rutzmmsdx3FftFZEBfC4JNdETvu/M1iw5h/8wNCI7Wq56GB6lOATQYZNIhu2hqgKFExVGU09HhxsT9b+nWxVnAo", + "TQtIPN2qd1RYEsJY1JtZ3sLoeLjaZaE7hEAfieshxkSXU8GjA4JjliSXaBnwK28QkKCKxlXdKuLuZtvLxVrQtXsKUGrTKjVB", + "l52IMSgWDG8GCyogGWcziqNOGo/LLFr1HFTlW9nJdgeQNT2gEgxcR8IaNfp2xFg+JAnCHT3exRBWNsGKuaLgYV+fcwId+y4H", + "Wwsn6qBcAuxuJ82DmG9bJXCxoNXm6vMtth+ukscc/C4JQLGClmgoZeIcHO11EYT1G/PPwgxUDGsiHAHMIioH2ZEQ8aKowAgW", + "hegUrabKzG6SG5Eth4uPS0xNIJgCDnHevTV9GFPMK1KaZtuDZaXAx8LoY+6XQgEyiDxUF8ZEColFKMuDUol2I/eYvzBmymBv", + "Em+qz3V5Hu+RibwndAsKgB/LtNCzGTOjmbYIHi0U3OWtttkKQSFv9i5mMnNXA8G20MHQeBwoZ4ZMm8cfhu3RJTgciCRh8Bxk", + "nagTmahSiCkUlMnfQpSNa9dAqJiIIbXzbsdWxSAyWBd/S0DziPGILdkJV7k67fM26C8KHoXYA6jWxl5US2BjPfQ8YvLafVtW", + "oIV4WUnHDBNW2CTQoi1aqYCCI+iutfyk1ERopL0TYFVsgCgS4J5laPeXuiXj8/asMOPUIsvhAVILVAmb8gFcrtfuNv1Chowa", + "yN9YMT8e5+06Kx4poZBjWeZJWHZRmLCn7IfHX4cIXBw9FC/HpvY4NyFvYTcm9ZkciBPMniw0wjbIfUDi4WNqV0obpbET9WUz", + "32dyjidU9pVdikqqjagzVJy7wtNauz/ogoCVLyERyXjR2PPT9YbZfiGKGJa/1nDx5f2TqsxvKHrm2hGl+4YimqNqJ0i+0i+r", + "Djwpa6ki3TCb4nr/gFnQzLoFeDSZhNHcL0QOWR43kPaeiDsni0aeQ2eKwmMxCx21YrSjVLxmfHt4rFcqna6xy1w92VQDlAak", + "qwQUrwDZ7DorioxDdBJdHdZY5ATqRDnh3TxyQzweaijqzRUkWaBqND8VBOuw9S+sq5p5CRXa6yLlGEmo4o69+uLUkcnp3x89", + "lElXaNIe+lmshTEpr4MxquLj/eBm45GjAXg6Idtc7EBVaWBcjK3wq56gX9+o98zzNnVExzlVXDVNrjLU10ow4MgySHvpZZu9", + "8pOtFcQKmBnDb6FGmtopcH3mLDJNdFQNsR7h5J5nkdvu12RgdUe00JSj1duvpUCL3oFx0lHJdUCu4qi3rB/gE/qVjcIc5epO", + "ZFEj6bDZPhMVCiNVprVAnXuhK9yogM6bouAwNny0KNUI6qOg3+tZGGOajp452tf0Hb4YAlGtXrfHJD5mIe4s5kgg4RVfYvRF", + "q7PRbs8MNSoRttw3k4cnONz0uhkrM93uSYsNcEwZCzRy6jZ3K3XXzihj2WtrXlXvI9NWvwPxswYpxlLy27yJhI9GpS9YW1hh", + "1ckK5Iz4P9LvK9XIWmQiJxayINWuyE4s3SdsYBZ7ziWY7C7QkDZuAm2GYbTMGS9nMedSvPwogH2Bt2POJcQ1qtryBwGdiwMY", + "EEhg3lXn6ExohhuCevNEHTE1doxh3MsLCBsnP2cCIst6qjhhienGXBcNrU3MHydiUmEox3pGRkrYcOsURB7Rh5JabEsLnFGF", + "qtAa6UolqSJ1jMTkRGreBIhHdns6qoalY3R1KsBqIG0IDWAzPHpI8QsEhwI78zYFdlrZaCN4N9CcXcL8mPFlYTBZ/XnroNsp", + "eW7tkmm1POBCMPOU8U4KoXKwC5YXCGGYPS8PasjMlk5BAnlkBrXw4JhTDSX0b7cPxR+5qG0KBRPw8yjed9wn+NW/RNwd7jPt", + "vYFBYLl86vipAGtnRl9kaAuOHVOoj+pAztVFE8F7XT9KC7KOPsYca1GZCMr58dO6wgHfXeB1Rbp5cWTM0fi0iV+25UHtsIlx", + "Uc00RRyXaWFIhrjV9o5lQTLK5yfBcYgrLO71KssliAirm3A/ZtF2Xn9LUTSbfrB/kM3E5znVRk6Xx5/tfvT4Z8Auo14Y6ZSF", + "n9wgFTBEkp+H+C4ruz0IVNhE1Y5jnP4nu5c4qnqXFd4grgpx3R38nyPDj3/AM3cIVY546of4F0V5N839KBp7D1HlHGNGhDfj", + "uvnuFFH+GXX9SNeM7g647wf8FsHzQEwZI7jbHDH+6+4niDw/h7j5Acd6QdnuB44mbyP6exs12rbw/vSmcAzh8OWTB/QWrNIG", + "d/8Uj3+AmnLboPKH+daLAhjYlITsBcyormJu+g5meym/bAEMSneMJZzOySnfSrr2vqTXL0q2mlK6Xyutq28VEoDy3VqBS9AR", + "8LmcBXnnq/j3V4ziYC0hQlxcVcnfMyrtvo7PsKrUfx6p97JoGfsWA7nOZ3jKHdE+WxdwyKbgCj7A629y3pyxBISrIVmcWwIR", + "eSiveQFP0WdRy6h25jbckFOUCo/DGFyUfLoGV+wo5MaGNPKH0hH3FT5HtaEDkFgsgYaCPJKuFzSCQ+P83UEIPM27VYVC+Ukh", + "Z65Li+1I79wTUIQCF3lIj4uigbWBf+wgwuQR6ze5pz0janqEHrnqQ1PuyME38cQz7k3dvTakRy7jWbcZoMJifDTAbkqb3BYF", + "Lmq6GyKzJZpufPfb3uhlPbsL2JIfIHCFYAwfCyiIRO7oef6m2v+8PN5fZDzbdv6ecSkOVvRQRu+6TJ91kaCyY0xQN+4T6qZ1", + "1c5b7joEDuF5sS4zzgpvreMT/kuJwaFiIPx7214nziN5tSmuImXNHLWO1RwbtqpB1IzgmPvm9788dR73ieg0hfmh77hO5AJm", + "qH7ELBVdGWpa1lGxiJ9HNI7UJ3cx23XWZqa+x+dahWoO1vG5Gd4Lj92Sv9SGUkIwS/vL3d5cZd+rr75aWUYSH9gjhEEh3PbC", + "t2OZTQVEURhhbVL6HEVgbxHW7/Fid3a2qCntmMZvDOQ2IFUvoH/jsUQBpeyloD4E3ECdsuIcjvWyXiqmBHz4ZC3owR8VqlE+", + "plI59HYx0zdcAtKSZuvYO4cnocR0Ab0lvuEJ43XTJQ6EiWfUGA9yKnnDRnUyG4/TdFZ82yz27uL9uOeQ8Y3jrs3ACw0iWpKo", + "wHanQFQl0bdx4AlbAjuZkkKv1QpLURrktSD1hrEVzPV718qiHeuBON5SwGihp+7Rr8YhqSwdKwnA7CowIyf74xtfypOQIFYH", + "r+Ac+cIyn8LAhey9gL8ux5aGDp8JwtU+ZBlOVuRLMkSzKJe4z9aZYETOTIS5GdDz5qCA2UvPAaIlmgjteQFVqS3MRKPebM1T", + "XIKQI7mKJAmqR+8q+fHLZtDwJuLgyuHmcLs5QkxyJwSYDVti2WYItdfIGDPOeH0bu+gFr58pRlaLI8aCVW65KheGiaPwBXNg", + "aE0HTl17GXD6GVuOtqcGQWHFgCuM6Aag7NkTfoBUHOz+F+b6QKw4VZ4sx+O+RDwMwgUBgY1RLU0m7B5uV9hU5dZB2ZBKmEmo", + "kyvEIP8n8ccsDkDOt3Nfnq07a3mqRrPjvCnM4+jmpDFj8zPturpYa9kMSCZF4eKUxZzUCVS7cSDQy/5CuMYP2tVnZ0F0oa9e", + "CLHn3MY8rVzwTjHERSFwCazAcYfhEgtNDXXkmeaycHa3rSUDeHIfkdzlUmvGvHMLmUXqkGzs9V3RIq12EAOySTfAGUlc0WZb", + "hQTBsly8zpFd9cgMZdIKQMwKr4fJ22Y/7PqL2B90iVMd7U6jfqougiSOBU0Hbr0hB6UpNORmF3s4TpUdc+1FKgZQ3yFyFs6U", + "QghsxbTBHBDAEbFZ3EFVPzX0XunYROnU8ZWc0A5WpAZwgGZJBRMmo8/GphrwRQPQdsPyGi45imYAGx5xI/SOObNy2DgX15xZ", + "jwZUeXT4hwKRIHXVQ44pmCaYzsB+bIC2YA+IIqBdXt5/6OX9kzzGzD/FkZGxMCIFK6RHUigxbDOs/hjUPYb4WoBZBkYaoZdx", + "nu29EvDITpmZNDwCRnu6PW/+yuIQTNFbVtizcB6S83mCglxUpbPvoFwjpKqV2cX2XI4bUm3gl84y3tjCcVQWL+EycYRe26e+", + "OEj6zkzN6rsioKy3NI0cw3VYrld46E3a0kjsAa13J4bHA9/yjXzuDi7qCXDOTFsx16vPI/7FIiC0wJGAl+z1HNrCK6yV4xIr", + "drx8/qlYTTg0ajmyPqqXv+CjqZWDnvpVrQovqoewMMrpEYhOXVCJHeKtsT43izPJxcS6mfDeitSXfa8v84Tnt6cQP18tNfDZ", + "GIggHeiPjSUWDccY5gRTrHKVqJO0QcyAZRs0Bpsw/x7AKsh8VuGnpybBeTF6H5/9WE290912c3jvyFjRYxy3pc7xVs3lHJzp", + "riVcbh9/SH8FFeoILiEMFGqOEucdvK9itpLJUI2DzA3OasPK0WnPYvOOejqIAkaJTVjmOCjhOHIPmu1THSIWtQw2ueP1ce+L", + "AyPAv2WJNuDkdS4+DuYXE+6jp3alXDdPros4vqIdHUmpYbbb/qWlm0SVwozgfphZMT7uSRqJbmw1RSyC7ZcFnYkgErep1epR", + "x3Fey9seBQXSCCXAPj0NOCKgQW4BO1JOnt0pyHdapqthu0F2ewjVVjYj6liwnX+U6KJalthAIgaHQAkIHIJnI/kyHw6BIxJl", + "gRy+UqlTob+y1M4BS4fZdJyGUp4M9iW4uV94SfOS9MNamFNsN+n9+IXgH5t1tFk1tUBAh3TnzchVjpcnl8g9MJuwL4jHZFko", + "xgchmf7i3OJ/NvJsmHLriyPCh7N75fH27ipmOzYxhxB89vgaZg1WkSOIciP3w9wFIczNOWcxC/BQ8inmepIFcTmEbeIMkuwD", + "cOvE5zJWPvzsGmVRzHUBwz6wGH3Kh2xZVp74ep/Q88ITO64dc39iB9rEz5APR/hNMOb3PSqvn+f42o8cKVxT2PEz9NmTW/CZ", + "v0Ydm34dbElO3pcxlKoWxi/dZTlWz+rIaEJak/FsCMeaGPvI7IBHFUSyKDqUp/ysYmoxUBhxZ5KsN1JQ7ghOt3D6VVNOinzp", + "eTiuKkSYwIzHFfmMcOEMOMjbjZPeKjcsnq1ybP+sCEPF0ylmR9F1H8r1virLUg556GijNx8t01SS4i1d9Cu07erI4OdLwPsJ", + "0/F9M5VLXLZVSPm4RFpT88lraPEKwhFyaEEfG7gUheqLpdIffAKPiXYPnqRWSLRIyjNdejq49nRw5+ngO/h5/+zTwZWng388", + "W/vm2dqnz9auPVu78mzt+rO1q8/Wvvjvrev/++fntuT8/qr5b0TyYpuSvKAsw9cYt/+QU2Cc6JGsDVdcXpR0m60qDTI4Nj1h", + "kwK2CnVDikAHnIWEsy67QlFXO2wri23x7BWVvgkSgh9LEfSO5LC+lMc7J/WkmyrJaKuGbb5yXQp+deJmNSrNvswVppwU0/ms", + "oEz7hhTzXuSidW6Tdayf3ZGvNiRBdlmO3JGU31fqdGqfM/jM+sMNqd71q+D5aTdVFvKGyhDZfqezrsuJt6VVzd2/9oRL7S44", + "RhMC/kC5EaosLRr28It3J6EHAWQr6jZSf4MGK9xfplb9Yi20gTRdEnH55fmOOtYZs4BeSqyn4qRRuxmzCiR8qJQ/XKmFIQ3a", + "1ZTTllvtON2k14bUWdcYfwnmM9iGcjWosu5qi1eqVN7dP1mpTE1PZe+9Mf3Wm9m+8t7M33RJRCbY8DBVlnlc5mnCrRvUSJiG", + "Knirp5ziIhm/NY3+O270VDvmB+dS+78saCze0eJdhoLeHIpjUAgg8q/A/Zoll6zxoV8kMlDV5JJZgETPaNYH5k549VFMvamq", + "L1WO5teRyzhLmv70BPCXM+sgpCJFpud77XqJusC8eW/RbJT+fa9KbR/Og8743jGqQ1fu0ftq449D+0AGzEjJgXr8hRdS8bR6", + "HxTkwyepJZf/5Fuk19VWshnGe8nbtcZTzor2xpvd7GDPOOmdEcW1OEDeRsLy3EFMEPjIPzn8jsc7eUeqMbH28i6xRypMU+IK", + "5lO4wiXihwSED9We+tYzO3rs4JuHJ7PiQr80HRAZQPfFMZVJ+B6iMQw70/lVssTGEC7kuu3T5mDa/Eu2c1+p711QubbT7/Ah", + "lYSHbGbjmK6AVEsLhor6b5tJVqa6lYMIf03aj4X6iTwes+ZKdjs7UkY8PA/e2IfFE3AMx2tNHHXEr1ORLrO7VauCduqr6dUi", + "jlrhQ6k1RFPuJTABOEvSljKOjmAj18vJzUqyWedbx9OvyQpR4WjR4wSHySvlvfuyaX/1twnH59yz+pzuKWbpFSzx8pj2HE+2", + "YX94KEuvC89pr2Iz7cTkgAzuJOAQ8fvT3Kim3RPIJye/wLlUjls6mss88wM3wi6Oz+nCwnOas5qy0/Bez2m2GqIzLykLxdaL", + "MJhSO8+7fod8HDCK0tahA/oSbeUOIhrtdQRrNhB31XrrlwXtdUXBygY+xu1jxQpD3v1NBVyyiLwdRfCzw9dMuPO0cbmMFFOE", + "29oUrNZXqX3Ghr8TuigkT48Q+TXwvXvGjv0foSWBhw==", + }, + context = { + "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+PwABAgMEBQYH", + "CAkKCwwNDg8QERITFBUWFxgZGhscHR4fICEiIyQlJicoKSorLC0uLzAxMjM0NTY3ODk6Ozw9Pj8AAQIDBAUGBwgJCgsMDQ4P", + "EBESExQVFhcYGRobHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2Nzg5Ojs8PT4/AAECAwQFBgcICQoLDA0ODxAREhMUFRYX", + "GBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+PwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + "AAAAAAAAAAAAAAAAAQEBAQICAgIDAwMDBAQEBAUFBQUGBgYGBwcHBwgICAgJCQkJCgoKCgsLCwsMDAwMDQ0NDQ4ODg4PDw8P", + "EBAQEBERERESEhISExMTExQUFBQVFRUVFhYWFhcXFxcYGBgYGRkZGRoaGhobGxsbHBwcHB0dHR0eHh4eHx8fHyAgICAhISEh", + "IiIiIiMjIyMkJCQkJSUlJSYmJiYnJycnKCgoKCkpKSkqKioqKysrKywsLCwtLS0tLi4uLi8vLy8wMDAwMTExMTIyMjIzMzMz", + "NDQ0NDU1NTU2NjY2Nzc3Nzg4ODg5OTk5Ojo6Ojs7Ozs8PDw8PT09PT4+Pj4/Pz8/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQEAAAEAAAAAAAAAAAAAAAAAAAAAAAACAwQDAwUDBAYHAwMIAwkDCwsLCwsLCws", + "LCwgIBgoHAwMMDQ0NDA0NDQwNDQ0NDQwNDQ0NDQwNDQ0NDQYDBwMDAw4PDw8ODw8PDg8PDw8PDg8PDw8PDg8PDw8PBgMHAwA", + "AAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQIDAgMCAwID", + "AgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMAAAAAAAAAAAAAAAAAAAAA", + "AAAAAAAAAAAAAAAAAAAAAAABAQEBAQEBAQEBAQEBAQECAgICAgICAgICAQEBAQEBAQICAgICAgICAgICAgICAgICAgICAgIC", + "AgICAQEBAQEBAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMBAQEBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAICAgICAgIC", + "AgICAgICAgICAgICAgICAgICAgICAgICAAgICAgICAgICAgICAgICBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ", + "EBAQEBAQEBAQEBAQEBAQEBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgY", + "GBgYGBgYGBggICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg", + "KCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoMDAwMDAwMDAwMDAwMDAwOAABAQEBAQEB", + "AQEBAQEBAQECAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIDAwMDAwMDAwMDAwMDAwMD", + "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE", + "BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUF", + "BQUFBQUFBQUFBQUFBQUFBQYGBgYGBgYGBgYGBgYGBgc=", + }, + prefixSuffix = "ASACLCAIIG9mIHRoZSAEIG9mIAJzIAEuBSBhbmQgBCBpbiABIgQgdG8gAiI+AQoCLiABXQUgZm9yIAMgYSAGIHRoYXQgAScGIHdpdGggBiBmcm9tIAQgYnkgASgGLiBUaGUgBCBvbiAEIGFzIAQgaXMgBGluZyACCgkBOgNlZCACPSIEIGF0IANseSABLAI9JwUuY29tLwcuIFRoaXMgBSBub3QgA2VyIANhbCAEZnVsIARpdmUgBWxlc3MgBGVzdCAEaXplIALCoARvdXMgBSB0aGUgAmUgAA==", + prefixSuffixMap = { 0, 2, 5, 14, 19, 22, 24, 30, 35, 37, 42, 45, 47, 50, 52, 58, 62, 69, 71, 78, 85, 90, 92, 99, 104, 109, 114, 119, 122, 124, 128, 131, 136, 140, 142, 145, 151, 159, 165, 169, 173, 178, 183, 189, 194, 199, 202, 207, 213, 216 }, + transforms = { + 49, 0, 49, 49, 0, 0, 0, 0, 0, 49, 12, 49, 49, 10, 0, 49, 0, 47, 0, 0, 49, 4, 0, 0, 49, 0, 3, 49, 10, 49, + 49, 0, 6, 49, 13, 49, 49, 1, 49, 1, 0, 0, 49, 0, 1, 0, 10, 0, 49, 0, 7, 49, 0, 9, 48, 0, 0, 49, 0, 8, + 49, 0, 5, 49, 0, 10, 49, 0, 11, 49, 3, 49, 49, 0, 13, 49, 0, 14, 49, 14, 49, 49, 2, 49, 49, 0, 15, 49, 0, 16, + 0, 10, 49, 49, 0, 12, 5, 0, 49, 0, 0, 1, 49, 15, 49, 49, 0, 18, 49, 0, 17, 49, 0, 19, 49, 0, 20, 49, 16, 49, + 49, 17, 49, 47, 0, 49, 49, 4, 49, 49, 0, 22, 49, 11, 49, 49, 0, 23, 49, 0, 24, 49, 0, 25, 49, 7, 49, 49, 1, 26, + 49, 0, 27, 49, 0, 28, 0, 0, 12, 49, 0, 29, 49, 20, 49, 49, 18, 49, 49, 6, 49, 49, 0, 21, 49, 10, 1, 49, 8, 49, + 49, 0, 31, 49, 0, 32, 47, 0, 3, 49, 5, 49, 49, 9, 49, 0, 10, 1, 49, 10, 8, 5, 0, 21, 49, 11, 0, 49, 10, 10, + 49, 0, 30, 0, 0, 5, 35, 0, 49, 47, 0, 2, 49, 10, 17, 49, 0, 36, 49, 0, 33, 5, 0, 0, 49, 10, 21, 49, 10, 5, + 49, 0, 37, 0, 0, 30, 49, 0, 38, 0, 11, 0, 49, 0, 39, 0, 11, 49, 49, 0, 34, 49, 11, 8, 49, 10, 12, 0, 0, 21, + 49, 0, 40, 0, 10, 12, 49, 0, 41, 49, 0, 42, 49, 11, 17, 49, 0, 43, 0, 10, 5, 49, 11, 10, 0, 0, 34, 49, 10, 33, + 49, 0, 44, 49, 11, 5, 45, 0, 49, 0, 0, 33, 49, 10, 30, 49, 11, 30, 49, 0, 46, 49, 11, 1, 49, 10, 34, 0, 10, 33, + 0, 11, 30, 0, 11, 1, 49, 11, 33, 49, 11, 21, 49, 11, 12, 0, 11, 5, 49, 11, 34, 0, 11, 12, 0, 10, 30, 0, 11, 34, + 0, 10, 34, + }, +} +end +end + + + + + + Lzma + --!optimize 2 +--!nocheck +-- rosetta chunk Lzma (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 4 modules (3 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["codecs/compress/Lzma"] = function() + +-- codecs/compress/Lzma: LZMA and LZMA2 decoders, the .lzma ("LZMA alone") wrapper and the .xz container. +-- From LzmaSpec.cpp (Igor Pavlov) and the xz file format specification 1.2 (Lasse Collin / Igor Pavlov), both public +-- domain; the BCJ filters follow xz-embedded (public domain). +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Crc32 = __include("core/Crc32") +local Decode = __include("codecs/compress/Lzma/Decode") +local Filters = __include("codecs/compress/Lzma/Filters") +local Crc64 = __include("codecs/compress/Lzma/Crc64") + +local readu8, readu32 = buffer.readu8, buffer.readu32 + +local Lzma = {} + +local DEFAULT_MAX = 2 ^ 30 + +type Options = { + maxBytes: number?, +} +type Props = { lc: number, lp: number, pb: number, dictSize: number? } + +local toBuffer = Bytes.toBuffer +local args = Bytes.span + +local function maxOf(opts: Options?): number + local m = opts and opts.maxBytes + return if type(m) == "number" and m >= 0 then m else DEFAULT_MAX +end + +local function fail(msg: any, at: number?): Err.Err + local s = tostring(msg) + local code = Err.CORRUPT + if string.sub(s, 1, 5) == "limit" then + code = Err.LIMIT + elseif string.find(s, "truncated", 1, true) then + code = Err.TRUNCATED + end + return Err.new(code, s, at) +end + +local function propsByte(d: number): (number?, number, number) + if d >= 225 then + return nil, 0, 0 + end + return d % 9, (d // 9) % 5, d // 45 +end +Lzma.propsByte = propsByte + +local function decodeLzma(st: Decode.State, b: buffer, o: number, e: number, unpackSize: number?): (number?, Err.Err?) + local ip, ierr = Decode.rcInit(st, b, o, e) + if not ip then + return nil, fail(ierr, o) + end + local target = if unpackSize then st.op + unpackSize else math.huge + if unpackSize and target > st.maxBytes then + return nil, Err.new(Err.LIMIT, string.format("output of %d bytes is over maxBytes", unpackSize)) + end + if unpackSize and not Decode.ensure(st, target) then + return nil, Err.new(Err.LIMIT, "output over maxBytes") + end + local status, res = Decode.run(st, b, ip, e, target) + if not status then + return nil, fail(res, o) + end + if unpackSize and st.op ~= target then + return nil, Err.new(Err.CORRUPT, "end marker before the declared size", o) + end + return res :: number, nil +end + +function Lzma.lzma(buf: buffer | string, offset: number?, length: number?, props: any, unpackSize: number?, opts: Options?): (buffer?, any) + local b, o, l, aerr = args("Lzma.lzma", buf, offset, length) + if not b then + return nil, aerr + end + local lc, lp, pb + if type(props) == "table" then + lc, lp, pb = props.lc, props.lp, props.pb + else + local pbuf = toBuffer(props) + if not pbuf or buffer.len(pbuf) < 1 then + return nil, Err.new(Err.ARG, "Lzma.lzma: props must be the 5-byte properties or { lc, lp, pb }") + end + lc, lp, pb = propsByte(readu8(pbuf, 0)) + if not lc then + return nil, Err.new(Err.CORRUPT, "bad LZMA properties byte") + end + end + if type(lc) ~= "number" or type(lp) ~= "number" or type(pb) ~= "number" then + return nil, Err.new(Err.ARG, "Lzma.lzma: bad props") + end + if unpackSize ~= nil and (type(unpackSize) ~= "number" or unpackSize < 0 or unpackSize % 1 ~= 0) then + return nil, Err.new(Err.ARG, "Lzma.lzma: bad unpackSize") + end + local max = maxOf(opts) + local st = Decode.new(if unpackSize then unpackSize else l * 4, max) + local ok, perr = Decode.setProps(st, lc, lp, pb) + if not ok then + return nil, Err.new(Err.CORRUPT, tostring(perr)) + end + local consumed, err = decodeLzma(st, b, o, o + l, unpackSize) + if not consumed then + return nil, err + end + return Decode.finish(st), consumed +end + +-- .lzma file: props byte, dict size, u64 unpacked size +function Lzma.alone(buf: buffer | string, offset: number?, length: number?, opts: Options?): (buffer?, any) + local b, o, l, aerr = args("Lzma.alone", buf, offset, length) + if not b then + return nil, aerr + end + if l < 13 then + return nil, Err.new(Err.TRUNCATED, "truncated .lzma header", o) + end + local lo, hi = readu32(b, o + 5), readu32(b, o + 9) + local size: number? = nil + if not (lo == 0xFFFFFFFF and hi == 0xFFFFFFFF) then + if hi >= 2 ^ 21 then + return nil, Err.new(Err.CORRUPT, "bad .lzma size", o + 5) + end + size = hi * 4294967296 + lo + end + return Lzma.lzma(b, o + 13, l - 13, buffer.fromstring(buffer.readstring(b, o, 1)), size, opts) +end + +local function decodeLzma2(st: Decode.State, b: buffer, o: number, e: number): (number?, Err.Err?) + local p = o + local needDict, needProps = true, true + while true do + if p >= e then + return nil, Err.new(Err.TRUNCATED, "truncated LZMA2 stream", p) + end + local c = readu8(b, p) + if c == 0 then + return p + 1, nil + end + if c == 1 or c == 2 then + if p + 3 > e then + return nil, Err.new(Err.TRUNCATED, "truncated LZMA2 chunk header", p) + end + local n = readu8(b, p + 1) * 256 + readu8(b, p + 2) + 1 + if c == 1 then + Decode.resetDict(st) + needDict = false + elseif needDict then + return nil, Err.new(Err.CORRUPT, "LZMA2 chunk without a dictionary reset", p) + end + if p + 3 + n > e then + return nil, Err.new(Err.TRUNCATED, "truncated LZMA2 stored chunk", p) + end + local ok, cerr = Decode.copy(st, n, b, p + 3) + if not ok then + return nil, fail(cerr, p) + end + st.remLen = 0 + p += 3 + n + elseif c >= 0x80 then + if p + 5 > e then + return nil, Err.new(Err.TRUNCATED, "truncated LZMA2 chunk header", p) + end + local usize = (c % 32) * 65536 + readu8(b, p + 1) * 256 + readu8(b, p + 2) + 1 + local psize = readu8(b, p + 3) * 256 + readu8(b, p + 4) + 1 + local mode = (c // 32) % 4 + local q = p + 5 + if mode == 3 then + Decode.resetDict(st) + needDict = false + elseif needDict then + return nil, Err.new(Err.CORRUPT, "LZMA2 chunk without a dictionary reset", p) + end + if mode >= 2 then + if q >= e then + return nil, Err.new(Err.TRUNCATED, "truncated LZMA2 properties", q) + end + local lc, lp, pb = propsByte(readu8(b, q)) + if not lc or lc + lp > 4 then + return nil, Err.new(Err.CORRUPT, "bad LZMA2 properties", q) + end + Decode.setProps(st, lc, lp, pb) + needProps = false + q += 1 + elseif needProps then + return nil, Err.new(Err.CORRUPT, "LZMA2 chunk without properties", p) + elseif mode == 1 then + Decode.resetState(st) + end + if q + psize > e then + return nil, Err.new(Err.TRUNCATED, "truncated LZMA2 chunk", q) + end + local target = st.op + usize + if target > st.maxBytes then + return nil, Err.new(Err.LIMIT, "output over maxBytes") + end + Decode.ensure(st, target) + local ip, ierr = Decode.rcInit(st, b, q, q + psize) + if not ip then + return nil, fail(ierr, q) + end + local status, res = Decode.run(st, b, ip, q + psize, target) + if not status then + return nil, fail(res, q) + end + if status ~= "full" or st.op ~= target then + return nil, Err.new(Err.CORRUPT, "LZMA2 chunk size mismatch", p) + end + p = q + psize + else + return nil, Err.new(Err.CORRUPT, "bad LZMA2 control byte " .. c, p) + end + end +end + +function Lzma.lzma2(buf: buffer | string, offset: number?, length: number?, _dictSize: number?, unpackSize: number?, opts: Options?): (buffer?, any) + local b, o, l, aerr = args("Lzma.lzma2", buf, offset, length) + if not b then + return nil, aerr + end + local max = maxOf(opts) + local st = Decode.new(if type(unpackSize) == "number" and unpackSize >= 0 then unpackSize else l * 4, max) + local consumed, err = decodeLzma2(st, b, o, o + l) + if not consumed then + return nil, err + end + if type(unpackSize) == "number" and st.op ~= unpackSize then + return nil, Err.new(Err.CORRUPT, string.format("LZMA2 output is %d bytes, expected %d", st.op, unpackSize)) + end + return Decode.finish(st), consumed +end + +-- filter ids (xz numbering; 7z's method ids map onto these in archive/7z) +Lzma.FILTER = table.freeze({ + delta = 0x03, + x86 = 0x04, + powerpc = 0x05, + ia64 = 0x06, + arm = 0x07, + armthumb = 0x08, + sparc = 0x09, + arm64 = 0x0A, + riscv = 0x0B, + lzma2 = 0x21, +}) +local BCJ: { [number]: (buffer, number, number, number) -> () } = { + [0x04] = Filters.x86, + [0x05] = Filters.powerpc, + [0x07] = Filters.arm, + [0x08] = Filters.armthumb, + [0x09] = Filters.sparc, + [0x0A] = Filters.arm64, +} + +-- filter properties: BCJ start offset u32le, delta distance - 1 +function Lzma.filter(id: number, b: buffer, o: number, n: number, props: any?): (boolean?, Err.Err?) + local pb = toBuffer(props) + local plen = if pb then buffer.len(pb) else 0 + if id == 0x03 then + if plen ~= 1 then + return nil, Err.new(Err.CORRUPT, "bad delta filter properties") + end + Filters.delta(b, o, n, readu8(pb :: buffer, 0) + 1) + return true, nil + end + local f = BCJ[id] + if not f then + return nil, Err.new(Err.UNSUPPORTED, string.format("filter 0x%x is not supported", id)) + end + local start = 0 + if plen == 4 then + start = readu32(pb :: buffer, 0) + elseif plen ~= 0 then + return nil, Err.new(Err.CORRUPT, "bad BCJ filter properties") + end + f(b, o, n, start) + return true, nil +end + +local XZ_MAGIC = "\253" .. "7zXZ\0" +local CHECK_SIZE = { [0] = 0, 4, 4, 4, 8, 8, 8, 16, 16, 16, 32, 32, 32, 64, 64, 64 } + +local function vli(b: buffer, p: number, e: number): (number?, number) + local v, mul = 0, 1 + for i = 0, 8 do + if p + i >= e then + return nil, p + end + local c = readu8(b, p + i) + v += (c % 128) * mul + if c < 128 then + if c == 0 and i > 0 then + return nil, p -- non-minimal encoding + end + return v, p + i + 1 + end + mul *= 128 + end + return nil, p +end +Lzma.vli = vli + +local function crc(b: buffer, o: number, n: number): number + return Crc32.raw(b, o, n) +end + +local function xzStream(st: Decode.State, b: buffer, o: number, e: number): (number?, Err.Err?) + if o + 12 > e then + return nil, Err.new(Err.TRUNCATED, "truncated xz stream header", o) + end + if buffer.readstring(b, o, 6) ~= XZ_MAGIC then + return nil, Err.new(Err.CORRUPT, "bad xz magic", o) + end + if readu8(b, o + 6) ~= 0 or readu8(b, o + 7) > 15 then + return nil, Err.new(Err.UNSUPPORTED, "unknown xz stream flags", o + 6) + end + if crc(b, o + 6, 2) ~= readu32(b, o + 8) then + return nil, Err.new(Err.CHECKSUM, "xz stream header CRC-32 mismatch", o + 8) + end + local check = readu8(b, o + 7) + local csize = CHECK_SIZE[check] + local p = o + 12 + local records: { { number } } = {} + while true do + if p >= e then + return nil, Err.new(Err.TRUNCATED, "truncated xz block", p) + end + local hs = readu8(b, p) + if hs == 0 then + break -- the index + end + local hsize = (hs + 1) * 4 + if p + hsize > e then + return nil, Err.new(Err.TRUNCATED, "truncated xz block header", p) + end + if crc(b, p, hsize - 4) ~= readu32(b, p + hsize - 4) then + return nil, Err.new(Err.CHECKSUM, "xz block header CRC-32 mismatch", p) + end + local flags = readu8(b, p + 1) + if flags % 64 >= 4 then + return nil, Err.new(Err.UNSUPPORTED, "reserved xz block flags", p + 1) + end + local nfilters = flags % 4 + 1 + local q = p + 2 + local he = p + hsize - 4 + local csz, usz: number? = nil, nil + if flags >= 128 or (flags // 64) % 2 == 1 then + if (flags // 64) % 2 == 1 then + local v + v, q = vli(b, q, he) + if not v or v == 0 then + return nil, Err.new(Err.CORRUPT, "bad xz compressed size", q) + end + csz = v + end + if flags >= 128 then + local v + v, q = vli(b, q, he) + if not v then + return nil, Err.new(Err.CORRUPT, "bad xz uncompressed size", q) + end + usz = v + end + end + local filters: { { id: number, props: buffer } } = {} + for _ = 1, nfilters do + local id, psz + id, q = vli(b, q, he) + if not id then + return nil, Err.new(Err.CORRUPT, "bad xz filter flags", q) + end + psz, q = vli(b, q, he) + if not psz or q + psz > he then + return nil, Err.new(Err.CORRUPT, "bad xz filter properties", q) + end + local pr = buffer.create(psz) + buffer.copy(pr, 0, b, q, psz) + q += psz + table.insert(filters, { id = id, props = pr }) + end + for k = q, he - 1 do + if readu8(b, k) ~= 0 then + return nil, Err.new(Err.CORRUPT, "nonzero xz block header padding", k) + end + end + local last = filters[nfilters] + if last.id ~= 0x21 or buffer.len(last.props) ~= 1 or readu8(last.props, 0) > 40 then + return nil, Err.new(Err.UNSUPPORTED, string.format("xz filter chain must end in LZMA2 (got 0x%x)", last.id), p) + end + for k = 1, nfilters - 1 do + local id = filters[k].id + if id ~= 0x03 and not BCJ[id] then + return nil, Err.new(Err.UNSUPPORTED, string.format("xz filter 0x%x is not supported", id), p) + end + end + -- data + local dstart = p + hsize + local ostart = st.op + local dend = if csz then dstart + csz else e + if dend > e then + return nil, Err.new(Err.TRUNCATED, "truncated xz block data", dstart) + end + local cend, derr = decodeLzma2(st, b, dstart, dend) + if not cend then + return nil, derr + end + if csz and cend ~= dend then + return nil, Err.new(Err.CORRUPT, "xz compressed size mismatch", dstart) + end + local un = st.op - ostart + if usz and un ~= usz then + return nil, Err.new(Err.CORRUPT, "xz uncompressed size mismatch", dstart) + end + for k = nfilters - 1, 1, -1 do + local ok, ferr = Lzma.filter(filters[k].id, st.out, ostart, un, filters[k].props) + if not ok then + return nil, ferr + end + end + local unpadded = hsize + (cend - dstart) + csize + local pe = cend + while (pe - p) % 4 ~= 0 do + if pe >= e then + return nil, Err.new(Err.TRUNCATED, "truncated xz block padding", pe) + end + if readu8(b, pe) ~= 0 then + return nil, Err.new(Err.CORRUPT, "nonzero xz block padding", pe) + end + pe += 1 + end + if pe + csize > e then + return nil, Err.new(Err.TRUNCATED, "truncated xz check", pe) + end + if check == 1 then + if crc(st.out, ostart, un) ~= readu32(b, pe) then + return nil, Err.new(Err.CHECKSUM, "xz block CRC-32 mismatch", pe) + end + elseif check == 4 then + local hi, lo = Crc64.of(st.out, ostart, un) + if lo ~= readu32(b, pe) or hi ~= readu32(b, pe + 4) then + return nil, Err.new(Err.CHECKSUM, "xz block CRC-64 mismatch", pe) + end + end + table.insert(records, { unpadded, un }) + p = pe + csize + end + -- index + local ip = p + local count, q = vli(b, p + 1, e) + if not count or count ~= #records then + return nil, Err.new(Err.CORRUPT, "xz index record count mismatch", p) + end + for i = 1, count do + local a, u + a, q = vli(b, q, e) + if not a then + return nil, Err.new(Err.TRUNCATED, "truncated xz index", q) + end + u, q = vli(b, q, e) + if not u then + return nil, Err.new(Err.TRUNCATED, "truncated xz index", q) + end + if a ~= records[i][1] or u ~= records[i][2] then + return nil, Err.new(Err.CORRUPT, "xz index does not match the blocks", q) + end + end + while (q - ip) % 4 ~= 0 do + if q >= e or readu8(b, q) ~= 0 then + return nil, Err.new(Err.CORRUPT, "bad xz index padding", q) + end + q += 1 + end + if q + 4 > e then + return nil, Err.new(Err.TRUNCATED, "truncated xz index", q) + end + if crc(b, ip, q - ip) ~= readu32(b, q) then + return nil, Err.new(Err.CHECKSUM, "xz index CRC-32 mismatch", q) + end + q += 4 + local isize = q - ip + -- footer + if q + 12 > e then + return nil, Err.new(Err.TRUNCATED, "truncated xz stream footer", q) + end + if crc(b, q + 4, 6) ~= readu32(b, q) then + return nil, Err.new(Err.CHECKSUM, "xz stream footer CRC-32 mismatch", q) + end + if (readu32(b, q + 4) + 1) * 4 ~= isize then + return nil, Err.new(Err.CORRUPT, "xz backward size mismatch", q + 4) + end + if readu8(b, q + 8) ~= 0 or readu8(b, q + 9) ~= check or buffer.readstring(b, q + 10, 2) ~= "YZ" then + return nil, Err.new(Err.CORRUPT, "bad xz stream footer", q + 8) + end + return q + 12, nil +end + +function Lzma.xz(buf: buffer | string, offset: number?, length: number?, opts: Options?): (buffer?, any) + local b, o, l, aerr = args("Lzma.xz", buf, offset, length) + if not b then + return nil, aerr + end + local e = o + l + local st = Decode.new(l * 4, maxOf(opts)) + local p = o + local nstreams = 0 + while true do + local nxt, err = xzStream(st, b, p, e) + if not nxt then + return nil, err + end + nstreams += 1 + p = nxt + -- stream padding: zero bytes in multiples of 4 + local z = p + while z < e and readu8(b, z) == 0 do + z += 1 + end + if z == e then + if (z - p) % 4 ~= 0 then + return nil, Err.new(Err.CORRUPT, "xz stream padding is not a multiple of 4", p) + end + p = z + break + end + if (z - p) % 4 ~= 0 then + return nil, Err.new(Err.CORRUPT, "xz stream padding is not a multiple of 4", p) + end + p = z + end + return Decode.finish(st), p +end + +function Lzma.isXz(b: buffer, o: number?): boolean + local off = o or 0 + return off + 6 <= buffer.len(b) and buffer.readstring(b, off, 6) == XZ_MAGIC +end + +return Lzma +end +__FILES["codecs/compress/Lzma/Crc64"] = @native function() + + + +-- codecs/compress/Lzma/Crc64: CRC-64/XZ (ECMA-182 polynomial, reflected: 0xC96C5795D7870F42), xz check type 4. +-- Written from the xz file format specification; the 64-bit value is kept as two u32 halves (hi, lo). +local band, bxor, rshift, lshift, bor = bit32.band, bit32.bxor, bit32.rshift, bit32.lshift, bit32.bor +local readu8 = buffer.readu8 + +local THI, TLO = table.create(256, 0), table.create(256, 0) +for n = 0, 255 do + local hi, lo = 0, n + for _ = 1, 8 do + local low = band(lo, 1) + lo = bor(rshift(lo, 1), lshift(band(hi, 1), 31)) + hi = rshift(hi, 1) + if low ~= 0 then + hi = bxor(hi, 0xC96C5795) + lo = bxor(lo, 0xD7870F42) + end + end + THI[n + 1], TLO[n + 1] = hi, lo +end + +local Crc64 = {} + +@native function Crc64.of(b: buffer, o: number, n: number): (number, number) + local hi, lo = 0xFFFFFFFF, 0xFFFFFFFF + for i = o, o + n - 1 do + local idx = band(bxor(lo, readu8(b, i)), 255) + 1 + lo = bxor(TLO[idx], bor(rshift(lo, 8), lshift(band(hi, 255), 24))) + hi = bxor(THI[idx], rshift(hi, 8)) + end + return bxor(hi, 0xFFFFFFFF), bxor(lo, 0xFFFFFFFF) +end + +return Crc64 +end +__FILES["codecs/compress/Lzma/Decode"] = @native function() + + + +-- codecs/compress/Lzma/Decode: the LZMA range decoder and LZ state machine, shared by LZMA (.lzma, 7z) and LZMA2. +-- Follows the LZMA specification's reference decoder (LzmaSpec.cpp, Igor Pavlov, public domain): probability layout, +-- state transitions, distance / length decoding. +local readu8, readu16, writeu8, writeu16 = buffer.readu8, buffer.readu16, buffer.writeu8, buffer.writeu16 +local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len +local rshift, band = bit32.rshift, bit32.band + +-- probability offsets (u16 entries) +local IS_MATCH = 0 -- 12 states x 16 pos states +local IS_REP = 192 +local IS_REP_G0 = 204 +local IS_REP_G1 = 216 +local IS_REP_G2 = 228 +local IS_REP0_LONG = 240 -- 12 x 16 +local POS_SLOT = 432 -- 4 x 64 +local SPEC_POS = 688 -- 115 +local ALIGN = 803 -- 16 +local LEN = 819 -- choice, choice2, low 16 x 8, mid 16 x 8, high 256 +local REP_LEN = 1333 +local LITERAL = 1847 -- 0x300 << (lc + lp) + +local TOP = 16777216 -- 2^24 + +local Decode = {} + +type State = { + out: buffer, + cap: number, + op: number, + dictStart: number, + maxBytes: number, + probs: buffer, + nprobs: number, + lc: number, + lp: number, + pb: number, + state: number, + rep0: number, + rep1: number, + rep2: number, + rep3: number, + remLen: number, + range: number, + code: number, +} + +@native function Decode.new(cap: number, maxBytes: number): State + local c = math.max(64, math.min(cap, maxBytes)) + return { + out = bcreate(c), + cap = c, + op = 0, + dictStart = 0, + maxBytes = maxBytes, + probs = bcreate(2), + nprobs = 0, + lc = 0, + lp = 0, + pb = 0, + state = 0, + rep0 = 0, + rep1 = 0, + rep2 = 0, + rep3 = 0, + remLen = 0, + range = 0xFFFFFFFF, + code = 0, + } +end + +@native function Decode.setProps(st: State, lc: number, lp: number, pb: number): (boolean, string?) + if lc > 8 or lp > 4 or pb > 4 or lc < 0 or lp < 0 or pb < 0 then + return false, "bad lc / lp / pb" + end + st.lc, st.lp, st.pb = lc, lp, pb + local n = LITERAL + 0x300 * 2 ^ (lc + lp) + if blen(st.probs) < n * 2 then + st.probs = bcreate(n * 2) + end + st.nprobs = n + Decode.resetState(st) + return true, nil +end + +@native function Decode.resetState(st: State) + local p = st.probs + for i = 0, st.nprobs - 1 do + writeu16(p, i * 2, 1024) + end + st.state = 0 + st.rep0, st.rep1, st.rep2, st.rep3 = 0, 0, 0, 0 + st.remLen = 0 +end + +@native function Decode.resetDict(st: State) + st.dictStart = st.op + st.remLen = 0 +end + +@native function Decode.rcInit(st: State, b: buffer, ip: number, iend: number): (number?, string?) + if ip + 5 > iend then + return nil, "truncated range coder init" + end + if readu8(b, ip) ~= 0 then + return nil, "bad range coder init byte" + end + st.code = readu8(b, ip + 1) * 16777216 + readu8(b, ip + 2) * 65536 + readu8(b, ip + 3) * 256 + readu8(b, ip + 4) + st.range = 0xFFFFFFFF + if st.code == st.range then + return nil, "bad range coder init" + end + return ip + 5, nil +end + +@native local function ensure(st: State, need: number): boolean + if need <= st.cap then + return true + end + if need > st.maxBytes then + return false + end + local c = math.min(math.max(st.cap * 2, need, 65536), st.maxBytes) + local nb = bcreate(c) + bcopy(nb, 0, st.out, 0, st.op) + st.out = nb + st.cap = c + return true +end +Decode.ensure = ensure + +@native function Decode.copy(st: State, n: number, b: buffer, ip: number): (boolean, string?) + if not ensure(st, st.op + n) then + return false, "limit: output over maxBytes" + end + bcopy(st.out, st.op, b, ip, n) + st.op += n + return true, nil +end + +-- module upvalues, so LuaJIT traces stay valid across calls (run() is not re-entrant) +local EMPTY = bcreate(2) +local probs: buffer = EMPTY +local inb: buffer = EMPTY +local range, code, ip, iend, over = 0, 0, 0, 0, 0 + +@native local function bit(i: number): number + local p = i * 2 + local prob = readu16(probs, p) + local bound = rshift(range, 11) * prob + local r + if code < bound then + range = bound + writeu16(probs, p, prob + rshift(2048 - prob, 5)) + r = 0 + else + range -= bound + code -= bound + writeu16(probs, p, prob - rshift(prob, 5)) + r = 1 + end + if range < TOP then + range *= 256 + if ip < iend then + code = code * 256 + readu8(inb, ip) + else + code *= 256 + over += 1 + end + ip += 1 + end + return r +end + +@native local function tree(base: number, nbits: number): number + local m = 1 + for _ = 1, nbits do + m = m * 2 + bit(base + m) + end + return m - 2 ^ nbits +end + +@native local function reverse(base: number, nbits: number): number + local m = 1 + local sym = 0 + for i = 0, nbits - 1 do + local b = bit(base + m) + m = m * 2 + b + sym += b * 2 ^ i + end + return sym +end + +@native local function direct(nbits: number): number + local res = 0 + for _ = 1, nbits do + range = rshift(range, 1) + local b = 0 + if code >= range then + code -= range + b = 1 + end + res = res * 2 + b + if range < TOP then + range *= 256 + if ip < iend then + code = code * 256 + readu8(inb, ip) + else + code *= 256 + over += 1 + end + ip += 1 + end + end + return res +end + +@native local function length(base: number, posState: number): number + if bit(base) == 0 then + return tree(base + 2 + posState * 8, 3) + end + if bit(base + 1) == 0 then + return 8 + tree(base + 130 + posState * 8, 3) + end + return 16 + tree(base + 258, 8) +end + +@native function Decode.run(st: State, inb0: buffer, ip0: number, iend0: number, outEnd: number): (string?, any) + probs = st.probs + inb = inb0 + iend = iend0 + local out = st.out + local cap = st.cap + local op = st.op + local dictStart = st.dictStart + range, code = st.range, st.code + ip = ip0 + over = 0 + local state = st.state + local rep0, rep1, rep2, rep3 = st.rep0, st.rep1, st.rep2, st.rep3 + local lc = st.lc + local lcShift = 2 ^ (8 - lc) + local lpMask = 2 ^ st.lp - 1 + local pbMask = 2 ^ st.pb - 1 + local lcMul = 2 ^ lc + + local status: string? = nil + local msg: string? = nil + + local remLen = st.remLen + if remLen > 0 then + local n = math.min(remLen, outEnd - op) + if n > 0 then + if op + n > cap then + st.op = op + if not ensure(st, op + n) then + probs, inb = EMPTY, EMPTY + return nil, "limit: output over maxBytes" + end + out, cap = st.out, st.cap + end + local src = op - rep0 - 1 + for k = 0, n - 1 do + writeu8(out, op + k, readu8(out, src + k)) + end + op += n + remLen -= n + end + end + + while true do + if op >= outEnd then + status = "full" + break + end + if over > 0 then + msg = "truncated" + break + end + if op + 273 > cap then + st.op = op + if not ensure(st, math.min(op + 273, outEnd)) then + msg = "limit: output over maxBytes" + break + end + out, cap = st.out, st.cap + end + local pos = op - dictStart + local posState = band(pos, pbMask) + -- is match? (inlined bit) + local pidx = (IS_MATCH + state * 16 + posState) * 2 + local prob = readu16(probs, pidx) + local bound = rshift(range, 11) * prob + if code < bound then + range = bound + writeu16(probs, pidx, prob + rshift(2048 - prob, 5)) + if range < TOP then + range *= 256 + if ip < iend then + code = code * 256 + readu8(inb, ip) + else + code *= 256 + over += 1 + end + ip += 1 + end + -- literal + local prev = if op > dictStart then readu8(out, op - 1) else 0 + local base = LITERAL + 0x300 * (band(pos, lpMask) * lcMul + prev // lcShift) + local sym = 1 + if state >= 7 then + local mpos = op - rep0 - 1 + local matchByte = if mpos >= dictStart then readu8(out, mpos) else 0 + repeat + local matchBit = band(rshift(matchByte, 7), 1) + matchByte *= 2 + local b = bit(base + (1 + matchBit) * 256 + sym) + sym = sym * 2 + b + if matchBit ~= b then + break + end + until sym >= 256 + end + while sym < 256 do + local p2 = (base + sym) * 2 + local pr = readu16(probs, p2) + local bd = rshift(range, 11) * pr + if code < bd then + range = bd + writeu16(probs, p2, pr + rshift(2048 - pr, 5)) + sym = sym * 2 + else + range -= bd + code -= bd + writeu16(probs, p2, pr - rshift(pr, 5)) + sym = sym * 2 + 1 + end + if range < TOP then + range *= 256 + if ip < iend then + code = code * 256 + readu8(inb, ip) + else + code *= 256 + over += 1 + end + ip += 1 + end + end + writeu8(out, op, sym - 256) + op += 1 + state = if state < 4 then 0 elseif state < 10 then state - 3 else state - 6 + else + range -= bound + code -= bound + writeu16(probs, pidx, prob - rshift(prob, 5)) + if range < TOP then + range *= 256 + if ip < iend then + code = code * 256 + readu8(inb, ip) + else + code *= 256 + over += 1 + end + ip += 1 + end + local len + if bit(IS_REP + state) == 0 then + -- simple match + len = length(LEN, posState) + state = if state < 7 then 7 else 10 + rep3, rep2, rep1 = rep2, rep1, rep0 + local lenState = if len < 3 then len else 3 + local slot = tree(POS_SLOT + lenState * 64, 6) + if slot < 4 then + rep0 = slot + else + local nd = slot // 2 - 1 + local dist = (2 + slot % 2) * 2 ^ nd + if slot < 14 then + dist += reverse(SPEC_POS + dist - slot, nd) + else + dist += direct(nd - 4) * 16 + dist += reverse(ALIGN, 4) + end + rep0 = dist + end + if rep0 == 0xFFFFFFFF then + status = "eos" + break + end + else + if bit(IS_REP_G0 + state) == 0 then + if bit(IS_REP0_LONG + state * 16 + posState) == 0 then + -- short rep: one byte at rep0 + if op == dictStart or rep0 >= op - dictStart then + msg = "distance past the dictionary start" + break + end + state = if state < 7 then 9 else 11 + writeu8(out, op, readu8(out, op - rep0 - 1)) + op += 1 + continue + end + else + local dist + if bit(IS_REP_G1 + state) == 0 then + dist = rep1 + else + if bit(IS_REP_G2 + state) == 0 then + dist = rep2 + else + dist = rep3 + rep3 = rep2 + end + rep2 = rep1 + end + rep1 = rep0 + rep0 = dist + end + len = length(REP_LEN, posState) + state = if state < 7 then 8 else 11 + end + -- copy len + 2 bytes from rep0 + 1 back + if rep0 >= op - dictStart then + msg = "distance past the dictionary start" + break + end + local n = len + 2 + local room = outEnd - op + if n > room then + remLen = n - room + n = room + end + local src = op - rep0 - 1 + if rep0 + 1 >= n then + bcopy(out, op, out, src, n) + else + for k = 0, n - 1 do + writeu8(out, op + k, readu8(out, src + k)) + end + end + op += n + end + end + st.op = op + st.range, st.code = range, code + st.state = state + st.rep0, st.rep1, st.rep2, st.rep3 = rep0, rep1, rep2, rep3 + st.remLen = remLen + probs, inb = EMPTY, EMPTY + if msg then + return nil, msg + end + if over > 0 then + return nil, "truncated" + end + return status, ip +end + +@native function Decode.finish(st: State): buffer + if st.cap == st.op then + return st.out + end + local b = bcreate(st.op) + bcopy(b, 0, st.out, 0, st.op) + return b +end + +return Decode +end +__FILES["codecs/compress/Lzma/Filters"] = @native function() + + + +-- codecs/compress/Lzma/Filters: the xz / 7z branch-call-jump (BCJ) and delta decoding filters, in place. +-- From the xz file format specification and xz-embedded's xz_dec_bcj.c (Lasse Collin, public domain). +local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32 +local band, bor, bxor, rshift, lshift, byteswap = bit32.band, bit32.bor, bit32.bxor, bit32.rshift, bit32.lshift, bit32.byteswap + +local TWO32 = 4294967296 + +local Filters = {} + +local MASK_ALLOWED = { [0] = true, true, true, false, true, false, false, false } +local MASK_BITNUM = { [0] = 0, 1, 2, 2, 3, 3, 3, 3 } + +@native local function msbyte(b: number): boolean + return b == 0 or b == 0xFF +end + +@native function Filters.x86(b: buffer, o: number, n: number, start: number) + if n <= 4 then + return + end + local size = n - 4 + local prevPos = -1 + local prevMask = 0 + local i = 0 + while i < size do + local c = readu8(b, o + i) + if band(c, 0xFE) ~= 0xE8 then + i += 1 + continue + end + local d = i - prevPos + if d > 3 then + prevMask = 0 + else + prevMask = band(lshift(prevMask, d - 1), 7) + if prevMask ~= 0 then + local bb = readu8(b, o + i + 4 - MASK_BITNUM[prevMask]) + if not MASK_ALLOWED[prevMask] or msbyte(bb) then + prevPos = i + prevMask = bor(lshift(prevMask, 1), 1) + i += 1 + continue + end + end + end + prevPos = i + if msbyte(readu8(b, o + i + 4)) then + local src = readu32(b, o + i + 1) + local dest + while true do + dest = (src - (start + i + 5)) % TWO32 + if prevMask == 0 then + break + end + local j = MASK_BITNUM[prevMask] * 8 + local bb = band(rshift(dest, 24 - j), 0xFF) + if not msbyte(bb) then + break + end + src = bxor(dest, 2 ^ (32 - j) - 1) + end + dest = band(dest, 0x01FFFFFF) + if band(dest, 0x01000000) ~= 0 then + dest = bor(dest, 0xFF000000) + end + writeu32(b, o + i + 1, dest) + i += 5 + else + prevMask = bor(lshift(prevMask, 1), 1) + i += 1 + end + end +end + +@native function Filters.arm(b: buffer, o: number, n: number, start: number) + local i = 0 + while i + 4 <= n do + if readu8(b, o + i + 3) == 0xEB then + local addr = readu8(b, o + i) + readu8(b, o + i + 1) * 256 + readu8(b, o + i + 2) * 65536 + addr = (addr * 4 - (start + i + 8)) % TWO32 + addr = rshift(addr, 2) + writeu8(b, o + i, band(addr, 255)) + writeu8(b, o + i + 1, band(rshift(addr, 8), 255)) + writeu8(b, o + i + 2, band(rshift(addr, 16), 255)) + end + i += 4 + end +end + +@native function Filters.armthumb(b: buffer, o: number, n: number, start: number) + local i = 0 + while i + 4 <= n do + local b1, b3 = readu8(b, o + i + 1), readu8(b, o + i + 3) + if band(b1, 0xF8) == 0xF0 and band(b3, 0xF8) == 0xF8 then + local addr = band(b1, 7) * 524288 + readu8(b, o + i) * 2048 + band(b3, 7) * 256 + readu8(b, o + i + 2) + addr = (addr * 2 - (start + i + 4)) % TWO32 + addr = rshift(addr, 1) + writeu8(b, o + i + 1, bor(0xF0, band(rshift(addr, 19), 7))) + writeu8(b, o + i, band(rshift(addr, 11), 255)) + writeu8(b, o + i + 3, bor(0xF8, band(rshift(addr, 8), 7))) + writeu8(b, o + i + 2, band(addr, 255)) + i += 4 + else + i += 2 + end + end +end + +@native function Filters.powerpc(b: buffer, o: number, n: number, start: number) + local i = 0 + while i + 4 <= n do + local instr = byteswap(readu32(b, o + i)) + if band(instr, 0xFC000003) == 0x48000001 then + instr = band(instr, 0x03FFFFFC) + instr = band((instr - (start + i)) % TWO32, 0x03FFFFFC) + instr = bor(instr, 0x48000001) + writeu32(b, o + i, byteswap(instr)) + end + i += 4 + end +end + +@native function Filters.sparc(b: buffer, o: number, n: number, start: number) + local i = 0 + while i + 4 <= n do + local instr = byteswap(readu32(b, o + i)) + local top = rshift(instr, 22) + if top == 0x100 or top == 0x1FF then + instr = (instr * 4) % TWO32 + instr = (instr - (start + i)) % TWO32 + instr = rshift(instr, 2) + instr = bor((0x40000000 - band(instr, 0x400000)) % TWO32, 0x40000000, band(instr, 0x3FFFFF)) + writeu32(b, o + i, byteswap(instr)) + end + i += 4 + end +end + +@native function Filters.arm64(b: buffer, o: number, n: number, start: number) + local i = 0 + while i + 4 <= n do + local pc = (start + i) % TWO32 + local instr = readu32(b, o + i) + if rshift(instr, 26) == 0x25 then + local src = instr + local p = (TWO32 - rshift(pc, 2)) % TWO32 + writeu32(b, o + i, bor(0x94000000, band((src + p) % TWO32, 0x03FFFFFF))) + elseif band(instr, 0x9F000000) == 0x90000000 then + local src = bor(band(rshift(instr, 29), 3), band(rshift(instr, 3), 0x001FFFFC)) + if band(src + 0x00020000, 0x001C0000) == 0 then + local p = (TWO32 - rshift(pc, 12)) % TWO32 + local dest = (src + p) % TWO32 + local v = band(instr, 0x9000001F) + v = bor(v, lshift(band(dest, 3), 29)) + v = bor(v, lshift(band(dest, 0x0003FFFC), 3)) + v = bor(v, band((TWO32 - band(dest, 0x00020000)) % TWO32, 0x00E00000)) + writeu32(b, o + i, v) + end + end + i += 4 + end +end + +-- delta filter: b[i] += b[i - dist] (1 <= dist <= 256) +@native function Filters.delta(b: buffer, o: number, n: number, dist: number) + for i = dist, n - 1 do + writeu8(b, o + i, band(readu8(b, o + i) + readu8(b, o + i - dist), 255)) + end +end + +return Filters +end +end + + + + + + Zstd + --!optimize 2 +--!nocheck +-- rosetta chunk Zstd (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 3 modules (2 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["codecs/compress/Zstd"] = function() + +-- codecs/compress/Zstd: Zstandard decompression (RFC 8878), written from the specification; no dictionaries. +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Decode = __include("codecs/compress/Zstd/Decode") + +local Zstd = {} + +type Options = { + maxBytes: number?, + verify: boolean?, +} + +-- magic numbers: a zstd frame, and skippable frames (0x184D2A50 .. 0x184D2A5F) +Zstd.MAGIC = "\40\181\47\253" + +function Zstd.isFrame(buf: buffer, offset: number?): boolean + local o = offset or 0 + if type(buf) ~= "buffer" or o < 0 or o + 4 > buffer.len(buf) then + return false + end + local m = buffer.readu32(buf, o) + return m == 0xFD2FB528 or bit32.band(m, 0xFFFFFFF0) == 0x184D2A50 +end + +-- 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, o, l, aerr = Bytes.span("Zstd.decompress", buf, offset, length) + if not b then + return nil, aerr + end + 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)) + end + 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.from(consumed, at, len) + end + if buffer.len(out) ~= len then + local r = buffer.create(len) + buffer.copy(r, 0, out, 0, len) + out = r + end + return out, consumed +end + +function Zstd.xxh64(buf: buffer, offset: number?, length: number?): (number, number) + local o = math.clamp(offset or 0, 0, buffer.len(buf)) + local l = math.clamp(length or (buffer.len(buf) - o), 0, buffer.len(buf) - o) + return Decode.hash(buf, o, l) +end + +return Zstd +end +__FILES["codecs/compress/Zstd/Decode"] = @native function() + + + +-- codecs/compress/Zstd/Decode: Zstandard frame decoder (RFC 8878), written from the specification (no reference code). +-- Backward bitstreams: bits [o - n, o) come from one readu32 at byte (o - n) / 8; bits before the stream read as zeros. +local Xxh64 = __include("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 +local bcreate, bcopy, bfill, blen = buffer.create, buffer.copy, buffer.fill, buffer.len + +local MAGIC = 0xFD2FB528 +local BLOCK_MAX = 131072 + +local Decode = {} + +-- literal length / match length codes: baseline, extra bits (index = code + 1) +local LL_BASE = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 20, 22, 24, 28, 32, 40, 48, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536 } +local LL_BITS = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 3, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 } +local ML_BASE = { + 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, + 35, 37, 39, 41, 43, 47, 51, 59, 67, 83, 99, 131, 259, 515, 1027, 2051, 4099, 8195, 16387, 32771, 65539, +} +local ML_BITS = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 1, 1, 1, 1, 2, 2, 3, 3, 4, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, +} +local LL_DEFAULT = { 4, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 2, 1, 1, 1, 1, 1, -1, -1, -1, -1 } +local ML_DEFAULT = { + 1, 4, 3, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, +} +local OF_DEFAULT = { 1, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1 } + +local HB = table.create(2048, 0) +do + local v = 0 + for i = 1, 2048 do + if i >= lshift(2, v) then + v += 1 + end + HB[i] = v + end +end + +@native local function peek(b: buffer, s: number, o: number, n: number): number + if n <= 0 then + return 0 + end + local lo = o - n + if lo >= 0 then + local byte = s + rshift(lo, 3) + local bl = blen(b) + if byte + 4 <= bl then + return band(rshift(readu32(b, byte), band(lo, 7)), lshift(1, n) - 1) + end + local v = 0 + local m = 1 + for k = 0, 3 do + if byte + k < bl then + v += readu8(b, byte + k) * m + end + m *= 256 + end + return band(rshift(v, band(lo, 7)), lshift(1, n) - 1) + end + if o <= 0 then + return 0 + end + return lshift(peek(b, s, o, o), -lo) +end + +@native local function streamBits(b: buffer, s: number, e: number): number + if e <= s then + return -1 + end + local last = readu8(b, e - 1) + if last == 0 then + return -1 + end + return (e - 1 - s) * 8 + HB[last] +end + +@native local function getF(b: buffer, p: number, e: number, bp: number, n: number): number + local byte = p + rshift(bp, 3) + local v = 0 + local m = 1 + for k = 0, 3 do + if byte + k < e then + v += readu8(b, byte + k) * m + end + m *= 256 + end + return band(rshift(v, band(bp, 7)), lshift(1, n) - 1) +end + +-- FSE decoding table entries (u32): symbol | nbBits << 8 | newStateBase << 16 +local symTmp = bcreate(512) + +-- normalized counts: { [symbol + 1] = count }, -1 = "less than 1" probability +@native local function buildFse(norm: { number }, nsym: number, al: number, t: buffer): (boolean?, string?) + local size = lshift(1, al) + local high = size - 1 + local next = table.create(nsym, 0) + for s = 0, nsym - 1 do + local c = norm[s + 1] + if c == -1 then + if high < 0 then + return nil, "bad FSE distribution" + end + writeu8(symTmp, high, s) + high -= 1 + next[s + 1] = 1 + else + next[s + 1] = c + end + end + local pos = 0 + local step = rshift(size, 1) + rshift(size, 3) + 3 + local mask = size - 1 + for s = 0, nsym - 1 do + local c = norm[s + 1] + for _ = 1, c do + writeu8(symTmp, pos, s) + local guard = 0 + repeat + pos = band(pos + step, mask) + guard += 1 + until pos <= high or guard > size + if guard > size then + return nil, "bad FSE distribution" + end + end + end + if pos ~= 0 then + return nil, "bad FSE distribution" + end + for u = 0, size - 1 do + local s = readu8(symTmp, u) + local ns = next[s + 1] + if ns < 1 or ns > 2048 then + return nil, "bad FSE distribution" + end + next[s + 1] = ns + 1 + local nb = al - HB[ns] + if nb < 0 then + return nil, "bad FSE distribution" + end + writeu32(t, u * 4, s + nb * 256 + (lshift(ns, nb) - size) * 65536) + end + return true, nil +end + +@native local function ncount(b: buffer, p: number, e: number, maxSym: number, maxAL: number, norm: { number }): (number?, any, number?) + if p >= e then + return nil, "truncated FSE table" + end + local al = getF(b, p, e, 0, 4) + 5 + if al > maxAL then + return nil, "FSE accuracy log too large" + end + local bp = 4 + local remaining = lshift(1, al) + 1 + local threshold = lshift(1, al) + local nbBits = al + 1 + local sym = 0 + local prev0 = false + while remaining > 1 and sym <= maxSym do + if prev0 then + local n0 = sym + while true do + local v = getF(b, p, e, bp, 2) + bp += 2 + if v == 3 then + n0 += 3 + if n0 > maxSym or bp > (e - p) * 8 then + return nil, "bad FSE table" + end + else + n0 += v + break + end + end + if n0 > maxSym then + return nil, "bad FSE table" + end + while sym < n0 do + norm[sym + 1] = 0 + sym += 1 + end + end + local max = 2 * threshold - 1 - remaining + local count + local low = getF(b, p, e, bp, nbBits - 1) + if low < max then + count = low + bp += nbBits - 1 + else + count = getF(b, p, e, bp, nbBits) + if count >= threshold then + count -= max + end + bp += nbBits + end + count -= 1 + remaining -= if count < 0 then -count else count + if remaining < 1 then + return nil, "bad FSE table" + end + norm[sym + 1] = count + sym += 1 + prev0 = count == 0 + while remaining < threshold do + nbBits -= 1 + threshold = rshift(threshold, 1) + end + end + if remaining ~= 1 then + return nil, "bad FSE table" + end + local used = rshift(bp + 7, 3) + if p + used > e then + return nil, "truncated FSE table" + end + for s = sym, maxSym do + norm[s + 1] = 0 + end + return al, used, sym +end + +@native local function predefined(dist: { number }, al: number): buffer + local t = bcreate(lshift(1, al) * 4) + buildFse(dist, #dist, al, t) + return t +end +local LL_PRE, ML_PRE, OF_PRE = predefined(LL_DEFAULT, 6), predefined(ML_DEFAULT, 6), predefined(OF_DEFAULT, 5) + +-- Huffman table entry (u16): sym | nbBits << 8 +local weights = bcreate(256) +local wfse = bcreate(64 * 4) +@native local function hufTable(b: buffer, p: number, e: number, st: any): (number?, string?) + if p >= e then + return nil, "truncated Huffman table" + end + local hdr = readu8(b, p) + local n = 0 + local used + if hdr >= 128 then + n = hdr - 127 + used = 1 + rshift(n + 1, 1) + if p + used > e then + return nil, "truncated Huffman table" + end + for i = 0, n - 1 do + local byte = readu8(b, p + 1 + rshift(i, 1)) + writeu8(weights, i, if band(i, 1) == 0 then rshift(byte, 4) else band(byte, 15)) + end + else + used = 1 + hdr + if p + used > e then + return nil, "truncated Huffman table" + end + local q, qe = p + 1, p + 1 + hdr + local norm = st.norm + local al, nb = ncount(b, q, qe, 255, 6, norm) + if not al then + return nil, nb + end + local ok, msg = buildFse(norm, 256, al, wfse) + if not ok then + return nil, msg + end + local ss = q + nb + local off = streamBits(b, ss, qe) + if off < 0 then + return nil, "bad Huffman weight stream" + end + local s1 = peek(b, ss, off, al) + off -= al + local s2 = peek(b, ss, off, al) + off -= al + while true do + if n > 254 then + return nil, "too many Huffman weights" + end + local e1 = readu32(wfse, s1 * 4) + writeu8(weights, n, band(e1, 255)) + n += 1 + local k = band(rshift(e1, 8), 255) + s1 = rshift(e1, 16) + peek(b, ss, off, k) + off -= k + if off < 0 then + writeu8(weights, n, band(readu32(wfse, s2 * 4), 255)) + n += 1 + break + end + local e2 = readu32(wfse, s2 * 4) + writeu8(weights, n, band(e2, 255)) + n += 1 + k = band(rshift(e2, 8), 255) + s2 = rshift(e2, 16) + peek(b, ss, off, k) + off -= k + if off < 0 then + writeu8(weights, n, band(readu32(wfse, s1 * 4), 255)) + n += 1 + break + end + end + end + -- the last weight is implied: the total must reach the next power of two + local total = 0 + for i = 0, n - 1 do + local w = readu8(weights, i) + if w > 11 then + return nil, "bad Huffman weight" + end + if w > 0 then + total += lshift(1, w - 1) + end + end + if total == 0 or total >= 2048 then + return nil, "bad Huffman weights" + end + local maxBits = HB[total] + 1 + local rest = lshift(1, maxBits) - total + if band(rest, rest - 1) ~= 0 then + return nil, "bad Huffman weights" + end + writeu8(weights, n, HB[rest] + 1) + local nsym = n + 1 + -- codes: the longest first, in symbol order within a length + local rankCount = table.create(13, 0) + for i = 0, nsym - 1 do + local w = readu8(weights, i) + if w > 0 then + local bits = maxBits + 1 - w + rankCount[bits + 1] += 1 + end + end + local rankIdx = table.create(13, 0) + rankIdx[maxBits + 1] = 0 + for i = maxBits, 1, -1 do + rankIdx[i] = rankIdx[i + 1] + rankCount[i + 1] * lshift(1, maxBits - i) + end + if rankIdx[1] ~= lshift(1, maxBits) then + return nil, "bad Huffman weights" + end + local t = st.huf + for i = 0, nsym - 1 do + local w = readu8(weights, i) + if w > 0 then + local bits = maxBits + 1 - w + local code = rankIdx[bits + 1] + local len = lshift(1, maxBits - bits) + local v = i + bits * 256 + for k = code, code + len - 1 do + writeu16(t, k * 2, v) + end + rankIdx[bits + 1] = code + len + end + end + st.hufBits = maxBits + return used, nil +end + +@native local function hufStream(b: buffer, s: number, e: number, t: buffer, mb: number, lit: buffer, dp: number, cnt: number): string? + local off = streamBits(b, s, e) + if off < 0 then + return "bad Huffman stream" + end + local mmask = lshift(1, mb) - 1 + local fastEnd = blen(b) - 4 + for k = dp, dp + cnt - 1 do + local lo = off - mb + local idx + if lo >= 0 then + local byte = s + rshift(lo, 3) + if byte <= fastEnd then + idx = band(rshift(readu32(b, byte), band(lo, 7)), mmask) + else + idx = peek(b, s, off, mb) + end + else + idx = peek(b, s, off, mb) + end + local v = readu16(t, idx * 2) + writeu8(lit, k, v) + off -= rshift(v, 8) + end + if off ~= 0 then + return "Huffman stream size mismatch" + end + return nil +end + +@native local function grow(st: any, need: number): boolean + if need > st.maxBytes then + return false + end + local cap = math.min(st.maxBytes, math.max(blen(st.out) * 2, need, 65536)) + local nb = bcreate(cap) + bcopy(nb, 0, st.out, 0, st.op) + st.out = nb + return true +end + +@native local function block(b: buffer, p: number, e: number, st: any): (string?, string?) + -- literals section + local b0 = readu8(b, p) + local ltype = band(b0, 3) + local sf = band(rshift(b0, 2), 3) + local regen + local litSrc, litPos + local lit = st.lit + if ltype <= 1 then + if sf == 0 or sf == 2 then + regen = rshift(b0, 3) + p += 1 + elseif sf == 1 then + if p + 2 > e then + return "TRUNCATED", "truncated literals header" + end + regen = rshift(b0, 4) + readu8(b, p + 1) * 16 + p += 2 + else + if p + 3 > e then + return "TRUNCATED", "truncated literals header" + end + regen = rshift(b0, 4) + readu8(b, p + 1) * 16 + readu8(b, p + 2) * 4096 + p += 3 + end + if regen > BLOCK_MAX then + return "CORRUPT", "literals too large" + end + if ltype == 0 then + if p + regen > e then + return "TRUNCATED", "truncated raw literals" + end + litSrc, litPos = b, p + p += regen + else + if p + 1 > e then + return "TRUNCATED", "truncated RLE literals" + end + bfill(lit, 0, readu8(b, p), regen) + litSrc, litPos = lit, 0 + p += 1 + end + else + local csize + if sf <= 1 then + if p + 3 > e then + return "TRUNCATED", "truncated literals header" + end + local v = b0 + readu8(b, p + 1) * 256 + readu8(b, p + 2) * 65536 + regen = band(rshift(v, 4), 0x3FF) + csize = band(rshift(v, 14), 0x3FF) + p += 3 + elseif sf == 2 then + if p + 4 > e then + return "TRUNCATED", "truncated literals header" + end + local v = readu32(b, p) + regen = band(rshift(v, 4), 0x3FFF) + csize = rshift(v, 18) + p += 4 + else + if p + 5 > e then + return "TRUNCATED", "truncated literals header" + end + local v = readu32(b, p) + regen = band(rshift(v, 4), 0x3FFFF) + csize = rshift(v, 22) + readu8(b, p + 4) * 1024 + p += 5 + end + if regen > BLOCK_MAX then + return "CORRUPT", "literals too large" + end + if p + csize > e then + return "TRUNCATED", "truncated compressed literals" + end + local hs, he = p, p + csize + p = he + if ltype == 2 then + local used, herr = hufTable(b, hs, he, st) + if not used then + return "CORRUPT", herr + end + hs += used + elseif not st.hufBits then + return "CORRUPT", "treeless literals without a previous Huffman table" + end + local t, mb = st.huf, st.hufBits + if sf == 0 then + local herr = hufStream(b, hs, he, t, mb, lit, 0, regen) + if herr then + return "CORRUPT", herr + end + else + if hs + 6 > he then + return "CORRUPT", "truncated jump table" + end + local l1, l2, l3 = readu16(b, hs), readu16(b, hs + 2), readu16(b, hs + 4) + local s1 = hs + 6 + local s2 = s1 + l1 + local s3 = s2 + l2 + local s4 = s3 + l3 + if s4 > he then + return "CORRUPT", "bad jump table" + end + local seg = rshift(regen + 3, 2) + local last = regen - 3 * seg + if last < 0 then + return "CORRUPT", "bad 4-stream literals size" + end + local herr = hufStream(b, s1, s2, t, mb, lit, 0, seg) + or hufStream(b, s2, s3, t, mb, lit, seg, seg) + or hufStream(b, s3, s4, t, mb, lit, 2 * seg, seg) + or hufStream(b, s4, he, t, mb, lit, 3 * seg, last) + if herr then + return "CORRUPT", herr + end + end + litSrc, litPos = lit, 0 + end + + -- sequences section header + if p >= e then + return "TRUNCATED", "missing sequences header" + end + local nbSeq = readu8(b, p) + p += 1 + if nbSeq >= 128 then + if nbSeq == 255 then + if p + 2 > e then + return "TRUNCATED", "truncated sequences header" + end + nbSeq = readu16(b, p) + 0x7F00 + p += 2 + else + if p + 1 > e then + return "TRUNCATED", "truncated sequences header" + end + nbSeq = (nbSeq - 128) * 256 + readu8(b, p) + p += 1 + end + end + local op = st.op + if nbSeq == 0 then + if p ~= e then + return "CORRUPT", "data after an empty sequences section" + end + if op + regen > blen(st.out) then + if not grow(st, op + regen) then + return "LIMIT", "output over the size limit" + end + end + bcopy(st.out, op, litSrc, litPos, regen) + st.op = op + regen + return nil, nil + end + if p >= e then + return "TRUNCATED", "missing compression modes" + end + local modes = readu8(b, p) + p += 1 + if band(modes, 3) ~= 0 then + return "CORRUPT", "reserved bits set in compression modes" + end + -- the three tables, in the order LL, OF, ML + local tabs = st.tabs + for k = 1, 3 do + local mode = band(rshift(modes, 8 - 2 * k), 3) + local maxSym = if k == 1 then 35 elseif k == 2 then 31 else 52 + local maxAL = if k == 1 then 9 elseif k == 2 then 8 else 9 + if mode == 0 then + tabs[k] = if k == 1 then LL_PRE elseif k == 2 then OF_PRE else ML_PRE + tabs[k + 3] = if k == 2 then 5 else 6 + elseif mode == 1 then + if p >= e then + return "TRUNCATED", "truncated RLE table" + end + local sym = readu8(b, p) + p += 1 + if sym > maxSym then + return "CORRUPT", "bad RLE symbol" + end + local t = st.rle[k] + writeu32(t, 0, sym) + tabs[k] = t + tabs[k + 3] = 0 + elseif mode == 2 then + local norm = st.norm + local al, used, nsym = ncount(b, p, e, maxSym, maxAL, norm) + if not al then + return "CORRUPT", used + end + p += used + local t = st.dyn[k] + local ok, msg = buildFse(norm, nsym :: number, al, t) + if not ok then + return "CORRUPT", msg + end + tabs[k] = t + tabs[k + 3] = al + else + if not tabs[k] then + return "CORRUPT", "repeated table without a previous one" + end + end + end + local llT, ofT, mlT = tabs[1] :: buffer, tabs[2] :: buffer, tabs[3] :: buffer + local llAL, ofAL, mlAL = tabs[4] :: number, tabs[5] :: number, tabs[6] :: number + + -- the sequences bitstream + local s = p + local off = streamBits(b, s, e) + if off < 0 then + return "CORRUPT", "bad sequences bitstream" + end + local llS = peek(b, s, off, llAL) + off -= llAL + local ofS = peek(b, s, off, ofAL) + off -= ofAL + local mlS = peek(b, s, off, mlAL) + off -= mlAL + local rep1, rep2, rep3 = st.rep1, st.rep2, st.rep3 + local out = st.out + local cap = blen(out) + local frameStart = st.frameStart + local lp, litEnd = litPos, litPos + regen + local fastEnd = blen(b) - 4 + for i = 1, nbSeq do + local ofE, llE, mlE = readu32(ofT, ofS * 4), readu32(llT, llS * 4), readu32(mlT, mlS * 4) + local ofCode = band(ofE, 255) + local mlCode = band(mlE, 255) + 1 + local llCode = band(llE, 255) + 1 + -- offset bits, then match length bits, then literal length bits + local ofv + if ofCode > 24 then + local hiN = ofCode - 24 + local hi = peek(b, s, off, hiN) + off -= hiN + ofv = lshift(1, ofCode) + hi * 16777216 + peek(b, s, off, 24) + off -= 24 + elseif ofCode > 0 then + local lo = off - ofCode + local v + if lo >= 0 and s + rshift(lo, 3) <= fastEnd then + v = band(rshift(readu32(b, s + rshift(lo, 3)), band(lo, 7)), lshift(1, ofCode) - 1) + else + v = peek(b, s, off, ofCode) + end + off = lo + ofv = lshift(1, ofCode) + v + else + ofv = 1 + end + local ml = ML_BASE[mlCode] + local nb = ML_BITS[mlCode] + if nb > 0 then + ml += peek(b, s, off, nb) + off -= nb + end + local ll = LL_BASE[llCode] + nb = LL_BITS[llCode] + if nb > 0 then + ll += peek(b, s, off, nb) + off -= nb + end + -- repeat offsets + local offset + if ofv > 3 then + offset = ofv - 3 + rep3 = rep2 + rep2 = rep1 + rep1 = offset + else + local idx = ofv - 1 + if ll == 0 then + idx += 1 + end + if idx == 0 then + offset = rep1 + else + if idx == 1 then + offset = rep2 + elseif idx == 2 then + offset = rep3 + else + offset = rep1 - 1 + end + if idx > 1 then + rep3 = rep2 + end + rep2 = rep1 + rep1 = offset + end + end + -- state updates (not after the last sequence): LL, ML, OF + if i < nbSeq then + nb = band(rshift(llE, 8), 255) + llS = rshift(llE, 16) + peek(b, s, off, nb) + off -= nb + nb = band(rshift(mlE, 8), 255) + mlS = rshift(mlE, 16) + peek(b, s, off, nb) + off -= nb + nb = band(rshift(ofE, 8), 255) + ofS = rshift(ofE, 16) + peek(b, s, off, nb) + off -= nb + end + -- execute + if lp + ll > litEnd then + return "CORRUPT", "literal length past the literals" + end + local need = op + ll + ml + if need > cap then + st.op = op + if not grow(st, need) then + return "LIMIT", "output over the size limit" + end + out = st.out + cap = blen(out) + end + if ll > 0 then + bcopy(out, op, litSrc, lp, ll) + op += ll + lp += ll + end + if offset > op - frameStart or offset < 1 then + return "CORRUPT", "match offset before the frame start" + end + local from = op - offset + if offset >= ml then + bcopy(out, op, out, from, ml) + op += ml + elseif offset == 1 then + bfill(out, op, readu8(out, from), ml) + op += ml + else + local left = ml + while left > 0 do + local n = if left < offset then left else offset + bcopy(out, op, out, from, n) + op += n + from += n + left -= n + end + end + end + if off ~= 0 then + return "CORRUPT", "sequences bitstream size mismatch" + end + local rest = litEnd - lp + if rest > 0 then + if op + rest > cap then + st.op = op + if not grow(st, op + rest) then + return "LIMIT", "output over the size limit" + end + out = st.out + end + bcopy(out, op, litSrc, lp, rest) + op += rest + end + st.op = op + st.rep1, st.rep2, st.rep3 = rep1, rep2, rep3 + return nil, nil +end + +@native function Decode.decompress(b: buffer, start: number, stop: number, maxBytes: number, verify: boolean): (buffer?, any, any, any) + local st: any = { + out = bcreate(math.min(maxBytes, math.max(4096, (stop - start) * 3))), + op = 0, + maxBytes = maxBytes, + lit = bcreate(BLOCK_MAX + 64), + huf = bcreate(2048 * 2), + hufBits = nil, + norm = table.create(256, 0), + tabs = {}, + rle = { bcreate(4), bcreate(4), bcreate(4) }, + dyn = { bcreate(512 * 4), bcreate(256 * 4), bcreate(512 * 4) }, + frameStart = 0, + rep1 = 1, + rep2 = 4, + rep3 = 8, + } + local pos = start + local frames = 0 + if stop - start < 4 then + return nil, "TRUNCATED", "not a zstd stream (too short)", start + end + while pos < stop do + if pos + 4 > stop then + return nil, "TRUNCATED", "truncated frame magic", pos + end + local magic = readu32(b, pos) + if band(magic, 0xFFFFFFF0) == 0x184D2A50 then + if pos + 8 > stop then + return nil, "TRUNCATED", "truncated skippable frame", pos + end + local size = readu32(b, pos + 4) + if pos + 8 + size > stop then + return nil, "TRUNCATED", "truncated skippable frame", pos + end + pos += 8 + size + frames += 1 + continue + end + if magic ~= MAGIC then + return nil, "CORRUPT", if frames == 0 then "bad magic" else "unknown data after frame " .. frames, pos + end + pos += 4 + if pos + 1 > stop then + return nil, "TRUNCATED", "truncated frame header", pos + end + local fhd = readu8(b, pos) + pos += 1 + local fcsFlag = rshift(fhd, 6) + local single = band(fhd, 0x20) ~= 0 + if band(fhd, 8) ~= 0 then + return nil, "CORRUPT", "reserved frame header bit set", pos - 1 + end + local checksum = band(fhd, 4) ~= 0 + local didFlag = band(fhd, 3) + local didSize = if didFlag == 3 then 4 else didFlag + local fcsSize = if fcsFlag == 0 then (if single then 1 else 0) else lshift(1, fcsFlag) + local hsize = (if single then 0 else 1) + didSize + fcsSize + if pos + hsize > stop then + return nil, "TRUNCATED", "truncated frame header", pos + end + local windowSize = 0 + if not single then + local wd = readu8(b, pos) + pos += 1 + local wlog = 10 + rshift(wd, 3) + if wlog > 41 then + return nil, "CORRUPT", "bad window size", pos - 1 + end + local base = 2 ^ wlog + windowSize = base + base / 8 * band(wd, 7) + end + local did = 0 + if didSize == 1 then + did = readu8(b, pos) + elseif didSize == 2 then + did = readu16(b, pos) + elseif didSize == 4 then + did = readu32(b, pos) + end + pos += didSize + if did ~= 0 then + return nil, "UNSUPPORTED", "dictionaries are not supported (dictionary " .. did .. ")", pos - didSize + end + local fcs = -1 + if fcsSize == 1 then + fcs = readu8(b, pos) + elseif fcsSize == 2 then + fcs = readu16(b, pos) + 256 + elseif fcsSize == 4 then + fcs = readu32(b, pos) + elseif fcsSize == 8 then + fcs = readu32(b, pos) + readu32(b, pos + 4) * 4294967296 + end + pos += fcsSize + if single then + windowSize = fcs + end + local blockMax = math.min(windowSize, BLOCK_MAX) + local frameStart = st.op + if fcs >= 0 then + if frameStart + fcs > st.maxBytes then + return nil, "LIMIT", string.format("frame content size %d is over the %d byte limit", fcs, st.maxBytes), pos + end + if frameStart + fcs > blen(st.out) then + grow(st, frameStart + fcs) + end + end + st.frameStart = frameStart + st.rep1, st.rep2, st.rep3 = 1, 4, 8 + st.hufBits = nil + table.clear(st.tabs) + local last = false + repeat + if pos + 3 > stop then + return nil, "TRUNCATED", "truncated block header", pos + end + local bh = readu16(b, pos) + readu8(b, pos + 2) * 65536 + last = band(bh, 1) ~= 0 + local btype = band(rshift(bh, 1), 3) + local bsize = rshift(bh, 3) + pos += 3 + if bsize > blockMax then + return nil, "CORRUPT", "block larger than the maximum block size", pos - 3 + end + if btype == 0 then + if pos + bsize > stop then + return nil, "TRUNCATED", "truncated raw block", pos + end + if st.op + bsize > blen(st.out) and not grow(st, st.op + bsize) then + return nil, "LIMIT", "output over the size limit", pos + end + bcopy(st.out, st.op, b, pos, bsize) + st.op += bsize + pos += bsize + elseif btype == 1 then + if pos + 1 > stop then + return nil, "TRUNCATED", "truncated RLE block", pos + end + if st.op + bsize > blen(st.out) and not grow(st, st.op + bsize) then + return nil, "LIMIT", "output over the size limit", pos + end + bfill(st.out, st.op, readu8(b, pos), bsize) + st.op += bsize + pos += 1 + elseif btype == 2 then + if pos + bsize > stop then + return nil, "TRUNCATED", "truncated compressed block", pos + end + if bsize == 0 then + return nil, "CORRUPT", "empty compressed block", pos + end + local code, msg = block(b, pos, pos + bsize, st) + if code then + return nil, code, msg, pos + end + pos += bsize + else + return nil, "CORRUPT", "reserved block type", pos - 3 + end + until last + local size = st.op - frameStart + if fcs >= 0 and size ~= fcs then + return nil, "CORRUPT", string.format("frame decoded to %d bytes, header says %d", size, fcs), pos + end + if checksum then + if pos + 4 > stop then + return nil, "TRUNCATED", "missing content checksum", pos + end + if verify then + local _, lo = Xxh64.hash(st.out, frameStart, size) + local want = readu32(b, pos) + if lo ~= want then + return nil, "CHECKSUM", string.format("content checksum mismatch (%08x, expected %08x)", lo, want), pos + end + end + pos += 4 + end + frames += 1 + end + return st.out, st.op, pos +end + +Decode.hash = Xxh64.hash + +return Decode +end +__FILES["codecs/compress/Zstd/Xxh64"] = @native function() + + + +-- codecs/compress/Zstd/Xxh64: XXH64 (seed 0) on 32-bit halves, from the xxHash specification (Yann Collet, BSD-2). +-- 64 x 64 -> 64 products split the low operand into 16-bit limbs so every partial product is exact below 2^53. +local bor, bxor, lshift, rshift = bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift +local readu8, readu32 = buffer.readu8, buffer.readu32 + +local T32 = 4294967296 + +local P1H, P1L = 0x9E3779B1, 0x85EBCA87 +local P2H, P2L = 0xC2B2AE3D, 0x27D4EB4F +local P3H, P3L = 0x165667B1, 0x9E3779F9 +local P4H, P4L = 0x85EBCA77, 0xC2B2AE63 +local P5H, P5L = 0x27D4EB2F, 0x165667C5 + +@native local function mul(ah: number, al: number, bh: number, bl: number): (number, number) + local a0 = al % 65536 + local a1 = (al - a0) / 65536 + local b0 = bl % 65536 + local b1 = (bl - b0) / 65536 + local mid = a1 * b0 + a0 * b1 + local mid0 = mid % 65536 + local lo = a0 * b0 + mid0 * 65536 + local lo32 = lo % T32 + local hi = a1 * b1 + (mid - mid0) / 65536 + (lo - lo32) / T32 + hi += (a0 * bh + ((a1 * bh) % 65536) * 65536) + (b0 * ah + ((b1 * ah) % 65536) * 65536) + return hi % T32, lo32 +end + +@native local function add(ah: number, al: number, bh: number, bl: number): (number, number) + local l = al + bl + local h = ah + bh + if l >= T32 then + l -= T32 + h += 1 + end + return h % T32, l +end + +@native local function rotl(h: number, l: number, r: number): (number, number) + return bor(lshift(h, r), rshift(l, 32 - r)), bor(lshift(l, r), rshift(h, 32 - r)) +end + +local P1L0, P1L1 = P1L % 65536, P1L // 65536 +local P2L0, P2L1 = P2L % 65536, P2L // 65536 + +-- round: acc = rotl(acc + input * P2, 31) * P1 +@native local function round(ah: number, al: number, ih: number, il: number): (number, number) + local a0 = il % 65536 + local a1 = (il - a0) / 65536 + local mid = a1 * P2L0 + a0 * P2L1 + local mid0 = mid % 65536 + local lo = a0 * P2L0 + mid0 * 65536 + local ml = lo % T32 + local mh = a1 * P2L1 + (mid - mid0) / 65536 + (lo - ml) / T32 + a0 * P2H + ((a1 * P2H) % 65536) * 65536 + P2L0 * ih + ((P2L1 * ih) % 65536) * 65536 + local l = al + ml + local h = ah + mh + if l >= T32 then + l -= T32 + h += 1 + end + h %= T32 + -- rotl 31 = rotr 1, in arithmetic (cheaper than bit32 calls on LuaJIT) + local hb, lb = h % 2, l % 2 + local rh, rl = hb * 2147483648 + (l - lb) / 2, lb * 2147483648 + (h - hb) / 2 + a0 = rl % 65536 + a1 = (rl - a0) / 65536 + mid = a1 * P1L0 + a0 * P1L1 + mid0 = mid % 65536 + lo = a0 * P1L0 + mid0 * 65536 + ml = lo % T32 + mh = a1 * P1L1 + (mid - mid0) / 65536 + (lo - ml) / T32 + a0 * P1H + ((a1 * P1H) % 65536) * 65536 + P1L0 * rh + ((P1L1 * rh) % 65536) * 65536 + return mh % T32, ml +end + +@native local function merge(hh: number, hl: number, vh: number, vl: number): (number, number) + local rh, rl = round(0, 0, vh, vl) + hh, hl = bxor(hh, rh), bxor(hl, rl) + hh, hl = mul(hh, hl, P1H, P1L) + return add(hh, hl, P4H, P4L) +end + +local Xxh64 = {} + +@native function Xxh64.hash(b: buffer, offset: number, length: number): (number, number) + local p = offset + local e = offset + length + local hh, hl = 0, 0 + if length >= 32 then + local v1h, v1l = add(P1H, P1L, P2H, P2L) + local v2h, v2l = P2H, P2L + local v3h, v3l = 0, 0 + local v4h, v4l = add(0, 0, (T32 - P1H - 1) % T32, (T32 - P1L) % T32) -- -P1 (two's complement) + local limit = e - 32 + while p <= limit do + v1h, v1l = round(v1h, v1l, readu32(b, p + 4), readu32(b, p)) + v2h, v2l = round(v2h, v2l, readu32(b, p + 12), readu32(b, p + 8)) + v3h, v3l = round(v3h, v3l, readu32(b, p + 20), readu32(b, p + 16)) + v4h, v4l = round(v4h, v4l, readu32(b, p + 28), readu32(b, p + 24)) + p += 32 + end + local ah, al = rotl(v1h, v1l, 1) + local bh, bl = rotl(v2h, v2l, 7) + hh, hl = add(ah, al, bh, bl) + bh, bl = rotl(v3h, v3l, 12) + hh, hl = add(hh, hl, bh, bl) + bh, bl = rotl(v4h, v4l, 18) + hh, hl = add(hh, hl, bh, bl) + hh, hl = merge(hh, hl, v1h, v1l) + hh, hl = merge(hh, hl, v2h, v2l) + hh, hl = merge(hh, hl, v3h, v3l) + hh, hl = merge(hh, hl, v4h, v4l) + else + hh, hl = P5H, P5L + end + 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) :: number + hh, hl = rotl(hh, hl, 27) + hh, hl = mul(hh, hl, P1H, P1L) + hh, hl = add(hh, hl, P4H, P4L) + p += 8 + end + if p + 4 <= e then + local kh, kl = mul(0, readu32(b, p), P1H, P1L) + 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) + p += 4 + end + while p < e do + local kh, kl = mul(0, readu8(b, p), P5H, P5L) + hh, hl = bxor(hh, kh), bxor(hl, kl) :: number + hh, hl = rotl(hh, hl, 11) + hh, hl = mul(hh, hl, P1H, P1L) + p += 1 + end + -- 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))) :: number -- h ^= h >> 29 + hh, hl = mul(hh, hl, P3H, P3L) + hl = bxor(hl, hh) -- h ^= h >> 32 + return hh, hl +end + +return Xxh64 +end +end + + + + + + Mpa + --!optimize 2 +--!nocheck +-- rosetta chunk Mpa (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 8 modules (5 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["codecs/audio/Mpa"] = function() + +-- codecs/audio/Mpa: MPEG audio layers I / II / III (ISO/IEC 11172-3, 13818-3, MPEG-2.5) without the file around it. +-- Core is a port of minimp3 by lieff (CC0, licenses/minimp3-CC0.txt), absorbed from mp3-luau c755bbf; the layer II / III +-- encoders are new. +local Mpa = { + Header = __include("codecs/audio/Mpa/Header"), + Core = __include("codecs/audio/Mpa/Core"), + Encode3 = __include("codecs/audio/Mpa/Encode3"), + Encode2 = __include("codecs/audio/Mpa/Encode2"), +} + +return Mpa +end +__FILES["codecs/audio/Mpa/Analysis"] = @native function() + + + +-- codecs/audio/Mpa/Analysis: the polyphase analysis filterbank (ISO/IEC 11172-3 C.1.3, figure C.4): window C = D / 32, +-- matrixing M[k][i] = cos((2k + 1)(i - 16) pi / 64). +local E = __include("codecs/audio/Mpa/EncTables") + +local Analysis = {} + +local C = table.create(512, 0) +for i = 1, 512 do + C[i] = E.D[i] / 32 +end +local M = table.create(32 * 64, 0) +for k = 0, 31 do + for i = 0, 63 do + M[k * 64 + i + 1] = math.cos((2 * k + 1) * (i - 16) * math.pi / 64) + end +end + +type State = { x: { number }, off: number, y: { number } } + +@native function Analysis.new(): State + return { x = table.create(1024, 0), off = 0, y = table.create(64, 0) } +end + +@native function Analysis.run(st: State, s: { number }, si: number, out: { number }, oi: number) + -- the window X is kept twice (x[p] and x[p + 512]) so X[i] = x[off + i + 1] without a modulo + local x = st.x + local off = (st.off - 32) % 512 + st.off = off + for j = 0, 31 do + local v = s[si + j] + local p = (off + 31 - j) % 512 + 1 -- X[31 - j]: the first new sample goes to X[31], the newest to X[0] + x[p] = v + x[p + 512] = v + end + local y = st.y + for i = 0, 63 do + local acc = 0 + local b = off + i + 1 + for j = 0, 7 do + acc += C[i + 64 * j + 1] * x[b + 64 * j] + end + y[i + 1] = acc + end + for k = 0, 31 do + local acc = 0 + local mb = k * 64 + for i = 1, 64 do + acc += M[mb + i] * y[i] + end + out[oi + k] = acc + end +end + +return Analysis +end +__FILES["codecs/audio/Mpa/Core"] = @native function() + + + +-- 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. +local T = __include("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 +local rf, wf = buffer.readf32, buffer.writef32 +local bcopy, bfill, bcreate = buffer.copy, buffer.fill, buffer.create +local min, max = math.min, math.max + +local MAX_BITRESERVOIR_BYTES = 511 +local MAX_FRAME = 2304 + 8 -- largest frame (free format) incl. padding, rounded up +local SCALE = 1 / 32768 + +-- tables (floats rounded to f32 like the C arrays) + +local F32 = bcreate(4) +@native local function f32(x: number): number + wf(F32, 0, x) + return rf(F32, 0) +end + +@native local function fbuf(list: { [number]: number }, n: number): buffer + local b = bcreate(n * 4) + for i = 0, n - 1 do + wf(b, i * 4, list[i]) + end + return b +end + +-- scalefactor band widths: long (8 x 23) | short (8 x 40) | mixed (8 x 40), one u8 buffer +local SFB_LONG, SFB_SHORT, SFB_MIXED = 0, 184, 504 +local SFB = bcreate(824 + 8) +for i = 0, 183 do + wu8(SFB, SFB_LONG + i, T.g_scf_long[i]) +end +for i = 0, 319 do + wu8(SFB, SFB_SHORT + i, T.g_scf_short[i]) + wu8(SFB, SFB_MIXED + i, T.g_scf_mixed[i]) +end + +local TABS = bcreate(2164 * 2) +for i = 0, 2163 do + buffer.writei16(TABS, i * 2, T.tabs[i]) +end +local TAB32, TAB33 = T.tab32, T.tab33 +local TABINDEX, LINBITS = T.tabindex, T.g_linbits +local SCF_PARTITIONS, SCFC_DECODE, GMOD, PREAMP = T.g_scf_partitions, T.g_scfc_decode, T.g_mod, T.g_preamp +local EXPFRAC = { [0] = f32(T.g_expfrac[0]), f32(T.g_expfrac[1]), f32(T.g_expfrac[2]), f32(T.g_expfrac[3]) } +local PAN = {} +for i = 0, 13 do + PAN[i] = f32(T.g_pan[i]) +end +local BITALLOC_CODE = T.g_bitalloc_code_tab +local HALFRATE = T.halfrate + +-- L3_pow_43 for every value a Huffman pair can give (15 + 8191 linbits), evaluated in f32 like the C code +local POW43 = bcreate(8207 * 4) +do + local g = {} + for i = 0, 144 do + g[i] = f32(T.g_pow43[i]) + end + local c43, c29 = f32(4 / 3), f32(2 / 9) + for x0 = 0, 8206 do + local v + if x0 < 129 then + v = g[16 + x0] + else + local x, mult = x0, 256 + if x < 1024 then + mult = 16 + x *= 8 + end + local sign = band(2 * x, 64) + local frac = f32((band(x, 63) - sign) / (band(x, bit32.bnot(63)) + sign)) + v = f32(f32(g[16 + rshift(x + sign, 6)] * f32(1 + f32(frac * f32(c43 + f32(frac * c29))))) * mult) + end + wf(POW43, x0 * 4, v) + end +end + +-- L12 dequantizer: 9.53674316e-07f / x (and two more steps of 2^(-1/3)) for 3, 7, ..., 65535, 3, 5, 9 +local DEQ_L12 = {} +do + local div = { 3, 7, 15, 31, 63, 127, 255, 511, 1023, 2047, 4095, 8191, 16383, 32767, 65535, 3, 5, 9 } + local base = { f32(9.53674316e-07), f32(7.56931807e-07), f32(6.00777173e-07) } + for i = 0, 17 do + for j = 0, 2 do + DEQ_L12[i * 3 + j] = f32(base[j + 1] / div[i + 1]) + end + end +end + +local AA = fbuf(T.g_aa, 16) +local TWID3 = fbuf(T.g_twid3, 6) +local MDCT_WIN0, MDCT_WIN1 = table.create(18, 0), table.create(18, 0) -- g_mdct_window[2][18], 1-based +for i = 0, 17 do + MDCT_WIN0[i + 1] = f32(T.g_mdct_window[i]) + MDCT_WIN1[i + 1] = f32(T.g_mdct_window[18 + i]) +end +local WINT = table.create(240, 0) -- g_win as a 1-based Luau array (f32 values) +for i = 0, 239 do + WINT[i + 1] = f32(T.g_win[i]) +end + +local FRAME = bcreate(MAX_FRAME + 64) -- the current frame, copied (bit reader reads up to 4 bytes ahead) +local MAIN = bcreate(MAX_BITRESERVOIR_BYTES + MAX_FRAME + 4096) +local GRBUF = bcreate(576 * 2 * 4) -- [ch][576] f32 +local SCF = bcreate(40 * 4) +local SYN = bcreate((18 + 15) * 64 * 4) +local IST = bcreate(2 * 39 + 8) -- ist_pos[2][39], u8 +local ISCF = bcreate(48) +local TMP = bcreate(18 * 4 * 2) -- imdct scratch: co[9] si[9] / short block copy[18] +local L12SCF = bcreate(192 * 4) -- L12 scalefactors [band*2 + ch][3], f32 +local BA = bcreate(64) +local SCFCOD = bcreate(64) + +-- layer III side info, per granule x channel (0..3) +local GR_P23, GR_BV, GR_SFC, GR_GAIN, GR_BT, GR_MIXED = {}, {}, {}, {}, {}, {} +local GR_NLONG, GR_NSHORT, GR_SFB, GR_PRE, GR_SCALE, GR_C1, GR_SCFSI = {}, {}, {}, {}, {}, {}, {} +local GR_TS, GR_RC, GR_SBG = {}, {}, {} -- [gr * 3 + k] +for i = 0, 3 do + GR_P23[i], GR_BV[i], GR_SFC[i], GR_GAIN[i], GR_BT[i], GR_MIXED[i] = 0, 0, 0, 0, 0, 0 + GR_NLONG[i], GR_NSHORT[i], GR_SFB[i], GR_PRE[i], GR_SCALE[i], GR_C1[i], GR_SCFSI[i] = 0, 0, 0, 0, 0, 0, 0 + for k = 0, 2 do + GR_TS[i * 3 + k], GR_RC[i * 3 + k], GR_SBG[i * 3 + k] = 0, 0, 0 + end +end +local MAXB = { [0] = -1, -1, -1 } +local SCFSIZE = { [0] = 0, 0, 0, 0 } + +local OVL: buffer = bcreate(4) -- mdct_overlap[2][9*32] +local QMF: buffer = bcreate(4) -- qmf_state[15*2*32] +local PCM: buffer = bcreate(4) + +-- bit reader (bs_t) + +local bsBuf: buffer = FRAME +local bsPos = 0 +local bsLimit = 0 + +@native local function getBits(n: number): number + local pos = bsPos + bsPos = pos + n + if pos + n > bsLimit then + return 0 + end + local w = lshift(bswap(ru32(bsBuf, rshift(pos, 3))), band(pos, 7)) + return rshift(w, 32 - n) +end + +-- layer III side info (L3_read_side_info): fills GR_*, returns main_data_begin or -1 + +@native local function readSideInfo(h1: number, h2: number, h3: number): number + local mono = band(h3, 0xC0) == 0xC0 + local mpeg1 = band(h1, 8) ~= 0 + local srIdx = band(rshift(h2, 2), 3) + (band(rshift(h1, 3), 1) + band(rshift(h1, 4), 1)) * 3 + if srIdx ~= 0 then + srIdx -= 1 + end + local grCount = if mono then 1 else 2 + local scfsi = 0 + local mdb + if mpeg1 then + grCount *= 2 + mdb = getBits(9) + scfsi = getBits(7 + grCount) + else + mdb = rshift(getBits(8 + grCount), grCount) + end + local part23sum = 0 + for gr = 0, grCount - 1 do + if mono then + scfsi = lshift(scfsi, 4) + end + local p23 = getBits(12) + GR_P23[gr] = p23 + part23sum += p23 + local bv = getBits(9) + if bv > 288 then + return -1 + end + GR_BV[gr] = bv + GR_GAIN[gr] = getBits(8) + local sfc = getBits(if mpeg1 then 4 else 9) + GR_SFC[gr] = sfc + GR_SFB[gr] = SFB_LONG + srIdx * 23 + GR_NLONG[gr] = 22 + GR_NSHORT[gr] = 0 + local tables + local g3 = gr * 3 + if getBits(1) ~= 0 then + local bt = getBits(2) + if bt == 0 then + return -1 + end + GR_BT[gr] = bt + local mixed = getBits(1) + GR_MIXED[gr] = mixed + GR_RC[g3] = 7 + GR_RC[g3 + 1] = 255 + if bt == 2 then + scfsi = band(scfsi, 0x0F0F) + if mixed == 0 then + GR_RC[g3] = 8 + GR_SFB[gr] = SFB_SHORT + srIdx * 40 + GR_NLONG[gr] = 0 + GR_NSHORT[gr] = 39 + else + GR_SFB[gr] = SFB_MIXED + srIdx * 40 + GR_NLONG[gr] = if mpeg1 then 8 else 6 + GR_NSHORT[gr] = 30 + end + end + tables = lshift(getBits(10), 5) + GR_SBG[g3] = getBits(3) + GR_SBG[g3 + 1] = getBits(3) + GR_SBG[g3 + 2] = getBits(3) + else + GR_BT[gr] = 0 + GR_MIXED[gr] = 0 + tables = getBits(15) + GR_RC[g3] = getBits(4) + GR_RC[g3 + 1] = getBits(3) + GR_RC[g3 + 2] = 255 + end + GR_TS[g3] = rshift(tables, 10) + GR_TS[g3 + 1] = band(rshift(tables, 5), 31) + GR_TS[g3 + 2] = band(tables, 31) + GR_PRE[gr] = if mpeg1 then getBits(1) elseif sfc >= 500 then 1 else 0 + GR_SCALE[gr] = getBits(1) + GR_C1[gr] = getBits(1) + GR_SCFSI[gr] = band(rshift(scfsi, 12), 15) + scfsi = lshift(scfsi, 4) + end + if part23sum + bsPos > bsLimit + mdb * 8 then + return -1 + end + return mdb +end + +@native local function ldexpQ2(y: number, e: number): number + repeat + local s = if e < 120 then e else 120 + y = f32(y * EXPFRAC[band(s, 3)] * lshift(1, 30 - arshift(s, 2))) + e -= s + until e <= 0 + return y +end + +-- L3_read_scalefactors + L3_decode_scalefactors -> SCF[0 .. nLong + nShort) +@native local function decodeScalefactors(h1: number, h3: number, istOff: number, gr: number, ch: number) + local mpeg1 = band(h1, 8) ~= 0 + local nLong, nShort = GR_NLONG[gr], GR_NSHORT[gr] + local part = ((if nShort ~= 0 then 1 else 0) + (if nLong == 0 then 1 else 0)) * 28 + local scfShift = GR_SCALE[gr] + 1 + local scfsi = GR_SCFSI[gr] + if mpeg1 then + local p = SCFC_DECODE[GR_SFC[gr]] + local hi, lo = rshift(p, 2), band(p, 3) + SCFSIZE[0], SCFSIZE[1], SCFSIZE[2], SCFSIZE[3] = hi, hi, lo, lo + else + local ist = if band(h3, 0x10) ~= 0 and ch ~= 0 then 1 else 0 + local sfc = rshift(GR_SFC[gr], ist) + local k = ist * 12 + while sfc >= 0 do + local modprod = 1 + for i = 3, 0, -1 do + SCFSIZE[i] = (sfc // modprod) % GMOD[k + i] + modprod *= GMOD[k + i] + end + sfc -= modprod + k += 4 + end + part += k + end + -- L3_read_scalefactors + local sp, ip = 0, istOff + for i = 0, 3 do + local cnt = SCF_PARTITIONS[part + i] + if cnt == 0 then + break + end + if mpeg1 and band(scfsi, 8) ~= 0 then + bcopy(ISCF, sp, IST, ip, cnt) + else + local bits = SCFSIZE[i] + if bits == 0 then + bfill(ISCF, sp, 0, cnt) + bfill(IST, ip, 0, cnt) + else + local maxScf = if mpeg1 then -1 else lshift(1, bits) - 1 + for k = 0, cnt - 1 do + local s = getBits(bits) + wu8(IST, ip + k, if s == maxScf then 255 else s) + wu8(ISCF, sp + k, s) + end + end + end + sp += cnt + ip += cnt + scfsi *= 2 + end + wu8(ISCF, sp, 0) + wu8(ISCF, sp + 1, 0) + wu8(ISCF, sp + 2, 0) + + if nShort ~= 0 then + local sh = 3 - scfShift + local g3 = gr * 3 + local s0, s1, s2 = lshift(GR_SBG[g3], sh), lshift(GR_SBG[g3 + 1], sh), lshift(GR_SBG[g3 + 2], sh) + for i = 0, nShort - 1, 3 do + local o = nLong + i + wu8(ISCF, o, band(ru8(ISCF, o) + s0, 255)) + wu8(ISCF, o + 1, band(ru8(ISCF, o + 1) + s1, 255)) + wu8(ISCF, o + 2, band(ru8(ISCF, o + 2) + s2, 255)) + end + elseif GR_PRE[gr] ~= 0 then + for i = 0, 9 do + wu8(ISCF, 11 + i, band(ru8(ISCF, 11 + i) + PREAMP[i], 255)) + end + end + + local gainExp = GR_GAIN[gr] - 4 - 210 - (if band(h3, 0xE0) == 0x60 then 2 else 0) + local gain = ldexpQ2(2048, 44 - gainExp) + for i = 0, nLong + nShort - 1 do + wf(SCF, i * 4, ldexpQ2(gain, lshift(ru8(ISCF, i), scfShift))) + end +end + +-- layer III Huffman decoding (L3_huffman) into GRBUF[dst ..], reads MAIN through a 32-bit cache + +@native local function huffman(dst: number, gr: number, limit: number) + local b = bsBuf + local one = 0.0 + local ireg = 0 + local bigValCnt = GR_BV[gr] + local sfb = GR_SFB[gr] + local scf = 0 + local pos = bsPos + local nextPtr = rshift(pos, 3) + local cache = lshift(bswap(ru32(b, nextPtr)), band(pos, 7)) + local sh = band(pos, 7) - 8 + nextPtr += 4 + local g3 = gr * 3 + local d = dst * 4 + + while bigValCnt > 0 do + if ireg > 2 then + break + end + local tabNum = GR_TS[g3 + ireg] + local sfbCnt = GR_RC[g3 + ireg] + ireg += 1 + local cb = TABINDEX[tabNum] + local linbits = LINBITS[tabNum] + repeat + local np = rshift(ru8(SFB, sfb), 1) + sfb += 1 + if np == 0 then + bigValCnt = 0 + break + end + local pairs = if bigValCnt < np then bigValCnt else np + one = rf(SCF, scf) + scf += 4 + for _ = 1, pairs do + local w = 5 + local leaf = ri16(TABS, (cb + rshift(cache, 27)) * 2) + while leaf < 0 do + cache = lshift(cache, w) + sh += w + w = band(leaf, 7) + leaf = ri16(TABS, (cb + rshift(cache, 32 - w) - leaf // 8) * 2) + end + local l = rshift(leaf, 8) + cache = lshift(cache, l) + sh += l + for _ = 1, 2 do + local lsb = band(leaf, 15) + if lsb == 15 and linbits ~= 0 then + lsb += rshift(cache, 32 - linbits) + cache = lshift(cache, linbits) + sh += linbits + while sh >= 0 do + cache = bor(cache, lshift(ru8(b, nextPtr), sh)) + nextPtr += 1 + sh -= 8 + end + end + local v = rf(POW43, lsb * 4) * one + if lsb ~= 0 then + if cache >= 0x80000000 then + v = -v + end + cache = lshift(cache, 1) + sh += 1 + end + wf(GRBUF, d, v) + d += 4 + leaf = rshift(leaf, 4) + end + while sh >= 0 do + cache = bor(cache, lshift(ru8(b, nextPtr), sh)) + nextPtr += 1 + sh -= 8 + end + end + bigValCnt -= np + sfbCnt -= 1 + until not (bigValCnt > 0 and sfbCnt >= 0) + end + + -- count1 quadruples + local np = 1 - bigValCnt + local cb1 = if GR_C1[gr] ~= 0 then TAB33 else TAB32 + local dend = 576 * 4 * 2 + while true do + local leaf = cb1[rshift(cache, 28)] + if band(leaf, 8) == 0 then + leaf = cb1[rshift(leaf, 3) + rshift(lshift(cache, 4), 32 - band(leaf, 3))] + end + local l = band(leaf, 7) + cache = lshift(cache, l) + sh += l + if nextPtr * 8 - 24 + sh > limit or d + 16 > dend then + break + end + np -= 1 + if np == 0 then + np = rshift(ru8(SFB, sfb), 1) + sfb += 1 + if np == 0 then + break + end + one = rf(SCF, scf) + scf += 4 + end + if band(leaf, 128) ~= 0 then + wf(GRBUF, d, if cache >= 0x80000000 then -one else one) + cache = lshift(cache, 1) + sh += 1 + end + if band(leaf, 64) ~= 0 then + wf(GRBUF, d + 4, if cache >= 0x80000000 then -one else one) + cache = lshift(cache, 1) + sh += 1 + end + np -= 1 + if np == 0 then + np = rshift(ru8(SFB, sfb), 1) + sfb += 1 + if np == 0 then + break + end + one = rf(SCF, scf) + scf += 4 + end + if band(leaf, 32) ~= 0 then + wf(GRBUF, d + 8, if cache >= 0x80000000 then -one else one) + cache = lshift(cache, 1) + sh += 1 + end + if band(leaf, 16) ~= 0 then + wf(GRBUF, d + 12, if cache >= 0x80000000 then -one else one) + cache = lshift(cache, 1) + sh += 1 + end + while sh >= 0 do + cache = bor(cache, lshift(ru8(b, nextPtr), sh)) + nextPtr += 1 + sh -= 8 + end + d += 16 + end + bsPos = limit +end + +-- L3_midside_stereo on GRBUF[left .. left + n) and its right channel at + 576 +@native local function midside(left: number, n: number) + for i = left * 4, (left + n - 1) * 4, 4 do + local a, c = rf(GRBUF, i), rf(GRBUF, i + 2304) + wf(GRBUF, i, a + c) + wf(GRBUF, i + 2304, a - c) + end +end + +@native local function intensityStereo(h1: number, h3: number, gr: number) + local mpeg1 = band(h1, 8) ~= 0 + local ms = band(h3, 0x20) ~= 0 + local nLong, nShort = GR_NLONG[gr], GR_NSHORT[gr] + local nSfb = nLong + nShort + local maxBlocks = if nShort ~= 0 then 3 else 1 + local sfb0 = GR_SFB[gr] + -- L3_stereo_top_band on the right channel + MAXB[0], MAXB[1], MAXB[2] = -1, -1, -1 + local right = 576 + for i = 0, nSfb - 1 do + local n = ru8(SFB, sfb0 + i) + for k = right, right + n - 1, 2 do + if rf(GRBUF, k * 4) ~= 0 or rf(GRBUF, k * 4 + 4) ~= 0 then + MAXB[i % 3] = i + break + end + end + right += n + end + if nLong ~= 0 then + local m = max(MAXB[0], MAXB[1], MAXB[2]) + MAXB[0], MAXB[1], MAXB[2] = m, m, m + end + for i = 0, maxBlocks - 1 do + local defaultPos = if mpeg1 then 3 else 0 + local itop = nSfb - maxBlocks + i + local prev = itop - maxBlocks + wu8(IST, 39 + itop, if MAXB[i] >= prev then defaultPos else ru8(IST, 39 + prev)) + end + -- L3_stereo_process + local mpeg2sh = band(GR_SFC[gr + 1], 1) + local maxPos = if mpeg1 then 7 else 64 + local s = if ms then f32(1.41421356) else 1 + local left = 0 + local i = 0 + while true do + local n = ru8(SFB, sfb0 + i) + if n == 0 then + break + end + local ipos = ru8(IST, 39 + i) + if i > MAXB[i % 3] and ipos < maxPos then + local kl, kr + if mpeg1 then + kl, kr = PAN[2 * ipos], PAN[2 * ipos + 1] + else + kl = 1 + kr = ldexpQ2(1, lshift(rshift(ipos + 1, 1), mpeg2sh)) + if band(ipos, 1) ~= 0 then + kl = kr + kr = 1 + end + end + 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) + wf(GRBUF, k, v * kl) + end + elseif ms then + midside(left, n) + end + left += n + i += 1 + end +end + +@native local function reorder(g: number, sfb: number) + local src, dst = g, 0 + while true do + local len = ru8(SFB, sfb) + if len == 0 then + break + end + for i = 0, len - 1 do + local s = (src + i) * 4 + wf(SYN, dst, rf(GRBUF, s)) + wf(SYN, dst + 4, rf(GRBUF, s + len * 4)) + wf(SYN, dst + 8, rf(GRBUF, s + len * 8)) + dst += 12 + end + src += 3 * len + sfb += 3 + end + bcopy(GRBUF, g * 4, SYN, 0, dst) +end + +local AA0 = table.create(8, 0) +local AA1 = table.create(8, 0) +for i = 0, 7 do + AA0[i + 1] = rf(AA, i * 4) + AA1[i + 1] = rf(AA, 32 + i * 4) +end + +@native local function antialias(g: number, nbands: number) + local o = g * 4 + for _ = 1, nbands do + for i = 0, 7 do + local ui, di = o + (18 + i) * 4, o + (17 - i) * 4 + local u, d = rf(GRBUF, ui), rf(GRBUF, di) + local c0, c1 = AA0[i + 1], AA1[i + 1] + wf(GRBUF, ui, u * c0 - d * c1) + wf(GRBUF, di, u * c1 + d * c0) + end + o += 72 + end +end + +-- BEGIN generated by tools/gen_dsp.py + +-- L3_dct3_9 on 9 values +@native local function dct3_9(s0: number, s1: number, s2: number, s3: number, s4: number, s5: number, s6: number, s7: number, s8: number) + local t0 = s0 + s6 * 0.5 + s0 -= s6 + local t4 = (s4 + s2) * 0.939692616 + local t2 = (s8 + s2) * 0.766044438 + s6 = (s4 - s8) * 0.173648179 + s4 += s8 - s2 + s2 = s0 - s4 * 0.5 + local y4 = s4 + s0 + s8 = t0 - t2 + s6 + s0 = t0 - t4 + t2 + s4 = t0 + t4 - s6 + s3 *= 0.866025388 + t0 = (s5 + s1) * 0.98480773 + t4 = (s5 - s7) * 0.342020154 + t2 = (s1 + s7) * 0.642787635 + s1 = (s1 - s5 - s7) * 0.866025388 + s5 = t0 - s3 - t2 + s7 = t4 - s3 - t0 + s3 = t4 + s3 - t2 + return s4 - s7, s2 + s1, s0 - s3, s8 + s5, y4, s8 - s5, s0 + s3, s2 - s1, s4 + s7 +end + +-- L3_imdct36: GRBUF[g ..], OVL[ov ..] (float indices), window W (1-based, 18 values) +@native local function imdct36(g: number, ov: number, W: { number }, nbands: number) + local w0 = W[1] + local w1 = W[2] + local w2 = W[3] + local w3 = W[4] + local w4 = W[5] + local w5 = W[6] + local w6 = W[7] + local w7 = W[8] + local w8 = W[9] + local w9 = W[10] + local w10 = W[11] + local w11 = W[12] + local w12 = W[13] + local w13 = W[14] + local w14 = W[15] + local w15 = W[16] + local w16 = W[17] + local w17 = W[18] + for _ = 1, nbands do + local gb = g * 4 + local g0 = rf(GRBUF, gb + 0) + local g1 = rf(GRBUF, gb + 4) + local g2 = rf(GRBUF, gb + 8) + local g3 = rf(GRBUF, gb + 12) + local g4 = rf(GRBUF, gb + 16) + local g5 = rf(GRBUF, gb + 20) + local g6 = rf(GRBUF, gb + 24) + local g7 = rf(GRBUF, gb + 28) + local g8 = rf(GRBUF, gb + 32) + local g9 = rf(GRBUF, gb + 36) + local g10 = rf(GRBUF, gb + 40) + local g11 = rf(GRBUF, gb + 44) + local g12 = rf(GRBUF, gb + 48) + local g13 = rf(GRBUF, gb + 52) + local g14 = rf(GRBUF, gb + 56) + local g15 = rf(GRBUF, gb + 60) + local g16 = rf(GRBUF, gb + 64) + local g17 = rf(GRBUF, gb + 68) + local c0, c1, c2, c3, c4, c5, c6, c7, c8 = dct3_9(-g0, g1 + g2, -(g3 + g4), g5 + g6, -(g7 + g8), g9 + g10, -(g11 + g12), g13 + g14, -(g15 + g16)) + local s0, s1, s2, s3, s4, s5, s6, s7, s8 = dct3_9(g17, g16 - g15, g13 - g14, g12 - g11, g9 - g10, g8 - g7, g5 - g6, g4 - g3, g1 - g2) + s1, s3, s5, s7 = -s1, -s3, -s5, -s7 + local ob = ov * 4 + do + local ovl = rf(OVL, ob + 0) + local sum = c0 * 0.675590217 + s0 * 0.737277329 + wf(OVL, ob + 0, c0 * 0.737277329 - s0 * 0.675590217) + wf(GRBUF, gb + 0, ovl * w0 - sum * w9) + wf(GRBUF, gb + 68, ovl * w9 + sum * w0) + end + do + local ovl = rf(OVL, ob + 4) + local sum = c1 * 0.60876143 + s1 * 0.793353319 + wf(OVL, ob + 4, c1 * 0.793353319 - s1 * 0.60876143) + wf(GRBUF, gb + 4, ovl * w1 - sum * w10) + wf(GRBUF, gb + 64, ovl * w10 + sum * w1) + end + do + local ovl = rf(OVL, ob + 8) + local sum = c2 * 0.537299633 + s2 * 0.843391478 + wf(OVL, ob + 8, c2 * 0.843391478 - s2 * 0.537299633) + wf(GRBUF, gb + 8, ovl * w2 - sum * w11) + wf(GRBUF, gb + 60, ovl * w11 + sum * w2) + end + do + local ovl = rf(OVL, ob + 12) + local sum = c3 * 0.4617486 + s3 * 0.887010813 + wf(OVL, ob + 12, c3 * 0.887010813 - s3 * 0.4617486) + wf(GRBUF, gb + 12, ovl * w3 - sum * w12) + wf(GRBUF, gb + 56, ovl * w12 + sum * w3) + end + do + local ovl = rf(OVL, ob + 16) + local sum = c4 * 0.382683426 + s4 * 0.923879504 + wf(OVL, ob + 16, c4 * 0.923879504 - s4 * 0.382683426) + wf(GRBUF, gb + 16, ovl * w4 - sum * w13) + wf(GRBUF, gb + 52, ovl * w13 + sum * w4) + end + do + local ovl = rf(OVL, ob + 20) + local sum = c5 * 0.300705791 + s5 * 0.953716934 + wf(OVL, ob + 20, c5 * 0.953716934 - s5 * 0.300705791) + wf(GRBUF, gb + 20, ovl * w5 - sum * w14) + wf(GRBUF, gb + 48, ovl * w14 + sum * w5) + end + do + local ovl = rf(OVL, ob + 24) + local sum = c6 * 0.216439605 + s6 * 0.976296008 + wf(OVL, ob + 24, c6 * 0.976296008 - s6 * 0.216439605) + wf(GRBUF, gb + 24, ovl * w6 - sum * w15) + wf(GRBUF, gb + 44, ovl * w15 + sum * w6) + end + do + local ovl = rf(OVL, ob + 28) + local sum = c7 * 0.130526185 + s7 * 0.991444886 + wf(OVL, ob + 28, c7 * 0.991444886 - s7 * 0.130526185) + wf(GRBUF, gb + 28, ovl * w7 - sum * w16) + wf(GRBUF, gb + 40, ovl * w16 + sum * w7) + end + do + local ovl = rf(OVL, ob + 32) + local sum = c8 * 0.0436193794 + s8 * 0.999048233 + wf(OVL, ob + 32, c8 * 0.999048233 - s8 * 0.0436193794) + wf(GRBUF, gb + 32, ovl * w8 - sum * w17) + wf(GRBUF, gb + 36, ovl * w17 + sum * w8) + end + g += 18 + ov += 9 + end +end + +-- mp3d_DCT_II (scalar path) over the n time slots of a channel at GRBUF[g ..]: t[4][8] in locals +@native local function dctII(g: number, n: number) + for k = 0, n - 1 do + local y = (g + k) * 4 + local t0_0, t1_0, t2_0, t3_0 + do + local x0, x1, x2, x3 = rf(GRBUF, y + 0), rf(GRBUF, y + 1080), rf(GRBUF, y + 1152), rf(GRBUF, y + 2232) + local a, b = x0 + x3, x1 + x2 + local c, d = (x1 - x2) * 10.1900082, (x0 - x3) * 0.50060302 + t0_0 = a + b + t1_0 = (a - b) * 0.502419293 + t2_0 = d + c + t3_0 = (d - c) * 0.502419293 + end + local t0_1, t1_1, t2_1, t3_1 + do + local x0, x1, x2, x3 = rf(GRBUF, y + 72), rf(GRBUF, y + 1008), rf(GRBUF, y + 1224), rf(GRBUF, y + 2160) + local a, b = x0 + x3, x1 + x2 + local c, d = (x1 - x2) * 3.40760851, (x0 - x3) * 0.505470932 + t0_1 = a + b + t1_1 = (a - b) * 0.522498608 + t2_1 = d + c + t3_1 = (d - c) * 0.522498608 + end + local t0_2, t1_2, t2_2, t3_2 + do + local x0, x1, x2, x3 = rf(GRBUF, y + 144), rf(GRBUF, y + 936), rf(GRBUF, y + 1296), rf(GRBUF, y + 2088) + local a, b = x0 + x3, x1 + x2 + local c, d = (x1 - x2) * 2.05778098, (x0 - x3) * 0.515447319 + t0_2 = a + b + t1_2 = (a - b) * 0.566944063 + t2_2 = d + c + t3_2 = (d - c) * 0.566944063 + end + local t0_3, t1_3, t2_3, t3_3 + do + local x0, x1, x2, x3 = rf(GRBUF, y + 216), rf(GRBUF, y + 864), rf(GRBUF, y + 1368), rf(GRBUF, y + 2016) + local a, b = x0 + x3, x1 + x2 + local c, d = (x1 - x2) * 1.4841646, (x0 - x3) * 0.531042576 + t0_3 = a + b + t1_3 = (a - b) * 0.646821797 + t2_3 = d + c + t3_3 = (d - c) * 0.646821797 + end + local t0_4, t1_4, t2_4, t3_4 + do + local x0, x1, x2, x3 = rf(GRBUF, y + 288), rf(GRBUF, y + 792), rf(GRBUF, y + 1440), rf(GRBUF, y + 1944) + local a, b = x0 + x3, x1 + x2 + local c, d = (x1 - x2) * 1.16943991, (x0 - x3) * 0.553103924 + t0_4 = a + b + t1_4 = (a - b) * 0.788154602 + t2_4 = d + c + t3_4 = (d - c) * 0.788154602 + end + local t0_5, t1_5, t2_5, t3_5 + do + local x0, x1, x2, x3 = rf(GRBUF, y + 360), rf(GRBUF, y + 720), rf(GRBUF, y + 1512), rf(GRBUF, y + 1872) + local a, b = x0 + x3, x1 + x2 + local c, d = (x1 - x2) * 0.972568214, (x0 - x3) * 0.582934976 + t0_5 = a + b + t1_5 = (a - b) * 1.06067765 + t2_5 = d + c + t3_5 = (d - c) * 1.06067765 + end + local t0_6, t1_6, t2_6, t3_6 + do + local x0, x1, x2, x3 = rf(GRBUF, y + 432), rf(GRBUF, y + 648), rf(GRBUF, y + 1584), rf(GRBUF, y + 1800) + local a, b = x0 + x3, x1 + x2 + local c, d = (x1 - x2) * 0.839349627, (x0 - x3) * 0.622504115 + t0_6 = a + b + t1_6 = (a - b) * 1.72244716 + t2_6 = d + c + t3_6 = (d - c) * 1.72244716 + end + local t0_7, t1_7, t2_7, t3_7 + do + local x0, x1, x2, x3 = rf(GRBUF, y + 504), rf(GRBUF, y + 576), rf(GRBUF, y + 1656), rf(GRBUF, y + 1728) + local a, b = x0 + x3, x1 + x2 + local c, d = (x1 - x2) * 0.744536281, (x0 - x3) * 0.674808323 + t0_7 = a + b + t1_7 = (a - b) * 5.10114861 + t2_7 = d + c + t3_7 = (d - c) * 5.10114861 + end + do + local x0, x1, x2, x3, x4, x5, x6, x7 = t0_0, t0_1, t0_2, t0_3, t0_4, t0_5, t0_6, t0_7 + local xt = x0 - x7 + x0 += x7 + x7 = x1 - x6 + x1 += x6 + x6 = x2 - x5 + x2 += x5 + x5 = x3 - x4 + x3 += x4 + x4 = x0 - x3 + x0 += x3 + x3 = x1 - x2 + x1 += x2 + t0_0 = x0 + x1 + t0_4 = (x0 - x1) * 0.707106769 + x5 += x6 + x6 = (x6 + x7) * 0.707106769 + x7 += xt + x3 = (x3 + x4) * 0.707106769 + x5 -= x7 * 0.198912367 + x7 += x5 * 0.382683426 + x5 -= x7 * 0.198912367 + x0 = xt - x6 + xt += x6 + t0_1 = (xt + x7) * 0.509795606 + t0_2 = (x4 + x3) * 0.541196108 + t0_3 = (x0 - x5) * 0.601344883 + t0_5 = (x0 + x5) * 0.899976194 + t0_6 = (x4 - x3) * 1.30656302 + t0_7 = (xt - x7) * 2.56291556 + end + do + local x0, x1, x2, x3, x4, x5, x6, x7 = t1_0, t1_1, t1_2, t1_3, t1_4, t1_5, t1_6, t1_7 + local xt = x0 - x7 + x0 += x7 + x7 = x1 - x6 + x1 += x6 + x6 = x2 - x5 + x2 += x5 + x5 = x3 - x4 + x3 += x4 + x4 = x0 - x3 + x0 += x3 + x3 = x1 - x2 + x1 += x2 + t1_0 = x0 + x1 + t1_4 = (x0 - x1) * 0.707106769 + x5 += x6 + x6 = (x6 + x7) * 0.707106769 + x7 += xt + x3 = (x3 + x4) * 0.707106769 + x5 -= x7 * 0.198912367 + x7 += x5 * 0.382683426 + x5 -= x7 * 0.198912367 + x0 = xt - x6 + xt += x6 + t1_1 = (xt + x7) * 0.509795606 + t1_2 = (x4 + x3) * 0.541196108 + t1_3 = (x0 - x5) * 0.601344883 + t1_5 = (x0 + x5) * 0.899976194 + t1_6 = (x4 - x3) * 1.30656302 + t1_7 = (xt - x7) * 2.56291556 + end + do + local x0, x1, x2, x3, x4, x5, x6, x7 = t2_0, t2_1, t2_2, t2_3, t2_4, t2_5, t2_6, t2_7 + local xt = x0 - x7 + x0 += x7 + x7 = x1 - x6 + x1 += x6 + x6 = x2 - x5 + x2 += x5 + x5 = x3 - x4 + x3 += x4 + x4 = x0 - x3 + x0 += x3 + x3 = x1 - x2 + x1 += x2 + t2_0 = x0 + x1 + t2_4 = (x0 - x1) * 0.707106769 + x5 += x6 + x6 = (x6 + x7) * 0.707106769 + x7 += xt + x3 = (x3 + x4) * 0.707106769 + x5 -= x7 * 0.198912367 + x7 += x5 * 0.382683426 + x5 -= x7 * 0.198912367 + x0 = xt - x6 + xt += x6 + t2_1 = (xt + x7) * 0.509795606 + t2_2 = (x4 + x3) * 0.541196108 + t2_3 = (x0 - x5) * 0.601344883 + t2_5 = (x0 + x5) * 0.899976194 + t2_6 = (x4 - x3) * 1.30656302 + t2_7 = (xt - x7) * 2.56291556 + end + do + local x0, x1, x2, x3, x4, x5, x6, x7 = t3_0, t3_1, t3_2, t3_3, t3_4, t3_5, t3_6, t3_7 + local xt = x0 - x7 + x0 += x7 + x7 = x1 - x6 + x1 += x6 + x6 = x2 - x5 + x2 += x5 + x5 = x3 - x4 + x3 += x4 + x4 = x0 - x3 + x0 += x3 + x3 = x1 - x2 + x1 += x2 + t3_0 = x0 + x1 + t3_4 = (x0 - x1) * 0.707106769 + x5 += x6 + x6 = (x6 + x7) * 0.707106769 + x7 += xt + x3 = (x3 + x4) * 0.707106769 + x5 -= x7 * 0.198912367 + x7 += x5 * 0.382683426 + x5 -= x7 * 0.198912367 + x0 = xt - x6 + xt += x6 + t3_1 = (xt + x7) * 0.509795606 + t3_2 = (x4 + x3) * 0.541196108 + t3_3 = (x0 - x5) * 0.601344883 + t3_5 = (x0 + x5) * 0.899976194 + t3_6 = (x4 - x3) * 1.30656302 + t3_7 = (xt - x7) * 2.56291556 + end + wf(GRBUF, y + 0, t0_0) + wf(GRBUF, y + 72, t2_0 + t3_0 + t3_1) + wf(GRBUF, y + 144, t1_0 + t1_1) + wf(GRBUF, y + 216, t2_1 + t3_0 + t3_1) + wf(GRBUF, y + 288, t0_1) + wf(GRBUF, y + 360, t2_1 + t3_1 + t3_2) + wf(GRBUF, y + 432, t1_1 + t1_2) + wf(GRBUF, y + 504, t2_2 + t3_1 + t3_2) + wf(GRBUF, y + 576, t0_2) + wf(GRBUF, y + 648, t2_2 + t3_2 + t3_3) + wf(GRBUF, y + 720, t1_2 + t1_3) + wf(GRBUF, y + 792, t2_3 + t3_2 + t3_3) + wf(GRBUF, y + 864, t0_3) + wf(GRBUF, y + 936, t2_3 + t3_3 + t3_4) + wf(GRBUF, y + 1008, t1_3 + t1_4) + wf(GRBUF, y + 1080, t2_4 + t3_3 + t3_4) + wf(GRBUF, y + 1152, t0_4) + wf(GRBUF, y + 1224, t2_4 + t3_4 + t3_5) + wf(GRBUF, y + 1296, t1_4 + t1_5) + wf(GRBUF, y + 1368, t2_5 + t3_4 + t3_5) + wf(GRBUF, y + 1440, t0_5) + wf(GRBUF, y + 1512, t2_5 + t3_5 + t3_6) + wf(GRBUF, y + 1584, t1_5 + t1_6) + wf(GRBUF, y + 1656, t2_6 + t3_5 + t3_6) + wf(GRBUF, y + 1728, t0_6) + wf(GRBUF, y + 1800, t2_6 + t3_6 + t3_7) + wf(GRBUF, y + 1872, t1_6 + t1_7) + wf(GRBUF, y + 1944, t2_7 + t3_6 + t3_7) + wf(GRBUF, y + 2016, t0_7) + wf(GRBUF, y + 2088, t2_7 + t3_7) + wf(GRBUF, y + 2160, t1_7) + wf(GRBUF, y + 2232, t3_7) + end +end + +-- END generated + + +-- L3_imdct12: x = TMP f32 index (stride 3), dst buffer + float index, ov = OVL float index +@native local function imdct12(x: number, dst: buffer, d: number, ov: number) + local xb = x * 4 + local x0, x3, x6, x9, x12, x15 = + rf(TMP, xb), rf(TMP, xb + 12), rf(TMP, xb + 24), rf(TMP, xb + 36), rf(TMP, xb + 48), rf(TMP, xb + 60) + -- L3_idct3(-x0, x6 + x3, x12 + x9) -> co + local c0, c1, c2 = -x0, (x6 + x3), (x12 + x9) + local m1 = (c1 * 0.86602540) + local a1 = (c0 - c2 * 0.5) + local co1 = c0 + c2 + local co0, co2 = a1 + m1, a1 - m1 + -- L3_idct3(x15, x12 - x9, x6 - x3) -> si + c0, c1, c2 = x15, (x12 - x9), (x6 - x3) + m1 = (c1 * 0.86602540) + a1 = (c0 - c2 * 0.5) + local si1 = -(c0 + c2) + local si0, si2 = a1 + m1, a1 - m1 + local ob, db = ov * 4, d * 4 + for i = 0, 2 do + local co = if i == 0 then co0 elseif i == 1 then co1 else co2 + local si = if i == 0 then si0 elseif i == 1 then si1 else si2 + local ovl = rf(OVL, ob + i * 4) + local sum = (co * rf(TWID3, (3 + i) * 4) + si * rf(TWID3, i * 4)) + wf(OVL, ob + i * 4, co * rf(TWID3, i * 4) - si * rf(TWID3, (3 + i) * 4)) + wf(dst, db + i * 4, ovl * rf(TWID3, (2 - i) * 4) - sum * rf(TWID3, (5 - i) * 4)) + wf(dst, db + (5 - i) * 4, ovl * rf(TWID3, (5 - i) * 4) + sum * rf(TWID3, (2 - i) * 4)) + end +end + +@native local function imdctShort(g: number, ov: number, nbands: number) + for _ = 1, nbands do + bcopy(TMP, 0, GRBUF, g * 4, 72) + bcopy(GRBUF, g * 4, OVL, ov * 4, 24) + imdct12(0, GRBUF, g + 6, ov + 6) + imdct12(1, GRBUF, g + 12, ov + 6) + imdct12(2, OVL, ov, ov + 6) + g += 18 + ov += 9 + end +end + +@native local function changeSign(g: number) + local o = (g + 18) * 4 + for _ = 0, 15 do + for i = 1, 17, 2 do + wf(GRBUF, o + i * 4, -rf(GRBUF, o + i * 4)) + end + o += 144 + end +end + +@native local function imdctGr(g: number, ov: number, bt: number, nLongBands: number) + if nLongBands ~= 0 then + imdct36(g, ov, MDCT_WIN0, nLongBands) + g += 18 * nLongBands + ov += 9 * nLongBands + end + if bt == 2 then + imdctShort(g, ov, 32 - nLongBands) + else + imdct36(g, ov, if bt == 3 then MDCT_WIN1 else MDCT_WIN0, 32 - nLongBands) + end +end + +-- L3_decode: one granule, side info at gr = grBase + ch +@native local function l3Decode(h1: number, h2: number, h3: number, grBase: number, nch: number) + for ch = 0, nch - 1 do + local gr = grBase + ch + local limit = bsPos + GR_P23[gr] + decodeScalefactors(h1, h3, ch * 39, gr, ch) + huffman(ch * 576, gr, limit) + end + if band(h3, 0x10) ~= 0 then + intensityStereo(h1, h3, grBase) + elseif band(h3, 0xE0) == 0x60 then + midside(0, 576) + end + local mySr = band(rshift(h2, 2), 3) + (band(rshift(h1, 3), 1) + band(rshift(h1, 4), 1)) * 3 + for ch = 0, nch - 1 do + local gr = grBase + ch + local aaBands = 31 + local nLongBands = if GR_MIXED[gr] ~= 0 then (if mySr == 2 then 4 else 2) else 0 + local g = ch * 576 + if GR_NSHORT[gr] ~= 0 then + aaBands = nLongBands - 1 + reorder(g + nLongBands * 18, GR_SFB[gr] + GR_NLONG[gr]) + end + antialias(g, aaBands) + imdctGr(g, ch * 288, GR_BT[gr], nLongBands) + changeSign(g) + end +end + +-- polyphase synthesis (mp3d_DCT_II, mp3d_synth, mp3d_synth_granule) + + +-- mp3d_synth_pair: z = SYN float index, dst = PCM float index +@native local function synthPair(dst: number, nch: number, z: number) + local zb = z * 4 + local a = (rf(SYN, zb + 14 * 256) - rf(SYN, zb)) * 29 + a += (rf(SYN, zb + 1 * 256) + rf(SYN, zb + 13 * 256)) * 213 + a += (rf(SYN, zb + 12 * 256) - rf(SYN, zb + 2 * 256)) * 459 + a += (rf(SYN, zb + 3 * 256) + rf(SYN, zb + 11 * 256)) * 2037 + a += (rf(SYN, zb + 10 * 256) - rf(SYN, zb + 4 * 256)) * 5153 + a += (rf(SYN, zb + 5 * 256) + rf(SYN, zb + 9 * 256)) * 6574 + a += (rf(SYN, zb + 8 * 256) - rf(SYN, zb + 6 * 256)) * 37489 + a += rf(SYN, zb + 7 * 256) * 75038 + wf(PCM, dst * 4, a * SCALE) + zb += 8 + a = rf(SYN, zb + 14 * 256) * 104 + a += rf(SYN, zb + 12 * 256) * 1567 + a += rf(SYN, zb + 10 * 256) * 9727 + a += rf(SYN, zb + 8 * 256) * 64019 + a += rf(SYN, zb + 6 * 256) * -9975 + a += rf(SYN, zb + 4 * 256) * -45 + a += rf(SYN, zb + 2 * 256) * 146 + a += rf(SYN, zb) * -5 + wf(PCM, (dst + 16 * nch) * 4, a * SCALE) +end + +-- mp3d_synth: two time slots of 32 subbands -> 64 samples per channel +@native local function synth(xl: number, dstl: number, nch: number, lins: number) + local xr = xl + 576 * (nch - 1) + local dstr = dstl + (nch - 1) + local zlin = lins + 15 * 64 + local zb = zlin * 4 + local xlb, xrb = xl * 4, xr * 4 + wf(SYN, zb + 60 * 4, rf(GRBUF, xlb + 288 * 4)) + wf(SYN, zb + 61 * 4, rf(GRBUF, xrb + 288 * 4)) + wf(SYN, zb + 62 * 4, rf(GRBUF, xlb)) + wf(SYN, zb + 63 * 4, rf(GRBUF, xrb)) + wf(SYN, zb + 124 * 4, rf(GRBUF, xlb + 289 * 4)) + wf(SYN, zb + 125 * 4, rf(GRBUF, xrb + 289 * 4)) + wf(SYN, zb + 126 * 4, rf(GRBUF, xlb + 4)) + wf(SYN, zb + 127 * 4, rf(GRBUF, xrb + 4)) + if nch == 2 then + synthPair(dstr, nch, lins + 4 * 15 + 1) + synthPair(dstr + 32 * nch, nch, lins + 4 * 15 + 64 + 1) + end + synthPair(dstl, nch, lins + 4 * 15) + synthPair(dstl + 32 * nch, nch, lins + 4 * 15 + 64) + + local w = 1 + for i = 14, 0, -1 do + local zi = zb + 16 * i + local s1 = (18 * (31 - i)) * 4 + local s2 = (18 * (1 + i)) * 4 + wf(SYN, zi, rf(GRBUF, xlb + s1)) + wf(SYN, zi + 4, rf(GRBUF, xrb + s1)) + wf(SYN, zi + 8, rf(GRBUF, xlb + s1 + 4)) + wf(SYN, zi + 12, rf(GRBUF, xrb + s1 + 4)) + wf(SYN, zi + 256, rf(GRBUF, xlb + s2 + 4)) + wf(SYN, zi + 260, rf(GRBUF, xrb + s2 + 4)) + wf(SYN, zi - 248, rf(GRBUF, xlb + s2)) + wf(SYN, zi - 244, rf(GRBUF, xrb + s2)) + -- the 8 window steps, even k (a += z w0 - y w1) and odd k (a += y w1 - z w0) in pairs; mono needs lanes 0, 2 + local a0, a1, a2, a3, b0, b1, b2, b3 = 0, 0, 0, 0, 0, 0, 0, 0 + local vz, vy = zi, zi - 15 * 256 + if nch == 2 then + for _ = 0, 3 do + local w0, w1, w2, w3 = WINT[w], WINT[w + 1], WINT[w + 2], WINT[w + 3] + w += 4 + local z0, z1, z2, z3 = rf(SYN, vz), rf(SYN, vz + 4), rf(SYN, vz + 8), rf(SYN, vz + 12) + local y0, y1, y2, y3 = rf(SYN, vy), rf(SYN, vy + 4), rf(SYN, vy + 8), rf(SYN, vy + 12) + b0 += z0 * w1 + y0 * w0 + b1 += z1 * w1 + y1 * w0 + b2 += z2 * w1 + y2 * w0 + b3 += z3 * w1 + y3 * w0 + a0 += z0 * w0 - y0 * w1 + a1 += z1 * w0 - y1 * w1 + a2 += z2 * w0 - y2 * w1 + a3 += z3 * w0 - y3 * w1 + vz -= 256 + vy += 256 + 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 + b3 += z3 * w3 + y3 * w2 + a0 += y0 * w3 - z0 * w2 + a1 += y1 * w3 - z1 * w2 + a2 += y2 * w3 - z2 * w2 + a3 += y3 * w3 - z3 * w2 + vz -= 256 + vy += 256 + end + wf(PCM, (dstr + (15 - i) * 2) * 4, a1 * SCALE) + wf(PCM, (dstr + (17 + i) * 2) * 4, b1 * SCALE) + wf(PCM, (dstr + (47 - i) * 2) * 4, a3 * SCALE) + wf(PCM, (dstr + (49 + i) * 2) * 4, b3 * SCALE) + else + for _ = 0, 3 do + local w0, w1, w2, w3 = WINT[w], WINT[w + 1], WINT[w + 2], WINT[w + 3] + w += 4 + local z0, z2 = rf(SYN, vz), rf(SYN, vz + 8) + local y0, y2 = rf(SYN, vy), rf(SYN, vy + 8) + b0 += z0 * w1 + y0 * w0 + b2 += z2 * w1 + y2 * w0 + a0 += z0 * w0 - y0 * w1 + a2 += z2 * w0 - y2 * w1 + vz -= 256 + vy += 256 + 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 + a2 += y2 * w3 - z2 * w2 + vz -= 256 + vy += 256 + end + end + wf(PCM, (dstl + (15 - i) * nch) * 4, a0 * SCALE) + wf(PCM, (dstl + (17 + i) * nch) * 4, b0 * SCALE) + wf(PCM, (dstl + (47 - i) * nch) * 4, a2 * SCALE) + wf(PCM, (dstl + (49 + i) * nch) * 4, b2 * SCALE) + end +end + +@native local function synthGranule(nbands: number, nch: number, pcm: number) + for ch = 0, nch - 1 do + dctII(576 * ch, nbands) + end + bcopy(SYN, 0, QMF, 0, 15 * 64 * 4) + for i = 0, nbands - 1, 2 do + synth(i, pcm + 32 * nch * i, nch, i * 64) + end + if nch == 1 then + local src = nbands * 64 * 4 + for i = 0, 15 * 64 * 4 - 8, 8 do + wf(QMF, i, rf(SYN, src + i)) + end + else + bcopy(QMF, 0, SYN, nbands * 64 * 4, 15 * 64 * 4) + end +end + +local ALLOC_L1 = { 76, 4, 32 } +local ALLOC_L2M2 = { 60, 4, 4, 44, 3, 7, 44, 2, 19 } +local ALLOC_L2M1 = { 0, 4, 3, 16, 4, 8, 32, 3, 12, 40, 2, 7 } +local ALLOC_L2M1_LOW = { 44, 4, 2, 44, 3, 10 } + +local totalBands, stereoBands = 0, 0 + +@native local function l12ReadScaleInfo(h1: number, h2: number, h3: number, kbpsHdr: number) + local mode = rshift(h3, 6) + local sb = if mode == 3 then 0 elseif mode == 1 then band(rshift(h3, 4), 3) * 4 + 4 else 32 + local layer1 = band(h1, 6) == 6 + local alloc, nbands + if layer1 then + alloc, nbands = ALLOC_L1, 32 + elseif band(h1, 8) == 0 then + alloc, nbands = ALLOC_L2M2, 30 + else + local srIdx = band(rshift(h2, 2), 3) + local kbps = if mode ~= 3 then rshift(kbpsHdr, 1) else kbpsHdr + if kbps == 0 then + kbps = 192 + end + alloc, nbands = ALLOC_L2M1, 27 + if kbps < 56 then + alloc, nbands = ALLOC_L2M1_LOW, if srIdx == 2 then 12 else 8 + elseif kbps >= 96 and srIdx ~= 1 then + nbands = 30 + end + end + totalBands = nbands + stereoBands = min(sb, nbands) + local k, baBits, codeOff, ai = 0, 0, 0, 1 + for i = 0, nbands - 1 do + if i == k then + codeOff, baBits, k = alloc[ai], alloc[ai + 1], k + alloc[ai + 2] + ai += 3 + end + local ba = BITALLOC_CODE[codeOff + getBits(baBits)] + wu8(BA, 2 * i, ba) + if i < stereoBands then + ba = BITALLOC_CODE[codeOff + getBits(baBits)] + end + wu8(BA, 2 * i + 1, if stereoBands ~= 0 then ba else 0) + end + for i = 0, 2 * nbands - 1 do + wu8(SCFCOD, i, if ru8(BA, i) ~= 0 then (if layer1 then 2 else getBits(2)) else 6) + end + -- L12_read_scalefactors + local so = 0 + for i = 0, 2 * nbands - 1 do + local s = 0 + local ba = ru8(BA, i) + local mask = if ba ~= 0 then 4 + band(rshift(19, ru8(SCFCOD, i)), 3) else 0 + local m = 4 + while m ~= 0 do + if band(mask, m) ~= 0 then + local b = getBits(6) + s = f32(DEQ_L12[ba * 3 - 6 + b % 3] * rshift(lshift(1, 21), b // 3)) + end + wf(L12SCF, so, s) + so += 4 + m = rshift(m, 1) + end + end + for i = stereoBands, nbands - 1 do + wu8(BA, 2 * i + 1, 0) + end +end + +@native local function l12Dequantize(g: number, groupSize: number): number + local choff = 576 + for j = 0, 3 do + local dst = g + groupSize * j + for i = 0, 2 * totalBands - 1 do + local ba = ru8(BA, i) + if ba ~= 0 then + if ba < 17 then + local half = lshift(1, ba - 1) - 1 + for k = 0, groupSize - 1 do + wf(GRBUF, (dst + k) * 4, getBits(ba) - half) + end + else + local mod = lshift(2, ba - 17) + 1 + local code = getBits(mod + 2 - rshift(mod, 3)) + for k = 0, groupSize - 1 do + wf(GRBUF, (dst + k) * 4, code % mod - mod // 2) + code //= mod + end + end + end + dst += choff + choff = 18 - choff + end + end + return groupSize * 4 +end + +@native local function l12ApplyScf(scfOff: number) + local sb, tb = stereoBands, totalBands + bcopy(GRBUF, (576 + sb * 18) * 4, GRBUF, sb * 18 * 4, (tb - sb) * 18 * 4) + for i = 0, tb - 1 do + local d = i * 72 + local s0 = rf(L12SCF, (scfOff + i * 6) * 4) + local s1 = rf(L12SCF, (scfOff + i * 6 + 3) * 4) + for k = 0, 11 do + local p = d + k * 4 + wf(GRBUF, p, rf(GRBUF, p) * s0) + wf(GRBUF, p + 2304, rf(GRBUF, p + 2304) * s1) + end + end +end + +local Core = {} + +Core.MAX_FRAME = MAX_FRAME + +type State = { + overlap: buffer, + qmf: buffer, + reserv: buffer, + reservLen: number, + needReset: boolean, +} + +@native function Core.newState(): State + return { + overlap = bcreate(2 * 9 * 32 * 4), + qmf = bcreate(15 * 2 * 32 * 4), + reserv = bcreate(MAX_BITRESERVOIR_BYTES + 8), + reservLen = 0, + needReset = false, + } +end + +-- memset(dec, 0): what minimp3 does whenever it has to re-sync +@native function Core.reset(st: State) + bfill(st.overlap, 0, 0) + bfill(st.qmf, 0, 0) + st.reservLen = 0 + st.needReset = false +end + +Core.lastChannels = 0 + +@native function Core.upmix(pcm: buffer, n: number) + if buffer.len(pcm) < n * 8 then + return + end + for i = n - 1, 0, -1 do + local v = rf(pcm, i * 4) + wf(pcm, i * 8, v) + wf(pcm, i * 8 + 4, v) + end +end + +@native function Core.decodeFrame(st: State, b: buffer, off: number, size: number, pcm: buffer): number + if size < 4 or size > MAX_FRAME or off < 0 or off + size > buffer.len(b) then + st.needReset = true + return 0 + end + if st.needReset then + Core.reset(st) + end + bcopy(FRAME, 0, b, off, size) + bfill(FRAME, size, 0, 8) + OVL, QMF, PCM = st.overlap, st.qmf, pcm + local h1, h2, h3 = ru8(FRAME, 1), ru8(FRAME, 2), ru8(FRAME, 3) + local nch = if band(h3, 0xC0) == 0xC0 then 1 else 2 + Core.lastChannels = nch + local layer = 4 - band(rshift(h1, 1), 3) + local spf = if band(h1, 6) == 6 then 384 elseif band(h1, 14) == 2 then 576 else 1152 + if buffer.len(pcm) < spf * nch * 4 then + return 0 + end + bsBuf, bsPos, bsLimit = FRAME, 32, size * 8 + if band(h1, 1) == 0 then + getBits(16) -- CRC + end + if layer == 3 then + local mdb = readSideInfo(h1, h2, h3) + if mdb < 0 or bsPos > bsLimit then + st.needReset = true + return 0 + end + -- L3_restore_reservoir + local frameBytes = (bsLimit - bsPos) // 8 + local reserv = st.reservLen + local have = min(reserv, mdb) + if have > 0 then + bcopy(MAIN, 0, st.reserv, max(0, reserv - mdb), have) + end + bcopy(MAIN, have, FRAME, bsPos // 8, frameBytes) + bfill(MAIN, have + frameBytes, 0, 8) + local success = reserv >= mdb + bsBuf, bsPos, bsLimit = MAIN, 0, (have + frameBytes) * 8 + if success then + local ngr = if band(h1, 8) ~= 0 then 2 else 1 + local p = 0 + for igr = 0, ngr - 1 do + bfill(GRBUF, 0, 0) + l3Decode(h1, h2, h3, igr * nch, nch) + synthGranule(18, nch, p) + p += 576 * nch + end + end + -- L3_save_reservoir + local pos = (bsPos + 7) // 8 + local remains = bsLimit // 8 - pos + if remains > MAX_BITRESERVOIR_BYTES then + pos += remains - MAX_BITRESERVOIR_BYTES + remains = MAX_BITRESERVOIR_BYTES + end + if remains > 0 and pos >= 0 then + bcopy(st.reserv, 0, MAIN, pos, remains) + end + st.reservLen = max(0, remains) + bsBuf = FRAME + return if success then spf else 0 + end + local kbps = 2 * HALFRATE[(if band(h1, 8) ~= 0 then 45 else 0) + (band(rshift(h1, 1), 3) - 1) * 15 + rshift(h2, 4)] + l12ReadScaleInfo(h1, h2, h3, kbps) + bfill(GRBUF, 0, 0) + local i = 0 + local p = 0 + local group = bor(layer, 1) + for igr = 0, 2 do + i += l12Dequantize(i, group) + if i == 12 then + i = 0 + l12ApplyScf(igr) + synthGranule(12, nch, p) + bfill(GRBUF, 0, 0) + p += 384 * nch + end + if bsPos > bsLimit then + st.needReset = true + return 0 + end + end + return spf +end + +@native function Core.probeL3(b: buffer, off: number, size: number): (number, number, number) + local n = min(size, 64) + if size < 4 or off + n > buffer.len(b) then + return -1, 0, 0 + end + bcopy(FRAME, 0, b, off, n) + local h1, h2, h3 = ru8(FRAME, 1), ru8(FRAME, 2), ru8(FRAME, 3) + bsBuf, bsPos, bsLimit = FRAME, 32, size * 8 + if band(h1, 1) == 0 then + getBits(16) + end + local mdb = readSideInfo(h1, h2, h3) + if mdb < 0 or bsPos > bsLimit then + return -1, 0, 0 + end + local ngr = (if band(h3, 0xC0) == 0xC0 then 1 else 2) * (if band(h1, 8) ~= 0 then 2 else 1) + local sum = 0 + for gr = 0, ngr - 1 do + sum += GR_P23[gr] + end + return mdb, sum, (bsLimit - bsPos) // 8 +end + +-- Layer I / II: minimp3 drops a frame that needs more bits than it has +@native function Core.probeL12(b: buffer, off: number, size: number): boolean + if size < 4 or size > MAX_FRAME or off + size > buffer.len(b) then + return false + end + bcopy(FRAME, 0, b, off, size) + bfill(FRAME, size, 0, 8) + local h1, h2, h3 = ru8(FRAME, 1), ru8(FRAME, 2), ru8(FRAME, 3) + bsBuf, bsPos, bsLimit = FRAME, 32, size * 8 + if band(h1, 1) == 0 then + getBits(16) + end + local layer = 4 - band(rshift(h1, 1), 3) + local kbps = 2 * HALFRATE[(if band(h1, 8) ~= 0 then 45 else 0) + (band(rshift(h1, 1), 3) - 1) * 15 + rshift(h2, 4)] + l12ReadScaleInfo(h1, h2, h3, kbps) + -- the samples: 3 calls of l12Dequantize, each 4 groups of (layer | 1) samples per allocated band + local group = bor(layer, 1) + local bits = 0 + for i = 0, 2 * totalBands - 1 do + local ba = ru8(BA, i) + if ba ~= 0 then + if ba < 17 then + bits += ba * group + else + local mod = lshift(2, ba - 17) + 1 + bits += mod + 2 - rshift(mod, 3) + end + end + end + return bsPos + 12 * bits <= bsLimit +end + +-- mp3dec_check_vbrtag on the frame b[off, off + size): 0 = no tag, -1 = a Xing / Info tag without a frame +-- count, 1 = tag; then frames, encoder delay + 529, padding - 529 (both 0 without a LAME extension) +@native function Core.vbrTag(b: buffer, off: number, size: number): (number, number, number, number) + if size < 12 or size > MAX_FRAME or off + size > buffer.len(b) then + return 0, 0, 0, 0 + end + bcopy(FRAME, 0, b, off, size) + bfill(FRAME, size, 0, 8) + local h1, h2, h3 = ru8(FRAME, 1), ru8(FRAME, 2), ru8(FRAME, 3) + bsBuf, bsPos, bsLimit = FRAME, 32, size * 8 + if band(h1, 1) == 0 then + getBits(16) + end + if readSideInfo(h1, h2, h3) < 0 then + return 0, 0, 0, 0 + end + local t = bsPos // 8 + if t > size or size - t < 8 then + return 0, 0, 0, 0 + end + local tag = buffer.readstring(FRAME, t, 4) + if tag ~= "Xing" and tag ~= "Info" then + return 0, 0, 0, 0 + end + local flags = ru8(FRAME, t + 7) + if band(flags, 1) == 0 then + return -1, 0, 0, 0 + end + t += 8 + if size - t < 4 then + return 0, 0, 0, 0 + end + local frames = bswap(ru32(FRAME, t)) + t += 4 + if band(flags, 2) ~= 0 then + if size - t < 4 then + return 0, 0, 0, 0 + end + t += 4 + end + if band(flags, 4) ~= 0 then + if size - t < 100 then + return 0, 0, 0, 0 + end + t += 100 + end + if band(flags, 8) ~= 0 then + if size - t < 4 then + return 0, 0, 0, 0 + end + t += 4 + end + if size - t < 1 then + return 0, 0, 0, 0 + end + local delay, padding = 0, 0 + if ru8(FRAME, t) ~= 0 then + if size - t <= 35 then + return 0, 0, 0, 0 + end + t += 21 + local t0, t1, t2 = ru8(FRAME, t), ru8(FRAME, t + 1), ru8(FRAME, t + 2) + delay = bor(lshift(t0, 4), rshift(t1, 4)) + 529 + padding = bor(lshift(band(t1, 15), 8), t2) - 529 + end + return 1, frames, delay, padding +end + +return Core +end +__FILES["codecs/audio/Mpa/EncTables"] = function() + +-- codecs/audio/Mpa/EncTables: the synthesis window D and the layer III Huffman trees of ISO/IEC 11172-3, from PDMP3 +-- (public domain / unlicense, Krister Lagerstrom and contributors: licenses/PDMP3-UNLICENSE.txt). Tree entries with a +-- high byte are nodes (high byte: left offset, low byte: right offset), else leaves (x << 4 | y; count1: v w x y bits). +local E = {} +E.D = { + 0.000000000, -0.000015259, -0.000015259, -0.000015259, -0.000015259, -0.000015259, -0.000015259, -0.000030518, + -0.000030518, -0.000030518, -0.000030518, -0.000045776, -0.000045776, -0.000061035, -0.000061035, -0.000076294, + -0.000076294, -0.000091553, -0.000106812, -0.000106812, -0.000122070, -0.000137329, -0.000152588, -0.000167847, + -0.000198364, -0.000213623, -0.000244141, -0.000259399, -0.000289917, -0.000320435, -0.000366211, -0.000396729, + -0.000442505, -0.000473022, -0.000534058, -0.000579834, -0.000625610, -0.000686646, -0.000747681, -0.000808716, + -0.000885010, -0.000961304, -0.001037598, -0.001113892, -0.001205444, -0.001296997, -0.001388550, -0.001480103, + -0.001586914, -0.001693726, -0.001785278, -0.001907349, -0.002014160, -0.002120972, -0.002243042, -0.002349854, + -0.002456665, -0.002578735, -0.002685547, -0.002792358, -0.002899170, -0.002990723, -0.003082275, -0.003173828, + 0.003250122, 0.003326416, 0.003387451, 0.003433228, 0.003463745, 0.003479004, 0.003479004, 0.003463745, + 0.003417969, 0.003372192, 0.003280640, 0.003173828, 0.003051758, 0.002883911, 0.002700806, 0.002487183, + 0.002227783, 0.001937866, 0.001617432, 0.001266479, 0.000869751, 0.000442505, -0.000030518, -0.000549316, + -0.001098633, -0.001693726, -0.002334595, -0.003005981, -0.003723145, -0.004486084, -0.005294800, -0.006118774, + -0.007003784, -0.007919312, -0.008865356, -0.009841919, -0.010848999, -0.011886597, -0.012939453, -0.014022827, + -0.015121460, -0.016235352, -0.017349243, -0.018463135, -0.019577026, -0.020690918, -0.021789551, -0.022857666, + -0.023910522, -0.024932861, -0.025909424, -0.026840210, -0.027725220, -0.028533936, -0.029281616, -0.029937744, + -0.030532837, -0.031005859, -0.031387329, -0.031661987, -0.031814575, -0.031845093, -0.031738281, -0.031478882, + 0.031082153, 0.030517578, 0.029785156, 0.028884888, 0.027801514, 0.026535034, 0.025085449, 0.023422241, + 0.021575928, 0.019531250, 0.017257690, 0.014801025, 0.012115479, 0.009231567, 0.006134033, 0.002822876, + -0.000686646, -0.004394531, -0.008316040, -0.012420654, -0.016708374, -0.021179199, -0.025817871, -0.030609131, + -0.035552979, -0.040634155, -0.045837402, -0.051132202, -0.056533813, -0.061996460, -0.067520142, -0.073059082, + -0.078628540, -0.084182739, -0.089706421, -0.095169067, -0.100540161, -0.105819702, -0.110946655, -0.115921021, + -0.120697021, -0.125259399, -0.129562378, -0.133590698, -0.137298584, -0.140670776, -0.143676758, -0.146255493, + -0.148422241, -0.150115967, -0.151306152, -0.151962280, -0.152069092, -0.151596069, -0.150497437, -0.148773193, + -0.146362305, -0.143264771, -0.139450073, -0.134887695, -0.129577637, -0.123474121, -0.116577148, -0.108856201, + 0.100311279, 0.090927124, 0.080688477, 0.069595337, 0.057617188, 0.044784546, 0.031082153, 0.016510010, + 0.001068115, -0.015228271, -0.032379150, -0.050354004, -0.069168091, -0.088775635, -0.109161377, -0.130310059, + -0.152206421, -0.174789429, -0.198059082, -0.221984863, -0.246505737, -0.271591187, -0.297210693, -0.323318481, + -0.349868774, -0.376800537, -0.404083252, -0.431655884, -0.459472656, -0.487472534, -0.515609741, -0.543823242, + -0.572036743, -0.600219727, -0.628295898, -0.656219482, -0.683914185, -0.711318970, -0.738372803, -0.765029907, + -0.791213989, -0.816864014, -0.841949463, -0.866363525, -0.890090942, -0.913055420, -0.935195923, -0.956481934, + -0.976852417, -0.996246338, -1.014617920, -1.031936646, -1.048156738, -1.063217163, -1.077117920, -1.089782715, + -1.101211548, -1.111373901, -1.120223999, -1.127746582, -1.133926392, -1.138763428, -1.142211914, -1.144287109, + 1.144989014, 1.144287109, 1.142211914, 1.138763428, 1.133926392, 1.127746582, 1.120223999, 1.111373901, + 1.101211548, 1.089782715, 1.077117920, 1.063217163, 1.048156738, 1.031936646, 1.014617920, 0.996246338, + 0.976852417, 0.956481934, 0.935195923, 0.913055420, 0.890090942, 0.866363525, 0.841949463, 0.816864014, + 0.791213989, 0.765029907, 0.738372803, 0.711318970, 0.683914185, 0.656219482, 0.628295898, 0.600219727, + 0.572036743, 0.543823242, 0.515609741, 0.487472534, 0.459472656, 0.431655884, 0.404083252, 0.376800537, + 0.349868774, 0.323318481, 0.297210693, 0.271591187, 0.246505737, 0.221984863, 0.198059082, 0.174789429, + 0.152206421, 0.130310059, 0.109161377, 0.088775635, 0.069168091, 0.050354004, 0.032379150, 0.015228271, + -0.001068115, -0.016510010, -0.031082153, -0.044784546, -0.057617188, -0.069595337, -0.080688477, -0.090927124, + 0.100311279, 0.108856201, 0.116577148, 0.123474121, 0.129577637, 0.134887695, 0.139450073, 0.143264771, + 0.146362305, 0.148773193, 0.150497437, 0.151596069, 0.152069092, 0.151962280, 0.151306152, 0.150115967, + 0.148422241, 0.146255493, 0.143676758, 0.140670776, 0.137298584, 0.133590698, 0.129562378, 0.125259399, + 0.120697021, 0.115921021, 0.110946655, 0.105819702, 0.100540161, 0.095169067, 0.089706421, 0.084182739, + 0.078628540, 0.073059082, 0.067520142, 0.061996460, 0.056533813, 0.051132202, 0.045837402, 0.040634155, + 0.035552979, 0.030609131, 0.025817871, 0.021179199, 0.016708374, 0.012420654, 0.008316040, 0.004394531, + 0.000686646, -0.002822876, -0.006134033, -0.009231567, -0.012115479, -0.014801025, -0.017257690, -0.019531250, + -0.021575928, -0.023422241, -0.025085449, -0.026535034, -0.027801514, -0.028884888, -0.029785156, -0.030517578, + 0.031082153, 0.031478882, 0.031738281, 0.031845093, 0.031814575, 0.031661987, 0.031387329, 0.031005859, + 0.030532837, 0.029937744, 0.029281616, 0.028533936, 0.027725220, 0.026840210, 0.025909424, 0.024932861, + 0.023910522, 0.022857666, 0.021789551, 0.020690918, 0.019577026, 0.018463135, 0.017349243, 0.016235352, + 0.015121460, 0.014022827, 0.012939453, 0.011886597, 0.010848999, 0.009841919, 0.008865356, 0.007919312, + 0.007003784, 0.006118774, 0.005294800, 0.004486084, 0.003723145, 0.003005981, 0.002334595, 0.001693726, + 0.001098633, 0.000549316, 0.000030518, -0.000442505, -0.000869751, -0.001266479, -0.001617432, -0.001937866, + -0.002227783, -0.002487183, -0.002700806, -0.002883911, -0.003051758, -0.003173828, -0.003280640, -0.003372192, + -0.003417969, -0.003463745, -0.003479004, -0.003479004, -0.003463745, -0.003433228, -0.003387451, -0.003326416, + 0.003250122, 0.003173828, 0.003082275, 0.002990723, 0.002899170, 0.002792358, 0.002685547, 0.002578735, + 0.002456665, 0.002349854, 0.002243042, 0.002120972, 0.002014160, 0.001907349, 0.001785278, 0.001693726, + 0.001586914, 0.001480103, 0.001388550, 0.001296997, 0.001205444, 0.001113892, 0.001037598, 0.000961304, + 0.000885010, 0.000808716, 0.000747681, 0.000686646, 0.000625610, 0.000579834, 0.000534058, 0.000473022, + 0.000442505, 0.000396729, 0.000366211, 0.000320435, 0.000289917, 0.000259399, 0.000244141, 0.000213623, + 0.000198364, 0.000167847, 0.000152588, 0.000137329, 0.000122070, 0.000106812, 0.000106812, 0.000091553, + 0.000076294, 0.000076294, 0.000061035, 0.000061035, 0.000045776, 0.000045776, 0.000030518, 0.000030518, + 0.000030518, 0.000030518, 0.000015259, 0.000015259, 0.000015259, 0.000015259, 0.000015259, 0.000015259, +} +E.LINBITS = { [0] = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 8, 10, 13, 4, 5, 6, 7, 8, 9, 11, 13, 0, 0 } +-- trees by table number (tables 16..23 share 16's tree, 24..31 share 24's) +E.TREES = { + [1] = { + 0x0201, 0x0000, 0x0201, 0x0010, 0x0201, 0x0001, 0x0011, + }, + [2] = { + 0x0201, 0x0000, 0x0401, 0x0201, 0x0010, 0x0001, 0x0201, 0x0011, 0x0401, 0x0201, 0x0020, 0x0021, 0x0201, 0x0012, 0x0201, 0x0002, + 0x0022, + }, + [3] = { + 0x0401, 0x0201, 0x0000, 0x0001, 0x0201, 0x0011, 0x0201, 0x0010, 0x0401, 0x0201, 0x0020, 0x0021, 0x0201, 0x0012, 0x0201, 0x0002, + 0x0022, + }, + [5] = { + 0x0201, 0x0000, 0x0401, 0x0201, 0x0010, 0x0001, 0x0201, 0x0011, 0x0801, 0x0401, 0x0201, 0x0020, 0x0002, 0x0201, 0x0021, 0x0012, + 0x0801, 0x0401, 0x0201, 0x0022, 0x0030, 0x0201, 0x0003, 0x0013, 0x0201, 0x0031, 0x0201, 0x0032, 0x0201, 0x0023, 0x0033, + }, + [6] = { + 0x0601, 0x0401, 0x0201, 0x0000, 0x0010, 0x0011, 0x0601, 0x0201, 0x0001, 0x0201, 0x0020, 0x0021, 0x0601, 0x0201, 0x0012, 0x0201, + 0x0002, 0x0022, 0x0401, 0x0201, 0x0031, 0x0013, 0x0401, 0x0201, 0x0030, 0x0032, 0x0201, 0x0023, 0x0201, 0x0003, 0x0033, + }, + [7] = { + 0x0201, 0x0000, 0x0401, 0x0201, 0x0010, 0x0001, 0x0801, 0x0201, 0x0011, 0x0401, 0x0201, 0x0020, 0x0002, 0x0021, 0x1201, 0x0601, + 0x0201, 0x0012, 0x0201, 0x0022, 0x0030, 0x0401, 0x0201, 0x0031, 0x0013, 0x0401, 0x0201, 0x0003, 0x0032, 0x0201, 0x0023, 0x0004, + 0x0a01, 0x0401, 0x0201, 0x0040, 0x0041, 0x0201, 0x0014, 0x0201, 0x0042, 0x0024, 0x0c01, 0x0601, 0x0401, 0x0201, 0x0033, 0x0043, + 0x0050, 0x0401, 0x0201, 0x0034, 0x0005, 0x0051, 0x0601, 0x0201, 0x0015, 0x0201, 0x0052, 0x0025, 0x0401, 0x0201, 0x0044, 0x0035, + 0x0401, 0x0201, 0x0053, 0x0054, 0x0201, 0x0045, 0x0055, + }, + [8] = { + 0x0601, 0x0201, 0x0000, 0x0201, 0x0010, 0x0001, 0x0201, 0x0011, 0x0401, 0x0201, 0x0021, 0x0012, 0x0e01, 0x0401, 0x0201, 0x0020, + 0x0002, 0x0201, 0x0022, 0x0401, 0x0201, 0x0030, 0x0003, 0x0201, 0x0031, 0x0013, 0x0e01, 0x0801, 0x0401, 0x0201, 0x0032, 0x0023, + 0x0201, 0x0040, 0x0004, 0x0201, 0x0041, 0x0201, 0x0014, 0x0042, 0x0c01, 0x0601, 0x0201, 0x0024, 0x0201, 0x0033, 0x0050, 0x0401, + 0x0201, 0x0043, 0x0034, 0x0051, 0x0601, 0x0201, 0x0015, 0x0201, 0x0005, 0x0052, 0x0601, 0x0201, 0x0025, 0x0201, 0x0044, 0x0035, + 0x0201, 0x0053, 0x0201, 0x0045, 0x0201, 0x0054, 0x0055, + }, + [9] = { + 0x0801, 0x0401, 0x0201, 0x0000, 0x0010, 0x0201, 0x0001, 0x0011, 0x0a01, 0x0401, 0x0201, 0x0020, 0x0021, 0x0201, 0x0012, 0x0201, + 0x0002, 0x0022, 0x0c01, 0x0601, 0x0401, 0x0201, 0x0030, 0x0003, 0x0031, 0x0201, 0x0013, 0x0201, 0x0032, 0x0023, 0x0c01, 0x0401, + 0x0201, 0x0041, 0x0014, 0x0401, 0x0201, 0x0040, 0x0033, 0x0201, 0x0042, 0x0024, 0x0a01, 0x0601, 0x0401, 0x0201, 0x0004, 0x0050, + 0x0043, 0x0201, 0x0034, 0x0051, 0x0801, 0x0401, 0x0201, 0x0015, 0x0052, 0x0201, 0x0025, 0x0044, 0x0601, 0x0401, 0x0201, 0x0005, + 0x0054, 0x0053, 0x0201, 0x0035, 0x0201, 0x0045, 0x0055, + }, + [10] = { + 0x0201, 0x0000, 0x0401, 0x0201, 0x0010, 0x0001, 0x0a01, 0x0201, 0x0011, 0x0401, 0x0201, 0x0020, 0x0002, 0x0201, 0x0021, 0x0012, + 0x1c01, 0x0801, 0x0401, 0x0201, 0x0022, 0x0030, 0x0201, 0x0031, 0x0013, 0x0801, 0x0401, 0x0201, 0x0003, 0x0032, 0x0201, 0x0023, + 0x0040, 0x0401, 0x0201, 0x0041, 0x0014, 0x0401, 0x0201, 0x0004, 0x0033, 0x0201, 0x0042, 0x0024, 0x1c01, 0x0a01, 0x0601, 0x0401, + 0x0201, 0x0050, 0x0005, 0x0060, 0x0201, 0x0061, 0x0016, 0x0c01, 0x0601, 0x0401, 0x0201, 0x0043, 0x0034, 0x0051, 0x0201, 0x0015, + 0x0201, 0x0052, 0x0025, 0x0401, 0x0201, 0x0026, 0x0036, 0x0071, 0x1401, 0x0801, 0x0201, 0x0017, 0x0401, 0x0201, 0x0044, 0x0053, + 0x0006, 0x0601, 0x0401, 0x0201, 0x0035, 0x0045, 0x0062, 0x0201, 0x0070, 0x0201, 0x0007, 0x0064, 0x0e01, 0x0401, 0x0201, 0x0072, + 0x0027, 0x0601, 0x0201, 0x0063, 0x0201, 0x0054, 0x0055, 0x0201, 0x0046, 0x0073, 0x0801, 0x0401, 0x0201, 0x0037, 0x0065, 0x0201, + 0x0056, 0x0074, 0x0601, 0x0201, 0x0047, 0x0201, 0x0066, 0x0075, 0x0401, 0x0201, 0x0057, 0x0076, 0x0201, 0x0067, 0x0077, + }, + [11] = { + 0x0601, 0x0201, 0x0000, 0x0201, 0x0010, 0x0001, 0x0801, 0x0201, 0x0011, 0x0401, 0x0201, 0x0020, 0x0002, 0x0012, 0x1801, 0x0801, + 0x0201, 0x0021, 0x0201, 0x0022, 0x0201, 0x0030, 0x0003, 0x0401, 0x0201, 0x0031, 0x0013, 0x0401, 0x0201, 0x0032, 0x0023, 0x0401, + 0x0201, 0x0040, 0x0004, 0x0201, 0x0041, 0x0014, 0x1e01, 0x1001, 0x0a01, 0x0401, 0x0201, 0x0042, 0x0024, 0x0401, 0x0201, 0x0033, + 0x0043, 0x0050, 0x0401, 0x0201, 0x0034, 0x0051, 0x0061, 0x0601, 0x0201, 0x0016, 0x0201, 0x0006, 0x0026, 0x0201, 0x0062, 0x0201, + 0x0015, 0x0201, 0x0005, 0x0052, 0x1001, 0x0a01, 0x0601, 0x0401, 0x0201, 0x0025, 0x0044, 0x0060, 0x0201, 0x0063, 0x0036, 0x0401, + 0x0201, 0x0070, 0x0017, 0x0071, 0x1001, 0x0601, 0x0401, 0x0201, 0x0007, 0x0064, 0x0072, 0x0201, 0x0027, 0x0401, 0x0201, 0x0053, + 0x0035, 0x0201, 0x0054, 0x0045, 0x0a01, 0x0401, 0x0201, 0x0046, 0x0073, 0x0201, 0x0037, 0x0201, 0x0065, 0x0056, 0x0a01, 0x0601, + 0x0401, 0x0201, 0x0055, 0x0057, 0x0074, 0x0201, 0x0047, 0x0066, 0x0401, 0x0201, 0x0075, 0x0076, 0x0201, 0x0067, 0x0077, + }, + [12] = { + 0x0c01, 0x0401, 0x0201, 0x0010, 0x0001, 0x0201, 0x0011, 0x0201, 0x0000, 0x0201, 0x0020, 0x0002, 0x1001, 0x0401, 0x0201, 0x0021, + 0x0012, 0x0401, 0x0201, 0x0022, 0x0031, 0x0201, 0x0013, 0x0201, 0x0030, 0x0201, 0x0003, 0x0040, 0x1a01, 0x0801, 0x0401, 0x0201, + 0x0032, 0x0023, 0x0201, 0x0041, 0x0033, 0x0a01, 0x0401, 0x0201, 0x0014, 0x0042, 0x0201, 0x0024, 0x0201, 0x0004, 0x0050, 0x0401, + 0x0201, 0x0043, 0x0034, 0x0201, 0x0051, 0x0015, 0x1c01, 0x0e01, 0x0801, 0x0401, 0x0201, 0x0052, 0x0025, 0x0201, 0x0053, 0x0035, + 0x0401, 0x0201, 0x0060, 0x0016, 0x0061, 0x0401, 0x0201, 0x0062, 0x0026, 0x0601, 0x0401, 0x0201, 0x0005, 0x0006, 0x0044, 0x0201, + 0x0054, 0x0045, 0x1201, 0x0a01, 0x0401, 0x0201, 0x0063, 0x0036, 0x0401, 0x0201, 0x0070, 0x0007, 0x0071, 0x0401, 0x0201, 0x0017, + 0x0064, 0x0201, 0x0046, 0x0072, 0x0a01, 0x0601, 0x0201, 0x0027, 0x0201, 0x0055, 0x0073, 0x0201, 0x0037, 0x0056, 0x0801, 0x0401, + 0x0201, 0x0065, 0x0074, 0x0201, 0x0047, 0x0066, 0x0401, 0x0201, 0x0075, 0x0057, 0x0201, 0x0076, 0x0201, 0x0067, 0x0077, + }, + [13] = { + 0x0201, 0x0000, 0x0601, 0x0201, 0x0010, 0x0201, 0x0001, 0x0011, 0x1c01, 0x0801, 0x0401, 0x0201, 0x0020, 0x0002, 0x0201, 0x0021, + 0x0012, 0x0801, 0x0401, 0x0201, 0x0022, 0x0030, 0x0201, 0x0003, 0x0031, 0x0601, 0x0201, 0x0013, 0x0201, 0x0032, 0x0023, 0x0401, + 0x0201, 0x0040, 0x0004, 0x0041, 0x4601, 0x1c01, 0x0e01, 0x0601, 0x0201, 0x0014, 0x0201, 0x0033, 0x0042, 0x0401, 0x0201, 0x0024, + 0x0050, 0x0201, 0x0043, 0x0034, 0x0401, 0x0201, 0x0051, 0x0015, 0x0401, 0x0201, 0x0005, 0x0052, 0x0201, 0x0025, 0x0201, 0x0044, + 0x0053, 0x0e01, 0x0801, 0x0401, 0x0201, 0x0060, 0x0006, 0x0201, 0x0061, 0x0016, 0x0401, 0x0201, 0x0080, 0x0008, 0x0081, 0x1001, + 0x0801, 0x0401, 0x0201, 0x0035, 0x0062, 0x0201, 0x0026, 0x0054, 0x0401, 0x0201, 0x0045, 0x0063, 0x0201, 0x0036, 0x0070, 0x0601, + 0x0401, 0x0201, 0x0007, 0x0055, 0x0071, 0x0201, 0x0017, 0x0201, 0x0027, 0x0037, 0x4801, 0x1801, 0x0c01, 0x0401, 0x0201, 0x0018, + 0x0082, 0x0201, 0x0028, 0x0401, 0x0201, 0x0064, 0x0046, 0x0072, 0x0801, 0x0401, 0x0201, 0x0084, 0x0048, 0x0201, 0x0090, 0x0009, + 0x0201, 0x0091, 0x0019, 0x1801, 0x0e01, 0x0801, 0x0401, 0x0201, 0x0073, 0x0065, 0x0201, 0x0056, 0x0074, 0x0401, 0x0201, 0x0047, + 0x0066, 0x0083, 0x0601, 0x0201, 0x0038, 0x0201, 0x0075, 0x0057, 0x0201, 0x0092, 0x0029, 0x0e01, 0x0801, 0x0401, 0x0201, 0x0067, + 0x0085, 0x0201, 0x0058, 0x0039, 0x0201, 0x0093, 0x0201, 0x0049, 0x0086, 0x0601, 0x0201, 0x00a0, 0x0201, 0x0068, 0x000a, 0x0201, + 0x00a1, 0x001a, 0x4401, 0x1801, 0x0c01, 0x0401, 0x0201, 0x00a2, 0x002a, 0x0401, 0x0201, 0x0095, 0x0059, 0x0201, 0x00a3, 0x003a, + 0x0801, 0x0401, 0x0201, 0x004a, 0x0096, 0x0201, 0x00b0, 0x000b, 0x0201, 0x00b1, 0x001b, 0x1401, 0x0801, 0x0201, 0x00b2, 0x0401, + 0x0201, 0x0076, 0x0077, 0x0094, 0x0601, 0x0401, 0x0201, 0x0087, 0x0078, 0x00a4, 0x0401, 0x0201, 0x0069, 0x00a5, 0x002b, 0x0c01, + 0x0601, 0x0401, 0x0201, 0x005a, 0x0088, 0x00b3, 0x0201, 0x003b, 0x0201, 0x0079, 0x00a6, 0x0601, 0x0401, 0x0201, 0x006a, 0x00b4, + 0x00c0, 0x0401, 0x0201, 0x000c, 0x0098, 0x00c1, 0x3c01, 0x1601, 0x0a01, 0x0601, 0x0201, 0x001c, 0x0201, 0x0089, 0x00b5, 0x0201, + 0x005b, 0x00c2, 0x0401, 0x0201, 0x002c, 0x003c, 0x0401, 0x0201, 0x00b6, 0x006b, 0x0201, 0x00c4, 0x004c, 0x1001, 0x0801, 0x0401, + 0x0201, 0x00a8, 0x008a, 0x0201, 0x00d0, 0x000d, 0x0201, 0x00d1, 0x0201, 0x004b, 0x0201, 0x0097, 0x00a7, 0x0c01, 0x0601, 0x0201, + 0x00c3, 0x0201, 0x007a, 0x0099, 0x0401, 0x0201, 0x00c5, 0x005c, 0x00b7, 0x0401, 0x0201, 0x001d, 0x00d2, 0x0201, 0x002d, 0x0201, + 0x007b, 0x00d3, 0x3401, 0x1c01, 0x0c01, 0x0401, 0x0201, 0x003d, 0x00c6, 0x0401, 0x0201, 0x006c, 0x00a9, 0x0201, 0x009a, 0x00d4, + 0x0801, 0x0401, 0x0201, 0x00b8, 0x008b, 0x0201, 0x004d, 0x00c7, 0x0401, 0x0201, 0x007c, 0x00d5, 0x0201, 0x005d, 0x00e0, 0x0a01, + 0x0401, 0x0201, 0x00e1, 0x001e, 0x0401, 0x0201, 0x000e, 0x002e, 0x00e2, 0x0801, 0x0401, 0x0201, 0x00e3, 0x006d, 0x0201, 0x008c, + 0x00e4, 0x0401, 0x0201, 0x00e5, 0x00ba, 0x00f0, 0x2601, 0x1001, 0x0401, 0x0201, 0x00f1, 0x001f, 0x0601, 0x0401, 0x0201, 0x00aa, + 0x009b, 0x00b9, 0x0201, 0x003e, 0x0201, 0x00d6, 0x00c8, 0x0c01, 0x0601, 0x0201, 0x004e, 0x0201, 0x00d7, 0x007d, 0x0201, 0x00ab, + 0x0201, 0x005e, 0x00c9, 0x0601, 0x0201, 0x000f, 0x0201, 0x009c, 0x006e, 0x0201, 0x00f2, 0x002f, 0x2001, 0x1001, 0x0601, 0x0401, + 0x0201, 0x00d8, 0x008d, 0x003f, 0x0601, 0x0201, 0x00f3, 0x0201, 0x00e6, 0x00ca, 0x0201, 0x00f4, 0x004f, 0x0801, 0x0401, 0x0201, + 0x00bb, 0x00ac, 0x0201, 0x00e7, 0x00f5, 0x0401, 0x0201, 0x00d9, 0x009d, 0x0201, 0x005f, 0x00e8, 0x1e01, 0x0c01, 0x0601, 0x0201, + 0x006f, 0x0201, 0x00f6, 0x00cb, 0x0401, 0x0201, 0x00bc, 0x00ad, 0x00da, 0x0801, 0x0201, 0x00f7, 0x0401, 0x0201, 0x007e, 0x007f, + 0x008e, 0x0601, 0x0401, 0x0201, 0x009e, 0x00ae, 0x00cc, 0x0201, 0x00f8, 0x008f, 0x1201, 0x0801, 0x0401, 0x0201, 0x00db, 0x00bd, + 0x0201, 0x00ea, 0x00f9, 0x0401, 0x0201, 0x009f, 0x00eb, 0x0201, 0x00be, 0x0201, 0x00cd, 0x00fa, 0x0e01, 0x0401, 0x0201, 0x00dd, + 0x00ec, 0x0601, 0x0401, 0x0201, 0x00e9, 0x00af, 0x00dc, 0x0201, 0x00ce, 0x00fb, 0x0801, 0x0401, 0x0201, 0x00bf, 0x00de, 0x0201, + 0x00cf, 0x00ee, 0x0401, 0x0201, 0x00df, 0x00ef, 0x0201, 0x00ff, 0x0201, 0x00ed, 0x0201, 0x00fd, 0x0201, 0x00fc, 0x00fe, + }, + [15] = { + 0x1001, 0x0601, 0x0201, 0x0000, 0x0201, 0x0010, 0x0001, 0x0201, 0x0011, 0x0401, 0x0201, 0x0020, 0x0002, 0x0201, 0x0021, 0x0012, + 0x3201, 0x1001, 0x0601, 0x0201, 0x0022, 0x0201, 0x0030, 0x0031, 0x0601, 0x0201, 0x0013, 0x0201, 0x0003, 0x0040, 0x0201, 0x0032, + 0x0023, 0x0e01, 0x0601, 0x0401, 0x0201, 0x0004, 0x0014, 0x0041, 0x0401, 0x0201, 0x0033, 0x0042, 0x0201, 0x0024, 0x0043, 0x0a01, + 0x0601, 0x0201, 0x0034, 0x0201, 0x0050, 0x0005, 0x0201, 0x0051, 0x0015, 0x0401, 0x0201, 0x0052, 0x0025, 0x0401, 0x0201, 0x0044, + 0x0053, 0x0061, 0x5a01, 0x2401, 0x1201, 0x0a01, 0x0601, 0x0201, 0x0035, 0x0201, 0x0060, 0x0006, 0x0201, 0x0016, 0x0062, 0x0401, + 0x0201, 0x0026, 0x0054, 0x0201, 0x0045, 0x0063, 0x0a01, 0x0601, 0x0201, 0x0036, 0x0201, 0x0070, 0x0007, 0x0201, 0x0071, 0x0055, + 0x0401, 0x0201, 0x0017, 0x0064, 0x0201, 0x0072, 0x0027, 0x1801, 0x1001, 0x0801, 0x0401, 0x0201, 0x0046, 0x0073, 0x0201, 0x0037, + 0x0065, 0x0401, 0x0201, 0x0056, 0x0080, 0x0201, 0x0008, 0x0074, 0x0401, 0x0201, 0x0081, 0x0018, 0x0201, 0x0082, 0x0028, 0x1001, + 0x0801, 0x0401, 0x0201, 0x0047, 0x0066, 0x0201, 0x0083, 0x0038, 0x0401, 0x0201, 0x0075, 0x0057, 0x0201, 0x0084, 0x0048, 0x0601, + 0x0401, 0x0201, 0x0090, 0x0019, 0x0091, 0x0401, 0x0201, 0x0092, 0x0076, 0x0201, 0x0067, 0x0029, 0x5c01, 0x2401, 0x1201, 0x0a01, + 0x0401, 0x0201, 0x0085, 0x0058, 0x0401, 0x0201, 0x0009, 0x0077, 0x0093, 0x0401, 0x0201, 0x0039, 0x0094, 0x0201, 0x0049, 0x0086, + 0x0a01, 0x0601, 0x0201, 0x0068, 0x0201, 0x00a0, 0x000a, 0x0201, 0x00a1, 0x001a, 0x0401, 0x0201, 0x00a2, 0x002a, 0x0201, 0x0095, + 0x0059, 0x1a01, 0x0e01, 0x0601, 0x0201, 0x00a3, 0x0201, 0x003a, 0x0087, 0x0401, 0x0201, 0x0078, 0x00a4, 0x0201, 0x004a, 0x0096, + 0x0601, 0x0401, 0x0201, 0x0069, 0x00b0, 0x00b1, 0x0401, 0x0201, 0x001b, 0x00a5, 0x00b2, 0x0e01, 0x0801, 0x0401, 0x0201, 0x005a, + 0x002b, 0x0201, 0x0088, 0x0097, 0x0201, 0x00b3, 0x0201, 0x0079, 0x003b, 0x0801, 0x0401, 0x0201, 0x006a, 0x00b4, 0x0201, 0x004b, + 0x00c1, 0x0401, 0x0201, 0x0098, 0x0089, 0x0201, 0x001c, 0x00b5, 0x5001, 0x2201, 0x1001, 0x0601, 0x0401, 0x0201, 0x005b, 0x002c, + 0x00c2, 0x0601, 0x0401, 0x0201, 0x000b, 0x00c0, 0x00a6, 0x0201, 0x00a7, 0x007a, 0x0a01, 0x0401, 0x0201, 0x00c3, 0x003c, 0x0401, + 0x0201, 0x000c, 0x0099, 0x00b6, 0x0401, 0x0201, 0x006b, 0x00c4, 0x0201, 0x004c, 0x00a8, 0x1401, 0x0a01, 0x0401, 0x0201, 0x008a, + 0x00c5, 0x0401, 0x0201, 0x00d0, 0x005c, 0x00d1, 0x0401, 0x0201, 0x00b7, 0x007b, 0x0201, 0x001d, 0x0201, 0x000d, 0x002d, 0x0c01, + 0x0401, 0x0201, 0x00d2, 0x00d3, 0x0401, 0x0201, 0x003d, 0x00c6, 0x0201, 0x006c, 0x00a9, 0x0601, 0x0401, 0x0201, 0x009a, 0x00b8, + 0x00d4, 0x0401, 0x0201, 0x008b, 0x004d, 0x0201, 0x00c7, 0x007c, 0x4401, 0x2201, 0x1201, 0x0a01, 0x0401, 0x0201, 0x00d5, 0x005d, + 0x0401, 0x0201, 0x00e0, 0x000e, 0x00e1, 0x0401, 0x0201, 0x001e, 0x00e2, 0x0201, 0x00aa, 0x002e, 0x0801, 0x0401, 0x0201, 0x00b9, + 0x009b, 0x0201, 0x00e3, 0x00d6, 0x0401, 0x0201, 0x006d, 0x003e, 0x0201, 0x00c8, 0x008c, 0x1001, 0x0801, 0x0401, 0x0201, 0x00e4, + 0x004e, 0x0201, 0x00d7, 0x007d, 0x0401, 0x0201, 0x00e5, 0x00ba, 0x0201, 0x00ab, 0x005e, 0x0801, 0x0401, 0x0201, 0x00c9, 0x009c, + 0x0201, 0x00f1, 0x001f, 0x0601, 0x0401, 0x0201, 0x00f0, 0x006e, 0x00f2, 0x0201, 0x002f, 0x00e6, 0x2601, 0x1201, 0x0801, 0x0401, + 0x0201, 0x00d8, 0x00f3, 0x0201, 0x003f, 0x00f4, 0x0601, 0x0201, 0x004f, 0x0201, 0x008d, 0x00d9, 0x0201, 0x00bb, 0x00ca, 0x0801, + 0x0401, 0x0201, 0x00ac, 0x00e7, 0x0201, 0x007e, 0x00f5, 0x0801, 0x0401, 0x0201, 0x009d, 0x005f, 0x0201, 0x00e8, 0x008e, 0x0201, + 0x00f6, 0x00cb, 0x2201, 0x1201, 0x0a01, 0x0601, 0x0401, 0x0201, 0x000f, 0x00ae, 0x006f, 0x0201, 0x00bc, 0x00da, 0x0401, 0x0201, + 0x00ad, 0x00f7, 0x0201, 0x007f, 0x00e9, 0x0801, 0x0401, 0x0201, 0x009e, 0x00cc, 0x0201, 0x00f8, 0x008f, 0x0401, 0x0201, 0x00db, + 0x00bd, 0x0201, 0x00ea, 0x00f9, 0x1001, 0x0801, 0x0401, 0x0201, 0x009f, 0x00dc, 0x0201, 0x00cd, 0x00eb, 0x0401, 0x0201, 0x00be, + 0x00fa, 0x0201, 0x00af, 0x00dd, 0x0e01, 0x0601, 0x0401, 0x0201, 0x00ec, 0x00ce, 0x00fb, 0x0401, 0x0201, 0x00bf, 0x00ed, 0x0201, + 0x00de, 0x00fc, 0x0601, 0x0401, 0x0201, 0x00cf, 0x00fd, 0x00ee, 0x0401, 0x0201, 0x00df, 0x00fe, 0x0201, 0x00ef, 0x00ff, + }, + [16] = { + 0x0201, 0x0000, 0x0601, 0x0201, 0x0010, 0x0201, 0x0001, 0x0011, 0x2a01, 0x0801, 0x0401, 0x0201, 0x0020, 0x0002, 0x0201, 0x0021, + 0x0012, 0x0a01, 0x0601, 0x0201, 0x0022, 0x0201, 0x0030, 0x0003, 0x0201, 0x0031, 0x0013, 0x0a01, 0x0401, 0x0201, 0x0032, 0x0023, + 0x0401, 0x0201, 0x0040, 0x0004, 0x0041, 0x0601, 0x0201, 0x0014, 0x0201, 0x0033, 0x0042, 0x0401, 0x0201, 0x0024, 0x0050, 0x0201, + 0x0043, 0x0034, 0x8a01, 0x2801, 0x1001, 0x0601, 0x0401, 0x0201, 0x0005, 0x0015, 0x0051, 0x0401, 0x0201, 0x0052, 0x0025, 0x0401, + 0x0201, 0x0044, 0x0035, 0x0053, 0x0a01, 0x0601, 0x0401, 0x0201, 0x0060, 0x0006, 0x0061, 0x0201, 0x0016, 0x0062, 0x0801, 0x0401, + 0x0201, 0x0026, 0x0054, 0x0201, 0x0045, 0x0063, 0x0401, 0x0201, 0x0036, 0x0070, 0x0071, 0x2801, 0x1201, 0x0801, 0x0201, 0x0017, + 0x0201, 0x0007, 0x0201, 0x0055, 0x0064, 0x0401, 0x0201, 0x0072, 0x0027, 0x0401, 0x0201, 0x0046, 0x0065, 0x0073, 0x0a01, 0x0601, + 0x0201, 0x0037, 0x0201, 0x0056, 0x0008, 0x0201, 0x0080, 0x0081, 0x0601, 0x0201, 0x0018, 0x0201, 0x0074, 0x0047, 0x0201, 0x0082, + 0x0201, 0x0028, 0x0066, 0x1801, 0x0e01, 0x0801, 0x0401, 0x0201, 0x0083, 0x0038, 0x0201, 0x0075, 0x0084, 0x0401, 0x0201, 0x0048, + 0x0090, 0x0091, 0x0601, 0x0201, 0x0019, 0x0201, 0x0009, 0x0076, 0x0201, 0x0092, 0x0029, 0x0e01, 0x0801, 0x0401, 0x0201, 0x0085, + 0x0058, 0x0201, 0x0093, 0x0039, 0x0401, 0x0201, 0x00a0, 0x000a, 0x001a, 0x0801, 0x0201, 0x00a2, 0x0201, 0x0067, 0x0201, 0x0057, + 0x0049, 0x0601, 0x0201, 0x0094, 0x0201, 0x0077, 0x0086, 0x0201, 0x00a1, 0x0201, 0x0068, 0x0095, 0xdc01, 0x7e01, 0x3201, 0x1a01, + 0x0c01, 0x0601, 0x0201, 0x002a, 0x0201, 0x0059, 0x003a, 0x0201, 0x00a3, 0x0201, 0x0087, 0x0078, 0x0801, 0x0401, 0x0201, 0x00a4, + 0x004a, 0x0201, 0x0096, 0x0069, 0x0401, 0x0201, 0x00b0, 0x000b, 0x00b1, 0x0a01, 0x0401, 0x0201, 0x001b, 0x00b2, 0x0201, 0x002b, + 0x0201, 0x00a5, 0x005a, 0x0601, 0x0201, 0x00b3, 0x0201, 0x00a6, 0x006a, 0x0401, 0x0201, 0x00b4, 0x004b, 0x0201, 0x000c, 0x00c1, + 0x1e01, 0x0e01, 0x0601, 0x0401, 0x0201, 0x00b5, 0x00c2, 0x002c, 0x0401, 0x0201, 0x00a7, 0x00c3, 0x0201, 0x006b, 0x00c4, 0x0801, + 0x0201, 0x001d, 0x0401, 0x0201, 0x0088, 0x0097, 0x003b, 0x0401, 0x0201, 0x00d1, 0x00d2, 0x0201, 0x002d, 0x00d3, 0x1201, 0x0601, + 0x0401, 0x0201, 0x001e, 0x002e, 0x00e2, 0x0601, 0x0401, 0x0201, 0x0079, 0x0098, 0x00c0, 0x0201, 0x001c, 0x0201, 0x0089, 0x005b, + 0x0e01, 0x0601, 0x0201, 0x003c, 0x0201, 0x007a, 0x00b6, 0x0401, 0x0201, 0x004c, 0x0099, 0x0201, 0x00a8, 0x008a, 0x0601, 0x0201, + 0x000d, 0x0201, 0x00c5, 0x005c, 0x0401, 0x0201, 0x003d, 0x00c6, 0x0201, 0x006c, 0x009a, 0x5801, 0x5601, 0x2401, 0x1001, 0x0801, + 0x0401, 0x0201, 0x008b, 0x004d, 0x0201, 0x00c7, 0x007c, 0x0401, 0x0201, 0x00d5, 0x005d, 0x0201, 0x00e0, 0x000e, 0x0801, 0x0201, + 0x00e3, 0x0401, 0x0201, 0x00d0, 0x00b7, 0x007b, 0x0601, 0x0401, 0x0201, 0x00a9, 0x00b8, 0x00d4, 0x0201, 0x00e1, 0x0201, 0x00aa, + 0x00b9, 0x1801, 0x0a01, 0x0601, 0x0401, 0x0201, 0x009b, 0x00d6, 0x006d, 0x0201, 0x003e, 0x00c8, 0x0601, 0x0401, 0x0201, 0x008c, + 0x00e4, 0x004e, 0x0401, 0x0201, 0x00d7, 0x00e5, 0x0201, 0x00ba, 0x00ab, 0x0c01, 0x0401, 0x0201, 0x009c, 0x00e6, 0x0401, 0x0201, + 0x006e, 0x00d8, 0x0201, 0x008d, 0x00bb, 0x0801, 0x0401, 0x0201, 0x00e7, 0x009d, 0x0201, 0x00e8, 0x008e, 0x0401, 0x0201, 0x00cb, + 0x00bc, 0x009e, 0x00f1, 0x0201, 0x001f, 0x0201, 0x000f, 0x002f, 0x4201, 0x3801, 0x0201, 0x00f2, 0x3401, 0x3201, 0x1401, 0x0801, + 0x0201, 0x00bd, 0x0201, 0x005e, 0x0201, 0x007d, 0x00c9, 0x0601, 0x0201, 0x00ca, 0x0201, 0x00ac, 0x007e, 0x0401, 0x0201, 0x00da, + 0x00ad, 0x00cc, 0x0a01, 0x0601, 0x0201, 0x00ae, 0x0201, 0x00db, 0x00dc, 0x0201, 0x00cd, 0x00be, 0x0601, 0x0401, 0x0201, 0x00eb, + 0x00ed, 0x00ee, 0x0601, 0x0401, 0x0201, 0x00d9, 0x00ea, 0x00e9, 0x0201, 0x00de, 0x0401, 0x0201, 0x00dd, 0x00ec, 0x00ce, 0x003f, + 0x00f0, 0x0401, 0x0201, 0x00f3, 0x00f4, 0x0201, 0x004f, 0x0201, 0x00f5, 0x005f, 0x0a01, 0x0201, 0x00ff, 0x0401, 0x0201, 0x00f6, + 0x006f, 0x0201, 0x00f7, 0x007f, 0x0c01, 0x0601, 0x0201, 0x008f, 0x0201, 0x00f8, 0x00f9, 0x0401, 0x0201, 0x009f, 0x00fa, 0x00af, + 0x0801, 0x0401, 0x0201, 0x00fb, 0x00bf, 0x0201, 0x00fc, 0x00cf, 0x0401, 0x0201, 0x00fd, 0x00df, 0x0201, 0x00fe, 0x00ef, + }, + [24] = { + 0x3c01, 0x0801, 0x0401, 0x0201, 0x0000, 0x0010, 0x0201, 0x0001, 0x0011, 0x0e01, 0x0601, 0x0401, 0x0201, 0x0020, 0x0002, 0x0021, + 0x0201, 0x0012, 0x0201, 0x0022, 0x0201, 0x0030, 0x0003, 0x0e01, 0x0401, 0x0201, 0x0031, 0x0013, 0x0401, 0x0201, 0x0032, 0x0023, + 0x0401, 0x0201, 0x0040, 0x0004, 0x0041, 0x0801, 0x0401, 0x0201, 0x0014, 0x0033, 0x0201, 0x0042, 0x0024, 0x0601, 0x0401, 0x0201, + 0x0043, 0x0034, 0x0051, 0x0601, 0x0401, 0x0201, 0x0050, 0x0005, 0x0015, 0x0201, 0x0052, 0x0025, 0xfa01, 0x6201, 0x2201, 0x1201, + 0x0a01, 0x0401, 0x0201, 0x0044, 0x0053, 0x0201, 0x0035, 0x0201, 0x0060, 0x0006, 0x0401, 0x0201, 0x0061, 0x0016, 0x0201, 0x0062, + 0x0026, 0x0801, 0x0401, 0x0201, 0x0054, 0x0045, 0x0201, 0x0063, 0x0036, 0x0401, 0x0201, 0x0071, 0x0055, 0x0201, 0x0064, 0x0046, + 0x2001, 0x0e01, 0x0601, 0x0201, 0x0072, 0x0201, 0x0027, 0x0037, 0x0201, 0x0073, 0x0401, 0x0201, 0x0070, 0x0007, 0x0017, 0x0a01, + 0x0401, 0x0201, 0x0065, 0x0056, 0x0401, 0x0201, 0x0080, 0x0008, 0x0081, 0x0401, 0x0201, 0x0074, 0x0047, 0x0201, 0x0018, 0x0082, + 0x1001, 0x0801, 0x0401, 0x0201, 0x0028, 0x0066, 0x0201, 0x0083, 0x0038, 0x0401, 0x0201, 0x0075, 0x0057, 0x0201, 0x0084, 0x0048, + 0x0801, 0x0401, 0x0201, 0x0091, 0x0019, 0x0201, 0x0092, 0x0076, 0x0401, 0x0201, 0x0067, 0x0029, 0x0201, 0x0085, 0x0058, 0x5c01, + 0x2201, 0x1001, 0x0801, 0x0401, 0x0201, 0x0093, 0x0039, 0x0201, 0x0094, 0x0049, 0x0401, 0x0201, 0x0077, 0x0086, 0x0201, 0x0068, + 0x00a1, 0x0801, 0x0401, 0x0201, 0x00a2, 0x002a, 0x0201, 0x0095, 0x0059, 0x0401, 0x0201, 0x00a3, 0x003a, 0x0201, 0x0087, 0x0201, + 0x0078, 0x004a, 0x1601, 0x0c01, 0x0401, 0x0201, 0x00a4, 0x0096, 0x0401, 0x0201, 0x0069, 0x00b1, 0x0201, 0x001b, 0x00a5, 0x0601, + 0x0201, 0x00b2, 0x0201, 0x005a, 0x002b, 0x0201, 0x0088, 0x00b3, 0x1001, 0x0a01, 0x0601, 0x0201, 0x0090, 0x0201, 0x0009, 0x00a0, + 0x0201, 0x0097, 0x0079, 0x0401, 0x0201, 0x00a6, 0x006a, 0x00b4, 0x0c01, 0x0601, 0x0201, 0x001a, 0x0201, 0x000a, 0x00b0, 0x0201, + 0x003b, 0x0201, 0x000b, 0x00c0, 0x0401, 0x0201, 0x004b, 0x00c1, 0x0201, 0x0098, 0x0089, 0x4301, 0x2201, 0x1001, 0x0801, 0x0401, + 0x0201, 0x001c, 0x00b5, 0x0201, 0x005b, 0x00c2, 0x0401, 0x0201, 0x002c, 0x00a7, 0x0201, 0x007a, 0x00c3, 0x0a01, 0x0601, 0x0201, + 0x003c, 0x0201, 0x000c, 0x00d0, 0x0201, 0x00b6, 0x006b, 0x0401, 0x0201, 0x00c4, 0x004c, 0x0201, 0x0099, 0x00a8, 0x1001, 0x0801, + 0x0401, 0x0201, 0x008a, 0x00c5, 0x0201, 0x005c, 0x00d1, 0x0401, 0x0201, 0x00b7, 0x007b, 0x0201, 0x001d, 0x00d2, 0x0901, 0x0401, + 0x0201, 0x002d, 0x00d3, 0x0201, 0x003d, 0x00c6, 0x55fa, 0x0401, 0x0201, 0x006c, 0x00a9, 0x0201, 0x009a, 0x00d4, 0x2001, 0x1001, + 0x0801, 0x0401, 0x0201, 0x00b8, 0x008b, 0x0201, 0x004d, 0x00c7, 0x0401, 0x0201, 0x007c, 0x00d5, 0x0201, 0x005d, 0x00e1, 0x0801, + 0x0401, 0x0201, 0x001e, 0x00e2, 0x0201, 0x00aa, 0x00b9, 0x0401, 0x0201, 0x009b, 0x00e3, 0x0201, 0x00d6, 0x006d, 0x1401, 0x0a01, + 0x0601, 0x0201, 0x003e, 0x0201, 0x002e, 0x004e, 0x0201, 0x00c8, 0x008c, 0x0401, 0x0201, 0x00e4, 0x00d7, 0x0401, 0x0201, 0x007d, + 0x00ab, 0x00e5, 0x0a01, 0x0401, 0x0201, 0x00ba, 0x005e, 0x0201, 0x00c9, 0x0201, 0x009c, 0x006e, 0x0801, 0x0201, 0x00e6, 0x0201, + 0x000d, 0x0201, 0x00e0, 0x000e, 0x0401, 0x0201, 0x00d8, 0x008d, 0x0201, 0x00bb, 0x00ca, 0x4a01, 0x0201, 0x00ff, 0x4001, 0x3a01, + 0x2001, 0x1001, 0x0801, 0x0401, 0x0201, 0x00ac, 0x00e7, 0x0201, 0x007e, 0x00d9, 0x0401, 0x0201, 0x009d, 0x00e8, 0x0201, 0x008e, + 0x00cb, 0x0801, 0x0401, 0x0201, 0x00bc, 0x00da, 0x0201, 0x00ad, 0x00e9, 0x0401, 0x0201, 0x009e, 0x00cc, 0x0201, 0x00db, 0x00bd, + 0x1001, 0x0801, 0x0401, 0x0201, 0x00ea, 0x00ae, 0x0201, 0x00dc, 0x00cd, 0x0401, 0x0201, 0x00eb, 0x00be, 0x0201, 0x00dd, 0x00ec, + 0x0801, 0x0401, 0x0201, 0x00ce, 0x00ed, 0x0201, 0x00de, 0x00ee, 0x000f, 0x0401, 0x0201, 0x00f0, 0x001f, 0x00f1, 0x0401, 0x0201, + 0x00f2, 0x002f, 0x0201, 0x00f3, 0x003f, 0x1201, 0x0801, 0x0401, 0x0201, 0x00f4, 0x004f, 0x0201, 0x00f5, 0x005f, 0x0401, 0x0201, + 0x00f6, 0x006f, 0x0201, 0x00f7, 0x0201, 0x007f, 0x008f, 0x0a01, 0x0401, 0x0201, 0x00f8, 0x00f9, 0x0401, 0x0201, 0x009f, 0x00af, + 0x00fa, 0x0801, 0x0401, 0x0201, 0x00fb, 0x00bf, 0x0201, 0x00fc, 0x00cf, 0x0401, 0x0201, 0x00fd, 0x00df, 0x0201, 0x00fe, 0x00ef, + }, + [32] = { + 0x0201, 0x0000, 0x0801, 0x0401, 0x0201, 0x0008, 0x0004, 0x0201, 0x0001, 0x0002, 0x0801, 0x0401, 0x0201, 0x000c, 0x000a, 0x0201, + 0x0003, 0x0006, 0x0601, 0x0201, 0x0009, 0x0201, 0x0005, 0x0007, 0x0401, 0x0201, 0x000e, 0x000d, 0x0201, 0x000f, 0x000b, + }, + [33] = { + 0x1001, 0x0801, 0x0401, 0x0201, 0x0000, 0x0001, 0x0201, 0x0002, 0x0003, 0x0401, 0x0201, 0x0004, 0x0005, 0x0201, 0x0006, 0x0007, + 0x0801, 0x0401, 0x0201, 0x0008, 0x0009, 0x0201, 0x000a, 0x000b, 0x0401, 0x0201, 0x000c, 0x000d, 0x0201, 0x000e, 0x000f, + }, +} +return E +end +__FILES["codecs/audio/Mpa/Encode2"] = @native function() + + + +-- codecs/audio/Mpa/Encode2: an MPEG audio layer II CBR encoder, written from ISO/IEC 11172-3 (2.4.2.3, C.1.5.2). +-- Bit allocation tables in minimp3's compact form (CC0, licenses/minimp3-CC0.txt); greedy allocation by noise (signal +-- level minus the quantizer's SNR), no psychoacoustic model. +local Bits = __include("core/Bits") +local T = __include("codecs/audio/Mpa/Tables") +local Analysis = __include("codecs/audio/Mpa/Analysis") + +local Encode2 = {} + +local floor, log = math.floor, math.log +local writeu8 = buffer.writeu8 + +local POW = table.create(40, 0) +for i = 0, 39 do + POW[i + 1] = 2 ^ i +end + +-- the allocation tables: { bit-allocation-code offset into g_bitalloc_code_tab, bits, band count } runs (minimp3) +local ALLOC_L2M1 = { 0, 4, 3, 16, 4, 8, 32, 3, 12, 40, 2, 7 } +local ALLOC_L2M1_LOW = { 44, 4, 2, 44, 3, 10 } +local ALLOC_L2M2 = { 60, 4, 4, 44, 3, 7, 44, 2, 19 } +local CODE = T.g_bitalloc_code_tab + +-- quantizer classes (minimp3's ba): 1..16 -> 2^ba - 1 levels in ba bits; 17 / 18 / 19 -> 3 / 5 / 9 levels grouped +@native local function levels(ba: number): number + if ba >= 17 then + return if ba == 17 then 3 elseif ba == 18 then 5 else 9 + end + return POW[ba + 1] - 1 +end +@native local function tripleBits(ba: number): number + if ba >= 17 then + return if ba == 17 then 5 elseif ba == 18 then 7 else 10 + end + return 3 * ba +end +-- the quantizer's signal-to-noise ratio in dB (ISO 11172-3 table C.5) +local SNR: { [number]: number } = {} +do + local byLevels = { + [3] = 7.00, + [5] = 11.00, + [7] = 16.00, + [9] = 20.84, + [15] = 25.28, + [31] = 31.59, + [63] = 37.75, + [127] = 43.84, + [255] = 49.89, + [511] = 55.93, + [1023] = 61.96, + [2047] = 67.98, + [4095] = 74.01, + [8191] = 80.03, + [16383] = 86.05, + [32767] = 92.01, + [65535] = 98.01, + } + for ba = 1, 19 do + SNR[ba] = byLevels[levels(ba)] or (6.02 * ba) + end +end + +-- scalefactors 2^(1 - i/3), i = 0 .. 62 +local SCF = table.create(63, 0) +for i = 0, 62 do + SCF[i + 1] = 2 ^ (1 - i / 3) +end + +local RATES = { + [44100] = { 3, 0 }, + [48000] = { 3, 1 }, + [32000] = { 3, 2 }, + [22050] = { 2, 0 }, + [24000] = { 2, 1 }, + [16000] = { 2, 2 }, +} +Encode2.RATES = RATES +local BITRATES_V1 = { 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384 } +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 = Bits.RawWriter +local put = Bits.msbPut + +type Source = { + sampleRate: number, + channels: number, + frames: number, + read: (self: any, n: number, out: buffer?) -> (buffer, number), + err: any, +} +type Options = { bitrate: number, mode: string, prefix: buffer? } + +@native function Encode2.encode(src: Source, opts: Options): (buffer?, string?) + local rate = src.sampleRate + local info = RATES[rate] + if not info then + return nil, "unsupported sample rate" + end + local version, srIndex = info[1], info[2] + local mpeg1 = version == 3 + local inCh = src.channels + local nch = if opts.mode == "mono" then 1 else 2 + local kbps = opts.bitrate + local list = if mpeg1 then BITRATES_V1 else BITRATES_V2 + local brIndex = table.find(list, kbps) + if not brIndex then + return nil, "unsupported bit rate" + end + local alloc, nbands + if not mpeg1 then + alloc, nbands = ALLOC_L2M2, 30 + else + local perCh = if nch == 2 then kbps // 2 else kbps + alloc, nbands = ALLOC_L2M1, 27 + if perCh < 56 then + alloc, nbands = ALLOC_L2M1_LOW, if srIndex == 2 then 12 else 8 + elseif perCh >= 96 and srIndex ~= 1 then + nbands = 30 + end + end + local bandOff, bandBits = table.create(nbands, 0), table.create(nbands, 0) + do + local k, ai = 0, 1 + local off, bits = 0, 0 + for i = 0, nbands - 1 do + if i == k then + off, bits, k = alloc[ai], alloc[ai + 1], k + alloc[ai + 2] + ai += 3 + end + bandOff[i + 1], bandBits[i + 1] = off, bits + end + end + -- per band: the classes it can take, in increasing order (index into the code table = the value written) + local steps: { { { number } } } = {} + for i = 1, nbands do + local s = {} + for v = 1, POW[bandBits[i] + 1] - 1 do + local ba = CODE[bandOff[i] + v] + if ba and ba > 0 then + table.insert(s, { v, ba }) + end + end + steps[i] = s + end + local w: W = { buf = buffer.create(65536), pos = 0, acc = 0, cnt = 0 } + if opts.prefix then + local pf = opts.prefix :: buffer + if buffer.len(pf) > buffer.len(w.buf) - 16 then + w.buf = buffer.create(buffer.len(pf) + 65536) + end + buffer.copy(w.buf, 0, pf, 0, buffer.len(pf)) + w.pos = buffer.len(pf) + end + local ana = { Analysis.new(), Analysis.new() } + local pcm = { table.create(1152, 0), table.create(1152, 0) } + -- subband samples: sb[c][band * 36 + t + 1], t = 0 .. 35 + local sbs = { table.create(32 * 36, 0), table.create(32 * 36, 0) } + local sub = table.create(32, 0) + local scf = { table.create(32 * 3, 0), table.create(32 * 3, 0) } + local bal = { table.create(32, 0), table.create(32, 0) } + local slot = 144000 * kbps + local rest = 0 + local tmp: buffer? = nil + local pending: buffer? = nil + local pendN, pendOff = 0, 0 + local srcDone, flushed = false, false + while true do + local got = 0 + while got < 1152 and not srcDone do + if pendN == 0 then + local b, n = src:read(4096, tmp) + if n <= 0 then + srcDone = true + break + end + tmp = b + pending, pendN, pendOff = b, n, 0 + end + local take = math.min(1152 - got, pendN) + local pb = pending :: buffer + for i = 0, take - 1 do + local base = (pendOff + i) * inCh * 4 + local l = buffer.readf32(pb, base) + local r = if inCh > 1 then buffer.readf32(pb, base + 4) else l + if nch == 1 then + pcm[1][got + i + 1] = if inCh > 1 then (l + r) * 0.5 else l + else + pcm[1][got + i + 1] = l + pcm[2][got + i + 1] = r + end + end + got += take + pendN -= take + pendOff += take + end + if got == 0 then + if flushed then + break + end + flushed = true + end + for c = 1, nch do + local s = pcm[c] + for i = got + 1, 1152 do + s[i] = 0 + end + local sb = sbs[c] + for t = 0, 35 do + Analysis.run(ana[c], s, t * 32 + 1, sub, 1) + for b = 0, 31 do + sb[b * 36 + t + 1] = sub[b + 1] + end + end + -- scalefactors: the smallest scalefactor (largest index) still >= the part's peak + local sc = scf[c] + for b = 0, nbands - 1 do + for part = 0, 2 do + local m = 0 + local o = b * 36 + part * 12 + for t = 1, 12 do + local v = math.abs(sb[o + t]) + if v > m then + m = v + end + end + local idx = 62 + if m > 0 then + idx = math.clamp(floor(3 * (1 - log(m) / log(2))), 0, 62) + while idx > 0 and SCF[idx + 1] < m do + idx -= 1 + end + while idx < 62 and SCF[idx + 2] >= m do + idx += 1 + end + end + sc[b * 3 + part + 1] = idx + end + end + end + local frameBytes = slot // rate + rest += slot % rate + local padding = 0 + if rest >= rate then + rest -= rate + padding = 1 + frameBytes += 1 + end + local avail = frameBytes * 8 - 32 + for b = 1, nbands do + avail -= bandBits[b] * nch + end + local level = { table.create(nbands, 0), table.create(nbands, 0) } + for c = 1, nch do + local sc = scf[c] + for b = 1, nbands do + local best = math.min(sc[(b - 1) * 3 + 1], sc[(b - 1) * 3 + 2], sc[(b - 1) * 3 + 3]) + level[c][b] = 20 * math.log10(SCF[best + 1]) + bal[c][b] = 0 + end + end + while true do + local bestC, bestB, bestNoise, bestCost = 0, 0, -math.huge, 0 + for c = 1, nch do + for b = 1, nbands do + local st = bal[c][b] + local s = steps[b] + if st < #s and level[c][b] > -110 then + local cur = if st == 0 then 0 else s[st][2] + local nxt = s[st + 1][2] + local noise = level[c][b] - (if st == 0 then 0 else SNR[cur]) + local cost = 12 * tripleBits(nxt) - (if st == 0 then 0 else 12 * tripleBits(cur)) + if st == 0 then + cost += 2 + 18 -- scfsi + three scalefactors + end + if cost <= avail and noise > bestNoise then + bestC, bestB, bestNoise, bestCost = c, b, noise, cost + end + end + end + end + if bestC == 0 then + break + end + bal[bestC][bestB] += 1 + avail -= bestCost + end + if w.pos + frameBytes + 64 > buffer.len(w.buf) then + local nb = buffer.create(buffer.len(w.buf) * 2 + frameBytes) + buffer.copy(nb, 0, w.buf, 0, w.pos) + w.buf = nb + end + local start = w.pos + put(w, 0x7FF, 11) + put(w, version, 2) + put(w, 2, 2) -- layer II + put(w, 1, 1) -- no CRC + put(w, brIndex, 4) + put(w, srIndex, 2) + put(w, padding, 1) + put(w, 0, 1) + put(w, if nch == 1 then 3 else 0, 2) + put(w, 0, 2) + put(w, 0, 1) + put(w, 1, 1) + put(w, 0, 2) + for b = 1, nbands do + for c = 1, nch do + local st = bal[c][b] + put(w, if st == 0 then 0 else steps[b][st][1], bandBits[b]) + end + end + -- scfsi (0: three scalefactors) and the scalefactors + for b = 1, nbands do + for c = 1, nch do + if bal[c][b] > 0 then + put(w, 0, 2) + end + end + end + for b = 1, nbands do + for c = 1, nch do + if bal[c][b] > 0 then + for part = 1, 3 do + put(w, scf[c][(b - 1) * 3 + part], 6) + end + end + end + end + -- samples: 12 granules of 3, band by band, channel by channel + for gr = 0, 11 do + local part = gr // 4 + for b = 1, nbands do + for c = 1, nch do + local st = bal[c][b] + if st > 0 then + local ba = steps[b][st][2] + local L = levels(ba) + local inv = 1 / SCF[scf[c][(b - 1) * 3 + part + 1] + 1] + local o = (b - 1) * 36 + gr * 3 + local sb = sbs[c] + local q0, q1, q2 + do + @native local function quant(x: number): number + 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 = 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)) + else + put(w, q0, ba) + put(w, q1, ba) + put(w, q2, ba) + end + end + end + end + end + if w.cnt > 0 then + put(w, 0, 8 - w.cnt) + end + while w.pos < start + frameBytes do + writeu8(w.buf, w.pos, 0) + w.pos += 1 + end + end + if src.err then + return nil, tostring(src.err) + end + local out = buffer.create(w.pos) + buffer.copy(out, 0, w.buf, 0, w.pos) + return out, nil +end + +return Encode2 +end +__FILES["codecs/audio/Mpa/Encode3"] = @native function() + + + +-- codecs/audio/Mpa/Encode3: an MPEG audio layer III CBR encoder in the spirit of shine (long blocks, global-gain rate +-- control, no bit reservoir). Written from ISO/IEC 11172-3 / 13818-3 (no shine / LAME code); Huffman codes derived +-- from the standard's decoder trees (codecs/audio/Mpa/EncTables, from PDMP3, public domain). +local Bits = __include("core/Bits") +local E = __include("codecs/audio/Mpa/EncTables") +local T = __include("codecs/audio/Mpa/Tables") +local Analysis = __include("codecs/audio/Mpa/Analysis") + +local Encode3 = {} + +local floor, sqrt, cos, pi = math.floor, math.sqrt, math.cos, math.pi +local writeu8 = buffer.writeu8 + +local POW = table.create(40, 0) +for i = 0, 39 do + POW[i + 1] = 2 ^ i +end + +-- CODE[t][x * 16 + y + 1], LEN[t][...] for the pair tables 1..31 (16..23 and 24..31 share a tree); count1 tables A +-- (32) and B (33) indexed by v * 8 + w * 4 + x * 2 + y + 1 +local CODE: { [number]: { number } } = {} +local LEN: { [number]: { number } } = {} +local XLEN: { [number]: number } = {} + +@native local function walk(tree: { number }, codes: { number }, lens: { number }, p: number, code: number, len: number) + local v = tree[p + 1] + if bit32.band(v, 0xFF00) == 0 then + local idx = bit32.band(v, 0xFF) + 1 + if lens[idx] == 0 then + codes[idx], lens[idx] = code, len + end + return + end + -- left (bit 0): offsets of 250+ chain + local q = p + while bit32.rshift(tree[q + 1], 8) >= 250 do + q += bit32.rshift(tree[q + 1], 8) + end + q += bit32.rshift(tree[q + 1], 8) + walk(tree, codes, lens, q, code * 2, len + 1) + q = p + while bit32.band(tree[q + 1], 0xFF) >= 250 do + q += bit32.band(tree[q + 1], 0xFF) + end + q += bit32.band(tree[q + 1], 0xFF) + walk(tree, codes, lens, q, code * 2 + 1, len + 1) +end + +for t = 1, 33 do + local src = if t >= 16 and t <= 23 then 16 elseif t >= 24 and t <= 31 then 24 else t + local tree = E.TREES[src] + if tree then + local codes, lens = table.create(256, 0), table.create(256, 0) + walk(tree, codes, lens, 0, 0, 0) + -- the leaf value of pair tables is x << 4 | y: index x * 16 + y + 1 (count1: the 4-bit vwxy) + CODE[t], LEN[t] = codes, lens + local xl = 0 + for idx = 1, 256 do + if lens[idx] > 0 then + local x = (idx - 1) // 16 + if x + 1 > xl then + xl = x + 1 + end + end + end + XLEN[t] = xl + end +end +local LINBITS = E.LINBITS +local SMALL: { [number]: { number } } = {} +for m = 0, 15 do + local list = {} + for _, t in { 1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15 } do + if XLEN[t] and XLEN[t] - 1 >= m then + table.insert(list, t) + end + end + SMALL[m] = list +end + +type W = Bits.RawWriter + +local put = Bits.msbPut +Encode3.put = put + +local RATES = { + -- rate -> version bits (3 MPEG-1, 2 MPEG-2, 0 MPEG-2.5), sample rate index, scalefactor band group (g_scf_long) + [44100] = { 3, 0, 5 }, + [48000] = { 3, 1, 6 }, + [32000] = { 3, 2, 7 }, + [22050] = { 2, 0, 2 }, + [24000] = { 2, 1, 3 }, + [16000] = { 2, 2, 4 }, + [11025] = { 0, 0, 0 }, + [12000] = { 0, 1, 0 }, + [8000] = { 0, 2, 1 }, +} +Encode3.RATES = RATES +local BITRATES_V1 = { 32, 40, 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 } +Encode3.BITRATES = { [1] = BITRATES_V1, [2] = BITRATES_V2 } + +-- the 36-point MDCT (long blocks): X[k] = 1/9 sum_i w_i z_i cos(pi/72 (2i + 19)(2k + 1)), w_i = sin(pi/36 (i + 1/2)) +local MDCT = table.create(18 * 36, 0) +for k = 0, 17 do + for i = 0, 35 do + MDCT[k * 36 + i + 1] = math.sin(pi / 36 * (i + 0.5)) * cos(pi / 72 * (2 * i + 19) * (2 * k + 1)) / 9 + end +end +local CI = { -0.6, -0.535, -0.33, -0.185, -0.095, -0.041, -0.0142, -0.0037 } +local CS, CA = table.create(8, 0), table.create(8, 0) +for i = 1, 8 do + local s = sqrt(1 + CI[i] * CI[i]) + CS[i], CA[i] = 1 / s, CI[i] / s +end + +type Plan = { + bits: number, + bigValues: number, + count1: number, + tables: { number }, + region0: number, + region1: number, + c1table: number, -- 0 = A (table 32), 1 = B (33) + addr1: number, + addr2: number, +} + +@native local function newPlan(): Plan + return { bits = 0, bigValues = 0, count1 = 0, tables = { 0, 0, 0 }, region0 = 0, region1 = 0, c1table = 0, addr1 = 0, addr2 = 0 } +end + +@native local function pairBits(ix: { number }, a: number, b: number, t: number): number + if t == 0 then + return 0 + end + local lens = LEN[t] + local lb = LINBITS[t] + local bits = 0 + for i = a, b - 1, 2 do + local x, y = ix[i + 1], ix[i + 2] + local extra = 0 + if x > 14 then + x = 15 + extra += lb + end + if y > 14 then + y = 15 + extra += lb + end + bits += lens[x * 16 + y + 1] + extra + if x ~= 0 then + bits += 1 + end + if y ~= 0 then + bits += 1 + end + end + return bits +end + +@native local function chooseTable(ix: { number }, a: number, b: number): (number, number) + if b <= a then + return 0, 0 + end + local m = 0 + for i = a + 1, b do + local v = ix[i] + if v > m then + m = v + end + end + if m == 0 then + return 0, 0 + end + if m <= 15 then + local best, bestBits = 0, math.huge + for _, t in SMALL[m] do + local bits = pairBits(ix, a, b, t) + if bits < bestBits then + best, bestBits = t, bits + end + end + return best, bestBits + end + local need = m - 15 + local best, bestBits = 0, math.huge + for _, group in { 16, 24 } do + for t = group, group + 7 do + if POW[LINBITS[t] + 1] - 1 >= need then + local bits = pairBits(ix, a, b, t) + if bits < bestBits then + best, bestBits = t, bits + end + break + end + end + end + return best, bestBits +end + +@native local function plan(ix: { number }, bounds: { number }, p: Plan) + local i = 576 + while i > 1 and ix[i] == 0 and ix[i - 1] == 0 do + i -= 2 + end + -- count1 region: quadruples of values <= 1 + local c1 = 0 + while i > 3 and ix[i] <= 1 and ix[i - 1] <= 1 and ix[i - 2] <= 1 and ix[i - 3] <= 1 do + i -= 4 + c1 += 1 + end + local bv = i -- big_values * 2 coefficients + p.bigValues, p.count1 = bv // 2, c1 + local ba, bb = 0, 0 + local lensA = LEN[32] + for q = 0, c1 - 1 do + local o = bv + q * 4 + local v, w, x, y = ix[o + 1], ix[o + 2], ix[o + 3], ix[o + 4] + local s = v + w + x + y + ba += lensA[v * 8 + w * 4 + x * 2 + y + 1] + s + bb += 4 + s + end + p.c1table = if bb < ba then 1 else 0 + local bits = if bb < ba then bb else ba + -- regions: region 0 / 1 / 2 split at scalefactor band boundaries + local j = 0 + while j + 1 < #bounds and bounds[j + 2] <= bv do + j += 1 + end + local r0 = math.clamp(floor((j + 1) / 3), 0, 15) + local r1 = math.clamp(floor((j + 1) / 3), 0, 7) + if r0 + r1 + 2 > 22 then + r1 = 22 - r0 - 2 + end + local a1 = math.min(bounds[r0 + 2] or 576, bv) + local a2 = math.min(bounds[r0 + r1 + 3] or 576, bv) + p.region0, p.region1, p.addr1, p.addr2 = r0, r1, a1, a2 + local t1, b1 = chooseTable(ix, 0, a1) + local t2, b2 = chooseTable(ix, a1, a2) + local t3, b3 = chooseTable(ix, a2, bv) + p.tables[1], p.tables[2], p.tables[3] = t1, t2, t3 + p.bits = bits + b1 + b2 + b3 +end + +@native local function writePairs(w: W, ix: { number }, sign: { boolean }, a: number, b: number, t: number) + if t == 0 then + return + end + local codes, lens = CODE[t], LEN[t] + local lb = LINBITS[t] + for i = a, b - 1, 2 do + local x, y = ix[i + 1], ix[i + 2] + local cx, cy = if x > 14 then 15 else x, if y > 14 then 15 else y + local idx = cx * 16 + cy + 1 + put(w, codes[idx], lens[idx]) + if cx == 15 then + put(w, x - 15, lb) + end + if x ~= 0 then + put(w, if sign[i + 1] then 1 else 0, 1) + end + if cy == 15 then + put(w, y - 15, lb) + end + if y ~= 0 then + put(w, if sign[i + 2] then 1 else 0, 1) + end + end +end + +@native local function writeHuffman(w: W, ix: { number }, sign: { boolean }, p: Plan) + local bv = p.bigValues * 2 + writePairs(w, ix, sign, 0, p.addr1, p.tables[1]) + writePairs(w, ix, sign, p.addr1, p.addr2, p.tables[2]) + writePairs(w, ix, sign, p.addr2, bv, p.tables[3]) + local codesA, lensA = CODE[32], LEN[32] + for q = 0, p.count1 - 1 do + local o = bv + q * 4 + local v, ww, x, y = ix[o + 1], ix[o + 2], ix[o + 3], ix[o + 4] + local idx = v * 8 + ww * 4 + x * 2 + y + if p.c1table == 1 then + put(w, 15 - idx, 4) -- table B: the 4 bits inverted + else + put(w, codesA[idx + 1], lensA[idx + 1]) + end + for k = 1, 4 do + if ix[o + k] ~= 0 then + put(w, if sign[o + k] then 1 else 0, 1) + end + end + end +end + +type Unit = { + xr: { number }, + xa: { number }, -- |xr|^(3/4) + ix: { number }, + sign: { boolean }, + plan: Plan, + gain: number, +} + +@native local function newUnit(): Unit + return { + xr = table.create(576, 0), + xa = table.create(576, 0), + ix = table.create(576, 0), + sign = table.create(576, false), + plan = newPlan(), + gain = 210, + } +end + +-- quantize with global gain g: false when a value overflows 8206 +@native local function quantize(u: Unit, g: number): boolean + local step = 2 ^ (-(g - 210) * 3 / 16) + local xa, ix = u.xa, u.ix + for i = 1, 576 do + local v = floor(xa[i] * step + 0.4054) + if v > 8206 then + return false + end + ix[i] = v + end + return true +end + +@native local function rateLoop(u: Unit, budget: number, bounds: { number }) + local xr, xa, sign = u.xr, u.xa, u.sign + local maxa = 0 + for i = 1, 576 do + local v = xr[i] + sign[i] = v < 0 + local a = math.abs(v) ^ 0.75 + xa[i] = a + if a > maxa then + maxa = a + end + end + local p = u.plan + if maxa < 1e-12 then + for i = 1, 576 do + u.ix[i] = 0 + end + plan(u.ix, bounds, p) + u.gain = 0 + return + end + local lo, hi = 0, 255 + local best = -1 + while lo <= hi do + local mid = (lo + hi) // 2 + if quantize(u, mid) then + plan(u.ix, bounds, p) + if p.bits <= budget then + best = mid + hi = mid - 1 + else + lo = mid + 1 + end + else + lo = mid + 1 + end + end + if best < 0 then + best = 255 + end + quantize(u, best) + plan(u.ix, bounds, p) + if p.bits > budget then -- give up on this granule: silence fits any budget + for i = 1, 576 do + u.ix[i] = 0 + end + plan(u.ix, bounds, p) + end + u.gain = best +end + +type Source = { + sampleRate: number, + channels: number, + frames: number, + read: (self: any, n: number, out: buffer?) -> (buffer, number), + err: any, +} +type Options = { + bitrate: number, + mode: string, + prefix: buffer?, +} + +@native function Encode3.encode(src: Source, opts: Options): (buffer?, string?) + local rate = src.sampleRate + local info = RATES[rate] + if not info then + return nil, "unsupported sample rate" + end + local version, srIndex, group = info[1], info[2], info[3] + local mpeg1 = version == 3 + local granules = if mpeg1 then 2 else 1 + local spf = 576 * granules + local inCh = src.channels + local mode = opts.mode + local nch = if mode == "mono" then 1 else 2 + local kbps = opts.bitrate + local list = if mpeg1 then BITRATES_V1 else BITRATES_V2 + local brIndex = table.find(list, kbps) + if not brIndex then + return nil, "unsupported bit rate" + end + local sideBytes = if mpeg1 then (if nch == 1 then 17 else 32) else (if nch == 1 then 9 else 17) + local slotNum = (if mpeg1 then 144000 else 72000) * kbps -- frame bytes * rate + local bounds = { 0 } + do + local acc = 0 + for k = 0, 21 do + acc += T.g_scf_long[group * 23 + k] + table.insert(bounds, acc) + end + end + local w: W = { buf = buffer.create(65536), pos = 0, acc = 0, cnt = 0 } + if opts.prefix then + local pf = opts.prefix :: buffer + local need = buffer.len(pf) + if need > buffer.len(w.buf) - 16 then + w.buf = buffer.create(need + 65536) + end + buffer.copy(w.buf, 0, pf, 0, need) + w.pos = need + end + local ana = { Analysis.new(), Analysis.new() } + local prev = { table.create(576, 0), table.create(576, 0) } + local cur = { table.create(576, 0), table.create(576, 0) } + local units = {} + for g = 1, 2 do + units[g] = { newUnit(), newUnit() } + end + local pcm = { table.create(spf, 0), table.create(spf, 0) } + local sub = table.create(32, 0) + local z = table.create(36, 0) + local rest = 0 + local tmp: buffer? = nil + local pending: buffer? = nil + local pendN, pendOff = 0, 0 + local srcDone = false + local flushed = false + while true do + local got = 0 + while got < spf and not srcDone do + if pendN == 0 then + local b, n = src:read(4096, tmp) + if n <= 0 then + srcDone = true + break + end + tmp = b + pending, pendN, pendOff = b, n, 0 + end + local take = math.min(spf - got, pendN) + local pb = pending :: buffer + for i = 0, take - 1 do + local base = (pendOff + i) * inCh * 4 + local l = buffer.readf32(pb, base) + local r = if inCh > 1 then buffer.readf32(pb, base + 4) else l + if nch == 1 then + if inCh > 1 then + l = (l + r) * 0.5 + end + pcm[1][got + i + 1] = l + else + pcm[1][got + i + 1] = l + pcm[2][got + i + 1] = r + end + end + got += take + pendN -= take + pendOff += take + end + if got == 0 then + if flushed then + break + end + flushed = true -- one silent frame after the input pushes its tail through the filterbank delay + end + for c = 1, nch do + local s = pcm[c] + for i = got + 1, spf do + s[i] = 0 + end + end + for g = 1, granules do + for c = 1, nch do + local cu, pv = cur[c], prev[c] + local s = pcm[c] + for k = 0, 17 do + Analysis.run(ana[c], s, (g - 1) * 576 + k * 32 + 1, sub, 1) + for sb = 0, 31 do + local v = sub[sb + 1] + if sb % 2 == 1 and k % 2 == 1 then + v = -v -- frequency inversion of the odd subbands + end + cu[sb * 18 + k + 1] = v + end + end + local xr = units[g][c].xr + for sb = 0, 31 do + local o = sb * 18 + for i = 1, 18 do + z[i] = pv[o + i] + z[i + 18] = cu[o + i] + end + for k = 0, 17 do + local acc = 0 + local mb = k * 36 + for i = 1, 36 do + acc += MDCT[mb + i] * z[i] + end + xr[o + k + 1] = acc + end + end + -- alias reduction butterflies (the inverse of the decoder's) + for sb = 1, 31 do + local o = sb * 18 + for i = 0, 7 do + local a, b = xr[o - i], xr[o + i + 1] + xr[o - i] = a * CS[i + 1] + b * CA[i + 1] + xr[o + i + 1] = b * CS[i + 1] - a * CA[i + 1] + end + end + prev[c], cur[c] = cu, pv + end + if mode == "joint" then + local x0, x1 = units[g][1].xr, units[g][2].xr + local r2 = sqrt(0.5) + for i = 1, 576 do + local l, r = x0[i], x1[i] + x0[i], x1[i] = (l + r) * r2, (l - r) * r2 + end + end + end + local frameBytes = slotNum // rate + rest += slotNum % rate + local padding = 0 + if rest >= rate then + rest -= rate + padding = 1 + frameBytes += 1 + end + local avail = (frameBytes - 4 - sideBytes) * 8 + local left = avail + local nUnits = granules * nch + local done = 0 + for g = 1, granules do + for c = 1, nch do + local budget = math.min(4095, left // (nUnits - done)) + local u = units[g][c] + rateLoop(u, budget, bounds) + left -= u.plan.bits + done += 1 + end + end + if w.pos + frameBytes + 64 > buffer.len(w.buf) then + local nb = buffer.create(buffer.len(w.buf) * 2 + frameBytes) + buffer.copy(nb, 0, w.buf, 0, w.pos) + w.buf = nb + end + local start = w.pos + put(w, 0x7FF, 11) + put(w, version, 2) + put(w, 1, 2) -- layer III + put(w, 1, 1) -- no CRC + put(w, brIndex, 4) + put(w, srIndex, 2) + put(w, padding, 1) + put(w, 0, 1) + put(w, if mode == "mono" then 3 elseif mode == "joint" then 1 else 0, 2) + put(w, if mode == "joint" then 2 else 0, 2) -- mode extension: mid / side on, intensity off + put(w, 0, 1) + put(w, 1, 1) -- original + put(w, 0, 2) + if mpeg1 then + put(w, 0, 9) -- main_data_begin + put(w, 0, if nch == 1 then 5 else 3) + for _ = 1, nch do + put(w, 0, 4) -- scfsi + end + else + put(w, 0, 8) + put(w, 0, if nch == 1 then 1 else 2) + end + for g = 1, granules do + for c = 1, nch do + local u = units[g][c] + local p = u.plan + put(w, p.bits, 12) -- part2_3_length (no scalefactor bits) + put(w, p.bigValues, 9) + put(w, u.gain, 8) + put(w, 0, if mpeg1 then 4 else 9) -- scalefac_compress + put(w, 0, 1) -- window switching off + put(w, p.tables[1], 5) + put(w, p.tables[2], 5) + put(w, p.tables[3], 5) + put(w, p.region0, 4) + put(w, p.region1, 3) + if mpeg1 then + put(w, 0, 1) -- preflag + end + put(w, 0, 1) -- scalefac_scale + put(w, p.c1table, 1) + end + end + for g = 1, granules do + for c = 1, nch do + local u = units[g][c] + writeHuffman(w, u.ix, u.sign, u.plan) + end + end + if w.cnt > 0 then + put(w, 0, 8 - w.cnt) + end + -- ancillary padding to the frame size + while w.pos < start + frameBytes do + writeu8(w.buf, w.pos, 0) + w.pos += 1 + end + end + if src.err then + return nil, tostring(src.err) + end + local out = buffer.create(w.pos) + buffer.copy(out, 0, w.buf, 0, w.pos) + return out, nil +end + +return Encode3 +end +__FILES["codecs/audio/Mpa/Header"] = @native function() + + + +-- codecs/audio/Mpa/Header: MPEG audio frame headers and frame sync, after minimp3's hdr_* and mp3d_find_frame / +-- mp3d_match_frame (CC0, licenses/minimp3-CC0.txt). +local T = __include("codecs/audio/Mpa/Tables") + +local band, bxor, rshift = bit32.band, bit32.bxor, bit32.rshift +local ru8 = buffer.readu8 + +local HALFRATE = T.halfrate +local HZ = { [0] = 44100, 48000, 32000 } + +local H = {} + +H.MAX_FREE_FORMAT_FRAME_SIZE = 2304 +H.MAX_FRAME_SYNC_MATCHES = 10 + +-- hdr_valid +@native function H.valid(b: buffer, o: number): boolean + if ru8(b, o) ~= 0xFF then + return false + end + local h1, h2 = ru8(b, o + 1), ru8(b, o + 2) + return (band(h1, 0xF0) == 0xF0 or band(h1, 0xFE) == 0xE2) + and band(rshift(h1, 1), 3) ~= 0 + and rshift(h2, 4) ~= 15 + and band(rshift(h2, 2), 3) ~= 3 +end +local valid = H.valid + +-- hdr_compare +@native function H.compare(b: buffer, o1: number, o2: number): boolean + if not valid(b, o2) then + return false + end + local a1, a2 = ru8(b, o1 + 1), ru8(b, o1 + 2) + local c1, c2 = ru8(b, o2 + 1), ru8(b, o2 + 2) + return band(bxor(a1, c1), 0xFE) == 0 + and band(bxor(a2, c2), 0x0C) == 0 + and (band(a2, 0xF0) == 0) == (band(c2, 0xF0) == 0) +end +local compare = H.compare + +-- from the header bytes h1 = byte 1, h2 = byte 2 +@native function H.bitrateKbps(h1: number, h2: number): number + local mpeg1 = if band(h1, 8) ~= 0 then 1 else 0 + local layer = band(rshift(h1, 1), 3) + return 2 * HALFRATE[mpeg1 * 45 + (layer - 1) * 15 + rshift(h2, 4)] +end +local bitrateKbps = H.bitrateKbps + +@native function H.sampleRate(h1: number, h2: number): number + local hz = HZ[band(rshift(h2, 2), 3)] + if band(h1, 8) == 0 then + hz //= 2 + end + if band(h1, 0x10) == 0 then + hz //= 2 + end + return hz +end +local sampleRate = H.sampleRate + +@native function H.frameSamples(h1: number): number + if band(h1, 6) == 6 then + return 384 + elseif band(h1, 14) == 2 then + return 576 + end + return 1152 +end +local frameSamples = H.frameSamples + +-- hdr_frame_bytes (without padding) +@native function H.frameBytes(b: buffer, o: number, freeSize: number): number + local h1, h2 = ru8(b, o + 1), ru8(b, o + 2) + local hz = sampleRate(h1, h2) + local fb = frameSamples(h1) * bitrateKbps(h1, h2) * 125 // hz + if band(h1, 6) == 6 then + fb = band(fb, 0xFFFFFFFC) + end + return if fb ~= 0 then fb else freeSize +end +local frameBytes = H.frameBytes + +@native function H.padding(b: buffer, o: number): number + if band(ru8(b, o + 2), 2) == 0 then + return 0 + end + return if band(ru8(b, o + 1), 6) == 6 then 4 else 1 +end +local padding = H.padding + +-- mp3d_match_frame: the frames chained after o (n bytes left) keep comparing equal +@native local function matchFrame(b: buffer, o: number, n: number, fb: number): boolean + local i = 0 + for nmatch = 0, H.MAX_FRAME_SYNC_MATCHES - 1 do + i += frameBytes(b, o + i, fb) + padding(b, o + i) + if i + 4 > n then + return nmatch > 0 + end + if not compare(b, o, o + i) then + return false + end + end + return true +end + +-- mp3d_find_frame +@native function H.findFrame(b: buffer, base: number, n: number, ffb: number): (number, number, number) + for i = 0, n - 5 do + local o = base + i + if valid(b, o) then + local fb = frameBytes(b, o, ffb) + local fap = fb + padding(b, o) + local k = 4 + while fb == 0 and k < H.MAX_FREE_FORMAT_FRAME_SIZE and i + 2 * k < n - 4 do + if compare(b, o, o + k) then + local f = k - padding(b, o) + local nextfb = f + padding(b, o + k) + if not (i + k + nextfb + 4 > n or not compare(b, o, o + k + nextfb)) then + fap = k + fb = f + ffb = f + end + end + k += 1 + end + if (fb ~= 0 and i + fap <= n and matchFrame(b, o, n - i, fb)) or (i == 0 and fap == n) then + return i, fap, ffb + end + ffb = 0 + end + end + return n, 0, ffb +end + +return H +end +__FILES["codecs/audio/Mpa/Tables"] = function() + +-- 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, + 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 56, 64, 72, 80, 0, 4, 8, 12, 16, 20, 24, 28, 32, 40, + 48, 56, 64, 72, 80, 0, 16, 24, 28, 32, 40, 48, 56, 64, 72, 80, 88, 96, 112, 128, 0, 16, 20, 24, + 28, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 0, 16, 24, 28, 32, 40, 48, 56, 64, 80, 96, 112, 128, + 160, 192, 0, 16, 32, 48, 64, 80, 96, 112, 128, 144, 160, 176, 192, 208, 224, +} +T.g_bitalloc_code_tab = { [0] = 0, + 17, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 0, 17, 18, 3, 19, 4, 5, 6, 7, + 8, 9, 10, 11, 12, 13, 16, 0, 17, 18, 3, 19, 4, 5, 16, 0, 17, 18, 16, 0, 17, 18, 19, 4, + 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0, 17, 18, 3, 19, 4, 5, 6, 7, 8, 9, 10, 11, + 12, 13, 14, 0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, +} +T.g_scf_long = { [0] = 6, + 6, 6, 6, 6, 6, 8, 10, 12, 14, 16, 20, 24, 28, 32, 38, 46, 52, 60, 68, 58, 54, 0, 12, 12, + 12, 12, 12, 12, 16, 20, 24, 28, 32, 40, 48, 56, 64, 76, 90, 2, 2, 2, 2, 2, 0, 6, 6, 6, + 6, 6, 6, 8, 10, 12, 14, 16, 20, 24, 28, 32, 38, 46, 52, 60, 68, 58, 54, 0, 6, 6, 6, 6, + 6, 6, 8, 10, 12, 14, 16, 18, 22, 26, 32, 38, 46, 54, 62, 70, 76, 36, 0, 6, 6, 6, 6, 6, + 6, 8, 10, 12, 14, 16, 20, 24, 28, 32, 38, 46, 52, 60, 68, 58, 54, 0, 4, 4, 4, 4, 4, 4, + 6, 6, 8, 8, 10, 12, 16, 20, 24, 28, 34, 42, 50, 54, 76, 158, 0, 4, 4, 4, 4, 4, 4, 6, + 6, 6, 8, 10, 12, 16, 18, 22, 28, 34, 40, 46, 54, 54, 192, 0, 4, 4, 4, 4, 4, 4, 6, 6, + 8, 10, 12, 16, 20, 24, 30, 38, 46, 56, 68, 84, 102, 26, 0, +} +T.g_scf_short = { [0] = 4, + 4, 4, 4, 4, 4, 4, 4, 4, 6, 6, 6, 8, 8, 8, 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, + 18, 18, 24, 24, 24, 30, 30, 30, 40, 40, 40, 18, 18, 18, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 12, 12, 12, 16, 16, 16, 20, 20, 20, 24, 24, 24, 28, 28, 28, 36, 36, 36, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 26, 26, 26, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 6, 6, 6, 6, 6, 6, 8, 8, + 8, 10, 10, 10, 14, 14, 14, 18, 18, 18, 26, 26, 26, 32, 32, 32, 42, 42, 42, 18, 18, 18, 0, 4, + 4, 4, 4, 4, 4, 4, 4, 4, 6, 6, 6, 8, 8, 8, 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, + 18, 18, 24, 24, 24, 32, 32, 32, 44, 44, 44, 12, 12, 12, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 6, 6, 6, 8, 8, 8, 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, 18, 18, 24, 24, 24, 30, 30, 30, + 40, 40, 40, 18, 18, 18, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 6, 6, 6, 8, 8, + 8, 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, 18, 18, 22, 22, 22, 30, 30, 30, 56, 56, 56, 0, 4, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 6, 6, 6, 6, 6, 6, 10, 10, 10, 12, 12, 12, 14, + 14, 14, 16, 16, 16, 20, 20, 20, 26, 26, 26, 66, 66, 66, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 6, 6, 6, 8, 8, 8, 12, 12, 12, 16, 16, 16, 20, 20, 20, 26, 26, 26, 34, 34, 34, + 42, 42, 42, 12, 12, 12, 0, +} +T.g_scf_mixed = { [0] = 6, + 6, 6, 6, 6, 6, 6, 6, 6, 8, 8, 8, 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, 18, 18, 24, + 24, 24, 30, 30, 30, 40, 40, 40, 18, 18, 18, 0, 0, 0, 0, 12, 12, 12, 4, 4, 4, 8, 8, 8, + 12, 12, 12, 16, 16, 16, 20, 20, 20, 24, 24, 24, 28, 28, 28, 36, 36, 36, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 26, 26, 26, 0, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 8, 8, 8, 10, 10, + 10, 14, 14, 14, 18, 18, 18, 26, 26, 26, 32, 32, 32, 42, 42, 42, 18, 18, 18, 0, 0, 0, 0, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 8, 8, 8, 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, 18, 18, 24, + 24, 24, 32, 32, 32, 44, 44, 44, 12, 12, 12, 0, 0, 0, 0, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 8, 8, 8, 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, 18, 18, 24, 24, 24, 30, 30, 30, 40, 40, 40, + 18, 18, 18, 0, 0, 0, 0, 4, 4, 4, 4, 4, 4, 6, 6, 4, 4, 4, 6, 6, 6, 8, 8, 8, + 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, 18, 18, 22, 22, 22, 30, 30, 30, 56, 56, 56, 0, 0, 4, + 4, 4, 4, 4, 4, 6, 6, 4, 4, 4, 6, 6, 6, 6, 6, 6, 10, 10, 10, 12, 12, 12, 14, 14, + 14, 16, 16, 16, 20, 20, 20, 26, 26, 26, 66, 66, 66, 0, 0, 4, 4, 4, 4, 4, 4, 6, 6, 4, + 4, 4, 6, 6, 6, 8, 8, 8, 12, 12, 12, 16, 16, 16, 20, 20, 20, 26, 26, 26, 34, 34, 34, 42, + 42, 42, 12, 12, 12, 0, 0, +} +T.g_expfrac = { [0] = 9.31322575e-10, + 7.83145814e-10, 6.58544508e-10, 5.53767716e-10, +} +T.g_scf_partitions = { [0] = 6, + 5, 5, 5, 6, 5, 5, 5, 6, 5, 7, 3, 11, 10, 0, 0, 7, 7, 7, 0, 6, 6, 6, 3, 8, + 8, 5, 0, 8, 9, 6, 12, 6, 9, 9, 9, 6, 9, 12, 6, 15, 18, 0, 0, 6, 15, 12, 0, 6, + 12, 9, 6, 6, 18, 9, 0, 9, 9, 6, 12, 9, 9, 9, 9, 9, 9, 12, 6, 18, 18, 0, 0, 12, + 12, 12, 0, 12, 9, 9, 6, 15, 12, 9, 0, +} +T.g_scfc_decode = { [0] = 0, + 1, 2, 3, 12, 5, 6, 7, 9, 10, 11, 13, 14, 15, 18, 19, +} +T.g_mod = { [0] = 5, + 5, 4, 4, 5, 5, 4, 1, 4, 3, 1, 1, 5, 6, 6, 1, 4, 4, 4, 1, 4, 3, 1, 1, +} +T.g_preamp = { [0] = 1, + 1, 1, 1, 2, 2, 3, 3, 3, 2, +} +T.g_pow43 = { [0] = 0, + -1, -2.519842, -4.326749, -6.349604, -8.549880, -10.902724, -13.390518, -16.000000, -18.720754, -21.544347, -24.463781, -27.473142, -30.567351, -33.741992, -36.993181, 0, 1, 2.519842, 4.326749, 6.349604, 8.549880, 10.902724, 13.390518, 16.000000, + 18.720754, 21.544347, 24.463781, 27.473142, 30.567351, 33.741992, 36.993181, 40.317474, 43.711787, 47.173345, 50.699631, 54.288352, 57.937408, 61.644865, 65.408941, 69.227979, 73.100443, 77.024898, 81.000000, 85.024491, 89.097188, 93.216975, 97.382800, 101.593667, + 105.848633, 110.146801, 114.487321, 118.869381, 123.292209, 127.755065, 132.257246, 136.798076, 141.376907, 145.993119, 150.646117, 155.335327, 160.060199, 164.820202, 169.614826, 174.443577, 179.305980, 184.201575, 189.129918, 194.090580, 199.083145, 204.107210, 209.162385, 214.248292, + 219.364564, 224.510845, 229.686789, 234.892058, 240.126328, 245.389280, 250.680604, 256.000000, 261.347174, 266.721841, 272.123723, 277.552547, 283.008049, 288.489971, 293.998060, 299.532071, 305.091761, 310.676898, 316.287249, 321.922592, 327.582707, 333.267377, 338.976394, 344.709550, + 350.466646, 356.247482, 362.051866, 367.879608, 373.730522, 379.604427, 385.501143, 391.420496, 397.362314, 403.326427, 409.312672, 415.320884, 421.350905, 427.402579, 433.475750, 439.570269, 445.685987, 451.822757, 457.980436, 464.158883, 470.357960, 476.577530, 482.817459, 489.077615, + 495.357868, 501.658090, 507.978156, 514.317941, 520.677324, 527.056184, 533.454404, 539.871867, 546.308458, 552.764065, 559.238575, 565.731879, 572.243870, 578.774440, 585.323483, 591.890898, 598.476581, 605.080431, 611.702349, 618.342238, 625.000000, 631.675540, 638.368763, 645.079578, +} +T.tabs = { [0] = 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 785, 785, 785, 785, 784, 784, 784, 784, 513, 513, 513, 513, 513, 513, 513, 513, 256, + 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, -255, 1313, 1298, 1282, 785, 785, 785, 785, 784, + 784, 784, 784, 769, 769, 769, 769, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 290, + 288, -255, 1313, 1298, 1282, 769, 769, 769, 769, 529, 529, 529, 529, 529, 529, 529, 529, 528, 528, 528, 528, 528, 528, 528, + 528, 512, 512, 512, 512, 512, 512, 512, 512, 290, 288, -253, -318, -351, -367, 785, 785, 785, 785, 784, 784, 784, 784, 769, + 769, 769, 769, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 819, 818, 547, 547, 275, + 275, 275, 275, 561, 560, 515, 546, 289, 274, 288, 258, -254, -287, 1329, 1299, 1314, 1312, 1057, 1057, 1042, 1042, 1026, 1026, 784, + 784, 784, 784, 529, 529, 529, 529, 529, 529, 529, 529, 769, 769, 769, 769, 768, 768, 768, 768, 563, 560, 306, 306, 291, + 259, -252, -413, -477, -542, 1298, -575, 1041, 1041, 784, 784, 784, 784, 769, 769, 769, 769, 256, 256, 256, 256, 256, 256, 256, + 256, 256, 256, 256, 256, 256, 256, 256, 256, -383, -399, 1107, 1092, 1106, 1061, 849, 849, 789, 789, 1104, 1091, 773, 773, 1076, + 1075, 341, 340, 325, 309, 834, 804, 577, 577, 532, 532, 516, 516, 832, 818, 803, 816, 561, 561, 531, 531, 515, 546, 289, + 289, 288, 258, -252, -429, -493, -559, 1057, 1057, 1042, 1042, 529, 529, 529, 529, 529, 529, 529, 529, 784, 784, 784, 784, 769, + 769, 769, 769, 512, 512, 512, 512, 512, 512, 512, 512, -382, 1077, -415, 1106, 1061, 1104, 849, 849, 789, 789, 1091, 1076, 1029, + 1075, 834, 834, 597, 581, 340, 340, 339, 324, 804, 833, 532, 532, 832, 772, 818, 803, 817, 787, 816, 771, 290, 290, 290, + 290, 288, 258, -253, -349, -414, -447, -463, 1329, 1299, -479, 1314, 1312, 1057, 1057, 1042, 1042, 1026, 1026, 785, 785, 785, 785, 784, + 784, 784, 784, 769, 769, 769, 769, 768, 768, 768, 768, -319, 851, 821, -335, 836, 850, 805, 849, 341, 340, 325, 336, 533, + 533, 579, 579, 564, 564, 773, 832, 578, 548, 563, 516, 321, 276, 306, 291, 304, 259, -251, -572, -733, -830, -863, -879, 1041, + 1041, 784, 784, 784, 784, 769, 769, 769, 769, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, + 256, -511, -527, -543, 1396, 1351, 1381, 1366, 1395, 1335, 1380, -559, 1334, 1138, 1138, 1063, 1063, 1350, 1392, 1031, 1031, 1062, 1062, 1364, + 1363, 1120, 1120, 1333, 1348, 881, 881, 881, 881, 375, 374, 359, 373, 343, 358, 341, 325, 791, 791, 1123, 1122, -703, 1105, 1045, + -719, 865, 865, 790, 790, 774, 774, 1104, 1029, 338, 293, 323, 308, -799, -815, 833, 788, 772, 818, 803, 816, 322, 292, 307, + 320, 561, 531, 515, 546, 289, 274, 288, 258, -251, -525, -605, -685, -765, -831, -846, 1298, 1057, 1057, 1312, 1282, 785, 785, 785, + 785, 784, 784, 784, 784, 769, 769, 769, 769, 512, 512, 512, 512, 512, 512, 512, 512, 1399, 1398, 1383, 1367, 1382, 1396, 1351, + -511, 1381, 1366, 1139, 1139, 1079, 1079, 1124, 1124, 1364, 1349, 1363, 1333, 882, 882, 882, 882, 807, 807, 807, 807, 1094, 1094, 1136, + 1136, 373, 341, 535, 535, 881, 775, 867, 822, 774, -591, 324, 338, -671, 849, 550, 550, 866, 864, 609, 609, 293, 336, 534, + 534, 789, 835, 773, -751, 834, 804, 308, 307, 833, 788, 832, 772, 562, 562, 547, 547, 305, 275, 560, 515, 290, 290, -252, + -397, -477, -557, -622, -653, -719, -735, -750, 1329, 1299, 1314, 1057, 1057, 1042, 1042, 1312, 1282, 1024, 1024, 785, 785, 785, 785, 784, + 784, 784, 784, 769, 769, 769, 769, -383, 1127, 1141, 1111, 1126, 1140, 1095, 1110, 869, 869, 883, 883, 1079, 1109, 882, 882, 375, + 374, 807, 868, 838, 881, 791, -463, 867, 822, 368, 263, 852, 837, 836, -543, 610, 610, 550, 550, 352, 336, 534, 534, 865, + 774, 851, 821, 850, 805, 593, 533, 579, 564, 773, 832, 578, 578, 548, 548, 577, 577, 307, 276, 306, 291, 516, 560, 259, + 259, -250, -2107, -2507, -2764, -2909, -2974, -3007, -3023, 1041, 1041, 1040, 1040, 769, 769, 769, 769, 256, 256, 256, 256, 256, 256, 256, + 256, 256, 256, 256, 256, 256, 256, 256, 256, -767, -1052, -1213, -1277, -1358, -1405, -1469, -1535, -1550, -1582, -1614, -1647, -1662, -1694, -1726, + -1759, -1774, -1807, -1822, -1854, -1886, 1565, -1919, -1935, -1951, -1967, 1731, 1730, 1580, 1717, -1983, 1729, 1564, -1999, 1548, -2015, -2031, 1715, 1595, + -2047, 1714, -2063, 1610, -2079, 1609, -2095, 1323, 1323, 1457, 1457, 1307, 1307, 1712, 1547, 1641, 1700, 1699, 1594, 1685, 1625, 1442, 1442, 1322, + 1322, -780, -973, -910, 1279, 1278, 1277, 1262, 1276, 1261, 1275, 1215, 1260, 1229, -959, 974, 974, 989, 989, -943, 735, 478, 478, 495, + 463, 506, 414, -1039, 1003, 958, 1017, 927, 942, 987, 957, 431, 476, 1272, 1167, 1228, -1183, 1256, -1199, 895, 895, 941, 941, 1242, + 1227, 1212, 1135, 1014, 1014, 490, 489, 503, 487, 910, 1013, 985, 925, 863, 894, 970, 955, 1012, 847, -1343, 831, 755, 755, 984, + 909, 428, 366, 754, 559, -1391, 752, 486, 457, 924, 997, 698, 698, 983, 893, 740, 740, 908, 877, 739, 739, 667, 667, 953, + 938, 497, 287, 271, 271, 683, 606, 590, 712, 726, 574, 302, 302, 738, 736, 481, 286, 526, 725, 605, 711, 636, 724, 696, + 651, 589, 681, 666, 710, 364, 467, 573, 695, 466, 466, 301, 465, 379, 379, 709, 604, 665, 679, 316, 316, 634, 633, 436, + 436, 464, 269, 424, 394, 452, 332, 438, 363, 347, 408, 393, 448, 331, 422, 362, 407, 392, 421, 346, 406, 391, 376, 375, + 359, 1441, 1306, -2367, 1290, -2383, 1337, -2399, -2415, 1426, 1321, -2431, 1411, 1336, -2447, -2463, -2479, 1169, 1169, 1049, 1049, 1424, 1289, 1412, + 1352, 1319, -2495, 1154, 1154, 1064, 1064, 1153, 1153, 416, 390, 360, 404, 403, 389, 344, 374, 373, 343, 358, 372, 327, 357, 342, + 311, 356, 326, 1395, 1394, 1137, 1137, 1047, 1047, 1365, 1392, 1287, 1379, 1334, 1364, 1349, 1378, 1318, 1363, 792, 792, 792, 792, 1152, + 1152, 1032, 1032, 1121, 1121, 1046, 1046, 1120, 1120, 1030, 1030, -2895, 1106, 1061, 1104, 849, 849, 789, 789, 1091, 1076, 1029, 1090, 1060, + 1075, 833, 833, 309, 324, 532, 532, 832, 772, 818, 803, 561, 561, 531, 560, 515, 546, 289, 274, 288, 258, -250, -1179, -1579, + -1836, -1996, -2124, -2253, -2333, -2413, -2477, -2542, -2574, -2607, -2622, -2655, 1314, 1313, 1298, 1312, 1282, 785, 785, 785, 785, 1040, 1040, 1025, + 1025, 768, 768, 768, 768, -766, -798, -830, -862, -895, -911, -927, -943, -959, -975, -991, -1007, -1023, -1039, -1055, -1070, 1724, 1647, -1103, + -1119, 1631, 1767, 1662, 1738, 1708, 1723, -1135, 1780, 1615, 1779, 1599, 1677, 1646, 1778, 1583, -1151, 1777, 1567, 1737, 1692, 1765, 1722, 1707, + 1630, 1751, 1661, 1764, 1614, 1736, 1676, 1763, 1750, 1645, 1598, 1721, 1691, 1762, 1706, 1582, 1761, 1566, -1167, 1749, 1629, 767, 766, 751, + 765, 494, 494, 735, 764, 719, 749, 734, 763, 447, 447, 748, 718, 477, 506, 431, 491, 446, 476, 461, 505, 415, 430, 475, + 445, 504, 399, 460, 489, 414, 503, 383, 474, 429, 459, 502, 502, 746, 752, 488, 398, 501, 473, 413, 472, 486, 271, 480, + 270, -1439, -1455, 1357, -1471, -1487, -1503, 1341, 1325, -1519, 1489, 1463, 1403, 1309, -1535, 1372, 1448, 1418, 1476, 1356, 1462, 1387, -1551, 1475, + 1340, 1447, 1402, 1386, -1567, 1068, 1068, 1474, 1461, 455, 380, 468, 440, 395, 425, 410, 454, 364, 467, 466, 464, 453, 269, 409, + 448, 268, 432, 1371, 1473, 1432, 1417, 1308, 1460, 1355, 1446, 1459, 1431, 1083, 1083, 1401, 1416, 1458, 1445, 1067, 1067, 1370, 1457, 1051, + 1051, 1291, 1430, 1385, 1444, 1354, 1415, 1400, 1443, 1082, 1082, 1173, 1113, 1186, 1066, 1185, 1050, -1967, 1158, 1128, 1172, 1097, 1171, 1081, + -1983, 1157, 1112, 416, 266, 375, 400, 1170, 1142, 1127, 1065, 793, 793, 1169, 1033, 1156, 1096, 1141, 1111, 1155, 1080, 1126, 1140, 898, + 898, 808, 808, 897, 897, 792, 792, 1095, 1152, 1032, 1125, 1110, 1139, 1079, 1124, 882, 807, 838, 881, 853, 791, -2319, 867, 368, + 263, 822, 852, 837, 866, 806, 865, -2399, 851, 352, 262, 534, 534, 821, 836, 594, 594, 549, 549, 593, 593, 533, 533, 848, + 773, 579, 579, 564, 578, 548, 563, 276, 276, 577, 576, 306, 291, 516, 560, 305, 305, 275, 259, -251, -892, -2058, -2620, -2828, + -2957, -3023, -3039, 1041, 1041, 1040, 1040, 769, 769, 769, 769, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, + 256, 256, 256, -511, -527, -543, -559, 1530, -575, -591, 1528, 1527, 1407, 1526, 1391, 1023, 1023, 1023, 1023, 1525, 1375, 1268, 1268, 1103, + 1103, 1087, 1087, 1039, 1039, 1523, -604, 815, 815, 815, 815, 510, 495, 509, 479, 508, 463, 507, 447, 431, 505, 415, 399, -734, + -782, 1262, -815, 1259, 1244, -831, 1258, 1228, -847, -863, 1196, -879, 1253, 987, 987, 748, -767, 493, 493, 462, 477, 414, 414, 686, + 669, 478, 446, 461, 445, 474, 429, 487, 458, 412, 471, 1266, 1264, 1009, 1009, 799, 799, -1019, -1276, -1452, -1581, -1677, -1757, -1821, + -1886, -1933, -1997, 1257, 1257, 1483, 1468, 1512, 1422, 1497, 1406, 1467, 1496, 1421, 1510, 1134, 1134, 1225, 1225, 1466, 1451, 1374, 1405, 1252, + 1252, 1358, 1480, 1164, 1164, 1251, 1251, 1238, 1238, 1389, 1465, -1407, 1054, 1101, -1423, 1207, -1439, 830, 830, 1248, 1038, 1237, 1117, 1223, + 1148, 1236, 1208, 411, 426, 395, 410, 379, 269, 1193, 1222, 1132, 1235, 1221, 1116, 976, 976, 1192, 1162, 1177, 1220, 1131, 1191, 963, + 963, -1647, 961, 780, -1663, 558, 558, 994, 993, 437, 408, 393, 407, 829, 978, 813, 797, 947, -1743, 721, 721, 377, 392, 844, + 950, 828, 890, 706, 706, 812, 859, 796, 960, 948, 843, 934, 874, 571, 571, -1919, 690, 555, 689, 421, 346, 539, 539, 944, + 779, 918, 873, 932, 842, 903, 888, 570, 570, 931, 917, 674, 674, -2575, 1562, -2591, 1609, -2607, 1654, 1322, 1322, 1441, 1441, 1696, + 1546, 1683, 1593, 1669, 1624, 1426, 1426, 1321, 1321, 1639, 1680, 1425, 1425, 1305, 1305, 1545, 1668, 1608, 1623, 1667, 1592, 1638, 1666, 1320, + 1320, 1652, 1607, 1409, 1409, 1304, 1304, 1288, 1288, 1664, 1637, 1395, 1395, 1335, 1335, 1622, 1636, 1394, 1394, 1319, 1319, 1606, 1621, 1392, + 1392, 1137, 1137, 1137, 1137, 345, 390, 360, 375, 404, 373, 1047, -2751, -2767, -2783, 1062, 1121, 1046, -2799, 1077, -2815, 1106, 1061, 789, + 789, 1105, 1104, 263, 355, 310, 340, 325, 354, 352, 262, 339, 324, 1091, 1076, 1029, 1090, 1060, 1075, 833, 833, 788, 788, 1088, + 1028, 818, 818, 803, 803, 561, 561, 531, 531, 816, 771, 546, 546, 289, 274, 288, 258, -253, -317, -381, -446, -478, -509, 1279, + 1279, -811, -1179, -1451, -1756, -1900, -2028, -2189, -2253, -2333, -2414, -2445, -2511, -2526, 1313, 1298, -2559, 1041, 1041, 1040, 1040, 1025, 1025, 1024, + 1024, 1022, 1007, 1021, 991, 1020, 975, 1019, 959, 687, 687, 1018, 1017, 671, 671, 655, 655, 1016, 1015, 639, 639, 758, 758, 623, + 623, 757, 607, 756, 591, 755, 575, 754, 559, 543, 543, 1009, 783, -575, -621, -685, -749, 496, -590, 750, 749, 734, 748, 974, + 989, 1003, 958, 988, 973, 1002, 942, 987, 957, 972, 1001, 926, 986, 941, 971, 956, 1000, 910, 985, 925, 999, 894, 970, -1071, + -1087, -1102, 1390, -1135, 1436, 1509, 1451, 1374, -1151, 1405, 1358, 1480, 1420, -1167, 1507, 1494, 1389, 1342, 1465, 1435, 1450, 1326, 1505, 1310, + 1493, 1373, 1479, 1404, 1492, 1464, 1419, 428, 443, 472, 397, 736, 526, 464, 464, 486, 457, 442, 471, 484, 482, 1357, 1449, 1434, + 1478, 1388, 1491, 1341, 1490, 1325, 1489, 1463, 1403, 1309, 1477, 1372, 1448, 1418, 1433, 1476, 1356, 1462, 1387, -1439, 1475, 1340, 1447, 1402, + 1474, 1324, 1461, 1371, 1473, 269, 448, 1432, 1417, 1308, 1460, -1711, 1459, -1727, 1441, 1099, 1099, 1446, 1386, 1431, 1401, -1743, 1289, 1083, + 1083, 1160, 1160, 1458, 1445, 1067, 1067, 1370, 1457, 1307, 1430, 1129, 1129, 1098, 1098, 268, 432, 267, 416, 266, 400, -1887, 1144, 1187, + 1082, 1173, 1113, 1186, 1066, 1050, 1158, 1128, 1143, 1172, 1097, 1171, 1081, 420, 391, 1157, 1112, 1170, 1142, 1127, 1065, 1169, 1049, 1156, + 1096, 1141, 1111, 1155, 1080, 1126, 1154, 1064, 1153, 1140, 1095, 1048, -2159, 1125, 1110, 1137, -2175, 823, 823, 1139, 1138, 807, 807, 384, + 264, 368, 263, 868, 838, 853, 791, 867, 822, 852, 837, 866, 806, 865, 790, -2319, 851, 821, 836, 352, 262, 850, 805, 849, + -2399, 533, 533, 835, 820, 336, 261, 578, 548, 563, 577, 532, 532, 832, 772, 562, 562, 547, 547, 305, 275, 560, 515, 290, + 290, 288, 258, +} +T.tab32 = { [0] = 130, + 162, 193, 209, 44, 28, 76, 140, 9, 9, 9, 9, 9, 9, 9, 9, 190, 254, 222, 238, 126, 94, 157, 157, 109, + 61, 173, 205, +} +T.tab33 = { [0] = 252, + 236, 220, 204, 188, 172, 156, 140, 124, 108, 92, 76, 60, 44, 28, 12, +} +T.tabindex = { [0] = 0, + 32, 64, 98, 0, 132, 180, 218, 292, 364, 426, 538, 648, 746, 0, 1126, 1460, 1460, 1460, 1460, 1460, 1460, 1460, 1460, 1842, + 1842, 1842, 1842, 1842, 1842, 1842, 1842, +} +T.g_linbits = { [0] = 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 8, 10, 13, 4, + 5, 6, 7, 8, 9, 11, 13, +} +T.g_pan = { [0] = 0, + 1, 0.21132487, 0.78867513, 0.36602540, 0.63397460, 0.5, 0.5, 0.63397460, 0.36602540, 0.78867513, 0.21132487, 1, 0, +} +T.g_aa = { [0] = 0.85749293, + 0.88174200, 0.94962865, 0.98331459, 0.99551782, 0.99916056, 0.99989920, 0.99999316, 0.51449576, 0.47173197, 0.31337745, 0.18191320, 0.09457419, 0.04096558, 0.01419856, 0.00369997, +} +T.g_twid9 = { [0] = 0.73727734, + 0.79335334, 0.84339145, 0.88701083, 0.92387953, 0.95371695, 0.97629601, 0.99144486, 0.99904822, 0.67559021, 0.60876143, 0.53729961, 0.46174861, 0.38268343, 0.30070580, 0.21643961, 0.13052619, 0.04361938, +} +T.g_twid3 = { [0] = 0.79335334, + 0.92387953, 0.99144486, 0.60876143, 0.38268343, 0.13052619, +} +T.g_mdct_window = { [0] = 0.99904822, + 0.99144486, 0.97629601, 0.95371695, 0.92387953, 0.88701083, 0.84339145, 0.79335334, 0.73727734, 0.04361938, 0.13052619, 0.21643961, 0.30070580, 0.38268343, 0.46174861, 0.53729961, 0.60876143, 0.67559021, 1, 1, 1, 1, 1, 1, 0.99144486, + 0.92387953, 0.79335334, 0, 0, 0, 0, 0, 0, 0.13052619, 0.38268343, 0.60876143, +} +T.g_sec = { [0] = 10.19000816, + 0.50060302, 0.50241929, 3.40760851, 0.50547093, 0.52249861, 2.05778098, 0.51544732, 0.56694406, 1.48416460, 0.53104258, 0.64682180, 1.16943991, 0.55310392, 0.78815460, 0.97256821, 0.58293498, 1.06067765, 0.83934963, 0.62250412, 1.72244716, 0.74453628, 0.67480832, 5.10114861, +} +T.g_win = { [0] = -1, + 26, -31, 208, 218, 401, -519, 2063, 2000, 4788, -5517, 7134, 5959, 35640, -39336, 74992, -1, 24, -35, 202, 222, 347, -581, 2080, 1952, + 4425, -5879, 7640, 5288, 33791, -41176, 74856, -1, 21, -38, 196, 225, 294, -645, 2087, 1893, 4063, -6237, 8092, 4561, 31947, -43006, 74630, -1, + 19, -41, 190, 227, 244, -711, 2085, 1822, 3705, -6589, 8492, 3776, 30112, -44821, 74313, -1, 17, -45, 183, 228, 197, -779, 2075, 1739, + 3351, -6935, 8840, 2935, 28289, -46617, 73908, -1, 16, -49, 176, 228, 153, -848, 2057, 1644, 3004, -7271, 9139, 2037, 26482, -48390, 73415, -2, + 14, -53, 169, 227, 111, -919, 2032, 1535, 2663, -7597, 9389, 1082, 24694, -50137, 72835, -2, 13, -58, 161, 224, 72, -991, 2001, 1414, + 2330, -7910, 9592, 70, 22929, -51853, 72169, -2, 11, -63, 154, 221, 36, -1064, 1962, 1280, 2006, -8209, 9750, -998, 21189, -53534, 71420, -2, + 10, -68, 147, 215, 2, -1137, 1919, 1131, 1692, -8491, 9863, -2122, 19478, -55178, 70590, -3, 9, -73, 139, 208, -29, -1210, 1870, 970, + 1388, -8755, 9935, -3300, 17799, -56778, 69679, -3, 8, -79, 132, 200, -57, -1283, 1817, 794, 1095, -8998, 9966, -4533, 16155, -58333, 68692, -4, + 7, -85, 125, 189, -83, -1356, 1759, 605, 814, -9219, 9959, -5818, 14548, -59838, 67629, -4, 7, -91, 117, 177, -106, -1428, 1698, 402, + 545, -9416, 9916, -7154, 12980, -61289, 66494, -5, 6, -97, 111, 163, -127, -1498, 1634, 185, 288, -9585, 9838, -8540, 11455, -62684, 65290, +} +return T +end +end + + + + + + Opus + --!optimize 2 +--!nocheck +-- rosetta chunk Opus (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 9 modules (6 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["codecs/audio/Opus"] = function() + +-- codecs/audio/Opus: the Opus codec (RFC 6716) without its container. +-- A port of the libopus 1.6 decoder (BSD, licenses/libopus-BSD.txt), absorbed from opus-luau dd2b4e5; the CELT encoder is new. +local Opus = { + Packet = __include("codecs/audio/Opus/Packet"), + Decoder = __include("codecs/audio/Opus/Decoder"), + Celt = __include("codecs/audio/Opus/Celt"), + Silk = __include("codecs/audio/Opus/Silk"), + CeltEncoder = __include("codecs/audio/Opus/CeltEncoder"), +} + +return Opus +end +__FILES["codecs/audio/Opus/Celt"] = @native function() + + + +-- codecs/audio/Opus/Celt: CELT decoder (RFC 6716 section 4.3), 48 kHz / 960-sample mode, noise-based PLC only. +-- A port of the libopus float decoder (celt_decoder.c, bands.c, vq.c, cwrs.c, rate.c, quant_bands.c, laplace.c, celt.c; +-- BSD, licenses/libopus-BSD.txt). The C code's band pointers are 0-based offsets into one table W. +local RD = __include("codecs/entropy/RangeCoder/Decoder") +local Mdct = __include("codecs/audio/Opus/Mdct") +local T = __include("codecs/audio/Opus/CeltTables") + +local Celt = {} + +local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift +local min, max, sqrt, floor, exp, cos = math.min, math.max, math.sqrt, math.floor, math.exp, math.cos +local decBitLogp, decIcdf, decBits, decUint = RD.bitLogp, RD.icdf, RD.bits, RD.uint +local decDecode, decDecodeBin, decUpdate = RD.decode, RD.decodeBin, RD.update +local tell, tellFrac = RD.tell, RD.tellFrac + +local NB_EBANDS = 21 +local EFF_EBANDS = 21 +local OVERLAP = 120 +local SHORT_MDCT = 120 +local MAX_LM = 3 +local DECODE_BUFFER_SIZE = 2048 +local BITRES = 3 +local MAX_FINE_BITS = 8 +local FINE_OFFSET = 21 +local QTHETA_OFFSET = 4 +local QTHETA_OFFSET_TWOPHASE = 16 +local SPREAD_AGGRESSIVE = 3 +local PREEMPH = 0.85000610 +local COMBFILTER_MINPERIOD = 15 +local FRAME_NONE, FRAME_NORMAL, FRAME_PLC_NOISE = 0, 1, 2 + +-- eBands (1-based: EB[i + 1] is eBands[i]) +local EB = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 34, 40, 48, 60, 78, 100 } +local ALLOC = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 90, 80, 75, 69, 63, 56, 49, 40, 34, 29, 20, 18, 10, 0, 0, 0, 0, 0, 0, 0, 0, + 110, 100, 90, 84, 78, 71, 65, 58, 51, 45, 39, 32, 26, 20, 12, 0, 0, 0, 0, 0, 0, + 118, 110, 103, 93, 86, 80, 75, 70, 65, 59, 53, 47, 40, 31, 23, 15, 4, 0, 0, 0, 0, + 126, 119, 112, 104, 95, 89, 83, 78, 72, 66, 60, 54, 47, 39, 32, 25, 17, 12, 1, 0, 0, + 134, 127, 120, 114, 103, 97, 91, 85, 78, 72, 66, 60, 54, 47, 41, 35, 29, 23, 16, 10, 1, + 144, 137, 130, 124, 113, 107, 101, 95, 88, 82, 76, 70, 64, 57, 51, 45, 39, 33, 26, 15, 1, + 152, 145, 138, 132, 123, 117, 111, 105, 98, 92, 86, 80, 74, 67, 61, 55, 49, 43, 36, 20, 1, + 162, 155, 148, 142, 133, 127, 121, 115, 108, 102, 96, 90, 84, 77, 71, 65, 59, 53, 46, 30, 1, + 172, 165, 158, 152, 143, 137, 131, 125, 118, 112, 106, 100, 94, 87, 81, 75, 69, 63, 56, 45, 20, + 200, 200, 200, 200, 200, 200, 200, 200, 198, 193, 188, 183, 178, 173, 168, 163, 158, 153, 148, 129, 104, +} +local NB_ALLOC_VECTORS = 11 +local LOG2_FRAC_TABLE = { 0, 8, 13, 16, 19, 21, 23, 24, 26, 27, 28, 29, 30, 31, 32, 32, 33, 34, 34, 35, 36, 36, 37, 37 } +local LOGN = T.logN400 +local CACHE_INDEX = T.cache_index50 +local CACHE_BITS = T.cache_bits50 +local CACHE_CAPS = T.cache_caps50 +local E_PROB = T.e_prob_model +local E_MEANS = { + 6.437500, 6.250000, 5.750000, 5.312500, 5.062500, 4.812500, 4.500000, 4.375000, 4.875000, 4.687500, + 4.562500, 4.437500, 4.875000, 4.625000, 4.312500, 4.500000, 4.375000, 4.625000, 4.750000, 4.437500, + 3.750000, 3.750000, 3.750000, 3.750000, 3.750000, +} +local PRED_COEF = { 29440 / 32768, 26112 / 32768, 21248 / 32768, 16384 / 32768 } +local BETA_COEF = { 30147 / 32768, 22282 / 32768, 12124 / 32768, 6554 / 32768 } +local BETA_INTRA = 4915 / 32768 +local TF_SELECT = { -- [LM][4 * isTransient + 2 * tf_select + flag] + { 0, -1, 0, -1, 0, -1, 0, -1 }, + { 0, -1, 0, -2, 1, 0, 1, -1 }, + { 0, -2, 0, -3, 2, 0, 1, -1 }, + { 0, -2, 0, -3, 3, 0, 1, -1 }, +} +local TRIM_ICDF = { 126, 124, 119, 109, 87, 41, 19, 9, 4, 2, 0 } +local SPREAD_ICDF = { 25, 23, 2, 0 } +local TAPSET_ICDF = { 2, 1, 0 } +local SMALL_ENERGY_ICDF = { 2, 1, 0 } +local EXP2_TABLE8 = { 16384, 17866, 19483, 21247, 23170, 25267, 27554, 30048 } +local ORDERY = { 1, 0, 3, 0, 2, 1, 7, 0, 4, 3, 6, 1, 5, 2, 15, 0, 8, 7, 12, 3, 11, 4, 14, 1, 9, 6, 13, 2, 10, 5 } +local BIT_INTERLEAVE = { 0, 1, 1, 1, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3 } +local BIT_DEINTERLEAVE = { 0x00, 0x03, 0x0C, 0x0F, 0x30, 0x33, 0x3C, 0x3F, 0xC0, 0xC3, 0xCC, 0xCF, 0xF0, 0xF3, 0xFC, 0xFF } +local COMB_GAINS = { + { 0.3066406250, 0.2170410156, 0.1296386719 }, + { 0.4638671875, 0.2680664062, 0.0 }, + { 0.7998046875, 0.1000976562, 0.0 }, +} + +local WINDOW = table.create(OVERLAP, 0) +for i = 0, OVERLAP - 1 do + local s = math.sin(0.5 * math.pi * (i + 0.5) / OVERLAP) + WINDOW[i + 1] = math.sin(0.5 * math.pi * s * s) +end +Celt.window = WINDOW + +-- PVQ codebook sizes U(n, k) (cwrs.c), flat: U[n * UK + k + 1], n, k in 0 .. 176 +local UK = 177 +local U = table.create(UK * UK, 0) +U[1] = 1 +for n = 1, UK - 1 do + for k = 1, UK - 1 do + U[n * UK + k + 1] = U[(n - 1) * UK + k + 1] + U[n * UK + k] + U[(n - 1) * UK + k] + end +end + +local NORM_BASE = 1920 +local W = table.create(4096, 0) +local TMP = table.create(256, 0) +local IY = table.create(256, 0) +local FREQ = table.create(960, 0) +local FREQ2 = table.create(960, 0) +local COLLAPSE = table.create(42, 0) +local TF_RES = table.create(21, 0) +local CAP = table.create(21, 0) +local OFFSETS = table.create(21, 0) +local FINE_QUANT = table.create(21, 0) +local PULSES = table.create(21, 0) +local FINE_PRIORITY = table.create(21, 0) +local BITS1 = table.create(21, 0) +local BITS2 = table.create(21, 0) +local THRESH = table.create(21, 0) +local TRIM_OFFSET = table.create(21, 0) + +@native local function imin(a: number, b: number): number + return if a < b then a else b +end +@native local function imax(a: number, b: number): number + return if a > b then a else b +end +-- C integer division (truncates toward zero) +@native local function tdiv(a: number, b: number): number + local q = a / b + return if q >= 0 then floor(q) else -floor(-q) +end + +@native local function exp2(x: number): number + return exp(0.6931471805599453094 * x) +end + +@native local function lcg(seed: number): number + return (1664525 * seed + 1013904223) % 4294967296 +end + +@native local function signed32(x: number): number + return if x >= 2147483648 then x - 4294967296 else x +end + +@native local function fracMul16(a: number, b: number): number + return (16384 + a * b) // 32768 +end + +@native local function bitexactCos(x: number): number + local tmp = (4096 + x * x) // 8192 + local x2 = tmp + x2 = (32767 - x2) + fracMul16(x2, (-7651 + fracMul16(x2, (8277 + fracMul16(-626, x2))))) + return 1 + x2 +end + +@native local function bitexactLog2tan(isin: number, icos: number): number + local lc = RD.ilog(icos) + local ls = RD.ilog(isin) + icos = icos * 2 ^ (15 - lc) + isin = isin * 2 ^ (15 - ls) + return (ls - lc) * 2048 + fracMul16(isin, fracMul16(isin, -2597) + 7932) - fracMul16(icos, fracMul16(icos, -2597) + 7932) +end + +-- energy (quant_bands.c, laplace.c) + +@native local function laplaceDecode(dec: RD.Dec, fs: number, decay: number): number + local val = 0 + local fm = decDecodeBin(dec, 15) + local fl = 0 + if fm >= fs then + val += 1 + fl = fs + fs = ((32768 - 32 - fs) * (16384 - decay)) // 32768 + 1 + while fs > 1 and fm >= fl + 2 * fs do + fs *= 2 + fl += fs + fs = ((fs - 2) * decay) // 32768 + fs += 1 + val += 1 + end + if fs <= 1 then + local di = rshift(fm - fl, 1) + val += di + fl += 2 * di + end + if fm < fl + fs then + val = -val + else + fl += fs + end + end + decUpdate(dec, fl, imin(fl + fs, 32768), 32768) + return val +end + +@native local function unquantCoarseEnergy(st: any, start: number, endb: number, intra: boolean, dec: RD.Dec, C: number, LM: number) + local oldE = st.oldBandE + local probBase = LM * 84 + (if intra then 42 else 0) -- e_prob_model[LM][intra], 0-based + local coef, beta + if intra then + coef = 0 + beta = BETA_INTRA + else + beta = BETA_COEF[LM + 1] + coef = PRED_COEF[LM + 1] + end + local prev0, prev1 = 0, 0 + local budget = dec.storage * 8 + for i = start, endb - 1 do + for c = 0, C - 1 do + local t = tell(dec) + local qi + if budget - t >= 15 then + local pi = 2 * imin(i, 20) + qi = laplaceDecode(dec, E_PROB[probBase + pi + 1] * 128, E_PROB[probBase + pi + 2] * 64) + elseif budget - t >= 2 then + qi = decIcdf(dec, SMALL_ENERGY_ICDF, 1, 2) + qi = if band(qi, 1) ~= 0 then -rshift(qi, 1) - 1 else rshift(qi, 1) + elseif budget - t >= 1 then + qi = if decBitLogp(dec, 1) then -1 else 0 + else + qi = -1 + end + local q = qi + local k = i + c * NB_EBANDS + 1 + local e = max(-9, oldE[k]) + local prev = if c == 0 then prev0 else prev1 + oldE[k] = coef * e + prev + q + prev = prev + q - beta * q + if c == 0 then + prev0 = prev + else + prev1 = prev + end + end + end +end + +@native local function unquantFineEnergy(st: any, start: number, endb: number, fineQuant: { number }, dec: RD.Dec, C: number) + local oldE = st.oldBandE + for i = start, endb - 1 do + local extra = fineQuant[i + 1] + if extra <= 0 then + continue + end + if tell(dec) + C * extra > dec.storage * 8 then + continue + end + for c = 0, C - 1 do + local q2 = decBits(dec, extra) + local offset = (q2 + 0.5) * 2 ^ (14 - extra) * (1 / 16384) - 0.5 + oldE[i + c * NB_EBANDS + 1] += offset + end + end +end + +@native local function unquantEnergyFinalise(st: any, start: number, endb: number, fineQuant: { number }, finePriority: { number }, bitsLeft: number, dec: RD.Dec, C: number) + local oldE = st.oldBandE + for prio = 0, 1 do + local i = start + while i < endb and bitsLeft >= C do + if fineQuant[i + 1] >= MAX_FINE_BITS or finePriority[i + 1] ~= prio then + i += 1 + continue + end + for c = 0, C - 1 do + local q2 = decBits(dec, 1) + local offset = (q2 - 0.5) * 2 ^ (14 - fineQuant[i + 1] - 1) * (1 / 16384) + oldE[i + c * NB_EBANDS + 1] += offset + bitsLeft -= 1 + end + i += 1 + end + end +end + +-- bit allocation (rate.c) + +@native local function bits2pulses(bandI: number, LM: number, bits: number): number + local base = CACHE_INDEX[(LM + 1) * NB_EBANDS + bandI + 1] + local lo, hi = 0, CACHE_BITS[base + 1] + bits -= 1 + for _ = 1, 6 do + local mid = rshift(lo + hi + 1, 1) + if CACHE_BITS[base + mid + 1] >= bits then + hi = mid + else + lo = mid + end + end + local loBits = if lo == 0 then -1 else CACHE_BITS[base + lo + 1] + if bits - loBits <= CACHE_BITS[base + hi + 1] - bits then + return lo + end + return hi +end + +@native local function pulses2bits(bandI: number, LM: number, pulses: number): number + if pulses == 0 then + return 0 + end + local base = CACHE_INDEX[(LM + 1) * NB_EBANDS + bandI + 1] + return CACHE_BITS[base + pulses + 1] + 1 +end + +@native local function getPulses(i: number): number + if i < 8 then + return i + end + return lshift(8 + band(i, 7), rshift(i, 3) - 1) +end + +-- clt_compute_allocation + interp_bits2pulses (decoder side) +@native local function computeAllocation(start: number, endb: number, offsets: { number }, cap: { number }, allocTrim: number, + total: number, pulses: { number }, ebits: { number }, finePriority: { number }, C: number, LM: number, ec: RD.Dec) + total = imax(total, 0) + local len = NB_EBANDS + local skipStart = start + local skipRsv = if total >= 8 then 8 else 0 + total -= skipRsv + local intensityRsv, dualStereoRsv = 0, 0 + if C == 2 then + intensityRsv = LOG2_FRAC_TABLE[endb - start + 1] + if intensityRsv > total then + intensityRsv = 0 + else + total -= intensityRsv + dualStereoRsv = if total >= 8 then 8 else 0 + total -= dualStereoRsv + end + end + local bits1, bits2, thresh, trimOffset = BITS1, BITS2, THRESH, TRIM_OFFSET + for j = start, endb - 1 do + local w = EB[j + 2] - EB[j + 1] + thresh[j + 1] = imax(C * 8, (3 * w * 2 ^ LM * 8) // 16) + trimOffset[j + 1] = (C * w * (allocTrim - 5 - LM) * (endb - j - 1) * 2 ^ (LM + BITRES)) // 64 + if w * 2 ^ LM == 1 then + trimOffset[j + 1] -= C * 8 + end + end + local lo, hi = 1, NB_ALLOC_VECTORS - 1 + repeat + local done = false + local psum = 0 + local mid = rshift(lo + hi, 1) + for j = endb - 1, start, -1 do + local N = EB[j + 2] - EB[j + 1] + local bitsj = (C * N * ALLOC[mid * len + j + 1] * 2 ^ LM) // 4 + if bitsj > 0 then + bitsj = imax(0, bitsj + trimOffset[j + 1]) + end + bitsj += offsets[j + 1] + if bitsj >= thresh[j + 1] or done then + done = true + psum += imin(bitsj, cap[j + 1]) + elseif bitsj >= C * 8 then + psum += C * 8 + end + end + if psum > total then + hi = mid - 1 + else + lo = mid + 1 + end + until lo > hi + hi = lo + lo -= 1 + for j = start, endb - 1 do + local N = EB[j + 2] - EB[j + 1] + local bits1j = (C * N * ALLOC[lo * len + j + 1] * 2 ^ LM) // 4 + local bits2j = if hi >= NB_ALLOC_VECTORS then cap[j + 1] else (C * N * ALLOC[hi * len + j + 1] * 2 ^ LM) // 4 + if bits1j > 0 then + bits1j = imax(0, bits1j + trimOffset[j + 1]) + end + if bits2j > 0 then + bits2j = imax(0, bits2j + trimOffset[j + 1]) + end + if lo > 0 then + bits1j += offsets[j + 1] + end + bits2j += offsets[j + 1] + if offsets[j + 1] > 0 then + skipStart = j + end + bits2j = imax(0, bits2j - bits1j) + bits1[j + 1] = bits1j + bits2[j + 1] = bits2j + end + + -- interp_bits2pulses + local bits = pulses + local allocFloor = C * 8 + local stereo = if C > 1 then 1 else 0 + local logM = LM * 8 + lo, hi = 0, 64 + for _ = 1, 6 do + local mid = rshift(lo + hi, 1) + local psum = 0 + local done = false + for j = endb - 1, start, -1 do + local tmp = bits1[j + 1] + (mid * bits2[j + 1]) // 64 + if tmp >= thresh[j + 1] or done then + done = true + psum += imin(tmp, cap[j + 1]) + elseif tmp >= allocFloor then + psum += allocFloor + end + end + if psum > total then + hi = mid + else + lo = mid + end + end + local psum = 0 + local done = false + for j = endb - 1, start, -1 do + local tmp = bits1[j + 1] + (lo * bits2[j + 1]) // 64 + if tmp < thresh[j + 1] and not done then + if tmp >= allocFloor then + tmp = allocFloor + else + tmp = 0 + end + else + done = true + end + tmp = imin(tmp, cap[j + 1]) + bits[j + 1] = tmp + psum += tmp + end + local codedBands = endb + while true do + local j = codedBands - 1 + if j <= skipStart then + total += skipRsv + break + end + local left = total - psum + local percoeff = left // (EB[codedBands + 1] - EB[start + 1]) + left -= (EB[codedBands + 1] - EB[start + 1]) * percoeff + local rem = imax(left - (EB[j + 1] - EB[start + 1]), 0) + local bandWidth = EB[codedBands + 1] - EB[j + 1] + local bandBits = bits[j + 1] + percoeff * bandWidth + rem + if bandBits >= imax(thresh[j + 1], allocFloor + 8) then + if decBitLogp(ec, 1) then + break + end + psum += 8 + bandBits -= 8 + end + psum -= bits[j + 1] + intensityRsv + if intensityRsv > 0 then + intensityRsv = LOG2_FRAC_TABLE[j - start + 1] + end + psum += intensityRsv + if bandBits >= allocFloor then + psum += allocFloor + bits[j + 1] = allocFloor + else + bits[j + 1] = 0 + end + codedBands -= 1 + end + local intensity, dualStereo = 0, false + if intensityRsv > 0 then + intensity = start + decUint(ec, codedBands + 1 - start) + end + if intensity <= start then + total += dualStereoRsv + dualStereoRsv = 0 + end + if dualStereoRsv > 0 then + dualStereo = decBitLogp(ec, 1) + end + local left = total - psum + local percoeff = left // (EB[codedBands + 1] - EB[start + 1]) + left -= (EB[codedBands + 1] - EB[start + 1]) * percoeff + for j = start, codedBands - 1 do + bits[j + 1] += percoeff * (EB[j + 2] - EB[j + 1]) + end + for j = start, codedBands - 1 do + local tmp = imin(left, EB[j + 2] - EB[j + 1]) + bits[j + 1] += tmp + left -= tmp + end + local balance = 0 + local j = start + while j < codedBands do + local N0 = EB[j + 2] - EB[j + 1] + local N = N0 * 2 ^ LM + local bit = bits[j + 1] + balance + local excess + if N > 1 then + excess = imax(bit - cap[j + 1], 0) + bits[j + 1] = bit - excess + local den = C * N + (if C == 2 and N > 2 and not dualStereo and j < intensity then 1 else 0) + local NClogN = den * (LOGN[j + 1] + logM) + local offset = (NClogN // 2) - den * FINE_OFFSET + if N == 2 then + offset += (den * 8) // 4 + end + if bits[j + 1] + offset < den * 2 * 8 then + offset += NClogN // 4 + elseif bits[j + 1] + offset < den * 3 * 8 then + offset += NClogN // 8 + end + local eb = imax(0, bits[j + 1] + offset + den * 4) + eb = (eb // den) // 8 + if C * eb > (bits[j + 1] // 8) then + eb = (bits[j + 1] // 2 ^ stereo) // 8 + end + eb = imin(eb, MAX_FINE_BITS) + finePriority[j + 1] = if eb * (den * 8) >= bits[j + 1] + offset then 1 else 0 + bits[j + 1] -= C * eb * 8 + ebits[j + 1] = eb + else + excess = imax(0, bit - C * 8) + bits[j + 1] = bit - excess + ebits[j + 1] = 0 + finePriority[j + 1] = 1 + end + if excess > 0 then + local extraFine = imin(excess // 2 ^ (stereo + BITRES), MAX_FINE_BITS - ebits[j + 1]) + ebits[j + 1] += extraFine + local extraBits = extraFine * C * 8 + finePriority[j + 1] = if extraBits >= excess - balance then 1 else 0 + excess -= extraBits + end + balance = excess + j += 1 + end + while j < endb do + ebits[j + 1] = (bits[j + 1] // 2 ^ stereo) // 8 + bits[j + 1] = 0 + finePriority[j + 1] = if ebits[j + 1] < 1 then 1 else 0 + j += 1 + end + return codedBands, balance, intensity, dualStereo +end + +-- PVQ (cwrs.c, vq.c) + +@native local function cwrsi(n: number, k: number, i: number, iy: { number }): number + local yy = 0 + local idx = 1 + local p, k0, val + while n > 2 do + if k >= n then + local rowBase = n * UK + 1 + p = U[rowBase + k + 1] + local neg = i >= p + if neg then + i -= p + end + k0 = k + local q = U[rowBase + n] + if q > i then + k = n + repeat + k -= 1 + p = U[k * UK + n + 1] + until p <= i + else + p = U[rowBase + k] + while p > i do + k -= 1 + p = U[rowBase + k] + end + end + i -= p + val = if neg then k - k0 else k0 - k + iy[idx] = val + idx += 1 + yy += val * val + else + p = U[k * UK + n + 1] + local q = U[(k + 1) * UK + n + 1] + if p <= i and i < q then + i -= p + iy[idx] = 0 + idx += 1 + else + local neg = i >= q + if neg then + i -= q + end + k0 = k + repeat + k -= 1 + p = U[k * UK + n + 1] + until p <= i + i -= p + val = if neg then k - k0 else k0 - k + iy[idx] = val + idx += 1 + yy += val * val + end + end + n -= 1 + end + p = 2 * k + 1 + local neg = i >= p + if neg then + i -= p + end + k0 = k + k = rshift(i + 1, 1) + if k ~= 0 then + i -= 2 * k - 1 + end + val = if neg then k - k0 else k0 - k + iy[idx] = val + yy += val * val + val = if i ~= 0 then -k else k + iy[idx + 1] = val + yy += val * val + return yy +end + +@native local function expRotation1(X: number, len: number, stride: number, c: number, s: number) + local ms = -s + local p = X + 1 + for _ = 0, len - stride - 1 do + local x1 = W[p] + local x2 = W[p + stride] + W[p + stride] = c * x2 + s * x1 + W[p] = c * x1 + ms * x2 + p += 1 + end + p = X + len - 2 * stride + for _ = len - 2 * stride - 1, 0, -1 do + local x1 = W[p] + local x2 = W[p + stride] + W[p + stride] = c * x2 + s * x1 + W[p] = c * x1 + ms * x2 + p -= 1 + end +end + +local SPREAD_FACTOR = { 15, 10, 5 } +@native local function expRotation(X: number, len: number, dir: number, stride: number, K: number, spread: number) + if 2 * K >= len or spread == 0 then + return + end + local factor = SPREAD_FACTOR[spread] + local gain = len / (len + factor * K) + local theta = 0.5 * (gain * gain) + local c = cos(0.5 * math.pi * theta) + local s = cos(0.5 * math.pi * (1 - theta)) + local stride2 = 0 + if len >= 8 * stride then + stride2 = 1 + while (stride2 * stride2 + stride2) * stride + rshift(stride, 2) < len do + stride2 += 1 + end + end + len = len // stride + for i = 0, stride - 1 do + local x = X + i * len + if dir < 0 then + if stride2 ~= 0 then + expRotation1(x, len, stride2, s, c) + end + expRotation1(x, len, 1, c, s) + else + expRotation1(x, len, 1, c, -s) + if stride2 ~= 0 then + expRotation1(x, len, stride2, s, -c) + end + end + end +end + +@native local function renormaliseVector(X: number, N: number, gain: number) + local E = 1e-15 + for i = X + 1, X + N do + local v = W[i] + E += v * v + end + local g = gain / sqrt(E) + for i = X + 1, X + N do + W[i] *= g + end +end + +@native local function algUnquant(X: number, N: number, K: number, spread: number, B: number, dec: RD.Dec, gain: number): number + local iy = IY + local ft = U[N * UK + K + 1] + U[N * UK + K + 2] + local Ryy = cwrsi(N, K, decUint(dec, ft), iy) + local g = gain / sqrt(Ryy) + for i = 1, N do + W[X + i] = iy[i] * g + end + expRotation(X, N, -1, B, K, spread) + if B <= 1 then + return 1 + end + local N0 = N // B + local mask = 0 + for i = 0, B - 1 do + for j = 1, N0 do + if iy[i * N0 + j] ~= 0 then + mask = bor(mask, lshift(1, i)) + break + end + end + end + return mask +end + +-- bands (bands.c) + +type Ctx = { + i: number, + intensity: number, + spread: number, + tf_change: number, + ec: RD.Dec, + remaining_bits: number, + seed: number, + disable_inv: boolean, + avoid_split_noise: boolean, +} +local ctx: Ctx = { + i = 0, + intensity = 0, + spread = 0, + tf_change = 0, + ec = (nil :: any), + remaining_bits = 0, + seed = 0, + disable_inv = false, + avoid_split_noise = false, +} + +@native local function haar1(X: number, N0: number, stride: number) + N0 = rshift(N0, 1) + local s = 0.70710678 + for i = 0, stride - 1 do + for j = 0, N0 - 1 do + local a = X + stride * 2 * j + i + 1 + local b = a + stride + local t1 = s * W[a] + local t2 = s * W[b] + W[a] = t1 + t2 + W[b] = t1 - t2 + end + end +end + +@native local function deinterleaveHadamard(X: number, N0: number, stride: number, hadamard: boolean) + local N = N0 * stride + local tmp = TMP + if hadamard then + local ob = stride - 2 + for i = 0, stride - 1 do + local o = ORDERY[ob + i + 1] * N0 + for j = 0, N0 - 1 do + tmp[o + j + 1] = W[X + j * stride + i + 1] + end + end + else + for i = 0, stride - 1 do + for j = 0, N0 - 1 do + tmp[i * N0 + j + 1] = W[X + j * stride + i + 1] + end + end + end + for k = 1, N do + W[X + k] = tmp[k] + end +end + +@native local function interleaveHadamard(X: number, N0: number, stride: number, hadamard: boolean) + local N = N0 * stride + local tmp = TMP + if hadamard then + local ob = stride - 2 + for i = 0, stride - 1 do + local o = ORDERY[ob + i + 1] * N0 + for j = 0, N0 - 1 do + tmp[j * stride + i + 1] = W[X + o + j + 1] + end + end + else + for i = 0, stride - 1 do + for j = 0, N0 - 1 do + tmp[j * stride + i + 1] = W[X + i * N0 + j + 1] + end + end + end + for k = 1, N do + W[X + k] = tmp[k] + end +end + +@native local function computeQn(N: number, b: number, offset: number, pulseCap: number, stereo: boolean): number + local N2 = 2 * N - 1 + if stereo and N == 2 then + N2 -= 1 + end + local qb = tdiv(b + N2 * offset, N2) + qb = imin(b - pulseCap - 32, qb) + qb = imin(64, qb) + if qb < 4 then + return 1 + end + local qn = rshift(EXP2_TABLE8[band(qb, 7) + 1], 14 - rshift(qb, 3)) + return lshift(rshift(qn + 1, 1), 1) +end + +@native local function computeTheta(N: number, b: number, B: number, B0: number, LM: number, stereo: boolean, fill: number) + local i = ctx.i + local ec = ctx.ec + local pulseCap = LOGN[i + 1] + LM * 8 + local offset = (pulseCap // 2) - (if stereo and N == 2 then QTHETA_OFFSET_TWOPHASE else QTHETA_OFFSET) + local qn = computeQn(N, b, offset, pulseCap, stereo) + if stereo and i >= ctx.intensity then + qn = 1 + end + local t0 = tellFrac(ec) + local itheta = 0 + local inv = false + if qn ~= 1 then + if stereo and N > 2 then + local p0 = 3 + local x0 = qn // 2 + local ft = p0 * (x0 + 1) + x0 + local fs = decDecode(ec, ft) + local x + if fs < (x0 + 1) * p0 then + x = fs // p0 + else + x = x0 + 1 + (fs - (x0 + 1) * p0) + end + if x <= x0 then + decUpdate(ec, p0 * x, p0 * (x + 1), ft) + else + decUpdate(ec, (x - 1 - x0) + (x0 + 1) * p0, (x - x0) + (x0 + 1) * p0, ft) + end + itheta = x + elseif B0 > 1 or stereo then + itheta = decUint(ec, qn + 1) + else + local h = rshift(qn, 1) + local ft = (h + 1) * (h + 1) + local fm = decDecode(ec, ft) + local fs, fl + if fm < rshift(h * (h + 1), 1) then + itheta = rshift(floor(sqrt(8 * fm + 1)) - 1, 1) + fs = itheta + 1 + fl = rshift(itheta * (itheta + 1), 1) + else + itheta = rshift(2 * (qn + 1) - floor(sqrt(8 * (ft - fm - 1) + 1)), 1) + fs = qn + 1 - itheta + fl = ft - rshift((qn + 1 - itheta) * (qn + 2 - itheta), 1) + end + decUpdate(ec, fl, fl + fs, ft) + end + itheta = (itheta * 16384) // qn + elseif stereo then + if b > 16 and ctx.remaining_bits > 16 then + inv = decBitLogp(ec, 2) + end + if ctx.disable_inv then + inv = false + end + itheta = 0 + end + local qalloc = tellFrac(ec) - t0 + b -= qalloc + local imid, iside, delta + if itheta == 0 then + imid = 32767 + iside = 0 + fill = band(fill, lshift(1, B) - 1) + delta = -16384 + elseif itheta == 16384 then + imid = 0 + iside = 32767 + fill = band(fill, lshift(lshift(1, B) - 1, B)) + delta = 16384 + else + imid = bitexactCos(itheta) + iside = bitexactCos(16384 - itheta) + delta = fracMul16((N - 1) * 128, bitexactLog2tan(iside, imid)) + end + return b, fill, inv, imid, iside, delta, itheta, qalloc +end + +@native local function quantBandN1(X: number, Y: number, lowbandOut: number): number + local x = X + local ec = ctx.ec + for _ = 0, (if Y >= 0 then 1 else 0) do + local sign = 0 + if ctx.remaining_bits >= 8 then + sign = decBits(ec, 1) + ctx.remaining_bits -= 8 + end + W[x + 1] = if sign ~= 0 then -1 else 1 + x = Y + end + if lowbandOut >= 0 then + W[lowbandOut + 1] = W[X + 1] + end + return 1 +end + +@native local function quantPartition(X: number, N: number, b: number, B: number, lowband: number, LM: number, gain: number, fill: number): number + local i = ctx.i + local B0 = B + local cm = 0 + local split = false + if LM ~= -1 and N > 2 then + local base = CACHE_INDEX[(LM + 1) * NB_EBANDS + i + 1] + split = b > CACHE_BITS[base + CACHE_BITS[base + 1] + 1] + 12 + end + if split then + N = rshift(N, 1) + local Y = X + N + LM -= 1 + if B == 1 then + fill = bor(band(fill, 1), lshift(fill, 1)) + end + B = rshift(B + 1, 1) + local _inv, imid, iside, delta, itheta, qalloc + b, fill, _inv, imid, iside, delta, itheta, qalloc = computeTheta(N, b, B, B0, LM, false, fill) + local mid = imid / 32768 + local side = iside / 32768 + if B0 > 1 and band(itheta, 0x3fff) ~= 0 then + if itheta > 8192 then + delta -= delta // 2 ^ (4 - LM) + else + delta = imin(0, delta + (N * 8) // 2 ^ (5 - LM)) + end + end + local mbits = imax(0, imin(b, tdiv(b - delta, 2))) + local sbits = b - mbits + ctx.remaining_bits -= qalloc + local nextLowband2 = if lowband >= 0 then lowband + N else -1 + local rebalance = ctx.remaining_bits + if mbits >= sbits then + cm = quantPartition(X, N, mbits, B, lowband, LM, gain * mid, fill) + rebalance = mbits - (rebalance - ctx.remaining_bits) + if rebalance > 24 and itheta ~= 0 then + sbits += rebalance - 24 + end + cm = bor(cm, lshift(quantPartition(Y, N, sbits, B, nextLowband2, LM, gain * side, rshift(fill, B)), rshift(B0, 1))) + else + cm = lshift(quantPartition(Y, N, sbits, B, nextLowband2, LM, gain * side, rshift(fill, B)), rshift(B0, 1)) + rebalance = sbits - (rebalance - ctx.remaining_bits) + if rebalance > 24 and itheta ~= 16384 then + mbits += rebalance - 24 + end + cm = bor(cm, quantPartition(X, N, mbits, B, lowband, LM, gain * mid, fill)) + end + else + local q = bits2pulses(i, LM, b) + local currBits = pulses2bits(i, LM, q) + ctx.remaining_bits -= currBits + while ctx.remaining_bits < 0 and q > 0 do + ctx.remaining_bits += currBits + q -= 1 + currBits = pulses2bits(i, LM, q) + ctx.remaining_bits -= currBits + end + if q ~= 0 then + cm = algUnquant(X, N, getPulses(q), ctx.spread, B, ctx.ec, gain) + else + local cmMask = lshift(1, B) - 1 + fill = band(fill, cmMask) + if fill == 0 then + for j = X + 1, X + N do + W[j] = 0 + end + else + local seed = ctx.seed + if lowband < 0 then + for j = X + 1, X + N do + seed = lcg(seed) + W[j] = signed32(seed) // 1048576 + end + cm = cmMask + else + for j = 0, N - 1 do + seed = lcg(seed) + local tmp = if band(seed, 0x8000) ~= 0 then 1 / 256 else -1 / 256 + W[X + j + 1] = W[lowband + j + 1] + tmp + end + cm = fill + end + ctx.seed = seed + renormaliseVector(X, N, gain) + end + end + end + return cm +end + +@native local function quantBand(X: number, N: number, b: number, B: number, lowband: number, LM: number, lowbandOut: number, + gain: number, lowbandScratch: number, fill: number): number + local N0 = N + local NB = N + local B0 = B + local timeDivide = 0 + local recombine = 0 + local longBlocks = B0 == 1 + local tfChange = ctx.tf_change + NB = NB // B + if N == 1 then + return quantBandN1(X, -1, lowbandOut) + end + if tfChange > 0 then + recombine = tfChange + end + if lowbandScratch >= 0 and lowband >= 0 and (recombine ~= 0 or (band(NB, 1) == 0 and tfChange < 0) or B0 > 1) then + for j = 1, N do + W[lowbandScratch + j] = W[lowband + j] + end + lowband = lowbandScratch + end + for k = 0, recombine - 1 do + if lowband >= 0 then + haar1(lowband, rshift(N, k), lshift(1, k)) + end + fill = bor(BIT_INTERLEAVE[band(fill, 0xF) + 1], lshift(BIT_INTERLEAVE[rshift(fill, 4) + 1], 2)) + end + B = rshift(B, recombine) + NB = lshift(NB, recombine) + while band(NB, 1) == 0 and tfChange < 0 do + if lowband >= 0 then + haar1(lowband, NB, B) + end + fill = bor(fill, lshift(fill, B)) + B = lshift(B, 1) + NB = rshift(NB, 1) + timeDivide += 1 + tfChange += 1 + end + B0 = B + local NB0 = NB + if B0 > 1 and lowband >= 0 then + deinterleaveHadamard(lowband, rshift(NB, recombine), lshift(B0, recombine), longBlocks) + end + local cm = quantPartition(X, N, b, B, lowband, LM, gain, fill) + if B0 > 1 then + interleaveHadamard(X, rshift(NB, recombine), lshift(B0, recombine), longBlocks) + end + NB = NB0 + B = B0 + for _ = 0, timeDivide - 1 do + B = rshift(B, 1) + NB = lshift(NB, 1) + cm = bor(cm, rshift(cm, B)) + haar1(X, NB, B) + end + for k = 0, recombine - 1 do + cm = BIT_DEINTERLEAVE[cm + 1] + haar1(X, rshift(N0, k), lshift(1, k)) + end + B = lshift(B, recombine) + if lowbandOut >= 0 then + local n = sqrt(N0) + for j = 1, N0 do + W[lowbandOut + j] = n * W[X + j] + end + end + return band(cm, lshift(1, B) - 1) +end + +@native local function stereoMerge(X: number, Y: number, mid: number, N: number) + local xp, side = 0, 0 + for j = 1, N do + local y = W[Y + j] + xp += y * W[X + j] + side += y * y + end + xp = mid * xp + local mm = mid * mid + local El = mm + side - 2 * xp + local Er = mm + side + 2 * xp + if Er < 6e-4 or El < 6e-4 then + for j = 1, N do + W[Y + j] = W[X + j] + end + return + end + local lgain = 1 / sqrt(El) + local rgain = 1 / sqrt(Er) + for j = 1, N do + local l = mid * W[X + j] + local r = W[Y + j] + W[X + j] = lgain * (l - r) + W[Y + j] = rgain * (l + r) + end +end + +@native local function quantBandStereo(X: number, Y: number, N: number, b: number, B: number, lowband: number, LM: number, + lowbandOut: number, lowbandScratch: number, fill: number): number + if N == 1 then + return quantBandN1(X, Y, lowbandOut) + end + local origFill = fill + local inv, imid, iside, delta, itheta, qalloc + b, fill, inv, imid, iside, delta, itheta, qalloc = computeTheta(N, b, B, B, LM, true, fill) + local mid = imid / 32768 + local side = iside / 32768 + local cm + if N == 2 then + local mbits = b + local sbits = 0 + if itheta ~= 0 and itheta ~= 16384 then + sbits = 8 + end + mbits -= sbits + local c = itheta > 8192 + ctx.remaining_bits -= qalloc + sbits + local x2, y2 = X, Y + if c then + x2, y2 = Y, X + end + local sign = 0 + if sbits ~= 0 then + sign = decBits(ctx.ec, 1) + end + sign = 1 - 2 * sign + cm = quantBand(x2, N, mbits, B, lowband, LM, lowbandOut, 1, lowbandScratch, origFill) + W[y2 + 1] = -sign * W[x2 + 2] + W[y2 + 2] = sign * W[x2 + 1] + local x0, x1 = mid * W[X + 1], mid * W[X + 2] + local y0, y1 = side * W[Y + 1], side * W[Y + 2] + W[X + 1] = x0 - y0 + W[Y + 1] = x0 + y0 + W[X + 2] = x1 - y1 + W[Y + 2] = x1 + y1 + else + local mbits = imax(0, imin(b, tdiv(b - delta, 2))) + local sbits = b - mbits + ctx.remaining_bits -= qalloc + local rebalance = ctx.remaining_bits + if mbits >= sbits then + cm = quantBand(X, N, mbits, B, lowband, LM, lowbandOut, 1, lowbandScratch, fill) + rebalance = mbits - (rebalance - ctx.remaining_bits) + if rebalance > 24 and itheta ~= 0 then + sbits += rebalance - 24 + end + cm = bor(cm, quantBand(Y, N, sbits, B, -1, LM, -1, side, -1, rshift(fill, B))) + else + cm = quantBand(Y, N, sbits, B, -1, LM, -1, side, -1, rshift(fill, B)) + rebalance = sbits - (rebalance - ctx.remaining_bits) + if rebalance > 24 and itheta ~= 16384 then + mbits += rebalance - 24 + end + cm = bor(cm, quantBand(X, N, mbits, B, lowband, LM, lowbandOut, 1, lowbandScratch, fill)) + end + end + if N ~= 2 then + stereoMerge(X, Y, mid, N) + end + if inv then + for j = Y + 1, Y + N do + W[j] = -W[j] + end + end + return cm +end + +@native local function quantAllBands(start: number, endb: number, hasY: boolean, N: number, collapse: { number }, + pulses: { number }, shortBlocks: boolean, spread: number, dualStereo: boolean, intensity: number, + tfRes: { number }, totalBits: number, balance: number, ec: RD.Dec, LM: number, codedBands: number, + seed: number, disableInv: boolean): number + local M = lshift(1, LM) + local B = if shortBlocks then M else 1 + local normOffset = M * EB[start + 1] + local C = if hasY then 2 else 1 + local norm = NORM_BASE + local norm2 = NORM_BASE + M * EB[NB_EBANDS] - normOffset + local lowbandScratch = M * EB[EFF_EBANDS] + local lowbandOffset = 0 + local updateLowband = true + ctx.ec = ec + ctx.intensity = intensity + ctx.seed = seed + ctx.spread = spread + ctx.disable_inv = disableInv + ctx.avoid_split_noise = B > 1 + for i = start, endb - 1 do + ctx.i = i + local last = i == endb - 1 + local X = M * EB[i + 1] + local Y = if hasY then N + M * EB[i + 1] else -1 + local Nb = M * EB[i + 2] - M * EB[i + 1] + local t = tellFrac(ec) + if i ~= start then + balance -= t + end + local remainingBits = totalBits - t - 1 + ctx.remaining_bits = remainingBits + local b + if i <= codedBands - 1 then + local currBalance = tdiv(balance, imin(3, codedBands - i)) + b = imax(0, imin(16383, imin(remainingBits + 1, pulses[i + 1] + currBalance))) + else + b = 0 + end + if (M * EB[i + 1] - Nb >= M * EB[start + 1] or i == start + 1) and (updateLowband or lowbandOffset == 0) then + lowbandOffset = i + end + if i == start + 1 then + local n1 = M * (EB[start + 2] - EB[start + 1]) + local n2 = M * (EB[start + 3] - EB[start + 2]) + for k = 0, n2 - n1 - 1 do + W[norm + n1 + k + 1] = W[norm + 2 * n1 - n2 + k + 1] + end + if dualStereo then + for k = 0, n2 - n1 - 1 do + W[norm2 + n1 + k + 1] = W[norm2 + 2 * n1 - n2 + k + 1] + end + end + end + local tfChange = tfRes[i + 1] + ctx.tf_change = tfChange + if last then + lowbandScratch = -1 + end + local effectiveLowband = -1 + local xcm, ycm + if lowbandOffset ~= 0 and (spread ~= SPREAD_AGGRESSIVE or B > 1 or tfChange < 0) then + effectiveLowband = imax(0, M * EB[lowbandOffset + 1] - normOffset - Nb) + local foldStart = lowbandOffset + repeat + foldStart -= 1 + until M * EB[foldStart + 1] <= effectiveLowband + normOffset + local foldEnd = lowbandOffset - 1 + repeat + foldEnd += 1 + until not (foldEnd < i and M * EB[foldEnd + 1] < effectiveLowband + normOffset + Nb) + xcm, ycm = 0, 0 + local fi = foldStart + repeat + xcm = bor(xcm, collapse[fi * C + 1]) + ycm = bor(ycm, collapse[fi * C + C]) + fi += 1 + until fi >= foldEnd + else + xcm = lshift(1, B) - 1 + ycm = xcm + end + if dualStereo and i == intensity then + dualStereo = false + for j = 1, M * EB[i + 1] - normOffset do + W[norm + j] = 0.5 * (W[norm + j] + W[norm2 + j]) + end + end + if dualStereo then + xcm = quantBand(X, Nb, b // 2, B, if effectiveLowband ~= -1 then norm + effectiveLowband else -1, LM, + if last then -1 else norm + M * EB[i + 1] - normOffset, 1, lowbandScratch, xcm) + ycm = quantBand(Y, Nb, b // 2, B, if effectiveLowband ~= -1 then norm2 + effectiveLowband else -1, LM, + if last then -1 else norm2 + M * EB[i + 1] - normOffset, 1, lowbandScratch, ycm) + else + local lb = if effectiveLowband ~= -1 then norm + effectiveLowband else -1 + local lo = if last then -1 else norm + M * EB[i + 1] - normOffset + if hasY then + xcm = quantBandStereo(X, Y, Nb, b, B, lb, LM, lo, lowbandScratch, bor(xcm, ycm)) + else + xcm = quantBand(X, Nb, b, B, lb, LM, lo, 1, lowbandScratch, bor(xcm, ycm)) + end + ycm = xcm + end + collapse[i * C + 1] = band(xcm, 255) + collapse[i * C + C] = band(ycm, 255) + balance += pulses[i + 1] + t + updateLowband = b > Nb * 8 + ctx.avoid_split_noise = false + end + return ctx.seed +end + +@native local function antiCollapse(st: any, C: number, size: number, LM: number, start: number, endb: number, + collapse: { number }, pulses: { number }, seed: number) + local logE, prev1logE, prev2logE = st.oldBandE, st.oldLogE, st.oldLogE2 + for i = start, endb - 1 do + local N0 = EB[i + 2] - EB[i + 1] + local depth = rshift((1 + pulses[i + 1]) // N0, LM) + local thresh = 0.5 * exp2(-0.125 * depth) + local sqrt1 = 1 / sqrt(N0 * 2 ^ LM) + for c = 0, C - 1 do + local k0 = c * NB_EBANDS + i + 1 + local prev1 = prev1logE[k0] + local prev2 = prev2logE[k0] + if C == 1 then + prev1 = max(prev1, prev1logE[NB_EBANDS + i + 1]) + prev2 = max(prev2, prev2logE[NB_EBANDS + i + 1]) + end + local Ediff = max(0, logE[k0] - min(prev1, prev2)) + local r = 2 * exp2(-Ediff) + if LM == 3 then + r *= 1.41421356 + end + r = min(thresh, r) * sqrt1 + local X = c * size + EB[i + 1] * 2 ^ LM + local renorm = false + local cmask = collapse[i * C + c + 1] + for k = 0, 2 ^ LM - 1 do + if band(cmask, lshift(1, k)) == 0 then + for j = 0, N0 - 1 do + seed = lcg(seed) + W[X + j * 2 ^ LM + k + 1] = if band(seed, 0x8000) ~= 0 then r else -r + end + renorm = true + end + end + if renorm then + renormaliseVector(X, N0 * 2 ^ LM, 1) + end + end + end +end + +@native local function denormaliseBands(X: number, freq: { number }, logE: { number }, eoff: number, start: number, endb: number, M: number, silence: boolean) + local N = M * SHORT_MDCT + local bound = M * EB[endb + 1] + if silence then + bound = 0 + start = 0 + endb = 0 + end + local f = 1 + local x = X + M * EB[start + 1] + if start ~= 0 then + for _ = 1, M * EB[start + 1] do + freq[f] = 0 + f += 1 + end + end + for i = start, endb - 1 do + local bandEnd = M * EB[i + 2] + local lg = logE[eoff + i + 1] + E_MEANS[i + 1] + local g = exp2(min(32, lg)) + for _ = M * EB[i + 1], bandEnd - 1 do + freq[f] = W[x + 1] * g + f += 1 + x += 1 + end + end + for k = bound + 1, N do + freq[k] = 0 + end +end + +@native local function celtSynthesis(st: any, C: number, CC: number, start: number, effEnd: number, isTransient: boolean, LM: number, silence: boolean, N: number) + local M = lshift(1, LM) + local B, NB, shift + if isTransient then + B = M + NB = SHORT_MDCT + shift = MAX_LM + else + B = 1 + NB = SHORT_MDCT * M + shift = MAX_LM - LM + end + local outBase = DECODE_BUFFER_SIZE - N + 1 + local oldE = st.oldBandE + local freq = FREQ + if CC == 2 and C == 1 then + denormaliseBands(0, freq, oldE, 0, start, effEnd, M, silence) + for c = 1, 2 do + local mem = st.mem[c] + for b = 0, B - 1 do + Mdct.backward(freq, b + 1, mem, outBase + NB * b, WINDOW, OVERLAP, shift, B) + end + end + elseif CC == 1 and C == 2 then + denormaliseBands(0, freq, oldE, 0, start, effEnd, M, silence) + denormaliseBands(N, FREQ2, oldE, NB_EBANDS, start, effEnd, M, silence) + local f2 = FREQ2 + for k = 1, N do + freq[k] = 0.5 * freq[k] + 0.5 * f2[k] + end + local mem = st.mem[1] + for b = 0, B - 1 do + Mdct.backward(freq, b + 1, mem, outBase + NB * b, WINDOW, OVERLAP, shift, B) + end + else + for c = 0, CC - 1 do + denormaliseBands(c * N, freq, oldE, c * NB_EBANDS, start, effEnd, M, silence) + local mem = st.mem[c + 1] + for b = 0, B - 1 do + Mdct.backward(freq, b + 1, mem, outBase + NB * b, WINDOW, OVERLAP, shift, B) + end + end + end +end + +-- comb_filter, in place on mem (1-based base index of sample 0) +@native local function combFilter(mem: { number }, base: number, T0: number, T1: number, N: number, g0: number, g1: number, + tapset0: number, tapset1: number, overlap: number) + if g0 == 0 and g1 == 0 then + return + end + T0 = imax(T0, COMBFILTER_MINPERIOD) + T1 = imax(T1, COMBFILTER_MINPERIOD) + local ga, gb = COMB_GAINS[tapset0 + 1], COMB_GAINS[tapset1 + 1] + local g00, g01, g02 = g0 * ga[1], g0 * ga[2], g0 * ga[3] + local g10, g11, g12 = g1 * gb[1], g1 * gb[2], g1 * gb[3] + local x1 = mem[base - T1 + 1] + local x2 = mem[base - T1] + local x3 = mem[base - T1 - 1] + local x4 = mem[base - T1 - 2] + if g0 == g1 and T0 == T1 and tapset0 == tapset1 then + overlap = 0 + end + local i = 0 + while i < overlap do + local p = base + i + local x0 = mem[p - T1 + 2] + local w = WINDOW[i + 1] + local f = w * w + local of = 1 - f + mem[p] = mem[p] + (of * g00) * mem[p - T0] + (of * g01) * (mem[p - T0 + 1] + mem[p - T0 - 1]) + + (of * g02) * (mem[p - T0 + 2] + mem[p - T0 - 2]) + (f * g10) * x2 + (f * g11) * (x1 + x3) + + (f * g12) * (x0 + x4) + x4 = x3 + x3 = x2 + x2 = x1 + x1 = x0 + i += 1 + end + if g1 == 0 then + return + end + -- constant part (comb_filter_const) + local p = base + i + x4 = mem[p - T1 - 2] + x3 = mem[p - T1 - 1] + x2 = mem[p - T1] + x1 = mem[p - T1 + 1] + for q = p, base + N - 1 do + local x0 = mem[q - T1 + 2] + mem[q] = mem[q] + g10 * x2 + g11 * (x1 + x3) + g12 * (x0 + x4) + x4 = x3 + x3 = x2 + x2 = x1 + x1 = x0 + end +end + +@native local function deemphasis(st: any, CC: number, N: number, pcm: { number }, pbase: number, accum: boolean) + local coef0 = PREEMPH + local xbase = DECODE_BUFFER_SIZE - N + for c = 0, CC - 1 do + local x = st.mem[c + 1] + local m = st.preemph[c + 1] + local y = pbase + c + if accum then + for j = 1, N do + local tmp = x[xbase + j] + 1e-30 + m + m = coef0 * tmp + pcm[y] += tmp * (1 / 32768) + y += CC + end + else + for j = 1, N do + local tmp = x[xbase + j] + 1e-30 + m + m = coef0 * tmp + pcm[y] = tmp * (1 / 32768) + y += CC + end + end + st.preemph[c + 1] = m + end +end + +@native local function resetState(st: any) + st.rng = 0 + st.error = 0 + st.loss_duration = 0 + st.plc_duration = 0 + st.last_frame_type = FRAME_NONE + st.skip_plc = true + st.postfilter_period = 0 + st.postfilter_period_old = 0 + st.postfilter_gain = 0 + st.postfilter_gain_old = 0 + st.postfilter_tapset = 0 + st.postfilter_tapset_old = 0 + st.preemph[1] = 0 + st.preemph[2] = 0 + for c = 1, st.channels do + local m = st.mem[c] + for k = 1, DECODE_BUFFER_SIZE + OVERLAP do + m[k] = 0 + end + end + for k = 1, 2 * NB_EBANDS do + st.oldBandE[k] = 0 + st.oldLogE[k] = -28 + st.oldLogE2[k] = -28 + st.backgroundLogE[k] = 0 + end +end + +-- celt_decoder_init(48000, channels) +@native function Celt.new(channels: number): any + local st = { + channels = channels, + stream_channels = channels, + start = 0, + ["end"] = EFF_EBANDS, + disable_inv = channels == 1, + mem = {}, + preemph = { 0, 0 }, + oldBandE = table.create(2 * NB_EBANDS, 0), + oldLogE = table.create(2 * NB_EBANDS, -28), + oldLogE2 = table.create(2 * NB_EBANDS, -28), + backgroundLogE = table.create(2 * NB_EBANDS, 0), + } + for c = 1, channels do + st.mem[c] = table.create(DECODE_BUFFER_SIZE + OVERLAP, 0) + end + resetState(st) + return st +end + +Celt.reset = resetState + +-- noise-based concealment (celt_decode_lost, FRAME_PLC_NOISE) +@native local function decodeLost(st: any, N: number, LM: number) + local C = st.channels + local start = st.start + local endb = st["end"] + local effEnd = imax(start, imin(endb, EFF_EBANDS)) + for c = 1, C do + table.move(st.mem[c], N + 1, DECODE_BUFFER_SIZE + OVERLAP, 1) + end + local decay = 2 ^ LM * 0.0625 + if st.last_frame_type ~= FRAME_PLC_NOISE then + decay += max(1, imin(160, st.loss_duration) * 0.0625) + end + local oldE, bg = st.oldBandE, st.backgroundLogE + for c = 0, C - 1 do + for i = start, endb - 1 do + local k = c * NB_EBANDS + i + 1 + oldE[k] = max(bg[k], oldE[k] - decay) + end + end + local seed = st.rng + for c = 0, C - 1 do + for i = start, effEnd - 1 do + local boffs = N * c + EB[i + 1] * 2 ^ LM + local blen = (EB[i + 2] - EB[i + 1]) * 2 ^ LM + for j = 1, blen do + seed = lcg(seed) + W[boffs + j] = signed32(seed) // 1048576 + end + renormaliseVector(boffs, blen, 1) + end + end + st.rng = seed + celtSynthesis(st, C, C, start, effEnd, false, LM, false, N) + local base = DECODE_BUFFER_SIZE - N + 1 + for c = 1, C do + st.postfilter_period = imax(st.postfilter_period, COMBFILTER_MINPERIOD) + st.postfilter_period_old = imax(st.postfilter_period_old, COMBFILTER_MINPERIOD) + combFilter(st.mem[c], base, st.postfilter_period_old, st.postfilter_period, SHORT_MDCT, st.postfilter_gain_old, + st.postfilter_gain, st.postfilter_tapset_old, st.postfilter_tapset, OVERLAP) + if LM ~= 0 then + combFilter(st.mem[c], base + SHORT_MDCT, st.postfilter_period, st.postfilter_period, N - SHORT_MDCT, + st.postfilter_gain, st.postfilter_gain, st.postfilter_tapset, st.postfilter_tapset, OVERLAP) + end + end + st.postfilter_period_old = st.postfilter_period + st.postfilter_gain_old = st.postfilter_gain + st.postfilter_tapset_old = st.postfilter_tapset + st.skip_plc = true + st.loss_duration = imin(10000, st.loss_duration + 2 ^ LM) + st.plc_duration = imin(10000, st.plc_duration + 2 ^ LM) + st.last_frame_type = FRAME_PLC_NOISE +end + +-- celt_decode_with_ec (buf nil or len <= 1 conceals) +@native function Celt.decode(st: any, buf: buffer?, off: number, len: number, pcm: { number }, pbase: number, frameSize: number, + dec: RD.Dec?, accum: boolean): number + local CC = st.channels + local C = st.stream_channels + local start = st.start + local endb = st["end"] + local LM = 0 + while LM <= MAX_LM and lshift(SHORT_MDCT, LM) ~= frameSize do + LM += 1 + end + if LM > MAX_LM then + return -1 + end + local M = lshift(1, LM) + if len < 0 or len > 1275 then + return -1 + end + local N = M * SHORT_MDCT + local effEnd = imin(endb, EFF_EBANDS) + if buf == nil or len <= 1 then + decodeLost(st, N, LM) + deemphasis(st, CC, N, pcm, pbase, accum) + return frameSize + end + if st.loss_duration == 0 then + st.skip_plc = false + end + if dec == nil then + dec = RD.new(buf :: buffer, off, len) + end + local ec = dec :: RD.Dec + local oldBandE, oldLogE, oldLogE2, bgLogE = st.oldBandE, st.oldLogE, st.oldLogE2, st.backgroundLogE + if C == 1 then + for i = 1, NB_EBANDS do + oldBandE[i] = max(oldBandE[i], oldBandE[NB_EBANDS + i]) + end + end + local totalBits = len * 8 + local t = tell(ec) + local silence + if t >= totalBits then + silence = true + elseif t == 1 then + silence = decBitLogp(ec, 15) + else + silence = false + end + if silence then + t = len * 8 + ec.nbits_total += t - tell(ec) + end + local postfilterGain, postfilterPitch, postfilterTapset = 0, 0, 0 + if start == 0 and t + 16 <= totalBits then + if decBitLogp(ec, 1) then + local octave = decUint(ec, 6) + postfilterPitch = lshift(16, octave) + decBits(ec, 4 + octave) - 1 + local qg = decBits(ec, 3) + if tell(ec) + 2 <= totalBits then + postfilterTapset = decIcdf(ec, TAPSET_ICDF, 1, 2) + end + postfilterGain = 0.09375 * (qg + 1) + end + t = tell(ec) + end + local isTransient = false + if LM > 0 and t + 3 <= totalBits then + isTransient = decBitLogp(ec, 3) + t = tell(ec) + end + local shortBlocks = isTransient + local intraEner = if t + 3 <= totalBits then decBitLogp(ec, 3) else false + if not intraEner and st.loss_duration ~= 0 then + local missing = imin(10, rshift(st.loss_duration, LM)) + local safety = if LM == 0 then 1.5 elseif LM == 1 then 0.5 else 0 + for c = 0, 1 do + for i = start, endb - 1 do + local k = c * NB_EBANDS + i + 1 + if oldBandE[k] < max(oldLogE[k], oldLogE2[k]) then + local E0, E1, E2 = oldBandE[k], oldLogE[k], oldLogE2[k] + local slope = max(E1 - E0, 0.5 * (E2 - E0)) + slope = min(slope, 2) + E0 -= max(0, (1 + missing) * slope) + oldBandE[k] = max(-20, E0) + else + oldBandE[k] = min(min(oldBandE[k], oldLogE[k]), oldLogE2[k]) + end + oldBandE[k] -= safety + end + end + end + unquantCoarseEnergy(st, start, endb, intraEner, ec, C, LM) + + -- tf_decode + local tfRes = TF_RES + do + local budget = ec.storage * 8 + local tt = tell(ec) + local logp = if isTransient then 2 else 4 + local tfSelectRsv = LM > 0 and tt + logp + 1 <= budget + if tfSelectRsv then + budget -= 1 + end + local tfChanged, curr = 0, 0 + for i = start, endb - 1 do + if tt + logp <= budget then + if decBitLogp(ec, logp) then + curr = bit32.bxor(curr, 1) + end + tt = tell(ec) + tfChanged = bor(tfChanged, curr) + end + tfRes[i + 1] = curr + logp = if isTransient then 4 else 5 + end + local tfSelect = 0 + local row = TF_SELECT[LM + 1] + local ti = if isTransient then 4 else 0 + if tfSelectRsv and row[ti + tfChanged + 1] ~= row[ti + 2 + tfChanged + 1] then + tfSelect = if decBitLogp(ec, 1) then 1 else 0 + end + for i = start, endb - 1 do + tfRes[i + 1] = row[ti + 2 * tfSelect + tfRes[i + 1] + 1] + end + end + + t = tell(ec) + local spread = 2 + if t + 4 <= totalBits then + spread = decIcdf(ec, SPREAD_ICDF, 1, 5) + end + local cap = CAP + for i = 0, NB_EBANDS - 1 do + local Nw = (EB[i + 2] - EB[i + 1]) * 2 ^ LM + cap[i + 1] = rshift((CACHE_CAPS[NB_EBANDS * (2 * LM + C - 1) + i + 1] + 64) * C * Nw, 2) + end + local offsets = OFFSETS + local dynallocLogp = 6 + totalBits *= 8 + t = tellFrac(ec) + for i = start, endb - 1 do + local width = C * (EB[i + 2] - EB[i + 1]) * 2 ^ LM + local quanta = imin(width * 8, imax(48, width)) + local loopLogp = dynallocLogp + local boost = 0 + while t + loopLogp * 8 < totalBits and boost < cap[i + 1] do + local flag = decBitLogp(ec, loopLogp) + t = tellFrac(ec) + if not flag then + break + end + boost += quanta + totalBits -= quanta + loopLogp = 1 + end + offsets[i + 1] = boost + if boost > 0 then + dynallocLogp = imax(2, dynallocLogp - 1) + end + end + local allocTrim = if t + 48 <= totalBits then decIcdf(ec, TRIM_ICDF, 1, 7) else 5 + local bits = len * 64 - tellFrac(ec) - 1 + local antiCollapseRsv = if isTransient and LM >= 2 and bits >= (LM + 2) * 8 then 8 else 0 + bits -= antiCollapseRsv + local pulses, fineQuant, finePriority = PULSES, FINE_QUANT, FINE_PRIORITY + local codedBands, balance, intensity, dualStereo = computeAllocation(start, endb, offsets, cap, allocTrim, bits, + pulses, fineQuant, finePriority, C, LM, ec) + unquantFineEnergy(st, start, endb, fineQuant, ec, C) + + for c = 1, CC do + table.move(st.mem[c], N + 1, DECODE_BUFFER_SIZE + OVERLAP, 1) + end + + local collapse = COLLAPSE + st.rng = quantAllBands(start, endb, C == 2, N, collapse, pulses, shortBlocks, spread, dualStereo, intensity, tfRes, + len * 64 - antiCollapseRsv, balance, ec, LM, codedBands, st.rng, st.disable_inv) + + local antiCollapseOn = false + if antiCollapseRsv > 0 then + antiCollapseOn = decBits(ec, 1) ~= 0 + end + unquantEnergyFinalise(st, start, endb, fineQuant, finePriority, len * 8 - tell(ec), ec, C) + if antiCollapseOn then + antiCollapse(st, C, N, LM, start, endb, collapse, pulses, st.rng) + end + if silence then + for i = 1, C * NB_EBANDS do + oldBandE[i] = -28 + end + end + + celtSynthesis(st, C, CC, start, effEnd, isTransient, LM, silence, N) + + local base = DECODE_BUFFER_SIZE - N + 1 + for c = 1, CC do + st.postfilter_period = imax(st.postfilter_period, COMBFILTER_MINPERIOD) + st.postfilter_period_old = imax(st.postfilter_period_old, COMBFILTER_MINPERIOD) + combFilter(st.mem[c], base, st.postfilter_period_old, st.postfilter_period, SHORT_MDCT, st.postfilter_gain_old, + st.postfilter_gain, st.postfilter_tapset_old, st.postfilter_tapset, OVERLAP) + if LM ~= 0 then + combFilter(st.mem[c], base + SHORT_MDCT, st.postfilter_period, postfilterPitch, N - SHORT_MDCT, + st.postfilter_gain, postfilterGain, st.postfilter_tapset, postfilterTapset, OVERLAP) + end + end + st.postfilter_period_old = st.postfilter_period + st.postfilter_gain_old = st.postfilter_gain + st.postfilter_tapset_old = st.postfilter_tapset + st.postfilter_period = postfilterPitch + st.postfilter_gain = postfilterGain + st.postfilter_tapset = postfilterTapset + if LM ~= 0 then + st.postfilter_period_old = st.postfilter_period + st.postfilter_gain_old = st.postfilter_gain + st.postfilter_tapset_old = st.postfilter_tapset + end + + if C == 1 then + for i = 1, NB_EBANDS do + oldBandE[NB_EBANDS + i] = oldBandE[i] + end + end + if not isTransient then + for i = 1, 2 * NB_EBANDS do + oldLogE2[i] = oldLogE[i] + oldLogE[i] = oldBandE[i] + end + else + for i = 1, 2 * NB_EBANDS do + oldLogE[i] = min(oldLogE[i], oldBandE[i]) + end + end + local maxBgIncrease = imin(160, st.loss_duration + M) * 0.001 + for i = 1, 2 * NB_EBANDS do + bgLogE[i] = min(bgLogE[i] + maxBgIncrease, oldBandE[i]) + end + for c = 0, 1 do + for i = 0, start - 1 do + local k = c * NB_EBANDS + i + 1 + oldBandE[k] = 0 + oldLogE[k] = -28 + oldLogE2[k] = -28 + end + for i = endb, NB_EBANDS - 1 do + local k = c * NB_EBANDS + i + 1 + oldBandE[k] = 0 + oldLogE[k] = -28 + oldLogE2[k] = -28 + end + end + st.rng = ec.rng + deemphasis(st, CC, N, pcm, pbase, accum) + st.loss_duration = 0 + st.plc_duration = 0 + st.last_frame_type = FRAME_NORMAL + if tell(ec) > 8 * len then + return -3 + end + if ec.error ~= 0 then + st.error = 1 + end + return frameSize +end + +return Celt +end +__FILES["codecs/audio/Opus/CeltEncoder"] = @native function() + + + +-- codecs/audio/Opus/CeltEncoder: a fixed-frame CELT encoder (RFC 6716 section 5.3): 20 ms, full band, CBR, long MDCTs only. +-- 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); the analysis is simplified. +local RE = __include("codecs/entropy/RangeCoder/Encoder") +local T = __include("codecs/audio/Opus/CeltTables") +local Mdct = __include("codecs/audio/Mdct") + +local CeltEncoder = {} + +local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift +local min, max, sqrt, floor, cos, log, atan2 = math.min, math.max, math.sqrt, math.floor, math.cos, math.log, math.atan2 +local encBitLogp, encIcdf, encBits, encUint, encEncode, encEncodeBin = RE.bitLogp, RE.icdf, RE.bits, RE.uint, RE.encode, RE.encodeBin +local tell, tellFrac = RE.tell, RE.tellFrac + +local NB_EBANDS = 21 +local OVERLAP = 120 +local SHORT_MDCT = 120 +local BITRES = 3 +local MAX_FINE_BITS = 8 +local FINE_OFFSET = 21 +local QTHETA_OFFSET = 4 +local PREEMPH = 0.85000610 +local LM = 3 -- 20 ms frames +local M = 8 +local N = 960 + +local EB = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 34, 40, 48, 60, 78, 100 } +local ALLOC = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 90, 80, 75, 69, 63, 56, 49, 40, 34, 29, 20, 18, 10, 0, 0, 0, 0, 0, 0, 0, 0, + 110, 100, 90, 84, 78, 71, 65, 58, 51, 45, 39, 32, 26, 20, 12, 0, 0, 0, 0, 0, 0, + 118, 110, 103, 93, 86, 80, 75, 70, 65, 59, 53, 47, 40, 31, 23, 15, 4, 0, 0, 0, 0, + 126, 119, 112, 104, 95, 89, 83, 78, 72, 66, 60, 54, 47, 39, 32, 25, 17, 12, 1, 0, 0, + 134, 127, 120, 114, 103, 97, 91, 85, 78, 72, 66, 60, 54, 47, 41, 35, 29, 23, 16, 10, 1, + 144, 137, 130, 124, 113, 107, 101, 95, 88, 82, 76, 70, 64, 57, 51, 45, 39, 33, 26, 15, 1, + 152, 145, 138, 132, 123, 117, 111, 105, 98, 92, 86, 80, 74, 67, 61, 55, 49, 43, 36, 20, 1, + 162, 155, 148, 142, 133, 127, 121, 115, 108, 102, 96, 90, 84, 77, 71, 65, 59, 53, 46, 30, 1, + 172, 165, 158, 152, 143, 137, 131, 125, 118, 112, 106, 100, 94, 87, 81, 75, 69, 63, 56, 45, 20, + 200, 200, 200, 200, 200, 200, 200, 200, 198, 193, 188, 183, 178, 173, 168, 163, 158, 153, 148, 129, 104, +} +local NB_ALLOC_VECTORS = 11 +local LOG2_FRAC_TABLE = { 0, 8, 13, 16, 19, 21, 23, 24, 26, 27, 28, 29, 30, 31, 32, 32, 33, 34, 34, 35, 36, 36, 37, 37 } +local LOGN = T.logN400 +local CACHE_INDEX = T.cache_index50 +local CACHE_BITS = T.cache_bits50 +local CACHE_CAPS = T.cache_caps50 +local E_PROB = T.e_prob_model +local E_MEANS = { + 6.437500, 6.250000, 5.750000, 5.312500, 5.062500, 4.812500, 4.500000, 4.375000, 4.875000, 4.687500, + 4.562500, 4.437500, 4.875000, 4.625000, 4.312500, 4.500000, 4.375000, 4.625000, 4.750000, 4.437500, + 3.750000, +} +local PRED_COEF = { 29440 / 32768, 26112 / 32768, 21248 / 32768, 16384 / 32768 } +local BETA_COEF = { 30147 / 32768, 22282 / 32768, 12124 / 32768, 6554 / 32768 } +local BETA_INTRA = 4915 / 32768 +local TF_SELECT = { 0, -2, 0, -3, 3, 0, 1, -1 } -- LM 3 +local TRIM_ICDF = { 126, 124, 119, 109, 87, 41, 19, 9, 4, 2, 0 } +local SPREAD_ICDF = { 25, 23, 2, 0 } +local SMALL_ENERGY_ICDF = { 2, 1, 0 } +local EXP2_TABLE8 = { 16384, 17866, 19483, 21247, 23170, 25267, 27554, 30048 } +local SPREAD_NORMAL = 2 +local SPREAD_FACTOR = { 15, 10, 5 } + +local WINDOW = table.create(OVERLAP, 0) +for i = 0, OVERLAP - 1 do + local s = math.sin(0.5 * math.pi * (i + 0.5) / OVERLAP) + 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 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] +local UK = 177 +local U = table.create(UK * UK, 0) +U[1] = 1 +for n = 1, UK - 1 do + for k = 1, UK - 1 do + U[n * UK + k + 1] = U[(n - 1) * UK + k + 1] + U[n * UK + k] + U[(n - 1) * UK + k] + end +end +@native local function pvqU(n: number, k: number): number + return U[n * UK + k + 1] +end + +@native local function imin(a: number, b: number): number + return if a < b then a else b +end +@native local function imax(a: number, b: number): number + return if a > b then a else b +end +@native local function tdiv(a: number, b: number): number + local q = a / b + return if q >= 0 then floor(q) else -floor(-q) +end +@native local function fracMul16(a: number, b: number): number + return (16384 + a * b) // 32768 +end +@native local function bitexactCos(x: number): number + local x2 = (4096 + x * x) // 8192 + x2 = (32767 - x2) + fracMul16(x2, (-7651 + fracMul16(x2, (8277 + fracMul16(-626, x2))))) + return 1 + x2 +end +@native local function bitexactLog2tan(isin: number, icos: number): number + local lc = RE.ilog(icos) + local ls = RE.ilog(isin) + icos = icos * 2 ^ (15 - lc) + isin = isin * 2 ^ (15 - ls) + return (ls - lc) * 2048 + fracMul16(isin, fracMul16(isin, -2597) + 7932) - fracMul16(icos, fracMul16(icos, -2597) + 7932) +end + +-- ec_laplace_encode: returns the value actually coded (clamped in the flat tail) +@native local function laplaceEncode(enc: RE.Enc, value: number, fs: number, decay: number): number + local fl = 0 + local val = value + if val ~= 0 then + local s = if val < 0 then -1 else 0 + val = if val < 0 then -val else val + fl = fs + fs = ((32768 - 32 - fs) * (16384 - decay)) // 32768 -- ec_laplace_get_freq1 + local i = 1 + while fs > 0 and i < val do + fs *= 2 + fl += fs + 2 + fs = (fs * decay) // 32768 + i += 1 + end + if fs == 0 then + local ndiMax = 32768 - fl + 1 - 1 + ndiMax = rshift(ndiMax - s, 1) + local di = imin(val - i, ndiMax - 1) + fl += (2 * di + 1 + s) + fs = imin(1, 32768 - fl) + value = if s ~= 0 then -(i + di) else i + di + else + fs += 1 + if s == 0 then + fl += fs + end + end + end + encEncodeBin(enc, fl, fl + fs, 15) + return value +end + +type State = { + channels: number, + oldBandE: { number }, + preMem: { number }, + inMem: { { number } }, + frames: number, + X: { { number } }, + bandLogE: { number }, + bandE: { number }, + error: { number }, + work: { number }, + tmp: { number }, + iy: { number }, + remaining: number, + spread: number, + dual: boolean, +} + +@native function CeltEncoder.new(channels: number): State + local inMem = {} + local X = {} + for c = 1, channels do + inMem[c] = table.create(OVERLAP, 0) + X[c] = table.create(N, 0) + end + return { + channels = channels, + oldBandE = table.create(2 * NB_EBANDS, 0), + preMem = table.create(channels, 0), + inMem = inMem, + frames = 0, + X = X, + bandLogE = table.create(2 * NB_EBANDS, 0), + bandE = table.create(2 * NB_EBANDS, 0), + error = table.create(2 * NB_EBANDS, 0), + work = table.create(2 * N, 0), + tmp = table.create(2 * N, 0), + iy = table.create(256, 0), + remaining = 0, + spread = SPREAD_NORMAL, + dual = false, + } +end + +@native local function quantCoarseEnergy(st: State, intra: boolean, enc: RE.Enc, C: number, budget: number, nbBytes: number) + local oldE, bandLogE, err = st.oldBandE, st.bandLogE, st.error + local probBase = LM * 84 + (if intra then 42 else 0) + local coef, beta + if intra then + coef, beta = 0, BETA_INTRA + else + coef, beta = PRED_COEF[LM + 1], BETA_COEF[LM + 1] + end + local maxDecay = min(16, nbBytes / 8) + local prev0, prev1 = 0, 0 + for i = 0, NB_EBANDS - 1 do + for c = 0, C - 1 do + local k = c * NB_EBANDS + i + 1 + local x = bandLogE[k] + local e = max(-9, oldE[k]) + local prev = if c == 0 then prev0 else prev1 + local f = x - coef * e - prev + local qi = floor(0.5 + f) + local decayBound = max(-28, oldE[k]) - maxDecay + if qi < 0 and x < decayBound then + qi += tdiv(decayBound - x, 1) + if qi > 0 then + qi = 0 + end + end + local t = tell(enc) + local bitsLeft = budget - t - 3 * C * (NB_EBANDS - i) + if i ~= 0 and bitsLeft < 30 then + if bitsLeft < 24 then + qi = imin(1, qi) + end + if bitsLeft < 16 then + qi = imax(-1, qi) + end + end + if budget - t >= 15 then + local pi = 2 * imin(i, 20) + qi = laplaceEncode(enc, qi, E_PROB[probBase + pi + 1] * 128, E_PROB[probBase + pi + 2] * 64) + elseif budget - t >= 2 then + qi = imax(-1, imin(qi, 1)) + encIcdf(enc, if qi < 0 then 1 else 2 * qi, SMALL_ENERGY_ICDF, 2) + elseif budget - t >= 1 then + qi = imin(0, qi) + encBitLogp(enc, qi ~= 0, 1) + else + qi = -1 + end + err[k] = f - qi + oldE[k] = coef * e + prev + qi + prev = prev + qi - beta * qi + if c == 0 then + prev0 = prev + else + prev1 = prev + end + end + end +end + +@native local function quantFineEnergy(st: State, fineQuant: { number }, enc: RE.Enc, C: number) + local oldE, err = st.oldBandE, st.error + for i = 0, NB_EBANDS - 1 do + local extra = fineQuant[i + 1] + if extra <= 0 then + continue + end + if tell(enc) + C * extra > enc.storage * 8 then + continue + end + local frac = 2 ^ extra + for c = 0, C - 1 do + local k = c * NB_EBANDS + i + 1 + local q2 = floor((err[k] + 0.5) * frac) + q2 = math.clamp(q2, 0, frac - 1) + encBits(enc, q2, extra) + local offset = (q2 + 0.5) * 2 ^ (14 - extra) * (1 / 16384) - 0.5 + oldE[k] += offset + err[k] -= offset + end + end +end + +@native local function quantEnergyFinalise(st: State, fineQuant: { number }, finePriority: { number }, bitsLeft: number, enc: RE.Enc, C: number) + local oldE, err = st.oldBandE, st.error + for prio = 0, 1 do + local i = 0 + while i < NB_EBANDS and bitsLeft >= C do + if fineQuant[i + 1] >= MAX_FINE_BITS or finePriority[i + 1] ~= prio then + i += 1 + continue + end + for c = 0, C - 1 do + local k = c * NB_EBANDS + i + 1 + local q2 = if err[k] < 0 then 0 else 1 + encBits(enc, q2, 1) + local offset = (q2 - 0.5) * 2 ^ (14 - fineQuant[i + 1] - 1) * (1 / 16384) + oldE[k] += offset + err[k] -= offset + bitsLeft -= 1 + end + i += 1 + end + end +end + +@native local function bits2pulses(bandI: number, lm: number, bits: number): number + local base = CACHE_INDEX[(lm + 1) * NB_EBANDS + bandI + 1] + local lo, hi = 0, CACHE_BITS[base + 1] + bits -= 1 + for _ = 1, 6 do + local mid = rshift(lo + hi + 1, 1) + if CACHE_BITS[base + mid + 1] >= bits then + hi = mid + else + lo = mid + end + end + local loBits = if lo == 0 then -1 else CACHE_BITS[base + lo + 1] + if bits - loBits <= CACHE_BITS[base + hi + 1] - bits then + return lo + end + return hi +end + +@native local function pulses2bits(bandI: number, lm: number, pulses: number): number + if pulses == 0 then + return 0 + end + local base = CACHE_INDEX[(lm + 1) * NB_EBANDS + bandI + 1] + return CACHE_BITS[base + pulses + 1] + 1 +end + +@native local function getPulses(i: number): number + if i < 8 then + return i + end + return lshift(8 + band(i, 7), rshift(i, 3) - 1) +end + +-- clt_compute_allocation (encoder side): keeps every band it can, no intensity stereo, dual stereo for C == 2 +@native local function computeAllocation(offsets: { number }, cap: { number }, allocTrim: number, total: number, + pulses: { number }, ebits: { number }, finePriority: { number }, C: number, enc: RE.Enc, wantDual: boolean) + local start, endb = 0, NB_EBANDS + total = imax(total, 0) + local len = NB_EBANDS + local skipStart = start + local skipRsv = if total >= 8 then 8 else 0 + total -= skipRsv + local intensityRsv, dualStereoRsv = 0, 0 + if C == 2 then + intensityRsv = LOG2_FRAC_TABLE[endb - start + 1] + if intensityRsv > total then + intensityRsv = 0 + else + total -= intensityRsv + dualStereoRsv = if total >= 8 then 8 else 0 + total -= dualStereoRsv + end + end + local bits1, bits2, thresh, trimOffset = {}, {}, {}, {} + for j = start, endb - 1 do + local w = EB[j + 2] - EB[j + 1] + thresh[j + 1] = imax(C * 8, (3 * w * 2 ^ LM * 8) // 16) + trimOffset[j + 1] = (C * w * (allocTrim - 5 - LM) * (endb - j - 1) * 2 ^ (LM + BITRES)) // 64 + if w * 2 ^ LM == 1 then + trimOffset[j + 1] -= C * 8 + end + end + local lo, hi = 1, NB_ALLOC_VECTORS - 1 + repeat + local done = false + local psum = 0 + local mid = rshift(lo + hi, 1) + for j = endb - 1, start, -1 do + local Nw = EB[j + 2] - EB[j + 1] + local bitsj = (C * Nw * ALLOC[mid * len + j + 1] * 2 ^ LM) // 4 + if bitsj > 0 then + bitsj = imax(0, bitsj + trimOffset[j + 1]) + end + bitsj += offsets[j + 1] + if bitsj >= thresh[j + 1] or done then + done = true + psum += imin(bitsj, cap[j + 1]) + elseif bitsj >= C * 8 then + psum += C * 8 + end + end + if psum > total then + hi = mid - 1 + else + lo = mid + 1 + end + until lo > hi + hi = lo + lo -= 1 + for j = start, endb - 1 do + local Nw = EB[j + 2] - EB[j + 1] + local bits1j = (C * Nw * ALLOC[lo * len + j + 1] * 2 ^ LM) // 4 + local bits2j = if hi >= NB_ALLOC_VECTORS then cap[j + 1] else (C * Nw * ALLOC[hi * len + j + 1] * 2 ^ LM) // 4 + if bits1j > 0 then + bits1j = imax(0, bits1j + trimOffset[j + 1]) + end + if bits2j > 0 then + bits2j = imax(0, bits2j + trimOffset[j + 1]) + end + if lo > 0 then + bits1j += offsets[j + 1] + end + bits2j += offsets[j + 1] + if offsets[j + 1] > 0 then + skipStart = j + end + bits2j = imax(0, bits2j - bits1j) + bits1[j + 1] = bits1j + bits2[j + 1] = bits2j + end + -- interp_bits2pulses + local bits = pulses + local allocFloor = C * 8 + local stereo = if C > 1 then 1 else 0 + local logM = LM * 8 + lo, hi = 0, 64 + for _ = 1, 6 do + local mid = rshift(lo + hi, 1) + local psum = 0 + local done = false + for j = endb - 1, start, -1 do + local tmp = bits1[j + 1] + (mid * bits2[j + 1]) // 64 + if tmp >= thresh[j + 1] or done then + done = true + psum += imin(tmp, cap[j + 1]) + elseif tmp >= allocFloor then + psum += allocFloor + end + end + if psum > total then + hi = mid + else + lo = mid + end + end + local psum = 0 + local done = false + for j = endb - 1, start, -1 do + local tmp = bits1[j + 1] + (lo * bits2[j + 1]) // 64 + if tmp < thresh[j + 1] and not done then + if tmp >= allocFloor then + tmp = allocFloor + else + tmp = 0 + end + else + done = true + end + tmp = imin(tmp, cap[j + 1]) + bits[j + 1] = tmp + psum += tmp + end + local codedBands = endb + while true do + local j = codedBands - 1 + if j <= skipStart then + total += skipRsv + break + end + local left = total - psum + local percoeff = left // (EB[codedBands + 1] - EB[start + 1]) + left -= (EB[codedBands + 1] - EB[start + 1]) * percoeff + local rem = imax(left - (EB[j + 1] - EB[start + 1]), 0) + local bandWidth = EB[codedBands + 1] - EB[j + 1] + local bandBits = bits[j + 1] + percoeff * bandWidth + rem + if bandBits >= imax(thresh[j + 1], allocFloor + 8) then + -- keep every band that can be coded: signal "no more skipping" + encBitLogp(enc, true, 1) + break + end + psum -= bits[j + 1] + intensityRsv + if intensityRsv > 0 then + intensityRsv = LOG2_FRAC_TABLE[j - start + 1] + end + psum += intensityRsv + if bandBits >= allocFloor then + psum += allocFloor + bits[j + 1] = allocFloor + else + bits[j + 1] = 0 + end + codedBands -= 1 + end + local intensity, dualStereo = 0, false + if intensityRsv > 0 then + intensity = codedBands -- no intensity stereo + encUint(enc, intensity - start, codedBands + 1 - start) + end + if intensity <= start then + total += dualStereoRsv + dualStereoRsv = 0 + end + if dualStereoRsv > 0 then + dualStereo = wantDual + encBitLogp(enc, dualStereo, 1) + end + local left = total - psum + local percoeff = left // (EB[codedBands + 1] - EB[start + 1]) + left -= (EB[codedBands + 1] - EB[start + 1]) * percoeff + for j = start, codedBands - 1 do + bits[j + 1] += percoeff * (EB[j + 2] - EB[j + 1]) + end + for j = start, codedBands - 1 do + local tmp = imin(left, EB[j + 2] - EB[j + 1]) + bits[j + 1] += tmp + left -= tmp + end + local balance = 0 + local j = start + while j < codedBands do + local N0 = EB[j + 2] - EB[j + 1] + local Nw = N0 * 2 ^ LM + local bit = bits[j + 1] + balance + local excess + if Nw > 1 then + excess = imax(bit - cap[j + 1], 0) + bits[j + 1] = bit - excess + local den = C * Nw + (if C == 2 and Nw > 2 and not dualStereo and j < intensity then 1 else 0) + local NClogN = den * (LOGN[j + 1] + logM) + local offset = (NClogN // 2) - den * FINE_OFFSET + if Nw == 2 then + offset += (den * 8) // 4 + end + if bits[j + 1] + offset < den * 2 * 8 then + offset += NClogN // 4 + elseif bits[j + 1] + offset < den * 3 * 8 then + offset += NClogN // 8 + end + local eb = imax(0, bits[j + 1] + offset + den * 4) + eb = (eb // den) // 8 + if C * eb > (bits[j + 1] // 8) then + eb = (bits[j + 1] // 2 ^ stereo) // 8 + end + eb = imin(eb, MAX_FINE_BITS) + finePriority[j + 1] = if eb * (den * 8) >= bits[j + 1] + offset then 1 else 0 + bits[j + 1] -= C * eb * 8 + ebits[j + 1] = eb + else + excess = imax(0, bit - C * 8) + bits[j + 1] = bit - excess + ebits[j + 1] = 0 + finePriority[j + 1] = 1 + end + if excess > 0 then + local extraFine = imin(excess // 2 ^ (stereo + BITRES), MAX_FINE_BITS - ebits[j + 1]) + ebits[j + 1] += extraFine + local extraBits = extraFine * C * 8 + finePriority[j + 1] = if extraBits >= excess - balance then 1 else 0 + excess -= extraBits + end + balance = excess + j += 1 + end + while j < endb do + ebits[j + 1] = (bits[j + 1] // 2 ^ stereo) // 8 + bits[j + 1] = 0 + finePriority[j + 1] = if ebits[j + 1] < 1 then 1 else 0 + j += 1 + end + return codedBands, balance, intensity, dualStereo +end + +-- icwrs: the index of the pulse vector iy[1..n] +@native local function icwrs(n: number, iy: { number }): number + local j = n -- 1-based position of _y[n - 1] + local i = if iy[j] < 0 then 1 else 0 + local k = math.abs(iy[j]) + repeat + j -= 1 + local nn = n - (j - 1) -- _n - j with 0-based j + i += pvqU(nn, k) + k += math.abs(iy[j]) + if iy[j] < 0 then + i += pvqU(nn, k + 1) + end + until j <= 1 + return i +end + +@native local function expRotation1(X: { number }, xo: number, len: number, stride: number, c: number, s: number) + local ms = -s + local p = xo + 1 + for _ = 0, len - stride - 1 do + local x1 = X[p] + local x2 = X[p + stride] + X[p + stride] = c * x2 + s * x1 + X[p] = c * x1 + ms * x2 + p += 1 + end + p = xo + len - 2 * stride + for _ = len - 2 * stride - 1, 0, -1 do + local x1 = X[p] + local x2 = X[p + stride] + X[p + stride] = c * x2 + s * x1 + X[p] = c * x1 + ms * x2 + p -= 1 + end +end + +-- exp_rotation(X, len, dir = 1, stride, K, spread): the encoder's spreading rotation +@native local function expRotation(X: { number }, xo: number, len: number, stride: number, K: number, spread: number) + if 2 * K >= len or spread == 0 then + return + end + local factor = SPREAD_FACTOR[spread] + local gain = len / (len + factor * K) + local theta = 0.5 * (gain * gain) + local c = cos(0.5 * math.pi * theta) + local s = cos(0.5 * math.pi * (1 - theta)) + local stride2 = 0 + if len >= 8 * stride then + stride2 = 1 + while (stride2 * stride2 + stride2) * stride + rshift(stride, 2) < len do + stride2 += 1 + end + end + len = len // stride + for i = 0, stride - 1 do + local x = xo + i * len + expRotation1(X, x, len, 1, c, -s) + if stride2 ~= 0 then + expRotation1(X, x, len, stride2, s, -c) + end + end +end + +-- op_pvq_search: the K-pulse vector closest to X[xo + 1 .. xo + n] into iy[1..n] +@native local function pvqSearch(X: { number }, xo: number, n: number, K: number, iy: { number }, y: { number }, absx: { number }) + local sign = y -- reuse: y holds 2 * |pulses| during the search, signs kept in absx's sign + local xy, yy = 0, 0 + local pulsesLeft = K + for j = 1, n do + local v = X[xo + j] + absx[j] = if v < 0 then -v else v + sign[j] = 0 + iy[j] = 0 + end + if K > rshift(n, 1) then + local sum = 0 + for j = 1, n do + sum += absx[j] + end + if not (sum > 1e-15 and sum < 64) then + absx[1] = 1 + for j = 2, n do + absx[j] = 0 + end + sum = 1 + end + local rcp = (K + 0.8) / sum + for j = 1, n do + local p = floor(rcp * absx[j]) + iy[j] = p + yy += p * p + xy += absx[j] * p + sign[j] = 2 * p + pulsesLeft -= p + end + end + if pulsesLeft > n + 3 then + yy += pulsesLeft * pulsesLeft + pulsesLeft * sign[1] + iy[1] += pulsesLeft + pulsesLeft = 0 + end + for _ = 1, pulsesLeft do + yy += 1 + local best = 1 + local rxy = xy + absx[1] + local bestNum = rxy * rxy + local bestDen = yy + sign[1] + for j = 2, n do + rxy = xy + absx[j] + local num = rxy * rxy + local den = yy + sign[j] + if bestDen * num > den * bestNum then + bestDen, bestNum, best = den, num, j + end + end + xy += absx[best] + yy += sign[best] + sign[best] += 2 + iy[best] += 1 + end + for j = 1, n do + if X[xo + j] < 0 then + iy[j] = -iy[j] + end + end +end + +local SCRATCH_Y = table.create(256, 0) +local SCRATCH_A = table.create(256, 0) +local ROT = table.create(256, 0) + +@native local function algQuant(st: State, X: { number }, xo: number, n: number, K: number, enc: RE.Enc) + for j = 1, n do + ROT[j] = X[xo + j] + end + expRotation(ROT, 0, n, 1, K, st.spread) + local iy = st.iy + pvqSearch(ROT, 0, n, K, iy, SCRATCH_Y, SCRATCH_A) + encUint(enc, icwrs(n, iy), pvqU(n, K) + pvqU(n, K + 1)) +end + +@native local function computeQn(n: number, b: number, offset: number, pulseCap: number): number + local N2 = 2 * n - 1 + local qb = tdiv(b + N2 * offset, N2) + qb = imin(b - pulseCap - 32, qb) + qb = imin(64, qb) + if qb < 4 then + return 1 + end + local qn = rshift(EXP2_TABLE8[band(qb, 7) + 1], 14 - rshift(qb, 3)) + return lshift(rshift(qn + 1, 1), 1) +end + +-- quant_partition (encoder, B = 1, mono): returns nothing (no resynthesis) +@native local function quantPartition(st: State, bandI: number, X: { number }, xo: number, n: number, b: number, lm: number, enc: RE.Enc) + local split = false + if lm ~= -1 and n > 2 then + local base = CACHE_INDEX[(lm + 1) * NB_EBANDS + bandI + 1] + split = b > CACHE_BITS[base + CACHE_BITS[base + 1] + 1] + 12 + end + if split then + n = rshift(n, 1) + local yo = xo + n + lm -= 1 + -- compute_theta (mono split, B0 = 1: triangular pdf) + local pulseCap = LOGN[bandI + 1] + lm * 8 + local offset = (pulseCap // 2) - QTHETA_OFFSET + local qn = computeQn(n, b, offset, pulseCap) + local t0 = tellFrac(enc) + local itheta = 0 + if qn ~= 1 then + local emid, eside = 1e-15, 1e-15 + for j = 1, n do + emid += X[xo + j] * X[xo + j] + eside += X[yo + j] * X[yo + j] + end + local it = floor(0.5 + 16384 * 0.63662 * atan2(sqrt(eside), sqrt(emid))) + itheta = (it * qn + 8192) // 16384 + local h = rshift(qn, 1) + local ft = (h + 1) * (h + 1) + local fs = if itheta <= h then itheta + 1 else qn + 1 - itheta + local fl = if itheta <= h then rshift(itheta * (itheta + 1), 1) else ft - rshift((qn + 1 - itheta) * (qn + 2 - itheta), 1) + encEncode(enc, fl, fl + fs, ft) + itheta = (itheta * 16384) // qn + end + local qalloc = tellFrac(enc) - t0 + b -= qalloc + local delta + if itheta == 0 then + delta = -16384 + elseif itheta == 16384 then + delta = 16384 + else + local imid = bitexactCos(itheta) + local iside = bitexactCos(16384 - itheta) + delta = fracMul16((n - 1) * 128, bitexactLog2tan(iside, imid)) + end + local mbits = imax(0, imin(b, tdiv(b - delta, 2))) + local sbits = b - mbits + st.remaining -= qalloc + local rebalance = st.remaining + if mbits >= sbits then + quantPartition(st, bandI, X, xo, n, mbits, lm, enc) + rebalance = mbits - (rebalance - st.remaining) + if rebalance > 24 and itheta ~= 0 then + sbits += rebalance - 24 + end + quantPartition(st, bandI, X, yo, n, sbits, lm, enc) + else + quantPartition(st, bandI, X, yo, n, sbits, lm, enc) + rebalance = sbits - (rebalance - st.remaining) + if rebalance > 24 and itheta ~= 16384 then + mbits += rebalance - 24 + end + quantPartition(st, bandI, X, xo, n, mbits, lm, enc) + end + else + local q = bits2pulses(bandI, lm, b) + local currBits = pulses2bits(bandI, lm, q) + st.remaining -= currBits + while st.remaining < 0 and q > 0 do + st.remaining += currBits + q -= 1 + currBits = pulses2bits(bandI, lm, q) + st.remaining -= currBits + end + if q ~= 0 then + algQuant(st, X, xo, n, getPulses(q), enc) + end + end +end + +-- quant_band_stereo (encoder, N > 2, B = 1): the mid / side angle (step pdf), then mid and side as mono bands; +-- qn == 1 falls back to intensity stereo (with the inversion bit when there is room) +@native local function quantBandStereo(st: State, i: number, n: number, xo: number, b: number, enc: RE.Enc) + local L, R = st.X[1], st.X[2] + local pulseCap = LOGN[i + 1] + LM * 8 + local offset = (pulseCap // 2) - QTHETA_OFFSET + local qn = computeQn(n, b, offset, pulseCap) + -- stereo_itheta: the angle between mid and side energies + local emid, eside = 1e-15, 1e-15 + for j = 1, n do + local m = 0.5 * L[xo + j] + 0.5 * R[xo + j] + local sd = 0.5 * L[xo + j] - 0.5 * R[xo + j] + emid += m * m + eside += sd * sd + end + local itheta = floor(0.5 + 16384 * 0.63662 * atan2(sqrt(eside), sqrt(emid))) + local t0 = tellFrac(enc) + @native local function intensityStereo() + local left, right = st.bandE[i + 1], st.bandE[NB_EBANDS + i + 1] + local norm = 1e-15 + sqrt(1e-15 + left * left + right * right) + local a1, a2 = left / norm, right / norm + for j = 1, n do + L[xo + j] = a1 * L[xo + j] + a2 * R[xo + j] + end + end + if qn ~= 1 then + itheta = (itheta * qn + 8192) // 16384 + local p0 = 3 + local x0 = qn // 2 + local ft = p0 * (x0 + 1) + x0 + if itheta <= x0 then + encEncode(enc, p0 * itheta, p0 * (itheta + 1), ft) + else + encEncode(enc, (itheta - 1 - x0) + (x0 + 1) * p0, (itheta - x0) + (x0 + 1) * p0, ft) + end + itheta = (itheta * 16384) // qn + if itheta == 0 then + intensityStereo() + else + -- stereo_split: mid / side + for j = 1, n do + local l = 0.70710678 * L[xo + j] + local r = 0.70710678 * R[xo + j] + L[xo + j] = l + r + R[xo + j] = r - l + end + end + else + local inv = itheta > 8192 + if inv then + for j = 1, n do + R[xo + j] = -R[xo + j] + end + end + intensityStereo() + if b > 16 and st.remaining > 16 then + encBitLogp(enc, inv, 2) + end + itheta = 0 + end + local qalloc = tellFrac(enc) - t0 + b -= qalloc + local delta + if itheta == 0 then + delta = -16384 + elseif itheta == 16384 then + delta = 16384 + else + local imid = bitexactCos(itheta) + local iside = bitexactCos(16384 - itheta) + delta = fracMul16((n - 1) * 128, bitexactLog2tan(iside, imid)) + end + local mbits = imax(0, imin(b, tdiv(b - delta, 2))) + local sbits = b - mbits + st.remaining -= qalloc + local rebalance = st.remaining + if mbits >= sbits then + quantPartition(st, i, L, xo, n, mbits, LM, enc) + rebalance = mbits - (rebalance - st.remaining) + if rebalance > 24 and itheta ~= 0 then + sbits += rebalance - 24 + end + quantPartition(st, i, R, xo, n, sbits, LM, enc) + else + quantPartition(st, i, R, xo, n, sbits, LM, enc) + rebalance = sbits - (rebalance - st.remaining) + if rebalance > 24 and itheta ~= 16384 then + mbits += rebalance - 24 + end + quantPartition(st, i, L, xo, n, mbits, LM, enc) + end +end + +-- quant_all_bands (encoder): mono, dual stereo or mid / side stereo +@native local function quantAllBands(st: State, C: number, pulses: { number }, dualStereo: boolean, totalBits: number, + balance: number, enc: RE.Enc, codedBands: number, intensity: number) + for i = 0, NB_EBANDS - 1 do + local xo = M * EB[i + 1] + local nb = M * EB[i + 2] - M * EB[i + 1] + local t = tellFrac(enc) + if i ~= 0 then + balance -= t + end + local remainingBits = totalBits - t - 1 + st.remaining = remainingBits + local b + if i <= codedBands - 1 then + local currBalance = tdiv(balance, imin(3, codedBands - i)) + b = imax(0, imin(16383, imin(remainingBits + 1, pulses[i + 1] + currBalance))) + else + b = 0 + end + if dualStereo and i == intensity then + dualStereo = false + end + if C == 2 and dualStereo then + quantPartition(st, i, st.X[1], xo, nb, b // 2, LM, enc) + quantPartition(st, i, st.X[2], xo, nb, b // 2, LM, enc) + elseif C == 2 then + quantBandStereo(st, i, nb, xo, b, enc) + else + quantPartition(st, i, st.X[1], xo, nb, b, LM, enc) + end + balance += pulses[i + 1] + t + end +end + +@native function CeltEncoder.encodeFrame(st: State, pcm: { number }, base: number, stride: number, nbBytes: number): buffer + local C = st.channels + local work, tmp = st.work, st.tmp + local silent = true + for c = 1, C do + local inMem = st.inMem[c] + local m = st.preMem[c] + -- tmp[1..1080] = the last 120 pre-emphasised samples + this frame's 960 + for k = 1, OVERLAP do + tmp[k] = inMem[k] + end + for k = 0, N - 1 do + local x = pcm[base + k * stride + c - 1] * 32768 + if x ~= 0 then + silent = false + end + tmp[OVERLAP + k + 1] = x - m + m = PREEMPH * x + end + st.preMem[c] = m + for k = 1, OVERLAP do + inMem[k] = tmp[N + k] + end + local q = 420 -- (2N - (N + OVERLAP)) / 2 zeros at each end + for k = 1, q do + work[k] = 0 + work[2 * N - k + 1] = 0 + end + for k = 1, OVERLAP do + work[q + k] = tmp[k] * WINDOW[k] + work[q + N + k] = tmp[N + k] * WINDOW[OVERLAP - k + 1] + end + for k = OVERLAP + 1, N do + work[q + k] = tmp[k] + end + local X = st.X[c] + Mdct.forward(PLAN, work, 1, X, 1, 1, MDCT_SCALE) + for i = 0, NB_EBANDS - 1 do + local a, z = M * EB[i + 1] + 1, M * EB[i + 2] + local s = 1e-27 + for k = a, z do + s += X[k] * X[k] + end + local E = sqrt(s) + st.bandE[(c - 1) * NB_EBANDS + i + 1] = E + st.bandLogE[(c - 1) * NB_EBANDS + i + 1] = log(E) / log(2) - E_MEANS[i + 1] + local g = 1 / (1e-27 + E) + for k = a, z do + X[k] *= g + end + end + end + local enc = RE.new(nbBytes) + local totalBits = nbBytes * 8 + local oldE = st.oldBandE + if silent then + encBitLogp(enc, true, 15) + enc.nbits_total += totalBits - tell(enc) + RE.done(enc) + for i = 1, 2 * NB_EBANDS do + oldE[i] = -28 + end + st.frames += 1 + return enc.buf + end + encBitLogp(enc, false, 15) + if tell(enc) + 16 <= totalBits then + encBitLogp(enc, false, 1) -- no post-filter + end + if tell(enc) + 3 <= totalBits then + encBitLogp(enc, false, 3) -- not transient + end + local intra = st.frames == 0 + if tell(enc) + 3 <= totalBits then + encBitLogp(enc, intra, 3) + else + intra = false + end + if C == 1 then + for i = 1, NB_EBANDS do + oldE[i] = max(oldE[i], oldE[NB_EBANDS + i]) + end + end + quantCoarseEnergy(st, intra, enc, C, totalBits, nbBytes) + -- tf_encode: no changes + do + local budget = totalBits + local tt = tell(enc) + local logp = 4 + if tt + logp + 1 <= budget then + budget -= 1 + end + for _ = 0, NB_EBANDS - 1 do + if tt + logp <= budget then + encBitLogp(enc, false, logp) + tt = tell(enc) + end + logp = 5 + end + -- tf_select is only coded when it changes something: not for LM 3 without changes + local _ = TF_SELECT + end + if tell(enc) + 4 <= totalBits then + encIcdf(enc, st.spread, SPREAD_ICDF, 5) + end + local cap = {} + for i = 0, NB_EBANDS - 1 do + local Nw = (EB[i + 2] - EB[i + 1]) * 2 ^ LM + cap[i + 1] = rshift((CACHE_CAPS[NB_EBANDS * (2 * LM + C - 1) + i + 1] + 64) * C * Nw, 2) + end + local offsets = table.create(NB_EBANDS, 0) + local total8 = totalBits * 8 + local t = tellFrac(enc) + for i = 0, NB_EBANDS - 1 do + if t + 6 * 8 < total8 and 0 < cap[i + 1] then + encBitLogp(enc, false, 6) -- no dynamic allocation boost + t = tellFrac(enc) + end + end + if t + 48 <= total8 then + encIcdf(enc, 5, TRIM_ICDF, 7) + end + local bits = nbBytes * 64 - tellFrac(enc) - 1 + local pulses, fineQuant, finePriority = table.create(NB_EBANDS, 0), table.create(NB_EBANDS, 0), table.create(NB_EBANDS, 0) + local codedBands, balance, intensity, dualStereo = computeAllocation(offsets, cap, 5, bits, pulses, fineQuant, finePriority, C, enc, st.dual) + quantFineEnergy(st, fineQuant, enc, C) + quantAllBands(st, C, pulses, dualStereo, nbBytes * 64, balance, enc, codedBands, intensity) + quantEnergyFinalise(st, fineQuant, finePriority, totalBits - tell(enc), enc, C) + RE.done(enc) + if C == 1 then + for i = 1, NB_EBANDS do + oldE[NB_EBANDS + i] = oldE[i] + end + end + st.frames += 1 + st.lastError = enc.error + return enc.buf +end + +CeltEncoder.FRAME = N +CeltEncoder.DELAY = OVERLAP -- the decoder's output lags the input by the MDCT overlap +return CeltEncoder +end +__FILES["codecs/audio/Opus/CeltTables"] = function() + +-- codecs/audio/Opus/CeltTables: from libopus celt/static_modes_float.h and celt/quant_bands.c (BSD, licenses/). +return { +logN400 = { + 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 16, 16, 16, 21, 21, 24, 29, 34, 36, +}, +cache_index50 = { + -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 0, 0, 41, 41, 41, 82, 82, 123, 164, 200, 222, 0, 0, 0, + 0, 0, 0, 0, 0, 41, 41, 41, 41, 123, 123, 123, 164, 164, 240, 266, 283, 295, 41, 41, 41, 41, 41, 41, + 41, 41, 123, 123, 123, 123, 240, 240, 240, 266, 266, 305, 318, 328, 336, 123, 123, 123, 123, 123, 123, 123, 123, 240, + 240, 240, 240, 305, 305, 305, 318, 318, 343, 351, 358, 364, 240, 240, 240, 240, 240, 240, 240, 240, 305, 305, 305, 305, + 343, 343, 343, 351, 351, 370, 376, 382, 387, +}, +cache_bits50 = { + 40, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 40, 15, 23, 28, 31, 34, 36, + 38, 39, 41, 42, 43, 44, 45, 46, 47, 47, 49, 50, 51, 52, 53, 54, 55, 55, 57, 58, 59, 60, 61, 62, + 63, 63, 65, 66, 67, 68, 69, 70, 71, 71, 40, 20, 33, 41, 48, 53, 57, 61, 64, 66, 69, 71, 73, 75, + 76, 78, 80, 82, 85, 87, 89, 91, 92, 94, 96, 98, 101, 103, 105, 107, 108, 110, 112, 114, 117, 119, 121, 123, + 124, 126, 128, 40, 23, 39, 51, 60, 67, 73, 79, 83, 87, 91, 94, 97, 100, 102, 105, 107, 111, 115, 118, 121, + 124, 126, 129, 131, 135, 139, 142, 145, 148, 150, 153, 155, 159, 163, 166, 169, 172, 174, 177, 179, 35, 28, 49, 65, + 78, 89, 99, 107, 114, 120, 126, 132, 136, 141, 145, 149, 153, 159, 165, 171, 176, 180, 185, 189, 192, 199, 205, 211, + 216, 220, 225, 229, 232, 239, 245, 251, 21, 33, 58, 79, 97, 112, 125, 137, 148, 157, 166, 174, 182, 189, 195, 201, + 207, 217, 227, 235, 243, 251, 17, 35, 63, 86, 106, 123, 139, 152, 165, 177, 187, 197, 206, 214, 222, 230, 237, 250, + 25, 31, 55, 75, 91, 105, 117, 128, 138, 146, 154, 161, 168, 174, 180, 185, 190, 200, 208, 215, 222, 229, 235, 240, + 245, 255, 16, 36, 65, 89, 110, 128, 144, 159, 173, 185, 196, 207, 217, 226, 234, 242, 250, 11, 41, 74, 103, 128, + 151, 172, 191, 209, 225, 241, 255, 9, 43, 79, 110, 138, 163, 186, 207, 227, 246, 12, 39, 71, 99, 123, 144, 164, + 182, 198, 214, 228, 241, 253, 9, 44, 81, 113, 142, 168, 192, 214, 235, 255, 7, 49, 90, 127, 160, 191, 220, 247, + 6, 51, 95, 134, 170, 203, 234, 7, 47, 87, 123, 155, 184, 212, 237, 6, 52, 97, 137, 174, 208, 240, 5, 57, + 106, 151, 192, 231, 5, 59, 111, 158, 202, 243, 5, 55, 103, 147, 187, 224, 5, 60, 113, 161, 206, 248, 4, 65, + 122, 175, 224, 4, 67, 127, 182, 234, +}, +cache_caps50 = { + 224, 224, 224, 224, 224, 224, 224, 224, 160, 160, 160, 160, 185, 185, 185, 178, 178, 168, 134, 61, 37, 224, 224, 224, + 224, 224, 224, 224, 224, 240, 240, 240, 240, 207, 207, 207, 198, 198, 183, 144, 66, 40, 160, 160, 160, 160, 160, 160, + 160, 160, 185, 185, 185, 185, 193, 193, 193, 183, 183, 172, 138, 64, 38, 240, 240, 240, 240, 240, 240, 240, 240, 207, + 207, 207, 207, 204, 204, 204, 193, 193, 180, 143, 66, 40, 185, 185, 185, 185, 185, 185, 185, 185, 193, 193, 193, 193, + 193, 193, 193, 183, 183, 172, 138, 65, 39, 207, 207, 207, 207, 207, 207, 207, 207, 204, 204, 204, 204, 201, 201, 201, + 188, 188, 176, 141, 66, 40, 193, 193, 193, 193, 193, 193, 193, 193, 193, 193, 193, 193, 194, 194, 194, 184, 184, 173, + 139, 65, 39, 204, 204, 204, 204, 204, 204, 204, 204, 201, 201, 201, 201, 198, 198, 198, 187, 187, 175, 140, 66, 40, +}, +e_prob_model = { + 72, 127, 65, 129, 66, 128, 65, 128, 64, 128, 62, 128, 64, 128, 64, 128, 92, 78, 92, 79, 92, 78, 90, 79, + 116, 41, 115, 40, 114, 40, 132, 26, 132, 26, 145, 17, 161, 12, 176, 10, 177, 11, 24, 179, 48, 138, 54, 135, + 54, 132, 53, 134, 56, 133, 55, 132, 55, 132, 61, 114, 70, 96, 74, 88, 75, 88, 87, 74, 89, 66, 91, 67, + 100, 59, 108, 50, 120, 40, 122, 37, 97, 43, 78, 50, 83, 78, 84, 81, 88, 75, 86, 74, 87, 71, 90, 73, + 93, 74, 93, 74, 109, 40, 114, 36, 117, 34, 117, 34, 143, 17, 145, 18, 146, 19, 162, 12, 165, 10, 178, 7, + 189, 6, 190, 8, 177, 9, 23, 178, 54, 115, 63, 102, 66, 98, 69, 99, 74, 89, 71, 91, 73, 91, 78, 89, + 86, 80, 92, 66, 93, 64, 102, 59, 103, 60, 104, 60, 117, 52, 123, 44, 138, 35, 133, 31, 97, 38, 77, 45, + 61, 90, 93, 60, 105, 42, 107, 41, 110, 45, 116, 38, 113, 38, 112, 38, 124, 26, 132, 27, 136, 19, 140, 20, + 155, 14, 159, 16, 158, 18, 170, 13, 177, 10, 187, 8, 192, 6, 175, 9, 159, 10, 21, 178, 59, 110, 71, 86, + 75, 85, 84, 83, 91, 66, 88, 73, 87, 72, 92, 75, 98, 72, 105, 58, 107, 54, 115, 52, 114, 55, 112, 56, + 129, 51, 132, 40, 150, 33, 140, 29, 98, 35, 77, 42, 42, 121, 96, 66, 108, 43, 111, 40, 117, 44, 123, 32, + 120, 36, 119, 33, 127, 33, 134, 34, 139, 21, 147, 23, 152, 20, 158, 25, 154, 26, 166, 21, 173, 16, 184, 13, + 184, 10, 150, 13, 139, 15, 22, 178, 63, 114, 74, 82, 84, 83, 92, 82, 103, 62, 96, 72, 96, 67, 101, 73, + 107, 72, 113, 55, 118, 52, 125, 52, 118, 52, 117, 55, 135, 49, 137, 39, 157, 32, 145, 29, 97, 33, 77, 40, +}, +} +end +__FILES["codecs/audio/Opus/Decoder"] = @native function() + + + +-- codecs/audio/Opus/Decoder: the Opus decoder proper (libopus src/opus_decoder.c and opus_multistream_decoder.c). +-- SILK / hybrid / CELT mode switching, redundant CELT frames of mode transitions, cross-fades, PLC, multistream. +local RD = __include("codecs/entropy/RangeCoder/Decoder") +local Packet = __include("codecs/audio/Opus/Packet") +local Celt = __include("codecs/audio/Opus/Celt") +local Silk = __include("codecs/audio/Opus/Silk") + +local Decoder = {} + +local MODE_SILK, MODE_HYBRID, MODE_CELT = Packet.MODE_SILK_ONLY, Packet.MODE_HYBRID, Packet.MODE_CELT_ONLY +local BW_NB, BW_MB, BW_WB, BW_SWB = Packet.BW_NB, Packet.BW_MB, Packet.BW_WB, Packet.BW_SWB +local F20, F10, F5, F2_5 = 960, 480, 240, 120 +local min, max = math.min, math.max +local readu8 = buffer.readu8 + +local WINDOW = Celt.window +local TRANS = table.create(F5 * 2, 0) +local REDUND = table.create(F5 * 2, 0) +local SILKTMP = table.create(F10 * 2, 0) +local SILENCE = buffer.create(2) +buffer.writeu8(SILENCE, 0, 0xFF) +buffer.writeu8(SILENCE, 1, 0xFF) +local EMPTY_EC = RD.new(buffer.create(0), 0, 0) +local OFFS = table.create(48, 0) +local SIZES = table.create(48, 0) + +type State = { + channels: number, + celt: any, + silk: any, + ctrl: any, + stream_channels: number, + frame_size: number, + mode: number, + bandwidth: number, + prev_mode: number, + prev_redundancy: boolean, + last_packet_duration: number, + rangeFinal: number, +} + +@native function Decoder.new(channels: number): State + return { + channels = channels, + celt = Celt.new(channels), + silk = Silk.new(channels), + ctrl = { + nChannelsAPI = channels, + nChannelsInternal = channels, + API_sampleRate = 48000, + internalSampleRate = 16000, + payloadSize_ms = 20, + }, + stream_channels = channels, + frame_size = 120, + mode = 0, + bandwidth = 0, + prev_mode = 0, + prev_redundancy = false, + last_packet_duration = 0, + rangeFinal = 0, + } +end + +@native function Decoder.reset(st: State) + Celt.reset(st.celt) + Silk.reset(st.silk) + st.stream_channels = st.channels + st.frame_size = 120 + st.mode = 0 + st.bandwidth = 0 + st.prev_mode = 0 + st.prev_redundancy = false + st.last_packet_duration = 0 + st.rangeFinal = 0 +end + +-- out = w^2 * in2 + (1 - w^2) * in1 over `overlap` samples per channel +@native local function smoothFade(in1: { number }, b1: number, in2: { number }, b2: number, out: { number }, bo: number, overlap: number, ch: number) + for c = 0, ch - 1 do + for i = 0, overlap - 1 do + local w = WINDOW[i + 1] + w *= w + local k = i * ch + c + out[bo + k] = w * in2[b2 + k] + (1 - w) * in1[b1 + k] + end + end +end + +@native local function decodeFrame(st: State, buf: buffer?, off: number, len: number, pcm: { number }, pbase: number, frameSize: number): number + local ch = st.channels + local celt = st.celt + if frameSize < F2_5 then + return -2 + end + frameSize = min(frameSize, 2880) + local data = buf + if len <= 1 then + data = nil + frameSize = min(frameSize, st.frame_size) + end + local audiosize, mode, bandwidth + local dec = EMPTY_EC + if data then + audiosize = st.frame_size + mode = st.mode + bandwidth = st.bandwidth + dec = RD.new(data, off, len) + else + audiosize = frameSize + mode = if st.prev_redundancy then MODE_CELT else st.prev_mode + bandwidth = 0 + if mode == 0 then + for i = 0, audiosize * ch - 1 do + pcm[pbase + i] = 0 + end + return audiosize + end + if audiosize > F20 then + repeat + local ret = decodeFrame(st, nil, 0, 0, pcm, pbase, min(audiosize, F20)) + if ret < 0 then + return ret + end + pbase += ret * ch + audiosize -= ret + until audiosize <= 0 + return frameSize + elseif audiosize < F20 then + if audiosize > F10 then + audiosize = F10 + elseif mode ~= MODE_SILK and audiosize > F5 and audiosize < F10 then + audiosize = F5 + end + end + end + local celtAccum = mode ~= MODE_CELT + local transition = false + if data and st.prev_mode > 0 + and ((mode == MODE_CELT and st.prev_mode ~= MODE_CELT and not st.prev_redundancy) + or (mode ~= MODE_CELT and st.prev_mode == MODE_CELT)) then + transition = true + end + if transition and mode == MODE_CELT then + decodeFrame(st, nil, 0, 0, TRANS, 1, min(F5, audiosize)) + end + if audiosize > frameSize then + return -1 + end + frameSize = audiosize + + if mode ~= MODE_CELT then + local tooSmall = frameSize < F10 + local sarr, sbase = pcm, pbase + if tooSmall then + sarr, sbase = SILKTMP, 1 + end + if st.prev_mode == MODE_CELT then + Silk.reset(st.silk) + end + local ctrl = st.ctrl + ctrl.payloadSize_ms = max(10, 1000 * audiosize // 48000) + if data then + ctrl.nChannelsInternal = st.stream_channels + if mode == MODE_SILK then + ctrl.internalSampleRate = if bandwidth == BW_NB then 8000 elseif bandwidth == BW_MB then 12000 else 16000 + else + ctrl.internalSampleRate = 16000 + end + end + local lost = if data == nil then 1 else 0 + local decoded = 0 + repeat + local ret, n = Silk.decode(st.silk, ctrl, lost, decoded == 0, dec, sarr, sbase + decoded * ch) + if ret ~= 0 or n <= 0 then + if lost ~= 0 or n <= 0 then + n = frameSize - decoded + for i = 0, n * ch - 1 do + sarr[sbase + decoded * ch + i] = 0 + end + else + return -3 + end + end + decoded += n + until decoded >= frameSize + if tooSmall then + for i = 0, frameSize * ch - 1 do + pcm[pbase + i] = SILKTMP[i + 1] + end + end + end + + local startBand = 0 + local redundancy, celtToSilk = false, false + local redundancyBytes = 0 + if mode ~= MODE_CELT and data and RD.tell(dec) + 17 + (if mode == MODE_HYBRID then 20 else 0) <= 8 * len then + if mode == MODE_HYBRID then + redundancy = RD.bitLogp(dec, 12) + else + redundancy = true + end + if redundancy then + celtToSilk = RD.bitLogp(dec, 1) + redundancyBytes = if mode == MODE_HYBRID then RD.uint(dec, 256) + 2 else len - bit32.rshift(RD.tell(dec) + 7, 3) + len -= redundancyBytes + if len * 8 < RD.tell(dec) then + len = 0 + redundancyBytes = 0 + redundancy = false + end + dec.storage -= redundancyBytes + end + end + if mode ~= MODE_CELT then + startBand = 17 + end + if redundancy then + transition = false + end + if transition and mode ~= MODE_CELT then + decodeFrame(st, nil, 0, 0, TRANS, 1, min(F5, audiosize)) + end + if bandwidth ~= 0 then + celt["end"] = if bandwidth == BW_NB then 13 elseif bandwidth == BW_MB or bandwidth == BW_WB then 17 elseif bandwidth == BW_SWB then 19 else 21 + end + celt.stream_channels = st.stream_channels + local redundantRng = 0 + if redundancy and celtToSilk then + celt.start = 0 + Celt.decode(celt, data, off + len, redundancyBytes, REDUND, 1, F5, nil, false) + redundantRng = celt.rng + end + celt.start = startBand + local celtRet = 0 + if mode ~= MODE_SILK then + local celtFrameSize = min(F20, frameSize) + if mode ~= st.prev_mode and st.prev_mode > 0 and not st.prev_redundancy then + Celt.reset(celt) + end + celtRet = Celt.decode(celt, data, off, len, pcm, pbase, celtFrameSize, if data then dec else nil, celtAccum) + st.rangeFinal = celt.rng + else + if st.prev_mode == MODE_HYBRID and not (redundancy and celtToSilk and st.prev_redundancy) then + celt.start = 0 + Celt.decode(celt, SILENCE, 0, 2, pcm, pbase, F2_5, nil, celtAccum) + end + st.rangeFinal = if data then dec.rng else 0 + end + if redundancy and not celtToSilk then + Celt.reset(celt) + celt.start = 0 + Celt.decode(celt, data, off + len, redundancyBytes, REDUND, 1, F5, nil, false) + redundantRng = celt.rng + local b = pbase + ch * (frameSize - F2_5) + smoothFade(pcm, b, REDUND, 1 + ch * F2_5, pcm, b, F2_5, ch) + end + if redundancy and celtToSilk and (st.prev_mode ~= MODE_SILK or st.prev_redundancy) then + for i = 0, F2_5 * ch - 1 do + pcm[pbase + i] = REDUND[1 + i] + end + smoothFade(REDUND, 1 + ch * F2_5, pcm, pbase + ch * F2_5, pcm, pbase + ch * F2_5, F2_5, ch) + end + if transition then + if audiosize >= F5 then + for i = 0, ch * F2_5 - 1 do + pcm[pbase + i] = TRANS[1 + i] + end + smoothFade(TRANS, 1 + ch * F2_5, pcm, pbase + ch * F2_5, pcm, pbase + ch * F2_5, F2_5, ch) + else + smoothFade(TRANS, 1, pcm, pbase, pcm, pbase, F2_5, ch) + end + end + if len <= 1 then + st.rangeFinal = 0 + else + st.rangeFinal = bit32.bxor(st.rangeFinal, redundantRng) + end + st.prev_mode = mode + st.prev_redundancy = redundancy and not celtToSilk + if celtRet < 0 then + return celtRet + end + return audiosize +end + +-- opus_decode_native (buf nil or len 0: conceal frameSize samples) +@native function Decoder.decode(st: State, buf: buffer?, off: number, len: number, pcm: { number }, pbase: number, frameSize: number, selfDelimited: boolean?): (number, number) + local ch = st.channels + if buf == nil or len == 0 then + if frameSize % 120 ~= 0 then + return -1, 0 + end + local count = 0 + repeat + local ret = decodeFrame(st, nil, 0, 0, pcm, pbase + count * ch, frameSize - count) + if ret <= 0 then + return if ret < 0 then ret else -3, 0 + end + count += ret + until count >= frameSize + st.last_packet_duration = count + return count, 0 + end + local b = buf :: buffer + local toc = readu8(b, off) + local packetMode = Packet.mode(toc) + local packetBandwidth = Packet.bandwidth(toc) + local packetFrameSize = Packet.samplesPerFrame(toc, 48000) + local packetChannels = Packet.channels(toc) + local count, _, packetOffset = Packet.parse(b, off, len, OFFS, SIZES, selfDelimited) + if count < 0 then + return -4, 0 + end + if count * packetFrameSize > frameSize then + return -2, 0 + end + st.mode = packetMode + st.bandwidth = packetBandwidth + st.frame_size = packetFrameSize + st.stream_channels = packetChannels + local nb = 0 + for i = 1, count do + local ret = decodeFrame(st, b, OFFS[i], SIZES[i], pcm, pbase + nb * ch, frameSize - nb) + if ret < 0 then + return ret, 0 + end + nb += ret + end + st.last_packet_duration = nb + return nb, packetOffset +end + +-- multistream (channel mapping families 0 / 1 / 255) + +type MS = { + channels: number, + streams: number, + coupled: number, + mapping: { number }, + decoders: { State }, + tmp: { number }, +} + +@native function Decoder.newMultistream(channels: number, streams: number, coupled: number, mapping: { number }): MS + local decs = {} + for s = 0, streams - 1 do + decs[s + 1] = Decoder.new(if s < coupled then 2 else 1) + end + return { + channels = channels, + streams = streams, + coupled = coupled, + mapping = mapping, + decoders = decs, + tmp = table.create(5760 * 2, 0), + } +end + +@native function Decoder.resetMultistream(ms: MS) + for _, d in ms.decoders do + Decoder.reset(d) + end +end + +@native local function copyOut(ms: MS, id: number, src: { number }, sc: number, sstride: number, pcm: { number }, pbase: number, n: number) + local nch = ms.channels + for c = 0, nch - 1 do + if ms.mapping[c + 1] == id then + local o = pbase + c + local s = 1 + sc + for _ = 1, n do + pcm[o] = src[s] + o += nch + s += sstride + end + end + end +end + +-- opus_multistream_decode_native +@native function Decoder.decodeMultistream(ms: MS, buf: buffer?, off: number, len: number, pcm: { number }, pbase: number, frameSize: number): number + local doPlc = buf == nil or len == 0 + frameSize = min(frameSize, 5760) + if not doPlc and len < 2 * ms.streams - 1 then + return -4 + end + local tmp = ms.tmp + for s = 0, ms.streams - 1 do + local d = ms.decoders[s + 1] + if not doPlc and len <= 0 then + return -3 + end + local ret, packetOffset = Decoder.decode(d, if doPlc then nil else buf, off, if doPlc then 0 else len, tmp, 1, frameSize, s ~= ms.streams - 1) + if not doPlc then + off += packetOffset + len -= packetOffset + end + if ret <= 0 then + return if ret < 0 then ret else -3 + end + frameSize = ret + if s < ms.coupled then + copyOut(ms, s * 2, tmp, 0, 2, pcm, pbase, frameSize) + copyOut(ms, s * 2 + 1, tmp, 1, 2, pcm, pbase, frameSize) + else + copyOut(ms, s + ms.coupled, tmp, 0, 1, pcm, pbase, frameSize) + end + end + local nch = ms.channels + for c = 0, nch - 1 do + if ms.mapping[c + 1] == 255 then + local o = pbase + c + for _ = 1, frameSize do + pcm[o] = 0 + o += nch + end + end + end + return frameSize +end + +@native function Decoder.writeF32(src: { number }, base: number, count: number, gain: number, out: buffer, o: number) + local writef32 = buffer.writef32 + if gain == 1 then + for i = base + 1, base + count do + writef32(out, o, src[i]) + o += 4 + end + else + for i = base + 1, base + count do + writef32(out, o, src[i] * gain) + o += 4 + end + end +end + +@native function Decoder.writeDownmix(src: { number }, base: number, n: number, srcCh: number, matrix: { number }, gain: number, out: buffer, o: number) + local writef32 = buffer.writef32 + local p = base + for _ = 1, n do + local l, r = 0, 0 + for c = 0, srcCh - 1 do + local v = src[p + c + 1] + l += v * matrix[c * 2 + 1] + r += v * matrix[c * 2 + 2] + end + writef32(out, o, l * gain) + writef32(out, o + 4, r * gain) + o += 8 + p += srcCh + end +end + +return Decoder +end +__FILES["codecs/audio/Opus/Mdct"] = @native function() + + + +-- codecs/audio/Opus/Mdct: CELT inverse MDCT (libopus celt/mdct.c clt_mdct_backward) over the kiss_fft radix 5 / 3 / 4 / 2 stages. +-- N = 1920 >> shift (FFT sizes 480 .. 60). Kept apart from codecs/audio/Mdct: CELT keeps only the middle N / 2 of the +-- full IMDCT, so the shared transform was 2-3x slower and changed the output bits. +local Mdct = {} + +local sin, cos, pi = math.sin, math.cos, math.pi + +type Plan = { + n: number, + factors: { number }, + bitrev: { number }, + twr: { number }, + twi: { number }, + trig: { number }, -- MDCT twiddles: (-sin, cos) pairs, N / 2 values + fr: { number }, + fi: { number }, +} + +local FACTORS = { + [0] = { 5, 96, 3, 32, 4, 8, 2, 4, 4, 1 }, + [1] = { 5, 48, 3, 16, 4, 4, 4, 1 }, + [2] = { 5, 24, 3, 8, 2, 4, 4, 1 }, + [3] = { 5, 12, 3, 4, 4, 1 }, +} + +@native local function bitrevTable(f: { number }, fout: number, fpos: number, fstride: number, factors: { number }, fi: number) + local p = factors[fi] + local m = factors[fi + 1] + if m == 1 then + for j = 0, p - 1 do + f[fpos + 1] = fout + j + fpos += fstride + end + else + for j = 0, p - 1 do + bitrevTable(f, fout, fpos, fstride * p, factors, fi + 2) + fpos += fstride + fout += m + end + end +end + +local plans: { Plan } = {} +for shift = 0, 3 do + local N = 1920 // 2 ^ shift + local n = N // 4 + local factors = FACTORS[shift] + local bitrev = table.create(n, 0) + bitrevTable(bitrev, 0, 0, 1, factors, 1) + local twr, twi = table.create(n, 0), table.create(n, 0) + for k = 0, n - 1 do + local ph = -2 * pi * k / n + twr[k + 1] = cos(ph) + twi[k + 1] = sin(ph) + end + local N2, N4 = N // 2, N // 4 + local trig = table.create(N2, 0) + for i = 0, N4 - 1 do + trig[2 * i + 1] = -sin(2 * pi * (i + 0.125) / N) + trig[2 * i + 2] = cos(2 * pi * (i + 0.125) / N) + end + plans[shift + 1] = { + n = n, + factors = factors, + bitrev = bitrev, + twr = twr, + twi = twi, + trig = trig, + fr = table.create(n, 0), + fi = table.create(n, 0), + } +end + +@native local function bfly2(fr: { number }, fi: { number }, N: number) + local tw = 0.7071067812 + local p = 1 + for _ = 1, N do + local tr, ti = fr[p + 4], fi[p + 4] + fr[p + 4] = fr[p] - tr + fi[p + 4] = fi[p] - ti + fr[p] += tr + fi[p] += ti + local a, b = fr[p + 5], fi[p + 5] + tr = (a + b) * tw + ti = (b - a) * tw + fr[p + 5] = fr[p + 1] - tr + fi[p + 5] = fi[p + 1] - ti + fr[p + 1] += tr + fi[p + 1] += ti + tr = fi[p + 6] + ti = -fr[p + 6] + fr[p + 6] = fr[p + 2] - tr + fi[p + 6] = fi[p + 2] - ti + fr[p + 2] += tr + fi[p + 2] += ti + a, b = fr[p + 7], fi[p + 7] + tr = (b - a) * tw + ti = -(b + a) * tw + fr[p + 7] = fr[p + 3] - tr + fi[p + 7] = fi[p + 3] - ti + fr[p + 3] += tr + fi[p + 3] += ti + p += 8 + end +end + +@native local function bfly4(fr: { number }, fi: { number }, fstride: number, twr: { number }, twi: { number }, m: number, N: number, mm: number) + if m == 1 then + local p = 1 + for _ = 1, N do + local r0, i0 = fr[p], fi[p] + local r1, i1 = fr[p + 1], fi[p + 1] + local r2, i2 = fr[p + 2], fi[p + 2] + local r3, i3 = fr[p + 3], fi[p + 3] + local s0r, s0i = r0 - r2, i0 - i2 + r0 += r2 + i0 += i2 + local s1r, s1i = r1 + r3, i1 + i3 + fr[p + 2] = r0 - s1r + fi[p + 2] = i0 - s1i + fr[p] = r0 + s1r + fi[p] = i0 + s1i + s1r, s1i = r1 - r3, i1 - i3 + fr[p + 1] = s0r + s1i + fi[p + 1] = s0i - s1r + fr[p + 3] = s0r - s1i + fi[p + 3] = s0i + s1r + p += 4 + end + else + local m2, m3 = 2 * m, 3 * m + for i = 0, N - 1 do + local p = i * mm + 1 + local t1, t2, t3 = 1, 1, 1 + for _ = 0, m - 1 do + local ar, ai = fr[p + m], fi[p + m] + local wr, wi = twr[t1], twi[t1] + local s0r, s0i = ar * wr - ai * wi, ar * wi + ai * wr + ar, ai = fr[p + m2], fi[p + m2] + wr, wi = twr[t2], twi[t2] + local s1r, s1i = ar * wr - ai * wi, ar * wi + ai * wr + ar, ai = fr[p + m3], fi[p + m3] + wr, wi = twr[t3], twi[t3] + local s2r, s2i = ar * wr - ai * wi, ar * wi + ai * wr + local f0r, f0i = fr[p], fi[p] + local s5r, s5i = f0r - s1r, f0i - s1i + f0r += s1r + f0i += s1i + local s3r, s3i = s0r + s2r, s0i + s2i + local s4r, s4i = s0r - s2r, s0i - s2i + fr[p + m2] = f0r - s3r + fi[p + m2] = f0i - s3i + t1 += fstride + t2 += fstride * 2 + t3 += fstride * 3 + fr[p] = f0r + s3r + fi[p] = f0i + s3i + fr[p + m] = s5r + s4i + fi[p + m] = s5i - s4r + fr[p + m3] = s5r - s4i + fi[p + m3] = s5i + s4r + p += 1 + end + end + end +end + +@native local function bfly3(fr: { number }, fi: { number }, fstride: number, twr: { number }, twi: { number }, m: number, N: number, mm: number) + local m2 = 2 * m + local epi3i = twi[fstride * m + 1] + for i = 0, N - 1 do + local p = i * mm + 1 + local t1, t2 = 1, 1 + for _ = 1, m do + local ar, ai = fr[p + m], fi[p + m] + local wr, wi = twr[t1], twi[t1] + local s1r, s1i = ar * wr - ai * wi, ar * wi + ai * wr + ar, ai = fr[p + m2], fi[p + m2] + wr, wi = twr[t2], twi[t2] + local s2r, s2i = ar * wr - ai * wi, ar * wi + ai * wr + local s3r, s3i = s1r + s2r, s1i + s2i + local s0r, s0i = s1r - s2r, s1i - s2i + t1 += fstride + t2 += fstride * 2 + local f0r, f0i = fr[p], fi[p] + local fmr, fmi = f0r - s3r * 0.5, f0i - s3i * 0.5 + s0r *= epi3i + s0i *= epi3i + fr[p] = f0r + s3r + fi[p] = f0i + s3i + fr[p + m2] = fmr + s0i + fi[p + m2] = fmi - s0r + fr[p + m] = fmr - s0i + fi[p + m] = fmi + s0r + p += 1 + end + end +end + +@native local function bfly5(fr: { number }, fi: { number }, fstride: number, twr: { number }, twi: { number }, m: number, N: number, mm: number) + local yar, yai = twr[fstride * m + 1], twi[fstride * m + 1] + local ybr, ybi = twr[fstride * 2 * m + 1], twi[fstride * 2 * m + 1] + for i = 0, N - 1 do + local p0 = i * mm + 1 + local p1, p2, p3, p4 = p0 + m, p0 + 2 * m, p0 + 3 * m, p0 + 4 * m + for u = 0, m - 1 do + local s0r, s0i = fr[p0], fi[p0] + local k = u * fstride + local ar, ai = fr[p1], fi[p1] + local wr, wi = twr[k + 1], twi[k + 1] + local s1r, s1i = ar * wr - ai * wi, ar * wi + ai * wr + ar, ai = fr[p2], fi[p2] + wr, wi = twr[2 * k + 1], twi[2 * k + 1] + local s2r, s2i = ar * wr - ai * wi, ar * wi + ai * wr + ar, ai = fr[p3], fi[p3] + wr, wi = twr[3 * k + 1], twi[3 * k + 1] + local s3r, s3i = ar * wr - ai * wi, ar * wi + ai * wr + ar, ai = fr[p4], fi[p4] + wr, wi = twr[4 * k + 1], twi[4 * k + 1] + local s4r, s4i = ar * wr - ai * wi, ar * wi + ai * wr + + local s7r, s7i = s1r + s4r, s1i + s4i + local s10r, s10i = s1r - s4r, s1i - s4i + local s8r, s8i = s2r + s3r, s2i + s3i + local s9r, s9i = s2r - s3r, s2i - s3i + + fr[p0] = s0r + (s7r + s8r) + fi[p0] = s0i + (s7i + s8i) + + local s5r = s0r + (s7r * yar + s8r * ybr) + local s5i = s0i + (s7i * yar + s8i * ybr) + local s6r = s10i * yai + s9i * ybi + local s6i = -(s10r * yai + s9r * ybi) + fr[p1] = s5r - s6r + fi[p1] = s5i - s6i + fr[p4] = s5r + s6r + fi[p4] = s5i + s6i + + local s11r = s0r + (s7r * ybr + s8r * yar) + local s11i = s0i + (s7i * ybr + s8i * yar) + local s12r = s9i * yai - s10i * ybi + local s12i = s10r * ybi - s9r * yai + fr[p2] = s11r + s12r + fi[p2] = s11i + s12i + fr[p3] = s11r - s12r + fi[p3] = s11i - s12i + + p0 += 1 + p1 += 1 + p2 += 1 + p3 += 1 + p4 += 1 + end + end +end + +-- opus_fft_impl (bit-reversed input) +@native local function fftImpl(pl: Plan) + local factors = pl.factors + local fr, fi, twr, twi = pl.fr, pl.fi, pl.twr, pl.twi + local fstride = { 1 } + local L = 0 + local m + repeat + local p = factors[2 * L + 1] + m = factors[2 * L + 2] + fstride[L + 2] = fstride[L + 1] * p + L += 1 + until m == 1 + m = factors[2 * L] + for i = L - 1, 0, -1 do + local m2 = if i ~= 0 then factors[2 * i] else 1 + local radix = factors[2 * i + 1] + if radix == 2 then + bfly2(fr, fi, fstride[i + 1]) + elseif radix == 4 then + bfly4(fr, fi, fstride[i + 1], twr, twi, m, fstride[i + 1], m2) + elseif radix == 3 then + bfly3(fr, fi, fstride[i + 1], twr, twi, m, fstride[i + 1], m2) + else + bfly5(fr, fi, fstride[i + 1], twr, twi, m, fstride[i + 1], m2) + end + m = m2 + end +end + +-- clt_mdct_backward +@native function Mdct.backward(inp: { number }, inBase: number, out: { number }, outBase: number, window: { number }, overlap: number, shift: number, stride: number) + local pl = plans[shift + 1] + local N4 = pl.n + local N2 = N4 * 2 + local trig = pl.trig + local bitrev = pl.bitrev + local fr, fi = pl.fr, pl.fi + -- pre-rotate, storing in bit-reversed order (real and imaginary swapped: an FFT is used instead of an IFFT) + local xp1 = inBase + local xp2 = inBase + stride * (N2 - 1) + for i = 0, N4 - 1 do + local x1 = inp[xp1] + local x2 = inp[xp2] + local t0, t1 = trig[2 * i + 1], trig[2 * i + 2] + local rev = bitrev[i + 1] + 1 + fi[rev] = x2 * t1 + x1 * t0 + fr[rev] = x1 * t1 - x2 * t0 + xp1 += 2 * stride + xp2 -= 2 * stride + end + fftImpl(pl) + local h = outBase + (overlap // 2) + for k = 0, N4 - 1 do + local re = fi[k + 1] + local im = fr[k + 1] + local t0, t1 = trig[2 * k + 1], trig[2 * k + 2] + out[h + 2 * k] = re * t1 + im * t0 + out[h + N2 - 1 - 2 * k] = re * t0 - im * t1 + end + -- mirror on both sides for TDAC + local xp = outBase + overlap - 1 + local yp = outBase + for i = 0, overlap // 2 - 1 do + local x1 = out[xp] + local x2 = out[yp] + local w1 = window[i + 1] + local w2 = window[overlap - i] + out[yp] = x2 * w2 - x1 * w1 + out[xp] = x2 * w1 + x1 * w2 + xp -= 1 + yp += 1 + end +end + +return Mdct +end +__FILES["codecs/audio/Opus/Packet"] = @native function() + + + +-- 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 +local band, rshift = bit32.band, bit32.rshift + +Packet.MODE_SILK_ONLY = 1000 +Packet.MODE_HYBRID = 1001 +Packet.MODE_CELT_ONLY = 1002 + +-- bandwidths as in libopus (OPUS_BANDWIDTH_NARROWBAND .. FULLBAND) +Packet.BW_NB = 1101 +Packet.BW_MB = 1102 +Packet.BW_WB = 1103 +Packet.BW_SWB = 1104 +Packet.BW_FB = 1105 + +@native function Packet.mode(toc: number): number + if band(toc, 0x80) ~= 0 then + return Packet.MODE_CELT_ONLY + elseif band(toc, 0x60) == 0x60 then + return Packet.MODE_HYBRID + else + return Packet.MODE_SILK_ONLY + end +end + +@native function Packet.bandwidth(toc: number): number + if band(toc, 0x80) ~= 0 then + local bw = 1102 + band(rshift(toc, 5), 3) + if bw == 1102 then + bw = 1101 + end + return bw + elseif band(toc, 0x60) == 0x60 then + return if band(toc, 0x10) ~= 0 then 1105 else 1104 + else + return 1101 + band(rshift(toc, 5), 3) + end +end + +@native function Packet.channels(toc: number): number + return if band(toc, 4) ~= 0 then 2 else 1 +end + +@native function Packet.samplesPerFrame(toc: number, Fs: number): number + if band(toc, 0x80) ~= 0 then + local a = band(rshift(toc, 3), 3) + return bit32.lshift(Fs, a) // 400 + elseif band(toc, 0x60) == 0x60 then + return if band(toc, 0x08) ~= 0 then Fs // 50 else Fs // 100 + else + local a = band(rshift(toc, 3), 3) + if a == 3 then + return Fs * 60 // 1000 + end + return bit32.lshift(Fs, a) // 100 + end +end + +@native function Packet.samples(buf: buffer, off: number, len: number): number + if len < 1 then + return -1 + end + local toc = readu8(buf, off) + local c = band(toc, 3) + local count + if c == 0 then + count = 1 + elseif c ~= 3 then + count = 2 + else + if len < 2 then + return -1 + end + count = band(readu8(buf, off + 1), 0x3F) + end + local n = count * Packet.samplesPerFrame(toc, 48000) + if n * 25 > 48000 * 3 then + return -1 + end + return n +end + +@native local function parseSize(buf: buffer, p: number, len: number): (number, number) + if len < 1 then + return -1, -1 + end + local b0 = readu8(buf, p) + if b0 < 252 then + return 1, b0 + elseif len < 2 then + return -1, -1 + end + return 2, 4 * readu8(buf, p + 1) + b0 +end + +-- opus_packet_parse_impl; self-delimited packets (multistream) carry an explicit size for the last frame +@native function Packet.parse(buf: buffer, off: number, len: number, offsets: { number }, sizes: { number }, selfDelimited: boolean?): (number, number, number) + if len < 1 then + return -1, 0, 0 + end + local toc = readu8(buf, off) + local framesize = Packet.samplesPerFrame(toc, 48000) + local p = off + 1 + len -= 1 + local lastSize = len + local count + local cbr = false + local pad = 0 + local c = band(toc, 3) + if c == 0 then + count = 1 + elseif c == 1 then + count = 2 + cbr = true + if not selfDelimited then + if band(len, 1) ~= 0 then + return -1, toc, 0 + end + lastSize = len // 2 + sizes[1] = lastSize + end + elseif c == 2 then + count = 2 + local bytes, s = parseSize(buf, p, len) + if bytes < 0 then + return -1, toc, 0 + end + len -= bytes + if s < 0 or s > len then + return -1, toc, 0 + end + sizes[1] = s + p += bytes + lastSize = len - s + else + if len < 1 then + return -1, toc, 0 + end + local ch = readu8(buf, p) + p += 1 + count = band(ch, 0x3F) + if count <= 0 or framesize * count > 5760 then + return -1, toc, 0 + end + len -= 1 + if band(ch, 0x40) ~= 0 then + local pb + repeat + if len <= 0 then + return -1, toc, 0 + end + pb = readu8(buf, p) + p += 1 + len -= 1 + local tmp = if pb == 255 then 254 else pb + len -= tmp + pad += tmp + until pb ~= 255 + end + if len < 0 then + return -1, toc, 0 + end + cbr = band(ch, 0x80) == 0 + if not cbr then + lastSize = len + for i = 1, count - 1 do + local bytes, s = parseSize(buf, p, len) + if bytes < 0 then + return -1, toc, 0 + end + len -= bytes + if s < 0 or s > len then + return -1, toc, 0 + end + sizes[i] = s + p += bytes + lastSize -= bytes + s + end + if lastSize < 0 then + return -1, toc, 0 + end + elseif not selfDelimited then + lastSize = len // count + if lastSize * count ~= len then + return -1, toc, 0 + end + for i = 1, count - 1 do + sizes[i] = lastSize + end + end + end + if selfDelimited then + local bytes, s = parseSize(buf, p, len) + if bytes < 0 then + return -1, toc, 0 + end + len -= bytes + if s < 0 or s > len then + return -1, toc, 0 + end + p += bytes + sizes[count] = s + if cbr then + if s * count > len then + return -1, toc, 0 + end + for i = 1, count - 1 do + sizes[i] = s + end + elseif bytes + s > lastSize then + return -1, toc, 0 + end + else + if lastSize > 1275 then + return -1, toc, 0 + end + sizes[count] = lastSize + end + for i = 1, count do + offsets[i] = p + p += sizes[i] + end + return count, toc, pad + (p - off) +end + +return Packet +end +__FILES["codecs/audio/Opus/Silk"] = @native function() + + + +-- 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; BSD, licenses/). C int32 / int16 values are Luau numbers; int32 x int32 products are split to stay below 2^53. +local RD = __include("codecs/entropy/RangeCoder/Decoder") +local T = __include("codecs/audio/Opus/SilkTables") + +local icdf = RD.icdf +local bitLogp = RD.bitLogp +local countlz = bit32.countlz +local floor = math.floor + +local Silk = {} + +local P2 = table.create(64, 0) +for s = 1, 63 do + P2[s] = 2 ^ s +end +@native local function p2(s: number): number + if s == 0 then + return 1 + end + return P2[s] +end + +@native local function s16(x: number): number + x = x % 65536 + if x >= 32768 then + return x - 65536 + end + return x +end + +@native local function i32(x: number): number + x = x % 4294967296 + if x >= 2147483648 then + return x - 4294967296 + end + return x +end + +@native local function sat16(x: number): number + if x > 32767 then + return 32767 + elseif x < -32768 then + return -32768 + end + return x +end + +@native local function addSat32(a: number, b: number): number + local s = a + b + if s > 2147483647 then + return 2147483647 + elseif s < -2147483648 then + return -2147483648 + end + return s +end + +@native local function subSat32(a: number, b: number): number + local s = a - b + if s > 2147483647 then + return 2147483647 + elseif s < -2147483648 then + return -2147483648 + end + return s +end + +-- silk_CLZ32 of a non-negative int32 +@native local function clz32(x: number): number + return countlz(x) +end + +-- silk_SMULWW (64-bit form): (a * b) >> 16, exact +@native local function mulww(a: number, b: number): number + return a * (b // 65536) + (a * (b % 65536)) // 65536 +end + +-- floor(a * b / 2^s) for int32 a, b and s >= 16, exact +@native local function mulshr(a: number, b: number, s: number): number + local t = a * (b // 65536) + (a * (b % 65536)) // 65536 + if s == 16 then + return t + end + return t // P2[s - 16] +end + +@native local function smmul(a: number, b: number): number + return mulshr(a, b, 32) +end + +-- silk_RSHIFT_ROUND (shift >= 1) +@native local function rround(a: number, s: number): number + return (a + p2(s - 1)) // P2[s] +end + +@native local function lshiftSat32(a: number, sh: number): number + if sh == 0 then + return a + end + local m = P2[sh] + local lo, hi = -2147483648 // m, 2147483647 // m + if a < lo then + a = lo + elseif a > hi then + a = hi + end + return a * m +end + +-- C integer division (truncation toward zero) +@native local function tdiv(a: number, b: number): number + local q = a / b + if q >= 0 then + return floor(q) + end + return -floor(-q) +end + +-- low 32 bits of a * b, as int32 +@native local function imul32(a: number, b: number): number + a = a % 4294967296 + local ah, al = a // 65536, a % 65536 + return i32(((ah * b) % 65536) * 65536 + al * b) +end + +@native local function silkRand(seed: number): number + return i32(907633515 + imul32(seed, 196314165)) +end + +@native local function rshift(a: number, s: number): number + if s == 0 then + return a + end + return a // P2[s] +end + +@native local function silkINVERSE32_varQ(b32: number, Qres: number): number + local b_headrm = clz32(math.abs(b32)) - 1 + local b32_nrm = b32 * p2(b_headrm) + local b32_inv = tdiv(536870911, b32_nrm // 65536) + local result = b32_inv * 65536 + local err_Q32 = i32((536870912 - (b32_nrm * b32_inv) // 65536) * 8) + result = i32(result + mulww(err_Q32, b32_inv)) + local lshift = 61 - b_headrm - Qres + if lshift <= 0 then + return lshiftSat32(result, -lshift) + elseif lshift < 32 then + return result // P2[lshift] + end + return 0 +end + +@native local function silkDIV32_varQ(a32: number, b32: number, Qres: number): number + local a_headrm = clz32(math.abs(a32)) - 1 + local a32_nrm = a32 * p2(a_headrm) + local b_headrm = clz32(math.abs(b32)) - 1 + local b32_nrm = b32 * p2(b_headrm) + local b32_inv = tdiv(536870911, b32_nrm // 65536) + local result = (a32_nrm * s16(b32_inv)) // 65536 + a32_nrm = i32(a32_nrm - i32(smmul(b32_nrm, result) * 8)) + result = result + (a32_nrm * s16(b32_inv)) // 65536 + local lshift = 29 + a_headrm - b_headrm - Qres + if lshift < 0 then + return lshiftSat32(result, -lshift) + elseif lshift < 32 then + return rshift(result, lshift) + end + return 0 +end + +@native local function silkLog2lin(inLog_Q7: number): number + if inLog_Q7 < 0 then + return 0 + elseif inLog_Q7 >= 3967 then + return 2147483647 + end + local out = p2(inLog_Q7 // 128) + local frac_Q7 = inLog_Q7 % 128 + local t = frac_Q7 + (frac_Q7 * (128 - frac_Q7) * -174) // 65536 + if inLog_Q7 < 2048 then + out = out + (out * t) // 128 + else + out = out + (out // 128) * t + end + return out +end + +@native local function silkSQRT_APPROX(x: number): number + if x <= 0 then + return 0 + end + local lz = clz32(x) + local rot = 24 - lz + local r + if rot == 0 then + r = x + elseif rot < 0 then + r = bit32.lrotate(x, -rot) + else + r = bit32.rrotate(x, rot) + end + local frac_Q7 = bit32.band(r, 0x7f) + local y = if bit32.band(lz, 1) ~= 0 then 32768 else 46214 + y = y // p2(lz // 2) + y = y + (y * (213 * frac_Q7)) // 65536 + return y +end + +-- silk_sum_sqr_shift: energy, shift +@native local function sumSqrShift(x: { number }, xo: number, len: number): (number, number) + local shft = 31 - clz32(len) + local nrg = len + local i = 0 + while i < len - 1 do + local a, b = x[xo + i], x[xo + i + 1] + nrg = i32(nrg + rshift(a * a + b * b, shft)) + i += 2 + end + if i < len then + local a = x[xo + i] + nrg = i32(nrg + rshift(a * a, shft)) + end + shft = math.max(0, shft + 3 - clz32(nrg)) + nrg = 0 + i = 0 + while i < len - 1 do + local a, b = x[xo + i], x[xo + i + 1] + nrg = i32(nrg + rshift(a * a + b * b, shft)) + i += 2 + end + if i < len then + local a = x[xo + i] + nrg = i32(nrg + rshift(a * a, shft)) + end + return nrg, shft +end + +-- silk_bwexpander (int16 coefficients), ar 1-based +@native local function bwexpander(ar: { number }, d: number, chirp_Q16: number) + local chirp_minus_one_Q16 = chirp_Q16 - 65536 + for i = 1, d - 1 do + ar[i] = s16((chirp_Q16 * ar[i] + 32768) // 65536) + chirp_Q16 += (chirp_Q16 * chirp_minus_one_Q16 + 32768) // 65536 + end + ar[d] = s16((chirp_Q16 * ar[d] + 32768) // 65536) +end + +@native local function bwexpander32(ar: { number }, d: number, chirp_Q16: number) + local chirp_minus_one_Q16 = chirp_Q16 - 65536 + for i = 1, d - 1 do + ar[i] = i32(mulww(chirp_Q16, ar[i])) + chirp_Q16 += (chirp_Q16 * chirp_minus_one_Q16 + 32768) // 65536 + end + ar[d] = i32(mulww(chirp_Q16, ar[d])) +end + +-- silk_LPC_fit: a_QIN (int32, QIN) -> a_QOUT (int16, QOUT) +@native local function lpcFit(a_QOUT: { number }, a_QIN: { number }, QOUT: number, QIN: number, d: number) + local sh = QIN - QOUT + local idx = 0 + local i = 0 + while i < 10 do + local maxabs = 0 + for k = 1, d do + local absval = math.abs(a_QIN[k]) + if absval > maxabs then + maxabs = absval + idx = k - 1 + end + end + maxabs = rround(maxabs, sh) + if maxabs > 32767 then + maxabs = math.min(maxabs, 163838) + local chirp_Q16 = 65470 - tdiv((maxabs - 32767) * 16384, (maxabs * (idx + 1)) // 4) + bwexpander32(a_QIN, d, chirp_Q16) + else + break + end + i += 1 + end + if i == 10 then + for k = 1, d do + a_QOUT[k] = sat16(rround(a_QIN[k], sh)) + a_QIN[k] = a_QOUT[k] * P2[sh] + end + else + for k = 1, d do + a_QOUT[k] = s16(rround(a_QIN[k], sh)) + end + end +end + +local A_LIMIT = 16773022 +local INV_GAIN_MIN = 107374 +local Atmp_QA = table.create(16, 0) + +-- RSHIFT_ROUND64(SMULL(a, b), Q) +@native local function mulRound(a: number, b: number, Q: number): number + if Q == 1 then + local p = a * b + return p // 2 + p % 2 + end + if Q - 1 >= 16 then + return (mulshr(a, b, Q - 1) + 1) // 2 + end + return ((a * b) // P2[Q - 1] + 1) // 2 +end + +@native local function lpcInversePredGainQA(A_QA: { number }, order: number): number + local invGain_Q30 = 1073741824 + local k = order - 1 + while k > 0 do + local ak = A_QA[k + 1] + if ak > A_LIMIT or ak < -A_LIMIT then + return 0 + end + local rc_Q31 = -(ak * 128) + local rc_mult1_Q30 = 1073741824 - smmul(rc_Q31, rc_Q31) + invGain_Q30 = smmul(invGain_Q30, rc_mult1_Q30) * 4 + if invGain_Q30 < INV_GAIN_MIN then + return 0 + end + local mult2Q = 32 - clz32(math.abs(rc_mult1_Q30)) + local rc_mult2 = silkINVERSE32_varQ(rc_mult1_Q30, mult2Q + 30) + for n = 0, (k + 1) // 2 - 1 do + local tmp1 = A_QA[n + 1] + local tmp2 = A_QA[k - n] + local t64 = mulRound(subSat32(tmp1, mulRound(tmp2, rc_Q31, 31)), rc_mult2, mult2Q) + if t64 > 2147483647 or t64 < -2147483648 then + return 0 + end + A_QA[n + 1] = t64 + t64 = mulRound(subSat32(tmp2, mulRound(tmp1, rc_Q31, 31)), rc_mult2, mult2Q) + if t64 > 2147483647 or t64 < -2147483648 then + return 0 + end + A_QA[k - n] = t64 + end + k -= 1 + end + local a0 = A_QA[1] + if a0 > A_LIMIT or a0 < -A_LIMIT then + return 0 + end + local rc_Q31 = -(a0 * 128) + local rc_mult1_Q30 = 1073741824 - smmul(rc_Q31, rc_Q31) + invGain_Q30 = smmul(invGain_Q30, rc_mult1_Q30) * 4 + if invGain_Q30 < INV_GAIN_MIN then + return 0 + end + return invGain_Q30 +end + +@native local function lpcInversePredGain(A_Q12: { number }, order: number): number + local DC_resp = 0 + for k = 1, order do + DC_resp += A_Q12[k] + Atmp_QA[k] = A_Q12[k] * 4096 + end + if DC_resp >= 4096 then + return 0 + end + return lpcInversePredGainQA(Atmp_QA, order) +end + +local ordering16 = { 0, 15, 8, 7, 4, 11, 12, 3, 2, 13, 10, 5, 6, 9, 14, 1 } +local ordering10 = { 0, 9, 6, 3, 4, 5, 8, 1, 2, 7 } +local cos_LSF_QA = table.create(16, 0) +local polyP = table.create(9, 0) +local polyQ = table.create(9, 0) +local a32_QA1 = table.create(16, 0) +local LSFCos = T.LSFCosTab_FIX_Q12 + +-- out[0..dd] (1-based storage), from interleaved cLSF starting at C index c0 +@native local function findPoly(out: { number }, cLSF: { number }, c0: number, dd: number) + out[1] = 65536 + out[2] = -cLSF[c0 + 1] + for k = 1, dd - 1 do + local ftmp = cLSF[c0 + 2 * k + 1] + out[k + 2] = out[k] * 2 - (ftmp * out[k + 1] + 32768) // 65536 + for n = k, 2, -1 do + out[n + 1] += out[n - 1] - (ftmp * out[n] + 32768) // 65536 + end + out[2] -= ftmp + end +end + +-- silk_NLSF2A: a_Q12 (1-based, d entries) from NLSF (1-based) +@native local function nlsf2a(a_Q12: { number }, NLSF: { number }, d: number) + local ordering = if d == 16 then ordering16 else ordering10 + for k = 1, d do + local nl = NLSF[k] + local f_int = nl // 256 + local f_frac = nl - f_int * 256 + local cos_val = LSFCos[f_int + 1] + local delta = LSFCos[f_int + 2] - cos_val + cos_LSF_QA[ordering[k] + 1] = (cos_val * 256 + delta * f_frac + 8) // 16 + end + local dd = d // 2 + findPoly(polyP, cos_LSF_QA, 0, dd) + findPoly(polyQ, cos_LSF_QA, 1, dd) + for k = 0, dd - 1 do + local Ptmp = polyP[k + 2] + polyP[k + 1] + local Qtmp = polyQ[k + 2] - polyQ[k + 1] + a32_QA1[k + 1] = -Qtmp - Ptmp + a32_QA1[d - k] = Qtmp - Ptmp + end + lpcFit(a_Q12, a32_QA1, 12, 17, d) + local i = 0 + while lpcInversePredGain(a_Q12, d) == 0 and i < 16 do + bwexpander32(a32_QA1, d, 65536 - P2[i + 1]) + for k = 1, d do + a_Q12[k] = s16((a32_QA1[k] + 16) // 32) + end + i += 1 + end +end + +-- silk_LPC_analysis_filter: out[oo + ix] for ix in [0, len), from inp[io + ix]; B 1-based Q12 +@native local function lpcAnalysisFilter(out: { number }, oo: number, inp: { number }, io: number, B: { number }, len: number, d: number) + for ix = d, len - 1 do + local base = io + ix - 1 + local acc = 0 + for j = 0, d - 1 do + acc += inp[base - j] * B[j + 1] + end + local out32_Q12 = i32(inp[base + 1] * 4096 - acc) + out[oo + ix] = sat16((out32_Q12 + 2048) // 4096) + end + for j = 0, d - 1 do + out[oo + j] = 0 + end +end + +local CB_NB_MB = { + nVectors = 32, + order = 10, + quantStepSize_Q16 = 11796, + CB1_NLSF_Q8 = T.NLSF_CB1_NB_MB_Q8, + CB1_Wght_Q9 = T.NLSF_CB1_Wght_Q9, + CB1_iCDF = T.NLSF_CB1_iCDF_NB_MB, + pred_Q8 = T.NLSF_PRED_NB_MB_Q8, + ec_sel = T.NLSF_CB2_SELECT_NB_MB, + ec_iCDF = T.NLSF_CB2_iCDF_NB_MB, + deltaMin_Q15 = T.NLSF_DELTA_MIN_NB_MB_Q15, +} +local CB_WB = { + nVectors = 32, + order = 16, + quantStepSize_Q16 = 9830, + CB1_NLSF_Q8 = T.NLSF_CB1_WB_Q8, + CB1_Wght_Q9 = T.NLSF_CB1_WB_Wght_Q9, + CB1_iCDF = T.NLSF_CB1_iCDF_WB, + pred_Q8 = T.NLSF_PRED_WB_Q8, + ec_sel = T.NLSF_CB2_SELECT_WB, + ec_iCDF = T.NLSF_CB2_iCDF_WB, + deltaMin_Q15 = T.NLSF_DELTA_MIN_WB_Q15, +} + +local ec_ix = table.create(16, 0) +local pred_Q8 = table.create(16, 0) +local res_Q10 = table.create(16, 0) + +@native local function nlsfUnpack(CB: any, CB1_index: number) + local order = CB.order + local sel = CB.ec_sel + local pq = CB.pred_Q8 + local p = CB1_index * order // 2 + for i = 0, order - 1, 2 do + p += 1 + local entry = sel[p] + ec_ix[i + 1] = (bit32.band(entry // 2, 7)) * 9 + pred_Q8[i + 1] = pq[i + bit32.band(entry, 1) * (order - 1) + 1] + ec_ix[i + 2] = (bit32.band(entry // 32, 7)) * 9 + pred_Q8[i + 2] = pq[i + bit32.band(entry // 16, 1) * (order - 1) + 2] + end +end + +@native local function nlsfStabilize(NLSF: { number }, NDeltaMin: { number }, L: number) + local loops = 0 + while loops < 20 do + local min_diff = NLSF[1] - NDeltaMin[1] + local I = 0 + for i = 1, L - 1 do + local diff = NLSF[i + 1] - (NLSF[i] + NDeltaMin[i + 1]) + if diff < min_diff then + min_diff = diff + I = i + end + end + local diff = 32768 - (NLSF[L] + NDeltaMin[L + 1]) + if diff < min_diff then + min_diff = diff + I = L + end + if min_diff >= 0 then + return + end + if I == 0 then + NLSF[1] = NDeltaMin[1] + elseif I == L then + NLSF[L] = 32768 - NDeltaMin[L + 1] + else + local min_center = 0 + for k = 0, I - 1 do + min_center += NDeltaMin[k + 1] + end + min_center += NDeltaMin[I + 1] // 2 + local max_center = 32768 + for k = L, I + 1, -1 do + max_center -= NDeltaMin[k + 1] + end + max_center -= NDeltaMin[I + 1] // 2 + local c = (NLSF[I] + NLSF[I + 1] + 1) // 2 + -- silk_LIMIT_32(c, min_center, max_center) + if min_center > max_center then + if c > min_center then + c = min_center + elseif c < max_center then + c = max_center + end + else + if c > max_center then + c = max_center + elseif c < min_center then + c = min_center + end + end + c = s16(c) + NLSF[I] = s16(c - NDeltaMin[I + 1] // 2) + NLSF[I + 1] = s16(NLSF[I] + NDeltaMin[I + 1]) + end + loops += 1 + end + -- fall back: insertion sort, then clamp + for i = 2, L do + local value = NLSF[i] + local j = i - 1 + while j >= 1 and value < NLSF[j] do + NLSF[j + 1] = NLSF[j] + j -= 1 + end + NLSF[j + 1] = value + end + NLSF[1] = math.max(NLSF[1], NDeltaMin[1]) + for i = 2, L do + NLSF[i] = math.max(NLSF[i], sat16(NLSF[i - 1] + NDeltaMin[i])) + end + NLSF[L] = math.min(NLSF[L], 32768 - NDeltaMin[L + 1]) + for i = L - 1, 1, -1 do + NLSF[i] = math.min(NLSF[i], NLSF[i + 1] - NDeltaMin[i + 1]) + end +end + +-- silk_NLSF_decode: pNLSF_Q15 (1-based) from indices (1-based: [1] = CB1 index) +@native local function nlsfDecode(pNLSF_Q15: { number }, NLSFIndices: { number }, CB: any) + nlsfUnpack(CB, NLSFIndices[1]) + local order = CB.order + local step = CB.quantStepSize_Q16 + local out_Q10 = 0 + for i = order - 1, 0, -1 do + local pred = (out_Q10 * pred_Q8[i + 1]) // 256 + out_Q10 = NLSFIndices[i + 2] * 1024 + if out_Q10 > 0 then + out_Q10 -= 102 + elseif out_Q10 < 0 then + out_Q10 += 102 + end + out_Q10 = pred + (out_Q10 * step) // 65536 + res_Q10[i + 1] = out_Q10 + end + local base = NLSFIndices[1] * order + local cb, w = CB.CB1_NLSF_Q8, CB.CB1_Wght_Q9 + for i = 1, order do + local v = tdiv(res_Q10[i] * 16384, w[base + i]) + cb[base + i] * 128 + if v < 0 then + v = 0 + elseif v > 32767 then + v = 32767 + end + pNLSF_Q15[i] = v + end + nlsfStabilize(pNLSF_Q15, CB.deltaMin_Q15, order) +end + +local RES_COPY, RES_UP2, RES_IIR_FIR = 0, 1, 2 +local up2_hq_0 = { 1746, 14986, 39083 - 65536 } +local up2_hq_1 = { 6854, 25769, 55542 - 65536 } +local FIR12 = T.resampler_frac_FIR_12 +local delay_matrix_dec = { + { 4, 0, 2, 0, 0, 0 }, + { 0, 9, 4, 7, 4, 4 }, + { 0, 3, 12, 7, 7, 7 }, +} + +@native local function rateID(R: number): number + local a = R // 4096 - (if R > 16000 then 1 else 0) + if R > 24000 then + a = a // 2 + end + return math.min(5, a - 1) +end + +@native local function newResampler(): any + return { + sIIR = table.create(6, 0), + sFIR = table.create(8, 0), + delayBuf = table.create(96, 0), + buf = table.create(2 * 160 + 8, 0), + resampler_function = RES_COPY, + batchSize = 0, + invRatio_Q16 = 0, + inputDelay = 0, + Fs_in_kHz = 0, + Fs_out_kHz = 0, + } +end + +@native local function copyResampler(dst: any, src: any) + for i = 1, 6 do + dst.sIIR[i] = src.sIIR[i] + end + for i = 1, 8 do + dst.sFIR[i] = src.sFIR[i] + end + for i = 1, 96 do + dst.delayBuf[i] = src.delayBuf[i] + end + dst.resampler_function = src.resampler_function + dst.batchSize = src.batchSize + dst.invRatio_Q16 = src.invRatio_Q16 + dst.inputDelay = src.inputDelay + dst.Fs_in_kHz = src.Fs_in_kHz + dst.Fs_out_kHz = src.Fs_out_kHz +end + +@native local function resamplerInit(S: any, Fs_Hz_in: number, Fs_Hz_out: number): number + table.clear(S.sIIR) + table.clear(S.sFIR) + table.clear(S.delayBuf) + for i = 1, 6 do + S.sIIR[i] = 0 + end + for i = 1, 8 do + S.sFIR[i] = 0 + end + for i = 1, 96 do + S.delayBuf[i] = 0 + end + if (Fs_Hz_in ~= 8000 and Fs_Hz_in ~= 12000 and Fs_Hz_in ~= 16000) or Fs_Hz_out < Fs_Hz_in then + return -1 -- the decoder only upsamples (or copies) + end + S.inputDelay = delay_matrix_dec[rateID(Fs_Hz_in) + 1][rateID(Fs_Hz_out) + 1] or 0 + S.Fs_in_kHz = Fs_Hz_in // 1000 + S.Fs_out_kHz = Fs_Hz_out // 1000 + S.batchSize = S.Fs_in_kHz * 10 + local up2x = 0 + if Fs_Hz_out > Fs_Hz_in then + if Fs_Hz_out == Fs_Hz_in * 2 then + S.resampler_function = RES_UP2 + else + S.resampler_function = RES_IIR_FIR + up2x = 1 + end + else + S.resampler_function = RES_COPY + end + local inv = (Fs_Hz_in * p2(14 + up2x)) // Fs_Hz_out * 4 + while mulww(inv, Fs_Hz_out) < Fs_Hz_in * p2(up2x) do + inv += 1 + end + S.invRatio_Q16 = inv + return 0 +end + +-- silk_resampler_private_up2_HQ: out[oo + 2k], out[oo + 2k + 1] from inp[io + k] +@native local function up2HQ(S: { number }, out: { number }, oo: number, inp: { number }, io: number, len: number) + local s0, s1, s2, s3, s4, s5 = S[1], S[2], S[3], S[4], S[5], S[6] + local c00, c01, c02 = up2_hq_0[1], up2_hq_0[2], up2_hq_0[3] + local c10, c11, c12 = up2_hq_1[1], up2_hq_1[2], up2_hq_1[3] + for k = 0, len - 1 do + local in32 = inp[io + k] * 1024 + local Y = in32 - s0 + local X = (Y * c00) // 65536 + local out32_1 = s0 + X + s0 = in32 + X + Y = out32_1 - s1 + X = (Y * c01) // 65536 + local out32_2 = s1 + X + s1 = out32_1 + X + Y = out32_2 - s2 + X = Y + (Y * c02) // 65536 + out32_1 = s2 + X + s2 = out32_2 + X + out[oo + 2 * k] = sat16((out32_1 + 512) // 1024) + Y = in32 - s3 + X = (Y * c10) // 65536 + out32_1 = s3 + X + s3 = in32 + X + Y = out32_1 - s4 + X = (Y * c11) // 65536 + out32_2 = s4 + X + s4 = out32_1 + X + Y = out32_2 - s5 + X = Y + (Y * c12) // 65536 + out32_1 = s5 + X + s5 = out32_2 + X + out[oo + 2 * k + 1] = sat16((out32_1 + 512) // 1024) + end + S[1], S[2], S[3], S[4], S[5], S[6] = s0, s1, s2, s3, s4, s5 +end + +@native local function iirFirInterpol(out: { number }, oo: number, buf: { number }, max_index_Q16: number, incr: number): number + local index_Q16 = 0 + while index_Q16 < max_index_Q16 do + local ti = ((index_Q16 % 65536) * 12) // 65536 + local b = index_Q16 // 65536 + 1 -- buf is 1-based + local f0 = ti * 4 + local f1 = (11 - ti) * 4 + local res_Q15 = buf[b] * FIR12[f0 + 1] + + buf[b + 1] * FIR12[f0 + 2] + + buf[b + 2] * FIR12[f0 + 3] + + buf[b + 3] * FIR12[f0 + 4] + + buf[b + 4] * FIR12[f1 + 4] + + buf[b + 5] * FIR12[f1 + 3] + + buf[b + 6] * FIR12[f1 + 2] + + buf[b + 7] * FIR12[f1 + 1] + out[oo] = sat16((res_Q15 + 16384) // 32768) + oo += 1 + index_Q16 += incr + end + return oo +end + +@native local function iirFir(S: any, out: { number }, oo: number, inp: { number }, io: number, inLen: number) + local buf = S.buf + local sFIR = S.sFIR + for i = 1, 8 do + buf[i] = sFIR[i] + end + local incr = S.invRatio_Q16 + local nSamplesIn + while true do + nSamplesIn = math.min(inLen, S.batchSize) + up2HQ(S.sIIR, buf, 9, inp, io, nSamplesIn) + oo = iirFirInterpol(out, oo, buf, nSamplesIn * 131072, incr) + io += nSamplesIn + inLen -= nSamplesIn + if inLen > 0 then + local o = nSamplesIn * 2 + for i = 1, 8 do + buf[i] = buf[o + i] + end + else + break + end + end + local o = nSamplesIn * 2 + for i = 1, 8 do + sFIR[i] = buf[o + i] + end +end + +@native local function resampleBlock(S: any, out: { number }, oo: number, inp: { number }, io: number, len: number) + local f = S.resampler_function + if f == RES_IIR_FIR then + iirFir(S, out, oo, inp, io, len) + elseif f == RES_UP2 then + up2HQ(S.sIIR, out, oo, inp, io, len) + else + for i = 0, len - 1 do + out[oo + i] = inp[io + i] + end + end +end + +-- silk_resampler: out[1..] from inp[io .. io + inLen - 1] +@native local function resampler(S: any, out: { number }, inp: { number }, io: number, inLen: number) + local fin = S.Fs_in_kHz + local delay = S.inputDelay + local nSamples = fin - delay + local db = S.delayBuf + for i = 0, nSamples - 1 do + db[delay + i + 1] = inp[io + i] + end + resampleBlock(S, out, 1, db, 1, fin) + resampleBlock(S, out, 1 + S.Fs_out_kHz, inp, io + nSamples, inLen - fin) + for i = 0, delay - 1 do + db[i + 1] = inp[io + inLen - delay + i] + end +end + +@native local function newChannel(): any + return { + prev_gain_Q16 = 65536, + exc_Q14 = table.create(320, 0), + sLPC_Q14_buf = table.create(16, 0), + outBuf = table.create(480, 0), + lagPrev = 0, + LastGainIndex = 0, + fs_kHz = 0, + fs_API_hz = 0, + nb_subfr = 0, + frame_length = 0, + subfr_length = 0, + ltp_mem_length = 0, + LPC_order = 0, + prevNLSF_Q15 = table.create(16, 0), + first_frame_after_reset = 1, + pitch_lag_low_bits_iCDF = T.uniform4_iCDF, + pitch_contour_iCDF = T.pitch_contour_iCDF, + nFramesDecoded = 0, + nFramesPerPacket = 0, + ec_prevSignalType = 0, + ec_prevLagIndex = 0, + VAD_flags = { 0, 0, 0 }, + LBRR_flag = 0, + LBRR_flags = { 0, 0, 0 }, + resampler_state = newResampler(), + psNLSF_CB = CB_NB_MB, + indices = { + signalType = 0, + quantOffsetType = 0, + GainsIndices = { 0, 0, 0, 0 }, + NLSFIndices = table.create(17, 0), + NLSFInterpCoef_Q2 = 0, + lagIndex = 0, + contourIndex = 0, + PERIndex = 0, + LTPIndex = { 0, 0, 0, 0 }, + LTP_scaleIndex = 0, + Seed = 0, + }, + sCNG = { + CNG_exc_buf_Q14 = table.create(320, 0), + CNG_smth_NLSF_Q15 = table.create(16, 0), + CNG_synth_state = table.create(16, 0), + CNG_smth_Gain_Q16 = 0, + rand_seed = 3176576, + fs_kHz = 0, + }, + lossCnt = 0, + prevSignalType = 0, + sPLC = { + pitchL_Q8 = 0, + LTPCoef_Q14 = table.create(5, 0), + prevLPC_Q12 = table.create(16, 0), + last_frame_lost = 0, + rand_seed = 0, + randScale_Q14 = 0, + conc_energy = 0, + conc_energy_shift = 0, + prevLTP_scale_Q14 = 0, + prevGain_Q16 = { 65536, 65536 }, + fs_kHz = 0, + nb_subfr = 2, + subfr_length = 20, + }, + -- per-frame decoder control (silk_decoder_control) and scratch + ctrl = { + pitchL = { 0, 0, 0, 0 }, + Gains_Q16 = { 0, 0, 0, 0 }, + PredCoef_Q12 = { table.create(16, 0), table.create(16, 0) }, + LTPCoef_Q14 = table.create(20, 0), + LTP_scale_Q14 = 0, + }, + pulses = table.create(336, 0), + out = table.create(322, 0), -- samplesOut1_tmp: [1], [2] = the 2 buffered samples, frame from [3] + } +end + +@native local function decoderSetFs(ch: any, fs_kHz: number, fs_API_Hz: number): number + local ret = 0 + ch.subfr_length = 5 * fs_kHz + local frame_length = ch.nb_subfr * ch.subfr_length + if ch.fs_kHz ~= fs_kHz or ch.fs_API_hz ~= fs_API_Hz then + ret += resamplerInit(ch.resampler_state, fs_kHz * 1000, fs_API_Hz) + ch.fs_API_hz = fs_API_Hz + end + if ch.fs_kHz ~= fs_kHz or frame_length ~= ch.frame_length then + if fs_kHz == 8 then + ch.pitch_contour_iCDF = if ch.nb_subfr == 4 then T.pitch_contour_NB_iCDF else T.pitch_contour_10_ms_NB_iCDF + else + ch.pitch_contour_iCDF = if ch.nb_subfr == 4 then T.pitch_contour_iCDF else T.pitch_contour_10_ms_iCDF + end + if ch.fs_kHz ~= fs_kHz then + ch.ltp_mem_length = 20 * fs_kHz + if fs_kHz == 8 or fs_kHz == 12 then + ch.LPC_order = 10 + ch.psNLSF_CB = CB_NB_MB + else + ch.LPC_order = 16 + ch.psNLSF_CB = CB_WB + end + if fs_kHz == 16 then + ch.pitch_lag_low_bits_iCDF = T.uniform8_iCDF + elseif fs_kHz == 12 then + ch.pitch_lag_low_bits_iCDF = T.uniform6_iCDF + else + ch.pitch_lag_low_bits_iCDF = T.uniform4_iCDF + end + ch.first_frame_after_reset = 1 + ch.lagPrev = 100 + ch.LastGainIndex = 10 + ch.prevSignalType = 0 + local ob, sl = ch.outBuf, ch.sLPC_Q14_buf + for i = 1, 480 do + ob[i] = 0 + end + for i = 1, 16 do + sl[i] = 0 + end + end + ch.fs_kHz = fs_kHz + ch.frame_length = frame_length + end + return ret +end + +local LTP_gain_iCDF = { T.LTP_gain_iCDF_0, T.LTP_gain_iCDF_1, T.LTP_gain_iCDF_2 } +local LTP_vq_Q7 = { T.LTP_gain_vq_0, T.LTP_gain_vq_1, T.LTP_gain_vq_2 } +local LBRR_flags_iCDF = { T.LBRR_flags_2_iCDF, T.LBRR_flags_3_iCDF } + +@native local function decodeIndices(ch: any, d: any, FrameIndex: number, decode_LBRR: boolean, condCoding: number) + local ind = ch.indices + local Ix + if decode_LBRR or ch.VAD_flags[FrameIndex + 1] ~= 0 then + Ix = icdf(d, T.type_offset_VAD_iCDF, 1, 8) + 2 + else + Ix = icdf(d, T.type_offset_no_VAD_iCDF, 1, 8) + end + local signalType = Ix // 2 + ind.signalType = signalType + ind.quantOffsetType = Ix % 2 + local gi = ind.GainsIndices + if condCoding == 2 then + gi[1] = icdf(d, T.delta_gain_iCDF, 1, 8) + else + gi[1] = icdf(d, T.gain_iCDF, signalType * 8 + 1, 8) * 8 + gi[1] += icdf(d, T.uniform8_iCDF, 1, 8) + end + for i = 2, ch.nb_subfr do + gi[i] = icdf(d, T.delta_gain_iCDF, 1, 8) + end + local CB = ch.psNLSF_CB + local ni = ind.NLSFIndices + ni[1] = icdf(d, CB.CB1_iCDF, (signalType // 2) * CB.nVectors + 1, 8) + nlsfUnpack(CB, ni[1]) + for i = 1, CB.order do + Ix = icdf(d, CB.ec_iCDF, ec_ix[i] + 1, 8) + if Ix == 0 then + Ix -= icdf(d, T.NLSF_EXT_iCDF, 1, 8) + elseif Ix == 8 then + Ix += icdf(d, T.NLSF_EXT_iCDF, 1, 8) + end + ni[i + 1] = Ix - 4 + end + if ch.nb_subfr == 4 then + ind.NLSFInterpCoef_Q2 = icdf(d, T.NLSF_interpolation_factor_iCDF, 1, 8) + else + ind.NLSFInterpCoef_Q2 = 4 + end + if signalType == 2 then + local absolute = true + if condCoding == 2 and ch.ec_prevSignalType == 2 then + local delta = icdf(d, T.pitch_delta_iCDF, 1, 8) + if delta > 0 then + ind.lagIndex = s16(ch.ec_prevLagIndex + delta - 9) + absolute = false + end + end + if absolute then + ind.lagIndex = icdf(d, T.pitch_lag_iCDF, 1, 8) * (ch.fs_kHz // 2) + ind.lagIndex += icdf(d, ch.pitch_lag_low_bits_iCDF, 1, 8) + end + ch.ec_prevLagIndex = ind.lagIndex + ind.contourIndex = icdf(d, ch.pitch_contour_iCDF, 1, 8) + ind.PERIndex = icdf(d, T.LTP_per_index_iCDF, 1, 8) + local tab = LTP_gain_iCDF[ind.PERIndex + 1] + for k = 1, ch.nb_subfr do + ind.LTPIndex[k] = icdf(d, tab, 1, 8) + end + if condCoding == 0 then + ind.LTP_scaleIndex = icdf(d, T.LTPscale_iCDF, 1, 8) + else + ind.LTP_scaleIndex = 0 + end + end + ch.ec_prevSignalType = signalType + ind.Seed = icdf(d, T.uniform4_iCDF, 1, 8) +end + +local shell0, shell1, shell2, shell3 = T.shell_code_table0, T.shell_code_table1, T.shell_code_table2, T.shell_code_table3 +local shellOff = T.shell_code_table_offsets + +@native local function split(d: any, p: number, tab: { number }): (number, number) + if p > 0 then + local a = icdf(d, tab, shellOff[p + 1] + 1, 8) + return a, p - a + end + return 0, 0 +end + +@native local function shellDecoder(out: { number }, o: number, d: any, pulses4: number) + local p3a, p3b = split(d, pulses4, shell3) + local p2a, p2b = split(d, p3a, shell2) + local p1a, p1b = split(d, p2a, shell1) + out[o], out[o + 1] = split(d, p1a, shell0) + out[o + 2], out[o + 3] = split(d, p1b, shell0) + p1a, p1b = split(d, p2b, shell1) + out[o + 4], out[o + 5] = split(d, p1a, shell0) + out[o + 6], out[o + 7] = split(d, p1b, shell0) + p2a, p2b = split(d, p3b, shell2) + p1a, p1b = split(d, p2a, shell1) + out[o + 8], out[o + 9] = split(d, p1a, shell0) + out[o + 10], out[o + 11] = split(d, p1b, shell0) + p1a, p1b = split(d, p2b, shell1) + out[o + 12], out[o + 13] = split(d, p1a, shell0) + out[o + 14], out[o + 15] = split(d, p1b, shell0) +end + +local sum_pulses = table.create(20, 0) +local nLshifts = table.create(20, 0) +local signIcdf = { 0, 0 } + +-- pulses[1 .. frame_length (rounded up to 16)] +@native local function decodePulses(d: any, pulses: { number }, signalType: number, quantOffsetType: number, frame_length: number) + local RateLevelIndex = icdf(d, T.rate_levels_iCDF, (signalType // 2) * 9 + 1, 8) + local iter = frame_length // 16 + if iter * 16 < frame_length then + iter += 1 + end + local ppb = T.pulses_per_block_iCDF + for i = 1, iter do + nLshifts[i] = 0 + local s = icdf(d, ppb, RateLevelIndex * 18 + 1, 8) + while s == 17 do + nLshifts[i] += 1 + s = icdf(d, ppb, 9 * 18 + 1 + (if nLshifts[i] == 10 then 1 else 0), 8) + if nLshifts[i] > 30 then + break -- corrupt stream guard + end + end + sum_pulses[i] = s + end + for i = 1, iter do + local o = (i - 1) * 16 + 1 + if sum_pulses[i] > 0 then + shellDecoder(pulses, o, d, sum_pulses[i]) + else + for k = 0, 15 do + pulses[o + k] = 0 + end + end + end + local lsb = T.lsb_iCDF + for i = 1, iter do + local nLS = nLshifts[i] + if nLS > 0 then + local o = (i - 1) * 16 + 1 + for k = 0, 15 do + local abs_q = pulses[o + k] + for _ = 1, nLS do + abs_q = abs_q * 2 + icdf(d, lsb, 1, 8) + end + pulses[o + k] = abs_q + end + sum_pulses[i] += nLS * 32 + end + end + -- silk_decode_signs + local signTab = T.sign_iCDF + local base = 7 * (quantOffsetType + signalType * 2) + local blocks = (frame_length + 8) // 16 + for i = 1, blocks do + local p = sum_pulses[i] + if p > 0 then + signIcdf[1] = signTab[base + math.min(p % 32, 6) + 1] + local o = (i - 1) * 16 + 1 + for j = 0, 15 do + local q = pulses[o + j] + if q > 0 then + pulses[o + j] = q * (icdf(d, signIcdf, 1, 8) * 2 - 1) + end + end + end + end +end + +local pNLSF_Q15 = table.create(16, 0) +local pNLSF0_Q15 = table.create(16, 0) + +@native local function gainsDequant(gain_Q16: { number }, ind: { number }, ch: any, conditional: boolean, nb_subfr: number) + local prev = ch.LastGainIndex + for k = 1, nb_subfr do + if k == 1 and not conditional then + prev = math.max(ind[k], prev - 16) + else + local ind_tmp = ind[k] - 4 + local thr = 8 + prev + if ind_tmp > thr then + prev += ind_tmp * 2 - thr + else + prev += ind_tmp + end + end + if prev < 0 then + prev = 0 + elseif prev > 63 then + prev = 63 + end + gain_Q16[k] = silkLog2lin(math.min((1907825 * prev) // 65536 + 2090, 3967)) + end + ch.LastGainIndex = prev +end + +local CB_lags = { + [8] = { [4] = { T.CB_lags_stage2, 11 }, [2] = { T.CB_lags_stage2_10_ms, 3 } }, + [0] = { [4] = { T.CB_lags_stage3, 34 }, [2] = { T.CB_lags_stage3_10_ms, 12 } }, +} + +@native local function decodeParameters(ch: any, ctrl: any, condCoding: number) + local ind = ch.indices + gainsDequant(ctrl.Gains_Q16, ind.GainsIndices, ch, condCoding == 2, ch.nb_subfr) + local order = ch.LPC_order + nlsfDecode(pNLSF_Q15, ind.NLSFIndices, ch.psNLSF_CB) + nlsf2a(ctrl.PredCoef_Q12[2], pNLSF_Q15, order) + if ch.first_frame_after_reset == 1 then + ind.NLSFInterpCoef_Q2 = 4 + end + local prevNLSF = ch.prevNLSF_Q15 + if ind.NLSFInterpCoef_Q2 < 4 then + local c = ind.NLSFInterpCoef_Q2 + for i = 1, order do + pNLSF0_Q15[i] = prevNLSF[i] + (c * (pNLSF_Q15[i] - prevNLSF[i])) // 4 + end + nlsf2a(ctrl.PredCoef_Q12[1], pNLSF0_Q15, order) + else + local a, b = ctrl.PredCoef_Q12[1], ctrl.PredCoef_Q12[2] + for i = 1, order do + a[i] = b[i] + end + end + for i = 1, order do + prevNLSF[i] = pNLSF_Q15[i] + end + if ch.lossCnt ~= 0 then + bwexpander(ctrl.PredCoef_Q12[1], order, 63570) + bwexpander(ctrl.PredCoef_Q12[2], order, 63570) + end + if ind.signalType == 2 then + -- silk_decode_pitch + local fs = ch.fs_kHz + local cbinfo = CB_lags[if fs == 8 then 8 else 0][ch.nb_subfr] + local cb, cbk_size = cbinfo[1], cbinfo[2] + local min_lag, max_lag = 2 * fs, 18 * fs + local lag = min_lag + ind.lagIndex + for k = 0, ch.nb_subfr - 1 do + local v = lag + cb[k * cbk_size + ind.contourIndex + 1] + if v < min_lag then + v = min_lag + elseif v > max_lag then + v = max_lag + end + ctrl.pitchL[k + 1] = v + end + local vq = LTP_vq_Q7[ind.PERIndex + 1] + for k = 0, ch.nb_subfr - 1 do + local Ix = ind.LTPIndex[k + 1] + for i = 1, 5 do + ctrl.LTPCoef_Q14[k * 5 + i] = vq[Ix * 5 + i] * 128 + end + end + ctrl.LTP_scale_Q14 = T.LTPScales_table_Q14[ind.LTP_scaleIndex + 1] + else + for k = 1, ch.nb_subfr do + ctrl.pitchL[k] = 0 + end + for k = 1, 5 * ch.nb_subfr do + ctrl.LTPCoef_Q14[k] = 0 + end + ind.PERIndex = 0 + ctrl.LTP_scale_Q14 = 0 + end +end + +local sLTP = table.create(320, 0) +local sLTP_Q15 = table.create(640, 0) +local res_Q14 = table.create(80, 0) +local sLPC_Q14 = table.create(96, 0) +local A_Q12_tmp = table.create(16, 0) +local QuantOffsets = { { 100, 240 }, { 32, 100 } } + +-- silk_decode_core: xq[xo .. xo + frame_length - 1] +@native local function decodeCore(ch: any, ctrl: any, xq: { number }, xo: number, pulses: { number }) + local ind = ch.indices + local exc = ch.exc_Q14 + local offset_Q10 = QuantOffsets[ind.signalType // 2 + 1][ind.quantOffsetType + 1] + local NLSF_interpolation_flag = ind.NLSFInterpCoef_Q2 < 4 + local frame_length = ch.frame_length + local subfr_length = ch.subfr_length + local ltp_mem_length = ch.ltp_mem_length + local order = ch.LPC_order + local outBuf = ch.outBuf + + local rand_seed = ind.Seed + for i = 1, frame_length do + rand_seed = silkRand(rand_seed) + local p = pulses[i] + local e = p * 16384 + if e > 0 then + e -= 1280 + elseif e < 0 then + e += 1280 + end + e += offset_Q10 * 16 + if rand_seed < 0 then + e = -e + end + exc[i] = e + rand_seed = i32(rand_seed + p) + end + + local sl = ch.sLPC_Q14_buf + for i = 1, 16 do + sLPC_Q14[i] = sl[i] + end + local pexc = 0 -- C offset into exc + local pxq = xo + local sLTP_buf_idx = ltp_mem_length -- C index into sLTP_Q15 + local lag = 0 + for k = 0, ch.nb_subfr - 1 do + local A_Q12 = ctrl.PredCoef_Q12[k // 2 + 1] + for i = 1, order do + A_Q12_tmp[i] = A_Q12[i] + end + local Bo = k * 5 -- C offset into LTPCoef_Q14 + local B = ctrl.LTPCoef_Q14 + local signalType = ind.signalType + local gain = ctrl.Gains_Q16[k + 1] + local Gain_Q10 = gain // 64 + local inv_gain_Q31 = silkINVERSE32_varQ(gain, 47) + local gain_adj_Q16 + if gain ~= ch.prev_gain_Q16 then + gain_adj_Q16 = silkDIV32_varQ(ch.prev_gain_Q16, gain, 16) + for i = 1, 16 do + sLPC_Q14[i] = i32(mulww(gain_adj_Q16, sLPC_Q14[i])) + end + else + gain_adj_Q16 = 65536 + end + ch.prev_gain_Q16 = gain + if ch.lossCnt ~= 0 and ch.prevSignalType == 2 and ind.signalType ~= 2 and k < 2 then + for i = 1, 5 do + B[Bo + i] = 0 + end + B[Bo + 3] = 4096 + signalType = 2 + ctrl.pitchL[k + 1] = ch.lagPrev + end + if signalType == 2 then + lag = ctrl.pitchL[k + 1] + if k == 0 or (k == 2 and NLSF_interpolation_flag) then + local start_idx = ltp_mem_length - lag - order - 2 + if start_idx < 1 then + start_idx = 1 -- corrupt stream guard (C asserts start_idx > 0) + end + if k == 2 then + for i = 0, 2 * subfr_length - 1 do + outBuf[ltp_mem_length + i + 1] = xq[xo + i] + end + end + lpcAnalysisFilter(sLTP, start_idx + 1, outBuf, start_idx + k * subfr_length + 1, A_Q12, ltp_mem_length - start_idx, order) + if k == 0 then + inv_gain_Q31 = ((inv_gain_Q31 * ctrl.LTP_scale_Q14) // 65536) * 4 + end + for i = 0, lag + 1 do + sLTP_Q15[sLTP_buf_idx - i] = (inv_gain_Q31 * sLTP[ltp_mem_length - i]) // 65536 + end + else + if gain_adj_Q16 ~= 65536 then + for i = 0, lag + 1 do + local j = sLTP_buf_idx - i + sLTP_Q15[j] = i32(mulww(gain_adj_Q16, sLTP_Q15[j])) + end + end + end + end + local presArr, presOff + if signalType == 2 then + local b0, b1, b2, b3, b4 = B[Bo + 1], B[Bo + 2], B[Bo + 3], B[Bo + 4], B[Bo + 5] + local pl = sLTP_buf_idx - lag + 2 + 1 -- 1-based index of pred_lag_ptr[0] + for i = 1, subfr_length do + local pred = 2 + pred += (sLTP_Q15[pl] * b0) // 65536 + pred += (sLTP_Q15[pl - 1] * b1) // 65536 + pred += (sLTP_Q15[pl - 2] * b2) // 65536 + pred += (sLTP_Q15[pl - 3] * b3) // 65536 + pred += (sLTP_Q15[pl - 4] * b4) // 65536 + pl += 1 + local r = exc[pexc + i] + pred * 2 + res_Q14[i] = r + sLTP_buf_idx += 1 + sLTP_Q15[sLTP_buf_idx] = r * 2 + end + presArr, presOff = res_Q14, 0 + else + presArr, presOff = exc, pexc + end + local a0, a1, a2, a3, a4, a5, a6, a7, a8, a9 = + A_Q12_tmp[1], A_Q12_tmp[2], A_Q12_tmp[3], A_Q12_tmp[4], A_Q12_tmp[5], + A_Q12_tmp[6], A_Q12_tmp[7], A_Q12_tmp[8], A_Q12_tmp[9], A_Q12_tmp[10] + local wide = order == 16 + local a10, a11, a12, a13, a14, a15 = A_Q12_tmp[11], A_Q12_tmp[12], A_Q12_tmp[13], A_Q12_tmp[14], A_Q12_tmp[15], A_Q12_tmp[16] + for i = 1, subfr_length do + local j = 16 + i -- 1-based index of sLPC_Q14[MAX_LPC_ORDER + i - 1 (C)] + 1 + local pred = order // 2 + pred += (sLPC_Q14[j - 1] * a0) // 65536 + pred += (sLPC_Q14[j - 2] * a1) // 65536 + pred += (sLPC_Q14[j - 3] * a2) // 65536 + pred += (sLPC_Q14[j - 4] * a3) // 65536 + pred += (sLPC_Q14[j - 5] * a4) // 65536 + pred += (sLPC_Q14[j - 6] * a5) // 65536 + pred += (sLPC_Q14[j - 7] * a6) // 65536 + pred += (sLPC_Q14[j - 8] * a7) // 65536 + pred += (sLPC_Q14[j - 9] * a8) // 65536 + pred += (sLPC_Q14[j - 10] * a9) // 65536 + if wide then + pred += (sLPC_Q14[j - 11] * a10) // 65536 + pred += (sLPC_Q14[j - 12] * a11) // 65536 + pred += (sLPC_Q14[j - 13] * a12) // 65536 + pred += (sLPC_Q14[j - 14] * a13) // 65536 + pred += (sLPC_Q14[j - 15] * a14) // 65536 + pred += (sLPC_Q14[j - 16] * a15) // 65536 + end + pred = i32(pred) + local v = addSat32(presArr[presOff + i], lshiftSat32(pred, 4)) + sLPC_Q14[j] = v + xq[pxq + i - 1] = sat16((mulww(v, Gain_Q10) + 128) // 256) + end + for i = 1, 16 do + sLPC_Q14[i] = sLPC_Q14[subfr_length + i] + end + pexc += subfr_length + pxq += subfr_length + end + for i = 1, 16 do + sl[i] = sLPC_Q14[i] + end +end + +local HARM_ATT_Q15 = { 32440, 31130 } +local PLC_RAND_ATTENUATE_V_Q15 = { 31130, 26214 } +local PLC_RAND_ATTENUATE_UV_Q15 = { 32440, 29491 } + +@native local function plcReset(ch: any) + local plc = ch.sPLC + plc.pitchL_Q8 = ch.frame_length * 128 + plc.prevGain_Q16[1] = 65536 + plc.prevGain_Q16[2] = 65536 + plc.subfr_length = 20 + plc.nb_subfr = 2 +end + +@native local function cngReset(ch: any) + local step = tdiv(32767, ch.LPC_order + 1) + local acc = 0 + local cng = ch.sCNG + for i = 1, ch.LPC_order do + acc += step + cng.CNG_smth_NLSF_Q15[i] = acc + end + cng.CNG_smth_Gain_Q16 = 0 + cng.rand_seed = 3176576 +end + +@native local function plcUpdate(ch: any, ctrl: any) + local plc = ch.sPLC + local nb = ch.nb_subfr + ch.prevSignalType = ch.indices.signalType + local LTP_Gain_Q14 = 0 + local coef = plc.LTPCoef_Q14 + if ch.indices.signalType == 2 then + local j = 0 + while j * ch.subfr_length < ctrl.pitchL[nb] do + if j == nb then + break + end + local t = 0 + local o = (nb - 1 - j) * 5 + for i = 1, 5 do + t += ctrl.LTPCoef_Q14[o + i] + end + if t > LTP_Gain_Q14 then + LTP_Gain_Q14 = t + for i = 1, 5 do + coef[i] = ctrl.LTPCoef_Q14[o + i] + end + plc.pitchL_Q8 = ctrl.pitchL[nb - j] * 256 + end + j += 1 + end + for i = 1, 5 do + coef[i] = 0 + end + coef[3] = LTP_Gain_Q14 + if LTP_Gain_Q14 < 11469 then + local scale_Q10 = tdiv(11469 * 1024, math.max(LTP_Gain_Q14, 1)) + for i = 1, 5 do + coef[i] = (s16(coef[i]) * s16(scale_Q10)) // 1024 + end + elseif LTP_Gain_Q14 > 15565 then + local scale_Q14 = tdiv(15565 * 16384, math.max(LTP_Gain_Q14, 1)) + for i = 1, 5 do + coef[i] = (s16(coef[i]) * s16(scale_Q14)) // 16384 + end + end + else + plc.pitchL_Q8 = ch.fs_kHz * 18 * 256 + for i = 1, 5 do + coef[i] = 0 + end + end + local p = ctrl.PredCoef_Q12[2] + for i = 1, ch.LPC_order do + plc.prevLPC_Q12[i] = p[i] + end + plc.prevLTP_scale_Q14 = ctrl.LTP_scale_Q14 + plc.prevGain_Q16[1] = ctrl.Gains_Q16[nb - 1] + plc.prevGain_Q16[2] = ctrl.Gains_Q16[nb] + plc.subfr_length = ch.subfr_length + plc.nb_subfr = nb +end + +local excBuf = table.create(160, 0) +local plcLTP = table.create(320, 0) +local plcLTP_Q14 = table.create(640, 0) +local A_plc = table.create(16, 0) + +@native local function plcConceal(ch: any, ctrl: any, frame: { number }, fo: number) + local plc = ch.sPLC + local ltp_mem_length = ch.ltp_mem_length + local order = ch.LPC_order + local prevGain_Q10_0 = plc.prevGain_Q16[1] // 64 + local prevGain_Q10_1 = plc.prevGain_Q16[2] // 64 + if ch.first_frame_after_reset ~= 0 then + for i = 1, 16 do + plc.prevLPC_Q12[i] = 0 + end + end + -- silk_PLC_energy + local sl, nb = ch.subfr_length, ch.nb_subfr + local exc = ch.exc_Q14 + for k = 0, 1 do + local g = if k == 0 then prevGain_Q10_0 else prevGain_Q10_1 + for i = 0, sl - 1 do + excBuf[k * sl + i + 1] = sat16(i32(mulww(exc[i + (k + nb - 2) * sl + 1], g)) // 256) + end + end + local energy1, shift1 = sumSqrShift(excBuf, 1, sl) + local energy2, shift2 = sumSqrShift(excBuf, sl + 1, sl) + local rand_off -- C offset into exc_Q14 + if rshift(energy1, shift2) < rshift(energy2, shift1) then + rand_off = math.max(0, (plc.nb_subfr - 1) * plc.subfr_length - 128) + else + rand_off = math.max(0, plc.nb_subfr * plc.subfr_length - 128) + end + local B = plc.LTPCoef_Q14 + local rand_scale_Q14 = plc.randScale_Q14 + local att = math.min(1, ch.lossCnt) + 1 + local harm_Gain_Q15 = HARM_ATT_Q15[att] + local rand_Gain_Q15 = if ch.prevSignalType == 2 then PLC_RAND_ATTENUATE_V_Q15[att] else PLC_RAND_ATTENUATE_UV_Q15[att] + bwexpander(plc.prevLPC_Q12, order, 64881) + for i = 1, order do + A_plc[i] = plc.prevLPC_Q12[i] + end + if ch.lossCnt == 0 then + rand_scale_Q14 = 16384 + if ch.prevSignalType == 2 then + for i = 1, 5 do + rand_scale_Q14 -= B[i] + end + rand_scale_Q14 = math.max(3277, s16(rand_scale_Q14)) + rand_scale_Q14 = s16((rand_scale_Q14 * s16(plc.prevLTP_scale_Q14)) // 16384) + else + local invGain_Q30 = lpcInversePredGain(plc.prevLPC_Q12, order) + local down = math.min(1073741824 // 8, invGain_Q30) + down = math.max(1073741824 // 256, down) + down = down * 8 + rand_Gain_Q15 = ((down * s16(rand_Gain_Q15)) // 65536) // 16384 + end + end + local rand_seed = plc.rand_seed + local lag = (plc.pitchL_Q8 + 128) // 256 + local sLTP_buf_idx = ltp_mem_length + local idx = ltp_mem_length - lag - order - 2 + if idx < 1 then + idx = 1 + end + lpcAnalysisFilter(plcLTP, idx + 1, ch.outBuf, idx + 1, A_plc, ltp_mem_length - idx, order) + local inv_gain_Q30 = silkINVERSE32_varQ(plc.prevGain_Q16[2], 46) + inv_gain_Q30 = math.min(inv_gain_Q30, 1073741823) + for i = idx + order, ltp_mem_length - 1 do + plcLTP_Q14[i + 1] = (inv_gain_Q30 * plcLTP[i + 1]) // 65536 + end + for _ = 0, ch.nb_subfr - 1 do + local pl = sLTP_buf_idx - lag + 2 + 1 + local b0, b1, b2, b3, b4 = B[1], B[2], B[3], B[4], B[5] + for _ = 1, sl do + local pred = 2 + pred += (plcLTP_Q14[pl] * b0) // 65536 + pred += (plcLTP_Q14[pl - 1] * b1) // 65536 + pred += (plcLTP_Q14[pl - 2] * b2) // 65536 + pred += (plcLTP_Q14[pl - 3] * b3) // 65536 + pred += (plcLTP_Q14[pl - 4] * b4) // 65536 + pl += 1 + rand_seed = silkRand(rand_seed) + local ri = (rand_seed // 33554432) % 128 + sLTP_buf_idx += 1 + plcLTP_Q14[sLTP_buf_idx] = i32((pred + (exc[rand_off + ri + 1] * s16(rand_scale_Q14)) // 65536) * 4) + end + for j = 1, 5 do + B[j] = (harm_Gain_Q15 * s16(B[j])) // 32768 + end + rand_scale_Q14 = (s16(rand_scale_Q14) * s16(rand_Gain_Q15)) // 32768 + plc.pitchL_Q8 = plc.pitchL_Q8 + (plc.pitchL_Q8 * 655) // 65536 + plc.pitchL_Q8 = math.min(plc.pitchL_Q8, 18 * ch.fs_kHz * 256) + lag = (plc.pitchL_Q8 + 128) // 256 + end + -- LPC synthesis in place over plcLTP_Q14, starting at C offset ltp_mem_length - 16 + local base = ltp_mem_length - 16 -- C offset of sLPC_Q14_ptr + local slb = ch.sLPC_Q14_buf + for i = 1, 16 do + plcLTP_Q14[base + i] = slb[i] + end + for i = 0, ch.frame_length - 1 do + local j = base + 16 + i + 1 -- 1-based index of sLPC_Q14_ptr[16 + i] + local pred = order // 2 + for t = 1, order do + pred += (plcLTP_Q14[j - t] * A_plc[t]) // 65536 + end + pred = i32(pred) + local v = addSat32(plcLTP_Q14[j], lshiftSat32(pred, 4)) + plcLTP_Q14[j] = v + frame[fo + i] = sat16((mulww(v, prevGain_Q10_1) + 128) // 256) + end + for i = 1, 16 do + slb[i] = plcLTP_Q14[base + ch.frame_length + i] + end + plc.rand_seed = rand_seed + plc.randScale_Q14 = s16(rand_scale_Q14) + for i = 1, 4 do + ctrl.pitchL[i] = lag + end +end + +@native local function plcGlueFrames(ch: any, frame: { number }, fo: number, length: number) + local plc = ch.sPLC + if ch.lossCnt ~= 0 then + plc.conc_energy, plc.conc_energy_shift = sumSqrShift(frame, fo, length) + plc.last_frame_lost = 1 + else + if plc.last_frame_lost ~= 0 then + local energy, energy_shift = sumSqrShift(frame, fo, length) + if energy_shift > plc.conc_energy_shift then + plc.conc_energy = rshift(plc.conc_energy, energy_shift - plc.conc_energy_shift) + elseif energy_shift < plc.conc_energy_shift then + energy = rshift(energy, plc.conc_energy_shift - energy_shift) + end + if energy > plc.conc_energy then + local LZ = clz32(plc.conc_energy) - 1 + plc.conc_energy = i32(plc.conc_energy * p2(LZ)) + energy = rshift(energy, math.max(24 - LZ, 0)) + local frac_Q24 = tdiv(plc.conc_energy, math.max(energy, 1)) + local gain_Q16 = silkSQRT_APPROX(frac_Q24) * 16 + local slope_Q16 = tdiv(65536 - gain_Q16, length) * 4 + for i = 0, length - 1 do + frame[fo + i] = (gain_Q16 * frame[fo + i]) // 65536 + gain_Q16 += slope_Q16 + if gain_Q16 > 65536 then + break + end + end + end + end + plc.last_frame_lost = 0 + end +end + +local A_cng = table.create(16, 0) +local CNG_sig = table.create(336, 0) + +@native local function cng(ch: any, ctrl: any, frame: { number }, fo: number, length: number) + local c = ch.sCNG + if ch.fs_kHz ~= c.fs_kHz then + cngReset(ch) + c.fs_kHz = ch.fs_kHz + end + local order = ch.LPC_order + if ch.lossCnt == 0 and ch.prevSignalType == 0 then + local sm = c.CNG_smth_NLSF_Q15 + for i = 1, order do + sm[i] += ((ch.prevNLSF_Q15[i] - sm[i]) * 16348) // 65536 + end + local max_Gain_Q16, subfr = 0, 0 + for i = 0, ch.nb_subfr - 1 do + if ctrl.Gains_Q16[i + 1] > max_Gain_Q16 then + max_Gain_Q16 = ctrl.Gains_Q16[i + 1] + subfr = i + end + end + local eb = c.CNG_exc_buf_Q14 + local sl = ch.subfr_length + for i = (ch.nb_subfr - 1) * sl, 1, -1 do + eb[sl + i] = eb[i] + end + for i = 1, sl do + eb[i] = ch.exc_Q14[subfr * sl + i] + end + for i = 1, ch.nb_subfr do + local g = ctrl.Gains_Q16[i] + c.CNG_smth_Gain_Q16 += ((g - c.CNG_smth_Gain_Q16) * 4634) // 65536 + if mulww(c.CNG_smth_Gain_Q16, 46396) > g then + c.CNG_smth_Gain_Q16 = g + end + end + end + if ch.lossCnt ~= 0 then + local gain_Q16 = i32(mulww(ch.sPLC.randScale_Q14, ch.sPLC.prevGain_Q16[2])) + if gain_Q16 >= 2097152 or c.CNG_smth_Gain_Q16 > 8388608 then + gain_Q16 = (gain_Q16 // 65536) * (gain_Q16 // 65536) + gain_Q16 = i32((c.CNG_smth_Gain_Q16 // 65536) * (c.CNG_smth_Gain_Q16 // 65536) - gain_Q16 * 32) + gain_Q16 = i32(silkSQRT_APPROX(gain_Q16) * 65536) + else + gain_Q16 = i32(mulww(gain_Q16, gain_Q16)) + gain_Q16 = i32(i32(mulww(c.CNG_smth_Gain_Q16, c.CNG_smth_Gain_Q16)) - gain_Q16 * 32) + gain_Q16 = i32(silkSQRT_APPROX(gain_Q16) * 256) + end + local gain_Q10 = gain_Q16 // 64 + -- silk_CNG_exc + local exc_mask = 255 + while exc_mask > length do + exc_mask //= 2 + end + local seed = c.rand_seed + for i = 1, length do + seed = silkRand(seed) + local idx = bit32.band((seed // 16777216) % 256, exc_mask) + CNG_sig[16 + i] = c.CNG_exc_buf_Q14[idx + 1] + end + c.rand_seed = seed + nlsf2a(A_cng, c.CNG_smth_NLSF_Q15, order) + for i = 1, 16 do + CNG_sig[i] = c.CNG_synth_state[i] + end + for i = 0, length - 1 do + local j = 16 + i + 1 + local pred = order // 2 + for t = 1, order do + pred += (CNG_sig[j - t] * A_cng[t]) // 65536 + end + pred = i32(pred) + local v = addSat32(CNG_sig[j], lshiftSat32(pred, 4)) + CNG_sig[j] = v + frame[fo + i] = sat16(frame[fo + i] + sat16((mulww(v, gain_Q10) + 128) // 256)) + end + for i = 1, 16 do + c.CNG_synth_state[i] = CNG_sig[length + i] + end + else + for i = 1, order do + c.CNG_synth_state[i] = 0 + end + end +end + +-- silk_decode_frame: writes frame_length samples to out[fo ..] +@native local function decodeFrame(ch: any, d: any, out: { number }, fo: number, lostFlag: number, condCoding: number): number + local L = ch.frame_length + local ctrl = ch.ctrl + ctrl.LTP_scale_Q14 = 0 + if lostFlag == 0 or (lostFlag == 2 and ch.LBRR_flags[ch.nFramesDecoded + 1] == 1) then + local pulses = ch.pulses + decodeIndices(ch, d, ch.nFramesDecoded, lostFlag ~= 0, condCoding) + decodePulses(d, pulses, ch.indices.signalType, ch.indices.quantOffsetType, L) + decodeParameters(ch, ctrl, condCoding) + decodeCore(ch, ctrl, out, fo, pulses) + local mv_len = ch.ltp_mem_length - L + local ob = ch.outBuf + for i = 1, mv_len do + ob[i] = ob[L + i] + end + for i = 0, L - 1 do + ob[mv_len + i + 1] = out[fo + i] + end + -- silk_PLC (update) + if ch.fs_kHz ~= ch.sPLC.fs_kHz then + plcReset(ch) + ch.sPLC.fs_kHz = ch.fs_kHz + end + plcUpdate(ch, ctrl) + ch.lossCnt = 0 + ch.prevSignalType = ch.indices.signalType + ch.first_frame_after_reset = 0 + else + if ch.fs_kHz ~= ch.sPLC.fs_kHz then + plcReset(ch) + ch.sPLC.fs_kHz = ch.fs_kHz + end + plcConceal(ch, ctrl, out, fo) + ch.lossCnt += 1 + local mv_len = ch.ltp_mem_length - L + local ob = ch.outBuf + for i = 1, mv_len do + ob[i] = ob[L + i] + end + for i = 0, L - 1 do + ob[mv_len + i + 1] = out[fo + i] + end + end + cng(ch, ctrl, out, fo, L) + plcGlueFrames(ch, out, fo, L) + ch.lagPrev = ctrl.pitchL[ch.nb_subfr] + return L +end + +@native local function stereoDecodePred(d: any, pred_Q13: { number }) + local n = icdf(d, T.stereo_pred_joint_iCDF, 1, 8) + local ix02 = n // 5 + local ix12 = n - 5 * ix02 + local ix00 = icdf(d, T.uniform3_iCDF, 1, 8) + local ix01 = icdf(d, T.uniform5_iCDF, 1, 8) + local ix10 = icdf(d, T.uniform3_iCDF, 1, 8) + local ix11 = icdf(d, T.uniform5_iCDF, 1, 8) + local q = T.stereo_pred_quant_Q13 + for c = 1, 2 do + local a = if c == 1 then ix00 + 3 * ix02 else ix10 + 3 * ix12 + local b = if c == 1 then ix01 else ix11 + local low_Q13 = q[a + 1] + local step_Q13 = ((q[a + 2] - low_Q13) * 6554) // 65536 + pred_Q13[c] = low_Q13 + s16(step_Q13) * (2 * b + 1) + end + pred_Q13[1] -= pred_Q13[2] +end + +-- x1, x2: samplesOut1_tmp arrays (C index j at [j + 1]) +@native local function stereoMSToLR(state: any, x1: { number }, x2: { number }, pred_Q13: { number }, fs_kHz: number, frame_length: number) + x1[1], x1[2] = state.sMid[1], state.sMid[2] + x2[1], x2[2] = state.sSide[1], state.sSide[2] + state.sMid[1], state.sMid[2] = x1[frame_length + 1], x1[frame_length + 2] + state.sSide[1], state.sSide[2] = x2[frame_length + 1], x2[frame_length + 2] + local pred0 = state.pred_prev_Q13[1] + local pred1 = state.pred_prev_Q13[2] + local interp = 8 * fs_kHz + local denom_Q16 = tdiv(65536, interp) + local delta0 = (s16(pred_Q13[1] - pred0) * s16(denom_Q16) + 32768) // 65536 + local delta1 = (s16(pred_Q13[2] - pred1) * s16(denom_Q16) + 32768) // 65536 + for n = 0, frame_length - 1 do + if n < interp then + pred0 += delta0 + pred1 += delta1 + elseif n == interp then + pred0 = pred_Q13[1] + pred1 = pred_Q13[2] + end + local sum = (x1[n + 1] + x1[n + 3] + x1[n + 2] * 2) * 512 + sum = x2[n + 2] * 256 + (sum * s16(pred0)) // 65536 + sum = sum + ((x1[n + 2] * 2048) * s16(pred1)) // 65536 + x2[n + 2] = sat16((sum + 128) // 256) + end + if frame_length <= interp then + -- the second loop never ran; the C code still ends with pred = pred_Q13 + end + state.pred_prev_Q13[1] = pred_Q13[1] + state.pred_prev_Q13[2] = pred_Q13[2] + for n = 0, frame_length - 1 do + local a, b = x1[n + 2], x2[n + 2] + x1[n + 2] = sat16(a + b) + x2[n + 2] = sat16(a - b) + end +end + +type State = any + +@native function Silk.new(apiChannels: number): State + return { + ch = { newChannel(), newChannel() }, + sStereo = { pred_prev_Q13 = { 0, 0 }, sMid = { 0, 0 }, sSide = { 0, 0 } }, + nChannelsAPI = 0, + nChannelsInternal = 0, + prev_decode_only_middle = 0, + MS_pred_Q13 = { 0, 0 }, + resampOut = table.create(960, 0), + apiChannels = apiChannels, + } +end + +-- silk_ResetDecoder (keeps nChannelsAPI / nChannelsInternal, like libopus) +@native function Silk.reset(st: State) + st.ch[1] = newChannel() + st.ch[2] = newChannel() + for _, ch in st.ch do + cngReset(ch) + plcReset(ch) + end + st.sStereo = { pred_prev_Q13 = { 0, 0 }, sMid = { 0, 0 }, sSide = { 0, 0 } } + st.prev_decode_only_middle = 0 +end + +@native local function initChannel(st: State, n: number) + local ch = newChannel() + cngReset(ch) + plcReset(ch) + st.ch[n] = ch +end + +@native function Silk.decode(st: State, ctrl: any, lostFlag: number, firstFrame: boolean, d: any, out: { number }, outBase: number): (number, number) + local ret = 0 + local nInt = ctrl.nChannelsInternal + local nAPI = ctrl.nChannelsAPI + local chs = st.ch + local decode_only_middle = 0 + local MS_pred_Q13 = st.MS_pred_Q13 + MS_pred_Q13[1], MS_pred_Q13[2] = 0, 0 + if nInt ~= 1 and nInt ~= 2 then + return -200, 0 + end + if firstFrame then + for n = 1, nInt do + chs[n].nFramesDecoded = 0 + end + end + if nInt > st.nChannelsInternal then + initChannel(st, 2) + end + local ch1 = chs[1] + local stereo_to_mono = nInt == 1 and st.nChannelsInternal == 2 and ctrl.internalSampleRate == 1000 * ch1.fs_kHz + if ch1.nFramesDecoded == 0 then + for n = 1, nInt do + local ch = chs[n] + local ms = ctrl.payloadSize_ms + if ms == 0 or ms == 10 then + ch.nFramesPerPacket = 1 + ch.nb_subfr = 2 + elseif ms == 20 then + ch.nFramesPerPacket = 1 + ch.nb_subfr = 4 + elseif ms == 40 then + ch.nFramesPerPacket = 2 + ch.nb_subfr = 4 + elseif ms == 60 then + ch.nFramesPerPacket = 3 + ch.nb_subfr = 4 + else + return -203, 0 + end + local fs_kHz_dec = ctrl.internalSampleRate // 1024 + 1 + if fs_kHz_dec ~= 8 and fs_kHz_dec ~= 12 and fs_kHz_dec ~= 16 then + return -200, 0 + end + ret += decoderSetFs(ch, fs_kHz_dec, ctrl.API_sampleRate) + end + end + if nAPI == 2 and nInt == 2 and (st.nChannelsAPI == 1 or st.nChannelsInternal == 1) then + local s = st.sStereo + s.pred_prev_Q13[1], s.pred_prev_Q13[2] = 0, 0 + s.sSide[1], s.sSide[2] = 0, 0 + copyResampler(chs[2].resampler_state, ch1.resampler_state) + end + st.nChannelsAPI = nAPI + st.nChannelsInternal = nInt + if ctrl.API_sampleRate > 48000 or ctrl.API_sampleRate < 8000 then + return -200, 0 + end + if lostFlag ~= 1 and ch1.nFramesDecoded == 0 then + for n = 1, nInt do + local ch = chs[n] + for i = 1, ch.nFramesPerPacket do + ch.VAD_flags[i] = if bitLogp(d, 1) then 1 else 0 + end + ch.LBRR_flag = if bitLogp(d, 1) then 1 else 0 + end + for n = 1, nInt do + local ch = chs[n] + ch.LBRR_flags[1], ch.LBRR_flags[2], ch.LBRR_flags[3] = 0, 0, 0 + if ch.LBRR_flag ~= 0 then + if ch.nFramesPerPacket == 1 then + ch.LBRR_flags[1] = 1 + else + local sym = icdf(d, LBRR_flags_iCDF[ch.nFramesPerPacket - 1], 1, 8) + 1 + for i = 0, ch.nFramesPerPacket - 1 do + ch.LBRR_flags[i + 1] = bit32.band(bit32.rshift(sym, i), 1) + end + end + end + end + if lostFlag == 0 then + -- skip all LBRR data + for i = 0, ch1.nFramesPerPacket - 1 do + for n = 1, nInt do + local ch = chs[n] + if ch.LBRR_flags[i + 1] ~= 0 then + if nInt == 2 and n == 1 then + stereoDecodePred(d, MS_pred_Q13) + if chs[2].LBRR_flags[i + 1] == 0 then + decode_only_middle = icdf(d, T.stereo_only_code_mid_iCDF, 1, 8) + end + end + local condCoding = if i > 0 and ch.LBRR_flags[i] ~= 0 then 2 else 0 + decodeIndices(ch, d, i, true, condCoding) + decodePulses(d, ch.pulses, ch.indices.signalType, ch.indices.quantOffsetType, ch.frame_length) + end + end + end + end + end + if nInt == 2 then + local fd = ch1.nFramesDecoded + if lostFlag == 0 or (lostFlag == 2 and ch1.LBRR_flags[fd + 1] == 1) then + stereoDecodePred(d, MS_pred_Q13) + if (lostFlag == 0 and chs[2].VAD_flags[fd + 1] == 0) or (lostFlag == 2 and chs[2].LBRR_flags[fd + 1] == 0) then + decode_only_middle = icdf(d, T.stereo_only_code_mid_iCDF, 1, 8) + else + decode_only_middle = 0 + end + else + MS_pred_Q13[1] = st.sStereo.pred_prev_Q13[1] + MS_pred_Q13[2] = st.sStereo.pred_prev_Q13[2] + end + end + if nInt == 2 and decode_only_middle == 0 and st.prev_decode_only_middle == 1 then + local c2 = chs[2] + for i = 1, 480 do + c2.outBuf[i] = 0 + end + for i = 1, 16 do + c2.sLPC_Q14_buf[i] = 0 + end + c2.lagPrev = 100 + c2.LastGainIndex = 10 + c2.prevSignalType = 0 + c2.first_frame_after_reset = 1 + end + local has_side + if lostFlag == 0 then + has_side = decode_only_middle == 0 + else + has_side = st.prev_decode_only_middle == 0 + or (nInt == 2 and lostFlag == 2 and chs[2].LBRR_flags[chs[2].nFramesDecoded + 1] == 1) + end + local nSamplesOutDec = ch1.frame_length + for n = 1, nInt do + local ch = chs[n] + if n == 1 or has_side then + local FrameIndex = ch1.nFramesDecoded - (n - 1) + local condCoding + if FrameIndex <= 0 then + condCoding = 0 + elseif lostFlag == 2 then + condCoding = if ch.LBRR_flags[FrameIndex] ~= 0 then 2 else 0 + elseif n > 1 and st.prev_decode_only_middle ~= 0 then + condCoding = 1 + else + condCoding = 2 + end + nSamplesOutDec = decodeFrame(ch, d, ch.out, 3, lostFlag, condCoding) + else + local o = ch.out + for i = 3, nSamplesOutDec + 2 do + o[i] = 0 + end + end + ch.nFramesDecoded += 1 + end + local o1 = ch1.out + if nAPI == 2 and nInt == 2 then + stereoMSToLR(st.sStereo, o1, chs[2].out, MS_pred_Q13, ch1.fs_kHz, nSamplesOutDec) + else + local sMid = st.sStereo.sMid + o1[1], o1[2], sMid[1], sMid[2] = sMid[1], sMid[2], o1[nSamplesOutDec + 1], o1[nSamplesOutDec + 2] + end + local nSamplesOut = (nSamplesOutDec * ctrl.API_sampleRate) // (ch1.fs_kHz * 1000) + local ro = st.resampOut + local scale = 1 / 32768 + for n = 1, math.min(nAPI, nInt) do + resampler(chs[n].resampler_state, ro, chs[n].out, 2, nSamplesOutDec) + if nAPI == 2 then + local b = outBase + n - 1 + for i = 0, nSamplesOut - 1 do + out[b + 2 * i] = ro[i + 1] * scale + end + else + for i = 0, nSamplesOut - 1 do + out[outBase + i] = ro[i + 1] * scale + end + end + end + if nAPI == 2 and nInt == 1 then + if stereo_to_mono then + resampler(chs[2].resampler_state, ro, o1, 2, nSamplesOutDec) + for i = 0, nSamplesOut - 1 do + out[outBase + 1 + 2 * i] = ro[i + 1] * scale + end + else + for i = 0, nSamplesOut - 1 do + out[outBase + 1 + 2 * i] = out[outBase + 2 * i] + end + end + end + if lostFlag == 1 then + for i = 1, st.nChannelsInternal do + chs[i].LastGainIndex = 10 + end + else + st.prev_decode_only_middle = decode_only_middle + end + return ret, nSamplesOut +end + +-- the pitch lag of the last frame at 48 kHz (decControl->prevPitchLag), 0 when unvoiced +@native function Silk.prevPitchLag(st: State): number + local ch = st.ch[1] + if ch.prevSignalType == 2 then + local mult = { 6, 4, 3 } + return ch.lagPrev * mult[(ch.fs_kHz - 8) // 4 + 1] + end + return 0 +end + +return Silk +end +__FILES["codecs/audio/Opus/SilkTables"] = function() + + +-- 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 = { + 179, 99, 0, +} +T.LTP_gain_iCDF_0 = { + 71, 56, 43, 30, 21, 12, 6, 0, +} +T.LTP_gain_iCDF_1 = { + 199, 165, 144, 124, 109, 96, 84, 71, 61, 51, 42, 32, 23, 15, 8, 0, +} +T.LTP_gain_iCDF_2 = { + 241, 225, 211, 199, 187, 175, 164, 153, 142, 132, 123, 114, 105, 96, 88, 80, 72, 64, 57, 50, + 44, 38, 33, 29, 24, 20, 16, 12, 9, 5, 2, 0, +} +T.LTP_gain_vq_0 = { + 4, 6, 24, 7, 5, 0, 0, 2, 0, 0, 12, 28, 41, 13, -4, -9, 15, 42, 25, 14, + 1, -2, 62, 41, -9, -10, 37, 65, -4, 3, -6, 4, 66, 7, -8, 16, 14, 38, -3, 33, +} +T.LTP_gain_vq_1 = { + 13, 22, 39, 23, 12, -1, 36, 64, 27, -6, -7, 10, 55, 43, 17, 1, 1, 8, 1, 1, + 6, -11, 74, 53, -9, -12, 55, 76, -12, 8, -3, 3, 93, 27, -4, 26, 39, 59, 3, -8, + 2, 0, 77, 11, 9, -8, 22, 44, -6, 7, 40, 9, 26, 3, 9, -7, 20, 101, -7, 4, + 3, -8, 42, 26, 0, -15, 33, 68, 2, 23, -2, 55, 46, -2, 15, 3, -1, 21, 16, 41, +} +T.LTP_gain_vq_2 = { + -6, 27, 61, 39, 5, -11, 42, 88, 4, 1, -2, 60, 65, 6, -4, -1, -5, 73, 56, 1, + -9, 19, 94, 29, -9, 0, 12, 99, 6, 4, 8, -19, 102, 46, -13, 3, 2, 13, 3, 2, + 9, -21, 84, 72, -18, -11, 46, 104, -22, 8, 18, 38, 48, 23, 0, -16, 70, 83, -21, 11, + 5, -11, 117, 22, -8, -6, 23, 117, -12, 3, 3, -8, 95, 28, 4, -10, 15, 77, 60, -15, + -1, 4, 124, 2, -4, 3, 38, 84, 24, -25, 2, 13, 42, 13, 31, 21, -4, 56, 46, -1, + -1, 35, 79, -13, 19, -7, 65, 88, -9, -14, 20, 4, 81, 49, -29, 20, 0, 75, 3, -17, + 5, -9, 44, 92, -8, 1, -3, 22, 69, 31, -6, 95, 41, -12, 5, 39, 67, 16, -4, 1, + 0, -6, 120, 55, -36, -13, 44, 122, 4, -24, 81, 5, 11, 3, 7, 2, 0, 9, 10, 88, +} +T.NLSF_CB1_WB_Q8 = { + 7, 23, 38, 54, 69, 85, 100, 116, 131, 147, 162, 178, 193, 208, 223, 239, 13, 25, 41, 55, + 69, 83, 98, 112, 127, 142, 157, 171, 187, 203, 220, 236, 15, 21, 34, 51, 61, 78, 92, 106, + 126, 136, 152, 167, 185, 205, 225, 240, 10, 21, 36, 50, 63, 79, 95, 110, 126, 141, 157, 173, + 189, 205, 221, 237, 17, 20, 37, 51, 59, 78, 89, 107, 123, 134, 150, 164, 184, 205, 224, 240, + 10, 15, 32, 51, 67, 81, 96, 112, 129, 142, 158, 173, 189, 204, 220, 236, 8, 21, 37, 51, + 65, 79, 98, 113, 126, 138, 155, 168, 179, 192, 209, 218, 12, 15, 34, 55, 63, 78, 87, 108, + 118, 131, 148, 167, 185, 203, 219, 236, 16, 19, 32, 36, 56, 79, 91, 108, 118, 136, 154, 171, + 186, 204, 220, 237, 11, 28, 43, 58, 74, 89, 105, 120, 135, 150, 165, 180, 196, 211, 226, 241, + 6, 16, 33, 46, 60, 75, 92, 107, 123, 137, 156, 169, 185, 199, 214, 225, 11, 19, 30, 44, + 57, 74, 89, 105, 121, 135, 152, 169, 186, 202, 218, 234, 12, 19, 29, 46, 57, 71, 88, 100, + 120, 132, 148, 165, 182, 199, 216, 233, 17, 23, 35, 46, 56, 77, 92, 106, 123, 134, 152, 167, + 185, 204, 222, 237, 14, 17, 45, 53, 63, 75, 89, 107, 115, 132, 151, 171, 188, 206, 221, 240, + 9, 16, 29, 40, 56, 71, 88, 103, 119, 137, 154, 171, 189, 205, 222, 237, 16, 19, 36, 48, + 57, 76, 87, 105, 118, 132, 150, 167, 185, 202, 218, 236, 12, 17, 29, 54, 71, 81, 94, 104, + 126, 136, 149, 164, 182, 201, 221, 237, 15, 28, 47, 62, 79, 97, 115, 129, 142, 155, 168, 180, + 194, 208, 223, 238, 8, 14, 30, 45, 62, 78, 94, 111, 127, 143, 159, 175, 192, 207, 223, 239, + 17, 30, 49, 62, 79, 92, 107, 119, 132, 145, 160, 174, 190, 204, 220, 235, 14, 19, 36, 45, + 61, 76, 91, 108, 121, 138, 154, 172, 189, 205, 222, 238, 12, 18, 31, 45, 60, 76, 91, 107, + 123, 138, 154, 171, 187, 204, 221, 236, 13, 17, 31, 43, 53, 70, 83, 103, 114, 131, 149, 167, + 185, 203, 220, 237, 17, 22, 35, 42, 58, 78, 93, 110, 125, 139, 155, 170, 188, 206, 224, 240, + 8, 15, 34, 50, 67, 83, 99, 115, 131, 146, 162, 178, 193, 209, 224, 239, 13, 16, 41, 66, + 73, 86, 95, 111, 128, 137, 150, 163, 183, 206, 225, 241, 17, 25, 37, 52, 63, 75, 92, 102, + 119, 132, 144, 160, 175, 191, 212, 231, 19, 31, 49, 65, 83, 100, 117, 133, 147, 161, 174, 187, + 200, 213, 227, 242, 18, 31, 52, 68, 88, 103, 117, 126, 138, 149, 163, 177, 192, 207, 223, 239, + 16, 29, 47, 61, 76, 90, 106, 119, 133, 147, 161, 176, 193, 209, 224, 240, 15, 21, 35, 50, + 61, 73, 86, 97, 110, 119, 129, 141, 175, 198, 218, 237, +} +T.NLSF_CB1_WB_Wght_Q9 = { + 3657, 2925, 2925, 2925, 2925, 2925, 2925, 2925, 2925, 2925, 2925, 2925, 2963, 2963, 2925, 2846, 3216, 3085, 2972, 3056, + 3056, 3010, 3010, 3010, 2963, 2963, 3010, 2972, 2888, 2846, 2846, 2726, 3920, 4014, 2981, 3207, 3207, 2934, 3056, 2846, + 3122, 3244, 2925, 2846, 2620, 2553, 2780, 2925, 3516, 3197, 3010, 3103, 3019, 2888, 2925, 2925, 2925, 2925, 2888, 2888, + 2888, 2888, 2888, 2753, 5054, 5054, 2934, 3573, 3385, 3056, 3085, 2793, 3160, 3160, 2972, 2846, 2513, 2540, 2753, 2888, + 4428, 4149, 2700, 2753, 2972, 3010, 2925, 2846, 2981, 3019, 2925, 2925, 2925, 2925, 2888, 2726, 3620, 3019, 2972, 3056, + 3056, 2873, 2806, 3056, 3216, 3047, 2981, 3291, 3291, 2981, 3310, 2991, 5227, 5014, 2540, 3338, 3526, 3385, 3197, 3094, + 3376, 2981, 2700, 2647, 2687, 2793, 2846, 2673, 5081, 5174, 4615, 4428, 2460, 2897, 3047, 3207, 3169, 2687, 2740, 2888, + 2846, 2793, 2846, 2700, 3122, 2888, 2963, 2925, 2925, 2925, 2925, 2963, 2963, 2963, 2963, 2925, 2925, 2963, 2963, 2963, + 4202, 3207, 2981, 3103, 3010, 2888, 2888, 2925, 2972, 2873, 2916, 3019, 2972, 3010, 3197, 2873, 3760, 3760, 3244, 3103, + 2981, 2888, 2925, 2888, 2972, 2934, 2793, 2793, 2846, 2888, 2888, 2660, 3854, 4014, 3207, 3122, 3244, 2934, 3047, 2963, + 2963, 3085, 2846, 2793, 2793, 2793, 2793, 2580, 3845, 4080, 3357, 3516, 3094, 2740, 3010, 2934, 3122, 3085, 2846, 2846, + 2647, 2647, 2846, 2806, 5147, 4894, 3225, 3845, 3441, 3169, 2897, 3413, 3451, 2700, 2580, 2673, 2740, 2846, 2806, 2753, + 4109, 3789, 3291, 3160, 2925, 2888, 2888, 2925, 2793, 2740, 2793, 2740, 2793, 2846, 2888, 2806, 5081, 5054, 3047, 3545, + 3244, 3056, 3085, 2944, 3103, 2897, 2740, 2740, 2740, 2846, 2793, 2620, 4309, 4309, 2860, 2527, 3207, 3376, 3376, 3075, + 3075, 3376, 3056, 2846, 2647, 2580, 2726, 2753, 3056, 2916, 2806, 2888, 2740, 2687, 2897, 3103, 3150, 3150, 3216, 3169, + 3056, 3010, 2963, 2846, 4375, 3882, 2925, 2888, 2846, 2888, 2846, 2846, 2888, 2888, 2888, 2846, 2888, 2925, 2888, 2846, + 2981, 2916, 2916, 2981, 2981, 3056, 3122, 3216, 3150, 3056, 3010, 2972, 2972, 2972, 2925, 2740, 4229, 4149, 3310, 3347, + 2925, 2963, 2888, 2981, 2981, 2846, 2793, 2740, 2846, 2846, 2846, 2793, 4080, 4014, 3103, 3010, 2925, 2925, 2925, 2888, + 2925, 2925, 2846, 2846, 2846, 2793, 2888, 2780, 4615, 4575, 3169, 3441, 3207, 2981, 2897, 3038, 3122, 2740, 2687, 2687, + 2687, 2740, 2793, 2700, 4149, 4269, 3789, 3657, 2726, 2780, 2888, 2888, 3010, 2972, 2925, 2846, 2687, 2687, 2793, 2888, + 4215, 3554, 2753, 2846, 2846, 2888, 2888, 2888, 2925, 2925, 2888, 2925, 2925, 2925, 2963, 2888, 5174, 4921, 2261, 3432, + 3789, 3479, 3347, 2846, 3310, 3479, 3150, 2897, 2460, 2487, 2753, 2925, 3451, 3685, 3122, 3197, 3357, 3047, 3207, 3207, + 2981, 3216, 3085, 2925, 2925, 2687, 2540, 2434, 2981, 3010, 2793, 2793, 2740, 2793, 2846, 2972, 3056, 3103, 3150, 3150, + 3150, 3103, 3010, 3010, 2944, 2873, 2687, 2726, 2780, 3010, 3432, 3545, 3357, 3244, 3056, 3010, 2963, 2925, 2888, 2846, + 3019, 2944, 2897, 3010, 3010, 2972, 3019, 3103, 3056, 3056, 3010, 2888, 2846, 2925, 2925, 2888, 3920, 3967, 3010, 3197, + 3357, 3216, 3291, 3291, 3479, 3704, 3441, 2726, 2181, 2460, 2580, 2607, +} +T.NLSF_CB1_iCDF_WB = { + 225, 204, 201, 184, 183, 175, 158, 154, 153, 135, 119, 115, 113, 110, 109, 99, 98, 95, 79, 68, + 52, 50, 48, 45, 43, 32, 31, 27, 18, 10, 3, 0, 255, 251, 235, 230, 212, 201, 196, 182, + 167, 166, 163, 151, 138, 124, 110, 104, 90, 78, 76, 70, 69, 57, 45, 34, 24, 21, 11, 6, + 5, 4, 3, 0, +} +T.NLSF_CB2_SELECT_WB = { + 0, 0, 0, 0, 0, 0, 0, 1, 100, 102, 102, 68, 68, 36, 34, 96, 164, 107, 158, 185, + 180, 185, 139, 102, 64, 66, 36, 34, 34, 0, 1, 32, 208, 139, 141, 191, 152, 185, 155, 104, + 96, 171, 104, 166, 102, 102, 102, 132, 1, 0, 0, 0, 0, 16, 16, 0, 80, 109, 78, 107, + 185, 139, 103, 101, 208, 212, 141, 139, 173, 153, 123, 103, 36, 0, 0, 0, 0, 0, 0, 1, + 48, 0, 0, 0, 0, 0, 0, 32, 68, 135, 123, 119, 119, 103, 69, 98, 68, 103, 120, 118, + 118, 102, 71, 98, 134, 136, 157, 184, 182, 153, 139, 134, 208, 168, 248, 75, 189, 143, 121, 107, + 32, 49, 34, 34, 34, 0, 17, 2, 210, 235, 139, 123, 185, 137, 105, 134, 98, 135, 104, 182, + 100, 183, 171, 134, 100, 70, 68, 70, 66, 66, 34, 131, 64, 166, 102, 68, 36, 2, 1, 0, + 134, 166, 102, 68, 34, 34, 66, 132, 212, 246, 158, 139, 107, 107, 87, 102, 100, 219, 125, 122, + 137, 118, 103, 132, 114, 135, 137, 105, 171, 106, 50, 34, 164, 214, 141, 143, 185, 151, 121, 103, + 192, 34, 0, 0, 0, 0, 0, 1, 208, 109, 74, 187, 134, 249, 159, 137, 102, 110, 154, 118, + 87, 101, 119, 101, 0, 2, 0, 36, 36, 66, 68, 35, 96, 164, 102, 100, 36, 0, 2, 33, + 167, 138, 174, 102, 100, 84, 2, 2, 100, 107, 120, 119, 36, 197, 24, 0, +} +T.NLSF_CB2_iCDF_WB = { + 255, 254, 253, 244, 12, 3, 2, 1, 0, 255, 254, 252, 224, 38, 3, 2, 1, 0, 255, 254, + 251, 209, 57, 4, 2, 1, 0, 255, 254, 244, 195, 69, 4, 2, 1, 0, 255, 251, 232, 184, + 84, 7, 2, 1, 0, 255, 254, 240, 186, 86, 14, 2, 1, 0, 255, 254, 239, 178, 91, 30, + 5, 1, 0, 255, 248, 227, 177, 100, 19, 2, 1, 0, +} +T.NLSF_PRED_WB_Q8 = { + 175, 148, 160, 176, 178, 173, 174, 164, 177, 174, 196, 182, 198, 192, 182, 68, 62, 66, 60, 72, + 117, 85, 90, 118, 136, 151, 142, 160, 142, 155, +} +T.NLSF_DELTA_MIN_WB_Q15 = { + 100, 3, 40, 3, 3, 3, 5, 14, 14, 10, 11, 3, 8, 9, 7, 3, 347, +} +T.NLSF_CB1_NB_MB_Q8 = { + 12, 35, 60, 83, 108, 132, 157, 180, 206, 228, 15, 32, 55, 77, 101, 125, 151, 175, 201, 225, + 19, 42, 66, 89, 114, 137, 162, 184, 209, 230, 12, 25, 50, 72, 97, 120, 147, 172, 200, 223, + 26, 44, 69, 90, 114, 135, 159, 180, 205, 225, 13, 22, 53, 80, 106, 130, 156, 180, 205, 228, + 15, 25, 44, 64, 90, 115, 142, 168, 196, 222, 19, 24, 62, 82, 100, 120, 145, 168, 190, 214, + 22, 31, 50, 79, 103, 120, 151, 170, 203, 227, 21, 29, 45, 65, 106, 124, 150, 171, 196, 224, + 30, 49, 75, 97, 121, 142, 165, 186, 209, 229, 19, 25, 52, 70, 93, 116, 143, 166, 192, 219, + 26, 34, 62, 75, 97, 118, 145, 167, 194, 217, 25, 33, 56, 70, 91, 113, 143, 165, 196, 223, + 21, 34, 51, 72, 97, 117, 145, 171, 196, 222, 20, 29, 50, 67, 90, 117, 144, 168, 197, 221, + 22, 31, 48, 66, 95, 117, 146, 168, 196, 222, 24, 33, 51, 77, 116, 134, 158, 180, 200, 224, + 21, 28, 70, 87, 106, 124, 149, 170, 194, 217, 26, 33, 53, 64, 83, 117, 152, 173, 204, 225, + 27, 34, 65, 95, 108, 129, 155, 174, 210, 225, 20, 26, 72, 99, 113, 131, 154, 176, 200, 219, + 34, 43, 61, 78, 93, 114, 155, 177, 205, 229, 23, 29, 54, 97, 124, 138, 163, 179, 209, 229, + 30, 38, 56, 89, 118, 129, 158, 178, 200, 231, 21, 29, 49, 63, 85, 111, 142, 163, 193, 222, + 27, 48, 77, 103, 133, 158, 179, 196, 215, 232, 29, 47, 74, 99, 124, 151, 176, 198, 220, 237, + 33, 42, 61, 76, 93, 121, 155, 174, 207, 225, 29, 53, 87, 112, 136, 154, 170, 188, 208, 227, + 24, 30, 52, 84, 131, 150, 166, 186, 203, 229, 37, 48, 64, 84, 104, 118, 156, 177, 201, 230, +} +T.NLSF_CB1_Wght_Q9 = { + 2897, 2314, 2314, 2314, 2287, 2287, 2314, 2300, 2327, 2287, 2888, 2580, 2394, 2367, 2314, 2274, 2274, 2274, 2274, 2194, + 2487, 2340, 2340, 2314, 2314, 2314, 2340, 2340, 2367, 2354, 3216, 2766, 2340, 2340, 2314, 2274, 2221, 2207, 2261, 2194, + 2460, 2474, 2367, 2394, 2394, 2394, 2394, 2367, 2407, 2314, 3479, 3056, 2127, 2207, 2274, 2274, 2274, 2287, 2314, 2261, + 3282, 3141, 2580, 2394, 2247, 2221, 2207, 2194, 2194, 2114, 4096, 3845, 2221, 2620, 2620, 2407, 2314, 2394, 2367, 2074, + 3178, 3244, 2367, 2221, 2553, 2434, 2340, 2314, 2167, 2221, 3338, 3488, 2726, 2194, 2261, 2460, 2354, 2367, 2207, 2101, + 2354, 2420, 2327, 2367, 2394, 2420, 2420, 2420, 2460, 2367, 3779, 3629, 2434, 2527, 2367, 2274, 2274, 2300, 2207, 2048, + 3254, 3225, 2713, 2846, 2447, 2327, 2300, 2300, 2274, 2127, 3263, 3300, 2753, 2806, 2447, 2261, 2261, 2247, 2127, 2101, + 2873, 2981, 2633, 2367, 2407, 2354, 2194, 2247, 2247, 2114, 3225, 3197, 2633, 2580, 2274, 2181, 2247, 2221, 2221, 2141, + 3178, 3310, 2740, 2407, 2274, 2274, 2274, 2287, 2194, 2114, 3141, 3272, 2460, 2061, 2287, 2500, 2367, 2487, 2434, 2181, + 3507, 3282, 2314, 2700, 2647, 2474, 2367, 2394, 2340, 2127, 3423, 3535, 3038, 3056, 2300, 1950, 2221, 2274, 2274, 2274, + 3404, 3366, 2087, 2687, 2873, 2354, 2420, 2274, 2474, 2540, 3760, 3488, 1950, 2660, 2897, 2527, 2394, 2367, 2460, 2261, + 3028, 3272, 2740, 2888, 2740, 2154, 2127, 2287, 2234, 2247, 3695, 3657, 2025, 1969, 2660, 2700, 2580, 2500, 2327, 2367, + 3207, 3413, 2354, 2074, 2888, 2888, 2340, 2487, 2247, 2167, 3338, 3366, 2846, 2780, 2327, 2154, 2274, 2287, 2114, 2061, + 2327, 2300, 2181, 2167, 2181, 2367, 2633, 2700, 2700, 2553, 2407, 2434, 2221, 2261, 2221, 2221, 2340, 2420, 2607, 2700, + 3038, 3244, 2806, 2888, 2474, 2074, 2300, 2314, 2354, 2380, 2221, 2154, 2127, 2287, 2500, 2793, 2793, 2620, 2580, 2367, + 3676, 3713, 2234, 1838, 2181, 2753, 2726, 2673, 2513, 2207, 2793, 3160, 2726, 2553, 2846, 2513, 2181, 2394, 2221, 2181, +} +T.NLSF_CB1_iCDF_NB_MB = { + 212, 178, 148, 129, 108, 96, 85, 82, 79, 77, 61, 59, 57, 56, 51, 49, 48, 45, 42, 41, + 40, 38, 36, 34, 31, 30, 21, 12, 10, 3, 1, 0, 255, 245, 244, 236, 233, 225, 217, 203, + 190, 176, 175, 161, 149, 136, 125, 114, 102, 91, 81, 71, 60, 52, 43, 35, 28, 20, 19, 18, + 12, 11, 5, 0, +} +T.NLSF_CB2_SELECT_NB_MB = { + 16, 0, 0, 0, 0, 99, 66, 36, 36, 34, 36, 34, 34, 34, 34, 83, 69, 36, 52, 34, + 116, 102, 70, 68, 68, 176, 102, 68, 68, 34, 65, 85, 68, 84, 36, 116, 141, 152, 139, 170, + 132, 187, 184, 216, 137, 132, 249, 168, 185, 139, 104, 102, 100, 68, 68, 178, 218, 185, 185, 170, + 244, 216, 187, 187, 170, 244, 187, 187, 219, 138, 103, 155, 184, 185, 137, 116, 183, 155, 152, 136, + 132, 217, 184, 184, 170, 164, 217, 171, 155, 139, 244, 169, 184, 185, 170, 164, 216, 223, 218, 138, + 214, 143, 188, 218, 168, 244, 141, 136, 155, 170, 168, 138, 220, 219, 139, 164, 219, 202, 216, 137, + 168, 186, 246, 185, 139, 116, 185, 219, 185, 138, 100, 100, 134, 100, 102, 34, 68, 68, 100, 68, + 168, 203, 221, 218, 168, 167, 154, 136, 104, 70, 164, 246, 171, 137, 139, 137, 155, 218, 219, 139, +} +T.NLSF_CB2_iCDF_NB_MB = { + 255, 254, 253, 238, 14, 3, 2, 1, 0, 255, 254, 252, 218, 35, 3, 2, 1, 0, 255, 254, + 250, 208, 59, 4, 2, 1, 0, 255, 254, 246, 194, 71, 10, 2, 1, 0, 255, 252, 236, 183, + 82, 8, 2, 1, 0, 255, 252, 235, 180, 90, 17, 2, 1, 0, 255, 248, 224, 171, 97, 30, + 4, 1, 0, 255, 254, 236, 173, 95, 37, 7, 1, 0, +} +T.NLSF_PRED_NB_MB_Q8 = { + 179, 138, 140, 148, 151, 149, 153, 151, 163, 116, 67, 82, 59, 92, 72, 100, 89, 92, +} +T.NLSF_DELTA_MIN_NB_MB_Q15 = { + 250, 3, 6, 3, 3, 3, 4, 3, 3, 3, 461, +} +T.pitch_lag_iCDF = { + 253, 250, 244, 233, 212, 182, 150, 131, 120, 110, 98, 85, 72, 60, 49, 40, 32, 25, 19, 15, + 13, 11, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, +} +T.pitch_delta_iCDF = { + 210, 208, 206, 203, 199, 193, 183, 168, 142, 104, 74, 52, 37, 27, 20, 14, 10, 6, 4, 2, + 0, +} +T.pitch_contour_iCDF = { + 223, 201, 183, 167, 152, 138, 124, 111, 98, 88, 79, 70, 62, 56, 50, 44, 39, 35, 31, 27, + 24, 21, 18, 16, 14, 12, 10, 8, 6, 4, 3, 2, 1, 0, +} +T.pitch_contour_NB_iCDF = { + 188, 176, 155, 138, 119, 97, 67, 43, 26, 10, 0, +} +T.pitch_contour_10_ms_iCDF = { + 165, 119, 80, 61, 47, 35, 27, 20, 14, 9, 4, 0, +} +T.pitch_contour_10_ms_NB_iCDF = { + 113, 63, 0, +} +T.stereo_pred_quant_Q13 = { + -13732, -10050, -8266, -7526, -6500, -5000, -2950, -820, 820, 2950, 5000, 6500, 7526, 8266, 10050, 13732, +} +T.stereo_pred_joint_iCDF = { + 249, 247, 246, 245, 244, 234, 210, 202, 201, 200, 197, 174, 82, 59, 56, 55, 54, 46, 22, 12, + 11, 10, 9, 7, 0, +} +T.stereo_only_code_mid_iCDF = { + 64, 0, +} +T.LBRR_flags_2_iCDF = { + 203, 150, 0, +} +T.LBRR_flags_3_iCDF = { + 215, 195, 166, 125, 110, 82, 0, +} +T.lsb_iCDF = { + 120, 0, +} +T.LTPscale_iCDF = { + 128, 64, 0, +} +T.type_offset_VAD_iCDF = { + 232, 158, 10, 0, +} +T.type_offset_no_VAD_iCDF = { + 230, 0, +} +T.NLSF_interpolation_factor_iCDF = { + 243, 221, 192, 181, 0, +} +T.LTPScales_table_Q14 = { + 15565, 12288, 8192, +} +T.uniform3_iCDF = { + 171, 85, 0, +} +T.uniform4_iCDF = { + 192, 128, 64, 0, +} +T.uniform5_iCDF = { + 205, 154, 102, 51, 0, +} +T.uniform6_iCDF = { + 213, 171, 128, 85, 43, 0, +} +T.uniform8_iCDF = { + 224, 192, 160, 128, 96, 64, 32, 0, +} +T.NLSF_EXT_iCDF = { + 100, 40, 16, 7, 3, 1, 0, +} +T.gain_iCDF = { + 224, 112, 44, 15, 3, 2, 1, 0, 254, 237, 192, 132, 70, 23, 4, 0, 255, 252, 226, 155, + 61, 11, 2, 0, +} +T.delta_gain_iCDF = { + 250, 245, 234, 203, 71, 50, 42, 38, 35, 33, 31, 29, 28, 27, 26, 25, 24, 23, 22, 21, + 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, + 0, +} +T.LSFCosTab_FIX_Q12 = { + 8192, 8190, 8182, 8170, 8152, 8130, 8104, 8072, 8034, 7994, 7946, 7896, 7840, 7778, 7714, 7644, 7568, 7490, 7406, 7318, + 7226, 7128, 7026, 6922, 6812, 6698, 6580, 6458, 6332, 6204, 6070, 5934, 5792, 5648, 5502, 5352, 5198, 5040, 4880, 4718, + 4552, 4382, 4212, 4038, 3862, 3684, 3502, 3320, 3136, 2948, 2760, 2570, 2378, 2186, 1990, 1794, 1598, 1400, 1202, 1002, + 802, 602, 402, 202, 0, -202, -402, -602, -802, -1002, -1202, -1400, -1598, -1794, -1990, -2186, -2378, -2570, -2760, -2948, + -3136, -3320, -3502, -3684, -3862, -4038, -4212, -4382, -4552, -4718, -4880, -5040, -5198, -5352, -5502, -5648, -5792, -5934, -6070, -6204, + -6332, -6458, -6580, -6698, -6812, -6922, -7026, -7128, -7226, -7318, -7406, -7490, -7568, -7644, -7714, -7778, -7840, -7896, -7946, -7994, + -8034, -8072, -8104, -8130, -8152, -8170, -8182, -8190, -8192, +} +T.pulses_per_block_iCDF = { + 125, 51, 26, 18, 15, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 198, 105, + 45, 22, 15, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 213, 162, 116, 83, + 59, 43, 32, 24, 18, 15, 12, 9, 7, 6, 5, 3, 2, 0, 239, 187, 116, 59, 28, 16, + 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 250, 229, 188, 135, 86, 51, 30, 19, + 13, 10, 8, 6, 5, 4, 3, 2, 1, 0, 249, 235, 213, 185, 156, 128, 103, 83, 66, 53, + 42, 33, 26, 21, 17, 13, 10, 0, 254, 249, 235, 206, 164, 118, 77, 46, 27, 16, 10, 7, + 5, 4, 3, 2, 1, 0, 255, 253, 249, 239, 220, 191, 156, 119, 85, 57, 37, 23, 15, 10, + 6, 4, 2, 0, 255, 253, 251, 246, 237, 223, 203, 179, 152, 124, 98, 75, 55, 40, 29, 21, + 15, 0, 255, 254, 253, 247, 220, 162, 106, 67, 42, 28, 18, 12, 9, 6, 4, 3, 2, 0, +} +T.rate_levels_iCDF = { + 241, 190, 178, 132, 87, 74, 41, 14, 0, 223, 193, 157, 140, 106, 57, 39, 18, 0, +} +T.shell_code_table0 = { + 128, 0, 214, 42, 0, 235, 128, 21, 0, 244, 184, 72, 11, 0, 248, 214, 128, 42, 7, 0, + 248, 225, 170, 80, 25, 5, 0, 251, 236, 198, 126, 54, 18, 3, 0, 250, 238, 211, 159, 82, + 35, 15, 5, 0, 250, 231, 203, 168, 128, 88, 53, 25, 6, 0, 252, 238, 216, 185, 148, 108, + 71, 40, 18, 4, 0, 253, 243, 225, 199, 166, 128, 90, 57, 31, 13, 3, 0, 254, 246, 233, + 212, 183, 147, 109, 73, 44, 23, 10, 2, 0, 255, 250, 240, 223, 198, 166, 128, 90, 58, 33, + 16, 6, 1, 0, 255, 251, 244, 231, 210, 181, 146, 110, 75, 46, 25, 12, 5, 1, 0, 255, + 253, 248, 238, 221, 196, 164, 128, 92, 60, 35, 18, 8, 3, 1, 0, 255, 253, 249, 242, 229, + 208, 180, 146, 110, 76, 48, 27, 14, 7, 3, 1, 0, +} +T.shell_code_table1 = { + 129, 0, 207, 50, 0, 236, 129, 20, 0, 245, 185, 72, 10, 0, 249, 213, 129, 42, 6, 0, + 250, 226, 169, 87, 27, 4, 0, 251, 233, 194, 130, 62, 20, 4, 0, 250, 236, 207, 160, 99, + 47, 17, 3, 0, 255, 240, 217, 182, 131, 81, 41, 11, 1, 0, 255, 254, 233, 201, 159, 107, + 61, 20, 2, 1, 0, 255, 249, 233, 206, 170, 128, 86, 50, 23, 7, 1, 0, 255, 250, 238, + 217, 186, 148, 108, 70, 39, 18, 6, 1, 0, 255, 252, 243, 226, 200, 166, 128, 90, 56, 30, + 13, 4, 1, 0, 255, 252, 245, 231, 209, 180, 146, 110, 76, 47, 25, 11, 4, 1, 0, 255, + 253, 248, 237, 219, 194, 163, 128, 93, 62, 37, 19, 8, 3, 1, 0, 255, 254, 250, 241, 226, + 205, 177, 145, 111, 79, 51, 30, 15, 6, 2, 1, 0, +} +T.shell_code_table2 = { + 129, 0, 203, 54, 0, 234, 129, 23, 0, 245, 184, 73, 10, 0, 250, 215, 129, 41, 5, 0, + 252, 232, 173, 86, 24, 3, 0, 253, 240, 200, 129, 56, 15, 2, 0, 253, 244, 217, 164, 94, + 38, 10, 1, 0, 253, 245, 226, 189, 132, 71, 27, 7, 1, 0, 253, 246, 231, 203, 159, 105, + 56, 23, 6, 1, 0, 255, 248, 235, 213, 179, 133, 85, 47, 19, 5, 1, 0, 255, 254, 243, + 221, 194, 159, 117, 70, 37, 12, 2, 1, 0, 255, 254, 248, 234, 208, 171, 128, 85, 48, 22, + 8, 2, 1, 0, 255, 254, 250, 240, 220, 189, 149, 107, 67, 36, 16, 6, 2, 1, 0, 255, + 254, 251, 243, 227, 201, 166, 128, 90, 55, 29, 13, 5, 2, 1, 0, 255, 254, 252, 246, 234, + 213, 183, 147, 109, 73, 43, 22, 10, 4, 2, 1, 0, +} +T.shell_code_table3 = { + 130, 0, 200, 58, 0, 231, 130, 26, 0, 244, 184, 76, 12, 0, 249, 214, 130, 43, 6, 0, + 252, 232, 173, 87, 24, 3, 0, 253, 241, 203, 131, 56, 14, 2, 0, 254, 246, 221, 167, 94, + 35, 8, 1, 0, 254, 249, 232, 193, 130, 65, 23, 5, 1, 0, 255, 251, 239, 211, 162, 99, + 45, 15, 4, 1, 0, 255, 251, 243, 223, 186, 131, 74, 33, 11, 3, 1, 0, 255, 252, 245, + 230, 202, 158, 105, 57, 24, 8, 2, 1, 0, 255, 253, 247, 235, 214, 179, 132, 84, 44, 19, + 7, 2, 1, 0, 255, 254, 250, 240, 223, 196, 159, 112, 69, 36, 15, 6, 2, 1, 0, 255, + 254, 253, 245, 231, 209, 176, 136, 93, 55, 27, 11, 3, 2, 1, 0, 255, 254, 253, 252, 239, + 221, 194, 158, 117, 76, 42, 18, 4, 3, 2, 1, 0, +} +T.shell_code_table_offsets = { + 0, 0, 2, 5, 9, 14, 20, 27, 35, 44, 54, 65, 77, 90, 104, 119, 135, +} +T.sign_iCDF = { + 254, 49, 67, 77, 82, 93, 99, 198, 11, 18, 24, 31, 36, 45, 255, 46, 66, 78, 87, 94, + 104, 208, 14, 21, 32, 42, 51, 66, 255, 94, 104, 109, 112, 115, 118, 248, 53, 69, 80, 88, + 95, 102, +} +T.CB_lags_stage2_10_ms = { + 0, 1, 0, 0, 0, 1, +} +T.CB_lags_stage3_10_ms = { + 0, 0, 1, -1, 1, -1, 2, -2, 2, -2, 3, -3, 0, 1, 0, 1, -1, 2, -1, 2, + -2, 3, -2, 3, +} +T.CB_lags_stage2 = { + 0, 2, -1, -1, -1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, + 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, -1, 2, 1, 0, 1, 1, + 0, 0, -1, -1, +} +T.CB_lags_stage3 = { + 0, 0, 1, -1, 0, 1, -1, 0, -1, 1, -2, 2, -2, -2, 2, -3, 2, 3, -3, -4, + 3, -4, 4, 4, -5, 5, -6, -5, 6, -7, 6, 5, 8, -9, 0, 0, 1, 0, 0, 0, + 0, 0, 0, 0, -1, 1, 0, 0, 1, -1, 0, 1, -1, -1, 1, -1, 2, 1, -1, 2, + -2, -2, 2, -2, 2, 2, 3, -3, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, + 0, 1, -1, 1, 0, 0, 2, 1, -1, 2, -1, -1, 2, -1, 2, 2, -1, 3, -2, -2, + -2, 3, 0, 1, 0, 0, 1, 0, 1, -1, 2, -1, 2, -1, 2, 3, -2, 3, -2, -2, + 4, 4, -3, 5, -3, -4, 6, -4, 6, 5, -5, 8, -6, -5, -7, 9, +} +T.resampler_frac_FIR_12 = { + 189, -600, 617, 30567, 117, -159, -1070, 29704, 52, 221, -2392, 28276, -4, 529, -3350, 26341, -48, 758, -3956, 23973, + -80, 905, -4235, 21254, -99, 972, -4222, 18278, -107, 967, -3957, 15143, -103, 896, -3487, 11950, -91, 773, -2865, 8798, + -71, 611, -2143, 5784, -46, 425, -1375, 2996, +} +return T +end +end + + + + + + Vorbis + --!optimize 2 +--!nocheck +-- rosetta chunk Vorbis (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 5 modules (3 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["codecs/audio/Vorbis"] = function() + +-- codecs/audio/Vorbis: the Vorbis I decoder without its container. +-- A Luau port of stb_vorbis 1.22 (public domain / MIT, licenses/stb_vorbis-LICENSE.txt). +local Vorbis = { + Setup = __include("codecs/audio/Vorbis/Setup"), + Codebook = __include("codecs/audio/Vorbis/Codebook"), + Packet = __include("codecs/audio/Vorbis/Packet"), + Tables = __include("codecs/audio/Vorbis/Tables"), +} + +return Vorbis +end +__FILES["codecs/audio/Vorbis/Codebook"] = @native function() + + + +-- codecs/audio/Vorbis/Codebook: the Vorbis LSB-first bit reader and codebooks (Vorbis I spec sections 2 and 3). +-- Ported from stb_vorbis 1.22 (public domain / MIT, licenses/stb_vorbis-LICENSE.txt). Reading past the packet end gives +-- zero bits and sets eop (the spec's end-of-packet condition); an invalid codeword also sets eop and decodes to -1. +local Codebook = {} + +local readu8 = buffer.readu8 +local floor = math.floor + +local POW = table.create(41, 0) +for i = 0, 40 do + POW[i + 1] = 2 ^ i +end + +type Br = { + buf: buffer, + pos: number, + limit: number, + acc: number, + cnt: number, + pad: number, + eop: boolean, +} + +@native function Codebook.reader(buf: buffer, offset: number, size: number): Br + return { buf = buf, pos = offset, limit = offset + size, acc = 0, cnt = 0, pad = 0, eop = false } +end + +@native local function bits(br: Br, n: number): number + if n == 0 then + return 0 + end + local acc, cnt = br.acc, br.cnt + if cnt < n then + local b, p, lim = br.buf, br.pos, br.limit + repeat + if p < lim then + acc += readu8(b, p) * POW[cnt + 1] + p += 1 + else + br.pad += 8 + end + cnt += 8 + until cnt >= n + br.pos = p + end + local m = POW[n + 1] + local v = acc % m + br.acc = (acc - v) / m + cnt -= n + br.cnt = cnt + if cnt < br.pad then + br.eop = true + br.pad = cnt + end + return v +end +Codebook.bits = bits + +-- ilog (spec 9.2.1) +@native local function ilog(x: number): number + local n = 0 + while x > 0 do + n += 1 + x = floor(x / 2) + end + return n +end +Codebook.ilog = ilog + +-- float32_unpack (spec 9.2.2) +@native local function float32Unpack(x: number): number + local mantissa = x % 2097152 + local sign = x >= 2147483648 + local exp = floor((x % 2147483648) / 2097152) + local v = mantissa * 2 ^ (exp - 788) + return if sign then -v else v +end + +type Book = { + dims: number, + entries: number, + fastBits: number, + fastLen: { number }, -- per fastBits-bit prefix: code length (> 0), 0 = continue in the tree, -1 = invalid + fastSym: { number }, -- symbol, or the tree node to continue from + c0: { number }, -- tree: child for bit 0 / 1: > 0 node, < 0 leaf (-symbol - 1), 0 none + c1: { number }, + lookup: number, + vq: { number }?, + used: number, +} + +local MAX_ENTRIES = 2 ^ 20 +local MAX_VQ = 2 ^ 22 + +-- lookup1_values(entries, dims): the largest r with r^dims <= entries +@native local function lookup1Values(entries: number, dims: number): number + local r = floor(math.exp(math.log(entries) / dims)) + if floor((r + 1) ^ dims) <= entries then + r += 1 + end + if (r + 1) ^ dims <= entries then + return -1 + end + if floor(r ^ dims) > entries then + return -1 + end + return r +end + +-- assign codewords (spec 3.2.1: in entry order, the lowest free leaf) and build the decode tree + fast table +@native local function build(book: Book, lengths: { number }): string? + local n = book.entries + local c0, c1 = book.c0, book.c1 + local nodes = 1 + c0[1], c1[1] = 0, 0 + local available = table.create(33, 0) -- available[l]: the free code at depth l, as a 32-bit left-aligned value + 1 (0 = none) + local first = true + local used = 0 + local maxLen = 0 + for i = 0, n - 1 do + local len = lengths[i + 1] + if len > 0 then + local code: number + if first then + first = false + code = 0 + for l = 1, len do + available[l + 1] = POW[33 - l] + 1 + end + else + local z = len + while z > 0 and available[z + 1] == 0 do + z -= 1 + end + if z == 0 then + return "over-subscribed codebook" + end + code = available[z + 1] - 1 + available[z + 1] = 0 + for y = len, z + 1, -1 do + available[y + 1] = code + POW[33 - y] + 1 + end + end + local node = 1 + for d = 1, len do + local bit = floor(code / POW[33 - d]) % 2 + local child = if bit == 0 then c0[node] else c1[node] + if d == len then + if child ~= 0 then + return "ambiguous codeword" + end + if bit == 0 then + c0[node] = -(i + 1) + else + c1[node] = -(i + 1) + end + else + if child < 0 then + return "ambiguous codeword" + elseif child == 0 then + nodes += 1 + c0[nodes], c1[nodes] = 0, 0 + child = nodes + if bit == 0 then + c0[node] = child + else + c1[node] = child + end + end + node = child + end + end + used += 1 + if len > maxLen then + maxLen = len + end + end + end + book.used = used + local fb = math.clamp(maxLen, 1, 10) + book.fastBits = fb + local size = POW[fb + 1] + local fl, fs = table.create(size, -1), table.create(size, 0) + for idx = 0, size - 1 do + local node = 1 + local v = idx + for d = 1, fb do + local bit = v % 2 + v = (v - bit) / 2 + local child = if bit == 0 then c0[node] else c1[node] + if child < 0 then + fl[idx + 1], fs[idx + 1] = d, -child - 1 + break + elseif child == 0 then + break + end + node = child + if d == fb then + fl[idx + 1], fs[idx + 1] = 0, node + end + end + end + book.fastLen, book.fastSym = fl, fs + return nil +end + +@native function Codebook.read(br: Br): (Book?, string?) + if bits(br, 24) ~= 0x564342 then + return nil, "bad codebook sync" + end + local dims = bits(br, 16) + local entries = bits(br, 24) + local ordered = bits(br, 1) + if br.eop then + return nil, "setup header ends in a codebook" + end + if dims == 0 and entries ~= 0 then + return nil, "codebook with 0 dimensions" + end + if entries > MAX_ENTRIES then + return nil, "codebook with " .. entries .. " entries" + end + local lengths = table.create(entries, 0) + if ordered == 1 then + local cur = 0 + local len = bits(br, 5) + 1 + while cur < entries do + local num = bits(br, ilog(entries - cur)) + if len >= 32 or cur + num > entries or br.eop then + return nil, "bad ordered codebook lengths" + end + for k = cur + 1, cur + num do + lengths[k] = len + end + cur += num + len += 1 + end + else + local sparse = bits(br, 1) + for j = 1, entries do + if sparse == 0 or bits(br, 1) == 1 then + local l = bits(br, 5) + 1 + if l == 32 then + return nil, "codeword length 32" + end + lengths[j] = l + end + end + end + if br.eop then + return nil, "setup header ends in a codebook" + end + local book: Book = { + dims = dims, + entries = entries, + fastBits = 1, + fastLen = {}, + fastSym = {}, + c0 = {}, + c1 = {}, + lookup = 0, + vq = nil, + used = 0, + } + local err = build(book, lengths) + if err then + return nil, err + end + local lookup = bits(br, 4) + if lookup > 2 then + return nil, "lookup type " .. lookup + end + book.lookup = lookup + if lookup > 0 then + local minimum = float32Unpack(bits(br, 32)) + local delta = float32Unpack(bits(br, 32)) + local valueBits = bits(br, 4) + 1 + local seq = bits(br, 1) == 1 + local nvalues + if lookup == 1 then + nvalues = lookup1Values(entries, dims) + if nvalues < 0 then + return nil, "bad lookup1 size" + end + else + nvalues = entries * dims + end + if nvalues == 0 then + return nil, "empty lookup table" + end + if entries * dims > MAX_VQ or nvalues > MAX_VQ then + return nil, "lookup table too large" + end + local mults = table.create(nvalues, 0) + for j = 1, nvalues do + mults[j] = bits(br, valueBits) + end + if br.eop then + return nil, "setup header ends in a lookup table" + end + -- expand to one vector per entry (spec 3.2.1, "VQ lookup table vector representation") + local vq = table.create(entries * dims, 0) + for e = 0, entries - 1 do + local last = 0 + local div = 1 + for k = 0, dims - 1 do + local off + if lookup == 1 then + off = floor(e / div) % nvalues + div *= nvalues + else + off = e * dims + k + end + local v = mults[off + 1] * delta + minimum + last + if seq then + last = v + end + vq[e * dims + k + 1] = v + end + end + book.vq = vq + end + return book, nil +end + +@native local function decode(br: Br, book: Book): number + local fb = book.fastBits + local acc, cnt = br.acc, br.cnt + if cnt < fb then + local b, p, lim = br.buf, br.pos, br.limit + repeat + if p < lim then + acc += readu8(b, p) * POW[cnt + 1] + p += 1 + else + br.pad += 8 + end + cnt += 8 + until cnt >= fb + br.pos = p + br.acc, br.cnt = acc, cnt + end + local idx = acc % POW[fb + 1] + 1 + local l = book.fastLen[idx] + if l > 0 then + local m = POW[l + 1] + br.acc = (acc - acc % m) / m + cnt -= l + br.cnt = cnt + if cnt < br.pad then + br.eop = true + br.pad = cnt + return -1 + end + return book.fastSym[idx] + elseif l == 0 then + bits(br, fb) + local node = book.fastSym[idx] + local c0, c1 = book.c0, book.c1 + while true do + local child = if bits(br, 1) == 0 then c0[node] else c1[node] + if br.eop then + return -1 + end + if child < 0 then + return -child - 1 + elseif child == 0 then + br.eop = true + return -1 + end + node = child + end + end + br.eop = true + return -1 +end +Codebook.decode = decode + +return Codebook +end +__FILES["codecs/audio/Vorbis/Packet"] = @native function() + + + +-- codecs/audio/Vorbis/Packet: Vorbis audio packet decoding (Vorbis I spec sections 4.3, 7, 8). +-- Floors, residues and coupling ported from stb_vorbis 1.22 (public domain / MIT, 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 two window +-- centres, so granule positions count exactly the samples returned (the first packet returns none). +local Codebook = __include("codecs/audio/Vorbis/Codebook") +local Setup = __include("codecs/audio/Vorbis/Setup") +local Tables = __include("codecs/audio/Vorbis/Tables") +local Mdct = __include("codecs/audio/Mdct") + +local Packet = {} + +local bits, decode = Codebook.bits, Codebook.decode +local ilog = Codebook.ilog +local INV_DB = Tables +local RANGE = { 256, 128, 86, 64 } + +type State = { + channels: number, + n0: number, + n1: number, + setup: Setup.Setup, + plans: { [number]: Mdct.Plan }, + slopes: { [number]: { number } }, + spec: { { number } }, + frame: { { number } }, + tail: { { number } }, + tailLen: number, + prevN: number, + out: { { number } }, + finalY: { { number } }, + step2: { number }, + inter: { number }, + zero: { boolean }, + reallyZero: { boolean }, + partClass: { { { number } } }, +} + +@native function Packet.new(id: Setup.Ident, setup: Setup.Setup): State? + local n0, n1, ch = id.blocksize0, id.blocksize1, id.channels + local plans: { [number]: Mdct.Plan } = {} + local slopes: { [number]: { number } } = {} + for _, n in { n0, n1 } do + local p = Mdct.new(n) + if not p then + return nil + end + plans[n] = p + local w = Mdct.window("vorbis", n) :: { number } + local half = table.create(n // 2, 0) + for i = 1, n // 2 do + half[i] = w[i] + end + slopes[n // 2] = half + end + @native local function arrays(len: number): { { number } } + local t = table.create(ch) + for c = 1, ch do + t[c] = table.create(len, 0) + end + return t + end + local partClass = table.create(ch) + for c = 1, ch do + partClass[c] = {} + end + return { + channels = ch, + n0 = n0, + n1 = n1, + setup = setup, + plans = plans, + slopes = slopes, + spec = arrays(n1 // 2), + frame = arrays(n1), + tail = arrays(n1 // 2), + tailLen = 0, + prevN = 0, + out = arrays(n1), + finalY = arrays(math.max(2, setup.maxFloorValues)), + step2 = table.create(math.max(2, setup.maxFloorValues), 0), + inter = table.create(n1 // 2 * ch, 0), + zero = table.create(ch, false), + reallyZero = table.create(ch, false), + partClass = partClass, + } +end + +@native function Packet.reset(st: State) + st.prevN = 0 + st.tailLen = 0 +end + +@native function Packet.blocksize(st: State, b: buffer, off: number, size: number): number + if size < 1 then + return 0 + end + local br = Codebook.reader(b, off, size) + if bits(br, 1) ~= 0 then + return 0 + end + local m = bits(br, st.setup.modeBits) + local mode = st.setup.modes[m + 1] + if not mode or br.eop then + return 0 + end + return if mode.blockflag == 1 then st.n1 else st.n0 +end + +@native local function predict(x: number, x0: number, x1: number, y0: number, y1: number): number + local dy = y1 - y0 + local adx = x1 - x0 + local off = ((if dy < 0 then -dy else dy) * (x - x0)) // adx + return if dy < 0 then y0 - off else y0 + off +end + +-- multiply out[x0 .. x1) by the floor line from (x0, y0) to (x1, y1) (stb draw_line) +@native local function drawLine(out: { number }, x0: number, y0: number, x1: number, y1: number, n: number) + local dy = y1 - y0 + local adx = x1 - x0 + local ady = if dy < 0 then -dy else dy + local base = if dy < 0 then -(ady // adx) else ady // adx + local sy = if dy < 0 then base - 1 else base + 1 + ady -= (if base < 0 then -base else base) * adx + if x1 > n then + x1 = n + end + local x, y, err = x0, y0, 0 + if x < x1 then + out[x + 1] *= INV_DB[y % 256 + 1] + x += 1 + while x < x1 do + err += ady + if err >= adx then + err -= adx + y += sy + else + y += base + end + out[x + 1] *= INV_DB[y % 256 + 1] + x += 1 + end + end +end + +@native local function floorDecode(st: State, br: Codebook.Br, g: Setup.Floor1, finalY: { number }): boolean + if bits(br, 1) == 0 then + return false + end + local books = st.setup.books + local range = RANGE[g.multiplier] + local yb = ilog(range) - 1 + finalY[1] = bits(br, yb) + finalY[2] = bits(br, yb) + local offset = 2 + for j = 1, g.partitions do + local pclass = g.partitionClass[j] + 1 + local cdim = g.classDims[pclass] + local cbits = g.classSubs[pclass] + local csub = 2 ^ cbits + local cval = 0 + if cbits > 0 then + cval = decode(br, books[g.classMaster[pclass] + 1]) + if cval < 0 then + return false + end + end + local subs = g.subBooks[pclass] + for _ = 1, cdim do + local book = subs[cval % csub + 1] + cval = cval // csub + if book >= 0 then + local v = decode(br, books[book + 1]) + if v < 0 then + return false + end + finalY[offset + 1] = v + else + finalY[offset + 1] = 0 + end + offset += 1 + end + end + if br.eop then + return false + end + -- step 1: amplitude value synthesis + local step2 = st.step2 + step2[1], step2[2] = 1, 1 + local xl, low, high = g.xlist, g.low, g.high + for j = 2, g.values - 1 do + local lo, hi = low[j + 1], high[j + 1] + local pred = predict(xl[j + 1], xl[lo + 1], xl[hi + 1], finalY[lo + 1], finalY[hi + 1]) + local val = finalY[j + 1] + local highroom = range - pred + local lowroom = pred + local room = if highroom < lowroom then highroom * 2 else lowroom * 2 + if val ~= 0 then + step2[lo + 1], step2[hi + 1], step2[j + 1] = 1, 1, 1 + if val >= room then + if highroom > lowroom then + finalY[j + 1] = val - lowroom + pred + else + finalY[j + 1] = pred - val + highroom - 1 + end + elseif val % 2 == 1 then + finalY[j + 1] = pred - (val + 1) // 2 + else + finalY[j + 1] = pred + val // 2 + end + else + step2[j + 1] = 0 + finalY[j + 1] = pred + end + end + for j = 1, g.values do + if step2[j] == 0 then + finalY[j] = -1 + end + end + return true +end + +-- multiply target[1 .. n2] by the floor curve (stb do_floor) +@native local function floorCurve(g: Setup.Floor1, finalY: { number }, target: { number }, n2: number) + local mult = g.multiplier + local lx, ly = 0, finalY[1] * mult + local sorted, xl = g.sorted, g.xlist + for q = 2, g.values do + local j = sorted[q] + 1 + local fy = finalY[j] + if fy >= 0 then + local hy = fy * mult + local hx = xl[j] + if lx ~= hx then + drawLine(target, lx, ly, hx, hy, n2) + end + lx, ly = hx, hy + end + end + if lx < n2 then + local v = INV_DB[ly % 256 + 1] + for j = lx + 1, n2 do + target[j] *= v + end + end +end + +@native local function partition(br: Codebook.Br, book: Codebook.Book, target: { number }, offset: number, psize: number, rtype: number, limit: number): boolean + local vq = book.vq + if not vq then + br.eop = true -- a scalar book in a vector context: invalid stream + return false + end + local dims = book.dims + if rtype == 0 then + local step = psize // dims + for k = 0, step - 1 do + local e = decode(br, book) + if e < 0 then + return false + end + local base = e * dims + for i = 0, dims - 1 do + local at = offset + k + i * step + if at < limit then + target[at + 1] += vq[base + i + 1] + end + end + end + else + local k = 0 + while k < psize do + local e = decode(br, book) + if e < 0 then + return false + end + local base = e * dims + local len = math.min(dims, psize - k) + local at = offset + k + for i = 0, len - 1 do + if at + i < limit then + target[at + i + 1] += vq[base + i + 1] + end + end + k += dims + end + end + return true +end + +@native local function residue(st: State, br: Codebook.Br, r: Setup.Residue, targets: { { number } | false }, ch: number, n2: number) + local books = st.setup.books + local rtype = r.type + local cbook = books[r.classbook + 1] + local classwords = cbook.dims + for j = 1, ch do + local t = targets[j] + if t then + for i = 1, n2 do + (t :: { number })[i] = 0 + end + end + end + local any = false + for j = 1, ch do + if targets[j] then + any = true + end + end + if not any then + return + end + local psize = r.partSize + local rb = r.books + local classdata = r.classdata + if rtype == 2 and ch > 1 then + local total = n2 * ch + local inter = st.inter + for i = 1, total do + inter[i] = 0 + end + local lb = math.min(r.begin, total) + local le = math.min(r.finish, total) + local partRead = (le - lb) // psize + local pc = st.partClass[1] + local done = false + for pass = 1, 8 do + if done then + break + end + local pcount, classSet = 0, 1 + while pcount < partRead do + if pass == 1 then + local q = decode(br, cbook) + if q < 0 then + done = true + break + end + pc[classSet] = classdata[q + 1] + end + local cls = pc[classSet] + local i = 0 + while i < classwords and pcount < partRead do + local b = rb[cls[i + 1] + 1][pass] + if b >= 0 then + if not partition(br, books[b + 1], inter, r.begin + pcount * psize, psize, 1, total) then + done = true + break + end + end + i += 1 + pcount += 1 + end + if done then + break + end + classSet += 1 + end + end + for j = 1, ch do + local t = targets[j] + if t then + local tt = t :: { number } + local v = j + for i = 1, n2 do + tt[i] = inter[v] + v += ch + end + end + end + return + end + local lb = math.min(r.begin, n2) + local le = math.min(r.finish, n2) + local partRead = (le - lb) // psize + local pcs = st.partClass + for pass = 1, 8 do + local pcount, classSet = 0, 1 + while pcount < partRead do + if pass == 1 then + for j = 1, ch do + if targets[j] then + local q = decode(br, cbook) + if q < 0 then + return + end + pcs[j][classSet] = classdata[q + 1] + end + end + end + local i = 0 + while i < classwords and pcount < partRead do + for j = 1, ch do + local t = targets[j] + if t then + local c = pcs[j][classSet][i + 1] + local b = rb[c + 1][pass] + if b >= 0 then + if not partition(br, books[b + 1], t :: { number }, r.begin + pcount * psize, psize, rtype, n2) then + return + end + end + end + end + i += 1 + pcount += 1 + end + classSet += 1 + end + end +end + +@native function Packet.decode(st: State, b: buffer, off: number, size: number): number + if size < 1 then + return -1 + end + local setup = st.setup + local br = Codebook.reader(b, off, size) + if bits(br, 1) ~= 0 then + return -1 + end + local mode = setup.modes[bits(br, setup.modeBits) + 1] + if not mode then + return -1 + end + local n, prevLong, nextLong + if mode.blockflag == 1 then + n = st.n1 + prevLong = bits(br, 1) == 1 + nextLong = bits(br, 1) == 1 + else + n = st.n0 + prevLong, nextLong = false, false + end + if br.eop then + return -1 + end + local n2 = n // 2 + local n0 = st.n0 + local leftStart, leftEnd, rightStart, rightEnd + if mode.blockflag == 1 and not prevLong then + leftStart, leftEnd = (n - n0) // 4, (n + n0) // 4 + else + leftStart, leftEnd = 0, n2 + end + if mode.blockflag == 1 and not nextLong then + rightStart, rightEnd = (n * 3 - n0) // 4, (n * 3 + n0) // 4 + else + rightStart, rightEnd = n2, n + end + local map = setup.mappings[mode.mapping + 1] + local ch = st.channels + local spec, zero, reallyZero = st.spec, st.zero, st.reallyZero + for c = 1, ch do + local s = map.mux[c] + 1 + local g = setup.floors[map.submapFloor[s] + 1] + local ok = floorDecode(st, br, g, st.finalY[c]) + zero[c] = not ok + reallyZero[c] = not ok + end + -- channels coupled to a non-silent channel are decoded too + for i = 1, map.couplingSteps do + local m, a = map.magnitude[i] + 1, map.angle[i] + 1 + if not zero[m] or not zero[a] then + zero[m], zero[a] = false, false + end + end + for i = 1, map.submaps do + local targets: { { number } | false } = {} + local k = 0 + for c = 1, ch do + if map.mux[c] == i - 1 then + k += 1 + targets[k] = if zero[c] then false else spec[c] + end + end + residue(st, br, setup.residues[map.submapResidue[i] + 1], targets, k, n2) + end + for i = map.couplingSteps, 1, -1 do + local m, a = spec[map.magnitude[i] + 1], spec[map.angle[i] + 1] + for j = 1, n2 do + local mv, av = m[j], a[j] + local m2, a2 + if mv > 0 then + if av > 0 then + m2, a2 = mv, mv - av + else + a2, m2 = mv, mv + av + end + else + if av > 0 then + m2, a2 = mv, mv + av + else + a2, m2 = mv, mv - av + end + end + m[j], a[j] = m2, a2 + end + end + local plan = st.plans[n] + local lslope = st.slopes[leftEnd - leftStart] + local rslope = st.slopes[rightEnd - rightStart] + for c = 1, ch do + local sp = spec[c] + local fr = st.frame[c] + if reallyZero[c] then + for j = 1, n do + fr[j] = 0 + end + else + local s = map.mux[c] + 1 + floorCurve(setup.floors[map.submapFloor[s] + 1], st.finalY[c], sp, n2) + Mdct.inverse(plan, sp, 1, 1, fr, 1) + for j = 1, leftStart do + fr[j] = 0 + end + local L = leftEnd - leftStart + for j = 0, L - 1 do + fr[leftStart + j + 1] *= lslope[j + 1] + end + local R = rightEnd - rightStart + for j = 0, R - 1 do + fr[rightStart + j + 1] *= rslope[R - j] + end + for j = rightEnd + 1, n do + fr[j] = 0 + end + end + end + -- overlap-add with the previous frame; return the samples between the two centres + local prevN = st.prevN + local count = 0 + if prevN > 0 then + count = prevN // 4 + n // 4 + local o = prevN // 4 - n // 4 -- this frame starts o samples after the previous centre + local tl = st.tailLen + for c = 1, ch do + local out, tail, fr = st.out[c], st.tail[c], st.frame[c] + for j = 0, count - 1 do + local v = if j < tl then tail[j + 1] else 0 + local fi = j - o + if fi >= 0 then + v += fr[fi + 1] + end + out[j + 1] = v + end + end + end + local tl = rightEnd - n2 + for c = 1, ch do + local tail, fr = st.tail[c], st.frame[c] + for j = 1, tl do + tail[j] = fr[n2 + j] + end + end + st.tailLen = tl + st.prevN = n + return count +end + +return Packet +end +__FILES["codecs/audio/Vorbis/Setup"] = @native function() + + +-- codecs/audio/Vorbis/Setup: the three Vorbis header packets (Vorbis I spec section 4.2). +-- Ported from stb_vorbis 1.22 start_decoder (public domain / MIT, licenses/stb_vorbis-LICENSE.txt). Floor 0 is +-- rejected as unsupported, as stb_vorbis does. +local Codebook = __include("codecs/audio/Vorbis/Codebook") + +local Setup = {} + +local bits, ilog = Codebook.bits, Codebook.ilog +local readu8, readu32 = buffer.readu8, buffer.readu32 + +type Ident = { + channels: number, + sampleRate: number, + bitrateMax: number, + bitrateNominal: number, + bitrateMin: number, + blocksize0: number, + blocksize1: number, +} + +type Floor1 = { + partitions: number, + partitionClass: { number }, + classDims: { number }, + classSubs: { number }, + classMaster: { number }, + subBooks: { { number } }, + multiplier: number, + xlist: { number }, + values: number, + sorted: { number }, + low: { number }, + high: { number }, +} + +type Residue = { + type: number, + begin: number, + finish: number, + partSize: number, + classifications: number, + classbook: number, + books: { { number } }, + classdata: { { number } }, +} + +type Mapping = { + submaps: number, + couplingSteps: number, + magnitude: { number }, + angle: { number }, + mux: { number }, + submapFloor: { number }, + submapResidue: { number }, +} + +type Mode = { blockflag: number, mapping: number } + +type Setup = { + books: { Codebook.Book }, + floors: { Floor1 }, + residues: { Residue }, + mappings: { Mapping }, + modes: { Mode }, + modeBits: number, + maxFloorValues: number, +} + +@native local function isVorbis(b: buffer, o: number, n: number, kind: number): boolean + return n >= 7 and readu8(b, o) == kind and buffer.readstring(b, o + 1, 6) == "vorbis" +end +Setup.isVorbis = isVorbis + +@native function Setup.ident(b: buffer, o: number, n: number): (Ident?, string?) + if not isVorbis(b, o, n, 1) then + return nil, "not a Vorbis identification header" + end + if n < 30 then + return nil, "short identification header" + end + if readu32(b, o + 7) ~= 0 then + return nil, "Vorbis version " .. readu32(b, o + 7) + end + local ch = readu8(b, o + 11) + local rate = readu32(b, o + 12) + local bs = readu8(b, o + 28) + local l0, l1 = bs % 16, bs // 16 + if ch == 0 or rate == 0 then + return nil, "no channels or no sample rate" + end + if l0 < 6 or l0 > 13 or l1 < 6 or l1 > 13 or l0 > l1 then + return nil, "bad blocksizes" + end + if readu8(b, o + 29) % 2 == 0 then + return nil, "identification header framing bit not set" + end + return { + channels = ch, + sampleRate = rate, + bitrateMax = buffer.readi32(b, o + 16), + bitrateNominal = buffer.readi32(b, o + 20), + bitrateMin = buffer.readi32(b, o + 24), + blocksize0 = 2 ^ l0, + blocksize1 = 2 ^ l1, + }, + nil +end + +@native function Setup.comment(b: buffer, o: number, n: number): (string?, { string }?) + if not isVorbis(b, o, n, 3) then + return nil, nil + end + local p, e = o + 7, o + n + if p + 4 > e then + return nil, nil + end + local vlen = readu32(b, p) + p += 4 + if vlen > e - p then + return nil, nil + end + local vendor = buffer.readstring(b, p, vlen) + p += vlen + local list = {} + if p + 4 > e then + return vendor, list + end + local count = readu32(b, p) + p += 4 + for _ = 1, count do + if p + 4 > e then + break + end + local len = readu32(b, p) + p += 4 + if len > e - p then + break + end + table.insert(list, buffer.readstring(b, p, len)) + p += len + end + return vendor, list +end + +@native function Setup.setup(b: buffer, o: number, n: number, id: Ident): (Setup?, string?) + if not isVorbis(b, o, n, 5) then + return nil, "not a Vorbis setup header" + end + local br = Codebook.reader(b, o + 7, n - 7) + local channels = id.channels + local books: { Codebook.Book } = {} + local nbooks = bits(br, 8) + 1 + for i = 1, nbooks do + local book, err = Codebook.read(br) + if not book then + return nil, "codebook " .. (i - 1) .. ": " .. tostring(err) + end + books[i] = book + end + -- time domain transforms (placeholders) + local ntimes = bits(br, 6) + 1 + for _ = 1, ntimes do + if bits(br, 16) ~= 0 then + return nil, "bad time domain transform" + end + end + local floors: { Floor1 } = {} + local maxValues = 0 + local nfloors = bits(br, 6) + 1 + for i = 1, nfloors do + local ftype = bits(br, 16) + if ftype == 0 then + return nil, "floor 0" + elseif ftype ~= 1 then + return nil, "bad floor type " .. ftype + end + local parts = bits(br, 5) + local pclass = table.create(parts, 0) + local maxClass = -1 + for j = 1, parts do + pclass[j] = bits(br, 4) + if pclass[j] > maxClass then + maxClass = pclass[j] + end + end + local cdims, csubs, cmaster, subBooks = {}, {}, {}, {} + for j = 1, maxClass + 1 do + cdims[j] = bits(br, 3) + 1 + csubs[j] = bits(br, 2) + cmaster[j] = -1 + if csubs[j] > 0 then + cmaster[j] = bits(br, 8) + if cmaster[j] >= nbooks then + return nil, "bad floor master book" + end + end + local sb = {} + for k = 1, 2 ^ csubs[j] do + sb[k] = bits(br, 8) - 1 + if sb[k] >= nbooks then + return nil, "bad floor subclass book" + end + end + subBooks[j] = sb + end + local mult = bits(br, 2) + 1 + local rangebits = bits(br, 4) + local xlist = { 0, 2 ^ rangebits } + for j = 1, parts do + local c = pclass[j] + for _ = 1, cdims[c + 1] do + table.insert(xlist, bits(br, rangebits)) + end + end + local values = #xlist + if values > 65 * 8 then + return nil, "too many floor points" + end + if br.eop then + return nil, "setup header ends in a floor" + end + local order = table.create(values, 0) + for j = 1, values do + order[j] = j - 1 + end + table.sort(order, @native function(a: number, c: number): boolean + return xlist[a + 1] < xlist[c + 1] + end) + for j = 1, values - 1 do + if xlist[order[j] + 1] == xlist[order[j + 1] + 1] then + return nil, "duplicate floor x" + end + end + local low, high = table.create(values, 0), table.create(values, 0) + for j = 2, values - 1 do + local lo, hi = -1, 65536 + local x = xlist[j + 1] + for k = 0, j - 1 do + local xv = xlist[k + 1] + if xv > lo and xv < x then + low[j + 1], lo = k, xv + end + if xv < hi and xv > x then + high[j + 1], hi = k, xv + end + end + end + floors[i] = { + partitions = parts, + partitionClass = pclass, + classDims = cdims, + classSubs = csubs, + classMaster = cmaster, + subBooks = subBooks, + multiplier = mult, + xlist = xlist, + values = values, + sorted = order, + low = low, + high = high, + } + if values > maxValues then + maxValues = values + end + end + local residues: { Residue } = {} + local nres = bits(br, 6) + 1 + for i = 1, nres do + local rtype = bits(br, 16) + if rtype > 2 then + return nil, "bad residue type " .. rtype + end + local rbegin, rend = bits(br, 24), bits(br, 24) + local psize = bits(br, 24) + 1 + local ncls = bits(br, 6) + 1 + local cbook = bits(br, 8) + if rend < rbegin then + return nil, "residue end before begin" + end + if cbook >= nbooks then + return nil, "bad residue classbook" + end + local cascade = table.create(ncls, 0) + for j = 1, ncls do + local lowBits = bits(br, 3) + local highBits = if bits(br, 1) == 1 then bits(br, 5) else 0 + cascade[j] = highBits * 8 + lowBits + end + local rbooks = {} + for j = 1, ncls do + local row = table.create(8, -1) + local c = cascade[j] + for k = 1, 8 do + if c % 2 == 1 then + row[k] = bits(br, 8) + if row[k] >= nbooks then + return nil, "bad residue book" + end + end + c = c // 2 + end + rbooks[j] = row + end + if br.eop then + return nil, "setup header ends in a residue" + end + -- class numbers of each classbook entry (stb's classdata) + local cb = books[cbook + 1] + local cw = cb.dims + if cb.entries * cw > 2 ^ 22 then + return nil, "residue classbook too large" + end + local classdata = table.create(cb.entries) + for j = 0, cb.entries - 1 do + local row = table.create(cw, 0) + local tmp = j + for k = cw, 1, -1 do + row[k] = tmp % ncls + tmp = tmp // ncls + end + classdata[j + 1] = row + end + residues[i] = { + type = rtype, + begin = rbegin, + finish = rend, + partSize = psize, + classifications = ncls, + classbook = cbook, + books = rbooks, + classdata = classdata, + } + end + local mappings: { Mapping } = {} + local nmaps = bits(br, 6) + 1 + local chBits = ilog(channels - 1) + for i = 1, nmaps do + if bits(br, 16) ~= 0 then + return nil, "bad mapping type" + end + local submaps = if bits(br, 1) == 1 then bits(br, 4) + 1 else 1 + local steps = 0 + local mag, ang = {}, {} + if bits(br, 1) == 1 then + steps = bits(br, 8) + 1 + if steps > channels then + return nil, "too many coupling steps" + end + for k = 1, steps do + mag[k] = bits(br, chBits) + ang[k] = bits(br, chBits) + if mag[k] >= channels or ang[k] >= channels or mag[k] == ang[k] then + return nil, "bad coupling channels" + end + end + end + if bits(br, 2) ~= 0 then + return nil, "mapping reserved bits set" + end + local mux = table.create(channels, 0) + if submaps > 1 then + for j = 1, channels do + mux[j] = bits(br, 4) + if mux[j] >= submaps then + return nil, "bad channel mux" + end + end + end + local sf, sr = {}, {} + for j = 1, submaps do + bits(br, 8) + sf[j] = bits(br, 8) + sr[j] = bits(br, 8) + if sf[j] >= nfloors or sr[j] >= nres then + return nil, "bad submap floor / residue" + end + end + mappings[i] = { + submaps = submaps, + couplingSteps = steps, + magnitude = mag, + angle = ang, + mux = mux, + submapFloor = sf, + submapResidue = sr, + } + end + local modes: { Mode } = {} + local nmodes = bits(br, 6) + 1 + for i = 1, nmodes do + local bf = bits(br, 1) + local wt, tt = bits(br, 16), bits(br, 16) + local m = bits(br, 8) + if wt ~= 0 or tt ~= 0 or m >= nmaps then + return nil, "bad mode" + end + modes[i] = { blockflag = bf, mapping = m } + end + if br.eop then + return nil, "setup header truncated" + end + if bits(br, 1) ~= 1 then + return nil, "setup header framing bit not set" + end + return { + books = books, + floors = floors, + residues = residues, + mappings = mappings, + modes = modes, + modeBits = ilog(nmodes - 1), + maxFloorValues = maxValues, + }, + nil +end + +return Setup +end +__FILES["codecs/audio/Vorbis/Tables"] = function() + +-- 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). +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, + 1.7623575e-07, 1.8768855e-07, 1.9988561e-07, 2.1287530e-07, 2.2670913e-07, 2.4144197e-07, 2.5713223e-07, 2.7384213e-07, + 2.9163793e-07, 3.1059021e-07, 3.3077411e-07, 3.5226968e-07, 3.7516214e-07, 3.9954229e-07, 4.2550680e-07, 4.5315863e-07, + 4.8260743e-07, 5.1396998e-07, 5.4737065e-07, 5.8294187e-07, 6.2082472e-07, 6.6116941e-07, 7.0413592e-07, 7.4989464e-07, + 7.9862701e-07, 8.5052630e-07, 9.0579828e-07, 9.6466216e-07, 1.0273513e-06, 1.0941144e-06, 1.1652161e-06, 1.2409384e-06, + 1.3215816e-06, 1.4074654e-06, 1.4989305e-06, 1.5963394e-06, 1.7000785e-06, 1.8105592e-06, 1.9282195e-06, 2.0535261e-06, + 2.1869758e-06, 2.3290978e-06, 2.4804557e-06, 2.6416497e-06, 2.8133190e-06, 2.9961443e-06, 3.1908506e-06, 3.3982101e-06, + 3.6190449e-06, 3.8542308e-06, 4.1047004e-06, 4.3714470e-06, 4.6555282e-06, 4.9580707e-06, 5.2802740e-06, 5.6234160e-06, + 5.9888572e-06, 6.3780469e-06, 6.7925283e-06, 7.2339451e-06, 7.7040476e-06, 8.2047000e-06, 8.7378876e-06, 9.3057248e-06, + 9.9104632e-06, 1.0554501e-05, 1.1240392e-05, 1.1970856e-05, 1.2748789e-05, 1.3577278e-05, 1.4459606e-05, 1.5399272e-05, + 1.6400004e-05, 1.7465768e-05, 1.8600792e-05, 1.9809576e-05, 2.1096914e-05, 2.2467911e-05, 2.3928002e-05, 2.5482978e-05, + 2.7139006e-05, 2.8902651e-05, 3.0780908e-05, 3.2781225e-05, 3.4911534e-05, 3.7180282e-05, 3.9596466e-05, 4.2169667e-05, + 4.4910090e-05, 4.7828601e-05, 5.0936773e-05, 5.4246931e-05, 5.7772202e-05, 6.1526565e-05, 6.5524908e-05, 6.9783085e-05, + 7.4317983e-05, 7.9147585e-05, 8.4291040e-05, 8.9768747e-05, 9.5602426e-05, 0.00010181521, 0.00010843174, 0.00011547824, + 0.00012298267, 0.00013097477, 0.00013948625, 0.00014855085, 0.00015820453, 0.00016848555, 0.00017943469, 0.00019109536, + 0.00020351382, 0.00021673929, 0.00023082423, 0.00024582449, 0.00026179955, 0.00027881276, 0.00029693158, 0.00031622787, + 0.00033677814, 0.00035866388, 0.00038197188, 0.00040679456, 0.00043323036, 0.00046138411, 0.00049136745, 0.00052329927, + 0.00055730621, 0.00059352311, 0.00063209358, 0.00067317058, 0.00071691700, 0.00076350630, 0.00081312324, 0.00086596457, + 0.00092223983, 0.00098217216, 0.0010459992, 0.0011139742, 0.0011863665, 0.0012634633, 0.0013455702, 0.0014330129, + 0.0015261382, 0.0016253153, 0.0017309374, 0.0018434235, 0.0019632195, 0.0020908006, 0.0022266726, 0.0023713743, + 0.0025254795, 0.0026895994, 0.0028643847, 0.0030505286, 0.0032487691, 0.0034598925, 0.0036847358, 0.0039241906, + 0.0041792066, 0.0044507950, 0.0047400328, 0.0050480668, 0.0053761186, 0.0057254891, 0.0060975636, 0.0064938176, + 0.0069158225, 0.0073652516, 0.0078438871, 0.0083536271, 0.0088964928, 0.009474637, 0.010090352, 0.010746080, + 0.011444421, 0.012188144, 0.012980198, 0.013823725, 0.014722068, 0.015678791, 0.016697687, 0.017782797, + 0.018938423, 0.020169149, 0.021479854, 0.022875735, 0.024362330, 0.025945531, 0.027631618, 0.029427276, + 0.031339626, 0.033376252, 0.035545228, 0.037855157, 0.040315199, 0.042935108, 0.045725273, 0.048696758, + 0.051861348, 0.055231591, 0.058820850, 0.062643361, 0.066714279, 0.071049749, 0.075666962, 0.080584227, + 0.085821044, 0.091398179, 0.097337747, 0.10366330, 0.11039993, 0.11757434, 0.12521498, 0.13335215, + 0.14201813, 0.15124727, 0.16107617, 0.17154380, 0.18269168, 0.19456402, 0.20720788, 0.22067342, + 0.23501402, 0.25028656, 0.26655159, 0.28387361, 0.30232132, 0.32196786, 0.34289114, 0.36517414, + 0.38890521, 0.41417847, 0.44109412, 0.46975890, 0.50028648, 0.53279791, 0.56742212, 0.60429640, + 0.64356699, 0.68538959, 0.72993007, 0.77736504, 0.82788260, 0.88168307, 0.9389798, 1.0, +}) +end +end + + + + + + Aac + --!optimize 2 +--!nocheck +-- rosetta chunk Aac (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 3 modules (1 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["codecs/audio/Aac"] = function() + +-- codecs/audio/Aac: AAC-LC decoder (ISO/IEC 14496-3 subpart 4, ISO/IEC 13818-7): AudioSpecificConfig, ADTS, raw_data_block. +-- Written from the standard; no third-party code. HE-AAC decodes its AAC-LC core at the core rate. Not supported: Main +-- prediction, LTP, SSR, coupling channels, 960-sample frames, ER / USAC (UNSUPPORTED). +local Err = __include("core/Err") +local Bits = __include("core/Bits") +local Decode = __include("codecs/audio/Aac/Decode") + +local Aac = {} + +Aac.RATES = { 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350 } +local CONFIG_CHANNELS = { 1, 2, 3, 4, 5, 6, 8 } +-- element order (AAC: C, L, R, ...) -> WAV order (L, R, C, LFE, ...) for channel configurations 3 .. 7 +local CONFIG_MAP: { [number]: { number } } = { + [3] = { 3, 1, 2 }, + [4] = { 3, 1, 2, 4 }, + [5] = { 3, 1, 2, 4, 5 }, + [6] = { 3, 1, 2, 5, 6, 4 }, + [7] = { 3, 7, 8, 1, 2, 5, 6, 4 }, +} + +type Config = { + objectType: number, -- 2 = AAC-LC (the core object type when SBR / PS is signalled) + sfIndex: number, + sampleRate: number, + channelConfig: number, + channels: number, + sbr: boolean, + ps: boolean, + extensionRate: number?, + frameLength: number, +} + +local function rateIndex(rate: number): number + -- the nearest standard rate (ISO 14496-3 table 4.82 mapping for explicit frequencies) + local best, bi = math.huge, 4 + for i, r in Aac.RATES do + if math.abs(r - rate) < best then + best, bi = math.abs(r - rate), i - 1 + end + end + return bi +end + +local function objectType(br: Bits.BitReader): number + local t = br:read(5) + if t == 31 then + t = 32 + br:read(6) + end + return t +end + +local function frequency(br: Bits.BitReader): (number, number) + local i = br:read(4) + if i == 15 then + local f = br:read(24) + return rateIndex(f), f + end + return i, Aac.RATES[i + 1] or 0 +end + +-- program_config_element +local function pce(br: Bits.BitReader): number + br:read(4 + 2 + 4) + local front, side, back = br:read(4), br:read(4), br:read(4) + local lfe, assoc, cc = br:read(2), br:read(3), br:read(4) + if br:read(1) == 1 then + br:read(4) + end + if br:read(1) == 1 then + br:read(4) + end + if br:read(1) == 1 then + br:read(3) + end + local channels = 0 + for _ = 1, front + side + back do + channels += if br:read(1) == 1 then 2 else 1 + br:read(4) + end + channels += lfe + br:skip(lfe * 4 + assoc * 4 + cc * 5) + br:align() + br:skip(br:read(8) * 8) + return channels +end + +function Aac.config(asc: buffer): (Config?, Err.Err?) + if type(asc) ~= "buffer" or buffer.len(asc) < 2 then + return nil, Err.new(Err.TRUNCATED, "AudioSpecificConfig is shorter than 2 bytes") + end + local br = Bits.msbReader(asc) + local aot = objectType(br) + local sfi, rate = frequency(br) + local chcfg = br:read(4) + local sbr, ps = false, false + local extRate: number? = nil + if aot == 5 or aot == 29 then + sbr = true + ps = aot == 29 + local _, er = frequency(br) + extRate = er + aot = objectType(br) + if aot == 22 then + br:read(4) + end + end + if aot ~= 2 and aot ~= 1 and aot ~= 4 then + if aot == 0 or br.err then + return nil, Err.new(Err.CORRUPT, "bad AudioSpecificConfig") + end + return nil, Err.new(Err.UNSUPPORTED, "AAC object type " .. aot .. " (only AAC-LC)") + end + if aot ~= 2 then + return nil, Err.new(Err.UNSUPPORTED, if aot == 1 then "AAC Main" else "AAC LTP") + end + -- GASpecificConfig + local frameLengthFlag = br:read(1) + if br:read(1) == 1 then + br:read(14) + end + local ext = br:read(1) + local channels = CONFIG_CHANNELS[chcfg] or 0 + if chcfg == 0 then + channels = pce(br) + elseif chcfg > 7 then + return nil, Err.new(Err.UNSUPPORTED, "channel configuration " .. chcfg) + end + if ext == 1 then + br:read(1) -- extensionFlag3 + end + -- backward-compatible SBR signalling + if not sbr and br:bitsLeft() >= 16 then + if br:read(11) == 0x2b7 then + local et = objectType(br) + if et == 5 and br:read(1) == 1 then + sbr = true + local _, er = frequency(br) + extRate = er + if br:bitsLeft() >= 12 and br:read(11) == 0x548 then + ps = br:read(1) == 1 + end + end + end + end + if br.err and channels == 0 then + return nil, br.err + end + if sfi > 12 or rate <= 0 then + return nil, Err.new(Err.CORRUPT, "bad sampling frequency index " .. sfi) + end + if frameLengthFlag == 1 then + return nil, Err.new(Err.UNSUPPORTED, "960-sample AAC frames") + end + if channels < 1 or channels > 8 then + return nil, Err.new(Err.UNSUPPORTED, channels .. " channels") + end + return { + objectType = aot, + sfIndex = sfi, + sampleRate = rate, + channelConfig = chcfg, + channels = channels, + sbr = sbr, + ps = ps, + extensionRate = extRate, + frameLength = 1024, + }, nil +end + +function Aac.asc(aot: number, sfIndex: number, channelConfig: number): buffer + local b = buffer.create(2) + local v = aot * 2048 + sfIndex * 128 + channelConfig * 8 + buffer.writeu8(b, 0, bit32.rshift(v, 8)) + buffer.writeu8(b, 1, bit32.band(v, 255)) + return b +end + +type Adts = { + headerSize: number, -- 7, or 9 with a CRC + frameSize: number, + objectType: number, + sfIndex: number, + sampleRate: number, + channelConfig: number, + blocks: number, -- raw_data_blocks in the frame (1 .. 4) + protected: boolean, +} + +function Aac.adts(b: buffer, o: number, limit: number): Adts? + if o < 0 or o + 7 > limit or o + 7 > buffer.len(b) then + return nil + end + local b0, b1, b2, b3, b4, b5, b6 = buffer.readu8(b, o), buffer.readu8(b, o + 1), buffer.readu8(b, o + 2), buffer.readu8(b, o + 3), buffer.readu8(b, o + 4), buffer.readu8(b, o + 5), buffer.readu8(b, o + 6) + if b0 ~= 0xFF or bit32.band(b1, 0xF6) ~= 0xF0 then -- sync, layer 0 + return nil + end + local protected = bit32.band(b1, 1) == 0 + local profile = bit32.rshift(b2, 6) + local sfi = bit32.band(bit32.rshift(b2, 2), 15) + local ch = bit32.band(b2, 1) * 4 + bit32.rshift(b3, 6) + local size = bit32.band(b3, 3) * 2048 + b4 * 8 + bit32.rshift(b5, 5) + local blocks = bit32.band(b6, 3) + 1 + local hs = if protected then 9 else 7 + if sfi > 12 or size < hs then + return nil + end + return { + headerSize = hs, + frameSize = size, + objectType = profile + 1, + sfIndex = sfi, + sampleRate = Aac.RATES[sfi + 1], + channelConfig = ch, + blocks = blocks, + protected = protected, + } +end + +type Decoder = { + config: Config, + channels: number, + sampleRate: number, + frameLength: number, + pcm: { number }, + sbr: boolean, + onExtension: ((kind: number, element: number, buf: buffer, bitPos: number, bits: number) -> ())?, + decode: (self: Decoder, buf: buffer, offset: number?, length: number?) -> (number?, Err.Err?), + reset: (self: Decoder) -> (), + state: Decode.State, +} + +local function decode(self: Decoder, buf: buffer, offset: number?, length: number?): (number?, Err.Err?) + local o = offset or 0 + local n = length or (buffer.len(buf) - o) + if type(buf) ~= "buffer" or o < 0 or n < 0 or o + n > buffer.len(buf) then + return nil, Err.new(Err.ARG, "packet range out of the buffer") + end + local st = self.state + st.onExtension = self.onExtension + local chans, msg = Decode.frame(st, buf, o, n) + if not chans then + return nil, Err.new(Err.CORRUPT, msg or "bad frame", o) + end + if st.sbr then + self.sbr = true + end + if chans == 0 then + for i = 1, 1024 * self.channels do + st.pcm[i] = 0 + end + return 1024, nil + end + if chans ~= self.channels then + return nil, Err.new(Err.CORRUPT, string.format("frame has %d channels, the configuration %d", chans, self.channels), o) + end + return 1024, nil +end + +local function reset(self: Decoder) + for _, c in self.state.ch do + for i = 1, 1024 do + c.overlap[i] = 0 + end + c.prevShape = 0 + end +end + +function Aac.decoder(asc: any): (Decoder?, Err.Err?) + local cfg: Config + if type(asc) == "buffer" then + local c, err = Aac.config(asc) + if not c then + return nil, err + end + cfg = c + elseif type(asc) == "table" and type(asc.sfIndex) == "number" and type(asc.channels) == "number" then + local sfi = asc.sfIndex + if sfi < 0 or sfi > 12 or asc.channels < 1 or asc.channels > 8 then + return nil, Err.new(Err.ARG, "bad sampling index / channels") + end + if (asc.objectType or 2) ~= 2 then + return nil, Err.new(Err.UNSUPPORTED, "AAC object type " .. asc.objectType .. " (only AAC-LC)") + end + cfg = { + objectType = 2, + sfIndex = sfi, + sampleRate = Aac.RATES[sfi + 1], + channelConfig = asc.channelConfig or asc.channels, + channels = asc.channels, + sbr = false, + ps = false, + frameLength = 1024, + } :: Config + else + return nil, Err.new(Err.ARG, "decoder: expected an AudioSpecificConfig buffer") + end + local st = Decode.state(cfg.sfIndex) + st.channels = cfg.channels + if cfg.channelConfig >= 3 then + st.map = CONFIG_MAP[cfg.channelConfig] + end + return { + config = cfg, + channels = cfg.channels, + sampleRate = cfg.sampleRate, + frameLength = 1024, + pcm = st.pcm, + sbr = cfg.sbr, + onExtension = nil, + decode = decode, + reset = reset, + state = st, + }, nil +end + +return Aac +end +__FILES["codecs/audio/Aac/Decode"] = @native function() + + + +-- codecs/audio/Aac/Decode: the AAC-LC raw_data_block decoder (ISO/IEC 14496-3 subpart 4). +-- Written from the standard; no third-party code. PNS uses FFmpeg's LCG so the noise matches it. +local Mdct = __include("codecs/audio/Mdct") +local Tables = __include("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 + +local Decode = {} + +local ONLY_LONG, LONG_START, EIGHT_SHORT, LONG_STOP = 0, 1, 2, 3 +local ZERO_HCB, ESC_HCB, NOISE_HCB, INTENSITY_HCB2, INTENSITY_HCB = 0, 11, 13, 14, 15 + +-- one packet at a time: module-level cursor over a zero-padded copy (a frame decode never yields) +local B: buffer = buffer.create(16) +local BP = 0 +local BL = 0 +local OVER = false + +@native local function getBits(n: number): number + local p = BP + BP = p + n + if p > BL then + OVER = true + return 0 + end + return rshift(lshift(byteswap(readu32(B, rshift(p, 3))), band(p, 7)), 32 - n) +end +@native local function peekBits(n: number): number + local p = BP + if p > BL then + return 0 + end + return rshift(lshift(byteswap(readu32(B, rshift(p, 3))), band(p, 7)), 32 - n) +end +@native local function getLong(n: number): number + if n > 24 then + local hi = getBits(n - 16) + return hi * 65536 + getBits(16) + end + return getBits(n) +end + +local PEEK = 10 +type Book = { tab: { number }, map: { [number]: number }, maxLen: number } + +@native local function book(codes: { number }, bits: { number }): Book + local tab = table.create(2 ^ PEEK, 0) + local map = {} + local maxLen = 0 + for s = 1, #codes do + local c, l = codes[s], bits[s] + maxLen = math.max(maxLen, l) + if l <= PEEK then + local shift = 2 ^ (PEEK - l) + for k = 0, shift - 1 do + tab[c * shift + k + 1] = (s - 1) * 32 + l + end + else + map[l * 2 ^ 20 + c] = s - 1 + end + end + return { tab = tab, map = map, maxLen = maxLen } +end + +local SF_BOOK = book(Tables.SF_CODES, Tables.SF_BITS) +local SPEC_BOOK: { Book } = {} +for i = 1, 11 do + SPEC_BOOK[i] = book(Tables.SPEC_CODES[i], Tables.SPEC_BITS[i]) +end + +@native local function huff(bk: Book): number + local e = bk.tab[peekBits(PEEK) + 1] + if e > 0 then + BP += band(e, 31) + return rshift(e, 5) + end + local code = getBits(PEEK) + local map = bk.map + for l = PEEK + 1, bk.maxLen do + code = code * 2 + getBits(1) + local s = map[l * 1048576 + code] + if s then + return s + end + end + return -1 +end + +local DIM = { 4, 4, 4, 4, 2, 2, 2, 2, 2, 2, 2 } +local UNSIGNED = { false, false, true, true, false, false, true, true, true, true, true } +local MOD = { 3, 3, 3, 3, 9, 9, 8, 8, 13, 13, 17 } +local OFF = { 1, 1, 0, 0, 4, 4, 0, 0, 0, 0, 0 } + +-- |q|^(4/3) +local POW43 = table.create(8192, 0) +for i = 0, 8191 do + POW43[i + 1] = i ^ (4 / 3) +end + +local SINE_LONG = Mdct.window("sine", 2048) :: { number } +local KBD_LONG = Mdct.window("kbd", 2048, 4) :: { number } +local SINE_SHORT = Mdct.window("sine", 256) :: { number } +local KBD_SHORT = Mdct.window("kbd", 256, 6) :: { number } +local PLAN_LONG = Mdct.new(2048) :: Mdct.Plan +local PLAN_SHORT = Mdct.new(256) :: Mdct.Plan + +type Channel = { + spec: { number }, + overlap: { number }, + prevShape: number, + windowSequence: number, + windowShape: number, + maxSfb: number, + numGroups: number, + groupLen: { number }, + bandType: { number }, + sf: { number }, + tnsFilters: { { { number } } }, +} + +type State = { + sfIndex: number, + channels: number, + frameLength: number, + ch: { Channel }, + pcm: { number }, + random: number, + time: { number }, + frame: { number }, + short: { number }, + onExtension: ((kind: number, element: number, buf: buffer, bitPos: number, bits: number) -> ())?, + extensions: number, + sbr: boolean, + map: { number }?, +} + +@native local function newChannel(): Channel + return { + spec = table.create(1024, 0), + overlap = table.create(1024, 0), + prevShape = 0, + windowSequence = 0, + windowShape = 0, + maxSfb = 0, + numGroups = 1, + groupLen = { 1, 0, 0, 0, 0, 0, 0, 0 }, + bandType = table.create(8 * 64, 0), + sf = table.create(8 * 64, 0), + tnsFilters = {}, + } +end +Decode.newChannel = newChannel + +@native local function icsInfo(st: State, c: Channel): string? + if getBits(1) ~= 0 then + return "reserved ics bit set" + end + c.windowSequence = getBits(2) + c.windowShape = getBits(1) + if c.windowSequence == EIGHT_SHORT then + c.maxSfb = getBits(4) + local grouping = getBits(7) + local ng = 1 + local gl = c.groupLen + gl[1] = 1 + for w = 1, 7 do + if band(grouping, 2 ^ (6 - (w - 1))) ~= 0 then + gl[ng] += 1 + else + ng += 1 + gl[ng] = 1 + end + end + c.numGroups = ng + if c.maxSfb > Tables.NUM_SWB_SHORT[st.sfIndex + 1] then + return "max_sfb over the short band count" + end + else + c.maxSfb = getBits(6) + c.numGroups = 1 + c.groupLen[1] = 1 + if getBits(1) ~= 0 then + return "prediction (AAC Main / LTP) is not supported" + end + if c.maxSfb > Tables.NUM_SWB_LONG[st.sfIndex + 1] then + return "max_sfb over the long band count" + end + end + return nil +end + +@native local function sectionData(c: Channel): string? + local long = c.windowSequence ~= EIGHT_SHORT + local bits = if long then 5 else 3 + local esc = 2 ^ bits - 1 + local maxSfb = c.maxSfb + local bt = c.bandType + for g = 0, c.numGroups - 1 do + local k = 0 + while k < maxSfb do + local cb = getBits(4) + if cb == 12 then + return "reserved codebook 12" + end + local len = 0 + while true do + local inc = getBits(bits) + len += inc + if inc ~= esc then + break + end + if OVER then + return "section data runs past the end" + end + end + if k + len > maxSfb then + return "section runs past max_sfb" + end + for s = k, k + len - 1 do + bt[g * maxSfb + s + 1] = cb + end + k += len + if OVER then + return "section data runs past the end" + end + end + end + return nil +end + +@native local function scaleFactors(c: Channel, globalGain: number): string? + local sfv = globalGain + local noise = globalGain - 90 + local is = 0 + local firstNoise = true + local maxSfb = c.maxSfb + local bt, sf = c.bandType, c.sf + for g = 0, c.numGroups - 1 do + for s = 0, maxSfb - 1 do + local i = g * maxSfb + s + 1 + local cb = bt[i] + if cb == ZERO_HCB then + sf[i] = 0 + elseif cb == INTENSITY_HCB or cb == INTENSITY_HCB2 then + local d = huff(SF_BOOK) + if d < 0 then + return "bad scalefactor code" + end + is += d - 60 + sf[i] = math.clamp(is, -155, 100) + elseif cb == NOISE_HCB then + if firstNoise then + noise += getBits(9) - 256 + firstNoise = false + else + local d = huff(SF_BOOK) + if d < 0 then + return "bad scalefactor code" + end + noise += d - 60 + end + sf[i] = math.clamp(noise, -100, 155) + else + local d = huff(SF_BOOK) + if d < 0 then + return "bad scalefactor code" + end + sfv += d - 60 + if sfv < 0 or sfv > 255 then + return "scalefactor out of range" + end + sf[i] = sfv + end + end + end + return nil +end + +@native local function tnsData(st: State, c: Channel): string? + local short = c.windowSequence == EIGHT_SHORT + local nw = if short then 8 else 1 + local filters = {} + for w = 1, nw do + local list = {} + local nFilt = getBits(if short then 1 else 2) + if nFilt > 0 then + local coefRes = getBits(1) + for _ = 1, nFilt do + local length = getBits(if short then 4 else 6) + local order = getBits(if short then 3 else 5) + local f = { length, order, 0 } + if order > (if short then 7 else 12) then + return "TNS order too high" + end + if order > 0 then + f[3] = getBits(1) + local compress = getBits(1) + local resBits = coefRes + 3 + local nb = resBits - compress + local iq = ((2 ^ (resBits - 1)) - 0.5) / (math.pi / 2) + local iqm = ((2 ^ (resBits - 1)) + 0.5) / (math.pi / 2) + local tmp = table.create(order, 0) + for k = 1, order do + local v = getBits(nb) + if v >= 2 ^ (nb - 1) then + v -= 2 ^ nb + end + tmp[k] = math.sin(v / (if v >= 0 then iq else iqm)) + end + -- parcor -> LPC + local a = table.create(order + 1, 0) + local b = table.create(order + 1, 0) + a[1] = 1 + for m = 1, order do + for i = 1, m - 1 do + b[i + 1] = a[i + 1] + tmp[m] * a[m - i + 1] + end + for i = 1, m - 1 do + a[i + 1] = b[i + 1] + end + a[m + 1] = tmp[m] + end + for k = 1, order do + f[3 + k] = a[k + 1] + end + end + table.insert(list, f) + end + end + filters[w] = list + end + c.tnsFilters = filters + local _ = st + return nil +end + +@native local function applyTns(st: State, c: Channel) + local short = c.windowSequence == EIGHT_SHORT + local swb = if short then Tables.SWB_SHORT[st.sfIndex + 1] else Tables.SWB_LONG[st.sfIndex + 1] + local numSwb = if short then Tables.NUM_SWB_SHORT[st.sfIndex + 1] else Tables.NUM_SWB_LONG[st.sfIndex + 1] + local maxBands = if short then Tables.TNS_MAX_BANDS_SHORT[st.sfIndex + 1] else Tables.TNS_MAX_BANDS_LONG[st.sfIndex + 1] + local mmm = math.min(maxBands, c.maxSfb) + if mmm == 0 then + return + end + local spec = c.spec + for w, list in c.tnsFilters do + local bottom = numSwb + for _, f in list do + local top = bottom + bottom = math.max(0, top - f[1]) + local order = f[2] + if order > 0 then + local start = swb[math.min(bottom, mmm) + 1] + local stop = swb[math.min(top, mmm) + 1] + local size = stop - start + if size > 0 then + local inc = 1 + local p = (w - 1) * 128 + start + 1 + if f[3] == 1 then + inc = -1 + p = (w - 1) * 128 + stop + end + for m = 0, size - 1 do + local y = spec[p] + local lim = if m < order then m else order + for i = 1, lim do + y -= spec[p - i * inc] * f[3 + i] + end + spec[p] = y + p += inc + end + end + end + end + end +end + +@native local function spectralData(st: State, c: Channel, pulses: { number }?): string? + local short = c.windowSequence == EIGHT_SHORT + local swb = if short then Tables.SWB_SHORT[st.sfIndex + 1] else Tables.SWB_LONG[st.sfIndex + 1] + local spec = c.spec + for i = 1, 1024 do + spec[i] = 0 + end + local maxSfb = c.maxSfb + local bt, sf = c.bandType, c.sf + local win = 0 + for g = 0, c.numGroups - 1 do + local glen = c.groupLen[g + 1] + for s = 0, maxSfb - 1 do + local idx = g * maxSfb + s + 1 + local cb = bt[idx] + local lo, hi = swb[s + 1], swb[s + 2] + local width = hi - lo + if cb == ZERO_HCB or cb == INTENSITY_HCB or cb == INTENSITY_HCB2 then + -- zeros (intensity bands are filled from the other channel later) + continue + elseif cb == NOISE_HCB then + local scale = 2 ^ (0.25 * sf[idx]) + for w = 0, glen - 1 do + local base = (win + w) * 128 + lo + local energy = 0 + local r = st.random + for k = 1, width do + r = (r * 1664525 + 1013904223) % 4294967296 + local v = if r >= 2147483648 then r - 4294967296 else r + spec[base + k] = v + energy += v * v + end + st.random = r + local m = if energy > 0 then scale / sqrt(energy) else 0 + for k = 1, width do + spec[base + k] *= m + end + end + continue + end + local bk = SPEC_BOOK[cb] + local dim, uns, mod, off = DIM[cb], UNSIGNED[cb], MOD[cb], OFF[cb] + local gain = 2 ^ (0.25 * (sf[idx] - 100)) + for w = 0, glen - 1 do + local base = (win + w) * 128 + lo + local k = 0 + while k < width do + local sym = huff(bk) + if sym < 0 then + return "bad spectral code" + end + -- unpack the symbol into dim values (first value most significant) + local vals1: number, vals2: number, vals3: number, vals4: number + if dim == 4 then + vals4 = sym % mod - off + sym = (sym - (sym % mod)) / mod + vals3 = sym % mod - off + sym = (sym - (sym % mod)) / mod + vals2 = sym % mod - off + sym = (sym - (sym % mod)) / mod + vals1 = sym % mod - off + else + vals2 = sym % mod - off + vals1 = (sym - (sym % mod)) / mod - off + end + if uns then + if vals1 ~= 0 and getBits(1) == 1 then + vals1 = -vals1 + end + if vals2 ~= 0 and getBits(1) == 1 then + vals2 = -vals2 + end + if dim == 4 then + if vals3 ~= 0 and getBits(1) == 1 then + vals3 = -vals3 + end + if vals4 ~= 0 and getBits(1) == 1 then + vals4 = -vals4 + end + end + if cb == ESC_HCB then + for e = 1, 2 do + local v = if e == 1 then vals1 else vals2 + if v == 16 or v == -16 then + local n = 0 + while getBits(1) == 1 do + n += 1 + if n > 8 or OVER then + return "bad escape" + end + end + local esc = 2 ^ (n + 4) + getBits(n + 4) + if v < 0 then + esc = -esc + end + if e == 1 then + vals1 = esc + else + vals2 = esc + end + end + end + end + end + local p = base + k + 1 + spec[p] = vals1 + spec[p + 1] = vals2 + if dim == 4 then + spec[p + 2] = vals3 + spec[p + 3] = vals4 + end + k += dim + end + if OVER then + return "spectral data runs past the end" + end + end + -- dequantise (pulses are added to the quantised values first: long windows only, applied below) + if not pulses then + for w = 0, glen - 1 do + local base = (win + w) * 128 + lo + for k = 1, width do + local q = spec[base + k] + if q ~= 0 then + local aq = if q < 0 then -q else q + local v = (POW43[aq + 1] or aq ^ (4 / 3)) * gain + spec[base + k] = if q < 0 then -v else v + end + end + end + end + end + win += glen + end + if pulses then + for i = 1, #pulses, 2 do + local pos = pulses[i] + 1 + if pos <= 1024 then + local q = spec[pos] + spec[pos] = if q > 0 then q + pulses[i + 1] else q - pulses[i + 1] + end + end + for s = 0, maxSfb - 1 do + local idx = s + 1 + local cb = bt[idx] + if cb ~= ZERO_HCB and cb < NOISE_HCB then + local gain = 2 ^ (0.25 * (sf[idx] - 100)) + for k = swb[s + 1] + 1, swb[s + 2] do + local q = spec[k] + if q ~= 0 then + local aq = if q < 0 then -q else q + local v = (POW43[aq + 1] or aq ^ (4 / 3)) * gain + spec[k] = if q < 0 then -v else v + end + end + end + end + end + return nil +end + +-- individual_channel_stream +@native local function ics(st: State, c: Channel, commonWindow: boolean): string? + local globalGain = getBits(8) + if not commonWindow then + local e = icsInfo(st, c) + if e then + return e + end + end + local e = sectionData(c) + if e then + return e + end + e = scaleFactors(c, globalGain) + if e then + return e + end + local pulses: { number }? = nil + if getBits(1) == 1 then + if c.windowSequence == EIGHT_SHORT then + return "pulse data in a short window" + end + local n = getBits(2) + 1 + local startSfb = getBits(6) + if startSfb >= Tables.NUM_SWB_LONG[st.sfIndex + 1] then + return "bad pulse start band" + end + local pos = Tables.SWB_LONG[st.sfIndex + 1][startSfb + 1] + local list = {} + for _ = 1, n do + pos += getBits(5) + table.insert(list, pos) + table.insert(list, getBits(4)) + end + pulses = list + end + c.tnsFilters = {} + if getBits(1) == 1 then + e = tnsData(st, c) + if e then + return e + end + end + if getBits(1) == 1 then + return "gain control (AAC SSR) is not supported" + end + if OVER then + return "channel stream runs past the end" + end + return spectralData(st, c, pulses) +end + +@native local function msStereo(st: State, l: Channel, r: Channel, mask: { number }) + local short = l.windowSequence == EIGHT_SHORT + local swb = if short then Tables.SWB_SHORT[st.sfIndex + 1] else Tables.SWB_LONG[st.sfIndex + 1] + local maxSfb = l.maxSfb + local a, b = l.spec, r.spec + local win = 0 + for g = 0, l.numGroups - 1 do + local glen = l.groupLen[g + 1] + for s = 0, maxSfb - 1 do + local idx = g * maxSfb + s + 1 + if mask[idx] == 1 and l.bandType[idx] < NOISE_HCB and r.bandType[idx] < NOISE_HCB then + for w = 0, glen - 1 do + local base = (win + w) * 128 + for k = base + swb[s + 1] + 1, base + swb[s + 2] do + local m, sd = a[k], b[k] + a[k], b[k] = m + sd, m - sd + end + end + end + end + win += glen + end +end + +@native local function intensity(st: State, l: Channel, r: Channel, mask: { number }, msPresent: number) + local short = r.windowSequence == EIGHT_SHORT + local swb = if short then Tables.SWB_SHORT[st.sfIndex + 1] else Tables.SWB_LONG[st.sfIndex + 1] + local maxSfb = r.maxSfb + local a, b = l.spec, r.spec + local win = 0 + for g = 0, r.numGroups - 1 do + local glen = r.groupLen[g + 1] + for s = 0, maxSfb - 1 do + local idx = g * maxSfb + s + 1 + local cb = r.bandType[idx] + if cb == INTENSITY_HCB or cb == INTENSITY_HCB2 then + local sign = if cb == INTENSITY_HCB then 1 else -1 + if msPresent ~= 0 and mask[idx] == 1 then + sign = -sign + end + local scale = sign * 0.5 ^ (0.25 * r.sf[idx]) + for w = 0, glen - 1 do + local base = (win + w) * 128 + for k = base + swb[s + 1] + 1, base + swb[s + 2] do + b[k] = a[k] * scale + end + end + end + end + win += glen + end +end + +@native local function filterbank(st: State, c: Channel, out: { number }, stride: number, offset: number) + local seq, shape, prev = c.windowSequence, c.windowShape, c.prevShape + local spec, overlap = c.spec, c.overlap + local frame = st.frame + local scale = 1 / 32768 + if seq == EIGHT_SHORT then + for i = 1, 2048 do + frame[i] = 0 + end + local tmp = st.short + local rise0 = if prev == 1 then KBD_SHORT else SINE_SHORT + local wcur = if shape == 1 then KBD_SHORT else SINE_SHORT + for w = 0, 7 do + Mdct.inverse(PLAN_SHORT, spec, w * 128 + 1, 1, tmp, 1, 2 / 256) + local rise = if w == 0 then rise0 else wcur + local base = 448 + w * 128 + for n = 1, 128 do + frame[base + n] += tmp[n] * rise[n] + frame[base + 128 + n] += tmp[128 + n] * wcur[128 + n] + end + end + else + local t = st.time + Mdct.inverse(PLAN_LONG, spec, 1, 1, t, 1, 2 / 2048) + if seq == LONG_STOP then + local rise = if prev == 1 then KBD_SHORT else SINE_SHORT + for n = 1, 448 do + frame[n] = 0 + end + for n = 1, 128 do + frame[448 + n] = t[448 + n] * rise[n] + end + for n = 577, 1024 do + frame[n] = t[n] + end + else + local rise = if prev == 1 then KBD_LONG else SINE_LONG + for n = 1, 1024 do + frame[n] = t[n] * rise[n] + end + end + if seq == LONG_START then + local fall = if shape == 1 then KBD_SHORT else SINE_SHORT + for n = 1025, 1472 do + frame[n] = t[n] + end + for n = 1, 128 do + frame[1472 + n] = t[1472 + n] * fall[128 + n] + end + for n = 1601, 2048 do + frame[n] = 0 + end + else + local fall = if shape == 1 then KBD_LONG else SINE_LONG + for n = 1025, 2048 do + frame[n] = t[n] * fall[n] + end + end + end + local p = offset + for n = 1, 1024 do + out[p] = (frame[n] + overlap[n]) * scale + overlap[n] = frame[1024 + n] + p += stride + end + c.prevShape = shape +end + +@native function Decode.frame(st: State, buf: buffer, off: number, len: number): (number?, string?) + if buffer.len(B) < len + 16 then + B = buffer.create(len + 256) + end + buffer.copy(B, 0, buf, off, len) + buffer.fill(B, len, 0, 16) + BP, BL, OVER = 0, len * 8, false + local chans = st.ch + local nextCh = 1 + local order: { Channel } = {} + local lastElement = -1 + while true do + if BP + 3 > BL then + break -- tolerate a missing END + end + local id = getBits(3) + if id == 7 then + break + end + if id == 0 or id == 3 then -- SCE / LFE + getBits(4) + local c = chans[nextCh] + if not c then + c = newChannel() + chans[nextCh] = c + end + local e = ics(st, c, false) + if e then + return nil, e + end + applyTns(st, c) + table.insert(order, c) + nextCh += 1 + lastElement = id + elseif id == 1 then -- CPE + getBits(4) + local l, r = chans[nextCh], chans[nextCh + 1] + if not l then + l = newChannel() + chans[nextCh] = l + end + if not r then + r = newChannel() + chans[nextCh + 1] = r + end + local common = getBits(1) == 1 + local msPresent = 0 + local mask = table.create(8 * 64, 0) + if common then + local e = icsInfo(st, l) + if e then + return nil, e + end + r.windowSequence, r.windowShape, r.maxSfb, r.numGroups = l.windowSequence, l.windowShape, l.maxSfb, l.numGroups + for i = 1, 8 do + r.groupLen[i] = l.groupLen[i] + end + msPresent = getBits(2) + if msPresent == 1 then + for i = 1, l.numGroups * l.maxSfb do + mask[i] = getBits(1) + end + elseif msPresent == 2 then + for i = 1, l.numGroups * l.maxSfb do + mask[i] = 1 + end + elseif msPresent == 3 then + return nil, "reserved ms_mask_present" + end + end + local e = ics(st, l, common) + if e then + return nil, e + end + e = ics(st, r, common) + if e then + return nil, e + end + if common and msPresent ~= 0 then + msStereo(st, l, r, mask) + end + if common then + intensity(st, l, r, mask, msPresent) + end + applyTns(st, l) + applyTns(st, r) + table.insert(order, l) + table.insert(order, r) + nextCh += 2 + lastElement = id + elseif id == 2 then + return nil, "coupling channel elements are not supported" + elseif id == 4 then -- DSE + getBits(4) + local align = getBits(1) + local count = getBits(8) + if count == 255 then + count += getBits(8) + end + if align == 1 then + BP = (BP + 7) // 8 * 8 + end + BP += count * 8 + elseif id == 5 then -- PCE: skipped here (parsed from the configuration) + return nil, "program config element inside the stream is not supported" + elseif id == 6 then -- FIL + local count = getBits(4) + if count == 15 then + count += getBits(8) - 1 + end + if count > 0 then + local start = BP + local kind = getBits(4) + if kind == 13 or kind == 14 then -- EXT_SBR_DATA / EXT_SBR_DATA_CRC + st.sbr = true + end + st.extensions += 1 + local hook = st.onExtension + if hook then + hook(kind, lastElement, B, start, count * 8) + end + BP = start + count * 8 + end + end + if OVER or BP > BL then + return nil, "frame runs past the end" + end + if nextCh > 9 then + return nil, "more than 8 channels" + end + end + local n = #order + if n == 0 then + return 0, nil + end + local pcm = st.pcm + local map = st.map + for i, c in order do + local o = if map and map[i] then map[i] else i + filterbank(st, c, pcm, n, o) + end + return n, nil +end + +@native function Decode.state(sfIndex: number): State + return { + sfIndex = sfIndex, + channels = 0, + frameLength = 1024, + ch = {}, + pcm = table.create(1024 * 8, 0), + random = 0x1f2e3d4c, + time = table.create(2048, 0), + frame = table.create(2048, 0), + short = table.create(256, 0), + onExtension = nil, + extensions = 0, + sbr = false, + map = nil, + } +end + +local _ = abs +local _2 = floor +return Decode +end +__FILES["codecs/audio/Aac/Tables"] = function() + +-- codecs/audio/Aac/Tables: the AAC-LC tables of ISO/IEC 14496-3 (subpart 4, Annex 4.A): Huffman codebooks, scalefactor +-- band offsets, TNS band limits. Transcribed from FFmpeg libavcodec/aactab.c (tables of the standard, no code; see +-- licenses/NOTICE.md). Generated; do not edit. +local Tables = {} + +Tables.SF_CODES = { + 262120, 262118, 262119, 262117, 524277, 524273, 524269, 524278, 524270, 524271, 524272, 524284, 524285, 524287, 524286, 524279, + 524280, 524283, 524281, 262116, 524282, 262115, 131055, 131056, 65525, 131054, 65522, 65523, 65524, 65521, 32758, 32759, + 16377, 16373, 16375, 16371, 16374, 16370, 8183, 8181, 4089, 4087, 4086, 2041, 4084, 2040, 1017, 1015, + 1013, 504, 503, 250, 248, 246, 121, 58, 56, 26, 11, 4, 0, 10, 12, 27, + 57, 59, 120, 122, 247, 249, 502, 505, 1012, 1014, 1016, 2037, 2036, 2038, 2039, 4085, + 4088, 8180, 8182, 8184, 16376, 16372, 65520, 32756, 65526, 32757, 262114, 524249, 524250, 524251, 524252, 524253, + 524254, 524248, 524242, 524243, 524244, 524245, 524246, 524274, 524255, 524263, 524264, 524265, 524266, 524267, 524262, 524256, + 524257, 524258, 524259, 524260, 524261, 524247, 524268, 524276, 524275, +} + +Tables.SF_BITS = { + 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 18, 19, 18, 17, 17, 16, 17, 16, 16, 16, 16, + 15, 15, 14, 14, 14, 14, 14, 14, 13, 13, 12, 12, 12, 11, 12, 11, 10, 10, 10, 9, 9, 8, 8, 8, 7, 6, 6, 5, 4, 3, + 1, 4, 4, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 10, 11, 11, 11, 11, 12, 12, 13, 13, 13, 14, 14, 16, 15, 16, 15, + 18, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, + 19, +} + +Tables.SPEC_CODES = { + { + 2040, 497, 2045, 1013, 104, 1008, 2039, 492, 2037, 1009, 114, 1012, 116, 17, 118, 491, + 108, 1014, 2044, 481, 2033, 496, 97, 502, 2034, 490, 2043, 498, 105, 493, 119, 23, + 111, 486, 100, 485, 103, 21, 98, 18, 0, 20, 101, 22, 109, 489, 99, 484, + 107, 19, 113, 483, 112, 499, 2046, 487, 2035, 495, 96, 494, 2032, 482, 2042, 1011, + 106, 488, 117, 16, 115, 500, 110, 1015, 2038, 480, 2041, 1010, 102, 501, 2047, 503, + 2036, + }, + { + 499, 111, 509, 235, 35, 234, 503, 232, 506, 242, 45, 112, 32, 6, 43, 110, + 40, 233, 505, 102, 248, 231, 27, 241, 500, 107, 501, 236, 42, 108, 44, 10, + 39, 103, 26, 245, 36, 8, 31, 9, 0, 7, 29, 11, 48, 239, 28, 100, + 30, 12, 41, 243, 47, 240, 508, 113, 498, 244, 33, 230, 247, 104, 504, 238, + 34, 101, 49, 2, 38, 237, 37, 106, 507, 114, 510, 105, 46, 246, 511, 109, + 502, + }, + { + 0, 9, 239, 11, 25, 240, 491, 486, 1010, 10, 53, 495, 52, 55, 489, 493, + 487, 1011, 494, 1005, 8186, 492, 498, 2041, 2040, 1016, 4088, 8, 56, 1014, 54, 117, + 1009, 1003, 1004, 4084, 24, 118, 2036, 57, 116, 1007, 499, 500, 2038, 488, 1002, 8188, + 242, 497, 4091, 1013, 2035, 4092, 238, 1015, 32766, 496, 2037, 32765, 8187, 16378, 65535, 241, + 1008, 16380, 490, 1006, 16379, 4086, 4090, 32764, 2034, 4085, 65534, 1012, 2039, 32763, 4087, 4089, + 32762, + }, + { + 7, 22, 246, 24, 8, 239, 495, 243, 2040, 25, 23, 237, 21, 1, 226, 240, + 112, 1008, 494, 241, 2042, 238, 228, 1010, 2038, 1007, 2045, 5, 20, 242, 9, 4, + 229, 244, 232, 1012, 6, 2, 231, 3, 0, 107, 227, 105, 499, 235, 230, 1014, + 110, 106, 500, 1004, 496, 1017, 245, 236, 2043, 234, 111, 1015, 2041, 1011, 4095, 233, + 109, 1016, 108, 104, 501, 1006, 498, 2036, 2039, 1009, 4094, 1005, 497, 2037, 2046, 1013, + 2044, + }, + { + 8191, 4087, 2036, 2024, 1009, 2030, 2041, 4088, 8189, 4093, 2033, 1000, 488, 240, 492, 1006, + 2034, 4090, 4084, 1007, 498, 232, 112, 236, 496, 1002, 2035, 2027, 491, 234, 26, 8, + 25, 238, 495, 2029, 1008, 242, 115, 11, 0, 10, 113, 243, 2025, 2031, 494, 239, + 24, 9, 27, 235, 489, 2028, 2038, 1003, 499, 237, 114, 233, 497, 1005, 2039, 4086, + 2032, 1001, 493, 241, 490, 1004, 2040, 4089, 8188, 4092, 4085, 2026, 1011, 1010, 2037, 4091, + 8190, + }, + { + 2046, 1021, 497, 491, 500, 490, 496, 1020, 2045, 1014, 485, 234, 108, 113, 104, 240, + 486, 1015, 499, 239, 50, 39, 40, 38, 49, 235, 503, 488, 111, 46, 8, 4, + 6, 41, 107, 494, 495, 114, 45, 2, 0, 3, 47, 115, 506, 487, 110, 43, + 7, 1, 5, 44, 109, 492, 505, 238, 48, 36, 42, 37, 51, 236, 498, 1016, + 484, 237, 106, 112, 105, 116, 241, 1018, 2047, 1017, 502, 493, 504, 489, 501, 1019, + 2044, + }, + { + 0, 5, 55, 116, 242, 491, 1005, 2039, 4, 12, 53, 113, 236, 238, 494, 501, + 54, 52, 114, 234, 241, 489, 499, 1013, 115, 112, 235, 240, 497, 496, 1004, 1018, + 243, 237, 488, 495, 1007, 1009, 1017, 2043, 493, 239, 490, 498, 1011, 1016, 2041, 2044, + 1006, 492, 500, 1012, 1015, 2040, 4093, 4094, 2038, 1008, 1010, 1014, 2042, 2045, 4092, 4095, + }, + { + 14, 5, 16, 48, 111, 241, 506, 1022, 3, 0, 4, 18, 44, 106, 117, 248, + 15, 2, 6, 20, 46, 105, 114, 245, 47, 17, 19, 42, 50, 108, 236, 250, + 113, 43, 45, 49, 109, 112, 242, 505, 239, 104, 51, 107, 110, 238, 249, 1020, + 504, 116, 115, 237, 240, 246, 502, 509, 1021, 243, 244, 247, 503, 507, 508, 1023, + }, + { + 0, 5, 55, 231, 478, 974, 985, 1992, 1997, 4040, 4061, 8164, 8172, 4, 12, 53, + 114, 234, 237, 482, 977, 979, 992, 2008, 4047, 4053, 54, 52, 113, 232, 236, 481, + 975, 989, 987, 2000, 4039, 4052, 4068, 230, 112, 233, 477, 483, 978, 988, 1996, 1994, + 2014, 4056, 4074, 8155, 479, 235, 476, 486, 981, 990, 1995, 2013, 2012, 4045, 4066, 4071, + 8161, 976, 480, 484, 982, 1989, 2001, 2011, 4050, 2016, 4057, 4075, 8163, 8169, 1988, 485, + 983, 1990, 1999, 2010, 4043, 4058, 4067, 4073, 8166, 8179, 8183, 2003, 984, 993, 2004, 2009, + 4051, 4062, 8157, 8153, 8162, 8170, 8177, 8182, 2002, 980, 986, 1991, 2007, 2018, 4046, 4059, + 8152, 8174, 16368, 8180, 16370, 2017, 991, 1993, 2006, 4042, 4048, 4069, 4070, 8171, 8175, 16371, + 16372, 16373, 4064, 1998, 2005, 4038, 4049, 4065, 8160, 8168, 8176, 16369, 16376, 16374, 32764, 4072, + 2015, 4041, 4055, 4060, 8156, 8159, 8173, 8181, 16377, 16379, 32765, 32766, 8167, 4044, 4054, 4063, + 8158, 8154, 8165, 8178, 16378, 16375, 16380, 16381, 32767, + }, + { + 34, 8, 29, 38, 95, 211, 463, 976, 983, 1005, 2032, 2038, 4093, 7, 0, 1, + 9, 32, 84, 96, 213, 220, 468, 973, 990, 2023, 28, 2, 6, 12, 30, 40, + 91, 205, 217, 462, 476, 985, 1009, 37, 11, 10, 13, 36, 87, 97, 204, 221, + 460, 478, 979, 999, 93, 33, 31, 35, 39, 89, 100, 216, 223, 466, 482, 989, + 1006, 209, 85, 41, 86, 88, 98, 206, 224, 226, 474, 980, 995, 2027, 457, 94, + 90, 92, 99, 202, 218, 455, 458, 480, 987, 1000, 2028, 483, 210, 203, 208, 215, + 219, 454, 469, 472, 970, 986, 2026, 2033, 481, 212, 207, 214, 222, 225, 464, 470, + 977, 981, 1010, 2030, 2043, 1001, 461, 456, 459, 465, 471, 479, 975, 992, 1007, 2022, + 2040, 4090, 1003, 477, 467, 473, 475, 978, 972, 988, 1002, 2029, 2035, 2041, 4089, 2034, + 974, 484, 971, 984, 982, 994, 997, 2024, 2036, 2037, 2039, 4091, 2042, 1004, 991, 993, + 996, 998, 1008, 2025, 2031, 4088, 4094, 4092, 4095, + }, + { + 0, 6, 25, 61, 156, 198, 423, 912, 962, 991, 2022, 2035, 4091, 2028, 4090, 4094, + 910, 5, 1, 8, 20, 55, 66, 146, 175, 401, 421, 437, 926, 960, 930, 973, + 2006, 174, 23, 7, 9, 24, 57, 64, 142, 163, 184, 409, 428, 449, 945, 918, + 958, 970, 157, 60, 21, 22, 26, 59, 68, 145, 165, 190, 406, 430, 441, 929, + 913, 933, 981, 148, 154, 54, 56, 58, 65, 140, 155, 176, 195, 414, 427, 444, + 927, 911, 937, 975, 147, 191, 62, 63, 67, 69, 158, 167, 185, 404, 418, 442, + 451, 934, 935, 955, 980, 159, 416, 143, 141, 144, 152, 166, 182, 196, 415, 431, + 447, 921, 959, 948, 969, 999, 168, 438, 171, 164, 170, 178, 194, 197, 408, 420, + 440, 908, 932, 964, 966, 989, 1000, 173, 943, 402, 189, 188, 398, 407, 410, 419, + 433, 909, 920, 951, 979, 977, 987, 2013, 180, 990, 425, 411, 412, 417, 426, 429, + 435, 907, 946, 952, 974, 993, 992, 2002, 2021, 183, 2019, 443, 424, 422, 432, 434, + 439, 923, 922, 954, 949, 982, 2007, 996, 2008, 2026, 186, 2024, 928, 445, 436, 906, + 452, 914, 938, 944, 956, 983, 2004, 2012, 2011, 2005, 2032, 193, 2043, 968, 931, 917, + 925, 940, 942, 965, 984, 994, 998, 2020, 2023, 2016, 2025, 2039, 400, 2034, 915, 446, + 448, 916, 919, 941, 963, 961, 978, 2010, 2009, 2015, 2027, 2036, 2042, 405, 2040, 957, + 924, 939, 936, 947, 953, 976, 995, 997, 2018, 2014, 2029, 2033, 2041, 2044, 403, 4093, + 988, 950, 967, 972, 971, 985, 986, 2003, 2017, 2030, 2031, 2037, 2038, 4092, 4095, 413, + 450, 181, 161, 150, 151, 149, 153, 160, 162, 172, 169, 177, 179, 187, 192, 399, + 4, + }, +} + +Tables.SPEC_BITS = { + { + 11, 9, 11, 10, 7, 10, 11, 9, 11, 10, 7, 10, 7, 5, 7, 9, 7, 10, 11, 9, 11, 9, 7, 9, 11, 9, 11, 9, 7, 9, + 7, 5, 7, 9, 7, 9, 7, 5, 7, 5, 1, 5, 7, 5, 7, 9, 7, 9, 7, 5, 7, 9, 7, 9, 11, 9, 11, 9, 7, 9, + 11, 9, 11, 10, 7, 9, 7, 5, 7, 9, 7, 10, 11, 9, 11, 10, 7, 9, 11, 9, 11, + }, + { + 9, 7, 9, 8, 6, 8, 9, 8, 9, 8, 6, 7, 6, 5, 6, 7, 6, 8, 9, 7, 8, 8, 6, 8, 9, 7, 9, 8, 6, 7, + 6, 5, 6, 7, 6, 8, 6, 5, 6, 5, 3, 5, 6, 5, 6, 8, 6, 7, 6, 5, 6, 8, 6, 8, 9, 7, 9, 8, 6, 8, + 8, 7, 9, 8, 6, 7, 6, 4, 6, 8, 6, 7, 9, 7, 9, 7, 6, 8, 9, 7, 9, + }, + { + 1, 4, 8, 4, 5, 8, 9, 9, 10, 4, 6, 9, 6, 6, 9, 9, 9, 10, 9, 10, 13, 9, 9, 11, 11, 10, 12, 4, 6, 10, + 6, 7, 10, 10, 10, 12, 5, 7, 11, 6, 7, 10, 9, 9, 11, 9, 10, 13, 8, 9, 12, 10, 11, 12, 8, 10, 15, 9, 11, 15, + 13, 14, 16, 8, 10, 14, 9, 10, 14, 12, 12, 15, 11, 12, 16, 10, 11, 15, 12, 12, 15, + }, + { + 4, 5, 8, 5, 4, 8, 9, 8, 11, 5, 5, 8, 5, 4, 8, 8, 7, 10, 9, 8, 11, 8, 8, 10, 11, 10, 11, 4, 5, 8, + 4, 4, 8, 8, 8, 10, 4, 4, 8, 4, 4, 7, 8, 7, 9, 8, 8, 10, 7, 7, 9, 10, 9, 10, 8, 8, 11, 8, 7, 10, + 11, 10, 12, 8, 7, 10, 7, 7, 9, 10, 9, 11, 11, 10, 12, 10, 9, 11, 11, 10, 11, + }, + { + 13, 12, 11, 11, 10, 11, 11, 12, 13, 12, 11, 10, 9, 8, 9, 10, 11, 12, 12, 10, 9, 8, 7, 8, 9, 10, 11, 11, 9, 8, + 5, 4, 5, 8, 9, 11, 10, 8, 7, 4, 1, 4, 7, 8, 11, 11, 9, 8, 5, 4, 5, 8, 9, 11, 11, 10, 9, 8, 7, 8, + 9, 10, 11, 12, 11, 10, 9, 8, 9, 10, 11, 12, 13, 12, 12, 11, 10, 10, 11, 12, 13, + }, + { + 11, 10, 9, 9, 9, 9, 9, 10, 11, 10, 9, 8, 7, 7, 7, 8, 9, 10, 9, 8, 6, 6, 6, 6, 6, 8, 9, 9, 7, 6, + 4, 4, 4, 6, 7, 9, 9, 7, 6, 4, 4, 4, 6, 7, 9, 9, 7, 6, 4, 4, 4, 6, 7, 9, 9, 8, 6, 6, 6, 6, + 6, 8, 9, 10, 9, 8, 7, 7, 7, 7, 8, 10, 11, 10, 9, 9, 9, 9, 9, 10, 11, + }, + { + 1, 3, 6, 7, 8, 9, 10, 11, 3, 4, 6, 7, 8, 8, 9, 9, 6, 6, 7, 8, 8, 9, 9, 10, 7, 7, 8, 8, 9, 9, + 10, 10, 8, 8, 9, 9, 10, 10, 10, 11, 9, 8, 9, 9, 10, 10, 11, 11, 10, 9, 9, 10, 10, 11, 12, 12, 11, 10, 10, 10, + 11, 11, 12, 12, + }, + { + 5, 4, 5, 6, 7, 8, 9, 10, 4, 3, 4, 5, 6, 7, 7, 8, 5, 4, 4, 5, 6, 7, 7, 8, 6, 5, 5, 6, 6, 7, + 8, 8, 7, 6, 6, 6, 7, 7, 8, 9, 8, 7, 6, 7, 7, 8, 8, 10, 9, 7, 7, 8, 8, 8, 9, 9, 10, 8, 8, 8, + 9, 9, 9, 10, + }, + { + 1, 3, 6, 8, 9, 10, 10, 11, 11, 12, 12, 13, 13, 3, 4, 6, 7, 8, 8, 9, 10, 10, 10, 11, 12, 12, 6, 6, 7, 8, + 8, 9, 10, 10, 10, 11, 12, 12, 12, 8, 7, 8, 9, 9, 10, 10, 11, 11, 11, 12, 12, 13, 9, 8, 9, 9, 10, 10, 11, 11, + 11, 12, 12, 12, 13, 10, 9, 9, 10, 11, 11, 11, 12, 11, 12, 12, 13, 13, 11, 9, 10, 11, 11, 11, 12, 12, 12, 12, 13, 13, + 13, 11, 10, 10, 11, 11, 12, 12, 13, 13, 13, 13, 13, 13, 11, 10, 10, 11, 11, 11, 12, 12, 13, 13, 14, 13, 14, 11, 10, 11, + 11, 12, 12, 12, 12, 13, 13, 14, 14, 14, 12, 11, 11, 12, 12, 12, 13, 13, 13, 14, 14, 14, 15, 12, 11, 12, 12, 12, 13, 13, + 13, 13, 14, 14, 15, 15, 13, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15, + }, + { + 6, 5, 6, 6, 7, 8, 9, 10, 10, 10, 11, 11, 12, 5, 4, 4, 5, 6, 7, 7, 8, 8, 9, 10, 10, 11, 6, 4, 5, 5, + 6, 6, 7, 8, 8, 9, 9, 10, 10, 6, 5, 5, 5, 6, 7, 7, 8, 8, 9, 9, 10, 10, 7, 6, 6, 6, 6, 7, 7, 8, + 8, 9, 9, 10, 10, 8, 7, 6, 7, 7, 7, 8, 8, 8, 9, 10, 10, 11, 9, 7, 7, 7, 7, 8, 8, 9, 9, 9, 10, 10, + 11, 9, 8, 8, 8, 8, 8, 9, 9, 9, 10, 10, 11, 11, 9, 8, 8, 8, 8, 8, 9, 9, 10, 10, 10, 11, 11, 10, 9, 9, + 9, 9, 9, 9, 10, 10, 10, 11, 11, 12, 10, 9, 9, 9, 9, 10, 10, 10, 10, 11, 11, 11, 12, 11, 10, 9, 10, 10, 10, 10, + 10, 11, 11, 11, 11, 12, 11, 10, 10, 10, 10, 10, 10, 11, 11, 12, 12, 12, 12, + }, + { + 4, 5, 6, 7, 8, 8, 9, 10, 10, 10, 11, 11, 12, 11, 12, 12, 10, 5, 4, 5, 6, 7, 7, 8, 8, 9, 9, 9, 10, 10, + 10, 10, 11, 8, 6, 5, 5, 6, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 8, 7, 6, 6, 6, 7, 7, 8, 8, 8, + 9, 9, 9, 10, 10, 10, 10, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 8, 8, 7, 7, 7, 7, + 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 8, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 10, 8, 9, + 8, 8, 8, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 10, 10, 8, 10, 9, 8, 8, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, + 10, 11, 8, 10, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 11, 11, 8, 11, 9, 9, 9, 9, 9, 9, 10, 10, 10, + 10, 10, 11, 10, 11, 11, 8, 11, 10, 9, 9, 10, 9, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 8, 11, 10, 10, 10, 10, 10, + 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 9, 11, 10, 9, 9, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 9, 11, 10, + 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 9, 12, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 12, + 12, 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 5, + }, +} + +Tables.SWB_LONG = { + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64, 72, 80, 88, 96, + 108, 120, 132, 144, 156, 172, 188, 212, 240, 276, 320, 384, 448, 512, 576, 640, 704, 768, 832, 896, + 960, 1024, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64, 72, 80, 88, 96, + 108, 120, 132, 144, 156, 172, 188, 212, 240, 276, 320, 384, 448, 512, 576, 640, 704, 768, 832, 896, + 960, 1024, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64, 72, 80, 88, 100, + 112, 124, 140, 156, 172, 192, 216, 240, 268, 304, 344, 384, 424, 464, 504, 544, 584, 624, 664, 704, + 744, 784, 824, 864, 904, 944, 984, 1024, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80, 88, 96, 108, 120, + 132, 144, 160, 176, 196, 216, 240, 264, 292, 320, 352, 384, 416, 448, 480, 512, 544, 576, 608, 640, + 672, 704, 736, 768, 800, 832, 864, 896, 928, 1024, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80, 88, 96, 108, 120, + 132, 144, 160, 176, 196, 216, 240, 264, 292, 320, 352, 384, 416, 448, 480, 512, 544, 576, 608, 640, + 672, 704, 736, 768, 800, 832, 864, 896, 928, 1024, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80, 88, 96, 108, 120, + 132, 144, 160, 176, 196, 216, 240, 264, 292, 320, 352, 384, 416, 448, 480, 512, 544, 576, 608, 640, + 672, 704, 736, 768, 800, 832, 864, 896, 928, 960, 992, 1024, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 52, 60, 68, 76, 84, 92, 100, 108, + 116, 124, 136, 148, 160, 172, 188, 204, 220, 240, 260, 284, 308, 336, 364, 396, 432, 468, 508, 552, + 600, 652, 704, 768, 832, 896, 960, 1024, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 52, 60, 68, 76, 84, 92, 100, 108, + 116, 124, 136, 148, 160, 172, 188, 204, 220, 240, 260, 284, 308, 336, 364, 396, 432, 468, 508, 552, + 600, 652, 704, 768, 832, 896, 960, 1024, + }, + { + 0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 100, 112, 124, 136, 148, 160, 172, 184, + 196, 212, 228, 244, 260, 280, 300, 320, 344, 368, 396, 424, 456, 492, 532, 572, 616, 664, 716, 772, + 832, 896, 960, 1024, + }, + { + 0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 100, 112, 124, 136, 148, 160, 172, 184, + 196, 212, 228, 244, 260, 280, 300, 320, 344, 368, 396, 424, 456, 492, 532, 572, 616, 664, 716, 772, + 832, 896, 960, 1024, + }, + { + 0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 100, 112, 124, 136, 148, 160, 172, 184, + 196, 212, 228, 244, 260, 280, 300, 320, 344, 368, 396, 424, 456, 492, 532, 572, 616, 664, 716, 772, + 832, 896, 960, 1024, + }, + { + 0, 12, 24, 36, 48, 60, 72, 84, 96, 108, 120, 132, 144, 156, 172, 188, 204, 220, 236, 252, + 268, 288, 308, 328, 348, 372, 396, 420, 448, 476, 508, 544, 580, 620, 664, 712, 764, 820, 880, 944, + 1024, + }, + { + 0, 12, 24, 36, 48, 60, 72, 84, 96, 108, 120, 132, 144, 156, 172, 188, 204, 220, 236, 252, + 268, 288, 308, 328, 348, 372, 396, 420, 448, 476, 508, 544, 580, 620, 664, 712, 764, 820, 880, 944, + 1024, + }, +} + +Tables.SWB_SHORT = { + { + 0, 4, 8, 12, 16, 20, 24, 32, 40, 48, 64, 92, 128, + }, + { + 0, 4, 8, 12, 16, 20, 24, 32, 40, 48, 64, 92, 128, + }, + { + 0, 4, 8, 12, 16, 20, 24, 32, 40, 48, 64, 92, 128, + }, + { + 0, 4, 8, 12, 16, 20, 28, 36, 44, 56, 68, 80, 96, 112, 128, + }, + { + 0, 4, 8, 12, 16, 20, 28, 36, 44, 56, 68, 80, 96, 112, 128, + }, + { + 0, 4, 8, 12, 16, 20, 28, 36, 44, 56, 68, 80, 96, 112, 128, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 64, 76, 92, 108, 128, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 64, 76, 92, 108, 128, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 60, 72, 88, 108, 128, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 60, 72, 88, 108, 128, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 60, 72, 88, 108, 128, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 60, 72, 88, 108, 128, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 60, 72, 88, 108, 128, + }, +} + +Tables.NUM_SWB_LONG = { + 41, 41, 47, 49, 49, 51, 47, 47, 43, 43, 43, 40, 40, +} + +Tables.NUM_SWB_SHORT = { + 12, 12, 12, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, +} + +Tables.TNS_MAX_BANDS_LONG = { + 31, 31, 34, 40, 42, 51, 46, 46, 42, 42, 42, 39, 39, +} + +Tables.TNS_MAX_BANDS_SHORT = { + 9, 9, 10, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, +} + +return Tables +end +end + + + + + + Flac + --!optimize 2 +--!nocheck +-- rosetta chunk Flac (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 3 modules (2 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["codecs/audio/Flac"] = function() + +-- codecs/audio/Flac: FLAC frames without the container (frame header, subframes, CRC-8 / CRC-16) and the frame encoder. +-- Absorbed from flac-luau 7083d0d; the encoder is new. +local Flac = { + Frame = __include("codecs/audio/Flac/Frame"), + Encode = __include("codecs/audio/Flac/Encode"), +} + +return Flac +end +__FILES["codecs/audio/Flac/Encode"] = @native function() + + + +-- codecs/audio/Flac/Encode: the FLAC encoder (RFC 9639), written from the RFC. +-- The presets mirror libFLAC's -0 .. -8; QLP precision follows libFLAC's table. +local Bits = __include("core/Bits") +local Md5 = __include("core/Md5") +local VorbisComment = __include("codecs/audio/VorbisComment") +local Frame = __include("codecs/audio/Flac/Frame") + +local Encode = {} + +local floor, abs, log = math.floor, math.abs, math.log +local readf32, writeu8 = buffer.readf32, buffer.writeu8 + +local POW = table.create(64, 0) +for i = 0, 63 do + POW[i + 1] = 2 ^ i +end + +@native local function crc8(b: buffer, o: number, n: number): number + return Frame.crc8(b, o, o + n) +end +@native local function crc16(b: buffer, o: number, n: number): number + return Frame.crc16(b, o, o + n) +end +Encode.crc8, Encode.crc16 = crc8, crc16 + +type W = Bits.RawWriter + +@native local function ensure(w: W, n: number) + local need = w.pos + n + 16 + local cap = buffer.len(w.buf) + if need > cap then + local nb = buffer.create(math.max(cap * 2, need)) + buffer.copy(nb, 0, w.buf, 0, w.pos) + w.buf = nb + end +end + +local put = Bits.msbPut + +@native local function putSigned(w: W, v: number, n: number) + put(w, if v < 0 then v + POW[n + 1] else v, n) +end + +@native local function alignByte(w: W) + if w.cnt > 0 then + put(w, 0, 8 - w.cnt) + end +end + +@native local function putUtf8(w: W, v: number) + if v < 0x80 then + put(w, v, 8) + return + end + local n = if v < 0x800 then 2 elseif v < 0x10000 then 3 elseif v < 0x200000 then 4 elseif v < 0x4000000 then 5 elseif v < 0x80000000 then 6 else 7 + local first = if n == 7 then 0xFE else (0xFF00 // POW[n + 1]) % 256 -- n leading ones + local shift = 6 * (n - 1) + put(w, first + floor(v / POW[shift + 1]), 8) + for k = n - 2, 0, -1 do + put(w, 0x80 + floor(v / POW[6 * k + 1]) % 64, 8) + end +end + +type Config = { + blockSize: number, + maxLpcOrder: number, + maxPartitionOrder: number, + stereo: string, + exhaustiveOrder: boolean, +} +local PRESETS: { Config } = { + { blockSize = 1152, maxLpcOrder = 0, maxPartitionOrder = 3, stereo = "independent", exhaustiveOrder = false }, + { blockSize = 1152, maxLpcOrder = 0, maxPartitionOrder = 3, stereo = "adaptive", exhaustiveOrder = false }, + { blockSize = 1152, maxLpcOrder = 0, maxPartitionOrder = 3, stereo = "exhaustive", exhaustiveOrder = false }, + { blockSize = 4096, maxLpcOrder = 6, maxPartitionOrder = 4, stereo = "independent", exhaustiveOrder = false }, + { blockSize = 4096, maxLpcOrder = 8, maxPartitionOrder = 4, stereo = "adaptive", exhaustiveOrder = false }, + { blockSize = 4096, maxLpcOrder = 8, maxPartitionOrder = 5, stereo = "exhaustive", exhaustiveOrder = false }, + { blockSize = 4096, maxLpcOrder = 8, maxPartitionOrder = 6, stereo = "exhaustive", exhaustiveOrder = false }, + { blockSize = 4096, maxLpcOrder = 12, maxPartitionOrder = 6, stereo = "exhaustive", exhaustiveOrder = false }, + { blockSize = 4096, maxLpcOrder = 12, maxPartitionOrder = 6, stereo = "exhaustive", exhaustiveOrder = true }, +} +Encode.PRESETS = PRESETS + +type Plan = { + kind: number, + bits: number, + order: number, + wasted: number, + bps: number, + res: { number }, + porder: number, + params: { number }, + method: number, -- 0 Rice (4-bit params), 1 Rice2 (5-bit) + qlp: { number }, + shift: number, + precision: number, + x: { number }, +} + +@native local function newPlan(n: number): Plan + return { + kind = 1, + bits = 0, + order = 0, + wasted = 0, + bps = 16, + res = table.create(n, 0), + porder = 0, + params = table.create(64, 0), + method = 0, + qlp = table.create(32, 0), + shift = 0, + precision = 0, + x = table.create(n, 0), + } +end + +type Scratch = { + sums: { number }, + counts: { number }, + ks: { number }, + bestKs: { number }, + tmpRes: { number }, + win: { number }, + winN: number, + wx: { number }, + autoc: { number }, + lpc: { { number } }, + err: { number }, + qlp: { number }, +} + +@native local function rice(sc: Scratch, res: { number }, n: number, order: number, maxP: number): (number, number, number) + local p = maxP + while p > 0 and (n % POW[p + 1] ~= 0 or n // POW[p + 1] <= order) do + p -= 1 + end + local sums, counts = sc.sums, sc.counts + local parts = POW[p + 1] + local ps = n // parts + for j = 0, parts - 1 do + local s = 0 + local a = if j == 0 then order + 1 else j * ps + 1 + local e = (j + 1) * ps + for i = a, e do + local r = res[i] + s += if r >= 0 then 2 * r else -2 * r - 1 + end + sums[j + 1] = s + counts[j + 1] = e - a + 1 + end + local bestBits, bestP, bestMethod = math.huge, 0, 0 + local ks, bestKs = sc.ks, sc.bestKs + local q = p + while true do + local np = POW[q + 1] + local total = 0 + local maxk = 0 + for j = 1, np do + local s, c = sums[j], counts[j] + local k = 0 + local cost = s + c -- k = 0: unary s, plus one stop bit per sample + if c > 0 and s > c then + local k0 = floor(log(s / c) / 0.6931471805599453) + for kk = math.max(0, k0 - 1), math.min(30, k0 + 1) do + local cc = c * (kk + 1) + floor(s / POW[kk + 1]) + if cc < cost then + cost, k = cc, kk + end + end + end + ks[j] = k + if k > maxk then + maxk = k + end + total += cost + end + local method = if maxk > 14 then 1 else 0 + total += np * (if method == 1 then 5 else 4) + 2 + 4 + if total < bestBits then + bestBits, bestP, bestMethod = total, q, method + for j = 1, np do + bestKs[j] = ks[j] + end + end + if q == 0 then + break + end + for j = 1, np // 2 do + sums[j] = sums[2 * j - 1] + sums[2 * j] + counts[j] = counts[2 * j - 1] + counts[2 * j] + end + q -= 1 + end + return bestBits, bestP, bestMethod +end + +@native local function keepRice(sc: Scratch, plan: Plan, porder: number, method: number) + plan.porder, plan.method = porder, method + local params = plan.params + for j = 1, POW[porder + 1] do + params[j] = sc.bestKs[j] + end +end + +@native local function fixedResidual(x: { number }, n: number, order: number, res: { number }) + for i = 1, order do + res[i] = 0 + end + if order == 0 then + for i = 1, n do + res[i] = x[i] + end + elseif order == 1 then + for i = 2, n do + res[i] = x[i] - x[i - 1] + end + elseif order == 2 then + for i = 3, n do + res[i] = x[i] - 2 * x[i - 1] + x[i - 2] + end + elseif order == 3 then + for i = 4, n do + res[i] = x[i] - 3 * x[i - 1] + 3 * x[i - 2] - x[i - 3] + end + else + for i = 5, n do + res[i] = x[i] - 4 * x[i - 1] + 6 * x[i - 2] - 4 * x[i - 3] + x[i - 4] + end + end +end + +-- the fixed order with the smallest residual magnitude (libFLAC's estimate) +@native local function bestFixedOrder(x: { number }, n: number): (number, number) + if n <= 4 then + return 0, 0 + end + local s0, s1, s2, s3, s4 = 0, 0, 0, 0, 0 + local a, b, c, d = x[4], x[4] - x[3], x[4] - 2 * x[3] + x[2], x[4] - 3 * x[3] + 3 * x[2] - x[1] + for i = 5, n do + local e0 = x[i] + local e1 = e0 - a + local e2 = e1 - b + local e3 = e2 - c + local e4 = e3 - d + s0 += abs(e0) + s1 += abs(e1) + s2 += abs(e2) + s3 += abs(e3) + s4 += abs(e4) + a, b, c, d = e0, e1, e2, e3 + end + local best, bs = 0, s0 + if s1 < bs then + best, bs = 1, s1 + end + if s2 < bs then + best, bs = 2, s2 + end + if s3 < bs then + best, bs = 3, s3 + end + if s4 < bs then + best, bs = 4, s4 + end + return best, bs +end +Encode.bestFixedOrder = bestFixedOrder + +-- libFLAC's default QLP coefficient precision for a block size +@native local function qlpPrecision(bps: number, n: number): number + if bps > 16 then + return 15 + end + if n <= 192 then + return 7 + elseif n <= 384 then + return 8 + elseif n <= 576 then + return 9 + elseif n <= 1152 then + return 10 + elseif n <= 2304 then + return 11 + elseif n <= 4608 then + return 12 + end + return 13 +end + +@native local function quantize(lp: { number }, order: number, precision: number, qlp: { number }): number? + local cmax = 0 + for i = 1, order do + local a = abs(lp[i]) + if a > cmax then + cmax = a + end + end + if cmax <= 0 or cmax ~= cmax or cmax == math.huge then + return nil + end + local log2cmax = 0 + while cmax >= 1 do + cmax /= 2 + log2cmax += 1 + end + while cmax < 0.5 do + cmax *= 2 + log2cmax -= 1 + end + -- frexp: cmax = m * 2^log2cmax with m in [0.5, 1) + log2cmax -= 1 + local p = precision - 1 + local qmax = POW[p + 1] - 1 + local qmin = -POW[p + 1] + local shift = p - log2cmax - 1 + if shift > 15 then + shift = 15 + elseif shift < 0 then + return nil + end + local err = 0 + local scale = POW[shift + 1] + for i = 1, order do + err += lp[i] * scale + local q = floor(err + 0.5) + if q > qmax then + q = qmax + elseif q < qmin then + q = qmin + end + err -= q + qlp[i] = q + end + return shift +end + +@native local function lpcResidual(x: { number }, n: number, order: number, qlp: { number }, shift: number, res: { number }) + local d = POW[shift + 1] + for i = 1, order do + res[i] = 0 + end + for i = order + 1, n do + local s = 0 + for j = 1, order do + s += qlp[j] * x[i - j] + end + res[i] = x[i] - floor(s / d) + end +end + +@native local function levinson(sc: Scratch, maxOrder: number): number + local r = sc.autoc + local e = r[1] + if e <= 0 then + return 0 + end + local a = table.create(maxOrder + 1, 0) + local tmp = table.create(maxOrder + 1, 0) + for o = 1, maxOrder do + local acc = r[o + 1] + for j = 1, o - 1 do + acc -= a[j] * r[o - j + 1] + end + local k = acc / e + for j = 1, o - 1 do + tmp[j] = a[j] - k * a[o - j] + end + for j = 1, o - 1 do + a[j] = tmp[j] + end + a[o] = k + e *= (1 - k * k) + local row = sc.lpc[o] + for j = 1, o do + row[j] = a[j] + end + sc.err[o] = e + if e <= 0 then + return o + end + end + return maxOrder +end + +@native local function analyze(sc: Scratch, cfg: Config, src: { number }, n: number, bps: number, plan: Plan) + local x = plan.x + local first = src[1] + local constant = true + for i = 1, n do + local v = src[i] + if v ~= first then + constant = false + end + end + if constant then + plan.kind, plan.bits, plan.wasted, plan.bps = 0, 8 + bps, 0, bps + plan.res[1] = first + return + end + local wasted = 0 + do + local w = 0 + while w < bps - 1 do + local m = POW[w + 2] + local all = true + for i = 1, n do + if src[i] % m ~= 0 then + all = false + break + end + end + if not all then + break + end + w += 1 + end + wasted = w + end + local d = POW[wasted + 1] + for i = 1, n do + x[i] = src[i] / d + end + local b = bps - wasted + local hdr = 8 + wasted + plan.wasted, plan.bps = wasted, b + plan.kind, plan.bits = 1, hdr + n * b + local fo = bestFixedOrder(x, n) + if n > fo then + local tmp = sc.tmpRes + fixedResidual(x, n, fo, tmp) + local rb, po, me = rice(sc, tmp, n, fo, cfg.maxPartitionOrder) + local bits = hdr + fo * b + rb + if bits < plan.bits then + plan.kind, plan.bits, plan.order = 2, bits, fo + sc.tmpRes, plan.res = plan.res, tmp + keepRice(sc, plan, po, me) + end + end + local maxOrder = math.min(cfg.maxLpcOrder, n - 1, 32) + if maxOrder > 0 then + local win = sc.win + if sc.winN ~= n then + -- tukey(0.5) + local np = floor(0.25 * n) + for i = 1, n do + win[i] = 1 + end + if np > 0 then + for i = 0, np - 1 do + local v = 0.5 - 0.5 * math.cos(math.pi * i / np) + win[i + 1] = v + win[n - i] = v + end + end + sc.winN = n + end + local wx = sc.wx + for i = 1, n do + wx[i] = x[i] * win[i] + end + local ac = sc.autoc + for lag = 0, maxOrder do + local s = 0 + for i = lag + 1, n do + s += wx[i] * wx[i - lag] + end + ac[lag + 1] = s + end + local top = levinson(sc, maxOrder) + if top > 0 then + local precision = qlpPrecision(b, n) + local orders = {} + if cfg.exhaustiveOrder then + for o = 1, top do + table.insert(orders, o) + end + else + -- estimated bits: (n - o) * 0.5 * log2(err_o / n) + o * precision + local bestO, bestE = 1, math.huge + for o = 1, top do + local e = sc.err[o] + local est = if e > 0 then (n - o) * 0.5 * log(e / n) / 0.6931471805599453 + o * (precision + b) else -math.huge + if est < bestE then + bestO, bestE = o, est + end + end + orders[1] = bestO + end + local qlp = sc.qlp + for _, o in orders do + local prec = precision + local shift = quantize(sc.lpc[o], o, prec, qlp) + if shift then + local tmp = sc.tmpRes + lpcResidual(x, n, o, qlp, shift, tmp) + local rb, po, me = rice(sc, tmp, n, o, cfg.maxPartitionOrder) + local bits = hdr + o * b + 4 + 5 + o * prec + rb + if bits < plan.bits then + plan.kind, plan.bits, plan.order = 3, bits, o + plan.shift, plan.precision = shift, prec + for j = 1, o do + plan.qlp[j] = qlp[j] + end + sc.tmpRes, plan.res = plan.res, tmp + keepRice(sc, plan, po, me) + end + end + end + end + end +end + +@native local function writeResidual(w: W, plan: Plan, n: number) + local method = plan.method + put(w, method, 2) + local porder = plan.porder + put(w, porder, 4) + local parts = POW[porder + 1] + local ps = n // parts + local res = plan.res + local pbits = if method == 1 then 5 else 4 + for j = 0, parts - 1 do + local k = plan.params[j + 1] + put(w, k, pbits) + local a = if j == 0 then plan.order + 1 else j * ps + 1 + local e = (j + 1) * ps + local mk = POW[k + 1] + for i = a, e do + local r = res[i] + local u = if r >= 0 then 2 * r else -2 * r - 1 + local hi = floor(u / mk) + local lo = u - hi * mk + if hi + 1 + k <= 32 then + put(w, mk + lo, hi + 1 + k) + else + local q = hi + while q > 24 do + put(w, 0, 24) + q -= 24 + end + put(w, 1, q + 1) + put(w, lo, k) + end + end + end +end + +@native local function writeSubframe(w: W, plan: Plan, n: number) + local kind = plan.kind + local typ = if kind == 0 then 0 elseif kind == 1 then 1 elseif kind == 2 then 8 + plan.order else 32 + plan.order - 1 + put(w, 0, 1) + put(w, typ, 6) + if kind ~= 0 and plan.wasted > 0 then + put(w, 1, 1) + put(w, 1, plan.wasted) -- k - 1 zeros, then a one + else + put(w, 0, 1) + end + local b = plan.bps + if kind == 0 then + putSigned(w, plan.res[1], b) + return + end + local x = plan.x + if kind == 1 then + for i = 1, n do + putSigned(w, x[i], b) + end + return + end + for i = 1, plan.order do + putSigned(w, x[i], b) + end + if kind == 3 then + put(w, plan.precision - 1, 4) + put(w, plan.shift, 5) + for j = 1, plan.order do + putSigned(w, plan.qlp[j], plan.precision) + end + end + writeResidual(w, plan, n) +end + +local RATE_CODES: { [number]: number } = { + [88200] = 1, + [176400] = 2, + [192000] = 3, + [8000] = 4, + [16000] = 5, + [22050] = 6, + [24000] = 7, + [32000] = 8, + [44100] = 9, + [48000] = 10, + [96000] = 11, +} +local SIZE_CODES: { [number]: number } = { [8] = 1, [12] = 2, [16] = 4, [20] = 5, [24] = 6, [32] = 7 } + +@native local function blockCode(n: number): (number, number) -- code, extra bits (0, 8, 16) + if n == 192 then + return 1, 0 + end + for k = 2, 5 do + if n == 576 * POW[k - 1] then + return k, 0 + end + end + for k = 8, 15 do + if n == 256 * POW[k - 7] then + return k, 0 + end + end + if n <= 256 then + return 6, 8 + end + return 7, 16 +end + +type Source = { + sampleRate: number, + channels: number, + frames: number, + tags: { [string]: string }, + read: (self: any, n: number, out: buffer?) -> (buffer, number), + err: any, +} +type Options = { + level: number, + bits: number, + blockSize: number?, + seekInterval: number, + padding: number, + vendor: string, +} + +@native function Encode.encode(src: Source, opts: Options): (buffer?, string?) + local cfg = PRESETS[opts.level + 1] + local ch, rate, bps = src.channels, src.sampleRate, opts.bits + local bs = opts.blockSize or cfg.blockSize + local w: W = { buf = buffer.create(65536), pos = 0, acc = 0, cnt = 0 } + put(w, 0x664C6143, 32) -- "fLaC" + put(w, 0, 1) + put(w, 0, 7) + put(w, 34, 24) + local siData = w.pos + for _ = 1, 34 do + put(w, 0, 8) + end + local seekPoints = 0 + local seekAt = 0 + local interval = floor(opts.seekInterval * rate) + if interval > 0 and src.frames > 0 then + seekPoints = (src.frames - 1) // interval + 1 + if seekPoints > 65535 // 18 * 18 then + seekPoints = 0 + end + end + local comments = VorbisComment.fields(src.tags) + local vendor = opts.vendor + local vcLen = 4 + #vendor + 4 + for _, c in comments do + vcLen += 4 + #c + end + if seekPoints > 0 then + put(w, 0, 1) + put(w, 3, 7) + put(w, seekPoints * 18, 24) + seekAt = w.pos + ensure(w, seekPoints * 18) + for _ = 1, seekPoints do + put(w, 0xFFFFFFFF, 32) -- sample number: a placeholder until a frame fills it + put(w, 0xFFFFFFFF, 32) + put(w, 0, 32) -- byte offset + put(w, 0, 32) + put(w, 0, 16) -- frame samples + end + end + -- VORBIS_COMMENT (little-endian lengths) + @native local function le32(v: number) + put(w, v % 256, 8) + put(w, (v // 256) % 256, 8) + put(w, (v // 65536) % 256, 8) + put(w, v // 16777216, 8) + end + ensure(w, vcLen + 8) + put(w, if opts.padding > 0 then 0 else 1, 1) -- the last metadata block unless PADDING follows + put(w, 4, 7) + put(w, vcLen, 24) + le32(#vendor) + for i = 1, #vendor do + put(w, string.byte(vendor, i), 8) + end + le32(#comments) + for _, c in comments do + ensure(w, #c + 8) + le32(#c) + for i = 1, #c do + put(w, string.byte(c, i), 8) + end + end + if opts.padding > 0 then + ensure(w, opts.padding + 8) + put(w, 1, 1) + put(w, 1, 7) + put(w, opts.padding, 24) + for _ = 1, opts.padding do + put(w, 0, 8) + end + end + local audioStart = w.pos + local md5 = Md5.new() + local mbytes = (bps + 7) // 8 + local mbuf = buffer.create(bs * ch * mbytes) + local scale = POW[bps] + local maxv, minv = scale - 1, -scale + local X: { { number } } = table.create(ch) :: any + for c = 1, ch do + X[c] = table.create(bs, 0) + end + local side = table.create(bs, 0) + local mid = table.create(bs, 0) + local plans = {} + for i = 1, 4 do + plans[i] = newPlan(bs) + end + for c = 1, ch do + plans[4 + c] = newPlan(bs) + end + local lpcRows = {} + for o = 1, 32 do + lpcRows[o] = table.create(o, 0) + end + local sc: Scratch = { + sums = table.create(64, 0), + counts = table.create(64, 0), + ks = table.create(64, 0), + bestKs = table.create(64, 0), + tmpRes = table.create(bs, 0), + win = table.create(bs, 0), + winN = 0, + wx = table.create(bs, 0), + autoc = table.create(33, 0), + lpc = lpcRows, + err = table.create(32, 0), + qlp = table.create(32, 0), + } + local frameNo = 0 + local total = 0 + local minFrame, maxFrame = math.huge, 0 + local seekNext = 0 + local seekIdx = 0 + local rateCode = RATE_CODES[rate] or 0 + local sizeCode = SIZE_CODES[bps] or 0 + local tmp: buffer? = nil + local pendingBuf: buffer? = nil + local pendingN, pendingOff = 0, 0 + @native local function readBlock(): (buffer?, number) + local out = buffer.create(bs * ch * 4) + local got = 0 + while got < bs do + if pendingN == 0 then + local b, n = src:read(math.max(bs, 4096), tmp) + if n <= 0 then + break + end + tmp = b + pendingBuf, pendingN, pendingOff = b, n, 0 + end + local take = math.min(bs - got, pendingN) + buffer.copy(out, got * ch * 4, pendingBuf :: buffer, pendingOff * ch * 4, take * ch * 4) + got += take + pendingN -= take + pendingOff += take + end + return out, got + end + while true do + local fb, n = readBlock() + if n <= 0 or fb == nil then + break + end + -- to integers (+ the MD5 bytes, signed little endian) + local mo = 0 + for i = 0, n - 1 do + for c = 1, ch do + local v = floor(readf32(fb, (i * ch + c - 1) * 4) * scale + 0.5) + if v ~= v then + v = 0 + elseif v > maxv then + v = maxv + elseif v < minv then + v = minv + end + X[c][i + 1] = v + local u = if v < 0 then v + 4294967296 else v + for k = 0, mbytes - 1 do + writeu8(mbuf, mo, floor(u / POW[8 * k + 1]) % 256) + mo += 1 + end + end + end + md5:update(mbuf, 0, mo) + local assign = ch - 1 + local chosen: { Plan } = {} + if ch == 2 and cfg.stereo ~= "independent" then + local L, R = X[1], X[2] + for i = 1, n do + local l, r = L[i], R[i] + side[i] = l - r + mid[i] = floor((l + r) / 2) + end + local pl, pr, pm, ps = plans[1], plans[2], plans[3], plans[4] + if cfg.stereo == "adaptive" then + local _, el = bestFixedOrder(L, n) + local _, er = bestFixedOrder(R, n) + local _, em = bestFixedOrder(mid, n) + local _, es = bestFixedOrder(side, n) + -- the estimate picks one decorrelated pair; it is kept only if it beats left / right for real + local best = math.min(el + es, er + es, em + es) + analyze(sc, cfg, L, n, bps, pl) + analyze(sc, cfg, R, n, bps, pr) + chosen, assign = { pl, pr }, 1 + if best < el + er then + analyze(sc, cfg, side, n, bps + 1, ps) + if best == em + es then + analyze(sc, cfg, mid, n, bps, pm) + if pm.bits + ps.bits < pl.bits + pr.bits then + chosen, assign = { pm, ps }, 10 + end + elseif best == el + es then + if pl.bits + ps.bits < pl.bits + pr.bits then + chosen, assign = { pl, ps }, 8 + end + elseif ps.bits + pr.bits < pl.bits + pr.bits then + chosen, assign = { ps, pr }, 9 + end + end + else + analyze(sc, cfg, L, n, bps, pl) + analyze(sc, cfg, R, n, bps, pr) + analyze(sc, cfg, mid, n, bps, pm) + analyze(sc, cfg, side, n, bps + 1, ps) + local lr, ls, rs, msb = pl.bits + pr.bits, pl.bits + ps.bits, ps.bits + pr.bits, pm.bits + ps.bits + local best = math.min(lr, ls, rs, msb) + if best == lr then + chosen, assign = { pl, pr }, 1 + elseif best == msb then + chosen, assign = { pm, ps }, 10 + elseif best == ls then + chosen, assign = { pl, ps }, 8 + else + chosen, assign = { ps, pr }, 9 + end + end + else + for c = 1, ch do + analyze(sc, cfg, X[c], n, bps, plans[4 + c]) + chosen[c] = plans[4 + c] + end + end + local need = n * ch * 4 + 64 + for _, p in chosen do + need += (p.bits // 8) + 8 + end + ensure(w, need) + local start = w.pos + while seekIdx < seekPoints and total >= seekNext do + local at = seekAt + seekIdx * 18 + local sn, off = total, start - audioStart + local tb = w.buf + for k = 0, 7 do + writeu8(tb, at + k, floor(sn / POW[8 * (7 - k) + 1]) % 256) + writeu8(tb, at + 8 + k, floor(off / POW[8 * (7 - k) + 1]) % 256) + end + writeu8(tb, at + 16, n // 256) + writeu8(tb, at + 17, n % 256) + seekIdx += 1 + seekNext = seekIdx * interval + end + put(w, 0x3FFE, 14) + put(w, 0, 1) + put(w, 0, 1) -- fixed block size + local bcode, bextra = blockCode(n) + put(w, bcode, 4) + put(w, rateCode, 4) + put(w, assign, 4) + put(w, sizeCode, 3) + put(w, 0, 1) + putUtf8(w, frameNo) + if bextra > 0 then + put(w, n - 1, bextra) + end + put(w, crc8(w.buf, start, w.pos - start), 8) + for _, p in chosen do + writeSubframe(w, p, n) + end + alignByte(w) + local c16 = crc16(w.buf, start, w.pos - start) + put(w, c16, 16) + local fsize = w.pos - start + if fsize < minFrame then + minFrame = fsize + end + if fsize > maxFrame then + maxFrame = fsize + end + frameNo += 1 + total += n + if n < bs then + break + end + end + if src.err then + return nil, tostring(src.err) + end + local out = buffer.create(w.pos) + buffer.copy(out, 0, w.buf, 0, w.pos) + local si = Encode.streaminfo(bs, if frameNo > 0 then minFrame else 0, maxFrame, rate, ch, bps, total, md5:digest()) + buffer.copy(out, siData, si, 0, 34) + return out, nil +end + +-- STREAMINFO: 34 bytes +@native function Encode.streaminfo(bs: number, minFrame: number, maxFrame: number, rate: number, ch: number, bps: number, total: number, md5: string): buffer + local w: W = { buf = buffer.create(64), pos = 0, acc = 0, cnt = 0 } + put(w, bs, 16) + put(w, bs, 16) + put(w, minFrame, 24) + put(w, maxFrame, 24) + put(w, rate, 20) + put(w, ch - 1, 3) + put(w, bps - 1, 5) + put(w, floor(total / 2 ^ 32), 4) + put(w, total % 2 ^ 32, 32) + for i = 1, 16 do + put(w, string.byte(md5, i), 8) + end + local out = buffer.create(34) + buffer.copy(out, 0, w.buf, 0, 34) + return out +end + +return Encode +end +__FILES["codecs/audio/Flac/Frame"] = @native function() + + + +-- codecs/audio/Flac/Frame: FLAC frames: header (CRC-8), sync search, subframes, residuals, decorrelation, CRC-16. +-- Absorbed from flac-luau 7083d0d (no third-party code). The input needs PAD zero bytes after `len`: the bit reader +-- reads 32-bit words unchecked and compares its position with the data end once per sample. +local readu8, readu32 = buffer.readu8, buffer.readu32 +local band, bxor, lshift, rshift, countlz, byteswap = bit32.band, bit32.bxor, bit32.lshift, bit32.rshift, + bit32.countlz, bit32.byteswap +local floor = math.floor + +local Frame = {} +Frame.PAD = 32 + +-- CRC-8 (poly 0x07) and CRC-16 (poly 0x8005), MSB first, init 0 +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 band(c, 0x80) ~= 0 then band(bxor(lshift(c, 1), 0x07), 0xFF) else band(lshift(c, 1), 0xFF) + end + CRC8[i + 1] = c + local d = lshift(i, 8) + for _ = 1, 8 do + d = if band(d, 0x8000) ~= 0 then band(bxor(lshift(d, 1), 0x8005), 0xFFFF) else band(lshift(d, 1), 0xFFFF) + end + CRC16[i + 1] = d +end + +@native local function crc16(b: buffer, from: number, to: number): number + local c = 0 + for i = from, to - 1 do + c = bxor(band(lshift(c, 8), 0xFFFF), CRC16[bxor(rshift(c, 8), readu8(b, i)) + 1]) + end + return c +end +Frame.crc16 = crc16 + +@native 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 +end + +local BLOCK = { [1] = 192, [2] = 576, [3] = 1152, [4] = 2304, [5] = 4608, [8] = 256, [9] = 512, [10] = 1024, + [11] = 2048, [12] = 4096, [13] = 8192, [14] = 16384, [15] = 32768 } +local RATE = { [1] = 88200, [2] = 176400, [3] = 192000, [4] = 8000, [5] = 16000, [6] = 22050, [7] = 24000, + [8] = 32000, [9] = 44100, [10] = 48000, [11] = 96000 } +local BITS = { [1] = 8, [2] = 12, [4] = 16, [5] = 20, [6] = 24, [7] = 32 } + +type Header = { + offset: number, + size: number, -- header bytes, CRC-8 included + blockSize: number, + sampleRate: number, + channels: number, + assignment: number, -- 0..7 independent, 8 left/side, 9 side/right, 10 mid/side + bps: number, + variable: boolean, -- variable block size: number is a sample number, else a frame number + number: number, +} + +@native function Frame.header(b: buffer, pos: number, len: number, si: any): Header? + if pos < 0 or pos + 6 > len then + return nil + end + if readu8(b, pos) ~= 0xFF then + return nil + end + local b1 = readu8(b, pos + 1) + if band(b1, 0xFE) ~= 0xF8 then + return nil + end + local b2 = readu8(b, pos + 2) + local b3 = readu8(b, pos + 3) + local bsCode, rCode = rshift(b2, 4), band(b2, 15) + local chCode, sCode = rshift(b3, 4), band(rshift(b3, 1), 7) + if bsCode == 0 or rCode == 15 or chCode > 10 or sCode == 3 or band(b3, 1) ~= 0 then + return nil + end + -- UTF-8-like coded number + local p = pos + 4 + local x = readu8(b, p) + p += 1 + local num, more + if x < 0x80 then + num, more = x, 0 + elseif x >= 0xC0 and x < 0xE0 then + num, more = band(x, 0x1F), 1 + elseif x >= 0xE0 and x < 0xF0 then + num, more = band(x, 0x0F), 2 + elseif x >= 0xF0 and x < 0xF8 then + num, more = band(x, 0x07), 3 + elseif x >= 0xF8 and x < 0xFC then + num, more = band(x, 0x03), 4 + elseif x >= 0xFC and x < 0xFE then + num, more = band(x, 0x01), 5 + elseif x == 0xFE then + num, more = 0, 6 + else + return nil + end + for _ = 1, more do + local c = readu8(b, p) + p += 1 + if band(c, 0xC0) ~= 0x80 then + return nil + end + num = num * 64 + band(c, 0x3F) + end + local variable = band(b1, 1) == 1 + if not variable and more > 5 then + return nil + end + local bs = BLOCK[bsCode] + if bsCode == 6 then + bs = readu8(b, p) + 1 + p += 1 + elseif bsCode == 7 then + bs = readu8(b, p) * 256 + readu8(b, p + 1) + 1 + p += 2 + end + local rate = RATE[rCode] + if rCode == 0 then + rate = si and si.sampleRate or 0 + elseif rCode == 12 then + rate = readu8(b, p) * 1000 + p += 1 + elseif rCode == 13 then + rate = readu8(b, p) * 256 + readu8(b, p + 1) + p += 2 + elseif rCode == 14 then + rate = (readu8(b, p) * 256 + readu8(b, p + 1)) * 10 + p += 2 + end + local bps = BITS[sCode] + if sCode == 0 then + bps = si and si.bitsPerSample or 0 + end + if not bs or not bps or bps < 4 or bps > 32 or p + 1 > len then + return nil + end + if crc8(b, pos, p) ~= readu8(b, p) then + return nil + end + return { + offset = pos, + size = p + 1 - pos, + blockSize = bs, + sampleRate = rate or 0, + channels = if chCode < 8 then chCode + 1 else 2, + assignment = chCode, + bps = bps, + variable = variable, + number = num, + } +end + +@native function Frame.find(b: buffer, pos: number, limit: number, len: number, si: any): Header? + local lim = math.min(limit, len - 6) + if pos < 0 then + pos = 0 + end + while pos < lim do + if readu8(b, pos) == 0xFF then + local b1 = readu8(b, pos + 1) + if b1 == 0xF8 or b1 == 0xF9 then + local h = Frame.header(b, pos, len, si) + if h then + return h + end + end + end + pos += 1 + end + return nil +end + +@native local function bits(b: buffer, p: number, n: number): number + if n == 0 then + return 0 + elseif n <= 24 then + return rshift(lshift(byteswap(readu32(b, rshift(p, 3))), band(p, 7)), 32 - n) + end + local hi = rshift(lshift(byteswap(readu32(b, rshift(p, 3))), band(p, 7)), 32 - (n - 16)) + local q = p + n - 16 + return hi * 65536 + rshift(lshift(byteswap(readu32(b, rshift(q, 3))), band(q, 7)), 16) +end + +@native local function sbits(b: buffer, p: number, n: number): number + local v = bits(b, p, n) + if n > 0 and v >= POW2[n] then + v -= POW2[n + 1] + end + return v +end + +@native local function residual(b: buffer, p: number, lim: number, s: { number }, n: number, order: number): number + local method = bits(b, p, 2) + if method > 1 then + return -1 + end + local porder = bits(b, p + 2, 4) + p += 6 + local pbits = if method == 0 then 4 else 5 + local escape = if method == 0 then 15 else 31 + local parts = POW2[porder + 1] + local psize = rshift(n, porder) + if psize * parts ~= n or psize < order then + return -1 + end + local i = order + 1 + for part = 0, parts - 1 do + if p > lim then + return -1 + end + local k = bits(b, p, pbits) + p += pbits + local stop = (part + 1) * psize + if k == escape then + local nb = bits(b, p, 5) + p += 5 + if nb == 0 then + for j = i, stop do + s[j] = 0 + end + else + local half, full = POW2[nb], POW2[nb + 1] + for j = i, stop do + if p > lim then + return -1 + end + local v = bits(b, p, nb) + p += nb + if v >= half then + v -= full + end + s[j] = v + end + end + elseif k <= 24 then + local pk = POW2[k + 1] + local rk = 32 - k + for j = i, stop do + if p > lim then + return -1 + end + local sh = band(p, 7) + local w = lshift(byteswap(readu32(b, rshift(p, 3))), sh) + local q, r + if w ~= 0 then + q = countlz(w) + local used = q + 1 + k + if used <= 32 - sh then + r = if k == 0 then 0 else rshift(lshift(w, q + 1), rk) + p += used + else + p += q + 1 + r = if k == 0 then 0 else rshift(lshift(byteswap(readu32(b, rshift(p, 3))), band(p, 7)), rk) + p += k + end + else + q = 32 - sh + p += q + while true do + if p > lim then + return -1 + end + local w2 = lshift(byteswap(readu32(b, rshift(p, 3))), band(p, 7)) + if w2 ~= 0 then + local z = countlz(w2) + q += z + p += z + 1 + break + end + local adv = 32 - band(p, 7) + q += adv + p += adv + end + r = if k == 0 then 0 else rshift(lshift(byteswap(readu32(b, rshift(p, 3))), band(p, 7)), rk) + p += k + end + local u = q * pk + r + local h = floor(u * 0.5) + s[j] = if h + h == u then h else -h - 1 + end + else + -- k = 25..30 (Rice2): the remainder takes two reads + local pk = POW2[k + 1] + for j = i, stop do + if p > lim then + return -1 + end + local q = 0 + while true do + if p > lim then + return -1 + end + local w = lshift(byteswap(readu32(b, rshift(p, 3))), band(p, 7)) + if w ~= 0 then + local z = countlz(w) + q += z + p += z + 1 + break + end + local adv = 32 - band(p, 7) + q += adv + p += adv + end + local r = bits(b, p, k) + p += k + local u = q * pk + r + local h = floor(u * 0.5) + s[j] = if h + h == u then h else -h - 1 + end + end + i = stop + 1 + end + return p +end + +@native local function fixed(s: { number }, n: number, order: number) + if order == 1 then + local a = s[1] + for i = 2, n do + a += s[i] + s[i] = a + end + elseif order == 2 then + local a, c = s[2], s[1] + for i = 3, n do + local v = s[i] + 2 * a - c + s[i] = v + c = a + a = v + end + elseif order == 3 then + local a, c, d = s[3], s[2], s[1] + for i = 4, n do + local v = s[i] + 3 * a - 3 * c + d + s[i] = v + d = c + c = a + a = v + end + elseif order == 4 then + local a, c, d, e = s[4], s[3], s[2], s[1] + for i = 5, n do + local v = s[i] + 4 * a - 6 * c + 4 * d - e + s[i] = v + e = d + d = c + c = a + a = v + end + end +end + +-- LPC restoration: s[i] += floor(sum(coef[j] * s[i - j]) / 2^shift); unrolled for orders up to 12 +@native local function lpc(s: { number }, n: number, cf: { number }, order: number, shift: number) + local div = POW2[shift + 1] + local inv = 1 / div + if order <= 4 then + local c1, c2, c3, c4 = cf[1], cf[2] or 0, cf[3] or 0, cf[4] or 0 + local s1, s2, s3, s4 = s[order], s[order - 1] or 0, s[order - 2] or 0, s[order - 3] or 0 + for i = order + 1, n do + local v = s[i] + floor((c1 * s1 + c2 * s2 + c3 * s3 + c4 * s4) * inv) + s[i] = v + s4 = s3 + s3 = s2 + s2 = s1 + s1 = v + end + elseif order <= 8 then + local c1, c2, c3, c4, c5, c6, c7, c8 = cf[1], cf[2], cf[3], cf[4], cf[5], cf[6] or 0, cf[7] or 0, cf[8] or 0 + local s1, s2, s3, s4, s5 = s[order], s[order - 1], s[order - 2], s[order - 3], s[order - 4] + local s6, s7, s8 = s[order - 5] or 0, s[order - 6] or 0, s[order - 7] or 0 + for i = order + 1, n do + local v = s[i] + + floor((c1 * s1 + c2 * s2 + c3 * s3 + c4 * s4 + c5 * s5 + c6 * s6 + c7 * s7 + c8 * s8) * inv) + s[i] = v + s8 = s7 + s7 = s6 + s6 = s5 + s5 = s4 + s4 = s3 + s3 = s2 + s2 = s1 + s1 = v + end + elseif order <= 12 then + local c1, c2, c3, c4, c5, c6, c7, c8 = cf[1], cf[2], cf[3], cf[4], cf[5], cf[6], cf[7], cf[8] + local c9, c10, c11, c12 = cf[9], cf[10] or 0, cf[11] or 0, cf[12] or 0 + local s1, s2, s3, s4, s5, s6 = s[order], s[order - 1], s[order - 2], s[order - 3], s[order - 4], s[order - 5] + local s7, s8, s9 = s[order - 6], s[order - 7], s[order - 8] + local s10, s11, s12 = s[order - 9] or 0, s[order - 10] or 0, s[order - 11] or 0 + for i = order + 1, n do + local v = s[i] + + floor( + ( + c1 * s1 + c2 * s2 + c3 * s3 + c4 * s4 + c5 * s5 + c6 * s6 + + c7 * s7 + c8 * s8 + c9 * s9 + c10 * s10 + c11 * s11 + c12 * s12 + ) * inv + ) + s[i] = v + s12 = s11 + s11 = s10 + s10 = s9 + s9 = s8 + s8 = s7 + s7 = s6 + s6 = s5 + s5 = s4 + s4 = s3 + s3 = s2 + s2 = s1 + s1 = v + end + else + for i = order + 1, n do + local sum = 0 + for j = 1, order do + sum += cf[j] * s[i - j] + end + s[i] += floor(sum * inv) + end + end +end + +@native local function subframe(b: buffer, p: number, lim: number, s: { number }, n: number, bps: number, cf: { number }): number + if p > lim then + return -1 + end + local hdr = bits(b, p, 8) + p += 8 + if hdr >= 128 then + return -1 + end + local typ = rshift(hdr, 1) + local wasted = 0 + if band(hdr, 1) == 1 then + -- unary count of wasted bits (minus one) + while true do + if p > lim or wasted > 32 then + return -1 + end + local bit = bits(b, p, 1) + p += 1 + wasted += 1 + if bit == 1 then + break + end + end + bps -= wasted + if bps < 1 then + return -1 + end + end + if typ == 0 then + local v = sbits(b, p, bps) + p += bps + for i = 1, n do + s[i] = v + end + elseif typ == 1 then + for i = 1, n do + if p > lim then + return -1 + end + s[i] = sbits(b, p, bps) + p += bps + end + elseif typ >= 8 and typ <= 12 then + local order = typ - 8 + if order > n then + return -1 + end + for i = 1, order do + if p > lim then + return -1 + end + s[i] = sbits(b, p, bps) + p += bps + end + p = residual(b, p, lim, s, n, order) + if p < 0 then + return -1 + end + fixed(s, n, order) + elseif typ >= 32 then + local order = typ - 31 + if order > n then + return -1 + end + for i = 1, order do + if p > lim then + return -1 + end + s[i] = sbits(b, p, bps) + p += bps + end + local prec = bits(b, p, 4) + 1 + p += 4 + if prec == 16 then + return -1 + end + local shift = sbits(b, p, 5) + p += 5 + if shift < 0 then + return -1 + end + for j = 1, order do + if p > lim then + return -1 + end + cf[j] = sbits(b, p, prec) + p += prec + end + for j = order + 1, 12 do + cf[j] = 0 -- the unrolled filters read up to 12 coefficients + end + p = residual(b, p, lim, s, n, order) + if p < 0 then + return -1 + end + lpc(s, n, cf, order, shift) + else + return -1 + end + if wasted > 0 then + local m = POW2[wasted + 1] + for i = 1, n do + s[i] *= m + end + end + return p +end + +@native function Frame.decode(b: buffer, len: number, h: Header, chans: { { number } }, cf: { number }, checkCrc: boolean): (number?, string?) + local n = h.blockSize + local lim = len * 8 + local p = (h.offset + h.size) * 8 + local asg = h.assignment + for c = 1, h.channels do + local bps = h.bps + if (asg == 8 and c == 2) or (asg == 9 and c == 1) or (asg == 10 and c == 2) then + bps += 1 -- the side channel + end + p = subframe(b, p, lim, chans[c], n, bps, cf) + if p < 0 then + return nil, "bad subframe" + end + end + local e = rshift(p + 7, 3) + if e + 2 > len then + return nil, "truncated frame" + end + if checkCrc then + local want = readu8(b, e) * 256 + readu8(b, e + 1) + if crc16(b, h.offset, e) ~= want then + return nil, "crc16 mismatch" + end + end + if asg >= 8 then + local l, r = chans[1], chans[2] + if asg == 8 then + for i = 1, n do + r[i] = l[i] - r[i] + end + elseif asg == 9 then + for i = 1, n do + l[i] += r[i] + end + else + for i = 1, n do + local side = r[i] + local m = l[i] * 2 + (side % 2) + l[i] = (m + side) * 0.5 + r[i] = (m - side) * 0.5 + end + end + end + return e + 2, nil +end + +return Frame +end +end + + + + + + Musepack + --!optimize 2 +--!nocheck +-- rosetta chunk Musepack (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 3 modules (1 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["codecs/audio/Musepack"] = function() + +-- codecs/audio/Musepack: Musepack (MPC) stream versions 7 and 8. +-- A port of libmpcdec (musepack_src_r475: mpc_demux.c, streaminfo.c, mpc_decoder.c; BSD-3-Clause, (c) The Musepack +-- Development Team, licenses/libmpcdec-BSD.txt), gapless like libmpcdec. SV4 - SV6 are UNSUPPORTED. +local Err = __include("core/Err") +local Crc32 = __include("core/Crc32") +local Decode = __include("codecs/audio/Musepack/Decode") + +local Musepack = {} + +local RATES = { 44100, 48000, 37800, 32000 } +local FRAME, DELAY, PAD = Decode.FRAME, Decode.DELAY, Decode.PAD +local readu8 = buffer.readu8 + +type Stream = { + version: number, + sampleRate: number, + channels: number, + frames: number, + maxBand: number, + ms: boolean, + profile: number, -- SV7: the profile index (7 telephone .. 13 braindead); SV8: the quality (0 .. 15.875) + encoder: number, -- encoder version (SV7: one byte; SV8: major * 2^24 + minor * 2^16 + build * 2^8) + gapless: boolean, + pns: boolean?, + gain: { titleGain: number, titlePeak: number, albumGain: number, albumPeak: number }?, + blockFrames: number, -- frames per packet (SV7: 1; SV8: 2^block_pwr) + bytes: number, + count: number, + start: (i: number) -> number, + decode: (i: number) -> (number?, Err.Err?), + pcm: () -> { number }, + reset: () -> (), + skip: number, + stop: number, + preroll: number, +} + +-- SV7 reads the stream as little-endian 32-bit words, most significant bit first: swap them into a padded copy +local function swapped(buf: buffer, p: number, limit: number): buffer + local n = limit - p + local words = (n + 3) // 4 + local out = buffer.create(words * 4 + PAD) + buffer.copy(out, 0, buf, p, n) + for i = 0, words - 1 do + buffer.writeu32(out, i * 4, bit32.byteswap(buffer.readu32(out, i * 4))) + end + return out +end + +local function sv7(buf: buffer, start: number, limit: number): (Stream?, Err.Err?) + if limit - start < 32 then + return nil, Err.new(Err.TRUNCATED, "SV7 header", start) + end + local ver = bit32.band(readu8(buf, start + 3), 15) + if ver ~= 7 then + return nil, Err.new(Err.UNSUPPORTED, "Musepack stream version " .. ver .. " (SV7 and SV8 only)", start) + end + local s = swapped(buf, start + 4, limit) + local totalBits = (limit - start - 4) * 8 + local at = Decode.bitsAt + local frames = at(s, 0, 16) * 65536 + at(s, 16, 16) + local ms = at(s, 33, 1) == 1 + local maxBand = at(s, 34, 6) + local profile = at(s, 40, 4) + local rate = RATES[at(s, 46, 2) + 1] + local gainTitle, peakTitle = at(s, 64, 16), at(s, 80, 16) + local gainAlbum, peakAlbum = at(s, 96, 16), at(s, 112, 16) + local gapless = at(s, 128, 1) == 1 + local last = at(s, 129, 11) + local encoder = at(s, 160, 8) + if maxBand == 0 or maxBand >= 32 then + return nil, Err.new(Err.CORRUPT, "bad band count " .. maxBand, start) + end + if last == 0 then + last = FRAME + elseif last > FRAME then + return nil, Err.new(Err.CORRUPT, "bad last frame length", start) + end + if frames == 0 then + return nil, Err.new(Err.CORRUPT, "no frames", start) + end + if frames > 2 ^ 24 then + return nil, Err.new(Err.LIMIT, "more than 2^24 frames", start) + end + local samples = frames * FRAME - (if gapless then FRAME - last else DELAY) + -- the frame index: a 20-bit size in front of each frame (the last one has 11 more bits: its length) + local offs: { number }, sizes: { number } = {}, {} + local pos = 168 + for i = 1, frames do + if pos + 20 > totalBits then + break + end + local size = at(s, pos, 20) + local stop = pos + 20 + size + (if i == frames then 11 else 0) + if stop > totalBits then + break + end + offs[i], sizes[i] = pos + 20, size + pos = stop + end + local have = #offs + if have == 0 then + return nil, Err.new(Err.TRUNCATED, "no complete frame", start) + end + -- frames past the stream (a truncated file, or the synthesis tail of a gapless stream) decode as silence + local need = math.min((samples + DELAY + FRAME - 1) // FRAME, have + 1) + local stopAt = math.min(samples + DELAY, have * FRAME + (if have < frames then 0 else FRAME)) + local st = Decode.state(7, maxBand, ms, 2) + local pcm = table.create(FRAME * 2, 0) + local prev = 0 + local out: Stream = { + version = 7, + sampleRate = rate, + channels = 2, + frames = math.max(0, stopAt - DELAY), + maxBand = maxBand, + ms = ms, + profile = profile, + encoder = encoder, + gapless = gapless, + gain = { titleGain = gainTitle, titlePeak = peakTitle, albumGain = gainAlbum, albumPeak = peakAlbum }, + blockFrames = 1, + bytes = limit - start, + count = need, + start = function(i: number): number + return (i - 1) * FRAME + end, + decode = function(i: number): (number?, Err.Err?) + if i ~= prev + 1 then + Decode.reset(st, if i == 1 then 0 else 0x01010101) + end + prev = i + local o: number? = offs[i] + if o == nil then + Decode.frame(st, s, -1, 0, false, pcm, 1) + return FRAME, nil + end + local e, msg = Decode.frame(st, s, o, o + sizes[i], false, pcm, 1) + if not e then + return nil, Err.from(msg, start + 4 + o // 8) + end + if e ~= o + sizes[i] then + return nil, Err.new(Err.CORRUPT, "frame " .. i .. " has the wrong size", start + 4 + o // 8) + end + return FRAME, nil + end, + pcm = function(): { number } + return pcm + end, + reset = function() + prev = -1 + end, + skip = DELAY, + stop = stopAt, + preroll = 32, + } + return out, nil +end + +-- a packet size: 7 bits per byte, most significant first, bit 7 = more +local function varint(buf: buffer, p: number, limit: number): (number, number) + local v = 0 + for k = 0, 7 do + if p + k >= limit then + return -1, p + end + local b = readu8(buf, p + k) + v = v * 128 + bit32.band(b, 127) + if b < 128 then + return v, p + k + 1 + end + end + return -1, p +end + +local function sv8(buf: buffer, start: number, limit: number): (Stream?, Err.Err?) + local p = start + 4 + local sh: { [string]: any }? = nil + local gain, pns, profile, encoder = nil, nil, 0, 0 + local apOff: { number }, apSize: { number } = {}, {} + while p + 2 < limit do + local k1, k2 = readu8(buf, p), readu8(buf, p + 1) + if k1 < 65 or k1 > 90 or k2 < 65 or k2 > 90 then + return nil, Err.new(Err.CORRUPT, "bad packet key", p) + end + local key = buffer.readstring(buf, p, 2) + local size, body = varint(buf, p + 2, limit) + if size < 0 or size < body - p then + return nil, Err.new(Err.CORRUPT, "bad packet size", p) + end + local stop = p + size + if stop > limit then + if key == "AP" then + break + end + return nil, Err.new(Err.TRUNCATED, key .. " packet", p) + end + if key == "SH" then + if stop - body < 6 then + return nil, Err.new(Err.CORRUPT, "short stream header", p) + end + local crc = buffer.readu32(buf, body) + crc = bit32.byteswap(crc) + if Crc32.of(buf, body + 4, stop - body - 4) ~= crc then + return nil, Err.new(Err.CHECKSUM, "stream header CRC", p) + end + if readu8(buf, body + 4) ~= 8 then + return nil, Err.new(Err.UNSUPPORTED, "Musepack stream version " .. readu8(buf, body + 4), p) + end + local samples, q = varint(buf, body + 5, stop) + local silence, q2 = varint(buf, q, stop) + if samples < 0 or silence < 0 or q2 + 2 > stop then + return nil, Err.new(Err.CORRUPT, "bad stream header", p) + end + local b0, b1 = readu8(buf, q2), readu8(buf, q2 + 1) + sh = { + samples = samples, + silence = silence, + rate = RATES[bit32.rshift(b0, 5) + 1], + maxBand = bit32.band(b0, 31) + 1, + channels = bit32.rshift(b1, 4) + 1, + ms = bit32.band(b1, 8) ~= 0, + blockPwr = bit32.band(b1, 7) * 2, + } + elseif key == "RG" and stop - body >= 9 and readu8(buf, body) == 1 then + local function u16(o: number): number + return readu8(buf, body + o) * 256 + readu8(buf, body + o + 1) + end + gain = { titleGain = u16(1), titlePeak = u16(3), albumGain = u16(5), albumPeak = u16(7) } + elseif key == "EI" and stop - body >= 4 then + local b = readu8(buf, body) + profile = bit32.rshift(b, 1) / 8 + pns = bit32.band(b, 1) == 1 + encoder = readu8(buf, body + 1) * 2 ^ 24 + readu8(buf, body + 2) * 2 ^ 16 + readu8(buf, body + 3) * 2 ^ 8 + elseif key == "AP" then + table.insert(apOff, body) + table.insert(apSize, stop - body) + elseif key == "SE" then + break + end + p = stop + end + if not sh then + return nil, Err.new(Err.CORRUPT, "no stream header", start) + end + local h = sh :: { [string]: any } + local samples, silence, maxBand, channels = h.samples, h.silence, h.maxBand, h.channels + if maxBand >= 32 or channels > 2 or silence > samples then + return nil, Err.new(Err.UNSUPPORTED, string.format("%d bands, %d channels", maxBand, channels), start) + end + if samples > 2 ^ 34 then + return nil, Err.new(Err.LIMIT, "too many samples", start) + end + if #apOff == 0 then + return nil, Err.new(Err.CORRUPT, "no audio packet", start) + end + local per = 2 ^ h.blockPwr + if per * FRAME * channels > 2 ^ 22 then + return nil, Err.new(Err.LIMIT, per .. " frames per audio packet", start) + end + local needFrames = (samples + DELAY + FRAME - 1) // FRAME + local count = math.min(#apOff, (needFrames + per - 1) // per) + local stopAt = math.min(samples + DELAY, count * per * FRAME) + local st = Decode.state(8, maxBand, h.ms, channels) + local pcm = table.create(per * FRAME * channels, 0) + local scratch = buffer.create(0) + local out: Stream = { + version = 8, + sampleRate = h.rate, + channels = channels, + frames = math.max(0, stopAt - DELAY - silence), + maxBand = maxBand, + ms = h.ms, + profile = profile, + encoder = encoder, + gapless = true, + pns = pns, + gain = gain, + blockFrames = per, + bytes = limit - start, + count = count, + start = function(i: number): number + return (i - 1) * per * FRAME + end, + decode = function(i: number): (number?, Err.Err?) + local o: number, size: number = apOff[i], apSize[i] + if buffer.len(scratch) < size + PAD then + scratch = buffer.create(size + PAD) + end + buffer.copy(scratch, 0, buf, o, size) + local nf = math.min(per, needFrames - (i - 1) * per) + local pos = 0 + for f = 1, nf do + local e, msg = Decode.frame(st, scratch, pos, size * 8, f == 1, pcm, (f - 1) * FRAME * channels + 1) + if not e then + return nil, Err.from(msg, o) + end + pos = e + end + if nf == per and size * 8 - pos > 7 then + return nil, Err.new(Err.CORRUPT, "audio packet " .. i .. " has unused data", o) + end + return nf * FRAME, nil + end, + pcm = function(): { number } + return pcm + end, + reset = function() + Decode.reset(st, 0) + end, + skip = DELAY + silence, + stop = stopAt, + preroll = 1, + } + return out, nil +end + +function Musepack.magic(buf: buffer, p: number, limit: number): number + if p + 4 > limit then + return 0 + end + local m = buffer.readstring(buf, p, 4) + if m == "MPCK" then + return 8 + end + if string.sub(m, 1, 3) == "MP+" then + return 7 + end + return 0 +end + +function Musepack.open(buf: buffer, start: number, limit: number): (Stream?, Err.Err?) + local v = Musepack.magic(buf, start, limit) + if v == 8 then + return sv8(buf, start, limit) + elseif v == 7 then + return sv7(buf, start, limit) + end + return nil, Err.new(Err.CORRUPT, "not a Musepack stream", start) +end + +return Musepack +end +__FILES["codecs/audio/Musepack/Decode"] = @native function() + + + +-- codecs/audio/Musepack/Decode: one Musepack SV7 / SV8 frame (1152 samples per channel). +-- A line-by-line port of libmpcdec's mpc_decoder.c, requant.c and synth_filter.c (musepack_src_r475, BSD-3-Clause, (c) The +-- Musepack Development Team, licenses/libmpcdec-BSD.txt). The caller pads the buffer by PAD bytes past `limit`. +local T = __include("codecs/audio/Musepack/Tables") + +local readu32, bswap, extract, band, bor, rshift, lshift, bnot, bxor = + buffer.readu32, bit32.byteswap, bit32.extract, bit32.band, bit32.bor, bit32.rshift, bit32.lshift, bit32.bnot, bit32.bxor +local abs = math.abs + +local Decode = {} +Decode.PAD = 8192 +Decode.DELAY = 481 -- MPC_DECODER_SYNTH_DELAY +Decode.FRAME = 1152 + +local L = T.lut +local HDR, SCFI7, DSCF7 = L(T.HuffHdr), L(T.HuffSCFI), L(T.HuffDSCF) +local Q7: { { T.Lut } } = { + { L(T.HuffQ1_0), L(T.HuffQ1_1) }, + { L(T.HuffQ2_0), L(T.HuffQ2_1) }, + { L(T.HuffQ3_0), L(T.HuffQ3_1) }, + { L(T.HuffQ4_0), L(T.HuffQ4_1) }, + { L(T.HuffQ5_0), L(T.HuffQ5_1) }, + { L(T.HuffQ6_0), L(T.HuffQ6_1) }, + { L(T.HuffQ7_0), L(T.HuffQ7_1) }, +} +local BANDS8 = L(T.H_Bands, T.S_Bands) +local SCFI8 = { L(T.H_SCFI_1, T.S_SCFI_1), L(T.H_SCFI_2, T.S_SCFI_2) } +local DSCF8 = { L(T.H_DSCF_1, T.S_DSCF_1), L(T.H_DSCF_2, T.S_DSCF_2) } +local RES8 = { L(T.H_Res_1, T.S_Res_1), L(T.H_Res_2, T.S_Res_2) } +local Q1_8 = L(T.H_Q1, T.S_Q1) +local Q9UP = L(T.H_Q9up, T.S_Q9up) +-- mpc_can_Q[res - 2][0 / 1] for res 2 and 5 .. 8; res 3 / 4 use Q34[res - 2] +local Q8: { [number]: { T.Lut } } = { + [2] = { L(T.H_Q2_1, T.S_Q2_1), L(T.H_Q2_2, T.S_Q2_2) }, + [5] = { L(T.H_Q5_1, T.S_Q5_1), L(T.H_Q5_2, T.S_Q5_2) }, + [6] = { L(T.H_Q6_1, T.S_Q6_1), L(T.H_Q6_2, T.S_Q6_2) }, + [7] = { L(T.H_Q7_1, T.S_Q7_1), L(T.H_Q7_2, T.S_Q7_2) }, + [8] = { L(T.H_Q8_1, T.S_Q8_1), L(T.H_Q8_2, T.S_Q8_2) }, +} +local Q34 = { L(T.H_Q3, T.S_Q3), L(T.H_Q4, T.S_Q4) } +local THRES = { [2] = 3, [5] = 1, [6] = 3, [7] = 4, [8] = 8 } +local CC, DC, RES_BIT = T.CC, T.DC, T.RES_BIT +local CNK, CNK_LEN, CNK_LOST, LOG2, LOG2_LOST = T.CNK, T.CNK_LEN, T.CNK_LOST, T.LOG2, T.LOG2_LOST + +-- the f32 rounding of the C tables (libmpcdec decodes in single precision) +local F32 = buffer.create(4) +@native local function f32(x: number): number + buffer.writef32(F32, 0, x) + return buffer.readf32(F32, 0) +end +for i, v in CC do + CC[i] = f32(v) +end + +-- SCF[i]: the scalefactor of index i (0 .. 255, the index's low byte): 2^-15 * 0.83298...^(s - 1), s = i as int8 +-- (libmpcdec's mpc_decoder_scale_output in float mode: 1 dB steps, the table filled outwards from index 1) +local SCF = table.create(256, 0) +do + local f1 = 1 / 32768 + local f2 = f1 + SCF[2] = f32(f1) + f1 *= 0.83298066476582673961 + f2 *= 1 / 0.83298066476582673961 + for n = 1, 128 do + SCF[band(1 + n, 255) + 1] = f32(f1) + SCF[band(1 - n, 255) + 1] = f32(f2) + f1 *= 0.83298066476582673961 + f2 *= 1 / 0.83298066476582673961 + end +end + +-- the synthesis window D (Di_opt / 65536), 32 x 16, row-major +local DW = table.create(512, 0) +for i, v in T.DI do + DW[i] = f32(v / 65536) +end + +local B: buffer = buffer.create(0) +local P = 0 + +@native local function bits(n: number): number + if n <= 0 then + return 0 + end + if n > 24 then + local hi = bits(n - 16) + return hi * 65536 + bits(16) + end + local w = bswap(readu32(B, rshift(P, 3))) + local v = extract(w, 32 - band(P, 7) - n, n) + P += n + return v +end + +@native local function peek16(): number + local w = bswap(readu32(B, rshift(P, 3))) + return extract(w, 16 - band(P, 7), 16) +end + +@native local function huff(t: T.Lut): number + local code = peek16() + local k = rshift(code, 8) + 1 + local n = t.len[k] + if n > 0 then + P += n + return t.val[k] + end + local j = t.val[k] + local codes = t.codes + while code < codes[j] do + j += 1 + end + n = t.lens[j] + P += n + local sym = t.sym + if sym then + return sym[band(t.vals[j] - rshift(code, 16 - n), 255) + 1] or 0 + end + return t.vals[j] +end + +-- mpc_bits_log_dec: 0 .. max +@native local function logDec(max: number): number + if max <= 0 then + return 0 + end + local v = 0 + local len, lost = LOG2[max], LOG2_LOST[max] + if len > 1 then + v = bits(len - 1) + end + if v >= lost then + v = v * 2 + bits(1) - lost + end + return v +end + +-- mpc_bits_enum_dec: an n-bit word with k bits set +@native local function enumDec(k: number, n: number): number + local out = 0 + local code = bits(CNK_LEN[k][n] - 1) + local lost = CNK_LOST[k][n] + if code >= lost then + code = code * 2 + bits(1) - lost + end + repeat + n -= 1 + local c = CNK[k][n + 1] + if code >= c then + out = bor(out, lshift(1, n)) + code -= c + k -= 1 + end + until k <= 0 or n <= 0 + return out +end + +-- mpc_random_int: two polynomial counters, XORed +local PARITY = table.create(256, 0) +for i = 0, 255 do + local p, v = 0, i + while v > 0 do + p = bxor(p, band(v, 1)) + v = rshift(v, 1) + end + PARITY[i + 1] = p +end + +-- mpc_compute_new_V: 32 subband samples Y[y .. y + 31] -> 64 V values at V[o .. o + 63] (the ISO 11172-3 matrixing +-- through Byeong Gi Lee's fast DCT) +-- (two halves: as one function, its native lowering fails register allocation and the whole function runs +-- interpreted) +@native local function newVEven(Y: { number }, y: number, V: { number }, o: number) + local A00 = Y[y] + Y[y + 31] + local A01 = Y[y + 1] + Y[y + 30] + local A02 = Y[y + 2] + Y[y + 29] + local A03 = Y[y + 3] + Y[y + 28] + local A04 = Y[y + 4] + Y[y + 27] + local A05 = Y[y + 5] + Y[y + 26] + local A06 = Y[y + 6] + Y[y + 25] + local A07 = Y[y + 7] + Y[y + 24] + local A08 = Y[y + 8] + Y[y + 23] + local A09 = Y[y + 9] + Y[y + 22] + local A10 = Y[y + 10] + Y[y + 21] + local A11 = Y[y + 11] + Y[y + 20] + local A12 = Y[y + 12] + Y[y + 19] + local A13 = Y[y + 13] + Y[y + 18] + local A14 = Y[y + 14] + Y[y + 17] + local A15 = Y[y + 15] + Y[y + 16] + local B00 = A00 + A15 + local B01 = A01 + A14 + local B02 = A02 + A13 + local B03 = A03 + A12 + local B04 = A04 + A11 + local B05 = A05 + A10 + local B06 = A06 + A09 + local B07 = A07 + A08 + local B08 = (A00 - A15) * 0.5024192929 + local B09 = (A01 - A14) * 0.5224986076 + local B10 = (A02 - A13) * 0.5669440627 + local B11 = (A03 - A12) * 0.6468217969 + local B12 = (A04 - A11) * 0.7881546021 + local B13 = (A05 - A10) * 1.0606776476 + local B14 = (A06 - A09) * 1.7224471569 + local B15 = (A07 - A08) * 5.1011486053 + A00 = B00 + B07 + A01 = B01 + B06 + A02 = B02 + B05 + A03 = B03 + B04 + A04 = (B00 - B07) * 0.5097956061 + A05 = (B01 - B06) * 0.6013448834 + A06 = (B02 - B05) * 0.8999761939 + A07 = (B03 - B04) * 2.5629155636 + A08 = B08 + B15 + A09 = B09 + B14 + A10 = B10 + B13 + A11 = B11 + B12 + A12 = (B08 - B15) * 0.5097956061 + A13 = (B09 - B14) * 0.6013448834 + A14 = (B10 - B13) * 0.8999761939 + A15 = (B11 - B12) * 2.5629155636 + B00 = A00 + A03 + B01 = A01 + A02 + B02 = (A00 - A03) * 0.5411961079 + B03 = (A01 - A02) * 1.3065630198 + B04 = A04 + A07 + B05 = A05 + A06 + B06 = (A04 - A07) * 0.5411961079 + B07 = (A05 - A06) * 1.3065630198 + B08 = A08 + A11 + B09 = A09 + A10 + B10 = (A08 - A11) * 0.5411961079 + B11 = (A09 - A10) * 1.3065630198 + B12 = A12 + A15 + B13 = A13 + A14 + B14 = (A12 - A15) * 0.5411961079 + B15 = (A13 - A14) * 1.3065630198 + A00 = B00 + B01 + A01 = (B00 - B01) * 0.7071067691 + A02 = B02 + B03 + A03 = (B02 - B03) * 0.7071067691 + A04 = B04 + B05 + A05 = (B04 - B05) * 0.7071067691 + A06 = B06 + B07 + A07 = (B06 - B07) * 0.7071067691 + A08 = B08 + B09 + A09 = (B08 - B09) * 0.7071067691 + A10 = B10 + B11 + A11 = (B10 - B11) * 0.7071067691 + A12 = B12 + B13 + A13 = (B12 - B13) * 0.7071067691 + A14 = B14 + B15 + A15 = (B14 - B15) * 0.7071067691 + V[o + 48] = -A00 + V[o] = A01 + V[o + 8] = A03 + V[o + 40] = -A02 - A03 + V[o + 12] = A07 + local t = A05 + A07 + V[o + 4] = t + V[o + 36] = -(t + A06) + V[o + 44] = -A04 - A06 - A07 + V[o + 14] = A15 + t = A11 + A15 + V[o + 10] = t + V[o + 6] = t + A13 + t = A09 + A13 + A15 + V[o + 2] = t + t = -t - A14 + V[o + 34] = t + V[o + 38] = t + A09 - A10 - A11 + t = -(A12 + A14 + A15) + V[o + 46] = t - A08 + V[o + 42] = t - A10 - A11 +end + +@native local function newVOdd(Y: { number }, y: number, V: { number }, o: number) + local A00, A01, A02, A03, A04, A05, A06, A07, A08, A09, A10, A11, A12, A13, A14, A15 + local B00, B01, B02, B03, B04, B05, B06, B07, B08, B09, B10, B11, B12, B13, B14, B15 + local t + A00 = (Y[y] - Y[y + 31]) * 0.5006030202 + A01 = (Y[y + 1] - Y[y + 30]) * 0.5054709315 + A02 = (Y[y + 2] - Y[y + 29]) * 0.5154473186 + A03 = (Y[y + 3] - Y[y + 28]) * 0.5310425758 + A04 = (Y[y + 4] - Y[y + 27]) * 0.5531039238 + A05 = (Y[y + 5] - Y[y + 26]) * 0.5829349756 + A06 = (Y[y + 6] - Y[y + 25]) * 0.6225041151 + A07 = (Y[y + 7] - Y[y + 24]) * 0.6748083234 + A08 = (Y[y + 8] - Y[y + 23]) * 0.7445362806 + A09 = (Y[y + 9] - Y[y + 22]) * 0.8393496275 + A10 = (Y[y + 10] - Y[y + 21]) * 0.9725682139 + A11 = (Y[y + 11] - Y[y + 20]) * 1.1694399118 + A12 = (Y[y + 12] - Y[y + 19]) * 1.4841645956 + A13 = (Y[y + 13] - Y[y + 18]) * 2.0577809811 + A14 = (Y[y + 14] - Y[y + 17]) * 3.4076085091 + A15 = (Y[y + 15] - Y[y + 16]) * 10.1900081635 + B00 = A00 + A15 + B01 = A01 + A14 + B02 = A02 + A13 + B03 = A03 + A12 + B04 = A04 + A11 + B05 = A05 + A10 + B06 = A06 + A09 + B07 = A07 + A08 + B08 = (A00 - A15) * 0.5024192929 + B09 = (A01 - A14) * 0.5224986076 + B10 = (A02 - A13) * 0.5669440627 + B11 = (A03 - A12) * 0.6468217969 + B12 = (A04 - A11) * 0.7881546021 + B13 = (A05 - A10) * 1.0606776476 + B14 = (A06 - A09) * 1.7224471569 + B15 = (A07 - A08) * 5.1011486053 + A00 = B00 + B07 + A01 = B01 + B06 + A02 = B02 + B05 + A03 = B03 + B04 + A04 = (B00 - B07) * 0.5097956061 + A05 = (B01 - B06) * 0.6013448834 + A06 = (B02 - B05) * 0.8999761939 + A07 = (B03 - B04) * 2.5629155636 + A08 = B08 + B15 + A09 = B09 + B14 + A10 = B10 + B13 + A11 = B11 + B12 + A12 = (B08 - B15) * 0.5097956061 + A13 = (B09 - B14) * 0.6013448834 + A14 = (B10 - B13) * 0.8999761939 + A15 = (B11 - B12) * 2.5629155636 + B00 = A00 + A03 + B01 = A01 + A02 + B02 = (A00 - A03) * 0.5411961079 + B03 = (A01 - A02) * 1.3065630198 + B04 = A04 + A07 + B05 = A05 + A06 + B06 = (A04 - A07) * 0.5411961079 + B07 = (A05 - A06) * 1.3065630198 + B08 = A08 + A11 + B09 = A09 + A10 + B10 = (A08 - A11) * 0.5411961079 + B11 = (A09 - A10) * 1.3065630198 + B12 = A12 + A15 + B13 = A13 + A14 + B14 = (A12 - A15) * 0.5411961079 + B15 = (A13 - A14) * 1.3065630198 + A00 = (B00 + B01) + A01 = (B00 - B01) * 0.7071067691 + A02 = (B02 + B03) + A03 = (B02 - B03) * 0.7071067691 + A04 = (B04 + B05) + A05 = (B04 - B05) * 0.7071067691 + A06 = (B06 + B07) + A07 = (B06 - B07) * 0.7071067691 + A08 = (B08 + B09) + A09 = (B08 - B09) * 0.7071067691 + A10 = (B10 + B11) + A11 = (B10 - B11) * 0.7071067691 + A12 = (B12 + B13) + A13 = (B12 - B13) * 0.7071067691 + A14 = (B14 + B15) + A15 = (B14 - B15) * 0.7071067691 + V[o + 15] = A15 + t = A07 + A15 + V[o + 13] = t + t += A11 + V[o + 11] = t + V[o + 5] = t + A05 + A13 + t = A03 + A11 + A15 + V[o + 9] = t + V[o + 7] = t + A13 + t = A01 + A09 + A13 + A15 + V[o + 1] = t + V[o + 33] = -t - A14 + t = A05 + A07 + A09 + A13 + A15 + V[o + 3] = t + V[o + 35] = -t - A06 - A14 + t = -(A10 + A11 + A13 + A14 + A15) + V[o + 37] = t - A05 - A06 - A07 + V[o + 39] = t - A02 - A03 + t += A13 - A12 + V[o + 41] = t - A02 - A03 + V[o + 43] = t - A04 - A06 - A07 + t = -(A08 + A12 + A14 + A15) + V[o + 47] = t - A00 + V[o + 45] = t - A04 - A06 - A07 + for i = 0, 15 do + V[o + 32 - i] = -V[o + i] + end + for i = 33, 47 do + V[o + 96 - i] = V[o + i] + end +end + +@native local function newV(Y: { number }, y: number, V: { number }, o: number) + newVEven(Y, y, V, o) + newVOdd(Y, y, V, o) +end +type State = { + version: number, + maxBand: number, + ms: boolean, + channels: number, + resL: { number }, + resR: { number }, + scfL: { number }, + scfR: { number }, + scfiL: { number }, + scfiR: { number }, + dscfL: { boolean }, + dscfR: { boolean }, + msf: { boolean }, + qL: { number }, + qR: { number }, + yL: { number }, + yR: { number }, + vL: { number }, + vR: { number }, + r1: number, + r2: number, + lastMaxBand: number, +} + +@native function Decode.state(version: number, maxBand: number, ms: boolean, channels: number): State + local st: State = { + version = version, + maxBand = maxBand, + ms = ms, + channels = channels, + resL = table.create(33, 0), + resR = table.create(33, 0), + scfL = table.create(99, 0), + scfR = table.create(99, 0), + scfiL = table.create(33, 0), + scfiR = table.create(33, 0), + dscfL = table.create(33, false), + dscfR = table.create(33, false), + msf = table.create(33, false), + qL = table.create(32 * 36, 0), + qR = table.create(32 * 36, 0), + yL = table.create(36 * 32, 0), + yR = table.create(36 * 32, 0), + vL = table.create(2304 + 960, 0), + vR = table.create(2304 + 960, 0), + r1 = 1, + r2 = 1, + lastMaxBand = 0, + } + return st +end + +-- libmpcdec assumes scf 0 at the stream start, 0x01010101 mid-SV7; the noise generator restarts, as in a fresh stream +@native function Decode.reset(st: State, scf: number) + for i = 1, 99 do + st.scfL[i] = scf + st.scfR[i] = scf + end + for i = 1, 33 do + st.resL[i], st.resR[i] = 0, 0 + st.dscfL[i], st.dscfR[i] = false, false + st.msf[i] = false + end + for i = 1, 2304 + 960 do + st.vL[i], st.vR[i] = 0, 0 + end + st.lastMaxBand = 0 + st.r1, st.r2 = 1, 1 +end + +@native local function noise(st: State, q: { number }, o: number) + local r1, r2 = st.r1, st.r2 + for k = 0, 35 do + local t1 = PARITY[band(r1, 0xF5) + 1] + local t2 = PARITY[band(rshift(r2, 25), 0x63) + 1] + r1 = bor(rshift(r1, 1), lshift(t1, 31)) + r2 = bor(band(lshift(r2, 1), 0xFFFFFFFF), t2) + local t = bxor(r1, r2) + q[o + k] = band(rshift(t, 24), 255) + band(rshift(t, 16), 255) + band(rshift(t, 8), 255) + band(t, 255) - 510 + end + st.r1, st.r2 = r1, r2 +end + +-- mpc_decoder_read_bitstream_sv7 +@native local function readSv7(st: State, limit: number): (boolean?, string?) + local resL, resR, msf = st.resL, st.resR, st.msf + local maxUsed = 0 + local ms = st.ms + resL[1] = bits(4) + resR[1] = bits(4) + if resL[1] ~= 0 or resR[1] ~= 0 then + if ms then + msf[1] = bits(1) == 1 + end + maxUsed = 1 + end + for n = 1, st.maxBand do + local idx = huff(HDR) + resL[n + 1] = if idx ~= 4 then resL[n] + idx else bits(4) + idx = huff(HDR) + resR[n + 1] = if idx ~= 4 then resR[n] + idx else bits(4) + local l, r = resL[n + 1], resR[n + 1] + if l < -1 or l > 17 or r < -1 or r > 17 then + return nil, "bad band resolution" + end + if l ~= 0 or r ~= 0 then + if ms then + msf[n + 1] = bits(1) == 1 + end + maxUsed = n + 1 + end + end + if resL[1] > 17 or resR[1] > 17 then + return nil, "bad band resolution" + end + -- SCFI + local scfiL, scfiR = st.scfiL, st.scfiR + for n = 1, maxUsed do + if resL[n] ~= 0 then + scfiL[n] = huff(SCFI7) + end + if resR[n] ~= 0 then + scfiR[n] = huff(SCFI7) + end + end + if P > limit then + return nil, "truncated frame" + end + -- SCF / DSCF + for n = 1, maxUsed do + for c = 1, 2 do + local res = if c == 1 then resL[n] else resR[n] + if res ~= 0 then + local scf = if c == 1 then st.scfL else st.scfR + local scfi = if c == 1 then scfiL[n] else scfiR[n] + local o = (n - 1) * 3 + local idx = huff(DSCF7) + local s0 = if idx ~= 8 then scf[o + 3] + idx else bits(6) + local s1, s2 + if scfi == 1 then + idx = huff(DSCF7) + s1 = if idx ~= 8 then s0 + idx else bits(6) + s2 = s1 + elseif scfi == 3 then + s1, s2 = s0, s0 + elseif scfi == 2 then + s1 = s0 + idx = huff(DSCF7) + s2 = if idx ~= 8 then s1 + idx else bits(6) + else + idx = huff(DSCF7) + s1 = if idx ~= 8 then s0 + idx else bits(6) + idx = huff(DSCF7) + s2 = if idx ~= 8 then s1 + idx else bits(6) + end + scf[o + 1] = if s0 > 1024 then 0x8080 else s0 + scf[o + 2] = if s1 > 1024 then 0x8080 else s1 + scf[o + 3] = if s2 > 1024 then 0x8080 else s2 + end + end + end + if P > limit then + return nil, "truncated frame" + end + -- samples + for n = 1, maxUsed do + for c = 1, 2 do + local res = if c == 1 then resL[n] else resR[n] + local q = if c == 1 then st.qL else st.qR + local o = (n - 1) * 36 + 1 + if res == -1 then + noise(st, q, o) + elseif res == 1 then + local tab = Q7[1][bits(1) + 1] + for k = 0, 35, 3 do + local idx = huff(tab) + q[o + k] = idx % 3 - 1 + q[o + k + 1] = (idx // 3) % 3 - 1 + q[o + k + 2] = idx // 9 - 1 + end + elseif res == 2 then + local tab = Q7[2][bits(1) + 1] + for k = 0, 35, 2 do + local idx = huff(tab) + q[o + k] = idx % 5 - 2 + q[o + k + 1] = idx // 5 - 2 + end + elseif res >= 3 and res <= 7 then + local tab = Q7[res][bits(1) + 1] + for k = 0, 35 do + q[o + k] = huff(tab) + end + elseif res >= 8 then + local nb, dc = RES_BIT[res], DC[res + 2] + for k = 0, 35 do + q[o + k] = bits(nb) - dc + end + end + if P > limit then + return nil, "truncated frame" + end + end + end + -- bands above maxUsed: silent + for n = maxUsed + 1, st.maxBand + 1 do + resL[n], resR[n] = 0, 0 + end + return true, nil +end + +@native local function readSv8(st: State, key: boolean, limit: number): (boolean?, string?) + local resL, resR, msf = st.resL, st.resR, st.msf + local maxBand = st.maxBand + local maxUsed + if key then + maxUsed = logDec(maxBand + 1) + else + maxUsed = st.lastMaxBand + huff(BANDS8) + if maxUsed > 32 then + maxUsed -= 33 + end + end + if maxUsed > maxBand + 1 then + return nil, "bad band count" + end + st.lastMaxBand = maxUsed + if maxUsed > 0 then + local l, r = huff(RES8[1]), huff(RES8[1]) + resL[maxUsed] = if l > 15 then l - 17 else l + resR[maxUsed] = if r > 15 then r - 17 else r + for n = maxUsed - 1, 1, -1 do + l = huff(RES8[if resL[n + 1] > 2 then 2 else 1]) + resL[n + 1] + resL[n] = if l > 15 then l - 17 else l + r = huff(RES8[if resR[n + 1] > 2 then 2 else 1]) + resR[n + 1] + resR[n] = if r > 15 then r - 17 else r + end + if st.ms then + local tot = 0 + for n = 1, maxUsed do + if resL[n] ~= 0 or resR[n] ~= 0 then + tot += 1 + end + end + local cnt = logDec(tot) + local tmp = 0 + if cnt ~= 0 and cnt ~= tot then + tmp = enumDec(math.min(cnt, tot - cnt), tot) + end + if cnt * 2 > tot then + tmp = bnot(tmp) + end + for n = maxUsed, 1, -1 do + if resL[n] ~= 0 or resR[n] ~= 0 then + msf[n] = band(tmp, 1) == 1 + tmp = rshift(tmp, 1) + end + end + end + end + for n = maxUsed + 1, maxBand + 1 do + resL[n], resR[n] = 0, 0 + end + -- SCFI + local dscfL, dscfR = st.dscfL, st.dscfR + if key then + for n = 1, 32 do + dscfL[n], dscfR[n] = true, true + end + end + local scfiL, scfiR = st.scfiL, st.scfiR + for n = 1, maxUsed do + local cnt = -1 + if resL[n] ~= 0 then + cnt += 1 + end + if resR[n] ~= 0 then + cnt += 1 + end + if cnt >= 0 then + local tmp = huff(SCFI8[cnt + 1]) + if resL[n] ~= 0 then + scfiL[n] = rshift(tmp, 2 * cnt) + end + if resR[n] ~= 0 then + scfiR[n] = band(tmp, 3) + end + end + end + if P > limit then + return nil, "truncated frame" + end + -- SCF / DSCF + for n = 1, maxUsed do + for c = 1, 2 do + local res = if c == 1 then resL[n] else resR[n] + if res ~= 0 then + local scf = if c == 1 then st.scfL else st.scfR + local scfi = if c == 1 then scfiL[n] else scfiR[n] + local dscf = if c == 1 then dscfL else dscfR + local o = (n - 1) * 3 + if dscf[n] then + scf[o + 1] = bits(7) - 6 + dscf[n] = false + else + local tmp = huff(DSCF8[2]) + if tmp == 64 then + tmp += bits(6) + end + scf[o + 1] = band(scf[o + 3] - 25 + tmp, 127) - 6 + end + for m = 0, 1 do + if band(lshift(scfi, m), 2) == 0 then + local tmp = huff(DSCF8[1]) + if tmp == 31 then + tmp = 64 + bits(6) + end + scf[o + m + 2] = band(scf[o + m + 1] - 25 + tmp, 127) - 6 + else + scf[o + m + 2] = scf[o + m + 1] + end + end + end + end + end + if P > limit then + return nil, "truncated frame" + end + -- samples + for n = 1, maxUsed do + for c = 1, 2 do + local res = if c == 1 then resL[n] else resR[n] + local q = if c == 1 then st.qL else st.qR + local o = (n - 1) * 36 + 1 + if res == 2 then + local tabs = Q8[2] + local thres = 3 + local idx = 6 + for k = 0, 35, 3 do + local tmp = huff(tabs[if idx > thres then 2 else 1]) + local a, b, cc = tmp % 5 - 2, (tmp // 5) % 5 - 2, tmp // 25 - 2 + q[o + k], q[o + k + 1], q[o + k + 2] = a, b, cc + idx = rshift(idx, 1) + abs(a) + abs(b) + abs(cc) + end + elseif res == 1 then + local k = 0 + while k < 36 do + local kmax = k + 18 + local cnt = huff(Q1_8) + local idx = 0 + if cnt > 0 and cnt < 18 then + idx = enumDec(if cnt <= 9 then cnt else 18 - cnt, 18) + end + if cnt > 9 then + idx = bnot(idx) + end + while k < kmax do + q[o + k] = 0 + if band(idx, 0x20000) ~= 0 then + q[o + k] = bits(1) * 2 - 1 + end + idx = lshift(idx, 1) + k += 1 + end + end + elseif res == -1 then + noise(st, q, o) + elseif res == 3 or res == 4 then + local tab = Q34[res - 2] + for k = 0, 35, 2 do + local s = band(huff(tab), 255) + local s1, s2 = band(s, 15), rshift(s, 4) + q[o + k] = if s1 >= 8 then s1 - 16 else s1 + q[o + k + 1] = if s2 >= 8 then s2 - 16 else s2 + end + elseif res >= 5 and res <= 8 then + local tabs = Q8[res] + local thres = THRES[res] + local idx = 2 * thres + for k = 0, 35 do + local v = huff(tabs[if idx > thres then 2 else 1]) + q[o + k] = v + idx = rshift(idx, 1) + abs(v) + end + elseif res >= 9 then + local sh = res - 9 + local dc = DC[res + 2] + for k = 0, 35 do + local v = band(huff(Q9UP), 255) + if sh > 0 then + v = v * 2 ^ sh + bits(sh) + end + q[o + k] = v - dc + end + elseif res < -1 then + return nil, "bad band resolution" + end + if P > limit then + return nil, "truncated frame" + end + end + end + return true, nil +end + +@native local function requant(st: State) + local resL, resR, msf = st.resL, st.resR, st.msf + local scfL, scfR, qL, qR, yL, yR = st.scfL, st.scfR, st.qL, st.qR, st.yL, st.yR + for b = 1, st.maxBand + 1 do + local rl, rr = resL[b], resR[b] + local ccl, ccr = CC[rl + 2] or 0, CC[rr + 2] or 0 + local ms = msf[b] + local o = (b - 1) * 36 + 1 + for part = 0, 2 do + local fl = if rl ~= 0 then f32(ccl * SCF[band(scfL[(b - 1) * 3 + part + 1], 255) + 1]) else 0 + local fr = if rr ~= 0 then f32(ccr * SCF[band(scfR[(b - 1) * 3 + part + 1], 255) + 1]) else 0 + local y = part * 12 * 32 + b + local qo = o + part * 12 + if ms then + for k = 0, 11 do + local l, r = fl * qL[qo + k], fr * qR[qo + k] + yL[y], yR[y] = l + r, l - r + y += 32 + end + else + for k = 0, 11 do + yL[y], yR[y] = fl * qL[qo + k], fr * qR[qo + k] + y += 32 + end + end + end + end +end + + +-- mpc_synthese_filter_float +@native local function synth(V: { number }, Y: { number }, out: { number }, base: number, step: number) + table.move(V, 1, 960, 2305) + local o = 2304 + 1 + local dw = DW + local p = base + for n = 0, 35 do + o -= 64 + newV(Y, n * 32 + 1, V, o) + for k = 0, 31 do + local v = o + k + local d = k * 16 + 1 + out[p] = V[v] * dw[d] + V[v + 96] * dw[d + 1] + V[v + 128] * dw[d + 2] + V[v + 224] * dw[d + 3] + + V[v + 256] * dw[d + 4] + V[v + 352] * dw[d + 5] + V[v + 384] * dw[d + 6] + V[v + 480] * dw[d + 7] + + V[v + 512] * dw[d + 8] + V[v + 608] * dw[d + 9] + V[v + 640] * dw[d + 10] + V[v + 736] * dw[d + 11] + + V[v + 768] * dw[d + 12] + V[v + 864] * dw[d + 13] + V[v + 896] * dw[d + 14] + V[v + 992] * dw[d + 15] + p += step + end + end +end + +@native function Decode.frame(st: State, buf: buffer, bitPos: number, limitBits: number, key: boolean, out: { number }, base: number): (number?, string?) + if bitPos >= 0 then + if rshift(limitBits, 3) + Decode.PAD > buffer.len(buf) or bitPos > limitBits then + return nil, "truncated frame" + end + B, P = buf, bitPos + local ok, err + if st.version == 8 then + ok, err = readSv8(st, key, limitBits) + else + ok, err = readSv7(st, limitBits) + end + B = buffer.create(0) + if not ok then + return nil, err + end + else + for b = 1, st.maxBand + 1 do + st.resL[b], st.resR[b] = 0, 0 + end + end + local pos = P + requant(st) + local ch = st.channels + synth(st.vL, st.yL, out, base, ch) + if ch > 1 then + synth(st.vR, st.yR, out, base + 1, ch) + end + return if bitPos >= 0 then pos else bitPos, nil +end + +@native function Decode.bitsAt(buf: buffer, bitPos: number, n: number): number + local w = bswap(readu32(buf, rshift(bitPos, 3))) + return extract(w, 32 - band(bitPos, 7) - n, n) +end + +return Decode +end +__FILES["codecs/audio/Musepack/Tables"] = function() + +-- codecs/audio/Musepack/Tables: the Musepack SV7 / SV8 Huffman tables, synthesis window and requantisation constants. +-- Ported from libmpcdec (musepack_src_r475: huffman.c, synth_filter.c, requant.c, mpc_bits_reader.c; BSD-3-Clause, +-- (c) The Musepack Development Team, licenses/libmpcdec-BSD.txt). Huffman tables: flat { code, length, value, ... } +-- sorted by descending left-aligned 16-bit code; canonical (SV8) tables map value - (code >> (16 - length)). +local T = {} + +T.HuffHdr = { + 32768, 1, 0, 24576, 3, 1, 24064, 7, -4, 23936, 9, 3, 23808, 9, 4, 23552, 8, -5, 22528, 6, 2, 20480, 5, -3, 16384, 4, -2, 0, 2, -1, +} +T.HuffSCFI = { + 32768, 1, 1, 24576, 3, 2, 16384, 3, 0, 0, 2, 3, +} +T.HuffDSCF = { + 63488, 5, 5, 61440, 5, -4, 57344, 4, 3, 53248, 4, -3, 49152, 4, 8, 40960, 3, 1, 36864, 4, 0, 34816, 5, -5, 33792, 6, 7, 32768, 6, -7, + 24576, 3, -1, 16384, 3, 2, 12288, 4, 4, 10240, 5, 6, 8192, 5, -6, 0, 3, -2, +} +T.HuffQ1_0 = { + 57344, 3, 13, 56320, 6, 26, 55296, 6, 0, 54272, 6, 20, 53248, 6, 6, 49152, 4, 14, 45056, 4, 12, 40960, 4, 4, 36864, 4, 22, 35840, 6, 8, + 34816, 6, 18, 33792, 6, 24, 32768, 6, 2, 28672, 4, 16, 24576, 4, 10, 22528, 5, 17, 20480, 5, 9, 18432, 5, 1, 16384, 5, 25, 14336, 5, 5, + 12288, 5, 21, 10240, 5, 3, 8192, 5, 11, 6144, 5, 15, 4096, 5, 23, 2048, 5, 19, 0, 5, 7, +} +T.HuffQ1_1 = { + 32768, 1, 13, 32256, 7, 15, 31744, 7, 1, 31232, 7, 11, 30720, 7, 7, 30208, 7, 17, 29696, 7, 25, 29184, 7, 19, 29056, 9, 8, 28928, 9, 18, + 28800, 9, 2, 28672, 9, 24, 28160, 7, 3, 27648, 7, 23, 27136, 7, 21, 26624, 7, 5, 26368, 8, 0, 26112, 8, 26, 25856, 8, 6, 25600, 8, 20, + 24576, 6, 9, 20480, 4, 14, 16384, 4, 12, 12288, 4, 4, 8192, 4, 22, 4096, 4, 16, 0, 4, 10, +} +T.HuffQ2_0 = { + 61440, 4, 13, 57344, 4, 17, 53248, 4, 7, 49152, 4, 11, 48128, 6, 1, 47104, 6, 23, 46592, 7, 4, 46080, 7, 20, 45568, 7, 0, 45056, 7, 24, + 43008, 5, 22, 40960, 5, 10, 32768, 3, 12, 30720, 5, 2, 28672, 5, 14, 24576, 4, 6, 20480, 4, 18, 16384, 4, 8, 12288, 4, 16, 10240, 5, 9, + 8192, 5, 5, 6144, 5, 15, 4096, 5, 21, 2048, 5, 19, 0, 5, 3, +} +T.HuffQ2_1 = { + 63488, 5, 18, 61440, 5, 6, 59392, 5, 8, 59136, 8, 3, 59072, 10, 24, 59008, 10, 4, 58944, 10, 0, 58880, 10, 20, 58368, 7, 23, 57856, 7, 1, + 57344, 7, 19, 55296, 5, 16, 54784, 7, 15, 54272, 7, 21, 53760, 7, 9, 53248, 7, 5, 52224, 6, 2, 51200, 6, 10, 50176, 6, 14, 49152, 6, 22, + 32768, 2, 12, 24576, 3, 13, 16384, 3, 17, 8192, 3, 11, 0, 3, 7, +} +T.HuffQ3_0 = { + 57344, 3, 1, 53248, 4, 3, 49152, 4, -3, 40960, 3, 2, 32768, 3, -2, 16384, 2, 0, 0, 2, -1, +} +T.HuffQ3_1 = { + 49152, 2, 0, 32768, 2, -1, 16384, 2, 1, 12288, 4, -2, 10240, 5, 3, 8192, 5, -3, 0, 3, 2, +} +T.HuffQ4_0 = { + 57344, 3, 0, 49152, 3, -1, 40960, 3, 1, 32768, 3, -2, 24576, 3, 2, 20480, 4, -4, 16384, 4, 4, 8192, 3, 3, 0, 3, -3, +} +T.HuffQ4_1 = { + 57344, 3, 1, 53248, 4, 2, 49152, 4, -3, 32768, 2, 0, 24576, 3, -2, 20480, 4, 3, 18432, 5, -4, 16384, 5, 4, 0, 2, -1, +} +T.HuffQ5_0 = { + 61440, 4, 2, 59392, 5, 5, 58368, 6, -7, 57344, 6, 7, 53248, 4, -3, 49152, 4, 3, 47104, 5, -6, 45056, 5, 6, 40960, 4, -4, 36864, 4, 4, + 32768, 4, -5, 24576, 3, 0, 16384, 3, -1, 8192, 3, 1, 0, 3, -2, +} +T.HuffQ5_1 = { + 61440, 4, 3, 59392, 5, 4, 58880, 7, 6, 58624, 8, -7, 58368, 8, 7, 57344, 6, -6, 49152, 3, 0, 40960, 3, -1, 32768, 3, 1, 24576, 3, -2, + 16384, 3, 2, 14336, 5, -5, 12288, 5, 5, 8192, 4, -4, 0, 3, -3, +} +T.HuffQ6_0 = { + 63488, 5, 3, 61440, 5, -4, 60416, 6, -11, 59392, 6, 12, 57344, 5, 4, 55296, 5, 6, 53248, 5, -5, 51200, 5, 5, 49152, 5, 7, 47104, 5, -7, + 46080, 6, -12, 45056, 6, -13, 43008, 5, -6, 40960, 5, 8, 38912, 5, -8, 36864, 5, 9, 34816, 5, -9, 33792, 6, 13, 33280, 7, -15, 32768, 7, 15, + 28672, 4, 0, 26624, 5, -10, 24576, 5, 10, 20480, 4, -1, 16384, 4, 2, 12288, 4, 1, 8192, 4, -2, 7168, 6, 14, 6144, 6, -14, 4096, 5, 11, + 0, 4, -3, +} +T.HuffQ6_1 = { + 63488, 5, -6, 61440, 5, 6, 57344, 4, 1, 53248, 4, -1, 52736, 7, 10, 52224, 7, -10, 51968, 8, -11, 51840, 9, -12, 51808, 11, 13, 51800, 13, 15, + 51792, 13, -14, 51784, 13, 14, 51776, 13, -15, 51712, 10, -13, 51456, 8, 11, 51200, 8, 12, 50176, 6, -9, 49152, 6, 9, 45056, 4, -2, 40960, 4, 2, + 36864, 4, 3, 32768, 4, -3, 30720, 5, -7, 28672, 5, 7, 24576, 4, -4, 20480, 4, 4, 18432, 5, -8, 16384, 5, 8, 12288, 4, 5, 8192, 4, -5, + 0, 3, 0, +} +T.HuffQ7_0 = { + 64512, 6, 7, 63488, 6, 8, 62464, 6, 9, 61440, 6, -8, 60416, 6, 11, 59904, 7, 21, 59648, 8, -28, 59392, 8, 28, 58368, 6, -9, 57856, 7, -22, + 57344, 7, -21, 56320, 6, -10, 55296, 6, -11, 54272, 6, 10, 53248, 6, 12, 52224, 6, -13, 51712, 7, 22, 51200, 7, 23, 50176, 6, -12, 49152, 6, 13, + 48128, 6, 14, 47104, 6, -14, 46592, 7, -23, 46336, 8, -29, 46080, 8, 29, 45056, 6, -15, 44032, 6, 15, 43008, 6, 16, 41984, 6, -16, 41472, 7, -24, + 40960, 7, 24, 39936, 6, 17, 39424, 7, -25, 39168, 8, -30, 38912, 8, 30, 37888, 6, -17, 36864, 6, 18, 35840, 6, -18, 35328, 7, 25, 34816, 7, 26, + 33792, 6, 19, 33280, 7, -26, 32768, 7, -27, 30720, 5, 2, 29696, 6, -19, 28672, 6, 20, 26624, 5, -1, 26368, 8, -31, 26112, 8, 31, 25600, 7, 27, + 24576, 6, -20, 22528, 5, 1, 20480, 5, -5, 18432, 5, -3, 16384, 5, 3, 14336, 5, 0, 12288, 5, -2, 10240, 5, -4, 8192, 5, 4, 6144, 5, 5, + 4096, 5, -6, 2048, 5, 6, 0, 5, -7, +} +T.HuffQ7_1 = { + 63488, 5, -1, 61440, 5, 2, 59392, 5, -2, 57344, 5, 3, 57088, 8, -20, 57024, 10, 24, 57020, 14, 28, 57016, 14, -28, 57012, 14, -30, 57008, 14, 30, + 56992, 12, -27, 56988, 14, 29, 56984, 14, -29, 56980, 14, 31, 56976, 14, -31, 56960, 12, 27, 56832, 9, -22, 56320, 7, -17, 55296, 6, -11, 53248, 5, -3, + 51200, 5, 4, 49152, 5, -4, 48640, 7, 17, 48384, 8, 20, 48256, 9, 22, 48192, 10, -25, 48128, 10, -26, 47104, 6, 12, 45056, 5, 5, 43008, 5, -5, + 40960, 5, 6, 38912, 5, -6, 37888, 6, -12, 37376, 7, -18, 36864, 7, 18, 35840, 6, 13, 34816, 6, -13, 32768, 5, -7, 31744, 6, 14, 31488, 8, 21, + 31232, 8, -21, 30720, 7, -19, 28672, 5, 7, 26624, 5, 8, 25600, 6, -14, 24576, 6, -15, 22528, 5, -8, 21504, 6, 15, 20992, 7, 19, 20928, 10, 25, + 20864, 10, 26, 20736, 9, -23, 20608, 9, 23, 20480, 9, -24, 18432, 5, -9, 16384, 5, 9, 15360, 6, 16, 14336, 6, -16, 12288, 5, 10, 8192, 4, 0, + 6144, 5, -10, 4096, 5, 11, 0, 4, 1, +} +T.H_SCFI_1 = { + 32768, 1, 1, 16384, 2, 2, 0, 3, 3, +} +T.H_SCFI_2 = { + 32768, 2, 3, 16384, 3, 5, 6144, 5, 11, 1024, 6, 14, 0, 7, 15, +} +T.H_DSCF_1 = { + 40960, 3, 7, 16384, 4, 12, 10240, 5, 16, 6144, 6, 21, 3584, 7, 27, 1792, 8, 34, 896, 9, 41, 320, 10, 48, 128, 11, 53, 48, 12, 57, + 24, 13, 60, 0, 14, 63, +} +T.H_DSCF_2 = { + 24576, 3, 7, 12288, 4, 10, 6144, 5, 13, 4096, 6, 16, 2560, 7, 20, 1536, 8, 25, 896, 9, 31, 448, 10, 38, 224, 11, 45, 80, 12, 52, + 32, 13, 57, 12, 14, 61, 0, 15, 64, +} +T.H_Bands = { + 32768, 1, 1, 16384, 2, 2, 8192, 3, 3, 4096, 5, 6, 2048, 6, 8, 1536, 7, 10, 768, 8, 13, 512, 9, 16, 320, 10, 20, 192, 11, 25, + 16, 12, 31, 0, 13, 32, +} +T.H_Res_1 = { + 32768, 1, 1, 16384, 2, 2, 8192, 3, 3, 4096, 4, 4, 2048, 5, 5, 1024, 6, 6, 512, 7, 7, 256, 8, 8, 128, 9, 9, 64, 10, 10, + 32, 11, 11, 16, 12, 12, 8, 13, 13, 4, 14, 14, 2, 15, 15, 0, 16, 16, +} +T.H_Res_2 = { + 16384, 2, 3, 8192, 3, 4, 4096, 4, 5, 2048, 5, 6, 1024, 6, 7, 512, 7, 8, 256, 8, 9, 128, 9, 10, 64, 10, 11, 32, 11, 12, + 16, 12, 13, 0, 14, 16, +} +T.H_Q1 = { + 24576, 3, 7, 4096, 4, 10, 2048, 5, 11, 1024, 6, 12, 512, 7, 13, 256, 8, 14, 128, 9, 15, 64, 10, 16, 32, 11, 17, 0, 12, 18, +} +T.H_Q2_1 = { + 57344, 3, 7, 32768, 4, 14, 15360, 6, 38, 10752, 7, 53, 4608, 8, 74, 1536, 9, 92, 960, 10, 104, 96, 11, 119, 32, 12, 122, 0, 13, 124, +} +T.H_Q2_2 = { + 61440, 4, 15, 28672, 5, 30, 18432, 6, 44, 15360, 7, 62, 3072, 8, 92, 1920, 9, 104, 192, 10, 119, 64, 11, 122, 0, 12, 124, +} +T.H_Q3 = { + 57344, 3, 7, 32768, 4, 14, 20480, 5, 22, 9216, 6, 32, 2560, 7, 41, 512, 8, 46, 0, 9, 48, +} +T.H_Q4 = { + 61440, 4, 15, 36864, 5, 30, 13312, 6, 48, 6144, 7, 61, 1280, 8, 73, 256, 9, 78, 0, 10, 80, 0, 0, 90, +} +T.H_Q5_1 = { + 49152, 2, 3, 16384, 3, 6, 8192, 4, 8, 4096, 5, 10, 2048, 6, 12, 0, 7, 14, +} +T.H_Q5_2 = { + 24576, 3, 7, 8192, 4, 10, 4096, 5, 12, 0, 6, 14, +} +T.H_Q6_1 = { + 49152, 2, 3, 32768, 3, 6, 16384, 4, 10, 10240, 5, 14, 3072, 6, 19, 2048, 7, 22, 1024, 8, 26, 0, 9, 30, +} +T.H_Q6_2 = { + 20480, 4, 15, 8192, 5, 20, 4096, 6, 24, 1024, 7, 28, 0, 8, 30, +} +T.H_Q7_1 = { + 49152, 2, 3, 32768, 3, 6, 24576, 4, 10, 16384, 5, 16, 10240, 6, 24, 5120, 7, 34, 2560, 8, 44, 1024, 9, 54, 0, 10, 62, +} +T.H_Q7_2 = { + 24576, 5, 31, 9216, 6, 43, 4096, 7, 52, 512, 8, 60, 0, 9, 62, +} +T.H_Q8_1 = { + 49152, 2, 3, 32768, 3, 6, 28672, 4, 10, 22528, 5, 17, 14336, 6, 28, 10240, 7, 42, 6400, 8, 62, 3328, 9, 87, 640, 10, 113, 96, 11, 123, + 0, 12, 126, +} +T.H_Q8_2 = { + 38912, 6, 63, 10752, 7, 101, 1024, 8, 122, 0, 9, 126, +} +T.H_Q9up = { + 63488, 6, 63, 44032, 7, 125, 9728, 8, -45, 640, 9, -7, 64, 10, -2, 0, 11, -1, +} +T.S_SCFI_1 = { + 2, 3, 1, 0, +} +T.S_SCFI_2 = { + 15, 10, 14, 11, 13, 9, 7, 6, 5, 12, 8, 3, 2, 0, 4, 1, +} +T.S_DSCF_1 = { + 35, 34, 33, 36, 32, 30, 29, 27, 26, 37, 28, 25, 39, 38, 24, 23, 40, 22, 21, 20, 19, 43, 42, 41, 18, 17, 16, 15, 46, 45, 44, 14, + 13, 12, 11, 49, 48, 47, 31, 10, 9, 8, 7, 6, 52, 51, 50, 5, 4, 3, 54, 53, 2, 1, 0, 57, 56, 55, 63, 62, 61, 60, 59, 58, +} +T.S_DSCF_2 = { + 33, 32, 31, 30, 29, 34, 28, 27, 36, 35, 26, 37, 25, 38, 24, 23, 40, 39, 22, 21, 42, 41, 20, 19, 18, 45, 44, 43, 17, 16, 15, 14, + 48, 47, 46, 13, 12, 11, 10, 64, 52, 51, 50, 49, 9, 8, 7, 6, 55, 54, 53, 5, 4, 3, 58, 57, 56, 2, 1, 63, 62, 61, 60, 59, + 0, +} +T.S_Bands = { + 0, 32, 1, 31, 2, 30, 3, 4, 29, 6, 5, 28, 7, 27, 26, 8, 25, 24, 23, 9, 22, 21, 20, 18, 17, 16, 15, 14, 12, 11, 10, 19, + 13, +} +T.S_Res_1 = { + 0, 1, 16, 2, 3, 4, 5, 15, 6, 7, 8, 9, 10, 11, 12, 14, 13, +} +T.S_Res_2 = { + 16, 1, 0, 2, 15, 3, 14, 4, 5, 13, 6, 12, 7, 11, 10, 9, 8, +} +T.S_Q1 = { + 7, 6, 5, 4, 3, 10, 9, 8, 2, 1, 11, 0, 12, 13, 14, 15, 16, 18, 17, +} +T.S_Q2_1 = { + 62, 87, 67, 63, 61, 57, 37, 93, 92, 88, 86, 83, 82, 81, 68, 66, 58, 56, 42, 41, 38, 36, 32, 31, 112, 91, 72, 64, 60, 52, 43, 33, + 12, 117, 113, 111, 107, 97, 89, 85, 77, 73, 71, 69, 65, 59, 55, 53, 51, 47, 39, 35, 27, 17, 13, 11, 7, 118, 116, 108, 106, 98, 96, 94, + 90, 84, 80, 78, 76, 48, 46, 44, 40, 34, 30, 28, 26, 18, 16, 8, 6, 122, 110, 102, 74, 70, 54, 50, 22, 2, 123, 121, 119, 115, 114, 109, + 105, 103, 101, 99, 95, 79, 75, 49, 45, 29, 25, 23, 21, 19, 15, 14, 10, 9, 5, 3, 1, 124, 104, 20, 0, 120, 100, 24, 4, +} +T.S_Q2_2 = { + 62, 92, 87, 86, 82, 68, 67, 66, 63, 61, 58, 57, 56, 42, 38, 37, 32, 93, 91, 88, 83, 81, 43, 41, 36, 33, 31, 112, 72, 64, 60, 52, + 12, 118, 117, 116, 113, 111, 108, 107, 106, 98, 97, 96, 94, 90, 89, 85, 84, 80, 78, 77, 76, 73, 71, 69, 65, 59, 55, 53, 51, 48, 47, 46, + 44, 40, 39, 35, 34, 30, 28, 27, 26, 18, 17, 16, 13, 11, 8, 7, 6, 122, 110, 74, 70, 54, 50, 22, 14, 2, 123, 121, 119, 115, 114, 109, + 105, 103, 102, 101, 99, 95, 79, 75, 49, 45, 29, 25, 23, 21, 19, 15, 10, 9, 5, 3, 1, 124, 104, 20, 0, 120, 100, 24, 4, +} +T.S_Q3 = { + 0, 17, 16, 1, 15, -16, -1, 32, 31, 2, 14, -15, -32, 34, 33, 47, 46, 18, 30, -14, -2, -31, -17, -18, 49, 48, 63, 19, 29, 3, 13, -13, + -3, -30, -47, -48, -33, 50, 62, 35, 45, -29, -19, -46, -34, 51, 61, -45, -35, +} +T.S_Q4 = { + 0, 32, 17, 16, 31, 2, 1, 15, 14, -15, -16, -1, -32, 49, 48, 34, 33, 47, 46, 19, 18, 30, 29, 3, 13, -13, -14, -2, -3, -30, -31, -17, + -18, -47, -48, -33, 64, 50, 63, 62, 35, 45, 4, 12, -29, -19, -46, -34, -64, -49, 66, 65, 79, 78, 51, 61, 36, 44, 20, 28, -12, -4, -28, -20, + -45, -35, -62, -63, -50, 67, 77, 52, 60, -44, -36, -61, -51, 68, 76, -60, -52, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, +} +T.S_Q5_1 = { + 0, 2, 1, -1, -2, 3, -3, 4, -4, 5, -5, 7, 6, -6, -7, +} +T.S_Q5_2 = { + 2, 1, 0, -1, -2, 4, 3, -3, -4, 5, -5, 7, 6, -6, -7, +} +T.S_Q6_1 = { + 0, 1, -1, 3, 2, -2, -3, 4, -4, -5, 8, 7, 6, 5, -6, -7, -8, 9, -9, 11, 10, -10, -11, 15, 14, 13, 12, -12, -13, -14, -15, +} +T.S_Q6_2 = { + 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, 8, 7, 6, -6, -7, -8, 10, 9, -9, -10, 13, 12, 11, -11, -12, -13, 15, 14, -14, -15, +} +T.S_Q7_1 = { + 0, 1, -1, 2, -2, 4, 3, -3, -4, 7, 6, 5, -5, -6, -7, 13, 11, 10, 9, 8, -8, -9, -10, -11, -12, 17, 16, 15, 14, 12, -13, -14, + -15, -16, -17, 28, 27, 21, 20, 19, 18, -18, -19, -20, -21, -27, -28, 31, 30, 29, 26, 25, 24, 23, 22, -22, -23, -24, -25, -26, -29, -30, -31, +} +T.S_Q7_2 = { + 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, -6, -7, -8, -9, 17, 16, 15, 14, 13, 12, 11, -10, -11, -12, -13, -14, + -15, -16, -17, 22, 21, 20, 19, 18, -18, -19, -20, -21, -22, 29, 28, 27, 26, 25, 24, 23, -23, -24, -25, -26, -27, -28, -29, 31, 30, -30, -31, +} +T.S_Q8_1 = { + 0, 1, -1, -2, 3, 2, -3, 7, 6, 5, 4, -4, -5, -6, -7, 11, 10, 9, 8, -8, -9, -10, -11, 19, 18, 17, 16, 15, 14, 13, 12, -12, + -13, -14, -15, -16, -17, -19, 56, 55, 31, 28, 27, 26, 25, 24, 23, 22, 21, 20, -18, -20, -21, -22, -23, -24, -25, -26, -27, -33, -54, -56, 63, 62, + 61, 60, 59, 58, 57, 54, 53, 43, 40, 39, 38, 37, 36, 35, 34, 33, 32, 30, 29, -28, -29, -30, -31, -32, -34, -35, -36, -37, -38, -39, -40, -41, + -43, -53, -55, -57, -58, -59, -60, -61, 49, 47, 46, 45, 44, 42, 41, -42, -44, -45, -46, -47, -48, -49, -50, -62, -63, 52, 51, 50, 48, -51, -52, +} +T.S_Q8_2 = { + 13, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13, 39, 38, 37, 36, 35, 34, + 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 12, -14, -15, -16, -17, -18, -19, -20, -21, -22, -23, -24, + -25, -26, -27, -28, -29, -30, -31, -32, -33, -34, -35, -36, -37, -38, -39, -40, -41, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, + 44, 43, 42, 41, 40, -42, -43, -44, -45, -46, -47, -48, -49, -50, -51, -52, -53, -54, -55, -56, -57, -58, -59, 63, 62, 61, 60, -60, -61, -62, -63, +} +T.S_Q9up = { + -128, 127, -108, -110, -111, -112, -113, -114, -115, -116, -117, -118, -119, -120, -121, -122, -123, -124, -125, -126, -127, 126, 125, 124, 123, 122, 121, 120, 119, 118, 117, 116, + 115, 114, 113, 112, 111, 110, 109, 108, -44, -45, -46, -47, -48, -49, -50, -51, -52, -53, -54, -55, -56, -57, -58, -59, -60, -61, -62, -63, -64, -65, -66, -67, + -68, -69, -70, -71, -72, -73, -74, -75, -76, -77, -78, -79, -80, -81, -82, -83, -84, -85, -86, -87, -88, -89, -90, -91, -92, -93, -94, -95, -96, -97, -98, -99, + -100, -101, -102, -103, -104, -105, -106, -107, -109, 107, 106, 105, 104, 103, 102, 101, 100, 99, 98, 97, 96, 95, 94, 93, 92, 91, 90, 89, 88, 87, 86, 85, + 84, 83, 82, 81, 80, 79, 78, 77, 76, 75, 74, 73, 72, 71, 70, 69, 68, 67, 66, 65, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, + 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 40, 20, 19, -7, -8, -9, -10, -11, -12, -13, -14, -15, -16, -17, -18, -19, -20, -21, -22, -23, -24, + -25, -26, -27, -28, -29, -30, -31, -32, -33, -34, -35, -36, -37, -38, -39, -40, -41, -42, -43, 41, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, + 27, 26, 25, 24, 23, 22, 21, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, -3, -4, -5, -6, 4, 3, 2, 1, 0, -1, -2, +} + +-- Di_opt[32][16] (times 65536) +T.DI = { + 0, -29, 213, -459, 2037, -5153, 6574, -37489, 75038, 37489, 6574, 5153, 2037, 459, 213, 29, + -1, -31, 218, -519, 2000, -5517, 5959, -39336, 74992, 35640, 7134, 4788, 2063, 401, 208, 26, + -1, -35, 222, -581, 1952, -5879, 5288, -41176, 74856, 33791, 7640, 4425, 2080, 347, 202, 24, + -1, -38, 225, -645, 1893, -6237, 4561, -43006, 74630, 31947, 8092, 4063, 2087, 294, 196, 21, + -1, -41, 227, -711, 1822, -6589, 3776, -44821, 74313, 30112, 8492, 3705, 2085, 244, 190, 19, + -1, -45, 228, -779, 1739, -6935, 2935, -46617, 73908, 28289, 8840, 3351, 2075, 197, 183, 17, + -1, -49, 228, -848, 1644, -7271, 2037, -48390, 73415, 26482, 9139, 3004, 2057, 153, 176, 16, + -2, -53, 227, -919, 1535, -7597, 1082, -50137, 72835, 24694, 9389, 2663, 2032, 111, 169, 14, + -2, -58, 224, -991, 1414, -7910, 70, -51853, 72169, 22929, 9592, 2330, 2001, 72, 161, 13, + -2, -63, 221, -1064, 1280, -8209, -998, -53534, 71420, 21189, 9750, 2006, 1962, 36, 154, 11, + -2, -68, 215, -1137, 1131, -8491, -2122, -55178, 70590, 19478, 9863, 1692, 1919, 2, 147, 10, + -3, -73, 208, -1210, 970, -8755, -3300, -56778, 69679, 17799, 9935, 1388, 1870, -29, 139, 9, + -3, -79, 200, -1283, 794, -8998, -4533, -58333, 68692, 16155, 9966, 1095, 1817, -57, 132, 8, + -4, -85, 189, -1356, 605, -9219, -5818, -59838, 67629, 14548, 9959, 814, 1759, -83, 125, 7, + -4, -91, 177, -1428, 402, -9416, -7154, -61289, 66494, 12980, 9916, 545, 1698, -106, 117, 7, + -5, -97, 163, -1498, 185, -9585, -8540, -62684, 65290, 11455, 9838, 288, 1634, -127, 111, 6, + -5, -104, 146, -1567, -45, -9727, -9975, -64019, 64019, 9975, 9727, 45, 1567, -146, 104, 5, + -6, -111, 127, -1634, -288, -9838, -11455, -65290, 62684, 8540, 9585, -185, 1498, -163, 97, 5, + -7, -117, 106, -1698, -545, -9916, -12980, -66494, 61289, 7154, 9416, -402, 1428, -177, 91, 4, + -7, -125, 83, -1759, -814, -9959, -14548, -67629, 59838, 5818, 9219, -605, 1356, -189, 85, 4, + -8, -132, 57, -1817, -1095, -9966, -16155, -68692, 58333, 4533, 8998, -794, 1283, -200, 79, 3, + -9, -139, 29, -1870, -1388, -9935, -17799, -69679, 56778, 3300, 8755, -970, 1210, -208, 73, 3, + -10, -147, -2, -1919, -1692, -9863, -19478, -70590, 55178, 2122, 8491, -1131, 1137, -215, 68, 2, + -11, -154, -36, -1962, -2006, -9750, -21189, -71420, 53534, 998, 8209, -1280, 1064, -221, 63, 2, + -13, -161, -72, -2001, -2330, -9592, -22929, -72169, 51853, -70, 7910, -1414, 991, -224, 58, 2, + -14, -169, -111, -2032, -2663, -9389, -24694, -72835, 50137, -1082, 7597, -1535, 919, -227, 53, 2, + -16, -176, -153, -2057, -3004, -9139, -26482, -73415, 48390, -2037, 7271, -1644, 848, -228, 49, 1, + -17, -183, -197, -2075, -3351, -8840, -28289, -73908, 46617, -2935, 6935, -1739, 779, -228, 45, 1, + -19, -190, -244, -2085, -3705, -8492, -30112, -74313, 44821, -3776, 6589, -1822, 711, -227, 41, 1, + -21, -196, -294, -2087, -4063, -8092, -31947, -74630, 43006, -4561, 6237, -1893, 645, -225, 38, 1, + -24, -202, -347, -2080, -4425, -7640, -33791, -74856, 41176, -5288, 5879, -1952, 581, -222, 35, 1, + -26, -208, -401, -2063, -4788, -7134, -35640, -74992, 39336, -5959, 5517, -2000, 519, -218, 31, 1, +} + +-- requantisation: Cc[res] = 65536 / steps (res -1 .. 17, stored at res + 2), Dc[res] = (steps - 1) / 2, bits per +-- sample of the plain quantisers (res 8 .. 17) +T.CC = { + 111.285962475327, 65536.000000000000, 21845.333333333332, 13107.200000000001, 9362.285714285713, + 7281.777777777777, 4369.066666666666, 2114.064516129032, 1040.253968253968, 516.031496062992, 257.003921568627, + 128.250489236790, 64.062561094819, 32.015632633121, 16.003907203907, 8.000976681723, 4.000244155527, + 2.000061037018, 1.000015259021, +} +T.DC = { 2, 0, 1, 2, 3, 4, 7, 15, 31, 63, 127, 255, 511, 1023, 2047, 4095, 8191, 16383, 32767 } +T.RES_BIT = { [8] = 7, [9] = 8, [10] = 9, [11] = 10, [12] = 11, [13] = 12, [14] = 13, [15] = 14, [16] = 15, [17] = 16 } + +-- log_dec(max): ceil(log2(max + 2)) bits and the unused codes (index max + 1, max = 0 .. 31) +T.LOG2 = { 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6 } +T.LOG2_LOST = { 0, 1, 0, 3, 2, 1, 0, 7, 6, 5, 4, 3, 2, 1, 0, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 31 } + +-- enum_dec: CNK[k][n + 1] = C(n, k) (k = 1 .. 16, n = 0 .. 31), the code length ceil(log2 C(n, k)) and the unused +-- codes 2^len - C(n, k) (computed: libmpcdec's tables, whose last entry is 0) +T.CNK, T.CNK_LEN, T.CNK_LOST = {}, {}, {} +do + for k = 1, 16 do + local c, l, lost = table.create(32, 0), table.create(32, 0), table.create(32, 0) + for n = 0, 32 do + local v = 0 + if n >= k then + v = 1 + for i = 1, k do + v = v * (n - k + i) / i + end + v = math.floor(v + 0.5) + end + if n <= 31 then + c[n + 1] = v + end + if n >= 1 then + local bits = 0 + while 2 ^ bits < v do + bits += 1 + end + l[n] = bits + lost[n] = if v > 0 then 2 ^ bits - v else 0 + end + end + T.CNK[k], T.CNK_LEN[k], T.CNK_LOST[k] = c, l, lost + end + T.CNK_LOST[16][32] = 0 +end + +type Lut = { + len: { number }, + val: { number }, + codes: { number }, + lens: { number }, + vals: { number }, + sym: { number }?, +} + +function T.lut(tab: { number }, sym: { number }?): Lut + local codes, lens, vals = {}, {}, {} + for i = 1, #tab, 3 do + table.insert(codes, tab[i]) + table.insert(lens, tab[i + 1]) + table.insert(vals, tab[i + 2]) + end + local function find(code: number): number + local j = 1 + while code < codes[j] do + j += 1 + end + return j + end + local function symbol(j: number, code: number): number + if sym then + local idx = bit32.band(vals[j] - bit32.rshift(code, 16 - lens[j]), 255) + return sym[idx + 1] or 0 + end + return vals[j] + end + local len, val = table.create(256, 0), table.create(256, 0) + for p = 0, 255 do + local lo, hi = find(p * 256), find(p * 256 + 255) + if lo == hi and lens[lo] <= 8 then + len[p + 1] = lens[lo] + val[p + 1] = symbol(lo, p * 256) + else + len[p + 1] = 0 + val[p + 1] = hi + end + end + return { len = len, val = val, codes = codes, lens = lens, vals = vals, sym = sym } +end + +return T +end +end + + + + + + WavPack + --!optimize 2 +--!nocheck +-- rosetta chunk WavPack (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 3 modules (2 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["codecs/audio/WavPack"] = function() + +-- codecs/audio/WavPack: the WavPack 4 / 5 audio codec (the blocks of .wv files, and of WavPack in Matroska). +-- Ported from WavPack 5.9.0 (David Bryant, BSD 3-clause, licenses/wavpack-LICENSE.txt). Not supported: DSD, pre-4.0 +-- streams (version < 0x402). +local Err = __include("core/Err") +local Block = __include("codecs/audio/WavPack/Block") + +local WavPack = {} + +type Header = { + size: number, -- the whole block (ckSize + 8) + version: number, + index: number, -- the first sample of the block (40 bits) + total: number, -- total samples of the file (-1: unknown) + samples: number, + flags: number, + crc: number, +} + +local RATES = { 6000, 8000, 9600, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000, 64000, 88200, 96000, 192000 } +WavPack.MONO, WavPack.HYBRID, WavPack.FLOAT, WavPack.INITIAL, WavPack.FINAL = 4, 8, 0x80, 0x800, 0x1000 +WavPack.DSD = 0x80000000 + +function WavPack.header(buf: buffer, at: number, limit: number?): (Header?, string?) + local lim = math.min(limit or buffer.len(buf), buffer.len(buf)) + if at < 0 or at + 32 > lim then + return nil, "truncated block header" + end + if buffer.readstring(buf, at, 4) ~= "wvpk" then + return nil, "no block header" + end + local ck = buffer.readu32(buf, at + 4) + local version = buffer.readu16(buf, at + 8) + if ck % 2 == 1 or ck < 24 or ck > 0x1000000 then + return nil, "bad block size" + end + if version < 0x402 or version > 0x410 then + return nil, "unsupported: stream version " .. string.format("0x%x", version) + end + local total = buffer.readu32(buf, at + 12) + local tu8 = buffer.readu8(buf, at + 11) + local h: Header = { + size = ck + 8, + version = version, + index = buffer.readu32(buf, at + 16) + buffer.readu8(buf, at + 10) * 4294967296, + total = if total == 0xFFFFFFFF then -1 else total + tu8 * 4294967296 - tu8, + samples = buffer.readu32(buf, at + 20), + flags = buffer.readu32(buf, at + 24), + crc = buffer.readu32(buf, at + 28), + } + if at + h.size > lim then + return nil, "truncated block" + end + return h, nil +end + +type Info = { + channels: number, + channelMask: number, + sampleRate: number, + bitsPerSample: number, + bytesPerSample: number, + float: boolean, + hybrid: boolean, + md5: string?, + version: number, +} + +function WavPack.info(buf: buffer, at: number, limit: number?): (Info?, Err.Err?) + local h, herr = WavPack.header(buf, at, limit) + if not h then + return nil, Err.from(herr, at) + end + local m, merr = Block.meta(buf, at, h.size) + if not m then + return nil, Err.from(merr, at) + end + local flags = h.flags + if bit32.band(flags, WavPack.DSD) ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "DSD audio") + end + local bytes = bit32.band(flags, 3) + 1 + local info: Info = { + channels = if bit32.band(flags, WavPack.MONO) ~= 0 then 1 else 2, + channelMask = 0, + sampleRate = 44100, + bitsPerSample = bytes * 8 - bit32.band(bit32.rshift(flags, 13), 31), + bytesPerSample = bytes, + float = bit32.band(flags, WavPack.FLOAT) ~= 0, + hybrid = bit32.band(flags, WavPack.HYBRID) ~= 0, + version = h.version, + } + info.channelMask = if info.channels == 1 then 4 else 3 + local sr = bit32.band(bit32.rshift(flags, 23), 15) + if sr < 15 then + info.sampleRate = RATES[sr + 1] + end + local o = m[0x27] -- ID_SAMPLE_RATE + if o and (m[0x27 + 256] == 3 or m[0x27 + 256] == 4) then + local rate = buffer.readu8(buf, o) + buffer.readu8(buf, o + 1) * 256 + buffer.readu8(buf, o + 2) * 65536 + if m[0x27 + 256] == 4 then + rate += bit32.band(buffer.readu8(buf, o + 3), 0x7F) * 16777216 + end + info.sampleRate = rate + end + o = m[0xD] -- ID_CHANNEL_INFO + if o then + local len = m[0xD + 256] + if len == 0 or len > 7 then + return nil, Err.new(Err.CORRUPT, "bad channel info", o) + end + local mask = 0 + if len >= 6 then + info.channels = buffer.readu8(buf, o) + bit32.band(buffer.readu8(buf, o + 2), 0xF) * 256 + 1 + mask = buffer.readu8(buf, o + 3) + buffer.readu8(buf, o + 4) * 256 + buffer.readu8(buf, o + 5) * 65536 + if len == 7 then + mask += buffer.readu8(buf, o + 6) * 16777216 + end + else + info.channels = buffer.readu8(buf, o) + for k = 1, len - 1 do + mask += buffer.readu8(buf, o + k) * 256 ^ (k - 1) + end + end + info.channelMask = mask + end + if info.channels < 1 then + return nil, Err.new(Err.CORRUPT, "no channels") + end + if info.sampleRate < 1 then + return nil, Err.new(Err.CORRUPT, "bad sample rate") + end + return info, nil +end + +function WavPack.md5(buf: buffer, at: number, limit: number?): string? + local h = WavPack.header(buf, at, limit) + if not h then + return nil + end + local m = Block.meta(buf, at, h.size) + if not m then + return nil + end + local o = m[0x26] + if not o or m[0x26 + 256] ~= 16 then + return nil + end + local hex = table.create(16, "") + for k = 0, 15 do + hex[k + 1] = string.format("%02x", buffer.readu8(buf, o + k)) + end + return table.concat(hex) +end + +type Decoder = { + channels: number, + pcm: { number }, + frame: (self: Decoder, buf: buffer, blocks: { number }, cbuf: buffer?, cblocks: { number }?) -> (number?, Err.Err?), + state: Block.State, +} + +local function frame(self: Decoder, buf: buffer, blocks: { number }, cbuf: buffer?, cblocks: { number }?): (number?, Err.Err?) + local C = self.channels + local n = -1 + local c0 = 0 + for i, at in blocks do + if c0 >= C then + break + end + local h, herr = WavPack.header(buf, at) + if not h then + return nil, Err.from(herr, at) + end + if n < 0 then + n = h.samples + if n * C > 16777216 then + return nil, Err.new(Err.LIMIT, "a frame of " .. n .. " samples x " .. C .. " channels", at) + end + if #self.pcm < n * C then + self.pcm = table.create(n * C, 0) + end + elseif h.samples ~= n then + return nil, Err.new(Err.CORRUPT, "blocks of a frame differ in length", at) + end + local cb, cp, cs = nil, nil, nil + if cbuf and cblocks and cblocks[i] then + local ch = WavPack.header(cbuf, cblocks[i]) + if ch and ch.samples == h.samples and ch.index == h.index then + cb, cp, cs = cbuf, cblocks[i], ch.size + end + end + local got, msg = Block.decode(self.state, buf, at, h.size, self.pcm, c0, C, cb, cp, cs) + if not got then + return nil, Err.from(msg, at) + end + c0 += got + end + if n < 0 then + return 0, nil + end + if c0 < C then + return nil, Err.new(Err.CORRUPT, "a frame is missing channels") + end + return n, nil +end + +function WavPack.decoder(channels: number): Decoder + return { + channels = channels, + pcm = table.create(4096 * channels, 0), + frame = frame, + state = Block.state(), + } +end + +WavPack.checksum = Block.checksum +WavPack.meta = Block.meta + +return WavPack +end +__FILES["codecs/audio/WavPack/Block"] = @native function() + + + +-- codecs/audio/WavPack/Block: one WavPack 4 / 5 block (one mono or stereo stream of a frame) -> samples. +-- Ported from WavPack 5.9.0 (David Bryant, BSD 3-clause, licenses/wavpack-LICENSE.txt): unpack.c, read_words.c, +-- unpack_floats.c, decorr_utils.c / entropy_utils.c, open_utils.c. DSD blocks are UNSUPPORTED. +local Tables = __include("codecs/audio/WavPack/Tables") + +local readu8, readi8, readu16, readi16, readu32 = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16, buffer.readu32 +local writeu32, readf32 = buffer.writeu32, buffer.readf32 +local band, rshift, countlz = bit32.band, bit32.rshift, bit32.countlz +local exp2s, log2, restoreWeight = Tables.exp2s, Tables.log2, Tables.restoreWeight +local sign, clamp = math.sign, math.clamp + +local Block = {} + +local TWO32 = 4294967296 +local P2: { number } = table.create(34, 0) +for i = 0, 33 do + P2[i + 1] = 2 ^ i +end +local ONES: { number } = table.create(256, 0) +for b = 0, 255 do + local n, v = 0, b + while v % 2 == 1 do + n += 1 + v = v // 2 + end + ONES[b + 1] = n +end + +local MONO_FLAG, HYBRID, JOINT, CROSS, SHAPE, FLOAT, INT32 = 4, 8, 0x10, 0x20, 0x40, 0x80, 0x100 +local HBITRATE, HBALANCE, NEW_SHAPING, FALSE_STEREO, DSD = 0x200, 0x400, 0x20000000, 0x40000000, 0x80000000 +local FLOAT_SHIFT_ONES, FLOAT_SHIFT_SAME, FLOAT_SHIFT_SENT, FLOAT_ZEROS_SENT, FLOAT_NEG_ZEROS = 1, 2, 4, 8, 0x10 +local PAD = 64 -- zero bytes after each copied bitstream: reads past the end stay in the buffer +local MAX_SAMPLES = 2 ^ 20 +local D2, D1 = 17, 9 -- the first data index of the work table (stereo / mono): 8 frames of history in front + +type Meta = { [number]: number } -- id -> offset; id + 256 -> byte length + +@native function Block.meta(buf: buffer, p: number, size: number): (Meta?, string?) + local m: Meta = {} + local q, stop = p + 32, p + size + while stop - q >= 2 do + local id = readu8(buf, q) + local len = readu8(buf, q + 1) * 2 + q += 2 + if band(id, 0x80) ~= 0 then + if stop - q < 2 then + return nil, "truncated metadata" + end + len += readu8(buf, q) * 512 + readu8(buf, q + 1) * 131072 + q += 2 + id -= 0x80 + end + local odd = 0 + if band(id, 0x40) ~= 0 then + if len == 0 then + return nil, "odd-sized empty metadata" + end + id -= 0x40 + len -= 1 + odd = 1 + end + if stop - q < len + odd then + return nil, "truncated metadata" + end + m[id] = q + m[id + 256] = len + q += len + odd + end + return m, nil +end + +@native function Block.checksum(buf: buffer, p: number, m: Meta): boolean + local o = m[0x2F] + if not o then + return true + end + local len = m[0x2F + 256] + if len ~= 2 and len ~= 4 then + return false + end + local words = (o - 2 - p) // 2 + local csum = TWO32 - 1 + for i = 0, words - 1 do + csum = (csum * 3 + readu16(buf, p + i * 2)) % TWO32 + end + if len == 4 then + return readu32(buf, o) == csum + end + csum = bit32.bxor(csum, rshift(csum, 16)) + return readu16(buf, o) == band(csum, 0xFFFF) +end + +type Reader = { b: buffer, p: number, e: number, n: number } +type State = { [string]: any } + +@native function Block.state(): State + return { + W = table.create(D2 + 2 * 4096, 0), + term = table.create(16, 0), + delta = table.create(16, 0), + wA = table.create(16, 0), + wB = table.create(16, 0), + sA = table.create(16 * 8, 0), + sB = table.create(16 * 8, 0), + med = table.create(6, 0), + slow = { 0, 0 }, + limit = { 0, 0 }, + bacc = { 0, 0 }, + bdelta = { 0, 0 }, + sacc = { 0, 0 }, + sdelta = { 0, 0 }, + err = { 0, 0 }, + R1 = { b = buffer.create(0), p = 0, e = 0, n = 0 } :: Reader, + R2 = { b = buffer.create(0), p = 0, e = 0, n = 0 } :: Reader, + R3 = { b = buffer.create(0), p = 0, e = 0, n = 0 } :: Reader, + scratch = buffer.create(4), + } +end + +@native local function openReader(R: Reader, buf: buffer, o: number, len: number) + if buffer.len(R.b) < len + PAD then + R.b = buffer.create(len + PAD + 1024) + else + buffer.fill(R.b, len, 0, PAD) + end + buffer.copy(R.b, 0, buf, o, len) + R.p = 0 + R.e = len * 8 + R.n = len + PAD +end + +@native local function bits(R: Reader, n: number): number + if n <= 0 then + return 0 + end + local p = R.p + local byte = rshift(p, 3) + if byte + 8 > R.n then + R.p = R.e + 1 + return 0 + end + local b = R.b + if n <= 25 then + R.p = p + n + return band(rshift(readu32(b, byte), band(p, 7)), P2[n + 1] - 1) + end + local lo = band(rshift(readu32(b, byte), band(p, 7)), 0xFFFF) + p += 16 + R.p = p + n - 16 + return lo + band(rshift(readu32(b, rshift(p, 3)), band(p, 7)), P2[n - 15] - 1) * 65536 +end + +@native local function bit(R: Reader): number + return bits(R, 1) +end + +@native local function trailing(R: Reader, max: number): number + local c = 0 + while c < max do + local p = R.p + local byte = rshift(p, 3) + if byte + 8 > R.n then + R.p = R.e + 1 + return max + end + local ones = ONES[band(rshift(readu32(R.b, byte), band(p, 7)), 255) + 1] + if ones < 8 then + if c + ones >= max then + R.p = p + (max - c) + return max + end + R.p = p + ones + 1 + return c + ones + end + c += 8 + R.p = p + 8 + end + R.p -= c - max + return max +end + +-- the "Elias gamma"-like count (cbits ones, a zero, cbits - 1 bits) -> value | nil (33 ones) +@native local function gamma(R: Reader): number? + local c = trailing(R, 33) + if c == 33 then + return nil + end + if c < 2 then + return c + end + return bits(R, c - 1) + P2[c] +end + +-- read_code +@native local function readCode(R: Reader, maxcode: number): number + if maxcode < 2 then + return if maxcode == 1 then bits(R, 1) else 0 + end + local bc = 32 - countlz(maxcode) + local extras = P2[bc + 1] - maxcode - 1 + local code = bits(R, bc - 1) + if code >= extras then + code = code * 2 - extras + bits(R, 1) + end + return code +end + +-- ones(R) -> the unary count with its escape (LIMIT_ONES = 16) | nil (the end marker) +@native local function onesCount(R: Reader): number? + local c = trailing(R, 17) + if c == 17 then + return nil + end + if c == 16 then + local g = gamma(R) + if not g then + return nil + end + c = g + 16 + end + return c +end + +-- get_words_lossless +@native local function wordsLossless(st: State, count: number, d: number): boolean + local R: Reader = st.R1 + local b, pos, lim = R.b, R.p, R.e + local W = st.W + local med = st.med + local stereo = d == D2 + local a0, a1, a2, c0, c1, c2 = med[4], med[5], med[6], med[1], med[2], med[3] + if not stereo then + a0, a1, a2, c0, c1, c2 = med[1], med[2], med[3], 0, 0, 0 + end + local hz, ho, za = 0, 0, 0 + for idx = d, d + count - 1 do + if stereo then + a0, a1, a2, c0, c1, c2 = c0, c1, c2, a0, a1, a2 + end + if pos > lim then + return false + end + if hz ~= 0 then + hz = 0 + local maxcode = a0 // 16 + a0 -= ((a0 + 126) // 128) * 2 + local w = rshift(readu32(b, rshift(pos, 3)), band(pos, 7)) + local low, used = 0, 0 + if maxcode < 2 then + if maxcode == 1 then + low, used = band(w, 1), 1 + end + else + local bc = 32 - countlz(maxcode) + if bc > 24 then + R.p = pos + low = readCode(R, maxcode) + pos = R.p + w = rshift(readu32(b, rshift(pos, 3)), band(pos, 7)) + else + local extras = P2[bc + 1] - maxcode - 1 + low = band(w, P2[bc] - 1) + if low >= extras then + low = low * 2 - extras + band(rshift(w, bc - 1), 1) + used = bc + else + used = bc - 1 + end + end + end + if band(rshift(w, used), 1) ~= 0 then + W[idx] = -low - 1 + else + W[idx] = low + end + pos += used + 1 + continue + end + if a0 < 2 and ho == 0 and c0 < 2 then + if za > 0 then + za -= 1 + if za > 0 then + W[idx] = 0 + continue + end + else + R.p = pos + local g = gamma(R) + pos = R.p + if not g then + return false + end + za = g + if za > 0 then + a0, a1, a2, c0, c1, c2 = 0, 0, 0, 0, 0, 0 + W[idx] = 0 + continue + end + end + end + local w = rshift(readu32(b, rshift(pos, 3)), band(pos, 7)) + local ones = ONES[band(w, 255) + 1] + if ones == 8 then + ones = 8 + ONES[band(rshift(w, 8), 255) + 1] + end + if ones < 16 then + pos += ones + 1 + else + if band(w, 0x10000) ~= 0 then + return false + end + R.p = pos + 17 + local g = gamma(R) + pos = R.p + if not g then + return false + end + ones = g + 16 + end + local hold = ho + ho = band(ones, 1) + hz = 1 - ho + ones = ones // 2 + hold + local low, high + if ones == 0 then + low = 0 + high = a0 // 16 + a0 -= ((a0 + 126) // 128) * 2 + else + low = a0 // 16 + 1 + a0 += ((a0 + 128) // 128) * 5 + if ones == 1 then + high = low + a1 // 16 + a1 -= ((a1 + 62) // 64) * 2 + else + low += a1 // 16 + 1 + a1 += ((a1 + 64) // 64) * 5 + if ones == 2 then + high = low + a2 // 16 + a2 -= ((a2 + 30) // 32) * 2 + else + low += (ones - 2) * (a2 // 16 + 1) + high = low + a2 // 16 + a2 += ((a2 + 32) // 32) * 5 + end + end + end + local maxcode = high - low + w = rshift(readu32(b, rshift(pos, 3)), band(pos, 7)) + local used = 0 + if maxcode < 2 then + if maxcode == 1 then + low += band(w, 1) + used = 1 + end + else + if maxcode >= 536870912 then + return false + end + local bc = 32 - countlz(maxcode) + if bc > 24 then + R.p = pos + low += readCode(R, maxcode) + pos = R.p + w = rshift(readu32(b, rshift(pos, 3)), band(pos, 7)) + else + local extras = P2[bc + 1] - maxcode - 1 + local code = band(w, P2[bc] - 1) + if code >= extras then + code = code * 2 - extras + band(rshift(w, bc - 1), 1) + used = bc + else + used = bc - 1 + end + low += code + end + end + if band(rshift(w, used), 1) ~= 0 then + W[idx] = -low - 1 + else + W[idx] = low + end + pos += used + 1 + end + R.p = pos + return pos <= lim +end + +@native local function updateErrorLimit(st: State, flags: number, mono: boolean) + local bacc, bdelta, slow, limit = st.bacc, st.bdelta, st.slow, st.limit + bacc[1] = (bacc[1] + bdelta[1]) % TWO32 + local br0 = bacc[1] // 65536 + if mono then + if band(flags, HBITRATE) ~= 0 then + local sl0 = (slow[1] + 128) // 256 + limit[1] = if sl0 - br0 > -256 then exp2s(sl0 - br0 + 256) % TWO32 else 0 + else + limit[1] = exp2s(br0) % TWO32 + end + return + end + bacc[2] = (bacc[2] + bdelta[2]) % TWO32 + local br1 = bacc[2] // 65536 + if band(flags, HBITRATE) ~= 0 then + local sl0 = (slow[1] + 128) // 256 + local sl1 = (slow[2] + 128) // 256 + if band(flags, HBALANCE) ~= 0 then + local balance = (sl1 - sl0 + br1 + 1) // 2 + if balance > br0 then + br1 = br0 * 2 + br0 = 0 + elseif -balance > br0 then + br0 = br0 * 2 + br1 = 0 + else + br1 = br0 + balance + br0 = br0 - balance + end + end + limit[1] = if sl0 - br0 > -256 then exp2s(sl0 - br0 + 256) % TWO32 else 0 + limit[2] = if sl1 - br1 > -256 then exp2s(sl1 - br1 + 256) % TWO32 else 0 + else + limit[1] = exp2s(br0) % TWO32 + limit[2] = exp2s(br1) % TWO32 + end +end + +-- get_word +@native local function getWord(st: State, chan: number, flags: number, mono: boolean): (number?, number) + local R: Reader = st.R1 + local med = st.med + local mb = chan * 3 + local correction = 0 + if R.p > R.e then + return nil, 0 + end + if med[1] < 2 and st.hz == 0 and st.ho == 0 and med[4] < 2 then + if st.za > 0 then + st.za -= 1 + if st.za > 0 then + local s = st.slow + s[chan + 1] -= (s[chan + 1] + 128) // 256 + return 0, 0 + end + else + local g = gamma(R) + if not g then + return nil, 0 + end + st.za = g + if g > 0 then + local s = st.slow + s[chan + 1] -= (s[chan + 1] + 128) // 256 + for k = 1, 6 do + med[k] = 0 + end + return 0, 0 + end + end + end + local ones + if st.hz ~= 0 then + ones = 0 + st.hz = 0 + else + local c = onesCount(R) + if not c then + return nil, 0 + end + ones = c + if st.ho ~= 0 then + st.ho = band(ones, 1) + ones = ones // 2 + 1 + else + st.ho = band(ones, 1) + ones = ones // 2 + end + st.hz = 1 - st.ho + end + if band(flags, HYBRID) ~= 0 and chan == 0 then + updateErrorLimit(st, flags, mono) + end + local m0, m1, m2 = med[mb + 1], med[mb + 2], med[mb + 3] + local low, high + if ones == 0 then + low = 0 + high = m0 // 16 + m0 -= ((m0 + 126) // 128) * 2 + else + low = m0 // 16 + 1 + m0 += ((m0 + 128) // 128) * 5 + if ones == 1 then + high = low + m1 // 16 + m1 -= ((m1 + 62) // 64) * 2 + else + low += m1 // 16 + 1 + m1 += ((m1 + 64) // 64) * 5 + if ones == 2 then + high = low + m2 // 16 + m2 -= ((m2 + 30) // 32) * 2 + else + low += (ones - 2) * (m2 // 16 + 1) + high = low + m2 // 16 + m2 += ((m2 + 32) // 32) * 5 + end + end + end + med[mb + 1], med[mb + 2], med[mb + 3] = m0 % TWO32, m1 % TWO32, m2 % TWO32 + low = band(low % TWO32, 0x7FFFFFFF) + high = band(high % TWO32, 0x7FFFFFFF) + if low > high then + high = low + end + local mid = (high + low + 1) // 2 + local limit = st.limit[chan + 1] + if limit == 0 then + mid = readCode(R, high - low) + low + else + while high - low > limit do + if R.p > R.e then + return nil, 0 + end + if bits(R, 1) == 1 then + low = mid + mid = (high + low + 1) // 2 + else + high = mid - 1 + mid = (high + low + 1) // 2 + end + end + end + local sign = bits(R, 1) + if st.wvc and limit ~= 0 then + local value = readCode(st.R2, high - low) + low + correction = if sign == 1 then mid - value else value - mid + end + if band(flags, HBITRATE) ~= 0 then + local s = st.slow + s[chan + 1] = s[chan + 1] - (s[chan + 1] + 128) // 256 + log2(mid) + end + return if sign == 1 then -mid - 1 else mid, correction +end + +-- the decorrelation passes over the whole block (stereo, from W[D2]): unpack.c decorr_stereo_pass +@native local function passesStereo(st: State, n: number) + local W = st.W + local last = D2 + 2 * n - 2 + local terms, deltas, wAs, wBs, sA, sB = st.term, st.delta, st.wA, st.wB, st.sA, st.sB + for t = 1, st.nterms do + local term, delta, wA, wB = terms[t], deltas[t], wAs[t], wBs[t] + local so = (t - 1) * 8 + if term > 8 then + local a0, a1, b0, b1 = sA[so + 1], sA[so + 2], sB[so + 1], sB[so + 2] + local dv = term - 16 -- 17: 2 a0 - a1, 18: a0 + (a0 - a1) / 2 + for i = D2, last, 2 do + local sam = a0 + (a0 - a1) // dv + local x = W[i] + local o = (wA * sam + 512) // 1024 + x + wA += delta * sign(sam * x) + a1, a0 = a0, o + W[i] = o + sam = b0 + (b0 - b1) // dv + x = W[i + 1] + o = (wB * sam + 512) // 1024 + x + wB += delta * sign(sam * x) + b1, b0 = b0, o + W[i + 1] = o + end + elseif term > 0 then + for j = 0, term - 1 do + W[D2 + 2 * (j - term)] = sA[so + j + 1] + W[D2 + 1 + 2 * (j - term)] = sB[so + j + 1] + end + local back = 2 * term + for i = D2, last, 2 do + local sam = W[i - back] + local x = W[i] + W[i] = (wA * sam + 512) // 1024 + x + wA += delta * sign(sam * x) + sam = W[i + 1 - back] + x = W[i + 1] + W[i + 1] = (wB * sam + 512) // 1024 + x + wB += delta * sign(sam * x) + end + elseif term == -1 then + local sa = sA[so + 1] + for i = D2, last, 2 do + local x = W[i] + local sam = x + (wA * sa + 512) // 1024 + wA = clamp(wA + delta * sign(sa * x), -1024, 1024) + W[i] = sam + x = W[i + 1] + sa = x + (wB * sam + 512) // 1024 + wB = clamp(wB + delta * sign(sam * x), -1024, 1024) + W[i + 1] = sa + end + elseif term == -2 then + local sb = sB[so + 1] + for i = D2, last, 2 do + local x = W[i + 1] + local sam = x + (wB * sb + 512) // 1024 + wB = clamp(wB + delta * sign(sb * x), -1024, 1024) + W[i + 1] = sam + x = W[i] + sb = x + (wA * sam + 512) // 1024 + wA = clamp(wA + delta * sign(sam * x), -1024, 1024) + W[i] = sb + end + else -- -3 + local sa, sb = sA[so + 1], sB[so + 1] + for i = D2, last, 2 do + local x = W[i] + local samA = x + (wA * sa + 512) // 1024 + wA = clamp(wA + delta * sign(sa * x), -1024, 1024) + x = W[i + 1] + local samB = x + (wB * sb + 512) // 1024 + wB = clamp(wB + delta * sign(sb * x), -1024, 1024) + W[i], W[i + 1] = samA, samB + sa, sb = samB, samA + end + end + end +end + +-- the decorrelation passes (mono, from W[D1]): unpack.c decorr_mono_pass +@native local function passesMono(st: State, n: number) + local W = st.W + local last = D1 + n - 1 + local terms, deltas, wAs, sA = st.term, st.delta, st.wA, st.sA + for t = 1, st.nterms do + local term, delta, wA = terms[t], deltas[t], wAs[t] + local so = (t - 1) * 8 + if term > 8 then + local a0, a1 = sA[so + 1], sA[so + 2] + local dv = term - 16 -- 17: 2 a0 - a1, 18: a0 + (a0 - a1) / 2 + for i = D1, last do + local sam = a0 + (a0 - a1) // dv + local x = W[i] + local o = (wA * sam + 512) // 1024 + x + wA += delta * sign(sam * x) + a1, a0 = a0, o + W[i] = o + end + else + for j = 0, term - 1 do + W[D1 + j - term] = sA[so + j + 1] + end + for i = D1, last do + local sam = W[i - term] + local x = W[i] + W[i] = (wA * sam + 512) // 1024 + x + wA += delta * sign(sam * x) + end + end + end +end + +@native local function shaped(st: State, c: number, flags: number, correction: number): number + -- returns the value to subtract (temp) and updates the error state (noise shaping, unpack.c) + local sacc, sdelta, err = st.sacc, st.sdelta, st.err + sacc[c] = (sacc[c] + sdelta[c]) % TWO32 + local sw = sacc[c] // 65536 + if sw >= 32768 then + sw -= 65536 + end + local temp = -((sw * err[c] + 512) // 1024) + if band(flags, NEW_SHAPING) ~= 0 and sw < 0 and temp ~= 0 then + if temp == err[c] then + temp = if temp < 0 then temp + 1 else temp - 1 + end + err[c] = temp - correction + else + err[c] = -correction + end + return temp +end + +@native local function hybridMono(st: State, n: number, flags: number): boolean + local W = st.W + local terms, deltas, wAs, sA = st.term, st.delta, st.wA, st.sA + local nterms = st.nterms + local m = 0 + local crc = TWO32 - 1 + for i = 0, n - 1 do + local word, corr = getWord(st, 0, flags, true) + if not word then + return false + end + local rw = word + for t = 1, nterms do + local term, so = terms[t], (t - 1) * 8 + local sam, k + if term > 8 then + sam = if term % 2 == 1 then 2 * sA[so + 1] - sA[so + 2] else (3 * sA[so + 1] - sA[so + 2]) // 2 + sA[so + 2] = sA[so + 1] + k = 0 + else + sam = sA[so + m + 1] + k = band(m + term, 7) + end + local temp = (wAs[t] * sam + 512) // 1024 + rw + wAs[t] += deltas[t] * sign(sam * rw) + sA[so + k + 1] = temp + rw = temp + end + m = band(m + 1, 7) + if band(flags, SHAPE) ~= 0 then + local temp = shaped(st, 1, flags, corr) + rw += corr - temp + else + rw += corr + end + crc = (crc * 3 + rw) % TWO32 + W[D1 + i] = rw + end + st.crcv = crc + return true +end + +@native local function hybridStereo(st: State, n: number, flags: number): boolean + local W = st.W + local terms, deltas, wAs, wBs, sA, sB = st.term, st.delta, st.wA, st.wB, st.sA, st.sB + local nterms = st.nterms + local m = 0 + local crc = TWO32 - 1 + local cross = band(flags, CROSS) ~= 0 + local joint = band(flags, JOINT) ~= 0 + for i = 0, n - 1 do + local left, corr0 = getWord(st, 0, flags, false) + if not left then + return false + end + local right, corr1 = getWord(st, 1, flags, false) + if not right then + return false + end + local leftc, rightc = 0, 0 + if cross then + leftc, rightc = left + corr0, right + corr1 + for t = 1, nterms do + local term, so = terms[t], (t - 1) * 8 + if term > 0 then + local samA, samB + if term > 8 then + if term % 2 == 1 then + samA = 2 * sA[so + 1] - sA[so + 2] + samB = 2 * sB[so + 1] - sB[so + 2] + else + samA = (3 * sA[so + 1] - sA[so + 2]) // 2 + samB = (3 * sB[so + 1] - sB[so + 2]) // 2 + end + else + samA, samB = sA[so + m + 1], sB[so + m + 1] + end + leftc += (wAs[t] * samA + 512) // 1024 + rightc += (wBs[t] * samB + 512) // 1024 + elseif term == -1 then + leftc += (wAs[t] * sA[so + 1] + 512) // 1024 + rightc += (wBs[t] * leftc + 512) // 1024 + else + rightc += (wBs[t] * sB[so + 1] + 512) // 1024 + if term == -3 then + leftc += (wAs[t] * sA[so + 1] + 512) // 1024 + else + leftc += (wAs[t] * rightc + 512) // 1024 + end + end + end + if joint then + rightc -= leftc // 2 + leftc += rightc + end + end + for t = 1, nterms do + local term, delta, so = terms[t], deltas[t], (t - 1) * 8 + if term > 0 then + local samA, samB, k + if term > 8 then + if term % 2 == 1 then + samA = 2 * sA[so + 1] - sA[so + 2] + samB = 2 * sB[so + 1] - sB[so + 2] + else + samA = (3 * sA[so + 1] - sA[so + 2]) // 2 + samB = (3 * sB[so + 1] - sB[so + 2]) // 2 + end + sA[so + 2] = sA[so + 1] + sB[so + 2] = sB[so + 1] + k = 0 + else + samA, samB = sA[so + m + 1], sB[so + m + 1] + k = band(m + term, 7) + end + local left2 = (wAs[t] * samA + 512) // 1024 + left + local right2 = (wBs[t] * samB + 512) // 1024 + right + wAs[t] += delta * sign(samA * left) + wBs[t] += delta * sign(samB * right) + left, right = left2, right2 + sA[so + k + 1], sB[so + k + 1] = left, right + elseif term == -1 then + local sa = sA[so + 1] + local left2 = left + (wAs[t] * sa + 512) // 1024 + wAs[t] = clamp(wAs[t] + delta * sign(sa * left), -1024, 1024) + left = left2 + local right2 = right + (wBs[t] * left2 + 512) // 1024 + wBs[t] = clamp(wBs[t] + delta * sign(left2 * right), -1024, 1024) + right = right2 + sA[so + 1] = right + else + local sb = sB[so + 1] + local right2 = right + (wBs[t] * sb + 512) // 1024 + wBs[t] = clamp(wBs[t] + delta * sign(sb * right), -1024, 1024) + right = right2 + if term == -3 then + right2 = sA[so + 1] + sA[so + 1] = right + end + local left2 = left + (wAs[t] * right2 + 512) // 1024 + wAs[t] = clamp(wAs[t] + delta * sign(right2 * left), -1024, 1024) + left = left2 + sB[so + 1] = left + end + end + m = band(m + 1, 7) + if not cross then + leftc, rightc = left + corr0, right + corr1 + if joint then + rightc -= leftc // 2 + leftc += rightc + end + end + if joint then + right -= left // 2 + left += right + end + if band(flags, SHAPE) ~= 0 then + local temp = shaped(st, 1, flags, leftc - left) + left = leftc - temp + temp = shaped(st, 2, flags, rightc - right) + right = rightc - temp + else + left, right = leftc, rightc + end + crc = (crc * 9 + left * 3 + right) % TWO32 + W[D2 + 2 * i], W[D2 + 2 * i + 1] = left, right + end + st.crcv = crc + return true +end + +@native local function readMeta(st: State, buf: buffer, m: Meta, flags: number, version: number): string? + local mono = band(flags, MONO_FLAG + FALSE_STEREO) ~= 0 + local o = m[2] + if o then -- decorrelation terms + local cnt = m[2 + 256] + if cnt > 16 then + return "too many decorrelation terms" + end + st.nterms = cnt + for i = 0, cnt - 1 do + local v = readu8(buf, o + i) + local t = cnt - i + local term = band(v, 0x1F) - 5 + if term == 0 or term < -3 or (term > 8 and term < 17) or term > 18 or (mono and term < 0) then + return "bad decorrelation term" + end + st.term[t] = term + st.delta[t] = band(rshift(v, 5), 7) + end + end + local nterms = st.nterms + o = m[3] + if o then -- weights, from the last pass back + for t = 1, nterms do + st.wA[t], st.wB[t] = 0, 0 + end + local cnt = m[3 + 256] + if not mono then + cnt //= 2 + end + if cnt > nterms then + return "too many decorrelation weights" + end + local q = o + for t = nterms, nterms - cnt + 1, -1 do + st.wA[t] = restoreWeight(readi8(buf, q)) + q += 1 + if not mono then + st.wB[t] = restoreWeight(readi8(buf, q)) + q += 1 + end + end + end + local sA, sB = st.sA, st.sB + o = m[4] + if o then -- decorrelation samples, from the last pass back + for k = 1, nterms * 8 do + sA[k], sB[k] = 0, 0 + end + local q, stop = o, o + m[4 + 256] + if version == 0x402 and band(flags, HYBRID) ~= 0 then + if q + (if mono then 2 else 4) > stop then + return "bad decorrelation samples" + end + st.err[1] = exp2s(readi16(buf, q)) + q += 2 + if not mono then + st.err[2] = exp2s(readi16(buf, q)) + q += 2 + end + end + local t = nterms + while t >= 1 and q < stop do + local term, so = st.term[t], (t - 1) * 8 + if term > 8 then + if q + (if mono then 4 else 8) > stop then + return "bad decorrelation samples" + end + sA[so + 1], sA[so + 2] = exp2s(readi16(buf, q)), exp2s(readi16(buf, q + 2)) + q += 4 + if not mono then + sB[so + 1], sB[so + 2] = exp2s(readi16(buf, q)), exp2s(readi16(buf, q + 2)) + q += 4 + end + elseif term < 0 then + if q + 4 > stop then + return "bad decorrelation samples" + end + sA[so + 1], sB[so + 1] = exp2s(readi16(buf, q)), exp2s(readi16(buf, q + 2)) + q += 4 + else + for k = 1, term do + if q + (if mono then 2 else 4) > stop then + return "bad decorrelation samples" + end + sA[so + k] = exp2s(readi16(buf, q)) + q += 2 + if not mono then + sB[so + k] = exp2s(readi16(buf, q)) + q += 2 + end + end + end + t -= 1 + end + if q ~= stop then + return "bad decorrelation samples" + end + end + o = m[5] + if o then -- entropy medians + if m[5 + 256] ~= (if mono then 6 else 12) then + return "bad entropy variables" + end + for k = 0, (if mono then 2 else 5) do + st.med[k + 1] = exp2s(readu16(buf, o + k * 2)) % TWO32 + end + end + o = m[6] + if o then -- hybrid profile + local q, stop = o, o + m[6 + 256] + local w = if mono then 2 else 4 + if band(flags, HBITRATE) ~= 0 then + if q + w > stop then + return "bad hybrid profile" + end + st.slow[1] = exp2s(readu16(buf, q)) % TWO32 + if not mono then + st.slow[2] = exp2s(readu16(buf, q + 2)) % TWO32 + end + q += w + end + if q + w > stop then + return "bad hybrid profile" + end + st.bacc[1] = readu16(buf, q) * 65536 + if not mono then + st.bacc[2] = readu16(buf, q + 2) * 65536 + end + q += w + if q < stop then + if q + w > stop then + return "bad hybrid profile" + end + st.bdelta[1] = exp2s(readi16(buf, q)) + if not mono then + st.bdelta[2] = exp2s(readi16(buf, q + 2)) + end + q += w + if q < stop then + return "bad hybrid profile" + end + end + end + o = m[7] + if o then -- noise shaping + local len = m[7 + 256] + if len == 2 then + st.sacc[1] = (restoreWeight(readi8(buf, o)) * 65536) % TWO32 + st.sacc[2] = (restoreWeight(readi8(buf, o + 1)) * 65536) % TWO32 + elseif len >= (if mono then 4 else 8) then + st.err[1] = exp2s(readi16(buf, o)) + st.sacc[1] = exp2s(readi16(buf, o + 2)) % TWO32 + if not mono then + st.err[2] = exp2s(readi16(buf, o + 4)) + st.sacc[2] = exp2s(readi16(buf, o + 6)) % TWO32 + end + local q = o + (if mono then 4 else 8) + if len == (if mono then 6 else 12) then + st.sdelta[1] = exp2s(readi16(buf, q)) % TWO32 + if not mono then + st.sdelta[2] = exp2s(readi16(buf, q + 2)) % TWO32 + end + end + else + return "bad shaping weights" + end + end + o = m[8] + if o then + if m[8 + 256] ~= 4 then + return "bad float info" + end + st.fflags, st.fshift, st.fmaxexp = readu8(buf, o), readu8(buf, o + 1), readu8(buf, o + 2) + end + o = m[9] + if o then + if m[9 + 256] ~= 4 then + return "bad int32 info" + end + st.isent, st.izeros, st.iones, st.idups = readu8(buf, o), readu8(buf, o + 1), readu8(buf, o + 2), readu8(buf, o + 3) + end + return nil +end + +-- float_values (R = the wvx stream or nil) +@native local function floatValue(st: State, v: number, R: Reader?): number + local fflags, exp = st.fflags, st.fmaxexp + local mant, e, sign = 0, 0, 0 + if v == 0 then + if R then + if band(fflags, FLOAT_ZEROS_SENT) ~= 0 then + if bits(R, 1) == 1 then + mant = bits(R, 23) + if exp >= 25 then + e = bits(R, 8) + end + sign = bits(R, 1) + elseif band(fflags, FLOAT_NEG_ZEROS) ~= 0 then + sign = bits(R, 1) + end + end + end + else + v = (v * P2[band(st.fshift, 31) + 1]) % TWO32 + if v >= 2147483648 then + v -= TWO32 + end + if v < 0 then + v = -v + sign = 1 + end + if R then + if v == 0x1000000 then + if bits(R, 1) == 1 then + mant = bits(R, 23) + end + e = 255 + else + local shift = 0 + if exp > 0 then + while v < 0x800000 do + exp -= 1 + if exp == 0 then + break + end + shift += 1 + v *= 2 + end + end + shift = band(shift, 31) + if shift > 0 then + if band(fflags, FLOAT_SHIFT_ONES) ~= 0 or (band(fflags, FLOAT_SHIFT_SAME) ~= 0 and bits(R, 1) == 1) then + v += P2[shift + 1] - 1 + elseif band(fflags, FLOAT_SHIFT_SENT) ~= 0 then + local mask = P2[shift + 1] - 1 + local zeros = 0 + local maxOnes, minZeros = st.fmaxones, st.fminzeros + if maxOnes > 0 and shift > maxOnes then + zeros = shift - maxOnes + end + if minZeros > zeros then + zeros = if minZeros > shift then shift else minZeros + end + local sc = shift - zeros + if sc > 0 then + v = bit32.bor(v % TWO32, band(bits(R, sc) * P2[zeros + 1], mask)) + end + end + end + mant = band(v % TWO32, 0x7FFFFF) + e = band(exp, 255) + end + else + if v >= 0x1000000 then + while band(v, 0xF000000) ~= 0 do + v //= 2 + exp += 1 + end + elseif exp > 0 then + local shift = 0 + while v < 0x800000 do + exp -= 1 + if exp == 0 then + break + end + shift += 1 + v *= 2 + end + shift = band(shift, 31) + if shift > 0 and band(fflags, FLOAT_SHIFT_ONES) ~= 0 then + v += P2[shift + 1] - 1 + end + end + mant = band(v % TWO32, 0x7FFFFF) + e = band(exp, 255) + end + end + if R then + st.crcx = (st.crcx * 27 + mant * 9 + e * 3 + sign) % TWO32 + end + local sc = st.scratch + writeu32(sc, 0, sign * 2147483648 + e * 8388608 + mant) + return readf32(sc, 0) +end + +-- fixup_samples + false stereo + interleave +@native local function emit(st: State, flags: number, n: number, d: number, P: { number }, c0: number, C: number, lossy: boolean) + local W = st.W + local s = if d == D2 then 2 else 1 + local count = n * s + local R: Reader? = if st.wvx then st.R3 else nil + if band(flags, FLOAT) ~= 0 then + for k = 0, count - 1 do + W[d + k] = floatValue(st, W[d + k], R) + end + else + local shift = band(rshift(flags, 13), 31) + if band(flags, INT32) ~= 0 then + local sent, zeros, ones, dups = band(st.isent, 31), band(st.izeros, 31), band(st.iones, 31), band(st.idups, 31) + if R then + local maxw = st.imaxw + local crc = st.crcx + for k = d, d + count - 1 do + local v = W[k] + if sent > 0 then + if maxw > 0 then + local pv = if v < 0 then -v - 1 else v + local width = (32 - countlz(pv)) + sent + local btr = sent + if width > maxw then + btr -= width - maxw + end + if width <= maxw or btr > 0 then + v = (v * P2[btr + 1] + bits(R, btr)) * P2[sent - btr + 1] + else + v *= P2[sent + 1] + end + else + v = v * P2[sent + 1] + bits(R, sent) + end + end + if zeros > 0 then + v *= P2[zeros + 1] + elseif ones > 0 then + v = (v + 1) * P2[ones + 1] - 1 + elseif dups > 0 then + local lo = v % 2 + v = (v + lo) * P2[dups + 1] - lo + end + v %= TWO32 + if v >= 2147483648 then + v -= TWO32 + end + crc = (crc * 9 + (v % 65536) * 3 + (v // 65536) % 65536) % TWO32 + W[k] = v + end + st.crcx = crc + elseif sent == 0 and zeros + ones + dups > 0 then + while lossy and band(flags, 3) == 3 and shift < 8 do + if zeros > 0 then + zeros -= 1 + elseif ones > 0 then + ones -= 1 + elseif dups > 0 then + dups -= 1 + else + break + end + shift += 1 + end + for k = d, d + count - 1 do + local v = W[k] + if zeros > 0 then + v *= P2[zeros + 1] + elseif ones > 0 then + v = (v + 1) * P2[ones + 1] - 1 + elseif dups > 0 then + local lo = v % 2 + v = (v + lo) * P2[dups + 1] - lo + end + W[k] = v + end + else + shift += zeros + sent + ones + dups + end + end + shift = band(shift, 31) + if lossy then + local bytes = band(flags, 3) + local top = if bytes == 0 then 127 elseif bytes == 1 then 32767 elseif bytes == 2 then 8388607 else 2147483647 + local minv, maxv = (-top - 1) // P2[shift + 1], top // P2[shift + 1] + local mul = P2[shift + 1] + for k = d, d + count - 1 do + local v = W[k] + if v < minv then + v = minv + elseif v > maxv then + v = maxv + end + W[k] = v * mul + end + elseif shift > 0 then + local mul = P2[shift + 1] + for k = d, d + count - 1 do + W[k] *= mul + end + end + end + if s == 2 then + if c0 == 0 and C == 2 then + for k = 0, count - 1 do + P[k + 1] = W[d + k] + end + elseif c0 + 2 <= C then + for i = 0, n - 1 do + P[i * C + c0 + 1] = W[d + 2 * i] + P[i * C + c0 + 2] = W[d + 2 * i + 1] + end + else + for i = 0, n - 1 do + P[i * C + c0 + 1] = W[d + 2 * i] + end + end + elseif band(flags, FALSE_STEREO) ~= 0 and c0 + 2 <= C then + for i = 0, n - 1 do + local v = W[d + i] + P[i * C + c0 + 1] = v + P[i * C + c0 + 2] = v + end + elseif C == 1 then + for k = 0, n - 1 do + P[k + 1] = W[d + k] + end + else + for i = 0, n - 1 do + P[i * C + c0 + 1] = W[d + i] + end + end +end + +@native function Block.decode(st: State, buf: buffer, p: number, size: number, P: { number }, c0: number, C: number, cbuf: buffer?, cp: number?, csize: number?): (number?, string?) + local version = readu16(buf, p + 8) + local n = readu32(buf, p + 20) + local flags = readu32(buf, p + 24) + local crcWant = readu32(buf, p + 28) + if band(flags, DSD) ~= 0 then + return nil, "unsupported: DSD audio" + end + if version < 0x402 or version > 0x410 then + return nil, "unsupported: stream version " .. version + end + if n > MAX_SAMPLES then + return nil, "limit: block of " .. n .. " samples" + end + if band(flags, MONO_FLAG + FALSE_STEREO) == MONO_FLAG + FALSE_STEREO then + return nil, "bad block flags" + end + local mm, merr = Block.meta(buf, p, size) + if not mm then + return nil, merr + end + local m: Meta = mm + local cm: Meta = {} + local cb: buffer = buf + local hasC = false + if cbuf and cp and csize then + local cmeta, cerr = Block.meta(cbuf, cp, csize) + if not cmeta then + return nil, cerr + end + cm, cb, hasC = cmeta, cbuf, true + crcWant = readu32(cbuf, cp + 28) + end + st.nterms = 0 + local sA, sB, wA, wB = st.sA, st.sB, st.wA, st.wB + for k = 1, 128 do + sA[k], sB[k] = 0, 0 + end + for t = 1, 16 do + wA[t], wB[t] = 0, 0 + end + local med = st.med + for k = 1, 6 do + med[k] = 0 + end + st.slow[1], st.slow[2], st.limit[1], st.limit[2] = 0, 0, 0, 0 + st.bacc[1], st.bacc[2], st.bdelta[1], st.bdelta[2] = 0, 0, 0, 0 + st.sacc[1], st.sacc[2], st.sdelta[1], st.sdelta[2], st.err[1], st.err[2] = 0, 0, 0, 0, 0, 0 + st.fflags, st.fshift, st.fmaxexp, st.fminzeros, st.fmaxones = 0, 0, 0, 0, 0 + st.isent, st.izeros, st.iones, st.idups, st.imaxw = 0, 0, 0, 0, 0 + st.hz, st.ho, st.za = 0, 0, 0 + st.crcx = TWO32 - 1 + st.wvc, st.wvx = false, false + local e = readMeta(st, buf, m, flags, version) + if e then + return nil, e + end + if hasC then + e = readMeta(st, cb, cm, flags, version) + if e then + return nil, e + end + end + local mono = band(flags, MONO_FLAG + FALSE_STEREO) ~= 0 + local out = if band(flags, MONO_FLAG) ~= 0 then 1 else 2 + if n == 0 then + return out, nil + end + local o = m[0xA] + if not o or m[0xA + 256] == 0 or m[0xA + 256] % 2 == 1 then + return nil, "no audio bitstream" + end + openReader(st.R1, buf, o, m[0xA + 256]) + if hasC then + local co = cm[0xB] + if co and cm[0xB + 256] > 0 and cm[0xB + 256] % 2 == 0 then + openReader(st.R2, cb, co, cm[0xB + 256]) + st.wvc = true + end + end + -- the wvx stream: in the wv block (pure lossless) or the wvc block (hybrid lossless) + local xb, xm = buf, m + if hasC and (cm[0xC] or cm[0x2C]) then + xb, xm = cb, cm + end + local xid = if xm[0x2C] then 0x2C elseif xm[0xC] then 0xC else nil + if xid then + local xo, xl = xm[xid], xm[xid + 256] + if xl <= 4 or xl % 2 == 1 then + return nil, "bad wvx bitstream" + end + st.crcwvx = readu32(xb, xo) + openReader(st.R3, xb, xo + 4, xl - 4) + st.wvx = true + if xid == 0x2C then + if band(flags, FLOAT) ~= 0 then + st.fminzeros = bits(st.R3, 5) + st.fmaxones = bits(st.R3, 5) + else + st.imaxw = bits(st.R3, 5) + end + end + end + local hybrid = band(flags, HYBRID) ~= 0 + local d = if mono then D1 else D2 + local W = st.W + if #W < d + 2 * n then + W = table.create(d + 2 * n + 64, 0) + st.W = W + end + local crc = TWO32 - 1 + if not st.wvc then + if hybrid then + if mono then + for i = 0, n - 1 do + local v = getWord(st, 0, flags, true) + if not v then + return nil, "bad audio bitstream" + end + W[d + i] = v + end + else + for i = 0, n - 1 do + local l = getWord(st, 0, flags, false) + local r = l and getWord(st, 1, flags, false) + if not l or not r then + return nil, "bad audio bitstream" + end + W[d + 2 * i], W[d + 2 * i + 1] = l, r + end + end + elseif not wordsLossless(st, if mono then n else 2 * n, d) then + return nil, "bad audio bitstream" + end + if mono then + passesMono(st, n) + for k = d, d + n - 1 do + crc = (crc * 3 + W[k]) % TWO32 + end + else + passesStereo(st, n) + local last = d + 2 * n - 2 + if band(flags, JOINT) ~= 0 then + for k = d, last, 2 do + local l = W[k] + local r = W[k + 1] - l // 2 + l += r + W[k], W[k + 1] = l, r + crc = (crc * 9 + l * 3 + r) % TWO32 + end + else + for k = d, last, 2 do + crc = (crc * 9 + W[k] * 3 + W[k + 1]) % TWO32 + end + end + end + else + local ok = if mono then hybridMono(st, n, flags) else hybridStereo(st, n, flags) + if not ok then + return nil, "bad audio bitstream" + end + crc = st.crcv + end + if st.R1.p > st.R1.e or (st.wvc and st.R2.p > st.R2.e) then + return nil, "truncated audio bitstream" + end + if crc ~= crcWant then + return nil, "checksum: block CRC mismatch" + end + emit(st, flags, n, d, P, c0, C, hybrid and not st.wvc) + if st.wvx and (st.R3.p > st.R3.e or st.crcx ~= st.crcwvx) then + return nil, "checksum: wvx CRC mismatch" + end + return out, nil +end + +Block.bits = bits +Block.bit = bit + +return Block +end +__FILES["codecs/audio/WavPack/Tables"] = @native function() + + + +-- codecs/audio/WavPack/Tables: the log2 / exp2 tables, wp_log2, wp_exp2s, restore_weight. Ported from WavPack 5.9.0 +-- entropy_utils.c (David Bryant, BSD 3-clause, licenses/wavpack-LICENSE.txt). +local band, rshift, lshift, countlz = bit32.band, bit32.rshift, bit32.lshift, bit32.countlz + +local Tables = {} + +local LOG2: { number } = { + 0, 1, 3, 4, 6, 7, 9, 10, 11, 13, 14, 16, 17, 18, 20, 21, 22, 24, 25, 26, 28, 29, 30, 32, 33, 34, 36, 37, 38, 40, 41, 42, + 44, 45, 46, 47, 49, 50, 51, 52, 54, 55, 56, 57, 59, 60, 61, 62, 63, 65, 66, 67, 68, 69, 71, 72, 73, 74, 75, 77, 78, 79, 80, 81, + 82, 84, 85, 86, 87, 88, 89, 90, 92, 93, 94, 95, 96, 97, 98, 99, 100, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 116, 117, + 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, + 150, 151, 152, 153, 154, 155, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 178, + 179, 180, 181, 182, 183, 184, 185, 185, 186, 187, 188, 189, 190, 191, 192, 192, 193, 194, 195, 196, 197, 198, 198, 199, 200, 201, 202, 203, 203, 204, 205, 206, + 207, 208, 208, 209, 210, 211, 212, 212, 213, 214, 215, 216, 216, 217, 218, 219, 220, 220, 221, 222, 223, 224, 224, 225, 226, 227, 228, 228, 229, 230, 231, 231, + 232, 233, 234, 234, 235, 236, 237, 238, 238, 239, 240, 241, 241, 242, 243, 244, 244, 245, 246, 247, 247, 248, 249, 249, 250, 251, 252, 252, 253, 254, 255, 255, +} +local EXP2: { number } = { + 0, 1, 1, 2, 3, 3, 4, 5, 6, 6, 7, 8, 8, 9, 10, 11, 11, 12, 13, 14, 14, 15, 16, 16, 17, 18, 19, 19, 20, 21, 22, 22, + 23, 24, 25, 25, 26, 27, 28, 29, 29, 30, 31, 32, 32, 33, 34, 35, 36, 36, 37, 38, 39, 40, 40, 41, 42, 43, 44, 44, 45, 46, 47, 48, + 48, 49, 50, 51, 52, 53, 53, 54, 55, 56, 57, 58, 58, 59, 60, 61, 62, 63, 64, 65, 65, 66, 67, 68, 69, 70, 71, 72, 72, 73, 74, 75, + 76, 77, 78, 79, 80, 81, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, + 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 135, 136, 137, 138, + 139, 140, 141, 142, 143, 144, 145, 146, 147, 149, 150, 151, 152, 153, 154, 155, 156, 157, 159, 160, 161, 162, 163, 164, 165, 166, 168, 169, 170, 171, 172, 173, + 175, 176, 177, 178, 179, 180, 182, 183, 184, 185, 186, 188, 189, 190, 191, 192, 194, 195, 196, 197, 198, 200, 201, 202, 203, 205, 206, 207, 208, 210, 211, 212, + 214, 215, 216, 217, 219, 220, 221, 222, 224, 225, 226, 228, 229, 230, 232, 233, 234, 236, 237, 238, 240, 241, 242, 244, 245, 246, 248, 249, 250, 252, 253, 255, +} + +@native function Tables.exp2s(lg: number): number + if lg < 0 then + local v = Tables.exp2s(-lg) + v = -(if v >= 2147483648 then v - 4294967296 else v) + return if v >= 2147483648 then v - 4294967296 else v + end + local value = bit32.bor(EXP2[band(lg, 255) + 1], 0x100) + local k = lg // 256 + local r = if k <= 9 then rshift(value, 9 - k) else lshift(value, band(k - 9, 31)) + return if r >= 2147483648 then r - 4294967296 else r +end + +@native function Tables.log2(v: number): number + v = (v + rshift(v, 9)) % 4294967296 + if v < 256 then + local dbits = 32 - countlz(v) + return dbits * 256 + LOG2[band(lshift(v, 9 - dbits), 255) + 1] + end + local dbits = 32 - countlz(v) + return dbits * 256 + LOG2[band(rshift(v, dbits - 9), 255) + 1] +end + +@native function Tables.restoreWeight(w: number): number + local r = w * 8 + if r > 0 then + r += (r + 64) // 128 + end + return r +end + +return Tables +end +end + + + + + + Tracker + --!optimize 2 +--!nocheck +-- rosetta chunk Tracker (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 6 modules (4 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["codecs/audio/Tracker"] = function() + +-- codecs/audio/Tracker: the shared tracker engine behind music/mod, s3m, xm and it, and the formats mapped onto them. +-- Written 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. +-- +-- Pattern cells are 5 bytes: note, instrument, volume column, effect, parameter. Notes: 0 none, 1..120 (1 = C-0; C-4 = 49 +-- plays an XM / MOD sample at its base rate, C-5 = 61 an S3M / IT sample at its C5 speed), 253 note fade, 254 note cut, +-- 255 key off. MOD / XM effects 0..35 (XM letters G.. = 16..), XM volume byte as stored; S3M / IT effects 1..26 (A = 1), +-- S3M volume 0 = none else volume + 1, IT volume byte + 1 (0 = none). Extension effects (Tracker.EXT): 0x40 / 0x41 note +-- slide up / down, 0x42 / 0x43 with retrigger (param = ticks per step << 4 | semitones), 0x44 / 0x45 auto portamento +-- up / down (669), 0x46 frequency adjust (+ param * 80 Hz, 669), 0x47 / 0x48 / 0x49 tempo 256 / 512 / 768 + param (MED). +-- +-- Pitch: linear P = (ref - note) * 64 - transpose, frequency = base * 2^(-P/768). Amiga: P = 1712 * 8363 / base * +-- 2^(Plinear / 768), frequency = 8363 * 1712 / P (FT2 / ST3 period units; slides add 4 per effect unit in both). +-- MOD / XM: base 8363, ref 49, transpose = relativeNote * 64 + finetune / 2; S3M / IT: base = c5speed, ref 61. +local Err = __include("core/Err") +local Types = __include("Types") +local Player = __include("codecs/audio/Tracker/Player") +local Mixer = __include("codecs/audio/Tracker/Mixer") +local Pcm = __include("codecs/audio/Tracker/Pcm") +local Tables = __include("codecs/audio/Tracker/Tables") + +local Tracker = {} + +Tracker.Pcm = Pcm +Tracker.Tables = Tables + +type Envelope = { + enabled: boolean, + ticks: { number }, + values: { number }, + loop: boolean, + loopStart: number, + loopEnd: number, + sustain: boolean, + susStart: number, + susEnd: number, + carry: boolean?, + filter: boolean?, + raw: any?, +} + +type Pattern = { rows: number, data: buffer } + +type RenderOptions = { + sampleRate: number?, + interpolation: ("linear" | "none")?, + stereoSeparation: number?, + loop: boolean?, + maxDuration: number?, +} + +local CELL = 5 + +Tracker.EXT = Player.EXT + +Tracker.st2Tempo = Tables.st2Tempo + +local FAMILIES = { mod = true, s3m = true, xm = true, it = true } + +function Tracker.family(m: any): string? + local f = m.engine or m.format + return if type(f) == "string" and FAMILIES[f] then f else nil +end + +function Tracker.newModule(format: string, channels: number, engine: string?): any + local fam = engine or format + local m = { + kind = "music", + format = format, + engine = engine, + title = "", + channels = channels, + speed = 6, + tempo = 125, + globalVolume = 128, + mixVolume = 48, + order = {}, + restart = 0, + linear = fam == "xm" or fam == "it", + instrumentMode = fam == "xm" or fam == "it", + flags = {}, + channelPan = {}, + channelVolume = {}, + channelMute = {}, + patterns = {}, + instruments = {}, + samples = {}, + meta = {}, + render = Tracker.renderMethod, + } + for i = 1, channels do + m.channelVolume[i] = 64 + if fam == "mod" then + local k = (i - 1) % 4 + m.channelPan[i] = if k == 0 or k == 3 then 64 else 192 -- the Amiga's L R R L, at OpenMPT's default width + else + m.channelPan[i] = 128 + end + end + return m +end + +function Tracker.newPattern(rows: number, channels: number): Pattern + return { rows = rows, data = buffer.create(rows * channels * CELL) } +end + +function Tracker.newSample(name: string?): any + return { + name = name or "", + data = buffer.create(0), + length = 0, + channels = 1, + bits = 8, + loopStart = 0, + loopEnd = 0, + loopType = 0, + susStart = 0, + susEnd = 0, + susType = 0, + volume = 64, + globalVolume = 64, + pan = nil :: number?, + c5speed = 8363, + relativeNote = 0, + finetune = 0, + vibType = 0, + vibSweep = 0, + vibDepth = 0, + vibRate = 0, + } +end + +function Tracker.newEnvelope(): Envelope + return { enabled = false, ticks = {}, values = {}, loop = false, loopStart = 1, loopEnd = 1, sustain = false, susStart = 1, susEnd = 1 } +end + +function Tracker.newInstrument(name: string?): any + local sm, nm = table.create(120, 0), table.create(120, 0) + for i = 1, 120 do + nm[i] = i + end + return { + name = name or "", + sampleMap = sm, + noteMap = nm, + volEnv = nil :: Envelope?, + panEnv = nil :: Envelope?, + pitchEnv = nil :: Envelope?, + fadeout = 0, + nna = 0, + dct = 0, + dca = 0, + globalVolume = 128, + pan = nil :: number?, + pps = 0, + ppc = 60, + cutoff = nil :: number?, + resonance = nil :: number?, + vibType = 0, + vibSweep = 0, + vibDepth = 0, + vibRate = 0, + } +end + +function Tracker.cell(m: any, pattern: number, row: number, channel: number): (number?, number, number, number, number) + local p = m.patterns[pattern + 1] + if not p or row < 0 or row >= p.rows or channel < 1 or channel > m.channels then + return nil, 0, 0, 0, 0 + end + local o = (row * m.channels + channel - 1) * CELL + local d = p.data + return buffer.readu8(d, o), buffer.readu8(d, o + 1), buffer.readu8(d, o + 2), buffer.readu8(d, o + 3), buffer.readu8(d, o + 4) +end + +function Tracker.setCell(m: any, pattern: number, row: number, channel: number, note: number, ins: number, vol: number, fx: number, param: number): boolean + local p = m.patterns[pattern + 1] + if not p or row < 0 or row >= p.rows or channel < 1 or channel > m.channels then + return false + end + local o = (row * m.channels + channel - 1) * CELL + local d = p.data + buffer.writeu8(d, o, note % 256) + buffer.writeu8(d, o + 1, ins % 256) + buffer.writeu8(d, o + 2, vol % 256) + buffer.writeu8(d, o + 3, fx % 256) + buffer.writeu8(d, o + 4, param % 256) + return true +end + +local function num(v: any, lo: number, hi: number): boolean + return type(v) == "number" and v == v and v >= lo and v <= hi +end + +local function fixEnvelope(e: any): (any, string?) + if e == nil then + return nil + end + if type(e) ~= "table" or type(e.ticks) ~= "table" or type(e.values) ~= "table" then + return nil, "bad envelope" + end + local n = math.min(#e.ticks, #e.values) + local last = -1 + for i = 1, n do + local t, v = e.ticks[i], e.values[i] + if not num(t, 0, 1e6) or not num(v, -64, 64) or t <= last then + -- points must go forward: keep the valid prefix + n = i - 1 + break + end + last = t + end + for i = #e.ticks, n + 1, -1 do + e.ticks[i] = nil + end + for i = #e.values, n + 1, -1 do + e.values[i] = nil + end + if n == 0 then + e.enabled = false + end + local function idx(v: any): number + return if num(v, 1, math.max(1, n)) then math.floor(v) else 1 + end + e.loopStart, e.loopEnd = idx(e.loopStart), idx(e.loopEnd) + e.susStart, e.susEnd = idx(e.susStart), idx(e.susEnd) + if e.loopEnd < e.loopStart then + e.loop = false + end + if e.susEnd < e.susStart then + e.sustain = false + end + return e +end + +local function fixLoop(s0: any, e0: any, t0: any, len: number): (number, number, number) + if not num(t0, 0, 2) or t0 == 0 or not num(s0, -2 ^ 52, 2 ^ 52) or not num(e0, -2 ^ 52, 2 ^ 52) then + return 0, 0, 0 + end + local s: number = math.floor(math.clamp(s0, 0, len)) + local e: number = math.floor(math.clamp(e0, 0, len)) + local t: number = math.floor(t0) + if e - s < 1 or t == 0 then + return 0, 0, 0 + end + if t == 2 and e - s < 2 then + t = 1 + end + return s, e, t +end + +function Tracker.validate(m: any): (boolean?, Err.Err?) + if type(m) ~= "table" then + return nil, Err.new(Err.ARG, "not a module") + end + if not Tracker.family(m) then + return nil, Err.new(Err.ARG, "unknown tracker format " .. tostring(m.engine or m.format)) + end + if m.preamp ~= nil and not num(m.preamp, 0, 256) then + m.preamp = nil + end + if not num(m.channels, 1, 128) or m.channels % 1 ~= 0 then + return nil, Err.new(Err.ARG, "bad channel count") + end + if type(m.order) ~= "table" or type(m.patterns) ~= "table" or type(m.samples) ~= "table" then + return nil, Err.new(Err.ARG, "module without order / patterns / samples") + end + m.instruments = if type(m.instruments) == "table" then m.instruments else {} + m.flags = if type(m.flags) == "table" then m.flags else {} + m.channelPan = if type(m.channelPan) == "table" then m.channelPan else {} + m.channelVolume = if type(m.channelVolume) == "table" then m.channelVolume else {} + m.channelMute = if type(m.channelMute) == "table" then m.channelMute else {} + for i = 1, m.channels do + local p = m.channelPan[i] + if p ~= 512 and not num(p, 0, 256) then + m.channelPan[i] = 128 + end + if not num(m.channelVolume[i], 0, 64) then + m.channelVolume[i] = 64 + end + end + m.speed = if num(m.speed, 1, 255) then math.floor(m.speed) else 6 + m.tempo = if num(m.tempo, 1, 1000) then m.tempo else 125 + m.globalVolume = if num(m.globalVolume, 0, 128) then m.globalVolume else 128 + m.mixVolume = if num(m.mixVolume, 0, 256) then m.mixVolume else 48 + m.restart = if num(m.restart, 0, 1e6) then math.floor(m.restart) else 0 + for i, o in m.order do + if not num(o, 0, 255) then + return nil, Err.new(Err.ARG, "bad order entry " .. i) + end + end + for i, p in m.patterns do + if type(p) ~= "table" or not num(p.rows, 1, 1024) or type(p.data) ~= "buffer" or buffer.len(p.data) < p.rows * m.channels * CELL then + return nil, Err.new(Err.ARG, "bad pattern " .. (i - 1)) + end + end + for i, s in m.samples do + if type(s) ~= "table" then + return nil, Err.new(Err.ARG, "bad sample " .. i) + end + local nch = if s.channels == 2 then 2 else 1 + s.channels = nch + if not num(s.length, 0, 2 ^ 31) or type(s.data) ~= "buffer" or buffer.len(s.data) < math.floor(s.length) * nch * 4 then + return nil, Err.new(Err.ARG, "sample " .. i .. ": data shorter than its length") + end + s.length = math.floor(s.length) + s.loopStart, s.loopEnd, s.loopType = fixLoop(s.loopStart or 0, s.loopEnd or 0, s.loopType or 0, s.length) + s.susStart, s.susEnd, s.susType = fixLoop(s.susStart or 0, s.susEnd or 0, s.susType or 0, s.length) + s.volume = if num(s.volume, 0, 64) then s.volume else 64 + s.globalVolume = if num(s.globalVolume, 0, 64) then s.globalVolume else 64 + if s.pan ~= nil and not num(s.pan, 0, 256) then + s.pan = nil + end + s.c5speed = if num(s.c5speed, 1, 1e7) then s.c5speed else 8363 + s.relativeNote = if num(s.relativeNote, -128, 127) then s.relativeNote else 0 + s.finetune = if num(s.finetune, -128, 127) then s.finetune else 0 + end + for i, ins in m.instruments do + if type(ins) ~= "table" or type(ins.sampleMap) ~= "table" or type(ins.noteMap) ~= "table" then + return nil, Err.new(Err.ARG, "bad instrument " .. i) + end + for n = 1, 120 do + if not num(ins.sampleMap[n], 0, 1e6) then + ins.sampleMap[n] = 0 + end + if not num(ins.noteMap[n], 1, 120) then + ins.noteMap[n] = n + end + end + local err + ins.volEnv, err = fixEnvelope(ins.volEnv) + if err then + return nil, Err.new(Err.ARG, "instrument " .. i .. ": " .. err) + end + ins.panEnv, err = fixEnvelope(ins.panEnv) + if err then + return nil, Err.new(Err.ARG, "instrument " .. i .. ": " .. err) + end + ins.pitchEnv, err = fixEnvelope(ins.pitchEnv) + if err then + return nil, Err.new(Err.ARG, "instrument " .. i .. ": " .. err) + end + ins.fadeout = if num(ins.fadeout, 0, 65535) then ins.fadeout else 0 + ins.globalVolume = if num(ins.globalVolume, 0, 128) then ins.globalVolume else 128 + if ins.pan ~= nil and not num(ins.pan, 0, 256) then + ins.pan = nil + end + if ins.cutoff ~= nil and not num(ins.cutoff, 0, 127) then + ins.cutoff = nil + end + if ins.resonance ~= nil and not num(ins.resonance, 0, 127) then + ins.resonance = nil + end + end + return true, nil +end + +local Decoder = {} +Decoder.__index = Decoder + +function Tracker.duration(m: any, opts: RenderOptions?): (number?, Err.Err?) + local ok, err = Tracker.validate(m) + if not ok then + return nil, err + end + local sr = opts and opts.sampleRate or 44100 + local maxFrames = (opts and opts.maxDuration or 3600) * sr + local st = Player.new(m, sr, { stereoSeparation = 100 }) + local frames = 0 + while frames < maxFrames do + local f = Player.tick(st) + if f == 0 and st.ended then + break + end + frames += f + end + return math.min(frames, maxFrames) / sr, nil +end + +local function newPlayer(self: any) + self.st = Player.new(self.module, self.sampleRate, self.opts) + self.st.ramp = math.max(1, math.floor(self.sampleRate * 0.0015)) + self.left = 0 + self.pos = 0 +end + +function Tracker.render(m: any, opts: RenderOptions?): (Types.Decoder?, Err.Err?) + local o: RenderOptions = opts or {} + local sr = o.sampleRate or 44100 + if type(sr) ~= "number" or sr < 1000 or sr > 384000 then + return nil, Err.new(Err.ARG, "sampleRate must be 1000..384000") + end + local seconds, err = Tracker.duration(m, o) + if not seconds then + return nil, err + end + local frames = math.floor(seconds * sr + 0.5) + local self = setmetatable({ + sampleRate = sr, + channels = 2, + frames = frames, + duration = frames / sr, + bitrate = 0, + tags = { title = m.title or "" }, + module = m, + opts = o, + linear = o.interpolation ~= "none", + maxFrames = (o.maxDuration or 3600) * sr, + st = nil :: any, + left = 0, + pos = 0, + }, Decoder) + newPlayer(self) + return self :: any, nil +end + +function Tracker.renderMethod(self: any, opts: RenderOptions?): Types.Decoder + local dec = Tracker.render(self, opts) + return dec :: any +end + +local function run(self: any, out: buffer?, n: number): number + local st = self.st + local done = 0 + while done < n do + if self.left <= 0 then + if self.pos + done >= self.maxFrames then + break + end + local f = Player.tick(st) + if f == 0 and st.ended then + break + end + self.left = f + if f == 0 then + continue + end + end + local k = math.min(self.left, n - done) + Mixer.mix(st, out, done, k, self.linear) + self.left -= k + done += k + end + self.pos += done + return done +end + +function Decoder.read(self: any, n: number, out: buffer?): (buffer, number) + n = math.max(0, math.floor(tonumber(n) or 0)) + local o = out + if o == nil or buffer.len(o) < n * 8 then + o = buffer.create(n * 8) + else + buffer.fill(o, 0, 0, n * 8) + end + local got = run(self, o, n) + return o :: buffer, got +end + +function Decoder.seek(self: any, seconds: number) + local target = math.max(0, math.floor((tonumber(seconds) or 0) * self.sampleRate)) + newPlayer(self) + local chunk = 65536 + while self.pos < target do + local got = run(self, nil, math.min(chunk, target - self.pos)) + if got == 0 then + break + end + end + for _, v in self.st.voices do + v.gl, v.gr = 0, 0 + end +end + +function Decoder.position(self: any): number + return self.pos / self.sampleRate +end + +return Tracker +end +__FILES["codecs/audio/Tracker/Load"] = function() + +-- codecs/audio/Tracker/Load: helpers mapping other tracker formats' effects onto the engine's S3M / IT or MOD / XM families. +-- Ported from OpenMPT's ModCommand helpers (ConvertModCommand, ConvertToVolCommand, FillInTwoCommands, GetEffectWeight, +-- CPattern::WriteEffect; BSD licence, licenses/openmpt-LICENSE.txt). +local Err = __include("core/Err") +local Player = __include("codecs/audio/Tracker/Player") +local Pcm = __include("codecs/audio/Tracker/Pcm") +local Tables = __include("codecs/audio/Tracker/Tables") + +local Load = {} + +local EXT = Player.EXT + +local IT: { [string]: number } = { + speed = 1, + jump = 2, + ["break"] = 3, + volslide = 4, + portadown = 5, + portaup = 6, + toneporta = 7, + vibrato = 8, + tremor = 9, + arpeggio = 10, + vibratovol = 11, + toneportavol = 12, + chanvol = 13, + chanvolslide = 14, + offset = 15, + panslide = 16, + retrig = 17, + tremolo = 18, + s3mex = 19, + tempo = 20, + finevibrato = 21, + globalvol = 22, + globalvolslide = 23, + panning8 = 24, + panbrello = 25, + noteslideup = EXT.NOTE_SLIDE_UP, + noteslidedown = EXT.NOTE_SLIDE_DOWN, + noteslideupretrig = EXT.NOTE_SLIDE_UP_RETRIG, + noteslidedownretrig = EXT.NOTE_SLIDE_DOWN_RETRIG, + autoportaup = EXT.AUTO_PORTA_UP, + autoportadown = EXT.AUTO_PORTA_DOWN, + freqadjust = EXT.FREQ_ADJUST, +} +Load.IT = IT + +-- OpenMPT's effect weights (low to high): which of two effects a cell keeps when only one fits +local WEIGHT: { [string]: number } = {} +for i, n in + { + "none", "keyoff", "tremolo", "finevibrato", "vibrato", "panbrello", "s3mex", "modex", "panslide", "panning8", + "noteslideupretrig", "noteslideup", "noteslidedownretrig", "noteslidedown", "portaup", "autoportaup", + "portadown", "autoportadown", "volslide", "vibratovol", "volume", "volume8", "offset", "tremor", "retrig", + "arpeggio", "toneporta", "toneportavol", "chanvolslide", "chanvol", "globalvolslide", "globalvol", "tempo", + "speed", "jump", "break", + } +do + WEIGHT[n] = i +end + +local GLOBAL = { jump = true, ["break"] = true, speed = true, tempo = true, globalvol = true, globalvolslide = true } + +-- OpenMPT's IsGlobalCommand +function Load.isGlobal(name: string?, param: number): boolean + if name == nil then + return false + end + if GLOBAL[name] then + return true + end + local x = param // 16 + if name == "modex" then + return x == 0 or x == 6 or x == 0xE + elseif name == "s3mex" then + return x == 6 or x == 0xB or x == 0xE + end + return false +end + +-- OpenMPT's ConvertModCommand +local MODFX: { [number]: string } = { + [0] = "arpeggio", [1] = "portaup", [2] = "portadown", [3] = "toneporta", [4] = "vibrato", [5] = "toneportavol", + [6] = "vibratovol", [7] = "tremolo", [8] = "panning8", [9] = "offset", [10] = "volslide", [11] = "jump", + [12] = "volume", [13] = "break", [14] = "modex", [15] = "tempo", [16] = "globalvol", [17] = "globalvolslide", + [20] = "keyoff", [25] = "panslide", [27] = "retrig", [29] = "tremor", +} +function Load.modCommand(cmd: number, param: number): (string?, number) + if cmd == 0 and param == 0 then + return nil, 0 + elseif cmd == 0xF and param < 0x20 then + return "speed", param + end + local n = MODFX[cmd] + if n == "break" then + param = (param // 16) * 10 + param % 16 + end + return n, param +end + +-- OpenMPT's ConvertToVolCommand (force: fit with some loss of precision) +function Load.itVolume(name: string?, param: number, force: boolean): number? + if name == "volume" then + return math.min(param, 64) + 1 + elseif name == "volume8" then + if not force and param % 4 ~= 0 then + return nil + end + return (param + 3) // 4 + 1 + elseif name == "portaup" or name == "portadown" then + if not force and (param % 4 ~= 0 or param >= 0xE0) then + return nil + end + return (if name == "portaup" then 115 else 105) + math.min(param // 4, 9) + 1 + elseif name == "toneporta" then + if param >= 0xF0 then + return 193 + 9 + 1 + end + for n = 0, 9 do + local v = Tables.IT_VOLPORTA[n + 1] + if (force and param <= v) or param == v then + return 193 + n + 1 + end + end + return nil + elseif name == "vibrato" then + if force then + param = math.min(param % 16, 9) + elseif param % 16 > 9 or param >= 16 then + return nil + end + return 203 + param % 16 + 1 + elseif name == "panning8" then + return 128 + (if param == 255 then 64 else param // 4) + 1 + elseif name == "volslide" then + local x, y = param // 16, param % 16 + if param == 0 then + return nil + elseif y == 0 then + return 85 + math.min(x, 9) + 1 + elseif x == 0 then + return 95 + math.min(y, 9) + 1 + elseif y == 0xF then + return 65 + math.min(x, 9) + 1 + elseif x == 0xF then + return 75 + math.min(y, 9) + 1 + end + return nil + elseif name == "s3mex" and param // 16 == 8 then + return 128 + (param % 16) * 4 + 2 + 1 + end + return nil +end + +function Load.itEffect(name: string?, param: number): (number, number) + if name == nil then + return 0, 0 + end + if name == "modex" then + local x, y = param // 16, param % 16 + if x == 1 then + return IT.portaup, 0xF0 + y + elseif x == 2 then + return IT.portadown, 0xF0 + y + elseif x == 9 then + return IT.retrig, y + elseif x == 0xA then + return IT.volslide, y * 16 + 0xF + elseif x == 0xB then + return IT.volslide, 0xF0 + y + end + local s = ({ [3] = 1, [4] = 3, [5] = 2, [6] = 0xB, [7] = 4, [8] = 8, [0xC] = 0xC, [0xD] = 0xD, [0xE] = 0xE })[x] + if s then + return IT.s3mex, s * 16 + y + end + return 0, 0 + end + local code = IT[name] + if code == nil then + return 0, 0 + end + return code, param +end + +-- OpenMPT's FillInTwoCommands +function Load.fillTwo(e1: string?, p1: number, e2: string?, p2: number): (number, string?, number, string?, number) + if e1 ~= nil and e1 == e2 then + e2 = nil -- the same effect twice: keep one (most are absolute; slides are kept once too, a simplification) + end + for n = 0, 3 do + local v = Load.itVolume(e1, p1, n > 1) + if e1 == nil or v then + if v == nil and (e2 == "volume" or e2 == "volume8") then + -- the engine's IT family sets volumes in the volume column only + return Load.itVolume(e2, p2, true) or 0, nil, 0, nil, 0 + end + return v or 0, e2, p2, nil, 0 + end + e1, p1, e2, p2 = e2, p2, e1, p1 + end + if (WEIGHT[e1 :: string] or 0) > (WEIGHT[e2 :: string] or 0) then + e1, p1, e2, p2 = e2, p2, e1, p1 + end + return 0, e2, p2, e1, p1 +end + +-- OpenMPT's CPattern::WriteEffect +function Load.writeEffect(m: any, pattern: number, row: number, fx: number, param: number, retry: string?, channel: number?, multiple: boolean?): boolean + local p = m.patterns[pattern + 1] + if not p then + return false + end + local fam = m.engine or m.format + local modLike = fam == "mod" or fam == "xm" + local nch = m.channels + local d = p.data + local guard = 0 + while row >= 0 and row < p.rows and guard < 1024 do + guard += 1 + local c0, c1 = 1, nch + if channel then + c0, c1 = channel, channel + end + for c = c0, c1 do + local o = (row * nch + c - 1) * 5 + if not multiple and buffer.readu8(d, o + 3) == fx and (fx ~= 0 or not modLike) then + return true + end + end + for c = c0, c1 do + local o = (row * nch + c - 1) * 5 + local f, q = buffer.readu8(d, o + 3), buffer.readu8(d, o + 4) + if f == 0 and (not modLike or q == 0) then + buffer.writeu8(d, o + 3, fx) + buffer.writeu8(d, o + 4, param) + return true + end + end + if retry == "next" then + row += 1 + elseif retry == "prev" then + row -= 1 + else + return false + end + end + return false +end + +function Load.readSample(buf: buffer, offset: number, frames: number, spec: any, s: any, budget: { left: number }): (boolean?, Err.Err?) + local nch = spec.channels or 1 + local bps = spec.bits // 8 + local limit = math.min(spec.limit or buffer.len(buf), buffer.len(buf)) + local avail = math.max(0, limit - offset) // (nch * bps) + local n = math.max(0, math.min(math.floor(frames), avail)) + budget.left -= n * nch * 4 + if budget.left < 0 then + return nil, Err.new(Err.LIMIT, "sample data over the maxBytes limit") + end + local data = Pcm.decode(buf, offset, n, spec) + if not data then + return nil, Err.new(Err.TRUNCATED, "sample data", offset) + end + s.data, s.length, s.bits, s.channels = data, n, spec.bits, nch + return true, nil +end + +-- S3M / MOD pattern breaks store the row as two decimal digits +function Load.bcd(n: number): number + n = math.clamp(math.floor(n), 0, 99) + return (n // 10) * 16 + n % 10 +end + +return Load +end +__FILES["codecs/audio/Tracker/Mixer"] = @native function() + + +-- codecs/audio/Tracker/Mixer: tracker voice mixing (loops, IT sustain loops, IT two-pole resonant filter, click ramps). +-- No third-party code. +local floor, ceil, min = math.floor, math.ceil, math.min +local readf32, writef32 = buffer.readf32, buffer.writef32 + +local Mixer = {} + +@native local function mixVoice(v: any, out: buffer?, off: number, n: number, linear: boolean, ramp: number) + local data: buffer = v.data + local nch = v.nch + local inc = v.inc + if not (inc > 0 and inc < 1e6) then + return + end + local len = v.len + local hi = len - 1 + local i = 0 + local guard = 0 + while i < n do + guard += 1 + if guard > n + 64 then + return + end + local s, e, t + if v.keyOn and v.susT > 0 then + s, e, t = v.susS, v.susE, v.susT + elseif v.loopT > 0 then + s, e, t = v.loopS, v.loopE, v.loopT + else + s, e, t = 0, len, 0 + end + local p = v.p + local dir = v.dir + local count + if dir > 0 then + local lim = if t == 2 then e - 1 else e + if p >= lim then + if t == 0 then + v.active = false + return + elseif t == 1 then + p = s + (p - e) % (e - s) + else + p = 2 * (e - 1) - p + if p < s then + p = s + end + v.dir = -1 + end + v.p = p + continue + end + count = ceil((lim - p) / inc) + else + if p < s then + p = 2 * s - p + if p > e - 1 then + p = e - 1 + end + v.p = p + v.dir = 1 + continue + end + count = floor((p - s) / inc) + 1 + end + if count < 1 then + count = 1 + end + local m = min(n - i, count) + local step = inc * dir + if out == nil then + v.p = p + step * m + i += m + continue + end + local wrapJ = if t == 1 then s else e - 1 + local gl, gr = v.gl, v.gr + local rl = v.rampN + local dl, dr = 0, 0 + local tl, tr = v.tl, v.tr + if rl > 0 then + dl, dr = (tl - gl) / rl, (tr - gr) / rl + end + local fOn = v.fOn + local fa, fb0, fb1 = v.fa, v.fb0, v.fb1 + local y1l, y2l, y1r, y2r = v.y1l, v.y2l, v.y1r, v.y2r + local o = (off + i) * 8 + for _ = 1, m do + local idx = floor(p) + if idx > hi then + idx = hi + elseif idx < 0 then + idx = 0 + end + local j = idx + 1 + if j >= e then + j = wrapJ + end + if j > hi then + j = hi + end + local xl, xr + if nch == 1 then + local a = readf32(data, idx * 4) + if linear then + local b = readf32(data, j * 4) + xl = a + (b - a) * (p - idx) + else + xl = a + end + if fOn then + local y = xl * fa + y1l * fb0 + y2l * fb1 + y2l, y1l = y1l, y + xl = y + end + xr = xl + else + local al = readf32(data, idx * 8) + local ar = readf32(data, idx * 8 + 4) + if linear then + local f = p - idx + xl = al + (readf32(data, j * 8) - al) * f + xr = ar + (readf32(data, j * 8 + 4) - ar) * f + else + xl, xr = al, ar + end + if fOn then + local y = xl * fa + y1l * fb0 + y2l * fb1 + y2l, y1l = y1l, y + xl = y + y = xr * fa + y1r * fb0 + y2r * fb1 + y2r, y1r = y1r, y + xr = y + end + end + if rl > 0 then + gl += dl + gr += dr + rl -= 1 + if rl == 0 then + gl, gr = tl, tr + end + end + writef32(out, o, readf32(out, o) + xl * gl) + writef32(out, o + 4, readf32(out, o + 4) + xr * gr) + o += 8 + p += step + end + v.p = p + v.gl, v.gr, v.rampN = gl, gr, rl + v.y1l, v.y2l, v.y1r, v.y2r = y1l, y2l, y1r, y2r + i += m + end + local _ = ramp +end + +@native function Mixer.mix(st: any, out: buffer?, off: number, n: number, linear: boolean) + for _, v in st.voices do + if v.active and v.data then + mixVoice(v, out, off, n, linear, 0) + end + end +end + +return Mixer +end +__FILES["codecs/audio/Tracker/Pcm"] = @native function() + + +-- codecs/audio/Tracker/Pcm: raw 8 / 16-bit tracker sample data (signed / unsigned, XM / IT 2.15 delta coding, +-- interleaved or planar stereo) <-> f32. +local readu8, readi8, readu16, readi16 = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16 +local writef32, readf32, writeu8, writei16 = buffer.writef32, buffer.readf32, buffer.writeu8, buffer.writei16 +local floor = math.floor + +local Pcm = {} + +type Spec = { + bits: number, + signed: boolean, + delta: boolean?, -- each value is the difference to the previous one (XM, IT 2.15 "delta" flag) + channels: number?, + planar: boolean?, -- stereo stored as all left then all right (XM, IT); default interleaved + bigEndian: boolean?, +} + +@native function Pcm.bytes(frames: number, spec: Spec): number + return frames * (spec.channels or 1) * (spec.bits // 8) +end + +@native function Pcm.decode(buf: buffer, off: number, frames: number, spec: Spec): buffer? + local nch = spec.channels or 1 + local bps = spec.bits // 8 + local total = frames * nch + if frames < 0 or off < 0 or off + total * bps > buffer.len(buf) then + return nil + end + local out = buffer.create(total * 4) + local planar = spec.planar and nch == 2 + for c = 0, nch - 1 do + local acc = 0 + for i = 0, frames - 1 do + local k = if planar then c * frames + i else i * nch + c + local v + if bps == 1 then + if spec.signed then + v = readi8(buf, off + k) + else + v = readu8(buf, off + k) - 128 + end + if spec.delta then + acc = (acc + v + 128) % 256 - 128 + v = acc + end + writef32(out, (i * nch + c) * 4, v / 128) + else + local p = off + k * 2 + if spec.bigEndian then + v = readu8(buf, p) * 256 + readu8(buf, p + 1) + if spec.signed and v >= 32768 then + v -= 65536 + end + elseif spec.signed then + v = readi16(buf, p) + else + v = readu16(buf, p) + end + if not spec.signed then + v -= 32768 + end + if spec.delta then + acc = (acc + v + 32768) % 65536 - 32768 + v = acc + end + writef32(out, (i * nch + c) * 4, v / 32768) + end + end + end + return out +end + +@native function Pcm.encode(samples: buffer, frames: number, spec: Spec): buffer + local nch = spec.channels or 1 + local bps = spec.bits // 8 + local out = buffer.create(frames * nch * bps) + local planar = spec.planar and nch == 2 + local avail = buffer.len(samples) // 4 + for c = 0, nch - 1 do + local prev = 0 + for i = 0, frames - 1 do + local si = i * nch + c + local x = if si < avail then readf32(samples, si * 4) else 0 + local k = if planar then c * frames + i else i * nch + c + if bps == 1 then + local v = math.clamp(floor(x * 128 + 0.5), -128, 127) + local w = v + if spec.delta then + w = (v - prev) % 256 + prev = v + else + w = if spec.signed then v % 256 else v + 128 + end + writeu8(out, k, w) + else + local v = math.clamp(floor(x * 32768 + 0.5), -32768, 32767) + local w = v + if spec.delta then + w = (v - prev + 32768) % 65536 - 32768 + prev = v + elseif not spec.signed then + w = v + 32768 + if w >= 32768 then + w -= 65536 + end + end + writei16(out, k * 2, w) + end + end + end + return out +end + +@native function Pcm.bitsNeeded(samples: buffer): number + for i = 0, buffer.len(samples) // 4 - 1 do + local x = readf32(samples, i * 4) * 128 + if x ~= floor(x) then + return 16 + end + end + return 8 +end + +return Pcm +end +__FILES["codecs/audio/Tracker/Player"] = @native function() + + +-- codecs/audio/Tracker/Player: the tracker sequencer for the MOD, S3M, XM and IT effect families. +-- 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. +local Tables = __include("codecs/audio/Tracker/Tables") + +local wave64, autoWave = Tables.wave64, Tables.autoWave +local AMIGA = Tables.AMIGA +local AMIGA_PAL = Tables.AMIGA_PAL +local floor, min, max, clamp, abs = math.floor, math.min, math.max, math.clamp, math.abs +local readu8 = buffer.readu8 + +local Player = {} + +local MOD, S3M, XM, IT = 1, 2, 3, 4 +Player.MOD, Player.S3M, Player.XM, Player.IT = MOD, S3M, XM, IT +local FAMILY = { mod = MOD, s3m = S3M, xm = XM, it = IT } + +local EXT = { + NOTE_SLIDE_UP = 0x40, + NOTE_SLIDE_DOWN = 0x41, + NOTE_SLIDE_UP_RETRIG = 0x42, + NOTE_SLIDE_DOWN_RETRIG = 0x43, + AUTO_PORTA_UP = 0x44, + AUTO_PORTA_DOWN = 0x45, + FREQ_ADJUST = 0x46, + TEMPO_256 = 0x47, -- set the tempo to 256 + param (0x48: 512 + param, 0x49: 768 + param) +} +Player.EXT = EXT + +local BG_VOICES = 64 + +@native local function newVoice(): any + return { + active = false, + chan = 0, + bg = false, + data = nil :: buffer?, + nch = 1, + len = 0, + loopS = 0, + loopE = 0, + loopT = 0, + susS = 0, + susE = 0, + susT = 0, + p = 0, + dir = 1, + inc = 0, + smp = nil :: any, + smpIdx = 0, + ins = nil :: any, + insIdx = 0, + note = 0, + vol = 0, + pan = 128, + chanVol = 64, + period = 0, + periodOut = 0, + base = 8363, + keyOn = true, + fading = false, + fade = 65536, + volEnvPos = 0, + panEnvPos = 0, + pitchEnvPos = 0, + volEnvOn = true, + panEnvOn = true, + pitchEnvOn = true, + envVol = 64, + envPan = 0, + envPitch = 0, + avPos = 0, + avAmp = 0, + gl = 0, + gr = 0, + tl = 0, + tr = 0, + started = false, + cutoff = 127, + reso = 0, + fOn = false, + fa = 1, + fb0 = 0, + fb1 = 0, + y1l = 0, + y2l = 0, + y1r = 0, + y2r = 0, + tremorMute = false, + surround = false, + rampN = 0, + owner = 0, + order = 0, + } +end + +@native local function newChannel(i: number, pan: number, vol: number): any + return { + idx = i, + voice = nil :: any, + note = 0, + realNote = 0, + insIdx = 0, + smpIdx = 0, + smp = nil :: any, + vol = 0, + pan = pan, + basePan = pan, + chanVol = vol, + period = 0, + target = 0, + portaSpeed = 0, + base = 8363, + finetune = nil :: number?, + fx = 0, + param = 0, + vcmd = 0, + mPortaUp = 0, + mPortaDn = 0, + mFineUp = 0, + mFineDn = 0, + mXFineUp = 0, + mXFineDn = 0, + mVolSlide = 0, + mFineVolUp = 0, + mFineVolDn = 0, + mOffset = 0, + mHighOffset = 0, + mPanSlide = 0, + mGVolSlide = 0, + mRetrig = 0, + mTremor = 0, + mArp = 0, + mS3M = 0, + mEF = 0, + mChanVolSlide = 0, + mTempo = 0, + mVolCol = 0, + mS = 0, + vibSpeed = 0, + vibDepth = 0, + vibPos = 0, + vibWave = 0, + tremSpeed = 0, + tremDepth = 0, + tremPos = 0, + tremWave = 0, + panbSpeed = 0, + panbDepth = 0, + panbPos = 0, + panbWave = 0, + vibDelta = 0, + tremDelta = 0, + panbDelta = 0, + arp = 0, + loopRow = 0, + loopCount = 0, + retrigCount = 0, + tremorCount = 0, + tremorOn = true, + delayTick = -1, + dNote = 0, + dIns = 0, + dVol = 0, + cutTick = -1, + keyOffTick = -1, + nna = -1, + surround = false, + cutoff = 127, + reso = 0, + volEnvOn = true, + panEnvOn = true, + pitchEnvOn = true, + muted = false, + triggered = false, + autoPorta = 0, -- auto portamento (EXT 0x44 / 0x45): period units per tick, + down + autoTone = false, + hzAdd = 0, -- EXT 0x46: Hz added to the frequency (669) + slideCount = 0, + mNoteSlide = 0, + tonePortaRow = false, + } +end + +@native function Player.new(m: any, sampleRate: number, opts: any): any + local fmt = FAMILY[m.engine or m.format] or MOD + local flags = m.flags + local ptPeriods = fmt == MOD or flags.periods == "amiga" + local st: any = { + m = m, + fmt = fmt, + sr = sampleRate, + nch = m.channels, + speed = m.speed, + tempo = m.tempo, + gvol = m.globalVolume, + linear = m.linear, + insMode = m.instrumentMode and #m.instruments > 0, + oldFx = m.flags.oldEffects or false, + compatG = m.flags.compatGxx or false, + fastSlides = flags.fastSlides or false, + amigaLimits = flags.amigaLimits or false, + ptPeriods = ptPeriods, + hz = flags.periods == "hz", + hzScale = if type(flags.hzSlide) == "number" then flags.hzSlide else 1, + hzTone = if type(flags.hzTonePorta) == "number" then flags.hzTonePorta else 1, + fastPortas = flags.fastPortas or false, + autoTonePorta = flags.autoTonePorta or false, + autoReset = flags.autoReset or false, + st2Tempo = flags.st2Tempo or false, + oktSlides = flags.oktSlides or false, + ft2Pan = flags.panLaw == "ft2", + envHold = flags.envRowHold or false, + ord = 0, + row = 0, + tick = 0, + pat = nil :: any, + patIdx = -1, + patDelay = 0, + patDelayRep = 0, + fineDelay = 0, + jumpOrd = -1, + ft2BreakPos = 0, + breakRow = -1, + loopJump = -1, + ended = false, + visited = {} :: { [number]: boolean }, + chans = {}, + voices = {}, + age = 0, + tickFrames = 0, + frac = 0, + separation = math.clamp((opts and opts.stereoSeparation or 100) / 100, 0, 2), + master = 1, + rows = 0, + ramp = 64, + amiga = if ptPeriods then AMIGA_PAL else AMIGA, + loopAllowed = opts and opts.loop or false, + } + for i = 1, m.channels do + local pan = m.channelPan[i] or 128 + local cv = m.channelVolume[i] or 64 + local c = newChannel(i, pan, cv) + c.basePan = pan + c.muted = m.channelMute[i] or false + if pan == 512 then -- surround marker + c.pan = 128 + c.surround = true + end + st.chans[i] = c + end + for i = 1, m.channels + BG_VOICES do + st.voices[i] = newVoice() + end + st.master = Player.masterGain(m, fmt) + Player.startOrder(st, 0, 0) + return st +end + +-- the output scale per format, calibrated against OpenMPT's default mix levels (tools/fixtures: a full-scale sine at +-- volume 64 on one centred channel) +@native function Player.masterGain(m: any, fmt: number): number + if type(m.preamp) == "number" then + return m.preamp / 128 -- OpenMPT's sample pre-amp, as set by the format's loader + end + if fmt == IT or fmt == S3M then + return (m.mixVolume or 48) / 128 -- OpenMPT: linear in the mix / master volume, 64 = 0.5 + end + if fmt == XM then + return 0.375 -- OpenMPT's XM pre-amp (48 / 128), whatever the channel count + end + -- MOD: OpenMPT scales by the channel count (4 channels: 0.5; 2 / channels between 2 and 8) + return 2 / clamp(m.channels, 2, 8) +end + +@native function Player.startOrder(st: any, ord: number, row: number) + local m = st.m + local order = m.order + local n = #order + local guard = 0 + local o = ord + while true do + guard += 1 + if guard > n + 2 then + st.ended = true + return + end + if o >= n then + o = m.restart or 0 + if o >= n or o < 0 then + o = 0 + end + if n == 0 then + st.ended = true + return + end + end + local p = order[o + 1] + if p == 255 then + o = n -- the end marker: wrap to the restart position + elseif p == 254 or m.patterns[p + 1] == nil then + o += 1 + else + st.ord = o + st.patIdx = p + st.pat = m.patterns[p + 1] + st.row = if row < st.pat.rows then row else 0 + return + end + end +end + +@native local function advanceRow(st: any) + if st.stopAfterRow then + st.ended = true + return + end + local loopRow = st.loopJump + if st.jumpOrd >= 0 or st.breakRow >= 0 then + local o = if st.jumpOrd >= 0 then st.jumpOrd else st.ord + 1 + local r = if st.breakRow >= 0 then st.breakRow else 0 + st.jumpOrd, st.breakRow, st.loopJump = -1, -1, -1 + st.ft2BreakPos = 0 + Player.startOrder(st, o, r) + return + end + if loopRow >= 0 then + st.loopJump = -1 + -- the rows inside a pattern loop are played again on purpose: forget them for the song-end check + for r = loopRow, st.row do + st.visited[st.ord * 1024 + r] = nil + end + st.row = loopRow + return + end + st.row += 1 + if st.row >= st.pat.rows then + -- FT2 (XM): the next pattern starts at the row a pattern loop last jumped to (the E6x "bug" FT2 players keep) + local r = if st.fmt == XM then st.ft2BreakPos else 0 + st.ft2BreakPos = 0 + Player.startOrder(st, st.ord + 1, r) + end +end + +@native 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 + base, ref = 8363, 49 + tr = (smp.relativeNote or 0) * 64 + (ft or smp.finetune or 0) / 2 + else + base, ref, tr = smp.c5speed or 8363, 61, 0 + if base <= 0 then + base = 8363 + end + end + local plin = (ref - note) * 64 - tr + if st.hz then + -- periods are frequencies (Hz, rounded as OpenMPT does): the sample's rate at C-5 + return floor((smp.c5speed or 8363) * 2 ^ ((note - 61) / 12)), base + end + if st.ptPeriods then + -- ProTracker: integer periods from the finetune tables (finetune 0 table scaled by 2^(-ft / 96), rounded) + local ftp = (ft or smp.finetune or 0) / 16 + local n = note + (if st.fmt == MOD or st.fmt == XM then smp.relativeNote or 0 else 0) + return 4 * floor(Tables.noteToPeriod(n) * 2 ^ (-ftp / 12 / 8) + 0.5), base + end + if st.linear then + return plin, base + end + return 1712 * 8363 / base * 2 ^ (plin / 768), base +end + +@native local function arpPeriod(st: any, period: number, semis: number): number + if semis == 0 then + return period + end + if st.hz then + return period * 2 ^ (semis / 12) + end + if st.linear then + return period - semis * 64 + end + return period * 2 ^ (-semis / 12) +end + +@native local function clampPeriod(st: any, c: any) + if st.hz then + c.period = clamp(c.period, 1, 1e6) + elseif st.linear then + c.period = clamp(c.period, -6000, 6000) + elseif st.amigaLimits then + c.period = clamp(c.period, 113 * 4, 856 * 4) + else + c.period = clamp(c.period, 1, 1e6) + end +end + +-- pitch slides in period units (positive: down; 4 per effect unit); in Hz mode the frequency moves units * hzSlide Hz the other way +@native local function slide(st: any, c: any, units: number) + if st.hz then + c.period -= units * st.hzScale + else + c.period += units + end + clampPeriod(st, c) +end + +@native local function allocVoice(st: any): any + local best, bestScore = nil, math.huge + for _, v in st.voices do + if not v.active and v.owner == 0 then + return v + end + if v.bg then + local s = (v.vol * v.envVol * v.fade) / 1e9 + v.order * 1e-9 + if s < bestScore then + best, bestScore = v, s + end + end + end + if best then + best.active = false + return best + end + for _, v in st.voices do + if not v.active then + local c = st.chans[v.owner] + if c and c.voice == v then + c.voice = nil + end + return v + end + end + return st.voices[1] +end + +@native local function keyOff(st: any, v: any) + if not v or not v.active then + return + end + v.keyOn = false + local ins = v.ins + if st.fmt == XM then + if not (ins and ins.volEnv and ins.volEnv.enabled) then + v.vol = 0 + local c = st.chans[v.chan] + if c and c.voice == v then + c.vol = 0 + end + else + v.fading = true + end + elseif st.fmt == IT then + if ins then + local env = ins.volEnv + if not (env and env.enabled and v.volEnvOn) or env.loop then + v.fading = true + end + end + end +end + +@native local function noteFade(v: any) + if v and v.active then + v.fading = true + end +end + +@native local function cutVoice(v: any) + if v then + v.active = false + end +end + +@native local function startVoice(st: any, c: any, smp: any, smpIdx: number, ins: any, insIdx: number, note: number, period: number, base: number, keepEnv: any) + local v = c.voice + if v == nil or v.bg then + v = allocVoice(st) + c.voice = v + v.owner = c.idx + end + local wasActive = v.active + v.active = smp.length > 0 and smp.data ~= nil + v.chan = c.idx + v.bg = false + v.smp = smp + v.smpIdx = smpIdx + v.data = smp.data + v.nch = smp.channels or 1 + v.len = smp.length + v.loopS, v.loopE, v.loopT = smp.loopStart, smp.loopEnd, smp.loopType + v.susS, v.susE, v.susT = smp.susStart or 0, smp.susEnd or 0, smp.susType or 0 + v.p = 0 + v.dir = 1 + v.ins = ins + v.insIdx = insIdx + v.note = note + v.period = period + v.periodOut = period + v.base = base + st.age += 1 + v.order = st.age + if keepEnv ~= true then + if keepEnv ~= "release" then + v.keyOn = true + v.fading = false + end + v.fade = 65536 + v.volEnvPos, v.panEnvPos, v.pitchEnvPos = 0, 0, 0 + v.avPos, v.avAmp = 0, 0 + v.envVol, v.envPan, v.envPitch = 64, 0, 0 + v.volEnvOn, v.panEnvOn, v.pitchEnvOn = true, true, true + v.y1l, v.y2l, v.y1r, v.y2r = 0, 0, 0, 0 + end + if not wasActive then + v.gl, v.gr = 0, 0 + end + return v +end + +-- IT new note actions on the channel's current voice (and duplicate checks on all its voices) +@native local function newNoteAction(st: any, c: any, ins: any, insIdx: number, note: number, smpIdx: number) + if ins and ins.dct and ins.dct > 0 then + for _, u in st.voices do + if u.active and u.chan == c.idx and u.insIdx == insIdx then + local dup = (ins.dct == 1 and u.note == note) or (ins.dct == 2 and u.smpIdx == smpIdx) or ins.dct == 3 + if dup then + local a = ins.dca or 0 + if a == 0 then + cutVoice(u) + elseif a == 1 then + keyOff(st, u) + else + noteFade(u) + end + end + end + end + end + local v = c.voice + if v == nil or not v.active then + return + end + local nna = c.nna + if nna < 0 then + nna = if v.ins then (v.ins.nna or 0) else 0 + end + if nna == 0 then + -- cut: the voice is reused for the new note (a short click is avoided by its ramp from the old gains) + v.active = false + return + end + v.bg = true + v.owner = 0 + c.voice = nil + if nna == 2 then + keyOff(st, v) + elseif nna == 3 then + noteFade(v) + end +end + +@native local function isPorta(st: any, fx: number, vcmd: number): boolean + local f = st.fmt + if f == MOD then + return fx == 3 or fx == 5 + elseif f == XM then + return fx == 3 or fx == 5 or (vcmd >= 0xF0) + end + -- S3M / IT: G (7) or L (12); IT volume column g (193..202, stored + 1) + return fx == 7 or fx == 12 or (f == IT and vcmd >= 194 and vcmd <= 203) +end + +@native local function resolve(st: any, insIdx: number, note: number): (any, number, any, number) + local m = st.m + if st.insMode then + local ins = m.instruments[insIdx] + if not ins or note < 1 or note > 120 then + return nil, 0, ins, note + end + local si = ins.sampleMap[note] or 0 + local rn = ins.noteMap[note] or note + local smp = m.samples[si] + return smp, si, ins, rn + end + local smp = m.samples[insIdx] + return smp, insIdx, nil, note +end + +@native local function setInstrumentDefaults(st: any, c: any, smp: any, ins: any) + if smp then + c.vol = smp.volume + end + if st.fmt == IT then + -- IT: a sample's or instrument's default panning holds for its notes; the channel panning (set by the + -- effects) comes back for the others + local p = (smp and smp.pan) or (ins and ins.pan) + c.pan = p or c.basePan + if p then + c.surround = false + end + elseif smp and smp.pan then + c.pan = smp.pan + c.basePan = c.pan + c.surround = false + end + if ins and st.fmt == IT then + if ins.cutoff then + c.cutoff = ins.cutoff + end + if ins.resonance then + c.reso = ins.resonance + end + end +end + +@native local function sampleOffset(st: any, c: any, v: any) + local f = st.fmt + local fx, param = c.fx, c.param + local off = -1 + if (f == MOD or f == XM) and fx == 9 then + if param > 0 then + c.mOffset = param + end + off = (if f == XM then c.mOffset else param) * 256 + elseif (f == S3M or f == IT) and fx == 15 then + if param > 0 then + c.mOffset = param + end + off = c.mOffset * 256 + (if f == IT then c.mHighOffset * 65536 else 0) + end + if off > 0 and v and v.active then + if off >= v.len then + if v.loopT > 0 and f ~= MOD then + off = v.loopS + elseif f == MOD and v.loopT > 0 then + off = v.loopS + else + v.active = false + return + end + end + v.p = off + end +end + +@native local function trigger(st: any, c: any, note: number, insIdx: number, vcmd: number) + local f = st.fmt + local m = st.m + local porta = isPorta(st, c.fx, vcmd) + local hasNote = note >= 1 and note <= 120 + if insIdx > 0 then + local valid = if st.insMode then m.instruments[insIdx] ~= nil else m.samples[insIdx] ~= nil + if valid then + c.insIdx = insIdx + local n = if hasNote then note else c.note + local smp, _, ins = resolve(st, insIdx, if n > 0 then n else 61) + setInstrumentDefaults(st, c, smp, ins) + if not hasNote then + local v = c.voice + if f == XM and v then + -- an instrument number alone (FT2 / OpenMPT): the playing note's envelopes restart (key on, no + -- fadeout); the new instrument applies from the next note + v.keyOn, v.fading, v.fade = true, false, 65536 + v.volEnvPos, v.panEnvPos, v.avPos, v.avAmp = 0, 0, 0, 0 + elseif (f == MOD or f == S3M) and smp then + c.smp, c.smpIdx = smp, insIdx + end + end + elseif f == XM and hasNote then + -- an empty instrument: the note stops the channel + c.insIdx = insIdx + if c.voice then + c.voice.active = false + end + hasNote = false + end + end + if hasNote then + local useIns = c.insIdx + local smp, smpIdx, ins, realNote = resolve(st, useIns, note) + if smp == nil then + if (f == MOD or f == S3M) and c.smp then + smp, smpIdx = c.smp, c.smpIdx + end + end + if smp then + local ft = c.finetune + local period, base = notePeriod(st, realNote, smp, ft) + local v = c.voice + if porta and ((v and v.active) or f == MOD or f == XM) then + -- tone portamento: a new target, no new note (ProTracker / FT2 never start a note with it) + c.target = period + if st.fmt == IT or st.fmt == S3M then + c.note = note + end + else + if f == IT and st.insMode then + newNoteAction(st, c, ins, useIns, realNote, smpIdx) + end + -- FT2: a note without an instrument number restarts the sample only (envelopes, key off and + -- fadeout carry on); with another instrument than the playing one, its envelopes and fadeout start + -- over but a key off stays + local keep: any = false + if f == XM and insIdx == 0 and c.voice ~= nil then + keep = if c.voice.ins == ins then true else "release" + end + c.triggered = true + c.hzAdd = 0 + c.tremorOn = true + c.retrigCount = 0 + v = startVoice(st, c, smp, smpIdx, ins, useIns, realNote, period, base, keep) + v.patNote = note + c.period, c.target, c.base = period, period, base + c.note, c.realNote = note, realNote + c.smp, c.smpIdx = smp, smpIdx + if insIdx > 0 or f == MOD or f == S3M then + -- volume was set by the instrument; MOD / S3M keep the channel volume + end + if c.vibWave < 4 then + c.vibPos = 0 + end + if c.tremWave < 4 then + c.tremPos = 0 + end + v.cutoff, v.reso = c.cutoff, c.reso + v.volEnvOn, v.panEnvOn, v.pitchEnvOn = true, true, true + c.nna = -1 + sampleOffset(st, c, v) + end + elseif f == IT or f == XM then + -- a note mapped to no sample cuts + if c.voice and not porta then + if f == IT and st.insMode then + newNoteAction(st, c, nil, 0, note, 0) + end + if c.voice then + c.voice.active = false + end + end + end + elseif note == 255 then + if f == S3M or f == MOD then + cutVoice(c.voice) + elseif c.voice then + keyOff(st, c.voice) + end + elseif note == 254 then + cutVoice(c.voice) + if f ~= IT then + c.vol = 0 + end + elseif note == 253 then + noteFade(c.voice) + end + -- the volume column's set-volume / set-panning parts (the rest runs with the effects) + if vcmd > 0 then + if f == S3M then + c.vol = min(vcmd - 1, 64) + elseif f == XM then + if vcmd >= 0x10 and vcmd <= 0x50 then + c.vol = vcmd - 0x10 + elseif vcmd >= 0xC0 and vcmd <= 0xCF then + c.pan = (vcmd - 0xC0) * 16 + c.basePan = c.pan + end + elseif f == IT then + local v = vcmd - 1 + if v <= 64 then + c.vol = v + elseif v >= 128 and v <= 192 then + c.pan = (v - 128) * 4 + c.basePan = c.pan + c.surround = false + end + end + end +end + +@native local function volSlideMod(c: any, param: number) + local x, y = param // 16, param % 16 + if x > 0 then + c.vol = min(64, c.vol + x) + else + c.vol = max(0, c.vol - y) + end +end + +@native local function tonePorta(st: any, c: any, speed: number) + if c.period == c.target then + return + end + if st.hz then + speed *= st.hzScale * st.hzTone + end + if c.period < c.target then + c.period = min(c.period + speed, c.target) + else + c.period = max(c.period - speed, c.target) + end +end + +@native local function vibrato(st: any, c: any, scale: number) + c.vibDelta = wave64(c.vibWave % 4, c.vibPos) * c.vibDepth * scale + c.vibPos = (c.vibPos + c.vibSpeed) % 64 +end + +@native local function tremolo(c: any, scale: number) + c.tremDelta = floor(wave64(c.tremWave % 4, c.tremPos) * c.tremDepth * scale) + c.tremPos = (c.tremPos + c.tremSpeed) % 64 +end + +@native local function retrigVoice(st: any, c: any) + local v = c.voice + if v and v.smp then + v.active = v.smp.length > 0 + v.p = 0 + v.dir = 1 + end +end + +@native local function retrigVolume(c: any, x: number) + if x == 0 or x == 8 then + return + end + local mul = Tables.RETRIG_MUL[x + 1] + if mul ~= 1 then + c.vol = floor(c.vol * mul) + else + c.vol += Tables.RETRIG_ADD[x + 1] + end + c.vol = clamp(c.vol, 0, 64) +end + +-- S3M / IT D-style slide: fine parts only on tick 0, normal parts on other ticks (fast: normal parts on tick 0 too) +@native local function dSlide(value: number, param: number, tick: number, fast: boolean, hi: number): number + local x, y = param // 16, param % 16 + if y == 0xF and x > 0 then + if tick == 0 then + return min(hi, value + x) + end + return value + elseif x == 0xF and y > 0 then + if tick == 0 then + return max(0, value - y) + end + return value + end + if tick == 0 and not fast then + return value + end + if y == 0 then + return min(hi, value + x) + elseif x == 0 then + return max(0, value - y) + end + return value +end + +@native local function fxModXm(st: any, c: any, tick: number) + local fx, param = c.fx, c.param + local xm = st.fmt == XM + local x, y = param // 16, param % 16 + if fx == 0 then + if param ~= 0 then + local k = tick % 3 + c.arp = if k == 1 then x elseif k == 2 then y else 0 + end + elseif fx == 1 then + if xm and param > 0 then + c.mPortaUp = param + end + if tick > 0 or st.fastPortas then + slide(st, c, -(if xm then c.mPortaUp else param) * 4) + end + elseif fx == 2 then + if xm and param > 0 then + c.mPortaDn = param + end + if tick > 0 or st.fastPortas then + slide(st, c, (if xm then c.mPortaDn else param) * 4) + end + elseif fx == 3 or fx == 5 then + if fx == 3 and param > 0 then + c.portaSpeed = param + end + if tick > 0 or st.fastPortas then + tonePorta(st, c, c.portaSpeed * 4) + end + elseif fx == 4 or fx == 6 then + if fx == 4 then + if x > 0 then + c.vibSpeed = x + end + if y > 0 then + c.vibDepth = y + end + end + if tick > 0 then + vibrato(st, c, 8 / 255) + end + elseif fx == 7 then + if x > 0 then + c.tremSpeed = x + end + if y > 0 then + c.tremDepth = y + end + if tick > 0 then + tremolo(c, 1 / 64) + end + elseif fx == 8 then + if tick == 0 then + c.pan = param + c.basePan = c.pan + c.surround = false + end + elseif fx == 0xB then + if tick == 0 then + st.jumpOrd = param + if st.breakRow < 0 then + st.breakRow = 0 + end + end + elseif fx == 0xC then + if tick == 0 then + c.vol = min(param, 64) + end + elseif fx == 0xD then + if tick == 0 then + local r = x * 10 + y + if r > 63 then + r = 0 + end + st.breakRow = r + end + elseif fx == 0xE then + if x == 1 then + if xm and y > 0 then + c.mFineUp = y + end + if tick == 0 then + slide(st, c, -(if xm then c.mFineUp else y) * 4) + end + elseif x == 2 then + if xm and y > 0 then + c.mFineDn = y + end + if tick == 0 then + slide(st, c, (if xm then c.mFineDn else y) * 4) + end + elseif x == 4 then + c.vibWave = y % 8 + elseif x == 6 then + if tick == 0 then + if y == 0 then + c.loopRow = st.row + elseif c.loopCount == 0 then + c.loopCount = y + st.loopJump = c.loopRow + st.ft2BreakPos = c.loopRow + else + c.loopCount -= 1 + if c.loopCount > 0 then + st.loopJump = c.loopRow + end + st.ft2BreakPos = c.loopRow + end + end + elseif x == 7 then + c.tremWave = y % 8 + elseif x == 8 then + if tick == 0 then -- FT2 ignores E8x in XM; OpenMPT (the reference) applies it + c.pan = y * 17 + c.basePan = c.pan + c.surround = false + end + elseif x == 9 then + if y > 0 and tick > 0 and tick % y == 0 then + retrigVoice(st, c) + end + elseif x == 0xA then + if xm and y > 0 then + c.mFineVolUp = y + end + if tick == 0 then + c.vol = min(64, c.vol + (if xm then c.mFineVolUp else y)) + end + elseif x == 0xB then + if xm and y > 0 then + c.mFineVolDn = y + end + if tick == 0 then + c.vol = max(0, c.vol - (if xm then c.mFineVolDn else y)) + end + elseif x == 0xC then + if tick == y then + c.vol = 0 + end + elseif x == 0xE then + if tick == 0 and st.patDelayRep == 0 and st.patDelay == 0 then + st.patDelay = y + end + end + elseif fx == 0xF then + if tick == 0 then + if param == 0 then + if not xm then + st.stopAfterRow = true -- ProTracker F00: the song stops (after this row, as OpenMPT plays it) + end + elseif param < 32 then + st.speed = param + else + st.tempo = param + end + end + elseif fx == 16 then -- G + if tick == 0 then + st.gvol = min(param, 64) * 2 + end + elseif fx == 17 then -- H + if param > 0 then + c.mGVolSlide = param + end + if tick > 0 then + local p = c.mGVolSlide + local px, py = p // 16, p % 16 + if px > 0 then + st.gvol = min(128, st.gvol + px * 2) + else + st.gvol = max(0, st.gvol - py * 2) + end + end + elseif fx == 20 then -- K + if tick == param then + keyOff(st, c.voice) + end + elseif fx == 21 then -- L + if tick == 0 and c.voice then + c.voice.volEnvPos = param + c.voice.panEnvPos = param + end + elseif fx == 25 then -- P + if param > 0 then + c.mPanSlide = param + end + if tick > 0 then + local p = c.mPanSlide + local px, py = p // 16, p % 16 + if px > 0 then + c.pan = min(255, c.pan + px) + c.basePan = c.pan + else + c.pan = max(0, c.pan - py) + c.basePan = c.pan + end + end + elseif fx == 27 then -- R + if x > 0 then + c.mRetrig = c.mRetrig % 16 + x * 16 + end + if y > 0 then + c.mRetrig = (c.mRetrig // 16) * 16 + y + end + local interval = c.mRetrig % 16 + if tick == 0 and c.triggered then + c.retrigCount = 0 + else + c.retrigCount += 1 + end + if interval > 0 and c.retrigCount >= interval then + c.retrigCount = 0 + retrigVolume(c, c.mRetrig // 16) + retrigVoice(st, c) + end + elseif fx == 29 then -- T + if param > 0 then + c.mTremor = param + end + elseif fx == 33 then -- X + if x == 1 then + if y > 0 then + c.mXFineUp = y + end + if tick == 0 then + slide(st, c, -c.mXFineUp) + end + elseif x == 2 then + if y > 0 then + c.mXFineDn = y + end + if tick == 0 then + slide(st, c, c.mXFineDn) + end + end + end + -- the volume slide half of 5xy / 6xy and Axy + if fx == 0xA or fx == 5 or fx == 6 then + if xm then + if param > 0 then + c.mVolSlide = param + end + if tick > 0 or st.fastSlides then + volSlideMod(c, c.mVolSlide) + end + elseif tick > 0 or st.fastSlides then + volSlideMod(c, param) + end + end + -- tremor (XM Txy): on x + 1 ticks, off y + 1 ticks + if fx == 29 and tick > 0 then + local on, off = c.mTremor // 16 + 1, c.mTremor % 16 + 1 + c.tremorCount %= on + off + c.tremorOn = c.tremorCount < on + c.tremorCount += 1 + end +end + +-- the XM volume column (everything but set volume / set panning, done by trigger) +@native local function volColXm(st: any, c: any, tick: number) + local v = c.vcmd + if v < 0x60 then + return + end + local hi, lo = v // 16, v % 16 + if hi == 6 then + if tick > 0 then + c.vol = max(0, c.vol - lo) + end + elseif hi == 7 then + if tick > 0 then + c.vol = min(64, c.vol + lo) + end + elseif hi == 8 then + if tick == 0 then + c.vol = max(0, c.vol - lo) + end + elseif hi == 9 then + if tick == 0 then + c.vol = min(64, c.vol + lo) + end + elseif hi == 0xA then + if lo > 0 then + c.vibSpeed = lo + end + elseif hi == 0xB then + if lo > 0 then + c.vibDepth = lo + end + if tick > 0 then + vibrato(st, c, 8 / 255) + end + elseif hi == 0xD then + if tick > 0 then + c.pan = max(0, c.pan - lo) + c.basePan = c.pan + end + elseif hi == 0xE then + if tick > 0 then + c.pan = min(255, c.pan + lo) + c.basePan = c.pan + end + elseif hi == 0xF then + if lo > 0 then + c.portaSpeed = lo * 16 + end + if tick > 0 then + tonePorta(st, c, c.portaSpeed * 4) + end + end +end + +-- the parameter after memory: IT keeps one memory per effect group, ST3 one memory for most effects +@native local function mem(st: any, c: any, field: string, param: number): number + if st.fmt == S3M then + if param > 0 then + c.mS3M = param + end + return c.mS3M + end + if param > 0 then + c[field] = param + end + return c[field] +end + +@native local function portaS3m(st: any, c: any, p: number, tick: number, sign: number) + if p >= 0xF0 then + if tick == 0 then + slide(st, c, sign * (p % 16) * 4) + end + elseif p >= 0xE0 then + if tick == 0 then + slide(st, c, sign * (p % 16)) + end + elseif tick > 0 or st.fastPortas then + slide(st, c, sign * p * 4) + end +end + +@native local function fxS3mIt(st: any, c: any, tick: number) + local fx, param = c.fx, c.param + local it = st.fmt == IT + if fx == 1 then -- A speed + if tick == 0 and param > 0 then + if st.st2Tempo then + st.speed, st.tempo = Tables.st2Tempo(param) + else + st.speed = param + end + end + elseif fx == 2 then -- B jump + if tick == 0 then + st.jumpOrd = param + if st.breakRow < 0 then + st.breakRow = 0 + end + end + elseif fx == 3 then -- C break + if tick == 0 then + st.breakRow = if it then param else (param // 16) * 10 + param % 16 + end + elseif fx == 4 or fx == 11 or fx == 12 then -- D volume slide (K, L: + vibrato / tone portamento) + local p = mem(st, c, "mVolSlide", param) + c.vol = dSlide(c.vol, p, tick, st.fastSlides, 64) + elseif fx == 5 then -- E porta down + local p = mem(st, c, "mEF", param) + portaS3m(st, c, p, tick, 1) + elseif fx == 6 then -- F porta up + local p = mem(st, c, "mEF", param) + portaS3m(st, c, p, tick, -1) + elseif fx == 9 then -- I tremor + local p = mem(st, c, "mTremor", param) + if tick > 0 or not it then + local on, off = p // 16, p % 16 + if it and st.oldFx or not it then + on, off = on + 1, off + 1 + end + on, off = max(on, 1), max(off, 1) + c.tremorCount %= on + off + c.tremorOn = c.tremorCount < on + c.tremorCount += 1 + end + elseif fx == 10 then -- J arpeggio + local p = mem(st, c, "mArp", param) + local k = tick % 3 + c.arp = if k == 1 then p // 16 elseif k == 2 then p % 16 else 0 + elseif fx == 13 then -- M channel volume + if tick == 0 and param <= 64 then + c.chanVol = param + end + elseif fx == 14 then -- N channel volume slide + local p = mem(st, c, "mChanVolSlide", param) + c.chanVol = dSlide(c.chanVol, p, tick, false, 64) + elseif fx == 16 then -- P panning slide (0..64 scale x 4) + local p = mem(st, c, "mPanSlide", param) + local pan64 = c.pan / 4 + local x, y = p // 16, p % 16 + if y == 0xF and x > 0 then + if tick == 0 then + pan64 = max(0, pan64 - x) + end + elseif x == 0xF and y > 0 then + if tick == 0 then + pan64 = min(64, pan64 + y) + end + elseif tick > 0 then + if y == 0 then + pan64 = max(0, pan64 - x) + elseif x == 0 then + pan64 = min(64, pan64 + y) + end + end + c.pan = pan64 * 4 + c.basePan = c.pan + c.surround = false + elseif fx == 17 then -- Q retrigger + volume change + local p = mem(st, c, "mRetrig", param) + local interval = p % 16 + if interval > 0 then + if tick == 0 and c.retrigCount <= 0 then + c.retrigCount = interval + end + if tick > 0 then + c.retrigCount -= 1 + if c.retrigCount <= 0 then + c.retrigCount = interval + retrigVolume(c, p // 16) + retrigVoice(st, c) + end + end + end + elseif fx == 18 then -- R tremolo + if param // 16 > 0 then + c.tremSpeed = param // 16 + end + if param % 16 > 0 then + c.tremDepth = param % 16 + end + if tick > 0 then + tremolo(c, 1 / 64) + end + elseif fx == 19 then -- S extended + local p = if it then mem(st, c, "mS", param) else mem(st, c, "mS", param) + local x, y = p // 16, p % 16 + if x == 3 then + c.vibWave = y % 8 + elseif x == 4 then + c.tremWave = y % 8 + elseif x == 5 then + c.panbWave = y % 8 + elseif x == 6 then + if tick == 0 then + st.fineDelay += y + end + elseif x == 7 then + if tick == 0 then + if y <= 2 then + for _, u in st.voices do + if u.active and u.bg and u.chan == c.idx then + if y == 0 then + cutVoice(u) + elseif y == 1 then + keyOff(st, u) + else + noteFade(u) + end + end + end + elseif y <= 6 then + c.nna = y - 3 + else + local v = c.voice + if v then + if y == 7 then + v.volEnvOn = false + elseif y == 8 then + v.volEnvOn = true + elseif y == 9 then + v.panEnvOn = false + elseif y == 10 then + v.panEnvOn = true + elseif y == 11 then + v.pitchEnvOn = false + elseif y == 12 then + v.pitchEnvOn = true + end + end + end + end + elseif x == 8 then + if tick == 0 then + c.pan = y * 17 + c.basePan = c.pan + c.surround = false + end + elseif x == 9 then + if tick == 0 and y == 1 then + c.surround = true + end + elseif x == 0xA then + if tick == 0 then + c.mHighOffset = y + end + elseif x == 0xB then + if tick == 0 then + if y == 0 then + c.loopRow = st.row + elseif c.loopCount == 0 then + c.loopCount = y + st.loopJump = c.loopRow + else + c.loopCount -= 1 + if c.loopCount > 0 then + st.loopJump = c.loopRow + elseif it then + c.loopRow = st.row + 1 + end + end + end + elseif x == 0xC then + local at = if y == 0 and it then 1 else y + if tick == at and (y > 0 or it) then + if it then + cutVoice(c.voice) + end + c.vol = 0 + end + elseif x == 0xE then + if tick == 0 and st.patDelayRep == 0 and st.patDelay == 0 then + st.patDelay = y + end + end + elseif fx == 20 then -- T tempo + if param >= 0x20 then + if tick == 0 then + st.tempo = param + end + elseif it then + if param > 0 then + c.mTempo = param + end + local p = c.mTempo + if tick > 0 then + if p >= 0x10 then + st.tempo = min(255, st.tempo + (p - 0x10)) + else + st.tempo = max(32, st.tempo - p) + end + end + end + elseif fx == 22 then -- V global volume + if tick == 0 then + if it then + if param <= 128 then + st.gvol = param + end + else + st.gvol = min(param, 64) * 2 + end + end + elseif fx == 23 then -- W global volume slide + local p = mem(st, c, "mGVolSlide", param) + st.gvol = dSlide(st.gvol, p, tick, false, 128) + elseif fx == 24 then -- X panning + if tick == 0 then + if it then + c.pan = param + c.basePan = c.pan + c.surround = false + elseif param <= 0x80 then + c.pan = param * 2 + c.basePan = c.pan + c.surround = false + elseif param == 0xA4 then + c.surround = true + end + end + elseif fx == 25 then -- Y panbrello + if param // 16 > 0 then + c.panbSpeed = param // 16 + end + if param % 16 > 0 then + c.panbDepth = param % 16 + end + c.panbDelta = wave64(c.panbWave % 4, c.panbPos // 4) * c.panbDepth / 16 + c.panbPos = (c.panbPos + c.panbSpeed) % 256 + elseif fx == 26 then -- Z MIDI macro: the default IT macros (Z00..Z7F cutoff, Z80..Z8F resonance) + if tick == 0 then + if param < 0x80 then + c.cutoff = param + elseif param < 0x90 then + c.reso = (param - 0x80) * 8 + end + if c.voice then + c.voice.cutoff, c.voice.reso = c.cutoff, c.reso + end + end + end + -- tone portamento (G, L) + if fx == 7 or fx == 12 then + if fx == 7 then + if st.fmt == S3M then + if param > 0 then + c.portaSpeed = param + end + elseif st.compatG then + if param > 0 then + c.portaSpeed = param + end + else + if param > 0 then + c.mEF = param + end + c.portaSpeed = c.mEF + end + end + if tick > 0 or st.fastPortas then + tonePorta(st, c, c.portaSpeed * 4) + end + end + -- vibrato (H, U, K) + if fx == 8 or fx == 21 or fx == 11 then + if fx ~= 11 then + if param // 16 > 0 then + c.vibSpeed = param // 16 + end + if param % 16 > 0 then + c.vibDepth = param % 16 + end + end + local scale = if fx == 21 then 2 / 255 else 8 / 255 + if it and not st.oldFx then + scale /= 2 + end + if tick > 0 or (it and not st.oldFx) then + vibrato(st, c, scale) + end + end +end + +-- the IT volume column (value stored + 1): slides, portamento, vibrato +@native local function volColIt(st: any, c: any, tick: number) + local v = c.vcmd - 1 + if v < 65 then + return + end + if v <= 74 then + local p = v - 65 + if p > 0 then + c.mVolCol = p + end + if tick == 0 then + c.vol = min(64, c.vol + c.mVolCol) + end + elseif v <= 84 then + local p = v - 75 + if p > 0 then + c.mVolCol = p + end + if tick == 0 then + c.vol = max(0, c.vol - c.mVolCol) + end + elseif v <= 94 then + local p = v - 85 + if p > 0 then + c.mVolCol = p + end + if tick > 0 then + c.vol = min(64, c.vol + c.mVolCol) + end + elseif v <= 104 then + local p = v - 95 + if p > 0 then + c.mVolCol = p + end + if tick > 0 then + c.vol = max(0, c.vol - c.mVolCol) + end + elseif v <= 114 then + local p = (v - 105) * 4 + if p > 0 then + c.mEF = p + end + if tick > 0 then + slide(st, c, c.mEF * 4) + end + elseif v <= 124 then + local p = (v - 115) * 4 + if p > 0 then + c.mEF = p + end + if tick > 0 then + slide(st, c, -c.mEF * 4) + end + elseif v >= 193 and v <= 202 then + local p = Tables.IT_VOLPORTA[v - 192] or 0 + if p > 0 then + if st.compatG then + c.portaSpeed = p + else + c.mEF = p + c.portaSpeed = p + end + end + if tick > 0 then + tonePorta(st, c, c.portaSpeed * 4) + end + elseif v >= 203 and v <= 212 then + local d = v - 203 + if d > 0 then + c.vibDepth = d + end + if tick > 0 or not st.oldFx then + vibrato(st, c, if st.oldFx then 8 / 255 else 4 / 255) + end + end +end + +@native local function fxExt(st: any, c: any, tick: number) + local fx, param = c.fx, c.param + if fx >= EXT.NOTE_SLIDE_UP and fx <= EXT.NOTE_SLIDE_DOWN_RETRIG then + -- note slides (PTM, Oktalyzer): every (param >> 4) ticks by (param & 15) semitones; Oktalyzer (flags.oktSlides): + -- 1x = every tick, 5x = once on the first tick + if tick == 0 then + if param // 16 > 0 then + c.mNoteSlide = (param // 16) * 16 + c.mNoteSlide % 16 + end + if param % 16 > 0 then + c.mNoteSlide = (c.mNoteSlide // 16) * 16 + param % 16 + end + c.slideCount = c.mNoteSlide // 16 + end + local p = c.mNoteSlide + local go + if st.oktSlides then + go = p // 16 == 1 or tick == 0 + else + go = false + if tick > 0 then + c.slideCount -= 1 + go = c.slideCount == 0 + end + end + if go and c.smp and c.realNote > 0 then + c.slideCount = p // 16 + local up = fx == EXT.NOTE_SLIDE_UP or fx == EXT.NOTE_SLIDE_UP_RETRIG + c.realNote = clamp(c.realNote + (if up then p % 16 else -(p % 16)), 1, 120) + c.period = notePeriod(st, c.realNote, c.smp, c.finetune) + if fx >= EXT.NOTE_SLIDE_UP_RETRIG then + retrigVoice(st, c) + end + end + elseif fx == EXT.AUTO_PORTA_UP or fx == EXT.AUTO_PORTA_DOWN then + if tick == 0 then + c.autoPorta = (if fx == EXT.AUTO_PORTA_UP then -param else param) * 4 + end + elseif fx == EXT.FREQ_ADJUST then + if tick == 0 then + c.hzAdd = param * 80 + end + elseif fx >= EXT.TEMPO_256 and fx <= EXT.TEMPO_256 + 2 then + if tick == 0 then + st.tempo = (fx - EXT.TEMPO_256 + 1) * 256 + param + end + end + -- auto slides: every tick (fast portamentos) or every tick but the first + if tick > 0 or st.fastPortas then + if c.autoPorta ~= 0 then + slide(st, c, c.autoPorta) + end + if c.autoTone and not c.tonePortaRow then + tonePorta(st, c, c.portaSpeed * 4) + end + end +end + +@native local function noteDelayOf(st: any, fx: number, param: number): number + if (st.fmt == MOD or st.fmt == XM) and fx == 0xE and param // 16 == 0xD then + return param % 16 + elseif (st.fmt == S3M or st.fmt == IT) and fx == 19 and param // 16 == 0xD then + return param % 16 + end + return 0 +end + +@native local function finetuneOf(st: any, fx: number, param: number): number? + if (st.fmt == MOD or st.fmt == XM) and fx == 0xE and param // 16 == 5 then + local y = param % 16 + if st.fmt == MOD then + return (if y >= 8 then y - 16 else y) * 16 + end + return (y - 8) * 16 + end + return nil +end + +@native local function runEffects(st: any, c: any, tick: number) + c.vibDelta, c.arp = 0, 0 + if (c.fx >= 0x40 and c.fx < 0x50) or c.autoPorta ~= 0 or c.autoTone then + fxExt(st, c, tick) + end + if st.fmt == MOD or st.fmt == XM then + fxModXm(st, c, tick) + if st.fmt == XM then + volColXm(st, c, tick) + end + else + if st.fmt == IT then + volColIt(st, c, tick) + end + fxS3mIt(st, c, tick) + end + -- keep the tremolo / panbrello offsets only while their effect runs + local fx = c.fx + if st.fmt == MOD or st.fmt == XM then + if fx ~= 7 then + c.tremDelta = 0 + end + -- XM: a tremor that ends in its off phase keeps the channel silent until the next note (OpenMPT / FT2) + else + if fx ~= 18 then + c.tremDelta = 0 + end + if fx ~= 9 then + c.tremorOn = true + end + if fx ~= 25 then + c.panbDelta = 0 + end + end +end + +@native local function processRow(st: any) + local m = st.m + local pat = st.pat + local nch = st.nch + local data = pat.data + local base = st.row * nch * 5 + st.visited[st.ord * 1024 + st.row] = true + st.rows += 1 + for i = 1, nch do + local c = st.chans[i] + local o = base + (i - 1) * 5 + local note, ins, vcmd, fx, param = readu8(data, o), readu8(data, o + 1), readu8(data, o + 2), readu8(data, o + 3), readu8(data, o + 4) + if (st.fmt == MOD or st.fmt == XM) and fx == 0 and param == 0 then + fx = 255 + end + c.fx, c.param, c.vcmd = fx, param, vcmd + c.cutTick, c.keyOffTick = -1, -1 + if st.autoReset and fx ~= 0 and fx ~= 255 then + -- 669: any effect stops the auto slides + c.autoPorta, c.autoTone = 0, false + end + local tp = isPorta(st, fx, vcmd) + c.tonePortaRow = tp + if tp and st.autoTonePorta then + c.autoTone = param ~= 0 or not st.autoReset or not isPorta(st, fx, 0) + end + c.triggered = false + local delay = noteDelayOf(st, fx, param) + c.finetune = finetuneOf(st, fx, param) + if delay > 0 then + c.delayTick, c.dNote, c.dIns, c.dVol = delay, note, ins, vcmd + else + c.delayTick = -1 + trigger(st, c, note, ins, vcmd) + end + runEffects(st, c, 0) + end + local _ = m +end + +@native local function updateEnvelope(env: any, pos: number, keyOn: boolean, it: boolean): (number, number, boolean) + local ticks, values = env.ticks, env.values + local n = #ticks + if n == 0 then + return 0, pos, true + end + local value + if pos <= ticks[1] then + value = values[1] + elseif pos >= ticks[n] then + value = values[n] + else + local i = 1 + while i < n and ticks[i + 1] <= pos do + i += 1 + end + local t0, t1 = ticks[i], ticks[i + 1] + if t1 > t0 then + value = values[i] + (values[i + 1] - values[i]) * (pos - t0) / (t1 - t0) + else + value = values[i + 1] + end + end + local nextPos = pos + 1 + local ended = false + -- sustain / loop: only when the position runs over the end point (a position set past it, by Lxx, runs on) + -- FT2 jumps when the position reaches the end tick (its value is not played: a loop lasts end - start ticks), + -- IT after playing it (end - start + 1 ticks) + local se, le = ticks[env.susEnd], ticks[env.loopEnd] + local over = if it then 1 else 0 + if keyOn and env.sustain and se and pos <= se and nextPos >= se + over then + nextPos = ticks[env.susStart] or nextPos + elseif env.loop and le and pos <= le and nextPos >= le + over then + nextPos = ticks[env.loopStart] or nextPos + elseif nextPos > ticks[n] then + nextPos = ticks[n] + ended = true + end + return value, nextPos, ended +end + +@native local function updateVoice(st: any, v: any) + local ins = v.ins + local it = st.fmt == IT + local envVol, envPan, envPitch = 64, 0, 0 + local filterEnv = nil + if ins then + local hold = st.envHold and st.tick == 0 -- MED: the envelopes do not move on a row's first tick + local e = ins.volEnv + if e and e.enabled and v.volEnvOn then + local val, np, ended = updateEnvelope(e, v.volEnvPos, v.keyOn, it) + envVol, v.volEnvPos = val, if hold then v.volEnvPos else np + if ended and it then + if val <= 0 then + v.active = false + return + end + v.fading = true + end + end + e = ins.panEnv + if e and e.enabled and v.panEnvOn then + local val, np = updateEnvelope(e, v.panEnvPos, v.keyOn, it) + envPan, v.panEnvPos = val, if hold then v.panEnvPos else np + end + e = ins.pitchEnv + if e and e.enabled and v.pitchEnvOn then + local val, np = updateEnvelope(e, v.pitchEnvPos, v.keyOn, it) + v.pitchEnvPos = if hold then v.pitchEnvPos else np + if e.filter then + filterEnv = val + else + envPitch = val + end + end + if v.fading then + local fo = ins.fadeout or 0 + v.fade -= if it then fo * 64 else fo * 2 + if v.fade <= 0 then + v.fade = 0 + v.active = false + return + end + end + end + v.envVol = envVol + -- auto-vibrato: XM per instrument, IT per sample + local avSrc = if it then v.smp else ins + local avDelta = 0 + if avSrc and (avSrc.vibDepth or 0) > 0 then + local depth = avSrc.vibDepth + local sweep = avSrc.vibSweep or 0 + if it then + -- IT: the depth ramps up by the rate (vibSweep here) every tick, in 1/256 steps + local target = depth * 256 + if sweep == 0 then + v.avAmp = target + elseif v.avAmp < target then + v.avAmp = min(target, v.avAmp + sweep) + end + avDelta = autoWave(avSrc.vibType or 0, v.avPos, true) * v.avAmp / (256 * 64) * 4 + else + if sweep == 0 then + v.avAmp = depth * 256 + elseif v.keyOn then + v.avAmp = min(depth * 256, v.avAmp + depth * 256 / sweep) + end + avDelta = autoWave(avSrc.vibType or 0, v.avPos, false) * v.avAmp / (256 * 64) + end + v.avPos = (v.avPos + (avSrc.vibRate or 0)) % 256 + end + local P = v.periodOut + avDelta + local freq + if st.hz then + freq = max(0, P + (v.hzAdd or 0)) + elseif st.linear then + freq = v.base * 2 ^ (-P / 768) + else + freq = if P > 0 then st.amiga / P else 0 + end + if envPitch ~= 0 then + freq *= 2 ^ (envPitch / 24) + end + v.inc = freq / st.sr + local smp = v.smp + local vol = v.vol / 64 * envVol / 64 * v.fade / 65536 * st.gvol / 128 + -- channel, sample and instrument global volumes (64 / 64 / 128 unless an IT file, or another format's loader, + -- sets them) + vol *= v.chanVol / 64 * (if smp then (smp.globalVolume or 64) / 64 else 1) * (if ins then (ins.globalVolume or 128) / 128 else 1) + if v.tremorMute then + vol = 0 + end + local pan = v.pan + if it and ins and (ins.pps or 0) ~= 0 then + pan = clamp(pan + ((v.patNote or v.note) - (ins.ppc or 60) - 1) * ins.pps / 2, 0, 256) + end + if envPan ~= 0 then + local range = 128 - abs(pan - 128) + pan += envPan * range / 32 + end + pan = clamp(pan, 0, 256) + pan = clamp(128 + (pan - 128) * st.separation, 0, 256) + local g = vol * st.master + if v.surround then + v.tl, v.tr = g * 0.5, -g * 0.5 + elseif st.ft2Pan then + -- FT2's square-root pan law (OpenMPT's CompatibleFT2 mix levels), pan at most 255 + local p = min(pan, 255) + v.tl, v.tr = g * math.sqrt((256 - p) / 256), g * math.sqrt(p / 256) + else + v.tl, v.tr = g * (256 - pan) / 256, g * pan / 256 + end + v.rampN = st.ramp + local cutoff = v.cutoff + if filterEnv ~= nil or cutoff < 127 or v.reso > 0 then + local cc = cutoff + if filterEnv ~= nil then + cc = cutoff * (filterEnv + 32) / 64 + end + local fhz = 110 * 2 ^ (0.25 + cc / 24) + fhz = clamp(fhz, 120, min(20000, st.sr / 2)) + local dmp = 10 ^ (-v.reso * (24 / 128) / 20) + local fc = fhz * 2 * math.pi / st.sr + local d = (1 - 2 * dmp) * fc + if d > 2 then + d = 2 + end + d = (2 * dmp - d) / fc + local e = 1 / (fc * fc) + local den = 1 + d + e + v.fa, v.fb0, v.fb1 = 1 / den, (d + e + e) / den, -e / den + v.fOn = not (cc >= 127 and v.reso == 0) + else + v.fOn = false + end +end + +@native function Player.tick(st: any): number + if st.ended then + return 0 + end + local tick = st.tick + if tick == 0 and st.patDelayRep == 0 then + local key = st.ord * 1024 + st.row + if st.visited[key] and not st.loopAllowed then + st.ended = true + return 0 + end + if st.visited[key] then + table.clear(st.visited) + end + st.fineDelay = 0 + processRow(st) + else + local t = tick % st.speed + local rep = tick >= st.speed or st.patDelayRep > 0 + for i = 1, st.nch do + local c = st.chans[i] + if c.delayTick == tick and not rep then + c.delayTick = -1 + trigger(st, c, c.dNote, c.dIns, c.dVol) + end + if rep and t == 0 then + c.vibDelta, c.arp = 0, 0 + else + runEffects(st, c, if t == 0 then 1 else t) + end + end + end + if st.ended then + return 0 + end + for i = 1, st.nch do + local c = st.chans[i] + local v = c.voice + if v and v.active and v.chan == i and not v.bg then + local P = arpPeriod(st, c.period, c.arp) + (if st.hz then -c.vibDelta * st.hzScale else c.vibDelta) + v.period, v.periodOut, v.base = c.period, P, c.base + v.hzAdd = c.hzAdd + v.vol = clamp(c.vol + c.tremDelta, 0, 64) + if c.muted then + v.vol = 0 + end + v.pan = clamp(c.pan + c.panbDelta, 0, 256) + v.surround = c.surround + v.chanVol = c.chanVol + v.tremorMute = not c.tremorOn + v.cutoff, v.reso = c.cutoff, c.reso + end + end + for _, v in st.voices do + if v.active then + updateVoice(st, v) + end + end + -- frames for this tick: 2.5 / tempo seconds, truncated per tick (as OpenMPT does) + local frames = floor(st.sr * 2.5 / max(1, st.tempo)) + st.tick += 1 + if st.tick >= st.speed + st.fineDelay then + st.tick = 0 + if st.patDelayRep < st.patDelay then + st.patDelayRep += 1 + else + st.patDelay, st.patDelayRep = 0, 0 + advanceRow(st) + end + end + return frames +end + +return Player +end +__FILES["codecs/audio/Tracker/Tables"] = @native function() + + +-- codecs/audio/Tracker/Tables: tracker lookup tables, from the public format documents (ProTracker 2.3 effect docs, +-- FT2 / XM spec, ST3 TECH.DOC, ITTECH.TXT). +local Tables = {} + +-- the ProTracker half-sine (32 steps, 0..255) +local SINE32 = { 0, 24, 49, 74, 97, 120, 141, 161, 180, 197, 212, 224, 235, 244, 250, 253, 255, 253, 250, 244, 235, 224, 212, 197, 180, 161, 141, 120, 97, 74, 49, 24 } + +local RANDOM: { number } = {} +do + local s = 12345 + for i = 1, 64 do + s = (s * 1103515245 + 12345) % 2147483648 + RANDOM[i] = (s // 65536) % 511 - 255 + end +end +@native function Tables.wave64(kind: number, pos: number): number + local p = pos % 64 + if kind == 1 then + return 255 - p * 8 + elseif kind == 2 then + return if p < 32 then 255 else -255 + elseif kind == 3 then + return RANDOM[p + 1] + end + local v = SINE32[(p % 32) + 1] + return if p >= 32 then -v else v +end + +local SINE256: { number } = {} +for i = 0, 255 do + SINE256[i + 1] = math.floor(math.sin(i * math.pi / 128) * 64 + 0.5) +end +@native function Tables.autoWave(kind: number, pos: number, it: boolean): number + local p = pos % 256 + if it then + if kind == 1 then + return 64 - (p + 1) // 2 + elseif kind == 2 then + return if p < 128 then 64 else -64 + elseif kind == 3 then + return RANDOM[(p % 64) + 1] // 4 + end + return SINE256[p + 1] + end + if kind == 1 then + return if p < 128 then 64 else -64 + elseif kind == 2 then + return 64 - (p + 1) // 2 + elseif kind == 3 then + return (p + 1) // 2 - 64 + end + return SINE256[p + 1] +end + +-- ProTracker periods, finetune 0, C-0 .. B-4; note 1 = C-0 (FT2 numbering), C-2 (428) = note 49 plays at 8363 Hz +local PERIODS = { + 3424, 3232, 3048, 2880, 2712, 2560, 2416, 2280, 2152, 2032, 1920, 1812, + 1712, 1616, 1524, 1440, 1356, 1280, 1208, 1140, 1076, 1016, 960, 906, + 856, 808, 762, 720, 678, 640, 604, 570, 538, 508, 480, 453, + 428, 404, 381, 360, 339, 320, 302, 285, 269, 254, 240, 226, + 214, 202, 190, 180, 170, 160, 151, 143, 135, 127, 120, 113, + 107, 101, 95, 90, 85, 80, 75, 71, 67, 63, 60, 56, +} +Tables.PERIODS = PERIODS +Tables.PERIOD_FIRST_NOTE = 13 -- PERIODS[1] is note 13 (C-1 in FT2 numbering = ProTracker octave -1) + +@native function Tables.periodToNote(period: number): number + if period <= 0 then + return 0 + end + for i = 1, #PERIODS do + if PERIODS[i] == period then + return i + Tables.PERIOD_FIRST_NOTE - 1 + end + end + local n = 49 + math.floor(12 * math.log(428 / period) / math.log(2) + 0.5) + return math.clamp(n, 1, 120) +end + +@native function Tables.noteToPeriod(note: number): number + local i = note - Tables.PERIOD_FIRST_NOTE + 1 + if i >= 1 and i <= #PERIODS then + return PERIODS[i] + end + return math.max(1, math.floor(428 * 2 ^ ((49 - note) / 12) + 0.5)) +end + +-- IT volume column "g" (tone portamento) speeds +Tables.IT_VOLPORTA = { 0, 1, 4, 8, 16, 32, 64, 96, 128, 255 } + +-- XM Rxy / S3M-IT Qxy volume changes: kind 0 add, 1 multiply; value +Tables.RETRIG_ADD = { 0, -1, -2, -4, -8, -16, 0, 0, 0, 1, 2, 4, 8, 16, 0, 0 } +Tables.RETRIG_MUL = { 1, 1, 1, 1, 1, 1, 2 / 3, 0.5, 1, 1, 1, 1, 1, 1, 1.5, 2 } + +-- frequency = AMIGA / period; period 1712 plays an 8363 Hz sample at its base rate (FT2 / ST3 units, 4x ProTracker's) +Tables.AMIGA = 8363 * 1712 +-- MOD: the PAL Amiga clock (7093789.2 Hz / 2 per ProTracker period unit; period 428 plays at 8287 Hz) +Tables.AMIGA_PAL = 7093789.2 / 2 * 4 + +-- Scream Tracker 2 tempo byte as OpenMPT plays it (ConvertST2Tempo: ST2's tick length at 23863 Hz, as a fractional BPM) +local ST2_FACTOR = { 140, 50, 25, 15, 10, 7, 6, 4, 3, 3, 2, 2, 2, 2, 1, 1 } +@native function Tables.st2Tempo(byte: number): (number, number) + local hi, lo = byte // 16, byte % 16 + local d = 50 - (ST2_FACTOR[hi + 1] * lo) // 16 -- never 0; negative at tempo 06..0F (C integer division truncates) + local spt = if d > 0 then 23863 // d else -(23863 // -d) + if spt <= 0 then + spt += 65536 + end + return math.max(hi, 1), math.floor((23863 * 50000 + spt) / (spt * 2)) / 10000 +end + +return Tables +end +end + + + + + + Hively + --!optimize 2 +--!nocheck +-- rosetta chunk Hively (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 4 modules (2 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["codecs/audio/Hively"] = function() + +-- codecs/audio/Hively: the AHX / HivelyTracker engine (loader, replayer, waveform tables, render glue). +-- A port of hvl2wav replay.c 1.9 (BSD-3-Clause, (c) 2006-2018 Pete Gordon; licenses/hivelytracker-LICENSE.txt); at +-- hvl2wav's settings the output equals its 16-bit samples / 32768. hvl2wav pads a 44.1 kHz speed-multiplier-4 frame to +-- 882 samples with stale data; this renders 880. +local Err = __include("core/Err") +local Types = __include("Types") +local Load = __include("codecs/audio/Hively/Load") +local Player = __include("codecs/audio/Hively/Player") +local Pcm = __include("codecs/audio/Pcm") + +local Hively = {} + +type Tune = Load.Tune +type RenderOptions = { + sampleRate: number?, + subsong: number?, + stereo: number?, -- AHX stereo separation 0..4 (4 = 100 % Amiga L R R L); default 0 as hvl2wav + loop: boolean?, + maxDuration: number?, -- seconds, default 600 (hvl2wav's 10 minute limit) +} + +function Hively.parse(b: buffer, base: number?, limit: number?): (Tune?, Err.Err?) + local tune, msg, kind = Load.parse(b, base or 0, limit or buffer.len(b)) + if not tune then + return nil, Err.from(msg or "corrupt", nil, kind) + end + return tune, nil +end + +local function settings(tune: Tune, opts: RenderOptions?): (number?, number, number, Err.Err?) + local o: RenderOptions = opts or {} + local rate = o.sampleRate or 44100 + if type(rate) ~= "number" or rate < 8000 or rate > 192000 or rate % 1 ~= 0 then + return nil, 0, 0, Err.new(Err.ARG, "render: sampleRate must be an integer 8000..192000") + end + local sub = o.subsong or 0 + if type(sub) ~= "number" or sub < 0 or sub > #tune.subsongs or sub % 1 ~= 0 then + return nil, 0, 0, Err.new(Err.ARG, string.format("render: subsong must be 0..%d", #tune.subsongs)) + end + return rate, sub, tonumber(o.stereo) or 0, nil +end + +function Hively.frameCount(tune: Tune, opts: RenderOptions?): number + local rate, sub, stereo = settings(tune, opts) + local st = rate and Player.new(tune, rate :: number, stereo, sub) + if not st then + return 0 + end + local maxFrames = math.floor(((opts and opts.maxDuration) or 600) * 50) + local n = 0 + while n < maxFrames and not st.songEndReached do + for _ = 1, tune.speedMultiplier do + Player.irq(st, false) + end + n += 1 + end + return n +end + +function Hively.decoder(tune: Tune, opts: RenderOptions?): (Types.Decoder?, Err.Err?) + local rate, sub, stereo, err = settings(tune, opts) + if not rate then + return nil, err + end + local sr = rate :: number + local mult = tune.speedMultiplier + local perIrq = sr // 50 // mult + local perFrame = perIrq * mult + local nframes = Hively.frameCount(tune, opts) + local frames = nframes * perFrame + local loop = opts ~= nil and opts.loop == true + local st = Player.new(tune, sr, stereo, sub) :: Player.State + local fbuf = buffer.create(perFrame * 8) + local fpos, ffill = 0, 0 + local pos = 0 + + local function nextFrame() + for k = 0, mult - 1 do + Player.irq(st, true) + Player.mix(st, fbuf, k * perIrq, perIrq) + end + fpos, ffill = 0, perFrame + end + + local dec = { + sampleRate = sr, + channels = 2, + frames = frames, + duration = frames / sr, + bitrate = 0, + tags = { title = if tune.title ~= "" then tune.title else nil } :: Types.Tags, + } + local function read(_self: any, n: number, out: buffer?): (buffer, number) + n = math.max(0, math.floor(n)) + if not loop then + n = math.min(n, frames - pos) + end + local b = out + if not b or buffer.len(b) < n * 8 then + b = buffer.create(math.max(n, 1) * 8) + end + local ob = b :: buffer + local done = 0 + while done < n do + if fpos >= ffill then + nextFrame() + end + local k = math.min(n - done, ffill - fpos) + buffer.copy(ob, done * 8, fbuf, fpos * 8, k * 8) + fpos += k + done += k + end + pos += n + return ob, n + end + dec.read = read :: any + local scratch = buffer.create(4096 * 8) + dec.seek = function(_self: any, seconds: number) + local target = math.max(0, math.floor((tonumber(seconds) or 0) * sr)) + if not loop then + target = math.min(target, frames) + end + if target < pos then + st = Player.new(tune, sr, stereo, sub) :: Player.State + pos, fpos, ffill = 0, 0, 0 + end + while pos < target do + read(nil, math.min(4096, target - pos), scratch) + end + end :: any + dec.position = function(_self: any): number + return pos / sr + end :: any + return (dec :: any) :: Types.Decoder, nil +end + +function Hively.module(tune: Tune): Types.Module + local patterns = {} + for t = 0, tune.trackNr do + local data = buffer.create(tune.trackLength * 6) + buffer.copy(data, 0, tune.tracks, t * 64 * 6, tune.trackLength * 6) + patterns[t + 1] = { rows = tune.trackLength, data = data } + end + local order, positions = {}, {} + for i = 0, tune.positionNr - 1 do + order[i + 1] = i + local tr, tp = {}, {} + for c = 0, tune.channels - 1 do + tr[c + 1] = buffer.readu8(tune.positions, (i * 16 + c) * 2) + tp[c + 1] = buffer.readi8(tune.positions, (i * 16 + c) * 2 + 1) + end + positions[i + 1] = { tracks = tr, transpose = tp } + end + local m: any = { + kind = "music", + format = tune.format, + title = tune.title, + channels = tune.channels, + speed = 6, + tempo = 125 * tune.speedMultiplier, -- 50 Hz player calls per speed multiplier (a tick lasts 2.5 / tempo s) + patterns = patterns, + order = order, + positions = positions, + restart = tune.restart, + subsongs = table.clone(tune.subsongs), + instruments = tune.instruments, + samples = {}, + meta = { + source = { + format = tune.format, + version = tune.version, + speedMultiplier = tune.speedMultiplier, + trackLength = tune.trackLength, + tracks = tune.trackNr + 1, + mixgain = if tune.format == "hvl" then tune.mixgain else nil, + stereo = if tune.format == "hvl" then tune.stereo else nil, + }, + }, + tune = tune, + } + m.render = function(self: any, opts: RenderOptions?): Types.Decoder + local dec, derr = Hively.decoder(self.tune, opts) + if dec then + return dec + end + local empty: any = Pcm.audioDecoder(Types.Audio.new(44100, 2, 0)) + empty.err = derr + return empty + end + return m :: Types.Module +end + +return Hively +end +__FILES["codecs/audio/Hively/Load"] = function() + +-- codecs/audio/Hively/Load: AHX ("THX\0".."THX\2") and HivelyTracker ("HVL\0", "HVL\1") module files -> Tune. +-- Ported from hvl2wav replay.c 1.9 (hvl_load_ahx / hvl_reset; BSD-3-Clause, (c) 2006-2018 Pete Gordon; +-- licenses/hivelytracker-LICENSE.txt), with bounds checks the C code does not have. +local Load = {} + +local readu8, readi8 = buffer.readu8, buffer.readi8 + +type PlistEntry = { note: number, waveform: number, fixed: number, fx: { number }, param: { number } } +type Instrument = { + name: string, + volume: number, + waveLength: number, + filterLower: number, + filterUpper: number, + filterSpeed: number, + squareLower: number, + squareUpper: number, + squareSpeed: number, + vibratoDelay: number, + vibratoSpeed: number, + vibratoDepth: number, + hardCutRelease: number, + hardCutReleaseFrames: number, + envelope: { aFrames: number, aVolume: number, dFrames: number, dVolume: number, sFrames: number, rFrames: number, rVolume: number }, + plist: { speed: number, length: number, entries: { PlistEntry } }, +} +type Tune = { + format: string, + version: number, + title: string, + channels: number, + positionNr: number, + restart: number, + speedMultiplier: number, + trackLength: number, + trackNr: number, + instrumentNr: number, + subsongs: { number }, + positions: buffer, -- positionNr * 16 * 2 bytes: per channel track (u8), transpose (i8) + tracks: buffer, -- 257 * 64 * 6 bytes: per track row note, instrument, fx, param, fxb, paramb + instruments: { Instrument }, + mixgain: number, -- (percent * 256) / 100, HVL only (AHX: set by the stereo separation at render time) + stereo: number, + emptyTrack0: boolean, +} + +local function cstring(b: buffer, p: number, limit: number, max: number): (string, number) + local e = p + while e < limit and e - p < max and readu8(b, e) ~= 0 do + e += 1 + end + return buffer.readstring(b, p, e - p), e +end + +function Load.parse(b: buffer, base: number, limit: number): (Tune?, string?, string?) + local size = limit - base + if size < 14 then + return nil, "truncated header", "truncated" + end + local function u8(o: number): number + return readu8(b, base + o) + end + local magic = buffer.readstring(b, base, 3) + local ahx = magic == "THX" and u8(3) < 3 + if not ahx and not (magic == "HVL" and u8(3) <= 1) then + return nil, "not an AHX / HVL module", nil + end + if not ahx and size < 16 then + return nil, "truncated header", "truncated" + end + local posn = bit32.band(u8(6), 0x0f) * 256 + u8(7) + local insn, ssn, trkl, trkn = u8(12), u8(13), u8(10), u8(11) + local chnn = if ahx then 4 else bit32.rshift(u8(8), 2) + 4 + local tune: Tune = { + format = if ahx then "ahx" else "hvl", + version = u8(3), + title = "", + channels = chnn, + positionNr = posn, + restart = if ahx then u8(8) * 256 + u8(9) else bit32.band(u8(8), 3) * 256 + u8(9), + speedMultiplier = bit32.band(bit32.rshift(u8(6), 5), 3) + 1, + trackLength = trkl, + trackNr = trkn, + instrumentNr = insn, + subsongs = {}, + positions = buffer.create(math.max(posn, 1) * 32), + tracks = buffer.create(257 * 64 * 6), + instruments = {}, + mixgain = if ahx then 256 else (u8(14) * 256) // 100, + stereo = if ahx then 0 else math.min(u8(15), 4), + emptyTrack0 = bit32.band(u8(6), 0x80) ~= 0, + } + if posn == 0 or posn > 1000 or trkl > 64 or trkl == 0 or insn > 64 then + return nil, string.format("bad header (positions %d, track length %d, instruments %d)", posn, trkl, insn), nil + end + if chnn > 16 then + return nil, "unsupported: more than 16 channels", "unsupported" + end + if tune.restart >= posn then + tune.restart = posn - 1 + end + local nameAt = u8(4) * 256 + u8(5) + local nptr = limit + if nameAt < size then + local title, e = cstring(b, base + nameAt, limit, 128) + tune.title = title + nptr = e + 1 + end + + local p = base + (if ahx then 14 else 16) + local function need(n: number): boolean + return p + n <= limit + end + if not need(ssn * 2 + posn * chnn * 2) then + return nil, "truncated position list", "truncated" + end + for i = 1, ssn do + local s = readu8(b, p) * 256 + readu8(b, p + 1) + if s >= posn then + s = 0 + end + tune.subsongs[i] = s + p += 2 + end + for i = 0, posn - 1 do + for j = 0, chnn - 1 do + buffer.writeu8(tune.positions, (i * 16 + j) * 2, readu8(b, p)) + buffer.writei8(tune.positions, (i * 16 + j) * 2 + 1, readi8(b, p + 1)) + p += 2 + end + end + local tracks = tune.tracks + for i = 0, trkn do + if not (tune.emptyTrack0 and i == 0) then + for j = 0, trkl - 1 do + local o = (i * 64 + j) * 6 + if ahx then + if not need(3) then + return nil, "truncated track data", "truncated" + end + local b0, b1 = readu8(b, p), readu8(b, p + 1) + buffer.writeu8(tracks, o, bit32.band(bit32.rshift(b0, 2), 0x3f)) + buffer.writeu8(tracks, o + 1, bit32.band(b0, 3) * 16 + bit32.rshift(b1, 4)) + buffer.writeu8(tracks, o + 2, bit32.band(b1, 0xf)) + buffer.writeu8(tracks, o + 3, readu8(b, p + 2)) + p += 3 + else + if not need(1) then + return nil, "truncated track data", "truncated" + end + if readu8(b, p) == 0x3f then + p += 1 + else + if not need(5) then + return nil, "truncated track data", "truncated" + end + local fx = readu8(b, p + 2) + buffer.writeu8(tracks, o, readu8(b, p)) + buffer.writeu8(tracks, o + 1, readu8(b, p + 1)) + buffer.writeu8(tracks, o + 2, bit32.rshift(fx, 4)) + buffer.writeu8(tracks, o + 3, readu8(b, p + 3)) + buffer.writeu8(tracks, o + 4, bit32.band(fx, 0xf)) + buffer.writeu8(tracks, o + 5, readu8(b, p + 4)) + p += 5 + end + end + end + end + end + local plSize = if ahx then 4 else 5 + for i = 1, insn do + if not need(22) then + return nil, "truncated instrument", "truncated" + end + local function at(k: number): number + return readu8(b, p + k) + end + local name = "" + if nptr < limit then + local e + name, e = cstring(b, nptr, limit, 128) + nptr = e + 1 + end + local plen = at(21) + local ins: Instrument = { + name = name, + volume = at(0), + filterSpeed = bit32.bor(bit32.band(bit32.rshift(at(1), 3), 0x1f), bit32.band(bit32.rshift(at(12), 2), 0x20)), + waveLength = bit32.band(at(1), 7), + envelope = { aFrames = at(2), aVolume = at(3), dFrames = at(4), dVolume = at(5), sFrames = at(6), rFrames = at(7), rVolume = at(8) }, + filterLower = bit32.band(at(12), 0x7f), + vibratoDelay = at(13), + hardCutReleaseFrames = bit32.band(bit32.rshift(at(14), 4), 7), + hardCutRelease = if bit32.band(at(14), 0x80) ~= 0 then 1 else 0, + vibratoDepth = bit32.band(at(14), 0x0f), + vibratoSpeed = at(15), + squareLower = at(16), + squareUpper = at(17), + squareSpeed = at(18), + filterUpper = bit32.band(at(19), 0x3f), + plist = { speed = at(20), length = plen, entries = {} }, + } + p += 22 + if not need(plen * plSize) then + return nil, "truncated instrument play list", "truncated" + end + for j = 1, plen do + local e: PlistEntry + local b0, b1, b2, b3 = readu8(b, p), readu8(b, p + 1), readu8(b, p + 2), readu8(b, p + 3) + if ahx then + local k = bit32.band(bit32.rshift(b0, 5), 7) + k = if k == 6 then 12 elseif k == 7 then 15 else k + local l = bit32.band(bit32.rshift(b0, 2), 7) + l = if l == 6 then 12 elseif l == 7 then 15 else l + e = { + fx = { l, k }, + waveform = bit32.band(b0 * 2, 6) + bit32.rshift(b1, 7), + fixed = bit32.band(bit32.rshift(b1, 6), 1), + note = bit32.band(b1, 0x3f), + param = { b2, b3 }, + } + -- 1.6: version 0 modules (before filters) drop the "toggle filter" half of command 4 + if tune.version == 0 and l == 4 and bit32.band(b2, 0xf0) ~= 0 then + e.param[1] = bit32.band(b2, 0x0f) + end + if tune.version == 0 and k == 4 and bit32.band(b3, 0xf0) ~= 0 then + e.param[2] = bit32.band(b3, 0x0f) + end + else + e = { + fx = { bit32.band(b0, 0xf), bit32.band(bit32.rshift(b1, 3), 0xf) }, + waveform = bit32.band(b1, 7), + fixed = bit32.band(bit32.rshift(b2, 6), 1), + note = bit32.band(b2, 0x3f), + param = { b3, readu8(b, p + 4) }, + } + end + ins.plist.entries[j] = e + p += plSize + end + tune.instruments[i] = ins + end + return tune, nil, nil +end + +return Load +end +__FILES["codecs/audio/Hively/Player"] = @native function() + + +-- codecs/audio/Hively/Player: the AHX / HivelyTracker replayer and integer mixer, as hvl2wav's replay.c 1.9 computes them. +-- Ported from HivelyTracker (BSD-3-Clause, (c) 2006-2018 Pete Gordon; licenses/hivelytracker-LICENSE.txt). Where the C +-- code reads outside its arrays on bad data this port clamps instead. +local Tables = __include("codecs/audio/Hively/Tables") +local Load = __include("codecs/audio/Hively/Load") + +local Player = {} + +local readu8, readi8, writei8, writef32 = buffer.readu8, buffer.readi8, buffer.writei8, buffer.writef32 +local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift + +local FILTER_SET = Tables.FILTER_SET +local WO_TRIANGLE_04, WO_SAWTOOTH_04 = Tables.WO_TRIANGLE_04, Tables.WO_SAWTOOTH_04 +local WO_SQUARES, WO_WHITENOISE = Tables.WO_SQUARES, Tables.WO_WHITENOISE +local OFFSETS, VIB, PERIOD = Tables.OFFSETS, Tables.VIB, Tables.PERIOD +local WAVEFORM_AT = { [0] = WO_TRIANGLE_04, WO_SAWTOOTH_04, 0, WO_WHITENOISE } +local WRAP = 0x280 * 65536 +local TWO32 = 4294967296 + +local f32scratch = buffer.create(4) + +@native local function s16(v: number): number + return (v + 32768) % 65536 - 32768 +end + +@native local function tdiv(a: number, b: number): number -- C integer division (truncates) + local q = a / b + return if q >= 0 then math.floor(q) else -math.floor(-q) +end + +@native local function period(i: number): number + return PERIOD[i] or 0 +end + +-- (3546897.f * 65536.f) / period as a float, then / mix rate as a double, truncated +@native local function deltaOf(p: number, freq: number): number + if p == 0 then + return 1 + end + writef32(f32scratch, 0, 232449441792 / p) -- 3546897 * 65536 = 232449441792 (exact in a float) + local d = math.floor(buffer.readf32(f32scratch, 0) / freq) + if d < 0 then + d = 0 + end + if d > WRAP then + d -= WRAP + end + if d == 0 then + d = 1 + end + return d +end + +type Voice = { [string]: any } +type State = { + tune: Load.Tune, + freq: number, + version: number, + channels: number, + voices: { Voice }, + tempo: number, + posNr: number, + posJump: number, + posJumpNote: number, + noteNr: number, + stepWaitFrames: number, + getNewPosition: boolean, + patternBreak: boolean, + songEndReached: boolean, + playingTime: number, + mixgain: number, + waves: buffer, + panL: { number }, + panR: { number }, +} + +@native local function newVoice(i: number): Voice + return { + track = 0, nextTrack = 0, transpose = 0, nextTranspose = 0, overrideTranspose = 1000, + adsrVolume = 0, aFrames = 0, aVolume = 0, dFrames = 0, dVolume = 0, sFrames = 0, rFrames = 0, rVolume = 0, + instrument = false :: any, samplePos = 0, delta = 1, instrPeriod = 0, trackPeriod = 0, vibratoPeriod = 0, + waveLength = 0, noteMaxVolume = 0, perfSubVolume = 0, newWaveform = false, waveform = 0, plantPeriod = false, + voiceVolume = 0, plantSquare = false, ignoreSquare = 0, fixedNote = 0, volumeSlideUp = 0, volumeSlideDown = 0, + hardCut = 0, hardCutRelease = 0, hardCutReleaseF = 0, periodSlideOn = false, periodSlideSpeed = 0, + periodSlidePeriod = 0, periodSlideLimit = 0, periodSlideWithLimit = false, periodPerfSlideSpeed = 0, + periodPerfSlidePeriod = 0, periodPerfSlideOn = false, vibratoDelay = 0, vibratoSpeed = 0, vibratoCurrent = 0, + vibratoDepth = 0, squareOn = 0, squareInit = 0, squareWait = 0, squareLowerLimit = 0, squareUpperLimit = 0, + squarePos = 0, squareSign = 0, squareSlidingIn = false, squareReverse = false, filterOn = 0, filterInit = 0, + filterWait = 0, filterSpeed = 0, filterUpperLimit = 0, filterLowerLimit = 0, filterPos = 0, filterSign = 0, + filterSlidingIn = false, ignoreFilter = 0, perfCurrent = 0, perfSpeed = 0, perfWait = 0, perfList = false :: any, + audioSrc = false :: any, audioOff = 0, noteDelayOn = false, noteCutOn = false, noteDelayWait = 0, noteCutWait = 0, + audioPeriod = 0, audioVolume = 0, wnHi = 0, wnLo = 0x280, + squareBuf = buffer.create(0x80), voiceBuf = buffer.create(0x284), voiceNum = i, trackMasterVolume = 0x40, + pan = 0, setPan = 0, panMultLeft = 0, panMultRight = 0, + ringSamplePos = 0, ringDelta = 0, ringMix = false, ringPlantPeriod = false, ringBasePeriod = 0, + ringAudioPeriod = 0, ringAudioOff = -1, ringNewWaveform = false, ringWaveform = 0, ringFixedPeriod = 0, + ringBuf = buffer.create(0x284), + } +end + +@native function Player.new(tune: Load.Tune, freq: number, stereo: number, subsong: number): State? + if subsong < 0 or subsong > #tune.subsongs then + return nil + end + local t = Tables.get() + local defstereo = if tune.format == "ahx" then math.clamp(math.floor(stereo), 0, 4) else tune.stereo + local mixgain = tune.mixgain + if tune.format == "ahx" then + local defgain = { [0] = 71, 72, 76, 85, 100 } + mixgain = (defgain[defstereo] * 256) // 100 + end + local st: State = { + tune = tune, freq = freq, version = if tune.format == "hvl" then tune.version else 0, + channels = tune.channels, voices = {}, tempo = 6, posNr = if subsong > 0 then tune.subsongs[subsong] else 0, + posJump = 0, posJumpNote = 0, noteNr = 0, stepWaitFrames = 0, getNewPosition = true, patternBreak = false, + songEndReached = false, playingTime = 0, mixgain = mixgain, waves = t.waves, panL = t.panL, panR = t.panR, + } + local left, right = Tables.STEREO_LEFT[defstereo], Tables.STEREO_RIGHT[defstereo] + for i = 0, 15 do + local v = newVoice(i) + local p = if i % 4 == 0 or i % 4 == 3 then left else right + v.pan, v.setPan, v.panMultLeft, v.panMultRight = p, p, t.panL[p], t.panR[p] + st.voices[i + 1] = v + end + return st +end + +@native local function setPan(st: State, v: Voice, p: number) + v.pan = p + v.panMultLeft, v.panMultRight = st.panL[p], st.panR[p] +end + +@native local function stepfx1(st: State, v: Voice, fx: number, param: number) + if fx == 0x0 then + local lo = band(param, 0x0f) + if lo > 0 and lo <= 9 then + st.posJump = lo + end + elseif fx == 0x5 or fx == 0xa then + v.volumeSlideDown = band(param, 0x0f) + v.volumeSlideUp = rshift(param, 4) + elseif fx == 0x7 then + if param > 127 then + param -= 256 + end + setPan(st, v, param + 128) + v.setPan = param + 128 + elseif fx == 0xb then + st.posJump = (st.posJump * 100 + band(param, 0x0f) + rshift(param, 4) * 10) % 65536 + st.patternBreak = true + if st.posJump <= st.posNr then + st.songEndReached = true + end + elseif fx == 0xd then + st.posJump = st.posNr + 1 + st.posJumpNote = band(param, 0x0f) + rshift(param, 4) * 10 + st.patternBreak = true + if st.posJumpNote > st.tune.trackLength then + st.posJumpNote = 0 + end + elseif fx == 0xe then + if rshift(param, 4) == 0xc and band(param, 0x0f) < st.tempo then + v.noteCutWait = band(param, 0x0f) + if v.noteCutWait ~= 0 then + v.noteCutOn = true + v.hardCutRelease = 0 + end + end + elseif fx == 0xf then + st.tempo = param + if param == 0 then + st.songEndReached = true + end + end +end + +@native local function stepfx2(v: Voice, fx: number, param: number, note: number): number + if fx == 0x9 then + v.squarePos = rshift(param, 5 - v.waveLength) + v.ignoreSquare = 1 + elseif fx == 0x3 or fx == 0x5 then + if fx == 0x3 and param ~= 0 then + v.periodSlideSpeed = param + end + if note ~= 0 then + local new = period(note) + local diff = period(v.trackPeriod) - new + new = diff + v.periodSlidePeriod + if new ~= 0 then + v.periodSlideLimit = s16(-diff) + end + end + v.periodSlideOn = true + v.periodSlideWithLimit = true + note = 0 + end + return note +end + +@native local function stepfx3(st: State, v: Voice, fx: number, param: number) + if fx == 0x01 then + v.periodSlideSpeed = -param + v.periodSlideOn = true + v.periodSlideWithLimit = false + elseif fx == 0x02 then + v.periodSlideSpeed = param + v.periodSlideOn = true + v.periodSlideWithLimit = false + elseif fx == 0x04 then + if param == 0 or param == 0x40 then + return + end + if param < 0x40 then + v.ignoreFilter = param + return + end + if param > 0x7f then + return + end + v.filterPos = param - 0x40 + elseif fx == 0x0c then + if param <= 0x40 then + v.noteMaxVolume = param + return + end + param -= 0x50 + if param < 0 then + return + end + if param <= 0x40 then + for i = 1, st.channels do + st.voices[i].trackMasterVolume = param + end + return + end + param -= 0xa0 - 0x50 + if param < 0 then + return + end + if param <= 0x40 then + v.trackMasterVolume = param + end + elseif fx == 0xe then + local sub, lo = rshift(param, 4), band(param, 0x0f) + if sub == 0x1 then + v.periodSlidePeriod = s16(v.periodSlidePeriod - lo) + v.plantPeriod = true + elseif sub == 0x2 then + v.periodSlidePeriod = s16(v.periodSlidePeriod + lo) + v.plantPeriod = true + elseif sub == 0x4 then + v.vibratoDepth = lo + elseif sub == 0xa then + v.noteMaxVolume = math.min(v.noteMaxVolume + lo, 0x40) + elseif sub == 0xb then + v.noteMaxVolume = math.max(v.noteMaxVolume - lo, 0) + elseif sub == 0xf then + if st.version >= 1 and lo == 1 then + v.overrideTranspose = v.transpose + end + end + end +end + +@native local function processStep(st: State, v: Voice) + v.volumeSlideUp, v.volumeSlideDown = 0, 0 + local tune = st.tune + local track = readu8(tune.positions, (st.posNr * 16 + v.voiceNum) * 2) + local so = (track * 64 + st.noteNr) * 6 + local tracks = tune.tracks + local note, instr = readu8(tracks, so), readu8(tracks, so + 1) + local fx, fxp, fxb, fxbp = band(readu8(tracks, so + 2), 0xf), readu8(tracks, so + 3), band(readu8(tracks, so + 4), 0xf), readu8(tracks, so + 5) + + local doneNoteDel = false + if fx == 0xe and band(fxp, 0xf0) == 0xd0 then + if v.noteDelayOn then + v.noteDelayOn = false + doneNoteDel = true + elseif band(fxp, 0x0f) < st.tempo then + v.noteDelayWait = band(fxp, 0x0f) + if v.noteDelayWait ~= 0 then + v.noteDelayOn = true + return + end + end + end + if not doneNoteDel and fxb == 0xe and band(fxbp, 0xf0) == 0xd0 then + if v.noteDelayOn then + v.noteDelayOn = false + elseif band(fxbp, 0x0f) < st.tempo then + v.noteDelayWait = band(fxbp, 0x0f) + if v.noteDelayWait ~= 0 then + v.noteDelayOn = true + return + end + end + end + + if note ~= 0 then + v.overrideTranspose = 1000 + end + stepfx1(st, v, fx, fxp) + stepfx1(st, v, fxb, fxbp) + + if instr ~= 0 and instr <= tune.instrumentNr then + local ins = tune.instruments[instr] + setPan(st, v, v.setPan) + v.periodSlideSpeed, v.periodSlidePeriod, v.periodSlideLimit = 0, 0, 0 + v.perfSubVolume = 0x40 + v.adsrVolume = 0 + v.instrument = ins + v.samplePos = 0 + local env = ins.envelope + v.aFrames = env.aFrames + v.aVolume = s16(if v.aFrames ~= 0 then tdiv(env.aVolume * 256, v.aFrames) else env.aVolume * 256) + v.dFrames = env.dFrames + v.dVolume = s16(if v.dFrames ~= 0 then tdiv((env.dVolume - env.aVolume) * 256, v.dFrames) else env.dVolume * 256) + v.sFrames = env.sFrames + v.rFrames = env.rFrames + v.rVolume = s16(if v.rFrames ~= 0 then tdiv((env.rVolume - env.dVolume) * 256, v.rFrames) else env.rVolume * 256) + v.waveLength = math.min(ins.waveLength, 5) + v.noteMaxVolume = ins.volume + v.vibratoCurrent = 0 + v.vibratoDelay = ins.vibratoDelay + v.vibratoDepth = ins.vibratoDepth + v.vibratoSpeed = ins.vibratoSpeed + v.vibratoPeriod = 0 + v.hardCutRelease = ins.hardCutRelease + v.hardCut = ins.hardCutReleaseFrames + v.ignoreSquare, v.squareSlidingIn = 0, false + v.squareWait, v.squareOn = 0, 0 + local lower = rshift(ins.squareLower, 5 - v.waveLength) + local upper = rshift(ins.squareUpper, 5 - v.waveLength) + if upper < lower then + lower, upper = upper, lower + end + v.squareUpperLimit, v.squareLowerLimit = upper, lower + v.ignoreFilter, v.filterWait, v.filterOn = 0, 0, 0 + v.filterSlidingIn = false + local d6, d3, d4 = ins.filterSpeed, ins.filterLower, ins.filterUpper + v.filterSpeed = d6 + if d3 > d4 then + d3, d4 = d4, d3 + end + v.filterUpperLimit, v.filterLowerLimit = d4, d3 + v.filterPos = 32 + v.perfWait, v.perfCurrent = 0, 0 + v.perfSpeed = ins.plist.speed + v.perfList = ins.plist + v.ringMix = false + v.ringSamplePos = 0 + v.ringPlantPeriod = false + v.ringNewWaveform = false + end + + v.periodSlideOn = false + note = stepfx2(v, fx, fxp, note) + note = stepfx2(v, fxb, fxbp, note) + if note ~= 0 then + v.trackPeriod = note + v.plantPeriod = true + end + stepfx3(st, v, fx, fxp) + stepfx3(st, v, fxb, fxbp) +end + +@native local function plistCommand(st: State, v: Voice, fx: number, param: number) + if fx == 0 then + if param > 0 and param < 0x40 then + if v.ignoreFilter ~= 0 then + v.filterPos = v.ignoreFilter + v.ignoreFilter = 0 + else + v.filterPos = param + end + v.newWaveform = true + end + elseif fx == 1 then + v.periodPerfSlideSpeed = param + v.periodPerfSlideOn = true + elseif fx == 2 then + v.periodPerfSlideSpeed = -param + v.periodPerfSlideOn = true + elseif fx == 3 then + if v.ignoreSquare == 0 then + v.squarePos = rshift(param, 5 - v.waveLength) + else + v.ignoreSquare = 0 + end + elseif fx == 4 then + if param == 0 then + v.squareOn = 1 - v.squareOn + v.squareInit = v.squareOn + v.squareSign = 1 + else + if band(param, 0x0f) ~= 0 then + v.squareOn = 1 - v.squareOn + v.squareInit = v.squareOn + v.squareSign = if band(param, 0x0f) == 0x0f then -1 else 1 + end + if band(param, 0xf0) ~= 0 then + v.filterOn = 1 - v.filterOn + v.filterInit = v.filterOn + v.filterSign = if band(param, 0xf0) == 0xf0 then -1 else 1 + end + end + elseif fx == 5 then + v.perfCurrent = param + elseif fx == 7 or fx == 8 then + if param >= 1 and param <= 0x3c then + v.ringBasePeriod = param + v.ringFixedPeriod = 1 + elseif param >= 0x81 and param <= 0xbc then + v.ringBasePeriod = param - 0x80 + v.ringFixedPeriod = 0 + else + v.ringBasePeriod = 0 + v.ringFixedPeriod = 0 + v.ringNewWaveform = false + v.ringAudioOff = -1 + v.ringMix = false + return + end + v.ringWaveform = fx - 7 + v.ringNewWaveform = true + v.ringPlantPeriod = true + elseif fx == 9 then + if param > 127 then + param -= 256 + end + setPan(st, v, param + 128) + elseif fx == 12 then + if param <= 0x40 then + v.noteMaxVolume = param + return + end + param -= 0x50 + if param < 0 then + return + end + if param <= 0x40 then + v.perfSubVolume = param + return + end + param -= 0xa0 - 0x50 + if param < 0 then + return + end + if param <= 0x40 then + v.trackMasterVolume = param + end + elseif fx == 15 then + v.perfSpeed = param + v.perfWait = param + end +end + +-- the noise offset generator (vc_WNRandom, a 64-bit `long` in hvl2wav): W += 2239384; +-- W = ((((W >> 8) | (W << 24)) + 782323) ^ 75) - 6735 +@native local function wnStep(v: Voice) + local hi, lo = v.wnHi, v.wnLo + 2239384 + if lo >= TWO32 then + lo -= TWO32 + hi = (hi + 1) % TWO32 + end + local shi = rshift(hi, 8) + if hi >= 0x80000000 then + shi = bor(shi, 0xff000000) + end + local nlo = bor(rshift(lo, 8), lshift(band(hi, 0xff), 24), lshift(lo, 24)) + local nhi = bor(shi, lshift(hi, 24), rshift(lo, 8)) + nlo += 782323 + if nlo >= TWO32 then + nlo -= TWO32 + nhi = (nhi + 1) % TWO32 + end + nlo = bit32.bxor(nlo, 75) + nlo -= 6735 + if nlo < 0 then + nlo += TWO32 + nhi = (nhi + TWO32 - 1) % TWO32 + end + v.wnHi, v.wnLo = nhi, nlo +end + +@native local function processFrame(st: State, v: Voice) + local tune = st.tune + if v.noteDelayOn then + if v.noteDelayWait <= 0 then + processStep(st, v) + else + v.noteDelayWait -= 1 + end + end + + if v.hardCut ~= 0 then + local row = st.noteNr + 1 + local nextinst + if row < tune.trackLength then + nextinst = readu8(tune.tracks, ((v.track * 64) + row) * 6 + 1) + else + nextinst = readu8(tune.tracks, (v.nextTrack * 64) * 6 + 1) + end + if nextinst ~= 0 then + local d1 = math.max(st.tempo - v.hardCut, 0) + if not v.noteCutOn then + v.noteCutOn = true + v.noteCutWait = d1 + v.hardCutReleaseF = -(d1 - st.tempo) + else + v.hardCut = 0 + end + end + end + + if v.noteCutOn then + if v.noteCutWait <= 0 then + v.noteCutOn = false + if v.hardCutRelease ~= 0 then + local ins = v.instrument + local f = v.hardCutReleaseF + v.rVolume = if f ~= 0 then s16(tdiv(-(v.adsrVolume - ins.envelope.rVolume * 256), f)) else 0 + v.rFrames = f + v.aFrames, v.dFrames, v.sFrames = 0, 0, 0 + else + v.noteMaxVolume = 0 + end + else + v.noteCutWait -= 1 + end + end + + if v.aFrames ~= 0 then + v.adsrVolume += v.aVolume + v.aFrames -= 1 + if v.aFrames <= 0 then + v.adsrVolume = v.instrument.envelope.aVolume * 256 + end + elseif v.dFrames ~= 0 then + v.adsrVolume += v.dVolume + v.dFrames -= 1 + if v.dFrames <= 0 then + v.adsrVolume = v.instrument.envelope.dVolume * 256 + end + elseif v.sFrames ~= 0 then + v.sFrames -= 1 + elseif v.rFrames ~= 0 then + v.adsrVolume += v.rVolume + v.rFrames -= 1 + if v.rFrames <= 0 then + v.adsrVolume = v.instrument.envelope.rVolume * 256 + end + end + + v.noteMaxVolume = math.clamp(v.noteMaxVolume + v.volumeSlideUp - v.volumeSlideDown, 0, 0x40) + + if v.periodSlideOn then + if v.periodSlideWithLimit then + local d0 = v.periodSlidePeriod - v.periodSlideLimit + local d2 = v.periodSlideSpeed + if d0 > 0 then + d2 = -d2 + end + if d0 ~= 0 then + local sum = d0 + d2 + -- (d0 + d2) ^ d0 >= 0: the same sign (or zero) + if (sum >= 0) == (d0 >= 0) then + d0 = v.periodSlidePeriod + d2 + else + d0 = v.periodSlideLimit + end + v.periodSlidePeriod = s16(d0) + v.plantPeriod = true + end + else + v.periodSlidePeriod = s16(v.periodSlidePeriod + v.periodSlideSpeed) + v.plantPeriod = true + end + end + + if v.vibratoDepth ~= 0 then + if v.vibratoDelay <= 0 then + v.vibratoPeriod = (VIB[v.vibratoCurrent] * v.vibratoDepth) // 128 + v.plantPeriod = true + v.vibratoCurrent = band(v.vibratoCurrent + v.vibratoSpeed, 0x3f) + else + v.vibratoDelay -= 1 + end + end + + local pl = v.perfList + if pl then + if v.instrument and v.perfCurrent < v.instrument.plist.length then + local overflow = v.perfWait == 128 + v.perfWait = s16(v.perfWait - 1) + local w8 = (v.perfWait + 128) % 256 - 128 + if overflow or w8 <= 0 then + local cur = v.perfCurrent + v.perfCurrent += 1 + v.perfWait = v.perfSpeed + local e = pl.entries[cur + 1] + if e then + if e.waveform ~= 0 then + v.waveform = e.waveform - 1 + v.newWaveform = true + v.periodPerfSlideSpeed, v.periodPerfSlidePeriod = 0, 0 + end + v.periodPerfSlideOn = false + plistCommand(st, v, e.fx[1], e.param[1]) + plistCommand(st, v, e.fx[2], e.param[2]) + if e.note ~= 0 then + v.instrPeriod = e.note + v.plantPeriod = true + v.fixedNote = e.fixed + end + end + end + else + if v.perfWait ~= 0 then + v.perfWait -= 1 + else + v.periodPerfSlideSpeed = 0 + end + end + end + + if v.periodPerfSlideOn then + v.periodPerfSlidePeriod = s16(v.periodPerfSlidePeriod - v.periodPerfSlideSpeed) + if v.periodPerfSlidePeriod ~= 0 then + v.plantPeriod = true + end + end + + if v.waveform == 2 and v.squareOn ~= 0 then + v.squareWait -= 1 + if v.squareWait <= 0 then + local d1, d2, d3 = v.squareLowerLimit, v.squareUpperLimit, v.squarePos + if v.squareInit ~= 0 then + v.squareInit = 0 + if d3 <= d1 then + v.squareSlidingIn = true + v.squareSign = 1 + elseif d3 >= d2 then + v.squareSlidingIn = true + v.squareSign = -1 + end + end + if d1 == d3 or d2 == d3 then + if v.squareSlidingIn then + v.squareSlidingIn = false + else + v.squareSign = -v.squareSign + end + end + d3 += v.squareSign + v.squarePos = s16(d3) + v.plantSquare = true + local ins: any = v.instrument + v.squareWait = if ins then ins.squareSpeed else 0 + end + end + + if v.filterOn ~= 0 then + v.filterWait -= 1 + if v.filterWait <= 0 then + local d1, d2, d3 = v.filterLowerLimit, v.filterUpperLimit, v.filterPos + if v.filterInit ~= 0 then + v.filterInit = 0 + if d3 <= d1 then + v.filterSlidingIn = true + v.filterSign = 1 + elseif d3 >= d2 then + v.filterSlidingIn = true + v.filterSign = -1 + end + end + local fmax = if v.filterSpeed < 4 then 5 - v.filterSpeed else 1 + for _ = 1, fmax do + if d1 == d3 or d2 == d3 then + if v.filterSlidingIn then + v.filterSlidingIn = false + else + v.filterSign = -v.filterSign + end + end + d3 += v.filterSign + end + v.filterPos = math.clamp(d3, 1, 63) + v.newWaveform = true + v.filterWait = math.max(v.filterSpeed - 3, 1) + end + end + + local waves = st.waves + local fpos = math.clamp(v.filterPos, 1, 63) + if v.waveform == 2 or v.plantSquare then + -- CalcSquare + local sp = WO_SQUARES + (fpos - 0x20) * FILTER_SET + local x = v.squarePos * 2 ^ (5 - v.waveLength) + if x > 0x20 then + x = 0x40 - x + v.squareReverse = true + end + if x > 0 then + sp += (x - 1) * 128 + end + local delta = 32 // 2 ^ v.waveLength + local sb = v.squareBuf + for i = 0, 4 * 2 ^ v.waveLength - 1 do + writei8(sb, i, readi8(waves, sp)) + sp += delta + end + v.newWaveform = true + v.waveform = 2 + v.plantSquare = false + end + + if v.waveform == 3 then + v.newWaveform = true + end + + if v.ringNewWaveform then + if v.ringWaveform > 1 then + v.ringWaveform = 1 + end + v.ringAudioOff = WAVEFORM_AT[v.ringWaveform] + OFFSETS[v.waveLength] + end + + if v.newWaveform and v.waveform <= 3 then + if v.waveform == 2 then + v.audioSrc, v.audioOff = v.squareBuf, 0 + else + local off = WAVEFORM_AT[v.waveform] + (fpos - 0x20) * FILTER_SET + if v.waveform < 2 then + off += OFFSETS[v.waveLength] + else + off += band(band(v.wnLo, 2 * 0x280 - 1), 0xfffffffe) + wnStep(v) + end + v.audioSrc, v.audioOff = waves, off + end + end + + if v.ringAudioOff >= 0 then + local rp = v.ringBasePeriod + if v.ringFixedPeriod == 0 then + if v.overrideTranspose ~= 1000 then + rp += v.overrideTranspose + v.trackPeriod - 1 + else + rp += v.transpose + v.trackPeriod - 1 + end + end + rp = period(math.clamp(s16(rp), 0, 60)) + if v.ringFixedPeriod == 0 then + rp += v.periodSlidePeriod + end + rp = s16(rp + v.periodPerfSlidePeriod + v.vibratoPeriod) + v.ringAudioPeriod = math.clamp(rp, 0x71, 0xd60) + end + + local ap = v.instrPeriod + if v.fixedNote == 0 then + if v.overrideTranspose ~= 1000 then + ap += v.overrideTranspose + v.trackPeriod - 1 + else + ap += v.transpose + v.trackPeriod - 1 + end + end + ap = period(math.clamp(s16(ap), 0, 60)) + if v.fixedNote == 0 then + ap += v.periodSlidePeriod + end + ap = s16(ap + v.periodPerfSlidePeriod + v.vibratoPeriod) + v.audioPeriod = math.clamp(ap, 0x71, 0xd60) + + local vol = (v.adsrVolume // 256 * v.noteMaxVolume) // 64 + vol = (vol * v.perfSubVolume) // 64 + vol = (vol * v.trackMasterVolume) // 64 + v.audioVolume = s16(vol) +end + +@native local function fillCycles(dst: buffer, src: buffer, off: number, len: number) + if off < 0 or off + len > buffer.len(src) then + buffer.fill(dst, 0, 0, 0x281) + return + end + buffer.copy(dst, 0, src, off, len) + local filled = len + while filled < 0x280 do + local k = math.min(filled, 0x280 - filled) + buffer.copy(dst, filled, dst, 0, k) + filled += k + end + writei8(dst, 0x280, readi8(dst, 0)) +end + +@native local function setAudio(st: State, v: Voice) + v.voiceVolume = v.audioVolume % 256 + if v.plantPeriod then + v.plantPeriod = false + v.delta = deltaOf(v.audioPeriod, st.freq) + end + local src: buffer? = v.audioSrc or nil + if v.newWaveform and src then + fillCycles(v.voiceBuf, src, v.audioOff, if v.waveform == 3 then 0x280 else 4 * 2 ^ v.waveLength) + end + if v.ringPlantPeriod then + v.ringPlantPeriod = false + v.ringDelta = deltaOf(v.ringAudioPeriod, st.freq) + end + if v.ringNewWaveform and v.ringAudioOff >= 0 then + fillCycles(v.ringBuf, st.waves, v.ringAudioOff, 4 * 2 ^ v.waveLength) + v.ringMix = true + end +end + +-- hvl_play_irq (audio = false skips the audio side) +@native function Player.irq(st: State, audio: boolean) + local tune = st.tune + local nch = st.channels + local voices = st.voices + if st.stepWaitFrames == 0 then + if st.getNewPosition then + local nextpos = if st.posNr + 1 == tune.positionNr then 0 else st.posNr + 1 + local P = tune.positions + for i = 0, nch - 1 do + local v = voices[i + 1] + v.track = readu8(P, (st.posNr * 16 + i) * 2) + v.transpose = readi8(P, (st.posNr * 16 + i) * 2 + 1) + v.nextTrack = readu8(P, (nextpos * 16 + i) * 2) + v.nextTranspose = readi8(P, (nextpos * 16 + i) * 2 + 1) + end + st.getNewPosition = false + end + for i = 1, nch do + processStep(st, voices[i]) + end + st.stepWaitFrames = st.tempo + end + for i = 1, nch do + processFrame(st, voices[i]) + end + st.playingTime += 1 + st.stepWaitFrames = s16(st.stepWaitFrames - 1) + if st.stepWaitFrames == 0 then + if not st.patternBreak then + st.noteNr += 1 + if st.noteNr >= tune.trackLength then + st.posJump = st.posNr + 1 + st.posJumpNote = 0 + st.patternBreak = true + end + end + if st.patternBreak then + st.patternBreak = false + st.posNr = st.posJump + st.noteNr = st.posJumpNote + if st.posNr >= tune.positionNr then + -- (past the end is bad data: the C code reads outside its position list) + st.songEndReached = true + st.posNr = tune.restart + end + st.posJumpNote = 0 + st.posJump = 0 + st.getNewPosition = true + end + end + if audio then + for i = 1, nch do + setAudio(st, voices[i]) + end + end +end + +-- hvl_mixchunk: integer mixing, s16 clipping, / 32768 +@native function Player.mix(st: State, out: buffer, at: number, n: number) + local nch = st.channels + local voices = st.voices + local src, rsrc, delta, rdelta, vol, pos, rpos, panl, panr = {}, {}, {}, {}, {}, {}, {}, {}, {} + for i = 1, nch do + local v = voices[i] + delta[i] = math.max(v.delta, 1) + vol[i] = v.voiceVolume + pos[i] = v.samplePos + src[i] = v.voiceBuf + panl[i] = v.panMultLeft + panr[i] = v.panMultRight + rdelta[i] = math.max(v.ringDelta, 1) + rpos[i] = v.ringSamplePos + rsrc[i] = if v.ringMix then v.ringBuf else false + end + local gain = st.mixgain + local o = at * 8 + local samples = n + while samples > 0 do + local loops = samples + for i = 1, nch do + if pos[i] >= WRAP then + pos[i] -= WRAP + end + local cnt = (WRAP - pos[i] - 1) // delta[i] + 1 + if cnt < loops then + loops = cnt + end + if rsrc[i] then + if rpos[i] >= WRAP then + rpos[i] -= WRAP + end + cnt = (WRAP - rpos[i] - 1) // rdelta[i] + 1 + if cnt < loops then + loops = cnt + end + end + end + samples -= loops + for _ = 1, loops do + local a, b = 0, 0 + for i = 1, nch do + local j + local r = rsrc[i] + if r then + j = ((readi8(src[i], pos[i] // 65536) * readi8(r, rpos[i] // 65536)) // 128) * vol[i] + rpos[i] += rdelta[i] + else + j = readi8(src[i], pos[i] // 65536) * vol[i] + end + a += (j * panl[i]) // 128 + b += (j * panr[i]) // 128 + pos[i] += delta[i] + end + a = (a * gain) // 256 + b = (b * gain) // 256 + if a < -32768 then + a = -32768 + elseif a > 32767 then + a = 32767 + end + if b < -32768 then + b = -32768 + elseif b > 32767 then + b = 32767 + end + writef32(out, o, a / 32768) + writef32(out, o + 4, b / 32768) + o += 8 + end + end + for i = 1, nch do + voices[i].samplePos = pos[i] + voices[i].ringSamplePos = rpos[i] + end +end + +return Player +end +__FILES["codecs/audio/Hively/Tables"] = @native function() + + +-- codecs/audio/Hively/Tables: the AHX / HivelyTracker replayer's waveform, panning, vibrato and period tables. +-- Ported from hvl2wav replay.c 1.9 (BSD-3-Clause, (c) 2006-2018 Pete Gordon; licenses/hivelytracker-LICENSE.txt) as +-- built on 64-bit Linux (`long` is 64-bit: the noise generator's shifts do not wrap at 32 bits). +local Tables = {} + +local band, bor, bxor, lshift, rshift = bit32.band, bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift + +local FILTER_SET = 0xfc + 0xfc + 0x80 * 0x1f + 0x80 + 3 * 0x280 -- 6520: one filtered copy of every waveform +local WHITENOISELEN = 0x280 * 3 +local WO_LOWPASSES = 0 +local WO_TRIANGLE_04 = WO_LOWPASSES + FILTER_SET * 31 +local WO_SAWTOOTH_04 = WO_TRIANGLE_04 + 0xfc +local WO_SQUARES = WO_SAWTOOTH_04 + 0xfc +local WO_WHITENOISE = WO_SQUARES + 0x80 * 0x20 +local WO_HIGHPASSES = WO_WHITENOISE + WHITENOISELEN +local WAVES_SIZE = WO_HIGHPASSES + FILTER_SET * 31 + +Tables.FILTER_SET = FILTER_SET +Tables.WO_TRIANGLE_04 = WO_TRIANGLE_04 +Tables.WO_SAWTOOTH_04 = WO_SAWTOOTH_04 +Tables.WO_SQUARES = WO_SQUARES +Tables.WO_WHITENOISE = WO_WHITENOISE +Tables.WAVES_SIZE = WAVES_SIZE +-- offset of the waveform of length 4 << n inside the triangle / sawtooth runs +Tables.OFFSETS = { [0] = 0x00, 0x04, 0x04 + 0x08, 0x04 + 0x08 + 0x10, 0x04 + 0x08 + 0x10 + 0x20, 0x04 + 0x08 + 0x10 + 0x20 + 0x40 } + +Tables.VIB = { + [0] = 0, 24, 49, 74, 97, 120, 141, 161, 180, 197, 212, 224, 235, 244, 250, 253, 255, + 253, 250, 244, 235, 224, 212, 197, 180, 161, 141, 120, 97, 74, 49, 24, + 0, -24, -49, -74, -97, -120, -141, -161, -180, -197, -212, -224, -235, -244, -250, -253, -255, + -253, -250, -244, -235, -224, -212, -197, -180, -161, -141, -120, -97, -74, -49, -24, +} + +Tables.PERIOD = { + [0] = 0x0000, 0x0D60, 0x0CA0, 0x0BE8, 0x0B40, 0x0A98, 0x0A00, 0x0970, + 0x08E8, 0x0868, 0x07F0, 0x0780, 0x0714, 0x06B0, 0x0650, 0x05F4, + 0x05A0, 0x054C, 0x0500, 0x04B8, 0x0474, 0x0434, 0x03F8, 0x03C0, + 0x038A, 0x0358, 0x0328, 0x02FA, 0x02D0, 0x02A6, 0x0280, 0x025C, + 0x023A, 0x021A, 0x01FC, 0x01E0, 0x01C5, 0x01AC, 0x0194, 0x017D, + 0x0168, 0x0153, 0x0140, 0x012E, 0x011D, 0x010D, 0x00FE, 0x00F0, + 0x00E2, 0x00D6, 0x00CA, 0x00BE, 0x00B4, 0x00AA, 0x00A0, 0x0097, + 0x008F, 0x0087, 0x007F, 0x0078, 0x0071, +} + +Tables.STEREO_LEFT = { [0] = 128, 96, 64, 32, 0 } +Tables.STEREO_RIGHT = { [0] = 128, 160, 193, 225, 255 } + +@native local function i8(v: number): number + v = v % 256 + return if v >= 128 then v - 256 else v +end + +@native local function genSawtooth(w: buffer, at: number, len: number) + local add = 256 // (len - 1) + local val = -128 + for i = 0, len - 1 do + buffer.writei8(w, at + i, i8(val)) + val += add + end +end + +@native local function genTriangle(w: buffer, at: number, len: number) + local d5 = len // 4 + local d1 = 128 // d5 + local d4 = -(len // 2) + local p = at + local val = 0 + for _ = 1, d5 do + buffer.writei8(w, p, i8(val)) + p += 1 + val += d1 + end + buffer.writei8(w, p, 0x7f) + p += 1 + if d5 ~= 1 then + val = 128 + for _ = 1, d5 - 1 do + val -= d1 + buffer.writei8(w, p, i8(val)) + p += 1 + end + end + local q = p + d4 + for _ = 1, d5 * 2 do + local c = buffer.readi8(w, q) + q += 1 + buffer.writei8(w, p, if c == 0x7f then -128 else i8(-c)) + p += 1 + end +end + +@native local function genSquare(w: buffer, at: number) + local p = at + for i = 1, 0x20 do + for _ = 1, (0x40 - i) * 2 do + buffer.writei8(w, p, -128) + p += 1 + end + for _ = 1, i * 2 do + buffer.writei8(w, p, 0x7f) + p += 1 + end + end +end + +-- hvl_GenWhiteNoise with `unsigned long` = 64 bits: (hi, lo) halves +@native local function genWhiteNoise(w: buffer, at: number, len: number) + local hi, lo = 0, 0x41595321 + for i = 0, len - 1 do + local s = i8(band(lo, 0xff)) + if band(lo, 0x100) ~= 0 then + s = 0x7f -- (int32)(ays & 0xffff) >= 0 always holds + end + buffer.writei8(w, at + i, s) + -- ays = (ays >> 5) | (ays << 27) + local nlo = bor(rshift(lo, 5), lshift(band(hi, 31), 27), lshift(lo, 27)) + -- (the high half is masked off next: ays & 0xffffff00 zero-extends) + lo = bor(band(nlo, 0xffffff00), bxor(band(nlo, 0xff), 0x9a)) + local bx = band(lo, 0xffff) + -- ays = (ays << 2) | (ays >> 30) + lo = bor(lshift(lo, 2), rshift(lo, 30)) + local ax = band(lo, 0xffff) + bx = band(bx + ax, 0xffff) + ax = bxor(ax, bx) + lo = bor(band(lo, 0xffff0000), ax) + -- ays = (ays >> 3) | (ays << 29) + hi = rshift(lo, 3) + lo = bor(rshift(lo, 3), lshift(lo, 29)) + end +end + +local LENTAB = { 3, 7, 0xf, 0x1f, 0x3f, 0x7f, 3, 7, 0xf, 0x1f, 0x3f, 0x7f } +for _ = 1, 32 do + table.insert(LENTAB, 0x7f) +end +table.insert(LENTAB, 0x280 * 3 - 1) + +@native local function clip(x: number): number + if x > 127 then + return 127 + elseif x < -128 then + return -128 + end + return x +end + +@native local function trunc8(x: number): number + return if x >= 0 then math.floor(x) else -math.floor(-x) +end + +@native local function genFilterWaves(w: buffer) + local low, high = WO_LOWPASSES, WO_HIGHPASSES + local freq = 8 + for _ = 0, 30 do + local a0 = WO_TRIANGLE_04 + local fre = freq * 1.25 / 100.0 + for wv = 1, 45 do + local n = LENTAB[wv] + local mid, lo = 0, 0 + for i = 0, n do + local h = clip(buffer.readi8(w, a0 + i) - mid - lo) + mid = clip(mid + h * fre) + lo = clip(lo + mid * fre) + end + for i = 0, n do + local h = clip(buffer.readi8(w, a0 + i) - mid - lo) + mid = clip(mid + h * fre) + lo = clip(lo + mid * fre) + buffer.writei8(w, low, trunc8(lo)) + buffer.writei8(w, high, trunc8(h)) + low += 1 + high += 1 + end + a0 += n + 1 + end + freq += 3 + end +end + +local cache: { waves: buffer, panL: { number }, panR: { number } }? = nil + +@native function Tables.get(): { waves: buffer, panL: { number }, panR: { number } } + if cache then + return cache + end + local w = buffer.create(WAVES_SIZE) + local n = 4 + for k = 0, 5 do + genSawtooth(w, WO_SAWTOOTH_04 + Tables.OFFSETS[k], n) + genTriangle(w, WO_TRIANGLE_04 + Tables.OFFSETS[k], n) + n *= 2 + end + genSquare(w, WO_SQUARES) + genWhiteNoise(w, WO_WHITENOISE, WHITENOISELEN) + genFilterWaves(w) + -- sine panning: the start angle is a float expression in the C source ((3.14159265f * 2.0f) / 4.0f) + local f = buffer.create(4) + buffer.writef32(f, 0, 3.14159265) + local aa = buffer.readf32(f, 0) * 2 / 4 + local ab = 0.0 + local step = (3.14159265 * 2.0 / 4.0) / 256.0 + local pl: { number }, pr: { number } = {}, {} + for i = 0, 255 do + pl[i] = math.floor(math.sin(aa) * 255.0) + pr[i] = math.floor(math.sin(ab) * 255.0) + aa += step + ab += step + end + pl[255] = 0 + pr[0] = 0 + cache = { waves = w, panL = pl, panR = pr } + return cache :: any +end + +return Tables +end +end + + + + + + SoundFont + --!optimize 2 +--!nocheck +-- rosetta chunk SoundFont (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 4 modules (1 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["codecs/audio/SoundFont"] = function() + +-- codecs/audio/SoundFont: SoundFont 2 banks and the sample synth that plays MIDI through them. +-- The synth is a port of TinySoundFont (tsf.h v0.9, MIT, (c) 2017-2025 Bernhard Schelling; licenses/TinySoundFont-LICENSE.txt). +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Parse = __include("codecs/audio/SoundFont/Parse") +local Synth = __include("codecs/audio/SoundFont/Synth") +local Fallback = __include("codecs/audio/SoundFont/Fallback") + +local SoundFont = {} + +type SoundFont = Parse.SoundFont +type State = Synth.State + +SoundFont.Synth = Synth +SoundFont.defaultRegion = Parse.defaultRegion + +function SoundFont.sniff(r: Bytes.Reader): boolean + return r:peek(4) == "RIFF" and r:peek(4, 8) == "sfbk" +end + +function SoundFont.parse(src: any, opts: Parse.Options?): (SoundFont?, Err.Err?) + local r: Bytes.Reader + if type(src) == "string" then + r = Bytes.reader(buffer.fromstring(src)) + elseif type(src) == "buffer" then + r = Bytes.reader(src) + elseif type(src) == "table" and type(src.buf) == "buffer" then + r = Bytes.reader(src.buf, src.pos, src.limit - src.pos) + else + return nil, Err.new(Err.ARG, "soundfont: expected a buffer, string or Reader") + end + local ok, sf, err = pcall(Parse.parse, r, opts) + if not ok then + return nil, Err.new(Err.CORRUPT, "soundfont parser failed: " .. tostring(sf)) + end + return sf, err +end + +function SoundFont.fallback(): SoundFont + return Fallback.build() +end + +function SoundFont.isSoundFont(v: any): boolean + return type(v) == "table" and v.kind == "soundfont" and type(v.samples) == "buffer" and type(v.presets) == "table" +end + +function SoundFont.synth(sf: SoundFont?, sampleRate: number?, opts: { gain: number?, maxVoices: number? }?): State + return Synth.new(sf or Fallback.build(), sampleRate or 44100, opts and opts.gain, opts and opts.maxVoices) +end + +return SoundFont +end +__FILES["codecs/audio/SoundFont/Fallback"] = function() + +-- codecs/audio/SoundFont/Fallback: the built-in General MIDI set (generated waveforms per GM family, drum kit on bank 128). +-- No third-party code. +local Parse = __include("codecs/audio/SoundFont/Parse") + +local Fallback = {} + +local CYCLE = 256 +local NOISE = 32768 +local C4 = 261.6255653005986 + +local function hzToCents(hz: number): number + return 1200 * math.log(hz / 8.176, 2) +end + +local cached: any = nil + +function Fallback.build(): any + if cached then + return cached + end + local waves = { "sine", "triangle", "square", "saw" } + local count = #waves * CYCLE + NOISE + local samples = buffer.create((count + 1) * 4) + local starts: { [string]: number } = {} + for w, name in waves do + local base = (w - 1) * CYCLE + starts[name] = base + for i = 0, CYCLE - 1 do + local ph = i / CYCLE + local v + if name == "sine" then + v = math.sin(2 * math.pi * ph) + elseif name == "triangle" then + v = if ph < 0.25 then 4 * ph elseif ph < 0.75 then 2 - 4 * ph else 4 * ph - 4 + elseif name == "square" then + v = if ph < 0.5 then 0.6 else -0.6 + else + v = (1 - 2 * ph) * 0.7 + end + buffer.writef32(samples, (base + i) * 4, v) + end + end + local noiseStart = #waves * CYCLE + starts.noise = noiseStart + local seed = 12345 + for i = 0, NOISE - 1 do + seed = (seed * 1103515245 + 12345) % 2147483648 + buffer.writef32(samples, (noiseStart + i) * 4, (seed / 1073741824 - 1) * 0.7) + end + + local function region(wave: string, fields: { [string]: number }): { [string]: number } + local r = Parse.defaultRegion() + local s = starts[wave] + r.offset = s + r.loopMode = 1 + r.loopStart = s + if wave == "noise" then + r.stop, r.loopEnd, r.sampleRate, r.keycenter = s + NOISE, s + NOISE - 1, 44100, 60 + else + r.stop, r.loopEnd, r.sampleRate, r.keycenter = s + CYCLE, s + CYCLE - 1, CYCLE * C4, 60 + end + r.aRelease = 0.08 + for k, v in fields do + r[k] = v + end + return r + end + + local families: { { any } } = { + { "piano", "triangle", { aDecay = 2.5, aSustain = 0, aRelease = 0.25 } }, + { "chromatic", "sine", { aDecay = 1.2, aSustain = 0, aRelease = 0.3 } }, + { "organ", "square", { aAttack = 0.005, aRelease = 0.05, filterFc = hzToCents(5000) } }, + { "guitar", "saw", { aDecay = 1.5, aSustain = 0, aRelease = 0.15, filterFc = hzToCents(3000) } }, + { "bass", "triangle", { aDecay = 1.5, aSustain = 0.4, aRelease = 0.1 } }, + { "strings", "saw", { aAttack = 0.08, aRelease = 0.3, filterFc = hzToCents(4000), freqVibLFO = hzToCents(5.5), vibLfoToPitch = 8, delayVibLFO = 0.2 } }, + { "ensemble", "saw", { aAttack = 0.12, aRelease = 0.4, filterFc = hzToCents(3500), freqVibLFO = hzToCents(5), vibLfoToPitch = 10 } }, + { "brass", "saw", { aAttack = 0.03, aRelease = 0.12, filterFc = hzToCents(1200), mAttack = 0.05, mDecay = 0.3, mSustain = 0.4, modEnvToFilterFc = 2400 } }, + { "reed", "square", { aAttack = 0.02, aRelease = 0.08, filterFc = hzToCents(2500) } }, + { "pipe", "sine", { aAttack = 0.04, aRelease = 0.12, freqVibLFO = hzToCents(5), vibLfoToPitch = 12, delayVibLFO = 0.3 } }, + { "lead", "square", { aAttack = 0.005, aRelease = 0.1, filterFc = hzToCents(6000) } }, + { "pad", "saw", { aAttack = 0.4, aRelease = 0.8, filterFc = hzToCents(1800), freqModLFO = hzToCents(0.5), modLfoToFilterFc = 600 } }, + { "synthfx", "triangle", { aAttack = 0.2, aRelease = 1.0, freqModLFO = hzToCents(3), modLfoToVolume = 60 } }, + { "ethnic", "saw", { aDecay = 1.0, aSustain = 0, aRelease = 0.2, filterFc = hzToCents(3000) } }, + { "percussive", "sine", { aDecay = 0.4, aSustain = 0, aRelease = 0.1, mDecay = 0.1, mSustain = 0, modEnvToPitch = 1200 } }, + { "sfx", "noise", { aAttack = 0.05, aRelease = 0.5, filterFc = hzToCents(3000) } }, + } + local presets = {} + for program = 0, 127 do + local f = families[program // 8 + 1] + table.insert(presets, { name = "fallback " .. f[1], preset = program, bank = 0, regions = { region(f[2], f[3]) } }) + end + + local kit = {} + local function drum(lo: number, hi: number, wave: string, fields: { [string]: number }) + local r = region(wave, fields) + r.lokey, r.hikey = lo, hi + r.sampleRate *= 2 ^ ((fields.semis or 0) / 12) + r.semis = nil :: any + table.insert(kit, r) + end + local sweep = { mDecay = 0.06, mSustain = 0, modEnvToPitch = 2400 } + local function with(a: { [string]: number }, b: { [string]: number }): { [string]: number } + local c = table.clone(a) + for k, v in b do + c[k] = v + end + return c + end + drum(0, 34, "noise", { aDecay = 0.1, aSustain = 0, keytrack = 0, filterFc = hzToCents(4000) }) + drum(35, 36, "sine", with(sweep, { aDecay = 0.35, aSustain = 0, aRelease = 0.05, keytrack = 0, semis = -26 })) + drum(37, 37, "noise", { aDecay = 0.05, aSustain = 0, keytrack = 0, filterFc = hzToCents(5000) }) + drum(38, 38, "noise", { aDecay = 0.2, aSustain = 0, keytrack = 0, filterFc = hzToCents(6000) }) + drum(39, 39, "noise", { aDecay = 0.15, aSustain = 0, keytrack = 0, filterFc = hzToCents(8000) }) + drum(40, 40, "noise", { aDecay = 0.18, aSustain = 0, keytrack = 0, filterFc = hzToCents(7000) }) + for _, k in { 41, 43, 45, 47, 48, 50 } do + drum(k, k, "sine", with(sweep, { aDecay = 0.4, aSustain = 0, semis = (k - 41) - 12, keytrack = 0 })) + end + drum(42, 42, "noise", { aDecay = 0.05, aSustain = 0, group = 1, keytrack = 0, semis = 12 }) + drum(44, 44, "noise", { aDecay = 0.08, aSustain = 0, group = 1, keytrack = 0, semis = 12 }) + drum(46, 46, "noise", { aDecay = 0.45, aSustain = 0, group = 1, keytrack = 0, semis = 12 }) + drum(49, 49, "noise", { aDecay = 1.5, aSustain = 0, keytrack = 0, semis = 7 }) + drum(51, 51, "noise", { aDecay = 1.0, aSustain = 0, keytrack = 0, semis = 10, filterFc = hzToCents(9000) }) + drum(52, 59, "noise", { aDecay = 1.2, aSustain = 0, keytrack = 0, semis = 5 }) + drum(60, 127, "noise", { aDecay = 0.12, aSustain = 0, keytrack = 30, filterFc = hzToCents(5000) }) + table.insert(presets, { name = "fallback drums", preset = 0, bank = 128, regions = kit }) + + cached = { + kind = "soundfont", + info = { name = "rosetta fallback" }, + samples = samples, + sampleCount = count, + presets = presets, + sampleHeaders = {}, + instruments = {}, + meta = { source = { format = "fallback" } }, + } + return cached +end + +return Fallback +end +__FILES["codecs/audio/SoundFont/Parse"] = function() + +-- codecs/audio/SoundFont/Parse: SoundFont 2.0x (sfbk RIFF) reader, zones merged into regions as TinySoundFont does. +-- After tsf.h v0.9 (MIT, (c) Bernhard Schelling; licenses/TinySoundFont-LICENSE.txt) tsf_load_presets / +-- tsf_region_operator / tsf_region_envtosecs. Unlike tsf.h, initialAttenuation is cB * 0.04 dB (FluidSynth's +-- EMU-compatible scale; tsf uses 0.01). +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") + +local Parse = {} + +type Region = { [string]: number } + +type Preset = { name: string, preset: number, bank: number, regions: { Region } } + +type SoundFont = { + kind: "soundfont", + info: { [string]: string }, + samples: buffer, -- f32 mono, sampleCount + 1 floats (a zero pad sample past the end) + sampleCount: number, + presets: { Preset }, + sampleHeaders: { { [string]: any } }, + instruments: { { name: string, zones: number } }, + meta: { [string]: any }, +} + +local GEN_INSTRUMENT, GEN_SAMPLEID = 41, 53 + +-- generator op -> { field, mode, limit }. modes: f / i (value, merged by adding then clamping), a (sample address +-- add), a15 (coarse address add: * 32768), kr / vr (key / velocity range), loop, group, key (overriding root key) +local LIM12K5K = { 1, -12000, 5000 } +local LIM12K8K = { 1, -12000, 8000 } +local LIM1200 = { 1, -1200, 1200 } +local GEN: { [number]: { any } } = { + [0] = { "offset", "a" }, + [1] = { "stop", "a" }, + [2] = { "loopStart", "a" }, + [3] = { "loopEnd", "a" }, + [4] = { "offset", "a15" }, + [5] = { "modLfoToPitch", "i", { 1, -12000, 12000 } }, + [6] = { "vibLfoToPitch", "i", { 1, -12000, 12000 } }, + [7] = { "modEnvToPitch", "i", { 1, -12000, 12000 } }, + [8] = { "filterFc", "i", { 1, 1500, 13500 } }, + [9] = { "filterQ", "i", { 1, 0, 960 } }, + [10] = { "modLfoToFilterFc", "i", { 1, -12000, 12000 } }, + [11] = { "modEnvToFilterFc", "i", { 1, -12000, 12000 } }, + [12] = { "stop", "a15" }, + [13] = { "modLfoToVolume", "i", { 1, -960, 960 } }, + [17] = { "pan", "f", { 0.001, -0.5, 0.5 } }, + [21] = { "delayModLFO", "f", LIM12K5K }, + [22] = { "freqModLFO", "i", { 1, -16000, 4500 } }, + [23] = { "delayVibLFO", "f", LIM12K5K }, + [24] = { "freqVibLFO", "i", { 1, -16000, 4500 } }, + [25] = { "mDelay", "f", LIM12K5K }, + [26] = { "mAttack", "f", LIM12K8K }, + [27] = { "mHold", "f", LIM12K5K }, + [28] = { "mDecay", "f", LIM12K8K }, + [29] = { "mSustain", "f", { 1, 0, 1000 } }, + [30] = { "mRelease", "f", LIM12K8K }, + [31] = { "mKeyHold", "f", LIM1200 }, + [32] = { "mKeyDecay", "f", LIM1200 }, + [33] = { "aDelay", "f", LIM12K5K }, + [34] = { "aAttack", "f", LIM12K8K }, + [35] = { "aHold", "f", LIM12K5K }, + [36] = { "aDecay", "f", LIM12K8K }, + [37] = { "aSustain", "f", { 1, 0, 1440 } }, + [38] = { "aRelease", "f", LIM12K8K }, + [39] = { "aKeyHold", "f", LIM1200 }, + [40] = { "aKeyDecay", "f", LIM1200 }, + [43] = { "", "kr" }, + [44] = { "", "vr" }, + [45] = { "loopStart", "a15" }, + [48] = { "attenuation", "f", { 0.04, 0, 57.6 } }, + [50] = { "loopEnd", "a15" }, + [51] = { "transpose", "i" }, + [52] = { "tune", "i" }, + [54] = { "loopMode", "loop" }, + [56] = { "keytrack", "i" }, + [57] = { "group", "group" }, + [58] = { "keycenter", "key" }, +} +local MERGE: { { any } } = {} +do + local seen: { [string]: boolean } = {} + for op = 0, 58 do + local g = GEN[op] + if g and (g[2] == "f" or g[2] == "i" or g[2] == "a") and not seen[g[1]] then + seen[g[1]] = true + table.insert(MERGE, g) + end + end +end + +local FIELDS = { + "loopMode", "sampleRate", "lokey", "hikey", "lovel", "hivel", "group", "offset", "stop", "loopStart", "loopEnd", + "transpose", "tune", "keycenter", "keytrack", "attenuation", "pan", "filterQ", "filterFc", "modEnvToPitch", + "modEnvToFilterFc", "modLfoToFilterFc", "modLfoToVolume", "delayModLFO", "freqModLFO", "modLfoToPitch", + "delayVibLFO", "freqVibLFO", "vibLfoToPitch", "aDelay", "aAttack", "aHold", "aDecay", "aSustain", "aRelease", + "aKeyHold", "aKeyDecay", "mDelay", "mAttack", "mHold", "mDecay", "mSustain", "mRelease", "mKeyHold", "mKeyDecay", + "sampleIndex", +} + +-- tsf_region_clear (relative: a preset zone, all zero so values add to the instrument's) +local function clear(relative: boolean): Region + local r: Region = {} + for _, f in FIELDS do + r[f] = 0 + end + r.hikey, r.hivel, r.keycenter = 127, 127, 60 + if relative then + return r + end + r.keytrack = 100 + r.keycenter = -1 + for _, p in { "a", "m" } do + for _, s in { "Delay", "Attack", "Hold", "Decay", "Release" } do + r[p .. s] = -12000 + end + end + r.filterFc = 13500 + r.delayModLFO, r.delayVibLFO = -12000, -12000 + return r +end + +local function copy(r: Region): Region + local c: Region = {} + for k, v in r do + c[k] = v + end + return c +end + +function Parse.defaultRegion(): Region + local r = clear(false) + r.keycenter = 60 + for _, p in { "a", "m" } do + for _, s in { "Delay", "Attack", "Hold", "Decay", "Release" } do + r[p .. s] = 0 + end + end + r.aSustain, r.mSustain = 1, 1 + r.delayModLFO, r.delayVibLFO = 0, 0 + return r +end + +-- set one generator (tsf_region_operator with an amount); lo / hi = the two bytes, s = signed 16, w = unsigned 16 +local function operator(r: Region, op: number, lo: number, hi: number, s: number, w: number) + local g = GEN[op] + if not g then + return + end + local mode = g[2] + if mode == "f" or mode == "i" then + r[g[1]] = s + elseif mode == "a" then + r[g[1]] += s + elseif mode == "a15" then + r[g[1]] += s * 32768 + elseif mode == "kr" then + r.lokey, r.hikey = lo, hi + elseif mode == "vr" then + r.lovel, r.hivel = lo, hi + elseif mode == "loop" then + local m = w % 4 + r.loopMode = if m == 3 then 2 elseif m == 1 then 1 else 0 + elseif mode == "group" then + r.group = w + elseif mode == "key" then + r.keycenter = s + end +end + +-- merge(zone, preset): zone += preset, then clamp (tsf_region_operator without an amount) +local function merge(z: Region, p: Region) + for _, g in MERGE do + local f = g[1] + local v = z[f] + p[f] + local lim = g[3] + if lim then + v *= lim[1] + v = math.clamp(v, lim[2], lim[3]) + end + z[f] = v + end +end + +local function tc2s(tc: number): number + return 2 ^ (tc / 1200) +end + +-- envtosecs (tsf_region_envtosecs): timecents to seconds; hold / decay stay in timecents when they scale by key +local function envToSecs(r: Region, p: string, sustainIsGain: boolean) + for _, s in { "Delay", "Attack", "Release" } do + local v = r[p .. s] + r[p .. s] = if v < -11950 then 0 else tc2s(v) + end + if r[p .. "KeyHold"] == 0 then + local v = r[p .. "Hold"] + r[p .. "Hold"] = if v < -11950 then 0 else tc2s(v) + end + if r[p .. "KeyDecay"] == 0 then + local v = r[p .. "Decay"] + r[p .. "Decay"] = if v < -11950 then 0 else tc2s(v) + end + local sus = r[p .. "Sustain"] + if sus < 0 then + sus = 0 + elseif sustainIsGain then + sus = if -sus / 10 > -100 then 10 ^ (-sus / 10 * 0.05) else 0 + else + sus = 1 - sus / 1000 + end + r[p .. "Sustain"] = sus +end + +type Hydra = { [string]: { { number } } } + +-- record layouts: field byte widths (2 / 4 = little endian unsigned, -2 signed, 20 = name, 1 = byte, -1 = signed byte) +local LAYOUT: { [string]: { number } } = { + phdr = { 20, 2, 2, 2, 4, 4, 4 }, + pbag = { 2, 2 }, + pmod = { 2, 2, -2, 2, 2 }, + pgen = { 2, 2 }, + inst = { 20, 2 }, + ibag = { 2, 2 }, + imod = { 2, 2, -2, 2, 2 }, + igen = { 2, 2 }, + shdr = { 20, 4, 4, 4, 4, 4, 1, -1, 2, 2 }, +} +local RECSIZE: { [string]: number } = { phdr = 38, pbag = 4, pmod = 10, pgen = 4, inst = 22, ibag = 4, imod = 10, igen = 4, shdr = 46 } + +local INFO_NAMES = { + isng = "engine", INAM = "name", irom = "rom", ICRD = "date", IENG = "author", IPRD = "product", + ICOP = "copyright", ICMT = "comment", ISFT = "software", +} + +type Options = { maxRegions: number?, maxSamples: number? } + +function Parse.parse(r: Bytes.Reader, opts: Options?): (SoundFont?, Err.Err?) + local maxRegions = opts and opts.maxRegions or 1000000 + local maxSamples = opts and opts.maxSamples or 2 ^ 28 + if r:string(4) ~= "RIFF" then + return r:fail(Err.CORRUPT, "not a RIFF file") + end + local riffSize = r:u32le() + if r:string(4) ~= "sfbk" then + return r:fail(Err.CORRUPT, "not a SoundFont (no sfbk)") + end + if r.err then + return nil, r.err + end + local body = r:sub(12, math.max(0, riffSize - 4)) + local info: { [string]: string } = {} + local hydra: Hydra = {} + local smpl: Bytes.Reader? = nil + local sm24: Bytes.Reader? = nil + local version = "" + while body:remaining() >= 8 do + local id, size = body:string(4), body:u32le() + local chunk = body:slice(size) + if size % 2 == 1 and body:remaining() > 0 then + body:skip(1) + end + if id == "LIST" and chunk:remaining() >= 4 then + local kind = chunk:string(4) + while chunk:remaining() >= 8 do + local sid, ssize = chunk:string(4), chunk:u32le() + local sub = chunk:slice(ssize) + if ssize % 2 == 1 and chunk:remaining() > 0 then + chunk:skip(1) + end + if kind == "INFO" then + if sid == "ifil" and sub:remaining() >= 4 then + local major, minor = sub:u16le(), sub:u16le() + version = string.format("%d.%02d", major, minor) + elseif INFO_NAMES[sid] then + info[INFO_NAMES[sid]] = sub:fixed(sub:remaining()) + end + elseif kind == "sdta" then + if sid == "smpl" and not smpl then + smpl = sub + elseif sid == "sm24" then + sm24 = sub + end + elseif kind == "pdta" then + local layout = LAYOUT[sid] + if layout and not hydra[sid] then + local rs = RECSIZE[sid] + local n = sub:remaining() // rs + local recs = table.create(n) :: { { number } } + for i = 1, n do + local rec = {} + for _, w in layout do + if w == 20 then + table.insert(rec, 0) + sub:skip(20) + elseif w == 4 then + table.insert(rec, sub:u32le()) + elseif w == 2 then + table.insert(rec, sub:u16le()) + elseif w == -2 then + table.insert(rec, sub:i16le()) + elseif w == 1 then + table.insert(rec, sub:u8()) + else + table.insert(rec, sub:i8()) + end + end + recs[i] = rec + end + hydra[sid] = recs + if sid == "phdr" or sid == "inst" or sid == "shdr" then + local names = table.create(n) + for i = 0, n - 1 do + names[i + 1] = sub:sub(i * rs, 20):fixed(20) + end + hydra[sid .. "Names"] = names :: any + end + end + end + end + end + end + if not smpl then + return nil, Err.new(Err.CORRUPT, "no sample data (sdta smpl)") + end + for _, k in { "phdr", "pbag", "pgen", "inst", "ibag", "igen", "shdr" } do + if not hydra[k] or #hydra[k] == 0 then + return nil, Err.new(Err.CORRUPT, "incomplete hydra: no " .. k .. " records") + end + end + local sr = smpl :: Bytes.Reader + local count = sr:remaining() // 2 + if count > maxSamples then + return nil, Err.new(Err.LIMIT, string.format("%d samples is over the %d sample limit", count, maxSamples)) + end + local samples = buffer.create((count + 1) * 4) + do + local b, p = sr.buf, sr.pos + local readi16, writef32 = buffer.readi16, buffer.writef32 + local s24 = sm24 + if s24 and s24:remaining() >= count then + local q = s24.pos + local readu8 = buffer.readu8 + for i = 0, count - 1 do + writef32(samples, i * 4, (readi16(b, p + i * 2) * 256 + readu8(s24.buf, q + i)) / 8388607) + end + else + s24 = nil + for i = 0, count - 1 do + writef32(samples, i * 4, readi16(b, p + i * 2) / 32767) + end + end + sm24 = s24 + end + -- tsf_load_presets + local phdr, pbag, pgen = hydra.phdr, hydra.pbag, hydra.pgen + local inst, ibag, igen, shdr = hydra.inst, hydra.ibag, hydra.igen, hydra.shdr + local phdrNames, instNames, shdrNames = (hydra :: any).phdrNames, (hydra :: any).instNames, (hydra :: any).shdrNames + local nInst = #inst - 1 -- the last record of each list is the terminal one + local nShdr = #shdr - 1 + local function range(list: { { number } }, i: number, field: number, limit: number): (number, number) + local a = list[i][field] + 1 + local b = if list[i + 1] then list[i + 1][field] + 1 else a + return math.max(1, a), math.min(b, limit + 1) + end + local presets: { Preset } = {} + local regionTotal = 0 + for pi = 1, #phdr - 1 do + local ph = phdr[pi] + local preset: Preset = { name = phdrNames[pi], preset = ph[2], bank = ph[3], regions = {} } + local globalRegion = clear(true) + local b0, b1 = range(phdr, pi, 4, #pbag) + for bi = b0, b1 - 1 do + local presetRegion = copy(globalRegion) + local hadInstrument = false + local g0, g1 = range(pbag, bi, 1, #pgen) + for gi = g0, g1 - 1 do + local pg = pgen[gi] + local op, amount = pg[1], pg[2] + local lo, hi = amount % 256, amount // 256 + local s = if amount >= 32768 then amount - 65536 else amount + if op == GEN_INSTRUMENT then + hadInstrument = true + if amount < nInst then + local instRegion = clear(false) + local ib0, ib1 = range(inst, amount + 1, 2, #ibag) + for ibi = ib0, ib1 - 1 do + local zone = copy(instRegion) + local hadSample = false + local ig0, ig1 = range(ibag, ibi, 1, #igen) + for igi = ig0, ig1 - 1 do + local ig = igen[igi] + local iop, iamt = ig[1], ig[2] + if iop == GEN_SAMPLEID then + hadSample = true + if iamt >= nShdr then + break + end + local ok = not (zone.hikey < presetRegion.lokey or zone.lokey > presetRegion.hikey) + and not (zone.hivel < presetRegion.lovel or zone.lovel > presetRegion.hivel) + if ok then + local z = copy(zone) + z.lokey = math.max(z.lokey, presetRegion.lokey) + z.hikey = math.min(z.hikey, presetRegion.hikey) + z.lovel = math.max(z.lovel, presetRegion.lovel) + z.hivel = math.min(z.hivel, presetRegion.hivel) + merge(z, presetRegion) + envToSecs(z, "a", true) + envToSecs(z, "m", false) + z.delayModLFO = if z.delayModLFO < -11950 then 0 else tc2s(z.delayModLFO) + z.delayVibLFO = if z.delayVibLFO < -11950 then 0 else tc2s(z.delayVibLFO) + local sh = shdr[iamt + 1] + local sStart, sEnd, sLoopStart, sLoopEnd = sh[2], sh[3], sh[4], sh[5] + z.offset = math.clamp(z.offset + sStart, 0, count) + local stop = z.stop + sEnd + if stop > 0 and stop < count then + stop += 1 + else + stop = count + end + z.stop = math.clamp(stop, 0, count) + z.loopStart = math.clamp(z.loopStart + sLoopStart, 0, count) + local le = z.loopEnd + sLoopEnd + if sLoopEnd > 0 then + le -= 1 + end + z.loopEnd = math.clamp(le, 0, count) + if z.keycenter == -1 then + z.keycenter = sh[7] + end + z.tune += sh[8] + z.sampleRate = sh[6] + z.sampleIndex = iamt + regionTotal += 1 + if regionTotal > maxRegions then + return nil, Err.new(Err.LIMIT, "over " .. maxRegions .. " regions") + end + table.insert(preset.regions, z) + end + break -- sampleID ends a zone's generator list + else + local ilo, ihi = iamt % 256, iamt // 256 + operator(zone, iop, ilo, ihi, if iamt >= 32768 then iamt - 65536 else iamt, iamt) + end + end + if ibi == ib0 and not hadSample then + instRegion = zone -- the instrument's global zone + end + end + end + break -- instrument ends a preset zone's generator list + else + operator(presetRegion, op, lo, hi, s, amount) + end + end + if bi == b0 and not hadInstrument then + globalRegion = presetRegion -- the preset's global zone + end + end + table.insert(presets, preset) + end + -- sorted by bank, then preset, then file order (tsf's sortedIndex) + for i, p in presets do + (p :: any)._order = i + end + table.sort(presets, function(a: Preset, b: Preset): boolean + if a.bank ~= b.bank then + return a.bank < b.bank + end + if a.preset ~= b.preset then + return a.preset < b.preset + end + return (a :: any)._order < (b :: any)._order + end) + for _, p in presets do + (p :: any)._order = nil + end + local headers = table.create(nShdr) :: { { [string]: any } } + for i = 1, nShdr do + local sh = shdr[i] + headers[i] = { + name = shdrNames[i], + start = sh[2], + stop = sh[3], + loopStart = sh[4], + loopEnd = sh[5], + sampleRate = sh[6], + originalPitch = sh[7], + pitchCorrection = sh[8], + link = sh[9], + type = sh[10], + } + end + 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 + local sf: SoundFont = { + kind = "soundfont", + info = info, + samples = samples, + sampleCount = count, + presets = presets, + sampleHeaders = headers, + instruments = instruments, + meta = { source = { format = "sf2", version = version, sm24 = sm24 ~= nil } }, + } + return sf, nil +end + +return Parse +end +__FILES["codecs/audio/SoundFont/Synth"] = @native function() + + +-- 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). Unlike tsf.h, the envelope gain is ramped across each 64-sample block. +local Synth = {} + +local readf32, writef32, blen = buffer.readf32, buffer.writef32, buffer.len +local exp, log, sqrt, tan, floor = math.exp, math.log, math.sqrt, math.tan, math.floor + +local NONE, DELAY, ATTACK, HOLD, DECAY, SUSTAIN, RELEASE, DONE = 0, 1, 2, 3, 4, 5, 6, 7 +local BLOCK = 64 -- TSF_RENDER_EFFECTSAMPLEBLOCK: envelopes / LFOs / filter cutoff update per block +local FASTRELEASE = 0.01 +local PI = math.pi +local LOOP_NONE, LOOP_SUSTAIN = 0, 2 + +type Env = { + segment: number, + isExp: boolean, + isAmp: boolean, + vel: number, + level: number, + slope: number, + untilNext: number, + delay: number, + attack: number, + hold: number, + decay: number, + sustain: number, + release: number, +} +type Lfo = { untilStart: number, level: number, delta: number } +type Voice = { + preset: number, + key: number, + channel: number, + held: boolean, + region: { [string]: number }, + pitchIn: number, + pitchOut: number, + pos: number, + gainDB: number, + panL: number, + panR: number, + playIndex: number, + loopStart: number, + loopEnd: number, + amp: Env, + mod: Env, + lpActive: boolean, + qinv: number, + a0: number, + a1: number, + b1: number, + b2: number, + z1: number, + z2: number, + modlfo: Lfo, + viblfo: Lfo, +} +type Channel = { + preset: number, + bank: number, + pitchWheel: number, + midiPan: number, + midiVolume: number, + midiExpression: number, + midiRPN: number, + midiData: number, + sustain: boolean, + panOffset: number, + gainDB: number, + pitchRange: number, + tuning: number, +} +type State = { + presets: { { regions: { { [string]: number } }, preset: number, bank: number } }, + lookup: { [number]: number }, + samples: buffer, + rate: number, + gainDB: number, + voices: { Voice }, + maxVoices: number, + playIndex: number, + channels: { Channel }, +} + +@native local function tc2s(tc: number): number + return 2 ^ (tc / 1200) +end +@native local function cents2Hz(c: number): number + return 8.176 * 2 ^ (c / 1200) +end +@native local function db2gain(db: number): number + return if db > -100 then 10 ^ (db * 0.05) else 0 +end +@native local function gain2db(g: number): number + return if g <= 0.00001 then -100 else 20 * math.log10(g) +end + +@native local function releaseSamples(e: Env, rate: number): number + return floor((if e.release <= 0 then FASTRELEASE else e.release) * rate) +end + +@native local function nextSegment(e: Env, active: number, rate: number) + local seg = active + if seg == NONE then + e.untilNext = floor(e.delay * rate) + if e.untilNext > 0 then + e.segment, e.isExp, e.level, e.slope = DELAY, false, 0, 0 + return + end + seg = DELAY + end + if seg == DELAY then + e.untilNext = floor(e.attack * rate) + if e.untilNext > 0 then + if not e.isAmp then + -- the mod env attack scales with velocity (1 = full duration, 127 = 0.125 x) + e.untilNext = floor(e.attack * ((145 - e.vel) / 144) * rate) + end + e.segment, e.isExp, e.level = ATTACK, false, 0 + e.slope = if e.untilNext > 0 then 1 / e.untilNext else 1 + return + end + seg = ATTACK + end + if seg == ATTACK then + e.untilNext = floor(e.hold * rate) + if e.untilNext > 0 then + e.segment, e.isExp, e.level, e.slope = HOLD, false, 1, 0 + return + end + seg = HOLD + end + if seg == HOLD then + e.untilNext = floor(e.decay * rate) + if e.untilNext > 0 then + e.segment, e.level = DECAY, 1 + if e.isAmp then + local mystery = -9.226 / e.untilNext -- LinuxSampler's decay curve (as tsf.h) + e.slope = exp(mystery) + e.isExp = true + if e.sustain > 0 then + e.untilNext = floor(log(e.sustain) / mystery) + end + else + e.slope = -1 / e.untilNext + e.untilNext = floor(e.decay * (1 - e.sustain) * rate) + e.isExp = false + end + return + end + seg = DECAY + end + if seg == DECAY then + e.segment, e.level, e.slope, e.untilNext, e.isExp = SUSTAIN, e.sustain, 0, 0x7FFFFFFF, false + return + end + if seg == SUSTAIN then + e.segment = RELEASE + e.untilNext = math.max(1, releaseSamples(e, rate)) + if e.isAmp then + e.slope = exp(-9.226 / e.untilNext) + e.isExp = true + else + e.slope = -e.level / e.untilNext + e.isExp = false + end + return + end + e.segment, e.isExp, e.level, e.slope, e.untilNext = DONE, false, 0, 0, 0x7FFFFFF +end + +@native local function envSetup(e: Env, r: { [string]: number }, p: string, key: number, vel: number, isAmp: boolean, rate: number) + e.delay, e.attack, e.hold, e.decay = r[p .. "Delay"], r[p .. "Attack"], r[p .. "Hold"], r[p .. "Decay"] + e.sustain, e.release = r[p .. "Sustain"], r[p .. "Release"] + local kh, kd = r[p .. "KeyHold"], r[p .. "KeyDecay"] + if kh ~= 0 then + local h = e.hold + kh * (60 - key) + e.hold = if h < -10000 then 0 else tc2s(h) + end + if kd ~= 0 then + local d = e.decay + kd * (60 - key) + e.decay = if d < -10000 then 0 else tc2s(d) + end + e.vel, e.isAmp = vel, isAmp + nextSegment(e, NONE, rate) +end + +@native local function envProcess(e: Env, n: number, rate: number) + local slope = e.slope + if slope ~= 0 then + if e.isExp then + e.level *= slope ^ n + else + e.level += slope * n + end + end + e.untilNext -= n + if e.untilNext <= 0 then + nextSegment(e, e.segment, rate) + end +end + +@native local function newEnv(): Env + return { segment = DONE, isExp = false, isAmp = false, vel = 0, level = 0, slope = 0, untilNext = 0, delay = 0, attack = 0, hold = 0, decay = 0, sustain = 0, release = 0 } +end + +@native local function lowpassSetup(v: Voice, fc: number) + -- the biquad from earlevel.com (as tsf.h) + local k = tan(PI * fc) + local kk = k * k + local norm = 1 / (1 + k * v.qinv + kk) + v.a0 = kk * norm + v.a1 = 2 * v.a0 + v.b1 = 2 * (kk - 1) * norm + v.b2 = (1 - k * v.qinv + kk) * norm +end + +@native local function lfoSetup(l: Lfo, delay: number, freqCents: number, rate: number) + l.untilStart = floor(delay * rate) + l.delta = 4 * cents2Hz(freqCents) / rate + l.level = 0 +end + +@native local function lfoProcess(l: Lfo, n: number) + if l.untilStart > n then + l.untilStart -= n + return + end + l.level += l.delta * n + if l.level > 1 then + l.delta = -l.delta + l.level = 2 - l.level + elseif l.level < -1 then + l.delta = -l.delta + l.level = -2 - l.level + end +end + +@native local function calcPitch(v: Voice, shift: number, rate: number) + local r = v.region + local note = v.key + r.transpose + r.tune / 100 + local adjusted = r.keycenter + (note - r.keycenter) * (r.keytrack / 100) + shift + v.pitchIn = adjusted * 100 + v.pitchOut = r.sampleRate / (tc2s(r.keycenter * 100) * rate) +end + +@native local function setPan(v: Voice, pan: number) + if pan <= -0.5 then + v.panL, v.panR = 1, 0 + elseif pan >= 0.5 then + v.panL, v.panR = 0, 1 + else + v.panL, v.panR = sqrt(0.5 - pan), sqrt(0.5 + pan) + end +end + +@native local function channelShift(c: Channel): number + return if c.pitchWheel == 8192 then c.tuning else (c.pitchWheel / 16383 * c.pitchRange * 2) - c.pitchRange + c.tuning +end + +@native local function voiceEnd(s: State, v: Voice) + nextSegment(v.amp, SUSTAIN, s.rate) + nextSegment(v.mod, SUSTAIN, s.rate) + if v.region.loopMode == LOOP_SUSTAIN then + v.loopEnd = v.loopStart + end +end + +@native local function voiceEndQuick(s: State, v: Voice) + v.amp.release = 0 + nextSegment(v.amp, SUSTAIN, s.rate) + v.mod.release = 0 + nextSegment(v.mod, SUSTAIN, s.rate) +end + +@native local function newVoice(): Voice + return { + preset = -1, key = 0, channel = 0, held = false, region = {}, pitchIn = 0, pitchOut = 0, pos = 0, gainDB = 0, + panL = 0, panR = 0, playIndex = 0, loopStart = 0, loopEnd = 0, amp = newEnv(), mod = newEnv(), + lpActive = false, qinv = 0, a0 = 0, a1 = 0, b1 = 0, b2 = 0, z1 = 0, z2 = 0, + modlfo = { untilStart = 0, level = 0, delta = 0 }, viblfo = { untilStart = 0, level = 0, delta = 0 }, + } +end + +@native local function newChannel(): Channel + return { + preset = 1, bank = 0, pitchWheel = 8192, midiPan = 8192, midiVolume = 16383, midiExpression = 16383, + midiRPN = 0xFFFF, midiData = 0, sustain = false, panOffset = 0, gainDB = 0, pitchRange = 2, tuning = 0, + } +end + +@native function Synth.new(sf: any, rate: number, gain: number?, maxVoices: number?): State + local lookup: { [number]: number } = {} + for i, p in sf.presets do + local k = p.bank * 128 + p.preset + if lookup[k] == nil then + lookup[k] = i + end + end + local s: State = { + presets = sf.presets, + lookup = lookup, + samples = sf.samples, + rate = rate, + gainDB = gain2db(gain or 0.5), + voices = {}, + maxVoices = maxVoices or 256, + playIndex = 0, + channels = {}, + } + for ch = 1, 16 do + s.channels[ch] = newChannel() + end + for ch = 0, 15 do + Synth.program(s, ch, 0) + end + return s +end + +@native local function presetIndex(s: State, bank: number, preset: number): number + return s.lookup[bank * 128 + preset] or -1 +end + +@native function Synth.noteOn(s: State, ch: number, key: number, velocity: number) + local c = s.channels[ch + 1] + if not c then + return + end + if velocity <= 0 then + Synth.noteOff(s, ch, key) + return + end + local pi = c.preset + local preset = s.presets[pi] + if not preset then + return + end + local vel = math.min(velocity, 127) / 127 + local midiVel = floor(vel * 127) + local rate = s.rate + local voices = s.voices + local playIndex = s.playIndex + s.playIndex += 1 + for _, region in preset.regions do + if key < region.lokey or key > region.hikey or midiVel < region.lovel or midiVel > region.hivel then + continue + end + local voice: Voice? = nil + if region.group ~= 0 then + for _, v in voices do + if v.preset == pi and v.region.group == region.group then + voiceEndQuick(s, v) + elseif v.preset == -1 and not voice then + voice = v + end + end + else + for _, v in voices do + if v.preset == -1 then + voice = v + break + end + end + end + if not voice then + if #voices < s.maxVoices then + local v = newVoice() + table.insert(voices, v) + voice = v + else + local best = -1e18 + for _, v in voices do + if v.amp.segment == RELEASE then + local done = releaseSamples(v.amp, rate) - v.amp.untilNext + if done > best then + best, voice = done, v + end + end + end + if not voice then + continue + end + end + end + local v = voice :: Voice + v.region = region + v.preset = pi + v.key = key + v.channel = ch + v.playIndex = playIndex + v.held = false + v.gainDB = s.gainDB - region.attenuation - gain2db(1 / vel) + c.gainDB + calcPitch(v, channelShift(c), rate) + setPan(v, region.pan + c.panOffset) + v.pos = region.offset + local doLoop = region.loopMode ~= LOOP_NONE and region.loopStart < region.loopEnd + v.loopStart = if doLoop then region.loopStart else 0 + v.loopEnd = if doLoop then region.loopEnd else 0 + envSetup(v.amp, region, "a", key, midiVel, true, rate) + envSetup(v.mod, region, "m", key, midiVel, false, rate) + local fc = if region.filterFc <= 13500 then cents2Hz(region.filterFc) / rate else 1 + v.qinv = 1 / 10 ^ ((region.filterQ / 10) / 20) + v.z1, v.z2 = 0, 0 + v.lpActive = fc < 0.499 + if v.lpActive then + lowpassSetup(v, fc) + end + lfoSetup(v.modlfo, region.delayModLFO, region.freqModLFO, rate) + lfoSetup(v.viblfo, region.delayVibLFO, region.freqVibLFO, rate) + end +end + +@native function Synth.noteOff(s: State, ch: number, key: number) + local c = s.channels[ch + 1] + if not c then + return + end + local first = -1 + for _, v in s.voices do + if v.preset ~= -1 and v.channel == ch and v.key == key and v.amp.segment < RELEASE and not v.held then + if first == -1 or v.playIndex < first then + first = v.playIndex + end + end + end + if first == -1 then + return + end + for _, v in s.voices do + if v.preset ~= -1 and v.channel == ch and v.key == key and v.amp.segment < RELEASE and not v.held and v.playIndex == first then + if c.sustain then + v.held = true + else + voiceEnd(s, v) + end + end + end +end + +@native local function applyPitch(s: State, ch: number, c: Channel) + local shift = channelShift(c) + for _, v in s.voices do + if v.preset ~= -1 and v.channel == ch then + calcPitch(v, shift, s.rate) + end + end +end + +@native local function setVolume(s: State, ch: number, c: Channel, volume: number) + local db = gain2db(volume) + if db == c.gainDB then + return + end + local change = db - c.gainDB + for _, v in s.voices do + if v.preset ~= -1 and v.channel == ch then + v.gainDB += change + end + end + c.gainDB = db +end + +@native local function setChannelPan(s: State, ch: number, c: Channel, pan: number) + for _, v in s.voices do + if v.preset ~= -1 and v.channel == ch then + setPan(v, v.region.pan + pan - 0.5) + end + end + c.panOffset = pan - 0.5 +end + +@native local function setTuning(s: State, ch: number, c: Channel, tuning: number) + if c.tuning ~= tuning then + c.tuning = tuning + applyPitch(s, ch, c) + end +end + +@native local function setPitchRange(s: State, ch: number, c: Channel, range: number) + if c.pitchRange ~= range then + c.pitchRange = range + if c.pitchWheel ~= 8192 then + applyPitch(s, ch, c) + end + end +end + +@native local function setSustain(s: State, ch: number, c: Channel, on: boolean) + if c.sustain == on then + return + end + c.sustain = on + if on then + return + end + for _, v in s.voices do + if v.preset ~= -1 and v.channel == ch and v.amp.segment < RELEASE and v.held then + voiceEnd(s, v) + end + end +end + +-- channel 9: drums (bank 128) +@native function Synth.program(s: State, ch: number, program: number) + local c = s.channels[ch + 1] + if not c then + return + end + local bank = c.bank % 32768 + local idx + if ch == 9 then + idx = presetIndex(s, 128 + bank, program) + if idx == -1 then + idx = presetIndex(s, 128, program) + end + if idx == -1 then + idx = presetIndex(s, 128, 0) + end + if idx == -1 then + idx = presetIndex(s, bank, program) + end + else + idx = presetIndex(s, bank, program) + end + if idx == -1 then + idx = presetIndex(s, 0, program) + end + if idx ~= -1 then + c.preset = idx + end +end + +@native function Synth.pitchBend(s: State, ch: number, value: number) + local c = s.channels[ch + 1] + if not c or c.pitchWheel == value then + return + end + c.pitchWheel = value + applyPitch(s, ch, c) +end + +@native function Synth.control(s: State, ch: number, cc: number, value: number) + local c = s.channels[ch + 1] + if not c then + return + end + local volume, pan, data = false, false, false + if cc == 7 then + c.midiVolume = c.midiVolume % 128 + value * 128 + volume = true + elseif cc == 39 then + c.midiVolume = c.midiVolume - c.midiVolume % 128 + value + volume = true + elseif cc == 11 then + c.midiExpression = c.midiExpression % 128 + value * 128 + volume = true + elseif cc == 43 then + c.midiExpression = c.midiExpression - c.midiExpression % 128 + value + volume = true + elseif cc == 10 then + c.midiPan = c.midiPan % 128 + value * 128 + pan = true + elseif cc == 42 then + c.midiPan = c.midiPan - c.midiPan % 128 + value + pan = true + elseif cc == 6 then + c.midiData = c.midiData % 128 + value * 128 + data = true + elseif cc == 38 then + c.midiData = c.midiData - c.midiData % 128 + value + data = true + elseif cc == 0 then + c.bank = 0x8000 + value -- bank select MSB alone acts like LSB (as tsf.h) + elseif cc == 32 then + c.bank = (if c.bank >= 0x8000 then (c.bank % 128) * 128 else 0) + value + elseif cc == 101 then + local rpn = if c.midiRPN == 0xFFFF then 0 else c.midiRPN + c.midiRPN = rpn % 128 + value * 128 + elseif cc == 100 then + local rpn = if c.midiRPN == 0xFFFF then 0 else c.midiRPN + c.midiRPN = rpn - rpn % 128 + value + elseif cc == 98 or cc == 99 then + c.midiRPN = 0xFFFF + elseif cc == 64 then + setSustain(s, ch, c, value >= 64) + elseif cc == 120 then + for _, v in s.voices do + if v.preset ~= -1 and v.channel == ch and (v.amp.segment < RELEASE or v.amp.release ~= 0) then + voiceEndQuick(s, v) + end + end + elseif cc == 123 then + for _, v in s.voices do + if v.preset ~= -1 and v.channel == ch and v.amp.segment < RELEASE then + voiceEnd(s, v) + end + end + elseif cc == 121 then + c.midiVolume, c.midiExpression, c.midiPan, c.bank, c.midiRPN, c.midiData = 16383, 16383, 8192, 0, 0xFFFF, 0 + setVolume(s, ch, c, 1) + setChannelPan(s, ch, c, 0.5) + setPitchRange(s, ch, c, 2) + setTuning(s, ch, c, 0) + end + if volume then + -- the cube gives a decent MIDI volume curve (tsf.h) + setVolume(s, ch, c, ((c.midiVolume / 16383) * (c.midiExpression / 16383)) ^ 3) + elseif pan then + setChannelPan(s, ch, c, c.midiPan / 16383) + elseif data then + if c.midiRPN == 0 then + setPitchRange(s, ch, c, c.midiData // 128 + 0.01 * (c.midiData % 128)) + elseif c.midiRPN == 1 then + local t = c.tuning + setTuning(s, ch, c, (if t < 0 then math.ceil(t) else floor(t)) + (c.midiData - 8192) / 8192) + elseif c.midiRPN == 2 and cc == 6 then + local t = c.tuning + setTuning(s, ch, c, (value - 64) + (t - (if t < 0 then math.ceil(t) else floor(t)))) + end + end +end + +@native function Synth.midi(s: State, status: number, d1: number, d2: number) + local kind, ch = status // 16, status % 16 + if kind == 9 then + Synth.noteOn(s, ch, d1, d2) + elseif kind == 8 then + Synth.noteOff(s, ch, d1) + elseif kind == 11 then + Synth.control(s, ch, d1, d2) + elseif kind == 12 then + Synth.program(s, ch, d1) + elseif kind == 14 then + Synth.pitchBend(s, ch, d1 + d2 * 128) + end +end + +@native function Synth.reset(s: State) + for _, v in s.voices do + v.preset = -1 + end + for ch = 1, 16 do + s.channels[ch] = newChannel() + end + for ch = 0, 15 do + Synth.program(s, ch, 0) + end +end + +@native function Synth.active(s: State): number + local n = 0 + for _, v in s.voices do + if v.preset ~= -1 then + n += 1 + end + end + return n +end + +@native local function voiceRender(s: State, v: Voice, out: buffer, frame: number, numSamples: number) + local region = v.region + local input = s.samples + local rate = s.rate + local modEnvToPitch, modEnvToFilterFc = region.modEnvToPitch, region.modEnvToFilterFc + local modLfoToPitch, modLfoToFilterFc, modLfoToVolume = region.modLfoToPitch, region.modLfoToFilterFc, region.modLfoToVolume + local vibLfoToPitch = region.vibLfoToPitch + local updateModEnv = modEnvToPitch ~= 0 or modEnvToFilterFc ~= 0 + local updateModLfo = v.modlfo.delta ~= 0 and (modLfoToPitch ~= 0 or modLfoToFilterFc ~= 0 or modLfoToVolume ~= 0) + local updateVibLfo = v.viblfo.delta ~= 0 and vibLfoToPitch ~= 0 + local loopStart, loopEnd = v.loopStart, v.loopEnd + local isLooping = loopStart < loopEnd + local endD = region.stop + local loopEndD = loopEnd + 1 + local loopLen = loopEnd - loopStart + 1 + local pos = v.pos + local lpActive, a0, a1, b1, b2, z1, z2 = v.lpActive, v.a0, v.a1, v.b1, v.b2, v.z1, v.z2 + local dynamicLowpass = modLfoToFilterFc ~= 0 or modEnvToFilterFc ~= 0 + local dynamicPitch = modLfoToPitch ~= 0 or modEnvToPitch ~= 0 or vibLfoToPitch ~= 0 + local dynamicGain = modLfoToVolume ~= 0 + local filterFc = region.filterFc + local pitchRatio = if dynamicPitch then 0 else tc2s(v.pitchIn) * v.pitchOut + local noteGain = if dynamicGain then 0 else db2gain(v.gainDB) + local o = frame * 8 + while numSamples > 0 do + local block = if numSamples > BLOCK then BLOCK else numSamples + numSamples -= block + if dynamicLowpass then + local fres = filterFc + v.modlfo.level * modLfoToFilterFc + v.mod.level * modEnvToFilterFc + local fc = if fres <= 13500 then cents2Hz(fres) / rate else 1 + lpActive = fc < 0.499 + if lpActive then + lowpassSetup(v, fc) + a0, a1, b1, b2 = v.a0, v.a1, v.b1, v.b2 + end + end + if dynamicPitch then + pitchRatio = tc2s(v.pitchIn + (v.modlfo.level * modLfoToPitch + v.viblfo.level * vibLfoToPitch + v.mod.level * modEnvToPitch)) * v.pitchOut + end + if dynamicGain then + noteGain = db2gain(v.gainDB + v.modlfo.level * modLfoToVolume * 0.1) + end + local gainMono = noteGain * v.amp.level + envProcess(v.amp, block, rate) + if updateModEnv then + envProcess(v.mod, block, rate) + end + if updateModLfo then + lfoProcess(v.modlfo, block) + end + if updateVibLfo then + lfoProcess(v.viblfo, block) + end + -- ramp the gain across the block to the envelope's next level (tsf.h steps it per block: zipper noise) + local gainNext = noteGain * v.amp.level + local step = (gainNext - gainMono) / block + local panL, panR = v.panL, v.panR + local g = gainMono + local k = block + while k > 0 and pos < endD do + k -= 1 + local ip = floor(pos) + local np = if ip >= loopEnd and isLooping then loopStart else ip + 1 + local s0 = readf32(input, ip * 4) + local val = s0 + (readf32(input, np * 4) - s0) * (pos - ip) + if lpActive then + local y = val * a0 + z1 + z1 = val * a1 + z2 - b1 * y + z2 = val * a0 - b2 * y + val = y + end + val *= g + g += step + writef32(out, o, readf32(out, o) + val * panL) + writef32(out, o + 4, readf32(out, o + 4) + val * panR) + o += 8 + pos += pitchRatio + if pos >= loopEndD and isLooping then + pos -= loopLen + end + end + o += k * 8 + if not (pos < endD) or v.amp.segment == DONE then + v.preset = -1 + return + end + end + v.pos = pos + v.lpActive, v.z1, v.z2 = lpActive, z1, z2 +end + +@native function Synth.render(s: State, out: buffer, frame: number, n: number) + local room = blen(out) // 8 - frame + if frame < 0 or room <= 0 then + return + end + if n > room then + n = room + end + if n <= 0 then + return + end + -- the sample buffer must hold every region's range + the pad sample (checked once against hand-made SoundFonts) + local count = blen(s.samples) // 4 - 1 + for _, v in s.voices do + if v.preset ~= -1 then + local r = v.region + if r.stop > count or r.loopEnd > count or r.offset < 0 or r.loopStart < 0 or v.pos < 0 then + v.preset = -1 + else + voiceRender(s, v, out, frame, n) + end + end + end +end + +return Synth +end +end + + + + + + Draco + --!optimize 2 +--!nocheck +-- rosetta chunk Draco (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 7 modules (0 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["codecs/model/Draco"] = function() + +-- codecs/model/Draco: Google Draco geometry decompression (.drc; glTF KHR_draco_mesh_compression; Roblox mesh v6 / v7). +-- Port of Draco 1.5.7's decoder (Apache-2.0, licenses/draco-LICENSE.txt): bitstreams 1.0 - 2.2 meshes, 2.3 kd-tree +-- point clouds; values match draco_decoder bit for bit (f32 rounding at every dequantization step). +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Reader = __include("codecs/model/Draco/Reader") +local Connectivity = __include("codecs/model/Draco/Connectivity") +local Attributes = __include("codecs/model/Draco/Attributes") + +local Draco = {} + +local NAMES = { [0] = "POSITION", "NORMAL", "COLOR", "TEX_COORD", "GENERIC", "TANGENT", "MATERIAL", "JOINTS", "WEIGHTS" } +local TYPES = { "i8", "u8", "i16", "u16", "i32", "u32", "i64", "u64", "f32", "f64", "bool" } +Draco.ATTRIBUTE_NAMES = NAMES +Draco.DATA_TYPES = TYPES + +type Attribute = { + name: string, + typeId: number, + uniqueId: number, + components: number, + type: string, + normalized: boolean, + data: buffer, +} +type Metadata = { entries: { [string]: buffer }, children: { [string]: Metadata }, attributes: { [number]: Metadata }? } +type Geometry = { + kind: "mesh" | "points", + version: string, + method: string, + numPoints: number, + numFaces: number, + indices: buffer?, + attributes: { Attribute }, + metadata: Metadata?, +} +type Header = { major: number, minor: number, kind: "mesh" | "points", method: number, flags: number } + +function Draco.sniff(buf: buffer, off: number?): boolean + local o = off or 0 + return buffer.len(buf) >= o + 5 and buffer.readstring(buf, o, 5) == "DRACO" +end + +local function header(d: Reader.D): (Header?, string?) + if Reader.remaining(d) < 11 then + return nil, "truncated header" + end + if buffer.readstring(d.b, d.pos, 5) ~= "DRACO" then + return nil, "not Draco data" + end + d.pos += 5 + local major, minor, kind, method = Reader.u8(d), Reader.u8(d), Reader.u8(d), Reader.u8(d) + local flags = Reader.u16(d) + if kind > 1 then + return nil, "unsupported: geometry type " .. kind + end + return { major = major, minor = minor, kind = if kind == 0 then "points" else "mesh", method = method, flags = flags }, nil +end + +function Draco.info(src: buffer | string, off: number?, len: number?): (Header?, Err.Err?) + local buf, o, l, aerr = Bytes.span("draco", src, off, len) + if not buf then + return nil, aerr + end + local d = Reader.new(buf, o, o + l, 0) + local h, err = header(d) + if not h then + return nil, Err.from(err, 0) + end + return h, nil +end + +local function metadataElement(d: Reader.D, depth: number): Metadata? + if depth > 1000 then + return nil + end + local m: Metadata = { entries = {}, children = {} } + local n = Reader.varint(d) + if d.bad or n > Reader.remaining(d) then + return nil + end + for _ = 1, n do + local nameLen = Reader.u8(d) + if d.bad or Reader.remaining(d) < nameLen then + return nil + end + local name = buffer.readstring(d.b, d.pos, nameLen) + d.pos += nameLen + local size = Reader.varint(d) + if d.bad or size == 0 or size > Reader.remaining(d) then + return nil + end + local v = buffer.create(size) + buffer.copy(v, 0, d.b, d.pos, size) + d.pos += size + m.entries[name] = v + end + local subs = Reader.varint(d) + if d.bad or subs > Reader.remaining(d) then + return nil + end + for _ = 1, subs do + local nameLen = Reader.u8(d) + if d.bad or Reader.remaining(d) < nameLen then + return nil + end + local name = buffer.readstring(d.b, d.pos, nameLen) + d.pos += nameLen + local child = metadataElement(d, depth + 1) + if not child then + return nil + end + m.children[name] = child + end + return m +end + +local function metadata(d: Reader.D): Metadata? + local n = Reader.varint(d) + if d.bad or n > Reader.remaining(d) then + return nil + end + local atts: { [number]: Metadata } = {} + for _ = 1, n do + local id = Reader.varint(d) + local m = metadataElement(d, 0) + if not m then + return nil + end + atts[id] = m + end + local m = metadataElement(d, 0) + if not m then + return nil + end + m.attributes = atts + return m +end + +local WRITE: { [number]: (buffer, number, number) -> () } = { + [1] = buffer.writei8, + [2] = buffer.writeu8, + [3] = buffer.writei16, + [4] = buffer.writeu16, + [5] = buffer.writei32, + [6] = buffer.writeu32, + [9] = buffer.writef32, + [11] = buffer.writeu8, +} + +local function expand(a: Attributes.Attr, numPoints: number): (buffer?, string?) + local size = Attributes.DT_LENGTH[a.dataType] + local comps = a.comps + local stride = size * comps + local out = buffer.create(numPoints * stride) + local map = a.map + local n = a.numValues + if a.raw then + local raw = a.raw :: buffer + for p = 0, numPoints - 1 do + local e = if map then map[p + 1] else p + if e >= n then + return nil, "attribute value out of range" + end + buffer.copy(out, p * stride, raw, e * stride, stride) + end + return out, nil + end + local vals = a.values :: { number } + local w = WRITE[a.dataType] + if not w then + return nil, "unsupported: data type " .. a.dataType + end + for p = 0, numPoints - 1 do + local e = if map then map[p + 1] else p + if e >= n then + return nil, "attribute value out of range" + end + local o = p * stride + local k = e * comps + for c = 1, comps do + w(out, o, vals[k + c]) + o += size + end + end + return out, nil +end + +local function decode(buf: buffer, o: number, l: number, opts: any): (Geometry?, string?, string?) + local d = Reader.new(buf, o, o + l, 0) + local h, herr = header(d) + if not h then + return nil, herr, nil + end + local ver = h.major * 256 + h.minor + local maxVer = if h.kind == "points" then 0x0203 else 0x0202 + if h.major < 1 or ver > maxVer then + return nil, string.format("unsupported: bitstream version %d.%d", h.major, h.minor), nil + end + d.ver = ver + local maxPoints = (opts and opts.maxPoints) or 2 ^ 24 + local maxFaces = (opts and opts.maxFaces) or 2 ^ 24 + local meta: Metadata? = nil + if ver >= 0x0103 and bit32.band(h.flags, 0x8000) ~= 0 then + meta = metadata(d) + if not meta then + return nil, d.bad or "bad metadata", nil + end + end + local mesh: Connectivity.Mesh? = nil + local numPoints = 0 + local method + if h.kind == "mesh" then + if h.method == 0 then + method = "sequential" + local m, err = Connectivity.sequential(d) + if not m then + return nil, err, nil + end + mesh = m + elseif h.method == 1 then + method = "edgebreaker" + local kind = Reader.u8(d) + if d.bad then + return nil, d.bad, nil + end + if kind > 2 then + return nil, "unknown edgebreaker traversal " .. kind, nil + end + local m, err = Connectivity.edgebreaker(d, kind) + if not m then + return nil, err, nil + end + mesh = m + else + return nil, "unsupported: mesh encoding method " .. h.method, nil + end + local m = mesh :: Connectivity.Mesh + if m.numFaces > maxFaces then + return nil, "too many faces", "limit" + end + numPoints = m.numPoints + else + if h.method > 1 then + return nil, "unsupported: point cloud encoding method " .. h.method, nil + end + method = if h.method == 1 then "kdtree" else "sequential" + numPoints = Reader.i32(d) + if d.bad then + return nil, d.bad, nil + end + if numPoints < 0 then + return nil, "bad point count", nil + end + end + if numPoints > maxPoints then + return nil, "too many points", "limit" + end + local attrs, aerr = Attributes.decode(d, { numPoints = numPoints, mesh = mesh, edgebreaker = method == "edgebreaker", kdTree = method == "kdtree" }) + if not attrs then + return nil, aerr, nil + end + local g: Geometry = { + kind = h.kind, + version = h.major .. "." .. h.minor, + method = method, + numPoints = numPoints, + numFaces = 0, + indices = nil, + attributes = {}, + metadata = meta, + } + if mesh then + local nf = mesh.numFaces + local idx = buffer.create(nf * 12) + local faces = mesh.faces + for i = 1, nf * 3 do + local v = faces[i] + if v < 0 or v >= numPoints then + return nil, "face index out of range", nil + end + buffer.writeu32(idx, (i - 1) * 4, v) + end + g.numFaces = nf + g.indices = idx + end + for _, a in attrs do + local data, err = expand(a, numPoints) + if not data then + return nil, err, nil + end + table.insert(g.attributes, { + name = NAMES[a.type] or "GENERIC", + typeId = a.type, + uniqueId = a.uniqueId, + components = a.comps, + type = TYPES[a.dataType], + normalized = a.normalized, + data = data, + }) + end + return g, nil, nil +end + +function Draco.decode(src: buffer | string, off: number?, len: number?, opts: any?): (Geometry?, Err.Err?) + local buf, o, l, aerr = Bytes.span("draco", src, off, len) + if not buf then + return nil, aerr + end + local ok, g, msg, kind = pcall(decode, buf, o, l, opts) + if not ok then + return nil, Err.new(Err.CORRUPT, "draco: internal error: " .. tostring(g)) + end + if not g then + return nil, Err.from("draco: " .. tostring(msg), nil, kind or (if string.find(tostring(msg), "^unsupported") then "unsupported" elseif string.find(tostring(msg), "truncated") then "truncated" else nil)) + end + return g, nil +end + +function Draco.attribute(g: Geometry, uniqueId: number): Attribute? + for _, a in g.attributes do + if a.uniqueId == uniqueId then + return a + end + end + return nil +end + +return Draco +end +__FILES["codecs/model/Draco/Attributes"] = function() + +-- codecs/model/Draco/Attributes: Draco attribute decoders and sequential attribute decoding (bitstreams 1.0 - 2.2). +-- Port of Draco 1.5.7 compression/attributes/*, point_cloud_decoder.cc, attribute_quantization_transform.cc and +-- attribute_octahedron_transform.cc (Apache-2.0, licenses/draco-LICENSE.txt). +local Reader = __include("codecs/model/Draco/Reader") +local Connectivity = __include("codecs/model/Draco/Connectivity") +local Predict = __include("codecs/model/Draco/Predict") +local KdTree = __include("codecs/model/Draco/KdTree") + +local Attributes = {} + +type D = Reader.D + +-- data type ids (draco::DataType) -> byte length +local DT_LENGTH = { [1] = 1, [2] = 1, [3] = 2, [4] = 2, [5] = 4, [6] = 4, [7] = 8, [8] = 8, [9] = 4, [10] = 8, [11] = 1 } +Attributes.DT_LENGTH = DT_LENGTH + +type Attr = { + id: number, + type: number, -- GeometryAttribute::Type (0 POSITION, 1 NORMAL, 2 COLOR, 3 TEX_COORD, 4 GENERIC, 5.. transcoder types) + dataType: number, + comps: number, + normalized: boolean, + uniqueId: number, + seqType: number, -- 0 generic, 1 integer, 2 quantization, 3 normals + map: { number }?, + numValues: number, + portable: { number }?, + values: { number }?, + raw: buffer?, + quant: { min: { number }, range: number, bits: number }?, + octBits: number?, + scheme: Predict.Scheme?, +} + +type Decoder = { + attrs: { Attr }, + traversal: { ct: Connectivity.CT, enc: Connectivity.Enc, method: number }?, + md: Predict.MeshData?, + points: { number }?, +} + +type Geom = { numPoints: number, mesh: Connectivity.Mesh?, edgebreaker: boolean, kdTree: boolean } + +local function zigzag(v: number): number + if v % 2 == 1 then + return -(v // 2) - 1 + end + return v // 2 +end + +-- parent getter: portable integers from 2.0 on, the final values before (truncated unless the scheme uses floats) +local function parentGetter(ver: number, pos: Attr, floats: boolean): Predict.Parent? + local old = ver < 0x0200 + local vals = if old then pos.values else pos.portable + if not vals or pos.comps ~= 3 or (not old and pos.seqType == 3) then + return nil + end + local map = pos.map + local trunc = old and not floats + return function(point: number): (number, number, number) + local e = if map then (map[point + 1] or 0) else point + local o = e * 3 + local x, y, z = vals[o + 1] or 0, vals[o + 2] or 0, vals[o + 3] or 0 + if trunc then + x = if x < 0 then math.ceil(x) else math.floor(x) + y = if y < 0 then math.ceil(y) else math.floor(y) + z = if z < 0 then math.ceil(z) else math.floor(z) + end + return x, y, z + end +end + +local function decodeIntegerValues(d: D, a: Attr, points: { number }, scheme: Predict.Scheme?): (boolean, string?) + local comps = if a.seqType == 3 then 2 else a.comps + local n = #points + local numValues = n * comps + if n == 0 then + return false, "no values" + end + local compressed = Reader.u8(d) + if d.bad then + return false, d.bad + end + local vals: { number } + if compressed > 0 then + local s = Reader.symbols(d, numValues, comps) + if not s then + return false, d.bad or "bad values" + end + vals = s + else + local nb = Reader.u8(d) + if d.bad then + return false, d.bad + end + if nb < 1 or nb > 4 then + return false, "bad value byte count" + end + if Reader.remaining(d) < nb * numValues then + return false, "truncated values" + end + vals = table.create(numValues, 0) + local b, p = d.b, d.pos + if nb == 4 then + for i = 1, numValues do + vals[i] = buffer.readu32(b, p) + p += 4 + end + elseif nb == 1 then + for i = 1, numValues do + vals[i] = buffer.readu8(b, p) + p += 1 + end + elseif nb == 2 then + for i = 1, numValues do + vals[i] = buffer.readu16(b, p) + p += 2 + end + else + for i = 1, numValues do + vals[i] = buffer.readu16(b, p) + buffer.readu8(b, p + 2) * 65536 + p += 3 + end + end + d.pos = p + end + if not scheme or not scheme.tr.positive then + for i = 1, numValues do + vals[i] = zigzag(vals[i]) + end + else + local i32 = Predict.i32 + for i = 1, numValues do + vals[i] = i32(vals[i]) + end + end + if scheme then + if not Predict.decodeData(scheme, d) then + return false, d.bad or "bad prediction data" + end + local ok, err = Predict.compute(scheme, vals, n, comps, points) + if not ok then + return false, err + end + end + a.portable = vals + a.numValues = n + return true, nil +end + +local function decodeQuantInfo(d: D, a: Attr): boolean + local mins = table.create(a.comps, 0) + for c = 1, a.comps do + mins[c] = Reader.f32(d) + end + local range = Reader.f32(d) + local bits = Reader.u8(d) + if d.bad or bits < 1 or bits > 30 then + return false + end + a.quant = { min = mins, range = range, bits = bits } + return true +end + +-- StoreValues: integer -> the data type; quantized -> f32; octahedral -> unit vectors +local function storeValues(a: Attr): (boolean, string?) + local src = a.portable :: { number } + local n = a.numValues + local fround = Predict.fround + if a.seqType == 1 then + local dt = a.dataType + local out = table.create(n * a.comps, 0) + for i = 1, n * a.comps do + local v = src[i] + if dt == 1 then + v = (v + 128) % 256 - 128 + elseif dt == 2 or dt == 11 then + v %= 256 + elseif dt == 3 then + v = (v + 32768) % 65536 - 32768 + elseif dt == 4 then + v %= 65536 + elseif dt == 6 then + v %= 4294967296 + elseif dt ~= 5 then + return false, "unsupported: integer attribute of data type " .. dt + end + out[i] = v + end + a.values = out + elseif a.seqType == 2 then + local q = a.quant + if not q then + return false, "no quantization data" + end + local maxQ = 2 ^ q.bits - 1 + local delta = fround(q.range / fround(maxQ)) + local comps = a.comps + local mins = q.min + local out = table.create(n * comps, 0) + local k = 1 + for _ = 1, n do + for c = 1, comps do + out[k] = fround(fround(fround(src[k]) * delta) + mins[c]) + k += 1 + end + end + a.values = out + elseif a.seqType == 3 then + local o = Predict.octahedron(a.octBits or 0) + if not o then + return false, "bad normal quantization" + end + local out = table.create(n * 3, 0) + for i = 0, n - 1 do + local x, y, z = Predict.octToVector(o, src[i * 2 + 1], src[i * 2 + 2]) + out[i * 3 + 1], out[i * 3 + 2], out[i * 3 + 3] = x, y, z + end + a.values = out + end + return true, nil +end + +function Attributes.decode(d: D, g: Geom): ({ Attr }?, string?) + local ver = d.ver + local numDecoders = Reader.u8(d) + if d.bad then + return nil, d.bad + end + local mesh = g.mesh + local decoders: { Decoder } = {} + for i = 0, numDecoders - 1 do + local dec: Decoder = { attrs = {}, traversal = nil, md = nil, points = nil } + if g.edgebreaker and mesh then + local attDataId = Reader.i8(d) + local decoderType = Reader.u8(d) + if d.bad then + return nil, d.bad + end + local ad = nil + if attDataId >= 0 then + ad = mesh.attrData[attDataId + 1] + if not ad or ad.decoderId >= 0 then + return nil, "bad attribute data id" + end + ad.decoderId = i + else + if mesh.posDecoderId >= 0 then + return nil, "two position decoders" + end + mesh.posDecoderId = i + end + local method = 0 + if ver >= 0x0102 then + method = Reader.u8(d) + if d.bad or method >= 2 then + return nil, "bad traversal method" + end + end + local ct = mesh.ct :: Connectivity.CT + local enc + if decoderType == 0 then + if ad then + enc = ad.enc + ad.used = false + else + enc = mesh.posEnc :: Connectivity.Enc + end + dec.traversal = { ct = ct, enc = enc, method = method } + else + if method ~= 0 or not ad then + return nil, "bad corner attribute decoder" + end + local cad = ad :: Connectivity.AttrData + enc = cad.enc + dec.traversal = { ct = cad.ct :: Connectivity.CT, enc = enc, method = 0 } + end + local pct = if ad and ad.used then ad.ct :: Connectivity.CT else ct + dec.md = { ct = pct, e2c = enc.e2c, v2e = enc.v2e } + end + decoders[i + 1] = dec + end + local all: { Attr } = {} + for _, dec in decoders do + local n = Reader.count(d, 0x0200) + if d.bad then + return nil, d.bad + end + if n == 0 or n > 5 * Reader.remaining(d) then + return nil, "bad attribute count" + end + for _ = 1, n do + local attType, dataType, comps, normalized = Reader.u8(d), Reader.u8(d), Reader.u8(d), Reader.u8(d) + if d.bad then + return nil, d.bad + end + if attType >= 9 or dataType == 0 or dataType >= 12 or comps == 0 then + return nil, "bad attribute descriptor" + end + local uniqueId = if ver < 0x0103 then Reader.u16(d) else Reader.varint(d) + local a: Attr = { + id = #all, + type = attType, + dataType = dataType, + comps = comps, + normalized = normalized > 0, + uniqueId = uniqueId, + seqType = 0, + map = nil, + numValues = 0, + } + table.insert(all, a) + table.insert(dec.attrs, a) + end + for _, a in (if g.kdTree then {} else dec.attrs) do + local t = Reader.u8(d) + if d.bad then + return nil, d.bad + end + if t > 3 then + return nil, "unknown attribute decoder " .. t + end + if (t == 2 or t == 3) and a.dataType ~= 9 then + return nil, "quantized attribute is not f32" + end + if t == 3 and a.comps ~= 3 then + return nil, "normal attribute without 3 components" + end + a.seqType = t + end + end + if d.bad then + return nil, d.bad + end + local function named(t: number): Attr? + for _, a in all do + if a.type == t then + return a + end + end + return nil + end + for _, dec in decoders do + if g.kdTree then + local ok, err = KdTree.decode(d, dec.attrs, g.numPoints) + if not ok then + return nil, err + end + continue + end + local points: { number } + local trav = dec.traversal + if trav then + local faces = (mesh :: Connectivity.Mesh).faces + local p = Connectivity.traverse(trav.ct, faces, trav.enc, trav.method) + if not p then + return nil, "bad attribute traversal" + end + points = p + local numPoints = (mesh :: Connectivity.Mesh).numPoints + for _, a in dec.attrs do + local m = Connectivity.mapping(trav.ct, faces, trav.enc, numPoints) + if not m then + return nil, "bad attribute mapping" + end + a.map = m + end + else + points = table.create(g.numPoints, 0) + for i = 1, g.numPoints do + points[i] = i - 1 + end + end + dec.points = points + for _, a in dec.attrs do + if a.seqType == 0 then + local stride = DT_LENGTH[a.dataType] * a.comps + local size = #points * stride + if Reader.remaining(d) < size then + return nil, "truncated attribute values" + end + local raw = buffer.create(size) + buffer.copy(raw, 0, d.b, d.pos, size) + d.pos += size + a.raw = raw + a.numValues = #points + continue + end + local psm = Reader.i8(d) + if d.bad then + return nil, d.bad + end + if psm < -2 or psm >= 7 then + return nil, "bad prediction scheme" + end + local scheme: Predict.Scheme? = nil + if psm ~= -2 then + local ptt = Reader.i8(d) + if d.bad then + return nil, d.bad + end + if ptt < -1 or ptt >= 4 then + return nil, "bad prediction transform" + end + if a.seqType == 3 then + if ptt == 2 or ptt == 3 then + scheme = Predict.new(psm, Predict.transform(ptt), dec.md) + end + elseif ptt == 1 then + scheme = Predict.new(psm, Predict.transform(1), dec.md) + end + end + if scheme and Predict.needsParent(scheme) then + local pos = named(0) + local getter = pos and parentGetter(ver, pos, scheme.method == 3) + if not getter then + return nil, "prediction needs the decoded positions" + end + scheme.parent = getter + end + if ver < 0x0200 then + if a.seqType == 2 and not decodeQuantInfo(d, a) then + return nil, d.bad or "bad quantization data" + elseif a.seqType == 3 then + a.octBits = Reader.u8(d) + end + end + local ok, err = decodeIntegerValues(d, a, points, scheme) + if not ok then + return nil, err + end + a.scheme = scheme + if ver < 0x0200 then + local ok2, err2 = storeValues(a) + if not ok2 then + return nil, err2 + end + end + end + if ver >= 0x0200 then + for _, a in dec.attrs do + if a.seqType == 2 then + if not decodeQuantInfo(d, a) then + return nil, d.bad or "bad quantization data" + end + elseif a.seqType == 3 then + a.octBits = Reader.u8(d) + end + end + if d.bad then + return nil, d.bad + end + for _, a in dec.attrs do + if a.seqType ~= 0 then + local ok, err = storeValues(a) + if not ok then + return nil, err + end + end + end + end + end + return all, nil +end + +return Attributes +end +__FILES["codecs/model/Draco/Connectivity"] = function() + +-- codecs/model/Draco/Connectivity: Draco mesh connectivity (sequential and Edgebreaker) and traversal sequencers. +-- Port of Draco 1.5.7 mesh_sequential_decoder.cc, mesh_edgebreaker_decoder_impl.cc, mesh_edgebreaker_traversal_*, +-- corner_table, mesh_attribute_corner_table, traverser/* (Apache-2.0, licenses/draco-LICENSE.txt). +local Reader = __include("codecs/model/Draco/Reader") + +local Connectivity = {} + +type D = Reader.D + +type CT = { c2v: { number }, opp: { number }, lmc: { number }, nv: number, nf: number } +type Enc = { v2e: { number }, e2c: { number }, numValues: number } +type AttrData = { decoderId: number, used: boolean, seams: { number }, ct: CT?, enc: Enc } +type Mesh = { + faces: { number }, + numFaces: number, + numPoints: number, + ct: CT?, + attrData: { AttrData }, + posEnc: Enc?, + posDecoderId: number, +} + +local TOPOLOGY_C, TOPOLOGY_S, TOPOLOGY_L, TOPOLOGY_R, TOPOLOGY_E = 0, 1, 3, 5, 7 +local SYMBOL_TO_TOPOLOGY = { [0] = TOPOLOGY_C, TOPOLOGY_S, TOPOLOGY_L, TOPOLOGY_R, TOPOLOGY_E } + +local function nextC(c: number): number + if c < 0 then + return -1 + end + return if c % 3 == 2 then c - 2 else c + 1 +end +local function prevC(c: number): number + if c < 0 then + return -1 + end + return if c % 3 == 0 then c + 2 else c - 1 +end +Connectivity.next = nextC +Connectivity.prev = prevC + +local function newEnc(nv: number): Enc + return { v2e = table.create(nv, 0), e2c = {}, numValues = 0 } +end + +function Connectivity.sequential(d: D): (Mesh?, string?) + local numFaces, numPoints + if d.ver < 0x0202 then + numFaces, numPoints = Reader.u32(d), Reader.u32(d) + else + numFaces, numPoints = Reader.varint(d), Reader.varint(d) + end + if d.bad then + return nil, d.bad + end + if numFaces > 0xffffffff // 3 or numFaces > Reader.remaining(d) // 3 then + return nil, "too many faces" + end + local method = Reader.u8(d) + local n = numFaces * 3 + local faces = table.create(n, 0) + if method == 0 then + local sym = Reader.symbols(d, n, 1) + if not sym then + return nil, d.bad or "bad indices" + end + local last = 0 + for i = 1, n do + local e = sym[i] + local diff = e // 2 + if e % 2 == 1 then + if diff > last then + return nil, "bad index delta" + end + diff = -diff + elseif diff > 0x7fffffff - last then + return nil, "bad index delta" + end + last += diff + faces[i] = last + end + else + local b = d.b + if numPoints < 256 then + if d.pos + n > d.limit then + return nil, "truncated indices" + end + for i = 1, n do + faces[i] = buffer.readu8(b, d.pos + i - 1) + end + d.pos += n + elseif numPoints < 65536 then + if d.pos + n * 2 > d.limit then + return nil, "truncated indices" + end + for i = 1, n do + faces[i] = buffer.readu16(b, d.pos + (i - 1) * 2) + end + d.pos += n * 2 + elseif numPoints < 2 ^ 21 and d.ver >= 0x0202 then + for i = 1, n do + faces[i] = Reader.varint(d) + end + else + if d.pos + n * 4 > d.limit then + return nil, "truncated indices" + end + for i = 1, n do + faces[i] = buffer.readu32(b, d.pos + (i - 1) * 4) + end + d.pos += n * 4 + end + end + if d.bad then + return nil, d.bad + end + return { faces = faces, numFaces = numFaces, numPoints = numPoints, ct = nil, attrData = {}, posEnc = nil, posDecoderId = -1 }, nil +end + +type Trav = { + decodeSymbol: () -> number, + newActiveCorner: (corner: number) -> (), + mergeVertices: (dest: number, src: number) -> (), + startFace: () -> boolean, + seam: (i: number) -> boolean, +} + +-- MeshEdgebreakerTraversalDecoder::Start +local function standardStart(buf: D, numAttributeData: number, withSymbols: boolean): (any?, D) + local st: any = {} + if withSymbols then + local sym = Reader.copy(buf) + local size = Reader.startBits(sym, true) + if sym.bad then + buf.bad = sym.bad + return nil, buf + end + buf = Reader.copy(sym) + buf.bitMode = false + if size > Reader.remaining(buf) then + Reader.fail(buf, "traversal symbols past the end") + return nil, buf + end + buf.pos += size + st.sym = sym + end + if buf.ver < 0x0202 then + local sf = Reader.copy(buf) + local size = Reader.startBits(sf, true) + if sf.bad then + buf.bad = sf.bad + return nil, buf + end + buf = Reader.copy(sf) + buf.bitMode = false + if size > Reader.remaining(buf) then + Reader.fail(buf, "start faces past the end") + return nil, buf + end + buf.pos += size + st.startBuf = sf + else + local bd = Reader.bitDecoder(buf) + if not bd then + return nil, buf + end + st.startDec = bd + end + st.seams = {} + for i = 1, numAttributeData do + local bd = Reader.bitDecoder(buf) + if not bd then + return nil, buf + end + st.seams[i] = bd + end + return st, buf +end + +local function standardSymbol(sym: D): number + local s = Reader.bits(sym, 1) + if s == TOPOLOGY_C then + return s + end + return s + Reader.bits(sym, 2) * 2 +end + +-- traversal decoder kind: 0 standard, 1 predictive, 2 valence +local function makeTraversal(kind: number, buf: D, numAttributeData: number, numVertices: number, numFaces: number, ct: CT): (Trav?, D) + local ver = buf.ver + local st, out = standardStart(buf, numAttributeData, kind ~= 2 or ver < 0x0202) + if not st then + return nil, out + end + local function startFace(): boolean + if st.startBuf then + return Reader.bits(st.startBuf, 1) == 1 + end + return Reader.bit(st.startDec) + end + local function seam(i: number): boolean + return Reader.bit(st.seams[i + 1]) + end + local valences = table.create(numVertices, 0) + local c2v = ct.c2v + local function vtx(c: number): number + return if c < 0 then -1 else (c2v[c + 1] or -1) + end + local function addValence(v: number, k: number) + if v >= 0 and v < numVertices then + valences[v + 1] += k + end + end + local function mergeVertices(dest: number, src: number) + if dest >= 0 and dest < numVertices and src >= 0 and src < numVertices then + valences[dest + 1] += valences[src + 1] + end + end + local lastSymbol = -1 + local function updateValences(corner: number) + local nx, pv = nextC(corner), prevC(corner) + if lastSymbol == TOPOLOGY_C or lastSymbol == TOPOLOGY_S then + addValence(vtx(nx), 1) + addValence(vtx(pv), 1) + elseif lastSymbol == TOPOLOGY_R then + addValence(vtx(corner), 1) + addValence(vtx(nx), 1) + addValence(vtx(pv), 2) + elseif lastSymbol == TOPOLOGY_L then + addValence(vtx(corner), 1) + addValence(vtx(nx), 2) + addValence(vtx(pv), 1) + elseif lastSymbol == TOPOLOGY_E then + addValence(vtx(corner), 2) + addValence(vtx(nx), 2) + addValence(vtx(pv), 2) + end + end + + if kind == 0 then + local sym = st.sym + return { + decodeSymbol = function(): number + return standardSymbol(sym) + end, + newActiveCorner = function(_c: number) end, + mergeVertices = function(_a: number, _b: number) end, + startFace = startFace, + seam = seam, + }, out + elseif kind == 1 then + -- predictive (deprecated): a bit says whether the predicted symbol (from the pivot's valence) is right + local n = Reader.i32(out) + if out.bad or n < 0 or n >= numVertices then + Reader.fail(out, "bad split symbol count") + return nil, out + end + local pred = Reader.bitDecoder(out) + if not pred then + return nil, out + end + local sym = st.sym + local predicted = -1 + return { + decodeSymbol = function(): number + if predicted ~= -1 and Reader.bit(pred) then + lastSymbol = predicted + return predicted + end + lastSymbol = standardSymbol(sym) + return lastSymbol + end, + newActiveCorner = function(corner: number) + updateValences(corner) + if lastSymbol == TOPOLOGY_C or lastSymbol == TOPOLOGY_R then + local pivot = vtx(nextC(corner)) + local val = if pivot >= 0 and pivot < numVertices then valences[pivot + 1] else 0 + predicted = if val < 6 then TOPOLOGY_R else TOPOLOGY_C + else + predicted = -1 + end + end, + mergeVertices = mergeVertices, + startFace = startFace, + seam = seam, + }, out + end + -- valence: per-context symbol streams chosen by the valence of the next vertex + local minValence, maxValence = 2, 7 + if ver < 0x0202 then + local nSplit = Reader.count(out, 0x0200) + if out.bad or nSplit >= numVertices then + Reader.fail(out, "bad split symbol count") + return nil, out + end + local mode = Reader.i8(out) + if out.bad or mode ~= 0 then + Reader.fail(out, "unsupported valence mode") + return nil, out + end + end + local contexts: { { number } } = {} + local counters: { number } = {} + for i = 1, maxValence - minValence + 1 do + local n = Reader.varint(out) + if out.bad then + return nil, out + end + if n > numFaces then + Reader.fail(out, "too many context symbols") + return nil, out + end + counters[i] = n + contexts[i] = {} + if n > 0 then + -- C++ ignores a failure here (the symbols stay zero) + local save = out.bad + local syms = Reader.symbols(out, n, 1) + if syms then + contexts[i] = syms + else + out.bad = save + end + end + end + local active = -1 + local sym = st.sym + return { + decodeSymbol = function(): number + if active ~= -1 then + local k = counters[active + 1] - 1 + counters[active + 1] = k + if k < 0 then + return -1 + end + local id = contexts[active + 1][k + 1] or 0 + if id > 4 then + return -1 + end + lastSymbol = SYMBOL_TO_TOPOLOGY[id] + elseif ver < 0x0202 then + lastSymbol = standardSymbol(sym) + else + lastSymbol = TOPOLOGY_E + end + return lastSymbol + end, + newActiveCorner = function(corner: number) + updateValences(corner) + local v = vtx(nextC(corner)) + local val = if v >= 0 and v < numVertices then valences[v + 1] else 0 + if val < minValence then + val = minValence + elseif val > maxValence then + val = maxValence + end + active = val - minValence + end, + mergeVertices = mergeVertices, + startFace = startFace, + seam = seam, + }, out +end + +local function splitEvents(eb: D, numFaces: number): { any }? + local ver = eb.ver + local n = Reader.count(eb, 0x0200) + if eb.bad then + return nil + end + local splits = {} + if n > 0 then + if n > numFaces then + Reader.fail(eb, "too many topology splits") + return nil + end + if ver < 0x0102 then + for i = 1, n do + local split = Reader.u32(eb) + local source = Reader.u32(eb) + local edge = Reader.u8(eb) % 2 + splits[i] = { source = source, split = split, edge = edge } + end + else + local last = 0 + for i = 1, n do + local source = Reader.varint(eb) + last + local delta = Reader.varint(eb) + if eb.bad then + return nil + end + if delta > source then + Reader.fail(eb, "bad topology split") + return nil + end + splits[i] = { source = source, split = source - delta, edge = 0 } + last = source + end + Reader.startBits(eb, false) + for i = 1, n do + local e = Reader.bits(eb, if ver < 0x0202 then 2 else 1) + splits[i].edge = e % 2 + end + Reader.endBits(eb) + end + end + -- hole events (before 2.1): read and ignored + local holes = 0 + if ver < 0x0200 then + holes = Reader.u32(eb) + elseif ver < 0x0201 then + holes = Reader.varint(eb) + end + if eb.bad then + return nil + end + if holes > Reader.remaining(eb) then + Reader.fail(eb, "too many hole events") + return nil + end + for _ = 1, holes do + if ver < 0x0102 then + Reader.i32(eb) + else + Reader.varint(eb) + end + end + if eb.bad then + return nil + end + return splits +end + +-- MeshAttributeCornerTable from the seam corners (InitEmpty, AddSeamEdge, RecomputeVertices) +local function attributeTable(ct: CT, seams: { number }): CT? + local c2v, opp, lmc = ct.c2v, ct.opp, ct.lmc + local nc = ct.nf * 3 + local function V(c: number): number + return if c < 0 then -1 else (c2v[c + 1] or -1) + end + local edgeSeam: { [number]: boolean } = {} + local vertSeam: { [number]: boolean } = {} + for _, c in seams do + edgeSeam[c] = true + vertSeam[V(nextC(c))] = true + vertSeam[V(prevC(c))] = true + local o = if c < 0 then -1 else (opp[c + 1] or -1) + if o ~= -1 then + edgeSeam[o] = true + vertSeam[V(nextC(o))] = true + vertSeam[V(prevC(o))] = true + end + end + local aopp = table.create(nc, -1) + for c = 0, nc - 1 do + aopp[c + 1] = if edgeSeam[c] then -1 else (opp[c + 1] or -1) + end + local ac2v = table.create(nc, -1) + local almc: { number } = {} + local num = 0 + local function swingLeftA(c: number): number + local n = nextC(c) + local o = if n < 0 then -1 else aopp[n + 1] + return nextC(o) + end + local function swingRight(c: number): number + local p = prevC(c) + local o = if p < 0 then -1 else (opp[p + 1] or -1) + return prevC(o) + end + for v = 0, ct.nv - 1 do + local c = lmc[v + 1] or -1 + if c ~= -1 then + local id = num + num += 1 + local first = c + if vertSeam[v] then + local act = swingLeftA(first) + while act ~= -1 do + first = act + act = swingLeftA(act) + if act == c then + return nil + end + end + end + ac2v[first + 1] = id + table.insert(almc, first) + local act = swingRight(first) + local guard = 0 + while act ~= -1 and act ~= first do + if edgeSeam[nextC(act)] then + id = num + num += 1 + table.insert(almc, act) + end + ac2v[act + 1] = id + act = swingRight(act) + guard += 1 + if guard > nc then + return nil + end + end + end + end + return { c2v = ac2v, opp = aopp, lmc = almc, nv = num, nf = ct.nf, vertSeam = vertSeam } :: any +end + +-- MeshEdgebreakerDecoderImpl::DecodeConnectivity (+ the traversal start, seams, AssignPointsToCorners) +function Connectivity.edgebreaker(d: D, traversalKind: number): (Mesh?, string?) + local ver = d.ver + if ver < 0x0202 then + Reader.count(d, 0x0200) -- num_new_vertices (unused) + end + local numEncodedVertices = Reader.count(d, 0x0200) + local numFaces = Reader.count(d, 0x0200) + if d.bad then + return nil, d.bad + end + if numFaces > 0xffffffff // 3 then + return nil, "too many faces" + end + if numEncodedVertices > numFaces * 3 then + return nil, "more vertices than corners" + end + local minEdges = (3 * numFaces) // 2 + local maxEdges = numEncodedVertices * (numEncodedVertices - 1) / 2 + if numEncodedVertices == 0 then + maxEdges = 0 + end + if maxEdges < minEdges then + return nil, "too few vertices for the faces" + end + local numAttributeData = Reader.u8(d) + local numSymbols = Reader.count(d, 0x0200) + if d.bad then + return nil, d.bad + end + if numFaces < numSymbols or numFaces > numSymbols + numSymbols // 3 then + return nil, "bad symbol count" + end + local numSplitSymbols = Reader.count(d, 0x0200) + if d.bad then + return nil, d.bad + end + if numSplitSymbols > numSymbols then + return nil, "bad split symbol count" + end + local maxVertices = numEncodedVertices + numSplitSymbols + + local c2v: { number } = {} + local opp: { number } = {} + local lmc: { number } = {} + local nv = 0 + local ct: CT = { c2v = c2v, opp = opp, lmc = lmc, nv = 0, nf = numFaces } + local notHole: { [number]: boolean } = {} + + local splits: { any }? + local splitBytes = 0 + if ver < 0x0202 then + local size = Reader.count(d, 0x0200) + if d.bad then + return nil, d.bad + end + if size == 0 or size > Reader.remaining(d) then + return nil, "bad connectivity size" + end + local eb = Reader.new(d.b, d.pos + size, d.limit, ver) + splits = splitEvents(eb, numFaces) + if not splits then + return nil, eb.bad or "bad split events" + end + splitBytes = eb.pos - (d.pos + size) + else + splits = splitEvents(d, numFaces) + if not splits then + return nil, d.bad or "bad split events" + end + end + local splitData = splits :: { any } + + local trav, after = makeTraversal(traversalKind, Reader.copy(d), numAttributeData, maxVertices, numFaces, ct) + if not trav then + return nil, after.bad or "bad traversal data" + end + + local function V(c: number): number + return if c < 0 then -1 else (c2v[c + 1] or -1) + end + local function O(c: number): number + return if c < 0 then -1 else (opp[c + 1] or -1) + end + local function setOpp(a: number, b: number) + if a >= 0 then + opp[a + 1] = b + end + if b >= 0 then + opp[b + 1] = a + end + end + local function setLmc(v: number, c: number) + if v >= 0 then + lmc[v + 1] = c + end + end + local function LMC(v: number): number + return if v < 0 then -1 else (lmc[v + 1] or -1) + end + local function addVertex(): number + nv += 1 + lmc[nv] = -1 + return nv - 1 + end + local function swingLeft(c: number): number + return nextC(O(nextC(c))) + end + local function swingRight(c: number): number + return prevC(O(prevC(c))) + end + + local stack: { number } = {} + local sp = 0 + local splitActive: { [number]: number } = {} + local invalidVerts: { number } = {} + local removeInvalid = numAttributeData == 0 + local nf = 0 + for symbolId = 0, numSymbols - 1 do + local face = nf + nf += 1 + local checkSplit = false + local symbol = trav.decodeSymbol() + local corner = 3 * face + if symbol == TOPOLOGY_C then + if sp == 0 then + return nil, "bad traversal (C)" + end + local a = stack[sp] + local vx = V(nextC(a)) + local b = nextC(LMC(vx)) + if a == b or O(a) ~= -1 or O(b) ~= -1 then + return nil, "bad traversal (C)" + end + setOpp(a, corner + 1) + setOpp(b, corner + 2) + local vap, vbn = V(prevC(a)), V(nextC(b)) + if vx == vap or vx == vbn then + return nil, "bad traversal (C)" + end + c2v[corner + 1] = vx + c2v[corner + 2] = vbn + c2v[corner + 3] = vap + setLmc(vap, corner + 2) + notHole[vx] = true + stack[sp] = corner + elseif symbol == TOPOLOGY_R or symbol == TOPOLOGY_L then + if sp == 0 then + return nil, "bad traversal (R / L)" + end + local a = stack[sp] + if O(a) ~= -1 then + return nil, "bad traversal (R / L)" + end + local oc, cl, cr + if symbol == TOPOLOGY_R then + oc, cl, cr = corner + 2, corner + 1, corner + else + oc, cl, cr = corner + 1, corner, corner + 2 + end + setOpp(oc, a) + local nvx = addVertex() + if nv > maxVertices then + return nil, "too many vertices" + end + c2v[oc + 1] = nvx + setLmc(nvx, oc) + local vr = V(prevC(a)) + c2v[cr + 1] = vr + setLmc(vr, cr) + c2v[cl + 1] = V(nextC(a)) + stack[sp] = corner + checkSplit = true + elseif symbol == TOPOLOGY_S then + if sp == 0 then + return nil, "bad traversal (S)" + end + local b = stack[sp] + stack[sp] = nil + sp -= 1 + local pushed = splitActive[symbolId] + if pushed then + sp += 1 + stack[sp] = pushed + end + if sp == 0 then + return nil, "bad traversal (S)" + end + local a = stack[sp] + if a == b or O(a) ~= -1 or O(b) ~= -1 then + return nil, "bad traversal (S)" + end + setOpp(a, corner + 2) + setOpp(b, corner + 1) + local vp = V(prevC(a)) + c2v[corner + 1] = vp + c2v[corner + 2] = V(nextC(a)) + local vbp = V(prevC(b)) + c2v[corner + 3] = vbp + setLmc(vbp, corner + 2) + local cn = nextC(b) + local vn = V(cn) + trav.mergeVertices(vp, vn) + setLmc(vp, LMC(vn)) + local first = cn + while cn ~= -1 do + c2v[cn + 1] = vp + cn = swingLeft(cn) + if cn == first then + return nil, "bad traversal (S loop)" + end + end + setLmc(vn, -1) + if removeInvalid then + table.insert(invalidVerts, vn) + end + stack[sp] = corner + elseif symbol == TOPOLOGY_E then + local v0 = addVertex() + c2v[corner + 1] = v0 + c2v[corner + 2] = addVertex() + c2v[corner + 3] = addVertex() + if nv > maxVertices then + return nil, "too many vertices" + end + setLmc(v0, corner) + setLmc(v0 + 1, corner + 1) + setLmc(v0 + 2, corner + 2) + sp += 1 + stack[sp] = corner + checkSplit = true + else + return nil, "bad traversal symbol" + end + ct.nv = nv + trav.newActiveCorner(stack[sp]) + if checkSplit then + local encId = numSymbols - symbolId - 1 + while true do + local top = splitData[#splitData] + if not top then + break + end + if top.source > encId then + return nil, "bad split symbol id" + end + if top.source ~= encId then + break + end + splitData[#splitData] = nil + local act = stack[sp] + local newActive = if top.edge == 1 then nextC(act) else prevC(act) + splitActive[numSymbols - top.split - 1] = newActive + end + end + end + if nv > maxVertices then + return nil, "too many vertices" + end + + -- start faces: interior faces that close the remaining holes + local initFaces = {} + while sp > 0 do + local corner = stack[sp] + stack[sp] = nil + sp -= 1 + if trav.startFace() then + if nf >= numFaces then + return nil, "too many faces" + end + local vn = V(nextC(corner)) + local b = nextC(LMC(vn)) + local vx = V(nextC(b)) + local c = nextC(LMC(vx)) + if corner == b or corner == c or b == c or O(corner) ~= -1 or O(b) ~= -1 or O(c) ~= -1 then + return nil, "bad start face" + end + local vp = V(nextC(c)) + local nc = 3 * nf + nf += 1 + setOpp(nc, corner) + setOpp(nc + 1, b) + setOpp(nc + 2, c) + c2v[nc + 1] = vx + c2v[nc + 2] = vp + c2v[nc + 3] = vn + for k = 0, 2 do + notHole[V(nc + k)] = true + end + table.insert(initFaces, nc) + end + end + if nf ~= numFaces then + return nil, "face count mismatch" + end + + -- compact the vertices removed by S symbols (no attribute data only) + local numVertices = nv + for _, inv in invalidVerts do + local src = numVertices - 1 + while src >= 0 and LMC(src) == -1 do + numVertices -= 1 + src = numVertices - 1 + end + if src >= inv then + -- every corner of src (VertexCornersIterator: left, then right) + local start = LMC(src) + local corners = {} + local cc = start + local left = true + local guard = 0 + while cc ~= -1 do + table.insert(corners, cc) + guard += 1 + if guard > numFaces * 3 + 3 then + return nil, "bad vertex fan" + end + if left then + cc = swingLeft(cc) + if cc == -1 then + cc = swingRight(start) + left = false + elseif cc == start then + cc = -1 + end + else + cc = swingRight(cc) + end + end + for _, cid in corners do + if V(cid) ~= src then + return nil, "bad vertex fan" + end + c2v[cid + 1] = inv + end + setLmc(inv, LMC(src)) + setLmc(src, -1) + notHole[inv] = notHole[src] + notHole[src] = true + numVertices -= 1 + end + end + + -- continue after the traversal data (and the split events before 2.2) + d.pos = after.pos + d.bad = after.bad + if ver < 0x0202 then + d.pos += splitBytes + end + + local attrData: { AttrData } = {} + for i = 1, numAttributeData do + attrData[i] = { decoderId = -1, used = true, seams = {}, ct = nil, enc = newEnc(0) } + end + if numAttributeData > 0 then + for f = 0, numFaces - 1 do + local base = 3 * f + for k = 0, 2 do + local c = if k == 0 then base elseif k == 1 then base + 1 else base + 2 + local o = O(c) + if o == -1 then + for i = 1, numAttributeData do + table.insert(attrData[i].seams, c) + end + elseif ver < 0x0201 or o // 3 >= f then + for i = 1, numAttributeData do + if trav.seam(i - 1) then + table.insert(attrData[i].seams, c) + end + end + end + end + end + end + ct.nv = nv + for i = 1, numAttributeData do + local act = attributeTable(ct, attrData[i].seams) + if not act then + return nil, "bad attribute seams" + end + attrData[i].ct = act + attrData[i].enc = newEnc(math.max(act.nv, nv)) + end + local posEnc = newEnc(nv) + + -- AssignPointsToCorners + local faces = table.create(numFaces * 3, 0) + local numPoints + if numAttributeData == 0 then + for c = 0, numFaces * 3 - 1 do + faces[c + 1] = V(c) + end + numPoints = numVertices + else + numPoints = 0 + for v = 0, nv - 1 do + local c = LMC(v) + if c ~= -1 then + local first = c + if notHole[v] then + for i = 1, numAttributeData do + local act = attrData[i].ct :: any + if act.vertSeam[V(c)] then + local vid = act.c2v[c + 1] + local a = swingRight(c) + local found = false + while a ~= c do + if a == -1 then + return nil, "bad seam fan" + end + if act.c2v[a + 1] ~= vid then + first = a + found = true + break + end + a = swingRight(a) + end + if found then + break + end + end + end + end + c = first + faces[c + 1] = numPoints + numPoints += 1 + local pc = c + c = swingRight(c) + local guard = 0 + while c ~= -1 and c ~= first do + local seam = false + for i = 1, numAttributeData do + local ac2v = (attrData[i].ct :: CT).c2v + if ac2v[c + 1] ~= ac2v[pc + 1] then + seam = true + break + end + end + if seam then + faces[c + 1] = numPoints + numPoints += 1 + else + faces[c + 1] = faces[pc + 1] + end + pc = c + c = swingRight(c) + guard += 1 + if guard > numFaces * 3 then + return nil, "bad vertex fan" + end + end + end + end + end + for k = 1, nv do + if not lmc[k] then + lmc[k] = -1 + end + end + return { + faces = faces, + numFaces = numFaces, + numPoints = numPoints, + ct = ct, + attrData = attrData, + posEnc = posEnc, + posDecoderId = -1, + }, nil +end + +-- MeshTraversalSequencer::GenerateSequence: method 0 depth first, 1 max prediction degree +function Connectivity.traverse(ct: CT, faces: { number }, enc: Enc, method: number): { number }? + local c2v, opp, lmc = ct.c2v, ct.opp, ct.lmc + local nf, nvt = ct.nf, ct.nv + local faceVisited = table.create(nf, false) + local vertVisited = table.create(nvt, false) + local points: { number } = {} + local v2e, e2c = enc.v2e, enc.e2c + local function V(c: number): number + return if c < 0 then -1 else (c2v[c + 1] or -1) + end + local function O(c: number): number + return if c < 0 then -1 else (opp[c + 1] or -1) + end + local function faceSeen(c: number): boolean + if c < 0 then + return true + end + return faceVisited[c // 3 + 1] == true + end + local function visit(v: number, c: number): boolean + if v < 0 or v >= nvt then + return false + end + vertVisited[v + 1] = true + table.insert(points, faces[c + 1]) + table.insert(e2c, c) + v2e[v + 1] = enc.numValues + enc.numValues += 1 + return true + end + local function onBoundary(v: number): boolean + local c = if v < 0 then -1 else (lmc[v + 1] or -1) + return nextC(O(nextC(c))) == -1 + end + if method == 0 then + local stack: { number } = {} + for f = 0, nf - 1 do + local start = 3 * f + if not faceSeen(start) then + stack[1] = start + for k = #stack, 2, -1 do + stack[k] = nil + end + local nx, pv = V(nextC(start)), V(prevC(start)) + if nx == -1 or pv == -1 then + return nil + end + if not vertVisited[nx + 1] and not visit(nx, nextC(start)) then + return nil + end + if not vertVisited[pv + 1] and not visit(pv, prevC(start)) then + return nil + end + while #stack > 0 do + local c = stack[#stack] + if c == -1 or faceSeen(c) then + stack[#stack] = nil + continue + end + while true do + faceVisited[c // 3 + 1] = true + local v = V(c) + if v == -1 then + return nil + end + if not vertVisited[v + 1] then + local boundary = onBoundary(v) + if not visit(v, c) then + return nil + end + if not boundary then + c = O(nextC(c)) + if c == -1 then + -- C++ would index face -1 here; treat as done + stack[#stack] = nil + break + end + continue + end + end + local rc, lc = O(nextC(c)), O(prevC(c)) + if faceSeen(rc) then + if faceSeen(lc) then + stack[#stack] = nil + break + end + c = lc + elseif faceSeen(lc) then + c = rc + else + stack[#stack] = lc + table.insert(stack, rc) + break + end + end + end + end + end + return points + end + if nvt == 0 then + return points + end + local degree = table.create(nvt, 0) + local stacks: { { number } } = { {}, {}, {} } + local best = 0 + local function priority(c: number): number + local v = V(c) + if v < 0 or v >= nvt then + return 0 + end + local p = 0 + if not vertVisited[v + 1] then + degree[v + 1] += 1 + p = if degree[v + 1] > 1 then 1 else 2 + end + return p + end + for f = 0, nf - 1 do + local start = 3 * f + table.insert(stacks[1], start) + best = 0 + local nx, pv, tip = V(nextC(start)), V(prevC(start)), V(start) + for _, pair in { { nx, nextC(start) }, { pv, prevC(start) }, { tip, start } } do + local v = pair[1] + if v < 0 or v >= nvt then + return nil + end + if not vertVisited[v + 1] then + visit(v, pair[2]) + end + end + while true do + local c = -1 + for i = best, 2 do + local s = stacks[i + 1] + if #s > 0 then + c = s[#s] + s[#s] = nil + best = i + break + end + end + if c == -1 then + break + end + if not faceSeen(c) then + while true do + faceVisited[c // 3 + 1] = true + local v = V(c) + if v < 0 or v >= nvt then + return nil + end + if not vertVisited[v + 1] then + visit(v, c) + end + local rc, lc = O(nextC(c)), O(prevC(c)) + local rSeen, lSeen = faceSeen(rc), faceSeen(lc) + if not lSeen then + local p = priority(lc) + if rSeen and p <= best then + c = lc + continue + end + table.insert(stacks[p + 1], lc) + if p < best then + best = p + end + end + if not rSeen then + local p = priority(rc) + if p <= best then + c = rc + continue + end + table.insert(stacks[p + 1], rc) + if p < best then + best = p + end + end + break + end + end + end + end + return points +end + +-- MeshTraversalSequencer::UpdatePointToAttributeIndexMapping +function Connectivity.mapping(ct: CT, faces: { number }, enc: Enc, numPoints: number): { number }? + local map = table.create(numPoints, 0) + local c2v, v2e = ct.c2v, enc.v2e + for c = 0, ct.nf * 3 - 1 do + local p = faces[c + 1] + local v = c2v[c + 1] or -1 + if v == -1 then + return nil + end + local e = v2e[v + 1] or 0 + if p >= numPoints or e >= numPoints then + return nil + end + map[p + 1] = e + end + return map +end + +return Connectivity +end +__FILES["codecs/model/Draco/Int64"] = function() + +-- codecs/model/Draco/Int64: wrap-around int64 / uint64 for Draco's portable tex coord predictor. +-- Values are (hi, lo) 32-bit halves, two's complement (hi >= 2^31 is negative). +local Int64 = {} + +local P32 = 4294967296 +local P31 = 2147483648 + +function Int64.from(n: number): (number, number) + if n >= 0 then + return (n // P32) % P32, n % P32 + end + local h, l = Int64.from(-n) + return Int64.neg(h, l) +end + +function Int64.neg(h: number, l: number): (number, number) + if l == 0 then + return (P32 - h) % P32, 0 + end + return P32 - 1 - h, P32 - l +end + +function Int64.add(ah: number, al: number, bh: number, bl: number): (number, number) + local l = al + bl + local c = 0 + if l >= P32 then + l -= P32 + c = 1 + end + return (ah + bh + c) % P32, l +end + +function Int64.sub(ah: number, al: number, bh: number, bl: number): (number, number) + local nh, nl = Int64.neg(bh, bl) + return Int64.add(ah, al, nh, nl) +end + +function Int64.mul(ah: number, al: number, bh: number, bl: number): (number, number) + local a0, a1, a2, a3 = al % 65536, al // 65536, ah % 65536, ah // 65536 + local b0, b1, b2, b3 = bl % 65536, bl // 65536, bh % 65536, bh // 65536 + local c0 = a0 * b0 + local c1 = a1 * b0 + a0 * b1 + local c2 = a2 * b0 + a1 * b1 + a0 * b2 + local c3 = a3 * b0 + a2 * b1 + a1 * b2 + a0 * b3 + local lo = c0 + (c1 % 65536) * 65536 + local carry = lo // P32 + lo %= P32 + local hi = (c1 // 65536 + c2 + (c3 % 65536) * 65536 + carry) % P32 + return hi, lo +end + +function Int64.isNeg(h: number): boolean + return h >= P31 +end + +function Int64.signed(h: number, l: number): number + if h >= P31 then + return (h - P32) * P32 + l + end + return h * P32 + l +end + +function Int64.unsigned(h: number, l: number): number + return h * P32 + l +end + +function Int64.ucmp(ah: number, al: number, bh: number, bl: number): number + if ah ~= bh then + return if ah < bh then -1 else 1 + end + if al ~= bl then + return if al < bl then -1 else 1 + end + return 0 +end + +function Int64.cmp(ah: number, al: number, bh: number, bl: number): number + local sa = if ah >= P31 then ah - P32 else ah + local sb = if bh >= P31 then bh - P32 else bh + if sa ~= sb then + return if sa < sb then -1 else 1 + end + return Int64.ucmp(0, al, 0, bl) +end + +function Int64.udivmod(ah: number, al: number, bh: number, bl: number): (number, number, number, number) + if ah == 0 and bh == 0 then + return 0, al // bl, 0, al % bl + end + local qh, ql, rh, rl = 0, 0, 0, 0 + for i = 63, 0, -1 do + local bit = if i >= 32 then (ah // 2 ^ (i - 32)) % 2 else (al // 2 ^ i) % 2 + local over = rh >= P31 + rh = (rh * 2 + rl // P31) % P32 + rl = (rl * 2) % P32 + bit + if over or Int64.ucmp(rh, rl, bh, bl) >= 0 then + rh, rl = Int64.sub(rh, rl, bh, bl) + if i >= 32 then + qh += 2 ^ (i - 32) + else + ql += 2 ^ i + end + end + end + return qh, ql, rh, rl +end + +function Int64.div(ah: number, al: number, bh: number, bl: number): (number, number) + local na, nb = ah >= P31, bh >= P31 + if na then + ah, al = Int64.neg(ah, al) + end + if nb then + bh, bl = Int64.neg(bh, bl) + end + local qh, ql = Int64.udivmod(ah, al, bh, bl) + if na ~= nb then + return Int64.neg(qh, ql) + end + return qh, ql +end + +-- IntSqrt (draco/core/math_utils.h) on a uint64, step for step (wrap-around included) +function Int64.isqrt(h: number, l: number): (number, number) + if h == 0 and l == 0 then + return 0, 0 + end + local acth, actl = h, l + local sh, sl = 0, 1 + while Int64.ucmp(acth, actl, 0, 2) >= 0 do + sh, sl = Int64.add(sh, sl, sh, sl) + acth, actl = Int64.udivmod(acth, actl, 0, 4) + end + repeat + local qh, ql = Int64.udivmod(h, l, sh, sl) + local th, tl = Int64.add(sh, sl, qh, ql) + sh, sl = Int64.udivmod(th, tl, 0, 2) + if sh == 0 and sl == 0 then + return 0, 0 + end + local pph, ppl = Int64.mul(sh, sl, sh, sl) + until Int64.ucmp(pph, ppl, h, l) <= 0 + return sh, sl +end + +return Int64 +end +__FILES["codecs/model/Draco/KdTree"] = function() + +-- codecs/model/Draco/KdTree: kd-tree coded point cloud attributes (bitstream 2.3, compression levels 0 - 6). +-- Port of Draco 1.5.7 kd_tree_attributes_decoder.cc, dynamic_integer_points_kd_tree_decoder.h and the direct / +-- folded_integer bit decoders (Apache-2.0, licenses/draco-LICENSE.txt). Pre-2.3 kd-tree layouts are not supported. +local Reader = __include("codecs/model/Draco/Reader") +local Predict = __include("codecs/model/Draco/Predict") + +local KdTree = {} + +type D = Reader.D + +-- bits(n) reads MSB first +type Src = { next: () -> number, bits: (n: number) -> number? } + +local function direct(d: D): Src? + local size = Reader.u32(d) + if d.bad or size == 0 or size % 4 ~= 0 or size > Reader.remaining(d) then + Reader.fail(d, "kd-tree: bad direct bits") + return nil + end + local b, base, words = d.b, d.pos, size // 4 + d.pos += size + local pos, used = 0, 0 + return { + next = function(): number + if pos >= words then + return 0 + end + local w = buffer.readu32(b, base + pos * 4) + local bit = bit32.extract(w, 31 - used) + used += 1 + if used == 32 then + pos += 1 + used = 0 + end + return bit + end, + bits = function(n: number): number? + local remaining = 32 - used + if n <= remaining then + if pos >= words then + return nil + end + local w = buffer.readu32(b, base + pos * 4) + local v = bit32.extract(w, 32 - used - n, n) + used += n + if used == 32 then + pos += 1 + used = 0 + end + return v + end + if pos + 1 >= words then + return nil + end + local hiBits = bit32.extract(buffer.readu32(b, base + pos * 4), 0, remaining) + local lo = n - remaining + pos += 1 + used = lo + local loBits = bit32.extract(buffer.readu32(b, base + pos * 4), 32 - lo, lo) + return hiBits * 2 ^ lo + loBits + end, + } +end + +local function rans(d: D): Src? + local bd = Reader.bitDecoder(d) + if not bd then + return nil + end + local function nextBit(): number + return if Reader.bit(bd) then 1 else 0 + end + return { + next = nextBit, + bits = function(n: number): number? + local v = 0 + for _ = 1, n do + v = v * 2 + nextBit() + end + return v + end, + } +end + +local function folded(d: D): Src? + local parts: { Reader.Bits } = {} + for i = 1, 32 do + local bd = Reader.bitDecoder(d) + if not bd then + return nil + end + parts[i] = bd + end + local main = Reader.bitDecoder(d) + if not main then + return nil + end + return { + next = function(): number + return if Reader.bit(main :: Reader.Bits) then 1 else 0 + end, + bits = function(n: number): number? + local v = 0 + for i = 1, n do + v = v * 2 + (if Reader.bit(parts[i]) then 1 else 0) + end + return v + end, + } +end + +local function msb(n: number): number + local k = -1 + while n >= 1 do + n = n // 2 + k += 1 + end + return k +end + +-- DynamicIntegerPointsKdTreeDecoder::DecodePoints +local function decodePoints(d: D, level: number, dim: number, expected: number): ({ { number } }?, string?) + local bitLength = Reader.u32(d) + local numPoints = Reader.u32(d) + if d.bad then + return nil, d.bad + end + if bitLength > 32 then + return nil, "kd-tree: bad bit length" + end + if numPoints ~= expected then + return nil, "kd-tree: point count mismatch" + end + local out: { { number } } = {} + if numPoints == 0 then + return out, nil + end + local numbers = if level >= 4 then folded(d) elseif level >= 2 then rans(d) else direct(d) + local remainingBits = numbers and direct(d) + local axisDec = remainingBits and direct(d) + local half = axisDec and direct(d) + if not numbers or not remainingBits or not axisDec or not half then + return nil, d.bad or "kd-tree: bad bit decoders" + end + local selectAxis = level >= 6 + local zero = table.create(dim, 0) + local baseStack: { { number } } = { table.clone(zero) } + local levelStack: { { number } } = { table.clone(zero) } + local stack = { { numPoints, 0, 0 } } + local decoded = 0 + local p = table.create(dim, 0) + while #stack > 0 do + local st = stack[#stack] + stack[#stack] = nil + local n, lastAxis, sp = st[1], st[2], st[3] + local oldBase, levels = baseStack[sp + 1], levelStack[sp + 1] + if n > numPoints then + return nil, "kd-tree: bad point count" + end + local axis + if not selectAxis then + axis = if lastAxis == dim - 1 then 0 else lastAxis + 1 + elseif n < 64 then + axis = 0 + for a = 1, dim - 1 do + if levels[axis + 1] > levels[a + 1] then + axis = a + end + end + else + axis = (axisDec :: Src).bits(4) or 0 + end + if axis >= dim then + return nil, "kd-tree: bad axis" + end + local lvl = levels[axis + 1] + if bitLength - lvl == 0 then + for _ = 1, n do + table.insert(out, table.clone(oldBase)) + decoded += 1 + end + if decoded > numPoints then + return nil, "kd-tree: too many points" + end + continue + end + if n <= 2 then + for _ = 1, n do + local a = axis + for _ = 1, dim do + local rb = bitLength - levels[a + 1] + local v = 0 + if rb > 0 then + local got = remainingBits.bits(rb) + if got == nil then + return nil, "kd-tree: remaining bits run out" + end + v = got + end + p[a + 1] = bit32.bor(oldBase[a + 1], v) + a = if a == dim - 1 then 0 else a + 1 + end + table.insert(out, table.clone(p)) + decoded += 1 + end + if decoded > numPoints then + return nil, "kd-tree: too many points" + end + continue + end + if decoded > numPoints then + return nil, "kd-tree: too many points" + end + local rbits = bitLength - lvl + local modifier = 2 ^ (rbits - 1) + local nb = table.clone(oldBase) + nb[axis + 1] = (nb[axis + 1] + modifier) % 4294967296 + baseStack[sp + 2] = nb + local number = numbers.bits(msb(n)) or 0 + local first = n // 2 + if first < number then + return nil, "kd-tree: bad split" + end + first -= number + local second = n - first + if first ~= second and half.next() == 0 then + first, second = second, first + end + levels[axis + 1] += 1 + levelStack[sp + 2] = table.clone(levels) + if sp + 2 > 32 * dim + 1 then + return nil, "kd-tree: too deep" + end + if first > 0 then + table.insert(stack, { first, axis, sp }) + end + if second > 0 then + table.insert(stack, { second, axis, sp + 1 }) + end + end + if decoded ~= expected then + return nil, "kd-tree: point count mismatch" + end + return out, nil +end + +local SIGNED = { [1] = 8, [3] = 16, [5] = 32 } + +function KdTree.decode(d: D, attrs: { any }, numPoints: number): (boolean, string?) + if d.ver < 0x0203 then + return false, "unsupported: kd-tree point clouds before bitstream 2.3" + end + local level = Reader.u8(d) + if d.bad then + return false, d.bad + end + if level > 6 then + return false, "kd-tree: bad compression level" + end + local dim = 0 + for _, a in attrs do + local dt = a.dataType + if dt ~= 2 and dt ~= 4 and dt ~= 6 and dt ~= 1 and dt ~= 3 and dt ~= 5 and dt ~= 9 then + return false, "unsupported: kd-tree attribute of data type " .. dt + end + dim += a.comps + end + local points, err = decodePoints(d, level, dim, numPoints) + if not points then + return false, err + end + -- the portable values per attribute: the low bytes of each u32 for 8 / 16-bit types + local off = 0 + for _, a in attrs do + local comps = a.comps + local vals = table.create(numPoints * comps, 0) + local mod = if a.dataType == 1 or a.dataType == 2 then 256 elseif a.dataType == 3 or a.dataType == 4 then 65536 else 4294967296 + local raw = a.dataType == 9 + for i, pt in points do + for c = 1, comps do + local v = pt[off + c] + vals[(i - 1) * comps + c] = if raw then v else v % mod + end + end + a.portable = vals + a.values = vals + a.numValues = numPoints + a.map = nil + off += comps + end + for _, a in attrs do + if a.dataType == 9 then + local mins = table.create(a.comps, 0) + for c = 1, a.comps do + mins[c] = Reader.f32(d) + end + local range = Reader.f32(d) + local bits = Reader.u8(d) + if d.bad or bits < 1 or bits > 30 then + return false, d.bad or "kd-tree: bad quantization" + end + a.quant = { min = mins, range = range, bits = bits } + end + end + for _, a in attrs do + if SIGNED[a.dataType] then + local mins = table.create(a.comps, 0) + for c = 1, a.comps do + local v = Reader.varint(d) + mins[c] = if v % 2 == 1 then -(v // 2) - 1 else v // 2 + end + if d.bad then + return false, d.bad + end + a.signedMin = mins + end + end + local fround = Predict.fround + for _, a in attrs do + local vals = a.portable :: { number } + local comps = a.comps + if a.dataType == 9 then + local q = a.quant + local delta = fround(q.range / fround(2 ^ q.bits - 1)) + local out = table.create(#vals, 0) + for i = 1, #vals do + local c = (i - 1) % comps + 1 + local v = vals[i] + if v >= 2147483648 then + v -= 4294967296 + end + out[i] = fround(fround(fround(v) * delta) + q.min[c]) + end + a.values = out + elseif SIGNED[a.dataType] then + -- the C++ reads the stored (already narrowed) unsigned values back + local bits = SIGNED[a.dataType] + local mins = a.signedMin + local out = table.create(#vals, 0) + for i = 1, #vals do + local c = (i - 1) % comps + 1 + local u = vals[i] + if u > 2147483647 then + return false, "kd-tree: signed value out of range" + end + local s = Predict.i32(u + mins[c]) + local m = 2 ^ bits + out[i] = (s + m / 2) % m - m / 2 + end + a.values = out + end + end + return true, nil +end + +return KdTree +end +__FILES["codecs/model/Draco/Predict"] = function() + +-- codecs/model/Draco/Predict: Draco attribute prediction schemes and their decoding transforms. +-- C++ integer semantics (int32 wrap, truncating division, exact 64-bit products) and f32 rounding at every step. +-- Port of Draco 1.5.7 prediction_schemes/*, normal_compression_utils.h (Apache-2.0, licenses/draco-LICENSE.txt). +local Reader = __include("codecs/model/Draco/Reader") +local Connectivity = __include("codecs/model/Draco/Connectivity") +local Int64 = __include("codecs/model/Draco/Int64") + +local Predict = {} + +type D = Reader.D +type CT = Connectivity.CT + +local nextC, prevC = Connectivity.next, Connectivity.prev + +local F32 = buffer.create(4) +local function fround(x: number): number + buffer.writef32(F32, 0, x) + return buffer.readf32(F32, 0) +end +Predict.fround = fround + +local function i32(x: number): number + return (x + 2147483648) % 4294967296 - 2147483648 +end +Predict.i32 = i32 + +local function tdiv(a: number, b: number): number + local q = a / b + return if q < 0 then math.ceil(q) else math.floor(q) +end + +-- static_cast<int> of a float with the decoder's NaN / range guard (INT_MIN) +local function truncInt(x: number): number + if x ~= x or x > 2147483647 or x < -2147483648 then + return -2147483648 + end + return tdiv(x, 1) +end + +-- exact a * b = p + e (Dekker), for integers below 2^53 +local SPLIT = 134217729 +local function twoProd(a: number, b: number): (number, number) + local p = a * b + local t = SPLIT * a + local ah = t - (t - a) + local al = a - ah + t = SPLIT * b + local bh = t - (t - b) + local bl = b - bh + return p, ((ah * bh - p) + ah * bl + al * bh) + al * bl +end + +-- trunc(a * b / c) for integers, exact while the true product is below 2^106 (c > 0) +local function mulDiv(a: number, b: number, c: number): number + local neg = (a < 0) ~= (b < 0) + a, b = math.abs(a), math.abs(b) + local p = a * b + local q + if p < 9007199254740992 then + q = p // c + else + q = math.floor(p / c) + local ph, pl = twoProd(a, b) + local qh, ql = twoProd(q, c) + local r = (ph - qh) + (pl - ql) + while r < 0 do + q -= 1 + r += c + end + while r >= c do + q += 1 + r -= c + end + end + return if neg then -q else q +end + +-- floor(sqrt(a * b)) (IntSqrt of a 64-bit product), exact for a, b < 2^53 +local function isqrtProd(a: number, b: number): number + if a == 0 or b == 0 then + return 0 + end + local s = math.floor(math.sqrt(a) * math.sqrt(b)) + local ph, pl = twoProd(a, b) + local function le(x: number): boolean + local xh, xl = twoProd(x, x) + if xh ~= ph then + return xh < ph + end + return xl <= pl + end + while s > 0 and not le(s) do + s -= 1 + end + while le(s + 1) do + s += 1 + end + return s +end + +type Oct = { bits: number, maxQ: number, maxV: number, center: number, scale: number } + +function Predict.octahedron(bits: number): Oct? + if bits < 2 or bits > 30 then + return nil + end + local maxQ = 2 ^ bits - 1 + local maxV = maxQ - 1 + return { bits = bits, maxQ = maxQ, maxV = maxV, center = maxV // 2, scale = fround(2 / fround(maxV)) } +end + +local function canonicalizeCoords(o: Oct, s: number, t: number): (number, number) + local maxV, center = o.maxV, o.center + if (s == 0 and t == 0) or (s == 0 and t == maxV) or (s == maxV and t == 0) then + return maxV, maxV + elseif s == 0 and t > center then + t = center - (t - center) + elseif s == maxV and t < center then + t = center + (center - t) + elseif t == maxV and s < center then + s = center + (center - s) + elseif t == 0 and s > center then + s = center - (s - center) + end + return s, t +end + +local function intVectorToOct(o: Oct, x: number, y: number, z: number): (number, number) + local s, t + local center, maxV = o.center, o.maxV + if x >= 0 then + s, t = y + center, z + center + else + s = if y < 0 then math.abs(z) else maxV - math.abs(z) + t = if z < 0 then math.abs(y) else maxV - math.abs(y) + end + return canonicalizeCoords(o, s, t) +end + +local function canonicalizeVector(o: Oct, x: number, y: number, z: number): (number, number, number) + local sum = math.abs(x) + math.abs(y) + math.abs(z) + local center = o.center + if sum == 0 then + return center, y, z + end + x = mulDiv(x, center, sum) + y = mulDiv(y, center, sum) + if z >= 0 then + z = center - math.abs(x) - math.abs(y) + else + z = -(center - math.abs(x) - math.abs(y)) + end + return x, y, z +end + +local function invertDiamond(o: Oct, s: number, t: number): (number, number) + local signS, signT + if s >= 0 and t >= 0 then + signS, signT = 1, 1 + elseif s <= 0 and t <= 0 then + signS, signT = -1, -1 + else + signS = if s > 0 then 1 else -1 + signT = if t > 0 then 1 else -1 + end + local cs, ctv = signS * o.center, signT * o.center + local us, ut = s + s - cs, t + t - ctv + if signS * signT >= 0 then + us, ut = -ut, -us + else + us, ut = ut, us + end + return tdiv(i32(us + cs), 2), tdiv(i32(ut + ctv), 2) +end + +local function modMax(o: Oct, x: number): number + if x > o.center then + return x - o.maxQ + elseif x < -o.center then + return x + o.maxQ + end + return x +end + +-- quantized octahedral (s, t) -> unit vector, in f32 like the C++ +function Predict.octToVector(o: Oct, s: number, t: number): (number, number, number) + local y = fround(fround(fround(s) * o.scale) - 1) + local z = fround(fround(fround(t) * o.scale) - 1) + local x = fround(fround(1 - math.abs(y)) - math.abs(z)) + local xo = -x + if xo < 0 then + xo = 0 + end + y = fround(if y < 0 then y + xo else y - xo) + z = fround(if z < 0 then z + xo else z - xo) + local n2 = fround(fround(fround(x * x) + fround(y * y)) + fround(z * z)) + if n2 < 1e-6 then + return 0, 0, 0 + end + local dd = fround(1 / fround(math.sqrt(n2))) + return fround(x * dd), fround(y * dd), fround(z * dd) +end + +type Transform = { + kind: number, -- 1 wrap, 2 octahedron, 3 octahedron canonicalized + positive: boolean, -- corrections are stored without the zig-zag sign mapping + min: number, + max: number, + maxDif: number, + oct: Oct?, +} + +function Predict.transform(kind: number): Transform + return { kind = kind, positive = kind ~= 1, min = 0, max = 0, maxDif = 0, oct = nil } +end + +function Predict.decodeTransform(tr: Transform, d: D): boolean + if tr.kind == 1 then + local mn, mx = Reader.i32(d), Reader.i32(d) + if d.bad or mn > mx then + return false + end + local dif = mx - mn + if dif >= 2147483647 then + return false + end + tr.min, tr.max, tr.maxDif = mn, mx, dif + 1 + return true + end + local maxQ = Reader.i32(d) + if tr.kind == 3 or d.ver < 0x0202 then + Reader.i32(d) -- center value (unused) + end + if d.bad or maxQ <= 0 or maxQ % 2 == 0 then + return false + end + local bits = 0 + while 2 ^ bits <= maxQ do + bits += 1 + end + local o = Predict.octahedron(bits) + if not o then + return false + end + tr.oct = o + return true +end + +local function apply(tr: Transform, pred: { number }, data: { number }, off: number, comps: number) + if tr.kind == 1 then + local mn, mx, dif = tr.min, tr.max, tr.maxDif + for c = 1, comps do + local p = pred[c] + if p > mx then + p = mx + elseif p < mn then + p = mn + end + local v = i32(p + data[off + c]) + if v > mx then + v -= dif + elseif v < mn then + v += dif + end + data[off + c] = v + end + return + end + local o = tr.oct :: Oct + local center = o.center + local ps, pt = pred[1] - center, pred[2] - center + local cs, ct = data[off + 1], data[off + 2] + local inDiamond = math.abs(ps) + math.abs(pt) <= center + if not inDiamond then + ps, pt = invertDiamond(o, ps, pt) + end + local os_: number, ot: number = 0, 0 + if tr.kind == 2 then + os_ = modMax(o, i32(ps + cs)) + ot = modMax(o, i32(pt + ct)) + else + local bottomLeft = (ps == 0 and pt == 0) or (ps < 0 and pt <= 0) + local rot = 0 + if ps == 0 then + rot = if pt == 0 then 0 elseif pt > 0 then 3 else 1 + elseif ps > 0 then + rot = if pt >= 0 then 2 else 1 + else + rot = if pt <= 0 then 0 else 3 + end + local function rotate(x: number, y: number, r: number): (number, number) + if r == 1 then + return y, -x + elseif r == 2 then + return -x, -y + elseif r == 3 then + return -y, x + end + return x, y + end + if not bottomLeft then + ps, pt = rotate(ps, pt, rot) + end + os_ = modMax(o, i32(ps + cs)) + ot = modMax(o, i32(pt + ct)) + if not bottomLeft then + os_, ot = rotate(os_, ot, (4 - rot) % 4) + end + end + if not inDiamond then + os_, ot = invertDiamond(o, os_, ot) + end + data[off + 1] = os_ + center + data[off + 2] = ot + center +end +Predict.apply = apply + +type MeshData = { ct: CT, e2c: { number }, v2e: { number } } +type Parent = (point: number) -> (number, number, number) + +type Scheme = { + method: number, + tr: Transform, + md: MeshData?, + parent: Parent?, + crease: { { boolean } }?, + orient: { boolean }?, + flips: Reader.Bits?, + areaMode: boolean, + ver: number, +} + +local DELTA, PARALLELOGRAM, MULTI, TEXDEP, CONSTRAINED, TEXPORT, GEONORMAL = 0, 1, 2, 3, 4, 5, 6 +Predict.GEOMETRIC_NORMAL = GEONORMAL + +function Predict.needsParent(s: Scheme): boolean + return s.md ~= nil and (s.method == TEXDEP or s.method == TEXPORT or s.method == GEONORMAL) +end + +-- CreatePredictionSchemeForDecoder: md = nil (no corner table: sequential connectivity, point clouds) gives delta +function Predict.new(method: number, tr: Transform, md: MeshData?): Scheme + local m = method + if not md then + m = DELTA + elseif tr.kind ~= 1 then + if m ~= GEONORMAL then + m = DELTA + md = nil + end + elseif m < PARALLELOGRAM or m > GEONORMAL then + m = DELTA + md = nil + end + return { method = m, tr = tr, md = if m == DELTA then nil else md, parent = nil, areaMode = true, ver = 0x0202 } +end + +-- DecodePredictionData +function Predict.decodeData(s: Scheme, d: D): boolean + local m = s.method + s.ver = d.ver + if m == CONSTRAINED then + if d.ver < 0x0202 then + local mode = Reader.u8(d) + if d.bad or mode ~= 0 then + return false + end + end + local md = s.md :: MeshData + local crease = {} + for i = 1, 4 do + local n = Reader.varint(d) + if d.bad or n > md.ct.nf * 3 then + return false + end + local flags = table.create(n, false) + if n > 0 then + local bd = Reader.bitDecoder(d) + if not bd then + return false + end + for j = 1, n do + flags[j] = Reader.bit(bd) + end + end + crease[i] = flags + end + s.crease = crease + elseif m == TEXPORT then + local n = Reader.i32(d) + if d.bad or n < 0 or n > (s.md :: MeshData).ct.nf * 3 then + return false + end + local bd = Reader.bitDecoder(d) + if not bd then + return false + end + local orient = table.create(n, false) + local last = true + for i = 1, n do + if not Reader.bit(bd) then + last = not last + end + orient[i] = last + end + s.orient = orient + elseif m == TEXDEP then + local n = Reader.count(d, 0x0202) + local md = s.md :: MeshData + if d.bad or n == 0 or n > md.ct.nf * 3 then + return false + end + local bd = Reader.bitDecoder(d) + if not bd then + return false + end + local orient = table.create(n, false) + local last = true + for i = 1, n do + if not Reader.bit(bd) then + last = not last + end + orient[i] = last + end + s.orient = orient + elseif m == GEONORMAL then + if not Predict.decodeTransform(s.tr, d) then + return false + end + if d.ver < 0x0202 then + local mode = Reader.u8(d) + if d.bad or mode > 1 then + return false + end + s.areaMode = mode == 1 + end + local bd = Reader.bitDecoder(d) + if not bd then + return false + end + s.flips = bd + return true + end + return Predict.decodeTransform(s.tr, d) +end + +local function parallelogram(md: MeshData, p: number, ci: number, data: { number }, comps: number, out: { number }): boolean + local ct = md.ct + local oci = if ci < 0 then -1 else (ct.opp[ci + 1] or -1) + if oci == -1 then + return false + end + local c2v, v2e = ct.c2v, md.v2e + local vo, vn, vp = c2v[oci + 1] or -1, c2v[nextC(oci) + 1] or -1, c2v[prevC(oci) + 1] or -1 + if vo < 0 or vn < 0 or vp < 0 then + return false + end + local eo, en, ep = v2e[vo + 1] or 0, v2e[vn + 1] or 0, v2e[vp + 1] or 0 + if eo < p and en < p and ep < p then + for c = 1, comps do + out[c] = i32((data[en * comps + c] + data[ep * comps + c]) - data[eo * comps + c]) + end + return true + end + return false +end + +local function swingRight(ct: CT, c: number): number + local p = prevC(c) + local o = if p < 0 then -1 else (ct.opp[p + 1] or -1) + return prevC(o) +end +local function swingLeft(ct: CT, c: number): number + local n = nextC(c) + local o = if n < 0 then -1 else (ct.opp[n + 1] or -1) + return nextC(o) +end + +-- MeshPredictionSchemeTexCoordsPortablePredictor::ComputePredictedValue in int64 / uint64 like the C++ +local function texPortable(nu: number, nv: number, pu: number, pv: number, tx: number, ty: number, tz: number, nx: number, ny: number, nz: number, qx: number, qy: number, qz: number, pop: () -> boolean?): (string, any, any) + local pnx, pny, pnz = qx - nx, qy - ny, qz - nz + local cnx, cny, cnz = tx - nx, ty - ny, tz - nz + local pnu, pnv = pu - nu, pv - nv + local B = 67108864 -- 2^26: below it every product and sum stays exact in a double + local small = math.abs(pnx) < B and math.abs(pny) < B and math.abs(pnz) < B and math.abs(cnx) < B and math.abs(cny) < B and math.abs(cnz) < B + if small then + local pn2 = pnx * pnx + pny * pny + pnz * pnz + local dot = pnx * cnx + pny * cny + pnz * cnz + if pn2 < B and math.abs(dot) < B and math.abs(nu) < B and math.abs(nv) < B and math.abs(pnu) < B and math.abs(pnv) < B then + if pn2 == 0 then + return "fallback" + end + local xu, xv = nu * pn2 + dot * pnu, nv * pn2 + dot * pnv + local dx = tx - (nx + tdiv(dot * pnx, pn2)) + local dy = ty - (ny + tdiv(dot * pny, pn2)) + local dz = tz - (nz + tdiv(dot * pnz, pn2)) + local cx2 = dx * dx + dy * dy + dz * dz + if cx2 < B then + local norm = isqrtProd(cx2, pn2) + local cxu, cxv = pnv * norm, -pnu * norm + local o = pop() + if o == nil then + return "fail", "prediction: orientations run out" + end + if o then + return "ok", i32(tdiv(xu + cxu, pn2)), i32(tdiv(xv + cxv, pn2)) + end + return "ok", i32(tdiv(xu - cxu, pn2)), i32(tdiv(xv - cxv, pn2)) + end + end + end + local from, add, sub, mul, div = Int64.from, Int64.add, Int64.sub, Int64.mul, Int64.div + local function dot3(ax: number, ay: number, az: number, bx: number, by: number, bz: number): (number, number) + local xh, xl = from(ax) + local yh, yl = from(ay) + local zh, zl = from(az) + local uh, ul = from(bx) + local vh, vl = from(by) + local wh, wl = from(bz) + local h1, l1 = mul(xh, xl, uh, ul) + local h2, l2 = mul(yh, yl, vh, vl) + local h3, l3 = mul(zh, zl, wh, wl) + h1, l1 = add(h1, l1, h2, l2) + return add(h1, l1, h3, l3) + end + local p2h, p2l = dot3(pnx, pny, pnz, pnx, pny, pnz) + if p2h == 0 and p2l == 0 then + return "fallback" + end + local dh, dl = dot3(pnx, pny, pnz, cnx, cny, cnz) + local MAXH, MAXL = 2147483647, 4294967295 -- INT64_MAX + local function absmax(...: number): (number, number) + local m = 0 + for _, x in { ... } do + m = math.max(m, math.abs(x)) + end + return from(m) + end + local function absI(h: number, l: number): (number, number) + if Int64.isNeg(h) then + return Int64.neg(h, l) + end + return h, l + end + -- the overflow guards (unsigned divisions as in the C++) + local nmh, nml = absmax(nu, nv) + local lh, ll = Int64.udivmod(MAXH, MAXL, p2h, p2l) + if Int64.ucmp(nmh, nml, lh, ll) > 0 then + return "fail", "prediction: tex coord overflow" + end + local adh, adl = absI(dh, dl) + local pmh, pml = absmax(pnu, pnv) + lh, ll = Int64.div(MAXH, MAXL, pmh, pml) + if Int64.cmp(adh, adl, lh, ll) > 0 then + return "fail", "prediction: tex coord overflow" + end + local nuh, nul = from(nu) + local nvh, nvl = from(nv) + local puh, pul = from(pnu) + local pvh, pvl = from(pnv) + local xuh, xul + do + local ah, al = mul(nuh, nul, p2h, p2l) + local bh, bl = mul(dh, dl, puh, pul) + xuh, xul = add(ah, al, bh, bl) + end + local xvh, xvl + do + local ah, al = mul(nvh, nvl, p2h, p2l) + local bh, bl = mul(dh, dl, pvh, pvl) + xvh, xvl = add(ah, al, bh, bl) + end + local pam = math.max(math.abs(pnx), math.abs(pny), math.abs(pnz)) + local pah, pal = from(pam) + lh, ll = Int64.div(MAXH, MAXL, pah, pal) + if Int64.cmp(adh, adl, lh, ll) > 0 then + return "fail", "prediction: tex coord overflow" + end + -- x_pos = next + (dot * pn) / pn2; cx = tip - x_pos + local function proj(n: number, pc: number, t: number): (number, number) + local ph, pl = from(pc) + local mh, ml = mul(dh, dl, ph, pl) + local qh, ql = div(mh, ml, p2h, p2l) + local nh, nl = from(n) + local xh, xl = add(nh, nl, qh, ql) + local th, tl = from(t) + return sub(th, tl, xh, xl) + end + local ax, axl = proj(nx, pnx, tx) + local ay, ayl = proj(ny, pny, ty) + local az, azl = proj(nz, pnz, tz) + local c2h, c2l = mul(ax, axl, ax, axl) + do + local h, l = mul(ay, ayl, ay, ayl) + c2h, c2l = add(c2h, c2l, h, l) + h, l = mul(az, azl, az, azl) + c2h, c2l = add(c2h, c2l, h, l) + end + local prh, prl = mul(c2h, c2l, p2h, p2l) + local sh, sl = Int64.isqrt(prh, prl) + -- cx_uv = (pn_uv.v, -pn_uv.u) * norm + local cuh, cul = mul(pvh, pvl, sh, sl) + local nh, nl = Int64.neg(puh, pul) + local cvh, cvl = mul(nh, nl, sh, sl) + local o = pop() + if o == nil then + return "fail", "prediction: orientations run out" + end + local uh, ul, vh, vl + if o then + uh, ul = add(xuh, xul, cuh, cul) + vh, vl = add(xvh, xvl, cvh, cvl) + else + uh, ul = sub(xuh, xul, cuh, cul) + vh, vl = sub(xvh, xvl, cvh, cvl) + end + uh, ul = div(uh, ul, p2h, p2l) + vh, vl = div(vh, vl, p2h, p2l) + -- static_cast<int>: the low 32 bits + return "ok", i32(ul), i32(vl) +end + +-- ComputeOriginalValues (in place); points = the entry -> point map +function Predict.compute(s: Scheme, data: { number }, numEntries: number, comps: number, points: { number }): (boolean, string?) + local tr = s.tr + local m = s.method + local pred = table.create(math.max(comps, 3), 0) + if m == DELTA then + if numEntries == 0 then + return true, nil + end + apply(tr, pred, data, 0, comps) + for e = 1, numEntries - 1 do + local off = e * comps + for c = 1, comps do + pred[c] = data[off - comps + c] + end + apply(tr, pred, data, off, comps) + end + return true, nil + end + local md = s.md :: MeshData + local e2c = md.e2c + local n = #e2c + if n ~= numEntries then + return false, "prediction: value count mismatch" + end + local ct = md.ct + local function previous(p: number) + local off = (p - 1) * comps + for c = 1, comps do + pred[c] = data[off + c] + end + end + if m == PARALLELOGRAM or m == MULTI or m == CONSTRAINED then + if n == 0 then + return true, nil + end + apply(tr, pred, data, 0, comps) + local para = table.create(comps, 0) + local preds: { { number } } = { table.create(comps, 0), table.create(comps, 0), table.create(comps, 0), table.create(comps, 0) } + local creasePos = { 0, 0, 0, 0 } + local nc = ct.nf * 3 + for p = 1, n - 1 do + local start = e2c[p + 1] + local off = p * comps + if m == PARALLELOGRAM then + if parallelogram(md, p, start, data, comps, pred) then + apply(tr, pred, data, off, comps) + else + previous(p) + apply(tr, pred, data, off, comps) + end + elseif m == MULTI then + for c = 1, comps do + pred[c] = 0 + end + local count = 0 + local ci = start + local guard = 0 + while ci ~= -1 do + if parallelogram(md, p, ci, data, comps, para) then + for c = 1, comps do + pred[c] = i32(pred[c] + para[c]) + end + count += 1 + end + ci = swingRight(ct, ci) + if ci == start then + ci = -1 + end + guard += 1 + if guard > nc then + return false, "prediction: bad vertex fan" + end + end + if count == 0 then + previous(p) + else + for c = 1, comps do + pred[c] = tdiv(pred[c], count) + end + end + apply(tr, pred, data, off, comps) + else + local count = 0 + local ci = start + local first = true + local guard = 0 + while ci ~= -1 do + if parallelogram(md, p, ci, data, comps, preds[count + 1]) then + count += 1 + if count == 4 then + break + end + end + if first then + ci = swingLeft(ct, ci) + else + ci = swingRight(ct, ci) + end + if ci == start then + break + end + if ci == -1 and first then + first = false + ci = swingRight(ct, start) + end + guard += 1 + if guard > nc then + return false, "prediction: bad vertex fan" + end + end + local used = 0 + if count > 0 then + for c = 1, comps do + pred[c] = 0 + end + local crease = s.crease :: { { boolean } } + for i = 1, count do + local pos = creasePos[count] + 1 + creasePos[count] = pos + local flag = crease[count][pos] + if flag == nil then + return false, "prediction: crease flags run out" + end + if not flag then + used += 1 + for c = 1, comps do + pred[c] = i32(pred[c] + preds[i][c]) + end + end + end + end + if used == 0 then + previous(p) + else + for c = 1, comps do + pred[c] = tdiv(pred[c], used) + end + end + apply(tr, pred, data, off, comps) + end + end + return true, nil + end + local parent = s.parent + if not parent then + return false, "prediction: no position attribute" + end + local c2v, v2e = ct.c2v, md.v2e + local function entryOf(c: number): number + local v = if c < 0 then -1 else (c2v[c + 1] or -1) + if v < 0 then + return math.huge + end + return v2e[v + 1] or 0 + end + local function posOf(e: number): (number, number, number) + local pt = points[e + 1] + if pt == nil then + return 0, 0, 0 + end + return parent(pt) + end + if m == TEXPORT or m == TEXDEP then + if comps ~= 2 then + return false, "prediction: tex coords need 2 components" + end + local orient = s.orient :: { boolean } + local no = #orient + for p = 0, n - 1 do + local ci = e2c[p + 1] + local ne, pe = entryOf(nextC(ci)), entryOf(prevC(ci)) + local done = false + if pe < p and ne < p then + local nu, nv = data[ne * 2 + 1], data[ne * 2 + 2] + local pu, pv = data[pe * 2 + 1], data[pe * 2 + 2] + if m == TEXPORT then + if pu == nu and pv == nv then + pred[1], pred[2] = pu, pv + done = true + else + local tx, ty, tz = posOf(p) + local nx, ny, nz = posOf(ne) + local qx, qy, qz = posOf(pe) + local status, u, v = texPortable(nu, nv, pu, pv, tx, ty, tz, nx, ny, nz, qx, qy, qz, function(): boolean? + if no == 0 then + return nil + end + local o = orient[no] + orient[no] = nil + no -= 1 + return o + end) + if status == "fail" then + return false, u :: any + elseif status == "ok" then + pred[1], pred[2] = u, v + done = true + end + end + else + local fnu, fnv, fpu, fpv = fround(nu), fround(nv), fround(pu), fround(pv) + if fpu == fnu and fpv == fnv then + pred[1], pred[2] = truncInt(fpu), truncInt(fpv) + done = true + else + local tx: number, ty: number, tz: number = posOf(p) + local nx: number, ny: number, nz: number = posOf(ne) + local qx: number, qy: number, qz: number = posOf(pe) + tx, ty, tz, nx, ny, nz = fround(tx), fround(ty), fround(tz), fround(nx), fround(ny), fround(nz) + qx, qy, qz = fround(qx), fround(qy), fround(qz) + local pnx, pny, pnz = fround(qx - nx), fround(qy - ny), fround(qz - nz) + local cnx, cny, cnz = fround(tx - nx), fround(ty - ny), fround(tz - nz) + local pn2 = fround(fround(fround(pnx * pnx) + fround(pny * pny)) + fround(pnz * pnz)) + local sv, tv = 0, 0 + if s.ver < 0x0102 or pn2 > 0 then + local dot = fround(fround(fround(pnx * cnx) + fround(pny * cny)) + fround(pnz * cnz)) + sv = fround(dot / pn2) + local ex, ey, ez = fround(cnx - fround(pnx * sv)), fround(cny - fround(pny * sv)), fround(cnz - fround(pnz * sv)) + local e2 = fround(fround(fround(ex * ex) + fround(ey * ey)) + fround(ez * ez)) + tv = fround(math.sqrt(fround(e2 / pn2))) + end + local pnu, pnv = fround(fpu - fnu), fround(fpv - fnv) + local pnus = fround(fround(pnu * sv) + fnu) + local pnut = fround(pnu * tv) + local pnvs = fround(fround(pnv * sv) + fnv) + local pnvt = fround(pnv * tv) + if no == 0 then + return false, "prediction: orientations run out" + end + local o = orient[no] + orient[no] = nil + no -= 1 + local u: number, v: number = 0, 0 + if o then + u = fround(pnus - pnvt) + v = fround(pnvs + pnut) + else + u = fround(pnus + pnvt) + v = fround(pnvs - pnut) + end + local function toInt(x: number): number + local r = math.floor(x + 0.5) + if r ~= r or r > 2147483647 or r < -2147483648 then + return -2147483648 + end + return r + end + pred[1] = toInt(u) + pred[2] = toInt(v) + done = true + end + end + end + if not done then + local off = -1 + if pe < p then + off = pe * 2 + end + if ne < p then + off = ne * 2 + elseif p > 0 then + off = (p - 1) * 2 + else + off = -1 + end + if off < 0 then + pred[1], pred[2] = 0, 0 + else + pred[1], pred[2] = data[off + 1], data[off + 2] + end + end + apply(tr, pred, data, p * 2, 2) + end + return true, nil + end + local o = tr.oct + local flips = s.flips + if not o or not flips or comps ~= 2 then + return false, "prediction: bad geometric normal setup" + end + local nc = ct.nf * 3 + for p = 0, n - 1 do + local ci = e2c[p + 1] + local cx, cy, cz = posOf(entryOf(ci)) + local sx, sy, sz = 0, 0, 0 + -- VertexCornersIterator from ci: swing left, then right from the start + local c = ci + local left = true + local guard = 0 + while c ~= -1 do + local cn, cp + if s.areaMode then + cn, cp = nextC(c), prevC(c) + else + cn, cp = nextC(ci), prevC(ci) + end + local ax, ay, az = posOf(entryOf(cn)) + local bx, by, bz = posOf(entryOf(cp)) + ax, ay, az = ax - cx, ay - cy, az - cz + bx, by, bz = bx - cx, by - cy, bz - cz + sx += ay * bz - az * by + sy += az * bx - ax * bz + sz += ax * by - ay * bx + if left then + c = swingLeft(ct, c) + if c == -1 then + c = swingRight(ct, ci) + left = false + elseif c == ci then + c = -1 + end + else + c = swingRight(ct, c) + end + guard += 1 + if guard > nc then + return false, "prediction: bad vertex fan" + end + end + local upper = 2 ^ 29 + local sum = math.abs(sx) + math.abs(sy) + math.abs(sz) + if sum > upper then + local q = sum // upper + sx, sy, sz = tdiv(sx, q), tdiv(sy, q), tdiv(sz, q) + end + sx, sy, sz = i32(sx), i32(sy), i32(sz) + sx, sy, sz = canonicalizeVector(o, sx, sy, sz) + if Reader.bit(flips) then + sx, sy, sz = -sx, -sy, -sz + end + pred[1], pred[2] = intVectorToOct(o, sx, sy, sz) + apply(tr, pred, data, p * 2, 2) + end + return true, nil +end + +return Predict +end +__FILES["codecs/model/Draco/Reader"] = function() + +-- codecs/model/Draco/Reader: Draco's decoder buffer (LE fields, LEB128, LSB-first bit runs) and rANS / rABS decoders. +-- Port of Draco 1.5.7 core/decoder_buffer, core/varint_decoding, entropy/ans.h, rans_symbol_decoder.h, symbol_decoding.cc +-- and rans_bit_decoder.cc (Apache-2.0, licenses/draco-LICENSE.txt). +local Reader = {} + +local readu8, readu16, readu32, readi32, readf32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi32, buffer.readf32 +local band, rshift = bit32.band, bit32.rshift + +type D = { + b: buffer, + pos: number, + limit: number, + ver: number, -- major * 256 + minor + bad: string?, + bitMode: boolean, + bitStart: number, + bitOff: number, +} + +function Reader.new(b: buffer, pos: number, limit: number, ver: number): D + return { b = b, pos = pos, limit = limit, ver = ver, bad = nil, bitMode = false, bitStart = pos, bitOff = 0 } +end + +-- a copy (C++ DecoderBuffer is copied by value: positions are independent afterwards) +function Reader.copy(d: D): D + return { b = d.b, pos = d.pos, limit = d.limit, ver = d.ver, bad = d.bad, bitMode = d.bitMode, bitStart = d.bitStart, bitOff = d.bitOff } +end + +function Reader.fail(d: D, msg: string): number + if not d.bad then + d.bad = msg + end + return 0 +end + +function Reader.remaining(d: D): number + return d.limit - d.pos +end + +function Reader.u8(d: D): number + local p = d.pos + if p + 1 > d.limit then + return Reader.fail(d, "truncated") + end + d.pos = p + 1 + return readu8(d.b, p) +end + +function Reader.i8(d: D): number + local v = Reader.u8(d) + return if v >= 128 then v - 256 else v +end + +function Reader.u16(d: D): number + local p = d.pos + if p + 2 > d.limit then + return Reader.fail(d, "truncated") + end + d.pos = p + 2 + return readu16(d.b, p) +end + +function Reader.u32(d: D): number + local p = d.pos + if p + 4 > d.limit then + return Reader.fail(d, "truncated") + end + d.pos = p + 4 + return readu32(d.b, p) +end + +function Reader.i32(d: D): number + local p = d.pos + if p + 4 > d.limit then + return Reader.fail(d, "truncated") + end + d.pos = p + 4 + return readi32(d.b, p) +end + +function Reader.u64(d: D): number + local p = d.pos + if p + 8 > d.limit then + return Reader.fail(d, "truncated") + end + d.pos = p + 8 + return readu32(d.b, p) + readu32(d.b, p + 4) * 4294967296 +end + +function Reader.f32(d: D): number + local p = d.pos + if p + 4 > d.limit then + return Reader.fail(d, "truncated") + end + d.pos = p + 4 + return readf32(d.b, p) +end + +-- LEB128 (at most 5 bytes for 32-bit values, 10 for 64-bit); 32-bit values wrap like the C++ shifts +function Reader.varint(d: D, wide: boolean?): number + local maxBytes = if wide then 10 else 5 + local v, mul = 0, 1 + for _ = 1, maxBytes do + local p = d.pos + if p + 1 > d.limit then + return Reader.fail(d, "truncated varint") + end + local c = readu8(d.b, p) + d.pos = p + 1 + v += band(c, 127) * mul + if c < 128 then + if not wide then + v %= 4294967296 + end + return v + end + mul *= 128 + end + return Reader.fail(d, "varint too long") +end + +-- a count stored as u32 before `fixedBefore` (a version number) and as a varint from then on +function Reader.count(d: D, fixedBefore: number): number + if d.ver < fixedBefore then + return Reader.u32(d) + end + return Reader.varint(d) +end + +-- StartBitDecoding(decodeSize): an optional size (u64 before 2.2, varint64 after), then LSB-first bits up to the end +-- of the buffer; EndBitDecoding moves pos past the whole bytes consumed. +function Reader.startBits(d: D, decodeSize: boolean): number + local size = 0 + if decodeSize then + if d.ver < 0x0202 then + size = Reader.u64(d) + else + size = Reader.varint(d, true) + end + end + d.bitMode = true + d.bitStart = d.pos + d.bitOff = 0 + return size +end + +function Reader.bits(d: D, n: number): number + if not d.bitMode then + return Reader.fail(d, "bit decoder not active") + end + if n > 32 then + return Reader.fail(d, "bit run over 32 bits") + end + local b, start, limit = d.b, d.bitStart, d.limit + local off = d.bitOff + local v, mul = 0, 1 + for _ = 1, n do + local byte = start + rshift(off, 3) + if byte < limit then + if band(rshift(readu8(b, byte), band(off, 7)), 1) == 1 then + v += mul + end + off += 1 + end + mul *= 2 + end + d.bitOff = off + return v +end + +function Reader.endBits(d: D) + d.bitMode = false + d.pos = d.bitStart + (d.bitOff + 7) // 8 +end + +-- the precision for a symbol alphabet of `bitLength`-bit symbols: (3 * bits) / 2 clamped to 12..20 +local function precisionBits(bitLength: number): number + local p = (3 * bitLength) // 2 + return if p < 12 then 12 elseif p > 20 then 20 else p +end + +type Rans = { + b: buffer, + base: number, + off: number, + state: number, + lBase: number, + precBits: number, + lut: { number }, + prob: { number }, + cum: { number }, + numSymbols: number, +} + +-- RAnsSymbolDecoder::Create: the probability table +local function ransCreate(d: D, precBits: number): Rans? + local numSymbols = Reader.count(d, 0x0200) + if d.bad then + return nil + end + if numSymbols // 64 > Reader.remaining(d) then + Reader.fail(d, "rans: too many symbols") + return nil + end + local prec = 2 ^ precBits + local prob = table.create(numSymbols, 0) + local i = 0 + while i < numSymbols do + local data = Reader.u8(d) + if d.bad then + return nil + end + local token = band(data, 3) + if token == 3 then + local offset = rshift(data, 2) + if i + offset >= numSymbols then + Reader.fail(d, "rans: bad zero run") + return nil + end + for j = 0, offset do + prob[i + j + 1] = 0 + end + i += offset + 1 + else + local p = rshift(data, 2) + for k = 1, token do + p += Reader.u8(d) * 2 ^ (8 * k - 2) + end + if d.bad then + return nil + end + prob[i + 1] = p + i += 1 + end + end + local lut: { number } = {} + local cum = table.create(numSymbols, 0) + if numSymbols > 0 then + lut = table.create(prec, 0) + local c, act = 0, 0 + for s = 1, numSymbols do + cum[s] = c + c += prob[s] + if c > prec then + Reader.fail(d, "rans: probabilities over the precision") + return nil + end + for j = act + 1, c do + lut[j] = s + end + act = c + end + if c ~= prec then + Reader.fail(d, "rans: probabilities do not sum to the precision") + return nil + end + end + return { + b = d.b, + base = 0, + off = 0, + state = 0, + lBase = prec * 4, + precBits = precBits, + lut = lut, + prob = prob, + cum = cum, + numSymbols = numSymbols, + } +end + +-- read_init over [base, base + size): the final state is stored in the last 1-4 bytes +local function ansInit(b: buffer, base: number, size: number, lBase: number, allow4: boolean): (number?, number?) + if size < 1 then + return nil, nil + end + local x = rshift(readu8(b, base + size - 1), 6) + local off: number, state: number = 0, 0 + if x == 0 then + off = size - 1 + state = band(readu8(b, base + size - 1), 0x3F) + elseif x == 1 then + if size < 2 then + return nil, nil + end + off = size - 2 + state = band(readu16(b, base + size - 2), 0x3FFF) + elseif x == 2 then + if size < 3 then + return nil, nil + end + off = size - 3 + state = readu16(b, base + size - 3) + band(readu8(b, base + size - 1), 0x3F) * 65536 + else + if not allow4 or size < 4 then + return nil, nil + end + off = size - 4 + state = band(readu32(b, base + size - 4), 0x3FFFFFFF) + end + state += lBase + if state >= lBase * 256 then + return nil, nil + end + return off, state +end + +-- RAnsSymbolDecoder::StartDecoding: the coded size, then the bytes +local function ransStart(d: D, r: Rans): boolean + local size + if d.ver < 0x0200 then + size = Reader.u64(d) + else + size = Reader.varint(d, true) + end + if d.bad then + return false + end + if size > Reader.remaining(d) then + Reader.fail(d, "rans: data past the end") + return false + end + local off, state = ansInit(d.b, d.pos, size, r.lBase, true) + if not off then + Reader.fail(d, "rans: bad initial state") + return false + end + r.base, r.off, r.state = d.pos, off, state :: number + d.pos += size + return true +end + +local function ransRead(r: Rans, n: number, out: { number }, first: number) + local b, base, off, state = r.b, r.base, r.off, r.state + local lBase, bits = r.lBase, r.precBits + local mask = 2 ^ bits - 1 + local lut, prob, cum = r.lut, r.prob, r.cum + for i = first, first + n - 1 do + while state < lBase and off > 0 do + off -= 1 + state = state * 256 + readu8(b, base + off) + end + local quo, rem = rshift(state, bits), band(state, mask) + local s = lut[rem + 1] + state = quo * prob[s] + rem - cum[s] + out[i] = s - 1 + end + r.off, r.state = off, state +end + +local function decodeTagged(d: D, n: number, comps: number, out: { number }): boolean + local tag = ransCreate(d, precisionBits(5)) + if not tag or not ransStart(d, tag) then + return false + end + if n > 0 and tag.numSymbols == 0 then + Reader.fail(d, "rans: no symbols") + return false + end + Reader.startBits(d, false) + local len = { 0 } + local k = 1 + local i = 0 + while i < n do + ransRead(tag, 1, len, 1) + local bitLength = len[1] + for _ = 1, comps do + if k > n then + break + end + out[k] = Reader.bits(d, bitLength) + k += 1 + end + if d.bad then + return false + end + i += comps + end + Reader.endBits(d) + return true +end + +local function decodeRaw(d: D, n: number, out: { number }): boolean + local maxBitLength = Reader.u8(d) + if d.bad then + return false + end + if maxBitLength < 1 or maxBitLength > 18 then + Reader.fail(d, "rans: bad symbol bit length") + return false + end + local r = ransCreate(d, precisionBits(maxBitLength)) + if not r then + return false + end + if n > 0 and r.numSymbols == 0 then + Reader.fail(d, "rans: no symbols") + return false + end + if not ransStart(d, r) then + return false + end + ransRead(r, n, out, 1) + return true +end + +-- DecodeSymbols +function Reader.symbols(d: D, n: number, comps: number): { number }? + local out = table.create(n, 0) + if n == 0 then + return out + end + local scheme = Reader.u8(d) + if d.bad then + return nil + end + local ok + if scheme == 0 then + ok = decodeTagged(d, n, math.max(comps, 1), out) + elseif scheme == 1 then + ok = decodeRaw(d, n, out) + else + Reader.fail(d, "rans: unknown symbol coding scheme") + ok = false + end + return if ok then out else nil +end + +type Bits = { b: buffer, base: number, off: number, state: number, p0: number, p: number } + +-- RAnsBitDecoder::StartDecoding: prob_zero, the size (u32 before 2.2), the bytes +function Reader.bitDecoder(d: D): Bits? + local p0 = Reader.u8(d) + local size = Reader.count(d, 0x0202) + if d.bad then + return nil + end + if size > Reader.remaining(d) then + Reader.fail(d, "rabs: data past the end") + return nil + end + local off, state = ansInit(d.b, d.pos, size, 4096, false) + if not off then + Reader.fail(d, "rabs: bad initial state") + return nil + end + local bd = { b = d.b, base = d.pos, off = off, state = state :: number, p0 = p0, p = 256 - p0 } + d.pos += size + return bd +end + +-- rabs_desc_read: one bit (true / false) +function Reader.bit(bd: Bits): boolean + local state, off = bd.state, bd.off + if state < 4096 and off > 0 then + off -= 1 + state = state * 256 + readu8(bd.b, bd.base + off) + bd.off = off + end + local quot, rem = rshift(state, 8), band(state, 255) + local p = bd.p + local xn = quot * p + if rem < p then + bd.state = xn + rem + return true + end + bd.state = state - xn - p + return false +end + +return Reader +end +end + + + + + + archive_1 + --!optimize 2 +--!nocheck +-- rosetta chunk archive_1 (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 33 modules (3 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["archive/7z"] = function() + +-- archive/7z: 7z (7zFormat.txt, LZMA SDK, public domain). Supports: encoded headers, solid folders, copy / LZMA / +-- LZMA2 / Deflate / BZip2 / Zstd (7-Zip-zstd frames) with BCJ and delta filters, anti items (skipped), CRC-32s. +-- Not supported: PPMd, BCJ2, Deflate64, other plug-in codecs, AES, multi-volume, external header references, writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Crc32 = __include("core/Crc32") +local Types = __include("Types") +local Lzma = __include("codecs/compress/Lzma") +local Deflate = __include("codecs/compress/Deflate") +local Bzip2 = __include("codecs/compress/Bzip2") +local Zstd = __include("codecs/compress/Zstd") +local Archive = __include("containers/Archive") +local Header = __include("archive/7z/Header") + +-- ------------------------------------------------------------------------------------------------ contract +local SevenZip = { + name = "7z", + 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", "codecs/text/Text" }, + caps = { decode = true, encode = false, methods = { "copy", "lzma", "lzma2", "deflate", "bcj", "delta" }, encrypted = false }, +} + +type DecodeOptions = { + maxBytes: number?, -- default 2^30, per folder or header + checkCrc: boolean?, -- default true +} + +-- ------------------------------------------------------------------------------------------------ constants +local MAGIC = "7z\188\175\39\28" + +-- method id -> xz filter id (BCJ / delta) +local FILTERS: { [string]: number } = { + ["\3\3\1\3"] = 0x04, -- x86 + ["\3\3\2\5"] = 0x05, -- PowerPC + ["\3\3\5\1"] = 0x07, -- ARM + ["\3\3\7\1"] = 0x08, -- ARM-Thumb + ["\3\3\8\5"] = 0x09, -- SPARC + ["\10"] = 0x0A, -- ARM64 + ["\3"] = 0x03, -- delta +} +local NAMES: { [string]: string } = { + ["\0"] = "copy", + ["\3\1\1"] = "lzma", + ["\33"] = "lzma2", + ["\4\1\8"] = "deflate", + ["\4\1\9"] = "deflate64", + ["\4\2\2"] = "bzip2", + ["\3\4\1"] = "ppmd", + ["\3\3\1\27"] = "bcj2", + ["\6\241\7\1"] = "aes", + ["\4\247\17\1"] = "zstd", + ["\4\247\17\2"] = "brotli", + ["\3\3\1\3"] = "bcj", + ["\3\3\2\5"] = "ppc", + ["\3\3\5\1"] = "arm", + ["\3\3\7\1"] = "armt", + ["\3\3\8\5"] = "sparc", + ["\10"] = "arm64", + ["\3"] = "delta", +} + +local function methodName(id: string): string + local n = NAMES[id] + if n then + return n + end + local hex = {} + for i = 1, #id do + table.insert(hex, string.format("%02x", string.byte(id, i))) + end + return "method " .. table.concat(hex) +end + +-- ------------------------------------------------------------------------------------------------ sniff +function SevenZip.sniff(r: Bytes.Reader): number + return if r:peek(6) == MAGIC then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- folder decoding: evaluate the coder graph from the main out stream; every coder here has one in and one out stream +type Ctx = { buf: buffer, base: number, limit: number, maxBytes: number } + +local function packStart(ctx: Ctx, s: Header.Streams, index: number): number + local p = ctx.base + 32 + s.packPos + for i = 1, index do + p += s.packSizes[i] + end + return p +end + +local function decodeFolder(ctx: Ctx, s: Header.Streams, f: Header.Folder): (buffer?, Err.Err?) + local inBase, outBase = {}, {} + local ni, no = 0, 0 + for i, c in f.coders do + inBase[i], outBase[i] = ni, no + ni += c.numIn + no += c.numOut + end + local depth = 0 + local function out(outIdx: number): (buffer?, Err.Err?) + depth += 1 + if depth > 32 then + return nil, Err.new(Err.CORRUPT, "coder graph too deep") + end + local ci + for i, c in f.coders do + if outIdx >= outBase[i] and outIdx < outBase[i] + c.numOut then + ci = i + end + end + if not ci then + return nil, Err.new(Err.CORRUPT, "bad bind pair") + end + local c = f.coders[ci] + if c.numIn ~= 1 or c.numOut ~= 1 then + return nil, Err.new(Err.UNSUPPORTED, methodName(c.id) .. " (multi-stream coder)") + end + local size = f.unpackSizes[outIdx + 1] or 0 + if size > ctx.maxBytes then + return nil, Err.new(Err.LIMIT, string.format("folder of %d bytes is over maxBytes", size)) + end + local inIdx = inBase[ci] + local src: buffer, so: number, sl: number + local bound = nil + for _, bp in f.bindPairs do + if bp.inIndex == inIdx then + bound = bp.outIndex + end + end + if bound then + local b, e = out(bound) + if not b then + return nil, e + end + src = b + so = 0 + sl = buffer.len(b) + else + local k = table.find(f.packed, inIdx) + if not k then + return nil, Err.new(Err.CORRUPT, "unbound coder input") + end + local pi = f.firstPack + k - 1 + if pi >= #s.packSizes then + return nil, Err.new(Err.CORRUPT, "missing pack stream") + end + so = packStart(ctx, s, pi) + sl = s.packSizes[pi + 1] + if so + sl > ctx.limit or so < ctx.base then + return nil, Err.new(Err.TRUNCATED, "pack stream past the end of the archive", so) + end + src = ctx.buf + end + local id = c.id + 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") + end + local b = buffer.create(size) + buffer.copy(b, 0, src, so, size) + 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") + end + local b, e = Lzma.lzma(src, so, sl, c.props, size, opts) + return b, if b then nil else e + elseif id == "\33" then + local b, e = Lzma.lzma2(src, so, sl, nil, size, opts) + return b, if b then nil else e + elseif id == "\4\1\8" then + local b, e = Deflate.inflate(src, so, sl, size) + return b, if b then nil else e + elseif id == "\4\2\2" or id == "\4\247\17\1" then -- BZip2, Zstd (7-Zip-zstd: plain zstd frames) + local b, e + if id == "\4\2\2" then + b, e = Bzip2.decompress(src, so, sl, opts) + else + b, e = Zstd.decompress(src, so, sl, opts) + end + if not b then + return nil, e + end + if buffer.len(b) ~= size then + return nil, Err.new(Err.CORRUPT, methodName(id) .. " stream decodes to the wrong size") + end + return b, nil + elseif FILTERS[id] then + if sl ~= size then + return nil, Err.new(Err.CORRUPT, "filter size mismatch") + end + local b = buffer.create(size) + buffer.copy(b, 0, src, so, size) + local ok, e = Lzma.filter(FILTERS[id], b, 0, size, c.props) + if not ok then + return nil, e + end + return b, nil + end + return nil, Err.new(Err.UNSUPPORTED, methodName(id) .. " is not supported") + end + local main = Header.mainOut(f) + if not main then + return nil, Err.new(Err.CORRUPT, "folder without a main output") + end + return out(main) +end + +local function folderMethod(f: Header.Folder): string + local names = {} + for _, c in f.coders do + table.insert(names, methodName(c.id)) + end + return table.concat(names, "+") +end + +function SevenZip.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Archive?, Err.Err?) + 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 + if limit - base < 32 then + return nil, Err.new(Err.TRUNCATED, "truncated signature header", base) + end + if buffer.readstring(b, base, 6) ~= MAGIC then + return nil, Err.new(Err.CORRUPT, "bad 7z signature", base) + end + if buffer.readu8(b, base + 6) ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "7z major version " .. buffer.readu8(b, base + 6), base + 6) + end + if Crc32.raw(b, base + 12, 20) ~= buffer.readu32(b, base + 8) then + return nil, Err.new(Err.CHECKSUM, "start header CRC-32 mismatch", base + 8) + end + local hr = Bytes.reader(b, base + 12, 20) + local nextOff, nextSize, nextCrc = hr:u64le(), hr:u64le(), hr:u32le() + local ctx: Ctx = { buf = b, base = base, limit = limit, maxBytes = maxBytes } + local a = Archive.new("7z") + if nextSize == 0 then + return a, nil -- an empty archive + end + local ho = base + 32 + nextOff + if nextOff < 0 or ho + nextSize > limit then + return nil, Err.new(Err.TRUNCATED, "header past the end of the archive", base + 12) + end + if Crc32.raw(b, ho, nextSize) ~= nextCrc then + return nil, Err.new(Err.CHECKSUM, "header CRC-32 mismatch", ho) + end + local hbuf, hoff, hlen = b, ho, nextSize + local parsed + for _ = 1, 4 do + local p, perr = Header.parse(hbuf, hoff, hlen) + if not p then + return nil, perr + end + if not p.encoded then + parsed = p + break + end + -- an encoded header: decode folder 1 of its streams, then parse again + local es = p.encoded + local f = es.folders[1] + if not f then + return nil, Err.new(Err.CORRUPT, "encoded header without a folder") + end + local hb, herr = decodeFolder(ctx, es, f) + if not hb then + return nil, herr + end + 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 = hb + hoff = 0 + hlen = buffer.len(hb) + end + if not parsed then + return nil, Err.new(Err.CORRUPT, "nested encoded headers") + end + local s: Header.Streams = parsed.streams or { packPos = 0, packSizes = {}, folders = {}, subSizes = {}, subCrcs = {} } + a.meta.folders = #s.folders + a.meta.solid = false + local cache: { [number]: buffer } = {} + local subFolder: { number }, subOffset: { number } = {}, {} + do + local si = 1 + for fi, f in s.folders do + if f.numSub > 1 then + a.meta.solid = true + end + local off = 0 + for _ = 1, f.numSub do + subFolder[si], subOffset[si] = fi, off + off += s.subSizes[si] or 0 + si += 1 + end + if off > Header.unpackSize(f) then + return nil, Err.new(Err.CORRUPT, "substreams exceed their folder") + end + end + end + local function folderData(fi: number): (buffer?, Err.Err?) + local c = cache[fi] + if c then + return c, nil + end + local f = s.folders[fi] + local d, e = decodeFolder(ctx, s, f) + if not d then + return nil, e + end + if checkCrc and f.crc and Crc32.raw(d, 0, buffer.len(d)) ~= f.crc then + return nil, Err.new(Err.CHECKSUM, "folder CRC-32 mismatch") + end + cache[fi] = d + return d, nil + end + local si = 0 + for _, file in parsed.files do + if file.anti then + continue + end + local attr = file.attributes + local isDir = file.emptyStream and not file.emptyFile + if attr and bit32.band(attr, 0x10) ~= 0 then + isDir = true + end + local mode = if attr and bit32.band(attr, 0x8000) ~= 0 then bit32.rshift(attr, 16) else nil + local e: Archive.Entry = { + name = file.name, + size = 0, + dir = isDir, + mtime = file.mtime, + attributes = attr, + mode = mode, + } + if not file.emptyStream then + si += 1 + local idx = si + local fi = subFolder[idx] + if not fi then + return nil, Err.new(Err.CORRUPT, "more files than streams") + end + local size = s.subSizes[idx] + e.size = size + e.method = folderMethod(s.folders[fi]) + if s.folders[fi].numSub == 1 then + local pk = 0 + for k = 1, #s.folders[fi].packed do + pk += s.packSizes[s.folders[fi].firstPack + k] or 0 + end + e.compressedSize = pk + end + e.crc = s.subCrcs[idx] + e.load = function(): (buffer?, Err.Err?) + local d, derr = folderData(fi) + if not d then + return nil, derr + end + local off = subOffset[idx] + if off + size > buffer.len(d) then + return nil, Err.new(Err.CORRUPT, "substream past its folder") + end + local out = buffer.create(size) + buffer.copy(out, 0, d, off, size) + local want = s.subCrcs[idx] + 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, nil + end + end + Archive.put(a, e) + end + return a, nil +end + +return SevenZip +end +__FILES["archive/7z/Header"] = function() + +-- archive/7z/Header: the 7z header parser (7zFormat.txt, LZMA SDK, Igor Pavlov, public domain): streams, files info. +local Text = __include("codecs/text/Text") +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") + +local Header = {} + +type Coder = { id: string, numIn: number, numOut: number, props: buffer } +type Folder = { + coders: { Coder }, + bindPairs: { { inIndex: number, outIndex: number } }, + packed: { number }, -- in-stream index of each packed stream + unpackSizes: { number }, -- per out stream + crc: number?, + firstPack: number, -- index of the folder's first pack stream (0-based) + numSub: number, -- substreams (files) in the folder +} +type Streams = { + packPos: number, + packSizes: { number }, + folders: { Folder }, + subSizes: { number }, -- every substream, folder by folder + subCrcs: { [number]: number }, -- 1-based substream index -> CRC +} +type File = { + name: string, + emptyStream: boolean, + emptyFile: boolean, + anti: boolean, + mtime: number?, + attributes: number?, +} +type Parsed = { streams: Streams?, files: { File }, encoded: Streams? } + +local K = { + End = 0x00, + Header = 0x01, + ArchiveProperties = 0x02, + AdditionalStreamsInfo = 0x03, + MainStreamsInfo = 0x04, + FilesInfo = 0x05, + PackInfo = 0x06, + UnPackInfo = 0x07, + SubStreamsInfo = 0x08, + Size = 0x09, + CRC = 0x0A, + Folder = 0x0B, + CodersUnPackSize = 0x0C, + NumUnPackStream = 0x0D, + EmptyStream = 0x0E, + EmptyFile = 0x0F, + Anti = 0x10, + Name = 0x11, + MTime = 0x14, + WinAttributes = 0x15, + EncodedHeader = 0x17, + Dummy = 0x19, +} +Header.K = K + +local Fail = {} + +local function bad(r: Bytes.Reader, msg: string, code: string?): never + error(setmetatable({ err = Err.new(code or Err.CORRUPT, msg, r.pos) }, Fail), 0) +end + +local function check(r: Bytes.Reader) + if r.err then + error(setmetatable({ err = r.err }, Fail), 0) + end +end + +local function byte(r: Bytes.Reader): number + local v = r:u8() + check(r) + return v +end + +-- NUMBER: the first byte's leading 1 bits count the extra (little-endian) bytes +local function number(r: Bytes.Reader): number + local first = byte(r) + local mask = 0x80 + local value = 0 + for i = 0, 7 do + if bit32.band(first, mask) == 0 then + local high = bit32.band(first, mask - 1) + return value + high * 2 ^ (8 * i) + end + value += byte(r) * 2 ^ (8 * i) + mask = bit32.rshift(mask, 1) + end + return value +end + +-- a count bounded by the bytes left (every counted item takes at least `min` bytes) +local function count(r: Bytes.Reader, min: number?): number + local n = number(r) + if n * (min or 1) > r:remaining() + 1 then + bad(r, "count " .. n .. " is larger than the header") + end + return n +end + +local function bits(r: Bytes.Reader, n: number): { boolean } + local out = table.create(n, false) + local cur, mask = 0, 0 + for i = 1, n do + if mask == 0 then + cur = byte(r) + mask = 0x80 + end + out[i] = bit32.band(cur, mask) ~= 0 + mask = bit32.rshift(mask, 1) + end + return out +end + +-- bits preceded by an "all defined" byte +local function defined(r: Bytes.Reader, n: number): { boolean } + if byte(r) ~= 0 then + return table.create(n, true) + end + return bits(r, n) +end + +local function digests(r: Bytes.Reader, n: number): { [number]: number } + local def = defined(r, n) + local out = {} + for i = 1, n do + if def[i] then + out[i] = r:u32le() + end + end + check(r) + return out +end + +local function packInfo(r: Bytes.Reader, s: Streams) + s.packPos = number(r) + local n = count(r) + while true do + local t = byte(r) + if t == K.End then + break + elseif t == K.Size then + for i = 1, n do + s.packSizes[i] = number(r) + end + elseif t == K.CRC then + digests(r, n) + else + bad(r, "unexpected property " .. t .. " in pack info") + end + end + if #s.packSizes ~= n then + bad(r, "missing pack sizes") + end +end + +local function folder(r: Bytes.Reader): Folder + local ncoders = count(r) + if ncoders == 0 or ncoders > 64 then + bad(r, "bad coder count " .. ncoders) + end + local f: Folder = { coders = {}, bindPairs = {}, packed = {}, unpackSizes = {}, crc = nil, firstPack = 0, numSub = 1 } + local totalIn, totalOut = 0, 0 + for _ = 1, ncoders do + local flags = byte(r) + if bit32.band(flags, 0x80) ~= 0 then + bad(r, "alternative coder methods", Err.UNSUPPORTED) + end + local idSize = bit32.band(flags, 0x0F) + local id = r:string(idSize) + check(r) + local nin, nout = 1, 1 + if bit32.band(flags, 0x10) ~= 0 then + nin = number(r) + nout = number(r) + if nin > 64 or nout > 64 then + bad(r, "bad coder stream count") + end + end + local props = buffer.create(0) + if bit32.band(flags, 0x20) ~= 0 then + local n = count(r) + props = r:bytes(n) + check(r) + end + table.insert(f.coders, { id = id, numIn = nin, numOut = nout, props = props }) + totalIn += nin + totalOut += nout + end + if totalOut == 0 then + bad(r, "a folder without output") + end + for _ = 1, totalOut - 1 do + local i, o = number(r), number(r) + table.insert(f.bindPairs, { inIndex = i, outIndex = o }) + end + local npacked = totalIn - (totalOut - 1) + if npacked < 1 then + bad(r, "bad bind pairs") + end + if npacked == 1 then + for i = 0, totalIn - 1 do + local bound = false + for _, bp in f.bindPairs do + if bp.inIndex == i then + bound = true + end + end + if not bound then + table.insert(f.packed, i) + break + end + end + if #f.packed ~= 1 then + bad(r, "no packed stream") + end + else + for _ = 1, npacked do + table.insert(f.packed, number(r)) + end + end + return f +end + +-- the folder's main out stream: the one no bind pair consumes +function Header.mainOut(f: Folder): number? + local total = 0 + for _, c in f.coders do + total += c.numOut + end + for o = 0, total - 1 do + local bound = false + for _, bp in f.bindPairs do + if bp.outIndex == o then + bound = true + end + end + if not bound then + return o + end + end + return nil +end + +function Header.unpackSize(f: Folder): number + local m = Header.mainOut(f) + return if m then f.unpackSizes[m + 1] or 0 else 0 +end + +local function unpackInfo(r: Bytes.Reader, s: Streams) + if byte(r) ~= K.Folder then + bad(r, "expected the folder list") + end + local n = count(r) + if byte(r) ~= 0 then + bad(r, "external folders", Err.UNSUPPORTED) + end + for i = 1, n do + s.folders[i] = folder(r) + end + if byte(r) ~= K.CodersUnPackSize then + bad(r, "expected the coder unpack sizes") + end + for _, f in s.folders do + local total = 0 + for _, c in f.coders do + total += c.numOut + end + for k = 1, total do + f.unpackSizes[k] = number(r) + end + end + while true do + local t = byte(r) + if t == K.End then + break + elseif t == K.CRC then + local d = digests(r, n) + for i = 1, n do + s.folders[i].crc = d[i] + end + else + bad(r, "unexpected property " .. t .. " in unpack info") + end + end +end + +local function subStreamsInfo(r: Bytes.Reader, s: Streams) + local t = byte(r) + if t == K.NumUnPackStream then + for _, f in s.folders do + f.numSub = count(r, 0) + end + t = byte(r) + end + local sizes = s.subSizes + if t == K.Size then + for _, f in s.folders do + if f.numSub > 0 then + local sum = 0 + for _ = 1, f.numSub - 1 do + local v = number(r) + sum += v + table.insert(sizes, v) + end + local total = Header.unpackSize(f) + if sum > total then + bad(r, "substream sizes exceed the folder") + end + table.insert(sizes, total - sum) + end + end + t = byte(r) + else + for _, f in s.folders do + if f.numSub > 1 then + bad(r, "missing substream sizes") + elseif f.numSub == 1 then + table.insert(sizes, Header.unpackSize(f)) + end + end + end + -- CRCs for the streams whose folder CRC does not already cover them + local unknown = 0 + for _, f in s.folders do + if not (f.numSub == 1 and f.crc) then + unknown += f.numSub + end + end + while t ~= K.End do + if t == K.CRC then + local d = digests(r, unknown) + local k, si = 1, 1 + for _, f in s.folders do + if f.numSub == 1 and f.crc then + s.subCrcs[si] = f.crc + si += 1 + else + for _ = 1, f.numSub do + s.subCrcs[si] = d[k] + k += 1 + si += 1 + end + end + end + else + bad(r, "unexpected property " .. t .. " in substreams info") + end + t = byte(r) + end +end + +local function streamsInfo(r: Bytes.Reader): Streams + local s: Streams = { packPos = 0, packSizes = {}, folders = {}, subSizes = {}, subCrcs = {} } + local sawSub = false + while true do + local t = byte(r) + if t == K.End then + break + elseif t == K.PackInfo then + packInfo(r, s) + elseif t == K.UnPackInfo then + unpackInfo(r, s) + elseif t == K.SubStreamsInfo then + subStreamsInfo(r, s) + sawSub = true + else + bad(r, "unexpected property " .. t .. " in streams info") + end + end + if not sawSub then + for i, f in s.folders do + f.numSub = 1 + table.insert(s.subSizes, Header.unpackSize(f)) + if f.crc then + s.subCrcs[i] = f.crc + end + end + end + local p = 0 + for _, f in s.folders do + f.firstPack = p + p += #f.packed + end + if p > #s.packSizes then + bad(r, "folders use more pack streams than exist") + end + return s +end + +local function utf16(b: buffer, o: number, n: number): string + return Text.utf16(b, o, n, false) +end + +local function filesInfo(r: Bytes.Reader): { File } + local n = count(r, 0) + if n > 1000000 then + bad(r, "too many files", Err.LIMIT) + end + local files: { File } = table.create(n) :: { File } + for i = 1, n do + files[i] = { name = "", emptyStream = false, emptyFile = false, anti = false } + end + local empties: { number } = {} + while true do + local t = byte(r) + if t == K.End then + break + end + local size = number(r) + if size > r:remaining() then + bad(r, "file property past the header") + end + local pr = r:slice(size) + check(r) + if t == K.EmptyStream then + local v = bits(pr, n) + empties = {} + for i = 1, n do + files[i].emptyStream = v[i] + if v[i] then + table.insert(empties, i) + end + end + elseif t == K.EmptyFile or t == K.Anti then + local v = bits(pr, #empties) + for k, i in empties do + if t == K.EmptyFile then + files[i].emptyFile = v[k] + else + files[i].anti = v[k] + end + end + elseif t == K.Name then + if byte(pr) ~= 0 then + bad(pr, "external names", Err.UNSUPPORTED) + end + local b = pr.buf + local p = pr.pos + for i = 1, n do + local q = p + while q + 1 < pr.limit and buffer.readu16(b, q) ~= 0 do + q += 2 + end + if q + 1 >= pr.limit then + bad(pr, "unterminated name") + end + files[i].name = utf16(b, p, q - p) + p = q + 2 + end + elseif t == K.MTime or t == K.WinAttributes then + local def = defined(pr, n) + if byte(pr) ~= 0 then + bad(pr, "external file properties", Err.UNSUPPORTED) + end + for i = 1, n do + if def[i] then + if t == K.MTime then + local ft = pr:u64le() + files[i].mtime = math.floor(ft / 1e7 - 11644473600) + else + files[i].attributes = pr:u32le() + end + end + end + check(pr) + end + -- other properties (CTime, ATime, StartPos, Dummy, ...) are skipped + end + return files +end + +local function header(r: Bytes.Reader): Parsed + local p: Parsed = { streams = nil, files = {}, encoded = nil } + while true do + local t = byte(r) + if t == K.End then + break + elseif t == K.ArchiveProperties then + while true do + local pt = byte(r) + if pt == 0 then + break + end + r:skip(number(r)) + check(r) + end + elseif t == K.AdditionalStreamsInfo then + streamsInfo(r) + elseif t == K.MainStreamsInfo then + p.streams = streamsInfo(r) + elseif t == K.FilesInfo then + p.files = filesInfo(r) + else + bad(r, "unexpected property " .. t .. " in the header") + end + end + return p +end + +function Header.parse(b: buffer, o: number, n: number): (Parsed?, Err.Err?) + local r = Bytes.reader(b, o, n) + local ok, res = pcall(function(): Parsed + local t = byte(r) + if t == K.Header then + return header(r) + elseif t == K.EncodedHeader then + return { streams = nil, files = {}, encoded = streamsInfo(r) } + end + return bad(r, "bad header type " .. t) + end) + if ok then + return res, nil + end + if type(res) == "table" and getmetatable(res :: any) == Fail then + return nil, (res :: any).err + end + error(res, 0) +end + +return Header +end +__FILES["archive/adf"] = function() + +-- archive/adf: Amiga disk images (AmigaDOS OFS / FFS, intl, dircache; ADF-FAQ by Laurent Clévy): 72-slot hash tables, +-- extension blocks / OFS chains, soft and hard links, protection bits, comments, dates since 1978-01-01, ISO-8859-1 +-- names, header checksums. Not supported: writing, DOS\6 / DOS\7, RDB hard-disk images, dircache blocks. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Archive = __include("containers/Archive") + +-- ------------------------------------------------------------------------------------------------ contract +local Adf = { + name = "adf", + category = "archive", + extensions = { "adf" }, + mime = { "application/x-amiga-disk-format" }, + deps = { "core/Err", "core/Bytes", "containers/Archive" }, + caps = { decode = true, encode = false, variants = { "ofs", "ffs" } }, +} + +type DecodeOptions = { maxEntries: number? } -- default 65536 + +-- ------------------------------------------------------------------------------------------------ constants +local BS = 512 +local HT = 72 -- hash table slots in a 512-byte block +local T_HEADER, T_DATA, T_LIST = 2, 8, 16 +local ST_ROOT, ST_USERDIR, ST_SOFTLINK, ST_LINKDIR, ST_FILE, ST_LINKFILE = 1, 2, 3, 4, -3, -4 +local EPOCH = 252460800 -- 1978-01-01 in unix seconds + +-- ------------------------------------------------------------------------------------------------ sniff +function Adf.sniff(r: Bytes.Reader): number + local n = r:size() + if n < 4 * BS or n % BS ~= 0 then + return 0 + end + local h = r:peek(4) + if string.sub(h, 1, 3) ~= "DOS" or string.byte(h, 4) > 5 then + return 0 + end + return if n == 901120 or n == 1802240 then 0.95 else 0.6 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function latin1(s: string): string + if not string.find(s, "[\128-\255]") then + return s + end + local out = table.create(#s) + for i = 1, #s do + out[i] = utf8.char(string.byte(s, i)) + end + return table.concat(out) +end + +type Disk = { b: buffer, base: number, blocks: number } + +local function u32(d: Disk, blk: number, off: number): number + local o = d.base + blk * BS + off + return buffer.readu8(d.b, o) * 16777216 + buffer.readu8(d.b, o + 1) * 65536 + buffer.readu8(d.b, o + 2) * 256 + buffer.readu8(d.b, o + 3) +end + +local function i32(d: Disk, blk: number, off: number): number + local v = u32(d, blk, off) + return if v >= 0x80000000 then v - 0x100000000 else v +end + +local function bstr(d: Disk, blk: number, off: number, max: number): string + local o = d.base + blk * BS + off + local n = math.min(buffer.readu8(d.b, o), max) + return latin1(buffer.readstring(d.b, o + 1, n)) +end + +local function checksumOk(d: Disk, blk: number): boolean + local sum = 0 + for i = 0, BS - 4, 4 do + sum = (sum + u32(d, blk, i)) % 0x100000000 + end + return sum == 0 +end + +local function date(d: Disk, blk: number, off: number): number + return (u32(d, blk, off) * 86400 + u32(d, blk, off + 4) * 60 + u32(d, blk, off + 8) // 50) + EPOCH +end + +local function dataBlocks(d: Disk, hdr: number, maxBlocks: number): ({ number }?, string?) + local out = {} + local blk = hdr + local seen: { [number]: boolean } = {} + while blk ~= 0 do + if blk < 2 or blk >= d.blocks or seen[blk] then + return nil, "bad extension block " .. blk + end + seen[blk] = true + if blk ~= hdr and (u32(d, blk, 0) ~= T_LIST or not checksumOk(d, blk)) then + return nil, "bad extension block " .. blk + end + local n = u32(d, blk, 8) + if n > HT then + return nil, "bad block count in " .. blk + end + for k = 0, n - 1 do + local db = u32(d, blk, 24 + (HT - 1 - k) * 4) + if db < 2 or db >= d.blocks then + return nil, "bad data block " .. db + end + table.insert(out, db) + if #out > maxBlocks then + return nil, "more data blocks than the disk has" + end + end + blk = u32(d, blk, BS - 8) + end + return out, nil +end + +local function readFile(d: Disk, hdr: number, ofs: boolean): (buffer?, string?) + local size = u32(d, hdr, BS - 188) + if size > d.blocks * BS then + return nil, "file larger than the disk" + end + local list, err = dataBlocks(d, hdr, d.blocks) + if not list then + return nil, err + end + local out = buffer.create(size) + local o = 0 + for _, db in list do + if o >= size then + break + end + if ofs then + if u32(d, db, 0) ~= T_DATA then + return nil, "data block " .. db .. " is not an OFS data block" + end + local n = math.min(u32(d, db, 12), 488, size - o) + buffer.copy(out, o, d.b, d.base + db * BS + 24, n) + o += n + else + local n = math.min(BS, size - o) + buffer.copy(out, o, d.b, d.base + db * BS, n) + o += n + end + end + if o < size then + return nil, "file data ends early" + end + return out, nil +end + +function Adf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + local n = r:size() + if n < 4 * BS or n % BS ~= 0 then + return nil, Err.new(Err.CORRUPT, "not a whole number of 512-byte blocks") + end + local h = r:peek(4) + if string.sub(h, 1, 3) ~= "DOS" then + return nil, Err.new(Err.CORRUPT, "no DOS boot block") + end + local flags = string.byte(h, 4) + if flags > 5 then + return nil, Err.new(Err.UNSUPPORTED, "DOS\\" .. flags .. " (long names) file systems") + end + local d: Disk = { b = r.buf, base = r.base, blocks = n // BS } + local ofs = bit32.band(flags, 1) == 0 + local root = (d.blocks - 1 + 2) // 2 + if u32(d, root, 0) ~= T_HEADER or i32(d, root, BS - 4) ~= ST_ROOT then + return nil, Err.new(Err.CORRUPT, "no root block at " .. root) + end + if not checksumOk(d, root) then + return nil, Err.new(Err.CHECKSUM, "root block checksum") + end + local a = Archive.new("adf") + a.meta.volume = bstr(d, root, BS - 80, 30) + a.meta.fs = if ofs then "ofs" else "ffs" + a.meta.intl = flags >= 2 + a.meta.dircache = flags >= 4 + a.meta.dosType = flags + a.meta.modified = date(d, root, BS - 92) + a.meta.created = date(d, root, BS - 28) + a.meta.source = { format = "adf", fs = a.meta.fs, blocks = d.blocks } + local maxEntries = o.maxEntries or 65536 + local count = 0 + local pathOf: { [number]: string } = {} + local links: { { entry: any, target: number } } = {} + local visited: { [number]: boolean } = { [root] = true } + + local function walk(dir: number, prefix: string): (boolean, Err.Err?) + for slot = 0, HT - 1 do + local blk = u32(d, dir, 24 + slot * 4) + while blk ~= 0 do + if blk < 2 or blk >= d.blocks or visited[blk] then + return false, Err.new(Err.CORRUPT, "bad or looping hash chain at block " .. blk) + end + visited[blk] = true + count += 1 + if count > maxEntries then + return false, Err.new(Err.LIMIT, "more than maxEntries entries") + end + if u32(d, blk, 0) ~= T_HEADER then + return false, Err.new(Err.CORRUPT, "block " .. blk .. " is not a header block") + end + if not checksumOk(d, blk) then + return false, Err.new(Err.CHECKSUM, "header block " .. blk .. " checksum") + end + local name = prefix .. bstr(d, blk, BS - 80, 30) + local st = i32(d, blk, BS - 4) + local e: any = { + name = name, + size = 0, + dir = false, + mtime = date(d, blk, BS - 92), + protect = u32(d, blk, BS - 192), + comment = bstr(d, blk, BS - 184, 79), + method = "store", + } + if e.comment == "" then + e.comment = nil + end + if st == ST_USERDIR then + e.name = name .. "/" + e.dir = true + pathOf[blk] = e.name + Archive.put(a, e) + local ok, err = walk(blk, e.name) + if not ok then + return false, err + end + elseif st == ST_FILE then + e.size = u32(d, blk, BS - 188) + pathOf[blk] = name + local hb = blk + e.load = function(): (buffer?, Err.Err?) + local data, err = readFile(d, hb, ofs) + if not data then + return nil, Err.new(Err.CORRUPT, tostring(err)) + end + return data, nil + end + Archive.put(a, e) + elseif st == ST_SOFTLINK then + local lo = d.base + blk * BS + 24 + local s = buffer.readstring(d.b, lo, BS - 24 - 200) + e.link = latin1(string.match(s, "^[^%z]*") or "") + e.type = "symlink" + Archive.put(a, e) + elseif st == ST_LINKFILE or st == ST_LINKDIR then + e.type = "hardlink" + e.dir = st == ST_LINKDIR + if e.dir then + e.name = name .. "/" + end + Archive.put(a, e) + table.insert(links, { entry = e, target = u32(d, blk, BS - 44) }) + end + blk = u32(d, blk, BS - 16) + end + end + return true, nil + end + local ok, err = walk(root, "") + if not ok then + return nil, err + end + -- hard links: the linked path, and a file link reads its target's data + for _, l in links do + local target = pathOf[l.target] + l.entry.hardlink = target + if target and not l.entry.dir then + local te = a._byName[target] + if te then + l.entry.size = te.size + l.entry.load = te.load + end + end + end + return a, nil +end + +return Adf +end +__FILES["archive/applesingle"] = function() + +-- archive/applesingle: AppleSingle (0x00051600) / AppleDouble (0x00051607) v1 and v2 (RFC 1740): data fork (1), +-- resource fork (2), real name (3), comment (4), dates (8; v1 file info 7), Finder info (9), as containers/MacFile. +-- Supports: read, write v2. Not supported: icon, ProDOS / MS-DOS / AFP info entries (kept in meta.entries). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Archive = __include("containers/Archive") +local MacFile = __include("containers/MacFile") + +-- ------------------------------------------------------------------------------------------------ contract +local AppleSingle = { + name = "applesingle", + category = "archive", + extensions = { "as", "applesingle", "appledouble" }, + mime = { "application/applefile", "multipart/appledouble" }, + deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/MacFile" }, + caps = { decode = true, encode = true, forks = true, variants = { "applesingle", "appledouble" } }, +} + +type DecodeOptions = { name: string?, maxBytes: number? } +type EncodeOptions = { + double: boolean?, -- default false + name: string?, +} + +-- ------------------------------------------------------------------------------------------------ constants +local SINGLE, DOUBLE = 0x00051600, 0x00051607 +local Y2K = 946684800 -- 2000-01-01 in unix seconds + +-- ------------------------------------------------------------------------------------------------ sniff +function AppleSingle.sniff(r: Bytes.Reader): number + local h = r:peek(8) + if #h < 8 then + return 0 + end + local magic = string.sub(h, 1, 4) + local ver = string.sub(h, 5, 8) + if (magic == "\0\5\22\0" or magic == "\0\5\22\7") and (ver == "\0\1\0\0" or ver == "\0\2\0\0") then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function encoder(a: any, o: any?): (buffer?, Err.Err?) + return AppleSingle.encode(a, o) +end + +local function i32(v: number): number + return if v >= 0x80000000 then v - 0x100000000 else v +end + +function AppleSingle.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + local magic, ver = r:u32be(), r:u32be() + r:skip(16) + local count = r:u16be() + if r.err then + return nil, r.err + end + if (magic ~= SINGLE and magic ~= DOUBLE) or (ver ~= 0x10000 and ver ~= 0x20000) then + return nil, Err.new(Err.CORRUPT, "not AppleSingle / AppleDouble") + end + local size = r:size() + local info: MacFile.Info = { name = "", data = buffer.create(0), rsrc = buffer.create(0), type = "\0\0\0\0", creator = "\0\0\0\0", flags = 0 } + local others = {} + local total = 0 + for _ = 1, count do + local id, off, len = r:u32be(), r:u32be(), r:u32be() + if r.err then + return nil, r.err + end + if off + len > size then + return nil, Err.new(Err.TRUNCATED, "entry " .. id .. " past the end") + end + total += len + if total > (o.maxBytes or 2 ^ 30) then + return nil, Err.new(Err.LIMIT, "entries larger than maxBytes") + end + local e = r:sub(off, len) + if id == 1 then + info.data = e:bytes(len) + elseif id == 2 then + info.rsrc = e:bytes(len) + elseif id == 3 then + info.name = MacFile.name(e:string(len)) + elseif id == 4 then + info.comment = MacFile.name(e:string(len)) + elseif id == 8 and len >= 8 then + local c, m = e:u32be(), e:u32be() + info.created = if c == 0x80000000 then nil else i32(c) + Y2K + info.modified = if m == 0x80000000 then nil else i32(m) + Y2K + elseif id == 7 and len >= 12 and ver == 0x10000 then + local c, m = e:u32be(), e:u32be() + info.created, info.modified = MacFile.fromMac(c), MacFile.fromMac(m) + elseif id == 9 and len >= 10 then + info.type, info.creator = e:string(4), e:string(4) + info.flags = e:u16be() + else + table.insert(others, { id = id, length = len }) + end + end + if info.name == "" then + local n = if type(o.name) == "string" then string.match(o.name, "([^/\\]+)$") else nil + info.name = if n then (string.match(n, "^%._(.+)$") or n) else "data" + end + local a = Archive.new("applesingle", encoder) + MacFile.put(a, info, magic == DOUBLE) + a.meta.double = magic == DOUBLE + a.meta.entries = others + a.meta.stream = magic == SINGLE and buffer.len(info.rsrc) == 0 + a.meta.source = { format = "applesingle", variant = if magic == DOUBLE then "appledouble" else "applesingle", version = ver // 0x10000 } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function AppleSingle.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local files, err = MacFile.collect(value, o.name) + if not files then + return nil, err + end + local f = files[1] + if not f then + return nil, Err.new(Err.ARG, "nothing to encode") + end + local name = MacFile.roman(f.name) + local function date(t: number?): number + if type(t) ~= "number" then + return 0x80000000 + end + return math.clamp(math.floor(t - Y2K), -0x80000000, 0x7FFFFFFF) % 0x100000000 + end + local dates = Bytes.writer(16) + dates:u32be(date(f.created or f.modified)) + dates:u32be(date(f.modified)) + dates:u32be(0x80000000) + dates:u32be(0x80000000) + local finder = Bytes.writer(32) + finder:string(f.type) + finder:string(f.creator) + finder:u16be(f.flags) + finder:string(string.rep("\0", 22)) + local entries: { { any } } = { { 3, buffer.fromstring(name) } } + if f.comment then + table.insert(entries, { 4, buffer.fromstring(MacFile.roman(f.comment)) }) + end + table.insert(entries, { 8, dates:finish() }) + table.insert(entries, { 9, finder:finish() }) + if not o.double then + table.insert(entries, { 1, f.data }) + end + if buffer.len(f.rsrc) > 0 or o.double then + table.insert(entries, { 2, f.rsrc }) + end + local w = Bytes.writer() + w:u32be(if o.double then DOUBLE else SINGLE) + w:u32be(0x20000) + w:string(string.rep("\0", 16)) + w:u16be(#entries) + local off = 26 + 12 * #entries + for _, e in entries do + w:u32be(e[1]) + w:u32be(off) + w:u32be(buffer.len(e[2])) + off += buffer.len(e[2]) + end + for _, e in entries do + w:bytes(e[2]) + end + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- new() -> an empty AppleSingle Archive: a:add(name, data); add "name.rsrc" for a resource fork +function AppleSingle.new(): any + local a = Archive.new("applesingle", encoder) + a.meta.source = { format = "applesingle" } + return a +end + +return AppleSingle +end +__FILES["archive/ar"] = function() + +-- archive/ar: Unix ar ("!<arch>\n"; ar(5), deb(5); no code ported): System V / GNU ("//" names, "/" and "/SYM64/" +-- symbols) and BSD ("#1/<len>", "__.SYMDEF"); .deb payload and control fields. Supports: read, write gnu / bsd. +-- Not supported: thin archives ("!<thin>"), writing symbol tables or .deb control data. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Deflate = __include("codecs/compress/Deflate") +local Lzma = __include("codecs/compress/Lzma") +local Zstd = __include("codecs/compress/Zstd") +local Bzip2 = __include("codecs/compress/Bzip2") +local Archive = __include("containers/Archive") +local Tar = __include("containers/Tar") + +-- ------------------------------------------------------------------------------------------------ contract +local Ar = { + name = "ar", + category = "archive", + extensions = { "a", "ar", "deb", "lib" }, + mime = { "application/x-archive", "application/vnd.debian.binary-package" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/compress/Lzma", "codecs/compress/Zstd", "codecs/compress/Bzip2", "containers/Archive", "containers/Tar" }, + caps = { decode = true, encode = true, variants = { "gnu", "bsd" }, deb = true }, +} + +type DecodeOptions = { + maxEntries: number?, -- default 1e6 + maxBytes: number?, -- .deb control.tar limit (default 2^26) +} +type EncodeOptions = { + variant: ("gnu" | "bsd")?, -- default: the source's ("bsd" for a .deb), else "gnu" +} + +-- ------------------------------------------------------------------------------------------------ constants +local MAGIC = "!<arch>\n" +local HEADER = 60 + +-- ------------------------------------------------------------------------------------------------ sniff +function Ar.sniff(r: Bytes.Reader): number + if r:peek(8) == MAGIC then + return if r:peek(13, 68) == "debian-binary" then 1 else 0.9 + end + return if r:peek(8) == "!<thin>\n" then 0.5 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function lazy(b: buffer, at: number, n: number): () -> (buffer?, Err.Err?) + return function(): (buffer?, Err.Err?) + local out = buffer.create(n) + buffer.copy(out, 0, b, at, n) + return out, nil + end +end + +local function decimal(s: string): number? + local d = string.match(s, "^%s*(%d+)%s*$") + return if d then tonumber(d) else (if string.find(s, "^%s*$") then 0 else nil) +end + +-- the System V symbol table: a big-endian count, the member offsets, then the NUL-terminated names +local function sysvSymbols(b: buffer, o: number, n: number, wide: boolean): { { name: string, offset: number } } + local out = {} + local w = if wide then 8 else 4 + if n < w then + return out + end + local count = if wide then bit32.byteswap(buffer.readu32(b, o + 4)) else bit32.byteswap(buffer.readu32(b, o)) + if count * w + w > n then + return out + end + local s = o + w + count * w + local e = o + n + for i = 0, count - 1 do + local off = bit32.byteswap(buffer.readu32(b, o + w + i * w + (w - 4))) + local q = s + while q < e and buffer.readu8(b, q) ~= 0 do + q += 1 + end + table.insert(out, { name = buffer.readstring(b, s, q - s), offset = off }) + s = q + 1 + if s > e then + break + end + end + return out +end + +-- the BSD __.SYMDEF table: a byte count of { name index, member offset } u32 pairs, the string table size, the strings +local function bsdSymbols(b: buffer, o: number, n: number): { { name: string, offset: number } } + local out = {} + if n < 8 then + return out + end + local rb = buffer.readu32(b, o) + if rb % 8 ~= 0 or rb + 8 > n then + return out + end + local strs = o + 8 + rb + local strn = math.min(buffer.readu32(b, o + 4 + rb), o + n - strs) + for i = 0, rb // 8 - 1 do + local sx = buffer.readu32(b, o + 4 + i * 8) + if sx < strn then + local q = strs + sx + while q < strs + strn and buffer.readu8(b, q) ~= 0 do + q += 1 + end + table.insert(out, { name = buffer.readstring(b, strs + sx, q - strs - sx), offset = buffer.readu32(b, o + 8 + i * 8) }) + end + end + return out +end + +-- the fields of a deb control file ("Field: value", continuation lines start with a space or tab) +local function controlFields(s: string): { [string]: string } + local out: { [string]: string } = {} + local last: string? = nil + for line in string.gmatch(s, "([^\n]*)\n?") do + local c = string.sub(line, 1, 1) + if (c == " " or c == "\t") and last then + out[last] ..= "\n" .. string.sub(line, 2) + else + local k, v = string.match(line, "^([^:%s]+):%s*(.-)%s*$") + if k then + out[k], last = v :: string, k + end + end + end + return out +end + +local function debControl(b: buffer, o: number, n: number, name: string, maxBytes: number): { [string]: string }? + local ext = string.match(name, "^control%.tar%.?(%w*)$") + local raw: buffer? + local opts: any = { maxBytes = maxBytes } + if ext == "" then + raw = buffer.create(n) + buffer.copy(raw :: buffer, 0, b, o, n) + elseif ext == "gz" then + raw = Deflate.gunzip(b, o, n) + elseif ext == "xz" then + raw = Lzma.xz(b, o, n, opts) + elseif ext == "lzma" then + raw = Lzma.alone(b, o, n, opts) + elseif ext == "zst" then + raw = Zstd.decompress(b, o, n, opts) + elseif ext == "bz2" then + raw = Bzip2.decompress(b, o, n, opts) + end + if not raw then + return nil + end + local list = Tar.read(raw) + for _, e in list or {} do + if (e.name == "./control" or e.name == "control") and e.type == "0" then + return controlFields(buffer.readstring(raw, e.offset, e.size)) + end + end + return nil +end + +local function encode(archive: any, opts: any?): (buffer?, Err.Err?) + return Ar.encode(archive, opts) +end + +function Ar.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + local maxEntries = o.maxEntries or 1e6 + local b, base, e = r.buf, r.base, r.limit + if r:peek(8) == "!<thin>\n" then + return nil, Err.new(Err.UNSUPPORTED, "thin archives (members are outside the file)", base) + end + if r:peek(8) ~= MAGIC then + return nil, Err.new(Err.CORRUPT, "bad magic", base) + end + local a = Archive.new("ar", encode) + local variant = "gnu" + local longNames: string? = nil + local symbols: { { name: string, offset: number } }? = nil + local offsets: { [number]: string } = {} + local count = 0 + local p = base + 8 + while p < e do + local c = buffer.readu8(b, p) + if (c == 0 or c == 10) and not string.find(buffer.readstring(b, p, math.min(e - p, 65536)), "[^%z\n]") then + break -- trailing padding (bsdtar fills its last 10240-byte block with zeros) + end + if p + HEADER > e then + return nil, Err.new(Err.TRUNCATED, "member header past the end", p) + end + if buffer.readstring(b, p + 58, 2) ~= "`\n" then + return nil, Err.new(Err.CORRUPT, "bad member header", p + 58) + end + local rawName = buffer.readstring(b, p, 16) + local mtime = decimal(buffer.readstring(b, p + 16, 12)) + local uid = decimal(buffer.readstring(b, p + 28, 6)) + local gid = decimal(buffer.readstring(b, p + 34, 6)) + local modeS = string.match(buffer.readstring(b, p + 40, 8), "^%s*([0-7]*)%s*$") + local size = decimal(buffer.readstring(b, p + 48, 10)) + if not (mtime and uid and gid and modeS and size) then + return nil, Err.new(Err.CORRUPT, "bad member header field", p) + end + local mode = if modeS == "" then 0 else tonumber(modeS, 8) :: number + local data = p + HEADER + if data + size > e then + return nil, Err.new(Err.TRUNCATED, "member data past the end", data) + end + local nextP = data + size + size % 2 + local name = string.gsub(rawName, " +$", "") + local dataSize = size + if string.sub(name, 1, 3) == "#1/" then + local n = tonumber(string.sub(name, 4)) + if not n or n > size then + return nil, Err.new(Err.CORRUPT, "bad BSD name length", p) + end + name = buffer.readstring(b, data, n) + local z = string.find(name, "\0", 1, true) + if z then + name = string.sub(name, 1, z - 1) + end + data += n + dataSize -= n + variant = "bsd" + elseif name == "//" then + longNames = buffer.readstring(b, data, size) + p = nextP + continue + elseif name == "/" or name == "/SYM64/" then + symbols = sysvSymbols(b, data, size, name == "/SYM64/") + p = nextP + continue + elseif string.match(name, "^/%d+$") then + local off = tonumber(string.sub(name, 2)) :: number + if not longNames or off >= #longNames then + return nil, Err.new(Err.CORRUPT, "long name outside the name table", p) + end + local s = string.match(longNames, "^([^\n]*)", off + 1) :: string + name = string.gsub(s, "/$", "") + elseif string.sub(name, -1) == "/" then + name = string.sub(name, 1, -2) + end + if name == "__.SYMDEF" or name == "__.SYMDEF SORTED" or name == "__.SYMDEF_64" or name == "__.SYMDEF_64 SORTED" then + symbols = bsdSymbols(b, data, dataSize) + variant = "bsd" + p = nextP + continue + end + if name == "" then + return nil, Err.new(Err.CORRUPT, "empty member name", p) + end + offsets[p - base] = name + count += 1 + if count > maxEntries then + return nil, Err.new(Err.LIMIT, "more than " .. maxEntries .. " entries") + end + Archive.put(a, { + name = name, + size = dataSize, + dir = false, + mtime = mtime, + uid = uid, + gid = gid, + mode = bit32.band(mode, 0xFFF), + armode = modeS, + method = "store", + load = if dataSize > 0 then lazy(b, data, dataSize) else nil, + }) + p = nextP + end + if symbols then + local out = {} + for _, s in symbols do + table.insert(out, { name = s.name, member = offsets[s.offset] }) + end + a.meta.symbols = out + end + a.meta.source = { format = "ar", variant = variant } + local list = a._entries + if list[1] and list[1].name == "debian-binary" then + a.meta.source.variant = "deb" + local v = a:read("debian-binary") + a.meta.debian = if v then (string.match(buffer.tostring(v), "^%s*(.-)%s*$")) else nil + for _, ent in list do + if string.match(ent.name, "^data%.tar") then + a.meta.payload = ent.name + elseif string.match(ent.name, "^control%.tar") then + local cb = a:read(ent.name) + if cb then + a.meta.control = debControl(cb, 0, buffer.len(cb), ent.name, o.maxBytes or 2 ^ 26) + end + end + end + end + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function pad(s: string, n: number): string + return s .. string.rep(" ", n - #s) +end + +local function header(name: string, e: any, size: number): string? + local mtime = math.floor(if type(e.mtime) == "number" then e.mtime else 0) + local uid = if type(e.uid) == "number" then e.uid else 0 + local gid = if type(e.gid) == "number" then e.gid else 0 + local mode: string = if type(e.armode) == "string" and string.find(e.armode, "^[0-7]+$") then e.armode + else string.format("%o", if type(e.mode) == "number" then bit32.band(e.mode, 0xFFF) else 0x1A4) + local f: { string } = { tostring(mtime), tostring(uid), tostring(gid), mode, tostring(size) } + local w = { 12, 6, 6, 8, 10 } + for i, s in f do + if #s > w[i] or string.find(s, "[^%d]") then + return nil + end + end + return pad(name, 16) .. pad(f[1], 12) .. pad(f[2], 6) .. pad(f[3], 6) .. pad(f[4], 8) .. pad(f[5], 10) .. "`\n" +end + +function Ar.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local items = Archive.entries(archive) + if not items then + return nil, Err.new(Err.ARG, "expected an Archive") + end + local o: EncodeOptions = opts or {} + local src = type(archive.meta) == "table" and type(archive.meta.source) == "table" and archive.meta.source + local variant = o.variant or (if src and src.format == "ar" and (src.variant == "bsd" or src.variant == "deb") then "bsd" else "gnu") + if variant ~= "gnu" and variant ~= "bsd" then + return nil, Err.new(Err.ARG, "variant must be gnu or bsd") + end + local files = {} + for _, it in items do + local e: any = it.entry + if not e.dir and (e.type == nil or e.type == "0") then + local data, err = it.read() + if not data then + return nil, err + end + table.insert(files, { e = e, data = data }) + end + end + local w = Bytes.writer(1024) + w:string(MAGIC) + -- GNU: names over 15 bytes (or holding "/" or a space) go into the "//" table + local table_: { string } = {} + local nameOf: { string } = {} + local tsize = 0 + for i, f in files do + local name: string = f.e.name + if string.find(name, "\n") or name == "" then + return nil, Err.new(Err.ARG, "entry " .. i .. ": bad name for ar") + end + if variant == "gnu" then + if #name > 15 or string.find(name, "[/ ]") then + nameOf[i] = "/" .. tsize + table.insert(table_, name .. "/\n") + tsize += #name + 2 + else + nameOf[i] = name .. "/" + end + end + end + if #table_ > 0 then + local t = table.concat(table_) + if #t % 2 == 1 then + t ..= "\n" + end + w:string(pad("//", 48) .. pad(tostring(#t), 10) .. "`\n" .. t) + end + for i, f in files do + local name: string = f.e.name + local size = buffer.len(f.data) + local prefix = "" + local field = nameOf[i] + if variant == "bsd" then + if #name > 16 or string.find(name, " ") then + field = "#1/" .. #name + prefix = name + else + field = name + end + end + local h = header(field, f.e, size + #prefix) + if not h then + return nil, Err.new(Err.ARG, "entry " .. name .. ": a field does not fit the ar header") + end + w:string(h) + w:string(prefix) + w:bytes(f.data) + if (size + #prefix) % 2 == 1 then + w:string("\n") + end + end + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +function Ar.new(): any + local a = Archive.new("ar", encode) + a.meta.source = { format = "ar", variant = "gnu" } + return a +end + +return Ar +end +__FILES["archive/arj"] = function() + +-- archive/arj: ARJ (Robert Jung; arj's technote.txt): headers CRC-32 checked, methods 0 stored, 1..3 Lzh "lh6", 4 Lzh +-- "arj4", directories (file type 3), DOS times as UTC; file CRC-32 verified. Not supported: garbled (encrypted) files, +-- multi-volume archives, chapters, writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Crc32 = __include("core/Crc32") +local Lzh = __include("codecs/compress/Lzh") +local Archive = __include("containers/Archive") + +-- ------------------------------------------------------------------------------------------------ contract +local Arj = { + name = "arj", + category = "archive", + extensions = { "arj" }, + mime = { "application/x-arj" }, + deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/compress/Lzh", "containers/Archive" }, + caps = { decode = true, encode = false, methods = { "store", "arj1", "arj2", "arj3", "arj4" } }, +} + +type DecodeOptions = { + maxBytes: number?, -- default 2^30 + maxEntries: number?, -- default 65536 +} + +-- ------------------------------------------------------------------------------------------------ constants +local OS = { [0] = "msdos", "primos", "unix", "amiga", "macos", "os2", "appleiigs", "atarist", "next", "vaxvms", "win95", "win32" } + +-- ------------------------------------------------------------------------------------------------ sniff +function Arj.sniff(r: Bytes.Reader): number + local h = r:peek(4) + if #h == 4 and string.byte(h, 1) == 0x60 and string.byte(h, 2) == 0xEA then + local size = string.byte(h, 3) + string.byte(h, 4) * 256 + return if size > 0 and size <= 2600 then 0.9 else 0 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +type Header = { fields: Bytes.Reader, name: string, comment: string, size: number, at: number, next: number } + +-- the header block at p: 60 EA, size, the basic header, its CRC-32, extended headers; nil at the end marker +local function block(r: Bytes.Reader, p: number): (Header?, string?) + local h = r:sub(p, 4) + local id1, id2, size = h:u8(), h:u8(), h:u16le() + if h.err then + return nil, "truncated header" + end + if id1 ~= 0x60 or id2 ~= 0xEA then + return nil, "bad header id" + end + if size == 0 then + return nil, nil + end + if size > 2600 then + return nil, "header too large" + end + if p + 4 + size + 4 > r:size() then + return nil, "truncated header" + end + local crc = r:sub(p + 4 + size, 4):u32le() + if Crc32.of(r.buf, r.base + p + 4, size) ~= crc then + return nil, "checksum: header CRC-32 mismatch" + end + local f = r:sub(p + 4, size) + local first = f:u8() + if first < 30 or first > size then + return nil, "bad first header size" + end + f:seek(first) + local name = f:cstring() + local comment = f:cstring() + -- extended headers + local q = p + 4 + size + 4 + local guard = 0 + while true do + local e = r:sub(q, 2) + local n = e:u16le() + if e.err then + return nil, "truncated extended header" + end + q += 2 + if n == 0 then + break + end + q += n + 4 + guard += 1 + if guard > 256 or q > r:size() then + return nil, "truncated extended header" + end + end + f:seek(0) + return { fields = f, name = name, comment = comment, size = size, at = p, next = q }, nil +end + +function Arj.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + local maxBytes = o.maxBytes or 2 ^ 30 + local maxEntries = o.maxEntries or 65536 + local main, err = block(r, 0) + if not main then + return nil, Err.from(err or "no main header", r.base) + end + local a = Archive.new("arj") + local mf = main.fields + mf:skip(1) + local version, minVersion, host = mf:u8(), mf:u8(), mf:u8() + local flags = mf:u8() + mf:skip(3) + local created = mf:u32le() + a.meta.archive = main.name + a.meta.comment = if main.comment ~= "" then main.comment else nil + a.meta.os = OS[host] + a.meta.created = Archive.fromDos(created) + a.meta.source = { format = "arj", version = version, minVersion = minVersion, flags = flags } + local p = main.next + local count = 0 + while true do + local h, herr = block(r, p) + if herr then + return nil, Err.from(herr, r.base + p) + end + if not h then + break + end + count += 1 + if count > maxEntries then + return nil, Err.new(Err.LIMIT, "more than maxEntries entries") + end + local f = h.fields + f:skip(1) + f:skip(2) + local hostOs = f:u8() + local fl = f:u8() + local method = f:u8() + local ftype = f:u8() + f:skip(1) + local stamp = f:u32le() + local packed, size, crc = f:u32le(), f:u32le(), f:u32le() + f:skip(2) + local mode = f:u16le() + local dataAt = h.next + if dataAt + packed > r:size() then + return nil, Err.new(Err.TRUNCATED, "entry " .. h.name .. " data past the end", r.base + dataAt) + end + local name = string.gsub(h.name, "\\", "/") + local isDir = ftype == 3 + if isDir and string.sub(name, -1) ~= "/" then + name ..= "/" + end + local e: any = { + name = name, + size = if isDir then 0 else size, + compressedSize = packed, + method = if method == 0 then "store" else "arj" .. method, + mtime = Archive.fromDos(stamp), + dir = isDir, + mode = mode, + os = OS[hostOs], + comment = if h.comment ~= "" then h.comment else nil, + fileType = ftype, + } + if ftype ~= 4 then -- 4: a volume label, not a file + if not isDir and size > 0 then + if size > maxBytes then + return nil, Err.new(Err.LIMIT, name .. ": larger than maxBytes") + end + local buf, at = r.buf, r.base + dataAt + e.load = function(): (buffer?, Err.Err?) + if bit32.band(fl, 0x01) ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "garbled (encrypted) entries") + end + if bit32.band(fl, 0x0C) ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "an entry split across volumes") + end + local out: buffer?, derr: string? + if method == 0 then + if packed < size then + return nil, Err.new(Err.CORRUPT, "stored entry shorter than its size") + end + out = buffer.create(size) + buffer.copy(out :: buffer, 0, buf, at, size) + elseif method >= 1 and method <= 3 then + out, derr = Lzh.decode(buf, at, packed, size, "lh6") + elseif method == 4 then + out, derr = Lzh.decode(buf, at, packed, size, "arj4") + else + return nil, Err.new(Err.UNSUPPORTED, "method " .. method) + end + if not out then + return nil, Err.from(derr) + end + if Crc32.of(out) ~= crc then + return nil, Err.new(Err.CHECKSUM, "CRC-32 mismatch") + end + return out, nil + end + end + Archive.put(a, e) + end + p = dataAt + packed + end + return a, nil +end + +return Arj +end +__FILES["archive/binhex"] = function() + +-- archive/binhex: BinHex 4.0 (.hqx; RFC 1741 notes): 6-bit text, RLE90, header and forks each with CRC-16/XMODEM, as +-- containers/MacFile; writes 64 characters a line, as BinHex 4.0 tools do. Not supported: BinHex 2 / 3 / 5, several +-- files in one .hqx (the first is read). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Crc16 = __include("core/Crc16") +local Archive = __include("containers/Archive") +local MacFile = __include("containers/MacFile") + +-- ------------------------------------------------------------------------------------------------ contract +local Binhex = { + name = "binhex", + category = "archive", + extensions = { "hqx", "hcx" }, + mime = { "application/mac-binhex40" }, + deps = { "core/Err", "core/Bytes", "core/Crc16", "containers/Archive", "containers/MacFile" }, + caps = { decode = true, encode = true, forks = true }, +} + +type DecodeOptions = { maxBytes: number? } -- default 2^30 +type EncodeOptions = { name: string? } + +-- ------------------------------------------------------------------------------------------------ constants +local ALPHABET = "!\"#$%&'()*+,-012345689@ABCDEFGHIJKLMNPQRSTUVXYZ[`abcdefhijklmpqr" +local VALUE: { [number]: number } = {} +for i = 1, 64 do + VALUE[string.byte(ALPHABET, i)] = i - 1 +end +local BANNER = "(This file must be converted with BinHex" + +-- ------------------------------------------------------------------------------------------------ sniff +function Binhex.sniff(r: Bytes.Reader): number + local head = r:peek(2048) + local at = string.find(head, BANNER, 1, true) + if not at then + return 0 + end + return if at == 1 then 1 else 0.8 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function unhex(text: string, maxBytes: number): (buffer?, string?) + local banner = string.find(text, BANNER, 1, true) + if not banner then + return nil, "no BinHex banner" + end + local start = string.find(text, ":", banner, true) + if not start then + return nil, "truncated: no data start" + end + local raw = Bytes.writer(#text) + local acc, nbits = 0, 0 + local closed = false + for i = start + 1, #text do + local c = string.byte(text, i) + if c == 58 then -- ":" + closed = true + break + end + local v = VALUE[c] + if v then + acc = bit32.bor(bit32.lshift(bit32.band(acc, 0xFFFF), 6), v) + nbits += 6 + if nbits >= 8 then + nbits -= 8 + raw:u8(bit32.band(bit32.rshift(acc, nbits), 255)) + end + elseif c ~= 10 and c ~= 13 and c ~= 9 and c ~= 32 then + return nil, string.format("bad character 0x%02x", c) + end + end + if not closed then + return nil, "truncated: no closing colon" + end + local src = raw:finish() + -- RLE90: 0x90 n repeats the previous byte n - 1 more times; 0x90 0 is a literal 0x90 + local out = Bytes.writer(buffer.len(src) * 2) + local n = buffer.len(src) + local prev = 0 + local i = 0 + while i < n do + local c = buffer.readu8(src, i) + if c == 0x90 and i + 1 < n then + local count = buffer.readu8(src, i + 1) + i += 2 + if count == 0 then + out:u8(0x90) + prev = 0x90 + else + if out:tell() + count > maxBytes then + return nil, "limit: data larger than maxBytes" + end + for _ = 2, count do + out:u8(prev) + end + end + else + out:u8(c) + prev = c + i += 1 + end + end + return out:finish(), nil +end + +local function encoder(a: any, o: any?): (buffer?, Err.Err?) + return Binhex.encode(a, o) +end + +function Binhex.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + local maxBytes = o.maxBytes or 2 ^ 30 + local b, err = unhex(buffer.readstring(r.buf, r.base, r.limit - r.base), maxBytes) + if not b then + return nil, Err.from(err) + end + local h = Bytes.reader(b) + local nameLen = h:u8() + local name = h:string(nameLen) + h:skip(1) -- version + local ftype, creator = h:string(4), h:string(4) + local flags = h:u16be() + local dlen, rlen = h:u32be(), h:u32be() + local hcrc = h:u16be() + if h.err then + return nil, h.err + end + if Crc16.ccitt(b, 0, h:tell() - 2) ~= hcrc then + return nil, Err.new(Err.CHECKSUM, "header CRC mismatch") + end + if dlen + rlen > maxBytes then + return nil, Err.new(Err.LIMIT, "forks larger than maxBytes") + end + local forks = {} + for k, len in { dlen, rlen } do + local at = h:tell() + local fork = h:bytes(len) + local crc = h:u16be() + if h.err then + return nil, h.err + end + if Crc16.ccitt(b, at, len) ~= crc then + return nil, Err.new(Err.CHECKSUM, (if k == 1 then "data" else "resource") .. " fork CRC mismatch") + end + forks[k] = fork + end + local a = Archive.new("binhex", encoder) + MacFile.put(a, { name = MacFile.name(name), data = forks[1], rsrc = forks[2], type = ftype, creator = creator, flags = flags }) + a.meta.stream = rlen == 0 + a.meta.source = { format = "binhex" } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Binhex.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local files, err = MacFile.collect(value, o.name) + if not files then + return nil, err + end + local f = files[1] + if not f then + return nil, Err.new(Err.ARG, "nothing to encode") + end + local name = MacFile.roman(f.name) + if #name < 1 or #name > 63 then + return nil, Err.new(Err.ARG, "the name must be 1..63 bytes") + end + local w = Bytes.writer() + w:u8(#name) + w:string(name) + w:u8(0) + w:string(f.type) + w:string(f.creator) + w:u16be(f.flags) + w:u32be(buffer.len(f.data)) + w:u32be(buffer.len(f.rsrc)) + local hdr = w:finish() + local body = Bytes.writer() + for _, part in { hdr, f.data, f.rsrc } do + body:bytes(part) + body:u16be(Crc16.ccitt(part, 0, buffer.len(part))) + end + local src = body:finish() + local rle = Bytes.writer(buffer.len(src) + 16) + local n = buffer.len(src) + local i = 0 + while i < n do + local c = buffer.readu8(src, i) + local run = 1 + while i + run < n and run < 255 and buffer.readu8(src, i + run) == c do + run += 1 + end + if c == 0x90 then + rle:u8(0x90) + rle:u8(0) + run = 1 + else + rle:u8(c) + if run >= 3 then + rle:u8(0x90) + rle:u8(run) + else + run = 1 + end + end + i += run + end + local bytes = rle:finish() + -- 6-bit characters, 64 to a line (the first line includes the colon) + local chars = { ":" } + local col = 1 + local acc, nbits = 0, 0 + local function put(v: number) + table.insert(chars, string.sub(ALPHABET, v + 1, v + 1)) + col += 1 + if col == 64 then + table.insert(chars, "\n") + col = 0 + end + end + for k = 0, buffer.len(bytes) - 1 do + acc = bit32.bor(bit32.lshift(bit32.band(acc, 0xFF), 8), buffer.readu8(bytes, k)) + nbits += 8 + while nbits >= 6 do + nbits -= 6 + put(bit32.band(bit32.rshift(acc, nbits), 63)) + end + end + if nbits > 0 then + put(bit32.band(bit32.lshift(acc, 6 - nbits), 63)) + end + table.insert(chars, ":\n") + return buffer.fromstring("(This file must be converted with BinHex 4.0)\n" .. table.concat(chars)), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +function Binhex.new(): any + local a = Archive.new("binhex", encoder) + a.meta.source = { format = "binhex" } + return a +end + +return Binhex +end +__FILES["archive/br"] = function() + +-- archive/br: a Brotli (RFC 7932) stream as a single-entry archive (codecs/compress/Brotli). Supports: read. +-- Not supported: write. No magic number: sniff accepts only data that decodes cleanly, at a low confidence. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Brotli = __include("codecs/compress/Brotli") +local Archive = __include("containers/Archive") + +-- ------------------------------------------------------------------------------------------------ contract +local Br = { + name = "br", + category = "archive", + extensions = { "br" }, + mime = { "application/x-brotli" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Brotli", "containers/Archive" }, + caps = { decode = true, encode = false, stream = true }, +} + +type DecodeOptions = { + name: string?, + maxBytes: number?, -- default 2^30 +} + +-- ------------------------------------------------------------------------------------------------ constants +local SNIFF_WHOLE = 262144 -- streams up to this size are decoded whole by sniff +local SNIFF_PREFIX = 65536 + +-- ------------------------------------------------------------------------------------------------ sniff +function Br.sniff(r: Bytes.Reader): number + local n = r:remaining() + if n == 0 then + return 0 + end + if n <= SNIFF_WHOLE then + local out, consumed = Brotli.decompress(r.buf, r.pos, n, { maxBytes = 2 ^ 26 }) + if out and consumed == r.limit then + return if buffer.len(out) > 0 then 0.3 else 0.05 + end + return 0 + end + local _, err = Brotli.decompress(r.buf, r.pos, SNIFF_PREFIX, { maxBytes = 2 ^ 22 }) + if err and (err.code == Err.TRUNCATED or err.code == Err.LIMIT) then + return 0.05 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Br.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local n = r:remaining() + local out, consumed = Brotli.decompress(r.buf, r.pos, n, { maxBytes = opts and opts.maxBytes }) + if not out then + local e: Err.Err = consumed + e.message = string.gsub(e.message, "^brotli: ", "") + return nil, e + end + local a = Archive.new("br") + a.meta.stream = true + a.meta.compressedSize = consumed - r.pos + Archive.put(a, { + name = Archive.streamName(opts, Br.extensions), + size = buffer.len(out), + compressedSize = consumed - r.pos, + method = "brotli", + dir = false, + data = out, + }) + return a, nil +end + +return Br +end +__FILES["archive/bz2"] = function() + +-- archive/bz2: a .bz2 file as a single-stream archive of one entry (codecs/compress/Bzip2). Supports: read, +-- concatenated streams joined as bzip2 -d does. Not supported: writing, randomised blocks (bzip2 0.9.0 and older). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Archive = __include("containers/Archive") +local Bzip2 = __include("codecs/compress/Bzip2") + +-- ------------------------------------------------------------------------------------------------ contract +local Bz2 = { + name = "bz2", + category = "archive", + extensions = { "bz2", "tbz2", "tbz" }, + mime = { "application/x-bzip2" }, + deps = { "core/Err", "core/Bytes", "containers/Archive", "codecs/compress/Bzip2" }, + caps = { decode = true, encode = false, stream = true }, +} + +type DecodeOptions = { + maxBytes: number?, -- default 2^30 + name: string?, +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Bz2.sniff(r: Bytes.Reader): number + local h = r:peek(10) + if #h < 10 or string.sub(h, 1, 3) ~= "BZh" then + return 0 + end + local lv = string.byte(h, 4) + if lv < 0x31 or lv > 0x39 then + return 0 + end + local magic = string.sub(h, 5, 10) + if magic == "\x31\x41\x59\x26\x53\x59" or magic == "\x17\x72\x45\x38\x50\x90" then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Bz2.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local out, consumed = Bzip2.decompress(r.buf, r.base, r.limit - r.base, { maxBytes = opts and opts.maxBytes }) + if not out then + return nil, consumed + end + local a = Archive.new("bz2") + a.meta.stream = true + Archive.put(a, { + name = Archive.streamName(opts, Bz2.extensions), + size = buffer.len(out), + compressedSize = consumed - r.base, + method = "bzip2", + dir = false, + data = out, + }) + return a, nil +end + +return Bz2 +end +__FILES["archive/cab"] = function() + +-- archive/cab: Microsoft Cabinet (MSCF 1.3, [MS-CAB]): folders none / MSZIP ("CK" + raw deflate, dictionary carried +-- over between blocks) / LZX (2^15..2^21) / Quantum (2^10..2^21), DOS times as UTC, checksums verified; writes one +-- stored or MSZIP folder. Not supported: files spanning cabinets of a set, signed / self-extracting stubs. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Deflate = __include("codecs/compress/Deflate") +local Lzx = __include("codecs/compress/Lzx") +local Quantum = __include("codecs/compress/Quantum") +local Archive = __include("containers/Archive") +local Sum = __include("archive/cab/Sum") + +-- ------------------------------------------------------------------------------------------------ contract +local Cab = { + name = "cab", + category = "archive", + extensions = { "cab" }, + mime = { "application/vnd.ms-cab-compressed" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/compress/Lzx", "codecs/compress/Quantum", "containers/Archive" }, + caps = { decode = true, encode = true, methods = { "store", "mszip", "lzx", "quantum" } }, +} + +type DecodeOptions = { + maxBytes: number?, -- default 2^30 + maxEntries: number?, -- default 65535 + verify: boolean?, -- default true +} +type EncodeOptions = { + compression: ("mszip" | "none")?, -- default "mszip" + level: number?, -- 0..9 (default 6) + setId: number?, -- default 0 +} + +-- ------------------------------------------------------------------------------------------------ constants +local FLAG_PREV, FLAG_NEXT, FLAG_RESERVE = 0x0001, 0x0002, 0x0004 +local ATTR_UTF8 = 0x80 +local METHOD = { [0] = "store", "mszip", "quantum", "lzx" } +local BLOCK = 32768 + +-- ------------------------------------------------------------------------------------------------ sniff +function Cab.sniff(r: Bytes.Reader): number + if r:peek(8) == "MSCF\0\0\0\0" then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +type Folder = { + dataAt: number, -- offset of the first CFDATA (relative to the reader) + blocks: number, + type: number, -- typeCompress + index: number, +} +type Block = { at: number, len: number, size: number } + +-- a block with cbUncomp 0 runs into the next cabinet +local function blocks(r: Bytes.Reader, f: Folder, dataReserve: number, verify: boolean, maxBytes: number): ({ Block }?, any, boolean?) + local list: { Block } = {} + local p = f.dataAt + local total = 0 + for i = 1, f.blocks do + local h = r:sub(p, 8) + local csum, cbData, cbUncomp = h:u32le(), h:u16le(), h:u16le() + if h.err then + return nil, Err.new(Err.TRUNCATED, "data block header past the end", r.base + p) + end + local at = p + 8 + dataReserve + if at + cbData > r:size() then + return nil, Err.new(Err.TRUNCATED, "data block past the end", r.base + p) + end + if cbUncomp == 0 then + return list, total, true + end + if verify and csum ~= 0 and Sum.block(r.buf, r.base + at, cbData, cbUncomp) ~= csum then + return nil, Err.new(Err.CHECKSUM, "data block " .. i .. " checksum mismatch", r.base + p) + end + total += cbUncomp + if total > maxBytes then + return nil, Err.new(Err.LIMIT, "folder larger than maxBytes") + end + table.insert(list, { at = r.base + at, len = cbData, size = cbUncomp }) + p = at + cbData + end + return list, total, false +end + +local function inflateFolder(buf: buffer, list: { Block }, total: number, typ: number): (buffer?, Err.Err?) + local method = bit32.band(typ, 15) + local out = buffer.create(total) + if method == 0 then + local o = 0 + for _, b in list do + if b.len ~= b.size then + return nil, Err.new(Err.CORRUPT, "stored block with different sizes", b.at) + end + buffer.copy(out, o, buf, b.at, b.len) + o += b.len + end + return out, nil + elseif method == 1 then + local spans: { { offset: number, length: number, size: number } } = {} + for _, b in list do + table.insert(spans, { offset = b.at, length = b.len, size = b.size }) + end + return Deflate.mszip(buf, spans) + elseif method == 3 then + local bits = bit32.band(bit32.rshift(typ, 8), 31) + local n = 0 + for _, b in list do + n += b.len + end + local src = buffer.create(n) + local o = 0 + for _, b in list do + buffer.copy(src, o, buf, b.at, b.len) + o += b.len + end + local res, err = Lzx.decode(src, 0, n, total, bits) + if not res then + return nil, Err.from(err) + end + return res, nil + elseif method == 2 then + local res, err = Quantum.decode(buf, list, total, bit32.band(bit32.rshift(typ, 8), 31)) + if not res then + return nil, Err.from(err) + end + return res, nil + end + return nil, Err.new(Err.UNSUPPORTED, "compression type " .. method) +end + +local function encode(archive: any, opts: any?): (buffer?, Err.Err?) + return Cab.encode(archive, opts) +end + +function Cab.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + local maxBytes = o.maxBytes or 2 ^ 30 + local maxEntries = o.maxEntries or 65535 + local verify = o.verify ~= false + if not r:match("MSCF") then + return nil, Err.new(Err.CORRUPT, "no MSCF signature", r.base) + end + r:skip(4) + local cbCabinet = r:u32le() + r:skip(4) + local coffFiles = r:u32le() + r:skip(4) + local minor, major = r:u8(), r:u8() + local cFolders, cFiles, flags = r:u16le(), r:u16le(), r:u16le() + local setId, iCabinet = r:u16le(), r:u16le() + local headerReserve, folderReserve, dataReserve = 0, 0, 0 + if bit32.band(flags, FLAG_RESERVE) ~= 0 then + headerReserve, folderReserve, dataReserve = r:u16le(), r:u8(), r:u8() + end + local a = Archive.new("cab", encode) + local meta: any = a.meta + if headerReserve > 0 then + meta.reserve = r:bytes(headerReserve) + end + if bit32.band(flags, FLAG_PREV) ~= 0 then + meta.prevCabinet, meta.prevDisk = r:cstring(256), r:cstring(256) + end + if bit32.band(flags, FLAG_NEXT) ~= 0 then + meta.nextCabinet, meta.nextDisk = r:cstring(256), r:cstring(256) + end + if r.err then + return nil, r.err + end + if major ~= 1 then + return nil, Err.new(Err.UNSUPPORTED, "cabinet version " .. major .. "." .. minor) + end + meta.setId, meta.cabinet = setId, iCabinet + meta.source = { + format = "cab", + version = major .. "." .. minor, + size = cbCabinet, + flags = flags, + reserve = { header = headerReserve, folder = folderReserve, data = dataReserve }, + } + local folders: { Folder } = {} + local methods = {} + for i = 1, cFolders do + local dataAt, nblocks, typ = r:u32le(), r:u16le(), r:u16le() + r:skip(folderReserve) + if r.err then + return nil, r.err + end + folders[i] = { dataAt = dataAt, blocks = nblocks, type = typ, index = i } + local m = METHOD[bit32.band(typ, 15)] + methods[i] = { + method = m or ("type " .. bit32.band(typ, 15)), + window = if m == "lzx" or m == "quantum" then bit32.band(bit32.rshift(typ, 8), 31) else nil, + level = if m == "quantum" then bit32.band(bit32.rshift(typ, 4), 15) else nil, + blocks = nblocks, + } + end + meta.folders = methods + if cFiles == 0 or cFolders == 0 then + return nil, Err.new(Err.CORRUPT, "a cabinet without files or folders") + end + if cFiles > maxEntries then + return nil, Err.new(Err.LIMIT, "more than maxEntries files") + end + local cachedIndex, cachedData, cachedRuns = 0, nil :: buffer?, false + local function folderData(f: Folder): (buffer?, Err.Err?, boolean?) + if cachedIndex == f.index then + return cachedData, nil, cachedRuns + end + local list, total, runs = blocks(r, f, dataReserve, verify, maxBytes) + if not list then + return nil, total, false + end + local data, err = inflateFolder(r.buf, list, total, f.type) + if not data then + return nil, err, false + end + cachedIndex, cachedData, cachedRuns = f.index, data, runs == true + return data, nil, runs + end + local fr = r:sub(coffFiles) + for _ = 1, cFiles do + local size, offset, iFolder = fr:u32le(), fr:u32le(), fr:u16le() + local date, time, attribs = fr:u16le(), fr:u16le(), fr:u16le() + local raw = fr:cstring(65536) + if fr.err then + return nil, fr.err + end + local name = string.gsub(raw, "\\", "/") + local spanned: string? = nil + local folder: Folder? + if iFolder == 0xFFFD or iFolder == 0xFFFF then + spanned = "a file continued from the previous cabinet" + folder = folders[1] + elseif iFolder == 0xFFFE then + spanned = "a file continued in the next cabinet" + folder = folders[#folders] + else + folder = folders[iFolder + 1] + if iFolder == 0 and bit32.band(flags, FLAG_PREV) ~= 0 then + spanned = "a folder continued from the previous cabinet" + end + end + if not folder then + return nil, Err.new(Err.CORRUPT, "file " .. name .. " in a missing folder " .. iFolder) + end + local fo = folder :: Folder + if size > maxBytes then + return nil, Err.new(Err.LIMIT, name .. ": larger than maxBytes") + end + local e: any = { + name = name, + size = size, + method = METHOD[bit32.band(fo.type, 15)] or "unknown", + mtime = Archive.fromDos(date * 65536 + time), + dir = false, + attributes = bit32.band(attribs, 0xFF7F), + utf8 = bit32.band(attribs, ATTR_UTF8) ~= 0, + folder = fo.index, + offset = offset, + readonly = bit32.band(attribs, 0x01) ~= 0, + executable = bit32.band(attribs, 0x40) ~= 0, + } + if spanned then + e.spanned = true + end + if size > 0 or spanned then + e.load = function(): (buffer?, Err.Err?) + if spanned then + return nil, Err.new(Err.UNSUPPORTED, spanned :: string) + end + local data, err, runs = folderData(fo) + if not data then + return nil, err + end + if offset + size > buffer.len(data) then + if runs then + return nil, Err.new(Err.UNSUPPORTED, "a file continued in the next cabinet") + end + return nil, Err.new(Err.CORRUPT, "file past the end of its folder") + end + local out = buffer.create(size) + buffer.copy(out, 0, data, offset, size) + return out, nil + end + end + Archive.put(a, e) + end + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Cab.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local compression = o.compression or "mszip" + if compression ~= "mszip" and compression ~= "none" then + return nil, Err.new(Err.ARG, "compression must be \"mszip\" or \"none\"") + end + local level = o.level or 6 + 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") + end + local files, ferr = Archive.files(archive) + if not files then + return nil, ferr + end + if #files == 0 then + return nil, Err.new(Err.ARG, "a cabinet needs at least one file") + end + if #files > 65535 then + return nil, Err.new(Err.ARG, "more than 65535 files") + end + local total = 0 + for _, f in files do + total += buffer.len(f.data) + end + if total > 0x7FFF8000 then + return nil, Err.new(Err.ARG, "more than 2 GB of data") + end + local folder = buffer.create(total) + local p = 0 + for _, f in files do + buffer.copy(folder, p, f.data, 0, buffer.len(f.data)) + p += buffer.len(f.data) + end + local data = Bytes.writer(total // 2 + 64) + local nblocks = 0 + local s = 0 + while s < total do + local n = math.min(BLOCK, total - s) + local chunk = buffer.create(n) + buffer.copy(chunk, 0, folder, s, n) + local payload: buffer + if compression == "mszip" then + local z, zerr = Deflate.compress(chunk, { level = level }) + if not z then + return nil, zerr + end + payload = buffer.create(buffer.len(z) + 2) + buffer.writeu16(payload, 0, 0x4B43) + buffer.copy(payload, 2, z, 0, buffer.len(z)) + else + payload = chunk + end + local len = buffer.len(payload) + data:u32le(Sum.block(payload, 0, len, n)) + data:u16le(len) + data:u16le(n) + data:bytes(payload) + nblocks += 1 + s += n + end + local blob = data:finish() + local table_ = Bytes.writer(64 + #files * 32) + local offset = 0 + for _, f in files do + local e: any = f.entry + local name = string.gsub(f.name, "/", "\\") + local attribs = if type(e.attributes) == "number" then bit32.band(e.attributes, 0x7F) else 0x20 + if string.find(name, "[\128-\255]") then + attribs = bit32.bor(attribs, ATTR_UTF8) + end + local stamp = Archive.toDos(e.mtime) + table_:u32le(buffer.len(f.data)) + table_:u32le(offset) + table_:u16le(0) + table_:u16le(stamp // 65536) + table_:u16le(stamp % 65536) + table_:u16le(attribs) + table_:cstring(name) + offset += buffer.len(f.data) + end + local fileTable = table_:finish() + local nfolders = 1 + local coffFiles = 36 + 8 * nfolders + local dataAt = coffFiles + buffer.len(fileTable) + local size = dataAt + buffer.len(blob) + local w = Bytes.writer(size) + w:string("MSCF") + w:u32le(0) + w:u32le(size) + w:u32le(0) + w:u32le(coffFiles) + w:u32le(0) + w:u8(3) + w:u8(1) + w:u16le(nfolders) + w:u16le(#files) + w:u16le(0) + w:u16le(o.setId or 0) + w:u16le(0) + w:u32le(dataAt) + w:u16le(nblocks) + w:u16le(if compression == "mszip" then 1 else 0) + w:bytes(fileTable) + w:bytes(blob) + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +function Cab.new(): any + local a = Archive.new("cab", encode) + a.meta.source = { format = "cab" } + return a +end + +return Cab +end +__FILES["archive/cab/Sum"] = @native function() + + + +-- archive/cab/Sum: the CFDATA.csum checksum ([MS-CAB] 2.4): XOR of LE u32 words, the last 1..3 bytes packed most +-- significant first, then the cbData / cbUncomp word. + +local readu8, readu32, blen = buffer.readu8, buffer.readu32, buffer.len +local bxor, bor, lshift = bit32.bxor, bit32.bor, bit32.lshift + +local Sum = {} + +@native function Sum.of(buf: buffer, off: number, len: number, seed: number): number + if off < 0 or len <= 0 or off + len > blen(buf) then + return seed + end + local s = seed + local p = off + local stop = off + len - len % 4 + while p < stop do + s = bxor(s, readu32(buf, p)) + p += 4 + end + local rem = len % 4 + local tail = 0 + if rem == 3 then + tail = bor(lshift(readu8(buf, p), 16), lshift(readu8(buf, p + 1), 8), readu8(buf, p + 2)) + elseif rem == 2 then + tail = bor(lshift(readu8(buf, p), 8), readu8(buf, p + 1)) + elseif rem == 1 then + tail = readu8(buf, p) + end + return bxor(s, tail) +end + +@native function Sum.block(buf: buffer, dataAt: number, cbData: number, cbUncomp: number): number + return bxor(Sum.of(buf, dataAt, cbData, 0), cbData + cbUncomp * 65536) +end + +return Sum +end +__FILES["archive/cpio"] = function() + +-- archive/cpio: cpio (newc, crc, odc, old binary in both byte orders; containers/Cpio). Supports: read (lazy), write as +-- newc / crc / odc; tar hard links ("1") share an inode with their target. Not supported: uname / gname (dropped). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Archive = __include("containers/Archive") +local Cpio = __include("containers/Cpio") + +-- ------------------------------------------------------------------------------------------------ contract +local CpioFormat = { + name = "cpio", + category = "archive", + extensions = { "cpio" }, + mime = { "application/x-cpio" }, + deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Cpio" }, + caps = { decode = true, encode = true, variants = { "newc", "crc", "odc", "bin" } }, +} + +type DecodeOptions = { + maxEntries: number?, -- default 1e6 + verify: boolean?, -- default true +} +type EncodeOptions = { + variant: ("newc" | "crc" | "odc")?, -- default: the source archive's (old binary: newc), else "newc" + format: string?, -- any other value (the api's "cpio") means the variant default + block: number?, -- default 512, as GNU cpio; 1 = none +} + +-- ------------------------------------------------------------------------------------------------ sniff +function CpioFormat.sniff(r: Bytes.Reader): number + local m = r:peek(6) + if m == "070701" or m == "070702" or m == "070707" then + return 1 + end + local b2 = r:peek(2) + if (b2 == "\199\113" or b2 == "\113\199") and r:remaining() >= 26 then + return 0.5 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function lazy(b: buffer, at: number, n: number): () -> (buffer?, Err.Err?) + return function(): (buffer?, Err.Err?) + local out = buffer.create(n) + buffer.copy(out, 0, b, at, n) + return out, nil + end +end + +local function encode(archive: any, opts: any?): (buffer?, Err.Err?) + return CpioFormat.encode(archive, opts) +end + +function CpioFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local list, info = Cpio.read(r.buf, r.base, r.limit - r.base, opts) + if not list then + return nil, info + end + local a = Archive.new("cpio", encode) + for _, e in list do + local data = e.type == "0" and e.size > 0 + Archive.put(a, { + name = e.name, + size = if data then e.size else 0, + dir = e.dir, + mtime = e.mtime, + mode = bit32.band(e.mode, 0xFFF), + uid = e.uid, + gid = e.gid, + type = e.type, + link = e.link, + hardlink = e.hardlink, + nlink = e.nlink, + ino = e.ino, + devmajor = e.devmajor, + devminor = e.devminor, + rdevmajor = e.rdevmajor, + rdevminor = e.rdevminor, + method = "store", + load = if data then lazy(r.buf, e.offset, e.size) else nil, + }) + end + a.meta.source = { format = "cpio", variant = info.format } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function num(v: any): number? + return if type(v) == "number" then v else nil +end + +function CpioFormat.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local items = Archive.entries(archive) + if not items then + return nil, Err.new(Err.ARG, "expected an Archive") + end + local index: { [string]: number } = {} + for i, it in items do + index[it.entry.name] = index[it.entry.name] or i + end + -- tar hard links ("1"): the same inode as their target, which counts the links + local links: { [number]: number } = {} + local target: { [number]: number } = {} + for i, it in items do + local e: any = it.entry + if e.type == "1" and type(e.link) == "string" and index[e.link] then + local t = index[e.link] + target[i] = t + links[t] = (links[t] or 1) + 1 + end + end + local list: { Cpio.WriteEntry } = {} + for i, it in items do + local e: any = it.entry + local typ = if type(e.type) == "string" and Cpio.TYPE_MODE[e.type] then e.type elseif e.dir then "5" else "0" + local src = target[i] + local ino, nlink = num(e.ino), num(e.nlink) + if src then + typ, ino, nlink = "0", src, links[src] + elseif links[i] then + ino, nlink = i, links[i] + end + local data: buffer? = nil + if typ == "0" then + local b, err = (items[src or i] :: any).read() + if not b then + return nil, err + end + data = b + end + local mode = num(e.mode) + table.insert(list, { + name = e.name, + data = data, + type = typ, + link = if type(e.link) == "string" and typ == "2" then e.link else nil, + mode = if mode then bit32.band(mode, 0xFFF) else nil, + uid = num(e.uid), + gid = num(e.gid), + nlink = nlink, + mtime = num(e.mtime), + ino = ino, + devmajor = num(e.devmajor), + devminor = num(e.devminor), + rdevmajor = num(e.rdevmajor), + rdevminor = num(e.rdevminor), + }) + end + local o: any = opts or {} + local src = type(archive.meta) == "table" and type(archive.meta.source) == "table" and archive.meta.source + local own = if src and src.format == "cpio" and (src.variant == "crc" or src.variant == "odc") then src.variant else "newc" + local variant = o.variant or (if o.format == "crc" or o.format == "odc" or o.format == "newc" then o.format else own) + return Cpio.write(list, { format = variant, block = o.block }) +end + +-- ------------------------------------------------------------------------------------------------ extras +function CpioFormat.new(): any + local a = Archive.new("cpio", encode) + a.meta.source = { format = "cpio" } + return a +end + +return CpioFormat +end +__FILES["archive/d64"] = function() + +-- archive/d64: Commodore D64 (1541: 35 / 40 / 42 tracks, error block), D71, D81 (Peter Schepers' notes); PETSCII names +-- as VICE's c1541 (0x41..0x5A -> a..z, 0xC1..0xDA / 0x61..0x7A -> A..Z, else U+E0xx); writes with interleave 10 as +-- CBM DOS (not a real drive's sectors). Not supported: GEOS VLIR files (first chain), 1581 partition contents. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Archive = __include("containers/Archive") + +-- ------------------------------------------------------------------------------------------------ contract +local D64 = { + name = "d64", + category = "archive", + extensions = { "d64", "d71", "d81" }, + mime = { "application/x-d64" }, + deps = { "core/Err", "core/Bytes", "containers/Archive" }, + caps = { decode = true, encode = true, variants = { "d64", "d71", "d81" } }, +} + +type DecodeOptions = { maxEntries: number? } -- default 4096 +type EncodeOptions = { + variant: ("d64" | "d71" | "d81")?, -- default: the variant read, else "d64" + disk: string?, -- default "rosetta" / the name read + id: string?, -- default "fl" +} + +-- ------------------------------------------------------------------------------------------------ constants +local TYPES = { [0] = "del", "seq", "prg", "usr", "rel", "cbm", "dir" } +local TYPE_CODE: { [string]: number } = { del = 0, seq = 1, prg = 2, usr = 3, rel = 4 } + +type Geometry = { kind: string, tracks: number, offsets: { number }, spt: { number }, dirTrack: number, total: number } + +local function geometry(kind: string, tracks: number): Geometry + local offsets, spt = {}, {} + local o = 0 + for t = 1, tracks do + local n + if kind == "d81" then + n = 40 + else + local s = if kind == "d71" and t > 35 then t - 35 else t + n = if s <= 17 then 21 elseif s <= 24 then 19 elseif s <= 30 then 18 else 17 + end + offsets[t], spt[t] = o, n + o += n * 256 + end + return { kind = kind, tracks = tracks, offsets = offsets, spt = spt, dirTrack = if kind == "d81" then 40 else 18, total = o } +end + +-- image sizes -> geometry (sizes with the error-info block appended too) +local function detect(len: number): Geometry? + for _, g in { { "d64", 35 }, { "d64", 40 }, { "d64", 42 }, { "d71", 70 }, { "d81", 80 } } :: { { any } } do + local geo = geometry(g[1] :: string, g[2] :: number) + local sectors = geo.total // 256 + if len == geo.total or (g[1] ~= "d81" and len == geo.total + sectors) then + return geo + end + end + return nil +end + +-- ------------------------------------------------------------------------------------------------ sniff +function D64.sniff(r: Bytes.Reader): number + local geo = detect(r:size()) + if not geo then + return 0 + end + -- the BAM / header sector: dir track link and DOS version byte + local h = r:sub(geo.offsets[geo.dirTrack], 256) + local t, s, v = h:u8(), h:u8(), h:u8() + if geo.kind == "d81" then + return if t == 40 and s == 3 and v == 0x44 then 0.9 else 0.3 + end + return if t == 18 and s == 1 and (v == 0x41 or v == 0) then 0.9 else 0.3 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function petscii(raw: string): string + local out = table.create(#raw) + for i = 1, #raw do + local c = string.byte(raw, i) + if c >= 0x41 and c <= 0x5A then + out[i] = string.char(c + 32) + elseif c >= 0xC1 and c <= 0xDA then + out[i] = string.char(c - 0x80) + elseif c >= 0x61 and c <= 0x7A then + out[i] = string.char(c - 32) + elseif c >= 0x20 and c <= 0x40 and c ~= 0x2F then + out[i] = string.char(c) + else + out[i] = utf8.char(0xE000 + c) + end + end + return table.concat(out) +end + +local function toPetscii(name: string): string + local out = {} + if not utf8.len(name) then + return string.sub(name, 1, 16) + end + for _, c in utf8.codes(name) do + local b + if c >= 0x61 and c <= 0x7A then + b = c - 32 + elseif c >= 0x41 and c <= 0x5A then + b = c + 0x80 + elseif c >= 0xE000 and c <= 0xE0FF then + b = c - 0xE000 + elseif c >= 0x20 and c <= 0x40 and c ~= 0x2F then + b = c + else + b = 0x3F + end + table.insert(out, string.char(b)) + end + return string.sub(table.concat(out), 1, 16) +end + +local function encoder(a: any, o: any?): (buffer?, Err.Err?) + return D64.encode(a, o) +end + +local function chain(b: buffer, base: number, geo: Geometry, t: number, s: number): (buffer?, string?) + local w = Bytes.writer() + local seen: { [number]: boolean } = {} + while t ~= 0 do + if t < 1 or t > geo.tracks or s >= geo.spt[t] then + return nil, string.format("chain leaves the disk at %d/%d", t, s) + end + local key = t * 256 + s + if seen[key] then + return nil, string.format("chain loops at %d/%d", t, s) + end + seen[key] = true + local o = base + geo.offsets[t] + s * 256 + local nt, ns = buffer.readu8(b, o), buffer.readu8(b, o + 1) + if nt == 0 then + local last = math.max(ns, 1) + if last >= 2 then + w:bytes(buffer.fromstring(buffer.readstring(b, o + 2, last - 1))) + end + else + w:bytes(buffer.fromstring(buffer.readstring(b, o + 2, 254))) + end + t, s = nt, ns + end + return w:finish(), nil +end + +function D64.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + local geo = detect(r:size()) + if not geo then + return nil, Err.new(Err.CORRUPT, "not a D64 / D71 / D81 image size (" .. r:size() .. " bytes)") + end + local b, base = r.buf, r.base + local hdr = base + geo.offsets[geo.dirTrack] + local nameAt, idAt = if geo.kind == "d81" then 0x04 else 0x90, if geo.kind == "d81" then 0x16 else 0xA2 + local diskRaw = buffer.readstring(b, hdr + nameAt, 16) + local a = Archive.new("d64", encoder) + a.meta.disk = petscii((string.gsub(diskRaw, "\160+$", ""))) + a.meta.id = petscii(buffer.readstring(b, hdr + idAt, 2)) + a.meta.variant = geo.kind + a.meta.tracks = geo.tracks + a.meta.errorInfo = r:size() ~= geo.total + a.meta.source = { format = "d64", variant = geo.kind, tracks = geo.tracks } + local t, s = buffer.readu8(b, hdr), buffer.readu8(b, hdr + 1) + local seen: { [number]: boolean } = {} + local count = 0 + local maxEntries = o.maxEntries or 4096 + while t ~= 0 do + if t < 1 or t > geo.tracks or s >= geo.spt[t] or seen[t * 256 + s] then + return nil, Err.new(Err.CORRUPT, string.format("bad directory sector %d/%d", t, s)) + end + seen[t * 256 + s] = true + local so = base + geo.offsets[t] + s * 256 + for k = 0, 7 do + local e = so + k * 32 + local ft = buffer.readu8(b, e + 2) + local kind = bit32.band(ft, 15) + if ft ~= 0 and kind ~= 0 then + count += 1 + if count > maxEntries then + return nil, Err.new(Err.LIMIT, "more than maxEntries directory entries") + end + local raw = buffer.readstring(b, e + 5, 16) + local name = petscii((string.gsub(raw, "\160+$", ""))) + local base_name, n = name, 2 + while a._byName[name] do + name = base_name .. ";" .. n + n += 1 + end + local ty = TYPES[kind] or "?" + local entry: any = { + name = name, + rawName = raw, + type = ty, + closed = bit32.band(ft, 0x80) ~= 0, + locked = bit32.band(ft, 0x40) ~= 0, + blocks = buffer.readu16(b, e + 30), + dir = false, + method = "store", + } + if ty == "cbm" or ty == "dir" then + entry.size = 0 + else + local data, err = chain(b, base, geo, buffer.readu8(b, e + 3), buffer.readu8(b, e + 4)) + if not data then + return nil, Err.new(Err.CORRUPT, name .. ": " .. tostring(err)) + end + entry.size = buffer.len(data) + entry.data = data + if ty == "rel" then + entry.recordLength = buffer.readu8(b, e + 23) + end + end + Archive.put(a, entry) + end + end + t, s = buffer.readu8(b, so), buffer.readu8(b, so + 1) + end + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- BAM layout per variant: where each track's free count + bitmap lives +local function bamEntry(geo: Geometry, img: buffer, t: number): (number, number, number) + local dir = geo.offsets[geo.dirTrack] + if geo.kind == "d81" then + local side = if t <= 40 then 1 else 2 + local tt = if t <= 40 then t else t - 40 + local o = dir + side * 256 + 0x10 + (tt - 1) * 6 + return o, o + 1, 5 + end + if t <= 35 then + local o = dir + 4 + (t - 1) * 4 + return o, o + 1, 3 + end + -- d71 side 2: counts at 18/0 0xDD.., bitmaps on track 53 sector 0 + return dir + 0xDD + (t - 36), geo.offsets[53] + (t - 36) * 3, 3 +end + +local function setFree(geo: Geometry, img: buffer, t: number, s: number, free: boolean) + local co, bo = bamEntry(geo, img, t) + local byte = bo + bit32.rshift(s, 3) + local mask = bit32.lshift(1, bit32.band(s, 7)) + local cur = buffer.readu8(img, byte) + local isFree = bit32.band(cur, mask) ~= 0 + if free and not isFree then + buffer.writeu8(img, byte, bit32.bor(cur, mask)) + buffer.writeu8(img, co, buffer.readu8(img, co) + 1) + elseif not free and isFree then + buffer.writeu8(img, byte, bit32.band(cur, bit32.bnot(mask))) + buffer.writeu8(img, co, buffer.readu8(img, co) - 1) + end +end + +function D64.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local variant = o.variant or (if type(value) == "table" and type(value.meta) == "table" and value.meta.variant then value.meta.variant else "d64") + if variant ~= "d64" and variant ~= "d71" and variant ~= "d81" then + return nil, Err.new(Err.ARG, "variant must be d64, d71 or d81") + end + local files, err = Archive.files(value, "data") + if not files then + return nil, err + end + local geo = geometry(variant, if variant == "d64" then 35 elseif variant == "d71" then 70 else 80) + local img = buffer.create(geo.total) + local dirT = geo.dirTrack + local dir = geo.offsets[dirT] + local diskName = toPetscii(o.disk or (if type(value) == "table" and type(value.meta) == "table" and type(value.meta.disk) == "string" then value.meta.disk else "rosetta")) + local id = toPetscii(o.id or "fl") + local function pad16(s: string): string + return s .. string.rep("\160", 16 - #s) + end + local firstDir + if variant == "d81" then + buffer.writestring(img, dir, "\40\3\68\0") + buffer.writestring(img, dir + 4, pad16(diskName) .. "\160\160" .. string.sub(id .. " ", 1, 2) .. "\160" .. "3D" .. "\160\160") + for side = 1, 2 do + local bo = dir + side * 256 + buffer.writestring(img, bo, if side == 1 then "\40\2\68\187" else "\0\255\68\187") + buffer.writestring(img, bo + 4, string.sub(id .. " ", 1, 2) .. "\192\0") + end + firstDir = 3 + else + buffer.writestring(img, dir, "\18\1\65" .. (if variant == "d71" then "\128" else "\0")) + buffer.writestring(img, dir + 0x90, pad16(diskName) .. "\160\160" .. string.sub(id .. " ", 1, 2) .. "\160" .. "2A" .. "\160\160\160\160") + firstDir = 1 + end + for t = 1, geo.tracks do + for s = 0, geo.spt[t] - 1 do + setFree(geo, img, t, s, true) + end + end + -- system sectors: the header / BAM sectors and the first directory sector + local used = { [dirT * 256 + 0] = true, [dirT * 256 + firstDir] = true } + if variant == "d81" then + used[dirT * 256 + 1], used[dirT * 256 + 2] = true, true + elseif variant == "d71" then + for s = 0, geo.spt[53] - 1 do + used[53 * 256 + s] = true + end + end + for k in used do + setFree(geo, img, k // 256, k % 256, false) + end + local maxDirSectors = geo.spt[dirT] - firstDir + if #files > maxDirSectors * 8 then + return nil, Err.new(Err.LIMIT, "too many files for one directory track") + end + -- allocation: tracks nearest the directory track first, interleave 10 + local order = {} + for d = 1, geo.tracks do + for _, t in { dirT - d, dirT + d } do + if t >= 1 and t <= geo.tracks and t ~= dirT and not (variant == "d71" and t == 53) then + table.insert(order, t) + end + end + end + local ti, lastS = 1, -10 + local function alloc(): (number?, number?) + while ti <= #order do + local t = order[ti] + local n = geo.spt[t] + for k = 0, n - 1 do + local s = (lastS + 10 + k) % n + if not used[t * 256 + s] then + used[t * 256 + s] = true + setFree(geo, img, t, s, false) + lastS = s + return t, s + end + end + ti += 1 + lastS = -10 + end + return nil, nil + end + local dirSector, slot = firstDir, 0 + local dirSectors = { firstDir } + for _, f in files do + local data = f.data + local n = buffer.len(data) + local blocks = math.max(1, math.ceil(n / 254)) + local first_t, first_s = 0, 0 + local prev = -1 + for k = 0, blocks - 1 do + local t, s = alloc() + if not t or not s then + return nil, Err.new(Err.LIMIT, "disk full") + end + local so = geo.offsets[t] + s * 256 + if prev < 0 then + first_t, first_s = t, s + else + buffer.writeu8(img, prev, t) + buffer.writeu8(img, prev + 1, s) + end + local len = math.min(254, n - k * 254) + if len > 0 then + buffer.copy(img, so + 2, data, k * 254, len) + end + buffer.writeu8(img, so + 1, if k == blocks - 1 then len + 1 else 0) + prev = so + end + if slot == 8 then + -- next directory sector on the directory track (interleave 3) + local nextS = nil + for k = 0, geo.spt[dirT] - 1 do + local s = (dirSector + 3 + k) % geo.spt[dirT] + if not used[dirT * 256 + s] then + nextS = s + break + end + end + if not nextS then + return nil, Err.new(Err.LIMIT, "directory full") + end + used[dirT * 256 + nextS] = true + setFree(geo, img, dirT, nextS, false) + buffer.writeu8(img, dir + dirSector * 256, dirT) + buffer.writeu8(img, dir + dirSector * 256 + 1, nextS) + dirSector, slot = nextS, 0 + table.insert(dirSectors, nextS) + end + local e = dir + dirSector * 256 + slot * 32 + local ty: number = if type(f.entry.type) == "string" and TYPE_CODE[f.entry.type] then TYPE_CODE[f.entry.type] :: number else 2 + buffer.writeu8(img, e + 2, 0x80 + ty) + buffer.writeu8(img, e + 3, first_t) + buffer.writeu8(img, e + 4, first_s) + local raw = if type(f.entry.rawName) == "string" and #f.entry.rawName == 16 then (string.gsub(f.entry.rawName, "\160+$", "")) else toPetscii(f.name) + buffer.writestring(img, e + 5, pad16(raw)) + buffer.writeu16(img, e + 30, blocks) + slot += 1 + end + buffer.writeu8(img, dir + dirSector * 256 + 1, 0xFF) + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ extras +function D64.new(variant: string?): any + local a = Archive.new("d64", encoder) + a.meta.variant = variant or "d64" + a.meta.source = { format = "d64" } + return a +end + +return D64 +end +__FILES["archive/fat"] = function() + +-- archive/fat: FAT12 / FAT16 / FAT32 images (floppy, or the first FAT partition of an MBR) through containers/Fat. +-- Supports: VFAT long names, NT lower-case 8.3, DOS dates as UTC; writes FAT12 floppies (360..2880 KB) that mtools and +-- fsck.fat read. Not supported: writing FAT16 / FAT32, exFAT, boot code. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Archive = __include("containers/Archive") +local Fat = __include("containers/Fat") + +-- ------------------------------------------------------------------------------------------------ contract +local FatFormat = { + name = "fat", + category = "archive", + extensions = { "img", "ima", "vfd", "flp", "fat" }, + mime = { "application/x-fat-image" }, + deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Fat" }, + caps = { decode = true, encode = true, variants = { "fat12", "fat16", "fat32" } }, +} + +type DecodeOptions = { + partition: number?, -- 1..4 (default: the first FAT partition, or the image itself) + maxEntries: number?, -- default 65536 +} +type EncodeOptions = { + size: number?, -- KB: 360 / 720 / 1200 / 1440 / 2880 (default 1440) + label: string?, +} + +-- ------------------------------------------------------------------------------------------------ sniff +function FatFormat.sniff(r: Bytes.Reader): number + if r:remaining() < 512 then + return 0 + end + local v = Fat.open(r.buf, r.base + r.pos, r.limit - r.base - r.pos) + if not v then + return 0 + end + return if v.partition then 0.6 else 0.8 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function encoder(a: any, o: any?): (buffer?, Err.Err?) + return FatFormat.encode(a, o) +end + +function FatFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + local v, err = Fat.open(r.buf, r.base, r.limit - r.base, { partition = o.partition }) + if not v then + return nil, Err.from(err) + end + local list, lerr = Fat.list(v, o.maxEntries) + if not list then + return nil, Err.from(lerr) + end + local a = Archive.new("fat", encoder) + for _, e in list do + local entry = e + Archive.put(a, { + name = e.name, + size = e.size, + dir = e.dir, + mtime = e.mtime, + attr = e.attr, + shortName = e.shortName, + method = "store", + load = if e.dir or e.size == 0 then nil else function(): (buffer?, Err.Err?) + local b, rerr = Fat.read(v :: Fat.Volume, entry) + if not b then + return nil, Err.from(rerr) + end + return b, nil + end, + }) + end + a.meta.fat = v.bits + a.meta.label = v.label + a.meta.oem = v.oem + a.meta.partition = v.partition + a.meta.source = { format = "fat", bits = v.bits, clusterSize = v.spc * v.bps } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function FatFormat.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local items = Archive.entries(value) + if not items then + return nil, Err.new(Err.ARG, "expected an Archive") + end + local files: { Fat.WriteFile } = {} + for _, it in items do + local e: any = it.entry + local data: buffer? = nil + if not e.dir then + local b, err = it.read() + if not b then + return nil, err + end + data = b + end + table.insert(files, { name = e.name, data = data, dir = e.dir, mtime = e.mtime }) + end + local img, err = Fat.write(files, { size = o.size, label = o.label }) + if not img then + return nil, if string.match(tostring(err), "^limit") then Err.from(err) else Err.new(Err.ARG, tostring(err)) + end + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ extras +function FatFormat.new(): any + local a = Archive.new("fat", encoder) + a.meta.source = { format = "fat" } + return a +end + +return FatFormat +end +__FILES["archive/grp"] = function() + +-- archive/grp: Build engine GRP ("KenSilverman", u32 count, 16-byte entries: 12-byte name + u32 size, then the data), +-- from Ken Silverman's description; no code taken. Supports: read (lazy), write (names stored as given, at most 12 +-- bytes). Not supported: the "GRP 2" / RFF / SSI variants. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Sniff = __include("core/Sniff") +local Archive = __include("containers/Archive") + +-- ------------------------------------------------------------------------------------------------ contract +local Grp = { + name = "grp", + category = "archive", + extensions = { "grp" }, + mime = { "application/x-build-grp" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "containers/Archive" }, + caps = { decode = true, encode = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { maxEntries: number? } -- default 1e6 +type EncodeOptions = { upper: boolean? } -- Build looks names up case-insensitively; default false + +-- ------------------------------------------------------------------------------------------------ constants +local MAGIC = "KenSilverman" + +-- ------------------------------------------------------------------------------------------------ sniff +function Grp.sniff(r: Bytes.Reader): number + return Sniff.magic(r, MAGIC) +end + +-- ------------------------------------------------------------------------------------------------ decode +local function encode(archive: any, opts: any?): (buffer?, Err.Err?) + return Grp.encode(archive, opts) +end + +function Grp.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + if not r:match(MAGIC) then + return nil, Err.new(Err.CORRUPT, "bad magic", 0) + end + local count = r:u32le() + if r.err then + return nil, r.err + end + if count > (opts and opts.maxEntries or 1e6) then + return nil, Err.new(Err.LIMIT, "too many entries: " .. count) + end + if count * 16 > r:remaining() then + return nil, Err.new(Err.TRUNCATED, "directory past the end", 12) + end + local a = Archive.new("grp", encode) + local at = 16 + count * 16 + local size = r.limit - r.base + for i = 0, count - 1 do + local name = r:fixed(12) + local n = r:u32le() + if at + n > size then + return nil, Err.new(Err.TRUNCATED, "entry " .. name .. " past the end", 16 + i * 16) + end + Archive.put(a, { name = name, size = n, dir = false, method = "store", offset = at, load = Archive.slice(r.buf, r.base + at, n) }) + at += n + end + if r.err then + return nil, r.err + end + a.meta.source = { format = "grp", entries = count } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Grp.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local items, err = Archive.collect(archive) + if not items then + return nil, err + end + local files: { { name: string, data: buffer } } = {} + for _, it in items do + if not it.entry.dir then + local name = it.entry.name + if opts and opts.upper then + name = string.upper(name) + end + if #name > 12 then + return nil, Err.new(Err.ARG, "name longer than 12 bytes: " .. name) + end + table.insert(files, { name = name, data = it.data }) + end + end + local w = Bytes.writer() + w:string(MAGIC) + w:u32le(#files) + for _, f in files do + w:string(f.name) + w:fill(0, 12 - #f.name) + w:u32le(buffer.len(f.data)) + end + for _, f in files do + w:bytes(f.data) + end + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +function Grp.new(): any + local a = Archive.new("grp", encode) + a.meta.source = { format = "grp" } + return a +end + +return Grp +end +__FILES["archive/gzip"] = function() + +-- archive/gzip: gzip (RFC 1952) as a single-stream archive of one entry (FNAME, MTIME; codecs/compress/Deflate). +-- Supports: concatenated members as one stream (as gzip -d); write (several entries: a .tar.gz). +-- Not supported: FHCRC verification. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Crc32 = __include("core/Crc32") +local Deflate = __include("codecs/compress/Deflate") +local Archive = __include("containers/Archive") +local Tar = __include("containers/Tar") + +-- ------------------------------------------------------------------------------------------------ contract +local Gzip = { + name = "gzip", + category = "archive", + extensions = { "gz", "tgz", "gzip" }, + mime = { "application/gzip" }, + deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/compress/Deflate", "containers/Archive", "containers/Tar" }, + caps = { decode = true, encode = true, stream = true }, +} + +type DecodeOptions = { name: string? } +type EncodeOptions = { + level: number?, -- 0..9, default 6 + name: string?, -- default: the entry's name; none for a buffer + mtime: number?, -- default: the entry's mtime, else 0 +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Gzip.sniff(r: Bytes.Reader): number + return if r:peek(3) == "\31\139\8" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function header(b: buffer, o: number, e: number): { [string]: any } + local h: { [string]: any } = {} + if o + 10 > e then + return h + end + local flg = buffer.readu8(b, o + 3) + h.mtime = buffer.readu32(b, o + 4) + h.os = buffer.readu8(b, o + 9) + local q = o + 10 + 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" } } :: { { any } } do + if bit32.band(flg, f[1]) ~= 0 then + local s = q + while q < e and buffer.readu8(b, q) ~= 0 do + q += 1 + end + if q < e then + h[f[2]] = buffer.readstring(b, s, q - s) + end + q += 1 + end + end + return h +end + +function Gzip.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local out, err = Deflate.gunzip(r.buf, r.base, r.limit - r.base) + if not out then + return nil, err + end + local h = header(r.buf, r.base, r.limit) + local a = Archive.new("gzip", function(arc: any, o: any?): (buffer?, Err.Err?) + return Gzip.encode(arc, o) + end) + a.meta.stream = true + a.meta.source = { format = "gzip", os = h.os } + a.meta.comment = h.comment + local name = h.name + if not name or name == "" or string.find(name, "[/\\]") then + name = Archive.streamName(opts, Gzip.extensions) + end + Archive.put(a, { + name = name, + size = buffer.len(out), + compressedSize = r.limit - r.base, + method = "deflate", + mtime = if h.mtime and h.mtime > 0 then h.mtime :: number else nil, + dir = false, + data = out, + }) + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Gzip.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + 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") + end + local data: buffer + local name: string? = o.name + local mtime: number = o.mtime or 0 + if type(value) == "buffer" then + data = value + elseif type(value) == "string" then + data = buffer.fromstring(value) + else + local items = Archive.entries(value) + if not items then + return nil, Err.new(Err.ARG, "expected an Archive, a buffer or a string") + end + local files: typeof(items) = {} + for _, it in items do + if not it.entry.dir then + table.insert(files, it) + end + end + if #files == 1 and #items == 1 then + local b, err = files[1].read() + if not b then + return nil, err + end + data = b + name = name or files[1].entry.name + mtime = o.mtime or files[1].entry.mtime or 0 + else + -- several entries: a tar inside + local list = {} + for _, it in items do + local e: any = it.entry + local b = nil + if not e.dir then + local rb, err = it.read() + if not rb then + return nil, err + end + b = rb + end + table.insert(list, { name = e.name, data = b, dir = e.dir, mtime = e.mtime, mode = e.mode }) + end + local t, terr = Tar.write(list) + if not t then + return nil, terr + end + data = t + end + end + if type(mtime) ~= "number" or mtime < 0 or mtime >= 2 ^ 32 then + mtime = 0 + end + local raw, cerr = Deflate.compress(data, { level = level }) + if not raw then + return nil, cerr + end + local w = Bytes.writer(buffer.len(raw) + 32 + (if name then #name else 0)) + w:string("\31\139\8") + w:u8(if name then 8 else 0) + w:u32le(math.floor(mtime)) + w:u8(if level >= 9 then 2 elseif level <= 1 then 4 else 0) + w:u8(255) + if name then + local z = string.find(name, "\0", 1, true) + w:cstring(if z then string.sub(name, 1, z - 1) else name) + end + w:bytes(raw) + w:u32le(Crc32.raw(data, 0, buffer.len(data))) + w:u32le(buffer.len(data) % 4294967296) + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +function Gzip.new(data: (buffer | string)?, name: string?): any + local a = Archive.new("gzip", function(arc: any, o: any?): (buffer?, Err.Err?) + return Gzip.encode(arc, o) + end) + a.meta.stream = true + a.meta.source = { format = "gzip" } + if data then + a:add(name or "data", data) + end + return a +end + +return Gzip +end +__FILES["archive/iso"] = function() + +-- archive/iso: ISO 9660 images through containers/Iso9660. Supports: plain names, Joliet, Rock Ridge (RR, else Joliet, +-- else plain), multi-extent files, El Torito boot catalog (meta.boot). Not supported: writing, UDF, interleaved files +-- (UNSUPPORTED), zisofs (stored bytes), multi-session images (the first session). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Archive = __include("containers/Archive") +local Iso9660 = __include("containers/Iso9660") + +-- ------------------------------------------------------------------------------------------------ contract +local Iso = { + name = "iso", + category = "archive", + extensions = { "iso" }, + mime = { "application/x-iso9660-image" }, + deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Iso9660" }, + caps = { decode = true, encode = false, extensions = { "joliet", "rockridge", "eltorito" } }, +} + +type DecodeOptions = { + prefer: ("rockridge" | "joliet" | "iso9660")?, -- default: Rock Ridge, else Joliet, else plain + maxEntries: number?, -- default 1e6 +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Iso.sniff(r: Bytes.Reader): number + return if r:peek(5, 16 * 2048 + 1) == "CD001" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Iso.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local list, info = Iso9660.read(r.buf, r.base, r.limit - r.base, opts) + if not list then + return nil, info + end + local a = Archive.new("iso") + local b, limit = r.buf, r.limit + for _, e in list do + local data = e.type == "0" and e.size > 0 + Archive.put(a, { + name = e.name, + size = e.size, + dir = e.dir, + mtime = e.mtime, + type = e.type, + mode = e.mode, + uid = e.uid, + gid = e.gid, + nlink = e.nlink, + link = e.link, + rdev = e.rdev, + hidden = e.hidden, + method = if e.zisofs then "zisofs" else "store", + load = if data + then function(): (buffer?, Err.Err?) + return Iso9660.extract(b, e, limit) + end + else nil, + }) + end + a.meta.boot = info.boot + info.boot = nil + a.meta.iso = info + a.meta.source = { format = "iso", tree = info.tree } + return a, nil +end + +return Iso +end +__FILES["archive/lha"] = function() + +-- archive/lha: LHA / LZH (and LArc .lzs; Yoshizaki's LHa notes, lhasa's lha_file_header.c, ISC): header levels 0-3, +-- methods lh0 / lz4 / lhd / lh1 / lh4-lh7 / lhx / lzs / lz5, CRC-16 (ARC), "name|target" symlinks; writes level 2, +-- stored. Not supported: PMarc pm0-pm2, compression when writing, multi-volume, stubs beyond the first 64 KB. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Crc16 = __include("core/Crc16") +local Lzh = __include("codecs/compress/Lzh") +local Archive = __include("containers/Archive") + +-- ------------------------------------------------------------------------------------------------ contract +local Lha = { + name = "lha", + category = "archive", + extensions = { "lzh", "lha", "lzs" }, + mime = { "application/x-lzh-compressed" }, + deps = { "core/Err", "core/Bytes", "core/Crc16", "codecs/compress/Lzh", "containers/Archive" }, + caps = { decode = true, encode = true, methods = { "lh0", "lh1", "lh4", "lh5", "lh6", "lh7", "lhx", "lzs", "lz5", "lz4", "lhd" } }, +} + +type DecodeOptions = { + maxBytes: number?, -- default 2^30 + maxEntries: number?, -- default 65536 +} +type EncodeOptions = {} + +-- ------------------------------------------------------------------------------------------------ constants +local METHODS: { [string]: boolean } = { + ["-lh0-"] = true, ["-lz4-"] = true, ["-lhd-"] = true, ["-lh1-"] = true, ["-lh4-"] = true, ["-lh5-"] = true, + ["-lh6-"] = true, ["-lh7-"] = true, ["-lhx-"] = true, ["-lzs-"] = true, ["-lz5-"] = true, ["-lh2-"] = true, + ["-lh3-"] = true, ["-pm0-"] = true, ["-pm1-"] = true, ["-pm2-"] = true, ["-lk7-"] = true, +} + +-- ------------------------------------------------------------------------------------------------ sniff +local function isHeader(s: string): boolean + if #s < 22 then + return false + end + local m = string.sub(s, 3, 7) + local level = string.byte(s, 21) + return METHODS[m] == true and level <= 3 +end + +function Lha.sniff(r: Bytes.Reader): number + if isHeader(r:peek(22)) then + return 0.95 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- "." / ".." collapsed as lhasa does +local function path(s: string): string + s = string.gsub(s, "[\\\255]", "/") + local parts = {} + for part in string.gmatch(s, "[^/]+") do + if part ~= "." and part ~= ".." then + table.insert(parts, part) + end + end + return table.concat(parts, "/") .. (if string.sub(s, -1) == "/" and #parts > 0 then "/" else "") +end + +type Header = { + method: string, + packed: number, + size: number, + mtime: number?, + level: number, + name: string, + dir: string?, + crc: number?, + mode: number?, + uid: number?, + gid: number?, + uname: string?, + gname: string?, + attr: number?, + comment: string?, + os: string?, + dataAt: number, +} + +local function extended(r: Bytes.Reader, p: number, w: number, first: number, h: Header, limit: number): (number?, string?) + local size = first + local guard = 0 + while size ~= 0 do + guard += 1 + if guard > 4096 or size < w + 1 or p + size > limit then + return nil, "bad extended header" + end + local e = r:sub(p, size) + local kind = e:u8() + local body = size - 1 - w + if kind == 0x01 then + h.name = e:string(body) + elseif kind == 0x02 then + h.dir = e:string(body) + elseif kind == 0x3F or kind == 0x71 then + h.comment = e:string(body) + elseif kind == 0x40 and body >= 2 then + h.attr = e:u16le() + elseif kind == 0x50 and body >= 2 then + h.mode = e:u16le() + elseif kind == 0x51 and body >= 4 then + h.gid, h.uid = e:u16le(), e:u16le() + elseif kind == 0x52 then + h.gname = e:string(body) + elseif kind == 0x53 then + h.uname = e:string(body) + elseif kind == 0x54 and body >= 4 then + h.mtime = e:u32le() + elseif kind == 0x42 and body >= 16 then + h.packed, h.size = e:u64le(), e:u64le() + end + e:seek(size - w) + local nextSize = if w == 2 then e:u16le() else e:u32le() + if e.err then + return nil, "truncated extended header" + end + p += size + size = nextSize + end + return p, nil +end + +local OS = { [0x4D] = "msdos", [0x55] = "unix", [0x32] = "os2", [0x39] = "os9", [0x4B] = "os68k", [0x33] = "os386", + [0x48] = "human68k", [0x43] = "cpm", [0x46] = "flex", [0x6D] = "mac", [0x77] = "windows95", [0x57] = "windowsnt", + [0x52] = "runser", [0x54] = "townsos", [0x58] = "xosk", [0x41] = "amiga", [0x61] = "atari", [0x4A] = "java" } + +local function header(r: Bytes.Reader, p: number): (Header?, string?) + local limit = r:size() + if p >= limit or r:sub(p, 1):u8() == 0 then + return nil, nil + end + if p + 22 > limit then + return nil, "truncated header" + end + local s = r:sub(p, 26) + local b0 = s:u8() + s:u8() + local method = s:string(5) + local packed, size, stamp = s:u32le(), s:u32le(), s:u32le() + s:u8() + local level = s:u8() + if not METHODS[method] then + return nil, "bad method " .. method + end + local h: Header = { method = string.sub(method, 2, 4), packed = packed, size = size, level = level, name = "", dataAt = 0 } + if level == 0 or level == 1 then + local hsize = b0 + 2 + if p + hsize > limit or hsize < 24 then + return nil, "truncated header" + end + local hr = r:sub(p + 21, hsize - 21) + local nlen = hr:u8() + h.name = hr:string(nlen) + h.crc = hr:u16le() + h.mtime = Archive.fromDos(stamp) + if level == 0 then + -- an optional Unix extension: 'U', mtime, mode, uid, gid + if hr:remaining() >= 11 and (hr:peekU8() == 0x55 or hr:peekU8() == 0x4B) then + h.os = if hr:u8() == 0x55 then "unix" else "os68k" + h.mtime = hr:u32le() + h.mode = hr:u16le() + h.uid, h.gid = hr:u16le(), hr:u16le() + end + h.dataAt = p + hsize + else + h.os = OS[hr:u8()] + local first = r:sub(p + hsize - 2, 2):u16le() + local e, err = extended(r, p + hsize, 2, first, h, limit) + if not e then + return nil, err + end + h.packed = packed - (e - (p + hsize)) + h.dataAt = e + end + if hr.err then + return nil, "truncated header" + end + elseif level == 2 then + local total = r:sub(p, 2):u16le() + local hr = r:sub(p + 21, 5) + h.crc = hr:u16le() + local osByte = hr:u8() + h.os = OS[osByte] + if osByte == 0x4B then + total += 2 -- LHa for OS-9/68k writes the header length without its own two bytes (as lhasa compensates) + end + local first = hr:u16le() + h.mtime = stamp + local e, err = extended(r, p + 26, 2, first, h, limit) + if not e or hr.err then + return nil, err or "truncated header" + end + h.dataAt = p + total + if total < 26 or h.dataAt > limit then + return nil, "bad level 2 header size" + end + elseif level == 3 then + local hr = r:sub(p + 21, 11) + h.crc = hr:u16le() + h.os = OS[hr:u8()] + local total = hr:u32le() + local first = hr:u32le() + h.mtime = stamp + local e, err = extended(r, p + 32, 4, first, h, limit) + if not e or hr.err then + return nil, err or "truncated header" + end + h.dataAt = p + total + if total < 32 or h.dataAt > limit then + return nil, "bad level 3 header size" + end + else + return nil, "unsupported: header level " .. level + end + return h, nil +end + +local LZH_METHOD = { lh1 = "lh1", lh4 = "lh4", lh5 = "lh5", lh6 = "lh6", lh7 = "lh7", lhx = "lhx", lzs = "lzs", lz5 = "lz5" } + +local function encoder(a: any, o: any?): (buffer?, Err.Err?) + return Lha.encode(a, o) +end + +function Lha.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + local maxBytes = o.maxBytes or 2 ^ 30 + local maxEntries = o.maxEntries or 65536 + local p = 0 + if not isHeader(r:peek(22)) then + local head = r:peek(65536) + local at = nil + for k = 1, #head - 22 do + if string.byte(head, k + 2) == 45 and isHeader(string.sub(head, k, k + 21)) then + at = k - 1 + break + end + end + if not at then + return nil, Err.new(Err.CORRUPT, "no LHA header") + end + p = at + end + local a = Archive.new("lha", encoder) + local count = 0 + local levels = {} + while true do + local h, err = header(r, p) + if err then + return nil, Err.from(err, r.base + p) + end + if not h then + break + end + count += 1 + if count > maxEntries then + return nil, Err.new(Err.LIMIT, "more than maxEntries entries") + end + levels[h.level] = true + if h.packed < 0 or h.dataAt + h.packed > r:size() then + return nil, Err.new(Err.TRUNCATED, "entry " .. path(h.name) .. " data past the end", r.base + h.dataAt) + end + -- MS-DOS-like archives store names in capitals: all-caps names read in lower case, as lhasa / LHa do + local os = h.os + if os == nil or os == "msdos" or os == "atari" or os == "os2" then + if not string.find(h.name .. (h.dir or ""), "%l") then + h.name = string.lower(h.name) + h.dir = if h.dir then string.lower(h.dir) else nil + end + end + -- the full path (a Unix symlink "name|target" may be split across the directory and file name headers) + local name = path(h.name) + if h.dir and h.dir ~= "" then + local d = path(h.dir) + if string.sub(d, -1) ~= "/" then + d ..= "/" + end + name = d .. name + end + local link: string? = nil + local bar = string.find(name, "|", 1, true) + if bar then + name, link = string.sub(name, 1, bar - 1), string.sub(name, bar + 1) + end + local isDir = h.method == "lhd" + if isDir and link == nil and string.sub(name, -1) ~= "/" then + name ..= "/" + end + local e: any = { + name = name, + size = if isDir or link then 0 else h.size, + compressedSize = h.packed, + method = h.method, + mtime = h.mtime, + dir = isDir and link == nil, + mode = h.mode, + uid = h.uid, + gid = h.gid, + uname = h.uname, + gname = h.gname, + attr = h.attr, + comment = h.comment, + os = h.os, + level = h.level, + crc = h.crc, + } + if link then + e.link = link + e.type = "symlink" + elseif not isDir and h.size > 0 then + if h.size > maxBytes then + return nil, Err.new(Err.LIMIT, name .. ": larger than maxBytes") + end + local at, packed, size, method, crc = h.dataAt, h.packed, h.size, h.method, h.crc + local buf, base = r.buf, r.base + e.load = function(): (buffer?, Err.Err?) + local out: buffer?, derr: string? + if method == "lh0" or method == "lz4" then + if packed < size then + return nil, Err.new(Err.CORRUPT, "stored entry shorter than its size") + end + out = buffer.create(size) + buffer.copy(out :: buffer, 0, buf, base + at, size) + elseif LZH_METHOD[method] then + out, derr = Lzh.decode(buf, base + at, packed, size, LZH_METHOD[method]) + else + return nil, Err.new(Err.UNSUPPORTED, "method " .. method) + end + if not out then + return nil, Err.from(derr) + end + if crc and Crc16.arc(out, 0, size) ~= crc then + return nil, Err.new(Err.CHECKSUM, "CRC-16 mismatch") + end + return out, nil + end + end + Archive.put(a, e) + p = h.dataAt + h.packed + end + a.meta.source = { format = "lha", levels = levels } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Lha.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local items = Archive.entries(value) + if not items then + return nil, Err.new(Err.ARG, "expected an Archive") + end + local out = Bytes.writer() + for _, it in items do + local e: any = it.entry + local data = buffer.create(0) + if not e.dir then + local b, err = it.read() + if not b then + return nil, err + end + data = b + end + local full = string.gsub(e.name, "/+$", "") + local dirPart, base = string.match(full, "^(.*/)([^/]*)$") + if not dirPart then + dirPart, base = "", full + end + if e.dir then + dirPart, base = full .. "/", "" + end + local h = Bytes.writer() + h:u16le(0) + h:string(if e.dir then "-lhd-" else "-lh0-") + h:u32le(buffer.len(data)) + h:u32le(buffer.len(data)) + h:u32le(if type(e.mtime) == "number" and e.mtime >= 0 then math.floor(e.mtime) % 4294967296 else 0) + h:u8(0x20) + h:u8(2) + h:u16le(Crc16.arc(data, 0, buffer.len(data))) + h:u8(0x55) -- 'U'nix + -- extended headers: [type][body][size of the next one]; the first size ends the base header + local exts: { { any } } = { { 0x00, "\0\0" }, { 0x01, base } } + if dirPart ~= "" then + table.insert(exts, { 0x02, (string.gsub(dirPart :: string, "/", "\255")) }) + end + if type(e.mode) == "number" then + local m = bit32.band(e.mode, 0xFFF) + (if e.dir then 0x4000 else 0x8000) + table.insert(exts, { 0x50, string.char(m % 256, m // 256) }) + end + h:u16le(#exts[1][2] + 3) + for i, x in exts do + h:u8(x[1]) + h:string(x[2]) + h:u16le(if exts[i + 1] then #exts[i + 1][2] + 3 else 0) + end + local hb = h:finish() + local total = buffer.len(hb) + if total > 65535 then + return nil, Err.new(Err.ARG, "header too long for " .. e.name) + end + buffer.writeu16(hb, 0, total) + -- the header CRC covers the whole header with its own field zero + local crcAt = 24 + 2 + 1 -- first ext: size (2) at 24, type at 26, CRC at 27 + buffer.writeu16(hb, crcAt, Crc16.arc(hb, 0, total)) + out:bytes(hb) + out:bytes(data) + end + out:u8(0) + return out:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +function Lha.new(): any + local a = Archive.new("lha", encoder) + a.meta.source = { format = "lha" } + return a +end + +return Lha +end +__FILES["archive/lz4"] = function() + +-- archive/lz4: LZ4 frames (lz4_Frame_format.md 1.6.x) as a single-stream archive. Supports: concatenated, skippable +-- (0x184D2A50..5F) and legacy (0x184C2102, 8 MB blocks) frames, linked blocks, 64 KB .. 4 MB, XXH32 checksums; writes +-- one frame of independent blocks. Not supported: dictionaries, writing linked blocks or legacy frames. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Lz4 = __include("codecs/compress/Lz4") +local Xxh32 = __include("codecs/compress/Xxh32") +local Archive = __include("containers/Archive") + +-- ------------------------------------------------------------------------------------------------ contract +local Lz4Format = { + name = "lz4", + category = "archive", + extensions = { "lz4", "tlz4" }, + mime = { "application/x-lz4" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Lz4", "codecs/compress/Xxh32", "containers/Archive" }, + caps = { decode = true, encode = true, stream = true, legacy = true }, +} + +type DecodeOptions = { + maxBytes: number?, -- default 2^30 + verify: boolean?, -- default true; the header checksum is always checked + name: string?, +} +type EncodeOptions = { + blockSize: number?, -- 65536, 262144, 1048576 or 4194304 (default 4 MB, as the lz4 tool) + blockChecksum: boolean?, -- default false + contentChecksum: boolean?, -- default true + contentSize: boolean?, -- default false +} + +-- ------------------------------------------------------------------------------------------------ constants +local MAGIC = 0x184D2204 +local LEGACY = 0x184C2102 +local LEGACY_BLOCK = 8 * 1048576 +local SIZES: { [number]: number } = { [4] = 65536, [5] = 262144, [6] = 1048576, [7] = 4194304 } + +-- ------------------------------------------------------------------------------------------------ sniff +function Lz4Format.sniff(r: Bytes.Reader): number + local m = r:peek(4) + if m == "\4\34\77\24" then + return 1 + elseif m == "\2\33\76\24" then + return 0.9 + elseif #m == 4 and string.byte(m, 1) >= 0x50 and string.byte(m, 1) <= 0x5F and string.sub(m, 2) == "\42\77\24" then + -- a skippable frame (zstd shares the magic): an LZ4 frame after it + local h = r:peek(4, 4) + if #h == 4 then + local n = string.byte(h, 1) + string.byte(h, 2) * 256 + string.byte(h, 3) * 65536 + string.byte(h, 4) * 16777216 + if r:peek(4, 8 + n) == "\4\34\77\24" then + return 1 + end + end + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function skippable(m: number): boolean + return m >= 0x184D2A50 and m <= 0x184D2A5F +end + +type Out = { buf: buffer, n: number, max: number } + +local function room(out: Out, k: number): boolean + local need = out.n + k + if need > out.max then + return false + end + if need > buffer.len(out.buf) then + local nb = buffer.create(math.min(math.max(buffer.len(out.buf) * 2, need), out.max)) + buffer.copy(nb, 0, out.buf, 0, out.n) + out.buf = nb + end + return true +end + +local function frame(b: buffer, p: number, e: number, out: Out, verify: boolean): (number?, Err.Err?) + if p + 7 > e then + return nil, Err.new(Err.TRUNCATED, "frame header past the end", p) + end + local flg, bd = buffer.readu8(b, p + 4), buffer.readu8(b, p + 5) + if bit32.rshift(flg, 6) ~= 1 then + return nil, Err.new(Err.UNSUPPORTED, "frame version " .. bit32.rshift(flg, 6), p + 4) + end + if bit32.band(flg, 2) ~= 0 or bit32.band(bd, 0x8F) ~= 0 then + return nil, Err.new(Err.CORRUPT, "reserved descriptor bits set", p + 4) + end + local independent = bit32.band(flg, 0x20) ~= 0 + local blockSum = bit32.band(flg, 0x10) ~= 0 + local hasSize = bit32.band(flg, 0x08) ~= 0 + local contentSum = bit32.band(flg, 0x04) ~= 0 + local hasDict = bit32.band(flg, 0x01) ~= 0 + local bmax = SIZES[bit32.rshift(bd, 4)] + if not bmax then + return nil, Err.new(Err.CORRUPT, "bad block maximum size", p + 5) + end + local q = p + 6 + local size: number? = nil + if hasSize then + if q + 8 > e then + return nil, Err.new(Err.TRUNCATED, "frame header past the end", q) + end + size = buffer.readu32(b, q) + buffer.readu32(b, q + 4) * 4294967296 + q += 8 + end + if hasDict then + return nil, Err.new(Err.UNSUPPORTED, "frames with a dictionary", q) + end + if q + 1 > e then + return nil, Err.new(Err.TRUNCATED, "frame header past the end", q) + end + local hc = bit32.band(bit32.rshift(Xxh32.hash(b, p + 4, q - p - 4), 8), 255) + if hc ~= buffer.readu8(b, q) then + return nil, Err.new(Err.CHECKSUM, "frame header checksum mismatch", q) + end + q += 1 + if size and out.n + size > out.max then + return nil, Err.new(Err.LIMIT, "content over " .. out.max .. " bytes", p) + end + local start = out.n + while true do + if q + 4 > e then + return nil, Err.new(Err.TRUNCATED, "block header past the end", q) + end + local bs = buffer.readu32(b, q) + q += 4 + if bs == 0 then + break + end + local raw = bit32.band(bs, 0x80000000) ~= 0 + local n = bit32.band(bs, 0x7FFFFFFF) + if n > bmax then + return nil, Err.new(Err.CORRUPT, "block larger than the maximum", q - 4) + end + if q + n + (if blockSum then 4 else 0) > e then + return nil, Err.new(Err.TRUNCATED, "block past the end", q) + end + if blockSum and verify and Xxh32.hash(b, q, n) ~= buffer.readu32(b, q + n) then + return nil, Err.new(Err.CHECKSUM, "block checksum mismatch", q + n) + end + if not room(out, if raw then n else bmax) and not room(out, if raw then n else math.min(bmax, out.max - out.n)) then + return nil, Err.new(Err.LIMIT, "output over " .. out.max .. " bytes", q) + end + if raw then + buffer.copy(out.buf, out.n, b, q, n) + out.n += n + else + local lim = math.min(out.n + bmax, buffer.len(out.buf)) + local dEnd, msg = Lz4.decodeInto(b, q, q + n, out.buf, out.n, lim, if independent then out.n else start) + if not dEnd then + if msg and string.sub(msg, 1, 6) == "limit:" and lim < out.n + bmax then + return nil, Err.new(Err.LIMIT, "output over " .. out.max .. " bytes", q) + end + return nil, Err.from(msg, q) + end + out.n = dEnd + end + q += n + (if blockSum then 4 else 0) + end + if contentSum then + if q + 4 > e then + return nil, Err.new(Err.TRUNCATED, "content checksum past the end", q) + end + if verify and Xxh32.hash(out.buf, start, out.n - start) ~= buffer.readu32(b, q) then + return nil, Err.new(Err.CHECKSUM, "content checksum mismatch", q) + end + q += 4 + end + if size and out.n - start ~= size then + return nil, Err.new(Err.CORRUPT, "content size mismatch", p + 6) + end + return q, nil +end + +-- a legacy frame at p: blocks of up to 8 MB until the input ends or a magic number follows +local function legacy(b: buffer, p: number, e: number, out: Out): (number?, Err.Err?) + local q = p + 4 + while q + 4 <= e do + local n = buffer.readu32(b, q) + if n == MAGIC or n == LEGACY or skippable(n) then + break + end + q += 4 + if q + n > e then + return nil, Err.new(Err.TRUNCATED, "block past the end", q) + end + if not room(out, LEGACY_BLOCK) and not room(out, math.min(LEGACY_BLOCK, out.max - out.n)) then + return nil, Err.new(Err.LIMIT, "output over " .. out.max .. " bytes", q) + end + local lim = math.min(out.n + LEGACY_BLOCK, buffer.len(out.buf)) + local dEnd, msg = Lz4.decodeInto(b, q, q + n, out.buf, out.n, lim) + if not dEnd then + return nil, Err.from(msg, q) + end + out.n = dEnd + q += n + end + return q, nil +end + +function Lz4Format.decompress(src: buffer | string, offset: number?, length: number?, opts: DecodeOptions?): (buffer?, Err.Err?) + local b, o, n, aerr = Bytes.span("Lz4.decompress", src, offset, length) + if not b then + return nil, aerr + end + local maxBytes = (opts and opts.maxBytes) or 2 ^ 30 + local verify = not (opts and opts.verify == false) + local out: Out = { buf = buffer.create(math.min(math.max(n * 3, 256), maxBytes)), n = 0, max = maxBytes } + local p, e = o, o + n + local frames = 0 + while p + 4 <= e do + local m = buffer.readu32(b, p) + local q, err + if m == MAGIC then + q, err = frame(b, p, e, out, verify) + frames += 1 + elseif m == LEGACY then + q, err = legacy(b, p, e, out) + frames += 1 + elseif skippable(m) then + if p + 8 > e then + return nil, Err.new(Err.TRUNCATED, "skippable frame past the end", p) + end + q = p + 8 + buffer.readu32(b, p + 4) + if q > e then + return nil, Err.new(Err.TRUNCATED, "skippable frame past the end", p) + end + elseif frames > 0 then + break -- trailing data after the frames (as lz4 -d, which warns) + else + return nil, Err.new(Err.CORRUPT, "bad magic", p) + end + if not q then + return nil, err + end + p = q :: number + end + if frames == 0 then + return nil, Err.new(if n < 4 then Err.TRUNCATED else Err.CORRUPT, "no LZ4 frame", o) + end + local res = buffer.create(out.n) + buffer.copy(res, 0, out.buf, 0, out.n) + return res, nil +end + +local function encode(value: any, opts: any?): (buffer?, Err.Err?) + return Lz4Format.encode(value, opts) +end + +function Lz4Format.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + local n = r.limit - r.base + local out, err = Lz4Format.decompress(r.buf, r.base, n, o) + if not out then + return nil, err + end + local a = Archive.new("lz4", encode) + a.meta.stream = true + a.meta.source = { format = "lz4", legacy = r:peek(4) == "\2\33\76\24" } + local name = Archive.streamName(o, { "lz4" }) + local stem, ext = string.match(name, "^(.+)%.(%w+)$") + if stem and ext and string.lower(ext) == "tlz4" then + name = stem .. ".tar" + end + Archive.put(a, { name = name, size = buffer.len(out), compressedSize = n, method = "lz4", dir = false, data = out }) + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Lz4Format.compress(data: buffer | string, opts: EncodeOptions?): (buffer?, Err.Err?) + local b, o, n, aerr = Bytes.span("Lz4.compress", data, nil, nil) + if not b then + return nil, aerr + end + local op: EncodeOptions = opts or {} + local bsize = op.blockSize or 4194304 + local bd = nil + for k, v in SIZES do + if v == bsize then + bd = k + end + end + if not bd then + return nil, Err.new(Err.ARG, "blockSize must be 65536, 262144, 1048576 or 4194304") + end + local blockSum = op.blockChecksum == true + local contentSum = op.contentChecksum ~= false + local withSize = op.contentSize == true + local w = Bytes.writer(n + n // 200 + 64) + w:u32le(MAGIC) + local flg = 0x40 + 0x20 + (if blockSum then 0x10 else 0) + (if withSize then 0x08 else 0) + (if contentSum then 0x04 else 0) + w:u8(flg) + w:u8(bd * 16) + if withSize then + w:u32le(n % 4294967296) + w:u32le(n // 4294967296) + end + local hc = bit32.band(bit32.rshift(Xxh32.hash(w.buf, 4, w.pos - 4), 8), 255) + w:u8(hc) + local scratch = buffer.create(Lz4.bound(math.min(bsize, math.max(n, 1)))) + local p = o + while p < o + n do + local k = math.min(bsize, o + n - p) + local c = Lz4.encodeInto(b, p, k, scratch, 0) + local at = w.pos + if c < k then + w:u32le(c) + local q = w:reserve(c) + buffer.copy(w.buf, q, scratch, 0, c) + w.pos = q + c + else + w:u32le(k + 0x80000000) + local q = w:reserve(k) + buffer.copy(w.buf, q, b, p, k) + w.pos = q + k + end + if blockSum then + local len = w.pos - at - 4 + w:u32le(Xxh32.hash(w.buf, at + 4, len)) + end + p += k + end + w:u32le(0) + if contentSum then + w:u32le(Xxh32.hash(b, o, n)) + end + return w:finish(), nil +end + +function Lz4Format.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local data, err = Archive.streamData(value) + if not data then + return nil, err + end + return Lz4Format.compress(data, opts) +end + +return Lz4Format +end +__FILES["archive/macbinary"] = function() + +-- archive/macbinary: MacBinary I / II / III (128-byte header, forks padded to 128, Get Info comment; II / III +-- CRC-16/XMODEM, III 'mBIN'), from the MacBinary II / III specs (Lempereur et al.), as containers/MacFile. +-- Supports: read, write III. Not supported: the secondary header's content (skipped). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Crc16 = __include("core/Crc16") +local Archive = __include("containers/Archive") +local MacFile = __include("containers/MacFile") + +-- ------------------------------------------------------------------------------------------------ contract +local MacBinary = { + name = "macbinary", + category = "archive", + extensions = { "bin", "macbin" }, + mime = { "application/x-macbinary" }, + deps = { "core/Err", "core/Bytes", "core/Crc16", "containers/Archive", "containers/MacFile" }, + caps = { decode = true, encode = true, forks = true, variants = { "I", "II", "III" } }, +} + +type DecodeOptions = { maxBytes: number? } -- default 2^30 +type EncodeOptions = { name: string? } + +-- ------------------------------------------------------------------------------------------------ sniff +local function version(b: buffer, o: number, len: number): string? + if len < 128 then + return nil + end + local u8 = function(i: number): number + return buffer.readu8(b, o + i) + end + if u8(0) ~= 0 or u8(74) ~= 0 then + return nil + end + local nameLen = u8(1) + if nameLen < 1 or nameLen > 63 then + return nil + end + local function be32(i: number): number + return u8(i) * 16777216 + u8(i + 1) * 65536 + u8(i + 2) * 256 + u8(i + 3) + end + local dlen, rlen = be32(83), be32(87) + if dlen > 0x7FFFFFFF or rlen > 0x7FFFFFFF then + return nil + end + local crc = u8(124) * 256 + u8(125) + if crc == Crc16.ccitt(b, o, 124) and (crc ~= 0 or u8(122) >= 129) then + return if buffer.readstring(b, o + 102, 4) == "mBIN" then "III" else "II" + end + if buffer.readstring(b, o + 102, 4) == "mBIN" then + return nil -- III with a bad CRC + end + -- MacBinary I: byte 82 zero, bytes 99..125 zero, the forks within the file + if u8(82) ~= 0 then + return nil + end + for i = 99, 125 do + if u8(i) ~= 0 then + return nil + end + end + local need = 128 + math.ceil(dlen / 128) * 128 + rlen + return if need <= len + 127 then "I" else nil +end + +function MacBinary.sniff(r: Bytes.Reader): number + local n = math.min(r:remaining(), 128) + if n < 128 then + return 0 + end + local v = version(r.buf, r.base + r.pos, r.limit - r.base - r.pos) + return if v == "III" then 0.95 elseif v == "II" then 0.8 elseif v == "I" then 0.3 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function encoder(a: any, o: any?): (buffer?, Err.Err?) + return MacBinary.encode(a, o) +end + +local function pad(n: number): number + return math.ceil(n / 128) * 128 +end + +function MacBinary.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + local len = r.limit - r.base + local v = version(r.buf, r.base, len) + if not v then + if len >= 128 and buffer.readstring(r.buf, r.base + 102, 4) == "mBIN" then + return nil, Err.new(Err.CHECKSUM, "header CRC mismatch") + end + return nil, Err.new(if len < 128 then Err.TRUNCATED else Err.CORRUPT, "not a MacBinary header") + end + local h = r:sub(0, 128) + h:seek(1) + local name = h:string(h:u8()) + h:seek(65) + local ftype, creator = h:string(4), h:string(4) + local flagsHi = h:u8() + h:seek(83) + local dlen, rlen = h:u32be(), h:u32be() + local created, modified = h:u32be(), h:u32be() + local commentLen = h:u16be() + local flagsLo = h:u8() + h:seek(120) + local secondary = h:u16be() + if v == "I" then + commentLen, flagsLo, secondary = 0, 0, 0 + end + if dlen + rlen > (o.maxBytes or 2 ^ 30) then + return nil, Err.new(Err.LIMIT, "forks larger than maxBytes") + end + r:seek(128 + pad(secondary)) + local data = r:bytes(dlen) + r:seek(128 + pad(secondary) + pad(dlen)) + local rsrc = r:bytes(rlen) + local comment: string? = nil + if commentLen > 0 and r:seek(128 + pad(secondary) + pad(dlen) + pad(rlen)) then + comment = MacFile.name(r:string(math.min(commentLen, r:remaining()))) + end + if r.err then + return nil, r.err + end + local a = Archive.new("macbinary", encoder) + MacFile.put(a, { + name = MacFile.name(name), + data = data, + rsrc = rsrc, + type = ftype, + creator = creator, + flags = flagsHi * 256 + flagsLo, + created = MacFile.fromMac(created), + modified = MacFile.fromMac(modified), + comment = comment, + }) + a.meta.stream = rlen == 0 + a.meta.source = { format = "macbinary", version = v } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function MacBinary.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local files, err = MacFile.collect(value, o.name) + if not files then + return nil, err + end + local f = files[1] + if not f then + return nil, Err.new(Err.ARG, "nothing to encode") + end + local name = MacFile.roman(f.name) + if #name < 1 or #name > 63 then + return nil, Err.new(Err.ARG, "the name must be 1..63 bytes") + end + local dlen, rlen = buffer.len(f.data), buffer.len(f.rsrc) + local comment = if f.comment then MacFile.roman(f.comment) else "" + local out = buffer.create(128 + pad(dlen) + pad(rlen) + #comment) + buffer.writeu8(out, 1, #name) + buffer.writestring(out, 2, name) + buffer.writestring(out, 65, f.type) + buffer.writestring(out, 69, f.creator) + buffer.writeu8(out, 73, bit32.rshift(f.flags, 8)) + local function be32(at: number, v: number) + buffer.writeu32(out, at, bit32.byteswap(v)) + end + be32(83, dlen) + be32(87, rlen) + be32(91, MacFile.toMac(f.created or f.modified)) + be32(95, MacFile.toMac(f.modified)) + buffer.writeu8(out, 99, bit32.rshift(#comment, 8)) + buffer.writeu8(out, 100, bit32.band(#comment, 255)) + buffer.writeu8(out, 101, bit32.band(f.flags, 255)) + buffer.writestring(out, 102, "mBIN") + buffer.writeu8(out, 122, 130) + buffer.writeu8(out, 123, 129) + local crc = Crc16.ccitt(out, 0, 124) + buffer.writeu8(out, 124, bit32.rshift(crc, 8)) + buffer.writeu8(out, 125, bit32.band(crc, 255)) + buffer.copy(out, 128, f.data) + buffer.copy(out, 128 + pad(dlen), f.rsrc) + buffer.writestring(out, 128 + pad(dlen) + pad(rlen), comment) + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- new() -> an empty MacBinary Archive: a:add(name, data); add "name.rsrc" for a resource fork +function MacBinary.new(): any + local a = Archive.new("macbinary", encoder) + a.meta.source = { format = "macbinary" } + return a +end + +return MacBinary +end +__FILES["archive/mpq"] = function() + +-- archive/mpq: Blizzard MPQ ("The MoPaQ Archive Format", Olbrantz / Roy; StormLib docs; no code taken). Supports: +-- header v1-4, hash / block / hi-block tables, prefixed archives, (listfile), encrypted files, imploded and zlib / +-- PKWARE / bzip2 / LZMA / sparse sectors. Not supported: Huffman / ADPCM sectors, patch files, HET / BET, writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Archive = __include("containers/Archive") +local Deflate = __include("codecs/compress/Deflate") +local Bzip2 = __include("codecs/compress/Bzip2") +local Lzma = __include("codecs/compress/Lzma") +local Explode = __include("codecs/compress/Explode") +local Crypt = __include("archive/mpq/Crypt") + +-- ------------------------------------------------------------------------------------------------ contract +local Mpq = { + name = "mpq", + category = "archive", + extensions = { "mpq", "w3x", "w3m", "sc2map", "sc2data", "s2ma", "scm", "scx" }, + mime = { "application/x-mpq" }, + deps = { "core/Err", "core/Bytes", "containers/Archive", "codecs/compress/Deflate", "codecs/compress/Bzip2", "codecs/compress/Lzma", "codecs/compress/Explode" }, + caps = { decode = true, encode = false, versions = { 1, 2, 3, 4 }, methods = { "zlib", "implode", "bzip2", "lzma", "sparse" }, encryption = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + names: { string }?, + maxEntries: number?, -- default 1e6 + maxBytes: number?, -- default 2^30 +} + +-- ------------------------------------------------------------------------------------------------ constants +local FLAG_IMPLODE, FLAG_COMPRESS, FLAG_ENCRYPTED, FLAG_FIX_KEY = 0x100, 0x200, 0x10000, 0x20000 +local FLAG_PATCH, FLAG_SINGLE, FLAG_DELETE, FLAG_CRC, FLAG_EXISTS = 0x100000, 0x1000000, 0x2000000, 0x4000000, 0x80000000 +local KEY_HASH_TABLE, KEY_BLOCK_TABLE = Crypt.hash("(hash table)", 3), Crypt.hash("(block table)", 3) +local TWO32 = 4294967296 +local band = bit32.band + +-- ------------------------------------------------------------------------------------------------ sniff +function Mpq.sniff(r: Bytes.Reader): number + local m = r:peek(4) + if m == "MPQ\x1A" or m == "MPQ\x1B" then + return 1 + end + -- a prefixed archive (an installer stub): the header on a 512-byte boundary in the first 64 KB + for at = 512, math.min(65536, r:remaining() - 32), 512 do + if r:peek(4, at) == "MPQ\x1A" then + return 0.6 + end + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- sparse: a big-endian u32 size, then runs: 0x80 | (n - 1) followed by n bytes, or n - 3 meaning n zeros +local function unsparse(b: buffer, at: number, n: number, want: number): (buffer?, string?) + local out = buffer.create(want) + local p, stop, o = at + 4, at + n, 0 + while p < stop and o < want do + local c = buffer.readu8(b, p) + p += 1 + if c >= 0x80 then + local k = c - 0x7F + if p + k > stop then + return nil, "sparse run past the end" + end + k = math.min(k, want - o) + buffer.copy(out, o, b, p, k) + p += k + o += k + else + o = math.min(want, o + c + 3) + end + end + return out, nil +end + +local function decompress(b: buffer, at: number, n: number, want: number): (buffer?, Err.Err?) + if n < 1 then + return nil, Err.new(Err.CORRUPT, "empty compressed sector") + end + local mask = buffer.readu8(b, at) + local cur: buffer, cat: number, cn: number = b, at + 1, n - 1 + if mask == 0x12 then + if cn < 14 or buffer.readu8(b, cat) ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "LZMA sector with a filter") + end + local props = buffer.readstring(b, cat + 1, 5) + local out, e = Lzma.lzma(b, cat + 14, cn - 14, props, want, { maxBytes = want }) + if not out then + return nil, e + end + return out, nil + end + if band(mask, 0xC1) ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, string.format("Huffman / ADPCM sector (mask 0x%02x)", mask)) + end + if band(mask, 0x10) ~= 0 then + local out, e = Bzip2.decompress(cur, cat, cn, { maxBytes = want }) + if not out then + return nil, e + end + cur, cat, cn = out, 0, buffer.len(out) + end + if band(mask, 0x08) ~= 0 then + local out, e = Explode.decompress(cur, cat, cn, want) + if not out then + return nil, e + end + cur, cat, cn = out, 0, buffer.len(out) + end + if band(mask, 0x02) ~= 0 then + local out, e = Deflate.zlib(cur, cat, cn) + if not out then + return nil, e + end + cur, cat, cn = out, 0, buffer.len(out) + end + if band(mask, 0x20) ~= 0 then + local out, msg = unsparse(cur, cat, cn, want) + if not out then + return nil, Err.from(msg) + end + cur, cat, cn = out, 0, buffer.len(out) + end + if band(mask, 0x3A) ~= mask then + return nil, Err.new(Err.UNSUPPORTED, string.format("compression mask 0x%02x", mask)) + end + if cn ~= want then + return nil, Err.new(Err.CORRUPT, "sector decompressed to " .. tostring(cn) .. " bytes, expected " .. tostring(want)) + end + if cur == b then + local len = cn :: number + local copy = buffer.create(len) + buffer.copy(copy, 0, b, cat, len) + return copy, nil + end + return cur, nil +end + +type Block = { offset: number, csize: number, size: number, flags: number } + +local function readFile(b: buffer, limit: number, blk: Block, at: number, name: string?, sectorSize: number, maxBytes: number): (buffer?, Err.Err?) + local flags = blk.flags + if band(flags, FLAG_PATCH) ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "patch files") + end + if blk.size > maxBytes then + return nil, Err.new(Err.LIMIT, "file of " .. blk.size .. " bytes") + end + if at + blk.csize > limit then + return nil, Err.new(Err.TRUNCATED, "file data past the end") + end + local encrypted = band(flags, FLAG_ENCRYPTED) ~= 0 + local key = 0 + if encrypted then + if not name then + return nil, Err.new(Err.UNSUPPORTED, "encrypted file without a known name") + end + key = Crypt.hash(Crypt.baseName(name), 3) + if band(flags, FLAG_FIX_KEY) ~= 0 then + key = bit32.bxor((key + blk.offset) % TWO32, blk.size % TWO32) + end + end + local compressed = band(flags, FLAG_COMPRESS + FLAG_IMPLODE) ~= 0 + local imploded = band(flags, FLAG_IMPLODE) ~= 0 + local function sector(src: buffer, sat: number, sn: number, want: number, k: number): (buffer?, Err.Err?) + local raw = buffer.create(sn) + buffer.copy(raw, 0, src, sat, sn) + if encrypted then + Crypt.decrypt(raw, 0, sn, k) + end + if compressed and sn < want then + if imploded then + return Explode.decompress(raw, 0, sn, want) + end + return decompress(raw, 0, sn, want) + end + if sn ~= want then + if sn > want then + local cut = buffer.create(want) + buffer.copy(cut, 0, raw, 0, want) + return cut, nil + end + return nil, Err.new(Err.CORRUPT, "stored sector of " .. sn .. " bytes, expected " .. want) + end + return raw, nil + end + if band(flags, FLAG_SINGLE) ~= 0 then + local out, e = sector(b, at, blk.csize, blk.size, key) + if out and buffer.len(out) ~= blk.size then + return nil, Err.new(Err.CORRUPT, "file size mismatch") + end + return out, e + end + local out = buffer.create(blk.size) + local nsec = (blk.size + sectorSize - 1) // sectorSize + if not compressed then + -- stored in sectors (each decrypted with key + its index) + for i = 0, nsec - 1 do + local want = math.min(sectorSize, blk.size - i * sectorSize) + local s, e = sector(b, at + i * sectorSize, want, want, key + i) + if not s then + return nil, e + end + buffer.copy(out, i * sectorSize, s, 0, want) + end + return out, nil + end + local entries = nsec + 1 + (if band(flags, FLAG_CRC) ~= 0 then 1 else 0) + if entries * 4 > blk.csize then + return nil, Err.new(Err.CORRUPT, "sector table larger than the file") + end + local tbl = buffer.create(entries * 4) + buffer.copy(tbl, 0, b, at, entries * 4) + if encrypted then + Crypt.decrypt(tbl, 0, entries * 4, (key - 1) % TWO32) + end + for i = 0, nsec - 1 do + local s0, s1 = buffer.readu32(tbl, i * 4), buffer.readu32(tbl, i * 4 + 4) + if s1 < s0 or s1 > blk.csize then + return nil, Err.new(Err.CORRUPT, "bad sector offset table") + end + local want = math.min(sectorSize, blk.size - i * sectorSize) + local s, e = sector(b, at + s0, s1 - s0, want, key + i) + if not s then + return nil, e + end + if buffer.len(s) ~= want then + return nil, Err.new(Err.CORRUPT, "sector " .. i .. " decompressed to " .. buffer.len(s) .. " bytes, expected " .. want) + end + buffer.copy(out, i * sectorSize, s, 0, want) + end + return out, nil +end + +local function encode(_archive: any, _opts: any?): (buffer?, Err.Err?) + return nil, Err.new(Err.UNSUPPORTED, "MPQ archives are read-only") +end + +local function findHeader(r: Bytes.Reader): number? + local size = r.limit - r.base + local p = 0 + while p + 32 <= size do + local m = buffer.readstring(r.buf, r.base + p, 4) + if m == "MPQ\x1A" then + return p + elseif m == "MPQ\x1B" and p + 12 <= size then + local at = p + buffer.readu32(r.buf, r.base + p + 8) + if at + 32 <= size and buffer.readstring(r.buf, r.base + at, 4) == "MPQ\x1A" then + return at + end + end + p += 512 + end + return nil +end + +function Mpq.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local found = findHeader(r) + if not found then + return nil, Err.new(if r:remaining() < 32 then Err.TRUNCATED else Err.CORRUPT, "no MPQ header", 0) + end + local h: number = found + local hr = r:sub(h) + hr:skip(4) + local headerSize, archiveSize = hr:u32le(), hr:u32le() + local version, shift = hr:u16le(), hr:u16le() + local hashPos, blockPos, hashCount, blockCount = hr:u32le(), hr:u32le(), hr:u32le(), hr:u32le() + local hiBlockPos, hashHi, blockHi = 0, 0, 0 + if version >= 1 and headerSize >= 44 then + hiBlockPos = hr:u64le() + hashHi, blockHi = hr:u16le(), hr:u16le() + end + if hr.err then + return nil, hr.err + end + if shift > 20 then + return nil, Err.new(Err.CORRUPT, "bad sector size shift " .. shift, h + 14) + end + local sectorSize = 512 * 2 ^ shift + if hashCount == 0 then + return nil, Err.new(Err.UNSUPPORTED, "no classic hash table (HET / BET only)") + end + local maxEntries: number = opts and opts.maxEntries or 1e6 + if hashCount > maxEntries * 4 or blockCount > maxEntries then + return nil, Err.new(Err.LIMIT, "too many entries") + end + local size = r.limit - r.base + local hashAt = h + hashPos + hashHi * TWO32 + local blockAt = h + blockPos + blockHi * TWO32 + if hashAt + hashCount * 16 > size or blockAt + blockCount * 16 > size then + return nil, Err.new(Err.TRUNCATED, "hash / block table past the end", h + 16) + end + local hashes = buffer.create(hashCount * 16) + buffer.copy(hashes, 0, r.buf, r.base + hashAt, hashCount * 16) + Crypt.decrypt(hashes, 0, hashCount * 16, KEY_HASH_TABLE) + local blocksBuf = buffer.create(blockCount * 16) + buffer.copy(blocksBuf, 0, r.buf, r.base + blockAt, blockCount * 16) + Crypt.decrypt(blocksBuf, 0, blockCount * 16, KEY_BLOCK_TABLE) + local hiAt = if hiBlockPos > 0 then h + hiBlockPos else -1 + if hiAt >= 0 and hiAt + blockCount * 2 > size then + hiAt = -1 + end + local blocks: { Block } = {} + for i = 0, blockCount - 1 do + local hi = if hiAt >= 0 then buffer.readu16(r.buf, r.base + hiAt + i * 2) else 0 + blocks[i + 1] = { + offset = buffer.readu32(blocksBuf, i * 16) + hi * TWO32, + csize = buffer.readu32(blocksBuf, i * 16 + 4), + size = buffer.readu32(blocksBuf, i * 16 + 8), + flags = buffer.readu32(blocksBuf, i * 16 + 12), + } + end + local maxBytes = opts and opts.maxBytes or 2 ^ 30 + local mask = hashCount - 1 + local pow2 = band(hashCount, mask) == 0 + local function lookup(name: string): number? + local h0, h1, h2 = Crypt.hash(name, 0), Crypt.hash(name, 1), Crypt.hash(name, 2) + local start = if pow2 then band(h0, mask) else h0 % hashCount + for k = 0, hashCount - 1 do + local o = ((start + k) % hashCount) * 16 + local bi = buffer.readu32(hashes, o + 12) + if bi == 0xFFFFFFFF then + return nil + end + if bi ~= 0xFFFFFFFE and buffer.readu32(hashes, o) == h1 and buffer.readu32(hashes, o + 4) == h2 and bi < blockCount then + return bi + 1 + end + end + return nil + end + local function usable(bi: number): boolean + local f = blocks[bi].flags + return band(f, FLAG_EXISTS) ~= 0 and band(f, FLAG_DELETE) == 0 + end + local function blockData(bi: number, name: string?): (buffer?, Err.Err?) + local blk = blocks[bi] + return readFile(r.buf, r.limit, blk, r.base + h + blk.offset, name, sectorSize, maxBytes) + end + local names: { string } = {} + for _, internal in { "(attributes)", "(signature)", "(user data)" } do + table.insert(names, internal) + end + local lf = lookup("(listfile)") + if lf and usable(lf) then + table.insert(names, "(listfile)") + local data = blockData(lf, "(listfile)") + if data then + for line in string.gmatch(buffer.tostring(data), "[^\r\n;]+") do + local nm = string.match(line, "^%s*(.-)%s*$") + if nm and nm ~= "" then + table.insert(names, nm) + end + end + end + end + if opts and type(opts.names) == "table" then + for _, nm in opts.names do + if type(nm) == "string" then + table.insert(names, nm) + end + end + end + local a = Archive.new("mpq", encode) + local named: { [number]: string } = {} + local function add(bi: number, name: string?) + local blk = blocks[bi] + local entryName = name or string.format("File%08d.xxx", bi - 1) + Archive.put(a, { + name = entryName, + size = blk.size, + compressedSize = blk.csize, + dir = false, + method = if band(blk.flags, FLAG_IMPLODE) ~= 0 then "implode" elseif band(blk.flags, FLAG_COMPRESS) ~= 0 then "compress" else "store", + encrypted = band(blk.flags, FLAG_ENCRYPTED) ~= 0, + flags = blk.flags, + block = bi - 1, + load = function(): (buffer?, Err.Err?) + return blockData(bi, name) + end, + }) + end + for _, nm in names do + local bi = lookup(nm) + if bi and usable(bi) and not named[bi] then + named[bi] = nm + add(bi, nm) + end + end + for bi = 1, blockCount do + if not named[bi] and usable(bi) and blocks[bi].size > 0 then + add(bi, nil) + end + end + a.meta.source = { format = "mpq", version = version + 1, sectorSize = sectorSize, offset = h, archiveSize = archiveSize, hashTable = hashCount, blockTable = blockCount } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ extras +Mpq.hash = Crypt.hash + +return Mpq +end +__FILES["archive/mpq/Crypt"] = @native function() + + +-- archive/mpq/Crypt: the MPQ encryption table, name hash (0 = table index, 1 / 2 = name check, 3 = file key) and +-- block decryption, from "The MoPaQ Archive Format" (Olbrantz / Roy) and StormLib's docs; no code taken. Mod 2^32. +local readu32, writeu32 = buffer.readu32, buffer.writeu32 +local bxor, band, bor, lshift, rshift, bnot = bit32.bxor, bit32.band, bit32.bor, bit32.lshift, bit32.rshift, bit32.bnot + +local Crypt = {} + +local TWO32 = 4294967296 +local TABLE = buffer.create(0x500 * 4) +do + local seed = 0x00100001 + for i1 = 0, 255 do + local i2 = i1 + for _ = 0, 4 do + seed = (seed * 125 + 3) % 0x2AAAAB + local t1 = band(seed, 0xFFFF) * 65536 + seed = (seed * 125 + 3) % 0x2AAAAB + local t2 = band(seed, 0xFFFF) + writeu32(TABLE, i2 * 4, t1 + t2) + i2 += 0x100 + end + end +end + +-- name hash: ASCII upper case, '/' as '\' +@native function Crypt.hash(name: string, kind: number): number + local s1, s2 = 0x7FED7FED, 0xEEEEEEEE + local base = kind * 0x100 + for i = 1, #name do + local c = string.byte(name, i) + if c >= 97 and c <= 122 then + c -= 32 + elseif c == 47 then + c = 92 + end + s1 = bxor(readu32(TABLE, (base + c) * 4), (s1 + s2) % TWO32) + s2 = (c + s1 + s2 + lshift(s2, 5) + 3) % TWO32 + end + return s1 +end + +-- whole u32s; a trailing partial word is left as is +@native function Crypt.decrypt(buf: buffer, at: number, n: number, key: number) + local s2 = 0xEEEEEEEE + local k = key % TWO32 + for i = 0, n // 4 - 1 do + local o = at + i * 4 + s2 = (s2 + readu32(TABLE, (0x400 + band(k, 0xFF)) * 4)) % TWO32 + local ch = bxor(readu32(buf, o), (k + s2) % TWO32) + k = bor((lshift(bnot(k), 0x15) + 0x11111111) % TWO32, rshift(k, 0x0B)) + s2 = (ch + s2 + lshift(s2, 5) + 3) % TWO32 + writeu32(buf, o, ch) + end +end + +-- the file key uses the base name +@native function Crypt.baseName(name: string): string + return string.match(name, "([^\\/]*)$") or name +end + +return Crypt +end +__FILES["archive/pak"] = function() + +-- archive/pak: Quake / Quake II / Half-Life PAK ("PACK": 56-byte names, 64-byte entries) and SiN ("SPAK": 120-byte +-- names), from Quake's common.c (dpackheader_t / dpackfile_t) and the Quake specs; no code taken. Supports: read +-- (lazy), write. Not supported: Daikatana's compressed entries. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Sniff = __include("core/Sniff") +local Archive = __include("containers/Archive") + +-- ------------------------------------------------------------------------------------------------ contract +local Pak = { + name = "pak", + category = "archive", + extensions = { "pak", "sin" }, + mime = { "application/x-pak" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "containers/Archive" }, + caps = { decode = true, encode = true, variants = { "quake", "sin" } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { maxEntries: number? } -- default 1e6 +type EncodeOptions = { variant: ("quake" | "sin")? } -- default: the source variant, else "quake" + +-- ------------------------------------------------------------------------------------------------ constants +local VARIANTS = { quake = { magic = "PACK", nameLen = 56 }, sin = { magic = "SPAK", nameLen = 120 } } + +-- ------------------------------------------------------------------------------------------------ sniff +function Pak.sniff(r: Bytes.Reader): number + if r:remaining() < 12 then + return 0 + end + return math.max(Sniff.magic(r, "PACK", 0, 0.9), Sniff.magic(r, "SPAK", 0, 0.9)) +end + +-- ------------------------------------------------------------------------------------------------ decode +local function encode(archive: any, opts: any?): (buffer?, Err.Err?) + return Pak.encode(archive, opts) +end + +function Pak.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local magic = r:string(4) + local dirOfs, dirLen = r:u32le(), r:u32le() + if r.err then + return nil, r.err + end + local variant = if magic == "PACK" then "quake" elseif magic == "SPAK" then "sin" else nil + if not variant then + return nil, Err.new(Err.CORRUPT, "bad magic", 0) + end + local nameLen = VARIANTS[variant].nameLen + local entrySize = nameLen + 8 + local size = r.limit - r.base + if dirOfs + dirLen > size then + return nil, Err.new(Err.TRUNCATED, "directory past the end", 4) + end + if dirLen % entrySize ~= 0 then + return nil, Err.new(Err.CORRUPT, "directory size is not a multiple of " .. entrySize, 8) + end + local count = dirLen // entrySize + if count > (opts and opts.maxEntries or 1e6) then + return nil, Err.new(Err.LIMIT, "too many entries: " .. count) + end + local a = Archive.new("pak", encode) + local d = r:sub(dirOfs, dirLen) + for i = 0, count - 1 do + local name = d:fixed(nameLen) + local at, n = d:u32le(), d:u32le() + if d.err then + return nil, d.err + end + if at + n > size then + return nil, Err.new(Err.TRUNCATED, "entry " .. name .. " past the end", dirOfs + i * entrySize) + end + Archive.put(a, { name = name, size = n, dir = false, method = "store", offset = at, load = Archive.slice(r.buf, r.base + at, n) }) + end + a.meta.source = { format = "pak", variant = variant, entries = count } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Pak.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local items, err = Archive.collect(archive) + if not items then + return nil, err + end + local src = type(archive) == "table" and type(archive.meta) == "table" and archive.meta.source + local variant = opts and opts.variant or (if type(src) == "table" and src.format == "pak" then src.variant else nil) or "quake" + local v = VARIANTS[variant] + if not v then + return nil, Err.new(Err.ARG, "unknown variant " .. tostring(variant)) + end + local files: { { name: string, data: buffer } } = {} + for _, it in items do + if not it.entry.dir then + local name = string.gsub(it.entry.name, "\\", "/") + if #name >= v.nameLen then + return nil, Err.new(Err.ARG, "name longer than " .. (v.nameLen - 1) .. " bytes: " .. name) + end + table.insert(files, { name = name, data = it.data }) + end + end + local w = Bytes.writer() + w:string(v.magic) + w:u32le(0) + w:u32le(0) + local offsets: { number } = {} + for i, f in files do + offsets[i] = w:tell() + w:bytes(f.data) + end + local dirOfs = w:tell() + for i, f in files do + w:string(f.name) + w:fill(0, v.nameLen - #f.name) + w:u32le(offsets[i]) + w:u32le(buffer.len(f.data)) + end + w:setU32le(4, dirOfs) + w:setU32le(8, w:tell() - dirOfs) + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +function Pak.new(variant: ("quake" | "sin")?): any + local a = Archive.new("pak", encode) + a.meta.source = { format = "pak", variant = variant or "quake" } + return a +end + +return Pak +end +__FILES["archive/rpm"] = function() + +-- archive/rpm: RPM v3 / v4 (rpm.org, LSB package format; no code ported): 96-byte lead, signature header (8-byte +-- aligned), main header; the payload (gzip / bzip2 / xz / lzma / zstd / none) is cpio; %ghost files not listed. +-- Not supported: writing, signature / digest checks, "stripped cpio" (files over 4 GiB), delta rpms. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Deflate = __include("codecs/compress/Deflate") +local Lzma = __include("codecs/compress/Lzma") +local Zstd = __include("codecs/compress/Zstd") +local Bzip2 = __include("codecs/compress/Bzip2") +local Archive = __include("containers/Archive") +local Cpio = __include("containers/Cpio") + +-- ------------------------------------------------------------------------------------------------ contract +local Rpm = { + name = "rpm", + category = "archive", + extensions = { "rpm" }, + mime = { "application/x-rpm" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/compress/Lzma", "codecs/compress/Zstd", "codecs/compress/Bzip2", "containers/Archive", "containers/Cpio" }, + caps = { decode = true, encode = false, compressors = { "gzip", "bzip2", "xz", "lzma", "zstd" } }, +} + +type DecodeOptions = { + maxBytes: number?, -- default 2^30 + maxEntries: number?, -- default 1e6 +} + +-- ------------------------------------------------------------------------------------------------ constants +local LEAD_MAGIC = "\237\171\238\219" +local HEADER_MAGIC = "\142\173\232\1" +local RPMFILE_GHOST = 64 + +local NAMES: { [number]: string } = { + [1000] = "name", + [1001] = "version", + [1002] = "release", + [1003] = "epoch", + [1004] = "summary", + [1005] = "description", + [1006] = "buildtime", + [1007] = "buildhost", + [1009] = "size", + [1010] = "distribution", + [1011] = "vendor", + [1014] = "license", + [1015] = "packager", + [1016] = "group", + [1020] = "url", + [1021] = "os", + [1022] = "arch", + [1044] = "sourcerpm", + [1047] = "provides", + [1049] = "requires", + [1124] = "payloadFormat", + [1125] = "payloadCompressor", + [1126] = "payloadFlags", + [5009] = "longsize", +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Rpm.sniff(r: Bytes.Reader): number + return if r:peek(4) == LEAD_MAGIC then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function header(b: buffer, p: number, e: number): (any, any) + if p + 16 > e then + return nil, Err.new(Err.TRUNCATED, "header past the end", p) + end + if buffer.readstring(b, p, 4) ~= HEADER_MAGIC then + return nil, Err.new(Err.CORRUPT, "bad header magic", p) + end + local n = bit32.byteswap(buffer.readu32(b, p + 8)) + local hsize = bit32.byteswap(buffer.readu32(b, p + 12)) + local index = p + 16 + local store = index + n * 16 + if n > 0x10000 or hsize > 0x10000000 then + return nil, Err.new(Err.LIMIT, "header too large", p) + end + if store + hsize > e then + return nil, Err.new(Err.TRUNCATED, "header data past the end", p) + end + local tags: { [number]: any } = {} + local se = store + hsize + for i = 0, n - 1 do + local q = index + i * 16 + local tag = bit32.byteswap(buffer.readu32(b, q)) + local typ = bit32.byteswap(buffer.readu32(b, q + 4)) + local off = bit32.byteswap(buffer.readu32(b, q + 8)) + local count = bit32.byteswap(buffer.readu32(b, q + 12)) + local d = store + off + if off > hsize then + return nil, Err.new(Err.CORRUPT, "tag data outside the header", q) + end + local width = if typ == 2 or typ == 1 then 1 elseif typ == 3 then 2 elseif typ == 4 then 4 elseif typ == 5 then 8 else 0 + if width > 0 then + if d + count * width > se then + return nil, Err.new(Err.CORRUPT, "tag data outside the header", q) + end + local v = table.create(count) + for k = 0, count - 1 do + local x = d + k * width + v[k + 1] = if width == 1 then buffer.readu8(b, x) + elseif width == 2 then bit32.bor(bit32.lshift(buffer.readu8(b, x), 8), buffer.readu8(b, x + 1)) + elseif width == 4 then bit32.byteswap(buffer.readu32(b, x)) + else bit32.byteswap(buffer.readu32(b, x)) * 4294967296 + bit32.byteswap(buffer.readu32(b, x + 4)) + end + tags[tag] = v + elseif typ == 7 then + if d + count > se then + return nil, Err.new(Err.CORRUPT, "tag data outside the header", q) + end + tags[tag] = buffer.readstring(b, d, count) + elseif typ == 6 or typ == 8 or typ == 9 then + local v = {} + local s = d + local want = if typ == 6 then 1 else count + if want > hsize then + return nil, Err.new(Err.CORRUPT, "bad string count", q) + end + for _ = 1, want do + local z = s + while z < se and buffer.readu8(b, z) ~= 0 do + z += 1 + end + if z >= se then + return nil, Err.new(Err.CORRUPT, "unterminated string", s) + end + table.insert(v, buffer.readstring(b, s, z - s)) + s = z + 1 + end + tags[tag] = if typ == 6 then v[1] else v + end + end + return tags, se +end + +local function files(tags: { [number]: any }): { any } + local names: { string } = {} + local bn, dn, di = tags[1117], tags[1118], tags[1116] + if type(bn) == "table" and type(dn) == "table" and type(di) == "table" then + for i, base in bn do + local d = dn[(di[i] or 0) + 1] + names[i] = (if type(d) == "string" then d else "") .. base + end + elseif type(tags[1027]) == "table" then + names = tags[1027] + end + local sizes = tags[5008] or tags[1028] or {} + local modes, mtimes, links = tags[1030] or {}, tags[1034] or {}, tags[1036] or {} + local users, groups, flags = tags[1039] or {}, tags[1040] or {}, tags[1037] or {} + local out = {} + for i, n in names do + table.insert(out, { + name = n, + size = sizes[i] or 0, + mode = modes[i] or 0, + mtime = mtimes[i] or 0, + link = if links[i] and links[i] ~= "" then links[i] else nil, + user = users[i], + group = groups[i], + flags = flags[i] or 0, + }) + end + return out +end + +local function strip(name: string): string + return (string.gsub(name, "^%.?/+", "")) +end + +local function payload(b: buffer, p: number, e: number, compressor: string?, o: DecodeOptions): (any, Err.Err?) + local n = e - p + local opts: any = { maxBytes = o.maxBytes or 2 ^ 30 } + local raw: buffer?, err: any + local m = if n >= 6 then buffer.readstring(b, p, 6) else "" + if string.sub(m, 1, 2) == "\31\139" then + raw, err = Deflate.gunzip(b, p, n) + elseif m == "\253" .. "7zXZ\0" then + raw, err = Lzma.xz(b, p, n, opts) + elseif string.sub(m, 1, 3) == "BZh" then + raw, err = Bzip2.decompress(b, p, n, opts) + elseif string.sub(m, 1, 4) == "\40\181\47\253" then + raw, err = Zstd.decompress(b, p, n, opts) + elseif compressor == "lzma" then + raw, err = Lzma.alone(b, p, n, opts) + elseif string.sub(m, 1, 5) == "07070" then + raw = buffer.create(n) + buffer.copy(raw :: buffer, 0, b, p, n) + else + return nil, Err.new(Err.UNSUPPORTED, "payload compressor " .. tostring(compressor), p) + end + if not raw then + return nil, err + end + if buffer.len(raw) >= 6 and buffer.readstring(raw, 0, 6) == "07070X" then + return nil, Err.new(Err.UNSUPPORTED, "stripped cpio payload (files over 4 GiB)") + end + local list, cerr = Cpio.read(raw, 0, nil, { maxEntries = o.maxEntries }) + if not list then + return nil, cerr + end + local by = {} + for _, ent in list do + by[strip(ent.name)] = ent + end + return { buf = raw, by = by }, nil +end + +function Rpm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + local b, base, e = r.buf, r.base, r.limit + if e - base < 96 then + return nil, Err.new(Err.TRUNCATED, "lead past the end", base) + end + if buffer.readstring(b, base, 4) ~= LEAD_MAGIC then + return nil, Err.new(Err.CORRUPT, "bad lead magic", base) + end + local major, minor = buffer.readu8(b, base + 4), buffer.readu8(b, base + 5) + local kind = bit32.bor(bit32.lshift(buffer.readu8(b, base + 6), 8), buffer.readu8(b, base + 7)) + local leadName = buffer.readstring(b, base + 10, 66) + leadName = string.match(leadName, "^[^%z]*") :: string + if major < 3 then + return nil, Err.new(Err.UNSUPPORTED, "rpm format version " .. major, base + 4) + end + local sig, sigEnd = header(b, base + 96, e) + if not sig then + return nil, sigEnd + end + local hp = base + (sigEnd - base + 7) // 8 * 8 + local tags, hEnd = header(b, hp, e) + if not tags then + return nil, hEnd + end + local a = Archive.new("rpm") + local info: { [string]: any } = { tags = tags, signature = sig, type = if kind == 1 then "source" else "binary", lead = { major = major, minor = minor, name = leadName } } + for tag, key in NAMES do + local v = tags[tag] + if type(v) == "table" and tag ~= 1047 and tag ~= 1049 then -- numbers and i18n strings: the first value + v = v[1] + end + info[key] = v + end + a.meta.rpm = info + a.meta.source = { format = "rpm", compressor = info.payloadCompressor } + if info.payloadFormat and info.payloadFormat ~= "cpio" then + return nil, Err.new(Err.UNSUPPORTED, "payload format " .. tostring(info.payloadFormat), hEnd) + end + local cache: any = nil + local cacheErr: Err.Err? = nil + local function entry(name: string): (any, Err.Err?) + if not cache and not cacheErr then + cache, cacheErr = payload(b, hEnd, e, info.payloadCompressor, o) + end + if not cache then + return nil, cacheErr + end + local ent = cache.by[name] + if not ent then + return nil, Err.new(Err.CORRUPT, "file " .. name .. " is not in the payload") + end + return ent, nil + end + local list = files(tags) + if #list > (o.maxEntries or 1e6) then + return nil, Err.new(Err.LIMIT, "too many files") + end + for _, f in list do + if bit32.band(f.flags, RPMFILE_GHOST) ~= 0 then + continue + end + local name = strip(f.name) + local typ = Cpio.TYPE_OF[bit32.band(f.mode, 0xF000)] or "0" + local data = typ == "0" and f.size > 0 + Archive.put(a, { + name = name, + size = if data then f.size else 0, + dir = typ == "5", + mtime = f.mtime, + mode = bit32.band(f.mode, 0xFFF), + type = typ, + link = if typ == "2" then f.link else nil, + uname = f.user, + gname = f.group, + method = if info.payloadCompressor then info.payloadCompressor else "store", + load = if data + then function(): (buffer?, Err.Err?) + local ent, err = entry(name) + if not ent then + return nil, err + end + local out = buffer.create(ent.size) + buffer.copy(out, 0, cache.buf, ent.offset, ent.size) + return out, nil + end + else nil, + }) + end + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ extras +function Rpm.cpio(r: Bytes.Reader, opts: DecodeOptions?): (buffer?, Err.Err?) + local a, err = Rpm.decode(r, opts) + if not a then + return nil, err + end + local p = r.base + 96 + local _, sigEnd = header(r.buf, p, r.limit) + local hp = r.base + (sigEnd - r.base + 7) // 8 * 8 + local _, hEnd = header(r.buf, hp, r.limit) + local pl, perr = payload(r.buf, hEnd, r.limit, a.meta.rpm.payloadCompressor, opts or {}) + if not pl then + return nil, perr + end + return pl.buf, nil +end + +return Rpm +end +__FILES["archive/tar"] = function() + +-- archive/tar: tar archives (ustar, pax, GNU long names; containers/Tar). Supports: read (lazy), write from any +-- Archive. Not supported: sparse files, multi-volume archives. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Archive = __include("containers/Archive") +local Tar = __include("containers/Tar") + +-- ------------------------------------------------------------------------------------------------ contract +local TarFormat = { + name = "tar", + category = "archive", + extensions = { "tar" }, + mime = { "application/x-tar" }, + deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Tar" }, + caps = { decode = true, encode = true, variants = { "ustar", "pax", "gnu" } }, +} + +type DecodeOptions = { maxEntries: number? } -- default 1e6 +type EncodeOptions = { format: ("pax" | "gnu" | "ustar")? } -- default "pax": ustar + pax records when needed + +-- ------------------------------------------------------------------------------------------------ sniff +function TarFormat.sniff(r: Bytes.Reader): number + if r:remaining() < 512 then + return 0 + end + if not Tar.valid(r.buf, r.pos) then + return 0 + end + return if r:peek(5, 257) == "ustar" then 0.95 else 0.6 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function lazy(b: buffer, at: number, n: number): () -> (buffer?, Err.Err?) + return function(): (buffer?, Err.Err?) + local out = buffer.create(n) + buffer.copy(out, 0, b, at, n) + return out, nil + end +end + +local function encode(archive: any, opts: any?): (buffer?, Err.Err?) + return TarFormat.encode(archive, opts) +end + +function TarFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local list, err = Tar.read(r.buf, r.base, r.limit - r.base, opts) + if not list then + return nil, err + end + local a = Archive.new("tar", encode) + for _, e in list do + Archive.put(a, { + name = e.name, + size = e.size, + dir = e.dir, + mtime = e.mtime, + mode = e.mode, + uid = e.uid, + gid = e.gid, + uname = e.uname, + gname = e.gname, + type = e.type, + link = e.link, + method = "store", + load = if e.dir or e.size == 0 then nil else lazy(r.buf, e.offset, e.size), + }) + end + a.meta.source = { format = "tar" } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function TarFormat.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local items = Archive.entries(archive) + if not items then + return nil, Err.new(Err.ARG, "expected an Archive") + end + local list: { Tar.WriteEntry } = {} + for _, it in items do + local e: any = it.entry + local data: buffer? = nil + if not e.dir and e.type ~= "1" and e.type ~= "2" then + local b, err = it.read() + if not b then + return nil, err + end + data = b + end + table.insert(list, { + name = e.name, + data = data, + dir = e.dir, + type = if type(e.type) == "string" and #e.type == 1 then e.type else nil, + link = if type(e.link) == "string" then e.link else nil, + mode = if type(e.mode) == "number" then e.mode else nil, + uid = if type(e.uid) == "number" then e.uid else nil, + gid = if type(e.gid) == "number" then e.gid else nil, + uname = if type(e.uname) == "string" then e.uname else nil, + gname = if type(e.gname) == "string" then e.gname else nil, + mtime = if type(e.mtime) == "number" then e.mtime else nil, + }) + end + return Tar.write(list, opts) +end + +-- ------------------------------------------------------------------------------------------------ extras +function TarFormat.new(): any + local a = Archive.new("tar", encode) + a.meta.source = { format = "tar" } + return a +end + +return TarFormat +end +__FILES["archive/uu"] = function() + +-- archive/uu: uuencode (POSIX), xxencode and GNU "begin-base64" blocks, one entry each (variant detected per block); +-- written as GNU sharutils does (45 bytes a line, "`" for zero; base64 60 characters + "===="). Not supported: postings +-- split over several files, yEnc (archive/yenc), BinHex (archive/binhex). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Base64 = __include("core/Base64") +local Archive = __include("containers/Archive") + +-- ------------------------------------------------------------------------------------------------ contract +local Uu = { + name = "uu", + category = "archive", + extensions = { "uu", "uue", "xxe", "b64" }, + mime = { "text/x-uuencode" }, + deps = { "core/Err", "core/Bytes", "core/Base64", "containers/Archive" }, + caps = { decode = true, encode = true, variants = { "uu", "xx", "base64" } }, +} + +type DecodeOptions = { maxBytes: number?, name: string? } -- default 2^30 +type EncodeOptions = { + variant: ("uu" | "xx" | "base64")?, -- default "uu" + mode: number?, -- default 0o644 + name: string?, +} + +-- ------------------------------------------------------------------------------------------------ constants +local XX = "+-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" +local XX_VALUE: { [number]: number } = {} +for i = 1, 64 do + XX_VALUE[string.byte(XX, i)] = i - 1 +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Uu.sniff(r: Bytes.Reader): number + local head = r:peek(4096) + if string.match(head, "^begin%-base64 [0-7]+ [^\r\n]") or string.match(head, "^begin [0-7]+ [^\r\n]") then + return 0.9 + end + if string.match(head, "\nbegin%-base64 [0-7]+ [^\r\n]") or string.match(head, "\nbegin [0-7][0-7][0-7]+ [^\r\n]") then + return 0.5 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function value(c: number, xx: boolean): number? + if xx then + return XX_VALUE[c] + end + if c >= 32 and c <= 96 then + return bit32.band(c - 32, 63) + end + return nil +end + +local function fits(line: string, xx: boolean): boolean + local n = value(string.byte(line, 1) or 0, xx) + if not n then + return false + end + local need = math.ceil(n / 3) * 4 + if #line - 1 < need or #line - 1 > need + 2 then + return false + end + for i = 2, need + 1 do + if not value(string.byte(line, i), xx) then + return false + end + end + return true +end + +local function decodeLines(lines: { string }, xx: boolean, maxBytes: number): (buffer?, string?) + local total = 0 + for _, l in lines do + total += value(string.byte(l, 1) or 0, xx) or 0 + end + if total > maxBytes then + return nil, "limit: data larger than maxBytes" + end + local out = buffer.create(total) + local o = 0 + for li, l in lines do + local n = value(string.byte(l, 1) or 0, xx) or 0 + local p = 2 + local left = n + while left > 0 do + local a = value(string.byte(l, p) or 0, xx) + local b = value(string.byte(l, p + 1) or 0, xx) + local c = value(string.byte(l, p + 2) or 0, xx) or 0 + local d = value(string.byte(l, p + 3) or 0, xx) or 0 + if not a or not b then + return nil, "bad character in line " .. li + end + local v = a * 262144 + b * 4096 + c * 64 + d + for k = 2, 0, -1 do + if left > 0 then + buffer.writeu8(out, o, bit32.band(bit32.rshift(v, k * 8), 255)) + o += 1 + left -= 1 + end + end + p += 4 + end + end + return out, nil +end + +type Block = { name: string, mode: number, variant: string, data: buffer } + +local function parse(text: string, maxBytes: number): ({ Block }?, string?) + local lines = string.split(text, "\n") + local blocks: { Block } = {} + local i = 1 + while i <= #lines do + local line = string.gsub(lines[i], "\r$", "") + local b64, mode, name = string.match(line, "^begin(%-base64) ([0-7]+) (.+)$") + if not b64 then + mode, name = string.match(line, "^begin ([0-7]+) (.+)$") + end + if mode and name then + local body: { string } = {} + local closed = false + i += 1 + while i <= #lines do + local l = string.gsub(lines[i], "\r$", "") + if (b64 and l == "====") or (not b64 and l == "end") then + closed = true + break + end + table.insert(body, l) + i += 1 + end + if not closed then + return nil, "truncated: block " .. name .. " has no end line" + end + local data, variant + if b64 then + local d, err = Base64.decode(table.concat(body)) + if not d then + return nil, "block " .. name .. ": " .. tostring(err) + end + data, variant = d, "base64" + else + -- drop the empty-line terminator ("`" / " " in uu, "+" in xx) and blank lines + local data_lines: { string } = {} + for _, l in body do + if l ~= "" then + table.insert(data_lines, l) + end + end + local uuOk, xxOk = true, true + for _, l in data_lines do + uuOk = uuOk and fits(l, false) + xxOk = xxOk and fits(l, true) + end + local xx = xxOk and not uuOk + if not uuOk and not xxOk then + return nil, "block " .. name .. ": lines are neither uuencode nor xxencode" + end + local d, err = decodeLines(data_lines, xx, maxBytes) + if not d then + return nil, err + end + data, variant = d, if xx then "xx" else "uu" + end + table.insert(blocks, { name = name, mode = tonumber(mode, 8) or 0, variant = variant, data = data }) + end + i += 1 + end + if #blocks == 0 then + return nil, "no begin line" + end + return blocks, nil +end + +local function encoder(a: any, o: any?): (buffer?, Err.Err?) + return Uu.encode(a, o) +end + +function Uu.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + local blocks, err = parse(buffer.readstring(r.buf, r.base, r.limit - r.base), o.maxBytes or 2 ^ 30) + if not blocks then + return nil, Err.from(err) + end + local a = Archive.new("uu", encoder) + for _, b in blocks do + Archive.put(a, { name = b.name, size = buffer.len(b.data), dir = false, mode = b.mode, variant = b.variant, method = b.variant, data = b.data }) + end + a.meta.stream = #a:list() == 1 + a.meta.source = { format = "uu", variant = blocks[1].variant } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function encodeLines(data: buffer, xx: boolean, out: { string }) + local n = buffer.len(data) + local function ch(v: number): string + if xx then + return string.sub(XX, v + 1, v + 1) + end + return if v == 0 then "`" else string.char(v + 32) + end + local p = 0 + while p < n do + local len = math.min(45, n - p) + local parts = { ch(len) } + for q = p, p + len - 1, 3 do + local b0 = buffer.readu8(data, q) + local b1 = if q + 1 < p + len then buffer.readu8(data, q + 1) else 0 + local b2 = if q + 2 < p + len then buffer.readu8(data, q + 2) else 0 + local v = b0 * 65536 + b1 * 256 + b2 + table.insert(parts, ch(bit32.rshift(v, 18)) .. ch(bit32.band(bit32.rshift(v, 12), 63)) .. ch(bit32.band(bit32.rshift(v, 6), 63)) .. ch(bit32.band(v, 63))) + end + table.insert(out, table.concat(parts)) + p += len + end + table.insert(out, ch(0)) +end + +function Uu.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local variant = o.variant or "uu" + if variant ~= "uu" and variant ~= "xx" and variant ~= "base64" then + return nil, Err.new(Err.ARG, "variant must be uu, xx or base64") + end + local files, err = Archive.files(value, o.name) + if not files then + return nil, err + end + if #files == 0 then + return nil, Err.new(Err.ARG, "nothing to encode") + end + local out: { string } = {} + for _, f in files do + if string.find(f.name, "[\r\n]") then + return nil, Err.new(Err.ARG, "file names may not contain line breaks") + end + local mode = if type(f.entry.mode) == "number" then f.entry.mode else (o.mode or 0x1A4) + local m = string.format("%o", bit32.band(mode, 0xFFF)) + if variant == "base64" then + table.insert(out, "begin-base64 " .. m .. " " .. f.name) + local s = Base64.encode(f.data) + for p = 1, #s, 60 do + table.insert(out, string.sub(s, p, p + 59)) + end + table.insert(out, "====") + else + table.insert(out, "begin " .. m .. " " .. f.name) + encodeLines(f.data, variant == "xx", out) + table.insert(out, "end") + end + end + return buffer.fromstring(table.concat(out, "\n") .. "\n"), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +function Uu.new(): any + local a = Archive.new("uu", encoder) + a.meta.source = { format = "uu" } + return a +end + +return Uu +end +__FILES["archive/vpk"] = function() + +-- archive/vpk: Valve VPK v1 / v2 directory files (Valve Developer Community page; no code taken): preload bytes, +-- embedded (index 0x7fff) or part-file data ("<name>_NNN.vpk"), CRC-32 checked; writes one self-contained v2 file +-- with its MD5s. Not supported: Respawn (Titanfall) VPKs, signature checks, writing multi-part archives. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Input = __include("core/Input") +local Crc32 = __include("core/Crc32") +local Md5 = __include("core/Md5") +local Archive = __include("containers/Archive") + +-- ------------------------------------------------------------------------------------------------ contract +local Vpk = { + name = "vpk", + category = "archive", + extensions = { "vpk" }, + mime = { "application/x-vpk" }, + deps = { "core/Err", "core/Bytes", "core/Input", "core/Crc32", "core/Md5", "containers/Archive" }, + caps = { decode = true, encode = true, versions = { 1, 2 }, multipart = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + verify: boolean?, -- default true + resolve: ((name: string) -> (buffer | string)?)?, + files: { [string]: buffer | string }?, + name: string?, -- "pak01_dir.vpk" -> "pak01_000.vpk" + maxEntries: number?, -- default 1e6 +} +type EncodeOptions = { version: number? } -- 1 or 2 (default: the source's, else 2) + +-- ------------------------------------------------------------------------------------------------ constants +local SIGNATURE = 0x55AA1234 +local EMBEDDED = 0x7FFF + +-- ------------------------------------------------------------------------------------------------ sniff +function Vpk.sniff(r: Bytes.Reader): number + if r:remaining() < 12 or r:peek(4) ~= "\x34\x12\xAA\x55" then + return 0 + end + local v = r:peekU8(4) + return if v == 1 or v == 2 then 1 else 0.5 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function encode(archive: any, opts: any?): (buffer?, Err.Err?) + return Vpk.encode(archive, opts) +end + +local function partLoader(opts: DecodeOptions?): (number) -> (buffer?, Err.Err?) + local cache: { [number]: buffer } = {} + local prefix = "pak01" + if opts and type(opts.name) == "string" then + local base = string.match(opts.name, "([^/\\]+)$") or opts.name + prefix = string.match(base, "^(.*)_dir%.[vV][pP][kK]$") or string.match(base, "^(.*)%.[vV][pP][kK]$") or base + end + return function(index: number): (buffer?, Err.Err?) + local hit = cache[index] + if hit then + return hit, nil + end + local name = string.format("%s_%03d.vpk", prefix, index) + local b = Input.sibling(opts, name) + if not b then + return nil, Err.new(Err.UNSUPPORTED, "part file " .. name .. " not available (opts.resolve / opts.files)") + end + cache[index] = b + return b, nil + end +end + +local function loader(r: Bytes.Reader, e: any, dataBase: number, part: (number) -> (buffer?, Err.Err?), verify: boolean): () -> (buffer?, Err.Err?) + return function(): (buffer?, Err.Err?) + local src: buffer, at: number + if e.archiveIndex == EMBEDDED then + src, at = r.buf, r.base + dataBase + e.archiveOffset + if dataBase + e.archiveOffset + e.length > r.limit - r.base then + return nil, Err.new(Err.TRUNCATED, "entry " .. e.name .. " past the end") + end + else + local b, err = part(e.archiveIndex) + if not b then + return nil, err + end + src, at = b, e.archiveOffset + if at + e.length > buffer.len(b) then + return nil, Err.new(Err.TRUNCATED, "entry " .. e.name .. " past the end of part " .. e.archiveIndex) + end + end + local out = buffer.create(e.preloadLength + e.length) + buffer.copy(out, 0, r.buf, e.preloadAt, e.preloadLength) + buffer.copy(out, e.preloadLength, src, at, e.length) + if verify and Crc32.of(out) ~= e.crc32 then + return nil, Err.new(Err.CHECKSUM, "entry " .. e.name .. ": CRC-32 mismatch") + end + return out, nil + end +end + +function Vpk.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local sig, version, treeSize = r:u32le(), r:u32le(), r:u32le() + if r.err then + return nil, r.err + end + if sig ~= SIGNATURE then + return nil, Err.new(Err.CORRUPT, "bad signature", 0) + end + if version ~= 1 and version ~= 2 then + return nil, Err.new(Err.UNSUPPORTED, "VPK version " .. version, 4) + end + local v2: any = nil + if version == 2 then + v2 = { fileDataSize = r:u32le(), archiveMd5Size = r:u32le(), otherMd5Size = r:u32le(), signatureSize = r:u32le() } + if r.err then + return nil, r.err + end + end + local headerLen = r:tell() - r.base + if headerLen + treeSize > r.limit - r.base then + return nil, Err.new(Err.TRUNCATED, "tree past the end", 8) + end + local t = r:sub(headerLen, treeSize) + local a = Archive.new("vpk", encode) + local part = partLoader(opts) + local verify = not (opts and opts.verify == false) + local maxEntries = opts and opts.maxEntries or 1e6 + local count = 0 + local parts: { [number]: boolean } = {} + local dataBase = headerLen + treeSize + while true do + local ext = t:cstring() + if t.err then + return nil, t.err + end + if ext == "" then + break + end + while true do + local path = t:cstring() + if t.err then + return nil, t.err + end + if path == "" then + break + end + while true do + local name = t:cstring() + if t.err then + return nil, t.err + end + if name == "" then + break + end + local e: any = { crc32 = t:u32le(), preloadLength = t:u16le(), archiveIndex = t:u16le(), archiveOffset = t:u32le(), length = t:u32le() } + local term = t:u16le() + e.preloadAt = t.pos + t:skip(e.preloadLength) + if t.err then + return nil, t.err + end + if term ~= 0xFFFF then + return nil, Err.new(Err.CORRUPT, "bad entry terminator", t:tell() + headerLen) + end + count += 1 + if count > maxEntries then + return nil, Err.new(Err.LIMIT, "too many entries") + end + local full = (if path == " " then "" else path .. "/") .. name .. (if ext == " " then "" else "." .. ext) + e.name = full + if e.archiveIndex ~= EMBEDDED then + parts[e.archiveIndex] = true + end + Archive.put(a, { + name = full, + size = e.preloadLength + e.length, + dir = false, + method = "store", + crc32 = e.crc32, + archiveIndex = if e.archiveIndex == EMBEDDED then nil else e.archiveIndex, + preload = e.preloadLength, + load = loader(r, e, dataBase, part, verify), + }) + end + end + end + local partList: { number } = {} + for k in parts do + table.insert(partList, k) + end + table.sort(partList) + a.meta.source = { format = "vpk", version = version, entries = count, parts = partList } + if v2 then + local md5At = dataBase + v2.fileDataSize + if v2.otherMd5Size == 48 and md5At + v2.archiveMd5Size + 48 <= r.limit - r.base then + local m = r:sub(md5At + v2.archiveMd5Size, 48) + v2.treeMd5, v2.chunkHashesMd5, v2.fileMd5 = m:string(16), m:string(16), m:string(16) + end + a.meta.source.v2 = v2 + end + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Vpk.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local items, err = Archive.collect(archive) + if not items then + return nil, err + end + local src = type(archive) == "table" and type(archive.meta) == "table" and archive.meta.source + local version = opts and opts.version or (if type(src) == "table" and src.format == "vpk" then src.version else nil) or 2 + if version ~= 1 and version ~= 2 then + return nil, Err.new(Err.ARG, "version must be 1 or 2") + end + -- group by extension, then path, keeping first-seen order + local exts: { string } = {} + local byExt: { [string]: { paths: { string }, byPath: { [string]: { { name: string, data: buffer } } } } } = {} + for _, it in items do + if not it.entry.dir then + local full = string.gsub(it.entry.name, "\\", "/") + local dir, file = string.match(full, "^(.*)/([^/]*)$") + if not dir then + dir, file = " ", full + end + local stem, ext = string.match(file :: string, "^(.*)%.([^.]*)$") + if not stem or stem == "" then + stem, ext = file, " " + end + if stem == "" or dir == "" or string.find(full, "\0", 1, true) then + return nil, Err.new(Err.ARG, "bad entry name: " .. it.entry.name) + end + local g = byExt[ext :: string] + if not g then + g = { paths = {}, byPath = {} } + byExt[ext :: string] = g + table.insert(exts, ext :: string) + end + local l = g.byPath[dir :: string] + if not l then + l = {} + g.byPath[dir :: string] = l + table.insert(g.paths, dir :: string) + end + table.insert(l, { name = stem :: string, data = it.data }) + end + end + local tree = Bytes.writer() + local data = Bytes.writer() + for _, ext in exts do + tree:cstring(ext) + local g = byExt[ext] + for _, path in g.paths do + tree:cstring(path) + for _, f in g.byPath[path] do + tree:cstring(f.name) + tree:u32le(Crc32.of(f.data)) + tree:u16le(0) + tree:u16le(EMBEDDED) + tree:u32le(data:tell()) + tree:u32le(buffer.len(f.data)) + tree:u16le(0xFFFF) + data:bytes(f.data) + end + tree:u8(0) + end + tree:u8(0) + end + tree:u8(0) + local tb, db = tree:finish(), data:finish() + local w = Bytes.writer(buffer.len(tb) + buffer.len(db) + 128) + w:u32le(SIGNATURE) + w:u32le(version) + w:u32le(buffer.len(tb)) + if version == 2 then + w:u32le(buffer.len(db)) + w:u32le(0) + w:u32le(48) + w:u32le(0) + end + w:bytes(tb) + w:bytes(db) + if version == 2 then + local treeMd5 = Md5.new() + treeMd5:update(tb) + local tmd = treeMd5:digest() + local chunkMd5 = Md5.new():digest() + local file = Md5.new() + local sofar = w:finish() + file:update(sofar) + file:update(buffer.fromstring(tmd .. chunkMd5)) + local out = Bytes.writer(buffer.len(sofar) + 48) + out:bytes(sofar) + out:string(tmd) + out:string(chunkMd5) + out:string(file:digest()) + return out:finish(), nil + end + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +function Vpk.new(version: number?): any + local a = Archive.new("vpk", encode) + a.meta.source = { format = "vpk", version = version or 2 } + return a +end + +return Vpk +end +__FILES["archive/wad"] = function() + +-- archive/wad: Doom-engine WADs (IWAD / PWAD; Unofficial Doom Specs, w_wad.c / r_data.c; no code taken), plus lumps, +-- palettes, pictures, wall textures and maps. Entry names: "<map>/<lump>", repeats "<name>~<n>". Not supported: UDMF +-- geometry (lumps listed), Strife's TEXTURE variant, big-endian (Jaguar) WADs, compressed Jaguar lumps. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Archive = __include("containers/Archive") +local Pixels = __include("codecs/image/Pixels") +local Picture = __include("archive/wad/Picture") +local Map = __include("archive/wad/Map") + +-- ------------------------------------------------------------------------------------------------ contract +local Wad = { + name = "wad", + category = "archive", + extensions = { "wad" }, + mime = { "application/x-doom" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Archive", "codecs/image/Pixels", "codecs/model/Polygon" }, + caps = { decode = true, encode = true, images = true, maps = true, variants = { "iwad", "pwad" } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { maxEntries: number? } -- default 1e6 +type EncodeOptions = { type: ("IWAD" | "PWAD")? } -- default: the source's, else "PWAD" +type Lump = { + name: string, + entry: string, + index: number, + offset: number, + size: number, + namespace: string?, -- between *_START / *_END markers + map: string?, + marker: boolean?, -- a zero-size marker (F_START, MAP01, ...) +} +type MapOptions = { + textures: boolean?, -- default true + palette: number?, -- default 0 +} + +-- ------------------------------------------------------------------------------------------------ constants +local MAP_LUMPS: { [string]: boolean } = { + THINGS = true, LINEDEFS = true, SIDEDEFS = true, VERTEXES = true, SEGS = true, SSECTORS = true, NODES = true, + SECTORS = true, REJECT = true, BLOCKMAP = true, BEHAVIOR = true, SCRIPTS = true, LEAFS = true, LIGHTS = true, + MACROS = true, GL_VERT = true, GL_SEGS = true, GL_SSECT = true, GL_NODES = true, GL_PVS = true, +} +-- namespace markers: first letter(s) before _START / _END +local NAMESPACES: { [string]: string } = { S = "sprites", SS = "sprites", P = "patches", PP = "patches", P1 = "patches", P2 = "patches", + P3 = "patches", F = "flats", FF = "flats", F1 = "flats", F2 = "flats", F3 = "flats", C = "colormaps", + TX = "textures", HI = "hires", A = "acs", V = "voices" } + +-- ------------------------------------------------------------------------------------------------ sniff +function Wad.sniff(r: Bytes.Reader): number + if r:remaining() < 12 then + return 0 + end + local m = r:peek(4) + if m ~= "IWAD" and m ~= "PWAD" then + return 0 + end + return 0.9 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function encode(archive: any, opts: any?): (buffer?, Err.Err?) + return Wad.encode(archive, opts) +end + +local function nameAt(b: buffer, at: number): string + local s = buffer.readstring(b, at, 8) + local z = string.find(s, "\0", 1, true) + return string.upper(if z then string.sub(s, 1, z - 1) else s) +end + +function Wad.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local kind = r:string(4) + local count, dirOfs = r:i32le(), r:i32le() + if r.err then + return nil, r.err + end + if kind ~= "IWAD" and kind ~= "PWAD" then + return nil, Err.new(Err.CORRUPT, "bad magic", 0) + end + local size = r.limit - r.base + if count < 0 or dirOfs < 0 then + return nil, Err.new(Err.CORRUPT, "negative directory field", 4) + end + if count > (opts and opts.maxEntries or 1e6) then + return nil, Err.new(Err.LIMIT, "too many lumps: " .. count) + end + if dirOfs + count * 16 > size then + return nil, Err.new(Err.TRUNCATED, "directory past the end", 8) + end + local a = Archive.new("wad", encode) + local lumps: { Lump } = {} + local seen: { [string]: number } = {} + local b = r.buf + local ns: string? = nil + local map: string? = nil + local udmf = false + for i = 0, count - 1 do + local o = r.base + dirOfs + i * 16 + local at, n = buffer.readi32(b, o), buffer.readi32(b, o + 4) + local name = nameAt(b, o + 8) + if n < 0 or at < 0 or (n > 0 and at + n > size) then + return nil, Err.new(Err.TRUNCATED, "lump " .. name .. " past the end", dirOfs + i * 16) + end + -- map membership: a lump followed by THINGS (binary) or TEXTMAP (UDMF) starts a map + local nextName = if i + 1 < count then nameAt(b, o + 24) else "" + local inMap: string? = nil + if map then + if udmf then + inMap = map + if name == "ENDMAP" then + map = nil + end + elseif MAP_LUMPS[name] then + inMap = map + else + map = nil + end + end + local isMapMarker = not inMap and (nextName == "THINGS" or nextName == "TEXTMAP") + if isMapMarker then + map, udmf = name, nextName == "TEXTMAP" + end + local marker: boolean = false + local pre = string.match(name, "^(%w+)_START$") + local post = string.match(name, "^(%w+)_END$") + if pre and NAMESPACES[pre] then + ns = NAMESPACES[pre] + marker = true + elseif post and NAMESPACES[post] then + ns = if #post > 1 and NAMESPACES[string.sub(post, 1, 1)] == ns and (string.match(post, "%d$")) then ns else nil + marker = true + end + local entry = if inMap then inMap .. "/" .. name else name + local k = seen[entry] + if k then + k += 1 + seen[entry] = k + entry = entry .. "~" .. k + else + seen[entry] = 1 + end + local lump: Lump = { name = name, entry = entry, index = i + 1, offset = at, size = n, namespace = if marker then nil else ns, map = inMap, marker = (n == 0 and (marker or isMapMarker)) or nil } + table.insert(lumps, lump) + Archive.put(a, { name = entry, size = n, dir = false, method = "store", lump = name, namespace = lump.namespace, map = inMap, load = Archive.slice(b, r.base + at, n) }) + end + a.meta.source = { format = "wad", type = kind, lumps = count } + a.meta.wad = { lumps = lumps, buf = b, base = r.base } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Wad.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local items, err = Archive.collect(archive) + if not items then + return nil, err + end + local src = type(archive) == "table" and type(archive.meta) == "table" and archive.meta.source + local kind = opts and opts.type or (if type(src) == "table" and src.format == "wad" then src.type else nil) or "PWAD" + if kind ~= "IWAD" and kind ~= "PWAD" then + return nil, Err.new(Err.ARG, "type must be IWAD or PWAD") + end + local list: { { name: string, data: buffer } } = {} + for _, it in items do + if not it.entry.dir then + local base = string.match(it.entry.name, "([^/\\]*)$") or it.entry.name + base = string.upper((string.gsub(base, "~%d+$", ""))) + if #base > 8 or #base == 0 then + return nil, Err.new(Err.ARG, "lump name must be 1..8 bytes: " .. it.entry.name) + end + table.insert(list, { name = base, data = it.data }) + end + end + local w = Bytes.writer() + w:string(kind) + w:u32le(#list) + w:u32le(0) + local offs: { number } = {} + for i, l in list do + offs[i] = w:tell() + w:bytes(l.data) + end + local dirOfs = w:tell() + for i, l in list do + w:u32le(offs[i]) + w:u32le(buffer.len(l.data)) + w:string(l.name) + w:fill(0, 8 - #l.name) + end + w:setU32le(8, dirOfs) + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +local function info(a: any): any + return type(a) == "table" and type(a.meta) == "table" and a.meta.wad or nil +end + +-- the last lump named name (PWAD order: later lumps override) +local function find(w: any, name: string, ns: string?): Lump? + local up = string.upper(name) + local best: Lump? = nil + for _, l in w.lumps do + if l.name == up and not l.map then + if ns == nil or l.namespace == ns then + best = l + elseif not best then + best = l + end + end + end + if best and ns and best.namespace ~= ns then + for _, l in w.lumps do + if l.name == up and l.namespace == ns then + best = l + end + end + end + return best +end + +function Wad.new(kind: ("IWAD" | "PWAD")?): any + local a = Archive.new("wad", encode) + a.meta.source = { format = "wad", type = kind or "PWAD" } + return a +end + +function Wad.lumps(a: any): { Lump }? + local w = info(a) + return w and w.lumps +end + +function Wad.palette(a: any, index: number?): (buffer?, Err.Err?) + local w = info(a) + if not w then + return nil, Err.new(Err.ARG, "expected a decoded WAD archive") + end + local l = find(w, "PLAYPAL") + local i = index or 0 + if not l or l.size < (i + 1) * 768 then + return nil, Err.new(Err.UNSUPPORTED, "no PLAYPAL palette " .. i) + end + return Pixels.palette(w.buf, w.base + l.offset + i * 768, 256), nil +end + +function Wad.image(a: any, name: string, opts: { palette: number?, kind: string? }?): (Types.Image?, Err.Err?) + local w = info(a) + if not w then + return nil, Err.new(Err.ARG, "expected a decoded WAD archive") + end + local kind = opts and opts.kind + local l = find(w, name, if kind == "flat" then "flats" else nil) + if not l then + return nil, Err.new(Err.ARG, "no lump named " .. tostring(name)) + end + local pal, perr = Wad.palette(a, opts and opts.palette) + if not pal then + return nil, perr + end + local at = w.base + l.offset + local pw, ph, left, top = Picture.header(w.buf, at, l.size) + local asFlat = kind == "flat" or (kind ~= "picture" and (l.namespace == "flats" or not pw)) + if asFlat then + local fw, fh = Picture.flatSize(l.size) + if not fw then + return nil, Err.new(Err.UNSUPPORTED, "lump " .. l.name .. " is neither a picture nor a flat") + end + local img = Types.Image.new(fw, fh) + Picture.flat(w.buf, at, fw, fh, pal, img.pixels) + img.meta.source = { format = "wad", kind = "flat", lump = l.name } + return img, nil + end + if not pw then + return nil, Err.new(Err.CORRUPT, "lump " .. l.name .. " is not a valid picture") + end + local img = Types.Image.new(pw, ph) + local ok, msg = Picture.decode(w.buf, at, l.size, pal, img.pixels, pw, ph) + if not ok then + return nil, Err.from(msg, l.offset) + end + img.meta.offset = { left, top } + img.meta.source = { format = "wad", kind = "picture", lump = l.name, left = left, top = top } + return img, nil +end + +local function textureDefs(w: any): { [string]: any } + if w.textures then + return w.textures + end + local defs: { [string]: any } = {} + w.textures = defs + local pn = find(w, "PNAMES") + local names: { string } = {} + if pn and pn.size >= 4 then + local at = w.base + pn.offset + local n = math.min(buffer.readi32(w.buf, at), (pn.size - 4) // 8) + for i = 0, n - 1 do + names[i + 1] = nameAt(w.buf, at + 4 + i * 8) + end + end + for _, tl in { "TEXTURE1", "TEXTURE2" } do + local l = find(w, tl) + if l and l.size >= 4 then + local r = Bytes.reader(w.buf, w.base + l.offset, l.size) + local n = r:i32le() + if n > 0 and n * 4 <= l.size - 4 then + for i = 0, n - 1 do + r:seek(4 + i * 4) + local o = r:i32le() + if o > 0 and o + 22 <= l.size then + r:seek(o) + local tname = string.upper(r:fixed(8)) + r:skip(4) + local tw, th = r:i16le(), r:i16le() + r:skip(4) + local pc = r:i16le() + local patches = {} + for _ = 1, math.max(0, pc) do + local px, py, pi = r:i16le(), r:i16le(), r:i16le() + r:skip(4) + if names[pi + 1] then + table.insert(patches, { x = px, y = py, patch = names[pi + 1] }) + end + end + if not r.err and tw > 0 and th > 0 and defs[tname] == nil then + defs[tname] = { width = tw, height = th, patches = patches } + end + r.err = nil + end + end + end + end + end + return defs +end + +function Wad.texture(a: any, name: string, opts: { palette: number? }?): (Types.Image?, Err.Err?) + local w = info(a) + if not w then + return nil, Err.new(Err.ARG, "expected a decoded WAD archive") + end + local def = textureDefs(w)[string.upper(name)] + if not def then + return nil, Err.new(Err.ARG, "no texture named " .. tostring(name)) + end + if def.width * def.height > 4096 * 4096 then + return nil, Err.new(Err.LIMIT, "texture too big") + end + local img = Types.Image.new(def.width, def.height) + for _, p in def.patches do + local pimg = Wad.image(a, p.patch, { palette = opts and opts.palette, kind = "picture" }) + if pimg then + Picture.blit(pimg.pixels, pimg.width, pimg.height, img.pixels, def.width, def.height, p.x, p.y) + end + end + img.meta.source = { format = "wad", kind = "texture", texture = string.upper(name), patches = #def.patches } + return img, nil +end + +function Wad.maps(a: any): { string } + local w = info(a) + local out: { string } = {} + if w then + local seen: { [string]: boolean } = {} + for _, l in w.lumps do + if l.map and not seen[l.map] then + seen[l.map] = true + table.insert(out, l.map) + end + end + end + return out +end + +function Wad.mapData(a: any, name: string): (Map.MapData?, Err.Err?) + local w = info(a) + if not w then + return nil, Err.new(Err.ARG, "expected a decoded WAD archive") + end + local up = string.upper(name) + local lumps: { [string]: Map.Lump } = {} + for _, l in w.lumps do + if l.map == up and lumps[l.name] == nil then + lumps[l.name] = { buf = w.buf, at = w.base + l.offset, size = l.size } + end + end + if not next(lumps) then + return nil, Err.new(Err.ARG, "no map named " .. tostring(name)) + end + if lumps.TEXTMAP then + return nil, Err.new(Err.UNSUPPORTED, "UDMF (TEXTMAP) maps") + end + local m, msg = Map.parse(lumps, lumps.BEHAVIOR ~= nil) + if not m then + return nil, Err.from(msg) + end + return m, nil +end + +function Wad.map(a: any, name: string, opts: MapOptions?): (Types.Scene?, Err.Err?) + local m, err = Wad.mapData(a, name) + if not m then + return nil, err + end + local w = info(a) + local defs = textureDefs(w) + local images = not (opts and opts.textures == false) + local cache: { [string]: any } = {} + local pal = opts and opts.palette + local function image(kind: string, tname: string): Types.Image? + local key = kind .. ":" .. tname + local c = cache[key] + if c == nil then + local img = if kind == "flat" then Wad.image(a, tname, { kind = "flat", palette = pal }) else Wad.texture(a, tname, { palette = pal }) + c = img or false + cache[key] = c + end + return if c then c else nil + end + local tex: Map.Textures = { + size = function(kind: string, tname: string): (number?, number?) + if kind == "texture" then + local d = defs[tname] + if d then + return d.width, d.height + end + return nil, nil + end + local l = find(w, tname, "flats") + if l then + local fw, fh = Picture.flatSize(l.size) + return fw, fh + end + return nil, nil + end, + image = if images then image else nil, + } + local scene = Map.scene(m, tex, string.upper(name)) + scene.meta.source = { format = "wad", map = string.upper(name), mapFormat = m.format, things = #m.things, linedefs = #m.linedefs, sectors = #m.sectors, vertices = #m.vertices // 2 } + return scene, nil +end + +return Wad +end +__FILES["archive/wad/Map"] = function() + +-- archive/wad/Map: Doom / Heretic / Hexen binary map lumps (Hexen when BEHAVIOR is present) to tables and a Scene, with +-- vanilla texture alignment (offsets, unpegged) and the sky hack; z up, map units. From the Unofficial Doom Specs and +-- the Hexen specs; no code taken. Not supported: UDMF (TEXTMAP). +local Types = __include("Types") +local Polygon = __include("codecs/model/Polygon") + +local Map = {} + +local Scene = Types.Scene +local readu8, readi16, readu16 = buffer.readu8, buffer.readi16, buffer.readu16 +local writef32, writeu32 = buffer.writef32, buffer.writeu32 + +type Lump = { buf: buffer, at: number, size: number } +type Thing = { x: number, y: number, z: number?, angle: number, type: number, flags: number, tid: number?, special: number?, args: { number }? } +type Linedef = { v1: number, v2: number, flags: number, special: number, tag: number?, args: { number }?, front: number?, back: number? } +type Sidedef = { xoff: number, yoff: number, upper: string, lower: string, middle: string, sector: number } +type Sector = { floor: number, ceiling: number, floorFlat: string, ceilingFlat: string, light: number, special: number, tag: number } +type MapData = { + format: "doom" | "hexen", + things: { Thing }, + linedefs: { Linedef }, + sidedefs: { Sidedef }, + vertices: { number }, -- x1, y1, x2, y2, ... + sectors: { Sector }, +} +type Textures = { + size: (kind: string, name: string) -> (number?, number?), + image: ((kind: string, name: string) -> Types.Image?)?, +} + +-- ------------------------------------------------------------------------------------------------ parse +local function name8(b: buffer, at: number): string + local s = buffer.readstring(b, at, 8) + local z = string.find(s, "\0", 1, true) + return string.upper(if z then string.sub(s, 1, z - 1) else s) +end + +local function side(v: number): number? + return if v == 0xFFFF then nil else v + 1 +end + +function Map.parse(lumps: { [string]: Lump }, hexen: boolean): (MapData?, string?) + for _, k in { "LINEDEFS", "SIDEDEFS", "VERTEXES", "SECTORS" } do + if not lumps[k] then + return nil, "map has no " .. k + end + end + local m: MapData = { format = if hexen then "hexen" else "doom", things = {}, linedefs = {}, sidedefs = {}, vertices = {}, sectors = {} } + local v = lumps.VERTEXES + for i = 0, v.size // 4 - 1 do + table.insert(m.vertices, readi16(v.buf, v.at + i * 4)) + table.insert(m.vertices, readi16(v.buf, v.at + i * 4 + 2)) + end + local s = lumps.SECTORS + for i = 0, s.size // 26 - 1 do + local o = s.at + i * 26 + table.insert(m.sectors, { + floor = readi16(s.buf, o), + ceiling = readi16(s.buf, o + 2), + floorFlat = name8(s.buf, o + 4), + ceilingFlat = name8(s.buf, o + 12), + light = readi16(s.buf, o + 20), + special = readu16(s.buf, o + 22), + tag = readu16(s.buf, o + 24), + }) + end + local sd = lumps.SIDEDEFS + for i = 0, sd.size // 30 - 1 do + local o = sd.at + i * 30 + table.insert(m.sidedefs, { + xoff = readi16(sd.buf, o), + yoff = readi16(sd.buf, o + 2), + upper = name8(sd.buf, o + 4), + lower = name8(sd.buf, o + 12), + middle = name8(sd.buf, o + 20), + sector = readu16(sd.buf, o + 28) + 1, + }) + end + local l = lumps.LINEDEFS + local ls = if hexen then 16 else 14 + for i = 0, l.size // ls - 1 do + local o = l.at + i * ls + local b = l.buf + if hexen then + table.insert(m.linedefs, { + v1 = readu16(b, o) + 1, + v2 = readu16(b, o + 2) + 1, + flags = readu16(b, o + 4), + special = readu8(b, o + 6), + args = { readu8(b, o + 7), readu8(b, o + 8), readu8(b, o + 9), readu8(b, o + 10), readu8(b, o + 11) }, + front = side(readu16(b, o + 12)), + back = side(readu16(b, o + 14)), + }) + else + table.insert(m.linedefs, { + v1 = readu16(b, o) + 1, + v2 = readu16(b, o + 2) + 1, + flags = readu16(b, o + 4), + special = readu16(b, o + 6), + tag = readu16(b, o + 8), + front = side(readu16(b, o + 10)), + back = side(readu16(b, o + 12)), + }) + end + end + local t = lumps.THINGS + if t then + local ts = if hexen then 20 else 10 + for i = 0, t.size // ts - 1 do + local o = t.at + i * ts + local b = t.buf + if hexen then + table.insert(m.things, { + tid = readi16(b, o), + x = readi16(b, o + 2), + y = readi16(b, o + 4), + z = readi16(b, o + 6), + angle = readi16(b, o + 8), + type = readu16(b, o + 10), + flags = readu16(b, o + 12), + special = readu8(b, o + 14), + args = { readu8(b, o + 15), readu8(b, o + 16), readu8(b, o + 17), readu8(b, o + 18), readu8(b, o + 19) }, + }) + else + table.insert(m.things, { + x = readi16(b, o), + y = readi16(b, o + 2), + angle = readi16(b, o + 4), + type = readu16(b, o + 6), + flags = readu16(b, o + 8), + }) + end + end + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ sector outlines +-- sector loops: front sides v1 -> v2, back sides v2 -> v1, lines with the sector on both sides left out; the sharpest +-- right turn at forks; unclosed chains dropped +local function loops(m: MapData): { [number]: { { number } } } + local edges: { [number]: { { number } } } = {} + local nv = #m.vertices // 2 + local function add(sec: number, a: number, b: number) + local e = edges[sec] or {} + edges[sec] = e + table.insert(e, { a, b }) + end + for _, ld in m.linedefs do + if ld.v1 >= 1 and ld.v1 <= nv and ld.v2 >= 1 and ld.v2 <= nv and ld.v1 ~= ld.v2 then + local fs = ld.front and m.sidedefs[ld.front] + local bs = ld.back and m.sidedefs[ld.back] + local f = fs and fs.sector + local b = bs and bs.sector + if f ~= b then + if f and m.sectors[f] then + add(f, ld.v1, ld.v2) + end + if b and m.sectors[b] then + add(b, ld.v2, ld.v1) + end + end + end + end + local V = m.vertices + local out: { [number]: { { number } } } = {} + for sec, list in edges do + local from: { [number]: { number } } = {} + for i, e in list do + local l = from[e[1]] or {} + from[e[1]] = l + table.insert(l, i) + end + local used: { [number]: boolean } = {} + local res: { { number } } = {} + for start = 1, #list do + if not used[start] then + used[start] = true + local loop = { list[start][1] } + local cur = start + local closed = false + for _ = 1, #list do + local e = list[cur] + local at = e[2] + if at == loop[1] then + closed = true + break + end + table.insert(loop, at) + local cands = from[at] + local best, bestT = nil :: number?, math.huge + if cands then + local ix, iy = V[at * 2 - 1] - V[e[1] * 2 - 1], V[at * 2] - V[e[1] * 2] + for _, c in cands do + if not used[c] then + local n2 = list[c][2] + local ox, oy = V[n2 * 2 - 1] - V[at * 2 - 1], V[n2 * 2] - V[at * 2] + local t = math.atan2(ix * oy - iy * ox, ix * ox + iy * oy) + if t < bestT then + best, bestT = c, t + end + end + end + end + if not best then + break + end + used[best] = true + cur = best + end + if closed and #loop >= 3 then + table.insert(res, loop) + end + end + end + out[sec] = res + end + return out +end + +local function insideLoop(V: { number }, loop: { number }, x: number, y: number): boolean + local c = false + local n = #loop + local j = n + for i = 1, n do + local ax, ay = V[loop[i] * 2 - 1], V[loop[i] * 2] + local bx, by = V[loop[j] * 2 - 1], V[loop[j] * 2] + if (ay > y) ~= (by > y) and x < (bx - ax) * (y - ay) / (by - ay) + ax then + c = not c + end + j = i + end + return c +end + +-- ------------------------------------------------------------------------------------------------ scene +type Batch = { kind: string, name: string, pos: { number }, nrm: { number }, uv: { number } } + +local LOWER_UNPEGGED, UPPER_UNPEGGED, TWO_SIDED = 16, 8, 4 + +function Map.scene(m: MapData, tex: Textures, name: string?): Types.Scene + local batches: { [string]: Batch } = {} + local order: { string } = {} + local function batch(kind: string, tname: string): Batch + local key = kind .. ":" .. tname + local b = batches[key] + if not b then + b = { kind = kind, name = tname, pos = {}, nrm = {}, uv = {} } + batches[key] = b + table.insert(order, key) + end + return b + end + local function vert(b: Batch, x: number, y: number, z: number, nx: number, ny: number, nz: number, u: number, v: number) + local p, n, t = b.pos, b.nrm, b.uv + p[#p + 1], p[#p + 2], p[#p + 3] = x, y, z + n[#n + 1], n[#n + 2], n[#n + 3] = nx, ny, nz + t[#t + 1], t[#t + 2] = u, v + end + local V = m.vertices + local nv = #V // 2 + local secLoops = loops(m) + for sec, ls in secLoops do + local s = m.sectors[sec] + local flat: { { number } } = {} + for li, loop in ls do + local f: { number } = {} + for _, vi in loop do + table.insert(f, V[vi * 2 - 1]) + table.insert(f, V[vi * 2]) + end + flat[li] = f + end + local tris = Polygon.triangulate(flat) + for pass = 1, 2 do + local tname = if pass == 1 then s.floorFlat else s.ceilingFlat + local fw, fh = tex.size("flat", tname) + local w, h = fw or 64, fh or 64 + local z = if pass == 1 then s.floor else s.ceiling + local b = batch("flat", tname) + local nz = if pass == 1 then 1 else -1 + for k = 1, #tris, 6 do + for c = 0, 2 do + local cc = if pass == 1 then c else 2 - c + local loop = ls[tris[k + cc * 2]] + local vi = loop[tris[k + cc * 2 + 1]] + local x, y = V[vi * 2 - 1], V[vi * 2] + vert(b, x, y, z, 0, 0, nz, x / w, -y / h) + end + end + end + end + local function quad(tname: string, x1: number, y1: number, x2: number, y2: number, zb: number, zt: number, xoff: number, len: number, texTop: number, yoff: number) + if tname == "-" or tname == "" or zt <= zb then + return + end + local tw, th = tex.size("texture", tname) + local w, h = tw or 64, th or 128 + local b = batch("texture", tname) + local dx, dy = x2 - x1, y2 - y1 + local l = math.sqrt(dx * dx + dy * dy) + local nx, ny = dy / l, -dx / l + local u0, u1 = xoff / w, (xoff + len) / w + local vb, vt = (texTop - zb + yoff) / h, (texTop - zt + yoff) / h + vert(b, x1, y1, zb, nx, ny, 0, u0, vb) + vert(b, x2, y2, zb, nx, ny, 0, u1, vb) + vert(b, x2, y2, zt, nx, ny, 0, u1, vt) + vert(b, x1, y1, zb, nx, ny, 0, u0, vb) + vert(b, x2, y2, zt, nx, ny, 0, u1, vt) + vert(b, x1, y1, zt, nx, ny, 0, u0, vt) + end + for _, ld in m.linedefs do + if ld.v1 >= 1 and ld.v1 <= nv and ld.v2 >= 1 and ld.v2 <= nv and ld.v1 ~= ld.v2 then + local ax, ay, bx, by = V[ld.v1 * 2 - 1], V[ld.v1 * 2], V[ld.v2 * 2 - 1], V[ld.v2 * 2] + local len = math.sqrt((bx - ax) ^ 2 + (by - ay) ^ 2) + for sideN = 1, 2 do + local sdi = if sideN == 1 then ld.front else ld.back + local odi = if sideN == 1 then ld.back else ld.front + local sd = sdi and m.sidedefs[sdi] + local me = sd and m.sectors[sd.sector] + if sd and me then + local x1, y1, x2, y2 = ax, ay, bx, by + if sideN == 2 then + x1, y1, x2, y2 = bx, by, ax, ay + end + local od = odi and m.sidedefs[odi] + local other = od and m.sectors[od.sector] + if not other then + local th = select(2, tex.size("texture", sd.middle)) or 128 + local top = if bit32.band(ld.flags, LOWER_UNPEGGED) ~= 0 then me.floor + th else me.ceiling + quad(sd.middle, x1, y1, x2, y2, me.floor, me.ceiling, sd.xoff, len, top, sd.yoff) + else + if other.floor > me.floor then + local top = if bit32.band(ld.flags, LOWER_UNPEGGED) ~= 0 then me.ceiling else other.floor + quad(sd.lower, x1, y1, x2, y2, me.floor, other.floor, sd.xoff, len, top, sd.yoff) + end + local sky = string.sub(me.ceilingFlat, 1, 5) == "F_SKY" and string.sub(other.ceilingFlat, 1, 5) == "F_SKY" + if other.ceiling < me.ceiling and not sky then + local th = select(2, tex.size("texture", sd.upper)) or 128 + local top = if bit32.band(ld.flags, UPPER_UNPEGGED) ~= 0 then me.ceiling else other.ceiling + th + quad(sd.upper, x1, y1, x2, y2, other.ceiling, me.ceiling, sd.xoff, len, top, sd.yoff) + end + if sd.middle ~= "-" and sd.middle ~= "" and bit32.band(ld.flags, TWO_SIDED) ~= 0 then + local th = select(2, tex.size("texture", sd.middle)) or 128 + local lo, hi = math.max(me.floor, other.floor), math.min(me.ceiling, other.ceiling) + local top = if bit32.band(ld.flags, LOWER_UNPEGGED) ~= 0 then lo + th else hi + quad(sd.middle, x1, y1, x2, y2, math.max(lo, top + sd.yoff - th), math.min(hi, top + sd.yoff), sd.xoff, len, top, sd.yoff) + end + end + end + end + end + end + local scene = Scene.new() + scene.meta.up = "z" + local mesh: Types.Mesh = { name = name, primitives = {} } + local texIndex: { [string]: number } = {} + for _, key in order do + local b = batches[key] + local n = #b.pos // 3 + if n > 0 then + local pb, nb, ub, ib = buffer.create(n * 12), buffer.create(n * 12), buffer.create(n * 8), buffer.create(n * 4) + for i = 1, n * 3 do + writef32(pb, (i - 1) * 4, b.pos[i]) + writef32(nb, (i - 1) * 4, b.nrm[i]) + end + for i = 1, n * 2 do + writef32(ub, (i - 1) * 4, b.uv[i]) + end + for i = 0, n - 1 do + writeu32(ib, i * 4, i) + end + local ti = texIndex[key] + if not ti then + table.insert(scene.textures, { name = b.name, uri = b.name, image = if tex.image then tex.image(b.kind, b.name) else nil, extras = { wad = { kind = b.kind } } }) + ti = #scene.textures + texIndex[key] = ti + end + local mat = Scene.material(b.name) + mat.metallic = 0 + mat.baseColorTexture = { texture = ti } + mat.extras = { wad = { kind = b.kind } } + table.insert(scene.materials, mat) + table.insert(mesh.primitives, { + attributes = { + POSITION = Scene.accessor(pb, "f32", 3, n), + NORMAL = Scene.accessor(nb, "f32", 3, n), + TEXCOORD_0 = Scene.accessor(ub, "f32", 2, n), + }, + indices = Scene.accessor(ib, "u32", 1, n), + mode = "triangles" :: any, + material = #scene.materials, + extras = { wad = { kind = b.kind, texture = b.name } }, + }) + end + end + table.insert(scene.meshes, mesh) + scene.nodes[1] = { name = name, children = {}, mesh = 1 } + scene.roots[1] = 1 + for i, th in m.things do + local z = th.z or 0 + for sec, ls in secLoops do + local inside = false + for _, loop in ls do + if insideLoop(V, loop, th.x, th.y) then + inside = not inside + end + end + if inside then + z += m.sectors[sec].floor + break + end + end + local a = math.rad(th.angle) / 2 + table.insert(scene.nodes, { + name = "thing " .. i, + children = {}, + translation = { th.x, th.y, z }, + rotation = { 0, 0, math.sin(a), math.cos(a) }, + extras = { thing = { type = th.type, angle = th.angle, flags = th.flags, tid = th.tid, special = th.special, args = th.args } }, + }) + table.insert(scene.nodes[1].children, #scene.nodes) + end + return scene +end + +return Map +end +__FILES["archive/wad/Picture"] = @native function() + + +-- archive/wad/Picture: Doom picture lumps (column posts: topdelta / length / pad / pixels / pad; DeePsea tall patches: +-- a topdelta not above the previous is relative) and raw flats to rgba8, from the Unofficial Doom Specs and r_data.c; +-- no code taken. Transparent pixels are 0. +local readu8, readu16, readi16, readu32, writeu32 = buffer.readu8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.writeu32 + +local Picture = {} + +@native function Picture.header(b: buffer, at: number, n: number): (number?, number, number, number) + if n < 8 then + return nil, 0, 0, 0 + end + local w, h = readu16(b, at), readu16(b, at + 2) + if w == 0 or h == 0 or w > 4096 or h > 4096 or 8 + w * 4 > n then + return nil, 0, 0, 0 + end + for x = 0, w - 1 do + local o = readu32(b, at + 8 + x * 4) + if o < 8 + w * 4 or o >= n then + return nil, 0, 0, 0 + end + end + return w, h, readi16(b, at + 4), readi16(b, at + 6) +end + +@native function Picture.decode(b: buffer, at: number, n: number, pal: buffer, out: buffer, w: number, h: number): (boolean, string?) + local stop = at + n + for x = 0, w - 1 do + local p = at + readu32(b, at + 8 + x * 4) + local top = -1 + while true do + if p >= stop then + return false, "column " .. x .. " runs past the end" + end + local delta = readu8(b, p) + if delta == 255 then + break + end + if p + 3 > stop then + return false, "post header past the end" + end + local len = readu8(b, p + 1) + top = if delta <= top then top + delta else delta + if p + 4 + len > stop then + return false, "post past the end" + end + local src = p + 3 + for k = 0, len - 1 do + local y = top + k + if y < h then + writeu32(out, (y * w + x) * 4, readu32(pal, readu8(b, src + k) * 4)) + end + end + p += 4 + len + end + end + return true, nil +end + +@native function Picture.flatSize(n: number): (number?, number) + if n == 4096 then + return 64, 64 + elseif n == 4160 then + return 64, 64 -- Heretic / Hexen: 64 x 65, the last row is padding + elseif n == 8192 then + return 64, 128 + elseif n == 12800 then + return 64, 200 -- Heretic / Hexen scrolling flats + end + local s = math.floor(math.sqrt(n) + 0.5) + if s * s == n and s > 0 then + return s, s + end + if n > 0 and n % 64 == 0 then + return 64, n // 64 + end + return nil, 0 +end + +@native function Picture.flat(b: buffer, at: number, w: number, h: number, pal: buffer, out: buffer) + for i = 0, w * h - 1 do + writeu32(out, i * 4, readu32(pal, readu8(b, at + i) * 4)) + end +end + +@native function Picture.blit(src: buffer, sw: number, sh: number, dst: buffer, dw: number, dh: number, ox: number, oy: number) + local x0, x1 = math.max(0, -ox), math.min(sw, dw - ox) - 1 + for y = math.max(0, -oy), math.min(sh, dh - oy) - 1 do + local so, d = y * sw, (y + oy) * dw + ox + for x = x0, x1 do + local v = readu32(src, (so + x) * 4) + if v ~= 0 then + writeu32(dst, (d + x) * 4, v) + end + end + end +end + +return Picture +end +__FILES["archive/xz"] = function() + +-- archive/xz: .xz (xz file format 1.2) and .lzma ("LZMA alone") as single-stream archives (codecs/compress/Lzma). +-- Supports: concatenated streams, padding, checks none / CRC-32 / CRC-64 (SHA-256 unverified), LZMA2, delta, BCJ +-- x86 / PowerPC / ARM / ARM-Thumb / SPARC / ARM64. Not supported: writing, IA-64 / RISC-V filters. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Lzma = __include("codecs/compress/Lzma") +local Archive = __include("containers/Archive") + +-- ------------------------------------------------------------------------------------------------ contract +local Xz = { + name = "xz", + category = "archive", + extensions = { "xz", "txz", "lzma" }, + mime = { "application/x-xz", "application/x-lzma" }, + 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" } }, +} + +type DecodeOptions = { + maxBytes: number?, -- default 2^30 + name: string?, +} + +-- ------------------------------------------------------------------------------------------------ constants +local XZ_MAGIC = "\253" .. "7zXZ\0" + +-- ------------------------------------------------------------------------------------------------ sniff +-- .lzma files have no magic: props byte < 225 (0x5D for every preset), a dictionary size of 2^n or 2^n + 2^(n-1), +-- a size of -1 or under 2^40, and a 0 range coder byte +local function aloneScore(r: Bytes.Reader): number + local h = r:peek(14) + if #h < 14 then + return 0 + end + local d = string.byte(h, 1) + if d >= 225 or string.byte(h, 14) ~= 0 then + return 0 + end + local dict = string.byte(h, 2) + string.byte(h, 3) * 256 + string.byte(h, 4) * 65536 + string.byte(h, 5) * 16777216 + local okDict = false + for n = 12, 31 do + if dict == 2 ^ n or (n < 31 and dict == 2 ^ n + 2 ^ (n - 1)) then + okDict = true + break + end + end + if not okDict then + return 0 + end + local s = string.sub(h, 6, 13) + if s ~= string.rep("\255", 8) and (string.byte(h, 11) ~= 0 or string.byte(h, 12) ~= 0 or string.byte(h, 13) ~= 0) then + return 0 + end + return if d == 0x5D then 0.4 else 0.2 +end + +function Xz.sniff(r: Bytes.Reader): number + if r:peek(6) == XZ_MAGIC then + return 1 + end + return aloneScore(r) +end + +-- ------------------------------------------------------------------------------------------------ decode +function Xz.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Archive?, Err.Err?) + local o: DecodeOptions = opts or {} + local n = r.limit - r.base + local out, res + local method + if r:peek(6) == XZ_MAGIC then + out, res = Lzma.xz(r.buf, r.base, n, o) + method = "lzma2" + else + out, res = Lzma.alone(r.buf, r.base, n, o) + method = "lzma" + end + if not out then + return nil, res + end + local a = Archive.new("xz") + a.meta.stream = true + a.meta.container = if method == "lzma" then "lzma" else "xz" + Archive.put(a, { + name = Archive.streamName(o, Xz.extensions), + size = buffer.len(out), + compressedSize = n, + method = method, + dir = false, + data = out, + }) + return a, nil +end + +return Xz +end +__FILES["archive/yenc"] = function() + +-- archive/yenc: yEnc 1.3 (=ybegin / =ypart / =yend, byte + 42, "=" escapes; Jürgen Helbing's draft): parts in one text +-- joined, pcrc32 / crc32 / size verified; writes one 128-character-line part per file, escaping NUL, LF, CR, "=" and a +-- leading / trailing TAB, space or ".", as uuenview / yencode do. Not supported: parts spread over several files. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Crc32 = __include("core/Crc32") +local Archive = __include("containers/Archive") + +-- ------------------------------------------------------------------------------------------------ contract +local Yenc = { + name = "yenc", + category = "archive", + extensions = { "yenc", "ync" }, + mime = { "application/x-yenc" }, + deps = { "core/Err", "core/Bytes", "core/Crc32", "containers/Archive" }, + caps = { decode = true, encode = true, multipart = true }, +} + +type DecodeOptions = { maxBytes: number?, name: string? } -- default 2^30 +type EncodeOptions = { + line: number?, -- default 128 + name: string?, +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Yenc.sniff(r: Bytes.Reader): number + local head = r:peek(4096) + if string.match(head, "^=ybegin ") then + return 0.95 + end + return if string.find(head, "\n=ybegin [^\n]*name=") then 0.6 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- key=value fields of a keyword line; name= runs to the end of the line +local function fields(line: string): { [string]: string } + local f: { [string]: string } = {} + local s, name = string.match(line, "^(.-)name=(.*)$") + if s then + f.name = string.gsub(name :: string, "%s+$", "") + line = s + end + for k, v in string.gmatch(line, "(%w+)=(%S+)") do + f[k] = v + end + return f +end + +local function decodeData(src: buffer, i: number, j: number, out: buffer, o: number): number + local lim = buffer.len(out) + local esc = false + for p = i, j - 1 do + local c = buffer.readu8(src, p) + if c == 13 or c == 10 then + continue + end + if c == 61 and not esc then + esc = true + continue + end + if esc then + c -= 64 + esc = false + end + if o < lim then + buffer.writeu8(out, o, (c - 42) % 256) + end + o += 1 + end + return o +end + +local function countData(src: buffer, i: number, j: number): number + local n, esc = 0, false + for p = i, j - 1 do + local c = buffer.readu8(src, p) + if c ~= 13 and c ~= 10 then + if c == 61 and not esc then + esc = true + else + esc = false + n += 1 + end + end + end + return n +end + +type Part = { first: number, last: number, from: number, to: number, pcrc: number?, part: number? } +type File = { name: string, size: number, crc: number?, parts: { Part }, total: number? } + +local function hex(s: string?): number? + return if s and string.match(s, "^%x+$") and #s <= 8 then tonumber(s, 16) else nil +end + +local function parse(b: buffer, base: number, limit: number): ({ File }?, string?) + local files: { File } = {} + local byName: { [string]: File } = {} + local p = base + local cur: File? = nil + local part: Part? = nil + while p < limit do + local nl = p + while nl < limit and buffer.readu8(b, nl) ~= 10 do + nl += 1 + end + local isKey = nl - p >= 2 and buffer.readu8(b, p) == 61 and buffer.readu8(b, p + 1) == 121 -- "=y" + if isKey then + local line = string.gsub(buffer.readstring(b, p, nl - p), "\r$", "") + local kw = string.match(line, "^=y(%a+)") + local f = fields(line) + if kw == "begin" then + local name = f.name + local size = tonumber(f.size or "") + if not name or name == "" or not size or size < 0 then + return nil, "=ybegin without name or size" + end + local file: File? = byName[name] + if not file then + local nf: File = { name = name :: string, size = size, parts = {}, total = tonumber(f.total or "") } + byName[name] = nf + table.insert(files, nf) + file = nf + end + cur = file + part = { first = 0, last = size, from = nl + 1, to = nl + 1, part = tonumber(f.part or "") } + elseif kw == "part" and part then + local first, last = tonumber(f.begin or ""), tonumber(f["end"] or "") + if not first or not last or first < 1 or last < first - 1 then + return nil, "bad =ypart range" + end + part.first, part.last = first - 1, last + part.from, part.to = nl + 1, nl + 1 + elseif kw == "end" and part and cur then + part.pcrc = hex(f.pcrc32) + if f.crc32 then + cur.crc = hex(f.crc32) + end + local size = tonumber(f.size or "") + if size and size ~= part.last - part.first then + return nil, "=yend size " .. size .. " does not match the part (" .. (part.last - part.first) .. ")" + end + table.insert(cur.parts, part) + part = nil + end + elseif part then + part.to = nl + 1 + end + p = nl + 1 + end + if part then + return nil, "truncated: no =yend" + end + if #files == 0 then + return nil, "no =ybegin line" + end + return files, nil +end + +local function encoder(a: any, o: any?): (buffer?, Err.Err?) + return Yenc.encode(a, o) +end + +function Yenc.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + local maxBytes = o.maxBytes or 2 ^ 30 + local b = r.buf + local files, perr = parse(b, r.base, math.min(r.limit, buffer.len(b))) + if not files then + return nil, Err.from(perr) + end + local a = Archive.new("yenc", encoder) + local incomplete = {} + for _, f in files do + if f.size > maxBytes then + return nil, Err.new(Err.LIMIT, f.name .. ": size over maxBytes") + end + local out = buffer.create(f.size) + local covered = 0 + for _, pt in f.parts do + local n = countData(b, pt.from, pt.to) + if n ~= pt.last - pt.first or pt.last > f.size then + return nil, Err.new(Err.CORRUPT, f.name .. ": part data is " .. n .. " bytes, the header says " .. (pt.last - pt.first)) + end + local tmp = buffer.create(n) + decodeData(b, pt.from, pt.to, tmp, 0) + if pt.pcrc and Crc32.of(tmp) ~= pt.pcrc then + return nil, Err.new(Err.CHECKSUM, f.name .. ": part CRC mismatch") + end + buffer.copy(out, pt.first, tmp, 0, n) + covered += n + end + local whole = covered == f.size + if whole and f.crc and Crc32.of(out) ~= f.crc then + return nil, Err.new(Err.CHECKSUM, f.name .. ": CRC mismatch") + end + if not whole then + table.insert(incomplete, f.name) + end + Archive.put(a, { name = f.name, size = f.size, dir = false, method = "yenc", data = out, complete = whole }) + end + a.meta.stream = #files == 1 + a.meta.incomplete = if #incomplete > 0 then incomplete else nil + a.meta.source = { format = "yenc" } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Yenc.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local lineLen = o.line or 128 + if type(lineLen) ~= "number" or lineLen < 2 or lineLen > 997 then + return nil, Err.new(Err.ARG, "line must be 2..997") + end + local files, err = Archive.files(value, o.name) + if not files then + return nil, err + end + if #files == 0 then + return nil, Err.new(Err.ARG, "nothing to encode") + end + local w = Bytes.writer() + for _, f in files do + if string.find(f.name, "[\r\n]") then + return nil, Err.new(Err.ARG, "file names may not contain line breaks") + end + local data = f.data + local n = buffer.len(data) + w:string(string.format("=ybegin line=%d size=%d name=%s\r\n", lineLen, n, f.name)) + local col = 0 + for i = 0, n - 1 do + local c = (buffer.readu8(data, i) + 42) % 256 + local critical = c == 0 or c == 10 or c == 13 or c == 61 + if not critical and (c == 9 or c == 32) and (col == 0 or col >= lineLen - 1 or i == n - 1) then + critical = true + elseif not critical and c == 46 and col == 0 then + critical = true + end + if critical then + w:u8(61) + w:u8((c + 64) % 256) + col += 2 + else + w:u8(c) + col += 1 + end + if col >= lineLen and i < n - 1 then + w:string("\r\n") + col = 0 + end + end + if n > 0 then + w:string("\r\n") + end + w:string(string.format("=yend size=%d crc32=%08x\r\n", n, Crc32.of(data))) + end + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +function Yenc.new(): any + local a = Archive.new("yenc", encoder) + a.meta.source = { format = "yenc" } + return a +end + +return Yenc +end +__FILES["archive/z"] = function() + +-- archive/z: Unix compress (.Z: LZW, magic 1F 9D, 9..16-bit codes, block mode) as a single-stream archive of one +-- entry (codecs/compress/UnixCompress). Supports: read; write byte for byte as ncompress (several entries: a .tar.Z). +-- Not supported: pack (.z, 1F 1E) and compact (1F FF) files. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local UnixCompress = __include("codecs/compress/UnixCompress") +local Archive = __include("containers/Archive") + +-- ------------------------------------------------------------------------------------------------ contract +local Z = { + name = "z", + category = "archive", + extensions = { "z", "taz", "tz" }, + mime = { "application/x-compress" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/UnixCompress", "containers/Archive" }, + caps = { decode = true, encode = true, stream = true, bits = { 9, 16 } }, +} + +type DecodeOptions = { + maxBytes: number?, -- default 2^30 + name: string?, +} +type EncodeOptions = { + maxBits: number?, -- 9..16 (compress -b), default 16 +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Z.sniff(r: Bytes.Reader): number + if r:peek(2) ~= "\31\157" then + return 0 + end + local f = r:peekU8(2) + return if f >= 0 and bit32.band(f, 0x60) == 0 and bit32.band(f, 0x1F) >= 9 and bit32.band(f, 0x1F) <= 16 then 1 else 0.3 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function entryName(opts: DecodeOptions): string + local name = Archive.streamName(opts, { "z" }) + local stem, ext = string.match(name, "^(.+)%.(%w+)$") + if stem and ext and (string.lower(ext) == "taz" or string.lower(ext) == "tz") then + return stem .. ".tar" + end + return name +end + +local function encode(value: any, opts: any?): (buffer?, Err.Err?) + return Z.encode(value, opts) +end + +function Z.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + local n = r.limit - r.base + local out, err = UnixCompress.decompress(r.buf, r.base, n, o) + if not out then + return nil, err + end + local a = Archive.new("z", encode) + a.meta.stream = true + a.meta.source = { format = "z", maxBits = bit32.band(buffer.readu8(r.buf, r.base + 2), 0x1F), blockMode = bit32.band(buffer.readu8(r.buf, r.base + 2), 0x80) ~= 0 } + Archive.put(a, { + name = entryName(o), + size = buffer.len(out), + compressedSize = n, + method = "lzw", + dir = false, + data = out, + }) + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Z.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local data, err = Archive.streamData(value) + if not data then + return nil, err + end + return UnixCompress.compress(data, 0, buffer.len(data), { maxBits = opts and opts.maxBits }) +end + +-- ------------------------------------------------------------------------------------------------ extras +function Z.new(data: (buffer | string)?, name: string?): any + local a = Archive.new("z", encode) + a.meta.stream = true + a.meta.source = { format = "z" } + if data then + a:add(name or "data", data) + end + return a +end + +return Z +end +end + + + + + + archive_2 + --!optimize 2 +--!nocheck +-- rosetta chunk archive_2 (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 3 modules (0 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["archive/zip"] = function() + +-- archive/zip: ZIP archives on containers/Zip, absorbed from zip-luau 121d4b0 (same author) plus a new writer. +-- Supports: stored / deflated entries (CRC-checked), ZIP64, data descriptors, comments, self-extractors, UTF-8 names; +-- writing, unchanged entries copied. Not supported: encryption, methods other than store / deflate, multi-disk. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Container = __include("containers/Zip") + +-- ------------------------------------------------------------------------------------------------ contract +local Zip = { + name = "zip", + category = "archive", + extensions = { "zip", "wsz" }, + mime = { "application/zip", "application/x-zip-compressed" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Zip" }, + caps = { decode = true, encode = true, methods = { "store", "deflate" }, zip64 = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + verify: boolean?, -- default true +} +type AddOptions = Container.AddOptions +type WriteOptions = Container.FinishOptions + +-- ------------------------------------------------------------------------------------------------ constants +local METHODS = { [0] = "store", [8] = "deflate", [9] = "deflate64", [12] = "bzip2", [14] = "lzma", [93] = "zstd", [95] = "xz", [99] = "aes" } + +local Archive = {} +Archive.__index = Archive + +local function new(zip: any, verify: boolean): any + local a = setmetatable({ + kind = "archive", + format = "zip", + meta = { source = { format = "zip" }, comment = if zip then zip.comment else nil, zip64 = if zip then zip.zip64 else nil }, + _zip = zip, + _verify = verify, + _order = {} :: { string }, + _items = {} :: { [string]: any }, + }, Archive) + if zip then + for _, e in zip:list() do + if a._items[e.name] == nil then + table.insert(a._order, e.name) + end + a._items[e.name] = { raw = e } + end + end + return a +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Zip.sniff(r: Bytes.Reader): number + local s = r:peek(4) + -- ZIP-based formats (docx, jar, 3mf, ...) score higher in their own sniff + if s == "PK\3\4" or s == "PK\5\6" then + return 0.6 + end + if string.sub(s, 1, 2) == "MZ" then + return 0 -- a self-extractor opens with Zip.decode / opts.format = "zip" + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Zip.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Archive?, Err.Err?) + local zip, err = Container.open(r) + if not zip then + return nil, err + end + return new(zip, not (opts and opts.verify == false)), nil +end + +function Zip.create(): Types.Archive + return new(nil, true) +end + +-- ------------------------------------------------------------------------------------------------ encode +function Zip.encode(value: any, opts: WriteOptions?): (buffer?, Err.Err?) + if type(value) ~= "table" then + return nil, Err.new(Err.ARG, "encode: needs an Archive or a { name = data } table") + end + if getmetatable(value) == Archive then + return value:write(opts) + end + local a = new(nil, true) + if value.kind == "archive" and type(value.list) == "function" and type(value.read) == "function" then + for _, e in value:list() do + if e.dir then + a:add(e.name, nil, { mtime = e.mtime }) + else + local data, err = value:read(e.name) + if not data then + return nil, err + end + a:add(e.name, data, { mtime = e.mtime }) + end + end + else + local names = {} + for k, v in value do + if type(k) ~= "string" or (type(v) ~= "buffer" and type(v) ~= "string") then + return nil, Err.new(Err.ARG, "encode: a { name = data } table needs string names and buffer / string data") + end + table.insert(names, k) + end + table.sort(names) + for _, k in names do + a:add(k, value[k]) + end + end + return a:write(opts) +end + +-- ------------------------------------------------------------------------------------------------ extras + +function Archive.list(self: any): { Types.ArchiveEntry } + local out = {} + for _, name in self._order do + local it = self._items[name] + if it.raw then + local e = it.raw + table.insert(out, { + name = e.name, + size = e.size, + compressedSize = e.compressedSize, + method = METHODS[e.method] or ("method " .. e.method), + mtime = e.mtime, + dir = e.isDir, + crc32 = e.crc32, + comment = e.comment, + }) + else + table.insert(out, { + name = name, + size = buffer.len(it.data), + compressedSize = nil, + method = it.opts.method or "deflate", + mtime = it.opts.mtime, + dir = string.sub(name, -1) == "/", + }) + end + end + return out +end + +function Archive.read(self: any, name: string): (buffer?, Err.Err?) + if type(name) ~= "string" then + return nil, Err.new(Err.ARG, "read: name must be a string") + end + local it = self._items[name] + if it and not it.raw then + local copy = buffer.create(buffer.len(it.data)) + buffer.copy(copy, 0, it.data) + return copy, nil + end + if it then + return self._zip:read(it.raw, self._verify) + end + if self._zip then + local e = self._zip:find(name) + if e and self._items[e.name] and self._items[e.name].raw == e then + return self._zip:read(e, self._verify) + end + end + return nil, Err.new(Err.ARG, "no entry " .. name) +end + +function Archive.add(self: any, name: string, data: any, opts: AddOptions?) + local b: buffer = if type(data) == "string" then buffer.fromstring(data) elseif type(data) == "buffer" then data else buffer.create(0) + if self._items[name] == nil then + table.insert(self._order, name) + end + self._items[name] = { data = b, opts = opts or {} } +end + +function Archive.remove(self: any, name: string): boolean + if self._items[name] == nil then + return false + end + self._items[name] = nil + local i = table.find(self._order, name) + if i then + table.remove(self._order, i) + end + return true +end + +function Archive.write(self: any, opts: WriteOptions?): (buffer?, Err.Err?) + local w = Container.writer() + for _, name in self._order do + local it = self._items[name] + local ok, err + if it.raw then + ok, err = w:addRaw(it.raw, self._zip) + else + ok, err = w:add(name, it.data, it.opts) + end + if not ok then + return nil, err + end + end + local o: WriteOptions = opts or {} + if o.comment == nil and self.meta.comment and self.meta.comment ~= "" then + o = table.clone(o) + o.comment = self.meta.comment + end + return w:finish(o) +end + +Zip.Container = Container + +return Zip +end +__FILES["archive/zoo"] = function() + +-- archive/zoo: Zoo 1.x / 2.x (zoo 2.10's zoo.h / ar.h): directory entries type 1 and 2, methods 0 stored, 1 LZW +-- (13-bit), 2 lh5; CRC-16 (ARC) verified; MS-DOS dates as UTC. Not supported: writing, file generations beyond the +-- newest (older versions of a name get ";<version>"). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Crc16 = __include("core/Crc16") +local Lzw = __include("codecs/compress/Lzw") +local Lzh = __include("codecs/compress/Lzh") +local Archive = __include("containers/Archive") + +-- ------------------------------------------------------------------------------------------------ contract +local Zoo = { + name = "zoo", + category = "archive", + extensions = { "zoo" }, + mime = { "application/x-zoo" }, + deps = { "core/Err", "core/Bytes", "core/Crc16", "codecs/compress/Lzw", "codecs/compress/Lzh", "containers/Archive" }, + caps = { decode = true, encode = false, methods = { "store", "lzw", "lzh" } }, +} + +type DecodeOptions = { + maxBytes: number?, -- default 2^30 + maxEntries: number?, -- default 65536 +} + +-- ------------------------------------------------------------------------------------------------ constants +local TAG = 0xFDC4A7DC + +-- ------------------------------------------------------------------------------------------------ sniff +function Zoo.sniff(r: Bytes.Reader): number + local h = r:peek(24) + if #h < 24 then + return 0 + end + local tag = string.byte(h, 21) + string.byte(h, 22) * 256 + string.byte(h, 23) * 65536 + string.byte(h, 24) * 16777216 + if tag ~= TAG then + return 0 + end + return if string.sub(h, 1, 4) == "ZOO " then 1 else 0.8 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Zoo.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + local maxBytes = o.maxBytes or 2 ^ 30 + local maxEntries = o.maxEntries or 65536 + local h = r:sub(0, 34) + local text = h:string(20) + local tag, start = h:u32le(), h:u32le() + h:skip(4) + local major, minor = h:u8(), h:u8() + if h.err then + return nil, h.err + end + if tag ~= TAG then + return nil, Err.new(Err.CORRUPT, "no zoo tag") + end + local a = Archive.new("zoo") + a.meta.text = string.match(text, "^[^%z\26]*") + a.meta.source = { format = "zoo", version = major .. "." .. minor } + local p = start + local count = 0 + local seen: { [number]: boolean } = {} + local size = r:size() + while true do + if seen[p] or p < 34 or p + 51 > size then + return nil, Err.new(if p + 51 > size then Err.TRUNCATED else Err.CORRUPT, "bad directory entry offset " .. p) + end + seen[p] = true + local e = r:sub(p, size - p) + local etag = e:u32le() + local etype, method = e:u8(), e:u8() + local nextP, dataAt = e:u32le(), e:u32le() + local date, time = e:u16le(), e:u16le() + local crc = e:u16le() + local orig, packed = e:u32le(), e:u32le() + e:skip(2) + local deleted = e:u8() + e:skip(1) + local commentAt, commentLen = e:u32le(), e:u16le() + local fname = e:fixed(13) + if e.err then + return nil, e.err + end + if etag ~= TAG then + return nil, Err.new(Err.CORRUPT, "bad directory entry tag", r.base + p) + end + if nextP == 0 then + break + end + count += 1 + if count > maxEntries then + return nil, Err.new(Err.LIMIT, "more than maxEntries entries") + end + local name, dir = fname, "" + local entry: any = {} + if etype == 2 then + local varLen = e:u16le() + e:skip(3) -- tz, dir_crc + if varLen > 0 then + local v = e:slice(varLen) + local nlen, dlen = v:u8(), v:u8() + local lname = v:string(nlen) + dir = v:string(dlen) + if nlen > 0 then + name = string.match(lname, "^[^%z]*") or lname + end + if v:remaining() >= 2 then + entry.system = v:u16le() + end + if v:remaining() >= 3 then + local f0, f1, f2 = v:u8(), v:u8(), v:u8() + local attr = f0 + f1 * 256 + f2 * 65536 + if bit32.band(attr, 0x400000) ~= 0 then + entry.mode = bit32.band(attr, 0xFFFF) + end + end + if v:remaining() >= 4 then + local vflag, ver = v:u16le(), v:u16le() + if bit32.band(vflag, 0x40) ~= 0 then + entry.version = ver + end + end + end + if e.err then + return nil, e.err + end + end + dir = string.match(dir, "^[^%z]*") or dir + dir = string.gsub(dir, "\\", "/") + local full = if dir ~= "" then (string.gsub(dir, "/+$", "")) .. "/" .. name else name + full = string.gsub(full, "^/+", "") + if deleted == 0 then + local key = full + if a._byName[key] then + key = full .. ";" .. tostring(entry.version or count) + end + entry.name = key + entry.size = orig + entry.compressedSize = packed + entry.method = if method == 0 then "store" elseif method == 1 then "lzw" elseif method == 2 then "lzh" else "method" .. method + entry.mtime = Archive.fromDos(date * 65536 + time) + entry.dir = false + if commentLen > 0 and commentAt + commentLen <= size then + entry.comment = r:sub(commentAt, commentLen):string(commentLen) + end + if dataAt + packed > size then + return nil, Err.new(Err.TRUNCATED, full .. ": data past the end") + end + if orig > maxBytes then + return nil, Err.new(Err.LIMIT, full .. ": larger than maxBytes") + end + if orig > 0 then + local buf, at = r.buf, r.base + dataAt + entry.load = function(): (buffer?, Err.Err?) + local out: buffer?, derr: string? + if method == 0 then + if packed < orig then + return nil, Err.new(Err.CORRUPT, "stored entry shorter than its size") + end + out = buffer.create(orig) + buffer.copy(out :: buffer, 0, buf, at, orig) + elseif method == 1 then + local ob = buffer.create(orig) + local n, lerr = Lzw.decode(buf, at, packed, ob, 0, orig, "zoo") + if n ~= orig then + return nil, Err.from(lerr or "corrupt: LZW data ends early") + end + out = ob + elseif method == 2 then + out, derr = Lzh.decode(buf, at, packed, orig, "lh5") + else + return nil, Err.new(Err.UNSUPPORTED, "packing method " .. method) + end + if not out then + return nil, Err.from(derr) + end + if Crc16.arc(out, 0, orig) ~= crc then + return nil, Err.new(Err.CHECKSUM, "CRC-16 mismatch") + end + return out, nil + end + end + Archive.put(a, entry) + end + p = nextP + end + return a, nil +end + +return Zoo +end +__FILES["archive/zst"] = function() + +-- archive/zst: a Zstandard file (.zst, RFC 8878) as a single-stream archive of one entry (codecs/compress/Zstd). +-- Supports: read; the entry is named after the file without its extension (".tzst" -> ".tar"), else "data". +-- Not supported: dictionaries, writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Zstd = __include("codecs/compress/Zstd") +local Archive = __include("containers/Archive") + +-- ------------------------------------------------------------------------------------------------ contract +local Zst = { + name = "zst", + category = "archive", + extensions = { "zst", "tzst" }, + mime = { "application/zstd" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Zstd", "containers/Archive" }, + caps = { decode = true, encode = false, stream = true }, +} + +type DecodeOptions = { + maxBytes: number?, -- default 2^30 + verify: boolean?, -- default true + name: string?, +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Zst.sniff(r: Bytes.Reader): number + local m = r:peek(4) + if m == Zstd.MAGIC then + return 1 + end + -- a skippable frame (0x184D2A50 .. 0x184D2A5F) is usually followed by a zstd frame + if #m == 4 and string.sub(m, 2, 4) == "\42\77\24" and bit32.band(string.byte(m, 1), 0xF0) == 0x50 then + return 0.5 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Zst.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + local len = r.limit - r.base + local out, err = Zstd.decompress(r.buf, r.base, len, { maxBytes = o.maxBytes, verify = o.verify }) + if not out then + return nil, err + end + local a = Archive.new("zst") + a.meta.stream = true + Archive.put(a, { + name = Archive.streamName(o, Zst.extensions), + size = buffer.len(out), + compressedSize = len, + method = "zstd", + dir = false, + data = out, + }) + return a, nil +end + +return Zst +end +end + + + + + + audio + --!optimize 2 +--!nocheck +-- rosetta chunk audio (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 29 modules (5 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["audio/aac"] = function() + +-- audio/aac: raw AAC in ADTS framing (ISO/IEC 13818-7 / 14496-3 1.A.3). Supports: AAC-LC via codecs/audio/Aac (1-8 +-- channels, every rate), CRC-protected headers, a leading ID3v2 tag, resync, seeking by frame; HE-AAC plays its +-- AAC-LC core. Not supported: writing, ADIF, LATM. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Pcm = __include("codecs/audio/Pcm") +local Stream = __include("codecs/audio/Stream") +local Aac = __include("codecs/audio/Aac") + +-- ------------------------------------------------------------------------------------------------ contract +local AacFormat = { + name = "aac", + category = "audio", + extensions = { "aac", "adts" }, + mime = { "audio/aac", "audio/aacp", "audio/x-aac" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Aac", "codecs/audio/Pcm", "codecs/audio/Stream" }, + caps = { decode = true, encode = false, codecs = { "aac" }, streaming = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + maxFrames: number?, -- default 2^22 +} + +-- ------------------------------------------------------------------------------------------------ constants +local readu8 = buffer.readu8 + +local function id3Size(b: buffer, p: number, limit: number): number + if p + 10 > limit or buffer.readstring(b, p, 3) ~= "ID3" then + return 0 + end + local s = 0 + for i = 6, 9 do + s = s * 128 + bit32.band(readu8(b, p + i), 127) + end + local footer = if bit32.band(readu8(b, p + 5), 0x10) ~= 0 then 10 else 0 + return 10 + s + footer +end + +local ID3_TAGS: { [string]: string } = { + TIT2 = "title", TPE1 = "artist", TALB = "album", TYER = "date", TDRC = "date", TCON = "genre", TRCK = "track", + COMM = "comment", TCOM = "composer", TPE2 = "albumartist", +} +local function id3Tags(b: buffer, p: number, size: number): Types.Tags + local tags: Types.Tags = {} + local ver = readu8(b, p + 3) + if ver < 3 then + return tags + end + local q, stop = p + 10, p + size + while q + 10 <= stop do + local id = buffer.readstring(b, q, 4) + if not string.match(id, "^[A-Z0-9][A-Z0-9][A-Z0-9][A-Z0-9]$") then + break + end + local n = 0 + for i = 4, 7 do + n = if ver == 4 then n * 128 + bit32.band(readu8(b, q + i), 127) else n * 256 + readu8(b, q + i) + end + if n < 1 or q + 10 + n > stop then + break + end + local key = ID3_TAGS[id] + local enc = readu8(b, q + 10) + if key and (enc == 0 or enc == 3) then + local s = buffer.readstring(b, q + 11, n - 1) + if id == "COMM" and #s > 3 then + s = string.sub(s, 4) + local z = string.find(s, "\0", 1, true) + if z then + s = string.sub(s, z + 1) + end + end + s = (string.gsub(s, "%z+$", "")) + tags[key] = s + end + q += 10 + n + end + return tags +end + +-- ------------------------------------------------------------------------------------------------ sniff +function AacFormat.sniff(r: Bytes.Reader): number + local b, p, limit = r.buf, r.pos, r.limit + p += id3Size(b, p, limit) + local h = Aac.adts(b, p, limit) + if not h then + return 0 + end + local h2 = Aac.adts(b, p + h.frameSize, limit) + if h2 and h2.sfIndex == h.sfIndex and h2.channelConfig == h.channelConfig then + return 0.9 + end + return if p + h.frameSize >= limit then 0.7 else 0.4 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function index(r: Bytes.Reader, maxFrames: number): ({ number }, { number }, Aac.Adts?, Err.Err?) + local b, limit = r.buf, r.limit + local p = r.base + id3Size(b, r.base, limit) + local offs, sizes = {}, {} + local first: Aac.Adts? = nil + while p + 7 <= limit do + local h = Aac.adts(b, p, limit) + if h and first and (h.sfIndex ~= first.sfIndex or h.channelConfig ~= first.channelConfig) then + h = nil + end + if not h then + p += 1 + continue + end + if p + h.frameSize > limit then + break + end + if not first then + first = h + end + if h.blocks ~= 1 then + return offs, sizes, first, Err.new(Err.UNSUPPORTED, "ADTS frames with " .. h.blocks .. " raw data blocks", p) + end + table.insert(offs, p + h.headerSize) + table.insert(sizes, h.frameSize - h.headerSize) + if #offs > maxFrames then + return offs, sizes, first, Err.new(Err.LIMIT, "more than " .. maxFrames .. " frames") + end + p += h.frameSize + end + return offs, sizes, first, nil +end + +function AacFormat.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?) + local o: DecodeOptions = opts or {} + local offs, sizes, first, ierr = index(r, o.maxFrames or 2 ^ 22) + if ierr then + return nil, ierr + end + if not first then + return nil, Err.new(Err.CORRUPT, "no ADTS frame", r.base) + end + local h = first :: Aac.Adts + if h.objectType ~= 2 then + return nil, Err.new(Err.UNSUPPORTED, "ADTS profile " .. h.objectType .. " (only AAC-LC)") + end + if h.channelConfig == 0 then + return nil, Err.new(Err.UNSUPPORTED, "ADTS with a program config element (channel configuration 0)") + end + local channels = ({ 1, 2, 3, 4, 5, 6, 8 })[h.channelConfig] :: number + local dec, derr = Aac.decoder({ sfIndex = h.sfIndex, channels = channels, channelConfig = h.channelConfig }) + if not dec then + return nil, derr + end + local d = dec :: Aac.Decoder + local sr = d.sampleRate + local nframes = #offs + local total = nframes * 1024 + local bytes = 0 + for _, s in sizes do + bytes += s + end + 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 out: any = { + sampleRate = sr, + channels = channels, + frames = total, + duration = total / sr, + bitrate = if total > 0 then math.floor(bytes * 8 * sr / total) else 0, + tags = tags, + codec = "aac", + } + -- 1024 samples per ADTS frame; one frame of pre-roll for the overlap + 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?) + local dec, err = AacFormat.open(r, opts) + if not dec then + return nil, err + end + local d: any = dec + return Pcm.drain(d, { format = "aac", codec = "aac", bitrate = d.bitrate }) +end + +return AacFormat +end +__FILES["audio/ac3"] = function() + +-- audio/ac3: raw AC-3 (Dolby Digital, ATSC A/52) via codecs/audio/Ac3. Supports: every channel layout (WAVE order, no +-- downmix), 32 / 44.1 / 48 kHz, every bit rate, the CRC check, resync, exact seeking; drc 0 .. 1, off by default. +-- Not supported: writing, E-AC-3 (UNSUPPORTED), bsid 9 / 10 reduced-rate streams. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Pcm = __include("codecs/audio/Pcm") +local Stream = __include("codecs/audio/Stream") +local Ac3 = __include("codecs/audio/Ac3") + +-- ------------------------------------------------------------------------------------------------ contract +local Ac3Format = { + name = "ac3", + category = "audio", + extensions = { "ac3", "a52" }, + mime = { "audio/ac3", "audio/x-ac3" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/Ac3" }, + caps = { decode = true, encode = false, codecs = { "ac3" }, channels = 6, streaming = true, lossy = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + maxFrames: number?, -- default 2^22 + drc: number?, -- 0 = off (default), 1 = full + crc: boolean?, -- default true; a bad frame ends the stream with Err.CHECKSUM +} + +-- ------------------------------------------------------------------------------------------------ sniff +-- E-AC-3 sniffs too, so it reports UNSUPPORTED rather than an unknown format +function Ac3Format.sniff(r: Bytes.Reader): number + local b, p, limit = r.buf, r.pos, r.limit + local h = Ac3.header(b, p, limit) + if not h then + return 0 + end + local h2 = Ac3.header(b, p + h.frameSize, limit) + if h2 and h2.sampleRate == h.sampleRate then + return 0.9 + end + return if p + h.frameSize >= limit then 0.6 else 0.3 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- a header counts when the next one follows it, or the data ends +local function index(r: Bytes.Reader, maxFrames: number): ({ number }, { number }, Ac3.Header?, Err.Err?) + local b, limit = r.buf, r.limit + local p = r.base + local offs, sizes = {}, {} + local first: Ac3.Header? = nil + while p + 8 <= limit do + local h = Ac3.header(b, p, limit) + if h and first and (h.sampleRate ~= first.sampleRate or h.bsid > 10) then + h = nil + end + if h and not first and p + h.frameSize + 8 <= limit then + local h2 = Ac3.header(b, p + h.frameSize, limit) + if not h2 then + h = nil + end + end + if not h then + p += 1 + continue + end + if not first then + first = h + if h.bsid > 10 then + return offs, sizes, first, Err.new(Err.UNSUPPORTED, "E-AC-3 (Dolby Digital Plus)", p) + elseif h.bsid > 8 then + return offs, sizes, first, Err.new(Err.UNSUPPORTED, "reduced sample rate AC-3 (bsid " .. h.bsid .. ")", p) + end + end + if p + h.frameSize > limit then + break + end + table.insert(offs, p) + table.insert(sizes, h.frameSize) + if #offs > maxFrames then + return offs, sizes, first, Err.new(Err.LIMIT, "more than " .. maxFrames .. " frames") + end + p += h.frameSize + end + return offs, sizes, first, nil +end + +function Ac3Format.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?) + local o: DecodeOptions = opts or {} + local offs, sizes, first, ierr = index(r, o.maxFrames or 2 ^ 22) + if ierr then + return nil, ierr + end + if not first or #offs == 0 then + return nil, Err.new(Err.CORRUPT, "no AC-3 syncframe", r.base) + end + local h = first :: Ac3.Header + local d = Ac3.decoder({ drc = o.drc, crc = o.crc }) + local buf = r.buf + local n = #offs + local out = { + sampleRate = h.sampleRate, + channels = h.channels, + frames = n * 1536, + duration = n * 1536 / h.sampleRate, + bitrate = h.bitrate, + tags = {}, + codec = "ac3", + acmod = h.acmod, + lfe = h.lfeon, + } + return Stream.packets(out, { + count = n, + start = function(i: number): number + return (i - 1) * 1536 + end, + decode = function(i: number): (number?, Err.Err?) + local frames, err = d:decode(buf, offs[i], sizes[i]) + if frames and d.channels ~= h.channels then + return nil, Err.new(Err.UNSUPPORTED, "channel layout change inside the stream", offs[i]) + end + return frames, err + end, + pcm = function(): { number } + return d.pcm + end, + reset = function() + d:reset() + end, + preroll = 1, + }) +end + +function Ac3Format.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) + local dec, err = Ac3Format.open(r, opts) + if not dec then + return nil, err + end + local d: any = dec + return Pcm.drain(d, { format = "ac3", codec = "ac3", acmod = d.acmod, lfe = d.lfe, bitrate = d.bitrate }) +end + +return Ac3Format +end +__FILES["audio/adpcm"] = function() + +-- audio/adpcm: headerless ADPCM (.adpcm / .ima / .vox) via codecs/audio/Adpcm; sniff is 0, the layout comes from opts. +-- "ima": DVI nibbles, high first; "ima_wav": MS IMA blocks; "ms": MS ADPCM, 7 standard coefficient pairs; "ima_qt": +-- Apple ima4 (34-byte packets, 64 frames); "psx": PS-ADPCM (16-byte frames, 28 samples). Encode: ima, ima_wav, ms. +-- Not supported: raw DSP / ADX (their coefficients live in a header). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Pcm = __include("codecs/audio/Pcm") +local Adpcm = __include("codecs/audio/Adpcm") +local Decoder = __include("codecs/audio/Adpcm/Decoder") + +-- ------------------------------------------------------------------------------------------------ contract +local Raw = { + name = "adpcm", + category = "audio", + extensions = { "adpcm", "ima" }, + mime = { "audio/x-adpcm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm", "codecs/audio/Adpcm/Decoder" }, + caps = { decode = true, encode = true, streaming = true, lossy = true, headerless = true, codecs = { "ima", "ima_wav", "ms", "ima_qt", "psx" } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type Codec = "ima" | "ima_wav" | "ms" | "ima_qt" | "psx" +type Options = { + codec: Codec?, -- default "ima" + sampleRate: number?, -- default 22050 (decode) + channels: number?, -- default 1 (decode) + blockAlign: number?, -- ima_wav / ms; default 1024 decoding, 256 * channels encoding + lowFirst: boolean?, + interleave: number?, -- psx: bytes per channel (default 16) + maxFrames: number?, -- default 2^28 +} + +-- ------------------------------------------------------------------------------------------------ constants +local CODECS = { ima = true, ima_wav = true, ms = true, ima_qt = true, psx = true } + +-- ------------------------------------------------------------------------------------------------ sniff +function Raw.sniff(_r: Bytes.Reader): number + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Raw.decode(r: Bytes.Reader, opts: Options?): (Types.Audio?, Err.Err?) + local dec, err = Raw.open(r, opts) + if not dec then + return nil, err + end + local limit = opts and opts.maxFrames or 2 ^ 28 + if dec.frames > limit or dec.frames * dec.channels > 2 ^ 28 then + return nil, Err.new(Err.LIMIT, string.format("%d frames is over the limit", dec.frames)) + end + return Pcm.drain(dec, { format = "adpcm", codec = (dec :: any).codec }, limit) +end + +-- ------------------------------------------------------------------------------------------------ encode +function Raw.encode(value: any, opts: Options?): (buffer?, Err.Err?) + local o: Options = opts or {} + local codec = o.codec or "ima" + if codec ~= "ima" and codec ~= "ima_wav" and codec ~= "ms" then + return nil, Err.new(Err.ARG, "encode: codec must be ima, ima_wav or ms") + end + local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local a, cerr = Pcm.collect(src) + if not a then + return nil, cerr + end + local ch, n, x = a.channels, a.frames, a.samples + if codec == "ima" then + local out = buffer.create((n * ch + 1) // 2) + local st = buffer.create(8 * ch) + for c = 0, ch - 1 do + Adpcm.imaEncode(x, c, ch, n, st, c * 8, out, 0, c, ch, not o.lowFirst) + end + return out, nil + end + local ba = o.blockAlign or 256 * ch + local spb = Decoder.blockFrames(codec, ba, ch) + if type(ba) ~= "number" or ba ~= math.floor(ba) or ba > 65535 or not spb or spb < 2 then + return nil, Err.new(Err.ARG, "bad blockAlign " .. tostring(ba)) + end + if codec == "ima_wav" and (ba % (4 * ch) ~= 0) then + return nil, Err.new(Err.ARG, "ima_wav: blockAlign must be a multiple of 4 * channels") + end + local blocks = (n + spb - 1) // spb + local out = buffer.create(blocks * ba) + local st = buffer.create(8 * ch) + for b = 0, blocks - 1 do + local f0 = b * spb + if codec == "ms" then + Adpcm.msEncode(x, f0, n - f0, ch, spb, out, b * ba) + else + Adpcm.imaWavEncode(x, f0, n - f0, ch, spb, st, out, b * ba) + end + end + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Raw.open(r: Bytes.Reader, opts: Options?): (Types.Decoder?, Err.Err?) + if type(r) ~= "table" or type(r.buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "open: expected a Reader") + end + local o: Options = opts or {} + local codec = o.codec or "ima" + local rate, ch = o.sampleRate or 22050, o.channels or 1 + if not CODECS[codec] then + return nil, Err.new(Err.ARG, "unknown codec " .. tostring(codec)) + end + if type(rate) ~= "number" or rate <= 0 or rate ~= rate or type(ch) ~= "number" or ch < 1 or ch > 255 or ch ~= math.floor(ch) then + return nil, Err.new(Err.ARG, "bad sampleRate or channels") + end + local size = r.limit - r.base + local dec: any = { sampleRate = rate, channels = ch, tags = {}, codec = codec, frames = 0, duration = 0 } + local d, err + if codec == "ima" then + d, err = Decoder.nibbles(dec, { buf = r.buf, offset = r.base, size = size, hi = not o.lowFirst }) + elseif codec == "psx" then + local il = o.interleave or 16 + if type(il) ~= "number" or il < 16 or il % 16 ~= 0 then + return nil, Err.new(Err.ARG, "interleave must be a multiple of 16") + end + d, err = Decoder.interleaved(dec, { kind = "psx", buf = r.buf, offset = r.base, size = size, interleave = if ch == 1 then 16 else il }) + else + local ba = o.blockAlign or 1024 + if type(ba) ~= "number" or ba < 1 or ba ~= math.floor(ba) then + return nil, Err.new(Err.ARG, "bad blockAlign") + end + d, err = Decoder.blocks(dec, { kind = codec :: any, buf = r.buf, offset = r.base, size = size, blockAlign = ba }) + end + if not d then + return nil, err + end + d.bitrate = if d.duration > 0 then math.floor(size * 8 / d.duration) else 0 + return d, nil +end + +return Raw +end +__FILES["audio/adx"] = function() + +-- audio/adx: CRI ADX via codecs/audio/Adpcm; header and decoder follow vgmstream r2117 (ISC, +-- licenses/vgmstream-LICENSE.txt), bit-exact with it. Supports: encoding type 3, versions 3-5, 1-8 channels, loop +-- points; encode as version 4. Not supported: encrypted ADX (0x0408 / 0x0409), encoding types 2 and 4, AHX. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Pcm = __include("codecs/audio/Pcm") +local Adpcm = __include("codecs/audio/Adpcm") +local Decoder = __include("codecs/audio/Adpcm/Decoder") + +-- ------------------------------------------------------------------------------------------------ contract +local Adx = { + name = "adx", + category = "audio", + extensions = { "adx" }, + mime = { "audio/x-adx" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm", "codecs/audio/Adpcm/Decoder" }, + caps = { decode = true, encode = true, streaming = true, lossy = true, loops = true, channels = 8 }, +} + +-- ------------------------------------------------------------------------------------------------ types +type Loop = { start: number, stop: number } +type DecodeOptions = { + maxFrames: number?, -- default 2^28 +} +type EncodeOptions = { + loop: Loop?, -- frames, stop exclusive; default the source's meta.source.loop + cutoff: number?, -- Hz, default 500 (as CRI's encoders) +} + +-- ------------------------------------------------------------------------------------------------ constants +local FRAME = 18 + +-- ------------------------------------------------------------------------------------------------ sniff +function Adx.sniff(r: Bytes.Reader): number + if r:peekU8(0) ~= 0x80 or r:peekU8(1) ~= 0 then + return 0 + end + local off = r:peekU8(2) * 256 + r:peekU8(3) + return if r:peek(6, off - 2) == "(c)CRI" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Adx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) + local dec, err = Adx.open(r) + if not dec then + return nil, err + end + local d = dec :: any + local limit = opts and opts.maxFrames or 2 ^ 28 + 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 + return Pcm.drain(d, { format = "adx", version = d.version, cutoff = d.cutoff, loop = d.loop }, limit) +end + +-- ------------------------------------------------------------------------------------------------ encode +function Adx.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local ch, rate = src.channels, src.sampleRate + if ch > 8 then + return nil, Err.new(Err.ARG, "ADX holds at most 8 channels") + end + if rate ~= math.floor(rate) or rate < 1 or rate >= 2 ^ 31 then + return nil, Err.new(Err.ARG, "the sample rate must be a positive integer") + end + local loop = o.loop + if loop == nil then + local v = value :: any + local m = type(v.meta) == "table" and type(v.meta.source) == "table" and v.meta.source.loop + loop = if type(m) == "table" then m else (if type(v.loop) == "table" then v.loop else nil) + end + local a, cerr = Pcm.collect(src) + if not a then + return nil, cerr + end + local n = a.frames + if loop and (type(loop.start) ~= "number" or type(loop.stop) ~= "number" or loop.start < 0 or loop.stop <= loop.start or loop.stop > n) then + return nil, Err.new(Err.ARG, "loop must be { start, stop } inside the audio") + end + local cutoff = o.cutoff or 500 + if type(cutoff) ~= "number" or cutoff < 1 or cutoff >= rate / 2 or cutoff > 65535 then + return nil, Err.new(Err.ARG, "bad cutoff") + end + cutoff = math.floor(cutoff) + local c1, c2 = Adpcm.adxCoefs(cutoff, rate) + local hist = if ch > 1 then 4 * ch else 8 + local start = 0x18 + hist + (if loop then 0x18 else 0) + 6 + start = (start + 3) // 4 * 4 + local nframes = (n + 31) // 32 + local w = Bytes.writer(start + (nframes + 1) * FRAME * ch) + w:u16be(0x8000) + w:u16be(start - 4) + w:u8(3) + w:u8(FRAME) + w:u8(4) + w:u8(ch) + w:u32be(rate) + w:u32be(n) + w:u16be(cutoff) + w:u16be(0x0400) + w:u32be(0) + w:fill(0, hist) + if loop then + local bytesAt = function(f: number): number + return start + (f // 32) * FRAME * ch + end + w:u16be(0) + w:u16be(1) + w:u32be(1) + w:u32be(loop.start) + w:u32be(bytesAt(loop.start)) + w:u32be(loop.stop) + w:u32be(bytesAt(loop.stop + 31)) + end + w:fill(0, start - 6 - w.pos) + w:string("(c)CRI") + local at = w:reserve(nframes * FRAME * ch) + local st = buffer.create(8 * ch) + for c = 0, ch - 1 do + Adpcm.adxEncode(a.samples, c, ch, n, c1, c2, st, c * 8, w.buf, at + c * FRAME, FRAME * ch) + end + w.pos = at + nframes * FRAME * ch + -- the end marker: scale 0x8001, then the padding size + w:u16be(0x8001) + w:u16be(FRAME - 4) + w:fill(0, FRAME - 4) + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Adx.open(r: Bytes.Reader, _opts: any?): (Types.Decoder?, Err.Err?) + if type(r) ~= "table" or type(r.buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "open: expected a Reader") + end + if Adx.sniff(r) == 0 then + return nil, Err.new(Err.CORRUPT, "not an ADX file") + end + local h = r:sub(0) + local copyright = (h:seek(2) and h:u16be()) or 0 + local start = copyright + 4 + local enc, fsize, bits, ch = h:u8(), h:u8(), h:u8(), h:u8() + local rate, frames, cutoff, version = h:u32be(), h:u32be(), h:u16be(), h:u16be() + if h.err then + return nil, h.err + end + if version == 0x0408 or version == 0x0409 then + return nil, Err.new(Err.UNSUPPORTED, "encrypted ADX (keys needed)") + end + if enc ~= 3 then + return nil, Err.new(Err.UNSUPPORTED, "encoding type " .. enc .. (if enc == 0x10 or enc == 0x11 then " (AHX)" else "")) + end + if fsize ~= FRAME or bits ~= 4 then + return nil, Err.new(Err.UNSUPPORTED, string.format("frame size %d, %d bits", fsize, bits)) + end + if ch < 1 or ch > 8 then + return nil, Err.new(Err.CORRUPT, "bad channel count " .. ch) + end + if rate < 1 or rate >= 2 ^ 31 then + return nil, Err.new(Err.CORRUPT, "bad sample rate " .. rate) + end + if version ~= 0x0300 and version ~= 0x0400 and version ~= 0x0500 then + return nil, Err.new(Err.UNSUPPORTED, string.format("version 0x%04X", version)) + end + local size = r.limit - r.base - start + if size < 0 then + return nil, Err.new(Err.TRUNCATED, "the header runs past the end") + end + -- loop points and the initial history (vgmstream's reading of the extra header fields) + local hist: { number }? = nil + local loopsAt: number? = nil + if version == 0x0300 then + if start - 6 >= 0x14 + 0x18 then + loopsAt = 0x14 + end + elseif version == 0x0400 then + local hsize = if ch > 1 then 4 * ch else 8 + hist = {} + for c = 0, ch - 1 do + local hh = r:sub(0x18 + c * 4, 4) + local h1, h2 = hh:i16be(), hh:i16be() + hist[c * 2 + 1], hist[c * 2 + 2] = if hh.err then 0 else h1, if hh.err then 0 else h2 + end + local ainf = 0 + local ai = r:sub(0x18 + hsize + 4, 8) + if ai:string(4) == "AINF" then + ainf = ai:u32be() + end + if start - ainf - 6 >= 0x18 + hsize + 0x18 then + loopsAt = 0x18 + hsize + end + end + local loopTable: { start: number, stop: number }? = nil + if loopsAt then + local l = r:sub(loopsAt + 4, 0x14) + local flag, ls, _, le = l:u32be(), l:u32be(), l:u32be(), l:u32be() + if not l.err and flag ~= 0 and le > ls then + loopTable = { start = ls, stop = le } + end + end + local c1, c2 = Adpcm.adxCoefs(cutoff, rate) + local dec: any = { sampleRate = rate, channels = ch, tags = {}, version = version, cutoff = cutoff, loop = loopTable } + local d, err = Decoder.interleaved(dec, { + kind = "adx", + buf = r.buf, + offset = r.base + start, + size = size, + interleave = FRAME, + frames = frames, + c1 = c1, + c2 = c2, + v3 = version == 0x0300, + hist = hist, + }) + if not d then + return nil, err + end + d.bitrate = rate * FRAME * ch * 8 // 32 + return d, nil +end + +return Adx +end +__FILES["audio/aiff"] = function() + +-- audio/aiff: AIFF / AIFF-C (Apple AIFF 1.3, AIFF-C draft 1991). Supports: PCM 1-32 bits; AIFF-C NONE / twos / +-- sowt / raw / in24 / in32 / fl32 / fl64 / ulaw / alaw / ima4; text chunks as tags; truncated SSND; encode 8-32 bit, +-- sowt, fl32, fl64, ulaw, alaw. Not supported: other compressed AIFF-C codecs, MARK / INST, the ID3 chunk. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Chunks = __include("containers/Chunks") +local Pcm = __include("codecs/audio/Pcm") +local Adpcm = __include("codecs/audio/Adpcm/Decoder") + +-- ------------------------------------------------------------------------------------------------ contract +local Aiff = { + name = "aiff", + category = "audio", + extensions = { "aiff", "aif", "aifc", "afc" }, + mime = { "audio/aiff", "audio/x-aiff" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm/Decoder", "containers/Chunks" }, + caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, lossy = false }, +} + +type DecodeOptions = { + maxFrames: number?, -- default 2^28 +} +type EncodeOptions = { + sampleFormat: ("s8" | "s16" | "s24" | "s32" | "f32" | "f64" | "ulaw" | "alaw")?, -- default "s16" + littleEndian: boolean?, -- 16-bit only, as AIFF-C "sowt" (ffmpeg reads no other sowt); default false + aifc: boolean?, -- default: only when the sample format needs it +} + +-- ------------------------------------------------------------------------------------------------ constants +local TEXT_TAGS = { NAME = "title", AUTH = "artist", ["(c) "] = "copyright", ANNO = "comment" } +local TEXT_ORDER = { { "NAME", "title" }, { "AUTH", "artist" }, { "(c) ", "copyright" }, { "ANNO", "comment" } } +local AIFC_VERSION = 0xA2805140 + +local function ext80(b: buffer, o: number): number + local se = buffer.readu8(b, o) * 256 + buffer.readu8(b, o + 1) + local hi = bit32.byteswap(buffer.readu32(b, o + 2)) + local lo = bit32.byteswap(buffer.readu32(b, o + 6)) + local e = bit32.band(se, 0x7FFF) + if e == 0 and hi == 0 and lo == 0 then + return 0 + end + if e == 0x7FFF then + return math.huge + end + local v = (hi * 4294967296 + lo) * 2 ^ (e - 16383 - 63) + return if se >= 0x8000 then -v else v +end + +local function writeExt80(w: Bytes.Writer, x: number) + if x <= 0 or x ~= x then + w:fill(0, 10) + return + end + local e = 0 + while x >= 2 ^ (e + 1) do + e += 1 + end + while x < 2 ^ e do + e -= 1 + end + local m = x * 2 ^ (63 - e) + local hi = math.floor(m / 4294967296) + local lo = m - hi * 4294967296 + w:u16be(e + 16383) + w:u32be(hi) + w:u32be(math.floor(lo)) +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", nil + elseif bits <= 16 then + return "s16be", nil + elseif bits <= 24 then + return "s24be", nil + elseif bits <= 32 then + return "s32be", nil + end + return nil, "bad sample size " .. bits + elseif comp == "sowt" then + if bits >= 1 and bits <= 8 then + return "s8", nil + elseif bits <= 16 then + return "s16le", nil + elseif bits <= 24 then + return "s24le", nil + elseif bits <= 32 then + return "s32le", nil + end + return nil, "bad sample size " .. bits + elseif comp == "raw " then + return "u8", nil + elseif comp == "in24" then + return "s24be", nil + elseif comp == "in32" then + return "s32be", nil + elseif comp == "42ni" then + return "s32le", nil + elseif comp == "fl32" or comp == "FL32" then + return "f32be", nil + elseif comp == "fl64" or comp == "FL64" then + return "f64be", nil + elseif comp == "ulaw" or comp == "ULAW" then + return "ulaw", nil + elseif comp == "alaw" or comp == "ALAW" then + return "alaw", nil + elseif comp == "ima4" then + return "ima4", nil + end + return nil, "compression " .. string.format("%q", comp) +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Aiff.sniff(r: Bytes.Reader): number + if r:remaining() < 12 or r:peek(4) ~= "FORM" then + return 0 + end + local form = buffer.readstring(r.buf, r.pos + 8, 4) + return if form == "AIFF" or form == "AIFC" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +type Info = { + channels: number, + frames: number, + sampleRate: number, + bits: number, + format: string, + compression: string, + aifc: boolean, + dataOffset: number, -- absolute in r.buf + dataSize: number, + truncated: boolean, + tags: Types.Tags, +} + +local function parse(r: Bytes.Reader): (Info?, Err.Err?) + local b = r.buf + local base, limit = r.base, r.limit + if limit - base < 12 or buffer.readstring(b, base, 4) ~= "FORM" then + return nil, Err.new(Err.CORRUPT, "not a FORM file", base) + end + local form = buffer.readstring(b, base + 8, 4) + if form ~= "AIFF" and form ~= "AIFC" then + return nil, Err.new(Err.CORRUPT, "FORM type " .. string.format("%q", form) .. " is not AIFF / AIFC", base + 8) + end + local aifc = form == "AIFC" + local formEnd = math.min(limit, base + 8 + bit32.byteswap(buffer.readu32(b, base + 4))) + local info: Info? = nil + local comm = false + local ssnd: number? = nil + local ssndLen = 0 + local tags: Types.Tags = {} + -- 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) + end + local ch = buffer.readu8(b, d) * 256 + buffer.readu8(b, d + 1) + local frames = bit32.byteswap(buffer.readu32(b, d + 2)) + local bits = buffer.readu8(b, d + 6) * 256 + buffer.readu8(b, d + 7) + local rate = ext80(b, d + 8) + local comp = if aifc then buffer.readstring(b, d + 18, 4) else "NONE" + if ch < 1 then + return nil, Err.new(Err.CORRUPT, "no channels", d) + end + if not (rate > 0 and rate < 2 ^ 31) then + return nil, Err.new(Err.CORRUPT, "bad sample rate", d + 8) + end + local fmt, why = sampleFormat(comp, bits) + if not fmt then + return nil, Err.new(if comp == "NONE" or comp == "twos" or comp == "sowt" then Err.CORRUPT else Err.UNSUPPORTED, why :: string, d + 18) + end + info = { + channels = ch, + frames = frames, + sampleRate = rate, + bits = bits, + format = fmt, + compression = comp, + aifc = aifc, + dataOffset = 0, + dataSize = 0, + truncated = false, + tags = tags, + } + comm = true + elseif id == "SSND" then + if avail < 8 then + return nil, Err.new(Err.TRUNCATED, "SSND chunk too short", p) + end + local off = bit32.byteswap(buffer.readu32(b, d)) + ssnd = d + 8 + off + ssndLen = math.max(0, avail - 8 - off) + if len >= 8 + off then + ssndLen = math.min(ssndLen, len - 8 - off) + end + elseif TEXT_TAGS[id] then + local s = buffer.readstring(b, d, avail) + local z = string.find(s, "\0", 1, true) + if z then + s = string.sub(s, 1, z - 1) + end + local key = TEXT_TAGS[id] + tags[key] = if tags[key] then tags[key] .. "\n" .. s else s + end + if len > formEnd - d then + break + end + end + if not comm or not info then + return nil, Err.new(Err.CORRUPT, "no COMM chunk", base) + end + local fi = info :: Info + if fi.frames > 0 and not ssnd then + return nil, Err.new(Err.TRUNCATED, "no SSND chunk", base) + end + local present + if fi.format == "ima4" then + fi.frames *= 64 -- COMM counts packets + present = if ssnd then ssndLen // (34 * fi.channels) * 64 else 0 + else + present = if ssnd then ssndLen // (fi.channels * Pcm.Convert.SIZE[fi.format]) else 0 + end + if present < fi.frames then + fi.frames = present + fi.truncated = true + end + fi.dataOffset = ssnd or base + fi.dataSize = ssndLen + return fi, nil +end + +function Aiff.info(r: Bytes.Reader): (Info?, Err.Err?) + return parse(r) +end + +function Aiff.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) + local dec, err = Aiff.open(r, opts) + if not dec then + return nil, err + end + return Pcm.drain(dec) +end + +-- ------------------------------------------------------------------------------------------------ encode +local FORMATS = { + s8 = { "s8", 8, "NONE" }, + s16 = { "s16be", 16, "NONE" }, + s24 = { "s24be", 24, "NONE" }, + s32 = { "s32be", 32, "NONE" }, + f32 = { "f32be", 32, "fl32" }, + f64 = { "f64be", 64, "fl64" }, + ulaw = { "ulaw", 16, "ulaw" }, + alaw = { "alaw", 16, "alaw" }, +} +local LE = { s16be = "s16le" } +local COMP_NAMES = { NONE = "not compressed", sowt = "", fl32 = "32-bit floating point", fl64 = "64-bit floating point", ulaw = "\181Law 2:1", alaw = "ALaw 2:1" } + +function Aiff.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local o: EncodeOptions = opts or {} + local spec = FORMATS[o.sampleFormat or "s16"] + if not spec then + return nil, Err.new(Err.ARG, "unknown sampleFormat " .. tostring(o.sampleFormat)) + end + local fmt, bits, comp = spec[1], spec[2], spec[3] + if o.littleEndian then + if not LE[fmt] then + return nil, Err.new(Err.ARG, "littleEndian needs 16-bit samples") + end + fmt, comp = LE[fmt], "sowt" + end + if src.channels > 65535 then + return nil, Err.new(Err.ARG, "too many channels") + end + local aifc = o.aifc or comp ~= "NONE" + local w = Bytes.writer(65536) + w:string("FORM") + w:u32be(0) + w:string(if aifc then "AIFC" else "AIFF") + if aifc then + w:string("FVER") + w:u32be(4) + w:u32be(AIFC_VERSION) + end + for _, pair in TEXT_ORDER do + local id, key = pair[1], pair[2] + local s = src.tags[key] + if type(s) == "string" and #s > 0 then + w:string(id) + w:u32be(#s) + w:string(s) + if #s % 2 == 1 then + w:u8(0) + end + end + end + local commAt = w:tell() + w:string("COMM") + if aifc then + local name = COMP_NAMES[comp] or "" + local plen = 1 + #name + plen += plen % 2 + w:u32be(22 + plen) + else + w:u32be(18) + end + w:u16be(src.channels) + w:u32be(0) -- frames, patched + w:u16be(bits) + writeExt80(w, src.sampleRate) + if aifc then + w:string(comp) + local name = COMP_NAMES[comp] or "" + w:u8(#name) + w:string(name) + if (1 + #name) % 2 == 1 then + w:u8(0) + end + end + local ssndAt = w:tell() + w:string("SSND") + w:u32be(0) -- patched + w:u32be(0) -- offset + w:u32be(0) -- block size + local frames, perr = Pcm.encode(src, fmt, w) + if not frames then + return nil, perr + end + local dataLen = w:tell() - ssndAt - 16 + if dataLen % 2 == 1 then + w:u8(0) + end + w:setU32be(ssndAt + 4, dataLen + 8) + w:setU32be(commAt + 10, frames) + w:setU32be(4, w:tell() - 8) + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Aiff.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?) + local info, err = parse(r) + if not info then + return nil, err + end + local maxFrames = opts and opts.maxFrames or 2 ^ 28 + if info.frames > maxFrames then + return nil, Err.new(Err.LIMIT, string.format("%d frames is over the %d frame limit", info.frames, maxFrames)) + end + local dec, derr + if info.format == "ima4" then + local base = { sampleRate = info.sampleRate, channels = info.channels, tags = info.tags } + dec, derr = Adpcm.blocks(base, { kind = "ima_qt", buf = r.buf, offset = info.dataOffset, size = info.dataSize, frames = info.frames }) + if dec then + (dec :: any).bitrate = math.floor(info.sampleRate * 34 * 8 * info.channels / 64) + end + else + dec, derr = Pcm.rawDecoder(r.buf, info.dataOffset, info.frames, info.channels, info.sampleRate, info.format, info.tags) + end + if not dec then + return nil, derr + end + local d = dec :: any + d.source = { + format = "aiff", + aifc = info.aifc, + compression = info.compression, + bitDepth = info.bits, + sampleFormat = info.format, + truncated = info.truncated or nil, + } + return dec, nil +end + +return Aiff +end +__FILES["audio/ape"] = function() + +-- audio/ape: Monkey's Audio (.ape) via codecs/audio/Ape and ApeTag, from the Monkey's Audio SDK 13.28 (BSD 3-clause, +-- licenses/monkeys-audio-LICENSE.txt). Supports: versions 3.95+, every level, 8-32-bit integer and 32-bit float, 1-32 +-- channels, an ID3v2 prefix, seeking by the seek table. Not supported: files before 3.95, encoding. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Pcm = __include("codecs/audio/Pcm") +local Stream = __include("codecs/audio/Stream") +local ApeTag = __include("codecs/audio/ApeTag") +local ApeCodec = __include("codecs/audio/Ape") + +-- ------------------------------------------------------------------------------------------------ contract +local Ape = { + name = "ape", + category = "audio", + extensions = { "ape" }, + mime = { "audio/ape", "audio/x-ape", "audio/x-monkeys-audio" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/Ape" }, + caps = { decode = true, encode = false, streaming = true, seek = true, lossless = true, float = true, depths = { 8, 16, 24, 32 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type OpenOptions = { + maxFrames: number?, -- default 2^28 +} + +-- ------------------------------------------------------------------------------------------------ constants +local LEVELS = { [1000] = "fast", [2000] = "normal", [3000] = "high", [4000] = "extra high", [5000] = "insane" } + +-- ------------------------------------------------------------------------------------------------ sniff +function Ape.sniff(r: Bytes.Reader): number + local head = r:peek(4) + if head == "MAC " or head == "MACF" then -- MACF: float samples + return 1 + end + if string.sub(head, 1, 3) == "ID3" then + local sz = 0 + for i = 6, 9 do + local v = r:peekU8(i) + if v < 0 then + return 0 + end + sz = sz * 128 + bit32.band(v, 127) + end + local footer = bit32.band(math.max(r:peekU8(5), 0), 0x10) ~= 0 + local id = r:peek(4, 10 + sz + (if footer then 10 else 0)) + return if id == "MAC " or id == "MACF" then 1 else 0 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Ape.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?) + local dec, err = Ape.open(r, opts) + if not dec then + return nil, err + end + local d = dec :: any + local limit = opts and opts.maxFrames or 2 ^ 28 + 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 + return Pcm.drain(d, d.source, limit) +end + +-- ------------------------------------------------------------------------------------------------ open +function Ape.open(r: Bytes.Reader, opts: OpenOptions?): (Types.Decoder?, Err.Err?) + if type(r) == "buffer" then + r = Bytes.reader(r :: any) + end + if type(r) ~= "table" or type(r.buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "open: expected a Reader") + end + local buf, base, limit = r.buf, r.base, r.limit + local tags, tagInfo = ApeTag.find(buf, base, limit) + local stop = if tagInfo then tagInfo.start else limit + local info, err = ApeCodec.info(buf, base, stop) + if not info then + return nil, err + end + if info.channels * info.blocksPerFrame > 2 ^ 24 then + return nil, Err.new(Err.LIMIT, "frames of " .. info.blocksPerFrame .. " blocks") + end + local codec, cerr = ApeCodec.decoder(info) + if not codec then + return nil, cerr + end + local frames = info.totalBlocks + local bpf = info.blocksPerFrame + local dec: any = { + sampleRate = info.sampleRate, + channels = info.channels, + frames = frames, + duration = frames / info.sampleRate, + bitrate = if frames > 0 then math.floor((stop - base) * 8 * info.sampleRate / frames) else 0, + tags = tags or {}, + bitsPerSample = info.bitsPerSample, + float = info.float, + level = LEVELS[info.level] or tostring(info.level), + version = info.version, + md5 = info.md5, + source = { format = "ape", bitDepth = info.bitsPerSample, float = info.float, level = info.level, version = info.version, programVersion = info.programVersion, tags = tagInfo and tagInfo.items }, + } + local count = info.totalFrames + return Stream.packets(dec, { + count = count, + start = function(i: number): number + return if i > count then frames else (i - 1) * bpf + end, + decode = function(i: number): (number?, Err.Err?) + return codec:frame(buf, i) + end, + pcm = function(): { number } + return codec.pcm + end, + reset = function() end, + stop = frames, + scale = if info.float then 1 else 1 / 2 ^ (info.bitsPerSample - 1), + ints = not info.float, + }) +end + +return Ape +end +__FILES["audio/au"] = function() + +-- audio/au: Sun / NeXT audio (.au / .snd), big endian. Supports: encodings 1 (mu-law), 2-5 (8-32-bit linear), 6 / 7 +-- (float), 27 (A-law), data size 0xFFFFFFFF (to the end), the annotation as tags.comment; encode to any of them. +-- Not supported: G.721 / G.722 / G.723 ADPCM and the other NeXT encodings. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Pcm = __include("codecs/audio/Pcm") + +-- ------------------------------------------------------------------------------------------------ contract +local Au = { + name = "au", + category = "audio", + extensions = { "au", "snd" }, + mime = { "audio/basic", "audio/x-au" }, + 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 }, +} + +type DecodeOptions = { + maxFrames: number?, -- default 2^28 +} +type EncodeOptions = { + sampleFormat: ("s8" | "s16" | "s24" | "s32" | "f32" | "f64" | "ulaw" | "alaw")?, -- default "s16" +} + +-- ------------------------------------------------------------------------------------------------ constants +local ENCODINGS: { [number]: string } = { + [1] = "ulaw", + [2] = "s8", + [3] = "s16be", + [4] = "s24be", + [5] = "s32be", + [6] = "f32be", + [7] = "f64be", + [27] = "alaw", +} +local WRITE = { + ulaw = { 1, "ulaw" }, + s8 = { 2, "s8" }, + s16 = { 3, "s16be" }, + s24 = { 4, "s24be" }, + s32 = { 5, "s32be" }, + f32 = { 6, "f32be" }, + f64 = { 7, "f64be" }, + alaw = { 27, "alaw" }, +} +local BITS = { ulaw = 8, alaw = 8, s8 = 8, s16be = 16, s24be = 24, s32be = 32, f32be = 32, f64be = 64 } + +local function be32(b: buffer, o: number): number + return bit32.byteswap(buffer.readu32(b, o)) +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Au.sniff(r: Bytes.Reader): number + return if r:peek(4) == ".snd" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Au.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) + local dec, err = Au.open(r, opts) + if not dec then + return nil, err + end + return Pcm.drain(dec) +end + +-- ------------------------------------------------------------------------------------------------ encode +function Au.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local o: EncodeOptions = opts or {} + local spec = WRITE[o.sampleFormat or "s16"] + if not spec then + return nil, Err.new(Err.ARG, "unknown sampleFormat " .. tostring(o.sampleFormat)) + end + if src.sampleRate ~= math.floor(src.sampleRate) or src.sampleRate >= 2 ^ 32 then + return nil, Err.new(Err.ARG, "the sample rate must be an integer") + end + -- annotation: the comment tag, NUL-terminated, padded to a multiple of 8 (at least 4 bytes, as Sun requires) + local note = if type(src.tags.comment) == "string" then src.tags.comment else "" + local alen = #note + 1 + alen = math.max(8, alen + (8 - alen % 8) % 8) + local w = Bytes.writer(65536) + w:string(".snd") + w:u32be(24 + alen) + w:u32be(0xFFFFFFFF) + w:u32be(spec[1]) + w:u32be(src.sampleRate) + w:u32be(src.channels) + w:string(note) + w:fill(0, alen - #note) + local frames, perr = Pcm.encode(src, spec[2], w) + if not frames then + return nil, perr + end + w:setU32be(8, w:tell() - 24 - alen) + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Au.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?) + local b, base, limit = r.buf, r.base, r.limit + if limit - base < 24 or buffer.readstring(b, base, 4) ~= ".snd" then + return nil, Err.new(Err.CORRUPT, "bad magic", base) + end + local off, size, enc, rate, ch = be32(b, base + 4), be32(b, base + 8), be32(b, base + 12), be32(b, base + 16), be32(b, base + 20) + local fmt = ENCODINGS[enc] + if not fmt then + return nil, Err.new(Err.UNSUPPORTED, "encoding " .. enc, base + 12) + end + if ch < 1 or ch > 65535 then + return nil, Err.new(Err.CORRUPT, "bad channel count " .. ch, base + 20) + end + if rate < 1 then + return nil, Err.new(Err.CORRUPT, "bad sample rate", base + 16) + end + if off < 24 or off > limit - base then + return nil, Err.new(Err.CORRUPT, "bad data offset", base + 4) + end + local tags: Types.Tags = {} + if off > 24 then + local s = buffer.readstring(b, base + 24, off - 24) + local z = string.find(s, "\0", 1, true) + if z then + s = string.sub(s, 1, z - 1) + end + if #s > 0 then + tags.comment = s + end + end + local avail = limit - base - off + local truncated = false + if size == 0xFFFFFFFF then + size = avail + elseif size > avail then + size = avail + truncated = true + end + local frameBytes = ch * Pcm.Convert.SIZE[fmt] + local frames = size // frameBytes + local maxFrames = opts and opts.maxFrames or 2 ^ 28 + if frames > maxFrames then + return nil, Err.new(Err.LIMIT, string.format("%d frames is over the %d frame limit", frames, maxFrames)) + end + local dec, derr = Pcm.rawDecoder(b, base + off, frames, ch, rate, fmt, tags) + if not dec then + return nil, derr + end + local d = dec :: any + d.source = { format = "au", encoding = enc, sampleFormat = fmt, bitDepth = BITS[fmt], truncated = truncated or nil } + return dec, nil +end + +return Au +end +__FILES["audio/brstm"] = function() + +-- audio/brstm: Nintendo BRSTM (Wii, "RSTM", BE), BCSTM (3DS, "CSTM", LE), BFSTM (Wii U BE / Switch LE, "FSTM"); layouts +-- follow vgmstream r2117 (ISC, licenses/vgmstream-LICENSE.txt), bit-exact. Supports: DSP ADPCM, PCM16 / PCM8, 1-255 +-- channels, loop points. Read only. Not supported: BCSTM IMA ADPCM, BRSTM 0.1, BFSTM regions, the track table. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Pcm = __include("codecs/audio/Pcm") +local Decoder = __include("codecs/audio/Adpcm/Decoder") + +-- ------------------------------------------------------------------------------------------------ contract +local Brstm = { + name = "brstm", + category = "audio", + extensions = { "brstm", "bcstm", "bfstm" }, + mime = { "audio/x-brstm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm/Decoder" }, + caps = { decode = true, encode = false, streaming = true, lossy = true, loops = true, containers = { "RSTM", "CSTM", "FSTM" } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + maxFrames: number?, -- default 2^28 +} + +-- ------------------------------------------------------------------------------------------------ constants +local CODECS = { [0] = "pcm8", [1] = "pcm16", [2] = "dsp", [3] = "ima" } + +-- ------------------------------------------------------------------------------------------------ sniff +function Brstm.sniff(r: Bytes.Reader): number + local m = r:peek(4) + if m ~= "RSTM" and m ~= "CSTM" and m ~= "FSTM" then + return 0 + end + local bom = r:peek(2, 4) + return if bom == "\254\255" or bom == "\255\254" then 1 else 0 +end + +function Brstm.variant(r: Bytes.Reader): string? + local m = r:peek(4) + return if m == "RSTM" then "brstm" elseif m == "CSTM" then "bcstm" elseif m == "FSTM" then "bfstm" else nil +end + +-- ------------------------------------------------------------------------------------------------ decode +function Brstm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) + local dec, err = Brstm.open(r) + if not dec then + return nil, err + end + local d = dec :: any + local limit = opts and opts.maxFrames or 2 ^ 28 + 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 + return Pcm.drain(d, { format = "brstm", container = d.container, codec = d.codec, loop = d.loop }, limit) +end + +-- ------------------------------------------------------------------------------------------------ open +local function view(r: Bytes.Reader, be: boolean) + local v = { err = nil :: string? } + local size = r.limit - r.base + local function at(o: number, n: number): Bytes.Reader? + if o < 0 or o + n > size then + v.err = "an offset points past the end" + return nil + end + return r:sub(o, n) + end + function v.u8(o: number): number + local s = at(o, 1) + return if s then s:u8() else 0 + end + function v.u16(o: number): number + local s = at(o, 2) + return if s then (if be then s:u16be() else s:u16le()) else 0 + end + function v.i16(o: number): number + local s = at(o, 2) + return if s then (if be then s:i16be() else s:i16le()) else 0 + end + function v.u32(o: number): number + local s = at(o, 4) + return if s then (if be then s:u32be() else s:u32le()) else 0 + end + function v.i32(o: number): number + local s = at(o, 4) + return if s then (if be then s:i32be() else s:i32le()) else 0 + end + return v +end + +type Layout = { + codec: number, + loop: boolean, + ch: number, + rate: number, + loopStart: number, + frames: number, + blockSize: number, + lastPadded: number, + data: number, -- absolute + adp: { number }, -- each channel's DSP info offset (coefficients, then gain, ps, yn1, yn2) + hist: number?, -- the per-block history table: (yn1, yn2) per channel per block + histEntries: number, +} + +local function parseRstm(v: any): (Layout?, string?) + if v.u16(0x06) ~= 0x0100 then + return nil, string.format("unsupported: BRSTM version %d.%d", v.u8(0x06), v.u8(0x07)) + end + local head = v.u32(0x10) + local adpc = v.u32(0x18) + if v.u32(head) ~= 0x48454144 then -- "HEAD", read big-endian + return nil, "no HEAD chunk" + end + local base = head + 8 + local info = base + v.u32(base + 4) + local chans = base + v.u32(base + 20) + local ch = v.u8(info + 2) + local L: Layout = { + codec = v.u8(info), + loop = v.u8(info + 1) ~= 0, + ch = ch, + rate = v.u16(info + 4), + loopStart = v.u32(info + 8), + frames = v.u32(info + 12), + data = v.u32(info + 16), + blockSize = v.u32(info + 24), + lastPadded = v.u32(info + 40), + adp = {}, + hist = nil, + histEntries = 0, + } + for c = 0, ch - 1 do + local ci = base + v.u32(chans + 4 + c * 8 + 4) + L.adp[c + 1] = base + v.u32(ci + 4) + end + if adpc > 0 and v.u32(adpc) == 0x41445043 then -- "ADPC" + L.hist = adpc + 8 + L.histEntries = (v.u32(adpc + 4) - 8) // math.max(1, 4 * ch) + end + return L, nil +end + +local function parseFstm(v: any): (Layout?, string?) + local info: number, seek: number, data: number = 0, 0, 0 + local seekSize: number = 0 + for i = 0, math.min(v.u16(0x10), 16) - 1 do + local id, off = v.u16(0x14 + i * 12), v.u32(0x14 + i * 12 + 4) + if id == 0x4000 then + info = off + elseif id == 0x4001 then + seek = off + seekSize = v.u32(0x14 + i * 12 + 8) :: number + elseif id == 0x4002 then + data = off + end + end + if info == 0 or data == 0 then + return nil, "no INFO or DATA block" + end + local stream = info + 8 + v.i32(info + 0x0C) + local chans = info + 8 + v.i32(info + 0x1C) + local ch = v.u8(stream + 2) + local dataRef = stream + 0x30 + local L: Layout = { + codec = v.u8(stream), + loop = v.u8(stream + 1) ~= 0, + ch = ch, + rate = v.u32(stream + 4), + loopStart = v.u32(stream + 8), + frames = v.u32(stream + 12), + blockSize = v.u32(stream + 20), + lastPadded = v.u32(stream + 36), + data = if v.u16(dataRef) == 0x1F00 then data + 8 + v.i32(dataRef + 4) else data + 0x20, + adp = {}, + hist = nil, + histEntries = 0, + } + for c = 0, ch - 1 do + local ci = chans + v.i32(chans + 4 + c * 8 + 4) + L.adp[c + 1] = ci + v.i32(ci + 4) + end + if seek > 0 and seekSize > 8 then + L.hist = seek + 8 + L.histEntries = (seekSize - 8) // math.max(1, 4 * ch) + end + return L, nil +end + +function Brstm.open(r: Bytes.Reader, _opts: any?): (Types.Decoder?, Err.Err?) + if type(r) ~= "table" or type(r.buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "open: expected a Reader") + end + if r.limit - r.base < 0x40 then + return nil, Err.new(Err.TRUNCATED, "the header runs past the end") + end + if Brstm.sniff(r) == 0 then + return nil, Err.new(Err.CORRUPT, "not a BRSTM / BCSTM / BFSTM file") + end + local magic = r:peek(4) + local be = r:peek(2, 4) == "\254\255" + local v = view(r, be) + local parsed: Layout?, msg: string? + if magic == "RSTM" then + if not be then + return nil, Err.new(Err.CORRUPT, "a little-endian BRSTM") + end + parsed, msg = parseRstm(v) + else + parsed, msg = parseFstm(v) + end + if v.err then + return nil, Err.new(Err.TRUNCATED, v.err) + elseif not parsed then + return nil, Err.from(msg) + end + local L = parsed :: Layout + local codec = CODECS[L.codec] + if not codec then + return nil, Err.new(Err.CORRUPT, "codec " .. L.codec) + elseif codec == "ima" then + return nil, Err.new(Err.UNSUPPORTED, "IMA ADPCM streams") + end + local ch = L.ch + if ch < 1 or L.rate < 1 then + return nil, Err.new(Err.CORRUPT, "bad channel count or sample rate") + end + local size = r.limit - r.base - L.data + if L.data < 0 or size < 0 then + return nil, Err.new(Err.TRUNCATED, "the data starts past the end") + end + local kind = if codec == "dsp" then "dsp" elseif codec == "pcm8" then "s8" elseif be then "s16be" else "s16le" + local coefs: buffer? = nil + local hist: { number }? = nil + if codec == "dsp" then + coefs = buffer.create(64 * ch) + hist = {} + for c = 0, ch - 1 do + local adp = L.adp[c + 1] + for k = 0, 15 do + buffer.writei32(coefs :: buffer, c * 64 + k * 4, v.i16(adp + k * 2)) + end + hist[c * 2 + 1], hist[c * 2 + 2] = v.i16(adp + 36), v.i16(adp + 38) + end + if v.err then + return nil, Err.new(Err.TRUNCATED, v.err) + end + end + local histAt, entries = L.hist, L.histEntries + local loop = if L.loop and L.loopStart < L.frames then { start = L.loopStart, stop = L.frames } else nil + local dec: any = { sampleRate = L.rate, channels = ch, tags = {}, container = magic, codec = codec, loop = loop } + local block = L.blockSize + if block < 1 or (kind == "dsp" and block % 8 ~= 0) or (kind ~= "s8" and block % 2 ~= 0) then + return nil, Err.new(Err.CORRUPT, "bad block size " .. block) + end + local d, err = Decoder.interleaved(dec, { + kind = kind :: any, + buf = r.buf, + offset = r.base + L.data, + size = size, + interleave = block, + lastInterleave = if L.lastPadded > 0 and L.lastPadded <= block then L.lastPadded else block, + frames = L.frames, + coefs = coefs, + hist = hist, + restore = if codec == "dsp" and histAt + then function(row: number, st: buffer): boolean + if row >= entries then + return false + end + for c = 0, ch - 1 do + local p = (histAt :: number) + (row * ch + c) * 4 + buffer.writei32(st, c * 8, v.i16(p)) + buffer.writei32(st, c * 8 + 4, v.i16(p + 2)) + end + return v.err == nil + end + else nil, + }) + if d then + d.bitrate = if d.duration > 0 then math.floor(size * 8 / d.duration) else 0 + end + return d, err +end + +return Brstm +end +__FILES["audio/caf"] = function() + +-- audio/caf: Apple Core Audio Format (CAF 1.0 spec). Supports: linear PCM (8-32-bit integer, 32 / 64-bit float, either +-- endian), ALAC, AAC-LC (kuki esds), mu-law, A-law, IMA4; pakt trimming, data size -1, info tags, seeking; encode PCM +-- (16 / 24-bit BE, 32-bit float) and ALAC (16 / 20 / 24-bit). Not supported: other compressed formats. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Chunks = __include("containers/Chunks") +local Pcm = __include("codecs/audio/Pcm") +local Stream = __include("codecs/audio/Stream") +local Aac = __include("codecs/audio/Aac") +local Alac = __include("codecs/audio/Alac") +local Adpcm = __include("codecs/audio/Adpcm/Decoder") + +-- ------------------------------------------------------------------------------------------------ contract +local Caf = { + name = "caf", + category = "audio", + extensions = { "caf", "caff" }, + mime = { "audio/x-caf" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Aac", "codecs/audio/Adpcm/Decoder", "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 }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + maxPackets: number?, -- default 2^24 +} +type EncodeOptions = { + codec: ("pcm" | "alac")?, -- default "alac" + bitDepth: number?, -- pcm: 16 (default), 24, 32 (float); alac: 16 (default), 20, 24 + tags: Types.Tags?, -- default: the audio's tags +} + +-- ------------------------------------------------------------------------------------------------ constants +local INFO_TAGS: { [string]: string } = { + title = "title", artist = "artist", album = "album", year = "date", genre = "genre", ["track number"] = "track", + comments = "comment", composer = "composer", copyright = "copyright", lyricist = "lyricist", + ["encoding application"] = "encoder", ["recorded date"] = "recorded", tempo = "bpm", +} +local TAG_INFO: { [string]: string } = {} +for k, v in INFO_TAGS do + TAG_INFO[v] = k +end + +local ULAW, ALAW = table.create(256, 0), table.create(256, 0) +for i = 0, 255 do + local u = 255 - i + local t = (bit32.band(u, 15) * 8 + 132) * 2 ^ bit32.band(bit32.rshift(u, 4), 7) + ULAW[i + 1] = if bit32.band(u, 128) ~= 0 then 132 - t else t - 132 + local a = bit32.bxor(i, 0x55) + local seg = bit32.band(bit32.rshift(a, 4), 7) + local m = bit32.band(a, 15) * 16 + 8 + if seg > 0 then + m = (m + 256) * 2 ^ (seg - 1) + end + ALAW[i + 1] = if bit32.band(a, 128) ~= 0 then m else -m +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Caf.sniff(r: Bytes.Reader): number + local h = r:peek(8) + if #h == 8 and string.sub(h, 1, 4) == "caff" and string.byte(h, 5) == 0 and string.byte(h, 6) == 1 then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +type Desc = { rate: number, format: string, flags: number, bytesPerPacket: number, framesPerPacket: number, channels: number, bits: number } +type Parsed = { + desc: Desc, + dataStart: number, -- absolute + dataEnd: number, + cookie: buffer?, + packets: { number }?, -- sizes (pakt) + packetFrames: { number }?, + priming: number, + remainder: number, + validFrames: number?, + tags: Types.Tags, +} + +-- the esds payload in a kuki (version / flags, then the ES_Descriptor) -> the DecoderSpecificInfo +local function esdsConfig(b: buffer): buffer? + local r = Bytes.reader(b) + if r:peekU8() ~= 3 then + r:skip(4) -- the esds atom's version / flags + end + local function len(): number + local n = 0 + for _ = 1, 4 do + local c = r:u8() + n = n * 128 + bit32.band(c, 127) + if c < 128 then + break + end + end + return n + end + while not r:eof() and not r.err do + local tag = r:u8() + local n = len() + if tag == 3 then + r:skip(2) + local f = r:u8() + if bit32.band(f, 0x80) ~= 0 then + r:skip(2) + end + if bit32.band(f, 0x40) ~= 0 then + r:skip(r:u8()) + end + if bit32.band(f, 0x20) ~= 0 then + r:skip(2) + end + elseif tag == 4 then + r:skip(13) + elseif tag == 5 then + if n > 0 and r:need(n) then + return r:bytes(n) + end + return nil + else + r:skip(n) + end + end + return nil +end + +local function vlq(r: Bytes.Reader): number + local v = 0 + for _ = 1, 8 do + local c = r:u8() + v = v * 128 + bit32.band(c, 127) + if c < 128 then + return v + end + end + r:fail(Err.CORRUPT, "bad packet table entry") + return 0 +end + +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 + local p: Parsed = { desc = nil :: any, dataStart = 0, dataEnd = 0, priming = 0, remainder = 0, tags = {} } + local haveData = false + -- 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 = { + rate = c:f64be(), + format = c:string(4), + flags = c:u32be(), + bytesPerPacket = c:u32be(), + framesPerPacket = c:u32be(), + channels = c:u32be(), + bits = c:u32be(), + } + if c.err then + return nil, c.err + end + elseif typ == "data" then + p.dataStart = start + 4 -- edit count + p.dataEnd = stop + haveData = true + elseif typ == "kuki" then + p.cookie = c:bytes(stop - start) + elseif typ == "pakt" then + local n = c:i64be() + p.validFrames = c:i64be() + p.priming = c:i32be() + p.remainder = c:i32be() + if c.err then + return nil, c.err + end + if n < 0 or n > (o.maxPackets or 2 ^ 24) or n > c:remaining() then + return nil, Err.new(Err.LIMIT, "packet table of " .. n .. " entries", start) + end + local d = p.desc + if not d then + return nil, Err.new(Err.CORRUPT, "pakt before desc", start) + end + local sizes, frames = table.create(n, 0), nil + if d.framesPerPacket == 0 then + frames = table.create(n, 0) + end + for i = 1, n do + sizes[i] = if d.bytesPerPacket == 0 then vlq(c) else d.bytesPerPacket + if frames then + frames[i] = vlq(c) + end + end + if c.err then + return nil, c.err + end + p.packets, p.packetFrames = sizes, frames + elseif typ == "info" then + local n = c:u32be() + for _ = 1, math.min(n, 1000) do + local k = c:cstring() + local v = c:cstring() + if c.err then + break + end + p.tags[INFO_TAGS[string.lower(k)] or string.lower(k)] = v + end + end + if typ == "data" and stop >= r.limit then + break + end + end + if not p.desc then + return nil, Err.new(Err.CORRUPT, "no desc chunk", r.base) + end + if not haveData then + return nil, Err.new(Err.CORRUPT, "no data chunk", r.base) + end + local d = p.desc + if d.channels < 1 or d.channels > 64 or d.rate <= 0 or d.rate ~= d.rate or d.rate > 1e7 then + return nil, Err.new(Err.CORRUPT, "bad stream description") + end + return p, nil +end + +type Source = { + channels: number, + rate: number, + packetCount: number, + packetFrames: (number) -> number, + decode: (number) -> (number?, Err.Err?), + pcm: { number }, + reset: () -> (), + codec: string, + bits: number?, +} + +local function source(r: Bytes.Reader, p: Parsed): (Source?, Err.Err?) + local d = p.desc + local b = r.buf + local ch = d.channels + local fmt = d.format + if fmt == "lpcm" or fmt == "ulaw" or fmt == "alaw" then + local bits = if fmt == "lpcm" then d.bits else 8 + local float = fmt == "lpcm" and bit32.band(d.flags, 1) ~= 0 + local little = fmt == "lpcm" and bit32.band(d.flags, 2) ~= 0 + local bpf = d.bytesPerPacket + if bpf == 0 then + bpf = ch * (bits // 8) + end + if not (bits == 8 or bits == 16 or bits == 24 or bits == 32 or (bits == 64 and float)) or (float and bits < 32) then + return nil, Err.new(Err.UNSUPPORTED, "linear PCM with " .. bits .. " bits") + end + local bps = bits // 8 + if bpf < ch * bps then + return nil, Err.new(Err.CORRUPT, "bytes per packet smaller than a frame") + end + local total = (p.dataEnd - p.dataStart) // bpf + local per = 1024 + local pcm = table.create(per * ch, 0) + local scale = 1 / 2 ^ (bits - 1) + local readu8, readi8 = buffer.readu8, buffer.readi8 + local src: Source = { + channels = ch, + rate = d.rate, + packetCount = (total + per - 1) // per, + packetFrames = function(i: number): number + return math.min(per, total - (i - 1) * per) + end, + pcm = pcm, + reset = function() end, + codec = if fmt == "lpcm" then "pcm" else fmt, + bits = bits, + decode = function(i: number): (number?, Err.Err?) + local f0 = (i - 1) * per + local n = math.min(per, total - f0) + local k = 1 + for f = f0, f0 + n - 1 do + local q = p.dataStart + f * bpf + for _ = 1, ch do + local v + if fmt == "ulaw" then + v = ULAW[readu8(b, q) + 1] / 32768 + elseif fmt == "alaw" then + v = ALAW[readu8(b, q) + 1] / 32768 + elseif float then + if bits == 32 then + v = if little then buffer.readf32(b, q) else Bytes.reader(b, q, 4):f32be() + else + v = if little then buffer.readf64(b, q) else Bytes.reader(b, q, 8):f64be() + end + elseif bits == 8 then + v = readi8(b, q) * scale + elseif bits == 16 then + v = if little then buffer.readi16(b, q) else readi8(b, q) * 256 + readu8(b, q + 1) + v *= scale + elseif bits == 24 then + if little then + v = readi8(b, q + 2) * 65536 + readu8(b, q + 1) * 256 + readu8(b, q) + else + v = readi8(b, q) * 65536 + readu8(b, q + 1) * 256 + readu8(b, q + 2) + end + v *= scale + else + if little then + v = buffer.readi32(b, q) + else + v = readi8(b, q) * 16777216 + readu8(b, q + 1) * 65536 + readu8(b, q + 2) * 256 + readu8(b, q + 3) + end + v *= scale + end + pcm[k] = v + k += 1 + q += bps + end + end + return n, nil + end, + } + return src, nil + end + local sizes = p.packets + if not sizes or (#sizes == 0 and d.bytesPerPacket > 0) then -- constant packets: pakt may list none + if d.bytesPerPacket > 0 then + local n = (p.dataEnd - p.dataStart) // d.bytesPerPacket + sizes = table.create(n, d.bytesPerPacket) + else + return nil, Err.new(Err.CORRUPT, "compressed CAF without a packet table") + end + end + local offsets = table.create(#(sizes :: { number }), 0) + local o = p.dataStart + for i, s in sizes :: { number } do + offsets[i] = o + o += s + if o > p.dataEnd then + -- a truncated file: keep the whole packets + offsets[i] = nil :: any + sizes = table.move(sizes :: { number }, 1, i - 1, 1, {}) + break + end + end + local count = #(sizes :: { number }) + local fpp = d.framesPerPacket + local pf = p.packetFrames + local function framesOf(i: number): number + return if pf then pf[i] else fpp + end + local cookie = p.cookie + if fmt == "alac" then + if not cookie then + return nil, Err.new(Err.CORRUPT, "ALAC without a magic cookie") + end + local cfg, err = Alac.config(cookie :: buffer) + if not cfg then + return nil, err + end + local dec = Alac.decoder(cfg) + local pcm = table.create(cfg.frameLength * cfg.channels, 0) + local scale = 1 / 2 ^ (cfg.bitDepth - 1) + return { + channels = cfg.channels, + rate = d.rate, + packetCount = count, + packetFrames = framesOf, + pcm = pcm, + reset = function() end, + codec = "alac", + bits = cfg.bitDepth, + decode = function(i: number): (number?, Err.Err?) + local n, e = dec:decode(b, offsets[i], (sizes :: { number })[i]) + if not n then + return nil, e + end + local src = dec.pcm + for k = 1, n * cfg.channels do + pcm[k] = src[k] * scale + end + return n, nil + end, + }, nil + elseif fmt == "aac " then + local asc = if cookie then esdsConfig(cookie :: buffer) else nil + if not asc then + return nil, Err.new(Err.CORRUPT, "AAC without an esds magic cookie") + end + local dec, err = Aac.decoder(asc :: buffer) + if not dec then + return nil, err + end + local ad = dec :: Aac.Decoder + return { + channels = ad.channels, + rate = d.rate, + packetCount = count, + packetFrames = framesOf, + pcm = ad.pcm, + reset = function() + ad:reset() + end, + codec = "aac", + decode = function(i: number): (number?, Err.Err?) + return ad:decode(b, offsets[i], (sizes :: { number })[i]) + end, + }, nil + end + return nil, Err.new(Err.UNSUPPORTED, "CAF format '" .. fmt .. "'") +end + +function Caf.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?) + local p, err = parse(r, opts or {}) + if not p then + return nil, err + end + local pp = p :: Parsed + if pp.desc.format == "ima4" then + -- Apple IMA ADPCM: 34-byte packets per channel, 64 frames; the predictor carries across packets + local ch = pp.desc.channels + local packets = (pp.dataEnd - pp.dataStart) // (34 * ch) + local frames = packets * 64 + if pp.validFrames and pp.validFrames >= 0 then + frames = math.min(frames, pp.validFrames) + end + local dec: any = { sampleRate = pp.desc.rate, channels = ch, tags = pp.tags, codec = "ima4", bitsPerSample = 16 } + local d, derr = Adpcm.blocks(dec, { kind = "ima_qt", buf = r.buf, offset = pp.dataStart, size = pp.dataEnd - pp.dataStart, frames = frames }) + if d then + d.bitrate = math.floor(pp.desc.rate * 34 * 8 * ch / 64) + end + return d, derr + end + local s, serr = source(r, pp) + if not s then + return nil, serr + end + local src = s :: Source + local ch, rate = src.channels, src.rate + local starts = table.create(src.packetCount + 1, 0) + local total = 0 + for i = 1, src.packetCount do + starts[i] = total + total += src.packetFrames(i) + end + starts[src.packetCount + 1] = total + local skip = math.max(0, p.priming) + local stopAt = total + if p.validFrames and p.validFrames >= 0 then + stopAt = math.min(total, skip + p.validFrames) + elseif p.remainder > 0 then + stopAt = math.max(skip, total - p.remainder) + end + local frames = math.max(0, stopAt - skip) + local dec: any = { + sampleRate = rate, + channels = ch, + frames = frames, + duration = frames / rate, + bitrate = if frames > 0 then math.floor((p.dataEnd - p.dataStart) * 8 * rate / frames) else 0, + tags = p.tags, + codec = src.codec, + bitsPerSample = src.bits, + } + 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?) + local dec, err = Caf.open(r, opts) + if not dec then + return nil, err + end + local d: any = dec + return Pcm.drain(d, { format = "caf", codec = d.codec, bitsPerSample = d.bitsPerSample }) +end + +-- ------------------------------------------------------------------------------------------------ encode +local function chunk(w: Bytes.Writer, typ: string, size: number) + w:string(typ) + w:i64be(size) +end + +function Caf.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + 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 + local codec = o.codec or "alac" + if codec ~= "alac" and codec ~= "pcm" then + return nil, Err.new(Err.ARG, "codec must be 'alac' or 'pcm'") + end + local sr, ch = value.sampleRate, value.channels + local depth = o.bitDepth or 16 + if codec == "pcm" and depth ~= 16 and depth ~= 24 and depth ~= 32 then + return nil, Err.new(Err.ARG, "pcm bitDepth 16, 24 or 32 (float)") + end + if ch < 1 or ch > 64 or sr <= 0 then + return nil, Err.new(Err.ARG, "bad sample rate / channels") + end + local isAudio = value.kind == "audio" and type(value.samples) == "buffer" + if not isAudio and type(value.read) ~= "function" then + return nil, Err.new(Err.ARG, "expected an Audio or a Decoder") + end + if isAudio and buffer.len(value.samples) < value.frames * ch * 4 then + return nil, Err.new(Err.ARG, "audio.samples is shorter than frames * channels") + end + local done = 0 + local chunkBuf: buffer? = nil + local function nextBlock(n: number): (buffer?, number, number) + if isAudio then + local k = math.min(n, value.frames - done) + local base = done * ch * 4 + done += k + return value.samples, base, k + end + local b, got = value:read(n, chunkBuf) + chunkBuf = b + done += got + return b, 0, got + end + local readf32 = buffer.readf32 + local data = Bytes.writer(65536) + local sizes: { number } = {} + local enc: Alac.Encoder? = nil + if codec == "alac" then + local e, err = Alac.encoder({ sampleRate = math.floor(sr), channels = ch, bitDepth = depth }) + if not e then + return nil, err + end + enc = e + local ints = table.create(4096 * ch, 0) + local peak = 2 ^ (depth - 1) + while true do + local b, base, n = nextBlock(4096) + if not b or n <= 0 then + break + end + for i = 0, n * ch - 1 do + local v = math.floor(readf32(b, base + i * 4) * peak + 0.5) + ints[i + 1] = math.clamp(v, -peak, peak - 1) + end + local pkt, perr = (e :: Alac.Encoder):encode(ints, 1, n) + if not pkt then + return nil, perr + end + data:bytes(pkt) + table.insert(sizes, buffer.len(pkt)) + end + else + local peak = 2 ^ (depth - 1) + while true do + local b, base, n = nextBlock(4096) + if not b or n <= 0 then + break + end + for i = 0, n * ch - 1 do + local f = readf32(b, base + i * 4) + if depth == 32 then + data:f32be(f) + else + local v = math.clamp(math.floor(f * peak + 0.5), -peak, peak - 1) + if depth == 16 then + data:u16be(v % 65536) + else + data:u24be(v % 16777216) + end + end + end + end + end + local frames = done + local w = Bytes.writer(data:tell() + 1024) + w:string("caff") + w:u16be(1) + w:u16be(0) + chunk(w, "desc", 32) + w:f64be(sr) + if codec == "alac" then + w:string("alac") + w:u32be(({ [16] = 1, [20] = 2, [24] = 3, [32] = 4 })[depth] or 1) + w:u32be(0) + w:u32be(4096) + w:u32be(ch) + w:u32be(0) + else + w:string("lpcm") + w:u32be(if depth == 32 then 1 else 0) -- float / big-endian integer + w:u32be(ch * depth // 8) + w:u32be(1) + w:u32be(ch) + w:u32be(depth) + end + local tags = o.tags or value.tags or {} + local keys = {} + for k, v in tags do + if type(v) == "string" then + table.insert(keys, k) + end + end + table.sort(keys) + if #keys > 0 then + local info = Bytes.writer(256) + info:u32be(#keys) + for _, k in keys do + info:cstring(TAG_INFO[k] or k) + info:cstring(tags[k]) + end + chunk(w, "info", info:tell()) + w:bytes(info.buf, 0, info:tell()) + end + if enc then + local cookie = Alac.cookie(enc.config) + chunk(w, "kuki", buffer.len(cookie)) + w:bytes(cookie) + local pk = Bytes.writer(64 + #sizes * 2) + pk:i64be(#sizes) + pk:i64be(frames) + pk:u32be(0) + pk:u32be(#sizes * 4096 - frames) + for _, s in sizes do + -- BER variable-length integer + local bytes = { s % 128 } + local v = s // 128 + while v > 0 do + table.insert(bytes, 1, 128 + v % 128) + v //= 128 + end + for _, x in bytes do + pk:u8(x) + end + end + chunk(w, "pakt", pk:tell()) + w:bytes(pk.buf, 0, pk:tell()) + end + chunk(w, "data", data:tell() + 4) + w:u32be(0) -- edit count + w:bytes(data.buf, 0, data:tell()) + return w:finish(), nil +end + +return Caf +end +__FILES["audio/flac"] = function() + +-- audio/flac: FLAC (RFC 9639), native and Ogg FLAC; absorbed from flac-luau 7083d0d (same author). Supports: every +-- subframe type, Rice / Rice2, 4-32 bits, 1-8 channels, CRC-16 resync, seeking, an ID3v2 prefix, the main metadata +-- blocks; encode levels 0-8 (libFLAC presets), 4-24 bits. Not supported: MD5 check on decode, chained Ogg, Ogg output. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Ogg = __include("containers/Ogg") +local Stream = __include("audio/flac/Stream") +local Encode = __include("codecs/audio/Flac/Encode") +local Pcm = __include("codecs/audio/Pcm") + +-- ------------------------------------------------------------------------------------------------ contract +local Flac = { + name = "flac", + category = "audio", + extensions = { "flac", "oga" }, + mime = { "audio/flac", "audio/x-flac" }, + 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 }, +} + +-- ------------------------------------------------------------------------------------------------ types +type Decoder = Stream.Decoder +type OpenOptions = { + crc16: boolean?, -- default true; a bad frame is skipped by resyncing + maxFrames: number?, -- default 2^28 +} +type EncodeOptions = { + level: number?, -- 0..8 like libFLAC's -0 .. -8 (default 5) + bits: number?, -- 4..24; default the source's bit depth if 4..24, else 16 + blockSize: number?, -- 16..65535 (default: the level's, 1152 or 4096) + seekInterval: number?, -- seconds between SEEKTABLE points when the length is known (default 10; 0 = none) + padding: number?, -- bytes of PADDING after the metadata (default 0) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Flac.sniff(r: Bytes.Reader): number + local head = r:peek(4) + if head == "fLaC" then + return 1 + end + if head == "OggS" then + -- the first page's packet: 0x7F "FLAC" (the Ogg FLAC mapping) + local nseg = r:peekU8(26) + if nseg > 0 and r:peek(5, 27 + nseg) == "\127FLAC" then + return 1 + end + return 0 + end + if string.sub(head, 1, 3) == "ID3" then + -- an ID3v2 tag, then fLaC (mp3 files start with ID3 too) + local sz = 0 + for i = 6, 9 do + local v = r:peekU8(i) + if v < 0 then + return 0 + end + sz = sz * 128 + bit32.band(v, 127) + end + local footer = bit32.band(math.max(r:peekU8(5), 0), 0x10) ~= 0 + return if r:peek(4, 10 + sz + (if footer then 10 else 0)) == "fLaC" then 1 else 0 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Flac.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?) + local dec, err = Flac.open(r, opts) + if not dec then + return nil, err + end + local d = dec :: any + local limit = opts and opts.maxFrames or 2 ^ 28 + 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 + 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 +function Flac.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local o: EncodeOptions = opts or {} + local level = o.level or 5 + if type(level) ~= "number" or level ~= math.floor(level) or level < 0 or level > 8 then + return nil, Err.new(Err.ARG, "level must be 0..8") + end + local bits = o.bits + if bits == nil then + local v = value :: any + local sb = (type(v.meta) == "table" and type(v.meta.source) == "table" and v.meta.source.bitDepth) or v.bitsPerSample + bits = if type(sb) == "number" and sb >= 4 and sb <= 24 then sb else 16 + end + if type(bits) ~= "number" or bits ~= math.floor(bits) or bits < 4 or bits > 24 then + return nil, Err.new(Err.ARG, "bits must be 4..24") + end + local bs = o.blockSize + if bs ~= nil and (type(bs) ~= "number" or bs ~= math.floor(bs) or bs < 16 or bs > 65535) then + return nil, Err.new(Err.ARG, "blockSize must be 16..65535") + end + if src.channels > 8 then + return nil, Err.new(Err.ARG, "FLAC holds at most 8 channels") + end + if src.sampleRate ~= math.floor(src.sampleRate) or src.sampleRate < 1 or src.sampleRate >= 2 ^ 20 then + return nil, Err.new(Err.ARG, "the sample rate must be an integer below 2^20") + end + local out, msg = Encode.encode(src :: any, { + level = level, + bits = bits :: number, + blockSize = bs, + seekInterval = math.max(0, o.seekInterval or 10), + padding = math.clamp(math.floor(o.padding or 0), 0, 0xFFFFFF), + vendor = "rosetta", + }) + if not out then + return nil, Err.new(Err.CORRUPT, tostring(msg)) + end + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Flac.open(r: Bytes.Reader, opts: OpenOptions?): (Decoder?, Err.Err?) + if type(r) == "buffer" then + r = Bytes.reader(r :: any) + end + if type(r) ~= "table" or type(r.buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "open: expected a Reader") + end + local dec, msg, code = Stream.open(r.buf, r.base, r.limit - r.base, opts) + if not dec then + return nil, Err.new(code or Err.CORRUPT, tostring(msg)) + end + return dec, nil +end + +-- ------------------------------------------------------------------------------------------------ extras +Flac.Stream = Stream +Flac.Ogg = Ogg + +return Flac +end +__FILES["audio/flac/Meta"] = @native function() + + + +-- audio/flac/Meta: STREAMINFO, SEEKTABLE, VORBIS_COMMENT and PICTURE blocks; absorbed from flac-luau 7083d0d. +local VorbisComment = __include("codecs/audio/VorbisComment") + +local readu8, readu32 = buffer.readu8, buffer.readu32 + +local Meta = {} + +@native local function be16(b: buffer, p: number): number + return readu8(b, p) * 256 + readu8(b, p + 1) +end +@native local function be24(b: buffer, p: number): number + return readu8(b, p) * 65536 + readu8(b, p + 1) * 256 + readu8(b, p + 2) +end +@native local function be32(b: buffer, p: number): number + return be16(b, p) * 65536 + be16(b, p + 2) +end + +type StreamInfo = { + minBlockSize: number, + maxBlockSize: number, + minFrameSize: number, -- 0 = unknown + maxFrameSize: number, + sampleRate: number, + channels: number, + bitsPerSample: number, + totalSamples: number, -- 0 = unknown + md5: string, -- 32 hex digits (all zero = not set) +} + +type SeekPoint = { sample: number, offset: number, samples: number } + +type Picture = { + type: number, + mime: string, + description: string, + width: number, + height: number, + depth: number, + colors: number, + offset: number, -- the image bytes are buf[offset .. offset + size - 1] + size: number, +} + +type Info = { + streamInfo: StreamInfo, + seekTable: { SeekPoint }, + vendor: string, + tags: { [string]: string }, -- upper-case keys; repeated keys are joined with "; " + comments: { { key: string, value: string } }, + pictures: { Picture }, + firstFrame: number, -- byte offset just after the last metadata block +} + +@native local function streamInfo(b: buffer, p: number): StreamInfo + local b12, b13 = readu8(b, p + 12), readu8(b, p + 13) + local hex = table.create(16) + for i = 0, 15 do + hex[i + 1] = string.format("%02x", readu8(b, p + 18 + i)) + end + return { + minBlockSize = be16(b, p), + maxBlockSize = be16(b, p + 2), + minFrameSize = be24(b, p + 4), + maxFrameSize = be24(b, p + 7), + sampleRate = readu8(b, p + 10) * 4096 + readu8(b, p + 11) * 16 + bit32.rshift(b12, 4), + channels = bit32.band(bit32.rshift(b12, 1), 7) + 1, + bitsPerSample = bit32.band(b12, 1) * 16 + bit32.rshift(b13, 4) + 1, + totalSamples = bit32.band(b13, 15) * 4294967296 + be32(b, p + 14), + md5 = table.concat(hex), + } +end + +@native local function vorbisComment(b: buffer, p: number, e: number, info: Info): boolean + if p + 4 > e then + return false + end + local vl = readu32(b, p) + p += 4 + if p + vl > e then + return false + end + info.vendor = buffer.readstring(b, p, vl) + p += vl + if p + 4 > e then + return false + end + local n = readu32(b, p) + p += 4 + for _ = 1, n do + if p + 4 > e then + return false + end + local l = readu32(b, p) + p += 4 + if p + l > e then + return false + end + local s = buffer.readstring(b, p, l) + p += l + local eq = string.find(s, "=", 1, true) + if eq then + 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 + end + return true +end + +@native local function picture(b: buffer, p: number, e: number): Picture? + if p + 8 > e then + return nil + end + local typ = be32(b, p) + local ml = be32(b, p + 4) + p += 8 + if p + ml + 4 > e then + return nil + end + local mime = buffer.readstring(b, p, ml) + p += ml + local dl = be32(b, p) + p += 4 + if p + dl + 20 > e then + return nil + end + local desc = buffer.readstring(b, p, dl) + p += dl + local pic = { + type = typ, + mime = mime, + description = desc, + width = be32(b, p), + height = be32(b, p + 4), + depth = be32(b, p + 8), + colors = be32(b, p + 12), + offset = p + 20, + size = be32(b, p + 16), + } + if pic.offset + pic.size > e then + return nil + end + return pic +end + +@native function Meta.parse(b: buffer, pos: number, len: number): (Info?, string?) + if pos + 4 > len or buffer.readstring(b, pos, 4) ~= "fLaC" then + return nil, "Flac: no fLaC marker" + end + local info: Info = { + streamInfo = nil :: any, + seekTable = {}, + vendor = "", + tags = {}, + comments = {}, + pictures = {}, + firstFrame = 0, + } + local p = pos + 4 + while true do + if p + 4 > len then + return nil, "Flac: truncated metadata" + end + local h = readu8(b, p) + local last = h >= 128 + local typ = bit32.band(h, 127) + local size = be24(b, p + 1) + p += 4 + local e = p + size + if e > len then + return nil, "Flac: truncated metadata block" + end + if typ == 0 then + if size < 34 then + return nil, "Flac: bad STREAMINFO" + end + info.streamInfo = streamInfo(b, p) + elseif typ == 3 then + for q = p, e - 18, 18 do + local hi = be32(b, q) + if hi ~= 0xFFFFFFFF then -- placeholder points are all ones + table.insert(info.seekTable, { + sample = hi * 4294967296 + be32(b, q + 4), + offset = be32(b, q + 8) * 4294967296 + be32(b, q + 12), + samples = be16(b, q + 16), + }) + end + end + elseif typ == 4 then + vorbisComment(b, p, e, info) + elseif typ == 6 then + local pic = picture(b, p, e) + if pic then + table.insert(info.pictures, pic) + end + elseif typ == 127 then + return nil, "Flac: invalid metadata block type" + end + p = e + if last then + break + end + end + if not info.streamInfo then + return nil, "Flac: no STREAMINFO" + end + local si = info.streamInfo + if si.sampleRate == 0 then + return nil, "Flac: bad STREAMINFO values" + end + info.firstFrame = p + return info, nil +end + +return Meta +end +__FILES["audio/flac/Stream"] = @native function() + + + +-- audio/flac/Stream: streaming FLAC decoder (native and Ogg FLAC); absorbed from flac-luau 7083d0d (same author). +local Bytes = __include("core/Bytes") +local Ogg = __include("containers/Ogg") +local Frame = __include("codecs/audio/Flac/Frame") +local Meta = __include("audio/flac/Meta") + +local Stream = {} + +local writef32, writei32 = buffer.writef32, buffer.writei32 +type Header = any -- Frame.Header +local PAD = Frame.PAD + +type Decoder = { + sampleRate: number, + channels: number, + bitsPerSample: number, + frames: number, -- total sample frames (per channel); 0 if unknown and not found + duration: number, -- seconds + bitrate: number, -- average bits per second of the audio data + tags: { [string]: string }, + comments: { { key: string, value: string } }, + vendor: string, + md5: string, + seekTable: { any }, + pictures: { any }, + container: string, -- "flac" | "ogg" + read: (Decoder, number, buffer?) -> (buffer, number), + readInt: (Decoder, number, buffer?) -> (buffer, number), + seek: (Decoder, number) -> boolean, + seekSample: (Decoder, number) -> boolean, + position: (Decoder) -> (number, number), +} + +local Dec = {} +Dec.__index = Dec + +@native local function sampleOf(self: any, h: Header): number + return if h.variable then h.number else h.number * self._nominal +end + +@native local function plausible(self: any, h: Header): boolean + if h.channels ~= self.channels or h.bps ~= self.bitsPerSample or h.blockSize > 65536 then + return false + end + if self.frames > 0 and sampleOf(self, h) >= self.frames then + return false + end + return true +end + +@native local function findFrame(self: any, pos: number, limit: number): Header? + local b, len, si = self._b, self._len, self._si + while true do + local h = Frame.find(b, pos, limit, len, si) + if not h then + return nil + end + if plausible(self, h) then + return h + end + pos = h.offset + 1 + end +end + +@native local function ensure(self: any, n: number) + if n > self._cap then + for c = 1, self.channels do + self._chans[c] = table.create(n, 0) + end + self._cap = n + end +end + +@native local function decodeAt(self: any, pos: number): boolean + local b, len = self._b, self._len + while true do + local h = Frame.header(b, pos, len, self._si) + if not h or not plausible(self, h) then + h = findFrame(self, pos, len) + if not h then + self._pos = len + return false + end + end + ensure(self, h.blockSize) + local nextPos = Frame.decode(b, len, h, self._chans, self._cf, self._crc) + if nextPos then + local s = sampleOf(self, h) + local n = h.blockSize + if self.frames > 0 and s + n > self.frames then + n = math.max(0, self.frames - s) + end + self._pos = nextPos + self._fs = s + self._fn = n + self._cur = 0 + return true + end + pos = h.offset + 1 + end +end + +@native local function pull(self: any, maxFrames: number, asInt: boolean, dst: buffer?): (buffer, number) + local ch = self.channels + local want = math.floor(tonumber(maxFrames) or 0) + if not (want >= 0) then + want = 0 + end + want = math.min(want, 2 ^ 26 // ch) -- keeps the output buffer under 256 MB + local reuse = dst ~= nil and type(dst) == "buffer" and buffer.len(dst) >= want * ch * 4 + local out = if reuse then dst :: buffer else buffer.create(want * ch * 4) + local got = 0 + local scale = 1 / 2 ^ (self.bitsPerSample - 1) + local stride = ch * 4 + while got < want do + if self._cur >= self._fn then + if self._pos >= self._len or not decodeAt(self, self._pos) then + self._fs += self._cur + self._cur, self._fn = 0, 0 + break + end + end + local take = math.min(want - got, self._fn - self._cur) + local from = self._cur + 1 + local to = self._cur + take + for c = 1, ch do + local s = self._chans[c] + local o = (got * ch + c - 1) * 4 + if asInt then + for i = from, to do + writei32(out, o, s[i]) + o += stride + end + else + for i = from, to do + writef32(out, o, s[i] * scale) + o += stride + end + end + end + self._cur += take + got += take + end + if got < want and not reuse then + local short = buffer.create(got * ch * 4) + buffer.copy(short, 0, out, 0, got * ch * 4) + out = short + end + return out, got +end + +@native function Dec.read(self: any, maxFrames: number, out: buffer?): (buffer, number) + return pull(self, maxFrames, false, out) +end + +@native function Dec.readInt(self: any, maxFrames: number, out: buffer?): (buffer, number) + return pull(self, maxFrames, true, out) +end + +@native function Dec.position(self: any): (number, number) + local s = self._fs + self._cur + return s / self.sampleRate, s +end + +@native function Dec.seekSample(self: any, t: number): boolean + t = math.floor(tonumber(t) or 0) + if not (t >= 0) then + t = 0 + end + if self.frames > 0 and t >= self.frames then + self._pos, self._fs, self._fn, self._cur = self._len, self.frames, 0, 0 + return true + end + if self._fn > 0 and t >= self._fs and t < self._fs + self._fn then + self._cur = t - self._fs + return true + end + local first, len = self._first, self._len + local lo, hi = first, len + for _, sp in self.seekTable do + local o = first + sp.offset + if o < len then + if sp.sample <= t then + lo = math.max(lo, o) + else + hi = math.min(hi, o) + break + end + end + end + local window = math.max(16384, 2 * self._si.maxFrameSize) + while hi - lo > window do + local mid = (lo + hi) // 2 + local h = findFrame(self, mid, hi) + if h and sampleOf(self, h) <= t then + lo = h.offset + else + hi = mid + end + end + local pos = lo + while true do + local h = findFrame(self, pos, len) + if not h then + self._pos, self._fs, self._fn, self._cur = len, math.max(t, self.frames), 0, 0 + return false + end + local s = sampleOf(self, h) + if s + h.blockSize > t then + if decodeAt(self, h.offset) then + if self._fs <= t and t < self._fs + self._fn then + self._cur = t - self._fs + return true + elseif self._fs > t then + return false + end + pos = self._pos + else + return false + end + else + pos = h.offset + h.size + end + end +end + +@native function Dec.seek(self: any, seconds: number): boolean + return self:seekSample(math.floor((tonumber(seconds) or 0) * self.sampleRate + 0.5)) +end + +@native local function scanLength(self: any): number + local len = self._len + local step = math.max(65536, 2 * self._si.maxFrameSize) + local from = len + while from > self._first do + local start = math.max(self._first, from - step) + local best: Header? = nil + local pos = start + while true do + local h = findFrame(self, pos, from) + if not h then + break + end + best = h + pos = h.offset + 1 + end + if best then + local s = sampleOf(self, best) + -- the last frame may be shorter than its header claims only via STREAMINFO, which is unknown here + return s + best.blockSize + end + from = start + end + return 0 +end + +@native local function skipId3(b: buffer, base: number, len: number): number + local p = 0 + while p + 10 <= len and buffer.readstring(b, base + p, 3) == "ID3" do + local sz = 0 + for i = 6, 9 do + sz = sz * 128 + bit32.band(buffer.readu8(b, base + p + i), 127) + end + local footer = bit32.band(buffer.readu8(b, base + p + 5), 0x10) ~= 0 + p += 10 + sz + (if footer then 10 else 0) + end + return p +end + +@native function Stream.open(buf: buffer, base: number, srcLen: number, opts: { crc16: boolean? }?): (Decoder?, string?, string?) + local b, len, container + if srcLen >= 4 and buffer.readstring(buf, base, 4) == "OggS" then + local demux, err = Ogg.open(Bytes.reader(buf, base, srcLen)) + if not demux then + return nil, (err :: any).message, "CORRUPT" + end + local serial = demux:find("flac") + if not serial then + return nil, "no FLAC stream in the Ogg file", "CORRUPT" + end + -- rebuild a native stream: "fLaC" + metadata (from the header packets) + frames (one per packet) + local packets, total = {}, 0 + for p in demux:packets(serial) do + local off, size = p.offset, p.size + if #packets == 0 then + if size < 13 then + return nil, "bad Ogg FLAC header", "CORRUPT" + end + off += 9 + size -= 9 + end + table.insert(packets, { p.data, off, size }) + total += size + end + b = buffer.create(total + PAD) + local o = 0 + for _, p in packets do + buffer.copy(b, o, p[1], p[2], p[3]) + o += p[3] + end + len = total + container = "ogg" + else + local start = skipId3(buf, base, srcLen) + if start + 4 > srcLen or buffer.readstring(buf, base + start, 4) ~= "fLaC" then + return nil, "not a FLAC file", "CORRUPT" + end + len = srcLen - start + b = buffer.create(len + PAD) + buffer.copy(b, 0, buf, base + start, len) + container = "flac" + end + local info, err = Meta.parse(b, 0, len) + if not info then + return nil, err, "CORRUPT" + end + local si = info.streamInfo + local self = setmetatable({ + sampleRate = si.sampleRate, + channels = si.channels, + bitsPerSample = si.bitsPerSample, + frames = si.totalSamples, + duration = 0, + bitrate = 0, + tags = info.tags, + comments = info.comments, + vendor = info.vendor, + md5 = si.md5, + seekTable = info.seekTable, + pictures = info.pictures, + container = container, + _b = b, + _len = len, + _si = si, + _first = info.firstFrame, + _pos = info.firstFrame, + _chans = {}, + _cap = 0, + _cf = table.create(32, 0), + _crc = not (opts and opts.crc16 == false), + _fs = 0, + _fn = 0, + _cur = 0, + _nominal = math.max(si.maxBlockSize, 1), + }, Dec) + ensure(self, math.max(si.maxBlockSize, 16)) + local h = findFrame(self, info.firstFrame, len) + if h then + if not h.variable then + self._nominal = h.blockSize + end + end + if self.frames == 0 then + self.frames = scanLength(self) + end + self.duration = self.frames / self.sampleRate + if self.duration > 0 then + self.bitrate = (len - info.firstFrame) * 8 / self.duration + end + return self :: any, nil +end + +Stream.Dec = Dec + +return Stream +end +__FILES["audio/m4a"] = function() + +-- audio/m4a: MPEG-4 audio (M4A / M4B / MP4 / MOV audio tracks) via containers/IsoBmff. Supports: AAC-LC (HE-AAC plays +-- its core), ALAC, edit-list gapless trimming, seeking, iTunes tags and cover art; encode ALAC (16 / 20 / 24-bit, 1-8 +-- channels). Not supported: writing AAC, other codecs in MP4 (UNSUPPORTED), encrypted files. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Pcm = __include("codecs/audio/Pcm") +local Stream = __include("codecs/audio/Stream") +local IsoBmff = __include("containers/IsoBmff") +local Aac = __include("codecs/audio/Aac") +local Alac = __include("codecs/audio/Alac") + +-- ------------------------------------------------------------------------------------------------ contract +local M4a = { + name = "m4a", + category = "audio", + extensions = { "m4a", "m4b", "m4r" }, + mime = { "audio/mp4", "audio/x-m4a", "audio/m4a" }, + 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 }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + track: number?, -- the track id to play (default: the first AAC / ALAC track) + gapless: boolean?, -- apply the edit list (default true) + maxSamples: number?, -- default 2^25 +} +type EncodeOptions = { + bitDepth: number?, -- 16 (default), 20 or 24 + frameLength: number?, -- samples per packet, default 4096 + tags: Types.Tags?, -- default: the audio's tags + pictures: { { mime: string, data: buffer } }?, -- default: audio.meta.pictures +} + +-- ------------------------------------------------------------------------------------------------ constants +local AUDIO_BRANDS: { [string]: number } = { ["M4A "] = 1, ["M4B "] = 1, ["M4P "] = 1, ["M4V "] = 0.3 } + +-- ------------------------------------------------------------------------------------------------ sniff +function M4a.sniff(r: Bytes.Reader): number + local brand = IsoBmff.sniff(r) + if brand == nil then + return 0 + end + if AUDIO_BRANDS[brand] then + return AUDIO_BRANDS[brand] + end + if brand == "avif" or brand == "avis" or brand == "heic" or brand == "heix" or brand == "mif1" or brand == "msf1" or brand == "crx " then + return 0 + end + return 0.4 -- an MP4 / MOV that may hold audio; a video format claims it more strongly +end + +-- ------------------------------------------------------------------------------------------------ decode +type PacketDecoder = { + channels: number, + sampleRate: number, + frameSize: number, + pcm: { number }, + decode: (buf: buffer, off: number, len: number) -> (number?, Err.Err?), + reset: () -> (), +} + +local function packetDecoder(t: IsoBmff.Track): (PacketDecoder?, Err.Err?) + if not t.config then + return nil, Err.new(Err.CORRUPT, "track " .. t.id .. " (" .. t.codec .. ") has no codec configuration") + end + if t.codec == "alac" then + local cfg, err = Alac.config(t.config :: buffer) + if not cfg then + return nil, err + end + local dec = Alac.decoder(cfg) + local pcm = table.create(cfg.frameLength * cfg.channels, 0) + local scale = 1 / 2 ^ (cfg.bitDepth - 1) + local pd: PacketDecoder = { + channels = cfg.channels, + sampleRate = if cfg.sampleRate > 0 then cfg.sampleRate else (t.sampleRate or 44100), + frameSize = cfg.frameLength, + pcm = pcm, + decode = function(buf: buffer, off: number, len: number): (number?, Err.Err?) + local n, e = dec:decode(buf, off, len) + if not n then + return nil, e + end + local src = dec.pcm + for i = 1, n * cfg.channels do + pcm[i] = src[i] * scale + end + return n, nil + end, + reset = function() end, + } + return pd, nil + elseif t.codec == "aac" then + local dec, err = Aac.decoder(t.config :: buffer) + if not dec then + return nil, err + end + local d = dec :: Aac.Decoder + local pd: PacketDecoder = { + channels = d.channels, + sampleRate = d.sampleRate, + frameSize = d.frameLength, + pcm = d.pcm, + decode = function(buf: buffer, off: number, len: number): (number?, Err.Err?) + return d:decode(buf, off, len) + end, + reset = function() + d:reset() + end, + } + return pd, nil + end + return nil, Err.new(Err.UNSUPPORTED, "audio codec " .. t.codec .. " in MP4") +end + +function M4a.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?) + local o: DecodeOptions = opts or {} + local movie, err = IsoBmff.parse(r, { maxSamples = o.maxSamples }) + if not movie then + return nil, err + end + local track: IsoBmff.Track? = nil + local other: IsoBmff.Track? = nil + for _, t in movie.tracks do + if t.kind == "audio" then + if o.track and t.id ~= o.track then + continue + end + if t.codec == "aac" or t.codec == "alac" then + track = t + break + end + other = other or t + end + end + if not track then + if other then + return nil, Err.new(Err.UNSUPPORTED, "audio codec " .. other.codec .. " in MP4") + end + return nil, Err.new(Err.CORRUPT, "no audio track") + end + local t = track :: IsoBmff.Track + local pd, perr = packetDecoder(t) + if not pd then + return nil, perr + end + local p = pd :: PacketDecoder + local channels, sr = p.channels, p.sampleRate + local tickScale = sr / t.timescale + local gapless = o.gapless ~= false + local skip = if gapless then math.floor(t.skip * tickScale + 0.5) else 0 + local total = 0 + for i = 1, t.sampleCount do + total += t.durations[i] + end + total = math.floor(total * tickScale + 0.5) + if gapless and t.playDuration then + total = math.min(total, skip + math.floor(t.playDuration * tickScale + 0.5)) + 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 + if gapless and not t.edits and smpb then + local f: { number } = {} + for w in string.gmatch(smpb, "%x+") do + 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] + total = f[2] + f[4] + end + end + local frames = math.max(0, total - skip) + local buf = r.buf + local dec: any = { + sampleRate = sr, + channels = channels, + frames = frames, + duration = frames / sr, + bitrate = 0, + tags = tags, + pictures = pictures, + codec = t.codec, + track = t, + movie = movie, + } + 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) + -- 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 + +function M4a.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) + local dec, err = M4a.open(r, opts) + if not dec then + return nil, err + end + local d: any = dec + 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, derr +end + +-- ------------------------------------------------------------------------------------------------ encode +function M4a.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + 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 + local sr, ch = value.sampleRate, value.channels + local enc, eerr = Alac.encoder({ sampleRate = sr, channels = ch, bitDepth = o.bitDepth or 16, frameLength = o.frameLength }) + if not enc then + return nil, eerr + end + local e = enc :: Alac.Encoder + local depth = e.config.bitDepth + local fl = e.config.frameLength + local peak = 2 ^ (depth - 1) + local packets: { buffer } = {} + local durations: { number } = {} + local ints = table.create(fl * ch, 0) + local floor = math.floor + local readf32 = buffer.readf32 + local src: buffer, srcFrames = nil :: any, 0 + local isAudio = value.kind == "audio" and type(value.samples) == "buffer" + if isAudio then + src, srcFrames = value.samples, value.frames + if buffer.len(src) < srcFrames * ch * 4 then + return nil, Err.new(Err.ARG, "audio.samples is shorter than frames * channels") + end + elseif type(value.read) ~= "function" then + return nil, Err.new(Err.ARG, "expected an Audio or a Decoder") + end + local done = 0 + local chunk: buffer? = nil + while true do + local n, b, base + if isAudio then + n = math.min(fl, srcFrames - done) + b, base = src, done * ch * 4 + else + local got + b, got = value:read(fl, chunk) + chunk = b + n, base = got, 0 + end + if n <= 0 then + break + end + for i = 0, n * ch - 1 do + local v = floor(readf32(b, base + i * 4) * peak + 0.5) + if v >= peak then + v = peak - 1 + elseif v < -peak then + v = -peak + end + ints[i + 1] = v + end + local pkt, perr = e:encode(ints, 1, n) + if not pkt then + return nil, perr + end + table.insert(packets, pkt) + table.insert(durations, n) + done += n + if isAudio and done >= srcFrames then + break + end + end + local tags = o.tags or value.tags or {} + local pictures = o.pictures or (value.meta and value.meta.pictures) or nil + local timescale = if sr < 65536 then sr else 0 + local file, merr = IsoBmff.mux({ + brand = "M4A ", + minor = 0, + compatible = { "M4A ", "mp42", "isom" }, + timescale = 1000, + tracks = { + { + kind = "audio", + entry = "alac", + timescale = if timescale > 0 then timescale else 48000, + samples = packets, + durations = if timescale > 0 then durations else (function() + local d = {} + for i, v in durations do + d[i] = math.floor(v * 48000 / sr + 0.5) + end + return d + end)(), + sampleRate = sr, + channels = ch, + bitsPerSample = depth, + config = Alac.cookie(e.config), + }, + }, + tags = tags, + pictures = pictures, + }) + if not file then + return nil, merr + end + return file, nil +end + +return M4a +end +__FILES["audio/mp3"] = function() + +-- audio/mp3: MPEG audio layers I-III (ISO/IEC 11172-3, 13818-3, MPEG-2.5); absorbed from mp3-luau c755bbf, a port of +-- minimp3 by lieff (CC0: licenses/minimp3-CC0.txt). Supports: every mode, CBR / VBR / free format, Xing / LAME gapless, +-- exact seeking, ID3v2 / ID3v1 tags; encode layers III / II (CBR). Not supported: MPEG-2 multichannel, CRC, VBR output. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Header = __include("codecs/audio/Mpa/Header") +local Index = __include("audio/mp3/Index") +local Tags = __include("audio/mp3/Tags") +local Stream = __include("audio/mp3/Stream") +local Encode3 = __include("codecs/audio/Mpa/Encode3") +local Encode2 = __include("codecs/audio/Mpa/Encode2") +local Pcm = __include("codecs/audio/Pcm") +local Resample = __include("codecs/audio/Resample") + +-- ------------------------------------------------------------------------------------------------ contract +local Mp3 = { + name = "mp3", + category = "audio", + extensions = { "mp3", "mp2", "mp1", "mpga" }, + mime = { "audio/mpeg", "audio/mp3", "audio/mpa" }, + 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 }, +} + +-- ------------------------------------------------------------------------------------------------ types +type OpenOptions = { + maxFrames: number?, -- default 2^31 +} +type Decoder = Stream.Decoder +type EncodeOptions = { + layer: number?, -- 3 (MP3, default) or 2 (MP2) + bitrate: number?, -- bits per second, constant: one of the layer's rates (default 128000 for layer III, 192000 for + -- layer II; MPEG-2 / 2.5 rates: 64000 / 96000); values below 1000 are kbit/s (128 = 128000, the old unit) + 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/audio/Resample) + resampleQuality: ("low" | "medium" | "high")?, -- codecs/audio/Resample quality (default "medium") +} + +-- ------------------------------------------------------------------------------------------------ constants +local MAX_FRAMES = 2 ^ 31 + +-- ------------------------------------------------------------------------------------------------ sniff +function Mp3.sniff(r: Bytes.Reader): number + local b, p, lim = r.buf, r.pos, r.limit + local id3 = false + for _ = 1, 4 do -- (ffmpeg writes a tag even when the input had one: tags can follow each other) + local n = if p + 3 <= lim and buffer.readstring(b, p, 3) == "ID3" then Tags.id3v2Size(b, p, lim) else 0 + if n <= 0 then + break + end + id3 = true + p += n + end + if p + 4 > lim or not Header.valid(b, p) then + return if id3 then 0.5 else 0 + end + local fb = Header.frameBytes(b, p, 0) + if fb > 0 then + fb += Header.padding(b, p) + if p + fb + 4 <= lim and Header.compare(b, p, p + fb) then + return 0.9 + end + if p + fb == lim then + return 0.6 + end + end + return if id3 then 0.7 else 0.25 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Mp3.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?) + local dec, err = Mp3.open(r, opts) + if not dec then + return nil, err + end + 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 + return a, derr +end + +-- ------------------------------------------------------------------------------------------------ encode +local ID3_FRAMES = { + { "title", "TIT2" }, + { "artist", "TPE1" }, + { "album", "TALB" }, + { "albumartist", "TPE2" }, + { "year", "TDRC" }, + { "date", "TDRC" }, + { "track", "TRCK" }, + { "genre", "TCON" }, + { "composer", "TCOM" }, +} + +local function id3Tag(tags: { [string]: any }): buffer? + local w = Bytes.writer(256) + local seen: { [string]: boolean } = {} + local function syncsafe(v: number) + w:u8((v // 2097152) % 128) + w:u8((v // 16384) % 128) + w:u8((v // 128) % 128) + w:u8(v % 128) + end + for _, f in ID3_FRAMES do + local v = tags[f[1]] + if type(v) == "string" and #v > 0 and not seen[f[2]] then + seen[f[2]] = true + w:string(f[2]) + syncsafe(#v + 1) + w:u16be(0) + w:u8(3) -- UTF-8 + w:string(v) + end + end + if type(tags.comment) == "string" and #tags.comment > 0 then + local v = tags.comment + w:string("COMM") + syncsafe(#v + 5) + w:u16be(0) + w:u8(3) + w:string("eng") + w:u8(0) -- empty description + w:string(v) + end + local body = w:finish() + if buffer.len(body) == 0 then + return nil + end + local out = Bytes.writer(buffer.len(body) + 10) + out:string("ID3") + out:u8(4) + out:u8(0) + out:u8(0) + local n = buffer.len(body) + out:u8((n // 2097152) % 128) + out:u8((n // 16384) % 128) + out:u8((n // 128) % 128) + out:u8(n % 128) + out:bytes(body) + return out:finish() +end + +function Mp3.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local o: EncodeOptions = opts or {} + local layer = o.layer or 3 + if layer ~= 2 and layer ~= 3 then + return nil, Err.new(Err.ARG, "layer must be 2 or 3") + end + local Enc = if layer == 3 then Encode3 else Encode2 + 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 + return nil, Err.new(Err.ARG, "mode must be stereo, joint or mono") + end + if src.channels > 2 then + return nil, Err.new(Err.ARG, "MPEG audio holds 1 or 2 channels") + end + if layer == 2 and mode == "joint" then + mode = "stereo" + 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 type(bitrate) == "number" and bitrate >= 1000 then + bitrate /= 1000 + end + if not table.find(Enc.BITRATES[if mpeg1 then 1 else 2], bitrate) then + return nil, Err.new(Err.ARG, string.format("%s bit/s is not a layer %d bit rate at %d Hz", tostring(if type(o.bitrate) == "number" and o.bitrate < 1000 then o.bitrate * 1000 else o.bitrate), layer, rate)) + end + if layer == 2 and mpeg1 then + -- the standard's allowed bit rate / mode combinations + if mode == "mono" and bitrate > 192 then + return nil, Err.new(Err.ARG, "layer II mono is at most 192 kbps") + elseif mode ~= "mono" and (bitrate == 32 or bitrate == 48 or bitrate == 56 or bitrate == 80) then + return nil, Err.new(Err.ARG, "layer II stereo needs 64 kbps or more (and not 80)") + end + end + local prefix = if o.id3 == false then nil else id3Tag(src.tags) + local out, msg = Enc.encode(src :: any, { bitrate = bitrate, mode = mode, prefix = prefix }) + if not out then + return nil, Err.new(Err.ARG, tostring(msg)) + end + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ open +local function stringTags(t: any): { [string]: string } + local out: { [string]: string } = {} + for k, v in t do + if type(k) == "string" and type(v) == "string" and k ~= "id3v2" then + out[k] = v + end + end + return out +end + +function Mp3.open(r: Bytes.Reader, opts: OpenOptions?): (Decoder?, Err.Err?) + local b = r.buf + if r.base ~= 0 or r.limit ~= buffer.len(b) then + b = buffer.create(r.limit - r.base) -- the core indexes from offset 0 + buffer.copy(b, 0, r.buf, r.base, r.limit - r.base) + end + local okTags, tags, start, stop = pcall(Tags.parse, b) + if not okTags then + tags, start, stop = { raw = {} }, 0, buffer.len(b) + end + local idx = Index.build(b, start, stop) + if not idx then + return nil, Err.new(Err.CORRUPT, "no MPEG audio frames found") + end + local dec = Stream.new(b, idx, stringTags(tags), { + raw = tags.raw, + id3v2 = tags.id3v2, + id3v1 = tags.id3v1 == true, + ape = tags.ape == true, + }) + if dec.frames > (opts and opts.maxFrames or MAX_FRAMES) then + return nil, Err.new(Err.LIMIT, string.format("%d sample frames is over the limit", dec.frames)) + end + return dec, nil +end + +-- ------------------------------------------------------------------------------------------------ extras +Mp3.Tags = Tags + +return Mp3 +end +__FILES["audio/mp3/Index"] = @native function() + + + +-- audio/mp3/Index: the frame index as minimp3_ex's mp3dec_load_buf walks it, simulating the layer III bit reservoir. +local Header = __include("codecs/audio/Mpa/Header") +local Core = __include("codecs/audio/Mpa/Core") + +local band, rshift = bit32.band, bit32.rshift +local ru8 = buffer.readu8 +local min, max = math.min, math.max + +local compare, frameBytes, padding, findFrame = + Header.compare, Header.frameBytes, Header.padding, Header.findFrame + +local Index = {} + +Index.FLAG_RESET = 1 -- decoder state is zeroed before this frame (minimp3 re-synced here) +Index.FLAG_OUTPUT = 2 -- this frame gives samples in a continuous decode + +type Index = { + n: number, -- frames + off: buffer, -- u32 byte offset per frame + size: buffer, -- u16 byte size per frame (header and padding included) + flags: buffer, -- u8 FLAG_* + out: buffer, -- u32 first output sample (before the encoder delay is cut) per frame + main: buffer, -- u16 layer III main data bytes per frame (0 for layers I / II) + outTotal: number, -- samples (per channel) of a continuous decode, delay not cut + bytes: number, -- audio bytes in indexed frames + sampleRate: number, + channels: number, -- the most channels of any frame + layer: number, + version: number, -- 1, 2 or 2.5 + spf: number, -- samples per frame + -- Xing / Info / LAME + vbrTag: number, -- mp3dec_check_vbrtag result of the first frame (0 = none) + tagFrames: number, + delay: number, + padding: number, + skipped: number, -- frames with another sample rate or layer, left out +} + +@native local function grow(b: buffer, n: number): buffer + local nb = buffer.create(n) + buffer.copy(nb, 0, b, 0, math.min(buffer.len(b), n)) + return nb +end + +@native function Index.build(b: buffer, start: number, stop: number): Index? + local cap = 1024 + local OFF, SIZE, FLAGS, OUT, MAIN = buffer.create(cap * 4), buffer.create(cap * 2), buffer.create(cap), buffer.create(cap * 4), buffer.create(cap * 2) + local n = 0 + local pos = start + local prev = -1 -- offset of the last decoded header (dec->header), -1 = none + local ffb = 0 -- free format bytes + local reserv = 0 + local outTotal = 0 + local bytes = 0 + local first = true + local skipped = 0 + local outCh = 0 -- the most channels of a frame that gives output + local hz, nch, layer, spf, version = 0, 0, 0, 0, 0 + local vbr, tagFrames, delay, pad = 0, 0, 0, 0 + + while true do + local remaining = stop - pos + if remaining <= 0 then + break + end + local fs = 0 + local reset = false + if remaining > 4 and prev >= 0 and compare(b, prev, pos) then + fs = frameBytes(b, pos, ffb) + padding(b, pos) + if fs ~= remaining and (fs + 4 > remaining or not compare(b, pos, pos + fs)) then + fs = 0 + end + end + if fs == 0 then + reset = true + reserv = 0 + local i + i, fs, ffb = findFrame(b, pos, remaining, 0) + if fs == 0 or i + fs > remaining then + break + end + pos += i + end + if fs < 4 or fs > Core.MAX_FRAME then + prev = -1 + pos += max(fs, 1) + continue + end + local h1, h2, h3 = ru8(b, pos + 1), ru8(b, pos + 2), ru8(b, pos + 3) + local fLayer = 4 - band(rshift(h1, 1), 3) + local fHz = Header.sampleRate(h1, h2) + local fCh = if band(h3, 0xC0) == 0xC0 then 1 else 2 + + if first then + first = false + 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) + if ret ~= 0 then + vbr, tagFrames, delay, pad = ret, frames, d, p + if ret < 0 then + delay, pad = 0, 0 + end + -- the tag frame is not audio; the next frame is found again from scratch + prev = -1 + pos += fs + continue + end + end + elseif fHz ~= hz or fLayer ~= layer then + skipped += 1 + prev = pos + pos += fs + continue + end + + local output = true + local mainBytes = 0 + local nextPrev = pos + if fLayer == 3 then + local mdb, p23, mb = Core.probeL3(b, pos, fs) + if mdb < 0 then + output = false + nextPrev = -1 -- mp3dec_init: the next frame re-syncs + else + mainBytes = mb + local have = min(reserv, mdb) + output = reserv >= mdb + local remains = have + mb - (if output then (p23 + 7) // 8 else 0) + reserv = max(0, min(remains, 511)) + end + else + output = Core.probeL12(b, pos, fs) + if not output then + nextPrev = -1 + end + end + + if output and fCh > outCh then + outCh = fCh -- mono / stereo switches: the stream is stereo, mono frames are duplicated + 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) :: buffer + end + buffer.writeu32(OFF, n * 4, pos) + buffer.writeu16(SIZE, n * 2, fs) + buffer.writeu8(FLAGS, n, (if reset then Index.FLAG_RESET else 0) + (if output then Index.FLAG_OUTPUT else 0)) + buffer.writeu32(OUT, n * 4, outTotal) + buffer.writeu16(MAIN, n * 2, min(mainBytes, 65535)) + n += 1 + bytes += fs + if output then + outTotal += spf + end + prev = nextPrev + pos += fs + end + + if first then + return nil + end + return { + n = n, + off = OFF, + size = SIZE, + flags = FLAGS, + out = OUT, + main = MAIN, + outTotal = outTotal, + bytes = bytes, + sampleRate = hz, + channels = if outCh > 0 then outCh else nch, + layer = layer, + version = version, + spf = spf, + vbrTag = vbr, + tagFrames = tagFrames, + delay = delay, + padding = pad, + skipped = skipped, + } +end + +return Index +end +__FILES["audio/mp3/Stream"] = function() + + +-- audio/mp3/Stream: streaming Decoder over the frame index (gapless, exact seeking); from mp3-luau (same author). +local Core = __include("codecs/audio/Mpa/Core") +local Index = __include("audio/mp3/Index") + +local FLAG_RESET, FLAG_OUTPUT = Index.FLAG_RESET, Index.FLAG_OUTPUT +local ru8, ru16, ru32 = buffer.readu8, buffer.readu16, buffer.readu32 +local band = bit32.band +local min, max, floor = math.min, math.max, math.floor + +local Stream = {} + +local Decoder = {} +Decoder.__index = Decoder + +type Decoder = typeof(setmetatable( + {} :: { + sampleRate: number, + channels: number, + frames: number, + duration: number, + bitrate: number, + tags: { [string]: string }, + id3: any, + layer: number, + version: number, + vbr: boolean, + delay: number, + padding: number, + mpegFrames: number, + _buf: buffer, + _idx: any, + _st: any, + _pcm: buffer, + _cur: number, + _pcmPos: number, + _pcmEnd: number, + _minAbs: number, + _endAbs: number, + _pos: number, + }, + Decoder +)) + +function Stream.new(b: buffer, idx: any, tags: { [string]: string }, id3: any): Decoder + local spf, hz, nch = idx.spf, idx.sampleRate, idx.channels + -- gapless: minimp3_ex cuts delay samples off the start and caps the length at the Xing / LAME count + local delay = 0 + local total = idx.outTotal + if idx.vbrTag > 0 then + delay = idx.delay + total = max(0, total - delay) + -- (a frame count of 0: written by an encoder that couldn't seek back to fill it in, e.g. ffmpeg writing to a + -- pipe; ffmpeg ignores it too. The frames found in the file are the length.) + if idx.tagFrames > 0 then + local detected = spf * idx.tagFrames + if detected >= delay then + detected -= delay + end + if idx.padding > 0 and detected >= idx.padding then + detected -= idx.padding + end + total = min(total, detected) + end + end + delay = min(delay, idx.outTotal) + local self = setmetatable({ + sampleRate = hz, + channels = nch, + frames = total, + duration = total / hz, + bitrate = if idx.n > 0 then floor(idx.bytes * 8 * hz / (idx.n * spf) + 0.5) else 0, -- bit/s + tags = tags, + id3 = id3, + layer = idx.layer, + version = idx.version, + vbr = idx.vbrTag ~= 0, + delay = delay, + padding = if idx.vbrTag > 0 then max(0, idx.padding) else 0, + mpegFrames = idx.n, + _buf = b, + _idx = idx, + _st = Core.newState(), + _pcm = buffer.create(1152 * 2 * 4), + _cur = 0, + _pcmPos = 0, + _pcmEnd = 0, + _minAbs = delay, + _endAbs = delay + total, + _pos = 0, + }, Decoder) + return self +end + + +local function fill(self: Decoder): boolean + local idx = self._idx + local n = idx.n + local spf = idx.spf + local st = self._st + while self._cur < n do + local f = self._cur + self._cur = f + 1 + local flags = ru8(idx.flags, f) + if band(flags, FLAG_RESET) ~= 0 then + Core.reset(st) + end + local a = ru32(idx.out, f * 4) + if a >= self._endAbs then + self._cur = n + return false + end + local got = Core.decodeFrame(st, self._buf, ru32(idx.off, f * 4), ru16(idx.size, f * 2), self._pcm) + if got > 0 and band(flags, FLAG_OUTPUT) ~= 0 then + if Core.lastChannels < self.channels then + Core.upmix(self._pcm, got) + end + local lo = max(a, self._minAbs) + local hi = min(a + spf, self._endAbs) + if hi > lo then + self._pcmPos = lo - a + self._pcmEnd = hi - a + return true + end + end + end + return false +end + +function Decoder.read(self: Decoder, maxFrames: number?, out: buffer?): (buffer, number) + local ch = self.channels + local want = tonumber(maxFrames) or 4096 + if want ~= want then + want = 0 + end + want = floor(max(0, min(want, self.frames - self._pos))) + if out and buffer.len(out) < want * ch * 4 then + out = nil + end + local dst = out or buffer.create(want * ch * 4) + local got = 0 + local pcm = self._pcm + while got < want do + if self._pcmPos >= self._pcmEnd then + if not fill(self) then + break + end + end + local k = min(want - got, self._pcmEnd - self._pcmPos) + buffer.copy(dst, got * ch * 4, pcm, self._pcmPos * ch * 4, k * ch * 4) + got += k + self._pcmPos += k + end + self._pos += got + if not out and got < want then + local r = buffer.create(got * ch * 4) + buffer.copy(r, 0, dst, 0, got * ch * 4) + dst = r + end + return dst, got +end + +function Decoder.seek(self: Decoder, seconds: number) + local hz = self.sampleRate + local target = floor((tonumber(seconds) or 0) * hz + 0.5) + target = max(0, min(target, self.frames)) + self:seekFrame(target) +end + +function Decoder.seekFrame(self: Decoder, target: number) + target = tonumber(target) or 0 + if target ~= target then + target = 0 + end + target = max(0, min(floor(target), self.frames)) + local idx = self._idx + local abs = self.delay + target + self._pos = target + self._minAbs = abs + self._pcmPos, self._pcmEnd = 0, 0 + Core.reset(self._st) + local n = idx.n + if abs >= self._endAbs or n == 0 then + self._cur = n + return + end + local lo, hi = 0, n - 1 + while lo < hi do + local mid = (lo + hi + 1) // 2 + if ru32(idx.out, mid * 4) <= abs then + lo = mid + else + hi = mid - 1 + end + end + local j = lo + -- go back >= 2 frames (layer I needs 2 for the polyphase history), and for layer III until the main data + -- before frame j - 1 covers the largest reservoir (511 bytes), stopping at a frame where the decoder resets + local need = if idx.layer == 3 then 511 else 0 + local s, back, acc = j, 0, 0 + while s > 0 and band(ru8(idx.flags, s), FLAG_RESET) == 0 do + if back >= 2 and acc >= need then + break + end + s -= 1 + back += 1 + if back >= 2 then + acc += ru16(idx.main, s * 2) + end + end + self._cur = s +end + +function Decoder.position(self: Decoder): (number, number) + return self._pos / self.sampleRate, self._pos +end + +function Decoder.readAll(self: Decoder): (buffer, number) + return self:read(max(0, self.frames - self._pos)) +end + +Stream.Decoder = Decoder + +return Stream +end +__FILES["audio/mp3/Tags"] = function() + + +-- audio/mp3/Tags: ID3v2.2-2.4 and ID3v1 / 1.1 tags (APEv2 skipped); the audio range as minimp3_ex's mp3dec_skip_id3. +local band, bor, lshift = bit32.band, bit32.bor, bit32.lshift +local ru8 = buffer.readu8 + +local Tags = {} + +-- ID3v1 genres 0..147 (the original 80 + the Winamp extensions) +local GENRES = { + [0] = "Blues", "Classic Rock", "Country", "Dance", "Disco", "Funk", "Grunge", "Hip-Hop", "Jazz", "Metal", + "New Age", "Oldies", "Other", "Pop", "R&B", "Rap", "Reggae", "Rock", "Techno", "Industrial", "Alternative", + "Ska", "Death Metal", "Pranks", "Soundtrack", "Euro-Techno", "Ambient", "Trip-Hop", "Vocal", "Jazz+Funk", + "Fusion", "Trance", "Classical", "Instrumental", "Acid", "House", "Game", "Sound Clip", "Gospel", "Noise", + "AlternRock", "Bass", "Soul", "Punk", "Space", "Meditative", "Instrumental Pop", "Instrumental Rock", "Ethnic", + "Gothic", "Darkwave", "Techno-Industrial", "Electronic", "Pop-Folk", "Eurodance", "Dream", "Southern Rock", + "Comedy", "Cult", "Gangsta", "Top 40", "Christian Rap", "Pop/Funk", "Jungle", "Native American", "Cabaret", + "New Wave", "Psychadelic", "Rave", "Showtunes", "Trailer", "Lo-Fi", "Tribal", "Acid Punk", "Acid Jazz", "Polka", + "Retro", "Musical", "Rock & Roll", "Hard Rock", "Folk", "Folk-Rock", "National Folk", "Swing", "Fast Fusion", + "Bebob", "Latin", "Revival", "Celtic", "Bluegrass", "Avantgarde", "Gothic Rock", "Progressive Rock", + "Psychedelic Rock", "Symphonic Rock", "Slow Rock", "Big Band", "Chorus", "Easy Listening", "Acoustic", "Humour", + "Speech", "Chanson", "Opera", "Chamber Music", "Sonata", "Symphony", "Booty Bass", "Primus", "Porn Groove", + "Satire", "Slow Jam", "Club", "Tango", "Samba", "Folklore", "Ballad", "Power Ballad", "Rhythmic Soul", + "Freestyle", "Duet", "Punk Rock", "Drum Solo", "A capella", "Euro-House", "Dance Hall", "Goa", "Drum & Bass", + "Club-House", "Hardcore", "Terror", "Indie", "BritPop", "Negerpunk", "Polsk Punk", "Beat", + "Christian Gangsta Rap", "Heavy Metal", "Black Metal", "Crossover", "Contemporary Christian", "Christian Rock", + "Merengue", "Salsa", "Thrash Metal", "Anime", "JPop", "Synthpop", +} +Tags.GENRES = GENRES + +-- frame id -> field name (v2.3/2.4 ids and their v2.2 equivalents) +local FIELDS = { + TIT2 = "title", TT2 = "title", + TPE1 = "artist", TP1 = "artist", + TALB = "album", TAL = "album", + TPE2 = "albumartist", TP2 = "albumartist", + TYER = "date", TYE = "date", TDRC = "date", + TRCK = "track", TRK = "track", + TPOS = "disc", TPA = "disc", + TCON = "genre", TCO = "genre", + TCOM = "composer", TCM = "composer", + COMM = "comment", COM = "comment", +} + +local function utf8char(cp: number): string + if cp < 0 or cp > 0x10FFFF or (cp >= 0xD800 and cp <= 0xDFFF) then + cp = 0xFFFD + end + return utf8.char(cp) +end + +-- bytes [i, j) of b, decoded from ID3 text encoding enc (0 latin-1, 1 UTF-16 + BOM, 2 UTF-16BE, 3 UTF-8) +local function decodeText(b: buffer, i: number, j: number, enc: number): string + local out = {} + if enc == 1 or enc == 2 then + local le = false + if enc == 1 and j - i >= 2 then + local b0, b1 = ru8(b, i), ru8(b, i + 1) + if b0 == 0xFF and b1 == 0xFE then + le = true + i += 2 + elseif b0 == 0xFE and b1 == 0xFF then + i += 2 + else + le = true -- no BOM: assume little-endian (what most taggers write) + end + end + local pending = 0 + while i + 1 < j do + local u = if le then bor(ru8(b, i), lshift(ru8(b, i + 1), 8)) else bor(lshift(ru8(b, i), 8), ru8(b, i + 1)) + i += 2 + if u >= 0xD800 and u <= 0xDBFF then + pending = u + else + if u >= 0xDC00 and u <= 0xDFFF and pending ~= 0 then + u = 0x10000 + lshift(pending - 0xD800, 10) + (u - 0xDC00) + end + pending = 0 + table.insert(out, if u == 0 then "\0" else utf8char(u)) + end + end + elseif enc == 3 then + local s = buffer.readstring(b, i, j - i) + if utf8.len(s) then + return s + end + enc = 0 -- invalid UTF-8: fall back to latin-1 + end + if enc == 0 then + for k = i, j - 1 do + local c = ru8(b, k) + table.insert(out, if c < 0x80 then string.char(c) else utf8char(c)) + end + end + return table.concat(out) +end + +local function clean(s: string): string + s = string.gsub(s, "[%z%s]+$", "") + s = string.gsub(s, "%z+", " / ") + return s +end + +-- "(17)", "(17)Rock", "17" -> "Rock" +local function genreName(s: string): string + local n = tonumber(string.match(s, "^%((%d+)%)$") or string.match(s, "^(%d+)$")) + if n and GENRES[n] then + return GENRES[n] + end + local rest = string.match(s, "^%(%d+%)(.+)$") + return rest or s +end + +local function syncsafe(b: buffer, o: number): number + return bor(lshift(band(ru8(b, o), 0x7F), 21), lshift(band(ru8(b, o + 1), 0x7F), 14), lshift(band(ru8(b, o + 2), 0x7F), 7), band(ru8(b, o + 3), 0x7F)) +end + +local function be32(b: buffer, o: number): number + return bor(lshift(ru8(b, o), 24), lshift(ru8(b, o + 1), 16), lshift(ru8(b, o + 2), 8), ru8(b, o + 3)) +end + +-- undo unsynchronisation (FF 00 -> FF) of b[i, j) into a new buffer +local function deunsync(b: buffer, i: number, j: number): buffer + local out = buffer.create(math.max(0, j - i)) + local n = 0 + local k = i + while k < j do + local c = ru8(b, k) + buffer.writeu8(out, n, c) + n += 1 + k += if c == 0xFF and k + 1 < j and ru8(b, k + 1) == 0 then 2 else 1 + end + local r = buffer.create(n) + buffer.copy(r, 0, out, 0, n) + return r +end + +-- minimp3's ID3v2 detection: total tag size (header + body + footer) or 0 +function Tags.id3v2Size(b: buffer, o: number, len: number): number + if len - o < 10 or buffer.readstring(b, o, 3) ~= "ID3" then + return 0 + end + if band(ru8(b, o + 5), 15) ~= 0 then + return 0 + end + for k = 6, 9 do + if band(ru8(b, o + k), 0x80) ~= 0 then + return 0 + end + end + local size = syncsafe(b, o + 6) + 10 + if band(ru8(b, o + 5), 16) ~= 0 then + size += 10 + end + return size +end + +local function setField(tags: any, id: string, text: string) + tags.raw[id] = text + local f = FIELDS[id] + if f and tags[f] == nil and text ~= "" then + tags[f] = if f == "genre" then genreName(text) else text + end +end + +local function parseV2(b: buffer, o: number, size: number, tags: any) + local ver = ru8(b, o + 3) + local flags = ru8(b, o + 5) + if ver < 2 or ver > 4 then + return + end + tags.id3v2 = "2." .. ver + local bodyEnd = math.min(o + 10 + syncsafe(b, o + 6), buffer.len(b)) + local body = b + local p, e = o + 10, bodyEnd + if band(flags, 0x80) ~= 0 and ver < 4 then + body = deunsync(b, p, e) + 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) + p += if ver == 3 then be32(body, p) + 4 else syncsafe(body, p) + end + local hdr = if ver == 2 then 6 else 10 + while p + hdr <= e do + local c0 = ru8(body, p) + if c0 == 0 then + break -- padding + end + local id, fsize, fflags + if ver == 2 then + id = buffer.readstring(body, p, 3) + fsize = bor(lshift(ru8(body, p + 3), 16), lshift(ru8(body, p + 4), 8), ru8(body, p + 5)) + fflags = 0 + else + id = buffer.readstring(body, p, 4) + fsize = if ver == 4 then syncsafe(body, p + 4) else be32(body, p + 4) + fflags = bor(lshift(ru8(body, p + 8), 8), ru8(body, p + 9)) + end + if not string.match(id, "^[A-Z0-9]+$") or fsize <= 0 or p + hdr + fsize > e then + break + end + local fs, fe = p + hdr, p + hdr + fsize + local fb = body + local skip = false + if ver == 3 then + skip = band(fflags, 0x00C0) ~= 0 -- compressed / encrypted + elseif ver == 4 then + skip = band(fflags, 0x000C) ~= 0 + if not skip and band(fflags, 0x0001) ~= 0 then + fs += 4 -- data length indicator + end + if not skip and band(fflags, 0x0002) ~= 0 and fs < fe then + fb = deunsync(body, fs, fe) + fs = 0 + fe = buffer.len(fb) + end + end + if not skip and fs < fe then + local first = string.sub(id, 1, 1) + local enc = ru8(fb, fs) + if first == "T" and id ~= "TXXX" and id ~= "TXX" then + setField(tags, id, clean(decodeText(fb, fs + 1, fe, enc))) + elseif (id == "COMM" or id == "COM") and fe - fs >= 4 then + -- encoding, language[3], short description (NUL-terminated in the encoding), text + local q = fs + 4 + local wide = enc == 1 or enc == 2 + while q < fe do + if wide then + if q + 1 < fe and ru8(fb, q) == 0 and ru8(fb, q + 1) == 0 then + q += 2 + break + end + q += 2 + else + if ru8(fb, q) == 0 then + q += 1 + break + end + q += 1 + end + end + if q <= fe then + setField(tags, id, clean(decodeText(fb, q, fe, enc))) + end + end + end + p += hdr + fsize + end +end + +local function v1String(b: buffer, o: number, n: number): string + return (string.gsub(decodeText(b, o, o + n, 0), "[%z%s]+$", "")) +end + +function Tags.parse(b: buffer): (any, number, number) + local len = buffer.len(b) + local tags: any = { raw = {} } + local start, stop = 0, len + local v2 = Tags.id3v2Size(b, 0, len) + if v2 > 0 then + pcall(parseV2, b, 0, v2, tags) + start = math.min(v2, len) + end + -- mp3dec_skip_id3v1 on what follows the ID3v2 tag + local size = stop - start + if size >= 128 and buffer.readstring(b, start + size - 128, 3) == "TAG" then + local o = start + size - 128 + tags.id3v1 = true + local v1: { [string]: any } = { + title = v1String(b, o + 3, 30), + artist = v1String(b, o + 33, 30), + album = v1String(b, o + 63, 30), + 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) + v1.track = tostring(ru8(b, o + 126)) + else + v1.comment = v1String(b, o + 97, 30) + end + local g = ru8(b, o + 127) + if GENRES[g] then + v1.genre = GENRES[g] + end + for k, v in v1 do + if tags[k] == nil and v ~= "" then + tags[k] = v + end + end + size -= 128 + if size >= 227 and buffer.readstring(b, start + size - 227, 4) == "TAG+" then + size -= 227 + end + end + if size > 32 and buffer.readstring(b, start + size - 32, 8) == "APETAGEX" then + size -= 32 + local t = start + size + 12 + local tagSize = bor(ru8(b, t), lshift(ru8(b, t + 1), 8), lshift(ru8(b, t + 2), 16), lshift(ru8(b, t + 3), 24)) + if size >= tagSize then + size -= tagSize + end + tags.ape = true + end + stop = start + size + return tags, start, stop +end + +return Tags +end +__FILES["audio/mpc"] = function() + +-- audio/mpc: Musepack (.mpc / .mp+ / .mpp) SV7 and SV8 via codecs/audio/Musepack (a libmpcdec port). Supports: mono / +-- stereo, 32-48 kHz, gapless length, seeking (SV8 exact; SV7 with 32 frames of pre-roll, as libmpcdec), APEv2 tags, +-- an ID3v2 prefix, ReplayGain in meta. Not supported: writing, SV4-SV6 (UNSUPPORTED), chapters. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Pcm = __include("codecs/audio/Pcm") +local Stream = __include("codecs/audio/Stream") +local ApeTag = __include("codecs/audio/ApeTag") +local Musepack = __include("codecs/audio/Musepack") + +-- ------------------------------------------------------------------------------------------------ contract +local Mpc = { + name = "mpc", + category = "audio", + extensions = { "mpc", "mp+", "mpp" }, + mime = { "audio/x-musepack", "audio/musepack" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/Musepack" }, + caps = { decode = true, encode = false, codecs = { "musepack" }, versions = { 7, 8 }, streaming = true, lossy = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + maxFrames: number?, -- default 2^31 +} + +-- ------------------------------------------------------------------------------------------------ constants +local function id3v2(b: buffer, p: number, limit: number): number + if p + 10 > limit or buffer.readstring(b, p, 3) ~= "ID3" then + return 0 + end + local n = 10 + for i = 6, 9 do + n += bit32.band(buffer.readu8(b, p + i), 127) * 128 ^ (9 - i) + end + return n + (if bit32.band(buffer.readu8(b, p + 5), 0x10) ~= 0 then 10 else 0) +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Mpc.sniff(r: Bytes.Reader): number + local b, p, limit = r.buf, r.pos, r.limit + p += id3v2(b, p, limit) + local v = Musepack.magic(b, p, limit) + if v == 8 then + return 1 + end + return if v == 7 then 0.9 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Mpc.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?) + local o: DecodeOptions = opts or {} + local b, base, limit = r.buf, r.base, r.limit + local start = base + id3v2(b, base, limit) + local tags, info = ApeTag.find(b, start, limit) + local stop = if info and info.start > start then info.start else limit + local s, err = Musepack.open(b, start, stop) + if not s then + return nil, err + end + if s.frames > (o.maxFrames or 2 ^ 31) then + return nil, Err.new(Err.LIMIT, "more than " .. (o.maxFrames or 2 ^ 31) .. " frames") + end + local duration = s.frames / s.sampleRate + local dec = { + sampleRate = s.sampleRate, + channels = s.channels, + frames = s.frames, + duration = duration, + bitrate = if duration > 0 then math.floor(s.bytes * 8 / duration + 0.5) else 0, + tags = tags or {}, + codec = "musepack", + version = s.version, + profile = s.profile, + gain = s.gain, + } + return Stream.packets(dec, s :: any) +end + +function Mpc.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) + local dec, err = Mpc.open(r, opts) + if not dec then + return nil, err + end + local d: any = dec + return Pcm.drain(d, { format = "mpc", codec = "musepack", version = d.version, profile = d.profile, gain = d.gain, bitrate = d.bitrate }) +end + +return Mpc +end +__FILES["audio/opus"] = function() + +-- audio/opus: Ogg Opus (RFC 6716, RFC 7845); absorbed from opus-luau dd2b4e5, a port of the libopus 1.6 decoder (BSD: +-- licenses/libopus-BSD.txt). Supports: every mode / bandwidth / frame size, mapping families 0 / 1 / 255, seeking, PLC; +-- encode CELT only (20 ms, full band, CBR). Not supported: SILK / hybrid encoding, mapping family 3, chained streams. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Ogg = __include("containers/Ogg") +local Decoder = __include("codecs/audio/Opus/Decoder") +local Packet = __include("codecs/audio/Opus/Packet") +local VorbisComment = __include("codecs/audio/VorbisComment") +local Pcm = __include("codecs/audio/Pcm") +local RangeDecoder = __include("codecs/entropy/RangeCoder/Decoder") +local Celt = __include("codecs/audio/Opus/Celt") +local Silk = __include("codecs/audio/Opus/Silk") +local Encode = __include("audio/opus/Encode") + +-- ------------------------------------------------------------------------------------------------ contract +local Opus = { + name = "opus", + category = "audio", + extensions = { "opus" }, + mime = { "audio/opus", "audio/ogg" }, + 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 }, +} + +-- ------------------------------------------------------------------------------------------------ types +type OpenOptions = { + verify: boolean?, -- check the Ogg page CRCs (default true; false decodes damaged files) + stereo: boolean?, -- downmix more than 2 channels to stereo (default false; dec.channels is then 2) +} + +-- ------------------------------------------------------------------------------------------------ constants +local SAMPLE_RATE = 48000 + +-- stereo downmix weights for the Vorbis channel orders of mapping family 1 (3 to 8 channels), as in opusfile +local DOWNMIX = { + [3] = { 0.5858, 0, 0.4142, 0.4142, 0, 0.5858 }, + [4] = { 0.4226, 0, 0, 0.4226, 0.366, 0.2114, 0.2114, 0.366 }, + [5] = { 0.651, 0, 0.46, 0.46, 0, 0.651, 0.5636, 0.3254, 0.3254, 0.5636 }, + [6] = { 0.529, 0, 0.3741, 0.3741, 0, 0.529, 0.4582, 0.2645, 0.2645, 0.4582, 0.3741, 0.3741 }, + [7] = { 0.4553, 0, 0.322, 0.322, 0, 0.4553, 0.3943, 0.2277, 0.2277, 0.3943, 0.2788, 0.2788, 0.322, 0.322 }, + [8] = { 0.3886, 0, 0.2748, 0.2748, 0, 0.3886, 0.3366, 0.1943, 0.1943, 0.3366, 0.3366, 0.1943, 0.1943, 0.3366, 0.2748, 0.2748 }, +} +local PREROLL = 3840 -- 80 ms, RFC 7845 section 4.6 +local MAX_PACKET = 5760 -- 120 ms + +type Head = { + version: number, + channels: number, + preSkip: number, + inputSampleRate: number, + outputGain: number, -- Q7.8 dB + mappingFamily: number, + streams: number, + coupled: number, + mapping: { number }, +} + +-- OpusHead (RFC 7845 section 5.1) +local function parseHead(b: buffer, off: number, size: number): (Head?, string?) + if size < 19 or buffer.readstring(b, off, 8) ~= "OpusHead" then + return nil, "not an OpusHead packet" + end + local version = buffer.readu8(b, off + 8) + if bit32.rshift(version, 4) ~= 0 then + return nil, "unsupported OpusHead version " .. version + end + local channels = buffer.readu8(b, off + 9) + if channels < 1 then + return nil, "OpusHead: zero channels" + end + local head: Head = { + version = version, + channels = channels, + preSkip = buffer.readu16(b, off + 10), + inputSampleRate = buffer.readu32(b, off + 12), + outputGain = buffer.readi16(b, off + 16), + mappingFamily = buffer.readu8(b, off + 18), + streams = 1, + coupled = channels - 1, + mapping = {}, + } + if head.mappingFamily == 0 then + if channels > 2 then + return nil, "OpusHead: mapping family 0 with more than 2 channels" + end + head.mapping = if channels == 2 then { 0, 1 } else { 0 } + else + if head.mappingFamily == 3 then + return nil, "unsupported channel mapping family 3 (projection)" + end + if size < 21 + channels then + return nil, "OpusHead: truncated channel mapping table" + end + head.streams = buffer.readu8(b, off + 19) + head.coupled = buffer.readu8(b, off + 20) + if head.streams < 1 or head.coupled > head.streams or head.streams + head.coupled > 255 then + return nil, "OpusHead: bad stream counts" + end + for c = 0, channels - 1 do + local m = buffer.readu8(b, off + 21 + c) + if m ~= 255 and m >= head.streams + head.coupled then + return nil, "OpusHead: bad channel mapping" + end + head.mapping[c + 1] = m + end + end + return head, nil +end + +-- OpusTags (RFC 7845 section 5.2) +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 "", {}, {} + end + local p = off + 8 + local e = off + size + local vlen = buffer.readu32(b, p) + p += 4 + if p + vlen > e then + return "", {}, {} + end + local vendor = buffer.readstring(b, p, vlen) + p += vlen + local list = {} + if p + 4 <= e then + 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) + p += 4 + if p + l > e then + break + end + table.insert(list, buffer.readstring(b, p, l)) + p += l + end + end + local tags, raw = VorbisComment.tags(list) + return vendor, tags, raw +end + +Opus.Decoder = Decoder +Opus.Packet = Packet +Opus.RangeDecoder = RangeDecoder +Opus.Celt = Celt +Opus.Silk = Silk +Opus.parseHead = parseHead +Opus.parseTags = parseTags +Opus.SAMPLE_RATE = SAMPLE_RATE + +-- ------------------------------------------------------------------------------------------------ sniff +function Opus.sniff(r: Bytes.Reader): number + if r:peek(4) ~= "OggS" then + return 0 + end + local nseg = r:peekU8(26) + if nseg < 1 then + return 0 + end + return if r:peek(8, 27 + nseg) == "OpusHead" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Opus.decode(r: any, opts: OpenOptions?): (Types.Audio?, Err.Err?) + local dec, err = Opus.open(r, opts) + if not dec then + return nil, err + end + 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 +function Opus.encode(value: any, opts: Encode.Options?): (buffer?, Err.Err?) + return Encode.encode(value, opts) +end + +-- ------------------------------------------------------------------------------------------------ open +local Stream = {} +Stream.__index = Stream + +local function decodeNext(self: any): boolean + local p = self.demux:nextPacket(self.serial) + if p == nil then + return false + end + local n + if p.size > 0 then + n = Decoder.decodeMultistream(self.ms, p.data, p.offset, p.size, self.pend, 1, MAX_PACKET) + else + n = -1 + end + if n < 0 then + -- corrupt or empty packet: conceal for its nominal duration + local dur = if p.size > 0 then Packet.samples(p.data, p.offset, p.size) else -1 + if dur <= 0 then + dur = self.lastDuration + end + n = Decoder.decodeMultistream(self.ms, nil, 0, 0, self.pend, 1, dur) + if n < 0 then + n = dur + for i = 1, n * self.channels do + self.pend[i] = 0 + end + end + end + self.lastDuration = n + self.pendStart = self.decoded + self.pendLen = n + self.pendPos = 0 + self.decoded += n + return true +end + +function Stream.read(self: any, maxFrames: number, into: buffer?): (buffer, number) + local ch = self.channels + local mf = if type(maxFrames) == "number" and maxFrames == maxFrames then maxFrames else 0 + local want = math.max(0, math.min(math.floor(mf), self.endSample - self.next)) + local reuse = into ~= nil and buffer.len(into) >= want * ch * 4 + local out = if reuse then into :: buffer else buffer.create(want * ch * 4) + local got = 0 + local gain = self.gain + while got < want do + if self.pendPos >= self.pendLen then + if not decodeNext(self) then + break + end + end + local s = self.pendStart + self.pendPos + if s < self.next then + self.pendPos = math.min(self.pendLen, self.pendPos + (self.next - s)) + continue + end + local n = math.min(self.pendLen - self.pendPos, want - got) + if self.downmix then + 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 + self.next += n + end + if got < want then + if not reuse then + local trimmed = buffer.create(got * ch * 4) + buffer.copy(trimmed, 0, out, 0, got * ch * 4) + out = trimmed + end + self.endSample = self.next + end + return out, got +end + +function Stream.position(self: any): number + return (self.next - self.preSkip) / SAMPLE_RATE +end + +function Stream.seek(self: any, seconds: number) + local sec = if type(seconds) == "number" and seconds == seconds then seconds else 0 + local p = math.floor(math.max(0, math.min(sec, 1e12)) * SAMPLE_RATE + 0.5) + p = math.min(p, self.frames) + local target = p + self.preSkip -- decoded-sample index of the wanted sample + Decoder.resetMultistream(self.ms) + self.pendLen, self.pendPos = 0, 0 + local g = target - PREROLL + self.startGranule + local start = -1 + if g > self.startGranule then + start = self.demux:seekGranule(self.serial, g) or -1 + end + if start < 0 then + self.demux:rewind(self.serial) + self.demux:nextPacket(self.serial) -- OpusHead + self.demux:nextPacket(self.serial) -- OpusTags + self.decoded = 0 + else + self.decoded = start - self.startGranule + end + self.pendStart = self.decoded + self.next = target +end + +function Opus.open(r: any, opts: OpenOptions?): (any, Err.Err?) + local demux, derr = Ogg.open(r, if opts and opts.verify == false then { verify = false } else nil) + if not demux then + return nil, derr + end + local serial = demux:find("opus") + if serial == nil then + return nil, Err.new(Err.CORRUPT, "no Opus stream in the Ogg file") + end + local hp = demux:nextPacket(serial) + if hp == nil then + return nil, Err.new(Err.TRUNCATED, "missing OpusHead") + end + local head, herr = parseHead(hp.data, hp.offset, hp.size) + if not head then + return nil, Err.new(if string.find(herr or "", "unsupported", 1, true) then Err.UNSUPPORTED else Err.CORRUPT, herr or "bad OpusHead") + end + local tp = demux:nextPacket(serial) + if tp == nil then + return nil, Err.new(Err.TRUNCATED, "missing OpusTags") + end + 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 + while true do + local p = demux:nextPacket(serial) + if p == nil then + break + end + local d = if p.size > 0 then Packet.samples(p.data, p.offset, p.size) else 0 + sum += math.max(d, 0) + if p.granule ~= -1 then + startGranule = math.max(0, p.granule - sum) + break + end + end + demux:rewind(serial) + demux:nextPacket(serial) + demux:nextPacket(serial) + local info = demux:stream(serial) + local last = if info and info.lastGranule and info.lastGranule >= 0 then info.lastGranule else startGranule + local frames = math.max(0, last - startGranule - head.preSkip) + local downmix = nil + if opts and opts.stereo and head.channels > 2 then + downmix = DOWNMIX[head.channels] + if downmix == nil or head.mappingFamily ~= 1 then -- unknown layout: every channel to both sides, equally + downmix = table.create(head.channels * 2, 1 / head.channels) + end + end + local self = setmetatable({ + demux = demux, + serial = serial, + head = head, + vendor = vendor, + tags = tags, + comments = rawTags, + -- 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, + sourceChannels = head.channels, + downmix = downmix, + frames = frames, + duration = frames / SAMPLE_RATE, + bitrate = if frames > 0 then math.floor(demux.size * 8 / (frames / SAMPLE_RATE)) else 0, + preSkip = head.preSkip, + startGranule = startGranule, + gain = 10 ^ (head.outputGain / (20 * 256)), + ms = Decoder.newMultistream(head.channels, head.streams, head.coupled, head.mapping), + pend = table.create(MAX_PACKET * head.channels, 0), + pendStart = 0, + pendLen = 0, + pendPos = 0, + decoded = 0, -- decoded-sample index of the next packet's first sample + next = head.preSkip, -- decoded-sample index of the next sample read() returns + endSample = head.preSkip + frames, + lastDuration = 960, + }, Stream) + return self, nil +end + + +return Opus +end +__FILES["audio/opus/Encode"] = function() + +-- audio/opus/Encode: Ogg Opus writing (RFC 7845), CELT only (TOC config 31: full band, 20 ms, code 0), family 0. +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Ogg = __include("containers/Ogg") +local Pcm = __include("codecs/audio/Pcm") +local Resample = __include("codecs/audio/Resample") +local VorbisComment = __include("codecs/audio/VorbisComment") +local CeltEncoder = __include("codecs/audio/Opus/CeltEncoder") + +local Encode = {} + +type Options = { + bitrate: number?, -- bits per second (default 64000 per channel; 6000 .. 510000, constant); values below 1000 + -- are kbit/s (96 = 96000), as for every encoder's bitrate option + tags: { [string]: string }?, -- default: the audio's tags + vendor: string?, -- OpusTags vendor (default "rosetta") + serial: number?, -- Ogg stream serial (default 0x4f707573) +} + +local floor = math.floor + +function Encode.encode(value: any, opts: Options?): (buffer?, Err.Err?) + local o: Options = opts or {} + local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + 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 = src.sampleRate + if rate < 1000 or rate > 768000 then + return nil, Err.new(Err.ARG, "bad sample rate " .. tostring(rate)) + end + local bitrate = o.bitrate or 64000 * ch + if type(bitrate) == "number" and bitrate > 0 and bitrate < 1000 then + bitrate *= 1000 + end + if type(bitrate) ~= "number" or bitrate < 6000 or bitrate > 510000 then + return nil, Err.new(Err.ARG, "bitrate 6000 .. 510000") + end + if rate ~= 48000 then + local rs, rerr = Resample.source(src, 48000) + if not rs then + return nil, Err.new(Err.ARG, tostring(rerr)) + end + src = rs + end + 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 + local packets = (n48 + preSkip + FRAME - 1) // FRAME + for i = n48 * ch + 1, packets * FRAME * ch do + pcm[i] = 0 + end + local bytes = math.clamp(floor(bitrate * FRAME / 48000 / 8), if ch == 2 then 40 else 20, 1275 - 1) + local st = CeltEncoder.new(ch) + local mux = Ogg.muxer({ pageSize = 4096 }) + local s = mux:stream(o.serial or 0x4f707573) + -- OpusHead + local head = Bytes.writer(19) + head:string("OpusHead") + head:u8(1) + head:u8(ch) + head:u16le(preSkip) + head:u32le(floor(rate)) + head:u16le(0) + head:u8(0) + s:packet(head:finish(), 0, { flush = true }) + -- OpusTags + local tags = o.tags or src.tags or {} + local tw = Bytes.writer(256) + tw:string("OpusTags") + local vendor = o.vendor or "rosetta" + tw:u32le(#vendor) + tw:string(vendor) + local fields = VorbisComment.fields(tags) + tw:u32le(#fields) + for _, field in fields do + tw:u32le(#field) + tw:string(field) + end + s:packet(tw:finish(), 0, { flush = true }) + local toc = 31 * 8 + (if ch == 2 then 4 else 0) + for p = 0, packets - 1 do + local frame = CeltEncoder.encodeFrame(st, pcm, p * FRAME * ch + 1, ch, bytes) + local pkt = buffer.create(bytes + 1) + buffer.writeu8(pkt, 0, toc) + buffer.copy(pkt, 1, frame, 0, bytes) + local last = p == packets - 1 + local granule = if last then preSkip + n48 else (p + 1) * FRAME + s:packet(pkt, granule, { eos = last }) + end + return mux:finish(), nil +end + +return Encode +end +__FILES["audio/qoa"] = function() + +-- audio/qoa: QOA "Quite OK Audio" via codecs/audio/Qoa (a port of qoa.h, phoboslab, MIT). Supports: static and +-- streaming files, 1-255 channels, rates up to 16777215 Hz, frame-accurate seeking; encode byte-for-byte as qoa_encode, +-- 1-8 channels. Not supported: channel count or rate changes mid-stream. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Pcm = __include("codecs/audio/Pcm") +local Stream = __include("codecs/audio/Stream") +local Codec = __include("codecs/audio/Qoa") + +-- ------------------------------------------------------------------------------------------------ contract +local Qoa = { + name = "qoa", + category = "audio", + extensions = { "qoa" }, + mime = { "audio/qoa" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/Qoa" }, + caps = { decode = true, encode = true, streaming = true, lossy = true, seek = true, channels = 8 }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + maxFrames: number?, -- default 2^28 +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Qoa.sniff(r: Bytes.Reader): number + return if r:peek(4) == "qoaf" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Qoa.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) + local dec, err = Qoa.open(r) + if not dec then + return nil, err + end + local d = dec :: any + local limit = opts and opts.maxFrames or 2 ^ 28 + 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 + return Pcm.drain(d, { format = "qoa", streaming = d.streaming }, limit) +end + +-- ------------------------------------------------------------------------------------------------ encode +function Qoa.encode(value: any, _opts: any?): (buffer?, Err.Err?) + local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local ch, rate = src.channels, src.sampleRate + if ch > 8 then + return nil, Err.new(Err.ARG, "QOA (qoa.h) holds at most 8 channels") + end + if rate ~= math.floor(rate) or rate < 1 or rate > 0xFFFFFF then + return nil, Err.new(Err.ARG, "the sample rate must be an integer in 1 .. 16777215") + end + local FL = Codec.FRAME_LEN + local w = Bytes.writer(8 + (if src.frames > 0 then Codec.frameSize(ch, (src.frames + 19) // 20) + 24 * ch * (src.frames // FL + 1) else 65536)) + w:string("qoaf") + w:u32be(0) + local lms = Codec.newLms(ch) + local fb = buffer.create(FL * ch * 4) + local tmp: buffer? = nil + local total = 0 + while true do + -- one frame: 5120 sample frames (the last may be shorter), as qoa.h cuts them + local have = 0 + while have < FL do + local b, n = src:read(FL - have, tmp) + if n <= 0 then + break + end + tmp = b + buffer.copy(fb, have * ch * 4, b, 0, n * ch * 4) + have += n + end + if have == 0 then + break + end + local at = w:reserve(Codec.frameSize(ch, (have + 19) // 20)) + w.pos = at + Codec.encodeFrame(fb, 0, have, ch, rate, lms, w.buf, at) + total += have + if have < FL then + break + end + end + if src.err then + return nil, src.err + end + if total == 0 then + return nil, Err.new(Err.ARG, "QOA needs at least one sample") + end + if total >= 2 ^ 32 then + return nil, Err.new(Err.ARG, "too many samples for QOA") + end + local out = w:finish() + buffer.writeu32(out, 4, bit32.byteswap(total)) + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Qoa.open(r: Bytes.Reader, _opts: any?): (Types.Decoder?, Err.Err?) + if type(r) ~= "table" or type(r.buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "open: expected a Reader") + end + local h = r:sub(0) + if h:string(4) ~= "qoaf" then + return nil, Err.new(Err.CORRUPT, "not a QOA file") + end + local declared = h:u32be() + if h.err then + return nil, h.err + end + local buf = r.buf + local offs, starts = {}, {} + local p, total = r.base + 8, 0 + local ch, rate = 0, 0 + while p < r.limit do + local info, msg = Codec.frameInfo(buf, p, r.limit - p) + if not info then + if #offs == 0 then + return nil, Err.from(msg, p - r.base) + end + break -- a cut or damaged tail: keep the whole frames + end + if #offs == 0 then + ch, rate = info.channels, info.rate + elseif info.channels ~= ch or info.rate ~= rate then + return nil, Err.new(Err.UNSUPPORTED, "the channel count or rate changes mid-stream", p - r.base) + end + table.insert(offs, p) + table.insert(starts, total) + total += info.samples + p += info.size + if declared > 0 and total >= declared then + break + end + end + if #offs == 0 then + return nil, Err.new(Err.TRUNCATED, "no frames") + end + local frames = if declared > 0 then math.min(declared, total) else total + local pcm = buffer.create(Codec.FRAME_LEN * ch * 4) + local dec: any = { + sampleRate = rate, + channels = ch, + frames = frames, + duration = frames / rate, + bitrate = math.floor((p - r.base) * 8 / math.max(frames / rate, 1e-9)), + tags = {}, + streaming = declared == 0, + } + local limit = r.limit + return Stream.packets(dec, { + count = #offs, + start = function(i: number): number + return if i > #offs then total else starts[i] + end, + decode = function(i: number): (number?, Err.Err?) + local n, msg = Codec.decodeFrame(buf, offs[i], limit - offs[i], pcm, 0) + if not n then + return nil, Err.from(msg, offs[i] - r.base) + end + return n, nil + end, + pcm = function(): buffer + return pcm + end, + reset = function() end, + stop = frames, + }) +end + +return Qoa +end +__FILES["audio/tta"] = function() + +-- audio/tta: True Audio (.tta, TTA1) via codecs/audio/Tta, from the TTA1 format description. Supports: 8 / 16 / 24 +-- bits, any channel count, seeking by the seek table, APEv2 tags, an ID3v2 prefix. Not supported: password-protected +-- files, TTA2, ID3v2 contents, encoding. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Pcm = __include("codecs/audio/Pcm") +local Stream = __include("codecs/audio/Stream") +local ApeTag = __include("codecs/audio/ApeTag") +local TtaCodec = __include("codecs/audio/Tta") + +-- ------------------------------------------------------------------------------------------------ contract +local Tta = { + name = "tta", + category = "audio", + extensions = { "tta" }, + mime = { "audio/x-tta", "audio/tta" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/Tta" }, + caps = { decode = true, encode = false, streaming = true, seek = true, lossless = true, depths = { 8, 16, 24 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type OpenOptions = { + maxFrames: number?, -- default 2^28 +} + +-- ------------------------------------------------------------------------------------------------ sniff +local function id3Size(r: Bytes.Reader): number + if r:peek(3) ~= "ID3" then + return 0 + end + local sz = 0 + for i = 6, 9 do + local v = r:peekU8(i) + if v < 0 then + return 0 + end + sz = sz * 128 + bit32.band(v, 127) + end + local footer = bit32.band(math.max(r:peekU8(5), 0), 0x10) ~= 0 + return 10 + sz + (if footer then 10 else 0) +end + +function Tta.sniff(r: Bytes.Reader): number + return if r:peek(4, id3Size(r)) == "TTA1" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Tta.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?) + local dec, err = Tta.open(r, opts) + if not dec then + return nil, err + end + local d = dec :: any + local limit = opts and opts.maxFrames or 2 ^ 28 + 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 + return Pcm.drain(d, d.source, limit) +end + +-- ------------------------------------------------------------------------------------------------ open +function Tta.open(r: Bytes.Reader, opts: OpenOptions?): (Types.Decoder?, Err.Err?) + if type(r) == "buffer" then + r = Bytes.reader(r :: any) + end + if type(r) ~= "table" or type(r.buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "open: expected a Reader") + end + local buf, base, limit = r.buf, r.base, r.limit + local at = base + id3Size(r) + local tags, tagInfo = ApeTag.find(buf, at, limit) + local stop = if tagInfo then tagInfo.start else limit + local info, err = TtaCodec.info(buf, at, stop) + if not info then + return nil, err + end + if info.channels * info.frameLength > 2 ^ 24 then + return nil, Err.new(Err.LIMIT, info.channels .. " channels of " .. info.frameLength .. "-sample frames") + end + local codec = TtaCodec.decoder(info, stop) + local frames = info.samples + local dec: any = { + sampleRate = info.sampleRate, + channels = info.channels, + frames = frames, + duration = frames / info.sampleRate, + bitrate = if frames > 0 then math.floor((stop - base) * 8 * info.sampleRate / frames) else 0, + tags = tags or {}, + bitsPerSample = info.bitsPerSample, + float = false, + source = { format = "tta", bitDepth = info.bitsPerSample, tags = tagInfo and tagInfo.items }, + } + local fl, count = info.frameLength, info.frames + return Stream.packets(dec, { + count = count, + start = function(i: number): number + return if i > count then frames else (i - 1) * fl + end, + decode = function(i: number): (number?, Err.Err?) + return codec:frame(buf, i) + end, + pcm = function(): { number } + return codec.pcm + end, + reset = function() end, + stop = frames, + scale = 1 / 2 ^ (info.bitsPerSample - 1), + ints = true, + }) +end + +return Tta +end +__FILES["audio/vag"] = function() + +-- audio/vag: Sony VAG (PS-ADPCM: VAGp mono, VAGi stereo) and KVAG (IMA); layouts follow vgmstream r2117 (ISC, +-- licenses/vgmstream-LICENSE.txt), bit-exact, Sony's leading blank frame included. Supports: loop points; encode VAGp / +-- VAGi. Not supported: HEVAG (0x00020001 / 0x00030000), game-specific variants (pGAV, VAG1 / VAG2, Jak, ...). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Pcm = __include("codecs/audio/Pcm") +local Adpcm = __include("codecs/audio/Adpcm") +local Decoder = __include("codecs/audio/Adpcm/Decoder") + +-- ------------------------------------------------------------------------------------------------ contract +local Vag = { + name = "vag", + category = "audio", + extensions = { "vag" }, + mime = { "audio/x-vag" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm", "codecs/audio/Adpcm/Decoder" }, + caps = { decode = true, encode = true, streaming = true, lossy = true, loops = true, channels = 2 }, +} + +-- ------------------------------------------------------------------------------------------------ types +type Loop = { start: number, stop: number } +type DecodeOptions = { + maxFrames: number?, -- default 2^28 +} +type EncodeOptions = { + loop: Loop?, -- loop points in frames of the input (stop exclusive), rounded out to 28-sample frames; default: the + -- source's meta.source.loop, else none + name: string?, -- the 16-byte name field (default: tags.title) + interleave: number?, -- stereo: bytes per channel block (default 2048, a multiple of 16) +} + +-- ------------------------------------------------------------------------------------------------ constants +local HEVAG = { [0x00020001] = true, [0x00030000] = true } + +-- ------------------------------------------------------------------------------------------------ sniff +function Vag.sniff(r: Bytes.Reader): number + local m = r:peek(4) + return if m == "VAGp" or m == "VAGi" or m == "KVAG" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Vag.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) + local dec, err = Vag.open(r) + if not dec then + return nil, err + end + local d = dec :: any + local limit = opts and opts.maxFrames or 2 ^ 28 + 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 + return Pcm.drain(d, { format = "vag", variant = d.variant, codec = d.codec, loop = d.loop }, limit) +end + +-- ------------------------------------------------------------------------------------------------ encode +function Vag.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local ch, rate = src.channels, src.sampleRate + if ch > 2 then + return nil, Err.new(Err.ARG, "VAG holds mono or stereo") + end + if rate ~= math.floor(rate) or rate < 1 or rate >= 2 ^ 32 then + return nil, Err.new(Err.ARG, "the sample rate must be a positive integer") + end + local il = o.interleave or 2048 + if type(il) ~= "number" or il < 16 or il % 16 ~= 0 then + return nil, Err.new(Err.ARG, "interleave must be a multiple of 16") + end + local loop = o.loop + local v = value :: any + if loop == nil and type(v.meta) == "table" and type(v.meta.source) == "table" and type(v.meta.source.loop) == "table" then + loop = v.meta.source.loop + end + local a, cerr = Pcm.collect(src) + if not a then + return nil, cerr + end + local n = a.frames + local nf = (n + 27) // 28 -- data frames (after the blank one) + local ls, le = -1, -1 + if loop then + if type(loop.start) ~= "number" or type(loop.stop) ~= "number" or loop.start < 0 or loop.stop > n then + return nil, Err.new(Err.ARG, "loop must be { start, stop } inside the audio") + end + ls, le = loop.start // 28, (loop.stop + 27) // 28 - 1 + if le <= ls then + return nil, Err.new(Err.ARG, "the loop must span two 28-sample frames") + end + end + local chBytes = (nf + 1) * 16 + local stride = if ch == 1 then chBytes else (chBytes + il - 1) // il * il + local start = if ch == 1 then 0x30 else 0x800 + local out = buffer.create(start + stride * ch) + local title = o.name or (a.tags and a.tags.title) or "" + buffer.writestring(out, 0, if ch == 1 then "VAGp" else "VAGi") + buffer.writeu32(out, 4, bit32.byteswap(0x20)) + if ch == 2 then + buffer.writeu32(out, 8, il) + end + buffer.writeu32(out, 0x0C, bit32.byteswap(if ch == 1 then chBytes else stride)) + buffer.writeu32(out, 0x10, bit32.byteswap(rate)) + buffer.writestring(out, 0x20, string.sub(title, 1, 16)) + local st = buffer.create(8 * ch) + local plane = buffer.create(chBytes) + for c = 0, ch - 1 do + buffer.fill(plane, 0, 0) + Adpcm.psxEncode(a.samples, c, ch, n, st, c * 8, plane, 16, 16) + for k = 0, nf - 1 do + local flag = if k == ls then 6 elseif k == le then 3 elseif k > ls and k < le then 2 else 0 + if not loop and k == nf - 1 then + flag = 1 + end + buffer.writeu8(plane, 16 + k * 16 + 1, flag) + end + if ch == 1 then + buffer.copy(out, start, plane, 0, chBytes) + else + for b = 0, stride // il - 1 do + local take = math.clamp(chBytes - b * il, 0, il) + if take > 0 then + buffer.copy(out, start + (b * ch + c) * il, plane, b * il, take) + end + end + end + end + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- vgmstream's loop reading: channel 0's first start flag 6 and first end flag 3 +local function findLoop(buf: buffer, p: number, frames: number, il: number, ch: number): Loop? + local ls, le = -1, -1 + for k = 0, frames - 1 do + local off = p + (k * 16) // il * il * ch + (k * 16) % il + local flag = bit32.band(buffer.readu8(buf, off + 1), 15) + if flag == 6 and ls < 0 then + ls = k * 28 + elseif flag == 3 and le < 0 then + le = k * 28 + 28 + if ls >= 0 then + break + end + end + end + return if ls >= 0 and le > ls then { start = ls, stop = le } else nil +end + +function Vag.open(r: Bytes.Reader, _opts: any?): (Types.Decoder?, Err.Err?) + if type(r) ~= "table" or type(r.buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "open: expected a Reader") + end + local h = r:sub(0) + local magic = h:string(4) + local total = r.limit - r.base + if magic == "KVAG" then + local size, rate, stereo = h:u32le(), h:u32le(), h:u16le() + if h.err then + return nil, h.err + end + if rate < 1 or stereo > 1 then + return nil, Err.new(Err.CORRUPT, "bad KVAG header") + end + local dec: any = { sampleRate = rate, channels = stereo + 1, tags = {}, variant = "KVAG", codec = "ima" } + local d, err = Decoder.nibbles(dec, { buf = r.buf, offset = r.base + 14, size = math.min(size, total - 14), hi = true }) + if d then + d.bitrate = rate * 4 * (stereo + 1) + end + return d, err + end + if magic ~= "VAGp" and magic ~= "VAGi" then + return nil, Err.new(Err.CORRUPT, "not a VAG file") + end + local version, il = h:u32be(), h:u32le() + local chSize, rate = h:u32be(), h:u32be() + local name = r:sub(0x20, 16):cstring(16) + if h.err then + return nil, h.err + end + if HEVAG[version] then + return nil, Err.new(Err.UNSUPPORTED, "HEVAG (Vita / PS4 VAG)") + end + if rate < 1 or rate >= 2 ^ 31 then + return nil, Err.new(Err.CORRUPT, "bad sample rate " .. rate) + end + local ch, start = 1, 0x30 + if magic == "VAGi" then + ch, start = 2, 0x800 + if il < 16 or il % 16 ~= 0 then + return nil, Err.new(Err.CORRUPT, "bad interleave " .. il) + end + else + il = 16 + end + if total < start then + return nil, Err.new(Err.TRUNCATED, "the header runs past the end") + end + local size = math.min(chSize * ch, total - start) + local p = r.base + start + local frames = math.min(chSize // 16, (size // (il * ch)) * (il // 16) + math.clamp(size % (il * ch) - (ch - 1) * il, 0, il) // 16) + local loop = if magic == "VAGp" then findLoop(r.buf, p, frames, il, ch) else nil -- vgmstream: VAGi never loops + local tags = {} + if name ~= "" then + tags.title = name + end + local dec: any = { sampleRate = rate, channels = ch, tags = tags, variant = magic, codec = "psx", loop = loop } + local d, err = Decoder.interleaved(dec, { kind = "psx", buf = r.buf, offset = p, size = size, interleave = il, frames = frames * 28 }) + if d then + d.bitrate = rate * 16 * 8 * ch // 28 + end + return d, err +end + +return Vag +end +__FILES["audio/voc"] = function() + +-- audio/voc: Creative Voice File (.voc), from Creative's format description. Supports: block types 1, 2, 3, 5, 8, 9 +-- (8 / 16-bit, A-law, mu-law); markers and repeats played once, as ffmpeg; truncated files; encode version 1.20 type 9 +-- blocks. Not supported: Creative ADPCM, channel count changes mid-file (the first block's rate is used). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Pcm = __include("codecs/audio/Pcm") + +-- ------------------------------------------------------------------------------------------------ contract +local Voc = { + name = "voc", + category = "audio", + extensions = { "voc" }, + mime = { "audio/x-voc" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm" }, + caps = { decode = true, encode = true, streaming = true, depths = { 8, 16 }, lossy = false }, +} + +type DecodeOptions = { + maxFrames: number?, -- default 2^28 +} +type EncodeOptions = { + sampleFormat: ("u8" | "s16" | "alaw" | "ulaw")?, -- default "s16" +} + +-- ------------------------------------------------------------------------------------------------ constants +local MAGIC = "Creative Voice File\26" +local T9_CODECS: { [number]: string } = { [0] = "u8", [4] = "s16le", [6] = "alaw", [7] = "ulaw" } +local T1_CODECS: { [number]: string } = { [0] = "u8", [4] = "s16le" } +local WRITE = { u8 = { 0, "u8", 8 }, s16 = { 4, "s16le", 16 }, alaw = { 6, "alaw", 8 }, ulaw = { 7, "ulaw", 8 } } +local MAX_BLOCK = 0xFFFFFF - 12 -- payload bytes of one type 9 block (a 24-bit size, 12 header bytes) + +local readu8 = buffer.readu8 +local function u16(b: buffer, o: number): number + return readu8(b, o) + readu8(b, o + 1) * 256 +end +local function u24(b: buffer, o: number): number + return readu8(b, o) + readu8(b, o + 1) * 256 + readu8(b, o + 2) * 65536 +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Voc.sniff(r: Bytes.Reader): number + return if r:peek(20) == MAGIC then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +type Segment = { at: number, frames: number, fmt: string? } -- fmt nil: silence + +function Voc.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) + local b, base, limit = r.buf, r.base, r.limit + if limit - base < 26 or buffer.readstring(b, base, 20) ~= MAGIC then + return nil, Err.new(Err.CORRUPT, "bad magic", base) + end + local hsize = u16(b, base + 20) + local version = u16(b, base + 22) + if hsize < 26 or hsize > limit - base then + return nil, Err.new(Err.CORRUPT, "bad header size", base + 20) + end + local maxFrames = opts and opts.maxFrames or 2 ^ 28 + local rate, channels = 0, 0 + local extRate, extChannels = 0, 0 -- a type 8 block's settings for the next type 1 block + local lastFmt: string? = nil + local codec = -1 + local segments: { Segment } = {} + local total = 0 + local truncated = false + local tags: Types.Tags = {} + local p = base + hsize + local function add(at: number, bytes: number, fmt: string?, ch: number, sr: number): Err.Err? + if channels == 0 then + channels, rate = ch, sr + elseif ch ~= channels then + return Err.new(Err.UNSUPPORTED, "the channel count changes mid-file", at) + end + local frames = if fmt then bytes // (ch * Pcm.Convert.SIZE[fmt]) else bytes + if frames > 0 then + total += frames + if total > maxFrames then + return Err.new(Err.LIMIT, string.format("over the %d frame limit", maxFrames)) + end + table.insert(segments, { at = at, frames = frames, fmt = fmt }) + end + return nil + end + while p < limit do + local t = readu8(b, p) + if t == 0 then + break + end + if p + 4 > limit then + truncated = true + break + end + local size = u24(b, p + 1) + local d = p + 4 + local avail = math.min(size, limit - d) + if avail < size then + truncated = true + end + local err: Err.Err? = nil + if t == 1 then + if avail < 2 then + break + end + local div, c = readu8(b, d), readu8(b, d + 1) + local fmt = T1_CODECS[c] + if not fmt then + return nil, Err.new(Err.UNSUPPORTED, "Creative ADPCM (codec " .. c .. ")", d + 1) + end + local ch, sr = 1, 1000000 // (256 - div) + if extChannels > 0 then + ch, sr = extChannels, extRate + extChannels = 0 + end + lastFmt, codec = fmt, c + err = add(d + 2, avail - 2, fmt, ch, sr) + elseif t == 2 then + if lastFmt == nil then + return nil, Err.new(Err.CORRUPT, "continuation block before any sound data", p) + end + err = add(d, avail, lastFmt, channels, rate) + elseif t == 3 then + if avail < 3 then + break + end + local len, div = u16(b, d) + 1, readu8(b, d + 2) + err = add(d, len, nil, if channels > 0 then channels else 1, if rate > 0 then rate else 1000000 // (256 - div)) + elseif t == 5 then + local s = buffer.readstring(b, d, avail) + local z = string.find(s, "\0", 1, true) + if z then + s = string.sub(s, 1, z - 1) + end + tags.comment = if tags.comment then tags.comment .. "\n" .. s else s + elseif t == 8 then + if avail < 4 then + break + end + local tc, mode = u16(b, d), readu8(b, d + 3) + extChannels = mode + 1 + extRate = 256000000 // (extChannels * (65536 - tc)) + elseif t == 9 then + if avail < 12 then + break + end + local sr = readu8(b, d) + readu8(b, d + 1) * 256 + readu8(b, d + 2) * 65536 + readu8(b, d + 3) * 16777216 + local ch, c = readu8(b, d + 5), u16(b, d + 6) + local fmt = T9_CODECS[c] + if not fmt then + return nil, Err.new(Err.UNSUPPORTED, "codec " .. c, d + 6) + end + if ch < 1 or sr < 1 then + return nil, Err.new(Err.CORRUPT, "bad channels or sample rate", d) + end + lastFmt, codec = fmt, c + err = add(d + 12, avail - 12, fmt, ch, sr) + end + if err then + return nil, err + end + p = d + size + end + if channels == 0 then + return nil, Err.new(if truncated then Err.TRUNCATED else Err.CORRUPT, "no sound data", p) + end + local a = Types.Audio.new(rate, channels, total) + local o = 0 + for _, s in segments do + local n = s.frames * channels + if s.fmt then + Pcm.Convert.decode(b, s.at, s.fmt :: string, n, a.samples, o) + end + o += n * 4 + end + a.tags = tags + a.meta.source = { + format = "voc", + version = string.format("%d.%02d", version // 256, version % 256), + codec = codec, + sampleFormat = lastFmt, + bitDepth = if lastFmt == "s16le" then 16 else 8, + truncated = truncated or nil, + } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Voc.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local o: EncodeOptions = opts or {} + local spec = WRITE[o.sampleFormat or "s16"] + if not spec then + return nil, Err.new(Err.ARG, "unknown sampleFormat " .. tostring(o.sampleFormat)) + end + if src.channels > 255 then + return nil, Err.new(Err.ARG, "at most 255 channels") + end + if src.sampleRate ~= math.floor(src.sampleRate) or src.sampleRate >= 2 ^ 32 then + return nil, Err.new(Err.ARG, "the sample rate must be an integer") + end + local w = Bytes.writer(65536) + w:string(MAGIC) + w:u16le(26) + w:u16le(0x0114) + w:u16le((0xFFFF - 0x0114 + 0x1234 + 1) % 65536) -- ~version + 0x1234 + if type(src.tags.comment) == "string" and #src.tags.comment > 0 then + local s = string.sub(src.tags.comment, 1, 0xFFFFFE) + w:u8(5) + w:u24le(#s + 1) + w:string(s) + w:u8(0) + end + local size = Pcm.Convert.SIZE[spec[2]] + local frameBytes = size * src.channels + local framesPerBlock = MAX_BLOCK // frameBytes + local blockAt, blockFrames = -1, 0 + local tmp: buffer? = nil + while true do + local bf, n = src:read(math.min(8192, framesPerBlock), tmp) + if n <= 0 then + break + end + tmp = bf + local i = 0 + while i < n do + if blockAt < 0 or blockFrames == framesPerBlock then + blockAt = w:tell() + blockFrames = 0 + w:u8(9) + w:u24le(0) + w:u32le(src.sampleRate) + w:u8(spec[3]) + w:u8(src.channels) + w:u16le(spec[1]) + w:u32le(0) + end + local take = math.min(n - i, framesPerBlock - blockFrames) + local at = w:reserve(take * frameBytes) + Pcm.Convert.encode(bf, i * src.channels * 4, take * src.channels, spec[2], w.buf, at) + w.pos = at + take * frameBytes + blockFrames += take + i += take + local len = blockFrames * frameBytes + 12 + w:setU8(blockAt + 1, len % 256) + w:setU8(blockAt + 2, (len // 256) % 256) + w:setU8(blockAt + 3, len // 65536) + end + end + if src.err then + return nil, src.err + end + w:u8(0) -- terminator + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Voc.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?) + local a, err = Voc.decode(r, opts) + if not a then + return nil, err + end + local dec = Pcm.audioDecoder(a) :: any + dec.source = a.meta.source + return dec, nil +end + +return Voc +end +__FILES["audio/vorbis"] = function() + +-- audio/vorbis: Ogg Vorbis (Vorbis I spec; RFC 5215); the decoder is a port of stb_vorbis 1.22 (public domain / MIT, +-- licenses/stb_vorbis-LICENSE.txt) with libvorbis' sample-exact trimming and seeking. Supports: 1-255 channels, +-- floor 1, residues 0-2, packetDecoder for Matroska / MP4; an encoder. Not supported: floor 0, chained streams. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Ogg = __include("containers/Ogg") +local Setup = __include("codecs/audio/Vorbis/Setup") +local Packet = __include("codecs/audio/Vorbis/Packet") +local Encode = __include("audio/vorbis/Encode") +local Pcm = __include("codecs/audio/Pcm") +local VorbisComment = __include("codecs/audio/VorbisComment") + +-- ------------------------------------------------------------------------------------------------ contract +local Vorbis = { + name = "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", "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 }, +} + +type OpenOptions = { + verify: boolean?, -- check the Ogg page CRCs (default true) +} +type EncodeOptions = { + quality: number?, -- -1 .. 10 (default 3): the floor sits 2 * quality - 1 dB under the band energies (8 dB + -- less at the top of the spectrum), which sets the residue's quantization step + serial: number?, -- the Ogg stream serial number (default 0x464C5541) +} + +-- ------------------------------------------------------------------------------------------------ constants +local function waveOrder(ch: number): { number } + local m = Pcm.WAVE_FROM_VORBIS[ch] + if m then + return m + end + local id = table.create(ch, 0) + for c = 1, ch do + id[c] = c + end + return id +end + +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, 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, 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, nil, Err.new(code, serr or "bad setup header") + end + local tags, raw = VorbisComment.tags(comments or {}) + return id, setup, vendor, tags, raw, nil +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Vorbis.sniff(r: Bytes.Reader): number + if r:remaining() < 35 or r:peek(4) ~= "OggS" then + return 0 + end + local b, p = r.buf, r.pos + local nseg = buffer.readu8(b, p + 26) + local d = p + 27 + nseg + if d + 7 > r.limit then + return 0 + end + return if buffer.readu8(b, d) == 1 and buffer.readstring(b, d + 1, 6) == "vorbis" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Vorbis.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?) + local dec, err = Vorbis.open(r, opts) + if not dec then + return nil, err + end + return Pcm.drain(dec) +end + +-- ------------------------------------------------------------------------------------------------ encode +function Vorbis.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local o: EncodeOptions = opts or {} + local q = o.quality or 3 + if type(q) ~= "number" or q ~= q or q < -1 or q > 10 then + return nil, Err.new(Err.ARG, "quality must be -1 .. 10") + end + if src.channels > 255 then + return nil, Err.new(Err.ARG, "at most 255 channels") + end + if src.sampleRate ~= math.floor(src.sampleRate) or src.sampleRate < 1 or src.sampleRate >= 2 ^ 32 then + return nil, Err.new(Err.ARG, "the sample rate must be a positive integer") + end + local serial = o.serial or 0x464C5541 + if type(serial) ~= "number" or serial ~= math.floor(serial) or serial < 0 or serial >= 2 ^ 32 then + return nil, Err.new(Err.ARG, "serial must be a 32-bit unsigned integer") + end + local out, msg = Encode.encode(src :: any, { quality = q, vendor = "rosetta Vorbis encoder", serial = serial }) + if not out then + return nil, Err.new(Err.CORRUPT, tostring(msg)) + end + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ open +local Stream = {} +Stream.__index = Stream + +local function push(self: any, arrays: { { number } }, g0: number, count: number, hi: number) + local lo = math.max(g0, self.startG, self.skipTo) + if hi > g0 + count then + hi = g0 + count + end + if hi > lo then + table.insert(self.queue, { arrays, lo - g0 + 1, hi - g0, lo }) + end +end + +local function copyOut(self: any, count: number): { { number } } + local t = table.create(self.channels) + for c = 1, self.channels do + local src = self.st.out[c] + local a = table.create(count, 0) + table.move(src, 1, count, 1, a) + t[c] = a + end + return t +end + +local function decodeMore(self: any): boolean + local reader, st = self.reader, self.st + while not self.ended do + local p = reader:nextPacket() + if p == nil then + self.ended = true + break + end + if p.gap then + Packet.reset(st) + self.syncing, self.pend, self.pendCount = true, {}, 0 + end + local count = Packet.decode(st, p.data, p.offset, p.size) + if count >= 0 then + local endG = if p.eos and p.granule >= 0 then p.granule else math.huge + if self.syncing then + if count > 0 then + table.insert(self.pend, { copyOut(self, count), count }) + self.pendCount += count + end + if p.granule >= 0 then + -- the position is known again: this packet's output ends at its granule + local g = p.granule - self.pendCount + if p.eos and self.pendCount > 0 then + g = math.max(g, self.pos) -- an end-trimmed last page: keep the running position + end + for _, c in self.pend do + push(self, c[1], g, c[2], endG) + g += c[2] + end + self.pos = g + self.syncing, self.pend, self.pendCount = false, {}, 0 + end + else + local g0 = self.pos + self.pos += count + if count > 0 then + push(self, st.out, g0, count, endG) + end + if p.granule >= 0 and not p.eos then + self.pos = p.granule + end + end + if p.eos then + self.ended = true + end + if #self.queue > 0 then + return true + end + end + end + return #self.queue > 0 +end + +function Stream.read(self: any, n: number, out: buffer?): (buffer, number) + local ch = self.channels + n = math.max(0, math.floor(n)) + local b = if out and buffer.len(out) >= n * ch * 4 then out else buffer.create(n * ch * 4) + local got = 0 + local writef32 = buffer.writef32 + while got < n do + local q = self.queue[1] + if q == nil then + if not decodeMore(self) then + break + end + q = self.queue[1] + 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[order[c]] + local o = got * ch * 4 + (c - 1) * 4 + for i = first, first + take - 1 do + writef32(b, o, a[i]) + o += ch * 4 + end + end + got += take + self.next = q[4] + take + if first + take > last then + table.remove(self.queue, 1) + else + q[2] = first + take + q[4] += take + end + end + if got > 0 then + self.skipTo = -math.huge + end + return b, got +end + +function Stream.position(self: any): number + return (self.next - self.startG) / self.sampleRate +end + +local function restart(self: any) + local r = self.reader + r:rewind() + for _ = 1, 3 do + r:nextPacket() + end + Packet.reset(self.st) + self.pos = self.base + self.syncing, self.pend, self.pendCount = false, {}, 0 + self.ended = false + self.queue = {} +end + +function Stream.seek(self: any, seconds: number) + local target = self.startG + math.floor(math.max(0, seconds) * self.sampleRate + 0.5) + if target ~= target then + target = self.startG + end + if self.lastG >= 0 and target > self.lastG then + target = self.lastG + end + self.skipTo = target + self.next = target + local r = self.reader + local g = target - self.st.n1 + for _ = 1, 16 do + if g <= self.startG then + break + end + local G = r:seekGranule(g) + if G == nil or G < 0 then + break + end + -- decode forward to the next page boundary to learn the exact position + Packet.reset(self.st) + self.queue = {} + self.ended = false + self.syncing, self.pend, self.pendCount = true, {}, 0 + self.pos = G + local ok = false + while true do + local p = r:nextPacket() + if p == nil then + break + end + local count = Packet.decode(self.st, p.data, p.offset, p.size) + if count > 0 then + table.insert(self.pend, { copyOut(self, count), count }) + self.pendCount += count + end + if p.granule >= 0 then + if not p.eos then + local g0 = p.granule - self.pendCount + for _, c in self.pend do + push(self, c[1], g0, c[2], math.huge) + g0 += c[2] + end + self.pos = p.granule + self.syncing, self.pend, self.pendCount = false, {}, 0 + ok = true + end + break + end + end + if ok then + return + end + g = G - 1 -- the last page: start one page earlier + end + restart(self) + self.skipTo = target + self.next = target +end + +function Vorbis.open(r: any, opts: OpenOptions?): (Types.Decoder?, Err.Err?) + local demux, derr = Ogg.open(r, if opts and opts.verify == false then { verify = false } else nil) + if not demux then + return nil, derr + end + local serial = demux:find("vorbis") + if serial == nil then + return nil, Err.new(Err.CORRUPT, "no Vorbis stream in the Ogg file") + end + local reader = demux:reader(serial) + local h1 = reader:nextPacket() + if h1 == nil then + return nil, Err.new(Err.TRUNCATED, "missing identification header") + end + local id0, ierr = Setup.ident(h1.data, h1.offset, h1.size) + if not id0 then + return nil, Err.new(Err.CORRUPT, ierr or "bad identification header") + end + local h2 = reader:nextPacket() + if h2 == nil then + return nil, Err.new(Err.TRUNCATED, "missing comment header") + end + local h2copy = { data = Ogg.copy(h2), offset = 0, size = h2.size } + local h3 = reader:nextPacket() + if h3 == nil then + return nil, Err.new(Err.TRUNCATED, "missing setup header") + end + local id, setup, vendor, tags, raw, herr = headers(h1, h2copy, h3) + if not id then + return nil, herr + end + local st = Packet.new(id, setup) + if not st then + return nil, Err.new(Err.CORRUPT, "bad block sizes") + end + -- the granule of the first returned sample: the first granule page minus what its packets return + local base = 0 + do + local prev, sum = 0, 0 + while true do + local p = reader:nextPacket() + if p == nil then + break + end + local bs = Packet.blocksize(st, p.data, p.offset, p.size) + if bs > 0 then + if prev > 0 then + sum += prev // 4 + bs // 4 + end + prev = bs + end + if p.granule >= 0 then + base = p.granule - sum + if p.eos then + base = 0 -- one page holds the whole stream: the spec trims its end, not its start + end + break + end + end + end + local info = demux:stream(serial) + local lastG = if info and info.lastGranule and info.lastGranule >= 0 then info.lastGranule else -1 + local startG = math.max(base, 0) + local frames = if lastG >= 0 then math.max(0, lastG - startG) else 0 + local rate = id.sampleRate + local self = setmetatable({ + sampleRate = rate, + channels = id.channels, + frames = frames, + duration = frames / rate, + bitrate = if frames > 0 then math.floor(demux.size * 8 / (frames / rate)) else id.bitrateNominal, + tags = tags, + vendor = vendor, + ident = id, + -- WAVE channel order out (codecs/audio/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, + }, + demux = demux, + reader = reader, + st = st, + base = base, + startG = startG, + lastG = lastG, + pos = base, + next = startG, + skipTo = -math.huge, + queue = {}, + syncing = false, + pend = {}, + pendCount = 0, + ended = false, + }, Stream) + restart(self) + return self :: any, nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- raw Vorbis packets: Matroska / WebM / MP4 carry the three headers in their codec private data +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)) + if not id then + return nil, err + end + local st = Packet.new(id, setup) + if not st then + return nil, Err.new(Err.CORRUPT, "bad block sizes") + end + return { + sampleRate = id.sampleRate, + channels = id.channels, + vendor = vendor, + tags = tags, + 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 + end + return Packet.decode(st, b, offset, size) + end, + reset = function(_self: any) + Packet.reset(st) + end, + }, + nil +end + +return Vorbis +end +__FILES["audio/vorbis/Encode"] = @native function() + + + +-- audio/vorbis/Encode: Vorbis I encoder in Ogg, from the Vorbis I spec (no libvorbis code): long blocks only (2048), +-- one floor 1 per channel (30 posts), square-polar coupling, residue type 2, a fixed codebook set with Laplacian lengths. +local Mdct = __include("codecs/audio/Mdct") +local Pcm = __include("codecs/audio/Pcm") +local VorbisComment = __include("codecs/audio/VorbisComment") +local Ogg = __include("containers/Ogg") +local Tables = __include("codecs/audio/Vorbis/Tables") + +local Encode = {} + +local floor, log, exp, abs = math.floor, math.log, math.exp, math.abs +local writeu8 = buffer.writeu8 + +local POW = table.create(40, 0) +for i = 0, 39 do + POW[i + 1] = 2 ^ i +end + +local N = 2048 +local N2 = 1024 +local PSIZE_PER_CHANNEL = 16 -- residue partitions hold 16 values per channel (libvorbis needs a multiple of ch) +local MULT = 2 -- floor1 multiplier (range 128) +local RANGE = 128 +local NCLASS = 6 + +-- ------------------------------------------------------------------------------------------------ LSB-first bit writer +type W = { buf: buffer, pos: number, acc: number, cnt: number } + +@native local function newW(size: number): W + return { buf = buffer.create(size), pos = 0, acc = 0, cnt = 0 } +end + +@native local function put(w: W, v: number, n: number) + if n == 0 then + return + end + local acc = w.acc + v * POW[w.cnt + 1] + local cnt = w.cnt + n + local b, p = w.buf, w.pos + if p + 8 > buffer.len(b) then + local nb = buffer.create(buffer.len(b) * 2 + 64) + buffer.copy(nb, 0, b, 0, p) + b = nb + w.buf = nb + end + while cnt >= 8 do + local byte = acc % 256 + writeu8(b, p, byte) + p += 1 + acc = (acc - byte) / 256 + cnt -= 8 + end + w.acc, w.cnt, w.pos = acc, cnt, p +end + +@native local function finish(w: W): buffer + if w.cnt > 0 then + put(w, 0, 8 - w.cnt) + end + local out = buffer.create(w.pos) + buffer.copy(out, 0, w.buf, 0, w.pos) + return out +end + +@native local function putString(w: W, s: string) + for i = 1, #s do + put(w, string.byte(s, i), 8) + end +end + +@native local function ilog(x: number): number + local n = 0 + while x > 0 do + n += 1 + x = floor(x / 2) + end + return n +end + +-- ------------------------------------------------------------------------------------------------ codebooks +type Book = { + dims: number, + entries: number, + lengths: { number }, + codes: { number }, -- bit-reversed codewords (ready for the LSB-first writer) + lookup: number, -- 0 or 1 + minimum: number, + delta: number, + values: number, -- lookup1 values per dimension +} + +@native local function huffmanLengths(w: { number }): { number } + local n = #w + local total = 0 + for i = 1, n do + total += w[i] + end + local lens = table.create(n, 0) + if n == 1 then + lens[1] = 1 + return lens + end + local minw = total * 2 ^ -20 + local order = table.create(n, 0) + for i = 1, n do + order[i] = i + end + local weight = table.create(2 * n, 0) + local parent = table.create(2 * n, 0) + for i = 1, n do + weight[i] = math.max(w[i], minw) + end + table.sort(order, @native function(a: number, b: number): boolean + if weight[a] ~= weight[b] then + return weight[a] < weight[b] + end + return a < b + end) + local q1, h1 = order, 1 + local q2, h2, t2 = table.create(n, 0), 1, 0 + local nextId = n + @native local function pop(): number + local a = if h1 <= n then q1[h1] else nil + local b = if h2 <= t2 then q2[h2] else nil + if a and (not b or weight[a] <= weight[b]) then + h1 += 1 + return a + end + h2 += 1 + return b :: number + end + for _ = 1, n - 1 do + local a = pop() + local b = pop() + nextId += 1 + weight[nextId] = weight[a] + weight[b] + parent[a], parent[b] = nextId, nextId + t2 += 1 + q2[t2] = nextId + end + for i = 1, n do + local d, x = 0, i + while parent[x] ~= 0 do + x = parent[x] + d += 1 + end + lens[i] = d + end + return lens +end + +-- the spec's codeword assignment (lowest free leaf, in entry order) +@native local function assign(lens: { number }): { number } + local codes = table.create(#lens, 0) + local available = table.create(33, 0) + local first = true + for i, len in lens do + if len > 0 then + local code + if first then + first = false + code = 0 + for l = 1, len do + available[l + 1] = POW[33 - l] + 1 + end + else + local z = len + while z > 0 and available[z + 1] == 0 do + z -= 1 + end + code = available[z + 1] - 1 + available[z + 1] = 0 + for y = len, z + 1, -1 do + available[y + 1] = code + POW[33 - y] + 1 + end + end + -- the top len bits of the 32-bit left-aligned code, MSB first, reversed for the LSB-first writer + local msb = floor(code / POW[33 - len]) + local rev = 0 + for _ = 1, len do + rev = rev * 2 + msb % 2 + msb = floor(msb / 2) + end + codes[i] = rev + end + end + return codes +end + +@native local function makeBook(dims: number, entries: number, weight: (number) -> number, lookup: number, minimum: number, delta: number, values: number): Book + local w = table.create(entries, 0) + for e = 0, entries - 1 do + w[e + 1] = weight(e) + end + local lens = huffmanLengths(w) + return { dims = dims, entries = entries, lengths = lens, codes = assign(lens), lookup = lookup, minimum = minimum, delta = delta, values = values } +end + +@native local function vqBook(dims: number, h: number, scale: number, s: number, zeroBoost: number): Book + local values = 2 * h + 1 + local entries = values ^ dims + return makeBook(dims, entries, @native function(e: number): number + local wt = 1 + local x = e + for _ = 1, dims do + local v = x % values - h + x = x // values + wt *= exp(-abs(v) / s) * (if v == 0 then zeroBoost else 1) + end + return wt + end, 1, -h * scale, scale, values) +end + +local BOOK_FLOOR = makeBook(1, RANGE, @native function(e: number): number + return exp(-e / 7) + 0.002 +end, 0, 0, 0, 0) +local CLASS_W = { 0.30, 0.30, 0.20, 0.12, 0.06, 0.02 } +local BOOK_CLASS = makeBook(2, NCLASS * NCLASS, @native function(e: number): number + return CLASS_W[e % NCLASS + 1] * CLASS_W[e // NCLASS + 1] +end, 0, 0, 0, 0) +local BOOK_A = vqBook(4, 1, 1, 0.6, 2.5) -- |v| <= 1, 4 at a time (mostly zeros) +local BOOK_B = vqBook(2, 4, 1, 1.4, 1) -- |v| <= 4 +local BOOK_C = vqBook(2, 15, 1, 4, 1) -- |v| <= 15 +local BOOK_D = vqBook(2, 15, 16, 3, 1) -- multiples of 16 up to 240 +local BOOK_E = vqBook(2, 15, 256, 3, 1) -- multiples of 256 up to 3840 +local BOOKS = { BOOK_FLOOR, BOOK_CLASS, BOOK_A, BOOK_B, BOOK_C, BOOK_D, BOOK_E } +local FLOOR_BOOK, CLASS_BOOK, A_BOOK, B_BOOK, C_BOOK, D_BOOK, E_BOOK = 0, 1, 2, 3, 4, 5, 6 +-- the books of each residue class per pass (book numbers; -1 = none) +local CLASS_BOOKS = { + { -1, -1, -1 }, + { A_BOOK, -1, -1 }, + { B_BOOK, -1, -1 }, + { C_BOOK, -1, -1 }, + { D_BOOK, C_BOOK, -1 }, + { E_BOOK, D_BOOK, C_BOOK }, +} +local CLASS_MAX = { 0, 1, 4, 15, 255, 4095 } + +-- float32_pack (spec 9.2.2) of an integer-valued x +@native local function float32Pack(x: number): number + local sign = if x < 0 then 2147483648 else 0 + local m = abs(x) + local e = 788 + while m >= 2097152 do + m /= 2 + e += 1 + end + return sign + e * 2097152 + floor(m) +end + +@native local function writeBook(w: W, b: Book) + put(w, 0x564342, 24) + put(w, b.dims, 16) + put(w, b.entries, 24) + put(w, 0, 1) -- not ordered + put(w, 0, 1) -- not sparse + for i = 1, b.entries do + put(w, b.lengths[i] - 1, 5) + end + put(w, b.lookup, 4) + if b.lookup == 1 then + put(w, float32Pack(b.minimum), 32) + put(w, float32Pack(b.delta), 32) + local vb = ilog(b.values - 1) + put(w, vb - 1, 4) + put(w, 0, 1) -- sequence_p + for j = 0, b.values - 1 do + put(w, j, vb) + end + end +end + +@native local function putEntry(w: W, b: Book, e: number) + put(w, b.codes[e + 1], b.lengths[e + 1]) +end + +-- ------------------------------------------------------------------------------------------------ floor posts +-- x positions: 0, 1024, then 28 log-spaced points in bisection order (coarse first) so predictions are good +local POSTS: { number } = { 0, N2 } +do + local xs = {} + local seen = { [0] = true, [N2] = true } + for j = 0, 27 do + local x = floor(3 + 957 * (j / 27) ^ 2.2 + 0.5) -- 3 .. 960, denser at low frequencies + while seen[x] do + x += 1 + end + seen[x] = true + table.insert(xs, x) + end + table.sort(xs) + local queue = { { 1, #xs } } + local qh = 1 + while qh <= #queue do + local r = queue[qh] + qh += 1 + if r[1] <= r[2] then + local m = (r[1] + r[2]) // 2 + table.insert(POSTS, xs[m]) + table.insert(queue, { r[1], m - 1 }) + table.insert(queue, { m + 1, r[2] }) + end + end +end +local NPOSTS = #POSTS -- 30 +local FLOOR_PARTS = (NPOSTS - 2) // 4 -- 7 partitions of one class with 4 dimensions +local SORTED: { number } = table.create(NPOSTS, 0) -- post indices (1-based) by increasing x +for i = 1, NPOSTS do + SORTED[i] = i +end +table.sort(SORTED, @native function(a: number, b: number): boolean + return POSTS[a] < POSTS[b] +end) +local LOW, HIGH = table.create(NPOSTS, 0), table.create(NPOSTS, 0) +for j = 3, NPOSTS do + local lo, hi = -1, 65536 + local x = POSTS[j] + for k = 1, j - 1 do + local xv = POSTS[k] + if xv > lo and xv < x then + LOW[j], lo = k, xv + end + if xv < hi and xv > x then + HIGH[j], hi = k, xv + end + end +end +-- the floor value (0..127) closest to an amplitude, through the spec's inverse dB table +local DB = table.create(RANGE, 0) +for y = 0, RANGE - 1 do + DB[y + 1] = 20 * math.log10(Tables[y * MULT + 1]) +end +@native local function yOf(db: number): number + local y = floor((db - DB[1]) / (DB[RANGE] - DB[1]) * (RANGE - 1) + 0.5) + return math.clamp(y, 0, RANGE - 1) +end + +@native local function predict(x: number, x0: number, x1: number, y0: number, y1: number): number + local dy = y1 - y0 + local adx = x1 - x0 + local off = (abs(dy) * (x - x0)) // adx + return if dy < 0 then y0 - off else y0 + off +end + +-- render the decoder's floor curve for final Y values into F[1..N2] (only the posts the decoder marks used) +@native local function renderFloor(Y: { number }, used: { boolean }, F: { number }) + local lx, ly = 0, Y[1] * MULT + for q = 2, NPOSTS do + local j = SORTED[q] + if not used[j] then + continue + end + local hx, hy = POSTS[j], Y[j] * MULT + -- draw_line(lx, ly, hx, hy) + local dy = hy - ly + local adx = hx - lx + local ady = abs(dy) + local base = if dy < 0 then -(ady // adx) else ady // adx + local sy = if dy < 0 then base - 1 else base + 1 + ady -= abs(base) * adx + local x, y, err = lx, ly, 0 + local x1 = math.min(hx, N2) + if x < x1 then + F[x + 1] = Tables[y % 256 + 1] + x += 1 + while x < x1 do + err += ady + if err >= adx then + err -= adx + y += sy + else + y += base + end + F[x + 1] = Tables[y % 256 + 1] + x += 1 + end + end + lx, ly = hx, hy + end + for x = lx + 1, N2 do + F[x] = Tables[ly % 256 + 1] + end +end + +-- the coded value for target t at post j given the final values of its neighbours (spec 7.2.4 step 1, inverted) +@native local function floorVal(Y: { number }, j: number): number + local lo, hi = LOW[j], HIGH[j] + local pred = predict(POSTS[j], POSTS[lo], POSTS[hi], Y[lo], Y[hi]) + local t = Y[j] + local d = t - pred + if d == 0 then + return 0 + end + local highroom = RANGE - pred + local lowroom = pred + local room = if highroom < lowroom then highroom * 2 else lowroom * 2 + local cands = { if d > 0 then 2 * d else -2 * d - 1, d + lowroom, -d + highroom - 1 } + for _, v in cands do + if v > 0 and v < RANGE then + local got + if v >= room then + got = if highroom > lowroom then v - lowroom + pred else pred - v + highroom - 1 + elseif v % 2 == 1 then + got = pred - (v + 1) // 2 + else + got = pred + v // 2 + end + if got == t then + return v + end + end + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ headers +@native local function identHeader(ch: number, rate: number, nominal: number): buffer + local w = newW(64) + put(w, 1, 8) + putString(w, "vorbis") + put(w, 0, 32) + put(w, ch, 8) + put(w, rate, 32) + put(w, 0, 32) + put(w, nominal, 32) + put(w, 0, 32) + put(w, 8, 4) -- blocksize 0: 256 + put(w, 11, 4) -- blocksize 1: 2048 + put(w, 1, 1) + return finish(w) +end + +@native local function commentHeader(vendor: string, tags: { [string]: string }): buffer + local w = newW(256) + put(w, 3, 8) + putString(w, "vorbis") + put(w, #vendor, 32) + putString(w, vendor) + local fields = VorbisComment.fields(tags) + put(w, #fields, 32) + for _, s in fields do + put(w, #s, 32) + putString(w, s) + end + put(w, 1, 1) + return finish(w) +end + +@native local function setupHeader(ch: number): buffer + local w = newW(8192) + put(w, 5, 8) + putString(w, "vorbis") + -- codebooks + put(w, #BOOKS - 1, 8) + for _, b in BOOKS do + writeBook(w, b) + end + -- time domain placeholders + put(w, 0, 6) + put(w, 0, 16) + -- one floor 1 + put(w, 0, 6) + put(w, 1, 16) + put(w, FLOOR_PARTS, 5) + for _ = 1, FLOOR_PARTS do + put(w, 0, 4) -- class 0 + end + put(w, 3, 3) -- class 0: 4 dimensions + put(w, 0, 2) -- no subclasses + put(w, FLOOR_BOOK + 1, 8) -- its one subclass book (+1) + put(w, MULT - 1, 2) + put(w, 10, 4) -- rangebits: x in 0 .. 1024 + for j = 3, NPOSTS do + put(w, POSTS[j], 10) + end + -- one residue 2 + put(w, 0, 6) + put(w, 2, 16) + put(w, 0, 24) -- begin + put(w, N2 * ch, 24) -- end + put(w, PSIZE_PER_CHANNEL * ch - 1, 24) + put(w, NCLASS - 1, 6) + put(w, CLASS_BOOK, 8) + for c = 1, NCLASS do + local bits = 0 + for pass = 1, 3 do + if CLASS_BOOKS[c][pass] >= 0 then + bits += POW[pass] + end + end + put(w, bits % 8, 3) + if bits >= 8 then + put(w, 1, 1) + put(w, bits // 8, 5) + else + put(w, 0, 1) + end + end + for c = 1, NCLASS do + for pass = 1, 3 do + local b = CLASS_BOOKS[c][pass] + if b >= 0 then + put(w, b, 8) + end + end + end + -- one mapping + put(w, 0, 6) + put(w, 0, 16) + put(w, 0, 1) -- one submap + if ch == 2 then + put(w, 1, 1) + put(w, 0, 8) -- one coupling step + put(w, 0, 1) -- magnitude: channel 0 + put(w, 1, 1) -- angle: channel 1 + else + put(w, 0, 1) + end + put(w, 0, 2) + put(w, 0, 8) -- submap 0: time (unused) + put(w, 0, 8) -- floor 0 + put(w, 0, 8) -- residue 0 + -- one mode: long blocks + put(w, 0, 6) + put(w, 1, 1) + put(w, 0, 16) + put(w, 0, 16) + put(w, 0, 8) + put(w, 1, 1) -- framing + return finish(w) +end + +-- ------------------------------------------------------------------------------------------------ encoder +type Source = { + sampleRate: number, + channels: number, + frames: number, + tags: { [string]: string }, + read: (self: any, n: number, out: buffer?) -> (buffer, number), + err: any, +} +type Options = { + quality: number, -- -1 .. 10 + vendor: string, + serial: number, +} + +@native local function writePartition(w: W, v: { number }, o: number, psize: number, c: number, pass: number) + local b = CLASS_BOOKS[c][pass] + if b < 0 then + return + end + local book = BOOKS[b + 1] + local dims, h = book.dims, (book.values - 1) // 2 + local scale = book.delta + local values = book.values + local i = 0 + while i < psize do + local e = 0 + local m = 1 + for k = 0, dims - 1 do + local x = v[o + i + k + 1] + -- the part of x this pass carries (coarse passes take the rounded multiple of their scale) + local q + if pass < 3 and CLASS_BOOKS[c][pass + 1] >= 0 then + q = math.clamp(floor(x / scale + 0.5), -h, h) + else + q = math.clamp(x // scale, -h, h) + end + v[o + i + k + 1] = x - q * scale + e += (q + h) * m + m *= values + end + putEntry(w, book, e) + i += dims + end +end + +@native function Encode.encode(src: Source, opts: Options): (buffer?, string?) + local ch, rate = src.channels, src.sampleRate + local q = math.clamp(opts.quality, -1, 10) + local snrDb = 2 * q - 1 -- floor level below the band energy (at low frequencies; 8 dB less at the top) + local mux = Ogg.muxer({ pageSize = 4096 }) + local stream = mux:stream(opts.serial) + local nominal = floor(math.clamp(rate * ch * (0.6 + 0.12 * q), 32000, 500000)) + stream:packet(identHeader(ch, rate, nominal), 0, { flush = true }) + stream:packet(commentHeader(opts.vendor, src.tags), 0) + stream:packet(setupHeader(ch), 0, { flush = true }) + 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: { { number } } = table.create(ch) :: any + 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: { { 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) + end + local F = table.create(N2, 0) + local Y = table.create(NPOSTS, 0) + local vals = table.create(NPOSTS, 0) + local used = table.create(NPOSTS, false) + local inter = table.create(N2 * ch, 0) + local psize = PSIZE_PER_CHANNEL * ch + local npart = N2 * ch // psize + local classes = table.create(npart + 2, 0) + local total = 0 + local srcDone = false + local tmp: buffer? = nil + local pending: buffer? = nil + local pendN, pendOff = 0, 0 + local k = 0 + local lastWanted = -1 -- the last packet index needed (known once the input ends) + while true do + for c = 1, ch do + local fr = frame[c] + table.move(fr, N2 + 1, N, 1) + end + local got = 0 + while got < N2 and not srcDone do + if pendN == 0 then + local b, n = src:read(4096, tmp) + if n <= 0 then + srcDone = true + break + end + tmp = b + pending, pendN, pendOff = b, n, 0 + end + local take = math.min(N2 - got, pendN) + local pb = pending :: buffer + for i = 0, take - 1 do + local base = (pendOff + i) * ch * 4 + for c = 1, ch do + frame[order[c]][N2 + got + i + 1] = buffer.readf32(pb, base + (c - 1) * 4) + end + end + got += take + pendN -= take + pendOff += take + end + for c = 1, ch do + local fr = frame[c] + for i = N2 + got + 1, N do + fr[i] = 0 + end + end + total += got + if srcDone and lastWanted < 0 then + lastWanted = (total + N2 - 1) // N2 -- packets 0 .. lastWanted (packet j returns [(j-1)*1024, j*1024)) + end + -- this frame is centred on k*1024; its first half is [k*1024 - 1024, k*1024) + local energy = 0 + for c = 1, ch do + local fr = frame[c] + for i = 1, N do + blk[i] = fr[i] * win[i] + end + Mdct.forward(plan, blk, 1, X[c], 1, 1, 4 / N) + local xc = X[c] + for i = 1, N2 do + energy += xc[i] * xc[i] + end + end + local w = newW(2048) + put(w, 0, 1) -- audio packet + -- (one mode: 0 bits) long block, previous and next long + put(w, 1, 1) + put(w, 1, 1) + local silent = energy < 1e-18 + if silent then + for _ = 1, ch do + put(w, 0, 1) -- no floor: the channel is zero + end + else + -- the floor from the loudest channel's band energies at each post + for j = 1, NPOSTS do + local x = POSTS[j] + -- the band around x: halfway to the neighbouring posts in x order + local idx = table.find(SORTED, j) :: number + local lo = if idx > 1 then (POSTS[SORTED[idx - 1]] + x) // 2 else 0 + local hi = if idx < NPOSTS then (POSTS[SORTED[idx + 1]] + x) // 2 else N2 - 1 + if hi < lo then + hi = lo + end + local e = 0 + for c = 1, ch do + local xc = X[c] + local s = 0 + for i = lo + 1, math.min(hi + 1, N2) do + s += xc[i] * xc[i] + end + s /= (hi - lo + 1) + if s > e then + e = s + end + end + local db = if e > 0 then 10 * math.log10(e) - snrDb + 8 * x / N2 else -200 + Y[j] = yOf(db) + end + -- the decoder's step 2 flags: a point is drawn when its value or a later neighbour's value is nonzero + used[1], used[2] = true, true + for j = 3, NPOSTS do + local v = floorVal(Y, j) + vals[j] = v + used[j] = v ~= 0 + if v ~= 0 then + used[LOW[j]], used[HIGH[j]] = true, true + end + end + renderFloor(Y, used, F) + -- residues: X / F rounded, then coupling, then interleaving + for c = 1, ch do + local xc, rc = X[c], R[c] + for i = 1, N2 do + local v = floor(xc[i] / F[i] + 0.5) + rc[i] = math.clamp(v, -4095, 4095) + end + end + if ch == 2 then + local l, r = R[1], R[2] + for i = 1, N2 do + local a, b = l[i], r[i] + local m, an + if abs(a) > abs(b) then + m = a + an = if a > 0 then a - b else b - a + else + m = b + an = if b > 0 then a - b else b - a + end + -- keep the angle inside the books' range + l[i], r[i] = m, math.clamp(an, -4095, 4095) + end + end + for c = 1, ch do + local rc = R[c] + for i = 1, N2 do + inter[(i - 1) * ch + c] = rc[i] + end + end + -- floors + for _ = 1, ch do + put(w, 1, 1) + put(w, Y[1], 7) + put(w, Y[2], 7) + for j = 3, NPOSTS do + putEntry(w, BOOK_FLOOR, vals[j]) + end + end + -- residue classes + for p = 0, npart - 1 do + local m = 0 + for i = 1, psize do + local a = abs(inter[p * psize + i]) + if a > m then + m = a + end + end + local c = 1 + while CLASS_MAX[c] < m do + c += 1 + end + classes[p + 1] = c + end + classes[npart + 1] = 1 + for pass = 1, 3 do + for p = 0, npart - 1, 2 do + if pass == 1 then + putEntry(w, BOOK_CLASS, (classes[p + 1] - 1) * NCLASS + (classes[p + 2] - 1)) -- first partition: the high digit + end + writePartition(w, inter, p * psize, psize, classes[p + 1], pass) + if p + 1 < npart then + writePartition(w, inter, (p + 1) * psize, psize, classes[p + 2], pass) + end + end + end + end + local pk = finish(w) + local last = lastWanted >= 0 and k >= lastWanted + local granule = if k == 0 then 0 else math.min(k * N2, if lastWanted >= 0 then total else math.huge) + stream:packet(pk, granule, if last then { eos = true } else nil) + if last then + break + end + k += 1 + end + if src.err then + return nil, tostring(src.err) + end + return mux:finish(), nil +end + +Encode.BOOKS = BOOKS + +return Encode +end +__FILES["audio/wav"] = function() + + +-- audio/wav: WAVE in RIFF / RIFX / RF64 / BW64; absorbed from wav-luau fd9a909 (same author). Supports: PCM 8-32 bit, +-- float 32 / 64, A-law, mu-law, IMA / MS ADPCM, EXTENSIBLE, LIST/INFO tags, data size 0 / 0xFFFFFFFF (to the end); +-- encode PCM and f32, EXTENSIBLE and RF64 as ffmpeg. Not supported: encoding ADPCM / A-law / mu-law / f64, RIFX output. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Pcm = __include("codecs/audio/Pcm") +local Riff = __include("containers/Riff") +local Codecs = __include("audio/wav/Codecs") +local Adpcm = __include("codecs/audio/Adpcm") + +-- ------------------------------------------------------------------------------------------------ contract +local Wav = { + name = "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/audio/Pcm", "codecs/audio/Adpcm" }, + caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, rf64 = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type Tags = { [string]: string } +type OpenOptions = { + maxBytes: number?, +} +type EncodeOptions = { + sampleFormat: ("u8" | "s16" | "s24" | "s32" | "f32")?, -- default "s16" + rf64: (boolean | "auto")?, -- default "auto": RF64 only when the file passes 4 GiB + extensible: boolean?, -- force (true) or forbid (false) WAVE_FORMAT_EXTENSIBLE; default as ffmpeg + channelMask: number?, -- the EXTENSIBLE speaker mask (default: ffmpeg's default layout for the channel count) + tags: Tags?, -- default: the Audio's tags + rf64Threshold: number?, -- testing: the RIFF size past which "auto" switches to RF64 (default 0xFFFFFFFF) +} + +-- ------------------------------------------------------------------------------------------------ constants +Wav.FORMAT_PCM = 1 +Wav.FORMAT_MS_ADPCM = 2 +Wav.FORMAT_FLOAT = 3 +Wav.FORMAT_ALAW = 6 +Wav.FORMAT_MULAW = 7 +Wav.FORMAT_IMA_ADPCM = 0x11 +Wav.FORMAT_EXTENSIBLE = 0xFFFE + +local FORMAT_NAMES = { + [1] = "pcm", + [2] = "ms_adpcm", + [3] = "float", + [6] = "alaw", + [7] = "mulaw", + [0x11] = "ima_adpcm", +} + +-- LIST/INFO ids -> tag names +local INFO_TAGS = { + INAM = "title", + IART = "artist", + IPRD = "album", + ICMT = "comment", + ICRD = "date", + IGNR = "genre", + ITRK = "track", + IPRT = "track", + ISFT = "encoder", + ICOP = "copyright", + IENG = "engineer", + ISBJ = "subject", + IKEY = "keywords", +} + +-- A-law / mu-law -> f32 tables (G.711, as ffmpeg's alaw2linear / ulaw2linear) +local ALAW, MULAW = buffer.create(1024), buffer.create(1024) +do + for i = 0, 255 do + local a = bit32.bxor(i, 0x55) + local t = bit32.band(a, 15) + local seg = bit32.rshift(bit32.band(a, 0x70), 4) + if seg > 0 then + t = bit32.lshift(t * 2 + 1 + 32, seg + 2) + else + t = bit32.lshift(t * 2 + 1, 3) + end + if bit32.band(a, 0x80) == 0 then + t = -t + end + buffer.writef32(ALAW, i * 4, t / 32768) + local u = bit32.band(bit32.bnot(i), 255) + local m = bit32.lshift(bit32.lshift(bit32.band(u, 15), 3) + 0x84, bit32.rshift(bit32.band(u, 0x70), 4)) + local v = if bit32.band(u, 0x80) ~= 0 then 0x84 - m else m - 0x84 + buffer.writef32(MULAW, i * 4, v / 32768) + end +end + +local Decoder = {} +Decoder.__index = Decoder + +type Decoder = typeof(setmetatable( + {} :: { + sampleRate: number, + channels: number, + frames: number, + duration: number, + bitrate: number, + tags: Tags, + format: string, + formatTag: number, + bitsPerSample: number, + blockAlign: number, + container: string, + dataOffset: number, + dataSize: number, + truncated: boolean, + channelMask: number?, + validBits: number?, + _buf: buffer, + _pos: number, + _be: boolean, + _bytes: number, + _kind: string, + _spb: number, + _cache: buffer?, + _cacheBlock: number, + _cacheFrames: number, + _coefs: buffer?, + _ncoef: number, + _state: buffer?, + _tmp: buffer, + }, + Decoder +)) + +local function trimTag(s: string): string + local e = #s + while e > 0 do + local c = string.byte(s, e) + if c ~= 0 and c ~= 32 then + break + end + e -= 1 + end + local z = string.find(s, "\0", 1, true) + if z and z <= e then + e = z - 1 + end + return string.sub(s, 1, e) +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Wav.sniff(r: Bytes.Reader): number + return if Riff.sniff(r) == "WAVE" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Wav.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?) + local dec, err = Wav.open(r, opts) + if not dec then + return nil, err + end + return Pcm.drain(dec, { + format = "wav", + codec = dec.format, + bitDepth = dec.bitsPerSample, + container = dec.container, + channelMask = dec.channelMask, + truncated = dec.truncated, + }) +end + +-- ------------------------------------------------------------------------------------------------ encode +local SAMPLE_BYTES = { u8 = 1, s16 = 2, s24 = 3, s32 = 4, f32 = 4 } +-- ffmpeg's default speaker masks per channel count (av_channel_layout_default) +local MASKS = { [1] = 0x4, [2] = 0x3, [3] = 0xB, [4] = 0x107, [5] = 0x37, [6] = 0x3F, [7] = 0x70F, [8] = 0x63F } +local GUID_TAIL = "\0\0\0\0\16\0\128\0\0\170\0\56\155\113" -- KSDATAFORMAT_SUBTYPE_* after the 2-byte format tag +-- tags -> LIST/INFO ids (the first id per name) +local TAG_IDS = { title = "INAM", artist = "IART", album = "IPRD", comment = "ICMT", date = "ICRD", genre = "IGNR", track = "ITRK", encoder = "ISFT", copyright = "ICOP", engineer = "IENG", subject = "ISBJ", keywords = "IKEY" } +local BLOCK = 65536 -- frames per data piece when streaming a Decoder + +local function encodeParts(value: any, opts: EncodeOptions?, asParts: boolean): (any, Err.Err?) + if type(value) ~= "table" then + return nil, Err.new(Err.ARG, "encode: needs an Audio or a Decoder") + end + local o: EncodeOptions = opts or {} + local kind = o.sampleFormat or "s16" + local bytes: number? = SAMPLE_BYTES[kind] + if not bytes then + return nil, Err.new(Err.ARG, "encode: sampleFormat must be u8, s16, s24, s32 or f32") + end + local rate: number, ch: number = value.sampleRate, value.channels + if type(rate) ~= "number" or rate < 1 or rate > 4294967295 or rate % 1 ~= 0 then + return nil, Err.new(Err.ARG, "encode: bad sample rate") + end + if type(ch) ~= "number" or ch < 1 or ch > 65535 or ch % 1 ~= 0 then + return nil, Err.new(Err.ARG, "encode: bad channel count") + end + local isAudio = type(value.samples) == "buffer" + if not isAudio and type(value.read) ~= "function" then + return nil, Err.new(Err.ARG, "encode: needs an Audio (samples) or a Decoder (read)") + end + local frameBytes = bytes * ch + local pieces: { buffer } = {} + local frames: number = 0 + if isAudio then + frames = (value.frames :: number?) or (buffer.len(value.samples) // (ch * 4)) + if type(frames) ~= "number" or frames < 0 or buffer.len(value.samples) < frames * ch * 4 then + return nil, Err.new(Err.ARG, "encode: the samples buffer is shorter than frames * channels") + end + if not asParts and frames * frameBytes > 0x3FFFFF00 then + return nil, Err.new(Err.LIMIT, "encode: over 1 GiB of samples (use Wav.encodeParts)") + end + -- pieces of at most 256 MiB + local per = math.max(1, 0x10000000 // frameBytes) + local f0 = 0 + while f0 < frames do + local n = math.min(per, frames - f0) + local b = buffer.create(n * frameBytes) + Codecs.quantize(value.samples, f0 * ch, b, 0, n * ch, kind) + table.insert(pieces, b) + f0 += n + end + else + local tmp = buffer.create(BLOCK * ch * 4) + while true do + local ok, out, n = pcall(value.read, value, BLOCK, tmp) + if not ok then + return nil, Err.new(Err.ARG, "encode: the decoder failed: " .. tostring(out)) + end + if type(n) ~= "number" or n <= 0 or type(out) ~= "buffer" then + break + end + n = math.min(n, buffer.len(out) // (ch * 4)) + local b = buffer.create(n * frameBytes) + Codecs.quantize(out, 0, b, 0, n * ch, kind) + table.insert(pieces, b) + frames += n + if not asParts and frames * frameBytes > 0x3FFFFF00 then + return nil, Err.new(Err.LIMIT, "encode: over 1 GiB of samples (use Wav.encodeParts)") + end + end + end + local dataSize = frames * frameBytes + local bits = bytes * 8 + local float = kind == "f32" + local tag = if float then 3 else 1 + local extensible = ch > 2 or rate > 48000 or (not float and bits > 16) + if o.extensible ~= nil then + extensible = o.extensible + end + local w = Riff.writer("WAVE", { rf64 = if o.rf64 ~= nil then o.rf64 else "auto", sampleCount = frames, rf64Threshold = o.rf64Threshold }) + local fmt = Bytes.writer(40) + fmt:u16le(if extensible then 0xFFFE else tag) + fmt:u16le(ch) + fmt:u32le(rate) + fmt:u32le(rate * frameBytes) + fmt:u16le(frameBytes) + fmt:u16le(bits) + if extensible then + fmt:u16le(22) + fmt:u16le(bits) + fmt:u32le(o.channelMask or MASKS[ch] or 0) + fmt:u16le(tag) + fmt:string(GUID_TAIL) + elseif float then + fmt:u16le(0) -- cbSize + end + w:chunk("fmt ", fmt:finish()) + if float then + local fact = Bytes.writer(4) + fact:u32le(if w.rf64 == true or frames > 0xFFFFFFFF then 0xFFFFFFFF else frames) -- RF64: in ds64 (as ffmpeg) + w:chunk("fact", fact:finish()) + end + local tags = o.tags or value.tags + if type(tags) == "table" then + local items = {} + local keys = {} + for k in tags do + if type(k) == "string" then + table.insert(keys, k) + end + end + table.sort(keys) + for _, k in keys do + local v = tags[k] + -- 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 + end + if #items > 0 then + w:list("INFO", items) + end + end + w:chunk("data", pieces) + local _ = dataSize + return w:finish({ parts = asParts }) +end + +function Wav.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + return encodeParts(value, opts, false) +end + +function Wav.encodeParts(value: any, opts: EncodeOptions?): ({ buffer }?, Err.Err?) + return encodeParts(value, opts, true) +end + +-- ------------------------------------------------------------------------------------------------ open +function Wav.open(r: Bytes.Reader, _opts: OpenOptions?): (Decoder?, Err.Err?) + if type(r) == "buffer" or type(r) == "string" then + r = Bytes.reader(if type(r) == "string" then buffer.fromstring(r) else r :: any) + end + local f, ferr = Riff.read(r, { openEnded = { data = true } }) + if not f then + return nil, ferr + end + if f.form ~= "WAVE" then + return nil, Err.new(Err.CORRUPT, "not a WAVE file (" .. f.form .. ")", f.base + 8) + end + local buf = f.buf + local magic = f.container + local be = f.bigEndian + + local fmt: any = nil + local tags: Tags = {} + local dataOff, dataSize = -1, 0 + local truncated = false + local ds64Frames: number? = if f.ds64 and f.ds64.sampleCount > 0 then f.ds64.sampleCount else nil + local factFrames: number? = nil + local function u16(o: number): number + return Riff.u16(f, o) + end + local function u32(o: number): number + return Riff.u32(f, o) + end + local function i16(o: number): number + local v = u16(o) + return if v >= 32768 then v - 65536 else v + end + for _, c in f.chunks do + local id, size, body, avail = c.id, c.size, c.offset, c.avail + if id == "fmt " and avail >= 14 then + fmt = { + tag = u16(body), + channels = u16(body + 2), + rate = u32(body + 4), + byteRate = u32(body + 8), + blockAlign = u16(body + 12), + bits = if avail >= 16 then u16(body + 14) else 8, + body = body, + avail = avail, + } + elseif id == "fact" and avail >= 4 then + factFrames = u32(body) + elseif id == "LIST" and Riff.listType(f, c) == "INFO" then + for _, sc in Riff.list(f, c) do + local name = INFO_TAGS[sc.id] + if sc.avail > 0 then + local v = trimTag(buffer.readstring(buf, sc.offset, sc.avail)) + if v ~= "" then + tags[name or string.lower(sc.id)] = v + end + end + end + elseif id == "data" and dataOff < 0 then + dataOff = body + dataSize = avail + truncated = c.truncated + end + local _ = size + end + + if not fmt then + return nil, Err.new(Err.CORRUPT, "no fmt chunk") + end + if dataOff < 0 then + return nil, Err.new(Err.CORRUPT, "no data chunk") + end + local tag, ch, rate, bits = fmt.tag, fmt.channels, fmt.rate, fmt.bits + local channelMask: number? = nil + local validBits: number? = nil + if tag == 0xFFFE then + if fmt.avail < 40 then + return nil, Err.new(Err.CORRUPT, "WAVE_FORMAT_EXTENSIBLE without its extension") + end + local valid = u16(fmt.body + 18) + channelMask = u32(fmt.body + 20) + tag = u16(fmt.body + 24) -- the GUID's first two bytes are the format tag + -- valid bits < container bits: the samples are left-justified, so decoding the container is right + validBits = valid + end + if ch < 1 or ch > 255 then + return nil, Err.new(Err.CORRUPT, "bad channel count " .. ch) + end + if rate < 1 or rate > 4000000 then + return nil, Err.new(Err.CORRUPT, "bad sample rate " .. rate) + end + local name: string? = FORMAT_NAMES[tag] + if not name then + return nil, Err.new(Err.UNSUPPORTED, string.format("format 0x%04X", tag)) + end + + local dec = setmetatable({}, Decoder) :: any + dec.sampleRate = rate + dec.channels = ch + dec.tags = tags + dec.format = name + dec.formatTag = tag + dec.bitsPerSample = bits + dec.container = magic + dec.dataOffset = dataOff + dec.dataSize = dataSize + dec.channelMask = channelMask + dec._buf = buf + dec._pos = 0 + dec._be = be + dec._tmp = buffer.create(8) + dec._cacheBlock = -1 + dec._cacheFrames = 0 + dec._ncoef = 0 + + local blockAlign: number = fmt.blockAlign + local frames: number + if name == "pcm" or name == "float" or name == "alaw" or name == "mulaw" then + local bytes + if name == "alaw" or name == "mulaw" then + bytes = 1 + elseif name == "float" then + if bits ~= 32 and bits ~= 64 then + return nil, Err.new(Err.UNSUPPORTED, "float size " .. bits) + end + bytes = bits // 8 + else + if bits < 1 or bits > 32 then + return nil, Err.new(Err.UNSUPPORTED, "PCM size " .. bits) + end + -- container: from blockAlign when it is consistent, else from the bit depth + bytes = (bits + 7) // 8 + if blockAlign >= ch and blockAlign % ch == 0 and blockAlign // ch >= bytes and blockAlign // ch <= 4 then + bytes = blockAlign // ch + end + end + blockAlign = bytes * ch + dec._bytes = bytes + dec._kind = name + frames = dataSize // blockAlign + dec._spb = 1 + elseif name == "ima_adpcm" or name == "ms_adpcm" then + if blockAlign < 1 then + return nil, Err.new(Err.CORRUPT, "ADPCM with blockAlign 0") + end + local spb = if fmt.avail >= 20 then u16(fmt.body + 18) else 0 + if name == "ima_adpcm" then + if bits ~= 4 then + return nil, Err.new(Err.UNSUPPORTED, "IMA ADPCM size " .. bits) + end + if blockAlign < 4 * ch then + return nil, Err.new(Err.CORRUPT, "IMA ADPCM block too small") + end + local computed = (blockAlign - 4 * ch) * 2 // ch + 1 + if spb < 1 or spb > computed then + spb = computed + end + else + if blockAlign < 7 * ch then + return nil, Err.new(Err.CORRUPT, "MS ADPCM block too small") + end + local computed = (blockAlign - 7 * ch) * 2 // ch + 2 + if spb < 2 or spb > computed then + spb = computed + end + -- coefficients from the fmt extension, else the 7 standard pairs + local c1, c2 = Adpcm.MS_COEF1, Adpcm.MS_COEF2 + local ncoef = 7 + if fmt.avail >= 22 then + local k = u16(fmt.body + 20) + if k >= 1 and k <= 256 and fmt.avail >= 22 + 4 * k then + ncoef = k + c1, c2 = {}, {} + for i = 1, k do + c1[i] = i16(fmt.body + 22 + (i - 1) * 4) + c2[i] = i16(fmt.body + 24 + (i - 1) * 4) + end + end + end + local coefs = buffer.create(ncoef * 8) + for i = 1, ncoef do + buffer.writei32(coefs, (i - 1) * 8, c1[i]) + buffer.writei32(coefs, (i - 1) * 8 + 4, c2[i]) + end + dec._coefs = coefs + dec._ncoef = ncoef + dec._state = buffer.create(20 * ch) + end + if spb * ch > 2 ^ 20 then + return nil, Err.new(Err.LIMIT, "ADPCM block too large") + end + dec._kind = name + dec._spb = spb + dec._cache = buffer.create(spb * ch * 4) + local full = dataSize // blockAlign + frames = full * spb + local rest = dataSize - full * blockAlign + if rest > 0 then + -- a partial last block: the frames it holds whole + if name == "ima_adpcm" then + if rest >= 4 * ch then + frames += math.min(spb, 1 + ((rest - 4 * ch) // (4 * ch)) * 8) + end + elseif rest >= 7 * ch then + frames += math.min(spb, 2 + ((rest - 7 * ch) * 2) // ch) + end + end + -- fact: the true length (the last block is padded) + if factFrames and factFrames > 0 and factFrames < frames then + frames = factFrames + end + else + return nil, Err.new(Err.UNSUPPORTED, "format " .. name) + end + if ds64Frames and ds64Frames > 0 and ds64Frames < frames then + frames = ds64Frames + end + dec.blockAlign = blockAlign + dec.frames = frames + dec.duration = frames / rate + dec.truncated = truncated + dec.validBits = validBits + dec.bitrate = if fmt.byteRate > 0 then fmt.byteRate * 8 else math.floor(rate * blockAlign * 8 / dec._spb) + return dec, nil +end + +-- ------------------------------------------------------------------------------------------------ extras +function Decoder.read(self: Decoder, maxFrames: number, out: buffer?): (buffer, number) + local ch = self.channels + local req = math.floor(tonumber(maxFrames) or 0) + if req ~= req then -- NaN (math.min / max treat it differently on LuaJIT) + req = 0 + end + local want = math.max(0, math.min(req, self.frames - self._pos)) + local dst: buffer = if out and type(out) == "buffer" and buffer.len(out) >= want * ch * 4 + then out + else buffer.create(want * ch * 4) + if want == 0 then + return dst, 0 + end + local kind = self._kind + if self._spb == 1 then + local off = self.dataOffset + self._pos * self.blockAlign + local count = want * ch + if kind == "pcm" then + Codecs.int(self._buf, off, dst, 0, count, self._bytes, self._be) + elseif kind == "float" then + Codecs.float(self._buf, off, dst, 0, count, self._bytes, self._be, self._tmp) + elseif kind == "alaw" then + Codecs.law(self._buf, off, dst, 0, count, ALAW) + else + Codecs.law(self._buf, off, dst, 0, count, MULAW) + end + self._pos += want + return dst, want + end + local spb, ba = self._spb, self.blockAlign + local cache = self._cache :: buffer + local done = 0 + while done < want do + local block = self._pos // spb + if block ~= self._cacheBlock then + local off = self.dataOffset + block * ba + local avail = math.min(ba, self.dataOffset + self.dataSize - off) + local got + if kind == "ima_adpcm" then + got = Adpcm.imaWav(self._buf, off, avail, ch, spb, cache, 0) + else + got = Adpcm.msBlock(self._buf, off, avail, ch, spb, cache, 0, self._coefs :: buffer, self._ncoef, + self._state :: buffer) + end + self._cacheBlock = block + self._cacheFrames = got + end + local inBlock = self._pos - block * spb + local k = math.min(want - done, self._cacheFrames - inBlock) + if k <= 0 then + break + end + Codecs.copy(cache, inBlock * ch, dst, done * ch, k * ch) + done += k + self._pos += k + end + return dst, done +end + +function Decoder.seek(self: Decoder, seconds: number) + local f = math.floor((tonumber(seconds) or 0) * self.sampleRate + 0.5) + if f ~= f then + f = 0 + end + self._pos = math.clamp(f, 0, self.frames) +end + +function Decoder.seekFrame(self: Decoder, frame: number) + local f = math.floor(tonumber(frame) or 0) + if f ~= f then + f = 0 + end + self._pos = math.clamp(f, 0, self.frames) +end + +function Decoder.position(self: Decoder): number + return self._pos / self.sampleRate +end + +function Decoder.tell(self: Decoder): number + return self._pos +end + +return Wav +end +__FILES["audio/wav/Codecs"] = @native function() + + + +-- audio/wav/Codecs: PCM / float / G.711 sample loops into interleaved f32 and back; absorbed from wav-luau fd9a909. +local readu8, readi8, readu16, readi16, readu32, readi32 = + buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.readi32 +local readf32, readf64, writef32, writeu32 = buffer.readf32, buffer.readf64, buffer.writef32, buffer.writeu32 +local band, rshift, byteswap = bit32.band, bit32.rshift, bit32.byteswap +local writeu8, writeu16, writei16, writei32 = buffer.writeu8, buffer.writeu16, buffer.writei16, buffer.writei32 + +local Codecs = {} + +-- integer PCM: 1 byte = unsigned, 2 / 3 / 4 bytes = signed +@native function Codecs.int(src: buffer, off: number, dst: buffer, d: number, count: number, bytes: number, be: boolean) + local o = d * 4 + if bytes == 1 then + for i = 0, count - 1 do + writef32(dst, o + i * 4, (readu8(src, off + i) - 128) / 128) + end + elseif bytes == 2 then + if be then + for i = 0, count - 1 do + local s = off + i * 2 + local v = readi8(src, s) * 256 + readu8(src, s + 1) + writef32(dst, o + i * 4, v / 32768) + end + else + for i = 0, count - 1 do + writef32(dst, o + i * 4, readi16(src, off + i * 2) / 32768) + end + end + elseif bytes == 3 then + if be then + for i = 0, count - 1 do + local s = off + i * 3 + local v = readi8(src, s) * 65536 + readu8(src, s + 1) * 256 + readu8(src, s + 2) + writef32(dst, o + i * 4, v / 8388608) + end + else + for i = 0, count - 1 do + local s = off + i * 3 + local v = readi8(src, s + 2) * 65536 + readu16(src, s) + writef32(dst, o + i * 4, v / 8388608) + end + end + else + if be then + for i = 0, count - 1 do + local v = byteswap(readu32(src, off + i * 4)) + if v >= 0x80000000 then + v -= 0x100000000 + end + writef32(dst, o + i * 4, v / 2147483648) + end + else + for i = 0, count - 1 do + writef32(dst, o + i * 4, readi32(src, off + i * 4) / 2147483648) + end + end + end +end + +@native function Codecs.float(src: buffer, off: number, dst: buffer, d: number, count: number, bytes: number, be: boolean, + tmp: buffer) + local o = d * 4 + if bytes == 4 then + if be then + for i = 0, count - 1 do + writeu32(tmp, 0, byteswap(readu32(src, off + i * 4))) + writef32(dst, o + i * 4, readf32(tmp, 0)) + end + else + for i = 0, count - 1 do + writef32(dst, o + i * 4, readf32(src, off + i * 4)) + end + end + else + if be then + for i = 0, count - 1 do + local s = off + i * 8 + writeu32(tmp, 0, byteswap(readu32(src, s + 4))) + writeu32(tmp, 4, byteswap(readu32(src, s))) + writef32(dst, o + i * 4, readf64(tmp, 0)) + end + else + for i = 0, count - 1 do + writef32(dst, o + i * 4, readf64(src, off + i * 8)) + end + end + end +end + +@native function Codecs.law(src: buffer, off: number, dst: buffer, d: number, count: number, tbl: buffer) + local o = d * 4 + for i = 0, count - 1 do + writef32(dst, o + i * 4, readf32(tbl, readu8(src, off + i) * 4)) + end +end + +@native function Codecs.copy(src: buffer, sOff: number, dst: buffer, dOff: number, count: number) + buffer.copy(dst, dOff * 4, src, sOff * 4, count * 4) +end + +@native function Codecs.quantize(src: buffer, s: number, dst: buffer, off: number, count: number, kind: string) + local so = s * 4 + if kind == "f32" then + buffer.copy(dst, off, src, so, count * 4) + elseif kind == "s16" then + for i = 0, count - 1 do + local v = math.floor(readf32(src, so + i * 4) * 32768 + 0.5) + if v > 32767 then + v = 32767 + elseif v < -32768 then + v = -32768 + elseif v ~= v then + v = 0 + end + writei16(dst, off + i * 2, v) + end + elseif kind == "s24" then + for i = 0, count - 1 do + local v = math.floor(readf32(src, so + i * 4) * 8388608 + 0.5) + if v > 8388607 then + v = 8388607 + elseif v < -8388608 then + v = -8388608 + elseif v ~= v then + v = 0 + end + if v < 0 then + v += 16777216 + end + local o = off + i * 3 + writeu16(dst, o, v % 65536) + writeu8(dst, o + 2, v // 65536) + end + elseif kind == "s32" then + for i = 0, count - 1 do + local v = math.floor(readf32(src, so + i * 4) * 2147483648 + 0.5) + if v > 2147483647 then + v = 2147483647 + elseif v < -2147483648 then + v = -2147483648 + elseif v ~= v then + v = 0 + end + writei32(dst, off + i * 4, v) + end + else -- u8 + for i = 0, count - 1 do + local v = math.floor(readf32(src, so + i * 4) * 128 + 0.5) + if v > 127 then + v = 127 + elseif v < -128 then + v = -128 + elseif v ~= v then + v = 0 + end + writeu8(dst, off + i, v + 128) + end + end +end + +return Codecs +end +__FILES["audio/wavpack"] = function() + +-- audio/wavpack: WavPack (.wv) via codecs/audio/WavPack, from the WavPack 5 file format document and WavPack 5.9.0's +-- open_utils.c (BSD 3-clause, licenses/wavpack-LICENSE.txt). Supports: lossless and hybrid (lossy without the .wvc, as +-- wvunpack), 8-32-bit integer and float, 1-4096 channels, seeking, APEv2. Not supported: DSD, WavPack 1-3, encoding. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Pcm = __include("codecs/audio/Pcm") +local Stream = __include("codecs/audio/Stream") +local ApeTag = __include("codecs/audio/ApeTag") +local WavPackCodec = __include("codecs/audio/WavPack") + +-- ------------------------------------------------------------------------------------------------ contract +local WavPack = { + name = "wavpack", + category = "audio", + extensions = { "wv" }, + mime = { "audio/x-wavpack", "audio/wavpack" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/WavPack" }, + caps = { decode = true, encode = false, streaming = true, seek = true, lossless = true, hybrid = true, float = true, depths = { 8, 12, 16, 20, 24, 32 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type OpenOptions = { + correction: (buffer | string)?, -- the .wvc file of a hybrid file (default: opts.resolve(name .. "c") when given) + resolve: ((uri: string) -> buffer?)?, + name: string?, + maxFrames: number?, -- default 2^28 +} + +-- ------------------------------------------------------------------------------------------------ sniff +function WavPack.sniff(r: Bytes.Reader): number + if r:peek(4) ~= "wvpk" then + return 0 + end + local v = r:peekU8(9) + return if v == 4 then 1 else 0.5 +end + +-- ------------------------------------------------------------------------------------------------ decode +function WavPack.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?) + local dec, err = WavPack.open(r, opts) + if not dec then + return nil, err + end + local d = dec :: any + local limit = opts and opts.maxFrames or 2 ^ 28 + 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 + return Pcm.drain(d, d.source, limit) +end + +-- ------------------------------------------------------------------------------------------------ open +type Index = { offsets: { { number } }, starts: { number }, samples: { number }, total: number, first: number, md5: string? } + +local function index(buf: buffer, base: number, limit: number): (Index?, string?) + local at = base + local idx: Index = { offsets = {}, starts = {}, samples = {}, total = -1, first = -1 } + local cur: { number }? = nil + local initial = -1 + local resyncs = 0 + while at + 32 <= limit do + local h = WavPackCodec.header(buf, at, limit) + if not h then + -- garbage (or a tag) between blocks: search the next header + if resyncs > 64 then + break + end + local s = buffer.readstring(buf, at + 1, math.min(limit - at - 1, 1048576)) + local k = string.find(s, "wvpk", 1, true) + if not k then + break + end + at = at + k + resyncs += 1 + continue + end + if initial < 0 then + initial = h.index + idx.total = h.total + end + if h.samples > 0 then + if bit32.band(h.flags, WavPackCodec.INITIAL) ~= 0 or not cur then + cur = { at } + table.insert(idx.offsets, cur) + table.insert(idx.starts, h.index - initial) + table.insert(idx.samples, h.samples) + if idx.first < 0 then + idx.first = at + end + else + table.insert(cur, at) + end + if bit32.band(h.flags, WavPackCodec.FINAL) ~= 0 then + cur = nil + end + else + idx.md5 = idx.md5 or WavPackCodec.md5(buf, at, limit) + end + at += h.size + end + if idx.first < 0 then + return nil, "no audio blocks" + end + return idx, nil +end + +local function correctionFile(opts: OpenOptions?): buffer? + if not opts then + return nil + end + local c = opts.correction + if type(c) == "string" then + return buffer.fromstring(c) + elseif type(c) == "buffer" then + return c + end + if type(opts.resolve) == "function" and type(opts.name) == "string" then + local base = string.match(opts.name, "([^/\\]+)$") + if base then + local ok, b = pcall(opts.resolve, base .. "c") + if ok and type(b) == "buffer" then + return b + end + end + end + return nil +end + +function WavPack.open(r: Bytes.Reader, opts: OpenOptions?): (Types.Decoder?, Err.Err?) + if type(r) == "buffer" then + r = Bytes.reader(r :: any) + end + if type(r) ~= "table" or type(r.buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "open: expected a Reader") + end + local buf, base, limit = r.buf, r.base, r.limit + local tags, tagInfo = ApeTag.find(buf, base, limit) + local stop = if tagInfo then tagInfo.start else limit + local idx, ierr = index(buf, base, stop) + if not idx then + return nil, Err.from(ierr, base) + end + local info, err = WavPackCodec.info(buf, idx.first, stop) + if not info then + return nil, err + end + if info.channels > 256 then + return nil, Err.new(Err.LIMIT, info.channels .. " channels") + end + local count = #idx.offsets + local last = idx.starts[count] + idx.samples[count] + local frames = if idx.total >= 0 then math.min(idx.total, last) else last + local cbuf = if info.hybrid then correctionFile(opts) else nil + local cfor: { [number]: { number } } = {} + if cbuf then + local cidx = index(cbuf, 0, buffer.len(cbuf)) + if cidx then + for i, offs in cidx.offsets do + cfor[cidx.starts[i]] = offs + end + else + cbuf = nil + end + end + local codec = WavPackCodec.decoder(info.channels) + local dec: any = { + sampleRate = info.sampleRate, + channels = info.channels, + frames = frames, + duration = frames / info.sampleRate, + bitrate = if frames > 0 then math.floor((stop - base) * 8 * info.sampleRate / frames) else 0, + tags = tags or {}, + bitsPerSample = info.bitsPerSample, + float = info.float, + hybrid = info.hybrid, + lossless = not info.hybrid or cbuf ~= nil, + channelMask = info.channelMask, + md5 = idx.md5, + source = { format = "wavpack", bitDepth = info.bitsPerSample, float = info.float, hybrid = info.hybrid, correction = cbuf ~= nil, version = info.version, tags = tagInfo and tagInfo.items }, + } + local starts, offsets = idx.starts, idx.offsets + return Stream.packets(dec, { + count = count, + start = function(i: number): number + return if i > count then last else starts[i] + end, + decode = function(i: number): (number?, Err.Err?) + local co = if cbuf then cfor[starts[i]] else nil + return codec:frame(buf, offsets[i], if co then cbuf else nil, co) + end, + pcm = function(): { number } + return codec.pcm + end, + reset = function() end, + stop = frames, + scale = if info.float then 1 else 1 / 2 ^ (info.bytesPerSample * 8 - 1), + ints = not info.float, + }) +end + +return WavPack +end +end + + + + + + cad + --!optimize 2 +--!nocheck +-- rosetta chunk cad (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 4 modules (2 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["cad/step"] = function() + +-- cad/step: STEP physical files (ISO 10303-21 eds 1-3; AP203 / AP214 / AP242 / any schema). Supports: header, DATA +-- sections, simple and complex instances, every parameter kind, ANCHOR / REFERENCE / SIGNATURE kept raw; B-rep via the +-- injected plug-in (cad/step/Brep). Not supported: STEP-XML (10303-28), .stpZ, ed. 3 value instances, \P?\ code pages. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Sniff = __include("core/Sniff") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Parse = __include("cad/step/Parse") +local Write = __include("cad/step/Write") +local Brep = __include("cad/step/Brep") + +-- ------------------------------------------------------------------------------------------------ contract +local Step = { + name = "step", + category = "cad", + extensions = { "step", "stp", "p21" }, + mime = { "model/step", "application/step", "application/p21" }, + deps = { "core/Err", "core/Bytes", "Types", "core/Sniff" }, + caps = { decode = true, encode = true, complexEntities = true, sections = true, brep = "plugin", tessellate = "plugin" }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + maxBytes: number?, -- default 2^30 + maxEntities: number?, -- default 2^24 +} +type EncodeOptions = { + schema: string?, -- overrides the header's FILE_SCHEMA + name: string?, -- default: the header's, else "model" + timestamp: string?, -- default "1970-01-01T00:00:00" + crlf: boolean?, +} +type BrepOptions = { + brep: any?, + plugins: { [string]: any }?, + chord: number?, -- millimetres (default 0.05) + tess: { [string]: any }?, +} + +-- ------------------------------------------------------------------------------------------------ constants +Step.NULL = table.freeze({ null = true }) -- $ +Step.DERIVED = table.freeze({ derived = true }) -- * + +local SCHEMAS = { + AP203 = "CONFIG_CONTROL_DESIGN", + AP214 = "AUTOMOTIVE_DESIGN { 1 0 10303 214 1 1 1 1 }", + AP242 = "AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF { 1 0 10303 442 1 1 4 }", +} +Step.SCHEMAS = SCHEMAS + +local function schemaOf(name: string): string + local n = string.upper(string.match(name, "^%s*([^%s{]+)") or name) + if n == "CONFIG_CONTROL_DESIGN" or string.find(n, "^AP203") then + return "AP203" + elseif n == "AUTOMOTIVE_DESIGN" or n == "AUTOMOTIVE_DESIGN_CC2" or string.find(n, "^AP214") then + return "AP214" + elseif string.find(n, "^AP242") then + return "AP242" + end + return n +end +Step.schemaOf = schemaOf + +-- ------------------------------------------------------------------------------------------------ sniff +function Step.sniff(r: Bytes.Reader): number + local head = Sniff.text(r, 256) + head = string.gsub(head, "^%s*/%*.-%*/", "") + if string.find(head, "^%s*ISO%-10303%-21%s*;") then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Step.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Cad?, Err.Err?) + local size = r.limit - r.base + if size > (opts and opts.maxBytes or 2 ^ 30) then + return nil, Err.new(Err.LIMIT, "file over maxBytes") + end + local s = buffer.readstring(r.buf, r.base, size) + local bom = 0 + if string.sub(s, 1, 3) == "\239\187\191" then + s = string.sub(s, 4) + bom = 3 + end + local res, msg, at = Parse.parse(s, Step.NULL, Step.DERIVED, opts and opts.maxEntities or 2 ^ 24) + if not res then + local off = if at then r.base + bom + at - 1 else nil + if msg == "LIMIT" then + return nil, Err.new(Err.LIMIT, "more entity instances than maxEntities", off) + end + local m = msg or "parse error" + if string.find(m, "^truncated") or string.find(m, "^unterminated") or (at and at > #s) then + return nil, Err.new(Err.TRUNCATED, m, off) + end + return nil, Err.new(Err.CORRUPT, m, off) + end + local fs = res.header.FILE_SCHEMA + local schemaName = if fs and type(fs[1]) == "table" and type(fs[1][1]) == "string" then fs[1][1] else "" + local cad: Types.Cad = { + kind = "cad", + schema = if schemaName ~= "" then schemaOf(schemaName) else "unknown", + header = res.header, + entities = res.entities, + meta = { + count = res.count, + headerOrder = res.headerOrder, + source = { + format = "step", + schemaName = schemaName, + sections = res.sections, + extra = if #res.extra > 0 then res.extra else nil, + duplicates = if res.duplicates > 0 then res.duplicates else nil, + terminated = res.terminated, + }, + }, + } + return cad, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function headerArgs(cad: Types.Cad, o: EncodeOptions): { [string]: { any } } + local h = if type(cad.header) == "table" then cad.header else {} + local out: { [string]: { any } } = {} + for k, v in h do + out[k] = v + end + if type(out.FILE_DESCRIPTION) ~= "table" then + out.FILE_DESCRIPTION = { { "rosetta" }, "2;1" } + end + if type(out.FILE_NAME) ~= "table" then + out.FILE_NAME = { o.name or "model", o.timestamp or "1970-01-01T00:00:00", { "" }, { "" }, "rosetta", "rosetta", "" } + end + local schema = o.schema or (if type(out.FILE_SCHEMA) ~= "table" then cad.schema else nil) + if schema then + out.FILE_SCHEMA = { { SCHEMAS[schema] or schema } } + end + return out +end + +function Step.encode(cad: Types.Cad, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(cad) ~= "table" or cad.kind ~= "cad" or type(cad.entities) ~= "table" then + return nil, Err.new(Err.ARG, "needs a Cad (kind = \"cad\", entities)") + end + local o: EncodeOptions = opts or {} + local nl = if o.crlf then "\r\n" else "\n" + local ctx: Write.Ctx = { out = {}, null = Step.NULL, derived = Step.DERIVED, err = nil } + local out = ctx.out + table.insert(out, "ISO-10303-21;" .. nl .. "HEADER;" .. nl) + local header = headerArgs(cad, o) + local order = { "FILE_DESCRIPTION", "FILE_NAME", "FILE_SCHEMA" } + local seen = { FILE_DESCRIPTION = true, FILE_NAME = true, FILE_SCHEMA = true } + local meta: any = if type(cad.meta) == "table" then cad.meta else {} + local rest = {} + for _, k in (if type(meta.headerOrder) == "table" then meta.headerOrder else {}) do + if type(k) == "string" and header[k] and not seen[k] then + seen[k] = true + table.insert(order, k) + end + end + for k in header do + if type(k) == "string" and not seen[k] then + table.insert(rest, k) + end + end + table.sort(rest) + for _, k in rest do + table.insert(order, k) + end + for _, k in order do + if not Write.record(ctx, k, header[k]) then + return nil, Err.new(Err.ARG, "header " .. tostring(k) .. ": " .. tostring(ctx.err)) + end + table.insert(out, ";" .. nl) + end + table.insert(out, "ENDSEC;" .. nl) + local source = if type(meta.source) == "table" then meta.source else {} + if type(source.extra) == "table" then + for _, x in source.extra do + if type(x) == "table" and type(x.name) == "string" and type(x.text) == "string" then + table.insert(out, x.name .. x.text .. "ENDSEC;" .. nl) + end + end + end + local ids = {} + for id, e in cad.entities do + if type(id) ~= "number" or id ~= math.floor(id) or id < 0 or type(e) ~= "table" then + return nil, Err.new(Err.ARG, "entity ids must be non-negative integers (" .. tostring(id) .. ")") + end + table.insert(ids, id) + end + table.sort(ids) + local sections = if type(source.sections) == "table" and #source.sections > 1 then source.sections else { {} } + for si, sec in sections do + if #sections > 1 then + table.insert(out, "DATA") + local params = {} + if sec.name ~= nil then + params[1] = sec.name + params[2] = if sec.schema ~= nil then sec.schema else {} + if not Write.list(ctx, params, 0) then + return nil, Err.new(Err.ARG, "section " .. si .. ": " .. tostring(ctx.err)) + end + end + table.insert(out, ";" .. nl) + else + table.insert(out, "DATA;" .. nl) + end + for _, id in ids do + local e: any = cad.entities[id] + local esec = if type(e.section) == "number" then e.section else 1 + if #sections == 1 or esec == si or (si == 1 and (esec < 1 or esec > #sections)) then + table.insert(out, string.format("#%.0f=", id)) + if e.type == "COMPLEX" or type(e.parts) == "table" then + if type(e.parts) ~= "table" or #e.parts == 0 then + return nil, Err.new(Err.ARG, "#" .. id .. ": a complex instance without parts") + end + table.insert(out, "(") + for _, p in e.parts do + if type(p) ~= "table" or not Write.record(ctx, p.type, p.args) then + return nil, Err.new(Err.ARG, "#" .. id .. ": " .. tostring(ctx.err or "bad part")) + end + end + table.insert(out, ")") + elseif not Write.record(ctx, e.type, e.args) then + return nil, Err.new(Err.ARG, "#" .. id .. ": " .. tostring(ctx.err)) + end + table.insert(out, ";" .. nl) + end + end + table.insert(out, "ENDSEC;" .. nl) + end + table.insert(out, "END-ISO-10303-21;" .. nl) + return buffer.fromstring(table.concat(out)), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +function Step.get(cad: Types.Cad, id: any): Types.StepEntity? + if type(id) == "table" then + id = id.ref + end + return cad.entities[id] +end + +function Step.ids(cad: Types.Cad): { number } + local out = {} + for id in cad.entities do + table.insert(out, id) + end + table.sort(out) + return out +end + +function Step.byType(cad: Types.Cad, name: string): { number } + local n = string.upper(name) + local out = {} + for id, e in cad.entities do + if e.type == n then + table.insert(out, id) + elseif e.parts then + for _, p in e.parts do + if p.type == n then + table.insert(out, id) + break + end + end + end + end + table.sort(out) + return out +end + +function Step.part(e: Types.StepEntity?, name: string): { any }? + if not e then + return nil + end + if e.type == name then + return e.args + end + if e.parts then + for _, p in e.parts do + if p.type == name then + return p.args + end + end + end + return nil +end + +function Step.add(cad: Types.Cad, type: string, args: { any }): number + local top = 0 + for id in cad.entities do + if id > top then + top = id + end + end + local id = top + 1 + cad.entities[id] = { id = id, type = string.upper(type), args = args } + cad.meta.count = (cad.meta.count or 0) + 1 + return id +end + +function Step.real(t: { [any]: any }, key: any): { [any]: any } + local mt: any = getmetatable(t) + if not mt then + mt = { __reals = {} } + setmetatable(t, mt) + end + mt.__reals[key] = true + return t +end + +function Step.new(schema: string?): Types.Cad + return { kind = "cad", schema = schema or "AP214", header = {}, entities = {}, meta = { count = 0 } } +end + +Step.plugin = Brep.plugin + +local function textOf(cad: Types.Cad): (string?, Err.Err?) + local buf, err = Step.encode(cad) + if not buf then + return nil, err + end + return buffer.tostring(buf), nil +end + +function Step.toBodies(cad: Types.Cad, opts: BrepOptions?): (({ any })?, any) + local plug, perr = Brep.find(opts) + if not plug then + return nil, perr + end + local text, err = textOf(cad) + if not text then + return nil, err + end + local bodies, res, rerr = Brep.read(plug, text, opts) + if not bodies then + return nil, rerr + end + return bodies, res +end + +function Step.fromBodies(bodies: { any }, opts: BrepOptions?): (Types.Cad?, Err.Err?) + if type(bodies) ~= "table" then + return nil, Err.new(Err.ARG, "needs a list of bodies") + end + local plug, perr = Brep.find(opts) + if not plug then + return nil, perr + end + local text, err = Brep.write(plug, bodies, opts) + if not text then + return nil, err + end + return Step.decode(Bytes.reader(buffer.fromstring(text))) +end + +function Step.tessellate(value: any, opts: BrepOptions?): (Types.Scene?, Err.Err?) + local plug, perr = Brep.find(opts) + if not plug then + return nil, perr + end + local bodies = value + if type(value) == "table" and value.kind == "cad" then + local b, err = Step.toBodies(value, opts) + if not b then + return nil, err + end + bodies = b + end + if type(bodies) ~= "table" then + return nil, Err.new(Err.ARG, "needs a Cad or a list of bodies") + end + return Brep.scene(plug, bodies, opts) +end + +return Step +end +__FILES["cad/step/Brep"] = function() + +-- cad/step/Brep: the injected B-rep plug-in (Rosetta.plugins.brep; never required by rosetta), called under pcall. +-- Interface (each may throw): read(text, opts) -> { bodies, stats? }; write(bodies, opts) -> text; +-- tessellate(body, opts) -> { positions, normals?, indices (1-based triples), faceOf? }; or brep-luau's modules as-is. +local Err = __include("core/Err") +local Types = __include("Types") + +local Brep = {} + +type Plugin = { + read: (text: string, opts: any) -> any, + write: ((bodies: { any }, opts: any) -> string)?, + tessellate: ((body: any, opts: any) -> any)?, +} + +local function rgbOf(c: any): (number?, number?, number?) + if c == nil then + return nil, nil, nil + end + local ok, r, g, b = pcall(function(): (any, any, any) + if type(c) == "table" then + return c.r or c.R or c[1], c.g or c.G or c[2], c.b or c.B or c[3] + end + return (c :: any).R, (c :: any).G, (c :: any).B + end) + if ok and type(r) == "number" and type(g) == "number" and type(b) == "number" then + return r, g, b + end + return nil, nil, nil +end + +function Brep.plugin(p: any): (Plugin?, string?) + if type(p) ~= "table" then + return nil, "needs the B-rep plug-in (Rosetta.plugins.brep = { read, write, tessellate }, e.g. brep-luau's { Step, StepBrep, StepWrite, Tess })" + end + if type(p.read) == "function" then + return { + read = p.read, + write = if type(p.write) == "function" then p.write else nil, + tessellate = if type(p.tessellate) == "function" then p.tessellate else nil, + }, nil + end + local S, SB, SW, Tess = p.Step, p.StepBrep, p.StepWrite, p.Tess + if type(S) == "table" and type(SB) == "table" and type(S.parse) == "function" and type(SB.read) == "function" then + return { + read = function(text: string, opts: any): any + return SB.read(S.parse(text), opts) + end, + write = if type(SW) == "table" and type(SW.write) == "function" + then function(bodies: { any }, opts: any): string + local o = if type(opts) == "table" then table.clone(opts) else {} + if o.colors == nil then + local colors = {} + for i, b in bodies do + local r, g, bl = rgbOf(type(b) == "table" and b.color or nil) + if r then + colors[i] = { r, g, bl } + end + end + o.colors = colors + end + return SW.write(bodies, o) + end + else nil, + tessellate = if type(Tess) == "table" and type(Tess.body) == "function" + then function(body: any, opts: any): any + return Tess.body(body, opts) + end + else nil, + }, nil + end + return nil, "the B-rep plug-in has neither read() nor brep-luau's Step + StepBrep modules" +end + +function Brep.find(opts: any): (Plugin?, Err.Err?) + local p = nil + if type(opts) == "table" then + p = opts.brep + if p == nil and type(opts.plugins) == "table" then + p = opts.plugins.brep + end + end + local plug, why = Brep.plugin(p) + if not plug then + return nil, Err.new(Err.UNSUPPORTED, why :: string) + end + return plug, nil +end + +function Brep.read(plug: Plugin, text: string, opts: any): (({ any })?, any, Err.Err?) + local ok, res = pcall(plug.read, text, opts) + if not ok then + return nil, nil, Err.new(Err.CORRUPT, "the B-rep plug-in failed to read: " .. tostring(res)) + end + if type(res) ~= "table" or type(res.bodies) ~= "table" then + return nil, nil, Err.new(Err.CORRUPT, "the B-rep plug-in's read returned no bodies") + end + return res.bodies, res, nil +end + +function Brep.write(plug: Plugin, bodies: { any }, opts: any): (string?, Err.Err?) + local w = plug.write + if not w then + return nil, Err.new(Err.UNSUPPORTED, "the B-rep plug-in has no write()") + end + local ok, res = pcall(w, bodies, opts) + if not ok then + return nil, Err.new(Err.ARG, "the B-rep plug-in failed to write: " .. tostring(res)) + end + if type(res) ~= "string" then + return nil, Err.new(Err.ARG, "the B-rep plug-in's write returned no text") + end + return res, nil +end + +local function xyz(p: any): (number, number, number) + if type(p) == "table" then + return tonumber(p.x or p.X or p[1]) or 0, tonumber(p.y or p.Y or p[2]) or 0, tonumber(p.z or p.Z or p[3]) or 0 + end + return (p :: any).X, (p :: any).Y, (p :: any).Z +end + +local function linear(c: number): number + c = math.clamp(c, 0, 1) + return if c <= 0.04045 then c / 12.92 else ((c + 0.055) / 1.055) ^ 2.4 +end + +-- baseColor = the STEP colour converted from sRGB to linear; extras.color = the colour as written +function Brep.scene(plug: Plugin, bodies: { any }, opts: any): (Types.Scene?, Err.Err?) + local tess = plug.tessellate + if not tess then + return nil, Err.new(Err.UNSUPPORTED, "the B-rep plug-in has no tessellate()") + end + local scene = Types.Scene.new() + scene.meta.up = "z" + scene.meta.unit = 0.001 + local tessOpts = if type(opts) == "table" and type(opts.tess) == "table" + then opts.tess + else { chord = if type(opts) == "table" and type(opts.chord) == "number" then opts.chord else 0.05 } + local matByKey: { [string]: number } = {} + local function material(r: number?, g: number?, b: number?): number + local key = if r then string.format("%.6f,%.6f,%.6f", r, g :: number, b :: number) else "default" + local m = matByKey[key] + if m then + return m + end + local mat = Types.Scene.material(if r then "step_" .. #scene.materials + 1 else "default") + if r then + mat.baseColor = { linear(r), linear(g :: number), linear(b :: number), 1 } + mat.extras = { color = { r, g, b } } + else + mat.baseColor = { 0.6, 0.6, 0.6, 1 } + end + mat.metallic, mat.roughness = 0, 0.5 + table.insert(scene.materials, mat) + matByKey[key] = #scene.materials + return #scene.materials + end + for bi, body in bodies do + local ok, mesh = pcall(tess, body, tessOpts) + if not ok then + return nil, Err.new(Err.CORRUPT, "the B-rep plug-in failed to tessellate body " .. bi .. ": " .. tostring(mesh)) + end + if type(mesh) ~= "table" or type(mesh.positions) ~= "table" or type(mesh.indices) ~= "table" then + return nil, Err.new(Err.CORRUPT, "the B-rep plug-in's tessellate returned no mesh") + end + local cok, prims = pcall(function(): { Types.Primitive } + local P, N, I = mesh.positions, mesh.normals, mesh.indices + local nv = #P + local pos = Types.Scene.accessor(nil, "f32", 3, nv) + local nrm = if type(N) == "table" and #N == nv then Types.Scene.accessor(nil, "f32", 3, nv) else nil + for i = 1, nv do + local x, y, z = xyz(P[i]) + buffer.writef32(pos.data, (i - 1) * 12, x) + buffer.writef32(pos.data, (i - 1) * 12 + 4, y) + buffer.writef32(pos.data, (i - 1) * 12 + 8, z) + if nrm then + local a, b, c = xyz(N[i]) + buffer.writef32(nrm.data, (i - 1) * 12, a) + buffer.writef32(nrm.data, (i - 1) * 12 + 4, b) + buffer.writef32(nrm.data, (i - 1) * 12 + 8, c) + end + end + local br, bg, bb = rgbOf(type(body) == "table" and body.color or nil) + local groups: { { mat: number, tris: { number } } } = {} + local byMat: { [number]: { mat: number, tris: { number } } } = {} + local faceOf = if type(mesh.faceOf) == "table" then mesh.faceOf else {} + local nt = #I // 3 + for t = 1, nt do + local f = faceOf[t] + local r, g, b = rgbOf(type(f) == "table" and f.color or nil) + if not r then + r, g, b = br, bg, bb + end + local m = material(r, g, b) + local grp = byMat[m] + if not grp then + grp = { mat = m, tris = {} } + byMat[m] = grp + table.insert(groups, grp) + end + table.insert(grp.tris, t) + end + local out: { Types.Primitive } = {} + for _, grp in groups do + local idx = Types.Scene.accessor(nil, "u32", 1, #grp.tris * 3) + for k, t in grp.tris do + for c = 0, 2 do + local v = (tonumber(I[(t - 1) * 3 + c + 1]) or 1) - 1 + buffer.writeu32(idx.data, ((k - 1) * 3 + c) * 4, math.clamp(v, 0, math.max(nv - 1, 0))) + end + end + local attrs: { [string]: Types.Accessor } = { POSITION = pos } + if nrm then + attrs.NORMAL = nrm + end + table.insert(out, { attributes = attrs, indices = idx, mode = "triangles" :: any, material = grp.mat }) + end + return out + end) + if not cok then + return nil, Err.new(Err.CORRUPT, "bad tessellation of body " .. bi .. ": " .. tostring(prims)) + end + local name = if type(body) == "table" and type(body.name) == "string" then body.name else "body_" .. bi + table.insert(scene.meshes, { name = name, primitives = prims }) + table.insert(scene.nodes, { name = name, children = {}, mesh = #scene.meshes }) + table.insert(scene.roots, #scene.nodes) + end + scene.meta.source = { format = "step", tessellated = true, bodies = #bodies } + return scene, nil +end + +return Brep +end +__FILES["cad/step/Parse"] = @native function() + + +-- cad/step/Parse: ISO 10303-21 text -> header + entity instances, one pass; never throws (nil, message, offset). +-- An integral real (`0.`, `1.E2`) is marked in its holder's metatable (`__reals = { [index | "value"] = true }`). +local Parse = {} + +local sbyte, ssub, sfind, schar, floor = string.byte, string.sub, string.find, string.char, math.floor + +local MAX_DEPTH = 100 + +type Ctx = { + s: string, + n: number, + err: string?, + errAt: number?, + null: any, + derived: any, +} + +@native local function fail(ctx: Ctx, msg: string, at: number): nil + if not ctx.err then + ctx.err, ctx.errAt = msg, at + end + return nil +end + +@native local function skip(ctx: Ctx, i: number): number + local s, n = ctx.s, ctx.n + while i <= n do + local c = sbyte(s, i) + if c == 32 or c == 10 or c == 13 or c == 9 or c == 12 then + i += 1 + elseif c == 47 and sbyte(s, i + 1) == 42 then + local _, e = sfind(s, "*/", i + 2, true) + if not e then + fail(ctx, "unterminated comment", i) + return n + 1 + end + i = e + 1 + else + return i + end + end + return i +end + +@native local function isAlpha(c: number): boolean + return (c >= 65 and c <= 90) or (c >= 97 and c <= 122) or c == 95 +end +@native local function isWord(c: number): boolean + return (c >= 65 and c <= 90) or (c >= 97 and c <= 122) or c == 95 or (c >= 48 and c <= 57) +end + +@native local function keyword(ctx: Ctx, i: number): (string?, number) + local s, n = ctx.s, ctx.n + local j = i + if j <= n and sbyte(s, j) == 33 then -- '!' user-defined + j += 1 + end + if j > n or not isAlpha(sbyte(s, j) :: number) then + return nil, i + end + j += 1 + while j <= n and isWord(sbyte(s, j) :: number) do + j += 1 + end + return string.upper(ssub(s, i, j - 1)), j +end + +@native local function utf8char(cp: number): string + if cp < 0x80 then + return schar(cp) + elseif cp < 0x800 then + return schar(0xC0 + floor(cp / 64), 0x80 + cp % 64) + elseif cp < 0x10000 then + return schar(0xE0 + floor(cp / 4096), 0x80 + floor(cp / 64) % 64, 0x80 + cp % 64) + elseif cp < 0x110000 then + return schar(0xF0 + floor(cp / 262144), 0x80 + floor(cp / 4096) % 64, 0x80 + floor(cp / 64) % 64, 0x80 + cp % 64) + end + return "\239\191\189" +end +Parse.utf8char = utf8char + +@native local function hexAt(s: string, i: number, k: number): number? + local h = ssub(s, i, i + k - 1) + if #h ~= k or sfind(h, "[^%x]") then + return nil + end + return tonumber(h, 16) +end + +-- Part 21 escapes: '' \\ \S\c \X\hh \X2\..\X0\ \X4\..\X0\; \P?\ ignored (ISO 8859-1); raw bytes >= 0x80 pass through +@native function Parse.unescape(raw: string): string + if not sfind(raw, "[\\']") then + return raw + end + local out = {} + local i, n = 1, #raw + local plain = 1 + while i <= n do + local c = sbyte(raw, i) + if c == 39 then -- '' -> ' + table.insert(out, ssub(raw, plain, i)) + i += 2 + plain = i + elseif c == 92 then + table.insert(out, ssub(raw, plain, i - 1)) + local d = sbyte(raw, i + 1) + if d == 92 then + table.insert(out, "\\") + i += 2 + elseif d == 83 and sbyte(raw, i + 2) == 92 and i + 3 <= n then -- \S\c + table.insert(out, utf8char(((sbyte(raw, i + 3) :: number) + 128) % 256)) + i += 4 + elseif d == 80 and sbyte(raw, i + 3) == 92 then -- \P?\ code page + i += 4 + elseif d == 88 and sbyte(raw, i + 2) == 92 then -- \X\hh + local h = hexAt(raw, i + 3, 2) + if h then + table.insert(out, utf8char(h)) + i += 5 + else + table.insert(out, "\\") + i += 1 + end + elseif d == 88 and (sbyte(raw, i + 2) == 50 or sbyte(raw, i + 2) == 52) and sbyte(raw, i + 3) == 92 then + local k = if sbyte(raw, i + 2) == 50 then 4 else 8 + local j = i + 4 + local hi: number? = nil + while j <= n do + if sbyte(raw, j) == 92 then + break + end + local cp = hexAt(raw, j, k) + if not cp then + break + end + if k == 4 and cp >= 0xD800 and cp < 0xDC00 then + hi = cp + elseif k == 4 and hi and cp >= 0xDC00 and cp < 0xE000 then + table.insert(out, utf8char(0x10000 + (hi - 0xD800) * 1024 + (cp - 0xDC00))) + hi = nil + else + table.insert(out, utf8char(cp)) + hi = nil + end + j += k + end + if ssub(raw, j, j + 3) == "\\X0\\" then + j += 4 + end + i = j + else + table.insert(out, "\\") + i += 1 + end + plain = i + else + i += 1 + end + end + table.insert(out, ssub(raw, plain, n)) + return table.concat(out) +end + +@native local function markReal(t: { [any]: any }, key: any) + local mt: any = getmetatable(t) + if not mt then + mt = { __reals = {} } + setmetatable(t, mt) + end + mt.__reals[key] = true +end + +local value: (ctx: Ctx, i: number, depth: number) -> (any, number, boolean) + +@native local function list(ctx: Ctx, i: number, depth: number): ({ any }?, number) + local s = ctx.s + local out = {} + i = skip(ctx, i) + if sbyte(s, i) == 41 then + return out, i + 1 + end + local k = 0 + while true do + local v, j, intReal = value(ctx, i, depth + 1) + if v == nil then + return nil, j + end + k += 1 + out[k] = v + if intReal then + markReal(out, k) + end + j = skip(ctx, j) + local c = sbyte(s, j) + if c == 44 then + i = skip(ctx, j + 1) + elseif c == 41 then + return out, j + 1 + elseif c == nil then + return fail(ctx, "truncated list", j), j + else + return fail(ctx, "expected , or ) in a list", j), j + end + end +end +Parse.list = list + +value = @native function(ctx: Ctx, i: number, depth: number): (any, number, boolean) + if depth > MAX_DEPTH then + return fail(ctx, "lists nested too deeply", i), i, false + end + local s = ctx.s + i = skip(ctx, i) + local c = sbyte(s, i) + if c == nil then + return fail(ctx, "truncated parameter", i), i, false + elseif c == 35 then -- #ref + local _, e = sfind(s, "^%d+", i + 1) + if not e then + return fail(ctx, "bad entity reference", i), i, false + end + return { ref = tonumber(ssub(s, i + 1, e)) }, e + 1, false + elseif c == 39 then -- 'string' + local j = i + 1 + while true do + local q = sfind(s, "'", j, true) + if not q then + return fail(ctx, "unterminated string", i), i, false + end + if sbyte(s, q + 1) == 39 then + j = q + 2 + else + return Parse.unescape(ssub(s, i + 1, q - 1)), q + 1, false + end + end + elseif c == 36 then + return ctx.null, i + 1, false + elseif c == 42 then + return ctx.derived, i + 1, false + elseif c == 40 then + local l, j = list(ctx, i + 1, depth) + return l, j, false + elseif c == 46 then -- .ENUM. + local _, e = sfind(s, "^[%a_][%w_]*%.", i + 1) + if not e then + return fail(ctx, "bad enumeration", i), i, false + end + return { enum = string.upper(ssub(s, i + 1, e - 1)) }, e + 1, false + elseif c == 34 then -- "binary" + local _, e = sfind(s, "^[0-3]%x*\"", i + 1) + if not e then + return fail(ctx, "bad binary literal", i), i, false + end + return { binary = string.upper(ssub(s, i + 1, e - 1)) }, e + 1, false + elseif (c >= 48 and c <= 57) or c == 45 or c == 43 then + local _, e = sfind(s, "^[+-]?%d*%.?%d*[eE]?[+-]?%d*", i) + local tok = ssub(s, i, e :: number) + local num = tonumber(if c == 43 then ssub(tok, 2) else tok) + if num == nil then + -- "1.E" without digits and the like + local core = string.match(tok, "^[+-]?%d*%.?%d*") + num = core and tonumber(if c == 43 then ssub(core, 2) else core) + if num == nil then + return fail(ctx, "bad number", i), i, false + end + e = i + #(core :: string) - 1 + end + local real = sfind(tok, "[.eE]") ~= nil + local nv = num :: number + return nv, (e :: number) + 1, real and nv == floor(nv) and nv == nv + elseif isAlpha(c) or c == 33 then -- typed parameter NAME(value) + local word, j = keyword(ctx, i) + j = skip(ctx, j) + if word == nil or sbyte(s, j) ~= 40 then + return fail(ctx, "expected a parameter", i), i, false + end + local v, k, intReal = value(ctx, j + 1, depth + 1) + if v == nil then + return nil, k, false + end + k = skip(ctx, k) + if sbyte(s, k) ~= 41 then + return fail(ctx, "expected ) after a typed parameter", k), k, false + end + local t = { typed = word, value = v } + if intReal then + markReal(t, "value") + end + return t, k + 1, false + end + return fail(ctx, "unexpected character " .. string.format("%q", schar(c)), i), i, false +end +Parse.value = value + +@native local function record(ctx: Ctx, i: number): (string?, { any }?, number) + local word, j = keyword(ctx, i) + if not word then + return fail(ctx, "expected an entity name", i), nil, i + end + j = skip(ctx, j) + if sbyte(ctx.s, j) ~= 40 then + return fail(ctx, "expected ( after " .. word, j), nil, j + end + local args, k = list(ctx, j + 1, 0) + if not args then + return nil, nil, k + end + return word, args, k +end + +@native local function expect(ctx: Ctx, i: number, ch: number, what: string): number? + i = skip(ctx, i) + if sbyte(ctx.s, i) ~= ch then + if i > ctx.n then + return fail(ctx, "truncated: expected " .. what, i) + end + return fail(ctx, "expected " .. what, i) + end + return i + 1 +end + +@native local function at(s: string, i: number, word: string): boolean + return ssub(s, i, i + #word - 1) == word +end + +type Result = { + header: { [string]: { any } }, + headerOrder: { string }, + entities: { [number]: any }, + count: number, + sections: { { name: any?, schema: any? } }, + extra: { { name: string, text: string } }, + duplicates: number, + terminated: boolean, +} + +@native function Parse.parse(s: string, null: any, derived: any, maxEntities: number): (Result?, string?, number?) + local ctx: Ctx = { s = s, n = #s, err = nil, errAt = nil, null = null, derived = derived } + local res: Result = { + header = {}, + headerOrder = {}, + entities = {}, + count = 0, + sections = {}, + extra = {}, + duplicates = 0, + terminated = false, + } + local i = skip(ctx, 1) + if not at(s, i, "ISO-10303-21") then + return nil, "no ISO-10303-21 magic", i + end + local ni = expect(ctx, i + 12, 59, ";") + if not ni then + return nil, ctx.err, ctx.errAt + end + i = ni + local sawData = false + while true do + i = skip(ctx, i) + if ctx.err then + return nil, ctx.err, ctx.errAt + end + if i > ctx.n then + if not sawData then + return nil, "truncated: no DATA section", i + end + break + end + if at(s, i, "END-ISO-10303-21") then + res.terminated = true + local e = expect(ctx, i + 16, 59, ";") + if not e then + return nil, ctx.err, ctx.errAt + end + break + end + local word, j = keyword(ctx, i) + if word == "HEADER" then + local e = expect(ctx, j, 59, ";") + if not e then + return nil, ctx.err, ctx.errAt + end + i = e + while true do + i = skip(ctx, i) + if at(s, i, "ENDSEC") then + local e2 = expect(ctx, i + 6, 59, ";") + if not e2 then + return nil, ctx.err, ctx.errAt + end + i = e2 + break + end + if i > ctx.n then + return nil, "truncated header", i + end + local t, args, k = record(ctx, i) + if not t then + return nil, ctx.err, ctx.errAt + end + local e2 = expect(ctx, k, 59, ";") + if not e2 then + return nil, ctx.err, ctx.errAt + end + if res.header[t] == nil then + table.insert(res.headerOrder, t) + end + res.header[t] = args :: { any } + i = e2 + end + elseif word == "DATA" then + sawData = true + local sec: { name: any?, schema: any? } = {} + j = skip(ctx, j) + if sbyte(s, j) == 40 then + local params, k = list(ctx, j + 1, 0) + if not params then + return nil, ctx.err, ctx.errAt + end + sec.name, sec.schema = params[1], params[2] + j = k + end + table.insert(res.sections, sec) + local secIndex = #res.sections + local e = expect(ctx, j, 59, ";") + if not e then + return nil, ctx.err, ctx.errAt + end + i = e + while true do + i = skip(ctx, i) + if ctx.err then + return nil, ctx.err, ctx.errAt + end + local c = sbyte(s, i) + if c == nil then + return nil, "truncated: the DATA section has no ENDSEC", i + end + if c ~= 35 then + if at(s, i, "ENDSEC") then + local e2 = expect(ctx, i + 6, 59, ";") + if not e2 then + return nil, ctx.err, ctx.errAt + end + i = e2 + break + end + return nil, "expected an entity instance (#id = ...)", i + end + local _, idEnd = sfind(s, "^%d+", i + 1) + if not idEnd then + return nil, "bad entity instance name", i + end + local id = tonumber(ssub(s, i + 1, idEnd)) :: number + local k = expect(ctx, idEnd + 1, 61, "=") + if not k then + return nil, ctx.err, ctx.errAt + end + k = skip(ctx, k) + local ent: any + if sbyte(s, k) == 40 then -- complex instance (A(..) B(..)) + local parts = {} + k = skip(ctx, k + 1) + while sbyte(s, k) ~= 41 do + if k > ctx.n then + return nil, "truncated complex instance", k + end + local t, args, k2 = record(ctx, k) + if not t then + return nil, ctx.err, ctx.errAt + end + table.insert(parts, { type = t, args = args }) + k = skip(ctx, k2) + end + if #parts == 0 then + return nil, "empty complex instance", k + end + ent = { id = id, type = "COMPLEX", args = {}, parts = parts } + k += 1 + else + local t, args, k2 = record(ctx, k) + if not t then + return nil, ctx.err, ctx.errAt + end + ent = { id = id, type = t, args = args } + k = k2 + end + local e2 = expect(ctx, k, 59, ";") + if not e2 then + return nil, ctx.err, ctx.errAt + end + if secIndex > 1 then + ent.section = secIndex + end + if res.entities[id] then + res.duplicates += 1 + else + res.count += 1 + if res.count > maxEntities then + return nil, "LIMIT", i + end + end + res.entities[id] = ent + i = e2 + end + elseif word == "ANCHOR" or word == "REFERENCE" or word == "SIGNATURE" then + -- kept as raw text (to the ENDSEC outside strings) + local k = j + local stop: number? = nil + while k <= ctx.n do + local c = sbyte(s, k) + if c == 39 then + local q = k + 1 + while true do + local p = sfind(s, "'", q, true) + if not p then + return nil, "unterminated string", k + end + if sbyte(s, p + 1) == 39 then + q = p + 2 + else + k = p + 1 + break + end + end + elseif c == 69 and at(s, k, "ENDSEC") then + stop = k + break + else + k += 1 + end + end + if not stop then + return nil, "truncated " .. word .. " section", i + end + table.insert(res.extra, { name = word, text = ssub(s, j, stop - 1) }) + local e2 = expect(ctx, stop + 6, 59, ";") + if not e2 then + return nil, ctx.err, ctx.errAt + end + i = e2 + else + return nil, "unknown section " .. tostring(word), i + end + end + if not sawData then + return nil, "no DATA section", i + end + return res, nil, nil +end + +return Parse +end +__FILES["cad/step/Write"] = @native function() + + +-- cad/step/Write: header + entity instances -> ISO 10303-21 text (escaped strings, shortest round-trip reals). +local Write = {} + +local sformat, sbyte, ssub, sfind, floor, huge = string.format, string.byte, string.sub, string.find, math.floor, math.huge + +local MAX_DEPTH = 100 + +-- Part 21 real: a '.' always, upper-case E +@native function Write.real(v: number): string? + if v ~= v or v == huge or v == -huge then + return nil + end + local s = sformat("%.15g", v) + if tonumber(s) ~= v then + s = sformat("%.16g", v) + if tonumber(s) ~= v then + s = sformat("%.17g", v) + end + end + s = string.upper(s) + local e = sfind(s, "E", 1, true) + if not sfind(s, ".", 1, true) then + if e then + s = ssub(s, 1, e - 1) .. "." .. ssub(s, e) + else + s ..= "." + end + end + return s +end + +local HEX = "0123456789ABCDEF" +@native local function hex(v: number, k: number): string + local out = table.create(k) + for i = k, 1, -1 do + local d = v % 16 + out[i] = ssub(HEX, d + 1, d + 1) + v = floor(v / 16) + end + return table.concat(out) +end + +@native function Write.str(s: string): string + if not sfind(s, "[^ -&(-[%]^-~]") then -- printable ASCII without ' and \ + return "'" .. s .. "'" + end + local out = { "'" } + local i, n = 1, #s + local wide: number? = nil -- 4 (\X2\) or 8 (\X4\) while in an extended run + @native local function close() + if wide then + table.insert(out, "\\X0\\") + wide = nil + end + end + while i <= n do + local c = sbyte(s, i) :: number + if c >= 32 and c < 127 then + close() + if c == 39 then + table.insert(out, "''") + elseif c == 92 then + table.insert(out, "\\\\") + else + table.insert(out, string.char(c)) + end + i += 1 + else + local cp: number? = nil + local len = 1 + if c >= 0xC2 and c < 0xE0 then + local c2 = sbyte(s, i + 1) + if c2 and c2 >= 0x80 and c2 < 0xC0 then + cp, len = (c - 0xC0) * 64 + (c2 - 0x80), 2 + end + elseif c >= 0xE0 and c < 0xF0 then + local c2, c3 = sbyte(s, i + 1, i + 2) + if c2 and c3 and c2 >= 0x80 and c2 < 0xC0 and c3 >= 0x80 and c3 < 0xC0 then + local v = (c - 0xE0) * 4096 + (c2 - 0x80) * 64 + (c3 - 0x80) + if v >= 0x800 and (v < 0xD800 or v >= 0xE000) then + cp, len = v, 3 + end + end + elseif c >= 0xF0 and c < 0xF5 then + local c2, c3, c4 = sbyte(s, i + 1, i + 3) + if c2 and c3 and c4 and c2 >= 0x80 and c2 < 0xC0 and c3 >= 0x80 and c3 < 0xC0 and c4 >= 0x80 and c4 < 0xC0 then + local v = (c - 0xF0) * 262144 + (c2 - 0x80) * 4096 + (c3 - 0x80) * 64 + (c4 - 0x80) + if v >= 0x10000 and v < 0x110000 then + cp, len = v, 4 + end + end + end + if cp == nil then + close() + table.insert(out, "\\X\\" .. hex(c, 2)) + i += 1 + else + local k = if cp >= 0x10000 then 8 else 4 + if wide ~= k then + close() + table.insert(out, if k == 4 then "\\X2\\" else "\\X4\\") + wide = k + end + table.insert(out, hex(cp, k)) + i += len + end + end + end + close() + table.insert(out, "'") + return table.concat(out) +end + +@native local function isName(s: any): boolean + return type(s) == "string" and sfind(s, "^!?[%a_][%w_]*$") ~= nil +end +Write.isName = isName + +type Ctx = { out: { string }, null: any, derived: any, err: string? } + +local value: (ctx: Ctx, v: any, real: boolean, depth: number) -> boolean + +@native local function reals(t: any): { [any]: boolean }? + local mt = getmetatable(t) + return if type(mt) == "table" and type(mt.__reals) == "table" then mt.__reals else nil +end + +@native local function list(ctx: Ctx, t: { any }, depth: number): boolean + local out = ctx.out + table.insert(out, "(") + local marks = reals(t) + local n = #t + for i = 1, n do + if i > 1 then + table.insert(out, ",") + end + if not value(ctx, t[i], marks ~= nil and marks[i] == true, depth + 1) then + return false + end + end + table.insert(out, ")") + return true +end +Write.list = list + +value = @native function(ctx: Ctx, v: any, real: boolean, depth: number): boolean + local out = ctx.out + if depth > MAX_DEPTH then + ctx.err = "values nested too deeply (or a cycle)" + return false + end + local tv = type(v) + if tv == "number" then + if not real and v == floor(v) and v > -2 ^ 53 and v < 2 ^ 53 then + table.insert(out, sformat("%.0f", v)) + return true + end + local r = Write.real(v) + if not r then + ctx.err = "a number that STEP cannot hold (nan / inf)" + return false + end + table.insert(out, r) + return true + elseif tv == "string" then + table.insert(out, Write.str(v)) + return true + elseif tv == "boolean" then + table.insert(out, if v then ".T." else ".F.") + return true + elseif tv == "table" then + if v == ctx.null then + table.insert(out, "$") + return true + elseif v == ctx.derived then + table.insert(out, "*") + return true + end + local ref = v.ref + if ref ~= nil then + if type(ref) ~= "number" or ref ~= floor(ref) or ref < 0 then + ctx.err = "bad entity reference " .. tostring(ref) + return false + end + table.insert(out, sformat("#%.0f", ref)) + return true + end + local enum = v.enum + if enum ~= nil then + if type(enum) ~= "string" or not sfind(enum, "^[%a_][%w_]*$") then + ctx.err = "bad enumeration " .. tostring(enum) + return false + end + table.insert(out, "." .. string.upper(enum) .. ".") + return true + end + local bin = v.binary + if bin ~= nil then + if type(bin) ~= "string" or not sfind(bin, "^[0-3]%x*$") then + ctx.err = "bad binary literal" + return false + end + table.insert(out, "\"" .. string.upper(bin) .. "\"") + return true + end + local typed = v.typed + if typed ~= nil then + if not isName(typed) then + ctx.err = "bad typed parameter name " .. tostring(typed) + return false + end + if v.value == nil then + ctx.err = "typed parameter " .. typed .. " without a value" + return false + end + local marks = reals(v) + table.insert(out, string.upper(typed) .. "(") + if not value(ctx, v.value, marks ~= nil and marks.value == true, depth + 1) then + return false + end + table.insert(out, ")") + return true + end + return list(ctx, v, depth) + end + ctx.err = "cannot write a " .. tv .. " value" + return false +end +Write.value = value + +@native function Write.record(ctx: Ctx, t: any, args: any): boolean + if not isName(t) then + ctx.err = "bad entity type " .. tostring(t) + return false + end + if type(args) ~= "table" then + ctx.err = "entity " .. t .. " without an args list" + return false + end + table.insert(ctx.out, string.upper(t)) + return list(ctx, args, 0) +end + +return Write +end +end + + + + + + codecs_audio + --!optimize 2 +--!nocheck +-- rosetta chunk codecs_audio (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 21 modules (10 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["codecs/audio/Ac3"] = function() + +-- codecs/audio/Ac3: AC-3 (Dolby Digital, ATSC A/52) syncframes: syncinfo / BSI, CRC check and decoder. +-- Written from ATSC A/52:2018; no third-party code. E-AC-3 (bsid 11 .. 16) and bsid 9 / 10 are UNSUPPORTED. +local Err = __include("core/Err") +local T = __include("codecs/audio/Ac3/Tables") +local Decode = __include("codecs/audio/Ac3/Decode") + +local Ac3 = {} + +local readu8 = buffer.readu8 +local NFCHANS = { [0] = 2, 1, 2, 3, 3, 4, 4, 5 } + +type Header = { + sampleRate: number, + frameSize: number, + bitrate: number, + channels: number, + acmod: number, + lfeon: boolean, + bsid: number, +} + +function Ac3.header(b: buffer, o: number, limit: number): Header? + if o < 0 or o + 8 > limit or o + 8 > buffer.len(b) then + return nil + end + if readu8(b, o) ~= 0x0B or readu8(b, o + 1) ~= 0x77 then + return nil + end + local bsid = bit32.rshift(readu8(b, o + 5), 3) + if bsid > 10 then + if bsid > 16 then + return nil + end + -- E-AC-3: strmtyp(2) substreamid(3) frmsiz(11) fscod(2) ... + local words = bit32.band(readu8(b, o + 2), 7) * 256 + readu8(b, o + 3) + 1 + local fs = bit32.rshift(readu8(b, o + 4), 6) + return { + sampleRate = if fs < 3 then T.RATES[fs + 1] else 0, + frameSize = words * 2, + bitrate = 0, + channels = 0, + acmod = bit32.band(bit32.rshift(readu8(b, o + 4), 1), 7), + lfeon = false, + bsid = bsid, + } + end + local b4 = readu8(b, o + 4) + local fscod, frmsizecod = bit32.rshift(b4, 6), bit32.band(b4, 63) + local words = T.frameWords(fscod, frmsizecod) + if words == 0 then + return nil + end + local acmod = bit32.rshift(readu8(b, o + 6), 5) + -- lfeon: after acmod and the optional cmixlev / surmixlev / dsurmod fields + local skip = 0 + if bit32.band(acmod, 1) == 1 and acmod ~= 1 then + skip += 2 + end + if bit32.band(acmod, 4) ~= 0 then + skip += 2 + end + if acmod == 2 then + skip += 2 + end + local w = readu8(b, o + 6) * 256 + readu8(b, o + 7) + local lfeon = bit32.extract(w, 12 - skip, 1) == 1 + local shift = if bsid > 8 then bsid - 8 else 0 + return { + sampleRate = T.RATES[fscod + 1] // 2 ^ shift, + frameSize = words * 2, + bitrate = T.BITRATES[frmsizecod // 2 + 1] * 1000 // 2 ^ shift, + channels = NFCHANS[acmod] + (if lfeon then 1 else 0), + acmod = acmod, + lfeon = lfeon, + bsid = bsid, + } +end + +-- CRC-16 of A/52 section 7.10.1 (x^16 + x^15 + x^2 + 1, MSB first, zero start): 0 over everything after the sync word +local CRC = table.create(256, 0) +for i = 0, 255 do + local c = i * 256 + for _ = 1, 8 do + c = if c >= 0x8000 then bit32.bxor(bit32.band(c * 2, 0xFFFF), 0x8005) else c * 2 + end + CRC[i + 1] = c +end + +function Ac3.crc(b: buffer, o: number, n: number): number + local c = 0 + for i = o, o + n - 1 do + c = bit32.bxor(bit32.band(c * 256, 0xFFFF), CRC[bit32.bxor(bit32.rshift(c, 8), readu8(b, i)) + 1]) + end + return c +end + +type Options = { + drc: number?, -- 0 = off (default, as ffmpeg -drc_scale 0), 1 = as the stream says + crc: boolean?, +} + +type Decoder = { + pcm: { number }, + channels: number, + sampleRate: number, + blocks: { number }, + decode: (self: Decoder, buf: buffer, offset: number?, length: number?) -> (number?, Err.Err?), + reset: (self: Decoder) -> (), +} + +function Ac3.decoder(opts: Options?): Decoder + local o: Options = opts or {} + local drc = math.max(0, o.drc or 0) + local checkCrc = o.crc ~= false + local st = Decode.state() + local scratch = buffer.create(3840 + Decode.PAD) + local dec: Decoder + dec = { + pcm = st.pcm, + channels = 0, + sampleRate = 0, + blocks = st.blocks, + decode = function(self: Decoder, buf: buffer, offset: number?, length: number?): (number?, Err.Err?) + local off = offset or 0 + if type(buf) ~= "buffer" or off < 0 or off >= buffer.len(buf) then + return nil, Err.new(Err.ARG, "frame range out of the buffer") + end + local h = Ac3.header(buf, off, buffer.len(buf)) + if not h then + return nil, Err.new(Err.CORRUPT, "no AC-3 syncframe", off) + end + local n = h.frameSize + if length and length < n or off + n > buffer.len(buf) then + return nil, Err.new(Err.TRUNCATED, "truncated syncframe", off) + end + if checkCrc and Ac3.crc(buf, off + 2, n - 2) ~= 0 then + return nil, Err.new(Err.CHECKSUM, "syncframe CRC", off) + end + buffer.copy(scratch, 0, buf, off, n) + local frames, msg = Decode.frame(st, scratch, n, drc) + if not frames then + return nil, Err.from(msg, off) + end + self.pcm = st.pcm + self.channels = st.channels + self.sampleRate = h.sampleRate + return frames, nil + end, + reset = function(_self: Decoder) + Decode.reset(st) + end, + } + return dec +end + +return Ac3 +end +__FILES["codecs/audio/Ac3/Decode"] = @native function() + + + +-- codecs/audio/Ac3/Decode: one AC-3 syncframe (6 audio blocks of 256 samples) -> PCM. +-- Written from ATSC A/52:2018 (5.3 syntax, 7.1 exponents, 7.2 bit allocation, 7.3 mantissas, 7.4 coupling, 7.5 +-- rematrixing, 7.7.1 dynamic range, 7.9 transforms); no third-party code. The caller pads the frame by PAD bytes. +local T = __include("codecs/audio/Ac3/Tables") +local Mdct = __include("codecs/audio/Mdct") + +local readu32, bswap, extract, band, rshift = buffer.readu32, bit32.byteswap, bit32.extract, bit32.band, bit32.rshift +local max, min = math.max, math.min + +local Decode = {} +Decode.PAD = 2048 + +local CPL, LFE = 7, 6 -- channel slots: 1 .. 5 full bandwidth, 6 LFE, 7 the coupling channel +local NFCHANS = { [0] = 2, 1, 2, 3, 3, 4, 4, 5 } + +local SLOWDEC, FASTDEC, SLOWGAIN, DBPBTAB, FLOORTAB, FASTGAIN = T.SLOWDEC, T.FASTDEC, T.SLOWGAIN, T.DBPBTAB, T.FLOORTAB, T.FASTGAIN +local BNDTAB, BNDSZ, MASKTAB, LATAB, HTH, BAPTAB = T.BNDTAB, T.BNDSZ, T.MASKTAB, T.LATAB, T.HTH, T.BAPTAB + +local POW2 = table.create(32, 0) +for e = 0, 31 do + POW2[e + 1] = 2 ^ -e +end +-- symmetric quantiser values (Tables 7.19 - 7.23): Q1[code + 1] etc. +@native local function levels(n: number): { number } + local t = {} + for c = 0, n - 1 do + t[c + 1] = (2 * c - (n - 1)) / n + end + return t +end +local Q1, Q2, Q3, Q4, Q5 = levels(3), levels(5), levels(7), levels(11), levels(15) +-- bits of the asymmetric quantisers (bap 6 .. 15) +local QBITS = { [6] = 5, [7] = 6, [8] = 7, [9] = 8, [10] = 9, [11] = 10, [12] = 11, [13] = 12, [14] = 14, [15] = 16 } + +local WINDOW = Mdct.window("kbd", 512, 5) :: { number } +local PLAN512 = Mdct.new(512) :: Mdct.Plan +local PLAN256 = Mdct.new(256) :: Mdct.Plan + +local B: buffer = buffer.create(0) +local P = 0 + +@native local function bits(n: number): number + if n <= 0 then + return 0 + end + if n > 24 then + local hi = bits(n - 16) + return hi * 65536 + bits(16) + end + local w = bswap(readu32(B, rshift(P, 3))) + local v = extract(w, 32 - band(P, 7) - n, n) + P += n + return v +end + +type State = { + fscod: number, + acmod: number, + lfeon: boolean, + nfchans: number, + channels: number, + map: { number }, + drc: number, + exp: { { number } }, + bap: { { number } }, + coef: { { number } }, + delay: { { number } }, + endmant: { number }, + chexpstr: { number }, + blksw: { boolean }, + dithflag: { boolean }, + fsnroffst: { number }, + fgaincod: { number }, + dbaOn: { boolean }, + dbaOffst: { { number } }, + dbaLen: { { number } }, + dbaBa: { { number } }, + cplinu: boolean, + chincpl: { boolean }, + phsflginu: boolean, + cplbegf: number, + cplendf: number, + cplbndstrc: { boolean }, -- [sbnd + 1], sbnd = 0 .. 17 (absolute sub-band) + cplco: { { number } }, + phsflg: { boolean }, + cplfleak: number, + cplsleak: number, + rematflg: { boolean }, + sdcycod: number, + fdcycod: number, + sgaincod: number, + dbpbcod: number, + floorcod: number, + csnroffst: number, + dynrng: { number }, -- gain for Ch1 / Ch2 + seed: number, + psd: { number }, + bndpsd: { number }, + excite: { number }, + mask: { number }, + y: { number }, + pcm: { number }, + blocks: { number }, +} + +@native local function arrays(n: number, size: number, v: any): { any } + local t = {} + for i = 1, n do + t[i] = table.create(size, v) + end + return t +end + +@native function Decode.state(): State + return { + fscod = 0, + acmod = 2, + lfeon = false, + nfchans = 2, + channels = 2, + map = { 1, 2, 3, 4, 5, 6 }, + drc = 0, + exp = arrays(7, 264, 0), + bap = arrays(7, 264, 0), + coef = arrays(7, 256, 0), + delay = arrays(6, 256, 0), + endmant = table.create(7, 0), + chexpstr = table.create(7, 0), + blksw = table.create(7, false), + dithflag = table.create(7, false), + fsnroffst = table.create(7, 0), + fgaincod = table.create(7, 0), + dbaOn = table.create(7, false), + dbaOffst = arrays(7, 8, 0), + dbaLen = arrays(7, 8, 0), + dbaBa = arrays(7, 8, 0), + cplinu = false, + chincpl = table.create(7, false), + phsflginu = false, + cplbegf = 0, + cplendf = 0, + cplbndstrc = table.create(18, false), + cplco = arrays(5, 18, 0), + phsflg = table.create(18, false), + cplfleak = 0, + cplsleak = 0, + rematflg = table.create(4, false), + sdcycod = 0, + fdcycod = 0, + sgaincod = 0, + dbpbcod = 0, + floorcod = 0, + csnroffst = 0, + dynrng = { 1, 1 }, + seed = 1, + psd = table.create(256, 0), + bndpsd = table.create(50, 0), + excite = table.create(50, 0), + mask = table.create(50, 0), + y = table.create(512, 0), + pcm = table.create(1536 * 2, 0), + blocks = table.create(6, 0), + } +end + +@native function Decode.reset(st: State) + for _, d in st.delay do + for i = 1, 256 do + d[i] = 0 + end + end +end + +-- grouped exponents: 7 bits = 3 deltas each after absexp, grpsize bins per delta; each exponent stays in 0 .. 24 +@native local function exponents(e: { number }, absexp: number, ngrps: number, grpsize: number, first: number): boolean + local prev = absexp + local k = first + 1 + for _ = 1, ngrps do + local g = bits(7) + if g >= 125 then + return false + end + local d1 = g // 25 + local d2 = (g % 25) // 5 + local d3 = g % 5 + for m = 1, 3 do + local d = if m == 1 then d1 elseif m == 2 then d2 else d3 + prev += d - 2 + if prev < 0 or prev > 24 then + return false + end + for _ = 1, grpsize do + e[k] = prev + k += 1 + end + end + end + return true +end + +@native local function logadd(a: number, b: number): number + local c = a - b + local adr = min(rshift(if c >= 0 then c else -c, 1), 255) + return if c >= 0 then a + LATAB[adr + 1] else b + LATAB[adr + 1] +end + +@native local function lowcomp(a: number, b0: number, b1: number, bin: number): number + if bin < 7 then + if b0 + 256 == b1 then + a = 384 + elseif b0 > b1 then + a = max(0, a - 64) + end + elseif bin < 20 then + if b0 + 256 == b1 then + a = 320 + elseif b0 > b1 then + a = max(0, a - 64) + end + else + a = max(0, a - 128) + end + return a +end + +-- section 7.2.2: the bap of bins [start, stop) of channel slot ch +@native local function allocate(st: State, ch: number, start: number, stop: number, fgain: number, snroffset: number, isLfe: boolean) + local e, bap = st.exp[ch], st.bap[ch] + local psd, bndpsd, excite, mask = st.psd, st.bndpsd, st.excite, st.mask + local sdecay, fdecay = SLOWDEC[st.sdcycod + 1], FASTDEC[st.fdcycod + 1] + local sgain, dbknee, floor = SLOWGAIN[st.sgaincod + 1], DBPBTAB[st.dbpbcod + 1], FLOORTAB[st.floorcod + 1] + if floor >= 0x8000 then + floor -= 0x10000 -- 0xf800: a negative 16-bit value + end + for bin = start, stop - 1 do + psd[bin + 1] = 3072 - e[bin + 1] * 128 + end + -- PSD integration + local j = start + local k = MASKTAB[start + 1] + local lastbin + repeat + lastbin = min(BNDTAB[k + 1] + BNDSZ[k + 1], stop) + local v = psd[j + 1] + j += 1 + while j < lastbin do + v = logadd(v, psd[j + 1]) + j += 1 + end + bndpsd[k + 1] = v + k += 1 + until stop <= lastbin + -- excitation + local bndstrt = MASKTAB[start + 1] + local bndend = MASKTAB[stop] + 1 + local fastleak, slowleak = 0, 0 + local begin + if bndstrt == 0 then + local lc = 0 + lc = lowcomp(lc, bndpsd[1], bndpsd[2], 0) + excite[1] = bndpsd[1] - fgain - lc + lc = lowcomp(lc, bndpsd[2], bndpsd[3], 1) + excite[2] = bndpsd[2] - fgain - lc + begin = 7 + for bin = 2, 6 do + local last = isLfe and bin == 6 + if not last then + lc = lowcomp(lc, bndpsd[bin + 1], bndpsd[bin + 2], bin) + end + fastleak = bndpsd[bin + 1] - fgain + slowleak = bndpsd[bin + 1] - sgain + excite[bin + 1] = fastleak - lc + if not last and bndpsd[bin + 1] <= bndpsd[bin + 2] then + begin = bin + 1 + break + end + end + for bin = begin, min(bndend, 22) - 1 do + if not (isLfe and bin == 6) then + lc = lowcomp(lc, bndpsd[bin + 1], bndpsd[bin + 2], bin) + end + fastleak = max(fastleak - fdecay, bndpsd[bin + 1] - fgain) + slowleak = max(slowleak - sdecay, bndpsd[bin + 1] - sgain) + excite[bin + 1] = max(fastleak - lc, slowleak) + end + begin = 22 + else + begin = bndstrt + fastleak = st.cplfleak * 256 + 768 + slowleak = st.cplsleak * 256 + 768 + end + for bin = begin, bndend - 1 do + fastleak = max(fastleak - fdecay, bndpsd[bin + 1] - fgain) + slowleak = max(slowleak - sdecay, bndpsd[bin + 1] - sgain) + excite[bin + 1] = max(fastleak, slowleak) + end + -- masking curve + local hth = HTH[st.fscod + 1] + for bin = bndstrt, bndend - 1 do + local x = excite[bin + 1] + local p = bndpsd[bin + 1] + if p < dbknee then + x += (dbknee - p) // 4 + end + mask[bin + 1] = max(x, hth[bin + 1]) + end + -- delta bit allocation + if st.dbaOn[ch] then + local offs, lens, bas = st.dbaOffst[ch], st.dbaLen[ch], st.dbaBa[ch] + local b = 0 + for seg = 1, #offs do + b += offs[seg] + local ba = bas[seg] + local delta = if ba >= 4 then (ba - 3) * 128 else (ba - 4) * 128 + for _ = 1, lens[seg] do + if b < 50 then + mask[b + 1] += delta + end + b += 1 + end + end + end + -- bit allocation pointers + local i = start + j = MASKTAB[start + 1] + repeat + lastbin = min(BNDTAB[j + 1] + BNDSZ[j + 1], stop) + local m = mask[j + 1] - snroffset - floor + if m < 0 then + m = 0 + end + m = band(m, 0x1fe0) + floor + while i < lastbin do + local adr = (psd[i + 1] - m) // 32 + bap[i + 1] = BAPTAB[min(63, max(0, adr)) + 1] + i += 1 + end + j += 1 + until stop <= lastbin +end + +-- grouped mantissa state (bap 1, 2, 4 share groups across channels within a block) +local G1, G2, G4 = table.create(3, 0), table.create(3, 0), table.create(2, 0) +local n1, n2, n4 = 0, 0, 0 + +@native local function dither(st: State): number + local s = (st.seed * 1664525 + 1013904223) % 4294967296 + st.seed = s + return (s / 2147483648 - 1) * 0.707 +end + +@native local function mantissas(st: State, ch: number, start: number, stop: number, out: { number }, dith: boolean) + local e, bap = st.exp[ch], st.bap[ch] + for bin = start, stop - 1 do + local b = bap[bin + 1] + local v + if b == 0 then + v = if dith then dither(st) else 0 + elseif b == 1 then + if n1 == 0 then + local g = bits(5) + if g > 26 then + g = 26 + end + G1[1], G1[2], G1[3] = Q1[g // 9 + 1], Q1[(g % 9) // 3 + 1], Q1[g % 3 + 1] + n1 = 3 + end + v = G1[4 - n1] + n1 -= 1 + elseif b == 2 then + if n2 == 0 then + local g = bits(7) + if g > 124 then + g = 124 + end + G2[1], G2[2], G2[3] = Q2[g // 25 + 1], Q2[(g % 25) // 5 + 1], Q2[g % 5 + 1] + n2 = 3 + end + v = G2[4 - n2] + n2 -= 1 + elseif b == 3 then + v = Q3[min(bits(3), 6) + 1] + elseif b == 4 then + if n4 == 0 then + local g = bits(7) + if g > 120 then + g = 120 + end + G4[1], G4[2] = Q4[g // 11 + 1], Q4[g % 11 + 1] + n4 = 2 + end + v = G4[3 - n4] + n4 -= 1 + elseif b == 5 then + v = Q5[min(bits(4), 14) + 1] + else + local nb = QBITS[b] + local m = bits(nb) + local half = 2 ^ (nb - 1) + if m >= half then + m -= 2 * half + end + v = m / half + end + out[bin + 1] = v * POW2[e[bin + 1] + 1] + end +end + +@native local function readDba(st: State, ch: number) + local nseg = bits(3) + 1 + local offs, lens, bas = st.dbaOffst[ch], st.dbaLen[ch], st.dbaBa[ch] + table.clear(offs) + table.clear(lens) + table.clear(bas) + for seg = 1, nseg do + offs[seg] = bits(5) + lens[seg] = bits(4) + bas[seg] = bits(3) + end +end + +local EXPGRP = { 3, 6, 12 } -- bins per group of 3 deltas, by strategy (D15 / D25 / D45) + +@native local function audblk(st: State, blk: number, limit: number): (boolean?, string?) + local nf, acmod = st.nfchans, st.acmod + for ch = 1, nf do + st.blksw[ch] = bits(1) == 1 + end + for ch = 1, nf do + st.dithflag[ch] = bits(1) == 1 + end + for i = 1, if acmod == 0 then 2 else 1 do + if bits(1) == 1 then + local v = bits(8) + local x = rshift(v, 5) + if x >= 4 then + x -= 8 + end + local g = 2 ^ (x + 1) * (32 + band(v, 31)) / 64 + st.dynrng[i] = if st.drc == 1 then g else g ^ st.drc + elseif blk == 0 then + st.dynrng[i] = 1 + end + end + if bits(1) == 1 then + st.cplinu = bits(1) == 1 + if st.cplinu then + if acmod < 2 then + return nil, "coupling in a mono / dual mono stream" + end + for ch = 1, nf do + st.chincpl[ch] = bits(1) == 1 + end + st.phsflginu = if acmod == 2 then bits(1) == 1 else false + st.cplbegf = bits(4) + st.cplendf = bits(4) + if st.cplendf + 3 <= st.cplbegf then + return nil, "bad coupling range" + end + st.cplbndstrc[st.cplbegf + 1] = false + for sbnd = st.cplbegf + 1, st.cplendf + 2 do + st.cplbndstrc[sbnd + 1] = bits(1) == 1 + end + else + for ch = 1, nf do + st.chincpl[ch] = false + end + st.phsflginu = false + end + elseif blk == 0 then + return nil, "no coupling strategy in block 0" + end + local cplinu = st.cplinu + local cplbegf, cplendf = st.cplbegf, st.cplendf + local cplstrt = 37 + 12 * cplbegf + local cplend = 37 + 12 * (cplendf + 3) + -- coupling coordinates (per sub-band, duplicated over each coupling band) + if cplinu then + local anyNew = false + for ch = 1, nf do + if st.chincpl[ch] then + if bits(1) == 1 then + anyNew = true + local mstr = bits(2) * 3 + local co = st.cplco[ch] + local v = 0 + for sbnd = cplbegf, cplendf + 2 do + if not st.cplbndstrc[sbnd + 1] then + local ex, mant = bits(4), bits(4) + local m = if ex == 15 then mant / 16 else (mant + 16) / 32 + v = m * 2 ^ -(ex + mstr) + end + co[sbnd + 1] = v + end + end + end + end + if acmod == 2 and st.phsflginu and anyNew then + local f = false + for sbnd = cplbegf, cplendf + 2 do + if not st.cplbndstrc[sbnd + 1] then + f = bits(1) == 1 + end + st.phsflg[sbnd + 1] = f + end + end + end + if acmod == 2 then + if bits(1) == 1 then + local n = if not cplinu or cplbegf > 2 then 4 elseif cplbegf > 0 then 3 else 2 + for r = 1, 4 do + st.rematflg[r] = if r <= n then bits(1) == 1 else false + end + elseif blk == 0 then + for r = 1, 4 do + st.rematflg[r] = false + end + end + end + local chexpstr = st.chexpstr + chexpstr[CPL] = if cplinu then bits(2) else 0 + for ch = 1, nf do + chexpstr[ch] = bits(2) + end + chexpstr[LFE] = if st.lfeon then bits(1) else 0 + if blk == 0 then + for ch = 1, nf do + if chexpstr[ch] == 0 then + return nil, "exponent reuse in block 0" + end + end + if (cplinu and chexpstr[CPL] == 0) or (st.lfeon and chexpstr[LFE] == 0) then + return nil, "exponent reuse in block 0" + end + end + local endmant = st.endmant + for ch = 1, nf do + if chexpstr[ch] ~= 0 then + if st.chincpl[ch] then + endmant[ch] = cplstrt + else + local bw = bits(6) + if bw > 60 then + return nil, "bad channel bandwidth code" + end + endmant[ch] = 37 + 3 * (bw + 12) + end + end + end + endmant[LFE] = 7 + if cplinu and chexpstr[CPL] ~= 0 then + local abs = bits(4) * 2 + local grp = EXPGRP[chexpstr[CPL]] + if not exponents(st.exp[CPL], abs, (cplend - cplstrt) // grp, grp // 3, cplstrt) then + return nil, "bad coupling exponents" + end + end + for ch = 1, nf do + local s = chexpstr[ch] + if s ~= 0 then + local grp = EXPGRP[s] + local ngrps + if s == 1 then + ngrps = (endmant[ch] - 1) // 3 + elseif s == 2 then + ngrps = (endmant[ch] - 1 + 3) // 6 + else + ngrps = (endmant[ch] - 1 + 9) // 12 + end + local e = st.exp[ch] + e[1] = bits(4) + if not exponents(e, e[1], ngrps, grp // 3, 1) then + return nil, "bad exponents" + end + bits(2) -- gainrng + end + end + if st.lfeon and chexpstr[LFE] ~= 0 then + local e = st.exp[LFE] + e[1] = bits(4) + if not exponents(e, e[1], 2, 1, 1) then + return nil, "bad LFE exponents" + end + end + if P > limit then + return nil, "truncated block" + end + if bits(1) == 1 then + st.sdcycod, st.fdcycod, st.sgaincod, st.dbpbcod, st.floorcod = bits(2), bits(2), bits(2), bits(2), bits(3) + elseif blk == 0 then + return nil, "no bit allocation parameters in block 0" + end + if bits(1) == 1 then + st.csnroffst = bits(6) + if cplinu then + st.fsnroffst[CPL], st.fgaincod[CPL] = bits(4), bits(3) + end + for ch = 1, nf do + st.fsnroffst[ch], st.fgaincod[ch] = bits(4), bits(3) + end + if st.lfeon then + st.fsnroffst[LFE], st.fgaincod[LFE] = bits(4), bits(3) + end + elseif blk == 0 then + return nil, "no SNR offsets in block 0" + end + if cplinu then + if bits(1) == 1 then + st.cplfleak, st.cplsleak = bits(3), bits(3) + end + end + if bits(1) == 1 then + local modes = table.create(7, 0) + if cplinu then + modes[CPL] = bits(2) + end + for ch = 1, nf do + modes[ch] = bits(2) + end + if cplinu and modes[CPL] == 1 then + readDba(st, CPL) + end + for ch = 1, nf do + if modes[ch] == 1 then + readDba(st, ch) + end + end + for _, ch in { 1, 2, 3, 4, 5, CPL } do + if modes[ch] == 1 then + st.dbaOn[ch] = true + elseif modes[ch] == 2 or modes[ch] == 3 then + st.dbaOn[ch] = false + end + end + elseif blk == 0 then + for ch = 1, 7 do + st.dbaOn[ch] = false + end + end + if bits(1) == 1 then + P += bits(9) * 8 + end + if P > limit then + return nil, "truncated block" + end + local zero = st.csnroffst == 0 + if zero then + for ch = 1, nf do + if st.fsnroffst[ch] ~= 0 then + zero = false + end + end + if (cplinu and st.fsnroffst[CPL] ~= 0) or (st.lfeon and st.fsnroffst[LFE] ~= 0) then + zero = false + end + end + @native local function alloc(ch: number, start: number, stop: number, isLfe: boolean) + if zero then + for i = start + 1, stop do + st.bap[ch][i] = 0 + end + else + local snr = ((st.csnroffst - 15) * 16 + st.fsnroffst[ch]) * 4 + allocate(st, ch, start, stop, FASTGAIN[st.fgaincod[ch] + 1], snr, isLfe) + end + end + if cplinu then + alloc(CPL, cplstrt, cplend, false) + end + for ch = 1, nf do + alloc(ch, 0, endmant[ch], false) + end + if st.lfeon then + alloc(LFE, 0, 7, true) + end + n1, n2, n4 = 0, 0, 0 + local gotCpl = false + local coef = st.coef + for ch = 1, nf do + local c = coef[ch] + mantissas(st, ch, 0, endmant[ch], c, st.dithflag[ch]) + for i = endmant[ch] + 1, 256 do + c[i] = 0 + end + if cplinu and st.chincpl[ch] and not gotCpl then + mantissas(st, CPL, cplstrt, cplend, coef[CPL], false) + gotCpl = true + end + if P > limit then + return nil, "truncated block" + end + end + if st.lfeon then + local c = coef[LFE] + mantissas(st, LFE, 0, 7, c, false) + for i = 8, 256 do + c[i] = 0 + end + end + if P > limit then + return nil, "truncated block" + end + -- decoupling (section 7.4): dither the coupling channel's zero-bit mantissas per channel + if cplinu then + local cc, cbap, cexp = coef[CPL], st.bap[CPL], st.exp[CPL] + for ch = 1, nf do + if st.chincpl[ch] then + local c, co = coef[ch], st.cplco[ch] + local dith = st.dithflag[ch] + local flip = acmod == 2 and ch == 2 and st.phsflginu + for sbnd = cplbegf, cplendf + 2 do + local f = co[sbnd + 1] * 8 + if flip and st.phsflg[sbnd + 1] then + f = -f + end + for k = 37 + 12 * sbnd + 1, 37 + 12 * sbnd + 12 do + local v = cc[k] + if cbap[k] == 0 then + v = if dith then dither(st) * POW2[cexp[k] + 1] else 0 + end + c[k] = v * f + end + end + for k = cplend + 1, 256 do + c[k] = 0 + end + end + end + end + -- rematrixing (section 7.5) + if acmod == 2 then + local stop = if cplinu then cplstrt else min(endmant[1], endmant[2]) + local l, r = coef[1], coef[2] + local edges = { 13, 25, 37, 61, 253 } + for rb = 1, 4 do + if st.rematflg[rb] then + for k = edges[rb] + 1, min(edges[rb + 1], stop) do + local a, b = l[k], r[k] + l[k], r[k] = a + b, a - b + end + end + end + end + return true, nil +end + +@native local function synth(st: State, ch: number, short: boolean, gain: number, out: { number }, base: number, step: number) + local x, y, d, w = st.coef[ch], st.y, st.delay[ch], WINDOW + if short then + -- two 256-point transforms of the interleaved coefficients, phases alpha = -1 (n0 = 0) and +1 (n0 = N / 2) + local z = st.psd + Mdct.inverse(PLAN256, x, 1, 2, z, 1, -2 * gain) + for n = 0, 63 do + y[n + 1] = -z[n + 193] + end + for n = 64, 255 do + y[n + 1] = z[n - 63] + end + Mdct.inverse(PLAN256, x, 2, 2, z, 1, -2 * gain) + for n = 0, 191 do + y[257 + n] = z[n + 65] + end + for n = 192, 255 do + y[257 + n] = -z[n - 191] + end + else + Mdct.inverse(PLAN512, x, 1, 1, y, 1, -2 * gain) + end + local p = base + for n = 1, 256 do + out[p] = y[n] * w[n] + d[n] + d[n] = y[n + 256] * w[n + 256] + p += step + end +end + +-- the output index of each slot (1 .. 5 full bandwidth, 6 LFE) in WAVE order: L R C LFE surrounds +local ORDER: { [number]: { number } } = { + [0] = { 1, 2 }, + { 1 }, + { 1, 2 }, + { 1, 3, 2 }, + { 1, 2, 3 }, + { 1, 3, 2, 4 }, + { 1, 2, 3, 4 }, + { 1, 3, 2, 4, 5 }, +} +local HAS_C = { [0] = false, true, false, true, false, true, false, true } + +@native function Decode.frame(st: State, buf: buffer, len: number, drc: number): (number?, string?) + if len < 8 or buffer.len(buf) < len + Decode.PAD then + return nil, "truncated frame" + end + B, P = buf, 32 + local fscod = bits(2) + bits(6) + local bsid = bits(5) + if bsid > 8 then + B = buffer.create(0) + return nil, "unsupported: bsid " .. bsid .. (if bsid > 10 then " (E-AC-3)" else " (reduced sample rate)") + end + if fscod == 3 then + B = buffer.create(0) + return nil, "bad sample rate code" + end + bits(3) -- bsmod + local acmod = bits(3) + if band(acmod, 1) == 1 and acmod ~= 1 then + bits(2) + end + if band(acmod, 4) ~= 0 then + bits(2) + end + if acmod == 2 then + bits(2) + end + local lfeon = bits(1) == 1 + for _ = 1, if acmod == 0 then 2 else 1 do + bits(5) + if bits(1) == 1 then + bits(8) + end + if bits(1) == 1 then + bits(8) + end + if bits(1) == 1 then + bits(7) + end + end + bits(2) + if bits(1) == 1 then + bits(14) + end + if bits(1) == 1 then + bits(14) + end + if bits(1) == 1 then + P += (bits(6) + 1) * 8 + end + local nf = NFCHANS[acmod] + local channels = nf + (if lfeon then 1 else 0) + if st.acmod ~= acmod or st.lfeon ~= lfeon then + local order = ORDER[acmod] + local map = table.create(6, 0) + local nfront = if HAS_C[acmod] then 3 elseif acmod == 1 then 1 else 2 + for ch = 1, nf do + local o = order[ch] + map[ch] = if lfeon and o > nfront then o + 1 else o + end + if lfeon then + map[LFE] = nfront + 1 + end + st.map = map + st.pcm = table.create(1536 * channels, 0) + Decode.reset(st) + end + st.fscod, st.acmod, st.lfeon, st.nfchans, st.channels, st.drc = fscod, acmod, lfeon, nf, channels, drc + local pcm = st.pcm + local limit = len * 8 - 16 -- crc2 + for blk = 0, 5 do + st.blocks[blk + 1] = P + local ok, err = audblk(st, blk, limit) + if not ok then + B = buffer.create(0) + return nil, err + end + local base = blk * 256 * channels + for ch = 1, nf do + local g = st.dynrng[if acmod == 0 and ch == 2 then 2 else 1] + synth(st, ch, st.blksw[ch], g, pcm, base + st.map[ch], channels) + end + if lfeon then + synth(st, LFE, false, st.dynrng[1], pcm, base + st.map[LFE], channels) + end + end + B = buffer.create(0) + return 1536, nil +end + +return Decode +end +__FILES["codecs/audio/Ac3/Tables"] = function() + +-- codecs/audio/Ac3/Tables: transcribed from ATSC A/52:2018 section 7.2.3 (bit allocation tables) and section 5.4 (frame +-- sizes); masktab is derived from bndtab / bndsz. No third-party code. +local T = {} + +T.SLOWDEC = { 0x0f, 0x11, 0x13, 0x15 } +T.FASTDEC = { 0x3f, 0x53, 0x67, 0x7b } +T.SLOWGAIN = { 0x540, 0x4d8, 0x478, 0x410 } +T.DBPBTAB = { 0x000, 0x700, 0x900, 0xb00 } +T.FLOORTAB = { 0x2f0, 0x2b0, 0x270, 0x230, 0x1f0, 0x170, 0x0f0, 0xf800 } +T.FASTGAIN = { 0x080, 0x100, 0x180, 0x200, 0x280, 0x300, 0x380, 0x400 } + +-- bit allocation bands: first bin and width (Table 7.12) +T.BNDTAB = { + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, + 25, 26, 27, 28, 31, 34, 37, 40, 43, 46, 49, 55, 61, 67, 73, 79, 85, 97, 109, 121, 133, 157, 181, 205, 229, +} +T.BNDSZ = { + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 6, 6, 6, 6, 6, 6, 12, 12, 12, 12, 24, 24, 24, 24, 24, +} +-- masktab (Table 7.13; bins 253 .. 255 map to 0) +T.MASKTAB = table.create(256, 0) +for b = 1, 50 do + for k = T.BNDTAB[b], T.BNDTAB[b] + T.BNDSZ[b] - 1 do + T.MASKTAB[k + 1] = b - 1 + end +end + +-- log-addition table (Table 7.14) +T.LATAB = { + 0x0040, 0x003f, 0x003e, 0x003d, 0x003c, 0x003b, 0x003a, 0x0039, 0x0038, 0x0037, 0x0036, 0x0035, 0x0034, 0x0034, 0x0033, 0x0032, + 0x0031, 0x0030, 0x002f, 0x002f, 0x002e, 0x002d, 0x002c, 0x002c, 0x002b, 0x002a, 0x0029, 0x0029, 0x0028, 0x0027, 0x0026, 0x0026, + 0x0025, 0x0024, 0x0024, 0x0023, 0x0023, 0x0022, 0x0021, 0x0021, 0x0020, 0x0020, 0x001f, 0x001e, 0x001e, 0x001d, 0x001d, 0x001c, + 0x001c, 0x001b, 0x001b, 0x001a, 0x001a, 0x0019, 0x0019, 0x0018, 0x0018, 0x0017, 0x0017, 0x0016, 0x0016, 0x0015, 0x0015, 0x0015, + 0x0014, 0x0014, 0x0013, 0x0013, 0x0013, 0x0012, 0x0012, 0x0012, 0x0011, 0x0011, 0x0011, 0x0010, 0x0010, 0x0010, 0x000f, 0x000f, + 0x000f, 0x000e, 0x000e, 0x000e, 0x000d, 0x000d, 0x000d, 0x000d, 0x000c, 0x000c, 0x000c, 0x000c, 0x000b, 0x000b, 0x000b, 0x000b, + 0x000a, 0x000a, 0x000a, 0x000a, 0x000a, 0x0009, 0x0009, 0x0009, 0x0009, 0x0009, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, + 0x0007, 0x0007, 0x0007, 0x0007, 0x0007, 0x0007, 0x0006, 0x0006, 0x0006, 0x0006, 0x0006, 0x0006, 0x0006, 0x0006, 0x0005, 0x0005, + 0x0005, 0x0005, 0x0005, 0x0005, 0x0005, 0x0005, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, + 0x0004, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0002, + 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, + 0x0002, 0x0002, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, + 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, + 0x0001, 0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, +} + +-- hearing threshold (Table 7.15): HTH[fscod + 1][band + 1] +T.HTH = { + { + 0x04d0, 0x04d0, 0x0440, 0x0400, 0x03e0, 0x03c0, 0x03b0, 0x03b0, 0x03a0, 0x03a0, + 0x03a0, 0x03a0, 0x03a0, 0x0390, 0x0390, 0x0390, 0x0380, 0x0380, 0x0370, 0x0370, + 0x0360, 0x0360, 0x0350, 0x0350, 0x0340, 0x0340, 0x0330, 0x0320, 0x0310, 0x0300, + 0x02f0, 0x02f0, 0x02f0, 0x02f0, 0x0300, 0x0310, 0x0340, 0x0390, 0x03e0, 0x0420, + 0x0460, 0x0490, 0x04a0, 0x0460, 0x0440, 0x0440, 0x0520, 0x0800, 0x0840, 0x0840, + }, + { + 0x04f0, 0x04f0, 0x0460, 0x0410, 0x03e0, 0x03d0, 0x03c0, 0x03b0, 0x03b0, 0x03a0, + 0x03a0, 0x03a0, 0x03a0, 0x03a0, 0x0390, 0x0390, 0x0390, 0x0380, 0x0380, 0x0380, + 0x0370, 0x0370, 0x0360, 0x0360, 0x0350, 0x0350, 0x0340, 0x0340, 0x0320, 0x0310, + 0x0300, 0x02f0, 0x02f0, 0x02f0, 0x02f0, 0x0300, 0x0320, 0x0350, 0x0390, 0x03e0, + 0x0420, 0x0450, 0x04a0, 0x0490, 0x0460, 0x0440, 0x0480, 0x0630, 0x0840, 0x0840, + }, + { + 0x0580, 0x0580, 0x04b0, 0x0450, 0x0420, 0x03f0, 0x03e0, 0x03d0, 0x03c0, 0x03b0, + 0x03b0, 0x03b0, 0x03a0, 0x03a0, 0x03a0, 0x03a0, 0x03a0, 0x03a0, 0x03a0, 0x03a0, + 0x0390, 0x0390, 0x0390, 0x0390, 0x0380, 0x0380, 0x0380, 0x0370, 0x0360, 0x0350, + 0x0340, 0x0330, 0x0320, 0x0310, 0x0300, 0x02f0, 0x02f0, 0x02f0, 0x0300, 0x0310, + 0x0330, 0x0350, 0x03c0, 0x0410, 0x0470, 0x04a0, 0x0460, 0x0440, 0x0450, 0x04e0, + }, +} + +-- bit allocation pointers (Table 7.16) +T.BAPTAB = { + 0, 1, 1, 1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 10, + 10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, +} + +-- words per syncframe (Table 5.18) for frmsizecod // 2 (the nominal bit rate in kbps) and fscod: 48 kHz = 2 x rate, +-- 32 kHz = 3 x rate, 44.1 kHz = floor(rate x 1536000 / 705600) + (frmsizecod & 1) +T.BITRATES = { 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 448, 512, 576, 640 } +T.RATES = { 48000, 44100, 32000 } + +function T.frameWords(fscod: number, frmsizecod: number): number + local kbps = T.BITRATES[frmsizecod // 2 + 1] + if not kbps or fscod > 2 then + return 0 + end + if fscod == 0 then + return 2 * kbps + elseif fscod == 2 then + return 3 * kbps + end + return kbps * 1536000 // 705600 + frmsizecod % 2 +end + +return T +end +__FILES["codecs/audio/Adpcm/Decoder"] = function() + +-- codecs/audio/Adpcm/Decoder: the streaming Types.Decoder over packetised ADPCM (ADX, VAG, BRSTM, raw IMA) with exact seeking. +-- New in rosetta. +local Err = __include("core/Err") +local Stream = __include("codecs/audio/Stream") +local Adpcm = __include("codecs/audio/Adpcm") + +local Decoder = {} + +type Spec = { + count: number, + packetFrames: number, + frames: number, + state: buffer, + decode: (i: number, out: buffer) -> (number?, Err.Err?), + restore: ((i: number) -> boolean)?, +} + +function Decoder.packets(dec: any, spec: Spec): (any, Err.Err?) + local ch = dec.channels + local pf = spec.packetFrames + local st = spec.state + local out = buffer.create(pf * ch * 4) + local decodeP = spec.decode + local restore = spec.restore + local snaps: { [number]: buffer } = {} + local nextPacket = 1 + local function snap(i: number) + if not snaps[i] then + local b = buffer.create(buffer.len(st)) + buffer.copy(b, 0, st) + snaps[i] = b + end + end + snap(1) + local function decode(i: number): (number?, Err.Err?) + if i ~= nextPacket then + if snaps[i] then + buffer.copy(st, 0, snaps[i]) + elseif restore and restore(i) then + else + local j = i - 1 + while j > 1 and not snaps[j] do + j -= 1 + end + buffer.copy(st, 0, snaps[j]) + for k = j, i - 1 do + local n, e = decodeP(k, out) + if not n then + return nil, e + end + snap(k + 1) + end + end + end + local n, e = decodeP(i, out) + if n then + nextPacket = i + 1 + snap(i + 1) + end + return n, e + end + return Stream.packets(dec, { + count = spec.count, + start = function(i: number): number + return (i - 1) * pf + end, + decode = decode, + pcm = function(): buffer + return out + end, + reset = function() end, + stop = spec.frames, + }) +end + +local FRAME: { [string]: number } = { psx = 16, adx = 18, dsp = 8, s16be = 2, s16le = 2, s8 = 1 } -- bytes per frame +local SPF: { [string]: number } = { psx = 28, adx = 32, dsp = 14, s16be = 1, s16le = 1, s8 = 1 } -- samples per frame + +local function pcm(kind: string, src: buffer, p: number, n: number, dst: buffer, d: number, ds: number) + if kind == "s8" then + for k = 0, n - 1 do + buffer.writef32(dst, (d + k * ds) * 4, buffer.readi8(src, p + k) / 128) + end + elseif kind == "s16le" then + for k = 0, n - 1 do + buffer.writef32(dst, (d + k * ds) * 4, buffer.readi16(src, p + k * 2) / 32768) + end + else + for k = 0, n - 1 do + local v = buffer.readu8(src, p + k * 2) * 256 + buffer.readu8(src, p + k * 2 + 1) + buffer.writef32(dst, (d + k * ds) * 4, (if v >= 32768 then v - 65536 else v) / 32768) + end + end +end + +type InterleavedSpec = { + kind: "psx" | "adx" | "dsp" | "s16be" | "s16le" | "s8", + buf: buffer, + offset: number, + size: number, + interleave: number, + lastInterleave: number?, -- bytes per channel in the last row (BRSTM's padded last block), default interleave + frames: number?, + c1: number?, + c2: number?, + v3: boolean?, + coefs: buffer?, -- dsp: 16 i32 per channel + hist: { number }?, + restore: ((row: number, st: buffer) -> boolean)?, -- the exact history at the start of a row (BRSTM ADPC) +} + +function Decoder.interleaved(dec: any, spec: InterleavedSpec): (any, Err.Err?) + local ch = dec.channels + local kind = spec.kind + local fsize, spf = FRAME[kind], SPF[kind] + local il = spec.interleave + local last = spec.lastInterleave or il + if not fsize or ch < 1 or il < fsize or il % fsize ~= 0 or last < 0 or last > il then + return nil, Err.new(Err.CORRUPT, "bad interleave " .. tostring(il)) + end + local buf, base, size = spec.buf, spec.offset, spec.size + local rowBytes = il * ch + local rows = math.max(1, math.ceil(size / rowBytes)) + local function rowFrames(r: number): number + local width = if r == rows - 1 then last else il + -- channel c sits at c * width in the row: the last channel is the one a cut file shortens + local per = math.clamp(size - r * rowBytes - (ch - 1) * width, 0, width) + return (per // fsize) * spf + end + local fullFrames = (il // fsize) * spf + local total = (rows - 1) * fullFrames + rowFrames(rows - 1) + local frames = math.min(spec.frames or total, total) + local st = buffer.create(8 * ch) + if spec.hist then + for c = 0, ch - 1 do + buffer.writei32(st, c * 8, spec.hist[c * 2 + 1] or 0) + buffer.writei32(st, c * 8 + 4, spec.hist[c * 2 + 2] or 0) + end + end + local rowsPer = if spec.restore then 1 else math.max(1, 4096 // fullFrames) + local pf = rowsPer * fullFrames + local c1, c2, v3, coefs = spec.c1 or 0, spec.c2 or 0, spec.v3 == true, spec.coefs + local restore = spec.restore + dec.frames = frames + dec.duration = frames / dec.sampleRate + return Decoder.packets(dec, { + count = math.max(1, math.ceil(frames / pf)), + packetFrames = pf, + frames = frames, + state = st, + restore = if restore + then function(i: number): boolean + return restore(i - 1, st) + end + else nil, + decode = function(i: number, out: buffer): (number?, Err.Err?) + local got = 0 + for r = (i - 1) * rowsPer, math.min(i * rowsPer, rows) - 1 do + local n = math.min(rowFrames(r), frames - r * fullFrames) + if n <= 0 then + break + end + local nf = math.ceil(n / spf) + local width = if r == rows - 1 then last else il + for c = 0, ch - 1 do + local p = base + r * rowBytes + c * width + local d = got * ch + c + if kind == "psx" then + Adpcm.psx(buf, p, fsize, nf, st, c * 8, out, d, ch) + elseif kind == "adx" then + Adpcm.adx(buf, p, fsize, nf, c1, c2, v3, st, c * 8, out, d, ch) + elseif kind == "dsp" then + Adpcm.dsp(buf, p, n, coefs :: buffer, c * 64, st, c * 8, out, d, ch) + else + pcm(kind, buf, p, n, out, d, ch) + end + end + got += n + end + return got, nil + end, + }) +end + +type NibbleSpec = { + buf: buffer, + offset: number, + size: number, + hi: boolean?, -- the high nibble first (DVI / KVAG); default low first + frames: number?, +} + +-- IMA from predictor 0, step index 0; channel c in nibbles c, c + ch, ... +function Decoder.nibbles(dec: any, spec: NibbleSpec): (any, Err.Err?) + local ch = dec.channels + local buf, base = spec.buf, spec.offset + local frames = math.min(spec.frames or math.huge, (spec.size * 2) // ch) + local st = buffer.create(8 * ch) + local hi = spec.hi == true + dec.frames = frames + dec.duration = frames / dec.sampleRate + return Decoder.packets(dec, { + count = math.max(1, math.ceil(frames / 4096)), + packetFrames = 4096, + frames = frames, + state = st, + decode = function(i: number, out: buffer): (number?, Err.Err?) + local f0 = (i - 1) * 4096 + local n = math.min(4096, frames - f0) + for c = 0, ch - 1 do + Adpcm.ima(buf, base, f0 * ch + c, ch, n, hi, st, c * 8, out, c, ch) + end + return n, nil + end, + }) +end + +type BlockSpec = { + kind: "ms" | "ima_wav" | "ima_qt", + buf: buffer, + offset: number, + size: number, + blockAlign: number?, + frames: number?, + coefs: { number }?, -- ms: coefficient pairs, flat (default the 7 standard pairs) +} + +function Decoder.blockFrames(kind: string, ba: number, ch: number): number? + if kind == "ima_qt" then + return 64 + elseif kind == "ms" then + return if ba >= 7 * ch then (ba - 7 * ch) * 2 // ch + 2 else nil + end + return if ba >= 4 * ch then (ba - 4 * ch) * 2 // ch + 1 else nil +end + +function Decoder.blocks(dec: any, spec: BlockSpec): (any, Err.Err?) + local ch = dec.channels + local kind = spec.kind + local ba = if kind == "ima_qt" then 34 * ch else spec.blockAlign or 0 + local spb = Decoder.blockFrames(kind, ba, ch) + if not spb then + return nil, Err.new(Err.CORRUPT, "block of " .. ba .. " bytes is too small") + end + if spb * ch > 2 ^ 20 then + return nil, Err.new(Err.LIMIT, "ADPCM block too large") + end + local buf, base, size = spec.buf, spec.offset, spec.size + local full = size // ba + local rest = size - full * ba + local total = full * spb + if kind ~= "ima_qt" and rest > 0 then + if kind == "ms" then + total += if rest >= 7 * ch then math.min(spb, 2 + ((rest - 7 * ch) * 2) // ch) else 0 + elseif rest >= 4 * ch then + total += math.min(spb, 1 + ((rest - 4 * ch) // (4 * ch)) * 8) + end + end + local frames = math.min(spec.frames or total, total) + local ncoef = 7 + local cf = spec.coefs + if cf and #cf >= 2 then + ncoef = math.min(256, #cf // 2) + end + local coefs = buffer.create(ncoef * 8) + for k = 0, ncoef - 1 do + buffer.writei32(coefs, k * 8, if cf and #cf >= 2 then cf[k * 2 + 1] else Adpcm.MS_COEF1[k + 1]) + buffer.writei32(coefs, k * 8 + 4, if cf and #cf >= 2 then cf[k * 2 + 2] else Adpcm.MS_COEF2[k + 1]) + end + local scratch = buffer.create(20 * ch) + dec.frames = frames + dec.duration = frames / dec.sampleRate + dec.blockAlign = ba + dec.samplesPerBlock = spb + return Decoder.packets(dec, { + count = math.max(1, math.ceil(frames / spb)), + packetFrames = spb, + frames = frames, + state = scratch, + decode = function(i: number, out: buffer): (number?, Err.Err?) + local off = base + (i - 1) * ba + local avail = math.min(ba, base + size - off) + if kind == "ms" then + return Adpcm.msBlock(buf, off, avail, ch, spb, out, 0, coefs, ncoef, scratch), nil + elseif kind == "ima_wav" then + return Adpcm.imaWav(buf, off, avail, ch, spb, out, 0), nil + end + if avail < ba then + return 0, nil + end + for c = 0, ch - 1 do + Adpcm.imaQt(buf, off + c * 34, scratch, c * 8, out, c, ch) + end + return 64, nil + end, + }) +end + +return Decoder +end +__FILES["codecs/audio/Alac"] = function() + +-- codecs/audio/Alac: Apple Lossless (ALAC) decoder and encoder. +-- Written from the ALAC format as Apple published it; no third-party code. ALAC stores C L R ... for 3+ channels; the +-- API uses WAV order. +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Decode = __include("codecs/audio/Alac/Decode") +local Encode = __include("codecs/audio/Alac/Encode") + +local Alac = {} + +type Config = { + frameLength: number, + compatibleVersion: number, + bitDepth: number, + pb: number, + mb: number, + kb: number, + channels: number, + maxRun: number, + maxFrameBytes: number, + avgBitRate: number, + sampleRate: number, +} + +local TO_WAV: { { number } } = { + { 1 }, + { 1, 2 }, + { 3, 1, 2 }, + { 3, 1, 2, 4 }, + { 3, 1, 2, 4, 5 }, + { 3, 1, 2, 5, 6, 4 }, + { 3, 1, 2, 5, 6, 7, 4 }, + { 3, 7, 8, 1, 2, 5, 6, 4 }, +} +local ELEMENTS: { { number } } = { + { 1 }, + { 2 }, + { 1, 2 }, + { 1, 2, 1 }, + { 1, 2, 2 }, + { 1, 2, 2, 1 }, + { 1, 2, 2, 1, 1 }, + { 1, 2, 2, 2, 1 }, +} +Alac.TO_WAV = TO_WAV + +function Alac.config(buf: buffer, offset: number?, length: number?): (Config?, Err.Err?) + local r = Bytes.reader(buf, offset, length) + -- a QuickTime 'wave' payload may hold frma + alac atoms ahead of the cookie + for _ = 1, 2 do + local typ = r:peek(4, 4) + if typ == "frma" then + r:skip(12) + elseif typ == "alac" then + r:skip(12) + end + end + if r:remaining() < 24 then + return nil, Err.new(Err.TRUNCATED, "ALAC configuration is shorter than 24 bytes") + end + local c: Config = { + frameLength = r:u32be(), + compatibleVersion = r:u8(), + bitDepth = r:u8(), + pb = r:u8(), + mb = r:u8(), + kb = r:u8(), + channels = r:u8(), + maxRun = r:u16be(), + maxFrameBytes = r:u32be(), + avgBitRate = r:u32be(), + sampleRate = r:u32be(), + } + if c.compatibleVersion ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "ALAC version " .. c.compatibleVersion) + end + if c.frameLength < 1 or c.frameLength > 65536 then + return nil, Err.new(Err.CORRUPT, "bad ALAC frame length " .. c.frameLength) + end + if c.bitDepth ~= 16 and c.bitDepth ~= 20 and c.bitDepth ~= 24 and c.bitDepth ~= 32 then + return nil, Err.new(Err.UNSUPPORTED, "ALAC bit depth " .. c.bitDepth) + end + if c.channels < 1 or c.channels > 8 then + return nil, Err.new(Err.UNSUPPORTED, "ALAC with " .. c.channels .. " channels") + end + if c.kb < 1 or c.kb > 24 then + return nil, Err.new(Err.CORRUPT, "bad ALAC rice limit " .. c.kb) + end + return c, nil +end + +function Alac.cookie(c: Config): buffer + local w = Bytes.writer(24) + w:u32be(c.frameLength) + w:u8(0) + w:u8(c.bitDepth) + w:u8(c.pb) + w:u8(c.mb) + w:u8(c.kb) + w:u8(c.channels) + w:u16be(c.maxRun) + w:u32be(c.maxFrameBytes) + w:u32be(c.avgBitRate) + w:u32be(c.sampleRate) + return w:finish() +end + +type Decoder = { + config: Config, + pcm: { number }, + decode: (self: Decoder, buf: buffer, offset: number?, length: number?) -> (number?, Err.Err?), + state: Decode.State, +} + +local function decode(self: Decoder, buf: buffer, offset: number?, length: number?): (number?, Err.Err?) + local o = offset or 0 + local n = length or (buffer.len(buf) - o) + if o < 0 or n < 0 or o + n > buffer.len(buf) then + return nil, Err.new(Err.ARG, "packet range out of the buffer") + end + local frames, msg = Decode.frame(self.state, buf, o, n) + if not frames then + return nil, Err.new(Err.CORRUPT, msg or "bad packet", o) + end + local ch = self.config.channels + local src, dst = self.state.out, self.pcm + if ch <= 2 then + for i = 1, frames * ch do + dst[i] = src[i] + end + else + local map = TO_WAV[ch] + for f = 0, frames - 1 do + local base = f * ch + for k = 1, ch do + dst[base + map[k]] = src[base + k] + end + end + end + return frames, nil +end + +function Alac.decoder(cfg: Config): Decoder + return { + config = cfg, + pcm = table.create(cfg.frameLength * cfg.channels, 0), + decode = decode, + state = Decode.state(cfg), + } +end + +type Encoder = { + config: Config, + encode: (self: Encoder, samples: { number }, first: number, frames: number) -> (buffer?, Err.Err?), + state: Encode.State, + bytes: number, + frames: number, +} + +local function encode(self: Encoder, samples: { number }, first: number, frames: number): (buffer?, Err.Err?) + local cfg = self.config + if type(samples) ~= "table" or frames < 1 or frames > cfg.frameLength or frames % 1 ~= 0 then + return nil, Err.new(Err.ARG, "encode: 1 .. " .. cfg.frameLength .. " frames of interleaved integer samples") + end + if first < 1 or first + frames * cfg.channels - 1 > #samples then + return nil, Err.new(Err.ARG, "encode: the samples end early") + end + local ch = cfg.channels + local pkt = Encode.frame(self.state, samples, first, frames, TO_WAV[ch], ELEMENTS[ch]) + local n = buffer.len(pkt) + self.bytes += n + self.frames += frames + if n > cfg.maxFrameBytes then + cfg.maxFrameBytes = n + end + if self.frames > 0 then + cfg.avgBitRate = math.floor(self.bytes * 8 * cfg.sampleRate / self.frames) + end + return pkt, nil +end + +type EncoderOptions = { + sampleRate: number, + channels: number, + bitDepth: number?, + frameLength: number?, +} + +function Alac.encoder(opts: EncoderOptions): (Encoder?, Err.Err?) + if type(opts) ~= "table" then + return nil, Err.new(Err.ARG, "encoder: expected options") + end + local depth = opts.bitDepth or 16 + local ch = opts.channels + if depth ~= 16 and depth ~= 20 and depth ~= 24 then + return nil, Err.new(Err.ARG, "encoder: bitDepth 16, 20 or 24") + end + if type(ch) ~= "number" or ch < 1 or ch > 8 or ch % 1 ~= 0 then + return nil, Err.new(Err.ARG, "encoder: 1 .. 8 channels") + end + local sr = opts.sampleRate + if type(sr) ~= "number" or sr < 1 or sr % 1 ~= 0 then + return nil, Err.new(Err.ARG, "encoder: bad sampleRate") + end + local fl = opts.frameLength or 4096 + if fl < 16 or fl > 16384 or fl % 1 ~= 0 then + return nil, Err.new(Err.ARG, "encoder: frameLength 16 .. 16384") + end + local cfg: Config = { + frameLength = fl, + compatibleVersion = 0, + bitDepth = depth, + pb = 40, + mb = 10, + kb = 14, + channels = ch, + maxRun = 255, + maxFrameBytes = 0, + avgBitRate = 0, + sampleRate = sr, + } + return { + config = cfg, + encode = encode, + state = Encode.state(cfg), + bytes = 0, + frames = 0, + }, nil +end + +return Alac +end +__FILES["codecs/audio/Alac/Decode"] = @native function() + + + +-- codecs/audio/Alac/Decode: the ALAC frame decoder (SCE / CPE / LFE / DSE / FIL / END elements). +-- Written from the ALAC format as published by Apple (ALACDecoder / ag_dec / dp_dec, Apache 2.0; behaviour, not code). +local readu32, readu8 = buffer.readu32, buffer.readu8 +local byteswap, lshift, rshift, band, countlz, bnot = bit32.byteswap, bit32.lshift, bit32.rshift, bit32.band, bit32.countlz, bit32.bnot +local floor = math.floor + +local Decode = {} + +type State = { + frameLength: number, + bitDepth: number, + pb: number, + mb: number, + kb: number, + channels: number, + maxRun: number, + scratch: buffer, -- the packet + 16 zero bytes (reads past the end are safe; the overrun is checked) + pred: { { number } }, + mix: { { number } }, + shift: { number }, + out: { number }, +} + +local POW = table.create(64, 0) +for i = 0, 63 do + POW[i + 1] = 2 ^ i +end + +@native local function bitsAt(b: buffer, pos: number, n: number): number + local w = byteswap(readu32(b, rshift(pos, 3))) + return rshift(lshift(w, band(pos, 7)), 32 - n) +end + +@native local function signExtend(v: number, bits: number): number + local m = POW[bits + 1] + v = v % m + if v >= m / 2 then + v -= m + end + return v +end + +-- the adaptive Golomb-Rice value: unary prefix (escape after 9 ones: `bps` raw bits), then k bits +@native local function scalar(b: buffer, pos: number, k: number, m: number, bps: number): (number, number) + local w = lshift(byteswap(readu32(b, rshift(pos, 3))), band(pos, 7)) + local pre = countlz(bnot(w)) + if pre >= 9 then + pos += 9 + local v + if bps > 25 then + v = bitsAt(b, pos, bps - 16) * 65536 + bitsAt(b, pos + bps - 16, 16) + else + v = bitsAt(b, pos, bps) + end + return v, pos + bps + end + pos += pre + 1 + if k == 1 then + return pre, pos + end + local v = bitsAt(b, pos, k) + local x = pre * m + if v > 1 then + return x + v - 1, pos + k + end + return x, pos + k - 1 +end + +@native local function rice(b: buffer, pos: number, limit: number, out: { number }, n: number, bps: number, mult: number, st: State): number + local history = st.mb + local kb = st.kb + local signMod = 0 + local i = 1 + while i <= n do + if pos > limit then + return -1 -- each value reads at most 41 bits past here: inside the 16 padding bytes + end + local k = 31 - countlz(floor(history / 512) + 3) + if k > kb then + k = kb + end + local x + x, pos = scalar(b, pos, k, POW[k + 1] - 1, bps) + x += signMod + signMod = 0 + out[i] = if x % 2 == 0 then x / 2 else -(x + 1) / 2 + if x > 0xFFFF then + history = 0xFFFF + else + history += x * mult - floor(history * mult / 512) + end + if history < 128 and i < n then + if pos > limit then + return -1 + end + local lg = if history > 0 then 31 - countlz(history) else 0 + k = 7 - lg + floor((history + 16) / 64) + if k > kb then + k = kb + end + local run + run, pos = scalar(b, pos, k, POW[k + 1] - 1, 16) + if run > 0 then + if run > n - i then + return -1 + end + for j = i + 1, i + run do + out[j] = 0 + end + i += run + end + if run < 0xFFFF then + signMod = 1 -- the next value is not 0 (unless the run hit its maximum) + end + history = 0 + end + i += 1 + end + return pos +end + +@native local function predict(err: { number }, out: { number }, n: number, bps: number, coefs: { number }, order: number, quant: number) + out[1] = err[1] + if n <= 1 then + return + end + if order == 0 then + if out ~= err then + for i = 2, n do + out[i] = err[i] + end + end + return + end + if order == 31 then + for i = 2, n do + out[i] = signExtend(out[i - 1] + err[i], bps) + end + return + end + local i = 2 + while i <= order + 1 and i <= n do + out[i] = signExtend(out[i - 1] + err[i], bps) + i += 1 + end + local half = if quant > 0 then POW[quant] else 0 + local qd = POW[quant + 1] + -- coefs[1] multiplies the most recent sample + while i <= n do + local d = out[i - order - 1] + local val = 0 + for j = 1, order do + val += (out[i - j] - d) * coefs[j] + end + val = floor((val + half) / qd) + local e = err[i] + out[i] = signExtend(val + d + e, bps) + if e ~= 0 then + local es = if e > 0 then 1 else -1 + -- adapt from the oldest sample to the newest while the error keeps its sign + for j = order, 1, -1 do + if e * es <= 0 then + break + end + local v = d - out[i - j] + local sgn = if v > 0 then es elseif v < 0 then -es else 0 + coefs[j] -= sgn + e -= floor(v * sgn / qd) * (order - j + 1) + end + end + i += 1 + end +end + +@native function Decode.frame(st: State, buf: buffer, off: number, len: number): (number?, string?) + if len <= 0 then + return nil, "empty packet" + end + local b = st.scratch + if buffer.len(b) < len + 16 then + b = buffer.create(len + 64) + st.scratch = b + end + buffer.copy(b, 0, buf, off, len) + buffer.fill(b, len, 0, 16) + local limit = len * 8 + local pos = 0 + local channels = st.channels + local ch = 0 + local frames = -1 + local out = st.out + while true do + if pos + 3 > limit then + return nil, "frame runs past the end" + end + local tag = bitsAt(b, pos, 3) + pos += 3 + if tag == 7 then -- END + break + elseif tag == 0 or tag == 1 or tag == 3 then -- SCE / CPE / LFE + local nch = if tag == 1 then 2 else 1 + if ch + nch > channels then + return nil, "more channels than the configuration" + end + pos += 4 -- element instance tag + if bitsAt(b, pos, 12) ~= 0 then + return nil, "bad element header" + end + pos += 12 + local h = bitsAt(b, pos, 4) + pos += 4 + local partial = rshift(h, 3) + local shiftBytes = band(rshift(h, 1), 3) + local escape = band(h, 1) + if shiftBytes == 3 then + return nil, "bad shift" + end + local n = st.frameLength + if partial == 1 then + n = bitsAt(b, pos, 16) * 65536 + bitsAt(b, pos + 16, 16) + pos += 32 + end + if n < 1 or n > st.frameLength then + return nil, "bad frame length " .. n + end + if frames >= 0 and n ~= frames then + return nil, "elements of different lengths" + end + frames = n + if #out < n * channels then + for k = #out + 1, n * channels do + out[k] = 0 + end + end + local shift = shiftBytes * 8 + local bps = st.bitDepth - shift + nch - 1 + if bps > 32 or bps < 1 then + return nil, "bad sample size" + end + if pos > limit then + return nil, "frame runs past the end" + end + local mixBits, mixRes = 0, 0 + local p0, p1 = st.pred[1], st.pred[2] + local m0, m1 = st.mix[1], st.mix[2] + local shiftBuf = st.shift + if escape == 0 then + mixBits = bitsAt(b, pos, 8) + mixRes = bitsAt(b, pos + 8, 8) + pos += 16 + if mixRes >= 128 then + mixRes -= 256 + end + local mode, denShift, pbFactor, order = {}, {}, {}, {} + local coefs = { {}, {} } + for c = 1, nch do + 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) :: 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 + for j = 1, order[c] do + local v = bitsAt(b, pos, 16) + pos += 16 + coefs[c][j] = if v >= 32768 then v - 65536 else v + end + end + if pos > limit then + return nil, "frame runs past the end" + end + local shiftPos = pos + if shift > 0 then + pos += shift * n * nch + end + for c = 1, nch do + local p = if c == 1 then p0 else p1 + local mb = if c == 1 then m0 else m1 + pos = rice(b, pos, limit, p, n, bps, floor(st.pb * pbFactor[c] / 4), st) + if pos < 0 or pos > limit then + return nil, "bad residuals" + end + if mode[c] == 15 then + predict(p, p, n, bps, {}, 31, 0) + elseif mode[c] ~= 0 then + return nil, "unknown prediction mode " .. mode[c] + end + predict(p, mb, n, bps, coefs[c], order[c], denShift[c]) + end + if shift > 0 then + local sp = shiftPos + for i = 1, n * nch do + shiftBuf[i] = bitsAt(b, sp, shift) + sp += shift + end + end + else + -- uncompressed: interleaved samples of bitDepth bits + local bits = st.bitDepth + if pos + n * nch * bits > limit then + return nil, "frame runs past the end" + end + for i = 1, n do + for c = 1, nch do + local v + if bits > 25 then + v = bitsAt(b, pos, bits - 16) * 65536 + bitsAt(b, pos + bits - 16, 16) + else + v = bitsAt(b, pos, bits) + end + pos += bits + v = signExtend(v, bits) + if c == 1 then + m0[i] = v + else + m1[i] = v + end + end + end + shift = 0 + end + local sm = POW[shift + 1] + if nch == 2 then + local den = POW[mixBits + 1] + for i = 1, n do + local u, v = m0[i], m1[i] + local l, r + if mixRes ~= 0 then + l = u + v - floor(mixRes * v / den) + r = l - v + else + l, r = u, v + end + if shift > 0 then + l = l * sm + shiftBuf[2 * i - 1] + r = r * sm + shiftBuf[2 * i] + end + local o = (i - 1) * channels + ch + 1 + out[o] = l + out[o + 1] = r + end + else + for i = 1, n do + local v = m0[i] + if shift > 0 then + v = v * sm + shiftBuf[i] + end + out[(i - 1) * channels + ch + 1] = v + end + end + ch += nch + elseif tag == 4 then -- DSE + pos += 4 + local align = bitsAt(b, pos, 1) + local count = bitsAt(b, pos + 1, 8) + pos += 9 + if count == 255 then + count += bitsAt(b, pos, 8) + pos += 8 + end + if align == 1 then + pos = (pos + 7) // 8 * 8 + end + pos += count * 8 + elseif tag == 6 then -- FIL + local count = bitsAt(b, pos, 4) + pos += 4 + if count == 15 then + count += bitsAt(b, pos, 8) - 1 + pos += 8 + end + pos += count * 8 + else + return nil, "unsupported element " .. tag + end + if pos > limit then + return nil, "frame runs past the end" + end + end + if frames < 0 then + return 0, nil + end + if ch < channels then + for i = 1, frames do + for c = ch + 1, channels do + out[(i - 1) * channels + c] = 0 + end + end + end + return frames, nil +end + +@native function Decode.state(cfg: any): State + local n = cfg.frameLength + return { + frameLength = n, + bitDepth = cfg.bitDepth, + pb = cfg.pb, + mb = cfg.mb, + kb = cfg.kb, + channels = cfg.channels, + maxRun = cfg.maxRun, + scratch = buffer.create(math.max(64, cfg.maxFrameBytes or 0) + 64), + pred = { table.create(n, 0), table.create(n, 0) }, + mix = { table.create(n, 0), table.create(n, 0) }, + shift = table.create(n * 2, 0), + out = table.create(n * cfg.channels, 0), + } +end + +local _ = readu8 +return Decode +end +__FILES["codecs/audio/Alac/Encode"] = @native function() + + + +-- codecs/audio/Alac/Encode: an ALAC frame encoder (mixBits 2, LPC orders 4 / 8 with denShift 9, escape frames). +-- Written from the ALAC format; no third-party code. +local band, rshift, bor, lshift, countlz = bit32.band, bit32.rshift, bit32.bor, bit32.lshift, bit32.countlz +local readu8, writeu8 = buffer.readu8, buffer.writeu8 +local floor, abs = math.floor, math.abs + +local Encode = {} + +local POW = table.create(64, 0) +for i = 0, 63 do + POW[i + 1] = 2 ^ i +end + +local DENSHIFT = 9 +local PB_FACTOR = 4 + +type State = { + frameLength: number, + bitDepth: number, + pb: number, + mb: number, + kb: number, + channels: number, + out: buffer, + pos: number, + cap: number, + u: { number }, + v: { number }, + err: { number }, + work: { number }, +} + +@native local function put(st: State, v: number, n: number) + local pos = st.pos + if pos + n > st.cap then + st.pos = st.cap + 1 -- overflow: the caller falls back to an uncompressed frame + return + end + local b = st.out + while n > 0 do + local byte = rshift(pos, 3) + local free = 8 - band(pos, 7) + local take = if n < free then n else free + local bits = band(rshift(v, n - take), POW[take + 1] - 1) + writeu8(b, byte, bor(readu8(b, byte), lshift(bits, free - take))) + pos += take + n -= take + end + st.pos = pos +end + +@native local function putBig(st: State, v: number, n: number) + if n > 24 then + local lo = v % 65536 + put(st, (v - lo) / 65536, n - 16) + put(st, lo, 16) + else + put(st, v, n) + end +end + +@native local function signExtend(v: number, bits: number): number + local m = POW[bits + 1] + v = v % m + if v >= m / 2 then + v -= m + end + return v +end + +@native local function scalarBits(x: number, k: number, m: number, bps: number): number + local pre = if k == 1 then x else floor(x / m) + if pre >= 9 then + return 9 + bps + end + if k == 1 then + return pre + 1 + end + local r = x - pre * m + return pre + 1 + (if r == 0 then k - 1 else k) +end + +@native local function scalar(st: State, x: number, k: number, m: number, bps: number) + local pre = if k == 1 then x else floor(x / m) + if pre >= 9 then + put(st, 511, 9) + putBig(st, x, bps) + return + end + put(st, POW[pre + 2] - 2, pre + 1) + if k ~= 1 then + local r = x - pre * m + if r == 0 then + put(st, 0, k - 1) + else + put(st, r + 1, k) + end + end +end + +@native local function rice(st: State, e: { number }, n: number, bps: number, mult: number, write: boolean): number + local history = st.mb + local kb = st.kb + local signMod = 0 + local bits = 0 + local i = 1 + while i <= n do + local k = 31 - countlz(floor(history / 512) + 3) + if k > kb then + k = kb + end + local v = e[i] + local zz = if v >= 0 then 2 * v else -2 * v - 1 + local x = zz - signMod + signMod = 0 + local m = POW[k + 1] - 1 + if write then + scalar(st, x, k, m, bps) + else + bits += scalarBits(x, k, m, bps) + end + if zz > 0xFFFF then -- the decoder adapts on the value with its sign modifier added back + history = 0xFFFF + else + history += zz * mult - floor(history * mult / 512) + end + if history < 128 and i < n then + local lg = if history > 0 then 31 - countlz(history) else 0 + k = 7 - lg + floor((history + 16) / 64) + if k > kb then + k = kb + end + local run = 0 + while i + run < n and e[i + run + 1] == 0 and run < 0xFFFF do + run += 1 + end + m = POW[k + 1] - 1 + if write then + scalar(st, run, k, m, 16) + else + bits += scalarBits(run, k, m, 16) + end + i += run + if run < 0xFFFF then + signMod = 1 + end + history = 0 + end + i += 1 + end + return bits +end + +-- residuals of x[1..n] under the decoder's adaptive FIR starting from coefs (adapted in place, like the decoder) +@native local function residuals(x: { number }, e: { number }, n: number, bps: number, coefs: { number }, order: number, quant: number) + e[1] = x[1] + if n <= 1 then + return + end + local i = 2 + while i <= order + 1 and i <= n do + e[i] = signExtend(x[i] - x[i - 1], bps) + i += 1 + end + local half = POW[quant] + local qd = POW[quant + 1] + while i <= n do + local d = x[i - order - 1] + local val = 0 + for j = 1, order do + val += (x[i - j] - d) * coefs[j] + end + val = floor((val + half) / qd) + local r = signExtend(x[i] - val - d, bps) + e[i] = r + if r ~= 0 then + local es = if r > 0 then 1 else -1 + for j = order, 1, -1 do + if r * es <= 0 then + break + end + local v = d - x[i - j] + local sgn = if v > 0 then es elseif v < 0 then -es else 0 + coefs[j] -= sgn + r -= floor(v * sgn / qd) * (order - j + 1) + end + end + i += 1 + end +end + +@native local function lpc(x: { number }, n: number, order: number, work: { number }): { number } + local ac = table.create(order + 1, 0) + for i = 1, n do + local t = (2 * (i - 1) - (n - 1)) / (n + 1) + work[i] = x[i] * (1 - t * t) + end + for lag = 0, order do + local s = 0 + for i = lag + 1, n do + s += work[i] * work[i - lag] + end + ac[lag + 1] = s + end + local coefs = table.create(order, 0) + if ac[1] <= 0 then + return coefs + end + ac[1] *= 1.0001 -- a little white noise: keeps the recursion stable + local a = table.create(order + 1, 0) + local tmp = table.create(order + 1, 0) + local errv = ac[1] + for i = 1, order do + local acc = ac[i + 1] + for j = 1, i - 1 do + acc -= a[j] * ac[i - j + 1] + end + local kc = acc / errv + for j = 1, i - 1 do + tmp[j] = a[j] - kc * a[i - j] + end + for j = 1, i - 1 do + a[j] = tmp[j] + end + a[i] = kc + errv *= (1 - kc * kc) + if errv <= 0 then + break + end + end + local scale = POW[DENSHIFT + 1] + for j = 1, order do + coefs[j] = math.clamp(floor(a[j] * scale + 0.5), -32768, 32767) + end + return coefs +end + +@native local function analyse(st: State, x: { number }, n: number, bps: number): (number, { number }, number) + local mult = floor(st.pb * PB_FACTOR / 4) + local bestOrder, bestCoefs, bestBits = 0, {}, math.huge + for _, order in { 4, 8 } do + if order >= n then + continue + end + local coefs = lpc(x, n, order, st.work) + local trial = table.clone(coefs) + residuals(x, st.err, n, bps, trial, order, DENSHIFT) + local bits = rice(st, st.err, n, bps, mult, false) + order * 16 + if bits < bestBits then + bestOrder, bestCoefs, bestBits = order, coefs, bits + end + end + if bestBits == math.huge then + -- tiny frames: first-order prediction (order 31 is only a decoder mode; order 0 = no prediction) + for i = 1, n do + st.err[i] = x[i] + end + return 0, {}, rice(st, st.err, n, bps, mult, false) + end + return bestOrder, bestCoefs, bestBits +end + +@native function Encode.frame(st: State, samples: { number }, first: number, frames: number, map: { number }, elements: { number }): buffer + local channels, depth = st.channels, st.bitDepth + local n = frames + local partial = n ~= st.frameLength + local rawBits = n * channels * depth + local need = rawBits + 64 * #elements + 64 + if st.cap < need + 8 * 32 * 2 * #elements * 16 then + local bytes = (need + 8 * 32 * 2 * #elements * 16) // 8 + 16 + st.out = buffer.create(bytes) + st.cap = bytes * 8 + end + buffer.fill(st.out, 0, 0) + st.pos = 0 + local u, v = st.u, st.v + local mult = floor(st.pb * PB_FACTOR / 4) + local compressed = true + local ch = 1 + for _, nch in elements do + local a, b = map[ch], map[ch + 1] + local bps = depth + nch - 1 + local mixRes = 0 + if nch == 2 then + local best = math.huge + for res = 0, 4 do + local cost = 0 + local pu, pv = 0, 0 + for i = 0, n - 1 do + local l = samples[first + i * channels + a - 1] + local r = samples[first + i * channels + b - 1] + local uu, vv + if res == 0 then + uu, vv = l, r + else + uu, vv = floor((res * l + (4 - res) * r) / 4), l - r + end + cost += abs(uu - pu) + abs(vv - pv) + pu, pv = uu, vv + end + if cost < best then + best, mixRes = cost, res + end + end + for i = 1, n do + local l = samples[first + (i - 1) * channels + a - 1] + local r = samples[first + (i - 1) * channels + b - 1] + if mixRes == 0 then + u[i], v[i] = l, r + else + u[i], v[i] = floor((mixRes * l + (4 - mixRes) * r) / 4), l - r + end + end + else + for i = 1, n do + u[i] = samples[first + (i - 1) * channels + a - 1] + end + end + put(st, if nch == 2 then 1 else 0, 3) + put(st, 0, 4) + put(st, 0, 12) + put(st, if partial then 1 else 0, 1) + put(st, 0, 2) + put(st, 0, 1) + if partial then + putBig(st, n, 32) + end + put(st, if mixRes == 0 then 0 else 2, 8) + put(st, mixRes, 8) + local orders, coefsList = {}, {} + for c = 1, nch do + local x = if c == 1 then u else v + local order, coefs = analyse(st, x, n, bps) + orders[c], coefsList[c] = order, coefs + put(st, 0 * 16 + DENSHIFT, 8) -- mode 0, denShift + put(st, PB_FACTOR * 32 + order, 8) + for j = 1, order do + put(st, coefs[j] % 65536, 16) + end + end + for c = 1, nch do + local x = if c == 1 then u else v + local order = orders[c] + if order == 0 then + for i = 1, n do + st.err[i] = x[i] + end + else + residuals(x, st.err, n, bps, table.clone(coefsList[c]), order, DENSHIFT) + end + rice(st, st.err, n, bps, mult, true) + end + ch += nch + if st.pos > rawBits + 64 * #elements then + compressed = false + break + end + end + if not compressed then + buffer.fill(st.out, 0, 0) + st.pos = 0 + ch = 1 + for _, nch in elements do + put(st, if nch == 2 then 1 else 0, 3) + put(st, 0, 4) + put(st, 0, 12) + put(st, if partial then 1 else 0, 1) + put(st, 0, 2) + put(st, 1, 1) + if partial then + putBig(st, n, 32) + end + for i = 0, n - 1 do + for c = 0, nch - 1 do + putBig(st, samples[first + i * channels + map[ch + c] - 1] % POW[depth + 1], depth) + end + end + ch += nch + end + end + put(st, 7, 3) -- END + local bytes = (st.pos + 7) // 8 + local pkt = buffer.create(bytes) + buffer.copy(pkt, 0, st.out, 0, bytes) + return pkt +end + +@native function Encode.state(cfg: any): State + local n = cfg.frameLength + return { + frameLength = n, + bitDepth = cfg.bitDepth, + pb = cfg.pb, + mb = cfg.mb, + kb = cfg.kb, + channels = cfg.channels, + out = buffer.create(16), + pos = 0, + cap = 0, + u = table.create(n, 0), + v = table.create(n, 0), + err = table.create(n, 0), + work = table.create(n, 0), + } +end + +return Encode +end +__FILES["codecs/audio/Ape"] = function() + +-- codecs/audio/Ape: the Monkey's Audio codec (.ape), file versions 3.95 and later. +-- Ported from the Monkey's Audio SDK 13.28 (Matthew T. Ashland, BSD 3-clause since v10, licenses/monkeys-audio-LICENSE.txt): +-- APEHeader.cpp, APEInfo / APEDecompress.cpp. Not supported: pre-3.95 (UNSUPPORTED), the pre-8.50 "interim" 24-bit re-decode. +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Decode = __include("codecs/audio/Ape/Decode") + +local Ape = {} + +type Info = { + version: number, -- file version * 1000 (3990) + programVersion: number, + level: number, -- 1000 (fast) .. 5000 (insane) + flags: number, + channels: number, + sampleRate: number, + bitsPerSample: number, + float: boolean, + blocksPerFrame: number, + finalFrameBlocks: number, + totalFrames: number, + totalBlocks: number, + frameStart: { number }, + firstFrame: number, -- byte offset of frame 1 (the word alignment origin) + dataEnd: number, + limit: number, + md5: string?, +} + +local FLAG_8, FLAG_24, FLAG_PEAK, FLAG_SEEKN, FLAG_WAVHDR, FLAG_FLOAT = 1, 8, 4, 16, 32, 4096 + +function Ape.find(buf: buffer, base: number, limit: number): number? + local at = base + if limit - at >= 10 and buffer.readstring(buf, at, 3) == "ID3" then + local size = 0 + for i = 6, 9 do + size = size * 128 + bit32.band(buffer.readu8(buf, at + i), 127) + end + local footer = bit32.band(buffer.readu8(buf, at + 5), 16) ~= 0 + at += size + (if footer then 20 else 10) + if not footer then + while at < limit and buffer.readu8(buf, at) == 0 do + at += 1 + end + end + end + if at + 4 > limit then + return nil + end + local id = buffer.readstring(buf, at, 4) + if id == "MAC " or id == "MACF" then + return at + end + local s = buffer.readstring(buf, at, math.min(limit - at, 1048576)) + local k = string.find(s, "MAC ", 1, true) + return if k then at + k - 1 else nil +end + +function Ape.info(buf: buffer, base: number, limit: number): (Info?, Err.Err?) + local at = Ape.find(buf, base, limit) + if not at then + return nil, Err.new(Err.CORRUPT, "no Monkey's Audio header") + end + local junk = at - base -- seek offsets count from the start of the APE data (after any junk / ID3v2) + local r = Bytes.reader(buf, at, limit - at) + r:skip(4) + local version = r:u16le() + if r.err then + return nil, r.err + end + if version < 3950 then + return nil, Err.new(Err.UNSUPPORTED, "Monkey's Audio file version " .. version .. " (3950 and later are supported)") + end + local info: any = { version = version, programVersion = 0 } + local seekCount, seekAt + if version >= 3980 then + info.programVersion = r:u16le() + local descBytes, headBytes, seekBytes, hdrDataBytes = r:u32le(), r:u32le(), r:u32le(), r:u32le() + local dataLo, dataHi, termBytes = r:u32le(), r:u32le(), r:u32le() + local md5 = r:string(16) + r:seek(descBytes) + info.level = r:u16le() + info.flags = r:u16le() + info.blocksPerFrame = r:u32le() + info.finalFrameBlocks = r:u32le() + info.totalFrames = r:u32le() + info.bitsPerSample = r:u16le() + info.channels = r:u16le() + info.sampleRate = r:u32le() + if r.err then + return nil, r.err + end + seekAt = at + descBytes + headBytes + seekCount = seekBytes // 4 + info.dataEnd = seekAt + seekBytes + hdrDataBytes + dataLo + dataHi * 4294967296 + local _ = termBytes + local hex = table.create(16, "") + local any = false + for k = 1, 16 do + local b = string.byte(md5, k) + any = any or b ~= 0 + hex[k] = string.format("%02x", b) + end + info.md5 = if any then table.concat(hex) else nil + else + info.level = r:u16le() + info.flags = r:u16le() + info.channels = r:u16le() + info.sampleRate = r:u32le() + local headerBytes = r:u32le() + r:u32le() -- terminating bytes + info.totalFrames = r:u32le() + info.finalFrameBlocks = r:u32le() + if bit32.band(info.flags, FLAG_PEAK) ~= 0 then + r:skip(4) + end + seekCount = info.totalFrames + if bit32.band(info.flags, FLAG_SEEKN) ~= 0 then + seekCount = r:u32le() + end + if bit32.band(info.flags, FLAG_WAVHDR) == 0 then + r:skip(headerBytes) + end + if r.err then + return nil, r.err + end + info.blocksPerFrame = 73728 * 4 + info.bitsPerSample = if bit32.band(info.flags, FLAG_8) ~= 0 then 8 elseif bit32.band(info.flags, FLAG_24) ~= 0 then 24 else 16 + seekAt = r:tell() + info.dataEnd = limit + end + local C, bits = info.channels, info.bitsPerSample + if C < 1 or C > 32 then + return nil, Err.new(Err.CORRUPT, "bad channel count " .. C) + end + if bits ~= 8 and bits ~= 16 and bits ~= 24 and bits ~= 32 then + return nil, Err.new(Err.UNSUPPORTED, bits .. "-bit samples") + end + if info.sampleRate < 1 or info.blocksPerFrame < 1 or info.blocksPerFrame > 10000000 or info.finalFrameBlocks > info.blocksPerFrame then + return nil, Err.new(Err.CORRUPT, "bad header") + end + if info.totalFrames < 1 then + return nil, Err.new(Err.CORRUPT, "no frames") + end + info.float = bit32.band(info.flags, FLAG_FLOAT) ~= 0 and bits == 32 + info.totalBlocks = (info.totalFrames - 1) * info.blocksPerFrame + info.finalFrameBlocks + if seekCount < info.totalFrames or seekAt + seekCount * 4 > limit then + return nil, Err.new(Err.TRUNCATED, "the seek table is incomplete") + end + local starts = table.create(info.totalFrames, 0) + local add, prev = 0, 0 + for i = 1, info.totalFrames do + local v = buffer.readu32(buf, seekAt + (i - 1) * 4) + if v < prev then + add += 4294967296 + end + prev = v + starts[i] = base + junk + add + v + end + for i = 1, info.totalFrames do + if starts[i] < base or (i > 1 and starts[i] < starts[i - 1]) then + return nil, Err.new(Err.CORRUPT, "bad seek table entry " .. i) + end + end + info.frameStart = starts + info.firstFrame = starts[1] + info.dataEnd = math.min(math.max(info.dataEnd, starts[info.totalFrames]), limit) + info.limit = limit + return info :: Info, nil +end + +type Decoder = { + info: Info, + pcm: { number }, + frame: (self: Decoder, buf: buffer, i: number) -> (number?, Err.Err?), + state: Decode.State, +} + +local function frame(self: Decoder, buf: buffer, i: number): (number?, Err.Err?) + local info = self.info + if i < 1 or i > info.totalFrames then + return nil, Err.new(Err.ARG, "no frame " .. i) + end + local start = info.frameStart[i] + local rem = (start - info.firstFrame) % 4 + local want = (if i < info.totalFrames then info.frameStart[i + 1] else info.dataEnd) + 4 + local stop = math.min(want, info.limit, buffer.len(buf)) + if start + 8 > stop then + return nil, Err.new(Err.TRUNCATED, "frame " .. i .. " is past the end of the data", start) + end + local n = if i < info.totalFrames then info.blocksPerFrame else info.finalFrameBlocks + local n2, msg = Decode.frame(self.state, buf, start - rem, rem, stop, n, self.pcm, info.float, stop < want - 4) + if not n2 then + return nil, Err.from(msg, start) + end + return n2, nil +end + +function Ape.decoder(info: Info): (Decoder?, Err.Err?) + local st, msg = Decode.state(info.version, info.level, info.bitsPerSample, info.channels) + if not st then + return nil, Err.from(msg) + end + return { + info = info, + pcm = table.create(math.min(info.blocksPerFrame, 1048576) * info.channels, 0), + frame = frame, + state = st, + }, nil +end + +return Ape +end +__FILES["codecs/audio/Ape/Decode"] = @native function() + + + +-- codecs/audio/Ape/Decode: one Monkey's Audio frame -> samples. +-- Ported from the Monkey's Audio SDK 13.28 (Matthew T. Ashland, BSD 3-clause, licenses/monkeys-audio-LICENSE.txt): +-- UnBitArray.cpp, Old/UnBitArrayOld.cpp, NNFilter.h, NewPredictor.cpp, Prepare.cpp, APEDecompressCore.cpp, FloatTransform.cpp. +local Crc32 = __include("core/Crc32") + +local readu8, readu32, writeu32, byteswap = buffer.readu8, buffer.readu32, buffer.writeu32, bit32.byteswap +local writeu8, writei16, writeu16, writei32, readf32 = buffer.writeu8, buffer.writei16, buffer.writeu16, buffer.writei32, buffer.readf32 +local readi16, readi32 = buffer.readi16, buffer.readi32 +local band, bor, bnot, rshift, lshift, bxor = bit32.band, bit32.bor, bit32.bnot, bit32.rshift, bit32.lshift, bit32.bxor +local sign = math.sign + +local Decode = {} + +local TWO31, TWO32 = 2147483648, 4294967296 +local PAD = 64 + +-- the range coder's symbol models (UnBitArrayBase.h) +local RT1 = { 0, 14824, 28224, 39348, 47855, 53994, 58171, 60926, 62682, 63786, 64463, 64878, 65126, 65276, 65365, 65419, 65450, 65469, 65480, 65487, 65491, 65493, 65494, 65495, 65496, 65497, 65498, 65499, 65500, 65501, 65502, 65503, 65504, 65505, 65506, 65507, 65508, 65509, 65510, 65511, 65512, 65513, 65514, 65515, 65516, 65517, 65518, 65519, 65520, 65521, 65522, 65523, 65524, 65525, 65526, 65527, 65528, 65529, 65530, 65531, 65532, 65533, 65534, 65535, 65536 } +local RT2 = { 0, 19578, 36160, 48417, 56323, 60899, 63265, 64435, 64971, 65232, 65351, 65416, 65447, 65466, 65476, 65482, 65485, 65488, 65490, 65491, 65492, 65493, 65494, 65495, 65496, 65497, 65498, 65499, 65500, 65501, 65502, 65503, 65504, 65505, 65506, 65507, 65508, 65509, 65510, 65511, 65512, 65513, 65514, 65515, 65516, 65517, 65518, 65519, 65520, 65521, 65522, 65523, 65524, 65525, 65526, 65527, 65528, 65529, 65530, 65531, 65532, 65533, 65534, 65535, 65536 } +local KMIN = { 0, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608, 16777216, 33554432, 67108864, 134217728, 268435456, 536870912, 1073741824, 2147483648, 0, 0, 0, 0, 0 } + +-- symbol(total) lookup buffers (RangeOverflowTable), built on first use +local OVT: { [number]: buffer } = {} +@native local function overflowTable(rt: { number }): buffer + local t = OVT[rt[2]] + if t then + return t + end + t = buffer.create(65536) + local o = 0 + for z = 0, 65535 do + if z >= rt[o + 2] then + o += 1 + end + writeu8(t, z, o) + end + OVT[rt[2]] = t + return t +end + +@native local function wrap32(v: number): number + if v >= TWO31 or v < -TWO31 then + return (v + TWO31) % TWO32 - TWO31 + end + return v +end + +-- C integer division by 2 (toward zero) +@native local function half(v: number): number + return if v >= 0 then v // 2 else -((-v) // 2) +end + +type Filter = { order: number, shift: number, M: buffer, I: buffer, D: buffer } +type State = { + version: number, + bits: number, + channels: number, + filters: { Filter }, -- per level, applied last to first on decode (as m_spNNFilter2, 1, 0) + V: { { number } }, + S: buffer, + crcbuf: buffer, + scratch: buffer, + lastX: number, + rc: Rc, +} + +local FILTERS: { [number]: { number } } = { -- level -> { order, shift, ... } in m_spNNFilter, 1, 2 order + [1000] = {}, + [2000] = { 16, 11 }, + [3000] = { 64, 11 }, + [4000] = { 256, 13, 32, 10 }, + [5000] = { 1280, 15, 256, 13, 16, 11 }, +} + +@native function Decode.state(version: number, level: number, bits: number, channels: number): (State?, string?) + local spec = FILTERS[level] + if not spec then + return nil, "unsupported: compression level " .. level + end + local filters: { Filter } = {} + for k = 1, #spec, 2 do + local order = spec[k] + local es = if bits >= 32 then 4 else 2 + table.insert(filters, { + order = order, + shift = spec[k + 1], + M = buffer.create(order * es), + I = buffer.create((512 + order + 1) * es), + D = buffer.create((512 + order + 1) * es), + }) + end + local V = {} + for c = 1, channels do + V[c] = {} + end + return { + version = version, + bits = bits, + channels = channels, + filters = filters, + V = V, + S = buffer.create(1024), + crcbuf = buffer.create(1024), + scratch = buffer.create(4), + lastX = 0, + rc = { q = 0, low = 0, range = 0, prev = 0 }, + }, nil +end + +-- the range coder as a record (the 3.95 - 3.98 model's RangeDecodeFastWithUpdate) +type Rc = { q: number, low: number, range: number, prev: number } +@native local function rcBits(rc: Rc, S: buffer, nb: number): number + local q, low, range, prev = rc.q, rc.low, rc.range, rc.prev + while range <= 8388608 do + local byte = readu8(S, q) + q += 1 + low = low * 256 + bor(lshift(band(prev, 1), 7), rshift(byte, 1)) + prev = byte + range *= 256 + end + range = range // 2 ^ nb + local r = 0 + if range > 0 then + r = low // range + low %= range + end + rc.q, rc.low, rc.range, rc.prev = q, low, range, prev + return r +end + +@native local function values(st: State, q: number, lim: number, n: number, order: { number }, old: boolean): (number?, string?) + local S = st.S + local V = st.V + local version = st.version + -- FlushBitArray: a dummy byte, then the first byte + local prev = readu8(S, q + 1) + q += 2 + local low = rshift(prev, 1) + local range = 128 + local nch = #order + local ksum = table.create(nch, 16384) + local kk = table.create(nch, 10) + local ovt = overflowTable(if old then RT1 else RT2) + local RT = if old then RT1 else RT2 + for b = 1, n do + for ci = 1, nch do + if q > lim then + return nil, "overrun" + end + local ks = ksum[ci] + local value + -- the overflow symbol (RangeDecodeFast(16) + the model) + while range <= 8388608 do + local byte = readu8(S, q) + q += 1 + low = low * 256 + bor(lshift(band(prev, 1), 7), rshift(byte, 1)) + prev = byte + range *= 256 + end + range = range // 65536 + local total = low // range + if total >= 65536 then + return nil, "bad range code" + end + local ov = readu8(ovt, total) + low -= range * RT[ov + 1] + range *= RT[ov + 2] - RT[ov + 1] + if not old then + local pivot = math.max(ks // 32, 1) + while ov == 63 do + -- escape: 32 bits of overflow (two 16-bit range decodes); 1 = the overflow signal + local r = 0 + for _ = 1, 2 do + while range <= 8388608 do + local byte = readu8(S, q) + q += 1 + low = low * 256 + bor(lshift(band(prev, 1), 7), rshift(byte, 1)) + prev = byte + range *= 256 + end + range = range // 65536 + if range == 0 then + return nil, "bad range code" + end + r = r * 65536 + low // range + low %= range + end + ov = r + if ov == 1 then + pivot = 32768 + while range <= 8388608 do + local byte = readu8(S, q) + q += 1 + low = low * 256 + bor(lshift(band(prev, 1), 7), rshift(byte, 1)) + prev = byte + range *= 256 + end + range = range // 65536 + total = low // range + if total >= 65536 then + return nil, "bad range code" + end + ov = readu8(ovt, total) + low -= range * RT[ov + 1] + range *= RT[ov + 2] - RT[ov + 1] + else + break + end + end + local base + if pivot >= 65536 then + local pbits = 0 + while pivot // 2 ^ pbits > 0 do + pbits += 1 + end + local split = 2 ^ (if pbits >= 16 then pbits - 16 else 0) + local pa = pivot // split + 1 + while range <= 8388608 do + local byte = readu8(S, q) + q += 1 + low = low * 256 + bor(lshift(band(prev, 1), 7), rshift(byte, 1)) + prev = byte + range *= 256 + end + range = range // pa + local ba = low // range + low %= range + while range <= 8388608 do + local byte = readu8(S, q) + q += 1 + low = low * 256 + bor(lshift(band(prev, 1), 7), rshift(byte, 1)) + prev = byte + range *= 256 + end + range = range // split + local bb = low // range + low %= range + base = ba * split + bb + else + while range <= 8388608 do + local byte = readu8(S, q) + q += 1 + low = low * 256 + bor(lshift(band(prev, 1), 7), rshift(byte, 1)) + prev = byte + range *= 256 + end + range = range // pivot + base = low // range + low %= range + end + value = base + ov * pivot + else + -- 3.95 - 3.98: k bits (escape: k in 5 bits) + local rc = st.rc + rc.q, rc.low, rc.range, rc.prev = q, low, range, prev + local k + if ov == 63 then + k = rcBits(rc, S, 5) + ov = 0 + else + k = math.max(kk[ci] - 1, 0) + end + if k <= 16 or version < 3910 then + value = rcBits(rc, S, k) + else + local x1 = rcBits(rc, S, 16) + value = x1 + rcBits(rc, S, k - 16) * 65536 + end + value += ov * 2 ^ k + q = rc.q + low = rc.low + range = rc.range + prev = rc.prev + end + ks = (ks + (value + 1) // 2 - (ks + 16) // 32) % TWO32 + ksum[ci] = ks + if old then + local k = kk[ci] + if ks < KMIN[k + 1] then + kk[ci] = k - 1 + elseif KMIN[k + 2] ~= 0 and ks >= KMIN[k + 2] then + kk[ci] = k + 1 + end + end + V[order[ci]][b] = if value % 2 == 1 then (value - 1) // 2 + 1 else -(value // 2) + end + end + return q, nil +end + +-- ((v >> s) & m) ~= 0 for an int64 v (s given as 2^s) +@native local function negBit(v: number, p2: number, m: number): boolean + return band((v // p2) % TWO32, m) ~= 0 +end + +@native local function dot16(M: buffer, I: buffer, b: number, span: number): number + local dot = 0 + for k = 0, span - 16, 16 do + local bb = b + k + dot += readi16(I, bb) * readi16(M, k) + readi16(I, bb + 2) * readi16(M, k + 2) + + readi16(I, bb + 4) * readi16(M, k + 4) + readi16(I, bb + 6) * readi16(M, k + 6) + + readi16(I, bb + 8) * readi16(M, k + 8) + readi16(I, bb + 10) * readi16(M, k + 10) + + readi16(I, bb + 12) * readi16(M, k + 12) + readi16(I, bb + 14) * readi16(M, k + 14) + end + return dot +end + +-- the same, adapting each weight after its use: M += D * dm (int16, wrapping) +@native local function dotAdapt16(M: buffer, I: buffer, D: buffer, b: number, span: number, dm: number): number + local dot = 0 + for k = 0, span - 8, 8 do + local bb = b + k + local m0, m1, m2, m3 = readi16(M, k), readi16(M, k + 2), readi16(M, k + 4), readi16(M, k + 6) + dot += readi16(I, bb) * m0 + readi16(I, bb + 2) * m1 + readi16(I, bb + 4) * m2 + readi16(I, bb + 6) * m3 + writei16(M, k, m0 + readi16(D, bb) * dm) + writei16(M, k + 2, m1 + readi16(D, bb + 2) * dm) + writei16(M, k + 4, m2 + readi16(D, bb + 4) * dm) + writei16(M, k + 6, m3 + readi16(D, bb + 6) * dm) + end + return dot +end + +-- one CNNFilter (DecompressGeneric); weights in the C types (int16 up to 24-bit files, int32 for 32-bit) wrap as C does +@native local function nnFilter(f: Filter, v: { number }, n: number, newDelta: boolean, wide: boolean) + local order, M, I, D = f.order, f.M, f.I, f.D + local es = if wide then 4 else 2 + local shift = 2 ^ f.shift + local round = shift // 2 + buffer.fill(M, 0, 0, order * es) + buffer.fill(I, 0, 0, (order + 1) * es) + buffer.fill(D, 0, 0, (order + 1) * es) + local p = order + local total = 512 + order + local avg = 0 + local span = order * 2 + for t = 1, n do + local x = v[t] + local dm = -sign(x) -- the weights move by +delta when x < 0, -delta when x > 0 + local dot = 0 + if wide then + local b = (p - order) * 4 + for k = 0, order * 4 - 4, 4 do + local m = readi32(M, k) + local pr = readi32(I, b + k) * m + if pr >= TWO31 or pr < -TWO31 then + pr = (pr + TWO31) % TWO32 - TWO31 + end + dot += pr + if dm ~= 0 then + writei32(M, k, m + readi32(D, b + k) * dm) + end + end + else + local b = (p - order) * 2 + dot = if dm == 0 then dot16(M, I, b, span) else dotAdapt16(M, I, D, b, span, dm) + dot = wrap32(dot) + end + local o = x + (dot + round) // shift + if not wide then + o = wrap32(o) + end + local d = 0 + local a = if o < 0 then -o else o + if newDelta then + if a > avg * 3 then + d = if (if wide then negBit(o, 33554432, 64) else o < 0) then 32 else -32 + elseif a > (avg * 4) // 3 then + d = if (if wide then negBit(o, 67108864, 32) else o < 0) then 16 else -16 + elseif a > 0 then + d = if (if wide then negBit(o, 134217728, 16) else o < 0) then 8 else -8 + end + local dd = a - avg + avg += if dd >= 0 then dd // 16 else -((-dd) // 16) + else + d = if o == 0 then 0 elseif o < 0 then 4 else -4 + end + local sat = if o > 32767 then 32767 elseif o < -32768 then -32768 else o + if wide then + local q = p * 4 + writei32(D, q, d) + if newDelta then + writei32(D, q - 4, readi32(D, q - 4) // 2) + writei32(D, q - 8, readi32(D, q - 8) // 2) + else + writei32(D, q - 16, readi32(D, q - 16) // 2) + end + writei32(D, q - 32, readi32(D, q - 32) // 2) + writei32(I, q, sat) + else + local q = p * 2 + writei16(D, q, d) + if newDelta then + writei16(D, q - 2, readi16(D, q - 2) // 2) + writei16(D, q - 4, readi16(D, q - 4) // 2) + else + writei16(D, q - 8, readi16(D, q - 8) // 2) + end + writei16(D, q - 16, readi16(D, q - 16) // 2) + writei16(I, q, sat) + end + v[t] = o + p += 1 + if p == total then + buffer.copy(I, 0, I, (p - order) * es, order * es) + buffer.copy(D, 0, D, (p - order) * es, order * es) + p = order + end + end +end + +-- the adapt sign of a 32-bit file's int64 prediction value: ((v >> 30) & 2) - 1, or 0 +@native local function adaptWide(v: number): number + if v == 0 then + return 0 + end + return if (v // 1073741824) % 4 >= 2 then 1 else -1 +end + +-- CPredictorDecompress3950toCurrent, single-channel form +@native local function predictOne(st: State, v: { number }, n: number) + local wide = st.bits >= 32 + local lastA, prevA0, A1, A2, A3 = 0, 0, 0, 0, 0 + local MA0, MA1, MA2, MA3 = 360, 317, -109, 98 + local stage = 0 + for t = 1, n do + local nA = v[t] + local A0 = lastA + A3 = A2 + A2 = A1 + A1 = A0 - prevA0 + prevA0 = A0 + local predA = A0 * MA0 + A1 * MA1 + A2 * MA2 + A3 * MA3 + local cur + if wide then + cur = nA + predA // 1024 + else + cur = wrap32(nA + wrap32(predA) // 1024) + end + local s = sign(nA) + if s ~= 0 then + if wide then + s = -s + MA0 += adaptWide(A0) * s + MA1 += adaptWide(A1) * s + MA2 += adaptWide(A2) * s + MA3 += adaptWide(A3) * s + else + MA0 += sign(A0) * s + MA1 += sign(A1) * s + MA2 += sign(A2) * s + MA3 += sign(A3) * s + end + end + stage = wrap32(cur + (stage * 31) // 32) + lastA = cur + v[t] = stage + end +end + +-- the stereo predictors: Y = P1(nY, last X), X = P0(nX, Y); X into V[1], Y into V[2] +@native local function predictStereo(st: State, X: { number }, Y: { number }, n: number) + local wide = st.bits >= 32 + -- predictor 1 (Y) + local yLast, yPrev, yA1, yA2, yA3 = 0, 0, 0, 0, 0 + local yBin, yBprev, yB1, yB2, yB3, yB4 = 0, 0, 0, 0, 0, 0 + local yMA0, yMA1, yMA2, yMA3 = 360, 317, -109, 98 + local yMB0, yMB1, yMB2, yMB3, yMB4 = 0, 0, 0, 0, 0 + local yStage = 0 + -- predictor 0 (X) + local xLast, xPrev, xA1, xA2, xA3 = 0, 0, 0, 0, 0 + local xBin, xBprev, xB1, xB2, xB3, xB4 = 0, 0, 0, 0, 0, 0 + local xMA0, xMA1, xMA2, xMA3 = 360, 317, -109, 98 + local xMB0, xMB1, xMB2, xMB3, xMB4 = 0, 0, 0, 0, 0 + local xStage = 0 + local lastX = 0 + for t = 1, n do + local nA = Y[t] + local A0 = yLast + yA3 = yA2 + yA2 = yA1 + yA1 = A0 - yPrev + yPrev = A0 + local B0 = lastX - (yBin * 31) // 32 + yBin = lastX + yB4 = yB3 + yB3 = yB2 + yB2 = yB1 + yB1 = B0 - yBprev + yBprev = B0 + local predA = A0 * yMA0 + yA1 * yMA1 + yA2 * yMA2 + yA3 * yMA3 + local predB = B0 * yMB0 + yB1 * yMB1 + yB2 * yMB2 + yB3 * yMB3 + yB4 * yMB4 + local cur + if wide then + cur = nA + (predA + predB // 2) // 1024 + else + cur = wrap32(nA + wrap32(wrap32(predA) + wrap32(predB) // 2) // 1024) + end + local s = sign(nA) + if s ~= 0 then + if wide then + s = -s + yMA0 += adaptWide(A0) * s + yMA1 += adaptWide(yA1) * s + yMA2 += adaptWide(yA2) * s + yMA3 += adaptWide(yA3) * s + yMB0 += adaptWide(B0) * s + yMB1 += adaptWide(yB1) * s + yMB2 += adaptWide(yB2) * s + yMB3 += adaptWide(yB3) * s + yMB4 += adaptWide(yB4) * s + else + yMA0 += sign(A0) * s + yMA1 += sign(yA1) * s + yMA2 += sign(yA2) * s + yMA3 += sign(yA3) * s + yMB0 += sign(B0) * s + yMB1 += sign(yB1) * s + yMB2 += sign(yB2) * s + yMB3 += sign(yB3) * s + yMB4 += sign(yB4) * s + end + end + yStage = wrap32(cur + (yStage * 31) // 32) + yLast = cur + local yv = yStage + nA = X[t] + A0 = xLast + xA3 = xA2 + xA2 = xA1 + xA1 = A0 - xPrev + xPrev = A0 + B0 = yv - (xBin * 31) // 32 + xBin = yv + xB4 = xB3 + xB3 = xB2 + xB2 = xB1 + xB1 = B0 - xBprev + xBprev = B0 + predA = A0 * xMA0 + xA1 * xMA1 + xA2 * xMA2 + xA3 * xMA3 + predB = B0 * xMB0 + xB1 * xMB1 + xB2 * xMB2 + xB3 * xMB3 + xB4 * xMB4 + if wide then + cur = nA + (predA + predB // 2) // 1024 + else + cur = wrap32(nA + wrap32(wrap32(predA) + wrap32(predB) // 2) // 1024) + end + s = sign(nA) + if s ~= 0 then + if wide then + s = -s + xMA0 += adaptWide(A0) * s + xMA1 += adaptWide(xA1) * s + xMA2 += adaptWide(xA2) * s + xMA3 += adaptWide(xA3) * s + xMB0 += adaptWide(B0) * s + xMB1 += adaptWide(xB1) * s + xMB2 += adaptWide(xB2) * s + xMB3 += adaptWide(xB3) * s + xMB4 += adaptWide(xB4) * s + else + xMA0 += sign(A0) * s + xMA1 += sign(xA1) * s + xMA2 += sign(xA2) * s + xMA3 += sign(xA3) * s + xMB0 += sign(B0) * s + xMB1 += sign(xB1) * s + xMB2 += sign(xB2) * s + xMB3 += sign(xB3) * s + xMB4 += sign(xB4) * s + end + end + xStage = wrap32(cur + (xStage * 31) // 32) + xLast = cur + lastX = xStage + X[t], Y[t] = xStage, yv + end +end + +@native function Decode.frame(st: State, buf: buffer, at: number, rem: number, stop: number, n: number, P: { number }, float: boolean, cut: boolean): (number?, string?) + local C, bits = st.channels, st.bits + local len = math.max(0, stop - at) + local words = (len + 3) // 4 + local S = st.S + if buffer.len(S) < words * 4 + PAD then + S = buffer.create(words * 4 + PAD + 4096) + st.S = S + end + buffer.fill(S, 0, 0, words * 4 + PAD) + -- the bit array: 32-bit little-endian words read MSB first + for w = 0, words - 1 do + local o = at + w * 4 + if o + 4 <= stop then + writeu32(S, w * 4, byteswap(readu32(buf, o))) + else + for k = 0, 3 do + if o + k < stop then + writeu8(S, w * 4 + 3 - k, readu8(buf, o + k)) + end + end + end + end + @native local function u32be(q: number): number + return readu8(S, q) * 16777216 + readu8(S, q + 1) * 65536 + readu8(S, q + 2) * 256 + readu8(S, q + 3) + end + local q = rem + if q + 16 > words * 4 + PAD then + return nil, "truncated frame" + end + local stored = u32be(q) + q += 4 + local special = 0 + if st.version > 3820 then + if stored >= TWO31 then + special = u32be(q) + q += 4 + end + stored %= TWO31 + end + local V = st.V + local order: { number } + local mode + if C == 1 then + if band(special, 1) ~= 0 then + mode = "silence" + order = {} + else + mode = "mono" + order = { 1 } + end + elseif C == 2 then + if band(special, 3) == 3 then + mode = "silence" + order = {} + elseif band(special, 4) ~= 0 then + mode = "pseudo" + order = { 1 } + else + mode, order = "stereo", { 2, 1 } + end + else + mode = "multi" + order = {} + for c = 1, C do + order[c] = c + end + end + local lim = words * 4 + PAD - 40 + if #order > 0 then + local qe = values(st, q, lim, n, order, st.version < 3990) + if not qe or qe > words * 4 + 8 then + return nil, if cut then "truncated frame" else "bad frame: the values run over its data" + end + -- the NN filters (last level first), then the predictors + local newDelta = st.version >= 3980 + local filters = st.filters + for _, c in order do + for f = #filters, 1, -1 do + nnFilter(filters[f], V[c], n, newDelta, bits >= 32) + end + end + if mode == "stereo" then + predictStereo(st, V[1], V[2], n) + else + for _, c in order do + predictOne(st, V[c], n) + end + end + end + -- Unprepare: values -> channels, the CRC over the output bytes as the WAV holds them + local bps = bits // 8 + local cb = st.crcbuf + if buffer.len(cb) < n * C * bps then + cb = buffer.create(n * C * bps + 1024) + st.crcbuf = cb + end + local paired: { [number]: boolean } = {} + if C == 2 and mode == "stereo" then + paired[0] = true + elseif C == 4 and (bits == 16 or bits == 24) then + paired[0], paired[2] = true, true + elseif C >= 6 and (bits == 16 or bits == 24) then + paired[0], paired[4] = true, true + if C >= 8 then + paired[6] = true + end + end + local o = 0 + local mono = mode == "mono" or mode == "pseudo" + local X = V[1] + for t = 1, n do + local base = (t - 1) * C + local c = 0 + while c < C do + local a: number, b2: number = 0, 0 + local pair = paired[c] + if mode == "silence" then + a = 0 + b2 = 0 + elseif mono then + a = X[t] + b2 = a + elseif pair then + local x, y = V[c + 1][t], V[c + 2][t] + a = x - half(y) + b2 = a + y + else + a = V[c + 1][t] + end + local width = if pair or (C == 2) then 2 else 1 + for k = 0, width - 1 do + local s: number = if k == 0 then a else b2 + if bits == 16 then + if s < -32768 or s > 32767 then + return nil, "sample out of range" + end + writei16(cb, o, s) + o += 2 + elseif bits == 8 then + s = (s + 128) % 256 - 128 + writeu8(cb, o, s + 128) + o += 1 + elseif bits == 24 then + s = (s + 8388608) % 16777216 - 8388608 + local u = s % 16777216 + writeu16(cb, o, u % 65536) + writeu8(cb, o + 2, u // 65536) + o += 3 + else + s = wrap32(s) + writei32(cb, o, s) + o += 4 + end + P[base + c + k + 1] = s + end + c += width + end + end + local crc = Crc32.of(cb, 0, o) + if crc // 2 ~= stored then + return nil, "checksum: frame CRC mismatch" + end + if float then + local sc = st.scratch + for k = 1, n * C do + local u = P[k] % TWO32 + local out = bor(band(u, 0xC3FFFFFF), bxor(bnot(band(u, 0x3C000000)), 0xC3FFFFFF)) + if out >= TWO31 then + out = bor(bnot(out), 0x80000000) + end + writeu32(sc, 0, out) + P[k] = readf32(sc, 0) + end + end + return n, nil +end + +return Decode +end +__FILES["codecs/audio/ApeTag"] = function() + +-- codecs/audio/ApeTag: APEv1 / APEv2 tags -> Types.Tags. +-- From the APEv2 specification (wiki.hydrogenaud.io); no third-party code. Items + a 32-byte "APETAGEX" footer, optional +-- 32-byte header (APEv2), before an optional ID3v1 tag. +local ApeTag = {} + +type Item = { key: string, value: string, kind: string } +type Info = { start: number, stop: number, version: number, items: { Item } } + +local TO_TAG: { [string]: string } = { + year = "date", + ["album artist"] = "albumartist", + albumartist = "albumartist", + tracknumber = "track", + discnumber = "disc", + description = "comment", +} +local KINDS = { [0] = "text", "binary", "link", "text" } + +function ApeTag.tagKey(key: string): string + local k = string.lower(key) + return TO_TAG[k] or k +end + +function ApeTag.parse(buf: buffer, footer: number, start: number?): ({ [string]: string }?, Info?) + local lo = start or 0 + local n = buffer.len(buf) + if footer < lo or footer + 32 > n or buffer.readstring(buf, footer, 8) ~= "APETAGEX" then + return nil, nil + end + local version = buffer.readu32(buf, footer + 8) + local size = buffer.readu32(buf, footer + 12) -- items + footer + local count = buffer.readu32(buf, footer + 16) + local flags = buffer.readu32(buf, footer + 20) + if size < 32 or footer + 32 - size < lo then + return nil, nil + end + local p = footer + 32 - size + local first = p + if version >= 2000 and bit32.band(flags, 0x80000000) ~= 0 and p - 32 >= lo and buffer.readstring(buf, p - 32, 8) == "APETAGEX" then + first = p - 32 + end + local stop = footer + local tags: { [string]: string } = {} + local items: { Item } = {} + for _ = 1, math.min(count, 65536) do + if p + 9 > stop then + break + end + local len = buffer.readu32(buf, p) + local iflags = buffer.readu32(buf, p + 4) + local k = p + 8 + while k < stop and buffer.readu8(buf, k) ~= 0 do + k += 1 + end + if k >= stop then + break + end + local key = buffer.readstring(buf, p + 8, k - p - 8) + local v0 = k + 1 + if len > stop - v0 then + break + end + local value = buffer.readstring(buf, v0, len) + local kind = if version >= 2000 then KINDS[bit32.band(bit32.rshift(iflags, 1), 3)] else "text" + table.insert(items, { key = key, value = value, kind = kind }) + if kind == "text" and key ~= "" then + local tk = ApeTag.tagKey(key) + local s = (string.gsub(value, "%z+$", "")) + s = (string.gsub(s, "%z", "; ")) + local old = tags[tk] + tags[tk] = if old then old .. "; " .. s else s + end + p = v0 + len + end + return tags, { start = first, stop = footer + 32, version = version, items = items } +end + +function ApeTag.find(buf: buffer, start: number, limit: number): ({ [string]: string }?, Info?) + if limit > buffer.len(buf) then + limit = buffer.len(buf) + end + if limit - start >= 32 then + local tags, info = ApeTag.parse(buf, limit - 32, start) + if tags then + return tags, info + end + end + if limit - start >= 160 and buffer.readstring(buf, limit - 128, 3) == "TAG" then + return ApeTag.parse(buf, limit - 160, start) + end + return nil, nil +end + +return ApeTag +end +__FILES["codecs/audio/Mdct"] = @native function() + + + +-- codecs/audio/Mdct: MDCT / IMDCT for any N divisible by 4, DCT-IV, and the sine / KBD / Vorbis windows. +-- Through an N / 4-point complex FFT; written from the textbook definitions, no third-party code. +-- +-- X[k] = sum_{j=0}^{N-1} x[j] cos(2 pi / N (j + 1/2 + N/4) (k + 1/2)) forward, k = 0 .. N/2 - 1 +-- y[j] = sum_{k=0}^{N/2-1} X[k] cos(2 pi / N (j + 1/2 + N/4) (k + 1/2)) inverse, j = 0 .. N - 1 +-- +-- Unnormalised: forward + inverse + overlap-add with a Princen-Bradley window gives the input times N / 4 (the AAC spec +-- IMDCT is inverse(..., 2 / N)). +local Fft = __include("codecs/audio/Mdct/Fft") + +local cos, sin, pi, sqrt = math.cos, math.sin, math.pi, math.sqrt + +local Mdct = {} +Mdct.Fft = Fft + +type Plan = { + n: number, + m: number, + fft: Fft.Plan, + twc: { number }, -- cos / sin (pi (p + 1/8) / M), p = 0 .. N/4 - 1 + tws: { number }, + re: { number }, + im: { number }, + c: { number }, +} + +@native function Mdct.new(n: number): Plan? + if type(n) ~= "number" or n < 4 or n % 4 ~= 0 or n > 2 ^ 24 then + return nil + end + local m = n // 2 + local q = n // 4 + local fft = Fft.new(q) + if not fft then + return nil + end + local twc, tws = table.create(q, 0), table.create(q, 0) + for p = 0, q - 1 do + local a = pi * (p + 0.125) / m + twc[p + 1], tws[p + 1] = cos(a), sin(a) + end + return { + n = n, + m = m, + fft = fft, + twc = twc, + tws = tws, + re = table.create(q, 0), + im = table.create(q, 0), + c = table.create(m, 0), + } +end + +@native local function dct4Post(plan: Plan, out: { number }, oi: number, os: number, scale: number) + local q, m = plan.n // 4, plan.m + local re, im, twc, tws = plan.re, plan.im, plan.twc, plan.tws + Fft.forward(plan.fft, re, im) + for k = 0, q - 1 do + local c, s = twc[k + 1], tws[k + 1] + local tr, ti = re[k + 1], im[k + 1] + out[oi + 2 * k * os] = (tr * c + ti * s) * scale + out[oi + (m - 1 - 2 * k) * os] = -(ti * c - tr * s) * scale + end +end + +-- C[k] = sum_{n=0}^{M-1} u[n] cos(pi / M (n + 1/2) (k + 1/2)), M = N / 2 (its own inverse up to 2 / M) +@native function Mdct.dct4(plan: Plan, u: { number }, ui: number, us: number, out: { number }, oi: number, os: number, scale: number?) + local q, m = plan.n // 4, plan.m + local re, im, twc, tws = plan.re, plan.im, plan.twc, plan.tws + for p = 0, q - 1 do + local a, b = u[ui + 2 * p * us], u[ui + (m - 1 - 2 * p) * us] + local c, s = twc[p + 1], tws[p + 1] + re[p + 1] = a * c + b * s + im[p + 1] = b * c - a * s + end + dct4Post(plan, out, oi, os, scale or 1) +end + +@native function Mdct.forward(plan: Plan, x: { number }, xi: number, out: { number }, oi: number, os: number?, scale: number?) + local q, m = plan.n // 4, plan.m + local h = m // 2 + local re, im, twc, tws = plan.re, plan.im, plan.twc, plan.tws + -- fold: u[j] = -x[3M/2 - 1 - j] - x[3M/2 + j] (j < M/2), x[j - M/2] - x[3M/2 - 1 - j] (j >= M/2) + local b3 = xi + 3 * h + for p = 0, q - 1 do + local j = 2 * p + local a + if j < h then + a = -x[b3 - 1 - j] - x[b3 + j] + else + a = x[xi + j - h] - x[b3 - 1 - j] + end + j = m - 1 - 2 * p + local b + if j < h then + b = -x[b3 - 1 - j] - x[b3 + j] + else + b = x[xi + j - h] - x[b3 - 1 - j] + end + local c, s = twc[p + 1], tws[p + 1] + re[p + 1] = a * c + b * s + im[p + 1] = b * c - a * s + end + dct4Post(plan, out, oi, os or 1, scale or 1) +end + +@native function Mdct.inverse(plan: Plan, inp: { number }, ii: number, is: number?, y: { number }, yi: number, scale: number?) + local m = plan.m + local h = m // 2 + local c = plan.c + Mdct.dct4(plan, inp, ii, is or 1, c, 1, 1, scale) + -- unfold: y = (C2, -C2 reversed, -C1 reversed, -C1) + for j = 0, h - 1 do + y[yi + j] = c[h + j + 1] + y[yi + h + j] = -c[m - j] + y[yi + m + j] = -c[h - j] + y[yi + 3 * h + j] = -c[j + 1] + end +end + +@native local function besselI0(x: number): number + local sum, term = 1, 1 + local k = 1 + while k < 200 do + term *= (x / (2 * k)) ^ 2 + sum += term + if term < sum * 1e-17 then + break + end + k += 1 + end + return sum +end +Mdct.besselI0 = besselI0 + +-- "sine" sin(pi (n + 1/2) / N); "kbd" Kaiser-Bessel-derived (AAC: alpha 4 long, 6 short); "vorbis" +-- sin(pi / 2 sin^2(pi (n + 1/2) / N)). All satisfy w[n]^2 + w[n + N/2]^2 = 1. +@native function Mdct.window(kind: string, n: number, alpha: number?): { number }? + if type(n) ~= "number" or n < 2 or n % 2 ~= 0 then + return nil + end + local w = table.create(n, 0) + if kind == "sine" then + for i = 0, n - 1 do + w[i + 1] = sin(pi * (i + 0.5) / n) + end + elseif kind == "vorbis" then + for i = 0, n - 1 do + local s = sin(pi * (i + 0.5) / n) + w[i + 1] = sin(pi / 2 * s * s) + end + elseif kind == "kbd" then + local half = n // 2 + local a = alpha or 4 + local kais = table.create(half + 1, 0) + local total = 0 + for i = 0, half do + local r = 2 * i / half - 1 + kais[i + 1] = besselI0(pi * a * sqrt(math.max(0, 1 - r * r))) + total += kais[i + 1] + end + local acc = 0 + for i = 0, half - 1 do + acc += kais[i + 1] + local v = sqrt(acc / total) + w[i + 1] = v + w[n - i] = v + end + else + return nil + end + return w +end + +@native function Mdct.fft(n: number): Fft.Plan? + return Fft.new(n) +end + +return Mdct +end +__FILES["codecs/audio/Mdct/Fft"] = @native function() + + + +-- codecs/audio/Mdct/Fft: mixed-radix complex FFT (radix 4, 2, 3, 5, generic odd), self-sorting Stockham passes (the +-- FFTPACK / pocketfft pass structure, written from the textbook derivation; no third-party code). +local Fft = {} + +type Plan = { + n: number, + factors: { number }, + -- per pass: twiddles exp(-2 pi i u i l1 / n) for u = 1 .. p - 1, i = 0 .. ido - 1 at [(u - 1) * ido + i + 1] + twr: { { number } }, + twi: { { number } }, + -- per pass, generic odd radix: exp(-2 pi i k / p) for k = 0 .. p - 1 + rr: { { number } }, + ri: { { number } }, + sre: { number }, + sim: { number }, +} + +local cos, sin, pi = math.cos, math.sin, math.pi + +@native function Fft.new(n: number): Plan? + if type(n) ~= "number" or n < 1 or n % 1 ~= 0 or n > 2 ^ 24 then + return nil + end + local factors = {} + local m = n + while m % 4 == 0 do + table.insert(factors, 4) + m //= 4 + end + while m % 2 == 0 do + table.insert(factors, 2) + m //= 2 + end + local f = 3 + while m > 1 do + while m % f == 0 do + table.insert(factors, f) + m //= f + end + f += 2 + if f * f > m and m > 1 then + table.insert(factors, m) + m = 1 + end + end + local twr, twi, rr, ri = {}, {}, {}, {} + local l1 = 1 + for k, p in factors do + local ido = n // (l1 * p) + local tr, ti = table.create((p - 1) * ido, 0), table.create((p - 1) * ido, 0) + for u = 1, p - 1 do + for i = 0, ido - 1 do + local a = -2 * pi * u * i * l1 / n + tr[(u - 1) * ido + i + 1] = cos(a) + ti[(u - 1) * ido + i + 1] = sin(a) + end + end + twr[k], twi[k] = tr, ti + local cr, ci = table.create(p, 0), table.create(p, 0) + for j = 0, p - 1 do + cr[j + 1] = cos(-2 * pi * j / p) + ci[j + 1] = sin(-2 * pi * j / p) + end + rr[k], ri[k] = cr, ci + l1 *= p + end + return { + n = n, + factors = factors, + twr = twr, + twi = twi, + rr = rr, + ri = ri, + sre = table.create(n, 0), + sim = table.create(n, 0), + } +end + +-- one pass of radix p: cc (i, v, k) = src[1 + i + ido * (v + p * k)] -> ch (i, k, u) = dst[1 + i + ido * (k + l1 * u)] +@native local function pass(p: number, ido: number, l1: number, ar: { number }, ai: { number }, br: { number }, bi: { number }, tr: { number }, ti: { number }, cr: { number }, ci: { number }) + local lp = ido * l1 + if p == 4 then + for k = 0, l1 - 1 do + for i = 0, ido - 1 do + local s = 1 + i + ido * 4 * k + local a0r, a0i = ar[s], ai[s] + local a1r, a1i = ar[s + ido], ai[s + ido] + local a2r, a2i = ar[s + 2 * ido], ai[s + 2 * ido] + local a3r, a3i = ar[s + 3 * ido], ai[s + 3 * ido] + local t0r, t0i = a0r + a2r, a0i + a2i + local t1r, t1i = a0r - a2r, a0i - a2i + local t2r, t2i = a1r + a3r, a1i + a3i + local t3r, t3i = a1r - a3r, a1i - a3i + local d = 1 + i + ido * k + br[d], bi[d] = t0r + t2r, t0i + t2i + local y1r, y1i = t1r + t3i, t1i - t3r + local y2r, y2i = t0r - t2r, t0i - t2i + local y3r, y3i = t1r - t3i, t1i + t3r + if i == 0 then + br[d + lp], bi[d + lp] = y1r, y1i + br[d + 2 * lp], bi[d + 2 * lp] = y2r, y2i + br[d + 3 * lp], bi[d + 3 * lp] = y3r, y3i + else + local w1r, w1i = tr[i + 1], ti[i + 1] + local w2r, w2i = tr[ido + i + 1], ti[ido + i + 1] + local w3r, w3i = tr[2 * ido + i + 1], ti[2 * ido + i + 1] + br[d + lp], bi[d + lp] = y1r * w1r - y1i * w1i, y1r * w1i + y1i * w1r + br[d + 2 * lp], bi[d + 2 * lp] = y2r * w2r - y2i * w2i, y2r * w2i + y2i * w2r + br[d + 3 * lp], bi[d + 3 * lp] = y3r * w3r - y3i * w3i, y3r * w3i + y3i * w3r + end + end + end + elseif p == 2 then + for k = 0, l1 - 1 do + for i = 0, ido - 1 do + local s = 1 + i + ido * 2 * k + local a0r, a0i = ar[s], ai[s] + local a1r, a1i = ar[s + ido], ai[s + ido] + local d = 1 + i + ido * k + br[d], bi[d] = a0r + a1r, a0i + a1i + local yr, yi = a0r - a1r, a0i - a1i + if i == 0 then + br[d + lp], bi[d + lp] = yr, yi + else + local wr, wi = tr[i + 1], ti[i + 1] + br[d + lp], bi[d + lp] = yr * wr - yi * wi, yr * wi + yi * wr + end + end + end + elseif p == 3 then + local c = 0.86602540378443864676 -- sin(pi / 3) + for k = 0, l1 - 1 do + for i = 0, ido - 1 do + local s = 1 + i + ido * 3 * k + local a0r, a0i = ar[s], ai[s] + local a1r, a1i = ar[s + ido], ai[s + ido] + local a2r, a2i = ar[s + 2 * ido], ai[s + 2 * ido] + local tr_, ti_ = a1r + a2r, a1i + a2i + local sr, si = a1r - a2r, a1i - a2i + local d = 1 + i + ido * k + br[d], bi[d] = a0r + tr_, a0i + ti_ + local mr, mi = a0r - 0.5 * tr_, a0i - 0.5 * ti_ + local y1r, y1i = mr + c * si, mi - c * sr + local y2r, y2i = mr - c * si, mi + c * sr + if i == 0 then + br[d + lp], bi[d + lp] = y1r, y1i + br[d + 2 * lp], bi[d + 2 * lp] = y2r, y2i + else + local w1r, w1i = tr[i + 1], ti[i + 1] + local w2r, w2i = tr[ido + i + 1], ti[ido + i + 1] + br[d + lp], bi[d + lp] = y1r * w1r - y1i * w1i, y1r * w1i + y1i * w1r + br[d + 2 * lp], bi[d + 2 * lp] = y2r * w2r - y2i * w2i, y2r * w2i + y2i * w2r + end + end + end + else + -- generic radix: y_u = sum_v a_v exp(-2 pi i u v / p), then the twiddle + for k = 0, l1 - 1 do + for i = 0, ido - 1 do + local s = 1 + i + ido * p * k + local d = 1 + i + ido * k + for u = 0, p - 1 do + local yr, yi = 0, 0 + local j = 0 + for v = 0, p - 1 do + local xr, xi = ar[s + v * ido], ai[s + v * ido] + local wr, wi = cr[j + 1], ci[j + 1] + yr += xr * wr - xi * wi + yi += xr * wi + xi * wr + j += u + if j >= p then + j -= p + end + end + if u > 0 and i > 0 then + local wr, wi = tr[(u - 1) * ido + i + 1], ti[(u - 1) * ido + i + 1] + yr, yi = yr * wr - yi * wi, yr * wi + yi * wr + end + br[d + u * lp], bi[d + u * lp] = yr, yi + end + end + end + end +end + +-- X[k] = sum x[j] exp(-2 pi i j k / n), in place; the inverse (without 1 / n) is forward(plan, im, re) +@native function Fft.forward(plan: Plan, re: { number }, im: { number }) + local n = plan.n + local ar, ai, br, bi = re, im, plan.sre, plan.sim + local l1 = 1 + for k, p in plan.factors do + local ido = n // (l1 * p) + pass(p, ido, l1, ar, ai, br, bi, plan.twr[k], plan.twi[k], plan.rr[k], plan.ri[k]) + ar, ai, br, bi = br, bi, ar, ai + l1 *= p + end + if ar ~= re then + for j = 1, n do + re[j], im[j] = ar[j], ai[j] + end + end +end + +return Fft +end +__FILES["codecs/audio/MidiRender"] = function() + +-- codecs/audio/MidiRender: the MIDI tempo map, event timeline and the Decoder that plays a Midi through SoundFont. +-- Lengths as python mido computes them. Format 0 / 1: one tempo map from every track, tracks merged (ties keep track +-- order); format 2: each track is its own song, played one after another. +local Err = __include("core/Err") +local Types = __include("Types") +local SoundFont = __include("codecs/audio/SoundFont") + +local Synth = SoundFont.Synth + +local Render = {} + +type TempoMap = { ticks: { number }, secs: { number }, us: { number }, division: number } + +local STATUS = { noteOff = 0x80, noteOn = 0x90, aftertouch = 0xA0, controller = 0xB0, program = 0xC0, channelPressure = 0xD0, pitchBend = 0xE0 } + +local function tempoOf(ev: any): number? + if ev.type == "meta" and ev.meta == 0x51 and type(ev.data) == "table" and #ev.data >= 3 then + return ev.data[1] * 65536 + ev.data[2] * 256 + ev.data[3] + end + return nil +end + +function Render.tempoMap(midi: Types.Midi, track: number?): TempoMap + local changes: { { number } } = {} + for ti, t in midi.tracks do + if track == nil or track == ti then + for i, ev in t.events do + local us = tempoOf(ev) + if us then + table.insert(changes, { ev.tick, ti, i, us }) + end + end + end + end + table.sort(changes, function(a: { number }, b: { number }): boolean + if a[1] ~= b[1] then + return a[1] < b[1] + end + if a[2] ~= b[2] then + return a[2] < b[2] + end + return a[3] < b[3] + end) + local map: TempoMap = { ticks = { 0 }, secs = { 0 }, us = { 500000 }, division = midi.division } + local div = midi.division + for _, c in changes do + local n = #map.ticks + local tick = c[1] + local sec = map.secs[n] + (tick - map.ticks[n]) * map.us[n] * 1e-6 / div + if tick == map.ticks[n] then + map.us[n] = c[4] + else + table.insert(map.ticks, tick) + table.insert(map.secs, sec) + table.insert(map.us, c[4]) + end + end + return map +end + +function Render.seconds(map: TempoMap, tick: number): number + local div = map.division + if div < 0 then + local fps = -(div // 256) + local tpf = div % 256 + if tpf == 0 then + return 0 + end + return tick / ((if fps == 29 then 29.97 else fps) * tpf) + end + local ticks = map.ticks + local lo, hi = 1, #ticks + while lo < hi do + local mid = (lo + hi + 1) // 2 + if ticks[mid] <= tick then + lo = mid + else + hi = mid - 1 + end + end + return map.secs[lo] + (tick - ticks[lo]) * map.us[lo] * 1e-6 / div +end + +function Render.length(midi: Types.Midi): number + if #midi.tracks == 0 then + return 0 + end + if midi.format == 2 then + local total = 0 + for ti, t in midi.tracks do + local map = Render.tempoMap(midi, ti) + local last = 0 + for _, ev in t.events do + last = math.max(last, ev.tick) + end + total += Render.seconds(map, last) + end + return total + end + local map = Render.tempoMap(midi) + local last = 0 + for _, t in midi.tracks do + for _, ev in t.events do + last = math.max(last, ev.tick) + end + end + return Render.seconds(map, last) +end + +type Timeline = { time: { number }, status: { number }, d1: { number }, d2: { number }, length: number } + +function Render.timeline(midi: Types.Midi): Timeline + local items: { { any } } = {} + local offset = 0 + local function add(map: TempoMap, ti: number, t: any, base: number) + for i, ev in t.events do + local st = STATUS[ev.type] + if st and type(ev.data) == "table" then + local ch = ev.channel or 0 + table.insert(items, { base + Render.seconds(map, ev.tick), ti, i, st + ch % 16, ev.data[1] or 0, ev.data[2] or 0 }) + end + end + end + if midi.format == 2 then + for ti, t in midi.tracks do + local map = Render.tempoMap(midi, ti) + add(map, ti, t, offset) + local last = 0 + for _, ev in t.events do + last = math.max(last, ev.tick) + end + offset += Render.seconds(map, last) + end + else + local map = Render.tempoMap(midi) + for ti, t in midi.tracks do + add(map, ti, t, 0) + end + end + table.sort(items, function(a: { any }, b: { any }): boolean + if a[1] ~= b[1] then + return a[1] < b[1] + end + if a[2] ~= b[2] then + return a[2] < b[2] + end + return a[3] < b[3] + end) + 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 + return tl +end + +type RenderOptions = { + sampleRate: number?, + soundfont: any?, + gain: number?, + tail: number?, + maxVoices: number?, +} + +function Render.decoder(midi: Types.Midi, opts: RenderOptions?): (Types.Decoder?, Err.Err?) + if type(midi) ~= "table" or type(midi.tracks) ~= "table" or type(midi.division) ~= "number" or midi.division == 0 then + return nil, Err.new(Err.ARG, "render: needs a Midi value") + end + local o: RenderOptions = opts or {} + local rate = o.sampleRate or 44100 + if type(rate) ~= "number" or rate < 1000 or rate > 384000 then + return nil, Err.new(Err.ARG, "render: sampleRate must be 1000..384000") + end + local sf = o.soundfont + if sf == nil then + sf = SoundFont.fallback() + elseif not SoundFont.isSoundFont(sf) then + local parsed, err = SoundFont.parse(sf) + if not parsed then + return nil, err + end + sf = parsed + end + local tl = Render.timeline(midi) + local tail = o.tail or 1 + local frames = math.max(0, math.ceil((tl.length + tail) * rate)) + local nev = #tl.time + local evFrame: { number } = table.create(nev) :: { number } + for i = 1, nev do + evFrame[i] = math.floor(tl.time[i] * rate + 0.5) + end + local gain, maxVoices = o.gain, o.maxVoices + local state = Synth.new(sf, rate, gain, maxVoices) + local pos, nextEv = 0, 1 + + local dec = { + sampleRate = rate, + channels = 2, + frames = frames, + duration = frames / rate, + bitrate = 0, + tags = {} :: Types.Tags, + } + local mtags = type(midi.meta) == "table" and midi.meta.tags + if type(mtags) == "table" then + for k, v in mtags do + if type(k) == "string" and type(v) == "string" then + dec.tags[k] = v + end + end + end + for _, t in midi.tracks do + if t.name and not dec.tags.title then + dec.tags.title = t.name + end + end + + local function read(_self: any, n: number, out: buffer?): (buffer, number) + n = math.max(0, math.min(math.floor(n), frames - pos)) + local buf = out + if not buf or buffer.len(buf) < n * 8 then + buf = buffer.create(math.max(n, 1) * 8) + end + local b = buf :: buffer + buffer.fill(b, 0, 0, n * 8) + local i = 0 + while i < n do + while nextEv <= nev and evFrame[nextEv] <= pos + i do + Synth.midi(state, tl.status[nextEv], tl.d1[nextEv], tl.d2[nextEv]) + nextEv += 1 + end + local stop = n + if nextEv <= nev then + stop = math.min(n, evFrame[nextEv] - pos) + end + if stop > i then + Synth.render(state, b, i, stop - i) + i = stop + end + end + pos += n + return b, n + end + dec.read = read :: any + local scratch = buffer.create(4096 * 8) + dec.seek = function(_self: any, seconds: number) + local target = math.clamp(math.floor((tonumber(seconds) or 0) * rate), 0, frames) + if target < pos then + Synth.reset(state) + pos, nextEv = 0, 1 + end + while pos < target do + read(nil, math.min(4096, target - pos), scratch) + end + end :: any + dec.position = function(_self: any): number + return pos / rate + end :: any + return (dec :: any) :: Types.Decoder, nil +end + +-- tempo meta making each tick last 1 / ticksPerSecond s at that division (MUS, XMIDI, HMP / HMI) +function Render.tempoBytes(division: number, ticksPerSecond: number): { number } + local us = math.clamp(math.floor(division * 1e6 / ticksPerSecond + 0.5), 1, 0xFFFFFF) + return { us // 65536, (us // 256) % 256, us % 256 } +end + +type PendingOff = { tick: number, onTick: number, ev: Types.MidiEvent } + +-- XMIDI / HMI note durations: at equal ticks an off whose note started earlier goes before the file's events, +-- an off of a zero-length note after them +function Render.merge(events: { Types.MidiEvent }, offs: { PendingOff }): { Types.MidiEvent } + for i, o in offs do + (o :: any).seq = i + end + table.sort(offs, function(a: any, b: any): boolean + if a.tick ~= b.tick then + return a.tick < b.tick + end + return a.seq < b.seq + end) + local out: { Types.MidiEvent } = table.create(#events + #offs) :: { Types.MidiEvent } + local k = 1 + for _, ev in events do + while k <= #offs and (offs[k].tick < ev.tick or (offs[k].tick == ev.tick and offs[k].onTick < ev.tick)) do + table.insert(out, offs[k].ev) + k += 1 + end + table.insert(out, ev) + end + for j = k, #offs do + table.insert(out, offs[j].ev) + end + return out +end + +local function render(self: Types.Midi, opts: RenderOptions?): Types.Decoder + local dec, err = Render.decoder(self, opts) + if not dec then + local empty: any = { + sampleRate = 44100, channels = 2, frames = 0, duration = 0, bitrate = 0, tags = {}, err = err, + read = function(_self: any, _n: number, out: buffer?): (buffer, number) + return out or buffer.create(0), 0 + end, + seek = function() end, + position = function(): number + return 0 + end, + } + return empty + end + return dec +end + +function Render.summarize(midi: Types.Midi) + local tempos, sigs, keys = {}, {}, {} + local map = Render.tempoMap(midi) + for ti, t in midi.tracks do + for _, ev in t.events do + if ev.type == "meta" then + local d = ev.data :: { number } + if ev.meta == 0x51 and #d >= 3 then + table.insert(tempos, { tick = ev.tick, track = ti, usPerQuarter = d[1] * 65536 + d[2] * 256 + d[3], bpm = 60000000 / math.max(1, d[1] * 65536 + d[2] * 256 + d[3]), seconds = Render.seconds(map, ev.tick) }) + elseif ev.meta == 0x58 and #d >= 4 then + table.insert(sigs, { tick = ev.tick, track = ti, numerator = d[1], denominator = 2 ^ math.min(d[2], 31), clocksPerClick = d[3], notated32ndsPerBeat = d[4] }) + elseif ev.meta == 0x59 and #d >= 2 then + table.insert(keys, { tick = ev.tick, track = ti, sharps = if d[1] >= 128 then d[1] - 256 else d[1], minor = d[2] == 1 }) + end + end + end + end + midi.meta.tempos = tempos + midi.meta.timeSignatures = sigs + midi.meta.keySignatures = keys + midi.meta.length = Render.length(midi) +end + +function Render.attach(midi: Types.Midi, source: { [string]: any }) + Render.summarize(midi) + midi.meta.source = source + midi.render = render +end + +return Render +end +__FILES["codecs/audio/Pcm"] = function() + +-- codecs/audio/Pcm: PCM plumbing shared by audio formats: raw sample formats, streaming Decoders, encoder input sources. +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Convert = __include("codecs/audio/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 +} + +type Source = { + sampleRate: number, + channels: number, + frames: number, + tags: Types.Tags, + read: (self: Source, n: number, out: buffer?) -> (buffer, number), + err: Err.Err?, +} + +local function audioRead(self: any, n: number, out: buffer?): (buffer, number) + local a = self._audio + local ch = a.channels + local left = a.frames - self._pos + if n > left then + n = left + end + 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) + buffer.copy(b, 0, a.samples, self._pos * ch * 4, bytes) + self._pos += n + return b, n +end + +local function decoderRead(self: any, n: number, out: buffer?): (buffer, number) + if self._done then + return out or buffer.create(0), 0 + end + local ok, b, got = pcall(self._dec.read, self._dec, n, out) + if not ok then + self._done = true + self.err = Err.new(Err.CORRUPT, "source decoder failed: " .. tostring(b)) + return out or buffer.create(0), 0 + end + if type(b) ~= "buffer" or type(got) ~= "number" or got <= 0 then + self._done = true + return out or buffer.create(0), 0 + end + local ch = self.channels + if buffer.len(b) < got * ch * 4 then + got = buffer.len(b) // (ch * 4) + end + return b, got +end + +function Pcm.source(v: any): (Source?, Err.Err?) + if type(v) ~= "table" then + return nil, Err.new(Err.ARG, "needs an Audio or an audio Decoder") + end + local sr, ch = v.sampleRate, v.channels + if type(sr) ~= "number" or sr <= 0 or sr ~= sr or type(ch) ~= "number" or ch < 1 or ch ~= math.floor(ch) then + return nil, Err.new(Err.ARG, "bad sampleRate or channels") + end + if v.kind == "audio" and type(v.samples) == "buffer" then + local frames = v.frames + if type(frames) ~= "number" or frames < 0 or buffer.len(v.samples) < frames * ch * 4 then + return nil, Err.new(Err.ARG, "the Audio's samples buffer is shorter than frames * channels * 4") + end + return { sampleRate = sr, channels = ch, frames = frames, tags = v.tags or {}, read = audioRead, _audio = v, _pos = 0 } :: any, nil + end + if type(v.read) == "function" then + local frames = if type(v.frames) == "number" and v.frames > 0 then v.frames else 0 + return { sampleRate = sr, channels = ch, frames = frames, tags = v.tags or {}, read = decoderRead, _dec = v, _done = false } :: any, nil + end + return nil, Err.new(Err.ARG, "needs an Audio or an audio Decoder") +end + +function Pcm.collect(src: Source, maxFrames: number?): (Types.Audio?, Err.Err?) + local ch = src.channels + local cap = math.max(src.frames, 4096) + local data = buffer.create(cap * ch * 4) + local total = 0 + local limit = maxFrames or 2 ^ 31 + local tmp: buffer? = nil + 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 + break + end + tmp = b + if total + n > limit then + return nil, Err.new(Err.LIMIT, string.format("more than %d frames", limit)) + end + if total + n > cap then + cap = math.max(cap * 2, total + n) + local nd = buffer.create(cap * ch * 4) + buffer.copy(nd, 0, data, 0, total * ch * 4) + data = nd + end + buffer.copy(data, total * ch * 4, b, 0, n * ch * 4) + total += n + end + if src.err then + return nil, src.err + end + local a = Types.Audio.new(src.sampleRate, ch, 0) + a.frames = total + if buffer.len(data) == total * ch * 4 then + a.samples = data + else + a.samples = buffer.create(total * ch * 4) + buffer.copy(a.samples, 0, data, 0, total * ch * 4) + end + a.tags = table.clone(src.tags) + return a, nil +end + +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 + +function Pcm.rawDecoder(buf: buffer, offset: number, frames: number, channels: number, sampleRate: number, fmt: string, tags: Types.Tags?): (Types.Decoder?, Err.Err?) + local size = Convert.SIZE[fmt] + if not size then + return nil, Err.new(Err.ARG, "unknown sample format " .. tostring(fmt)) + end + if channels < 1 or sampleRate <= 0 or frames < 0 or offset < 0 or offset + frames * channels * size > buffer.len(buf) then + return nil, Err.new(Err.ARG, "bad raw PCM layout") + end + local pos = 0 + local frameBytes = channels * size + local dec = { + sampleRate = sampleRate, + channels = channels, + frames = frames, + duration = frames / sampleRate, + bitrate = sampleRate * frameBytes * 8, + tags = tags or {}, + } + function dec.read(_self: any, n: number, out: buffer?): (buffer, number) + n = math.clamp(math.floor(n), 0, frames - pos) + local bytes = n * channels * 4 + local b = if out and buffer.len(out) >= bytes then out else buffer.create(bytes) + if n > 0 then + Convert.decode(buf, offset + pos * frameBytes, fmt, n * channels, b, 0) + pos += n + end + return b, n + end + function dec.seek(_self: any, seconds: number) + local f = math.floor(seconds * sampleRate + 0.5) + pos = if f ~= f then 0 else math.clamp(f, 0, frames) + end + function dec.position(_self: any): number + return pos / sampleRate + end + return dec :: any, nil +end + +function Pcm.audioDecoder(a: Types.Audio): Types.Decoder + local d = Pcm.rawDecoder(a.samples, 0, a.frames, a.channels, a.sampleRate, "f32le", a.tags) :: any + d.bitrate = a.sampleRate * a.channels * 32 + return d +end + +function Pcm.encode(src: Source, fmt: string, w: Bytes.Writer): (number?, Err.Err?) + local size = Convert.SIZE[fmt] + if not size then + return nil, Err.new(Err.ARG, "unknown sample format " .. tostring(fmt)) + end + local ch = src.channels + local total = 0 + local tmp: buffer? = nil + while true do + local b, n = src:read(8192, tmp) + if n <= 0 then + break + end + tmp = b + local at = w:reserve(n * ch * size) + Convert.encode(b, 0, n * ch, fmt, w.buf, at) + w.pos = at + n * ch * size + total += n + end + if src.err then + return nil, src.err + end + return total, nil +end + +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 + +function Pcm.toInt(x: number, bits: number): number + local s = 2 ^ (bits - 1) + local v = math.floor(x * s + 0.5) + if v ~= v then + return 0 + end + if v >= s then + return s - 1 + elseif v < -s then + return -s + end + return v +end + +function Pcm.fromInt(v: number, bits: number): number + return v / 2 ^ (bits - 1) +end + +return Pcm +end +__FILES["codecs/audio/Pcm/Convert"] = @native function() + + + +-- codecs/audio/Pcm/Convert: raw sample formats <-> interleaved f32. +-- Integers map to v / 2^(bits-1) (as ffmpeg does). G.711 A-law / mu-law per ITU-T G.711 (the classic Sun g711.c +-- algorithm, written from the spec). +local Convert = {} + +local readu8, readi8, readi16, readi32, readu32 = buffer.readu8, buffer.readi8, buffer.readi16, buffer.readi32, buffer.readu32 +local readf32, readf64, writef32, writef64 = buffer.readf32, buffer.readf64, buffer.writef32, buffer.writef64 +local writeu8, writeu16, writeu32, writei16, writei32 = buffer.writeu8, buffer.writeu16, buffer.writeu32, buffer.writei16, buffer.writei32 +local floor = math.floor +local byteswap = bit32.byteswap + +local SIZE: { [string]: number } = { + u8 = 1, + s8 = 1, + s16le = 2, + s16be = 2, + s24le = 3, + s24be = 3, + s32le = 4, + s32be = 4, + f32le = 4, + f32be = 4, + f64le = 8, + f64be = 8, + alaw = 1, + ulaw = 1, +} +Convert.SIZE = SIZE +Convert.BITS = { + u8 = 8, + s8 = 8, + s16le = 16, + s16be = 16, + s24le = 24, + s24be = 24, + s32le = 32, + s32be = 32, + f32le = 32, + f32be = 32, + f64le = 64, + f64be = 64, + alaw = 16, + ulaw = 16, +} + +local ALAW = table.create(256, 0) +local ULAW = table.create(256, 0) +for code = 0, 255 do + local a = bit32.bxor(code, 0x55) + local t = bit32.band(a, 0x0F) * 16 + local seg = bit32.rshift(bit32.band(a, 0x70), 4) + if seg == 0 then + t += 8 + elseif seg == 1 then + t += 0x108 + else + t = (t + 0x108) * 2 ^ (seg - 1) + end + ALAW[code + 1] = if bit32.band(a, 0x80) ~= 0 then t else -t + local u = bit32.bxor(code, 0xFF) + local m = (bit32.band(u, 0x0F) * 8 + 0x84) * 2 ^ bit32.rshift(bit32.band(u, 0x70), 4) + ULAW[code + 1] = if bit32.band(u, 0x80) ~= 0 then 0x84 - m else m - 0x84 +end + +local SEG_AEND = { 0x1F, 0x3F, 0x7F, 0xFF, 0x1FF, 0x3FF, 0x7FF, 0xFFF } +local SEG_UEND = { 0x3F, 0x7F, 0xFF, 0x1FF, 0x3FF, 0x7FF, 0xFFF, 0x1FFF } +@native local function segment(v: number, ends: { number }): number + for i = 1, 8 do + if v <= ends[i] then + return i - 1 + end + end + return 8 +end + +@native local function alawEncode(pcm: number): number + local mask + local v = floor(pcm / 8) -- 13-bit magnitude domain + if v >= 0 then + mask = 0xD5 + else + mask = 0x55 + v = -v - 1 + end + local seg = segment(v, SEG_AEND) + local aval + if seg >= 8 then + aval = 0x7F + else + aval = seg * 16 + if seg < 2 then + aval += bit32.band(floor(v / 2), 0x0F) + else + aval += bit32.band(floor(v / 2 ^ seg), 0x0F) + end + end + return bit32.bxor(aval, mask) +end + +@native local function ulawEncode(pcm: number): number + local v = floor(pcm / 4) -- 14-bit + local mask + if v < 0 then + v = -v + mask = 0x7F + else + mask = 0xFF + end + if v > 8159 then + v = 8159 + end + v += 0x21 + local seg = segment(v, SEG_UEND) + local uval + if seg >= 8 then + uval = 0x7F + else + uval = seg * 16 + bit32.band(floor(v / 2 ^ (seg + 1)), 0x0F) + end + return bit32.bxor(uval, mask) +end +Convert.alawEncode = alawEncode +Convert.ulawEncode = ulawEncode +Convert.ALAW = ALAW +Convert.ULAW = ULAW + +@native function Convert.decode(src: buffer, so: number, fmt: string, count: number, dst: buffer, d: number): boolean + if fmt == "s16le" then + for i = 0, count - 1 do + writef32(dst, d + i * 4, readi16(src, so + i * 2) / 32768) + end + elseif fmt == "s16be" then + for i = 0, count - 1 do + local p = so + i * 2 + local v = readu8(src, p) * 256 + readu8(src, p + 1) + if v >= 32768 then + v -= 65536 + end + writef32(dst, d + i * 4, v / 32768) + end + elseif fmt == "u8" then + for i = 0, count - 1 do + writef32(dst, d + i * 4, (readu8(src, so + i) - 128) / 128) + end + elseif fmt == "s8" then + for i = 0, count - 1 do + writef32(dst, d + i * 4, readi8(src, so + i) / 128) + end + elseif fmt == "s24le" then + for i = 0, count - 1 do + local p = so + i * 3 + local v = readu8(src, p) + readu8(src, p + 1) * 256 + readi8(src, p + 2) * 65536 + writef32(dst, d + i * 4, v / 8388608) + end + elseif fmt == "s24be" then + for i = 0, count - 1 do + local p = so + i * 3 + local v = readi8(src, p) * 65536 + readu8(src, p + 1) * 256 + readu8(src, p + 2) + writef32(dst, d + i * 4, v / 8388608) + end + elseif fmt == "s32le" then + for i = 0, count - 1 do + writef32(dst, d + i * 4, readi32(src, so + i * 4) / 2147483648) + end + elseif fmt == "s32be" then + for i = 0, count - 1 do + local v = byteswap(readu32(src, so + i * 4)) + if v >= 2147483648 then + v -= 4294967296 + end + writef32(dst, d + i * 4, v / 2147483648) + end + elseif fmt == "f32le" then + buffer.copy(dst, d, src, so, count * 4) + elseif fmt == "f32be" then + for i = 0, count - 1 do + writeu32(dst, d + i * 4, byteswap(readu32(src, so + i * 4))) + end + elseif fmt == "f64le" then + for i = 0, count - 1 do + writef32(dst, d + i * 4, readf64(src, so + i * 8)) + end + elseif fmt == "f64be" then + local tmp = buffer.create(8) + for i = 0, count - 1 do + local p = so + i * 8 + writeu32(tmp, 0, byteswap(readu32(src, p + 4))) + writeu32(tmp, 4, byteswap(readu32(src, p))) + writef32(dst, d + i * 4, readf64(tmp, 0)) + end + elseif fmt == "alaw" then + for i = 0, count - 1 do + writef32(dst, d + i * 4, ALAW[readu8(src, so + i) + 1] / 32768) + end + elseif fmt == "ulaw" then + for i = 0, count - 1 do + writef32(dst, d + i * 4, ULAW[readu8(src, so + i) + 1] / 32768) + end + else + return false + end + return true +end + +@native local function q(x: number, s: number): number + local v = floor(x * s + 0.5) + if v ~= v then + return 0 + end + if v >= s then + return s - 1 + elseif v < -s then + return -s + end + return v +end + +@native function Convert.encode(src: buffer, so: number, count: number, fmt: string, dst: buffer, d: number): boolean + if fmt == "s16le" then + for i = 0, count - 1 do + writei16(dst, d + i * 2, q(readf32(src, so + i * 4), 32768)) + end + elseif fmt == "s16be" then + for i = 0, count - 1 do + local v = q(readf32(src, so + i * 4), 32768) % 65536 + writeu16(dst, d + i * 2, (v % 256) * 256 + v // 256) + end + elseif fmt == "u8" then + for i = 0, count - 1 do + writeu8(dst, d + i, q(readf32(src, so + i * 4), 128) + 128) + end + elseif fmt == "s8" then + for i = 0, count - 1 do + writeu8(dst, d + i, q(readf32(src, so + i * 4), 128) % 256) + end + elseif fmt == "s24le" then + for i = 0, count - 1 do + local v = q(readf32(src, so + i * 4), 8388608) % 16777216 + local p = d + i * 3 + writeu8(dst, p, v % 256) + writeu8(dst, p + 1, (v // 256) % 256) + writeu8(dst, p + 2, v // 65536) + end + elseif fmt == "s24be" then + for i = 0, count - 1 do + local v = q(readf32(src, so + i * 4), 8388608) % 16777216 + local p = d + i * 3 + writeu8(dst, p, v // 65536) + writeu8(dst, p + 1, (v // 256) % 256) + writeu8(dst, p + 2, v % 256) + end + elseif fmt == "s32le" then + for i = 0, count - 1 do + writei32(dst, d + i * 4, q(readf32(src, so + i * 4), 2147483648)) + end + elseif fmt == "s32be" then + for i = 0, count - 1 do + writeu32(dst, d + i * 4, byteswap(q(readf32(src, so + i * 4), 2147483648) % 4294967296)) + end + elseif fmt == "f32le" then + buffer.copy(dst, d, src, so, count * 4) + elseif fmt == "f32be" then + for i = 0, count - 1 do + writeu32(dst, d + i * 4, byteswap(readu32(src, so + i * 4))) + end + elseif fmt == "f64le" then + for i = 0, count - 1 do + writef64(dst, d + i * 8, readf32(src, so + i * 4)) + end + elseif fmt == "f64be" then + local tmp = buffer.create(8) + for i = 0, count - 1 do + writef64(tmp, 0, readf32(src, so + i * 4)) + local p = d + i * 8 + writeu32(dst, p, byteswap(readu32(tmp, 4))) + writeu32(dst, p + 4, byteswap(readu32(tmp, 0))) + end + elseif fmt == "alaw" then + for i = 0, count - 1 do + writeu8(dst, d + i, alawEncode(q(readf32(src, so + i * 4), 32768))) + end + elseif fmt == "ulaw" then + for i = 0, count - 1 do + writeu8(dst, d + i, ulawEncode(q(readf32(src, so + i * 4), 32768))) + end + else + return false + end + return true +end + +return Convert +end +__FILES["codecs/audio/Qoa"] = @native function() + + + +-- codecs/audio/Qoa: the "Quite OK Audio" codec (QOA). +-- Ported from qoa.h (phoboslab/qoa, Dominic Szablewski, MIT: licenses/qoa-LICENSE.txt); encoding is byte-for-byte +-- qoa.h's, including its 32-bit wrap in the reciprocal division. +local readu8, readu32, readf32, writef32, writeu32 = buffer.readu8, buffer.readu32, buffer.readf32, buffer.writef32, buffer.writeu32 +local readi32, writei32 = buffer.readi32, buffer.writei32 +local band, rshift, bor, lshift, byteswap = bit32.band, bit32.rshift, bit32.bor, bit32.lshift, bit32.byteswap +local floor = math.floor + +local Qoa = {} + +Qoa.SLICE_LEN = 20 +Qoa.SLICES_PER_FRAME = 256 +Qoa.FRAME_LEN = 256 * 20 +Qoa.MAX_CHANNELS = 255 + +local QUANT = { 7, 7, 7, 5, 5, 3, 3, 1, 0, 0, 2, 2, 4, 4, 6, 6, 6 } -- residual -8 .. 8 -> code +local RECIP = { 65536, 9363, 3121, 1457, 781, 475, 311, 216, 156, 117, 90, 71, 57, 47, 39, 32 } +-- DEQ[sf * 8 + q + 1] +local DEQ = { + 1, -1, 3, -3, 5, -5, 7, -7, + 5, -5, 18, -18, 32, -32, 49, -49, + 16, -16, 53, -53, 95, -95, 147, -147, + 34, -34, 113, -113, 203, -203, 315, -315, + 63, -63, 210, -210, 378, -378, 588, -588, + 104, -104, 345, -345, 621, -621, 966, -966, + 158, -158, 528, -528, 950, -950, 1477, -1477, + 228, -228, 760, -760, 1368, -1368, 2128, -2128, + 316, -316, 1053, -1053, 1895, -1895, 2947, -2947, + 422, -422, 1405, -1405, 2529, -2529, 3934, -3934, + 548, -548, 1828, -1828, 3290, -3290, 5117, -5117, + 696, -696, 2320, -2320, 4176, -4176, 6496, -6496, + 868, -868, 2893, -2893, 5207, -5207, 8099, -8099, + 1064, -1064, 3548, -3548, 6386, -6386, 9933, -9933, + 1286, -1286, 4288, -4288, 7718, -7718, 12005, -12005, + 1536, -1536, 5120, -5120, 9216, -9216, 14336, -14336, +} + +@native local function be32(b: buffer, p: number): number + return byteswap(readu32(b, p)) +end + +@native local function s16(v: number): number + return if v >= 32768 then v - 65536 else v +end + +@native function Qoa.frameSize(ch: number, slices: number): number + return 8 + 16 * ch + 8 * slices * ch +end + +type FrameInfo = { channels: number, rate: number, samples: number, size: number } + +@native function Qoa.frameInfo(b: buffer, p: number, avail: number): (FrameInfo?, string?) + if avail < 8 then + return nil, "truncated frame header" + end + local hi, lo = be32(b, p), be32(b, p + 4) + local ch = rshift(hi, 24) + local rate = band(hi, 0xFFFFFF) + local samples = rshift(lo, 16) + local size = band(lo, 0xFFFF) + if ch == 0 or rate == 0 or samples == 0 then + return nil, "bad frame header" + end + local slices = (samples + 19) // 20 + local head = 8 + 16 * ch + if slices > 256 or size < head or slices * ch > (size - head) // 8 then + return nil, "bad frame size" + end + if size > avail then + return nil, "truncated frame" + end + return { channels = ch, rate = rate, samples = samples, size = size }, nil +end + +@native function Qoa.decodeFrame(b: buffer, p: number, avail: number, dst: buffer, d: number): (number?, number | string) + local info, msg = Qoa.frameInfo(b, p, avail) + if not info then + return nil, msg :: string + end + local ch, samples = info.channels, info.samples + for c = 0, ch - 1 do + local lp = p + 8 + c * 16 + local hA, hB, hC, hD = be32(b, lp), be32(b, lp + 4), be32(b, lp + 8), be32(b, lp + 12) + local h0, h1, h2, h3 = s16(rshift(hA, 16)), s16(band(hA, 0xFFFF)), s16(rshift(hB, 16)), s16(band(hB, 0xFFFF)) + local w0, w1, w2, w3 = s16(rshift(hC, 16)), s16(band(hC, 0xFFFF)), s16(rshift(hD, 16)), s16(band(hD, 0xFFFF)) + local sp = p + 8 + 16 * ch + c * 8 + local o = (d + c) * 4 + local os = ch * 4 + local s0 = 0 + while s0 < samples do + local hi, lo = be32(b, sp), be32(b, sp + 4) + local base = rshift(hi, 28) * 8 + 1 + local n = math.min(20, samples - s0) + for k = 0, n - 1 do + local q + if k < 9 then + q = band(rshift(hi, 25 - 3 * k), 7) + elseif k == 9 then + q = band(hi, 1) * 4 + rshift(lo, 30) + else + q = band(rshift(lo, 57 - 3 * k), 7) + end + local pred = (w0 * h0 + w1 * h1 + w2 * h2 + w3 * h3) // 8192 + local dq = DEQ[base + q] + local r = pred + dq + if r > 32767 then + r = 32767 + elseif r < -32768 then + r = -32768 + end + writef32(dst, o, r / 32768) + o += os + local delta = dq // 16 + w0 += if h0 < 0 then -delta else delta + w1 += if h1 < 0 then -delta else delta + w2 += if h2 < 0 then -delta else delta + w3 += if h3 < 0 then -delta else delta + h0, h1, h2, h3 = h1, h2, h3, r + end + s0 += 20 + sp += 8 * ch + end + end + return samples, info.size +end + +-- LMS state: 8 i32 per channel (history 0..3, weights 0..3); initial weights 0, 0, -1, 2 (<< 13) +@native function Qoa.newLms(ch: number): buffer + local st = buffer.create(32 * ch) + for c = 0, ch - 1 do + writei32(st, c * 32 + 24, -8192) + writei32(st, c * 32 + 28, 16384) + end + return st +end + +@native local function toS16(x: number): number + local v = floor(x * 32768 + 0.5) + if v ~= v then + return 0 + elseif v > 32767 then + return 32767 + elseif v < -32768 then + return -32768 + end + return v +end + +-- qoa.h's qoa_div: a rounding division by the scale factor through its .16 reciprocal (in 32-bit int arithmetic, which +-- wraps for big residuals at scale factor 0), rounding away from zero +@native local function qdiv(v: number, sf: number): number + local x = v * RECIP[sf + 1] + 32768 + if x >= 2147483648 or x < -2147483648 then + x = (x + 2147483648) % 4294967296 - 2147483648 + end + local n = x // 65536 + local sv = if v > 0 then 1 elseif v < 0 then -1 else 0 + local sn = if n > 0 then 1 elseif n < 0 then -1 else 0 + return n + sv - sn +end + +@native function Qoa.encodeFrame(x: buffer, xf: number, n: number, ch: number, rate: number, lms: buffer, out: buffer, p: number): number + local slices = (n + 19) // 20 + local size = Qoa.frameSize(ch, slices) + writeu32(out, p, byteswap(bor(lshift(ch, 24), rate))) + writeu32(out, p + 4, byteswap(bor(lshift(n, 16), size))) + for c = 0, ch - 1 do + local so = c * 32 + -- the history and weights as big-endian i16 x 4 + for i = 0, 3 do + local hv = band(readi32(lms, so + i * 4), 0xFFFF) + local wv = band(readi32(lms, so + 16 + i * 4), 0xFFFF) + buffer.writeu8(out, p + 8 + c * 16 + i * 2, rshift(hv, 8)) + buffer.writeu8(out, p + 8 + c * 16 + i * 2 + 1, band(hv, 255)) + buffer.writeu8(out, p + 8 + c * 16 + 8 + i * 2, rshift(wv, 8)) + buffer.writeu8(out, p + 8 + c * 16 + 8 + i * 2 + 1, band(wv, 255)) + end + end + local xs = table.create(20, 0) + local codes = table.create(20, 0) + local best = table.create(20, 0) + local prevSf = table.create(ch, 0) + local sp = p + 8 + 16 * ch + for s = 0, slices - 1 do + local len = math.min(20, n - s * 20) + for c = 0, ch - 1 do + for k = 1, len do + xs[k] = toS16(readf32(x, ((xf + s * 20 + k - 1) * ch + c) * 4)) + end + local so = c * 32 + local H0, H1, H2, H3 = readi32(lms, so), readi32(lms, so + 4), readi32(lms, so + 8), readi32(lms, so + 12) + local W0, W1, W2, W3 = readi32(lms, so + 16), readi32(lms, so + 20), readi32(lms, so + 24), readi32(lms, so + 28) + local bestRank, bestSf = math.huge, 0 + local b0, b1, b2, b3, bw0, bw1, bw2, bw3 = H0, H1, H2, H3, W0, W1, W2, W3 + for sfi = 0, 15 do + local sf = (sfi + prevSf[c + 1]) % 16 + local h0, h1, h2, h3, w0, w1, w2, w3 = H0, H1, H2, H3, W0, W1, W2, W3 + local rank = 0 + local base = sf * 8 + 1 + for k = 1, len do + local v = xs[k] + local pred = (w0 * h0 + w1 * h1 + w2 * h2 + w3 * h3) // 8192 + local res = v - pred + local sc = qdiv(res, sf) + if sc > 8 then + sc = 8 + elseif sc < -8 then + sc = -8 + end + local q = QUANT[sc + 9] + local dq = DEQ[base + q] + local r = pred + dq + if r > 32767 then + r = 32767 + elseif r < -32768 then + r = -32768 + end + local sq = w0 * w0 + w1 * w1 + w2 * w2 + w3 * w3 + if sq >= 2147483648 then -- C int arithmetic + sq = (sq + 2147483648) % 4294967296 - 2147483648 + end + local pen = sq // 262144 - 0x8ff + if pen < 0 then + pen = 0 + end + local e = v - r + rank += e * e + pen * pen + if rank > bestRank then + break + end + local delta = dq // 16 + w0 += if h0 < 0 then -delta else delta + w1 += if h1 < 0 then -delta else delta + w2 += if h2 < 0 then -delta else delta + w3 += if h3 < 0 then -delta else delta + h0, h1, h2, h3 = h1, h2, h3, r + codes[k] = q + end + if rank < bestRank then + bestRank, bestSf = rank, sf + b0, b1, b2, b3, bw0, bw1, bw2, bw3 = h0, h1, h2, h3, w0, w1, w2, w3 + for k = 1, len do + best[k] = codes[k] + end + end + end + prevSf[c + 1] = bestSf + writei32(lms, so, b0) + writei32(lms, so + 4, b1) + writei32(lms, so + 8, b2) + writei32(lms, so + 12, b3) + writei32(lms, so + 16, bw0) + writei32(lms, so + 20, bw1) + writei32(lms, so + 24, bw2) + writei32(lms, so + 28, bw3) + -- the slice: sf in the top 4 bits, then the codes, unused codes 0 + local hi, lo = bestSf * 268435456, 0 + for k = 0, 19 do + local q = if k < len then best[k + 1] else 0 + if k < 9 then + hi += q * 2 ^ (25 - 3 * k) + elseif k == 9 then + hi += rshift(q, 2) + lo += band(q, 3) * 1073741824 + else + lo += q * 2 ^ (57 - 3 * k) + end + end + writeu32(out, sp, byteswap(hi)) + writeu32(out, sp + 4, byteswap(lo)) + sp += 8 + end + end + return size +end + +return Qoa +end +__FILES["codecs/audio/Resample"] = @native function() + + + +-- codecs/audio/Resample: sample-rate conversion by band-limited (Kaiser-windowed sinc) polyphase interpolation. +-- New in rosetta. +-- +-- 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 (default 0.97) of the lower Nyquist frequency. +-- +-- 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 (centred filter, zero outside the input); n input frames give +-- floor(n * to / from + 0.5) output frames. +local Resample = {} + +type Options = { + quality: ("low" | "medium" | "high")?, + cutoff: number?, +} + +type Resampler = { + from: number, + to: number, + channels: number, + process: (self: Resampler, src: buffer, frames: number, out: buffer?) -> (buffer, number), + 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 + +@native 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 + +@native 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, + half: number, + phases: number, + exact: boolean, + h: { number }, -- phase p, tap k: h[p * taps + k + 1] +} + +-- phase p: an output p / phases past an input sample; tap k multiplies input floor(t) - half + 1 + k +@native 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 + +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, + inFrames: number, + outPos: number, + done: boolean, + process: any, + flush: any, +} + +@native 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 + local rel = first - base + 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 + 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: { number } = table.create((histFrames - drop) * ch) :: any + 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 + +@native 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 + +@native 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 + +@native 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: { number }? = 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 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 = { + 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 + +@native 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 + +@native 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) + 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 + @native function out.read(self: any, n: number, dst: buffer?): (buffer, number) + n = floor(n) + while pendingFrames - pendingPos <= 0 and not ended do + 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 + 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 +end +__FILES["codecs/audio/Stream"] = function() + +-- codecs/audio/Stream: the streaming Types.Decoder over a packetised codec (gapless trim, seeking with pre-roll). +-- New in rosetta. +local Err = __include("core/Err") + +local Stream = {} + +type Spec = { + count: number, + start: (i: number) -> number, + decode: (i: number) -> (number?, Err.Err?), + pcm: () -> { number } | buffer, + reset: () -> (), + skip: number?, + stop: number?, + preroll: number?, + cumulative: boolean?, -- frames after a packet = frames before + its output (default: start(i) + its output) + scale: number?, + ints: boolean?, +} + +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 + 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 + + local scale = spec.scale or 1 + local function pull(n: number, out: buffer?, asInt: boolean): (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, writei32 = buffer.writef32, buffer.writei32 + 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 + if type(src) == "buffer" then + if scale == 1 and not asInt then + buffer.copy(ob, q, src, s * 4, take * ch * 4) + else + for k = 0, take * ch - 1 do + local v = buffer.readf32(src, (s + k) * 4) + if asInt then + writei32(ob, q, v) + else + writef32(ob, q, v * scale) + end + q += 4 + end + end + elseif asInt then + for k = 1, take * ch do + writei32(ob, q, src[s + k]) + q += 4 + end + elseif scale == 1 then + for k = 1, take * ch do + writef32(ob, q, src[s + k]) + q += 4 + end + else + for k = 1, take * ch do + writef32(ob, q, src[s + k] * scale) + q += 4 + end + end + pendPos += take + got += take + end + pos += got + return ob, got + end + + function dec.read(_self: any, n: number, out: buffer?): (buffer, number) + return pull(n, out, false) + end + if spec.ints then + function dec.readInt(_self: any, n: number, out: buffer?): (buffer, number) + return pull(n, out, true) + end + 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 + 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 + + if count > 0 and frames > 0 and not fill() and failed then + return nil, failed + end + return dec, nil +end + +return Stream +end +__FILES["codecs/audio/Tta"] = function() + +-- codecs/audio/Tta: the TTA1 (True Audio) lossless codec. +-- From the TTA1 format description (22-byte header and seek table with CRC-32s, frames of 256 / 245 seconds); no libtta / +-- ffmpeg code (LGPL). Format 2 (password) is UNSUPPORTED. +local Err = __include("core/Err") +local Crc32 = __include("core/Crc32") +local Decode = __include("codecs/audio/Tta/Decode") + +local Tta = {} + +type Info = { + format: number, + channels: number, + bitsPerSample: number, + sampleRate: number, + samples: number, + frameLength: number, -- samples per frame (256 * rate / 245) + frames: number, + offsets: { number }, + sizes: { number }, +} + +function Tta.info(buf: buffer, at: number, limit: number): (Info?, Err.Err?) + if at + 22 > limit then + return nil, Err.new(Err.TRUNCATED, "truncated header") + end + if buffer.readstring(buf, at, 4) ~= "TTA1" then + return nil, Err.new(Err.CORRUPT, "no TTA1 header") + end + if Crc32.of(buf, at, 18) ~= buffer.readu32(buf, at + 18) then + return nil, Err.new(Err.CHECKSUM, "header CRC mismatch", at) + end + local format = buffer.readu16(buf, at + 4) + local info: Info = { + format = format, + channels = buffer.readu16(buf, at + 6), + bitsPerSample = buffer.readu16(buf, at + 8), + sampleRate = buffer.readu32(buf, at + 10), + samples = buffer.readu32(buf, at + 14), + frameLength = 0, + frames = 0, + offsets = {}, + sizes = {}, + } + if format == 2 then + return nil, Err.new(Err.UNSUPPORTED, "password-protected TTA") + elseif format ~= 1 then + return nil, Err.new(Err.UNSUPPORTED, "TTA format " .. format) + end + local bits = info.bitsPerSample + if bits ~= 8 and bits ~= 16 and bits ~= 24 then + return nil, Err.new(Err.UNSUPPORTED, bits .. "-bit TTA") + end + if info.channels < 1 or info.sampleRate < 1 then + return nil, Err.new(Err.CORRUPT, "bad header") + end + info.frameLength = (256 * info.sampleRate) // 245 + if info.frameLength < 1 then + return nil, Err.new(Err.CORRUPT, "bad sample rate") + end + local frames = (info.samples + info.frameLength - 1) // info.frameLength + info.frames = frames + local st = at + 22 + if st + frames * 4 + 4 > limit then + return nil, Err.new(Err.TRUNCATED, "truncated seek table") + end + if Crc32.of(buf, st, frames * 4) ~= buffer.readu32(buf, st + frames * 4) then + return nil, Err.new(Err.CHECKSUM, "seek table CRC mismatch", st) + end + local o = st + frames * 4 + 4 + for i = 1, frames do + local size = buffer.readu32(buf, st + (i - 1) * 4) + info.offsets[i] = o + info.sizes[i] = size + o += size + end + return info, nil +end + +type Decoder = { + info: Info, + pcm: { number }, + limit: number, + frame: (self: Decoder, buf: buffer, i: number) -> (number?, Err.Err?), + state: Decode.State, +} + +local function frame(self: Decoder, buf: buffer, i: number): (number?, Err.Err?) + local info = self.info + if i < 1 or i > info.frames then + return nil, Err.new(Err.ARG, "no frame " .. i) + end + local o, size = info.offsets[i], info.sizes[i] + if o + size > self.limit then + return nil, Err.new(Err.TRUNCATED, "frame " .. i .. " runs past the end", o) + end + local n = if i < info.frames then info.frameLength else info.samples - (info.frames - 1) * info.frameLength + local got, msg = Decode.frame(self.state, buf, o, size, n, self.pcm) + if not got then + return nil, Err.from(msg, o) + end + return got, nil +end + +function Tta.decoder(info: Info, limit: number): Decoder + return { + info = info, + pcm = table.create(info.frameLength * info.channels, 0), + limit = limit, + frame = frame, + state = Decode.state(info.channels, info.bitsPerSample // 8), + } +end + +return Tta +end +__FILES["codecs/audio/Tta/Decode"] = @native function() + + + +-- codecs/audio/Tta/Decode: one TTA1 frame -> samples, from the TTA1 format description; no libtta / ffmpeg code. +-- Bit-exact against the ttaenc 3.4.1 decoder (tools/fixtures/tta.py). +local Crc32 = __include("core/Crc32") + +local readu8, readu32 = buffer.readu8, buffer.readu32 +local band, rshift = bit32.band, bit32.rshift +local min, max, floor = math.min, math.max, math.floor + +local Decode = {} + +local TWO31, TWO32 = 2147483648, 4294967296 +local INV31 = 1 / TWO31 +local PAD = 16 +local P2: { number } = table.create(40, 0) +for i = 0, 39 do + P2[i + 1] = 2 ^ i +end +local ONES: { number } = table.create(256, 0) +for b = 0, 255 do + local n, v = 0, b + while v % 2 == 1 do + n += 1 + v //= 2 + end + ONES[b + 1] = n +end + +@native local function longUnary(S: buffer, pos: number, lim: number): (number?, number) + local unary = 0 + while pos <= lim do + local w = rshift(readu32(S, rshift(pos, 3)), band(pos, 7)) + local ones = ONES[band(w, 255) + 1] + if ones < 8 then + return unary + ones, pos + ones + 1 + end + unary += 8 + pos += 8 + end + return nil, pos +end + +type State = { + channels: number, + bytes: number, + S: buffer, + R: { number }, + Q: { number }, + X: { number }, + L: { number }, + E: { number }, + last: { number }, + cur: { number }, +} + +@native function Decode.state(channels: number, bytes: number): State + return { + channels = channels, + bytes = bytes, + S = buffer.create(4096), + R = table.create(channels * 4, 0), + Q = table.create(channels * 8, 0), + X = table.create(channels * 8, 0), + L = table.create(channels * 8, 0), + E = table.create(channels, 0), + last = table.create(channels, 0), + cur = table.create(channels, 0), + } +end + +@native function Decode.frame(st: State, buf: buffer, o: number, len: number, n: number, P: { number }): (number?, string?) + if len < 4 then + return nil, "truncated frame" + end + local dlen = len - 4 + if Crc32.of(buf, o, dlen) ~= readu32(buf, o + dlen) then + return nil, "checksum: frame CRC mismatch" + end + local S = st.S + if buffer.len(S) < dlen + PAD then + S = buffer.create(dlen + PAD + 4096) + st.S = S + end + buffer.copy(S, 0, buf, o, dlen) + buffer.fill(S, dlen, 0, PAD) + local C, bytes = st.channels, st.bytes + local shift = if bytes == 2 then 9 else 10 -- the filter's precision per sample size + local fdiv = 2 ^ shift + local round = fdiv // 2 + local pk = if bytes == 1 then 16 else 32 -- the fixed predictor: last * (pk - 1) / pk + local R, Q, X, L, E, last, cur = st.R, st.Q, st.X, st.L, st.E, st.last, st.cur + for c = 0, C - 1 do + R[c * 4 + 1], R[c * 4 + 2], R[c * 4 + 3], R[c * 4 + 4] = 10, 10, 16384, 16384 + E[c + 1], last[c + 1] = 0, 0 + for i = 1, 8 do + Q[c * 8 + i], X[c * 8 + i], L[c * 8 + i] = 0, 0, 0 + end + end + local pos = 0 + local lim = dlen * 8 + local c = 0 + for idx = 1, n * C do + do + if pos > lim then + return nil, "truncated frame" + end + local unary + local w = rshift(readu32(S, rshift(pos, 3)), band(pos, 7)) + local ones = ONES[band(w, 255) + 1] + if ones < 8 then + unary = ones + pos += ones + 1 + else + local u, p2 = longUnary(S, pos, lim) + if not u then + return nil, "truncated frame" + end + unary, pos = u, p2 + end + local rb = c * 4 + local k0, k1, s0, s1 = R[rb + 1], R[rb + 2], R[rb + 3], R[rb + 4] + local deep = unary > 0 + local k + if deep then + k = k1 + unary -= 1 + else + k = k0 + end + local value = unary + if k > 0 then + local bits + if k <= 24 then + bits = band(rshift(readu32(S, rshift(pos, 3)), band(pos, 7)), P2[k + 1] - 1) + else + local lo = band(rshift(readu32(S, rshift(pos, 3)), band(pos, 7)), 0xFFFF) + local p2 = pos + 16 + bits = lo + band(rshift(readu32(S, rshift(p2, 3)), band(p2, 7)), P2[k - 15] - 1) * 65536 + end + pos += k + value = unary * P2[k + 1] + bits + end + if deep then + s1 += value - s1 // 16 + if k1 > 0 and s1 < P2[k1 + 5] then + k1 -= 1 + elseif s1 > P2[k1 + 6] then + k1 += 1 + end + value += P2[k0 + 1] + end + s0 += value - s0 // 16 + if k0 > 0 and s0 < P2[k0 + 5] then + k0 -= 1 + elseif s0 > P2[k0 + 6] then + k0 += 1 + end + R[rb + 1] = math.min(k0, 31) + R[rb + 2] = math.min(k1, 31) + R[rb + 3] = s0 + R[rb + 4] = s1 + local odd = value % 2 -- odd -> (v + 1) / 2, even -> -v / 2 (branch-free) + value = (value + odd) // 2 * (2 * odd - 1) + -- the adaptive filter: the weights step toward the sign of the last residual + local fb = c * 8 + local err = E[c + 1] + -- (one assignment per statement: LuaJIT cannot coalesce long multiple assignments) + local dq = max(-1, min(1, err)) + local x1, x2, x3, x4 = X[fb + 1], X[fb + 2], X[fb + 3], X[fb + 4] + local x5, x6, x7, x8 = X[fb + 5], X[fb + 6], X[fb + 7], X[fb + 8] + local q1 = Q[fb + 1] + x1 * dq + local q2 = Q[fb + 2] + x2 * dq + local q3 = Q[fb + 3] + x3 * dq + local q4 = Q[fb + 4] + x4 * dq + local q5 = Q[fb + 5] + x5 * dq + local q6 = Q[fb + 6] + x6 * dq + local q7 = Q[fb + 7] + x7 * dq + local q8 = Q[fb + 8] + x8 * dq + Q[fb + 1] = q1 + Q[fb + 2] = q2 + Q[fb + 3] = q3 + Q[fb + 4] = q4 + Q[fb + 5] = q5 + Q[fb + 6] = q6 + Q[fb + 7] = q7 + Q[fb + 8] = q8 + local l2, l3, l4, l5 = L[fb + 2], L[fb + 3], L[fb + 4], L[fb + 5] + local l6, l7, l8 = L[fb + 6], L[fb + 7], L[fb + 8] + local sum = round + L[fb + 1] * q1 + l2 * q2 + l3 * q3 + l4 * q4 + l5 * q5 + l6 * q6 + l7 * q7 + l8 * q8 + if sum >= TWO31 or sum < -TWO31 then + sum = (sum + TWO31) % TWO32 - TWO31 + end + -- the steps follow the delay line's signs (x 1, 2, 2, 4) + X[fb + 1] = x2 + X[fb + 2] = x3 + X[fb + 3] = x4 + X[fb + 4] = x5 + X[fb + 5] = 1 + 2 * floor(l5 * INV31) -- -1 for a negative value, else 1 (branch-free) + X[fb + 6] = 2 + 4 * floor(l6 * INV31) + X[fb + 7] = 2 + 4 * floor(l7 * INV31) + X[fb + 8] = 4 + 8 * floor(l8 * INV31) + E[c + 1] = value + value += sum // fdiv + -- the delay line: the last value and its first and second differences + local n7 = value - l8 + local n6 = n7 - l7 + L[fb + 1] = l2 + L[fb + 2] = l3 + L[fb + 3] = l4 + L[fb + 4] = l5 + L[fb + 5] = n6 - l6 + L[fb + 6] = n6 + L[fb + 7] = n7 + L[fb + 8] = value + value += (last[c + 1] * (pk - 1)) // pk + last[c + 1] = value + cur[c + 1] = value + end + c += 1 + if c == C then + -- inter-channel decorrelation: the last channel carries half the previous one, the others are differences + c = 0 + local o = idx - C + if C == 1 then + P[idx] = cur[1] + elseif C == 2 then + local a = cur[1] + local b = cur[2] + (if a >= 0 then a // 2 else -((-a) // 2)) + P[o + 1], P[o + 2] = b - a, b + else + local a = cur[C - 1] + cur[C] += if a >= 0 then a // 2 else -((-a) // 2) + for r = C - 1, 1, -1 do + cur[r] = cur[r + 1] - cur[r] + end + for k = 1, C do + P[o + k] = cur[k] + end + end + end + end + if pos > lim then + return nil, "truncated frame" + end + return n, nil +end + +return Decode +end +__FILES["codecs/audio/VorbisComment"] = function() + +-- codecs/audio/VorbisComment: Vorbis comment fields ("KEY=value"; Vorbis, Opus, FLAC) <-> Types.Tags. +local VorbisComment = {} + +type Field = { key: string, value: string } + +local TO_TAG: { [string]: string } = { tracknumber = "track", discnumber = "disc", description = "comment" } +local TO_FIELD: { [string]: string } = { track = "TRACKNUMBER", disc = "DISCNUMBER" } + +function VorbisComment.tagKey(name: string): string + local k = string.lower(name) + return TO_TAG[k] or k +end + +function VorbisComment.fieldName(key: string): string + return TO_FIELD[key] or string.upper(key) +end + +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 + +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: { string } = table.create(#keys) :: any + for i, k in keys do + out[i] = VorbisComment.fieldName(k) .. "=" .. tags[k] + end + return out +end + +return VorbisComment +end +end + + + + + + codecs_compress + --!optimize 2 +--!nocheck +-- rosetta chunk codecs_compress (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 11 modules (10 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["codecs/compress/Bzip2"] = function() + +-- codecs/compress/Bzip2: bzip2 decompressor (BWT + MTF + Huffman, the .bz2 stream format of bzip2 0.9.5 / 1.0.x). +-- Written from the format description (no third-party code); randomised blocks (bzip2 0.9.0 and older) are unsupported. +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Decode = __include("codecs/compress/Bzip2/Decode") + +local Bzip2 = {} + +type Options = { + maxBytes: number?, +} + +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) + if not b then + return nil, aerr + end + 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") + end + local out, nOut, consumed = Decode.decode(b, o, o + l, maxBytes) + if not out then + return nil, Err.from("bzip2: " .. tostring(nOut), o, consumed) + end + local res = out + if buffer.len(out) ~= nOut then + res = buffer.create(nOut) + buffer.copy(res, 0, out, 0, nOut) + end + return res, consumed +end + +function Bzip2.crc(buf: buffer, offset: number?, length: number?): number + local CT = Decode.crcTable + local o = offset or 0 + local e = o + (length or (buffer.len(buf) - o)) + local c = 0xFFFFFFFF + for i = o, e - 1 do + c = bit32.bxor(bit32.lshift(c, 8), CT[bit32.bxor(bit32.rshift(c, 24), buffer.readu8(buf, i)) + 1]) + end + return bit32.bxor(c, 0xFFFFFFFF) +end + +return Bzip2 +end +__FILES["codecs/compress/Bzip2/Decode"] = @native function() + + + +-- codecs/compress/Bzip2/Decode: bzip2 stream decoder (bzip2 1.0.x sources, Joe Tsai's "bzip2 format specification"). +-- Huffman groups, MTF + RUNA/RUNB, inverse BWT, RLE1; block CRC-32/BZIP2 (MSB first) and the combined stream CRC. +-- Written from the format description; no third-party code. +local Crc32 = __include("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: core/Crc32) +local CT = Crc32.MSB_TABLE +Decode.crcTable = CT + +local MASK = table.create(33, 0) +for i = 0, 32 do + MASK[i + 1] = if i == 32 then 0xFFFFFFFF else 2 ^ i - 1 +end + +local PBITS = 10 +local PSIZE = 1024 +local MAXGROUPS = 6 +local MAXALPHA = 258 +local MAXLEN = 20 + +local LOOK = bcreate(MAXGROUPS * PSIZE * 4) +local LENS = bcreate(MAXGROUPS * MAXALPHA) +local PERM = table.create(MAXGROUPS * MAXALPHA, 0) +local FIRST = table.create(MAXGROUPS * (MAXLEN + 1), 0) +local COUNT = table.create(MAXGROUPS * (MAXLEN + 1), 0) +local OFFS = table.create(MAXGROUPS * (MAXLEN + 1), 0) +local MAXL = table.create(MAXGROUPS, 0) +local CFTAB = table.create(257, 0) +local MTF = table.create(256, 0) +local SEQ = table.create(256, 0) + +@native local function buildGroup(g: number, n: number): boolean + local lbase = g * MAXALPHA + local cbase = g * (MAXLEN + 1) + for l = 0, MAXLEN do + COUNT[cbase + l + 1] = 0 + end + local maxLen = 0 + for s = 0, n - 1 do + local l = readu8(LENS, lbase + s) + COUNT[cbase + l + 1] += 1 + if l > maxLen then + maxLen = l + end + end + MAXL[g + 1] = maxLen + -- canonical codes: by length, then symbol + local code, idx = 0, 0 + for l = 1, MAXLEN do + FIRST[cbase + l + 1] = code + OFFS[cbase + l + 1] = idx + local c = COUNT[cbase + l + 1] + code += c + idx += c + if code > 2 ^ l then + return false + end + code *= 2 + end + local pbase = g * MAXALPHA + local tbase = g * PSIZE * 4 + bfill(LOOK, tbase, 0, PSIZE * 4) + local next = table.create(MAXLEN + 1, 0) + for l = 1, MAXLEN do + next[l + 1] = OFFS[cbase + l + 1] + end + for s = 0, n - 1 do + local l = readu8(LENS, lbase + s) + local k = next[l + 1] + next[l + 1] = k + 1 + PERM[pbase + k + 1] = s + if l <= PBITS then + local c = FIRST[cbase + l + 1] + (k - OFFS[cbase + l + 1]) + local shift = PBITS - l + local from = lshift(c, shift) + local entry = s * 32 + l + for j = from, from + lshift(1, shift) - 1 do + writeu32(LOOK, tbase + j * 4, entry) + end + end + end + return true +end + +@native local function grow(out: buffer, op: number, need: number): buffer + local nb = bcreate(math.max(blen(out) * 2, need, 65536)) + bcopy(nb, 0, out, 0, op) + return nb +end + +@native function Decode.decode(b: buffer, o: number, e: number, maxBytes: number): (buffer?, any, any) + local out = bcreate(math.min(math.max(65536, (e - o) * 4), maxBytes + 1)) + local op = 0 + local p = o + local bb, bc = 0, 0 + local tt: buffer? = nil + local ttSize = 0 + local streams = 0 + local consumedEnd = o + + while true do + -- stream header (byte aligned) + if streams > 0 then + if p + 4 > e or readu8(b, p) ~= 0x42 or readu8(b, p + 1) ~= 0x5A or readu8(b, p + 2) ~= 0x68 then + break -- trailing data after a stream is ignored, as bzip2 -d does + end + end + if p + 4 > e then + return nil, "truncated stream header", "truncated" + end + if readu8(b, p) ~= 0x42 or readu8(b, p + 1) ~= 0x5A or readu8(b, p + 2) ~= 0x68 then + return nil, "bad magic", "corrupt" + end + local level = readu8(b, p + 3) - 0x30 + if level < 1 or level > 9 then + return nil, "bad block size", "corrupt" + end + local maxBlock = level * 100000 + if ttSize < maxBlock then + tt = bcreate(maxBlock * 4) + ttSize = maxBlock + end + local T = tt :: buffer + p += 4 + bb, bc = 0, 0 + local combined = 0 + + while true do + -- 48-bit magic + 32-bit CRC + while bc <= 24 do + bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) + p += 1 + bc += 8 + end + local m1 = band(rshift(bb, bc - 24), 0xFFFFFF) + bc -= 24 + while bc <= 24 do + bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) + p += 1 + bc += 8 + end + local m2 = band(rshift(bb, bc - 24), 0xFFFFFF) + bc -= 24 + while bc <= 24 do + bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) + p += 1 + bc += 8 + end + local c1 = band(rshift(bb, bc - 16), 0xFFFF) + bc -= 16 + while bc <= 24 do + bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) + p += 1 + bc += 8 + end + local storedCrc = band(rshift(bb, bc - 16), 0xFFFF) + c1 * 65536 + bc -= 16 + if (p - o) * 8 - bc > (e - o) * 8 then + return nil, "truncated block header", "truncated" + end + if m1 == 0x177245 and m2 == 0x385090 then + if storedCrc ~= combined then + return nil, string.format("stream CRC mismatch (%08x, expected %08x)", combined, storedCrc), "checksum" + end + -- align to the byte after the stream + p -= bc // 8 + bb, bc = 0, 0 + break + end + if m1 ~= 0x314159 or m2 ~= 0x265359 then + return nil, "bad block magic", "corrupt" + end + + -- randomised bit, origPtr, symbol map + while bc <= 24 do + bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) + p += 1 + bc += 8 + end + local rnd = band(rshift(bb, bc - 1), 1) + bc -= 1 + while bc <= 24 do + bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) + p += 1 + bc += 8 + end + local origPtr = band(rshift(bb, bc - 24), 0xFFFFFF) + bc -= 24 + if rnd ~= 0 then + return nil, "randomised blocks (bzip2 0.9.0 and older) are not supported", "unsupported" + end + while bc <= 24 do + bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) + p += 1 + bc += 8 + end + local used = band(rshift(bb, bc - 16), 0xFFFF) + bc -= 16 + local nInUse = 0 + for i = 0, 15 do + if band(used, lshift(1, 15 - i)) ~= 0 then + while bc <= 24 do + bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) + p += 1 + bc += 8 + end + local bits = band(rshift(bb, bc - 16), 0xFFFF) + bc -= 16 + for j = 0, 15 do + if band(bits, lshift(1, 15 - j)) ~= 0 then + SEQ[nInUse + 1] = i * 16 + j + nInUse += 1 + end + end + end + end + if nInUse == 0 then + return nil, "no symbols in use", "corrupt" + end + local alphaSize = nInUse + 2 + + -- groups and selectors + while bc <= 24 do + bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) + p += 1 + bc += 8 + end + local nGroups = band(rshift(bb, bc - 3), 7) + bc -= 3 + local nSelectors = band(rshift(bb, bc - 15), 0x7FFF) + bc -= 15 + if nGroups < 2 or nGroups > 6 then + return nil, "bad number of Huffman groups", "corrupt" + end + if nSelectors < 1 then + return nil, "no selectors", "corrupt" + end + local selectors = buffer.create(nSelectors) + local mtfg0, mtfg1, mtfg2, mtfg3, mtfg4, mtfg5 = 0, 1, 2, 3, 4, 5 + for i = 0, nSelectors - 1 do + local j = 0 + while true do + if bc <= 24 then + bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) + p += 1 + bc += 8 + end + bc -= 1 + if band(rshift(bb, bc), 1) == 0 then + break + end + j += 1 + if j >= nGroups then + return nil, "bad selector", "corrupt" + end + end + -- move-to-front over the group list + local v + if j == 0 then + v = mtfg0 + elseif j == 1 then + v = mtfg1 + mtfg1 = mtfg0 + elseif j == 2 then + v = mtfg2 + mtfg2, mtfg1 = mtfg1, mtfg0 + elseif j == 3 then + v = mtfg3 + mtfg3, mtfg2, mtfg1 = mtfg2, mtfg1, mtfg0 + elseif j == 4 then + v = mtfg4 + mtfg4, mtfg3, mtfg2, mtfg1 = mtfg3, mtfg2, mtfg1, mtfg0 + else + v = mtfg5 + mtfg5, mtfg4, mtfg3, mtfg2, mtfg1 = mtfg4, mtfg3, mtfg2, mtfg1, mtfg0 + end + mtfg0 = v + writeu8(selectors, i, v) + end + if (p - o) * 8 - bc > (e - o) * 8 then + return nil, "truncated selectors", "truncated" + end + + -- code lengths (delta coded) + for g = 0, nGroups - 1 do + while bc <= 24 do + bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) + p += 1 + bc += 8 + end + local len = band(rshift(bb, bc - 5), 31) + bc -= 5 + for s = 0, alphaSize - 1 do + while true do + if len < 1 or len > MAXLEN then + return nil, "bad code length", "corrupt" + end + if bc <= 24 then + bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) + p += 1 + bc += 8 + end + bc -= 1 + if band(rshift(bb, bc), 1) == 0 then + break + end + bc -= 1 + if band(rshift(bb, bc), 1) == 0 then + len += 1 + else + len -= 1 + end + end + writeu8(LENS, g * MAXALPHA + s, len) + end + if not buildGroup(g, alphaSize) then + return nil, "over-subscribed Huffman code", "corrupt" + end + end + if (p - o) * 8 - bc > (e - o) * 8 then + return nil, "truncated code lengths", "truncated" + end + + -- MTF / RUNA / RUNB symbols -> T low bytes + for i = 0, 255 do + CFTAB[i + 1] = 0 + MTF[i + 1] = i + end + local eob = alphaSize - 1 + local nblock = 0 + local selIdx = 0 + local left = 0 + local g = 0 + local tbase, pbase, cbase, gmax = 0, 0, 0, 0 + local runLen, runBit = 0, 1 + while true do + if left == 0 then + if selIdx >= nSelectors then + return nil, "ran out of selectors", "corrupt" + end + g = readu8(selectors, selIdx) + selIdx += 1 + left = 50 + tbase = g * PSIZE * 4 + pbase = g * MAXALPHA + cbase = g * (MAXLEN + 1) + gmax = MAXL[g + 1] + end + left -= 1 + while bc <= 24 do + bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) + p += 1 + bc += 8 + end + local ent = readu32(LOOK, tbase + band(rshift(bb, bc - PBITS), PSIZE - 1) * 4) + local sym + if ent ~= 0 then + bc -= band(ent, 31) + sym = rshift(ent, 5) + else + local v = band(rshift(bb, bc - gmax), MASK[gmax + 1]) + sym = -1 + for l = PBITS + 1, gmax do + local c = rshift(v, gmax - l) + local f = FIRST[cbase + l + 1] + local k = c - f + if k >= 0 and k < COUNT[cbase + l + 1] then + sym = PERM[pbase + OFFS[cbase + l + 1] + k + 1] + bc -= l + break + end + end + if sym < 0 then + return nil, "bad Huffman code", "corrupt" + end + end + if sym <= 1 then + -- RUNA / RUNB: bijective base-2 run length of the front symbol + runLen += runBit * (sym + 1) + runBit *= 2 + if runLen > maxBlock then + return nil, "run past the block size", "corrupt" + end + else + if runLen > 0 then + if nblock + runLen > maxBlock then + return nil, "block larger than its declared size", "corrupt" + end + local ch = SEQ[MTF[1] + 1] + CFTAB[ch + 1] += runLen + for k = nblock, nblock + runLen - 1 do + writeu32(T, k * 4, ch) + end + nblock += runLen + runLen, runBit = 0, 1 + end + if sym == eob then + break + end + local idx = sym - 1 + if idx >= nInUse then + return nil, "bad MTF index", "corrupt" + end + if nblock >= maxBlock then + return nil, "block larger than its declared size", "corrupt" + end + local v = MTF[idx + 1] + for k = idx, 1, -1 do + MTF[k + 1] = MTF[k] + end + MTF[1] = v + local ch = SEQ[v + 1] + CFTAB[ch + 1] += 1 + writeu32(T, nblock * 4, ch) + nblock += 1 + end + if (p - o) * 8 - bc > (e - o) * 8 then + return nil, "truncated block data", "truncated" + end + end + if origPtr >= nblock then + return nil, "bad BWT origin pointer", "corrupt" + end + + local sum = 0 + for i = 0, 255 do + local c = CFTAB[i + 1] + CFTAB[i + 1] = sum + sum += c + end + for i = 0, nblock - 1 do + local ch = band(readu32(T, i * 4), 255) + local k = CFTAB[ch + 1] + CFTAB[ch + 1] = k + 1 + writeu32(T, k * 4, bor(readu32(T, k * 4), lshift(i, 8))) + end + + if op + nblock + 4096 > blen(out) then + out = grow(out, op, op + nblock + 4096) + end + local cap = blen(out) + local crc = 0xFFFFFFFF + local tPos = rshift(readu32(T, origPtr * 4), 8) + local last, run = -1, 0 + local i = 0 + while i < nblock do + local v = readu32(T, tPos * 4) + local ch = band(v, 255) + tPos = rshift(v, 8) + i += 1 + if run == 4 then + -- ch is a repeat count for the previous byte + if ch > 0 then + if op + ch > maxBytes then + return nil, "output larger than maxBytes", "limit" + end + if op + ch + 256 > cap then + out = grow(out, op, op + ch + nblock - i + 4096) + cap = blen(out) + end + bfill(out, op, last, ch) + op += ch + for _ = 1, ch do + crc = bxor(lshift(crc, 8), CT[bxor(rshift(crc, 24), last) + 1]) + end + end + run = 0 + last = -1 + else + if ch == last then + run += 1 + else + run = 1 + last = ch + end + if op + 256 > cap then + if op >= maxBytes then + return nil, "output larger than maxBytes", "limit" + end + out = grow(out, op, op + nblock - i + 4096) + cap = blen(out) + end + writeu8(out, op, ch) + op += 1 + crc = bxor(lshift(crc, 8), CT[bxor(rshift(crc, 24), ch) + 1]) + end + end + if op > maxBytes then + return nil, "output larger than maxBytes", "limit" + end + crc = bxor(crc, 0xFFFFFFFF) + if crc ~= storedCrc then + return nil, string.format("block CRC mismatch (%08x, expected %08x)", crc, storedCrc), "checksum" + end + combined = bxor(bor(lshift(combined, 1), rshift(combined, 31)), crc) + end + streams += 1 + consumedEnd = p + if p >= e then + break + end + end + return out, op, consumedEnd +end + +return Decode +end +__FILES["codecs/compress/Explode"] = @native function() + + + +-- codecs/compress/Explode: decompressor for the PKWARE Data Compression Library "implode" format (DCL, 1987). +-- Code tables and bit order (LSB first, Huffman codes inverted) after Mark Adler's blast.c (zlib licence: +-- licenses/blast-LICENSE.txt); the decoder is new code. +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") + +local readu8, writeu8 = buffer.readu8, buffer.writeu8 + +local Explode = {} + +local MAXBITS = 13 + +-- blast.c's tables: each byte is (count - 1) << 4 | code length +local LITLEN = { 11, 124, 8, 7, 28, 7, 188, 13, 76, 4, 10, 8, 12, 10, 12, 10, 8, 23, 8, 9, 7, 6, 7, 8, 7, 6, 55, 8, 23, + 24, 12, 11, 7, 9, 11, 12, 6, 7, 22, 5, 7, 24, 6, 11, 9, 6, 7, 22, 7, 11, 38, 7, 9, 8, 25, 11, 8, 11, 9, 12, 8, 12, 5, + 38, 5, 38, 5, 11, 7, 5, 6, 21, 6, 10, 53, 8, 7, 24, 10, 27, 44, 253, 253, 253, 252, 252, 252, 13, 12, 45, 12, 45, 12, + 61, 12, 45, 44, 173 } +local LENLEN = { 2, 35, 36, 53, 38, 23 } +local DISTLEN = { 2, 20, 53, 230, 247, 151, 248 } +local BASE = { 3, 2, 4, 5, 6, 7, 8, 9, 10, 12, 16, 24, 40, 72, 136, 264 } +local EXTRA = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8 } + +type Code = { count: { number }, symbol: { number } } + +@native local function construct(rep: { number }): Code + local lengths: { number } = {} + for _, b in rep do + local len = b % 16 + for _ = 0, b // 16 do + table.insert(lengths, len) + end + end + local count = table.create(MAXBITS + 1, 0) + for _, l in lengths do + count[l + 1] += 1 + end + local offs = table.create(MAXBITS + 2, 0) + for l = 1, MAXBITS do + offs[l + 2] = offs[l + 1] + count[l + 1] + end + local symbol = table.create(#lengths, 0) + for s, l in lengths do + if l ~= 0 then + offs[l + 1] += 1 + symbol[offs[l + 1]] = s - 1 + end + end + return { count = count, symbol = symbol } +end + +local LIT = construct(LITLEN) +local LEN = construct(LENLEN) +local DIST = construct(DISTLEN) + +@native function Explode.decompress(buf: buffer | string, offset: number?, length: number?, maxOut: number?): (buffer?, Err.Err?) + local b, o, l, aerr = Bytes.span("Explode.decompress", buf, offset, length) + if not b then + return nil, aerr + end + local src: buffer = b + local p, stop = o, o + l + if l < 2 then + return nil, Err.new(Err.TRUNCATED, "implode header", 0) + end + local lit, dict = readu8(src, p), readu8(src, p + 1) + p += 2 + if lit > 1 then + return nil, Err.new(Err.CORRUPT, "bad literal mode " .. lit, 0) + end + if dict < 4 or dict > 6 then + return nil, Err.new(Err.CORRUPT, "bad dictionary size " .. dict, 1) + end + local limit = maxOut or 2 ^ 30 + local cap = math.max(64, math.min(limit, l * 8)) + local out = buffer.create(cap) + local n = 0 + local bitbuf, bitcnt = 0, 0 + local truncated = false + + @native local function bits(need: number): number + while bitcnt < need do + if p >= stop then + truncated = true + return 0 + end + bitbuf += readu8(src, p) * 2 ^ bitcnt + p += 1 + bitcnt += 8 + end + local v = bitbuf % 2 ^ need + bitbuf = (bitbuf - v) / 2 ^ need + bitcnt -= need + return v + end + + @native local function decode(h: Code): number + local code, first, index = 0, 0, 0 + local count, symbol = h.count, h.symbol + for len = 1, MAXBITS do + local bit = bits(1) + if truncated then + return -1 + end + code += 1 - bit + local c = count[len + 1] + if code < first + c then + return symbol[index + code - first + 1] + end + index += c + first = (first + c) * 2 + code *= 2 + end + return -2 + end + + while n < limit do + local flag = bits(1) + if truncated then + break + end + if flag == 1 then + local sym = decode(LEN) + if sym < 0 then + if truncated then + break + end + return nil, Err.new(Err.CORRUPT, "bad length code", p - o) + end + local len = BASE[sym + 1] + bits(EXTRA[sym + 1]) + if truncated then + break + end + if len == 519 then + break + end + local shift = if len == 2 then 2 else dict + local d = decode(DIST) + if d < 0 then + if truncated then + break + end + return nil, Err.new(Err.CORRUPT, "bad distance code", p - o) + end + local dist = d * 2 ^ shift + bits(shift) + 1 + if truncated then + break + end + if dist > n then + return nil, Err.new(Err.CORRUPT, "distance too far back", p - o) + end + if n + len > limit then + len = limit - n + end + if n + len > cap then + cap = math.max(cap * 2, n + len) + local grown = buffer.create(cap) + buffer.copy(grown, 0, out, 0, n) + out = grown + end + local from = n - dist + for k = 0, len - 1 do + writeu8(out, n + k, readu8(out, from + k)) + end + n += len + else + local sym = if lit == 1 then decode(LIT) else bits(8) + if truncated then + break + end + if sym < 0 then + return nil, Err.new(Err.CORRUPT, "bad literal code", p - o) + end + if n >= cap then + cap *= 2 + local grown = buffer.create(cap) + buffer.copy(grown, 0, out, 0, n) + out = grown + end + writeu8(out, n, sym) + n += 1 + end + end + if truncated and n < limit and not maxOut then + return nil, Err.new(Err.TRUNCATED, "no end code", l) + end + local res = buffer.create(n) + buffer.copy(res, 0, out, 0, n) + return res, nil +end + +return Explode +end +__FILES["codecs/compress/Lz4"] = @native function() + + + +-- codecs/compress/Lz4: the LZ4 block format (lz4 doc/lz4_Block_format.md), decode and the reference "fast" encoder. +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") + +local Lz4 = {} + +type Options = { + maxBytes: number?, +} + +local readu8, writeu8, readu16, writeu16, readu32 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16, buffer.readu32 +local bcopy, bcreate, blen = buffer.copy, buffer.create, buffer.len +local band, rshift = bit32.band, bit32.rshift + +local MINMATCH = 4 +local LASTLITERALS = 5 -- the last 5 bytes are always literals +local MFLIMIT = 12 -- the last match starts at least 12 bytes before the end +local MAX_OFFSET = 65535 +local HASH_BITS = 13 +local HASH_SIZE = 2 ^ HASH_BITS + +@native function Lz4.decodeInto(src: buffer, p: number, limit: number, dst: buffer, d: number, dstLimit: number, histStart: number?): (number?, string?) + local lo = histStart or d + if limit > blen(src) or dstLimit > blen(dst) or p < 0 or d < 0 or lo < 0 or lo > d then + return nil, "corrupt: bad ranges" + end + if p >= limit then + return nil, "truncated: empty block" + end + while true do + if p >= limit then + return nil, "truncated" + end + local token = readu8(src, p) + p += 1 + local lit = rshift(token, 4) + if lit == 15 then + local b = 255 + while b == 255 do + if p >= limit then + return nil, "truncated" + end + b = readu8(src, p) + p += 1 + lit += b + end + end + if lit > 0 then + if p + lit > limit then + return nil, "truncated: literals past the end" + end + if d + lit > dstLimit then + return nil, "limit: output larger than expected" + end + bcopy(dst, d, src, p, lit) + p += lit + d += lit + end + if p >= limit then + return d, nil -- the last sequence has no match + end + if p + 2 > limit then + return nil, "truncated" + end + local off = readu16(src, p) + p += 2 + if off == 0 or d - off < lo then + return nil, "corrupt: bad match offset" + end + local ml = band(token, 15) + if ml == 15 then + local b = 255 + while b == 255 do + if p >= limit then + return nil, "truncated" + end + b = readu8(src, p) + p += 1 + ml += b + end + end + ml += MINMATCH + if d + ml > dstLimit then + return nil, "limit: output larger than expected" + end + local s = d - off + if off >= ml then + bcopy(dst, d, dst, s, ml) + d += ml + elseif off == 1 then + buffer.fill(dst, d, readu8(dst, s), ml) + d += ml + else + local n = ml + while n > 0 do + local c = d - s + if c > n then + c = n + end + bcopy(dst, d, dst, s, c) + d += c + n -= c + end + end + end +end + +@native function Lz4.decompress(src: buffer | string, offset: number?, length: number?, outSize: number?, opts: Options?): (buffer?, Err.Err?) + local b, o, l, aerr = Bytes.span("Lz4.decompress", src, offset, length) + if not b then + return nil, aerr + end + if outSize ~= nil then + if type(outSize) ~= "number" or outSize < 0 or outSize % 1 ~= 0 then + return nil, Err.new(Err.ARG, "Lz4.decompress: bad outSize") + end + local out = bcreate(outSize) + local e, msg = Lz4.decodeInto(b, o, o + l, out, 0, outSize) + if not e then + return nil, Err.from(msg, o) + end + if e ~= outSize then + return nil, Err.new(Err.CORRUPT, string.format("block decodes to %d bytes, expected %d", e, outSize), o) + end + return out, nil + end + local max = (opts and opts.maxBytes) or 2 ^ 28 + local size = math.min(math.max(l * 4, 256), max) + while true do + local out = bcreate(size) + local e, msg = Lz4.decodeInto(b, o, o + l, out, 0, size) + if e then + local res = bcreate(e) + bcopy(res, 0, out, 0, e) + return res, nil + end + if not (msg and string.sub(msg, 1, 6) == "limit:") then + return nil, Err.from(msg, o) + end + if size >= max then + return nil, Err.new(Err.LIMIT, "output over " .. max .. " bytes", o) + end + size = math.min(size * 4, max) + end +end + +@native function Lz4.bound(n: number): number + return n + n // 255 + 16 +end + +@native local function extend(dst: buffer, o: number, n: number): number + while n >= 255 do + writeu8(dst, o, 255) + o += 1 + n -= 255 + end + writeu8(dst, o, n) + return o + 1 +end + +-- Knuth's multiplicative hash (v * 2654435761 mod 2^32, top bits), exact in doubles +@native local function hash(v: number): number + local vl, vh = band(v, 0xFFFF), rshift(v, 16) + local mid = (vh * 0x79B1 + vl * 0x9E37) % 65536 + return ((vl * 0x79B1 + mid * 65536) % 4294967296) // (2 ^ (32 - HASH_BITS)) + 1 +end + +local hashTable: { number } = table.create(HASH_SIZE, -1e9) + +@native function Lz4.encodeInto(src: buffer, p: number, n: number, dst: buffer, d: number): number + local op = d + local anchor = p + local iend = p + n + local ht = hashTable + for i = 1, HASH_SIZE do + ht[i] = -1e9 + end + if n >= MFLIMIT + 1 then + local mflimit = iend - MFLIMIT -- a match starts before this + local matchEnd = iend - LASTLITERALS -- and ends at or before this + local ip = p + local skip = 64 + while ip < mflimit do + local v = readu32(src, ip) + local h = hash(v) + local ref = ht[h] + ht[h] = ip + if ref >= p and ip - ref <= MAX_OFFSET and readu32(src, ref) == v then + while ip > anchor and ref > p and readu8(src, ip - 1) == readu8(src, ref - 1) do + ip -= 1 + ref -= 1 + end + local a = ip + MINMATCH + local bpos = ref + MINMATCH + while a + 4 <= matchEnd and readu32(src, a) == readu32(src, bpos) do + a += 4 + bpos += 4 + end + while a < matchEnd and readu8(src, a) == readu8(src, bpos) do + a += 1 + bpos += 1 + end + local ml = a - ip + local lit = ip - anchor + local tok = op + op += 1 + local tl = if lit >= 15 then 15 else lit + if lit >= 15 then + op = extend(dst, op, lit - 15) + end + if lit > 0 then + bcopy(dst, op, src, anchor, lit) + op += lit + end + writeu16(dst, op, ip - ref) + op += 2 + local m = ml - MINMATCH + local tm = if m >= 15 then 15 else m + if m >= 15 then + op = extend(dst, op, m - 15) + end + writeu8(dst, tok, tl * 16 + tm) + ip = a + anchor = ip + skip = 64 + if ip - 2 >= p and ip - 2 < mflimit then + local w = readu32(src, ip - 2) + ht[hash(w)] = ip - 2 + end + else + ip += rshift(skip, 6) -- step up over incompressible data (the reference's acceleration) + skip += 1 + end + end + end + local lit = iend - anchor + local tok = op + op += 1 + if lit >= 15 then + op = extend(dst, op, lit - 15) + writeu8(dst, tok, 0xF0) + else + writeu8(dst, tok, lit * 16) + end + if lit > 0 then + bcopy(dst, op, src, anchor, lit) + op += lit + end + return op - d +end + +@native function Lz4.compress(src: buffer | string, offset: number?, length: number?): (buffer?, Err.Err?) + local b, o, l, aerr = Bytes.span("Lz4.compress", src, offset, length) + if not b then + return nil, aerr + end + local tmp = bcreate(Lz4.bound(l)) + local n = Lz4.encodeInto(b, o, l, tmp, 0) + local out = bcreate(n) + bcopy(out, 0, tmp, 0, n) + return out, nil +end + +return Lz4 +end +__FILES["codecs/compress/Lzh"] = @native function() + + + +-- codecs/compress/Lzh: the LHA family of LZSS decoders (lh1, lh4-lh7, lhx, lzs, lz5, ARJ 1-4, Zoo 2). +-- Ported from lhasa 0.6.0 (Simon Howard, ISC: licenses/lhasa-LICENSE.txt); ARJ method 4 from the ARJ technical notes. +-- Windows start filled as the original tools fill them (spaces; lz5's pattern); offsets before the output read it. +local Huffman = __include("codecs/entropy/Huffman") + +local Lzh = {} + +local readu8, writeu8, readu32 = buffer.readu8, buffer.writeu8, buffer.readu32 +local band, rshift, lshift = bit32.band, bit32.rshift, bit32.lshift +local floor = math.floor + +type Reader = { src: buffer, pos: number, limit: number, acc: number, cnt: number, over: number } + +@native local function reader(src: buffer, off: number, len: number): Reader + return { src = src, pos = off, limit = math.min(off + len, buffer.len(src)), acc = 0, cnt = 0, over = 0 } +end + +@native local function fill(r: Reader) + while r.cnt <= 24 do + local b = 0 + if r.pos < r.limit then + b = readu8(r.src, r.pos) + r.pos += 1 + else + r.over += 8 + end + r.acc = r.acc * 256 + b + r.cnt += 8 + end +end + +@native local function peek(r: Reader, n: number): number + if r.cnt < n then + fill(r) + end + return floor(r.acc / 2 ^ (r.cnt - n)) % 2 ^ n +end + +@native local function skip(r: Reader, n: number) + if r.cnt < n then + fill(r) + end + r.cnt -= n + r.acc = r.acc % 2 ^ r.cnt +end + +@native local function bits(r: Reader, n: number): number + if n == 0 then + return 0 + end + local v = peek(r, n) + skip(r, n) + return v +end + +type Table = { tab: buffer, P: number, S: number, single: number } + +@native local function newTable(nsym: number, P: number): Table + return { tab = buffer.create(Huffman.capacity(nsym, P, 16) * 4), P = P, S = 0, single = -1 } +end + +@native local function build(t: Table, lens: buffer, n: number): boolean + t.single = -1 + local S = Huffman.buildMsb(lens, 0, n, t.tab, t.P) + if S < 0 then + return false + end + t.S = S + return true +end + +@native local function decodeSym(r: Reader, t: Table): number + if t.single >= 0 then + return t.single + end + local P, S = t.P, t.S + local e = readu32(t.tab, peek(r, P) * 4) + local l = band(e, 31) + if l == 0 then + if e == 0 then + return -1 + end + local idx = peek(r, P + S) + e = readu32(t.tab, (rshift(e, 5) + band(idx, lshift(1, S) - 1)) * 4) + l = band(e, 31) + if l == 0 then + return -1 + end + end + skip(r, l) + return rshift(e, 5) +end + +local lens = buffer.create(512) + +@native local function lengthValue(r: Reader): number + local len = bits(r, 3) + if len == 7 then + while bits(r, 1) == 1 do + len += 1 + if len > 16 then + return 17 + end + end + end + return len +end + +-- the temp (code-length code) table and the offset table share this layout; special = 2 for the temp table +@native local function readLengths(r: Reader, t: Table, nbits: number, maxN: number, special: number): boolean + local n = bits(r, nbits) + if n == 0 then + t.single = bits(r, nbits) + return true + end + n = math.min(n, maxN) + buffer.fill(lens, 0, 0, 512) + local i = 0 + while i < n do + local l = lengthValue(r) + if l > 16 then + return false + end + writeu8(lens, i, l) + if i == special then + local z = bits(r, 2) + i += z + end + i += 1 + end + return build(t, lens, math.min(i, maxN)) +end + +@native local function readCodes(r: Reader, temp: Table, codes: Table): boolean + local n = bits(r, 9) + if n == 0 then + codes.single = bits(r, 9) + return true + end + n = math.min(n, 510) + buffer.fill(lens, 0, 0, 512) + local i = 0 + while i < n do + local c = decodeSym(r, temp) + if c < 0 then + return false + end + if c <= 2 then + local count = if c == 0 then 1 elseif c == 1 then bits(r, 4) + 3 else bits(r, 9) + 20 + i += count + else + if c - 2 > 16 then + return false + end + writeu8(lens, i, c - 2) + i += 1 + end + end + return build(codes, lens, n) +end + +local OFFSET_BITS = { lh4 = 4, lh5 = 4, lh6 = 5, lh7 = 5, lhx = 5 } + +@native local function decodeNew(src: buffer, off: number, len: number, out: buffer, n: number, method: string): string? + local r = reader(src, off, len) + local obits = OFFSET_BITS[method] + local temp, codes, offs = newTable(19, 8), newTable(510, 10), newTable(32, 8) + local o = 0 + local remaining = 0 + while o < n do + if remaining == 0 then + remaining = bits(r, 16) + if not readLengths(r, temp, 5, 19, 2) or not readCodes(r, temp, codes) or not readLengths(r, offs, obits, lshift(1, obits) - 1, -1) then + return if r.over > 0 then "truncated" else "bad Huffman table" + end + if r.over > 32 then + return "truncated" + end + if remaining == 0 then + return "empty block" + end + end + remaining -= 1 + local c = decodeSym(r, codes) + if c < 0 then + return "bad code" + end + if c < 256 then + writeu8(out, o, c) + o += 1 + else + local count = c - 256 + 3 + local p = decodeSym(r, offs) + if p < 0 then + return "bad offset code" + end + if p > 1 then + p = lshift(1, p - 1) + bits(r, p - 1) + end + local from = o - p - 1 + for _ = 1, count do + if o >= n then + break + end + writeu8(out, o, if from >= 0 then readu8(out, from) else 0x20) + o += 1 + from += 1 + end + end + if r.over > 32 then + return "truncated" + end + end + return nil +end + +local NUM_CODES = 314 +local NUM_NODES = NUM_CODES * 2 - 1 +local REORDER = 32 * 1024 +local FDIST = { 1, 3, 8, 12, 24, 16 } + +local offsetLookup = table.create(256, 0) +local offsetLength = table.create(64, 0) +do + local code, offset = 0, 0 + for i, count in FDIST do + local l = i - 1 + 3 + local iter = lshift(1, 8 - l) + for _ = 1, count do + for k = 0, iter - 1 do + offsetLookup[code + k + 1] = offset + end + offsetLength[offset + 1] = l + code += iter + offset += 1 + end + end +end + +@native local function decodeLh1(src: buffer, off: number, len: number, out: buffer, n: number): string? + local r = reader(src, off, len) + local leaf = table.create(NUM_NODES, false) + local child = table.create(NUM_NODES, 0) + local parent = table.create(NUM_NODES, 0) + local freq = table.create(NUM_NODES, 0) + local group = table.create(NUM_NODES, 0) + local leafNodes = table.create(NUM_CODES, 0) + local groups = table.create(NUM_NODES, 0) + local leader = table.create(NUM_NODES, 0) + local numGroups = 0 + @native local function initGroups() + for i = 0, NUM_NODES - 1 do + groups[i + 1] = i + end + numGroups = 0 + end + @native local function allocGroup(): number + local g = groups[numGroups + 1] + numGroups += 1 + return g + end + @native local function freeGroup(g: number) + numGroups -= 1 + groups[numGroups + 1] = g + end + initGroups() + do + local ni = NUM_NODES - 1 + local lg = allocGroup() + for i = 0, NUM_CODES - 1 do + leaf[ni + 1], child[ni + 1], freq[ni + 1], group[ni + 1] = true, i, 1, lg + leader[lg + 1] = ni + leafNodes[i + 1] = ni + ni -= 1 + end + local c = NUM_NODES - 1 + while ni >= 0 do + leaf[ni + 1], child[ni + 1] = false, c + parent[c + 1], parent[c] = ni, ni + freq[ni + 1] = freq[c + 1] + freq[c] + if freq[ni + 1] == freq[ni + 2] then + group[ni + 1] = group[ni + 2] + else + group[ni + 1] = allocGroup() + end + leader[group[ni + 1] + 1] = ni + ni -= 1 + c -= 2 + end + end + @native local function makeLeader(ni: number): number + local g = group[ni + 1] + local li = leader[g + 1] + if li == ni then + return ni + end + leaf[li + 1], leaf[ni + 1] = leaf[ni + 1], leaf[li + 1] + child[li + 1], child[ni + 1] = child[ni + 1], child[li + 1] + for _, x in { ni, li } do + if leaf[x + 1] then + leafNodes[child[x + 1] + 1] = x + else + parent[child[x + 1] + 1] = x + parent[child[x + 1]] = x + end + end + return li + end + @native local function incrementNode(ni: number) + freq[ni + 1] += 1 + if ni < NUM_NODES - 1 and group[ni + 1] == group[ni + 2] then + leader[group[ni + 1] + 1] += 1 + if freq[ni + 1] == freq[ni] then + group[ni + 1] = group[ni] + else + group[ni + 1] = allocGroup() + leader[group[ni + 1] + 1] = ni + end + elseif freq[ni + 1] == freq[ni] then + freeGroup(group[ni + 1]) + group[ni + 1] = group[ni] + end + end + @native local function reconstruct() + -- leaves to the front, halved + local li = 0 + for i = 0, NUM_NODES - 1 do + if leaf[i + 1] then + leaf[li + 1], child[li + 1], freq[li + 1] = true, child[i + 1], (freq[i + 1] + 1) // 2 + li += 1 + end + end + local lp = NUM_CODES - 1 + local c = NUM_NODES - 1 + local i = NUM_NODES - 1 + while i >= 0 do + while c - i < 2 do + leaf[i + 1], child[i + 1], freq[i + 1] = leaf[lp + 1], child[lp + 1], freq[lp + 1] + leafNodes[child[i + 1] + 1] = i + i -= 1 + lp -= 1 + end + local f = freq[c + 1] + freq[c] + while lp >= 0 and f >= freq[lp + 1] do + leaf[i + 1], child[i + 1], freq[i + 1] = leaf[lp + 1], child[lp + 1], freq[lp + 1] + leafNodes[child[i + 1] + 1] = i + i -= 1 + lp -= 1 + end + leaf[i + 1], freq[i + 1], child[i + 1] = false, f, c + parent[c + 1], parent[c] = i, i + i -= 1 + c -= 2 + end + initGroups() + local g = allocGroup() + group[1] = g + leader[g + 1] = 0 + for k = 1, NUM_NODES - 1 do + if freq[k + 1] == freq[k] then + group[k + 1] = group[k] + else + g = allocGroup() + group[k + 1] = g + leader[g + 1] = k + end + end + end + local o = 0 + while o < n do + local ni = 0 + local guard = 0 + while not leaf[ni + 1] do + ni = child[ni + 1] - bits(r, 1) + guard += 1 + if guard > NUM_NODES or ni < 0 then + return "bad tree" + end + end + local code = child[ni + 1] + -- lhasa's increment_for_code + if freq[1] >= REORDER then + reconstruct() + end + freq[1] += 1 + local x = leafNodes[code + 1] + while x ~= 0 do + x = makeLeader(x) + incrementNode(x) + x = parent[x + 1] + end + if code < 256 then + writeu8(out, o, code) + o += 1 + else + local future = peek(r, 8) + local hi = offsetLookup[future + 1] + skip(r, offsetLength[hi + 1]) + local offset = hi * 64 + bits(r, 6) + local count = code - 256 + 3 + local from = o - offset - 1 + for _ = 1, count do + if o >= n then + break + end + writeu8(out, o, if from >= 0 then readu8(out, from) else 0x20) + o += 1 + from += 1 + end + end + if r.over > 32 then + return "truncated" + end + end + return nil +end + +-- LArc lzs / lz5: a 2 KB / 4 KB ring (absolute ring positions, not distances) +@native local function decodeLzs(src: buffer, off: number, len: number, out: buffer, n: number): string? + local r = reader(src, off, len) + local ring = buffer.create(2048) + buffer.fill(ring, 0, 0x20) + local rp = 2048 - 17 + local o = 0 + while o < n do + if bits(r, 1) == 1 then + local b = bits(r, 8) + writeu8(out, o, b) + writeu8(ring, rp, b) + rp = (rp + 1) % 2048 + o += 1 + else + local pos = bits(r, 11) + local l = bits(r, 4) + 2 + for k = 0, l - 1 do + if o >= n then + break + end + local b = readu8(ring, (pos + k) % 2048) + writeu8(out, o, b) + writeu8(ring, rp, b) + rp = (rp + 1) % 2048 + o += 1 + end + end + if r.over > 32 then + return "truncated" + end + end + return nil +end + +local LZ5_INIT = buffer.create(4096) +do + local p = 0 + for i = 0, 255 do + for _ = 1, 13 do + writeu8(LZ5_INIT, p, i) + p += 1 + end + end + for i = 0, 255 do + writeu8(LZ5_INIT, p, i) + p += 1 + end + for i = 0, 255 do + writeu8(LZ5_INIT, p, 255 - i) + p += 1 + end + p += 128 + for _ = 1, 110 do + writeu8(LZ5_INIT, p, 0x20) + p += 1 + end +end + +@native local function decodeLz5(src: buffer, off: number, len: number, out: buffer, n: number): string? + local ring = buffer.create(4096) + buffer.copy(ring, 0, LZ5_INIT) + local rp = 4096 - 18 + local p = off + local limit = math.min(off + len, buffer.len(src)) + local o = 0 + while o < n do + if p >= limit then + return "truncated" + end + local flags = readu8(src, p) + p += 1 + for bit = 0, 7 do + if o >= n then + break + end + if band(flags, lshift(1, bit)) ~= 0 then + if p >= limit then + return "truncated" + end + local b = readu8(src, p) + p += 1 + writeu8(out, o, b) + writeu8(ring, rp, b) + rp = (rp + 1) % 4096 + o += 1 + else + if p + 2 > limit then + return "truncated" + end + local c0, c1 = readu8(src, p), readu8(src, p + 1) + p += 2 + local start = lshift(band(c1, 0xF0), 4) + c0 + local l = band(c1, 15) + 3 + for k = 0, l - 1 do + if o >= n then + break + end + local b = readu8(ring, (start + k) % 4096) + writeu8(out, o, b) + writeu8(ring, rp, b) + rp = (rp + 1) % 4096 + o += 1 + end + end + end + end + return nil +end + +@native local function decodeArj4(src: buffer, off: number, len: number, out: buffer, n: number): string? + local r = reader(src, off, len) + @native local function prefixed(start: number, stop: number): number + local plus, pwr = 0, lshift(1, start) + local width = start + while width < stop do + if bits(r, 1) == 0 then + break + end + plus += pwr + pwr *= 2 + width += 1 + end + return (if width ~= 0 then bits(r, width) else 0) + plus + end + local o = 0 + while o < n do + local c = prefixed(0, 7) + if c == 0 then + writeu8(out, o, bits(r, 8)) + o += 1 + else + local count = c - 1 + 3 + local pos = prefixed(9, 13) + local from = o - pos - 1 + for _ = 1, count do + if o >= n then + break + end + writeu8(out, o, if from >= 0 then readu8(out, from) else 0) + o += 1 + from += 1 + end + end + if r.over > 32 then + return "truncated" + end + end + return nil +end + +Lzh.METHODS = { "lh1", "lh4", "lh5", "lh6", "lh7", "lhx", "lzs", "lz5", "arj4" } + +@native function Lzh.decode(src: buffer, off: number, len: number, outSize: number, method: string): (buffer?, string?) + if off < 0 or len < 0 or off > buffer.len(src) or outSize < 0 or outSize ~= outSize then + return nil, "bad arguments" + end + local out = buffer.create(outSize) + if outSize == 0 then + return out, nil + end + local err: string? + if OFFSET_BITS[method] then + err = decodeNew(src, off, len, out, outSize, method) + elseif method == "lh1" then + err = decodeLh1(src, off, len, out, outSize) + elseif method == "lzs" then + err = decodeLzs(src, off, len, out, outSize) + elseif method == "lz5" then + err = decodeLz5(src, off, len, out, outSize) + elseif method == "arj4" then + err = decodeArj4(src, off, len, out, outSize) + else + return nil, "unsupported: method " .. tostring(method) + end + if err then + return nil, err + end + return out, nil +end + +return Lzh +end +__FILES["codecs/compress/Lzw"] = @native function() + + + +-- codecs/compress/Lzw: LZW decoder and encoder, from the GIF89a spec (appendix F) and TIFF 6.0 section 13 (new code). +-- gif: LSB-first, clear = 2^min, EOI = clear + 1, width grows when the next code reaches 2^width (max 12, then frozen). +-- tiff: MSB-first, clear = 256, EOI = 257, early change (at 2^width - 1). zoo (method 1): gif layout, up to 13 bits. +local readu8, writeu8, readu16, writeu16 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16 +local band, rshift, lshift = bit32.band, bit32.rshift, bit32.lshift +local blen = buffer.len + +local Lzw = {} + +local MAX_CODES = 4096 -- 12-bit codes (GIF, TIFF) +local TABLE = 8192 -- the tables hold 13-bit codes (Zoo) + +local prefix = buffer.create(TABLE * 2) +local suffix = buffer.create(TABLE) +local first = buffer.create(TABLE) +local length = buffer.create(TABLE * 2) + +@native local function emit(out: buffer, o: number, c: number, l: number, lim: number) + local p = o + l - 1 + if p < lim then + while p >= o do + writeu8(out, p, readu8(suffix, c)) + c = readu16(prefix, c * 2) + p -= 1 + end + else + while p >= o do + if p < lim then + writeu8(out, p, readu8(suffix, c)) + end + c = readu16(prefix, c * 2) + p -= 1 + end + end +end + +@native function Lzw.decode(src: buffer, off: number, len: number, out: buffer, outOff: number, maxOut: number, variant: string, minCodeSize: number?): (number, string?) + local n = blen(src) + if off < 0 or off > n then + return 0, "corrupt" + end + local e = math.min(off + math.max(0, len), n) + local lim = math.min(outOff + math.max(0, maxOut), blen(out)) + if outOff < 0 then + return 0, "corrupt" + end + local msb = variant == "tiff" + local early = 0 + local min = minCodeSize or 8 + local maxCodes, maxBits = MAX_CODES, 12 + if variant == "zoo" then + min, maxCodes, maxBits = 8, TABLE, 13 + end + if msb then + min = 8 + early = 1 + -- old-style TIFF LZW: LSB-first, no early change (libtiff LZWPreDecode's check) + if e - off >= 2 and readu8(src, off) == 0 and band(readu8(src, off + 1), 1) == 1 then + msb = false + early = 0 + end + end + if min < 1 or min > 11 then + return 0, "corrupt" + end + local clear = lshift(1, min) + local eoi = clear + 1 + for i = 0, clear - 1 do + writeu16(prefix, i * 2, 0) + writeu8(suffix, i, band(i, 255)) + writeu8(first, i, band(i, 255)) + writeu16(length, i * 2, 1) + end + local size = min + 1 + local mask = lshift(1, size) - 1 + local nextc = clear + 2 + local prev = -1 + local o = outOff + local p = off + local acc, nb = 0, 0 + while true do + while nb < size do + if p >= e then + return o - outOff, "truncated" + end + if msb then + acc = acc * 256 + readu8(src, p) + else + acc += lshift(readu8(src, p), nb) + end + p += 1 + nb += 8 + end + local c + if msb then + nb -= size + c = band(rshift(acc, nb), mask) + acc = band(acc, lshift(1, nb) - 1) + else + c = band(acc, mask) + acc = rshift(acc, size) + nb -= size + end + if c == clear then + size = min + 1 + mask = lshift(1, size) - 1 + nextc = clear + 2 + prev = -1 + elseif c == eoi then + return o - outOff, nil + else + if o >= lim then + return o - outOff, nil + end + if prev < 0 then + if c >= clear then + return o - outOff, "corrupt" + end + writeu8(out, o, readu8(suffix, c)) + o += 1 + prev = c + else + local l + if c < nextc then + l = readu16(length, c * 2) + emit(out, o, c, l, lim) + if nextc < maxCodes then + writeu16(prefix, nextc * 2, prev) + writeu8(suffix, nextc, readu8(first, c)) + writeu8(first, nextc, readu8(first, prev)) + writeu16(length, nextc * 2, readu16(length, prev * 2) + 1) + nextc += 1 + end + elseif c == nextc and nextc < maxCodes then + -- KwKwK: the new entry is prev + first(prev) + local f = readu8(first, prev) + writeu16(prefix, nextc * 2, prev) + writeu8(suffix, nextc, f) + writeu8(first, nextc, f) + l = readu16(length, prev * 2) + 1 + writeu16(length, nextc * 2, l) + nextc += 1 + emit(out, o, c, l, lim) + else + return o - outOff, "corrupt" + end + o = math.min(o + l, lim) + prev = c + end + if nextc + early >= lshift(1, size) and size < maxBits then + size += 1 + mask = lshift(1, size) - 1 + end + end + end +end + +local HASH = 8192 +local hkey = buffer.create(HASH * 4) +local hval = buffer.create(HASH * 2) + +@native function Lzw.encode(data: buffer, off: number, len: number, variant: string, minCodeSize: number?): buffer + local msb = variant == "tiff" + local min = if msb then 8 else math.clamp(minCodeSize or 8, 1, 11) + local early = if msb then 1 else 0 + local symMask = lshift(1, min) - 1 + local clear = lshift(1, min) + local eoi = clear + 1 + local n = blen(data) + off = math.clamp(off, 0, n) + local e = math.clamp(off + len, off, n) + local cap = (e - off) * 2 + 64 + local out = buffer.create(cap) + local op = 0 + local acc, nb = 0, 0 + local size = min + 1 + @native local function put(code: number) + if op + 4 > cap then + cap *= 2 + local nbuf = buffer.create(cap) + buffer.copy(nbuf, 0, out, 0, op) + out = nbuf + end + if msb then + acc = acc * lshift(1, size) + code + nb += size + while nb >= 8 do + nb -= 8 + writeu8(out, op, rshift(acc, nb)) + op += 1 + acc = band(acc, lshift(1, nb) - 1) + end + else + acc += lshift(code, nb) + nb += size + while nb >= 8 do + writeu8(out, op, band(acc, 255)) + op += 1 + acc = rshift(acc, 8) + nb -= 8 + end + end + end + buffer.fill(hkey, 0, 0, HASH * 4) + local nextc = clear + 2 + put(clear) + if e > off then + local cur = band(readu8(data, off), symMask) + for i = off + 1, e - 1 do + local b = band(readu8(data, i), symMask) + local key = cur * 256 + b + 1 + local h = band(cur * 31 + b * 4099, HASH - 1) + local found = -1 + while true do + local k = buffer.readi32(hkey, h * 4) + if k == 0 then + break + elseif k == key then + found = readu16(hval, h * 2) + break + end + h = band(h + 1, HASH - 1) + end + if found >= 0 then + cur = found + else + put(cur) + if nextc >= MAX_CODES - 2 then + put(clear) + size = min + 1 + nextc = clear + 2 + buffer.fill(hkey, 0, 0, HASH * 4) + else + buffer.writei32(hkey, h * 4, key) + writeu16(hval, h * 2, nextc) + nextc += 1 + if nextc + early > lshift(1, size) and size < 12 then + size += 1 + end + end + cur = b + end + end + put(cur) + -- the decoder adds an entry for this last code too: its width may grow before EOI + if nextc < MAX_CODES then + nextc += 1 + if nextc + early > lshift(1, size) and size < 12 then + size += 1 + end + end + end + put(eoi) + if nb > 0 then + writeu8(out, op, if msb then band(lshift(acc, 8 - nb), 255) else band(acc, 255)) + op += 1 + end + local res = buffer.create(op) + buffer.copy(res, 0, out, 0, op) + return res +end + +return Lzw +end +__FILES["codecs/compress/Lzx"] = @native function() + + + +-- codecs/compress/Lzx: the LZX decoder for Microsoft Cabinet folders (windows of 2^15 .. 2^21 bytes). +-- Written from Microsoft's LZX data format documentation (Cabinet SDK) and [MS-PATCH]; no code from libmspack. +-- Frames of 32768 output bytes, 16-bit aligned at their ends; trees, R0..R2 and the window persist across a folder. +local Huffman = __include("codecs/entropy/Huffman") + +local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift +local readu8, readu16, readu32, readi32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi32 +local writeu8, writei32 = buffer.writeu8, buffer.writei32 +local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len + +local Lzx = {} + +local FRAME = 32768 +local MAINP, LENP, ALIGNP, PREP = 10, 8, 7, 6 +local MAXMAIN = 256 + 8 * 50 +local NLEN = 249 +local SAFETY = 64 -- pre-tree runs may run past the end of a tree: room for them (as the format's reference decoder) + +-- position slots: footer bits and base of each formatted offset slot +local EXTRA = table.create(51, 0) +local BASE = table.create(51, 0) +do + local b = 0 + for i = 0, 50 do + local e = if i < 4 then 0 else math.min(i // 2 - 1, 17) + EXTRA[i + 1] = e + BASE[i + 1] = b + b += lshift(1, e) + end +end +local SLOTS: { [number]: number } = { [15] = 30, [16] = 32, [17] = 34, [18] = 36, [19] = 38, [20] = 42, [21] = 50 } + +-- 16-bit little-endian words, read most significant bit first +type State = { src: buffer, pos: number, stop: number, bb: number, cnt: number, over: number } + +@native local function refill(s: State) + while s.cnt <= 16 do + local p = s.pos + local w = 0 + if p + 2 <= s.stop then + w = readu16(s.src, p) + s.pos = p + 2 + elseif p < s.stop then + w = readu8(s.src, p) + s.pos = p + 1 + s.over += 8 + else + s.over += 16 + end + s.bb = bor(s.bb, lshift(w, 16 - s.cnt)) + s.cnt += 16 + end +end + +@native local function bits(s: State, n: number): number + if s.cnt < n then + refill(s) + end + local v = rshift(s.bb, 32 - n) + s.bb = lshift(s.bb, n) + s.cnt -= n + return v +end + +@native local function sym(s: State, tab: buffer, P: number, S: number): number + if s.cnt < 16 then + refill(s) + end + local e = readu32(tab, rshift(s.bb, 32 - P) * 4) + local l = band(e, 31) + if l == 0 then + if e == 0 then + return -1 + end + e = readu32(tab, (rshift(e, 5) + band(rshift(s.bb, 32 - P - S), lshift(1, S) - 1)) * 4) + l = band(e, 31) + if l == 0 then + return -1 + end + end + s.bb = lshift(s.bb, l) + s.cnt -= l + return rshift(e, 5) +end + +-- code lengths as deltas of their previous values, through a fresh 20-symbol pre-tree (runs 17 / 18 / 19) +@native local function readLens(s: State, lens: buffer, first: number, last: number, pre: buffer, preLens: buffer): boolean + for i = 0, 19 do + writeu8(preLens, i, bits(s, 4)) + end + local S = Huffman.buildMsb(preLens, 0, 20, pre, PREP) + if S < 0 then + return false + end + local cap = blen(lens) + local x = first + while x < last do + local z = sym(s, pre, PREP, S) + if z < 0 then + return false + end + if z == 17 or z == 18 then + local run = if z == 17 then bits(s, 4) + 4 else bits(s, 5) + 20 + for _ = 1, run do + if x < cap then + writeu8(lens, x, 0) + end + x += 1 + end + elseif z == 19 then + local run = bits(s, 1) + 4 + local d = sym(s, pre, PREP, S) + if d < 0 or d > 16 then + return false + end + local v = (readu8(lens, x) - d + 17) % 17 + for _ = 1, run do + if x < cap then + writeu8(lens, x, v) + end + x += 1 + end + else + writeu8(lens, x, (readu8(lens, x) - z + 17) % 17) + x += 1 + end + end + return true +end + +-- E8 translation, frame by frame: absolute call targets back to relative +@native local function translate(out: buffer, n: number, size: number) + local base = 0 + local frame = 0 + while base < n and frame < 32768 do + local fs = math.min(FRAME, n - base) + if fs > 10 then + local i = base + local stop = base + fs - 10 + while i < stop do + if readu8(out, i) == 0xE8 then + local abs = readi32(out, i + 1) + if abs >= -i and abs < size then + writei32(out, i + 1, if abs >= 0 then abs - i else abs + size) + end + i += 5 + else + i += 1 + end + end + end + base += fs + frame += 1 + end +end + +@native function Lzx.decode(src: buffer, offset: number, length: number, outSize: number, windowBits: number): (buffer?, string?) + local nslots = SLOTS[windowBits] + if not nslots then + return nil, "unsupported: LZX window 2^" .. tostring(windowBits) + end + if offset < 0 or length < 0 or offset + length > blen(src) or outSize < 0 or outSize % 1 ~= 0 then + return nil, "bad arguments" + end + local windowSize = lshift(1, windowBits) + local mainN = 256 + 8 * nslots + local out = bcreate(outSize) + local mainLens, lenLens, alignLens, preLens = bcreate(MAXMAIN + SAFETY), bcreate(NLEN + SAFETY), bcreate(8), bcreate(20) + local mainTab = bcreate(Huffman.capacity(MAXMAIN, MAINP, 16) * 4) + local lenTab = bcreate(Huffman.capacity(NLEN, LENP, 16) * 4) + local alignTab = bcreate(Huffman.capacity(8, ALIGNP, 16) * 4) + local preTab = bcreate(Huffman.capacity(20, PREP, 16) * 4) + local s: State = { src = src, pos = offset, stop = offset + length, bb = 0, cnt = 0, over = 0 } + local R0: number, R1: number, R2: number = 1, 1, 1 + local intel = 0 + local started = false + local btype, bremain, bsize = 0, 0, 0 + local mainS, lenS, alignS = 0, 0, 0 + local op = 0 + while op < outSize do + local frameEnd = math.min(op + FRAME, outSize) + while op < frameEnd do + if bremain == 0 then + if btype == 3 and band(bsize, 1) == 1 then + s.pos += 1 + end + if not started then + started = true + if bits(s, 1) == 1 then + local hi = bits(s, 16) + intel = hi * 65536 + bits(s, 16) + end + end + btype = bits(s, 3) + local hi = bits(s, 16) + bsize = hi * 256 + bits(s, 8) + bremain = bsize + if s.over > s.cnt then + return nil, "truncated input" + end + if bsize == 0 then + return nil, "empty block" + end + if btype == 2 then + for i = 0, 7 do + writeu8(alignLens, i, bits(s, 3)) + end + alignS = Huffman.buildMsb(alignLens, 0, 8, alignTab, ALIGNP) + if alignS < 0 then + return nil, "bad aligned offset tree" + end + end + if btype == 1 or btype == 2 then + if not readLens(s, mainLens, 0, 256, preTab, preLens) or not readLens(s, mainLens, 256, mainN, preTab, preLens) then + return nil, "bad main tree" + end + mainS = Huffman.buildMsb(mainLens, 0, mainN, mainTab, MAINP) + if mainS < 0 then + return nil, "bad main tree" + end + if not readLens(s, lenLens, 0, NLEN, preTab, preLens) then + return nil, "bad length tree" + end + lenS = Huffman.buildMsb(lenLens, 0, NLEN, lenTab, LENP) + if lenS < 0 then + return nil, "bad length tree" + end + elseif btype == 3 then + -- 1..16 bits of padding to a 16-bit boundary, then R0..R2 and the bytes + local k = s.cnt % 16 + if k == 0 then + k = 16 + end + local p = s.pos - (s.cnt - k) // 8 + s.bb, s.cnt = 0, 0 + if s.over > 0 or p + 12 > s.stop then + return nil, "truncated uncompressed block" + end + R0 = readu32(src, p) + R1 = readu32(src, p + 4) + R2 = readu32(src, p + 8) + s.pos = p + 12 + else + return nil, "bad block type " .. btype + end + if s.over > s.cnt then + return nil, "truncated input" + end + end + local runEnd = op + math.min(bremain, frameEnd - op) + if btype == 3 then + local n = runEnd - op + local p = s.pos + if p + n > s.stop then + return nil, "truncated uncompressed block" + end + bcopy(out, op, src, p, n) + s.pos = p + n + op += n + bremain -= n + else + local bb, cnt, pos, over = s.bb, s.cnt, s.pos, s.over + local stop = s.stop + local aligned = btype == 2 + local start = op + while op < runEnd do + while cnt <= 16 do + local w = 0 + if pos + 2 <= stop then + w = readu16(src, pos) + pos += 2 + elseif pos < stop then + w = readu8(src, pos) + pos += 1 + over += 8 + else + over += 16 + end + bb = bor(bb, lshift(w, 16 - cnt)) + cnt += 16 + end + local e = readu32(mainTab, rshift(bb, 32 - MAINP) * 4) + local l = band(e, 31) + if l == 0 then + if e == 0 then + return nil, "bad main code" + end + e = readu32(mainTab, (rshift(e, 5) + band(rshift(bb, 32 - MAINP - mainS), lshift(1, mainS) - 1)) * 4) + l = band(e, 31) + if l == 0 then + return nil, "bad main code" + end + end + bb = lshift(bb, l) + cnt -= l + local m = rshift(e, 5) + if m < 256 then + writeu8(out, op, m) + op += 1 + else + m -= 256 + local len = band(m, 7) + if len == 7 then + while cnt <= 16 do + local w = 0 + if pos + 2 <= stop then + w = readu16(src, pos) + pos += 2 + else + over += 16 + end + bb = bor(bb, lshift(w, 16 - cnt)) + cnt += 16 + end + local le = readu32(lenTab, rshift(bb, 32 - LENP) * 4) + local ll = band(le, 31) + if ll == 0 then + if le == 0 then + return nil, "bad length code" + end + le = readu32(lenTab, (rshift(le, 5) + band(rshift(bb, 32 - LENP - lenS), lshift(1, lenS) - 1)) * 4) + ll = band(le, 31) + if ll == 0 then + return nil, "bad length code" + end + end + bb = lshift(bb, ll) + cnt -= ll + len += rshift(le, 5) + end + len += 2 + local slot = rshift(m, 3) + local dist: number + if slot == 0 then + dist = R0 + elseif slot == 1 then + dist = R1 + R1 = R0 + R0 = dist + elseif slot == 2 then + dist = R2 + R2 = R0 + R0 = dist + else + local ex = EXTRA[slot + 1] + dist = BASE[slot + 1] - 2 + if ex > 0 then + while cnt <= 16 do + local w = 0 + if pos + 2 <= stop then + w = readu16(src, pos) + pos += 2 + else + over += 16 + end + bb = bor(bb, lshift(w, 16 - cnt)) + cnt += 16 + end + if aligned and ex >= 3 then + if ex > 3 then + dist += lshift(rshift(bb, 35 - ex), 3) + bb = lshift(bb, ex - 3) + cnt -= ex - 3 + while cnt <= 16 do + local w = 0 + if pos + 2 <= stop then + w = readu16(src, pos) + pos += 2 + else + over += 16 + end + bb = bor(bb, lshift(w, 16 - cnt)) + cnt += 16 + end + end + local ae = readu32(alignTab, rshift(bb, 32 - ALIGNP) * 4) + local al = band(ae, 31) + if al == 0 then + return nil, "bad aligned offset code" + end + bb = lshift(bb, al) + cnt -= al + dist += rshift(ae, 5) + else + dist += rshift(bb, 32 - ex) + bb = lshift(bb, ex) + cnt -= ex + end + end + R2 = R1 + R1 = R0 + R0 = dist + end + if dist < 1 or dist > op or dist > windowSize then + return nil, "match offset before the start of the data" + end + if op + len > runEnd then + return nil, "match past the end of its block or frame" + end + local from = op - dist + if dist >= len then + bcopy(out, op, out, from, len) + else + for k = 0, len - 1 do + writeu8(out, op + k, readu8(out, from + k)) + end + end + op += len + end + end + s.bb, s.cnt, s.pos, s.over = bb, cnt, pos, over + bremain -= op - start + end + end + -- the end of a frame: realign to 16 bits + local k = s.cnt % 16 + s.bb = lshift(s.bb, k) + s.cnt -= k + if s.over > s.cnt then + return nil, "truncated input" + end + end + if intel ~= 0 then + translate(out, outSize, intel) + end + return out, nil +end + +return Lzx +end +__FILES["codecs/compress/PackBits"] = @native function() + + + +-- codecs/compress/PackBits: the Apple PackBits run-length code (TIFF compression 32773, PSD RLE, IFF ByteRun1). +-- Header byte n < 128 copies n + 1 literal bytes, n > 128 repeats the next byte 257 - n times, 128 is a no-op. +local PackBits = {} + +local readu8, writeu8 = buffer.readu8, buffer.writeu8 + +@native 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 + +@native 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 +end +__FILES["codecs/compress/Quantum"] = @native function() + + + +-- codecs/compress/Quantum: the Quantum decoder (David Stafford's LZ77 + adaptive arithmetic coder) for Cabinet folders. +-- Written from Matthew Russotto's Quantum notes and the cabinet documentation; no code from libmspack. Frequencies grow +-- by 8 and rescale above 3800 (halved; every 50th time rebuilt and re-sorted); each CFDATA frame restarts the coder. + +local band, bor, bxor, lshift, rshift = bit32.band, bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift +local readu8, writeu8 = buffer.readu8, buffer.writeu8 +local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len +local floor = math.floor + +local Quantum = {} + +-- position slots (offset - 1 = base + footer) and length slots (length - 5 = base + footer) +local PBASE = table.create(42, 0) +local PEXTRA = table.create(42, 0) +do + local b = 0 + for i = 0, 41 do + local e = if i < 4 then 0 else i // 2 - 1 + PEXTRA[i + 1] = e + PBASE[i + 1] = b + b += lshift(1, e) + end +end +local LEXTRA = { 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 } +local LBASE = table.create(27, 0) +do + local b = 0 + for i = 1, 27 do + LBASE[i] = b + b += lshift(1, LEXTRA[i]) + end +end + +-- model: sym[1..n] in their current order, cumulative frequencies cum[1..n + 1] (cum[n + 1] = 0) +type Model = { n: number, sym: { number }, cum: { number }, shifts: number } + +@native local function model(first: number, n: number): Model + local sym = table.create(n, 0) + local cum = table.create(n + 1, 0) + for i = 1, n do + sym[i] = first + i - 1 + cum[i] = n - i + 1 + end + cum[n + 1] = 0 + return { n = n, sym = sym, cum = cum, shifts = 4 } +end + +@native local function rescale(m: Model) + local n, sym, cum = m.n, m.sym, m.cum + m.shifts -= 1 + if m.shifts > 0 then + for i = n, 1, -1 do + local c = rshift(cum[i], 1) + if c <= cum[i + 1] then + c = cum[i + 1] + 1 + end + cum[i] = c + end + return + end + m.shifts = 50 + -- cumulative -> halved frequencies (rounded up: no symbol drops to zero) + for i = 1, n do + cum[i] = rshift(cum[i] - cum[i + 1] + 1, 1) + end + -- sort by frequency, decreasing (a selection-style exchange sort: its order of equal frequencies is the format's) + for i = 1, n - 1 do + for j = i + 1, n do + if cum[i] < cum[j] then + cum[i], cum[j] = cum[j], cum[i] + sym[i], sym[j] = sym[j], sym[i] + end + end + end + for i = n, 1, -1 do + cum[i] += cum[i + 1] + end +end + +type Coder = { src: buffer, pos: number, stop: number, acc: number, cnt: number, over: number, H: number, L: number, C: number, bad: boolean } + +@native local function bit(c: Coder): number + if c.cnt == 0 then + local p = c.pos + if p < c.stop then + c.acc = readu8(c.src, p) + c.pos = p + 1 + else + c.acc = 0 + c.over += 1 + end + c.cnt = 8 + end + c.cnt -= 1 + return band(rshift(c.acc, c.cnt), 1) +end + +@native local function raw(c: Coder, n: number): number + local v = 0 + for _ = 1, n do + v = v * 2 + bit(c) + end + return v +end + +@native local function symbol(c: Coder, m: Model): number + local cum = m.cum + local H, L, C = c.H, c.L, c.C + local range = H - L + 1 + local total = cum[1] + if range <= 0 or C < L or C > H then + c.bad = true + return 0 + end + local f = band(floor(((C - L + 1) * total - 1) / range), 0xFFFF) + local n = m.n + local i = 2 + while i <= n and cum[i] > f do + i += 1 + end + -- the symbol is sym[i - 1]: its interval is [cum[i], cum[i - 1]) + local s = m.sym[i - 1] + H = L + floor(cum[i - 1] * range / total) - 1 + L = L + floor(cum[i] * range / total) + for k = 1, i - 1 do + cum[k] += 8 + end + if cum[1] > 3800 then + rescale(m) + end + while true do + if band(bxor(L, H), 0x8000) ~= 0 then + if band(L, 0x4000) ~= 0 and band(H, 0x4000) == 0 then + -- underflow: L and H straddle the middle + C = bxor(C, 0x4000) + L = band(L, 0x3FFF) + H = bor(H, 0x4000) + else + break + end + end + L = band(lshift(L, 1), 0xFFFF) + H = bor(band(lshift(H, 1), 0xFFFF), 1) + C = bor(band(lshift(C, 1), 0xFFFF), bit(c)) + end + c.H, c.L, c.C = H, L, C + return s +end + +@native function Quantum.decode(src: buffer, blocks: { { at: number, len: number, size: number } }, outSize: number, windowBits: number): (buffer?, string?) + if type(windowBits) ~= "number" or windowBits < 10 or windowBits > 21 or windowBits % 1 ~= 0 then + return nil, "unsupported: Quantum window 2^" .. tostring(windowBits) + end + if outSize < 0 or outSize % 1 ~= 0 then + return nil, "bad output size" + end + local total = 0 + for _, b in blocks do + if b.at < 0 or b.len < 0 or b.at + b.len > blen(src) or b.size < 0 then + return nil, "bad block range" + end + total += b.size + end + if total ~= outSize then + return nil, "block sizes do not add up to the output size" + end + local window = lshift(1, windowBits) + local slots = windowBits * 2 + local selector = model(0, 7) + local lit = { model(0, 64), model(64, 64), model(128, 64), model(192, 64) } + local m3 = model(0, math.min(slots, 24)) + local m4 = model(0, math.min(slots, 36)) + local m5 = model(0, slots) + local mlen = model(0, 27) + local out = bcreate(outSize) + local op = 0 + for _, b in blocks do + local frameEnd = op + b.size + local c: Coder = { src = src, pos = b.at, stop = b.at + b.len, acc = 0, cnt = 0, over = 0, H = 0xFFFF, L = 0, C = 0, bad = false } + c.C = raw(c, 16) + while op < frameEnd do + local sel = symbol(c, selector) + if c.bad then + return nil, "bad arithmetic code" + end + if sel < 4 then + writeu8(out, op, symbol(c, lit[sel + 1])) + op += 1 + else + local len, slot + if sel == 4 then + len = 3 + slot = symbol(c, m3) + elseif sel == 5 then + len = 4 + slot = symbol(c, m4) + elseif sel == 6 then + local ls = symbol(c, mlen) + len = LBASE[ls + 1] + raw(c, LEXTRA[ls + 1]) + 5 + slot = symbol(c, m5) + else + return nil, "bad selector" + end + local dist = PBASE[slot + 1] + raw(c, PEXTRA[slot + 1]) + 1 + if dist > op or dist > window then + return nil, "match offset before the start of the data" + end + if op + len > frameEnd then + return nil, "match past the end of its frame" + end + local from = op - dist + if dist >= len then + bcopy(out, op, out, from, len) + else + for k = 0, len - 1 do + writeu8(out, op + k, readu8(out, from + k)) + end + end + op += len + end + if c.bad then + return nil, "bad arithmetic code" + end + if c.over > 4 then + return nil, "truncated frame" + end + end + end + return out, nil +end + +return Quantum +end +__FILES["codecs/compress/UnixCompress"] = @native function() + + + +-- codecs/compress/UnixCompress: the LZW of Unix compress (.Z: magic 1F 9D, a flags byte: max width 9..16, block mode). +-- From the ncompress sources (public domain: licenses/ncompress-UNLICENSE.txt); the encoder matches ncompress 5.0. +-- LSB-first codes from 9 bits; block mode code 256 clears; a width change or CLEAR skips the rest of the 8-code group. +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") + +local UnixCompress = {} + +type DecodeOptions = { maxBytes: number? } +type EncodeOptions = { maxBits: number? } + +local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32 +local band, bor, rshift, lshift = bit32.band, bit32.bor, bit32.rshift, bit32.lshift +local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len + +local MAXCODES = 65536 +local CHECK_GAP = 10000 + +local prefix = bcreate(MAXCODES * 4) +local suffix = bcreate(MAXCODES) +local first = bcreate(MAXCODES) +local length = bcreate(MAXCODES * 4) + +@native function UnixCompress.decompress(buf: buffer | string, offset: number?, len: number?, opts: DecodeOptions?): (buffer?, Err.Err?) + local b, o, n, aerr = Bytes.span("UnixCompress.decompress", buf, offset, len) + if not b then + return nil, aerr + end + local maxBytes = (opts and opts.maxBytes) or 2 ^ 30 + if n < 3 then + return nil, Err.new(Err.TRUNCATED, "header past the end", o) + end + if readu8(b, o) ~= 0x1F or readu8(b, o + 1) ~= 0x9D then + return nil, Err.new(Err.CORRUPT, "bad magic", o) + end + local flags = readu8(b, o + 2) + local maxbits = band(flags, 0x1F) + local block = band(flags, 0x80) ~= 0 + if maxbits < 9 or maxbits > 16 then + return nil, Err.new(Err.UNSUPPORTED, "maximum code width " .. maxbits, o + 2) + end + if band(flags, 0x60) ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "reserved flag bits set", o + 2) + end + local maxmax = lshift(1, maxbits) + for i = 0, 255 do + writeu32(prefix, i * 4, 0) + writeu8(suffix, i, i) + writeu8(first, i, i) + writeu32(length, i * 4, 1) + end + local cap = math.min(math.max(n * 3, 1024), maxBytes) + local out = bcreate(cap) + local op = 0 + local totalBits = (n - 3) * 8 + local base = o + 3 + local pos = 0 + local gbase = 0 + local nbits = 9 + local mask = 511 + local maxcode = 511 + local freeEnt = if block then 257 else 256 + local prev = -1 + while pos + nbits <= totalBits do + if freeEnt > maxcode then + local g = nbits * 8 + pos = gbase + (pos - gbase + g - 1) // g * g + gbase = pos + nbits += 1 + maxcode = if nbits == maxbits then maxmax else lshift(1, nbits) - 1 + mask = lshift(1, nbits) - 1 + continue + end + local q = base + rshift(pos, 3) + local acc = readu8(b, q) + if q + 1 < o + n then + acc = bor(acc, lshift(readu8(b, q + 1), 8)) + end + if q + 2 < o + n then + acc = bor(acc, lshift(readu8(b, q + 2), 16)) + end + local c = band(rshift(acc, band(pos, 7)), mask) + pos += nbits + if c == 256 and block then + local g = nbits * 8 + pos = gbase + (pos - gbase + g - 1) // g * g + gbase = pos + nbits = 9 + mask = 511 + maxcode = 511 + freeEnt = 257 + prev = -1 + continue + end + local l + if prev < 0 then + if c >= 256 then + return nil, Err.new(Err.CORRUPT, "first code is not a literal", base + rshift(pos, 3)) + end + l = 1 + elseif c < freeEnt then + l = readu32(length, c * 4) + elseif c == freeEnt then + l = readu32(length, prev * 4) + 1 + else + return nil, Err.new(Err.CORRUPT, "code past the table", base + rshift(pos, 3)) + end + if op + l > cap then + if op + l > maxBytes then + return nil, Err.new(Err.LIMIT, "output over " .. maxBytes .. " bytes") + end + local ncap = math.min(math.max(cap * 2, op + l), maxBytes) + local nb = bcreate(ncap) + bcopy(nb, 0, out, 0, op) + out, cap = nb, ncap + end + -- the new entry (prev + first byte of c's string) before the copy: KwKwK reads it + if prev >= 0 and freeEnt < maxmax then + local f = if c == freeEnt then readu8(first, prev) else readu8(first, c) + writeu32(prefix, freeEnt * 4, prev) + writeu8(suffix, freeEnt, f) + writeu8(first, freeEnt, readu8(first, prev)) + writeu32(length, freeEnt * 4, readu32(length, prev * 4) + 1) + freeEnt += 1 + elseif prev >= 0 then + if c == freeEnt then + return nil, Err.new(Err.CORRUPT, "code past the table", base + rshift(pos, 3)) + end + end + local p = op + l - 1 + local k = c + while p >= op do + writeu8(out, p, readu8(suffix, k)) + k = readu32(prefix, k * 4) + p -= 1 + end + op += l + prev = c + end + local res = bcreate(op) + bcopy(res, 0, out, 0, op) + return res, nil +end + +local HSIZE = 1 * 131072 +local hkey = bcreate(HSIZE * 4) +local hval = bcreate(HSIZE * 4) + +@native function UnixCompress.compress(buf: buffer | string, offset: number?, len: number?, opts: EncodeOptions?): (buffer?, Err.Err?) + local b, o, n, aerr = Bytes.span("UnixCompress.compress", buf, offset, len) + if not b then + return nil, aerr + end + local maxbits = (opts and opts.maxBits) or 16 + if type(maxbits) ~= "number" or maxbits < 9 or maxbits > 16 or maxbits % 1 ~= 0 then + return nil, Err.new(Err.ARG, "maxBits must be 9..16") + end + local cap = 3 + n * 2 + 64 + local out = bcreate(cap) + writeu8(out, 0, 0x1F) + writeu8(out, 1, 0x9D) + writeu8(out, 2, bor(maxbits, 0x80)) + local outbits = 24 + local boff = 24 + local acc, nb = 0, 0 + local nbits = 9 + local extcode = 513 + local maxmax = lshift(1, maxbits) + local stcode = true + local freeEnt = 257 + local ratio = 0 + local checkpoint = CHECK_GAP + buffer.fill(hkey, 0, 0, HSIZE * 4) + @native local function put(code: number) + acc = bor(acc, lshift(code, nb)) + nb += nbits + outbits += nbits + while nb >= 8 do + local q = rshift(outbits - nb, 3) + if q < cap then + writeu8(out, q, band(acc, 255)) + end + acc = rshift(acc, 8) + nb -= 8 + end + end + @native local function align() + -- round outbits up to a whole group of nbits-bit codes since boff; the skipped bits are zeros + local g = nbits * 8 + local nbits2 = boff + (outbits - boff + g - 1) // g * g + if nb > 0 then + local q = rshift(outbits - nb, 3) + if q < cap then + writeu8(out, q, band(acc, 255)) + end + end + acc, nb = 0, 0 + outbits = nbits2 + boff = nbits2 + end + if n == 0 then + local res = bcreate(3) + bcopy(res, 0, out, 0, 3) + return res, nil + end + local ent = readu8(b, o) + local e = o + n + local i = o + 1 + -- checks happen with a one-byte current string, right after an output (and at the start) + @native local function checks(consumed: number) + if freeEnt >= extcode then + if nbits < maxbits then + align() + nbits += 1 + extcode = if nbits < maxbits then lshift(1, nbits) + 1 else lshift(1, nbits) + else + extcode = math.huge + stcode = false + end + end + if not stcode and consumed >= checkpoint then + checkpoint = consumed + CHECK_GAP + local outBytes = rshift(outbits, 3) + local rat + if consumed > 0x7FFFFF then + local d = rshift(outBytes, 8) + rat = if d == 0 then 0x7FFFFFFF else consumed // d + else + rat = (consumed * 256) // outBytes + end + if rat >= ratio then + ratio = rat + else + ratio = 0 + buffer.fill(hkey, 0, 0, HSIZE * 4) + put(256) + align() + nbits = 9 + extcode = 513 + freeEnt = 257 + stcode = true + end + end + end + checks(1) + while i < e do + local c = readu8(b, i) + i += 1 + local key = ent * 256 + c + 1 + local h = band(ent * 4099 + c * 131 + rshift(ent, 5), HSIZE - 1) + local found = -1 + while true do + local k = readu32(hkey, h * 4) + if k == 0 then + break + elseif k == key then + found = readu32(hval, h * 4) + break + end + h = band(h + 1, HSIZE - 1) + end + if found >= 0 then + ent = found + else + put(ent) + if stcode then + writeu32(hkey, h * 4, key) + writeu32(hval, h * 4, freeEnt) + freeEnt += 1 + end + ent = c + checks(i - o) + end + if rshift(outbits, 3) + 8 > cap then + local ncap = cap * 2 + local nbuf = bcreate(ncap) + bcopy(nbuf, 0, out, 0, cap) + out, cap = nbuf, ncap + end + end + put(ent) + if nb > 0 then + local q = rshift(outbits - nb, 3) + if q < cap then + writeu8(out, q, band(acc, 255)) + end + end + local size = rshift(outbits + 7, 3) + local res = bcreate(size) + bcopy(res, 0, out, 0, math.min(size, cap)) + return res, nil +end + +@native function UnixCompress.isCompress(b: buffer, o: number?): boolean + local p = o or 0 + return p + 3 <= blen(b) and readu8(b, p) == 0x1F and readu8(b, p + 1) == 0x9D +end + +return UnixCompress +end +__FILES["codecs/compress/Xxh32"] = @native function() + + + +-- codecs/compress/Xxh32: XXH32 for the LZ4 frame checksums, from the xxHash specification (Yann Collet, BSD-2). +-- 32 x 32 -> 32 products split one operand into 16-bit limbs so every partial product is exact in a double. +local Xxh32 = {} + +local bxor, bor, lshift, rshift = bit32.bxor, bit32.bor, bit32.lshift, bit32.rshift +local readu8, readu32 = buffer.readu8, buffer.readu32 + +local T32 = 4294967296 +local P1, P2, P3, P4, P5 = 0x9E3779B1, 0x85EBCA77, 0xC2B2AE3D, 0x27D4EB2F, 0x165667B1 + +@native local function mul(a: number, b: number): number + local a0 = a % 65536 + local a1 = (a - a0) / 65536 + return (a0 * b + ((a1 * b) % 65536) * 65536) % T32 +end + +@native local function rotl(x: number, r: number): number + return bor(lshift(x, r), rshift(x, 32 - r)) +end + +@native local function round(acc: number, lane: number): number + return mul(rotl((acc + mul(lane, P2)) % T32, 13), P1) +end + +@native function Xxh32.hash(b: buffer, offset: number?, length: number?, seed: number?): number + local n0 = buffer.len(b) + local o = math.clamp(offset or 0, 0, n0) + local n = math.clamp(length or (n0 - o), 0, n0 - o) + local s = (seed or 0) % T32 + local p = o + local e = o + n + local h + if n >= 16 then + local v1 = (s + P1 + P2) % T32 + local v2 = (s + P2) % T32 + local v3 = s + local v4 = (s - P1) % T32 + local last = e - 16 + while p <= last do + v1 = round(v1, readu32(b, p)) + v2 = round(v2, readu32(b, p + 4)) + v3 = round(v3, readu32(b, p + 8)) + v4 = round(v4, readu32(b, p + 12)) + p += 16 + end + h = (rotl(v1, 1) + rotl(v2, 7) + rotl(v3, 12) + rotl(v4, 18)) % T32 + else + h = (s + P5) % T32 + end + h = (h + n) % T32 + while p + 4 <= e do + h = mul(rotl((h + mul(readu32(b, p), P3)) % T32, 17), P4) + p += 4 + end + while p < e do + h = mul(rotl((h + readu8(b, p) * P5) % T32, 11), P1) + p += 1 + end + h = mul(bxor(h, rshift(h, 15)), P2) + h = mul(bxor(h, rshift(h, 13)), P3) + return bxor(h, rshift(h, 16)) +end + +return Xxh32 +end +end + + + + + + codecs_entropy + --!optimize 2 +--!nocheck +-- rosetta chunk codecs_entropy (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 4 modules (3 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["codecs/entropy/Huffman"] = @native function() + + +-- codecs/entropy/Huffman: canonical Huffman codes (RFC 1951 3.2.2 / JPEG Annex C order). +-- Decoding table entry (u32, indexed by the next P bits; LSB tables by bit-reversed codes, MSB tables by the code): +-- symbol * 32 + length a code of length <= P bits +-- offset * 32 a link: index offset + the following S bits (subtable of 2^S entries) +-- 0 no code (incomplete code set) +local Bits = __include("core/Bits") + +local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift +local readu8, readu32, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu32 +local bfill = buffer.fill + +local MAXLEN = 16 + +local Huffman = {} +Huffman.MAXLEN = MAXLEN + +local REV = table.create(256, 0) +for i = 0, 255 do + local r, v = 0, i + for _ = 1, 8 do + r = r * 2 + v % 2 + v = v // 2 + end + REV[i + 1] = r +end + +@native local function reverse(code: number, len: number): number + return rshift(bor(lshift(REV[band(code, 255) + 1], 8), REV[band(rshift(code, 8), 255) + 1]), 16 - len) +end +Huffman.reverse = reverse + +@native function Huffman.capacity(nsym: number, P: number, maxLen: number): number + return 2 ^ P + (if maxLen > P then nsym * 2 ^ (maxLen - P) else 0) +end + +local count = table.create(MAXLEN + 1, 0) +local nextc = table.create(MAXLEN + 1, 0) + +@native local function build(lens: buffer, off: number, n: number, tab: buffer, P: number, msb: boolean): number + for i = 1, MAXLEN + 1 do + count[i] = 0 + end + for s = 0, n - 1 do + local l = readu8(lens, off + s) + if l > MAXLEN then + return -1 + end + count[l + 1] += 1 + end + count[1] = 0 + local left = 1 + local maxLen = 0 + for l = 1, MAXLEN do + left = left * 2 - count[l + 1] + if left < 0 then + return -1 + end + if count[l + 1] > 0 then + maxLen = l + end + end + local code = 0 + for l = 1, MAXLEN do + code = (code + count[l]) * 2 + nextc[l] = code + end + local psize = lshift(1, P) + bfill(tab, 0, 0, psize * 4) + local S = if maxLen > P then maxLen - P else 0 + local ssize = lshift(1, S) + local nextSub = psize + for s = 0, n - 1 do + local l = readu8(lens, off + s) + if l > 0 then + local c = nextc[l] + nextc[l] = c + 1 + local entry = s * 32 + l + if l <= P then + if msb then + local first = lshift(c, P - l) + local last = first + lshift(1, P - l) - 1 + for i = first, last do + writeu32(tab, i * 4, entry) + end + else + local step = lshift(1, l) + local i = reverse(c, l) + while i < psize do + writeu32(tab, i * 4, entry) + i += step + end + end + else + local pre, rest + if msb then + pre = rshift(c, l - P) + rest = band(c, lshift(1, l - P) - 1) + else + local rev = reverse(c, l) + pre = band(rev, psize - 1) + rest = rshift(rev, P) + end + local e = readu32(tab, pre * 4) + local sub + if e == 0 then + sub = nextSub + nextSub += ssize + bfill(tab, sub * 4, 0, ssize * 4) + writeu32(tab, pre * 4, sub * 32) + else + sub = rshift(e, 5) + end + local k = l - P + if msb then + local first = lshift(rest, S - k) + for i = first, first + lshift(1, S - k) - 1 do + writeu32(tab, (sub + i) * 4, entry) + end + else + local step = lshift(1, k) + local i = rest + while i < ssize do + writeu32(tab, (sub + i) * 4, entry) + i += step + end + end + end + end + end + return S +end + +@native function Huffman.buildLsb(lens: buffer, off: number, n: number, tab: buffer, P: number): number + return build(lens, off, n, tab, P, false) +end + +@native function Huffman.buildMsb(lens: buffer, off: number, n: number, tab: buffer, P: number): number + return build(lens, off, n, tab, P, true) +end + +@native function Huffman.decodeLsb(br: Bits.BitReader, tab: buffer, P: number, S: number): number + local e = readu32(tab, br:peek(P) * 4) + local l = band(e, 31) + if l == 0 then + if e == 0 then + return -1 + end + local idx = br:peek(P + S) + e = readu32(tab, (rshift(e, 5) + rshift(idx, P)) * 4) + l = band(e, 31) + if l == 0 then + return -1 + end + end + br:skip(l) + return rshift(e, 5) +end + +@native function Huffman.decodeMsb(br: Bits.BitReader, tab: buffer, P: number, S: number): number + local e = readu32(tab, br:peek(P) * 4) + local l = band(e, 31) + if l == 0 then + if e == 0 then + return -1 + end + local idx = br:peek(P + S) + e = readu32(tab, (rshift(e, 5) + band(idx, lshift(1, S) - 1)) * 4) + l = band(e, 31) + if l == 0 then + return -1 + end + end + br:skip(l) + return rshift(e, 5) +end + +@native function Huffman.codes(lengths: { number }): { number } + local cnt = table.create(MAXLEN + 1, 0) + for _, l in lengths do + if l > 0 then + cnt[l + 1] += 1 + end + end + local nxt = table.create(MAXLEN + 1, 0) + local code = 0 + for l = 1, MAXLEN do + code = (code + cnt[l]) * 2 + nxt[l + 1] = code + end + local out = table.create(#lengths, 0) + for i, l in lengths do + if l > 0 then + out[i] = nxt[l + 1] + nxt[l + 1] += 1 + end + end + return out +end + +@native function Huffman.lengths(freqs: { number }, maxLen: number): { number } + local n = #freqs + local out = table.create(n, 0) + local syms = {} + for i = 1, n do + if freqs[i] > 0 then + table.insert(syms, i) + end + end + if #syms == 0 then + return out + end + if #syms == 1 then + out[syms[1]] = 1 + return out + end + table.sort(syms, @native function(a: number, b: number): boolean + if freqs[a] ~= freqs[b] then + return freqs[a] < freqs[b] + end + return a < b + end) + local m = #syms + local weight = table.create(2 * m, 0) + local parent = table.create(2 * m, 0) + for i = 1, m do + weight[i] = freqs[syms[i]] + end + local li, ni, nn = 1, m + 1, m + 1 + @native local function take(): number + if li <= m and (ni >= nn or weight[li] <= weight[ni]) then + li += 1 + return li - 1 + end + ni += 1 + return ni - 1 + end + for _ = 1, m - 1 do + local a = take() + local b = take() + weight[nn] = weight[a] + weight[b] + parent[a] = nn + parent[b] = nn + nn += 1 + end + local depth = table.create(2 * m, 0) + for i = nn - 2, 1, -1 do + depth[i] = depth[parent[i]] + 1 + end + -- length limiting: JPEG Annex K.3 (move pairs from the deepest level up) + local bl = table.create(m + maxLen + 2, 0) + local deepest = 0 + for i = 1, m do + bl[depth[i]] += 1 + deepest = math.max(deepest, depth[i]) + end + for l = deepest, maxLen + 1, -1 do + while bl[l] > 0 do + local j = l - 2 + while j > 0 and bl[j] == 0 do + j -= 1 + end + bl[l] -= 2 + bl[l - 1] += 1 + bl[j + 1] += 2 + bl[j] -= 1 + end + end + local k = 1 + for l = math.min(deepest, maxLen), 1, -1 do + for _ = 1, bl[l] do + out[syms[k]] = l + k += 1 + end + end + return out +end + +return Huffman +end +__FILES["codecs/entropy/RangeCoder"] = function() + +-- codecs/entropy/RangeCoder: the RFC 6716 range coder used by Opus, a port of libopus celt/entdec.c + entenc.c. +-- BSD: licenses/libopus-BSD.txt. +local RangeCoder = { + Decoder = __include("codecs/entropy/RangeCoder/Decoder"), + Encoder = __include("codecs/entropy/RangeCoder/Encoder"), +} + +return RangeCoder +end +__FILES["codecs/entropy/RangeCoder/Decoder"] = @native function() + + + +-- codecs/entropy/RangeCoder/Decoder: the Opus range decoder (RFC 6716 4.1), a port of libopus celt/entdec.c (BSD: +-- licenses/libopus-BSD.txt). Raw bits (ec_dec_bits) are read from the end of the frame backwards. +-- All values stay below 2^32, so floor division on plain numbers is exact. +local RangeDecoder = {} + +type Dec = { + buf: buffer, + base: number, + storage: number, + offs: number, + end_offs: number, + end_window: number, + nend_bits: number, + nbits_total: number, + rng: number, + val: number, + rem: number, + ext: number, + error: number, +} + +local SYM_BITS = 8 +local CODE_BITS = 32 +local CODE_TOP = 2147483648 -- 1 << 31 +local CODE_BOT = 8388608 -- CODE_TOP >> 8 +local CODE_EXTRA = 7 -- (CODE_BITS - 2) % SYM_BITS + 1 +local SYM_MAX = 255 +local UINT_BITS = 8 +local WINDOW_SIZE = 32 + +local countlz = bit32.countlz +local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift +local readu8 = buffer.readu8 + +@native local function ilog(x: number): number + return 32 - countlz(x) +end +RangeDecoder.ilog = ilog + +@native local function normalize(d: Dec) + local rng, val, rem = d.rng, d.val, d.rem + while rng <= CODE_BOT do + d.nbits_total += SYM_BITS + rng = rng * 256 + local sym = rem + local offs = d.offs + if offs < d.storage then + rem = readu8(d.buf, d.base + offs) + d.offs = offs + 1 + else + rem = 0 + end + sym = rshift(bor(lshift(sym, 8), rem), SYM_BITS - CODE_EXTRA) + val = band(val * 256 + band(SYM_MAX, bit32.bnot(sym)), CODE_TOP - 1) + end + d.rng, d.val, d.rem = rng, val, rem +end + +@native function RangeDecoder.new(buf: buffer, base: number, storage: number): Dec + local d: Dec = { + buf = buf, + base = base, + storage = storage, + offs = 0, + end_offs = 0, + end_window = 0, + nend_bits = 0, + nbits_total = CODE_BITS + 1 - ((CODE_BITS - CODE_EXTRA) // SYM_BITS) * SYM_BITS, + rng = 128, -- 1 << CODE_EXTRA + val = 0, + rem = 0, + ext = 0, + error = 0, + } + local rem = 0 + if storage > 0 then + rem = readu8(buf, base) + d.offs = 1 + end + d.rem = rem + d.val = d.rng - 1 - rshift(rem, SYM_BITS - CODE_EXTRA) + normalize(d) + return d +end + +@native function RangeDecoder.decode(d: Dec, ft: number): number + local ext = d.rng // ft + d.ext = ext + local s = d.val // ext + return ft - math.min(s + 1, ft) +end + +@native function RangeDecoder.decodeBin(d: Dec, bits: number): number + local ext = rshift(d.rng, bits) + d.ext = ext + local s = d.val // ext + local ft = lshift(1, bits) + return ft - math.min(s + 1, ft) +end + +@native function RangeDecoder.update(d: Dec, fl: number, fh: number, ft: number) + local s = d.ext * (ft - fh) + d.val = band(d.val - s, 0xFFFFFFFF) -- uint32 wrap (corrupt streams only) + if fl > 0 then + d.rng = d.ext * (fh - fl) + else + d.rng -= s + end + normalize(d) +end + +@native function RangeDecoder.bitLogp(d: Dec, logp: number): boolean + local r = d.rng + local v = d.val + local s = rshift(r, logp) + local ret = v < s + if ret then + d.rng = s + else + d.val = v - s + d.rng = r - s + end + normalize(d) + return ret +end + +@native function RangeDecoder.icdf(d: Dec, icdf: { number }, off: number, ftb: number): number + local s = d.rng + local v = d.val + local r = rshift(s, ftb) + local ret = -1 + local t + repeat + t = s + ret += 1 + s = r * icdf[off + ret] + until v >= s + d.val = v - s + d.rng = t - s + normalize(d) + return ret +end + +@native function RangeDecoder.bits(d: Dec, bits: number): number + local window = d.end_window + local available = d.nend_bits + if available < bits then + repeat + local b = 0 + local eo = d.end_offs + if eo < d.storage then + eo += 1 + d.end_offs = eo + b = readu8(d.buf, d.base + d.storage - eo) + end + window = bor(window, lshift(b, available)) + available += SYM_BITS + until available > WINDOW_SIZE - SYM_BITS + end + local ret = band(window, lshift(1, bits) - 1) + if bits == 32 then + ret = window + end + window = rshift(window, bits) + available -= bits + d.end_window = window + d.nend_bits = available + d.nbits_total += bits + return ret +end + +@native function RangeDecoder.uint(d: Dec, ft0: number): number + local ft = ft0 - 1 + local ftb = ilog(ft) + if ftb > UINT_BITS then + ftb -= UINT_BITS + local ft1 = rshift(ft, ftb) + 1 + local s = RangeDecoder.decode(d, ft1) + RangeDecoder.update(d, s, s + 1, ft1) + local t = bor(lshift(s, ftb), RangeDecoder.bits(d, ftb)) + if t <= ft then + return t + end + d.error = 1 + return ft + else + local s = RangeDecoder.decode(d, ft0) + RangeDecoder.update(d, s, s + 1, ft0) + return s + end +end + +@native function RangeDecoder.tell(d: Dec): number + return d.nbits_total - ilog(d.rng) +end + +local correction = { 35733, 38967, 42495, 46340, 50535, 55109, 60097, 65535 } +@native function RangeDecoder.tellFrac(d: Dec): number + local nbits = d.nbits_total * 8 + local l = ilog(d.rng) + local r = rshift(d.rng, l - 16) + local b = rshift(r, 12) - 8 + if r > correction[b + 1] then + b += 1 + end + return nbits - (l * 8 + b) +end + +return RangeDecoder +end +__FILES["codecs/entropy/RangeCoder/Encoder"] = @native function() + + + +-- codecs/entropy/RangeCoder/Encoder: the Opus range encoder (RFC 6716 5.1), a port of libopus celt/entenc.c (BSD: +-- licenses/libopus-BSD.txt). Range-coded symbols from the front of the frame, raw bits (ec_enc_bits) from the back. +local RangeEncoder = {} + +type Enc = { + buf: buffer, + storage: number, + offs: number, + end_offs: number, + end_window: number, + nend_bits: number, + nbits_total: number, + rng: number, + val: number, + rem: number, + ext: number, + error: number, +} + +local CODE_TOP = 2147483648 -- 1 << 31 +local CODE_BOT = 8388608 -- CODE_TOP >> 8 +local CODE_SHIFT = 23 +local SYM_MAX = 255 + +local countlz = bit32.countlz +local band = bit32.band +local readu8, writeu8 = buffer.readu8, buffer.writeu8 +local floor = math.floor + +@native local function ilog(x: number): number + return 32 - countlz(x) +end +RangeEncoder.ilog = ilog + +@native function RangeEncoder.new(storage: number): Enc + return { + buf = buffer.create(math.max(storage, 1)), + storage = storage, + offs = 0, + end_offs = 0, + end_window = 0, + nend_bits = 0, + nbits_total = 33, -- EC_CODE_BITS + 1 + rng = CODE_TOP, + val = 0, + rem = -1, + ext = 0, + error = 0, + } +end + +@native local function writeByte(e: Enc, v: number) + if e.offs + e.end_offs >= e.storage then + e.error = -1 + return + end + writeu8(e.buf, e.offs, band(v, 255)) + e.offs += 1 +end + +@native local function writeByteAtEnd(e: Enc, v: number) + if e.offs + e.end_offs >= e.storage then + e.error = -1 + return + end + e.end_offs += 1 + writeu8(e.buf, e.storage - e.end_offs, band(v, 255)) +end + +@native local function carryOut(e: Enc, c: number) + if c ~= SYM_MAX then + local carry = if c >= 256 then 1 else 0 + if e.rem >= 0 then + writeByte(e, e.rem + carry) + end + if e.ext > 0 then + local sym = band(SYM_MAX + carry, 255) + repeat + writeByte(e, sym) + e.ext -= 1 + until e.ext <= 0 + end + e.rem = band(c, 255) + else + e.ext += 1 + end +end + +@native local function normalize(e: Enc) + while e.rng <= CODE_BOT do + carryOut(e, floor(e.val / 8388608)) + e.val = (e.val * 256) % CODE_TOP + e.rng *= 256 + e.nbits_total += 8 + end +end + +@native function RangeEncoder.encode(e: Enc, fl: number, fh: number, ft: number) + local r = floor(e.rng / ft) + if fl > 0 then + e.val += e.rng - r * (ft - fl) + e.rng = r * (fh - fl) + else + e.rng -= r * (ft - fh) + end + normalize(e) +end + +@native function RangeEncoder.encodeBin(e: Enc, fl: number, fh: number, bits: number) + local ft = 2 ^ bits + local r = floor(e.rng / ft) + if fl > 0 then + e.val += e.rng - r * (ft - fl) + e.rng = r * (fh - fl) + else + e.rng -= r * (ft - fh) + end + normalize(e) +end + +@native function RangeEncoder.bitLogp(e: Enc, v: boolean, logp: number) + local r = e.rng + local s = floor(r / 2 ^ logp) + r -= s + if v then + e.val += r + e.rng = s + else + e.rng = r + end + normalize(e) +end + +@native function RangeEncoder.icdf(e: Enc, s: number, icdf: { number }, ftb: number) + local r = floor(e.rng / 2 ^ ftb) + if s > 0 then + e.val += e.rng - r * icdf[s] + e.rng = r * (icdf[s] - icdf[s + 1]) + else + e.rng -= r * icdf[s + 1] + end + normalize(e) +end + +@native function RangeEncoder.bits(e: Enc, fl: number, n: number) + local window = e.end_window + local used = e.nend_bits + if used + n > 32 then + repeat + writeByteAtEnd(e, window % 256) + window = floor(window / 256) + used -= 8 + until used < 8 + end + window += fl * 2 ^ used + used += n + e.end_window = window + e.nend_bits = used + e.nbits_total += n +end + +@native function RangeEncoder.uint(e: Enc, fl: number, ft: number) + ft -= 1 + local ftb = ilog(ft) + if ftb > 8 then + ftb -= 8 + local sh = 2 ^ ftb + local ft1 = floor(ft / sh) + 1 + local hi = floor(fl / sh) + RangeEncoder.encode(e, hi, hi + 1, ft1) + RangeEncoder.bits(e, fl - hi * sh, ftb) + else + RangeEncoder.encode(e, fl, fl + 1, ft + 1) + end +end + +@native function RangeEncoder.tell(e: Enc): number + return e.nbits_total - ilog(e.rng) +end + +local CORRECTION = { 35733, 38967, 42495, 46340, 50535, 55109, 60097, 65535 } +@native function RangeEncoder.tellFrac(e: Enc): number + local nbits = e.nbits_total * 8 + local l = ilog(e.rng) + local r = floor(e.rng / 2 ^ (l - 16)) + local b = floor(r / 4096) - 8 + if r > CORRECTION[b + 1] then + b += 1 + end + return nbits - (l * 8 + b) +end + +@native function RangeEncoder.done(e: Enc) + local l = 32 - ilog(e.rng) + local msk = floor((CODE_TOP - 1) / 2 ^ l) + local stop = floor((e.val + msk) / (msk + 1)) * (msk + 1) + if stop + msk >= e.val + e.rng then + l += 1 + msk = floor(msk / 2) + stop = floor((e.val + msk) / (msk + 1)) * (msk + 1) + end + while l > 0 do + carryOut(e, floor(stop / 8388608)) + stop = (stop * 256) % CODE_TOP + l -= 8 + end + if e.rem >= 0 or e.ext > 0 then + carryOut(e, 0) + end + local window = e.end_window + local used = e.nend_bits + while used >= 8 do + writeByteAtEnd(e, window % 256) + window = floor(window / 256) + used -= 8 + end + if e.error == 0 then + local a, b = e.offs, e.storage - e.end_offs + if b > a then + buffer.fill(e.buf, a, 0, b - a) + end + if used > 0 then + if e.end_offs >= e.storage then + e.error = -1 + else + l = -l + if e.offs + e.end_offs >= e.storage and l < used then + window = window % 2 ^ l + e.error = -1 + end + local p = e.storage - e.end_offs - 1 + writeu8(e.buf, p, bit32.bor(readu8(e.buf, p), window)) + end + end + end +end + +local _ = CODE_SHIFT +return RangeEncoder +end +end + + + + + + codecs_font + --!optimize 2 +--!nocheck +-- rosetta chunk codecs_font (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 6 modules (0 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["codecs/font/Bitmap"] = function() + +-- codecs/font/Bitmap: the standard Font value for bitmap fonts (BDF, PCF, PSF, Windows FON / FNT) and their 1-bit rows. +-- Bit rows are MSB = left pixel unless lsbFirst; a pixel >= 128 is on. +local Err = __include("core/Err") +local Types = __include("Types") + +local Bitmap = {} + +local readu8, writeu8 = buffer.readu8, buffer.writeu8 + +function Bitmap.unpack(b: buffer, off: number, w: number, h: number, stride: number, lsbFirst: boolean?): buffer + local out = buffer.create(math.max(0, w * h)) + local n = buffer.len(b) + for y = 0, h - 1 do + local row = off + y * stride + for x = 0, w - 1 do + local p = row + bit32.rshift(x, 3) + if p >= 0 and p < n then + local byte = readu8(b, p) + local bitn = if lsbFirst then bit32.band(x, 7) else 7 - bit32.band(x, 7) + if bit32.band(bit32.rshift(byte, bitn), 1) ~= 0 then + writeu8(out, y * w + x, 255) + end + end + end + end + return out +end + +function Bitmap.pack(px: buffer, w: number, h: number, stride: number?, lsbFirst: boolean?): buffer + local s = stride or math.ceil(w / 8) + local out = buffer.create(math.max(0, s * h)) + local n = buffer.len(px) + for y = 0, h - 1 do + for x = 0, w - 1 do + local i = y * w + x + if i < n and readu8(px, i) >= 128 then + local p = y * s + bit32.rshift(x, 3) + local bitn = if lsbFirst then bit32.band(x, 7) else 7 - bit32.band(x, 7) + writeu8(out, p, bit32.bor(readu8(out, p), bit32.lshift(1, bitn))) + end + end + end + return out +end + +local Face = {} +Face.__index = Face + +function Face.glyphIndex(self: any, cp: number): number + return self._index[cp] or 0 +end + +function Face.advance(self: any, g: number): number + local gl = self.bitmap.glyphs[g + 1] + return if gl then gl.advance else 0 +end + +function Face.kern(_self: any, _a: number, _b: number): number + return 0 +end + +function Face.outline(_self: any, _g: number): { any }? + return nil +end + +function Face.rasterize(self: any, g: number, px: number?): Types.Image? + local gl: Types.BitmapGlyph? = self.bitmap.glyphs[g + 1] + if not gl or gl.width < 0 or gl.height < 0 then + return nil + end + local img = Types.Image.new(gl.width, gl.height, "alpha8") + local n = math.min(buffer.len(img.pixels), buffer.len(gl.pixels)) + if n > 0 then + buffer.copy(img.pixels, 0, gl.pixels, 0, n) + end + img.meta.left = gl.left + img.meta.top = gl.top + img.meta.advance = gl.advance + img.meta.glyph = g + img.meta.scale = if type(px) == "number" and self.bitmap.size > 0 then px / self.bitmap.size else 1 + return img +end + +function Bitmap.font(strike: Types.BitmapStrike, info: { [string]: any }?, meta: { [string]: any }?): any + local index: { [number]: number } = {} + for i, gl in strike.glyphs do + local cp = gl.codepoint + if cp and index[cp] == nil then + index[cp] = i - 1 + end + end + if strike.map then + for cp, g in strike.map do + if index[cp] == nil and g >= 0 and g < #strike.glyphs then + index[cp] = g + end + end + end + local f = setmetatable({ + kind = "font", + info = info or {}, + unitsPerEm = strike.size, + ascent = strike.ascent, + descent = -strike.descent, + lineGap = 0, + numGlyphs = #strike.glyphs, + bitmap = strike, + meta = meta or {}, + _index = index, + }, Face) + if strike.default then + setmetatable(index, { __index = function() + return strike.default + end }) + end + return f +end + +type StrikeOptions = { + px: number?, + chars: (string | { number })?, + threshold: number?, +} + +local function codepoints(chars: (string | { number })?): { number } + if type(chars) == "table" then + return chars + end + local out = {} + if type(chars) == "string" then + for _, c in utf8.codes(chars) do + table.insert(out, c) + end + return out + end + for c = 32, 126 do + table.insert(out, c) + end + return out +end + +function Bitmap.strike(font: any, opts: StrikeOptions?): (Types.BitmapStrike?, Err.Err?) + if type(font) ~= "table" or font.kind ~= "font" then + return nil, Err.new(Err.ARG, "expected a Font") + end + if type(font.bitmap) == "table" and type(font.bitmap.glyphs) == "table" then + return font.bitmap, nil + end + if type(font.rasterize) ~= "function" or type(font.glyphIndex) ~= "function" then + return nil, Err.new(Err.ARG, "font has no glyphs to rasterize") + end + local o: StrikeOptions = opts or {} + local px = o.px or 16 + if type(px) ~= "number" or px < 1 or px > 1024 then + return nil, Err.new(Err.ARG, "px must be 1..1024") + end + local threshold = o.threshold or 128 + local upm = if type(font.unitsPerEm) == "number" and font.unitsPerEm > 0 then font.unitsPerEm else px + local scale = px / upm + local ascent = math.ceil((font.ascent or upm) * scale) + local descent = math.ceil(math.abs(font.descent or 0) * scale) + local glyphs: { Types.BitmapGlyph } = {} + local function add(cp: number?, g: number) + local ok, img = pcall(font.rasterize, font, g, px) + local adv = 0 + local aok, a = pcall(font.advance, font, g) + if aok and type(a) == "number" then + adv = math.floor(a * scale + 0.5) + end + local gl: Types.BitmapGlyph = { codepoint = cp, width = 0, height = 0, left = 0, top = 0, advance = adv, pixels = buffer.create(0) } + if ok and type(img) == "table" and type(img.pixels) == "buffer" and img.format == "alpha8" then + local n = img.width * img.height + local pxs = buffer.create(n) + for i = 0, math.min(n, buffer.len(img.pixels)) - 1 do + if readu8(img.pixels, i) >= threshold then + writeu8(pxs, i, 255) + end + end + gl.width, gl.height, gl.pixels = img.width, img.height, pxs + gl.left = math.floor(img.meta.left or 0) + gl.top = math.floor(img.meta.top or 0) + if type(img.meta.advance) == "number" then + gl.advance = math.floor(img.meta.advance + 0.5) + end + end + table.insert(glyphs, gl) + end + add(nil, 0) + for _, cp in codepoints(o.chars) do + local ok, g = pcall(font.glyphIndex, font, cp) + if ok and type(g) == "number" and g > 0 then + add(cp, g) + end + end + return { size = px, ascent = ascent, descent = descent, glyphs = glyphs, default = 0 }, nil +end + +return Bitmap +end +__FILES["codecs/font/Cff"] = function() + +-- codecs/font/Cff: Compact Font Format (Adobe TN #5176) and Type 2 charstrings (TN #5177), the outlines of .otf fonts. +-- Charstrings ported from stb_truetype 1.26 (public domain / MIT) via imgui-luau's imstb_truetype.lua, plus +-- flex1's last delta, an operation budget, and the TN #5177 4.4 arithmetic / storage operators. +local Cff = {} + +local readu8 = buffer.readu8 +local blen = buffer.len + +local function u8(b: buffer, o: number): number + if o < 0 or o + 1 > blen(b) then + return 0 + end + return readu8(b, o) +end +local function uN(b: buffer, o: number, n: number): number + local v = 0 + for i = 0, n - 1 do + v = v * 256 + u8(b, o + i) + end + return v +end + +type Index = { count: number, offSize: number, offsets: number, data: number, next: number } +type Font = { + buf: buffer, + base: number, + limit: number, + charStrings: Index, + gsubrs: Index, + subrs: Index?, + fdSubrs: { Index? }?, + fdSelect: number?, + numGlyphs: number, + cid: boolean, + fontMatrix: { number }?, +} + +local function index(b: buffer, p: number, limit: number): Index? + if p + 2 > limit then + return nil + end + local count = uN(b, p, 2) + if count == 0 then + return { count = 0, offSize = 1, offsets = p + 2, data = p + 2, next = p + 2 } + end + local offSize = u8(b, p + 2) + if offSize < 1 or offSize > 4 then + return nil + end + local offsets = p + 3 + local data = offsets + (count + 1) * offSize - 1 -- offsets are 1-based + if data + 1 > limit then + return nil + end + local last = uN(b, offsets + count * offSize, offSize) + if data + last > limit then + return nil + end + return { count = count, offSize = offSize, offsets = offsets, data = data, next = data + last } +end + +local function item(b: buffer, idx: Index, i: number): (number?, number) + if i < 0 or i >= idx.count then + return nil, 0 + end + local s = uN(b, idx.offsets + i * idx.offSize, idx.offSize) + local e = uN(b, idx.offsets + (i + 1) * idx.offSize, idx.offSize) + if s < 1 or e < s or idx.data + e > idx.next then + return nil, 0 + end + return idx.data + s, e - s +end +Cff.item = item + +-- DICT operators: two-byte ops (12 x) are keyed 1200 + x +local function dict(b: buffer, p: number, n: number): { [number]: { number } } + local out: { [number]: { number } } = {} + local ops: { number } = {} + local e = p + n + while p < e do + local b0 = u8(b, p) + if b0 <= 21 then + local op = b0 + p += 1 + if b0 == 12 then + op = 1200 + u8(b, p) + p += 1 + end + out[op] = ops + ops = {} + elseif b0 == 28 then + local v = uN(b, p + 1, 2) + table.insert(ops, if v >= 32768 then v - 65536 else v) + p += 3 + elseif b0 == 29 then + local v = uN(b, p + 1, 4) + table.insert(ops, if v >= 2147483648 then v - 4294967296 else v) + p += 5 + elseif b0 == 30 then -- real number: BCD nibbles + local s = {} + p += 1 + local done = false + while p < e and not done do + local byte = u8(b, p) + p += 1 + for _, nib in { byte // 16, byte % 16 } do + if nib <= 9 then + table.insert(s, tostring(nib)) + elseif nib == 10 then + table.insert(s, ".") + elseif nib == 11 then + table.insert(s, "E") + elseif nib == 12 then + table.insert(s, "E-") + elseif nib == 14 then + table.insert(s, "-") + elseif nib == 15 then + done = true + break + end + end + end + table.insert(ops, tonumber(table.concat(s)) or 0) + elseif b0 >= 32 and b0 <= 246 then + table.insert(ops, b0 - 139) + p += 1 + elseif b0 >= 247 and b0 <= 250 then + table.insert(ops, (b0 - 247) * 256 + u8(b, p + 1) + 108) + p += 2 + elseif b0 >= 251 and b0 <= 254 then + table.insert(ops, -(b0 - 251) * 256 - u8(b, p + 1) - 108) + p += 2 + else + p += 1 -- reserved + end + if #ops > 48 then + return out + end + end + return out +end + +local function privateSubrs(b: buffer, base: number, limit: number, d: { [number]: { number } }): Index? + local pr = d[18] + if not pr or #pr < 2 then + return nil + end + local size, off = pr[1], pr[2] + local ps = base + off + if size < 0 or off < 0 or ps + size > limit then + return nil + end + local pd = dict(b, ps, size) + local s = pd[19] + if not s or #s < 1 then + return nil + end + return index(b, ps + s[1], limit) +end + +function Cff.parse(b: buffer, offset: number, length: number): (Font?, string?) + local base, limit = offset, math.min(offset + length, blen(b)) + if limit - base < 4 then + return nil, "truncated CFF header" + end + local major, hdrSize = u8(b, base), u8(b, base + 2) + if major == 2 then + return nil, "unsupported: CFF2 (variable font outlines)" + end + if major ~= 1 then + return nil, "bad CFF version " .. major + end + local names = index(b, base + hdrSize, limit) + if not names then + return nil, "bad name INDEX" + end + local tops = index(b, names.next, limit) + if not tops or tops.count < 1 then + return nil, "bad Top DICT INDEX" + end + local strings = index(b, tops.next, limit) + if not strings then + return nil, "bad String INDEX" + end + local gsubrs = index(b, strings.next, limit) + if not gsubrs then + return nil, "bad global subrs INDEX" + end + local ts, tl = item(b, tops, 0) + if not ts then + return nil, "bad Top DICT" + end + local top = dict(b, ts, tl) + local cso = top[17] + if not cso or #cso < 1 then + return nil, "no CharStrings" + end + local cst = top[1206] + if cst and cst[1] ~= 2 then + return nil, "unsupported: charstring type " .. tostring(cst[1]) + end + local charStrings = index(b, base + cso[1], limit) + if not charStrings then + return nil, "bad CharStrings INDEX" + end + local f: Font = { + buf = b, + base = base, + limit = limit, + charStrings = charStrings, + gsubrs = gsubrs, + subrs = nil, + fdSubrs = nil, + fdSelect = nil, + numGlyphs = charStrings.count, + cid = top[1230] ~= nil, + fontMatrix = top[1207], + } + if f.cid then + local fda, fds = top[1236], top[1237] + if not fda or not fds then + return nil, "CID font without FDArray / FDSelect" + end + local fdArray = index(b, base + fda[1], limit) + if not fdArray then + return nil, "bad FDArray" + end + local list: { Index? } = {} + for i = 0, math.min(fdArray.count, 256) - 1 do + local s, l = item(b, fdArray, i) + list[i + 1] = if s then privateSubrs(b, base, limit, dict(b, s, l)) else nil + end + f.fdSubrs = list + f.fdSelect = base + fds[1] + else + f.subrs = privateSubrs(b, base, limit, top) + end + return f, nil +end + +local function bias(count: number): number + return if count < 1240 then 107 elseif count < 33900 then 1131 else 32768 +end + +local function localSubrs(f: Font, g: number): Index? + if not f.cid then + return f.subrs + end + local b, p = f.buf, f.fdSelect :: number + local fmt = u8(b, p) + local fd = -1 + if fmt == 0 then + fd = u8(b, p + 1 + g) + elseif fmt == 3 then + local n = uN(b, p + 1, 2) + local first = uN(b, p + 3, 2) + for i = 0, n - 1 do + local q = p + 5 + i * 3 + local v = u8(b, q) + local nxt = uN(b, q + 1, 2) + if g >= first and g < nxt then + fd = v + break + end + first = nxt + end + end + local list = f.fdSubrs :: { Index? } + return list[fd + 1] +end + +local BUDGET = 200000 -- operators per glyph (subroutine bombs) + +function Cff.outline(f: Font, g: number): ({ any }?, string?) + local b = f.buf + local p, len = item(b, f.charStrings, g) + if not p then + return nil, "bad glyph index " .. tostring(g) + end + local e = p + len + local cmds: { any } = {} + local s: { number } = table.create(48, 0) + local sp = 0 + local trans = table.create(32, 0) :: { number } + local x, y = 0, 0 + local open = false + local maskbits = 0 + local inHeader = true + local stack: { { number } } = {} + local subrs: Index? = nil + local haveSubrs = false + local ops = 0 + local seed = 12345 + + local function moveTo(dx: number, dy: number) + if open then + table.insert(cmds, { op = "close" }) + end + x += dx + y += dy + table.insert(cmds, { op = "moveTo", x, y }) + open = true + end + local function lineTo(dx: number, dy: number) + if not open then + moveTo(0, 0) + end + x += dx + y += dy + table.insert(cmds, { op = "lineTo", x, y }) + end + local function curveTo(dx1: number, dy1: number, dx2: number, dy2: number, dx3: number, dy3: number) + if not open then + moveTo(0, 0) + end + local x1, y1 = x + dx1, y + dy1 + local x2, y2 = x1 + dx2, y1 + dy2 + x, y = x2 + dx3, y2 + dy3 + table.insert(cmds, { op = "cubicTo", x1, y1, x2, y2, x, y }) + end + local function S(i: number): number + return s[i + 1] or 0 + end + + while true do + if p >= e then + if #stack > 0 then + local r = table.remove(stack) :: { number } + p, e = r[1], r[2] + continue + end + break + end + ops += 1 + if ops > BUDGET then + return nil, "charstring too long (subroutine loop?)" + end + local b0 = u8(b, p) + p += 1 + local clear = true + local i = 0 + if b0 == 19 or b0 == 20 then -- hintmask, cntrmask + if inHeader then + maskbits += sp // 2 + end + inHeader = false + p += (maskbits + 7) // 8 + elseif b0 == 1 or b0 == 3 or b0 == 18 or b0 == 23 then -- hstem vstem hstemhm vstemhm + maskbits += sp // 2 + elseif b0 == 21 then -- rmoveto + inHeader = false + if sp < 2 then + return nil, "rmoveto stack" + end + moveTo(S(sp - 2), S(sp - 1)) + elseif b0 == 4 then -- vmoveto + inHeader = false + if sp < 1 then + return nil, "vmoveto stack" + end + moveTo(0, S(sp - 1)) + elseif b0 == 22 then -- hmoveto + inHeader = false + if sp < 1 then + return nil, "hmoveto stack" + end + moveTo(S(sp - 1), 0) + elseif b0 == 5 then -- rlineto + if sp < 2 then + return nil, "rlineto stack" + end + while i + 1 < sp do + lineTo(S(i), S(i + 1)) + i += 2 + end + elseif b0 == 6 or b0 == 7 then -- hlineto / vlineto: alternate + if sp < 1 then + return nil, "hlineto stack" + end + local horiz = b0 == 6 + while i < sp do + if horiz then + lineTo(S(i), 0) + else + lineTo(0, S(i)) + end + horiz = not horiz + i += 1 + end + elseif b0 == 31 or b0 == 30 then -- hvcurveto / vhcurveto: alternate + if sp < 4 then + return nil, "hvcurveto stack" + end + local horiz = b0 == 31 + while i + 3 < sp do + local last = if sp - i == 5 then S(i + 4) else 0 + if horiz then + curveTo(S(i), 0, S(i + 1), S(i + 2), last, S(i + 3)) + else + curveTo(0, S(i), S(i + 1), S(i + 2), S(i + 3), last) + end + horiz = not horiz + i += 4 + end + elseif b0 == 8 then -- rrcurveto + if sp < 6 then + return nil, "rrcurveto stack" + end + while i + 5 < sp do + curveTo(S(i), S(i + 1), S(i + 2), S(i + 3), S(i + 4), S(i + 5)) + i += 6 + end + elseif b0 == 24 then -- rcurveline + if sp < 8 then + return nil, "rcurveline stack" + end + while i + 5 < sp - 2 do + curveTo(S(i), S(i + 1), S(i + 2), S(i + 3), S(i + 4), S(i + 5)) + i += 6 + end + lineTo(S(i), S(i + 1)) + elseif b0 == 25 then -- rlinecurve + if sp < 8 then + return nil, "rlinecurve stack" + end + while i + 1 < sp - 6 do + lineTo(S(i), S(i + 1)) + i += 2 + end + curveTo(S(i), S(i + 1), S(i + 2), S(i + 3), S(i + 4), S(i + 5)) + elseif b0 == 26 or b0 == 27 then -- vvcurveto / hhcurveto + if sp < 4 then + return nil, "vv/hhcurveto stack" + end + local f0 = 0 + if sp % 2 == 1 then + f0 = S(0) + i = 1 + end + while i + 3 < sp do + if b0 == 27 then + curveTo(S(i), f0, S(i + 1), S(i + 2), S(i + 3), 0) + else + curveTo(f0, S(i), S(i + 1), S(i + 2), 0, S(i + 3)) + end + f0 = 0 + i += 4 + end + elseif b0 == 10 or b0 == 29 then -- callsubr / callgsubr + if b0 == 10 and not haveSubrs then + subrs = localSubrs(f, g) + haveSubrs = true + end + if sp < 1 then + return nil, "callsubr stack" + end + local idx = if b0 == 10 then subrs else f.gsubrs + if not idx then + return nil, "no subroutines" + end + local n = math.floor(S(sp - 1)) + bias(idx.count) + sp -= 1 + if #stack >= 10 then + return nil, "subroutine recursion limit" + end + local sp0, sl = item(b, idx, n) + if not sp0 then + return nil, "subroutine " .. n .. " not found" + end + table.insert(stack, { p, e }) + p, e = sp0, sp0 + sl + clear = false + elseif b0 == 11 then -- return + if #stack == 0 then + return nil, "return outside a subroutine" + end + local r = table.remove(stack) :: { number } + p, e = r[1], r[2] + clear = false + elseif b0 == 14 then -- endchar + if open then + table.insert(cmds, { op = "close" }) + end + return cmds, nil + elseif b0 == 12 then -- escape + local b1 = u8(b, p) + p += 1 + if b1 == 34 then -- hflex + if sp < 7 then + return nil, "hflex stack" + end + curveTo(S(0), 0, S(1), S(2), S(3), 0) + curveTo(S(4), 0, S(5), -S(2), S(6), 0) + elseif b1 == 35 then -- flex + if sp < 13 then + return nil, "flex stack" + end + curveTo(S(0), S(1), S(2), S(3), S(4), S(5)) + curveTo(S(6), S(7), S(8), S(9), S(10), S(11)) + elseif b1 == 36 then -- hflex1 + if sp < 9 then + return nil, "hflex1 stack" + end + curveTo(S(0), S(1), S(2), S(3), S(4), 0) + curveTo(S(5), 0, S(6), S(7), S(8), -(S(1) + S(3) + S(7))) + elseif b1 == 37 then -- flex1 + if sp < 11 then + return nil, "flex1 stack" + end + local dx = S(0) + S(2) + S(4) + S(6) + S(8) + local dy = S(1) + S(3) + S(5) + S(7) + S(9) + local dx6, dy6 = S(10), S(10) + if math.abs(dx) > math.abs(dy) then + dy6 = -dy + else + dx6 = -dx + end + curveTo(S(0), S(1), S(2), S(3), S(4), S(5)) + curveTo(S(6), S(7), S(8), S(9), dx6, dy6) + else + clear = false + local top = sp + local a, c = S(top - 2), S(top - 1) + local function set(n: number, v: number) + sp = math.max(0, sp - n) + sp += 1 + s[sp] = v + end + if b1 == 3 then + set(2, if a ~= 0 and c ~= 0 then 1 else 0) -- and + elseif b1 == 4 then + set(2, if a ~= 0 or c ~= 0 then 1 else 0) -- or + elseif b1 == 5 then + set(1, if c == 0 then 1 else 0) -- not + elseif b1 == 9 then + set(1, math.abs(c)) + elseif b1 == 10 then + set(2, a + c) + elseif b1 == 11 then + set(2, a - c) + elseif b1 == 12 then + set(2, if c ~= 0 then a / c else 0) + elseif b1 == 14 then + set(1, -c) + elseif b1 == 15 then + set(2, if a == c then 1 else 0) + elseif b1 == 18 then + sp = math.max(0, sp - 1) -- drop + elseif b1 == 20 then -- put: val i + local k = math.floor(c) + if k >= 0 and k < 32 then + trans[k + 1] = a + end + sp = math.max(0, sp - 2) + elseif b1 == 21 then -- get + local k = math.floor(c) + set(1, if k >= 0 and k < 32 then trans[k + 1] else 0) + elseif b1 == 22 then -- ifelse: s1 s2 v1 v2 -> v1 <= v2 ? s1 : s2 + local s1, s2, v1, v2 = S(top - 4), S(top - 3), S(top - 2), S(top - 1) + set(4, if v1 <= v2 then s1 else s2) + elseif b1 == 23 then -- random (deterministic) + seed = (seed * 1103515245 + 12345) % 2147483648 + set(0, (seed % 65535 + 1) / 65536) + elseif b1 == 24 then + set(2, a * c) + elseif b1 == 26 then + set(1, math.sqrt(math.max(0, c))) + elseif b1 == 27 then + set(0, c) -- dup + elseif b1 == 28 then -- exch + if sp >= 2 then + s[sp - 1], s[sp] = s[sp], s[sp - 1] + end + elseif b1 == 29 then -- index + local k = math.floor(c) + local v = if k < 0 then S(top - 2) else S(top - 2 - k) + set(1, v) + elseif b1 == 30 then -- roll: n j + local n, j = math.floor(a), math.floor(c) + sp = math.max(0, sp - 2) + if n > 0 and n <= sp then + local base = sp - n + local tmp = table.create(n, 0) + for k = 0, n - 1 do + tmp[((k + j) % n) + 1] = s[base + k + 1] + end + for k = 0, n - 1 do + s[base + k + 1] = tmp[k + 1] + end + end + else + return nil, "unknown operator 12 " .. b1 + end + if sp > 48 then + return nil, "stack overflow" + end + end + elseif b0 >= 32 or b0 == 28 then -- operands + local v + if b0 == 28 then + v = uN(b, p, 2) + if v >= 32768 then + v -= 65536 + end + p += 2 + elseif b0 <= 246 then + v = b0 - 139 + elseif b0 <= 250 then + v = (b0 - 247) * 256 + u8(b, p) + 108 + p += 1 + elseif b0 <= 254 then + v = -(b0 - 251) * 256 - u8(b, p) - 108 + p += 1 + else -- 255: 16.16 fixed + v = uN(b, p, 4) + if v >= 2147483648 then + v -= 4294967296 + end + v /= 65536 + p += 4 + end + if sp >= 48 then + return nil, "operand stack overflow" + end + sp += 1 + s[sp] = v + clear = false + else + return nil, "reserved operator " .. b0 + end + if clear then + sp = 0 + end + end + return nil, "no endchar" +end + +return Cff +end +__FILES["codecs/font/GlyphNames"] = function() + +-- codecs/font/GlyphNames: PostScript glyph names -> Unicode (AGL specification) and Adobe StandardEncoding. +-- Data: the Adobe Glyph List For New Fonts (AGLFN 1.7, BSD-3-Clause: licenses/agl-LICENSE.txt; the f-ligatures and +-- dotlessj added) and StandardEncoding, generated from fontTools.agl / fontTools.encodings.StandardEncoding. +local GlyphNames = {} + +-- AGLFN: "name hex" pairs +local AGL = "" .. + "A 41 AE C6 AEacute 1FC Aacute C1 Abreve 102 Acircumflex C2 Adieresis C4 Agrave C0 Alpha 391 " .. + "Alphatonos 386 Amacron 100 Aogonek 104 Aring C5 Aringacute 1FA Atilde C3 B 42 Beta 392 C 43 Cacute " .. + "106 Ccaron 10C Ccedilla C7 Ccircumflex 108 Cdotaccent 10A Chi 3A7 D 44 Dcaron 10E Dcroat 110 Delta " .. + "2206 E 45 Eacute C9 Ebreve 114 Ecaron 11A Ecircumflex CA Edieresis CB Edotaccent 116 Egrave C8 " .. + "Emacron 112 Eng 14A Eogonek 118 Epsilon 395 Epsilontonos 388 Eta 397 Etatonos 389 Eth D0 Euro 20AC " .. + "F 46 G 47 Gamma 393 Gbreve 11E Gcaron 1E6 Gcircumflex 11C Gdotaccent 120 H 48 H18533 25CF H18543 " .. + "25AA H18551 25AB H22073 25A1 Hbar 126 Hcircumflex 124 I 49 IJ 132 Iacute CD Ibreve 12C Icircumflex " .. + "CE Idieresis CF Idotaccent 130 Ifraktur 2111 Igrave CC Imacron 12A Iogonek 12E Iota 399 " .. + "Iotadieresis 3AA Iotatonos 38A Itilde 128 J 4A Jcircumflex 134 K 4B Kappa 39A L 4C Lacute 139 " .. + "Lambda 39B Lcaron 13D Ldot 13F Lslash 141 M 4D Mu 39C N 4E Nacute 143 Ncaron 147 Ntilde D1 Nu 39D O " .. + "4F OE 152 Oacute D3 Obreve 14E Ocircumflex D4 Odieresis D6 Ograve D2 Ohorn 1A0 Ohungarumlaut 150 " .. + "Omacron 14C Omega 2126 Omegatonos 38F Omicron 39F Omicrontonos 38C Oslash D8 Oslashacute 1FE Otilde " .. + "D5 P 50 Phi 3A6 Pi 3A0 Psi 3A8 Q 51 R 52 Racute 154 Rcaron 158 Rfraktur 211C Rho 3A1 S 53 SF010000 " .. + "250C SF020000 2514 SF030000 2510 SF040000 2518 SF050000 253C SF060000 252C SF070000 2534 SF080000 " .. + "251C SF090000 2524 SF100000 2500 SF110000 2502 SF190000 2561 SF200000 2562 SF210000 2556 SF220000 " .. + "2555 SF230000 2563 SF240000 2551 SF250000 2557 SF260000 255D SF270000 255C SF280000 255B SF360000 " .. + "255E SF370000 255F SF380000 255A SF390000 2554 SF400000 2569 SF410000 2566 SF420000 2560 SF430000 " .. + "2550 SF440000 256C SF450000 2567 SF460000 2568 SF470000 2564 SF480000 2565 SF490000 2559 SF500000 " .. + "2558 SF510000 2552 SF520000 2553 SF530000 256B SF540000 256A Sacute 15A Scaron 160 Scedilla 15E " .. + "Scircumflex 15C Sigma 3A3 T 54 Tau 3A4 Tbar 166 Tcaron 164 Theta 398 Thorn DE U 55 Uacute DA Ubreve " .. + "16C Ucircumflex DB Udieresis DC Ugrave D9 Uhorn 1AF Uhungarumlaut 170 Umacron 16A Uogonek 172 " .. + "Upsilon 3A5 Upsilon1 3D2 Upsilondieresis 3AB Upsilontonos 38E Uring 16E Utilde 168 V 56 W 57 Wacute " .. + "1E82 Wcircumflex 174 Wdieresis 1E84 Wgrave 1E80 X 58 Xi 39E Y 59 Yacute DD Ycircumflex 176 " .. + "Ydieresis 178 Ygrave 1EF2 Z 5A Zacute 179 Zcaron 17D Zdotaccent 17B Zeta 396 a 61 aacute E1 abreve " .. + "103 acircumflex E2 acute B4 acutecomb 301 adieresis E4 ae E6 aeacute 1FD agrave E0 aleph 2135 alpha " .. + "3B1 alphatonos 3AC amacron 101 ampersand 26 angle 2220 angleleft 2329 angleright 232A anoteleia 387 " .. + "aogonek 105 approxequal 2248 aring E5 aringacute 1FB arrowboth 2194 arrowdblboth 21D4 arrowdbldown " .. + "21D3 arrowdblleft 21D0 arrowdblright 21D2 arrowdblup 21D1 arrowdown 2193 arrowleft 2190 arrowright " .. + "2192 arrowup 2191 arrowupdn 2195 arrowupdnbse 21A8 asciicircum 5E asciitilde 7E asterisk 2A " .. + "asteriskmath 2217 at 40 atilde E3 b 62 backslash 5C bar 7C beta 3B2 block 2588 braceleft 7B " .. + "braceright 7D bracketleft 5B bracketright 5D breve 2D8 brokenbar A6 bullet 2022 c 63 cacute 107 " .. + "caron 2C7 carriagereturn 21B5 ccaron 10D ccedilla E7 ccircumflex 109 cdotaccent 10B cedilla B8 cent " .. + "A2 chi 3C7 circle 25CB circlemultiply 2297 circleplus 2295 circumflex 2C6 club 2663 colon 3A " .. + "colonmonetary 20A1 comma 2C congruent 2245 copyright A9 currency A4 d 64 dagger 2020 daggerdbl 2021 " .. + "dcaron 10F dcroat 111 degree B0 delta 3B4 diamond 2666 dieresis A8 dieresistonos 385 divide F7 " .. + "dkshade 2593 dnblock 2584 dollar 24 dong 20AB dotaccent 2D9 dotbelowcomb 323 dotlessi 131 dotlessj " .. + "237 dotmath 22C5 e 65 eacute E9 ebreve 115 ecaron 11B ecircumflex EA edieresis EB edotaccent 117 " .. + "egrave E8 eight 38 element 2208 ellipsis 2026 emacron 113 emdash 2014 emptyset 2205 endash 2013 eng " .. + "14B eogonek 119 epsilon 3B5 epsilontonos 3AD equal 3D equivalence 2261 estimated 212E eta 3B7 " .. + "etatonos 3AE eth F0 exclam 21 exclamdbl 203C exclamdown A1 existential 2203 f 66 female 2640 ff " .. + "FB00 ffi FB03 ffl FB04 fi FB01 figuredash 2012 filledbox 25A0 filledrect 25AC five 35 fiveeighths " .. + "215D fl FB02 florin 192 four 34 fraction 2044 franc 20A3 g 67 gamma 3B3 gbreve 11F gcaron 1E7 " .. + "gcircumflex 11D gdotaccent 121 germandbls DF gradient 2207 grave 60 gravecomb 300 greater 3E " .. + "greaterequal 2265 guillemotleft AB guillemotright BB guilsinglleft 2039 guilsinglright 203A h 68 " .. + "hbar 127 hcircumflex 125 heart 2665 hookabovecomb 309 house 2302 hungarumlaut 2DD hyphen 2D i 69 " .. + "iacute ED ibreve 12D icircumflex EE idieresis EF igrave EC ij 133 imacron 12B infinity 221E " .. + "integral 222B integralbt 2321 integraltp 2320 intersection 2229 invbullet 25D8 invcircle 25D9 " .. + "invsmileface 263B iogonek 12F iota 3B9 iotadieresis 3CA iotadieresistonos 390 iotatonos 3AF itilde " .. + "129 j 6A jcircumflex 135 k 6B kappa 3BA kgreenlandic 138 l 6C lacute 13A lambda 3BB lcaron 13E ldot " .. + "140 less 3C lessequal 2264 lfblock 258C lira 20A4 logicaland 2227 logicalnot AC logicalor 2228 " .. + "longs 17F lozenge 25CA lslash 142 ltshade 2591 m 6D macron AF male 2642 minus 2212 minute 2032 mu " .. + "B5 multiply D7 musicalnote 266A musicalnotedbl 266B n 6E nacute 144 napostrophe 149 ncaron 148 nine " .. + "39 notelement 2209 notequal 2260 notsubset 2284 ntilde F1 nu 3BD numbersign 23 o 6F oacute F3 " .. + "obreve 14F ocircumflex F4 odieresis F6 oe 153 ogonek 2DB ograve F2 ohorn 1A1 ohungarumlaut 151 " .. + "omacron 14D omega 3C9 omega1 3D6 omegatonos 3CE omicron 3BF omicrontonos 3CC one 31 onedotenleader " .. + "2024 oneeighth 215B onehalf BD onequarter BC onethird 2153 openbullet 25E6 ordfeminine AA " .. + "ordmasculine BA orthogonal 221F oslash F8 oslashacute 1FF otilde F5 p 70 paragraph B6 parenleft 28 " .. + "parenright 29 partialdiff 2202 percent 25 period 2E periodcentered B7 perpendicular 22A5 " .. + "perthousand 2030 peseta 20A7 phi 3C6 phi1 3D5 pi 3C0 plus 2B plusminus B1 prescription 211E product " .. + "220F propersubset 2282 propersuperset 2283 proportional 221D psi 3C8 q 71 question 3F questiondown " .. + "BF quotedbl 22 quotedblbase 201E quotedblleft 201C quotedblright 201D quoteleft 2018 quotereversed " .. + "201B quoteright 2019 quotesinglbase 201A quotesingle 27 r 72 racute 155 radical 221A rcaron 159 " .. + "reflexsubset 2286 reflexsuperset 2287 registered AE revlogicalnot 2310 rho 3C1 ring 2DA rtblock " .. + "2590 s 73 sacute 15B scaron 161 scedilla 15F scircumflex 15D second 2033 section A7 semicolon 3B " .. + "seven 37 seveneighths 215E shade 2592 sigma 3C3 sigma1 3C2 similar 223C six 36 slash 2F smileface " .. + "263A space 20 spade 2660 sterling A3 suchthat 220B summation 2211 sun 263C t 74 tau 3C4 tbar 167 " .. + "tcaron 165 therefore 2234 theta 3B8 theta1 3D1 thorn FE three 33 threeeighths 215C threequarters BE " .. + "tilde 2DC tildecomb 303 tonos 384 trademark 2122 triagdn 25BC triaglf 25C4 triagrt 25BA triagup " .. + "25B2 two 32 twodotenleader 2025 twothirds 2154 u 75 uacute FA ubreve 16D ucircumflex FB udieresis " .. + "FC ugrave F9 uhorn 1B0 uhungarumlaut 171 umacron 16B underscore 5F underscoredbl 2017 union 222A " .. + "universal 2200 uogonek 173 upblock 2580 upsilon 3C5 upsilondieresis 3CB upsilondieresistonos 3B0 " .. + "upsilontonos 3CD uring 16F utilde 169 v 76 w 77 wacute 1E83 wcircumflex 175 wdieresis 1E85 " .. + "weierstrass 2118 wgrave 1E81 x 78 xi 3BE y 79 yacute FD ycircumflex 177 ydieresis FF yen A5 ygrave " .. + "1EF3 z 7A zacute 17A zcaron 17E zdotaccent 17C zero 30 zeta 3B6 " .. + "" + +-- StandardEncoding: 256 names, "-" = .notdef +local STD = "" .. + "- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - space exclam quotedbl numbersign " .. + "dollar percent ampersand quoteright parenleft parenright asterisk plus comma hyphen period slash " .. + "zero one two three four five six seven eight nine colon semicolon less equal greater question at A " .. + "B C D E F G H I J K L M N O P Q R S T U V W X Y Z bracketleft backslash bracketright asciicircum " .. + "underscore quoteleft a b c d e f g h i j k l m n o p q r s t u v w x y z braceleft bar braceright " .. + "asciitilde - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - exclamdown cent " .. + "sterling fraction yen florin section currency quotesingle quotedblleft guillemotleft guilsinglleft " .. + "guilsinglright fi fl - endash dagger daggerdbl periodcentered - paragraph bullet quotesinglbase " .. + "quotedblbase quotedblright guillemotright ellipsis perthousand - questiondown - grave acute " .. + "circumflex tilde macron breve dotaccent dieresis - ring cedilla - hungarumlaut ogonek caron emdash " .. + "- - - - - - - - - - - - - - - - AE - ordfeminine - - - - Lslash Oslash OE ordmasculine - - - - - ae " .. + "- - - dotlessi - - lslash oslash oe germandbls - - - - " .. + "" + +local byName: { [string]: number }? = nil + +local function load(): { [string]: number } + local t: { [string]: number } = {} + for name, hex in string.gmatch(AGL, "(%S+) (%x+)") do + t[name] = tonumber(hex, 16) :: number + end + byName = t + return t +end + +local STANDARD: { [number]: string } = {} +do + local i = 0 + for name in string.gmatch(STD, "%S+") do + if name ~= "-" then + STANDARD[i] = name + end + i += 1 + end +end +GlyphNames.STANDARD = STANDARD + +function GlyphNames.unicode(name: string): number? + local base = string.match(name, "^([^%.]+)") or name + local t = byName or load() + local v = t[base] + if v then + return v + end + local hex = string.match(base, "^uni(%x%x%x%x)") + if hex then + local c = tonumber(hex, 16) :: number + return if c >= 0xD800 and c < 0xE000 then nil else c + end + hex = string.match(base, "^u(%x%x%x%x%x?%x?)$") + if hex then + local c = tonumber(hex, 16) :: number + return if c > 0x10FFFF or (c >= 0xD800 and c < 0xE000) then nil else c + end + local first = string.match(base, "^([^_]+)_") + if first then + return GlyphNames.unicode(first) + end + return nil +end + +return GlyphNames +end +__FILES["codecs/font/TrueType"] = function() + +-- codecs/font/TrueType: the sfnt container (.ttf, .otf with CFF outlines, .ttc collections) as the standard Font value. +-- Ported from stb_truetype 1.26 (public domain / MIT, Sean Barrett et al.) via imgui-luau's imstb_truetype.lua. +local Err = __include("core/Err") +local Types = __include("Types") +local Raster = __include("codecs/image/Raster") +local Cff = __include("codecs/font/Cff") +local Glyf = __include("codecs/font/TrueType/Glyf") +local Tables = __include("codecs/font/TrueType/Tables") + +local TrueType = {} + +local u16, i16, u32 = Tables.u16, Tables.i16, Tables.u32 + +local function tag(b: buffer, o: number): string + if o < 0 or o + 4 > buffer.len(b) then + return "" + end + return buffer.readstring(b, o, 4) +end + +function TrueType.count(b: buffer, offset: number?): number + local o = offset or 0 + local t = tag(b, o) + if t == "ttcf" then + return u32(b, o + 8) + end + if t == "\0\1\0\0" or t == "OTTO" or t == "true" or t == "typ1" then + return 1 + end + return 0 +end + +function TrueType.tables(b: buffer, file: number, dir: number, limit: number): ({ [string]: { number } }?, string?) + local n = u16(b, dir + 4) + if dir + 12 + n * 16 > limit then + return nil, "table directory past the end" + end + local out: { [string]: { number } } = {} + for i = 0, n - 1 do + local r = dir + 12 + i * 16 + local t = tag(b, r) + local off, len = u32(b, r + 8), u32(b, r + 12) + if file + off + len <= limit then + out[t] = { file + off, len } + end + end + return out, nil +end + +local Face = {} +Face.__index = Face + +function Face.glyphIndex(self: any, cp: number): number + return Tables.glyph(self._cmap, cp) +end + +function Face.advance(self: any, g: number): number + if type(g) ~= "number" or g < 0 or g >= self.numGlyphs then + return 0 + end + local nh = self._numHMetrics + if nh == 0 then + return 0 + end + local h = self._hmtx + return u16(self._buf, h + 4 * math.min(g, nh - 1)) +end + +function Face.leftSideBearing(self: any, g: number): number + if type(g) ~= "number" or g < 0 or g >= self.numGlyphs then + return 0 + end + local nh, h = self._numHMetrics, self._hmtx + if g < nh then + return i16(self._buf, h + 4 * g + 2) + end + return i16(self._buf, h + 4 * nh + 2 * (g - nh)) +end + +function Face.kern(self: any, a: number, b: number): number + if type(a) ~= "number" or type(b) ~= "number" then + return 0 + end + local key = a * 65536 + b + local cache = self._kernCache + local v = cache[key] + if v then + return v + end + v = 0 + if self._gpos then + v = Tables.gposKern(self._gpos, a, b) + end + if v == 0 and self._kern then + v = self._kern[key] or 0 + end + cache[key] = v + return v +end + +function Face.kernCodepoints(self: any, a: number, b: number): number + return self:kern(self:glyphIndex(a), self:glyphIndex(b)) +end + +function Face.outline(self: any, g: number): { any }? + if type(g) ~= "number" or g < 0 or g >= self.numGlyphs or g % 1 ~= 0 then + return nil + end + local ok, cmds, err = pcall(function() + if self._cff then + return Cff.outline(self._cff, g) + end + return Glyf.outline(self._glyf, g) + end) + if not ok then + self.meta.lastError = tostring(cmds) + return nil + end + if not cmds then + self.meta.lastError = err + end + return cmds +end + +function Face.bounds(self: any, g: number): (number?, number, number, number) + local cmds = self:outline(g) + if not cmds then + return nil, 0, 0, 0 + end + local x0, y0, x1, y1 = math.huge, math.huge, -math.huge, -math.huge + for _, c in cmds do + for i = 1, #c - 1, 2 do + local x, y = c[i], c[i + 1] + x0, y0, x1, y1 = math.min(x0, x), math.min(y0, y), math.max(x1, x), math.max(y1, y) + end + end + if x0 > x1 then + return nil, 0, 0, 0 + end + return x0, y0, x1, y1 +end + +function Face.scale(self: any, px: number): number + return px / self.unitsPerEm +end + +type RasterOptions = { + scaleX: number?, + scaleY: number?, + shiftX: number?, + shiftY: number?, +} + +-- meta.top counts up from the baseline, as FreeType's bitmap_top +function Face.rasterize(self: any, g: number, px: number, opts: RasterOptions?): Types.Image? + if type(px) ~= "number" or not (px > 0) or px > 4096 then + return nil + end + local cmds = self:outline(g) + if not cmds then + return nil + end + 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 + local m = Raster.mask(cmds, { transform = { sx, 0, 0, -sy, tx, ty }, maxPixels = 2 ^ 24 }) + local img + if m then + img = Types.Image.new(m.width, m.height, "alpha8") + buffer.copy(img.pixels, 0, m.coverage) + img.meta.left = m.x + img.meta.top = -m.y + else + img = Types.Image.new(0, 0, "alpha8") + img.meta.left = 0 + img.meta.top = 0 + end + img.meta.advance = self:advance(g) * sx + img.meta.glyph = g + return img +end + +type Options = { index: number? } + +function TrueType.font(buf: buffer, offset: number?, length: number?, opts: Options?): (any, Err.Err?) + local b = buf + local file = offset or 0 + local limit = math.min(buffer.len(b), file + (length or (buffer.len(b) - file))) + if limit - file < 12 then + return nil, Err.new(Err.TRUNCATED, "too short for an sfnt header", file) + end + local dir = file + local index = (opts and opts.index) or 0 + local count = TrueType.count(b, file) + if tag(b, file) == "ttcf" then + if type(index) ~= "number" or index < 0 or index >= count or index % 1 ~= 0 then + return nil, Err.new(Err.ARG, string.format("font index %s out of range (collection of %d)", tostring(index), count)) + end + dir = file + u32(b, file + 12 + index * 4) + if dir + 12 > limit then + return nil, Err.new(Err.TRUNCATED, "collection font directory past the end", file) + end + elseif count == 0 then + return nil, Err.new(Err.CORRUPT, "not an sfnt font", file) + end + local sfntTag = tag(b, dir) + if sfntTag == "typ1" then + return nil, Err.new(Err.UNSUPPORTED, "PostScript Type 1 sfnt", dir) + end + local t, terr = TrueType.tables(b, file, dir, limit) + if not t then + return nil, Err.new(Err.TRUNCATED, terr or "bad table directory", dir) + end + for _, need in { "head", "hhea", "maxp", "hmtx" } do + if not t[need] then + return nil, Err.new(Err.CORRUPT, "missing the " .. need .. " table", dir) + end + end + local head, hhea, maxp, hmtx = t.head[1], t.hhea[1], t.maxp[1], t.hmtx[1] + if t.head[2] < 54 or t.hhea[2] < 36 or t.maxp[2] < 6 then + return nil, Err.new(Err.TRUNCATED, "short head / hhea / maxp table", dir) + end + local upem = u16(b, head + 18) + if upem < 16 or upem > 16384 then + return nil, Err.new(Err.CORRUPT, "bad unitsPerEm " .. upem, head + 18) + end + local numGlyphs = u16(b, maxp + 4) + local nh = math.min(u16(b, hhea + 34), numGlyphs) + if nh * 4 > t.hmtx[2] then + nh = t.hmtx[2] // 4 + end + local font: any = setmetatable({ + kind = "font", + info = {}, + unitsPerEm = upem, + ascent = i16(b, hhea + 4), + descent = i16(b, hhea + 6), + lineGap = i16(b, hhea + 8), + numGlyphs = numGlyphs, + bbox = { i16(b, head + 36), i16(b, head + 38), i16(b, head + 40), i16(b, head + 42) }, + pages = nil, + meta = {}, + _buf = b, + _hmtx = hmtx, + _numHMetrics = nh, + _kernCache = {}, + }, Face) + if t.glyf and t.loca then + font._glyf = { + buf = b, + glyf = t.glyf[1], + glyfLen = t.glyf[2], + loca = t.loca[1], + locaLen = t.loca[2], + longLoca = i16(b, head + 50) ~= 0, + numGlyphs = numGlyphs, + } + font.meta.outlines = "truetype" + elseif t["CFF "] then + local cff, cerr = Cff.parse(b, t["CFF "][1], t["CFF "][2]) + if not cff then + local code = if cerr and string.find(cerr, "unsupported", 1, true) then Err.UNSUPPORTED else Err.CORRUPT + return nil, Err.new(code, "CFF: " .. tostring(cerr), t["CFF "][1]) + end + font._cff = cff + font.meta.outlines = "cff" + elseif t.CFF2 then + return nil, Err.new(Err.UNSUPPORTED, "CFF2 outlines (variable OpenType)", dir) + else + return nil, Err.new(Err.UNSUPPORTED, "no glyf or CFF outlines (bitmap-only font?)", dir) + end + if t.cmap then + font._cmap = Tables.cmap(b, t.cmap[1], t.cmap[2]) + end + if t.kern then + font._kern = Tables.kern(b, t.kern[1], t.kern[2]) + end + if t.GPOS then + font._gpos = Tables.gpos(b, t.GPOS[1], t.GPOS[2]) + end + if t.name then + local names = Tables.names(b, t.name[1], t.name[2]) + for k, v in names do + font.info[k] = v + end + font.info.family = names.typographicFamily or names.family + font.info.style = names.typographicStyle or names.style + end + if t["OS/2"] and t["OS/2"][2] >= 10 then + font.meta.os2 = Tables.os2(b, t["OS/2"][1], t["OS/2"][2]) + end + if t.post and t.post[2] >= 16 then + local p = t.post[1] + font.meta.italicAngle = i16(b, p + 4) + u16(b, p + 6) / 65536 + font.meta.underlinePosition = i16(b, p + 8) + font.meta.underlineThickness = i16(b, p + 10) + font.meta.fixedPitch = u32(b, p + 12) ~= 0 + end + local tags = {} + for k in t do + table.insert(tags, k) + end + table.sort(tags) + font.meta.tables = tags + font.meta.sfnt = if sfntTag == "OTTO" then "OTTO" else "TrueType" + font.meta.collection = if count > 1 or tag(b, file) == "ttcf" then { index = index, count = count } else nil + return font, nil +end + +return TrueType +end +__FILES["codecs/font/TrueType/Glyf"] = function() + +-- codecs/font/TrueType/Glyf: TrueType glyph outlines from the glyf / loca tables, simple and composite. +-- Ported from stb_truetype 1.26 (public domain / MIT, Sean Barrett) via imgui-luau's imstb_truetype.lua; component +-- offsets follow FreeType and the spec (stb also scales the offsets of transformed components). +local Glyf = {} + +local readu8, readi8 = buffer.readu8, buffer.readi8 +local blen = buffer.len +local band = bit32.band + +local function u8(b: buffer, o: number): number + if o < 0 or o + 1 > blen(b) then + return 0 + end + return readu8(b, o) +end +local function u16(b: buffer, o: number): number + if o < 0 or o + 2 > blen(b) then + return 0 + end + return readu8(b, o) * 256 + readu8(b, o + 1) +end +local function i16(b: buffer, o: number): number + local v = u16(b, o) + return if v >= 32768 then v - 65536 else v +end +local function u32(b: buffer, o: number): number + return u16(b, o) * 65536 + u16(b, o + 2) +end + +type Face = { + buf: buffer, + glyf: number, + glyfLen: number, + loca: number, + locaLen: number, + longLoca: boolean, + numGlyphs: number, + [string]: any, +} + +function Glyf.range(f: Face, g: number): (number?, number) + if g < 0 or g >= f.numGlyphs or g % 1 ~= 0 then + return nil, 0 + end + local a, z + if f.longLoca then + 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) :: number + else + if (g + 2) * 2 > f.locaLen then + return nil, 0 + end + a, z = u16(f.buf, f.loca + g * 2) * 2, u16(f.buf, f.loca + g * 2 + 2) * 2 + end + if z <= a or z > f.glyfLen then + return nil, 0 + end + return f.glyf + a, z - a +end + +function Glyf.bounds(f: Face, g: number): (number?, number, number, number) + local o, n = Glyf.range(f, g) + if not o or n < 10 then + return nil, 0, 0, 0 + end + local b = f.buf + return i16(b, o + 2), i16(b, o + 4), i16(b, o + 6), i16(b, o + 8) +end + +type Contour = { x: { number }, y: { number }, on: { boolean } } + +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) :: { number } + local p = o + 10 + if p + nc * 2 + 2 > e then + return nil, "glyph header past the end" + end + local last = -1 + for i = 1, nc do + local v = u16(b, p) + if v < last then + return nil, "contour end points out of order" + end + ends[i] = v + last = v + p += 2 + end + local n = last + 1 + if n > MAX_POINTS then + return nil, "too many points" + end + local ins = u16(b, p) + p += 2 + ins + if p > e then + return nil, "instructions past the end" + end + local flags = table.create(n, 0) + local i = 1 + while i <= n do + if p >= e then + return nil, "flags past the end" + end + local fl = readu8(b, p) + p += 1 + flags[i] = fl + i += 1 + if band(fl, 8) ~= 0 then + if p >= e then + return nil, "flags past the end" + end + local rep = readu8(b, p) + p += 1 + for _ = 1, rep do + if i > n then + break + end + flags[i] = fl + i += 1 + end + end + end + local xs = table.create(n, 0) + local x = 0 + for k = 1, n do + local fl = flags[k] + if band(fl, 2) ~= 0 then + if p >= e then + return nil, "x coordinates past the end" + end + local d = readu8(b, p) + p += 1 + x += if band(fl, 16) ~= 0 then d else -d + elseif band(fl, 16) == 0 then + if p + 2 > e then + return nil, "x coordinates past the end" + end + x += i16(b, p) + p += 2 + end + xs[k] = x + end + local ys = table.create(n, 0) + local y = 0 + for k = 1, n do + local fl = flags[k] + if band(fl, 4) ~= 0 then + if p >= e then + return nil, "y coordinates past the end" + end + local d = readu8(b, p) + p += 1 + y += if band(fl, 32) ~= 0 then d else -d + elseif band(fl, 32) == 0 then + if p + 2 > e then + return nil, "y coordinates past the end" + end + y += i16(b, p) + p += 2 + end + ys[k] = y + end + local out = table.create(nc) :: { Contour } + local s = 1 + for c = 1, nc do + local z = ends[c] + 1 + local cx, cy, con = {}, {}, {} + for k = s, z do + table.insert(cx, xs[k]) + table.insert(cy, ys[k]) + table.insert(con, band(flags[k], 1) ~= 0) + end + out[c] = { x = cx, y = cy, on = con } + s = z + 1 + end + return out, nil +end + +local contours: (f: Face, g: number, depth: number) -> ({ Contour }?, string?) + +local function composite(f: Face, o: number, len: number, depth: number): ({ Contour }?, string?) + local b = f.buf + local e = o + len + local p = o + 10 + local out: { Contour } = {} + local total = 0 + while true do + if p + 4 > e then + return nil, "component past the end" + end + local flags = u16(b, p) + local gi = u16(b, p + 2) + p += 4 + local a1, a2 + if band(flags, 1) ~= 0 then -- ARG_1_AND_2_ARE_WORDS + if p + 4 > e then + return nil, "component past the end" + end + if band(flags, 2) ~= 0 then + a1, a2 = i16(b, p), i16(b, p + 2) :: number + else + a1, a2 = u16(b, p), u16(b, p + 2) :: number + end + p += 4 + else + if p + 2 > e then + return nil, "component past the end" + end + if band(flags, 2) ~= 0 then + a1, a2 = readi8(b, p), readi8(b, p + 1) :: number + else + a1, a2 = readu8(b, p), readu8(b, p + 1) :: number + end + p += 2 + end + local m1, m2, m3, m4 = 1, 0, 0, 1 + if band(flags, 8) ~= 0 then -- WE_HAVE_A_SCALE + m1 = i16(b, p) / 16384 + m4 = m1 + p += 2 + elseif band(flags, 0x40) ~= 0 then -- WE_HAVE_AN_X_AND_Y_SCALE + m1, m4 = i16(b, p) / 16384, i16(b, p + 2) / 16384 + p += 4 + elseif band(flags, 0x80) ~= 0 then -- WE_HAVE_A_TWO_BY_TWO + m1, m2, m3, m4 = i16(b, p) / 16384, i16(b, p + 2) / 16384, i16(b, p + 4) / 16384, i16(b, p + 6) / 16384 + p += 8 + end + if p > e then + return nil, "component past the end" + end + local child, err = contours(f, gi, depth + 1) + if not child then + return nil, err + end + local tc = table.create(#child) :: { Contour } + for i, c in child do + 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 + ny[k] = m2 * x + m4 * y + end + tc[i] = { x = nx, y = ny, on = c.on } + end + local dx, dy + if band(flags, 2) ~= 0 then -- ARGS_ARE_XY_VALUES + dx, dy = a1, a2 + if band(flags, 0x800) ~= 0 and band(flags, 0x1000) == 0 then -- SCALED_COMPONENT_OFFSET + dx, dy = m1 * a1 + m3 * a2, m2 * a1 + m4 * a2 + end + else + -- point matching: parent point a1 (in what is composed so far) meets child point a2 + local function pt(list: { Contour }, idx: number): (number?, number) + local k = idx + for _, c in list do + local n = #c.x + if k < n then + return c.x[k + 1], c.y[k + 1] + end + k -= n + end + return nil, 0 + end + local px, py = pt(out, a1) + local cx, cy = pt(tc, a2) + if not px or not cx then + return nil, "component point index out of range" + end + dx, dy = px - cx, py - (cy :: number) + end + for _, c in tc do + for k = 1, #c.x do + c.x[k] += dx + c.y[k] += dy + end + total += #c.x + table.insert(out, c) + end + if total > MAX_POINTS then + return nil, "too many points" + end + if band(flags, 0x20) == 0 then -- MORE_COMPONENTS + break + end + end + return out, nil +end + +contours = function(f: Face, g: number, depth: number): ({ Contour }?, string?) + if depth > 8 then + return nil, "composite glyphs nested too deep" + end + local o, len = Glyf.range(f, g) + if not o then + return {}, nil + end + if len < 10 then + return nil, "glyph header past the end" + end + local nc = i16(f.buf, o) + if nc >= 0 then + return simple(f.buf, o, len, nc) + end + return composite(f, o, len, depth) +end + +function Glyf.outline(f: Face, g: number): ({ any }?, string?) + local cs, err = contours(f, g, 0) + if not cs then + return nil, err + end + local cmds = {} + for _, c in cs do + local n = #c.x + if n < 2 then + continue + end + local xs, ys, on = c.x, c.y, c.on + -- the start: the first on-curve point, or the midpoint of the first two off-curve points + local s = 0 + for k = 1, n do + if on[k] then + s = k + break + end + end + local sx, sy + if s == 0 then + sx, sy = (xs[1] + xs[n]) / 2, (ys[1] + ys[n]) / 2 + s = 1 + -- all off-curve: start at the implied midpoint between the last and the first, then walk from 1 + table.insert(cmds, { op = "moveTo", sx, sy }) + local cx, cy = xs[1], ys[1] + for k = 2, n do + local x, y = xs[k], ys[k] + table.insert(cmds, { op = "quadTo", cx, cy, (cx + x) / 2, (cy + y) / 2 }) + cx, cy = x, y + end + table.insert(cmds, { op = "quadTo", cx, cy, sx, sy }) + table.insert(cmds, { op = "close" }) + continue + end + sx, sy = xs[s], ys[s] + table.insert(cmds, { op = "moveTo", sx, sy }) + local off = false + local cx, cy = 0, 0 + for i = 1, n do + local k = (s + i - 1) % n + 1 + local x, y, isOn = xs[k], ys[k], on[k] + if i == n then + x, y, isOn = sx, sy, true + end + if isOn then + if off then + table.insert(cmds, { op = "quadTo", cx, cy, x, y }) + elseif i < n then + table.insert(cmds, { op = "lineTo", x, y }) + end + off = false + else + if off then + table.insert(cmds, { op = "quadTo", cx, cy, (cx + x) / 2, (cy + y) / 2 }) + end + cx, cy = x, y + off = true + end + end + table.insert(cmds, { op = "close" }) + end + return cmds, nil +end + +function Glyf.counts(f: Face, g: number): (number, number) + local cs = contours(f, g, 0) + if not cs then + return 0, 0 + end + local n = 0 + for _, c in cs do + n += #c.x + end + return n, #cs +end + +return Glyf +end +__FILES["codecs/font/TrueType/Tables"] = function() + +-- codecs/font/TrueType/Tables: the sfnt cmap (0, 4, 6, 10, 12, 13), kern, GPOS pair kerning, name and OS/2 tables. +-- Written from the OpenType spec; stb_truetype 1.26 (public domain / MIT) was the reference for cmap 4 and GPOS. +local Text = __include("codecs/text/Text") +local Tables = {} + +local readu8 = buffer.readu8 +local blen = buffer.len +local band = bit32.band + +local function u8(b: buffer, o: number): number + if o < 0 or o + 1 > blen(b) then + return 0 + end + return readu8(b, o) +end +local function u16(b: buffer, o: number): number + if o < 0 or o + 2 > blen(b) then + return 0 + end + return readu8(b, o) * 256 + readu8(b, o + 1) +end +local function i16(b: buffer, o: number): number + local v = u16(b, o) + return if v >= 32768 then v - 65536 else v +end +local function u32(b: buffer, o: number): number + return u16(b, o) * 65536 + u16(b, o + 2) +end +Tables.u8, Tables.u16, Tables.i16, Tables.u32 = u8, u16, i16, u32 + +type Cmap = { buf: buffer, at: number, format: number, symbol: boolean } + +-- cmap subtable preference: Unicode full repertoire, then BMP, then symbol, then Mac +function Tables.cmap(b: buffer, o: number, n: number): Cmap? + local count = u16(b, o + 2) + local best, bestRank, symbol = -1, 0, false + for i = 0, count - 1 do + local r = o + 4 + i * 8 + if r + 8 > o + n then + break + end + local pid, eid, off = u16(b, r), u16(b, r + 2), u32(b, r + 4) + local at = o + off + if off >= n then + continue + end + local fmt = u16(b, at) + local rank = 0 + if pid == 3 and eid == 10 then + rank = 6 + elseif pid == 0 and (eid == 4 or eid == 6) then + rank = 5 + elseif pid == 3 and eid == 1 then + rank = 4 + elseif pid == 0 and fmt ~= 14 then + rank = 3 + elseif pid == 3 and eid == 0 then + rank = 2 + elseif pid == 1 and eid == 0 then + rank = 1 + end + if fmt ~= 0 and fmt ~= 4 and fmt ~= 6 and fmt ~= 10 and fmt ~= 12 and fmt ~= 13 then + rank = 0 + end + if rank > bestRank then + best, bestRank, symbol = at, rank, pid == 3 and eid == 0 + end + end + if best < 0 then + return nil + end + return { buf = b, at = best, format = u16(b, best), symbol = symbol } +end + +local function lookup(c: Cmap, cp: number): number + local b, t, fmt = c.buf, c.at, c.format + if fmt == 0 then + return if cp < 256 then u8(b, t + 6 + cp) else 0 + elseif fmt == 6 then + local first, count = u16(b, t + 6), u16(b, t + 8) + if cp >= first and cp < first + count then + return u16(b, t + 10 + (cp - first) * 2) + end + return 0 + elseif fmt == 10 then + local first, count = u32(b, t + 12), u32(b, t + 16) + if cp >= first and cp < first + count then + return u16(b, t + 20 + (cp - first) * 2) + end + return 0 + elseif fmt == 4 then + if cp > 0xFFFF then + return 0 + end + local segX2 = u16(b, t + 6) + local segs = segX2 // 2 + local ends = t + 14 + local lo, hi = 0, segs - 1 + while lo < hi do + local mid = (lo + hi) // 2 + if u16(b, ends + mid * 2) < cp then + lo = mid + 1 + else + hi = mid + end + end + if segs == 0 or u16(b, ends + lo * 2) < cp then + return 0 + end + local starts = ends + segX2 + 2 + local start = u16(b, starts + lo * 2) + if cp < start then + return 0 + end + local deltaAt = starts + segX2 + lo * 2 + local delta = u16(b, deltaAt) + local rangeAt = deltaAt + segX2 + local ro = u16(b, rangeAt) + if ro == 0 then + return (cp + delta) % 65536 + end + local g = u16(b, rangeAt + ro + (cp - start) * 2) + if g == 0 then + return 0 + end + return (g + delta) % 65536 + elseif fmt == 12 or fmt == 13 then + local n = u32(b, t + 12) + local lo, hi = 0, n - 1 + while lo <= hi do + local mid = (lo + hi) // 2 + local g = t + 16 + mid * 12 + local s, e = u32(b, g), u32(b, g + 4) + if cp < s then + hi = mid - 1 + elseif cp > e then + lo = mid + 1 + else + local gid = u32(b, g + 8) + return if fmt == 12 then gid + cp - s else gid + end + end + return 0 + end + return 0 +end + +function Tables.glyph(c: Cmap?, cp: number): number + if not c or type(cp) ~= "number" or cp < 0 or cp > 0x10FFFF or cp % 1 ~= 0 then + return 0 + end + local g = lookup(c, cp) + if g == 0 and c.symbol and cp < 256 then + g = lookup(c, 0xF000 + cp) -- symbol fonts map U+F020.. to the 8-bit codes + end + return g +end + +function Tables.kern(b: buffer, o: number, n: number): { [number]: number } + local pairs: { [number]: number } = {} + local e = o + n + local apple = u32(b, o) == 0x00010000 + local count = if apple then u32(b, o + 4) else u16(b, o + 2) + local p = if apple then o + 8 else o + 4 + for _ = 1, math.min(count, 64) do + if p + 6 > e then + break + end + local len, fmt, horizontal, cross, minimum, hdr + if apple then + len = u32(b, p) + local cov = u16(b, p + 4) + fmt = band(cov, 0xFF) + horizontal = band(cov, 0x8000) == 0 + cross = band(cov, 0x4000) ~= 0 + minimum = band(cov, 0x2000) ~= 0 -- (variation) treated as not applicable + hdr = 8 + else + len = u16(b, p + 2) + local cov = u16(b, p + 4) + fmt = cov // 256 + horizontal = band(cov, 1) ~= 0 + minimum = band(cov, 2) ~= 0 + cross = band(cov, 4) ~= 0 + hdr = 6 + end + if fmt == 0 and horizontal and not cross and not minimum then + local np = u16(b, p + hdr) + local q = p + hdr + 8 + for k = 0, np - 1 do + local r = q + k * 6 + if r + 6 > e then + break + end + local key = u16(b, r) * 65536 + u16(b, r + 2) + pairs[key] = (pairs[key] or 0) + i16(b, r + 4) + end + end + if len < hdr then + break + end + -- Microsoft subtables often have a wrong 16-bit length for big tables: only the first is reliable then + if not apple and len < hdr + 8 then + break + end + p += len + end + return pairs +end + +local function popcount(v: number): number + local c = 0 + while v ~= 0 do + c += band(v, 1) + v = bit32.rshift(v, 1) + end + return c +end + +local function coverage(b: buffer, t: number, g: number): number + local fmt = u16(b, t) + if fmt == 1 then + local n = u16(b, t + 2) + local lo, hi = 0, n - 1 + while lo <= hi do + local mid = (lo + hi) // 2 + local v = u16(b, t + 4 + mid * 2) + if g < v then + hi = mid - 1 + elseif g > v then + lo = mid + 1 + else + return mid + end + end + elseif fmt == 2 then + local n = u16(b, t + 2) + local lo, hi = 0, n - 1 + while lo <= hi do + local mid = (lo + hi) // 2 + local r = t + 4 + mid * 6 + local s, e = u16(b, r), u16(b, r + 2) + if g < s then + hi = mid - 1 + elseif g > e then + lo = mid + 1 + else + return u16(b, r + 4) + g - s + end + end + end + return -1 +end + +local function classOf(b: buffer, t: number, g: number): number + local fmt = u16(b, t) + if fmt == 1 then + local s, n = u16(b, t + 2), u16(b, t + 4) + if g >= s and g < s + n then + return u16(b, t + 6 + (g - s) * 2) + end + elseif fmt == 2 then + local n = u16(b, t + 2) + local lo, hi = 0, n - 1 + while lo <= hi do + local mid = (lo + hi) // 2 + local r = t + 4 + mid * 6 + local s, e = u16(b, r), u16(b, r + 2) + if g < s then + hi = mid - 1 + elseif g > e then + lo = mid + 1 + else + return u16(b, r + 4) + end + end + end + return 0 +end + +local function xAdvance(b: buffer, r: number, vf: number): number + if band(vf, 4) == 0 then + return 0 + end + return i16(b, r + 2 * popcount(band(vf, 3))) +end + +local function pairPos(b: buffer, t: number, l: number, r: number): (boolean, number) + local fmt = u16(b, t) + local ci = coverage(b, t + u16(b, t + 2), l) + if ci < 0 then + return false, 0 + end + local vf1, vf2 = u16(b, t + 4), u16(b, t + 6) + local s1, s2 = 2 * popcount(band(vf1, 0xFF)), 2 * popcount(band(vf2, 0xFF)) + if fmt == 1 then + local count = u16(b, t + 8) + if ci >= count then + return false, 0 + end + local ps = t + u16(b, t + 10 + ci * 2) + local n = u16(b, ps) + local rec = 2 + s1 + s2 + local lo, hi = 0, n - 1 + while lo <= hi do + local mid = (lo + hi) // 2 + local q = ps + 2 + mid * rec + local g = u16(b, q) + if r < g then + hi = mid - 1 + elseif r > g then + lo = mid + 1 + else + return true, xAdvance(b, q + 2, vf1) + end + end + return false, 0 + elseif fmt == 2 then + local cd1, cd2 = t + u16(b, t + 8), t + u16(b, t + 10) + local n1, n2 = u16(b, t + 12), u16(b, t + 14) + local c1, c2 = classOf(b, cd1, l), classOf(b, cd2, r) + if c1 >= n1 or c2 >= n2 then + return false, 0 + end + local q = t + 16 + (c1 * n2 + c2) * (s1 + s2) + return true, xAdvance(b, q, vf1) + end + return false, 0 +end + +type Gpos = { buf: buffer, subtables: { { number } } } + +function Tables.gpos(b: buffer, o: number, n: number): Gpos? + if n < 10 or u16(b, o) ~= 1 then + return nil + end + local fl, ll = o + u16(b, o + 6), o + u16(b, o + 8) + local want: { [number]: boolean } = {} + local any = false + local nf = u16(b, fl) + for i = 0, nf - 1 do + local r = fl + 2 + i * 6 + if u32(b, r) == 0x6B65726E then -- "kern" + local f = fl + u16(b, r + 4) + for k = 0, u16(b, f + 2) - 1 do + want[u16(b, f + 4 + k * 2)] = true + any = true + end + end + end + if not any then + return nil + end + local lookups: { { number } } = {} + local nl = u16(b, ll) + for i = 0, nl - 1 do + if want[i] then + local lt = ll + u16(b, ll + 2 + i * 2) + local ty = u16(b, lt) + local subs: { number } = {} + for k = 0, math.min(u16(b, lt + 4), 4096) - 1 do + local st = lt + u16(b, lt + 6 + k * 2) + local sty = ty + if ty == 9 and u16(b, st) == 1 then -- extension + sty = u16(b, st + 2) + st += u32(b, st + 4) + end + if sty == 2 then + table.insert(subs, st) + end + end + if #subs > 0 then + table.insert(lookups, subs) + end + end + end + if #lookups == 0 then + return nil + end + return { buf = b, subtables = lookups } +end + +function Tables.gposKern(g: Gpos, l: number, r: number): number + local total = 0 + for _, subs in g.subtables do + for _, st in subs do + local applies, v = pairPos(g.buf, st, l, r) + if applies then + total += v + break + end + end + end + return total +end + +local MAC_ROMAN_HIGH = { + 0xC4, 0xC5, 0xC7, 0xC9, 0xD1, 0xD6, 0xDC, 0xE1, 0xE0, 0xE2, 0xE4, 0xE3, 0xE5, 0xE7, 0xE9, 0xE8, + 0xEA, 0xEB, 0xED, 0xEC, 0xEE, 0xEF, 0xF1, 0xF3, 0xF2, 0xF4, 0xF6, 0xF5, 0xFA, 0xF9, 0xFB, 0xFC, + 0x2020, 0xB0, 0xA2, 0xA3, 0xA7, 0x2022, 0xB6, 0xDF, 0xAE, 0xA9, 0x2122, 0xB4, 0xA8, 0x2260, 0xC6, 0xD8, + 0x221E, 0xB1, 0x2264, 0x2265, 0xA5, 0xB5, 0x2202, 0x2211, 0x220F, 0x3C0, 0x222B, 0xAA, 0xBA, 0x3A9, 0xE6, 0xF8, + 0xBF, 0xA1, 0xAC, 0x221A, 0x192, 0x2248, 0x2206, 0xAB, 0xBB, 0x2026, 0xA0, 0xC0, 0xC3, 0xD5, 0x152, 0x153, + 0x2013, 0x2014, 0x201C, 0x201D, 0x2018, 0x2019, 0xF7, 0x25CA, 0xFF, 0x178, 0x2044, 0x20AC, 0x2039, 0x203A, 0xFB01, 0xFB02, + 0x2021, 0xB7, 0x201A, 0x201E, 0x2030, 0xC2, 0xCA, 0xC1, 0xCB, 0xC8, 0xCD, 0xCE, 0xCF, 0xCC, 0xD3, 0xD4, + 0xF8FF, 0xD2, 0xDA, 0xDB, 0xD9, 0x131, 0x2C6, 0x2DC, 0xAF, 0x2D8, 0x2D9, 0x2DA, 0xB8, 0x2DD, 0x2DB, 0x2C7, +} + +local function utf16be(b: buffer, o: number, n: number): string + return Text.utf16(b, o, n, true) +end + +local function macRoman(b: buffer, o: number, n: number): string + local out = {} + for k = 0, n - 1 do + local c = u8(b, o + k) + table.insert(out, utf8.char(if c < 128 then c else MAC_ROMAN_HIGH[c - 127])) + end + return table.concat(out) +end + +local NAME_IDS: { [number]: string } = { + [0] = "copyright", + [1] = "family", + [2] = "style", + [3] = "uniqueId", + [4] = "fullName", + [5] = "version", + [6] = "postScriptName", + [7] = "trademark", + [8] = "manufacturer", + [9] = "designer", + [10] = "description", + [11] = "vendorUrl", + [12] = "designerUrl", + [13] = "license", + [14] = "licenseUrl", + [16] = "typographicFamily", + [17] = "typographicStyle", +} + +function Tables.names(b: buffer, o: number, n: number): { [string]: string } + local out: { [string]: string } = {} + local rank: { [string]: number } = {} + local count, strings = u16(b, o + 2), o + u16(b, o + 4) + for i = 0, math.min(count, 4096) - 1 do + local r = o + 6 + i * 12 + if r + 12 > o + n then + break + end + local pid, eid, lang, nid = u16(b, r), u16(b, r + 2), u16(b, r + 4), u16(b, r + 6) + 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: 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) + elseif pid == 0 then + rk = 3 + s = utf16be(b, strings + off, len) + elseif pid == 1 and eid == 0 then + rk = if lang == 0 then 1 else 0.5 + s = macRoman(b, strings + off, len) + end + if s and rk > (rank[key] or 0) then + out[key] = s + rank[key] = rk + end + end + end + return out +end + +function Tables.os2(b: buffer, o: number, n: number): { [string]: number } + local t: { [string]: number } = { + version = u16(b, o), + xAvgCharWidth = i16(b, o + 2), + weightClass = u16(b, o + 4), + widthClass = u16(b, o + 6), + fsType = u16(b, o + 8), + } + if n >= 78 then + t.fsSelection = u16(b, o + 62) + t.firstChar = u16(b, o + 64) + t.lastChar = u16(b, o + 66) + t.typoAscender = i16(b, o + 68) + t.typoDescender = i16(b, o + 70) + t.typoLineGap = i16(b, o + 72) + t.winAscent = u16(b, o + 74) + t.winDescent = u16(b, o + 76) + end + if n >= 96 and t.version >= 2 then + t.xHeight = i16(b, o + 86) + t.capHeight = i16(b, o + 88) + end + return t +end + +return Tables +end +end + + + + + + codecs_image + --!optimize 2 +--!nocheck +-- rosetta chunk codecs_image (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 8 modules (7 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["codecs/image/Blend"] = @native function() + + +-- codecs/image/Blend: rgba8 layer compositing (straight alpha) with the W3C Compositing and Blending Level 1 modes. +-- Clipping is source-atop (the backdrop keeps its alpha); unknown mode names composite as normal. +local Blend = {} + +local readu8, writeu8, readu32, writeu32, blen = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32, buffer.len +local min, max, floor, sqrt, abs = math.min, math.max, math.floor, math.sqrt, math.abs + +local IDS: { [string]: number } = { + normal = 0, + dissolve = 1, + darken = 2, + multiply = 3, + colorBurn = 4, + linearBurn = 5, + darkerColor = 6, + lighten = 7, + screen = 8, + colorDodge = 9, + linearDodge = 10, + add = 10, + lighterColor = 11, + overlay = 12, + softLight = 13, + hardLight = 14, + vividLight = 15, + linearLight = 16, + pinLight = 17, + hardMix = 18, + difference = 19, + exclusion = 20, + subtract = 21, + divide = 22, + hue = 23, + saturation = 24, + color = 25, + luminosity = 26, +} +local MODES: { [string]: boolean } = {} +for k in IDS do + MODES[k] = true +end +Blend.MODES = table.freeze(MODES) + +@native local function burn(cb: number, cs: number): number + if cb >= 1 then + return 1 + elseif cs <= 0 then + return 0 + end + return 1 - min(1, (1 - cb) / cs) +end +@native local function dodge(cb: number, cs: number): number + if cb <= 0 then + return 0 + elseif cs >= 1 then + return 1 + end + return min(1, cb / (1 - cs)) +end + +-- B(cb, cs) of a separable mode +@native local function sep(m: number, cb: number, cs: number): number + if m == 3 then + return cb * cs + elseif m == 8 then + return cb + cs - cb * cs + elseif m == 2 then + return min(cb, cs) + elseif m == 7 then + return max(cb, cs) + elseif m == 12 then -- overlay = hardLight(cs, cb) + if cb <= 0.5 then + return 2 * cb * cs + end + local c = 2 * cb - 1 + return cs + c - cs * c + elseif m == 14 then + if cs <= 0.5 then + return 2 * cb * cs + end + local c = 2 * cs - 1 + return cb + c - cb * c + elseif m == 13 then + if cs <= 0.5 then + return cb - (1 - 2 * cs) * cb * (1 - cb) + end + local d = if cb <= 0.25 then ((16 * cb - 12) * cb + 4) * cb else sqrt(cb) + return cb + (2 * cs - 1) * (d - cb) + elseif m == 9 then + return dodge(cb, cs) + elseif m == 4 then + return burn(cb, cs) + elseif m == 5 then + return max(0, cb + cs - 1) + elseif m == 10 then + return min(1, cb + cs) + elseif m == 15 then + if cs <= 0.5 then + return burn(cb, 2 * cs) + end + return dodge(cb, 2 * cs - 1) + elseif m == 16 then + return max(0, min(1, cb + 2 * cs - 1)) + elseif m == 17 then + if cs <= 0.5 then + return min(cb, 2 * cs) + end + return max(cb, 2 * cs - 1) + elseif m == 18 then + return if cb + cs >= 1 then 1 else 0 + elseif m == 19 then + return abs(cb - cs) + elseif m == 20 then + return cb + cs - 2 * cb * cs + elseif m == 21 then + return max(0, cb - cs) + elseif m == 22 then + if cs <= 0 then + return if cb <= 0 then 0 else 1 + end + return min(1, cb / cs) + end + return cs +end + +-- non-separable helpers (W3C): lum, clip, setLum, sat, setSat +@native local function lum(r: number, g: number, b: number): number + return 0.3 * r + 0.59 * g + 0.11 * b +end +@native local function clipColor(r: number, g: number, b: number): (number, number, number) + local l = lum(r, g, b) + local n = min(r, g, b) + local x = max(r, g, b) + if n < 0 and l - n > 1e-12 then + r, g, b = l + (r - l) * l / (l - n), l + (g - l) * l / (l - n), l + (b - l) * l / (l - n) + end + if x > 1 and x - l > 1e-12 then + r, g, b = l + (r - l) * (1 - l) / (x - l), l + (g - l) * (1 - l) / (x - l), l + (b - l) * (1 - l) / (x - l) + end + return r, g, b +end +@native local function setLum(r: number, g: number, b: number, l: number): (number, number, number) + local d = l - lum(r, g, b) + return clipColor(r + d, g + d, b + d) +end +@native local function setSat(r: number, g: number, b: number, s: number): (number, number, number) + local mx = max(r, g, b) + local mn = min(r, g, b) + if mx - mn <= 1e-12 then + return 0, 0, 0 + end + local k = s / (mx - mn) + return (r - mn) * k, (g - mn) * k, (b - mn) * k +end + +@native local function composite(dst: buffer, dw: number, dh: number, src: buffer, sw: number, sh: number, x: number, y: number, opacity: number, mode: string?, opts: { clip: boolean?, mask: any? }?) + x, y = floor(x), floor(y) + if opacity <= 0 or dw <= 0 or dh <= 0 or sw <= 0 or sh <= 0 then + return + end + if blen(dst) < dw * dh * 4 or blen(src) < sw * sh * 4 then + return + end + local op = min(1, opacity) + local m = IDS[mode or "normal"] or 0 + local clip = opts ~= nil and opts.clip == true + local mask = if opts ~= nil then opts.mask else nil + 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) :: 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) :: number + mdef = (tonumber(mask.default) or 255) / 255 + elseif type(mask) == "table" then + mdef = (tonumber(mask.default) or 255) / 255 + end + local x0, y0 = max(0, x), max(0, y) + local x1, y1 = min(dw, x + sw), min(dh, y + sh) + for py = y0, y1 - 1 do + local so = ((py - y) * sw + (x0 - x)) * 4 + local do_ = (py * dw + x0) * 4 + for px = x0, x1 - 1 do + local sa8 = readu8(src, so + 3) + if sa8 ~= 0 then + local sa = sa8 / 255 * op + if mbuf ~= nil or mdef ~= 1 then + local mv = mdef + local mxx, myy = px - mx0, py - my0 + if mbuf ~= nil and mxx >= 0 and myy >= 0 and mxx < mw and myy < mh then + mv = readu8(mbuf, myy * mw + mxx) / 255 + end + sa *= mv + end + if m == 1 then -- dissolve: a hash threshold per pixel, full alpha where it shows + local h = (px * 73856093 + py * 19349663) % 65536 / 65536 + sa = if h < sa then 1 else 0 + end + local ba8 = readu8(dst, do_ + 3) + if sa > 0 and not (clip and ba8 == 0) then + local sr, sg, sb = readu8(src, so) / 255, readu8(src, so + 1) / 255, readu8(src, so + 2) / 255 + if ba8 == 0 then + writeu32(dst, do_, readu32(src, so)) + writeu8(dst, do_ + 3, floor(sa * 255 + 0.5)) + else + local ba = ba8 / 255 + 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) :: number + elseif m == 6 then + if lum(sr, sg, sb) >= lum(br, bg, bb) then + mr, mg, mb = br, bg, bb + end + elseif m == 11 then + if lum(sr, sg, sb) < lum(br, bg, bb) then + mr, mg, mb = br, bg, bb + end + elseif m == 23 then + local s = max(br, bg, bb) - min(br, bg, bb) + local r1, g1, b1 = setSat(sr, sg, sb, s) + mr, mg, mb = setLum(r1, g1, b1, lum(br, bg, bb)) + elseif m == 24 then + local s = max(sr, sg, sb) - min(sr, sg, sb) + local r1, g1, b1 = setSat(br, bg, bb, s) + mr, mg, mb = setLum(r1, g1, b1, lum(br, bg, bb)) + elseif m == 25 then + mr, mg, mb = setLum(sr, sg, sb, lum(br, bg, bb)) + elseif m == 26 then + mr, mg, mb = setLum(br, bg, bb, lum(sr, sg, sb)) + end + local orr, og, ob, oa + if clip then + -- source-atop: the backdrop's alpha; the mixed colour where the backdrop is opaque + orr = sa * mr + (1 - sa) * br + og = sa * mg + (1 - sa) * bg + ob = sa * mb + (1 - sa) * bb + oa = ba + else + oa = sa + ba * (1 - sa) + local ws, wm, wb = sa * (1 - ba), sa * ba, (1 - sa) * ba + orr = (ws * sr + wm * mr + wb * br) / oa + og = (ws * sg + wm * mg + wb * bg) / oa + ob = (ws * sb + wm * mb + wb * bb) / oa + end + writeu8(dst, do_, floor(max(0, min(1, orr)) * 255 + 0.5)) + writeu8(dst, do_ + 1, floor(max(0, min(1, og)) * 255 + 0.5)) + writeu8(dst, do_ + 2, floor(max(0, min(1, ob)) * 255 + 0.5)) + writeu8(dst, do_ + 3, floor(max(0, min(1, oa)) * 255 + 0.5)) + end + end + end + so += 4 + do_ += 4 + end + end +end + +@native local function lerp(dst: buffer, from: buffer, t: number, n: number, w: number?, mask: any?) + if blen(dst) < n * 4 or blen(from) < n * 4 then + return + end + if mask == nil or w == nil or w <= 0 then + for i = 0, n * 4 - 1 do + local a = readu8(from, i) + writeu8(dst, i, floor(a + (readu8(dst, i) - a) * t + 0.5)) + end + return + end + local mbuf: buffer? = mask.pixels + local mw, mh = floor(tonumber(mask.width) or 0), floor(tonumber(mask.height) or 0) + local mx0, my0 = floor(tonumber(mask.x) or 0), floor(tonumber(mask.y) or 0) + local mdef = (tonumber(mask.default) or 255) / 255 + if type(mbuf) ~= "buffer" or mw <= 0 or mh <= 0 or blen(mbuf) < mw * mh then + mbuf = nil + end + for p = 0, n - 1 do + local px, py = p % w, p // w + local mv = mdef + local mxx, myy = px - mx0, py - my0 + if mbuf ~= nil and mxx >= 0 and myy >= 0 and mxx < mw and myy < mh then + mv = readu8(mbuf, myy * mw + mxx) / 255 + end + local tt = t * mv + local o = p * 4 + for k = o, o + 3 do + local a = readu8(from, k) + writeu8(dst, k, floor(a + (readu8(dst, k) - a) * tt + 0.5)) + end + end +end +Blend.composite = composite +Blend.lerp = lerp + +@native local function isImage(v: any): boolean + return type(v) == "table" and v.format == "rgba8" and type(v.pixels) == "buffer" and type(v.width) == "number" and type(v.height) == "number" and buffer.len(v.pixels) >= v.width * v.height * 4 +end + +@native local function maskOf(l: any): any + local m = l.mask + if type(m) ~= "table" or m.disabled or type(m.image) ~= "table" or type(m.image.pixels) ~= "buffer" then + return nil + end + local img = m.image + local px = img.pixels + if img.format == "rgba8" then + local n = img.width * img.height + local g = buffer.create(n) + for i = 0, n - 1 do + buffer.writeu8(g, i, buffer.readu8(px, i * 4)) + end + px = g + end + return { pixels = px, width = img.width, height = img.height, x = m.x or 0, y = m.y or 0, default = m.default or 255 } +end + +@native local function compose(layers: { any }, canvas: buffer, w: number, h: number, hidden: boolean) + local i = 1 + while i <= #layers do + local l = layers[i] + i += 1 + if type(l) ~= "table" or (l.visible == false and not hidden) then + -- clipped layers above a hidden base are hidden too + while i <= #layers and type(layers[i]) == "table" and layers[i].clip do + i += 1 + end + continue + end + local opacity = (tonumber(l.opacity) or 1) * (tonumber(l.fillOpacity) or 1) + local mode = if type(l.blend) == "string" then l.blend else "normal" + local src: buffer? = nil + if type(l.children) == "table" then + if mode == "passThrough" then + local before = buffer.create(w * h * 4) + buffer.copy(before, 0, canvas, 0, w * h * 4) + compose(l.children, canvas, w, h, hidden) + -- the group's opacity and mask limit how much of its effect reaches the canvas (as in Photoshop) + local gm = maskOf(l) + if opacity < 1 or gm ~= nil then + lerp(canvas, before, opacity, w * h, w, gm) + end + continue + end + src = buffer.create(w * h * 4) + compose(l.children, src :: buffer, w, h, hidden) + elseif isImage(l.image) then + if l.image.width > 0 and l.image.height > 0 then + local b = buffer.create(w * h * 4) + composite(b, w, h, l.image.pixels, l.image.width, l.image.height, tonumber(l.x) or 0, tonumber(l.y) or 0, 1, "normal") + src = b + end + end + -- clipping layers above this one: composited onto it with their alpha limited to it + while i <= #layers and type(layers[i]) == "table" and layers[i].clip do + local c = layers[i] + i += 1 + if src and (c.visible ~= false or hidden) and isImage(c.image) then + composite(src :: buffer, w, h, c.image.pixels, c.image.width, c.image.height, tonumber(c.x) or 0, tonumber(c.y) or 0, (tonumber(c.opacity) or 1) * (tonumber(c.fillOpacity) or 1), c.blend, { clip = true, mask = maskOf(c) }) + end + end + if src then + composite(canvas, w, h, src :: buffer, w, h, 0, 0, opacity, mode, { mask = maskOf(l) }) + end + end +end + +@native function Blend.flatten(layers: { any }, canvas: buffer, w: number, h: number, hidden: boolean) + if blen(canvas) >= w * h * 4 then + compose(layers, canvas, w, h, hidden) + end +end + +return Blend +end +__FILES["codecs/image/Etc"] = @native function() + + + +-- codecs/image/Etc: ETC1 / ETC2 / EAC block texture decoding (Khronos Data Format Specification 1.3, section 21). +-- New in rosetta. Signed EAC values are biased into rgba8 (-1 -> 1, 0 -> 128, +1 -> 255). +local Etc = {} + +Etc.BLOCK = table.freeze({ etc1 = 8, etc2_rgb = 8, etc2_rgba = 16, etc2_rgba1 = 8, eac_r11 = 8, eac_r11s = 8, eac_rg11 = 16, eac_rg11s = 16 }) :: { [string]: number } + +local readu8, readu32, writeu8, writeu16, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu8, buffer.writeu16, buffer.writeu32 +local band, rshift, byteswap = bit32.band, bit32.rshift, bit32.byteswap + +local MOD = { -- the ETC1 intensity modifiers per table: index (msb * 2 + lsb) -> a, b, -a, -b + { 2, 8, -2, -8 }, + { 5, 17, -5, -17 }, + { 9, 29, -9, -29 }, + { 13, 42, -13, -42 }, + { 18, 60, -18, -60 }, + { 24, 80, -24, -80 }, + { 33, 106, -33, -106 }, + { 47, 183, -47, -183 }, +} +local DIST = { 3, 6, 11, 16, 23, 32, 41, 64 } -- T / H mode distances +local EAC = { + { -3, -6, -9, -15, 2, 5, 8, 14 }, + { -3, -7, -10, -13, 2, 6, 9, 12 }, + { -2, -5, -8, -13, 1, 4, 7, 12 }, + { -2, -4, -6, -13, 1, 3, 5, 12 }, + { -3, -6, -8, -12, 2, 5, 7, 11 }, + { -3, -7, -9, -11, 2, 6, 8, 10 }, + { -4, -7, -8, -11, 3, 6, 7, 10 }, + { -3, -5, -8, -11, 2, 4, 7, 10 }, + { -2, -6, -8, -10, 1, 5, 7, 9 }, + { -2, -5, -8, -10, 1, 4, 7, 9 }, + { -2, -4, -8, -10, 1, 3, 7, 9 }, + { -2, -5, -7, -10, 1, 4, 6, 9 }, + { -3, -4, -7, -10, 2, 3, 6, 9 }, + { -1, -2, -3, -10, 0, 1, 2, 9 }, + { -4, -6, -8, -9, 3, 5, 7, 8 }, + { -3, -5, -7, -9, 2, 4, 6, 8 }, +} + +@native local function clamp8(v: number): number + return if v < 0 then 0 elseif v > 255 then 255 else v +end +@native local function rgb(r: number, g: number, b: number): number + return clamp8(r) + clamp8(g) * 256 + clamp8(b) * 65536 + 0xFF000000 +end + +-- blk: 16 u32 rgba8 pixels in raster order (y * 4 + x) +local P = table.create(4, 0) + +@native local function be32(src: buffer, p: number): number + return byteswap(readu32(src, p)) +end + +-- the 2-bit pixel index of pixel i (column-major: i = x * 4 + y) +@native local function pix(lo: number, i: number): number + return band(rshift(lo, i + 15), 2) + band(rshift(lo, i), 1) +end + +-- ETC1 / ETC2 colour block; the RGB A1 variant: bit 33 = opaque +@native local function colour(src: buffer, p: number, blk: buffer, etc2: boolean, punch: boolean) + local hi, lo = be32(src, p), be32(src, p + 4) + local diffBit = band(rshift(hi, 1), 1) + local flip = band(hi, 1) + local opaque = not punch or diffBit == 1 + local r1, g1, b1, r2, g2, b2 + if not punch and diffBit == 0 then + r1, r2 = band(rshift(hi, 28), 15) * 17, band(rshift(hi, 24), 15) * 17 + g1, g2 = band(rshift(hi, 20), 15) * 17, band(rshift(hi, 16), 15) * 17 + b1, b2 = band(rshift(hi, 12), 15) * 17, band(rshift(hi, 8), 15) * 17 + else + local R, G, B = band(rshift(hi, 27), 31), band(rshift(hi, 19), 31), band(rshift(hi, 11), 31) + local dR, dG, dB = band(rshift(hi, 24), 7), band(rshift(hi, 16), 7), band(rshift(hi, 8), 7) + if dR >= 4 then + dR -= 8 + end + if dG >= 4 then + dG -= 8 + end + if dB >= 4 then + dB -= 8 + end + local R2, G2, B2 = R + dR, G + dG, B + dB + if etc2 and (R2 < 0 or R2 > 31) then + -- T mode + local ra = band(rshift(hi, 27), 3) * 4 + band(rshift(hi, 24), 3) + local c1r, c1g, c1b = ra * 17, band(rshift(hi, 20), 15) * 17, band(rshift(hi, 16), 15) * 17 + local c2r, c2g, c2b = band(rshift(hi, 12), 15) * 17, band(rshift(hi, 8), 15) * 17, band(rshift(hi, 4), 15) * 17 + local d = DIST[band(rshift(hi, 2), 3) * 2 + band(hi, 1) + 1] + P[1] = rgb(c1r, c1g, c1b) + P[2] = rgb(c2r + d, c2g + d, c2b + d) + P[3] = rgb(c2r, c2g, c2b) + P[4] = rgb(c2r - d, c2g - d, c2b - d) + elseif etc2 and (G2 < 0 or G2 > 31) then + -- H mode + local q1r = band(rshift(hi, 27), 15) + local q1g = band(rshift(hi, 24), 7) * 2 + band(rshift(hi, 20), 1) + local q1b = band(rshift(hi, 19), 1) * 8 + band(rshift(hi, 15), 7) + local q2r, q2g, q2b = band(rshift(hi, 11), 15), band(rshift(hi, 7), 15), band(rshift(hi, 3), 15) + local order = if q1r * 256 + q1g * 16 + q1b >= q2r * 256 + q2g * 16 + q2b then 1 else 0 + local d = DIST[band(rshift(hi, 2), 1) * 4 + band(hi, 1) * 2 + order + 1] + local c1r, c1g, c1b, c2r, c2g, c2b = q1r * 17, q1g * 17, q1b * 17, q2r * 17, q2g * 17, q2b * 17 + P[1] = rgb(c1r + d, c1g + d, c1b + d) + P[2] = rgb(c1r - d, c1g - d, c1b - d) + P[3] = rgb(c2r + d, c2g + d, c2b + d) + P[4] = rgb(c2r - d, c2g - d, c2b - d) + elseif etc2 and (B2 < 0 or B2 > 31) then + -- planar (always opaque) + local ro = band(rshift(hi, 25), 63) + local go = band(rshift(hi, 24), 1) * 64 + band(rshift(hi, 17), 63) + local bo = band(rshift(hi, 16), 1) * 32 + band(rshift(hi, 11), 3) * 8 + band(rshift(hi, 7), 7) + local rh = band(rshift(hi, 2), 31) * 2 + band(hi, 1) + local gh, bh = band(rshift(lo, 25), 127), band(rshift(lo, 19), 63) + local rv, gv, bv = band(rshift(lo, 13), 63), band(rshift(lo, 6), 127), band(lo, 63) + ro, rh, rv = ro * 4 + rshift(ro, 4), rh * 4 + rshift(rh, 4), rv * 4 + rshift(rv, 4) + go, gh, gv = go * 2 + rshift(go, 6), gh * 2 + rshift(gh, 6), gv * 2 + rshift(gv, 6) + bo, bh, bv = bo * 4 + rshift(bo, 4), bh * 4 + rshift(bh, 4), bv * 4 + rshift(bv, 4) + for y = 0, 3 do + for x = 0, 3 do + local r = (x * (rh - ro) + y * (rv - ro) + 4 * ro + 2) // 4 + local g = (x * (gh - go) + y * (gv - go) + 4 * go + 2) // 4 + local b = (x * (bh - bo) + y * (bv - bo) + 4 * bo + 2) // 4 + writeu32(blk, (y * 4 + x) * 4, rgb(r, g, b)) + end + end + return + else + r1, g1, b1 = R * 8 + rshift(R, 2), G * 8 + rshift(G, 2), B * 8 + rshift(B, 2) + r2, g2, b2 = R2 * 8 + rshift(R2, 2), G2 * 8 + rshift(G2, 2), B2 * 8 + rshift(B2, 2) + end + if not r1 then + for i = 0, 15 do + local x, y = rshift(i, 2), band(i, 3) + local idx = pix(lo, i) + local c = if not opaque and idx == 2 then 0 else P[idx + 1] + writeu32(blk, (y * 4 + x) * 4, c) + end + return + end + end + local t1, t2 = MOD[band(rshift(hi, 5), 7) + 1], MOD[band(rshift(hi, 2), 7) + 1] + for i = 0, 15 do + local x, y = rshift(i, 2), band(i, 3) + local second = if flip == 0 then x >= 2 else y >= 2 + local idx = pix(lo, i) + local c + if not opaque and idx == 2 then + c = 0 + else + local m = if second then t2[idx + 1] else t1[idx + 1] + if not opaque and idx == 0 then + m = 0 + end + if second then + c = rgb((r2 :: number) + m, (g2 :: number) + m, (b2 :: number) + m) + else + c = rgb((r1 :: number) + m, (g1 :: number) + m, (b1 :: number) + m) + end + end + writeu32(blk, (y * 4 + x) * 4, c) + end +end + +local VALS = table.create(16, 0) + +@native local function eac(src: buffer, p: number, mode: string) + local base = readu8(src, p) + local b1 = readu8(src, p + 1) + local mult, tab = rshift(b1, 4), EAC[band(b1, 15) + 1] + -- 48 index bits, pixel 0 (column-major) first: bytes 2..7 big-endian, as 24 + 24 bits + local hiIdx = readu8(src, p + 2) * 65536 + readu8(src, p + 3) * 256 + readu8(src, p + 4) + local loIdx = readu8(src, p + 5) * 65536 + readu8(src, p + 6) * 256 + readu8(src, p + 7) + if mode == "s11" then + if base >= 128 then + base -= 256 + end + if base == -128 then + base = -127 + end + end + for i = 0, 15 do + local idx = if i < 8 then band(rshift(hiIdx, 21 - i * 3), 7) else band(rshift(loIdx, 21 - (i - 8) * 3), 7) + local m = tab[idx + 1] + local v + if mode == "alpha" then + v = clamp8(base + m * mult) + elseif mode == "u11" then + v = if mult == 0 then base * 8 + 4 + m else base * 8 + 4 + m * mult * 8 + v = if v < 0 then 0 elseif v > 2047 then 2047 else v + else + v = if mult == 0 then base * 8 + m else base * 8 + m * mult * 8 + v = if v < -1023 then -1023 elseif v > 1023 then 1023 else v + end + VALS[band(i, 3) * 4 + rshift(i, 2) + 1] = v + end +end + +@native local function to8(v: number, signed: boolean): number + if signed then + return math.floor(v * 127 / 1023 + 0.5) + 128 + end + return math.floor(v * 255 / 2047 + 0.5) +end +@native local function to16(v: number, signed: boolean): number + if signed then + return math.floor((v + 1023) * 65535 / 2046 + 0.5) + end + return v * 32 + rshift(v, 6) +end + +@native function Etc.size(kind: string, w: number, h: number): number? + local b = Etc.BLOCK[kind] + return if b then ((w + 3) // 4) * ((h + 3) // 4) * b else nil +end + +@native function Etc.decode(kind: string, src: buffer, offset: number, w: number, h: number, out: buffer?, outOffset: number?, wide: boolean?): (buffer?, string?) + local bytes = Etc.BLOCK[kind] + if not bytes then + return nil, "unsupported: unknown block format " .. tostring(kind) + end + if w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 then + return nil, "bad image size" + end + local need = Etc.size(kind, w, h) :: number + if offset < 0 or offset + need > buffer.len(src) then + return nil, "truncated: block data runs past the end" + end + local isEac = string.sub(kind, 1, 3) == "eac" + local w16 = isEac and wide == true + local bpp = if w16 then 8 else 4 + local oo = outOffset or 0 + local dst = out or buffer.create(w * h * bpp) + if oo + w * h * bpp > buffer.len(dst) then + return nil, "output buffer too small" + end + local signed = kind == "eac_r11s" or kind == "eac_rg11s" + local two = kind == "eac_rg11" or kind == "eac_rg11s" + local mode11 = if signed then "s11" else "u11" + local etc2 = kind ~= "etc1" + local punch = kind == "etc2_rgba1" + local blk = buffer.create(16 * bpp) + local bw, bh = (w + 3) // 4, (h + 3) // 4 + local p = offset + local rowBytes = w * bpp + for by = 0, bh - 1 do + local rows = math.min(4, h - by * 4) + for bx = 0, bw - 1 do + if isEac then + eac(src, p, mode11) + for i = 0, 15 do + local v = VALS[i + 1] + if w16 then + local q = to16(v, signed) + writeu16(blk, i * 8, q) + writeu16(blk, i * 8 + 2, if two then 0 else q) + writeu16(blk, i * 8 + 4, if two then 0 else q) + writeu16(blk, i * 8 + 6, 65535) + else + local q = to8(v, signed) + writeu32(blk, i * 4, if two then q + 0xFF000000 else q + q * 256 + q * 65536 + 0xFF000000) + end + end + if two then + eac(src, p + 8, mode11) + for i = 0, 15 do + local v = VALS[i + 1] + if w16 then + writeu16(blk, i * 8 + 2, to16(v, signed)) + else + writeu8(blk, i * 4 + 1, to8(v, signed)) + end + end + end + elseif kind == "etc2_rgba" then + colour(src, p + 8, blk, true, false) + eac(src, p, "alpha") + for i = 0, 15 do + writeu8(blk, i * 4 + 3, VALS[i + 1]) + end + else + colour(src, p, blk, etc2, punch) + end + p += bytes + local cols = math.min(4, w - bx * 4) + local base = oo + (by * 4) * rowBytes + bx * 4 * bpp + for y = 0, rows - 1 do + buffer.copy(dst, base + y * rowBytes, blk, y * 4 * bpp, cols * bpp) + end + end + end + return dst, nil +end + +return Etc +end +__FILES["codecs/image/Half"] = @native function() + + + +-- codecs/image/Half: IEEE 754 binary16 <-> number (round to nearest even, overflow to infinity). New in rosetta. +local Half = {} + +local band, bor, rshift, lshift = bit32.band, bit32.bor, bit32.rshift, bit32.lshift + +@native local function toFloat(h: number): number + local s = if h >= 32768 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 * (1024 + m) * 2 ^ (e - 25) +end +Half.toFloat = toFloat + +local TABLE: { [number]: number } = table.create(65536, 0) +for h = 0, 65535 do + TABLE[h] = toFloat(h) +end +Half.TABLE = TABLE + +local scratch = buffer.create(4) + +@native function Half.fromFloat(f: number): number + if f ~= f then + return 0x7E00 + end + buffer.writef32(scratch, 0, f) + local x = buffer.readu32(scratch, 0) + local sign = band(rshift(x, 16), 0x8000) + local e = band(rshift(x, 23), 0xFF) + local m = band(x, 0x7FFFFF) + if e == 255 then + return bor(sign, 0x7C00) + end + local ne = e - 112 + if ne >= 31 then + return bor(sign, 0x7C00) + elseif ne <= 0 then + if ne < -10 then + return sign + end + m = bor(m, 0x800000) + local shift = 14 - ne + local hm = rshift(m, shift) + local rem = band(m, lshift(1, shift) - 1) + local halfway = lshift(1, shift - 1) + if rem > halfway or (rem == halfway and band(hm, 1) == 1) then + hm += 1 + end + return sign + hm + end + local hm = rshift(m, 13) + local rem = band(m, 0x1FFF) + if rem > 0x1000 or (rem == 0x1000 and band(hm, 1) == 1) then + hm += 1 -- a carry out of the mantissa bumps the exponent (up to infinity), as it should + end + return sign + ne * 1024 + hm +end + +return Half +end +__FILES["codecs/image/Pixels"] = @native function() + + + +-- codecs/image/Pixels: row loops between packed pixel layouts and rgba8 for BMP / DIB. +-- Indexed, BGR(A), 5-5-5, bit masks, RLE4 / RLE8. From bmp-luau b86aed6 (same author); the encoder loops are new. +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 + +local Pixels = {} + +@native function Pixels.palette(src: buffer, base: number, n: number, bgr: boolean?): buffer + local pal = buffer.create(1024) + local m = if base >= 0 then math.clamp(math.min(n, (buffer.len(src) - base) // 3), 0, 256) else 0 + for i = 0, 255 do + local v = 0xFF000000 + if i < m then + local o = base + i * 3 + local r, g, b = readu8(src, o), readu8(src, o + 1), readu8(src, o + 2) + if bgr then + r, b = b, r + end + v = bor(0xFF000000, lshift(b, 16), lshift(g, 8), r) + end + writeu32(pal, i * 4, v) + end + return pal +end + +@native function Pixels.indexed(src: buffer, base: number, stride: number, bpp: number, dst: buffer, w: number, h: number, + topDown: boolean, pal: buffer) + local mask = lshift(1, bpp) - 1 + for r = 0, h - 1 do + local so = base + r * stride + local d = (if topDown then r else h - 1 - r) * w * 4 + if bpp == 8 then + for x = 0, w - 1 do + writeu32(dst, d + x * 4, readu32(pal, readu8(src, so + x) * 4)) + end + elseif bpp == 4 then + for x = 0, w - 1 do + local b = readu8(src, so + rshift(x, 1)) + local i = if band(x, 1) == 0 then rshift(b, 4) else band(b, 15) + writeu32(dst, d + x * 4, readu32(pal, i * 4)) + end + else + for x = 0, w - 1 do + local bit = x * bpp + local b = readu8(src, so + rshift(bit, 3)) + local i = band(rshift(b, 8 - bpp - band(bit, 7)), mask) + writeu32(dst, d + x * 4, readu32(pal, i * 4)) + end + end + 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 +@native 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 +@native function Pixels.bgr24(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 = so + x * 3 + writeu32(dst, d + x * 4, + bor(readu8(src, s + 2), lshift(readu8(src, s + 1), 8), lshift(readu8(src, s), 16), 0xFF000000)) + end + end +end + +-- 32 bpp B, G, R, A (BI_RGB, or BITFIELDS with the standard masks) +@native function Pixels.bgra32(src: buffer, base: number, stride: number, dst: buffer, w: number, h: number, + topDown: boolean): number + local aor = 0 + 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 p = readu32(src, so + x * 4) + writeu32(dst, d + x * 4, bor(band(p, 0xFF00FF00), band(rshift(p, 16), 0xFF), lshift(band(p, 0xFF), 16))) + aor = bor(aor, p) + end + end + return rshift(aor, 24) +end + +@native function Pixels.masked(src: buffer, base: number, stride: number, bpp: number, dst: buffer, w: number, h: number, + topDown: boolean, shr: number, mr: number, tr: buffer, shg: number, mg: number, tg: buffer, shb: number, + mb: number, tb: buffer, sha: number, ma: number, ta: buffer): number + local bytes = rshift(bpp, 3) + local aor = 0 + 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 = so + x * bytes + local p + if bytes == 2 then + p = readu16(src, s) + elseif bytes == 4 then + p = readu32(src, s) + else + p = bor(readu16(src, s), lshift(readu8(src, s + 2), 16)) + end + local a = band(rshift(p, sha), ma) + aor = bor(aor, a) + local o = d + x * 4 + writeu8(dst, o, readu8(tr, band(rshift(p, shr), mr))) + writeu8(dst, o + 1, readu8(tg, band(rshift(p, shg), mg))) + writeu8(dst, o + 2, readu8(tb, band(rshift(p, shb), mb))) + writeu8(dst, o + 3, readu8(ta, a)) + end + end + return aor +end + +-- 32-bit images whose alpha channel is all zero are opaque +@native function Pixels.opaque(dst: buffer, n: number) + for i = 0, n - 1 do + writeu8(dst, i * 4 + 3, 255) + end +end + +-- RLE8 / RLE4: pixels skipped by a delta or an early end of line / bitmap stay transparent +@native function Pixels.rle(src: buffer, pos: number, stop: number, rle4: boolean, dst: buffer, w: number, h: number, + topDown: boolean, pal: buffer): number + local x, y = 0, 0 + local written = 0 + local row = (if topDown then 0 else h - 1) * w * 4 + local rowStep = if topDown then w * 4 else -w * 4 + while y < h and pos + 1 < stop do + local n = readu8(src, pos) + local v = readu8(src, pos + 1) + pos += 2 + if n > 0 then + -- encoded run: n pixels of index v (RLE4: alternating high / low nibble) + local e = math.min(x + n, w) + if rle4 then + local hi, lo = readu32(pal, rshift(v, 4) * 4), readu32(pal, band(v, 15) * 4) + for i = x, e - 1 do + writeu32(dst, row + i * 4, if band(i - x, 1) == 0 then hi else lo) + end + else + local c = readu32(pal, v * 4) + for i = x, e - 1 do + writeu32(dst, row + i * 4, c) + end + end + if e > x then + written += e - x + end + x += n + elseif v == 0 then + -- end of line + x = 0 + y += 1 + row += rowStep + elseif v == 1 then + break -- end of bitmap + elseif v == 2 then + -- delta: right dx, up (in file rows) dy + if pos + 1 >= stop then + break + end + local dx, dy = readu8(src, pos), readu8(src, pos + 1) + pos += 2 + x += dx + y += dy + row += rowStep * dy + else + -- absolute run of v pixels, padded to a 16-bit boundary + local nb = if rle4 then rshift(v + 1, 1) else v + if pos + nb > stop then + break + end + local e = math.min(x + v, w) + for i = x, e - 1 do + local k = i - x + local idx + if rle4 then + local b = readu8(src, pos + rshift(k, 1)) + idx = if band(k, 1) == 0 then rshift(b, 4) else band(b, 15) + else + idx = readu8(src, pos + k) + end + writeu32(dst, row + i * 4, readu32(pal, idx * 4)) + end + if e > x then + written += e - x + end + x += v + pos += nb + band(nb, 1) + end + end + return written +end + +@native function Pixels.encode24(src: buffer, w: number, h: number, dst: buffer, base: number, stride: number) + for y = 0, h - 1 do + local s = y * w * 4 + local d = base + (h - 1 - y) * stride + for x = 0, w - 1 do + local v = readu32(src, s + x * 4) + writeu8(dst, d, band(rshift(v, 16), 255)) + writeu8(dst, d + 1, band(rshift(v, 8), 255)) + writeu8(dst, d + 2, band(v, 255)) + d += 3 + end + end +end + +@native function Pixels.encode32(src: buffer, w: number, h: number, dst: buffer, base: number) + for y = 0, h - 1 do + local s = y * w * 4 + local d = base + (h - 1 - y) * w * 4 + for x = 0, w - 1 do + local v = readu32(src, s + x * 4) + writeu32(dst, d + x * 4, bor(band(v, 0xFF00FF00), band(rshift(v, 16), 255), lshift(band(v, 255), 16))) + end + end +end + +@native function Pixels.encode8(src: buffer, w: number, h: number, dst: buffer, base: number, stride: number, idx: { [number]: number }) + for y = 0, h - 1 do + local s = y * w * 4 + local d = base + (h - 1 - y) * stride + for x = 0, w - 1 do + writeu8(dst, d + x, idx[band(readu32(src, s + x * 4), 0xFFFFFF)] or 0) + end + end +end + +@native function Pixels.colours(src: buffer, n: number, max: number): ({ number }, boolean) + local seen: { [number]: boolean } = {} + local list: { number } = {} + local alpha = false + for i = 0, n - 1 do + local v = readu32(src, i * 4) + if v < 0xFF000000 then + alpha = true + end + local c = band(v, 0xFFFFFF) + if #list <= max and not seen[c] then + seen[c] = true + list[#list + 1] = c + end + end + return list, alpha +end + +return Pixels +end +__FILES["codecs/image/Quantize"] = @native function() + + + +-- codecs/image/Quantize: palette quantization of rgba8 pixels (median cut or octree, Floyd-Steinberg dithering). +-- New in rosetta: Heckbert's median cut and the Gervautz-Purgathofer octree over a 5-bit-per-channel histogram; +-- deterministic on every runtime (no table iteration order is relied on). +local readu8, writeu8 = buffer.readu8, buffer.writeu8 +local readu32, writeu32, readf64, writef64 = buffer.readu32, buffer.writeu32, buffer.readf64, buffer.writef64 +local floor = math.floor +local blen = buffer.len + +local Quantize = {} + +type Color = { number } +type PaletteOptions = { + method: ("mediancut" | "octree")?, +} +type MapOptions = { + dither: boolean?, + transparentIndex: number?, +} + +local BINS = 32768 -- 5 bits per channel + +@native local function count(pixels: buffer, n: number): (buffer, buffer) + -- per bin: u32 count; f64 sums of r, g, b + local cnt = buffer.create(BINS * 4) + local sums = buffer.create(BINS * 24) + for i = 0, n - 1 do + local o = i * 4 + if readu8(pixels, o + 3) >= 128 then + local r, g, b = readu8(pixels, o), readu8(pixels, o + 1), readu8(pixels, o + 2) + local bin = (r // 8) * 1024 + (g // 8) * 32 + b // 8 + writeu32(cnt, bin * 4, readu32(cnt, bin * 4) + 1) + local s = bin * 24 + writef64(sums, s, readf64(sums, s) + r) + writef64(sums, s + 8, readf64(sums, s + 8) + g) + writef64(sums, s + 16, readf64(sums, s + 16) + b) + end + end + return cnt, sums +end + +@native local function mean(cnt: buffer, sums: buffer, bins: { number }, lo: number, hi: number): Color + local n, r, g, b = 0, 0, 0, 0 + for i = lo, hi do + local bin = bins[i] + n += readu32(cnt, bin * 4) + r += readf64(sums, bin * 24) + g += readf64(sums, bin * 24 + 8) + b += readf64(sums, bin * 24 + 16) + end + if n == 0 then + return { 0, 0, 0, 255 } + end + return { floor(r / n + 0.5), floor(g / n + 0.5), floor(b / n + 0.5), 255 } +end + +@native local function medianCut(cnt: buffer, sums: buffer, maxColors: number): { Color } + local bins: { number } = {} + for bin = 0, BINS - 1 do + if readu32(cnt, bin * 4) > 0 then + table.insert(bins, bin) + end + end + if #bins == 0 then + return {} + end + local boxes: { { number } } = {} + @native local function channel(bin: number, c: number): number + if c == 0 then + return bin // 1024 + elseif c == 1 then + return (bin // 32) % 32 + end + return bin % 32 + end + @native local function stats(box: { number }): (number, number, number) + local mins, maxs = { 31, 31, 31 }, { 0, 0, 0 } + local n = 0 + for i = box[1], box[2] do + local bin = bins[i] + n += readu32(cnt, bin * 4) + for c = 0, 2 do + local v = channel(bin, c) + if v < mins[c + 1] then + mins[c + 1] = v + end + if v > maxs[c + 1] then + maxs[c + 1] = v + end + end + end + local best, range = 0, -1 + for c = 0, 2 do + local rg = maxs[c + 1] - mins[c + 1] + if rg > range then + best, range = c, rg + end + end + return best, range, n + end + @native local function scored(lo: number, hi: number): { number } + local c, range, n = stats({ lo, hi }) + return { lo, hi, c, if hi > lo then range * math.sqrt(n) else 0 } + end + boxes[1] = scored(1, #bins) + while #boxes < maxColors do + -- split the box with the largest range * sqrt(count) score (ties: the first) + local pick, pickScore = 0, 0 + for i, box in boxes do + if box[4] > pickScore then + pick, pickScore = i, box[4] + end + end + if pick == 0 then + break + end + 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) :: { number } + for i = lo, hi do + keys[i - lo + 1] = channel(bins[i], c) * BINS + bins[i] + end + table.sort(keys) + local total = 0 + for i = 1, #keys do + local bin = keys[i] % BINS + bins[lo + i - 1] = bin + total += readu32(cnt, bin * 4) + end + -- the weighted median, keeping both halves non-empty + local acc, cut = 0, lo + for i = lo, hi - 1 do + acc += readu32(cnt, bins[i] * 4) + cut = i + if acc * 2 >= total then + break + end + end + boxes[pick] = scored(lo, cut) + table.insert(boxes, scored(cut + 1, hi)) + end + local pal = table.create(#boxes) :: { Color } + for i, box in boxes do + pal[i] = mean(cnt, sums, bins, box[1], box[2]) + end + return pal +end + +-- octree over the histogram bins: 5 levels, one bit of each channel per level +@native local function octree(cnt: buffer, sums: buffer, maxColors: number): { Color } + local child: { number } = {} -- node * 8 + k -> node (0 = none) + local n: { number } = {} + local sr: { number }, sg: { number }, sb: { number } = {}, {}, {} + local leaf: { boolean } = {} + local level: { number } = {} + local nodes = 1 + n[1], sr[1], sg[1], sb[1], leaf[1], level[1] = 0, 0, 0, 0, false, 0 + for k = 1, 8 do + child[k] = 0 + end + local byLevel: { { number } } = { {}, {}, {}, {}, {} } + table.insert(byLevel[1], 1) + local leaves = 0 + for bin = 0, BINS - 1 do + local c = readu32(cnt, bin * 4) + if c > 0 then + local r5, g5, b5 = bin // 1024, (bin // 32) % 32, bin % 32 + local node = 1 + for lv = 0, 4 do + local sh = 4 - lv + local k = ((r5 // 2 ^ sh) % 2) * 4 + ((g5 // 2 ^ sh) % 2) * 2 + (b5 // 2 ^ sh) % 2 + local slot = (node - 1) * 8 + k + 1 + local nx = child[slot] + if nx == 0 then + nodes += 1 + nx = nodes + child[slot] = nx + for j = 1, 8 do + child[(nx - 1) * 8 + j] = 0 + end + n[nx], sr[nx], sg[nx], sb[nx], level[nx] = 0, 0, 0, 0, lv + 1 + leaf[nx] = lv == 4 + if lv == 4 then + leaves += 1 + else + table.insert(byLevel[lv + 2], nx) + end + end + node = nx + end + n[node] += c + sr[node] += readf64(sums, bin * 24) + sg[node] += readf64(sums, bin * 24 + 8) + sb[node] += readf64(sums, bin * 24 + 16) + end + end + -- fold the deepest inner nodes (fewest pixels first, ties by creation order) until few enough leaves remain + @native local function fold(node: number): number + local merged = 0 + for k = 1, 8 do + local slot = (node - 1) * 8 + k + local ch = child[slot] + if ch ~= 0 then + n[node] += n[ch] + sr[node] += sr[ch] + sg[node] += sg[ch] + sb[node] += sb[ch] + child[slot] = 0 + merged += 1 + end + end + leaf[node] = true + return merged - 1 + end + @native local function subtotal(node: number): number + local s = 0 + for k = 1, 8 do + local ch = child[(node - 1) * 8 + k] + if ch ~= 0 then + s += n[ch] + end + end + return s + end + for lv = 5, 1, -1 do + if leaves <= maxColors then + break + end + local list = byLevel[lv] + local order = table.create(#list) :: { { any } } + for i, node in list do + order[i] = { node, subtotal(node), i } + end + table.sort(order, @native function(a: { number }, b: { number }): boolean + if a[2] ~= b[2] then + return a[2] < b[2] + end + return a[3] < b[3] + end) + for _, e in order do + if leaves <= maxColors then + break + end + leaves -= fold(e[1]) + end + end + local pal: { Color } = {} + @native local function walk(node: number) + if leaf[node] then + local c = n[node] + if c > 0 then + table.insert(pal, { floor(sr[node] / c + 0.5), floor(sg[node] / c + 0.5), floor(sb[node] / c + 0.5), 255 }) + end + return + end + for k = 1, 8 do + local ch = child[(node - 1) * 8 + k] + if ch ~= 0 then + walk(ch) + end + end + end + walk(1) + -- the root itself can end up a leaf with everything (maxColors 1) + while #pal > maxColors do + table.remove(pal) + end + return pal +end + +@native function Quantize.palette(pixels: buffer, w: number, h: number, maxColors: number, opts: PaletteOptions?): ({ Color }, boolean) + if type(pixels) ~= "buffer" or type(w) ~= "number" or type(h) ~= "number" or w < 0 or h < 0 or blen(pixels) < w * h * 4 then + return {}, false + end + local maxc = math.clamp(floor(tonumber(maxColors) or 256), 1, 65536) + local npx = w * h + local seen: { [number]: boolean } = {} + local exact: { Color } = {} + local over = false + for i = 0, npx - 1 do + local o = i * 4 + if readu8(pixels, o + 3) >= 128 then + local r, g, b = readu8(pixels, o), readu8(pixels, o + 1), readu8(pixels, o + 2) + local key = r * 65536 + g * 256 + b + if not seen[key] then + if #exact >= maxc then + over = true + break + end + seen[key] = true + table.insert(exact, { r, g, b, 255 }) + end + end + end + if not over then + return exact, true + end + local cnt, sums = count(pixels, npx) + local method = opts and opts.method or "mediancut" + if method == "octree" and maxc >= 8 then -- below 8 the octree can only fold to a single colour + return octree(cnt, sums, maxc), false + end + return medianCut(cnt, sums, maxc), false +end + +@native function Quantize.map(pixels: buffer, w: number, h: number, palette: { Color }, opts: MapOptions?): buffer + if type(pixels) ~= "buffer" or type(w) ~= "number" or type(h) ~= "number" or w < 0 or h < 0 or blen(pixels) < w * h * 4 or type(palette) ~= "table" then + return buffer.create(0) + end + local npx = w * h + local out = buffer.create(npx) + local dither = opts and opts.dither or false + local tidx = opts and opts.transparentIndex + 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) + table.insert(pg, c[2] or 0) + table.insert(pb, c[3] or 0) + table.insert(pi, i - 1) + end + end + 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) :: { number } + for k = 1, np do + order[k] = pg[k] * 65536 + k + end + table.sort(order) + 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] + end + pr, pg, pb, pi = r2, g2, b2, i2 + end + local startAt = table.create(256, np) + do + local k = 1 + for g = 0, 255 do + while k <= np and pg[k] < g do + k += 1 + end + startAt[g + 1] = k + end + end + if np == 0 then + if tidx then + buffer.fill(out, 0, math.clamp(tidx, 0, 255), npx) + end + return out + end + local cache: { [number]: number } = {} + @native local function nearest(r: number, g: number, b: number): number + local key = r * 65536 + g * 256 + b + local hit = cache[key] + if hit then + return hit + end + local best, bd = 1, math.huge + local up = startAt[math.clamp(g, 0, 255) + 1] + local down = up - 1 + while up <= np or down >= 1 do + if up <= np then + local dg = pg[up] - g + if dg * dg * 4 >= bd then + up = np + 1 + else + local dr, db = r - pr[up], b - pb[up] + local d = dr * dr * 2 + dg * dg * 4 + db * db * 3 + if d < bd then + best, bd = up, d + end + up += 1 + end + end + if down >= 1 then + local dg = g - pg[down] + if dg * dg * 4 >= bd then + down = 0 + else + local dr, db = r - pr[down], b - pb[down] + local d = dr * dr * 2 + dg * dg * 4 + db * db * 3 + if d < bd then + best, bd = down, d + end + down -= 1 + end + end + end + cache[key] = best + return best + end + local tbyte = if tidx then math.clamp(tidx, 0, 255) else 0 + if not dither then + for i = 0, npx - 1 do + local o = i * 4 + if tidx and readu8(pixels, o + 3) < 128 then + writeu8(out, i, tbyte) + else + writeu8(out, i, pi[nearest(readu8(pixels, o), readu8(pixels, o + 1), readu8(pixels, o + 2))]) + end + end + return out + end + local rowLen = (w + 2) * 24 + local cur, nxt = buffer.create(rowLen), buffer.create(rowLen) + for y = 0, h - 1 do + buffer.fill(nxt, 0, 0, rowLen) + for x = 0, w - 1 do + local i = y * w + x + local o = i * 4 + if tidx and readu8(pixels, o + 3) < 128 then + writeu8(out, i, tbyte) + else + local e = (x + 1) * 24 + local r = math.clamp(floor(readu8(pixels, o) + readf64(cur, e) + 0.5), 0, 255) + local g = math.clamp(floor(readu8(pixels, o + 1) + readf64(cur, e + 8) + 0.5), 0, 255) + local b = math.clamp(floor(readu8(pixels, o + 2) + readf64(cur, e + 16) + 0.5), 0, 255) + local k = nearest(r, g, b) + writeu8(out, i, pi[k]) + local er, eg, eb = r - pr[k], g - pg[k], b - pb[k] + -- 7/16 right, 3/16 down-left, 5/16 down, 1/16 down-right + writef64(cur, e + 24, readf64(cur, e + 24) + er * 0.4375) + writef64(cur, e + 32, readf64(cur, e + 32) + eg * 0.4375) + writef64(cur, e + 40, readf64(cur, e + 40) + eb * 0.4375) + writef64(nxt, e - 24, readf64(nxt, e - 24) + er * 0.1875) + writef64(nxt, e - 16, readf64(nxt, e - 16) + eg * 0.1875) + writef64(nxt, e - 8, readf64(nxt, e - 8) + eb * 0.1875) + writef64(nxt, e, readf64(nxt, e) + er * 0.3125) + writef64(nxt, e + 8, readf64(nxt, e + 8) + eg * 0.3125) + writef64(nxt, e + 16, readf64(nxt, e + 16) + eb * 0.3125) + writef64(nxt, e + 24, readf64(nxt, e + 24) + er * 0.0625) + writef64(nxt, e + 32, readf64(nxt, e + 32) + eg * 0.0625) + writef64(nxt, e + 40, readf64(nxt, e + 40) + eb * 0.0625) + end + end + cur, nxt = nxt, cur + end + return out +end + +@native function Quantize.quantize(pixels: buffer, w: number, h: number, maxColors: number, opts: any?): (buffer, { Color }, boolean) + local pal, exact = Quantize.palette(pixels, w, h, maxColors, opts) + local mo = opts + if exact and opts and opts.dither then + mo = table.clone(opts) + mo.dither = false + end + return Quantize.map(pixels, w, h, pal, mo), pal, exact +end + +return Quantize +end +__FILES["codecs/image/Raster"] = @native function() + + + +-- codecs/image/Raster: an antialiased scanline rasterizer (nonzero / even-odd) for line and Bézier paths, plus a stroker. +-- New code; the signed-area accumulation follows font-rs (Raph Levien, Apache-2.0 / MIT; algorithm only) and stb_truetype +-- v2, and the summed coverage a maps as FreeType does: nonzero = min(1, |a|), even-odd = |a| folded modulo 2. +local Raster = {} + +local floor, ceil, min, max, abs, sqrt = math.floor, math.ceil, math.min, math.max, math.abs, math.sqrt +local readf32, writef32, readu8, writeu8 = buffer.readf32, buffer.writef32, buffer.readu8, buffer.writeu8 +local bcreate = buffer.create + +type Cmd = { op: string, [number]: number } +type Path = { Cmd } +type Transform = { number } +type Mask = { x: number, y: number, width: number, height: number, coverage: buffer } +type Options = { + transform: Transform?, + rule: ("nonzero" | "evenodd")?, + clip: { number }?, + tolerance: number?, + maxPixels: number?, + opacity: number?, +} + +local LIMIT = 1e7 -- coordinates beyond this (device pixels) are treated as broken + +-- transforms { a, b, c, d, e, f } in SVG matrix order: x' = a x + c y + e, y' = b x + d y + f +Raster.IDENTITY = table.freeze({ 1, 0, 0, 1, 0, 0 }) + +@native function Raster.multiply(m: Transform, n: Transform): Transform + 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 +@native function Raster.translate(tx: number, ty: number): Transform + return { 1, 0, 0, 1, tx, ty } +end +@native function Raster.scale(sx: number, sy: number?): Transform + return { sx, 0, 0, sy or sx, 0, 0 } +end +@native function Raster.rotate(radians: number): Transform + local c, s = math.cos(radians), math.sin(radians) + return { c, s, -s, c, 0, 0 } +end +@native function Raster.invert(m: Transform): Transform? + local det = m[1] * m[4] - m[2] * m[3] + if det == 0 or det ~= det then + return nil + end + local id = 1 / det + local a, b, c, d = m[4] * id, -m[2] * id, -m[3] * id, m[1] * id + return { a, b, c, d, -(a * m[5] + c * m[6]), -(b * m[5] + d * m[6]) } +end +@native function Raster.apply(m: Transform, x: number, y: number): (number, number) + return m[1] * x + m[3] * y + m[5], m[2] * x + m[4] * y + m[6] +end + +local Builder = {} +Builder.__index = Builder +type Builder = typeof(setmetatable({} :: { cmds: Path }, Builder)) + +@native function Raster.path(): Builder + return setmetatable({ cmds = {} :: Path }, Builder) +end +@native function Builder.moveTo(self: Builder, x: number, y: number): Builder + table.insert(self.cmds, { op = "moveTo", x, y }) + return self +end +@native function Builder.lineTo(self: Builder, x: number, y: number): Builder + table.insert(self.cmds, { op = "lineTo", x, y }) + return self +end +@native function Builder.quadTo(self: Builder, cx: number, cy: number, x: number, y: number): Builder + table.insert(self.cmds, { op = "quadTo", cx, cy, x, y }) + return self +end +@native function Builder.cubicTo(self: Builder, c1x: number, c1y: number, c2x: number, c2y: number, x: number, y: number): Builder + table.insert(self.cmds, { op = "cubicTo", c1x, c1y, c2x, c2y, x, y }) + return self +end +@native function Builder.close(self: Builder): Builder + table.insert(self.cmds, { op = "close" } :: Cmd) + return self +end +@native function Builder.rect(self: Builder, x: number, y: number, w: number, h: number): Builder + return self:moveTo(x, y):lineTo(x + w, y):lineTo(x + w, y + h):lineTo(x, y + h):close() +end +@native function Builder.ellipse(self: Builder, cx: number, cy: number, rx: number, ry: number): Builder + local k = 0.5522847498307936 -- 4/3 (sqrt 2 - 1): cubic quarter circle + self:moveTo(cx + rx, cy) + self:cubicTo(cx + rx, cy + ry * k, cx + rx * k, cy + ry, cx, cy + ry) + self:cubicTo(cx - rx * k, cy + ry, cx - rx, cy + ry * k, cx - rx, cy) + self:cubicTo(cx - rx, cy - ry * k, cx - rx * k, cy - ry, cx, cy - ry) + self:cubicTo(cx + rx * k, cy - ry, cx + rx, cy - ry * k, cx + rx, cy) + return self:close() +end + +@native local function commands(path: any): Path? + if type(path) ~= "table" then + return nil + end + if type(path.cmds) == "table" then + return path.cmds + end + return path +end + +@native local function operands(c: any, n: number): boolean + if type(c) ~= "table" then + return false + end + for i = 1, n do + local v = c[i] + if type(v) ~= "number" or v ~= v or abs(v) > 1e15 then + return false + end + end + return true +end + +@native local function flatten(path: any, transform: Transform?, tolerance: number?, minLen: number): ({ { number } }, number?, number?, number?, number?) + local cmds = commands(path) + local polys: { { number } } = {} + if not cmds then + 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, nil, nil, nil, nil + end + local tol = tolerance or 0.1 + if type(tol) ~= "number" or not (tol > 0.001) then + tol = 0.1 + end + local cur: { number }? = nil + local px, py = 0, 0 + local sx, sy = 0, 0 + local bx0, by0, bx1, by1 = math.huge, math.huge, -math.huge, -math.huge + @native local function point(x: number, y: number) + local poly = cur :: { number } + local n = #poly + poly[n + 1] = x + poly[n + 2] = y + if x < bx0 then + bx0 = x + end + if x > bx1 then + bx1 = x + end + if y < by0 then + by0 = y + end + if y > by1 then + by1 = y + end + end + @native local function start(x: number, y: number) + if cur and #cur >= minLen then + table.insert(polys, cur) + end + cur = {} + point(x, y) + sx, sy = x, y + px, py = x, y + end + for _, cmd in cmds do + local op = if type(cmd) == "table" then cmd.op else nil + if op == "moveTo" then + if operands(cmd, 2) then + start(a * cmd[1] + c * cmd[2] + e, b * cmd[1] + d * cmd[2] + f) + end + elseif op == "lineTo" then + if operands(cmd, 2) then + if not cur then + start(px, py) + end + px, py = a * cmd[1] + c * cmd[2] + e, b * cmd[1] + d * cmd[2] + f + point(px, py) + end + elseif op == "quadTo" then + if operands(cmd, 4) then + if not cur then + start(px, py) + end + local x1, y1 = a * cmd[1] + c * cmd[2] + e, b * cmd[1] + d * cmd[2] + f + local x2, y2 = a * cmd[3] + c * cmd[4] + e, b * cmd[3] + d * cmd[4] + f + local ddx, ddy = px - 2 * x1 + x2, py - 2 * y1 + y2 + local n = ceil(sqrt(sqrt(ddx * ddx + ddy * ddy) * 0.25 / tol)) + n = if n ~= n then 1 else max(1, min(n, 500)) + local x0, y0 = px, py + for i = 1, n - 1 do + local t = i / n + local u = 1 - t + point(u * u * x0 + 2 * u * t * x1 + t * t * x2, u * u * y0 + 2 * u * t * y1 + t * t * y2) + end + point(x2, y2) + px, py = x2, y2 + end + elseif op == "cubicTo" then + if operands(cmd, 6) then + if not cur then + start(px, py) + end + local x1, y1 = a * cmd[1] + c * cmd[2] + e, b * cmd[1] + d * cmd[2] + f + local x2, y2 = a * cmd[3] + c * cmd[4] + e, b * cmd[3] + d * cmd[4] + f + local x3, y3 = a * cmd[5] + c * cmd[6] + e, b * cmd[5] + d * cmd[6] + f + local ax, ay = px - 2 * x1 + x2, py - 2 * y1 + y2 + local bxx, byy = x1 - 2 * x2 + x3, y1 - 2 * y2 + y3 + local dd = max(sqrt(ax * ax + ay * ay), sqrt(bxx * bxx + byy * byy)) + local n = ceil(sqrt(dd * 0.75 / tol)) + n = if n ~= n then 1 else max(1, min(n, 500)) + local x0, y0 = px, py + for i = 1, n - 1 do + local t = i / n + local u = 1 - t + local w0, w1, w2, w3 = u * u * u, 3 * u * u * t, 3 * u * t * t, t * t * t + point(w0 * x0 + w1 * x1 + w2 * x2 + w3 * x3, w0 * y0 + w1 * y1 + w2 * y2 + w3 * y3) + end + point(x3, y3) + px, py = x3, y3 + end + elseif op == "close" then + if cur then + if #cur >= minLen then + table.insert(polys, cur) + end + cur = nil + px, py = sx, sy + end + end + end + if cur and #cur >= minLen then + table.insert(polys, cur) + end + if #polys == 0 or bx0 ~= bx0 or by0 ~= by0 or bx1 ~= bx1 or by1 ~= by1 then + return polys, nil, nil, nil, nil + end + return polys, bx0, by0, bx1, by1 +end + +@native function Raster.flatten(path: any, transform: Transform?, tolerance: number?): ({ { number } }, number?, number?, number?, number?) + return flatten(path, transform, tolerance, 6) +end + +-- the signed area each pixel gains from one edge (font-rs draw_line) +@native local function line(acc: buffer, S: number, H: number, x0: number, y0: number, x1: number, y1: number) + if y0 == y1 then + return + end + local W = S - 2 + local xl, xr = 0, W -- x stays in [0, W] (rounding in the splits and in x + dxdy * dy must never index outside) + local dir = 1 + if y0 > y1 then + dir = -1 + x0, x1 = x1, x0 + y0, y1 = y1, y0 + end + if y1 <= 0 or y0 >= H then + return + end + local dxdy = (x1 - x0) / (y1 - y0) + local x = x0 + if y0 < 0 then + x -= y0 * dxdy + end + local ystart = max(0, floor(y0)) + local yend = min(H, ceil(y1)) - 1 + for y = ystart, yend do + local ls = y * S + local dy = min(y + 1, y1) - max(y, y0) + local xnext = x + dxdy * dy + if xnext < xl then + xnext = xl + elseif xnext > xr then + xnext = xr + end + if x < xl then + x = xl + elseif x > xr then + x = xr + end + local dd = dy * dir + local xa, xb = x, xnext + if xa > xb then + xa, xb = xb, xa + end + local xaf = floor(xa) + local xai = xaf + local xbc = ceil(xb) + local xbi = xbc + if xbi <= xai + 1 then + local xmf = 0.5 * (x + xnext) - xaf + local o = (ls + xai) * 4 + writef32(acc, o, readf32(acc, o) + dd - dd * xmf) + writef32(acc, o + 4, readf32(acc, o + 4) + dd * xmf) + else + local s = 1 / (xb - xa) + local x0f = xa - xaf + local a0 = 0.5 * s * (1 - x0f) * (1 - x0f) + local x1f = xb - xbc + 1 + local am = 0.5 * s * x1f * x1f + local o = (ls + xai) * 4 + writef32(acc, o, readf32(acc, o) + dd * a0) + if xbi == xai + 2 then + writef32(acc, o + 4, readf32(acc, o + 4) + dd * (1 - a0 - am)) + else + local a1 = s * (1.5 - x0f) + writef32(acc, o + 4, readf32(acc, o + 4) + dd * (a1 - a0)) + local ds = dd * s + for xi = xai + 2, xbi - 2 do + local q = (ls + xi) * 4 + writef32(acc, q, readf32(acc, q) + ds) + end + local a2 = a1 + (xbi - xai - 3) * s + local q = (ls + xbi - 1) * 4 + writef32(acc, q, readf32(acc, q) + dd * (1 - a2 - am)) + end + local q = (ls + xbi) * 4 + writef32(acc, q, readf32(acc, q) + dd * am) + end + x = xnext + end +end + +-- edges split at x = 0 / x = W: the parts outside go onto the border, whose cover still applies to the row +@native local function clampx(x: number, W: number): number + return if x < 0 then 0 elseif x > W then W else x +end +@native local function edge(acc: buffer, S: number, W: number, H: number, x0: number, y0: number, x1: number, y1: number) + if y0 == y1 or not (abs(x0) < LIMIT and abs(y0) < LIMIT and abs(x1) < LIMIT and abs(y1) < LIMIT) then + return -- horizontal, or non-finite (NaN fails every comparison) + end + if (y0 <= 0 and y1 <= 0) or (y0 >= H and y1 >= H) then + return + end + local dx = x1 - x0 + local ta, tb = 2, 2 + if dx ~= 0 then + local t0 = (0 - x0) / dx + local tw = (W - x0) / dx + if t0 > 0 and t0 < 1 then + ta = t0 + end + if tw > 0 and tw < 1 then + tb = tw + end + if ta > tb then + ta, tb = tb, ta + end + end + local dy = y1 - y0 + local px, py = x0, y0 + if ta < 1 then + local qx, qy = x0 + dx * ta, y0 + dy * ta + line(acc, S, H, clampx(px, W), py, clampx(qx, W), qy) + px, py = qx, qy + end + if tb < 1 then + local qx, qy = x0 + dx * tb, y0 + dy * tb + line(acc, S, H, clampx(px, W), py, clampx(qx, W), qy) + px, py = qx, qy + end + line(acc, S, H, clampx(px, W), py, clampx(x1, W), y1) +end + +@native 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, 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" + end + local X0, Y0, X1, Y1 = floor(bx0 :: number), floor(by0 :: number), ceil(bx1 :: number), ceil(by1 :: number) + 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 + Y0 = max(Y0, floor(clip[2])) + Y1 = min(Y1, ceil(clip[4])) + X1 = min(X1, ceil(clip[3])) + local cx0 = floor(clip[1]) + X0 = max(X0, cx0) + end + local W, H = X1 - X0, Y1 - Y0 + if W <= 0 or H <= 0 then + return nil, nil + end + local maxPixels = if type(o.maxPixels) == "number" then o.maxPixels else 2 ^ 26 + if W * H > maxPixels then + return nil, "limit" + end + local S = W + 2 + local acc = bcreate(S * H * 4) + for _, poly in polys do + local n = #poly + local lx, ly = poly[n - 1] - X0, poly[n] - Y0 + for i = 1, n - 1, 2 do + local x, y = poly[i] - X0, poly[i + 1] - Y0 + edge(acc, S, W, H, lx, ly, x, y) + lx, ly = x, y + end + end + local cov = bcreate(W * H) + local evenodd = o.rule == "evenodd" + for y = 0, H - 1 do + local sum = 0 + local ls = y * S + local os = y * W + for x = 0, W - 1 do + sum += readf32(acc, (ls + x) * 4) + local v = abs(sum) + if evenodd then + v = v % 2 + if v > 1 then + v = 2 - v + end + elseif v > 1 then + v = 1 + end + writeu8(cov, os + x, floor(v * 255 + 0.5)) + end + end + return { x = X0, y = Y0, width = W, height = H, coverage = cov }, nil +end + +@native function Raster.fill(img: any, path: any, paint: any, opts: Options?): (boolean, string?) + if type(img) ~= "table" or type(img.pixels) ~= "buffer" or type(img.width) ~= "number" or type(img.height) ~= "number" then + return false, "fill: expected an rgba8 image" + end + local iw, ih = img.width, img.height + local px = img.pixels + if buffer.len(px) < iw * ih * 4 then + return false, "fill: image pixels too short" + end + 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]) } + else + o.clip = { 0, 0, iw, ih } + end + local m, why = Raster.mask(path, o) + if not m then + return why == nil, why + end + local opacity = if type(o.opacity) == "number" then math.clamp(o.opacity, 0, 1) else 1 + local fn: any = nil + local cr, cg, cb, ca = 0, 0, 0, 255 + if type(paint) == "function" then + fn = paint + elseif type(paint) == "table" then + cr, cg, cb = tonumber(paint[1]) or 0, tonumber(paint[2]) or 0, tonumber(paint[3]) or 0 + ca = tonumber(paint[4]) or 255 + else + return false, "fill: paint must be a colour or a function" + end + local cov = m.coverage + local mw = m.width + for y = 0, m.height - 1 do + local iy = m.y + y + for x = 0, mw - 1 do + local cv = readu8(cov, y * mw + x) + if cv > 0 then + local ix = m.x + x + local r, g, b, a = cr, cg, cb, ca + if fn then + local ok, r2, g2, b2, a2 = pcall(fn, ix + 0.5, iy + 0.5) + if not ok then + return false, "fill: paint function failed" + end + r, g, b, a = tonumber(r2) or 0, tonumber(g2) or 0, tonumber(b2) or 0, tonumber(a2) or 255 + end + local sa = math.clamp(a, 0, 255) / 255 * cv / 255 * opacity + if sa > 0 then + local p = (iy * iw + ix) * 4 + local da = readu8(px, p + 3) / 255 + local oa = sa + da * (1 - sa) + local k = da * (1 - sa) + writeu8(px, p, floor((math.clamp(r, 0, 255) * sa + readu8(px, p) * k) / oa + 0.5)) + writeu8(px, p + 1, floor((math.clamp(g, 0, 255) * sa + readu8(px, p + 1) * k) / oa + 0.5)) + writeu8(px, p + 2, floor((math.clamp(b, 0, 255) * sa + readu8(px, p + 2) * k) / oa + 0.5)) + writeu8(px, p + 3, floor(oa * 255 + 0.5)) + end + end + end + end + return true, nil +end + +type StrokeOptions = { + width: number?, + join: ("miter" | "round" | "bevel")?, + cap: ("butt" | "round" | "square")?, + miterLimit: number?, + tolerance: number?, + closed: boolean?, +} + +-- push a polygon (flat x, y list) as a closed subpath with positive orientation, so overlapping pieces add up +-- under the nonzero rule +@native local function polygon(out: Path, pts: { number }) + local n = #pts + if n < 6 then + return + end + local area = 0 + for i = 1, n - 1, 2 do + local j = if i + 2 > n then 1 else i + 2 + area += pts[i] * pts[j + 1] - pts[j] * pts[i + 1] + end + if area == 0 then + return + end + if area > 0 then + table.insert(out, { op = "moveTo", pts[1], pts[2] }) + for i = 3, n - 1, 2 do + table.insert(out, { op = "lineTo", pts[i], pts[i + 1] }) + end + else + table.insert(out, { op = "moveTo", pts[n - 1], pts[n] }) + for i = n - 3, 1, -2 do + table.insert(out, { op = "lineTo", pts[i], pts[i + 1] }) + end + end + table.insert(out, { op = "close" } :: Cmd) +end + +@native local function arcPoints(cx: number, cy: number, r: number, a0: number, a1: number, tol: number, pts: { number }) + local da = a1 - a0 + local step = 2 * math.acos(math.clamp(1 - tol / max(r, 1e-9), -1, 1)) + local n = max(1, min(256, ceil(abs(da) / max(step, 0.01)))) + for i = 0, n do + local t = a0 + da * i / n + table.insert(pts, cx + r * math.cos(t)) + table.insert(pts, cy + r * math.sin(t)) + end +end + +@native function Raster.stroke(path: any, opts: StrokeOptions?): Path + local o: StrokeOptions = opts or {} + local hw = (if type(o.width) == "number" and o.width > 0 then o.width else 1) / 2 + local join = o.join or "miter" + local cap = o.cap or "butt" + local miterLimit = if type(o.miterLimit) == "number" and o.miterLimit >= 1 then o.miterLimit else 4 + local tol = if type(o.tolerance) == "number" and o.tolerance > 0.0005 then o.tolerance else 0.1 + local out: Path = {} + local cmds = commands(path) + if not cmds then + return out + end + -- subpaths with their closed flag (flatten loses it, so split here) + local subs: { { cmds: Path, closed: boolean } } = {} + local cur: Path? = nil + local lx, ly = 0, 0 + for _, c in cmds do + local op = if type(c) == "table" then c.op else nil + if op == "moveTo" and operands(c, 2) then + cur = { c } + table.insert(subs, { cmds = cur :: Path, closed = o.closed == true }) + lx, ly = c[1], c[2] + elseif op == "close" then + if cur then + subs[#subs].closed = true + cur = nil + end + elseif op == "lineTo" or op == "quadTo" or op == "cubicTo" then + if not cur then + cur = { { op = "moveTo", lx, ly } } + table.insert(subs, { cmds = cur :: Path, closed = o.closed == true }) + end + table.insert(cur :: Path, c) + end + end + for _, sub in subs do + local polys = flatten(sub.cmds, nil, tol, 4) + local pts = polys[1] + if not pts then + -- a degenerate subpath (a single point): round / square caps draw a dot + local m = sub.cmds[1] + if #sub.cmds >= 1 and operands(m, 2) and cap ~= "butt" then + local d = {} + if cap == "round" then + arcPoints(m[1], m[2], hw, 0, 2 * math.pi, tol, d) + else + d = { m[1] - hw, m[2] - hw, m[1] + hw, m[2] - hw, m[1] + hw, m[2] + hw, m[1] - hw, m[2] + hw } + end + polygon(out, d) + end + continue + end + local p: { number } = { pts[1], pts[2] } + for i = 3, #pts - 1, 2 do + if abs(pts[i] - p[#p - 1]) > 1e-9 or abs(pts[i + 1] - p[#p]) > 1e-9 then + table.insert(p, pts[i]) + table.insert(p, pts[i + 1]) + end + end + local closed = sub.closed + if closed and #p >= 4 and abs(p[1] - p[#p - 1]) < 1e-9 and abs(p[2] - p[#p]) < 1e-9 then + table.remove(p) + table.remove(p) + end + local n = #p // 2 + if n < 2 then + continue + end + local segs = if closed then n else n - 1 + local dirs: { number } = {} + for s = 0, segs - 1 do + local i, j = s, (s + 1) % n + local x0, y0, x1, y1 = p[2 * i + 1], p[2 * i + 2], p[2 * j + 1], p[2 * j + 2] + local dx, dy = x1 - x0, y1 - y0 + local len = sqrt(dx * dx + dy * dy) + local ux, uy = dx / len, dy / len + dirs[2 * s + 1], dirs[2 * s + 2] = ux, uy + local nx, ny = -uy * hw, ux * hw + polygon(out, { x0 + nx, y0 + ny, x1 + nx, y1 + ny, x1 - nx, y1 - ny, x0 - nx, y0 - ny }) + end + @native local function joinAt(k: number, s0: number, s1: number) + local x, y = p[2 * k + 1], p[2 * k + 2] + local ax, ay = dirs[2 * s0 + 1], dirs[2 * s0 + 2] + local bx, by = dirs[2 * s1 + 1], dirs[2 * s1 + 2] + local cross = ax * by - ay * bx + if abs(cross) < 1e-12 and ax * bx + ay * by > 0 then + return + end + -- the outer side: left normals when turning right (cross < 0) + local sgn = if cross < 0 then 1 else -1 + local n0x, n0y = -ay * hw * sgn, ax * hw * sgn + local n1x, n1y = -by * hw * sgn, bx * hw * sgn + if join == "round" then + local d = { x, y } + local a0 = math.atan2(n0y, n0x) + local a1 = math.atan2(n1y, n1x) + local da = a1 - a0 + while da > math.pi do + da -= 2 * math.pi + end + while da < -math.pi do + da += 2 * math.pi + end + arcPoints(x, y, hw, a0, a0 + da, tol, d) + polygon(out, d) + else + local cosT = ax * bx + ay * by + local miter = if join == "miter" then 1 / sqrt(max(1e-12, (1 + cosT) / 2)) else math.huge + if join == "miter" and miter <= miterLimit then + local mx, my = n0x + n1x, n0y + n1y + local ml = sqrt(mx * mx + my * my) + if ml > 1e-12 then + local scale = hw * miter / ml + polygon(out, { x, y, x + n0x, y + n0y, x + mx * scale, y + my * scale, x + n1x, y + n1y }) + return + end + end + polygon(out, { x, y, x + n0x, y + n0y, x + n1x, y + n1y }) + end + end + if closed then + for k = 0, n - 1 do + joinAt(k, (k - 1) % n, k) + end + else + for k = 1, n - 2 do + joinAt(k, k - 1, k) + end + if cap ~= "butt" then + for _, endInfo in { { 0, 0, -1 }, { n - 1, segs - 1, 1 } } do + local k, s, sgn = endInfo[1], endInfo[2], endInfo[3] + local x, y = p[2 * k + 1], p[2 * k + 2] + local ux, uy = dirs[2 * s + 1] * sgn, dirs[2 * s + 2] * sgn + local nx, ny = -uy * hw, ux * hw + if cap == "square" then + polygon(out, { x + nx, y + ny, x + nx + ux * hw, y + ny + uy * hw, x - nx + ux * hw, y - ny + uy * hw, x - nx, y - ny }) + else + local d = {} + local a0 = math.atan2(ny, nx) + arcPoints(x, y, hw, a0, a0 - math.pi, tol, d) + polygon(out, d) + end + end + end + end + end + return out +end + +return Raster +end +__FILES["codecs/image/Texel"] = @native function() + + + +-- codecs/image/Texel: uncompressed GPU texel formats -> the standard pixel formats. New in rosetta. +-- Names list channels from the lowest address / bit up (DXGI order); snorm -> rgba8 is biased (8-bit: s + 128). +local Half = __include("codecs/image/Half") + +local Texel = {} + +type Channel = { c: string, shift: number, bits: number } +type Desc = { + bytes: number, + kind: "array" | "packed" | "r11g11b10f" | "rgb9e5" | "pair" | "ayuv", + size: number?, + type: string?, + order: string?, + channels: { Channel }?, +} + +local readu8, readu16, readu32, readi8, readi16, readi32, readf32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi8, buffer.readi16, buffer.readi32, buffer.readf32 +local writeu8, writeu16, writeu32, writef32 = buffer.writeu8, buffer.writeu16, buffer.writeu32, buffer.writef32 +local band, rshift, lshift = bit32.band, bit32.rshift, bit32.lshift +local HALF = Half.TABLE + +local FORMATS: { [string]: Desc } = {} +@native local function array(name: string, size: number, typ: string, order: string) + FORMATS[name] = { bytes = size * #order, kind = "array", size = size, type = typ, order = order } +end +for _, o in { "r", "rg", "rgb", "rgba" } do + array(o .. "8", 1, "unorm", o) + array(o .. "8s", 1, "snorm", o) + array(o .. "8ui", 1, "uint", o) + array(o .. "8i", 1, "sint", o) + array(o .. "16", 2, "unorm", o) + array(o .. "16s", 2, "snorm", o) + array(o .. "16ui", 2, "uint", o) + array(o .. "16i", 2, "sint", o) + array(o .. "16f", 2, "float", o) + array(o .. "32ui", 4, "uint", o) + array(o .. "32i", 4, "sint", o) + array(o .. "32f", 4, "float", o) +end +array("bgr8", 1, "unorm", "bgr") +array("bgra8", 1, "unorm", "bgra") +array("bgrx8", 1, "unorm", "bgrx") +array("rgbx8", 1, "unorm", "rgbx") +array("a8", 1, "unorm", "a") +array("l8", 1, "unorm", "l") +array("la8", 1, "unorm", "la") +array("l16", 2, "unorm", "l") +array("la16", 2, "unorm", "la") +array("a16", 2, "unorm", "a") + +@native local function packed(name: string, bytes: number, spec: { any }) + local ch: { Channel } = {} + for i = 1, #spec, 3 do + table.insert(ch, { c = spec[i], shift = spec[i + 1], bits = spec[i + 2] }) + end + FORMATS[name] = { bytes = bytes, kind = "packed", channels = ch } +end +packed("b5g6r5", 2, { "b", 0, 5, "g", 5, 6, "r", 11, 5 }) +packed("r5g6b5", 2, { "r", 0, 5, "g", 5, 6, "b", 11, 5 }) +packed("b5g5r5a1", 2, { "b", 0, 5, "g", 5, 5, "r", 10, 5, "a", 15, 1 }) +packed("b5g5r5x1", 2, { "b", 0, 5, "g", 5, 5, "r", 10, 5 }) +packed("a1b5g5r5", 2, { "a", 0, 1, "b", 1, 5, "g", 6, 5, "r", 11, 5 }) +packed("a1r5g5b5", 2, { "a", 0, 1, "r", 1, 5, "g", 6, 5, "b", 11, 5 }) +packed("b4g4r4a4", 2, { "b", 0, 4, "g", 4, 4, "r", 8, 4, "a", 12, 4 }) +packed("r4g4b4a4", 2, { "r", 0, 4, "g", 4, 4, "b", 8, 4, "a", 12, 4 }) +packed("a4b4g4r4", 2, { "a", 0, 4, "b", 4, 4, "g", 8, 4, "r", 12, 4 }) +packed("a4r4g4b4", 2, { "a", 0, 4, "r", 4, 4, "g", 8, 4, "b", 12, 4 }) +packed("rgb10a2", 4, { "r", 0, 10, "g", 10, 10, "b", 20, 10, "a", 30, 2 }) +packed("bgr10a2", 4, { "b", 0, 10, "g", 10, 10, "r", 20, 10, "a", 30, 2 }) +packed("r3g3b2", 1, { "b", 0, 2, "g", 2, 3, "r", 5, 3 }) +FORMATS.r11g11b10f = { bytes = 4, kind = "r11g11b10f" } +FORMATS.rgb9e5 = { bytes = 4, kind = "rgb9e5" } +-- 4:2:2 pairs (2 pixels in 4 bytes; bytes = per pixel) and 4:4:4 AYUV (bytes V U Y A); Y'CbCr is BT.601 limited range +FORMATS.yuy2 = { bytes = 2, kind = "pair", order = "yuyv" } +FORMATS.uyvy = { bytes = 2, kind = "pair", order = "uyvy" } +FORMATS.rgbg = { bytes = 2, kind = "pair", order = "rgbg" } +FORMATS.grgb = { bytes = 2, kind = "pair", order = "grgb" } +FORMATS.ayuv = { bytes = 4, kind = "ayuv" } +Texel.FORMATS = FORMATS + +@native function Texel.masked(bytes: number, r: number, g: number, b: number, a: number, luminance: boolean?): Desc? + if bytes < 1 or bytes > 4 then + return nil + end + local ch: { Channel } = {} + for i, m in { r, g, b, a } do + if m ~= 0 then + local shift = 0 + while band(m, lshift(1, shift)) == 0 and shift < 31 do + shift += 1 + end + local bits = 0 + while shift + bits < 32 and band(m, lshift(1, shift + bits)) ~= 0 do + bits += 1 + end + local name = if i == 1 then (if luminance then "l" else "r") elseif i == 2 then "g" elseif i == 3 then "b" else "a" + table.insert(ch, { c = name, shift = shift, bits = bits }) + end + end + if #ch == 0 then + return nil + end + return { bytes = bytes, kind = "packed", channels = ch } +end + +@native function Texel.size(fmt: string | Desc, w: number, h: number): number? + local d = if type(fmt) == "string" then FORMATS[fmt] else fmt + if not d then + return nil + end + return if d.kind == "pair" then ((w + 1) // 2) * 4 * h else d.bytes * w * h +end + +@native local function nativeOf(d: Desc): string + if d.kind == "array" then + local t, s = d.type, d.size :: number + if t == "float" or t == "snorm" or t == "sint" or (t == "uint" and s > 1) then + return "rgbaf32" + end + return if s == 1 then "rgba8" else "rgba16" + elseif d.kind == "packed" then + local wide = false + for _, c in d.channels :: { Channel } do + wide = wide or c.bits > 8 + end + return if wide then "rgba16" else "rgba8" + end + return "rgbaf32" +end +Texel.nativeOf = nativeOf + +@native local function uf11(v: number): number + local e, m = rshift(v, 6), band(v, 63) + if e == 0 then + return m / 64 * 2 ^ -14 + elseif e == 31 then + return if m == 0 then math.huge else 0 / 0 + end + return (1 + m / 64) * 2 ^ (e - 15) +end +@native local function uf10(v: number): number + local e, m = rshift(v, 5), band(v, 31) + if e == 0 then + return m / 32 * 2 ^ -14 + elseif e == 31 then + return if m == 0 then math.huge else 0 / 0 + end + return (1 + m / 32) * 2 ^ (e - 15) +end + +@native local function component(src: buffer, q: number, size: number, typ: string): (number, number) + if typ == "unorm" then + if size == 1 then + local v = readu8(src, q) + return v / 255, v + elseif size == 2 then + local v = readu16(src, q) + return v / 65535, (v * 255 + 32767) // 65535 + end + local v = readu32(src, q) + return v / 4294967295, math.floor(v / 4294967295 * 255 + 0.5) + elseif typ == "snorm" then + if size == 1 then + local v = math.max(readi8(src, q), -127) + return v / 127, v + 128 + elseif size == 2 then + local v = math.max(readi16(src, q), -32767) + return v / 32767, math.floor(v * 127 / 32767 + 0.5) + 128 + end + local v = math.max(readi32(src, q), -2147483647) + return v / 2147483647, math.floor(v * 127 / 2147483647 + 0.5) + 128 + elseif typ == "float" then + local f = if size == 2 then HALF[readu16(src, q)] else readf32(src, q) + local c = if f ~= f then 0 elseif f < 0 then 0 elseif f > 1 then 1 else f + return f, math.floor(c * 255 + 0.5) + elseif typ == "uint" then + local v = if size == 1 then readu8(src, q) elseif size == 2 then readu16(src, q) else readu32(src, q) + return v, math.min(v, 255) + end + local v = if size == 1 then readi8(src, q) elseif size == 2 then readi16(src, q) else readi32(src, q) + return v, math.clamp(v, 0, 255) +end + +@native local function ycc(y: number, u: number, v: number, a: number): number + local c, d, e = 1.164 * (y - 16), u - 128, v - 128 + local r = math.clamp(math.floor(c + 1.596 * e + 0.5), 0, 255) + local g = math.clamp(math.floor(c - 0.392 * d - 0.813 * e + 0.5), 0, 255) + local b = math.clamp(math.floor(c + 2.017 * d + 0.5), 0, 255) + return r + g * 256 + b * 65536 + a * 16777216 +end + +@native local function yuv(d: Desc, src: buffer, offset: number, w: number, h: number, pitch: number, dst: buffer): buffer + local n = 0 + local order = d.order or "" + for y = 0, h - 1 do + local s = offset + y * pitch + for x = 0, w - 1 do + if d.kind == "ayuv" then + local q = s + x * 4 + writeu32(dst, n, ycc(readu8(src, q + 2), readu8(src, q + 1), readu8(src, q), readu8(src, q + 3))) + else + local q = s + (x // 2) * 4 + local b0, b1, b2, b3 = readu8(src, q), readu8(src, q + 1), readu8(src, q + 2), readu8(src, q + 3) + local odd = x % 2 == 1 + if order == "yuyv" then + writeu32(dst, n, ycc(if odd then b2 else b0, b1, b3, 255)) + elseif order == "uyvy" then + writeu32(dst, n, ycc(if odd then b3 else b1, b0, b2, 255)) + elseif order == "rgbg" then + writeu32(dst, n, b0 + (if odd then b3 else b1) * 256 + b2 * 65536 + 0xFF000000) + else + writeu32(dst, n, b1 + (if odd then b2 else b0) * 256 + b3 * 65536 + 0xFF000000) + end + end + n += 4 + end + end + return dst +end + +@native function Texel.decode(fmt: string | Desc, src: buffer, offset: number, w: number, h: number, native: boolean?, rowPitch: number?): (buffer?, string) + local d = if type(fmt) == "string" then FORMATS[fmt] else fmt + if not d then + return nil, "unsupported: unknown texel format " .. tostring(fmt) + end + local tb = d.bytes + local rowBytes = if d.kind == "pair" then ((w + 1) // 2) * 4 else tb * w + local pitch = rowPitch or rowBytes + if w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 or pitch < rowBytes then + return nil, "bad image size" + end + if offset < 0 or offset + pitch * (h - 1) + rowBytes > buffer.len(src) then + return nil, "truncated: texel data runs past the end" + end + local out = if native and d.kind ~= "pair" and d.kind ~= "ayuv" then nativeOf(d) else "rgba8" + local bpp = if out == "rgba8" then 4 elseif out == "rgba16" then 8 else 16 + local dst = buffer.create(w * h * bpp) + local n = 0 + if d.kind == "array" then + local order, size, typ = d.order :: string, d.size :: number, d.type :: string + if size == 1 and typ == "unorm" and out == "rgba8" and (order == "rgba" or order == "bgra" or order == "bgrx" or order == "rgbx") then + local swap = order == "bgra" or order == "bgrx" + local opaque = order == "bgrx" or order == "rgbx" + for y = 0, h - 1 do + local s = offset + y * pitch + for x = 0, w - 1 do + local v = readu32(src, s + x * 4) + if swap then + v = band(v, 0xFF00FF00) + band(rshift(v, 16), 0xFF) + lshift(band(v, 0xFF), 16) + end + if opaque then + v = band(v, 0xFFFFFF) + 0xFF000000 + end + writeu32(dst, n, v) + n += 4 + end + end + return dst, out + end + local nc = #order + local map = table.create(nc, 0) + for i = 1, nc do + local c = string.sub(order, i, i) + map[i] = if c == "r" then (if nc == 1 then 4 else 0) elseif c == "g" then 1 elseif c == "b" then 2 elseif c == "a" then 3 elseif c == "l" then 4 else -1 + end + local f = table.create(4, 0) + local q8 = table.create(4, 0) + for y = 0, h - 1 do + local s = offset + y * pitch + for _ = 0, w - 1 do + f[1], f[2], f[3], f[4] = 0, 0, 0, 1 + q8[1], q8[2], q8[3], q8[4] = 0, 0, 0, 255 + for i = 1, nc do + local m = map[i] + if m >= 0 then + local fv, bv = component(src, s, size, typ) + if m == 4 then + f[1], f[2], f[3] = fv, fv, fv + q8[1], q8[2], q8[3] = bv, bv, bv + else + f[m + 1], q8[m + 1] = fv, bv + end + end + s += size + end + if out == "rgba8" then + writeu32(dst, n, q8[1] + q8[2] * 256 + q8[3] * 65536 + q8[4] * 16777216) + elseif out == "rgba16" then + for c = 0, 3 do + writeu16(dst, n + c * 2, math.floor(math.clamp(f[c + 1], 0, 1) * 65535 + 0.5)) + end + else + for c = 0, 3 do + writef32(dst, n + c * 4, f[c + 1]) + end + end + n += bpp + end + end + return dst, out + elseif d.kind == "packed" then + local chs = d.channels :: { Channel } + for y = 0, h - 1 do + local s = offset + y * pitch + for _ = 0, w - 1 do + local v = if tb == 1 then readu8(src, s) elseif tb == 2 then readu16(src, s) elseif tb == 3 then readu16(src, s) + readu8(src, s + 2) * 65536 else readu32(src, s) + s += tb + local r, g, b, a = 0, 0, 0, 1 + for _, c in chs do + local maxv = lshift(1, c.bits) - 1 + local x = band(rshift(v, c.shift), maxv) / (if c.bits >= 32 then 4294967295 else maxv) + local k = c.c + if k == "r" then + r = x + elseif k == "g" then + g = x + elseif k == "b" then + b = x + elseif k == "a" then + a = x + else + r, g, b = x, x, x + end + end + if out == "rgba8" then + writeu32(dst, n, math.floor(r * 255 + 0.5) + math.floor(g * 255 + 0.5) * 256 + math.floor(b * 255 + 0.5) * 65536 + math.floor(a * 255 + 0.5) * 16777216) + else + writeu16(dst, n, math.floor(r * 65535 + 0.5)) + writeu16(dst, n + 2, math.floor(g * 65535 + 0.5)) + writeu16(dst, n + 4, math.floor(b * 65535 + 0.5)) + writeu16(dst, n + 6, math.floor(a * 65535 + 0.5)) + end + n += bpp + end + end + return dst, out + end + if d.kind == "pair" or d.kind == "ayuv" then + return yuv(d, src, offset, w, h, pitch, dst), out + end + local nine = d.kind == "rgb9e5" + for y = 0, h - 1 do + local s = offset + y * pitch + for _ = 0, w - 1 do + local v = readu32(src, s) + s += 4 + local sc = if nine then 2 ^ (rshift(v, 27) - 24) else 0 + local r: number = if nine then band(v, 511) * sc else uf11(band(v, 2047)) + local g: number = if nine then band(rshift(v, 9), 511) * sc else uf11(band(rshift(v, 11), 2047)) + local b: number = if nine then band(rshift(v, 18), 511) * sc else uf10(rshift(v, 22)) + if out == "rgba8" then + @native local function q(x: number): number + return if x ~= x or x <= 0 then 0 elseif x >= 1 then 255 else math.floor(x * 255 + 0.5) + end + writeu32(dst, n, q(r) + q(g) * 256 + q(b) * 65536 + 0xFF000000) + else + writef32(dst, n, r) + writef32(dst, n + 4, g) + writef32(dst, n + 8, b) + writef32(dst, n + 12, 1) + end + n += bpp + end + end + return dst, out +end + +return Texel +end +__FILES["codecs/image/Texture"] = function() + +-- codecs/image/Texture: one entry point over the texture pixel codecs (Bcn, Etc, Texel). New in rosetta. +local Types = __include("Types") +local Bcn = __include("codecs/image/Bcn") +local Etc = __include("codecs/image/Etc") +local Texel = __include("codecs/image/Texel") +local Half = __include("codecs/image/Half") + +local Texture = {} + +function Texture.known(name: string): string? + if Bcn.BLOCK[name] then + return "bcn" + elseif Etc.BLOCK[name] then + return "etc" + elseif Texel.FORMATS[name] then + return "texel" + end + return nil +end + +function Texture.size(name: string, w: number, h: number): number? + return Bcn.size(name, w, h) or Etc.size(name, w, h) or Texel.size(name, w, h) +end + +function Texture.block(name: string): (number?, number?, number?) + local b = Bcn.BLOCK[name] or Etc.BLOCK[name] + if b then + return 4, 4, b + end + local d = Texel.FORMATS[name] + if d then + return 1, 1, d.bytes + end + return nil, nil, nil +end + +function Texture.decode(name: string, src: buffer, offset: number, w: number, h: number, native: boolean?): (buffer?, string) + if Bcn.BLOCK[name] then + local px, err = Bcn.decode(name, src, offset, w, h) + if not px then + return nil, err or "bad block data" + end + if Bcn.FLOAT[name] then + if native then + return px, "rgbaf32" + end + local out = buffer.create(w * h * 4) + for i = 0, w * h - 1 do + for c = 0, 3 do + local v = buffer.readf32(px, i * 16 + c * 4) + buffer.writeu8(out, i * 4 + c, if v ~= v or v <= 0 then 0 elseif v >= 1 then 255 else math.floor(v * 255 + 0.5)) + end + end + return out, "rgba8" + end + return px, "rgba8" + elseif Etc.BLOCK[name] then + local wide = native == true and string.sub(name, 1, 3) == "eac" + local px, err = Etc.decode(name, src, offset, w, h, nil, 0, wide) + if not px then + return nil, err or "bad block data" + end + return px, if wide then "rgba16" else "rgba8" + end + return Texel.decode(name, src, offset, w, h, native) +end + +function Texture.image(px: buffer, pf: string, w: number, h: number): Types.Image + local img = Types.Image.new(0, 0, pf :: any) + img.width, img.height, img.pixels = w, h, px + return img +end + +type Surface = { level: number, layer: number, face: number, slice: number, image: Types.Image } + +function Texture.assemble(list: { Surface }, layout: string): Types.Image? + local first: Types.Image? = nil + local frames: { Types.Frame } = {} + local mips: { Types.Image } = {} + for _, s in list do + if s.level == 0 then + first = first or s.image + local fr: Types.Frame = { image = s.image, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" } + table.insert(frames, fr) + elseif s.layer == 0 and s.face == 0 and s.slice == 0 then + mips[s.level] = s.image + end + end + if not first then + return nil + end + local img = Texture.image(first.pixels, first.format, first.width, first.height) + if #frames > 1 then + img.frames = frames + end + if #mips > 0 then + img.meta.mipmaps = mips + end + img.meta.layout = layout + return img +end + +function Texture.halve(img: Types.Image): Types.Image + local w, h = img.width, img.height + local nw, nh = math.max(1, w // 2), math.max(1, h // 2) + local fmt = img.format + local out = Types.Image.new(nw, nh, fmt) + local src, dst = img.pixels, out.pixels + local cs = if fmt == "rgba8" then 1 elseif fmt == "rgba16" then 2 else 4 + local function get(x: number, y: number, c: number): number + local o = ((math.min(y, h - 1) * w + math.min(x, w - 1)) * 4 + c) * cs + return if cs == 1 then buffer.readu8(src, o) elseif cs == 2 then buffer.readu16(src, o) else buffer.readf32(src, o) + end + for y = 0, nh - 1 do + for x = 0, nw - 1 do + for c = 0, 3 do + local x0, y0 = x * 2, y * 2 + local v = (get(x0, y0, c) + get(x0 + 1, y0, c) + get(x0, y0 + 1, c) + get(x0 + 1, y0 + 1, c)) / 4 + local o = ((y * nw + x) * 4 + c) * cs + if cs == 1 then + buffer.writeu8(dst, o, math.floor(v + 0.5)) + elseif cs == 2 then + buffer.writeu16(dst, o, math.floor(v + 0.5)) + else + buffer.writef32(dst, o, v) + end + end + end + end + return out +end + +function Texture.toHalf(px: buffer, n: number): buffer + local out = buffer.create(n * 8) + local from = Half.fromFloat + for i = 0, n * 4 - 1 do + buffer.writeu16(out, i * 2, from(buffer.readf32(px, i * 4))) + end + return out +end + +return Texture +end +end + + + + + + codecs_model + --!optimize 2 +--!nocheck +-- rosetta chunk codecs_model (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 17 modules (2 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["codecs/model/Mat4"] = function() + +-- codecs/model/Mat4: 4x4 matrix (column-major, glTF / Types.Scene layout) and quaternion { x, y, z, w } helpers. +local Types = __include("Types") + +local Mat4 = {} + +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 + +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 + +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 } +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 + +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 + +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 + +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 + +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 + +-- T * R * S (glTF 2.0 node transform) +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 + +-- 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 + +function Mat4.decomposeStrict(m: M4): ({ number }?, { number }?, { number }?) + return split(m, true) +end + +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 + +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 + +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 + +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 + +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 + +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 + +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 +end +__FILES["codecs/model/MeshFlatten"] = function() + +-- codecs/model/MeshFlatten: a Scene to one world-space mesh, for the writers of mesh-only formats (STL, PLY, OFF). +local Types = __include("Types") + +local Flatten = {} + +local readf32, readf64 = buffer.readf32, buffer.readf64 +local readu8, readu16, readu32 = buffer.readu8, buffer.readu16, buffer.readu32 +local readi8, readi16, readi32 = buffer.readi8, buffer.readi16, buffer.readi32 + +local SIZE = Types.COMPONENT_SIZE +-- normalized integer types: their scale (raw / scale = the normalized value) +local NORM: { [string]: number } = { unorm8 = 255, unorm16 = 65535, snorm8 = 127, snorm16 = 32767 } + +type Attr = { + type: string, + components: number, + raw: boolean, + values: { number }, +} +type PartInfo = { + prim: Types.Primitive, + mesh: Types.Mesh?, + node: Types.Node?, + firstVertex: number, + vertexCount: number, + firstFace: number, + faceCount: number, + identity: boolean, +} +type Merged = { + count: number, + attrs: { [string]: Attr }, + sizes: { number }?, + corners: { number }, + parts: { PartInfo }, +} + +function Flatten.numbers(acc: any, raw: boolean?): ({ number }?, string?) + if type(acc) ~= "table" or type(acc.data) ~= "buffer" then + return nil, "accessor without a data buffer" + end + local t, comps, count = acc.type, acc.components, acc.count + local size = SIZE[t] + if size == nil then + return nil, "unknown accessor type " .. tostring(t) + end + if type(comps) ~= "number" or type(count) ~= "number" or comps < 1 or comps > 16 or count < 0 or comps % 1 ~= 0 or count % 1 ~= 0 then + return nil, "bad accessor components / count" + end + local n = count * comps + local d: buffer = acc.data + if buffer.len(d) < n * size then + return nil, "accessor data shorter than count * components" + end + local out = table.create(n) :: { number } + if t == "f32" then + for i = 0, n - 1 do + out[i + 1] = readf32(d, i * 4) + end + elseif t == "f64" then + for i = 0, n - 1 do + out[i + 1] = readf64(d, i * 8) + end + elseif t == "u8" or t == "unorm8" then + for i = 0, n - 1 do + out[i + 1] = readu8(d, i) + end + elseif t == "u16" or t == "unorm16" then + for i = 0, n - 1 do + out[i + 1] = readu16(d, i * 2) + end + elseif t == "u32" then + for i = 0, n - 1 do + out[i + 1] = readu32(d, i * 4) + end + elseif t == "i8" or t == "snorm8" then + for i = 0, n - 1 do + out[i + 1] = readi8(d, i) + end + elseif t == "i16" or t == "snorm16" then + for i = 0, n - 1 do + out[i + 1] = readi16(d, i * 2) + end + else -- i32 + for i = 0, n - 1 do + out[i + 1] = readi32(d, i * 4) + end + end + local scale = NORM[t] + if scale and not raw then + local signed = t == "snorm8" or t == "snorm16" + for i = 1, n do + local v = out[i] / scale + out[i] = if signed and v < -1 then -1 else v + end + end + return out, nil +end + +local IDENTITY = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 } + +local mul = Types.Scene.mul + +local function numList(v: any, n: number): boolean + if type(v) ~= "table" then + return false + end + for i = 1, n do + if type(v[i]) ~= "number" then + return false + end + end + return true +end + +local function localMatrix(node: any): ({ number }?, string?) + if node.matrix ~= nil then + if not numList(node.matrix, 16) then + return nil, "node matrix is not 16 numbers" + end + local m = table.create(16) :: { number } + for i = 1, 16 do + m[i] = node.matrix[i] + end + return m, nil + end + local t, q, s = node.translation, node.rotation, node.scale + if t == nil and q == nil and s == nil then + return nil, nil + end + if (t ~= nil and not numList(t, 3)) or (q ~= nil and not numList(q, 4)) or (s ~= nil and not numList(s, 3)) then + return nil, "bad node translation / rotation / scale" + end + local x, y, z, w = 0, 0, 0, 1 + if q then + x, y, z, w = q[1], q[2], q[3], q[4] + end + local sx, sy, sz = 1, 1, 1 + if s then + sx, sy, sz = s[1], s[2], s[3] + end + local tx, ty, tz = 0, 0, 0 + if t then + tx, ty, tz = t[1], t[2], t[3] + end + return { + (1 - 2 * (y * y + z * z)) * sx, + (2 * (x * y + z * w)) * sx, + (2 * (x * z - y * w)) * sx, + 0, + (2 * (x * y - z * w)) * sy, + (1 - 2 * (x * x + z * z)) * sy, + (2 * (y * z + x * w)) * sy, + 0, + (2 * (x * z + y * w)) * sz, + (2 * (y * z - x * w)) * sz, + (1 - 2 * (x * x + y * y)) * sz, + 0, + tx, + ty, + tz, + 1, + }, + nil +end + +local function isIdentity(m: { number }): boolean + for i = 1, 16 do + if m[i] ~= IDENTITY[i] then + return false + end + end + return true +end + +type Instance = { prim: Types.Primitive, mesh: Types.Mesh?, node: Types.Node?, matrix: { number }? } + +local function instances(scene: any): ({ Instance }?, string?) + local out: { Instance } = {} + local nodes, meshes = scene.nodes, scene.meshes + if type(nodes) ~= "table" or type(meshes) ~= "table" then + return nil, "scene without nodes / meshes tables" + end + local function addMesh(mi: any, node: Types.Node?, m: { number }?): string? + local mesh = meshes[mi] + if type(mesh) ~= "table" or type(mesh.primitives) ~= "table" then + return "node refers to a missing mesh " .. tostring(mi) + end + for _, prim in mesh.primitives do + if type(prim) ~= "table" or type(prim.attributes) ~= "table" then + return "bad primitive" + end + table.insert(out, { prim = prim, mesh = mesh, node = node, matrix = m }) + end + return nil + end + local visiting: { [number]: boolean } = {} + local function visit(ni: any, parent: { number }?, depth: number): string? + local node = nodes[ni] + if type(node) ~= "table" then + return "missing node " .. tostring(ni) + end + if depth > 256 or visiting[ni] then + return "node hierarchy is cyclic or too deep" + end + visiting[ni] = true + local m, merr = localMatrix(node) + if merr then + return merr + end + local world = if m and parent then mul(parent, m) elseif m then m else parent + if node.mesh ~= nil then + local e = addMesh(node.mesh, node, world) + if e then + return e + end + end + if type(node.children) == "table" then + for _, c in node.children do + local e = visit(c, world, depth + 1) + if e then + return e + end + end + end + visiting[ni] = nil + return nil + end + local roots = scene.roots + if type(roots) == "table" and #roots > 0 then + for _, ri in roots do + local e = visit(ri, nil, 0) + if e then + return nil, e + end + end + elseif #nodes > 0 then + local isChild: { [number]: boolean } = {} + for _, n in nodes do + if type(n) == "table" and type(n.children) == "table" then + for _, c in n.children do + isChild[c] = true + end + end + end + for i = 1, #nodes do + if not isChild[i] then + local e = visit(i, nil, 0) + if e then + return nil, e + end + end + end + else + for i = 1, #meshes do + local e = addMesh(i, nil, nil) + if e then + return nil, e + end + end + end + return out, nil +end + +local function faces(prim: any, nv: number): (any, any, string?) + local mode = prim.mode or "triangles" + if mode == "points" then + return "points", nil, nil + elseif mode == "lines" or mode == "line_strip" or mode == "line_loop" then + return "skip", nil, nil + end + local idx: { number } + if prim.indices ~= nil then + local v, err = Flatten.numbers(prim.indices, true) + if not v then + return nil, nil, "indices: " .. tostring(err) + end + idx = v + else + idx = table.create(nv) :: { number } + for i = 1, nv do + idx[i] = i - 1 + end + end + for i = 1, #idx do + local v = idx[i] + if v < 0 or v >= nv or v % 1 ~= 0 then + return nil, nil, string.format("index %s out of range (%d vertices)", tostring(v), nv) + end + end + if mode == "triangles" then + local n = #idx - #idx % 3 + if n ~= #idx then + local c = table.create(n) :: { number } + table.move(idx, 1, n, 1, c) + idx = c + end + return false, idx, nil + elseif mode == "polygons" then + if prim.faces == nil then + return nil, nil, "polygons primitive without faces" + end + local sizes, err = Flatten.numbers(prim.faces, true) + if not sizes then + return nil, nil, "faces: " .. tostring(err) + end + local total = 0 + for i = 1, #sizes do + local s = sizes[i] + if s < 0 or s % 1 ~= 0 then + return nil, nil, "bad face size" + end + total += s + end + if total ~= #idx then + return nil, nil, "face sizes do not add up to the index count" + end + return sizes, idx, nil + elseif mode == "triangle_strip" or mode == "triangle_fan" then + local c = {} + for i = 3, #idx do + if mode == "triangle_fan" then + table.insert(c, idx[1]) + table.insert(c, idx[i - 1]) + table.insert(c, idx[i]) + elseif i % 2 == 1 then + table.insert(c, idx[i - 2]) + table.insert(c, idx[i - 1]) + table.insert(c, idx[i]) + else + table.insert(c, idx[i - 1]) + table.insert(c, idx[i - 2]) + table.insert(c, idx[i]) + end + end + return false, c, nil + end + return nil, nil, "unknown primitive mode " .. tostring(mode) +end + +-- the fill value of a missing attribute component: colours default to opaque white, everything else to 0 +local function fill(name: string, t: string, raw: boolean): number + if string.sub(name, 1, 6) ~= "COLOR_" then + return 0 + end + return if raw and NORM[t] then NORM[t] else 1 +end + +local function f32(v: number): number + local b = buffer.create(4) + buffer.writef32(b, 0, v) + return buffer.readf32(b, 0) +end + +function Flatten.merge(scene: any, keep: (string) -> boolean, opts: { triangulate: boolean? }?): (Merged?, string?) + if type(scene) ~= "table" then + return nil, "not a scene" + end + local list, lerr = instances(scene) + if not list then + return nil, lerr + end + local triangulate = opts and opts.triangulate or false + local types: { [string]: string } = {} + local comps: { [string]: number } = {} + local used: { Instance } = {} + for _, inst in list do + local mode = inst.prim.mode or "triangles" + if mode ~= "lines" and mode ~= "line_strip" and mode ~= "line_loop" then + local pos = inst.prim.attributes.POSITION + if type(pos) ~= "table" then + return nil, "primitive without POSITION" + end + table.insert(used, inst) + for name, acc in inst.prim.attributes do + if type(name) == "string" and (name == "POSITION" or keep(name)) and type(acc) == "table" then + local t = acc.type + if types[name] == nil then + types[name] = t + elseif types[name] ~= t then + types[name] = "f32" + end + comps[name] = math.max(comps[name] or 0, tonumber(acc.components) or 0) + end + end + end + end + if (comps.POSITION or 3) < 3 then + return nil, "POSITION needs 3 components" + end + local attrs: { [string]: Attr } = {} + for name, t in types do + local raw = NORM[t] ~= nil + if name == "POSITION" or name == "NORMAL" then + raw = false + end + attrs[name] = { type = if name == "POSITION" or name == "NORMAL" then "f32" else t, components = if name == "POSITION" or name == "NORMAL" then 3 else comps[name], raw = raw, values = {} } + end + local merged: Merged = { count = 0, attrs = attrs, sizes = nil, corners = {}, parts = {} } + local sizes: { number } = {} + local anyFaces = false + local corners = merged.corners + for _, inst in used do + local prim: any = inst.prim + local posAcc = prim.attributes.POSITION + local nv = tonumber(posAcc.count) or 0 + local m = inst.matrix + local identity = m == nil or isIdentity(m :: { number }) + local info: PartInfo = { prim = prim, mesh = inst.mesh, node = inst.node, firstVertex = merged.count, vertexCount = nv, firstFace = #sizes, faceCount = 0, identity = identity } + for name, a in attrs do + local acc = prim.attributes[name] + local dst = a.values + local n0 = #dst + local ac = a.components + if acc == nil then + local f = fill(name, a.type, a.raw) + for i = 1, nv * ac do + dst[n0 + i] = f + end + else + if acc.count ~= nv then + return nil, name .. " count differs from POSITION" + end + local vals, err = Flatten.numbers(acc, a.raw and acc.type == a.type) + if not vals then + return nil, name .. ": " .. tostring(err) + end + local sc = acc.components + if a.raw and acc.type ~= a.type then + return nil, name .. ": mixed accessor types" + end + local f = fill(name, a.type, a.raw) + if name == "POSITION" and not identity then + local mm = m :: { number } + for i = 0, nv - 1 do + local x, y, z = vals[i * sc + 1], vals[i * sc + 2], vals[i * sc + 3] + dst[n0 + i * 3 + 1] = f32(mm[1] * x + mm[5] * y + mm[9] * z + mm[13]) + dst[n0 + i * 3 + 2] = f32(mm[2] * x + mm[6] * y + mm[10] * z + mm[14]) + dst[n0 + i * 3 + 3] = f32(mm[3] * x + mm[7] * y + mm[11] * z + mm[15]) + end + elseif name == "NORMAL" and not identity and sc >= 3 then + local mm = m :: { number } + -- the cofactor matrix of the upper 3x3 = det * inverse transpose; the sign of det keeps the direction + local a1, a2, a3, b1, b2, b3, c1, c2, c3 = mm[1], mm[2], mm[3], mm[5], mm[6], mm[7], mm[9], mm[10], mm[11] + local n11, n12, n13 = b2 * c3 - b3 * c2, b3 * c1 - b1 * c3, b1 * c2 - b2 * c1 + local n21, n22, n23 = c2 * a3 - c3 * a2, c3 * a1 - c1 * a3, c1 * a2 - c2 * a1 + local n31, n32, n33 = a2 * b3 - a3 * b2, a3 * b1 - a1 * b3, a1 * b2 - a2 * b1 + local sgn = if a1 * n11 + a2 * n12 + a3 * n13 < 0 then -1 else 1 + for i = 0, nv - 1 do + local x, y, z = vals[i * sc + 1], vals[i * sc + 2], vals[i * sc + 3] + -- column j of the cofactor matrix multiplies component j: (inverse transpose) * n + local nx = n11 * x + n21 * y + n31 * z + local ny = n12 * x + n22 * y + n32 * z + local nz = n13 * x + n23 * y + n33 * z + local l = math.sqrt(nx * nx + ny * ny + nz * nz) + if l > 0 then + nx, ny, nz = sgn * nx / l, sgn * ny / l, sgn * nz / l + end + dst[n0 + i * 3 + 1] = f32(nx) + dst[n0 + i * 3 + 2] = f32(ny) + dst[n0 + i * 3 + 3] = f32(nz) + end + else + for i = 0, nv - 1 do + for c = 1, ac do + dst[n0 + i * ac + c] = if c <= sc then vals[i * sc + c] else f + end + end + end + end + end + local fs, cs, ferr = faces(prim, nv) + if ferr then + return nil, ferr + end + local flip = false + if not identity then + local mm = m :: { number } + local det = mm[1] * (mm[6] * mm[11] - mm[7] * mm[10]) - mm[5] * (mm[2] * mm[11] - mm[3] * mm[10]) + mm[9] * (mm[2] * mm[7] - mm[3] * mm[6]) + flip = det < 0 + end + if fs ~= "points" and fs ~= "skip" then + anyFaces = true + local base = merged.count + local cl: { number } = cs + local p = 0 + local nf = if fs then #fs else #cl // 3 + for f = 1, nf do + local s = if fs then fs[f] else 3 + if triangulate then + for k = 2, s - 1 do + table.insert(sizes, 3) + local a, b, c = cl[p + 1], cl[p + k], cl[p + k + 1] + if flip then + b, c = c, b + end + table.insert(corners, base + a) + table.insert(corners, base + b) + table.insert(corners, base + c) + end + else + table.insert(sizes, s) + if flip then + table.insert(corners, base + cl[p + 1]) + for k = s, 2, -1 do + table.insert(corners, base + cl[p + k]) + end + else + for k = 1, s do + table.insert(corners, base + cl[p + k]) + end + end + end + p += s + end + end + info.faceCount = #sizes - info.firstFace + merged.count += nv + table.insert(merged.parts, info) + end + merged.sizes = if anyFaces then sizes else nil + return merged, nil +end + +return Flatten +end +__FILES["codecs/model/Minecraft"] = function() + +-- codecs/model/Minecraft: what Minecraft's voxel formats share (model/schematic, model/mca). New code. +local Types = __include("Types") +local Nbt = __include("codecs/text/Nbt") +local Colors = __include("codecs/model/Minecraft/Colors") +local Legacy = __include("codecs/model/Minecraft/Legacy") +local Packed = __include("codecs/model/Minecraft/Packed") + +local Minecraft = {} + +Minecraft.Packed = Packed +Minecraft.Legacy = Legacy + +function Minecraft.parseState(s: string): (string, { { string } }) + local name, rest = string.match(s, "^%s*([^%[%s]*)%s*(.*)$") + local n = name or "" + if n ~= "" and not string.find(n, ":", 1, true) then + n = "minecraft:" .. n + end + local props = {} + local body = rest and string.match(rest :: string, "^%[(.*)%]%s*$") + if body then + for pair in string.gmatch(body, "[^,]+") do + local k, v = string.match(pair, "^%s*([^=%s]+)%s*=%s*(.-)%s*$") + if k then + table.insert(props, { k, v :: string }) + end + end + end + return n, props +end + +function Minecraft.stateString(name: string, props: { any }?): string + if not props or next(props) == nil then + return name + end + local parts = {} + if props[1] ~= nil then + for _, kv in props do + table.insert(parts, kv[1] .. "=" .. tostring(kv[2])) + end + else + for _, k in Types.keys(props) do + table.insert(parts, tostring(k) .. "=" .. tostring((props :: any)[k])) + end + end + return name .. "[" .. table.concat(parts, ",") .. "]" +end + +function Minecraft.stateFromNbt(c: any): string? + if type(c) ~= "table" or type(c.Name) ~= "string" then + return nil + end + local props = {} + if type(c.Properties) == "table" then + for _, k in Types.keys(c.Properties) do + local v = c.Properties[k] + table.insert(props, { k, if type(v) == "string" then v else tostring(Nbt.number(v) or v) }) + end + end + return Minecraft.stateString(c.Name, props) +end + +function Minecraft.stateToNbt(s: string): { [string]: any } + local name, props = Minecraft.parseState(s) + local c = Types.object({ Name = name }, { "Name" }) + if #props > 0 then + local p, keys = {}, {} + for _, kv in props do + p[kv[1]] = kv[2] + table.insert(keys, kv[1]) + end + Types.set(c, "Properties", Types.object(p, keys)) + end + return c +end + +function Minecraft.baseName(s: string): string + local name = string.match(s, "^%s*([^%[%s]*)") or "" + return string.match(name, ":(.*)$") or name +end + +local AIR = { air = true, cave_air = true, void_air = true, structure_void = true, light = true, barrier = true, moving_piston = true } +function Minecraft.isAir(s: string): boolean + return AIR[Minecraft.baseName(s)] == true +end + +local function hex(h: string): { number } + local c = { tonumber(string.sub(h, 1, 2), 16) or 0, tonumber(string.sub(h, 3, 4), 16) or 0, tonumber(string.sub(h, 5, 6), 16) or 0, 255 } + if #h >= 8 then + c[4] = tonumber(string.sub(h, 7, 8), 16) or 255 + end + return c +end +local function list(s: string): { { number } } + local out = {} + for h in string.gmatch(s, "%x+") do + table.insert(out, hex(h)) + end + return out +end + +local EXACT: { [string]: { number } } = {} +for name, h in string.gmatch(Colors.BLOCKS, "([%w_]+)=(%x+)") do + EXACT[name :: string] = hex(h :: string) +end +local WOOL, CONCRETE, TERRACOTTA = list(Colors.WOOL), list(Colors.CONCRETE), list(Colors.TERRACOTTA) +local PLANKS, BARK, LEAVES = list(Colors.PLANKS), list(Colors.BARK), list(Colors.LEAVES) +-- longest prefixes first, so light_blue wins over blue and dark_oak over oak +local function byLength(names: { string }): { { any } } + local out: { { any } } = {} + for i, n in names do + table.insert(out, { n, i }) + end + table.sort(out, function(a: { any }, b: { any }): boolean + return #(a[1] :: string) > #(b[1] :: string) + end) + return out +end +local DYES, WOODS = byLength(Colors.DYES), byLength(Colors.WOODS) +local SUFFIXES = { + "_wall_hanging_sign", "_hanging_sign", "_wall_sign", "_sign", "_fence_gate", "_fence", "_pressure_plate", "_button", + "_trapdoor", "_door", "_stairs", "_slab", "_wall", "_pane", "_carpet", "_wall_banner", "_banner", "_bars", +} +local PREFIXES = { "waxed_", "potted_", "flowing_", "infested_", "lit_", "unlit_", "unpowered_", "powered_", "chipped_", "damaged_" } +local CORAL: { [string]: { number } } = { tube = hex("3157d0"), brain = hex("cf5b9f"), bubble = hex("a118a0"), fire = hex("a6252f"), horn = hex("d8c53e") } +local FALLBACK = hex("909090") + +local function mix(c: { number }, w: { number }, t: number): { number } + return { math.floor(c[1] + (w[1] - c[1]) * t + 0.5), math.floor(c[2] + (w[2] - c[2]) * t + 0.5), math.floor(c[3] + (w[3] - c[3]) * t + 0.5), c[4] } +end + +local resolve: (string, number) -> { number }? + +local function family(n: string): { number }? + for _, d in DYES do + local pre = d[1] .. "_" + if string.sub(n, 1, #pre) == pre then + local rest = string.sub(n, #pre + 1) + local i = d[2] + if rest == "concrete" then + return CONCRETE[i] + elseif rest == "concrete_powder" then + return mix(CONCRETE[i], { 255, 255, 255, 255 }, 0.2) + elseif rest == "terracotta" then + return TERRACOTTA[i] + elseif string.find(rest, "glass", 1, true) then + local c = table.clone(WOOL[i]) + c[4] = 0x80 + return c + end + return WOOL[i] + end + end + local stripped = string.match(n, "^stripped_(.*)$") + for _, w in WOODS do + local pre = w[1] .. "_" + local m = stripped or n + if string.sub(m, 1, #pre) == pre then + local rest = string.sub(m, #pre + 1) + local i = w[2] + if stripped then + return PLANKS[i] + elseif rest == "log" or rest == "wood" or rest == "stem" or rest == "hyphae" then + return BARK[i] + elseif rest == "leaves" or rest == "sapling" or rest == "propagule" then + return LEAVES[i] + elseif rest == "block" and w[1] == "bamboo" then + return EXACT.bamboo_block + end + return PLANKS[i] + end + end + return nil +end + +local function keywords(n: string): { number }? + if string.find(n, "copper", 1, true) then + return if string.find(n, "oxidized", 1, true) then EXACT.oxidized_copper + elseif string.find(n, "weathered", 1, true) then EXACT.weathered_copper + elseif string.find(n, "exposed", 1, true) then EXACT.exposed_copper + else EXACT.copper_block + elseif string.find(n, "coral", 1, true) then + if string.find(n, "dead", 1, true) then + return hex("857e79") + end + for k, c in CORAL do + if string.find(n, k, 1, true) then + return c + end + end + elseif string.find(n, "_ore$") then + return if string.find(n, "deepslate", 1, true) then EXACT.deepslate + elseif string.find(n, "nether", 1, true) then EXACT.netherrack + else EXACT.stone + end + for _, k in { "deepslate", "blackstone", "sandstone", "prismarine", "purpur", "quartz", "glass", "ice", "stone", "brick", "nether", "end", "mushroom", "grass", "candle", "head", "skull", "rail", "sign", "tulip", "orchid" } do + if string.find(n, k, 1, true) then + local alias = ({ glass = "glass", ice = "ice", stone = "stone", brick = "bricks", nether = "nether_bricks", ["end"] = "end_stone", mushroom = "mushroom_stem", grass = "short_grass", candle = "white_wool", head = "polished_andesite", skull = "bone_block", rail = "rail", sign = "oak_planks", tulip = "red_tulip", orchid = "blue_orchid", deepslate = "deepslate", blackstone = "blackstone", sandstone = "sandstone", prismarine = "prismarine", purpur = "purpur_block", quartz = "quartz_block" } :: any)[k] + return EXACT[alias] + end + end + return nil +end + +resolve = function(n: string, depth: number): { number }? + if depth > 4 then + return nil + end + local c = EXACT[n] + if c then + return c + end + local renamed = Legacy.RENAMED[n] + if renamed then + return resolve(renamed, depth + 1) + end + for _, p in PREFIXES do + if string.sub(n, 1, #p) == p then + return resolve(string.sub(n, #p + 1), depth + 1) + end + end + c = family(n) + if c then + return c + end + for _, sfx in SUFFIXES do + if #n > #sfx and string.sub(n, -#sfx) == sfx then + local base = string.sub(n, 1, #n - #sfx) + for _, form in { base, base .. "s", base .. "_block", base .. "_planks" } do + local fc = EXACT[form] or family(form) + if fc then + return fc + end + end + return resolve(base, depth + 1) + end + end + return keywords(n) +end + +local cache: { [string]: { number } | false } = {} +function Minecraft.color(s: string): { number }? + local hit = cache[s] + if hit ~= nil then + return hit or nil + end + local name, props = Minecraft.parseState(s) + local n = string.match(name, ":(.*)$") or name + local res: { number }? = nil + if not AIR[n] then + local variants = Legacy.VARIANTS[n] or (if n == "double_wooden_slab" then Legacy.VARIANTS.planks else nil) + if variants then + local data = 0 + for _, kv in props do + if kv[1] == "data" then + data = tonumber(kv[2]) or 0 + end + end + local v = variants[data % (Legacy.MASK[n] or 16) + 1] or variants[1] + res = resolve(v, 0) + end + res = res or resolve(n, 0) or FALLBACK + end + cache[s] = res or false + return res +end + +local REVERSE: { [string]: { number } }? = nil +local function reverse(): { [string]: { number } } + if REVERSE then + return REVERSE + end + local r: { [string]: { number } } = {} + local byName: { [string]: number } = {} + for i, n in Legacy.NAMES do + if n ~= "-" then + byName[n] = i - 1 + end + end + for legacy, modern in Legacy.RENAMED do + r[modern] = { byName[legacy], 0 } + end + for legacy, variants in Legacy.VARIANTS do + for d, v in variants do + if r[v] == nil then + r[v] = { byName[legacy], d - 1 } + end + end + end + for n, id in byName do + if r[n] == nil then + r[n] = { id, 0 } + end + end + REVERSE = r + return r +end + +-- the rest of the data value stays as [data=N], so legacyId gives it back exactly +function Minecraft.legacyState(id: number, data: number): string + local n = Legacy.NAMES[id + 1] + if n == nil or n == "-" then + return "minecraft:legacy_" .. id .. (if data ~= 0 then "[data=" .. data .. "]" else "") + end + local variants = Legacy.VARIANTS[n] + if variants then + local idx = data % (Legacy.MASK[n] or 16) + local v = variants[idx + 1] + if v then + return "minecraft:" .. v .. (if data ~= idx then "[data=" .. data .. "]" else "") + end + end + return "minecraft:" .. (Legacy.RENAMED[n] or n) .. (if data ~= 0 then "[data=" .. data .. "]" else "") +end + +function Minecraft.legacyId(s: string): (number?, number?) + local name, props = Minecraft.parseState(s) + local n = string.match(name, ":(.*)$") or name + local id: number?, data = nil, 0 + local lid = string.match(n, "^legacy_(%d+)$") + if lid then + id = tonumber(lid) + else + local e = reverse()[n] + if e then + id, data = e[1], e[2] + end + end + if id == nil then + return nil, nil + end + for _, kv in props do + if kv[1] == "data" then + data = (tonumber(kv[2]) or data) % 16 + end + end + return id, data +end + +function Minecraft.voxels(sx: number, sy: number, sz: number, states: { string }, indices: buffer): Types.Voxels + local v = Types.Voxels.new(sx, sy, sz) + local lut = buffer.create(#states) + local slots: { [string]: number } = {} + local used = 0 + for i, s in states do + local c = Minecraft.color(s) + local slot = 0 + if c then + local key = string.format("%d,%d,%d,%d", c[1], c[2], c[3], c[4]) + slot = slots[key] + if not slot then + if used < 255 then + used += 1 + slot = used + v.palette[slot] = { c[1], c[2], c[3], c[4] } + else + local best, bd = 1, math.huge + for k = 1, 255 do + local p = v.palette[k] + local d = (p[1] - c[1]) ^ 2 + (p[2] - c[2]) ^ 2 + (p[3] - c[3]) ^ 2 + (p[4] - c[4]) ^ 2 + if d < bd then + best, bd = k, d + end + end + slot = best + end + slots[key] = slot + end + end + buffer.writeu8(lut, i - 1, slot) + end + local n = sx * sy * sz + local data, nstates = v.data, #states + for i = 0, n - 1 do + local s = buffer.readu16(indices, i * 2) + buffer.writeu8(data, i, if s < nstates then buffer.readu8(lut, s) else 0) + end + v.blocks = { palette = states, data = indices } + return v +end + +local CANDIDATES: { { any } }? = nil +local function candidates(): { { any } } + if CANDIDATES then + return CANDIDATES + end + local out = {} + for _, d in Colors.DYES do + for _, kind in { "wool", "concrete", "terracotta" } do + local s = "minecraft:" .. d .. "_" .. kind + table.insert(out, { s, Minecraft.color(s) }) + end + end + for _, w in Colors.WOODS do + local s = "minecraft:" .. w .. "_planks" + table.insert(out, { s, Minecraft.color(s) }) + end + for _, n in { "stone", "cobblestone", "bricks", "sand", "red_sand", "dirt", "grass_block", "gravel", "deepslate", "sandstone", "quartz_block", "obsidian", "netherrack", "end_stone", "prismarine", "dark_prismarine", "snow_block", "gold_block", "iron_block", "diamond_block", "emerald_block", "lapis_block", "redstone_block", "coal_block", "glowstone", "sponge", "melon", "pumpkin", "hay_block", "bone_block", "clay", "packed_ice", "nether_bricks", "purpur_block", "andesite", "diorite", "granite", "calcite", "tuff", "blackstone", "mud", "moss_block", "amethyst_block", "copper_block", "oxidized_copper" } do + local s = "minecraft:" .. n + table.insert(out, { s, Minecraft.color(s) }) + end + CANDIDATES = out + return out +end + +function Minecraft.nearestBlock(c: { number }): string + local a = c[4] or 255 + if a < 200 then + local best, bd = "minecraft:glass", math.huge + for i, d in Colors.DYES do + local w = WOOL[i] + local dist = (w[1] - c[1]) ^ 2 + (w[2] - c[2]) ^ 2 + (w[3] - c[3]) ^ 2 + if dist < bd then + best, bd = "minecraft:" .. d .. "_stained_glass", dist + end + end + return best + end + local best, bd = "minecraft:stone", math.huge + for _, cand in candidates() do + local k = cand[2] + local dist = (k[1] - c[1]) ^ 2 + (k[2] - c[2]) ^ 2 + (k[3] - c[3]) ^ 2 + if dist < bd then + best, bd = cand[1], dist + end + end + return best +end + +function Minecraft.blocksOf(v: Types.Voxels): ({ string }?, any) + local n = v.size[1] * v.size[2] * v.size[3] + local b = v.blocks + if b then + if type(b.palette) ~= "table" or type(b.data) ~= "buffer" or buffer.len(b.data) < n * 2 then + return nil, "voxels.blocks must hold a palette and a u16 per cell" + end + if #b.palette == 0 or #b.palette > 65536 then + return nil, "voxels.blocks.palette must have 1 .. 65536 states" + end + return b.palette, b.data + end + local states = { "minecraft:air" } + local slotOf: { [number]: number } = { [0] = 0 } + local byState: { [string]: number } = { ["minecraft:air"] = 0 } + local out = buffer.create(n * 2) + local data = v.data + for i = 0, n - 1 do + local p = buffer.readu8(data, i) + local s = slotOf[p] + if s == nil then + local col = v.palette[p] or { 128, 128, 128, 255 } + local st = Minecraft.nearestBlock(col) + s = byState[st] + if s == nil then + table.insert(states, st) + s = #states - 1 + byState[st] = s + end + slotOf[p] = s + end + buffer.writeu16(out, i * 2, s :: number) + end + return states, out +end + +-- block entities: Sponge v3 { pos = { x, y, z }, id, data } <-> flat { x, y, z, id, ... } (MCEdit, Litematica, +-- chunks) / Sponge v1 / v2 { Pos, Id, ... } +local function int(v: any): number? + local n = Nbt.number(v) + if n == nil or n ~= n or n % 1 ~= 0 then + return nil + end + return n +end +local function ints(v: any): { number }? + if Nbt.isTag(v) and v.type == "intArray" then + return v.value + elseif type(v) == "table" and not Nbt.isTag(v) and (v :: any)[1] ~= nil then + local out: { number } = {} + for i, x in v :: { any } do + out[i] = Nbt.number(x) or 0 + end + return out + end + return nil +end +Minecraft.int = int +Minecraft.ints = ints + +local function rest(c: any, skip: { [string]: boolean }): { [string]: any } + local out, keys = {}, {} + for _, k in Types.keys(c) do + if not skip[k] then + out[k] = c[k] + table.insert(keys, k) + end + end + return Types.object(out, keys) +end + +local FLAT_SKIP = { x = true, y = true, z = true, id = true } +local POS_SKIP = { Pos = true, Id = true } + +function Minecraft.blockEntity(c: any, style: string): any + if type(c) ~= "table" or Nbt.isTag(c) then + return nil + end + if style == "flat" then + return { pos = { int(c.x) or 0, int(c.y) or 0, int(c.z) or 0 }, id = if type(c.id) == "string" then c.id else nil, data = rest(c, FLAT_SKIP) } + end + local p = ints(c.Pos) or { 0, 0, 0 } + local data = if style == "data" then (if type(c.Data) == "table" then c.Data else Types.object()) else rest(c, POS_SKIP) + return { pos = { p[1] or 0, p[2] or 0, p[3] or 0 }, id = if type(c.Id) == "string" then c.Id else nil, data = data } +end + +function Minecraft.flatBlockEntity(be: any, style: string): any + local o = Types.object() + local data = if type(be.data) == "table" then be.data else Types.object() + if style == "flat" then + Types.set(o, "x", be.pos[1]) + Types.set(o, "y", be.pos[2]) + Types.set(o, "z", be.pos[3]) + if be.id then + Types.set(o, "id", be.id) + end + for _, k in Types.keys(data) do + if not FLAT_SKIP[k] then + Types.set(o, k, data[k]) + end + end + return o + end + Types.set(o, "Pos", Nbt.intArray({ be.pos[1], be.pos[2], be.pos[3] })) + if be.id then + Types.set(o, "Id", be.id) + end + if style == "data" then + Types.set(o, "Data", data) + else + for _, k in Types.keys(data) do + if not POS_SKIP[k] then + Types.set(o, k, data[k]) + end + end + end + return o +end + +return Minecraft +end +__FILES["codecs/model/Minecraft/Colors"] = function() + +-- codecs/model/Minecraft/Colors: default Minecraft block colours as name=rrggbb or name=rrggbbaa. +-- Hand-picked approximations; no game assets or wiki tables copied. +local Colors = {} + +Colors.BLOCKS = [[ +stone=7d7d7d granite=956756 polished_granite=9a6a59 diorite=bcbcbc polished_diorite=c0c0c2 andesite=888889 +polished_andesite=848686 grass_block=6d9a3f dirt=866043 coarse_dirt=77553b podzol=5b3f18 rooted_dirt=90674c +mud=3c3a3d cobblestone=7a7a7a bedrock=555555 sand=dbcf9f red_sand=be6621 gravel=837f7e suspicious_sand=d6c996 +suspicious_gravel=817c7b sandstone=d8cb9b chiseled_sandstone=d8ca9b cut_sandstone=d9cd9e smooth_sandstone=dfd5a5 +red_sandstone=b5621f cut_red_sandstone=bc6620 chiseled_red_sandstone=b7601e smooth_red_sandstone=b5621f +sponge=c3c04a wet_sponge=aaab3c glass=c0f5fe50 tinted_glass=2c262ec0 lapis_block=1f438c gold_block=f6d03d +iron_block=dcdcdc diamond_block=62ede4 emerald_block=2acb57 redstone_block=af1805 coal_block=101010 +netherite_block=433e40 copper_block=c06c50 exposed_copper=a17e68 weathered_copper=6c9a6f oxidized_copper=52a284 +cut_copper=bf6b51 raw_iron_block=a6896b raw_gold_block=dda92e raw_copper_block=9a6a4e amethyst_block=8562b8 +budding_amethyst=84609f bricks=976253 bookshelf=75603d chiseled_bookshelf=b29159 mossy_cobblestone=6e7660 +obsidian=0f0a18 crying_obsidian=200a3c tnt=db4130 spawner=24364a chest=a0742d trapped_chest=a0742d +ender_chest=2a3b3c crafting_table=81633c furnace=6d6d6d snow=f9fefe snow_block=f9fefe powder_snow=f8fdfd +ice=92b8fec8 packed_ice=8db4fa blue_ice=74a7fd frosted_ice=8cb4fac8 clay=a0a6b3 pumpkin=c6761a +carved_pumpkin=c27118 jack_o_lantern=d79a32 netherrack=612626 soul_sand=513e32 soul_soil=4b3a2e basalt=505055 +polished_basalt=636367 smooth_basalt=48484e glowstone=ab8354 magma_block=8e3f1f nether_bricks=2c1518 +red_nether_bricks=450709 cracked_nether_bricks=281417 chiseled_nether_bricks=2f171c nether_wart_block=720202 +warped_wart_block=167879 end_stone=dbdea0 end_stone_bricks=dae0a2 purpur_block=a97ea9 purpur_pillar=ab81ab +prismarine=63a29a prismarine_bricks=63ab9e dark_prismarine=335b4b sea_lantern=acc7be hay_block=a68b0c +terracotta=985e43 quartz_block=ebe5de smooth_quartz=ece6df quartz_bricks=eae5dd quartz_pillar=ebe6e0 +chiseled_quartz_block=e7e2da smooth_stone=9e9e9e stone_bricks=7a7979 mossy_stone_bricks=737969 +cracked_stone_bricks=767676 chiseled_stone_bricks=777777 deepslate=505053 cobbled_deepslate=4d4d51 +polished_deepslate=484849 deepslate_bricks=474747 cracked_deepslate_bricks=414141 deepslate_tiles=373737 +cracked_deepslate_tiles=343434 chiseled_deepslate=363637 reinforced_deepslate=505350 tuff=6c6d67 +polished_tuff=626a63 tuff_bricks=626660 calcite=dfe0dc dripstone_block=866b5c pointed_dripstone=816757 +moss_block=596d2d moss_carpet=596d2d pale_moss_block=6b7069 melon=6f9118 cactus=587f28 sugar_cane=95c165 +bamboo=5d8f1e bamboo_block=7f9030 stripped_bamboo_block=c0ad50 water=3f76e4b4 bubble_column=3f76e4b4 +lava=cf5b14 short_grass=5b8a32 grass=5b8a32 tall_grass=5b8a32 fern=586e30 large_fern=586e30 dead_bush=6b4f29 +vine=3c6e18 glow_lichen=708079 lily_pad=208030 seagrass=307b16 tall_seagrass=307b16 kelp=3b7f22 +kelp_plant=3b7f22 dried_kelp_block=323b27 red_mushroom_block=c82e2d brown_mushroom_block=957051 +mushroom_stem=cbc4b9 red_mushroom=d84a3e brown_mushroom=9a7759 slime_block=6fc05bc8 honey_block=fba92fc8 +honeycomb_block=e5941e bone_block=e1ddc9 shroomlight=f19346 target=e2aa9e respawn_anchor=4b1e86 +lodestone=939599 blackstone=2a2328 polished_blackstone=35303b polished_blackstone_bricks=302a32 +cracked_polished_blackstone_bricks=2c2629 chiseled_polished_blackstone=35303b gilded_blackstone=382b26 +crimson_nylium=831f1f warped_nylium=2b7265 crimson_roots=7e0812 warped_roots=148a7c packed_mud=8e6b50 +mud_bricks=89684f sculk=0d1e24 sculk_catalyst=2d3a3b sculk_sensor=074654 sculk_shrieker=c6cdab +redstone_lamp=5f361e note_block=58392a jukebox=5d4030 beacon=75dcd7 observer=626262 piston=9a8d6c +sticky_piston=8b9c66 piston_head=9a8d6c dispenser=7a7a7a dropper=7a7a7a hopper=434343 anvil=444444 +chipped_anvil=444444 damaged_anvil=444444 cauldron=4a4a4a rail=7d6c4b powered_rail=8a6d3e detector_rail=7b6853 +activator_rail=74574b ladder=7c5f35 scaffolding=aa8449 lantern=6a5b54 soul_lantern=4a6366 campfire=6e5638 +soul_campfire=4e5d5d barrel=86643b smoker=5a5853 blast_furnace=6c6b6b cartography_table=685032 +fletching_table=c5b485 smithing_table=39394a loom=8e7965 stonecutter=7b7672 grindstone=8e8e8e composter=704a26 +beehive=b8945b bee_nest=c5964b farmland=8f6646 dirt_path=94793f mycelium=6f6365 torch=ffd80060 +wall_torch=ffd80060 soul_torch=6be1e360 redstone_torch=c0210f60 redstone_wire=9e0b0060 lever=6e6e6e60 +cobweb=e4e9ea80 iron_bars=8b8d8b90 chain=3a404e90 end_rod=e0d8d0 chorus_plant=5e395e chorus_flower=977a97 +dragon_egg=0c0910 end_portal_frame=5b7860 enchanting_table=813838 brewing_stand=7a654f flower_pot=7d4536 +cake=f8dede conduit=9f8b71 lectern=ad8a54 bell=fdd533 decorated_pot=8f4f35 crafter=7a6c64 +trial_spawner=3b4a55 vault=46545c heavy_core=4c5056 command_block=b5886c chain_command_block=829f8f +repeating_command_block=8370b0 structure_block=58475b jigsaw=50455a +dandelion=e0c41c poppy=c42b1a blue_orchid=2aa8d0 allium=b878e8 azure_bluet=dfe6d7 red_tulip=c43b1b +orange_tulip=e07e1b white_tulip=e0e8db pink_tulip=e8b8d8 oxeye_daisy=e8e8c8 cornflower=4f76d8 +lily_of_the_valley=e8e8e8 wither_rose=2a2c18 sunflower=f0c71d lilac=b88cb8 rose_bush=b02a1e peony=e8b8e0 +torchflower=d9b14e pitcher_plant=7a97c8 pink_petals=f0b8d0 spore_blossom=d066a8 azalea=5f7a2c +flowering_azalea=7c6b6e sweet_berry_bush=3f6a2f cocoa=8c5428 wheat=a99c30 carrots=4a9a1e potatoes=4c9a2a +beetroots=5a8a2a nether_wart=8a1818 crimson_fungus=8a2525 warped_fungus=2a7a6e twisting_vines=148a7c +weeping_vines=8a1414 hanging_roots=a17561 big_dripleaf=6b8f34 small_dripleaf=6b8f34 cave_vines=5a6d23 +frogspawn=66605ca0 sniffer_egg=8a5045 turtle_egg=dcd8b8 sea_pickle=6a7030 mangrove_roots=4b3c27 +muddy_mangrove_roots=46413a ochre_froglight=f6e8a6 verdant_froglight=dcf0d6 pearlescent_froglight=f1e1ea +creaking_heart=5a4a3c resin_block=d9661c resin_bricks=ce5a1a +]] + +Colors.DYES = { "white", "orange", "magenta", "light_blue", "yellow", "lime", "pink", "gray", "light_gray", "cyan", "purple", "blue", "brown", "green", "red", "black" } +Colors.WOOL = "e9ecec f07613 bd44b3 3aafd9 f8c527 70b919 ed8dac 3e4447 8e8e86 158991 792aac 35399d 724728 546d1b a12722 141519" +Colors.CONCRETE = "cfd5d6 e06100 a9309f 2389c6 f0af15 5ea818 d5658e 36393d 7d7d73 157788 64209c 2c2e8f 603b1f 495b24 8e2020 080a0f" +Colors.TERRACOTTA = "d1b2a1 a15325 95576c 716c89 ba8523 677534 a14e4e 392a23 876a61 575b5b 764656 4a3b5b 4d3323 4c532a 8f3d2e 251610" + +Colors.WOODS = { "oak", "spruce", "birch", "jungle", "acacia", "dark_oak", "mangrove", "cherry", "pale_oak", "bamboo", "crimson", "warped" } +Colors.PLANKS = "a2834f 735531 c0af79 a07351 a85a32 432b14 763631 e3b3ad e4d9d3 c1ad50 653147 2b6963" +Colors.BARK = "6d5533 3a2510 d8d7d2 55441a 676157 3e2f17 543a26 371b22 524a46 7f9030 5c1919 3a3a4d" +Colors.LEAVES = "4a7a20 3d5d3d 5f8a3c 3f8a1c 4b7a1e 3c6a18 4b8a28 e5adc2 878d76 5d8f1e 831f1f 2b7265" + +return Colors +end +__FILES["codecs/model/Minecraft/Legacy"] = function() + +-- codecs/model/Minecraft/Legacy: pre-1.13 numeric block ids and their data-value variants. +-- From the Minecraft wiki "Java Edition data values/Pre-flattening" (facts, not code). +local Legacy = {} + +local function words(s: string): { string } + local out = {} + for w in string.gmatch(s, "%S+") do + table.insert(out, w) + end + return out +end + +-- ids 0 .. 255 (NAMES[id + 1]), "-" = unused +Legacy.NAMES = words([[air stone grass dirt cobblestone planks sapling bedrock flowing_water water flowing_lava +lava sand gravel gold_ore iron_ore coal_ore log leaves sponge glass lapis_ore lapis_block dispenser sandstone noteblock +bed golden_rail detector_rail sticky_piston web tallgrass deadbush piston piston_head wool piston_extension +yellow_flower red_flower brown_mushroom red_mushroom gold_block iron_block double_stone_slab stone_slab brick_block tnt +bookshelf mossy_cobblestone obsidian torch fire mob_spawner oak_stairs chest redstone_wire diamond_ore diamond_block +crafting_table wheat farmland furnace lit_furnace standing_sign wooden_door ladder rail stone_stairs wall_sign lever +stone_pressure_plate iron_door wooden_pressure_plate redstone_ore lit_redstone_ore unlit_redstone_torch redstone_torch +stone_button snow_layer ice snow cactus clay reeds jukebox fence pumpkin netherrack soul_sand glowstone portal +lit_pumpkin cake unpowered_repeater powered_repeater stained_glass trapdoor monster_egg stonebrick +brown_mushroom_block red_mushroom_block iron_bars glass_pane melon_block pumpkin_stem melon_stem vine fence_gate +brick_stairs stone_brick_stairs mycelium waterlily nether_brick nether_brick_fence nether_brick_stairs nether_wart +enchanting_table brewing_stand cauldron end_portal end_portal_frame end_stone dragon_egg redstone_lamp +lit_redstone_lamp double_wooden_slab wooden_slab cocoa sandstone_stairs emerald_ore ender_chest tripwire_hook tripwire +emerald_block spruce_stairs birch_stairs jungle_stairs command_block beacon cobblestone_wall flower_pot carrots +potatoes wooden_button skull anvil trapped_chest light_weighted_pressure_plate heavy_weighted_pressure_plate +unpowered_comparator powered_comparator daylight_detector redstone_block quartz_ore hopper quartz_block quartz_stairs +activator_rail dropper stained_hardened_clay stained_glass_pane leaves2 log2 acacia_stairs dark_oak_stairs slime +barrier iron_trapdoor prismarine sea_lantern hay_block carpet hardened_clay coal_block packed_ice double_plant +standing_banner wall_banner daylight_detector_inverted red_sandstone red_sandstone_stairs double_stone_slab2 +stone_slab2 spruce_fence_gate birch_fence_gate jungle_fence_gate dark_oak_fence_gate acacia_fence_gate spruce_fence +birch_fence jungle_fence dark_oak_fence acacia_fence spruce_door birch_door jungle_door acacia_door dark_oak_door +end_rod chorus_plant chorus_flower purpur_block purpur_pillar purpur_stairs purpur_double_slab purpur_slab end_bricks +beetroots grass_path end_gateway repeating_command_block chain_command_block frosted_ice magma nether_wart_block +red_nether_brick bone_block structure_void observer white_shulker_box orange_shulker_box magenta_shulker_box +light_blue_shulker_box yellow_shulker_box lime_shulker_box pink_shulker_box gray_shulker_box silver_shulker_box +cyan_shulker_box purple_shulker_box blue_shulker_box brown_shulker_box green_shulker_box red_shulker_box +black_shulker_box white_glazed_terracotta orange_glazed_terracotta magenta_glazed_terracotta +light_blue_glazed_terracotta yellow_glazed_terracotta lime_glazed_terracotta pink_glazed_terracotta +gray_glazed_terracotta silver_glazed_terracotta cyan_glazed_terracotta purple_glazed_terracotta +blue_glazed_terracotta brown_glazed_terracotta green_glazed_terracotta red_glazed_terracotta black_glazed_terracotta +concrete concrete_powder - - structure_block]]) + +-- one-to-one renames only, so the way back is exact (lit_furnace, powered_repeater, ... keep their legacy names) +Legacy.RENAMED = { + grass = "grass_block", brick_block = "bricks", stonebrick = "stone_bricks", hardened_clay = "terracotta", + melon_block = "melon", lit_pumpkin = "jack_o_lantern", slime = "slime_block", magma = "magma_block", + red_nether_brick = "red_nether_bricks", nether_brick = "nether_bricks", end_bricks = "end_stone_bricks", + mob_spawner = "spawner", web = "cobweb", snow_layer = "snow", snow = "snow_block", noteblock = "note_block", + quartz_ore = "nether_quartz_ore", reeds = "sugar_cane", waterlily = "lily_pad", + tallgrass = "short_grass", grass_path = "dirt_path", double_stone_slab = "smooth_stone", + stone_slab = "smooth_stone_slab", deadbush = "dead_bush", yellow_flower = "dandelion", + fence = "oak_fence", fence_gate = "oak_fence_gate", + wooden_door = "oak_door", trapdoor = "oak_trapdoor", wooden_pressure_plate = "oak_pressure_plate", + wooden_button = "oak_button", stone_stairs = "cobblestone_stairs", standing_sign = "oak_sign", + wall_sign = "oak_wall_sign", golden_rail = "powered_rail", portal = "nether_portal", piston_extension = "moving_piston", + silver_shulker_box = "light_gray_shulker_box", silver_glazed_terracotta = "light_gray_glazed_terracotta", + monster_egg = "infested_stone", + standing_banner = "white_banner", wall_banner = "white_wall_banner", skull = "skeleton_skull", + bed = "red_bed", +} :: { [string]: string } + +-- legacy names whose data value selects the variant: the modern names by data value (0-based) +local DYED = "white orange magenta light_blue yellow lime pink gray light_gray cyan purple blue brown green red black" +local function dyed(suffix: string): { string } + local out = {} + for i, d in words(DYED) do + out[i] = d .. "_" .. suffix + end + return out +end +Legacy.VARIANTS = { + stone = { "stone", "granite", "polished_granite", "diorite", "polished_diorite", "andesite", "polished_andesite" }, + dirt = { "dirt", "coarse_dirt", "podzol" }, + planks = { "oak_planks", "spruce_planks", "birch_planks", "jungle_planks", "acacia_planks", "dark_oak_planks" }, + wooden_slab = { "oak_slab", "spruce_slab", "birch_slab", "jungle_slab", "acacia_slab", "dark_oak_slab" }, + sapling = { "oak_sapling", "spruce_sapling", "birch_sapling", "jungle_sapling", "acacia_sapling", "dark_oak_sapling" }, + sand = { "sand", "red_sand" }, + log = { "oak_log", "spruce_log", "birch_log", "jungle_log" }, -- data % 4 + log2 = { "acacia_log", "dark_oak_log" }, + leaves = { "oak_leaves", "spruce_leaves", "birch_leaves", "jungle_leaves" }, + leaves2 = { "acacia_leaves", "dark_oak_leaves" }, + sponge = { "sponge", "wet_sponge" }, + sandstone = { "sandstone", "chiseled_sandstone", "cut_sandstone" }, + red_sandstone = { "red_sandstone", "chiseled_red_sandstone", "cut_red_sandstone" }, + stonebrick = { "stone_bricks", "mossy_stone_bricks", "cracked_stone_bricks", "chiseled_stone_bricks" }, + quartz_block = { "quartz_block", "chiseled_quartz_block", "quartz_pillar" }, + prismarine = { "prismarine", "prismarine_bricks", "dark_prismarine" }, + cobblestone_wall = { "cobblestone_wall", "mossy_cobblestone_wall" }, + red_flower = { "poppy", "blue_orchid", "allium", "azure_bluet", "red_tulip", "orange_tulip", "white_tulip", "pink_tulip", "oxeye_daisy" }, + double_plant = { "sunflower", "lilac", "tall_grass", "large_fern", "rose_bush", "peony" }, + wool = dyed("wool"), + carpet = dyed("carpet"), + stained_glass = dyed("stained_glass"), + stained_glass_pane = dyed("stained_glass_pane"), + stained_hardened_clay = dyed("terracotta"), + concrete = dyed("concrete"), + concrete_powder = dyed("concrete_powder"), +} :: { [string]: { string } } +Legacy.MASK = { log = 4, log2 = 4, leaves = 4, leaves2 = 4, sapling = 8, wooden_slab = 8, quartz_block = 8, double_plant = 8 } :: { [string]: number } + +return Legacy +end +__FILES["codecs/model/Minecraft/Packed"] = @native function() + + + +-- codecs/model/Minecraft/Packed: Minecraft's packed index arrays. New code. +-- Minecraft wiki "Chunk format", Sponge / Litematica schematic specs: little-endian int64 longs of bits-wide indices, +-- spanning long boundaries (Litematica, chunks before 1.16) or floor(64 / bits) per long plus padding (since 1.16). +local Packed = {} + +local readu8, readu16, readu32 = buffer.readu8, buffer.readu16, buffer.readu32 +local writeu8, writeu16 = buffer.writeu8, buffer.writeu16 +local extract, band, rshift, lshift, bor = bit32.extract, bit32.band, bit32.rshift, bit32.lshift, bit32.bor + +@native function Packed.longsNeeded(count: number, bits: number, spanning: boolean): number + if spanning then + return (count * bits + 63) // 64 + end + local per = 64 // bits + return (count + per - 1) // per +end + +@native function Packed.unpack(longs: buffer, bits: number, count: number, spanning: boolean, out: buffer, max: number): (boolean, string?) + if bits < 1 or bits > 16 then + return false, "unsupported: " .. bits .. "-bit packed indices" + end + local need = Packed.longsNeeded(count, bits, spanning) + if buffer.len(longs) < need * 8 then + return false, "packed array too short (" .. buffer.len(longs) // 8 .. " longs, need " .. need .. ")" + end + if buffer.len(out) < count * 2 then + return false, "output too small" + end + local n = need * 8 + local src = buffer.create(n + 4) + buffer.copy(src, 0, longs, 0, n) + if spanning then + local p = 0 + for i = 0, count - 1 do + local v = extract(readu32(src, rshift(p, 3)), band(p, 7), bits) + if v >= max then + return false, "index " .. v .. " past the palette (" .. max .. ")" + end + writeu16(out, i * 2, v) + p += bits + end + else + local per = 64 // bits + local i = 0 + local base = 0 + while i < count do + local p = 0 + for _ = 1, per do + if i >= count then + break + end + local v = extract(readu32(src, base + rshift(p, 3)), band(p, 7), bits) + if v >= max then + return false, "index " .. v .. " past the palette (" .. max .. ")" + end + writeu16(out, i * 2, v) + i += 1 + p += bits + end + base += 8 + end + end + return true, nil +end + +@native function Packed.pack(indices: buffer, count: number, bits: number, spanning: boolean): buffer + local need = Packed.longsNeeded(count, bits, spanning) + local out = buffer.create(need * 8 + 4) + local per = 64 // bits + for i = 0, count - 1 do + local v = readu16(indices, i * 2) + local p = if spanning then i * bits else (i // per) * 64 + (i % per) * bits + local at = rshift(p, 3) + local sh = band(p, 7) + local x = lshift(v, sh) + for k = 0, 2 do + local bits8 = band(rshift(x, k * 8), 0xff) + if bits8 ~= 0 then + writeu8(out, at + k, bor(readu8(out, at + k), bits8)) + end + end + end + local res = buffer.create(need * 8) + buffer.copy(res, 0, out, 0, need * 8) + return res +end + +@native function Packed.bitsFor(n: number, min: number): number + local b = min + while lshift(1, b) < n and b < 31 do + b += 1 + end + return b +end + +-- Sponge BlockData: unsigned LEB128 varints +@native function Packed.varints(src: buffer, offset: number, length: number, count: number, out: buffer, max: number): (boolean, string?) + if buffer.len(out) < count * 2 or offset + length > buffer.len(src) then + return false, "bad varint array arguments" + end + local p, e = offset, offset + length + for i = 0, count - 1 do + local v, sh = 0, 0 + while true do + if p >= e then + return false, "truncated: block data ends after " .. i .. " of " .. count .. " entries" + end + local c = readu8(src, p) + p += 1 + v += band(c, 0x7f) * 2 ^ sh + if c < 128 then + break + end + sh += 7 + if sh > 28 then + return false, "varint too long" + end + end + if v >= max then + return false, "index " .. v .. " past the palette (" .. max .. ")" + end + writeu16(out, i * 2, v) + end + return true, nil +end + +@native function Packed.toVarints(indices: buffer, count: number): buffer + local out = buffer.create(count * 3) + local p = 0 + for i = 0, count - 1 do + local v = readu16(indices, i * 2) + while v >= 128 do + writeu8(out, p, band(v, 0x7f) + 128) + p += 1 + v = rshift(v, 7) + end + writeu8(out, p, v) + p += 1 + end + local res = buffer.create(p) + buffer.copy(res, 0, out, 0, p) + return res +end + +-- nibble arrays: Minecraft low nibble first; WorldEdit AddBlocks high nibble first +@native function Packed.nibble(src: buffer, offset: number, i: number, highFirst: boolean): number + local b = readu8(src, offset + rshift(i, 1)) + local odd = band(i, 1) == 1 + if odd == highFirst then + return band(b, 15) + end + return rshift(b, 4) +end + +@native function Packed.setNibble(dst: buffer, offset: number, i: number, v: number, highFirst: boolean) + local at = offset + rshift(i, 1) + local b = readu8(dst, at) + local odd = band(i, 1) == 1 + if odd == highFirst then + writeu8(dst, at, bor(band(b, 0xf0), band(v, 15))) + else + writeu8(dst, at, bor(band(b, 0x0f), lshift(band(v, 15), 4))) + end +end + +-- Minecraft order: x fastest, then z, then y (schematics, chunk sections) +@native function Packed.fromYzx(src: buffer, sx: number, sy: number, sz: number, dst: buffer?, ox: number?, oy: number?, oz: number?, dsx: number?, dsy: number?): buffer + local out = dst or buffer.create(sx * sy * sz * 2) + local bx, by, bz = ox or 0, oy or 0, oz or 0 + local wx, wy = dsx or sx, dsy or sy + local i = 0 + for y = 0, sy - 1 do + for z = 0, sz - 1 do + local d = (bx + wx * ((by + y) + wy * (bz + z))) * 2 + for _ = 0, sx - 1 do + writeu16(out, d, readu16(src, i)) + i += 2 + d += 2 + end + end + end + return out +end + +@native function Packed.toYzx(src: buffer, sx: number, sy: number, sz: number): buffer + local out = buffer.create(sx * sy * sz * 2) + local i = 0 + for y = 0, sy - 1 do + for z = 0, sz - 1 do + local s = (sx * (y + sy * z)) * 2 + for _ = 0, sx - 1 do + writeu16(out, i, readu16(src, s)) + i += 2 + s += 2 + end + end + end + return out +end + +return Packed +end +__FILES["codecs/model/Polygon"] = function() + +-- codecs/model/Polygon: 2D polygons with holes to triangles by hole bridging and ear clipping. New code. +-- After D. Eberly, "Triangulation by Ear Clipping" (no code taken). +local Polygon = {} + +type Pt = { x: number, y: number, loop: number, index: number } + +local function area(pts: { Pt }): number + local a = 0 + local n = #pts + for i = 1, n do + local p, q = pts[i], pts[i % n + 1] + a += p.x * q.y - q.x * p.y + end + return a / 2 +end + +local function inside(pts: { Pt }, x: number, y: number): boolean + local c = false + local n = #pts + local j = n + for i = 1, n do + local a, b = pts[i], pts[j] + if (a.y > y) ~= (b.y > y) and x < (b.x - a.x) * (y - a.y) / (b.y - a.y) + a.x then + c = not c + end + j = i + end + return c +end + +local function cross(o: Pt, a: Pt, b: Pt): number + return (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x) +end + +local function crosses(p1: Pt, p2: Pt, q1: Pt, q2: Pt): boolean + if (p1.x == q1.x and p1.y == q1.y) or (p1.x == q2.x and p1.y == q2.y) or (p2.x == q1.x and p2.y == q1.y) or (p2.x == q2.x and p2.y == q2.y) then + return false + end + local d1, d2 = cross(q1, q2, p1), cross(q1, q2, p2) + local d3, d4 = cross(p1, p2, q1), cross(p1, p2, q2) + return ((d1 > 0 and d2 < 0) or (d1 < 0 and d2 > 0)) and ((d3 > 0 and d4 < 0) or (d3 < 0 and d4 > 0)) +end + +local function visible(m: Pt, v: Pt, rings: { { Pt } }): boolean + for _, r in rings do + local n = #r + for i = 1, n do + if crosses(m, v, r[i], r[i % n + 1]) then + return false + end + end + end + return true +end + +local function bridge(outer: { Pt }, h: { Pt }, others: { { Pt } }): { Pt } + local mi = 1 + for i, p in h do + if p.x > h[mi].x then + mi = i + end + end + local m = h[mi] + local best, bestD = 0, math.huge + for pass = 1, 2 do + for i, v in outer do + if pass == 2 or v.x >= m.x then + local d = (v.x - m.x) ^ 2 + (v.y - m.y) ^ 2 + if d < bestD and visible(m, v, others) then + best, bestD = i, d + end + end + end + if best > 0 then + break + end + end + if best == 0 then + best = 1 + end + local out: { Pt } = {} + for i = 1, best do + table.insert(out, outer[i]) + end + local n = #h + for k = 0, n do + table.insert(out, h[(mi - 1 + k) % n + 1]) + end + for i = best, #outer do + table.insert(out, outer[i]) + end + return out +end + +local function inTri(a: Pt, b: Pt, c: Pt, p: Pt): boolean + return cross(a, b, p) >= 0 and cross(b, c, p) >= 0 and cross(c, a, p) >= 0 +end + +local function clip(ring: { Pt }, out: { number }) + local pts = table.clone(ring) + local guard = #pts * #pts + 16 + while #pts > 3 and guard > 0 do + guard -= 1 + local n = #pts + local found, bestI, bestScore = 0, 1, -math.huge + for i = 1, n do + local a, b, c = pts[(i - 2) % n + 1], pts[i], pts[i % n + 1] + local cr = cross(a, b, c) + if cr > 0 then + local ok = true + for k = 1, n do + local p = pts[k] + if p ~= a and p ~= b and p ~= c and not (p.x == b.x and p.y == b.y) and not (p.x == a.x and p.y == a.y) and not (p.x == c.x and p.y == c.y) and inTri(a, b, c, p) then + ok = false + break + end + end + if ok then + found = i + break + end + end + if cr > bestScore then + bestI, bestScore = i, cr + end + end + local i = if found > 0 then found else bestI + local a, b, c = pts[(i - 2) % n + 1], pts[i], pts[i % n + 1] + if cross(a, b, c) ~= 0 then + table.insert(out, a.loop) + table.insert(out, a.index) + table.insert(out, b.loop) + table.insert(out, b.index) + table.insert(out, c.loop) + table.insert(out, c.index) + end + table.remove(pts, i) + end + if #pts == 3 and cross(pts[1], pts[2], pts[3]) > 0 then + for k = 1, 3 do + table.insert(out, pts[k].loop) + table.insert(out, pts[k].index) + end + end +end + +function Polygon.triangulate(loops: { { number } }): { number } + local rings: { { Pt } } = {} + local areas: { number } = {} + for li, l in loops do + local pts: { Pt } = {} + for k = 1, #l - 1, 2 do + local x, y = l[k], l[k + 1] + if type(x) == "number" and type(y) == "number" and x == x and y == y then + table.insert(pts, { x = x, y = y, loop = li, index = (k + 1) // 2 }) + end + end + local a = if #pts >= 3 then area(pts) else 0 + if a ~= 0 then + table.insert(rings, pts) + table.insert(areas, math.abs(a)) + if a < 0 then -- counter-clockwise for now; holes are flipped below + local r: { Pt } = {} + for k = #pts, 1, -1 do + table.insert(r, pts[k]) + end + rings[#rings] = r + end + end + end + local n = #rings + local depth, parent = table.create(n, 0), table.create(n, 0) + for i = 1, n do + local p = rings[i][1] + for j = 1, n do + if j ~= i and areas[j] > areas[i] and inside(rings[j], p.x, p.y) then + depth[i] += 1 + if parent[i] == 0 or areas[j] < areas[parent[i]] then + parent[i] = j + end + end + end + end + local holes: { [number]: { number } } = {} + for i = 1, n do + if depth[i] % 2 == 1 and parent[i] > 0 then + local list = holes[parent[i]] or {} + holes[parent[i]] = list + table.insert(list, i) + end + end + local out: { number } = {} + for i = 1, n do + if depth[i] % 2 == 0 then + local ring = rings[i] + local hs = holes[i] + if hs then + table.sort(hs, function(a: number, b: number): boolean + local ma, mb = -math.huge, -math.huge + for _, p in rings[a] do + ma = math.max(ma, p.x) + end + for _, p in rings[b] do + mb = math.max(mb, p.x) + end + return ma > mb + end) + local flipped: { { Pt } } = {} + for _, h in hs do + local r: { Pt } = {} + local src = rings[h] + for k = #src, 1, -1 do + table.insert(r, src[k]) + end + table.insert(flipped, r) + end + for k, h in flipped do + local others: { { Pt } } = { ring } + for k2 = k + 1, #flipped do + table.insert(others, flipped[k2]) + end + ring = bridge(ring, h, others) + end + end + clip(ring, out) + end + end + return out +end + +return Polygon +end +__FILES["codecs/model/Rbx/Binary"] = @native function() + + + +-- codecs/model/Rbx/Binary: the property column codecs of the Roblox binary format (rbx-dom docs/binary.md). +-- PROP columns: byte-interleaved big-endian values, zigzag signed integers, rotated floats, delta-coded referents. +local Rbx = __include("codecs/model/Rbx") +local Bytes = __include("core/Bytes") + +local Binary = {} + +local readu8, readu16, readi16, readu32, readf32, readf64 = + buffer.readu8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.readf32, buffer.readf64 +local writeu32, readstring = buffer.writeu32, buffer.readstring +local writef32 = buffer.writef32 +local floor = math.floor + +local scratch = buffer.create(8) +local TWO32 = 4294967296 + +-- the rotated float encoding: bits rotated left by one (sign in bit 0) +@native local function unrotate(x: number): number + writeu32(scratch, 0, x // 2 + (x % 2) * 2147483648) + return readf32(scratch, 0) +end +@native local function rotate(v: number): number + writef32(scratch, 0, v) + local bits = readu32(scratch, 0) + return (bits * 2) % TWO32 + bits // 2147483648 +end +@native local function unzigzag(x: number): number + return if x % 2 == 0 then x // 2 else -(x + 1) // 2 +end +@native local function zigzag32(v: number): number + v = floor(v) + return (if v >= 0 then v * 2 else -v * 2 - 1) % TWO32 +end + +@native local function u32s(b: buffer, p: number, n: number): { number } + local out = table.create(n, 0) + local n2, n3 = n * 2, n * 3 + for i = 0, n - 1 do + out[i + 1] = readu8(b, p + i) * 16777216 + readu8(b, p + n + i) * 65536 + readu8(b, p + n2 + i) * 256 + readu8(b, p + n3 + i) + end + return out +end +@native local function i32s(b: buffer, p: number, n: number): { number } + local out = u32s(b, p, n) + for i = 1, n do + out[i] = unzigzag(out[i]) + end + return out +end +@native local function f32s(b: buffer, p: number, n: number): { number } + local out = u32s(b, p, n) + for i = 1, n do + out[i] = unrotate(out[i]) + end + return out +end +@native local function i64s(b: buffer, p: number, n: number): { number } + local out = table.create(n, 0) + for i = 0, n - 1 do + local hi = readu8(b, p + i) * 16777216 + readu8(b, p + n + i) * 65536 + readu8(b, p + 2 * n + i) * 256 + readu8(b, p + 3 * n + i) + local lo = readu8(b, p + 4 * n + i) * 16777216 + readu8(b, p + 5 * n + i) * 65536 + readu8(b, p + 6 * n + i) * 256 + readu8(b, p + 7 * n + i) + local half = hi * 2147483648 + lo // 2 + out[i + 1] = if lo % 2 == 0 then half else -half - 1 + end + return out +end + +@native local function putU32s(w: Bytes.Writer, vals: { number }) + local n = #vals + local p = w:reserve(4 * n) + local b = w.buf + for i = 0, n - 1 do + local v = vals[i + 1] % TWO32 + buffer.writeu8(b, p + i, v // 16777216) + buffer.writeu8(b, p + n + i, (v // 65536) % 256) + buffer.writeu8(b, p + 2 * n + i, (v // 256) % 256) + buffer.writeu8(b, p + 3 * n + i, v % 256) + end + w.pos = p + 4 * n +end +@native local function putI32s(w: Bytes.Writer, vals: { number }) + local t = table.create(#vals, 0) + for i, v in vals do + t[i] = zigzag32(v) + end + putU32s(w, t) +end +@native local function putF32s(w: Bytes.Writer, vals: { number }) + local t = table.create(#vals, 0) + for i, v in vals do + t[i] = rotate(v) + end + putU32s(w, t) +end +@native local function putI64s(w: Bytes.Writer, vals: { number }) + local n = #vals + local p = w:reserve(8 * n) + local b = w.buf + for i = 0, n - 1 do + local v = floor(vals[i + 1]) + local z = if v >= 0 then v * 2 else -v * 2 - 1 + local hi, lo = (z // TWO32) % TWO32, z % TWO32 + buffer.writeu8(b, p + i, hi // 16777216) + buffer.writeu8(b, p + n + i, (hi // 65536) % 256) + buffer.writeu8(b, p + 2 * n + i, (hi // 256) % 256) + buffer.writeu8(b, p + 3 * n + i, hi % 256) + buffer.writeu8(b, p + 4 * n + i, lo // 16777216) + buffer.writeu8(b, p + 5 * n + i, (lo // 65536) % 256) + buffer.writeu8(b, p + 6 * n + i, (lo // 256) % 256) + buffer.writeu8(b, p + 7 * n + i, lo % 256) + end + w.pos = p + 8 * n +end + +-- referent arrays: zigzag i32, interleaved, each the difference from the previous one +@native function Binary.readRefs(b: buffer, p: number, limit: number, n: number): ({ number }?, number) + if n < 0 or p + 4 * n > limit then + return nil, p + end + local out = i32s(b, p, n) + local acc = 0 + for i = 1, n do + acc += out[i] + out[i] = acc + end + return out, p + 4 * n +end +@native function Binary.writeRefs(w: Bytes.Writer, refs: { number }) + local d = table.create(#refs, 0) + local prev = 0 + for i, r in refs do + d[i] = r - prev + prev = r + end + putI32s(w, d) +end + +type Ctx = { + ref: ((number) -> any)?, + refOf: ((any) -> number)?, + shared: { string }?, + sharedIndex: ((string) -> number)?, +} + +@native local function str(b: buffer, p: number, limit: number): (string?, number) + if p + 4 > limit then + return nil, p + end + local len = readu32(b, p) + if p + 4 + len > limit then + return nil, p + end + return readstring(b, p + 4, len), p + 4 + len +end + +@native local function cframes(b: buffer, p: number, limit: number, n: number): ({ any }?, number) + local rots: { { number } } = table.create(n) :: any + for i = 1, n do + if p >= limit then + return nil, p + end + local id = readu8(b, p) + p += 1 + if id == 0 then + if p + 36 > limit then + return nil, p + end + local m = table.create(9, 0) + for k = 0, 8 do + m[k + 1] = readf32(b, p + 4 * k) + end + rots[i] = m + p += 36 + else + local m = Rbx.ROTATIONS[id] + if not m then + return nil, -1 + end + rots[i] = m + end + end + if p + 12 * n > limit then + return nil, p + end + local xs, ys, zs = f32s(b, p, n), f32s(b, p + 4 * n, n), f32s(b, p + 8 * n, n) + local out = table.create(n) + for i = 1, n do + local m = rots[i] + out[i] = { xs[i], ys[i], zs[i], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8], m[9] } + end + return out, p + 12 * n +end + +local FIXED: { [number]: number } = { + [0x02] = 1, + [0x03] = 4, + [0x04] = 4, + [0x05] = 8, + [0x06] = 8, + [0x07] = 16, + [0x08] = 24, + [0x09] = 1, + [0x0A] = 1, + [0x0B] = 4, + [0x0C] = 12, + [0x0D] = 8, + [0x0E] = 12, + [0x0F] = 4, + [0x12] = 4, + [0x13] = 4, + [0x14] = 6, + [0x17] = 8, + [0x18] = 16, + [0x1A] = 3, + [0x1B] = 8, + [0x1C] = 4, + [0x1F] = 16, + [0x21] = 8, +} + +@native function Binary.decode(t: number, b: buffer, p: number, limit: number, n: number, ctx: Ctx): ({ any }?, any) + if limit > buffer.len(b) or p < 0 or n < 0 then + return nil, "corrupt: bad ranges" + end + local size = FIXED[t] + if size and p + size * n > limit then + return nil, "truncated property values" + end + if t == 0x01 or t == 0x1D then + local out = table.create(n, "") + for i = 1, n do + local s, q = str(b, p, limit) + if not s then + return nil, "truncated string" + end + out[i] = s + p = q + end + return out, p + elseif t == 0x02 then + local out = table.create(n, false) + for i = 1, n do + out[i] = readu8(b, p + i - 1) ~= 0 + end + return out, p + n + elseif t == 0x03 then + return i32s(b, p, n), p + 4 * n + elseif t == 0x04 then + return f32s(b, p, n), p + 4 * n + elseif t == 0x05 then + local out = table.create(n, 0) + for i = 1, n do + out[i] = readf64(b, p + 8 * (i - 1)) + end + return out, p + 8 * n + elseif t == 0x06 then + local s, o = f32s(b, p, n), i32s(b, p + 4 * n, n) + local out = table.create(n) + for i = 1, n do + out[i] = { s[i], o[i] } + end + return out, p + 8 * n + elseif t == 0x07 then + local xs, ys, xo, yo = f32s(b, p, n), f32s(b, p + 4 * n, n), i32s(b, p + 8 * n, n), i32s(b, p + 12 * n, n) + local out = table.create(n) + for i = 1, n do + out[i] = { xs[i], xo[i], ys[i], yo[i] } + end + return out, p + 16 * n + elseif t == 0x08 then + local out = table.create(n) + for i = 1, n do + local q = p + 24 * (i - 1) + out[i] = { readf32(b, q), readf32(b, q + 4), readf32(b, q + 8), readf32(b, q + 12), readf32(b, q + 16), readf32(b, q + 20) } + end + return out, p + 24 * n + elseif t == 0x09 or t == 0x0A then + local out = table.create(n, 0) + for i = 1, n do + out[i] = readu8(b, p + i - 1) + end + return out, p + n + elseif t == 0x0B or t == 0x12 then + return u32s(b, p, n), p + 4 * n + elseif t == 0x0C or t == 0x0E or t == 0x0D or t == 0x18 then + local k = if t == 0x0D then 2 elseif t == 0x18 then 4 else 3 + local cols: { { number } } = table.create(k) :: any + for c = 1, k do + cols[c] = f32s(b, p + 4 * n * (c - 1), n) + end + local out = table.create(n) + for i = 1, n do + local v = table.create(k, 0) + for c = 1, k do + v[c] = cols[c][i] + end + out[i] = v + end + return out, p + 4 * k * n + elseif t == 0x0F or t == 0x14 then + local k = if t == 0x0F then 2 else 3 + local out = table.create(n) + for i = 1, n do + local q = p + 2 * k * (i - 1) + out[i] = if k == 2 then { readi16(b, q), readi16(b, q + 2) } else { readi16(b, q), readi16(b, q + 2), readi16(b, q + 4) } + end + return out, p + 2 * k * n + elseif t == 0x10 then + local out, q = cframes(b, p, limit, n) + if not out then + return nil, if q == -1 then "corrupt: bad CFrame rotation id" else "truncated CFrame values" + end + return out, q + elseif t == 0x13 then + local refs, q = Binary.readRefs(b, p, limit, n) + if not refs then + return nil, "truncated referents" + end + local out = table.create(n) + local ref = ctx.ref + for i = 1, n do + out[i] = if ref and refs[i] >= 0 then ref(refs[i]) else nil + end + return out, q + elseif t == 0x15 or t == 0x16 then + local k = if t == 0x15 then 3 else 5 + local out = table.create(n) + for i = 1, n do + if p + 4 > limit then + return nil, "truncated sequence" + end + local count = readu32(b, p) + p += 4 + if p + count * 4 * k > limit then + return nil, "truncated sequence" + end + local seq = table.create(count) + for j = 1, count do + local key = table.create(k, 0) + for c = 1, k do + key[c] = readf32(b, p + 4 * (c - 1)) + end + seq[j] = key + p += 4 * k + end + out[i] = seq + end + return out, p + elseif t == 0x17 then + local out = table.create(n) + for i = 1, n do + out[i] = { readf32(b, p + 8 * (i - 1)), readf32(b, p + 8 * (i - 1) + 4) } + end + return out, p + 8 * n + elseif t == 0x19 then + local out = table.create(n) + for i = 1, n do + if p >= limit then + return nil, "truncated physical properties" + end + local flag = readu8(b, p) + p += 1 + if flag % 2 == 1 then + local k = if flag // 2 % 2 == 1 then 6 else 5 + if p + 4 * k > limit then + return nil, "truncated physical properties" + end + local v = table.create(6, 1) -- acoustic absorption 1 when the file leaves it out + for c = 1, k do + v[c] = readf32(b, p + 4 * (c - 1)) + end + out[i] = v + p += 4 * k + elseif flag ~= 0 then + return nil, "unknown" + end + end + return out, p + elseif t == 0x1A then + local out = table.create(n) + for i = 1, n do + out[i] = { readu8(b, p + i - 1), readu8(b, p + n + i - 1), readu8(b, p + 2 * n + i - 1) } + end + return out, p + 3 * n + elseif t == 0x1B or t == 0x21 then + return i64s(b, p, n), p + 8 * n + elseif t == 0x1C then + local idx = u32s(b, p, n) + local shared: { string } = ctx.shared or {} + local out: { string } = table.create(n, "") + for i = 1, n do + local s = shared[idx[i] + 1] + if s == nil then + return nil, "corrupt: shared string index out of range" + end + out[i] = s + end + return out, p + 4 * n + elseif t == 0x1E then + if p >= limit or readu8(b, p) ~= 0x10 then + return nil, "unknown" + end + local cfs, q = cframes(b, p + 1, limit, n) + if not cfs then + return nil, if q == -1 then "corrupt: bad CFrame rotation id" else "truncated CFrame values" + end + if q + 1 + n > limit or readu8(b, q) ~= 0x02 then + return nil, "truncated optional CFrame flags" + end + local out = table.create(n) + for i = 1, n do + out[i] = if readu8(b, q + i) ~= 0 then cfs[i] else nil + end + return out, q + 1 + n + elseif t == 0x1F then + local out = table.create(n, "") + local hex = table.create(16, "") + for i = 0, n - 1 do + local by = table.create(16, 0) + for k = 0, 15 do + by[k + 1] = readu8(b, p + k * n + i) + end + -- bytes 8..15: the random part rotated left by one bit (as a 64-bit integer); undo it + local carry = by[16] % 2 + for k = 9, 16 do + local v = by[k] + by[k] = v // 2 + carry * 128 + carry = v % 2 + end + for k = 1, 8 do + hex[k] = string.format("%02x", by[8 + k]) + end + for k = 1, 8 do + hex[8 + k] = string.format("%02x", by[k + 4 - (if k > 4 then 8 else 0)]) + end + out[i + 1] = table.concat(hex) + end + return out, p + 16 * n + elseif t == 0x20 then + local out = table.create(n) + for i = 1, n do + local fam, q = str(b, p, limit) + if not fam or q + 3 > limit then + return nil, "truncated font" + end + local weight, style = readu16(b, q), readu8(b, q + 2) + local face, q2 = str(b, q + 3, limit) + if not face then + return nil, "truncated font" + end + out[i] = { family = fam, weight = weight, style = if style == 1 then "Italic" else "Normal", cachedFaceId = if face ~= "" then face else nil } + p = q2 + end + return out, p + elseif t == 0x22 then + if p + 4 * n > limit then + return nil, "truncated content" + end + local kinds = i32s(b, p, n) + p += 4 * n + if p + 4 > limit then + return nil, "truncated content" + end + local nu = readu32(b, p) + p += 4 + local uris = table.create(math.min(nu, n)) + for j = 1, nu do + local s, q = str(b, p, limit) + if not s then + return nil, "truncated content" + end + uris[j] = s + p = q + end + if p + 4 > limit then + return nil, "truncated content" + end + local no = readu32(b, p) + local objs, q = Binary.readRefs(b, p + 4, limit, no) + if not objs or q + 4 > limit then + return nil, "truncated content" + end + if readu32(b, q) ~= 0 then + return nil, "unknown" -- external objects: kept raw + end + p = q + 4 + local out = table.create(n) + local iu, io = 1, 1 + for i = 1, n do + local k = kinds[i] + if k == 1 then + if iu > nu then + return nil, "corrupt: content uri count" + end + out[i] = uris[iu] + iu += 1 + elseif k == 2 then + if io > no then + return nil, "corrupt: content object count" + end + local r = objs[io] + out[i] = if ctx.ref and r >= 0 then ctx.ref(r) else nil + io += 1 + elseif k ~= 0 then + return nil, "unknown" + end + end + return out, p + end + return nil, "unknown" +end + +@native local function num(v: any): number + return if type(v) == "number" and v == v then v else 0 +end +@native local function column(vals: { any }, n: number, c: number): { number } + local out = table.create(n, 0) + for i = 1, n do + local v = vals[i] + out[i] = if type(v) == "table" then num(v[c]) else 0 + end + return out +end + +@native local function putString(w: Bytes.Writer, s: string) + w:u32le(#s) + w:string(s) +end + +@native local function putCFrames(w: Bytes.Writer, vals: { any }, n: number) + for i = 1, n do + local v = vals[i] + local cf = if type(v) == "table" then v else { 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1 } + local id = Rbx.rotationId(cf) + w:u8(id) + if id == 0 then + for k = 4, 12 do + w:f32le(num(cf[k])) + end + end + end + putF32s(w, column(vals, n, 1)) + putF32s(w, column(vals, n, 2)) + putF32s(w, column(vals, n, 3)) +end + +@native local function hexByte(s: string, i: number): number + return tonumber(string.sub(s, 2 * i - 1, 2 * i), 16) or 0 +end + +@native function Binary.encode(t: number, vals: { any }, n: number, w: Bytes.Writer, ctx: Ctx): string? + if t == 0x01 or t == 0x1D then + for i = 1, n do + local v = vals[i] + putString(w, if type(v) == "string" then v else "") + end + elseif t == 0x02 then + for i = 1, n do + w:u8(if vals[i] then 1 else 0) + end + elseif t == 0x03 then + local c = table.create(n, 0) + for i = 1, n do + c[i] = num(vals[i]) + end + putI32s(w, c) + elseif t == 0x04 then + local c = table.create(n, 0) + for i = 1, n do + c[i] = num(vals[i]) + end + putF32s(w, c) + elseif t == 0x05 then + for i = 1, n do + w:f64le(num(vals[i])) + end + elseif t == 0x06 then + putF32s(w, column(vals, n, 1)) + putI32s(w, column(vals, n, 2)) + elseif t == 0x07 then + putF32s(w, column(vals, n, 1)) + putF32s(w, column(vals, n, 3)) + putI32s(w, column(vals, n, 2)) + putI32s(w, column(vals, n, 4)) + elseif t == 0x08 then + for i = 1, n do + local v = vals[i] + for c = 1, 6 do + w:f32le(if type(v) == "table" then num(v[c]) else 0) + end + end + elseif t == 0x09 or t == 0x0A then + for i = 1, n do + w:u8(num(vals[i]) % 256) + end + elseif t == 0x0B or t == 0x12 then + local c = table.create(n, 0) + for i = 1, n do + c[i] = floor(num(vals[i])) + end + putU32s(w, c) + elseif t == 0x0C or t == 0x0E or t == 0x0D or t == 0x18 then + local k = if t == 0x0D then 2 elseif t == 0x18 then 4 else 3 + for c = 1, k do + putF32s(w, column(vals, n, c)) + end + elseif t == 0x0F or t == 0x14 then + local k = if t == 0x0F then 2 else 3 + for i = 1, n do + local v = vals[i] + for c = 1, k do + local x = floor(if type(v) == "table" then num(v[c]) else 0) % 65536 + w:u16le(x) + end + end + elseif t == 0x10 then + putCFrames(w, vals, n) + elseif t == 0x13 then + local refs = table.create(n, -1) + local refOf = ctx.refOf + for i = 1, n do + refs[i] = if refOf and vals[i] ~= nil then refOf(vals[i]) else -1 + end + Binary.writeRefs(w, refs) + elseif t == 0x15 or t == 0x16 then + local k = if t == 0x15 then 3 else 5 + for i = 1, n do + local seq = vals[i] + if type(seq) ~= "table" then + seq = {} + end + w:u32le(#seq) + for _, key in seq do + for c = 1, k do + w:f32le(if type(key) == "table" then num(key[c]) else 0) + end + end + end + elseif t == 0x17 then + for i = 1, n do + local v = vals[i] + w:f32le(if type(v) == "table" then num(v[1]) else 0) + w:f32le(if type(v) == "table" then num(v[2]) else 0) + end + elseif t == 0x19 then + for i = 1, n do + local v = vals[i] + if type(v) ~= "table" then + w:u8(0) + else + local acoustic = v[6] ~= nil and v[6] ~= 1 -- (rbx-dom leaves the default out) + w:u8(if acoustic then 3 else 1) + for c = 1, if acoustic then 6 else 5 do + w:f32le(num(v[c])) + end + end + end + elseif t == 0x1A then + for c = 1, 3 do + for i = 1, n do + local v = vals[i] + w:u8(math.clamp(floor(if type(v) == "table" then num(v[c]) else 0), 0, 255)) + end + end + elseif t == 0x1B or t == 0x21 then + local c = table.create(n, 0) + for i = 1, n do + c[i] = num(vals[i]) + end + putI64s(w, c) + elseif t == 0x1C then + local idx = table.create(n, 0) + local si = ctx.sharedIndex + for i = 1, n do + local v = vals[i] + idx[i] = if si then si(if type(v) == "string" then v else "") else 0 + end + putU32s(w, idx) + elseif t == 0x1E then + w:u8(0x10) + putCFrames(w, vals, n) + w:u8(0x02) + for i = 1, n do + w:u8(if type(vals[i]) == "table" then 1 else 0) + end + elseif t == 0x1F then + local p = w:reserve(16 * n) + local b = w.buf + for i = 0, n - 1 do + local s = vals[i + 1] + if type(s) ~= "string" or #s ~= 32 or string.find(s, "[^%x]") then + return "a UniqueId is 32 hex digits" + end + -- index (hex 25..32) and time (17..24) first, then the random part (1..16) rotated left by one bit + local by = table.create(16, 0) + for k = 1, 4 do + by[k] = hexByte(s, 12 + k) + by[4 + k] = hexByte(s, 8 + k) + end + local top = hexByte(s, 1) // 128 + for k = 1, 8 do + local v = hexByte(s, k) + local nxt = if k < 8 then hexByte(s, k + 1) // 128 else top + by[8 + k] = (v * 2) % 256 + nxt + end + for k = 0, 15 do + buffer.writeu8(b, p + k * n + i, by[k + 1]) + end + end + w.pos = p + 16 * n + elseif t == 0x20 then + for i = 1, n do + local v = vals[i] + if type(v) ~= "table" then + v = Rbx.default("Font") + end + putString(w, if type(v.family) == "string" then v.family else "") + w:u16le(math.clamp(floor(num(v.weight)), 0, 65535)) + w:u8(if v.style == "Italic" then 1 else 0) + putString(w, if type(v.cachedFaceId) == "string" then v.cachedFaceId else "") + end + elseif t == 0x22 then + local kinds, uris, objs = table.create(n, 0), {}, {} + local refOf = ctx.refOf + for i = 1, n do + local v = vals[i] + if type(v) == "string" then + kinds[i] = 1 + table.insert(uris, v) + elseif type(v) == "table" then + kinds[i] = 2 + table.insert(objs, if refOf then refOf(v) else -1) + end + end + putI32s(w, kinds) + w:u32le(#uris) + for _, s in uris do + putString(w, s) + end + w:u32le(#objs) + Binary.writeRefs(w, objs) + w:u32le(0) + else + return "unknown type id " .. t + end + return nil +end + +return Binary +end +__FILES["codecs/model/Rig"] = function() + +-- codecs/model/Rig: the Scene mapping shared by game model formats (MD2 / MD3 / MDL / MD5 / SMD / ...). New code. +local Types = __include("Types") +local Mat4 = __include("codecs/model/Mat4") + +local Rig = {} + +local Scene = Types.Scene +local readf32, writef32, writeu16 = buffer.readf32, buffer.writef32, buffer.writeu16 + +type Joint = { + name: string?, + parent: number, + translation: { number }, + rotation: { number }, -- quaternion x, y, z, w + scale: { number }?, +} +type Range = { name: string?, first: number, last: number, fps: number? } +type Track = { translation: { number }?, rotation: { number }?, scale: { number }? } + +function Rig.morph(prim: Types.Primitive, frames: { buffer }, normals: { buffer }?): boolean + local pos = prim.attributes.POSITION + if not pos or pos.type ~= "f32" or pos.components ~= 3 then + return false + end + local nrm = prim.attributes.NORMAL + local n = pos.count * 3 + local targets: { { [string]: Types.Accessor } } = {} + local ok = true + for k, f in frames do + if buffer.len(f) < n * 4 then + ok = false + break + end + local t: { [string]: Types.Accessor } = {} + local d = buffer.create(n * 4) + local base = pos.data + for i = 0, n - 1 do + writef32(d, i * 4, readf32(f, i * 4) - readf32(base, i * 4)) + end + t.POSITION = Scene.accessor(d, "f32", 3, pos.count) + local fn = normals and normals[k] + if nrm and fn and nrm.type == "f32" and buffer.len(fn) >= n * 4 then + local dn = buffer.create(n * 4) + for i = 0, n - 1 do + writef32(dn, i * 4, readf32(fn, i * 4) - readf32(nrm.data, i * 4)) + end + t.NORMAL = Scene.accessor(dn, "f32", 3, pos.count) + end + targets[k] = t + end + if ok then + prim.targets = targets + end + return ok +end + +function Rig.morphAnimation(scene: Types.Scene, node: number, targets: number, ranges: { Range }, interpolation: string?) + for _, rg in ranges do + local first, last = math.max(1, math.floor(rg.first)), math.min(targets, math.floor(rg.last)) + if last >= first then + local keys = last - first + 1 + local fps = if rg.fps and rg.fps > 0 then rg.fps else 10 + local times = buffer.create(keys * 4) + local weights = buffer.create(keys * targets * 4) + for k = 0, keys - 1 do + writef32(times, k * 4, k / fps) + writef32(weights, (k * targets + first - 1 + k) * 4, 1) + end + table.insert(scene.animations, { + name = rg.name, + channels = { + { + node = node, + path = "weights" :: any, + input = Scene.accessor(times, "f32", 1, keys), + output = Scene.accessor(weights, "f32", 1, keys * targets), + interpolation = (if interpolation == "STEP" then "STEP" else "LINEAR") :: any, + }, + }, + }) + end + end +end + +-- Quake's precomputed normal table is not redistributable here +function Rig.normals(pos: buffer, count: number, indices: { number }): buffer + local out = buffer.create(count * 12) + local acc = table.create(count * 3, 0) + for k = 1, #indices - 2, 3 do + local a, b, c = indices[k], indices[k + 1], indices[k + 2] + if a >= 0 and b >= 0 and c >= 0 and a < count and b < count and c < count then + local ax, ay, az = readf32(pos, a * 12), readf32(pos, a * 12 + 4), readf32(pos, a * 12 + 8) + local ux, uy, uz = readf32(pos, b * 12) - ax, readf32(pos, b * 12 + 4) - ay, readf32(pos, b * 12 + 8) - az + local vx, vy, vz = readf32(pos, c * 12) - ax, readf32(pos, c * 12 + 4) - ay, readf32(pos, c * 12 + 8) - az + local nx, ny, nz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx + for _, v in { a, b, c } do + acc[v * 3 + 1] += nx + acc[v * 3 + 2] += ny + acc[v * 3 + 3] += nz + end + end + end + for v = 0, count - 1 do + local x, y, z = acc[v * 3 + 1], acc[v * 3 + 2], acc[v * 3 + 3] + local l = math.sqrt(x * x + y * y + z * z) + if l > 0 then + x, y, z = x / l, y / l, z / l + end + writef32(out, v * 12, x) + writef32(out, v * 12 + 4, y) + writef32(out, v * 12 + 8, z) + end + return out +end + +local function trs(j: Joint): { number } + return Mat4.compose(j.translation, j.rotation, j.scale) +end + +-- R = Rz * Ry * Rx: the Quake / Half-Life AngleQuaternion convention of MDL bones and SMD skeletons +function Rig.angles(x: number, y: number, z: number): { number } + local sy, cy = math.sin(z / 2), math.cos(z / 2) + local sp, cp = math.sin(y / 2), math.cos(y / 2) + local sr, cr = math.sin(x / 2), math.cos(x / 2) + return { sr * cp * cy - cr * sp * sy, cr * sp * cy + sr * cp * sy, cr * cp * sy - sr * sp * cy, cr * cp * cy + sr * sp * sy } +end + +function Rig.skeleton(scene: Types.Scene, joints: { Joint }, space: "local" | "world", root: number?): ({ number }, number, { { number } }) + local n = #joints + local world: { { number } } = {} + local nodes: { number } = {} + for i, j in joints do + local p = if j.parent >= 1 and j.parent < i then j.parent else 0 + local m = trs(j) + local lt, lr, ls = j.translation, j.rotation, j.scale + if space == "world" then + world[i] = m + if p > 0 then + local inv = Mat4.inverse(world[p]) + if inv then + local t, r, s = Mat4.decompose(Mat4.mul(inv, m)) + lt, lr, ls = t, r, s + end + end + else + world[i] = if p > 0 then Mat4.mul(world[p], m) else m + end + local node: Types.Node = { name = j.name, children = {}, translation = table.clone(lt), rotation = table.clone(lr), scale = if ls then table.clone(ls) else nil } + table.insert(scene.nodes, node) + local idx = #scene.nodes + nodes[i] = idx + if p > 0 then + table.insert(scene.nodes[nodes[p]].children, idx) + elseif root and scene.nodes[root] then + table.insert(scene.nodes[root].children, idx) + else + table.insert(scene.roots, idx) + end + end + local ibm = buffer.create(n * 64) + for i = 1, n do + local inv = Mat4.inverseFull(world[i]) or Mat4.identity() + for k = 1, 16 do + writef32(ibm, ((i - 1) * 16 + k - 1) * 4, inv[k]) + end + end + local acc = Scene.accessor(ibm, "f32", 16, n) + acc.matrix = true + table.insert(scene.skins, { joints = nodes, inverseBindMatrices = acc, skeleton = if n > 0 then nodes[1] else nil }) + return nodes, #scene.skins, world +end + +function Rig.influences(lists: { { number } }): (Types.Accessor, Types.Accessor) + local n = #lists + local jb, wb = buffer.create(n * 8), buffer.create(n * 16) + for v, l in lists do + local pairs_: { { number } } = {} + local at: { [number]: { number } } = {} + for k = 1, #l - 1, 2 do + if l[k + 1] > 0 then + local same = at[l[k]] + if same then + same[2] += l[k + 1] + else + local e = { l[k], l[k + 1] } + at[l[k]] = e + table.insert(pairs_, e) + end + end + end + table.sort(pairs_, function(a: { number }, b: { number }): boolean + return a[2] > b[2] + end) + local sum = 0 + for k = 1, math.min(4, #pairs_) do + sum += pairs_[k][2] + end + for k = 1, math.min(4, #pairs_) do + writeu16(jb, ((v - 1) * 4 + k - 1) * 2, math.clamp(pairs_[k][1], 0, 65535)) + writef32(wb, ((v - 1) * 4 + k - 1) * 4, pairs_[k][2] / sum) + end + end + return Scene.accessor(jb, "u16", 4, n), Scene.accessor(wb, "f32", 4, n) +end + +local function floats(t: { number }, count: number, comps: number): Types.Accessor? + if #t < count * comps then + return nil + end + local b = buffer.create(count * comps * 4) + for i = 1, count * comps do + writef32(b, (i - 1) * 4, t[i]) + end + return Scene.accessor(b, "f32", comps, count) +end + +function Rig.animation(scene: Types.Scene, name: string?, nodes: { number }, times: { number }, tracks: { [number]: Track }, interpolation: string?): number + local count = #times + local input = floats(times, count, 1) + local channels: { Types.Channel } = {} + local interp: any = if interpolation == "STEP" then "STEP" else "LINEAR" + if input then + for j, tr in tracks do + local node = nodes[j] + if node then + for _, path in { "translation", "rotation", "scale" } do + local keys = (tr :: any)[path] + local acc = keys and floats(keys, count, if path == "rotation" then 4 else 3) + if acc then + table.insert(channels, { node = node, path = path :: any, input = input, output = acc, interpolation = interp }) + end + end + end + end + end + table.insert(scene.animations, { name = name, channels = channels }) + return #scene.animations +end + +return Rig +end +__FILES["codecs/model/Sampler"] = function() + +-- codecs/model/Sampler: Scene animation sampling, STEP / LINEAR (slerp) / CUBICSPLINE as in glTF 2.0 animations. New code. +local Types = __include("Types") + +local Sampler = {} + +type Sample = (t: number) -> { number } +type Pose = { [number]: { [string]: { number } } } + +local function normalize(q: { number }): { number } + local l = math.sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3] + q[4] * q[4]) + if l <= 0 then + return { 0, 0, 0, 1 } + end + return { q[1] / l, q[2] / l, q[3] / l, q[4] / l } +end + +local function slerp(a: { number }, b: { number }, s: number): { number } + local d = a[1] * b[1] + a[2] * b[2] + a[3] * b[3] + a[4] * b[4] + local bx, by, bz, bw = b[1], b[2], b[3], b[4] + if d < 0 then + d, bx, by, bz, bw = -d, -bx, -by, -bz, -bw + end + local wa, wb + if d > 0.9995 then + wa, wb = 1 - s, s + else + local th = math.acos(math.min(d, 1)) + local sn = math.sin(th) + wa, wb = math.sin((1 - s) * th) / sn, math.sin(s * th) / sn + end + return normalize({ a[1] * wa + bx * wb, a[2] * wa + by * wb, a[3] * wa + bz * wb, a[4] * wa + bw * wb }) +end + +function Sampler.channel(ch: Types.Channel): Sample? + local inp, out = ch.input, ch.output + if type(inp) ~= "table" or type(out) ~= "table" then + return nil + end + local IN, OUT = Types.Scene.reader(inp), Types.Scene.reader(out) + local n = inp.count + if not IN or not OUT or n < 1 then + return nil + end + local cubic = ch.interpolation == "CUBICSPLINE" + local per = if cubic then 3 else 1 + local comps: number + if ch.path == "weights" then + comps = (out.count * out.components) // (n * per) + else + comps = if ch.path == "rotation" then 4 else 3 + end + if comps < 1 or out.count * out.components < n * per * comps then + return nil + end + local times = table.create(n) :: { number } + for k = 1, n do + times[k] = IN(k - 1, 0) + end + local oc = out.components + local function get(e: number): { number } + local v = table.create(comps) :: { number } + for c = 0, comps - 1 do + local flat = e * comps + c + v[c + 1] = OUT(flat // oc, flat % oc) + end + return v + end + local function value(k: number): { number } + return get(if cubic then (k - 1) * 3 + 1 else k - 1) + end + local rot = ch.path == "rotation" + local step = ch.interpolation == "STEP" + return function(t: number): { number } + if t <= times[1] or n == 1 then + return if rot then normalize(value(1)) else value(1) + end + if t >= times[n] then + return if rot then normalize(value(n)) else value(n) + end + local lo, hi = 1, n + while hi - lo > 1 do + local mid = (lo + hi) // 2 + if times[mid] <= t then + lo = mid + else + hi = mid + end + end + local dt = times[hi] - times[lo] + local s = if dt > 0 then (t - times[lo]) / dt else 0 + if step then + return if rot then normalize(value(lo)) else value(lo) + end + if cubic then + local p0, m0 = value(lo), get((lo - 1) * 3 + 2) + local p1, m1 = value(hi), get((hi - 1) * 3) + local s2, s3 = s * s, s * s * s + local h00, h10, h01, h11 = 2 * s3 - 3 * s2 + 1, s3 - 2 * s2 + s, -2 * s3 + 3 * s2, s3 - s2 + local v = table.create(comps) :: { number } + for c = 1, comps do + v[c] = h00 * p0[c] + h10 * dt * m0[c] + h01 * p1[c] + h11 * dt * m1[c] + end + return if rot then normalize(v) else v + end + local a, b = value(lo), value(hi) + if rot then + return slerp(normalize(a), normalize(b), s) + end + local v = table.create(comps) :: { number } + for c = 1, comps do + v[c] = a[c] + (b[c] - a[c]) * s + end + return v + end +end + +function Sampler.times(anim: Types.Animation): { number } + local seen: { [number]: boolean } = {} + local out: { number } = {} + for _, ch in anim.channels do + local inp = ch.input + local IN = type(inp) == "table" and Types.Scene.reader(inp) + if IN then + for k = 0, inp.count - 1 do + local t = IN(k, 0) + if not seen[t] and t == t then + seen[t] = true + table.insert(out, t) + end + end + end + end + table.sort(out) + return out +end + +function Sampler.pose(_scene: Types.Scene, anim: Types.Animation, t: number, samplers: { [any]: any }?): Pose + local cache: { [any]: any } = samplers or {} + local pose: Pose = {} + for _, ch in anim.channels do + if cache[ch] == nil then + cache[ch] = Sampler.channel(ch) or false + end + local s: Sample? = cache[ch] or nil + if s then + local p = pose[ch.node] + if not p then + p = {} + pose[ch.node] = p + end + p[ch.path] = s(t) + end + end + return pose +end + +return Sampler +end +__FILES["codecs/model/Vrml"] = function() + +-- codecs/model/Vrml: VRML97 / X3D scene-graph engine (classic and XML encodings) for model/vrml and model/x3d. +-- VRML97 ISO/IEC 14772-1, X3D ISO/IEC 19775-1, encodings ISO/IEC 19776-1 (XML) / -2 (classic). New code. +local Err = __include("core/Err") +local Types = __include("Types") +local Deflate = __include("codecs/compress/Deflate") +local XmlCodec = __include("codecs/text/Xml") +local Parse = __include("codecs/model/Vrml/Parse") +local VXml = __include("codecs/model/Vrml/Xml") +local Build = __include("codecs/model/Vrml/Build") +local Write = __include("codecs/model/Vrml/Write") + +local Vrml = {} + +type Graph = Parse.Graph +type Node = Parse.Node +type Options = Build.Options & { + files: { [string]: any }?, + resolve: ((uri: string) -> any)?, + maxBytes: number?, +} + +local function text(data: buffer | string, maxBytes: number?): (string?, Err.Err?) + local b = if type(data) == "string" then buffer.fromstring(data) else data + if buffer.len(b) >= 2 and buffer.readu8(b, 0) == 0x1F and buffer.readu8(b, 1) == 0x8B then + local out, err = Deflate.gunzip(b) + if not out then + return nil, err + end + if buffer.len(out) > (maxBytes or 2 ^ 28) then + return nil, Err.new(Err.LIMIT, "inflated file over maxBytes") + end + b = out + end + local s = buffer.tostring(b) + if string.sub(s, 1, 3) == "\239\187\191" then + s = string.sub(s, 4) + end + return s, nil +end + +local function code(msg: string): string + if string.find(msg, "unsupported", 1, true) then + return Err.UNSUPPORTED + elseif string.find(msg, "limit", 1, true) then + return Err.LIMIT + elseif string.find(msg, "unterminated", 1, true) then + return Err.TRUNCATED + end + return Err.CORRUPT +end + +function Vrml.parse(s: string): (Graph?, Err.Err?) + local g, msg = Parse.parse(s) + if not g then + return nil, Err.new(code(msg or "parse error"), msg or "parse error") + end + return g, nil +end + +function Vrml.parseXml(src: any): (Graph?, Err.Err?) + local doc = src + if type(src) == "string" then + local d, err = XmlCodec.decode(src) + if not d and err and err.code == Err.TRUNCATED and not string.find(src, "</X3D>", 1, true) then + -- VTK's X3D exporter leaves the root element open + d = XmlCodec.decode(src .. "\n</X3D>\n") + end + if not d then + return nil, err + end + doc = d + end + local g, msg = VXml.graph(doc) + if not g then + return nil, Err.new(code(msg or "bad X3D"), msg or "bad X3D") + end + return g, nil +end + +function Vrml.graph(data: buffer | string, opts: Options?): (Graph?, Err.Err?) + local s, err = text(data, opts and opts.maxBytes) + if not s then + return nil, err + end + local head = string.match(s, "^%s*(.?)") + if head == "<" then + return Vrml.parseXml(s) + end + if string.sub(s, 1, 4) == "\224\0\0\1" or string.sub(s, 1, 4) == "$EXI" then + return nil, Err.new(Err.UNSUPPORTED, "binary X3D (Fast Infoset / EXI encoding)") + end + return Vrml.parse(s) +end + +function Vrml.fetcher(opts: Options?): (uri: string) -> buffer? + return function(uri: string): buffer? + if not opts then + return nil + end + local v: any = nil + if type(opts.files) == "table" then + v = opts.files[uri] or opts.files[string.match(uri, "([^/\\]+)$") or uri] + end + if v == nil and type(opts.resolve) == "function" then + local ok, res = pcall(opts.resolve, uri) + v = if ok then res else nil + end + return if type(v) == "string" then buffer.fromstring(v) elseif type(v) == "buffer" then v else nil + end +end + +function Vrml.build(graph: Graph, opts: Options?): (Types.Scene?, Err.Err?) + local o: any = table.clone(opts or {}) + o.fetch = o.fetch or Vrml.fetcher(opts) + o.load = o.load or function(data: buffer): (any, string?) + local g, err = Vrml.graph(data, opts) + return g, if err then err.message else nil + end + local scene, msg = Build.scene(graph, o) + if not scene then + return nil, Err.new(code(msg or "build failed"), msg or "build failed") + end + return scene, nil +end + +function Vrml.decode(data: buffer | string, opts: Options?): (Types.Scene?, Err.Err?) + local g, err = Vrml.graph(data, opts) + if not g then + return nil, err + end + return Vrml.build(g, opts) +end + +function Vrml.encode(scene: Types.Scene, opts: Write.Options?): (string?, 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 s, msg = Write.text(scene, opts or {}) + if not s then + return nil, Err.new(Err.ARG, msg or "the scene could not be written") + end + return s, nil +end + +return Vrml +end +__FILES["codecs/model/Vrml/Build"] = function() + +-- codecs/model/Vrml/Build: the VRML97 / X3D node graph to a Scene. Written from the specifications; no third-party code. +-- A Transform is one TRS node (translation T + C, rotation R * SR, scale S) plus, when it has a center or scale +-- orientation, an inner node (rotation SR^-1, translation SR^-1 * -C) holding the children. +local Types = __include("Types") +local Mat4 = __include("codecs/model/Mat4") +local Fields = __include("codecs/model/Vrml/Fields") +local Geometry = __include("codecs/model/Vrml/Geometry") + +local Build = {} + +local S = Types.Scene +local nums, num, vec, bool, str, strs, node, nodes = Fields.nums, Fields.num, Fields.vec, Fields.bool, Fields.str, Fields.strs, Fields.node, Fields.nodes +local deg = math.deg + +type Options = Geometry.Options & { + fetch: ((uri: string) -> buffer?)?, + load: ((data: buffer) -> (any, string?))?, + format: string?, + maxInline: number?, +} + +local GROUP = { Group = true, Anchor = true, Billboard = true, Collision = true, StaticGroup = true, CADAssembly = true, CADLayer = true, LayerSet = true, Layer = true, HAnimSegment = true, HAnimSite = true, LOD = true, Switch = true } +local TRANSFORM = { Transform = true, CADPart = true, HAnimHumanoid = true, HAnimJoint = true } +local CHILDREN = { "children", "skeleton", "segments", "sites", "layers" } +local QUIET = { + WorldInfo = true, NavigationInfo = true, Background = true, TextureBackground = true, Fog = true, TimeSensor = true, + PositionInterpolator = true, OrientationInterpolator = true, ScalarInterpolator = true, ColorInterpolator = true, + CoordinateInterpolator = true, NormalInterpolator = true, TouchSensor = true, ProximitySensor = true, + VisibilitySensor = true, PlaneSensor = true, CylinderSensor = true, SphereSensor = true, Script = true, Sound = true, + AudioClip = true, MetadataString = true, MetadataFloat = true, MetadataInteger = true, MetadataDouble = true, + MetadataSet = true, MetadataBoolean = true, BooleanFilter = true, BooleanToggle = true, BooleanTrigger = true, + BooleanSequencer = true, IntegerSequencer = true, IntegerTrigger = true, TimeTrigger = true, KeySensor = true, + StringSensor = true, LoadSensor = true, +} +local MIME = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", gif = "image/gif", bmp = "image/bmp", webp = "image/webp", ktx2 = "image/ktx2", dds = "image/vnd-ms.dds", tga = "image/x-tga" } + +local function quat(r: { number }): { number } + return Mat4.axisAngle(r[1], r[2], r[3], deg(r[4])) +end +local function qmul(a: { number }, b: { number }): { number } + return { + a[4] * b[1] + a[1] * b[4] + a[2] * b[3] - a[3] * b[2], + a[4] * b[2] - a[1] * b[3] + a[2] * b[4] + a[3] * b[1], + a[4] * b[3] + a[1] * b[2] - a[2] * b[1] + a[3] * b[4], + a[4] * b[4] - a[1] * b[1] - a[2] * b[2] - a[3] * b[3], + } +end +local function qrot(q: { number }, v: { number }): { number } + local m = Mat4.fromQuat(q) + local x, y, z = Mat4.point(m, v[1], v[2], v[3]) + return { x, y, z } +end +local function isZero(v: { number }): boolean + return v[1] == 0 and v[2] == 0 and v[3] == 0 +end +local function isIdentityQ(q: { number }): boolean + return q[1] == 0 and q[2] == 0 and q[3] == 0 +end +local function between(a: { number }, b: { number }): { number } + local l = math.sqrt(b[1] * b[1] + b[2] * b[2] + b[3] * b[3]) + if l < 1e-12 then + return { 0, 0, 0, 1 } + end + local bx, by, bz = b[1] / l, b[2] / l, b[3] / l + local d = a[1] * bx + a[2] * by + a[3] * bz + if d < -0.999999 then + return if math.abs(a[1]) < 0.9 then { 0, a[3], -a[2], 0 } else { -a[3], 0, a[1], 0 } + end + local cx, cy, cz = a[2] * bz - a[3] * by, a[3] * bx - a[1] * bz, a[1] * by - a[2] * bx + local w = 1 + d + local n = math.sqrt(cx * cx + cy * cy + cz * cz + w * w) + return { cx / n, cy / n, cz / n, w / n } +end + +type Ctx = { + scene: Types.Scene, + opts: Options, + meshes: { [any]: any }, + materials: { [any]: any }, + textures: { [any]: number }, + instances: { [any]: { { node: number, center: { number }, so: { number } } } }, + skipped: { [string]: number }, + depth: number, + inline: number, + failure: string?, +} + +local function addNode(ctx: Ctx, n: Types.Node, parent: number?): number + local nodes_ = ctx.scene.nodes + table.insert(nodes_, n) + local i = #nodes_ + if parent then + table.insert(nodes_[parent].children, i) + else + table.insert(ctx.scene.roots, i) + end + return i +end + +local function texture(ctx: Ctx, t: any): number? + if not t then + return nil + end + if t.type == "MultiTexture" then + return texture(ctx, nodes(t, "texture")[1]) + end + local cached = ctx.textures[t] + if cached then + return cached + end + local tex: Types.Texture = { name = t.def } + if t.type == "ImageTexture" or t.type == "MovieTexture" then + local urls = strs(t, "url") + local fetch = ctx.opts.fetch + for _, u in urls do + local clean = string.match(u, "^([^#?]*)") or u + if not tex.uri and not string.find(clean, "^%a[%w+.-]*://") then + tex.uri = clean + end + local data = fetch and fetch(clean) + if data then + tex.uri, tex.data = clean, data + break + end + end + tex.uri = tex.uri or urls[1] + local ext = tex.uri and string.match(tex.uri, "%.(%w+)$") + tex.mime = if ext then MIME[string.lower(ext)] else nil + elseif t.type == "PixelTexture" then + -- SFImage: width height components pixels (0xRRGGBBAA style integers, MSB first) + local v = nums(t, "image") or {} + local w, h, c = math.floor(v[1] or 0), math.floor(v[2] or 0), math.floor(v[3] or 0) + if w > 0 and h > 0 and c >= 1 and c <= 4 and w * h <= 2 ^ 24 and #v >= 3 + w * h then + local img = Types.Image.new(w, h) + for i = 0, w * h - 1 do + local px = math.floor(v[4 + i]) % 2 ^ (8 * c) + local b = table.create(4, 0) + for k = c, 1, -1 do + b[k] = px % 256 + px //= 256 + end + local r, g, bl, a + if c <= 2 then + r, g, bl, a = b[1], b[1], b[1], if c == 2 then b[2] else 255 + else + r, g, bl, a = b[1], b[2], b[3], if c == 4 then b[4] else 255 + end + -- the image's first row is the bottom one + local row = h - 1 - i // w + local o = (row * w + i % w) * 4 + buffer.writeu8(img.pixels, o, r) + buffer.writeu8(img.pixels, o + 1, g) + buffer.writeu8(img.pixels, o + 2, bl) + buffer.writeu8(img.pixels, o + 3, a) + end + tex.image = img + end + else + ctx.skipped[t.type] = (ctx.skipped[t.type] or 0) + 1 + return nil + end + local rs, rt = bool(t, "repeatS", true), bool(t, "repeatT", true) + if not rs or not rt then + tex.sampler = { wrapS = if rs then "repeat" else "clamp", wrapT = if rt then "repeat" else "clamp" } + end + table.insert(ctx.scene.textures, tex) + ctx.textures[t] = #ctx.scene.textures + return #ctx.scene.textures +end + +local function textureRef(ctx: Ctx, t: any, xf: any): Types.TextureRef? + local i = texture(ctx, t) + if not i then + return nil + end + local ref: Types.TextureRef = { texture = i } + if xf and xf.type == "TextureTransform" then + local tr, sc, rot = vec(xf, "translation", { 0, 0 }), vec(xf, "scale", { 1, 1 }), num(xf, "rotation", 0) + if tr[1] ~= 0 or tr[2] ~= 0 or sc[1] ~= 1 or sc[2] ~= 1 or rot ~= 0 then + ref.transform = { offset = tr, scale = sc, rotation = rot } + end + end + return ref +end + +local function material(ctx: Ctx, app: any, solid: boolean): number? + if not app and solid then + return nil + end + local key = app or "default" + local cache = ctx.materials[key] + if type(cache) ~= "table" then + cache = {} + ctx.materials[key] = cache + end + local hit = (cache :: any)[solid] + if hit then + return hit + end + local m = S.material(app and app.def) + m.metallic = 0 + local x: { [string]: any } = {} + local mat = app and node(app, "material") + local tex = app and node(app, "texture") + local xf = app and node(app, "textureTransform") + if mat and mat.type == "TwoSidedMaterial" then + m.doubleSided = true + x.twoSided = true + end + if mat and (mat.type == "Material" or mat.type == "TwoSidedMaterial") then + local d, e, sp = vec(mat, "diffuseColor", { 0.8, 0.8, 0.8 }), vec(mat, "emissiveColor", { 0, 0, 0 }), vec(mat, "specularColor", { 0, 0, 0 }) + local sh, tr, amb = num(mat, "shininess", 0.2), num(mat, "transparency", 0), num(mat, "ambientIntensity", 0.2) + m.name = mat.def or m.name + m.baseColor = { d[1], d[2], d[3], 1 - tr } + m.emissive = e + m.roughness = math.clamp(math.sqrt(2 / (math.max(sh, 0) * 128 + 2)), 0, 1) + x.diffuseColor, x.emissiveColor, x.specularColor, x.shininess, x.transparency, x.ambientIntensity = d, e, sp, sh, tr, amb + if tr > 0 then + m.alphaMode = "blend" + end + -- X3D 4 texture fields + local dt = node(mat, "diffuseTexture") + if dt then + m.baseColorTexture = textureRef(ctx, dt, nil) + end + local nt = node(mat, "normalTexture") + if nt then + m.normalTexture = textureRef(ctx, nt, nil) + end + elseif mat and mat.type == "PhysicalMaterial" then + local b, e = vec(mat, "baseColor", { 1, 1, 1 }), vec(mat, "emissiveColor", { 0, 0, 0 }) + local tr = num(mat, "transparency", 0) + m.name = mat.def or m.name + m.baseColor = { b[1], b[2], b[3], 1 - tr } + m.emissive, m.metallic, m.roughness = e, num(mat, "metallic", 1), num(mat, "roughness", 1) + if tr > 0 then + m.alphaMode = "blend" + end + local slots: { [string]: string } = { baseTexture = "baseColorTexture", metallicRoughnessTexture = "metallicRoughnessTexture", normalTexture = "normalTexture", occlusionTexture = "occlusionTexture", emissiveTexture = "emissiveTexture" } + for field, slot in slots do + local t = node(mat, field) + if t then + (m :: any)[slot] = textureRef(ctx, t, nil) + end + end + elseif mat and mat.type == "UnlitMaterial" then + local e = vec(mat, "emissiveColor", { 1, 1, 1 }) + m.name = mat.def or m.name + m.baseColor = { e[1], e[2], e[3], 1 - num(mat, "transparency", 0) } + m.extensions = { KHR_materials_unlit = {} } + else + -- no material: unlit white (the specifications' default) + m.extensions = { KHR_materials_unlit = {} } + end + if tex and not m.baseColorTexture then + m.baseColorTexture = textureRef(ctx, tex, xf) + if m.baseColorTexture and xf then + x.textureCenter = vec(xf, "center", { 0, 0 }) + end + end + if not solid then + m.doubleSided = true + end + m.extras = { vrml = x } + table.insert(ctx.scene.materials, m) + local idx = #ctx.scene.materials + ;(cache :: any)[solid] = idx + return idx +end + +local walk: (ctx: Ctx, n: any, parent: number?) -> () + +local function shape(ctx: Ctx, n: any, parent: number?) + local geo = node(n, "geometry") + if not geo then + return + end + local mi = ctx.meshes[n] + if mi == nil then + local prim, solidOrErr = Geometry.primitive(geo, ctx.opts) + if not prim then + if solidOrErr then + ctx.failure = ctx.failure or solidOrErr + else + ctx.skipped[geo.type] = (ctx.skipped[geo.type] or 0) + 1 + end + ctx.meshes[n] = false :: any + return + end + local count = if prim.indices then prim.indices.count else prim.attributes.POSITION.count + if count == 0 then + ctx.meshes[n] = false + return + end + prim.material = material(ctx, node(n, "appearance"), solidOrErr == true) + table.insert(ctx.scene.meshes, { name = n.def or geo.def, primitives = { prim } }) + mi = #ctx.scene.meshes + ctx.meshes[n] = mi + elseif mi == false then + return + end + addNode(ctx, { name = n.def, children = {}, mesh = mi }, parent) +end + +local function viewpoint(ctx: Ctx, n: any, parent: number?) + local cam: any + if n.type == "OrthoViewpoint" then + local f = vec(n, "fieldOfView", { -1, -1, 1, 1 }) + cam = { type = "orthographic", xmag = (f[3] - f[1]) / 2, ymag = (f[4] - f[2]) / 2, znear = 0.125, zfar = 1e4 } + else + cam = { type = "perspective", yfov = num(n, "fieldOfView", 0.785398), znear = 0.125 } + end + cam.name = n.def or str(n, "description") + table.insert(ctx.scene.cameras, cam) + local o = vec(n, "orientation", { 0, 0, 1, 0 }) + local nd: Types.Node = { name = cam.name, children = {}, camera = #ctx.scene.cameras, translation = vec(n, "position", { 0, 0, 10 }) } + if o[4] ~= 0 then + nd.rotation = quat(o) + end + addNode(ctx, nd, parent) +end + +local function light(ctx: Ctx, n: any, parent: number?) + local t = n.type + local l: Types.Light = { name = n.def, type = "point", color = vec(n, "color", { 1, 1, 1 }), intensity = num(n, "intensity", 1) } + local nd: Types.Node = { name = n.def, children = {} } + local x: { [string]: any } = { ambientIntensity = num(n, "ambientIntensity", 0), on = bool(n, "on", true), global = bool(n, "global", t == "DirectionalLight") } + if t == "DirectionalLight" then + l.type = "directional" + nd.rotation = between({ 0, 0, -1 }, vec(n, "direction", { 0, 0, -1 })) + else + nd.translation = vec(n, "location", { 0, 0, 0 }) + l.range = num(n, "radius", 100) + x.attenuation = vec(n, "attenuation", { 1, 0, 0 }) + if t == "SpotLight" then + l.type = "spot" + nd.rotation = between({ 0, 0, -1 }, vec(n, "direction", { 0, 0, -1 })) + local cut = num(n, "cutOffAngle", 0.785398) + l.outerCone = cut + l.innerCone = math.min(num(n, "beamWidth", 1.570796), cut) + end + end + ;(l :: any).extras = { vrml = x } + table.insert(ctx.scene.lights, l) + nd.light = #ctx.scene.lights + addNode(ctx, nd, parent) +end + +local function children(ctx: Ctx, n: any, parent: number?) + if n.type == "Switch" then + local which = math.floor(num(n, "whichChoice", -1)) + local list = nodes(n, "choice") + if #list == 0 then + list = nodes(n, "children") + end + local c = list[which + 1] + if which >= 0 and c then + walk(ctx, c, parent) + end + return + elseif n.type == "LOD" then + local list = nodes(n, "level") + if #list == 0 then + list = nodes(n, "children") + end + if list[1] then + walk(ctx, list[1], parent) + end + return + end + for _, f in CHILDREN do + for _, c in nodes(n, f) do + walk(ctx, c, parent) + end + end +end + +local function transform(ctx: Ctx, n: any, parent: number?) + local t, c = vec(n, "translation", { 0, 0, 0 }), vec(n, "center", { 0, 0, 0 }) + local r, s, so = vec(n, "rotation", { 0, 0, 1, 0 }), vec(n, "scale", { 1, 1, 1 }), vec(n, "scaleOrientation", { 0, 0, 1, 0 }) + local qr, qs = quat(r), quat(so) + local outer: Types.Node = { name = n.def, children = {} } + local tt = { t[1] + c[1], t[2] + c[2], t[3] + c[3] } + if not isZero(tt) then + outer.translation = tt + end + local q = if isIdentityQ(qs) then qr else qmul(qr, qs) + if not isIdentityQ(q) then + outer.rotation = q + end + if s[1] ~= 1 or s[2] ~= 1 or s[3] ~= 1 then + outer.scale = s + end + local oi = addNode(ctx, outer, parent) + local list = ctx.instances[n] + if not list then + list = {} + ctx.instances[n] = list + end + table.insert(list, { node = oi, center = c, so = qs }) + local holder = oi + if not isZero(c) or not isIdentityQ(qs) then + local inv = { -qs[1], -qs[2], -qs[3], qs[4] } + local inner: Types.Node = { children = {}, translation = qrot(inv, { -c[1], -c[2], -c[3] }) } + if not isIdentityQ(inv) then + inner.rotation = inv + end + holder = addNode(ctx, inner, oi) + end + children(ctx, n, holder) +end + +local function inline(ctx: Ctx, n: any, parent: number?) + local fetch, load = ctx.opts.fetch, ctx.opts.load + if not fetch or not load or ctx.inline >= (ctx.opts.maxInline or 8) or not bool(n, "load", true) then + ctx.skipped.Inline = (ctx.skipped.Inline or 0) + 1 + return + end + for _, u in strs(n, "url") do + local data = fetch(string.match(u, "^([^#?]*)") or u) + if data then + local g = load(data) + if g then + local holder = addNode(ctx, { name = n.def, children = {} }, parent) + ctx.inline += 1 + for _, root in g.roots do + walk(ctx, root, holder) + end + ctx.inline -= 1 + return + end + end + end + ctx.skipped.Inline = (ctx.skipped.Inline or 0) + 1 +end + +function walk(ctx: Ctx, n: any, parent: number?) + if ctx.failure or type(n) ~= "table" then + return + end + ctx.depth += 1 + if ctx.depth > 200 then + ctx.failure = "limit: scene nested deeper than 200" + return + end + local t = n.type + if TRANSFORM[t] then + transform(ctx, n, parent) + elseif GROUP[t] then + local holder = parent + if n.def or parent == nil then + holder = addNode(ctx, { name = n.def, children = {} }, parent) + end + children(ctx, n, holder) + elseif t == "Shape" then + shape(ctx, n, parent) + elseif t == "CADFace" then + for _, s in nodes(n, "shape") do + walk(ctx, s, parent) + end + elseif t == "Viewpoint" or t == "OrthoViewpoint" then + viewpoint(ctx, n, parent) + elseif t == "DirectionalLight" or t == "PointLight" or t == "SpotLight" then + light(ctx, n, parent) + elseif t == "Inline" then + inline(ctx, n, parent) + elseif t == "WorldInfo" then + local src = ctx.scene.meta.source :: any + src.title = str(n, "title") + local info = strs(n, "info") + src.info = if #info > 0 then info else nil + elseif not QUIET[t] then + ctx.skipped[t] = (ctx.skipped[t] or 0) + 1 + end + ctx.depth -= 1 +end + +local TARGET = { set_translation = "translation", translation = "translation", set_rotation = "rotation", rotation = "rotation", set_scale = "scale", scale = "scale" } + +local function animations(ctx: Ctx, routes: { any }) + local timer: { [any]: any } = {} + for _, r in routes do + if (r.toField == "set_fraction" or r.toField == "fraction") and r.from.type == "TimeSensor" then + timer[r.to] = r.from + end + end + local anims: { [any]: Types.Animation } = {} + local order: { any } = {} + for _, r in routes do + local path = TARGET[r.toField] + local it = r.from + local inst = ctx.instances[r.to] + if not (path and inst and (it.type == "PositionInterpolator" or it.type == "OrientationInterpolator")) then + continue + end + if (path == "rotation") ~= (it.type == "OrientationInterpolator") then + continue + end + local key: { number }, kv: { number } = nums(it, "key") or {}, nums(it, "keyValue") or {} + local comps = if path == "rotation" then 4 else 3 + local n = math.min(#key, #kv // comps) + if n == 0 then + continue + end + local ts = timer[it] + local cycle = if ts then num(ts, "cycleInterval", 1) else 1 + local input = S.accessor(nil, "f32", 1, n) + for i = 0, n - 1 do + buffer.writef32(input.data, i * 4, key[i + 1] * cycle) + end + local id = ts or "routes" + local anim = anims[id] + if not anim then + anim = { name = if ts then ts.def else nil, channels = {} } + anims[id] = anim + table.insert(order, id) + end + for _, at in inst do + local out = S.accessor(nil, "f32", if path == "rotation" then 4 else 3, n) + local prev: { number }? = nil + for i = 0, n - 1 do + local v: { number } + if path == "rotation" then + v = quat({ kv[i * 4 + 1], kv[i * 4 + 2], kv[i * 4 + 3], kv[i * 4 + 4] }) + if not isIdentityQ(at.so) then + v = qmul(v, at.so) + end + if prev and prev[1] * v[1] + prev[2] * v[2] + prev[3] * v[3] + prev[4] * v[4] < 0 then + v = { -v[1], -v[2], -v[3], -v[4] } + end + prev = v + elseif path == "translation" then + v = { kv[i * 3 + 1] + at.center[1], kv[i * 3 + 2] + at.center[2], kv[i * 3 + 3] + at.center[3] } + else + v = { kv[i * 3 + 1], kv[i * 3 + 2], kv[i * 3 + 3] } + end + for c = 1, #v do + buffer.writef32(out.data, (i * #v + c - 1) * 4, v[c]) + end + end + table.insert(anim.channels, { node = at.node, path = path :: any, input = input, output = out, interpolation = "LINEAR" :: any }) + end + end + for _, id in order do + table.insert(ctx.scene.animations, anims[id]) + end +end + +function Build.scene(graph: any, opts: Options): (Types.Scene?, string?) + local scene = S.new() + scene.meta.up = "y" + local units = graph.units or {} + scene.meta.unit = if units.length and units.length.factor > 0 then units.length.factor else 1 + local h = graph.header or {} + local skipped: { [string]: number } = {} + scene.meta.source = { + format = opts.format or "vrml", version = h.version, encoding = h.encoding, profile = h.profile, x3d = h.x3d, + xml = h.xml, meta = graph.meta, components = graph.components, skipped = skipped, + } + local ctx: Ctx = { scene = scene, opts = opts, meshes = {}, materials = {}, textures = {}, instances = {}, skipped = skipped, depth = 0, inline = 0, failure = nil } + for _, n in graph.roots do + walk(ctx, n, nil) + end + if ctx.failure then + return nil, ctx.failure + end + animations(ctx, graph.routes or {}) + return scene, nil +end + +return Build +end +__FILES["codecs/model/Vrml/Fields"] = function() + +-- codecs/model/Vrml/Fields: typed reads of VRML / X3D node fields (classic arrays or X3D XML attribute strings). +local Fields = {} + +local gmatch, find, sub, byte = string.gmatch, string.find, string.sub, string.byte + +local function mfString(s: string): { string } + local out = {} + local p = find(s, "[^%s,]") + if not p or byte(s, p) ~= 34 then + return if p then { (string.match(s, "^%s*(.-)%s*$") :: string) } else {} + end + local n = #s + while p and p <= n do + if byte(s, p) ~= 34 then + break + end + local q = p + 1 + local parts = {} + while true do + local e = find(s, '["\\]', q) + if not e then + table.insert(parts, sub(s, q)) + table.insert(out, table.concat(parts)) + return out + end + table.insert(parts, sub(s, q, e - 1)) + if byte(s, e) == 92 then + table.insert(parts, sub(s, e + 1, e + 1)) + q = e + 2 + else + p = e + 1 + break + end + end + table.insert(out, table.concat(parts)) + p = find(s, "[^%s,]", p) + end + return out +end + +function Fields.nums(node: any, name: string): { number }? + local v = node.fields[name] + if v == nil then + return nil + end + if type(v) == "string" then + local out = {} + for w in gmatch(v, "[^%s,]+") do + local x = tonumber(w) + if x then + table.insert(out, x) + elseif w == "true" or w == "TRUE" then + table.insert(out, 1) + elseif w == "false" or w == "FALSE" then + table.insert(out, 0) + end + end + node.fields[name] = out + return out + end + if type(v) ~= "table" then + return nil + end + local ok = true + for _, x in v do + if type(x) ~= "number" then + ok = false + break + end + end + if ok then + return v + end + local out = {} + for _, x in v do + if type(x) == "number" then + table.insert(out, x) + elseif type(x) == "boolean" then + table.insert(out, if x then 1 else 0) + end + end + return out +end + +function Fields.num(node: any, name: string, default: number): number + local v = Fields.nums(node, name) + return if v and type(v[1]) == "number" then v[1] else default +end + +function Fields.vec(node: any, name: string, default: { number }): { number } + local v = Fields.nums(node, name) + if not v or #v < #default then + return default + end + local out: { number } = {} + for i = 1, #default do + out[i] = v[i] + end + return out +end + +function Fields.bool(node: any, name: string, default: boolean): boolean + local v = node.fields[name] + if type(v) == "string" then + local w = string.lower(string.match(v, "^%s*(%S*)") :: string) + return if w == "true" then true elseif w == "false" then false else default + end + if type(v) == "table" and type(v[1]) == "boolean" then + return v[1] + end + return default +end + +function Fields.strs(node: any, name: string): { string } + local v = node.fields[name] + if type(v) == "string" then + local out = mfString(v) + node.fields[name] = out + return out + end + local out = {} + if type(v) == "table" then + for _, x in v do + if type(x) == "string" then + table.insert(out, x) + end + end + end + return out +end + +function Fields.str(node: any, name: string, default: string?): string? + local v = node.fields[name] + if type(v) == "string" then + return v + end + if type(v) == "table" and type(v[1]) == "string" then + return v[1] + end + return default +end + +function Fields.nodes(node: any, name: string): { any } + local v = node.fields[name] + local out = {} + if type(v) == "table" then + for _, x in v do + if type(x) == "table" and type(x.type) == "string" then + table.insert(out, x) + end + end + end + return out +end + +function Fields.node(node: any, name: string): any + return Fields.nodes(node, name)[1] +end + +return Fields +end +__FILES["codecs/model/Vrml/Geometry"] = function() + +-- codecs/model/Vrml/Geometry: VRML97 / X3D geometry nodes to Scene primitives. New code, from the specifications. +-- Texture t is flipped to glTF's top-left origin unless flipV = false. +local Types = __include("Types") +local Fields = __include("codecs/model/Vrml/Fields") + +local Geometry = {} + +local S = Types.Scene +local nums, num, vec, bool, node = Fields.nums, Fields.num, Fields.vec, Fields.bool, Fields.node +local sqrt, sin, cos, pi = math.sqrt, math.sin, math.cos, math.pi + +type Options = { flipV: boolean?, triangulate: boolean?, segments: number?, maxVertices: number? } + +local function f32(list: { number }, comps: number, count: number): Types.Accessor + local a = S.accessor(nil, "f32", comps, count) + local d = a.data + for i = 1, math.min(#list, comps * count) do + buffer.writef32(d, (i - 1) * 4, list[i]) + end + return a +end + +local function u32(list: { number }): Types.Accessor + local a = S.accessor(nil, "u32", 1, #list) + for i, v in list do + buffer.writeu32(a.data, (i - 1) * 4, v) + end + return a +end + +local function colors(n: any): ({ number }?, number) + local c = node(n, "color") + if not c then + return nil, 3 + end + local comps = if c.type == "ColorRGBA" then 4 else 3 + return nums(c, "color") or {}, comps +end + +local function points(n: any, field: string, sub: string): { number }? + local c = node(n, field) + return if c then nums(c, sub) or {} else nil +end + +type PolyIn = { + P: { number }, + corners: { number }, + sizes: { number }, + N: { number }?, nIdx: { number }?, nFace: boolean?, + C: { number }?, cComps: number?, cIdx: { number }?, cFace: boolean?, + T: { number }?, tIdx: { number }?, + ccw: boolean, +} + +local function polyMesh(m: PolyIn, o: Options, maxV: number): (any, string?) + local P, corners, sizes = m.P, m.corners, m.sizes + local np = #P // 3 + local N, C, T = m.N, m.C, m.T + local cc = m.cComps or 3 + local function idx(list: { number }?, perFace: boolean?, f: number, k: number, c: number): number + if perFace then + return if list and #list > 0 then (list[f] or 0) else f - 1 + end + return if list and #list > 0 then (list[k] or c) else c + end + local simple = (N == nil or (not m.nFace and (m.nIdx == nil or #m.nIdx == 0))) and (C == nil or (not m.cFace and (m.cIdx == nil or #m.cIdx == 0))) and (T == nil or m.tIdx == nil or #m.tIdx == 0) + local vkey: { [string]: number } = {} + local vsrc: { { number } } = {} + local out: { number } = {} + local outSizes: { number } = {} + local k = 0 + for f, size in sizes do + local face: { number } = {} + local valid = size >= 3 + for q = 1, size do + k += 1 + local c = corners[k] + if c == nil or c < 0 or c >= np then + valid = false + end + face[q] = k + end + if valid then + local verts: { number } = {} + for q, kk in face do + local c = corners[kk] + if simple then + verts[q] = c + else + local ni = if N then idx(m.nIdx, m.nFace, f, kk, c) else -1 + local ci = if C then idx(m.cIdx, m.cFace, f, kk, c) else -1 + local ti = if T then idx(m.tIdx, false, f, kk, c) else -1 + local key = c .. ":" .. ni .. ":" .. ci .. ":" .. ti + local v = vkey[key] + if not v then + v = #vsrc + vsrc[v + 1] = { c, ni, ci, ti } + vkey[key] = v + if v >= maxV then + return nil, "limit: more than " .. maxV .. " vertices" + end + end + verts[q] = v + end + end + if not m.ccw then + for a = 2, (size + 1) // 2 do + verts[a], verts[size + 2 - a] = verts[size + 2 - a], verts[a] + end + end + if o.triangulate == false then + table.insert(outSizes, size) + for _, v in verts do + table.insert(out, v) + end + else + for a = 2, size - 1 do + table.insert(out, verts[1]) + table.insert(out, verts[a]) + table.insert(out, verts[a + 1]) + end + end + end + end + local nv = if simple then np else #vsrc + if nv > maxV then + return nil, "limit: more than " .. maxV .. " vertices" + end + local flipV = o.flipV ~= false + local pos = S.accessor(nil, "f32", 3, nv) + local nrm = if N then S.accessor(nil, "f32", 3, nv) else nil + local col = if C then S.accessor(nil, "f32", cc, nv) else nil + local tex = if T then S.accessor(nil, "f32", 2, nv) else nil + local wf = buffer.writef32 + for v = 0, nv - 1 do + local s = if simple then nil else vsrc[v + 1] + local c = if s then s[1] else v + for q = 0, 2 do + wf(pos.data, (v * 3 + q) * 4, P[c * 3 + q + 1] or 0) + end + if nrm and N then + local ni = if s then s[2] else v + for q = 0, 2 do + wf(nrm.data, (v * 3 + q) * 4, N[ni * 3 + q + 1] or 0) + end + end + if col and C then + local ci = if s then s[3] else v + for q = 0, cc - 1 do + wf(col.data, (v * cc + q) * 4, C[ci * cc + q + 1] or 1) + end + end + if tex and T then + local ti = if s then s[4] else v + local tt = T[ti * 2 + 2] or 0 + wf(tex.data, v * 8, T[ti * 2 + 1] or 0) + wf(tex.data, v * 8 + 4, if flipV then 1 - tt else tt) + end + end + local attrs: { [string]: Types.Accessor } = { POSITION = pos } + attrs.NORMAL, attrs.COLOR_0, attrs.TEXCOORD_0 = nrm, col, tex + local prim: Types.Primitive = { attributes = attrs, indices = u32(out), mode = "triangles" } + if o.triangulate == false then + prim.mode = "polygons" + prim.faces = u32(outSizes) + end + return prim +end + +local function split(list: { number }): ({ number }, { number }) + local corners, sizes = {}, {} + local run = 0 + for _, x in list do + if x < 0 then + if run > 0 then + table.insert(sizes, run) + end + run = 0 + else + table.insert(corners, x) + run += 1 + end + end + if run > 0 then + table.insert(sizes, run) + end + return corners, sizes +end + +-- per-face index lists keep only the entries of faces (the -1 separators of per-corner lists match the corners) +local function cornerList(list: { number }?): { number }? + if not list or #list == 0 then + return nil + end + local out = {} + for _, x in list do + if x >= 0 then + table.insert(out, x) + end + end + return out +end + +local function faceSet(n: any, o: Options, maxV: number): (Types.Primitive?, string?) + local P = points(n, "coord", "point") or {} + local corners, sizes = split(nums(n, "coordIndex") or {}) + local nPer, cPer = bool(n, "normalPerVertex", true), bool(n, "colorPerVertex", true) + local C, cc = colors(n) + local tc = node(n, "texCoord") + local m: PolyIn = { + P = P, corners = corners, sizes = sizes, ccw = bool(n, "ccw", true), + N = points(n, "normal", "vector"), nFace = not nPer, nIdx = if nPer then cornerList(nums(n, "normalIndex")) else nums(n, "normalIndex"), + C = C, cComps = cc, cFace = not cPer, cIdx = if cPer then cornerList(nums(n, "colorIndex")) else nums(n, "colorIndex"), + T = if tc and tc.type ~= "TextureCoordinateGenerator" then (nums(if tc.type == "MultiTextureCoordinate" then (node(tc, "texCoord") or tc) else tc, "point") or {}) else nil, + tIdx = cornerList(nums(n, "texCoordIndex")), + } + return polyMesh(m, o, maxV) +end + +local function triSet(n: any, o: Options, maxV: number): (Types.Primitive?, string?) + local t = n.type + local P = points(n, "coord", "point") or {} + local np = #P // 3 + local index = nums(n, "index") + local seq: { number } + if string.sub(t, 1, 7) == "Indexed" then + seq = index or {} + else + seq = {} + for i = 0, np - 1 do + seq[i + 1] = i + end + end + local corners, sizes = {}, {} + local function tri(a: number, b: number, c: number) + table.insert(corners, a) + table.insert(corners, b) + table.insert(corners, c) + table.insert(sizes, 3) + end + -- runs: -1 separated (indexed fans / strips) or fanCount / stripCount (plain fans / strips) + local function runs(): { { number } } + local out = {} + local counts = nums(n, if string.find(t, "Fan", 1, true) then "fanCount" else "stripCount") + if string.sub(t, 1, 7) == "Indexed" or not counts then + local cur = {} + for _, x in seq do + if x < 0 then + table.insert(out, cur) + cur = {} + else + table.insert(cur, x) + end + end + table.insert(out, cur) + else + local at = 1 + for _, c in counts do + local cur = {} + for q = 0, c - 1 do + cur[q + 1] = seq[at + q] + end + at += c + table.insert(out, cur) + end + end + return out + end + if t == "IndexedTriangleSet" or t == "TriangleSet" then + for i = 1, #seq - 2, 3 do + tri(seq[i], seq[i + 1], seq[i + 2]) + end + elseif t == "IndexedQuadSet" or t == "QuadSet" then + for i = 1, #seq - 3, 4 do + for q = 0, 3 do + table.insert(corners, seq[i + q]) + end + table.insert(sizes, 4) + end + elseif string.find(t, "Fan", 1, true) then + for _, r in runs() do + for i = 2, #r - 1 do + tri(r[1], r[i], r[i + 1]) + end + end + else + for _, r in runs() do + for i = 1, #r - 2 do + if i % 2 == 1 then + tri(r[i], r[i + 1], r[i + 2]) + else + tri(r[i + 1], r[i], r[i + 2]) + end + end + end + end + local nPer, cPer = bool(n, "normalPerVertex", true), bool(n, "colorPerVertex", true) + local C, cc = colors(n) + local tc = node(n, "texCoord") + local m: PolyIn = { + P = P, corners = corners, sizes = sizes, ccw = bool(n, "ccw", true), + N = points(n, "normal", "vector"), nFace = not nPer, C = C, cComps = cc, cFace = not cPer, + T = if tc and tc.type == "TextureCoordinate" then nums(tc, "point") or {} else nil, + } + return polyMesh(m, o, maxV) +end + +local function elevationGrid(n: any, o: Options, maxV: number): (Types.Primitive?, string?) + local nx, nz = math.floor(num(n, "xDimension", 0)), math.floor(num(n, "zDimension", 0)) + local dx, dz = num(n, "xSpacing", 1), num(n, "zSpacing", 1) + local h: { number } = nums(n, "height") or {} + if nx < 2 or nz < 2 then + return nil, nil + end + if nx * nz > maxV then + return nil, "limit: elevation grid of " .. nx .. " x " .. nz + end + local P: { number }, T: { number }, corners: { number }, sizes: { number } = {}, {}, {}, {} + for z = 0, nz - 1 do + for x = 0, nx - 1 do + table.insert(P, x * dx) + table.insert(P, h[z * nx + x + 1] or 0) + table.insert(P, z * dz) + table.insert(T, x / (nx - 1)) + table.insert(T, z / (nz - 1)) + end + end + for z = 0, nz - 2 do + for x = 0, nx - 2 do + local a = z * nx + x + -- counter-clockwise seen from +y: a, a + nx, a + nx + 1, a + 1 + for _, c in { a, a + nx, a + nx + 1, a + 1 } do + table.insert(corners, c) + end + table.insert(sizes, 4) + end + end + local C, cc = colors(n) + local tc = node(n, "texCoord") + local m: PolyIn = { + P = P, corners = corners, sizes = sizes, ccw = bool(n, "ccw", true), + N = points(n, "normal", "vector"), nFace = not bool(n, "normalPerVertex", true), C = C, cComps = cc, + cFace = not bool(n, "colorPerVertex", true), T = if tc then nums(tc, "point") or {} else T, + } + return polyMesh(m, o, maxV) +end + +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] } +end +local function sub3(a: { number }, b: { number }): { number } + return { a[1] - b[1], a[2] - b[2], a[3] - b[3] } +end +local function norm(a: { number }): ({ number }, number) + local l = sqrt(a[1] * a[1] + a[2] * a[2] + a[3] * a[3]) + return if l > 1e-12 then { a[1] / l, a[2] / l, a[3] / l } else { 0, 0, 0 }, l +end +-- rotate v about the unit axis k by angle a (Rodrigues) +local function rotate(v: { number }, k: { number }, a: number): { number } + local c, s = cos(a), sin(a) + local d = (k[1] * v[1] + k[2] * v[2] + k[3] * v[3]) * (1 - c) + local kv = cross(k, v) + return { v[1] * c + kv[1] * s + k[1] * d, v[2] * c + kv[2] * s + k[2] * d, v[3] * c + kv[3] * s + k[3] * d } +end + +local function extrusion(n: any, o: Options, maxV: number): (Types.Primitive?, string?) + local sp = nums(n, "spine") or { 0, 0, 0, 0, 1, 0 } + local cs = nums(n, "crossSection") or { 1, 1, 1, -1, -1, -1, -1, 1, 1, 1 } + local sc = nums(n, "scale") or { 1, 1 } + local ori = nums(n, "orientation") or { 0, 0, 1, 0 } + local ns, nc = #sp // 3, #cs // 2 + if ns < 2 or nc < 2 then + return nil, nil + end + if ns * nc > maxV then + return nil, "limit: extrusion of " .. ns .. " x " .. nc + end + local spine = {} + for i = 1, ns do + spine[i] = { sp[i * 3 - 2], sp[i * 3 - 1], sp[i * 3] } + end + local function same(a: { number }, b: { number }): boolean + return math.abs(a[1] - b[1]) < 1e-9 and math.abs(a[2] - b[2]) < 1e-9 and math.abs(a[3] - b[3]) < 1e-9 + end + local closedSpine = same(spine[1], spine[ns]) + local closedCs = math.abs(cs[1] - cs[nc * 2 - 1]) < 1e-9 and math.abs(cs[2] - cs[nc * 2]) < 1e-9 + -- spine-aligned cross-section planes: Y along the spine, Z from the bend, X = Y x Z + local Ys: { { number } }, Zs: { [number]: { number } } = {}, {} + for i = 1, ns do + local prev = if i > 1 then spine[i - 1] elseif closedSpine then spine[ns - 1] else nil + local nxt = if i < ns then spine[i + 1] elseif closedSpine then spine[2] else nil + local y = sub3(nxt or spine[i], prev or spine[i]) + Ys[i] = norm(y) + if prev and nxt then + local z, l = norm(cross(sub3(nxt, spine[i]), sub3(prev, spine[i]))) + Zs[i] = if l > 1e-12 then z else nil + end + end + -- missing Z: copy a neighbour's; a straight spine rotates (0, 0, 1) like (0, 1, 0) onto the spine direction + local firstZ = nil + for i = 1, ns do + if Zs[i] then + firstZ = Zs[i] + break + end + end + for i = 1, ns do + if not Ys[i] or (Ys[i][1] == 0 and Ys[i][2] == 0 and Ys[i][3] == 0) then + Ys[i] = Ys[i - 1] or { 0, 1, 0 } + end + end + for i = 1, ns do + if not Zs[i] then + if firstZ then + Zs[i] = Zs[i - 1] or firstZ + else + local y = Ys[i] + local axis, l = norm(cross({ 0, 1, 0 }, y)) + local ang = math.acos(math.clamp(y[2], -1, 1)) + Zs[i] = if l > 1e-12 then rotate({ 0, 0, 1 }, axis, ang) elseif y[2] < 0 then { 0, 0, -1 } else { 0, 0, 1 } + end + end + if i > 1 and Zs[i][1] * Zs[i - 1][1] + Zs[i][2] * Zs[i - 1][2] + Zs[i][3] * Zs[i - 1][3] < 0 then + Zs[i] = { -Zs[i][1], -Zs[i][2], -Zs[i][3] } + end + end + local nr = if closedSpine then ns - 1 else ns + local nring = if closedCs then nc - 1 else nc + local P = {} + for i = 1, nr do + local y, z = Ys[i], Zs[i] + local x = cross(y, z) + local si = if #sc >= i * 2 then i else 1 + local sx, sz = sc[si * 2 - 1] or 1, sc[si * 2] or 1 + local oi = if #ori >= i * 4 then i else 1 + local ax, ang = norm({ ori[oi * 4 - 3] or 0, ori[oi * 4 - 2] or 0, ori[oi * 4 - 1] or 1 }), ori[oi * 4] or 0 + for j = 1, nring do + local v = { cs[j * 2 - 1] * sx, 0, cs[j * 2] * sz } + if ang ~= 0 then + v = rotate(v, ax, ang) + end + local s = spine[i] + table.insert(P, s[1] + x[1] * v[1] + y[1] * v[2] + z[1] * v[3]) + table.insert(P, s[2] + x[2] * v[1] + y[2] * v[2] + z[2] * v[3]) + table.insert(P, s[3] + x[3] * v[1] + y[3] * v[2] + z[3] * v[3]) + end + end + local corners, sizes = {}, {} + local function at(i: number, j: number): number + return ((i - 1) % nr) * nring + (j - 1) % nring + end + for i = 1, ns - 1 do + for j = 1, nc - 1 do + for _, c in { at(i, j), at(i + 1, j), at(i + 1, j + 1), at(i, j + 1) } do + table.insert(corners, c) + end + table.insert(sizes, 4) + end + end + if not closedSpine then + if bool(n, "beginCap", true) then + for j = 1, nring do + table.insert(corners, at(1, j)) + end + table.insert(sizes, nring) + end + if bool(n, "endCap", true) then + for j = nring, 1, -1 do + table.insert(corners, at(ns, j)) + end + table.insert(sizes, nring) + end + end + return polyMesh({ P = P, corners = corners, sizes = sizes, ccw = bool(n, "ccw", true) }, o, maxV) +end + +local function lines(n: any, maxV: number): (any, string?) + local P = points(n, "coord", "point") or {} + local np = #P // 3 + local C, cc = colors(n) + local perVertex = bool(n, "colorPerVertex", true) + local runs: { { number } } = {} + if n.type == "LineSet" then + local at = 0 + for _, c in nums(n, "vertexCount") or {} do + local r = {} + for q = 0, c - 1 do + r[q + 1] = at + q + end + at += c + table.insert(runs, r) + end + else + local corners, sizes = split(nums(n, "coordIndex") or {}) + local k = 0 + for _, s in sizes do + local r = {} + for q = 1, s do + r[q] = corners[k + q] + end + k += s + table.insert(runs, r) + end + end + local cIdx = nums(n, "colorIndex") or {} + local cList = if perVertex then cornerList(cIdx) else nil + local vkey: { [string]: number } = {} + local src: { { number } } = {} + local out: { number } = {} + local k = 0 + for li, r in runs do + local prev: number? = nil + for _, c in r do + k += 1 + if c == nil or c < 0 or c >= np then + prev = nil + continue + end + local ci = if not C then -1 elseif perVertex then (if cList then cList[k] or c else c) else (cIdx[li] or li - 1) + local key = c .. ":" .. ci + local v = vkey[key] + if not v then + v = #src + src[v + 1] = { c, ci } + vkey[key] = v + end + if prev then + table.insert(out, prev) + table.insert(out, v) + end + prev = v + end + end + if #src > maxV then + return nil, "limit: more than " .. maxV .. " vertices" + end + local pos = S.accessor(nil, "f32", 3, #src) + local col = if C then S.accessor(nil, "f32", cc, #src) else nil + for v, s in src do + for q = 0, 2 do + buffer.writef32(pos.data, ((v - 1) * 3 + q) * 4, P[s[1] * 3 + q + 1]) + end + if col and C then + for q = 0, cc - 1 do + buffer.writef32(col.data, ((v - 1) * cc + q) * 4, C[s[2] * cc + q + 1] or 1) + end + end + end + return { attributes = { POSITION = pos, COLOR_0 = col } :: any, indices = u32(out), mode = "lines" } +end + +local function pointSet(n: any, maxV: number): (any, string?) + local P = points(n, "coord", "point") or {} + local np = #P // 3 + if np > maxV then + return nil, "limit: more than " .. maxV .. " points" + end + local C, cc = colors(n) + local attrs: { [string]: Types.Accessor } = { POSITION = f32(P, 3, np) } + if C then + local col = S.accessor(nil, "f32", cc, np) + for i = 0, np * cc - 1 do + buffer.writef32(col.data, i * 4, C[i + 1] or 1) + end + attrs.COLOR_0 = col + end + return { attributes = attrs, mode = "points" } +end + +local function direct(P: { number }, N: { number }, T: { number }, I: { number }, o: Options): Types.Primitive + local nv = #P // 3 + if o.flipV ~= false then + for i = 2, #T, 2 do + T[i] = 1 - T[i] + end + end + return { + attributes = { POSITION = f32(P, 3, nv), NORMAL = f32(N, 3, nv), TEXCOORD_0 = f32(T, 2, nv) }, + indices = u32(I), + mode = "triangles", + } +end + +local function box(n: any, o: Options): Types.Primitive + local s = vec(n, "size", { 2, 2, 2 }) + local hx, hy, hz = s[1] / 2, s[2] / 2, s[3] / 2 + local P, N, T, I = {}, {}, {}, {} + -- faces: normal, u axis, v axis (the specification's texture orientation) + local FACES = { + { { 0, 0, 1 }, { 1, 0, 0 }, { 0, 1, 0 } }, { { 0, 0, -1 }, { -1, 0, 0 }, { 0, 1, 0 } }, + { { 1, 0, 0 }, { 0, 0, -1 }, { 0, 1, 0 } }, { { -1, 0, 0 }, { 0, 0, 1 }, { 0, 1, 0 } }, + { { 0, 1, 0 }, { 1, 0, 0 }, { 0, 0, -1 } }, { { 0, -1, 0 }, { 1, 0, 0 }, { 0, 0, 1 } }, + } + for f, face in FACES do + local nn, u, v = face[1], face[2], face[3] + for _, c in { { -1, -1 }, { 1, -1 }, { 1, 1 }, { -1, 1 } } do + for q = 1, 3 do + local h = if q == 1 then hx elseif q == 2 then hy else hz + table.insert(P, (nn[q] + u[q] * c[1] + v[q] * c[2]) * h) + table.insert(N, nn[q]) + end + table.insert(T, (c[1] + 1) / 2) + table.insert(T, (c[2] + 1) / 2) + end + local b = (f - 1) * 4 + for _, x in { 0, 1, 2, 0, 2, 3 } do + table.insert(I, b + x) + end + end + return direct(P, N, T, I, o) +end + +-- a ring of segs + 1 vertices (seam doubled); s starts at the back (-z) and runs counter-clockwise seen from +y +local function ring(P: { number }, N: { number }?, T: { number }?, segs: number, y: number, r: number, t: number, ny: number?, nr: number?) + for i = 0, segs do + local a = 2 * pi * i / segs + local x, z = -sin(a), -cos(a) + table.insert(P, x * r) + table.insert(P, y) + table.insert(P, z * r) + if N then + table.insert(N, x * (nr or 1)) + table.insert(N, ny or 0) + table.insert(N, z * (nr or 1)) + end + if T then + table.insert(T, i / segs) + table.insert(T, t) + end + end +end + +local function cap(P: { number }, N: { number }, T: { number }, I: { number }, segs: number, y: number, r: number, ny: number) + local b = #P // 3 + for i = 0, segs - 1 do + local a = 2 * pi * i / segs + local x, z = -sin(a), -cos(a) + table.insert(P, x * r) + table.insert(P, y) + table.insert(P, z * r) + table.insert(N, 0) + table.insert(N, ny) + table.insert(N, 0) + -- the specification maps the cap like a top view: s = x, t = -z (top) or z (bottom) + table.insert(T, x / 2 + 0.5) + table.insert(T, (if ny > 0 then -z else z) / 2 + 0.5) + end + for i = 1, segs - 2 do + -- the ring runs counter-clockwise seen from +y: in order for the top, reversed for the bottom + if ny > 0 then + table.insert(I, b) + table.insert(I, b + i) + table.insert(I, b + i + 1) + else + table.insert(I, b) + table.insert(I, b + i + 1) + table.insert(I, b + i) + end + end +end + +local function band(I: { number }, a: number, b: number, segs: number) + for i = 0, segs - 1 do + table.insert(I, a + i) + table.insert(I, a + i + 1) + table.insert(I, b + i + 1) + table.insert(I, a + i) + table.insert(I, b + i + 1) + table.insert(I, b + i) + end +end + +local function sphere(n: any, o: Options, segs: number): Types.Primitive + local r = num(n, "radius", 1) + local rings = math.max(2, segs // 2) + local P, N, T, I = {}, {}, {}, {} + for j = 0, rings do + local phi = pi * j / rings -- from the bottom + local y, rr = -cos(phi), sin(phi) + ring(P, N, T, segs, y * r, rr * r, j / rings, y, rr) + end + for j = 0, rings - 1 do + band(I, j * (segs + 1), (j + 1) * (segs + 1), segs) + end + return direct(P, N, T, I, o) +end + +local function cylinder(n: any, o: Options, segs: number, cone: boolean): Types.Primitive + local r = num(n, if cone then "bottomRadius" else "radius", 1) + local h = num(n, "height", 2) + local P, N, T, I = {}, {}, {}, {} + if bool(n, "side", true) then + -- side normals: a cone's lean outwards by its slope + local l = sqrt(r * r + h * h) + local ny, nr = if cone and l > 0 then r / l else 0, if cone and l > 0 then h / l else 1 + ring(P, N, T, segs, -h / 2, r, 0, ny, nr) + ring(P, N, T, segs, h / 2, if cone then 0 else r, 1, ny, nr) + band(I, 0, segs + 1, segs) + end + if not cone and bool(n, "top", true) then + cap(P, N, T, I, segs, h / 2, r, 1) + end + if bool(n, "bottom", true) then + cap(P, N, T, I, segs, -h / 2, r, -1) + end + return direct(P, N, T, I, o) +end + +function Geometry.primitive(n: any, o: Options): (Types.Primitive?, any) + local t = n.type + local maxV = o.maxVertices or 2 ^ 24 + local segs = math.clamp(math.floor(o.segments or 32), 3, 1024) + local solid = bool(n, "solid", true) + local prim: Types.Primitive?, err: string? = nil, nil + if t == "IndexedFaceSet" then + prim, err = faceSet(n, o, maxV) + elseif t == "IndexedTriangleSet" or t == "TriangleSet" or t == "IndexedTriangleFanSet" or t == "TriangleFanSet" or t == "IndexedTriangleStripSet" or t == "TriangleStripSet" or t == "IndexedQuadSet" or t == "QuadSet" then + prim, err = triSet(n, o, maxV) + elseif t == "ElevationGrid" then + prim, err = elevationGrid(n, o, maxV) + elseif t == "Extrusion" then + prim, err = extrusion(n, o, maxV) + elseif t == "IndexedLineSet" or t == "LineSet" then + prim, err = lines(n, maxV) + solid = false + elseif t == "PointSet" then + prim, err = pointSet(n, maxV) + solid = false + elseif t == "Box" then + prim = box(n, o) + elseif t == "Sphere" then + prim = sphere(n, o, segs) + elseif t == "Cylinder" then + prim = cylinder(n, o, segs, false) + elseif t == "Cone" then + prim = cylinder(n, o, segs, true) + else + return nil, nil + end + if not prim then + return nil, err + end + return prim, solid +end + +return Geometry +end +__FILES["codecs/model/Vrml/Parse"] = function() + +-- codecs/model/Vrml/Parse: the VRML97 (ISO/IEC 14772-1) / X3D classic (ISO/IEC 19776-2) encoding parser. +-- Written from the specifications; no third-party code. +local Parse = {} + +type Node = { type: string, def: string?, fields: { [string]: any } } +type Route = { from: Node, fromField: string, to: Node, toField: string } +type Proto = { name: string, fields: { [string]: any }, body: { Node }, routes: { Route }, extern: boolean? } +type Graph = { + roots: { Node }, + routes: { Route }, + header: { [string]: any }, + meta: { [string]: string }, + components: { string }, + units: { [string]: { name: string, factor: number } }, + protos: { [string]: Proto }, +} +type IsRef = { is: string } + +local find, sub, byte, match, gmatch = string.find, string.sub, string.byte, string.match, string.gmatch + +local ID1 = "^[^%c%s%d\"#',%+%-%.%[\\%]{}][^%c%s\"#',%.%[\\%]{}]*" +local MAX_DEPTH = 200 +local DECL = { field = true, exposedField = true, eventIn = true, eventOut = true, initializeOnly = true, inputOutput = true, inputOnly = true, outputOnly = true } +local HAS_VALUE = { field = true, exposedField = true, initializeOnly = true, inputOutput = true } + +local function copy(node: Node, values: { [string]: any }, defaults: { [string]: any }, memo: { [any]: any }): Node + local done = memo[node] + if done then + return done + end + local out: Node = { type = node.type, def = node.def, fields = {} } + memo[node] = out + for k, v in node.fields do + if type(v) == "table" and type((v :: any).is) == "string" then + local name = (v :: any).is + local val = values[name] + if val == nil then + val = defaults[name] + end + out.fields[k] = val + elseif type(v) == "table" then + local arr = table.create(#v) + for i, x in v do + arr[i] = if type(x) == "table" and x.type then copy(x, values, defaults, memo) else x + end + out.fields[k] = arr + else + out.fields[k] = v + end + end + return out +end + +function Parse.expand(proto: Proto, values: { [string]: any }, def: string?, routes: { Route }?): Node? + if proto.extern or #proto.body == 0 then + return nil + end + local memo = {} + local first: Node? = nil + for _, n in proto.body do + local c = copy(n, values, proto.fields, memo) + first = first or c + end + if routes then + for _, r in proto.routes do + local from, to = memo[r.from], memo[r.to] + if from and to then + table.insert(routes, { from = from, fromField = r.fromField, to = to, toField = r.toField }) + end + end + end + local f = first :: Node + if def then + -- the instance gets its own copy of the node so its DEF name is its own + local out: Node = { type = f.type, def = def, fields = f.fields } + return out + end + return f +end + +function Parse.parse(text: string): (Graph?, string?) + local n = #text + local p = 1 + local graph: Graph = { roots = {}, routes = {}, header = {}, meta = {}, components = {}, units = {}, protos = {} } + local defs: { [string]: Node } = {} + local protos: { [string]: Proto } = graph.protos + local routes: { Route } = graph.routes + local failure: string? = nil + local depth = 0 + + local function line(at: number): number + local l = 1 + for _ in gmatch(sub(text, 1, at), "\n") do + l += 1 + end + return l + end + local function fail(msg: string) + if not failure then + failure = "line " .. line(p) .. ": " .. msg + end + end + + -- header line: #VRML V2.0 utf8 / #X3D V3.3 utf8 + local v, enc = match(text, "^#VRML V(%S+) (%S+)") + if v then + graph.header.version, graph.header.encoding = v, enc + if v ~= "2.0" then + return nil, "unsupported: VRML " .. v .. " (only VRML97 / X3D)" + end + else + v, enc = match(text, "^#X3D V(%S+) (%S+)") + if v then + graph.header.version, graph.header.encoding, graph.header.x3d = v, enc, true + end + end + + local function skip() + while true do + local q = find(text, "[^%s,]", p) + if not q then + p = n + 1 + return + end + p = q + if byte(text, p) == 35 then -- '#' + local e = find(text, "[\r\n]", p) + p = if e then e else n + 1 + else + return + end + end + end + local function token(): (string, any) + skip() + if p > n then + return "eof", nil + end + local c = byte(text, p) + if c == 123 or c == 125 or c == 91 or c == 93 then -- { } [ ] + p += 1 + return string.char(c), nil + elseif c == 34 then -- a string: \" and \\ escapes + local q = p + 1 + local parts = {} + while true do + local e = find(text, '["\\]', q) + if not e then + fail("unterminated string") + p = n + 1 + return "eof", nil + end + table.insert(parts, sub(text, q, e - 1)) + if byte(text, e) == 92 then + table.insert(parts, sub(text, e + 1, e + 1)) + q = e + 2 + else + p = e + 1 + return "str", table.concat(parts) + end + end + end + if (c >= 48 and c <= 57) or c == 43 or c == 45 or c == 46 then + local s, e = find(text, "^[+-]?0[xX]%x+", p) + if not s then + s, e = find(text, "^[+-]?%d*%.?%d*[eE][+-]?%d+", p) + end + if not s then + s, e = find(text, "^[+-]?%d*%.?%d*", p) + end + local num = tonumber(sub(text, p, e)) + if num then + p = (e :: number) + 1 + return "num", num + end + if c == 46 then + p += 1 + return ".", nil + end + local _, we = find(text, "^[^%s,%[%]{}#\"]+", p) + local w = sub(text, p, we) + p = (we :: number) + 1 + local wl = string.lower(w) + local val = if find(wl, "inf", 1, true) then (if c == 45 then -math.huge else math.huge) elseif find(wl, "nan", 1, true) then 0 else nil + if val == nil then + fail("bad number " .. w) + return "eof", nil + end + return "num", val + end + local s, e = find(text, ID1, p) + if s then + p = (e :: number) + 1 + return "id", sub(text, s, e) + end + fail("unexpected character " .. sub(text, p, p)) + p = n + 1 + return "eof", nil + end + local function peek(): (string, any) + local save = p + local k, val = token() + p = save + return k, val + end + + local parseNode: (first: string) -> (Node?, boolean) + local parseProto: (extern: boolean) -> () + local parseRoute: () -> () + + local function value(): any + local k, val = token() + if k == "[" then + local out = {} + local close = find(text, "]", p, true) + if close then + local seg = sub(text, p, close - 1) + if not find(seg, "[{}\"#]") then + local ok = true + for w in gmatch(seg, "[^%s,]+") do + local x = tonumber(w) + if x then + table.insert(out, x) + elseif w == "TRUE" or w == "FALSE" then + table.insert(out, w == "TRUE") + else + ok = false + break + end + end + if ok then + p = close + 1 + return out + end + table.clear(out) + end + end + while not failure do + k, val = token() + if k == "]" then + return out + elseif k == "num" or k == "str" then + table.insert(out, val) + elseif k == "id" and (val == "TRUE" or val == "FALSE") then + table.insert(out, val == "TRUE") + elseif k == "id" and val == "NULL" then + continue + elseif k == "id" then + local node = parseNode(val) + if node then + table.insert(out, node) + end + else + fail("unexpected " .. k .. " in a [ ] value") + return out + end + end + return out + elseif k == "num" then + local out = { val } + while true do + local save = p + local k2, v2 = token() + if k2 ~= "num" then + p = save + break + end + table.insert(out, v2) + end + return out + elseif k == "str" then + return { val } + elseif k == "id" then + if val == "TRUE" or val == "FALSE" then + return { val == "TRUE" } + elseif val == "NULL" then + return {} + end + local node = parseNode(val) + return if node then { node } else {} + end + fail("missing field value") + return {} + end + + local function body(node: Node) + while not failure do + local k, name = token() + if k == "}" then + return + elseif k ~= "id" then + fail("expected a field name in " .. node.type .. ", got " .. k) + return + end + if name == "ROUTE" then + parseRoute() + elseif name == "PROTO" or name == "EXTERNPROTO" then + parseProto(name == "EXTERNPROTO") + elseif DECL[name] then + -- Script / shader interface: <access> <type> <name> [<value> | IS <name>] + local _, _t = token() + local fk, fname = token() + if fk ~= "id" then + fail("bad interface declaration in " .. node.type) + return + end + local pk, pv = peek() + if pk == "id" and pv == "IS" then + token() + local _, ref = token() + node.fields[fname] = { is = ref } + elseif HAS_VALUE[name] then + node.fields[fname] = value() + end + else + local pk, pv = peek() + if pk == "id" and pv == "IS" then + token() + local _, ref = token() + node.fields[name] = { is = ref } + else + node.fields[name] = value() + end + end + end + end + + -- a node statement starting with the id `first` (DEF name Type { }, USE name, Type { }) + function parseNode(first: string): (Node?, boolean) + if first == "USE" then + local k, name = token() + if k ~= "id" then + fail("USE without a name") + return nil, false + end + local node = defs[name] + if not node then + fail("USE of an undefined name " .. tostring(name)) + end + return node, true + end + local def: string? = nil + local typ = first + if first == "DEF" then + local k, name = token() + local k2, t2 = token() + if k ~= "id" or k2 ~= "id" then + fail("bad DEF") + return nil, false + end + def, typ = name, t2 + end + local k = token() + if k ~= "{" then + fail("expected { after " .. typ) + return nil, false + end + depth += 1 + if depth > MAX_DEPTH then + fail("limit: nodes nested deeper than " .. MAX_DEPTH) + return nil, false + end + local node: Node = { type = typ, def = def, fields = {} } + body(node) + depth -= 1 + local proto = protos[typ] + if proto and not proto.extern then + local inst = Parse.expand(proto, node.fields, def, routes) + if inst then + node = inst + end + elseif proto then + (node :: any).extern = true + end + if def then + defs[def] = node + end + return node, false + end + + -- ROUTE from.field TO to.field + function parseRoute() + local function path(): (string?, string?) + local k1, a = token() + local k2 = token() + local k3, b = token() + if k1 ~= "id" or k2 ~= "." or k3 ~= "id" then + return nil, nil + end + return a, b + end + local a, af = path() + local k, to = token() + local b, bf = path() + if not (a and af and b and bf) or k ~= "id" or to ~= "TO" then + fail("bad ROUTE") + return + end + local from, dst = defs[a :: string], defs[b :: string] + if from and dst then + table.insert(routes, { from = from, fromField = af :: string, to = dst, toField = bf :: string }) + end + end + + -- PROTO name [ interface ] { body } / EXTERNPROTO name [ interface ] url + function parseProto(extern: boolean) + local k, name = token() + if k ~= "id" or token() ~= "[" then + fail("bad PROTO") + return + end + local proto: Proto = { name = name, fields = {}, body = {}, routes = {}, extern = extern or nil } + while not failure do + local k2, access = token() + if k2 == "]" then + break + elseif k2 ~= "id" or not DECL[access] then + fail("bad PROTO interface") + return + end + local _, _t = token() + local fk, fname = token() + if fk ~= "id" then + fail("bad PROTO interface") + return + end + if HAS_VALUE[access] and not extern then + proto.fields[fname] = value() + end + end + if extern then + value() + protos[name] = proto + return + end + if token() ~= "{" then + fail("PROTO " .. tostring(name) .. " without a body") + return + end + -- the body has its own DEF names and its own routes + local outerDefs, outerRoutes = defs, routes + defs, routes = {}, proto.routes + while not failure do + local k3, w = token() + if k3 == "}" then + break + elseif k3 ~= "id" then + fail("bad PROTO body") + break + elseif w == "ROUTE" then + parseRoute() + elseif w == "PROTO" or w == "EXTERNPROTO" then + parseProto(w == "EXTERNPROTO") + else + local node = parseNode(w) + if node then + table.insert(proto.body, node) + end + end + end + defs, routes = outerDefs, outerRoutes + protos[name] = proto + end + + while not failure do + local k, w = token() + if k == "eof" then + break + elseif k ~= "id" then + fail("unexpected " .. k) + break + end + if w == "ROUTE" then + parseRoute() + elseif w == "PROTO" or w == "EXTERNPROTO" then + parseProto(w == "EXTERNPROTO") + elseif w == "PROFILE" then + local _, prof = token() + graph.header.profile = prof + elseif w == "COMPONENT" then + local _, comp = token() -- name:level is one id + table.insert(graph.components, tostring(comp)) + elseif w == "META" then + local _, key = token() + local _, val = token() + graph.meta[tostring(key)] = tostring(val) + elseif w == "UNIT" then + local _, cat = token() + local _, uname = token() + local _, factor = token() + if type(cat) == "string" and type(factor) == "number" then + graph.units[cat] = { name = tostring(uname), factor = factor } + end + elseif w == "IMPORT" or w == "EXPORT" then + -- IMPORT inline.name AS name / EXPORT name AS name: no effect on the scene + local _, _a = token() + if peek() == "." then + token() + token() + end + local pk, pv = peek() + if pk == "id" and pv == "AS" then + token() + token() + end + else + local node = parseNode(w) + if node then + table.insert(graph.roots, node) + end + end + end + if failure then + return nil, failure + end + return graph, nil +end + +return Parse +end +__FILES["codecs/model/Vrml/Write"] = function() + +-- codecs/model/Vrml/Write: a Scene to VRML97 (`#VRML V2.0 utf8`), X3D classic (`#X3D V3.3 utf8`) or X3D XML. New code. +local Types = __include("Types") +local Mat4 = __include("codecs/model/Mat4") +local Flatten = __include("codecs/model/MeshFlatten") +local Xml = __include("codecs/text/Xml") + +local Write = {} + +type Options = { encoding: ("vrml97" | "x3dv" | "xml")?, files: { [string]: any }?, name: string?, flipV: boolean? } + +type WNode = { type: string, def: string?, use: string?, fields: { { any } } } + +local format, concat = string.format, table.concat + +local function fmt(v: number): string + if v ~= v then + return "0" + elseif v == math.huge then + return "1e38" + elseif v == -math.huge then + return "-1e38" + elseif v == math.floor(v) and math.abs(v) < 2 ^ 53 then + return format("%d", v) + end + return format("%.9g", v) +end + +local function W(t: string, def: string?): WNode + return { type = t, def = def, fields = {} } +end +local function F(n: WNode, name: string, kind: string, value: any, per: number?) + table.insert(n.fields, { name, kind, value, per }) +end + +local function namer(): (string?, string) -> string + local used: { [string]: boolean } = {} + return function(name: string?, fallback: string): string + local s = string.gsub(name or "", "[^%w_]", "_") + if s == "" or string.find(s, "^%d") then + s = fallback .. (if s ~= "" then "_" .. s else "") + end + local base, k = s, 1 + while used[s] do + k += 1 + s = base .. "_" .. k + end + used[s] = true + return s + end +end + +local function axisAngle(q: { number }): { number } + local x, y, z, w = q[1], q[2], q[3], q[4] + 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 + local s = math.sqrt(math.max(0, 1 - w * w)) + if s < 1e-9 then + return { 0, 0, 1, 0 } + end + return { x / s, y / s, z / s, 2 * math.acos(math.clamp(w, -1, 1)) } +end + +local function values(acc: any): { number }? + return (Flatten.numbers(acc)) +end + +local function faceSet(prim: any, doubleSided: boolean, o: Options, x3d: boolean): (WNode?, string?) + local tmp = { kind = "scene", nodes = {}, roots = {}, meshes = { { primitives = { prim } } } } + local keep = function(n: string): boolean + return n == "NORMAL" or n == "TEXCOORD_0" or n == "COLOR_0" + end + local m, err = Flatten.merge(tmp, keep, { triangulate = false }) + if not m then + return nil, err + end + if not m.sizes or #m.sizes == 0 then + return nil, nil + end + local g = W("IndexedFaceSet") + local coord = W("Coordinate") + F(coord, "point", "mf", m.attrs.POSITION.values, 3) + F(g, "coord", "node", coord) + local idx = {} + local p = 0 + for _, s in m.sizes do + for k = 1, s do + table.insert(idx, m.corners[p + k]) + end + table.insert(idx, -1) + p += s + end + F(g, "coordIndex", "mf", idx, 0) + local nrm = m.attrs.NORMAL + if nrm then + local nn = W("Normal") + F(nn, "vector", "mf", nrm.values, 3) + F(g, "normal", "node", nn) + end + local tc = m.attrs.TEXCOORD_0 + if tc then + local t = W("TextureCoordinate") + local vals, c = {}, tc.components + for i = 0, m.count - 1 do + local s, tt = tc.values[i * c + 1], tc.values[i * c + 2] + table.insert(vals, s) + table.insert(vals, if o.flipV ~= false then 1 - tt else tt) + end + F(t, "point", "mf", vals, 2) + F(g, "texCoord", "node", t) + end + local col = m.attrs.COLOR_0 + if col then + local c = col.components + local rgba = c >= 4 and x3d + local cn = W(if rgba then "ColorRGBA" else "Color") + local vals = {} + local scale = if col.raw then (if col.type == "unorm8" then 255 elseif col.type == "unorm16" then 65535 else 1) else 1 + for i = 0, m.count - 1 do + for k = 1, if rgba then 4 else 3 do + table.insert(vals, (col.values[i * c + k] or 1) / scale) + end + end + F(cn, "color", "mf", vals, if rgba then 4 else 3) + F(g, "color", "node", cn) + end + F(g, "solid", "bool", not doubleSided) + return g, nil +end + +local function coordNode(prim: any): (WNode?, number) + local pos = values(prim.attributes.POSITION) + if not pos then + return nil, 0 + end + local nv, pc = prim.attributes.POSITION.count, prim.attributes.POSITION.components + local p3 = {} + for i = 0, nv - 1 do + for k = 1, 3 do + table.insert(p3, pos[i * pc + k] or 0) + end + end + local coord = W("Coordinate") + F(coord, "point", "mf", p3, 3) + return coord, nv +end +local function colorNode(prim: any, nv: number, x3d: boolean): WNode? + local acc = prim.attributes.COLOR_0 + local col = acc and values(acc) + if not col then + return nil + end + local c = acc.components + local rgba = c >= 4 and x3d + local vals = {} + for i = 0, nv - 1 do + for k = 1, if rgba then 4 else 3 do + table.insert(vals, col[i * c + k] or 1) + end + end + local cn = W(if rgba then "ColorRGBA" else "Color") + F(cn, "color", "mf", vals, if rgba then 4 else 3) + return cn +end + +local function lineSet(prim: any, x3d: boolean): (WNode?, string?) + local coord, nv = coordNode(prim) + if not coord then + return nil, "lines without POSITION" + end + local ind: { number } + if prim.indices then + ind = values(prim.indices) or {} + else + ind = {} + for i = 0, nv - 1 do + ind[i + 1] = i + end + end + local idx = {} + local mode = prim.mode + if mode == "lines" then + for i = 1, #ind - 1, 2 do + table.insert(idx, ind[i]) + table.insert(idx, ind[i + 1]) + table.insert(idx, -1) + end + else + for _, v in ind do + table.insert(idx, v) + end + if mode == "line_loop" and #ind > 0 then + table.insert(idx, ind[1]) + end + table.insert(idx, -1) + end + for _, v in idx do + if v >= nv then + return nil, "line index out of range" + end + end + local g = W("IndexedLineSet") + F(g, "coord", "node", coord) + local cn = colorNode(prim, nv, x3d) + if cn then + F(g, "color", "node", cn) + end + F(g, "coordIndex", "mf", idx, 0) + return g, nil +end + +local function pointSet(prim: any, x3d: boolean): (WNode?, string?) + local coord, nv = coordNode(prim) + if not coord then + return nil, "points without POSITION" + end + local g = W("PointSet") + F(g, "coord", "node", coord) + local cn = colorNode(prim, nv, x3d) + if cn then + F(g, "color", "node", cn) + end + return g, nil +end + +local EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/gif"] = "gif", ["image/bmp"] = "bmp", ["image/webp"] = "webp", ["image/ktx2"] = "ktx2" } + +local function textureUrl(scene: any, i: number, o: Options, written: { [number]: string }): string? + if written[i] then + return written[i] + end + local tex = scene.textures[i] + if not tex then + return nil + end + local url = tex.uri + if tex.data and type(o.files) == "table" then + local base = string.match(o.name or "model", "([^/\\]+)$") or "model" + base = string.gsub(base, "%.[^.]*$", "") + local ext = EXT[tex.mime or ""] or (url and string.match(url, "%.(%w+)$")) or "png" + local file = if url and not string.find(url, "^data:") and not string.find(url, "[/\\]") then url else format("%s_%d.%s", base, i, ext) + o.files[file] = tex.data + url = file + end + if url then + written[i] = url + end + return url +end + +local function appearance(scene: any, mi: number, o: Options, written: { [number]: string }): WNode + local m = scene.materials[mi] + local app = W("Appearance") + local mat = W("Material") + local x = m.extras and m.extras.vrml or {} + local c = m.baseColor or { 1, 1, 1, 1 } + F(mat, "diffuseColor", "sf", { c[1], c[2], c[3] }) + local e = m.emissive or { 0, 0, 0 } + if e[1] ~= 0 or e[2] ~= 0 or e[3] ~= 0 then + F(mat, "emissiveColor", "sf", { e[1], e[2], e[3] }) + end + if type(x.specularColor) == "table" then + F(mat, "specularColor", "sf", x.specularColor) + end + local sh = x.shininess + if type(sh) ~= "number" then + local r = math.max(m.roughness or 1, 1e-3) + sh = math.clamp((2 / (r * r) - 2) / 128, 0, 1) + end + F(mat, "shininess", "sf", { sh }) + if type(x.ambientIntensity) == "number" then + F(mat, "ambientIntensity", "sf", { x.ambientIntensity }) + end + if (c[4] or 1) < 1 then + F(mat, "transparency", "sf", { 1 - c[4] }) + end + F(app, "material", "node", mat) + local ref = m.baseColorTexture + if ref and type(ref.texture) == "number" then + local url = textureUrl(scene, ref.texture, o, written) + local img = scene.textures[ref.texture] and scene.textures[ref.texture].image + if url or (img and img.format == "rgba8" and img.width * img.height <= 2 ^ 20) then + local it + if url then + it = W("ImageTexture") + F(it, "url", "mstr", { url }) + else + -- a decoded image only: PixelTexture (SFImage: width height 4, then 0xRRGGBBAA from the bottom row up) + it = W("PixelTexture") + local w, h = img.width, img.height + local v = { w, h, 4 } + for row = h - 1, 0, -1 do + for x = 0, w - 1 do + table.insert(v, buffer.readu32(img.pixels, (row * w + x) * 4)) + end + end + -- the pixels are little-endian RGBA bytes: swap to 0xRRGGBBAA + for i = 4, #v do + local p = v[i] + v[i] = (p % 256) * 16777216 + (p // 256 % 256) * 65536 + (p // 65536 % 256) * 256 + p // 16777216 + end + F(it, "image", "sf", v) + end + local s = scene.textures[ref.texture].sampler + if s and s.wrapS == "clamp" then + F(it, "repeatS", "bool", false) + end + if s and s.wrapT == "clamp" then + F(it, "repeatT", "bool", false) + end + F(app, "texture", "node", it) + local tf = ref.transform + if tf then + local tt = W("TextureTransform") + if tf.offset then + F(tt, "translation", "sf", tf.offset) + end + if tf.scale then + F(tt, "scale", "sf", tf.scale) + end + if tf.rotation then + F(tt, "rotation", "sf", { tf.rotation }) + end + F(app, "textureTransform", "node", tt) + end + end + end + return app +end + +function Write.graph(scene: any, o: Options): ({ WNode }?, { { string } }?, string?) + local x3d = o.encoding == "x3dv" or o.encoding == "xml" + local name = namer() + local nodeDef: { [number]: string } = {} + local meshShapes: { [number]: { WNode } } = {} + local appDef: { [any]: string } = {} + local written: { [number]: string } = {} + local failure: string? = nil + + local function shapes(mi: number): { WNode } + local done = meshShapes[mi] + if done then + local out = {} + for _, s in done do + table.insert(out, { type = "Shape", use = s.def, fields = {} }) + end + return out + end + local mesh = scene.meshes[mi] + local out = {} + for pi, prim in (if mesh then mesh.primitives else {}) :: { any } do + local mode = prim.mode or "triangles" + local mat = if type(prim.material) == "number" then scene.materials[prim.material] else nil + local geo, err + if mode == "lines" or mode == "line_strip" or mode == "line_loop" then + geo, err = lineSet(prim, x3d) + elseif mode == "points" then + geo, err = pointSet(prim, x3d) + else + geo, err = faceSet(prim, mat ~= nil and mat.doubleSided == true, o, x3d) + end + if err then + failure = failure or err + end + if geo then + local sh = W("Shape", name((mesh.name or "mesh") .. (if #mesh.primitives > 1 then "_" .. pi else ""), "Shape")) + if mat then + local key = prim.material + if appDef[key] then + F(sh, "appearance", "node", { type = "Appearance", use = appDef[key], fields = {} }) + else + local app = appearance(scene, prim.material, o, written) + app.def = name(mat.name, "Material") + appDef[key] = app.def + F(sh, "appearance", "node", app) + end + end + F(sh, "geometry", "node", geo) + table.insert(out, sh) + end + end + meshShapes[mi] = out + return out + end + + local visiting: { [number]: boolean } = {} + local function transform(ni: number): WNode? + local n = scene.nodes[ni] + if type(n) ~= "table" or visiting[ni] then + return nil + end + visiting[ni] = true + local def = name(n.name, "Node") + nodeDef[ni] = def + local t = W("Transform", def) + local tr, rot, sc = n.translation, n.rotation, n.scale + if n.matrix then + tr, rot, sc = Mat4.decompose(n.matrix) + end + if tr and (tr[1] ~= 0 or tr[2] ~= 0 or tr[3] ~= 0) then + F(t, "translation", "sf", { tr[1], tr[2], tr[3] }) + end + if rot then + local aa = axisAngle(rot) + if aa[4] ~= 0 then + F(t, "rotation", "sf", aa) + end + end + if sc and (sc[1] ~= 1 or sc[2] ~= 1 or sc[3] ~= 1) then + F(t, "scale", "sf", { sc[1], sc[2], sc[3] }) + end + local kids: { WNode } = {} + if type(n.mesh) == "number" then + for _, s in shapes(n.mesh) do + table.insert(kids, s) + end + end + local cam = if type(n.camera) == "number" then scene.cameras[n.camera] else nil + if cam then + local v + if cam.type == "orthographic" and x3d then + v = W("OrthoViewpoint") + local xm, ym = cam.xmag or 1, cam.ymag or 1 + F(v, "fieldOfView", "sf", { -xm, -ym, xm, ym }) + else + v = W("Viewpoint") + F(v, "fieldOfView", "sf", { cam.yfov or 0.785398 }) + end + F(v, "position", "sf", { 0, 0, 0 }) + if cam.name then + F(v, "description", "str", cam.name) + end + table.insert(kids, v) + end + local l = if type(n.light) == "number" then scene.lights[n.light] else nil + if l then + local typ = if l.type == "directional" then "DirectionalLight" elseif l.type == "spot" then "SpotLight" else "PointLight" + local ln = W(typ) + local c = l.color or { 1, 1, 1 } + F(ln, "color", "sf", { c[1], c[2], c[3] }) + F(ln, "intensity", "sf", { math.clamp(l.intensity or 1, 0, 1) }) + if typ ~= "PointLight" then + F(ln, "direction", "sf", { 0, 0, -1 }) + end + if typ ~= "DirectionalLight" then + F(ln, "location", "sf", { 0, 0, 0 }) + F(ln, "radius", "sf", { l.range or 100 }) + end + if typ == "SpotLight" then + F(ln, "cutOffAngle", "sf", { l.outerCone or 0.785398 }) + F(ln, "beamWidth", "sf", { l.innerCone or 0 }) + end + table.insert(kids, ln) + end + for _, c in n.children or {} do + local ct = transform(c) + if ct then + table.insert(kids, ct) + end + end + if #kids > 0 then + F(t, "children", "nodes", kids) + end + visiting[ni] = nil + return t + end + + local roots: { WNode } = {} + local list = scene.roots + if type(list) ~= "table" or #list == 0 then + local child = {} + for _, n in scene.nodes do + for _, c in n.children or {} do + child[c] = true + end + end + list = {} + for i = 1, #scene.nodes do + if not child[i] then + table.insert(list, i) + end + end + end + for _, ri in list do + local t = transform(ri) + if t then + table.insert(roots, t) + end + end + if #scene.nodes == 0 then + for mi = 1, #scene.meshes do + for _, s in shapes(mi) do + table.insert(roots, s) + end + end + end + + local routes: { { string } } = {} + for ai, anim in scene.animations or {} do + local tmax = 0 + local chans = {} + for _, ch in anim.channels or {} do + local target = nodeDef[ch.node] + if target and (ch.path == "translation" or ch.path == "rotation" or ch.path == "scale") then + local input, output = values(ch.input), values(ch.output) + if input and output and #input > 0 then + tmax = math.max(tmax, input[#input]) + table.insert(chans, { ch, target, input, output }) + end + end + end + if #chans > 0 then + local cycle = if tmax > 0 then tmax else 1 + local ts = W("TimeSensor", name(anim.name, "Animation" .. ai)) + F(ts, "cycleInterval", "sf", { cycle }) + F(ts, "loop", "bool", true) + table.insert(roots, ts) + for k, c in chans do + local ch, target, input, output = c[1], c[2], c[3], c[4] + local rot = ch.path == "rotation" + local it = W(if rot then "OrientationInterpolator" else "PositionInterpolator", name(ts.def .. "_" .. k, "Interpolator")) + local keys = {} + for i, tv in input do + keys[i] = tv / cycle + end + local comps = if rot then 4 else 3 + local stride = #output // #input + -- CUBICSPLINE stores in-tangent, value, out-tangent per key + local off = if ch.interpolation == "CUBICSPLINE" and stride == comps * 3 then comps else 0 + local kv = {} + for i = 0, #input - 1 do + local v = {} + for q = 1, comps do + v[q] = output[i * stride + off + q] or 0 + end + if rot then + v = axisAngle(v) + end + for _, x in v do + table.insert(kv, x) + end + end + F(it, "key", "mf", keys, 0) + F(it, "keyValue", "mf", kv, comps) + table.insert(roots, it) + table.insert(routes, { ts.def :: string, "fraction_changed", it.def :: string, "set_fraction" }) + table.insert(routes, { it.def :: string, "value_changed", target, "set_" .. ch.path }) + end + end + end + if failure then + return nil, nil, failure + end + return roots, routes, nil +end + +local function numbers(vals: { number }, per: number?, indent: string): string + local out = table.create(#vals) + for i, v in vals do + out[i] = fmt(v) + end + if per == 0 then + local lines, cur = {}, {} + for i, v in vals do + table.insert(cur, out[i]) + if v == -1 then + table.insert(lines, concat(cur, " ")) + cur = {} + end + end + if #cur > 0 then + table.insert(lines, concat(cur, " ")) + end + return concat(lines, "\n" .. indent) + end + if per and per > 0 then + local lines = {} + for i = 1, #out, per do + table.insert(lines, concat(out, " ", i, math.min(i + per - 1, #out))) + end + return concat(lines, ",\n" .. indent) + end + return concat(out, " ") +end + +local function quote(s: string): string + return '"' .. string.gsub(s, '(["\\])', "\\%1") .. '"' +end + +local function classic(roots: { WNode }, routes: { { string } }, x3d: boolean): string + local out = {} + if x3d then + table.insert(out, "#X3D V3.3 utf8\nPROFILE Interchange\n# written by rosetta\n") + else + table.insert(out, "#VRML V2.0 utf8\n# written by rosetta\n") + end + local function emit(n: WNode, ind: string): string + if n.use then + return "USE " .. n.use + end + local parts = { (if n.def then "DEF " .. n.def .. " " else "") .. n.type .. " {" } + local ind2 = ind .. " " + for _, f in n.fields do + local fname, kind, v, per = f[1], f[2], f[3], f[4] + local s + if kind == "sf" then + s = numbers(v, nil, ind2) + elseif kind == "mf" then + s = "[\n" .. ind2 .. " " .. numbers(v, per, ind2 .. " ") .. "\n" .. ind2 .. "]" + elseif kind == "bool" then + s = if v then "TRUE" else "FALSE" + elseif kind == "str" then + s = quote(v) + elseif kind == "mstr" then + local q = {} + for i, x in v do + q[i] = quote(x) + end + s = "[ " .. concat(q, " ") .. " ]" + elseif kind == "node" then + s = emit(v, ind2) + else + local q = {} + for i, x in v do + q[i] = ind2 .. " " .. emit(x, ind2 .. " ") + end + s = "[\n" .. concat(q, "\n") .. "\n" .. ind2 .. "]" + end + table.insert(parts, ind2 .. fname .. " " .. s) + end + table.insert(parts, ind .. "}") + return concat(parts, "\n") + end + for _, r in roots do + table.insert(out, emit(r, "")) + end + for _, r in routes do + table.insert(out, format("ROUTE %s.%s TO %s.%s", r[1], r[2], r[3], r[4])) + end + return concat(out, "\n") .. "\n" +end + +local DEFAULT = { Appearance = "appearance", Material = "material", ImageTexture = "texture", TextureTransform = "textureTransform", Coordinate = "coord", Normal = "normal", Color = "color", ColorRGBA = "color", TextureCoordinate = "texCoord", IndexedFaceSet = "geometry", IndexedLineSet = "geometry", PointSet = "geometry" } + +local function xml(roots: { WNode }, routes: { { string } }): (string?, string?) + local function element(n: WNode, field: string): any + local attrs = Types.object() + local kids = {} + if (DEFAULT[n.type] or "children") ~= field then + Types.set(attrs, "containerField", field) + end + if n.use then + Types.set(attrs, "USE", n.use) + return Xml.element(n.type, attrs :: any) + end + if n.def then + Types.set(attrs, "DEF", n.def) + end + for _, f in n.fields do + local fname, kind, v, per = f[1], f[2], f[3], f[4] + if kind == "sf" then + Types.set(attrs, fname, numbers(v, nil, "")) + elseif kind == "mf" then + local s = numbers(v, per, "") + Types.set(attrs, fname, (string.gsub(s, "\n", " "))) + elseif kind == "bool" then + Types.set(attrs, fname, if v then "true" else "false") + elseif kind == "str" then + Types.set(attrs, fname, v) + elseif kind == "mstr" then + local q = {} + for i, x in v do + q[i] = quote(x) + end + Types.set(attrs, fname, concat(q, " ")) + elseif kind == "node" then + table.insert(kids, element(v, fname)) + else + for _, x in v do + table.insert(kids, element(x, fname)) + end + end + end + return Xml.element(n.type, attrs :: any, kids) + end + local sceneKids = {} + for _, r in roots do + table.insert(sceneKids, element(r, "children")) + end + for _, r in routes do + local a = Types.object() + Types.set(a, "fromNode", r[1]) + Types.set(a, "fromField", r[2]) + Types.set(a, "toNode", r[3]) + Types.set(a, "toField", r[4]) + table.insert(sceneKids, Xml.element("ROUTE", a :: any)) + end + local ra = Types.object() + Types.set(ra, "profile", "Interchange") + Types.set(ra, "version", "3.3") + local meta = Types.object() + Types.set(meta, "name", "generator") + Types.set(meta, "content", "rosetta") + local root = Xml.element("X3D", ra :: any, { Xml.element("head", nil, { Xml.element("meta", meta :: any) }), Xml.element("Scene", nil, sceneKids) }) + local s, err = Xml.encode(Xml.document(root, { version = "1.0", encoding = "UTF-8" }), { indent = 2 }) + if not s then + return nil, if err then err.message else "xml" + end + return s, nil +end + +function Write.text(scene: any, o: Options): (string?, string?) + local roots, routes, err = Write.graph(scene, o) + if not roots or not routes then + return nil, err + end + if o.encoding == "xml" then + return xml(roots, routes) + end + return classic(roots, routes, o.encoding == "x3dv"), nil +end + +return Write +end +__FILES["codecs/model/Vrml/Xml"] = function() + +-- codecs/model/Vrml/Xml: the X3D XML encoding (ISO/IEC 19776-1) to the Vrml/Parse node graph. New code. +local Xml = __include("codecs/text/Xml") +local Parse = __include("codecs/model/Vrml/Parse") + +local VXml = {} + +local GEOMETRY = { + "Box", "Sphere", "Cone", "Cylinder", "IndexedFaceSet", "IndexedLineSet", "LineSet", "PointSet", "ElevationGrid", + "Extrusion", "Text", "IndexedTriangleSet", "TriangleSet", "IndexedTriangleFanSet", "TriangleFanSet", + "IndexedTriangleStripSet", "TriangleStripSet", "IndexedQuadSet", "QuadSet", "Arc2D", "ArcClose2D", "Circle2D", + "Disk2D", "Polyline2D", "Polypoint2D", "Rectangle2D", "TriangleSet2D", "GeoElevationGrid", "NurbsPatchSurface", +} +local CONTAINER: { [string]: string } = { + Appearance = "appearance", Material = "material", PhysicalMaterial = "material", TwoSidedMaterial = "material", + UnlitMaterial = "material", ImageTexture = "texture", PixelTexture = "texture", MovieTexture = "texture", + MultiTexture = "texture", ImageCubeMapTexture = "texture", TextureTransform = "textureTransform", + Coordinate = "coord", CoordinateDouble = "coord", Normal = "normal", Color = "color", ColorRGBA = "color", + TextureCoordinate = "texCoord", MultiTextureCoordinate = "texCoord", TextureCoordinateGenerator = "texCoord", + FontStyle = "fontStyle", TextureProperties = "textureProperties", FillProperties = "fillProperties", + LineProperties = "lineProperties", +} +for _, g in GEOMETRY do + CONTAINER[g] = "geometry" +end + +local function container(el: Xml.Node, typ: string): string + local c = el.attrs.containerField + if type(c) == "string" and c ~= "" then + return c + end + if string.sub(typ, 1, 8) == "Metadata" then + return "metadata" + end + return CONTAINER[typ] or "children" +end + +function VXml.graph(doc: Xml.Node): (Parse.Graph?, string?) + local root = doc.root or doc + if type(root) ~= "table" or Xml.localName(root.name) ~= "X3D" then + return nil, "no <X3D> root element" + end + local graph: Parse.Graph = { roots = {}, routes = {}, header = { x3d = true, xml = true }, meta = {}, components = {}, units = {}, protos = {} } + graph.header.version, graph.header.profile = root.attrs.version, root.attrs.profile + local defs: { [string]: Parse.Node } = {} + local protos = graph.protos + local routes = graph.routes + local depth = 0 + local failure: string? = nil + + local convert: (el: Xml.Node) -> Parse.Node? + local function route(el: Xml.Node) + local a = el.attrs + local from, to = defs[a.fromNode or ""], defs[a.toNode or ""] + local ff, tf = a.fromField, a.toField + if from and to and type(ff) == "string" and type(tf) == "string" then + table.insert(routes, { from = from, fromField = ff, to = to, toField = tf }) + end + end + local declare: (el: Xml.Node, extern: boolean) -> () + + local function children(el: Xml.Node, node: Parse.Node) + for _, ch in el.children do + if type(ch) ~= "table" or string.sub(ch.name, 1, 1) == "#" then + continue + end + local name = Xml.localName(ch.name) + if name == "ROUTE" then + route(ch) + elseif name == "IS" then + for _, c in Xml.children(ch, "connect") do + local nf, pf = c.attrs.nodeField, c.attrs.protoField + if nf and pf then + node.fields[nf] = { is = pf } + end + end + elseif name == "ProtoDeclare" or name == "ExternProtoDeclare" then + declare(ch, name == "ExternProtoDeclare") + elseif name == "field" or name == "fieldValue" then + continue -- Script / shader interfaces + else + local c = convert(ch) + if c then + local f = container(ch, if name == "ProtoInstance" then "" else name) + local list = node.fields[f] + if type(list) ~= "table" or (list :: any).is then + list = {} + node.fields[f] = list + end + table.insert(list, c) + end + end + end + end + + local function fieldValue(el: Xml.Node): any + if el.attrs.value ~= nil then + return el.attrs.value + end + local list = {} + for _, ch in el.children do + if type(ch) == "table" and string.sub(ch.name, 1, 1) ~= "#" then + local c = convert(ch) + if c then + table.insert(list, c) + end + end + end + return list + end + + function declare(el: Xml.Node, extern: boolean) + local name = el.attrs.name + if not name then + return + end + local proto: Parse.Proto = { name = name, fields = {}, body = {}, routes = {}, extern = extern or nil } + local iface = if extern then el else Xml.child(el, "ProtoInterface") + if iface then + for _, f in Xml.children(iface, "field") do + if f.attrs.name then + proto.fields[f.attrs.name] = fieldValue(f) + end + end + end + local bodyEl = Xml.child(el, "ProtoBody") + if bodyEl and not extern then + local outerDefs, outerRoutes = defs, routes + defs, routes = {}, proto.routes + for _, ch in bodyEl.children do + if type(ch) == "table" and string.sub(ch.name, 1, 1) ~= "#" then + local nm = Xml.localName(ch.name) + if nm == "ROUTE" then + route(ch) + elseif nm == "ProtoDeclare" or nm == "ExternProtoDeclare" then + declare(ch, nm == "ExternProtoDeclare") + else + local c = convert(ch) + if c then + table.insert(proto.body, c) + end + end + end + end + defs, routes = outerDefs, outerRoutes + end + protos[name] = proto + end + + function convert(el: Xml.Node): Parse.Node? + local a = el.attrs + if a.USE then + return defs[a.USE] + end + depth += 1 + if depth > 200 then + failure = failure or "limit: nodes nested deeper than 200" + depth -= 1 + return nil + end + local typ = Xml.localName(el.name) + local node: any + if typ == "ProtoInstance" then + local proto = protos[a.name or ""] + local values = {} + for _, fv in Xml.children(el, "fieldValue") do + if fv.attrs.name then + values[fv.attrs.name] = fieldValue(fv) + end + end + local inst = proto and Parse.expand(proto, values, a.DEF, routes) + node = inst or { type = a.name or "ProtoInstance", def = a.DEF, fields = values } + else + node = { type = typ, def = a.DEF, fields = {} } + for k, v in a do + if k ~= "DEF" and k ~= "USE" and k ~= "containerField" and k ~= "class" and not string.find(k, ":", 1, true) then + node.fields[k] = v + end + end + children(el, node) + end + depth -= 1 + if a.DEF then + defs[a.DEF] = node + end + return node + end + + for _, ch in root.children do + if type(ch) ~= "table" then + continue + end + local name = Xml.localName(ch.name) + if name == "head" then + for _, h in ch.children do + if type(h) == "table" then + local hn = Xml.localName(h.name) + if hn == "meta" and h.attrs.name then + graph.meta[h.attrs.name] = h.attrs.content or "" + elseif hn == "component" and h.attrs.name then + table.insert(graph.components, h.attrs.name .. ":" .. (h.attrs.level or "1")) + elseif hn == "unit" and h.attrs.category then + graph.units[h.attrs.category] = { name = h.attrs.name or "", factor = tonumber(h.attrs.conversionFactor) or 1 } + end + end + end + elseif name == "Scene" then + local scene: Parse.Node = { type = "Scene", fields = {} } + children(ch, scene) + local list = scene.fields.children + if type(list) == "table" then + graph.roots = list + end + for f, v in scene.fields do + -- a top-level node with another containerField still shows + if f ~= "children" and type(v) == "table" then + for _, x in v do + table.insert(graph.roots, x) + end + end + end + end + end + if failure then + return nil, failure + end + return graph, nil +end + +return VXml +end +end + + + + + + codecs_text + --!optimize 2 +--!nocheck +-- rosetta chunk codecs_text (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 11 modules (3 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["codecs/text/Json"] = function() + +-- codecs/text/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code. +local Err = __include("core/Err") +local Types = __include("Types") +local Decode = __include("codecs/text/Json/Decode") +local Encode = __include("codecs/text/Json/Encode") + +local Json = {} + +type DecodeOptions = Decode.Options +type EncodeOptions = Encode.Options + +Json.null = Types.null +Json.object = Types.object +Json.keys = Types.keys +Json.set = Types.set + +local function text(src: any): (string?, Err.Err?) + if type(src) == "string" then + return src, nil + elseif type(src) == "buffer" then + return buffer.tostring(src), nil + end + return nil, Err.new(Err.ARG, "expected a string or a buffer, got " .. typeof(src)) +end + +local function fail(msg: any, at: any, n: number): Err.Err + local m = tostring(msg) + local code = if string.find(m, "truncated", 1, true) or string.find(m, "unterminated", 1, true) or (at or 0) >= n + then Err.TRUNCATED + elseif string.find(m, "nested deeper", 1, true) then Err.LIMIT + else Err.CORRUPT + return Err.new(code, m, at) +end + +function Json.decode(src: string | buffer, opts: DecodeOptions?): (any, Err.Err?) + local s, terr = text(src) + if not s then + return nil, terr + end + local i = if string.sub(s, 1, 3) == "\239\187\191" then 4 else 1 + local v, ni, at = Decode.value(s, i, opts) + if v == nil then + return nil, fail(ni, at, #s) + end + local e = string.match(s, "^[ \t\n\r]*()", ni) :: any + if e <= #s then + return nil, Err.new(Err.CORRUPT, "trailing data after the value", e - 1) + end + return v, nil +end + +function Json.decodeAt(src: string | buffer, pos: number?, opts: DecodeOptions?): (any, any) + local s, terr = text(src) + if not s then + return nil, terr + end + local i = string.match(s, "^[ \t\n\r]*()", pos or 1) :: any + if i > #s then + return nil, nil + end + local v, ni, at = Decode.value(s, i, opts) + if v == nil then + return nil, fail(ni, at, #s) + end + return v, ni +end + +function Json.lines(src: string | buffer, opts: DecodeOptions?): () -> (number?, any, Err.Err?) + local s, terr = text(src) + local pos = 1 + local index = 0 + local dead = false + return function(): (number?, any, Err.Err?) + if dead then + return nil + end + index += 1 + if not s then + dead = true + return index, nil, terr + end + local v, ni = Json.decodeAt(s, pos, opts) + if v == nil then + dead = true + if ni == nil then + return nil + end + return index, nil, ni + end + pos = ni + return index, v, nil + end +end + +function Json.events(src: string | buffer, opts: DecodeOptions?): () -> (string?, any) + local s, terr = text(src) + if not s then + local done = false + return function(): (string?, any) + if done then + return nil, nil + end + done = true + return "error", terr + end + end + local str: string = s + local i = if string.sub(str, 1, 3) == "\239\187\191" then 4 else 1 + local nextEv = Decode.events(str, i, opts) + return function(): (string?, any) + local ev, v, at = nextEv() + if ev == "error" then + return ev, fail(v, at, #str) + end + return ev, v + end +end + +function Json.encode(value: any, opts: EncodeOptions?): (string?, Err.Err?) + local s, msg = Encode.encode(value, opts) + if not s then + return nil, Err.new(Err.ARG, msg or "cannot encode") + end + return s, nil +end + +Json.quote = Encode.quote +Json.number = Encode.number + +type Writer = { + err: Err.Err?, + beginObject: (self: Writer) -> Writer, + endObject: (self: Writer) -> Writer, + beginArray: (self: Writer) -> Writer, + endArray: (self: Writer) -> Writer, + key: (self: Writer, k: string) -> Writer, + value: (self: Writer, v: any) -> Writer, + flush: (self: Writer) -> string, + tostring: (self: Writer) -> (string?, Err.Err?), +} + +function Json.writer(opts: EncodeOptions?): Writer + local st = Encode.state(opts) + local ind = st.indent + local kinds: { boolean } = {} + local counts: { number } = {} + local depth = 0 + local keyDone = false + local flushed: { string } = {} + local w: any = { err = nil } + local function bad(msg: string) + if not w.err then + w.err = Err.new(Err.ARG, msg) + end + end + local function slot(isKey: boolean): boolean + if w.err then + return false + end + if depth == 0 then + if counts[0] and counts[0] > 0 then + bad("one top-level value only") + return false + end + counts[0] = 1 + return true + end + local obj = kinds[depth] + if obj and not isKey then + if not keyDone then + bad("an object member needs a key first") + return false + end + keyDone = false + return true + end + if isKey and not obj then + bad("key outside an object") + return false + end + if isKey and keyDone then + bad("two keys in a row") + return false + end + if counts[depth] > 0 then + table.insert(st.out, ",") + end + counts[depth] += 1 + if ind then + table.insert(st.out, "\n" .. string.rep(ind, depth)) + end + return true + end + local function open(obj: boolean) + if slot(false) then + table.insert(st.out, if obj then "{" else "[") + depth += 1 + kinds[depth], counts[depth] = obj, 0 + end + return w + end + local function close(obj: boolean) + if w.err then + return w + end + if depth == 0 or kinds[depth] ~= obj or (obj and keyDone) then + bad(if obj then "unbalanced endObject" else "unbalanced endArray") + return w + end + if ind and counts[depth] > 0 then + table.insert(st.out, "\n" .. string.rep(ind, depth - 1)) + end + table.insert(st.out, if obj then "}" else "]") + depth -= 1 + return w + end + function w.beginObject(_self: Writer): Writer + return open(true) + end + function w.beginArray(_self: Writer): Writer + return open(false) + end + function w.endObject(_self: Writer): Writer + return close(true) + end + function w.endArray(_self: Writer): Writer + return close(false) + end + function w.key(_self: Writer, k: string): Writer + if type(k) ~= "string" then + bad("key must be a string") + elseif slot(true) then + table.insert(st.out, Encode.quote(k, st.ascii, st.slash) .. (if ind then ": " else ":")) + keyDone = true + end + return w + end + function w.value(_self: Writer, v: any): Writer + if slot(false) then + st.n = #st.out + if not Encode.write(st, v, depth) then + bad(st.err or "cannot encode") + end + end + return w + end + function w.flush(_self: Writer): string + local s = table.concat(st.out) + table.clear(st.out) + st.n = 0 + table.insert(flushed, s) + return s + end + function w.tostring(_self: Writer): (string?, Err.Err?) + if w.err then + return nil, w.err + end + if depth ~= 0 then + return nil, Err.new(Err.ARG, "unclosed object / array") + end + return table.concat(flushed) .. table.concat(st.out), nil + end + return w :: Writer +end + +return Json +end +__FILES["codecs/text/Json/Decode"] = @native function() + + +-- codecs/text/Json/Decode: the RFC 8259 parser behind codecs/text/Json: iterative, strict grammar. +-- \u escapes with surrogate pairs; lone surrogates become WTF-8 bytes. +local Text = __include("codecs/text/Text") +local Types = __include("Types") + +local Decode = {} + +local byte, sub, find, match, char = string.byte, string.sub, string.find, string.match, string.char +local tonumber = tonumber +local concat = table.concat + +type Options = { + ordered: boolean?, + bigInts: ("number" | "string")?, + null: any?, + maxDepth: number?, +} + +local ESC: { [number]: string } = { + [34] = '"', + [92] = "\\", + [47] = "/", + [98] = "\b", + [102] = "\f", + [110] = "\n", + [114] = "\r", + [116] = "\t", +} + +local utf8char = Text.utf8char +Decode.utf8char = utf8char + +@native local function hex4(s: string, i: number): number? + local h = match(s, "^%x%x%x%x", i) + if not h then + return nil + end + return tonumber(h, 16) +end + +@native local function str(s: string, i: number): (string?, any, number?) + local j = find(s, '[%z\1-\31"\\]', i + 1) + if not j then + return nil, "unterminated string", #s + end + local c = byte(s, j) + if c == 34 then + return sub(s, i + 1, j - 1), j + 1 + end + local parts = {} + local np = 0 + local start = i + 1 + while true do + if c == 34 then + np += 1 + parts[np] = sub(s, start, j - 1) + return concat(parts), j + 1 + elseif c ~= 92 then + return nil, "control character in string", j - 1 + end + np += 1 + parts[np] = sub(s, start, j - 1) + local e = byte(s, j + 1) + if e == nil then + return nil, "unterminated string", #s + end + local simple = ESC[e] + if simple then + np += 1 + parts[np] = simple + start = j + 2 + elseif e == 117 then -- \u + local cp = hex4(s, j + 2) + if not cp then + return nil, "bad \\u escape", j - 1 + end + start = j + 6 + if cp >= 0xD800 and cp <= 0xDBFF and byte(s, start) == 92 and byte(s, start + 1) == 117 then + local lo = hex4(s, start + 2) + if lo and lo >= 0xDC00 and lo <= 0xDFFF then + cp = 0x10000 + (cp - 0xD800) * 1024 + (lo - 0xDC00) + start += 6 + end + end + np += 1 + parts[np] = utf8char(cp) + else + return nil, "bad escape", j - 1 + end + j = find(s, '[%z\1-\31"\\]', start) + if not j then + return nil, "unterminated string", #s + end + c = byte(s, j) + end +end +Decode.string = str + +@native local function num(s: string, i: number, bigStrings: boolean): (any, any, number?) + local p = i + if byte(s, p) == 45 then + p += 1 + end + local c = byte(s, p) + if c == 48 then + p += 1 + elseif c and c >= 49 and c <= 57 then + p = match(s, "^%d*()", p + 1) :: any + else + return nil, if c == nil then "truncated: expected a value" elseif p == i then "unexpected character" else "bad number", p - 1 + end + local int = true + if byte(s, p) == 46 then + local q = match(s, "^%d+()", p + 1) + if not q then + return nil, "bad fraction", p + end + p = q :: any + int = false + end + c = byte(s, p) + if c == 101 or c == 69 then + p += 1 + c = byte(s, p) + if c == 43 or c == 45 then + p += 1 + end + local q = match(s, "^%d+()", p) + if not q then + return nil, "bad exponent", p - 1 + end + p = q :: any + int = false + end + local text = sub(s, i, p - 1) + local n = tonumber(text) :: number + if n == nil then -- LuaJIT: absurd exponents (1e0066999...) -> nil; they overflow / underflow + local m, es = match(text, "^([^eE]*)[eE]([%+%-]?)") + local mv = tonumber(m) or 0 + n = if mv == 0 then mv elseif es == "-" then mv * 0 else mv * math.huge + end + if int and bigStrings and p - i > 15 and (n >= 9007199254740992 or n <= -9007199254740992) then + return text, p + end + return n, p +end +Decode.number = num + +@native function Decode.value(s: string, i: number, opts: Options?): (any, any, number?) + local o: Options = opts or {} + local ordered = o.ordered == true + local bigStrings = o.bigInts == "string" + local nullv = if o.null ~= nil then o.null else Types.null + local maxDepth = o.maxDepth or 1000 + local object = Types.object + + local stackT: { any } = {} + local stackK: { any } = {} + local stackO: { any } = {} + local depth = 0 + local n = #s + local value: any + + while true do + i = match(s, "^[ \t\n\r]*()", i) :: any + local c = byte(s, i) + local haveValue = true + if c == 123 then -- { + depth += 1 + if depth > maxDepth then + return nil, "nested deeper than " .. maxDepth, i - 1 + end + i = match(s, "^[ \t\n\r]*()", i + 1) :: any + local t = {} + c = byte(s, i) + if c == 125 then + i += 1 + depth -= 1 + value = object(t, {}) + elseif c == 34 then + local k, ni, at = str(s, i) + if k == nil then + return nil, ni, at + end + i = match(s, "^[ \t\n\r]*()", ni) :: any + if byte(s, i) ~= 58 then + return nil, if i > n then "truncated object" else "expected ':'", i - 1 + end + i += 1 + stackT[depth], stackK[depth] = t, k + stackO[depth] = if ordered then {} else true + haveValue = false + else + return nil, if c == nil then "truncated object" else "expected a key", i - 1 + end + elseif c == 91 then -- [ + depth += 1 + if depth > maxDepth then + return nil, "nested deeper than " .. maxDepth, i - 1 + end + i = match(s, "^[ \t\n\r]*()", i + 1) :: any + if byte(s, i) == 93 then + i += 1 + depth -= 1 + value = {} + else + stackT[depth], stackK[depth], stackO[depth] = {}, 0, false + haveValue = false + end + elseif c == 34 then + local v, ni, at = str(s, i) + if v == nil then + return nil, ni, at + end + value, i = v, ni + elseif c == 116 then + if sub(s, i, i + 3) ~= "true" then + return nil, "bad literal", i - 1 + end + value, i = true, i + 4 + elseif c == 102 then + if sub(s, i, i + 4) ~= "false" then + return nil, "bad literal", i - 1 + end + value, i = false, i + 5 + elseif c == 110 then + if sub(s, i, i + 3) ~= "null" then + return nil, "bad literal", i - 1 + end + value, i = nullv, i + 4 + elseif c == nil then + return nil, "truncated: expected a value", n + else + local v, ni, at = num(s, i, bigStrings) + if v == nil then + return nil, ni, at + end + value, i = v, ni + end + while haveValue do + if depth == 0 then + return value, i + end + local t = stackT[depth] + local ord = stackO[depth] + if ord then + local k = stackK[depth] + if ord ~= true and t[k] == nil then + table.insert(ord, k) + end + t[k] = value + else + local cnt = stackK[depth] + 1 + t[cnt] = value + stackK[depth] = cnt + end + i = match(s, "^[ \t\n\r]*()", i) :: any + c = byte(s, i) + if c == 44 then -- , + i = match(s, "^[ \t\n\r]*()", i + 1) :: any + if ord then + if byte(s, i) ~= 34 then + return nil, if i > n then "truncated object" else "expected a key", i - 1 + end + local k, ni, at = str(s, i) + if k == nil then + return nil, ni, at + end + i = match(s, "^[ \t\n\r]*()", ni) :: any + if byte(s, i) ~= 58 then + return nil, if i > n then "truncated object" else "expected ':'", i - 1 + end + i += 1 + stackK[depth] = k + end + haveValue = false + elseif ord and c == 125 then + i += 1 + value = if ord ~= true then object(t, ord) elseif next(t) == nil then object(t, {}) else t + stackT[depth] = nil + depth -= 1 + elseif not ord and c == 93 then + i += 1 + value = t + stackT[depth] = nil + depth -= 1 + elseif c == nil then + return nil, if ord then "truncated object" else "truncated array", n + else + return nil, if ord then "expected ',' or '}'" else "expected ',' or ']'", i - 1 + end + end + end +end + +@native function Decode.events(s: string, i: number, opts: Options?): () -> (string?, any, number?) + local o: Options = opts or {} + local bigStrings = o.bigInts == "string" + local nullv = if o.null ~= nil then o.null else Types.null + local maxDepth = o.maxDepth or 1000 + local stack: { boolean } = {} + local depth = 0 + local state = "value" + local n = #s + @native local function fail(msg: string, at: number): (string, any, number) + state = "dead" + return "error", msg, at + end + return @native function(): (string?, any, number?) + if state == "dead" then + return nil + end + i = match(s, "^[ \t\n\r]*()", i) :: any + local c = byte(s, i) + if state == "done" then + state = "dead" + if c ~= nil then + return "error", "trailing data", i - 1 + end + return nil + end + if state == "after" then + local obj = stack[depth] + if c == 44 then + i = match(s, "^[ \t\n\r]*()", i + 1) :: any + c = byte(s, i) + state = if obj then "key" else "value" + elseif c == (if obj then 125 else 93) then + i += 1 + stack[depth] = nil + depth -= 1 + state = if depth == 0 then "done" else "after" + return if obj then "endObject" else "endArray", nil + elseif c == nil then + return fail("truncated", n) + else + return fail("expected ',' or a close", i - 1) + end + end + if state == "first" then + local obj = stack[depth] + if c == (if obj then 125 else 93) then + i += 1 + stack[depth] = nil + depth -= 1 + state = if depth == 0 then "done" else "after" + return if obj then "endObject" else "endArray", nil + end + state = if obj then "key" else "value" + end + if state == "key" then + if c ~= 34 then + return fail(if c == nil then "truncated" else "expected a key", i - 1) + end + local k, ni, at = str(s, i) + if k == nil then + return fail(ni, at :: number) + end + i = match(s, "^[ \t\n\r]*()", ni) :: any + if byte(s, i) ~= 58 then + return fail("expected ':'", i - 1) + end + i += 1 + state = "value" + return "key", k + end + local after = if depth == 0 then "done" else "after" + if c == 123 or c == 91 then + depth += 1 + if depth > maxDepth then + return fail("nested deeper than " .. maxDepth, i - 1) + end + stack[depth] = c == 123 + i += 1 + state = "first" + return if c == 123 then "object" else "array", nil + elseif c == 34 then + local v, ni, at = str(s, i) + if v == nil then + return fail(ni, at :: number) + end + i = ni + state = after + return "value", v + elseif c == 116 and sub(s, i, i + 3) == "true" then + i += 4 + state = after + return "value", true + elseif c == 102 and sub(s, i, i + 4) == "false" then + i += 5 + state = after + return "value", false + elseif c == 110 and sub(s, i, i + 3) == "null" then + i += 4 + state = after + return "value", nullv + elseif c == nil then + return fail("truncated: expected a value", n) + end + local v, ni, at = num(s, i, bigStrings) + if v == nil then + return fail(ni, at :: number) + end + i = ni + state = after + return "value", v + end +end + +return Decode +end +__FILES["codecs/text/Json/Encode"] = @native function() + + +-- codecs/text/Json/Encode: the RFC 8259 serializer behind codecs/text/Json. +local Types = __include("Types") + +local Encode = {} + +local byte, format, gsub = string.byte, string.format, string.gsub +local floor, huge = math.floor, math.huge +local concat = table.concat + +type Options = { + indent: (number | string)?, + sortKeys: boolean?, + ascii: boolean?, + nan: ("error" | "null")?, + emptyTable: ("array" | "object")?, + maxDepth: number?, + escapeSlash: boolean?, +} + +local ESCAPES: { [string]: string } = { + ['"'] = '\\"', + ["\\"] = "\\\\", + ["\b"] = "\\b", + ["\f"] = "\\f", + ["\n"] = "\\n", + ["\r"] = "\\r", + ["\t"] = "\\t", + ["/"] = "\\/", +} +for c = 0, 31 do + local ch = string.char(c) + if not ESCAPES[ch] then + ESCAPES[ch] = format("\\u%04x", c) + end +end + +@native local function utf16(cp: number): string + if cp < 0x10000 then + return format("\\u%04x", cp) + end + cp -= 0x10000 + return format("\\u%04x\\u%04x", 0xD800 + cp // 1024, 0xDC00 + cp % 1024) +end + +@native local function asciiSeq(seq: string): string + local out = {} + local i, n = 1, #seq + while i <= n do + local c = byte(seq, i) + local cp, len + if c < 0xC0 then + cp, len = c, 1 + elseif c < 0xE0 then + cp, len = (c % 32) * 64 + (byte(seq, i + 1) or 128) % 64, 2 + elseif c < 0xF0 then + cp, len = (c % 16) * 4096 + ((byte(seq, i + 1) or 128) % 64) * 64 + (byte(seq, i + 2) or 128) % 64, 3 + else + cp, len = (c % 8) * 262144 + ((byte(seq, i + 1) or 128) % 64) * 4096 + ((byte(seq, i + 2) or 128) % 64) * 64 + (byte(seq, i + 3) or 128) % 64, 4 + end + table.insert(out, utf16(cp)) + i += len + end + return concat(out) +end + +-- ascii escapes DEL too, like Python's ensure_ascii +@native local function quote(s: string, ascii: boolean?, slash: boolean?): string + local pat = if slash then '[%z\1-\31"\\/]' else '[%z\1-\31"\\]' + if string.find(s, pat) then + s = gsub(s, pat, ESCAPES) + end + if ascii and string.find(s, "[\127-\255]") then + s = gsub(s, "\127", "\\u007f") + s = gsub(s, "[\192-\255][\128-\191]*", asciiSeq) + s = gsub(s, "[\128-\191]", asciiSeq) + end + return '"' .. s .. '"' +end +Encode.quote = quote + +local FLOAT_FORMATS = { "%.15g", "%.16g", "%.17g" } +@native local function number(x: number): string? + if x ~= x or x == huge or x == -huge then + return nil + end + if x == floor(x) and x > -1e15 and x < 1e15 then + if x == 0 and 1 / x < 0 then + return "-0" + end + return format("%d", x) + end + for _, f in FLOAT_FORMATS do + local t = format(f, x) + if tonumber(t) == x then + return t + end + end + return format("%.17g", x) +end +Encode.number = number + +@native local function keyLess(a: any, b: any): boolean + local ta, tb = type(a), type(b) + if ta ~= tb then + return ta == "number" + end + return a < b +end + +@native local function kind(t: { [any]: any }, emptyObject: boolean): string + if Types.isObject(t) then + return "object" + end + local n = #t + if n == 0 then + if next(t) == nil then + return if emptyObject then "object" else "array" + end + return "object" + end + local count = 0 + for _ in next, t do + count += 1 + end + return if count == n then "array" else "object" +end +Encode.kind = kind + +type State = { + out: { string }, + n: number, + indent: string?, + sort: boolean, + ascii: boolean, + slash: boolean, + nanNull: boolean, + emptyObject: boolean, + maxDepth: number, + null: any, + err: string?, +} + +@native local function put(st: State, s: string) + local n = st.n + 1 + st.out[n] = s + st.n = n +end + +@native local function value(st: State, v: any, depth: number): boolean + local tv = type(v) + if tv == "string" then + put(st, quote(v, st.ascii, st.slash)) + elseif tv == "number" then + local s = number(v) + if not s then + if not st.nanNull then + st.err = "cannot encode " .. tostring(v) + return false + end + s = "null" + end + put(st, s) + elseif tv == "boolean" then + put(st, if v then "true" else "false") + elseif v == nil or v == st.null or v == Types.null then + put(st, "null") + elseif tv == "table" then + if Types.Date.is(v) then + put(st, '"' .. tostring(v) .. '"') + return true + end + if depth >= st.maxDepth then + st.err = "nested deeper than " .. st.maxDepth .. " (a cycle?)" + return false + end + local ind = st.indent + local nl, nl2 = "", "" + if ind then + nl = "\n" .. string.rep(ind, depth + 1) + nl2 = "\n" .. string.rep(ind, depth) + end + if kind(v, st.emptyObject) == "array" then + local n = #v + if n == 0 then + put(st, "[]") + return true + end + put(st, "[") + for i = 1, n do + if i > 1 then + put(st, ",") + end + if ind then + put(st, nl) + end + if not value(st, v[i], depth + 1) then + return false + end + end + if ind then + put(st, nl2) + end + put(st, "]") + else + local keys: { any } + if Types.isObject(v) then + keys = Types.keys(v) + else + keys = {} + for k in next, v do + local tk = type(k) + if tk ~= "string" and tk ~= "number" then + st.err = "object key of type " .. tk + return false + end + table.insert(keys, k) + end + if st.sort then + table.sort(keys, keyLess) + end + end + if #keys == 0 then + put(st, "{}") + return true + end + put(st, "{") + local sep = if ind then ": " else ":" + for i, k in keys do + if i > 1 then + put(st, ",") + end + if ind then + put(st, nl) + end + local ks: string + if type(k) == "string" then + ks = k + elseif type(k) == "number" then + ks = number(k) or tostring(k) + else + st.err = "object key of type " .. type(k) + return false + end + put(st, quote(ks, st.ascii, st.slash)) + put(st, sep) + if not value(st, v[k], depth + 1) then + return false + end + end + if ind then + put(st, nl2) + end + put(st, "}") + end + elseif tv == "buffer" then + st.err = "cannot encode a buffer (encode it as base64 or an array first)" + return false + else + st.err = "cannot encode a " .. tv + return false + end + return true +end + +@native local function state(opts: Options?, nullv: any?): State + local o: Options = opts or {} + local ind: string? = nil + if type(o.indent) == "number" then + ind = if o.indent > 0 then string.rep(" ", o.indent) else nil + elseif type(o.indent) == "string" then + ind = o.indent + end + return { + out = {}, + n = 0, + indent = ind, + sort = o.sortKeys ~= false, + ascii = o.ascii == true, + slash = o.escapeSlash == true, + nanNull = o.nan == "null", + emptyObject = o.emptyTable == "object", + maxDepth = o.maxDepth or 1000, + null = nullv, + err = nil, + } +end +Encode.state = state +Encode.write = value + +@native function Encode.encode(v: any, opts: Options?, nullv: any?): (string?, string?) + local st = state(opts, nullv) + if not value(st, v, 0) then + return nil, st.err + end + return concat(st.out), nil +end + +return Encode +end +__FILES["codecs/text/Nbt"] = function() + +-- codecs/text/Nbt: Minecraft's Named Binary Tag format and SNBT (Minecraft wiki "NBT format", wiki.vg "NBT"). +-- Files may be gzip or zlib compressed; a Bedrock level.dat has an 8-byte header. +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Deflate = __include("codecs/compress/Deflate") +local Value = __include("codecs/text/Nbt/Value") +local Binary = __include("codecs/text/Nbt/Binary") +local Snbt = __include("codecs/text/Nbt/Snbt") + +local Nbt = {} + +type Tag = Value.Tag +type Info = { + name: string, + endian: "big" | "little", + varint: boolean?, + compression: "gzip" | "zlib" | "none", + header: number?, +} +type DecodeOptions = { + endian: ("big" | "little")?, + varint: boolean?, + nameless: boolean?, + maxDepth: number?, + maxBytes: number?, +} +type EncodeOptions = { + endian: ("big" | "little")?, + varint: boolean?, + nameless: boolean?, + name: string?, + compression: ("gzip" | "zlib" | "none")?, + header: number?, + level: number?, +} + +Nbt.TAG = Value.IDS +Nbt.TAG_NAMES = Value.NAMES +Nbt.byte = Value.byte +Nbt.short = Value.short +Nbt.int = Value.int +Nbt.long = Value.long +Nbt.float = Value.float +Nbt.double = Value.double +Nbt.intArray = Value.intArray +Nbt.longArray = Value.longArray +Nbt.longs = Value.longs +Nbt.list = Value.list +Nbt.listType = Value.listType +Nbt.compound = Value.compound +Nbt.typeOf = Value.typeOf +Nbt.isTag = Value.isTag +Nbt.number = Value.number +Nbt.fromHiLo = Value.fromHiLo +Nbt.toHiLo = Value.toHiLo + +local infos: { [any]: Info } = setmetatable({}, { __mode = "k" }) :: any + +function Nbt.info(v: any): Info? + return if type(v) == "table" then infos[v] else nil +end +function Nbt.setInfo(v: any, info: Info) + if type(v) == "table" then + infos[v] = info + end +end + +function Nbt.read(buf: buffer | string, offset: number?, length: number?, opts: DecodeOptions?): (any, any, number?) + local b, o, l, aerr = Bytes.span("Nbt.read", buf, offset, length) + if not b then + return nil, aerr + end + local v, name, at = Binary.read(b, o, o + l, opts :: any) + if v == nil then + return nil, Err.from(name, (at or o) - o) + end + return v, name, at +end + +function Nbt.write(v: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local out, e = Binary.write(v, opts :: any) + if not out then + return nil, Err.new(Err.ARG, tostring(e)) + end + return out, nil +end + +function Nbt.unwrap(buf: buffer | string, offset: number?, length: number?, maxBytes: number?): (buffer?, any, number?, string?) + local b, o, l, aerr = Bytes.span("Nbt.unwrap", buf, offset, length) + if not b then + return nil, aerr + end + local c0 = if l >= 2 then buffer.readu8(b, o) else 0 + local c1 = if l >= 2 then buffer.readu8(b, o + 1) else 0 + local out, err, comp + if c0 == 0x1f and c1 == 0x8b then + out, err = Deflate.gunzip(b, o, l) + comp = "gzip" + elseif c0 % 16 == 8 and c0 < 0x80 and (c0 * 256 + c1) % 31 == 0 then + out, err = Deflate.zlib(b, o, l) + comp = "zlib" + else + return b, o, o + l, "none" + end + if not out then + return nil, err + end + if buffer.len(out) > (maxBytes or 2 ^ 28) then + return nil, Err.new(Err.LIMIT, "inflates to " .. buffer.len(out) .. " bytes, over maxBytes") + end + return out, 0, buffer.len(out), comp +end + +type Peek = { + compression: string, + endian: "big" | "little", + header: boolean, + rootType: string, + name: string, + firstType: string?, + firstName: string?, + head: buffer, +} + +local function plausibleName(b: buffer, p: number, n: number): string? + if p + n > buffer.len(b) or n > 256 then + return nil + end + local s = buffer.readstring(b, p, n) + if string.find(s, "[%z\1-\31\127]") then + return nil + end + return s +end + +function Nbt.peek(buf: buffer, offset: number?, length: number?): Peek? + local o = offset or 0 + local l = length or (buffer.len(buf) - o) + if l < 3 then + return nil + end + local c0, c1 = buffer.readu8(buf, o), buffer.readu8(buf, o + 1) + local head: buffer + local comp = "none" + if c0 == 0x1f and c1 == 0x8b or (c0 % 16 == 8 and c0 < 0x80 and (c0 * 256 + c1) % 31 == 0) then + local h = Deflate.peek(buf, o, l, 1024) + if not h then + return nil + end + head, comp = h, if c0 == 0x1f then "gzip" else "zlib" + else + local n = math.min(l, 1024) + head = buffer.create(n) + buffer.copy(head, 0, buf, o, n) + end + local hn = buffer.len(head) + local function at(p: number, endian: string, header: boolean): Peek? + if p + 3 > hn then + return nil + end + local t = buffer.readu8(head, p) + if t ~= 10 and t ~= 9 then + return nil + end + local function u16(q: number): number + local a, b = buffer.readu8(head, q), buffer.readu8(head, q + 1) + return if endian == "big" then a * 256 + b else b * 256 + a + end + local nl = u16(p + 1) + local name = plausibleName(head, p + 3, nl) + if not name then + return nil + end + local res: Peek = { compression = comp, endian = endian :: any, header = header, rootType = Value.NAMES[t], name = name, head = head } + local q = p + 3 + nl + if t == 10 and q < hn then + local ft = buffer.readu8(head, q) + if ft > 12 then + return nil + end + if ft == 0 then + res.firstType = "end" + elseif q + 3 <= hn then + local fname = plausibleName(head, q + 3, u16(q + 1)) + if fname == nil and q + 3 + u16(q + 1) <= hn then + return nil + end + res.firstType, res.firstName = Value.NAMES[ft], fname + end + end + return res + end + if hn >= 12 and buffer.readu32(head, 4) == (if comp == "none" then l else -1) - 8 then + local r = at(8, "little", true) + if r then + return r + end + end + return at(0, "big", false) or at(0, "little", false) +end + +function Nbt.decode(buf: buffer | string, opts: DecodeOptions?, offset: number?, length: number?): (any, any) + local o: DecodeOptions = opts or {} + local b, s, e, comp = Nbt.unwrap(buf, offset, length, o.maxBytes) + if not b then + return nil, s + end + local data: buffer, start: number, stop: number = b, s, e :: number + local function try(endian: string, from: number, varint: boolean?): (any, any, number?) + return Binary.read(data, from, stop, { endian = endian :: any, varint = varint, nameless = o.nameless, maxDepth = o.maxDepth }) + end + local header: number? = nil + local v, name, at + if o.varint then + v, name, at = try("little", start, true) + elseif o.endian then + local from = start + if o.endian == "little" and stop - start >= 8 and buffer.readu32(data, start + 4) == stop - start - 8 then + header, from = buffer.readu32(data, start), start + 8 + end + v, name, at = try(o.endian, from) + else + -- Bedrock level.dat: version, length (u32le), then little-endian NBT + if stop - start >= 9 and buffer.readu32(data, start + 4) == stop - start - 8 and buffer.readu8(data, start + 8) == 10 then + v, name, at = try("little", start + 8) + if v ~= nil then + header = buffer.readu32(data, start) + o = table.clone(o) + o.endian = "little" + end + end + if v == nil then + local bv, bn, ba = try("big", start) + if bv ~= nil and ba == stop then + v, name, at, o = bv, bn, ba, table.clone(o) + o.endian = "big" + else + local lv, ln, la = try("little", start) + if lv ~= nil and (la == stop or bv == nil) then + v, name, at, o = lv, ln, la, table.clone(o) + o.endian = "little" + elseif bv ~= nil then + v, name, at, o = bv, bn, ba, table.clone(o) + o.endian = "big" + else + v, name, at = nil, bn, ba + end + end + end + end + if v == nil then + return nil, Err.from(name, (at or start) - start) + end + local info: Info = { + name = name, + endian = if o.varint or o.endian == "little" then "little" else "big", + varint = if o.varint then true else nil, + compression = comp :: any, + header = header, + } + if type(v) == "table" then + infos[v] = info + end + return v, info +end + +function Nbt.encode(v: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local info = Nbt.info(v) + local endian = o.endian or (info and info.endian) or "big" + local varint = if o.varint ~= nil then o.varint else (info and info.varint) + local raw, e = Binary.write(v, { + endian = endian, + varint = varint, + nameless = o.nameless, + name = o.name or (info and info.name) or "", + }) + if not raw then + return nil, Err.new(Err.ARG, tostring(e)) + end + local header = if o.header ~= nil then o.header else (info and info.header) + if header then + local h = buffer.create(buffer.len(raw) + 8) + buffer.writeu32(h, 0, header) + buffer.writeu32(h, 4, buffer.len(raw)) + buffer.copy(h, 8, raw) + raw = h + end + local comp = o.compression or (info and info.compression) or (if endian == "big" then "gzip" else "none") + if comp == "gzip" then + return Deflate.gzip(raw, { level = o.level }) + elseif comp == "zlib" then + return Deflate.zlibCompress(raw, { level = o.level }) + elseif comp ~= "none" then + return nil, Err.new(Err.ARG, "unknown compression " .. tostring(comp)) + end + return raw, nil +end + +function Nbt.parse(text: string | buffer, opts: Snbt.ParseOptions?): (any, Err.Err?) + local s = if type(text) == "buffer" then buffer.tostring(text) else text + if type(s) ~= "string" then + return nil, Err.new(Err.ARG, "Nbt.parse: text must be a string") + end + local v, e, at = Snbt.parse(s, opts) + if v == nil then + return nil, Err.from(e, (at or 1) - 1) + end + return v, nil +end + +function Nbt.print(v: any, opts: Snbt.PrintOptions?): (string?, Err.Err?) + local s, e = Snbt.print(v, opts) + if not s then + return nil, Err.new(Err.ARG, tostring(e)) + end + return s, nil +end + +function Nbt.get(v: any, path: string): any + local cur = v + for part in string.gmatch(path, "[^%.]+") do + local k, rest = string.match(part, "^([^%[]*)(.*)$") + if k ~= "" then + if type(cur) ~= "table" or Value.isTag(cur) then + return nil + end + cur = cur[k] + end + for idx in string.gmatch(rest :: string, "%[(%-?%d+)%]") do + local i = tonumber(idx) :: number + if type(cur) == "table" and not Value.isTag(cur) then + cur = cur[i + 1] + elseif Value.isTag(cur) and type(cur.value) == "table" then + cur = cur.value[i + 1] + elseif type(cur) == "buffer" and i >= 0 and i < buffer.len(cur) then + cur = buffer.readi8(cur, i) + else + return nil + end + end + end + return cur +end + +Nbt.object = Types.object +Nbt.shortest = Snbt.shortest + +return Nbt +end +__FILES["codecs/text/Nbt/Binary"] = function() + +-- codecs/text/Nbt/Binary: binary NBT read and write, from the Minecraft wiki "NBT format" page and wiki.vg "NBT". +-- Java big-endian (modified UTF-8 strings), Bedrock little-endian (UTF-8), and Bedrock network NBT (little-endian, +-- zigzag varint int / long, varint lengths). +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Value = __include("codecs/text/Nbt/Value") + +local Binary = {} + +type Options = { + endian: ("big" | "little")?, + varint: boolean?, + nameless: boolean?, + maxDepth: number?, + name: string?, +} + +local readu8, readi8, readu32, readi16 = buffer.readu8, buffer.readi8, buffer.readu32, buffer.readi16 +local readf32, readf64, writeu32, readstring = buffer.readf32, buffer.readf64, buffer.writeu32, buffer.readstring +local byteswap = bit32.byteswap +local TWO32 = 4294967296 +local NAMES, IDS = Value.NAMES, Value.IDS +local newTag = Value.TagMeta + +type State = { b: buffer, p: number, e: number, le: boolean, net: boolean, java: boolean, depth: number, maxDepth: number, err: string?, scratch: buffer } + +-- Java's DataOutput strings: U+0000 as C0 80, supplementary characters as two 3-byte surrogates (CESU-8) +local function fromModified(s: string): string + if not string.find(s, "[\192\237]") then + return s + end + local out = {} + local i, n = 1, #s + while i <= n do + local c = string.byte(s, i) + if c == 0xC0 and string.byte(s, i + 1) == 0x80 then + table.insert(out, "\0") + i += 2 + elseif c == 0xED and i + 5 <= n then + local b2, b3, c4, b5, b6 = string.byte(s, i + 1, i + 5) + if b2 >= 0xA0 and b2 <= 0xAF and c4 == 0xED and b5 >= 0xB0 and b5 <= 0xBF then + local hiS = 0xD000 + (b2 - 0x80) * 64 + (b3 - 0x80) + local loS = 0xD000 + (b5 - 0x80) * 64 + (b6 - 0x80) + table.insert(out, utf8.char(0x10000 + (hiS - 0xD800) * 1024 + (loS - 0xDC00))) + i += 6 + else + table.insert(out, string.char(c)) + i += 1 + end + else + local j = string.find(s, "[\192\237]", i + 1) or n + 1 + table.insert(out, string.sub(s, i, j - 1)) + i = j + end + end + return table.concat(out) +end + +local function toModified(s: string): string + if not string.find(s, "[%z\240-\244]") then + return s + end + local out = {} + local i, n = 1, #s + while i <= n do + local c = string.byte(s, i) + if c == 0 then + table.insert(out, "\192\128") + i += 1 + elseif c >= 0xF0 and c <= 0xF4 and i + 3 <= n then + local b2, b3, b4 = string.byte(s, i + 1, i + 3) + local cp = (c - 0xF0) * 262144 + (b2 - 0x80) * 4096 + (b3 - 0x80) * 64 + (b4 - 0x80) - 0x10000 + local hiS, loS = 0xD800 + cp // 1024, 0xDC00 + cp % 1024 + table.insert(out, string.char(0xED, 0x80 + (hiS - 0xD000) // 64, 0x80 + hiS % 64)) + table.insert(out, string.char(0xED, 0x80 + (loS - 0xD000) // 64, 0x80 + loS % 64)) + i += 4 + else + local j = string.find(s, "[%z\240-\244]", i + 1) or n + 1 + table.insert(out, string.sub(s, i, j - 1)) + i = j + end + end + return table.concat(out) +end +Binary.fromModified = fromModified +Binary.toModified = toModified + +local function fail(s: State, msg: string): nil + if not s.err then + s.err = msg + end + s.p = s.e + return nil +end + +local function need(s: State, n: number): boolean + if s.p + n > s.e then + fail(s, "truncated") + return false + end + return true +end + +local function u8(s: State): number + if not need(s, 1) then + return 0 + end + local v = readu8(s.b, s.p) + s.p += 1 + return v +end + +local function varuint(s: State): number -- up to 32 bits (5 bytes) + local v, mul = 0, 1 + for _ = 1, 5 do + if not need(s, 1) then + return 0 + end + local c = readu8(s.b, s.p) + s.p += 1 + v += (c % 128) * mul + if c < 128 then + return v % TWO32 + end + mul *= 128 + end + fail(s, "varint too long") + return 0 +end + +local function i16(s: State): number + if not need(s, 2) then + return 0 + end + local p = s.p + s.p = p + 2 + if s.le then + return readi16(s.b, p) + end + local v = readu8(s.b, p) * 256 + readu8(s.b, p + 1) + return if v >= 32768 then v - 65536 else v +end + +local function u32raw(s: State): number + if not need(s, 4) then + return 0 + end + local p = s.p + s.p = p + 4 + local v = readu32(s.b, p) + return if s.le then v else byteswap(v) +end + +local function i32(s: State): number + if s.net then + local n = varuint(s) + return if n % 2 == 0 then n // 2 else -(n + 1) // 2 + end + local v = u32raw(s) + return if v >= 0x80000000 then v - TWO32 else v +end + +-- a length: i32 (zigzag varint in network NBT) +local function len(s: State): number + return i32(s) +end + +local function i64(s: State): (number, number) + if s.net then + local lo, hi, sh = 0, 0, 0 + while true do + if sh >= 70 or not need(s, 1) then + fail(s, "varint too long") + return 0, 0 + end + local c = readu8(s.b, s.p) + s.p += 1 + local d = c % 128 + if sh < 32 then + local x = d * 2 ^ sh + lo += x % TWO32 + hi = (hi + x // TWO32) % TWO32 + else + hi = (hi + d * 2 ^ (sh - 32)) % TWO32 + end + sh += 7 + if c < 128 then + break + end + end + local odd = lo % 2 == 1 + lo = lo // 2 + (hi % 2) * 0x80000000 + hi = hi // 2 + if odd then + hi, lo = TWO32 - 1 - hi, TWO32 - 1 - lo + end + return hi, lo + end + if s.le then + local lo = u32raw(s) + return u32raw(s), lo + end + local hi = u32raw(s) + return hi, u32raw(s) +end + +local function f32(s: State): number + local v = u32raw(s) + writeu32(s.scratch, 0, v) + return readf32(s.scratch, 0) +end + +local function f64(s: State): number + local hi, lo + if s.le then + lo = u32raw(s) + hi = u32raw(s) + else + hi = u32raw(s) + lo = u32raw(s) + end + writeu32(s.scratch, 0, lo) + writeu32(s.scratch, 4, hi) + return readf64(s.scratch, 0) +end + +local function str(s: State): string + local n + if s.net then + n = varuint(s) + else + n = i16(s) % 65536 + end + if not need(s, n) then + return "" + end + local v = readstring(s.b, s.p, n) + s.p += n + return if s.java then fromModified(v) else v +end + +local function tag(name: string, v: any): any + return setmetatable({ type = name, value = v }, newTag) +end + +local MIN = { [0] = 0, 1, 2, 4, 8, 4, 8, 4, 2, 5, 1, 4, 4 } +local MIN_NET = { [0] = 0, 1, 2, 1, 1, 4, 8, 1, 1, 2, 1, 1, 1 } + +local payload: (State, number) -> any + +local function count(s: State, n: number, size: number): boolean + if n < 0 then + fail(s, "negative length " .. n) + return false + end + if n * size > s.e - s.p then + fail(s, "truncated: " .. n .. " elements past the end") + return false + end + return true +end + +payload = function(s: State, id: number): any + if id == 3 then + return i32(s) + elseif id == 8 then + return str(s) + elseif id == 10 then + s.depth += 1 + if s.depth > s.maxDepth then + return fail(s, "limit: nested deeper than " .. s.maxDepth) + end + local o, keys = {}, {} + while true do + local t = u8(s) + if s.err then + return nil + end + if t == 0 then + break + end + if t > 12 then + return fail(s, "bad tag type " .. t) + end + local k = str(s) + local v = payload(s, t) + if s.err then + return nil + end + if o[k] == nil then + table.insert(keys, k) + end + o[k] = v + end + s.depth -= 1 + return Types.object(o, keys) + elseif id == 1 then + if not need(s, 1) then + return nil + end + s.p += 1 + return tag("byte", readi8(s.b, s.p - 1)) + elseif id == 2 then + return tag("short", i16(s)) + elseif id == 4 then + local hi, lo = i64(s) + return tag("long", Value.fromHiLo(hi, lo)) + elseif id == 5 then + return tag("float", f32(s)) + elseif id == 6 then + return tag("double", f64(s)) + elseif id == 7 then + local n = len(s) + if not count(s, n, 1) then + return nil + end + local out = buffer.create(n) + buffer.copy(out, 0, s.b, s.p, n) + s.p += n + return out + elseif id == 9 then + local et = u8(s) + local n = len(s) + if s.err then + return nil + end + if et > 12 then + return fail(s, "bad list element type " .. et) + end + if et == 0 and n > 0 then + return fail(s, "list of end tags with " .. n .. " elements") + end + if not count(s, n, (if s.net then MIN_NET else MIN)[et]) then + return nil + end + s.depth += 1 + if s.depth > s.maxDepth then + return fail(s, "limit: nested deeper than " .. s.maxDepth) + end + local out = table.create(n) + for i = 1, n do + local v = payload(s, et) + if s.err then + return nil + end + out[i] = v + end + s.depth -= 1 + Value.setListType(out, NAMES[et]) + return out + elseif id == 11 then + local n = len(s) + if not count(s, n, if s.net then 1 else 4) then + return nil + end + local out = table.create(n) + for i = 1, n do + out[i] = i32(s) + end + return tag("intArray", out) + elseif id == 12 then + local n = len(s) + if not count(s, n, if s.net then 1 else 8) then + return nil + end + local out = buffer.create(n * 8) + if s.net then + for i = 0, n - 1 do + local hi, lo = i64(s) + writeu32(out, i * 8, lo) + writeu32(out, i * 8 + 4, hi) + end + elseif s.le then + buffer.copy(out, 0, s.b, s.p, n * 8) + s.p += n * 8 + else + local b, p = s.b, s.p + for i = 0, n - 1 do + local q = p + i * 8 + writeu32(out, i * 8 + 4, byteswap(readu32(b, q))) + writeu32(out, i * 8, byteswap(readu32(b, q + 4))) + end + s.p = p + n * 8 + end + return tag("longArray", out) + end + return fail(s, "bad tag type " .. id) +end + +function Binary.read(b: buffer, pos: number, limit: number, opts: Options?): (any, any, number?) + local o: Options = opts or {} + local net = o.varint == true + local le = net or o.endian == "little" + local s: State = { + b = b, + p = pos, + e = limit, + le = le, + net = net, + java = not le, + depth = 0, + maxDepth = o.maxDepth or 512, + err = nil, + scratch = buffer.create(8), + } + local id = u8(s) + if s.err then + return nil, s.err, pos + end + if id == 0 or id > 12 then + return nil, "bad root tag type " .. id, pos + end + local name = if o.nameless then "" else str(s) + local v = payload(s, id) + if s.err then + return nil, s.err, s.p + end + return v, name, s.p +end + +type WState = { w: Bytes.Writer, le: boolean, net: boolean, java: boolean, depth: number, maxDepth: number } + +local function wvaruint(w: Bytes.Writer, v: number) + v %= TWO32 + while v >= 128 do + w:u8(v % 128 + 128) + v //= 128 + end + w:u8(v) +end + +local function wi32(ws: WState, v: number) + v %= TWO32 + if ws.net then + local sv = if v >= 0x80000000 then v - TWO32 else v + wvaruint(ws.w, if sv >= 0 then sv * 2 else -sv * 2 - 1) + elseif ws.le then + ws.w:u32le(v) + else + ws.w:u32be(v) + end +end + +local function wi16(ws: WState, v: number) + v %= 65536 + if ws.le then + ws.w:u16le(v) + else + ws.w:u16be(v) + end +end + +local function wi64(ws: WState, hi: number, lo: number) + if ws.net then + -- zigzag: (n << 1) ^ (n >> 63) + local neg = hi >= 0x80000000 + local zh = (hi * 2) % TWO32 + (if lo >= 0x80000000 then 1 else 0) + local zl = (lo * 2) % TWO32 + if neg then + zh, zl = TWO32 - 1 - zh, TWO32 - 1 - zl + end + while zh > 0 or zl >= 128 do + ws.w:u8(zl % 128 + 128) + zl = zl // 128 + (zh % 128) * 0x2000000 + zh //= 128 + end + ws.w:u8(zl) + elseif ws.le then + ws.w:u32le(lo) + ws.w:u32le(hi) + else + ws.w:u32be(hi) + ws.w:u32be(lo) + end +end + +local function wstr(ws: WState, s: string): string? + local v = if ws.java then toModified(s) else s + if ws.net then + wvaruint(ws.w, #v) + else + if #v > 65535 then + return "string longer than 65535 bytes" + end + wi16(ws, #v) + end + ws.w:string(v) + return nil +end + +local function integer(v: any, lo: number, hi: number, what: string): (number?, string?) + local n = if type(v) == "boolean" then (if v then 1 else 0) else v + if type(n) ~= "number" or n % 1 ~= 0 or n < lo or n > hi then + return nil, "bad " .. what .. " value " .. tostring(n) + end + return n, nil +end + +local wpayload: (WState, string, any) -> string? + +local function wlist(ws: WState, v: { any }): string? + local lt = Value.listType(v) + local n = #v + local wrap = false + if not lt then + if n == 0 then + lt = "end" + else + local t1, e1 = Value.typeOf(v[1]) + if not t1 then + return e1 + end + lt = t1 + end + end + for i = 1, n do + local t, e = Value.typeOf(v[i]) + if not t then + return e + end + if t ~= lt then + wrap = true -- mixed element types: every element becomes a compound { [""] = value }, as Minecraft does + end + end + if wrap then + lt = "compound" + end + if lt == "end" and n > 0 then + return "a list of end tags cannot hold elements" + end + ws.w:u8(IDS[lt :: string]) + wi32(ws, n) + for i = 1, n do + local x = v[i] + if wrap and Value.typeOf(x) ~= "compound" then + x = Types.object({ [""] = x }, { "" }) + end + local e = wpayload(ws, lt :: string, x) + if e then + return e + end + end + return nil +end + +wpayload = function(ws: WState, t: string, v: any): string? + local w = ws.w + local x = if Value.isTag(v) then v.value else v + if t == "int" then + local n, e = integer(x, -2147483648, 4294967295, "int") + if not n then + return e + end + wi32(ws, n) + elseif t == "string" then + if type(x) ~= "string" then + return "bad string value" + end + return wstr(ws, x) + elseif t == "compound" then + ws.depth += 1 + if ws.depth > ws.maxDepth then + return "nested deeper than " .. ws.maxDepth .. " (a cycle?)" + end + for _, k in Types.keys(v) do + if type(k) ~= "string" then + return "compound key " .. tostring(k) .. " is not a string" + end + local c = v[k] + local ct, e = Value.typeOf(c) + if not ct then + return e .. " (key " .. k .. ")" + end + w:u8(IDS[ct :: string]) + e = wstr(ws, k) + if e then + return e + end + e = wpayload(ws, ct :: string, c) + if e then + return e + end + end + w:u8(0) + ws.depth -= 1 + elseif t == "list" then + ws.depth += 1 + if ws.depth > ws.maxDepth then + return "nested deeper than " .. ws.maxDepth .. " (a cycle?)" + end + local e = wlist(ws, v) + if e then + return e + end + ws.depth -= 1 + elseif t == "byte" then + local n, e = integer(x, -128, 255, "byte") + if not n then + return e + end + w:u8(n % 256) + elseif t == "short" then + local n, e = integer(x, -32768, 65535, "short") + if not n then + return e + end + wi16(ws, n) + elseif t == "long" then + local hi, lo = Value.toHiLo(x) + if not hi then + return "bad long value " .. tostring(x) + end + wi64(ws, hi, lo :: number) + elseif t == "float" or t == "double" then + if type(x) ~= "number" then + return "bad " .. t .. " value " .. tostring(x) + end + if t == "float" then + if ws.le then + w:f32le(x) + else + w:f32be(x) + end + elseif ws.le then + w:f64le(x) + else + w:f64be(x) + end + elseif t == "byteArray" then + if type(x) ~= "buffer" then + return "bad byteArray value" + end + wi32(ws, buffer.len(x)) + w:bytes(x) + elseif t == "intArray" then + if type(x) ~= "table" then + return "bad intArray value" + end + wi32(ws, #x) + for i = 1, #x do + local n, e = integer(x[i], -2147483648, 4294967295, "intArray element") + if not n then + return e + end + wi32(ws, n) + end + elseif t == "longArray" then + if type(x) ~= "buffer" or buffer.len(x) % 8 ~= 0 then + return "bad longArray value (a buffer of 8-byte little-endian longs)" + end + local n = buffer.len(x) // 8 + wi32(ws, n) + if ws.le and not ws.net then + w:bytes(x) + else + for i = 0, n - 1 do + wi64(ws, buffer.readu32(x, i * 8 + 4), buffer.readu32(x, i * 8)) + end + end + else + return "cannot write tag type " .. t + end + return nil +end + +function Binary.write(v: any, opts: Options?): (buffer?, string?) + local o: Options = opts or {} + local net = o.varint == true + local le = net or o.endian == "little" + local t, e = Value.typeOf(v) + if not t then + return nil, e + end + local ws: WState = { w = Bytes.writer(1024), le = le, net = net, java = not le, depth = 0, maxDepth = o.maxDepth or 512 } + ws.w:u8(IDS[t :: string]) + if not o.nameless then + e = wstr(ws, o.name or "") + if e then + return nil, e + end + end + e = wpayload(ws, t :: string, v) + if e then + return nil, e + end + return ws.w:finish(), nil +end + +return Binary +end +__FILES["codecs/text/Nbt/Snbt"] = function() + +-- codecs/text/Nbt/Snbt: stringified NBT, parse and print, from the Minecraft wiki "NBT format" SNBT section (1.21.5). +-- Not supported: the 1.21.5 operations bool(...) / uuid(...) and \N{name} escapes. +local Types = __include("Types") +local Value = __include("codecs/text/Nbt/Value") + +local Snbt = {} + +type ParseOptions = { maxDepth: number? } +type PrintOptions = { + indent: (number | string)?, + quote: string?, +} + +local byte, sub, find = string.byte, string.sub, string.find +local TWO32 = 4294967296 + +local function tag(name: string, v: any): any + return setmetatable({ type = name, value = v }, Value.TagMeta) +end + +type P = { s: string, i: number, n: number, err: string?, at: number, depth: number, maxDepth: number } + +local function fail(p: P, msg: string): nil + if not p.err then + p.err, p.at = msg, p.i + end + p.i = p.n + 1 + return nil +end + +local function ws(p: P) + local _, e = find(p.s, "^%s*", p.i) + p.i = (e :: number) + 1 +end + +local function isUnquoted(c: number): boolean + return (c >= 48 and c <= 57) or (c >= 65 and c <= 90) or (c >= 97 and c <= 122) or c == 95 or c == 45 or c == 46 or c == 43 +end + +local ESC: { [string]: string } = { ["\\"] = "\\", ["'"] = "'", ['"'] = '"', n = "\n", t = "\t", r = "\r", b = "\b", f = "\f", s = " " } + +local function quoted(p: P): string? + local q = sub(p.s, p.i, p.i) + p.i += 1 + local out = {} + while true do + local j = find(p.s, if q == '"' then '["\\]' else "['\\]", p.i) + if not j then + return fail(p, "unterminated string") + end + table.insert(out, sub(p.s, p.i, j - 1)) + if sub(p.s, j, j) == q then + p.i = j + 1 + return table.concat(out) + end + local c = sub(p.s, j + 1, j + 1) + if ESC[c] then + table.insert(out, ESC[c]) + p.i = j + 2 + elseif c == "x" or c == "u" or c == "U" then + local nd = if c == "x" then 2 elseif c == "u" then 4 else 8 + local hex = sub(p.s, j + 2, j + 1 + nd) + if #hex ~= nd or find(hex, "[^%x]") then + p.i = j + return fail(p, "bad \\" .. c .. " escape") + end + local cp = tonumber(hex, 16) :: number + if cp > 0x10FFFF or (cp >= 0xD800 and cp <= 0xDFFF) then + p.i = j + return fail(p, "bad code point in \\" .. c .. " escape") + end + table.insert(out, utf8.char(cp)) + p.i = j + 2 + nd + else + p.i = j + return fail(p, "bad escape \\" .. c) + end + end +end + +local INT_RANGE: { [string]: { number } } = { + b = { -128, 127, 255 }, + s = { -32768, 32767, 65535 }, + i = { -2147483648, 2147483647, 4294967295 }, +} +local INT_NAME = { b = "byte", s = "short", i = "int", l = "long" } + +local function integer(t: string): any + local sign, body = string.match(t, "^([+-]?)(.+)$") + body = string.gsub(body :: string, "_", "") :: string + local radix, digits, suffix = 10, body, "" + local low = string.lower(body) + local m, sfx + if sub(low, 1, 2) == "0x" then + -- b and s are hex digits: a byte / short suffix needs its signedness (0x7Fsb, 0xFFub) + m, sfx = string.match(sub(body, 3), "^(%x+)([sSuU][bBsSiIlL])$") + if not m then + m, sfx = string.match(sub(body, 3), "^(%x+)([iIlL]?)$") + end + if not m then + return nil + end + radix = 16 + elseif sub(low, 1, 2) == "0b" then + m, sfx = string.match(sub(body, 3), "^([01]+)([sSuU]?[bBsSiIlL]?)$") + if m then + radix = 2 + end + end + if not m then + m, sfx = string.match(body, "^(%d+)([sSuU]?[bBsSiIlL]?)$") + if not m then + return nil + end + end + digits, suffix = m :: string, string.lower(sfx :: string) + local unsigned = false + if #suffix == 2 then + unsigned = sub(suffix, 1, 1) == "u" + suffix = sub(suffix, 2) + elseif suffix == "u" then + return nil + end + if suffix == "" then + suffix = "i" + end + if unsigned and sign == "-" then + return nil + end + local hi, lo = 0, 0 + for k = 1, #digits do + local c = byte(digits, k) + local d = if c <= 57 then c - 48 elseif c >= 97 then c - 87 else c - 55 + local x = lo * radix + d + local carry = x // TWO32 + lo = x - carry * TWO32 + hi = hi * radix + carry + if hi >= TWO32 then + return nil + end + end + if suffix == "l" then + local neg = sign == "-" + if radix == 10 then + if hi > 0x80000000 or (hi == 0x80000000 and (lo > 0 or not neg)) then + return nil + end + end + if neg and (hi > 0 or lo > 0) then + lo = (TWO32 - lo) % TWO32 + hi = (TWO32 - 1 - hi + (if lo == 0 then 1 else 0)) % TWO32 + end + return tag("long", Value.fromHiLo(hi, lo)) + end + if hi > 0 then + return nil + end + local r = INT_RANGE[suffix] + local v = lo + if sign == "-" then + v = -v + end + if radix ~= 10 and not unsigned and sign ~= "-" and v > r[2] and v <= r[3] then + v -= r[3] + 1 -- hex / binary literals wrap into the signed range (0xFFb = -1b) + elseif unsigned then + if v > r[3] then + return nil + end + if v > r[2] then + v -= r[3] + 1 + end + end + if v < r[1] or v > r[2] then + return nil + end + if suffix == "i" then + return v + end + return tag(INT_NAME[suffix], v) +end + +local function number(t: string): any + local low = string.lower(t) + if low == "true" then + return tag("byte", 1) + elseif low == "false" then + return tag("byte", 0) + end + local sfx = sub(low, -1) + local special = string.match(low, "^([+-]?)infinity[fd]$") + if special then + return tag(if sfx == "f" then "float" else "double", if special == "-" then -math.huge else math.huge) + elseif low == "nanf" or low == "nand" then + return tag(if sfx == "f" then "float" else "double", 0 / 0) + end + local iv = integer(t) + if iv ~= nil then + return iv + end + local body = string.gsub(t, "_", "") + local m, fs = string.match(body, "^([+-]?[%d%.]+[eE]?[+-]?%d*)([fFdD]?)$") + if not m then + return nil + end + -- mantissa digits[.digits] or .digits, an optional exponent; without a fraction or an exponent a suffix is needed + local mant, ex = string.match(m :: string, "^(.-)([eE][+-]?%d+)$") + if not mant then + mant = m + end + if not (string.match(mant :: string, "^[+-]?%d+%.?%d*$") or string.match(mant :: string, "^[+-]?%.%d+$")) then + return nil + end + if fs == "" and not ex and not find(mant :: string, ".", 1, true) then + return nil + end + local v = tonumber(m) + if not v then + return nil + end + if string.lower(fs :: string) == "f" then + local b = buffer.create(4) + buffer.writef32(b, 0, v) + return tag("float", buffer.readf32(b, 0)) + end + return tag("double", v) +end + +local parseValue: (P) -> any + +local function token(p: P): string + local j = p.i + while j <= p.n and isUnquoted(byte(p.s, j)) do + j += 1 + end + local t = sub(p.s, p.i, j - 1) + p.i = j + return t +end + +local function key(p: P): string? + ws(p) + local c = sub(p.s, p.i, p.i) + if c == '"' or c == "'" then + return quoted(p) + end + local t = token(p) + if t == "" then + return fail(p, "expected a key") + end + return t +end + +local ARRAY = { B = "byte", I = "int", L = "long" } + +local function array(p: P, kind: string): any + local items = {} + ws(p) + if sub(p.s, p.i, p.i) ~= "]" then + while true do + ws(p) + local at = p.i + local t = token(p) + local v = if t ~= "" then number(t) else nil + local vt = Value.typeOf(v) + if v == nil or (vt ~= "byte" and vt ~= "short" and vt ~= "int" and vt ~= "long") then + p.i = at + return fail(p, "expected an integer in a " .. kind .. " array") + end + local x: any = if Value.isTag(v) then (v :: any).value else v + if kind == "byte" and (x < -128 or x > 127) or kind == "int" and vt == "long" then + p.i = at + return fail(p, "value out of range in a " .. kind .. " array") + end + table.insert(items, x) + ws(p) + local c = sub(p.s, p.i, p.i) + p.i += 1 + if c == "]" then + break + elseif c ~= "," then + p.i -= 1 + return fail(p, "expected , or ]") + end + ws(p) + if sub(p.s, p.i, p.i) == "]" then + p.i += 1 + break + end + end + else + p.i += 1 + end + if kind == "byte" then + local b = buffer.create(#items) + for i, x in items do + buffer.writei8(b, i - 1, x) + end + return b + elseif kind == "int" then + return tag("intArray", items) + end + return Value.longArray(items) +end + +parseValue = function(p: P): any + ws(p) + if p.i > p.n then + return fail(p, "expected a value") + end + local c = sub(p.s, p.i, p.i) + if c == "{" then + p.depth += 1 + if p.depth > p.maxDepth then + return fail(p, "limit: nested deeper than " .. p.maxDepth) + end + p.i += 1 + local o, keys = {}, {} + ws(p) + if sub(p.s, p.i, p.i) == "}" then + p.i += 1 + else + while true do + local k = key(p) + if p.err then + return nil + end + ws(p) + if sub(p.s, p.i, p.i) ~= ":" then + return fail(p, "expected :") + end + p.i += 1 + local v = parseValue(p) + if p.err then + return nil + end + if o[k :: string] == nil then + table.insert(keys, k) + end + o[k :: string] = v + ws(p) + local d = sub(p.s, p.i, p.i) + p.i += 1 + if d == "}" then + break + elseif d ~= "," then + p.i -= 1 + return fail(p, "expected , or }") + end + ws(p) + if sub(p.s, p.i, p.i) == "}" then + p.i += 1 + break + end + end + end + p.depth -= 1 + return Types.object(o, keys) + elseif c == "[" then + p.depth += 1 + if p.depth > p.maxDepth then + return fail(p, "limit: nested deeper than " .. p.maxDepth) + end + p.i += 1 + local kind = string.match(p.s, "^%s*([BIL])%s*;", p.i) + if kind then + local _, e = find(p.s, "^%s*[BIL]%s*;", p.i) + p.i = (e :: number) + 1 + local v = array(p, ARRAY[kind]) + p.depth -= 1 + return v + end + local items = {} + local lt: string? = nil + local mixed = false + ws(p) + if sub(p.s, p.i, p.i) == "]" then + p.i += 1 + else + while true do + local v = parseValue(p) + if p.err then + return nil + end + local t = Value.typeOf(v) + if lt == nil then + lt = t + elseif t ~= lt then + mixed = true + end + table.insert(items, v) + ws(p) + local d = sub(p.s, p.i, p.i) + p.i += 1 + if d == "]" then + break + elseif d ~= "," then + p.i -= 1 + return fail(p, "expected , or ]") + end + ws(p) + if sub(p.s, p.i, p.i) == "]" then + p.i += 1 + break + end + end + end + p.depth -= 1 + if not mixed then + Value.setListType(items, lt or "end") + end + return items + elseif c == '"' or c == "'" then + return quoted(p) + end + local at = p.i + local t = token(p) + if t == "" then + return fail(p, "unexpected character " .. string.format("%q", c)) + end + local v = number(t) + if v == nil then + if string.match(t, "^[+-]?%d[%d_]*[sSuU]?[bBsSiIlL]$") then + p.i = at + return fail(p, "number out of range: " .. t) + end + return t + end + return v +end + +function Snbt.parse(s: string, opts: ParseOptions?): (any, string?, number?) + local p: P = { s = s, i = 1, n = #s, err = nil, at = 1, depth = 0, maxDepth = (opts and opts.maxDepth) or 512 } + local v = parseValue(p) + if p.err then + return nil, p.err, p.at + end + ws(p) + if p.i <= p.n then + return nil, "trailing characters after the value", p.i + end + return v, nil, nil +end + +local function shortest(v: number, single: boolean): string + if v ~= v then + return "NaN" + elseif v == math.huge then + return "Infinity" + elseif v == -math.huge then + return "-Infinity" + end + local b = buffer.create(4) + if single then + buffer.writef32(b, 0, v) + v = buffer.readf32(b, 0) + end + local s = "" + for digits = if single then 6 else 15, 17 do + s = string.format("%." .. digits .. "g", v) + local back = tonumber(s) :: number + if single then + buffer.writef32(b, 0, back) + back = buffer.readf32(b, 0) + end + if back == v then + break + end + end + if not find(s, "[%.eEn]") then + s ..= ".0" + end + return s +end +Snbt.shortest = shortest + +local function quote(s: string, q: string): string + local other = if q == '"' then "'" else '"' + local _, nq = string.gsub(s, q, "") + local _, no = string.gsub(s, other, "") + if nq > no then + q = other + end + local e = string.gsub(s, "[\\" .. q .. "%c]", function(c: string): string + if c == "\\" or c == q then + return "\\" .. c + elseif c == "\n" then + return "\\n" + elseif c == "\t" then + return "\\t" + elseif c == "\r" then + return "\\r" + end + return string.format("\\x%02x", byte(c)) + end) + return q .. e .. q +end + +local function keyText(k: string, q: string): string + if k ~= "" and not find(k, "[^%w_%-%.%+]") then + return k + end + return quote(k, q) +end + +type Pr = { out: { string }, indent: string?, q: string, depth: number } + +local printValue: (Pr, any, number) -> string? + +local function scalar(v: any, q: string): string? + local tv = type(v) + if tv == "number" then + if v % 1 == 0 and v >= -2147483648 and v <= 2147483647 then + return string.format("%d", v) + end + return shortest(v, false) .. "d" + elseif tv == "string" then + return quote(v, q) + elseif tv == "boolean" then + return if v then "1b" else "0b" + elseif Value.isTag(v) then + local t, x = v.type, v.value + if t == "byte" then + return string.format("%db", x) + elseif t == "short" then + return string.format("%ds", x) + elseif t == "int" then + return string.format("%d", x) + elseif t == "long" then + return (if type(x) == "string" then x else string.format("%d", x)) .. "L" + elseif t == "float" then + return shortest(x, true) .. "f" + elseif t == "double" then + return shortest(x, false) .. "d" + elseif t == "string" then + return quote(x, q) + end + end + return nil +end + +local function seq(pr: Pr, head: string, items: { string }, close: string) + if pr.indent and #items > 0 then + local pad = string.rep(pr.indent, pr.depth) + table.insert(pr.out, head .. "\n" .. pad .. pr.indent .. table.concat(items, ",\n" .. pad .. pr.indent) .. "\n" .. pad .. close) + else + table.insert(pr.out, head .. table.concat(items, if pr.indent then ", " else ",") .. close) + end +end + +local function sub1(pr: Pr, v: any): (string?, string?) + local inner: Pr = { out = {}, indent = pr.indent, q = pr.q, depth = pr.depth + 1 } + local e = printValue(inner, v, inner.depth) + if e then + return nil, e + end + return table.concat(inner.out), nil +end + +printValue = function(pr: Pr, v: any, depth: number): string? + if depth > 512 then + return "nested deeper than 512 (a cycle?)" + end + local s = scalar(v, pr.q) + if s then + table.insert(pr.out, s) + return nil + end + local t, terr = Value.typeOf(v) + if not t then + return terr + end + if t == "byteArray" then + local items = table.create(buffer.len(v)) :: { string } + for i = 0, buffer.len(v) - 1 do + items[i + 1] = buffer.readi8(v, i) .. "b" + end + seq(pr, "[B;", items, "]") + elseif t == "intArray" then + local items = {} + for i, x in v.value do + items[i] = string.format("%d", x) + end + seq(pr, "[I;", items, "]") + elseif t == "longArray" then + local items = {} + for i, x in Value.longs(v) do + items[i] = (if type(x) == "string" then x else string.format("%d", x)) .. "L" + end + seq(pr, "[L;", items, "]") + elseif t == "list" then + local items: { string } = {} + for i = 1, #v do + local x, e = sub1(pr, v[i]) + if e then + return e + end + items[i] = x :: string + end + seq(pr, "[", items, "]") + else + local items = {} + for _, k in Types.keys(v) do + if type(k) ~= "string" then + return "compound key " .. tostring(k) .. " is not a string" + end + local x, e = sub1(pr, v[k]) + if e then + return e + end + table.insert(items, keyText(k, pr.q) .. (if pr.indent then ": " else ":") .. (x :: string)) + end + seq(pr, "{", items, "}") + end + return nil +end + +function Snbt.print(v: any, opts: PrintOptions?): (string?, string?) + local o: PrintOptions = opts or {} + local ind = o.indent + local pr: Pr = { + out = {}, + indent = if type(ind) == "number" then string.rep(" ", ind) elseif type(ind) == "string" then ind else nil, + q = if o.quote == "'" then "'" else '"', + depth = 0, + } + local e = printValue(pr, v, 0) + if e then + return nil, e + end + return table.concat(pr.out), nil +end + +Value.print = function(v: any): string + return Snbt.print(v) or "?" +end + +return Snbt +end +__FILES["codecs/text/Nbt/Value"] = function() + +-- codecs/text/Nbt/Value: the NBT value model shared by the binary and SNBT codecs. New code. +-- long values are numbers when |v| <= 2^53, else their exact decimal text; longArray values are buffers of +-- little-endian two's complement int64s. +local Types = __include("Types") + +local Value = {} + +-- tag ids (the binary format) <-> names +Value.NAMES = { + [0] = "end", + "byte", + "short", + "int", + "long", + "float", + "double", + "byteArray", + "string", + "list", + "compound", + "intArray", + "longArray", +} :: { [number]: string } +Value.IDS = {} :: { [string]: number } +for id = 0, 12 do + Value.IDS[Value.NAMES[id]] = id +end + +type Tag = { type: string, value: any } + +local TagMeta: { [string]: any } = {} +Value.TagMeta = TagMeta +Value.print = function(v: any): string + return tostring(v.value) +end +TagMeta.__tostring = function(v: any): string + return Value.print(v) +end +TagMeta.__eq = function(a: any, b: any): boolean + if a.type ~= b.type then + return false + end + local x, y = a.value, b.value + if type(x) == "buffer" and type(y) == "buffer" then + return buffer.tostring(x) == buffer.tostring(y) + elseif type(x) == "table" and type(y) == "table" then + if #x ~= #y then + return false + end + for i = 1, #x do + if x[i] ~= y[i] then + return false + end + end + return true + end + return x == y +end + +local listTypes: { [any]: string } = setmetatable({}, { __mode = "k" }) :: any + +local TWO32 = 4294967296 + +function Value.fromHiLo(hi: number, lo: number): number | string + local s = if hi >= 0x80000000 then hi - TWO32 else hi + if s >= -0x200000 and s < 0x200000 then + return s * TWO32 + lo + end + local neg = s < 0 + if neg then -- magnitude = 2^64 - v + lo = (TWO32 - lo) % TWO32 + hi = (TWO32 - 1 - hi + (if lo == 0 then 1 else 0)) % TWO32 + end + local parts = {} + while hi > 0 or lo > 0 do -- divide (hi, lo) by 10^4: r * 2^32 + lo < 10^4 * 2^32 stays exact, ql < 2^32 + local qh = hi // 10000 + local x = (hi - qh * 10000) * TWO32 + lo + local ql = x // 10000 + local d = x - ql * 10000 + hi, lo = qh, ql + table.insert(parts, 1, string.format(if hi > 0 or lo > 0 then "%04d" else "%d", d)) + end + return (if neg then "-" else "") .. table.concat(parts) +end + +function Value.toHiLo(v: any): (number?, number?) + if type(v) == "number" then + if v % 1 ~= 0 or v < -9223372036854775808 or v >= 9223372036854775808 then + return nil, nil + end + local hi = v // TWO32 + local lo = v - hi * TWO32 + return hi % TWO32, lo + elseif type(v) == "string" then + local neg, digits = string.match(v, "^(%-?)(%d+)$") + if not digits or #digits > 19 then + return nil, nil + end + local hi, lo = 0, 0 + for i = 1, #digits do + local x = lo * 10 + (string.byte(digits, i) - 48) + local carry = x // TWO32 + lo = x - carry * TWO32 + hi = hi * 10 + carry + end + if hi > 0x80000000 or (hi == 0x80000000 and (lo > 0 or neg == "")) then + return nil, nil + end + if neg == "-" and (hi > 0 or lo > 0) then + lo = (TWO32 - lo) % TWO32 + hi = (TWO32 - 1 - hi + (if lo == 0 then 1 else 0)) % TWO32 + end + return hi, lo + end + return nil, nil +end + +local function tag(name: string, v: any): Tag + return setmetatable({ type = name, value = v }, TagMeta) :: any +end +function Value.byte(n: number): Tag + return tag("byte", n) +end +function Value.short(n: number): Tag + return tag("short", n) +end +function Value.int(n: number): number + return n +end +function Value.long(v: number | string): Tag + if type(v) == "string" then + local hi, lo = Value.toHiLo(v) + if hi then + v = Value.fromHiLo(hi, lo :: number) + end + end + return tag("long", v) +end +local f32 = buffer.create(4) +function Value.float(n: number): Tag + buffer.writef32(f32, 0, n) + return tag("float", buffer.readf32(f32, 0)) +end +function Value.double(n: number): Tag + return tag("double", n) +end +function Value.intArray(t: { number }?): Tag + return tag("intArray", t or {}) +end +function Value.longArray(t: { any } | buffer | nil): Tag + if type(t) == "buffer" then + return tag("longArray", t) + end + local list: { any } = (t or {}) :: any + local b = buffer.create(#list * 8) + for i, x in list do + local hi, lo = Value.toHiLo(x) + buffer.writeu32(b, (i - 1) * 8, lo or 0) + buffer.writeu32(b, (i - 1) * 8 + 4, hi or 0) + end + return tag("longArray", b) +end +function Value.longs(a: Tag): { number | string } + local b: buffer = a.value + local out = table.create(buffer.len(b) // 8) :: { number | string } + for i = 0, buffer.len(b) // 8 - 1 do + out[i + 1] = Value.fromHiLo(buffer.readu32(b, i * 8 + 4), buffer.readu32(b, i * 8)) + end + return out +end +function Value.list(name: string, items: { any }?): { any } + local t = items or {} + listTypes[t] = name + return t +end +function Value.compound(t: { [string]: any }?, keys: { string }?): { [string]: any } + return Types.object(t, keys) +end +function Value.listType(t: any): string? + return listTypes[t] +end +function Value.setListType(t: any, name: string) + listTypes[t] = name +end +function Value.isTag(v: any): boolean + return type(v) == "table" and getmetatable(v) == TagMeta +end + +function Value.typeOf(v: any): (string?, string?) + local tv = type(v) + if tv == "number" then + return if v % 1 == 0 and v >= -2147483648 and v <= 2147483647 then "int" else "double", nil + elseif tv == "string" then + return "string", nil + elseif tv == "boolean" then + return "byte", nil + elseif tv == "buffer" then + return "byteArray", nil + elseif tv == "table" then + if getmetatable(v) == TagMeta then + local n = v.type + if Value.IDS[n] == nil or n == "end" or n == "list" or n == "compound" or n == "string" or n == "int" or n == "byteArray" then + if n == "int" or n == "string" or n == "byteArray" then + return n, nil + end + return nil, "bad tag type " .. tostring(n) + end + return n, nil + elseif Types.isObject(v) then + return "compound", nil + elseif listTypes[v] or v[1] ~= nil or next(v) == nil then + return "list", nil + end + return "compound", nil + end + return nil, "cannot write a " .. tv .. " as NBT" +end + +function Value.number(v: any): number? + if type(v) == "number" then + return v + elseif type(v) == "boolean" then + return if v then 1 else 0 + elseif Value.isTag(v) then + local x = v.value + if type(x) == "number" then + return x + elseif type(x) == "string" then + return tonumber(x) + end + end + return nil +end + +return Value +end +__FILES["codecs/text/Text"] = function() + + +-- codecs/text/Text: text decoding helpers: BOM stripping, Windows-1252 for text that is not UTF-8, line splitting. +-- Absorbed from playlist-luau 3fc7fd3 (same author, no third-party code). +local Text = {} + +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, + [0x87] = 0x2021, [0x88] = 0x02C6, [0x89] = 0x2030, [0x8A] = 0x0160, [0x8B] = 0x2039, [0x8C] = 0x0152, + [0x8E] = 0x017D, [0x91] = 0x2018, [0x92] = 0x2019, [0x93] = 0x201C, [0x94] = 0x201D, [0x95] = 0x2022, + [0x96] = 0x2013, [0x97] = 0x2014, [0x98] = 0x02DC, [0x99] = 0x2122, [0x9A] = 0x0161, [0x9B] = 0x203A, + [0x9C] = 0x0153, [0x9E] = 0x017E, [0x9F] = 0x0178, +} + +function Text.trim(s: string): string + return (string.match(s, "^%s*(.-)%s*$") :: string) +end + +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 + +function Text.toUtf8(text: string, warnings: { string }?): string + if string.sub(text, 1, 3) == "\239\187\191" then + text = string.sub(text, 4) + end + if utf8.len(text) then + return text + end + if warnings then + table.insert(warnings, "text is not UTF-8: read as Windows-1252") + end + local out = table.create(#text) + for i = 1, #text do + local b = string.byte(text, i) + if b < 0x80 then + out[i] = string.char(b) + else + out[i] = utf8.char(if b < 0xA0 then Text.CP1252[b] or 0xFFFD else b) + end + end + return table.concat(out) +end + +function Text.lines(text: string): { string } + text = string.gsub(text, "\r\n?", "\n") + local out = {} + for line in string.gmatch(text .. "\n", "([^\n]*)\n") do + table.insert(out, line) + end + return out +end + +return Text +end +__FILES["codecs/text/Url"] = function() + + +-- codecs/text/Url: RFC 3986 reference resolution (section 5.2), local-path classification and percent-encoding. +-- Absorbed from playlist-luau 3fc7fd3 (same author, no third-party code). +local Url = {} + +type Location = { url: string, playable: boolean, reason: string?, [string]: any } + +type Parts = { + scheme: string?, + authority: string?, + path: string, + query: string?, + fragment: string?, +} + +-- RFC 3986 appendix B: the five components of a URI reference +function Url.split(ref: string): Parts + local scheme, rest = string.match(ref, "^([%a][%w+%.%-]*):(.*)$") + if not scheme then + rest = ref + end + local s = rest :: string + local fragment, query, authority + local i = string.find(s, "#", 1, true) + if i then + fragment = string.sub(s, i + 1) + s = string.sub(s, 1, i - 1) + end + i = string.find(s, "?", 1, true) + if i then + query = string.sub(s, i + 1) + s = string.sub(s, 1, i - 1) + end + if string.sub(s, 1, 2) == "//" then + local j = string.find(s, "/", 3, true) + if j then + authority = string.sub(s, 3, j - 1) + s = string.sub(s, j) + else + authority = string.sub(s, 3) + s = "" + end + end + return { scheme = scheme, authority = authority, path = s, query = query, fragment = fragment } +end + +-- RFC 3986 section 5.3 +function Url.join(p: Parts): string + local out = {} + if p.scheme then + table.insert(out, p.scheme .. ":") + end + if p.authority then + table.insert(out, "//" .. p.authority) + end + table.insert(out, p.path) + if p.query then + table.insert(out, "?" .. p.query) + end + if p.fragment then + table.insert(out, "#" .. p.fragment) + end + return table.concat(out) +end + +-- RFC 3986 section 5.2.4 +function Url.removeDotSegments(path: string): string + local input = path + local output = {} + while input ~= "" do + if string.sub(input, 1, 3) == "../" then + input = string.sub(input, 4) + elseif string.sub(input, 1, 2) == "./" then + input = string.sub(input, 3) + elseif string.sub(input, 1, 3) == "/./" then + input = string.sub(input, 3) + elseif input == "/." then + input = "/" + elseif string.sub(input, 1, 4) == "/../" then + input = string.sub(input, 4) + table.remove(output) + elseif input == "/.." then + input = "/" + table.remove(output) + elseif input == "." or input == ".." then + input = "" + else + -- move the first segment (with its leading "/", up to the next "/") to the output + local j = string.find(input, "/", 2, true) + local seg = if j then string.sub(input, 1, j - 1) else input + table.insert(output, seg) + input = string.sub(input, #seg + 1) + end + end + return table.concat(output) +end + +-- RFC 3986 section 5.2.2 (strict) +function Url.resolve(ref: string, base: string): string + local r, b = Url.split(ref), Url.split(base) + local t: Parts = { path = "" } + if r.scheme then + t.scheme, t.authority, t.path, t.query = r.scheme, r.authority, Url.removeDotSegments(r.path), r.query + else + if r.authority then + t.authority, t.path, t.query = r.authority, Url.removeDotSegments(r.path), r.query + else + if r.path == "" then + t.path = b.path + t.query = if r.query then r.query else b.query + else + if string.sub(r.path, 1, 1) == "/" then + t.path = Url.removeDotSegments(r.path) + else + -- merge (5.2.3) + local merged + if b.authority and b.path == "" then + merged = "/" .. r.path + else + local k = string.match(b.path, "^.*()/") + merged = (if k then string.sub(b.path, 1, k) else "") .. r.path + end + t.path = Url.removeDotSegments(merged) + end + t.query = r.query + end + t.authority = b.authority + end + t.scheme = b.scheme + end + t.fragment = r.fragment + return Url.join(t) +end + +-- percent-encoded: controls, space, non-ASCII, "<>\"^`{|}" and "\\"; existing %XX escapes and reserved delimiters stay +function Url.encodeUnsafe(s: string): string + return (string.gsub(s, "[%z\1-\32\127-\255<>\"%^`{|}\\]", function(c: string): string + return string.format("%%%02X", string.byte(c)) + end)) +end + +function Url.isWindowsPath(s: string): boolean + return string.match(s, "^%a:[\\/]") ~= nil + or string.match(s, "^%a:$") ~= nil + or string.sub(s, 1, 2) == "\\\\" + or string.sub(s, 1, 1) == "\\" +end + +function Url.scheme(s: string): string? + if Url.isWindowsPath(s) then + return nil + end + local scheme = string.match(s, "^([%a][%w+%.%-]*):") + return if scheme then string.lower(scheme) else nil +end + +function Url.locate(raw: string, base: string?, baseScheme: string?): Location + local loc = (string.match(raw, "^%s*(.-)%s*$") :: string) + if Url.isWindowsPath(loc) then + return { url = loc, playable = false, reason = "local path" } + end + local scheme = Url.scheme(loc) + local url = loc + if not scheme and baseScheme == "windows" and base then + local dir = string.match(base, "^(.*[\\/])") or "" + return { url = dir .. loc, playable = false, reason = "local path" } + end + if scheme then + if scheme == "http" or scheme == "https" then + url = Url.encodeUnsafe(Url.resolve(loc, loc)) + end + elseif base and baseScheme then + url = Url.resolve(Url.encodeUnsafe((string.gsub(loc, "\\", "/"))), base) + scheme = baseScheme + else + return { url = loc, playable = false, reason = "relative path without a base URL" } + end + if scheme == "http" or scheme == "https" then + return { url = url, playable = true } + elseif scheme == "file" then + return { url = url, playable = false, reason = "local path" } + end + return { url = url, playable = false, reason = "scheme " .. tostring(scheme) } +end + +function Url.base(baseUrl: string?, warnings: { string }?): (string?, string?) + if type(baseUrl) ~= "string" or baseUrl == "" then + return nil, nil + end + local s = Url.scheme(baseUrl) + if s and Url.split(baseUrl).authority ~= nil or s == "file" then + return Url.encodeUnsafe(baseUrl), s + elseif Url.isWindowsPath(baseUrl) then + return baseUrl, "windows" + end + if warnings then + table.insert(warnings, "base URL is not absolute: " .. baseUrl) + end + return nil, nil +end + +return Url +end +__FILES["codecs/text/Xml"] = function() + +-- codecs/text/Xml: XML 1.0 parse (DOM and pull events) and serialize. New code. +-- Not supported: external entities / DTDs, validation, entity values containing markup. +local Err = __include("core/Err") +local Types = __include("Types") +local Parse = __include("codecs/text/Xml/Parse") + +local Xml = {} + +type Node = Types.XmlNode +type DecodeOptions = Parse.Options & { + comments: boolean?, + cdata: boolean?, + pi: boolean?, + parents: boolean?, +} +type EncodeOptions = { + indent: (number | string)?, + declaration: boolean?, + selfClose: boolean?, +} + +local find, gsub, sub, match = string.find, string.gsub, string.sub, string.match + +local function text(src: any): (string?, Err.Err?) + if type(src) == "string" then + return src, nil + elseif type(src) == "buffer" then + return buffer.tostring(src), nil + end + return nil, Err.new(Err.ARG, "expected a string or a buffer, got " .. typeof(src)) +end + +local function errCode(msg: string, at: number, n: number): string + if find(msg, "unterminated", 1, true) or find(msg, "truncated", 1, true) or find(msg, "unclosed", 1, true) or at >= n then + return Err.TRUNCATED + elseif find(msg, "over the limit", 1, true) or find(msg, "nested deeper", 1, true) then + return Err.LIMIT + elseif find(msg, "not supported", 1, true) or find(msg, "unsupported", 1, true) then + return Err.UNSUPPORTED + end + return Err.CORRUPT +end + +function Xml.events(src: string | buffer, opts: Parse.Options?): () -> (string?, any, any, any) + local s, terr = text(src) + local u, enc = nil, "" + if s then + u, enc = Parse.toUtf8(s) + end + if not u then + local e = terr or Err.new(if find(enc, "unsupported", 1, true) then Err.UNSUPPORTED else Err.CORRUPT, enc) + local done = false + return function(): (string?, any, any, any) + if done then + return nil + end + done = true + return "error", e + end + end + local str: string = u + local nextEv = Parse.events(str, opts) + return function(): (string?, any, any, any) + local ev, a, b, c = nextEv() + if ev == "error" then + return ev, Err.new(errCode(a, b, #str), a, b) + end + return ev, a, b, c + end +end + +function Xml.decode(src: string | buffer, opts: DecodeOptions?): (Node?, Err.Err?) + local o: DecodeOptions = opts or {} + local keepComments, keepCdata, keepPi = o.comments == true, o.cdata == true, o.pi == true + local parents = o.parents ~= false + local doc: any = { name = "#document", attrs = Types.object(), children = {}, parent = nil } + local cur: any = doc + local stack = { doc } + local depth = 1 + for ev, a, b, c in Xml.events(src, o) do + if ev == "start" then + local node: any = { name = a, attrs = b, children = {}, parent = if parents then cur else nil } + if c then + node.ns = c + end + table.insert(cur.children, node) + depth += 1 + stack[depth] = node + cur = node + if depth == 2 then + doc.root = node + end + elseif ev == "end" then + stack[depth] = nil + depth -= 1 + cur = stack[depth] + elseif ev == "text" or (ev == "cdata" and not keepCdata) then + local ch = cur.children + local last = #ch + if last > 0 and type(ch[last]) == "string" then + ch[last] ..= a + else + ch[last + 1] = a + end + elseif ev == "cdata" then + table.insert(cur.children, { name = "#cdata", attrs = Types.object(), children = {}, text = a, parent = if parents then cur else nil }) + elseif ev == "comment" then + if keepComments then + table.insert(cur.children, { name = "#comment", attrs = Types.object(), children = {}, text = a, parent = if parents then cur else nil }) + end + elseif ev == "pi" then + if keepPi then + table.insert(cur.children, { name = "#pi", attrs = Types.object(), children = {}, target = a, text = b, parent = if parents then cur else nil }) + end + elseif ev == "decl" then + doc.declaration = a + elseif ev == "doctype" then + doc.doctype = { raw = a, name = b.name, publicId = b.publicId, systemId = b.systemId, entities = b.entities } + elseif ev == "error" then + return nil, a + end + end + return doc, nil +end + +function Xml.element(name: string, attrs: { [string]: string }?, children: { any }?): Node + local a = attrs or Types.object() + if not Types.isObject(a) then + local keys = {} + for k in next, a do + table.insert(keys, k) + end + table.sort(keys) + a = Types.object(a, keys) + end + local node: any = { name = name, attrs = a, children = children or {} } + for _, ch in node.children do + if type(ch) == "table" then + ch.parent = node + end + end + return node +end + +function Xml.document(root: Node, declaration: { [string]: string }?): Node + local doc: any = { name = "#document", attrs = Types.object(), children = { root }, root = root, declaration = declaration } + root.parent = doc + return doc +end + +function Xml.append(parent: Node, child: any): any + table.insert(parent.children, child) + if type(child) == "table" then + child.parent = parent + end + return child +end + +function Xml.setAttr(node: Node, name: string, value: string?) + Types.set(node.attrs, name, value) +end + +function Xml.children(node: Node, name: string?): { Node } + local out = {} + for _, ch in node.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 + table.insert(out, ch) + end + end + end + return out +end + +function Xml.child(node: Node, name: string?): Node? + for _, ch in node.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 + return ch + end + end + end + return nil +end + +function Xml.descendants(node: Node, name: string?): { Node } + local out = {} + 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 :: string, ":", 1, true) and match(ch.name, ":(.*)$") == name) then + table.insert(out, ch) + end + walk(ch) + end + end + end + walk(node) + return out +end + +function Xml.text(node: any): string + if type(node) == "string" then + return node + end + if node.name == "#cdata" then + return node.text or "" + end + local parts = {} + local function walk(n: any) + for _, ch in n.children do + if type(ch) == "string" then + table.insert(parts, ch) + elseif ch.name == "#cdata" then + table.insert(parts, ch.text or "") + elseif string.byte(ch.name) ~= 35 then + walk(ch) + end + end + end + walk(node) + return table.concat(parts) +end + +function Xml.prefix(name: string): string + return match(name, "^([^:]*):") or "" +end +function Xml.localName(name: string): string + return match(name, ":(.*)$") or name +end + +function Xml.namespace(node: Node, prefix: string?): string? + return Parse.resolve(node, prefix or Xml.prefix(node.name)) +end + +function Xml.clark(node: Node, attrName: string?): string + local name = attrName or node.name + local prefix = Xml.prefix(name) + if attrName and prefix == "" then + return name + end + local uri = Parse.resolve(node, prefix) + if uri then + return "{" .. uri .. "}" .. Xml.localName(name) + end + return name +end + +local TEXT_ESC = { ["&"] = "&amp;", ["<"] = "&lt;", [">"] = "&gt;", ["\r"] = "&#13;" } +local ATTR_ESC = { ["&"] = "&amp;", ["<"] = "&lt;", [">"] = "&gt;", ['"'] = "&quot;", ["\t"] = "&#9;", ["\n"] = "&#10;", ["\r"] = "&#13;" } + +function Xml.escape(s: string): string + return (gsub(s, "[&<>\r]", TEXT_ESC)) +end +function Xml.escapeAttr(s: string): string + return (gsub(s, '[&<>"\t\n\r]', ATTR_ESC)) +end + +local function badName(name: any): boolean + return type(name) ~= "string" or not match(name, "^[%a_:\128-\255][%w_:%.%-\128-\255]*$") +end + +function Xml.encode(node: Node, opts: EncodeOptions?): (string?, Err.Err?) + local o: EncodeOptions = opts or {} + local ind: string? = nil + if type(o.indent) == "number" then + ind = if o.indent > 0 then string.rep(" ", o.indent) else nil + elseif type(o.indent) == "string" then + ind = o.indent + end + local selfClose = o.selfClose ~= false + local out: { string } = {} + local err: string? = nil + local seen: { [any]: boolean } = {} + + local write: (n: any, depth: number) -> () + function write(n: any, depth: number) + if err then + return + end + if type(n) == "string" then + table.insert(out, Xml.escape(n)) + return + end + if type(n) ~= "table" or type(n.name) ~= "string" then + err = "a child is not a node or a string" + return + end + if seen[n] then + err = "a node appears twice (a cycle?)" + return + end + seen[n] = true + local name = n.name + if name == "#comment" then + local t = n.text or "" + if find(t, "--", 1, true) or sub(t, -1) == "-" then + err = "comment text contains '--'" + return + end + table.insert(out, "<!--" .. t .. "-->") + elseif name == "#cdata" then + table.insert(out, "<![CDATA[" .. gsub(n.text or "", "]]>", "]]]]><![CDATA[>") .. "]]>") + elseif name == "#pi" then + if badName(n.target) or find(n.text or "", "?>", 1, true) then + err = "bad processing instruction" + return + end + table.insert(out, "<?" .. n.target .. (if n.text and n.text ~= "" then " " .. n.text else "") .. "?>") + elseif name == "#doctype" then + table.insert(out, "<!DOCTYPE" .. (n.text or "") .. ">") + elseif name == "#document" then + for i, ch in n.children do + if i > 1 and ind then + table.insert(out, "\n") + end + write(ch, 0) + end + else + if badName(name) then + err = "bad element name " .. tostring(name) + return + end + table.insert(out, "<" .. name) + local attrs = n.attrs or {} + for _, k in Types.keys(attrs) do + local v = attrs[k] + if badName(k) then + err = "bad attribute name " .. tostring(k) + return + end + if type(v) == "number" or type(v) == "boolean" then + v = tostring(v) + elseif type(v) ~= "string" then + err = "attribute " .. k .. " is not a string" + return + end + table.insert(out, " " .. k .. '="' .. Xml.escapeAttr(v) .. '"') + end + local ch = n.children or {} + if #ch == 0 then + table.insert(out, if selfClose then "/>" else "></" .. name .. ">") + return + end + table.insert(out, ">") + local pretty = ind ~= nil + if pretty then + for _, c in ch do + if type(c) == "string" or c.name == "#cdata" then + pretty = false + break + end + end + end + for _, c in ch do + if pretty then + table.insert(out, "\n" .. string.rep(ind :: string, depth + 1)) + end + write(c, depth + 1) + end + if pretty then + table.insert(out, "\n" .. string.rep(ind :: string, depth)) + end + table.insert(out, "</" .. name .. ">") + end + end + + local decl = o.declaration + if decl == nil then + decl = node.name == "#document" + end + if decl then + local d: any = node.declaration or {} + table.insert(out, '<?xml version="' .. (d.version or "1.0") .. '" encoding="UTF-8"' .. (if d.standalone then ' standalone="' .. d.standalone .. '"' else "") .. "?>") + table.insert(out, "\n") + end + if node.name == "#document" and node.doctype then + local dt: any = node.doctype + local raw = dt.raw + if raw == nil then + raw = " " .. (dt.name or (if node.root then node.root.name else "root")) + if dt.publicId then + raw ..= ' PUBLIC "' .. dt.publicId .. '" "' .. (dt.systemId or "") .. '"' + elseif dt.systemId then + raw ..= ' SYSTEM "' .. dt.systemId .. '"' + end + end + table.insert(out, "<!DOCTYPE" .. raw .. ">\n") + end + write(node, 0) + if err then + return nil, Err.new(Err.ARG, err) + end + if ind and node.name == "#document" then + table.insert(out, "\n") + end + return table.concat(out), nil +end + +return Xml +end +__FILES["codecs/text/Xml/Parse"] = @native function() + + +-- codecs/text/Xml/Parse: the XML 1.0 pull parser behind codecs/text/Xml: input decoding, line-ending normalization, +-- well-formedness checks, predefined entities, character references, internal DOCTYPE entities (expansion-limited). +local Text = __include("codecs/text/Text") +local Types = __include("Types") + +local Parse = {} + +local byte, sub, find, match, char, gsub, lower = string.byte, string.sub, string.find, string.match, string.char, string.gsub, string.lower + +type Options = { + whitespace: boolean?, + namespaces: boolean?, + entities: { [string]: string }?, + maxExpansion: number?, + maxDepth: number?, +} + +local NAME = "^[%a_:\128-\255][%w_:%.%-\128-\255]*" +local PREDEF: { [string]: string } = { lt = "<", gt = ">", amp = "&", quot = '"', apos = "'" } + +local utf8char = Text.utf8char +Parse.utf8char = utf8char + +local CP1252: { [number]: number } = { + [0x80] = 0x20AC, [0x82] = 0x201A, [0x83] = 0x0192, [0x84] = 0x201E, [0x85] = 0x2026, [0x86] = 0x2020, + [0x87] = 0x2021, [0x88] = 0x02C6, [0x89] = 0x2030, [0x8A] = 0x0160, [0x8B] = 0x2039, [0x8C] = 0x0152, + [0x8E] = 0x017D, [0x91] = 0x2018, [0x92] = 0x2019, [0x93] = 0x201C, [0x94] = 0x201D, [0x95] = 0x2022, + [0x96] = 0x2013, [0x97] = 0x2014, [0x98] = 0x02DC, [0x99] = 0x2122, [0x9A] = 0x0161, [0x9B] = 0x203A, + [0x9C] = 0x0153, [0x9E] = 0x017E, [0x9F] = 0x0178, +} + +@native local function utf16(s: string, start: number, le: boolean): (string?, string?) + local out = table.create(#s // 2) + local n = 0 + local i = start + local len = #s + while i + 1 <= len do + local a, b = byte(s, i, i + 1) + local u = if le then a + b * 256 else a * 256 + b + i += 2 + if u >= 0xD800 and u <= 0xDBFF then + if i + 1 > len then + return nil, "truncated UTF-16 surrogate pair" + end + local c, d = byte(s, i, i + 1) + local lo = if le then c + d * 256 else c * 256 + d + if lo < 0xDC00 or lo > 0xDFFF then + return nil, "bad UTF-16 surrogate pair" + end + i += 2 + u = 0x10000 + (u - 0xD800) * 1024 + (lo - 0xDC00) + elseif u >= 0xDC00 and u <= 0xDFFF then + return nil, "bad UTF-16 surrogate pair" + end + n += 1 + out[n] = utf8char(u) + end + if i <= len then + return nil, "odd number of bytes in UTF-16 text" + end + return table.concat(out), nil +end + +@native function Parse.toUtf8(s: string): (string?, string) + local b1, b2, b3 = byte(s, 1, 3) + if b1 == 0xEF and b2 == 0xBB and b3 == 0xBF then + return sub(s, 4), "utf-8" + elseif b1 == 0xFF and b2 == 0xFE then + local t, e = utf16(s, 3, true) + return t, e or "utf-16le" + elseif b1 == 0xFE and b2 == 0xFF then + local t, e = utf16(s, 3, false) + return t, e or "utf-16be" + elseif b1 == 0x3C and b2 == 0 then + local t, e = utf16(s, 1, true) + return t, e or "utf-16le" + elseif b1 == 0 and b2 == 0x3C then + local t, e = utf16(s, 1, false) + return t, e or "utf-16be" + end + local decl = match(s, "^<%?xml[^>]-%?>") + local enc = if decl then match(decl, "encoding%s*=%s*[\"']([%w%._%-]+)[\"']") else nil + if enc then + local e = lower(enc) + if e == "utf-8" or e == "utf8" or e == "us-ascii" or e == "ascii" then + if find(s, "[\128-\255]") and not utf8.len(s) then + return nil, "invalid UTF-8" + end + return s, e + elseif e == "iso-8859-1" or e == "latin1" or e == "latin-1" or e == "iso8859-1" or e == "windows-1252" or e == "cp1252" then + local w = e == "windows-1252" or e == "cp1252" + return (gsub(s, "[\128-\255]", @native function(c: string): string + local v = byte(c) + return utf8char(if w then CP1252[v] or v else v) + end)), e + elseif e == "utf-16" or e == "utf-16le" or e == "utf-16be" then + return s, "utf-8" -- declared UTF-16 but read as 8-bit text: trust the bytes + end + return nil, "unsupported encoding " .. enc + end + if find(s, "[\128-\255]") and not utf8.len(s) then + return nil, "invalid UTF-8" + end + return s, "utf-8" +end + +-- the <?xml ...?> pseudo-attributes, strictly: version, then encoding?, then standalone?, each after whitespace +@native local function xmlDecl(data: string): { [string]: string }? + local p = 1 + local out: { [string]: string } = {} + for k, key in { "version", "encoding", "standalone" } do + local ws = match(data, "^[ \t\n]*()", p) :: any + local q, v, e = match(data, "^" .. key .. "[ \t\n]*=[ \t\n]*([\"'])(.-)%1()", ws) + if q then + if k > 1 and ws == p then + return nil + end + if (key == "version" and not match(v, "^1%.%d+$")) + or (key == "encoding" and not match(v, "^%a[%w%._%-]*$")) + or (key == "standalone" and v ~= "yes" and v ~= "no") + then + return nil + end + out[key] = v + p = e + elseif key == "version" then + return nil + end + end + if match(data, "^[ \t\n]*()", p) ~= #data + 1 then + return nil + end + return out +end + +@native function Parse.events(s: string, opts: Options?): () -> (string?, any, any, any) + local o: Options = opts or {} + local keepWs = o.whitespace == true + local nsOn = o.namespaces == true + local maxExp = o.maxExpansion or 1e7 + local maxDepth = o.maxDepth or 10000 + local entities: { [string]: string } = {} + if o.entities then + for k, v in o.entities do + entities[k] = v + end + end + local external: { [string]: boolean } = {} + local expanded = 0 + if find(s, "\r", 1, true) then + s = gsub(gsub(s, "\r\n", "\n"), "\r", "\n") + end + local n = #s + local i = 1 + local stack: { string } = {} + local nsStack: { { [string]: string } } = {} + local preserve: { boolean } = {} + local depth = 0 + local rootSeen = false + local rootDone = false + local dead = false + local pending: { any }? = nil + local errMsg: string? = nil + local errAt = 0 + + @native local function fail(msg: string, at: number): (string, string, number) + dead = true + return "error", msg, at - 1 + end + + local decode: (raw: string, at: number, level: number) -> string? + @native function decode(raw: string, at: number, level: number): string? + if not find(raw, "&", 1, true) then + return raw + end + local parts = {} + local np = 0 + local p = 1 + while true do + local a = find(raw, "&", p, true) + if not a then + break + end + np += 1 + parts[np] = sub(raw, p, a - 1) + local ref, e = match(raw, "^&([^;&%s<]*);()", a) + if not ref then + errMsg, errAt = "bad reference (no ';')", at + a - 1 + return nil + end + local rep: string + if byte(ref) == 35 then -- # + local cp = if byte(ref, 2) == 120 then tonumber(match(ref, "^#x(%x+)$") or "", 16) else tonumber(match(ref, "^#(%d+)$") or "") + if not cp or cp > 0x10FFFF or (cp < 0x20 and cp ~= 9 and cp ~= 10 and cp ~= 13) or (cp >= 0xD800 and cp <= 0xDFFF) or cp == 0xFFFE or cp == 0xFFFF then + errMsg, errAt = "bad character reference &" .. ref .. ";", at + a - 1 + return nil + end + rep = utf8char(cp) + else + local pre = PREDEF[ref] + if pre then + rep = pre + else + local ent = entities[ref] + if not ent then + errMsg = if external[ref] then "external entity &" .. ref .. "; not supported" else "undefined entity &" .. ref .. ";" + errAt = at + a - 1 + return nil + end + if level > 40 then + errMsg, errAt = "entity references nested too deeply (recursive?)", at + a - 1 + return nil + end + local r = decode(ent, at + a - 1, level + 1) + if not r then + return nil + end + rep = r + end + end + expanded += #rep + if expanded > maxExp then + errMsg, errAt = "entity expansion over the limit", at + a - 1 + return nil + end + np += 1 + parts[np] = rep + p = e :: any + end + np += 1 + parts[np] = sub(raw, p) + return table.concat(parts) + end + + @native local function lookupNs(prefix: string): string? + for d = depth, 1, -1 do + local m = nsStack[d] + if m and m[prefix] ~= nil then + return m[prefix] + end + end + if prefix == "xml" then + return "http://www.w3.org/XML/1998/namespace" + end + return nil + end + + @native local function literal(p: number): (string?, number) + local q = byte(s, p) + if q ~= 34 and q ~= 39 then + return nil, p + end + local e = find(s, if q == 34 then '"' else "'", p + 1, true) + if not e then + return nil, p + end + return sub(s, p + 1, e - 1), e + 1 + end + -- ExternalID: SYSTEM "sys" | PUBLIC "pub" "sys" + @native local function externalId(p: number): (string?, string?, number?) + local kw = sub(s, p, p + 5) + if kw == "SYSTEM" then + local q = match(s, "^[ \t\n]+()", p + 6) :: any + if not q then + return nil, nil, nil + end + local sys, e = literal(q) + if not sys then + 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, nil, nil + end + local pub, e = literal(q) + if not pub or find(pub, "[^ \r\n%w%-'()+,./:=?;!*#@$_%%]") then + return nil, nil, nil + end + local r = match(s, "^[ \t\n]+()", e) :: any + if not r then + return nil, nil, nil + end + local sys, e2 = literal(r) + if not sys then + return nil, nil, nil + end + return pub, sys, e2 + end + return nil, nil, nil + end + @native local function entityValue(v: string): string? + if find(v, "%", 1, true) then + return nil -- parameter-entity references are not allowed in the internal subset's markup + end + local p = 1 + local parts = {} + while true do + local a = find(v, "&", p, true) + if not a then + table.insert(parts, sub(v, p)) + break + end + table.insert(parts, sub(v, p, a - 1)) + local hex = match(v, "^&#x(%x+);", a) + local dec = match(v, "^&#(%d+);", a) + if hex or dec then + local cp = tonumber(hex or dec, if hex then 16 else 10) :: number + if cp > 0x10FFFF or (cp < 0x20 and cp ~= 9 and cp ~= 10 and cp ~= 13) or (cp >= 0xD800 and cp <= 0xDFFF) then + return nil + end + table.insert(parts, utf8char(cp)) + p = (find(v, ";", a, true) :: number) + 1 + else + local name = match(v, "^&([%a_:\128-\255][%w_:%.%-\128-\255]*);", a) + if not name then + return nil + end + table.insert(parts, "&" .. name .. ";") + p = a + #name + 2 + end + end + return table.concat(parts) + end + @native local function doctype(): (string?, any) + local start = i + local p = match(s, "^[ \t\n]+()", i) :: any + if not p then + return nil, "bad DOCTYPE" + end + local name = match(s, NAME, p) + if not name then + return nil, "bad DOCTYPE name" + end + local info: any = { name = name, entities = {} } + p += #name + local q = match(s, "^[ \t\n]*()", p) :: any + if q > p and (sub(s, q, q + 5) == "SYSTEM" or sub(s, q, q + 5) == "PUBLIC") then + local pub, sys, e = externalId(q) + if not pub then + return nil, "bad DOCTYPE external id" + end + info.publicId = if pub ~= "" then pub else nil + info.systemId = sys + q = match(s, "^[ \t\n]*()", e) :: any + end + if byte(s, q) == 91 then -- the internal subset + q += 1 + while true do + q = match(s, "^[ \t\n]*()", q) :: any + local c = byte(s, q) + if c == 93 then + q += 1 + break + elseif c == 37 then -- %name; + local pe = match(s, "^%%[%a_:\128-\255][%w_:%.%-\128-\255]*;()", q) + if not pe then + return nil, "bad parameter-entity reference" + end + q = pe :: any + elseif sub(s, q, q + 3) == "<!--" then + local e = find(s, "--", q + 4, true) + if not e or byte(s, e + 2) ~= 62 then + return nil, if e then "'--' inside a comment" else "unterminated comment in DOCTYPE" + end + q = e + 3 + elseif sub(s, q, q + 1) == "<?" then + local target = match(s, NAME, q + 2) + local e = find(s, "?>", q + 2, true) + if not target or not e or lower(target) == "xml" then + return nil, "bad processing instruction in DOCTYPE" + end + q = e + 2 + elseif sub(s, q, q + 7) == "<!ENTITY" then + local r = match(s, "^[ \t\n]+()", q + 8) :: any + if not r then + return nil, "bad ENTITY declaration" + end + local isPe = false + if byte(s, r) == 37 then + isPe = true + r = match(s, "^[ \t\n]+()", r + 1) :: any + if not r then + return nil, "bad ENTITY declaration" + end + end + local ename = match(s, NAME, r) + if not ename then + return nil, "bad ENTITY name" + end + r = match(s, "^[ \t\n]+()", r + #ename) :: any + if not r then + return nil, "bad ENTITY declaration" + end + local val, e = literal(r) + if val then + local v = entityValue(val) + if not v then + return nil, "bad ENTITY value" + end + if not isPe and entities[ename] == nil then + entities[ename] = v + info.entities[ename] = v + end + r = e + else + local pub, _, e2 = externalId(r) + if not pub then + return nil, "bad ENTITY declaration" + end + r = e2 :: number + local nd = match(s, "^[ \t\n]+NDATA[ \t\n]+()", r) + if nd then + local nn = match(s, NAME, nd) + if not nn or isPe then + return nil, "bad NDATA" + end + r = nd + #nn + end + if not isPe then + external[ename] = true + end + end + r = match(s, "^[ \t\n]*()", r) :: any + if byte(s, r) ~= 62 then + return nil, "bad ENTITY declaration" + end + q = r + 1 + elseif sub(s, q, q + 8) == "<!ELEMENT" or sub(s, q, q + 8) == "<!ATTLIST" or sub(s, q, q + 9) == "<!NOTATION" then + local kw = match(s, "^<!(%u+)", q) :: string + local r = match(s, "^[ \t\n]+()", q + 2 + #kw) :: any + if not r or not match(s, NAME, r) then + return nil, "bad " .. kw .. " declaration" + end + while true do + local c2 = byte(s, r) + if c2 == nil then + return nil, "unterminated DOCTYPE" + elseif c2 == 34 or c2 == 39 then + local e = find(s, if c2 == 34 then '"' else "'", r + 1, true) + if not e then + return nil, "unterminated DOCTYPE" + end + r = e + 1 + elseif c2 == 62 then + break + elseif c2 == 60 then + return nil, "bad " .. kw .. " declaration" + else + r += 1 + end + end + q = r + 1 + elseif c == nil then + return nil, "unterminated DOCTYPE" + else + return nil, "bad markup in the DOCTYPE" + end + end + q = match(s, "^[ \t\n]*()", q) :: any + end + if byte(s, q) ~= 62 then + return nil, if q > n then "unterminated DOCTYPE" else "bad DOCTYPE" + end + i = q + 1 + return sub(s, start, q - 1), info + end + + return @native function(): (string?, any, any, any) + if dead then + return nil + end + if pending then + local ev = pending + pending = nil + depth -= 1 + if depth == 0 then + rootDone = true + end + return "end", ev[1] + end + while true do + if i > n then + dead = true + if depth > 0 then + return "error", "unclosed element <" .. stack[depth] .. ">", n + end + if not rootSeen then + return "error", "no root element", n + end + return nil + end + local c = byte(s, i) + if c ~= 60 then -- text + local e = find(s, "<", i, true) or (n + 1) + local raw = sub(s, i, e - 1) + local start = i + i = e + local wsOnly = not find(raw, "[^ \t\n]") + if depth == 0 then + if not wsOnly then + return fail(if rootDone then "text after the root element" else "text before the root element", start) + end + else + if find(raw, "]]>", 1, true) then + return fail("']]>' in text", start + (find(raw, "]]>", 1, true) :: number) - 1) + end + local bad = find(raw, "[%z\1-\8\11\12\14-\31]") + if bad then + return fail("control character in text", start + bad - 1) + end + if not wsOnly or keepWs or preserve[depth] then + local t = decode(raw, start, 0) + if not t then + return fail(errMsg :: string, errAt) + end + return "text", t + end + end + continue + end + local c2 = byte(s, i + 1) + if c2 == 47 then -- </ + local name = match(s, NAME, i + 2) + if not name then + return fail("bad end tag", i) + end + local p = match(s, "^[ \t\n]*()", i + 2 + #name) :: any + if byte(s, p) ~= 62 then + return fail(if p > n then "unterminated end tag" else "bad end tag", p) + end + if depth == 0 or stack[depth] ~= name then + return fail("mismatched end tag </" .. name .. ">" .. (if depth > 0 then " (open: <" .. stack[depth] .. ">)" else ""), i) + end + i = p + 1 + stack[depth] = nil + nsStack[depth] = nil + preserve[depth] = nil + depth -= 1 + if depth == 0 then + rootDone = true + end + return "end", name + elseif c2 == 33 then -- <! + if sub(s, i + 2, i + 3) == "--" then + local e = find(s, "--", i + 4, true) + if not e then + return fail("unterminated comment", i) + end + if byte(s, e + 2) ~= 62 then + return fail(if e + 2 > n then "unterminated comment" else "'--' inside a comment", e) + end + local text = sub(s, i + 4, e - 1) + i = e + 3 + return "comment", text + elseif sub(s, i + 2, i + 8) == "[CDATA[" then + if depth == 0 then + return fail("CDATA outside the root element", i) + end + local e = find(s, "]]>", i + 9, true) + if not e then + return fail("unterminated CDATA section", i) + end + local text = sub(s, i + 9, e - 1) + i = e + 3 + return "cdata", text + elseif sub(s, i + 2, i + 8) == "DOCTYPE" then + if rootSeen then + return fail("DOCTYPE after the root element", i) + end + local at = i + i += 9 + local raw, info = doctype() + if not raw then + return fail(info, at) + end + return "doctype", raw, info + end + return fail("bad markup declaration", i) + elseif c2 == 63 then -- <? + local target = match(s, NAME, i + 2) + if not target then + return fail("bad processing instruction", i) + end + local e = find(s, "?>", i + 2 + #target, true) + if not e then + return fail("unterminated processing instruction", i) + end + local data = sub(s, i + 2 + #target, e - 1) + if data ~= "" and not find(data, "^[ \t\n]") then + return fail("bad processing instruction", i) + end + data = match(data, "^[ \t\n]*(.-)$") :: string + local at = i + i = e + 2 + if lower(target) == "xml" then + if target ~= "xml" or at ~= 1 then + return fail("misplaced XML declaration", at) + end + local decl = xmlDecl(data) + if not decl then + return fail("bad XML declaration", at) + end + return "decl", decl + end + return "pi", target, data + end + local name = match(s, NAME, i + 1) + if not name then + return fail(if i + 1 > n then "truncated tag" else "bad tag name", i + 1) + end + if rootDone then + return fail("a second root element <" .. name .. ">", i) + end + local at = i + local p = i + 1 + #name + local attrs = Types.object() + local order = {} + local closed = false + local nsMap: { [string]: string }? = nil + while true do + local q = match(s, "^[ \t\n]*()", p) :: any + local cc = byte(s, q) + if cc == 62 then + p = q + 1 + break + elseif cc == 47 then + if byte(s, q + 1) ~= 62 then + return fail("bad tag end", q) + end + p = q + 2 + closed = true + break + elseif cc == nil then + return fail("truncated tag", q) + end + if q == p then + return fail("missing whitespace between attributes", q) + end + local an = match(s, NAME, q) + if not an then + return fail("bad attribute name", q) + end + local r = match(s, "^[ \t\n]*=[ \t\n]*()", q + #an) :: any + if not r then + return fail("attribute " .. an .. " without a value", q) + end + local qc = byte(s, r) + if qc ~= 34 and qc ~= 39 then + return fail("unquoted attribute value", r) + end + local e = find(s, if qc == 34 then '"' else "'", r + 1, true) + if not e then + return fail("unterminated attribute value", r) + end + local raw = sub(s, r + 1, e - 1) + if find(raw, "<", 1, true) then + return fail("'<' in an attribute value", r) + end + if find(raw, "[%z\1-\8\11\12\14-\31]") then + return fail("control character in an attribute value", r) + end + local v = decode(raw, r + 1, 0) + if not v then + return fail(errMsg :: string, errAt) + end + if find(raw, "[\t\n]") then + -- XML 1.0 3.3.3 attribute-value normalization: literal tab / newline become spaces (references stay) + v = decode((gsub(raw, "[\t\n]", " ")), r + 1, 0) :: string + end + if attrs[an] ~= nil then + return fail("duplicate attribute " .. an, q) + end + attrs[an] = v + table.insert(order, an) + if nsOn then + if an == "xmlns" or sub(an, 1, 6) == "xmlns:" then + local m: { [string]: string } = nsMap or {} + nsMap = m + m[if an == "xmlns" then "" else sub(an, 7)] = v + end + end + p = e + 1 + end + Types.object(attrs, order) + i = p + depth += 1 + if depth > maxDepth then + return fail("nested deeper than " .. maxDepth, at) + end + stack[depth] = name + nsStack[depth] = nsMap :: any + local sp = attrs["xml:space"] + preserve[depth] = if sp == "preserve" then true elseif sp == "default" then false else (preserve[depth - 1] or false) + rootSeen = true + local uri: string? = nil + if nsOn then + local prefix = match(name, "^([^:]*):") or "" + uri = lookupNs(prefix) + if uri == "" then + uri = nil + end + if prefix ~= "" and uri == nil then + return fail("undeclared namespace prefix " .. prefix, at) + end + end + if closed then + stack[depth] = nil + nsStack[depth] = nil + preserve[depth] = nil + pending = { name } + end + return "start", name, attrs, uri + end + end +end + +@native function Parse.resolve(node: any, prefix: string): string? + local p = node + local key = if prefix == "" then "xmlns" else "xmlns:" .. prefix + while p do + local a = p.attrs + if a and a[key] ~= nil then + local v = a[key] + return if v == "" then nil else v + end + p = p.parent + end + if prefix == "xml" then + return "http://www.w3.org/XML/1998/namespace" + end + return nil +end + +return Parse +end +end + + + + + + codecs_video + --!optimize 2 +--!nocheck +-- rosetta chunk codecs_video (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 1 modules (0 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["codecs/video/Video/Source"] = function() + +-- codecs/video/Video/Source: what a video writer (Matroska / WebM, AVI, Y4M, MP4) gets to write, from a VideoDecoder +-- or a Demuxer: each stream is copied (remuxed) or produced (decoded frames re-encoded, PCM audio). +local Err = __include("core/Err") +local Types = __include("Types") +local Yuv = __include("codecs/image/Yuv") + +local Source = {} + +type OutPacket = { pts: number, dts: number?, duration: number, keyframe: boolean, data: buffer } +type Stream = { + kind: "video" | "audio", + codec: string, + copied: boolean, + width: number?, + height: number?, + frameRate: number?, + sampleRate: number?, + channels: number?, + bitsPerSample: number?, + config: buffer?, + track: Types.Track?, + packets: { OutPacket }, +} +type Want = { + video: { copy: { [string]: boolean }?, encode: string? }?, + audio: { copy: { [string]: boolean }?, pcm: boolean? }?, +} + +local function allows(set: { [string]: boolean }?, codec: string): boolean + return set ~= nil and (set[codec] == true or set["*"] == true) +end + +local function copyPackets(dmx: any, track: Types.Track): { OutPacket } + local out = {} + local scale = if track.timescale and track.timescale > 0 then track.timescale else 1 + local n = dmx:count(track.id) + for k = 1, n do + local p = dmx:get(track.id, k) + if p then + table.insert(out, { pts = p.pts / scale, dts = (p.dts or p.pts) / scale, duration = (p.duration or 0) / scale, keyframe = p.keyframe, data = p.data }) + end + end + return out +end + +local function trackStream(track: Types.Track, packets: { OutPacket }): Stream + return { + kind = track.kind :: any, + codec = track.codec, + copied = true, + width = track.width, + height = track.height, + frameRate = track.frameRate, + sampleRate = track.sampleRate, + channels = track.channels, + bitsPerSample = track.bitsPerSample, + config = track.config, + track = track, + packets = packets, + } +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 = __include("codecs/video/Video") + local e = Video.entry(codec) + encode = e and e.encode + if not encode then + return nil, Err.new(Err.UNSUPPORTED, "no " .. codec .. " encoder") + end + end + if type(v.reset) == "function" then + v:reset() + end + local packets: { OutPacket } = {} + local w, h = v.width, v.height + local maxFrames = opts.maxFrames or math.huge + while #packets < maxFrames do + local f, err = v:nextFrame() + if not f then + if err then + return nil, err + end + break + end + local img: Types.Image = f.image + if (w == 0 or h == 0) and #packets == 0 then + w, h = img.width, img.height + end + if img.width ~= w or img.height ~= h then + return nil, Err.new(Err.UNSUPPORTED, "frame size changes mid-stream (" .. img.width .. "x" .. img.height .. ")") + end + local data: buffer? + if codec == "rawvideo" then + local y = if img.format == "yuv420p" then img else Yuv.imageFromRgba(img, "limited", "bt601") + if not y then + return nil, Err.new(Err.UNSUPPORTED, "frame format " .. img.format) + end + data = y.pixels + else + local e2 + data, e2 = (encode :: any)(img, opts) + if not data then + return nil, e2 or Err.new(Err.ARG, "frame " .. f.index .. " failed to encode") + end + end + table.insert(packets, { pts = f.pts, duration = f.duration, keyframe = true, data = data :: buffer }) + end + if #packets == 0 then + return nil, Err.new(Err.ARG, "no frames to write") + end + local fr = v.frameRate + if not fr or fr <= 0 then + local d = packets[1].duration + fr = if d > 0 then 1 / d else 25 + end + return { + kind = "video", + codec = codec, + copied = false, + width = w, + height = h, + frameRate = fr, + packets = packets, + } :: Stream, nil +end + +local function pcmFrom(dec: any, opts: any): (Stream?, Err.Err?) + local ch, rate = dec.channels, dec.sampleRate + if type(ch) ~= "number" or ch < 1 or type(rate) ~= "number" or rate <= 0 then + return nil, Err.new(Err.ARG, "audio decoder without channels / sample rate") + end + pcall(dec.seek, dec, 0) + local chunk = opts.audioChunk or 4096 + local packets: { OutPacket } = {} + local pos = 0 + local tmp: buffer? = nil + while true do + local ok, out, n = pcall(dec.read, dec, chunk, tmp) + if not ok or not out or not n or n <= 0 then + break + end + tmp = out + local data = buffer.create(n * ch * 2) + for i = 0, n * ch - 1 do + local s = buffer.readf32(out, i * 4) + local v = math.floor(s * 32768 + 0.5) + if v > 32767 then + v = 32767 + elseif v < -32768 then + v = -32768 + elseif v ~= v then + v = 0 + end + buffer.writei16(data, i * 2, v) + end + table.insert(packets, { pts = pos / rate, duration = n / rate, keyframe = true, data = data }) + pos += n + end + return { + kind = "audio", + codec = "pcm_s16le", + copied = false, + sampleRate = rate, + channels = ch, + bitsPerSample = 16, + packets = packets, + } :: Stream, nil +end + +function Source.streams(value: any, opts: any?, want: Want): ({ Stream }?, Err.Err?) + local o = opts or {} + if type(value) ~= "table" or (value.kind ~= "video" and value.kind ~= "demuxer") then + return nil, Err.new(Err.ARG, "expected a video (VideoDecoder) or a Demuxer") + end + local dmx = if value.kind == "demuxer" then value else value.demuxer + local out: { Stream } = {} + local vt: Types.Track? = if value.kind == "video" then value.track else (dmx and dmx:track("video")) + local wv = want.video + if wv and o.video ~= false then + if vt and dmx and allows(wv.copy, vt.codec) and not o.reencode then + table.insert(out, trackStream(vt, copyPackets(dmx, vt))) + elseif value.kind == "video" and wv.encode then + local s, err = encodeFrames(value, wv.encode, o) + if not s then + return nil, err + end + table.insert(out, s) + elseif vt then + return nil, Err.new(Err.UNSUPPORTED, "cannot write " .. vt.codec .. " video" .. (if wv.encode then "" else " (this container cannot take it and it cannot be re-encoded)")) + end + end + local wa = want.audio + if wa and o.audio ~= false then + local at: Types.Track? = dmx and dmx:track("audio") + if at and dmx and allows(wa.copy, at.codec) and not o.reencodeAudio then + table.insert(out, trackStream(at, copyPackets(dmx, at))) + elseif wa.pcm and value.kind == "video" and value.audio then + local s, err = pcmFrom(value.audio, o) + if not s then + return nil, err + end + if #s.packets > 0 then + table.insert(out, s) + end + elseif at and o.audio == true then + return nil, Err.new(Err.UNSUPPORTED, "cannot write " .. at.codec .. " audio to this container") + end + end + if #out == 0 then + return nil, Err.new(Err.ARG, "nothing to write (no video or audio stream)") + end + return out, nil +end + +-- integer rates as n / 1, NTSC rates as n * 1000 / 1001, else to a millisecond +function Source.rational(fps: number): (number, number) + if fps ~= fps or fps <= 0 then + return 25, 1 + end + if math.abs(fps - math.floor(fps + 0.5)) < 1e-6 then + return math.floor(fps + 0.5), 1 + end + local ntsc = fps * 1001 / 1000 + if math.abs(ntsc - math.floor(ntsc + 0.5)) < 1e-4 then + return math.floor(ntsc + 0.5) * 1000, 1001 + end + return math.floor(fps * 1000 + 0.5), 1000 +end + +function Source.constantRate(s: Stream, maxFps: number?): (number, number, { OutPacket }) + local fd = math.huge + for _, p in s.packets do + if p.duration and p.duration > 0 and p.duration < fd then + fd = p.duration + end + end + if fd == math.huge then + fd = if s.frameRate and s.frameRate > 0 then 1 / s.frameRate else 0.04 + end + fd = math.max(fd, 1 / (maxFps or 100)) + local num, den = Source.rational(1 / fd) + local step = den / num + local out: { OutPacket } = {} + local slots = 0 + local t0 = if s.packets[1] then s.packets[1].pts else 0 + for _, p in s.packets do + local stop = p.pts - t0 + (if p.duration and p.duration > 0 then p.duration else step) + local n = math.max(1, math.floor(stop / step + 0.5) - slots) + for _ = 1, n do + table.insert(out, { pts = t0 + slots * step, duration = step, keyframe = p.keyframe, data = p.data }) + slots += 1 + end + end + return num, den, out +end + +function Source.interleave(streams: { Stream }): { { any } } + local order = {} + local pos = table.create(#streams, 1) + while true do + local best, bt = 0, math.huge + for si, s in streams do + local p = s.packets[pos[si]] + if p then + local t = p.dts or p.pts + if best == 0 or t < bt then + best, bt = si, t + end + end + end + if best == 0 then + break + end + table.insert(order, { best, streams[best].packets[pos[best]] }) + pos[best] += 1 + end + return order +end + +return Source +end +end + + + + + + containers + --!optimize 2 +--!nocheck +-- rosetta chunk containers (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 19 modules (1 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["containers/Archive"] = function() + +-- containers/Archive: the in-memory Archive value (Types.Archive) archive formats return. Entries hold their data or +-- a lazy loader; write() calls the encoder the format attached, and any Archive can be encoded by any archive writer. +-- Single-stream archives (gzip, zst, xz, bz2, br) set meta.stream = true and hold one entry; the api unwraps them +-- (a .tar.gz loads as the tar inside). Never throws: read of a missing entry or a failed loader returns nil, Err. +local Err = __include("core/Err") +local Types = __include("Types") +local Tar = __include("containers/Tar") + +local Archive = {} + +-- an entry: the Types.ArchiveEntry fields plus format extras (mode, uid, gid, link, type, ...) and its data source +type Entry = { + name: string, + size: number, + compressedSize: number?, + method: string?, + mtime: number?, + dir: boolean, + data: buffer?, + load: (() -> (buffer?, Err.Err?))?, + [string]: any, +} +type Encoder = (archive: any, opts: any?) -> (buffer?, Err.Err?) + +local Methods = {} +Methods.__index = Methods + +local function public(e: Entry): Types.ArchiveEntry + local out: any = {} + for k, v in e :: any do + if k ~= "data" and k ~= "load" then + out[k] = v + end + end + return out +end + +function Methods.list(self: any): { Types.ArchiveEntry } + local out = table.create(#self._entries) :: { Types.ArchiveEntry } + for i, e in self._entries do + out[i] = public(e) + end + return out +end + +function Methods.read(self: any, name: string): (buffer?, Err.Err?) + local e: Entry? = self._byName[name] + if not e then + return nil, Err.new(Err.ARG, "no entry named " .. tostring(name)) + end + if e.data then + return e.data, nil + end + if e.load then + local ok, b, err = pcall(e.load) + if not ok then + return nil, Err.new(Err.CORRUPT, "entry " .. name .. ": " .. tostring(b)) + end + if not b then + return nil, err or Err.new(Err.CORRUPT, "entry " .. name .. ": decode failed") + end + return b, nil + end + return buffer.create(0), nil +end + +function Methods.add(self: any, name: string, data: buffer | string, opts: any?) + local b: buffer = if type(data) == "string" then buffer.fromstring(data) elseif type(data) == "buffer" then data else buffer.create(0) + local o = opts or {} + local e: Entry = { + name = name, + size = buffer.len(b), + dir = o.dir == true, + mtime = o.mtime, + mode = o.mode, + data = b, + } + Archive.put(self, e) +end + +function Methods.write(self: any, opts: any?): (buffer?, Err.Err?) + local enc: Encoder? = self._encode + if not enc then + return nil, Err.new(Err.UNSUPPORTED, self.format .. " archives are read-only") + end + return enc(self, opts) +end + +function Archive.new(format: string, encode: Encoder?): any + return setmetatable({ + kind = "archive", + format = format, + meta = {}, + _entries = {} :: { Entry }, + _byName = {} :: { [string]: Entry }, + _encode = encode, + }, Methods) +end + +function Archive.put(a: any, e: Entry) + local old = a._byName[e.name] + if old then + local i = table.find(a._entries, old) + if i then + a._entries[i] = e + end + else + table.insert(a._entries, e) + end + a._byName[e.name] = e +end + +function Archive.entries(value: any): { { entry: Types.ArchiveEntry, read: () -> (buffer?, Err.Err?) } }? + if type(value) ~= "table" or value.kind ~= "archive" or type(value.list) ~= "function" or type(value.read) ~= "function" then + return nil + end + local ok, list = pcall(value.list, value) + if not ok or type(list) ~= "table" then + return nil + end + local out = {} + for _, e in list do + if type(e) == "table" and type(e.name) == "string" then + table.insert(out, { + entry = e, + read = function(): (buffer?, Err.Err?) + local rok, b, err = pcall(value.read, value, e.name) + if not rok then + return nil, Err.new(Err.CORRUPT, tostring(b)) + end + return b, err + end, + }) + end + end + return out +end + +function Archive.slice(buf: buffer, at: number, n: number): () -> (buffer?, Err.Err?) + return function(): (buffer?, Err.Err?) + local out = buffer.create(n) + buffer.copy(out, 0, buf, at, n) + return out, nil + end +end + +function Archive.collect(value: any): ({ { entry: Types.ArchiveEntry, data: buffer } }?, Err.Err?) + local items = Archive.entries(value) + if not items then + return nil, Err.new(Err.ARG, "expected an Archive") + end + local out: { { entry: Types.ArchiveEntry, data: buffer } } = {} + for _, it in items do + local b: buffer = buffer.create(0) + if not it.entry.dir then + local d, err = it.read() + if not d then + return nil, err or Err.new(Err.CORRUPT, "entry " .. it.entry.name .. ": read failed") + end + b = d + end + table.insert(out, { entry = it.entry, data = b }) + end + return out, nil +end + +function Archive.files(value: any, name: string?): ({ { name: string, data: buffer, entry: any } }?, Err.Err?) + if type(value) == "buffer" or type(value) == "string" then + local b = if type(value) == "string" then buffer.fromstring(value) else value + return { { name = name or "data", data = b, entry = { name = name or "data", size = buffer.len(b), dir = false } } }, nil + end + local items = Archive.entries(value) + if not items then + return nil, Err.new(Err.ARG, "expected an Archive, a buffer or a string") + end + local out = {} + for _, it in items do + if not it.entry.dir then + local b, err = it.read() + if not b then + return nil, err + end + table.insert(out, { name = it.entry.name, data = b, entry = it.entry }) + end + end + return out, nil +end + +function Archive.streamData(value: any): (buffer?, Err.Err?) + if type(value) == "buffer" then + return value, nil + elseif type(value) == "string" then + return buffer.fromstring(value), nil + end + local items = Archive.entries(value) + if not items then + return nil, Err.new(Err.ARG, "expected an Archive, a buffer or a string") + end + if #items == 1 and not items[1].entry.dir then + return items[1].read() + end + local list = {} + for _, it in items do + local e: any = it.entry + local data: buffer? = nil + if not e.dir and (e.type == nil or e.type == "0") then + local b, err = it.read() + if not b then + return nil, err + end + data = b + end + local typ = if type(e.type) == "string" and #e.type == 1 then e.type else nil + table.insert(list, { name = e.name, data = data, dir = e.dir, type = typ, link = e.link, mtime = e.mtime, mode = e.mode }) + end + return Tar.write(list) +end + +-- MS-DOS date / time: stamp = date * 65536 + time (LHA / ARJ / ZIP); local time without a zone, read as UTC +function Archive.fromDos(stamp: number): number? + local time, date = stamp % 65536, stamp // 65536 + local y, m, d = 1980 + bit32.rshift(date, 9), bit32.band(bit32.rshift(date, 5), 15), bit32.band(date, 31) + if date == 0 or m < 1 or m > 12 or d < 1 then + return nil + end + local secs = bit32.rshift(time, 11) * 3600 + bit32.band(bit32.rshift(time, 5), 63) * 60 + bit32.band(time, 31) * 2 + return Types.Date.daysFromCivil(y, m, d) * 86400 + secs +end + +-- MS-DOS dates cover 1980-01-01 .. 2107-12-31 +function Archive.toDos(t: number?): number + if type(t) ~= "number" or t ~= t or t < 315532800 then + return 0x210000 -- 1980-01-01 00:00 + end + local s = math.floor(t) + local days = s // 86400 + local rem = s - days * 86400 + local y, m, d = Types.Date.civilFromDays(days) + if y > 2107 then + y, m, d, rem = 2107, 12, 31, 86398 + end + return ((y - 1980) * 512 + m * 32 + d) * 65536 + (rem // 3600) * 2048 + ((rem // 60) % 60) * 32 + (rem % 60) // 2 +end + +function Archive.streamName(opts: any?, exts: { string }): string + local name = if type(opts) == "table" and type(opts.name) == "string" then opts.name else nil + if not name then + return "data" + end + local base = string.match(name, "([^/\\]+)$") or name + local stem, ext = string.match(base, "^(.+)%.([%w]+)$") + if stem and ext then + local e = string.lower(ext) + if e == "tgz" or e == "tbz2" or e == "tbz" or e == "txz" or e == "tzst" then + return stem .. ".tar" + end + if table.find(exts, e) then + return stem + end + end + return base +end + +return Archive +end +__FILES["containers/Avi"] = function() + +-- containers/Avi: the AVI RIFF form (Microsoft AVI 1.0 + OpenDML 1.02), read and written. New in rosetta. The chunk +-- index comes from the OpenDML super index (indx -> ix##), else idx1 (movi-relative or absolute, detected), else a +-- scan of the movi lists. Writing: AVI 1.0 (avih, strl, LIST movi, idx1) with an odml / dmlh header. +-- Never throws: malformed data returns nil, Err (a damaged index falls back to scanning). +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") + +local readu8, readu16, readu32, readstring = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readstring + +local Avi = {} + +type Chunk = { offset: number, size: number, key: boolean } +type Stream = { + index: number, -- 0-based stream number (the "##" of the chunk ids) + type: string, -- strh fccType: "vids", "auds", "txts", "mids" + handler: string, + flags: number, + scale: number, + rate: number, + start: number, + length: number, + suggestedBufferSize: number, + sampleSize: number, + frame: { number }, -- rcFrame left, top, right, bottom + strf: buffer, -- the format block (BITMAPINFOHEADER / WAVEFORMATEX ...) + name: string?, + chunks: { Chunk }, +} +type File = { + avih: { microSecPerFrame: number, flags: number, totalFrames: number, streams: number, width: number, height: number }, + streams: { Stream }, + odml: { totalFrames: number }?, + info: { [string]: string }, + index: string, -- "odml" | "idx1" | "scan" +} + +local function u32(b: buffer, o: number): number + return readu32(b, o) +end + +local function walk(b: buffer, p: number, limit: number, fn: (id: string, data: number, size: number, ltype: string?) -> boolean?): number + while p + 8 <= limit do + local id = readstring(b, p, 4) + local size = u32(b, p + 4) + local data = p + 8 + local ltype: string? = nil + if (id == "LIST" or id == "RIFF") and data + 4 <= limit then + ltype = readstring(b, data, 4) + end + if data + size > limit then + size = limit - data + end + if fn(id, data, size, ltype) == false then + return p + end + p = data + size + (size % 2) + end + return p +end + +local function streamNumber(id: string): number? + local a, b = string.byte(id, 1, 2) + if not a or not b then + return nil + end + local function hex(c: number): number? + if c >= 48 and c <= 57 then + return c - 48 + elseif c >= 65 and c <= 70 then + return c - 55 + elseif c >= 97 and c <= 102 then + return c - 87 + end + return nil + end + local h, l = hex(a), hex(b) + if h and l then + return h * 16 + l + end + return nil +end +Avi.streamNumber = streamNumber + +local function parseStrl(b: buffer, data: number, size: number, index: number): Stream + local s: Stream = { + index = index, + type = "", + handler = "", + flags = 0, + scale = 1, + rate = 1, + start = 0, + length = 0, + suggestedBufferSize = 0, + sampleSize = 0, + frame = { 0, 0, 0, 0 }, + strf = buffer.create(0), + chunks = {}, + } + local indx: { number }? = nil + walk(b, data + 4, data + size, function(id: string, d: number, n: number): boolean? + if id == "strh" and n >= 48 then + s.type = readstring(b, d, 4) + s.handler = readstring(b, d + 4, 4) + s.flags = u32(b, d + 8) + s.scale = u32(b, d + 20) + s.rate = u32(b, d + 24) + s.start = u32(b, d + 28) + s.length = u32(b, d + 32) + s.suggestedBufferSize = u32(b, d + 36) + s.sampleSize = u32(b, d + 44) + if n >= 56 then + s.frame = { buffer.readi16(b, d + 48), buffer.readi16(b, d + 50), buffer.readi16(b, d + 52), buffer.readi16(b, d + 54) } + end + elseif id == "strf" then + local f = buffer.create(n) + buffer.copy(f, 0, b, d, n) + s.strf = f + elseif id == "strn" then + local str = readstring(b, d, n) + s.name = string.match(str, "^[^%z]*") + elseif id == "indx" and n >= 24 then + indx = { d, n } + end + return nil + end) + ;(s :: any)._indx = indx + return s +end + +-- an OpenDML index chunk (indx super index or ix## standard index) at d with n bytes: appends chunks to s +local function readIndex(b: buffer, d: number, n: number, s: Stream, limit: number, depth: number): boolean + if n < 24 or depth > 2 then + return false + end + local longsPerEntry = readu16(b, d) + local subType = readu8(b, d + 2) + local indexType = readu8(b, d + 3) + local entries = u32(b, d + 4) + if indexType == 0 then -- AVI_INDEX_OF_INDEXES: { qwOffset, dwSize, dwDuration } + if longsPerEntry ~= 4 then + return false + end + local p = d + 24 + for _ = 1, entries do + if p + 16 > d + n then + break + end + local off = u32(b, p) + u32(b, p + 4) * 4294967296 + local size = u32(b, p + 8) + p += 16 + if off > 0 and off + 8 <= limit then + local sz = math.min(u32(b, off + 4), limit - off - 8) + readIndex(b, off + 8, if size > 0 then math.min(sz, size) else sz, s, limit, depth + 1) + end + end + return #s.chunks > 0 + elseif indexType == 1 then -- AVI_INDEX_OF_CHUNKS: base offset, { dwOffset, dwSize } (or field index: 3 longs) + if n < 24 then + return false + end + local base = u32(b, d + 12) + u32(b, d + 16) * 4294967296 + local per = if subType == 1 then 12 else 8 -- AVI_INDEX_2FIELD + local p = d + 24 + for _ = 1, entries do + if p + per > d + n then + break + end + local off = u32(b, p) + local size = u32(b, p + 4) + p += per + local key = size < 0x80000000 + size %= 0x80000000 + local at = base + off + if at >= 0 and at + size <= limit then + table.insert(s.chunks, { offset = at, size = size, key = key }) + end + end + return true + end + return false +end + +function Avi.read(b: buffer, base: number, limit: number): (File?, Err.Err?) + if limit - base < 12 or readstring(b, base, 4) ~= "RIFF" or readstring(b, base + 8, 4) ~= "AVI " then + return nil, Err.new(Err.CORRUPT, "not an AVI file", base) + end + local file: File = { + avih = { microSecPerFrame = 0, flags = 0, totalFrames = 0, streams = 0, width = 0, height = 0 }, + streams = {}, + odml = nil, + info = {}, + index = "scan", + } + local movis: { { number } } = {} -- { data offset of the 'movi' fourcc, end } + local idx1: { number }? = nil + local hdrl = false + -- every RIFF piece (AVI, then AVIX for OpenDML files) + walk(b, base, limit, function(id: string, d: number, n: number, ltype: string?): boolean? + if id ~= "RIFF" then + return nil + end + walk(b, d + 4, d + n, function(cid: string, cd: number, cn: number, cltype: string?): boolean? + if cid == "LIST" and cltype == "hdrl" and not hdrl then + hdrl = true + local si = 0 + walk(b, cd + 4, cd + cn, function(hid: string, hd: number, hn: number, hltype: string?): boolean? + if hid == "avih" and hn >= 40 then + file.avih = { + microSecPerFrame = u32(b, hd), + flags = u32(b, hd + 12), + totalFrames = u32(b, hd + 16), + streams = u32(b, hd + 24), + width = u32(b, hd + 32), + height = u32(b, hd + 36), + } + elseif hid == "LIST" and hltype == "strl" then + table.insert(file.streams, parseStrl(b, hd, hn, si)) + si += 1 + elseif hid == "LIST" and hltype == "odml" then + walk(b, hd + 4, hd + hn, function(oid: string, od: number, on: number): boolean? + if oid == "dmlh" and on >= 4 then + file.odml = { totalFrames = u32(b, od) } + end + return nil + end) + end + return nil + end) + elseif cid == "LIST" and cltype == "movi" then + table.insert(movis, { cd, cd + cn }) + elseif cid == "LIST" and cltype == "INFO" then + walk(b, cd + 4, cd + cn, function(iid: string, idd: number, inn: number): boolean? + file.info[iid] = string.match(readstring(b, idd, inn), "^[^%z]*") or "" + return nil + end) + elseif cid == "idx1" and not idx1 then + idx1 = { cd, cn } + end + return nil + end) + return nil + end) + if not hdrl then + return nil, Err.new(Err.CORRUPT, "no hdrl list") + end + if #file.streams == 0 then + return nil, Err.new(Err.CORRUPT, "no streams") + end + -- 1. OpenDML indexes + local odml = true + for _, s in file.streams do + local ix = (s :: any)._indx + if not ix or not readIndex(b, ix[1], ix[2], s, limit, 0) then + odml = false + end + end + if odml then + file.index = "odml" + else + for _, s in file.streams do + table.clear(s.chunks) + end + -- 2. idx1 + local ok = false + if idx1 and movis[1] then + local d, n = idx1[1], idx1[2] + local count = n // 16 + local moviBase = movis[1][1] -- the 'movi' fourcc + -- relative or absolute offsets: check the first entry that points at a chunk id + local rel = true + if count > 0 then + local off = u32(b, d + 8) + local ckid = readstring(b, d, 4) + local relAt, absAt = moviBase + off, base + off + if relAt + 4 <= limit and readstring(b, relAt, 4) == ckid then + rel = true + elseif absAt + 4 <= limit and readstring(b, absAt, 4) == ckid then + rel = false + end + end + for k = 0, count - 1 do + local e = d + k * 16 + local ckid = readstring(b, e, 4) + local flags = u32(b, e + 4) + local off = u32(b, e + 8) + local size = u32(b, e + 12) + local sn = streamNumber(ckid) + local s = sn and file.streams[sn + 1] + if s and string.sub(ckid, 3, 4) ~= "pc" then + local at = (if rel then moviBase else base) + off + 8 + if at + size <= limit then + table.insert(s.chunks, { offset = at, size = size, key = bit32.band(flags, 0x10) ~= 0 }) + ok = true + end + end + end + end + if ok then + file.index = "idx1" + else + for _, s in file.streams do + table.clear(s.chunks) + end + -- 3. scan the movi lists + local function scan(d0: number, e0: number) + walk(b, d0, e0, function(id: string, d: number, n: number, ltype: string?): boolean? + if id == "LIST" and ltype == "rec " then + scan(d + 4, d + n) + return nil + end + local sn = streamNumber(id) + local s = sn and file.streams[sn + 1] + if s and string.sub(id, 1, 2) ~= "ix" and string.sub(id, 3, 4) ~= "pc" then + table.insert(s.chunks, { offset = d, size = n, key = true }) + end + return nil + end) + end + for _, m in movis do + scan(m[1] + 4, m[2]) + end + file.index = "scan" + end + end + for _, s in file.streams do + (s :: any)._indx = nil + end + return file, nil +end + +type WStream = { + type: string, -- "vids" | "auds" + handler: string, -- fccHandler (4 chars) + scale: number, + rate: number, + sampleSize: number, -- 0 = every chunk one sample (video, VBR audio) + strf: buffer, + name: string?, + width: number?, + height: number?, + quality: number?, + ckid: string?, -- the chunk id suffix: "dc" (video), "wb" (audio) +} +type WOptions = { + streams: { WStream }, + microSecPerFrame: number, + width: number, + height: number, + software: string?, +} + +function Avi.write(opts: WOptions, chunks: { { any } }): buffer + local ns = #opts.streams + local lengths = table.create(ns, 0) + local maxChunk = table.create(ns, 0) + local bytes = table.create(ns, 0) + local total = 0 + for _, c in chunks do + local si, data = c[1], c[2] + local n = buffer.len(data) + local s = opts.streams[si] + if s.sampleSize > 0 then + lengths[si] += n // s.sampleSize + else + lengths[si] += 1 + end + bytes[si] += n + if n > maxChunk[si] then + maxChunk[si] = n + end + total += n + 8 + (n % 2) + end + local frames = 0 + for si, s in opts.streams do + if s.type == "vids" and frames == 0 then + frames = lengths[si] + end + end + local w = Bytes.writer(total + 4096 + #chunks * 16) + w:string("RIFF") + local riffSize = w:tell() + w:u32le(0) + w:string("AVI ") + w:string("LIST") + local hdrlSize = w:tell() + w:u32le(0) + w:string("hdrl") + w:string("avih") + w:u32le(56) + local duration = if opts.microSecPerFrame > 0 then frames * opts.microSecPerFrame / 1e6 else 1 + local maxBytes = 0 + for si = 1, ns do + maxBytes += bytes[si] + end + w:u32le(math.floor(opts.microSecPerFrame + 0.5)) + w:u32le(if duration > 0 then math.floor(maxBytes / duration) else 0) + w:u32le(0) -- padding granularity + w:u32le(0x10 + 0x100) -- AVIF_HASINDEX | AVIF_ISINTERLEAVED + w:u32le(frames) + w:u32le(0) -- initial frames + w:u32le(ns) + local suggested = 0 + for si = 1, ns do + suggested = math.max(suggested, maxChunk[si] + 8) + end + w:u32le(suggested) + w:u32le(opts.width) + w:u32le(opts.height) + for _ = 1, 4 do + w:u32le(0) + end + for si, s in opts.streams do + w:string("LIST") + local strlSize = w:tell() + w:u32le(0) + w:string("strl") + w:string("strh") + w:u32le(56) + w:string(s.type) + w:string(s.handler) + w:u32le(0) -- flags + w:u16le(0) -- priority + w:u16le(0) -- language + w:u32le(0) -- initial frames + w:u32le(s.scale) + w:u32le(s.rate) + w:u32le(0) -- start + w:u32le(lengths[si]) + w:u32le(maxChunk[si]) + w:u32le(if s.quality then s.quality else 0xFFFFFFFF) + w:u32le(s.sampleSize) + w:u16le(0) + w:u16le(0) + w:u16le(s.width or 0) + w:u16le(s.height or 0) + w:string("strf") + w:u32le(buffer.len(s.strf)) + w:bytes(s.strf) + if buffer.len(s.strf) % 2 == 1 then + w:u8(0) + end + if s.name then + local nm = s.name .. "\0" + w:string("strn") + w:u32le(#nm) + w:string(nm) + if #nm % 2 == 1 then + w:u8(0) + end + end + w:setU32le(strlSize, w:tell() - strlSize - 4) + end + -- OpenDML extended header (total frames) + w:string("LIST") + w:u32le(16) + w:string("odml") + w:string("dmlh") + w:u32le(4) + w:u32le(frames) + w:setU32le(hdrlSize, w:tell() - hdrlSize - 4) + local sw = (opts.software or "rosetta") .. "\0" + if #sw % 2 == 1 then + sw ..= "\0" + end + w:string("LIST") + w:u32le(4 + 8 + #sw) + w:string("INFO") + w:string("ISFT") + w:u32le(#sw) + w:string(sw) + w:string("LIST") + local moviSize = w:tell() + w:u32le(0) + local moviBase = w:tell() + w:string("movi") + local index = table.create(#chunks) :: { { any } } + for _, c in chunks do + local si, data, key = c[1], c[2], c[3] + local s = opts.streams[si] + local id = string.format("%02d", si - 1) .. (s.ckid or (if s.type == "vids" then "dc" else "wb")) + local at = w:tell() + local n = buffer.len(data) + w:string(id) + w:u32le(n) + w:bytes(data) + if n % 2 == 1 then + w:u8(0) + end + table.insert(index, { id, if key then 0x10 else 0, at - moviBase, n }) + end + w:setU32le(moviSize, w:tell() - moviSize - 4) + w:string("idx1") + w:u32le(#index * 16) + for _, e in index do + w:string(e[1]) + w:u32le(e[2]) + w:u32le(e[3]) + w:u32le(e[4]) + end + w:setU32le(riffSize, w:tell() - 8) + return w:finish() +end + +type BitmapInfo = { + width: number, + height: number, -- signed: > 0 = bottom-up rows + bits: number, -- biBitCount + compression: string, -- biCompression as a FourCC ("\0\0\0\0" = BI_RGB) + palette: buffer?, -- bits <= 8: 256 u32 entries, bytes R, G, B, 0xFF (codecs/image/Pixels layout); unused ones 0 + extra: buffer?, -- the bytes after the 40-byte header (palette included), nil when none +} + +-- BITMAPINFOHEADER: the palette is the last (2^bits) * 4 bytes after the header (B, G, R, x; a trailing "BottomUp" +-- tag skipped), as the VfW codecs store it +function Avi.bitmapInfo(f: buffer): BitmapInfo? + local n = buffer.len(f) + if n < 40 then + return nil + end + local bits = readu16(f, 14) + local info: BitmapInfo = { + width = buffer.readi32(f, 4), + height = buffer.readi32(f, 8), + bits = bits, + compression = readstring(f, 16, 4), + } + if n > 40 then + local e = buffer.create(n - 40) + buffer.copy(e, 0, f, 40) + info.extra = e + if bits >= 1 and bits <= 8 then + local count = math.min(2 ^ bits, (n - 40) // 4) + local at = n - count * 4 + if at - 40 >= 9 and readstring(f, n - 9, 9) == "BottomUp\0" then + at -= 9 + end + local pal = buffer.create(1024) + for i = 0, count - 1 do + local o = at + i * 4 + buffer.writeu32(pal, i * 4, readu8(f, o + 2) + readu8(f, o + 1) * 256 + readu8(f, o) * 65536 + 0xFF000000) + end + info.palette = pal + end + end + return info +end + +return Avi +end +__FILES["containers/Chunks"] = function() + +-- containers/Chunks: the generic walker for chunked files (an id and a size per chunk, body, optional trailer and +-- padding): RIFF / RIFX / RF64, IFF / AIFF / AIFC, PNG (size first, CRC trailer), CAF (64-bit sizes). New in rosetta +-- (the RIFF leniency comes from containers/Riff, absorbed from wav-luau). +-- A chunk declared past the end keeps what is there (avail < size, truncated = true) and ends the walk; ids in +-- layout.openEnded with a size of 0 / 0xFFFFFFFF / past the end run to the end of the data (streamed writers). +-- layout.lenientPad: an odd-sized chunk written without its pad byte is detected (the next id is printable only one +-- byte earlier). layout.resize(id, declared) can replace a declared size (RF64's ds64). Never throws. +local Chunks = {} + +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 +} + +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 + +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 + +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 +end +__FILES["containers/Cpio"] = function() + +-- containers/Cpio: cpio, read and written, from cpio(5) (libarchive, GNU cpio) and POSIX.1-1988 (odc). Reads newc +-- (070701), crc (070702, byte sums verified), odc (070707), old binary in both byte orders; writes newc / crc / odc +-- padded to opts.block (512, as GNU cpio). A hard link group's data sits on its last link (as GNU cpio and bsdtar). +-- Never throws: bad data returns nil, Err. +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") + +local Cpio = {} + +type Entry = { + name: string, + size: number, -- data bytes (a symlink's target length; a hard link: the shared data's size) + mode: number, -- the whole st_mode (file type bits included) + type: string, -- tar type letters: "0" file, "5" directory, "2" symlink, "3" char device, "4" block device, "6" fifo, "s" socket + dir: boolean, + uid: number, + gid: number, + nlink: number, + mtime: number, + ino: number, + devmajor: number, + devminor: number, + rdevmajor: number, + rdevminor: number, + link: string?, -- symlink target + hardlink: string?, -- the first entry of this entry's hard link group (for the later links) + offset: number, -- absolute offset of the data in the buffer + check: number?, -- crc format: the stored byte sum +} +type ReadOptions = { + maxEntries: number?, -- default 1e6 + verify: boolean?, -- crc format: check the byte sums (default true) +} +type Info = { format: string } -- "newc" | "crc" | "odc" | "bin" | "binbe" + +local S_IFMT = 0xF000 +local TYPES: { [number]: string } = { + [0x8000] = "0", + [0x4000] = "5", + [0xA000] = "2", + [0x2000] = "3", + [0x6000] = "4", + [0x1000] = "6", + [0xC000] = "s", +} +local MODES: { [string]: number } = {} +for m, t in TYPES do + MODES[t] = m +end +Cpio.TYPE_MODE = MODES -- type letter -> S_IFMT bits +Cpio.TYPE_OF = TYPES -- S_IFMT bits -> type letter + +local TRAILER = "TRAILER!!!" + +function Cpio.format(b: buffer, o: number): string? + local n = buffer.len(b) + if o + 6 <= n then + local m = buffer.readstring(b, o, 6) + if m == "070701" then + return "newc" + elseif m == "070702" then + return "crc" + elseif m == "070707" then + return "odc" + end + end + if o + 2 <= n then + local v = buffer.readu16(b, o) + if v == 0x71C7 then + return "bin" + elseif v == 0xC771 then + return "binbe" + end + end + return nil +end + +-- a fixed-width number field: hex (newc) or octal (odc); nil when not all digits +local function num(b: buffer, o: number, n: number, base: number): number? + local s = buffer.readstring(b, o, n) + if base == 16 then + if not string.find(s, "^%x+$") then + return nil + end + elseif not string.find(s, "^[0-7]+$") then + return nil + end + return tonumber(s, base) +end + +-- the crc format's checksum: the sum of the data bytes mod 2^32 +function Cpio.checksum(b: buffer, o: number, n: number): number + local s = 0 + local i = o + local e = o + n + while i + 4 <= e do + local v = buffer.readu32(b, i) + s += bit32.band(v, 255) + bit32.band(bit32.rshift(v, 8), 255) + bit32.band(bit32.rshift(v, 16), 255) + bit32.rshift(v, 24) + i += 4 + end + while i < e do + s += buffer.readu8(b, i) + i += 1 + end + return s % 4294967296 +end + +local function header(b: buffer, p: number, e: number, fmt: string): (any, Err.Err?) + local h: any = {} + local nameAt + if fmt == "newc" or fmt == "crc" then + if p + 110 > e then + return nil, Err.new(Err.TRUNCATED, "header past the end", p) + end + local f = {} :: { number } + for i = 1, 13 do + local v = num(b, p + 6 + (i - 1) * 8, 8, 16) + if not v then + return nil, Err.new(Err.CORRUPT, "bad header field", p + 6 + (i - 1) * 8) + end + f[i] = v + end + h.ino, h.mode, h.uid, h.gid, h.nlink, h.mtime, h.size = f[1], f[2], f[3], f[4], f[5], f[6], f[7] + h.devmajor, h.devminor, h.rdevmajor, h.rdevminor, h.namesize, h.check = f[8], f[9], f[10], f[11], f[12], f[13] + nameAt = p + 110 + elseif fmt == "odc" then + if p + 76 > e then + return nil, Err.new(Err.TRUNCATED, "header past the end", p) + end + local widths = { 6, 6, 6, 6, 6, 6, 6, 11, 6, 11 } + local f = {} :: { number } + local q = p + 6 + for i, w in widths do + local v = num(b, q, w, 8) + if not v then + return nil, Err.new(Err.CORRUPT, "bad header field", q) + end + f[i] = v + q += w + end + h.ino, h.mode, h.uid, h.gid, h.nlink, h.mtime, h.namesize, h.size = f[2], f[3], f[4], f[5], f[6], f[8], f[9], f[10] + h.devmajor, h.devminor = bit32.rshift(f[1], 8), bit32.band(f[1], 255) + h.rdevmajor, h.rdevminor = bit32.rshift(f[7], 8), bit32.band(f[7], 255) + nameAt = p + 76 + else + if p + 26 > e then + return nil, Err.new(Err.TRUNCATED, "header past the end", p) + end + local be = fmt == "binbe" + local function u16(i: number): number + local v = buffer.readu16(b, p + i * 2) + return if be then bit32.bor(bit32.rshift(v, 8), bit32.band(bit32.lshift(v, 8), 0xFF00)) else v + end + local dev, rdev = u16(1), u16(7) + h.ino, h.mode, h.uid, h.gid, h.nlink = u16(2), u16(3), u16(4), u16(5), u16(6) + h.mtime = u16(8) * 65536 + u16(9) + h.namesize = u16(10) + h.size = u16(11) * 65536 + u16(12) + h.devmajor, h.devminor = bit32.rshift(dev, 8), bit32.band(dev, 255) + h.rdevmajor, h.rdevminor = bit32.rshift(rdev, 8), bit32.band(rdev, 255) + nameAt = p + 26 + end + if h.namesize < 1 or nameAt + h.namesize > e then + return nil, Err.new(if h.namesize < 1 then Err.CORRUPT else Err.TRUNCATED, "bad name size", nameAt) + end + h.nameAt = nameAt + return h, nil +end + +function Cpio.read(b: buffer, offset: number?, length: number?, opts: ReadOptions?): ({ Entry }?, any) + local o = offset or 0 + local e = math.min(buffer.len(b), o + (length or (buffer.len(b) - o))) + local maxEntries = (opts and opts.maxEntries) or 1e6 + local verify = not (opts and opts.verify == false) + local fmt = Cpio.format(b, o) + if not fmt or o >= e then + return nil, Err.new(Err.CORRUPT, "not a cpio archive", o) + end + local align = if fmt == "newc" or fmt == "crc" then 4 elseif fmt == "odc" then 1 else 2 + local out: { Entry } = {} + local groups: { [string]: { Entry } } = {} + local p = o + while true do + if p >= e then + return nil, Err.new(Err.TRUNCATED, "no TRAILER!!! entry", p) + end + if Cpio.format(b, p) ~= fmt then + return nil, Err.new(Err.CORRUPT, "bad header magic", p) + end + local h, herr = header(b, p, e, fmt) + if not h then + return nil, herr + end + local name = buffer.readstring(b, h.nameAt, h.namesize) + local z = string.find(name, "\0", 1, true) + if z then + name = string.sub(name, 1, z - 1) + end + local data = h.nameAt + h.namesize + data = o + (data - o + align - 1) // align * align + if name == TRAILER then + break + end + if data + h.size > e then + return nil, Err.new(Err.TRUNCATED, "entry " .. name .. " data past the end", data) + end + local typ = TYPES[bit32.band(h.mode, S_IFMT)] or "0" + local entry: Entry = { + name = name, + size = h.size, + mode = h.mode, + type = typ, + dir = typ == "5", + uid = h.uid, + gid = h.gid, + nlink = h.nlink, + mtime = h.mtime, + ino = h.ino, + devmajor = h.devmajor, + devminor = h.devminor, + rdevmajor = h.rdevmajor, + rdevminor = h.rdevminor, + link = if typ == "2" then buffer.readstring(b, data, h.size) else nil, + hardlink = nil, + offset = data, + check = if fmt == "crc" then h.check else nil, + } + if fmt == "crc" and verify and typ == "0" and Cpio.checksum(b, data, h.size) ~= h.check then + return nil, Err.new(Err.CHECKSUM, "entry " .. name .. ": data checksum mismatch", data) + end + if typ == "0" and h.nlink > 1 then + local key = h.devmajor .. ":" .. h.devminor .. ":" .. h.ino + local g = groups[key] + if not g then + g = {} + groups[key] = g + else + entry.hardlink = g[1].name + end + table.insert(g, entry) + end + table.insert(out, entry) + if #out > maxEntries then + return nil, Err.new(Err.LIMIT, "more than " .. maxEntries .. " entries") + end + p = data + h.size + p = o + (p - o + align - 1) // align * align + end + -- hard links: the links stored without data read the group's data (newc / crc keep it on the last link) + for _, g in groups do + local holder: Entry? = nil + for _, x in g do + if x.size > 0 then + holder = x + end + end + if holder then + for _, x in g do + if x.size == 0 then + x.size, x.offset = holder.size, holder.offset + end + end + end + end + return out, { format = fmt } +end + +type WriteEntry = { + name: string, + data: buffer?, -- file data (a symlink: its target, else taken from link) + mode: number?, -- st_mode; permission bits alone get the type bits from type / dir (default 0o644 / 0o755) + type: string?, -- a type letter (see Entry.type); default "0" ("5" for dir) + dir: boolean?, + link: string?, -- symlink target + uid: number?, + gid: number?, + nlink: number?, -- default 1 (2 for directories) + mtime: number?, -- unix seconds (default 0) + ino: number?, -- default: the entry's index (1, 2, ...); hard links share one + devmajor: number?, + devminor: number?, + rdevmajor: number?, + rdevminor: number?, +} +type WriteOptions = { + format: ("newc" | "crc" | "odc")?, -- default "newc" + block: number?, -- pad the archive to a multiple of this many bytes (default 512; 1 = no padding) +} + +local function hex8(v: number): string? + if v < 0 or v % 1 ~= 0 or v >= 4294967296 then + return nil + end + return string.format("%08X", v) +end + +local function oct(v: number, w: number): string? + if v < 0 or v % 1 ~= 0 or v >= 8 ^ w then + return nil + end + local s = string.format("%o", v) + return string.rep("0", w - #s) .. s +end + +function Cpio.write(entries: { WriteEntry }, opts: WriteOptions?): (buffer?, Err.Err?) + local fmt = (opts and opts.format) or "newc" + if fmt ~= "newc" and fmt ~= "crc" and fmt ~= "odc" then + return nil, Err.new(Err.ARG, "format must be newc, crc or odc") + end + local block = (opts and opts.block) or 512 + if type(block) ~= "number" or block < 1 or block % 1 ~= 0 then + return nil, Err.new(Err.ARG, "block must be a positive integer") + end + -- newc / crc: a hard link group's data goes on its last link only + local last: { [string]: number } = {} + local prepared: { any } = table.create(#entries) + for i, e in entries do + if type(e) ~= "table" or type(e.name) ~= "string" or e.name == "" then + return nil, Err.new(Err.ARG, "entry " .. i .. ": needs a name") + end + local typ = e.type or (if e.dir then "5" else "0") + local tbits = MODES[typ] + if not tbits then + return nil, Err.new(Err.ARG, "entry " .. e.name .. ": unknown type " .. tostring(typ)) + end + local mode = e.mode or (if typ == "5" then 0x1ED elseif typ == "2" then 0x1FF else 0x1A4) + if bit32.band(mode, S_IFMT) == 0 then + mode = bit32.bor(mode, tbits) + end + local data = e.data + if typ == "2" and not data then + data = buffer.fromstring(e.link or "") + elseif typ ~= "0" and typ ~= "2" then + data = nil + end + local nlink = e.nlink or (if typ == "5" then 2 else 1) + local ino = e.ino or i + local p = { e = e, mode = mode, data = data or buffer.create(0), nlink = nlink, ino = ino, typ = typ } + prepared[i] = p + if typ == "0" and nlink > 1 then + last[(e.devmajor or 0) .. ":" .. (e.devminor or 0) .. ":" .. ino] = i + end + end + local w = Bytes.writer(1024) + local function put(name: string, p: any, data: buffer): Err.Err? + local e = p.e + local namesize = #name + 1 + local size = buffer.len(data) + if fmt == "odc" then + local dev = (e.devmajor or 0) * 256 + (e.devminor or 0) + local rdev = (e.rdevmajor or 0) * 256 + (e.rdevminor or 0) + local fields = { + oct(dev, 6), + oct(p.ino, 6), + oct(p.mode, 6), + oct(e.uid or 0, 6), + oct(e.gid or 0, 6), + oct(p.nlink, 6), + oct(rdev, 6), + oct(math.floor(e.mtime or 0), 11), + oct(namesize, 6), + oct(size, 11), + } + for k = 1, 10 do + if not fields[k] then + return Err.new(Err.ARG, "entry " .. name .. ": a field does not fit the odc header") + end + end + w:string("070707" .. table.concat(fields :: { string })) + w:string(name) + w:u8(0) + w:bytes(data) + else + local check = if fmt == "crc" and p.typ == "0" then Cpio.checksum(data, 0, size) else 0 + local fields = { + hex8(p.ino), + hex8(p.mode), + hex8(e.uid or 0), + hex8(e.gid or 0), + hex8(p.nlink), + hex8(math.floor(e.mtime or 0)), + hex8(size), + hex8(e.devmajor or 0), + hex8(e.devminor or 0), + hex8(e.rdevmajor or 0), + hex8(e.rdevminor or 0), + hex8(namesize), + hex8(check), + } + for k = 1, 13 do + if not fields[k] then + return Err.new(Err.ARG, "entry " .. name .. ": a field does not fit the newc header") + end + end + w:string((if fmt == "crc" then "070702" else "070701") .. table.concat(fields :: { string })) + w:string(name) + w:u8(0) + w:fill(0, (4 - (110 + namesize) % 4) % 4) + w:bytes(data) + w:fill(0, (4 - size % 4) % 4) + end + return nil + end + for i, p in prepared do + local data = p.data + if fmt ~= "odc" and p.typ == "0" and p.nlink > 1 then + local e = p.e + if last[(e.devmajor or 0) .. ":" .. (e.devminor or 0) .. ":" .. p.ino] ~= i then + data = buffer.create(0) + end + end + local err = put(p.e.name, p, data) + if err then + return nil, err + end + end + local err = put(TRAILER, { e = {}, ino = 0, mode = 0, nlink = 1 }, buffer.create(0)) + if err then + return nil, err + end + w:fill(0, (block - w.pos % block) % block) + return w:finish(), nil +end + +return Cpio +end +__FILES["containers/Demux"] = function() + +-- containers/Demux: the indexed Types.Demuxer every video container builds (Matroska, AVI, MPEG-TS / PS, Y4M, MP4). +-- New in rosetta. Packets are offset + length into the source buffer (or own bytes); per-track cursors are independent. +local Types = __include("Types") + +local Demux = {} +local D = {} +D.__index = D + +type Demux = typeof(setmetatable( + {} :: { + kind: "demuxer", + format: string, + tracks: { Types.Track }, + duration: number, + startTime: number, + meta: { [string]: any }, + src: buffer, + n: number, + tr: { number }, + pts: { number }, + dts: { number }, + dur: { number }, + key: { boolean }, + off: { number }, + len: { number }, + data: { [number]: buffer }, + extra: { [number]: { [string]: any } }, + byTrack: { [number]: { number } }, + cur: { [number]: number }, + gcur: number, + }, + D +)) + +function Demux.new(format: string, tracks: { Types.Track }, src: buffer, meta: { [string]: any }?): Demux + return setmetatable({ + kind = "demuxer" :: "demuxer", + format = format, + tracks = tracks, + duration = 0, + startTime = 0, + meta = meta or {}, + src = src, + n = 0, + tr = {}, + pts = {}, + dts = {}, + dur = {}, + key = {}, + off = {}, + len = {}, + data = {}, + extra = {}, + byTrack = {}, + cur = {}, + gcur = 1, + }, D) +end + +function D.add(self: Demux, track: number, pts: number, dts: number?, duration: number?, keyframe: boolean, offset: number, length: number) + local i = self.n + 1 + self.n = i + self.tr[i] = track + self.pts[i] = pts + self.dts[i] = dts or pts + self.dur[i] = duration or 0 + self.key[i] = keyframe + self.off[i] = offset + self.len[i] = length +end + +function D.addData(self: Demux, track: number, pts: number, dts: number?, duration: number?, keyframe: boolean, data: buffer) + self:add(track, pts, dts, duration, keyframe, -1, buffer.len(data)) + self.data[self.n] = data +end + +function D.setExtra(self: Demux, key: string, value: any) + local e = self.extra[self.n] + if not e then + e = {} + self.extra[self.n] = e + end + e[key] = value +end + +function D.finish(self: Demux) + local byTrack: { [number]: { number } } = {} + for _, t in self.tracks do + byTrack[t.id] = {} + end + for i = 1, self.n do + local list = byTrack[self.tr[i]] + if list then + table.insert(list, i) + end + end + self.byTrack = byTrack + local total = self.duration + local start = math.huge + for _, t in self.tracks do + local list = byTrack[t.id] + local scale = if t.timescale and t.timescale > 0 then t.timescale else 1 + t.timescale = scale + local frameTicks = if t.frameRate and t.frameRate > 0 then scale / t.frameRate else 0 + -- durations from the next packet in presentation order + if #list > 0 then + local order = table.clone(list) + table.sort(order, function(a: number, b: number): boolean + return self.pts[a] < self.pts[b] + end) + for k = 1, #order do + local i = order[k] + if self.dur[i] <= 0 then + local nx = order[k + 1] + if nx and self.pts[nx] > self.pts[i] then + self.dur[i] = self.pts[nx] - self.pts[i] + elseif frameTicks > 0 then + self.dur[i] = frameTicks + elseif k > 1 then + self.dur[i] = self.dur[order[k - 1]] + end + end + end + local first, last = order[1], order[#order] + if t.kind == "video" or t.kind == "audio" then + start = math.min(start, self.pts[first] / scale) + end + local d = (self.pts[last] + self.dur[last] - math.min(0, self.pts[first])) / scale + if not t.duration or t.duration <= 0 then + t.duration = d + end + t.frames = t.frames or #list + end + if t.duration and t.duration > total then + total = t.duration + end + self.cur[t.id] = 1 + end + self.duration = total + -- the presentation time of the first video / audio packet (MPEG-TS streams start at ~1.4 s): VideoDecoders count + -- frame times from it + self.startTime = if start ~= math.huge and start > 0 then start else 0 +end + +function D._packet(self: Demux, i: number): Types.Packet + local data = self.data[i] + if not data then + local o, l = self.off[i], self.len[i] + local src = self.src + local n = buffer.len(src) + if o < 0 or o > n then + o, l = n, 0 + elseif o + l > n then + l = n - o + end + data = buffer.create(l) + buffer.copy(data, 0, src, o, l) + end + local p: any = { + track = self.tr[i], + pts = self.pts[i], + dts = self.dts[i], + duration = self.dur[i], + keyframe = self.key[i], + data = data :: buffer, + } + local e = self.extra[i] + if e then + for k, v in e do + p[k] = v + end + end + return p +end + +function D.read(self: Demux, track: number?): Types.Packet? + if track == nil then + local i = self.gcur + if i > self.n then + return nil + end + self.gcur = i + 1 + return self:_packet(i) + end + local list = self.byTrack[track] + if not list then + return nil + end + local c = self.cur[track] or 1 + local i = list[c] + if not i then + return nil + end + self.cur[track] = c + 1 + return self:_packet(i) +end + +function D.packets(self: Demux, track: number?): () -> Types.Packet? + return function(): Types.Packet? + return self:read(track) + end +end + +function D.count(self: Demux, track: number): number + local list = self.byTrack[track] + return if list then #list else 0 +end +function D.get(self: Demux, track: number, k: number): Types.Packet? + local list = self.byTrack[track] + local i = list and list[k] + if not i then + return nil + end + return self:_packet(i) +end + +function D.info(self: Demux, track: number, k: number): (number?, number?, number?, boolean?, number?) + local list = self.byTrack[track] + local i = list and list[k] + if not i then + return nil, nil, nil, nil, nil + end + return self.pts[i], self.dts[i], self.dur[i], self.key[i], self.len[i] +end + +function D.rewind(self: Demux, track: number?) + if track then + self.cur[track] = 1 + return + end + for id in self.cur do + self.cur[id] = 1 + end + self.gcur = 1 +end + +function D.seek(self: Demux, seconds: number) + local g = self.n + 1 + for _, t in self.tracks do + local list = self.byTrack[t.id] + if list and #list > 0 then + local target = seconds * t.timescale + local best = 1 + for k = 1, #list do + local i = list[k] + if self.key[i] and self.pts[i] <= target + 1e-6 then + best = k + end + end + self.cur[t.id] = best + if list[best] < g then + g = list[best] + end + end + end + self.gcur = if g > self.n then 1 else g +end + +function D.track(self: Demux, kind: string): Types.Track? + local first = nil + for _, t in self.tracks do + if t.kind == kind then + if t.default then + return t + end + first = first or t + end + end + return first +end + +return Demux +end +__FILES["containers/Ebml"] = function() + +-- containers/Ebml: EBML (RFC 8794), the binary structure under Matroska and WebM. New in rosetta. +-- Reading: element headers (IDs keep their length marker bits, as the specs write them: 0x1A45DFA3; sizes drop it; +-- an all-ones size is "unknown"), children iteration, and the value types (unsigned / signed integers, floats, +-- strings, binary). Writing: a byte builder with nested master elements whose 8-byte sizes are patched on close, and +-- minimal-length value elements. +-- Never throws: malformed input gives nil (readers) or stops iteration. +local Bytes = __include("core/Bytes") + +local readu8 = buffer.readu8 + +local Ebml = {} + +Ebml.UNKNOWN = -1 + +function Ebml.vint(buf: buffer, pos: number, limit: number): (number?, number?) + if pos >= limit then + return nil, nil + end + local b = readu8(buf, pos) + if b == 0 then + return nil, nil + end + local len = 1 + local mask = 0x80 + while bit32.band(b, mask) == 0 do + len += 1 + mask = mask // 2 + end + if pos + len > limit then + return nil, nil + end + local v = bit32.band(b, mask - 1) + local allOnes = v == mask - 1 + for i = 1, len - 1 do + local c = readu8(buf, pos + i) + v = v * 256 + c + if c ~= 255 then + allOnes = false + end + end + if allOnes then + return -1, len + end + return v, len +end + +function Ebml.svint(buf: buffer, pos: number, limit: number): (number?, number?) + local v, len = Ebml.vint(buf, pos, limit) + if v == nil or len == nil then + return nil, nil + end + if v == -1 then + return nil, nil + end + return v - (2 ^ (7 * len - 1) - 1), len +end + +function Ebml.id(buf: buffer, pos: number, limit: number): (number?, number?) + if pos >= limit then + return nil, nil + end + local b = readu8(buf, pos) + local len = if b >= 0x80 then 1 elseif b >= 0x40 then 2 elseif b >= 0x20 then 3 elseif b >= 0x10 then 4 else 0 + if len == 0 or pos + len > limit then + return nil, nil + end + local v = b + for i = 1, len - 1 do + v = v * 256 + readu8(buf, pos + i) + end + return v, len +end + +function Ebml.header(buf: buffer, pos: number, limit: number): (number?, number?, number?) + local id, il = Ebml.id(buf, pos, limit) + if not id or not il then + return nil, nil, nil + end + local size, sl = Ebml.vint(buf, pos + il, limit) + if not size or not sl then + return nil, nil, nil + end + return id, size, pos + il + sl +end + +function Ebml.children(buf: buffer, off: number, limit: number): () -> (number?, number, number) + local pos = off + return function(): (number?, number, number) + if pos >= limit then + return nil, 0, 0 + end + local id, size, data = Ebml.header(buf, pos, limit) + if not id or not size or not data then + pos = limit + return nil, 0, 0 + end + if size < 0 or data + size > limit then + size = limit - data + end + pos = data + size + return id, data, size + end +end + +function Ebml.uint(buf: buffer, off: number, len: number): number + local v = 0 + for i = 0, math.min(len, 8) - 1 do + v = v * 256 + readu8(buf, off + i) + end + return v +end +function Ebml.int(buf: buffer, off: number, len: number): number + if len <= 0 then + return 0 + end + local v = Ebml.uint(buf, off, len) + local n = math.min(len, 8) + if readu8(buf, off) >= 0x80 then + v -= 2 ^ (8 * n) + end + return v +end +function Ebml.float(buf: buffer, off: number, len: number): number + local r = Bytes.reader(buf, off, len) + if len == 4 then + return r:f32be() + elseif len == 8 then + return r:f64be() + end + return 0 +end +function Ebml.string(buf: buffer, off: number, len: number): string + local s = buffer.readstring(buf, off, len) + local z = string.find(s, "\0", 1, true) + if z then + s = string.sub(s, 1, z - 1) + end + return s +end +function Ebml.binary(buf: buffer, off: number, len: number): buffer + local b = buffer.create(len) + buffer.copy(b, 0, buf, off, len) + return b +end + +local W = {} +W.__index = W + +type Writer = typeof(setmetatable({} :: { w: Bytes.Writer }, W)) + +function Ebml.writer(capacity: number?): Writer + return setmetatable({ w = Bytes.writer(capacity or 65536) }, W) +end + +local function writeId(w: Bytes.Writer, id: number) + if id >= 0x1000000 then + w:u32be(id) + elseif id >= 0x10000 then + w:u24be(id) + elseif id >= 0x100 then + w:u16be(id) + else + w:u8(id) + end +end + +local function writeSize(w: Bytes.Writer, size: number, n: number?) + local len = n or 1 + if not n then + while size >= 2 ^ (7 * len) - 1 do + len += 1 + end + end + local v = size + 2 ^ (7 * len) -- the marker bit + local bytes = table.create(len, 0) + for i = len, 1, -1 do + bytes[i] = v % 256 + v = v // 256 + end + for i = 1, len do + w:u8(bytes[i]) + end +end +Ebml.writeSize = writeSize + +function Ebml.vintString(v: number, n: number?): string + local w = Bytes.writer(8) + writeSize(w, v, n) + return buffer.readstring(w:finish(), 0, w:tell()) +end + +function W.tell(self: Writer): number + return self.w:tell() +end + +function W.open(self: Writer, id: number): number + writeId(self.w, id) + local at = self.w:tell() + for _ = 1, 8 do + self.w:u8(0) + end + return at +end + +function W.close(self: Writer, at: number) + local w = self.w + local v = w:tell() - at - 8 + w:setU8(at, 0x01) + for i = 7, 1, -1 do + w:setU8(at + i, v % 256) + v = v // 256 + end +end + +function W.openUnknown(self: Writer, id: number) + writeId(self.w, id) + self.w:u8(0x01) + for _ = 1, 7 do + self.w:u8(0xFF) + end +end + +function W.uint(self: Writer, id: number, v: number) + local n = 1 + while v >= 2 ^ (8 * n) and n < 8 do + n += 1 + end + writeId(self.w, id) + writeSize(self.w, n) + local bytes = table.create(n, 0) + local x = v + for i = n, 1, -1 do + bytes[i] = x % 256 + x = x // 256 + end + for i = 1, n do + self.w:u8(bytes[i]) + end +end + +function W.int(self: Writer, id: number, v: number) + local n = 1 + while (v < -(2 ^ (8 * n - 1)) or v >= 2 ^ (8 * n - 1)) and n < 8 do + n += 1 + end + local u = if v < 0 then v + 2 ^ (8 * n) else v + writeId(self.w, id) + writeSize(self.w, n) + local bytes = table.create(n, 0) + for i = n, 1, -1 do + bytes[i] = u % 256 + u = u // 256 + end + for i = 1, n do + self.w:u8(bytes[i]) + end +end + +function W.float(self: Writer, id: number, v: number) + writeId(self.w, id) + writeSize(self.w, 8) + self.w:f64be(v) +end + +function W.string(self: Writer, id: number, s: string) + writeId(self.w, id) + writeSize(self.w, #s) + self.w:string(s) +end + +function W.binary(self: Writer, id: number, b: buffer, off: number?, len: number?) + local o = off or 0 + local n = len or (buffer.len(b) - o) + writeId(self.w, id) + writeSize(self.w, n) + self.w:bytes(b, o, n) +end + +function W.raw(self: Writer, s: string) + self.w:string(s) +end +function W.rawBuffer(self: Writer, b: buffer, off: number?, len: number?) + local o = off or 0 + self.w:bytes(b, o, len or (buffer.len(b) - o)) +end +function W.header(self: Writer, id: number, size: number) + writeId(self.w, id) + writeSize(self.w, size) +end + +function W.void(self: Writer, n: number) + self.w:u8(0xEC) + if n - 2 < 127 then + writeSize(self.w, n - 2, 1) + for _ = 1, n - 2 do + self.w:u8(0) + end + else + writeSize(self.w, n - 9, 8) + for _ = 1, n - 9 do + self.w:u8(0) + end + end +end + +function W.finish(self: Writer): buffer + return self.w:finish() +end + +return Ebml +end +__FILES["containers/Fat"] = function() + +-- containers/Fat: FAT12 / FAT16 / FAT32 over a byte range (BPB, chains, VFAT long names checksum-validated against +-- their 8.3 entry, NT lower-case flags; an MBR's first FAT partition) and a FAT12 floppy writer. New code, from +-- Microsoft's fatgen103 and the VFAT long-name layout. +-- DOS dates are local time without a zone: they are read and written as UTC. Never throws; every chain is bounded by +-- the cluster count (loops are errors). +local Archive = __include("containers/Archive") + +local Fat = {} + +local readu8, readu16, readu32 = buffer.readu8, buffer.readu16, buffer.readu32 + +type Volume = { + b: buffer, + base: number, -- byte offset of the volume (partition) in b + limit: number, + bps: number, -- bytes per sector + spc: number, -- sectors per cluster + fatOffset: number, -- byte offset of the first FAT (relative to base) + fatSize: number, -- bytes per FAT + rootOffset: number, -- FAT12 / 16: the fixed root directory + rootEntries: number, + rootCluster: number, -- FAT32 + dataOffset: number, -- byte offset of cluster 2 + clusters: number, -- data clusters + bits: number, -- 12 / 16 / 32 + label: string?, + oem: string, + media: number, + partition: number?, +} + +type Entry = { + name: string, + dir: boolean, + size: number, + mtime: number?, + cluster: number, + attr: number, + shortName: string, +} + +local function bpbAt(b: buffer, o: number, len: number): (Volume?, string?) + if len < 512 then + return nil, "truncated: smaller than a boot sector" + end + local jump = readu8(b, o) + local bps = readu16(b, o + 11) + local spc = readu8(b, o + 13) + if (jump ~= 0xEB and jump ~= 0xE9 and jump ~= 0xE8) or (bps ~= 512 and bps ~= 1024 and bps ~= 2048 and bps ~= 4096) then + return nil, "no FAT boot sector" + end + if spc == 0 or bit32.band(spc, spc - 1) ~= 0 then + return nil, "bad sectors per cluster" + end + local reserved, nfats, rootEntries = readu16(b, o + 14), readu8(b, o + 16), readu16(b, o + 17) + local total = readu16(b, o + 19) + if total == 0 then + total = readu32(b, o + 32) + end + local fatSectors = readu16(b, o + 22) + local fat32 = fatSectors == 0 + if fat32 then + fatSectors = readu32(b, o + 36) + end + if reserved == 0 or nfats == 0 or fatSectors == 0 or total == 0 then + return nil, "bad BPB" + end + local rootSectors = math.ceil(rootEntries * 32 / bps) + local dataSector = reserved + nfats * fatSectors + rootSectors + if dataSector >= total then + return nil, "bad BPB: no data area" + end + local clusters = (total - dataSector) // spc + local bits = if clusters < 4085 then 12 elseif clusters < 65525 then 16 else 32 + if fat32 and bits ~= 32 then + bits = 32 -- some small FAT32 volumes (mkfs.fat -F 32 on tiny images) are FAT32 regardless of the count + end + if total * bps > len then + -- images cut short at the last used sector are common: allow, reads past the end fail + total = len // bps + end + local labelAt = if bits == 32 then 71 else 43 + local sig = readu8(b, o + (if bits == 32 then 66 else 38)) + local label: string? = if sig == 0x29 then (string.gsub(buffer.readstring(b, o + labelAt, 11), " +$", "")) else nil + if label == "NO NAME" or label == "" then + label = nil + end + return { + b = b, + base = o, + limit = o + len, + bps = bps, + spc = spc, + fatOffset = reserved * bps, + fatSize = fatSectors * bps, + rootOffset = (reserved + nfats * fatSectors) * bps, + rootEntries = rootEntries, + rootCluster = if bits == 32 then readu32(b, o + 44) else 0, + dataOffset = dataSector * bps, + clusters = clusters, + bits = bits, + label = label, + oem = buffer.readstring(b, o + 3, 8), + media = readu8(b, o + 21), + }, nil +end + +type OpenOptions = { partition: number? } -- 1..4: the MBR partition (default: the first FAT one) + +local FAT_TYPES = { [0x01] = true, [0x04] = true, [0x06] = true, [0x0B] = true, [0x0C] = true, [0x0E] = true, [0x11] = true, [0x14] = true, [0x16] = true, [0x1B] = true, [0x1C] = true, [0x1E] = true } + +function Fat.open(b: buffer, off: number, len: number, opts: OpenOptions?): (Volume?, string?) + local o: OpenOptions = opts or {} + off = math.max(0, off) + len = math.min(len, buffer.len(b) - off) + if len < 512 then + return nil, "truncated: smaller than a boot sector" + end + if not o.partition then + local v = bpbAt(b, off, len) + if v then + return v, nil + end + end + -- an MBR: 0x55AA and four partition entries + if readu8(b, off + 510) ~= 0x55 or readu8(b, off + 511) ~= 0xAA then + return nil, "no FAT boot sector and no partition table" + end + for i = 1, 4 do + local e = off + 446 + (i - 1) * 16 + local ptype = readu8(b, e + 4) + local lba, count = readu32(b, e + 8), readu32(b, e + 12) + if (o.partition == i or (not o.partition and FAT_TYPES[ptype])) and ptype ~= 0 then + if lba * 512 >= len then + return nil, "truncated: partition " .. i .. " starts past the end" + end + local v, err = bpbAt(b, off + lba * 512, math.min(count * 512, len - lba * 512)) + if v then + v.partition = i + end + return v, err + end + end + return nil, if o.partition then "no partition " .. o.partition else "no FAT partition" +end + +local function nextCluster(v: Volume, c: number): number + local f = v.base + v.fatOffset + if v.bits == 12 then + local p = f + c + c // 2 + if p + 1 >= v.limit then + return 0xFFFFFFF + end + local w = readu16(v.b, p) + local n = if c % 2 == 0 then bit32.band(w, 0xFFF) else bit32.rshift(w, 4) + return if n >= 0xFF8 then 0xFFFFFFF elseif n == 0xFF7 then 0xFFFFFF7 else n + elseif v.bits == 16 then + local p = f + c * 2 + if p + 2 > v.limit then + return 0xFFFFFFF + end + local n = readu16(v.b, p) + return if n >= 0xFFF8 then 0xFFFFFFF elseif n == 0xFFF7 then 0xFFFFFF7 else n + end + local p = f + c * 4 + if p + 4 > v.limit then + return 0xFFFFFFF + end + return bit32.band(readu32(v.b, p), 0x0FFFFFFF) +end + +local function chainOf(v: Volume, first: number, maxClusters: number): ({ number }?, string?) + local out = {} + local c = first + while c >= 2 and c < 0xFFFFFF7 do + if c >= v.clusters + 2 then + return nil, "cluster " .. c .. " outside the volume" + end + table.insert(out, c) + if #out > maxClusters then + return nil, "cluster chain loops" + end + c = nextCluster(v, c) + end + if c == 0xFFFFFF7 then + return nil, "bad cluster in a chain" + end + return out, nil +end + +local function clusterOffset(v: Volume, c: number): number + return v.base + v.dataOffset + (c - 2) * v.spc * v.bps +end + +local function readChain(v: Volume, first: number, size: number?): (buffer?, string?) + local csize = v.spc * v.bps + local maxClusters = if size then math.ceil(size / csize) + 1 else v.clusters + local list, err = chainOf(v, first, math.min(maxClusters, v.clusters + 1)) + if not list then + return nil, err + end + local total = if size then size else #list * csize + if #list * csize < total then + return nil, "file data ends early (chain of " .. #list .. " clusters for " .. total .. " bytes)" + end + local out = buffer.create(total) + local o = 0 + for _, c in list do + local n = math.min(csize, total - o) + if n <= 0 then + break + end + local at = clusterOffset(v, c) + if at + n > v.limit then + return nil, "truncated: cluster " .. c .. " past the end of the image" + end + buffer.copy(out, o, v.b, at, n) + o += n + end + return out, nil +end + +local function latin1(s: string): string + if not string.find(s, "[\128-\255]") then + return s + end + local out = table.create(#s) + for i = 1, #s do + out[i] = utf8.char(string.byte(s, i)) + end + return table.concat(out) +end + +local function shortChecksum(raw: string): number + local sum = 0 + for i = 1, 11 do + sum = (bit32.rshift(sum, 1) + bit32.lshift(bit32.band(sum, 1), 7) + string.byte(raw, i)) % 256 + end + return sum +end + +local function ucs2(b: buffer, o: number, n: number, out: { number }) + for k = 0, n - 1 do + table.insert(out, readu16(b, o + k * 2)) + end +end + +local function parseDir(d: buffer, prefix: string, out: { Entry }): { Entry } + local lfn: { [number]: { number } } = {} + local lfnSum, lfnCount = -1, 0 + local subdirs = {} + for p = 0, buffer.len(d) - 32, 32 do + local first = readu8(d, p) + if first == 0 then + break + end + local attr = readu8(d, p + 11) + if first == 0xE5 then + lfn, lfnSum, lfnCount = {}, -1, 0 + elseif attr == 0x0F then + local seq = bit32.band(first, 0x3F) + if bit32.band(first, 0x40) ~= 0 then + lfn, lfnCount = {}, seq + lfnSum = readu8(d, p + 13) + end + if seq >= 1 and seq <= 20 and readu8(d, p + 13) == lfnSum then + local chars = {} + ucs2(d, p + 1, 5, chars) + ucs2(d, p + 14, 6, chars) + ucs2(d, p + 28, 2, chars) + lfn[seq] = chars + end + else + local raw = buffer.readstring(d, p, 11) + if first == 0x05 then + raw = "\229" .. string.sub(raw, 2) + end + local long: string? = nil + if lfnCount > 0 and lfnSum == shortChecksum(buffer.readstring(d, p, 11)) then + local cps = {} + local complete = true + for s = 1, lfnCount do + if not lfn[s] then + complete = false + break + end + for _, c in lfn[s] do + if c == 0 or c == 0xFFFF then + break + end + table.insert(cps, c) + end + end + if complete then + local parts = table.create(#cps) + for i, c in cps do + parts[i] = utf8.char(if c >= 0xD800 and c < 0xE000 then 0xFFFD else c) + end + long = table.concat(parts) + end + end + lfn, lfnSum, lfnCount = {}, -1, 0 + local nt = readu8(d, p + 12) + local base = string.gsub(string.sub(raw, 1, 8), " +$", "") + local ext = string.gsub(string.sub(raw, 9, 11), " +$", "") + if bit32.band(nt, 0x08) ~= 0 then + base = string.lower(base) + end + if bit32.band(nt, 0x10) ~= 0 then + ext = string.lower(ext) + end + local short = latin1(if ext ~= "" then base .. "." .. ext else base) + local isDir = bit32.band(attr, 0x10) ~= 0 + local isLabel = bit32.band(attr, 0x08) ~= 0 + if not isLabel and short ~= "." and short ~= ".." then + local name = prefix .. (long or short) + local cluster = readu16(d, p + 26) + readu16(d, p + 20) * 65536 + local e: Entry = { + name = if isDir then name .. "/" else name, + dir = isDir, + size = if isDir then 0 else readu32(d, p + 28), + mtime = Archive.fromDos(readu16(d, p + 24) * 65536 + readu16(d, p + 22)), + cluster = cluster, + attr = attr, + shortName = short, + } + table.insert(out, e) + if isDir then + table.insert(subdirs, e) + end + end + end + end + return subdirs +end + +function Fat.list(v: Volume, maxEntries: number?): ({ Entry }?, string?) + local out: { Entry } = {} + local limit = maxEntries or 65536 + local root: buffer?, err: string? + if v.bits == 32 then + root, err = readChain(v, v.rootCluster, nil) + else + local n = v.rootEntries * 32 + if v.base + v.rootOffset + n > v.limit then + return nil, "truncated: root directory past the end" + end + root = buffer.create(n) + buffer.copy(root :: buffer, 0, v.b, v.base + v.rootOffset, n) + end + if not root then + return nil, err + end + local seen: { [number]: boolean } = {} + local function walk(d: buffer, prefix: string, depth: number): string? + if depth > 64 then + return "directories nested too deep" + end + local start = #out + local subdirs = parseDir(d, prefix, out) + if #out > limit then + return "limit: more than maxEntries entries" + end + local _ = start + for _, s in subdirs do + if s.cluster >= 2 then + if seen[s.cluster] then + return "directory loop at cluster " .. s.cluster + end + seen[s.cluster] = true + local sd, serr = readChain(v, s.cluster, nil) + if not sd then + return s.name .. ": " .. tostring(serr) + end + local werr = walk(sd, s.name, depth + 1) + if werr then + return werr + end + end + end + return nil + end + local werr = walk(root :: buffer, "", 0) + if werr then + return nil, werr + end + return out, nil +end + +function Fat.read(v: Volume, e: Entry): (buffer?, string?) + if e.dir or e.size == 0 then + return buffer.create(0), nil + end + if e.cluster < 2 then + return nil, "file without clusters" + end + return readChain(v, e.cluster, e.size) +end + +type WriteFile = { name: string, data: buffer?, dir: boolean?, mtime: number? } +type WriteOptions = { + size: number?, -- 360 / 720 / 1200 / 1440 / 2880 KB (default 1440) + label: string?, -- volume label (default none) + serial: number?, -- volume serial number (default 0x12345678) +} + +local GEOMETRY = { + [360] = { sectors = 720, spc = 2, root = 112, media = 0xFD, fat = 2, spt = 9, heads = 2 }, + [720] = { sectors = 1440, spc = 2, root = 112, media = 0xF9, fat = 3, spt = 9, heads = 2 }, + [1200] = { sectors = 2400, spc = 1, root = 224, media = 0xF9, fat = 7, spt = 15, heads = 2 }, + [1440] = { sectors = 2880, spc = 1, root = 224, media = 0xF0, fat = 9, spt = 18, heads = 2 }, + [2880] = { sectors = 5760, spc = 2, root = 240, media = 0xF0, fat = 9, spt = 36, heads = 2 }, +} + +local VALID83 = "^[%w!#%$%%&'%(%)%-@%^_`{}~]+$" + +local function toDos(t: number?): (number, number) + local v = Archive.toDos(t) + return v // 65536, v % 65536 +end + +type Node = { name: string, data: buffer?, dir: boolean, mtime: number?, children: { Node }, byName: { [string]: Node }, cluster: number } + +local function shortName(name: string, used: { [string]: boolean }): (string, number, boolean) + local base, ext = string.match(name, "^(.*)%.([^%.]*)$") + if not base or base == "" then + base, ext = name, "" + end + local b, e = base :: string, ext :: string + -- a plain 8.3 name, all upper or all lower case per part: no long name needed + if #b <= 8 and #e <= 3 and string.match(b, VALID83) and (e == "" or string.match(e, VALID83)) then + local bu, eu = string.upper(b), string.upper(e) + local nt = 0 + local ok = true + if b ~= bu then + if b == string.lower(b) then + nt = bit32.bor(nt, 0x08) + else + ok = false + end + end + if e ~= eu then + if e == string.lower(e) then + nt = bit32.bor(nt, 0x10) + else + ok = false + end + end + local raw = bu .. string.rep(" ", 8 - #bu) .. eu .. string.rep(" ", 3 - #eu) + if ok and not used[raw] then + used[raw] = true + return raw, nt, false + end + end + local function clean(s: string): string + s = string.upper((string.gsub(s, "[%s%.]", ""))) + return (string.gsub(s, "[^%w!#%$%%&'%(%)%-@%^_`{}~]", "_")) + end + local cb, ce = clean(b), string.sub(clean(e), 1, 3) + if cb == "" then + cb = "_" + end + for n = 1, 999999 do + local tail = "~" .. n + local raw = string.sub(cb, 1, 8 - #tail) .. tail + raw = raw .. string.rep(" ", 8 - #raw) .. ce .. string.rep(" ", 3 - #ce) + if not used[raw] then + used[raw] = true + return raw, 0, true + end + end + return " ___", 0, true +end + +local function dirEntries(n: Node, parentCluster: number, isRoot: boolean, label: string?): buffer + local w = {} + local function entry(raw: string, attr: number, nt: number, cluster: number, size: number, mtime: number?) + local e = buffer.create(32) + buffer.writestring(e, 0, raw) + buffer.writeu8(e, 11, attr) + buffer.writeu8(e, 12, nt) + local date, time = toDos(mtime) + buffer.writeu16(e, 14, time) + buffer.writeu16(e, 16, date) + buffer.writeu16(e, 18, date) + buffer.writeu16(e, 22, time) + buffer.writeu16(e, 24, date) + buffer.writeu16(e, 26, cluster) + buffer.writeu32(e, 28, size) + table.insert(w, e) + end + if isRoot and label then + local l = string.sub(string.upper(label), 1, 11) + entry(l .. string.rep(" ", 11 - #l), 0x08, 0, 0, 0, n.mtime) + end + if not isRoot then + entry(". ", 0x10, 0, n.cluster, 0, n.mtime) + entry(".. ", 0x10, 0, parentCluster, 0, n.mtime) + end + local used: { [string]: boolean } = {} + for _, c in n.children do + local raw, nt, needLong = shortName(c.name, used) + if needLong then + local cps = {} + if utf8.len(c.name) then + for _, cp in utf8.codes(c.name) do + table.insert(cps, if cp > 0xFFFF then 0x5F else cp) + end + else + for i = 1, #c.name do + table.insert(cps, (string.byte(c.name, i))) + end + end + local count = math.ceil(#cps / 13) + local sum = shortChecksum(raw) + for s = count, 1, -1 do + local e = buffer.create(32) + buffer.writeu8(e, 0, if s == count then bit32.bor(s, 0x40) else s) + buffer.writeu8(e, 11, 0x0F) + buffer.writeu8(e, 13, sum) + local slots = { 1, 3, 5, 7, 9, 14, 16, 18, 20, 22, 24, 28, 30 } + for k = 1, 13 do + local i = (s - 1) * 13 + k + local v = if i <= #cps then cps[i] elseif i == #cps + 1 then 0 else 0xFFFF + buffer.writeu16(e, slots[k], v) + end + table.insert(w, e) + end + end + entry(raw, if c.dir then 0x10 else 0x20, nt, c.cluster, if c.dir then 0 else buffer.len(c.data or buffer.create(0)), c.mtime) + end + local out = buffer.create(#w * 32) + for i, e in w do + buffer.copy(out, (i - 1) * 32, e) + end + return out +end + +function Fat.write(files: { WriteFile }, opts: WriteOptions?): (buffer?, string?) + local o: WriteOptions = opts or {} + local g = GEOMETRY[o.size or 1440] + if not g then + return nil, "size must be 360, 720, 1200, 1440 or 2880" + end + local bps = 512 + local root: Node = { name = "", dir = true, children = {}, byName = {}, cluster = 0 } + local function node(path: string, isDir: boolean): (Node?, string?) + local cur = root + local parts = string.split(path, "/") + for i, p in parts do + if p ~= "" and p ~= "." then + if p == ".." then + return nil, "'..' in a path" + end + local last = i == #parts or (i == #parts - 1 and parts[#parts] == "") + local child: Node? = cur.byName[string.lower(p)] + if not child then + local nc: Node = { name = p, dir = isDir or not last, children = {}, byName = {}, cluster = 0 } + cur.byName[string.lower(p)] = nc + table.insert(cur.children, nc) + child = nc + elseif not child.dir and (not last or isDir) then + return nil, p .. " is both a file and a directory" + end + cur = child :: Node + end + end + return cur, nil + end + for _, f in files do + local n, err = node(f.name, f.dir == true) + if not n then + return nil, err + end + if n ~= root then + n.mtime = f.mtime + if not n.dir then + n.data = f.data or buffer.create(0) + end + end + end + local csize = g.spc * bps + local dataSector = 1 + 2 * g.fat + g.root * 32 // bps + local clusters = (g.sectors - dataSector) // g.spc + local img = buffer.create(g.sectors * bps) + local fat = buffer.create(g.fat * bps) + local nextFree = 2 + local function setFat(c: number, v: number) + local p = c + c // 2 + local w = buffer.readu16(fat, p) + if c % 2 == 0 then + w = bit32.bor(bit32.band(w, 0xF000), v) + else + w = bit32.bor(bit32.band(w, 0x000F), bit32.lshift(v, 4)) + end + buffer.writeu16(fat, p, w) + end + local function alloc(bytes: number): number? + local n = math.max(1, math.ceil(bytes / csize)) + if nextFree + n - 1 > clusters + 1 then + return nil + end + local first = nextFree + for k = 0, n - 1 do + setFat(first + k, if k == n - 1 then 0xFFF else first + k + 1) + end + nextFree += n + return first + end + -- clusters: files get theirs first; a directory's size depends on its entries (long names), so measure first + local function place(n: Node): string? + for _, c in n.children do + if c.dir then + local size = buffer.len(dirEntries(c, 0, false, nil)) + local cl = alloc(size) + if not cl then + return "disk full" + end + c.cluster = cl + local err = place(c) + if err then + return err + end + elseif c.data and buffer.len(c.data) > 0 then + local cl = alloc(buffer.len(c.data)) + if not cl then + return "disk full" + end + c.cluster = cl + local at = (dataSector + (cl - 2) * g.spc) * bps + buffer.copy(img, at, c.data) + end + end + return nil + end + local perr = place(root) + if perr then + return nil, "limit: " .. perr + end + local function writeDirs(n: Node, parent: number): string? + for _, c in n.children do + if c.dir then + local d = dirEntries(c, parent, false, nil) + buffer.copy(img, (dataSector + (c.cluster - 2) * g.spc) * bps, d) + local err = writeDirs(c, c.cluster) + if err then + return err + end + end + end + return nil + end + writeDirs(root, 0) + local rootDir = dirEntries(root, 0, true, o.label) + if buffer.len(rootDir) > g.root * 32 then + return nil, "limit: too many entries in the root directory" + end + buffer.copy(img, (1 + 2 * g.fat) * bps, rootDir) + setFat(0, 0xF00 + g.media) + setFat(1, 0xFFF) + buffer.copy(img, bps, fat) + buffer.copy(img, (1 + g.fat) * bps, fat) + buffer.writestring(img, 0, "\235\60\144" .. "FMTSLUAU") + buffer.writeu16(img, 11, bps) + buffer.writeu8(img, 13, g.spc) + buffer.writeu16(img, 14, 1) + buffer.writeu8(img, 16, 2) + buffer.writeu16(img, 17, g.root) + buffer.writeu16(img, 19, g.sectors) + buffer.writeu8(img, 21, g.media) + buffer.writeu16(img, 22, g.fat) + buffer.writeu16(img, 24, g.spt) + buffer.writeu16(img, 26, g.heads) + buffer.writeu8(img, 36, 0) + buffer.writeu8(img, 38, 0x29) + buffer.writeu32(img, 39, o.serial or 0x12345678) + local label = string.upper(string.sub(o.label or "NO NAME", 1, 11)) + buffer.writestring(img, 43, label .. string.rep(" ", 11 - #label) .. "FAT12 ") + buffer.writestring(img, 62, "\244\235\253") -- hlt; jmp $ (no boot code) + buffer.writeu8(img, 510, 0x55) + buffer.writeu8(img, 511, 0xAA) + return img, nil +end + +return Fat +end +__FILES["containers/Iso9660"] = function() + +-- containers/Iso9660: ISO 9660 (ECMA-119) images, read; from ECMA-119, SUSP / RRIP 1.12, Joliet and El Torito 1.0, no +-- code ported. Name sets: Rock Ridge, else Joliet (%/@, %/C, %/E), else plain (";1" and a trailing "." dropped); +-- multi-extent files joined, CL / RE / PL relocations resolved, El Torito catalog in info.boot. Not supported: zisofs +-- (read returns the stored bytes), interleaved files (Err.UNSUPPORTED), UDF, writing. +local Err = __include("core/Err") +local Types = __include("Types") +local Text = __include("codecs/text/Text") + +local Iso9660 = {} + +type Extent = { at: number, size: number } -- byte offset (from the image start) and length +type Entry = { + name: string, -- the path, "/" separated, no leading "/" + dir: boolean, + size: number, + extents: { Extent }, + mtime: number?, -- unix seconds + type: string, -- tar letters: "0" file, "5" directory, "2" symlink, "3" / "4" devices, "6" fifo, "s" socket + mode: number?, -- Rock Ridge: the permission bits + uid: number?, + gid: number?, + nlink: number?, + link: string?, -- Rock Ridge symlink target + rdev: number?, -- Rock Ridge PN: high * 2^32 + low + hidden: boolean?, + interleaved: boolean?, + zisofs: boolean?, +} +type ReadOptions = { + prefer: ("rockridge" | "joliet" | "iso9660")?, -- the name set (default: Rock Ridge, else Joliet, else plain) + maxEntries: number?, -- default 1e6 +} + +local SECTOR = 2048 +local S_TYPES: { [number]: string } = { [0x8000] = "0", [0x4000] = "5", [0xA000] = "2", [0x2000] = "3", [0x6000] = "4", [0x1000] = "6", [0xC000] = "s" } + +local function u16(b: buffer, o: number): number + return buffer.readu16(b, o) +end +local function u32(b: buffer, o: number): number + return buffer.readu32(b, o) +end +local function str(b: buffer, o: number, n: number): string + return (string.gsub(buffer.readstring(b, o, n), "[ %z]+$", "")) +end + +-- a 7-byte directory record date -> unix seconds +local function recDate(b: buffer, o: number): number? + local y = buffer.readu8(b, o) + local m, d = buffer.readu8(b, o + 1), buffer.readu8(b, o + 2) + if m < 1 or m > 12 or d < 1 or d > 31 then + return nil + end + local off = buffer.readi8(b, o + 6) + return Types.Date.toUnix({ kind = "datetime", year = 1900 + y, month = m, day = d, hour = buffer.readu8(b, o + 3), minute = buffer.readu8(b, o + 4), second = buffer.readu8(b, o + 5), offset = off * 15 }) +end + +-- a 17-byte descriptor date ("YYYYMMDDHHMMSScc" + offset) -> unix seconds +local function longDate(b: buffer, o: number): number? + local s = buffer.readstring(b, o, 16) + local y, mo, d, h, mi, se = string.match(s, "^(%d%d%d%d)(%d%d)(%d%d)(%d%d)(%d%d)(%d%d)%d%d$") + if not y or tonumber(y) == 0 then + return nil + end + local off = buffer.readi8(b, o + 16) + return Types.Date.toUnix({ kind = "datetime", year = tonumber(y), month = tonumber(mo), day = tonumber(d), hour = tonumber(h), minute = tonumber(mi), second = tonumber(se), offset = off * 15 }) +end + +type Susp = { [string]: any } + +local function suspEntries(b: buffer, base: number, limit: number, o: number, e: number, bs: number, budget: { number }): { { any } } + local out = {} + while o + 4 <= e do + local sig = buffer.readstring(b, o, 2) + local len = buffer.readu8(b, o + 2) + if len < 4 or o + len > e then + break + end + if sig == "ST" then + break + elseif sig == "CE" and len >= 28 then + local blk, off, n = u32(b, o + 4), u32(b, o + 12), u32(b, o + 20) + local at = base + blk * bs + off + budget[1] -= 1 + if budget[1] < 0 or at < base or at + n > limit or n > 65536 then + break + end + -- the rest of this area first, then the continuation (it holds what did not fit) + local rest = suspEntries(b, base, limit, o + len, e, bs, budget) + for _, x in rest do + table.insert(out, x) + end + local cont = suspEntries(b, base, limit, at, at + n, bs, budget) + for _, x in cont do + table.insert(out, x) + end + return out + end + table.insert(out, { sig, o, len }) + o += len + end + return out +end + +local function rockRidge(b: buffer, base: number, limit: number, o: number, e: number, bs: number): Susp + local rr: Susp = {} + local name: { string }? = nil + local slParts: { string }? = nil + local slRoot = false + local slCont = false + for _, x in suspEntries(b, base, limit, o, e, bs, { 32 }) do + local sig, at, len = x[1], x[2], x[3] + if sig == "NM" and len >= 5 then + local flags = buffer.readu8(b, at + 4) + if bit32.band(flags, 6) == 0 then + name = name or {} + table.insert(name :: { string }, buffer.readstring(b, at + 5, len - 5)) + end + elseif sig == "PX" and len >= 36 then + rr.mode, rr.nlink, rr.uid, rr.gid = u32(b, at + 4), u32(b, at + 12), u32(b, at + 20), u32(b, at + 28) + elseif sig == "PN" and len >= 20 then + rr.rdev = u32(b, at + 4) * 4294967296 + u32(b, at + 12) + elseif sig == "TF" and len >= 5 then + local flags = buffer.readu8(b, at + 4) + local w = if bit32.band(flags, 0x80) ~= 0 then 17 else 7 + local q = at + 5 + for bit = 0, 6 do + if bit32.band(flags, bit32.lshift(1, bit)) ~= 0 then + if q + w > at + len then + break + end + if bit == 1 then + rr.mtime = if w == 17 then longDate(b, q) else recDate(b, q) + end + q += w + end + end + elseif sig == "SL" and len >= 5 then + slParts = slParts or {} + local parts = slParts :: { string } + local q = at + 5 + while q + 2 <= at + len do + local cf, cl = buffer.readu8(b, q), buffer.readu8(b, q + 1) + if q + 2 + cl > at + len then + break + end + local piece = if bit32.band(cf, 2) ~= 0 then "." elseif bit32.band(cf, 4) ~= 0 then ".." else buffer.readstring(b, q + 2, cl) + if bit32.band(cf, 8) ~= 0 then + slRoot = #parts == 0 + piece = "" + end + if slCont and #parts > 0 then + parts[#parts] ..= piece + elseif bit32.band(cf, 8) == 0 or #parts > 0 then + table.insert(parts, piece) + end + slCont = bit32.band(cf, 1) ~= 0 + q += 2 + cl + end + elseif sig == "CL" and len >= 12 then + rr.child = u32(b, at + 4) + elseif sig == "RE" then + rr.relocated = true + elseif sig == "ZF" then + rr.zisofs = true + end + end + if name then + rr.name = table.concat(name) + end + if slParts then + rr.link = (if slRoot then "/" else "") .. table.concat(slParts, "/") + end + return rr +end + +type Record = { + name: string, + dir: boolean, + lba: number, + size: number, + ear: number, + flags: number, + interleave: boolean, + mtime: number?, + rr: Susp?, +} + +local function records(b: buffer, base: number, limit: number, at: number, size: number, bs: number, joliet: boolean, rrSkip: number?): ({ Record }?, Err.Err?) + if at + size > limit then + return nil, Err.new(Err.TRUNCATED, "directory past the end", at) + end + local out: { Record } = {} + local p = at + local e = at + size + while p < e do + local len = buffer.readu8(b, p) + if len == 0 then + p = at + ((p - at) // SECTOR + 1) * SECTOR -- the rest of the sector is padding + continue + end + if len < 34 or p + len > e then + return nil, Err.new(Err.CORRUPT, "bad directory record", p) + end + local nl = buffer.readu8(b, p + 32) + if 33 + nl > len then + return nil, Err.new(Err.CORRUPT, "bad name length", p + 32) + end + local raw = buffer.readstring(b, p + 33, nl) + if raw ~= "\0" and raw ~= "\1" then + local flags = buffer.readu8(b, p + 25) + local name + if joliet then + name = Text.utf16(b, p + 33, nl, true) + else + name = raw + end + name = string.gsub(name, ";%d*$", "") + if not joliet and bit32.band(flags, 2) == 0 then + name = string.gsub(name, "%.$", "") + end + local r: Record = { + name = name, + dir = bit32.band(flags, 2) ~= 0, + lba = u32(b, p + 2), + size = u32(b, p + 10), + ear = buffer.readu8(b, p + 1), + flags = flags, + interleave = buffer.readu8(b, p + 26) ~= 0 or buffer.readu8(b, p + 27) ~= 0, + mtime = recDate(b, p + 18), + rr = nil, + } + if rrSkip then + local su = p + 33 + nl + (if nl % 2 == 0 then 1 else 0) + rrSkip + r.rr = rockRidge(b, base, limit, su, p + len, bs) + end + table.insert(out, r) + end + p += len + end + return out, nil +end + +local function root(b: buffer, vd: number): (number, number) + return u32(b, vd + 156 + 2), u32(b, vd + 156 + 10) +end + +-- Rock Ridge in use: the root's "." record starts its system use area with SP (BE EF); its skip length +local function rockRidgeSkip(b: buffer, base: number, limit: number, lba: number, bs: number): number? + local p = base + lba * bs + if p + 34 > limit then + return nil + end + local len = buffer.readu8(b, p) + local nl = buffer.readu8(b, p + 32) + local su = p + 33 + nl + (if nl % 2 == 0 then 1 else 0) + if len < 34 or su + 7 > p + len or p + len > limit then + return nil + end + if buffer.readstring(b, su, 2) == "SP" and buffer.readu8(b, su + 4) == 0xBE and buffer.readu8(b, su + 5) == 0xEF then + return buffer.readu8(b, su + 6) + end + return nil +end + +local function boot(b: buffer, base: number, limit: number, vd: number, bs: number): { [string]: any }? + if str(b, vd + 7, 32) ~= "EL TORITO SPECIFICATION" then + return nil + end + local cat = u32(b, vd + 0x47) + local p = base + cat * bs + local info: { [string]: any } = { catalog = cat } + if p + 64 > limit or buffer.readu8(b, p) ~= 1 or buffer.readu8(b, p + 30) ~= 0x55 or buffer.readu8(b, p + 31) ~= 0xAA then + return info + end + local sum = 0 + for i = 0, 30, 2 do + sum += u16(b, p + i) + end + info.valid = sum % 65536 == 0 + info.platform = buffer.readu8(b, p + 1) + info.id = str(b, p + 4, 24) + local d = p + 32 + info.bootable = buffer.readu8(b, d) == 0x88 + info.media = buffer.readu8(b, d + 1) -- 0 no emulation, 1..3 floppies, 4 hard disk + info.loadSegment = u16(b, d + 2) + info.systemType = buffer.readu8(b, d + 4) + info.sectors = u16(b, d + 6) -- 512-byte virtual sectors + info.lba = u32(b, d + 8) + return info +end + +function Iso9660.read(b: buffer, offset: number?, length: number?, opts: ReadOptions?): ({ Entry }?, any) + local base = offset or 0 + local limit = math.min(buffer.len(b), base + (length or (buffer.len(b) - base))) + local o: ReadOptions = opts or {} + local maxEntries = o.maxEntries or 1e6 + local pvd: number? = nil + local svd: number? = nil + local jolietLevel: number? = nil + local bootInfo = nil + local p = base + 16 * SECTOR + for _ = 1, 64 do + if p + SECTOR > limit then + return nil, Err.new(Err.TRUNCATED, "volume descriptors past the end", p) + end + if buffer.readstring(b, p + 1, 5) ~= "CD001" then + return nil, Err.new(Err.CORRUPT, "bad volume descriptor", p) + end + local t = buffer.readu8(b, p) + if t == 255 then + break + elseif t == 1 and not pvd then + pvd = p + elseif t == 2 then + local esc = buffer.readstring(b, p + 88, 3) + if esc == "%/@" or esc == "%/C" or esc == "%/E" then + svd = p + jolietLevel = if esc == "%/@" then 1 elseif esc == "%/C" then 2 else 3 + end + elseif t == 0 then + bootInfo = bootInfo or { vd = p } + end + p += SECTOR + end + if not pvd then + return nil, Err.new(Err.CORRUPT, "no primary volume descriptor", base + 16 * SECTOR) + end + local pv = pvd :: number + local bs = u16(b, pv + 128) + if bs ~= 512 and bs ~= 1024 and bs ~= 2048 then + return nil, Err.new(Err.CORRUPT, "bad logical block size " .. bs, pv + 128) + end + local info: { [string]: any } = { + blockSize = bs, + blocks = u32(b, pv + 80), + systemId = str(b, pv + 8, 32), + volumeId = str(b, pv + 40, 32), + volumeSet = str(b, pv + 190, 128), + publisher = str(b, pv + 318, 128), + preparer = str(b, pv + 446, 128), + application = str(b, pv + 574, 128), + created = longDate(b, pv + 813), + modified = longDate(b, pv + 830), + joliet = jolietLevel, + } + if bootInfo then + info.boot = boot(b, base, limit, bootInfo.vd, bs) + end + local rlba, rsize = root(b, pv) + local rrSkip = rockRidgeSkip(b, base, limit, rlba, bs) + info.rockRidge = rrSkip ~= nil + local tree = o.prefer or (if rrSkip then "rockridge" elseif svd then "joliet" else "iso9660") + if tree == "joliet" and not svd then + tree = "iso9660" + elseif tree == "rockridge" and not rrSkip then + tree = "iso9660" + end + info.tree = tree + local joliet = tree == "joliet" + local useRR = if tree == "rockridge" then rrSkip else nil + if joliet then + rlba, rsize = root(b, svd :: number) + end + if tree == "joliet" then + info.volumeId = (string.gsub(Text.utf16(b, (svd :: number) + 40, 32, true), "[ %z]+$", "")) + end + local out: { Entry } = {} + local visited: { [number]: boolean } = {} + local stack = { { lba = rlba, size = rsize, path = "" } } + local relocatedDirs: { [string]: boolean } = {} + while #stack > 0 do + local d = table.remove(stack) :: any + if visited[d.lba] then + continue + end + visited[d.lba] = true + local list, err = records(b, base, limit, base + d.lba * bs, d.size, bs, joliet, useRR) + if not list then + return nil, err + end + local i = 1 + local subdirs = {} + while i <= #list do + local r = list[i] + -- multi-extent: this record and the following ones of the same name + local extents: { Extent } = { { at = base + (r.lba + r.ear) * bs, size = r.size } } + local total = r.size + local last = r + while bit32.band(last.flags, 0x80) ~= 0 and i < #list and list[i + 1].name == r.name do + i += 1 + last = list[i] + table.insert(extents, { at = base + (last.lba + last.ear) * bs, size = last.size }) + total += last.size + end + i += 1 + if bit32.band(r.flags, 4) ~= 0 then + continue -- an associated file (resource fork) + end + local rr: any = r.rr + if rr and rr.relocated then + continue -- shown where its CL placeholder is + end + local name = if rr and rr.name then rr.name else r.name + local path = d.path .. name + local isDir = r.dir + local lba: number, size: number = r.lba, r.size + if rr and rr.child then + -- a deep directory relocated by Rock Ridge: the placeholder points at it; its size is its "." record's + isDir = true + lba = rr.child + local q = base + lba * bs + size = if q + 14 <= limit then u32(b, q + 10) else 0 + end + local typ = if isDir then "5" else "0" + if rr and rr.mode then + typ = S_TYPES[bit32.band(rr.mode, 0xF000)] or typ + end + local e: Entry = { + name = path, + dir = isDir, + size = if isDir or typ ~= "0" then 0 else total, + extents = if isDir or typ ~= "0" then {} else extents, + mtime = if rr and rr.mtime then rr.mtime else r.mtime, + type = typ, + mode = if rr and rr.mode then bit32.band(rr.mode, 0xFFF) else nil, + uid = rr and rr.uid, + gid = rr and rr.gid, + nlink = rr and rr.nlink, + link = if rr and typ == "2" then rr.link else nil, + rdev = rr and rr.rdev, + hidden = if bit32.band(r.flags, 1) ~= 0 then true else nil, + interleaved = if r.interleave then true else nil, + zisofs = if rr and rr.zisofs then true else nil, + } + table.insert(out, e) + if #out > maxEntries then + return nil, Err.new(Err.LIMIT, "more than " .. maxEntries .. " entries") + end + if isDir then + table.insert(subdirs, { lba = lba, size = size, path = path .. "/" }) + end + end + for k = #subdirs, 1, -1 do + table.insert(stack, subdirs[k]) + end + if useRR then + for _, r in list do + if r.rr and r.rr.relocated then + relocatedDirs[d.path] = true + end + end + end + end + -- rr_moved (genisoimage's home of relocated directories): hidden when nothing else is in it + if useRR then + for dirPath in relocatedDirs do + local name = string.sub(dirPath, 1, -2) + local holds = false + for _, e in out do + if string.sub(e.name, 1, #dirPath) == dirPath then + holds = true + break + end + end + if not holds then + for k, e in out do + if e.name == name then + table.remove(out, k) + break + end + end + end + end + end + -- archive order: depth-first walk order is kept; directories sorted as the image stores them + return out, info +end + +function Iso9660.extract(b: buffer, e: Entry, limit: number?): (buffer?, Err.Err?) + if e.interleaved then + return nil, Err.new(Err.UNSUPPORTED, "interleaved file " .. e.name) + end + local lim = limit or buffer.len(b) + local out = buffer.create(e.size) + local q = 0 + for _, x in e.extents do + if x.at < 0 or x.at + x.size > lim then + return nil, Err.new(Err.TRUNCATED, "file " .. e.name .. " data past the end", x.at) + end + buffer.copy(out, q, b, x.at, x.size) + q += x.size + end + return out, nil +end + +function Iso9660.valid(b: buffer, offset: number?): boolean + local p = (offset or 0) + 16 * SECTOR + return p + 6 <= buffer.len(b) and buffer.readstring(b, p + 1, 5) == "CD001" +end + +return Iso9660 +end +__FILES["containers/IsoBmff"] = function() + +-- containers/IsoBmff: ISO base media file format (ISO/IEC 14496-12) and its relatives: MP4 / M4A / M4V / MOV (QuickTime) +-- / 3GP, fragmented MP4 (moof), HEIF / AVIF items (ISO/IEC 23008-12), iTunes tags. A container (layer 2): m4a, mp4, +-- mov, heif, avif build on it. Written from the specifications; no third-party code. +-- Sample offsets in tracks are absolute offsets into r.buf (r may cover part of a bigger buffer). Supports: 32 / 64-bit +-- boxes, stsz / stz2, stco / co64, ctts v0 / v1, stss, elst v0 / v1, QuickTime sound descriptions v1 / v2 and 'wave', +-- fragments with trex defaults / tfdt / data offsets. Not supported: external data references (dref urls), +-- encrypted tracks (sinf / senc are left to the caller), fragmented writing. Never throws. +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Box = __include("containers/IsoBmff/Box") +local Demux = __include("containers/IsoBmff/Demux") +local Meta = __include("containers/IsoBmff/Meta") +local Mux = __include("containers/IsoBmff/Mux") + +local IsoBmff = {} +IsoBmff.Box = Box +IsoBmff.Demux = Demux +IsoBmff.Meta = Meta + +type Track = Demux.Track +type Movie = Demux.Movie +type Items = Meta.Items +type Item = Meta.Item +type MuxSpec = Mux.MuxSpec +type MuxTrack = Mux.MuxTrack +type Picture = Meta.Picture + +local TOP: { [string]: boolean } = { + ftyp = true, moov = true, mdat = true, free = true, skip = true, wide = true, pnot = true, moof = true, + styp = true, sidx = true, meta = true, uuid = true, PICT = true, +} + +function IsoBmff.sniff(r: Bytes.Reader): string? + local head = r:peek(12) + if #head < 8 then + return nil + end + local typ = string.sub(head, 5, 8) + if typ == "ftyp" then + return if #head >= 12 then string.sub(head, 9, 12) else "" + end + if TOP[typ] then + local size = string.byte(head, 1) * 16777216 + string.byte(head, 2) * 65536 + string.byte(head, 3) * 256 + string.byte(head, 4) + if size == 1 or size == 0 or size >= 8 then + return "" + end + end + return nil +end + +function IsoBmff.parse(r: Bytes.Reader, opts: Demux.Options?): (Movie?, Err.Err?) + return Demux.parse(r, opts) +end + +function IsoBmff.tags(r: Bytes.Reader, movie: Movie): ({ [string]: string }, { Picture }) + local ilst = Box.path(movie.boxes, "moov/udta/meta/ilst") or Box.path(movie.boxes, "moov/meta/ilst") or Box.path(movie.boxes, "meta/ilst") + return Meta.tags(r.buf, ilst) +end + +function IsoBmff.items(r: Bytes.Reader, movie: Movie): (Items?, Err.Err?) + local meta = Box.path(movie.boxes, "meta") + if not meta then + return nil, Err.new(Err.CORRUPT, "no top-level meta box") + end + return Meta.items(r.buf, meta) +end + +function IsoBmff.itemData(r: Bytes.Reader, items: Items, id: number): (buffer?, Err.Err?) + return Meta.itemData(r.buf, r.base, r.limit, items, id) +end + +function IsoBmff.sample(r: Bytes.Reader, t: Track, i: number): buffer? + if i < 1 or i > t.sampleCount then + return nil + end + local n = t.sizes[i] + local out = buffer.create(n) + buffer.copy(out, 0, r.buf, t.offsets[i], n) + return out +end + +function IsoBmff.demux(r: Bytes.Reader, opts: Demux.Options?): (any, Err.Err?) + local movie, err = Demux.parse(r, opts) + if not movie then + return nil, err + end + local cursor: { [number]: number } = {} + local byId: { [number]: Track } = {} + for _, t in movie.tracks do + cursor[t.id] = 1 + byId[t.id] = t + end + local dmx = { tracks = movie.tracks, duration = movie.duration, movie = movie } + local function packet(t: Track, i: number): any + local dts = t.dts[i] + local cts = t.cts + return { + track = t.id, + dts = dts, + pts = dts + (if cts then cts[i] or 0 else 0), + duration = t.durations[i], + keyframe = t.sync == nil or (t.sync :: any)[i] == true, + data = IsoBmff.sample(r, t, i), + index = i, + } + end + function dmx.packets(_self: any, trackId: number?): () -> any + return function(): any + if trackId then + local t = byId[trackId] + if not t then + return nil + end + local i = cursor[trackId] + if i > t.sampleCount then + return nil + end + cursor[trackId] = i + 1 + return packet(t, i) + end + local best: Track? = nil + local bestOff = math.huge + for _, t in movie.tracks do + local i = cursor[t.id] + if i <= t.sampleCount and t.offsets[i] < bestOff then + best, bestOff = t, t.offsets[i] + end + end + if not best then + return nil + end + local i = cursor[best.id] + cursor[best.id] = i + 1 + return packet(best, i) + end + end + -- every track to its last sync sample at or before the time + function dmx.seek(_self: any, seconds: number) + for _, t in movie.tracks do + local target = seconds * t.timescale + local lo, hi = 1, t.sampleCount + local found = 1 + while lo <= hi do + local mid = (lo + hi) // 2 + if t.dts[mid] <= target then + found = mid + lo = mid + 1 + else + hi = mid - 1 + end + end + if t.sync then + while found > 1 and not (t.sync :: any)[found] do + found -= 1 + end + end + cursor[t.id] = found + end + end + return dmx, nil +end + +function IsoBmff.mux(spec: MuxSpec): (buffer?, Err.Err?) + return Mux.mux(spec) +end + +return IsoBmff +end +__FILES["containers/IsoBmff/Box"] = function() + +-- containers/IsoBmff/Box: the box tree of an ISO BMFF / QuickTime file (ISO/IEC 14496-12 4.2): 32-bit, 64-bit +-- (size 1) and to-the-end (size 0) sizes, uuid boxes, full-box version / flags, and the recursion into the container +-- boxes (moov / trak / mdia / minf / stbl / udta / meta / ilst items / moof / traf / iprp / ipco / iref / dinf / ...). +-- Sample descriptions (stsd) are left to the demuxer, which knows the sample entry layouts. Never throws. +local Err = __include("core/Err") + +local readu8, readu32, readstring = buffer.readu8, buffer.readu32, buffer.readstring +local byteswap = bit32.byteswap + +local Box = {} + +type Box = { + type: string, -- four characters ("moov", "\169nam", ...); "uuid" boxes also have `uuid` + start: number, -- absolute offset of the box in the buffer + size: number, -- the whole box, header included + data: number, -- absolute offset of the payload (after size / type / largesize / uuid) + stop: number, -- absolute offset just past the box (start + size, clamped to the parent) + uuid: string?, + children: { Box }?, -- container boxes + truncated: boolean?, -- the box claims more bytes than its parent has (clamped) +} + +-- plain container boxes: their payload is a list of boxes +local CONTAINERS = { + moov = true, trak = true, mdia = true, minf = true, stbl = true, dinf = true, edts = true, udta = true, + mvex = true, moof = true, traf = true, mfra = true, tref = true, iprp = true, ipco = true, sinf = true, + schi = true, wave = true, gmhd = true, tapt = true, ilst = true, clip = true, matt = true, rinf = true, + strk = true, strd = true, grpl = true, meco = true, mere = true, +} +-- full boxes (version + flags) whose payload is then a list of boxes, after `skip` more bytes +local FULL_CONTAINERS: { [string]: number } = { meta = 0, iref = 0, dref = 4 } +Box.CONTAINERS = CONTAINERS + +local function be32(b: buffer, o: number): number + return byteswap(readu32(b, o)) +end +Box.be32 = be32 + +-- the ilst item boxes ("\169nam", "trkn", "----", ...) contain data / mean / name boxes +local function isIlstItem(parentType: string?): boolean + return parentType == "ilst" +end + +function Box.header(b: buffer, p: number, limit: number): (Box?, Err.Err?) + if p + 8 > limit then + return nil, Err.new(Err.TRUNCATED, "box header runs past the end", p) + end + local size = be32(b, p) + local typ = readstring(b, p + 4, 4) + local data = p + 8 + if size == 1 then + if p + 16 > limit then + return nil, Err.new(Err.TRUNCATED, "64-bit box size runs past the end", p) + end + size = be32(b, p + 8) * 4294967296 + be32(b, p + 12) + data = p + 16 + elseif size == 0 then + size = limit - p + end + local uuid: string? = nil + if typ == "uuid" then + if data + 16 > limit then + return nil, Err.new(Err.TRUNCATED, "uuid runs past the end", p) + end + uuid = readstring(b, data, 16) + data += 16 + end + if size < data - p then + return nil, Err.new(Err.CORRUPT, string.format("box '%s' size %d is smaller than its header", typ, size), p) + end + local stop = p + size + local truncated: boolean? = nil + if stop > limit then + stop = limit + truncated = true + end + return { type = typ, start = p, size = size, data = data, stop = stop, uuid = uuid, children = nil, truncated = truncated }, nil +end + +function Box.list(b: buffer, p: number, limit: number, parentType: string?, depth: number?): ({ Box }, Err.Err?) + local d = depth or 0 + local out: { Box } = {} + local firstErr: Err.Err? = nil + if d > 32 then + return out, Err.new(Err.CORRUPT, "boxes nested too deep", p) + end + while p + 8 <= limit do + local box, err = Box.header(b, p, limit) + if not box then + firstErr = firstErr or err + break + end + if box.truncated then + firstErr = firstErr or Err.new(Err.TRUNCATED, "box '" .. box.type .. "' runs past the end", p) + end + local t = box.type + local kids: { Box }? = nil + local kerr: Err.Err? = nil + if CONTAINERS[t] or isIlstItem(parentType) then + kids, kerr = Box.list(b, box.data, box.stop, t, d + 1) + elseif FULL_CONTAINERS[t] then + local q = box.data + 4 + FULL_CONTAINERS[t] + -- QuickTime writes udta/meta as a plain container: its first child box follows directly + if t == "meta" and box.data + 8 <= box.stop and readstring(b, box.data + 4, 4) == "hdlr" then + q = box.data + end + if q <= box.stop then + kids, kerr = Box.list(b, q, box.stop, t, d + 1) + end + elseif t == "iinf" then + if box.data + 4 <= box.stop then + local v = readu8(b, box.data) + local q = box.data + 4 + (if v == 0 then 2 else 4) + if q <= box.stop then + kids, kerr = Box.list(b, q, box.stop, t, d + 1) + end + end + end + box.children = kids + if kerr then + firstErr = firstErr or kerr + end + table.insert(out, box) + if box.stop <= p then + break + end + p = box.stop + end + return out, firstErr +end + +function Box.child(box: Box?, typ: string): Box? + if not box or not box.children then + return nil + end + for _, c in box.children :: { Box } do + if c.type == typ then + return c + end + end + return nil +end + +function Box.childrenOf(box: Box?, typ: string): { Box } + local out = {} + if box and box.children then + for _, c in box.children :: { Box } do + if c.type == typ then + table.insert(out, c) + end + end + end + return out +end + +function Box.path(root: any, path: string): Box? + local cur: any = root + for part in string.gmatch(path, "[^/]+") do + if cur == nil then + return nil + end + local list = if cur.children ~= nil or cur.type ~= nil then cur.children else cur + local found = nil + if list then + for _, c in list do + if c.type == part then + found = c + break + end + end + end + cur = found + end + return cur +end + +function Box.fullHeader(b: buffer, box: Box): (number, number) + if box.data + 4 > box.stop then + return -1, 0 + end + local v = be32(b, box.data) + return bit32.rshift(v, 24), bit32.band(v, 0xFFFFFF) +end + +return Box +end +__FILES["containers/IsoBmff/Demux"] = function() + +-- containers/IsoBmff/Demux: tracks and sample tables of an ISO BMFF / QuickTime file (ISO/IEC 14496-12 8.3 - 8.8), +-- edit lists and fragments (mvex / trex, moof / traf / tfhd / tfdt / trun). The per-sample tables are columnar arrays, +-- offsets absolute in the reader's buffer. Never throws. +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Box = __include("containers/IsoBmff/Box") +local QtPalette = __include("containers/IsoBmff/QtPalette") + +local readstring = buffer.readstring + +local function readu16be(b: buffer, o: number): number + return buffer.readu8(b, o) * 256 + buffer.readu8(b, o + 1) +end + +local Demux = {} + +type Edit = { duration: number, mediaTime: number, rate: number } -- duration in movie ticks, mediaTime in media ticks (-1 = empty) + +type Track = { + id: number, + kind: "video" | "audio" | "subtitle" | "data", + codec: string, -- "aac", "alac", "mp3", "opus", "flac", "pcm", "h264", "hevc", "av1", "vp8", "vp9", "mpeg4", "mjpeg", "ac3", "eac3", "tx3g", ... or the entry fourcc + entry: string, -- the sample entry fourcc ("mp4a", "alac", "avc1", ...) + handler: string, -- hdlr type ("soun", "vide", "subt", "text", "pict", ...) + timescale: number, + duration: number, -- seconds (media duration; the edit list may shorten it) + mediaDuration: number, -- ticks + language: string?, -- ISO 639-2 ("und", "eng", ...) + width: number?, + height: number?, + sampleRate: number?, + channels: number?, + bitsPerSample: number?, + config: buffer?, -- codec configuration (AudioSpecificConfig, ALAC cookie, dOps, avcC, ...) + bitsPerPixel: number?, -- video: the sample description's depth (24, 32, 40 = 8-bit grey, ...) + palette: buffer?, -- video, 1..8-bit depths: 256 u32 entries (bytes R, G, B, 0xFF) + objectType: number?, -- esds objectTypeIndication + pcm: { bits: number, float: boolean, little: boolean }?, + entryBoxes: { Box.Box }, -- the sample entry's child boxes (esds, btrt, colr, pasp, ...) + edits: { Edit }?, + skip: number, -- media ticks to drop at the start (the first edit's media time: AAC priming) + delay: number, -- movie ticks of an initial empty edit + playDuration: number?, -- media ticks the edit list plays (nil: all) + sampleCount: number, + offsets: { number }, -- absolute offsets in the buffer + sizes: { number }, + dts: { number }, -- decode times in ticks + durations: { number }, + cts: { number }?, -- composition offsets (pts = dts + cts) when the track has ctts / trun offsets + sync: { [number]: boolean }?, -- sync samples (nil: every sample is a sync sample) + sampleDescription: { number }?, -- stsd index per sample when there are several entries + [string]: any, +} + +type Options = { maxSamples: number? } + +local HANDLER_KIND: { [string]: "video" | "audio" | "subtitle" | "data" } = { + soun = "audio", vide = "video", pict = "video", auxv = "video", subt = "subtitle", text = "subtitle", + sbtl = "subtitle", clcp = "subtitle", +} +local CODEC: { [string]: string } = { + mp4a = "aac", alac = "alac", Opus = "opus", fLaC = "flac", [".mp3"] = "mp3", ["ac-3"] = "ac3", ["ec-3"] = "eac3", + lpcm = "pcm", sowt = "pcm", twos = "pcm", ["raw "] = "pcm", in24 = "pcm", in32 = "pcm", fl32 = "pcm", fl64 = "pcm", + ipcm = "pcm", fpcm = "pcm", ulaw = "ulaw", alaw = "alaw", samr = "amr", sawb = "amrwb", + avc1 = "h264", avc3 = "h264", hvc1 = "hevc", hev1 = "hevc", av01 = "av1", vp08 = "vp8", vp09 = "vp9", + mp4v = "mpeg4", jpeg = "mjpeg", mjpa = "mjpeg", mjpb = "mjpeg", png = "png", ["s263"] = "h263", ["mp1v"] = "mpeg1", + ["mp2v"] = "mpeg2", tx3g = "tx3g", wvtt = "webvtt", stpp = "ttml", c608 = "cea608", text = "text", +} +-- esds objectTypeIndication -> codec +local OTI: { [number]: string } = { + [0x40] = "aac", [0x66] = "aac", [0x67] = "aac", [0x68] = "aac", [0x69] = "mp3", [0x6B] = "mp3", [0x6A] = "mpeg1", + [0x60] = "mpeg2", [0x61] = "mpeg2", [0x20] = "mpeg4", [0x21] = "h264", [0x6C] = "mjpeg", [0xA5] = "ac3", + [0xA6] = "eac3", [0xAD] = "opus", [0xDD] = "vorbis", +} +-- the box holding each video / audio codec's configuration +local CONFIG_BOX = { "avcC", "hvcC", "av1C", "vpcC", "dOps", "dfLa", "dac3", "dec3", "d263", "glbl" } +local FULL_CONFIG: { [string]: boolean } = { vpcC = true, dfLa = true, alac = true } + +local function payload(b: buffer, box: Box.Box, skip: number?): buffer + local o = box.data + (skip or 0) + local n = math.max(0, box.stop - o) + local out = buffer.create(n) + if n > 0 then + buffer.copy(out, 0, b, o, n) + end + return out +end + +local function reader(b: buffer, box: Box.Box): Bytes.Reader + return Bytes.reader(b, box.data, box.stop - box.data) +end + +-- expandable descriptor length (ISO 14496-1 8.3.3) +local function descLen(r: Bytes.Reader): number + local n = 0 + for _ = 1, 4 do + local c = r:u8() + n = n * 128 + bit32.band(c, 127) + if c < 128 then + break + end + end + return n +end + +function Demux.esds(b: buffer, box: Box.Box): (number?, buffer?, number?) + local r = reader(b, box) + r:skip(4) -- version / flags + if r:u8() ~= 3 then + return nil, nil, nil + end + descLen(r) + r:skip(2) -- ES_ID + local flags = r:u8() + if bit32.band(flags, 0x80) ~= 0 then + r:skip(2) + end + if bit32.band(flags, 0x40) ~= 0 then + r:skip(r:u8()) + end + if bit32.band(flags, 0x20) ~= 0 then + r:skip(2) + end + if r:u8() ~= 4 then + return nil, nil, nil + end + local dlen = descLen(r) + local dstart = r.pos + local oti = r:u8() + r:skip(1 + 3 + 4) -- streamType, bufferSize, maxBitrate + local avg = r:u32be() + local dsi: buffer? = nil + if r.pos < dstart + dlen and r:u8() == 5 then + local n = descLen(r) + if n > 0 and r:need(n) then + dsi = r:bytes(n) + end + end + if r.err then + return oti, nil, nil + end + return oti, dsi, avg +end + +local function sampleEntry(b: buffer, e: Box.Box, handler: string, t: Track) + local r = reader(b, e) + r:skip(6) + r:skip(2) -- data reference index + local typ = e.type + t.entry = typ + t.codec = CODEC[typ] or typ + local kind = t.kind + local childStart + if kind == "audio" then + local version = r:u16be() + r:skip(2 + 4) -- revision, vendor + local channels = r:u16be() + local bits = r:u16be() + r:skip(4) -- compression id, packet size + local rate = r:u32be() / 65536 + if version == 1 then + r:skip(16) + elseif version == 2 then + r:skip(4) + rate = r:f64be() + channels = r:u32be() + r:skip(4) + bits = r:u32be() + local lpcmFlags = r:u32be() + r:skip(8) + if typ == "lpcm" then + t.pcm = { + bits = bits, + float = bit32.band(lpcmFlags, 1) ~= 0, + little = bit32.band(lpcmFlags, 2) == 0, + } + end + end + t.channels, t.sampleRate, t.bitsPerSample = channels, rate, bits + if not t.pcm and t.codec == "pcm" then + local B: { [string]: number } = { sowt = 16, twos = 16, ["raw "] = 8, in24 = 24, in32 = 32, fl32 = 32, fl64 = 64 } + t.pcm = { + bits = B[typ] or bits, + float = typ == "fl32" or typ == "fl64", + little = typ == "sowt", + } + end + childStart = r.pos + elseif kind == "video" then + r:skip(16) + t.width = r:u16be() + t.height = r:u16be() + r:skip(4 + 4 + 4 + 2 + 32 + 2 + 2) + childStart = r.pos + -- QuickTime depth and colour table (palettised codecs: QuickTime RLE / SMC, Cinepak, ...) + local depth, pal = QtPalette.read(b, e.start, e.stop, if typ == "cvid" then "cinepak" else typ) + t.bitsPerPixel = depth + t.palette = pal + if pal and not r.err and readu16be(b, childStart - 2) == 0 and childStart + 8 <= e.stop then + childStart = math.min(e.stop, childStart + 8 + (readu16be(b, childStart + 6) + 1) * 8) + end + else + childStart = r.pos + end + if r.err then + t.entryBoxes = {} + return + end + local kids = Box.list(b, childStart, e.stop, typ) + t.entryBoxes = kids + -- QuickTime puts the codec boxes inside 'wave' + local all = table.clone(kids) + local wave = Box.child({ type = "", start = 0, size = 0, data = 0, stop = 0, children = kids } :: any, "wave") + if wave and wave.children then + for _, c in wave.children :: { Box.Box } do + table.insert(all, c) + end + end + local holder = { type = "", start = 0, size = 0, data = 0, stop = 0, children = all } :: any + local esds = Box.child(holder, "esds") + if esds then + local oti, dsi, avg = Demux.esds(b, esds) + t.objectType = oti + if oti and OTI[oti] then + t.codec = OTI[oti] + end + t.config = dsi + if avg and avg > 0 then + t.bitrate = avg + end + end + if typ == "alac" then + local a = Box.child(holder, "alac") + if a then + t.config = payload(b, a, 4) + end + end + for _, name in CONFIG_BOX do + local c = Box.child(holder, name) + if c then + t.config = payload(b, c, if FULL_CONFIG[name] then 4 else 0) + break + end + end +end + +local function track(b: buffer, trak: Box.Box, movieTimescale: number, trex: { [number]: any }, o: Options): (Track?, Err.Err?) + local tkhd = Box.child(trak, "tkhd") + local mdia = Box.child(trak, "mdia") + if not tkhd or not mdia then + return nil, Err.new(Err.CORRUPT, "trak without tkhd / mdia", trak.start) + end + local t: Track = { + id = 0, kind = "data", codec = "", entry = "", handler = "", timescale = 1, duration = 0, mediaDuration = 0, + entryBoxes = {}, skip = 0, delay = 0, sampleCount = 0, offsets = {}, sizes = {}, dts = {}, durations = {}, + } + do + local r = reader(b, tkhd) + local v = r:u8() + r:skip(3) + if v == 1 then + r:skip(16) + t.id = r:u32be() + r:skip(4 + 8) + else + r:skip(8) + t.id = r:u32be() + r:skip(4 + 4) + end + r:skip(8 + 2 + 2 + 2 + 2 + 36) + local w, h = r:u32be() / 65536, r:u32be() / 65536 + if r.err then + return nil, r.err + end + if w > 0 and h > 0 then + t.width, t.height = math.floor(w), math.floor(h) + end + end + local mdhd = Box.child(mdia, "mdhd") + if mdhd then + local r = reader(b, mdhd) + local v = r:u8() + r:skip(3) + if v == 1 then + r:skip(16) + t.timescale = r:u32be() + t.mediaDuration = r:u64be() + else + r:skip(8) + t.timescale = r:u32be() + t.mediaDuration = r:u32be() + end + local lang = r:u16be() + if not r.err and lang ~= 0 and lang ~= 0x7FFF then + t.language = string.char( + 96 + bit32.band(bit32.rshift(lang, 10), 31), + 96 + bit32.band(bit32.rshift(lang, 5), 31), + 96 + bit32.band(lang, 31) + ) + end + if t.timescale == 0 then + t.timescale = 1 + end + end + local hdlr = Box.child(mdia, "hdlr") + if hdlr and hdlr.data + 12 <= hdlr.stop then + t.handler = readstring(b, hdlr.data + 8, 4) + end + t.kind = HANDLER_KIND[t.handler] or "data" + local stbl = Box.path(mdia, "minf/stbl") + if not stbl then + return nil, Err.new(Err.CORRUPT, "track " .. t.id .. " has no sample table", mdia.start) + end + local stsd = Box.child(stbl, "stsd") + if stsd and stsd.data + 8 <= stsd.stop then + local entries = Box.list(b, stsd.data + 8, stsd.stop, "stsd") + if entries[1] then + sampleEntry(b, entries[1], t.handler, t) + end + t.sampleEntries = entries + end + local elst = Box.path(trak, "edts/elst") + if elst then + local r = reader(b, elst) + local v = r:u8() + r:skip(3) + local n = r:u32be() + if n <= (elst.stop - elst.data) // 12 then + local edits: { Edit } = {} + for _ = 1, n do + local dur: number, mt: number + if v == 1 then + dur, mt = r:u64be(), r:i64be() :: number + else + dur, mt = r:u32be(), r:i32be() :: number + end + local rate = r:i32be() / 65536 + if r.err then + break + end + table.insert(edits, { duration = dur, mediaTime = mt, rate = rate }) + end + t.edits = edits + local play = 0 + local started = false + for _, ed in edits do + if ed.mediaTime == -1 then + if not started then + t.delay += ed.duration + end + else + if not started then + t.skip = ed.mediaTime + started = true + end + play += ed.duration * t.timescale / math.max(1, movieTimescale) + end + end + if started and play > 0 then + t.playDuration = math.floor(play + 0.5) + end + end + end + local maxSamples = o.maxSamples or 2 ^ 25 + local sizes = t.sizes + local count = 0 + local stsz = Box.child(stbl, "stsz") + local stz2 = Box.child(stbl, "stz2") + if stsz then + local r = reader(b, stsz) + r:skip(4) + local fixed = r:u32be() + count = r:u32be() + if r.err then + return nil, r.err + end + if count > maxSamples then + return nil, Err.new(Err.LIMIT, string.format("track %d has %d samples (limit %d)", t.id, count, maxSamples), stsz.start) + end + if fixed ~= 0 then + for i = 1, count do + sizes[i] = fixed + end + else + if count * 4 > r:remaining() then + return nil, Err.new(Err.TRUNCATED, "stsz table runs past its box", stsz.start) + end + for i = 1, count do + sizes[i] = r:u32be() + end + end + elseif stz2 then + local r = reader(b, stz2) + r:skip(4 + 3) + local fieldSize = r:u8() + count = r:u32be() + if r.err then + return nil, r.err + end + if fieldSize ~= 4 and fieldSize ~= 8 and fieldSize ~= 16 then + return nil, Err.new(Err.CORRUPT, "bad stz2 field size " .. fieldSize, stz2.start) + end + if count * fieldSize / 8 > r:remaining() + 1 then + return nil, Err.new(Err.TRUNCATED, "stz2 table runs past its box", stz2.start) + end + for i = 1, count do + if fieldSize == 16 then + sizes[i] = r:u16be() + elseif fieldSize == 8 then + sizes[i] = r:u8() + else + local byte = r:peekU8() + if i % 2 == 1 then + sizes[i] = bit32.rshift(math.max(byte, 0), 4) + else + sizes[i] = bit32.band(math.max(byte, 0), 15) + r:skip(1) + end + end + end + end + local dts, durs = t.dts, t.durations + local stts = Box.child(stbl, "stts") + if stts and count > 0 then + local r = reader(b, stts) + r:skip(4) + local n = r:u32be() + if n * 8 > r:remaining() then + return nil, Err.new(Err.TRUNCATED, "stts table runs past its box", stts.start) + end + local i, time = 1, 0 + for _ = 1, n do + local c, d = r:u32be(), r:u32be() + for _ = 1, c do + if i > count then + break + end + dts[i], durs[i] = time, d + time += d + i += 1 + end + end + -- fewer stts entries than samples: repeat the last duration + local last = if i > 1 then durs[i - 1] else 0 + while i <= count do + dts[i], durs[i] = time, last + time += last + i += 1 + end + else + for i = 1, count do + dts[i], durs[i] = 0, 0 + end + end + local ctts = Box.child(stbl, "ctts") + if ctts and count > 0 then + local r = reader(b, ctts) + local v = r:u8() + r:skip(3) + local n = r:u32be() + if n * 8 <= r:remaining() then + local cts = table.create(count, 0) + local i = 1 + for _ = 1, n do + local c = r:u32be() + local off = if v == 1 then r:i32be() else r:u32be() + if v == 0 and off >= 2147483648 then + off -= 4294967296 -- writers put negative offsets in version 0 too + end + for _ = 1, c do + if i > count then + break + end + cts[i] = off + i += 1 + end + end + t.cts = cts + end + end + local stss = Box.child(stbl, "stss") + if stss then + local r = reader(b, stss) + r:skip(4) + local n = r:u32be() + if n * 4 <= r:remaining() then + local sync = {} + for _ = 1, n do + sync[r:u32be()] = true + end + t.sync = sync + end + end + local stco = Box.child(stbl, "stco") + local co64 = Box.child(stbl, "co64") + local chunks: { number } = {} + if stco or co64 then + local box = (stco or co64) :: Box.Box + local r = reader(b, box) + r:skip(4) + local n = r:u32be() + local w = if co64 then 8 else 4 + if n * w > r:remaining() then + return nil, Err.new(Err.TRUNCATED, "chunk offset table runs past its box", box.start) + end + for i = 1, n do + chunks[i] = if co64 then r:u64be() else r:u32be() + end + end + local stsc = Box.child(stbl, "stsc") + local offsets = t.offsets + if count > 0 then + if not stsc or #chunks == 0 then + return nil, Err.new(Err.CORRUPT, "track " .. t.id .. " has samples but no stsc / stco", stbl.start) + end + local r = reader(b, stsc) + r:skip(4) + local n = r:u32be() + if n * 12 > r:remaining() then + return nil, Err.new(Err.TRUNCATED, "stsc table runs past its box", stsc.start) + end + local first: { number }, per: { number }, desc: { number } = {}, {}, {} + for k = 1, n do + first[k], per[k], desc[k] = r:u32be(), r:u32be(), r:u32be() + end + local sdi: { number }? = nil + if n > 0 then + for k = 1, n do + if desc[k] ~= desc[1] then + sdi = table.create(count, 1) + end + end + end + local i = 1 + local base = 0 -- added by the caller (the file's offset in the buffer) + for k = 1, n do + local c0 = first[k] + local c1 = if k < n then first[k + 1] - 1 else #chunks + if c0 < 1 then + return nil, Err.new(Err.CORRUPT, "stsc first chunk 0", stsc.start) + end + for c = c0, math.min(c1, #chunks) do + local off = chunks[c] + base + for _ = 1, per[k] do + if i > count then + break + end + offsets[i] = off + if sdi then + sdi[i] = desc[k] + end + off += sizes[i] + i += 1 + end + if i > count then + break + end + end + if i > count then + break + end + end + if i <= count then + return nil, Err.new(Err.CORRUPT, string.format("track %d: the chunks hold %d of %d samples", t.id, i - 1, count), stsc.start) + end + t.sampleDescription = sdi + end + t.sampleCount = count + -- QuickTime PCM: one "sample" per sample frame (constant size, duration 1). Regroup into packets of up to 1024 + -- frames within each chunk (as ffmpeg does), so a packet is a useful amount of audio. + if t.kind == "audio" and count > 1 and not t.cts and not t.sync then + local fixed = sizes[1] + local uniform = fixed > 0 + for i = 1, count do + if sizes[i] ~= fixed or durs[i] ~= 1 then + uniform = false + break + end + end + if uniform then + local no, ns, nd, nu = {}, {}, {}, {} + local i = 1 + while i <= count do + local k = 1 + while k < 1024 and i + k <= count and offsets[i + k] == offsets[i] + k * fixed do + k += 1 + end + table.insert(no, offsets[i]) + table.insert(ns, k * fixed) + table.insert(nd, dts[i]) + table.insert(nu, k) + i += k + end + t.offsets, t.sizes, t.dts, t.durations = no, ns, nd, nu + t.sampleCount = #no + t.frameSize = fixed + t.sampleDescription = nil + end + end + t.trex = trex[t.id] + return t, nil +end + +local function fragments(b: buffer, fileBase: number, top: { Box.Box }, byId: { [number]: Track }, o: Options): Err.Err? + local maxSamples = o.maxSamples or 2 ^ 25 + for _, moof in top do + if moof.type ~= "moof" then + continue + end + local moofStart = moof.start - fileBase -- file offsets (r.base is added at the end) + local prevEnd = moofStart + for _, traf in Box.childrenOf(moof, "traf") do + local tfhd = Box.child(traf, "tfhd") + if not tfhd then + continue + end + local r = reader(b, tfhd) + r:skip(1) + local flags = r:u24be() + local id = r:u32be() + local t = byId[id] + if r.err or not t then + continue + end + local trex = t.trex or {} + local base + if bit32.band(flags, 0x1) ~= 0 then + base = r:u64be() + elseif bit32.band(flags, 0x20000) ~= 0 then + base = moofStart + else + base = prevEnd + end + if bit32.band(flags, 0x2) ~= 0 then + r:skip(4) + end + local defDur = if bit32.band(flags, 0x8) ~= 0 then r:u32be() else (trex.duration or 0) + local defSize = if bit32.band(flags, 0x10) ~= 0 then r:u32be() else (trex.size or 0) + local defFlags = if bit32.band(flags, 0x20) ~= 0 then r:u32be() else (trex.flags or 0) + if r.err then + return r.err + end + local n0 = t.sampleCount + local time = if n0 > 0 then t.dts[n0] + t.durations[n0] else 0 + local tfdt = Box.child(traf, "tfdt") + if tfdt then + local q = reader(b, tfdt) + local v = q:u8() + q:skip(3) + local bt = if v == 1 then q:u64be() else q:u32be() + if not q.err then + time = bt + end + end + local dataPos = base + for _, trun in Box.childrenOf(traf, "trun") do + local q = reader(b, trun) + local v = q:u8() + local tf = q:u24be() + local n = q:u32be() + if q.err then + return q.err + end + if t.sampleCount + n > maxSamples then + return Err.new(Err.LIMIT, "too many fragment samples", trun.start) + end + if bit32.band(tf, 0x1) ~= 0 then + dataPos = base + q:i32be() + end + local firstFlags = if bit32.band(tf, 0x4) ~= 0 then q:u32be() else nil + local per = 0 + for _, bit in { 0x100, 0x200, 0x400, 0x800 } do + if bit32.band(tf, bit) ~= 0 then + per += 4 + end + end + if n * per > q:remaining() then + return Err.new(Err.TRUNCATED, "trun table runs past its box", trun.start) + end + for k = 1, n do + local dur = if bit32.band(tf, 0x100) ~= 0 then q:u32be() else defDur + local size = if bit32.band(tf, 0x200) ~= 0 then q:u32be() else defSize + local sf = if bit32.band(tf, 0x400) ~= 0 then q:u32be() else (if k == 1 and firstFlags then firstFlags else defFlags) + local cto = 0 + if bit32.band(tf, 0x800) ~= 0 then + cto = if v == 1 then q:i32be() else q:u32be() + end + local i = t.sampleCount + 1 + t.sampleCount = i + t.offsets[i] = dataPos + t.sizes[i] = size + t.dts[i] = time + t.durations[i] = dur + if cto ~= 0 or t.cts then + if not t.cts then + t.cts = table.create(i - 1, 0) + end + (t.cts :: { number })[i] = cto + end + -- sample_is_non_sync_sample (bit 16) + local nonSync = bit32.band(sf, 0x10000) ~= 0 + if nonSync then + if not t.sync then + local s = {} + for j = 1, i - 1 do + s[j] = true + end + t.sync = s + end + elseif t.sync then + (t.sync :: any)[i] = true + end + time += dur + dataPos += size + end + prevEnd = dataPos + end + end + end + return nil +end + +type Movie = { + brand: string?, + minor: number?, + compatible: { string }, + timescale: number, + duration: number, -- seconds + tracks: { Track }, + boxes: { Box.Box }, + moov: Box.Box?, + fragmented: boolean, +} + +function Demux.parse(r: Bytes.Reader, opts: Options?): (Movie?, Err.Err?) + local o: Options = opts or {} + local b = r.buf + local top, terr = Box.list(b, r.base, r.limit) + if #top == 0 then + return nil, terr or Err.new(Err.CORRUPT, "no boxes", r.base) + end + local m: Movie = { compatible = {}, timescale = 1000, duration = 0, tracks = {}, boxes = top, fragmented = false } + local ftyp = Box.child({ children = top } :: any, "ftyp") + if ftyp and ftyp.data + 8 <= ftyp.stop then + m.brand = readstring(b, ftyp.data, 4) + m.minor = Box.be32(b, ftyp.data + 4) + local p = ftyp.data + 8 + while p + 4 <= ftyp.stop do + table.insert(m.compatible, readstring(b, p, 4)) + p += 4 + end + end + local moov = Box.child({ children = top } :: any, "moov") + m.moov = moov + if not moov then + return m, nil -- an image file (HEIF / AVIF) or a fragment: no tracks + end + local mvhd = Box.child(moov, "mvhd") + local movieDuration = 0 + if mvhd then + local q = reader(b, mvhd) + local v = q:u8() + q:skip(3) + if v == 1 then + q:skip(16) + m.timescale = q:u32be() + movieDuration = q:u64be() + else + q:skip(8) + m.timescale = q:u32be() + movieDuration = q:u32be() + end + if q.err or m.timescale == 0 then + m.timescale = 1000 + end + end + local trex = {} + local mvex = Box.child(moov, "mvex") + if mvex then + m.fragmented = true + for _, x in Box.childrenOf(mvex, "trex") do + local q = reader(b, x) + q:skip(4) + local id = q:u32be() + q:skip(4) + local d = { duration = q:u32be(), size = q:u32be(), flags = q:u32be() } + if not q.err then + trex[id] = d + end + end + end + local byId = {} + for _, trak in Box.childrenOf(moov, "trak") do + local t, err = track(b, trak, m.timescale, trex, o) + if not t then + return nil, err + end + table.insert(m.tracks, t) + byId[t.id] = t + end + if m.fragmented then + local ferr = fragments(b, r.base, top, byId, o) + if ferr then + return nil, ferr + end + end + -- durations; drop samples outside the buffer (a truncated file) but keep what is there + for _, t in m.tracks do + local n = t.sampleCount + local ticks = t.mediaDuration + if n > 0 then + ticks = math.max(ticks, t.dts[n] + t.durations[n]) + end + t.mediaDuration = ticks + t.duration = ticks / t.timescale + for i = 1, n do + local off = t.offsets[i] + if off < 0 or off + t.sizes[i] > r.limit - r.base then + t.sampleCount = i - 1 + t.truncated = true + break + end + end + -- the tables hold file offsets; make them buffer offsets + local base = r.base + if base ~= 0 then + local offs = t.offsets + for i = 1, t.sampleCount do + offs[i] += base + end + end + end + m.duration = movieDuration / m.timescale + if m.duration == 0 then + for _, t in m.tracks do + m.duration = math.max(m.duration, t.duration) + end + end + return m, nil +end + +return Demux +end +__FILES["containers/IsoBmff/Meta"] = function() + +-- containers/IsoBmff/Meta: the metadata boxes. HEIF / AVIF items (ISO/IEC 23008-12: pitm, iinf / infe, iloc +-- versions 0 - 2, iref, iprp / ipco / ipma, idat; the common properties ispe / pixi / colr / irot / imir / clap / auxC +-- decoded, codec configurations av1C / hvcC / avcC kept raw) and the iTunes tags (udta / meta / ilst: text, trkn / +-- disk, tmpo / cpil, gnre, covr pictures, '----' freeform), plus the ilst writer used by the muxer. +-- Never throws. +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Box = __include("containers/IsoBmff/Box") + +local readstring = buffer.readstring + +local Meta = {} + +local function reader(b: buffer, box: Box.Box): Bytes.Reader + return Bytes.reader(b, box.data, box.stop - box.data) +end + +local function uint(r: Bytes.Reader, size: number): number + if size == 0 then + return 0 + elseif size == 4 then + return r:u32be() + elseif size == 8 then + return r:u64be() + elseif size == 2 then + return r:u16be() + elseif size == 1 then + return r:u8() + end + r:fail(Err.CORRUPT, "bad iloc field size " .. size) + return 0 +end + +type Property = { type: string, box: Box.Box, [string]: any } +type Item = { + id: number, + type: string, -- "av01", "hvc1", "grid", "Exif", "mime", ... + name: string, + contentType: string?, + hidden: boolean, + construction: number, -- iloc construction method (0 file offset, 1 idat, 2 item) + baseOffset: number, + extents: { { offset: number, length: number } }, + properties: { Property }, -- in ipma order + essential: { [number]: boolean }, -- by index into properties + refs: { [string]: { number } }, -- iref type -> item ids (dimg, thmb, auxl, cdsc, ...) +} +type Items = { + primary: number?, + items: { [number]: Item }, + order: { number }, -- item ids in iinf order + idat: Box.Box?, + properties: { Property }, -- ipco, in order +} + +local function property(b: buffer, box: Box.Box): Property + local p: Property = { type = box.type, box = box } + local r = reader(b, box) + local t = box.type + if t == "ispe" then + r:skip(4) + p.width, p.height = r:u32be(), r:u32be() + elseif t == "pixi" then + r:skip(4) + local n = r:u8() + local bits = {} + for i = 1, math.min(n, 16) do + bits[i] = r:u8() + end + p.bits = bits + elseif t == "colr" then + local ct = r:string(4) + p.colourType = ct + if ct == "nclx" then + p.primaries, p.transfer, p.matrix = r:u16be(), r:u16be(), r:u16be() + p.fullRange = bit32.band(r:u8(), 0x80) ~= 0 + elseif ct == "rICC" or ct == "prof" then + p.icc = r:bytes(r:remaining()) + end + elseif t == "irot" then + p.angle = bit32.band(r:u8(), 3) * 90 + elseif t == "imir" then + p.axis = bit32.band(r:u8(), 1) + elseif t == "clap" then + local function frac(): number + local n, d = r:i32be(), r:u32be() + return if d == 0 then 0 else n / d + end + p.width, p.height, p.horizOff, p.vertOff = frac(), frac(), frac(), frac() + elseif t == "auxC" then + r:skip(4) + p.auxType = r:cstring() + else + local n = box.stop - box.data + local cfg = buffer.create(math.max(0, n)) + if n > 0 then + buffer.copy(cfg, 0, b, box.data, n) + end + p.config = cfg + end + return p +end + +function Meta.items(b: buffer, meta: Box.Box): (Items?, Err.Err?) + local out: Items = { items = {}, order = {}, properties = {} } + local pitm = Box.child(meta, "pitm") + if pitm then + local r = reader(b, pitm) + local v = r:u8() + r:skip(3) + out.primary = if v == 0 then r:u16be() else r:u32be() + end + local iinf = Box.child(meta, "iinf") + if iinf then + for _, infe in Box.childrenOf(iinf, "infe") do + local r = reader(b, infe) + local v = r:u8() + local flags = r:u24be() + local it: Item = { + id = 0, type = "", name = "", hidden = bit32.band(flags, 1) ~= 0, construction = 0, baseOffset = 0, + extents = {}, properties = {}, essential = {}, refs = {}, + } + if v >= 2 then + it.id = if v == 2 then r:u16be() else r:u32be() + r:skip(2) + it.type = r:string(4) + it.name = r:cstring() + if it.type == "mime" and r:remaining() > 0 then + it.contentType = r:cstring() + end + else + it.id = r:u16be() + r:skip(2) + it.name = r:cstring() + it.contentType = r:cstring() + it.type = "mime" + end + if r.err and it.id == 0 then + return nil, r.err + end + out.items[it.id] = it + table.insert(out.order, it.id) + end + end + local iloc = Box.child(meta, "iloc") + if iloc then + local r = reader(b, iloc) + local v = r:u8() + r:skip(3) + local a, c = r:u8(), r:u8() + local offSize, lenSize, baseSize = bit32.rshift(a, 4), bit32.band(a, 15), bit32.rshift(c, 4) + local idxSize = if v >= 1 then bit32.band(c, 15) else 0 + local n = if v < 2 then r:u16be() else r:u32be() + if r.err then + return nil, r.err + end + for _ = 1, n do + local id = if v < 2 then r:u16be() else r:u32be() + local method = 0 + if v >= 1 then + method = bit32.band(r:u16be(), 15) + end + r:skip(2) -- data reference index + local base = uint(r, baseSize) + local ne = r:u16be() + if r.err then + return nil, r.err + end + if ne * (offSize + lenSize + idxSize) > r:remaining() then + return nil, Err.new(Err.TRUNCATED, "iloc extents run past the box", iloc.start) + end + local extents = {} + for k = 1, ne do + if idxSize > 0 then + uint(r, idxSize) + end + extents[k] = { offset = base + uint(r, offSize), length = uint(r, lenSize) } + end + if r.err then + return nil, r.err + end + local it = out.items[id] + if not it then + it = { + id = id, type = "", name = "", hidden = false, construction = 0, baseOffset = 0, extents = {}, + properties = {}, essential = {}, refs = {}, + } :: Item + out.items[id] = it + table.insert(out.order, id) + end + it.construction, it.baseOffset, it.extents = method, base, extents + end + end + local iref = Box.child(meta, "iref") + if iref then + local v = Box.fullHeader(b, iref) + for _, ref in (iref.children or {}) :: { Box.Box } do + local r = reader(b, ref) + local from = if v == 0 then r:u16be() else r:u32be() + local n = r:u16be() + local to = {} + for k = 1, n do + to[k] = if v == 0 then r:u16be() else r:u32be() + end + local it = out.items[from] + if it and not r.err then + it.refs[ref.type] = to + end + end + end + local ipco = Box.path(meta, "iprp/ipco") + if ipco and ipco.children then + for i, pb in ipco.children :: { Box.Box } do + out.properties[i] = property(b, pb) + end + end + local ipma = Box.path(meta, "iprp/ipma") + if ipma then + local r = reader(b, ipma) + local v = r:u8() + local flags = r:u24be() + local n = r:u32be() + for _ = 1, n do + if r.err then + break + end + local id = if v < 1 then r:u16be() else r:u32be() + local na = r:u8() + local it = out.items[id] + for _ = 1, na do + local idx, ess + if bit32.band(flags, 1) ~= 0 then + local x = r:u16be() + idx, ess = bit32.band(x, 0x7FFF), x >= 0x8000 + else + local x = r:u8() + idx, ess = bit32.band(x, 0x7F), x >= 0x80 + end + local p = out.properties[idx] + if it and p and not r.err then + table.insert(it.properties, p) + if ess then + it.essential[#it.properties] = true + end + end + end + end + end + out.idat = Box.child(meta, "idat") + return out, nil +end + +function Meta.itemData(b: buffer, base: number, limit: number, items: Items, id: number): (buffer?, Err.Err?) + local it = items.items[id] + if not it then + return nil, Err.new(Err.CORRUPT, "no item " .. id) + end + local origin, stop + if it.construction == 0 then + origin, stop = base, limit + elseif it.construction == 1 then + local idat = items.idat + if not idat then + return nil, Err.new(Err.CORRUPT, "item " .. id .. " is in a missing idat") + end + origin, stop = idat.data, idat.stop + else + return nil, Err.new(Err.UNSUPPORTED, "item construction method " .. it.construction) + end + local total = 0 + for _, e in it.extents do + local len = e.length + if len == 0 then -- the whole rest of the file + len = stop - origin - e.offset + end + if e.offset < 0 or len < 0 or origin + e.offset + len > stop then + return nil, Err.new(Err.TRUNCATED, "item " .. id .. " runs past the end") + end + total += len + end + if total > 2 ^ 30 then + return nil, Err.new(Err.LIMIT, "item " .. id .. " is too big") + end + local out = buffer.create(total) + local p = 0 + for _, e in it.extents do + local len = if e.length == 0 then stop - origin - e.offset else e.length + buffer.copy(out, p, b, origin + e.offset, len) + p += len + end + return out, nil +end + +-- ilst item -> standard tag name +local TAG: { [string]: string } = { + ["\169nam"] = "title", ["\169ART"] = "artist", aART = "albumartist", ["\169alb"] = "album", ["\169day"] = "date", + ["\169gen"] = "genre", ["\169cmt"] = "comment", ["\169wrt"] = "composer", ["\169too"] = "encoder", + ["\169lyr"] = "lyrics", ["\169grp"] = "grouping", cprt = "copyright", desc = "description", ldes = "longdescription", + sonm = "titlesort", soar = "artistsort", soal = "albumsort", soaa = "albumartistsort", soco = "composersort", + tvsh = "show", ["\169st3"] = "subtitle", ["\169wrk"] = "work", ["\169mvn"] = "movement", purd = "purchasedate", + ["\169pub"] = "publisher", ["\169xyz"] = "location", +} +local TAG_ATOM: { [string]: string } = {} +for atom, name in TAG do + TAG_ATOM[name] = atom +end +Meta.TAG = TAG +Meta.TAG_ATOM = TAG_ATOM +-- freeform (----) names: tags keys are lower case; these keep their usual spelling when written back +local FREEFORM: { [string]: string } = { itunsmpb = "iTunSMPB", itunnorm = "iTunNORM", itunes_cddb_ids = "iTunes_CDDB_IDs" } + +-- the ID3v1 genres gnre indexes (1-based in gnre) +local GENRES = { + "Blues", "Classic Rock", "Country", "Dance", "Disco", "Funk", "Grunge", "Hip-Hop", "Jazz", "Metal", "New Age", + "Oldies", "Other", "Pop", "R&B", "Rap", "Reggae", "Rock", "Techno", "Industrial", "Alternative", "Ska", + "Death Metal", "Pranks", "Soundtrack", "Euro-Techno", "Ambient", "Trip-Hop", "Vocal", "Jazz+Funk", "Fusion", + "Trance", "Classical", "Instrumental", "Acid", "House", "Game", "Sound Clip", "Gospel", "Noise", "AlternRock", + "Bass", "Soul", "Punk", "Space", "Meditative", "Instrumental Pop", "Instrumental Rock", "Ethnic", "Gothic", + "Darkwave", "Techno-Industrial", "Electronic", "Pop-Folk", "Eurodance", "Dream", "Southern Rock", "Comedy", "Cult", + "Gangsta", "Top 40", "Christian Rap", "Pop/Funk", "Jungle", "Native American", "Cabaret", "New Wave", + "Psychadelic", "Rave", "Showtunes", "Trailer", "Lo-Fi", "Tribal", "Acid Punk", "Acid Jazz", "Polka", "Retro", + "Musical", "Rock & Roll", "Hard Rock", +} + +type Picture = { mime: string, data: buffer } + +function Meta.tags(b: buffer, ilst: Box.Box?): ({ [string]: string }, { Picture }) + local tags: { [string]: string } = {} + local pics: { Picture } = {} + if not ilst or not ilst.children then + return tags, pics + end + for _, item in ilst.children :: { Box.Box } do + local typ = item.type + local freeName: string? = nil + if typ == "----" then + local nm = Box.child(item, "name") + if nm and nm.data + 4 <= nm.stop then + freeName = readstring(b, nm.data + 4, nm.stop - nm.data - 4) + end + end + for _, d in Box.childrenOf(item, "data") do + if d.data + 8 > d.stop then + continue + end + local kind = bit32.band(Box.be32(b, d.data), 0xFFFFFF) + local p, n = d.data + 8, d.stop - d.data - 8 + if typ == "trkn" or typ == "disk" then + if n >= 6 then + local num = Box.be32(b, p) % 65536 + local total = Box.be32(b, p + 2) % 65536 + local key = if typ == "trkn" then "track" else "disc" + if num > 0 then + tags[key] = tostring(num) + end + if total > 0 then + tags[key .. "total"] = tostring(total) + end + end + elseif typ == "gnre" then + if n >= 2 then + local g = GENRES[Box.be32(b, p - 2) % 65536] + if g and not tags.genre then + tags.genre = g + end + end + elseif typ == "tmpo" then + if n >= 2 then + tags.bpm = tostring(Box.be32(b, p - 2) % 65536) + end + elseif typ == "cpil" or typ == "pgap" then + if n >= 1 then + tags[if typ == "cpil" then "compilation" else "gapless"] = tostring(buffer.readu8(b, p)) + end + elseif typ == "covr" then + local mime = if kind == 14 then "image/png" elseif kind == 27 then "image/bmp" else "image/jpeg" + local data = buffer.create(n) + buffer.copy(data, 0, b, p, n) + table.insert(pics, { mime = mime, data = data }) + elseif kind == 1 or kind == 0 then + local s = readstring(b, p, n) + local key = if freeName then string.lower(freeName) else TAG[typ] or string.lower(typ) + if typ == "\169gen" or not tags[key] then + tags[key] = s + end + end + end + end + return tags, pics +end + +local function box(w: Bytes.Writer, typ: string, body: (Bytes.Writer) -> ()) + local start = w:tell() + w:u32be(0) + w:string(typ) + body(w) + w:setU32be(start, w:tell() - start) +end +Meta.box = box + +local function dataBox(w: Bytes.Writer, kind: number, value: string | buffer) + box(w, "data", function() + w:u32be(kind) + w:u32be(0) + if type(value) == "string" then + w:string(value) + else + w:bytes(value) + end + end) +end + +local function num(s: string?): number + local v = tonumber(s or "") + if not v then + return 0 + end + return math.clamp(math.floor(v), 0, 65535) +end + +function Meta.writeIlst(w: Bytes.Writer, tags: { [string]: string }, pictures: { Picture }?) + box(w, "ilst", function() + local keys = {} + for k in tags do + table.insert(keys, k) + end + table.sort(keys) + local done: { [string]: boolean } = {} + for _, k in keys do + local v = tags[k] + if type(v) ~= "string" or done[k] then + continue + end + if k == "track" or k == "tracktotal" or k == "disc" or k == "disctotal" then + local base = if k == "track" or k == "tracktotal" then "track" else "disc" + if done[base] then + continue + end + done[base] = true + local atom = if base == "track" then "trkn" else "disk" + local n, total = num(tags[base]), num(tags[base .. "total"]) + box(w, atom, function() + box(w, "data", function() + w:u32be(0) + w:u32be(0) + w:u16be(0) + w:u16be(n) + w:u16be(total) + if atom == "trkn" then + w:u16be(0) + end + end) + end) + elseif k == "bpm" then + box(w, "tmpo", function() + box(w, "data", function() + w:u32be(21) + w:u32be(0) + w:u16be(num(v)) + end) + end) + elseif k == "compilation" or k == "gapless" then + box(w, if k == "compilation" then "cpil" else "pgap", function() + box(w, "data", function() + w:u32be(21) + w:u32be(0) + w:u8(if num(v) ~= 0 then 1 else 0) + end) + end) + elseif TAG_ATOM[k] then + box(w, TAG_ATOM[k], function() + dataBox(w, 1, v) + end) + else + box(w, "----", function() + box(w, "mean", function() + w:u32be(0) + w:string("com.apple.iTunes") + end) + box(w, "name", function() + w:u32be(0) + w:string(FREEFORM[k] or k) + end) + dataBox(w, 1, v) + end) + end + done[k] = true + end + if pictures and #pictures > 0 then + box(w, "covr", function() + for _, p in pictures :: { Picture } do + dataBox(w, if p.mime == "image/png" then 14 elseif p.mime == "image/bmp" then 27 else 13, p.data) + end + end) + end + end) +end + +-- udta / meta (hdlr mdir) / ilst +function Meta.writeUdta(w: Bytes.Writer, tags: { [string]: string }, pictures: { Picture }?) + box(w, "udta", function() + box(w, "meta", function() + w:u32be(0) + box(w, "hdlr", function() + w:u32be(0) + w:u32be(0) + w:string("mdir") + w:string("appl") + w:u32be(0) + w:u32be(0) + w:u8(0) + end) + Meta.writeIlst(w, tags, pictures) + end) + end) +end + +return Meta +end +__FILES["containers/IsoBmff/Mux"] = function() + +-- containers/IsoBmff/Mux: writes a progressive ISO BMFF / MP4 / M4A file (ISO/IEC 14496-12): ftyp, moov first ("fast +-- start"), the samples interleaved in chunks in one mdat, udta / meta / ilst tags; co64 past 4 GB. Audio and video +-- sample entries with their configuration box, plus raw child boxes. Never throws: bad specs return nil, Err.ARG. +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Meta = __include("containers/IsoBmff/Meta") + +local Mux = {} + +type MuxTrack = { + kind: "audio" | "video" | "subtitle" | "data", + entry: string, -- sample entry fourcc: "alac", "mp4a", "Opus", "fLaC", "avc1", "hvc1", "av01", "vp09", ... + timescale: number, -- ticks per second (audio: the sample rate) + samples: { buffer }?, -- one buffer per sample, or + data: buffer?, -- the samples back to back, with + sizes: { number }?, -- their sizes + durations: { number } | number, -- ticks per sample (or one constant) + cts: { number }?, -- composition offsets (video with B-frames) + sync: { [number]: boolean }?, -- sync samples (nil: all) + sampleRate: number?, + channels: number?, + bitsPerSample: number?, -- default 16 + width: number?, + height: number?, + config: buffer?, -- the codec configuration, written as the entry's configuration box + configBox: string?, -- its box type (default by entry: esds, alac, dOps, dfLa, avcC, hvcC, av1C, vpcC) + objectType: number?, -- esds objectTypeIndication (default 0x40, AAC) + bitrate: number?, -- esds average bitrate + boxes: { { type: string, data: buffer } }?, -- extra sample entry child boxes (raw payloads) + language: string?, -- ISO 639-2, default "und" + name: string?, -- hdlr name + skip: number?, -- media ticks to skip at the start (edit list media time: AAC priming) + playDuration: number?, -- media ticks to play (edit list) +} +type MuxSpec = { + brand: string?, -- default "isom" + minor: number?, + compatible: { string }?, + timescale: number?, -- movie timescale, default 1000 + tracks: { MuxTrack }, + tags: { [string]: string }?, + pictures: { Meta.Picture }?, + chunkDuration: number?, -- seconds of samples per chunk, default 1 +} + +local DEFAULT_CONFIG_BOX: { [string]: string } = { + mp4a = "esds", mp4v = "esds", alac = "alac", Opus = "dOps", fLaC = "dfLa", avc1 = "avcC", avc3 = "avcC", + hvc1 = "hvcC", hev1 = "hvcC", av01 = "av1C", vp08 = "vpcC", vp09 = "vpcC", ["ac-3"] = "dac3", ["ec-3"] = "dec3", +} +local FULL_BOX: { [string]: boolean } = { alac = true, dfLa = true, vpcC = true } +local HANDLER = { audio = "soun", video = "vide", subtitle = "sbtl", data = "meta" } + +local box = Meta.box + +local function lang(s: string?): number + local l = s or "und" + if #l ~= 3 then + l = "und" + end + local v = 0 + for i = 1, 3 do + v = v * 32 + bit32.band(string.byte(l, i) - 96, 31) + end + return v +end + +local function descriptor(w: Bytes.Writer, tag: number, body: (Bytes.Writer) -> ()) + local inner = Bytes.writer(64) + body(inner) + local n = inner:tell() + w:u8(tag) + -- 4-byte expandable length (the common iTunes / ffmpeg form) + w:u8(0x80 + bit32.band(bit32.rshift(n, 21), 127)) + w:u8(0x80 + bit32.band(bit32.rshift(n, 14), 127)) + w:u8(0x80 + bit32.band(bit32.rshift(n, 7), 127)) + w:u8(bit32.band(n, 127)) + w:bytes(inner.buf, 0, n) +end + +local function esds(w: Bytes.Writer, t: MuxTrack) + box(w, "esds", function() + w:u32be(0) + descriptor(w, 3, function(d) + d:u16be(0) -- ES_ID + d:u8(0) + descriptor(d, 4, function(c) + c:u8(t.objectType or 0x40) + c:u8(if t.kind == "video" then 0x11 else 0x15) -- streamType << 2 | upStream 0 | reserved 1 + c:u24be(0) + c:u32be(t.bitrate or 0) + c:u32be(t.bitrate or 0) + if t.config and buffer.len(t.config) > 0 then -- (MJPEG / MP3 have no decoder-specific info) + descriptor(c, 5, function(s) + s:bytes(t.config :: buffer) + end) + end + end) + descriptor(d, 6, function(s) + s:u8(2) + end) + end) + end) +end + +local function sampleEntry(w: Bytes.Writer, t: MuxTrack) + box(w, t.entry, function() + w:fill(0, 6) + w:u16be(1) -- data reference index + if t.kind == "audio" then + w:u16be(0) -- version + w:u16be(0) + w:u32be(0) + w:u16be(t.channels or 2) + w:u16be(t.bitsPerSample or 16) + w:u16be(0) + w:u16be(0) + local sr = t.sampleRate or t.timescale + w:u32be(if sr < 65536 then sr * 65536 else 0) + elseif t.kind == "video" then + w:fill(0, 16) + w:u16be(t.width or 0) + w:u16be(t.height or 0) + w:u32be(0x00480000) + w:u32be(0x00480000) + w:u32be(0) + w:u16be(1) -- frame count + w:fill(0, 32) -- compressor name + w:u16be(0x18) + w:i16be(-1) + end + local cb = t.configBox or DEFAULT_CONFIG_BOX[t.entry] + if t.config and cb then + if cb == "esds" then + esds(w, t) + else + box(w, cb, function() + if FULL_BOX[cb] then + w:u32be(0) + end + w:bytes(t.config :: buffer) + end) + end + end + for _, x in t.boxes or {} do + box(w, x.type, function() + w:bytes(x.data) + end) + end + end) +end + +type Chunk = { track: number, first: number, count: number, time: number, offset: number } + +local function runs(n: number, value: (number) -> number): { { number } } + local out = {} + for i = 1, n do + local v = value(i) + local last = out[#out] + if last and last[2] == v then + last[1] += 1 + else + table.insert(out, { 1, v }) + end + end + return out +end + +type Prepared = { + t: MuxTrack, + n: number, + sizes: { number }, + dur: (number) -> number, + total: number, -- media ticks + chunks: { Chunk }, + sample: (number) -> (buffer, number), -- buffer, offset +} + +local function moov(w: Bytes.Writer, spec: MuxSpec, prep: { Prepared }, co64: boolean) + local mts = spec.timescale or 1000 + local function toMovie(p: Prepared, ticks: number): number + return math.floor(ticks * mts / p.t.timescale + 0.5) + end + local movieDur = 0 + for _, p in prep do + local play = p.t.playDuration or (p.total - (p.t.skip or 0)) + movieDur = math.max(movieDur, toMovie(p, play)) + end + box(w, "moov", function() + box(w, "mvhd", function() + w:u32be(0) + w:u32be(0) + w:u32be(0) + w:u32be(mts) + w:u32be(movieDur) + w:u32be(0x00010000) + w:u16be(0x0100) + w:fill(0, 10) + for _, v in { 0x00010000, 0, 0, 0, 0x00010000, 0, 0, 0, 0x40000000 } do + w:u32be(v) + end + w:fill(0, 24) + w:u32be(#prep + 1) + end) + for id, p in prep do + local t = p.t + local play = t.playDuration or (p.total - (t.skip or 0)) + box(w, "trak", function() + box(w, "tkhd", function() + w:u32be(3) -- enabled, in movie + w:u32be(0) + w:u32be(0) + w:u32be(id) + w:u32be(0) + w:u32be(toMovie(p, play)) + w:fill(0, 8) + w:u16be(0) + w:u16be(0) + w:u16be(if t.kind == "audio" then 0x0100 else 0) + w:u16be(0) + for _, v in { 0x00010000, 0, 0, 0, 0x00010000, 0, 0, 0, 0x40000000 } do + w:u32be(v) + end + w:u32be((t.width or 0) * 65536) + w:u32be((t.height or 0) * 65536) + end) + if t.skip or t.playDuration then + box(w, "edts", function() + box(w, "elst", function() + w:u32be(0) + w:u32be(1) + w:u32be(toMovie(p, play)) + w:u32be(t.skip or 0) + w:u32be(0x00010000) + end) + end) + end + box(w, "mdia", function() + box(w, "mdhd", function() + w:u32be(0) + w:u32be(0) + w:u32be(0) + w:u32be(t.timescale) + w:u32be(p.total) + w:u16be(lang(t.language)) + w:u16be(0) + end) + box(w, "hdlr", function() + w:u32be(0) + w:u32be(0) + w:string(HANDLER[t.kind] or "meta") + w:fill(0, 12) + w:cstring(t.name or (if t.kind == "audio" then "SoundHandler" elseif t.kind == "video" then "VideoHandler" else "DataHandler")) + end) + box(w, "minf", function() + if t.kind == "audio" then + box(w, "smhd", function() + w:u32be(0) + w:u32be(0) + end) + elseif t.kind == "video" then + box(w, "vmhd", function() + w:u32be(1) + w:fill(0, 8) + end) + else + box(w, "nmhd", function() + w:u32be(0) + end) + end + box(w, "dinf", function() + box(w, "dref", function() + w:u32be(0) + w:u32be(1) + box(w, "url ", function() + w:u32be(1) -- self-contained + end) + end) + end) + box(w, "stbl", function() + box(w, "stsd", function() + w:u32be(0) + w:u32be(1) + sampleEntry(w, t) + end) + local stts = runs(p.n, p.dur) + box(w, "stts", function() + w:u32be(0) + w:u32be(#stts) + for _, r in stts do + w:u32be(r[1]) + w:u32be(r[2]) + end + end) + local cts = t.cts + if cts then + local cr = runs(p.n, function(i) + return cts[i] or 0 + end) + box(w, "ctts", function() + w:u32be(0x01000000) -- version 1: signed offsets + w:u32be(#cr) + for _, r in cr do + w:u32be(r[1]) + w:i32be(r[2]) + end + end) + end + local sync = t.sync + if sync then + local list = {} + for i = 1, p.n do + if sync[i] then + table.insert(list, i) + end + end + box(w, "stss", function() + w:u32be(0) + w:u32be(#list) + for _, i in list do + w:u32be(i) + end + end) + end + local stsc = runs(#p.chunks, function(i) + return p.chunks[i].count + end) + box(w, "stsc", function() + w:u32be(0) + w:u32be(#stsc) + local c = 1 + for _, r in stsc do + w:u32be(c) + w:u32be(r[2]) + w:u32be(1) + c += r[1] + end + end) + box(w, "stsz", function() + w:u32be(0) + local fixed = p.sizes[1] or 0 + for i = 2, p.n do + if p.sizes[i] ~= fixed then + fixed = -1 + break + end + end + if fixed >= 0 and p.n > 0 then + w:u32be(fixed) + w:u32be(p.n) + else + w:u32be(0) + w:u32be(p.n) + for i = 1, p.n do + w:u32be(p.sizes[i]) + end + end + end) + box(w, if co64 then "co64" else "stco", function() + w:u32be(0) + w:u32be(#p.chunks) + for _, c in p.chunks do + if co64 then + w:u64be(c.offset) + else + w:u32be(c.offset) + end + end + end) + end) + end) + end) + end) + end + if spec.tags and next(spec.tags) or spec.pictures and #spec.pictures > 0 then + Meta.writeUdta(w, spec.tags or {}, spec.pictures) + end + end) +end + +function Mux.mux(spec: MuxSpec): (buffer?, Err.Err?) + if type(spec) ~= "table" or type(spec.tracks) ~= "table" or #spec.tracks == 0 then + return nil, Err.new(Err.ARG, "mux: expected { tracks = { ... } }") + end + local prep: { Prepared } = {} + local all: { Chunk } = {} + for k, t in spec.tracks do + if type(t) ~= "table" or type(t.entry) ~= "string" or #t.entry ~= 4 or type(t.timescale) ~= "number" or t.timescale <= 0 then + return nil, Err.new(Err.ARG, "mux: track " .. k .. " needs a 4-character entry and a timescale") + end + if not HANDLER[t.kind] then + return nil, Err.new(Err.ARG, "mux: track " .. k .. ": bad kind " .. tostring(t.kind)) + end + local n, sizes, sample + if t.samples then + local list = t.samples + n = #list + sizes = table.create(n, 0) + for i = 1, n do + if type(list[i]) ~= "buffer" then + return nil, Err.new(Err.ARG, "mux: track " .. k .. ": sample " .. i .. " is not a buffer") + end + sizes[i] = buffer.len(list[i]) + end + sample = function(i: number): (buffer, number) + return list[i], 0 + end + elseif t.data and t.sizes then + n = #t.sizes + sizes = t.sizes + local starts = table.create(n, 0) + local o = 0 + for i = 1, n do + starts[i] = o + o += sizes[i] + end + if o > buffer.len(t.data) then + return nil, Err.new(Err.ARG, "mux: track " .. k .. ": sizes exceed the data") + end + local data = t.data + sample = function(i: number): (buffer, number) + return data, starts[i] + end + else + return nil, Err.new(Err.ARG, "mux: track " .. k .. " needs samples or data + sizes") + end + local durs = t.durations + local dur + if type(durs) == "number" then + dur = function(_: number): number + return durs + end + elseif type(durs) == "table" then + dur = function(i: number): number + return durs[i] or 0 + end + else + return nil, Err.new(Err.ARG, "mux: track " .. k .. " needs durations") + end + local total = 0 + local chunks: { Chunk } = {} + local per = (spec.chunkDuration or 1) * t.timescale + local cur: Chunk? = nil + for i = 1, n do + if not cur or total - cur.time >= per then + cur = { track = k, first = i, count = 0, time = total, offset = 0 } + table.insert(chunks, cur :: Chunk) + table.insert(all, cur :: Chunk) + end + (cur :: Chunk).count += 1 + total += dur(i) + end + prep[k] = { t = t, n = n, sizes = sizes, dur = dur, total = total, chunks = chunks, sample = sample } + end + -- interleave the chunks by time + table.sort(all, function(a: Chunk, b: Chunk): boolean + local ta = a.time / prep[a.track].t.timescale + local tb = b.time / prep[b.track].t.timescale + if ta ~= tb then + return ta < tb + end + if a.track ~= b.track then + return a.track < b.track + end + return a.first < b.first + end) + local mdatSize = 0 + for _, c in all do + local p = prep[c.track] + for i = c.first, c.first + c.count - 1 do + mdatSize += p.sizes[i] + end + end + local co64 = mdatSize > 4294967295 - 2 ^ 24 + local w = Bytes.writer(mdatSize + 4096) + box(w, "ftyp", function() + w:string(spec.brand or "isom") + w:u32be(spec.minor or 0x200) + for _, c in spec.compatible or { spec.brand or "isom", "iso2", "mp41" } do + w:string(string.sub(c .. " ", 1, 4)) + end + end) + -- moov twice: the first pass measures it, the second has the real chunk offsets + local probe = Bytes.writer(4096) + moov(probe, spec, prep, co64) + local mdatHeader = if mdatSize + 8 > 4294967295 then 16 else 8 + local o = w:tell() + probe:tell() + mdatHeader + for _, c in all do + c.offset = o + local p = prep[c.track] + for i = c.first, c.first + c.count - 1 do + o += p.sizes[i] + end + end + moov(w, spec, prep, co64) + if mdatHeader == 16 then + w:u32be(1) + w:string("mdat") + w:u64be(mdatSize + 16) + else + w:u32be(mdatSize + 8) + w:string("mdat") + end + for _, c in all do + local p = prep[c.track] + for i = c.first, c.first + c.count - 1 do + local b, off = p.sample(i) + w:bytes(b, off, p.sizes[i]) + end + end + return w:finish(), nil +end + +return Mux +end +__FILES["containers/IsoBmff/QtPalette"] = function() + +-- containers/IsoBmff/QtPalette: the depth and colour table of a QuickTime video sample description (Apple QuickTime +-- File Format, "Video sample description": depth at byte 82, color table ID at 84, then the table when the ID is 0). +-- Used by the MOV demuxer and by Matroska's V_QUICKTIME tracks (whose CodecPrivate is the same description). Depths 1, +-- 2, 4 and 8 are palettised: the colour table from the description, the Macintosh default table (ID -1), or a grey +-- ramp (depths 33..40: the 0x20 bit marks grey). Written from the QuickTime documentation; the default tables are the +-- Macintosh system palettes (white first, a 6x6x6 cube, then red / green / blue / grey ramps). +-- Never throws. +local readu8, writeu32 = buffer.readu8, buffer.writeu32 + +local function readu16(b: buffer, o: number): number -- big-endian + return readu8(b, o) * 256 + readu8(b, o + 1) +end +local function readu32(b: buffer, o: number): number + return readu16(b, o) * 65536 + readu16(b, o + 2) +end + +local QtPalette = {} + +local function rgb(r: number, g: number, b: number): number + return r + g * 256 + b * 65536 + 0xFF000000 +end + +-- the Macintosh default colour tables: 2 / 4 / 16 entries (System 7 control panel), 256 (the system palette) +local SMALL: { [number]: { number } } = { + [1] = { 0xFFFFFF, 0x000000 }, + [2] = { 0xFFFFFF, 0xACACAC, 0x555555, 0x000000 }, + [4] = { + 0xFFFFFF, 0xFCF305, 0xFF6402, 0xDD0806, 0xF20884, 0x4600A5, 0x0000D4, 0x02ABEA, + 0x1FB714, 0x006411, 0x562C05, 0x90713A, 0xC0C0C0, 0x808080, 0x404040, 0x000000, + }, +} + +local function defaultTable(bits: number): buffer + local pal = buffer.create(1024) + local small = SMALL[bits] + if small then + for i, c in small do + writeu32(pal, (i - 1) * 4, rgb(c // 65536, (c // 256) % 256, c % 256)) + end + return pal + end + local i = 0 + for r = 5, 0, -1 do + for g = 5, 0, -1 do + for b = 5, 0, -1 do + if i < 215 then + writeu32(pal, i * 4, rgb(r * 51, g * 51, b * 51)) + end + i += 1 + end + end + end + -- ramps without the cube's multiples of 0x33: red, green, blue, grey; then black + local RAMP = { 0xEE, 0xDD, 0xBB, 0xAA, 0x88, 0x77, 0x55, 0x44, 0x22, 0x11 } + i = 215 + for ch = 0, 3 do + for _, v in RAMP do + local r = if ch == 0 or ch == 3 then v else 0 + local g = if ch == 1 or ch == 3 then v else 0 + local b = if ch == 2 or ch == 3 then v else 0 + writeu32(pal, i * 4, rgb(r, g, b)) + i += 1 + end + end + writeu32(pal, 255 * 4, rgb(0, 0, 0)) + return pal +end + +-- Cinepak's grey flag selects its own grey mode, so no grey palette is made for it +function QtPalette.read(b: buffer, start: number, stop: number, codec: string?): (number?, buffer?) + if start + 86 > stop or stop > buffer.len(b) then + return nil, nil + end + local raw = readu16(b, start + 82) + local id = readu16(b, start + 84) + local bits = raw % 32 + local grey = raw >= 32 and (raw // 32) % 2 == 1 + if bits ~= 1 and bits ~= 2 and bits ~= 4 and bits ~= 8 then + return raw, nil + end + if grey and codec == "cinepak" then + return raw, nil + end + if grey and bits > 1 and id ~= 0 then + local pal = buffer.create(1024) + local count = 2 ^ bits + local step = 256 // (count - 1) + local v = 255 + for i = 0, count - 1 do + writeu32(pal, i * 4, rgb(v, v, v)) + v = math.max(0, v - step) + end + return bits, pal + elseif id ~= 0 then + return bits, defaultTable(bits) + end + local pal = buffer.create(1024) + if start + 94 <= stop then + local first = readu32(b, start + 86) + local last = readu16(b, start + 92) + if first <= 255 and last <= 255 then + for i = first, last do + local o = start + 94 + (i - first) * 8 + if o + 8 > stop then + break + end + writeu32(pal, i * 4, rgb(readu8(b, o + 2), readu8(b, o + 4), readu8(b, o + 6))) + end + end + end + return bits, pal +end + +return QtPalette +end +__FILES["containers/MacFile"] = function() + +-- containers/MacFile: classic Mac OS files (a data fork, a resource fork and Finder info) as Archive entries, shared by +-- the Mac encodings (archive/binhex, archive/macbinary, archive/applesingle). The convention (unar's "visible forks"): +-- the data fork is the entry `name`, a non-empty resource fork is a second entry `name .. ".rsrc"` with +-- entry.fork = "resource"; both carry macType / macCreator (4-character strings), finderFlags, created / mtime (unix +-- seconds) and comment. Writers pair them back with collect(). +-- New code. Never throws. +local Err = __include("core/Err") +local Archive = __include("containers/Archive") + +local MacFile = {} + +type Info = { + name: string, + data: buffer, + rsrc: buffer, + type: string, -- 4 bytes ("\0\0\0\0" when unknown) + creator: string, + flags: number, -- Finder flags (16 bits) + created: number?, -- unix seconds + modified: number?, + comment: string?, +} + +local MAC_EPOCH = 2082844800 -- seconds from 1904-01-01 to 1970-01-01 + +function MacFile.fromMac(s: number): number? + return if s == 0 then nil else s - MAC_EPOCH +end + +function MacFile.toMac(unix: number?): number + if type(unix) ~= "number" or unix ~= unix then + return 0 + end + return math.clamp(math.floor(unix + MAC_EPOCH), 0, 0xFFFFFFFF) +end + +-- Mac OS Roman bytes 0x80..0xFF +local ROMAN = { + 0x00C4, 0x00C5, 0x00C7, 0x00C9, 0x00D1, 0x00D6, 0x00DC, 0x00E1, 0x00E0, 0x00E2, 0x00E4, 0x00E3, 0x00E5, 0x00E7, 0x00E9, 0x00E8, + 0x00EA, 0x00EB, 0x00ED, 0x00EC, 0x00EE, 0x00EF, 0x00F1, 0x00F3, 0x00F2, 0x00F4, 0x00F6, 0x00F5, 0x00FA, 0x00F9, 0x00FB, 0x00FC, + 0x2020, 0x00B0, 0x00A2, 0x00A3, 0x00A7, 0x2022, 0x00B6, 0x00DF, 0x00AE, 0x00A9, 0x2122, 0x00B4, 0x00A8, 0x2260, 0x00C6, 0x00D8, + 0x221E, 0x00B1, 0x2264, 0x2265, 0x00A5, 0x00B5, 0x2202, 0x2211, 0x220F, 0x03C0, 0x222B, 0x00AA, 0x00BA, 0x03A9, 0x00E6, 0x00F8, + 0x00BF, 0x00A1, 0x00AC, 0x221A, 0x0192, 0x2248, 0x2206, 0x00AB, 0x00BB, 0x2026, 0x00A0, 0x00C0, 0x00C3, 0x00D5, 0x0152, 0x0153, + 0x2013, 0x2014, 0x201C, 0x201D, 0x2018, 0x2019, 0x00F7, 0x25CA, 0x00FF, 0x0178, 0x2044, 0x20AC, 0x2039, 0x203A, 0xFB01, 0xFB02, + 0x2021, 0x00B7, 0x201A, 0x201E, 0x2030, 0x00C2, 0x00CA, 0x00C1, 0x00CB, 0x00C8, 0x00CD, 0x00CE, 0x00CF, 0x00CC, 0x00D3, 0x00D4, + 0xF8FF, 0x00D2, 0x00DA, 0x00DB, 0x00D9, 0x0131, 0x02C6, 0x02DC, 0x00AF, 0x02D8, 0x02D9, 0x02DA, 0x00B8, 0x02DD, 0x02DB, 0x02C7, +} +local FROM_UNICODE: { [number]: number } = {} +for i, u in ROMAN do + FROM_UNICODE[u] = 127 + i +end + +function MacFile.name(s: string): string + if not string.find(s, "[\128-\255]") then + return s + end + local out = table.create(#s) + for i = 1, #s do + local c = string.byte(s, i) + out[i] = if c < 128 then string.char(c) else utf8.char(ROMAN[c - 127]) + end + return table.concat(out) +end + +function MacFile.roman(s: string): string + if not string.find(s, "[\128-\255]") or not utf8.len(s) then + return s + end + local out = {} + for _, c in utf8.codes(s) do + table.insert(out, if c < 128 then string.char(c) else string.char(FROM_UNICODE[c] or 63)) + end + return table.concat(out) +end + +local function four(s: any): string + if type(s) ~= "string" then + return "\0\0\0\0" + end + return string.sub(s .. "\0\0\0\0", 1, 4) +end + +function MacFile.put(a: any, f: Info, noData: boolean?) + local common = { + macType = f.type, + macCreator = f.creator, + finderFlags = f.flags, + created = f.created, + mtime = f.modified, + comment = f.comment, + dir = false, + } + local e: any = table.clone(common) + e.name, e.size, e.data, e.fork = f.name, buffer.len(f.data), f.data, "data" + if not noData and (buffer.len(f.data) > 0 or buffer.len(f.rsrc) == 0) then + Archive.put(a, e) + end + if buffer.len(f.rsrc) > 0 then + local r: any = table.clone(common) + r.name, r.size, r.data, r.fork = f.name .. ".rsrc", buffer.len(f.rsrc), f.rsrc, "resource" + Archive.put(a, r) + end +end + +function MacFile.collect(value: any, name: string?): ({ Info }?, Err.Err?) + local files, err = Archive.files(value, name) + if not files then + return nil, err + end + local out: { Info } = {} + local byName: { [string]: Info } = {} + local function get(n: string, e: any): Info + local f = byName[n] + if not f then + f = { + name = n, + data = buffer.create(0), + rsrc = buffer.create(0), + type = four(e.macType), + creator = four(e.macCreator), + flags = if type(e.finderFlags) == "number" then bit32.band(e.finderFlags, 0xFFFF) else 0, + created = if type(e.created) == "number" then e.created else nil, + modified = if type(e.mtime) == "number" then e.mtime else nil, + comment = if type(e.comment) == "string" then e.comment else nil, + } + byName[n] = f + table.insert(out, f) + end + return f :: Info + end + -- data forks first, so a resource fork finds its file whatever the order + for _, it in files do + if it.entry.fork ~= "resource" then + get(it.name, it.entry).data = it.data + end + end + for _, it in files do + if it.entry.fork == "resource" then + local base = string.match(it.name, "^(.*)%.rsrc$") or it.name + get(base, it.entry).rsrc = it.data + end + end + return out, nil +end + +return MacFile +end +__FILES["containers/Ogg"] = @native function() + + + +-- containers/Ogg: the Ogg container (RFC 3533): a demuxer (absorbed from ogg-luau be9f604, same author, no third-party +-- code) and the muxer (Ogg/Mux, new). Packets are reassembled across pages per serial; seeking bisects byte offsets +-- to the page holding a granule. Never throws. +local Err = __include("core/Err") +local Page = __include("containers/Ogg/Page") +local Mux = __include("containers/Ogg/Mux") + +local readu8 = buffer.readu8 +type PageInfo = any -- Page.Info (the sibling module is untyped here: required through `script` in Roblox) + +local Ogg = {} +Ogg.Page = Page +Ogg.Mux = Mux +Ogg.muxer = Mux.new + +type Packet = { + data: buffer, -- the packet bytes are data[offset .. offset + size - 1] + offset: number, + size: number, + granule: number, -- the page granule if this is the last packet finishing on its page, else -1 + pageGranule: number, -- the granule of the page the packet finishes on (may be -1) + bos: boolean, -- first packet of the stream + eos: boolean, -- last packet of the stream (last packet finishing on an eos page) + pageOffset: number, -- byte offset of the page the packet finishes on + gap: boolean, -- data was lost before this packet (a missing page / bad CRC in between) +} + +type Stream = { + serial: number, + codec: string, -- "opus" | "flac" | "vorbis" | "theora" | "speex" | "skeleton" | "flac-old" | "unknown" + firstPacket: buffer, -- a copy of the identification packet + bosOffset: number, -- byte offset of the bos page + lastGranule: number, -- the last known granule of the stream (-1 if none) +} + +local Reader = {} +Reader.__index = Reader + +@native local function newReader(d: any, serial: number, start: number): any + return setmetatable({ + demux = d, + buf = d.buf, + serial = serial, + start = start, -- the bos page offset + pagePos = start, -- where to look for the next page + page = nil :: PageInfo?, + seg = 0, -- next segment index on the page + dataPos = 0, -- byte offset of the next segment's data + lastComplete = -1, -- index of the last segment ending a packet on this page + firstPacketOnPage = true, + parts = {} :: { number }, -- pending partial packet: offset, len pairs + partLen = 0, + lastSeq = -1, + gap = false, + ended = false, + total = 0, + }, Reader) +end + +@native function Reader._nextPage(self: any): boolean + local b, d = self.buf, self.demux + while true do + local p = Page.find(b, self.pagePos, nil, d.verify) + if not p then + return false + end + self.pagePos = p.offset + p.size + if p.serial == self.serial then + if self.lastSeq >= 0 and p.sequence ~= (self.lastSeq + 1) % 4294967296 then + -- a page is missing: drop the partial packet + self.parts, self.partLen = {}, 0 + self.gap = true + end + self.lastSeq = p.sequence + self.page = p + self.seg = 0 + self.dataPos = p.offset + p.headerSize + self.firstPacketOnPage = true + local lc = -1 + local base = p.offset + 27 + for i = 0, p.nsegs - 1 do + if readu8(b, base + i) < 255 then + lc = i + end + end + self.lastComplete = lc + if p.continued then + if self.partLen == 0 and #self.parts == 0 then + -- the start of this packet is not ours (after a seek or a loss): skip its tail + local s = 0 + while s < p.nsegs do + local l = readu8(b, base + s) + self.dataPos += l + s += 1 + if l < 255 then + break + end + end + self.seg = s + self.firstPacketOnPage = false + end + elseif #self.parts > 0 then + -- a fresh packet while one was pending: the pending one is lost + self.parts, self.partLen = {}, 0 + self.gap = true + end + return true + end + end +end + +@native function Reader.nextPacket(self: any): Packet? + if self.ended then + return nil + end + local b = self.buf + while true do + local p = self.page + if p and self.seg < p.nsegs then + local base = p.offset + 27 + local start = self.dataPos + local len = 0 + local s = self.seg + local complete = false + while s < p.nsegs do + local l = readu8(b, base + s) + s += 1 + len += l + if l < 255 then + complete = true + break + end + end + self.seg = s + self.dataPos = start + len + if complete then + local data, off, size = b, start, len + local parts = self.parts + if #parts > 0 then + size = self.partLen + len + data = buffer.create(size) + off = 0 + local o = 0 + for i = 1, #parts, 2 do + buffer.copy(data, o, b, parts[i], parts[i + 1]) + o += parts[i + 1] + end + buffer.copy(data, o, b, start, len) + self.parts, self.partLen = {}, 0 + end + local last = (s - 1) == self.lastComplete + local pkt = { + data = data, + offset = off, + size = size, + granule = if last then p.granule else -1, + pageGranule = p.granule, + bos = p.bos and self.firstPacketOnPage, + eos = p.eos and last, + pageOffset = p.offset, + gap = self.gap, + } + self.firstPacketOnPage = false + self.gap = false + self.total += 1 + if pkt.eos then + self.ended = true + end + return pkt + else + -- the packet continues on a later page + table.insert(self.parts, start) + table.insert(self.parts, len) + self.partLen += len + end + else + if p and p.eos then + self.ended = true + return nil + end + if not self:_nextPage() then + self.ended = true + return nil + end + end + end +end + +@native function Reader.rewind(self: any) + self.pagePos = self.start + self.page = nil + self.seg = 0 + self.parts, self.partLen = {}, 0 + self.lastSeq = -1 + self.gap = false + self.ended = false +end + +@native function Reader._at(self: any, p: PageInfo) + self:rewind() + self.pagePos = p.offset + self:_nextPage() -- loads p (it is a valid page of this serial) + local b = self.buf + local base = p.offset + 27 + local dp = p.offset + p.headerSize + for i = 0, self.lastComplete do + dp += readu8(b, base + i) + end + self.seg = self.lastComplete + 1 + self.dataPos = dp + self.parts, self.partLen = {}, 0 + self.firstPacketOnPage = false + self.gap = false + self.ended = false +end + +-- seekGranule: after the last page with granule <= g (bisection, then a short scan); before every granule rewinds (-1) +@native function Reader.seekGranule(self: any, g: number): (number?, Err.Err?) + local b, d = self.buf, self.demux + local serial = self.serial + local verify = d.verify + @native local function nextOf(pos: number, limit: number?): PageInfo? + while true do + local p = Page.find(b, pos, limit, verify) + if not p then + return nil + end + if p.serial == serial and p.granule ~= -1 then + return p + end + pos = p.offset + p.size + end + end + local lo, hi = self.start, buffer.len(b) + local best: PageInfo? = nil + while hi - lo > 65536 do + local mid = (lo + hi) // 2 + local p = nextOf(mid, hi) + if p and p.granule <= g then + best = p + lo = p.offset + else + hi = mid + end + end + local pos = lo + while true do + local p = nextOf(pos) + if not p or p.granule > g then + break + end + best = p + pos = p.offset + p.size + end + if not best then + self:rewind() + return -1, nil + end + self:_at(best) + return best.granule, nil +end + +local Demux = {} +Demux.__index = Demux + +@native function Ogg.open(src: any, opts: { verify: boolean?, scanAll: boolean? }?): (any, Err.Err?) + local buf: buffer + if type(src) == "buffer" then + buf = src + elseif type(src) == "table" and type(src.buf) == "buffer" and type(src.base) == "number" and type(src.limit) == "number" then + if src.base == 0 and src.limit == buffer.len(src.buf) then + buf = src.buf + else + local n = math.max(0, src.limit - src.base) + buf = buffer.create(n) + buffer.copy(buf, 0, src.buf, src.base, n) + end + else + return nil, Err.new(Err.ARG, "open: expected a buffer or a Reader") + end + local verify = not (opts and opts.verify == false) + local first = Page.find(buf, 0, nil, verify) + if not first then + return nil, Err.new(Err.CORRUPT, "no Ogg page found") + end + local d = setmetatable({ + buf = buf, + size = buffer.len(buf), + verify = verify, + _streams = {} :: { Stream }, + _bySerial = {} :: { [number]: Stream }, + _readers = {} :: { [number]: any }, + _lastDone = false, + }, Demux) + -- the bos pages (at the start of the file, and later ones for chains if scanAll) + local pos = first.offset + local scanAll = opts and opts.scanAll + while true do + local p = Page.find(buf, pos, nil, verify) + if not p then + break + end + if p.bos and not d._bySerial[p.serial] then + local st = { + serial = p.serial, + codec = "unknown", + firstPacket = buffer.create(0), + bosOffset = p.offset, + lastGranule = -1, + } + table.insert(d._streams, st) + d._bySerial[p.serial] = st + local r = newReader(d, p.serial, p.offset) + local pk = r:nextPacket() + if pk then + local c = buffer.create(pk.size) + buffer.copy(c, 0, pk.data, pk.offset, pk.size) + st.firstPacket = c + st.codec = Page.codec(c, 0, pk.size) + end + elseif not p.bos and not scanAll then + break + end + pos = p.offset + p.size + end + if #d._streams == 0 then + return nil, Err.new(Err.CORRUPT, "no beginning-of-stream page") + end + return d, nil +end + +@native function Demux._scanLast(self: any) + if self._lastDone then + return + end + self._lastDone = true + local b = self.buf + local need = #self._streams + local pos = self.size - 27 + while need > 0 do + local p = Page.findBack(b, pos, 0, self.verify) + if not p then + break + end + local st = self._bySerial[p.serial] + if st and st.lastGranule == -1 and p.granule ~= -1 then + st.lastGranule = p.granule + need -= 1 + end + pos = p.offset - 1 + end +end + +@native function Demux.streams(self: any): { Stream } + self:_scanLast() + return self._streams +end + +@native function Demux.stream(self: any, serial: number): Stream? + self:_scanLast() + return self._bySerial[serial] +end + +@native function Demux.find(self: any, codec: string): number? + for _, s in self._streams do + if s.codec == codec then + return s.serial + end + end + return nil +end + +@native function Demux.reader(self: any, serial: number): (any, Err.Err?) + local r = self._readers[serial] + if r then + return r, nil + end + local st = self._bySerial[serial] + if not st then + return nil, Err.new(Err.ARG, "unknown serial " .. tostring(serial)) + end + r = newReader(self, serial, st.bosOffset) + self._readers[serial] = r + return r, nil +end + +@native function Demux.nextPacket(self: any, serial: number): Packet? + local r = self:reader(serial) + return if r then r:nextPacket() else nil +end + +@native function Demux.seekGranule(self: any, serial: number, g: number): (number?, Err.Err?) + local r, err = self:reader(serial) + if not r then + return nil, err + end + return r:seekGranule(g) +end + +@native function Demux.rewind(self: any, serial: number) + local r = self:reader(serial) + if r then + r:rewind() + end +end + +@native function Demux.packets(self: any, serial: number): () -> Packet? + local r = self:reader(serial) + return @native function() + return if r then r:nextPacket() else nil + end +end + +@native function Ogg.copy(p: Packet): buffer + local c = buffer.create(p.size) + buffer.copy(c, 0, p.data, p.offset, p.size) + return c +end + +return Ogg +end +__FILES["containers/Riff"] = function() + +-- containers/Riff: the RIFF chunk container (RIFF, RIFX big-endian, RF64 / BW64 with the ds64 chunk), read leniently +-- and written. Shared by audio/wav and the other RIFF forms (AVI, WebP, ANI, ...). The chunk walker comes from +-- wav-luau fd9a909 (same author, no third-party code), now the RIFF layout of containers/Chunks; the writer is new. +-- Lenient reading (what real files need): an odd-sized chunk without its pad byte is detected; a chunk declared past +-- the end keeps what is there (avail < size, truncated = true) and ends the walk; for the ids in opts.openEnded a +-- size of 0 or 0xFFFFFFFF means "up to the end of the file" (streamed writers) and ends the walk; RF64 sizes of +-- 0xFFFFFFFF come from the ds64 chunk (and its table). Never throws: bad data returns nil, Err. +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Chunks = __include("containers/Chunks") + +local readu8, readu16, readu32, readstring = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readstring + +local Riff = {} + +type Chunk = { + id: string, + start: number, -- absolute offset of the chunk header + offset: number, -- absolute offset of the body in the file's buffer + size: number, -- declared size (ds64-resolved), or what is available for open-ended / truncated chunks + declared: number, -- the raw size field + avail: number, -- body bytes present in the file (<= size) + truncated: boolean, -- declared past the end of the file + streamed: boolean, -- an open-ended chunk (size 0 / 0xFFFFFFFF up to the end) +} +type File = { + container: string, -- "RIFF" | "RIFX" | "RF64" (BW64 reads as RF64) + form: string, -- the form type: "WAVE", "AVI ", "WEBP", ... + bigEndian: boolean, + buf: buffer, + base: number, -- absolute offset of the file's first byte + limit: number, -- absolute offset past its last byte + size: number, -- the RIFF size field (ds64-resolved) + chunks: { Chunk }, + ds64: { riffSize: number, dataSize: number, sampleCount: number, table: { [string]: number } }?, +} +type ReadOptions = { + openEnded: { [string]: boolean }?, -- chunk ids whose size 0 / 0xFFFFFFFF means "to the end" (wav: data) + maxChunks: number?, -- stop after this many chunks (default 100000) +} + +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 + +function Riff.sniff(r: any): string? + local magic = r:peek(4) + if magic ~= "RIFF" and magic ~= "RIFX" and magic ~= "RF64" and magic ~= "BW64" then + return nil + end + local form = r:peek(4, 8) + return if #form == 4 then form else nil +end + +local function walk(b: buffer, p: number, limit: number, be: boolean, opts: ReadOptions?, ds64: any): { Chunk } + local layout: Chunks.Layout = { + bigEndian = be, + pad = 2, + lenientPad = true, + openEnded = opts and opts.openEnded, + maxChunks = opts and opts.maxChunks, + resize = if ds64 + then function(id: string, declared: number): number? + if declared ~= 0xFFFFFFFF then + return nil + end + return if id == "data" then ds64.dataSize else ds64.table[id] + end + else nil, + } + return Chunks.walk(b, p, limit, layout) :: any +end + +function Riff.read(src: any, opts: ReadOptions?): (File?, Err.Err?) + local r = if type(src) == "buffer" then Bytes.reader(src) else src + if type(r) ~= "table" or type(r.buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "read: expected a buffer or a Reader") + end + local b, base, limit = r.buf, r.base, r.limit + if limit - base < 12 then + return nil, Err.new(Err.TRUNCATED, "file too short for a RIFF header", base) + end + local magic = readstring(b, base, 4) + if magic ~= "RIFF" and magic ~= "RIFX" and magic ~= "RF64" and magic ~= "BW64" then + return nil, Err.new(Err.CORRUPT, "not a RIFF / RIFX / RF64 file", base) + end + local be = magic == "RIFX" + local f: File = { + container = if magic == "BW64" then "RF64" else magic, + form = readstring(b, base + 8, 4), + bigEndian = be, + buf = b, + base = base, + limit = limit, + size = u32(b, base + 4, be), + chunks = {}, + ds64 = nil, + } + -- RF64: the ds64 chunk comes first + if f.container == "RF64" and base + 20 <= limit and readstring(b, base + 12, 4) == "ds64" then + local sz = readu32(b, base + 16) + local o = base + 20 + if sz >= 24 and o + 24 <= limit then + local d = { + riffSize = readu32(b, o) + readu32(b, o + 4) * 4294967296, + dataSize = readu32(b, o + 8) + readu32(b, o + 12) * 4294967296, + sampleCount = readu32(b, o + 16) + readu32(b, o + 20) * 4294967296, + table = {} :: { [string]: number }, + } + if sz >= 28 and o + 28 <= limit then + local n = readu32(b, o + 24) + local q = o + 28 + for _ = 1, math.min(n, 1000) do + if q + 12 > limit or q + 12 > o + sz then + break + end + d.table[readstring(b, q, 4)] = readu32(b, q + 4) + readu32(b, q + 8) * 4294967296 + q += 12 + end + end + f.ds64 = d + if f.size == 0xFFFFFFFF then + f.size = d.riffSize + end + end + end + f.chunks = walk(b, base + 12, limit, be, opts, f.ds64) + return f, nil +end + +function Riff.find(f: File, id: string, from: number?): (Chunk?, number?) + for i = (from or 0) + 1, #f.chunks do + if f.chunks[i].id == id then + return f.chunks[i], i + end + end + return nil, nil +end + +function Riff.listType(f: File, c: Chunk): string? + if c.avail < 4 then + return nil + end + return readstring(f.buf, c.offset, 4) +end + +function Riff.list(f: File, c: Chunk, opts: ReadOptions?): { Chunk } + if c.avail < 4 then + return {} + end + return walk(f.buf, c.offset + 4, c.offset + c.avail, f.bigEndian, opts, nil) +end + +function Riff.body(f: File, c: Chunk): Bytes.Reader + return Bytes.reader(f.buf, c.offset, c.avail) +end + +function Riff.u16(f: File, o: number): number + if f.bigEndian then + return readu8(f.buf, o) * 256 + readu8(f.buf, o + 1) + end + return readu16(f.buf, o) +end +function Riff.u32(f: File, o: number): number + return u32(f.buf, o, f.bigEndian) +end + +local Writer = {} +Writer.__index = Writer + +type WriteOptions = { + bigEndian: boolean?, -- RIFX (default false) + rf64: (boolean | "auto")?, -- true: always RF64; false: never (sizes over 4 GiB are an error); default "auto" + sampleCount: number?, -- the ds64 sample count (RF64 WAVE: frames) + rf64Threshold: number?, -- "auto" switches to RF64 when the RIFF size would pass this (default 0xFFFFFFFF) +} + +function Riff.writer(form: string, opts: WriteOptions?): any + return setmetatable({ + form = string.sub(form .. " ", 1, 4), + be = opts and opts.bigEndian or false, + rf64 = if opts and opts.rf64 ~= nil then opts.rf64 else "auto", + sampleCount = opts and opts.sampleCount or 0, + threshold = opts and opts.rf64Threshold or 0xFFFFFFFF, + chunks = {} :: { any }, + }, Writer) +end + +function Writer.chunk(self: any, id: string, body: any, offset: number?, length: number?) + local parts = {} + local n = 0 + if type(body) == "table" then + for _, b in body do + table.insert(parts, { b, 0, buffer.len(b) }) + n += buffer.len(b) + end + else + local b: buffer = if type(body) == "string" then buffer.fromstring(body) else body + local o = offset or 0 + n = length or (buffer.len(b) - o) + parts[1] = { b, o, n } + end + table.insert(self.chunks, { id = string.sub(id .. " ", 1, 4), parts = parts, length = n }) +end + +function Writer.list(self: any, listType: string, items: { { any } }) + local w = Bytes.writer() + w:string(string.sub(listType .. " ", 1, 4)) + for _, it in items do + local v = it[2] + local data: buffer = if type(v) == "string" then buffer.fromstring(v .. "\0") else v + local n = buffer.len(data) + w:string(string.sub(it[1] .. " ", 1, 4)) + if self.be then + w:u32be(n) + else + w:u32le(n) + end + w:bytes(data) + if n % 2 == 1 then + w:u8(0) + end + end + self:chunk("LIST", w:finish()) +end + +function Writer.finish(self: any, opts: { parts: boolean? }?): (any, Err.Err?) + local total = 4 -- the form type + local big = false + local dataSize = 0 + for _, c in self.chunks do + total += 8 + c.length + c.length % 2 + if c.length > 0xFFFFFFFE then + big = true + end + if c.id == "data" then + dataSize = c.length + end + end + local rf64 = self.rf64 == true or (self.rf64 == "auto" and (big or total > self.threshold)) + if not rf64 and (big or total > 0xFFFFFFFF) then + return nil, Err.new(Err.LIMIT, "over 4 GiB without RF64") + end + if rf64 and self.be then + return nil, Err.new(Err.ARG, "RF64 is little-endian only") + end + if rf64 then + total += 36 -- ds64 + end + local asParts = opts and opts.parts + if not asParts and total + 8 > 0x40000000 then + return nil, Err.new(Err.LIMIT, "the file would not fit in a buffer (1 GiB): use finish({ parts = true })") + end + local out: { buffer } = {} + local w = Bytes.writer(if asParts then 256 else total + 8) + local function size32(v: number) + if self.be then + w:u32be(v) + else + w:u32le(v) + end + end + if rf64 then + w:string("RF64") + w:u32le(0xFFFFFFFF) + w:string(self.form) + w:string("ds64") + w:u32le(28) + w:u64le(total) + w:u64le(dataSize) + w:u64le(self.sampleCount) + w:u32le(0) -- no table: only data may be over 4 GiB + else + w:string(if self.be then "RIFX" else "RIFF") + size32(total) + w:string(self.form) + end + for _, c in self.chunks do + w:string(c.id) + if rf64 and (c.id == "data" or c.length > 0xFFFFFFFE) then + w:u32le(0xFFFFFFFF) + else + size32(c.length) + end + for _, p in c.parts do + if asParts then + table.insert(out, w:finish()) + w = Bytes.writer(64) + if p[2] == 0 and p[3] == buffer.len(p[1]) then + table.insert(out, p[1]) + else + local cp = buffer.create(p[3]) + buffer.copy(cp, 0, p[1], p[2], p[3]) + table.insert(out, cp) + end + else + w:bytes(p[1], p[2], p[3]) + end + end + if c.length % 2 == 1 then + w:u8(0) + end + end + if asParts then + if w:tell() > 0 then + table.insert(out, w:finish()) + end + return out, nil + end + return w:finish(), nil +end + +return Riff +end +__FILES["containers/Tar"] = function() + +-- containers/Tar: tar (POSIX.1-1988 ustar, POSIX.1-2001 pax, GNU), read and written; from POSIX pax(1) (IEEE Std +-- 1003.1-2017) and the GNU tar manual. Reads v7 / ustar / GNU / pax headers ('x' / 'g', 'L' / 'K', base-256, signed +-- checksums); writes ustar + pax, or GNU 'L' / 'K'. Not supported: sparse files, multi-volume (listed as "S" / "M"). +-- Never throws: bad data returns nil, Err. +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") + +local Tar = {} + +type Entry = { + name: string, + size: number, + type: string, -- "0" file, "5" directory, "2" symlink, "1" hard link, "3" / "4" devices, "6" fifo, ... + dir: boolean, + mode: number, + uid: number, + gid: number, + mtime: number, + link: string?, + uname: string?, + gname: string?, + offset: number, -- absolute offset of the data in the buffer + pax: { [string]: string }?, +} + +local BLOCK = 512 + +local function zeros(b: buffer, o: number): boolean + for i = 0, BLOCK - 1, 4 do + if buffer.readu32(b, o + i) ~= 0 then + return false + end + end + return true +end + +-- a numeric field: octal text (NUL / space terminated) or base-256 (high bit of the first byte) +local function number(b: buffer, o: number, n: number): number? + local first = buffer.readu8(b, o) + if first >= 0x80 then + local v = first - (if first >= 0xC0 then 0x100 else 0x80) -- 0xFF.. = negative + for i = 1, n - 1 do + v = v * 256 + buffer.readu8(b, o + i) + end + return v + end + local s = buffer.readstring(b, o, n) + s = string.match(s, "^[ %z]*([0-7]*)") or "" + if s == "" then + return 0 + end + return tonumber(s, 8) +end + +local function str(b: buffer, o: number, n: number): string + local s = buffer.readstring(b, o, n) + local z = string.find(s, "\0", 1, true) + return if z then string.sub(s, 1, z - 1) else s +end + +local function checksum(b: buffer, o: number): (number, number) + local u, s = 0, 0 + for i = 0, BLOCK - 1 do + local v = if i >= 148 and i < 156 then 32 else buffer.readu8(b, o + i) + u += v + s += if v >= 128 then v - 256 else v + end + return u, s +end + +function Tar.valid(b: buffer, o: number): boolean + if o + BLOCK > buffer.len(b) or zeros(b, o) then + return false + end + local want = number(b, o + 148, 8) + local u, s = checksum(b, o) + return want == u or want == s +end + +-- pax records "len key=value\n" -> { key = value } +local function pax(b: buffer, o: number, n: number, into: { [string]: string }): boolean + local s = buffer.readstring(b, o, n) + local p = 1 + while p <= #s do + if string.byte(s, p) == 0 then + break + end + local len = string.match(s, "^(%d+) ", p) + if not len then + return false + end + local l = tonumber(len) :: number + if l < #len + 3 or p + l - 1 > #s then + return false + end + local rec = string.sub(s, p + #len + 1, p + l - 2) -- without the trailing newline + local eq = string.find(rec, "=", 1, true) + if not eq then + return false + end + into[string.sub(rec, 1, eq - 1)] = string.sub(rec, eq + 1) + p += l + end + return true +end + +type ReadOptions = { maxEntries: number? } -- default 1e6 + +function Tar.read(b: buffer, offset: number?, length: number?, opts: ReadOptions?): ({ Entry }?, Err.Err?) + local o = offset or 0 + local e = math.min(buffer.len(b), o + (length or (buffer.len(b) - o))) + local maxEntries = (opts and opts.maxEntries) or 1e6 + local out: { Entry } = {} + local global: { [string]: string } = {} + local nextPax: { [string]: string }? = nil + local longName: string? = nil + local longLink: string? = nil + local p = o + while true do + if p + BLOCK > e then + if p == e then + break -- no end-of-archive blocks: accepted, as GNU tar does (with a warning) + end + return nil, Err.new(Err.TRUNCATED, "header past the end", p) + end + if zeros(b, p) then + break -- end of archive (one or two zero blocks; what follows is padding) + end + local want = number(b, p + 148, 8) + local u, s = checksum(b, p) + if want ~= u and want ~= s then + return nil, Err.new(if #out == 0 then Err.CORRUPT else Err.CHECKSUM, "bad header checksum", p + 148) + end + local typ = buffer.readstring(b, p + 156, 1) + if typ == "\0" then + typ = "0" + end + local size = number(b, p + 124, 12) + if not size or size < 0 then + return nil, Err.new(Err.CORRUPT, "bad size field", p + 124) + end + local data = p + BLOCK + local nextHeader = data + (size + BLOCK - 1) // BLOCK * BLOCK + local ustar = buffer.readstring(b, p + 257, 5) == "ustar" + -- meta records: pax / GNU long names + if typ == "x" or typ == "g" or typ == "L" or typ == "K" then + if data + size > e then + return nil, Err.new(Err.TRUNCATED, "extended header past the end", data) + end + if typ == "x" or typ == "g" then + local into = if typ == "g" then global else (nextPax or {}) + if not pax(b, data, size, into) then + return nil, Err.new(Err.CORRUPT, "bad pax record", data) + end + if typ == "x" then + nextPax = into + end + elseif typ == "L" then + longName = str(b, data, size) + else + longLink = str(b, data, size) + end + p = nextHeader + continue + end + local name = str(b, p, 100) + if ustar then + local prefix = str(b, p + 345, 155) + if prefix ~= "" and buffer.readstring(b, p + 257, 8) ~= "ustar \0" then -- (GNU uses the field for times) + name = prefix .. "/" .. name + end + end + local entry: Entry = { + name = name, + size = size, + type = typ, + dir = typ == "5", + mode = number(b, p + 100, 8) or 0, + uid = number(b, p + 108, 8) or 0, + gid = number(b, p + 116, 8) or 0, + mtime = number(b, p + 136, 12) or 0, + link = if typ == "1" or typ == "2" then str(b, p + 157, 100) else nil, + uname = if ustar then str(b, p + 265, 32) else nil, + gname = if ustar then str(b, p + 297, 32) else nil, + offset = data, + pax = nil, + } + if longName then + entry.name = longName + end + if longLink then + entry.link = longLink + end + local px = nextPax + for _, rec in { global, px } do + if rec then + if rec.path then + entry.name = rec.path + end + if rec.linkpath then + entry.link = rec.linkpath + end + if rec.size then + local sz = tonumber(rec.size) + if not sz or sz < 0 or sz % 1 ~= 0 then + return nil, Err.new(Err.CORRUPT, "bad pax size", p) + end + entry.size = sz + end + if rec.mtime then + entry.mtime = tonumber(rec.mtime) or entry.mtime + end + if rec.uid then + entry.uid = tonumber(rec.uid) or entry.uid + end + if rec.gid then + entry.gid = tonumber(rec.gid) or entry.gid + end + if rec.uname then + entry.uname = rec.uname + end + if rec.gname then + entry.gname = rec.gname + end + end + end + if px then + entry.pax = px + end + if typ == "5" or string.sub(entry.name, -1) == "/" and (typ == "0" and entry.size == 0) then + entry.dir = true + end + -- links, devices, fifos and directories carry no data (whatever the size field says, except GNU dumpdir) + local dataSize = if typ == "1" or typ == "2" or typ == "3" or typ == "4" or typ == "6" or typ == "5" then 0 else entry.size + if typ == "5" or typ == "1" or typ == "2" then + entry.size = 0 + end + nextHeader = data + (dataSize + BLOCK - 1) // BLOCK * BLOCK + if typ ~= "5" and data + dataSize > e then + return nil, Err.new(Err.TRUNCATED, "entry " .. entry.name .. " data past the end", data) + end + table.insert(out, entry) + if #out > maxEntries then + return nil, Err.new(Err.LIMIT, "more than " .. maxEntries .. " entries") + end + nextPax, longName, longLink = nil, nil, nil + p = nextHeader + end + return out, nil +end + +type WriteEntry = { + name: string, + data: buffer?, + dir: boolean?, + type: string?, -- default "0" ("5" for dir) + link: string?, + mode: number?, -- default 0o644 (0o755 for directories) + uid: number?, + gid: number?, + uname: string?, + gname: string?, + mtime: number?, -- unix seconds (default 0) +} +type WriteOptions = { format: ("pax" | "gnu" | "ustar")? } -- default "pax" (ustar headers + pax when needed) + +local function octal(w: buffer, o: number, n: number, v: number): boolean + -- n - 1 octal digits and a NUL; false when it does not fit + local s = string.format("%o", v) + if v < 0 or v % 1 ~= 0 or #s > n - 1 then + return false + end + buffer.writestring(w, o, string.rep("0", n - 1 - #s) .. s) + buffer.writeu8(w, o + n - 1, 0) + return true +end + +local function field(w: buffer, o: number, n: number, s: string) + buffer.writestring(w, o, string.sub(s, 1, n)) +end + +local function ascii(s: string): boolean + return not string.find(s, "[\128-\255]") +end + +local function paxRecord(key: string, value: string): string + local body = " " .. key .. "=" .. value .. "\n" + local n = #body + 1 + while #tostring(n) + #body ~= n do + n = #tostring(n) + #body + end + return tostring(n) .. body +end + +local function header(name: string, typ: string, size: number, e: WriteEntry, prefix: string, link: string, gnu: boolean): buffer + local h = buffer.create(BLOCK) + field(h, 0, 100, name) + local mode = e.mode or (if typ == "5" then 0x1ED else 0x1A4) + octal(h, 100, 8, mode % 0x200000) + octal(h, 108, 8, math.clamp(math.floor(e.uid or 0), 0, 0x1FFFFF)) + octal(h, 116, 8, math.clamp(math.floor(e.gid or 0), 0, 0x1FFFFF)) + octal(h, 124, 12, size) + octal(h, 136, 12, math.clamp(math.floor(e.mtime or 0), 0, 8 ^ 11 - 1)) + field(h, 148, 8, " ") + field(h, 156, 1, typ) + field(h, 157, 100, link) + field(h, 257, 8, if gnu then "ustar \0" else "ustar\00000") + field(h, 265, 32, e.uname or "") + field(h, 297, 32, e.gname or "") + field(h, 345, 155, prefix) + local u = checksum(h, 0) + field(h, 148, 8, string.format("%06o", u) .. "\0 ") + return h +end + +-- split a long path into ustar prefix (<= 155) + name (<= 100) at a slash, or nil +local function split(path: string): (string?, string?) + if #path <= 100 then + return "", path + end + for i = 2, math.min(#path - 1, 156) do -- the shortest prefix that works, as Python's tarfile + if string.sub(path, i, i) == "/" and i - 1 <= 155 and #path - i <= 100 then + return string.sub(path, 1, i - 1), string.sub(path, i + 1) + end + end + return nil, nil +end + +function Tar.write(entries: { WriteEntry }, opts: WriteOptions?): (buffer?, Err.Err?) + local fmt = (opts and opts.format) or "pax" + local w = Bytes.writer(BLOCK * (2 * #entries + 2)) + for i, e in entries do + if type(e) ~= "table" or type(e.name) ~= "string" or e.name == "" then + return nil, Err.new(Err.ARG, "entry " .. i .. ": needs a name") + end + local data = e.data or buffer.create(0) + local typ = e.type or (if e.dir then "5" else "0") + local name: string = e.name + if typ == "5" and string.sub(name, -1) ~= "/" then + name ..= "/" + end + local size = if typ == "0" or typ == "7" then buffer.len(data) else 0 + local link = e.link or "" + -- ustar splits long names into prefix + name; pax and GNU (as Python's tarfile and GNU tar) record them whole + local prefix, short + if fmt == "ustar" then + prefix, short = split(name) + elseif #name <= 100 then + prefix, short = "", name + end + local paxRecs: { string } = {} + -- GNU headers hold any bytes (UTF-8 names stay raw); ustar / pax headers are ASCII + local needName = prefix == nil or (fmt ~= "gnu" and not ascii(name)) + local needLink = #link > 100 or (fmt ~= "gnu" and not ascii(link)) + if needName or needLink then + if fmt == "ustar" then + return nil, Err.new(Err.ARG, "entry " .. name .. ": name or link too long / not ASCII for ustar") + elseif fmt == "gnu" then + if needName then + local ln = buffer.fromstring(name .. "\0") + w:bytes(header("././@LongLink", "L", buffer.len(ln), { mode = 0 } :: any, "", "", true)) + w:bytes(ln) + w:fill(0, (BLOCK - buffer.len(ln) % BLOCK) % BLOCK) + end + if needLink then + local ll = buffer.fromstring(link .. "\0") + w:bytes(header("././@LongLink", "K", buffer.len(ll), { mode = 0 } :: any, "", "", true)) + w:bytes(ll) + w:fill(0, (BLOCK - buffer.len(ll) % BLOCK) % BLOCK) + end + else + if needName then + table.insert(paxRecs, paxRecord("path", name)) + end + if needLink then + table.insert(paxRecs, paxRecord("linkpath", link)) + end + end + end + if size >= 8 ^ 11 then + if fmt ~= "pax" then + return nil, Err.new(Err.ARG, "entry " .. name .. ": 8 GiB or more needs pax") + end + table.insert(paxRecs, paxRecord("size", tostring(size))) + end + local mt = e.mtime or 0 + if fmt == "pax" and (mt < 0 or mt % 1 ~= 0 or mt >= 8 ^ 11) then + table.insert(paxRecs, paxRecord("mtime", string.format("%.9f", mt):gsub("0+$", ""):gsub("%.$", ""))) + end + if #paxRecs > 0 then + local body = buffer.fromstring(table.concat(paxRecs)) + w:bytes(header("././@PaxHeader", "x", buffer.len(body), { mode = 0 } :: any, "", "", false)) + w:bytes(body) + w:fill(0, (BLOCK - buffer.len(body) % BLOCK) % BLOCK) + end + if prefix == nil or (fmt ~= "gnu" and not ascii(name)) then + -- the header keeps an ASCII stand-in (each non-ASCII character as "?", as Python's tarfile) + local stand = if fmt == "gnu" then name else string.gsub(name, "[\192-\255][\128-\191]*", "?") + prefix, short = "", string.sub(stand, 1, 100) + end + w:bytes(header(short :: string, typ, if size >= 8 ^ 11 then 0 else size, e, prefix :: string, string.sub(link, 1, 100), fmt == "gnu")) + if size > 0 then + w:bytes(data) + w:fill(0, (BLOCK - size % BLOCK) % BLOCK) + end + end + w:fill(0, BLOCK * 2) + return w:finish(), nil +end + +return Tar +end +__FILES["containers/Zip"] = function() + + +-- containers/Zip: ZIP (PKWARE APPNOTE 6.3), read and written. The reader is absorbed from zip-luau 121d4b0 (same +-- author, no third-party code): EOCD search, ZIP64, prefix shifts (self-extractor stubs), stored / deflated entries, +-- data descriptors. The writer is new: stored / deflated, UTF-8 names, DOS times, raw entry copies, ZIP64 when needed. +-- Never throws: corrupt archives and bad arguments return nil, Err. +local Err = __include("core/Err") +local Types = __include("Types") +local Bytes = __include("core/Bytes") +local Crc32 = __include("core/Crc32") +local Deflate = __include("codecs/compress/Deflate") + +local Zip = {} +Zip.version = "1.1.0" + +type Entry = { + name: string, -- the path with "\" turned into "/" + rawName: string, -- the name bytes as stored + index: number, -- position in the central directory, 1-based + size: number, -- uncompressed size + compressedSize: number, + crc32: number, + method: number, -- 0 stored, 8 deflate (others are listed but not readable) + flags: number, -- general purpose bits (1 encrypted, 8 data descriptor, 2048 UTF-8 name) + offset: number, -- local header offset (already corrected for a prefix such as a self-extractor stub) + isDir: boolean, + utf8: boolean, + comment: string, + modified: { year: number, month: number, day: number, hour: number, min: number, sec: number }, + mtime: number, -- the modification time as Unix seconds (the DOS time read as UTC) + time: number, -- the raw DOS time and date + date: number, + attributes: number, -- external attributes + -- central-directory lengths of the name and extra field (a fallback when the local header is wrong) + cdNameLen: number, + cdExtraLen: number, +} + +local readu8, readu16, readu32 = buffer.readu8, buffer.readu16, buffer.readu32 + +local SIG_LOCAL, SIG_CD, SIG_EOCD = 0x04034b50, 0x02014b50, 0x06054b50 +local SIG_Z64_EOCD, SIG_Z64_LOC = 0x06064b50, 0x07064b50 + +local function readu64(b: buffer, o: number): number + return readu32(b, o) + readu32(b, o + 4) * 4294967296 +end + +local function sigAt(b: buffer, o: number, sig: number): boolean + return o >= 0 and o + 4 <= buffer.len(b) and readu32(b, o) == sig +end + +local function normalize(name: string): string + name = string.gsub(name, "\\", "/") + name = string.gsub(name, "^%./", "") + name = string.gsub(name, "^/+", "") + return name +end + +local function basename(name: string): string + return string.match(name, "([^/]*)/*$") or name +end + +-- junk that shares a basename with real files: macOS resource forks +local function isJunk(name: string): boolean + local l = string.lower(name) + return string.find(l, "__macosx/", 1, true) ~= nil or string.sub(basename(l), 1, 2) == "._" +end + +local Archive = {} +Archive.__index = Archive + + +function Zip.isZip(buf: buffer | string): boolean + local b = if type(buf) == "string" then buffer.fromstring(string.sub(buf, 1, 4)) else buf + return sigAt(b, 0, SIG_LOCAL) or sigAt(b, 0, SIG_EOCD) +end + +local function findEocd(b: buffer): number? + local n = buffer.len(b) + local fallback = nil + local stop = math.max(0, n - 22 - 65535) + for p = n - 22, stop, -1 do + if readu8(b, p) == 0x50 and readu32(b, p) == SIG_EOCD then + if p + 22 + readu16(b, p + 20) == n then + return p + end + fallback = fallback or p -- comment length disagrees (trailing junk or a wrong length): keep looking + end + end + return fallback +end + +local function parse(b: buffer): (any, Err.Err?) + local n = buffer.len(b) + if n < 22 then + return nil, Err.new(Err.TRUNCATED, "too small for an end of central directory record") + end + local eocd = findEocd(b) + if not eocd then + return nil, Err.new(Err.CORRUPT, "no end of central directory record") + end + local count = readu16(b, eocd + 10) + local cdSize = readu32(b, eocd + 12) + local cdOff = readu32(b, eocd + 16) + local commentLen = math.min(readu16(b, eocd + 20), n - eocd - 22) + local comment = buffer.readstring(b, eocd + 22, commentLen) + local cdEnd = eocd + -- ZIP64: the locator sits just before the end record + local zip64 = false + if sigAt(b, eocd - 20, SIG_Z64_LOC) then + local z = readu64(b, eocd - 20 + 8) + if not sigAt(b, z, SIG_Z64_EOCD) then + -- a prefix shifted everything: the record directly precedes the locator (56 bytes + extensible data) + local guess = eocd - 20 - 56 + if sigAt(b, guess, SIG_Z64_EOCD) then + z = guess + else + z = -1 + end + end + if z >= 0 and z + 56 <= n then + zip64 = true + count = readu64(b, z + 32) + cdSize = readu64(b, z + 40) + cdOff = readu64(b, z + 48) + cdEnd = z + end + end + if not zip64 and (count == 0xFFFF or cdSize == 0xFFFFFFFF or cdOff == 0xFFFFFFFF) then + return nil, Err.new(Err.CORRUPT, "ZIP64 fields without a ZIP64 record") + end + -- a prefix (self-extractor stub, or a zip appended to another file) shifts every offset + local delta = 0 + if count > 0 and not sigAt(b, cdOff, SIG_CD) then + delta = cdEnd - (cdOff + cdSize) + if not sigAt(b, cdOff + delta, SIG_CD) then + return nil, Err.new(Err.CORRUPT, "central directory not found") + end + end + local entries = table.create(math.min(count, 65536)) :: { any } + local p = cdOff + delta + for i = 1, count do + if not sigAt(b, p, SIG_CD) or p + 46 > n then + return nil, Err.new(Err.CORRUPT, string.format("bad central directory entry %d", i), p) + end + local flags = readu16(b, p + 8) + local method = readu16(b, p + 10) + local time, date = readu16(b, p + 12), readu16(b, p + 14) + local crc = readu32(b, p + 16) + local csize, usize = readu32(b, p + 20), readu32(b, p + 24) + local nameLen, extraLen, cmtLen = readu16(b, p + 28), readu16(b, p + 30), readu16(b, p + 32) + local disk = readu16(b, p + 34) + local off = readu32(b, p + 42) + if p + 46 + nameLen + extraLen + cmtLen > n then + return nil, Err.new(Err.TRUNCATED, string.format("central directory entry %d runs past the end", i), p) + end + local raw = buffer.readstring(b, p + 46, nameLen) + -- extra fields: ZIP64 (0x0001) holds the 32-bit fields that are all ones, in this order + local q, qe = p + 46 + nameLen, p + 46 + nameLen + extraLen + while q + 4 <= qe do + local id, sz = readu16(b, q), readu16(b, q + 2) + if id == 0x0001 then + local r, re = q + 4, math.min(q + 4 + sz, qe) + if usize == 0xFFFFFFFF and r + 8 <= re then + usize = readu64(b, r) + r += 8 + end + if csize == 0xFFFFFFFF and r + 8 <= re then + csize = readu64(b, r) + r += 8 + end + if off == 0xFFFFFFFF and r + 8 <= re then + off = readu64(b, r) + r += 8 + end + if disk == 0xFFFF and r + 4 <= re then + disk = readu32(b, r) + end + end + q += 4 + sz + end + local name = normalize(raw) + entries[i] = { + name = name, + rawName = raw, + index = i, + size = usize, + compressedSize = csize, + crc32 = crc, + method = method, + flags = flags, + offset = off + delta, + isDir = string.sub(raw, -1) == "/" or string.sub(raw, -1) == "\\", + utf8 = bit32.band(flags, 0x800) ~= 0, + comment = buffer.readstring(b, qe, cmtLen), + modified = { + year = 1980 + bit32.rshift(date, 9), + month = bit32.band(bit32.rshift(date, 5), 15), + day = bit32.band(date, 31), + hour = bit32.rshift(time, 11), + min = bit32.band(bit32.rshift(time, 5), 63), + sec = bit32.band(time, 31) * 2, + }, + mtime = Zip.unixTime(time, date), + time = time, + date = date, + attributes = readu32(b, p + 38), + cdNameLen = nameLen, + cdExtraLen = extraLen, + } + p = qe + cmtLen + end + local exact, lower, base = {}, {}, {} + for _, e in entries do + if not e.isDir then + exact[e.name] = exact[e.name] or e + local l = string.lower(e.name) + lower[l] = lower[l] or e + if not isJunk(e.name) then + local bn = basename(l) + local prev = base[bn] + -- prefer the shallowest path, then the first in directory order + if not prev or select(2, string.gsub(e.name, "/", "")) < select(2, string.gsub(prev.name, "/", "")) then + base[bn] = e + end + end + end + end + return setmetatable({ + buf = b, + entries = entries, + comment = comment, + zip64 = zip64, + _exact = exact, + _lower = lower, + _base = base, + }, Archive) +end + +function Zip.open(src: any): (any, Err.Err?) + local b: buffer + if type(src) == "string" then + b = buffer.fromstring(src) + elseif type(src) == "buffer" then + b = src + elseif type(src) == "table" and type(src.buf) == "buffer" then + if src.base == 0 and src.limit == buffer.len(src.buf) then + b = src.buf + else + local n = math.max(0, src.limit - src.base) + b = buffer.create(n) + buffer.copy(b, 0, src.buf, src.base, n) + end + else + return nil, Err.new(Err.ARG, "open: expected a buffer, a string or a Reader") + end + local ok, res, err = pcall(parse, b) + if not ok then + return nil, Err.new(Err.CORRUPT, "corrupt archive (" .. tostring(res) .. ")") + end + return res, err +end + +function Archive.list(self: any): { Entry } + return self.entries +end + +-- lookup: exact, then case-insensitive, then by basename (never __MACOSX/ or ._ files); "\\" and "/" are the same +function Archive.find(self: any, name: string): Entry? + local n = normalize(name) + local e = self._exact[n] + if e then + return e + end + local l = string.lower(n) + e = self._lower[l] + if e then + return e + end + return self._base[basename(l)] +end + +local function extract(b: buffer, e: Entry, dataStart: number): (buffer?, any) + local n = buffer.len(b) + if dataStart > n then + return nil, "data starts past the end" + end + if e.method == 0 then + if dataStart + e.size > n then + return nil, "truncated stored data" + end + local out = buffer.create(e.size) + buffer.copy(out, 0, b, dataStart, e.size) + return out + end + local len = math.min(e.compressedSize, n - dataStart) + local out, err = Deflate.inflate(b, dataStart, len, e.size) + if not out then + -- a wrong size in the directory: inflate without it and let the CRC decide + local out2 = Deflate.inflate(b, dataStart, n - dataStart) + if out2 then + return out2 + end + return nil, if type(err) == "table" then err.message else tostring(err) + end + return out +end + +-- data offset candidates: the local header's lengths, then the central directory's (some writers get the local +-- extra length wrong) +function Zip._starts(b: buffer, e: Entry): { number } + local o = e.offset + local starts = {} + if o >= 0 and o + 30 <= buffer.len(b) and readu32(b, o) == SIG_LOCAL then + table.insert(starts, o + 30 + readu16(b, o + 26) + readu16(b, o + 28)) + end + local alt = o + 30 + e.cdNameLen + e.cdExtraLen + if alt ~= starts[1] then + table.insert(starts, alt) + end + if alt ~= o + 30 + e.cdNameLen then + table.insert(starts, o + 30 + e.cdNameLen) + end + return starts +end + +function Archive.read(self: any, entry: Entry | string, verify: boolean?): (buffer?, Err.Err?) + local e: Entry? = if type(entry) == "string" then self:find(entry) else entry :: Entry + if not e then + return nil, Err.new(Err.ARG, "no entry " .. tostring(entry)) + end + if e.isDir then + return buffer.create(0), nil + end + if bit32.band(e.flags, 1) ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, e.name .. " is encrypted") + end + if e.method ~= 0 and e.method ~= 8 then + return nil, Err.new(Err.UNSUPPORTED, string.format("%s uses compression method %d (only stored and deflate)", e.name, e.method)) + end + local b = self.buf + local n = buffer.len(b) + local o = e.offset + if o < 0 or o + 30 > n then + return nil, Err.new(Err.CORRUPT, e.name .. ": local header out of range", o) + end + local starts = Zip._starts(b, e) + local firstErr: string? = nil + local code = Err.CORRUPT + for _, s in starts do + local out, err = extract(b, e, s) + if out then + if verify == false then + return out, nil + end + if buffer.len(out) ~= e.size then + err = string.format("size %d, expected %d", buffer.len(out), e.size) + else + local c = Deflate.crc32(out) + if c == e.crc32 then + return out, nil + end + err = string.format("CRC-32 mismatch (%08x, expected %08x)", c, e.crc32) + end + end + firstErr = firstErr or err + end + return nil, Err.new(if firstErr and string.find(firstErr, "CRC", 1, true) then Err.CHECKSUM else code, e.name .. ": " .. tostring(firstErr)) +end + +function Archive.readString(self: any, entry: Entry | string, verify: boolean?): (string?, Err.Err?) + local out, err = self:read(entry, verify) + if not out then + return nil, err + end + return buffer.tostring(out), nil +end + +local Writer = {} +Writer.__index = Writer + +type AddOptions = { + method: ("deflate" | "store")?, -- default "deflate" (stored instead when deflate does not make it smaller) + level: number?, -- deflate level 0..9 (default 6) + mtime: number?, -- modification time, Unix seconds (UTC); default 1980-01-01 00:00:00 (reproducible output) + comment: string?, + utf8: boolean?, -- set the UTF-8 name flag (default: when the name is not plain ASCII) + attributes: number?, -- external attributes (default: Unix 0644 for files, 0755 + MS-DOS directory for dirs) +} +type FinishOptions = { + comment: string?, -- the archive comment + zip64: boolean?, -- force the ZIP64 records (default: only when counts, sizes or offsets need them) +} + +function Zip.writer(): any + return setmetatable({ files = {} :: { any } }, Writer) +end + +-- days from 1970-01-01 to y-m-d (proleptic Gregorian) +local civil = Types.Date.civilFromDays +local function daysFrom(y: number, m: number, d: number): number + y = if m <= 2 then y - 1 else y + local era = (if y >= 0 then y else y - 399) // 400 + local yoe = y - era * 400 + local mp = if m > 2 then m - 3 else m + 9 + local doy = (153 * mp + 2) // 5 + d - 1 + local doe = yoe * 365 + yoe // 4 - yoe // 100 + doy + return era * 146097 + doe - 719468 +end + +-- Unix seconds -> DOS time, date (clamped to 1980..2107) +function Zip.dosTime(t: number?): (number, number) + if type(t) ~= "number" or t ~= t then + return 0, 0x21 + end + local s = math.floor(t) + local days = s // 86400 + local rem = s - days * 86400 + local y, m, d = civil(days) + if y < 1980 then + return 0, 0x21 + elseif y > 2107 then + y, m, d, rem = 2107, 12, 31, 86399 + end + local time = (rem // 3600) * 2048 + ((rem // 60) % 60) * 32 + (rem % 60) // 2 + return time, (y - 1980) * 512 + m * 32 + d +end + +-- DOS time, date -> Unix seconds (UTC) +function Zip.unixTime(time: number, date: number): number + local y = 1980 + bit32.rshift(date, 9) + local m = math.clamp(bit32.band(bit32.rshift(date, 5), 15), 1, 12) + local d = math.clamp(bit32.band(date, 31), 1, 31) + return daysFrom(y, m, d) * 86400 + bit32.rshift(time, 11) * 3600 + bit32.band(bit32.rshift(time, 5), 63) * 60 + bit32.band(time, 31) * 2 +end + +local function isAscii(s: string): boolean + return string.find(s, "[\128-\255]") == nil +end + +function Writer.add(self: any, name: string, data: any, opts: AddOptions?): (boolean, Err.Err?) + if type(name) ~= "string" or name == "" or #name > 65535 then + return false, Err.new(Err.ARG, "add: bad entry name") + end + local b: buffer + if type(data) == "string" then + b = buffer.fromstring(data) + elseif type(data) == "buffer" then + b = data + elseif data == nil and string.sub(name, -1) == "/" then + b = buffer.create(0) + else + return false, Err.new(Err.ARG, "add: data must be a buffer or a string") + end + local o: AddOptions = opts or {} + local method = o.method or "deflate" + if method ~= "deflate" and method ~= "store" then + return false, Err.new(Err.ARG, "add: method must be deflate or store") + end + local isDir = string.sub(name, -1) == "/" + local n = buffer.len(b) + local comp, code = b, 0 + if method == "deflate" and n > 0 and not isDir then + local z, zerr = Deflate.compress(b, { level = o.level or 6 }) + if not z then + return false, zerr + end + if buffer.len(z) < n then + comp, code = z, 8 + end + end + local time, date = Zip.dosTime(o.mtime) + table.insert(self.files, { + name = name, + method = code, + crc = if n > 0 then Crc32.of(b) else 0, + size = n, + data = comp, + dataOffset = 0, + dataLength = buffer.len(comp), + time = time, + date = date, + comment = o.comment or "", + utf8 = if o.utf8 ~= nil then o.utf8 else not isAscii(name), + attributes = o.attributes or (if isDir then 0x41ED0010 else 0x81A40000), + }) + return true, nil +end + +function Writer.addRaw(self: any, e: Entry, archive: any, newName: string?): (boolean, Err.Err?) + local b = archive.buf + local start: number? = nil + for _, s in Zip._starts(b, e) do + if s >= 0 and s + e.compressedSize <= buffer.len(b) then + start = s + break + end + end + if not start or bit32.band(e.flags, 1) ~= 0 then + return false, Err.new(Err.CORRUPT, e.name .. ": cannot copy the entry data") + end + local name = newName or e.name + table.insert(self.files, { + name = name, + method = e.method, + crc = e.crc32, + size = e.size, + data = b, + dataOffset = start, + dataLength = e.compressedSize, + time = e.time or 0, + date = e.date or 0x21, + comment = e.comment or "", + utf8 = e.utf8 or not isAscii(name), + attributes = e.attributes or (if e.isDir then 0x41ED0010 else 0x81A40000), + }) + return true, nil +end + +function Writer.finish(self: any, opts: FinishOptions?): (buffer?, Err.Err?) + local comment = opts and opts.comment or "" + if #comment > 65535 then + return nil, Err.new(Err.ARG, "finish: archive comment over 65535 bytes") + end + local force = opts and opts.zip64 or false + local total = 22 + #comment + 98 + for _, f in self.files do + total += 30 + #f.name + 20 + f.dataLength + 46 + #f.name + 28 + #f.comment + end + if total > 0x3FFFFFFF then + return nil, Err.new(Err.LIMIT, "finish: the archive would be over 1 GiB") + end + local w = Bytes.writer(total) + local offsets = {} + for i, f in self.files do + local off = w:tell() + offsets[i] = off + local big = force or f.size >= 0xFFFFFFFF or f.dataLength >= 0xFFFFFFFF + local flags = if f.utf8 then 0x800 else 0 + w:u32le(SIG_LOCAL) + w:u16le(if big then 45 else 20) + w:u16le(flags) + w:u16le(f.method) + w:u16le(f.time) + w:u16le(f.date) + w:u32le(f.crc) + w:u32le(if big then 0xFFFFFFFF else f.dataLength) + w:u32le(if big then 0xFFFFFFFF else f.size) + w:u16le(#f.name) + w:u16le(if big then 20 else 0) + w:string(f.name) + if big then + w:u16le(1) + w:u16le(16) + w:u64le(f.size) + w:u64le(f.dataLength) + end + w:bytes(f.data, f.dataOffset, f.dataLength) + end + local cdOff = w:tell() + for i, f in self.files do + local off = offsets[i] + local bigSize = force or f.size >= 0xFFFFFFFF or f.dataLength >= 0xFFFFFFFF + local bigOff = force or off >= 0xFFFFFFFF + local extra = (if bigSize then 16 else 0) + (if bigOff then 8 else 0) + local version = if bigSize or bigOff then 45 else 20 + w:u32le(SIG_CD) + w:u16le(0x0300 + version) -- made by: Unix + w:u16le(version) + w:u16le(if f.utf8 then 0x800 else 0) + w:u16le(f.method) + w:u16le(f.time) + w:u16le(f.date) + w:u32le(f.crc) + w:u32le(if bigSize then 0xFFFFFFFF else f.dataLength) + w:u32le(if bigSize then 0xFFFFFFFF else f.size) + w:u16le(#f.name) + w:u16le(if extra > 0 then extra + 4 else 0) + w:u16le(#f.comment) + w:u16le(0) -- disk + w:u16le(0) -- internal attributes + w:u32le(f.attributes) + w:u32le(if bigOff then 0xFFFFFFFF else off) + w:string(f.name) + if extra > 0 then + w:u16le(1) + w:u16le(extra) + if bigSize then + w:u64le(f.size) + w:u64le(f.dataLength) + end + if bigOff then + w:u64le(off) + end + end + w:string(f.comment) + end + local cdSize = w:tell() - cdOff + local count = #self.files + local z64 = force or count >= 0xFFFF or cdOff >= 0xFFFFFFFF or cdSize >= 0xFFFFFFFF + if z64 then + local rec = w:tell() + w:u32le(SIG_Z64_EOCD) + w:u64le(44) + w:u16le(0x032D) + w:u16le(45) + w:u32le(0) + w:u32le(0) + w:u64le(count) + w:u64le(count) + w:u64le(cdSize) + w:u64le(cdOff) + w:u32le(SIG_Z64_LOC) + w:u32le(0) + w:u64le(rec) + w:u32le(1) + end + w:u32le(SIG_EOCD) + w:u16le(0) + w:u16le(0) + w:u16le(if z64 then 0xFFFF else count) + w:u16le(if z64 then 0xFFFF else count) + w:u32le(if z64 then 0xFFFFFFFF else cdSize) + w:u32le(if z64 then 0xFFFFFFFF else cdOff) + w:u16le(#comment) + w:string(comment) + return w:finish(), nil +end + +return Zip +end +end + + + + + + core + --!optimize 2 +--!nocheck +-- rosetta chunk core (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 6 modules (5 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["core/Adler32"] = @native function() + + +-- core/Adler32: Adler-32 (RFC 1950, the zlib checksum). Absorbed from deflate-luau src/Deflate/Checksum.luau (same author; +-- no third-party code). Never throws: the range is clamped. +local readu8 = buffer.readu8 + +@native local function adler32(buf: buffer, off: number, len: number, adler: number?): number + local a0 = adler or 1 + local a, b = a0 % 65536, a0 // 65536 + local i, e = off, off + len + while i < e do + -- zlib NMAX: the largest n with 255 n (n + 1) / 2 + (n + 1) (BASE - 1) < 2^32 + local stop = math.min(e, i + 5552) + while i < stop do + a += readu8(buf, i) + b += a + i += 1 + end + a %= 65521 + b %= 65521 + end + return b * 65536 + a +end + +@native local function range(buf: buffer, offset: number?, length: number?): (number, number) + local n = buffer.len(buf) + local o = math.clamp(offset or 0, 0, n) + return o, math.clamp(length or (n - o), 0, n - o) +end + +local Adler32 = {} + +@native function Adler32.of(buf: buffer, offset: number?, length: number?, adler: number?): number + local o, l = range(buf, offset, length) + return adler32(buf, o, l, adler) +end + +@native function Adler32.string(s: string, adler: number?): number + return adler32(buffer.fromstring(s), 0, #s, adler) +end + +Adler32.raw = adler32 + +return Adler32 +end +__FILES["core/Base64"] = @native function() + + +-- 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 <data>, 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 Base64 = {} + +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 = 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, 11, 12, 13, 32 } do + buffer.writeu8(DEC, c, 64) +end +buffer.writeu8(DEC, string.byte("="), 65) + +local readu8, writeu8 = buffer.readu8, buffer.writeu8 + +@native 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 + 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 + if rest > 0 then + 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 + +@native 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 + 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 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 + 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 + +-- RFC 2397: data:[<mime>][;params][;base64],<data> (percent-encoded data when not base64) +@native 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)", @native function(h: string): string + return string.char(tonumber(h, 16) :: number) + end) + return buffer.fromstring(decoded), mime +end + +@native function Base64.dataUri(buf: buffer | string, mime: string?): string + return "data:" .. (mime or "application/octet-stream") .. ";base64," .. Base64.encode(buf) +end + +return Base64 +end +__FILES["core/Bits"] = @native function() + + +-- core/Bits: bit readers and writers, LSB-first (DEFLATE, GIF LZW, VP8L, ...) and MSB-first (JPEG entropy data +-- without the 0xFF00 unstuffing, MPEG, H.264, FLAC, ...). Up to 32 bits per read / write. +-- Plain arithmetic on an accumulator of at most 31 bits (no bit32 calls), exact on doubles, cheap on both runtimes. +-- Never throws: reading past the end returns zero bits and sets the sticky `err` (Err.TRUNCATED). +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") + +local readu8, blen = buffer.readu8, buffer.len +local floor = math.floor + +local POW = table.create(33, 0) +for i = 0, 32 do + POW[i + 1] = 2 ^ i +end + +local Bits = {} +Bits.POW = POW + +type BitReader = { + buf: buffer, + pos: number, -- next byte to load + limit: number, + acc: number, -- loaded, unread bits + cnt: number, -- how many + err: Err.Err?, + read: (BitReader, number) -> number, + peek: (BitReader, number) -> number, + skip: (BitReader, number) -> (), + align: (BitReader) -> (), + bytePos: (BitReader) -> number, + bitsLeft: (BitReader) -> number, +} + +@native local function overrun(self: any) + if not self.err then + self.err = Err.new(Err.TRUNCATED, "bit stream ends early", self.limit) + end +end + +-- LSB-first: the first bit of the stream is bit 0 of the first byte; a field's first bit is its least significant +local Lsb = {} +Lsb.__index = Lsb + +@native local function lsbFill(self: any, n: number) + local acc, cnt, pos = self.acc, self.cnt, self.pos + while cnt < n do + if pos < self.limit then + acc += readu8(self.buf, pos) * POW[cnt + 1] + pos += 1 + else + overrun(self) + end + cnt += 8 + end + self.acc, self.cnt, self.pos = acc, cnt, pos +end + +@native function Lsb.read(self: any, n: number): number + if n > 24 then + local lo = Lsb.read(self, 16) + return lo + Lsb.read(self, n - 16) * 65536 + end + if self.cnt < n then + lsbFill(self, n) + end + local m = POW[n + 1] + local v = self.acc % m + self.acc = (self.acc - v) / m + self.cnt -= n + return v +end +@native function Lsb.peek(self: any, n: number): number + if self.cnt < n then + local acc, cnt, pos = self.acc, self.cnt, self.pos + while cnt < n do -- no error for peeking past the end: the bits are zeros + if pos < self.limit then + acc += readu8(self.buf, pos) * POW[cnt + 1] + pos += 1 + end + cnt += 8 + end + -- keep the loaded bytes only when they are all real (zero padding past the end is not data) + if (pos - self.pos) * 8 == cnt - self.cnt then + self.acc, self.cnt, self.pos = acc, cnt, pos + end + return acc % POW[n + 1] + end + return self.acc % POW[n + 1] +end +@native function Lsb.skip(self: any, n: number) + while n > 24 do + Lsb.read(self, 24) + n -= 24 + end + Lsb.read(self, n) +end +@native function Lsb.align(self: any) + local k = self.cnt % 8 + if k > 0 then + Lsb.read(self, k) + end +end +@native function Lsb.bytePos(self: any): number + return self.pos - floor(self.cnt / 8) +end +@native function Lsb.bitsLeft(self: any): number + return (self.limit - self.pos) * 8 + self.cnt +end + +-- MSB-first: the first bit of the stream is bit 7 of the first byte; a field's first bit is its most significant +local Msb = {} +Msb.__index = Msb + +@native local function msbFill(self: any, n: number) + local acc, cnt, pos = self.acc, self.cnt, self.pos + while cnt < n do + if pos < self.limit then + acc = acc * 256 + readu8(self.buf, pos) + pos += 1 + else + acc *= 256 + overrun(self) + end + cnt += 8 + end + self.acc, self.cnt, self.pos = acc, cnt, pos +end + +@native function Msb.read(self: any, n: number): number + if n > 24 then + local hi = Msb.read(self, n - 16) + return hi * 65536 + Msb.read(self, 16) + end + if self.cnt < n then + msbFill(self, n) + end + local sh = POW[self.cnt - n + 1] + local v = floor(self.acc / sh) + self.acc -= v * sh + self.cnt -= n + return v +end +@native function Msb.peek(self: any, n: number): number + local acc, cnt, pos = self.acc, self.cnt, self.pos + while cnt < n do + if pos < self.limit then + acc = acc * 256 + readu8(self.buf, pos) + pos += 1 + else + acc *= 256 + end + cnt += 8 + end + -- keep the loaded bytes only when they are all real (zero padding past the end is not data) + if (pos - self.pos) * 8 == cnt - self.cnt then + self.acc, self.cnt, self.pos = acc, cnt, pos + end + return floor(acc / POW[cnt - n + 1]) +end +@native function Msb.skip(self: any, n: number) + while n > 24 do + Msb.read(self, 24) + n -= 24 + end + Msb.read(self, n) +end +@native function Msb.align(self: any) + local k = self.cnt % 8 + if k > 0 then + Msb.read(self, k) + end +end +Msb.bytePos = Lsb.bytePos +Msb.bitsLeft = Lsb.bitsLeft + +@native local function reader(meta: any, buf: buffer, offset: number?, length: number?): BitReader + local n = blen(buf) + local o = math.clamp(offset or 0, 0, n) + local l = math.clamp(length or (n - o), 0, n - o) + return setmetatable({ buf = buf, pos = o, limit = o + l, acc = 0, cnt = 0, err = nil }, meta) :: any +end + +@native function Bits.lsbReader(buf: buffer, offset: number?, length: number?): BitReader + return reader(Lsb, buf, offset, length) +end +@native function Bits.msbReader(buf: buffer, offset: number?, length: number?): BitReader + return reader(Msb, buf, offset, length) +end + +type BitWriter = { + out: Bytes.Writer, -- the bytes so far (whole bytes only) + acc: number, + cnt: number, + write: (BitWriter, number, number) -> (), + align: (BitWriter) -> (), + finish: (BitWriter) -> buffer, +} + +local LsbW = {} +LsbW.__index = LsbW +@native function LsbW.write(self: any, v: number, n: number) + if n > 24 then + local lo = v % 65536 + LsbW.write(self, lo, 16) + LsbW.write(self, (v - lo) / 65536, n - 16) + return + end + local acc = self.acc + (v % POW[n + 1]) * POW[self.cnt + 1] + local cnt = self.cnt + n + local out = self.out + while cnt >= 8 do + local byte = acc % 256 + out:u8(byte) + acc = (acc - byte) / 256 + cnt -= 8 + end + self.acc, self.cnt = acc, cnt +end +@native function LsbW.align(self: any) + if self.cnt > 0 then + self.out:u8(self.acc) + self.acc, self.cnt = 0, 0 + end +end +@native function LsbW.finish(self: any): buffer + LsbW.align(self) + return self.out:finish() +end + +local MsbW = {} +MsbW.__index = MsbW +@native function MsbW.write(self: any, v: number, n: number) + if n > 24 then + local lo = v % 65536 + MsbW.write(self, (v - lo) / 65536, n - 16) + MsbW.write(self, lo, 16) + return + end + local acc = self.acc * POW[n + 1] + (v % POW[n + 1]) + local cnt = self.cnt + n + local out = self.out + while cnt >= 8 do + local sh = POW[cnt - 8 + 1] + local byte = floor(acc / sh) + out:u8(byte) + acc -= byte * sh + cnt -= 8 + end + self.acc, self.cnt = acc, cnt +end +@native function MsbW.align(self: any) + if self.cnt > 0 then + self.out:u8(self.acc * POW[8 - self.cnt + 1]) + self.acc, self.cnt = 0, 0 + end +end +@native function MsbW.finish(self: any): buffer + MsbW.align(self) + return self.out:finish() +end + +-- w = { buf, pos, acc, cnt }: no growth (the caller keeps buf large enough); acc holds cnt < 8 bits +type RawWriter = { buf: buffer, pos: number, acc: number, cnt: number } +@native 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 + +@native function Bits.lsbWriter(capacity: number?): BitWriter + return setmetatable({ out = Bytes.writer(capacity), acc = 0, cnt = 0 }, LsbW) :: any +end +@native function Bits.msbWriter(capacity: number?): BitWriter + return setmetatable({ out = Bytes.writer(capacity), acc = 0, cnt = 0 }, MsbW) :: any +end + +return Bits +end +__FILES["core/Crc16"] = @native function() + + +-- core/Crc16: the 16-bit CRCs old archive formats use, table driven. New code. ccitt: CRC-16/XMODEM (0x1021, MSB first, +-- init 0, no final XOR; BinHex 4.0, MacBinary II / III). arc: CRC-16/ARC (0x8005 reflected = 0xA001, init 0; LHA, Zoo, +-- ARC). Never throws: the range is clamped. +local band, bxor, rshift, lshift = bit32.band, bit32.bxor, bit32.rshift, bit32.lshift +local readu8 = buffer.readu8 + +local MSB = table.create(256, 0) +local ARC = table.create(256, 0) +for n = 0, 255 do + local c = lshift(n, 8) + for _ = 1, 8 do + c = if band(c, 0x8000) ~= 0 then bxor(band(lshift(c, 1), 0xFFFF), 0x1021) else band(lshift(c, 1), 0xFFFF) + end + MSB[n + 1] = c + local r = n + for _ = 1, 8 do + r = if band(r, 1) ~= 0 then bxor(rshift(r, 1), 0xA001) else rshift(r, 1) + end + ARC[n + 1] = r +end + +local Crc16 = {} + +@native local function clamp(buf: buffer, off: number, len: number): (number, number) + local n = buffer.len(buf) + local o = math.clamp(math.floor(off), 0, n) + return o, math.clamp(math.floor(len), 0, n - o) +end + +@native function Crc16.ccitt(buf: buffer, off: number, len: number, crc: number?): number + local o, l = clamp(buf, off, len) + local c = crc or 0 + for i = o, o + l - 1 do + c = bxor(band(lshift(c, 8), 0xFFFF), MSB[bxor(rshift(c, 8), readu8(buf, i)) + 1]) + end + return c +end + +@native function Crc16.arc(buf: buffer, off: number, len: number, crc: number?): number + local o, l = clamp(buf, off, len) + local c = crc or 0 + for i = o, o + l - 1 do + c = bxor(rshift(c, 8), ARC[bxor(band(c, 0xFF), readu8(buf, i)) + 1]) + end + return c +end + +return Crc16 +end +__FILES["core/Md5"] = @native function() + + + +-- core/Md5: MD5 (RFC 1321), incremental. Written from the RFC. Used by the FLAC encoder (STREAMINFO's MD5 of the PCM); +-- not for security. +-- Never throws (ranges are clamped to the buffer). +local Md5 = {} + +local band, bor, bxor, bnot, lrotate = bit32.band, bit32.bor, bit32.bxor, bit32.bnot, bit32.lrotate +local readu32, writeu32, writeu8 = buffer.readu32, buffer.writeu32, buffer.writeu8 + +local K = table.create(64, 0) +for i = 0, 63 do + K[i + 1] = math.floor(math.abs(math.sin(i + 1)) * 4294967296) % 4294967296 +end +local S = { + 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, + 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, + 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, + 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, +} +local G = table.create(64, 0) +for i = 0, 63 do + if i < 16 then + G[i + 1] = i + elseif i < 32 then + G[i + 1] = (5 * i + 1) % 16 + elseif i < 48 then + G[i + 1] = (3 * i + 5) % 16 + else + G[i + 1] = (7 * i) % 16 + end +end + +type State = { + a: number, + b: number, + c: number, + d: number, + block: buffer, -- 64-byte pending block + fill: number, + total: number, -- bytes hashed + update: (self: State, buf: buffer, offset: number?, length: number?) -> (), + digest: (self: State) -> string, +} + +local M = table.create(16, 0) + +@native local function compress(st: State, blk: buffer, o: number) + for i = 0, 15 do + M[i + 1] = readu32(blk, o + i * 4) + end + local a, b, c, d = st.a, st.b, st.c, st.d + for i = 0, 63 do + local f + if i < 16 then + f = bor(band(b, c), band(bnot(b), d)) + elseif i < 32 then + f = bor(band(d, b), band(bnot(d), c)) + elseif i < 48 then + f = bxor(b, c, d) + else + f = bxor(c, bor(b, bnot(d))) + end + local tmp = d + d = c + c = b + b = (b + lrotate((a + f + K[i + 1] + M[G[i + 1] + 1]) % 4294967296, S[i + 1])) % 4294967296 + a = tmp + end + st.a = (st.a + a) % 4294967296 + st.b = (st.b + b) % 4294967296 + st.c = (st.c + c) % 4294967296 + st.d = (st.d + d) % 4294967296 +end + +@native local function update(self: State, buf: buffer, offset: number?, length: number?) + local n = buffer.len(buf) + local o = math.clamp(offset or 0, 0, n) + local len = math.clamp(length or (n - o), 0, n - o) + self.total += len + local blk = self.block + if self.fill > 0 then + local take = math.min(64 - self.fill, len) + buffer.copy(blk, self.fill, buf, o, take) + self.fill += take + o += take + len -= take + if self.fill == 64 then + compress(self, blk, 0) + self.fill = 0 + end + end + while len >= 64 do + compress(self, buf, o) + o += 64 + len -= 64 + end + if len > 0 then + buffer.copy(blk, 0, buf, o, len) + self.fill = len + end +end + +@native local function digest(self: State): string + local bits = self.total * 8 + local blk = self.block + local f = self.fill + writeu8(blk, f, 0x80) + f += 1 + if f > 56 then + buffer.fill(blk, f, 0, 64 - f) + compress(self, blk, 0) + f = 0 + end + buffer.fill(blk, f, 0, 56 - f) + writeu32(blk, 56, bits % 4294967296) + writeu32(blk, 60, math.floor(bits / 4294967296) % 4294967296) + compress(self, blk, 0) + self.fill = 0 + local out = buffer.create(16) + writeu32(out, 0, self.a) + writeu32(out, 4, self.b) + writeu32(out, 8, self.c) + writeu32(out, 12, self.d) + return buffer.tostring(out) +end + +@native function Md5.new(): State + return { + a = 0x67452301, + b = 0xEFCDAB89, + c = 0x98BADCFE, + d = 0x10325476, + block = buffer.create(64), + fill = 0, + total = 0, + update = update, + digest = digest, + } +end + +@native function Md5.hex(d: string): string + local out = table.create(#d) + for i = 1, #d do + out[i] = string.format("%02x", string.byte(d, i)) + end + return table.concat(out) +end + +@native function Md5.of(buf: buffer, offset: number?, length: number?): string + local h = Md5.new() + h:update(buf, offset, length) + return Md5.hex(h:digest()) +end + +return Md5 +end +__FILES["core/Sniff"] = function() + +-- 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. +local Sniff = {} + +type Peeker = { peek: (any, number, number?) -> string } + +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 + +function Sniff.dropBom(s: string): string + return if string.sub(s, 1, 3) == "\239\187\191" then string.sub(s, 4) else s +end + +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 +end +end + + + + + + data + --!optimize 2 +--!nocheck +-- rosetta chunk data (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 18 modules (3 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["data/cbor"] = function() + +-- data/cbor: CBOR (RFC 8949), new code. Supports: every major type, indefinite lengths, half / single / double +-- floats, tags 0 / 1 (Types.Date), 2 / 3 (bignums), 55799 (stripped), others as Cbor.tagged; simple values; sequences +-- (RFC 8742). Encode: shortest heads, definite lengths. Not supported: other semantic tags (kept as tagged values). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Codec = __include("data/cbor/Codec") + +-- ------------------------------------------------------------------------------------------------ contract +local Cbor = { + name = "cbor", + category = "data", + extensions = { "cbor" }, + mime = { "application/cbor", "application/cbor-seq" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, binary = true, ordered = true, tags = true }, +} + +type DecodeOptions = Codec.DecodeOptions & { + all: boolean?, -- default false +} +type EncodeOptions = Codec.EncodeOptions & { + all: boolean?, + selfDescribe: boolean?, -- 55799 tag prefix (d9 d9 f7) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Cbor.sniff(r: Bytes.Reader): number + return if r:peek(3) == "\217\217\247" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function codeOf(e: string): string + if string.find(e, "truncated", 1, true) or string.find(e, "past the end", 1, true) then + return Err.TRUNCATED + elseif string.find(e, "nested deeper", 1, true) then + return Err.LIMIT + end + return Err.CORRUPT +end + +function Cbor.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + if o.all then + local out = {} + while not r:eof() do + local v, e, at = Codec.decode(r, o) + if e then + return nil, Err.new(codeOf(e), e, at) + end + table.insert(out, v) + end + return out, nil + end + local v, e, at = Codec.decode(r, o) + if e then + return nil, Err.new(codeOf(e), e, at) + end + if not r:eof() then + return nil, Err.new(Err.CORRUPT, "trailing data after the item (opts.all reads a sequence)", r.pos - r.base) + end + return v, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Cbor.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local w = Bytes.writer() + if opts and opts.selfDescribe then + w:string("\217\217\247") + end + local items = { value } + if opts and opts.all then + if type(value) ~= "table" then + return nil, Err.new(Err.ARG, "all: expected an array of items") + end + items = value + end + for _, v in items do + local b, e = Codec.encode(v, opts) + if not b then + return nil, Err.new(Err.ARG, e or "cannot encode") + end + w:bytes(b) + end + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +Cbor.tagged = Codec.tagged +Cbor.isTagged = Codec.isTagged +Cbor.simple = Codec.simple +Cbor.isSimple = Codec.isSimple +Cbor.undefined = Codec.undefined + +return Cbor +end +__FILES["data/cbor/Codec"] = @native function() + + +-- data/cbor/Codec: CBOR (RFC 8949) decoder and encoder; never throws (errors return nil, message, offset). +local Bytes = __include("core/Bytes") +local Types = __include("Types") + +local Codec = {} + +local TWO32 = 4294967296 + +-- ------------------------------------------------------------------------------------------------ value types +local TaggedMeta = { __tostring = @native function(t: any): string + return "cbor.tag(" .. t.tag .. ")" +end } +local SimpleMeta = { __tostring = @native function(s: any): string + return "cbor.simple(" .. s.value .. ")" +end } +@native function Codec.tagged(tag: number, value: any): { tag: number, value: any } + return setmetatable({ tag = tag, value = value }, TaggedMeta) :: any +end +@native function Codec.isTagged(v: any): boolean + return type(v) == "table" and getmetatable(v) == TaggedMeta +end +-- unassigned simple values: 0..19, 32..255 +@native function Codec.simple(n: number): { value: number } + return setmetatable({ value = n }, SimpleMeta) :: any +end +@native function Codec.isSimple(v: any): boolean + return type(v) == "table" and getmetatable(v) == SimpleMeta +end +Codec.undefined = table.freeze(setmetatable({}, { __tostring = @native function() + return "undefined" +end })) + +@native local function bigText(s: string): string + local limbs = {} -- base 1e7, little-endian + for i = 1, #s do + local carry = string.byte(s, i) + for k = 1, #limbs do + local v = limbs[k] * 256 + carry + limbs[k] = v % 10000000 + carry = v // 10000000 + end + while carry > 0 do + table.insert(limbs, carry % 10000000) + carry //= 10000000 + end + end + if #limbs == 0 then + return "0" + end + local out = { string.format("%d", limbs[#limbs]) } + for k = #limbs - 1, 1, -1 do + table.insert(out, string.format("%07d", limbs[k])) + end + return table.concat(out) +end +@native local function incText(s: string): string + local digits: { number } = table.create(#s) :: { number } + for i = 1, #s do + digits[i] = string.byte(s, i) - 48 + end + local i = #digits + while i >= 1 do + if digits[i] < 9 then + digits[i] += 1 + break + end + digits[i] = 0 + i -= 1 + end + local out: { string } = table.create(#digits) :: { string } + for k, d in digits do + out[k] = string.char(48 + d) + end + return (if i == 0 then "1" else "") .. table.concat(out) +end + +type DecodeOptions = { + bigInts: ("number" | "string")?, + null: any?, -- default Types.null + undefined: any?, -- default Codec.undefined + maxDepth: number?, -- default 512 + dates: boolean?, -- default true +} + +type St = { r: Bytes.Reader, big: boolean, null: any, undef: any, maxDepth: number, dates: boolean } + +local BREAK = {} -- 0xFF break stop code + +-- additional information 31: indefinite length +@native local function arg(st: St, ai: number): (number?, string?, string?) + local r = st.r + if ai < 24 then + return ai, nil, nil + elseif ai == 24 then + return r:u8(), nil, nil + elseif ai == 25 then + return r:u16be(), nil, nil + elseif ai == 26 then + return r:u32be(), nil, nil + elseif ai == 27 then + local hi, lo = r:u32be(), r:u32be() + if st.big and hi >= 0x200000 then + return hi * TWO32 + lo, bigText(string.char(hi // 16777216, (hi // 65536) % 256, (hi // 256) % 256, hi % 256, lo // 16777216, (lo // 65536) % 256, (lo // 256) % 256, lo % 256)), nil + end + return hi * TWO32 + lo, nil, nil + elseif ai == 31 then + return nil, nil, nil + end + return nil, nil, "reserved additional information " .. ai +end + +local item: (st: St, depth: number) -> (any, string?) + +@native local function chunks(st: St, major: number, depth: number): (string?, string?) + local parts = {} + while true do + local r = st.r + local ib = r:u8() + if r.err then + return nil, "truncated" + end + if ib == 0xFF then + return table.concat(parts), nil + end + if ib // 32 ~= major then + return nil, "bad chunk in an indefinite string" + end + local n, _, e = arg(st, ib % 32) + if e or n == nil then + return nil, e or "nested indefinite string" + end + if r.err or not r:need(n) then + return nil, "truncated string" + end + table.insert(parts, r:string(n)) + end +end + +local half = Bytes.half + +@native local function tag(st: St, t: number, v: any): (any, string?) + if t == 0 and st.dates then + if type(v) ~= "string" then + return nil, "tag 0 needs a text string" + end + local d = Types.Date.parse(v) + if not d or not d.offset then + return nil, "tag 0: bad date-time " .. v + end + return d, nil + elseif t == 1 and st.dates then + if type(v) ~= "number" or v ~= v or v == math.huge or v == -math.huge then + return nil, "tag 1 needs a number" + end + return Types.Date.fromUnix(v), nil + elseif t == 2 or t == 3 then + if type(v) ~= "string" then + return nil, "bignum tag needs a byte string" + end + local s = v :: string + local n = 0 + for i = 1, #s do + n = n * 256 + string.byte(s, i) + end + if n >= 9007199254740992 then + -- read back from the exact text: correctly rounded, unlike the running sum + local text = bigText(s) + if t == 3 then + text = incText(text) + end + if st.big then + return if t == 2 then text else "-" .. text, nil + end + local x = tonumber(text) :: number + return if t == 2 then x else -x, nil + end + return if t == 2 then n else -1 - n, nil + elseif t == 55799 then + return v, nil + end + return Codec.tagged(t, v), nil +end + +@native function item(st: St, depth: number): (any, string?) + if depth > st.maxDepth then + return nil, "nested deeper than " .. st.maxDepth + end + local r = st.r + local ib = r:u8() + if r.err then + return nil, "truncated" + end + local major, ai = ib // 32, ib % 32 + if major == 7 then + if ai < 20 then + return Codec.simple(ai), nil + elseif ai == 20 then + return false, nil + elseif ai == 21 then + return true, nil + elseif ai == 22 then + return st.null, nil + elseif ai == 23 then + return st.undef, nil + elseif ai == 24 then + local n = r:u8() + if r.err then + return nil, "truncated" + end + if n < 32 then + return nil, "bad two-byte simple value" + end + return Codec.simple(n), nil + elseif ai == 25 then + local h = r:u16be() + return if r.err then nil else half(h), if r.err then "truncated" else nil + elseif ai == 26 then + local f = r:f32be() + return if r.err then nil else f, if r.err then "truncated" else nil + elseif ai == 27 then + local f = r:f64be() + return if r.err then nil else f, if r.err then "truncated" else nil + elseif ai == 31 then + return BREAK, nil + end + return nil, "reserved simple value" + end + local n, text, e = arg(st, ai) + if e then + return nil, e + end + if r.err then + return nil, "truncated" + end + if major == 0 then + if n == nil then + return nil, "indefinite integer" + end + return text or n, nil + elseif major == 1 then + if n == nil then + return nil, "indefinite integer" + end + if text then + return "-" .. incText(text), nil + end + return -1 - n, nil + elseif major == 2 or major == 3 then + local s: string + if n == nil then + local c, ce = chunks(st, major, depth) + if not c then + return nil, ce + end + s = c + else + if not r:need(n) then + return nil, "truncated string" + end + s = r:string(n) + end + if major == 2 then + return buffer.fromstring(s), nil + end + if string.find(s, "[\128-\255]") and not utf8.len(s) then + return nil, "invalid UTF-8 in a text string" + end + return s, nil + elseif major == 4 then + if n == nil then + local t = {} + while true do + local v, ve = item(st, depth + 1) + if ve then + return nil, ve + end + if v == BREAK then + return t, nil + end + table.insert(t, v) + end + end + if (n :: number) > r:remaining() then + return nil, "array count past the end" + end + 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 + end + if v == BREAK then + return nil, "unexpected break" + end + t[k] = v + end + return t, nil + elseif major == 5 then + if n ~= nil and n * 2 > r:remaining() then + return nil, "map count past the end" + end + local t = {} + local order = {} + local k = 0 + while n == nil or k < n do + k += 1 + local key, ke = item(st, depth + 1) + if ke then + return nil, ke + end + if key == BREAK then + if n == nil then + break + end + return nil, "unexpected break" + end + local v, ve = item(st, depth + 1) + if ve then + return nil, ve + end + if v == BREAK then + return nil, "unexpected break" + end + if key ~= key then + return nil, "NaN map key" + end + if t[key] == nil then + table.insert(order, key) + end + t[key] = v + end + return Types.object(t, order), nil + else -- 6: tag + if n == nil then + return nil, "indefinite tag" + end + local v, ve = item(st, depth + 1) + if ve then + return nil, ve + end + if v == BREAK then + return nil, "unexpected break" + end + if (n == 2 or n == 3) and type(v) == "buffer" then + return tag(st, n, buffer.tostring(v)) + end + return tag(st, n, v) + end +end + +@native function Codec.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, string?, number?) + local o: DecodeOptions = opts or {} + local st: St = { + r = r, + big = o.bigInts == "string", + null = if o.null ~= nil then o.null else Types.null, + undef = if o.undefined ~= nil then o.undefined else Codec.undefined, + maxDepth = o.maxDepth or 512, + dates = o.dates ~= false, + } + local v, e = item(st, 0) + if e then + return nil, e, r.pos - r.base + end + if v == BREAK then + return nil, "unexpected break", r.pos - r.base - 1 + end + return v, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +type EncodeOptions = { + compactFloats: boolean?, -- default false + sortKeys: boolean?, -- default true + emptyTable: ("array" | "map")?, -- default "array" + dates: ("string" | "epoch")?, -- tag 0 text (default) or tag 1 epoch seconds + maxDepth: number?, -- default 512 (also catches cycles) +} + +type ESt = { w: Bytes.Writer, compact: boolean, sort: boolean, emptyMap: boolean, epoch: boolean, maxDepth: number, err: string? } + +@native local function head(w: Bytes.Writer, major: number, n: number) + local m = major * 32 + if n < 24 then + w:u8(m + n) + elseif n < 256 then + w:u8(m + 24) + w:u8(n) + elseif n < 65536 then + w:u8(m + 25) + w:u16be(n) + elseif n < TWO32 then + w:u8(m + 26) + w:u32be(n) + elseif n >= 18446744073709551616 then -- -1 - (-2^64) rounds up to 2^64: the exact argument is 2^64 - 1 + w:u8(m + 27) + w:u32be(0xFFFFFFFF) + w:u32be(0xFFFFFFFF) + else + w:u8(m + 27) + w:u64be(n) + end +end + +@native local function toHalf(x: number): number? + if x ~= x then + return 0x7E00 + end + local sign = if x < 0 or (x == 0 and 1 / x < 0) then 0x8000 else 0 + local a = math.abs(x) + if a == math.huge then + return sign + 0x7C00 + end + if a == 0 then + return sign + end + local m, e = math.frexp(a) + local exp = e - 1 + 15 + if exp >= 31 then + return nil + end + if exp <= 0 then -- subnormal: a = mant * 2^-24 + local mant = a / 2 ^ -24 + if mant ~= math.floor(mant) or mant >= 1024 then + return nil + end + return sign + mant + end + local frac = (m * 2 - 1) * 1024 + if frac ~= math.floor(frac) then + return nil + end + return sign + exp * 1024 + frac +end +Codec.toHalf = toHalf + +local keyLess = Types.keyLess + +local isArray = Types.isArray + +local scratch = buffer.create(8) + +@native local function enc(st: ESt, v: any, depth: number): boolean + local w = st.w + local tv = type(v) + if v == nil or v == Types.null then + w:u8(0xF6) + elseif v == Codec.undefined then + w:u8(0xF7) + elseif tv == "boolean" then + w:u8(if v then 0xF5 else 0xF4) + elseif tv == "number" then + if v == math.floor(v) and v >= -18446744073709551616 and v < 18446744073709551616 and not (v == 0 and 1 / v < 0) then + if v >= 0 then + head(w, 0, v) + else + head(w, 1, -1 - v) + end + else + local h = if st.compact then toHalf(v) else nil + if h then + w:u8(0xF9) + w:u16be(h) + else + buffer.writef32(scratch, 0, v) + if st.compact and (buffer.readf32(scratch, 0) == v or v ~= v) then + w:u8(0xFA) + w:f32be(v) + else + w:u8(0xFB) + w:f64be(v) + end + end + end + elseif tv == "string" then + head(w, 3, #v) + w:string(v) + elseif tv == "buffer" then + head(w, 2, buffer.len(v)) + w:bytes(v) + elseif tv == "table" then + if depth >= st.maxDepth then + st.err = "nested deeper than " .. st.maxDepth .. " (a cycle?)" + return false + end + if Codec.isTagged(v) then + if type(v.tag) ~= "number" or v.tag < 0 or v.tag ~= math.floor(v.tag) then + st.err = "bad tag number" + return false + end + head(w, 6, v.tag) + return enc(st, v.value, depth + 1) + elseif Codec.isSimple(v) then + local n = v.value + if n < 20 then + w:u8(0xE0 + n) + elseif n >= 32 and n < 256 then + w:u8(0xF8) + w:u8(n) + else + st.err = "bad simple value " .. tostring(n) + return false + end + elseif Types.Date.is(v) then + if st.epoch then + w:u8(0xC1) + return enc(st, Types.Date.toUnix(v), depth + 1) + end + w:u8(0xC0) + local s = tostring(v) + head(w, 3, #s) + w:string(s) + elseif isArray(v, st.emptyMap) then + local n = #v + head(w, 4, n) + for k = 1, n do + if not enc(st, v[k], depth + 1) then + return false + end + end + else + local keys: { any } + if Types.isObject(v) then + keys = Types.keys(v) + else + keys = {} + for k in next, v do + table.insert(keys, k) + end + if st.sort then + table.sort(keys, keyLess) + end + end + head(w, 5, #keys) + for _, k in keys do + if not enc(st, k, depth + 1) or not enc(st, v[k], depth + 1) then + return false + end + end + end + else + st.err = "cannot encode a " .. tv + return false + end + return true +end + +@native function Codec.encode(v: any, opts: EncodeOptions?): (buffer?, string?) + local o: EncodeOptions = opts or {} + local st: ESt = { + w = Bytes.writer(256), + compact = o.compactFloats == true, + sort = o.sortKeys ~= false, + emptyMap = o.emptyTable == "map", + epoch = o.dates == "epoch", + maxDepth = o.maxDepth or 512, + err = nil, + } + if not enc(st, v, 0) then + return nil, st.err + end + return st.w:finish(), nil +end + +return Codec +end +__FILES["data/csv"] = function() + +-- data/csv: comma-separated values (RFC 4180, read as leniently as Python's csv), new code. Supports: one-byte or +-- "auto" delimiter, quoted fields with "" and line breaks, CRLF / LF / CR, header rows, numbers by option; encode +-- quotes minimally (QUOTE_MINIMAL) or always. Not supported: other escapes, multi-byte delimiters. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Sniff = __include("core/Sniff") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Json = __include("codecs/text/Json") + +-- ------------------------------------------------------------------------------------------------ contract +local Csv = { + name = "csv", + category = "data", + extensions = { "csv", "tsv" }, + mime = { "text/csv", "text/tab-separated-values" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Json", "core/Sniff" }, + caps = { decode = true, encode = true, header = true }, +} + +type DecodeOptions = { + delimiter: string?, -- default ","; "auto": one of , ; tab | + quote: string?, -- default '"' + header: boolean?, -- default false + numbers: boolean?, -- default false + maxRows: number?, -- default unlimited +} +type EncodeOptions = { + delimiter: string?, -- default "," + quote: string?, -- default '"' + newline: string?, -- default "\r\n" (RFC 4180) + quoteAll: boolean?, -- default false + columns: { string }?, -- default: keys in first-seen order + header: boolean?, -- default true +} + +-- ------------------------------------------------------------------------------------------------ constants +local find, sub, byte, gsub = string.find, string.sub, string.byte, string.gsub + +local function patEscape(c: string): string + return (gsub(c, "[%^%$%(%)%%%.%[%]%*%+%-%?]", "%%%0")) +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Csv.sniff(r: Bytes.Reader): number + local head = r:peek(1024) + if find(head, "%z") then + return 0 + end + local l1, l2 = string.match(head, "^([^\r\n]*)\r?\n([^\r\n]*)") + if not l1 or l1 == "" then + return 0 + end + for _, d in { ",", "\t", ";" } do + local _, c1 = gsub(l1, d, "") + local _, c2 = gsub(l2 :: string, d, "") + if c1 > 0 and c1 == c2 then + return 0.15 + end + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function guess(s: string, q: string): string + local line = string.match(s, "^[^\r\n]*") or "" + line = gsub(line, patEscape(q) .. "[^" .. patEscape(q) .. "]*" .. patEscape(q), "") + local best, bestN = ",", 0 + for _, d in { ",", ";", "\t", "|" } do + local _, n = gsub(line, patEscape(d), "") + if n > bestN then + best, bestN = d, n + end + end + return best +end + +function Csv.parse(s: string, opts: DecodeOptions?): ({ { string } }?, Err.Err?) + local o: DecodeOptions = opts or {} + local q = o.quote or '"' + local d = o.delimiter or "," + if d == "auto" then + d = guess(s, q) + end + if #d ~= 1 or #q ~= 1 or d == q or d == "\n" or d == "\r" then + return nil, Err.new(Err.ARG, "delimiter and quote must be single, different bytes (not line ends)") + end + local qb, db = byte(q), byte(d) + local stop = "[" .. patEscape(d) .. "\r\n]" + local maxRows = o.maxRows or math.huge + local rows: { { string } } = {} + local row: { string } = {} + local n = #s + local i = 1 + local rowEmpty = true + while true do + local c = byte(s, i) + local field: string + if c == qb then + local k = i + 1 + local parts = {} + while true do + local j = find(s, q, k, true) + if not j then + return nil, Err.new(Err.TRUNCATED, "unterminated quoted field", i - 1) + end + if byte(s, j + 1) == qb then + table.insert(parts, sub(s, k, j)) + k = j + 2 + else + table.insert(parts, sub(s, k, j - 1)) + i = j + 1 + break + end + end + -- text after the closing quote up to the delimiter is kept (Python's lenient reading) + local e = find(s, stop, i) or (n + 1) + if e > i then + table.insert(parts, sub(s, i, e - 1)) + end + i = e + field = table.concat(parts) + rowEmpty = false + else + local e = find(s, stop, i) or (n + 1) + field = sub(s, i, e - 1) + if e > i then + rowEmpty = false + end + i = e + end + table.insert(row, field) + c = byte(s, i) + if c == db then + rowEmpty = false + i += 1 + else + if c == 13 and byte(s, i + 1) == 10 then + i += 2 + elseif c ~= nil then + i += 1 + end + if not rowEmpty then + table.insert(rows, row) + if #rows > maxRows then + return nil, Err.new(Err.LIMIT, "more than " .. maxRows .. " rows") + end + end + row = {} + rowEmpty = true + if i > n then + break + end + end + end + return rows, nil +end + +local NUMBER = "^%s*[%-%+]?%d+%.?%d*[eE]?[%-%+]?%d*%s*$" +local function convert(v: string): any + if string.match(v, NUMBER) or string.match(v, "^%s*[%-%+]?%.%d+[eE]?[%-%+]?%d*%s*$") then + local x = tonumber(v) + if x then + return x + end + end + return v +end + +function Csv.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local s = buffer.readstring(r.buf, r.base, r.limit - r.base) + s = Sniff.dropBom(s) + local rows, err = Csv.parse(s, opts) + if not rows then + return nil, err + end + local o: DecodeOptions = opts or {} + if o.numbers then + for _, row in rows do + for k, v in row do + row[k] = convert(v) + end + end + end + if not o.header then + return rows, nil + end + local names = rows[1] or {} + local out = table.create(math.max(#rows - 1, 0)) + for k = 2, #rows do + local row = rows[k] + local obj = Types.object() + for c, name in names do + if row[c] ~= nil then + Types.set(obj, tostring(name), row[c]) + end + end + out[k - 1] = obj + end + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function text(v: any): (string?, string?) + local tv = type(v) + if tv == "string" then + return v, nil + elseif tv == "number" then + local s = Json.number(v) + if not s then + return if v ~= v then "nan" elseif v > 0 then "inf" else "-inf", nil + end + return s, nil + elseif tv == "boolean" then + return if v then "true" else "false", nil + elseif v == nil or v == Types.null then + return "", nil + elseif tv == "table" and Types.Date.is(v) then + return tostring(v), nil + end + return nil, "cannot write a " .. tv .. " as a field" +end + +local function isArray(t: any): boolean + if type(t) ~= "table" or Types.isObject(t) then + return false + end + local n = #t + return n > 0 or next(t) == nil +end + +function Csv.encode(rows: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local d, q, nl = o.delimiter or ",", o.quote or '"', o.newline or "\r\n" + if #d ~= 1 or #q ~= 1 or d == q then + return nil, Err.new(Err.ARG, "delimiter and quote must be single, different bytes") + end + if type(rows) ~= "table" then + return nil, Err.new(Err.ARG, "expected an array of rows") + end + local special = "[" .. patEscape(d) .. patEscape(q) .. "\r\n]" + local qq = q .. q + local out: { string } = {} + local function writeRow(fields: { any }, count: number): Err.Err? + local parts = table.create(count) + for k = 1, count do + local s, e = text(fields[k]) + if not s then + return Err.new(Err.ARG, "row " .. (#out + 1) .. ", field " .. k .. ": " .. tostring(e)) + end + if o.quoteAll or find(s, special) or (count == 1 and s == "") then + s = q .. gsub(s, patEscape(q), qq) .. q + end + parts[k] = s + end + table.insert(out, table.concat(parts, d) .. nl) + return nil + end + local keyed = rows[1] ~= nil and not isArray(rows[1]) + if keyed then + local cols = o.columns + if not cols then + local seen, list = {}, {} + for _, row in rows do + if type(row) ~= "table" then + return nil, Err.new(Err.ARG, "rows must be tables") + end + for _, k in Types.keys(row) do + if not seen[k] then + seen[k] = true + table.insert(list, k) + end + end + end + cols = list + end + local cl = cols :: { any } + if o.header ~= false then + local e = writeRow(cl, #cl) + if e then + return nil, e + end + end + for _, row in rows do + local fields = table.create(#cl) + for k, name in cl do + fields[k] = row[name] + end + local e = writeRow(fields, #cl) + if e then + return nil, e + end + end + else + for _, row in rows do + if type(row) ~= "table" then + return nil, Err.new(Err.ARG, "rows must be arrays of fields") + end + local e = writeRow(row, #row) + if e then + return nil, e + end + end + end + return buffer.fromstring(table.concat(out)), nil +end + +return Csv +end +__FILES["data/ini"] = function() + +-- data/ini: INI files read the way Python's configparser does (interpolation off, key case kept), new code. Supports: +-- [sections], key = / key:, ; and # comments, continuation lines, top-level keys, duplicates (last wins), inline +-- comments, keys without values, typed values by option. Not supported: interpolation, DEFAULT inheritance, escapes. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Sniff = __include("core/Sniff") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Json = __include("codecs/text/Json") + +-- ------------------------------------------------------------------------------------------------ contract +local Ini = { + name = "ini", + category = "data", + extensions = { "ini", "cfg", "conf", "inf", "desktop" }, + mime = { "text/plain" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Json", "core/Sniff" }, + caps = { decode = true, encode = true, ordered = true }, +} + +type DecodeOptions = { + inlineComments: boolean?, -- default false (configparser) + allowNoValue: boolean?, -- default false + types: boolean?, + strict: boolean?, -- default false +} +type EncodeOptions = { + delimiter: string?, -- default " = " +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Ini.sniff(r: Bytes.Reader): number + local head = r:peek(512) + if string.find(head, "%z") then + return 0 + end + local first = string.match(head, "^[%s]*([^\r\n]*)") + while first and string.match(first, "^[;#]") do + head = string.match(head, "^[^\n]*\n(.*)$") or "" + first = string.match(head, "^[%s]*([^\r\n]*)") + end + if first and string.match(first, "^%[[^%]]+%]%s*$") then + return 0.2 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local BOOLS: { [string]: boolean } = { ["true"] = true, ["false"] = false, yes = true, no = false, on = true, off = false } + +local function typed(v: any): any + if type(v) ~= "string" then + return v + end + local b = BOOLS[string.lower(v)] + if b ~= nil then + return b + end + if string.match(v, "^[%-%+]?%d+%.?%d*[eE]?[%-%+]?%d*$") or string.match(v, "^[%-%+]?%.%d+$") or string.match(v, "^0x%x+$") then + local n = tonumber(v) + if n then + return n + end + end + return v +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) + s = Sniff.dropBom(s) + local root = Types.object() + local cur = root + local lastKey: string? = nil + local lastIndent = 0 + local lastTable: any = nil + local seenKeys: { [any]: { [string]: boolean } } = {} + local pos = 1 + local lineStart = 0 + for line in string.gmatch(s .. "\n", "([^\n]*)\n") do + lineStart = pos - 1 + pos += #line + 1 + line = string.gsub(line, "\r$", "") + local indent = #(string.match(line, "^[ \t]*") :: string) + local trimmed = string.match(line, "^%s*(.-)%s*$") :: string + if trimmed == "" then + lastKey = nil + elseif string.match(trimmed, "^[;#]") then + -- configparser: comment lines may be indented and do not end a continuation + elseif lastKey and indent > lastIndent then + local v = trimmed + if o.inlineComments then + v = string.match(v, "^(.-)%s+[;#]") or v + end + local prev = lastTable[lastKey] + lastTable[lastKey] = (if type(prev) == "string" then prev else "") .. "\n" .. v + elseif string.sub(trimmed, 1, 1) == "[" and string.find(trimmed, "]", 2, true) then + local name = string.match(trimmed, "^%[(.*)%]") :: string + local existing = root[name] + if existing ~= nil and type(existing) ~= "table" then + return nil, Err.new(Err.CORRUPT, "section [" .. name .. "] has the name of a top-level key", lineStart) + end + if existing and o.strict then + return nil, Err.new(Err.CORRUPT, "duplicate section [" .. name .. "]", lineStart) + end + if not existing then + existing = Types.object() + Types.set(root, name, existing) + end + cur = existing + lastKey = nil + else + local key, value = string.match(trimmed, "^(.-)%s*[=:]%s*(.*)$") + if not key then + if not o.allowNoValue then + return nil, Err.new(Err.CORRUPT, "line without '=' or ':': " .. string.sub(trimmed, 1, 40), lineStart) + end + key, value = trimmed, true :: any + end + if key == "" then + return nil, Err.new(Err.CORRUPT, "empty key", lineStart) + end + if o.inlineComments and type(value) == "string" then + value = string.match(value, "^(.-)%s+[;#]") or (if string.match(value, "^[;#]") then "" else value) + end + local seen = seenKeys[cur] + if not seen then + seen = {} + seenKeys[cur] = seen + end + if seen[key :: string] and o.strict then + 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 :: string) .. " has the name of a section", lineStart) + end + Types.set(cur, key, value) + lastKey, lastIndent, lastTable = key, indent, cur + end + end + if o.types then + for _, k in Types.keys(root) do + local v = root[k] + if type(v) == "table" then + for _, k2 in Types.keys(v) do + v[k2] = typed(v[k2]) + end + else + root[k] = typed(v) + end + end + end + return root, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function text(v: any): string? + local tv = type(v) + if tv == "string" then + return (string.gsub(v, "\n", "\n\t")) + elseif tv == "number" then + return Json.number(v) or tostring(v) + elseif tv == "boolean" then + return if v then "true" else "false" + elseif v == Types.null then + return "" + elseif tv == "table" and Types.Date.is(v) then + return tostring(v) + end + return nil +end + +function Ini.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(value) ~= "table" then + return nil, Err.new(Err.ARG, "expected a table of sections") + end + local delim = (opts and opts.delimiter) or " = " + local out: { string } = {} + local err: string? = nil + local function keyOk(k: any): boolean + if type(k) ~= "string" and type(k) ~= "number" then + err = "keys must be strings" + return false + end + local ks = tostring(k) + if ks == "" or string.find(ks, "[=:\r\n]") or string.match(ks, "^[%s;#%[]") or string.match(ks, "%s$") then + err = "key " .. string.format("%q", ks) .. " cannot be written" + return false + end + return true + end + local function pairsOf(t: any, prefix: string, depth: number): boolean + if depth > 32 then + err = "sections nested too deeply (a cycle?)" + return false + end + local subs = {} + local lines = {} + for _, k in Types.keys(t) do + local v = t[k] + if type(v) == "table" and not Types.Date.is(v) and v ~= Types.null then + table.insert(subs, k) + else + if not keyOk(k) then + return false + end + local s = text(v) + if not s then + err = "cannot write a " .. type(v) .. " value" + return false + end + table.insert(lines, tostring(k) .. delim .. s .. "\n") + end + end + if prefix ~= "" then + table.insert(out, "[" .. prefix .. "]\n") + table.move(lines, 1, #lines, #out + 1, out) + table.insert(out, "\n") + elseif #lines > 0 then + table.move(lines, 1, #lines, #out + 1, out) + table.insert(out, "\n") + end + for _, k in subs do + local name = tostring(k) + if string.find(name, "[\r\n%]]") then + err = "section name " .. string.format("%q", name) .. " cannot be written" + return false + end + if not pairsOf(t[k], if prefix == "" then name else prefix .. "." .. name, depth + 1) then + return false + end + end + return true + end + if not pairsOf(value, "", 0) then + return nil, Err.new(Err.ARG, err or "cannot encode") + end + return buffer.fromstring(table.concat(out)), nil +end + +return Ini +end +__FILES["data/json"] = function() + +-- data/json: JSON (RFC 8259) over codecs/text/Json. Supports: decode to Luau values, compact / pretty encode, JSON +-- Lines. Not supported: JSON5 / comments / trailing commas. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Sniff = __include("core/Sniff") +local Bytes = __include("core/Bytes") +local Json = __include("codecs/text/Json") + +-- ------------------------------------------------------------------------------------------------ contract +local JsonFormat = { + name = "json", + category = "data", + extensions = { "json", "jsonl", "ndjson", "geojson" }, + mime = { "application/json", "application/x-ndjson" }, + deps = { "core/Err", "core/Bytes", "codecs/text/Json", "core/Sniff" }, + caps = { decode = true, encode = true, ordered = true, streaming = true }, +} + +type DecodeOptions = Json.DecodeOptions & { + lines: boolean?, -- default false +} +type EncodeOptions = Json.EncodeOptions & { + lines: boolean?, +} + +-- ------------------------------------------------------------------------------------------------ sniff +function JsonFormat.sniff(r: Bytes.Reader): number + 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]*(.)") + return if nxt == nil or nxt == '"' or nxt == "}" then 0.6 else 0.1 + elseif first == "[" then + -- past any nested '[': a JSON value must start (TOML / INI "[section]" and "[[table]]" do not) + local nxt = string.match(head, "^[ \t\r\n]*[%[ \t\r\n]*(.)") + if nxt == nil or string.find('{"-0123456789tfn]', nxt, 1, true) then + return 0.3 + end + return 0 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function JsonFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local s = buffer.readstring(r.buf, r.base, r.limit - r.base) + if opts and opts.lines then + local out = {} + for _, v, err in Json.lines(s, opts) do + if err then + return nil, err + end + table.insert(out, v) + end + return out, nil + end + return Json.decode(s, opts) +end + +-- ------------------------------------------------------------------------------------------------ encode +function JsonFormat.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + if opts and opts.lines then + if type(value) ~= "table" then + return nil, Err.new(Err.ARG, "lines: expected an array of values") + end + local o = table.clone(opts) :: any + o.indent = nil + local parts = {} + for i, v in value do + local s, err = Json.encode(v, o) + if not s then + return nil, err + end + parts[i] = s .. "\n" + end + return buffer.fromstring(table.concat(parts)), nil + end + local s, err = Json.encode(value, opts) + if not s then + return nil, err + end + if opts and opts.indent then + s ..= "\n" + end + return buffer.fromstring(s), nil +end + +return JsonFormat +end +__FILES["data/msgpack"] = function() + +-- data/msgpack: MessagePack (str8 / bin / ext revision), new code. Supports: every type, timestamps (ext -1) as +-- Types.Date, other ext as Msgpack.ext, exact 64-bit integers by option, concatenated streams; encode picks the +-- smallest forms. Not supported: none. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Codec = __include("data/msgpack/Codec") + +-- ------------------------------------------------------------------------------------------------ contract +local Msgpack = { + name = "msgpack", + category = "data", + extensions = { "msgpack", "mpk" }, + mime = { "application/msgpack", "application/x-msgpack" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, binary = true, ordered = true }, +} + +type DecodeOptions = Codec.DecodeOptions & { + all: boolean?, -- default false +} +type EncodeOptions = Codec.EncodeOptions & { + all: boolean?, +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Msgpack.sniff(_r: Bytes.Reader): number + return 0 -- no magic: by extension or opts.format only +end + +-- ------------------------------------------------------------------------------------------------ decode +function Msgpack.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + if o.all then + local out = {} + while not r:eof() do + local v, e, at = Codec.decode(r, o) + if e then + return nil, Err.from(e, at) + end + table.insert(out, v) + end + return out, nil + end + local v, e, at = Codec.decode(r, o) + if e then + local code = if string.find(e, "truncated", 1, true) or string.find(e, "past the end", 1, true) then Err.TRUNCATED + elseif string.find(e, "nested deeper", 1, true) then Err.LIMIT + else Err.CORRUPT + return nil, Err.new(code, e, at) + end + if not r:eof() then + return nil, Err.new(Err.CORRUPT, "trailing data after the value (opts.all reads a stream)", r.pos - r.base) + end + return v, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Msgpack.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + if opts and opts.all then + if type(value) ~= "table" then + return nil, Err.new(Err.ARG, "all: expected an array of values") + end + local w = Bytes.writer() + for _, v in value do + local b, e = Codec.encode(v, opts) + if not b then + return nil, Err.new(Err.ARG, e or "cannot encode") + end + w:bytes(b) + end + return w:finish(), nil + end + local b, e = Codec.encode(value, opts) + if not b then + return nil, Err.new(Err.ARG, e or "cannot encode") + end + return b, nil +end + +-- ------------------------------------------------------------------------------------------------ extras +Msgpack.ext = Codec.ext +Msgpack.isExt = Codec.isExt + +return Msgpack +end +__FILES["data/msgpack/Codec"] = @native function() + + +-- data/msgpack/Codec: MessagePack (2017 spec: str8 / bin / ext, timestamp ext -1) decoder and encoder; never throws. +local Bytes = __include("core/Bytes") +local Types = __include("Types") + +local Codec = {} + +local TWO32 = 4294967296 + +-- ext type: -128..127 +local ExtMeta = { __tostring = @native function(e: any): string + return "msgpack.ext(" .. e.type .. ", " .. buffer.len(e.data) .. " bytes)" +end } +@native function Codec.ext(t: number, data: buffer): { type: number, data: buffer } + return setmetatable({ type = t, data = data }, ExtMeta) :: any +end +@native function Codec.isExt(v: any): boolean + return type(v) == "table" and getmetatable(v) == ExtMeta +end + +@native local function u64text(hi: number, lo: number): string + if hi == 0 then + return string.format("%d", lo) + end + local digits = {} + local l = { hi // 65536, hi % 65536, lo // 65536, lo % 65536 } + while l[1] ~= 0 or l[2] ~= 0 or l[3] ~= 0 or l[4] ~= 0 do + local rem = 0 + for k = 1, 4 do + local cur = rem * 65536 + l[k] + l[k] = cur // 10 + rem = cur % 10 + end + table.insert(digits, 1, string.char(48 + rem)) + end + return table.concat(digits) +end +Codec.u64text = u64text + +type DecodeOptions = { + bigInts: ("number" | "string")?, + null: any?, -- default Types.null + maxDepth: number?, -- default 512 + timestamps: boolean?, -- default true + ordered: boolean?, -- default true +} + +type St = { r: Bytes.Reader, big: boolean, null: any, maxDepth: number, ts: boolean, ordered: boolean } + +@native local function int64(st: St, signed: boolean): any + local r = st.r + local hi, lo = r:u32be(), r:u32be() + if signed and hi >= 0x80000000 then + local nhi, nlo = 0xFFFFFFFF - hi, TWO32 - lo + if nlo == TWO32 then + nlo = 0 + nhi += 1 + end + if st.big and nhi >= 0x200000 then + return "-" .. u64text(nhi, nlo) + end + return -(nhi * TWO32 + nlo) + end + if st.big and hi >= 0x200000 then + return u64text(hi, lo) + end + return hi * TWO32 + lo +end + +local value: (st: St, depth: number) -> (any, string?) + +@native local function ext(st: St, n: number): (any, string?) + local r = st.r + local t = r:i8() + if r.err or not r:need(n) then + return nil, "truncated ext" + end + if t == -1 and st.ts then + local secs, ns = 0, 0 + if n == 4 then + secs = r:u32be() + elseif n == 8 then + local hi, lo = r:u32be(), r:u32be() + ns = hi // 4 + secs = (hi % 4) * TWO32 + lo + elseif n == 12 then + ns = r:u32be() + secs = r:i64be() + else + return nil, "bad timestamp length" + end + if ns > 999999999 then + return nil, "bad timestamp nanoseconds" + end + local d: any = Types.Date.fromUnix(secs) + d.nanosecond = ns + return d, nil + end + return Codec.ext(t, r:bytes(n)), nil +end + +@native local function array(st: St, n: number, depth: number): (any, string?) + if n > st.r:remaining() then + return nil, "array count past the end" + end + local t = table.create(n) + for k = 1, n do + local v, e = value(st, depth + 1) + if e then + return nil, e + end + t[k] = v + end + return t, nil +end + +@native local function map(st: St, n: number, depth: number): (any, string?) + if n * 2 > st.r:remaining() then + return nil, "map count past the end" + end + local t = {} + local order: { any }? = if st.ordered then table.create(n) else nil + for _ = 1, n do + local k, e = value(st, depth + 1) + if e then + return nil, e + end + local v, e2 = value(st, depth + 1) + if e2 then + return nil, e2 + end + if k ~= k then + return nil, "NaN map key" + end + if order and t[k] == nil then + table.insert(order, k) + end + t[k] = v + end + return Types.object(t, order or {}), nil +end + +@native function value(st: St, depth: number): (any, string?) + if depth > st.maxDepth then + return nil, "nested deeper than " .. st.maxDepth + end + local r = st.r + local b = r:u8() + if r.err then + return nil, "truncated" + end + if b < 0x80 then + return b, nil + elseif b >= 0xE0 then + return b - 256, nil + elseif b < 0x90 then + return map(st, b - 0x80, depth) + elseif b < 0xA0 then + return array(st, b - 0x90, depth) + elseif b < 0xC0 then + local n = b - 0xA0 + if not r:need(n) then + return nil, "truncated string" + end + return r:string(n), nil + elseif b == 0xC0 then + return st.null, nil + elseif b == 0xC2 then + return false, nil + elseif b == 0xC3 then + return true, nil + elseif b == 0xC4 or b == 0xC5 or b == 0xC6 then + local n = if b == 0xC4 then r:u8() elseif b == 0xC5 then r:u16be() else r:u32be() + if r.err or not r:need(n) then + return nil, "truncated bin" + end + return r:bytes(n), nil + elseif b == 0xC7 or b == 0xC8 or b == 0xC9 then + local n = if b == 0xC7 then r:u8() elseif b == 0xC8 then r:u16be() else r:u32be() + if r.err then + return nil, "truncated ext" + end + return ext(st, n) + elseif b == 0xCA then + local v = r:f32be() + return if r.err then nil else v, if r.err then "truncated" else nil + elseif b == 0xCB then + local v = r:f64be() + return if r.err then nil else v, if r.err then "truncated" else nil + elseif b >= 0xCC and b <= 0xD3 then + local v: any + if b == 0xCC then + v = r:u8() + elseif b == 0xCD then + v = r:u16be() + elseif b == 0xCE then + v = r:u32be() + elseif b == 0xCF then + v = int64(st, false) + elseif b == 0xD0 then + v = r:i8() + elseif b == 0xD1 then + v = r:i16be() + elseif b == 0xD2 then + v = r:i32be() + else + v = int64(st, true) + end + if r.err then + return nil, "truncated" + end + return v, nil + elseif b >= 0xD4 and b <= 0xD8 then + return ext(st, 2 ^ (b - 0xD4)) + elseif b >= 0xD9 and b <= 0xDB then + local n = if b == 0xD9 then r:u8() elseif b == 0xDA then r:u16be() else r:u32be() + if r.err or not r:need(n) then + return nil, "truncated string" + end + return r:string(n), nil + elseif b == 0xDC or b == 0xDD then + local n = if b == 0xDC then r:u16be() else r:u32be() + if r.err then + return nil, "truncated" + end + return array(st, n, depth) + elseif b == 0xDE or b == 0xDF then + local n = if b == 0xDE then r:u16be() else r:u32be() + if r.err then + return nil, "truncated" + end + return map(st, n, depth) + end + return nil, string.format("reserved type byte 0x%02x", b) +end + +@native function Codec.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, string?, number?) + local o: DecodeOptions = opts or {} + local st: St = { + r = r, + big = o.bigInts == "string", + null = if o.null ~= nil then o.null else Types.null, + maxDepth = o.maxDepth or 512, + ts = o.timestamps ~= false, + ordered = o.ordered ~= false, + } + local v, e = value(st, 0) + if e then + return nil, e, r.pos - r.base + end + return v, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +type EncodeOptions = { + float32: boolean?, -- default false + sortKeys: boolean?, -- default true + emptyTable: ("array" | "map")?, -- default "array" + maxDepth: number?, -- default 512 (also catches cycles) + stringsAsBin: boolean?, -- default false +} + +type ESt = { w: Bytes.Writer, f32: boolean, sort: boolean, emptyMap: boolean, maxDepth: number, bin: boolean, err: string? } + +@native local function writeInt(w: Bytes.Writer, v: number) + if v >= 0 then + if v < 128 then + w:u8(v) + elseif v < 256 then + w:u8(0xCC) + w:u8(v) + elseif v < 65536 then + w:u8(0xCD) + w:u16be(v) + elseif v < TWO32 then + w:u8(0xCE) + w:u32be(v) + else + w:u8(0xCF) + w:u64be(v) + end + else + if v >= -32 then + w:u8(v + 256) + elseif v >= -128 then + w:u8(0xD0) + w:u8(v + 256) + elseif v >= -32768 then + w:u8(0xD1) + w:u16be(v + 65536) + elseif v >= -2147483648 then + w:u8(0xD2) + w:u32be(v + TWO32) + else + w:u8(0xD3) + local hi = math.floor(v / TWO32) + local lo = v - hi * TWO32 + w:u32be(hi + TWO32) + w:u32be(lo) + end + end +end + +@native local function lenHeader(w: Bytes.Writer, n: number, fix: number?, fixMax: number, b8: number?, b16: number, b32: number) + if fix and n <= fixMax then + w:u8(fix + n) + elseif b8 and n < 256 then + w:u8(b8) + w:u8(n) + elseif n < 65536 then + w:u8(b16) + w:u16be(n) + else + w:u8(b32) + w:u32be(n) + end +end + +local keyLess = Types.keyLess + +local isArray = Types.isArray +Codec.isArray = isArray + +@native local function enc(st: ESt, v: any, depth: number): boolean + local w = st.w + local tv = type(v) + if v == nil or v == Types.null then + w:u8(0xC0) + elseif tv == "boolean" then + w:u8(if v then 0xC3 else 0xC2) + elseif tv == "number" then + if v == math.floor(v) and v >= -9223372036854775808 and v < 18446744073709551616 then + writeInt(w, v) + elseif st.f32 then + w:u8(0xCA) + w:f32be(v) + else + w:u8(0xCB) + w:f64be(v) + end + elseif tv == "string" then + if st.bin then + lenHeader(w, #v, nil, 0, 0xC4, 0xC5, 0xC6) + else + lenHeader(w, #v, 0xA0, 31, 0xD9, 0xDA, 0xDB) + end + w:string(v) + elseif tv == "buffer" then + lenHeader(w, buffer.len(v), nil, 0, 0xC4, 0xC5, 0xC6) + w:bytes(v) + elseif tv == "table" then + if depth >= st.maxDepth then + st.err = "nested deeper than " .. st.maxDepth .. " (a cycle?)" + return false + end + if Codec.isExt(v) then + local n = buffer.len(v.data) + if n == 1 or n == 2 or n == 4 or n == 8 or n == 16 then + w:u8(({ [1] = 0xD4, [2] = 0xD5, [4] = 0xD6, [8] = 0xD7, [16] = 0xD8 })[n]) + else + lenHeader(w, n, nil, 0, 0xC7, 0xC8, 0xC9) + end + w:u8(v.type % 256) + w:bytes(v.data) + elseif Types.Date.is(v) then + local t = Types.Date.toUnix(v) + local secs = math.floor(t) + local ns = (v :: any).nanosecond or 0 + if ns == 0 and secs >= 0 and secs < TWO32 then + w:u8(0xD6) + w:u8(0xFF) + w:u32be(secs) + elseif secs >= 0 and secs < 2 ^ 34 then + w:u8(0xD7) + w:u8(0xFF) + w:u32be(ns * 4 + secs // TWO32) + w:u32be(secs % TWO32) + else + w:u8(0xC7) + w:u8(12) + w:u8(0xFF) + w:u32be(ns) + local hi = math.floor(secs / TWO32) + w:u32be(hi % TWO32) + w:u32be(secs - hi * TWO32) + end + elseif isArray(v, st.emptyMap) then + local n = #v + lenHeader(w, n, 0x90, 15, nil, 0xDC, 0xDD) + for k = 1, n do + if not enc(st, v[k], depth + 1) then + return false + end + end + else + local keys: { any } + if Types.isObject(v) then + keys = Types.keys(v) + else + keys = {} + for k in next, v do + table.insert(keys, k) + end + if st.sort then + table.sort(keys, keyLess) + end + end + lenHeader(w, #keys, 0x80, 15, nil, 0xDE, 0xDF) + for _, k in keys do + if not enc(st, k, depth + 1) or not enc(st, v[k], depth + 1) then + return false + end + end + end + else + st.err = "cannot encode a " .. tv + return false + end + return true +end + +@native function Codec.encode(v: any, opts: EncodeOptions?): (buffer?, string?) + local o: EncodeOptions = opts or {} + local st: ESt = { + w = Bytes.writer(256), + f32 = o.float32 == true, + sort = o.sortKeys ~= false, + emptyMap = o.emptyTable == "map", + maxDepth = o.maxDepth or 512, + bin = o.stringsAsBin == true, + err = nil, + } + if not enc(st, v, 0) then + return nil, st.err + end + return st.w:finish(), nil +end + +return Codec +end +__FILES["data/nbt"] = function() + +-- data/nbt: Minecraft NBT files over codecs/text/Nbt. Supports: Java big-endian and Bedrock little-endian NBT +-- (level.dat header, varint by option), gzip / zlib / raw, every tag, exact round trips (Nbt.info). +-- Not supported: none. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Nbt = __include("codecs/text/Nbt") + +-- ------------------------------------------------------------------------------------------------ contract +local NbtFormat = { + name = "nbt", + category = "data", + extensions = { "nbt", "dat", "mcstructure", "dat_old" }, + mime = { "application/x-minecraft-nbt" }, + deps = { "core/Err", "core/Bytes", "codecs/text/Nbt" }, + caps = { decode = true, encode = true, binary = true, ordered = true, typed = true }, +} + +type DecodeOptions = Nbt.DecodeOptions +type EncodeOptions = Nbt.EncodeOptions + +-- ------------------------------------------------------------------------------------------------ sniff +function NbtFormat.sniff(r: Bytes.Reader): number + local p = Nbt.peek(r.buf, r.base, r.limit - r.base) + if not p or p.rootType ~= "compound" then + return 0 + end + if p.compression ~= "none" then + return if p.firstType then 1 else 0.5 -- gzip wrapped NBT: ties with archive/gzip go to the extension + end + return if p.firstType and p.firstName then 0.6 else 0.2 +end + +-- ------------------------------------------------------------------------------------------------ decode +function NbtFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local v, info = Nbt.decode(r.buf, opts, r.base, r.limit - r.base) + if v == nil then + return nil, info + end + return v, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function NbtFormat.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + if value == nil then + return nil, Err.new(Err.ARG, "nothing to encode") + end + return Nbt.encode(value, opts) +end + +-- ------------------------------------------------------------------------------------------------ extras +NbtFormat.info = Nbt.info +NbtFormat.Nbt = Nbt + +return NbtFormat +end +__FILES["data/plist"] = function() + +-- data/plist: Apple property lists, new code. Supports: XML read / write (byte-identical to Python's plistlib), +-- binary "bplist00" read, UIDs as Plist.uid. Not supported: binary write, OpenStep text, integers past 2^63; integral +-- reals write back as <integer>. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Xml = __include("codecs/text/Xml") +local Json = __include("codecs/text/Json") +local Base64 = __include("core/Base64") +local Binary = __include("data/plist/Binary") + +-- ------------------------------------------------------------------------------------------------ contract +local Plist = { + name = "plist", + category = "data", + extensions = { "plist" }, + mime = { "application/x-plist", "application/x-bplist" }, + deps = { "core/Err", "core/Bytes", "Types", "core/Base64", "codecs/text/Xml", "codecs/text/Json" }, + caps = { decode = true, encode = true, binary = "read", ordered = true }, +} + +type DecodeOptions = { + bigInts: ("number" | "string")?, + maxDepth: number?, -- default 512 +} +type EncodeOptions = { + sortKeys: boolean?, -- default true +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Plist.sniff(r: Bytes.Reader): number + local head = r:peek(256) + if string.sub(head, 1, 6) == "bplist" then + return 1 + end + if string.find(head, "<!DOCTYPE plist", 1, true) or string.find(head, "<plist", 1, true) then + return 0.9 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function xmlValue(node: any, opts: DecodeOptions?, depth: number): (any, string?) + if depth > ((opts and opts.maxDepth) or 512) then + return nil, "nested too deeply" + end + local name = node.name + if name == "dict" then + local out = Types.object() + local kids = Xml.children(node) + local i = 1 + while i <= #kids do + local k = kids[i] + if k.name ~= "key" then + return nil, "dict: expected <key>, got <" .. k.name .. ">" + end + local v = kids[i + 1] + if not v then + return nil, "dict: <key> without a value" + end + local val, e = xmlValue(v, opts, depth + 1) + if e then + return nil, e + end + Types.set(out, Xml.text(k), val) + i += 2 + end + return out, nil + elseif name == "array" then + local out = {} + for _, ch in Xml.children(node) do + local val, e = xmlValue(ch, opts, depth + 1) + if e then + return nil, e + end + table.insert(out, val) + end + return out, nil + elseif name == "string" then + return Xml.text(node), nil + elseif name == "integer" then + local t = string.match(Xml.text(node), "^%s*(.-)%s*$") :: string + local neg, hex = string.match(t, "^([%-%+]?)0[xX](%x+)$") + local n: number? + if hex then + n = tonumber(hex, 16) + if n and neg == "-" then + n = -n + end + elseif string.match(t, "^[%-%+]?%d+$") then + n = tonumber(t) + if n and math.abs(n) >= 2 ^ 53 and opts and opts.bigInts == "string" then + return (string.gsub(t, "^%+", "")), nil + end + end + if not n then + return nil, "bad integer " .. string.sub(t, 1, 30) + end + return n, nil + elseif name == "real" then + local t = string.lower(string.match(Xml.text(node), "^%s*(.-)%s*$") :: string) + local n = tonumber(t) + if not n then + if t == "nan" or t == "+nan" or t == "-nan" then + n = 0 / 0 + elseif t == "inf" or t == "+inf" or t == "infinity" or t == "+infinity" then + n = math.huge + elseif t == "-inf" or t == "-infinity" then + n = -math.huge + end + end + if not n then + return nil, "bad real " .. string.sub(t, 1, 30) + end + return n, nil + elseif name == "true" then + return true, nil + elseif name == "false" then + return false, nil + elseif name == "date" then + local d = Types.Date.parse((string.match(Xml.text(node), "^%s*(.-)%s*$"))) + if not d then + return nil, "bad date" + end + return d, nil + elseif name == "data" then + local b, e = Base64.decode(Xml.text(node)) + if not b then + return nil, e + end + return b, nil + end + return nil, "unknown element <" .. tostring(name) .. ">" +end + +function Plist.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local len = r.limit - r.base + 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.from(e) + end + return v, nil + end + local doc, err = Xml.decode(buffer.readstring(r.buf, r.base, len), { whitespace = true }) + if not doc then + return nil, err + end + local root = (doc :: any).root + if root.name == "plist" then + local kids = Xml.children(root) + if #kids ~= 1 then + return nil, Err.new(Err.CORRUPT, "<plist> must hold exactly one value") + end + root = kids[1] + end + local v, e = xmlValue(root, opts, 0) + if e then + return nil, Err.new(Err.CORRUPT, e) + end + return v, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local HEADER = '<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n<plist version="1.0">\n' + +local function esc(s: string): (string?, string?) + if string.find(s, "[%z\1-\8\11\12\14-\31]") then + return nil, "strings cannot contain control characters" + end + s = string.gsub(string.gsub(s, "\r\n", "\n"), "\r", "\n") + return (string.gsub(s, "[&<>]", { ["&"] = "&amp;", ["<"] = "&lt;", [">"] = "&gt;" })), nil +end + +local function keyLess(a: any, b: any): boolean + return a < b +end + +function Plist.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local sort = not (opts and opts.sortKeys == false) + local out: { string } = { HEADER } + local err: string? = nil + local function line(level: number, s: string) + table.insert(out, string.rep("\t", level) .. s .. "\n") + end + local write: (v: any, level: number, depth: number) -> boolean + function write(v: any, level: number, depth: number): boolean + if depth > 512 then + err = "nested deeper than 512 (a cycle?)" + return false + end + local tv = type(v) + if tv == "string" then + local s, e = esc(v) + if not s then + err = e + return false + end + line(level, "<string>" .. s .. "</string>") + elseif tv == "boolean" then + line(level, if v then "<true/>" else "<false/>") + elseif tv == "number" then + if v == math.floor(v) and math.abs(v) < 2 ^ 63 then + line(level, "<integer>" .. string.format("%d", v) .. "</integer>") + else + local s = Json.number(v) + if not s then + s = if v ~= v then "nan" elseif v > 0 then "inf" else "-inf" + end + line(level, "<real>" .. s .. "</real>") + end + elseif tv == "buffer" then + line(level, "<data>") + local maxLine = math.max(16, 76 - 8 * level) + for l in string.gmatch(Base64.encode(v, { wrap = maxLine // 4 * 4 }), "[^\n]+") do + line(level, l) + end + line(level, "</data>") + elseif tv == "table" and Types.Date.is(v) then + local d = Types.Date.fromUnix(math.floor(Types.Date.toUnix(v))) + line(level, string.format("<date>%04d-%02d-%02dT%02d:%02d:%02dZ</date>", d.year :: number, d.month :: number, d.day :: number, d.hour :: number, d.minute :: number, d.second :: number)) + elseif tv == "table" and Binary.isUid(v) then + err = "UIDs can only be written to binary plists" + return false + elseif tv == "table" and v ~= Types.null then + local n = #v + local isArray = false + if not Types.isObject(v) then + local c = 0 + for _ in next, v do + c += 1 + end + isArray = c == n + end + if isArray then + if n == 0 then + line(level, "<array/>") + return true + end + line(level, "<array>") + for k = 1, n do + if not write(v[k], level + 1, depth + 1) then + return false + end + end + line(level, "</array>") + else + local keys: { any } + if Types.isObject(v) then + keys = Types.keys(v) + else + keys = {} + for k in next, v do + table.insert(keys, k) + end + end + for _, k in keys do + if type(k) ~= "string" then + err = "dict keys must be strings" + return false + end + end + if sort and not Types.isObject(v) then + table.sort(keys, keyLess) + end + if #keys == 0 then + line(level, "<dict/>") + return true + end + line(level, "<dict>") + for _, k in keys do + local ks, e = esc(k) + if not ks then + err = e + return false + end + line(level + 1, "<key>" .. ks .. "</key>") + if not write(v[k], level + 1, depth + 1) then + return false + end + end + line(level, "</dict>") + end + else + err = "cannot write " .. (if v == Types.null then "null" else "a " .. tv) .. " in a plist" + return false + end + return true + end + if not write(value, 0, 0) then + return nil, Err.new(Err.ARG, err or "cannot encode") + end + table.insert(out, "</plist>\n") + return buffer.fromstring(table.concat(out)), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +Plist.uid = Binary.uid +Plist.isUid = Binary.isUid + +return Plist +end +__FILES["data/plist/Binary"] = @native function() + + +-- data/plist/Binary: binary plist reader ("bplist00", CFBinaryPList.c / Python's plistlib); 16-byte ints: low 8 bytes. +local Types = __include("Types") + +local Binary = {} + +local readu8 = buffer.readu8 +local TWO32 = 4294967296 +local EPOCH_2001 = 978307200 + +local UidMeta = { __tostring = @native function(u: any): string + return "UID(" .. u.uid .. ")" +end } +@native function Binary.uid(n: number): { uid: number } + return setmetatable({ uid = n }, UidMeta) :: any +end +@native function Binary.isUid(v: any): boolean + return type(v) == "table" and getmetatable(v) == UidMeta +end + +@native local function be(b: buffer, o: number, n: number): number + local v = 0 + for k = 0, n - 1 do + v = v * 256 + readu8(b, o + k) + end + return v +end + +@native local function utf8char(c: number): string + if c < 0x80 then + return string.char(c) + elseif c < 0x800 then + return string.char(0xC0 + c // 64, 0x80 + c % 64) + elseif c < 0x10000 then + return string.char(0xE0 + c // 4096, 0x80 + (c // 64) % 64, 0x80 + c % 64) + end + return string.char(0xF0 + c // 262144, 0x80 + (c // 4096) % 64, 0x80 + (c // 64) % 64, 0x80 + c % 64) +end + +type Options = { bigInts: ("number" | "string")?, maxDepth: number? } + +@native function Binary.decode(b: buffer, base: number, len: number, opts: Options?): (any, string?) + if len < 40 then + return nil, "truncated: shorter than header + trailer" + end + local t = base + len - 32 + local offSize, refSize = readu8(b, t + 6), readu8(b, t + 7) + local numObjects = be(b, t + 8, 8) + local top = be(b, t + 16, 8) + local tableOff = be(b, t + 24, 8) + if offSize < 1 or offSize > 8 or refSize < 1 or refSize > 8 then + return nil, "bad trailer sizes" + end + if numObjects < 1 or top >= numObjects or tableOff < 8 or tableOff + numObjects * offSize > len - 32 then + return nil, "bad trailer" + end + local maxDepth = (opts and opts.maxDepth) or 512 + local cache: { [number]: any } = {} + local busy: { [number]: boolean } = {} + + local object: (idx: number, depth: number) -> (any, string?) + + -- a length nibble: 0..14, or 15 = an int object follows + @native local function count(o: number, nib: number): (number?, number) + if nib < 15 then + return nib, o + 1 + end + if o + 2 > len - 32 then + return nil, 0 + end + local m = readu8(b, base + o + 1) + if m // 16 ~= 1 then + return nil, 0 + end + local w = 2 ^ (m % 16) + if w > 8 or o + 2 + w > len - 32 then + return nil, 0 + end + return be(b, base + o + 2, w), o + 2 + w + end + + @native local function ref(at: number): number + return be(b, base + at, refSize) + end + + @native function object(idx: number, depth: number): (any, string?) + local cached = cache[idx] + if cached ~= nil then + return cached, nil + end + if busy[idx] then + return nil, "object references form a cycle" + end + if depth > maxDepth then + return nil, "nested deeper than " .. maxDepth + end + if idx >= numObjects then + return nil, "object reference out of range" + end + local o = be(b, base + tableOff + idx * offSize, offSize) + if o < 8 or o >= len - 32 then + return nil, "object offset out of range" + end + local marker = readu8(b, base + o) + local hi, nib = marker // 16, marker % 16 + local v: any + if marker == 0x00 then + v = Types.null + elseif marker == 0x08 then + v = false + elseif marker == 0x09 then + v = true + elseif hi == 1 then + local w = 2 ^ nib + if w > 16 or o + 1 + w > len - 32 then + return nil, "bad integer" + end + if w == 16 then + o += 8 + w = 8 + end + if w == 8 then + local h, l = be(b, base + o + 1, 4), be(b, base + o + 5, 4) + if h >= 0x80000000 and nib == 3 then + v = (h - TWO32) * TWO32 + l + elseif opts and opts.bigInts == "string" and h >= 0x200000 then + local digits = {} + local limbs = { h // 65536, h % 65536, l // 65536, l % 65536 } + while limbs[1] + limbs[2] + limbs[3] + limbs[4] > 0 do + local rem = 0 + for k = 1, 4 do + local cur = rem * 65536 + limbs[k] + limbs[k] = cur // 10 + rem = cur % 10 + end + table.insert(digits, 1, string.char(48 + rem)) + end + v = table.concat(digits) + else + v = h * TWO32 + l + end + else + v = be(b, base + o + 1, w) + end + elseif hi == 2 then + if nib == 2 and o + 5 <= len - 32 then + local s = buffer.create(4) + for k = 0, 3 do + buffer.writeu8(s, k, readu8(b, base + o + 4 - k)) + end + v = buffer.readf32(s, 0) + elseif nib == 3 and o + 9 <= len - 32 then + local s = buffer.create(8) + for k = 0, 7 do + buffer.writeu8(s, k, readu8(b, base + o + 8 - k)) + end + v = buffer.readf64(s, 0) + else + return nil, "bad real" + end + elseif marker == 0x33 then + if o + 9 > len - 32 then + return nil, "truncated date" + end + local s = buffer.create(8) + for k = 0, 7 do + buffer.writeu8(s, k, readu8(b, base + o + 8 - k)) + end + local secs = buffer.readf64(s, 0) + if secs ~= secs or math.abs(secs) > 1e14 then + return nil, "bad date" + end + v = Types.Date.fromUnix(secs + EPOCH_2001) + elseif hi == 4 or hi == 5 or hi == 6 or hi == 7 then + local n, p = count(o, nib) + if not n then + return nil, "bad length" + end + local bytes = if hi == 6 then n * 2 else n + if p + bytes > len - 32 then + return nil, "string / data past the end" + end + if hi == 4 then + local d = buffer.create(bytes) + buffer.copy(d, 0, b, base + p, bytes) + v = d + elseif hi == 6 then + local parts = table.create(n) + local k = 0 + while k < n do + local u = be(b, base + p + k * 2, 2) + k += 1 + if u >= 0xD800 and u <= 0xDBFF and k < n then + local lo = be(b, base + p + k * 2, 2) + if lo >= 0xDC00 and lo <= 0xDFFF then + u = 0x10000 + (u - 0xD800) * 1024 + (lo - 0xDC00) + k += 1 + end + end + table.insert(parts, utf8char(u)) + end + v = table.concat(parts) + else + v = buffer.readstring(b, base + p, bytes) + end + elseif hi == 8 then + if o + 2 + nib > len - 32 then + return nil, "bad UID" + end + v = Binary.uid(be(b, base + o + 1, nib + 1)) + elseif hi == 0xA or hi == 0xC or hi == 0xD then + local n, p = count(o, nib) + if not n then + return nil, "bad length" + end + local refs = if hi == 0xD then n * 2 else n + if p + refs * refSize > len - 32 then + return nil, "collection past the end" + end + busy[idx] = true + if hi == 0xD then + local t2 = {} + local order = table.create(n) + for k = 0, n - 1 do + local key, ke = object(ref(p + k * refSize), depth + 1) + if ke then + return nil, ke + end + if type(key) ~= "string" then + return nil, "dict key is not a string" + end + local val, ve = object(ref(p + (n + k) * refSize), depth + 1) + if ve then + return nil, ve + end + if t2[key] == nil then + table.insert(order, key) + end + t2[key] = val + end + v = Types.object(t2, order) + else + local arr = table.create(n) + for k = 0, n - 1 do + local item, ie = object(ref(p + k * refSize), depth + 1) + if ie then + return nil, ie + end + arr[k + 1] = item + end + v = arr + end + busy[idx] = nil + else + return nil, string.format("unknown object marker 0x%02x", marker) + end + cache[idx] = v + return v, nil + end + + return object(top, 0) +end + +return Binary +end +__FILES["data/snbt"] = function() + +-- data/snbt: stringified NBT over codecs/text/Nbt. Supports: parse to data/nbt's values, compact or indented print. +-- Not supported: the 1.21.5 bool(...) / uuid(...) operations. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Sniff = __include("core/Sniff") +local Nbt = __include("codecs/text/Nbt") + +-- ------------------------------------------------------------------------------------------------ contract +local SnbtFormat = { + name = "snbt", + category = "data", + extensions = { "snbt" }, + mime = { "text/x-minecraft-snbt" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "codecs/text/Nbt" }, + caps = { decode = true, encode = true, ordered = true, typed = true }, +} + +type DecodeOptions = { maxDepth: number? } +type EncodeOptions = { + indent: (number | string)?, -- default: compact + quote: string?, -- default '"' +} + +-- ------------------------------------------------------------------------------------------------ sniff +function SnbtFormat.sniff(r: Bytes.Reader): number + -- SNBT has what JSON never has: unquoted keys, typed numbers (1b, 2.5f), [I; arrays, single-quoted strings + local head = Sniff.text(r, 512, true) + local first = string.sub(head, 1, 1) + if first ~= "{" and first ~= "[" then + return 0 + end + if string.find(head, "[{,]%s*[%a_][%w_%-%.%+]*%s*:") or string.find(head, "%d[bBsSlLfFdD]%s*[,}%]]") + or string.find(head, "%[[BIL]%s*;") or string.find(head, "[:,%[]%s*'") + then + return 0.7 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function SnbtFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local text = Sniff.dropBom(buffer.readstring(r.buf, r.base, r.limit - r.base)) + return Nbt.parse(text, opts) +end + +-- ------------------------------------------------------------------------------------------------ encode +function SnbtFormat.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + if value == nil then + return nil, Err.new(Err.ARG, "nothing to encode") + end + local s, e = Nbt.print(value, opts) + if not s then + return nil, e + end + return buffer.fromstring(s), nil +end + +return SnbtFormat +end +__FILES["data/toml"] = function() + +-- data/toml: TOML 1.0.0 (https://toml.io/en/v1.0.0), new code, tested against toml-test. Supports: the whole 1.0 +-- grammar and validity rules; tables as Types.object, datetimes as Types.Date. Not supported: TOML 1.1; the integer / +-- float distinction (integral values write as integers). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Decode = __include("data/toml/Decode") +local Encode = __include("data/toml/Encode") + +-- ------------------------------------------------------------------------------------------------ contract +local Toml = { + name = "toml", + category = "data", + extensions = { "toml" }, + mime = { "application/toml" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Json", "codecs/text/Text" }, + caps = { decode = true, encode = true, ordered = true, dates = true }, +} + +type DecodeOptions = Decode.Options +type EncodeOptions = Encode.Options + +-- ------------------------------------------------------------------------------------------------ sniff +-- INI looks the same: a [table] or key = value start scores low and the extension decides +function Toml.sniff(r: Bytes.Reader): number + local head = r:peek(512) + if string.find(head, "%z") then + return 0 + end + for line in string.gmatch(head, "[^\n]+") do + local l = string.match(line, "^[ \t]*(.-)[ \t\r]*$") :: string + if l ~= "" and string.sub(l, 1, 1) ~= "#" then + if string.match(l, "^%[%[?[%w_%-%.\"' ]+%]%]?$") or string.match(l, "^[%w_%-%.\"']+[ \t]*=[ \t]*[\"'%[{%dtf%+%-in]") then + return 0.2 + end + return 0 + end + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Toml.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local s = buffer.readstring(r.buf, r.base, r.limit - r.base) + local v, msg, at = Decode.decode(s, opts) + if v == nil then + local m = tostring(msg) + local code = if string.find(m, "unterminated", 1, true) then Err.TRUNCATED else Err.CORRUPT + return nil, Err.new(code, m, at) + end + return v, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Toml.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local s, msg = Encode.encode(value, opts) + if not s then + return nil, Err.new(Err.ARG, msg or "cannot encode") + end + return buffer.fromstring(s), nil +end + +return Toml +end +__FILES["data/toml/Decode"] = function() + +-- data/toml/Decode: TOML 1.0.0 parser with the 1.0 validity rules; never throws (nil, message, 0-based offset). +local Text = __include("codecs/text/Text") +local Types = __include("Types") + +local Decode = {} + +local byte, sub, find, match, gsub, char = string.byte, string.sub, string.find, string.match, string.gsub, string.char + +type Options = { + bigInts: ("number" | "string")?, -- default "number" +} + +local utf8char = Text.utf8char + +local ESC: { [number]: string } = { [98] = "\b", [116] = "\t", [110] = "\n", [102] = "\f", [114] = "\r", [34] = '"', [92] = "\\" } + +-- digits with single underscores between them +local function digitsOk(d: string, class: string): boolean + return d ~= "" and not find(d, "__", 1, true) and byte(d, 1) ~= 95 and byte(d, #d) ~= 95 and find(d, "^[" .. class .. "_]+$") ~= nil +end + +function Decode.decode(s: string, opts: Options?): (any, any, number?) + local bigStrings = opts ~= nil and opts.bigInts == "string" + local errMsg: string = "" + local errAt = 0 + local function fail(msg: string, at: number): nil + errMsg, errAt = msg, at - 1 + return nil + end + + if sub(s, 1, 3) == "\239\187\191" then + s = sub(s, 4) + end + do + local bad = find(s, "[%z\1-\8\11\12\14-\31\127]") + if bad then + return nil, "control character", bad - 1 + end + local cr = find(s, "\r[^\n]") or (if byte(s, #s) == 13 then #s else nil) + if cr then + return nil, "carriage return without a line feed", cr - 1 + end + if find(s, "[\128-\255]") then + if not utf8.len(s) then + return nil, "invalid UTF-8", 0 + end + local sur = find(s, "\237[\160-\191]") + if sur then + return nil, "invalid UTF-8 (surrogate)", sur - 1 + end + end + if find(s, "\r", 1, true) then + s = gsub(s, "\r\n", "\n") + end + end + local n = #s + + -- table bookkeeping: kind = "explicit" | "implicit" | "dotted" | "inline"; section = where dotted tables were made + local kinds: { [any]: string } = {} + local sections: { [any]: number } = {} + local aot: { [any]: boolean } = {} -- arrays of tables ([[x]]); other arrays are static + local arrays: { [any]: boolean } = {} + local section = 0 + local building: { any }? = nil -- tables created inside the inline table being parsed (frozen when it closes) + + local function newTable(kind: string): any + local t = Types.object({}, {}) + kinds[t] = kind + if building then + table.insert(building, t) + end + return t + end + + local function ws(i: number): number + return match(s, "^[ \t]*()", i) :: any + end + local function wsnl(i: number): number + while true do + i = match(s, "^[ \t\n]*()", i) :: any + if byte(s, i) == 35 then + i = find(s, "\n", i, true) or (n + 1) + else + return i + end + end + end + + local function escape(p: number, parts: { string }): number? + local e = byte(s, p + 1) + local simple = if e then ESC[e] else nil + if simple then + table.insert(parts, simple) + return p + 2 + elseif e == 117 or e == 85 then + local len = if e == 117 then 4 else 8 + local h = match(s, "^" .. string.rep("%x", len), p + 2) + if not h then + return fail("bad unicode escape", p) + end + local cp = tonumber(h, 16) :: number + if cp > 0x10FFFF or (cp >= 0xD800 and cp <= 0xDFFF) then + return fail("unicode escape is not a scalar value", p) + end + table.insert(parts, utf8char(cp)) + return p + 2 + len + end + return fail("bad escape", p) + end + + local function basic(i: number): (string?, number) + local parts = {} + local j = i + 1 + while true do + local p = find(s, '["\\\n]', j) + if not p or byte(s, p) == 10 then + return fail("unterminated string", p or n + 1), 0 + end + table.insert(parts, sub(s, j, p - 1)) + if byte(s, p) == 34 then + return table.concat(parts), p + 1 + end + local nj = escape(p, parts) + if not nj then + return nil, 0 + end + j = nj + end + end + local function multiBasic(i: number): (string?, number) + local j = i + 3 + if byte(s, j) == 10 then + j += 1 + end + local parts = {} + while true do + local p = find(s, '["\\]', j) + if not p then + return fail("unterminated multi-line string", i), 0 + end + table.insert(parts, sub(s, j, p - 1)) + if byte(s, p) == 34 then + if sub(s, p, p + 2) == '"""' then + local q = p + 3 + local extra = 0 + while byte(s, q) == 34 and extra < 2 do + extra += 1 + q += 1 + end + if byte(s, q) == 34 then + return fail("too many quotes", q), 0 + end + table.insert(parts, string.rep('"', extra)) + return table.concat(parts), q + end + table.insert(parts, '"') + j = p + 1 + else + local k = match(s, "^\\[ \t]*\n[ \t\n]*()", p) + if k then + j = k :: any + else + local nj = escape(p, parts) + if not nj then + return nil, 0 + end + j = nj + end + end + end + end + local function literal(i: number): (string?, number) + local e = find(s, "['\n]", i + 1) + if not e or byte(s, e) == 10 then + return fail("unterminated literal string", e or n + 1), 0 + end + return sub(s, i + 1, e - 1), e + 1 + end + local function multiLiteral(i: number): (string?, number) + local j = i + 3 + if byte(s, j) == 10 then + j += 1 + end + local e = find(s, "'''", j, true) + if not e then + return fail("unterminated multi-line literal string", i), 0 + end + local q = e + 3 + local extra = 0 + while byte(s, q) == 39 and extra < 2 do + extra += 1 + q += 1 + end + if byte(s, q) == 39 then + return fail("too many quotes", q), 0 + end + return sub(s, j, e - 1) .. string.rep("'", extra), q + end + + local function key(i: number): ({ string }?, number) + local keys: { string } = {} + while true do + i = ws(i) + local c = byte(s, i) + local k: string? + if c == 34 then + if sub(s, i, i + 2) == '"""' then + return fail("multi-line string as a key", i), 0 + end + k, i = basic(i) + elseif c == 39 then + if sub(s, i, i + 2) == "'''" then + return fail("multi-line string as a key", i), 0 + end + k, i = literal(i) + else + k = match(s, "^[%w_%-]+", i) + if k then + i += #k + else + return fail("expected a key", i), 0 + end + end + if k == nil then + return nil, 0 + end + table.insert(keys, k :: string) + i = ws(i) + if byte(s, i) == 46 then + i += 1 + else + return keys, i + end + end + end + + local function number(i: number): (any, number) + local tok = match(s, "^[%+%-]?[%w_%.]+", i) + if not tok then + return fail("expected a value", i), 0 + end + local last = byte(tok, #tok) + if (last == 101 or last == 69) and not find(tok, "^[%+%-]?0[xob]") then + local ext = match(s, "^[%+%-][%w_]*", i + #tok) + if ext then + tok ..= ext + end + end + local nexti = i + #tok + local sign, body = match(tok, "^([%+%-]?)(.*)$") + if body == "inf" or body == "nan" then + return (if body == "nan" then 0 / 0 elseif sign == "-" then -math.huge else math.huge), nexti + end + local prefix = sub(body :: string, 1, 2) + if prefix == "0x" or prefix == "0o" or prefix == "0b" then + if sign ~= "" then + return fail("sign on a non-decimal integer", i), 0 + end + local d = sub(body :: string, 3) + local class = if prefix == "0x" then "%x" elseif prefix == "0o" then "0-7" else "01" + if not digitsOk(d, class) then + return fail("bad integer", i), 0 + end + d = gsub(gsub(d, "_", ""), "^0+", "") + local over = if prefix == "0x" then #d > 16 or (#d == 16 and (tonumber(sub(d, 1, 1), 16) :: number) >= 8) + elseif prefix == "0o" then #d > 21 + else #d > 63 + if over then + return fail("integer out of 64-bit range", i), 0 + end + if d == "" then + return 0, nexti + end + local v = tonumber(d, if prefix == "0x" then 16 elseif prefix == "0o" then 8 else 2) :: number + if bigStrings and v >= 9007199254740992 then + return prefix .. d, nexti + end + return v, nexti + end + local ip, rest = match(body :: string, "^([%d_]+)(.*)$") + if not ip or not digitsOk(ip, "%d") then + return fail("bad number", i), 0 + end + local digits = gsub(ip, "_", "") + if #digits > 1 and byte(digits, 1) == 48 then + return fail("leading zero", i), 0 + end + if rest == "" then + local limit = if sign == "-" then "9223372036854775808" else "9223372036854775807" + if #digits > 19 or (#digits == 19 and digits > limit) then + return fail("integer out of 64-bit range", i), 0 + end + local v = tonumber(digits) :: number + if bigStrings and v >= 9007199254740992 then + return (if sign == "-" then "-" else "") .. digits, nexti + end + return if sign == "-" then -v else v, nexti + end + local text: string = (sign :: string) .. digits + local frac, r2 = match(rest :: string, "^%.([%d_]*)(.*)$") + if frac then + if not digitsOk(frac, "%d") then + return fail("bad fraction", i), 0 + end + text ..= "." .. gsub(frac, "_", "") + rest = r2 + end + if rest ~= "" then + local es, ed = match(rest :: string, "^[eE]([%+%-]?)([%d_]*)$") + if not es or not digitsOk(ed :: string, "%d") then + return fail("bad float", i), 0 + end + text ..= "e" .. es .. gsub(ed :: string, "_", "") + end + local v = tonumber(text) + if v == nil then + return fail("bad float", i), 0 + end + return v, nexti + end + + local function datetime(i: number): (any, number) + local j = i + if match(s, "^%d%d%d%d%-%d%d%-%d%d", i) then + j = i + 10 + local c = byte(s, j) + if (c == 84 or c == 116 or c == 32) and match(s, "^%d%d:", j + 1) then + j += 1 + elseif c == 84 or c == 116 then + return fail("bad datetime", i), 0 + else + local d = Types.Date.parse(sub(s, i, j - 1)) + if not d then + return fail("bad date", i), 0 + end + return d, j + end + end + local t = match(s, "^%d%d:%d%d:%d%d", j) + if not t then + return fail("bad time (seconds are required)", j), 0 + end + j += 8 + local frac = match(s, "^%.%d+", j) + if frac then + j += #frac + elseif byte(s, j) == 46 then + return fail("bad fraction", j), 0 + end + if j - i > 19 or match(s, "^%d%d%d%d%-", i) then + local off = match(s, "^[Zz]", j) or match(s, "^[%+%-]%d%d:%d%d", j) + if off then + j += #off + end + end + local d = Types.Date.parse(sub(s, i, j - 1)) + if not d then + return fail("bad datetime", i), 0 + end + return d, j + end + + local value: (i: number) -> (any, number) + local assign: (tbl: any, keys: { string }, v: any, sid: number, at: number) -> boolean + + local function array(i: number): (any, number) + local arr = {} + arrays[arr] = true + i += 1 + while true do + i = wsnl(i) + local c = byte(s, i) + if c == 93 then + return arr, i + 1 + elseif c == nil then + return fail("unterminated array", i), 0 + end + local v, ni = value(i) + if v == nil then + return nil, 0 + end + table.insert(arr, v) + i = wsnl(ni) + c = byte(s, i) + if c == 44 then + i += 1 + elseif c == 93 then + return arr, i + 1 + else + return fail(if c == nil then "unterminated array" else "expected ',' or ']'", i), 0 + end + end + end + + local function inline(i: number): (any, number) + local outer = building + local mine = {} + building = mine + local t = newTable("inline") + section += 1 + local sid = section + i = ws(i + 1) + if byte(s, i) == 125 then + building = outer + return t, i + 1 + end + while true do + local keys, ni = key(i) + if not keys then + return nil, 0 + end + i = ws(ni) + if byte(s, i) ~= 61 then + return fail("expected '='", i), 0 + end + local v, vi = value(ws(i + 1)) + if v == nil then + return nil, 0 + end + if not assign(t, keys, v, sid, i) then + return nil, 0 + end + i = ws(vi) + local c = byte(s, i) + if c == 44 then + i = ws(i + 1) + if byte(s, i) == 125 then + return fail("trailing comma in an inline table", i), 0 + end + elseif c == 125 then + break + else + return fail(if c == 10 then "newline in an inline table" else "expected ',' or '}'", i), 0 + end + end + for _, x in mine do + kinds[x] = "inline" + end + building = outer + if outer then + for _, x in mine do + table.insert(outer, x) + end + end + return t, i + 1 + end + + function value(i: number): (any, number) + local c = byte(s, i) + if c == 34 then + if sub(s, i, i + 2) == '"""' then + return multiBasic(i) + end + return basic(i) + elseif c == 39 then + if sub(s, i, i + 2) == "'''" then + return multiLiteral(i) + end + return literal(i) + elseif c == 116 then + if match(s, "^true", i) and not match(s, "^[%w_%-]", i + 4) then + return true, i + 4 + end + elseif c == 102 then + if match(s, "^false", i) and not match(s, "^[%w_%-]", i + 5) then + return false, i + 5 + end + elseif c == 91 then + return array(i) + elseif c == 123 then + return inline(i) + elseif c and ((c >= 48 and c <= 57) or c == 43 or c == 45 or c == 105 or c == 110) then + if match(s, "^%d%d%d%d%-", i) or match(s, "^%d%d:", i) then + return datetime(i) + end + return number(i) + end + return fail(if c == nil or c == 10 then "expected a value" else "bad value", i), 0 + end + + function assign(tbl: any, keys: { string }, v: any, sid: number, at: number): boolean + local t = tbl + for j = 1, #keys - 1 do + local k = keys[j] + local x = t[k] + if x == nil then + local nt = newTable("dotted") + sections[nt] = sid + Types.set(t, k, nt) + t = nt + elseif kinds[x] == "implicit" or (kinds[x] == "dotted" and sections[x] == sid) then + t = x + else + fail("cannot add to " .. k .. " with a dotted key (already defined)", at) + return false + end + end + local k = keys[#keys] + if t[k] ~= nil then + fail("duplicate key " .. k, at) + return false + end + Types.set(t, k, v) + return true + end + + -- after a key / value or a header: spaces, an optional comment, then a newline or the end + local function eol(i: number): number? + i = ws(i) + local c = byte(s, i) + if c == 35 then + return find(s, "\n", i, true) or (n + 1) + elseif c == 10 or c == nil then + return i + end + return fail("expected the end of the line", i) + end + + local root = newTable("explicit") + local cur = root + local i = 1 + while true do + i = ws(i) + local c = byte(s, i) + if c == nil then + break + elseif c == 10 then + i += 1 + elseif c == 35 then + i = find(s, "\n", i, true) or (n + 1) + elseif c == 91 then + local at = i + local isAot = byte(s, i + 1) == 91 + local keys, ni = key(i + (if isAot then 2 else 1)) + if not keys then + return nil, errMsg, errAt + end + ni = ws(ni) + if isAot then + if sub(s, ni, ni + 1) ~= "]]" then + return nil, "expected ']]'", ni - 1 + end + ni += 2 + else + if byte(s, ni) ~= 93 then + return nil, "expected ']'", ni - 1 + end + ni += 1 + end + local t = root + for j = 1, #keys - 1 do + local k = keys[j] + local x = t[k] + if x == nil then + local nt = newTable("implicit") + Types.set(t, k, nt) + t = nt + elseif kinds[x] and kinds[x] ~= "inline" then + t = x + elseif aot[x] then + t = x[#x] + else + return nil, "cannot define a table under " .. k .. " (already defined)", at - 1 + end + end + local k = keys[#keys] + local x = t[k] + if isAot then + local arr = x + if arr == nil then + arr = {} + aot[arr] = true + Types.set(t, k, arr) + elseif not aot[arr] then + return nil, "cannot define an array of tables " .. k .. " (already defined)", at - 1 + end + local nt = newTable("explicit") + table.insert(arr, nt) + cur = nt + else + if x == nil then + local nt = newTable("explicit") + Types.set(t, k, nt) + cur = nt + elseif kinds[x] == "implicit" then + kinds[x] = "explicit" + cur = x + else + return nil, "table " .. k .. " defined twice", at - 1 + end + end + section += 1 + local e = eol(ni) + if not e then + return nil, errMsg, errAt + end + i = e + else + local at = i + local keys, ni = key(i) + if not keys then + return nil, errMsg, errAt + end + ni = ws(ni) + if byte(s, ni) ~= 61 then + return nil, "expected '='", ni - 1 + end + local v, vi = value(ws(ni + 1)) + if v == nil then + return nil, errMsg, errAt + end + if not assign(cur, keys, v, section, at) then + return nil, errMsg, errAt + end + local e = eol(vi) + if not e then + return nil, errMsg, errAt + end + i = e + end + end + return root, nil, nil +end + +return Decode +end +__FILES["data/toml/Encode"] = function() + +-- data/toml/Encode: TOML 1.0.0 writer: plain values, then [a.b] sections and [[a.b]] arrays of tables; never throws. +local Types = __include("Types") +local Json = __include("codecs/text/Json") + +local Encode = {} + +local format, gsub, find = string.format, string.gsub, string.find + +type Options = { + inline: boolean?, -- default false + indent: (number | string)?, -- default none +} + +local ESC: { [string]: string } = { ['"'] = '\\"', ["\\"] = "\\\\", ["\b"] = "\\b", ["\t"] = "\\t", ["\n"] = "\\n", ["\f"] = "\\f", ["\r"] = "\\r", ["\127"] = "\\u007F" } +for c = 0, 31 do + local ch = string.char(c) + if not ESC[ch] then + ESC[ch] = format("\\u%04X", c) + end +end + +local function quote(str: string): string + return '"' .. gsub(str, '[%z\1-\31"\\\127]', ESC) .. '"' +end +Encode.quote = quote + +local function keyText(k: string): string + if find(k, "^[%w_%-]+$") then + return k + end + return quote(k) +end + +local function isMap(t: { [any]: any }): boolean + if Types.isObject(t) then + return true + end + local n = #t + if n == 0 then + return next(t) ~= nil + end + local count = 0 + for _ in next, t do + count += 1 + end + return count ~= n +end + +local function isDate(v: any): boolean + return Types.Date.is(v) +end + +local function isAot(v: any): boolean + if type(v) ~= "table" or isDate(v) or isMap(v) or #v == 0 then + return false + end + for _, x in v do + if type(x) ~= "table" or isDate(x) or not isMap(x) then + return false + end + end + return true +end + +local function keysOf(t: { [any]: any }): ({ string }?, string?) + local keys = Types.keys(t) + for _, k in keys do + if type(k) ~= "string" then + return nil, "table key of type " .. type(k) + end + end + return keys :: any, nil +end + +type State = { seen: { [any]: boolean }, err: string? } + +local inlineValue: (st: State, v: any) -> string? + +local function scalar(st: State, v: any): string? + local tv = type(v) + if v == Types.null then + st.err = "TOML has no null" + return nil + elseif tv == "string" then + return quote(v) + elseif tv == "boolean" then + return if v then "true" else "false" + elseif tv == "number" then + if v ~= v then + return "nan" + elseif v == math.huge then + return "inf" + elseif v == -math.huge then + return "-inf" + elseif v == math.floor(v) and math.abs(v) < 2 ^ 63 then + return format("%d", v) + end + local t = Json.number(v) :: string + if not find(t, "[%.eEn]") then + t ..= ".0" + end + return t + elseif tv == "table" and isDate(v) then + return tostring(v) + elseif tv == "table" then + return inlineValue(st, v) + end + st.err = "cannot encode a " .. tv + return nil +end + +function inlineValue(st: State, v: any): string? + if st.seen[v] then + st.err = "a table contains itself" + return nil + end + st.seen[v] = true + local parts = {} + if isMap(v) then + local keys, kerr = keysOf(v) + if not keys then + st.err = kerr + return nil + end + for _, k in keys do + local s = scalar(st, v[k]) + if not s then + return nil + end + table.insert(parts, keyText(k) .. " = " .. s) + end + st.seen[v] = nil + return if #parts == 0 then "{}" else "{ " .. table.concat(parts, ", ") .. " }" + end + for i = 1, #v do + local s = scalar(st, v[i]) + if not s then + return nil + end + parts[i] = s + end + st.seen[v] = nil + return "[" .. table.concat(parts, ", ") .. "]" +end + +local function section(st: State, t: any, path: string, out: { string }, inlineAll: boolean, ind: string, depth: number): boolean + if st.seen[t] then + st.err = "a table contains itself" + return false + end + st.seen[t] = true + local keys, kerr = keysOf(t) + if not keys then + st.err = kerr + return false + end + local pad = string.rep(ind, depth) + local subs = {} + for _, k in keys do + local v = t[k] + if not inlineAll and type(v) == "table" and not isDate(v) and (isMap(v) or isAot(v)) then + table.insert(subs, k) + else + local s = scalar(st, v) + if not s then + return false + end + table.insert(out, pad .. keyText(k) .. " = " .. s .. "\n") + end + end + for _, k in subs do + local v = t[k] + local p = (if path == "" then "" else path .. ".") .. keyText(k) + if isMap(v) then + table.insert(out, (if #out > 0 then "\n" else "") .. pad .. "[" .. p .. "]\n") + if not section(st, v, p, out, inlineAll, ind, depth + 1) then + return false + end + else + for _, el in v do + table.insert(out, (if #out > 0 then "\n" else "") .. pad .. "[[" .. p .. "]]\n") + if not section(st, el, p, out, inlineAll, ind, depth + 1) then + return false + end + end + end + end + st.seen[t] = nil + return true +end + +function Encode.encode(t: any, opts: Options?): (string?, string?) + if type(t) ~= "table" or isDate(t) or (not isMap(t) and next(t) ~= nil) then + return nil, "the top level must be a table with string keys" + end + local o: Options = opts or {} + local ind = if type(o.indent) == "number" then string.rep(" ", o.indent) elseif type(o.indent) == "string" then o.indent else "" + local st: State = { seen = {}, err = nil } + local out = {} + if not section(st, t, "", out, o.inline == true, ind, 0) then + return nil, st.err + end + return table.concat(out), nil +end + +return Encode +end +__FILES["data/xml"] = function() + +-- data/xml: XML 1.0 over codecs/text/Xml. Supports: decode to a "#document" XmlNode tree, encode a document or an +-- element. Not supported: external entities / DTDs, validation. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Sniff = __include("core/Sniff") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Xml = __include("codecs/text/Xml") + +-- ------------------------------------------------------------------------------------------------ contract +local XmlFormat = { + name = "xml", + category = "data", + extensions = { "xml", "xsd", "xsl", "xslt", "rss", "atom", "xhtml" }, + mime = { "application/xml", "text/xml" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Xml", "core/Sniff" }, + caps = { decode = true, encode = true, namespaces = true, streaming = true }, +} + +type DecodeOptions = Xml.DecodeOptions +type EncodeOptions = Xml.EncodeOptions + +-- ------------------------------------------------------------------------------------------------ sniff +function XmlFormat.sniff(r: Bytes.Reader): number + 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 + if string.match(head, "^[ \t\r\n]*<[%a!]") then + return 0.3 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function XmlFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.XmlNode?, Err.Err?) + return Xml.decode(buffer.readstring(r.buf, r.base, r.limit - r.base), opts) +end + +-- ------------------------------------------------------------------------------------------------ encode +function XmlFormat.encode(node: Types.XmlNode, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(node) ~= "table" or type(node.name) ~= "string" then + return nil, Err.new(Err.ARG, "expected an XmlNode") + end + local s, err = Xml.encode(node, opts) + if not s then + return nil, err + end + return buffer.fromstring(s), nil +end + +return XmlFormat +end +__FILES["data/yaml"] = function() + +-- data/yaml: YAML 1.2 (core schema), new code. Supports: block / flow styles, every scalar style, anchors and aliases +-- (shared, alias-bomb limit), core tags + !!binary / !!timestamp, %TAG, multi-document streams; writes block style. +-- Not supported (Err.UNSUPPORTED): complex keys, collections as keys; merge keys stay keys; YAML 1.1 types are strings. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Parse = __include("data/yaml/Parse") +local Emit = __include("data/yaml/Emit") + +-- ------------------------------------------------------------------------------------------------ contract +local Yaml = { + name = "yaml", + category = "data", + extensions = { "yaml", "yml" }, + mime = { "application/yaml", "application/x-yaml", "text/yaml" }, + deps = { "core/Err", "core/Bytes", "Types", "core/Base64", "codecs/text/Text" }, + caps = { decode = true, encode = true, ordered = true, multiDocument = true, anchors = true }, +} + +type DecodeOptions = Parse.Options +type EncodeOptions = Emit.Options + +-- ------------------------------------------------------------------------------------------------ sniff +function Yaml.sniff(r: Bytes.Reader): number + local head = r:peek(256) + if string.find(head, "%z") then + return 0 + end + if string.match(head, "^%%YAML ") then + return 0.9 + end + if string.match(head, "^%-%-%-[ \r\n]") then + return 0.5 + end + local line = string.match(head, "^[ \t\r\n]*([^\r\n]*)") + if line and (string.match(line, "^[%w_%-\"']+[%w_%- \"']*:[ ]") or string.match(line, "^[%w_%-]+:$") or string.match(line, "^%- ")) then + return 0.2 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Yaml.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + local docs, code, msg, at = Parse.run(text, opts) + if not docs then + return nil, Err.new(code, msg, at) + end + if opts and opts.all then + return docs, nil + end + local first = docs[1] + if first == nil then + return if opts and opts.null ~= nil then opts.null else Types.null, nil + end + return first, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Yaml.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local s, err = Emit.encode(value, opts) + if not s then + return nil, Err.new(Err.ARG, err or "cannot encode") + end + return buffer.fromstring(s), nil +end + +return Yaml +end +__FILES["data/yaml/Emit"] = function() + +-- data/yaml/Emit: YAML block-style writer; plain scalars only when they read back the same (core schema, no 1.1 bools). +local Types = __include("Types") +local Base64 = __include("core/Base64") +local Parse = __include("data/yaml/Parse") + +local Emit = {} + +type Options = { + indent: number?, -- default 2 + all: boolean?, + explicitStart: boolean?, -- default false + sortKeys: boolean?, -- default true + null: any?, +} + +local format, byte, find, gsub = string.format, string.byte, string.find, string.gsub + +local YAML11 = { + y = true, Y = true, yes = true, Yes = true, YES = true, n = true, N = true, no = true, No = true, NO = true, + on = true, On = true, ON = true, off = true, Off = true, OFF = true, +} + +local function number(x: number): string + if x ~= x then + return ".nan" + elseif x == math.huge then + return ".inf" + elseif x == -math.huge then + return "-.inf" + elseif x == math.floor(x) and math.abs(x) < 2 ^ 53 then + if x == 0 and 1 / x < 0 then + return "-0.0" + end + return format("%d", x) + end + for _, f in { "%.15g", "%.16g", "%.17g" } do + local t = format(f, x) + if tonumber(t) == x then + if not find(t, "[%.eEn]") then + t ..= ".0" + end + return t + end + end + return format("%.17g", x) +end + +local DQ: { [string]: string } = { + ["\\"] = "\\\\", + ['"'] = '\\"', + ["\n"] = "\\n", + ["\t"] = "\\t", + ["\r"] = "\\r", + ["\0"] = "\\0", + ["\27"] = "\\e", +} +local function dquote(s: string): string + s = gsub(s, '[%z\1-\31\127\\"]', function(c: string): string + return DQ[c] or format("\\x%02x", byte(c)) + end) + -- the Unicode line / paragraph separators and NEL would be folded as line breaks: escape them + s = gsub(s, "\226\128\168", "\\L") + s = gsub(s, "\226\128\169", "\\P") + s = gsub(s, "\194\133", "\\N") + return '"' .. s .. '"' +end + +local function plainOk(s: string): boolean + if s == "" or YAML11[s] then + return false + end + if Parse.resolve(s, Types.null) ~= s then + return false + end + if find(s, "^[%s]") or find(s, "[%s]$") then + return false + end + if find(s, "^[%-%?:,%[%]{}#&%*!|>'\"%%@`]") or find(s, "^%.%.%.") then + return false + end + if find(s, ": ", 1, true) or find(s, " #", 1, true) or find(s, ":$") or find(s, "[%z\1-\31\127]") then + return false + end + if find(s, "\226\128\168") or find(s, "\226\128\169") or find(s, "\194\133") or find(s, "\239\187\191") then + return false + end + -- not invalid UTF-8 (the reader treats the text as bytes, but other tools will not) + if find(s, "[\128-\255]") and not utf8.len(s) then + return false + end + return true +end + +local function str(s: string, ind: string, key: boolean): string + if plainOk(s) then + return s + end + if not key and find(s, "\n", 1, true) and not find(s, "[%z\1-\9\11-\31\127]") and not find(s, "[ ]\n") and not find(s, " $") + and not find(s, "^[ \n]") and not find(s, "\226\128[\168\169]") and not find(s, "\194\133") and (not find(s, "[\128-\255]") or utf8.len(s)) + then + local trailing = #(string.match(s, "\n*$") :: string) + local body = string.sub(s, 1, #s - trailing) + local chomp = if trailing == 0 then "-" elseif trailing == 1 then "" else "+" + local lines = string.split(body, "\n") + local out = { "|" .. chomp } + for _, l in lines do + table.insert(out, if l == "" then "" else ind .. l) + end + for _ = 2, trailing do + table.insert(out, "") + end + return table.concat(out, "\n") + end + return dquote(s) +end + +local isArray = Types.isArray + +local keyLess = Types.keyLess + +type St = { out: { string }, step: number, sort: boolean, null: any, refs: { [any]: number }, anchors: { [any]: string }, nextId: number, err: string? } + +local function count(st: St, v: any, onStack: { [any]: boolean }): boolean + if type(v) ~= "table" or v == Types.null or v == st.null or Types.Date.is(v) then + return true + end + if onStack[v] then + st.err = "a cycle (YAML aliases cannot point at their own ancestors here)" + return false + end + local r = st.refs[v] + st.refs[v] = (r or 0) + 1 + if r then + return true + end + onStack[v] = true + for k, x in next, v do + if not count(st, k, onStack) or not count(st, x, onStack) then + return false + end + end + onStack[v] = nil + return true +end + +local function scalar(st: St, v: any, ind: string, key: boolean): string? + local tv = type(v) + if v == nil or v == Types.null or (st.null ~= nil and v == st.null) then + return "null" + elseif tv == "boolean" then + return if v then "true" else "false" + elseif tv == "number" then + return number(v) + elseif tv == "string" then + return str(v, ind, key) + elseif tv == "buffer" then + return "!!binary " .. Base64.encode(v) + elseif tv == "table" and Types.Date.is(v) then + return tostring(v) + end + return nil +end + +local write: (st: St, v: any, depth: number) -> string? + +function write(st: St, v: any, depth: number): string? + local ind = string.rep(" ", st.step * (depth + 1)) + local s = scalar(st, v, ind, false) + if s then + return " " .. s + end + if type(v) ~= "table" then + st.err = "cannot write a " .. type(v) + return nil + end + local prefix = "" + if st.refs[v] and st.refs[v] > 1 then + local a = st.anchors[v] + if a then + return " *" .. a + end + st.nextId += 1 + a = "id" .. format("%03d", st.nextId) + st.anchors[v] = a + prefix = " &" .. a + end + local pad = string.rep(" ", st.step * depth) + if isArray(v) and not Types.isObject(v) then + if #v == 0 then + return prefix .. " []" + end + local parts = {} + for _, x in v do + local t = write(st, x, depth + 1) + if not t then + return nil + end + table.insert(parts, pad .. "-" .. t) + end + return prefix .. "\n" .. table.concat(parts, "\n") + end + local keys + if Types.isObject(v) then + keys = Types.keys(v) + else + keys = {} + for k in next, v do + table.insert(keys, k) + end + if st.sort then + table.sort(keys, keyLess) + end + end + if #keys == 0 then + return prefix .. " {}" + end + local parts = {} + for _, k in keys do + local ks = scalar(st, k, "", true) + if not ks or (type(k) == "table" and not Types.Date.is(k) and k ~= Types.null) then + st.err = "mapping keys must be scalars" + return nil + end + local t = write(st, v[k], depth + 1) + if not t then + return nil + end + table.insert(parts, pad .. ks .. ":" .. t) + end + return prefix .. "\n" .. table.concat(parts, "\n") +end + +local function document(st: St, v: any): string? + local t = write(st, v, 0) + if not t then + return nil + end + if string.sub(t, 1, 1) == "\n" then + return string.sub(t, 2) + end + local body = string.sub(t, 2) + if string.sub(body, 1, 1) == "&" then + return body + end + return body +end + +function Emit.encode(v: any, opts: Options?): (string?, string?) + local o: Options = opts or {} + local st: St = { + out = {}, + step = math.clamp(math.floor(o.indent or 2), 1, 10), + sort = o.sortKeys ~= false, + null = o.null, + refs = {}, + anchors = {}, + nextId = 0, + err = nil, + } + local docs = if o.all then v else { v } + if type(docs) ~= "table" then + return nil, "all: expected an array of documents" + end + local parts = {} + for i, d in docs do + st.refs, st.anchors = {}, {} + if not count(st, d, {}) then + return nil, st.err + end + local t = document(st, d) + if not t then + return nil, st.err + end + local start = i > 1 or o.explicitStart + if start then + -- a scalar / [] / {} can share the "---" line; a collection starts on the next one + local block = type(d) == "table" and d ~= Types.null and not Types.Date.is(d) and next(d) ~= nil + local sep = if block and not string.find(t, "^&") then "---\n" else "--- " + table.insert(parts, sep .. t .. "\n") + else + table.insert(parts, t .. "\n") + end + end + return table.concat(parts), nil +end + +return Emit +end +__FILES["data/yaml/Parse"] = function() + +-- data/yaml/Parse: YAML 1.2 recursive-descent parser; raises { yamlErr } tables caught by run(), never throws past it. +local Text = __include("codecs/text/Text") +local Types = __include("Types") +local Base64 = __include("core/Base64") + +local Parse = {} + +local byte, sub, find, match, char = string.byte, string.sub, string.find, string.match, string.char + +type Options = { + all: boolean?, -- default false + tags: ("error" | "ignore")?, -- default "error" + maxAliasNodes: number?, -- default 1e6 (billion laughs guard) + maxDepth: number?, -- default 500 + null: any?, -- default Types.null +} + +type St = { + s: string, + n: number, + anchors: { [string]: any }, + handles: { [string]: string }, + depth: number, + maxDepth: number, + aliasNodes: number, + maxAlias: number, + sizes: { [any]: number }, + ignoreTags: boolean, + null: any, +} + +local CORE = "tag:yaml.org,2002:" + +local function raise(code: string, msg: string, p: number) + error({ yamlErr = true, code = code, msg = msg, at = p - 1 }, 0) +end +local function corrupt(msg: string, p: number) + raise("CORRUPT", msg, p) +end + +-- ------------------------------------------------------------------------------------------------ helpers +local function col(s: string, p: number): number + local q = p + while q > 1 and byte(s, q - 1) ~= 10 do + q -= 1 + end + return p - q +end + +local function isWsEnd(c: number?): boolean + return c == nil or c == 32 or c == 9 or c == 10 +end + +local function docMarker(s: string, p: number): boolean + if p ~= 1 and byte(s, p - 1) ~= 10 then + return false + end + local m = sub(s, p, p + 2) + return (m == "---" or m == "...") and isWsEnd(byte(s, p + 3)) +end + +local function skip(s: string, p: number): number + local n = #s + while p <= n do + local c = byte(s, p) + if c == 32 or c == 9 or c == 10 then + p += 1 + elseif c == 35 and (p == 1 or isWsEnd(byte(s, p - 1))) then + local e = find(s, "\n", p, true) + if not e then + return n + 1 + end + p = e + 1 + else + return p + end + end + return p +end + +local function lineIndent(s: string, p: number): (number, boolean) + local q = p + while q > 1 and byte(s, q - 1) ~= 10 do + q -= 1 + end + local sp = (match(s, "^ *()", q) :: number) - q + return sp, find(sub(s, q, p - 1), "\t", 1, true) ~= nil +end + +-- block content at p on a new line must not be indented with tabs: a tab before p is an error when the spaces before +-- it do not already indent the line past ind (siblings: pass ind = their column - 1... any tab is an error) +local function noTabs(s: string, p: number, ind: number?) + local sp, tab = lineIndent(s, p) + if tab and (ind == nil or sp <= ind) then + error({ yamlErr = true, code = "CORRUPT", msg = "tab in indentation", at = p - 1 }, 0) + end +end + +local function skipLine(s: string, p: number): number + return match(s, "^[ \t]*()", p) :: any +end + +-- after a node on its line: only spaces and a comment may follow before the line break +local function endOfLine(s: string, p: number): boolean + local q = skipLine(s, p) + local c = byte(s, q) + return c == nil or c == 10 or (c == 35 and q > p) +end + +local utf8char = Text.utf8char + +-- ------------------------------------------------------------------------------------------------ resolution +function Parse.resolve(t: string, nullv: any): any + if t == "" or t == "~" or t == "null" or t == "Null" or t == "NULL" then + return nullv + end + local c = byte(t) + if c == 116 or c == 84 or c == 102 or c == 70 then + if t == "true" or t == "True" or t == "TRUE" then + return true + elseif t == "false" or t == "False" or t == "FALSE" then + return false + end + return t + end + if not ((c >= 48 and c <= 57) or c == 43 or c == 45 or c == 46) then + return t + end + if match(t, "^[-+]?%d+$") then + return tonumber(if c == 43 then sub(t, 2) else t) + end + local o = match(t, "^0o([0-7]+)$") + if o then + return tonumber(o, 8) + end + local x = match(t, "^0x(%x+)$") + if x then + return tonumber(x, 16) + end + if match(t, "^[-+]?%d+%.?%d*$") or match(t, "^[-+]?%.%d+$") or match(t, "^[-+]?%d+%.?%d*[eE][-+]?%d+$") or match(t, "^[-+]?%.%d+[eE][-+]?%d+$") then + local v = tonumber(if c == 43 then sub(t, 2) else t) + if v then + return v + end + end + local inf = match(t, "^([-+]?)%.[iI][nN][fF]$") + if inf and (t == inf .. ".inf" or t == inf .. ".Inf" or t == inf .. ".INF") then + return if inf == "-" then -math.huge else math.huge + end + if t == ".nan" or t == ".NaN" or t == ".NAN" then + return 0 / 0 + end + return t +end + +local function base64(t: string): buffer? + return (Base64.decode(t)) +end + +local function scalarValue(st: St, raw: string, plain: boolean, tag: string?, p: number): any + if tag == nil then + return if plain then Parse.resolve(raw, st.null) else raw + end + if tag == "!" or tag == CORE .. "str" then + return raw + end + if sub(tag, 1, #CORE) == CORE then + local kind = sub(tag, #CORE + 1) + local v = Parse.resolve(raw, st.null) + if kind == "null" then + if v ~= st.null then + corrupt("bad !!null " .. raw, p) + end + return v + elseif kind == "bool" then + if type(v) ~= "boolean" then + corrupt("bad !!bool " .. raw, p) + end + return v + elseif kind == "int" then + if type(v) ~= "number" or not (match(raw, "^[-+]?%d+$") or match(raw, "^0[ox]")) then + corrupt("bad !!int " .. raw, p) + end + return v + elseif kind == "float" then + if type(v) ~= "number" then + corrupt("bad !!float " .. raw, p) + end + return v + elseif kind == "binary" then + local b = base64(raw) + if not b then + corrupt("bad !!binary data", p) + end + return b + elseif kind == "timestamp" then + local d = Types.Date.parse(raw) + if not d then + corrupt("bad !!timestamp " .. raw, p) + end + return d + elseif kind == "map" or kind == "seq" then + corrupt("!!" .. kind .. " on a scalar", p) + end + end + if st.ignoreTags then + return if plain then Parse.resolve(raw, st.null) else raw + end + raise("UNSUPPORTED", "tag " .. tag, p) + return nil +end + +local function collectionTag(st: St, tag: string?, kind: string, p: number) + if tag == nil or tag == "!" or tag == CORE .. kind then + return + end + if sub(tag, 1, #CORE) == CORE then + local k = sub(tag, #CORE + 1) + if k == "map" or k == "seq" or k == "str" or k == "int" or k == "float" or k == "bool" or k == "null" or k == "binary" then + corrupt("!!" .. k .. " on a " .. kind, p) + end + end + if not st.ignoreTags then + raise("UNSUPPORTED", "tag " .. tag, p) + end +end + +local function size(st: St, v: any): number + if type(v) ~= "table" or v == st.null then + return 1 + end + local m = st.sizes[v] + if m then + return m + end + local total = 1 + for k, x in next, v do + total += size(st, k) + size(st, x) + end + st.sizes[v] = total + return total +end + +-- ------------------------------------------------------------------------------------------------ properties +type Props = { anchor: string?, tag: string?, at: number } + +local function properties(st: St, p: number): (Props?, number) + local s = st.s + local props: Props? = nil + while true do + local c = byte(s, p) + if c == 38 then -- & + local name = match(s, "^&([^%s,%[%]{}]+)", p) + if not name then + corrupt("bad anchor", p) + end + local pr: Props = props or { at = p } + props = pr + if pr.anchor then + corrupt("two anchors on one node", p) + end + pr.anchor = name + p = skipLine(s, p + 1 + #(name :: string)) + elseif c == 33 then -- ! + local pr: Props = props or { at = p } + props = pr + if pr.tag then + corrupt("two tags on one node", p) + end + local tag: string + if byte(s, p + 1) == 60 then -- !<verbatim> + local v = match(s, "^!<([^>%s]+)>", p) + if not v then + corrupt("bad verbatim tag", p) + end + tag = v :: string + p += #tag + 3 + else + local handle, suffix = match(s, "^(![%w%-]*!)([^%s,%[%]{}]*)", p) + if handle then + local prefix = st.handles[handle] + if not prefix then + corrupt("undefined tag handle " .. handle, p) + end + if suffix == "" then + corrupt("empty tag", p) + end + tag = prefix .. string.gsub(suffix :: string, "%%(%x%x)", function(h: string): string + return char(tonumber(h, 16) :: number) + end) + else + local sfx = match(s, "^!([^%s,%[%]{}]*)", p) :: string + if sfx == "" then + tag = "!" + else + tag = st.handles["!"] .. sfx + end + end + p += #(match(s, "^![^%s,%[%]{}]*", p) :: string) + end + pr.tag = tag + if not isWsEnd(byte(s, p)) and byte(s, p) ~= 44 and byte(s, p) ~= 93 and byte(s, p) ~= 125 then + corrupt("bad tag", p) + end + p = skipLine(s, p) + else + return props, p + end + end +end + +local function finish(st: St, props: Props?, v: any): any + if props and props.anchor then + st.anchors[props.anchor] = v + end + return v +end + +local function alias(st: St, p: number): (any, number) + local s = st.s + local name = match(s, "^%*([^%s,%[%]{}]+)", p) + if not name then + corrupt("bad alias", p) + end + local v = st.anchors[name :: string] + if v == nil then + corrupt("undefined alias *" .. (name :: string), p) + end + st.aliasNodes += size(st, v) + if st.aliasNodes > st.maxAlias then + raise("LIMIT", "alias expansion over " .. st.maxAlias .. " nodes", p) + end + return v, p + 1 + #(name :: string) +end + +-- ------------------------------------------------------------------------------------------------ scalars +-- line folding: lines holding only spaces / tabs count as empty +local function fold(s: string, p: number): (string, number) + local empties = 0 + local q = p + 1 + while true do + local r = skipLine(s, q) + if byte(s, r) == 10 then + empties += 1 + q = r + 1 + else + return (if empties == 0 then " " else string.rep("\n", empties)), q + end + end +end + +local ESC: { [number]: string } = { + [48] = "\0", + [97] = "\a", + [98] = "\b", + [116] = "\t", + [9] = "\t", + [110] = "\n", + [118] = "\v", + [102] = "\f", + [114] = "\r", + [101] = "\27", + [32] = " ", + [34] = '"', + [47] = "/", + [92] = "\\", + [78] = "\194\133", + [95] = "\194\160", + [76] = "\226\128\168", + [80] = "\226\128\169", +} + +local function quoted(st: St, p: number, ind: number): (string, number) + local s = st.s + local dq = byte(s, p) == 34 + local parts: { string } = {} + local i = p + 1 + local stop = if dq then '[\\"\n]' else "['\n]" + while true do + local j = find(s, stop, i) + if not j then + raise("TRUNCATED", "unterminated quoted scalar", p) + end + local jj = j :: number + local seg = sub(s, i, jj - 1) + local c = byte(s, jj) + if c == 10 then + table.insert(parts, (string.gsub(seg, "[ \t]+$", ""))) + local f, q = fold(s, jj) + if docMarker(s, q) then + corrupt("document marker inside a quoted scalar", q) + end + if ind >= 0 and (match(s, "^ *()", q) :: number) - q <= ind then + corrupt("a quoted scalar's continuation line is not indented", q) + end + table.insert(parts, f) + i = skipLine(s, q) + elseif dq and c == 92 then + table.insert(parts, seg) + local e = byte(s, jj + 1) + if e == 10 then -- escaped line break: joined without a space + local r = jj + 2 + while true do + local q = skipLine(s, r) + if byte(s, q) == 10 then + table.insert(parts, "\n") + r = q + 1 + else + i = q + break + end + end + elseif e == 120 or e == 117 or e == 85 then + local len = if e == 120 then 2 elseif e == 117 then 4 else 8 + local h = sub(s, jj + 2, jj + 1 + len) + if #h ~= len or not match(h, "^%x+$") then + corrupt("bad escape", jj) + end + local cp = tonumber(h, 16) :: number + if cp > 0x10FFFF then + corrupt("bad escape", jj) + end + table.insert(parts, utf8char(cp)) + i = jj + 2 + len + else + local r = if e then ESC[e] else nil + if not r then + corrupt("bad escape", jj) + end + table.insert(parts, r :: string) + i = jj + 2 + end + elseif not dq and byte(s, jj + 1) == 39 then + table.insert(parts, seg .. "'") + i = jj + 2 + else + table.insert(parts, seg) + return table.concat(parts), jj + 1 + end + end +end + +-- plain scalar: continuation lines indented deeper than ind (block context); flow context stops at , [ ] { } +local function plain(st: St, p: number, ind: number, flow: boolean): (string, number) + local s = st.s + local parts: { string } = {} + local i = p + local lastEnd = p + while true do + local j = i + local stopAt = nil + while true do + local c = byte(s, j) + if c == nil or c == 10 then + break + elseif c == 58 then -- : + local d = byte(s, j + 1) + if isWsEnd(d) or (flow and (d == 44 or d == 91 or d == 93 or d == 123 or d == 125)) then + stopAt = j + break + end + elseif c == 35 and (byte(s, j - 1) == 32 or byte(s, j - 1) == 9) then + stopAt = j + break + elseif flow and (c == 44 or c == 91 or c == 93 or c == 123 or c == 125) then + stopAt = j + break + end + j += 1 + end + local seg = string.gsub(sub(s, i, j - 1), "[ \t]+$", "") + table.insert(parts, seg) + lastEnd = i + #seg + if stopAt or byte(s, j) == nil then + return table.concat(parts), lastEnd + end + local f, q = fold(s, j) + local r = skipLine(s, q) + local c = byte(s, r) + if c == nil or docMarker(s, q) or c == 35 or (not flow and (match(s, "^ *()", q) :: number) - q <= ind) then + return table.concat(parts), lastEnd + end + if flow and (c == 44 or c == 93 or c == 125 or (c == 58 and isWsEnd(byte(s, r + 1)))) then + return table.concat(parts), lastEnd + end + table.insert(parts, f) + i = r + end +end + +local function blockScalar(st: St, p: number, ind: number): (string, number) + local s = st.s + local folded = byte(s, p) == 62 + local q = p + 1 + local explicit: number? = nil + local chomp = "clip" + for _ = 1, 2 do + local c = byte(s, q) + if c and c >= 49 and c <= 57 and not explicit then + explicit = c - 48 + q += 1 + elseif (c == 43 or c == 45) and chomp == "clip" then + chomp = if c == 43 then "keep" else "strip" + q += 1 + end + end + if not endOfLine(s, q) then + corrupt("bad block scalar header", q) + end + local nl = find(s, "\n", q, true) + local lines: { string } = {} + local trailing = 0 + if not nl then + return "", #s + 1 + end + local ls = (nl :: number) + 1 + local indent: number + if explicit then + indent = math.max(ind + explicit, 0) -- n + the indicator (n = -1 at the top level) + else + -- auto-detect: the first non-empty line; leading empty lines may not be longer + local maxEmpty = 0 + local r = ls + indent = -1 + while true do + local sp = (match(s, "^ *()", r) :: number) - r + local c = byte(s, r + sp) + if c == 10 then + maxEmpty = math.max(maxEmpty, sp) + r = r + sp + 1 + elseif c == nil then + maxEmpty = math.max(maxEmpty, sp) + indent = math.max(maxEmpty, ind + 1) + break + else + if docMarker(s, r) then + indent = math.max(maxEmpty, ind + 1) + break + end + indent = sp + if sp < maxEmpty then + corrupt("leading empty lines indented more than the block scalar", r) + end + break + end + end + if indent <= ind then + indent = ind + 1 + end + end + local r = ls + local pendingEmpty = 0 + local endPos = ls + while r <= #s do + if docMarker(s, r) then + break + end + local sp = (match(s, "^ *()", r) :: number) - r + local e = find(s, "\n", r, true) or (#s + 1) + if sp >= indent then + local text = sub(s, r + indent, e - 1) + for _ = 1, pendingEmpty do + table.insert(lines, "") + end + pendingEmpty = 0 + table.insert(lines, text) + elseif r + sp == e then + pendingEmpty += 1 + else + if byte(s, r + sp) == 9 then + corrupt("tab in block scalar indentation", r + sp) + end + break + end + r = e + 1 + endPos = math.min(r, #s + 1) + end + trailing = pendingEmpty + local body: string + if #lines == 0 then + body = "" + elseif not folded then + body = table.concat(lines, "\n") + else + local out: { string } = {} + local prevMore = false + local empties = 0 + local first = true + for _, l in lines do + if l == "" then + empties += 1 + else + local more = byte(l) == 32 or byte(l) == 9 + if first then + table.insert(out, string.rep("\n", empties)) + elseif empties == 0 then + table.insert(out, if more or prevMore then "\n" else " ") + else + table.insert(out, string.rep("\n", if more or prevMore then empties + 1 else empties)) + end + table.insert(out, l) + first = false + prevMore = more + empties = 0 + end + end + trailing += empties + body = table.concat(out) + end + if not folded then + -- literal: trailing "" lines inside `lines` are content-indented empty lines; count them as trailing + local k = #lines + while k > 0 and lines[k] == "" do + k -= 1 + trailing += 1 + end + body = table.concat(lines, "\n", 1, k) + if k == 0 then + body = "" + end + lines = table.move(lines, 1, k, 1, {}) + end + local hasContent = false + for _, l in lines do + if l ~= "" then + hasContent = true + break + end + end + if chomp == "strip" then + return body, endPos + elseif chomp == "clip" then + return (if hasContent then body .. "\n" else ""), endPos + end + return (if hasContent then body .. "\n" else "") .. string.rep("\n", trailing), endPos +end + +-- ------------------------------------------------------------------------------------------------ flow +local parseFlow: (st: St, p: number, ind: number) -> (any, number) + +local function enter(st: St, p: number) + st.depth += 1 + if st.depth > st.maxDepth then + raise("LIMIT", "nested deeper than " .. st.maxDepth, p) + end +end + +local function flowNode(st: St, p: number, ind: number): (any, number, boolean) + local s = st.s + local props, q = properties(st, p) + if props then + q = skip(s, q) + end + local c = byte(s, q) + local v: any + if c == 42 then -- * + if props then + corrupt("properties on an alias", q) + end + return alias(st, q) + elseif c == 91 or c == 123 then + v, q = parseFlow(st, q, ind) + collectionTag(st, props and props.tag, if c == 91 then "seq" else "map", q) + return finish(st, props, v), q, false + elseif c == 34 or c == 39 then + local t, r = quoted(st, q, ind) + return finish(st, props, scalarValue(st, t, false, props and props.tag, q)), r, false + elseif c == nil or c == 44 or c == 93 or c == 125 or (c == 58 and (isWsEnd(byte(s, q + 1)) or byte(s, q + 1) == 44 or byte(s, q + 1) == 93 or byte(s, q + 1) == 125)) then + return finish(st, props, scalarValue(st, "", true, props and props.tag, q)), (if props then q else p), true + elseif c == 35 or c == 38 or c == 33 or c == 124 or c == 62 or c == 37 or c == 64 or c == 96 then + corrupt("unexpected character in a flow collection", q) + elseif (c == 45 or c == 63 or c == 58) and (isWsEnd(byte(s, q + 1)) or byte(s, q + 1) == 44 or byte(s, q + 1) == 93 or byte(s, q + 1) == 125) then + if c == 63 then + raise("UNSUPPORTED", "explicit keys (?) in flow collections", q) + end + corrupt("unexpected '" .. char(c :: number) .. "' in a flow collection", q) + end + local t, r = plain(st, q, ind, true) + return finish(st, props, scalarValue(st, t, true, props and props.tag, q)), r, false +end + +local function checkKey(st: St, k: any, p: number): any + if type(k) == "table" and k ~= st.null and not Types.Date.is(k) then + raise("UNSUPPORTED", "collections as mapping keys", p) + end + if k ~= k then + corrupt("NaN as a mapping key", p) + end + return k +end + +function parseFlow(st: St, p: number, ind: number): (any, number) + local s = st.s + enter(st, p) + local isMap = byte(s, p) == 123 + local close = if isMap then 125 else 93 + local t: { [any]: any } = {} + local order: { any } = {} + local count = 0 + local q = p + 1 + local function flowSkip(from: number): number + local r = skip(s, from) + if ind >= 0 and r <= #s and find(sub(s, from, r), "\n", 1, true) and (lineIndent(s, r)) <= ind then + corrupt("a flow collection's line is not indented", r) + end + return r + end + while true do + q = flowSkip(q) + local c = byte(s, q) + if c == nil then + raise("TRUNCATED", "unterminated flow collection", p) + end + if docMarker(s, q) then + corrupt("document marker inside a flow collection", q) + end + if c == close then + q += 1 + break + end + local explicitKey = false + if c == 63 and isWsEnd(byte(s, q + 1)) then + explicitKey = true + q = flowSkip(q + 1) + end + local startLine = q + local k, r, empty = flowNode(st, q, ind) + r = flowSkip(r) + local hasColon = false + if byte(s, r) == 58 then + local d = byte(s, r + 1) + local jsonLike = byte(s, q) == 34 or byte(s, q) == 39 or byte(s, q) == 91 or byte(s, q) == 123 + if isWsEnd(d) or d == 44 or d == 93 or d == 125 or jsonLike then + hasColon = true + -- an implicit key must sit on one line + if not isMap and not explicitKey and find(sub(s, startLine, r), "\n", 1, true) then + corrupt("multi-line implicit key", startLine) + end + r += 1 + end + end + if isMap then + local v: any = st.null + if hasColon then + local r2 = flowSkip(r) + local cc = byte(s, r2) + if cc ~= 44 and cc ~= 125 then + v, r = flowNode(st, r2, ind) + end + end + if empty and not hasColon and not explicitKey then + corrupt("expected a mapping entry", q) + end + k = checkKey(st, k, q) + if t[k] == nil then + table.insert(order, k) + end + t[k] = v + else + local item = k + if hasColon or explicitKey then + local v: any = st.null + local r2 = if hasColon then flowSkip(r) else r + local cc = byte(s, r2) + if hasColon and cc ~= 44 and cc ~= 93 then + v, r = flowNode(st, r2, ind) + end + k = checkKey(st, k, q) + item = Types.object({ [k] = v }, { k }) + elseif empty then + corrupt("empty sequence entry", q) + end + count += 1 + t[count] = item + end + r = flowSkip(r) + local cc = byte(s, r) + if cc == 44 then + q = r + 1 + elseif cc == close then + q = r + 1 + break + elseif cc == nil then + raise("TRUNCATED", "unterminated flow collection", p) + else + corrupt(if isMap then "expected ',' or '}'" else "expected ',' or ']'", r) + end + end + st.depth -= 1 + if isMap then + return Types.object(t, order), q + end + return t, q +end + +-- ------------------------------------------------------------------------------------------------ block +local blockNode: (st: St, ind: number, p: number, inline: boolean, mapParent: boolean) -> (any, number) + +-- implicit key: on one line, followed by ':' and a space or the end of the line +local function implicitKey(st: St, p: number): (any, number?) + local s = st.s + local c = byte(s, p) + if c == 34 or c == 39 then + local ok, t, q = pcall(quoted, st, p, -1) + if not ok then + return nil, nil + end + if find(sub(s, p, q - 1), "\n", 1, true) then + return nil, nil + end + local r = skipLine(s, q) + if byte(s, r) == 58 and isWsEnd(byte(s, r + 1)) then + return t, r + 1 + end + return nil, nil + elseif c == 42 then + local name = match(s, "^%*([^%s,%[%]{}]+)", p) + if not name then + return nil, nil + end + local r = skipLine(s, p + 1 + #name) + if byte(s, r) == 58 and isWsEnd(byte(s, r + 1)) then + return true, r + 1 + end + return nil, nil + elseif c == 91 or c == 123 then + local e = find(s, "\n", p, true) or #s + 1 + local line = sub(s, p, e - 1) + if match(line, "[%]}]%s*:%s") or match(line, "[%]}]%s*:$") then + local ok, _, q = pcall(parseFlow, st, p, -1) + if ok and byte(s, skipLine(s, q)) == 58 then + raise("UNSUPPORTED", "collections as mapping keys", p) + end + end + return nil, nil + end + if c == nil or c == 10 or c == 35 or c == 124 or c == 62 or c == 37 or c == 64 or c == 96 or c == 44 or c == 93 or c == 125 then + return nil, nil + end + if (c == 45 or c == 63 or c == 58) and isWsEnd(byte(s, p + 1)) then + return nil, nil + end + local j = p + while true do + local d = byte(s, j) + if d == nil or d == 10 then + return nil, nil + elseif d == 58 and isWsEnd(byte(s, j + 1)) then + break + elseif d == 35 and (byte(s, j - 1) == 32 or byte(s, j - 1) == 9) then + return nil, nil + end + j += 1 + end + local t = string.gsub(sub(s, p, j - 1), "[ \t]+$", "") + return t, j + 1 +end + +local function readKey(st: St, p: number, props: Props?): (any, number) + local s = st.s + local c = byte(s, p) + local tag = props and props.tag + local k: any + local q: number + if c == 42 then + if props then + corrupt("properties on an alias", p) + end + k, q = alias(st, p) + q = skipLine(s, q) + q += 1 + elseif c == 34 or c == 39 then + local t, r = quoted(st, p, -1) + if find(sub(s, p, r - 1), "\n", 1, true) then + corrupt("multi-line implicit key", p) + end + k = scalarValue(st, t, false, tag, p) + q = skipLine(s, r) + 1 + else + local t, after = implicitKey(st, p) + if t == nil then + corrupt("expected a mapping key", p) + end + k = scalarValue(st, t, true, tag, p) + q = after :: number + end + k = finish(st, props, k) + return checkKey(st, k, p), q +end + +local function nextLineNode(st: St, ind: number, p: number, seqAt: boolean, mapParent: boolean): (any, number) + local s = st.s + local r = skip(s, p) + if r <= #s and not docMarker(s, r) then + local c = col(s, r) + if c > ind or (seqAt and c == ind and byte(s, r) == 45 and isWsEnd(byte(s, r + 1))) then + noTabs(s, r, ind) + return blockNode(st, ind, r, false, mapParent) + end + end + return st.null, p +end + +local function mapValue(st: St, mc: number, p: number, explicit: boolean): (any, number) + local s = st.s + local r = skipLine(s, p) + local cc = byte(s, r) + if cc == nil or cc == 10 or (cc == 35 and r > p) then + return nextLineNode(st, mc, r, true, true) + end + return blockNode(st, mc, r, not explicit, true) +end + +local function blockMap(st: St, mc: number, p: number, firstProps: Props?): (any, number) + local s = st.s + enter(st, p) + local t: { [any]: any } = {} + local order: { any } = {} + local q = p + local first = true + while true do + local props: Props? = nil + if first and firstProps then + props = firstProps + else + props, p = properties(st, p) + end + first = false + local c = byte(s, p) + local k: any + local v: any + if ((c == 63 and not props) or c == 58) and isWsEnd(byte(s, p + 1)) then + -- "? key" (explicit) and ": value" (an empty key) + k = st.null + q = p + if c == 63 then + local r = skipLine(s, p + 1) + local cc = byte(s, r) + if cc == nil or cc == 10 or (cc == 35 and r > p + 1) then + k, q = nextLineNode(st, mc, r, true, false) + else + k, q = blockNode(st, mc, r, false, false) + end + k = checkKey(st, k, p) + local r3 = skip(s, q) + if r3 <= #s and not docMarker(s, r3) and col(s, r3) == mc and byte(s, r3) == 58 and isWsEnd(byte(s, r3 + 1)) then + v, q = mapValue(st, mc, r3 + 1, true) + else + v = st.null + end + else + k = finish(st, props, scalarValue(st, "", true, props and props.tag, p)) + v, q = mapValue(st, mc, p + 1, true) + end + else + local after + k, after = readKey(st, p, props) + v, q = mapValue(st, mc, after, false) + end + if t[k] == nil then + table.insert(order, k) + end + t[k] = v + local r3 = skip(s, q) + if r3 > #s or docMarker(s, r3) then + break + end + local cc3 = col(s, r3) + if cc3 == mc then + noTabs(s, r3) + if byte(s, r3) == 45 and isWsEnd(byte(s, r3 + 1)) then + corrupt("a sequence entry where a mapping key is expected", r3) + end + p = r3 + elseif cc3 < mc then + break + else + corrupt("bad indentation of a mapping entry", r3) + end + end + st.depth -= 1 + return Types.object(t, order), q +end + +local function blockSeq(st: St, sc: number, p: number): (any, number) + local s = st.s + enter(st, p) + local t: { any } = {} + local q = p + while true do + local r = skipLine(s, p + 1) + local c = byte(s, r) + local v: any + if c == nil or c == 10 or (c == 35 and r > p + 1) then + v, q = nextLineNode(st, sc, r, false, false) + else + if find(sub(s, p + 1, r - 1), "\t", 1, true) and (((c == 45 or c == 63 or c == 58) and isWsEnd(byte(s, r + 1))) or implicitKey(st, r) ~= nil) then + corrupt("tab before a compact collection", r) + end + v, q = blockNode(st, sc, r, false, false) + end + table.insert(t, v) + local r3 = skip(s, q) + if r3 > #s or docMarker(s, r3) then + break + end + local cc = col(s, r3) + if cc == sc and byte(s, r3) == 45 and isWsEnd(byte(s, r3 + 1)) then + noTabs(s, r3) + p = r3 + elseif cc <= sc then + break + else + corrupt("bad indentation of a sequence entry", r3) + end + end + st.depth -= 1 + return t, q +end + +local function afterProps(st: St, ind: number, start: number, q: number, props: Props?, inline: boolean, mapParent: boolean): (any, number) + local s = st.s + local tag = props and props.tag + local c = byte(s, q) + if c == 42 then + if props then + corrupt("properties on an alias", q) + end + if implicitKey(st, q) ~= nil then + if inline then + corrupt("a mapping cannot start on its key's line", q) + end + return blockMap(st, col(s, q), q, nil) + end + local v, e = alias(st, q) + if not endOfLine(s, e) then + corrupt("unexpected text after an alias", e) + end + return v, e + end + if c == 45 and isWsEnd(byte(s, q + 1)) then + if inline or props then + corrupt("a sequence cannot start here", q) + end + return blockSeq(st, col(s, q), q) + elseif (c == 63 or c == 58) and isWsEnd(byte(s, q + 1)) then + if inline or (props and c == 63) then + corrupt("a mapping cannot start here", q) + end + return blockMap(st, col(s, start), q, props) + elseif c == 124 or c == 62 then + local text, e = blockScalar(st, q, ind) + return finish(st, props, scalarValue(st, text, false, tag, q)), e + elseif c == 91 or c == 123 then + implicitKey(st, q) -- raises UNSUPPORTED for a flow collection used as a key + local v, e = parseFlow(st, q, ind) + collectionTag(st, tag, if c == 91 then "seq" else "map", q) + if not endOfLine(s, e) then + corrupt("unexpected text after a flow collection", e) + end + return finish(st, props, v), e + end + if implicitKey(st, q) ~= nil then + if inline then + corrupt("a mapping cannot start on its key's line", q) + end + -- properties on the key's line belong to the first key + return blockMap(st, col(s, start), q, props) + end + if c == 34 or c == 39 then + local text, e = quoted(st, q, ind) + if not endOfLine(s, e) then + corrupt("unexpected text after a quoted scalar", e) + end + return finish(st, props, scalarValue(st, text, false, tag, q)), e + end + if c == 35 or c == 37 or c == 64 or c == 96 or c == 44 or c == 93 or c == 125 or c == 38 or c == 33 then + corrupt("unexpected character '" .. char(c :: number) .. "'", q) + end + local text, e = plain(st, q, ind, false) + if not endOfLine(s, e) then + corrupt("unexpected ':' (mapping values are not allowed here)", e) + end + return finish(st, props, scalarValue(st, text, true, tag, q)), e +end + +function blockNode(st: St, ind: number, p: number, inline: boolean, mapParent: boolean): (any, number) + local s = st.s + local props, q = properties(st, p) + if not props then + return afterProps(st, ind, p, q, nil, inline, mapParent) + end + -- properties ending their line apply to the node on the next lines; more properties there merge in, unless + -- they start a mapping key + local c = byte(s, q) + if not (c == nil or c == 10 or (c == 35 and q > p)) then + return afterProps(st, ind, p, q, props, inline, mapParent) + end + while true do + local r = skip(s, q) + if r > #s or docMarker(s, r) then + break + end + local cr = col(s, r) + if not (cr > ind or (mapParent and cr == ind and byte(s, r) == 45 and isWsEnd(byte(s, r + 1)))) then + break + end + noTabs(s, r, ind) + local cc = byte(s, r) + if cc == 38 or cc == 33 then + local p2, q2 = properties(st, r) + local c2 = byte(s, q2) + if c2 == nil or c2 == 10 or (c2 == 35 and q2 > r) then + local pr = props :: Props + if (p2 :: Props).anchor then + if pr.anchor then + corrupt("two anchors on one node", r) + end + pr.anchor = (p2 :: Props).anchor + end + if (p2 :: Props).tag then + if pr.tag then + corrupt("two tags on one node", r) + end + pr.tag = (p2 :: Props).tag + end + q = q2 + continue + end + if implicitKey(st, q2) ~= nil then + local v, e = blockMap(st, cr, r, nil) + collectionTag(st, (props :: Props).tag, "map", r) + return finish(st, props, v), e + end + -- properties then a scalar on the next line: merge + local pr = props :: Props + if (p2 :: Props).anchor and pr.anchor or (p2 :: Props).tag and pr.tag then + corrupt("two anchors or tags on one node", r) + end + pr.anchor = pr.anchor or (p2 :: Props).anchor + pr.tag = pr.tag or (p2 :: Props).tag + return afterProps(st, ind, r, q2, pr, false, mapParent) + end + local tag = (props :: Props).tag + if cc == 45 and isWsEnd(byte(s, r + 1)) then + local v, e = blockSeq(st, cr, r) + collectionTag(st, tag, "seq", r) + return finish(st, props, v), e + elseif ((cc == 63 or cc == 58) and isWsEnd(byte(s, r + 1))) or (cc ~= 91 and cc ~= 123 and implicitKey(st, r) ~= nil) then + local v, e = blockMap(st, cr, r, nil) + collectionTag(st, tag, "map", r) + return finish(st, props, v), e + elseif cc == 42 then + corrupt("properties on an alias", r) + end + return afterProps(st, ind, r, r, props, false, mapParent) + end + return finish(st, props, scalarValue(st, "", true, (props :: Props).tag, q)), q +end + +-- ------------------------------------------------------------------------------------------------ stream +local function stream(st: St): { any } + local s = st.s + local n = #s + local docs = {} + local p = 1 + local needEnd = false -- a bare document after a document must follow "..." or "---" + while true do + p = skip(s, p) + if p > n then + break + end + local sawDirective = false + st.handles = { ["!"] = "!", ["!!"] = CORE } + local yamlSeen = false + while byte(s, p) == 37 and col(s, p) == 0 do -- % + if needEnd then + corrupt("a directive needs '...' after the previous document", p) + end + local e = find(s, "\n", p, true) or n + 1 + local line = string.gsub(sub(s, p, e - 1), "%s+#.*$", "") + local name = match(line, "^%%(%S+)") + if name == "YAML" then + if yamlSeen then + corrupt("two %YAML directives", p) + end + yamlSeen = true + local v = match(line, "^%%YAML[ \t]+(%d+%.%d+)[ \t]*$") + if not v then + corrupt("bad %YAML directive", p) + end + elseif name == "TAG" then + local h, prefix = match(line, "^%%TAG[ \t]+(![%w%-]*!?)[ \t]+(%S+)[ \t]*$") + if not h then + corrupt("bad %TAG directive", p) + end + st.handles[h :: string] = prefix :: string + end + sawDirective = true + p = skip(s, e) + end + local explicit = false + if docMarker(s, p) and sub(s, p, p + 2) == "---" then + explicit = true + p += 3 + elseif sawDirective then + corrupt("directives without '---'", p) + elseif docMarker(s, p) then -- "..." + if not endOfLine(s, p + 3) then + corrupt("text after '...'", p + 3) + end + p += 3 + needEnd = false + continue + elseif needEnd then + corrupt("a second document needs '---'", p) + end + st.anchors = {} + local q = skip(s, p) + local value: any + if q > n or docMarker(s, q) then + value = st.null + p = q + else + if explicit and not find(sub(s, p, q), "\n", 1, true) then + local ok, _, q2 = pcall(properties, st, q) + local c = byte(s, q2) + if ok and c ~= 124 and c ~= 62 and not endOfLine(s, q2) and implicitKey(st, q2) ~= nil then + corrupt("a block mapping cannot start on the '---' line", q) + end + end + value, p = blockNode(st, -1, q, false, false) + local r = skip(s, p) + if r <= n and not docMarker(s, r) then + corrupt("unexpected content after the document", r) + end + p = r + end + table.insert(docs, value) + needEnd = true + if p <= n and docMarker(s, p) and sub(s, p, p + 2) == "..." then + if not endOfLine(s, p + 3) then + corrupt("text after '...'", p + 3) + end + p += 3 + needEnd = false + elseif p <= n and docMarker(s, p) then + needEnd = false + end + end + return docs +end + +function Parse.run(text: string, opts: Options?): (any, any, any, any) + local o: Options = opts or {} + local s = text + if sub(s, 1, 3) == "\239\187\191" then + s = sub(s, 4) + end + if find(s, "\r", 1, true) then + s = string.gsub(string.gsub(s, "\r\n", "\n"), "\r", "\n") + end + local st: St = { + s = s, + n = #s, + anchors = {}, + handles = {}, + depth = 0, + maxDepth = o.maxDepth or 500, + aliasNodes = 0, + maxAlias = o.maxAliasNodes or 1e6, + sizes = setmetatable({}, { __mode = "k" }) :: any, + ignoreTags = o.tags == "ignore", + null = if o.null ~= nil then o.null else Types.null, + } + local ok, res = pcall(stream, st) + if ok then + return res, nil, nil, nil + end + if type(res) == "table" and res.yamlErr then + return nil, res.code, res.msg, res.at + end + local msg = tostring(res) + if string.find(msg, "stack overflow", 1, true) then + return nil, "LIMIT", "nested too deeply", 0 + end + return nil, "CORRUPT", "internal error: " .. msg, 0 +end + +return Parse +end +end + + + + + + font + --!optimize 2 +--!nocheck +-- rosetta chunk font (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 14 modules (0 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["font/bdf"] = function() + +-- font/bdf: Glyph Bitmap Distribution Format 2.1 (and 2.2's METRICSSET 0), read and written, from Adobe's BDF 2.1 +-- spec. ENCODING is Unicode for ISO10646, ISO8859-1 and registry-less fonts; other charsets stay unmapped. Writes +-- Unicode (ISO10646-1) BDF 2.1 from any Font. Not supported: vertical metrics (SWIDTH1 / DWIDTH1 / VVECTOR ignored). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Bitmap = __include("codecs/font/Bitmap") + +-- ------------------------------------------------------------------------------------------------ contract +local Bdf = { + name = "bdf", + category = "font", + extensions = { "bdf" }, + mime = { "application/x-font-bdf" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/font/Bitmap" }, + caps = { decode = true, encode = true, bitmap = true }, +} + +type DecodeOptions = { maxGlyphs: number? } -- default 1114112 +type EncodeOptions = { + px: number?, -- default 16 + chars: (string | { number })?, -- default printable ASCII + name: string?, -- XLFD; default built from the family / style +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Bdf.sniff(r: Bytes.Reader): number + local head = r:peek(32) + return if string.match(head, "^STARTFONT%s+2%.%d") then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function unquote(v: string): any + local s = string.match(v, '^"(.*)"%s*$') + if s then + return (string.gsub(s, '""', '"')) + end + return tonumber(v) or v +end + +local function hexRow(line: string, w: number, row: buffer, rowOff: number) + local n = math.min(#line // 2, math.ceil(w / 8)) + for i = 0, n - 1 do + local v = tonumber(string.sub(line, i * 2 + 1, i * 2 + 2), 16) or 0 + buffer.writeu8(row, rowOff + i, v) + end +end + +function Bdf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + local maxGlyphs = o.maxGlyphs or 1114112 + local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + local lines = string.split(text, "\n") + local props: { [string]: any } = {} + local fontName, size = "", 0 + local fbb = { 0, 0, 0, 0 } + local fontDw = 0 + local glyphs: { Types.BitmapGlyph } = {} + local encodings: { number } = {} + local i = 1 + local n = #lines + local function line(): string + local l = string.gsub(lines[i] or "", "\r$", "") + i += 1 + return l + end + local first = line() + if not string.match(first, "^STARTFONT%s") then + return nil, Err.new(Err.CORRUPT, "no STARTFONT") + end + local ended = false + while i <= n do + local l = line() + local key, rest = string.match(l, "^(%S+)%s*(.*)$") + if key == "FONT" then + fontName = rest :: string + elseif key == "SIZE" then + size = tonumber(string.match(rest :: string, "^(%S+)")) or 0 + elseif key == "FONTBOUNDINGBOX" then + local a, b, c, d = string.match(rest :: string, "^(%-?%d+)%s+(%-?%d+)%s+(%-?%d+)%s+(%-?%d+)") + fbb = { tonumber(a) or 0, tonumber(b) or 0, tonumber(c) or 0, tonumber(d) or 0 } + elseif key == "DWIDTH" then + fontDw = tonumber(string.match(rest :: string, "^(%-?%d+)")) or 0 + elseif key == "STARTPROPERTIES" then + while i <= n do + local pl = line() + if string.match(pl, "^ENDPROPERTIES") then + break + end + local pk, pv = string.match(pl, "^(%S+)%s*(.*)$") + if pk then + props[pk :: string] = unquote(pv :: string) + end + end + elseif key == "STARTCHAR" then + if #glyphs >= maxGlyphs then + return nil, Err.new(Err.LIMIT, "more than maxGlyphs glyphs") + end + local name = rest :: string + local enc = -1 + local dw = fontDw + local bbx = { fbb[1], fbb[2], fbb[3], fbb[4] } + local px: buffer? = nil + while i <= n do + local cl = line() + local ck, cr = string.match(cl, "^(%S+)%s*(.*)$") + if ck == "ENCODING" then + local e1, e2 = string.match(cr :: string, "^(%-?%d+)%s*(%-?%d*)") + enc = tonumber(e1) or -1 + if enc == -1 and e2 and e2 ~= "" then + enc = -(tonumber(e2) or 1) - 1 -- a non-standard code: kept negative (meta.encodings) + end + elseif ck == "DWIDTH" then + dw = tonumber(string.match(cr :: string, "^(%-?%d+)")) or dw + elseif ck == "BBX" then + local a, b, c, d = string.match(cr :: string, "^(%-?%d+)%s+(%-?%d+)%s+(%-?%d+)%s+(%-?%d+)") + bbx = { tonumber(a) or 0, tonumber(b) or 0, tonumber(c) or 0, tonumber(d) or 0 } + elseif ck == "BITMAP" then + local w, h = bbx[1], bbx[2] + if w < 0 or h < 0 or w > 4096 or h > 4096 then + return nil, Err.new(Err.CORRUPT, "bad BBX in " .. name) + end + local stride = math.ceil(w / 8) + local rows = buffer.create(stride * h) + for y = 0, h - 1 do + local rl = string.gsub(lines[i] or "", "%s", "") + if string.match(rl, "^ENDCHAR") then + break + end + i += 1 + hexRow(rl, w, rows, y * stride) + end + px = Bitmap.unpack(rows, 0, w, h, stride) + elseif ck == "ENDCHAR" then + break + end + end + local gl: Types.BitmapGlyph = { + name = name, + codepoint = nil, + width = bbx[1], + height = bbx[2], + left = bbx[3], + top = bbx[4] + bbx[2], + advance = dw, + pixels = px or buffer.create(math.max(0, bbx[1] * bbx[2])), + } + table.insert(glyphs, gl) + table.insert(encodings, enc) + elseif key == "ENDFONT" then + ended = true + break + end + end + if not ended then + return nil, Err.new(Err.TRUNCATED, "no ENDFONT") + end + local registry = if type(props.CHARSET_REGISTRY) == "string" then string.upper(props.CHARSET_REGISTRY) else nil + local cset = if type(props.CHARSET_ENCODING) == "string" or type(props.CHARSET_ENCODING) == "number" then tostring(props.CHARSET_ENCODING) else nil + local unicode = registry == nil or registry == "ISO10646" or (registry == "ISO8859" and cset == "1") + local default: number? = nil + for k, gl in glyphs do + local enc = encodings[k] + if unicode and enc >= 0 then + gl.codepoint = enc + end + if type(props.DEFAULT_CHAR) == "number" and enc == props.DEFAULT_CHAR then + default = k - 1 + end + end + local pixelSize = if type(props.PIXEL_SIZE) == "number" then props.PIXEL_SIZE else (if fbb[2] > 0 then fbb[2] else size) + local strike: Types.BitmapStrike = { + size = pixelSize, + ascent = if type(props.FONT_ASCENT) == "number" then props.FONT_ASCENT else fbb[2] + fbb[4], + descent = if type(props.FONT_DESCENT) == "number" then props.FONT_DESCENT else -fbb[4], + glyphs = glyphs, + default = default, + } + local slant = props.SLANT + local weight = props.WEIGHT_NAME + local style = (if type(weight) == "string" and string.lower(weight) ~= "medium" and string.lower(weight) ~= "regular" then weight else "") + if slant == "I" or slant == "O" then + style = (if style ~= "" then style .. " " else "") .. "Italic" + end + local info = { + family = if type(props.FAMILY_NAME) == "string" then props.FAMILY_NAME else fontName, + style = if style ~= "" then style else "Regular", + fullName = fontName, + } + local font = Bitmap.font(strike, info, { + properties = props, + encodings = encodings, + unicode = unicode, + fontName = fontName, + boundingBox = fbb, + source = { format = "bdf", charset = if registry then registry .. "-" .. tostring(cset) else nil }, + }) + return font, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function quote(s: string): string + return '"' .. string.gsub(s, '"', '""') .. '"' +end + +function Bdf.encode(font: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local strike, err = Bitmap.strike(font, { px = o.px, chars = o.chars }) + if not strike then + return nil, err + end + local info = if type(font.info) == "table" then font.info else {} + local family = string.gsub(tostring(info.family or "rosetta"), "[%-\n\r\"]", " ") + local bold = string.find(string.lower(tostring(info.style or "")), "bold") ~= nil + local italic = string.find(string.lower(tostring(info.style or "")), "italic") ~= nil + local px = strike.size + local x0, y0, x1, y1 = math.huge, math.huge, -math.huge, -math.huge + for _, g in strike.glyphs do + if g.width > 0 and g.height > 0 then + x0 = math.min(x0, g.left) + x1 = math.max(x1, g.left + g.width) + y0 = math.min(y0, g.top - g.height) + y1 = math.max(y1, g.top) + end + end + if x0 == math.huge then + x0, y0, x1, y1 = 0, 0, 0, 0 + end + local name = o.name + or string.format("-rosetta-%s-%s-%s-normal--%d-%d-75-75-c-%d-ISO10646-1", family, if bold then "bold" else "medium", if italic then "i" else "r", px, px * 10, (x1 - x0) * 10) + local out = { + "STARTFONT 2.1", + "FONT " .. name, + string.format("SIZE %d 75 75", px), + string.format("FONTBOUNDINGBOX %d %d %d %d", x1 - x0, y1 - y0, x0, y0), + } + local defaultIndex = (strike.default or 0) + 1 + local props: { { any } } = { + { "FAMILY_NAME", quote(family) }, + { "WEIGHT_NAME", quote(if bold then "Bold" else "Medium") }, + { "SLANT", quote(if italic then "I" else "R") }, + { "PIXEL_SIZE", px }, + { "POINT_SIZE", px * 10 }, + { "RESOLUTION_X", 75 }, + { "RESOLUTION_Y", 75 }, + { "CHARSET_REGISTRY", quote("ISO10646") }, + { "CHARSET_ENCODING", quote("1") }, + { "FONT_ASCENT", strike.ascent }, + { "FONT_DESCENT", strike.descent }, + } + local dg = strike.glyphs[defaultIndex] + if dg and dg.codepoint then + table.insert(props, { "DEFAULT_CHAR", dg.codepoint }) + end + table.insert(out, "STARTPROPERTIES " .. #props) + for _, p in props do + table.insert(out, p[1] .. " " .. tostring(p[2])) + end + table.insert(out, "ENDPROPERTIES") + table.insert(out, "CHARS " .. #strike.glyphs) + for k, g in strike.glyphs do + local gname = g.name or (if g.codepoint then string.format("uni%04X", g.codepoint) else "glyph" .. (k - 1)) + table.insert(out, "STARTCHAR " .. string.gsub(gname, "%s", "_")) + table.insert(out, "ENCODING " .. (if g.codepoint then tostring(g.codepoint) else "-1")) + table.insert(out, string.format("SWIDTH %d 0", math.floor(g.advance * 1000 / math.max(1, px) + 0.5))) + table.insert(out, string.format("DWIDTH %d 0", g.advance)) + table.insert(out, string.format("BBX %d %d %d %d", g.width, g.height, g.left, g.top - g.height)) + table.insert(out, "BITMAP") + local stride = math.ceil(g.width / 8) + local rows = Bitmap.pack(g.pixels, g.width, g.height, stride) + for y = 0, g.height - 1 do + local hex = table.create(stride) + for x = 0, stride - 1 do + hex[x + 1] = string.format("%02X", buffer.readu8(rows, y * stride + x)) + end + table.insert(out, table.concat(hex)) + end + table.insert(out, "ENDCHAR") + end + table.insert(out, "ENDFONT") + return buffer.fromstring(table.concat(out, "\n") .. "\n"), nil +end + +return Bdf +end +__FILES["font/bmfont"] = function() + +-- font/bmfont: AngelCode BMFont descriptors (.fnt: text, XML, binary version 3), read and written, from the BMFont +-- documentation. Pages are image files (meta.pageFiles), loaded lazily; Bmfont.bake renders an outline Font to pages. +-- Not supported: packed multi-channel glyphs (read as alpha). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Parse = __include("font/bmfont/Parse") + +-- ------------------------------------------------------------------------------------------------ contract +local Bmfont = { + name = "bmfont", + category = "font", + extensions = { "fnt" }, + mime = { "application/x-bmfont" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, bitmap = true, variants = { "text", "xml", "binary" }, extraFiles = true }, +} + +type DecodeOptions = { + pages: { Types.Image }?, -- page id 0 first + loadPage: ((file: string, page: number) -> any)?, +} +type EncodeOptions = { + variant: ("text" | "xml" | "binary")?, -- default: the variant it was read from, else "text" + px: number?, + chars: (string | { number })?, + file: string?, -- default: opts.name without its extension, else "font" + name: string?, + files: { [string]: any }?, + encodeImage: ((img: any, format: string) -> (buffer?, any))?, +} +type BakeOptions = { + px: number?, -- default 32 + chars: (string | { number })?, -- default printable ASCII 32..126 + pageSize: number?, -- default: the smallest power of two that fits, up to 4096 + padding: number?, -- default 1 + file: string?, -- default "font"; pages are <file>_<n>.png +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Bmfont.sniff(r: Bytes.Reader): number + local head = r:peek(64) + if string.sub(head, 1, 4) == "BMF\3" then + return 1 + end + if string.match(head, "^info%s+face=") or string.match(head, "^info%s+") and string.find(head, "size=", 1, true) then + return 0.9 + end + if string.find(head, "<font>", 1, true) or (string.find(head, "<?xml", 1, true) and string.find(r:peek(512), "<font>", 1, true)) then + return if string.find(r:peek(512), "<info", 1, true) then 0.9 else 0.3 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local Face = {} +Face.__index = Face + +function Face.glyphIndex(self: any, cp: number): number + return self._index[cp] or 0 +end +function Face.advance(self: any, g: number): number + local c = self._chars[g] + return if c then c.xadvance else 0 +end +function Face.kern(self: any, a: number, b: number): number + local ca, cb = self._chars[a], self._chars[b] + if not ca or not cb then + return 0 + end + return self._kern[ca.id * 2097152 + cb.id] or 0 +end +function Face.outline(_self: any, _g: number): { any }? + return nil +end + +function Face.loadPages(self: any, loader: any?): (boolean?, Err.Err?) + local load = loader or self.meta.pageLoader + if type(load) ~= "function" then + return nil, Err.new(Err.ARG, "no page loader (pass font:loadPages(function(file) return image end))") + end + local pages = {} + for i, file in self.meta.pageFiles do + local ok, img, err = pcall(load, file, i - 1) + if not ok or type(img) ~= "table" or type(img.pixels) ~= "buffer" then + return nil, if Err.is(err) then err else Err.new(Err.IO, "page " .. file .. ": " .. tostring(if ok then err else img)) + end + pages[i] = img + end + self.pages = pages + return true, nil +end + +local CHANNEL = { [1] = 2, [2] = 1, [4] = 0, [8] = 3 } -- chnl bit -> byte in rgba8 + +function Face.rasterize(self: any, g: number, px: number?): Types.Image? + local c = self._chars[g] + if not c then + return nil + end + if not self.pages and self.meta.pageLoader then + self:loadPages() + end + local page = self.pages and self.pages[c.page + 1] + local img = Types.Image.new(c.width, c.height, "alpha8") + img.meta.left = c.xoffset + img.meta.top = (self.meta.base or 0) - c.yoffset + img.meta.advance = c.xadvance + img.meta.glyph = g + img.meta.scale = if type(px) == "number" and self.unitsPerEm > 0 then px / self.unitsPerEm else 1 + if not page then + return nil + end + local pw, ph = page.width, page.height + local bpp = Types.Image.bpp(page.format) or 4 + local ch = if page.format == "rgba8" then CHANNEL[c.chnl] or 3 else 0 + if page.format == "graya8" then + ch = 1 + end + for y = 0, c.height - 1 do + local sy = c.y + y + for x = 0, c.width - 1 do + local sx = c.x + x + if sx >= 0 and sy >= 0 and sx < pw and sy < ph then + buffer.writeu8(img.pixels, y * c.width + x, buffer.readu8(page.pixels, (sy * pw + sx) * bpp + math.min(ch, bpp - 1))) + end + end + end + return img +end + +local function face(d: Parse.Desc, variant: string): any + local f: any = setmetatable({ + kind = "font", + info = { + family = d.info.face, + style = if (d.info.bold or 0) ~= 0 and (d.info.italic or 0) ~= 0 then "Bold Italic" elseif (d.info.bold or 0) ~= 0 then "Bold" elseif (d.info.italic or 0) ~= 0 then "Italic" else "Regular", + fullName = d.info.face, + }, + unitsPerEm = math.abs(d.info.size or 0), + ascent = d.common.base or 0, + descent = (d.common.base or 0) - (d.common.lineHeight or 0), + lineGap = 0, + numGlyphs = #d.chars + 1, + pages = nil, + meta = { + bmfont = d, + variant = variant, + pageFiles = d.pages, + lineHeight = d.common.lineHeight, + base = d.common.base, + source = { format = "bmfont", variant = variant }, + }, + _chars = {}, + _index = {}, + _kern = {}, + }, Face) + for i, c in d.chars do + f._chars[i] = c + if f._index[c.id] == nil then + f._index[c.id] = i + end + end + for _, k in d.kernings do + f._kern[k[1] * 2097152 + k[2]] = k[3] + end + return f +end + +function Bmfont.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local d, err, variant + if r:peek(3) == "BMF" then + d, err = Parse.binary(r:sub(0)) + variant = "binary" + else + local s = r:peek(r:size()) + if string.find(string.sub(s, 1, 512), "<font", 1, true) then + d, err = Parse.xml(s) + variant = "xml" + else + d, err = Parse.text(s) + variant = "text" + end + end + if not d then + return nil, Err.from(err or "bad descriptor", r.base) + end + local f = face(d, variant) + if opts and type(opts.pages) == "table" then + f.pages = opts.pages + end + if opts and type(opts.loadPage) == "function" then + f.meta.pageLoader = opts.loadPage + end + return f, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function validDesc(d: any): boolean + if type(d) ~= "table" or type(d.info) ~= "table" or type(d.common) ~= "table" or type(d.pages) ~= "table" or type(d.chars) ~= "table" or type(d.kernings) ~= "table" then + return false + end + for _, c in d.chars do + for _, k in { "id", "x", "y", "width", "height", "xoffset", "yoffset", "xadvance", "page", "chnl" } do + local v = c[k] + if type(v) ~= "number" or v % 1 ~= 0 then + return false + end + end + if c.id < 0 or c.x < 0 or c.y < 0 or c.width < 0 or c.height < 0 or c.page < 0 or c.page > 255 or c.chnl < 0 or c.chnl > 255 then + return false + end + end + for _, k in d.kernings do + if type(k) ~= "table" or type(k[1]) ~= "number" or type(k[2]) ~= "number" or type(k[3]) ~= "number" then + return false + end + end + for _, p in d.pages do + if type(p) ~= "string" then + return false + end + end + return true +end + +function Bmfont.encode(font: any, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(font) ~= "table" or font.kind ~= "font" then + return nil, Err.new(Err.ARG, "expected a Font") + end + local d = type(font.meta) == "table" and font.meta.bmfont or nil + local pages = font.pages + if d == nil then + local file = opts and opts.file + if file == nil and opts and type(opts.name) == "string" then + file = string.match(opts.name, "([^/\\]-)%.[^./\\]*$") or string.match(opts.name, "([^/\\]+)$") + if file == "" then + file = nil + end + end + local baked, err = Bmfont.bake(font, { px = opts and opts.px, chars = opts and opts.chars, file = file }) + if not baked then + return nil, err + end + d = baked.meta.bmfont + pages = baked.pages + end + if not validDesc(d) then + return nil, Err.new(Err.ARG, "bad BMFont description in font.meta.bmfont") + end + local files = opts and opts.files + local encodeImage = opts and opts.encodeImage + if type(files) == "table" and type(encodeImage) == "function" and type(pages) == "table" then + for i, name in d.pages do + local img = pages[i] + if type(img) == "table" and type(name) == "string" and name ~= "" then + local ext = string.lower(string.match(name, "%.([%w]+)$") or "png") + local bytes, eerr = encodeImage(img, ext) + if not bytes then + return nil, Err.new(Err.ARG, "page " .. (i - 1) .. " (" .. name .. "): " .. tostring(eerr and eerr.message or eerr)) + end + files[name] = bytes + end + end + end + local variant = (opts and opts.variant) or (font.meta and font.meta.variant) or "text" + if variant == "text" then + return buffer.fromstring(Parse.writeText(d)), nil + elseif variant == "xml" then + return buffer.fromstring(Parse.writeXml(d)), nil + elseif variant == "binary" then + return Parse.writeBinary(d), nil + end + return nil, Err.new(Err.ARG, "variant must be text, xml or binary") +end + +-- ------------------------------------------------------------------------------------------------ extras +local function codepoints(chars: any): { number } + local out = {} + if type(chars) == "string" then + for _, c in utf8.codes(chars) do + table.insert(out, c) + end + elseif type(chars) == "table" then + for _, c in chars do + if type(c) == "number" then + table.insert(out, c) + end + end + else + for c = 32, 126 do + table.insert(out, c) + end + end + return out +end + +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: 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: { { cp: number, g: number, img: Types.Image } } = {} + local area = 0 + local seen = {} + for _, cp in codepoints(o.chars) do + local g = (font :: any):glyphIndex(cp) + if (g ~= 0 or cp == 0) and not seen[cp] then + seen[cp] = true + 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: 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 + end + end + local order = table.clone(glyphs) + table.sort(order, function(a: any, b: any): boolean + if a.img.height ~= b.img.height then + return a.img.height > b.img.height + end + return a.cp < b.cp + end) + local ascent = math.ceil(font.ascent * scale) + local lineHeight = math.ceil((font.ascent - font.descent + (font.lineGap or 0)) * scale) + local prefix = o.file or "font" + local d: Parse.Desc = { + info = { + face = font.info and font.info.family or "font", + size = px, + bold = 0, + italic = 0, + charset = "", + unicode = 1, + stretchH = 100, + smooth = 1, + aa = 1, + padding = { 0, 0, 0, 0 }, + spacing = { pad, pad }, + outline = 0, + }, + common = { lineHeight = lineHeight, base = ascent, scaleW = size, scaleH = size, pages = 0, packed = 0, alphaChnl = 0, redChnl = 4, greenChnl = 4, blueChnl = 4 }, + pages = {}, + chars = {}, + kernings = {}, + } + local pages: { Types.Image } = {} + local page: Types.Image? = nil + local x, y, rowH = pad, pad, 0 + local placed: { [number]: Parse.Char } = {} + for _, gl in order do + local w, h = gl.img.width, gl.img.height + if w + 2 * pad > size or h + 2 * pad > size then + return nil, Err.new(Err.LIMIT, "bake: glyph larger than the page") + end + if x + w + pad > size then + x, y, rowH = pad, y + rowH + pad, 0 + end + if not page or y + h + pad > size then + page = Types.Image.new(size, size) + table.insert(pages, page :: Types.Image) + table.insert(d.pages, string.format("%s_%d.png", prefix, #pages - 1)) + x, y, rowH = pad, pad, 0 + end + local pg = page :: Types.Image + for yy = 0, h - 1 do + for xx = 0, w - 1 do + local a = buffer.readu8(gl.img.pixels, yy * w + xx) + buffer.writeu32(pg.pixels, ((y + yy) * size + x + xx) * 4, 0x00FFFFFF + a * 16777216) + end + end + local c: Parse.Char = { + id = gl.cp, + x = x, + y = y, + width = w, + height = h, + xoffset = gl.img.meta.left, + yoffset = ascent - gl.img.meta.top, + xadvance = math.floor(gl.img.meta.advance + 0.5), + page = #pages - 1, + chnl = 15, + } + placed[gl.cp] = c + x += w + pad + rowH = math.max(rowH, h) + end + for _, gl in glyphs do + table.insert(d.chars, placed[gl.cp]) + end + d.common.pages = #pages + if type(font.kern) == "function" then + for _, a in glyphs do + for _, b in glyphs do + local k = font:kern(a.g, b.g) + if k ~= 0 then + local v = math.floor(k * scale + 0.5) + if v ~= 0 then + table.insert(d.kernings, { a.cp, b.cp, v }) + end + end + end + end + end + local f = face(d, "text") + f.pages = pages + return f, nil +end + +return Bmfont +end +__FILES["font/bmfont/Parse"] = function() + +-- font/bmfont/Parse: BMFont text / XML / binary v3 descriptors (angelcode.com/products/bmfont/doc/file_format.html). +local Bytes = __include("core/Bytes") + +local Parse = {} + +type Char = { + id: number, + x: number, + y: number, + width: number, + height: number, + xoffset: number, + yoffset: number, + xadvance: number, + page: number, + chnl: number, +} +type Desc = { + info: { [string]: any }, -- face, size, bold, italic, charset, unicode, stretchH, smooth, aa, padding {4}, spacing {2}, outline + common: { [string]: any }, -- lineHeight, base, scaleW, scaleH, pages, packed, alphaChnl, redChnl, greenChnl, blueChnl + pages: { string }, -- by page id: page id 0 is pages[1] + chars: { Char }, + kernings: { { number } }, -- { first, second, amount } +} + +local LIMIT = 1000000 + +local INFO_NUM = { "size", "bold", "italic", "unicode", "stretchH", "smooth", "aa", "outline" } +local COMMON_NUM = { "lineHeight", "base", "scaleW", "scaleH", "pages", "packed", "alphaChnl", "redChnl", "greenChnl", "blueChnl" } +local CHAR_NUM = { "id", "x", "y", "width", "height", "xoffset", "yoffset", "xadvance", "page", "chnl" } + +local function list(s: string?, n: number): { number } + local out = table.create(n, 0) + if s then + local i = 1 + for v in string.gmatch(s, "-?%d+") do + if i > n then + break + end + out[i] = tonumber(v) or 0 + i += 1 + end + end + return out +end + +local function new(): Desc + return { info = {}, common = {}, pages = {}, chars = {}, kernings = {} } +end + +local function apply(d: Desc, tag: string, a: { [string]: string }): string? + if tag == "info" then + d.info.face = a.face or "" + d.info.charset = a.charset or "" + for _, k in INFO_NUM do + d.info[k] = tonumber(a[k]) or 0 + end + d.info.padding = list(a.padding, 4) + d.info.spacing = list(a.spacing, 2) + elseif tag == "common" then + for _, k in COMMON_NUM do + d.common[k] = tonumber(a[k]) or 0 + end + elseif tag == "page" then + local id = tonumber(a.id) + if not id or id < 0 or id > 4096 or id % 1 ~= 0 then + return "bad page id" + end + d.pages[id + 1] = a.file or "" + elseif tag == "char" then + if #d.chars >= LIMIT then + return "too many chars" + end + local c: any = {} + for _, k in CHAR_NUM do + c[k] = tonumber(a[k]) or 0 + end + table.insert(d.chars, c) + elseif tag == "kerning" then + if #d.kernings >= LIMIT then + return "too many kerning pairs" + end + table.insert(d.kernings, { tonumber(a.first) or 0, tonumber(a.second) or 0, tonumber(a.amount) or 0 }) + end + return nil +end + +local function fill(d: Desc) + for i = 1, #d.pages do + d.pages[i] = d.pages[i] or "" + end +end + +-- ------------------------------------------------------------------------------------------------ text +function Parse.text(s: string): (Desc?, string?) + local d = new() + for line in string.gmatch(s, "[^\r\n]+") do + local tag, rest = string.match(line, "^%s*(%a+)(.*)$") + if tag then + local a: { [string]: string } = {} + -- key=value, key="quoted value" + local i = 1 + 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 :: string, "^%s*([%w_]+)=(%S*)()", i) + if not k2 then + break + end + a[k2] = v2 + i = e2 + end + end + local err = apply(d, tag, a) + if err then + return nil, err + end + end + end + if not d.common.lineHeight then + return nil, "no common line" + end + fill(d) + return d, nil +end + +-- ------------------------------------------------------------------------------------------------ XML +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? + if ENTITIES[e] then + return ENTITIES[e] + end + local n = if string.sub(e, 1, 2) == "#x" then tonumber(string.sub(e, 3), 16) elseif string.sub(e, 1, 1) == "#" then tonumber(string.sub(e, 2)) else nil + if n and n >= 0 and n <= 0x10FFFF then + return utf8.char(n) + end + return nil + end) + ) +end + +function Parse.xml(s: string): (Desc?, string?) + local d = new() + local seenFont = false + for tag, attrs in string.gmatch(s, "<(%a+)([^>]*)>") do + if tag == "font" then + seenFont = true + end + local a: { [string]: string } = {} + 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) + if err then + return nil, err + end + end + if not seenFont or not d.common.lineHeight then + return nil, "not a BMFont XML descriptor" + end + fill(d) + return d, nil +end + +-- ------------------------------------------------------------------------------------------------ binary +function Parse.binary(r: Bytes.Reader): (Desc?, string?) + if not r:match("BMF") then + return nil, "bad signature" + end + local version = r:u8() + if version ~= 3 then + return nil, "unsupported binary version " .. version + end + local d = new() + while not r:eof() do + local kind = r:u8() + local size = r:u32le() + if r.err then + return nil, "truncated block header" + end + local b = r:slice(size) + if r.err then + return nil, "block past the end" + end + if kind == 1 then + d.info.size = b:i16le() + local bits = b:u8() + d.info.smooth = bit32.band(bits, 0x80) ~= 0 and 1 or 0 + d.info.unicode = bit32.band(bits, 0x40) ~= 0 and 1 or 0 + d.info.italic = bit32.band(bits, 0x20) ~= 0 and 1 or 0 + d.info.bold = bit32.band(bits, 0x10) ~= 0 and 1 or 0 + d.info.fixedHeight = bit32.band(bits, 0x08) ~= 0 and 1 or 0 + d.info.charsetId = b:u8() + d.info.charset = "" + d.info.stretchH = b:u16le() + d.info.aa = b:u8() + d.info.padding = { b:u8(), b:u8(), b:u8(), b:u8() } + d.info.spacing = { b:u8(), b:u8() } + d.info.outline = b:u8() + d.info.face = b:cstring() + elseif kind == 2 then + d.common.lineHeight = b:u16le() + d.common.base = b:u16le() + d.common.scaleW = b:u16le() + d.common.scaleH = b:u16le() + d.common.pages = b:u16le() + d.common.packed = if bit32.band(b:u8(), 1) ~= 0 then 1 else 0 + d.common.alphaChnl = b:u8() + d.common.redChnl = b:u8() + d.common.greenChnl = b:u8() + d.common.blueChnl = b:u8() + elseif kind == 3 then + while not b:eof() and #d.pages < 4096 do + table.insert(d.pages, b:cstring()) + end + elseif kind == 4 then + local n = size // 20 + if n > LIMIT then + return nil, "too many chars" + end + for _ = 1, n do + table.insert(d.chars, { + id = b:u32le(), + x = b:u16le(), + y = b:u16le(), + width = b:u16le(), + height = b:u16le(), + xoffset = b:i16le(), + yoffset = b:i16le(), + xadvance = b:i16le(), + page = b:u8(), + chnl = b:u8(), + }) + end + elseif kind == 5 then + local n = size // 10 + if n > LIMIT then + return nil, "too many kerning pairs" + end + for _ = 1, n do + table.insert(d.kernings, { b:u32le(), b:u32le(), b:i16le() }) + end + end + if b.err then + return nil, "truncated block " .. kind + end + end + if not d.common.lineHeight then + return nil, "no common block" + end + return d, nil +end + +-- ------------------------------------------------------------------------------------------------ writers +local function num(v: any): string + return string.format("%d", math.floor(tonumber(v) or 0)) +end + +local function textLines(d: Desc, quote: (string) -> string): { { any } } + local i, c = d.info, d.common + local pad, sp = i.padding or { 0, 0, 0, 0 }, i.spacing or { 0, 0 } + local lines: { { any } } = { + { + "info", + { + { "face", quote(i.face or "") }, + { "size", num(i.size) }, + { "bold", num(i.bold) }, + { "italic", num(i.italic) }, + { "charset", quote(i.charset or "") }, + { "unicode", num(i.unicode) }, + { "stretchH", num(i.stretchH or 100) }, + { "smooth", num(i.smooth) }, + { "aa", num(i.aa) }, + { "padding", table.concat({ num(pad[1]), num(pad[2]), num(pad[3]), num(pad[4]) }, ",") }, + { "spacing", num(sp[1]) .. "," .. num(sp[2]) }, + { "outline", num(i.outline) }, + }, + }, + } + local cf = {} + for _, k in COMMON_NUM do + table.insert(cf, { k, num(c[k]) }) + end + table.insert(lines, { "common", cf }) + return lines +end + +function Parse.writeText(d: Desc): string + local out = {} + local function q(s: string): string + return '"' .. string.gsub(s, '"', "") .. '"' + end + for _, l in textLines(d, q) do + local parts = { l[1] } + for _, kv in l[2] do + table.insert(parts, kv[1] .. "=" .. kv[2]) + end + table.insert(out, table.concat(parts, " ")) + end + for id, file in d.pages do + table.insert(out, string.format('page id=%d file="%s"', id - 1, (string.gsub(file, '"', "")))) + end + table.insert(out, "chars count=" .. #d.chars) + for _, c in d.chars do + local parts = { "char" } + for _, k in CHAR_NUM do + table.insert(parts, k .. "=" .. num((c :: any)[k])) + end + table.insert(out, table.concat(parts, " ")) + end + if #d.kernings > 0 then + table.insert(out, "kernings count=" .. #d.kernings) + for _, k in d.kernings do + table.insert(out, string.format("kerning first=%s second=%s amount=%s", num(k[1]), num(k[2]), num(k[3]))) + end + end + return table.concat(out, "\n") .. "\n" +end + +local function esc(s: string): string + return (string.gsub(s, '[&<>"]', { ["&"] = "&amp;", ["<"] = "&lt;", [">"] = "&gt;", ['"'] = "&quot;" })) +end + +function Parse.writeXml(d: Desc): string + local out = { '<?xml version="1.0"?>', "<font>" } + for _, l in textLines(d, function(s: string): string + return s + end) do + local parts = { " <" .. l[1] } + for _, kv in l[2] do + table.insert(parts, kv[1] .. '="' .. esc(kv[2]) .. '"') + end + table.insert(out, table.concat(parts, " ") .. "/>") + end + table.insert(out, " <pages>") + for id, file in d.pages do + table.insert(out, string.format(' <page id="%d" file="%s"/>', id - 1, esc(file))) + end + table.insert(out, " </pages>") + table.insert(out, string.format(' <chars count="%d">', #d.chars)) + for _, c in d.chars do + local parts = { " <char" } + for _, k in CHAR_NUM do + table.insert(parts, k .. '="' .. num((c :: any)[k]) .. '"') + end + table.insert(out, table.concat(parts, " ") .. "/>") + end + table.insert(out, " </chars>") + if #d.kernings > 0 then + table.insert(out, string.format(' <kernings count="%d">', #d.kernings)) + for _, k in d.kernings do + table.insert(out, string.format(' <kerning first="%s" second="%s" amount="%s"/>', num(k[1]), num(k[2]), num(k[3]))) + end + table.insert(out, " </kernings>") + end + table.insert(out, "</font>") + return table.concat(out, "\n") .. "\n" +end + +function Parse.writeBinary(d: Desc): buffer + local w = Bytes.writer(64 + #d.chars * 20 + #d.kernings * 10) + w:string("BMF") + w:u8(3) + local i, c = d.info, d.common + local face = i.face or "" + w:u8(1) + w:u32le(14 + #face + 1) + w:u16le((tonumber(i.size) or 0) % 65536) + local bits = 0 + if (tonumber(i.smooth) or 0) ~= 0 then + bits += 0x80 + end + if (tonumber(i.unicode) or 0) ~= 0 then + bits += 0x40 + end + if (tonumber(i.italic) or 0) ~= 0 then + bits += 0x20 + end + if (tonumber(i.bold) or 0) ~= 0 then + bits += 0x10 + end + if (tonumber(i.fixedHeight) or 0) ~= 0 then + bits += 0x08 + end + w:u8(bits) + w:u8(tonumber(i.charsetId) or 0) + w:u16le(tonumber(i.stretchH) or 100) + w:u8(tonumber(i.aa) or 1) + local pad, sp = i.padding or { 0, 0, 0, 0 }, i.spacing or { 0, 0 } + for k = 1, 4 do + w:u8(pad[k] or 0) + end + w:u8(sp[1] or 0) + w:u8(sp[2] or 0) + w:u8(tonumber(i.outline) or 0) + w:cstring(face) + w:u8(2) + w:u32le(15) + for _, k in { "lineHeight", "base", "scaleW", "scaleH", "pages" } do + w:u16le((tonumber(c[k]) or 0) % 65536) + end + w:u8(if (tonumber(c.packed) or 0) ~= 0 then 1 else 0) + for _, k in { "alphaChnl", "redChnl", "greenChnl", "blueChnl" } do + w:u8(tonumber(c[k]) or 0) + end + if #d.pages > 0 then + local len = 0 + for _, p in d.pages do + len += #p + 1 + end + w:u8(3) + w:u32le(len) + for _, p in d.pages do + w:cstring(p) + end + end + w:u8(4) + w:u32le(#d.chars * 20) + for _, ch in d.chars do + w:u32le(ch.id) + w:u16le(ch.x) + w:u16le(ch.y) + w:u16le(ch.width) + w:u16le(ch.height) + w:u16le(ch.xoffset % 65536) + w:u16le(ch.yoffset % 65536) + w:u16le(ch.xadvance % 65536) + w:u8(ch.page) + w:u8(ch.chnl) + end + if #d.kernings > 0 then + w:u8(5) + w:u32le(#d.kernings * 10) + for _, k in d.kernings do + w:u32le(k[1]) + w:u32le(k[2]) + w:u16le(k[3] % 65536) + end + end + return w:finish() +end + +return Parse +end +__FILES["font/eot"] = function() + +-- font/eot: Embedded OpenType (versions 0x00010000, 0x00020001, 0x00020002; W3C EOT submission, 2008): the header +-- and the font data (XOR-0x50 obfuscated or not) through codecs/font/TrueType; writes EOT 2.1 around TrueType bytes. +-- Not supported: MicroType Express compression (flag 0x4: Err.UNSUPPORTED), signatures. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Text = __include("codecs/text/Text") +local TrueType = __include("codecs/font/TrueType") + +-- ------------------------------------------------------------------------------------------------ contract +local Eot = { + name = "eot", + category = "font", + extensions = { "eot" }, + mime = { "application/vnd.ms-fontobject" }, + deps = { "core/Err", "core/Bytes", "codecs/text/Text", "codecs/font/TrueType" }, + caps = { decode = true, encode = true, variants = { "1.0", "2.1", "2.2" } }, +} + +type DecodeOptions = {} +type EncodeOptions = { + xor: boolean?, -- XOR 0x50; default false + rootString: string?, -- default "" +} + +-- ------------------------------------------------------------------------------------------------ constants +local MAGIC = 0x504C +local COMPRESSED, XOR = 0x4, 0x10000000 + +-- ------------------------------------------------------------------------------------------------ sniff +function Eot.sniff(r: Bytes.Reader): number + local h = r:peek(36) + if #h < 36 then + return 0 + end + local ver = string.sub(h, 9, 12) + local magic = string.byte(h, 35) + string.byte(h, 36) * 256 + if magic == MAGIC and (ver == "\0\0\1\0" or ver == "\1\0\2\0" or ver == "\2\0\2\0") then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Eot.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local eotSize, dataSize, version, flags = r:u32le(), r:u32le(), r:u32le(), r:u32le() + local panose = r:string(10) + local charset, italic = r:u8(), r:u8() + local weight = r:u32le() + local fsType, magic = r:u16le(), r:u16le() + local ranges = { r:u32le(), r:u32le(), r:u32le(), r:u32le() } + local codepages = { r:u32le(), r:u32le() } + local checksum = r:u32le() + r:skip(16) + if r.err then + return nil, r.err + end + if magic ~= MAGIC then + return nil, Err.new(Err.CORRUPT, "bad magic number") + end + if version ~= 0x00010000 and version ~= 0x00020001 and version ~= 0x00020002 then + return nil, Err.new(Err.UNSUPPORTED, string.format("version 0x%08x", version)) + end + local function name(): string + r:skip(2) + local n = r:u16le() + local s = r:bytes(n) + return Text.utf16(s, 0, buffer.len(s)) + end + local eot: { [string]: any } = { + version = version, + flags = flags, + panose = panose, + charset = charset, + italic = italic ~= 0, + weight = weight, + fsType = fsType, + unicodeRange = ranges, + codePageRange = codepages, + checkSumAdjustment = checksum, + eotSize = eotSize, + } + eot.familyName, eot.styleName, eot.versionName, eot.fullName = name(), name(), name(), name() + if version >= 0x00020001 then + eot.rootString = name() + end + if version == 0x00020002 then + eot.rootStringChecksum = r:u32le() + eot.eudcCodePage = r:u32le() + r:skip(2) + r:skip(r:u16le()) -- signature + eot.eudcFlags = r:u32le() + r:skip(r:u32le()) -- EUDC font data + end + if r.err then + return nil, r.err + end + if bit32.band(flags, COMPRESSED) ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "MicroType Express compressed font data") + end + local data = r:bytes(dataSize) + if r.err then + return nil, r.err + end + if bit32.band(flags, XOR) ~= 0 then + for i = 0, dataSize - 1 do + buffer.writeu8(data, i, bit32.bxor(buffer.readu8(data, i), 0x50)) + end + end + local font, ferr = TrueType.font(data) + if not font then + return nil, ferr + end + font.meta.eot = eot + font.meta.fontData = data + font.meta.source = { format = "eot", version = version, outlines = font.meta.outlines } + return font, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function utf16(s: string): string + local out = {} + if utf8.len(s) then + for _, c in utf8.codes(s) do + if c >= 0x10000 then + c -= 0x10000 + local hi, lo = 0xD800 + bit32.rshift(c, 10), 0xDC00 + bit32.band(c, 0x3FF) + table.insert(out, string.char(hi % 256, hi // 256, lo % 256, lo // 256)) + else + table.insert(out, string.char(c % 256, c // 256)) + end + end + end + return table.concat(out) +end + +function Eot.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local data: buffer + if type(value) == "buffer" then + data = value + elseif type(value) == "string" then + data = buffer.fromstring(value) + elseif type(value) == "table" and type(value.meta) == "table" and type(value.meta.fontData) == "buffer" then + data = value.meta.fontData + else + return nil, Err.new(Err.ARG, "expected TrueType bytes (or a Font read from an EOT)") + end + local font, ferr = TrueType.font(data) + if not font then + return nil, ferr + end + local tables: { [string]: { number } } = TrueType.tables(data, 0, 0, buffer.len(data)) or {} + local function tab(tagName: string): Bytes.Reader? + local t: { number }? = tables[tagName] + return if t then Bytes.reader(data, t[1], t[2]) else nil + end + -- OS/2: PANOSE, weight, fsType, ranges, selection; head: checkSumAdjustment + local panose, weight, fsType, italic, charset = string.rep("\0", 10), 400, 0, 0, 1 + local ranges, codepages = { 0, 0, 0, 0 }, { 0, 0 } + local os2 = tab("OS/2") + if os2 then + os2:seek(4) + weight = os2:u16be() + os2:seek(8) + fsType = os2:u16be() + os2:seek(32) + panose = os2:string(10) + ranges = { os2:u32be(), os2:u32be(), os2:u32be(), os2:u32be() } + os2:seek(62) + local sel = os2:u16be() + italic = if bit32.band(sel, 1) ~= 0 then 1 else 0 + os2:seek(78) + codepages = { os2:u32be(), os2:u32be() } + if os2.err then + codepages = { 0, 0 } + end + end + local head = tab("head") + local checksum = 0 + if head then + head:seek(8) + checksum = head:u32be() + end + local info = font.info or {} + local names = { info.family or "", info.style or "", info.version or "", info.fullName or "" } + local w = Bytes.writer(buffer.len(data) + 512) + w:u32le(0) -- EOTSize, patched + w:u32le(buffer.len(data)) + w:u32le(0x00020001) + w:u32le(if o.xor then XOR else 0) + w:string(panose) + w:u8(charset) + w:u8(italic) + w:u32le(weight) + w:u16le(fsType) + w:u16le(MAGIC) + for _, v in ranges do + w:u32le(v) + end + for _, v in codepages do + w:u32le(v) + end + w:u32le(checksum) + w:string(string.rep("\0", 16)) + for _, s in names do + local u = utf16(tostring(s)) + w:u16le(0) + w:u16le(#u) + w:string(u) + end + local root = utf16(o.rootString or "") + w:u16le(0) + w:u16le(#root) + w:string(root) + local start = w:tell() + w:bytes(data) + local out = w:finish() + if o.xor then + for i = start, start + buffer.len(data) - 1 do + buffer.writeu8(out, i, bit32.bxor(buffer.readu8(out, i), 0x50)) + end + end + buffer.writeu32(out, 0, buffer.len(out)) + return out, nil +end + +return Eot +end +__FILES["font/fon"] = function() + +-- font/fon: Windows raster fonts: .fnt resources (versions 2.0 / 3.0) and .fon NE / PE executables holding them as +-- RT_FONT, from Microsoft's KB65123 and the NE / PE resource layouts; ANSI charset maps through Windows-1252. +-- Not supported: vector FNT (Err.UNSUPPORTED), writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Text = __include("codecs/text/Text") +local Bitmap = __include("codecs/font/Bitmap") + +-- ------------------------------------------------------------------------------------------------ contract +local Fon = { + name = "fon", + category = "font", + extensions = { "fon", "fnt" }, + mime = { "application/x-font-fnt" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Text", "codecs/font/Bitmap" }, + caps = { decode = true, encode = false, bitmap = true, variants = { "fnt2", "fnt3", "ne", "pe" } }, +} + +type DecodeOptions = { size: number? } -- default: the first strike + +-- ------------------------------------------------------------------------------------------------ sniff +local function isFnt(h: string): boolean + if #h < 4 then + return false + end + local ver = string.byte(h, 1) + string.byte(h, 2) * 256 + return ver == 0x200 or ver == 0x300 +end + +function Fon.sniff(r: Bytes.Reader): number + local h = r:peek(64) + if string.sub(h, 1, 2) == "MZ" and #h >= 64 then + local lfanew = string.byte(h, 61) + string.byte(h, 62) * 256 + string.byte(h, 63) * 65536 + local sig = r:peek(2, lfanew) + return if sig == "NE" then 0.6 elseif sig == "PE" then 0.2 else 0 + end + if isFnt(h) and #h >= 6 then + local size = string.byte(h, 3) + string.byte(h, 4) * 256 + string.byte(h, 5) * 65536 + string.byte(h, 6) * 16777216 + return if size == r:size() then 0.9 elseif size <= r:size() and size > 118 then 0.3 else 0 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function fnt(r: Bytes.Reader): (any, Err.Err?) + local version = r:u16le() + local total = r:u32le() + local copyright = string.match(r:string(60), "^[^%z]*") or "" + local ftype = r:u16le() + local points, vres, hres = r:u16le(), r:u16le(), r:u16le() + local ascent = r:u16le() + r:skip(4) -- internal / external leading + local italic = r:u8() + r:skip(2) + local weight = r:u16le() + local charset = r:u8() + local pixWidth, pixHeight = r:u16le(), r:u16le() + r:skip(5) -- pitch and family, average / max width + local first, last, default = r:u8(), r:u8(), r:u8() + r:skip(1 + 2 + 4) + local faceAt = r:u32le() + if r.err then + return nil, r.err + end + if version ~= 0x200 and version ~= 0x300 then + return nil, Err.new(Err.CORRUPT, "not a FNT resource") + end + if bit32.band(ftype, 1) ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "vector fonts") + end + if last < first or pixHeight == 0 or pixHeight > 1024 then + return nil, Err.new(Err.CORRUPT, "bad character range or height") + end + r:seek(if version == 0x300 then 148 else 118) + local glyphs: { Types.BitmapGlyph } = {} + for c = first, last do + local w = r:u16le() + local off = if version == 0x300 then r:u32le() else r:u16le() + if r.err then + return nil, r.err + end + if w > 4096 then + return nil, Err.new(Err.CORRUPT, "bad glyph width") + end + -- column-major: byte column k holds pixels 8k .. 8k + 7 of every row + local h = pixHeight + local px = buffer.create(w * h) + local cols = math.ceil(w / 8) + local base = r.base + off + local limit = r.base + r:size() + for k = 0, cols - 1 do + for y = 0, h - 1 do + local p = base + k * h + y + if p >= 0 and p < limit then + local byte = buffer.readu8(r.buf, p) + for b = 0, 7 do + local x = k * 8 + b + if x < w and bit32.band(byte, bit32.rshift(0x80, b)) ~= 0 then + buffer.writeu8(px, y * w + x, 255) + end + end + end + end + end + local cp: number? = nil + if charset == 0 then + cp = if c >= 0x80 and c < 0xA0 then Text.CP1252[c] else c + elseif c < 0x80 then + cp = c + end + table.insert(glyphs, { codepoint = cp, width = w, height = h, left = 0, top = ascent, advance = w, pixels = px }) + end + local face = "" + if faceAt > 0 and faceAt < r:size() then + face = r:sub(faceAt):cstring(256) + end + local dflt = default + first + local strike: Types.BitmapStrike = { + size = pixHeight, + ascent = ascent, + descent = pixHeight - ascent, + glyphs = glyphs, + default = if dflt >= first and dflt <= last then dflt - first else nil, + } + local style = (if weight >= 600 then "Bold" else "") .. (if italic ~= 0 then " Italic" else "") + style = string.gsub(style, "^ ", "") + return Bitmap.font(strike, { family = face, style = if style ~= "" then style else "Regular", fullName = face }, { + copyright = copyright, + points = points, + resolution = { hres, vres }, + charset = charset, + weight = weight, + pixWidth = pixWidth, + firstChar = first, + source = { format = "fon", version = if version == 0x300 then 3 else 2, size = total }, + }), nil +end + +local function neFonts(r: Bytes.Reader, ne: number): ({ { number } }?, string?) + local rt = r:sub(ne + 0x24, 2):u16le() + local t = r:sub(ne + rt) + local shift = t:u16le() + if shift > 16 then + return nil, "bad resource alignment" + end + local out = {} + for _ = 1, 64 do + local typeId = t:u16le() + if typeId == 0 or t.err then + break + end + local count = t:u16le() + t:skip(4) + for _ = 1, count do + local off, len = t:u16le(), t:u16le() + t:skip(8) + if typeId == 0x8008 then + table.insert(out, { off * 2 ^ shift, len * 2 ^ shift }) + end + end + end + if t.err then + return nil, "truncated resource table" + end + return out, nil +end + +-- RT_FONT: resource type 8 +local function peFonts(r: Bytes.Reader, pe: number): ({ { number } }?, string?) + local h = r:sub(pe + 4, 20) + h:skip(2) + local nsec = h:u16le() + h:skip(12) + local optSize = h:u16le() + local opt = r:sub(pe + 24, optSize) + local magic = opt:u16le() + local ddAt = if magic == 0x20B then 112 else 96 + opt:seek(ddAt + 2 * 8) + local rsrcRva = opt:u32le() + if opt.err or rsrcRva == 0 then + return {}, nil + end + local secs = r:sub(pe + 24 + optSize, nsec * 40) + local base, rva0 = -1, 0 + for _ = 1, nsec do + secs:skip(8) + local vsize, va, rawSize, rawAt = secs:u32le(), secs:u32le(), secs:u32le(), secs:u32le() + secs:skip(16) + if rsrcRva >= va and rsrcRva < va + math.max(vsize, rawSize) then + base, rva0 = rawAt + (rsrcRva - va), va - rawAt + end + end + if base < 0 then + return nil, "no resource section" + end + local out = {} + local function dir(at: number, depth: number, isFont: boolean) + if depth > 3 then + return + end + local d = r:sub(base + at, 16) + d:skip(12) + local named, ids = d:u16le(), d:u16le() + local e = r:sub(base + at + 16, (named + ids) * 8) + for _ = 1, math.min(named + ids, 512) do + local id, target = e:u32le(), e:u32le() + if e.err then + return + end + if depth == 0 and id ~= 8 then + continue + end + if bit32.band(target, 0x80000000) ~= 0 then + dir(bit32.band(target, 0x7FFFFFFF), depth + 1, isFont or depth == 0) + elseif isFont then + local leaf = r:sub(base + target, 8) + local dataRva, size = leaf:u32le(), leaf:u32le() + table.insert(out, { dataRva - rva0, size }) + end + end + end + dir(0, 0, false) + return out, nil +end + +function Fon.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + local list: { { number } } + if r:peek(2) == "MZ" then + local lfanew = r:sub(0x3C, 4):u32le() + local sig = r:peek(2, lfanew) + local l, err + if sig == "NE" then + l, err = neFonts(r, lfanew) + elseif sig == "PE" then + l, err = peFonts(r, lfanew) + else + return nil, Err.new(Err.CORRUPT, "an MZ file without an NE / PE header") + end + if not l then + return nil, Err.from(err) + end + list = l + else + if r:size() < 118 then + return nil, Err.new(Err.TRUNCATED, "shorter than a FNT header") + end + list = { { 0, r:size() } } + end + local fonts: { any } = {} + local firstErr: Err.Err? = nil + for _, res in list do + if res[1] + 118 <= r:size() then + local f, err = fnt(r:sub(res[1], res[2])) + if f then + table.insert(fonts, f) + else + firstErr = firstErr or err + end + end + end + if #fonts == 0 then + return nil, firstErr or Err.new(Err.CORRUPT, "no font resources") + end + local pick = fonts[1] + if type(o.size) == "number" then + for _, f in fonts do + if math.abs(f.unitsPerEm - o.size) < math.abs(pick.unitsPerEm - o.size) then + pick = f + end + end + end + pick.meta.strikes = fonts + return pick, nil +end + +return Fon +end +__FILES["font/hershey"] = function() + +-- font/hershey: Hershey vector fonts, JHF layout (5-column id, 3-column vertex count, extents, vertices as character +-- pairs offset by "R", " R" lifts the pen; records continue over 72-column lines). Units: unitsPerEm 32, y up. +-- Not supported: writing, .hmp index files, filled rendering. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Raster = __include("codecs/image/Raster") + +-- ------------------------------------------------------------------------------------------------ contract +local Hershey = { + name = "hershey", + category = "font", + extensions = { "jhf" }, + mime = { "application/x-hershey-font" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Raster" }, + caps = { decode = true, encode = false, strokes = true }, +} + +type DecodeOptions = { + map: ("ascii" | "id")?, -- default "ascii" + strokeWidth: number?, -- font units; default 2 + maxGlyphs: number?, -- default 65536 +} + +-- ------------------------------------------------------------------------------------------------ constants +local BASELINE = 9 -- the Hershey y of the Roman fonts' baseline (y grows downwards) + +-- ------------------------------------------------------------------------------------------------ sniff +-- the first record: 5-digit id, 3-digit count, then coordinate characters in " " .. "~" (the pen-up pair " R") +local function header(line: string): (number?, number?) + if #line < 10 then + return nil, nil + end + local id = tonumber((string.gsub(string.sub(line, 1, 5), "^%s+", ""))) + local n = tonumber((string.gsub(string.sub(line, 6, 8), "^%s+", ""))) + if not id or not n or n < 1 or string.find(string.sub(line, 1, 8), "[^%d ]") then + return nil, nil + end + return id, n +end + +function Hershey.sniff(r: Bytes.Reader): number + local head = r:peek(256) + local line = string.match(head, "^([^\r\n]*)") + local id, n = header(line or "") + if not id or not n then + return 0 + end + local body = string.sub(line :: string, 9) + if string.find(body, "[^ -~]") then + return 0 + end + return if #body == math.min(2 * n, 64) or #body == 2 * n then 0.7 else 0.3 +end + +-- ------------------------------------------------------------------------------------------------ decode +type Glyph = { id: number, left: number, right: number, cmds: { any } } + +local Face = {} +Face.__index = Face + +function Face.glyphIndex(self: any, cp: number): number + return self._index[cp] or 0 +end + +function Face.advance(self: any, g: number): number + local gl = self._glyphs[g + 1] + return if gl then gl.right - gl.left else 0 +end + +function Face.kern(_self: any, _a: number, _b: number): number + return 0 +end + +function Face.outline(self: any, g: number): { any }? + local gl = self._glyphs[g + 1] + if not gl then + return nil + end + local out = table.create(#gl.cmds) + for i, c in gl.cmds do + out[i] = table.clone(c) + end + return out +end + +function Face.rasterize(self: any, g: number, px: number): Types.Image? + local gl = self._glyphs[g + 1] + if not gl or type(px) ~= "number" or not (px > 0) or px > 4096 then + return nil + end + local s = px / self.unitsPerEm + local stroke = Raster.stroke(gl.cmds, { width = self.meta.strokeWidth, join = "round", cap = "round" }) + local m = Raster.mask(stroke, { transform = { s, 0, 0, -s, 0, 0 }, maxPixels = 2 ^ 24 }) + local img + if m then + img = Types.Image.new(m.width, m.height, "alpha8") + buffer.copy(img.pixels, 0, m.coverage) + img.meta.left = m.x + img.meta.top = -m.y + else + img = Types.Image.new(0, 0, "alpha8") + img.meta.left, img.meta.top = 0, 0 + end + img.meta.advance = (gl.right - gl.left) * s + img.meta.glyph = g + return img +end + +function Hershey.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + local maxGlyphs = o.maxGlyphs or 65536 + local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + local lines = string.split((string.gsub(text, "\r", "")), "\n") + local glyphs: { Glyph } = {} + local i = 1 + while i <= #lines do + local line = lines[i] + i += 1 + if string.match(line, "^%s*$") then + continue + end + local id, n = header(line) + if not id or not n then + return nil, Err.new(Err.CORRUPT, "bad record header on line " .. (i - 1)) + end + local data = string.sub(line, 9) + while #data < 2 * n and i <= #lines do + data ..= lines[i] + i += 1 + end + if #data < 2 * n then + return nil, Err.new(Err.TRUNCATED, "glyph " .. id .. " has fewer vertices than its count") + end + if #glyphs >= maxGlyphs then + return nil, Err.new(Err.LIMIT, "more than maxGlyphs glyphs") + end + local left = string.byte(data, 1) - 82 + local right = string.byte(data, 2) - 82 + local cmds: { any } = {} + local pen = false + for k = 1, n - 1 do + local a, b = string.byte(data, 2 * k + 1), string.byte(data, 2 * k + 2) + if a == 32 and b == 82 then + pen = false + else + local x, y = a - 82 - left, BASELINE - (b - 82) + local cmd: any = { op = if pen then "lineTo" else "moveTo" } + cmd[1], cmd[2] = x, y + table.insert(cmds, cmd) + pen = true + end + end + table.insert(glyphs, { id = id, left = left, right = right, cmds = cmds }) + end + if #glyphs == 0 then + return nil, Err.new(Err.CORRUPT, "no glyphs") + end + local index: { [number]: number } = {} + local byId = o.map == "id" + for k, g in glyphs do + local cp = if byId then g.id else 31 + k + if index[cp] == nil then + index[cp] = k - 1 + end + end + local font = setmetatable({ + kind = "font", + info = { family = "Hershey", style = "Regular" }, + unitsPerEm = 32, + ascent = 21, + descent = -7, + lineGap = 4, + numGlyphs = #glyphs, + meta = { + strokes = true, + strokeWidth = o.strokeWidth or 2, + ids = table.create(#glyphs, 0), + source = { format = "hershey", map = if byId then "id" else "ascii" }, + }, + _glyphs = glyphs, + _index = index, + }, Face) + for k, g in glyphs do + font.meta.ids[k] = g.id + end + return font, nil +end + +return Hershey +end +__FILES["font/pcf"] = function() + +-- font/pcf: X11 Portable Compiled Format bitmap fonts, from the PCF description in libXfont / FreeType's pcf driver +-- docs (no code copied); code points as font/bdf. Not supported: writing, INK_METRICS. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Bitmap = __include("codecs/font/Bitmap") + +-- ------------------------------------------------------------------------------------------------ contract +local Pcf = { + name = "pcf", + category = "font", + extensions = { "pcf" }, + mime = { "application/x-font-pcf" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/font/Bitmap" }, + caps = { decode = true, encode = false, bitmap = true }, +} + +type DecodeOptions = { maxGlyphs: number? } -- default 1114112 + +-- ------------------------------------------------------------------------------------------------ constants +local PROPERTIES, ACCELERATORS, METRICS, BITMAPS = 1, 2, 4, 8 +local BDF_ENCODINGS, SWIDTHS, GLYPH_NAMES, BDF_ACCELERATORS = 32, 64, 128, 256 +local COMPRESSED = 0x100 + +-- ------------------------------------------------------------------------------------------------ sniff +function Pcf.sniff(r: Bytes.Reader): number + return if r:peek(4) == "\1fcp" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +type Table = { format: number, size: number, offset: number } + +type TR = { r: Bytes.Reader, format: number, big: boolean } + +local function open(r: Bytes.Reader, t: Table?): TR? + if not t or t.offset + 4 > r:size() then + return nil + end + local s = r:sub(t.offset, t.size) + local format = s:u32le() + return { r = s, format = format, big = bit32.band(format, 4) ~= 0 } +end + +local function u32(t: TR): number + return if t.big then t.r:u32be() else t.r:u32le() +end +local function i32(t: TR): number + return if t.big then t.r:i32be() else t.r:i32le() +end +local function i16(t: TR): number + return if t.big then t.r:i16be() else t.r:i16le() +end +local function u16(t: TR): number + return if t.big then t.r:u16be() else t.r:u16le() +end + +local REV = buffer.create(256) +for i = 0, 255 do + local v, rv = i, 0 + for _ = 1, 8 do + rv = rv * 2 + v % 2 + v //= 2 + end + buffer.writeu8(REV, i, rv) +end + +function Pcf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + local maxGlyphs = o.maxGlyphs or 1114112 + if r:string(4) ~= "\1fcp" then + return nil, Err.new(if r.err then Err.TRUNCATED else Err.CORRUPT, "not a PCF file") + end + local count = r:u32le() + if count > 64 then + return nil, Err.new(Err.CORRUPT, "too many tables") + end + local tables: { [number]: Table } = {} + for _ = 1, count do + local ty, format, size, offset = r:u32le(), r:u32le(), r:u32le(), r:u32le() + tables[ty] = { format = format, size = size, offset = offset } + end + if r.err then + return nil, r.err + end + local props: { [string]: any } = {} + local pt = open(r, tables[PROPERTIES]) + if pt then + local n = i32(pt) + if n < 0 or n > 4096 then + return nil, Err.new(Err.CORRUPT, "bad property count") + end + local raw = {} + for k = 1, n do + raw[k] = { i32(pt), pt.r:u8(), i32(pt) } + end + if n % 4 ~= 0 then + pt.r:skip(4 - n % 4) + end + local strSize = i32(pt) + local strAt = pt.r:tell() + local function str(off: number): string + if off < 0 or off >= strSize then + return "" + end + local s = pt.r:sub(strAt + off, strSize - off) + return s:cstring() + end + for _, p in raw do + props[str(p[1])] = if p[2] ~= 0 then str(p[3]) else p[3] + end + if pt.r.err then + return nil, Err.new(Err.TRUNCATED, "properties table") + end + end + local ascent: number?, descent: number? = nil, nil + local at = open(r, tables[BDF_ACCELERATORS] or tables[ACCELERATORS]) + if at then + at.r:skip(8) + ascent, descent = i32(at), i32(at) + end + local mt = open(r, tables[METRICS]) + if not mt then + return nil, Err.new(Err.CORRUPT, "no METRICS table") + end + local metrics = {} + local compressed = bit32.band(mt.format, COMPRESSED) ~= 0 + local nm = if compressed then u16(mt) else u32(mt) + if nm > maxGlyphs then + return nil, Err.new(Err.LIMIT, "more than maxGlyphs glyphs") + end + for k = 1, nm do + if compressed then + local b = mt.r + metrics[k] = { b:u8() - 0x80, b:u8() - 0x80, b:u8() - 0x80, b:u8() - 0x80, b:u8() - 0x80 } + else + metrics[k] = { i16(mt), i16(mt), i16(mt), i16(mt), i16(mt) } + mt.r:skip(2) + end + end + if mt.r.err then + return nil, Err.new(Err.TRUNCATED, "metrics table") + end + local bt = open(r, tables[BITMAPS]) + if not bt then + return nil, Err.new(Err.CORRUPT, "no BITMAPS table") + end + local nb = u32(bt) + if nb ~= nm then + return nil, Err.new(Err.CORRUPT, "bitmap count differs from metrics count") + end + local offsets = table.create(nb, 0) + for k = 1, nb do + offsets[k] = u32(bt) + end + local sizes = { u32(bt), u32(bt), u32(bt), u32(bt) } + local padIndex = bit32.band(bt.format, 3) + local pad = bit32.lshift(1, padIndex) + local unit = bit32.lshift(1, bit32.band(bit32.rshift(bt.format, 4), 3)) + local msbBit = bit32.band(bt.format, 8) ~= 0 + local dataAt = bt.r:tell() + local dataSize = sizes[padIndex + 1] + if bt.r.err or dataAt + dataSize > bt.r:size() then + return nil, Err.new(Err.TRUNCATED, "bitmaps table") + end + -- the bitmap data normalised to MSB-first bits and bytes + local bits = bt.r:sub(dataAt, dataSize):bytes(dataSize) + if not msbBit then + for k = 0, dataSize - 1 do + buffer.writeu8(bits, k, buffer.readu8(REV, buffer.readu8(bits, k))) + end + end + if bt.big ~= msbBit and unit > 1 then + for k = 0, dataSize - unit, unit do + for j = 0, unit // 2 - 1 do + local x, y = buffer.readu8(bits, k + j), buffer.readu8(bits, k + unit - 1 - j) + buffer.writeu8(bits, k + j, y) + buffer.writeu8(bits, k + unit - 1 - j, x) + end + end + end + local glyphs: { Types.BitmapGlyph } = {} + for k = 1, nm do + local m = metrics[k] + local w, h = m[2] - m[1], m[4] + m[5] + if w < 0 or h < 0 or w > 4096 or h > 4096 then + return nil, Err.new(Err.CORRUPT, "bad glyph metrics") + end + local stride = math.ceil(w / (pad * 8)) * pad + local px = Bitmap.unpack(bits, offsets[k], w, h, stride) + glyphs[k] = { width = w, height = h, left = m[1], top = m[4], advance = m[3], pixels = px } + end + local encodings: { [number]: number } = {} + local default: number? = nil + local et = open(r, tables[BDF_ENCODINGS]) + if et then + local min2, max2, min1, max1, def = i16(et), i16(et), i16(et), i16(et), i16(et) + if min2 < 0 or max2 > 255 or min1 < 0 or max1 > 255 or max2 < min2 or max1 < min1 then + return nil, Err.new(Err.CORRUPT, "bad encoding ranges") + end + for b1 = min1, max1 do + for b2 = min2, max2 do + local g = u16(et) + if g ~= 0xFFFF and g < nm and encodings[g + 1] == nil then + encodings[g + 1] = b1 * 256 + b2 + end + end + end + if et.r.err then + return nil, Err.new(Err.TRUNCATED, "encodings table") + end + local dcols = max2 - min2 + 1 + local d1, d2 = def // 256, def % 256 + if d1 >= min1 and d1 <= max1 and d2 >= min2 and d2 <= max2 then + local slot = (d1 - min1) * dcols + (d2 - min2) + local dr = r:sub(tables[BDF_ENCODINGS].offset + 14 + slot * 2, 2) + local g = if et.big then dr:u16be() else dr:u16le() + if g ~= 0xFFFF and g < nm then + default = g + end + end + end + local nt = open(r, tables[GLYPH_NAMES]) + if nt then + local n = u32(nt) + if n == nm then + local offs = table.create(n, 0) + for k = 1, n do + offs[k] = u32(nt) + end + local strSize = u32(nt) + local strAt = nt.r:tell() + for k = 1, n do + if offs[k] < strSize then + glyphs[k].name = nt.r:sub(strAt + offs[k], strSize - offs[k]):cstring() + end + end + end + end + local registry = if type(props.CHARSET_REGISTRY) == "string" then string.upper(props.CHARSET_REGISTRY) else nil + local cset = if props.CHARSET_ENCODING ~= nil then tostring(props.CHARSET_ENCODING) else nil + local unicode = registry == nil or registry == "ISO10646" or (registry == "ISO8859" and cset == "1") + local encList = table.create(nm, -1) + for k = 1, nm do + local enc = encodings[k] + encList[k] = enc or -1 + if unicode and enc then + glyphs[k].codepoint = enc + end + end + local pixelSize = if type(props.PIXEL_SIZE) == "number" then props.PIXEL_SIZE else (ascent or 0) + (descent or 0) + local strike: Types.BitmapStrike = { + size = pixelSize, + ascent = if type(props.FONT_ASCENT) == "number" then props.FONT_ASCENT else ascent or 0, + descent = if type(props.FONT_DESCENT) == "number" then props.FONT_DESCENT else descent or 0, + glyphs = glyphs, + default = default, + } + local weight = props.WEIGHT_NAME + local style = if type(weight) == "string" and string.lower(weight) ~= "medium" and string.lower(weight) ~= "regular" then weight else "" + if props.SLANT == "I" or props.SLANT == "O" then + style = (if style ~= "" then style .. " " else "") .. "Italic" + end + return Bitmap.font(strike, { + family = if type(props.FAMILY_NAME) == "string" then props.FAMILY_NAME else nil, + style = if style ~= "" then style else "Regular", + fullName = if type(props.FONT) == "string" then props.FONT else nil, + }, { + properties = props, + encodings = encList, + unicode = unicode, + source = { format = "pcf", pad = pad, unit = unit, msbBit = msbBit, msbByte = bt.big, charset = if registry then registry .. "-" .. tostring(cset) else nil }, + }), nil +end + +return Pcf +end +__FILES["font/psf"] = function() + +-- font/psf: Linux console fonts (kbd project's psf docs, Andries Brouwer): PSF 1 (magic 36 04, UCS-2 table, FFFF / +-- FFFE) and PSF 2 (magic 72 B5 4A 86, UTF-8 table, FF / FE), read and written (PSF 2 by default); the ascent is the +-- cell height. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Bitmap = __include("codecs/font/Bitmap") + +-- ------------------------------------------------------------------------------------------------ contract +local Psf = { + name = "psf", + category = "font", + extensions = { "psf", "psfu" }, + mime = { "application/x-font-linux-psf" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/font/Bitmap" }, + caps = { decode = true, encode = true, bitmap = true, variants = { "psf1", "psf2" } }, +} + +type DecodeOptions = { maxGlyphs: number? } -- default 65536 +type EncodeOptions = { + version: number?, -- 1 or 2; default 2 + px: number?, -- default 16 + chars: (string | { number })?, -- default printable ASCII + unicode: boolean?, -- default true +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Psf.sniff(r: Bytes.Reader): number + local h = r:peek(4) + if h == "\114\181\74\134" then + return 1 + end + if string.sub(h, 1, 2) == "\54\4" and #h >= 4 and string.byte(h, 3) <= 7 and string.byte(h, 4) > 0 then + return 0.9 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Psf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + local maxGlyphs = o.maxGlyphs or 65536 + local version, count, width, height, stride, glyphAt, hasTable + if r:peek(4) == "\114\181\74\134" then + r:skip(4) + local ver, hsize, flags = r:u32le(), r:u32le(), r:u32le() + count = r:u32le() + local charsize = r:u32le() + height, width = r:u32le(), r:u32le() + if r.err then + return nil, r.err + end + if ver ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "PSF 2 version " .. ver) + end + stride = math.ceil(width / 8) + if width < 1 or height < 1 or width > 4096 or height > 4096 or charsize ~= stride * height then + return nil, Err.new(Err.CORRUPT, "bad glyph size") + end + version, glyphAt, hasTable = 2, hsize, bit32.band(flags, 1) ~= 0 + elseif r:peek(2) == "\54\4" then + r:skip(2) + local mode, charsize = r:u8(), r:u8() + if r.err then + return nil, r.err + end + version, width, height, stride = 1, 8, charsize, 1 + count = if bit32.band(mode, 1) ~= 0 then 512 else 256 + glyphAt, hasTable = 4, bit32.band(mode, 6) ~= 0 + if height < 1 then + return nil, Err.new(Err.CORRUPT, "zero glyph height") + end + else + return nil, Err.new(Err.CORRUPT, "not a PSF font") + end + if count < 1 or count > maxGlyphs then + return nil, Err.new(Err.LIMIT, "glyph count " .. count .. " over maxGlyphs") + end + local size = stride * height + if glyphAt + count * size > r:size() then + return nil, Err.new(Err.TRUNCATED, "glyph data past the end") + end + local glyphs: { Types.BitmapGlyph } = {} + for i = 0, count - 1 do + glyphs[i + 1] = { + width = width, + height = height, + left = 0, + top = height, + advance = width, + pixels = Bitmap.unpack(r.buf, r.base + glyphAt + i * size, width, height, stride), + } + end + local map: { [number]: number } = {} + local sequences = {} + local unicodeTable: { { any } } = {} + if hasTable then + local t = r:sub(glyphAt + count * size) + for i = 0, count - 1 do + local inSeq = false + local seq: { number } = {} + local entry: { any } = {} + unicodeTable[i + 1] = entry + local function endSeq() + if #seq > 0 then + table.insert(sequences, { glyph = i, codepoints = seq }) + table.insert(entry, seq) + end + seq = {} + end + while true do + if t:eof() then + break + end + local cp + if version == 1 then + cp = t:u16le() + if cp == 0xFFFF then + break + elseif cp == 0xFFFE then + endSeq() + inSeq = true + continue + end + else + local b = t:u8() + if b == 0xFF then + break + elseif b == 0xFE then + endSeq() + inSeq = true + continue + end + local n = if b < 0x80 then 0 elseif b >= 0xF0 then 3 elseif b >= 0xE0 then 2 elseif b >= 0xC0 then 1 else -1 + if n < 0 then + return nil, Err.new(Err.CORRUPT, "bad UTF-8 in the Unicode table") + end + cp = if n == 0 then b elseif n == 1 then bit32.band(b, 0x1F) elseif n == 2 then bit32.band(b, 0x0F) else bit32.band(b, 0x07) + for _ = 1, n do + cp = cp * 64 + bit32.band(t:u8(), 0x3F) + end + end + if inSeq then + table.insert(seq, cp) + continue + end + table.insert(entry, cp) + if map[cp] == nil then + map[cp] = i + if glyphs[i + 1].codepoint == nil then + glyphs[i + 1].codepoint = cp + end + end + end + endSeq() + end + if t.err then + return nil, Err.new(Err.TRUNCATED, "Unicode table") + end + else + for i = 0, count - 1 do + glyphs[i + 1].codepoint = i + end + end + local strike: Types.BitmapStrike = { size = height, ascent = height, descent = 0, glyphs = glyphs, map = map, default = 0 } + local defaultGlyph = map[0xFFFD] or map[0x3F] + if defaultGlyph then + strike.default = defaultGlyph + end + return Bitmap.font(strike, {}, { + unicode = hasTable, + sequences = sequences, + unicodeTable = if hasTable then unicodeTable else nil, + width = width, + height = height, + source = { format = "psf", version = version, glyphs = count }, + }), nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function utf8Bytes(cp: number): string + return utf8.char(cp) +end + +function Psf.encode(font: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local version = o.version or 2 + if version ~= 1 and version ~= 2 then + return nil, Err.new(Err.ARG, "version must be 1 or 2") + end + local strike, err = Bitmap.strike(font, { px = o.px, chars = o.chars }) + if not strike then + return nil, err + end + local glyphs = strike.glyphs + local n = #glyphs + if n == 0 then + return nil, Err.new(Err.ARG, "no glyphs") + end + local width = 0 + for _, g in glyphs do + width = math.max(width, g.advance, g.left + g.width) + end + local height = math.max(1, strike.ascent + strike.descent) + if version == 1 then + if width > 8 then + return nil, Err.new(Err.ARG, "PSF 1 glyphs are 8 pixels wide (this font needs " .. width .. ")") + end + if n > 512 then + return nil, Err.new(Err.ARG, "PSF 1 holds 256 or 512 glyphs (this font has " .. n .. ")") + end + width = 8 + end + width = math.max(width, 1) + local count = if version == 1 then (if n > 256 then 512 else 256) else n + local stride = math.ceil(width / 8) + local size = stride * height + local cells = buffer.create(count * size) + for i, g in glyphs do + local cell = buffer.create(width * height) + local x0, y0 = g.left, strike.ascent - g.top + for y = 0, g.height - 1 do + for x = 0, g.width - 1 do + local cx, cy = x0 + x, y0 + y + if cx >= 0 and cy >= 0 and cx < width and cy < height and buffer.readu8(g.pixels, y * g.width + x) >= 128 then + buffer.writeu8(cell, cy * width + cx, 255) + end + end + end + buffer.copy(cells, (i - 1) * size, Bitmap.pack(cell, width, height, stride)) + end + local cps: { { number } } = {} + for i = 1, count do + cps[i] = {} + end + local seen: { [number]: boolean } = {} + for i, g in glyphs do + if g.codepoint and not seen[g.codepoint] then + seen[g.codepoint] = true + table.insert(cps[i], g.codepoint) + end + end + if strike.map then + local extra: { { number } } = {} + for cp, gi in strike.map do + if not seen[cp] and gi >= 0 and gi < count then + table.insert(extra, { cp, gi }) + end + end + table.sort(extra, function(a: { number }, b: { number }): boolean + return a[1] < b[1] + end) + for _, e in extra do + seen[e[1]] = true + table.insert(cps[e[2] + 1], e[1]) + end + end + local meta = if type(font.meta) == "table" then font.meta else {} + local srcTable = if font.bitmap == strike and type(meta.unicodeTable) == "table" and #meta.unicodeTable == n then meta.unicodeTable else nil + local withTable = if o.unicode ~= nil then o.unicode else meta.unicode ~= false + local w = Bytes.writer(count * size + 64) + if version == 2 then + w:string("\114\181\74\134") + w:u32le(0) + w:u32le(32) + w:u32le(if withTable then 1 else 0) + w:u32le(count) + w:u32le(size) + w:u32le(height) + w:u32le(width) + else + w:string("\54\4") + w:u8((if count == 512 then 1 else 0) + (if withTable then 2 else 0)) + w:u8(height) + end + w:bytes(cells) + if withTable then + local function put(cp: number) + if version == 2 then + w:string(utf8Bytes(cp)) + elseif cp < 0xFFFE then + w:u16le(cp) + end + end + for i = 1, count do + -- a PSF read earlier writes its table back as it was (code points on several glyphs, sequences) + local list = if srcTable and srcTable[i] then srcTable[i] else cps[i] + for _, x in list do + if type(x) == "number" then + put(x) + end + end + for _, x in list do + if type(x) == "table" then + if version == 2 then + w:u8(0xFE) + else + w:u16le(0xFFFE) + end + for _, cp in x do + put(cp) + end + end + end + if version == 2 then + w:u8(0xFF) + else + w:u16le(0xFFFF) + end + end + end + return w:finish(), nil +end + +return Psf +end +__FILES["font/ttf"] = function() + +-- font/ttf: TrueType / OpenType (glyf or CFF) fonts and collections via codecs/font/TrueType, ported from stb_truetype +-- 1.26 (public domain / MIT) via imgui-luau's imstb_truetype.lua. Not supported: hinting, variable fonts, bitmap / +-- colour glyphs, GSUB, writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local TrueType = __include("codecs/font/TrueType") + +-- ------------------------------------------------------------------------------------------------ contract +local Ttf = { + name = "ttf", + category = "font", + extensions = { "ttf", "otf", "ttc", "otc" }, + mime = { "font/ttf", "font/otf", "font/collection" }, + deps = { "core/Err", "core/Bytes", "codecs/font/TrueType" }, + caps = { decode = true, encode = false, outlines = { "truetype", "cff" }, collection = true, kerning = true }, +} + +type DecodeOptions = { + index: number?, -- default 0 +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Ttf.sniff(r: Bytes.Reader): number + local m = r:peek(4) + if m == "\0\1\0\0" or m == "OTTO" or m == "ttcf" or m == "true" then + return 0.9 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Ttf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local font, err = TrueType.font(r.buf, r.base, r.limit - r.base, opts) + if not font then + return nil, err + end + font.meta.source = { format = "ttf", outlines = font.meta.outlines, sfnt = font.meta.sfnt } + return font, nil +end + +-- ------------------------------------------------------------------------------------------------ extras +function Ttf.count(r: Bytes.Reader): number + return TrueType.count(r.buf, r.base) +end + +return Ttf +end +__FILES["font/type1"] = function() + +-- font/type1: PostScript Type 1 fonts, PFB (segments 80 01 / 80 02 / 80 03) and PFA, from Adobe's "Adobe Type 1 Font +-- Format" (1990): eexec (r = 55665) and charstring (r = 4330) decryption, code points via codecs/font/GlyphNames. +-- Not supported: hinting, Multiple Master and CID-keyed (Type 9 / 11) fonts, writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Raster = __include("codecs/image/Raster") +local GlyphNames = __include("codecs/font/GlyphNames") +local Charstring = __include("font/type1/Charstring") + +-- ------------------------------------------------------------------------------------------------ contract +local Type1 = { + name = "type1", + category = "font", + extensions = { "pfb", "pfa", "t1" }, + mime = { "application/x-font-type1" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Raster", "codecs/font/GlyphNames" }, + caps = { decode = true, encode = false, outlines = { "type1" }, variants = { "pfb", "pfa" } }, +} + +type DecodeOptions = { maxGlyphs: number? } -- default 65536 + +-- ------------------------------------------------------------------------------------------------ sniff +function Type1.sniff(r: Bytes.Reader): number + local h = r:peek(64) + if string.sub(h, 1, 2) == "\128\1" then + h = string.sub(h, 7) + end + if string.sub(h, 1, 14) == "%!PS-AdobeFont" or string.sub(h, 1, 10) == "%!FontType" then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function sections(r: Bytes.Reader): (string?, buffer?, string?) + local b = r.buf + local n = r:size() + if r:peek(2) == "\128\1" then + local clear, bin = {}, Bytes.writer() + local p = 0 + while p + 2 <= n do + local h = r:sub(p, 6) + local m, ty, len = h:u8(), h:u8(), h:u32le() + if m ~= 128 then + return nil, nil, "bad PFB segment marker" + end + if ty == 3 then + break + end + if h.err or p + 6 + len > n then + return nil, nil, "truncated PFB segment" + end + if ty == 1 then + if #clear == 0 or bin:tell() == 0 then + table.insert(clear, buffer.readstring(b, r.base + p + 6, len)) + end + elseif ty == 2 then + bin:bytes(r:sub(p + 6, len):bytes(len)) + else + return nil, nil, "bad PFB segment type " .. ty + end + p += 6 + len + end + return table.concat(clear), bin:finish(), nil + end + local text = buffer.readstring(b, r.base, n) + local e = string.find(text, "eexec", 1, true) + if not e then + return nil, nil, "no eexec section" + end + local clear = string.sub(text, 1, e + 4) + -- PFA: hex digits after eexec, up to the zeros trailer (or binary if not hex) + local rest = string.sub(text, e + 5) + local hexPart = string.match(rest, "^%s*([%x%s]+)") + if hexPart and #hexPart > 8 then + local digits = string.gsub(hexPart, "%s", "") + local out = buffer.create(#digits // 2) + for i = 0, #digits // 2 - 1 do + buffer.writeu8(out, i, tonumber(string.sub(digits, i * 2 + 1, i * 2 + 2), 16) or 0) + end + return clear, out, nil + end + local s = string.match(rest, "^[\r\n]*(.*)$") or rest + return clear, buffer.fromstring(s), nil +end + +local function decrypt(src: buffer, off: number, n: number, key: number, skip: number): buffer + local r = key + local out = buffer.create(math.max(0, n - skip)) + for i = 0, n - 1 do + local c = buffer.readu8(src, off + i) + local p = bit32.bxor(c, bit32.rshift(r, 8)) + r = ((c + r) * 52845 + 22719) % 65536 + if i >= skip then + buffer.writeu8(out, i - skip, p) + end + end + return out +end + +-- binary strings of the private dictionary: "<len> RD <bytes>" / "<len> -| <bytes>" +local function binaryAt(priv: buffer, p: number, len: number): buffer? + if p < 0 or len < 0 or p + len > buffer.len(priv) then + return nil + end + local out = buffer.create(len) + buffer.copy(out, 0, priv, p, len) + return out +end + +local function psString(clear: string, key: string): string? + return string.match(clear, "/" .. key .. "%s*%((.-)%)%s*[rd]") or string.match(clear, "/" .. key .. "%s*%((.-)%)") +end + +local Face = {} +Face.__index = Face + +function Face.glyphIndex(self: any, cp: number): number + return self._cmap[cp] or 0 +end + +function Face.advance(self: any, g: number): number + local res = self:_run(g) + return if res then res.advance else 0 +end + +function Face.kern(_self: any, _a: number, _b: number): number + return 0 +end + +function Face._run(self: any, g: number): Charstring.Result? + local cached = self._cache[g] + if cached ~= nil then + return if cached == false then nil else cached + end + local cs = self._charstrings[g + 1] + if not cs then + return nil + end + local res = Charstring.run(cs, self._ctx) + self._cache[g] = res or false + return res +end + +function Face.outline(self: any, g: number): { any }? + local res = self:_run(g) + if not res then + return nil + end + local out = table.create(#res.cmds) + for i, c in res.cmds do + out[i] = table.clone(c) + end + return out +end + +function Face.rasterize(self: any, g: number, px: number): Types.Image? + if type(px) ~= "number" or not (px > 0) or px > 4096 then + return nil + end + local res = self:_run(g) + if not res then + return nil + end + local s = px / self.unitsPerEm + local m = Raster.mask(res.cmds, { transform = { s, 0, 0, -s, 0, 0 }, maxPixels = 2 ^ 24 }) + local img + if m then + img = Types.Image.new(m.width, m.height, "alpha8") + buffer.copy(img.pixels, 0, m.coverage) + img.meta.left, img.meta.top = m.x, -m.y + else + img = Types.Image.new(0, 0, "alpha8") + img.meta.left, img.meta.top = 0, 0 + end + img.meta.advance = res.advance * s + img.meta.glyph = g + return img +end + +function Type1.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + local maxGlyphs = o.maxGlyphs or 65536 + local clear, enc, serr = sections(r) + if not clear or not enc then + return nil, Err.from(serr) + end + if not string.find(clear, "eexec", 1, true) and buffer.len(enc) == 0 then + return nil, Err.new(Err.CORRUPT, "no eexec section") + end + if buffer.len(enc) < 4 then + return nil, Err.new(Err.TRUNCATED, "eexec section too short") + end + local priv = decrypt(enc, 0, buffer.len(enc), 55665, 4) + local ptext = buffer.tostring(priv) + local lenIV = tonumber(string.match(ptext, "/lenIV%s+(%-?%d+)") or "4") or 4 + local subrs: { buffer } = {} + local function charstring(p: number, len: number): buffer? + local raw = binaryAt(priv, p, len) + if not raw then + return nil + end + if lenIV < 0 then + return raw + end + return decrypt(raw, 0, len, 4330, lenIV) + end + local sAt = string.find(ptext, "/Subrs", 1, true) + local csAt = string.find(ptext, "/CharStrings", 1, true) + if not csAt then + return nil, Err.new(Err.CORRUPT, "no CharStrings") + end + if sAt and sAt < csAt then + local p = sAt + while true do + local s, e0, idx, len = string.find(ptext, "dup%s+(%d+)%s+(%d+)%s+%S+ ", p) + if not s or s > csAt then + break + end + local e = e0 :: number + local i, n = tonumber(idx) :: number, tonumber(len) :: number + if i > 65535 then + return nil, Err.new(Err.LIMIT, "too many subroutines") + end + local cs = charstring(e, n) + if not cs then + return nil, Err.new(Err.TRUNCATED, "subroutine " .. i .. " past the end") + end + subrs[i + 1] = cs + p = e + n + end + end + local names: { string } = {} + local charstrings: { buffer } = {} + local byName: { [string]: number } = {} + local p = csAt + 12 + while true do + local s, e0, name, len = string.find(ptext, "/([^%s/%[%]{}()<>]+)%s+(%d+)%s+%S+ ", p) + if not s then + break + end + local e = e0 :: number + if string.find(string.sub(ptext, p, s), "%send%s") then + break + end + local n = tonumber(len) :: number + local cs = charstring(e, n) + if not cs then + return nil, Err.new(Err.TRUNCATED, "charstring " .. tostring(name) .. " past the end") + end + if #names >= maxGlyphs then + return nil, Err.new(Err.LIMIT, "more than maxGlyphs glyphs") + end + table.insert(names, name :: string) + table.insert(charstrings, cs) + if byName[name :: string] == nil then + byName[name :: string] = #names - 1 + end + p = e + n + end + if #names == 0 then + return nil, Err.new(Err.CORRUPT, "no glyphs") + end + -- .notdef first: glyph 0 + local nd = byName[".notdef"] + if nd and nd ~= 0 then + names[1], names[nd + 1] = names[nd + 1], names[1] + charstrings[1], charstrings[nd + 1] = charstrings[nd + 1], charstrings[1] + byName[names[1]], byName[names[nd + 1]] = 0, nd + end + local encoding: { [number]: string } = {} + if string.find(clear, "/Encoding%s+StandardEncoding") then + for code, gname in GlyphNames.STANDARD do + encoding[code] = gname + end + else + for code, gname in string.gmatch(clear, "dup%s+(%d+)%s*/([^%s/]+)%s+put") do + encoding[tonumber(code) :: number] = gname + end + end + local cmap: { [number]: number } = {} + for _, gname in encoding do + local g = byName[gname] + local cp = GlyphNames.unicode(gname) + if g and cp and cmap[cp] == nil then + cmap[cp] = g + end + end + for k, gname in names do + local cp = GlyphNames.unicode(gname) + if cp and cmap[cp] == nil then + cmap[cp] = k - 1 + end + end + local fm = string.match(clear, "/FontMatrix%s*[%[{]([^%]}]*)[%]}]") + local scale = 0.001 + if fm then + local a = tonumber(string.match(fm, "^%s*(%S+)")) + if a and a > 0 then + scale = a + end + end + local bb = string.match(clear, "/FontBBox%s*[{%[]([^}%]]*)[}%]]") + local bbox = { 0, 0, 0, 0 } + if bb then + local k = 1 + for v in string.gmatch(bb, "%S+") do + bbox[k] = tonumber(v) or 0 + k += 1 + end + end + local upm = math.floor(1 / scale + 0.5) + local font = setmetatable({ + kind = "font", + info = { + family = psString(clear, "FamilyName") or string.match(clear, "/FontName%s*/(%S+)"), + style = psString(clear, "Weight") or "Regular", + fullName = psString(clear, "FullName"), + postscriptName = string.match(clear, "/FontName%s*/(%S+)"), + }, + unitsPerEm = upm, + ascent = bbox[4], + descent = bbox[2], + lineGap = 0, + numGlyphs = #names, + meta = { + glyphNames = names, + encoding = encoding, + bbox = bbox, + italicAngle = tonumber(string.match(clear, "/ItalicAngle%s+(%-?[%d%.]+)") or "0"), + lenIV = lenIV, + source = { format = "type1", variant = if r:peek(2) == "\128\1" then "pfb" else "pfa" }, + }, + _cmap = cmap, + _charstrings = charstrings, + _cache = {}, + }, Face) + font._ctx = { + subrs = subrs, + seac = function(code: number): Charstring.Result? + local gname = GlyphNames.STANDARD[code] + local g = if gname then byName[gname] else nil + if not g then + return nil + end + local res = Charstring.run(charstrings[g + 1], { subrs = subrs }) + return res + end, + } + return font, nil +end + +return Type1 +end +__FILES["font/type1/Charstring"] = function() + +-- font/type1/Charstring: Type 1 charstring interpreter (Adobe Type 1 Font Format, chapters 6 and 8); hints ignored. +local Charstring = {} + +type Result = { cmds: { any }, advance: number, sbx: number } +type Context = { subrs: { buffer }, seac: ((code: number) -> Result?)? } + +local readu8 = buffer.readu8 + +function Charstring.run(cs: buffer, ctx: Context): (Result?, string?) + local cmds: { any } = {} + local stack: { number } = {} + local sp = 0 + local ps: { number } = {} + local x, y = 0, 0 + local advance, sbx = 0, 0 + local open = false + local flex = false + local flexPts: { number } = {} + local budget = 200000 + local finished = false + + local function push(v: number) + if sp < 48 then + sp += 1 + stack[sp] = v + end + end + local function arg(i: number): number + return stack[i] or 0 + end + local function close() + if open then + table.insert(cmds, { op = "close" }) + open = false + end + end + local function moveTo(dx: number, dy: number) + x += dx + y += dy + if flex then + table.insert(flexPts, x) + table.insert(flexPts, y) + return + end + close() + local c: any = { op = "moveTo" } + c[1], c[2] = x, y + table.insert(cmds, c) + end + local function ensureOpen() + if not open then + -- a drawing operator without a moveto starts at the current point + local c: any = { op = "moveTo" } + c[1], c[2] = x, y + table.insert(cmds, c) + open = true + end + end + local function lineTo(dx: number, dy: number) + ensureOpen() + x += dx + y += dy + local c: any = { op = "lineTo" } + c[1], c[2] = x, y + table.insert(cmds, c) + end + local function curveTo(a: number, b: number, c: number, d: number, e: number, f: number) + ensureOpen() + local x1, y1 = x + a, y + b + local x2, y2 = x1 + c, y1 + d + x, y = x2 + e, y2 + f + local cmd: any = { op = "cubicTo" } + cmd[1], cmd[2], cmd[3], cmd[4], cmd[5], cmd[6] = x1, y1, x2, y2, x, y + table.insert(cmds, cmd) + end + + local function exec(b: buffer, depth: number): string? + if depth > 10 then + return "subroutines nested too deep" + end + local n = buffer.len(b) + local p = 0 + while p < n do + budget -= 1 + if budget <= 0 then + return "operation budget exceeded" + end + local v = readu8(b, p) + p += 1 + if v >= 32 then + if v <= 246 then + push(v - 139) + elseif v <= 250 then + if p >= n then + return "truncated number" + end + push((v - 247) * 256 + readu8(b, p) + 108) + p += 1 + elseif v <= 254 then + if p >= n then + return "truncated number" + end + push(-(v - 251) * 256 - readu8(b, p) - 108) + p += 1 + else + if p + 4 > n then + return "truncated number" + end + local u = readu8(b, p) * 16777216 + readu8(b, p + 1) * 65536 + readu8(b, p + 2) * 256 + readu8(b, p + 3) + push(if u >= 0x80000000 then u - 0x100000000 else u) + p += 4 + end + continue + end + local op = v + if op == 12 then + if p >= n then + return "truncated escape" + end + op = 1200 + readu8(b, p) + p += 1 + end + if op == 13 then -- hsbw + sbx, advance = arg(1), arg(2) + x, y = sbx, 0 + sp = 0 + elseif op == 1207 then -- sbw + sbx, advance = arg(1), arg(3) + x, y = arg(1), arg(2) + sp = 0 + elseif op == 21 then + moveTo(arg(1), arg(2)) + sp = 0 + elseif op == 22 then + moveTo(arg(1), 0) + sp = 0 + elseif op == 4 then + moveTo(0, arg(1)) + sp = 0 + elseif op == 5 then + lineTo(arg(1), arg(2)) + sp = 0 + elseif op == 6 then + lineTo(arg(1), 0) + sp = 0 + elseif op == 7 then + lineTo(0, arg(1)) + sp = 0 + elseif op == 8 then + curveTo(arg(1), arg(2), arg(3), arg(4), arg(5), arg(6)) + sp = 0 + elseif op == 30 then -- vhcurveto + curveTo(0, arg(1), arg(2), arg(3), arg(4), 0) + sp = 0 + elseif op == 31 then -- hvcurveto + curveTo(arg(1), 0, arg(2), arg(3), 0, arg(4)) + sp = 0 + elseif op == 9 then + close() + sp = 0 + elseif op == 10 then -- callsubr + local idx = arg(sp) + sp = math.max(0, sp - 1) + local sub = ctx.subrs[idx + 1] + if not sub then + return "call of a missing subroutine " .. idx + end + local err = exec(sub, depth + 1) + if err or finished then + return err + end + elseif op == 11 then -- return + return nil + elseif op == 14 then -- endchar + close() + finished = true + return nil + elseif op == 1212 then -- div + if sp >= 2 then + local d = stack[sp] + stack[sp - 1] = if d ~= 0 then stack[sp - 1] / d else 0 + sp -= 1 + end + elseif op == 1216 then -- callothersubr: args... n othersubr# + local num = arg(sp) + local count = arg(sp - 1) + sp = math.max(0, sp - 2) + count = math.clamp(count, 0, sp) + local args = {} + for i = 1, count do + args[i] = stack[sp - count + i] + end + sp -= count + if num == 1 then + flex = true + table.clear(flexPts) + elseif num == 2 then + -- a flex point: the rmoveto before it already recorded the point + elseif num == 0 and flex then + flex = false + -- flexPts: the reference point, then 6 control / end points + local f = flexPts + if #f >= 14 then + -- restore the current point to before the flex sequence's moves + local function curve(i: number) + ensureOpen() + local cmd: any = { op = "cubicTo" } + cmd[1], cmd[2], cmd[3], cmd[4], cmd[5], cmd[6] = f[i], f[i + 1], f[i + 2], f[i + 3], f[i + 4], f[i + 5] + table.insert(cmds, cmd) + end + curve(3) + curve(9) + x, y = f[13], f[14] + end + table.clear(ps) + table.insert(ps, args[3] or y) + table.insert(ps, args[2] or x) + elseif num == 3 then + table.clear(ps) + table.insert(ps, 3) + else + table.clear(ps) + for i = #args, 1, -1 do + table.insert(ps, args[i]) + end + end + elseif op == 1217 then -- pop + push(table.remove(ps) or 0) + elseif op == 1233 then -- setcurrentpoint + x, y = arg(1), arg(2) + sp = 0 + elseif op == 1206 then -- seac: asb adx ady bchar achar + local asb, adx, ady, bchar, achar = arg(1), arg(2), arg(3), arg(4), arg(5) + sp = 0 + local seac = ctx.seac + if not seac then + return "seac without base glyphs" + end + local base = seac(bchar) + local accent = seac(achar) + if not base or not accent then + return "seac of a missing glyph" + end + close() + for _, c in base.cmds do + table.insert(cmds, c) + end + local ox, oy = adx - asb, ady + for _, c in accent.cmds do + local t: any = { op = c.op } + for i = 1, #c, 2 do + t[i], t[i + 1] = c[i] + ox, c[i + 1] + oy + end + table.insert(cmds, t) + end + finished = true + return nil + elseif op == 1 or op == 3 or op == 1200 or op == 1201 or op == 1202 then + sp = 0 -- hints + else + sp = 0 -- unknown operators clear the stack + end + end + return nil + end + + local err = exec(cs, 0) + if err then + return nil, err + end + close() + return { cmds = cmds, advance = advance, sbx = sbx }, nil +end + +return Charstring +end +__FILES["font/woff"] = function() + +-- font/woff: WOFF 1.0 (W3C Recommendation, 2012): zlib-compressed sfnt tables, rebuilt and read through +-- codecs/font/TrueType; the metadata XML goes to meta.woffMetadata. Not supported: writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Deflate = __include("codecs/compress/Deflate") +local TrueType = __include("codecs/font/TrueType") + +-- ------------------------------------------------------------------------------------------------ contract +local Woff = { + name = "woff", + category = "font", + extensions = { "woff" }, + mime = { "font/woff" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/font/TrueType" }, + caps = { decode = true, encode = false, outlines = { "truetype", "cff" } }, +} + +type DecodeOptions = { + maxBytes: number?, -- default 2^28 +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Woff.sniff(r: Bytes.Reader): number + return if r:peek(4) == "wOFF" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Woff.sfnt(r: Bytes.Reader, opts: DecodeOptions?): (buffer?, Err.Err?, string?) + 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), nil + end + local flavor = r:string(4) + local length = r:u32be() + local numTables = r:u16be() + r:skip(2) + local total = r:u32be() + r:skip(4) + local metaOffset, metaLength, metaOrig = r:u32be(), r:u32be(), r:u32be() + r:skip(8) + if r.err then + return nil, r.err, nil + end + if flavor == "ttcf" then + 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), 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), nil + end + local dir = {} + for i = 1, numTables do + local e = { tag = r:string(4), offset = r:u32be(), comp = r:u32be(), orig = r:u32be(), sum = r:u32be() } + dir[i] = e + end + if r.err then + return nil, r.err, nil + end + local out = buffer.create(total) + local w = Bytes.writer(12) + w:string(flavor) + w:u16be(numTables) + local es, sel = 1, 0 + while es * 2 <= numTables do + es *= 2 + sel += 1 + end + w:u16be(es * 16) + w:u16be(sel) + w:u16be(numTables * 16 - es * 16) + buffer.copy(out, 0, w.buf, 0, 12) + 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), nil + end + if p + e.orig > total then + 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) + buffer.writeu32(out, d + 4, bit32.byteswap(e.sum)) + buffer.writeu32(out, d + 8, bit32.byteswap(p)) + buffer.writeu32(out, d + 12, bit32.byteswap(e.orig)) + 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), nil + end + buffer.copy(out, p, t, 0, e.orig) + else + buffer.copy(out, p, r.buf, base + e.offset, e.orig) + end + p += e.orig + p = (p + 3) // 4 * 4 + if p > total then + p = total + end + end + local xml = nil + if metaLength > 0 and metaOffset + metaLength <= r:size() then + local m = Deflate.zlib(r.buf, base + metaOffset, metaLength, metaOrig) + if m then + xml = buffer.tostring(m) + end + end + return out, nil, xml +end + +function Woff.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local sfnt, err, xml = Woff.sfnt(r, opts) + if not sfnt then + return nil, err + end + local font, ferr = TrueType.font(sfnt) + if not font then + return nil, ferr + end + font.meta.woffMetadata = xml + font.meta.source = { format = "woff", outlines = font.meta.outlines } + return font, nil +end + +return Woff +end +__FILES["font/woff2"] = function() + +-- font/woff2: WOFF 2.0 (W3C Recommendation): Brotli-compressed sfnt tables with the glyf / loca and hmtx transforms, +-- rebuilt by font/woff2/Rebuild. Not supported: collections, writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local TrueType = __include("codecs/font/TrueType") +local Rebuild = __include("font/woff2/Rebuild") + +-- ------------------------------------------------------------------------------------------------ contract +local Woff2 = { + name = "woff2", + category = "font", + extensions = { "woff2" }, + mime = { "font/woff2" }, + deps = { "core/Err", "core/Bytes", "codecs/font/TrueType", "codecs/compress/Brotli" }, + caps = { decode = true, encode = false, outlines = { "truetype", "cff" }, transforms = { "glyf", "loca", "hmtx" } }, +} + +type DecodeOptions = { + maxBytes: number?, -- default 2^28 +} + +-- ------------------------------------------------------------------------------------------------ constants +-- ------------------------------------------------------------------------------------------------ sniff +function Woff2.sniff(r: Bytes.Reader): number + return if r:peek(4) == "wOF2" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Woff2.sfnt(r: Bytes.Reader, opts: DecodeOptions?): (buffer?, Err.Err?) + local maxBytes = (opts and opts.maxBytes) or 2 ^ 28 + local at = r.base + local out, msg, code = Rebuild.sfnt(r, maxBytes) + if not out then + return nil, Err.from(msg or "rebuild failed", at, code or "corrupt") + end + return out, nil +end + +function Woff2.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local sfnt, err = Woff2.sfnt(r, opts) + if not sfnt then + return nil, err + end + local font, ferr = TrueType.font(sfnt) + if not font then + return nil, ferr + end + font.meta.source = { format = "woff2", outlines = font.meta.outlines } + return font, nil +end + +return Woff2 +end +__FILES["font/woff2/Rebuild"] = function() + +-- font/woff2/Rebuild: the sfnt of a WOFF2 file (W3C WOFF2, 2024 edition: section 5 glyf / loca, section 6 hmtx). +local Bytes = __include("core/Bytes") +local Brotli = __include("codecs/compress/Brotli") + +local Rebuild = {} + +local readu8 = buffer.readu8 +local band, rshift = bit32.band, bit32.rshift + +local KNOWN = { + "cmap", "head", "hhea", "hmtx", "maxp", "name", "OS/2", "post", "cvt ", "fpgm", "glyf", "loca", "prep", "CFF ", + "VORG", "EBDT", "EBLC", "gasp", "hdmx", "kern", "LTSH", "PCLT", "VDMX", "vhea", "vmtx", "BASE", "GDEF", "GPOS", + "GSUB", "EBSC", "JSTF", "MATH", "CBDT", "CBLC", "COLR", "CPAL", "SVG ", "sbix", "acnt", "avar", "bdat", "bloc", + "bsln", "cvar", "fdsc", "feat", "fmtx", "fvar", "gvar", "hsty", "just", "lcar", "mort", "morx", "opbd", "prop", + "trak", "Zapf", "Silf", "Glat", "Gloc", "Feat", "Sill", +} + +-- UIntBase128 from r +local function base128(r: Bytes.Reader): number? + local v = 0 + for i = 1, 5 do + local b = r:u8() + if r.err or (i == 1 and b == 0x80) then + return nil + end + if v >= 2 ^ 25 then + return nil + end + v = v * 128 + band(b, 0x7F) + if b < 0x80 then + return v + end + end + return nil +end + +type Stream = { buf: buffer, p: number, e: number, bad: boolean } +local function stream(b: buffer, p: number, n: number): Stream + return { buf = b, p = p, e = p + n, bad = false } +end +local function su8(s: Stream): number + if s.p >= s.e then + s.bad = true + return 0 + end + local v = readu8(s.buf, s.p) + s.p += 1 + return v +end +local function su16(s: Stream): number + return su8(s) * 256 + su8(s) +end +local function si16(s: Stream): number + local v = su16(s) + return if v >= 32768 then v - 65536 else v +end +local function s255(s: Stream): number + local c = su8(s) + if c == 253 then + return su16(s) + elseif c == 255 then + return su8(s) + 253 + elseif c == 254 then + return su8(s) + 506 + end + return c +end + +local function withSign(flag: number, v: number): number + return if band(flag, 1) ~= 0 then v else -v +end + +local function glyf(b: buffer, p: number, n: number, maxBytes: number): (any?, string?) + local h = stream(b, p, n) + su16(h) -- reserved + local option = su16(h) + local numGlyphs = su16(h) + local indexFormat = su16(h) + local sizes = {} + for i = 1, 7 do + sizes[i] = su16(h) * 65536 + su16(h) + end + if h.bad then + return nil, "truncated glyf transform header" + end + local at = h.p + local streams: { Stream } = {} + for i = 1, 7 do + if at + sizes[i] > p + n then + return nil, "glyf transform stream past the end" + end + streams[i] = stream(b, at, sizes[i]) + at += sizes[i] + end + local nContour, nPoints, flagS, glyphS, compS, bboxS, instrS = streams[1], streams[2], streams[3], streams[4], streams[5], streams[6], streams[7] + local overlap: Stream? = nil + if band(option, 1) ~= 0 then + overlap = stream(b, at, (numGlyphs + 7) // 8) + if at + (numGlyphs + 7) // 8 > p + n then + return nil, "overlap bitmap past the end" + end + end + -- the bbox bitmap leads the bbox stream + local bitmapLen = 4 * ((numGlyphs + 31) // 32) + if bitmapLen > sizes[6] then + return nil, "bbox bitmap past the end" + end + local bboxBits = bboxS.p + bboxS.p += bitmapLen + local function hasBox(g: number): boolean + return band(readu8(b, bboxBits + g // 8), rshift(0x80, g % 8)) ~= 0 + end + local w = Bytes.writer(n * 2) + local loca = table.create(numGlyphs + 1, 0) + local xMins = table.create(numGlyphs, 0) + for g = 0, numGlyphs - 1 do + loca[g + 1] = w.pos + local nc = si16(nContour) + if nContour.bad then + return nil, "nContour stream truncated" + end + if nc == 0 then + if hasBox(g) then + return nil, "empty glyph with a bounding box" + end + elseif nc > 0 then + local ends = table.create(nc, 0) + local total = 0 + for c = 1, nc do + total += s255(nPoints) + ends[c] = total - 1 + end + if nPoints.bad or total > 65535 then + return nil, "bad point counts" + end + local xs, ys, on = table.create(total, 0), table.create(total, 0), table.create(total, false) + local x, y = 0, 0 + for k = 1, total do + local fl = su8(flagS) + on[k] = rshift(fl, 7) == 0 + fl = band(fl, 0x7F) + local dx, dy + if fl < 10 then + dx = 0 + dy = withSign(fl, band(fl, 14) * 128 + su8(glyphS)) + elseif fl < 20 then + dx = withSign(fl, band(fl - 10, 14) * 128 + su8(glyphS)) + dy = 0 + elseif fl < 84 then + local b0 = fl - 20 + local b1 = su8(glyphS) + dx = withSign(fl, 1 + band(b0, 0x30) + rshift(b1, 4)) + dy = withSign(rshift(fl, 1), 1 + band(b0, 0x0C) * 4 + band(b1, 0x0F)) + elseif fl < 120 then + local b0 = fl - 84 + dx = withSign(fl, 1 + (b0 // 12) * 256 + su8(glyphS)) + dy = withSign(rshift(fl, 1), 1 + rshift(b0 % 12, 2) * 256 + su8(glyphS)) + elseif fl < 124 then + local b1, b2, b3 = su8(glyphS), su8(glyphS), su8(glyphS) + dx = withSign(fl, b1 * 16 + rshift(b2, 4)) + dy = withSign(rshift(fl, 1), band(b2, 0x0F) * 256 + b3) + else + local b1, b2, b3, b4 = su8(glyphS), su8(glyphS), su8(glyphS), su8(glyphS) + dx = withSign(fl, b1 * 256 + b2) + dy = withSign(rshift(fl, 1), b3 * 256 + b4) + end + x += dx + y += dy + xs[k], ys[k] = x, y + end + local ilen = s255(glyphS) + if flagS.bad or glyphS.bad then + return nil, "flag / glyph stream truncated" + end + local x0, y0, x1, y1 + if hasBox(g) then + 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 = 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 + end + end + xMins[g + 1] = x0 + w:u16be(nc % 65536) + w:u16be(x0 % 65536) + w:u16be(y0 % 65536) + w:u16be(x1 % 65536) + w:u16be(y1 % 65536) + for c = 1, nc do + w:u16be(ends[c]) + end + w:u16be(ilen) + if instrS.p + ilen > instrS.e then + return nil, "instruction stream truncated" + end + w:bytes(b, instrS.p, ilen) + instrS.p += ilen + local ov = overlap ~= nil and band(readu8(b, (overlap :: Stream).p + g // 8), rshift(0x80, g % 8)) ~= 0 + -- flags (short vectors, same-as-previous, repeats) and the coordinate deltas, as compilers write them + local fls = table.create(total, 0) + for k = 1, total do + local fl = if on[k] then 1 else 0 + if k == 1 and ov then + fl += 0x40 + end + local dx = xs[k] - (if k > 1 then xs[k - 1] else 0) + local dy = ys[k] - (if k > 1 then ys[k - 1] else 0) + if dx == 0 then + fl += 0x10 + elseif dx > -256 and dx < 256 then + fl += if dx > 0 then 0x12 else 0x02 + end + if dy == 0 then + fl += 0x20 + elseif dy > -256 and dy < 256 then + fl += if dy > 0 then 0x24 else 0x04 + end + fls[k] = fl + end + local k = 1 + while k <= total do + local fl = fls[k] + local run = 0 + while k + run + 1 <= total and fls[k + run + 1] == fl and run < 255 do + run += 1 + end + if run > 1 then + w:u8(fl + 8) + w:u8(run) + k += run + 1 + else + w:u8(fl) + k += 1 + end + end + for pass = 0, 1 do + local cs = if pass == 0 then xs else ys + local short, same = if pass == 0 then 0x02 else 0x04, if pass == 0 then 0x10 else 0x20 + local prev = 0 + for q = 1, total do + local d = cs[q] - prev + prev = cs[q] + local fl = fls[q] + if band(fl, short) ~= 0 then + w:u8(math.abs(d)) + elseif band(fl, same) == 0 then + w:u16be(d % 65536) + end + end + end + elseif nc == -1 then + if not hasBox(g) then + return nil, "composite glyph without a bounding box" + end + local x0, y0, x1, y1 = si16(bboxS), si16(bboxS), si16(bboxS), si16(bboxS) + xMins[g + 1] = x0 + w:u16be(0xFFFF) + w:u16be(x0 % 65536) + w:u16be(y0 % 65536) + w:u16be(x1 % 65536) + w:u16be(y1 % 65536) + -- copy the component records: their length follows from the flags + local start = compS.p + local instr = false + while true do + local fl = su16(compS) + su16(compS) -- glyph index + local len = if band(fl, 1) ~= 0 then 4 else 2 + if band(fl, 8) ~= 0 then + len += 2 + elseif band(fl, 0x40) ~= 0 then + len += 4 + elseif band(fl, 0x80) ~= 0 then + len += 8 + end + compS.p += len + if band(fl, 0x100) ~= 0 then + instr = true + end + if compS.bad or compS.p > compS.e then + return nil, "composite stream truncated" + end + if band(fl, 0x20) == 0 then + break + end + end + w:bytes(b, start, compS.p - start) + if instr then + local ilen = s255(glyphS) + if glyphS.bad or instrS.p + ilen > instrS.e then + return nil, "instruction stream truncated" + end + w:u16be(ilen) + w:bytes(b, instrS.p, ilen) + instrS.p += ilen + end + else + return nil, "bad contour count " .. nc + end + if bboxS.bad then + return nil, "bbox stream truncated" + end + -- 4-byte alignment + while w.pos % 4 ~= 0 do + w:u8(0) + end + if w.pos > maxBytes then + return nil, "limit" + end + end + loca[numGlyphs + 1] = w.pos + if indexFormat == 0 and w.pos > 0x1FFFE then + indexFormat = 1 -- (head.indexToLocFormat is patched to match) + end + return { glyf = w:finish(), loca = loca, xMins = xMins, numGlyphs = numGlyphs, indexFormat = indexFormat }, nil +end + +-- hmtx transform (version 1): advances + the side bearings that were not dropped +local function hmtx(b: buffer, p: number, n: number, numGlyphs: number, numH: number, xMins: { number }): (buffer?, string?) + local s = stream(b, p, n) + local flags = su8(s) + local out = Bytes.writer(numH * 4 + (numGlyphs - numH) * 2) + local adv = table.create(numH, 0) + for i = 1, numH do + adv[i] = su16(s) + end + local lsb = table.create(numGlyphs, 0) + for i = 1, numH do + lsb[i] = if band(flags, 1) == 0 then si16(s) else (xMins[i] or 0) + end + for i = numH + 1, numGlyphs do + lsb[i] = if band(flags, 2) == 0 then si16(s) else (xMins[i] or 0) + end + if s.bad then + return nil, "hmtx transform truncated" + end + for i = 1, numH do + out:u16be(adv[i]) + out:u16be(lsb[i] % 65536) + end + for i = numH + 1, numGlyphs do + out:u16be(lsb[i] % 65536) + end + return out:finish(), nil +end + +function Rebuild.sfnt(r: Bytes.Reader, maxBytes: number): (buffer?, string?, string?) + if not r:match("wOF2") then + return nil, "bad signature", "corrupt" + end + local flavor = r:string(4) + local length = r:u32be() + local numTables = r:u16be() + r:skip(2) + local totalSfnt = r:u32be() + local totalComp = r:u32be() + r:skip(24) + if r.err then + return nil, "truncated header", "truncated" + end + if flavor == "ttcf" then + return nil, "font collections in WOFF2", "unsupported" + end + if length > r:size() then + return nil, "file shorter than its header says", "truncated" + end + if numTables == 0 or numTables > 1024 then + return nil, "bad table count", "corrupt" + end + local dir = {} + local streamTotal = 0 + for i = 1, numTables do + local flags = r:u8() + local tag = KNOWN[band(flags, 63) + 1] + if band(flags, 63) == 63 then + tag = r:string(4) + end + local version = rshift(flags, 6) + local orig = base128(r) + if not tag or not orig then + return nil, "bad table directory entry " .. i, if r.err then "truncated" else "corrupt" + end + local transformed = if tag == "glyf" or tag == "loca" then version == 0 else version ~= 0 + local tlen = orig + if transformed then + local t = base128(r) + if not t then + return nil, "bad transformLength", "corrupt" + end + tlen = t + end + if (tag == "glyf" or tag == "loca") and not transformed and version ~= 3 then + return nil, "bad glyf / loca transform version", "corrupt" + end + if transformed and tag ~= "glyf" and tag ~= "loca" and tag ~= "hmtx" then + return nil, "unknown transform of " .. tag, "unsupported" + end + dir[i] = { tag = tag, orig = orig, len = tlen, transformed = transformed, at = streamTotal } + streamTotal += tlen + if streamTotal > maxBytes or orig > maxBytes then + return nil, "limit", "limit" + end + end + local compAt = r.pos + if compAt + totalComp > r.limit then + return nil, "compressed data past the end", "truncated" + end + local data, berr = Brotli.decompress(r.buf, compAt, totalComp, { maxBytes = math.max(streamTotal, 1) }) + if not data then + local e = berr :: any + return nil, "brotli: " .. tostring(e.message), if e.code == "LIMIT" then "limit" else "corrupt" + end + if buffer.len(data) < streamTotal then + return nil, "decompressed stream shorter than the tables", "corrupt" + end + local byTag: { [string]: any } = {} + for _, e in dir do + byTag[e.tag] = e + end + local tables: { [string]: buffer } = {} + local g = byTag.glyf + local xMins: { number } = {} + local locaLong: boolean? = nil + if g and g.transformed then + if not byTag.loca then + return nil, "glyf without loca", "corrupt" + end + local res, gerr = glyf(data, g.at, g.len, maxBytes) + if not res then + return nil, "glyf: " .. tostring(gerr), if gerr == "limit" then "limit" else "corrupt" + end + tables.glyf = res.glyf + xMins = res.xMins + local short = res.indexFormat == 0 + local lw = Bytes.writer((res.numGlyphs + 1) * 4) + for _, o in res.loca do + if short then + lw:u16be(o // 2) + else + lw:u32be(o) + end + end + tables.loca = lw:finish() + locaLong = not short + end + for _, e in dir do + if e.tag == "glyf" or e.tag == "loca" then + if not e.transformed then + local t = buffer.create(e.len) + buffer.copy(t, 0, data, e.at, e.len) + tables[e.tag] = t + end + elseif e.tag == "hmtx" and e.transformed then + -- needs numGlyphs (maxp) and numberOfHMetrics (hhea) + local mp, hh = byTag.maxp, byTag.hhea + if not mp or not hh or mp.len < 6 or hh.len < 36 then + return nil, "hmtx transform without maxp / hhea", "corrupt" + end + local numGlyphs = readu8(data, mp.at + 4) * 256 + readu8(data, mp.at + 5) + local numH = readu8(data, hh.at + 34) * 256 + readu8(data, hh.at + 35) + if numH < 1 or numH > numGlyphs then + return nil, "bad numberOfHMetrics", "corrupt" + end + local t, herr = hmtx(data, e.at, e.len, numGlyphs, numH, xMins) + if not t then + return nil, herr, "corrupt" + end + tables.hmtx = t + else + local t = buffer.create(e.len) + buffer.copy(t, 0, data, e.at, e.len) + tables[e.tag] = t + end + end + -- head.indexToLocFormat must agree with the rebuilt loca + if locaLong ~= nil and tables.head and buffer.len(tables.head) >= 54 then + buffer.writeu8(tables.head, 50, 0) + buffer.writeu8(tables.head, 51, if locaLong then 1 else 0) + end + -- the sfnt: directory sorted by tag, tables 4-byte aligned + local tags = {} + for t in tables do + table.insert(tags, t) + end + table.sort(tags) + local n = #tags + local size = 12 + 16 * n + for _, t in tags do + size += (buffer.len(tables[t]) + 3) // 4 * 4 + end + if size > maxBytes then + return nil, "limit", "limit" + end + local out = buffer.create(size) + buffer.writestring(out, 0, flavor) + local es, sel = 1, 0 + while es * 2 <= n do + es *= 2 + sel += 1 + end + local function be16(o: number, v: number) + buffer.writeu8(out, o, rshift(v, 8)) + buffer.writeu8(out, o + 1, band(v, 255)) + end + local function be32(o: number, v: number) + buffer.writeu32(out, o, bit32.byteswap(v)) + end + be16(4, n) + be16(6, es * 16) + be16(8, sel) + be16(10, n * 16 - es * 16) + local p = 12 + 16 * n + for i, t in tags do + local tb = tables[t] + local d = 12 + (i - 1) * 16 + buffer.writestring(out, d, t) + be32(d + 4, 0) -- checksums are not recomputed + be32(d + 8, p) + be32(d + 12, buffer.len(tb)) + buffer.copy(out, p, tb) + p += (buffer.len(tb) + 3) // 4 * 4 + end + local _ = totalSfnt + return out, nil, nil +end + +return Rebuild +end +end + + + + + + host + --!optimize 2 +--!nocheck +-- rosetta chunk host (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 4 modules (0 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["host/Love"] = function() + +-- host/Love: LÖVE 11+. Files through love.filesystem (the game folder and the save directory), falling back to io for +-- paths outside them. ImageData is rgba8; SoundData is 16-bit. +local Err = __include("core/Err") +local Types = __include("Types") + +local Host = {} +Host.name = "love" +Host.hasFiles = true + +local function love(): any + return (_G :: any).love +end +local function io(): any + return (_G :: any).io +end +-- the FFI, when the build runs on LuaJIT (always, under LÖVE); called through _G so the build leaves it alone +local function ffi(): any + local req = (_G :: any).require + local ok, m = pcall(req, "ffi") + return if ok then m else nil +end + +function Host.readFile(path: string): (buffer?, Err.Err?) + local fs = love().filesystem + if fs.getInfo(path, "file") then + local s, msg = fs.read(path) + if type(s) ~= "string" then + return nil, Err.new(Err.IO, "cannot read " .. path .. ": " .. tostring(msg)) + end + return buffer.fromstring(s), nil + end + local f, msg = io().open(path, "rb") + if not f then + return nil, Err.new(Err.IO, "cannot open " .. path .. ": " .. tostring(msg)) + end + local s = f:read("*a") + f:close() + return buffer.fromstring(s), nil +end + +function Host.writeFile(path: string, data: buffer): (boolean, Err.Err?) + local s = buffer.tostring(data) + if string.sub(path, 1, 1) ~= "/" and not string.find(path, "^%a:[/\\]") then + local ok, msg = love().filesystem.write(path, s) + if not ok then + return false, Err.new(Err.IO, "cannot write " .. path .. ": " .. tostring(msg)) + end + return true, nil + end + local f, msg = io().open(path, "wb") + if not f then + return false, Err.new(Err.IO, "cannot create " .. path .. ": " .. tostring(msg)) + end + f:write(s) + f:close() + return true, nil +end + +function Host.exists(path: string): boolean + if love().filesystem.getInfo(path, "file") then + return true + end + local f = io().open(path, "rb") + if f then + f:close() + return true + end + return false +end + +function Host.toImageData(img: any): (any, Err.Err?) + if img.format ~= "rgba8" then + return nil, Err.new(Err.ARG, "toImageData: needs rgba8 pixels, got " .. tostring(img.format)) + end + local n = img.width * img.height * 4 + 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) + return id + end + local bytes = love().data.newByteData(buffer.readstring(img.pixels, 0, n)) + return love().image.newImageData(img.width, img.height, "rgba8", bytes) +end + +function Host.fromImageData(id: any): Types.Image + local w, h = id:getDimensions() + local img = Types.Image.new(w, h, "rgba8") + 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 + end + local s = id:getString() + buffer.writestring(img.pixels, 0, s, math.min(#s, w * h * 4)) + return img +end + +function Host.toSoundData(a: any): (any, Err.Err?) + local samples, frames, channels, rate = a.samples, a.frames, a.channels, a.sampleRate + if samples == nil then + local parts, total = {}, 0 + while true do + local out, n = a:read(65536) + if n == 0 then + break + end + local copy = buffer.create(n * channels * 4) + buffer.copy(copy, 0, out, 0, n * channels * 4) + table.insert(parts, copy) + total += n + end + samples = buffer.create(total * channels * 4) + local o = 0 + for _, p in parts do + buffer.copy(samples, o, p) + o += buffer.len(p) + end + frames = total + end + local sd = love().sound.newSoundData(math.max(frames, 1), rate, 16, channels) + local count = frames * channels + local F: any = ffi() + if F then + local p = F.cast("int16_t*", sd:getFFIPointer()) + for i = 0, count - 1 do + local v = math.clamp(buffer.readf32(samples, i * 4), -1, 1) + p[i] = math.floor(v * 32767 + 0.5) + end + else + for i = 0, count - 1 do + sd:setSample(i, math.clamp(buffer.readf32(samples, i * 4), -1, 1)) + end + end + return sd +end + +return Host +end +__FILES["host/LuaJIT"] = function() + +-- host/LuaJIT: plain LuaJIT (or any Lua with io): files through io.open. +local Err = __include("core/Err") + +local Host = {} +Host.name = "luajit" +Host.hasFiles = true + +local function io(): any + return (_G :: any).io +end + +function Host.readFile(path: string): (buffer?, Err.Err?) + local f, msg = io().open(path, "rb") + if not f then + return nil, Err.new(Err.IO, "cannot open " .. path .. ": " .. tostring(msg)) + end + local s = f:read("*a") + f:close() + if type(s) ~= "string" then + return nil, Err.new(Err.IO, "cannot read " .. path) + end + return buffer.fromstring(s), nil +end + +function Host.writeFile(path: string, data: buffer): (boolean, Err.Err?) + local f, msg = io().open(path, "wb") + if not f then + return false, Err.new(Err.IO, "cannot create " .. path .. ": " .. tostring(msg)) + end + local ok, werr = f:write(buffer.tostring(data)) + f:close() + if not ok then + return false, Err.new(Err.IO, "cannot write " .. path .. ": " .. tostring(werr)) + end + return true, nil +end + +function Host.exists(path: string): boolean + local f = io().open(path, "rb") + if f then + f:close() + return true + end + return false +end + +return Host +end +__FILES["host/Luau"] = function() + +-- host/Luau: the Luau CLI (and any embedding without io): no file system. Sources are buffers or strings. +local Err = __include("core/Err") + +local Host = {} +Host.name = "luau" +Host.hasFiles = false + +function Host.readFile(path: string): (buffer?, Err.Err?) + return nil, Err.new(Err.IO, "no file system on this host (luau): pass a buffer or a string, not the path " .. path) +end + +function Host.writeFile(path: string, _data: buffer): (boolean, Err.Err?) + return false, Err.new(Err.IO, "no file system on this host (luau): cannot write " .. path) +end + +function Host.exists(_path: string): boolean + return false +end + +return Host +end +__FILES["host/Roblox"] = function() + +-- host/Roblox: no file system (sources are buffers or strings, e.g. from HttpService or an asset); converts the +-- standard types to EditableImage / EditableMesh. +local Err = __include("core/Err") +local Types = __include("Types") + +local Host = {} +Host.name = "roblox" +Host.hasFiles = false + +function Host.readFile(path: string): (buffer?, Err.Err?) + return nil, Err.new(Err.IO, "Roblox has no file system: pass a buffer or a string, not the path " .. path) +end + +function Host.writeFile(path: string, _data: buffer): (boolean, Err.Err?) + return false, Err.new(Err.IO, "Roblox has no file system: cannot write " .. path .. " (use F.save(value) for a buffer)") +end + +function Host.exists(_path: string): boolean + return false +end + +function Host.toEditableImage(img: any): (any, Err.Err?) + if img.format ~= "rgba8" then + return nil, Err.new(Err.ARG, "toEditableImage: needs rgba8 pixels, got " .. tostring(img.format)) + end + local AssetService = (game :: any):GetService("AssetService") + local size = Vector2.new(img.width, img.height) + local ok, ei = pcall(function() + return AssetService:CreateEditableImage({ Size = size }) + end) + if not ok or not ei then + return nil, Err.new(Err.IO, "CreateEditableImage failed: " .. tostring(ei)) + end + ei:WritePixelsBuffer(Vector2.zero, size, img.pixels) + return ei +end + +-- EditableMesh limits (measured in Studio): ~20k triangles and 60k vertices each, 8 growable per client. +-- Roblox is y-up, right-handed, counter-clockwise front faces, as glTF; EditableMesh colours are sRGB, COLOR_0 linear. + +type MeshPage = { + first: number, -- the first triangle (0-based) of the primitive in this page + count: number, -- triangles + vertices: { number }, -- local vertex i (1-based) = source vertex vertices[i] (0-based) + corners: buffer, -- u32 local vertex (0-based) per corner, 3 per triangle + min: { number }, -- bounds of the page's positions (source units) + max: { number }, +} + +type PageData = { + vertexCount: number, + triangleCount: number, + positions: { number }, -- x, y, z per vertex: (source - origin) * scale + normals: { number }?, -- x, y, z per vertex (unit; NORMAL scaled by the inverse scale) + uvs: { number }?, -- u, v per vertex (TEXCOORD_<opts.texCoord or 0>) + colors: { number }?, -- r, g, b, a per vertex, sRGB 0..1 (from linear COLOR_0) + corners: buffer, -- as MeshPage.corners + centre: { number }, -- origin * scale: where the page's local (0, 0, 0) sits +} + +type MeshOptions = { + maxTriangles: number?, -- per page, default 20000 + maxVertices: number?, -- per page, default 60000 + doubleSided: boolean?, -- toEditableMesh adds a back face per triangle (meshPages counts them), default false + scale: (number | { number })?, -- uniform or per axis, default 1 + origin: { number }?, -- subtracted before scaling, default the page's bounds centre + texCoord: number?, -- the TEXCOORD_n set for uvs, default 0 + flipV: boolean?, -- v = 1 - v, default false + normals: boolean?, -- NORMAL when present, default true + uvs: boolean?, -- default true + colors: boolean?, -- COLOR_0 when present, default true + editableMesh: any?, -- toEditableMesh appends to this mesh instead of creating one + yield: (() -> ())?, -- toEditableMesh calls it every yieldEvery triangles (e.g. a frame budget check) + yieldEvery: number?, -- default 2000 +} + +local function cornerReader(prim: any): ((number) -> number)? + local idx = prim.indices + if not idx then + return function(i: number): number + return i + end + end + local get = Types.Scene.reader(idx) + if not get then + return nil + end + return function(i: number): number + return (get :: any)(i, 0) + end +end + +local function checkPrim(prim: any): (number, Err.Err?) + if type(prim) ~= "table" or type(prim.attributes) ~= "table" or type(prim.attributes.POSITION) ~= "table" then + return 0, Err.new(Err.ARG, "expected a Primitive with POSITION") + end + if (prim.mode or "triangles") ~= "triangles" then + return 0, Err.new(Err.ARG, "needs a triangle primitive (F.ops.mesh.merge or triangulate first), got " .. tostring(prim.mode)) + end + local n = if prim.indices then prim.indices.count else prim.attributes.POSITION.count + return n // 3, nil +end + +function Host.meshPages(prim: any, opts: MeshOptions?): ({ MeshPage }?, Err.Err?) + local tris, err = checkPrim(prim) + if err then + return nil, err + end + local o: MeshOptions = opts or {} + local per = if o.doubleSided then 2 else 1 + local maxT = math.max(1, (o.maxTriangles or 20000) // per) + local maxV = math.max(3, o.maxVertices or 60000) + local pos = prim.attributes.POSITION + local getP = Types.Scene.reader(pos) + local corner = cornerReader(prim) + if not getP or not corner then + return nil, Err.new(Err.ARG, "unsupported accessor type") + end + local nv = pos.count + local pages: { MeshPage } = {} + local t = 0 + while t < tris do + local map: { [number]: number } = {} + local verts: { number } = {} + local first = t + local lo = { math.huge, math.huge, math.huge } + local hi = { -math.huge, -math.huge, -math.huge } + local cs: { number } = {} + while t < tris and t - first < maxT do + local a, b, c = corner(t * 3), corner(t * 3 + 1), corner(t * 3 + 2) + if a >= nv or b >= nv or c >= nv or a < 0 or b < 0 or c < 0 then + return nil, Err.new(Err.ARG, string.format("triangle %d: vertex index out of range", t)) + end + local fresh = (if map[a] then 0 else 1) + (if map[b] or b == a then 0 else 1) + (if map[c] or c == a or c == b then 0 else 1) + if #verts + fresh > maxV and t > first then + break + end + for _, v in { a, b, c } do + local l = map[v] + if not l then + l = #verts + verts[l + 1] = v + map[v] = l + for k = 1, 3 do + local x = (getP :: any)(v, k - 1) + if x < lo[k] then + lo[k] = x + end + if x > hi[k] then + hi[k] = x + end + end + end + cs[#cs + 1] = l + end + t += 1 + end + local corners = buffer.create(#cs * 4) + for i, l in cs do + buffer.writeu32(corners, (i - 1) * 4, l) + end + pages[#pages + 1] = { first = first, count = t - first, vertices = verts, corners = corners, min = lo, max = hi } + end + return pages, nil +end + +local function toSrgb(c: number): number + c = math.clamp(c, 0, 1) + return if c <= 0.0031308 then c * 12.92 else 1.055 * c ^ (1 / 2.4) - 0.055 +end + +function Host.pageData(prim: any, page: MeshPage, opts: MeshOptions?): (PageData?, Err.Err?) + local _, err = checkPrim(prim) + if err then + return nil, err + end + if type(page) ~= "table" or type(page.vertices) ~= "table" or type(page.corners) ~= "buffer" then + return nil, Err.new(Err.ARG, "expected a MeshPage from meshPages") + end + local o: MeshOptions = opts or {} + local sc = o.scale or 1 + local sx, sy, sz + if type(sc) == "table" then + sx, sy, sz = sc[1] or 1, sc[2] or 1, sc[3] or 1 + else + sx, sy, sz = sc, sc, sc + end + local origin = o.origin + or { (page.min[1] + page.max[1]) / 2, (page.min[2] + page.max[2]) / 2, (page.min[3] + page.max[3]) / 2 } + local attrs = prim.attributes + local getP = Types.Scene.reader(attrs.POSITION) + local getN = if o.normals ~= false and attrs.NORMAL then Types.Scene.reader(attrs.NORMAL) else nil + local uvAcc = if o.uvs ~= false then attrs["TEXCOORD_" .. tostring(o.texCoord or 0)] else nil + local getT = if uvAcc then Types.Scene.reader(uvAcc) else nil + local colAcc = if o.colors ~= false then attrs.COLOR_0 else nil + local getC = if colAcc then Types.Scene.reader(colAcc) else nil + if not getP then + return nil, Err.new(Err.ARG, "unsupported POSITION accessor type") + end + local n = #page.vertices + local positions = table.create(n * 3, 0) + local normals = if getN then table.create(n * 3, 0) else nil + local uvs = if getT then table.create(n * 2, 0) else nil + local colors = if getC then table.create(n * 4, 1) else nil + local ox, oy, oz = origin[1], origin[2], origin[3] + local flip = o.flipV == true + local alpha = colAcc and colAcc.components >= 4 + for i, v in page.vertices do + local j = (i - 1) * 3 + positions[j + 1] = ((getP :: any)(v, 0) - ox) * sx + positions[j + 2] = ((getP :: any)(v, 1) - oy) * sy + positions[j + 3] = ((getP :: any)(v, 2) - oz) * sz + if normals then + local x, y, z = (getN :: any)(v, 0) / sx, (getN :: any)(v, 1) / sy, (getN :: any)(v, 2) / sz + local len = math.sqrt(x * x + y * y + z * z) + if len > 0 then + x, y, z = x / len, y / len, z / len + else + x, y, z = 0, 1, 0 + end + normals[j + 1], normals[j + 2], normals[j + 3] = x, y, z + end + if uvs then + local u, w = (getT :: any)(v, 0), (getT :: any)(v, 1) + uvs[(i - 1) * 2 + 1] = u + uvs[(i - 1) * 2 + 2] = if flip then 1 - w else w + end + if colors then + local k = (i - 1) * 4 + colors[k + 1] = toSrgb((getC :: any)(v, 0)) + colors[k + 2] = toSrgb((getC :: any)(v, 1)) + colors[k + 3] = toSrgb((getC :: any)(v, 2)) + colors[k + 4] = if alpha then math.clamp((getC :: any)(v, 3), 0, 1) else 1 + end + end + return { + vertexCount = n, + triangleCount = page.count, + positions = positions, + normals = normals, + uvs = uvs, + colors = colors, + corners = page.corners, + centre = { ox * sx, oy * sy, oz * sz }, + }, nil +end + +function Host.toEditableMesh(prim: any, page: MeshPage?, opts: MeshOptions?): (any, any) + local o: MeshOptions = opts or {} + local pg = page + if not pg then + local pages, err = Host.meshPages(prim, o) + if not pages then + return nil, err + end + if #pages ~= 1 then + return nil, Err.new(Err.LIMIT, string.format("toEditableMesh: %d pages: split with meshPages", #pages)) + end + pg = pages[1] + end + local data, err = Host.pageData(prim, pg :: MeshPage, o) + if not data then + return nil, err + end + local d = data :: PageData + local em = o.editableMesh + local own = em == nil + if own then + local AssetService = (game :: any):GetService("AssetService") + local ok, made = pcall(function() + return AssetService:CreateEditableMesh() + end) + if not ok or not made then + return nil, Err.new(Err.IO, "CreateEditableMesh failed (a client has 8 growable EditableMeshes): " .. tostring(made)) + end + em = made + end + local ok, perr = pcall(function() + local P, N, U, C = d.positions, d.normals, d.uvs, d.colors + local vids = table.create(d.vertexCount, 0) + local nids = if N then table.create(d.vertexCount, 0) else nil + local bids = if N and o.doubleSided then table.create(d.vertexCount, 0) else nil + local uids = if U then table.create(d.vertexCount, 0) else nil + local cids = if C then table.create(d.vertexCount, 0) else nil + local palette: { [string]: number } = {} + for i = 1, d.vertexCount do + local j = (i - 1) * 3 + vids[i] = em:AddVertex(Vector3.new(P[j + 1], P[j + 2], P[j + 3])) + if N and nids then + local n = Vector3.new(N[j + 1], N[j + 2], N[j + 3]) + nids[i] = em:AddNormal(n) + if bids then + bids[i] = em:AddNormal(-n) + end + end + if U and uids then + uids[i] = em:AddUV(Vector2.new(U[(i - 1) * 2 + 1], U[(i - 1) * 2 + 2])) + end + if C and cids then + local k = (i - 1) * 4 + local r, g, b, a = C[k + 1], C[k + 2], C[k + 3], C[k + 4] + local key = string.format("%d,%d,%d,%d", math.floor(r * 255 + 0.5), math.floor(g * 255 + 0.5), math.floor(b * 255 + 0.5), math.floor(a * 255 + 0.5)) + local id = palette[key] + if not id then + id = em:AddColor(Color3.new(r, g, b), a) + palette[key] = id + end + cids[i] = id + end + end + local corners = d.corners + local every = o.yieldEvery or 2000 + local yield = o.yield + for t = 0, d.triangleCount - 1 do + local a = buffer.readu32(corners, t * 12) + 1 + local b = buffer.readu32(corners, t * 12 + 4) + 1 + local c = buffer.readu32(corners, t * 12 + 8) + 1 + local f = em:AddTriangle(vids[a], vids[b], vids[c]) + if nids then + em:SetFaceNormals(f, { nids[a], nids[b], nids[c] }) + end + if uids then + em:SetFaceUVs(f, { uids[a], uids[b], uids[c] }) + end + if cids then + em:SetFaceColors(f, { cids[a], cids[b], cids[c] }) + end + if o.doubleSided then + local g = em:AddTriangle(vids[a], vids[c], vids[b]) + if bids then + em:SetFaceNormals(g, { bids[a], bids[c], bids[b] }) + end + if uids then + em:SetFaceUVs(g, { uids[a], uids[c], uids[b] }) + end + if cids then + em:SetFaceColors(g, { cids[a], cids[c], cids[b] }) + end + end + if yield and (t + 1) % every == 0 then + yield() + end + end + end) + if not ok then + if own then + pcall(function() + em:Destroy() + end) + end + return nil, Err.new(Err.IO, "EditableMesh: " .. tostring(perr)) + end + return em, d.centre +end + +return Host +end +end + + + + + + image_1 + --!optimize 2 +--!nocheck +-- rosetta chunk image_1 (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 26 modules (8 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["image/ani"] = function() + +-- image/ani: Windows animated cursor (RIFF "ACON": anih header, rate / seq chunks, LIST fram of ICO / CUR chunks). +-- Supports: the steps as img.frames (seq order; rate or iDispRate in 1/60 s jiffies), CUR hotspots, INFO title / +-- author; icons through opts.decodeImage / opts.encodeImage. Not supported: raw frame bitmaps (AF_ICON clear). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Riff = __include("containers/Riff") + +-- ------------------------------------------------------------------------------------------------ contract +local Ani = { + name = "ani", + category = "image", + extensions = { "ani" }, + mime = { "application/x-navi-animation" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Riff" }, + caps = { decode = true, encode = true, alpha = true, animation = true, frames = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + decodeImage: ((buffer) -> (Types.Image?, Err.Err?))?, + maxFrames: number?, -- default 10000 +} +type EncodeOptions = { + encodeImage: ((Types.Image, string) -> (buffer?, Err.Err?))?, +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Ani.sniff(r: Bytes.Reader): number + return if r:peek(4) == "RIFF" and r:peek(4, 8) == "ACON" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Ani.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local f, ferr = Riff.read(r) + if not f then + return nil, ferr + end + if f.form ~= "ACON" then + return nil, Err.new(Err.CORRUPT, "not an ACON form", r.base + 8) + end + local anih = Riff.find(f, "anih") + if not anih or anih.avail < 36 then + return nil, Err.new(Err.CORRUPT, "missing anih header", r.base + 12) + end + local a = anih.offset + local nFrames, nSteps = Riff.u32(f, a + 4), Riff.u32(f, a + 8) + local dispRate, flags = Riff.u32(f, a + 28), Riff.u32(f, a + 32) + local maxFrames = opts and opts.maxFrames or 10000 + if nSteps == 0 then + nSteps = nFrames + end + if nFrames > maxFrames or nSteps > maxFrames then + return nil, Err.new(Err.LIMIT, "too many frames", a + 4) + end + if bit32.band(flags, 1) == 0 then + return nil, Err.new(Err.UNSUPPORTED, "raw frame bitmaps (AF_ICON clear)", a + 32) + end + local decodeImage = opts and opts.decodeImage + if not decodeImage then + return nil, Err.new(Err.UNSUPPORTED, "icon frames need the decodeImage hook") + end + local icons: { Types.Image } = {} + for _, c in f.chunks do + if c.id == "LIST" and Riff.listType(f, c) == "fram" then + for _, ic in Riff.list(f, c) do + if ic.id == "icon" then + local sub = buffer.create(ic.avail) + buffer.copy(sub, 0, f.buf, ic.offset, ic.avail) + local ok, im, ierr = pcall(decodeImage, sub) + if not ok or not im then + return nil, Err.new(Err.CORRUPT, "frame " .. (#icons + 1) .. ": " .. tostring(if ok then ierr else im), ic.offset) + end + table.insert(icons, im :: Types.Image) + end + end + end + end + if #icons == 0 then + return nil, Err.new(Err.TRUNCATED, "no icon frames") + end + local rate = Riff.find(f, "rate") + local seq = Riff.find(f, "seq ") + local frames: { Types.Frame } = {} + for s = 0, nSteps - 1 do + local idx = s + if seq and seq.avail >= (s + 1) * 4 then + idx = Riff.u32(f, seq.offset + s * 4) + end + local im = icons[idx + 1] + if not im then + if s >= #icons and not seq then + break + end + return nil, Err.new(Err.CORRUPT, "step " .. s .. " names frame " .. idx) + end + local jiffies = dispRate + if rate and rate.avail >= (s + 1) * 4 then + jiffies = Riff.u32(f, rate.offset + s * 4) + end + table.insert(frames, { image = im, delay = jiffies / 60, x = 0, y = 0, dispose = "background", blend = "source" } :: Types.Frame) + end + local first = frames[1].image + local img = Types.Image.new(0, 0, first.format) + img.width, img.height, img.pixels = first.width, first.height, first.pixels + img.frames = frames + img.loops = 0 + img.meta.hotspot = first.meta.hotspot + local text: { [string]: string } = {} + for _, c in f.chunks do + if c.id == "LIST" and Riff.listType(f, c) == "INFO" then + for _, it in Riff.list(f, c) do + local key = if it.id == "INAM" then "title" elseif it.id == "IART" then "author" else nil + if key then + text[key] = (string.gsub(buffer.readstring(f.buf, it.offset, it.avail), "%z+$", "")) + end + end + end + end + if next(text) then + img.meta.text = text + end + img.meta.source = { format = "ani", frames = #icons, steps = #frames, sequence = seq ~= nil, rate = dispRate } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Ani.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "needs an Image") + end + local encodeImage = opts and opts.encodeImage + if not encodeImage then + return nil, Err.new(Err.UNSUPPORTED, "icon frames need the encodeImage hook") + end + local frames: { Types.Frame } = if type(img.frames) == "table" and #img.frames > 0 then img.frames else { { image = img, delay = 1 / 6, x = 0, y = 0, dispose = "background", blend = "source" } :: Types.Frame } + local w = Riff.writer("ACON") + local jiffies: { number } = {} + local same = true + for i, fr in frames do + jiffies[i] = math.max(1, math.floor((fr.delay or 0) * 60 + 0.5)) + same = same and jiffies[i] == jiffies[1] + end + local head = Bytes.writer(36) + head:u32le(36) + head:u32le(#frames) + head:u32le(#frames) + head:u32le(0) + head:u32le(0) + head:u32le(0) + head:u32le(0) + head:u32le(jiffies[1]) + head:u32le(1) + w:chunk("anih", head:finish()) + if not same then + local rw = Bytes.writer(#frames * 4) + for _, j in jiffies do + rw:u32le(j) + end + w:chunk("rate", rw:finish()) + end + local items = {} + for i, fr in frames do + local im = fr.image + local ok, data, err = pcall(encodeImage, im, "ico") + if not ok or not data then + return nil, Err.new(Err.ARG, "frame " .. i .. ": " .. tostring(if ok then err else data)) + end + table.insert(items, { "icon", data }) + end + w:list("fram", items) + return w:finish() +end + +return Ani +end +__FILES["image/blp"] = function() + +-- image/blp: Blizzard BLP textures (BLP1 Warcraft III, BLP2 World of Warcraft), from the wowdev.wiki BLP page. +-- Supports: mip 0 of BLP1 JPEG (4 components: BGRA, no colour conversion) / palette and BLP2 palette (1 / 4 / 8-bit +-- alpha, LSB first) / DXT1 / DXT3 / DXT5 / BGRA; writes BLP2 BGRA + mips. Not supported: BLP0 (.b00 mips), BLP2 JPEG. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Jpeg = __include("codecs/image/Jpeg") +local Bcn = __include("codecs/image/Bcn") + +-- ------------------------------------------------------------------------------------------------ contract +local Blp = { + name = "blp", + category = "image", + extensions = { "blp" }, + mime = { "image/x-blp" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Jpeg", "codecs/image/Bcn" }, + caps = { decode = true, encode = true, alpha = true, variants = { "blp1", "blp2" }, compressions = { "jpeg", "palette", "dxt1", "dxt3", "dxt5", "bgra" } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { maxPixels: number? } -- default 2^26 +type EncodeOptions = { mips: boolean? } -- default false + +-- ------------------------------------------------------------------------------------------------ constants +local readu8, readu32, writeu32, writeu8 = buffer.readu8, buffer.readu32, buffer.writeu32, buffer.writeu8 + +-- ------------------------------------------------------------------------------------------------ sniff +function Blp.sniff(r: Bytes.Reader): number + local m = r:peek(4) + return if m == "BLP1" or m == "BLP2" then 1 elseif m == "BLP0" then 0.8 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function swap(v: number, a: number): number + local b, g, r = v % 256, (v // 256) % 256, (v // 65536) % 256 + return r + g * 256 + b * 65536 + a * 16777216 +end + +local function alphaAt(b: buffer, p: number, depth: number, i: number): number + if depth == 8 then + return readu8(b, p + i) + elseif depth == 4 then + local v = readu8(b, p + i // 2) + local n = if i % 2 == 0 then v % 16 else v // 16 + return n * 17 + elseif depth == 1 then + local v = readu8(b, p + i // 8) + return if bit32.band(v, bit32.lshift(1, i % 8)) ~= 0 then 255 else 0 + end + return 255 +end + +function Blp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local size = r.limit - r.base + local b, base = r.buf, r.base + local magic = r:peek(4) + if magic == "BLP0" then + return nil, Err.new(Err.UNSUPPORTED, "BLP0 (mips in external files)", 0) + end + if magic ~= "BLP1" and magic ~= "BLP2" then + return nil, Err.new(if size < 4 then Err.TRUNCATED else Err.CORRUPT, "bad magic", 0) + end + local v2 = magic == "BLP2" + local headerSize = if v2 then 20 + 128 + 1024 else 28 + 128 + if size < headerSize then + return nil, Err.new(Err.TRUNCATED, "header", 0) + end + local kind = readu32(b, base + 4) -- BLP1: 0 = JPEG, 1 = palette; BLP2: 1 (0 = JPEG) + local compression = if v2 then readu8(b, base + 8) elseif kind == 0 then 0 else 1 + local alphaDepth = if v2 then readu8(b, base + 9) else readu32(b, base + 8) + local alphaType = if v2 then readu8(b, base + 10) else 0 + local w, h = readu32(b, base + 12), readu32(b, base + 16) + local mipsAt = if v2 then 20 else 28 + if w == 0 or h == 0 or w > 65535 or h > 65535 then + return nil, Err.new(Err.CORRUPT, "bad size " .. w .. " x " .. h, 12) + end + if w * h > (opts and opts.maxPixels or 2 ^ 26) then + return nil, Err.new(Err.LIMIT, "image too big") + end + local offs: { number }, lens: { number } = {}, {} + local mips = 0 + for i = 0, 15 do + offs[i + 1] = readu32(b, base + mipsAt + i * 4) + lens[i + 1] = readu32(b, base + mipsAt + 64 + i * 4) + if offs[i + 1] ~= 0 and lens[i + 1] ~= 0 then + mips += 1 + end + end + local at, len = offs[1], lens[1] + if at + len > size or len == 0 then + return nil, Err.new(Err.TRUNCATED, "mip 0 past the end", mipsAt) + end + local img = Types.Image.new(w, h) + local px = img.pixels + local n = w * h + local src = base + at + local name: string + if (not v2 and kind == 0) or (v2 and kind == 0) then + if v2 then + return nil, Err.new(Err.UNSUPPORTED, "BLP2 JPEG") + end + -- the JPEG header shared by the mips, then the mip's own data + if size < headerSize + 4 then + return nil, Err.new(Err.TRUNCATED, "JPEG header size", headerSize) + end + local hs = readu32(b, base + headerSize) + if hs > 0x10000 or headerSize + 4 + hs > size then + return nil, Err.new(Err.CORRUPT, "bad JPEG header size", headerSize) + end + local jpg = buffer.create(hs + len) + buffer.copy(jpg, 0, b, base + headerSize + 4, hs) + buffer.copy(jpg, hs, b, src, len) + local info = Jpeg.info(jpg) + local four = info ~= nil and (info :: any).components == 4 + local dec, err = Jpeg.decode(jpg, 0, nil, { raw = four, maxPixels = opts and opts.maxPixels }) + if not dec then + return nil, err + end + local dw, dh = math.min(dec.width, w), math.min(dec.height, h) + for y = 0, dh - 1 do + for x = 0, dw - 1 do + local v = readu32(dec.pixels, (y * dec.width + x) * 4) + local a = if four and alphaDepth > 0 then v // 16777216 else 255 + writeu32(px, (y * w + x) * 4, swap(v, a)) + end + end + name = "jpeg" + elseif compression == 1 then + local palAt = base + (if v2 then 148 else headerSize) + local dataAt = src + if not v2 then + -- BLP1: the palette follows the header; the mip offsets point past it + if headerSize + 1024 > size then + return nil, Err.new(Err.TRUNCATED, "palette", headerSize) + end + end + local depth = if v2 then alphaDepth else (if alphaDepth >= 8 then 8 else 0) + local need = n + (if depth == 8 then n elseif depth == 4 then (n + 1) // 2 elseif depth == 1 then (n + 7) // 8 else 0) + if at + need > size then + return nil, Err.new(Err.TRUNCATED, "palette mip past the end", at) + end + for i = 0, n - 1 do + local e = readu32(b, palAt + readu8(b, dataAt + i) * 4) + writeu32(px, i * 4, swap(e, if depth > 0 then alphaAt(b, dataAt + n, depth, i) else 255)) + end + name = "palette" + elseif compression == 2 then + local kindName = if alphaType == 7 then "bc3" elseif alphaType == 1 then "bc2" else "bc1" + local want: number = Bcn.size(kindName, w, h) or 0 + if len < want then + return nil, Err.new(Err.TRUNCATED, "DXT mip shorter than " .. want .. " bytes", mipsAt + 64) + end + local dec, err = Bcn.decode(kindName, b, src, w, h) + if not dec then + return nil, Err.from(err) + end + buffer.copy(px, 0, dec, 0, n * 4) + if kindName == "bc1" and alphaDepth == 0 then + for i = 0, n - 1 do + writeu8(px, i * 4 + 3, 255) + end + end + name = ({ bc1 = "dxt1", bc2 = "dxt3", bc3 = "dxt5" } :: { [string]: string })[kindName] + elseif compression == 3 then + if len < n * 4 then + return nil, Err.new(Err.TRUNCATED, "BGRA mip too short", mipsAt + 64) + end + for i = 0, n - 1 do + local v = readu32(b, src + i * 4) + writeu32(px, i * 4, swap(v, v // 16777216)) + end + name = "bgra" + else + return nil, Err.new(Err.UNSUPPORTED, "compression " .. tostring(compression)) + end + img.meta.source = { format = "blp", version = if v2 then 2 else 1, compression = name, alphaDepth = alphaDepth, alphaType = alphaType, mips = mips } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function halve(px: buffer, w: number, h: number): (buffer, number, number) + local nw, nh = math.max(1, w // 2), math.max(1, h // 2) + local out = buffer.create(nw * nh * 4) + for y = 0, nh - 1 do + for x = 0, nw - 1 do + for c = 0, 3 do + local s = 0 + for dy = 0, 1 do + for dx = 0, 1 do + local sx, sy = math.min(x * 2 + dx, w - 1), math.min(y * 2 + dy, h - 1) + s += readu8(px, (sy * w + sx) * 4 + c) + end + end + writeu8(out, (y * nw + x) * 4 + c, (s + 2) // 4) + end + end + end + return out, nw, nh +end + +function Blp.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "expected an rgba8 Image") + end + local w, h = img.width, img.height + if w < 1 or h < 1 or w > 65535 or h > 65535 then + return nil, Err.new(Err.ARG, "bad size") + end + local levels: { buffer } = { img.pixels } + local sizes: { { number } } = { { w, h } } + if opts and opts.mips then + local p, cw, ch = img.pixels, w, h + while (cw > 1 or ch > 1) and #levels < 16 do + p, cw, ch = halve(p, cw, ch) + table.insert(levels, p) + table.insert(sizes, { cw, ch }) + end + end + local out = Bytes.writer(1172 + w * h * 6) + out:string("BLP2") + out:u32le(1) + out:u8(3) -- uncompressed BGRA + out:u8(8) -- alpha depth + out:u8(8) -- alpha type + out:u8(if #levels > 1 then 1 else 0) + out:u32le(w) + out:u32le(h) + local at = 1172 + for i = 1, 16 do + local l = levels[i] + out:u32le(if l then at else 0) + if l then + at += buffer.len(l) + end + end + for i = 1, 16 do + local l = levels[i] + out:u32le(if l then buffer.len(l) else 0) + end + out:fill(0, 1024) + for _, l in levels do + local p = out:reserve(buffer.len(l)) + local o = out.buf + for i = 0, buffer.len(l) // 4 - 1 do + local v = readu32(l, i * 4) + writeu32(o, p + i * 4, swap(v, v // 16777216)) + end + out.pos = p + buffer.len(l) + end + return out:finish(), nil +end + +return Blp +end +__FILES["image/bmp"] = function() + + +-- image/bmp: Windows / OS/2 BMP; absorbed from bmp-luau b86aed6 (same author), new encoder. Supports: headers 12 / +-- 16..64 / 40 / 52 / 56 / 108 / 124, 1..32 bpp, BITFIELDS / ALPHABITFIELDS, RLE8 / RLE4, both row orders, Pillow's +-- leniency and mask scaling; writes 8 / 24 / 32 bpp as Pillow. Not supported: embedded JPEG / PNG, OS/2 Huffman, RLE24. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Pixels = __include("codecs/image/Pixels") + +-- ------------------------------------------------------------------------------------------------ contract +local Bmp = { + name = "bmp", + category = "image", + extensions = { "bmp", "dib" }, + mime = { "image/bmp", "image/x-bmp", "image/x-ms-bmp" }, + 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 }, +} + +-- ------------------------------------------------------------------------------------------------ types +type Info = { + width: number, + height: number, + bitsPerPixel: number, + compression: number, + topDown: boolean, + headerSize: number, + os2: boolean, +} + +type DecodeOptions = { + maxPixels: number?, -- default 2^26 +} +type EncodeOptions = { + bitDepth: (number | "auto")?, -- default "auto": 8 if opaque with <= 256 colours, else 24 if opaque, else 32 + header: ("v4" | "info")?, -- 32 bpp: "v4" (default, BITFIELDS) or "info" (BI_RGB, as Pillow) +} + +-- ------------------------------------------------------------------------------------------------ constants +local MAX_PIXELS = 2 ^ 26 +local COMPRESSION_NAMES = { [0] = "rgb", "rle8", "rle4", "bitfields", "jpeg", "png", "alphabitfields" } + +local readu8, readu16, readu32, readi32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi32 +local band, rshift, lshift, countrz = bit32.band, bit32.rshift, bit32.lshift, bit32.countrz + +local function whole(r: Bytes.Reader): buffer + if r.base == 0 and r.limit == buffer.len(r.buf) then + return r.buf + end + local n = r.limit - r.base + local b = buffer.create(n) + buffer.copy(b, 0, r.buf, r.base, n) + return b +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Bmp.sniff(r: Bytes.Reader): number + if r:peek(2) ~= "BM" then + return 0 + end + local n = r:peekU8(14) + math.max(r:peekU8(15), 0) * 256 + if r:peekU8(16) == 0 and r:peekU8(17) == 0 and (n == 12 or n == 16 or n == 40 or n == 52 or n == 56 or n == 64 or n == 108 or n == 124) then + return 0.9 + end + return 0.2 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function parseHeader(buf: buffer): (Info?, any) + local n = buffer.len(buf) + if n < 18 then + return nil, Err.new(Err.TRUNCATED, "file too short") + end + if readu8(buf, 0) ~= 0x42 or readu8(buf, 1) ~= 0x4D then + return nil, Err.new(Err.CORRUPT, "not a BMP file (no BM signature)") + end + local hs = readu32(buf, 14) + if hs < 12 or 14 + hs > n then + return nil, Err.new(Err.CORRUPT, "bad header size " .. hs) + end + local info: Info = { + width = 0, + height = 0, + bitsPerPixel = 0, + compression = 0, + topDown = false, + headerSize = hs, + os2 = false, + } + if hs == 12 then + info.width = readu16(buf, 18) + info.height = readu16(buf, 20) + info.bitsPerPixel = readu16(buf, 24) + info.os2 = true + else + if hs < 16 then + return nil, Err.new(Err.CORRUPT, "bad header size " .. hs) + end + info.width = readi32(buf, 18) + local h = readi32(buf, 22) + info.bitsPerPixel = readu16(buf, 28) + if hs >= 20 then + info.compression = readu32(buf, 30) + end + if h < 0 then + info.topDown = true + h = -h + end + info.height = h + -- OS/2 2.x headers: 16 / 64 bytes, or any size that is not a Windows one + info.os2 = not (hs == 40 or hs == 52 or hs == 56 or hs == 108 or hs == 124) + end + return info +end + +function Bmp.info(r: Bytes.Reader): (Info?, Err.Err?) + return parseHeader(whole(r)) +end + +-- v * 255 // m, as Pillow (browsers replicate the top bits, which can differ by 1) +local function scaleTable(m: number, empty: number): buffer + local t = buffer.create(m + 1) + if m == 0 then + buffer.writeu8(t, 0, empty) + else + for v = 0, m do + buffer.writeu8(t, v, (v * 255) // m) + end + end + return t +end + +-- a mask wider than 16 bits keeps its top 16 +local function channel(mask: number, empty: number): (number, number, buffer) + if mask == 0 then + return 0, 0, scaleTable(0, empty) + end + local sh = countrz(mask) + local m = rshift(mask, sh) + -- holes in the mask: use the lowest contiguous run of bits + local bits = 0 + while bits < 32 and band(m, lshift(1, bits)) ~= 0 do + bits += 1 + end + if bits > 16 then + sh += bits - 16 + bits = 16 + end + m = lshift(1, bits) - 1 + return sh, m, scaleTable(m, empty) +end + +function Bmp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local buf = whole(r) + local info, herr = parseHeader(buf) + if not info then + return nil, herr + end + local n = buffer.len(buf) + local hs, w, h, bpp, comp = info.headerSize, info.width, info.height, info.bitsPerPixel, info.compression + if w <= 0 or h <= 0 then + return nil, Err.new(Err.CORRUPT, "bad size " .. w .. "x" .. h) + end + local maxPixels = (opts and opts.maxPixels) or MAX_PIXELS + if w * h > maxPixels then + return nil, Err.new(Err.LIMIT, "image too large (" .. w .. "x" .. h .. ")") + end + if info.os2 and hs ~= 12 and (comp == 3 or comp == 4) then + return nil, Err.new(Err.UNSUPPORTED, "OS/2 Huffman / RLE24 compression is not supported") + end + if comp == 4 or comp == 5 then + return nil, Err.new(Err.UNSUPPORTED, "embedded " .. (if comp == 4 then "JPEG" else "PNG") .. " is not supported") + end + if comp > 6 then + return nil, Err.new(Err.CORRUPT, "unknown compression " .. comp) + end + local valid = (bpp == 1 or bpp == 2 or bpp == 4 or bpp == 8 or bpp == 16 or bpp == 24 or bpp == 32) + if not valid then + return nil, Err.new(Err.CORRUPT, "unsupported bit depth " .. bpp) + end + if (comp == 1 and bpp ~= 8) or (comp == 2 and bpp ~= 4) then + return nil, Err.new(Err.CORRUPT, "RLE compression " .. comp .. " with " .. bpp .. " bpp") + end + if (comp == 3 or comp == 6) and bpp ~= 16 and bpp ~= 24 and bpp ~= 32 then + return nil, Err.new(Err.CORRUPT, "BITFIELDS with " .. bpp .. " bpp") + end + + -- masks: in the v2+ header, or right after a 40-byte header + local palStart = 14 + hs + local rm: number, gm: number, bm: number, am: number = 0, 0, 0, 0 + local hasMasks = false + if comp == 3 or comp == 6 then + hasMasks = true + if hs >= 52 then + rm = readu32(buf, 54) + gm = readu32(buf, 58) + bm = readu32(buf, 62) + if hs >= 56 then + am = readu32(buf, 66) + end + else + local count = if comp == 6 then 4 else 3 + if palStart + count * 4 > n then + return nil, Err.new(Err.TRUNCATED, "truncated bit masks") + end + rm = readu32(buf, palStart) + gm = readu32(buf, palStart + 4) + bm = readu32(buf, palStart + 8) + if comp == 6 then + am = readu32(buf, palStart + 12) + end + palStart += count * 4 + end + if comp == 3 and hs < 56 then + am = 0 + end + if rm == 0 and gm == 0 and bm == 0 then + hasMasks = false -- all-zero masks: use the defaults + end + end + + local entrySize = if hs == 12 then 3 else 4 + local declared = if hs >= 36 then readu32(buf, 46) else 0 + local palCount = 0 + if bpp <= 8 then + palCount = if declared == 0 or declared > lshift(1, bpp) then lshift(1, bpp) else declared + end + local off = readu32(buf, 10) + local pixelEnd = palStart + palCount * entrySize + if off < palStart or off >= n then + -- bad bfOffBits: the pixels start after the palette as declared + off = math.min(pixelEnd, n) + elseif bpp <= 8 and off < pixelEnd then + -- palette shorter than declared: it ends where the pixels start + palCount = (off - palStart) // entrySize + end + palCount = math.max(0, math.min(palCount, (n - palStart) // entrySize)) + local pal = buffer.create(256 * 4) + for i = 0, 255 do + buffer.writeu32(pal, i * 4, 0xFF000000) + end + for i = 0, palCount - 1 do + local p = palStart + i * entrySize + local bb, gg, rr = readu8(buf, p), readu8(buf, p + 1), readu8(buf, p + 2) + buffer.writeu32(pal, i * 4, rr + gg * 256 + bb * 65536 + 0xFF000000) + end + + local img = Types.Image.new(w, h, "rgba8") + local pixels = img.pixels + img.meta.source = { + format = "bmp", + bitDepth = bpp, + compression = COMPRESSION_NAMES[comp], + topDown = info.topDown, + headerSize = hs, + paletteSize = palCount, + os2 = info.os2, + } + if bpp <= 8 and palCount > 0 then + local palette: { { number } } = {} + for i = 0, palCount - 1 do + palette[i + 1] = { readu8(pal, i * 4), readu8(pal, i * 4 + 1), readu8(pal, i * 4 + 2), 255 } + end + img.meta.palette = palette + end + if hs >= 40 then + local xp, yp = readi32(buf, 38), readi32(buf, 42) + if xp > 0 and yp > 0 then + img.meta.dpi = { x = xp * 0.0254, y = yp * 0.0254 } + end + end + + if comp == 1 or comp == 2 then + Pixels.rle(buf, off, n, comp == 2, pixels, w, h, info.topDown, pal) + return img, nil + end + + -- uncompressed: make sure every row is readable (a truncated file reads as zeros) + local stride = ((w * bpp + 31) // 32) * 4 + local need = stride * h + local src, base = buf, off + if off + need > n then + src = buffer.create(need) + buffer.copy(src, 0, buf, off, n - off) + base = 0 + end + + if bpp <= 8 then + Pixels.indexed(src, base, stride, bpp, pixels, w, h, info.topDown, pal) + elseif bpp == 24 and not hasMasks then + Pixels.bgr24(src, base, stride, pixels, w, h, info.topDown) + elseif bpp == 32 and (not hasMasks or (rm == 0xFF0000 and gm == 0xFF00 and bm == 0xFF and (am == 0xFF000000 or am == 0))) then + local aor = Pixels.bgra32(src, base, stride, pixels, w, h, info.topDown) + if aor == 0 or (hasMasks and am == 0) then + Pixels.opaque(pixels, w * h) + end + else + if not hasMasks then + if bpp == 16 then + rm, gm, bm, am = 0x7C00, 0x3E0, 0x1F, 0 + else + rm, gm, bm, am = 0xFF0000, 0xFF00, 0xFF, 0 + end + end + local shr, mr, tr = channel(rm, 0) + local shg, mg, tg = channel(gm, 0) + local shb, mb, tb = channel(bm, 0) + local sha, ma, ta = channel(am, 255) + local aor = + Pixels.masked(src, base, stride, bpp, pixels, w, h, info.topDown, shr, mr, tr, shg, mg, tg, shb, mb, tb, sha, ma, ta) + if ma ~= 0 and aor == 0 then + Pixels.opaque(pixels, w * h) + end + end + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Bmp.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "encode: needs an rgba8 Image") + end + local w, h = 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 w > 0x7FFFFFFF or h > 0x7FFFFFFF then + return nil, Err.new(Err.ARG, "encode: bad image size") + end + if buffer.len(img.pixels) < w * h * 4 then + return nil, Err.new(Err.ARG, "encode: the pixel buffer is smaller than width * height * 4") + end + local want = opts and opts.bitDepth or "auto" + if want ~= "auto" and want ~= 8 and want ~= 24 and want ~= 32 then + return nil, Err.new(Err.ARG, "encode: bitDepth must be 8, 24, 32 or auto") + end + local headerKind = opts and opts.header or "v4" + if headerKind ~= "v4" and headerKind ~= "info" then + return nil, Err.new(Err.ARG, "encode: header must be v4 or info") + end + local colours, alpha = Pixels.colours(img.pixels, w * h, 256) + local bpp: number + if want == "auto" then + bpp = if alpha then 32 elseif #colours <= 256 then 8 else 24 + else + bpp = want :: number + if bpp == 8 and #colours > 256 then + return nil, Err.new(Err.ARG, "encode: more than 256 colours for 8 bpp") + end + end + local v4 = bpp == 32 and headerKind == "v4" + local hs = if v4 then 108 else 40 + local stride = ((w * bpp + 31) // 32) * 4 + local palCount = if bpp == 8 then #colours else 0 + local off = 14 + hs + palCount * 4 + local imageSize = stride * h + if off + imageSize > 0x3FFFFFFF then + return nil, Err.new(Err.LIMIT, "encode: the file would be over 1 GiB") + end + local out = buffer.create(off + imageSize) + local o = Bytes.writer(off) + o:string("BM") + o:u32le(off + imageSize) + o:u32le(0) + o:u32le(off) + o:u32le(hs) + o:i32le(w) + o:i32le(h) + o:u16le(1) + o:u16le(bpp) + o:u32le(if v4 then 3 else 0) -- BI_BITFIELDS / BI_RGB + o:u32le(imageSize) + 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 = 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) + o:u32le(palCount) + o:u32le(palCount) + if v4 then + o:u32le(0x00FF0000) + o:u32le(0x0000FF00) + o:u32le(0x000000FF) + o:u32le(0xFF000000) + o:string("BGRs") -- LCS_sRGB (stored little-endian: 'sRGB') + o:fill(0, 36 + 12) -- endpoints, gamma + end + local idx: { [number]: number } = {} + for i, c in colours do + if i > palCount then + break + end + idx[c] = i - 1 + o:u8(band(rshift(c, 16), 255)) + o:u8(band(rshift(c, 8), 255)) + o:u8(band(c, 255)) + o:u8(0) + end + buffer.copy(out, 0, o.buf, 0, off) + if bpp == 8 then + Pixels.encode8(img.pixels, w, h, out, off, stride, idx) + elseif bpp == 24 then + Pixels.encode24(img.pixels, w, h, out, off, stride) + else + Pixels.encode32(img.pixels, w, h, out, off) + end + return out, nil +end + +return Bmp +end +__FILES["image/dds"] = function() + +-- image/dds: DirectDraw Surface (Microsoft DDS guide: DDS_HEADER, DDS_PIXELFORMAT, DDS_HEADER_DXT10). Supports: DXGI +-- formats with a pixel layout, legacy FourCC and bit-mask formats, mips, cube maps, arrays, volumes; writes rgba8 / BC1 +-- / BC3 / BC4 / BC5 / rgba16 / rgbaf32. Not supported: planar video (NV12, P010), P8, R1_UNORM, stencil formats. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Sniff = __include("core/Sniff") +local Types = __include("Types") +local Bcn = __include("codecs/image/Bcn") +local Texel = __include("codecs/image/Texel") +local Texture = __include("codecs/image/Texture") + +-- ------------------------------------------------------------------------------------------------ contract +local Dds = { + name = "dds", + category = "image", + extensions = { "dds" }, + mime = { "image/vnd-ms.dds", "image/x-dds" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/image/Bcn", "codecs/image/Texel", "codecs/image/Texture" }, + caps = { decode = true, encode = true, alpha = true, float = true, mipmaps = true, cubemap = true, compressed = { "bc1", "bc2", "bc3", "bc4", "bc5", "bc6h", "bc7" } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + native: boolean?, -- default false: rgba8 + mips: boolean?, -- default false + surfaces: boolean?, -- default true + maxPixels: number?, -- default 2^26, over every decoded surface +} +type EncodeOptions = { + pixelFormat: ("rgba8" | "bgra8" | "bc1" | "bc3" | "bc4" | "bc5" | "rgba16" | "rgba16f" | "rgba32f")?, + mips: boolean?, -- default false + dx10: boolean?, -- default: when the format needs it, or for arrays + cube: boolean?, -- default: when img.meta.layout == "cube" + alphaThreshold: number?, -- default 128 +} + +-- ------------------------------------------------------------------------------------------------ constants +-- DXGI_FORMAT -> texture format name, sRGB +local DXGI: { [number]: string } = { + [1] = "rgba32f", [2] = "rgba32f", [3] = "rgba32ui", [4] = "rgba32i", + [5] = "rgb32f", [6] = "rgb32f", [7] = "rgb32ui", [8] = "rgb32i", + [9] = "rgba16", [10] = "rgba16f", [11] = "rgba16", [12] = "rgba16ui", [13] = "rgba16s", [14] = "rgba16i", + [15] = "rg32f", [16] = "rg32f", [17] = "rg32ui", [18] = "rg32i", + [23] = "rgb10a2", [24] = "rgb10a2", [26] = "r11g11b10f", + [27] = "rgba8", [28] = "rgba8", [29] = "rgba8", [30] = "rgba8ui", [31] = "rgba8s", [32] = "rgba8i", + [33] = "rg16", [34] = "rg16f", [35] = "rg16", [36] = "rg16ui", [37] = "rg16s", [38] = "rg16i", + [39] = "r32f", [40] = "r32f", [41] = "r32f", [42] = "r32ui", [43] = "r32i", + [48] = "rg8", [49] = "rg8", [50] = "rg8ui", [51] = "rg8s", [52] = "rg8i", + [53] = "r16", [54] = "r16f", [55] = "r16", [56] = "r16", [57] = "r16ui", [58] = "r16s", [59] = "r16i", + [60] = "r8", [61] = "r8", [62] = "r8ui", [63] = "r8s", [64] = "r8i", [65] = "a8", + [67] = "rgb9e5", [68] = "rgbg", [69] = "grgb", + [70] = "bc1", [71] = "bc1", [72] = "bc1", [73] = "bc2", [74] = "bc2", [75] = "bc2", [76] = "bc3", [77] = "bc3", [78] = "bc3", + [79] = "bc4", [80] = "bc4", [81] = "bc4s", [82] = "bc5", [83] = "bc5", [84] = "bc5s", + [85] = "b5g6r5", [86] = "b5g5r5a1", [87] = "bgra8", [88] = "bgrx8", [90] = "bgra8", [91] = "bgra8", [92] = "bgrx8", [93] = "bgrx8", + [94] = "bc6h", [95] = "bc6h", [96] = "bc6hs", [97] = "bc7", [98] = "bc7", [99] = "bc7", + [100] = "ayuv", [107] = "yuy2", [115] = "b4g4r4a4", [191] = "a4b4g4r4", +} +local SRGB = { [29] = true, [72] = true, [75] = true, [78] = true, [91] = true, [93] = true, [99] = true } +-- legacy FourCC codes (strings and D3DFMT numbers) +local FOURCC: { [string]: string } = { + DXT1 = "bc1", DXT2 = "bc2", DXT3 = "bc2", DXT4 = "bc3", DXT5 = "bc3", RXGB = "bc3", + ATI1 = "bc4", BC4U = "bc4", BC4S = "bc4s", ATI2 = "bc5", BC5U = "bc5", BC5S = "bc5s", + YUY2 = "yuy2", UYVY = "uyvy", RGBG = "rgbg", GRGB = "grgb", +} +local D3DFMT: { [number]: string } = { + [36] = "rgba16", [110] = "rgba16s", [111] = "r16f", [112] = "rg16f", [113] = "rgba16f", + [114] = "r32f", [115] = "rg32f", [116] = "rgba32f", [117] = "rg8s", [60] = "rg8s", [63] = "rgba8s", [64] = "rg16s", +} +local FACES = { "+x", "-x", "+y", "-y", "+z", "-z" } +local MAGIC = "DDS " + +local DDSD_MIPMAPCOUNT, DDSD_DEPTH = 0x20000, 0x800000 +local DDPF_ALPHAPIXELS, DDPF_ALPHA, DDPF_FOURCC, DDPF_RGB, DDPF_LUMINANCE, DDPF_BUMPDUDV = 0x1, 0x2, 0x4, 0x40, 0x20000, 0x80000 +local CAPS2_CUBEMAP, CAPS2_VOLUME = 0x200, 0x200000 +local MISC_CUBE = 0x4 + +local band = bit32.band + +-- ------------------------------------------------------------------------------------------------ sniff +function Dds.sniff(r: Bytes.Reader): number + return math.max(Sniff.magic(r, MAGIC .. "\124\0\0\0"), Sniff.magic(r, MAGIC, 0, 0.6)) +end + +-- ------------------------------------------------------------------------------------------------ decode +type Info = { + width: number, + height: number, + depth: number, + mips: number, + format: string, + layout: string, -- "2d" | "cube" | "array" | "volume" + layers: number, + faces: { string }, -- in file order + srgb: boolean, + dxgi: number?, + fourcc: string?, + dataOffset: number, -- relative to the file start + alphaMode: number?, + premultiplied: boolean?, + masked: Texel.Desc?, -- legacy bit-mask formats (format = "masked" unless the masks have a name) +} + +local function u32(b: buffer, o: number): number + return buffer.readu32(b, o) +end + +function Dds.info(r: Bytes.Reader): (Info?, Err.Err?) + local b, o, n = r.buf, r.base, r.limit - r.base + if n < 128 or buffer.readstring(b, o, 4) ~= MAGIC then + return nil, Err.new(if n < 128 and n >= 4 and buffer.readstring(b, o, 4) == MAGIC then Err.TRUNCATED else Err.CORRUPT, "not a DDS file", o) + end + if u32(b, o + 4) ~= 124 then + return nil, Err.new(Err.CORRUPT, "bad header size " .. u32(b, o + 4), o + 4) + end + local flags = u32(b, o + 8) + local h, w = u32(b, o + 12), u32(b, o + 16) + local depth = u32(b, o + 24) + local mips = u32(b, o + 28) + local pfFlags, fourccNum = u32(b, o + 80), u32(b, o + 84) + local bitCount = u32(b, o + 88) + local rm, gm, bm, am = u32(b, o + 92), u32(b, o + 96), u32(b, o + 100), u32(b, o + 104) + local caps2 = u32(b, o + 112) + if w == 0 or h == 0 or w > 65536 or h > 65536 then + return nil, Err.new(Err.CORRUPT, string.format("bad size %d x %d", w, h), o + 12) + end + if band(flags, DDSD_MIPMAPCOUNT) == 0 and mips > 1 and band(u32(b, o + 108), 0x400000) == 0 then + mips = 1 -- a count without the flag or the caps bit: some writers leave garbage + end + mips = math.max(1, mips) + local maxMips = 1 + do + local m = math.max(w, h, depth) + while m > 1 do + m //= 2 + maxMips += 1 + end + end + if mips > maxMips then + return nil, Err.new(Err.CORRUPT, "more mip levels than the size allows", o + 28) + end + local info: Info = { + width = w, + height = h, + depth = 1, + mips = mips, + format = "", + layout = "2d", + layers = 1, + faces = {}, + srgb = false, + dataOffset = 128, + } + local volume = band(caps2, CAPS2_VOLUME) ~= 0 or band(flags, DDSD_DEPTH) ~= 0 and depth > 1 + if band(pfFlags, DDPF_FOURCC) ~= 0 then + local fourcc = buffer.readstring(b, o + 84, 4) + if fourcc == "DX10" then + if n < 148 then + return nil, Err.new(Err.TRUNCATED, "missing DX10 header", o + 128) + end + local dxgi, dim, misc, arr, misc2 = u32(b, o + 128), u32(b, o + 132), u32(b, o + 136), u32(b, o + 140), u32(b, o + 144) + info.dxgi = dxgi + info.dataOffset = 148 + local name = DXGI[dxgi] + if not name then + return nil, Err.new(Err.UNSUPPORTED, "DXGI format " .. dxgi, o + 128) + end + info.format = name + info.srgb = SRGB[dxgi] == true + info.alphaMode = band(misc2, 7) + info.premultiplied = band(misc2, 7) == 2 + info.layers = math.max(1, arr) + if info.layers > 4096 then + return nil, Err.new(Err.CORRUPT, "array size " .. arr, o + 140) + end + if dim == 4 then + volume = true + elseif dim ~= 2 and dim ~= 3 and dim ~= 0 then + return nil, Err.new(Err.CORRUPT, "bad resource dimension " .. dim, o + 132) + else + volume = false + end + if band(misc, MISC_CUBE) ~= 0 then + info.layout = "cube" + info.faces = table.clone(FACES) + elseif info.layers > 1 then + info.layout = "array" + end + else + info.fourcc = fourcc + local name = FOURCC[fourcc] or D3DFMT[fourccNum] + if not name then + return nil, Err.new(Err.UNSUPPORTED, "FourCC " .. string.format("%q", fourcc), o + 84) + end + info.format = name + info.premultiplied = fourcc == "DXT2" or fourcc == "DXT4" + end + elseif band(pfFlags, DDPF_RGB + DDPF_LUMINANCE + DDPF_ALPHA + DDPF_BUMPDUDV + 0x200) ~= 0 then + local bytes = bitCount // 8 + if bitCount % 8 ~= 0 or bytes < 1 or bytes > 4 then + return nil, Err.new(Err.UNSUPPORTED, bitCount .. "-bit pixels", o + 88) + end + local lum = band(pfFlags, DDPF_LUMINANCE) ~= 0 + local alphaOnly = band(pfFlags, DDPF_ALPHA) ~= 0 and band(pfFlags, DDPF_RGB + DDPF_LUMINANCE) == 0 + local a = if band(pfFlags, DDPF_ALPHAPIXELS + DDPF_ALPHA) ~= 0 then am else 0 + local d + if alphaOnly then + d = Texel.masked(bytes, 0, 0, 0, if am ~= 0 then am else 0xFF) + elseif band(pfFlags, DDPF_BUMPDUDV) ~= 0 then + d = nil -- signed bump maps: handled by the D3DFMT names when they come as FourCC + else + d = Texel.masked(bytes, rm, if lum then 0 else gm, if lum then 0 else bm, a, lum) + end + if not d then + return nil, Err.new(Err.UNSUPPORTED, "pixel format masks", o + 92) + end + local key = string.format("%d:%x:%x:%x:%x:%s", bitCount, rm, gm, bm, a, tostring(lum)) + local named = ({ + ["32:ff:ff00:ff0000:ff000000:false"] = "rgba8", + ["32:ff0000:ff00:ff:ff000000:false"] = "bgra8", + ["32:ff0000:ff00:ff:0:false"] = "bgrx8", + ["32:ff:ff00:ff0000:0:false"] = "rgbx8", + ["24:ff0000:ff00:ff:0:false"] = "bgr8", + ["24:ff:ff00:ff0000:0:false"] = "rgb8", + ["8:ff:0:0:0:true"] = "l8", + ["16:ffff:0:0:0:true"] = "l16", + } :: { [string]: string })[key] + info.format = named or "masked" + info.masked = d + else + return nil, Err.new(Err.UNSUPPORTED, string.format("pixel format flags 0x%x", pfFlags), o + 80) + end + if volume then + info.layout = "volume" + info.depth = math.max(1, depth) + if info.depth > 2048 then + return nil, Err.new(Err.CORRUPT, "depth " .. depth, o + 24) + end + elseif band(caps2, CAPS2_CUBEMAP) ~= 0 and not info.dxgi then + info.layout = "cube" + for i, f in FACES do + if band(caps2, bit32.lshift(0x400, i - 1)) ~= 0 then + table.insert(info.faces, f) + end + end + if #info.faces == 0 then + info.faces = table.clone(FACES) + end + end + return info, nil +end + +local function surfaceSize(info: any, w: number, h: number): number + if info.format == "masked" then + return (info.masked :: Texel.Desc).bytes * w * h + end + return Texture.size(info.format, w, h) :: number +end + +function Dds.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local info, ierr = Dds.info(r) + if not info then + return nil, ierr + end + local native = opts and opts.native or false + local wantMips = opts and opts.mips or false + local wantAll = not (opts and opts.surfaces == false) + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + local b, base = r.buf, r.base + local p = base + info.dataOffset + local limit = r.limit + local count = if info.layout == "cube" then #info.faces * info.layers else info.layers + local list: { Texture.Surface } = {} + local pixels = 0 + local stop = false + for layer = 0, count - 1 do + local w, h, d = info.width, info.height, info.depth + for level = 0, info.mips - 1 do + local size = surfaceSize(info, w, h) + for slice = 0, d - 1 do + local want = (level == 0 and (wantAll or (layer == 0 and slice == 0))) or (wantMips and layer == 0 and slice == 0) + if want then + if p + size > limit then + if level > 0 or layer > 0 or slice > 0 then + stop = true -- a cut mip chain / later surface: keep what decoded + break + end + return nil, Err.new(Err.TRUNCATED, "surface data runs past the end", p) + end + pixels += w * h + if pixels > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("over the %d pixel limit", maxPixels)) + end + local px, pf + if info.format == "masked" then + px, pf = Texel.decode(info.masked :: Texel.Desc, b, p, w, h, native) + else + px, pf = Texture.decode(info.format, b, p, w, h, native) + end + if not px then + return nil, Err.from(pf, p) + end + local face = if info.layout == "cube" then layer % #info.faces else 0 + table.insert(list, { level = level, layer = layer, face = face, slice = slice, image = Texture.image(px, pf, w, h) }) + end + p += size + end + if stop then + break + end + w, h, d = math.max(1, w // 2), math.max(1, h // 2), math.max(1, d // 2) + end + if stop then + break + end + end + local img = Texture.assemble(list, info.layout) + if not img then + return nil, Err.new(Err.TRUNCATED, "no surface data", base + info.dataOffset) + end + if info.layout == "cube" then + img.meta.faces = info.faces + end + if info.srgb then + img.meta.colorSpace = "srgb" + elseif string.find(info.format, "f$") or info.format == "bc6h" or info.format == "bc6hs" or info.format == "rgb9e5" then + img.meta.colorSpace = "linear" + end + img.meta.source = { + format = "dds", + pixelFormat = info.format, + dxgi = info.dxgi, + fourcc = info.fourcc, + mips = info.mips, + layers = info.layers, + depth = info.depth, + premultiplied = info.premultiplied, + } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local BYTES_PF: { [string]: number } = { rgba8 = 4, bgra8 = 4, rgba16 = 8, rgba16f = 8, rgba32f = 16 } +local DX10_OUT: { [string]: number } = { rgba8 = 28, bgra8 = 87, bc1 = 71, bc3 = 77, bc4 = 80, bc5 = 83, rgba16 = 11, rgba16f = 10, rgba32f = 2 } + +local function surface(img: Types.Image, f: string, opts: EncodeOptions?): (buffer?, Err.Err?) + local w, h, px = img.width, img.height, img.pixels + if f == "bc1" or f == "bc3" or f == "bc4" or f == "bc5" then + local blocks, err = Bcn.encode(f, px, w, h, opts and { alphaThreshold = opts.alphaThreshold } or nil) + if not blocks then + return nil, Err.new(Err.ARG, tostring(err)) + end + return blocks, nil + elseif f == "bgra8" then + local out = buffer.create(w * h * 4) + for i = 0, w * h - 1 do + local v = buffer.readu32(px, i * 4) + buffer.writeu32(out, i * 4, band(v, 0xFF00FF00) + band(bit32.rshift(v, 16), 0xFF) + bit32.lshift(band(v, 0xFF), 16)) + end + return out, nil + elseif f == "rgba16f" then + return Texture.toHalf(px, w * h), nil + end + local out = buffer.create(w * h * (BYTES_PF[f] :: number)) + buffer.copy(out, 0, px, 0, buffer.len(out)) + return out, nil +end + +local function writeHeader(out: Bytes.Writer, w: number, h: number, f: string, mips: number, dx10: boolean, layers: number, cube: boolean) + local blockFmt = f == "bc1" or f == "bc3" or f == "bc4" or f == "bc5" + out:string(MAGIC) + out:u32le(124) + local flags = 0x1007 + (if mips > 1 then DDSD_MIPMAPCOUNT else 0) + (if blockFmt then 0x80000 else 0x8) + out:u32le(flags) + out:u32le(h) + out:u32le(w) + out:u32le(if blockFmt then Texture.size(f, w, h) :: number else w * (BYTES_PF[f] :: number)) + out:u32le(0) + out:u32le(if mips > 1 then mips else 0) + out:fill(0, 44) + -- DDS_PIXELFORMAT + out:u32le(32) + if dx10 then + out:u32le(DDPF_FOURCC) + out:string("DX10") + out:fill(0, 20) + elseif blockFmt then + out:u32le(DDPF_FOURCC) + out:string(({ bc1 = "DXT1", bc3 = "DXT5", bc4 = "ATI1", bc5 = "ATI2" } :: { [string]: string })[f]) + out:fill(0, 20) + else + out:u32le(DDPF_RGB + DDPF_ALPHAPIXELS) + out:u32le(0) + out:u32le(32) + if f == "bgra8" then + out:u32le(0xFF0000) + out:u32le(0xFF00) + out:u32le(0xFF) + else + out:u32le(0xFF) + out:u32le(0xFF00) + out:u32le(0xFF0000) + end + out:u32le(0xFF000000) + end + out:u32le(0x1000 + (if mips > 1 then 0x400008 else 0) + (if cube then 0x8 else 0)) + out:u32le(if cube then 0xFE00 else 0) + out:fill(0, 12) + if dx10 then + out:u32le(DX10_OUT[f]) + out:u32le(3) + out:u32le(if cube then MISC_CUBE else 0) + out:u32le(if cube then layers // 6 else layers) + out:u32le(0) + end +end + +function Dds.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or type(img.pixels) ~= "buffer" or type(img.width) ~= "number" or img.width < 1 or img.height < 1 then + return nil, Err.new(Err.ARG, "needs an Image") + end + local pf = img.format + if pf ~= "rgba8" and pf ~= "rgba16" and pf ~= "rgbaf32" then + return nil, Err.new(Err.ARG, "needs an rgba8, rgba16 or rgbaf32 Image (got " .. tostring(pf) .. ")") + end + local f: string = (opts and opts.pixelFormat) or (if pf == "rgba8" then "rgba8" elseif pf == "rgba16" then "rgba16" else "rgba32f") + if not DX10_OUT[f] then + return nil, Err.new(Err.ARG, "unknown pixelFormat " .. tostring(f)) + end + local needs = if f == "rgba16" then "rgba16" elseif f == "rgba16f" or f == "rgba32f" then "rgbaf32" else "rgba8" + if pf ~= needs then + return nil, Err.new(Err.ARG, string.format("pixelFormat %s needs an %s Image", f, needs)) + end + local images: { Types.Image } = { img } + if img.frames and #img.frames > 1 then + images = {} + for i, fr in img.frames do + local fi = fr.image + if type(fi) ~= "table" or fi.width ~= img.width or fi.height ~= img.height or fi.format ~= pf then + return nil, Err.new(Err.ARG, "frame " .. i .. ": every surface needs the image's size and pixel format") + end + images[i] = fi + end + end + local cube = if opts and opts.cube ~= nil then opts.cube else (img.meta and img.meta.layout == "cube") + if cube and #images % 6 ~= 0 then + return nil, Err.new(Err.ARG, "a cube map needs 6 faces per layer") + end + local dx10 = (opts and opts.dx10) or f == "rgba16" or f == "rgba16f" or f == "rgba32f" or (#images > 1 and not (cube and #images == 6)) + local mips = 1 + if opts and opts.mips then + local m = math.max(img.width, img.height) + while m > 1 do + m //= 2 + mips += 1 + end + end + local out = Bytes.writer(img.width * img.height * 4 * #images + 200) + writeHeader(out, img.width, img.height, f, mips, dx10, #images, cube == true) + for _, im in images do + local level = im + for m = 1, mips do + local data, err = surface(level, f, opts) + if not data then + return nil, err + end + out:bytes(data) + if m < mips then + level = Texture.halve(level) + end + end + end + return out:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +Dds.DXGI = DXGI + +return Dds +end +__FILES["image/exr"] = function() + +-- image/exr: OpenEXR (openexr.com file layout docs; PIZ after OpenEXR, BSD-3-Clause: licenses/openexr-LICENSE.md). +-- Supports: single / multipart, scanline / tiled (mip / rip level 0, mips), NONE / RLE / ZIPS / ZIP / PIZ, HALF / FLOAT +-- / UINT, subsampling, layers; writes scanlines. Not supported: deep, PXR24 / B44(A) / DWA / HTJ2K / ZSTD. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Sniff = __include("core/Sniff") +local Types = __include("Types") +local Half = __include("codecs/image/Half") +local Codec = __include("image/exr/Codec") +local Piz = __include("image/exr/Piz") + +-- ------------------------------------------------------------------------------------------------ contract +local Exr = { + name = "exr", + category = "image", + extensions = { "exr" }, + mime = { "image/x-exr", "image/aces" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/image/Half", "codecs/compress/Deflate" }, + caps = { decode = true, encode = true, alpha = true, float = true, hdr = true, depths = { 16, 32 }, multipart = true, tiled = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + native: boolean?, -- default false: rgba8, round(clamp(v, 0, 1) ^ (1 / 2.2) * 255) + part: (number | string)?, -- 1-based index or name; default 1 + layer: string?, + mips: boolean?, -- default false + maxPixels: number?, -- default 2^26 +} +type EncodeOptions = { + compression: ("none" | "zips" | "zip")?, -- default "zip" + pixelType: ("half" | "float")?, -- default "half" + alpha: boolean?, -- default: when some alpha is not 1 + level: number?, -- 1..9, default 6 +} + +-- ------------------------------------------------------------------------------------------------ constants +local MAGIC = "\118\47\49\1" +local COMPRESSION: { [number]: string } = { [0] = "none", "rle", "zips", "zip", "piz", "pxr24", "b44", "b44a", "dwaa", "dwab", "htj2k256", "htj2k32", "zstd" } +local LINES: { [number]: number } = { [0] = 1, 1, 1, 16, 32, 16, 32, 32, 32, 256 } +local GAMMA = 1 / 2.2 + +local readu8, readu32, readi32, readf32, readstring = buffer.readu8, buffer.readu32, buffer.readi32, buffer.readf32, buffer.readstring + +-- ------------------------------------------------------------------------------------------------ sniff +function Exr.sniff(r: Bytes.Reader): number + return Sniff.magic(r, MAGIC) +end + +-- ------------------------------------------------------------------------------------------------ decode +type Channel = { name: string, kind: number, linear: boolean, xs: number, ys: number } +type Part = { + attrs: { [string]: any }, + channels: { Channel }, + compression: number, + box: { number }, -- data window xMin, yMin, xMax, yMax + display: { number }, + tiled: boolean, + tiles: { number }?, -- xSize, ySize, mode, rounding + name: string?, + type: string?, + chunks: number, + offsets: { number }, +} + +local function cstr(b: buffer, p: number, limit: number, max: number): (string?, number) + local q = p + while q < limit and q - p <= max do + if readu8(b, q) == 0 then + return readstring(b, p, q - p), q + 1 + end + q += 1 + end + return nil, q +end + +local function f32(b: buffer, o: number): number + return readf32(b, o) +end + +local function value(b: buffer, p: number, size: number, typ: string): any + if typ == "chlist" then + local list: { Channel } = {} + local q, stop = p, p + size + while q < stop and readu8(b, q) ~= 0 do + local name, nq = cstr(b, q, stop, 255) + if not name or nq + 16 > stop then + return nil + end + table.insert(list, { name = name, kind = readi32(b, nq), linear = readu8(b, nq + 4) ~= 0, xs = readi32(b, nq + 8), ys = readi32(b, nq + 12) }) + q = nq + 16 + end + return list + elseif typ == "compression" or typ == "lineOrder" or typ == "envmap" or typ == "deepImageState" then + return if size >= 1 then readu8(b, p) else nil + elseif typ == "box2i" then + return if size >= 16 then { readi32(b, p), readi32(b, p + 4), readi32(b, p + 8), readi32(b, p + 12) } else nil + elseif typ == "box2f" then + return if size >= 16 then { f32(b, p), f32(b, p + 4), f32(b, p + 8), f32(b, p + 12) } else nil + elseif typ == "v2i" then + return if size >= 8 then { readi32(b, p), readi32(b, p + 4) } else nil + elseif typ == "v2f" then + return if size >= 8 then { f32(b, p), f32(b, p + 4) } else nil + elseif typ == "v3f" then + return if size >= 12 then { f32(b, p), f32(b, p + 4), f32(b, p + 8) } else nil + elseif typ == "float" then + return if size >= 4 then f32(b, p) else nil + elseif typ == "double" then + return if size >= 8 then buffer.readf64(b, p) else nil + elseif typ == "int" then + return if size >= 4 then readi32(b, p) else nil + elseif typ == "string" then + return readstring(b, p, size) + elseif typ == "tiledesc" then + if size < 9 then + return nil + end + local m = readu8(b, p + 8) + return { readu32(b, p), readu32(b, p + 4), m % 16, m // 16 } + elseif typ == "chromaticities" then + if size < 32 then + return nil + end + local t = {} + for i = 0, 7 do + t[i + 1] = f32(b, p + i * 4) + end + return t + end + local raw = buffer.create(size) + buffer.copy(raw, 0, b, p, size) + return raw +end + +local function header(b: buffer, p: number, limit: number): ({ [string]: any }?, number, Err.Err?) + local attrs: { [string]: any } = {} + local types: { [string]: string } = {} + while true do + if p >= limit then + return nil, p, Err.new(Err.TRUNCATED, "header runs past the end", p) + end + if readu8(b, p) == 0 then + attrs._types = types + return attrs, p + 1, nil + end + local name, q = cstr(b, p, limit, 255) + if not name then + return nil, p, Err.new(Err.CORRUPT, "bad attribute name", p) + end + local typ, q2 = cstr(b, q, limit, 255) + if not typ then + return nil, p, Err.new(Err.CORRUPT, "bad attribute type", q) + end + if q2 + 4 > limit then + return nil, p, Err.new(Err.TRUNCATED, "attribute size runs past the end", q2) + end + local size = readi32(b, q2) + if size < 0 or q2 + 4 + size > limit then + return nil, p, Err.new(Err.TRUNCATED, "attribute " .. name .. " runs past the end", q2) + end + attrs[name] = value(b, q2 + 4, size, typ) + types[name] = typ + p = q2 + 4 + size + end +end + +local function levelSize(n: number, l: number, roundUp: boolean): number + local d = 2 ^ l + return math.max(1, if roundUp then math.ceil(n / d) else n // d) +end +local function levelCount(w: number, h: number, mode: number, roundUp: boolean): (number, number) + local function count(n: number): number + local c = 1 + while levelSize(n, c - 1, roundUp) > 1 do + c += 1 + end + return c + end + if mode == 0 then + return 1, 1 + elseif mode == 1 then + local c = count(math.max(w, h)) + return c, c + end + return count(w), count(h) +end + +local function chunkCount(pt: Part): number + local w, h = pt.box[3] - pt.box[1] + 1, pt.box[4] - pt.box[2] + 1 + if not pt.tiled then + return (h + LINES[pt.compression] - 1) // LINES[pt.compression] + end + local t = pt.tiles :: { number } + local tx, ty, mode, roundUp = t[1], t[2], t[3], t[4] == 1 + local lx, ly = levelCount(w, h, mode, roundUp) + local n = 0 + if mode == 2 then + for y = 0, ly - 1 do + for x = 0, lx - 1 do + n += math.ceil(levelSize(w, x, roundUp) / tx) * math.ceil(levelSize(h, y, roundUp) / ty) + end + end + else + for l = 0, lx - 1 do + n += math.ceil(levelSize(w, l, roundUp) / tx) * math.ceil(levelSize(h, l, roundUp) / ty) + end + end + return n +end + +type Info = { multipart: boolean, tiled: boolean, deep: boolean, parts: { Part }, dataStart: number } + +local function parse(r: Bytes.Reader): (Info?, Err.Err?) + local b, base, limit = r.buf, r.base, r.limit + if limit - base < 8 or readstring(b, base, 4) ~= MAGIC then + return nil, Err.new(Err.CORRUPT, "not an OpenEXR file", base) + end + local ver = readu32(b, base + 4) + if ver % 256 ~= 2 then + return nil, Err.new(Err.UNSUPPORTED, "version " .. ver % 256, base + 4) + end + local flags = ver // 256 + local tiledFlag, deep, multi = bit32.band(flags, 2) ~= 0, bit32.band(flags, 8) ~= 0, bit32.band(flags, 16) ~= 0 + local info: Info = { multipart = multi, tiled = tiledFlag, deep = deep, parts = {}, dataStart = 0 } + local p = base + 8 + repeat + local attrs, q, herr = header(b, p, limit) + if not attrs then + return nil, herr + end + p = q + local chans = attrs.channels + local box = attrs.dataWindow + if type(chans) ~= "table" or type(box) ~= "table" or type(attrs.compression) ~= "number" then + return nil, Err.new(Err.CORRUPT, "missing channels / dataWindow / compression", p) + end + local typ = attrs.type + local pt: Part = { + attrs = attrs, + channels = chans, + compression = attrs.compression, + box = box, + display = attrs.displayWindow or box, + tiled = if typ then (typ == "tiledimage" or typ == "deeptile") else tiledFlag, + tiles = attrs.tiles, + name = attrs.name, + type = typ, + chunks = 0, + offsets = {}, + } + if pt.tiled and type(pt.tiles) ~= "table" then + return nil, Err.new(Err.CORRUPT, "tiled part without tiles", p) + end + if box[3] < box[1] or box[4] < box[2] or box[3] - box[1] >= 2 ^ 24 or box[4] - box[2] >= 2 ^ 24 then + return nil, Err.new(Err.CORRUPT, "bad data window", p) + end + if pt.tiled and ((pt.tiles :: any)[1] < 1 or (pt.tiles :: any)[2] < 1) then + return nil, Err.new(Err.CORRUPT, "bad tile size", p) + end + for _, c in chans do + if c.xs < 1 or c.ys < 1 or c.kind < 0 or c.kind > 2 then + return nil, Err.new(Err.CORRUPT, "bad channel " .. c.name, p) + end + end + table.insert(info.parts, pt) + if #info.parts > 4096 then + return nil, Err.new(Err.LIMIT, "too many parts", p) + end + until not multi or (p < limit and readu8(b, p) == 0) + if multi then + p += 1 + end + for _, pt in info.parts do + local n = if type(pt.attrs.chunkCount) == "number" then pt.attrs.chunkCount else (if LINES[pt.compression] then chunkCount(pt) else 0) + if n < 0 or n > 2 ^ 24 then + return nil, Err.new(Err.CORRUPT, "bad chunk count", p) + end + pt.chunks = n + if p + n * 8 > limit then + return nil, Err.new(Err.TRUNCATED, "offset table runs past the end", p) + end + for i = 0, n - 1 do + pt.offsets[i + 1] = readu32(b, p + i * 8) + readu32(b, p + i * 8 + 4) * 4294967296 + end + p += n * 8 + end + info.dataStart = p - base + return info, nil +end + +function Exr.info(r: Bytes.Reader): (Info?, Err.Err?) + return parse(r) +end + +local SIZE = { [0] = 4, 2, 4 } + +local function samples(a: number, b: number, s: number): number + return b // s - (a - 1) // s +end + +type Target = { [number]: number } + +local function newPlane(pw: number, ph: number): buffer + local px = buffer.create(pw * ph * 16) + for i = 0, pw * ph - 1 do + buffer.writef32(px, i * 16 + 12, 1) + end + return px +end +local function block(part: Part, target: Target, data: buffer, dp: number, y0: number, y1: number, x0: number, bw: number, plane: buffer, pw: number, ph: number, ox: number, oy: number): Err.Err? + local p = dp + for y = y0, y1 do + for i, c in part.channels do + if y % c.ys == 0 then + local nx = if c.xs == 1 then bw else samples(x0, x0 + bw - 1, c.xs) + local sz = SIZE[c.kind] + if p + nx * sz > buffer.len(data) then + return Err.new(Err.CORRUPT, "block too short") + end + local k = target[i] + if k ~= nil then + local row = y - oy + if c.xs == 1 and c.ys == 1 and k < 4 then + Codec.samples(data, p, nx, c.kind, plane, (row * pw + (x0 - ox)) * 16 + k * 4, 16) + else + local tmp = buffer.create(nx * 4) + Codec.samples(data, p, nx, c.kind, tmp, 0, 4) + local first = (x0 + c.xs - 1) // c.xs * c.xs + for s = 0, nx - 1 do + local v = buffer.readf32(tmp, s * 4) + local sx = first + s * c.xs + for yy = row, math.min(row + c.ys - 1, ph - 1) do + for xx = sx - ox, math.min(sx - ox + c.xs - 1, pw - 1) do + local o = (yy * pw + xx) * 16 + if k == 4 then + buffer.writef32(plane, o, v) + buffer.writef32(plane, o + 4, v) + buffer.writef32(plane, o + 8, v) + else + buffer.writef32(plane, o + k * 4, v) + end + end + end + end + end + end + p += nx * sz + end + end + end + return nil +end + +local function unpack(b: buffer, comp: number, part: Part, p: number, size: number, raw: number, y0: number, y1: number, x0: number, bw: number): (buffer?, number, Err.Err?) + if size == raw or comp == 0 then + if size < raw then + return nil, 0, Err.new(Err.CORRUPT, "short uncompressed block", p) + end + return b, p, nil + end + local out, err + if comp == 1 then + out, err = Codec.rle(b, p, size, raw) + elseif comp == 2 or comp == 3 then + out, err = Codec.unzip(b, p, size, raw) + else + local chans: { Piz.Chan } = {} + for i, c in part.channels do + chans[i] = { nx = samples(x0, x0 + bw - 1, c.xs), ny = samples(y0, y1, c.ys), size = SIZE[c.kind] // 2, ys = c.ys } + end + out, err = Piz.decode(b, p, size, chans, y0, y1, raw) + end + if not out then + return nil, 0, Err.from(err, p) + end + return out, 0, nil +end + +local function rawSize(part: Part, y0: number, y1: number, x0: number, bw: number): number + local n = 0 + for y = y0, y1 do + for _, c in part.channels do + if y % c.ys == 0 then + n += samples(x0, x0 + bw - 1, c.xs) * SIZE[c.kind] + end + end + end + return n +end + +function Exr.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local info, perr = parse(r) + if not info then + return nil, perr + end + local b, base, limit = r.buf, r.base, r.limit + local want = opts and opts.part or 1 + local pt: Part? = nil + local partIndex = 0 + for i, p in info.parts do + if (type(want) == "number" and i == want) or (type(want) == "string" and p.name == want) then + pt, partIndex = p, i + end + end + if not pt then + return nil, Err.new(Err.ARG, "no part " .. tostring(want)) + end + local part = pt :: Part + if info.deep or (part.type and string.find(part.type, "deep")) then + return nil, Err.new(Err.UNSUPPORTED, "deep data") + end + local comp: number = part.compression + if comp > 4 then + return nil, Err.new(Err.UNSUPPORTED, "compression " .. (COMPRESSION[comp] or tostring(comp))) + end + local box = part.box + local xMin, yMin, xMax, yMax = box[1], box[2], box[3], box[4] + local w, h = xMax - xMin + 1, yMax - yMin + 1 + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + if w * h > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels)) + end + local prefix = if opts and opts.layer then opts.layer .. "." else "" + local target: Target = {} + local hasRgb = false + for i, c in part.channels do + local n = c.name + if string.sub(n, 1, #prefix) == prefix then + local s = string.sub(n, #prefix + 1) + local k = if s == "R" or s == "r" then 0 elseif s == "G" or s == "g" then 1 elseif s == "B" or s == "b" then 2 elseif s == "A" or s == "a" then 3 else nil + if k then + target[i] = k + hasRgb = hasRgb or k < 3 + end + end + end + if not hasRgb then + for i, c in part.channels do + if c.name == prefix .. "Y" then + target[i] = 4 + end + end + end + local multi = info.multipart + local offsets = part.offsets + local bad = false + for _, o in offsets do + if o < info.dataStart or base + o + 8 > limit then + bad = true + break + end + end + if bad then + -- rebuild from the chunk sequence (every part's chunks follow the tables; multipart chunks name their part) + offsets = {} + local p = base + info.dataStart + local total = 0 + for _, q in info.parts do + total += q.chunks + end + for _ = 1, total do + local pi = 1 + local at = p + if multi then + if p + 4 > limit then + break + end + pi = readi32(b, p) + 1 + p += 4 + end + local q = info.parts[pi] + if not q then + break + end + local head = if q.tiled then 20 else 8 + if p + head > limit then + break + end + local size = readi32(b, p + head - 4) + if size < 0 then + break + end + if pi == partIndex then + table.insert(offsets, at - base) + end + p += head + size + end + end + + local planes: { [number]: buffer } = { [0] = newPlane(w, h) } + local tiles = part.tiles + local roundUp = tiles ~= nil and tiles[4] == 1 + local wantMips = opts and opts.mips and tiles ~= nil and tiles[3] == 1 + + local lpb = LINES[comp] + for ci, off in offsets do + local p = base + off + if multi then + if p + 4 > limit then + return nil, Err.new(Err.TRUNCATED, "chunk past the end", p) + end + if readi32(b, p) ~= partIndex - 1 then + return nil, Err.new(Err.CORRUPT, "chunk of another part in this part's table", p) + end + p += 4 + end + if part.tiled then + if p + 20 > limit then + return nil, Err.new(Err.TRUNCATED, "tile header past the end", p) + end + local tx, ty, lx, ly, size = readi32(b, p), readi32(b, p + 4), readi32(b, p + 8), readi32(b, p + 12), readi32(b, p + 16) + p += 20 + local t = tiles :: { number } + local level = if lx == 0 and ly == 0 then 0 elseif wantMips and lx == ly then lx else -1 + if level >= 0 then + local lw, lh = levelSize(w, level, roundUp), levelSize(h, level, roundUp) + local x0, y0 = tx * t[1], ty * t[2] + if tx < 0 or ty < 0 or x0 >= lw or y0 >= lh then + return nil, Err.new(Err.CORRUPT, "tile outside the image", p) + end + if size < 0 or p + size > limit then + return nil, Err.new(Err.TRUNCATED, "tile data past the end", p) + end + local bw, bh = math.min(t[1], lw - x0), math.min(t[2], lh - y0) + local plane = planes[level] + if not plane then + plane = newPlane(lw, lh) + planes[level] = plane + end + -- tile coordinates are relative to the level's data window origin + local ax, ay = xMin + x0, yMin + y0 + local raw = rawSize(part, ay, ay + bh - 1, ax, bw) + local data, dp, uerr = unpack(b, comp, part, p, size, raw, ay, ay + bh - 1, ax, bw) + if not data then + return nil, uerr + end + local berr = block(part, target, data, dp, ay, ay + bh - 1, ax, bw, plane, lw, lh, xMin, yMin) + if berr then + return nil, berr + end + end + else + if p + 8 > limit then + return nil, Err.new(Err.TRUNCATED, "chunk header past the end", p) + end + local y, size = readi32(b, p), readi32(b, p + 4) + p += 8 + if y < yMin or y > yMax or (y - yMin) % lpb ~= 0 then + return nil, Err.new(Err.CORRUPT, "bad scanline block y " .. y, p - 8) + end + if size < 0 or p + size > limit then + if ci > 1 then + break -- a cut file: keep the lines that decoded (meta.truncated) + end + return nil, Err.new(Err.TRUNCATED, "block data past the end", p) + end + local y1 = math.min(y + lpb - 1, yMax) + local raw = rawSize(part, y, y1, xMin, w) + local data, dp, uerr = unpack(b, comp, part, p, size, raw, y, y1, xMin, w) + if not data then + return nil, uerr + end + local berr = block(part, target, data, dp, y, y1, xMin, w, planes[0], w, h, xMin, yMin) + if berr then + return nil, berr + end + end + end + + local native = opts and opts.native + local function finish(px: buffer, pw: number, ph: number): Types.Image + if native then + local img = Types.Image.new(0, 0, "rgbaf32") + img.width, img.height, img.pixels = pw, ph, px + return img + end + local img = Types.Image.new(pw, ph, "rgba8") + local o = img.pixels + for i = 0, pw * ph - 1 do + for c = 0, 3 do + local v = buffer.readf32(px, i * 16 + c * 4) + v = if v ~= v or v <= 0 then 0 elseif v >= 1 then 1 else v + buffer.writeu8(o, i * 4 + c, math.floor((if c < 3 then v ^ GAMMA else v) * 255 + 0.5)) + end + end + return img + end + local img = finish(planes[0], w, h) + if wantMips then + local mips = {} + local l = 1 + while planes[l] do + mips[l] = finish(planes[l], levelSize(w, l, roundUp), levelSize(h, l, roundUp)) + l += 1 + end + if #mips > 0 then + img.meta.mipmaps = mips + end + end + local names, parts = {}, {} + for i, c in part.channels do + names[i] = c.name + end + for i, p in info.parts do + parts[i] = { name = p.name or "", type = p.type or (if p.tiled then "tiledimage" else "scanlineimage") } + end + img.meta.colorSpace = "linear" + img.meta.dataWindow = { x = xMin, y = yMin, width = w, height = h } + local dw = part.display + img.meta.displayWindow = { x = dw[1], y = dw[2], width = dw[3] - dw[1] + 1, height = dw[4] - dw[2] + 1 } + local attrs = {} + for k, v in part.attrs do + if k ~= "_types" and (type(v) == "string" or type(v) == "number") then + attrs[k] = v + end + end + img.meta.attributes = attrs + local kinds = {} + for i, c in part.channels do + kinds[i] = ({ [0] = "uint", "half", "float" })[c.kind] + end + img.meta.source = { + format = "exr", + compression = COMPRESSION[comp], + channels = names, + pixelTypes = kinds, + part = partIndex, + parts = parts, + tiled = part.tiled, + lineOrder = part.attrs.lineOrder, + bitDepth = if kinds[1] == "half" then 16 else 32, + } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function attr(w: Bytes.Writer, name: string, typ: string, data: buffer) + w:cstring(name) + w:cstring(typ) + w:u32le(buffer.len(data)) + w:bytes(data) +end + +function Exr.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or type(img.pixels) ~= "buffer" or (img.format ~= "rgbaf32" and img.format ~= "rgba8") then + return nil, Err.new(Err.ARG, "needs an rgbaf32 or rgba8 Image") + end + local w, h = img.width, img.height + if type(w) ~= "number" or w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 then + return nil, Err.new(Err.ARG, "bad image size") + end + local compName = opts and opts.compression or "zip" + local comp = if compName == "none" then 0 elseif compName == "zips" then 2 elseif compName == "zip" then 3 else nil + if not comp then + return nil, Err.new(Err.ARG, "compression must be none, zips or zip") + end + local ptype = opts and opts.pixelType or "half" + if ptype ~= "half" and ptype ~= "float" then + return nil, Err.new(Err.ARG, "pixelType must be half or float") + end + local level = opts and opts.level or 6 + local n = w * h + local fl = buffer.create(n * 16) + if img.format == "rgbaf32" then + buffer.copy(fl, 0, img.pixels, 0, n * 16) + else + for i = 0, n * 4 - 1 do + local v = buffer.readu8(img.pixels, i) / 255 + buffer.writef32(fl, i * 4, if i % 4 < 3 then v ^ 2.2 else v) + end + end + local alpha = opts and opts.alpha + if alpha == nil then + alpha = false + for i = 0, n - 1 do + if buffer.readf32(fl, i * 16 + 12) ~= 1 then + alpha = true + break + end + end + end + local chans = if alpha then { { "A", 3 }, { "B", 2 }, { "G", 1 }, { "R", 0 } } else { { "B", 2 }, { "G", 1 }, { "R", 0 } } + local kind = if ptype == "half" then 1 else 2 + local sz = if kind == 1 then 2 else 4 + local lpb = LINES[comp] + local nblocks = (h + lpb - 1) // lpb + local hw = Bytes.writer(512) + hw:string(MAGIC) + hw:u32le(2) + local cl = Bytes.writer() + for _, c in chans do + cl:cstring(c[1]) + cl:u32le(kind) + cl:u8(0) + cl:fill(0, 3) + cl:u32le(1) + cl:u32le(1) + end + cl:u8(0) + attr(hw, "channels", "chlist", cl:finish()) + attr(hw, "compression", "compression", buffer.fromstring(string.char(comp))) + local bw = Bytes.writer(16) + bw:u32le(0) + bw:u32le(0) + bw:u32le(w - 1) + bw:u32le(h - 1) + local boxb = bw:finish() + attr(hw, "dataWindow", "box2i", boxb) + attr(hw, "displayWindow", "box2i", boxb) + attr(hw, "lineOrder", "lineOrder", buffer.fromstring("\0")) + local fw = Bytes.writer(4) + fw:f32le(1) + attr(hw, "pixelAspectRatio", "float", fw:finish()) + attr(hw, "screenWindowCenter", "v2f", buffer.create(8)) + attr(hw, "screenWindowWidth", "float", fw:finish()) + hw:u8(0) + local tableAt = hw:tell() + hw:fill(0, nblocks * 8) + local from = Half.fromFloat + for bi = 0, nblocks - 1 do + local y0 = bi * lpb + local y1 = math.min(y0 + lpb - 1, h - 1) + local raw = buffer.create((y1 - y0 + 1) * #chans * w * sz) + local o = 0 + for y = y0, y1 do + for _, c in chans do + local k = c[2] + for x = 0, w - 1 do + local v = buffer.readf32(fl, ((y * w + x) * 4 + k) * 4) + if kind == 1 then + buffer.writeu16(raw, o, from(v)) + else + buffer.writef32(raw, o, v) + end + o += sz + end + end + end + local data = raw + if comp ~= 0 then + local z = Codec.zip(raw, level) + if buffer.len(z) < buffer.len(raw) then + data = z + end + end + local at = hw:tell() + hw:setU32le(tableAt + bi * 8, at) + hw:u32le(y0) + hw:u32le(buffer.len(data)) + hw:bytes(data) + end + return hw:finish(), nil +end + +return Exr +end +__FILES["image/exr/Codec"] = @native function() + + + +-- image/exr/Codec: OpenEXR RLE / ZIP / ZIPS blocks and sample conversion (after ImfZip / ImfRle, BSD-3-Clause). +local Deflate = __include("codecs/compress/Deflate") +local Half = __include("codecs/image/Half") + +local Codec = {} + +local readu8, writeu8, readi8, readu16, readu32, readf32, writef32 = buffer.readu8, buffer.writeu8, buffer.readi8, buffer.readu16, buffer.readu32, buffer.readf32, buffer.writef32 +local HALF = Half.TABLE + +@native local function reconstruct(t: buffer, n: number): buffer + local prev = if n > 0 then readu8(t, 0) else 0 + for i = 1, n - 1 do + prev = (prev + readu8(t, i) - 128) % 256 + writeu8(t, i, prev) + end + local out = buffer.create(n) + local half = (n + 1) // 2 + for i = 0, half - 1 do + writeu8(out, i * 2, readu8(t, i)) + end + for i = 0, n - half - 1 do + writeu8(out, i * 2 + 1, readu8(t, half + i)) + end + return out +end + +@native function Codec.rle(src: buffer, p: number, n: number, outSize: number): (buffer?, string?) + local t = buffer.create(outSize) + local o, stop = 0, p + n + while p < stop do + local c = readi8(src, p) + p += 1 + if c < 0 then + local cnt = -c + if p + cnt > stop or o + cnt > outSize then + return nil, "bad RLE run" + end + buffer.copy(t, o, src, p, cnt) + p += cnt + o += cnt + else + if p >= stop or o + c + 1 > outSize then + return nil, "bad RLE run" + end + buffer.fill(t, o, readu8(src, p), c + 1) + p += 1 + o += c + 1 + end + end + if o ~= outSize then + return nil, "RLE data too short" + end + return reconstruct(t, outSize), nil +end + +@native function Codec.unzip(src: buffer, p: number, n: number, outSize: number): (buffer?, string?) + local t, err = Deflate.zlib(src, p, n, outSize) + if not t then + return nil, tostring(err) + end + if buffer.len(t) ~= outSize then + return nil, "zlib block has the wrong size" + end + return reconstruct(t, outSize), nil +end + +@native function Codec.zip(raw: buffer, level: number): buffer + local n = buffer.len(raw) + local t = buffer.create(n) + local half = (n + 1) // 2 + for i = 0, n - 1 do + local v = readu8(raw, i) + if i % 2 == 0 then + writeu8(t, i // 2, v) + else + writeu8(t, half + i // 2, v) + end + end + local prev = if n > 0 then readu8(t, 0) else 0 + for i = 1, n - 1 do + local v = readu8(t, i) + writeu8(t, i, (v - prev + 384) % 256) + prev = v + end + return Deflate.zlibCompress(t, { level = level }) :: buffer +end + +@native function Codec.samples(src: buffer, p: number, count: number, kind: number, dst: buffer, d: number, step: number): number + if kind == 1 then + for i = 0, count - 1 do + writef32(dst, d + i * step, HALF[readu16(src, p + i * 2)]) + end + return p + count * 2 + elseif kind == 2 then + for i = 0, count - 1 do + writef32(dst, d + i * step, readf32(src, p + i * 4)) + end + else + for i = 0, count - 1 do + writef32(dst, d + i * step, readu32(src, p + i * 4)) + end + end + return p + count * 4 +end + +return Codec +end +__FILES["image/exr/Piz"] = @native function() + + + +-- image/exr/Piz: OpenEXR PIZ decompressor (after ImfPizCompressor / ImfHuf / ImfWav, BSD-3-Clause). +local Piz = {} + +local readu8, readu16, writeu16, readu32 = buffer.readu8, buffer.readu16, buffer.writeu16, buffer.readu32 +local band, rshift, lshift = bit32.band, bit32.rshift, bit32.lshift + +local USHORT_RANGE, BITMAP_SIZE = 65536, 8192 +local HUF_ENCSIZE = 65537 +local DECBITS = 14 +local SHORT_ZEROCODE_RUN, LONG_ZEROCODE_RUN, SHORTEST_LONG_RUN = 59, 63, 6 + +-- ------------------------------------------------------------------------------------------------ Huffman +@native local function unpackTable(src: buffer, p: number, limit: number, im: number, iM: number, len: { number }): number? + local c, lc = 0, 0 + @native local function bits(n: number): number? + while lc < n do + if p >= limit then + return nil + end + c = c * 256 + readu8(src, p) + p += 1 + lc += 8 + end + lc -= n + local v = c // 2 ^ lc + c -= v * 2 ^ lc + return v + end + local i = im + while i <= iM do + local l = bits(6) + if not l then + return nil + end + if l == LONG_ZEROCODE_RUN then + local z = bits(8) + if not z then + return nil + end + z += SHORTEST_LONG_RUN + if i + z > iM + 1 then + return nil + end + for k = i, i + z - 1 do + len[k + 1] = 0 + end + i += z + elseif l >= SHORT_ZEROCODE_RUN then + local z = l - SHORT_ZEROCODE_RUN + 2 + if i + z > iM + 1 then + return nil + end + for k = i, i + z - 1 do + len[k + 1] = 0 + end + i += z + else + len[i + 1] = l + i += 1 + end + end + return p +end + +@native local function huffman(src: buffer, p: number, n: number, out: buffer, nRaw: number): string? + if n == 0 then + return if nRaw == 0 then nil else "empty Huffman data" + end + if n < 20 then + return "truncated Huffman header" + end + local im, iM, nBits = readu32(src, p), readu32(src, p + 4), readu32(src, p + 12) + if im >= HUF_ENCSIZE or iM >= HUF_ENCSIZE or im > iM then + return "bad Huffman symbol range" + end + local limit = p + n + local len = table.create(HUF_ENCSIZE, 0) + local q = unpackTable(src, p + 20, limit, im, iM, len) + if not q then + return "bad Huffman table" + end + if q + (nBits + 7) // 8 > limit then + return "truncated Huffman data" + end + -- canonical codes (OpenEXR's order: longest codes get the smallest values) + local count = table.create(59, 0) + for s = im, iM do + local l = len[s + 1] + if l > 58 then + return "bad Huffman code length" + end + count[l + 1] += 1 + end + local start = table.create(59, 0) + local c = 0 + for l = 58, 1, -1 do + local nc = (c + count[l + 1]) // 2 + start[l + 1] = c + c = nc + end + local fast = buffer.create(lshift(1, DECBITS) * 4) -- (symbol + 1) * 64 + length; 0 = long or invalid + local long: { [number]: { [number]: number } } = {} + local maxLong = 0 + for s = im, iM do + local l = len[s + 1] + if l > 0 then + local code = start[l + 1] + start[l + 1] = code + 1 + if l <= DECBITS then + local base = code * 2 ^ (DECBITS - l) + local v = (s + 1) * 64 + l + for k = base, base + 2 ^ (DECBITS - l) - 1 do + if k < lshift(1, DECBITS) then + buffer.writeu32(fast, k * 4, v) + end + end + else + if l > 52 then + return "unsupported: Huffman code longer than 52 bits" + end + local t = long[l] + if not t then + t = {} + long[l] = t + end + t[code] = s + maxLong = math.max(maxLong, l) + end + end + end + local nbytes = (nBits + 7) // 8 + local data = buffer.create(nbytes + 8) + buffer.copy(data, 0, src, q, nbytes) + local bp = 0 + local o = 0 + local rlc = iM + local mask = lshift(1, DECBITS) - 1 + while bp < nBits do + local byte = rshift(bp, 3) + local w = bit32.byteswap(readu32(data, byte)) + local peek = band(rshift(w, 32 - DECBITS - band(bp, 7)), mask) + local e = readu32(fast, peek * 4) + local sym: number, l: number = 0, 0 + if e ~= 0 then + sym = e // 64 - 1 + l = band(e, 63) + else + -- a long code: bit by bit from length 15 + sym = -1 + local code = 0 + for k = 0, maxLong - 1 do + local bitAt = bp + k + code = code * 2 + band(rshift(readu8(data, rshift(bitAt, 3)), 7 - band(bitAt, 7)), 1) + if k + 1 > DECBITS then + local t = long[k + 1] + local found: number? = if t then t[code] else nil + if found then + sym = found + l = k + 1 + break + end + end + end + if sym < 0 then + return "invalid Huffman code" + end + end + bp += l + if bp > nBits then + return "Huffman code past the end of the data" + end + if sym == rlc then + if bp + 8 > nBits then + return "truncated run length" + end + local b2 = bit32.byteswap(readu32(data, rshift(bp, 3))) + local cs = band(rshift(b2, 24 - band(bp, 7)), 255) + bp += 8 + if o + cs > nRaw then + return "too much Huffman data" + end + if o == 0 then + return "run length at the start" + end + local s = readu16(out, (o - 1) * 2) + for _ = 1, cs do + writeu16(out, o * 2, s) + o += 1 + end + else + if o >= nRaw then + return "too much Huffman data" + end + writeu16(out, o * 2, sym) + o += 1 + end + end + if o ~= nRaw then + return "not enough Huffman data" + end + return nil +end + +-- ------------------------------------------------------------------------------------------------ wavelet +@native local function wav2Decode(t: buffer, base: number, nx: number, ox: number, ny: number, oy: number, mx: number) + local w14 = mx < 16384 + local n = math.min(nx, ny) + local p = 1 + while p <= n do + p *= 2 + end + p //= 2 + local p2 = p + p //= 2 + @native local function dec(l: number, h: number): (number, number) + if w14 then + local ls = if l >= 32768 then l - 65536 else l + local hs = if h >= 32768 then h - 65536 else h + local ai = ls + hs % 2 + hs // 2 + return ai % 65536, (ai - hs) % 65536 + end + local bb = (l - rshift(h, 1)) % 65536 + return (h + bb - 32768) % 65536, bb + end + while p >= 1 do + local oy1, oy2, ox1, ox2 = oy * p, oy * p2, ox * p, ox * p2 + local py = base + local ey = base + oy * (ny - p2) + while py <= ey do + local px = py + local ex = py + ox * (nx - p2) + while px <= ex do + local p01 = px + ox1 + local p10 = px + oy1 + local p11 = p10 + ox1 + local i00, i10 = dec(readu16(t, px * 2), readu16(t, p10 * 2)) + local i01, i11 = dec(readu16(t, p01 * 2), readu16(t, p11 * 2)) + local a, b = dec(i00, i01) + writeu16(t, px * 2, a) + writeu16(t, p01 * 2, b) + local c, d = dec(i10, i11) + writeu16(t, p10 * 2, c) + writeu16(t, p11 * 2, d) + px += ox2 + end + if band(nx, p) ~= 0 then + local p10 = px + oy1 + local a, b = dec(readu16(t, px * 2), readu16(t, p10 * 2)) + writeu16(t, px * 2, a) + writeu16(t, p10 * 2, b) + end + py += oy2 + end + if band(ny, p) ~= 0 then + local px = py + local ex = py + ox * (nx - p2) + while px <= ex do + local p01 = px + ox1 + local a, b = dec(readu16(t, px * 2), readu16(t, p01 * 2)) + writeu16(t, px * 2, a) + writeu16(t, p01 * 2, b) + px += ox2 + end + end + p2 = p + p //= 2 + end +end + +-- ------------------------------------------------------------------------------------------------ decode +type Chan = { nx: number, ny: number, size: number, ys: number } + +@native function Piz.decode(src: buffer, p: number, n: number, chans: { Chan }, minY: number, maxY: number, outSize: number): (buffer?, string?) + local total = 0 + for _, c in chans do + total += c.nx * c.ny * c.size + end + if total * 2 ~= outSize then + return nil, "PIZ block size mismatch" + end + local out = buffer.create(outSize) + if total == 0 then + return out, nil + end + local limit = p + n + if p + 4 > limit then + return nil, "truncated PIZ header" + end + local minNZ, maxNZ = readu16(src, p), readu16(src, p + 2) + p += 4 + if maxNZ >= BITMAP_SIZE then + return nil, "bad PIZ bitmap range" + end + local bitmap = buffer.create(BITMAP_SIZE) + if minNZ <= maxNZ then + local cnt = maxNZ - minNZ + 1 + if p + cnt > limit then + return nil, "truncated PIZ bitmap" + end + buffer.copy(bitmap, minNZ, src, p, cnt) + p += cnt + end + local lut = buffer.create(USHORT_RANGE * 2) + local k = 0 + for i = 0, USHORT_RANGE - 1 do + if i == 0 or band(readu8(bitmap, rshift(i, 3)), lshift(1, band(i, 7))) ~= 0 then + writeu16(lut, k * 2, i) + k += 1 + end + end + local maxValue = k - 1 + if p + 4 > limit then + return nil, "truncated PIZ length" + end + local length = readu32(src, p) + p += 4 + if length > limit - p then + return nil, "truncated PIZ data" + end + local tmp = buffer.create(total * 2) + local herr = huffman(src, p, length, tmp, total) + if herr then + return nil, herr + end + local starts = table.create(#chans, 0) + local at = 0 + for i, c in chans do + starts[i] = at + for j = 0, c.size - 1 do + wav2Decode(tmp, at + j, c.nx, c.size, c.ny, c.nx * c.size, maxValue) + end + at += c.nx * c.ny * c.size + end + for i = 0, total - 1 do + writeu16(tmp, i * 2, readu16(lut, readu16(tmp, i * 2) * 2)) + end + local o = 0 + local cursor = table.clone(starts) + for y = minY, maxY do + for i, c in chans do + if y % c.ys == 0 then + local cnt = c.nx * c.size + buffer.copy(out, o, tmp, cursor[i] * 2, cnt * 2) + cursor[i] += cnt + o += cnt * 2 + end + end + end + return out, nil +end + +return Piz +end +__FILES["image/gif"] = function() + +-- image/gif: GIF87a / GIF89a, from the GIF89a spec (CompuServe 1990). Supports: every image, interlace, LZW code sizes +-- 1..8, transparency, GCE delays / disposal, NETSCAPE2.0 / ANIMEXTS1.0 loops, comments; writes quantized frames. Not +-- supported: the plain text extension, the aspect ratio, the user input flag, blend "source" frames. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Lzw = __include("codecs/compress/Lzw") +local Quantize = __include("codecs/image/Quantize") +local Types = __include("Types") +local Decode = __include("image/gif/Decode") + +-- ------------------------------------------------------------------------------------------------ contract +local Gif = { + name = "gif", + category = "image", + extensions = { "gif" }, + mime = { "image/gif" }, + 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 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + maxPixels: number?, -- default 2^26 + maxTotalPixels: number?, -- default 2^28 + maxFrames: number?, -- default: all +} +type EncodeOptions = { + maxColors: number?, -- 2..256, default 256 + method: ("mediancut" | "octree")?, -- default "mediancut" + dither: boolean?, -- Floyd-Steinberg, default false + loops: number?, -- 0 = forever, 1..65536; default img.loops + globalPalette: boolean?, -- default false +} + +-- ------------------------------------------------------------------------------------------------ constants +local readu8 = buffer.readu8 +local DISPOSE = { [0] = "none", [1] = "none", [2] = "background", [3] = "previous" } +local DISPOSE_CODE: { [string]: number } = { none = 1, background = 2, previous = 3 } + +-- ------------------------------------------------------------------------------------------------ sniff +function Gif.sniff(r: Bytes.Reader): number + local s = r:peek(6) + return if s == "GIF89a" or s == "GIF87a" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function colorTable(b: buffer, p: number, n: number): (buffer, { { number } }) + local t = buffer.create(1024) + local list: { { number } } = table.create(n) :: { { number } } + for i = 0, 255 do + buffer.writeu32(t, i * 4, 0xFF000000) + end + for i = 0, n - 1 do + local q = p + i * 3 + local r, g, bl = readu8(b, q), readu8(b, q + 1), readu8(b, q + 2) + buffer.writeu32(t, i * 4, r + g * 256 + bl * 65536 + 0xFF000000) + list[i + 1] = { r, g, bl, 255 } + end + return t, list +end + +function Gif.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + local maxTotal = opts and opts.maxTotalPixels or 2 ^ 28 + local maxFrames = opts and opts.maxFrames or math.huge + local sig = r:string(6) + local cw, ch = r:u16le(), r:u16le() + local flags, bg, aspect = r:u8(), r:u8(), r:u8() + if r.err then + return nil, r.err + end + if sig ~= "GIF89a" and sig ~= "GIF87a" then + return nil, Err.new(Err.CORRUPT, "bad signature", r.base) + end + if cw == 0 or ch == 0 then + return nil, Err.new(Err.CORRUPT, "zero canvas size", r.base + 6) + end + if cw * ch > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", cw, ch, maxPixels)) + end + local b = r.buf + local gct: buffer? = nil + local gpal: { { number } }? = nil + if bit32.band(flags, 0x80) ~= 0 then + local n = bit32.lshift(1, bit32.band(flags, 7) + 1) + if not r:need(n * 3) then + return nil, r.err + end + gct, gpal = colorTable(b, r.pos, n) + r.pos += n * 3 + end + local img = Types.Image.new(cw, ch, "rgba8") + local frames: { Types.Frame } = {} + local comments: { string } = {} + local loops: number? = nil + local total = 0 + local delay, dispose, trans = 0, 0, -1 + local truncated = false + local interlacedAny = false + local localTables = 0 + local minCode = 8 + local limit = r.limit + local function subBlocks(): (buffer?, number) + local p = r.pos + local n = 0 + while true do + if p >= limit then + return nil, p + end + local len = readu8(b, p) + if len == 0 then + break + end + if p + 1 + len > limit then + -- keep what is there: a truncated last block + n += limit - p - 1 + p = limit + local out = buffer.create(n) + local q, o = r.pos, 0 + while q < limit do + local l = math.min(readu8(b, q), limit - q - 1) + buffer.copy(out, o, b, q + 1, l) + o += l + q += 1 + l + end + return out, -1 + end + n += len + p += 1 + len + end + local out = buffer.create(n) + local q, o = r.pos, 0 + while q < p do + local l = readu8(b, q) + buffer.copy(out, o, b, q + 1, l) + o += l + q += 1 + l + end + return out, p + 1 + end + local function skipBlocks(): boolean + local p = r.pos + while p < limit do + local len = readu8(b, p) + if len == 0 then + r.pos = p + 1 + return true + end + p += 1 + len + end + r.pos = limit + return false + end + while true do + if r.pos >= limit then + truncated = true + break + end + local intro = r:u8() + if intro == 0x3B then + break + elseif intro == 0x21 then + local label = r:u8() + if r.err then + truncated = true + break + end + local p = r.pos + if label == 0xF9 and p + 6 <= limit and readu8(b, p) >= 4 then + local f = readu8(b, p + 1) + dispose = bit32.band(bit32.rshift(f, 2), 7) + delay = readu8(b, p + 2) + readu8(b, p + 3) * 256 + trans = if bit32.band(f, 1) ~= 0 then readu8(b, p + 4) else -1 + elseif label == 0xFF and p + 15 <= limit and readu8(b, p) == 11 then + local id = buffer.readstring(b, p + 1, 11) + if (id == "NETSCAPE2.0" or id == "ANIMEXTS1.0") and readu8(b, p + 12) >= 3 and readu8(b, p + 13) == 1 then + local rep = readu8(b, p + 14) + readu8(b, p + 15) * 256 + loops = if rep == 0 then 0 else rep + 1 -- the stored value repeats: plays = value + 1 + end + elseif label == 0xFE then + local data = subBlocks() + if data then + table.insert(comments, buffer.tostring(data)) + end + end + if not skipBlocks() then + truncated = true + break + end + elseif intro == 0x2C then + local fx, fy, fw, fh = r:u16le(), r:u16le(), r:u16le(), r:u16le() + local f = r:u8() + if r.err then + truncated = true + break + end + if fw * fh > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("a %d x %d frame is over the %d pixel limit", fw, fh, maxPixels), r.pos) + end + total += fw * fh + if total > maxTotal then + return nil, Err.new(Err.LIMIT, string.format("the frames add up to over %d pixels", maxTotal), r.pos) + end + local pal = gct + if bit32.band(f, 0x80) ~= 0 then + local n = bit32.lshift(1, bit32.band(f, 7) + 1) + if not r:need(n * 3) then + truncated = true + break + end + pal = colorTable(b, r.pos, n) + r.pos += n * 3 + localTables += 1 + end + local interlaced = bit32.band(f, 0x40) ~= 0 + interlacedAny = interlacedAny or interlaced + local mc = r:u8() + if r.err then + truncated = true + break + end + if mc < 1 or mc > 11 then + return nil, Err.new(Err.CORRUPT, "bad LZW minimum code size " .. mc, r.pos - 1) + end + minCode = mc + local data, nextPos = subBlocks() + if not data then + truncated = true + break + end + local n = fw * fh + local idx = buffer.create(n) + local got, lerr = Lzw.decode(data, 0, buffer.len(data), idx, 0, n, "gif", mc) + if got < n or nextPos < 0 then + truncated = true -- the missing pixels stay index 0, as most decoders show them + end + local _ = lerr -- a corrupt code ends the frame early (kept: what was decoded is shown) + local t = buffer.create(1024) + if pal then + buffer.copy(t, 0, pal) + else + -- no colour table at all: a grey ramp (what the spec leaves to the decoder) + for i = 0, 255 do + buffer.writeu32(t, i * 4, i + i * 256 + i * 65536 + 0xFF000000) + end + end + if trans >= 0 then + buffer.writeu32(t, trans * 4, 0) + end + local fimg = Types.Image.new(fw, fh, "rgba8") + Decode.toRgba(idx, fw, fh, interlaced, t, fimg.pixels) + if #frames == 0 then + Decode.draw(img.pixels, cw, ch, fimg.pixels, fx, fy, fw, fh) + end + table.insert(frames, { + image = fimg, + delay = delay / 100, + x = fx, + y = fy, + dispose = DISPOSE[dispose] or "none", + blend = if trans >= 0 then "over" else "source", + } :: Types.Frame) + delay, dispose, trans = 0, 0, -1 + if nextPos < 0 then + break + end + r.pos = nextPos + if #frames >= maxFrames then + break + end + else + if #frames == 0 then + return nil, Err.new(Err.CORRUPT, string.format("bad block introducer 0x%02x", intro), r.pos - 1) + end + truncated = true + break + end + end + if #frames == 0 then + return nil, Err.new(Err.TRUNCATED, "no image data", r.pos) + end + if #frames > 1 then + img.frames = frames + img.loops = loops or 1 + else + img.loops = loops or 0 + end + img.meta.palette = gpal + img.meta.background = bg + if #comments > 0 then + img.meta.text = { comment = table.concat(comments, "\n") } + end + if truncated then + img.meta.truncated = true + end + img.meta.source = { + format = "gif", + version = string.sub(sig, 4), + bitDepth = minCode, + colorType = "palette", + frames = #frames, + interlaced = interlacedAny, + localPalettes = localTables, + aspect = aspect, + loopExtension = loops ~= nil, + } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function validImage(i: any): boolean + return type(i) == "table" and i.format == "rgba8" and type(i.pixels) == "buffer" and type(i.width) == "number" and type(i.height) == "number" and i.width >= 1 and i.height >= 1 and i.width <= 65535 and i.height <= 65535 and i.width % 1 == 0 and i.height % 1 == 0 and buffer.len(i.pixels) >= i.width * i.height * 4 +end + +local function hasTransparency(px: buffer, n: number): boolean + for i = 0, n - 1 do + if readu8(px, i * 4 + 3) < 128 then + return true + end + end + return false +end + +local function writeTable(w: Bytes.Writer, pal: { { number } }): number + local bits = 1 + while bit32.lshift(1, bits) < #pal do + bits += 1 + end + for i = 1, bit32.lshift(1, bits) do + local c = pal[i] + if c then + w:u8(c[1]) + w:u8(c[2]) + w:u8(c[3]) + else + w:fill(0, 3) + end + end + return bits +end + +local function tableBits(n: number): number + local bits = 1 + while bit32.lshift(1, bits) < n do + bits += 1 + end + return bits +end + +function Gif.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if not validImage(img) then + return nil, Err.new(Err.ARG, "needs an rgba8 Image of 1..65535 x 1..65535 pixels") + end + local maxColors = opts and opts.maxColors or 256 + if type(maxColors) ~= "number" or maxColors < 2 or maxColors > 256 then + return nil, Err.new(Err.ARG, "maxColors must be 2..256") + end + maxColors = math.floor(maxColors) + local method = opts and opts.method or "mediancut" + if method ~= "mediancut" and method ~= "octree" then + return nil, Err.new(Err.ARG, "method must be mediancut or octree") + end + local dither = opts and opts.dither or false + local list: { Types.Frame } = {} + if type(img.frames) == "table" and #(img.frames :: any) > 0 then + for i, f in img.frames :: { Types.Frame } do + if type(f) ~= "table" or not validImage(f.image) then + return nil, Err.new(Err.ARG, "frame " .. i .. ": needs an rgba8 image") + end + local x, y = f.x or 0, f.y or 0 + if type(x) ~= "number" or type(y) ~= "number" or x < 0 or y < 0 or x + f.image.width > 65535 or y + f.image.height > 65535 then + return nil, Err.new(Err.ARG, "frame " .. i .. ": bad position") + end + table.insert(list, f) + end + else + list[1] = { image = img, x = 0, y = 0, delay = 0, dispose = "none", blend = "source" } + end + local animated = #list > 1 + local loops = opts and opts.loops or img.loops or 0 + if type(loops) ~= "number" or loops < 0 or loops > 65536 or loops % 1 ~= 0 then + return nil, Err.new(Err.ARG, "loops must be 0..65536") + end + local shared = (opts and opts.globalPalette) or not animated + local qopts: Quantize.PaletteOptions = { method = method, dither = dither } + local globalPal: { { number } }? = nil + local globalTrans = false + if shared then + local npx = 0 + for _, f in list do + npx += f.image.width * f.image.height + end + local all = buffer.create(npx * 4) + local o = 0 + for _, f in list do + local n = f.image.width * f.image.height * 4 + buffer.copy(all, o, f.image.pixels, 0, n) + o += n + end + globalTrans = hasTransparency(all, npx) + local pal = Quantize.palette(all, npx, 1, if globalTrans then maxColors - 1 else maxColors, qopts) + if #pal == 0 then + pal = { { 0, 0, 0, 255 } } + end + if globalTrans then + table.insert(pal, { 0, 0, 0, 0 }) + end + globalPal = pal + end + local w = Bytes.writer(img.width * img.height + 1024) + w:string("GIF89a") + w:u16le(img.width) + w:u16le(img.height) + if globalPal then + w:u8(0x80 + 0x70 + (tableBits(#globalPal) - 1)) + w:u8(0) + w:u8(0) + writeTable(w, globalPal) + else + w:u8(0x70) + w:u8(0) + w:u8(0) + end + if animated and loops ~= 1 then + w:u8(0x21) + w:u8(0xFF) + w:u8(11) + w:string("NETSCAPE2.0") + w:u8(3) + w:u8(1) + w:u16le(if loops == 0 then 0 else loops - 1) + w:u8(0) + end + local text = img.meta and img.meta.text + local comment = text and (text.comment or text.Comment) + if type(comment) == "string" and #comment > 0 then + w:u8(0x21) + w:u8(0xFE) + for i = 1, #comment, 255 do + local part = string.sub(comment, i, i + 254) + w:u8(#part) + w:string(part) + end + w:u8(0) + end + for _, f in list do + local fi = f.image + local fw, fh = fi.width, fi.height + local n = fw * fh + local pal: { { number } } + local tidx: number? = nil + if globalPal then + pal = globalPal + if globalTrans then + tidx = #pal - 1 + end + else + local tr = hasTransparency(fi.pixels, n) + pal = Quantize.palette(fi.pixels, fw, fh, if tr then maxColors - 1 else maxColors, qopts) + if #pal == 0 then + pal = { { 0, 0, 0, 255 } } + end + if tr then + table.insert(pal, { 0, 0, 0, 0 }) + tidx = #pal - 1 + end + end + local idx = Quantize.map(fi.pixels, fw, fh, pal, { dither = dither, transparentIndex = tidx }) + -- the Graphic Control Extension: always for animations, else only for transparency + if animated or tidx then + local d = DISPOSE_CODE[f.dispose or "none"] or 1 + w:u8(0x21) + w:u8(0xF9) + w:u8(4) + w:u8(d * 4 + (if tidx then 1 else 0)) + w:u16le(math.clamp(math.floor((f.delay or 0) * 100 + 0.5), 0, 65535)) + w:u8(tidx or 0) + w:u8(0) + end + w:u8(0x2C) + w:u16le(f.x or 0) + w:u16le(f.y or 0) + w:u16le(fw) + w:u16le(fh) + local bits + if globalPal then + w:u8(0) + bits = tableBits(#globalPal) + else + bits = tableBits(#pal) + w:u8(0x80 + bits - 1) + writeTable(w, pal) + end + local mc = math.max(2, bits) + w:u8(mc) + local codes = Lzw.encode(idx, 0, n, "gif", mc) + local cl = buffer.len(codes) + local p = 0 + while p < cl do + local l = math.min(255, cl - p) + w:u8(l) + w:bytes(codes, p, l) + p += l + end + w:u8(0) + end + w:u8(0x3B) + return w:finish(), nil +end + +return Gif +end +__FILES["image/gif/Decode"] = @native function() + + + +-- image/gif/Decode: GIF frame pixels: palette indexes (plain or interlaced) to rgba8, drawn onto the canvas. +local readu8, readu32, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu32 + +local Decode = {} + +-- interlace passes: every 8th row from 0, every 8th from 4, every 4th from 2, every 2nd from 1 +@native local function interlacedRow(fh: number): { number } + local map = table.create(fh, 0) + local r = 0 + for _, pass in { { 0, 8 }, { 4, 8 }, { 2, 4 }, { 1, 2 } } do + local y = pass[1] + while y < fh do + map[y + 1] = r + r += 1 + y += pass[2] + end + end + return map +end + +@native function Decode.toRgba(indexes: buffer, fw: number, fh: number, interlaced: boolean, palette: buffer, out: buffer) + local rows = if interlaced then interlacedRow(fh) else nil + for y = 0, fh - 1 do + local src = (if rows then rows[y + 1] else y) * fw + local dst = y * fw * 4 + for x = 0, fw - 1 do + writeu32(out, dst + x * 4, readu32(palette, readu8(indexes, src + x) * 4)) + end + end +end + +@native function Decode.draw(canvas: buffer, cw: number, ch: number, frame: buffer, fx: number, fy: number, fw: number, fh: number) + local x0, y0 = math.max(0, fx), math.max(0, fy) + local x1, y1 = math.min(cw, fx + fw), math.min(ch, fy + fh) + for y = y0, y1 - 1 do + local s = ((y - fy) * fw - fx) * 4 + local d = y * cw * 4 + for x = x0, x1 - 1 do + local v = readu32(frame, s + x * 4) + if v >= 0x01000000 then + writeu32(canvas, d + x * 4, v) + end + end + end +end + +@native function Decode.clear(canvas: buffer, cw: number, ch: number, fx: number, fy: number, fw: number, fh: number) + local x0, y0 = math.max(0, fx), math.max(0, fy) + local x1, y1 = math.min(cw, fx + fw), math.min(ch, fy + fh) + if x1 <= x0 then + return + end + for y = y0, y1 - 1 do + buffer.fill(canvas, (y * cw + x0) * 4, 0, (x1 - x0) * 4) + end +end + +return Decode +end +__FILES["image/hdr"] = function() + +-- image/hdr: Radiance HDR / RGBE (.hdr, .pic), from the Radiance file format notes and rgbe.c. Supports: "#?" headers, +-- 32-bit_rle_rgbe, EXPOSURE (kept, not applied), the eight orientations, flat / old / new RLE; writes -Y +X new RLE. +-- Not supported: 32-bit_rle_xyze, PRIMARIES / COLORCORR (ignored). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Codec = __include("image/hdr/Codec") + +-- ------------------------------------------------------------------------------------------------ contract +local Hdr = { + name = "hdr", + category = "image", + extensions = { "hdr", "pic", "rgbe" }, + mime = { "image/vnd.radiance", "image/x-hdr" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, alpha = false, float = true, depths = { 32 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + native: boolean?, -- default false: rgba8, round(clamp(v, 0, 1) ^ (1 / 2.2) * 255) + maxPixels: number?, -- default 2^26 +} +type EncodeOptions = { + rle: boolean?, -- default true + exposure: number?, -- default: meta.exposure when not 1 +} + +-- ------------------------------------------------------------------------------------------------ constants +local GAMMA = 1 / 2.2 + +-- ------------------------------------------------------------------------------------------------ sniff +function Hdr.sniff(r: Bytes.Reader): number + local s = r:peek(10) + if s == "#?RADIANCE" then + return 1 + end + if string.sub(s, 1, 6) == "#?RGBE" then + return 1 + end + if string.sub(s, 1, 2) == "#?" and string.match(s, "^#%?%u") then + return 0.5 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Hdr.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + local b, limit = r.buf, r.limit + local p = r.base + local function line(): string? + local s = p + while p < limit and buffer.readu8(b, p) ~= 10 do + p += 1 + end + if p >= limit then + return nil + end + local l = buffer.readstring(b, s, p - s) + p += 1 + return l + end + local first = line() + if not first or string.sub(first, 1, 2) ~= "#?" then + return nil, Err.new(Err.CORRUPT, "not a Radiance file (no #? line)", r.base) + end + local exposure = 1 + local format = nil + local text: { [string]: string } = {} + while true do + local l = line() + if l == nil then + return nil, Err.new(Err.TRUNCATED, "header ends early", p) + end + l = string.gsub(l, "\r$", "") + if l == "" then + break + end + local k, v = string.match(l, "^%s*([%w_%-]+)%s*=%s*(.-)%s*$") + if k == "FORMAT" then + format = v + elseif k == "EXPOSURE" then + local e = tonumber(v) + if e and e > 0 then + exposure *= e + end + elseif k then + text[k] = v :: string + end + end + if format and format ~= "32-bit_rle_rgbe" then + return nil, Err.new(Err.UNSUPPORTED, "FORMAT=" .. format) + end + local res = line() + if not res then + 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 :: 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 + local w, h = if a1 == "Y" then inner else outer, if a1 == "Y" then outer else inner + if w < 1 or h < 1 then + return nil, Err.new(Err.CORRUPT, "zero size") + end + if w * h > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels)) + end + local img = Types.Image.new(w, h, "rgbaf32") + local px = img.pixels + local row = buffer.create(inner * 4) + local truncated = false + for i = 0, outer - 1 do + local np, err = Codec.readLine(b, p, limit, inner, row) + if not np then + if err == "truncated" then + truncated = true + break + end + return nil, Err.new(Err.CORRUPT, tostring(err), p) + end + p = np + -- where scanline i, pixel j lands: Y decreasing ("-Y") = top first, X increasing ("+X") = left first + local base, step + if a1 == "Y" then + local y = if s1 == "-" then i else h - 1 - i + if s2 == "+" then + base, step = y * w * 16, 16 + else + base, step = (y * w + w - 1) * 16, -16 + end + else + local x = if s1 == "+" then i else w - 1 - i + if s2 == "-" then + base, step = x * 16, w * 16 + else + base, step = ((h - 1) * w + x) * 16, -w * 16 + end + end + Codec.toFloat(row, inner, px, base, step) + end + if not (opts and opts.native) then + local o = Types.Image.new(w, h, "rgba8") + for i = 0, w * h - 1 do + for c = 0, 2 do + local v = buffer.readf32(px, i * 16 + c * 4) + buffer.writeu8(o.pixels, i * 4 + c, math.floor(math.clamp(v, 0, 1) ^ GAMMA * 255 + 0.5)) + end + buffer.writeu8(o.pixels, i * 4 + 3, 255) + end + o.meta = img.meta + img = o + end + img.meta.exposure = exposure + img.meta.colorSpace = "linear" + if next(text) then + img.meta.text = text + end + 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 :: string, s2 :: string, a2 :: string) } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Hdr.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or type(img.pixels) ~= "buffer" or (img.format ~= "rgbaf32" and img.format ~= "rgba8") then + return nil, Err.new(Err.ARG, "needs an rgbaf32 or rgba8 Image") + end + local w, h = img.width, img.height + local bpp = if img.format == "rgbaf32" then 16 else 4 + 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 then + return nil, Err.new(Err.ARG, "bad image size or pixel buffer") + end + local o: any = opts or {} + local px = img.pixels + if bpp == 4 then + local lut = table.create(256, 0) + for v = 0, 255 do + lut[v + 1] = (v / 255) ^ 2.2 + end + px = buffer.create(w * h * 16) + for i = 0, w * h - 1 do + for c = 0, 2 do + buffer.writef32(px, i * 16 + c * 4, lut[buffer.readu8(img.pixels, i * 4 + c) + 1]) + end + buffer.writef32(px, i * 16 + 12, 1) + end + end + local exposure = o.exposure or (img.meta and img.meta.exposure) + local head = "#?RADIANCE\n# written by rosetta\nFORMAT=32-bit_rle_rgbe\n" + if type(exposure) == "number" and exposure > 0 and exposure ~= 1 then + head ..= string.format("EXPOSURE=%.9g\n", exposure) + end + head ..= string.format("\n-Y %d +X %d\n", h, w) + local rle = o.rle ~= false and w >= 8 and w <= 32767 + local out = buffer.create(#head + h * (w * 5 + 8)) + buffer.writestring(out, 0, head) + local op = #head + local row = buffer.create(w * 4) + for y = 0, h - 1 do + Codec.fromFloat(px, y, w, row) + if rle then + op = Codec.writeLine(row, w, out, op) + else + buffer.copy(out, op, row, 0, w * 4) + for x = 0, w - 1 do + -- 1, 1, 1 would read as an old-style run marker + if buffer.readu8(out, op + x * 4) == 1 and buffer.readu8(out, op + x * 4 + 1) == 1 and buffer.readu8(out, op + x * 4 + 2) == 1 then + buffer.writeu8(out, op + x * 4 + 2, 0) + end + end + op += w * 4 + end + end + local res = buffer.create(op) + buffer.copy(res, 0, out, 0, op) + return res, nil +end + +return Hdr +end +__FILES["image/hdr/Codec"] = @native function() + + + +-- image/hdr/Codec: Radiance RGBE scanlines (Graphics Gems II; rgbe.c): mantissa * 2^(e - 136), no +0.5, as stb_image. +local readu8, writeu8, writef32, readf32 = buffer.readu8, buffer.writeu8, buffer.writef32, buffer.readf32 +local frexp = math.frexp + +local Codec = {} + +-- old-style RLE: 1, 1, 1, n repeats the previous pixel (n << 8 for consecutive markers); new-style: 2, 2, width, planes +@native function Codec.readLine(b: buffer, p: number, limit: number, w: number, row: buffer): (number?, string?) + if w >= 8 and w <= 32767 and p + 4 <= limit and readu8(b, p) == 2 and readu8(b, p + 1) == 2 and readu8(b, p + 2) < 128 then + if readu8(b, p + 2) * 256 + readu8(b, p + 3) ~= w then + return nil, "scanline width mismatch" + end + p += 4 + for c = 0, 3 do + local x = 0 + while x < w do + if p >= limit then + return nil, "truncated" + end + local n = readu8(b, p) + p += 1 + if n > 128 then + n -= 128 + if x + n > w or p >= limit then + return nil, if p >= limit then "truncated" else "bad run" + end + local v = readu8(b, p) + p += 1 + for i = x, x + n - 1 do + writeu8(row, i * 4 + c, v) + end + else + if n == 0 or x + n > w then + return nil, "bad count" + end + if p + n > limit then + return nil, "truncated" + end + for i = x, x + n - 1 do + writeu8(row, i * 4 + c, readu8(b, p)) + p += 1 + end + end + x += n + end + end + return p, nil + end + -- flat pixels, with old-style runs + local x = 0 + local shift = 0 + while x < w do + if p + 4 > limit then + return nil, "truncated" + end + local r, g, bl, e = readu8(b, p), readu8(b, p + 1), readu8(b, p + 2), readu8(b, p + 3) + p += 4 + if r == 1 and g == 1 and bl == 1 then + if x == 0 then + return nil, "run at the start of a scanline" + end + local n = e * 2 ^ shift + if x + n > w then + return nil, "bad run" + end + local q = (x - 1) * 4 + local pr, pg, pb, pe = readu8(row, q), readu8(row, q + 1), readu8(row, q + 2), readu8(row, q + 3) + for i = x, x + n - 1 do + writeu8(row, i * 4, pr) + writeu8(row, i * 4 + 1, pg) + writeu8(row, i * 4 + 2, pb) + writeu8(row, i * 4 + 3, pe) + end + x += n + shift += 8 + if shift > 24 then + return nil, "bad run" + end + else + writeu8(row, x * 4, r) + writeu8(row, x * 4 + 1, g) + writeu8(row, x * 4 + 2, bl) + writeu8(row, x * 4 + 3, e) + x += 1 + shift = 0 + end + end + return p, nil +end + +@native function Codec.toFloat(row: buffer, n: number, out: buffer, base: number, step: number) + for i = 0, n - 1 do + local q = i * 4 + local e = readu8(row, q + 3) + local o = base + i * step + if e == 0 then + writef32(out, o, 0) + writef32(out, o + 4, 0) + writef32(out, o + 8, 0) + else + local f = 2 ^ (e - 136) + writef32(out, o, readu8(row, q) * f) + writef32(out, o + 4, readu8(row, q + 1) * f) + writef32(out, o + 8, readu8(row, q + 2) * f) + end + writef32(out, o + 12, 1) + end +end + +@native function Codec.fromFloat(px: buffer, y: number, w: number, row: buffer) + for x = 0, w - 1 do + local q = (y * w + x) * 16 + local r, g, b = readf32(px, q), readf32(px, q + 4), readf32(px, q + 8) + if r ~= r or r < 0 then + r = 0 + end + if g ~= g or g < 0 then + g = 0 + end + if b ~= b or b < 0 then + b = 0 + end + local v = math.max(r, g, b) + local o = x * 4 + if v < 1e-32 or v == math.huge then + if v == math.huge then + -- clamp infinities to the largest RGBE value + writeu8(row, o, if r == math.huge then 255 else 0) + writeu8(row, o + 1, if g == math.huge then 255 else 0) + writeu8(row, o + 2, if b == math.huge then 255 else 0) + writeu8(row, o + 3, 255) + else + writeu8(row, o, 0) + writeu8(row, o + 1, 0) + writeu8(row, o + 2, 0) + writeu8(row, o + 3, 0) + end + else + local m, e = frexp(v) + if e > 127 then + writeu8(row, o, 255) + writeu8(row, o + 1, 255) + writeu8(row, o + 2, 255) + writeu8(row, o + 3, 255) + else + local s = m * 256 / v + writeu8(row, o, math.min(255, math.floor(r * s))) + writeu8(row, o + 1, math.min(255, math.floor(g * s))) + writeu8(row, o + 2, math.min(255, math.floor(b * s))) + writeu8(row, o + 3, e + 128) + end + end + end +end + +@native function Codec.writeLine(row: buffer, w: number, out: buffer, o: number): number + writeu8(out, o, 2) + writeu8(out, o + 1, 2) + writeu8(out, o + 2, w // 256) + writeu8(out, o + 3, w % 256) + o += 4 + for c = 0, 3 do + local cur = 0 + while cur < w do + local begRun = cur + local runCount = 0 + local oldRun = 0 + while runCount < 4 and begRun < w do + begRun += runCount + oldRun = runCount + runCount = 1 + if begRun < w then + local v = readu8(row, begRun * 4 + c) + while begRun + runCount < w and runCount < 127 and readu8(row, (begRun + runCount) * 4 + c) == v do + runCount += 1 + end + end + end + if oldRun > 1 and oldRun == begRun - cur then + writeu8(out, o, 128 + oldRun) + writeu8(out, o + 1, readu8(row, cur * 4 + c)) + o += 2 + cur = begRun + end + while cur < begRun do + local n = math.min(begRun - cur, 128) + writeu8(out, o, n) + o += 1 + for i = cur, cur + n - 1 do + writeu8(out, o, readu8(row, i * 4 + c)) + o += 1 + end + cur += n + end + if runCount >= 4 then + writeu8(out, o, 128 + runCount) + writeu8(out, o + 1, readu8(row, begRun * 4 + c)) + o += 2 + cur += runCount + end + end + end + return o +end + +return Codec +end +__FILES["image/icns"] = function() + +-- image/icns: Apple icon images (icns resource type). Supports: is32 / il32 / ih32 / it32 (icns RLE) with s8mk / l8mk / +-- h8mk / t8mk masks, ic04 / ic05 ARGB, 1-bit ics# / ICN# / ich# / icm#, PNG entries through opts.decodeImage; writes +-- PNG or RLE entries. Not supported: JPEG 2000 entries, 4 / 8-bit palette entries, nested dark-mode / TOC chunks. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Sniff = __include("core/Sniff") +local Types = __include("Types") +local Chunks = __include("containers/Chunks") + +-- ------------------------------------------------------------------------------------------------ contract +local Icns = { + name = "icns", + category = "image", + extensions = { "icns" }, + mime = { "image/icns", "image/x-icns" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "containers/Chunks" }, + caps = { decode = true, encode = true, alpha = true, frames = true, depths = { 1, 24, 32 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + decodeImage: ((buffer) -> (Types.Image?, Err.Err?))?, + maxPixels: number?, -- default 2^22 +} +type EncodeOptions = { + encodeImage: ((Types.Image, string) -> (buffer?, Err.Err?))?, + legacy: boolean?, -- default false +} + +-- ------------------------------------------------------------------------------------------------ constants +local RGB: { [string]: { any } } = { is32 = { 16, "s8mk" }, il32 = { 32, "l8mk" }, ih32 = { 48, "h8mk" }, it32 = { 128, "t8mk" } } +local MASKS: { [string]: boolean } = { s8mk = true, l8mk = true, h8mk = true, t8mk = true } +local ARGB: { [string]: number } = { ic04 = 16, ic05 = 32 } +local MONO: { [string]: { number } } = { ["ics#"] = { 16, 16 }, ["ICN#"] = { 32, 32 }, ["ich#"] = { 48, 48 }, ["icm#"] = { 16, 12 } } +local PNG_TYPES: { [number]: string } = { [16] = "icp4", [32] = "icp5", [64] = "icp6", [128] = "ic07", [256] = "ic08", [512] = "ic09", [1024] = "ic10" } +local LEGACY: { [number]: { string } } = { [16] = { "is32", "s8mk" }, [32] = { "il32", "l8mk" }, [48] = { "ih32", "h8mk" }, [128] = { "it32", "t8mk" } } +local LAYOUT: Chunks.Layout = { + bigEndian = true, + resize = function(_id: string, declared: number): number? + return math.max(0, declared - 8) + end, +} + +local readu8 = buffer.readu8 + +-- ------------------------------------------------------------------------------------------------ sniff +function Icns.sniff(r: Bytes.Reader): number + return Sniff.magic(r, "icns") +end + +-- ------------------------------------------------------------------------------------------------ decode +local function unrle(b: buffer, p: number, stop: number, out: buffer, channels: { number }, count: number): boolean + for _, ch in channels do + local i = 0 + while i < count do + if p >= stop then + return false + end + local c = readu8(b, p) + p += 1 + if c >= 128 then + local n = c - 125 + if p >= stop then + return false + end + local v = readu8(b, p) + p += 1 + for _ = 1, math.min(n, count - i) do + buffer.writeu8(out, i * 4 + ch, v) + i += 1 + end + else + local n = c + 1 + if p + n > stop then + return false + end + for k = 0, math.min(n, count - i) - 1 do + buffer.writeu8(out, (i + k) * 4 + ch, readu8(b, p + k)) + end + i += math.min(n, count - i) + p += n + end + end + end + return true +end + +local function isPng(b: buffer, p: number, n: number): boolean + return n >= 8 and buffer.readstring(b, p, 8) == "\137PNG\r\n\26\n" +end +local function isJp2(b: buffer, p: number, n: number): boolean + return n >= 12 and (buffer.readstring(b, p, 12) == "\0\0\0\12jP \r\n\135\n" or buffer.readstring(b, p, 4) == "\255\79\255\81") +end + +function Icns.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local b, o, limit = r.buf, r.base, r.limit + if limit - o < 8 or buffer.readstring(b, o, 4) ~= "icns" then + return nil, Err.new(Err.CORRUPT, "not an icns file", o) + end + local total = bit32.byteswap(buffer.readu32(b, o + 4)) + local stop = math.min(limit, o + math.max(total, 8)) + local list = Chunks.walk(b, o + 8, stop, LAYOUT) + local decodeImage = opts and opts.decodeImage + local maxPixels = opts and opts.maxPixels or 2 ^ 22 + local masks: { [string]: Chunks.Chunk } = {} + for _, c in list do + if MASKS[c.id] then + masks[c.id] = c + end + end + local frames: { Types.Frame } = {} + local skipped: { string } = {} + local function add(im: Types.Image, typ: string, extra: { [string]: any }?) + local src: { [string]: any } = { format = "icns", type = typ } + if extra then + for k, v in extra do + src[k] = v + end + end + im.meta.source = src :: any + table.insert(frames, { image = im, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" } :: Types.Frame) + end + for _, c in list do + local id, p, n = c.id, c.offset, c.avail + if c.truncated then + table.insert(skipped, id .. " (truncated)") + elseif RGB[id] then + local size = RGB[id][1] + local im = Types.Image.new(size, size, "rgba8") + local px = im.pixels + local q = if id == "it32" then p + 4 else p + local count = size * size + local ok + if n == count * 3 then + for i = 0, count - 1 do + for k = 0, 2 do + buffer.writeu8(px, i * 4 + k, readu8(b, p + k * count + i)) + end + end + ok = true + else + ok = unrle(b, q, p + n, px, { 0, 1, 2 }, count) + end + local m = masks[RGB[id][2]] + for i = 0, count - 1 do + buffer.writeu8(px, i * 4 + 3, if m and m.avail >= count then readu8(b, m.offset + i) else 255) + end + if ok then + add(im, id, { bitDepth = 24, mask = m ~= nil }) + else + table.insert(skipped, id .. " (bad RLE)") + end + elseif ARGB[id] and n >= 4 and buffer.readstring(b, p, 4) == "ARGB" then + local size = ARGB[id] + local im = Types.Image.new(size, size, "rgba8") + if unrle(b, p + 4, p + n, im.pixels, { 3, 0, 1, 2 }, size * size) then + add(im, id, { bitDepth = 32 }) + else + table.insert(skipped, id .. " (bad RLE)") + end + elseif MONO[id] then + local w, h = MONO[id][1], MONO[id][2] + local bytes = w * h // 8 + if n >= bytes * 2 then + local im = Types.Image.new(w, h, "rgba8") + for i = 0, w * h - 1 do + local bit = bit32.band(bit32.rshift(readu8(b, p + bit32.rshift(i, 3)), 7 - bit32.band(i, 7)), 1) + local mbit = bit32.band(bit32.rshift(readu8(b, p + bytes + bit32.rshift(i, 3)), 7 - bit32.band(i, 7)), 1) + buffer.writeu32(im.pixels, i * 4, (if bit == 1 then 0 else 0xFFFFFF) + mbit * 0xFF000000) + end + add(im, id, { bitDepth = 1 }) + end + elseif isPng(b, p, n) then + if decodeImage then + local sub = buffer.create(n) + buffer.copy(sub, 0, b, p, n) + local okc, im, ierr = pcall(decodeImage, sub) + if okc and im then + if im.width * im.height <= maxPixels then + add(im :: Types.Image, id, { png = true }) + else + table.insert(skipped, id .. " (over maxPixels)") + end + else + table.insert(skipped, id .. " (PNG: " .. tostring(if okc then ierr else im) .. ")") + end + else + table.insert(skipped, id .. " (PNG: no decodeImage hook)") + end + elseif isJp2(b, p, n) then + table.insert(skipped, id .. " (JPEG 2000)") + elseif not MASKS[id] and id ~= "TOC " and id ~= "icnV" and id ~= "name" and id ~= "info" then + table.insert(skipped, id) + end + end + if #frames == 0 then + if #skipped > 0 then + return nil, Err.new(Err.UNSUPPORTED, "no decodable entry (" .. table.concat(skipped, ", ") .. ")") + end + return nil, Err.new(Err.CORRUPT, "no icon entries", o + 8) + end + local main = frames[1].image + for _, f in frames do + if f.image.width * f.image.height > main.width * main.height then + main = f.image + end + end + local img = Types.Image.new(0, 0, "rgba8") + img.width, img.height, img.pixels = main.width, main.height, main.pixels + if #frames > 1 then + img.frames = frames + end + if #skipped > 0 then + img.meta.skipped = skipped + end + img.meta.source = { format = "icns", type = main.meta.source and main.meta.source.type, entries = #frames } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function rle(w: Bytes.Writer, px: buffer, ch: number, count: number) + local i = 0 + while i < count do + local v = readu8(px, i * 4 + ch) + local run = 1 + while i + run < count and run < 130 and readu8(px, (i + run) * 4 + ch) == v do + run += 1 + end + if run >= 3 then + w:u8(run + 125) + w:u8(v) + i += run + else + local lit = 0 + while i + lit < count and lit < 128 do + local a = readu8(px, (i + lit) * 4 + ch) + if i + lit + 2 < count and readu8(px, (i + lit + 1) * 4 + ch) == a and readu8(px, (i + lit + 2) * 4 + ch) == a then + break + end + lit += 1 + end + lit = math.max(lit, 1) + w:u8(lit - 1) + for k = 0, lit - 1 do + w:u8(readu8(px, (i + k) * 4 + ch)) + end + i += lit + end + end +end + +function Icns.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "needs an Image") + end + local images: { Types.Image } = {} + local seen: { [number]: boolean } = {} + local function take(im: Types.Image): Err.Err? + if type(im) ~= "table" or im.format ~= "rgba8" or im.width ~= im.height then + return Err.new(Err.ARG, "icons are square rgba8 images") + end + if not seen[im.width] then + seen[im.width] = true + table.insert(images, im) + end + return nil + end + local e = take(img) + if e then + return nil, e + end + if type(img.frames) == "table" then + for _, f in img.frames do + local fe = take(f.image) + if fe then + return nil, fe + end + end + end + table.sort(images, function(a: Types.Image, c: Types.Image): boolean + return a.width < c.width + end) + local encodeImage = opts and opts.encodeImage + local legacy = (opts and opts.legacy) or encodeImage == nil + local body = Bytes.writer() + local function chunk(id: string, data: buffer) + body:string(id) + body:u32be(buffer.len(data) + 8) + body:bytes(data) + end + for _, im in images do + local s = im.width + if legacy and LEGACY[s] then + local types = LEGACY[s] + local w = Bytes.writer() + if s == 128 then + w:u32be(0) + end + for ch = 0, 2 do + rle(w, im.pixels, ch, s * s) + end + chunk(types[1], w:finish()) + local m = buffer.create(s * s) + for i = 0, s * s - 1 do + buffer.writeu8(m, i, readu8(im.pixels, i * 4 + 3)) + end + chunk(types[2], m) + elseif encodeImage and PNG_TYPES[s] then + local ok, png, perr = pcall(encodeImage, im, "png") + if not ok or not png then + return nil, Err.new(Err.ARG, "PNG entry " .. s .. ": " .. tostring(if ok then perr else png)) + end + chunk(PNG_TYPES[s], png :: buffer) + else + return nil, Err.new(Err.ARG, string.format("no icns entry for %d x %d%s", s, s, if encodeImage then "" else " without an encodeImage hook (16 / 32 / 48 / 128 only)")) + end + end + local data = body:finish() + local out = Bytes.writer(buffer.len(data) + 8) + out:string("icns") + out:u32be(buffer.len(data) + 8) + out:bytes(data) + return out:finish(), nil +end + +return Icns +end +__FILES["image/ico"] = function() + +-- image/ico: Windows icons and cursors (ICO / CUR), from Microsoft's ICO documentation. Supports: every entry as a BMP +-- DIB (1..32-bit, AND mask) or PNG (opts.decodeImage), CUR hotspots; writes 32-bit DIB or PNG entries. Not supported: +-- resizing to icon sizes, DIB compression (BI_BITFIELDS read as 5-5-5 / BGRA), 2-colour planes. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Dib = __include("image/ico/Dib") + +-- ------------------------------------------------------------------------------------------------ contract +local Ico = { + name = "ico", + category = "image", + extensions = { "ico", "cur" }, + mime = { "image/vnd.microsoft.icon", "image/x-icon" }, + 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 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + decodeImage: ((buffer) -> (Types.Image?, Err.Err?))?, + maxPixels: number?, -- default 2^26 +} +type EncodeOptions = { + encodeImage: ((Types.Image, string) -> (buffer?, Err.Err?))?, + png: boolean?, -- default: only 256-pixel entries + cursor: boolean?, -- default: when the image has meta.hotspot +} + +-- ------------------------------------------------------------------------------------------------ constants +local PNG_SIG = "\137PNG\r\n\26\n" +local readu8 = buffer.readu8 + +-- ------------------------------------------------------------------------------------------------ sniff +function Ico.sniff(r: Bytes.Reader): number + if r:remaining() < 22 then + return 0 + end + local b, o = r.buf, r.pos + local typ = buffer.readu16(b, o + 2) + local count = buffer.readu16(b, o + 4) + if buffer.readu16(b, o) ~= 0 or (typ ~= 1 and typ ~= 2) or count == 0 then + return 0 + end + -- the first entry: reserved byte 0, a size and offset inside the file + local size, off = buffer.readu32(b, o + 14), buffer.readu32(b, o + 18) + if readu8(b, o + 9) ~= 0 or size == 0 or off < 6 + count * 16 then + return 0 + end + return 0.8 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function le16(b: buffer, p: number): number + return buffer.readu16(b, p) +end +local function le32(b: buffer, p: number): number + return buffer.readu32(b, p) +end + +function Ico.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + local decodeImage = opts and opts.decodeImage + local b, base, limit = r.buf, r.base, r.limit + if limit - base < 6 then + return nil, Err.new(Err.TRUNCATED, "short header", base) + end + local typ, count = le16(b, base + 2), le16(b, base + 4) + if le16(b, base) ~= 0 or (typ ~= 1 and typ ~= 2) then + return nil, Err.new(Err.CORRUPT, "not an ICO / CUR file", base) + end + if count == 0 then + return nil, Err.new(Err.CORRUPT, "no images", base) + end + if base + 6 + count * 16 > limit then + return nil, Err.new(Err.TRUNCATED, "directory runs past the end", base) + end + local frames: { Types.Frame } = {} + local best: Types.Image? = nil + local bestScore = -1 + local skipped, lastErr = 0, nil :: Err.Err? + for i = 0, count - 1 do + local d = base + 6 + i * 16 + local dw, dh = readu8(b, d), readu8(b, d + 1) + dw = if dw == 0 then 256 else dw + dh = if dh == 0 then 256 else dh + local f1, f2 = le16(b, d + 4), le16(b, d + 6) + local size, off = le32(b, d + 8), le32(b, d + 12) + local p, e = base + off, base + off + size + local img: Types.Image? = nil + local depth = 0 + local isPng = false + if off < 6 or p >= limit then + lastErr = Err.new(Err.TRUNCATED, "entry " .. (i + 1) .. " lies past the end", d) + else + e = math.min(e, limit) + if e - p >= 8 and buffer.readstring(b, p, 8) == PNG_SIG then + isPng = true + depth = 32 + if decodeImage then + local sub = buffer.create(e - p) + buffer.copy(sub, 0, b, p, e - p) + local ok, pimg, perr = pcall(decodeImage, sub) + if ok and pimg and pimg.format == "rgba8" then + img = pimg + else + lastErr = if ok and perr then perr else Err.new(Err.CORRUPT, "entry " .. (i + 1) .. ": bad PNG") + end + else + lastErr = Err.new(Err.UNSUPPORTED, "PNG entries need opts.decodeImage (F.load passes it)") + end + elseif e - p >= 40 then + local hs = le32(b, p) + local bw = buffer.readi32(b, p + 4) + local bh = buffer.readi32(b, p + 8) + local bpp = le16(b, p + 14) + local clrUsed = le32(b, p + 32) + local w = if bw > 0 then bw else dw + local h = if bh ~= 0 then math.abs(bh) // 2 else dh + if hs < 12 or hs > e - p or w < 1 or h < 1 or w > 4096 or h > 4096 then + lastErr = Err.new(Err.CORRUPT, "entry " .. (i + 1) .. ": bad bitmap header", p) + elseif bpp ~= 1 and bpp ~= 4 and bpp ~= 8 and bpp ~= 16 and bpp ~= 24 and bpp ~= 32 then + lastErr = Err.new(Err.UNSUPPORTED, "entry " .. (i + 1) .. ": " .. bpp .. "-bit bitmap", p) + elseif w * h > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels)) + else + depth = bpp + local q = p + hs + local palN = 0 + local pal = buffer.create(4) + if bpp <= 8 then + palN = if clrUsed > 0 and clrUsed < 2 ^ bpp then clrUsed else 2 ^ bpp + if q + palN * 4 > e then + palN = 0 + lastErr = Err.new(Err.TRUNCATED, "entry " .. (i + 1) .. ": colour table runs past the entry", q) + else + pal = buffer.create(palN * 4) + for k = 0, palN - 1 do + local c = q + k * 4 + buffer.writeu32(pal, k * 4, readu8(b, c + 2) + readu8(b, c + 1) * 256 + readu8(b, c) * 65536 + 0xFF000000) + end + q += palN * 4 + end + end + if bpp > 8 or palN > 0 then + if bpp == 16 and le32(b, p + 16) == 3 then + q += 12 -- BI_BITFIELDS masks (assumed 5-5-5) + end + local out = Types.Image.new(w, h, "rgba8") + local ok, msg = Dib.decode(b, q, e, w, h, bpp, pal, palN, out.pixels) + if ok then + img = out + else + lastErr = Err.new(Err.TRUNCATED, "entry " .. (i + 1) .. ": " .. tostring(msg), q) + end + end + end + else + lastErr = Err.new(Err.TRUNCATED, "entry " .. (i + 1) .. " is too short", p) + end + end + if img then + local im = img :: Types.Image + im.meta.source = { format = "ico", bitDepth = depth, png = isPng, colorCount = readu8(b, d + 2) } + 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" } :: Types.Frame) + local score = im.width * im.height * 64 + depth + if score > bestScore then + best, bestScore = im, score + end + else + skipped += 1 + end + end + if not best then + return nil, lastErr or Err.new(Err.CORRUPT, "no decodable entry") + end + local main = best :: Types.Image + local img = Types.Image.new(main.width, main.height, "rgba8") + buffer.copy(img.pixels, 0, main.pixels) + if #frames > 1 then + img.frames = frames + end + img.meta.source = { format = "ico", type = if typ == 2 then "cur" else "ico", bitDepth = main.meta.source and main.meta.source.bitDepth, entries = count, skipped = skipped, png = main.meta.source and main.meta.source.png } + img.meta.hotspot = main.meta.hotspot + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Ico.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" then + return nil, Err.new(Err.ARG, "needs an Image") + end + local o: any = opts or {} + local list: { Types.Image } = {} + if type(img.frames) == "table" and #img.frames > 0 then + for _, f in img.frames do + table.insert(list, f.image) + end + else + list[1] = img + end + local cursor = o.cursor + if cursor == nil then + cursor = type(img.meta) == "table" and img.meta.hotspot ~= nil + end + local blobs: { buffer } = {} + for i, im in list do + if type(im) ~= "table" or im.format ~= "rgba8" or type(im.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "entry " .. i .. ": needs an rgba8 Image") + end + local w, h = im.width, im.height + if type(w) ~= "number" or type(h) ~= "number" or w < 1 or h < 1 or w > 256 or h > 256 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(im.pixels) < w * h * 4 then + return nil, Err.new(Err.ARG, "entry " .. i .. ": icons are 1..256 pixels per side") + end + local png = nil + if o.encodeImage and (o.png or w == 256 or h == 256) then + local ok, res, err = pcall(o.encodeImage, im, "png") + if not ok or not res then + return nil, if ok and err then err else Err.new(Err.ARG, "entry " .. i .. ": PNG encode failed") + end + png = res + elseif o.png then + return nil, Err.new(Err.ARG, "opts.png needs opts.encodeImage (F.save passes it)") + end + if png then + blobs[i] = png + else + local maskStride = ((w + 31) // 32) * 4 + local n = 40 + w * h * 4 + maskStride * h + local d = buffer.create(n) + buffer.writeu32(d, 0, 40) + buffer.writei32(d, 4, w) + buffer.writei32(d, 8, h * 2) + buffer.writeu16(d, 12, 1) + buffer.writeu16(d, 14, 32) + buffer.writeu32(d, 20, w * h * 4 + maskStride * h) + Dib.encode(im.pixels, w, h, d, 40) + blobs[i] = d + end + end + local total = 6 + #list * 16 + for _, bl in blobs do + total += buffer.len(bl) + end + local out = buffer.create(total) + buffer.writeu16(out, 2, if cursor then 2 else 1) + buffer.writeu16(out, 4, #list) + local off = 6 + #list * 16 + for i, im in list do + local d = 6 + (i - 1) * 16 + buffer.writeu8(out, d, im.width % 256) + buffer.writeu8(out, d + 1, im.height % 256) + if cursor then + local hs = (type(im.meta) == "table" and im.meta.hotspot) or (img.meta and img.meta.hotspot) or { x = 0, y = 0 } + buffer.writeu16(out, d + 4, math.clamp(math.floor(tonumber(hs.x) or 0), 0, 65535)) + buffer.writeu16(out, d + 6, math.clamp(math.floor(tonumber(hs.y) or 0), 0, 65535)) + else + buffer.writeu16(out, d + 4, 1) + buffer.writeu16(out, d + 6, 32) + end + buffer.writeu32(out, d + 8, buffer.len(blobs[i])) + buffer.writeu32(out, d + 12, off) + buffer.copy(out, off, blobs[i]) + off += buffer.len(blobs[i]) + end + return out, nil +end + +return Ico +end +__FILES["image/ico/Dib"] = @native function() + + + +-- image/ico/Dib: ICO / CUR DIBs: XOR bitmap (1..32-bit, bottom-up, 4-byte rows) + 1-bit AND mask (1 = transparent). +local Pixels = __include("codecs/image/Pixels") + +local readu8, readu32, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu32 + +local Dib = {} + +-- 32-bit entries use their alpha unless it is all zero (old icons); then the AND mask decides +@native function Dib.decode(b: buffer, p: number, e: number, w: number, h: number, bpp: number, pal: buffer, palN: number, out: buffer): (boolean, string?) + local stride = ((w * bpp + 31) // 32) * 4 + local maskStride = ((w + 31) // 32) * 4 + if p + stride * h > e then + return false, "colour bitmap runs past the entry" + end + local hasMask = p + stride * h + maskStride * h <= e + local anyAlpha = false + 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 + end + if hasMask then + local mp = p + stride * h + for y = 0, h - 1 do + local row = mp + (h - 1 - y) * maskStride + for x = 0, w - 1 do + local o = (y * w + x) * 4 + local px = readu32(out, o) % 16777216 + if (readu8(b, row + x // 8) // 2 ^ (7 - x % 8)) % 2 == 1 then + writeu32(out, o, px) -- transparent + else + writeu32(out, o, px + 0xFF000000) + end + end + end + elseif bpp == 32 then + -- no alpha and no mask: opaque + for i = 0, w * h - 1 do + writeu32(out, i * 4, readu32(out, i * 4) % 16777216 + 0xFF000000) + end + end + return true, nil +end + +@native function Dib.encode(px: buffer, w: number, h: number, out: buffer, o: number): number + for y = h - 1, 0, -1 do + for x = 0, w - 1 do + local q = (y * w + x) * 4 + buffer.writeu8(out, o, readu8(px, q + 2)) + buffer.writeu8(out, o + 1, readu8(px, q + 1)) + buffer.writeu8(out, o + 2, readu8(px, q)) + buffer.writeu8(out, o + 3, readu8(px, q + 3)) + o += 4 + end + end + local maskStride = ((w + 31) // 32) * 4 + for y = h - 1, 0, -1 do + local acc, nb, written = 0, 0, 0 + for x = 0, w - 1 do + acc = acc * 2 + (if readu8(px, (y * w + x) * 4 + 3) == 0 then 1 else 0) + nb += 1 + if nb == 8 then + buffer.writeu8(out, o + written, acc) + written += 1 + acc, nb = 0, 0 + end + end + if nb > 0 then + buffer.writeu8(out, o + written, acc * 2 ^ (8 - nb)) + written += 1 + end + buffer.fill(out, o + written, 0, maskStride - written) + o += maskStride + end + return o +end + +return Dib +end +__FILES["image/ilbm"] = function() + +-- image/ilbm: IFF ILBM / PBM (EA IFF 85 "ILBM", Amiga ROM Kernel Manual). Supports: 1..8 planes + CMAP, EHB (CAMG +-- 0x80), HAM6 / HAM8 (CAMG 0x800; 4-bit v -> v * 17, ilbmtoppm shifts), 24 / 32 planes, PBM, masking 1 / 2, ByteRun1, +-- NAME / ANNO / AUTH. Not supported: ANIM, RGBN / RGB8 / ACBM / DEEP, SHAM / PCHG (ignored). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Chunks = __include("containers/Chunks") +local PackBits = __include("codecs/compress/PackBits") +local Pixels = __include("codecs/image/Pixels") + +-- ------------------------------------------------------------------------------------------------ contract +local Ilbm = { + name = "ilbm", + category = "image", + extensions = { "iff", "ilbm", "lbm", "pbm" }, + mime = { "image/x-ilbm", "image/x-iff" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/compress/PackBits", "codecs/image/Pixels" }, + caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 1, 2, 3, 4, 5, 6, 7, 8, 24, 32 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + adjustColors: boolean?, -- default false + maxPixels: number?, -- default 2^26 +} +type EncodeOptions = { + compress: boolean?, -- default true +} + +local readu8, readu16 = buffer.readu8, buffer.readu16 +local function be16(b: buffer, o: number): number + return bit32.rshift(bit32.byteswap(readu16(b, o)), 16) +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Ilbm.sniff(r: Bytes.Reader): number + if r:peek(4) ~= "FORM" then + return 0 + end + local t = r:peek(4, 8) + return if t == "ILBM" or t == "PBM " then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Ilbm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local b, o, limit = r.buf, r.base, r.limit + if limit - o < 12 or buffer.readstring(b, o, 4) ~= "FORM" then + return nil, Err.new(Err.CORRUPT, "not an IFF FORM", o) + end + local form = buffer.readstring(b, o + 8, 4) + if form ~= "ILBM" and form ~= "PBM " then + return nil, Err.new(Err.UNSUPPORTED, "FORM " .. form, o + 8) + end + local chunky = form == "PBM " + local list = Chunks.walk(b, o + 12, math.min(limit, o + 8 + bit32.byteswap(buffer.readu32(b, o + 4))), Chunks.IFF) + local bmhd, cmap, body = Chunks.find(list, "BMHD"), Chunks.find(list, "CMAP"), Chunks.find(list, "BODY") + if not bmhd or bmhd.avail < 20 then + return nil, Err.new(Err.CORRUPT, "missing BMHD", o + 12) + end + if not body then + return nil, Err.new(Err.TRUNCATED, "missing BODY", o + 12) + end + local q = bmhd.offset + local w, h = be16(b, q), be16(b, q + 2) + local planes, masking, comp = readu8(b, q + 8), readu8(b, q + 9), readu8(b, q + 10) + local trans = be16(b, q + 12) + if w == 0 or h == 0 then + return nil, Err.new(Err.CORRUPT, "bad size", q) + end + if comp > 1 then + return nil, Err.new(Err.UNSUPPORTED, "compression " .. comp, q + 10) + end + if not (planes >= 1 and planes <= 8 or planes == 24 or planes == 32) or (chunky and planes ~= 8) then + return nil, Err.new(Err.UNSUPPORTED, planes .. " planes", q + 8) + end + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + if w * h > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels)) + end + local camg = 0 + local c = Chunks.find(list, "CAMG") + if c and c.avail >= 4 then + camg = bit32.byteswap(buffer.readu32(b, c.offset)) + end + local ham = bit32.band(camg, 0x800) ~= 0 and (planes == 6 or planes == 8) + local ehb = bit32.band(camg, 0x80) ~= 0 and planes == 6 and not ham + local pal = buffer.create(1024) + local ncol = 0 + if cmap then + ncol = math.min(256, cmap.avail // 3) + local low = true + for i = 0, ncol * 3 - 1 do + low = low and bit32.band(readu8(b, cmap.offset + i), 15) == 0 + end + local adjust = low and opts and opts.adjustColors + for i = 0, ncol - 1 do + local function ch(k: number): number + local v = readu8(b, cmap.offset + i * 3 + k) + return if adjust then v + bit32.rshift(v, 4) else v + end + buffer.writeu32(pal, i * 4, ch(0) + ch(1) * 256 + ch(2) * 65536 + 0xFF000000) + end + end + if ncol == 0 and planes <= 8 then + local n = bit32.lshift(1, planes) + for i = 0, n - 1 do + local g = (i * 255) // math.max(1, n - 1) + buffer.writeu32(pal, i * 4, g * 0x10101 + 0xFF000000) + end + ncol = n + end + if ehb then + for i = 0, 31 do + local v = buffer.readu32(pal, i * 4) + local rr, gg, bb = bit32.band(v, 255), bit32.band(bit32.rshift(v, 8), 255), bit32.band(bit32.rshift(v, 16), 255) + buffer.writeu32(pal, (32 + i) * 4, bit32.rshift(rr, 1) + bit32.rshift(gg, 1) * 256 + bit32.rshift(bb, 1) * 65536 + 0xFF000000) + end + end + local rowBytes = if chunky then w + w % 2 else ((w + 15) // 16) * 2 + local total = if chunky then rowBytes * h else rowBytes * (planes + (if masking == 1 then 1 else 0)) * h + local raw = buffer.create(total) + local truncated + if comp == 1 then + local written = PackBits.decode(b, body.offset, body.offset + body.avail, raw, 0, total) + truncated = written < total + else + local n = math.min(total, body.avail) + buffer.copy(raw, 0, b, body.offset, n) + truncated = n < total + end + local img = Types.Image.new(w, h, "rgba8") + local px = img.pixels + if chunky then + Pixels.indexed(raw, 0, rowBytes, 8, px, w, h, true, pal) + if masking == 2 then + for i = 0, w * h - 1 do + local y, x = i // w, i % w + if readu8(raw, y * rowBytes + x) == trans then + buffer.writeu32(px, i * 4, 0) + end + end + end + else + local stride = rowBytes * (planes + (if masking == 1 then 1 else 0)) + local deep = planes >= 24 + local bits = planes - 2 + for y = 0, h - 1 do + local row = y * stride + local pr: number, pg: number, pb: number = 0, 0, 0 + if ham then + local v = buffer.readu32(pal, 0) + pr = bit32.band(v, 255) + pg = bit32.band(bit32.rshift(v, 8), 255) + pb = bit32.band(bit32.rshift(v, 16), 255) + end + for x = 0, w - 1 do + local byteAt, shift = bit32.rshift(x, 3), 7 - bit32.band(x, 7) + local idx = 0 + for k = 0, planes - 1 do + idx += bit32.band(bit32.rshift(readu8(raw, row + k * rowBytes + byteAt), shift), 1) * 2 ^ k + end + local out: number + if deep then + local a = if planes == 32 then bit32.rshift(idx, 24) % 256 else 255 + out = bit32.band(idx, 0xFFFFFF) + a * 16777216 + elseif ham then + local ctl = bit32.rshift(idx, bits) + local val = bit32.band(idx, bit32.lshift(1, bits) - 1) + local v8 = if bits == 4 then val * 17 else val * 4 + bit32.rshift(val, 4) + if ctl == 0 then + local v = buffer.readu32(pal, val * 4) + pr = bit32.band(v, 255) + pg = bit32.band(bit32.rshift(v, 8), 255) + pb = bit32.band(bit32.rshift(v, 16), 255) + elseif ctl == 1 then + pb = v8 + elseif ctl == 2 then + pr = v8 + else + pg = v8 + end + out = pr + pg * 256 + pb * 65536 + 0xFF000000 + else + out = buffer.readu32(pal, bit32.band(idx, 255) * 4) + if masking == 2 and idx == trans then + out = 0 + end + end + if masking == 1 then + local m = bit32.band(bit32.rshift(readu8(raw, row + planes * rowBytes + byteAt), shift), 1) + if m == 0 then + out = 0 + end + end + buffer.writeu32(px, (y * w + x) * 4, out) + end + end + end + if ncol > 0 and planes <= 8 and not ham then + local plist: { { number } } = {} + for i = 0, (if ehb then 64 else ncol) - 1 do + local v = buffer.readu32(pal, i * 4) + plist[i + 1] = { bit32.band(v, 255), bit32.band(bit32.rshift(v, 8), 255), bit32.band(bit32.rshift(v, 16), 255), 255 } + end + img.meta.palette = plist + end + local text: { [string]: string } = {} + for _, ch in list do + if ch.id == "NAME" or ch.id == "ANNO" or ch.id == "AUTH" or ch.id == "(c) " then + local s = buffer.readstring(b, ch.offset, ch.avail) + local key = string.gsub(ch.id, "[^%w]", "") + text[string.lower(key)] = (string.gsub(s, "%z+$", "")) + end + end + if next(text) then + img.meta.text = text + end + if truncated then + img.meta.truncated = true + end + img.meta.source = { format = "ilbm", form = form, planes = planes, bitDepth = planes, ham = ham, ehb = ehb, masking = masking, compression = comp, camg = camg } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Ilbm.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "needs an rgba8 Image") + end + local w, h = img.width, img.height + if w < 1 or h < 1 or w > 65535 or h > 65535 then + return nil, Err.new(Err.ARG, "size must be 1..65535") + end + local px = img.pixels + local cols, alpha = Pixels.colours(px, w * h, 256) + local usePal = not alpha and #cols <= 256 + local planes = if usePal then 1 elseif alpha then 32 else 24 + if usePal then + while bit32.lshift(1, planes) < #cols do + planes += 1 + end + end + local compress = not (opts and opts.compress == false) + local index: { [number]: number } = {} + for i, cv in cols do + index[cv] = i - 1 + end + local rowBytes = ((w + 15) // 16) * 2 + local body = Bytes.writer(rowBytes * planes * h) + local row = buffer.create(rowBytes) + for y = 0, h - 1 do + for k = 0, planes - 1 do + buffer.fill(row, 0, 0, rowBytes) + for x = 0, w - 1 do + local v = buffer.readu32(px, (y * w + x) * 4) + local idx = if usePal then (index[bit32.band(v, 0xFFFFFF)] or 0) else v + if bit32.band(bit32.rshift(idx, k), 1) == 1 then + local at = bit32.rshift(x, 3) + buffer.writeu8(row, at, bit32.bor(readu8(row, at), bit32.rshift(0x80, bit32.band(x, 7)))) + end + end + if compress then + body:bytes(PackBits.encode(row, 0, rowBytes)) + else + body:bytes(row) + end + end + end + local bodyData = body:finish() + local out = Bytes.writer(buffer.len(bodyData) + 900) + out:string("FORM") + out:u32be(0) + out:string("ILBM") + out:string("BMHD") + out:u32be(20) + out:u16be(w) + out:u16be(h) + out:u16be(0) + out:u16be(0) + out:u8(planes) + out:u8(0) + out:u8(if compress then 1 else 0) + out:u8(0) + out:u16be(0) + out:u8(1) + out:u8(1) + out:u16be(w) + out:u16be(h) + if usePal then + local n = bit32.lshift(1, planes) + out:string("CMAP") + out:u32be(n * 3) + for i = 1, n do + local cv = cols[i] or 0 + out:u8(bit32.band(cv, 255)) + out:u8(bit32.band(bit32.rshift(cv, 8), 255)) + out:u8(bit32.rshift(cv, 16)) + end + if (n * 3) % 2 == 1 then + out:u8(0) + end + end + out:string("BODY") + out:u32be(buffer.len(bodyData)) + out:bytes(bodyData) + if buffer.len(bodyData) % 2 == 1 then + out:u8(0) + end + local res = out:finish() + buffer.writeu32(res, 4, bit32.byteswap(buffer.len(res) - 8)) + return res, nil +end + +return Ilbm +end +__FILES["image/jpeg"] = function() + +-- image/jpeg: JPEG / JFIF / EXIF (ITU T.81) over codecs/image/Jpeg (from jpeg-luau 1.0, same author; bit-exact with +-- djpeg, byte-identical with cjpeg; IJG parts: licenses/libjpeg-turbo-LICENSE.md). Supports: SOF0/1/2/9/10, 8 / 12-bit, +-- scaled decodes, EXIF / ICC / COM / JFIF density. Not supported: lossless (SOF3), hierarchical, DNL, 2 components. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Codec = __include("codecs/image/Jpeg") + +-- ------------------------------------------------------------------------------------------------ contract +local Jpeg = { + name = "jpeg", + category = "image", + extensions = { "jpg", "jpeg", "jpe", "jfif" }, + mime = { "image/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 }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + scale: number?, -- 1 (default), 2, 4 or 8 + orient: boolean?, -- default false + native: boolean?, -- default false + maxPixels: number?, -- default 2^26 +} +type EncodeOptions = { + quality: number?, -- 1..100, default 90 (libjpeg scaling of the T.81 annex K tables) + subsampling: ("420" | "422" | "444")?, -- default "420" + progressive: boolean?, -- default false + optimize: boolean?, -- default false; progressive always optimises + gray: boolean?, -- default: true for gray8 images + restart: number?, -- in MCUs, default 0 = none + jfif: boolean?, -- default true + meta: boolean?, -- default true +} + +type Info = Codec.Info + +-- ------------------------------------------------------------------------------------------------ sniff +function Jpeg.sniff(r: Bytes.Reader): number + local s = r:peek(3) + return if s == "\255\216\255" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Jpeg.info(r: Bytes.Reader): (Info?, Err.Err?) + return Codec.info(r.buf, r.base, r.limit - r.base) +end + +function Jpeg.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + if opts ~= nil and type(opts) ~= "table" then + return nil, Err.new(Err.ARG, "options must be a table") + end + local o = opts or {} :: DecodeOptions + -- two JPEGs back to back are an image and a preview, as in MPF + return Codec.decode(r.buf, r.base, r.limit - r.base, { + scale = o.scale, + orient = o.orient, + native = o.native, + maxPixels = o.maxPixels, + fields = false, + }) +end + +-- ------------------------------------------------------------------------------------------------ encode +local function metaSegments(meta: any): ({ { marker: number, data: buffer } }, { unit: number, x: number, y: number }?) + local segments = {} + if type(meta.exif) == "buffer" and buffer.len(meta.exif) <= 65527 then + local d = buffer.create(buffer.len(meta.exif) + 6) + buffer.writestring(d, 0, "Exif\0\0") + buffer.copy(d, 6, meta.exif) + table.insert(segments, { marker = 0xE1, data = d }) + end + if type(meta.icc) == "buffer" then + local icc = meta.icc :: buffer + local n = buffer.len(icc) + local chunk = 65519 + local count = math.max(1, math.ceil(n / chunk)) + if count <= 255 then + for i = 1, count do + local a = (i - 1) * chunk + local l = math.min(chunk, n - a) + local d = buffer.create(l + 14) + buffer.writestring(d, 0, "ICC_PROFILE\0") + buffer.writeu8(d, 12, i) + buffer.writeu8(d, 13, count) + buffer.copy(d, 14, icc, a, l) + table.insert(segments, { marker = 0xE2, data = d }) + end + end + end + local text = meta.text + if type(text) == "table" and type(text.comment) == "string" and #text.comment <= 65533 then + table.insert(segments, { marker = 0xFE, data = buffer.fromstring(text.comment) }) + end + local density = nil + if type(meta.dpi) == "table" and type(meta.dpi.x) == "number" and type(meta.dpi.y) == "number" then + density = { unit = 1, x = math.clamp(math.floor(meta.dpi.x + 0.5), 1, 65535), y = math.clamp(math.floor(meta.dpi.y + 0.5), 1, 65535) } + end + return segments, density +end + +function Jpeg.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" then + return nil, Err.new(Err.ARG, "needs an Image") + end + if opts ~= nil and type(opts) ~= "table" then + return nil, Err.new(Err.ARG, "options must be a table") + end + local o: any = opts or {} + local segments, density = {}, nil + if o.meta ~= false then + segments, density = metaSegments(img.meta or {}) + elseif type(img.meta) == "table" then + local _ + _, density = metaSegments({ dpi = img.meta.dpi }) + end + return Codec.encode(img, { + quality = o.quality, + subsampling = o.subsampling, + progressive = o.progressive, + optimize = o.optimize, + gray = o.gray, + restart = o.restart, + jfif = o.jfif, + density = density, + segments = segments, + }) +end + +return Jpeg +end +__FILES["image/ktx"] = function() + +-- image/ktx: Khronos KTX 1.1 / KTX 2.0. Supports: KTX1 (GL compressed and uncompressed, big-endian), KTX2 (VkFormat BCn +-- / ETC2 / EAC / uncompressed; Zstd and ZLIB supercompression), mips, cubes, arrays, 3D, KTXorientation; writes +-- uncompressed KTX2. Not supported: Basis Universal (BasisLZ / UASTC), ASTC, PVRTC. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Sniff = __include("core/Sniff") +local Types = __include("Types") +local Deflate = __include("codecs/compress/Deflate") +local Zstd = __include("codecs/compress/Zstd") +local Texel = __include("codecs/image/Texel") +local Texture = __include("codecs/image/Texture") + +-- ------------------------------------------------------------------------------------------------ contract +local Ktx = { + name = "ktx", + category = "image", + extensions = { "ktx2", "ktx" }, + mime = { "image/ktx2", "image/ktx" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/compress/Deflate", "codecs/compress/Zstd", "codecs/image/Texel", "codecs/image/Texture" }, + caps = { decode = true, encode = true, alpha = true, float = true, mipmaps = true, cubemap = true, compressed = { "bc1", "bc2", "bc3", "bc4", "bc5", "bc6h", "bc7", "etc1", "etc2", "eac" } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + native: boolean?, -- default false: rgba8 + mips: boolean?, -- default false + surfaces: boolean?, -- default true + maxPixels: number?, -- default 2^26, over every decoded surface +} +type EncodeOptions = { + pixelFormat: ("rgba8" | "rgba16" | "rgba16f" | "rgba32f")?, -- default: the image's own (rgbaf32 -> rgba32f) + srgb: boolean?, -- default: meta.colorSpace == "srgb" + mips: boolean?, -- default false + cube: boolean?, -- default: meta.layout == "cube" + zlib: number?, -- 1..9, default none + keyValue: { [string]: string }?, -- KTXwriter is always written +} + +-- ------------------------------------------------------------------------------------------------ constants +local ID1 = "\171KTX 11\187\r\n\26\n" +local ID2 = "\171KTX 20\187\r\n\26\n" + +-- VkFormat -> texture format name +local VK: { [number]: string } = { + [2] = "a4b4g4r4", [3] = "a4r4g4b4", [4] = "b5g6r5", [5] = "r5g6b5", [6] = "a1b5g5r5", [7] = "a1r5g5b5", [8] = "b5g5r5a1", + [9] = "r8", [10] = "r8s", [13] = "r8ui", [14] = "r8i", [15] = "r8", + [16] = "rg8", [17] = "rg8s", [20] = "rg8ui", [21] = "rg8i", [22] = "rg8", + [23] = "rgb8", [24] = "rgb8s", [27] = "rgb8ui", [28] = "rgb8i", [29] = "rgb8", + [30] = "bgr8", [36] = "bgr8", + [37] = "rgba8", [38] = "rgba8s", [41] = "rgba8ui", [42] = "rgba8i", [43] = "rgba8", + [44] = "bgra8", [50] = "bgra8", + [58] = "bgr10a2", [64] = "rgb10a2", + [70] = "r16", [71] = "r16s", [74] = "r16ui", [75] = "r16i", [76] = "r16f", + [77] = "rg16", [78] = "rg16s", [81] = "rg16ui", [82] = "rg16i", [83] = "rg16f", + [84] = "rgb16", [85] = "rgb16s", [88] = "rgb16ui", [89] = "rgb16i", [90] = "rgb16f", + [91] = "rgba16", [92] = "rgba16s", [95] = "rgba16ui", [96] = "rgba16i", [97] = "rgba16f", + [98] = "r32ui", [99] = "r32i", [100] = "r32f", [101] = "rg32ui", [102] = "rg32i", [103] = "rg32f", + [104] = "rgb32ui", [105] = "rgb32i", [106] = "rgb32f", [107] = "rgba32ui", [108] = "rgba32i", [109] = "rgba32f", + [122] = "r11g11b10f", [123] = "rgb9e5", [124] = "r16", [126] = "r32f", + [131] = "bc1", [132] = "bc1", [133] = "bc1", [134] = "bc1", [135] = "bc2", [136] = "bc2", [137] = "bc3", [138] = "bc3", + [139] = "bc4", [140] = "bc4s", [141] = "bc5", [142] = "bc5s", [143] = "bc6h", [144] = "bc6hs", [145] = "bc7", [146] = "bc7", + [147] = "etc2_rgb", [148] = "etc2_rgb", [149] = "etc2_rgba1", [150] = "etc2_rgba1", [151] = "etc2_rgba", [152] = "etc2_rgba", + [153] = "eac_r11", [154] = "eac_r11s", [155] = "eac_rg11", [156] = "eac_rg11s", +} +local VK_SRGB = { [15] = true, [22] = true, [29] = true, [36] = true, [43] = true, [50] = true, [132] = true, [134] = true, [136] = true, [138] = true, [146] = true, [148] = true, [150] = true, [152] = true } +local VK_OPAQUE = { [131] = true, [132] = true } -- BC1 RGB: the 3-colour mode's index 3 is opaque black +-- OpenGL compressed internal formats +local GL_COMPRESSED: { [number]: string } = { + [0x83F0] = "bc1", [0x83F1] = "bc1", [0x83F2] = "bc2", [0x83F3] = "bc3", + [0x8C4C] = "bc1", [0x8C4D] = "bc1", [0x8C4E] = "bc2", [0x8C4F] = "bc3", + [0x8DBB] = "bc4", [0x8DBC] = "bc4s", [0x8DBD] = "bc5", [0x8DBE] = "bc5s", + [0x8E8C] = "bc7", [0x8E8D] = "bc7", [0x8E8E] = "bc6hs", [0x8E8F] = "bc6h", + [0x8D64] = "etc1", [0x9274] = "etc2_rgb", [0x9275] = "etc2_rgb", [0x9276] = "etc2_rgba1", [0x9277] = "etc2_rgba1", + [0x9278] = "etc2_rgba", [0x9279] = "etc2_rgba", [0x9270] = "eac_r11", [0x9271] = "eac_r11s", [0x9272] = "eac_rg11", [0x9273] = "eac_rg11s", +} +local GL_SRGB = { [0x8C4C] = true, [0x8C4D] = true, [0x8C4E] = true, [0x8C4F] = true, [0x8E8D] = true, [0x9275] = true, [0x9277] = true, [0x9279] = true, [0x8C41] = true, [0x8C43] = true } +local GL_OPAQUE = { [0x83F0] = true, [0x8C4C] = true } +-- glFormat -> channel order; glType -> bit size, Texel suffix +local GL_ORDER: { [number]: string } = { + [0x1903] = "r", [0x8227] = "rg", [0x1907] = "rgb", [0x1908] = "rgba", [0x80E0] = "bgr", [0x80E1] = "bgra", + [0x1909] = "l", [0x190A] = "la", [0x1906] = "a", + [0x8D94] = "r", [0x8228] = "rg", [0x8D98] = "rgb", [0x8D99] = "rgba", -- the _INTEGER formats +} +local GL_INTEGER = { [0x8D94] = true, [0x8228] = true, [0x8D98] = true, [0x8D99] = true } +local GL_PACKED: { [number]: string } = { + [0x8363] = "b5g6r5", [0x8033] = "a4b4g4r4", [0x8034] = "a1b5g5r5", [0x8368] = "rgb10a2", [0x8C3B] = "r11g11b10f", [0x8C3E] = "rgb9e5", +} +local GL_TYPES: { [number]: { any } } = { + [0x1401] = { 8, "", "ui" }, [0x1400] = { 8, "s", "i" }, [0x1403] = { 16, "", "ui" }, [0x1402] = { 16, "s", "i" }, + [0x1405] = { 32, "ui", "ui" }, [0x1404] = { 32, "i", "i" }, [0x140B] = { 16, "f", "f" }, [0x1406] = { 32, "f", "f" }, +} +local FACES = { "+x", "-x", "+y", "-y", "+z", "-z" } + +local readu32, readstring = buffer.readu32, buffer.readstring + +-- ------------------------------------------------------------------------------------------------ sniff +function Ktx.sniff(r: Bytes.Reader): number + return math.max(Sniff.magic(r, ID2), Sniff.magic(r, ID1)) +end + +-- ------------------------------------------------------------------------------------------------ decode +type Info = { + version: number, -- 1 or 2 + width: number, + height: number, + depth: number, -- 1 for 2D + layers: number, + faces: number, + levels: number, + format: string?, + unsupported: string?, + srgb: boolean, + opaque: boolean, -- BC1 RGB + vkFormat: number?, + glInternalFormat: number?, + supercompression: number?, + keyValue: { [string]: string }, + bigEndian: boolean?, + typeSize: number, + dataOffset: number, -- KTX1: the first imageSize field (relative to the file) + levelIndex: { { offset: number, length: number, uncompressed: number } }?, -- KTX2 +} + +local function u64(b: buffer, o: number): number + return readu32(b, o) + readu32(b, o + 4) * 4294967296 +end + +-- key / value pairs from [p, stop): u32 length, key NUL value, padding to 4 +local function keyValues(b: buffer, p: number, stop: number, be: boolean): { [string]: string } + local kv: { [string]: string } = {} + while p + 4 <= stop do + local n = readu32(b, p) + if be then + n = bit32.byteswap(n) + end + p += 4 + if n > stop - p then + break + end + local s = readstring(b, p, n) + local z = string.find(s, "\0", 1, true) + if z then + local v = string.sub(s, z + 1) + if string.sub(v, -1) == "\0" then + v = string.sub(v, 1, -2) + end + kv[string.sub(s, 1, z - 1)] = v + end + p += n + (3 - (n + 3) % 4) + end + return kv +end + +local function info1(r: Bytes.Reader): (Info?, Err.Err?) + local b, o, n = r.buf, r.base, r.limit - r.base + if n < 64 then + return nil, Err.new(Err.TRUNCATED, "short KTX1 header", o) + end + local e = readu32(b, o + 12) + local be = e == 0x01020304 + if not be and e ~= 0x04030201 then + return nil, Err.new(Err.CORRUPT, "bad endianness field", o + 12) + end + local function f(i: number): number + local v = readu32(b, o + 16 + i * 4) + return if be then bit32.byteswap(v) else v + end + local glType, typeSize, glFormat, internal = f(0), f(1), f(2), f(3) + local w, h, d, arr, faces, levels, kvBytes = f(5), f(6), f(7), f(8), f(9), f(10), f(11) + if w == 0 or w > 65536 or h > 65536 or d > 2048 or arr > 4096 or (faces ~= 1 and faces ~= 6) or levels > 32 then + return nil, Err.new(Err.CORRUPT, "bad KTX1 header", o + 16) + end + if 64 + kvBytes > n then + return nil, Err.new(Err.TRUNCATED, "key / value data runs past the end", o + 64) + end + local info: Info = { + version = 1, + width = w, + height = math.max(1, h), + depth = math.max(1, d), + layers = math.max(1, arr), + faces = faces, + levels = math.max(1, levels), + srgb = GL_SRGB[internal] == true, + opaque = GL_OPAQUE[internal] == true, + glInternalFormat = internal, + keyValue = keyValues(b, o + 64, o + 64 + kvBytes, be), + bigEndian = be, + typeSize = typeSize, + dataOffset = 64 + kvBytes, + } + if glType == 0 then + info.format = GL_COMPRESSED[internal] + if not info.format then + info.unsupported = string.format("compressed glInternalFormat 0x%04X", internal) + end + else + local name = GL_PACKED[glType] + if not name then + local order = GL_ORDER[glFormat] + local int = GL_INTEGER[glFormat] == true + -- glType -> component bits, Texel suffix (normalized / integer) + local t = GL_TYPES[glType] + local size: number? = t and t[1] + local suffix: string = if t then (if int then t[3] else t[2]) else "" + if order and size then + name = order .. tostring(size) .. suffix + end + end + if name and Texel.FORMATS[name] then + info.format = name + else + info.unsupported = string.format("glFormat 0x%04X / glType 0x%04X", glFormat, glType) + end + end + return info, nil +end + +local function info2(r: Bytes.Reader): (Info?, Err.Err?) + local b, o, n = r.buf, r.base, r.limit - r.base + if n < 80 then + return nil, Err.new(Err.TRUNCATED, "short KTX2 header", o) + end + local vk, typeSize = readu32(b, o + 12), readu32(b, o + 16) + local w, h, d = readu32(b, o + 20), readu32(b, o + 24), readu32(b, o + 28) + local layers, faces, levels, scheme = readu32(b, o + 32), readu32(b, o + 36), readu32(b, o + 40), readu32(b, o + 44) + if w == 0 or w > 65536 or h > 65536 or d > 2048 or layers > 4096 or (faces ~= 1 and faces ~= 6) or levels > 32 then + return nil, Err.new(Err.CORRUPT, "bad KTX2 header", o + 20) + end + local nl = math.max(1, levels) + if 80 + nl * 24 > n then + return nil, Err.new(Err.TRUNCATED, "level index runs past the end", o + 80) + end + local dfdOff, dfdLen, kvOff, kvLen = readu32(b, o + 48), readu32(b, o + 52), readu32(b, o + 56), readu32(b, o + 60) + local info: Info = { + version = 2, + width = w, + height = math.max(1, h), + depth = math.max(1, d), + layers = math.max(1, layers), + faces = faces, + levels = nl, + srgb = VK_SRGB[vk] == true, + opaque = VK_OPAQUE[vk] == true, + vkFormat = vk, + supercompression = scheme, + keyValue = if kvLen > 0 and kvOff + kvLen <= n then keyValues(b, o + kvOff, o + kvOff + kvLen, false) else {}, + typeSize = typeSize, + dataOffset = 0, + levelIndex = {}, + } + for i = 0, nl - 1 do + local q = o + 80 + i * 24 + table.insert(info.levelIndex :: any, { offset = u64(b, q), length = u64(b, q + 8), uncompressed = u64(b, q + 16) }) + end + -- the colour model of the DFD tells Basis Universal apart + local model = -1 + if dfdLen >= 16 and dfdOff + dfdLen <= n then + model = buffer.readu8(b, o + dfdOff + 12) + if buffer.readu8(b, o + dfdOff + 14) == 2 then + info.srgb = true + end + end + if scheme == 1 or model == 163 then + info.unsupported = "Basis Universal ETC1S / BasisLZ" + elseif model == 166 then + info.unsupported = "Basis Universal UASTC" + elseif scheme > 3 then + info.unsupported = "supercompression scheme " .. scheme + elseif vk == 0 then + info.unsupported = "VK_FORMAT_UNDEFINED" + else + info.format = VK[vk] + if not info.format then + info.unsupported = "VkFormat " .. vk .. (if vk >= 157 and vk <= 184 or vk >= 1000066000 then " (ASTC)" else "") + end + end + return info, nil +end + +function Ktx.info(r: Bytes.Reader): (Info?, Err.Err?) + local id = r:peek(12) + if id == ID2 then + return info2(r) + elseif id == ID1 then + return info1(r) + end + return nil, Err.new(Err.CORRUPT, "not a KTX file", r.base) +end + +local function swapped(b: buffer, p: number, n: number, size: number): buffer + local out = buffer.create(n) + buffer.copy(out, 0, b, p, n) + for i = 0, n - size, size do + if size == 2 then + buffer.writeu16(out, i, bit32.rshift(bit32.byteswap(buffer.readu16(out, i)), 16)) + else + buffer.writeu32(out, i, bit32.byteswap(buffer.readu32(out, i))) + end + end + return out +end + +-- flips the rows of a decoded surface (KTXorientation T=u) +local function flip(img: Types.Image) + local row = img.width * (Types.BPP[img.format] or 4) + local px = img.pixels + local tmp = buffer.create(row) + for y = 0, img.height // 2 - 1 do + local a, z = y * row, (img.height - 1 - y) * row + buffer.copy(tmp, 0, px, a, row) + buffer.copy(px, a, px, z, row) + buffer.copy(px, z, tmp, 0, row) + end +end + +function Ktx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local info, ierr = Ktx.info(r) + if not info then + return nil, ierr + end + local fmt = info.format + if not fmt then + return nil, Err.new(Err.UNSUPPORTED, info.unsupported or "format") + end + local native = opts and opts.native or false + local wantMips = opts and opts.mips or false + local wantAll = not (opts and opts.surfaces == false) + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + local b, base, limit = r.buf, r.base, r.limit + local bw, bh, bbytes = Texture.block(fmt) + local blockFmt = bw == 4 + local orient = info.keyValue.KTXorientation or "" + local up = string.find(orient, "T=u", 1, true) ~= nil or (info.version == 2 and string.sub(orient, 2, 2) == "u") + local list: { Texture.Surface } = {} + local pixels = 0 + local count = info.layers * info.faces + local p = base + info.dataOffset + local w, h, d = info.width, info.height, info.depth + for level = 0, info.levels - 1 do + local want = level == 0 or wantMips + local lb, lp = b, 0 + local rowPitch: number? = nil + local imgSize = Texture.size(fmt, w, h) :: number + local stride = imgSize + if info.version == 1 then + if p + 4 > limit then + if level == 0 then + return nil, Err.new(Err.TRUNCATED, "missing level 0", p) + end + break + end + local declared = readu32(b, p) + if info.bigEndian then + declared = bit32.byteswap(declared) + end + p += 4 + if not blockFmt then + local tight = (bbytes :: number) * w + rowPitch = tight + (3 - (tight + 3) % 4) + imgSize = (rowPitch :: number) * h + end + stride = imgSize + (3 - (imgSize + 3) % 4) -- cube padding + local total = stride * count * d + if declared < imgSize * (if info.faces == 6 and info.layers == 1 then 1 else count * d) and level == 0 then + return nil, Err.new(Err.CORRUPT, "imageSize too small for the format", p - 4) + end + if p + total > limit then + if level == 0 then + return nil, Err.new(Err.TRUNCATED, "level 0 data runs past the end", p) + end + break + end + lp = p + p += total + p += 3 - (total + 3) % 4 + if info.bigEndian and info.typeSize > 1 and want then + lb, lp = swapped(b, lp, total, info.typeSize), 0 + end + else + local li = (info.levelIndex :: any)[level + 1] + local off, len = base + li.offset, li.length + if off + len > limit or li.offset < 80 then + if level == 0 then + return nil, Err.new(Err.TRUNCATED, "level 0 data runs past the end", off) + end + break + end + local expect = imgSize * count * d + if want then + local scheme = info.supercompression + if scheme == 2 or scheme == 3 then + if li.uncompressed < expect or li.uncompressed > 2 ^ 31 then + return nil, Err.new(Err.CORRUPT, "bad uncompressed level size", base + 80 + level * 24) + end + local out, zerr + if scheme == 2 then + out, zerr = Zstd.decompress(b, off, len, { maxBytes = li.uncompressed }) + else + out, zerr = Deflate.zlib(b, off, len, li.uncompressed) + end + if not out then + return nil, Err.wrap(zerr) + end + lb, lp = out, 0 + else + lb, lp = b, off + end + if lp + expect > buffer.len(lb) then + return nil, Err.new(Err.TRUNCATED, "level " .. level .. " is too small", off) + end + end + end + if want then + for layer = 0, count - 1 do + for slice = 0, d - 1 do + if level == 0 and not wantAll and (layer > 0 or slice > 0) then + continue + end + if level > 0 and (layer > 0 or slice > 0) then + continue + end + pixels += w * h + if pixels > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("over the %d pixel limit", maxPixels)) + end + local at = lp + (layer * d + slice) * stride + local px, pf + if rowPitch then + px, pf = Texel.decode(fmt, lb, at, w, h, native, rowPitch) + else + px, pf = Texture.decode(fmt, lb, at, w, h, native) + end + if not px then + return nil, Err.from(pf, at) + end + local im = Texture.image(px, pf, w, h) + if info.opaque then + for i = 0, w * h - 1 do + buffer.writeu8(px, i * 4 + 3, 255) + end + end + if up then + flip(im) + end + table.insert(list, { level = level, layer = layer, face = layer % info.faces, slice = slice, image = im }) + end + end + end + w, h, d = math.max(1, w // 2), math.max(1, h // 2), math.max(1, d // 2) + end + local layout = if info.depth > 1 then "volume" elseif info.faces == 6 then "cube" elseif info.layers > 1 then "array" else "2d" + local img = Texture.assemble(list, layout) + if not img then + return nil, Err.new(Err.TRUNCATED, "no image data") + end + if info.faces == 6 then + img.meta.faces = table.clone(FACES) + end + if info.srgb then + img.meta.colorSpace = "srgb" + elseif string.find(fmt, "f$") or fmt == "bc6h" or fmt == "bc6hs" or fmt == "rgb9e5" then + img.meta.colorSpace = "linear" + end + img.meta.keyValue = info.keyValue + img.meta.source = { + format = "ktx", + version = info.version, + pixelFormat = fmt, + vkFormat = info.vkFormat, + glInternalFormat = info.glInternalFormat, + supercompression = info.supercompression, + mips = info.levels, + layers = info.layers, + depth = info.depth, + } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local OUT: { [string]: { number } } = { + rgba8 = { 37, 4, 1 }, + rgba16 = { 91, 8, 2 }, + rgba16f = { 97, 8, 2 }, + rgba32f = { 109, 16, 4 }, +} + +-- the DFD: one basic descriptor block with four samples (R G B A) +local function dfd(f: string, srgb: boolean): buffer + local spec = OUT[f] + local texel, comp = spec[2], spec[3] + local float = f == "rgba16f" or f == "rgba32f" + local w = Bytes.writer(92) + local blockSize = 24 + 16 * 4 + w:u32le(4 + blockSize) + w:u32le(0) -- vendor 0, descriptor type 0 + w:u32le(2 + blockSize * 65536) -- version 2, block size + w:u8(1) -- colour model RGBSDA + w:u8(1) -- primaries BT.709 + w:u8(if srgb then 2 else 1) -- transfer: sRGB / linear + w:u8(0) -- straight alpha + w:u32le(0) -- texel block 1 x 1 x 1 x 1 + w:u32le(texel) -- bytesPlane0 + w:u32le(0) + for c = 0, 3 do + local channel = if c == 3 then 15 else c + local qual = (if float then 0xC0 else 0) + (if srgb and c == 3 then 0x10 else 0) + w:u16le(c * comp * 8) + w:u8(comp * 8 - 1) + w:u8(channel + qual) + w:u32le(0) -- sample position + if float then + w:u32le(0xBF800000) + w:u32le(0x3F800000) + else + w:u32le(0) + w:u32le(if comp == 1 then 255 else 65535) + end + end + return w:finish() +end + +function Ktx.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or type(img.pixels) ~= "buffer" or type(img.width) ~= "number" or img.width < 1 or img.height < 1 then + return nil, Err.new(Err.ARG, "needs an Image") + end + local pf = img.format + if pf ~= "rgba8" and pf ~= "rgba16" and pf ~= "rgbaf32" then + return nil, Err.new(Err.ARG, "needs an rgba8, rgba16 or rgbaf32 Image (got " .. tostring(pf) .. ")") + end + local f: string = (opts and opts.pixelFormat) or (if pf == "rgbaf32" then "rgba32f" else pf) + local spec = OUT[f] + if not spec then + return nil, Err.new(Err.ARG, "unknown pixelFormat " .. tostring(f)) + end + local needs = if f == "rgba16f" or f == "rgba32f" then "rgbaf32" else f + if pf ~= needs then + return nil, Err.new(Err.ARG, string.format("pixelFormat %s needs an %s Image", f, needs)) + end + local srgb = f == "rgba8" and (if opts and opts.srgb ~= nil then opts.srgb else (img.meta and img.meta.colorSpace == "srgb")) + local images: { Types.Image } = { img } + if img.frames and #img.frames > 1 then + images = {} + for i, fr in img.frames do + local fi = fr.image + if type(fi) ~= "table" or fi.width ~= img.width or fi.height ~= img.height or fi.format ~= pf then + return nil, Err.new(Err.ARG, "frame " .. i .. ": every surface needs the image's size and pixel format") + end + images[i] = fi + end + end + local cube = if opts and opts.cube ~= nil then opts.cube else (img.meta and img.meta.layout == "cube") + if cube and (#images % 6 ~= 0 or img.width ~= img.height) then + return nil, Err.new(Err.ARG, "a cube map needs 6 square faces per layer") + end + local faces = if cube then 6 else 1 + local layers = #images // faces + local levels = 1 + if opts and opts.mips then + local m = math.max(img.width, img.height) + while m > 1 do + m //= 2 + levels += 1 + end + end + local zl = opts and opts.zlib + if zl ~= nil and (type(zl) ~= "number" or zl < 1 or zl > 9) then + return nil, Err.new(Err.ARG, "zlib level must be 1..9") + end + local levelData: { buffer } = {} + local raw: { number } = {} + local cur = table.clone(images) + for lv = 1, levels do + local w = Bytes.writer() + for i, im in cur do + local data = if f == "rgba16f" then Texture.toHalf(im.pixels, im.width * im.height) else im.pixels + w:bytes(data, 0, im.width * im.height * spec[2]) + if lv < levels then + cur[i] = Texture.halve(im) + end + end + local lb = w:finish() + raw[lv] = buffer.len(lb) + if zl then + lb = Deflate.zlibCompress(lb, { level = zl }) :: buffer + end + levelData[lv] = lb + end + local kvw = Bytes.writer() + local pairs_: { { string } } = { { "KTXwriter", "rosetta" } } + if opts and opts.keyValue then + for k, v in opts.keyValue do + if k ~= "KTXwriter" then + table.insert(pairs_, { k, v }) + end + end + end + table.sort(pairs_, function(a: { string }, c: { string }): boolean + return a[1] < c[1] + end) + for _, kv in pairs_ do + local n = #kv[1] + 1 + #kv[2] + 1 + kvw:u32le(n) + kvw:string(kv[1]) + kvw:u8(0) + kvw:string(kv[2]) + kvw:u8(0) + kvw:fill(0, 3 - (n + 3) % 4) + end + local kvd = kvw:finish() + local d = dfd(f, srgb == true) + local dfdOff = 80 + levels * 24 + local kvOff = dfdOff + buffer.len(d) + local dataStart = kvOff + buffer.len(kvd) + local align = if zl then 1 else (if spec[2] % 4 == 0 then spec[2] else 4) + -- smallest level first + local offsets: { number } = {} + local p = dataStart + for lv = levels, 1, -1 do + p += (align - p % align) % align + offsets[lv] = p + p += buffer.len(levelData[lv]) + end + local out = Bytes.writer(p) + out:string(ID2) + out:u32le(if f == "rgba8" and srgb then 43 else spec[1]) + out:u32le(spec[3]) + out:u32le(img.width) + out:u32le(img.height) + out:u32le(0) + out:u32le(if layers > 1 then layers else 0) + out:u32le(faces) + out:u32le(levels) + out:u32le(if zl then 3 else 0) + out:u32le(dfdOff) + out:u32le(buffer.len(d)) + out:u32le(kvOff) + out:u32le(buffer.len(kvd)) + out:u64le(0) + out:u64le(0) + for lv = 1, levels do + out:u64le(offsets[lv]) + out:u64le(buffer.len(levelData[lv])) + out:u64le(raw[lv]) + end + out:bytes(d) + out:bytes(kvd) + for lv = levels, 1, -1 do + out:fill(0, offsets[lv] - out:tell()) + out:bytes(levelData[lv]) + end + return out:finish(), nil +end + +return Ktx +end +__FILES["image/pcx"] = function() + +-- image/pcx: ZSoft PC Paintbrush (ZSoft "Technical Reference Manual" header and RLE). Supports: 1-bit, 1-bit x 2..4 +-- planes (EGA), 2 / 4-bit packed, 8-bit with the 256-colour end palette, 8-bit x 3 / 4 planes, RLE across scan lines, +-- uncompressed, DPI; writes 8-bit palette or 24 / 32-bit planes. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Pixels = __include("codecs/image/Pixels") + +-- ------------------------------------------------------------------------------------------------ contract +local Pcx = { + name = "pcx", + category = "image", + extensions = { "pcx", "pcc", "dcx" }, + mime = { "image/vnd.zbrush.pcx", "image/x-pcx" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Pixels" }, + caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 1, 2, 4, 8, 24, 32 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + maxPixels: number?, -- default 2^26 +} +type EncodeOptions = { + palette: boolean?, -- default true; false: always 24 / 32-bit planes +} + +local readu8, readu16 = buffer.readu8, buffer.readu16 + +-- ------------------------------------------------------------------------------------------------ sniff +function Pcx.sniff(r: Bytes.Reader): number + if r:size() < 128 then + return 0 + end + local m, v, e, bpp = r:peekU8(0), r:peekU8(1), r:peekU8(2), r:peekU8(3) + if m ~= 10 or (v ~= 0 and v ~= 2 and v ~= 3 and v ~= 4 and v ~= 5) or e > 1 then + return 0 + end + return if bpp == 1 or bpp == 2 or bpp == 4 or bpp == 8 then 0.8 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Pcx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local b, o, limit = r.buf, r.base, r.limit + if limit - o < 128 then + return nil, Err.new(Err.TRUNCATED, "short header", o) + end + if readu8(b, o) ~= 10 then + return nil, Err.new(Err.CORRUPT, "not a PCX file", o) + end + local version, enc, bpp = readu8(b, o + 1), readu8(b, o + 2), readu8(b, o + 3) + local x0, y0, x1, y1 = readu16(b, o + 4), readu16(b, o + 6), readu16(b, o + 8), readu16(b, o + 10) + local planes, bpl = readu8(b, o + 65), readu16(b, o + 66) + local w, h = x1 - x0 + 1, y1 - y0 + 1 + if x1 < x0 or y1 < y0 then + return nil, Err.new(Err.CORRUPT, "bad window", o + 4) + end + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + if w * h > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels)) + end + local kind + if bpp == 8 and planes == 1 then + kind = "pal8" + elseif bpp == 8 and (planes == 3 or planes == 4) then + kind = "rgb" + elseif bpp == 1 and planes >= 1 and planes <= 4 then + kind = "planar" + elseif (bpp == 2 or bpp == 4) and planes == 1 then + kind = "packed" + else + return nil, Err.new(Err.UNSUPPORTED, string.format("%d bits x %d planes", bpp, planes), o + 3) + end + if bpl * 8 < w * bpp then + return nil, Err.new(Err.CORRUPT, "bytes per line too small", o + 66) + end + -- the scan lines (planes after each other per line), RLE across lines + local total = bpl * planes * h + local raw = buffer.create(total) + local p, q = o + 128, 0 + local truncated = false + if enc == 1 then + while q < total do + if p >= limit then + truncated = true + break + end + local c = readu8(b, p) + p += 1 + if c >= 0xC0 then + if p >= limit then + truncated = true + break + end + local n = math.min(c - 0xC0, total - q) + buffer.fill(raw, q, readu8(b, p), n) + p += 1 + q += n + else + buffer.writeu8(raw, q, c) + q += 1 + end + end + else + local n = math.min(total, limit - p) + buffer.copy(raw, 0, b, p, n) + p += n + truncated = n < total + end + local pal = buffer.create(1024) + local function setPal(i: number, rr: number, gg: number, bb: number) + buffer.writeu32(pal, i * 4, rr + gg * 256 + bb * 65536 + 0xFF000000) + end + if kind == "pal8" then + local at = limit - 769 + if at >= p and readu8(b, at) == 12 then + for i = 0, 255 do + setPal(i, readu8(b, at + 1 + i * 3), readu8(b, at + 2 + i * 3), readu8(b, at + 3 + i * 3)) + end + else + for i = 0, 255 do + setPal(i, i, i, i) + end + end + elseif kind == "planar" and planes == 1 then + setPal(0, 0, 0, 0) + setPal(1, 255, 255, 255) + else + for i = 0, 15 do + setPal(i, readu8(b, o + 16 + i * 3), readu8(b, o + 17 + i * 3), readu8(b, o + 18 + i * 3)) + end + end + local img = Types.Image.new(w, h, "rgba8") + local px = img.pixels + if kind == "pal8" or kind == "packed" then + Pixels.indexed(raw, 0, bpl, bpp, px, w, h, true, pal) + elseif kind == "planar" then + for y = 0, h - 1 do + local row = y * bpl * planes + for x = 0, w - 1 do + local idx = 0 + for pl = 0, planes - 1 do + local byte = readu8(raw, row + pl * bpl + bit32.rshift(x, 3)) + idx += bit32.band(bit32.rshift(byte, 7 - bit32.band(x, 7)), 1) * bit32.lshift(1, pl) + end + buffer.writeu32(px, (y * w + x) * 4, buffer.readu32(pal, idx * 4)) + end + end + else + for y = 0, h - 1 do + local row = y * bpl * planes + for x = 0, w - 1 do + local d = (y * w + x) * 4 + buffer.writeu8(px, d, readu8(raw, row + x)) + buffer.writeu8(px, d + 1, readu8(raw, row + bpl + x)) + buffer.writeu8(px, d + 2, readu8(raw, row + 2 * bpl + x)) + buffer.writeu8(px, d + 3, if planes == 4 then readu8(raw, row + 3 * bpl + x) else 255) + end + end + end + if kind == "pal8" or kind == "packed" or (kind == "planar" and planes > 1) then + local list: { { number } } = {} + for i = 0, (if kind == "pal8" then 256 else bit32.lshift(1, bpp * planes)) - 1 do + local v = buffer.readu32(pal, i * 4) + list[i + 1] = { bit32.band(v, 255), bit32.band(bit32.rshift(v, 8), 255), bit32.band(bit32.rshift(v, 16), 255), 255 } + end + img.meta.palette = list + end + local hd, vd = readu16(b, o + 12), readu16(b, o + 14) + if hd > 0 and vd > 0 then + img.meta.dpi = { x = hd, y = vd } + end + if truncated then + img.meta.truncated = true + end + img.meta.source = { format = "pcx", version = version, bitDepth = bpp * planes, planes = planes, x = x0, y = y0, rle = enc == 1 } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function rleRow(out: Bytes.Writer, src: buffer, p: number, n: number) + local i = 0 + while i < n do + local v = readu8(src, p + i) + local run = 1 + while i + run < n and run < 63 and readu8(src, p + i + run) == v do + run += 1 + end + if run > 1 or v >= 0xC0 then + out:u8(0xC0 + run) + end + out:u8(v) + i += run + end +end + +function Pcx.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "needs an rgba8 Image") + end + local w, h = img.width, img.height + if w < 1 or h < 1 or w > 65535 or h > 65535 then + return nil, Err.new(Err.ARG, "size must be 1..65535") + end + local px = img.pixels + local cols, alpha = Pixels.colours(px, w * h, 256) + local usePal = not alpha and #cols <= 256 and not (opts and opts.palette == false) + local planes = if usePal then 1 elseif alpha then 4 else 3 + local bpl = w + w % 2 + local out = Bytes.writer(128 + w * h * planes + 800) + out:u8(10) + out:u8(5) + out:u8(1) + out:u8(8) + out:u16le(0) + out:u16le(0) + out:u16le(w - 1) + out:u16le(h - 1) + local dpi = img.meta and img.meta.dpi + out:u16le(if dpi then math.floor(dpi.x + 0.5) else 72) + out:u16le(if dpi then math.floor(dpi.y + 0.5) else 72) + out:fill(0, 48) + out:u8(0) + out:u8(planes) + out:u16le(bpl) + out:u16le(1) + out:fill(0, 58) + local row = buffer.create(bpl) + local index: { [number]: number } = {} + for i, c in cols do + index[c] = i - 1 + end + for y = 0, h - 1 do + for pl = 0, planes - 1 do + for x = 0, w - 1 do + local s = (y * w + x) * 4 + local v + if usePal then + v = index[bit32.band(buffer.readu32(px, s), 0xFFFFFF)] or 0 + else + v = readu8(px, s + pl) + end + buffer.writeu8(row, x, v) + end + rleRow(out, row, 0, bpl) + end + end + if usePal then + out:u8(12) + for i = 0, 255 do + local c = cols[i + 1] or 0 + out:u8(bit32.band(c, 255)) + out:u8(bit32.band(bit32.rshift(c, 8), 255)) + out:u8(bit32.rshift(c, 16)) + end + end + return out:finish(), nil +end + +return Pcx +end +__FILES["image/pnm"] = function() + +-- image/pnm: Netpbm, from the Netpbm format pages: PBM (P1 / P4), PGM (P2 / P5), PPM (P3 / P6), PAM (P7, depth 1..4) +-- and PFM (PF / Pf, either byte order, bottom-up rows). Supports: maxval 1..65535, PFM to rgba8 as clamp(v, 0, 1) * +-- 255; writes all seven types. Not supported: multi-image streams, PAM depths above 4. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Codec = __include("image/pnm/Codec") + +-- ------------------------------------------------------------------------------------------------ contract +local Pnm = { + name = "pnm", + category = "image", + extensions = { "pnm", "pbm", "pgm", "ppm", "pam", "pfm" }, + mime = { "image/x-portable-anymap", "image/x-portable-bitmap", "image/x-portable-graymap", "image/x-portable-pixmap", "image/x-portable-arbitrarymap", "image/x-portable-floatmap" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, alpha = true, depths = { 1, 8, 16, 32 }, float = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + native: boolean?, -- default false: rgba8 + maxPixels: number?, -- default 2^26 +} +type EncodeOptions = { + format: string?, -- default: grey -> pgm, opaque colour -> ppm, alpha -> pam, rgbaf32 -> pfm; "pnm" means the default + ascii: boolean?, -- default false + maxval: number?, -- 1..65535, default 255 (65535 for 16-bit / float sources) + threshold: number?, -- 0..255, default 128 +} + +-- ------------------------------------------------------------------------------------------------ constants +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 +function Pnm.sniff(r: Bytes.Reader): number + if r:remaining() < 3 then + return 0 + end + local a, b, c = r:peekU8(0), r:peekU8(1), r:peekU8(2) + if a ~= 80 then -- 'P' + return 0 + end + local ws = c == 32 or (c >= 9 and c <= 13) + if b >= 49 and b <= 55 and ws then -- P1..P7 + return 0.9 + end + if (b == 70 or b == 102) and ws then -- PF / Pf + return 0.9 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function isSpace(c: number): boolean + return c == 32 or (c >= 9 and c <= 13) +end + +local function token(b: buffer, p: number, limit: number): (string?, number) + while p < limit do + local c = readu8(b, p) + if c == 35 then + while p < limit and readu8(b, p) ~= 10 and readu8(b, p) ~= 13 do + p += 1 + end + elseif isSpace(c) then + p += 1 + else + break + end + end + local s = p + while p < limit and not isSpace(readu8(b, p)) and readu8(b, p) ~= 35 do + p += 1 + end + if p == s then + return nil, p + end + return buffer.readstring(b, s, p - s), p +end + +local function int(s: string?): number? + if s == nil or not string.match(s, "^%d+$") or #s > 9 then + return nil + end + return tonumber(s) +end + +function Pnm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + local native = opts and opts.native or false + local b, limit = r.buf, r.limit + if r.limit - r.base < 3 or readu8(b, r.base) ~= 80 then + return nil, Err.new(Err.CORRUPT, "not a Netpbm file", r.base) + end + local kind = string.char(readu8(b, r.base + 1)) + local p = r.base + 2 + 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 + local scale: number? = nil + if kind == "1" or kind == "2" or kind == "3" or kind == "4" or kind == "5" or kind == "6" or kind == "F" or kind == "f" then + local t1, t2, t3 + t1, p = token(b, p, limit) + t2, p = token(b, p, limit) + w, h = int(t1), int(t2) + if kind == "1" or kind == "4" then + maxval = 1 + elseif kind == "F" or kind == "f" then + t3, p = token(b, p, limit) + scale = if t3 then tonumber(t3) else nil + if scale == nil or scale == 0 then + return nil, Err.new(Err.CORRUPT, "bad PFM scale", p) + end + maxval = 1 + else + t3, p = token(b, p, limit) + maxval = int(t3) + end + if w == nil or h == nil or maxval == nil then + return nil, if p >= limit then Err.new(Err.TRUNCATED, "header ends early", p) else Err.new(Err.CORRUPT, "bad header", p) + end + if kind ~= "1" and kind ~= "2" and kind ~= "3" then + p += 1 -- exactly one whitespace byte before binary data + 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 :: number) > 255 then 2 else 1 + elseif kind == "7" then + local depth: number? + while true do + local key + key, p = token(b, p, limit) + if key == nil then + return nil, Err.new(Err.TRUNCATED, "PAM header ends early", p) + end + if key == "ENDHDR" then + break + end + local v + v, p = token(b, p, limit) + if key == "WIDTH" then + w = int(v) + elseif key == "HEIGHT" then + h = int(v) + elseif key == "DEPTH" then + depth = int(v) + elseif key == "MAXVAL" then + maxval = int(v) + elseif key == "TUPLTYPE" then + tupl = v + while p < limit and readu8(b, p) ~= 10 do + p += 1 + end + end + end + -- ENDHDR ends with a newline + while p < limit and readu8(b, p) ~= 10 do + p += 1 + end + p += 1 + 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 :: number) < 1 or (depth :: number) > 4 then + return nil, Err.new(Err.UNSUPPORTED, "PAM depth " .. (depth :: number)) + end + 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 + 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 + if w * h > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels)) + end + local n = w * h + local img: Types.Image + local colorType = if ch == 1 then "gray" elseif ch == 2 then "graya" elseif ch == 3 then "rgb" else "rgba" + if scale then + local f = Types.Image.new(w, h, "rgbaf32") + local ok, e = Codec.readFloats(b, p, limit, w, h, ch, (scale :: number) < 0, f.pixels) + if not ok then + return nil, Err.new(Err.TRUNCATED, tostring(e)) + end + img = f + if not native then + local o = Types.Image.new(w, h, "rgba8") + for i = 0, n * 4 - 1 do + local v = buffer.readf32(f.pixels, i * 4) + buffer.writeu8(o.pixels, i, if v ~= v then 0 else math.floor(math.clamp(v, 0, 1) * 255 + 0.5)) + end + img = o + end + img.meta.source = { format = "pnm", type = if ch == 3 then "pfm" else "pfm-gray", bitDepth = 32, colorType = colorType, scale = math.abs(scale :: number), byteOrder = if (scale :: number) < 0 then "little" else "big" } + return img, nil + end + local samples = buffer.create(n * ch * 2) + local ok, e + if mode == 0 then + ok, e = Codec.readBits(b, p, limit, w, h, samples) + else + ok, e = Codec.readSamples(b, p, limit, n * ch, mode, samples) + end + if not ok then + return nil, Err.new(if e == "truncated" then Err.TRUNCATED else Err.CORRUPT, tostring(e)) + end + local fmt: Types.PixelFormat = "rgba8" + if native then + local wide = maxval > 255 + if bits or bw or ch == 1 then + fmt = if wide then "gray16" else "gray8" + elseif ch == 2 then + fmt = if wide then "rgba16" else "graya8" + elseif ch == 3 then + fmt = if wide then "rgba16" else "rgb8" + else + fmt = if wide then "rgba16" else "rgba8" + end + end + img = Types.Image.new(w, h, fmt :: Types.PixelFormat) + Codec.pack(samples, n, ch, maxval, bits, FMT_CODE[fmt], img.pixels) + local typ = if kind == "7" then "pam" elseif bits then "pbm" elseif ch == 1 then "pgm" else "ppm" + img.meta.source = { + format = "pnm", + type = typ, + ascii = mode == 3 or mode == 4, + bitDepth = if bits or bw then 1 elseif maxval > 255 then 16 else 8, + maxval = maxval, + colorType = if bits or bw then "bilevel" else colorType, + tupltype = tupl, + } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local SUBTYPES = { pbm = true, pgm = true, ppm = true, pam = true, pfm = true } + +function Pnm.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "needs an Image") + end + local fc = FMT_CODE[img.format] + if fc == nil then + return nil, Err.new(Err.ARG, "unsupported pixel format " .. tostring(img.format)) + end + 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 + local o: any = opts or {} + local n = w * h + local isGray = img.format == "gray8" or img.format == "gray16" or img.format == "graya8" + local hasAlpha = img.format == "graya8" or img.format == "rgba16" or img.format == "rgba8" or img.format == "rgbaf32" + if hasAlpha and img.format ~= "graya8" then + -- an alpha channel that is fully opaque does not count + local opaque = true + for i = 0, n - 1 do + local a + if img.format == "rgba8" then + a = buffer.readu8(img.pixels, i * 4 + 3) == 255 + elseif img.format == "rgba16" then + a = buffer.readu16(img.pixels, i * 8 + 6) == 65535 + else + a = buffer.readf32(img.pixels, i * 16 + 12) == 1 + end + if not a then + opaque = false + break + end + end + hasAlpha = not opaque + end + local sub = if type(o.format) == "string" then string.lower(o.format) else nil + if not (sub and SUBTYPES[sub]) then + if img.format == "rgbaf32" and not hasAlpha then + sub = "pfm" + elseif hasAlpha then + sub = "pam" + elseif isGray then + sub = "pgm" + else + sub = "ppm" + end + end + local ascii = o.ascii == true + local wideSrc = img.format == "gray16" or img.format == "rgba16" or img.format == "rgbaf32" + 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 + local out: buffer + local op = 0 + local function header(s: string, extra: number) + out = buffer.create(#s + extra) + buffer.writestring(out, 0, s) + op = #s + end + if sub == "pfm" then + local ch = if isGray then 1 else 3 + local src = img + if img.format ~= "rgbaf32" then + local s = Codec.extract(img.pixels, fc, n, 4, true) + src = Types.Image.new(w, h, "rgbaf32") + for i = 0, n * 4 - 1 do + buffer.writef32(src.pixels, i * 4, buffer.readu16(s, i * 2) / 65535) + end + end + header(string.format("%s\n%d %d\n-1.0\n", if ch == 3 then "PF" else "Pf", w, h), n * ch * 4) + op = Codec.writeFloats(src.pixels, w, h, ch, out, op) + return out, nil + end + local ch = if sub == "pbm" or sub == "pgm" then 1 elseif sub == "ppm" then 3 elseif isGray then (if hasAlpha then 2 else 1) else (if hasAlpha then 4 else 3) + if sub == "pbm" then + local thr = o.threshold or 128 + local s = Codec.extract(img.pixels, fc, n, 1, false) + if ascii then + local parts = table.create(h + 1) + parts[1] = string.format("P1\n%d %d\n", w, h) + for y = 0, h - 1 do + local row = table.create(w) + for x = 0, w - 1 do + row[x + 1] = if buffer.readu16(s, (y * w + x) * 2) < thr then "1" else "0" + end + parts[y + 2] = table.concat(row, " ") .. "\n" + end + return buffer.fromstring(table.concat(parts)), nil + end + header(string.format("P4\n%d %d\n", w, h), ((w + 7) // 8) * h) + op = Codec.writeBits(s, w, h, thr, out, op) + return out, nil + end + local wide = maxval > 255 + local s = Codec.extract(img.pixels, fc, n, ch, wide) + if maxval ~= 255 and maxval ~= 65535 then + local top = if wide then 65535 else 255 + for i = 0, n * ch - 1 do + buffer.writeu16(s, i * 2, (buffer.readu16(s, i * 2) * maxval + top // 2) // top) + end + end + local magic + if sub == "pam" then + local tt = if ch == 1 then "GRAYSCALE" elseif ch == 2 then "GRAYSCALE_ALPHA" elseif ch == 3 then "RGB" else "RGB_ALPHA" + header(string.format("P7\nWIDTH %d\nHEIGHT %d\nDEPTH %d\nMAXVAL %d\nTUPLTYPE %s\nENDHDR\n", w, h, ch, maxval, tt), n * ch * (if wide then 2 else 1)) + op = Codec.writeSamples(s, n * ch, wide, out, op) + return out, nil + end + magic = if sub == "pgm" then (if ascii then "P2" else "P5") else (if ascii then "P3" else "P6") + if ascii then + local parts = table.create(h + 1) + parts[1] = string.format("%s\n%d %d\n%d\n", magic, w, h, maxval) + local rowLen = w * ch + for y = 0, h - 1 do + local row = table.create(rowLen) + for i = 0, rowLen - 1 do + row[i + 1] = tostring(buffer.readu16(s, (y * rowLen + i) * 2)) + end + parts[y + 2] = table.concat(row, " ") .. "\n" + end + return buffer.fromstring(table.concat(parts)), nil + end + header(string.format("%s\n%d %d\n%d\n", magic, w, h, maxval), n * ch * (if wide then 2 else 1)) + op = Codec.writeSamples(s, n * ch, wide, out, op) + return out, nil +end + +return Pnm +end +__FILES["image/pnm/Codec"] = @native function() + + + +-- image/pnm/Codec: Netpbm sample loops: P1 digits may run together; PFM either byte order. +local readu8, writeu8, readu16, writeu16 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16 +local readf32, writef32, readu32, writeu32 = buffer.readf32, buffer.writef32, buffer.readu32, buffer.writeu32 +local byteswap = bit32.byteswap + +local Codec = {} + +-- mode 1 = binary 8-bit, 2 = binary 16-bit big-endian, 3 = ASCII decimal, 4 = ASCII P1 (single digits) +@native function Codec.readSamples(b: buffer, p: number, limit: number, count: number, mode: number, out: buffer): (boolean, string?) + if mode == 1 then + if p + count > limit then + return false, "truncated" + end + for i = 0, count - 1 do + writeu16(out, i * 2, readu8(b, p + i)) + end + return true, nil + elseif mode == 2 then + if p + count * 2 > limit then + return false, "truncated" + end + for i = 0, count - 1 do + writeu16(out, i * 2, readu8(b, p + i * 2) * 256 + readu8(b, p + i * 2 + 1)) + end + return true, nil + end + local i = 0 + while i < count do + while p < limit do + local c = readu8(b, p) + if c == 35 then -- '#' + while p < limit and readu8(b, p) ~= 10 and readu8(b, p) ~= 13 do + p += 1 + end + elseif c == 32 or (c >= 9 and c <= 13) then + p += 1 + else + break + end + end + if p >= limit then + return false, "truncated" + end + local c = readu8(b, p) + if c < 48 or c > 57 then + return false, "bad ASCII sample" + end + if mode == 4 then + writeu16(out, i * 2, c - 48) + p += 1 + else + local v = 0 + while p < limit do + local d = readu8(b, p) + if d < 48 or d > 57 then + break + end + v = math.min(v * 10 + d - 48, 65535) + p += 1 + end + writeu16(out, i * 2, v) + end + i += 1 + end + return true, nil +end + +@native function Codec.readBits(b: buffer, p: number, limit: number, w: number, h: number, out: buffer): (boolean, string?) + local rowBytes = (w + 7) // 8 + if p + rowBytes * h > limit then + return false, "truncated" + end + for y = 0, h - 1 do + local r = p + y * rowBytes + for x = 0, w - 1 do + local byte = readu8(b, r + x // 8) + writeu16(out, (y * w + x) * 2, (byte // 2 ^ (7 - x % 8)) % 2) + end + end + return true, nil +end + +Codec.RGBA8, Codec.RGB8, Codec.GRAY8, Codec.GRAYA8, Codec.RGBA16, Codec.GRAY16, Codec.RGBAF32 = 0, 1, 2, 3, 4, 5, 6 + +-- 8-bit: round(v * 255 / maxval) +@native function Codec.pack(s: buffer, n: number, ch: number, maxval: number, invert: boolean, fmt: number, dst: buffer) + local wide = fmt == 4 or fmt == 5 + local top = if wide then 65535 else 255 + local half = maxval // 2 + @native local function get(i: number): number + local v = math.min(readu16(s, i * 2), maxval) + if invert then + v = maxval - v + end + if maxval == top then + return v + end + return (v * top + half) // maxval + end + for i = 0, n - 1 do + local q = i * ch + local r, g, b, a + if ch == 1 then + r = get(q) + g, b, a = r, r, top + elseif ch == 2 then + r = get(q) + g, b, a = r, r, get(q + 1) + elseif ch == 3 then + r, g, b, a = get(q), get(q + 1), get(q + 2), top + else + 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 :: number) * 16777216) + elseif fmt == 1 then + writeu8(dst, i * 3, r) + writeu8(dst, i * 3 + 1, g) + writeu8(dst, i * 3 + 2, b) + elseif fmt == 2 then + writeu8(dst, i, r) + elseif fmt == 3 then + writeu8(dst, i * 2, r) + 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 :: number) + elseif fmt == 5 then + writeu16(dst, i * 2, r) + end + end +end + +@native function Codec.readFloats(b: buffer, p: number, limit: number, w: number, h: number, ch: number, le: boolean, dst: buffer): (boolean, string?) + if p + w * h * ch * 4 > limit then + return false, "truncated" + end + local tmp = buffer.create(4) + for y = 0, h - 1 do + local row = p + (h - 1 - y) * w * ch * 4 + for x = 0, w - 1 do + local o = (y * w + x) * 16 + for c = 0, ch - 1 do + local v + if le then + v = readf32(b, row + (x * ch + c) * 4) + else + writeu32(tmp, 0, byteswap(readu32(b, row + (x * ch + c) * 4))) + v = readf32(tmp, 0) + end + writef32(dst, o + c * 4, v) + end + if ch == 1 then + local v = readf32(dst, o) + writef32(dst, o + 4, v) + writef32(dst, o + 8, v) + end + writef32(dst, o + 12, 1) + end + end + return true, nil +end + +@native local function f(v: number): number + if v ~= v then + return 0 + end + return math.floor(math.clamp(v, 0, 1) * 65535 + 0.5) +end + +-- grey from colour: Pillow's L = (299 R + 587 G + 114 B) / 1000 +@native function Codec.extract(px: buffer, fmt: number, n: number, ch: number, wide: boolean): buffer + local out = buffer.create(n * ch * 2) + local srcWide = fmt == 4 or fmt == 5 + local isGray = fmt == 2 or fmt == 3 or fmt == 5 + for i = 0, n - 1 do + local r, g, b, a + if fmt == 0 then + r, g, b, a = readu8(px, i * 4), readu8(px, i * 4 + 1), readu8(px, i * 4 + 2), readu8(px, i * 4 + 3) + elseif fmt == 1 then + r, g, b, a = readu8(px, i * 3), readu8(px, i * 3 + 1), readu8(px, i * 3 + 2), 255 + elseif fmt == 2 then + r = readu8(px, i) + g, b, a = r, r, 255 + elseif fmt == 3 then + r, a = readu8(px, i * 2), readu8(px, i * 2 + 1) + g, b = r, r + elseif fmt == 4 then + r, g, b, a = readu16(px, i * 8), readu16(px, i * 8 + 2), readu16(px, i * 8 + 4), readu16(px, i * 8 + 6) + elseif fmt == 5 then + r = readu16(px, i * 2) + g, b, a = r, r, 65535 + else + r, g, b, a = f(readf32(px, i * 16)), f(readf32(px, i * 16 + 4)), f(readf32(px, i * 16 + 8)), f(readf32(px, i * 16 + 12)) + end + local w16 = srcWide or fmt == 6 + local gray = r + if ch <= 2 and not isGray then + gray = (r * 299 + g * 587 + b * 114) // 1000 + end + local vals = if ch == 1 then 1 elseif ch == 2 then 2 else ch + for c = 0, vals - 1 do + local v + if ch <= 2 then + 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 :: number + end + if wide and not w16 then + v *= 257 + elseif w16 and not wide then + v = (v * 255 + 32767) // 65535 + end + writeu16(out, (i * ch + c) * 2, v) + end + end + return out +end + +@native function Codec.writeSamples(s: buffer, count: number, wide: boolean, out: buffer, o: number): number + if wide then + for i = 0, count - 1 do + local v = readu16(s, i * 2) + writeu8(out, o, v // 256) + writeu8(out, o + 1, v % 256) + o += 2 + end + else + for i = 0, count - 1 do + writeu8(out, o, readu16(s, i * 2)) + o += 1 + end + end + return o +end + +@native function Codec.writeBits(s: buffer, w: number, h: number, threshold: number, out: buffer, o: number): number + for y = 0, h - 1 do + local acc, nb = 0, 0 + for x = 0, w - 1 do + acc = acc * 2 + (if readu16(s, (y * w + x) * 2) < threshold then 1 else 0) + nb += 1 + if nb == 8 then + writeu8(out, o, acc) + o += 1 + acc, nb = 0, 0 + end + end + if nb > 0 then + writeu8(out, o, acc * 2 ^ (8 - nb)) + o += 1 + end + end + return o +end + +@native function Codec.writeFloats(px: buffer, w: number, h: number, ch: number, out: buffer, o: number): number + for y = h - 1, 0, -1 do + for x = 0, w - 1 do + local q = (y * w + x) * 16 + for c = 0, ch - 1 do + writef32(out, o, readf32(px, q + c * 4)) + o += 4 + end + end + end + return o +end + +return Codec +end +__FILES["image/qoi"] = function() + +-- image/qoi: QOI, the Quite OK Image format (specification 1.0, qoiformat.org). Supports: the whole spec (RGB / RGBA, +-- both colour space tags in meta.source.colorSpace). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Codec = __include("image/qoi/Codec") + +-- ------------------------------------------------------------------------------------------------ contract +local Qoi = { + name = "qoi", + category = "image", + extensions = { "qoi" }, + mime = { "image/qoi", "image/x-qoi" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, alpha = true, depths = { 8 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + native: boolean?, -- default false: rgba8 + maxPixels: number?, -- default 2^26 +} +type EncodeOptions = { + channels: number?, -- default: 3 for rgb8 or opaque rgba8, else 4 + linear: boolean?, -- default: meta.source.colorSpace == "linear" +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Qoi.sniff(r: Bytes.Reader): number + return if r:peek(4) == "qoif" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Qoi.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + local magic = r:string(4) + local w, h = r:u32be(), r:u32be() + local channels, cs = r:u8(), r:u8() + if r.err then + return nil, r.err + end + if magic ~= "qoif" then + return nil, Err.new(Err.CORRUPT, "bad magic", r.base) + end + if w == 0 or h == 0 or (channels ~= 3 and channels ~= 4) or cs > 1 then + return nil, Err.new(Err.CORRUPT, "bad header", r.base + 4) + end + if w * h > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels)) + end + local img = Types.Image.new(w, h, "rgba8") + local ok, e = Codec.decode(r.buf, r.pos, r.limit, img.pixels, w * h) + if not ok then + return nil, Err.new(Err.TRUNCATED, tostring(e)) + end + if opts and opts.native and channels == 3 then + local rgb = Types.Image.new(w, h, "rgb8") + local src, dst = img.pixels, rgb.pixels + for i = 0, w * h - 1 do + buffer.writeu16(dst, i * 3, buffer.readu16(src, i * 4)) + buffer.writeu8(dst, i * 3 + 2, buffer.readu8(src, i * 4 + 2)) + end + img = rgb + end + img.meta.source = { format = "qoi", bitDepth = 8, colorType = if channels == 4 then "rgba" else "rgb", channels = channels, colorSpace = if cs == 1 then "linear" else "srgb" } + if cs == 1 then + img.meta.colorSpace = "linear" + end + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Qoi.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or type(img.pixels) ~= "buffer" or (img.format ~= "rgba8" and img.format ~= "rgb8") then + return nil, Err.new(Err.ARG, "needs an rgba8 or rgb8 Image") + end + local w, h = img.width, img.height + local bpp = if img.format == "rgba8" then 4 else 3 + 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 then + return nil, Err.new(Err.ARG, "bad image size or pixel buffer") + end + local channels = opts and opts.channels + if channels == nil then + channels = 3 + if bpp == 4 then + local px = img.pixels + for i = 0, w * h - 1 do + if buffer.readu8(px, i * 4 + 3) ~= 255 then + channels = 4 + break + end + end + end + elseif channels ~= 3 and channels ~= 4 then + return nil, Err.new(Err.ARG, "channels must be 3 or 4") + end + local linear = opts and opts.linear + if linear == nil then + local src = img.meta and img.meta.source + linear = (type(src) == "table" and src.colorSpace == "linear") or (img.meta and img.meta.colorSpace == "linear") or false + end + local n = w * h + local out = buffer.create(14 + n * (bpp + 1) + 8) + buffer.writestring(out, 0, "qoif") + buffer.writeu32(out, 4, bit32.byteswap(w)) + buffer.writeu32(out, 8, bit32.byteswap(h)) + 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") + o += 8 + local res = buffer.create(o) + buffer.copy(res, 0, out, 0, o) + return res, nil +end + +return Qoi +end +__FILES["image/qoi/Codec"] = @native function() + + + +-- image/qoi/Codec: QOI op loops, from the QOI specification 1.0 (qoiformat.org). +local readu8, writeu8, writeu32 = buffer.readu8, buffer.writeu8, buffer.writeu32 + +local Codec = {} + +local index = buffer.create(256) + +@native function Codec.decode(b: buffer, p: number, limit: number, out: buffer, n: number): (boolean, string?) + buffer.fill(index, 0, 0, 256) + local r, g, bl, a = 0, 0, 0, 255 + local o = 0 + local stop = n * 4 + while o < stop do + if p >= limit then + return false, "truncated" + end + local op = readu8(b, p) + p += 1 + if op == 0xFE then + if p + 3 > limit then + return false, "truncated" + end + 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 = 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 = 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 + bl = (bl + op % 4 - 2) % 256 + elseif tag == 2 then + if p >= limit then + return false, "truncated" + end + local d2 = readu8(b, p) + p += 1 + local dg = op % 64 - 32 + g = (g + dg) % 256 + r = (r + dg + d2 // 16 - 8) % 256 + bl = (bl + dg + d2 % 16 - 8) % 256 + else + local run = op % 64 -- 1..62 more copies of the previous pixel (63 / 64 are RGB / RGBA) + local v = r + g * 256 + bl * 65536 + a * 16777216 + local e = math.min(o + run * 4, stop - 4) + while o < e do + writeu32(out, o, v) + o += 4 + end + end + end + writeu32(out, o, r + g * 256 + bl * 65536 + a * 16777216) + o += 4 + local h = ((r * 3 + g * 5 + bl * 7 + a * 11) % 64) * 4 + writeu8(index, h, r) + writeu8(index, h + 1, g) + writeu8(index, h + 2, bl) + writeu8(index, h + 3, a) + end + return true, nil +end + +@native function Codec.encode(px: buffer, n: number, bpp: number, out: buffer, o: number): number + buffer.fill(index, 0, 0, 256) + local pr, pg, pb, pa = 0, 0, 0, 255 + local run = 0 + local hasA = bpp == 4 + for i = 0, n - 1 do + local q = i * bpp + local r, g, b = readu8(px, q), readu8(px, q + 1), readu8(px, q + 2) + local a = if hasA then readu8(px, q + 3) else 255 + if r == pr and g == pg and b == pb and a == pa then + run += 1 + if run == 62 or i == n - 1 then + writeu8(out, o, 0xC0 + run - 1) + o += 1 + run = 0 + end + else + if run > 0 then + writeu8(out, o, 0xC0 + run - 1) + o += 1 + run = 0 + end + local h = (r * 3 + g * 5 + b * 7 + a * 11) % 64 + local hq = h * 4 + if readu8(index, hq) == r and readu8(index, hq + 1) == g and readu8(index, hq + 2) == b and readu8(index, hq + 3) == a then + writeu8(out, o, h) + o += 1 + else + writeu8(index, hq, r) + writeu8(index, hq + 1, g) + writeu8(index, hq + 2, b) + writeu8(index, hq + 3, a) + if a == pa then + local dr = (r - pr + 128) % 256 - 128 + local dg = (g - pg + 128) % 256 - 128 + local db = (b - pb + 128) % 256 - 128 + local dgr, dgb = dr - dg, db - dg + if dr >= -2 and dr <= 1 and dg >= -2 and dg <= 1 and db >= -2 and db <= 1 then + writeu8(out, o, 0x40 + (dr + 2) * 16 + (dg + 2) * 4 + db + 2) + o += 1 + elseif dg >= -32 and dg <= 31 and dgr >= -8 and dgr <= 7 and dgb >= -8 and dgb <= 7 then + writeu8(out, o, 0x80 + dg + 32) + writeu8(out, o + 1, (dgr + 8) * 16 + dgb + 8) + o += 2 + else + writeu8(out, o, 0xFE) + writeu8(out, o + 1, r) + writeu8(out, o + 2, g) + writeu8(out, o + 3, b) + o += 4 + end + else + writeu8(out, o, 0xFF) + writeu8(out, o + 1, r) + writeu8(out, o + 2, g) + writeu8(out, o + 3, b) + writeu8(out, o + 4, a) + o += 5 + end + end + pr, pg, pb, pa = r, g, b, a + end + end + return o +end + +return Codec +end +__FILES["image/sgi"] = function() + +-- image/sgi: Silicon Graphics images (Paul Haeberli's "The SGI Image File Format" 1.00). Supports: verbatim and RLE, 1 +-- / 2 bytes per channel, 1..4 channels, dimension 1..3, bottom-up rows, the image name; writes RGB(A) 8 / 16-bit. Not +-- supported: dithered / screen / colour-map files (colormap 1..3). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Sniff = __include("core/Sniff") +local Types = __include("Types") + +-- ------------------------------------------------------------------------------------------------ contract +local Sgi = { + name = "sgi", + category = "image", + extensions = { "sgi", "rgb", "rgba", "bw", "int", "inta" }, + mime = { "image/sgi", "image/x-rgb" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" }, + caps = { decode = true, encode = true, alpha = true, depths = { 8, 16 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + native: boolean?, -- default false: rgba8 + maxPixels: number?, -- default 2^26 +} +type EncodeOptions = { + rle: boolean?, -- default true + name: string?, -- up to 79 bytes; default meta.text.name +} + +local readu8, readu16, readu32 = buffer.readu8, buffer.readu16, buffer.readu32 +local function be16(b: buffer, o: number): number + return bit32.rshift(bit32.byteswap(readu16(b, o)), 16) +end +local function be32(b: buffer, o: number): number + return bit32.byteswap(readu32(b, o)) +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Sgi.sniff(r: Bytes.Reader): number + if Sniff.magic(r, "\1\218") == 0 or r:size() < 512 then + return 0 + end + local st, bpc = r:peekU8(2), r:peekU8(3) + return if st <= 1 and (bpc == 1 or bpc == 2) then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Sgi.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local b, o, limit = r.buf, r.base, r.limit + if limit - o < 512 then + return nil, Err.new(Err.TRUNCATED, "short header", o) + end + if be16(b, o) ~= 474 then + return nil, Err.new(Err.CORRUPT, "not an SGI image", o) + end + local rle, bpc, dim = readu8(b, o + 2), readu8(b, o + 3), be16(b, o + 4) + local w, h, z = be16(b, o + 6), be16(b, o + 8), be16(b, o + 10) + if dim == 1 then + h, z = 1, 1 + elseif dim == 2 then + z = 1 + end + if rle > 1 or (bpc ~= 1 and bpc ~= 2) or dim < 1 or dim > 3 or w == 0 or h == 0 or z == 0 then + return nil, Err.new(Err.CORRUPT, "bad header", o + 2) + end + if z > 4 then + return nil, Err.new(Err.UNSUPPORTED, z .. " channels", o + 10) + end + local cmap = be32(b, o + 104) + if cmap ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "colormap type " .. cmap, o + 104) + end + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + if w * h > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels)) + end + -- 8-bit values scaled * 257 + local plane = buffer.create(w * h * z * 2) + local truncated = false + local function put(c: number, row: number, x: number, v: number) + buffer.writeu16(plane, ((c * h + row) * w + x) * 2, if bpc == 1 then v * 257 else v) + end + if rle == 0 then + local need = w * h * z * bpc + local p = o + 512 + local avail = math.min(need, limit - p) + truncated = avail < need + for i = 0, avail // bpc - 1 do + local v = if bpc == 1 then readu8(b, p + i) else be16(b, p + i * 2) + buffer.writeu16(plane, i * 2, if bpc == 1 then v * 257 else v) + end + else + local n = h * z + if o + 512 + n * 8 > limit then + return nil, Err.new(Err.TRUNCATED, "RLE tables run past the end", o + 512) + end + for c = 0, z - 1 do + for row = 0, h - 1 do + local i = c * h + row + local start, len = be32(b, o + 512 + i * 4), be32(b, o + 512 + n * 4 + i * 4) + local p = o + start + local stop = math.min(limit, p + len) + local x = 0 + while x < w and p + bpc <= stop do + local cnt = if bpc == 1 then readu8(b, p) else be16(b, p) + p += bpc + local count = bit32.band(cnt, 0x7F) + if count == 0 then + break + end + if bit32.band(cnt, 0x80) ~= 0 then + for _ = 1, count do + if x >= w or p + bpc > stop then + break + end + put(c, row, x, if bpc == 1 then readu8(b, p) else be16(b, p)) + p += bpc + x += 1 + end + else + if p + bpc > stop then + break + end + local v = if bpc == 1 then readu8(b, p) else be16(b, p) + p += bpc + for _ = 1, count do + if x >= w then + break + end + put(c, row, x, v) + x += 1 + end + end + end + if x < w then + truncated = true + end + end + end + end + local wide = opts and opts.native and bpc == 2 + local img = Types.Image.new(w, h, if wide then "rgba16" else "rgba8") + local px = img.pixels + for y = 0, h - 1 do + local row = h - 1 - y + for x = 0, w - 1 do + local function s(c: number): number + return buffer.readu16(plane, ((c * h + row) * w + x) * 2) + end + local rr: number = s(0) + local gg: number = if z >= 3 then s(1) else rr + local bb: number = if z >= 3 then s(2) else rr + local aa: number = if z == 2 then s(1) elseif z == 4 then s(3) else 65535 + local d = (y * w + x) + if wide then + buffer.writeu16(px, d * 8, rr) + buffer.writeu16(px, d * 8 + 2, gg) + buffer.writeu16(px, d * 8 + 4, bb) + buffer.writeu16(px, d * 8 + 6, aa) + else + buffer.writeu32(px, d * 4, bit32.rshift(rr, 8) + bit32.rshift(gg, 8) * 256 + bit32.rshift(bb, 8) * 65536 + bit32.rshift(aa, 8) * 16777216) + end + end + end + local name = buffer.readstring(b, o + 24, 80) + local zpos = string.find(name, "\0", 1, true) + name = if zpos then string.sub(name, 1, zpos - 1) else name + if name ~= "" then + img.meta.text = { name = name } + end + if truncated then + img.meta.truncated = true + end + img.meta.source = { format = "sgi", bitDepth = bpc * 8, channels = z, rle = rle == 1, dimension = dim } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Sgi.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or (img.format ~= "rgba8" and img.format ~= "rgba16") or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "needs an rgba8 or rgba16 Image") + end + local w, h = img.width, img.height + if w < 1 or h < 1 or w > 65535 or h > 65535 then + return nil, Err.new(Err.ARG, "size must be 1..65535") + end + local wide = img.format == "rgba16" + local bpc = if wide then 2 else 1 + local px = img.pixels + local function sample(x: number, y: number, c: number): number + local i = (y * w + x) * 4 + c + return if wide then buffer.readu16(px, i * 2) else readu8(px, i) + end + local z = 3 + for i = 0, w * h - 1 do + if (if wide then buffer.readu16(px, i * 8 + 6) < 65535 else readu8(px, i * 4 + 3) < 255) then + z = 4 + break + end + end + local rle = not (opts and opts.rle == false) + local out = Bytes.writer(512 + w * h * z * bpc + h * z * 8) + out:u16be(474) + out:u8(if rle then 1 else 0) + out:u8(bpc) + out:u16be(3) + out:u16be(w) + out:u16be(h) + out:u16be(z) + out:u32be(0) + out:u32be(if wide then 65535 else 255) + out:u32be(0) + local name = (opts and opts.name) or (img.meta and img.meta.text and img.meta.text.name) or "" + name = string.sub(name, 1, 79) + out:string(name) + out:fill(0, 80 - #name) + out:u32be(0) + out:fill(0, 404) + local function put(v: number) + if wide then + out:u16be(v) + else + out:u8(v) + end + end + if not rle then + for c = 0, z - 1 do + for row = 0, h - 1 do + local y = h - 1 - row + for x = 0, w - 1 do + put(sample(x, y, c)) + end + end + end + return out:finish(), nil + end + local tables = out:tell() + out:fill(0, h * z * 8) + for c = 0, z - 1 do + for row = 0, h - 1 do + local y = h - 1 - row + local start = out:tell() + local x = 0 + while x < w do + -- a run of equal samples (>= 3) or literals up to the next run + local v = sample(x, y, c) + local run = 1 + while x + run < w and run < 127 and sample(x + run, y, c) == v do + run += 1 + end + if run >= 3 then + put(run) + put(v) + x += run + else + local lit = 0 + while x + lit < w and lit < 127 do + local a = sample(x + lit, y, c) + if x + lit + 2 < w and sample(x + lit + 1, y, c) == a and sample(x + lit + 2, y, c) == a then + break + end + lit += 1 + end + lit = math.max(lit, 1) + put(0x80 + lit) + for k = 0, lit - 1 do + put(sample(x + k, y, c)) + end + x += lit + end + end + put(0) + local i = c * h + row + out:setU32be(tables + i * 4, start) + out:setU32be(tables + h * z * 4 + i * 4, out:tell() - start) + end + end + return out:finish(), nil +end + +return Sgi +end +__FILES["image/sunras"] = function() + +-- image/sunras: Sun Raster (rasterfile(5), SunOS <rasterfile.h>). Supports: 1-bit (0 = white without a colour map), +-- 8-bit, 24 / 32-bit BGR / XBGR (RT_STANDARD, RT_OLD, RT_BYTE_ENCODED) or RGB / XRGB (RT_FORMAT_RGB), 0x80 RLE, 16-bit +-- row padding; 32-bit X is alpha unless all zero. Not supported: RT_FORMAT_TIFF / RT_FORMAT_IFF, RMT_RAW. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Sniff = __include("core/Sniff") +local Types = __include("Types") +local Pixels = __include("codecs/image/Pixels") + +-- ------------------------------------------------------------------------------------------------ contract +local Sunras = { + name = "sunras", + category = "image", + extensions = { "ras", "sun", "rs", "im1", "im8", "im24", "im32" }, + mime = { "image/x-sun-raster", "image/x-cmu-raster" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/image/Pixels" }, + caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 1, 8, 24, 32 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + maxPixels: number?, -- default 2^26 +} +type EncodeOptions = { + rle: boolean?, -- default true; false: RT_STANDARD +} + +local MAGIC = "\89\166\106\149" +local readu8, readu32 = buffer.readu8, buffer.readu32 +local function be32(b: buffer, o: number): number + return bit32.byteswap(readu32(b, o)) +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Sunras.sniff(r: Bytes.Reader): number + return Sniff.magic(r, MAGIC) +end + +-- ------------------------------------------------------------------------------------------------ decode +function Sunras.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local b, o, limit = r.buf, r.base, r.limit + if limit - o < 32 then + return nil, Err.new(Err.TRUNCATED, "short header", o) + end + if buffer.readstring(b, o, 4) ~= MAGIC then + return nil, Err.new(Err.CORRUPT, "not a Sun raster", o) + end + local w, h, depth, typ, maptype, maplen = be32(b, o + 4), be32(b, o + 8), be32(b, o + 12), be32(b, o + 20), be32(b, o + 24), be32(b, o + 28) + if w == 0 or h == 0 or w > 65536 or h > 65536 then + return nil, Err.new(Err.CORRUPT, "bad size", o + 4) + end + if depth ~= 1 and depth ~= 8 and depth ~= 24 and depth ~= 32 then + return nil, Err.new(Err.UNSUPPORTED, depth .. "-bit pixels", o + 12) + end + if typ == 4 or typ == 5 or typ > 5 and typ ~= 0xFFFF then + return nil, Err.new(Err.UNSUPPORTED, "raster type " .. typ, o + 20) + end + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + if w * h > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels)) + end + local p = o + 32 + if p + maplen > limit then + return nil, Err.new(Err.TRUNCATED, "colour map runs past the end", p) + end + local pal = buffer.create(1024) + local ncol = 0 + if maptype == 1 and maplen > 0 then + ncol = math.min(256, maplen // 3) + for i = 0, ncol - 1 do + buffer.writeu32(pal, i * 4, readu8(b, p + i) + readu8(b, p + ncol + i) * 256 + readu8(b, p + 2 * ncol + i) * 65536 + 0xFF000000) + end + elseif depth == 1 then + buffer.writeu32(pal, 0, 0xFFFFFFFF) + buffer.writeu32(pal, 4, 0xFF000000) + else + for i = 0, 255 do + buffer.writeu32(pal, i * 4, i * 0x10101 + 0xFF000000) + end + end + p += maplen + local stride = ((w * depth + 15) // 16) * 2 + local total = stride * h + local raw = buffer.create(total + 4) + local truncated = false + if typ == 2 then + local q = 0 + while q < total and p < limit do + local c = readu8(b, p) + p += 1 + if c ~= 0x80 then + buffer.writeu8(raw, q, c) + q += 1 + else + if p >= limit then + break + end + local n = readu8(b, p) + p += 1 + if n == 0 then + buffer.writeu8(raw, q, 0x80) + q += 1 + else + if p >= limit then + break + end + local cnt = math.min(n + 1, total - q) + buffer.fill(raw, q, readu8(b, p), cnt) + p += 1 + q += cnt + end + end + end + truncated = q < total + else + local n = math.min(total, limit - p) + buffer.copy(raw, 0, b, p, n) + truncated = n < total + end + local img = Types.Image.new(w, h, "rgba8") + local px = img.pixels + if depth <= 8 then + Pixels.indexed(raw, 0, stride, depth, px, w, h, true, pal) + else + local rgb = typ == 3 + local bytes = depth // 8 + local alpha = false + if bytes == 4 then + for y = 0, h - 1 do + for x = 0, w - 1 do + if readu8(raw, y * stride + x * 4) ~= 0 then + alpha = true + end + end + end + end + for y = 0, h - 1 do + for x = 0, w - 1 do + local s = y * stride + x * bytes + local a = 255 + if bytes == 4 then + a = if alpha then readu8(raw, s) else 255 + s += 1 + end + local c0, c1, c2 = readu8(raw, s), readu8(raw, s + 1), readu8(raw, s + 2) + local rr, bb = if rgb then c0 else c2, if rgb then c2 else c0 + buffer.writeu32(px, (y * w + x) * 4, rr + c1 * 256 + bb * 65536 + a * 16777216) + end + end + end + if ncol > 0 then + local list: { { number } } = {} + for i = 0, ncol - 1 do + local v = buffer.readu32(pal, i * 4) + list[i + 1] = { bit32.band(v, 255), bit32.band(bit32.rshift(v, 8), 255), bit32.band(bit32.rshift(v, 16), 255), 255 } + end + img.meta.palette = list + end + if truncated then + img.meta.truncated = true + end + img.meta.source = { format = "sunras", bitDepth = depth, type = typ, rle = typ == 2 } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Sunras.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "needs an rgba8 Image") + end + local w, h = img.width, img.height + if w < 1 or h < 1 then + return nil, Err.new(Err.ARG, "bad size") + end + local px = img.pixels + local alpha = false + for i = 0, w * h - 1 do + if readu8(px, i * 4 + 3) < 255 then + alpha = true + break + end + end + local depth = if alpha then 32 else 24 + local bytes = depth // 8 + local stride = ((w * depth + 15) // 16) * 2 + local raw = buffer.create(stride * h) + for y = 0, h - 1 do + for x = 0, w - 1 do + local s, d = (y * w + x) * 4, y * stride + x * bytes + if alpha then + buffer.writeu8(raw, d, readu8(px, s + 3)) + d += 1 + end + buffer.writeu8(raw, d, readu8(px, s + 2)) + buffer.writeu8(raw, d + 1, readu8(px, s + 1)) + buffer.writeu8(raw, d + 2, readu8(px, s)) + end + end + local rle = not (opts and opts.rle == false) + local body = raw + if rle then + local wr = Bytes.writer(stride * h) + local i, n = 0, stride * h + while i < n do + local v = readu8(raw, i) + local run = 1 + while i + run < n and run < 256 and readu8(raw, i + run) == v do + run += 1 + end + if run >= 3 or v == 0x80 then + if run == 1 then + wr:u8(0x80) + wr:u8(0) + else + wr:u8(0x80) + wr:u8(run - 1) + wr:u8(v) + end + else + for _ = 1, run do + wr:u8(v) + end + end + i += run + end + body = wr:finish() + end + local out = Bytes.writer(32 + buffer.len(body)) + out:string(MAGIC) + out:u32be(w) + out:u32be(h) + out:u32be(depth) + out:u32be(buffer.len(body)) + out:u32be(if rle then 2 else 1) + out:u32be(0) + out:u32be(0) + out:bytes(body) + return out:finish(), nil +end + +return Sunras +end +__FILES["image/tga"] = function() + +-- image/tga: Truevision TGA (TGA 2.0 specification). Supports: types 1 / 2 / 3 and RLE 9 / 10 / 11, 8..32-bit pixels +-- and colour maps, every origin, descriptor alpha bits (16-bit: only when 1 alpha bit is declared), the image ID, the +-- 2.0 footer. Not supported: the extension area's fields (ignored). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Codec = __include("image/tga/Codec") + +-- ------------------------------------------------------------------------------------------------ contract +local Tga = { + name = "tga", + category = "image", + extensions = { "tga", "icb", "vda", "vst", "tpic" }, + mime = { "image/x-tga", "image/x-targa" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 8, 15, 16, 24, 32 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + native: boolean?, -- default false: rgba8 + maxPixels: number?, -- default 2^26 +} +type EncodeOptions = { + rle: boolean?, -- default false + origin: ("bottom-left" | "top-left")?, -- default "bottom-left" + alpha: boolean?, -- default: 32-bit when any alpha < 255 + id: string?, -- up to 255 bytes; default meta.text.id +} + +-- ------------------------------------------------------------------------------------------------ constants +local TYPES = { [1] = true, [2] = true, [3] = true, [9] = true, [10] = true, [11] = true } +local FOOTER = "TRUEVISION-XFILE.\0" +local readu8 = buffer.readu8 + +-- ------------------------------------------------------------------------------------------------ sniff +type Header = { + idLen: number, + cmapType: number, + imageType: number, + cmapFirst: number, + cmapLen: number, + cmapBits: number, + width: number, + height: number, + depth: number, + desc: number, +} + +local function header(r: Bytes.Reader): Header? + if r.limit - r.base < 18 then + return nil + end + local b, o = r.buf, r.base + local function u16(q: number): number + return readu8(b, o + q) + readu8(b, o + q + 1) * 256 + end + local h: Header = { + idLen = readu8(b, o), + cmapType = readu8(b, o + 1), + imageType = readu8(b, o + 2), + cmapFirst = u16(3), + cmapLen = u16(5), + cmapBits = readu8(b, o + 7), + width = u16(12), + height = u16(14), + depth = readu8(b, o + 16), + desc = readu8(b, o + 17), + } + return h +end + +local function implausible(h: Header): string? + local t = h.imageType + if not TYPES[t] then + return "image type " .. t + end + if h.cmapType > 1 then + return "colour map type " .. h.cmapType + end + local mapped = t == 1 or t == 9 + if mapped and (h.cmapType ~= 1 or (h.depth ~= 8 and h.depth ~= 16)) then + return "colour-mapped image without a colour map" + end + if h.cmapType == 1 and h.cmapLen > 0 and h.cmapBits ~= 15 and h.cmapBits ~= 16 and h.cmapBits ~= 24 and h.cmapBits ~= 32 then + return "colour map entry size " .. h.cmapBits + end + if (t == 2 or t == 10) and h.depth ~= 15 and h.depth ~= 16 and h.depth ~= 24 and h.depth ~= 32 then + return "pixel depth " .. h.depth + end + if (t == 3 or t == 11) and h.depth ~= 8 and h.depth ~= 16 then + return "grey pixel depth " .. h.depth + end + if h.width == 0 or h.height == 0 then + return "zero size" + end + if h.desc >= 64 then + return "interleaving / reserved descriptor bits" + end + return nil +end + +function Tga.sniff(r: Bytes.Reader): number + local h = header(r) + if not h or implausible(h) then + return 0 + end + local n = r.limit - r.base + if n >= 44 and buffer.readstring(r.buf, r.limit - 18, 18) == FOOTER then + return 0.9 + end + return 0.2 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Tga.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + local h = header(r) + if not h then + return nil, Err.new(Err.TRUNCATED, "short header", r.base) + end + local why = implausible(h) + if why then + return nil, Err.new(if h.imageType == 0 then Err.UNSUPPORTED else Err.CORRUPT, why, r.base) + end + local w, ht = h.width, h.height + if w * ht > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, ht, maxPixels)) + end + local b = r.buf + local p = r.base + 18 + local id = if h.idLen > 0 and p + h.idLen <= r.limit then buffer.readstring(b, p, h.idLen) else nil + p += h.idLen + local pal = buffer.create(4) + local palN = 0 + if h.cmapType == 1 and h.cmapLen > 0 then + local eb = (h.cmapBits + 7) // 8 + if p + h.cmapLen * eb > r.limit then + return nil, Err.new(Err.TRUNCATED, "colour map runs past the end", p) + end + local first = h.cmapFirst + palN = first + h.cmapLen + pal = buffer.create(palN * 4) + buffer.fill(pal, 0, 0, palN * 4) + local kind = if h.cmapBits == 24 then 3 elseif h.cmapBits == 32 then 4 else 2 + for i = 0, h.cmapLen - 1 do + buffer.writeu32(pal, (first + i) * 4, Codec.pixel(b, p + i * eb, kind, false, pal, 0)) + end + for i = 0, first - 1 do + buffer.writeu32(pal, i * 4, 0xFF000000) + end + p += h.cmapLen * eb + end + local t = h.imageType + local alphaBits = h.desc % 16 + local kind + if t == 1 or t == 9 then + kind = if h.depth == 8 then 5 else 6 + elseif t == 3 or t == 11 then + kind = if h.depth == 8 then 0 else 1 + else + kind = if h.depth == 24 then 3 elseif h.depth == 32 then 4 else 2 + end + local bpp = (h.depth + 7) // 8 + local bottomUp = (h.desc // 32) % 2 == 0 + local rtl = (h.desc // 16) % 2 == 1 + local img = Types.Image.new(w, ht, "rgba8") + local _, truncated = Codec.decode(b, p, r.limit, w, ht, bpp, kind, h.depth == 16 and alphaBits >= 1, t >= 9, bottomUp, rtl, pal, palN, img.pixels) + local native = opts and opts.native + if native and kind == 0 then + local g = Types.Image.new(w, ht, "gray8") + for i = 0, w * ht - 1 do + buffer.writeu8(g.pixels, i, readu8(img.pixels, i * 4)) + end + img = g + elseif native and kind == 3 then + local c = Types.Image.new(w, ht, "rgb8") + for i = 0, w * ht - 1 do + buffer.writeu16(c.pixels, i * 3, buffer.readu16(img.pixels, i * 4)) + buffer.writeu8(c.pixels, i * 3 + 2, readu8(img.pixels, i * 4 + 2)) + end + img = c + end + if palN > 0 then + local palette = {} + for i = 0, palN - 1 do + palette[i + 1] = { readu8(pal, i * 4), readu8(pal, i * 4 + 1), readu8(pal, i * 4 + 2), readu8(pal, i * 4 + 3) } + end + img.meta.palette = palette + end + if id then + img.meta.text = { id = id } + end + if truncated then + img.meta.truncated = true + end + img.meta.source = { + format = "tga", + bitDepth = h.depth, + colorType = if kind >= 5 then "palette" elseif kind <= 1 then (if kind == 1 then "graya" else "gray") else (if kind == 3 then "rgb" else "rgba"), + rle = t >= 9, + origin = (if bottomUp then "bottom" else "top") .. "-" .. (if rtl then "right" else "left"), + alphaBits = alphaBits, + } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Tga.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "needs an Image") + end + local srcBpp = if img.format == "rgba8" then 4 elseif img.format == "rgb8" then 3 elseif img.format == "gray8" then 1 else nil + if not srcBpp then + return nil, Err.new(Err.ARG, "needs an rgba8, rgb8 or gray8 Image") + end + local w, h = img.width, img.height + if type(w) ~= "number" or type(h) ~= "number" or w < 1 or h < 1 or w > 65535 or h > 65535 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(img.pixels) < w * h * srcBpp then + return nil, Err.new(Err.ARG, "bad image size or pixel buffer (1..65535 per side)") + end + local o: any = opts or {} + local origin = o.origin or "bottom-left" + if origin ~= "bottom-left" and origin ~= "top-left" then + return nil, Err.new(Err.ARG, "origin must be \"bottom-left\" or \"top-left\"") + end + local outBpp = srcBpp + if srcBpp == 4 then + local alpha = o.alpha + if alpha == nil then + alpha = false + for i = 0, w * h - 1 do + if readu8(img.pixels, i * 4 + 3) ~= 255 then + alpha = true + break + end + end + end + outBpp = if alpha then 4 else 3 + end + local id = o.id or (img.meta and img.meta.text and img.meta.text.id) or "" + if type(id) ~= "string" then + id = "" + end + id = string.sub(id, 1, 255) + local rle = o.rle == true + local out = buffer.create(18 + #id + w * h * (outBpp + 1) + 26) + buffer.writeu8(out, 0, #id) + buffer.writeu8(out, 2, (if outBpp == 1 then 3 else 2) + (if rle then 8 else 0)) + buffer.writeu16(out, 12, w) + buffer.writeu16(out, 14, h) + buffer.writeu8(out, 16, outBpp * 8) + buffer.writeu8(out, 17, (if outBpp == 4 then 8 else 0) + (if origin == "top-left" then 32 else 0)) + buffer.writestring(out, 18, id) + local op = Codec.encode(img.pixels, w, h, srcBpp, outBpp, rle, origin == "top-left", out, 18 + #id) + -- TGA 2.0 footer: no extension / developer areas + buffer.writeu32(out, op, 0) + buffer.writeu32(out, op + 4, 0) + buffer.writestring(out, op + 8, FOOTER) + op += 26 + local res = buffer.create(op) + buffer.copy(res, 0, out, 0, op) + return res, nil +end + +return Tga +end +__FILES["image/tga/Codec"] = @native function() + + + +-- image/tga/Codec: Truevision TGA 2.0 pixel loops: raw / RLE (packets may cross scanlines on read, never on write). +local readu8, readu16, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu32 + +local Codec = {} + +-- kind: 0 grey 8, 1 grey + alpha 16, 2 = 15/16-bit ARGB1555, 3 = BGR 24, 4 = BGRA 32, 5 = index 8, 6 = index 16 +@native local function pixel(b: buffer, p: number, kind: number, alpha1: boolean, pal: buffer, palN: number): number + if kind == 0 then + return readu8(b, p) * 0x10101 + 0xFF000000 + elseif kind == 1 then + return readu8(b, p) * 0x10101 + readu8(b, p + 1) * 0x1000000 + elseif kind == 2 then + local v = readu16(b, p) + local r, g, bl = (v // 1024) % 32, (v // 32) % 32, v % 32 + local a = if alpha1 and v < 32768 then 0 else 255 + return (r * 255 + 15) // 31 + ((g * 255 + 15) // 31) * 256 + ((bl * 255 + 15) // 31) * 65536 + a * 16777216 -- round(v * 255 / 31), as ImageMagick + elseif kind == 3 then + return readu8(b, p + 2) + readu8(b, p + 1) * 256 + readu8(b, p) * 65536 + 0xFF000000 + elseif kind == 4 then + return readu8(b, p + 2) + readu8(b, p + 1) * 256 + readu8(b, p) * 65536 + readu8(b, p + 3) * 16777216 + end + local i = if kind == 5 then readu8(b, p) else readu16(b, p) + if i >= palN then + return 0xFF000000 + end + return readu32(pal, i * 4) +end +Codec.pixel = pixel + +@native function Codec.decode(b: buffer, p: number, limit: number, w: number, h: number, bpp: number, kind: number, alpha1: boolean, rle: boolean, bottomUp: boolean, rtl: boolean, pal: buffer, palN: number, out: buffer): (number, boolean) + local n = w * h + local i = 0 + @native local function put(v: number) + local row, col = i // w, i % w + if bottomUp then + row = h - 1 - row + end + if rtl then + col = w - 1 - col + end + writeu32(out, (row * w + col) * 4, v) + i += 1 + end + if not rle then + local avail = math.min(n, (limit - p) // bpp) + for _ = 1, avail do + put(pixel(b, p, kind, alpha1, pal, palN)) + p += bpp + end + return i, avail < n + end + while i < n do + if p >= limit then + return i, true + end + local hd = readu8(b, p) + p += 1 + local count = hd % 128 + 1 + if hd >= 128 then + if p + bpp > limit then + return i, true + end + local v = pixel(b, p, kind, alpha1, pal, palN) + p += bpp + for _ = 1, math.min(count, n - i) do + put(v) + end + else + for _ = 1, math.min(count, n - i) do + if p + bpp > limit then + return i, true + end + put(pixel(b, p, kind, alpha1, pal, palN)) + p += bpp + end + end + end + return i, false +end + +@native function Codec.encode(px: buffer, w: number, h: number, srcBpp: number, outBpp: number, rle: boolean, topDown: boolean, out: buffer, o: number): number + @native local function get(q: number): number + if srcBpp == 1 then + return readu8(px, q) + elseif srcBpp == 3 then + return readu8(px, q) + readu8(px, q + 1) * 256 + readu8(px, q + 2) * 65536 + 0xFF000000 + end + return readu32(px, q) + end + @native local function emit(v: number) + if outBpp == 1 then + writeu8(out, o, v % 256) + else + writeu8(out, o, (v // 65536) % 256) + writeu8(out, o + 1, (v // 256) % 256) + writeu8(out, o + 2, v % 256) + if outBpp == 4 then + writeu8(out, o + 3, v // 16777216) + end + end + o += outBpp + end + for y = 0, h - 1 do + local row = if topDown then y else h - 1 - y + local base = row * w * srcBpp + if not rle then + for x = 0, w - 1 do + emit(get(base + x * srcBpp)) + end + else + local x = 0 + while x < w do + local v = get(base + x * srcBpp) + local run = 1 + while x + run < w and run < 128 and get(base + (x + run) * srcBpp) == v do + run += 1 + end + if run >= 2 then + writeu8(out, o, 127 + run) + o += 1 + emit(v) + x += run + else + -- a raw packet up to the next run of 2 or more + local s = x + local cnt = 0 + while x < w and cnt < 128 do + local c = get(base + x * srcBpp) + if x + 1 < w and get(base + (x + 1) * srcBpp) == c then + break + end + cnt += 1 + x += 1 + end + writeu8(out, o, cnt - 1) + o += 1 + for k = s, s + cnt - 1 do + emit(get(base + k * srcBpp)) + end + end + end + end + end + return o +end + +return Codec +end +end + + + + + + image_2 + --!optimize 2 +--!nocheck +-- rosetta chunk image_2 (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 10 modules (3 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["image/tiff"] = function() + +-- image/tiff: TIFF 6.0 (+ Adobe technote 3, BigTIFF). Supports: strips, tiles, planar 1 / 2, none / LZW (old-style too) +-- / Deflate (8, 32946) / PackBits / JPEG (7), predictors 2 / 3, int / float samples, CMYK (naive), fill order 2. Not +-- supported: old-style JPEG (6), CCITT (2, 3, 4), YCbCr, CIELab, JBIG. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Deflate = __include("codecs/compress/Deflate") +local Lzw = __include("codecs/compress/Lzw") +local Pixels = __include("image/tiff/Pixels") +local PackBits = __include("codecs/compress/PackBits") + +-- ------------------------------------------------------------------------------------------------ contract +local Tiff = { + name = "tiff", + category = "image", + extensions = { "tif", "tiff" }, + mime = { "image/tiff" }, + 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 }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + native: boolean?, -- default false: rgba8 + maxPixels: number?, -- per page, default 2^26 + maxPages: number?, -- default 1024 + page: number?, -- 1-based + decodeImage: ((buffer) -> (any, any))?, +} +type EncodeOptions = { + compression: ("none" | "deflate" | "lzw" | "packbits")?, -- default "deflate" + predictor: boolean?, -- default true + level: number?, -- 0..9, default 6 + rowsPerStrip: number?, -- default: about 64 KB per strip +} + +-- ------------------------------------------------------------------------------------------------ constants +local TYPE_SIZE = { [1] = 1, [2] = 1, [3] = 2, [4] = 4, [5] = 8, [6] = 1, [7] = 1, [8] = 2, [9] = 4, [10] = 8, [11] = 4, [12] = 8, [13] = 4, [16] = 8, [17] = 8, [18] = 8 } +local COMPRESSION = { [1] = "none", [5] = "lzw", [8] = "deflate", [32946] = "deflate", [32773] = "packbits", [7] = "jpeg" } +local PHOTOMETRIC = { [0] = "miniswhite", [1] = "minisblack", [2] = "rgb", [3] = "palette", [5] = "cmyk", [6] = "ycbcr" } +local TWO32 = 4294967296 + +local readu8, readu16, readu32 = buffer.readu8, buffer.readu16, buffer.readu32 + +-- ------------------------------------------------------------------------------------------------ sniff +function Tiff.sniff(r: Bytes.Reader): number + local s = r:peek(4) + if s == "II*\0" or s == "MM\0*" or s == "II+\0" or s == "MM\0+" then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +type Entry = { tag: number, typ: number, count: number, at: number } +type Ctx = { b: buffer, base: number, limit: number, le: boolean, big: boolean } + +local function u16(c: Ctx, at: number): number + if at < c.base or at + 2 > c.limit then + return 0 + end + return if c.le then readu16(c.b, at) else readu8(c.b, at) * 256 + readu8(c.b, at + 1) +end +local function u32(c: Ctx, at: number): number + if at < c.base or at + 4 > c.limit then + return 0 + end + local v = readu32(c.b, at) + return if c.le then v else bit32.byteswap(v) +end +local function u64(c: Ctx, at: number): number + local lo, hi = u32(c, at), u32(c, at + 4) + if not c.le then + lo, hi = hi, lo + end + return hi * TWO32 + lo +end +local function off(c: Ctx, at: number): number + return if c.big then u64(c, at) else u32(c, at) +end + +local function values(c: Ctx, e: Entry?, max: number?): { number }? + if not e then + return nil + end + local size = TYPE_SIZE[e.typ] + if not size or e.count > (max or 1e7) or e.at < c.base or e.at + e.count * size > c.limit then + return nil + end + local out = table.create(e.count, 0) + local b = c.b + for i = 0, e.count - 1 do + local p = e.at + i * size + local t = e.typ + local v + if t == 1 or t == 2 or t == 7 then + v = readu8(b, p) + elseif t == 6 then + v = buffer.readi8(b, p) + elseif t == 3 then + v = u16(c, p) + elseif t == 8 then + v = u16(c, p) + if v >= 32768 then + v -= 65536 + end + elseif t == 4 or t == 13 then + v = u32(c, p) + elseif t == 9 then + v = u32(c, p) + if v >= 2147483648 then + v -= TWO32 + end + elseif t == 5 or t == 10 then + local n, d = u32(c, p), u32(c, p + 4) + if t == 10 then + if n >= 2147483648 then + n -= TWO32 + end + if d >= 2147483648 then + d -= TWO32 + end + end + v = if d ~= 0 then n / d else 0 + elseif t == 11 then + v = Pixels.f32(u32(c, p)) + elseif t == 12 then + local lo, hi = u32(c, p), u32(c, p + 4) + if not c.le then + lo, hi = hi, lo + end + v = Pixels.f64(lo, hi) + else + v = u64(c, p) + end + out[i + 1] = v + end + return out +end + +local function one(c: Ctx, e: Entry?, default: number): number + local v = values(c, e, 64) + return if v and v[1] then v[1] else default +end + +local function readIfd(c: Ctx, p: number): ({ [number]: Entry }?, number, Err.Err?) + local esize = if c.big then 20 else 12 + local hsize = if c.big then 8 else 2 + if p < c.base or p + hsize > c.limit then + return nil, 0, Err.new(Err.TRUNCATED, "IFD past the end", p) + end + local n = if c.big then u64(c, p) else u16(c, p) + if n == 0 or p + hsize + n * esize > c.limit then + return nil, 0, Err.new(if n == 0 then Err.CORRUPT else Err.TRUNCATED, "bad IFD entry count " .. n, p) + end + local entries: { [number]: Entry } = {} + for i = 0, n - 1 do + local q = p + hsize + i * esize + local tag, typ = u16(c, q), u16(c, q + 2) + local count = if c.big then u64(c, q + 4) else u32(c, q + 4) + local vat = q + (if c.big then 12 else 8) + local size = TYPE_SIZE[typ] + if size then + local at = vat + if count * size > (if c.big then 8 else 4) then + at = c.base + off(c, vat) + end + entries[tag] = { tag = tag, typ = typ, count = count, at = at } + end + end + local nq = p + hsize + n * esize + local nextOff = 0 + if nq + (if c.big then 8 else 4) <= c.limit then + nextOff = off(c, nq) + end + return entries, if nextOff > 0 then c.base + nextOff else 0, nil +end + +local function bytesOf(c: Ctx, e: Entry?, max: number): buffer? + if not e or e.at < c.base then + return nil + end + local size = TYPE_SIZE[e.typ] or 1 + local n = e.count * size + if n > max or e.at + n > c.limit then + return nil + end + local x = buffer.create(n) + buffer.copy(x, 0, c.b, e.at, n) + return x +end + +local function inflateChunk(c: Ctx, comp: number, p: number, len: number, out: buffer, o: number, size: number, rev: boolean): (number?, Err.Err?) + if p < c.base or len < 0 or p + len > c.limit then + -- 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, nil + end + end + local src, sp = c.b, p + if rev then + src = buffer.create(len) + buffer.copy(src, 0, c.b, p, len) + Pixels.reverseBits(src, 0, len) + sp = 0 + end + if comp == 1 then + local n = math.min(len, size) + buffer.copy(out, o, src, sp, n) + return n, nil + elseif comp == 5 then + local n = Lzw.decode(src, sp, len, out, o, size, "tiff") + return n, nil + elseif comp == 8 or comp == 32946 then + local raw = Deflate.zlib(src, sp, len, size) + if not raw then + raw = Deflate.zlib(src, sp, len) or Deflate.inflate(src, sp, len) + end + if not raw then + return nil, Err.new(Err.CORRUPT, "bad deflate data", p) + end + local n = math.min(buffer.len(raw :: buffer), size) + buffer.copy(out, o, raw :: buffer, 0, n) + return n, nil + elseif comp == 32773 then + return (PackBits.decode(src, sp, sp + len, out, o, size)), nil + end + return nil, Err.new(Err.UNSUPPORTED, "compression " .. comp) +end + +type Page = { image: Types.Image, info: { [string]: any } } + +local function decodePage(c: Ctx, t: { [number]: Entry }, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local w, h = one(c, t[256], 0), one(c, t[257], 0) + if w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 then + return nil, Err.new(Err.CORRUPT, "bad image size") + end + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + if w * h > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels)) + end + local spp = one(c, t[277], 1) + local bpsList = values(c, t[258], 64) or { 1 } + local bps = bpsList[1] or 1 + for i = 2, math.min(#bpsList, spp) do + if bpsList[i] ~= bps then + return nil, Err.new(Err.UNSUPPORTED, "different bit depths per sample") + end + end + local comp = one(c, t[259], 1) + local photo = one(c, t[262], if spp >= 3 then 2 else 1) + local planar = one(c, t[284], 1) + local predictor = one(c, t[317], 1) + local sfmt = one(c, t[339], 1) + local fill = one(c, t[266], 1) + if spp < 1 or spp > 16 or bps < 1 or bps > 64 then + return nil, Err.new(Err.UNSUPPORTED, string.format("%d samples of %d bits", spp, bps)) + end + if sfmt == 3 and bps ~= 16 and bps ~= 32 and bps ~= 64 then + return nil, Err.new(Err.UNSUPPORTED, bps .. "-bit floats") + end + if sfmt ~= 3 and bps > 32 then + return nil, Err.new(Err.UNSUPPORTED, bps .. "-bit integers") + end + if not COMPRESSION[comp] then + local names = { [2] = "CCITT RLE", [3] = "CCITT fax 3", [4] = "CCITT fax 4", [6] = "old-style JPEG", [34712] = "JPEG 2000", [34925] = "LZMA", [50000] = "Zstandard", [50001] = "WebP" } + return nil, Err.new(Err.UNSUPPORTED, (names[comp] or "compression") .. " (" .. comp .. ")") + end + if not PHOTOMETRIC[photo] then + return nil, Err.new(Err.UNSUPPORTED, "photometric interpretation " .. photo) + end + local cc = if photo == 2 or photo == 6 then 3 elseif photo == 5 then 4 else 1 + if spp < cc then + return nil, Err.new(Err.CORRUPT, string.format("%d samples for photometric %d", spp, photo)) + end + if photo == 5 and one(c, t[332], 1) ~= 1 then + return nil, Err.new(Err.UNSUPPORTED, "separated image that is not CMYK") + end + local extra = values(c, t[338], 16) or {} + local alpha, assoc = -1, false + if spp > cc then + local kind = extra[1] or 0 + alpha = cc + assoc = kind == 1 + end + local chunky = planar ~= 2 or spp == 1 + local tiled = t[322] ~= nil + local cw = if tiled then one(c, t[322], 0) else w + local ch = if tiled then one(c, t[323], 0) else math.min(one(c, t[278], h), h) + if cw < 1 or ch < 1 or cw > 65536 or (tiled and ch > 65536) then + return nil, Err.new(Err.CORRUPT, "bad tile / strip size") + end + if ch > h and not tiled then + ch = h + end + local pspp = if chunky then spp else 1 + local nplanes = if chunky then 1 else spp + local rb = math.ceil(w * pspp * bps / 8) + local crb = math.ceil(cw * pspp * bps / 8) + if rb * h * nplanes > 2 ^ 30 or crb * ch > 2 ^ 30 then + return nil, Err.new(Err.LIMIT, "decoded data over 1 GB") + end + local across = if tiled then math.ceil(w / cw) else 1 + local down = math.ceil(h / ch) + local perPlane = across * down + local offs = values(c, if tiled then t[324] else t[273], 2 ^ 24) + local lens = values(c, if tiled then t[325] else t[279], 2 ^ 24) + if not offs or #offs < perPlane * nplanes then + return nil, Err.new(Err.CORRUPT, "missing or short strip / tile offsets") + end + local planes: { buffer } = table.create(nplanes) :: { buffer } + for i = 1, nplanes do + planes[i] = buffer.create(rb * h + 8) + end + local tmp = buffer.create(crb * ch + 8) + local ftmp = buffer.create(math.max(rb, crb) + 8) + local le = c.le + local bytesPer = bps // 8 + local hook = opts and opts.decodeImage + local jpegTables = if comp == 7 then bytesOf(c, t[347], 1 * 2 ^ 20) else nil + local jpegPixels: buffer? = nil + if comp == 7 then + if type(hook) ~= "function" then + return nil, Err.new(Err.UNSUPPORTED, "JPEG-compressed TIFF needs opts.decodeImage (F.load supplies it)") + end + jpegPixels = buffer.create(w * h * 4) + end + for pl = 0, nplanes - 1 do + for ty = 0, down - 1 do + for tx = 0, across - 1 do + local idx = pl * perPlane + ty * across + tx + local p = c.base + offs[idx + 1] + local len = if lens and lens[idx + 1] then lens[idx + 1] else c.limit - p + local rows = if tiled then ch else math.min(ch, h - ty * ch) + local size = rows * crb + if comp == 7 then + -- JPEGTables (SOI .. EOI) + the chunk (SOI .. EOI): one stream without the inner EOI / SOI + if p < c.base or p + len > c.limit or len < 4 then + return nil, Err.new(Err.TRUNCATED, "JPEG chunk past the end", p) + end + local tl = if jpegTables and buffer.len(jpegTables) >= 4 then buffer.len(jpegTables) - 2 else 0 + local s = buffer.create(tl + len - (if tl > 0 then 2 else 0)) + if tl > 0 then + buffer.copy(s, 0, jpegTables :: buffer, 0, tl) + buffer.copy(s, tl, c.b, p + 2, len - 2) + else + buffer.copy(s, 0, c.b, p, len) + end + local ok, img, herr = pcall(hook :: any, s) + if not ok or type(img) ~= "table" or img.format ~= "rgba8" then + return nil, if ok and herr then herr else Err.new(Err.CORRUPT, "embedded JPEG: " .. tostring(if ok then herr else img)) + end + local x0, y0 = tx * cw, ty * ch + local cwid = math.min(cw, w - x0, img.width) + for yy = 0, math.min(rows, h - y0, img.height) - 1 do + buffer.copy(jpegPixels :: buffer, ((y0 + yy) * w + x0) * 4, img.pixels, yy * img.width * 4, cwid * 4) + end + continue + end + buffer.fill(tmp, 0, 0, size) + local _, derr = inflateChunk(c, comp, p, len, tmp, 0, size, fill == 2) + if derr then + return nil, derr + end + if predictor == 2 then + Pixels.unpredict2(tmp, 0, rows, crb, pspp, bps, le) + elseif predictor == 3 and bytesPer >= 2 and crb % bytesPer == 0 then + Pixels.unpredict3(tmp, 0, rows, crb, bytesPer, pspp, ftmp) + end + local plane = planes[pl + 1] + local x0b = math.floor(tx * cw * pspp * bps / 8) + local cols = math.min(cw, w - tx * cw) + local nb = math.min(math.ceil(cols * pspp * bps / 8), rb - x0b) + for yy = 0, rows - 1 do + local y = ty * ch + yy + if y >= h then + break + end + buffer.copy(plane, y * rb + x0b, tmp, yy * crb, nb) + end + end + end + end + local floatOut = sfmt == 3 + if predictor == 3 and floatOut then + le = true -- fpAcc leaves the samples little endian + end + local colorType = PHOTOMETRIC[photo] + local kind = "rgba8" + if opts and opts.native and comp ~= 7 then + if photo == 3 or photo == 5 then + kind = "rgba8" + elseif floatOut then + kind = "rgbaf32" + elseif cc == 1 then + if alpha >= 0 then + kind = if bps <= 8 then "graya8" else "rgba16" + else + kind = if bps <= 8 then "gray8" else "gray16" + end + else + if alpha >= 0 then + kind = if bps <= 8 then "rgba8" else "rgba16" + else + kind = if bps <= 8 then "rgb8" else "rgba16" + end + end + end + local img = Types.Image.new(w, h, kind :: any) + if comp == 7 then + img.pixels = jpegPixels :: buffer + else + if photo == 6 then + return nil, Err.new(Err.UNSUPPORTED, "uncompressed YCbCr") + end + local cmap = nil + if photo == 3 then + local n = 3 * 2 ^ math.min(bps, 16) + local cv = values(c, t[320], n) + if not cv or #cv < n then + return nil, Err.new(Err.CORRUPT, "palette image without a full ColorMap") + end + cmap = buffer.create(n * 2) + for i = 1, n do + buffer.writeu16(cmap, (i - 1) * 2, math.clamp(cv[i], 0, 65535)) + end + end + Pixels.convert({ + planes = planes, + rb = rb, + chunky = chunky, + w = w, + h = h, + spp = spp, + bps = bps, + sfmt = sfmt, + le = le, + photo = photo, + alpha = alpha, + assoc = assoc, + cmap = cmap, + kind = kind, + out = img.pixels, + }) + end + local xr, yr = one(c, t[282], 0), one(c, t[283], 0) + if xr > 0 and yr > 0 then + local unit = one(c, t[296], 2) + local k = if unit == 3 then 2.54 else 1 + if unit ~= 1 then + img.meta.dpi = { x = xr * k, y = yr * k } + end + end + img.meta.icc = bytesOf(c, t[34675], 2 ^ 26) + local function ascii(tag: number): string? + local v = bytesOf(c, t[tag], 65536) + if not v then + return nil + end + local s = buffer.tostring(v) + local z = string.find(s, "\0", 1, true) + return if z then string.sub(s, 1, z - 1) else s + end + local text = {} + for tag, key in { [270] = "description", [305] = "software", [306] = "datetime", [315] = "artist", [33432] = "copyright" } do + local s = ascii(tag) + if s and s ~= "" then + text[key] = s + end + end + if next(text) then + img.meta.text = text + end + img.meta.source = { + format = "tiff", + bitDepth = bps, + colorType = colorType, + photometric = photo, + samples = spp, + sampleFormat = if sfmt == 3 then "float" elseif sfmt == 2 then "int" else "uint", + compression = COMPRESSION[comp], + predictor = predictor, + planar = planar, + tiled = tiled, + alpha = if alpha >= 0 then (if assoc then "associated" else "unassociated") else nil, + bigtiff = c.big, + byteOrder = if c.le then "II" else "MM", + } + return img, nil +end + +local function pages(r: Bytes.Reader, maxPages: number): ({ { [number]: Entry } }?, Ctx?, Err.Err?) + local b, base, limit = r.buf, r.base, r.limit + if limit - base < 8 then + return nil, nil, Err.new(Err.TRUNCATED, "short header") + end + local bo = buffer.readstring(b, base, 2) + if bo ~= "II" and bo ~= "MM" then + return nil, nil, Err.new(Err.CORRUPT, "bad byte order mark") + end + local c: Ctx = { b = b, base = base, limit = limit, le = bo == "II", big = false } + local magic = u16(c, base + 2) + local first + if magic == 42 then + first = u32(c, base + 4) + elseif magic == 43 then + if limit - base < 16 or u16(c, base + 4) ~= 8 then + return nil, nil, Err.new(Err.CORRUPT, "bad BigTIFF header") + end + c.big = true + first = u64(c, base + 8) + else + return nil, nil, Err.new(Err.CORRUPT, "bad magic " .. magic) + end + local list = {} + local seen = {} + local p = base + first + while p > 0 and #list < maxPages do + if seen[p] then + break -- an IFD loop + end + seen[p] = true + local t, nextP, err = readIfd(c, p) + if not t then + if #list == 0 then + return nil, nil, err + end + break + end + table.insert(list, t) + p = nextP + end + return list, c, nil +end + +function Tiff.info(r: Bytes.Reader): ({ [string]: any }?, Err.Err?) + local list, c, err = pages(r, 1024) + if not list or not c then + return nil, err + end + local t = list[1] + return { + pages = #list, + width = one(c, t[256], 0), + height = one(c, t[257], 0), + bitDepth = one(c, t[258], 1), + samples = one(c, t[277], 1), + compression = COMPRESSION[one(c, t[259], 1)] or tostring(one(c, t[259], 1)), + photometric = PHOTOMETRIC[one(c, t[262], 1)], + bigtiff = c.big, + }, + nil +end + +function Tiff.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local maxPages = opts and opts.maxPages or 1024 + local list, c, err = pages(r, if opts and opts.page then math.max(1, opts.page) else maxPages) + if not list or not c then + return nil, err + end + if opts and opts.page then + local t = list[opts.page] + if not t then + return nil, Err.new(Err.ARG, "no page " .. tostring(opts.page)) + end + local img, perr = decodePage(c, t, opts) + if img then + (img.meta.source :: { [string]: any }).pages = #list + end + return img, perr + end + local first: Types.Image? = nil + local frames = {} + for i, t in list do + -- reduced-resolution subfiles (thumbnails) after page 1 are skipped + local sub = one(c, t[254], 0) + if i > 1 and bit32.band(sub, 1) ~= 0 then + continue + end + local img, perr = decodePage(c, t, opts) + if not img then + if i == 1 then + return nil, perr + end + continue + end + if not first then + first = img + end + table.insert(frames, { image = img, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" }) + end + local img = first :: Types.Image + (img.meta.source :: { [string]: any }).pages = #frames + if #frames > 1 then + img.frames = frames :: any + end + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local LAYOUT = { + gray8 = { 1, 8, 1, 1 }, + graya8 = { 2, 8, 1, 1 }, + gray16 = { 1, 16, 1, 1 }, + rgb8 = { 3, 8, 1, 2 }, + rgba8 = { 4, 8, 1, 2 }, + rgba16 = { 4, 16, 1, 2 }, + rgbaf32 = { 4, 32, 3, 2 }, +} +local COMP_CODES = { none = 1, deflate = 8, lzw = 5, packbits = 32773 } + +type Tag = { tag: number, typ: number, vals: { number }?, data: buffer? } + +local function encodePage(img: Types.Image, o: EncodeOptions, comp: number): ({ Tag }?, { buffer }?, Err.Err?) + local L = LAYOUT[img.format] + if not L then + return nil, nil, Err.new(Err.ARG, "unsupported pixel format " .. tostring(img.format)) + end + local w, h = img.width, img.height + local spp, bps, sfmt, photo = L[1], L[2], L[3], L[4] + local rb = w * spp * bps // 8 + if type(w) ~= "number" or w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 or w > 2 ^ 31 or buffer.len(img.pixels) < rb * h then + return nil, nil, Err.new(Err.ARG, "bad image size or pixel buffer") + end + local rps = o.rowsPerStrip or math.max(1, 65536 // rb) + if type(rps) ~= "number" or rps < 1 then + return nil, nil, Err.new(Err.ARG, "rowsPerStrip must be >= 1") + end + rps = math.min(math.floor(rps), h) + local predictor = 1 + if (comp == 8 or comp == 5) and o.predictor ~= false then + predictor = if sfmt == 3 then 3 else 2 + end + local strips = {} + local tmp = buffer.create(rb + 8) + for y0 = 0, h - 1, rps do + local rows = math.min(rps, h - y0) + local raw = buffer.create(rows * rb) + buffer.copy(raw, 0, img.pixels, y0 * rb, rows * rb) + if predictor == 2 then + Pixels.predict2(raw, 0, rows, rb, spp, bps) + elseif predictor == 3 then + Pixels.predict3(raw, 0, rows, rb, 4, spp, tmp) + end + local out + if comp == 1 then + out = raw + elseif comp == 8 then + out = Deflate.zlibCompress(raw, { level = o.level or 6 }) :: buffer + elseif comp == 5 then + out = Lzw.encode(raw, 0, rows * rb, "tiff") + else + local parts, total = {}, 0 + for r = 0, rows - 1 do + local p = PackBits.encode(raw, r * rb, rb) + table.insert(parts, p) + total += buffer.len(p) + end + out = buffer.create(total) + local q = 0 + for _, p in parts do + buffer.copy(out, q, p) + q += buffer.len(p) + end + end + table.insert(strips, out) + end + local bpsv = table.create(spp, bps) + local tags: { Tag } = { + { tag = 254, typ = 4, vals = { 0 } }, + { tag = 256, typ = 4, vals = { w } }, + { tag = 257, typ = 4, vals = { h } }, + { tag = 258, typ = 3, vals = bpsv }, + { tag = 259, typ = 3, vals = { comp } }, + { tag = 262, typ = 3, vals = { photo } }, + { tag = 273, typ = 4, vals = table.create(#strips, 0) }, -- patched + { tag = 277, typ = 3, vals = { spp } }, + { tag = 278, typ = 4, vals = { rps } }, + { tag = 279, typ = 4, vals = table.create(#strips, 0) }, + { tag = 284, typ = 3, vals = { 1 } }, + } + for i, s in strips do + (tags[10].vals :: { number })[i] = buffer.len(s) + end + local dpi = img.meta and img.meta.dpi + if type(dpi) == "table" and type(dpi.x) == "number" and type(dpi.y) == "number" and dpi.x > 0 and dpi.y > 0 then + table.insert(tags, { tag = 282, typ = 5, vals = { dpi.x } }) + table.insert(tags, { tag = 283, typ = 5, vals = { dpi.y } }) + table.insert(tags, { tag = 296, typ = 3, vals = { 2 } }) + end + if predictor > 1 then + table.insert(tags, { tag = 317, typ = 3, vals = { predictor } }) + end + if spp == 2 or spp == 4 then + table.insert(tags, { tag = 338, typ = 3, vals = { 2 } }) + end + if sfmt ~= 1 then + table.insert(tags, { tag = 339, typ = 3, vals = table.create(spp, sfmt) }) + end + local icc = img.meta and img.meta.icc + if type(icc) == "buffer" then + table.insert(tags, { tag = 34675, typ = 7, data = icc }) + 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 } :: { [string]: number } do + if type(text[key]) == "string" then + table.insert(tags, { tag = tag, typ = 2, data = buffer.fromstring(text[key] .. "\0") }) + end + end + end + table.sort(tags, function(a: Tag, b: Tag): boolean + return a.tag < b.tag + end) + return tags, strips, nil +end + +function Tiff.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "needs an Image") + end + local o: EncodeOptions = opts or {} + local comp = COMP_CODES[o.compression or "deflate"] + if not comp then + return nil, Err.new(Err.ARG, "compression must be none, deflate, lzw or packbits") + end + local list = { img } + if type(img.frames) == "table" and #img.frames > 1 then + list = {} + for _, f in img.frames :: any do + if type(f) ~= "table" or type(f.image) ~= "table" then + return nil, Err.new(Err.ARG, "bad frame") + end + table.insert(list, f.image) + end + end + local w = Bytes.writer(1024) + w:string("II") + w:u16le(42) + w:u32le(0) -- first IFD, patched + local prevNext = 4 + for _, page in list do + local tags, strips, err = encodePage(page, o, comp) + if not tags or not strips then + return nil, err + end + local soffs = {} + for i, s in strips do + if w:tell() % 2 == 1 then + w:u8(0) + end + soffs[i] = w:tell() + w:bytes(s) + end + for _, tg in tags do + if tg.tag == 273 then + tg.vals = soffs + end + end + -- out-of-line values + local valOff: { [number]: number } = {} + for i, tg in tags do + local size = TYPE_SIZE[tg.typ] + local n = if tg.data then buffer.len(tg.data :: buffer) else #(tg.vals :: { number }) * size + if n > 4 then + if w:tell() % 2 == 1 then + w:u8(0) + end + valOff[i] = w:tell() + if tg.data then + w:bytes(tg.data :: buffer) + else + for _, v in tg.vals :: { number } do + if tg.typ == 3 then + w:u16le(v) + elseif tg.typ == 4 then + w:u32le(v) + elseif tg.typ == 5 then + w:u32le(math.floor(v * 10000 + 0.5)) + w:u32le(10000) + end + end + end + end + end + if w:tell() % 2 == 1 then + w:u8(0) + end + local ifd = w:tell() + w:setU32le(prevNext, ifd) + w:u16le(#tags) + for i, tg in tags do + local count = if tg.data then buffer.len(tg.data :: buffer) else #(tg.vals :: { number }) + w:u16le(tg.tag) + w:u16le(tg.typ) + w:u32le(count) + if valOff[i] then + w:u32le(valOff[i]) + else + local start = w:tell() + if tg.data then + w:bytes(tg.data :: buffer) + else + for _, v in tg.vals :: { number } do + if tg.typ == 3 then + w:u16le(v) + else + w:u32le(v) + end + end + end + w:fill(0, 4 - (w:tell() - start)) + end + end + prevNext = w:tell() + w:u32le(0) + end + return w:finish(), nil +end + +return Tiff +end +__FILES["image/tiff/Pixels"] = @native function() + + + +-- image/tiff/Pixels: TIFF predictors 2 / 3 (TIFF 6.0 section 14, technote 3; 3 as libtiff fpAcc / fpDiff). +local Bytes = __include("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 +local floor = math.floor + +local Pixels = {} + +local scratch = buffer.create(8) + +-- floats read through their bits: LuaJIT's FFI can hand back a NaN with a payload its NaN-tagging misreads +@native local function f32(bits: number): number + if band(bits, 0x7F800000) == 0x7F800000 then + if band(bits, 0x7FFFFF) ~= 0 then + return 0 / 0 + end + return if bits >= 0x80000000 then -math.huge else math.huge + end + writeu32(scratch, 0, bits) + return readf32(scratch, 0) +end +@native local function f64(lo: number, hi: number): number + if band(hi, 0x7FF00000) == 0x7FF00000 then + if band(hi, 0xFFFFF) ~= 0 or lo ~= 0 then + return 0 / 0 + end + return if hi >= 0x80000000 then -math.huge else math.huge + end + writeu32(scratch, 0, lo) + writeu32(scratch, 4, hi) + return readf64(scratch, 0) +end +Pixels.f32 = f32 +Pixels.f64 = f64 + +-- ------------------------------------------------------------------------------------------------ fill order +local REV = buffer.create(256) +for i = 0, 255 do + local r = 0 + for k = 0, 7 do + if band(i, lshift(1, k)) ~= 0 then + r = bor(r, lshift(1, 7 - k)) + end + end + writeu8(REV, i, r) +end +@native function Pixels.reverseBits(b: buffer, off: number, len: number) + for i = off, off + len - 1 do + writeu8(b, i, readu8(REV, readu8(b, i))) + end +end + +-- ------------------------------------------------------------------------------------------------ predictors +@native function Pixels.unpredict2(b: buffer, off: number, rows: number, rb: number, stride: number, bps: number, le: boolean) + for r = 0, rows - 1 do + local base = off + r * rb + if bps == 8 then + for i = base + stride, base + rb - 1 do + writeu8(b, i, band(readu8(b, i) + readu8(b, i - stride), 255)) + end + elseif bps == 16 then + local n = rb // 2 + for k = stride, n - 1 do + local i = base + k * 2 + local j = i - stride * 2 + if le then + writeu16(b, i, band(readu16(b, i) + readu16(b, j), 0xFFFF)) + else + local v = readu8(b, i) * 256 + readu8(b, i + 1) + readu8(b, j) * 256 + readu8(b, j + 1) + writeu8(b, i, band(rshift(v, 8), 255)) + writeu8(b, i + 1, band(v, 255)) + end + end + elseif bps == 32 then + local n = rb // 4 + for k = stride, n - 1 do + local i = base + k * 4 + local j = i - stride * 4 + if le then + writeu32(b, i, (readu32(b, i) + readu32(b, j)) % 4294967296) + else + writeu32(b, i, byteswap((byteswap(readu32(b, i)) + byteswap(readu32(b, j))) % 4294967296)) + end + end + end + end +end + +@native function Pixels.predict2(b: buffer, off: number, rows: number, rb: number, stride: number, bps: number) + for r = 0, rows - 1 do + local base = off + r * rb + if bps == 8 then + for i = base + rb - 1, base + stride, -1 do + writeu8(b, i, band(readu8(b, i) - readu8(b, i - stride), 255)) + end + elseif bps == 16 then + for k = rb // 2 - 1, stride, -1 do + local i = base + k * 2 + writeu16(b, i, band(readu16(b, i) - readu16(b, i - stride * 2), 0xFFFF)) + end + end + end +end + +-- the samples come out little endian whatever the file's byte order (libtiff fpAcc) +@native function Pixels.unpredict3(b: buffer, off: number, rows: number, rb: number, bytes: number, stride: number, tmp: buffer) + local wc = rb // bytes + for r = 0, rows - 1 do + local base = off + r * rb + for i = base + stride, base + rb - 1 do + writeu8(b, i, band(readu8(b, i) + readu8(b, i - stride), 255)) + end + buffer.copy(tmp, 0, b, base, rb) + for c = 0, wc - 1 do + for k = 0, bytes - 1 do + writeu8(b, base + c * bytes + k, readu8(tmp, (bytes - k - 1) * wc + c)) + end + end + end +end + +@native function Pixels.predict3(b: buffer, off: number, rows: number, rb: number, bytes: number, stride: number, tmp: buffer) + local wc = rb // bytes + for r = 0, rows - 1 do + local base = off + r * rb + for c = 0, wc - 1 do + for k = 0, bytes - 1 do + writeu8(tmp, (bytes - k - 1) * wc + c, readu8(b, base + c * bytes + k)) + end + end + buffer.copy(b, base, tmp, 0, rb) + for i = base + rb - 1, base + stride, -1 do + writeu8(b, i, band(readu8(b, i) - readu8(b, i - stride), 255)) + end + end +end + +-- ------------------------------------------------------------------------------------------------ samples +local half = Bytes.half + +type Params = { + planes: { buffer }, + rb: number, + chunky: boolean, + w: number, + h: number, + spp: number, + bps: number, + sfmt: number, -- 1 uint, 2 int, 3 float + le: boolean, + photo: number, -- 0 min-is-white, 1 min-is-black, 2 RGB, 3 palette, 5 CMYK + alpha: number, + assoc: boolean, -- premultiplied alpha (undone) + cmap: buffer?, -- palette: 3 * 2^bps u16 (red block, green block, blue block) + kind: string, + out: buffer, +} + +@native local function fast(P: Params): boolean + if not P.chunky or P.bps ~= 8 or P.sfmt ~= 1 or P.assoc then + return false + end + local b, rb, w, h, spp, alpha, kind, out = P.planes[1], P.rb, P.w, P.h, P.spp, P.alpha, P.kind, P.out + local o = 0 + if P.photo == 2 and spp >= 3 and (kind == "rgba8" or kind == "rgb8") then + local four = kind == "rgba8" + for y = 0, h - 1 do + local p = y * rb + for _ = 0, w - 1 do + writeu8(out, o, readu8(b, p)) + writeu8(out, o + 1, readu8(b, p + 1)) + writeu8(out, o + 2, readu8(b, p + 2)) + if four then + writeu8(out, o + 3, if alpha >= 0 then readu8(b, p + alpha) else 255) + o += 4 + else + o += 3 + end + p += spp + end + end + return true + elseif (P.photo == 1 or P.photo == 0) and (kind == "rgba8" or kind == "gray8" or kind == "graya8") then + local inv = if P.photo == 0 then 255 else 0 + for y = 0, h - 1 do + local p = y * rb + for _ = 0, w - 1 do + local v = math.abs(inv - readu8(b, p)) + if kind == "gray8" then + writeu8(out, o, v) + o += 1 + elseif kind == "graya8" then + writeu8(out, o, v) + writeu8(out, o + 1, if alpha >= 0 then readu8(b, p + alpha) else 255) + o += 2 + else + writeu32(out, o, v * 0x10101 + (if alpha >= 0 then readu8(b, p + alpha) else 255) * 0x1000000) + o += 4 + end + p += spp + end + end + return true + end + return false +end + +@native function Pixels.convert(P: Params) + if fast(P) then + return + end + local planes, rb, chunky, w, h, spp, bps, sfmt, le = P.planes, P.rb, P.chunky, P.w, P.h, P.spp, P.bps, P.sfmt, P.le + local photo, alpha, assoc, cmap, kind, out = P.photo, P.alpha, P.assoc, P.cmap, P.kind, P.out + local maxv = 2 ^ math.min(bps, 32) - 1 + local float = sfmt == 3 + local signed = sfmt == 2 + local cmapN = 2 ^ math.min(bps, 16) + @native local function raw(s: number, x: number, row: number): number + local b, i + if chunky then + b, i = planes[1], x * spp + s + else + b, i = planes[s + 1], x + end + local ro = row * rb + if bps == 8 then + local v = readu8(b, ro + i) + return if signed then (v + 128) % 256 else v + elseif bps == 16 then + local p = ro + i * 2 + local v = if le then readu16(b, p) else readu8(b, p) * 256 + readu8(b, p + 1) + if float then + return half(v) + end + return if signed then (v + 32768) % 65536 else v + elseif bps == 32 then + local p = ro + i * 4 + if float then + return f32(if le then readu32(b, p) else byteswap(readu32(b, p))) + end + local v = if le then readu32(b, p) else byteswap(readu32(b, p)) + return if signed then (v + 2147483648) % 4294967296 else v + elseif bps == 64 then + local p = ro + i * 8 + if le then + return f64(readu32(b, p), readu32(b, p + 4)) + end + return f64(byteswap(readu32(b, p + 4)), byteswap(readu32(b, p))) + else + -- any other depth (1..31): MSB-first bit fields + local bit = i * bps + local v = 0 + local need = bps + local p = ro + rshift(bit, 3) + local sh = band(bit, 7) + local cur = band(readu8(b, p), rshift(255, sh)) + local avail = 8 - sh + while need > 0 do + if need >= avail then + v = v * 2 ^ avail + cur + need -= avail + p += 1 + cur = if need > 0 then readu8(b, p) else 0 + avail = 8 + else + v = v * 2 ^ need + rshift(cur, avail - need) + need = 0 + end + end + return v + end + end + -- normalised 0..1 (floats as stored) + @native local function norm(s: number, x: number, row: number): number + local v = raw(s, x, row) + if float then + return v + end + return v / maxv + end + local o = 0 + local is8 = kind == "rgba8" or kind == "rgb8" or kind == "gray8" or kind == "graya8" + local is16 = kind == "rgba16" or kind == "gray16" + local nch = if kind == "rgba8" or kind == "rgba16" or kind == "rgbaf32" then 4 elseif kind == "rgb8" then 3 elseif kind == "graya8" then 2 else 1 + for y = 0, h - 1 do + for x = 0, w - 1 do + local r, g, bl, a + if photo == 3 then + local idx = raw(0, x, y) + if cmap and idx < cmapN then + r = readu16(cmap, idx * 2) / 65535 + g = readu16(cmap, (cmapN + idx) * 2) / 65535 + bl = readu16(cmap, (2 * cmapN + idx) * 2) / 65535 + else + r, g, bl = 0, 0, 0 + end + elseif photo == 2 then + 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) + else + local v = norm(0, x, y) + if photo == 0 then + v = 1 - v + end + r, g, bl = v, v, v + end + if alpha >= 0 then + a = norm(alpha, x, y) + if assoc then + if a > 0 then + 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 + end + else + a = 1 + end + if is8 then + if r ~= r then + r = 0 + end + if g ~= g then + g = 0 + end + if bl ~= bl then + bl = 0 + end + if a ~= a then + a = 0 + end + local R = floor(math.clamp(r, 0, 1) * 255 + 0.5) + if nch == 1 then + writeu8(out, o, R) + elseif nch == 2 then + writeu8(out, o, R) + writeu8(out, o + 1, floor(math.clamp(a, 0, 1) * 255 + 0.5)) + else + writeu8(out, o, R) + writeu8(out, o + 1, floor(math.clamp(g, 0, 1) * 255 + 0.5)) + writeu8(out, o + 2, floor(math.clamp(bl, 0, 1) * 255 + 0.5)) + if nch == 4 then + writeu8(out, o + 3, floor(math.clamp(a, 0, 1) * 255 + 0.5)) + end + end + o += nch + elseif is16 then + if r ~= r then + r = 0 + end + if g ~= g then + g = 0 + end + if bl ~= bl then + bl = 0 + end + if a ~= a then + a = 0 + end + writeu16(out, o, floor(math.clamp(r, 0, 1) * 65535 + 0.5)) + if nch == 4 then + writeu16(out, o + 2, floor(math.clamp(g, 0, 1) * 65535 + 0.5)) + writeu16(out, o + 4, floor(math.clamp(bl, 0, 1) * 65535 + 0.5)) + writeu16(out, o + 6, floor(math.clamp(a, 0, 1) * 65535 + 0.5)) + end + o += nch * 2 + else + writef32(out, o, r) + writef32(out, o + 4, g) + writef32(out, o + 8, bl) + writef32(out, o + 12, a) + o += 16 + end + end + end +end + +return Pixels +end +__FILES["image/tim"] = function() + +-- image/tim: PlayStation TIM (magic 0x10), from Sony's PSX "File Formats" documentation. Supports: 4 / 8-bit CLUT, 15 / +-- 24-bit direct; colours are 1-5-5-5 STP-B-G-R, expanded (v << 3) | (v >> 2), 0x0000 transparent as on the hardware, +-- opaque black written as 0x8000. Not supported: mixed mode (pmode 4). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") + +-- ------------------------------------------------------------------------------------------------ contract +local Tim = { + name = "tim", + category = "image", + extensions = { "tim" }, + mime = { "image/x-tim" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 4, 8, 16, 24 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + clut: number?, -- 0-based, default 0 + maxPixels: number?, -- default 2^26 +} +type EncodeOptions = { + bpp: number?, -- 4, 8, 16 (default) or 24 + x: number?, -- default 0, 0 + y: number?, + clutX: number?, -- default 0, 480 + clutY: number?, +} + +-- ------------------------------------------------------------------------------------------------ constants +local readu8, readu16, writeu32, writeu16, readu32 = buffer.readu8, buffer.readu16, buffer.writeu32, buffer.writeu16, buffer.readu32 +local BPP = { [0] = 4, [1] = 8, [2] = 16, [3] = 24 } + +-- ------------------------------------------------------------------------------------------------ sniff +function Tim.sniff(r: Bytes.Reader): number + if r:remaining() < 20 or r:peek(4) ~= "\16\0\0\0" then + return 0 + end + local flags = r:peekU8(4) + if flags > 0x0F or (flags % 8) > 3 or r:peek(3, 5) ~= "\0\0\0" then + return 0 + end + return 0.8 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function colour(c: number): number + if c == 0 then + return 0 + end + local r, g, b = c % 32, (c // 32) % 32, (c // 1024) % 32 + r, g, b = r * 8 + r // 4, g * 8 + g // 4, b * 8 + b // 4 + return 0xFF000000 + b * 65536 + g * 256 + r +end + +function Tim.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local magic, flags = r:u32le(), r:u32le() + if r.err then + return nil, r.err + end + if magic ~= 0x10 then + return nil, Err.new(Err.CORRUPT, "bad magic", 0) + end + local pmode = flags % 8 + local bpp = BPP[pmode] + if not bpp then + return nil, Err.new(Err.UNSUPPORTED, "pmode " .. pmode .. " (mixed / unknown)", 4) + end + local stp = false + local pal: buffer? = nil + local clutInfo: any = nil + if bit32.band(flags, 8) ~= 0 then + local start = r:tell() + local bnum, cx, cy, cw, ch = r:u32le(), r:u16le(), r:u16le(), r:u16le(), r:u16le() + if r.err then + return nil, r.err + end + if bnum < 12 or cw * ch * 2 > bnum - 12 then + return nil, Err.new(Err.CORRUPT, "bad CLUT block", start) + end + if not r:need(cw * ch * 2) then + return nil, r.err + end + local row = math.clamp(math.floor(opts and opts.clut or 0), 0, math.max(ch - 1, 0)) + pal = buffer.create(256 * 4) + local p = r.pos + row * cw * 2 + for i = 0, math.min(cw, 256) - 1 do + local c = readu16(r.buf, p + i * 2) + if c >= 0x8000 then + stp = true + end + writeu32(pal :: buffer, i * 4, if c == 0x8000 then 0xFF000000 else colour(c % 0x8000)) + end + clutInfo = { x = cx, y = cy, colours = cw, count = ch, row = row } + r:seek(start + bnum) + if r.err then + return nil, r.err + end + elseif bpp <= 8 then + return nil, Err.new(Err.CORRUPT, "indexed image without a CLUT", 4) + end + local start = r:tell() + local bnum, ix, iy, iw, ih = r:u32le(), r:u16le(), r:u16le(), r:u16le(), r:u16le() + if r.err then + return nil, r.err + end + local w = if bpp == 4 then iw * 4 elseif bpp == 8 then iw * 2 elseif bpp == 16 then iw else (iw * 2) // 3 + local stride = iw * 2 + if w * ih > (opts and opts.maxPixels or 2 ^ 26) then + return nil, Err.new(Err.LIMIT, "image too big") + end + if bnum < 12 or stride * ih > bnum - 12 then + return nil, Err.new(Err.CORRUPT, "bad image block", start) + end + if not r:need(stride * ih) then + return nil, r.err + end + local img = Types.Image.new(w, ih) + local px, src, at = img.pixels, r.buf, r.pos + for y = 0, ih - 1 do + local row = at + y * stride + local d = y * w * 4 + if bpp == 4 then + for x = 0, w - 1 do + local v = readu8(src, row + x // 2) + local i = if x % 2 == 0 then v % 16 else v // 16 + writeu32(px, d + x * 4, readu32(pal :: buffer, i * 4)) + end + elseif bpp == 8 then + for x = 0, w - 1 do + writeu32(px, d + x * 4, readu32(pal :: buffer, readu8(src, row + x) * 4)) + end + elseif bpp == 16 then + for x = 0, w - 1 do + local c = readu16(src, row + x * 2) + if c >= 0x8000 then + stp = true + end + writeu32(px, d + x * 4, if c == 0x8000 then 0xFF000000 else colour(c % 0x8000)) + end + else + for x = 0, w - 1 do + local o = row + x * 3 + writeu32(px, d + x * 4, 0xFF000000 + readu8(src, o + 2) * 65536 + readu8(src, o + 1) * 256 + readu8(src, o)) + end + end + end + img.meta.source = { format = "tim", bpp = bpp, x = ix, y = iy, clut = clutInfo, stp = stp or nil } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function psx(v: number): number + local r, g, b, a = v % 256, (v // 256) % 256, (v // 65536) % 256, v // 16777216 + if a < 128 then + return 0 + end + local c = (b // 8) * 1024 + (g // 8) * 32 + r // 8 + return if c == 0 then 0x8000 else c +end + +function Tim.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "expected an rgba8 Image") + end + local w, h = img.width, img.height + local bpp = opts and opts.bpp or 16 + local per = ({ [4] = 4, [8] = 2, [16] = 1, [24] = 2 / 3 } :: { [number]: number })[bpp] + if not per then + return nil, Err.new(Err.ARG, "bpp must be 4, 8, 16 or 24") + end + local iw = if bpp == 24 then (w * 3 + 1) // 2 else math.ceil(w / per) + if iw > 0xFFFF or h > 0xFFFF then + return nil, Err.new(Err.ARG, "image too wide for TIM") + end + local px = img.pixels + local out = Bytes.writer(64 + iw * 2 * h) + out:u32le(0x10) + local colours: { number } = {} + local index: { [number]: number } = {} + if bpp <= 8 then + for i = 0, w * h - 1 do + local c = psx(readu32(px, i * 4)) + if not index[c] then + table.insert(colours, c) + index[c] = #colours - 1 + if #colours > (if bpp == 4 then 16 else 256) then + return nil, Err.new(Err.ARG, "more than " .. (if bpp == 4 then 16 else 256) .. " colours for a " .. bpp .. "-bit TIM") + end + end + end + local n = if bpp == 4 then 16 else 256 + out:u32le(8 + (if bpp == 4 then 0 else 1)) + out:u32le(12 + n * 2) + out:u16le(opts and opts.clutX or 0) + out:u16le(opts and opts.clutY or 480) + out:u16le(n) + out:u16le(1) + for i = 1, n do + out:u16le(colours[i] or 0) + end + else + out:u32le(if bpp == 16 then 2 else 3) + end + out:u32le(12 + iw * 2 * h) + out:u16le(opts and opts.x or 0) + out:u16le(opts and opts.y or 0) + out:u16le(iw) + out:u16le(h) + local at = out:reserve(iw * 2 * h) + local b = out.buf + buffer.fill(b, at, 0, iw * 2 * h) + for y = 0, h - 1 do + local row = at + y * iw * 2 + for x = 0, w - 1 do + local v = readu32(px, (y * w + x) * 4) + if bpp == 4 then + local i = index[psx(v)] + local o = row + x // 2 + buffer.writeu8(b, o, buffer.readu8(b, o) + (if x % 2 == 0 then i else i * 16)) + elseif bpp == 8 then + buffer.writeu8(b, row + x, index[psx(v)]) + elseif bpp == 16 then + writeu16(b, row + x * 2, psx(v)) + else + buffer.writeu8(b, row + x * 3, v % 256) + buffer.writeu8(b, row + x * 3 + 1, (v // 256) % 256) + buffer.writeu8(b, row + x * 3 + 2, (v // 65536) % 256) + end + end + end + out.pos = at + iw * 2 * h + return out:finish(), nil +end + +return Tim +end +__FILES["image/vtf"] = function() + +-- image/vtf: Valve Texture Format 7.0 - 7.5 (Source engine), from the Valve Developer Community VTF page. Supports: the +-- high-resolution image, mips / faces / slices / frames, uncompressed texels, DXT1 / DXT3 / DXT5, ATI1N / ATI2N (35 / +-- 34 Alien Swarm, 38 / 37 Source 2013). Not supported: P8, Strata / Source 2 formats, writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Bcn = __include("codecs/image/Bcn") +local Texel = __include("codecs/image/Texel") + +-- ------------------------------------------------------------------------------------------------ contract +local Vtf = { + name = "vtf", + category = "image", + extensions = { "vtf" }, + mime = { "image/x-vtf" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Bcn", "codecs/image/Texel" }, + caps = { decode = true, encode = false, alpha = true, animation = true, versions = { "7.0", "7.1", "7.2", "7.3", "7.4", "7.5" } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + mip: number?, -- 0 = full size, default + face: number?, -- 0-based, default 0 + slice: number?, -- 0-based, default 0 + frames: boolean?, -- default true + delay: number?, -- seconds, default 0.1 + maxPixels: number?, -- default 2^26 +} + +-- ------------------------------------------------------------------------------------------------ constants +local M = Texel.masked +local FORMATS: { [number]: any } = { + [0] = "rgba8", -- RGBA8888 + [1] = M(4, 0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF), -- ABGR8888 + [2] = "rgb8", -- RGB888 + [3] = "bgr8", -- BGR888 + [4] = "r5g6b5", -- RGB565: red in the low bits (as VTFLib / srctools read it) + [5] = "l8", -- I8 + [6] = "la8", -- IA88 + [8] = "a8", -- A8 + [9] = { texel = "rgb8", bluescreen = true }, -- RGB888_BLUESCREEN + [10] = { texel = "bgr8", bluescreen = true }, -- BGR888_BLUESCREEN + [11] = M(4, 0xFF000000, 0x000000FF, 0x0000FF00, 0x00FF0000), -- ARGB8888: VTFLib's layout (G, B, A, R in memory) + [12] = "bgra8", -- BGRA8888 + [13] = "bc1", -- DXT1 + [14] = "bc2", -- DXT3 + [15] = "bc3", -- DXT5 + [16] = "bgrx8", -- BGRX8888 + [17] = "b5g6r5", -- BGR565: blue in the low bits + [18] = "b5g5r5x1", -- BGRX5551 + [19] = "b4g4r4a4", -- BGRA4444 + [20] = "bc1a", -- DXT1_ONEBITALPHA + [21] = "b5g5r5a1", -- BGRA5551 + [22] = "rg8", -- UV88 + [23] = "rgba8", -- UVWQ8888 + [24] = "rgba16f", -- RGBA16161616F + [25] = "rgba16", -- RGBA16161616 + [26] = "rgba8", -- UVLX8888 + [27] = "r32f", -- R32F + [28] = "rgb32f", -- RGB323232F + [29] = "rgba32f", -- RGBA32323232F + [34] = "bc5", -- ATI2N (Alien Swarm and later) + [35] = "bc4", -- ATI1N (Alien Swarm and later) + [37] = "bc5", -- ATI2N (Source 2013) + [38] = "bc4", -- ATI1N (Source 2013) +} +local BCN: { [string]: boolean } = { bc1 = true, bc1a = true, bc2 = true, bc3 = true, bc4 = true, bc5 = true } +local NAMES: { [number]: string } = { [0] = "RGBA8888", "ABGR8888", "RGB888", "BGR888", "RGB565", "I8", "IA88", "P8", "A8", "RGB888_BLUESCREEN", + "BGR888_BLUESCREEN", "ARGB8888", "BGRA8888", "DXT1", "DXT3", "DXT5", "BGRX8888", "BGR565", "BGRX5551", "BGRA4444", + "DXT1_ONEBITALPHA", "BGRA5551", "UV88", "UVWQ8888", "RGBA16161616F", "RGBA16161616", "UVLX8888", "R32F", "RGB323232F", + "RGBA32323232F", "NV_DST16", "NV_DST24", "NV_INTZ", "NV_RAWZ", "ATI2N", "ATI1N", "NV_NULL", "ATI2N", "ATI1N" } +local ENVMAP = 0x4000 + +-- ------------------------------------------------------------------------------------------------ sniff +function Vtf.sniff(r: Bytes.Reader): number + return if r:peek(4) == "VTF\0" and r:peekU8(4) == 7 then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function imageSize(f: any, w: number, h: number): number + if type(f) == "string" and BCN[f] then + return Bcn.size(if f == "bc1a" then "bc1" else f, w, h) or 0 + end + return Texel.size(if type(f) == "table" and f.texel then f.texel else f, w, h) or 0 +end + +function Vtf.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local size = r.limit - r.base + local b, base = r.buf, r.base + if size < 64 then + return nil, Err.new(Err.TRUNCATED, "header", 0) + end + if buffer.readstring(b, base, 4) ~= "VTF\0" then + return nil, Err.new(Err.CORRUPT, "bad magic", 0) + end + local major, minor = buffer.readu32(b, base + 4), buffer.readu32(b, base + 8) + if major ~= 7 or minor > 5 then + return nil, Err.new(Err.UNSUPPORTED, "VTF version " .. major .. "." .. minor, 4) + end + local headerSize = buffer.readu32(b, base + 12) + local w, h = buffer.readu16(b, base + 16), buffer.readu16(b, base + 18) + local flags = buffer.readu32(b, base + 20) + local frames, firstFrame = buffer.readu16(b, base + 24), buffer.readu16(b, base + 26) + local refl = { buffer.readf32(b, base + 32), buffer.readf32(b, base + 36), buffer.readf32(b, base + 40) } + local bump = buffer.readf32(b, base + 48) + local fmtId = buffer.readi32(b, base + 52) + local mips = buffer.readu8(b, base + 56) + local lowFmt = buffer.readi32(b, base + 57) + local lowW, lowH = buffer.readu8(b, base + 61), buffer.readu8(b, base + 62) + local depth = if minor >= 2 and size >= 65 then math.max(1, buffer.readu16(b, base + 63)) else 1 + if w == 0 or h == 0 then + return nil, Err.new(Err.CORRUPT, "zero size", 16) + end + if w * h > (opts and opts.maxPixels or 2 ^ 26) then + return nil, Err.new(Err.LIMIT, "image too big") + end + local f: any = FORMATS[fmtId] + if not f then + return nil, Err.new(Err.UNSUPPORTED, "texel format " .. (NAMES[fmtId] or tostring(fmtId)), 52) + end + frames = math.max(1, frames) + mips = math.max(1, mips) + local faces = 1 + if bit32.band(flags, ENVMAP) ~= 0 then + faces = if minor < 5 and firstFrame ~= 0xFFFF then 7 else 6 + end + -- where the high-resolution data starts + local dataAt: number? = nil + if minor >= 3 then + if size < 80 then + return nil, Err.new(Err.TRUNCATED, "resource directory", 68) + end + local nres = buffer.readu32(b, base + 68) + if nres > 32 or 80 + nres * 8 > size then + return nil, Err.new(Err.CORRUPT, "bad resource count", 68) + end + for i = 0, nres - 1 do + local o = base + 80 + i * 8 + if buffer.readu8(b, o) == 0x30 and buffer.readu8(b, o + 1) == 0 and buffer.readu8(b, o + 2) == 0 then + dataAt = buffer.readu32(b, o + 4) + end + end + if not dataAt then + return nil, Err.new(Err.CORRUPT, "no high-resolution image resource", 80) + end + else + local lf = FORMATS[lowFmt] + local lowSize = if lowFmt >= 0 and lowW > 0 and lowH > 0 and lf then imageSize(lf, lowW, lowH) else 0 + dataAt = headerSize + lowSize + end + local mip = math.clamp(math.floor(opts and opts.mip or 0), 0, mips - 1) + local face = math.clamp(math.floor(opts and opts.face or 0), 0, faces - 1) + local slice = math.clamp(math.floor(opts and opts.slice or 0), 0, depth - 1) + local off = dataAt :: number + for m = mips - 1, mip + 1, -1 do + local mw, mh, md = math.max(1, w // 2 ^ m), math.max(1, h // 2 ^ m), math.max(1, depth // 2 ^ m) + off += imageSize(f, mw, mh) * md * faces * frames + end + local mw, mh, md = math.max(1, w // 2 ^ mip), math.max(1, h // 2 ^ mip), math.max(1, depth // 2 ^ mip) + local one = imageSize(f, mw, mh) + local function image(frame: number): (Types.Image?, Err.Err?) + local at = off + ((frame * faces + face) * md + math.min(slice, md - 1)) * one + if at + one > size or at < 0 then + return nil, Err.new(Err.TRUNCATED, "image data past the end", at) + end + local img = Types.Image.new(mw, mh) + if type(f) == "string" and BCN[f] then + local kind = if f == "bc1a" then "bc1" else f + local px, e = Bcn.decode(kind, b, base + at, mw, mh) + if not px then + return nil, Err.from(e) + end + buffer.copy(img.pixels, 0, px, 0, mw * mh * 4) + if f == "bc1" then + -- plain DXT1 carries no alpha: the transparent colour of 3-colour blocks reads as opaque black + for i = 0, mw * mh - 1 do + buffer.writeu8(img.pixels, i * 4 + 3, 255) + end + end + else + local blue = type(f) == "table" and f.bluescreen == true + local px, e = Texel.decode(if blue then f.texel else f, b, base + at, mw, mh) + if not px then + return nil, Err.from(e) + end + buffer.copy(img.pixels, 0, px, 0, mw * mh * 4) + if blue then + -- pure blue is the transparent key + for i = 0, mw * mh - 1 do + if buffer.readu32(img.pixels, i * 4) == 0xFFFF0000 then + buffer.writeu32(img.pixels, i * 4, 0) + end + end + end + end + return img, nil + end + local img, err = image(0) + if not img then + return nil, err + end + if frames > 1 and not (opts and opts.frames == false) then + local delay = opts and opts.delay or 0.1 + local list: { Types.Frame } = { { image = img, delay = delay, x = 0, y = 0, dispose = "none", blend = "source" } :: any } + for fr = 1, frames - 1 do + local fi, ferr = image(fr) + if not fi then + return nil, ferr + end + table.insert(list, { image = fi, delay = delay, x = 0, y = 0, dispose = "none", blend = "source" } :: any) + end + img.frames = list + img.loops = 0 + end + img.meta.source = { + format = "vtf", + version = major .. "." .. minor, + flags = flags, + frames = frames, + faces = faces, + depth = depth, + mips = mips, + texel = NAMES[fmtId], + reflectivity = refl, + bumpScale = bump, + } + return img, nil +end + +return Vtf +end +__FILES["image/webp"] = function() + +-- image/webp: WebP (RFC 9649); bitstreams ported from libwebp 1.6 (BSD-3-Clause, licenses/libwebp-LICENSE.txt). +-- Supports: VP8 key frames (bit-exact with dwebp), VP8L, ALPH, VP8X, ANIM / ANMF, ICC / EXIF / XMP; writes VP8L. Not +-- supported: lossy encoding, VP8 scale fields (ignored, as dwebp), alpha dithering. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Vp8 = __include("codecs/image/Vp8") +local Vp8L = __include("codecs/image/Vp8L") +local Riff = __include("containers/Riff") +local Alpha = __include("image/webp/Alpha") +local Anim = __include("image/webp/Anim") + +-- ------------------------------------------------------------------------------------------------ contract +local Webp = { + name = "webp", + category = "image", + extensions = { "webp" }, + mime = { "image/webp" }, + 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 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + maxPixels: number?, -- default 2^26 + native: boolean?, -- default false: rgba8 + upsampling: ("fancy" | "nearest")?, -- default "fancy" (libwebp's; "nearest" = dwebp -nofancy) + coalesce: boolean?, -- default false: each frame's own rectangle + frames: boolean?, -- default true +} + +type EncodeOptions = { + lossless: boolean?, -- true or nil + effort: number?, -- 0..9, default 5 + exact: boolean?, -- default false + loops: number?, -- default img.loops; 0 = forever + background: { number }?, -- default meta.background or 0 +} + +-- ------------------------------------------------------------------------------------------------ constants +local DEFAULT_MAX_PIXELS = 2 ^ 26 +local FLAG_ANIM, FLAG_XMP, FLAG_EXIF, FLAG_ALPHA, FLAG_ICC = 0x02, 0x04, 0x08, 0x10, 0x20 + +local readu8 = buffer.readu8 + +local function u24(buf: buffer, p: number): number + return readu8(buf, p) + readu8(buf, p + 1) * 256 + readu8(buf, p + 2) * 65536 +end + +local function corrupt(msg: string, offset: number?): (nil, Err.Err) + return nil, Err.new(Err.CORRUPT, msg, offset) +end + +local function fromMessage(msg: any, offset: number?): Err.Err + if Err.is(msg) then + return msg + end + local m = tostring(msg) + for _, k in { { "truncated: ", Err.TRUNCATED }, { "limit: ", Err.LIMIT }, { "unsupported: ", Err.UNSUPPORTED } } do + if string.sub(m, 1, #k[1]) == k[1] then + return Err.new(k[2], string.sub(m, #k[1] + 1), offset) + end + end + return Err.new(Err.CORRUPT, m, offset) +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Webp.sniff(r: Bytes.Reader): number + if r:peek(4) == "RIFF" and r:peek(4, 8) == "WEBP" then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +type Chunk = { id: string, off: number, size: number } -- off: absolute offset of the payload + +local function convert(list: { Riff.Chunk }): ({ Chunk }?, Err.Err?) + local out: { Chunk } = {} + for _, c in list do + if c.truncated then + return nil, Err.new(Err.TRUNCATED, "chunk '" .. c.id .. "' runs past the end", c.offset) + end + table.insert(out, { id = c.id, off = c.offset, size = c.size }) + end + return out, nil +end + +-- as libwebp: the RIFF size must fit the data and bytes after it are ignored +local function readChunks(r: Bytes.Reader): ({ Chunk }?, any) + local buf, base, limit = r.buf, r.base, r.limit + if limit - base < 12 then + return nil, Err.new(Err.TRUNCATED, "RIFF header", base) + end + if buffer.readstring(buf, base, 4) ~= "RIFF" or buffer.readstring(buf, base + 8, 4) ~= "WEBP" then + return nil, Err.new(Err.CORRUPT, "not a RIFF WEBP file", base) + end + local size = buffer.readu32(buf, base + 4) + if size < 12 then + return nil, Err.new(Err.CORRUPT, "RIFF size too small", base + 4) + end + if 8 + size > limit - base then + return nil, Err.new(Err.TRUNCATED, "the RIFF size runs past the end of the data", base + 4) + end + local f, err = Riff.read(Bytes.reader(buf, base, 8 + size)) + if not f then + return nil, err + end + local list, cerr = convert(f.chunks) + if not list then + return nil, cerr + end + return list, f +end + +local function subChunks(f: Riff.File, c: Chunk): ({ Chunk }?, Err.Err?) + local n = c.size - 12 + 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 } } + +-- the image chunks of a still image or an ANMF frame: the first ALPH (if any) and the first VP8 / VP8L chunk +local function findImage(chunks: { Chunk }, from: number): (Chunk?, Chunk?) + local alph: Chunk? = nil + for i = from, #chunks do + local c = chunks[i] + if c.id == "ALPH" and not alph then + alph = c + elseif c.id == "VP8 " or c.id == "VP8L" then + return c, alph + elseif c.id == "ANMF" then + break + end + end + return nil, nil +end + +local function decodeBitstream(buf: buffer, c: Chunk, alph: Chunk?, opts: DecodeOptions, allowNative: boolean): (Bitstream?, Err.Err?) + local maxPixels = opts.maxPixels or DEFAULT_MAX_PIXELS + if c.id == "VP8L" then + local rgba, w, h, alphaHint = Vp8L.decode(buf, c.off, c.size, maxPixels) + if not rgba then + return nil, w + end + return { rgba = rgba, w = w, h = h :: number, hasAlpha = alphaHint == true, source = { codec = "vp8l", lossless = true } }, nil + end + local y, u, v, w, h = Vp8.decodePlanes(buf, c.off, c.size, { maxPixels = maxPixels }) + if not y then + return nil, u + end + local fw, fh = w :: number, h :: number + local source: { [string]: any } = { codec = "vp8", lossless = false } + if allowNative and opts.native and not alph then + local img = Types.Image.new(fw, fh, "yuv420p") + local ny, nc = fw * fh, buffer.len(v :: buffer) + buffer.copy(img.pixels, 0, y, 0, ny) + buffer.copy(img.pixels, ny, u, 0, nc) + buffer.copy(img.pixels, ny + nc, v :: buffer, 0, nc) + return { yuv = img, w = fw, h = fh, hasAlpha = false, source = source }, nil + end + local rgba = Vp8.yuvToRgba(y, u, v :: buffer, fw, fh, opts.upsampling ~= "nearest") + if alph then + local a, info = Alpha.decode(buf, alph.off, alph.size, fw, fh) + if not a then + return nil, fromMessage(info, alph.off) + end + Vp8.setAlpha(rgba, a, fw * fh) + source.alpha = info + end + return { rgba = rgba, w = fw, h = fh, hasAlpha = alph ~= nil, source = source }, nil +end + +local function collectMeta(buf: buffer, chunks: { Chunk }, meta: Types.ImageMeta) + for _, c in chunks do + local key = if c.id == "ICCP" then "icc" elseif c.id == "EXIF" then "exif" elseif c.id == "XMP " then "xmp" else nil + if key and meta[key] == nil then + local b = buffer.create(c.size) + buffer.copy(b, 0, buf, c.off, c.size) + meta[key] = b + end + end +end + +function Webp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local o: DecodeOptions = opts or {} + local maxPixels = o.maxPixels or DEFAULT_MAX_PIXELS + local buf = r.buf + local chunks, file = readChunks(r) + if not chunks then + return nil, file + end + local first = chunks[1] + if not first then + return corrupt("no chunks", r.base + 12) + end + if first.id == "VP8 " or first.id == "VP8L" then + local bs, err = decodeBitstream(buf, first, nil, o, true) + if not bs then + return nil, err + end + local img = bs.yuv or Types.Image.new(bs.w, bs.h, "rgba8") + if bs.rgba then + img.pixels = bs.rgba + end + bs.source.format = "webp" + bs.source.bitDepth = 8 + bs.source.extended = false + img.meta.source = bs.source + return img, nil + end + if first.id ~= "VP8X" then + return corrupt("the first chunk is '" .. first.id .. "', not VP8, VP8L or VP8X", first.off - 8) + end + if first.size < 10 then + return nil, Err.new(Err.TRUNCATED, "VP8X chunk too small", first.off) + end + local flags = readu8(buf, first.off) + local cw = u24(buf, first.off + 4) + 1 + local ch = u24(buf, first.off + 7) + 1 + if cw * ch > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d canvas is over the %d pixel limit", cw, ch, maxPixels)) + end + local meta: Types.ImageMeta = {} + collectMeta(buf, chunks, meta) + + if bit32.band(flags, FLAG_ANIM) == 0 then + local c, alph = findImage(chunks, 2) + if not c then + return corrupt("no VP8 / VP8L image chunk") + end + local bs, err = decodeBitstream(buf, c, if c.id == "VP8 " then alph else nil, o, true) + if not bs then + return nil, err + end + if bs.w ~= cw or bs.h ~= ch then + return corrupt(string.format("image %d x %d does not match the %d x %d canvas", bs.w, bs.h, cw, ch), c.off) + end + local img = bs.yuv or Types.Image.new(cw, ch, "rgba8") + if bs.rgba then + img.pixels = bs.rgba + end + for k, v in meta do + img.meta[k] = v + end + bs.source.format = "webp" + bs.source.bitDepth = 8 + bs.source.extended = true + bs.source.flags = flags + img.meta.source = bs.source + return img, nil + end + + -- animation: ANIM then ANMF frames + local bg, loops = 0, 0 + local haveAnim = false + local frames: { Anim.Frame } = {} + local sources: { any } = {} + local delays: { number } = {} + local wantAll = o.frames ~= false + for i = 2, #chunks do + local c = chunks[i] + if c.id == "ANIM" then + if c.size < 6 then + return nil, Err.new(Err.TRUNCATED, "ANIM chunk too small", c.off) + end + bg = buffer.readu32(buf, c.off) + loops = buffer.readu16(buf, c.off + 4) + haveAnim = true + elseif c.id == "ANMF" then + if not haveAnim then + return corrupt("ANMF before ANIM", c.off) + end + if c.size < 16 then + return nil, Err.new(Err.TRUNCATED, "ANMF chunk too small", c.off) + end + local fx = u24(buf, c.off) * 2 + local fy = u24(buf, c.off + 3) * 2 + local fw = u24(buf, c.off + 6) + 1 + local fh = u24(buf, c.off + 9) + 1 + local dur = u24(buf, c.off + 12) + local fl = readu8(buf, c.off + 15) + if fx + fw > cw or fy + fh > ch then + return corrupt("frame " .. (#frames + 1) .. " lies outside the canvas", c.off) + end + local sub, serr = subChunks(file, c) + if not sub then + return nil, serr + end + local img, alph = findImage(sub, 1) + if not img then + return corrupt("frame " .. (#frames + 1) .. " has no image data", c.off) + end + local bs, err = decodeBitstream(buf, img, if img.id == "VP8 " then alph else nil, o, false) + if not bs then + return nil, err + end + if bs.w ~= fw or bs.h ~= fh then + return corrupt(string.format("frame %d: image %d x %d does not match its ANMF size %d x %d", #frames + 1, bs.w, bs.h, fw, fh), c.off) + end + table.insert(frames, { + rgba = bs.rgba :: buffer, + x = fx, + y = fy, + w = fw, + h = fh, + blend = bit32.band(fl, 2) == 0, + disposeBg = bit32.band(fl, 1) == 1, + hasAlpha = bs.hasAlpha, + }) + bs.source.hasAlpha = bs.hasAlpha + table.insert(sources, bs.source) + table.insert(delays, dur) + if not wantAll then + break + end + end + end + if #frames == 0 then + return corrupt("animation without frames") + end + local canvases = Anim.coalesce(cw, ch, frames) + local img = Types.Image.new(cw, ch, "rgba8") + img.pixels = canvases[1] + img.loops = loops + for k, v in meta do + img.meta[k] = v + end + img.meta.background = { bit32.band(bit32.rshift(bg, 16), 255), bit32.band(bit32.rshift(bg, 8), 255), bit32.band(bg, 255), bit32.rshift(bg, 24) } + img.meta.source = { format = "webp", bitDepth = 8, extended = true, flags = flags, animated = true, codec = sources[1].codec, lossless = sources[1].lossless } + if wantAll then + local list: { Types.Frame } = {} + for i, f in frames do + local fi: Types.Image + if o.coalesce then + fi = Types.Image.new(cw, ch, "rgba8") + fi.pixels = canvases[i] + else + fi = Types.Image.new(f.w, f.h, "rgba8") + fi.pixels = f.rgba + end + fi.meta.source = sources[i] + fi.meta.duration = delays[i] + list[i] = { + image = fi, + delay = delays[i] / 1000, + x = if o.coalesce then 0 else f.x, + y = if o.coalesce then 0 else f.y, + dispose = if not o.coalesce and f.disposeBg then "background" else "none", + blend = if not o.coalesce and f.blend then "over" else "source", + } + end + img.frames = list + end + return img, nil +end + +function Webp.info(r: Bytes.Reader): (any, Err.Err?) + local chunks, cerr = readChunks(r) + if not chunks then + return nil, cerr + end + local first = chunks[1] + if not first then + return corrupt("no chunks") + end + local buf = r.buf + if first.id == "VP8X" and first.size >= 10 then + local flags = readu8(buf, first.off) + local n = 0 + for _, c in chunks do + if c.id == "ANMF" then + n += 1 + end + end + return { + width = u24(buf, first.off + 4) + 1, + height = u24(buf, first.off + 7) + 1, + animated = bit32.band(flags, FLAG_ANIM) ~= 0, + alpha = bit32.band(flags, FLAG_ALPHA) ~= 0, + frames = if n > 0 then n else 1, + }, nil + elseif first.id == "VP8L" then + local i, err = Vp8L.info(buf, first.off, first.size) + if not i then + return nil, err + end + return { width = i.width, height = i.height, animated = false, alpha = i.alpha, lossless = true, frames = 1 }, nil + elseif first.id == "VP8 " then + local h, err = Vp8.info(buf, first.off, first.size) + if not h then + return nil, err + end + return { width = h.width, height = h.height, animated = false, alpha = false, lossless = false, frames = 1 }, nil + end + return corrupt("the first chunk is '" .. first.id .. "', not VP8, VP8L or VP8X") +end + +-- ------------------------------------------------------------------------------------------------ encode +local function hasAlpha(px: buffer, n: number): boolean + for i = 0, n - 1 do + if readu8(px, i * 4 + 3) ~= 255 then + return true + end + end + return false +end + +local function validImage(img: any): boolean + return type(img) == "table" and img.format == "rgba8" and type(img.pixels) == "buffer" and type(img.width) == "number" and type(img.height) == "number" and img.width >= 1 and img.height >= 1 and img.width <= 16384 and img.height <= 16384 and img.width % 1 == 0 and img.height % 1 == 0 and buffer.len(img.pixels) >= img.width * img.height * 4 +end + +local function vp8x(flags: number, w: number, h: number): buffer + local b = Bytes.writer(10) + b:u8(flags) + b:u24le(0) + b:u24le(w - 1) + b:u24le(h - 1) + return b:finish() +end + +local function metaChunk(meta: any, key: string): buffer? + local v = meta and meta[key] + if type(v) == "buffer" and buffer.len(v) > 0 then + return v + elseif type(v) == "string" and #v > 0 then + return buffer.fromstring(v) + end + return nil +end + +function Webp.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + if o.lossless == false then + return nil, Err.new(Err.UNSUPPORTED, "lossy WebP encoding is not supported (use lossless)") + end + if not validImage(img) then + return nil, Err.new(Err.ARG, "needs an rgba8 Image (1..16384 pixels a side)") + end + local effort = o.effort or 5 + if type(effort) ~= "number" or effort < 0 or effort > 9 then + return nil, Err.new(Err.ARG, "effort must be 0..9") + end + local vopts: Vp8L.EncodeOptions = { effort = effort, exact = o.exact } + local w, h = img.width, img.height + local icc, exif, xmp = metaChunk(img.meta, "icc"), metaChunk(img.meta, "exif"), metaChunk(img.meta, "xmp") + local frames = img.frames + local body = Riff.writer("WEBP", { rf64 = false }) + + if not frames or #frames == 0 then + local bits, err = Vp8L.encode(img.pixels, w, h, vopts) + if not bits then + return nil, err + end + if icc or exif or xmp then + local flags = (if icc then FLAG_ICC else 0) + (if exif then FLAG_EXIF else 0) + (if xmp then FLAG_XMP else 0) + if hasAlpha(img.pixels, w * h) then + flags += FLAG_ALPHA + end + body:chunk("VP8X", vp8x(flags, w, h)) + if icc then + body:chunk("ICCP", icc) + end + body:chunk("VP8L", bits) + if exif then + body:chunk("EXIF", exif) + end + if xmp then + body:chunk("XMP ", xmp) + end + else + body:chunk("VP8L", bits) + end + return body:finish() + end + + -- animation: frames as they are when WebP can store them (even offsets, dispose none / background), else every + -- frame flattened to a full canvas + local list: { Anim.Frame } = {} + local direct = true + for i, f in frames do + if type(f) ~= "table" or not validImage(f.image) then + return nil, Err.new(Err.ARG, "frame " .. i .. ": needs an rgba8 image") + end + local fx, fy = f.x or 0, f.y or 0 + local fw, fh = f.image.width, f.image.height + if type(fx) ~= "number" or type(fy) ~= "number" or fx < 0 or fy < 0 or fx % 1 ~= 0 or fy % 1 ~= 0 or fx + fw > w or fy + fh > h then + return nil, Err.new(Err.ARG, "frame " .. i .. ": rectangle outside the canvas") + end + local dispose = f.dispose or "none" + if dispose ~= "none" and dispose ~= "background" and dispose ~= "previous" then + return nil, Err.new(Err.ARG, "frame " .. i .. ": bad dispose " .. tostring(dispose)) + end + if dispose == "previous" or fx % 2 == 1 or fy % 2 == 1 then + direct = false + end + table.insert(list, { + rgba = f.image.pixels, + x = fx, + y = fy, + w = fw, + h = fh, + blend = f.blend == "over", + disposeBg = dispose == "background", + disposePrev = dispose == "previous", + hasAlpha = true, + }) + end + if not direct then + local canvases = Anim.composite(w, h, list) + for i, c in canvases do + list[i] = { rgba = c, x = 0, y = 0, w = w, h = h, blend = false, disposeBg = false, hasAlpha = true } + end + end + local anyAlpha = false + for _, f in list do + if hasAlpha(f.rgba, f.w * f.h) then + anyAlpha = true + break + end + end + local flags = FLAG_ANIM + (if anyAlpha then FLAG_ALPHA else 0) + (if icc then FLAG_ICC else 0) + (if exif then FLAG_EXIF else 0) + (if xmp then FLAG_XMP else 0) + body:chunk("VP8X", vp8x(flags, w, h)) + if icc then + body:chunk("ICCP", icc) + end + local loops = o.loops or img.loops or 0 + if type(loops) ~= "number" or loops < 0 or loops > 65535 then + return nil, Err.new(Err.ARG, "loops must be 0..65535") + end + local bgc = o.background or (img.meta and img.meta.background) or { 0, 0, 0, 0 } + if type(bgc) ~= "table" then + return nil, Err.new(Err.ARG, "background must be { r, g, b, a }") + end + for k = 1, 4 do + local v = bgc[k] + if v ~= nil and (type(v) ~= "number" or v < 0 or v > 255 or v % 1 ~= 0) then + return nil, Err.new(Err.ARG, "background must be { r, g, b, a } with 0..255 integers") + end + end + local anim = buffer.create(6) + -- the background colour is stored as B, G, R, A + buffer.writeu8(anim, 0, bgc[3] or 0) + buffer.writeu8(anim, 1, bgc[2] or 0) + buffer.writeu8(anim, 2, bgc[1] or 0) + buffer.writeu8(anim, 3, bgc[4] or 0) + buffer.writeu16(anim, 4, loops) + body:chunk("ANIM", anim) + for i, f in list do + local bits, err = Vp8L.encode(f.rgba, f.w, f.h, vopts) + if not bits then + return nil, err + end + local delay = frames[i].delay + local ms = if type(delay) == "number" and delay == delay then math.clamp(math.floor(delay * 1000 + 0.5), 0, 0xffffff) else 100 + local hdr = Bytes.writer(16 + buffer.len(bits) + 9) + hdr:u24le(f.x // 2) + hdr:u24le(f.y // 2) + hdr:u24le(f.w - 1) + hdr:u24le(f.h - 1) + hdr:u24le(ms) + hdr:u8((if f.blend then 0 else 2) + (if f.disposeBg then 1 else 0)) + local nb = buffer.len(bits) + hdr:string("VP8L") + hdr:u32le(nb) + hdr:bytes(bits) + if nb % 2 == 1 then + hdr:u8(0) + end + body:chunk("ANMF", hdr.buf, 0, hdr:tell()) + end + if exif then + body:chunk("EXIF", exif) + end + if xmp then + body:chunk("XMP ", xmp) + end + return body:finish() +end + +-- ------------------------------------------------------------------------------------------------ extras +function Webp.coalesce(img: Types.Image): { buffer }? + if type(img) ~= "table" or type(img.frames) ~= "table" or type(img.width) ~= "number" or type(img.height) ~= "number" then + return nil + end + local list: { Anim.Frame } = {} + for _, f in img.frames :: { Types.Frame } do + if type(f) ~= "table" or not validImage(f.image) or type(f.x) ~= "number" or type(f.y) ~= "number" or f.x < 0 or f.y < 0 or f.x % 1 ~= 0 or f.y % 1 ~= 0 or f.x + f.image.width > img.width or f.y + f.image.height > img.height then + return nil + end + table.insert(list, { + rgba = f.image.pixels, + x = f.x, + y = f.y, + w = f.image.width, + h = f.image.height, + blend = f.blend == "over", + disposeBg = f.dispose == "background", + hasAlpha = not (f.image.meta.source and f.image.meta.source.hasAlpha == false), + }) + end + return Anim.coalesce(img.width, img.height, list) +end + +return Webp +end +__FILES["image/webp/Alpha"] = @native function() + + +-- image/webp/Alpha: the ALPH chunk (RFC 9649 section 2.7.1.2); unfilters of libwebp src/dsp/filters.c (BSD-3-Clause, +-- licenses/libwebp-LICENSE.txt). +local Vp8L = __include("codecs/image/Vp8L") + +local readu8, writeu8 = buffer.readu8, buffer.writeu8 + +local Alpha = {} + +@native local function unfilter(a: buffer, w: number, h: number, filter: number) + if filter == 0 then + return + end + for y = 0, h - 1 do + local row = y * w + local prev = row - w + if y == 0 or filter == 1 then + -- horizontal (also the first row of the other filters): the left pixel, the first one from above + local pred = if y == 0 then 0 else readu8(a, prev) + for i = row, row + w - 1 do + pred = (pred + readu8(a, i)) % 256 + writeu8(a, i, pred) + end + elseif filter == 2 then + for i = 0, w - 1 do + writeu8(a, row + i, (readu8(a, prev + i) + readu8(a, row + i)) % 256) + end + else + local top = readu8(a, prev) + local topLeft, left = top, top + for i = 0, w - 1 do + top = readu8(a, prev + i) + local g = left + top - topLeft + g = if g < 0 then 0 elseif g > 255 then 255 else g + left = (readu8(a, row + i) + g) % 256 + topLeft = top + writeu8(a, row + i, left) + end + end + end +end + +@native function Alpha.decode(buf: buffer, off: number, len: number, w: number, h: number): (buffer?, any) + if len <= 1 then + return nil, "truncated: ALPH chunk" + end + local hb = readu8(buf, off) + local method = hb % 4 + local filter = (hb // 4) % 4 + local pre = (hb // 16) % 4 + if method > 1 or pre > 1 or hb >= 64 then + return nil, "bad ALPH header" + end + local a: buffer + if method == 0 then + if len - 1 < w * h then + return nil, "truncated: raw alpha" + end + a = buffer.create(w * h) + buffer.copy(a, 0, buf, off + 1, w * h) + else + local d, err = Vp8L.decodeAlpha(buf, off + 1, len - 1, w, h) + if not d then + local e = err :: any + return nil, if e.code == "TRUNCATED" then "truncated: alpha " .. e.message else "alpha: " .. e.message + end + a = d + end + unfilter(a, w, h, filter) + return a, { method = method, filter = filter, preprocessing = pre } +end + +return Alpha +end +__FILES["image/webp/Anim"] = @native function() + + +-- image/webp/Anim: WebP animation compositing; coalesce() matches libwebp's WebPAnimDecoder (src/demux/anim_decode.c, +-- BSD-3-Clause, licenses/libwebp-LICENSE.txt): the background colour is ignored, as the spec recommends. +local band, rshift = bit32.band, bit32.rshift +local readu32, writeu32 = buffer.readu32, buffer.writeu32 +local bcreate, bcopy, bfill = buffer.create, buffer.copy, buffer.fill + +local Anim = {} + +type Frame = { + rgba: buffer, + x: number, + y: number, + w: number, + h: number, + blend: boolean, + disposeBg: boolean, + disposePrev: boolean?, -- composite() only + hasAlpha: boolean, +} + +-- non-premultiplied 0xAABBGGRR, as libwebp BlendPixelNonPremult +@native local function blendPixel(src: number, dst: number): number + local sa = rshift(src, 24) + if sa == 0 then + return dst + end + local da = rshift(dst, 24) + local dfa = rshift(da * (256 - sa), 8) + local ba = sa + dfa + local scale = 16777216 // ba + local r = ((band(src, 255) * sa + band(dst, 255) * dfa) * scale) // 16777216 + local g = ((band(rshift(src, 8), 255) * sa + band(rshift(dst, 8), 255) * dfa) * scale) // 16777216 + local b = ((band(rshift(src, 16), 255) * sa + band(rshift(dst, 16), 255) * dfa) * scale) // 16777216 + return r + g * 256 + b * 65536 + ba * 16777216 +end +Anim.blendPixel = blendPixel + +@native local function blendRow(cur: buffer, prev: buffer, o: number, n: number) + for i = o, o + n - 1 do + local s = readu32(cur, i * 4) + if s < 0xff000000 then + writeu32(cur, i * 4, blendPixel(s, readu32(prev, i * 4))) + end + end +end + +@native local function draw(canvas: buffer, cw: number, f: Frame) + for j = 0, f.h - 1 do + bcopy(canvas, ((f.y + j) * cw + f.x) * 4, f.rgba, j * f.w * 4, f.w * 4) + end +end + +@native local function clearRect(canvas: buffer, cw: number, x: number, y: number, w: number, h: number) + for j = 0, h - 1 do + bfill(canvas, ((y + j) * cw + x) * 4, 0, w * 4) + end +end + +@native function Anim.coalesce(cw: number, ch: number, frames: { Frame }): { buffer } + local size = cw * ch * 4 + local out: { buffer } = {} + local disposed = bcreate(size) + local prev: Frame? = nil + local prevKey = false + for n, f in frames do + local full = f.w == cw and f.h == ch + local key + if n == 1 then + key = true + elseif (not f.hasAlpha or not f.blend) and full then + key = true + else + local p = prev :: Frame + key = p.disposeBg and ((p.w == cw and p.h == ch) or prevKey) + end + local cur = bcreate(size) + if not key then + bcopy(cur, 0, disposed, 0, size) + end + draw(cur, cw, f) + if n > 1 and f.blend and not key then + local p = prev :: Frame + if not p.disposeBg then + for j = 0, f.h - 1 do + blendRow(cur, disposed, (f.y + j) * cw + f.x, f.w) + end + else + -- the previous rectangle was cleared: blending with transparent there is a no-op for libwebp + local pmx, pmy = p.x + p.w, p.y + p.h + local smx = f.x + f.w + for j = 0, f.h - 1 do + local cy = f.y + j + if cy < p.y or cy >= pmy or f.x >= pmx or smx <= p.x then + blendRow(cur, disposed, cy * cw + f.x, f.w) + else + if f.x < p.x then + blendRow(cur, disposed, cy * cw + f.x, p.x - f.x) + end + if smx > pmx then + blendRow(cur, disposed, cy * cw + pmx, smx - pmx) + end + end + end + end + end + table.insert(out, cur) + prev = f + prevKey = key + bcopy(disposed, 0, cur, 0, size) + if f.disposeBg then + clearRect(disposed, cw, f.x, f.y, f.w, f.h) + end + end + return out +end + +@native function Anim.composite(cw: number, ch: number, frames: { Frame }): { buffer } + local size = cw * ch * 4 + local canvas = bcreate(size) + local out: { buffer } = {} + for _, f in frames do + local saved: buffer? = nil + if f.disposePrev then + saved = bcreate(size) + bcopy(saved :: buffer, 0, canvas, 0, size) + end + if f.blend then + for j = 0, f.h - 1 do + local co = (f.y + j) * cw + f.x + for i = 0, f.w - 1 do + local s = readu32(f.rgba, (j * f.w + i) * 4) + local d = readu32(canvas, (co + i) * 4) + writeu32(canvas, (co + i) * 4, if s >= 0xff000000 or d < 0x01000000 then s else blendPixel(s, d)) + end + end + else + draw(canvas, cw, f) + end + local shown = bcreate(size) + bcopy(shown, 0, canvas, 0, size) + table.insert(out, shown) + if saved then + canvas = saved + elseif f.disposeBg then + clearRect(canvas, cw, f.x, f.y, f.w, f.h) + end + end + return out +end + +return Anim +end +__FILES["image/xbm"] = function() + +-- image/xbm: X BitMap (X11 bitmap(1) C source; X10 16-bit variant). Supports: _width / _height / _x_hot / _y_hot +-- defines, char / short arrays in hex, decimal or octal, LSB first, set bits black; writes X11 format. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Sniff = __include("core/Sniff") +local Types = __include("Types") + +-- ------------------------------------------------------------------------------------------------ contract +local Xbm = { + name = "xbm", + category = "image", + extensions = { "xbm", "bm" }, + mime = { "image/x-xbitmap", "image/x-xbm" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" }, + caps = { decode = true, encode = true, depths = { 1 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + transparent: boolean?, -- default false: white + maxPixels: number?, -- default 2^26 +} +type EncodeOptions = { + name: string?, -- default "image" + threshold: number?, -- default 128 +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Xbm.sniff(r: Bytes.Reader): number + local s = Sniff.text(r, 256, true) + if string.match(s, "^#define%s+[%w_]*_?width%s+%d+") or string.match(s, "^/%*.-%*/%s*#define%s+[%w_]*width%s+%d+") then + return 0.9 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Xbm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local n = r.limit - r.base + if n > 2 ^ 26 then + return nil, Err.new(Err.LIMIT, "file too large") + end + local s = buffer.readstring(r.buf, r.base, n) + local w = tonumber(string.match(s, "#define%s+[%w_]-_?width%s+(%d+)")) + local h = tonumber(string.match(s, "#define%s+[%w_]-_?height%s+(%d+)")) + if not w or not h or w < 1 or h < 1 then + return nil, Err.new(Err.CORRUPT, "missing width / height defines") + end + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + if w * h > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels)) + end + local brace = string.find(s, "{", 1, true) + if not brace then + return nil, Err.new(Err.CORRUPT, "missing bits array") + end + local decl = string.sub(s, 1, brace) + local short = string.find(decl, "short", 1, true) ~= nil + local unit = if short then 16 else 8 + local per = (w + unit - 1) // unit + local want = per * h + local img = Types.Image.new(w, h, "rgba8") + local px = img.pixels + local clear = if opts and opts.transparent then 0x00FFFFFF else 0xFFFFFFFF + local got = 0 + local body = string.gsub(string.sub(s, brace + 1), "/%*.-%*/", " ") + for tok in string.gmatch(body, "[%w]+") do + if got >= want then + break + end + local v + if string.match(tok, "^0[xX]%x+$") then + v = tonumber(string.sub(tok, 3), 16) + elseif string.match(tok, "^0%d+$") then + v = tonumber(tok, 8) + elseif string.match(tok, "^%d+$") then + v = tonumber(tok) + end + if v then + local y, cx = got // per, (got % per) * unit + for k = 0, unit - 1 do + local x = cx + k + if x < w then + buffer.writeu32(px, (y * w + x) * 4, if bit32.band(bit32.rshift(v, k), 1) == 1 then 0xFF000000 else clear) + end + end + got += 1 + end + end + if got < want then + for i = got * unit, want * unit - 1 do + local y, x = i // (per * unit), i % (per * unit) + if x < w then + buffer.writeu32(px, (y * w + x) * 4, clear) + end + end + img.meta.truncated = true + end + local hx = tonumber(string.match(s, "#define%s+[%w_]-_?x_hot%s+(%d+)")) + local hy = tonumber(string.match(s, "#define%s+[%w_]-_?y_hot%s+(%d+)")) + if hx and hy then + img.meta.hotspot = { x = hx, y = hy } + end + local name = string.match(s, "#define%s+([%w_]-)_?width%s") + img.meta.source = { format = "xbm", bitDepth = 1, name = name, x10 = short } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Xbm.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "needs an rgba8 Image") + end + local w, h = img.width, img.height + if w < 1 or h < 1 then + return nil, Err.new(Err.ARG, "bad size") + end + local name = string.gsub(string.gsub(opts and opts.name or "image", "%.[^.]*$", ""), "[^%w_]", "_") + if name == "" or string.match(name, "^%d") then + name = "_" .. name + end + local th = opts and opts.threshold or 128 + local px = img.pixels + local parts = { + string.format("#define %s_width %d\n#define %s_height %d\n", name, w, name, h), + } + local hs: { x: number, y: number }? = img.meta and img.meta.hotspot + if hs then + table.insert(parts, string.format("#define %s_x_hot %d\n#define %s_y_hot %d\n", name, hs.x, name, hs.y)) + end + table.insert(parts, string.format("static unsigned char %s_bits[] = {\n", name)) + local per = (w + 7) // 8 + local bytes = {} + for y = 0, h - 1 do + for bx = 0, per - 1 do + local v = 0 + for k = 0, 7 do + local x = bx * 8 + k + if x < w then + local o = (y * w + x) * 4 + local lum = 0.299 * buffer.readu8(px, o) + 0.587 * buffer.readu8(px, o + 1) + 0.114 * buffer.readu8(px, o + 2) + if lum < th and buffer.readu8(px, o + 3) >= 128 then + v += bit32.lshift(1, k) + end + end + end + table.insert(bytes, string.format("0x%02x", v)) + end + end + for i = 1, #bytes, 12 do + table.insert(parts, " " .. table.concat(bytes, ", ", i, math.min(i + 11, #bytes)) .. (if i + 11 < #bytes then ",\n" else " };\n")) + end + return buffer.fromstring(table.concat(parts)), nil +end + +return Xbm +end +__FILES["image/xpm"] = function() + +-- image/xpm: X PixMap (XPM 3 C source and XPM 2 plain; Arnaud Le Hors's "XPM Manual"). Supports: the values line and +-- hotspot, c / g / g4 / m / s keys (c preferred, then g, g4, m), #RGB .. #RRRRGGGGBBBB, None, colour names (unknown: +-- black); writes XPM 3 with hex colours. Not supported: the extensions section (skipped). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Sniff = __include("core/Sniff") +local Types = __include("Types") +local Names = __include("image/xpm/Names") + +-- ------------------------------------------------------------------------------------------------ contract +local Xpm = { + name = "xpm", + category = "image", + extensions = { "xpm", "pm" }, + mime = { "image/x-xpixmap", "image/x-xpm" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" }, + caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 8 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + maxPixels: number?, -- default 2^26 +} +type EncodeOptions = { + name: string?, -- default "image" +} + +-- the characters of pixel codes (printable ASCII without '"' and '\') +local CODE_CHARS = " .XoO+@#$%&*=-;:>,<1234567890qwertyuipasdfghjklzxcvbnmMNBVCZASDFGHJKLPIUYTREWQ!~^/()_`'][{}|" + +-- ------------------------------------------------------------------------------------------------ sniff +function Xpm.sniff(r: Bytes.Reader): number + local s = Sniff.text(r, 64, true) + if string.sub(s, 1, 9) == "/* XPM */" or string.sub(s, 1, 6) == "! XPM2" then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function colour(v: string): number? + local l = string.lower(v) + if l == "none" or l == "transparent" then + return 0 + end + if string.sub(v, 1, 1) == "#" then + local hex = string.sub(v, 2) + local n = #hex + if n % 3 ~= 0 or n == 0 or n > 12 or not string.match(hex, "^%x+$") then + return nil + end + local k = n // 3 + local mx = 16 ^ k - 1 + local c = 0 + for i = 0, 2 do + local x = tonumber(string.sub(hex, i * k + 1, i * k + k), 16) :: number + c += math.floor(x * 255 / mx + 0.5) * 256 ^ i + end + return c + 0xFF000000 + end + local rgb = Names.lookup(l) + return if rgb then rgb + 0xFF000000 else nil +end + +local function strings(s: string): { string } + local out = {} + if string.sub(Sniff.dropBom(s), 1, 6) == "! XPM2" then + local first = true + for line in string.gmatch(s, "[^\n]+") do + if first then + first = false + else + table.insert(out, (string.gsub(line, "\r$", ""))) + end + end + return out + end + local i, n = 1, #s + while i <= n do + local c = string.sub(s, i, i) + if c == "/" and string.sub(s, i + 1, i + 1) == "*" then + local e = string.find(s, "*/", i + 2, true) + i = if e then e + 2 else n + 1 + elseif c == '"' then + local parts = {} + local j = i + 1 + while j <= n do + local d = string.sub(s, j, j) + if d == "\\" then + table.insert(parts, string.sub(s, j + 1, j + 1)) + j += 2 + elseif d == '"' then + break + else + local e = string.find(s, '["\\]', j) + local stop = (e or n + 1) - 1 + table.insert(parts, string.sub(s, j, stop)) + j = stop + 1 + end + end + table.insert(out, table.concat(parts)) + i = j + 1 + else + i += 1 + end + end + return out +end + +local KEYS = { c = true, m = true, g4 = true, g = true, s = true } + +function Xpm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local n = r.limit - r.base + if n > 2 ^ 27 then + return nil, Err.new(Err.LIMIT, "file too large") + end + local list = strings(buffer.readstring(r.buf, r.base, n)) + if #list == 0 then + return nil, Err.new(Err.CORRUPT, "no XPM strings") + end + local vals: { number } = {} + for tok in string.gmatch(list[1], "%S+") do + table.insert(vals, tonumber(tok) or -1) + end + local w: number, h: number, nc: number, cpp: number = vals[1] or -1, vals[2] or -1, vals[3] or -1, vals[4] or -1 + if w < 1 or h < 1 or nc < 1 or cpp < 1 or cpp > 8 or w % 1 ~= 0 or h % 1 ~= 0 then + return nil, Err.new(Err.CORRUPT, "bad values line") + end + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + if w * h > maxPixels or nc > 2 ^ 24 then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels)) + end + if #list < 1 + nc then + return nil, Err.new(Err.TRUNCATED, "colour table runs past the end") + end + local map: { [string]: number } = {} + local unknown: { string } = {} + local palette: { { number } } = {} + for i = 1, nc do + local line = list[1 + i] + local code = string.sub(line, 1, cpp) + local rest = string.sub(line, cpp + 1) + local found: { [string]: string } = {} + local key: string? = nil + local acc = {} + for tok in string.gmatch(rest, "%S+") do + if KEYS[tok] and (key == nil or #acc > 0) then + if key then + found[key] = table.concat(acc, " ") + end + key, acc = tok, {} + else + table.insert(acc, tok) + end + end + if key then + found[key] = table.concat(acc, " ") + end + local v = found.c or found.g or found.g4 or found.m + local c = if v then colour(v) else nil + if v and not c then + c = colour((string.gsub(v, " ", ""))) + end + local cv: number = c or 0xFF000000 + if not c then + table.insert(unknown, v or "") + end + c = cv + map[code] = cv + palette[i] = { bit32.band(cv, 255), bit32.band(bit32.rshift(cv, 8), 255), bit32.band(bit32.rshift(cv, 16), 255), bit32.rshift(cv, 24) } + end + local img = Types.Image.new(w, h, "rgba8") + local px = img.pixels + local truncated = false + for y = 0, h - 1 do + local row = list[2 + nc + y] + if not row then + truncated = true + break + end + for x = 0, w - 1 do + local c = map[string.sub(row, x * cpp + 1, x * cpp + cpp)] + buffer.writeu32(px, (y * w + x) * 4, c or 0) + end + end + if #vals >= 6 and vals[5] >= 0 and vals[6] >= 0 then + img.meta.hotspot = { x = vals[5], y = vals[6] } + end + if #unknown > 0 then + img.meta.unknownColours = unknown + end + if truncated then + img.meta.truncated = true + end + img.meta.palette = palette + img.meta.source = { format = "xpm", colours = nc, charsPerPixel = cpp } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Xpm.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "needs an rgba8 Image") + end + local w, h = img.width, img.height + if w < 1 or h < 1 then + return nil, Err.new(Err.ARG, "bad size") + end + local name = string.gsub(string.gsub(opts and opts.name or "image", "%.[^.]*$", ""), "[^%w_]", "_") + if name == "" or string.match(name, "^%d") then + name = "_" .. name + end + local px = img.pixels + local index: { [number]: number } = {} + local order: { number } = {} + local keys = table.create(w * h, 0) + for i = 0, w * h - 1 do + local v = buffer.readu32(px, i * 4) + local k = if v < 0x80000000 then -1 else bit32.band(v, 0xFFFFFF) + if not index[k] then + table.insert(order, k) + index[k] = #order + end + keys[i + 1] = index[k] + end + local nchars = #CODE_CHARS + local cpp = 1 + while nchars ^ cpp < #order do + cpp += 1 + end + local codes: { string } = {} + for i = 1, #order do + local v, s = i - 1, "" + for _ = 1, cpp do + local d = v % nchars + s ..= string.sub(CODE_CHARS, d + 1, d + 1) + v //= nchars + end + codes[i] = s + end + local parts = { "/* XPM */\n", string.format("static char *%s[] = {\n", name) } + local hs: { x: number, y: number }? = img.meta and img.meta.hotspot + if hs then + table.insert(parts, string.format('"%d %d %d %d %d %d",\n', w, h, #order, cpp, hs.x, hs.y)) + else + table.insert(parts, string.format('"%d %d %d %d",\n', w, h, #order, cpp)) + end + for i, k in order do + local col = if k < 0 then "None" else string.format("#%02X%02X%02X", bit32.band(k, 255), bit32.band(bit32.rshift(k, 8), 255), bit32.rshift(k, 16)) + table.insert(parts, string.format('"%s c %s",\n', codes[i], col)) + end + for y = 0, h - 1 do + local row = table.create(w, "") + for x = 0, w - 1 do + row[x + 1] = codes[keys[y * w + x + 1]] + end + table.insert(parts, '"' .. table.concat(row) .. '"' .. (if y < h - 1 then ",\n" else "\n")) + end + table.insert(parts, "};\n") + return buffer.fromstring(table.concat(parts)), nil +end + +return Xpm +end +__FILES["image/xpm/Names"] = function() + +-- image/xpm/Names: CSS Color 4 named colours with X11's values where they differ, and grey0 .. grey100. +local Names = {} + +local HEX: { [string]: number } = { + aliceblue = 0xF0F8FF, antiquewhite = 0xFAEBD7, aqua = 0x00FFFF, aquamarine = 0x7FFFD4, azure = 0xF0FFFF, + beige = 0xF5F5DC, bisque = 0xFFE4C4, black = 0x000000, blanchedalmond = 0xFFEBCD, blue = 0x0000FF, + blueviolet = 0x8A2BE2, brown = 0xA52A2A, burlywood = 0xDEB887, cadetblue = 0x5F9EA0, chartreuse = 0x7FFF00, + chocolate = 0xD2691E, coral = 0xFF7F50, cornflowerblue = 0x6495ED, cornsilk = 0xFFF8DC, crimson = 0xDC143C, + cyan = 0x00FFFF, darkblue = 0x00008B, darkcyan = 0x008B8B, darkgoldenrod = 0xB8860B, darkgray = 0xA9A9A9, + darkgreen = 0x006400, darkgrey = 0xA9A9A9, darkkhaki = 0xBDB76B, darkmagenta = 0x8B008B, darkolivegreen = 0x556B2F, + darkorange = 0xFF8C00, darkorchid = 0x9932CC, darkred = 0x8B0000, darksalmon = 0xE9967A, darkseagreen = 0x8FBC8F, + darkslateblue = 0x483D8B, darkslategray = 0x2F4F4F, darkslategrey = 0x2F4F4F, darkturquoise = 0x00CED1, + darkviolet = 0x9400D3, deeppink = 0xFF1493, deepskyblue = 0x00BFFF, dimgray = 0x696969, dimgrey = 0x696969, + dodgerblue = 0x1E90FF, firebrick = 0xB22222, floralwhite = 0xFFFAF0, forestgreen = 0x228B22, fuchsia = 0xFF00FF, + gainsboro = 0xDCDCDC, ghostwhite = 0xF8F8FF, gold = 0xFFD700, goldenrod = 0xDAA520, gray = 0xBEBEBE, + green = 0x00FF00, greenyellow = 0xADFF2F, grey = 0xBEBEBE, honeydew = 0xF0FFF0, hotpink = 0xFF69B4, + indianred = 0xCD5C5C, indigo = 0x4B0082, ivory = 0xFFFFF0, khaki = 0xF0E68C, lavender = 0xE6E6FA, + lavenderblush = 0xFFF0F5, lawngreen = 0x7CFC00, lemonchiffon = 0xFFFACD, lightblue = 0xADD8E6, lightcoral = 0xF08080, + lightcyan = 0xE0FFFF, lightgoldenrodyellow = 0xFAFAD2, lightgray = 0xD3D3D3, lightgreen = 0x90EE90, + lightgrey = 0xD3D3D3, lightpink = 0xFFB6C1, lightsalmon = 0xFFA07A, lightseagreen = 0x20B2AA, lightskyblue = 0x87CEFA, + lightslategray = 0x778899, lightslategrey = 0x778899, lightsteelblue = 0xB0C4DE, lightyellow = 0xFFFFE0, + lime = 0x00FF00, limegreen = 0x32CD32, linen = 0xFAF0E6, magenta = 0xFF00FF, maroon = 0xB03060, + mediumaquamarine = 0x66CDAA, mediumblue = 0x0000CD, mediumorchid = 0xBA55D3, mediumpurple = 0x9370DB, + mediumseagreen = 0x3CB371, mediumslateblue = 0x7B68EE, mediumspringgreen = 0x00FA9A, mediumturquoise = 0x48D1CC, + mediumvioletred = 0xC71585, midnightblue = 0x191970, mintcream = 0xF5FFFA, mistyrose = 0xFFE4E1, moccasin = 0xFFE4B5, + navajowhite = 0xFFDEAD, navy = 0x000080, navyblue = 0x000080, oldlace = 0xFDF5E6, olive = 0x808000, olivedrab = 0x6B8E23, + orange = 0xFFA500, orangered = 0xFF4500, orchid = 0xDA70D6, palegoldenrod = 0xEEE8AA, palegreen = 0x98FB98, + paleturquoise = 0xAFEEEE, palevioletred = 0xDB7093, papayawhip = 0xFFEFD5, peachpuff = 0xFFDAB9, peru = 0xCD853F, + pink = 0xFFC0CB, plum = 0xDDA0DD, powderblue = 0xB0E0E6, purple = 0xA020F0, rebeccapurple = 0x663399, red = 0xFF0000, + rosybrown = 0xBC8F8F, royalblue = 0x4169E1, saddlebrown = 0x8B4513, salmon = 0xFA8072, sandybrown = 0xF4A460, + seagreen = 0x2E8B57, seashell = 0xFFF5EE, sienna = 0xA0522D, silver = 0xC0C0C0, skyblue = 0x87CEEB, + slateblue = 0x6A5ACD, slategray = 0x708090, slategrey = 0x708090, snow = 0xFFFAFA, springgreen = 0x00FF7F, + steelblue = 0x4682B4, tan = 0xD2B48C, teal = 0x008080, thistle = 0xD8BFD8, tomato = 0xFF6347, turquoise = 0x40E0D0, + violet = 0xEE82EE, wheat = 0xF5DEB3, white = 0xFFFFFF, whitesmoke = 0xF5F5F5, yellow = 0xFFFF00, yellowgreen = 0x9ACD32, +} + +function Names.lookup(name: string): number? + local v = HEX[name] + if v then + return bit32.rshift(v, 16) + bit32.band(v, 0xFF00) + bit32.band(v, 0xFF) * 65536 + end + local n = string.match(name, "^gr[ae]y(%d+)$") + if n then + local k = tonumber(n) :: number + if k <= 100 then + local g = math.floor(k * 255 / 100 + 0.49) + return g * 0x10101 + end + end + return nil +end + +return Names +end +end + + + + + + layered + --!optimize 2 +--!nocheck +-- rosetta chunk layered (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 4 modules (1 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["layered/aseprite"] = function() + +-- layered/aseprite: Aseprite .ase / .aseprite (aseprite docs/ase-file-specs.md, v1.3). Supports: RGBA / grayscale / +-- indexed, frames, layer tree (groups, blend, opacity), raw / zlib / linked cels, palettes (0x2019, 0x0004 / 0x0011), +-- tags, user data. Not supported: tilemaps / tilesets (meta.skipped), slices, external files, colour profiles (sRGB). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Deflate = __include("codecs/compress/Deflate") + +-- ------------------------------------------------------------------------------------------------ contract +local Aseprite = { + name = "aseprite", + category = "layered", + extensions = { "aseprite", "ase" }, + mime = { "image/x-aseprite" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Deflate" }, + caps = { decode = true, encode = true, layers = true, groups = true, animation = true, depths = { 8, 16, 32 } }, +} + +type DecodeOptions = { + maxPixels: number?, -- default 2^26 + maxFrames: number?, -- default 65535 +} +type EncodeOptions = { + depth: number?, -- 32, 16 or 8; default meta.colorDepth if the pixels fit, else 32 + level: number?, -- default 6 +} + +-- ------------------------------------------------------------------------------------------------ constants +local BLENDS = { [0] = "normal", "multiply", "screen", "overlay", "darken", "lighten", "colorDodge", "colorBurn", "hardLight", "softLight", "difference", "exclusion", "hue", "saturation", "color", "luminosity", "linearDodge", "subtract", "divide" } +local BLEND_IDS: { [string]: number } = {} +for k, v in BLENDS do + BLEND_IDS[v] = k +end +BLEND_IDS.add = 16 +BLEND_IDS.passThrough = 0 +local DIRECTIONS = { [0] = "forward", "reverse", "pingpong", "pingpongReverse" } +local DIRECTION_IDS = { forward = 0, reverse = 1, pingpong = 2, pingpongReverse = 3 } + +-- ------------------------------------------------------------------------------------------------ sniff +function Aseprite.sniff(r: Bytes.Reader): number + if r:peekU8(4) == 0xE0 and r:peekU8(5) == 0xA5 then + local d = r:peekU8(12) + if (d == 32 or d == 16 or d == 8) and r:peekU8(13) == 0 then + return 1 + end + return 0.5 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function str(r: Bytes.Reader): string + return r:string(r:u16le()) +end + +local function toRGBA(src: buffer, so: number, n: number, depth: number, palette: buffer, transparent: number, background: boolean): buffer + local out = buffer.create(n * 4) + if depth == 32 then + buffer.copy(out, 0, src, so, n * 4) + elseif depth == 16 then + for i = 0, n - 1 do + local v, a = buffer.readu8(src, so + i * 2), buffer.readu8(src, so + i * 2 + 1) + buffer.writeu32(out, i * 4, v + v * 256 + v * 65536 + a * 16777216) + end + else + for i = 0, n - 1 do + local k = buffer.readu8(src, so + i) + local c = buffer.readu32(palette, k * 4) + if k == transparent and not background then + c = 0 + end + buffer.writeu32(out, i * 4, c) + end + end + return out +end + +type LayerInfo = { name: string, flags: number, type: number, level: number, blend: number, opacity: number, userData: any? } + +function Aseprite.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Layered?, Err.Err?) + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + local maxFrames = opts and opts.maxFrames or 65535 + if r:size() < 128 then + return nil, Err.new(Err.TRUNCATED, "header needs 128 bytes", r.pos) + end + r:skip(4) + if r:u16le() ~= 0xA5E0 then + return nil, Err.new(Err.CORRUPT, "bad magic", r.pos - 2) + end + local nframes, w, h, depth = r:u16le(), r:u16le(), r:u16le(), r:u16le() + local hflags = r:u32le() + r:skip(2 + 8) + local transparent = r:u8() + r:skip(3) + local ncolors = r:u16le() + local pw, ph = r:u8(), r:u8() + local gx, gy, gw, gh = r:i16le(), r:i16le(), r:u16le(), r:u16le() + r:seek(128) + if depth ~= 32 and depth ~= 16 and depth ~= 8 then + return nil, Err.new(Err.CORRUPT, "bad colour depth " .. depth) + end + if w < 1 or h < 1 then + return nil, Err.new(Err.CORRUPT, "bad size") + end + if w * h > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the pixel limit", w, h)) + end + if nframes > maxFrames then + return nil, Err.new(Err.LIMIT, "too many frames") + end + local bpp = depth // 8 + local palette = buffer.create(1024) + local palList: { { number } } = {} + local palNames: { [number]: string } = {} + local infos: { LayerInfo } = {} + local tags: { any } = {} + local frames: { { cels: { [number]: any }, delay: number } } = {} + local skipped = 0 + local lastUser: any = nil + local tagUser = 0 + for fi = 1, nframes do + local fstart = r.pos + local fbytes = r:u32le() + local fmagic = r:u16le() + local oldChunks = r:u16le() + local duration = r:u16le() + r:skip(2) + local newChunks = r:u32le() + if r.err then + return nil, r.err + end + if fmagic ~= 0xF1FA then + return nil, Err.new(Err.CORRUPT, "frame " .. fi .. ": bad magic", fstart + 4) + end + if fbytes < 16 or fstart + fbytes > r.limit then + return nil, Err.new(Err.TRUNCATED, "frame " .. fi .. " runs past the end", fstart) + end + local nchunks = if newChunks ~= 0 then newChunks else oldChunks + local frame = { cels = {}, delay = duration / 1000 } + frames[fi] = frame + local fr = Bytes.reader(r.buf, r.pos, fstart + fbytes - r.pos) + for _ = 1, nchunks do + if fr:remaining() < 6 then + break + end + local cstart = fr.pos + local csize = fr:u32le() + local ctype = fr:u16le() + if csize < 6 or cstart + csize > fr.limit then + return nil, Err.new(Err.CORRUPT, string.format("frame %d: chunk 0x%04x size %d", fi, ctype, csize), cstart) + end + local c = Bytes.reader(fr.buf, cstart + 6, csize - 6) + fr.pos = cstart + csize + if ctype == 0x2004 then + local info: LayerInfo = { flags = c:u16le(), type = c:u16le(), level = c:u16le(), name = "", blend = 0, opacity = 255 } + c:skip(4) + info.blend = c:u16le() + info.opacity = c:u8() + c:skip(3) + info.name = str(c) + if c.err then + return nil, c.err + end + if info.type == 2 then + skipped += 1 + end + table.insert(infos, info) + lastUser = info + elseif ctype == 0x2005 then + local li = c:u16le() + local x, y = c:i16le(), c:i16le() + local op = c:u8() + local ctyp = c:u16le() + local z = c:i16le() + c:skip(5) + if c.err then + return nil, c.err + end + local cel: any = { x = x, y = y, opacity = op, z = z } + if ctyp == 0 or ctyp == 2 then + local cw, ch = c:u16le(), c:u16le() + if c.err then + return nil, c.err + end + if cw * ch > maxPixels then + return nil, Err.new(Err.LIMIT, "cel over the pixel limit") + end + local n = cw * ch + local raw: buffer, ro: number + if ctyp == 0 then + if not c:need(n * bpp) then + return nil, c.err + end + raw, ro = c.buf, c.pos + else + local z2, zerr = Deflate.zlib(c.buf, c.pos, c.limit - c.pos, n * bpp) + if not z2 then + -- some writers leave padding after the stream: inflate without the exact size + local loose = Deflate.zlib(c.buf, c.pos, c.limit - c.pos) + if not loose or buffer.len(loose) < n * bpp then + return nil, Err.new(Err.CORRUPT, "frame " .. fi .. ": cel data: " .. tostring(zerr and zerr.message), c.pos) + end + z2 = loose + end + raw, ro = z2 :: buffer, 0 + end + cel.w, cel.h, cel.raw, cel.ro = cw, ch, raw, ro + elseif ctyp == 1 then + cel.link = c:u16le() + 1 + else + cel.skip = true -- tilemap cel + end + frame.cels[li + 1] = cel + lastUser = cel + elseif ctype == 0x2018 then + local n = c:u16le() + c:skip(8) + tagUser = 0 + for _ = 1, n do + local from, to = c:u16le(), c:u16le() + local dir = c:u8() + local rep = c:u16le() + c:skip(6) + local cr, cg, cb = c:u8(), c:u8(), c:u8() + c:skip(1) + local name = str(c) + if c.err then + return nil, c.err + end + table.insert(tags, { name = name, from = from + 1, to = to + 1, direction = DIRECTIONS[dir] or "forward", ["repeat"] = rep, color = { cr, cg, cb } }) + tagUser += 1 + end + lastUser = nil + elseif ctype == 0x2019 then + local size = c:u32le() + local first, last = c:u32le(), c:u32le() + c:skip(8) + if first > last or last > 255 or size > 256 then + return nil, Err.new(Err.CORRUPT, "bad palette range", cstart) + end + for k = first, last do + local f = c:u16le() + local cr, cg, cb, ca = c:u8(), c:u8(), c:u8(), c:u8() + if bit32.band(f, 1) ~= 0 then + palNames[k + 1] = str(c) + end + buffer.writeu32(palette, k * 4, cr + cg * 256 + cb * 65536 + ca * 16777216) + palList[k + 1] = { cr, cg, cb, ca } + end + for k = #palList + 1, size do + palList[k] = { 0, 0, 0, 255 } + end + if c.err then + return nil, c.err + end + elseif (ctype == 0x0004 or ctype == 0x0011) and #palList == 0 then + -- old palettes (used when there is no 0x2019 chunk): packets of (skip, count) entries of RGB + local packets = c:u16le() + local k = 0 + for _ = 1, packets do + k += c:u8() + local n = c:u8() + if n == 0 then + n = 256 + end + for _ = 1, n do + local cr, cg, cb = c:u8(), c:u8(), c:u8() + if ctype == 0x0011 then + cr, cg, cb = cr * 255 // 63, cg * 255 // 63, cb * 255 // 63 + end + if k < 256 then + buffer.writeu32(palette, k * 4, cr + cg * 256 + cb * 65536 + 0xFF000000) + end + k += 1 + end + end + if c.err then + return nil, c.err + end + for i = 0, math.min(k, 256) - 1 do + local v = buffer.readu32(palette, i * 4) + palList[i + 1] = { v % 256, v // 256 % 256, v // 65536 % 256, 255 } + end + palList = table.move(palList, 1, math.min(k, 256), 1, {}) + elseif ctype == 0x2020 then + local f = c:u32le() + local ud: any = {} + if bit32.band(f, 1) ~= 0 then + ud.text = str(c) + end + if bit32.band(f, 2) ~= 0 then + ud.color = { c:u8(), c:u8(), c:u8(), c:u8() } + end + if not c.err then + if tagUser > 0 then + -- after a tags chunk, user data chunks follow for each tag in order + local t = tags[#tags - tagUser + 1] + if t then + t.userData = ud + end + tagUser -= 1 + elseif lastUser then + lastUser.userData = ud + end + end + end + -- others (colour profile, slices, tilesets, external files, cel extras, masks, paths) are skipped + end + r.pos = fstart + fbytes + end + local _ = ncolors + local function build(fi: number): { Types.Layer } + local root: { Types.Layer } = {} + local stack: { { Types.Layer } } = { root } + for li, info in infos do + local level = math.min(info.level, #stack - 1) + local list = stack[level + 1] + local l: any = { + name = info.name, + x = 0, + y = 0, + opacity = if bit32.band(hflags, 1) ~= 0 or info.type ~= 0 then info.opacity / 255 else 1, + blend = BLENDS[info.blend] or "normal", + visible = bit32.band(info.flags, 1) ~= 0, + flags = info.flags, + } + if info.userData then + l.userData = info.userData + end + if info.type == 1 then + l.image = Types.Image.new(0, 0) + l.children = {} + -- Aseprite renders a group straight onto the backdrop unless it has its own blend mode / opacity (then + -- into a buffer of its own): pass-through vs isolated + if bit32.band(hflags, 2) == 0 or (info.blend == 0 and info.opacity == 255) then + l.blend = "passThrough" + l.opacity = 1 + end + table.insert(list, l) + for k = #stack, level + 2, -1 do + stack[k] = nil + end + stack[level + 2] = l.children + else + for k = #stack, level + 2, -1 do + stack[k] = nil + end + l.image = Types.Image.new(0, 0) + if info.type == 2 then + l.tilemap = true + end + local cel = frames[fi].cels[li] + local guard = 0 + while cel and cel.link and guard < 8 do -- follow links (one hop in valid files) + l.link = cel.link + local target = frames[cel.link] + cel = if target then target.cels[li] else nil + guard += 1 + end + if cel and cel.image then + l.image = cel.image + l.x, l.y = cel.x, cel.y + if cel.opacity < 255 then + l.fillOpacity = cel.opacity / 255 + end + if cel.z ~= 0 then + l.zIndex = cel.z + end + if cel.userData then + l.celUserData = cel.userData + end + end + table.insert(list, l) + end + end + return root + end + for _, f in frames do + for li, cel in pairs(f.cels) do + if cel.raw then + local info = infos[li] + local img = Types.Image.new(cel.w, cel.h) + img.pixels = toRGBA(cel.raw, cel.ro, cel.w * cel.h, depth, palette, transparent, info ~= nil and bit32.band(info.flags, 8) ~= 0) + cel.image = img + cel.raw = nil + end + end + end + local layered = Types.Layered.new(w, h) + local list = {} + for fi = 1, nframes do + list[fi] = { layers = build(fi), delay = frames[fi].delay } + end + if nframes > 0 then + layered.layers = list[1].layers + end + layered.frames = list + if #palList > 0 then + layered.meta.palette = palList + if next(palNames) then + layered.meta.paletteNames = palNames + end + end + layered.meta.tags = tags + layered.meta.colorDepth = depth + layered.meta.transparentIndex = transparent + layered.meta.pixelRatio = { if pw == 0 then 1 else pw, if ph == 0 then 1 else ph } + layered.meta.grid = { gx, gy, gw, gh } + if skipped > 0 then + layered.meta.skipped = skipped + end + layered.meta.source = { format = "aseprite", bitDepth = depth, colorType = if depth == 32 then "rgba" elseif depth == 16 then "graya" else "indexed" } + return layered, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +type Node = { layer: any, level: number } + +local function isImage(v: any): boolean + return type(v) == "table" and v.format == "rgba8" and type(v.pixels) == "buffer" and type(v.width) == "number" and type(v.height) == "number" and v.width >= 0 and v.height >= 0 and v.width < 65536 and v.height < 65536 and buffer.len(v.pixels) >= v.width * v.height * 4 +end + +-- the nodes of a tree in file order (a group, then its children one level deeper) +local function nodes(layers: { any }, level: number, out: { Node }): boolean + for _, l in layers do + if type(l) ~= "table" or level > 64 then + return false + end + table.insert(out, { layer = l, level = level }) + if type(l.children) == "table" then + if not nodes(l.children, level + 1, out) then + return false + end + end + end + return true +end + +local function writeStr(w: Bytes.Writer, s: string) + local n = math.min(#s, 65535) + w:u16le(n) + w:string(string.sub(s, 1, n)) +end + +function Aseprite.encode(layered: Types.Layered, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(layered) ~= "table" or type(layered.layers) ~= "table" or type(layered.width) ~= "number" or type(layered.height) ~= "number" then + return nil, Err.new(Err.ARG, "needs a Layered value") + end + local W, H = math.floor(layered.width), math.floor(layered.height) + if W < 1 or H < 1 or W > 65535 or H > 65535 then + return nil, Err.new(Err.ARG, "bad sprite size") + end + local meta: any = if type(layered.meta) == "table" then layered.meta else {} + local level = opts and opts.level or 6 + local frameList: { any } = if type(layered.frames) == "table" and #layered.frames > 0 then layered.frames else { { layers = layered.layers, delay = 0.1 } } + local struct: { Node } = {} + if not nodes(frameList[1].layers, 0, struct) then + return nil, Err.new(Err.ARG, "bad layer tree") + end + if #struct > 65535 or #frameList > 65535 then + return nil, Err.new(Err.ARG, "too many layers / frames") + end + local perFrame: { { Node } } = {} + for fi, f in frameList do + if type(f) ~= "table" or type(f.layers) ~= "table" then + return nil, Err.new(Err.ARG, "frame " .. fi .. ": no layers") + end + local ns: { Node } = {} + if not nodes(f.layers, 0, ns) or #ns ~= #struct then + return nil, Err.new(Err.ARG, "frame " .. fi .. ": its layer tree differs from frame 1's") + end + for k, n in ns do + if (type(n.layer.children) == "table") ~= (type(struct[k].layer.children) == "table") then + return nil, Err.new(Err.ARG, "frame " .. fi .. ": its layer tree differs from frame 1's") + end + if type(n.layer.children) ~= "table" and not isImage(n.layer.image) then + return nil, Err.new(Err.ARG, "frame " .. fi .. ": layer " .. tostring(n.layer.name) .. " needs an rgba8 image") + end + end + perFrame[fi] = ns + end + local depth = opts and opts.depth or meta.colorDepth or 32 + local explicit = opts ~= nil and opts.depth ~= nil + if depth ~= 32 and depth ~= 16 and depth ~= 8 then + return nil, Err.new(Err.ARG, "depth must be 32, 16 or 8") + end + local palette: { { number } } = if type(meta.palette) == "table" then meta.palette else {} + local transparent = if type(meta.transparentIndex) == "number" then meta.transparentIndex else 0 + local index: { [number]: number } = {} + for k = #palette, 1, -1 do + local c = palette[k] + if type(c) == "table" then + index[(c[1] or 0) + (c[2] or 0) * 256 + (c[3] or 0) * 65536 + (c[4] or 255) * 16777216] = k - 1 + end + end + if depth ~= 32 then + local fits = depth ~= 8 or #palette > 0 + for _, ns in perFrame do + for _, n in ns do + local img = n.layer.image + if fits and type(n.layer.children) ~= "table" then + local px = img.pixels + for i = 0, img.width * img.height - 1 do + local v = buffer.readu32(px, i * 4) + if depth == 16 then + local r, g, b = v % 256, v // 256 % 256, v // 65536 % 256 + if r ~= g or g ~= b then + fits = false + break + end + elseif v // 16777216 ~= 0 and index[v] == nil then + fits = false + break + end + end + end + end + end + if not fits then + if explicit then + return nil, Err.new(Err.ARG, "the pixels do not fit depth " .. depth .. (if depth == 8 then " with meta.palette" else "")) + end + depth = 32 + end + end + local bpp = depth // 8 + local function pixels(n: any): buffer + local img = n.layer.image + local count = img.width * img.height + if depth == 32 then + return img.pixels + end + local out = buffer.create(count * bpp) + local px = img.pixels + for i = 0, count - 1 do + local v = buffer.readu32(px, i * 4) + if depth == 16 then + buffer.writeu8(out, i * 2, v % 256) + buffer.writeu8(out, i * 2 + 1, v // 16777216) + else + local k = if v // 16777216 == 0 and bit32.band(tonumber(n.layer.flags) or 0, 8) == 0 then transparent else index[v] or transparent + buffer.writeu8(out, i, k) + end + end + return out + end + + local out = Bytes.writer(65536) + -- header (file size patched at the end) + out:u32le(0) + out:u16le(0xA5E0) + out:u16le(#frameList) + out:u16le(W) + out:u16le(H) + out:u16le(depth) + out:u32le(3) -- layer opacity and group opacity / blend valid + out:u16le(100) + out:u32le(0) + out:u32le(0) + out:u8(if depth == 8 then transparent else 0) + out:fill(0, 3) + out:u16le(if #palette > 0 and #palette < 256 then #palette else 0) + local ratio = if type(meta.pixelRatio) == "table" then meta.pixelRatio else { 1, 1 } + out:u8(math.clamp(tonumber(ratio[1]) or 1, 0, 255)) + out:u8(math.clamp(tonumber(ratio[2]) or 1, 0, 255)) + local grid = if type(meta.grid) == "table" then meta.grid else { 0, 0, 16, 16 } + out:i16le(tonumber(grid[1]) or 0) + out:i16le(tonumber(grid[2]) or 0) + out:u16le(math.clamp(tonumber(grid[3]) or 16, 0, 65535)) + out:u16le(math.clamp(tonumber(grid[4]) or 16, 0, 65535)) + out:fill(0, 84) + + local function chunk(fw: Bytes.Writer, ctype: number, body: Bytes.Writer) + local b = body:finish() + fw:u32le(buffer.len(b) + 6) + fw:u16le(ctype) + fw:bytes(b) + end + local function userData(fw: Bytes.Writer, ud: any): number + if type(ud) ~= "table" then + return 0 + end + local c = Bytes.writer(64) + local f = (if type(ud.text) == "string" then 1 else 0) + (if type(ud.color) == "table" then 2 else 0) + c:u32le(f) + if type(ud.text) == "string" then + writeStr(c, ud.text) + end + if type(ud.color) == "table" then + for k = 1, 4 do + c:u8(math.clamp(tonumber(ud.color[k]) or 0, 0, 255)) + end + end + chunk(fw, 0x2020, c) + return 1 + end + local firstAt: { [number]: { [any]: { frame: number, x: number, y: number, fill: number } } } = {} + for fi, f in frameList do + local fw = Bytes.writer(4096) + local count = 0 + if fi == 1 then + -- colour profile: sRGB + local cp = Bytes.writer(16) + cp:u16le(1) + cp:u16le(0) + cp:u32le(0) + cp:fill(0, 8) + chunk(fw, 0x2007, cp) + count += 1 + if #palette > 0 then + local p = Bytes.writer(#palette * 6 + 20) + local n = math.min(#palette, 256) + p:u32le(n) + p:u32le(0) + p:u32le(n - 1) + p:fill(0, 8) + local names = if type(meta.paletteNames) == "table" then meta.paletteNames else {} + for k = 1, n do + local c = palette[k] + local nm = names[k] + p:u16le(if type(nm) == "string" then 1 else 0) + p:u8(c[1] or 0) + p:u8(c[2] or 0) + p:u8(c[3] or 0) + p:u8(c[4] or 255) + if type(nm) == "string" then + writeStr(p, nm) + end + end + chunk(fw, 0x2019, p) + count += 1 + end + for _, n in struct do + local l = n.layer + local c = Bytes.writer(64) + local isGroup = type(l.children) == "table" + local flags = tonumber(l.flags) or 3 + flags = bit32.band(flags, bit32.bnot(1)) + (if l.visible == false then 0 else 1) + c:u16le(flags) + c:u16le(if isGroup then 1 else 0) + c:u16le(n.level) + c:u16le(0) + c:u16le(0) + c:u16le(BLEND_IDS[l.blend] or 0) + c:u8(math.clamp(math.floor((tonumber(l.opacity) or 1) * 255 + 0.5), 0, 255)) + c:fill(0, 3) + writeStr(c, tostring(l.name or "Layer")) + chunk(fw, 0x2004, c) + count += 1 + count += userData(fw, l.userData) + end + local tags = if type(meta.tags) == "table" then meta.tags else {} + if #tags > 0 then + local c = Bytes.writer(64) + c:u16le(#tags) + c:fill(0, 8) + for _, t in tags do + c:u16le(math.clamp((tonumber(t.from) or 1) - 1, 0, 65535)) + c:u16le(math.clamp((tonumber(t.to) or 1) - 1, 0, 65535)) + c:u8(DIRECTION_IDS[t.direction] or 0) + c:u16le(math.clamp(tonumber(t["repeat"]) or 0, 0, 65535)) + c:fill(0, 6) + local col = if type(t.color) == "table" then t.color else { 0, 0, 0 } + c:u8(col[1] or 0) + c:u8(col[2] or 0) + c:u8(col[3] or 0) + c:u8(0) + writeStr(c, tostring(t.name or "Tag")) + end + chunk(fw, 0x2018, c) + count += 1 + for _, t in tags do + if type(t.userData) == "table" then + count += userData(fw, t.userData) + else + local e = Bytes.writer(4) + e:u32le(0) + chunk(fw, 0x2020, e) + count += 1 + end + end + end + end + for li, n in perFrame[fi] do + local l = n.layer + if type(l.children) == "table" or l.image.width == 0 or l.image.height == 0 then + continue + end + local x, y = math.floor(tonumber(l.x) or 0), math.floor(tonumber(l.y) or 0) + local fill = math.clamp(math.floor((tonumber(l.fillOpacity) or 1) * 255 + 0.5), 0, 255) + local c = Bytes.writer(256) + c:u16le(li - 1) + c:i16le(x) + c:i16le(y) + c:u8(fill) + local seen = firstAt[li] and firstAt[li][l.image] + if seen and seen.x == x and seen.y == y and seen.fill == fill then + c:u16le(1) + c:i16le(tonumber(l.zIndex) or 0) + c:fill(0, 5) + c:u16le(seen.frame - 1) + else + c:u16le(2) + c:i16le(tonumber(l.zIndex) or 0) + c:fill(0, 5) + c:u16le(l.image.width) + c:u16le(l.image.height) + local z = Deflate.zlibCompress(pixels(n), { level = level }) + if not z then + return nil, Err.new(Err.ARG, "cel compression failed") + end + c:bytes(z) + firstAt[li] = firstAt[li] or {} + firstAt[li][l.image] = { frame = fi, x = x, y = y, fill = fill } + end + chunk(fw, 0x2005, c) + count += 1 + count += userData(fw, l.celUserData) + end + local body = fw:finish() + out:u32le(buffer.len(body) + 16) + out:u16le(0xF1FA) + out:u16le(math.min(count, 0xFFFF)) + out:u16le(math.clamp(math.floor((tonumber(f.delay) or 0.1) * 1000 + 0.5), 0, 65535)) + out:u16le(0) + out:u32le(count) + out:bytes(body) + end + out:setU32le(0, out:tell()) + return out:finish(), nil +end + +return Aseprite +end +__FILES["layered/ora"] = function() + +-- layered/ora: OpenRaster 0.0.6 (freedesktop.org; new code): a zip with a stored "mimetype" first, stack.xml, PNG +-- layers, mergedimage.png, Thumbnails/thumbnail.png. Supports: nested stacks (isolation="auto" = passThrough), layer +-- attributes, svg:* ops; PNGs via opts.decodeImage / encodeImage. Not supported: non-PNG sources, <text> / <filter>. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Zip = __include("containers/Zip") +local Xml = __include("codecs/text/Xml") +local Blend = __include("codecs/image/Blend") + +-- ------------------------------------------------------------------------------------------------ contract +local Ora = { + name = "ora", + category = "layered", + extensions = { "ora" }, + mime = { "image/openraster" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Zip", "codecs/text/Xml", "codecs/image/Blend" }, + caps = { decode = true, encode = true, layers = true, groups = true, depths = { 8 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + decodeImage: ((buffer) -> (Types.Image?, Err.Err?))?, + composite: boolean?, -- default true + maxLayers: number?, -- default 10000 +} +type EncodeOptions = { + encodeImage: ((Types.Image, string) -> (buffer?, Err.Err?))?, + composite: Types.Image?, -- default: the layers flattened + thumbnail: boolean?, -- default true +} + +-- ------------------------------------------------------------------------------------------------ constants +local MIME = "image/openraster" +local OPS: { [string]: string } = { + ["svg:src-over"] = "normal", ["svg:multiply"] = "multiply", ["svg:screen"] = "screen", ["svg:overlay"] = "overlay", + ["svg:darken"] = "darken", ["svg:lighten"] = "lighten", ["svg:color-dodge"] = "colorDodge", ["svg:color-burn"] = "colorBurn", + ["svg:hard-light"] = "hardLight", ["svg:soft-light"] = "softLight", ["svg:difference"] = "difference", + ["svg:exclusion"] = "exclusion", ["svg:hue"] = "hue", ["svg:saturation"] = "saturation", ["svg:color"] = "color", + ["svg:luminosity"] = "luminosity", ["svg:plus"] = "linearDodge", +} +local BACK: { [string]: string } = {} +for k, v in OPS do + BACK[v] = k +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Ora.sniff(r: Bytes.Reader): number + -- a zip whose first (stored) entry is "mimetype" holding image/openraster + if r:peek(4) == "PK\3\4" and r:peek(8, 30) == "mimetype" and r:peek(#MIME, 38) == MIME then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function num(v: any, default: number): number + local n = tonumber(v) + return if n and n == n then n else default +end + +function Ora.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Layered?, Err.Err?) + local zip, zerr = Zip.open(r) + if not zip then + return nil, zerr + end + local mt = zip:readString("mimetype") + if mt and string.gsub(mt, "%s+$", "") ~= MIME then + return nil, Err.new(Err.CORRUPT, "mimetype is not " .. MIME) + end + local stackText, serr = zip:readString("stack.xml") + if not stackText then + return nil, serr or Err.new(Err.CORRUPT, "missing stack.xml") + end + local doc, xerr = Xml.decode(stackText) + if not doc then + return nil, xerr + end + local root = doc.root + if not root or root.name ~= "image" then + return nil, Err.new(Err.CORRUPT, "stack.xml has no <image> root") + end + local decodeImage = opts and opts.decodeImage + if not decodeImage then + return nil, Err.new(Err.UNSUPPORTED, "PNG layers need the decodeImage hook") + end + local W, H = num(root.attrs.w, 0), num(root.attrs.h, 0) + if W < 1 or H < 1 or W > 65536 or H > 65536 then + return nil, Err.new(Err.CORRUPT, "bad image size") + end + local maxLayers = opts and opts.maxLayers or 10000 + local count = 0 + local function png(path: string): (Types.Image?, Err.Err?) + local data, derr = zip:read(path) + if not data then + return nil, derr or Err.new(Err.CORRUPT, "missing " .. path) + end + local ok, img, ierr = pcall(decodeImage, data) + if not ok or not img then + return nil, Err.new(Err.CORRUPT, path .. ": " .. tostring(if ok then ierr else img)) + end + return img, nil + end + -- stack.xml lists a <stack>'s children top first + local function stack(node: any, ox: number, oy: number): ({ Types.Layer }?, Err.Err?) + local out: { Types.Layer } = {} + for _, ch in node.children do + if type(ch) ~= "table" then + continue + end + local a = ch.attrs or {} + local visible = a.visibility ~= "hidden" + local op = a["composite-op"] or "svg:src-over" + local blend = OPS[op] or op + local x, y = ox + num(a.x, 0), oy + num(a.y, 0) + count += 1 + if count > maxLayers then + return nil, Err.new(Err.LIMIT, "too many layers") + end + if ch.name == "layer" then + local src = a.src + if type(src) ~= "string" then + continue + end + if string.lower(string.sub(src, -4)) ~= ".png" then + return nil, Err.new(Err.UNSUPPORTED, "layer source " .. src) + end + local img, perr = png(src) + if not img then + return nil, perr + end + local layer = Types.Layered.layer(a.name or src, img :: Types.Image, x, y) + layer.opacity = math.clamp(num(a.opacity, 1), 0, 1) + layer.visible = visible + layer.blend = blend + table.insert(out, 1, layer) + elseif ch.name == "stack" then + local kids, kerr = stack(ch, x, y) + if not kids then + return nil, kerr + end + local g = Types.Layered.group(a.name or "group", kids :: { Types.Layer }) + g.opacity = math.clamp(num(a.opacity, 1), 0, 1) + g.visible = visible + g.blend = if a.isolation == "isolate" then (if blend == "normal" then "normal" else blend) else "passThrough" + table.insert(out, 1, g) + end + end + return out, nil + end + local top = Xml.child(root, "stack") + if not top then + return nil, Err.new(Err.CORRUPT, "stack.xml has no <stack>") + end + local layers, lerr = stack(top, 0, 0) + if not layers then + return nil, lerr + end + local doc2 = Types.Layered.new(W, H) + doc2.layers = layers :: { Types.Layer } + if not (opts and opts.composite == false) and zip:find("mergedimage.png") then + doc2.meta.composite = png("mergedimage.png") + end + local xr, yr = tonumber(root.attrs.xres), tonumber(root.attrs.yres) + if xr and yr then + doc2.meta.dpi = { x = xr, y = yr } + end + doc2.meta.source = { format = "ora", version = root.attrs.version, layers = count } + return doc2, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function thumbnail(img: Types.Image, max: number): Types.Image + local w, h = img.width, img.height + local s = math.min(1, max / math.max(w, h)) + local tw, th = math.max(1, math.floor(w * s)), math.max(1, math.floor(h * s)) + local t = Types.Image.new(tw, th, "rgba8") + for y = 0, th - 1 do + local sy = math.min(h - 1, math.floor(y / s)) + for x = 0, tw - 1 do + local sx = math.min(w - 1, math.floor(x / s)) + buffer.writeu32(t.pixels, (y * tw + x) * 4, buffer.readu32(img.pixels, (sy * w + sx) * 4)) + end + end + return t +end + +function Ora.encode(doc: Types.Layered, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(doc) ~= "table" or type(doc.layers) ~= "table" or type(doc.width) ~= "number" or doc.width < 1 or doc.height < 1 then + return nil, Err.new(Err.ARG, "needs a Layered document") + end + local encodeImage = opts and opts.encodeImage + if not encodeImage then + return nil, Err.new(Err.UNSUPPORTED, "PNG layers need the encodeImage hook") + end + local W, H = doc.width, doc.height + local zw = Zip.writer() + zw:add("mimetype", MIME, { method = "store" }) + local files: { { any } } = {} + local n = 0 + local function png(img: Types.Image, label: string): (buffer?, Err.Err?) + if type(img) ~= "table" or img.format ~= "rgba8" then + return nil, Err.new(Err.ARG, label .. ": layers need rgba8 images") + end + local ok, data, err = pcall(encodeImage, img, "png") + if not ok or not data then + return nil, Err.new(Err.ARG, label .. ": " .. tostring(if ok then err else data)) + end + return data, nil + end + local function stack(layers: { Types.Layer }): ({ any }?, Err.Err?) + local kids = {} + for i = #layers, 1, -1 do + local l = layers[i] + local attrs: { [string]: string } = { + name = l.name or "", + opacity = string.format("%.6g", l.opacity or 1), + visibility = if l.visible == false then "hidden" else "visible", + } + if l.children then + attrs.isolation = if l.blend == "passThrough" then "auto" else "isolate" + if l.blend ~= "passThrough" then + attrs["composite-op"] = BACK[l.blend] or l.blend + end + local sub, serr = stack(l.children) + if not sub then + return nil, serr + end + table.insert(kids, Xml.element("stack", attrs, sub)) + else + n += 1 + local path = string.format("data/layer%03d.png", n) + local data, perr = png(l.image, "layer " .. tostring(l.name)) + if not data then + return nil, perr + end + table.insert(files, { path, data }) + attrs.src = path + attrs.x = tostring(math.floor(l.x or 0)) + attrs.y = tostring(math.floor(l.y or 0)) + attrs["composite-op"] = BACK[l.blend or "normal"] or l.blend or "svg:src-over" + table.insert(kids, Xml.element("layer", attrs)) + end + end + return kids, nil + end + local kids, kerr = stack(doc.layers) + if not kids then + return nil, kerr + end + local rootAttrs: { [string]: string } = { version = "0.0.6", w = tostring(W), h = tostring(H) } + local dpi = doc.meta and doc.meta.dpi + if dpi then + rootAttrs.xres, rootAttrs.yres = tostring(dpi.x), tostring(dpi.y) + end + local xml = Xml.encode(Xml.document(Xml.element("image", rootAttrs, { Xml.element("stack", {}, kids :: any) })), { indent = 1 }) + zw:add("stack.xml", xml :: string) + for _, f in files do + zw:add(f[1], f[2], { method = "store" }) + end + local merged = opts and opts.composite + if not merged then + local m = Types.Image.new(W, H, "rgba8") + Blend.flatten(doc.layers, m.pixels, W, H, false) + merged = m + end + local mdata, merr = png(merged :: Types.Image, "mergedimage") + if not mdata then + return nil, merr + end + zw:add("mergedimage.png", mdata, { method = "store" }) + if not (opts and opts.thumbnail == false) then + local tdata, terr = png(thumbnail(merged :: Types.Image, 256), "thumbnail") + if not tdata then + return nil, terr + end + zw:add("Thumbnails/thumbnail.png", tdata, { method = "store" }) + end + return zw:finish() +end + +return Ora +end +__FILES["layered/psd"] = function() + +-- layered/psd: Adobe Photoshop PSD / PSB (Photoshop File Formats Specification, 2016). Supports: every colour mode at +-- 1 / 8 / 16 / 32 bits, layers (RLE / ZIP channels, Lr16 / Lr32, iOpa, luni, masks, lsct groups), the merged image, +-- resources; encode: 8-bit RGB. Not supported: adjustment / type / smart-object contents, effects, vector masks. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Text = __include("codecs/text/Text") +local Blend = __include("codecs/image/Blend") +local Channels = __include("layered/psd/Channels") + +-- ------------------------------------------------------------------------------------------------ contract +local Psd = { + name = "psd", + category = "layered", + extensions = { "psd", "psb" }, + mime = { "image/vnd.adobe.photoshop" }, + 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 } }, +} + +type DecodeOptions = { + layers: boolean?, -- default true (false: the merged image only) + maxPixels: number?, -- default 2^26 + maxLayers: number?, -- default 10000 +} +type EncodeOptions = { + composite: Types.Image?, -- default: the layers flattened +} + +-- ------------------------------------------------------------------------------------------------ constants +local BLEND_KEYS: { [string]: string } = { + norm = "normal", + diss = "dissolve", + dark = "darken", + ["mul "] = "multiply", + idiv = "colorBurn", + lbrn = "linearBurn", + dkCl = "darkerColor", + lite = "lighten", + scrn = "screen", + ["div "] = "colorDodge", + lddg = "linearDodge", + lgCl = "lighterColor", + over = "overlay", + sLit = "softLight", + hLit = "hardLight", + vLit = "vividLight", + lLit = "linearLight", + pLit = "pinLight", + hMix = "hardMix", + diff = "difference", + smud = "exclusion", + fsub = "subtract", + fdiv = "divide", + ["hue "] = "hue", + ["sat "] = "saturation", + colr = "color", + ["lum "] = "luminosity", + pass = "passThrough", +} +local BLEND_NAMES: { [string]: string } = {} +for k, v in BLEND_KEYS do + BLEND_NAMES[v] = k +end +BLEND_NAMES.add = "lddg" + +-- colour channels per mode (the rest are alpha / spot channels) +local COLOR_CHANNELS = { [0] = 1, [1] = 1, [2] = 1, [3] = 3, [4] = 4, [7] = 1, [8] = 1, [9] = 3 } +local MODE_NAMES = { [0] = "bitmap", [1] = "gray", [2] = "indexed", [3] = "rgb", [4] = "cmyk", [7] = "multichannel", [8] = "duotone", [9] = "lab" } +-- additional layer info keys with 8-byte lengths in PSB +local LONG_KEYS = { LMsk = true, Lr16 = true, Lr32 = true, Layr = true, Mt16 = true, Mt32 = true, Mtrn = true, Alph = true, FMsk = true, lnk2 = true, FEid = true, FXid = true, PxSD = true } + +-- ------------------------------------------------------------------------------------------------ sniff +function Psd.sniff(r: Bytes.Reader): number + local h = r:peek(6) + if string.sub(h, 1, 4) == "8BPS" and (string.sub(h, 5, 6) == "\0\1" or string.sub(h, 5, 6) == "\0\2") then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +type Ctx = { psb: boolean, depth: number, mode: number, maxPixels: number, maxLayers: number } + +local function len(r: Bytes.Reader, psb: boolean): number + return if psb then r:u64be() else r:u32be() +end + +local function utf16be(s: string): string + return (string.gsub(Text.utf16(buffer.fromstring(s), 0, #s, true), "%z", "")) +end + +local function layerRecords(r: Bytes.Reader, c: Ctx): ({ any }?, boolean, Err.Err?) + local count = r:i16be() + local absAlpha = count < 0 + count = math.abs(count) + if r.err then + return nil, absAlpha, r.err + end + if count > c.maxLayers then + return nil, absAlpha, Err.new(Err.LIMIT, "over " .. c.maxLayers .. " layers") + end + local recs = {} + for li = 1, count do + local top, left, bottom, right = r:i32be(), r:i32be(), r:i32be(), r:i32be() + local nch = r:u16be() + if r.err then + return nil, absAlpha, r.err + end + if nch > 56 then + return nil, absAlpha, Err.new(Err.CORRUPT, "layer " .. li .. ": " .. nch .. " channels", r.pos) + end + local chans = {} + for k = 1, nch do + chans[k] = { id = r:i16be(), size = len(r, c.psb) } + end + if r:string(4) ~= "8BIM" and not r.err then + return nil, absAlpha, Err.new(Err.CORRUPT, "layer " .. li .. ": bad blend mode signature", r.pos - 4) + end + local key = r:string(4) + local opacity, clipping, flags = r:u8(), r:u8(), r:u8() + r:skip(1) + local extraLen = r:u32be() + if r.err then + return nil, absAlpha, r.err + end + local ex = r:slice(extraLen) + local rec: { [string]: any } = { + top = top, + left = left, + bottom = bottom, + right = right, + chans = chans, + blend = BLEND_KEYS[key] or "normal", + blendKey = key, + opacity = opacity / 255, + clip = clipping ~= 0, + hidden = bit32.band(flags, 2) ~= 0, + flags = flags, + } + -- mask data + local ml = ex:u32be() + if ml > 0 then + local mr = ex:slice(ml) + if ml >= 18 then + rec.mask = { top = mr:i32be(), left = mr:i32be(), bottom = mr:i32be(), right = mr:i32be(), default = mr:u8(), flags = mr:u8() } + end + end + -- blending ranges + ex:skip(ex:u32be()) + -- name: Pascal string padded to 4 + local nl = ex:u8() + rec.name = ex:string(nl) + ex:skip((4 - (nl + 1) % 4) % 4) + -- additional layer info + while ex:remaining() >= 12 do + local sig = ex:string(4) + if sig ~= "8BIM" and sig ~= "8B64" then + break + end + local k = ex:string(4) + local l = if c.psb and LONG_KEYS[k] then ex:u64be() else ex:u32be() + if ex.err then + break + end + local d = ex:slice(l) + if k == "luni" then + local n = d:u32be() + local s = d:string(math.min(n * 2, d:remaining())) + rec.name = utf16be(s) + elseif k == "lsct" or k == "lsdk" then + rec.section = d:u32be() + if d:remaining() >= 8 and d:string(4) == "8BIM" then + rec.sectionBlend = d:string(4) + end + elseif k == "iOpa" then + rec.fill = d:u8() / 255 + elseif k == "lyid" then + rec.id = d:u32be() + end + end + if r.err then + return nil, absAlpha, r.err + end + recs[li] = rec + end + -- channel image data + local b = r.buf + for li, rec in recs do + local w, h = rec.right - rec.left, rec.bottom - rec.top + if w < 0 or h < 0 or w > 300000 or h > 300000 then + return nil, absAlpha, Err.new(Err.CORRUPT, "layer " .. li .. ": bad bounds", r.pos) + end + if w * h > c.maxPixels then + return nil, absAlpha, Err.new(Err.LIMIT, string.format("layer %d: %d x %d is over the pixel limit", li, w, h)) + end + local planes: { [any]: buffer } = {} + for _, ch in rec.chans do + local p = r.pos + if ch.size < 0 or p + ch.size > r.limit then + return nil, absAlpha, Err.new(Err.TRUNCATED, "layer " .. li .. ": channel data past the end", p) + end + r.pos = p + ch.size + local cw, chh = w, h + if ch.id == -2 or ch.id == -3 then + local m = rec.mask + if not m then + continue + end + cw, chh = m.right - m.left, m.bottom - m.top + if cw < 0 or chh < 0 or cw * chh > c.maxPixels then + continue + end + end + if ch.size < 2 then + continue + end + local plane, perr = Channels.channel(b, p, p + ch.size, cw, chh, c.depth, c.psb) + if not plane then + return nil, absAlpha, Err.new(Err.CORRUPT, "layer " .. li .. " channel " .. ch.id .. ": " .. tostring(perr), p) + end + if c.depth == 32 then + Channels.swap32(plane) + end + if ch.id == -1 then + planes.alpha = plane + elseif ch.id == -2 then + rec.maskPlane = Channels.gray8(plane, cw, chh, c.depth) + elseif ch.id >= 0 and ch.id < 56 then + planes[ch.id + 1] = plane + end + end + local img = Types.Image.new(w, h) + if w > 0 and h > 0 then + img.pixels = Channels.toRGBA(planes, w, h, c.depth, c.mode, nil) + end + rec.image = img + end + return recs, absAlpha, nil +end + +local function tree(recs: { any }): { Types.Layer } + local root: { Types.Layer } = {} + local stack: { { Types.Layer } } = {} + local cur = root + local function layerOf(rec: any): Types.Layer + local l: any = { + name = rec.name, + image = rec.image, + x = rec.left, + y = rec.top, + opacity = rec.opacity, + blend = rec.blend, + visible = not rec.hidden, + } + if rec.clip then + l.clip = true + end + if rec.fill and rec.fill < 1 then + l.fillOpacity = rec.fill + end + if rec.id then + l.id = rec.id + end + if rec.mask and rec.maskPlane then + local m = rec.mask + local mi = Types.Image.new(m.right - m.left, m.bottom - m.top, "gray8") + mi.pixels = rec.maskPlane + l.mask = { image = mi, x = m.left, y = m.top, default = m.default, disabled = bit32.band(m.flags, 2) ~= 0 } + end + return l + end + for _, rec in recs do + local s = rec.section + if s == 3 then + table.insert(stack, cur) + cur = {} + elseif s == 1 or s == 2 then + local g = layerOf(rec) + g.image = Types.Image.new(0, 0) + g.children = cur + if rec.sectionBlend and BLEND_KEYS[rec.sectionBlend] then + g.blend = BLEND_KEYS[rec.sectionBlend] + end + ;(g :: any).collapsed = s == 2 + cur = table.remove(stack) or root + table.insert(cur, g) + else + table.insert(cur, layerOf(rec)) + end + end + -- unbalanced dividers: splice the open groups' layers back in + while #stack > 0 do + local parent = table.remove(stack) :: { Types.Layer } + for _, l in cur do + table.insert(parent, l) + end + cur = parent + end + return cur +end + +function Psd.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Layered?, Err.Err?) + local o: DecodeOptions = opts or {} + local c: Ctx = { psb = false, depth = 8, mode = 3, maxPixels = o.maxPixels or 2 ^ 26, maxLayers = o.maxLayers or 10000 } + if Psd.sniff(r) == 0 then + return nil, Err.new(Err.CORRUPT, "not a PSD (bad signature)", r.pos) + end + r:skip(4) + local version = r:u16be() + r:skip(6) + local nch, h, w, depth, mode = r:u16be(), r:u32be(), r:u32be(), r:u16be(), r:u16be() + if r.err then + return nil, r.err + end + c.psb, c.depth, c.mode = version == 2, depth, mode + if nch < 1 or nch > 56 then + return nil, Err.new(Err.CORRUPT, "bad channel count " .. nch) + end + local maxSide = if c.psb then 300000 else 30000 + if w < 1 or h < 1 or w > maxSide or h > maxSide then + return nil, Err.new(Err.CORRUPT, string.format("bad size %d x %d", w, h)) + end + if not (depth == 1 or depth == 8 or depth == 16 or depth == 32) then + return nil, Err.new(Err.CORRUPT, "bad depth " .. depth) + end + if COLOR_CHANNELS[mode] == nil then + return nil, Err.new(Err.CORRUPT, "bad colour mode " .. mode) + end + if (mode == 0) ~= (depth == 1) then + return nil, Err.new(Err.UNSUPPORTED, "1-bit data outside bitmap mode") + end + if w * h > c.maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, c.maxPixels)) + end + local layered = Types.Layered.new(w, h) + -- colour mode data + local cm = r:slice(r:u32be()) + local palette: buffer? = nil + if mode == 2 and cm:size() >= 768 then + palette = cm:bytes(768) + local pal = {} + for i = 0, 255 do + pal[i + 1] = { buffer.readu8(palette :: buffer, i), buffer.readu8(palette :: buffer, 256 + i), buffer.readu8(palette :: buffer, 512 + i), 255 } + end + layered.meta.palette = pal + end + -- image resources + local rr = r:slice(r:u32be()) + if r.err then + return nil, r.err + end + local resources = {} + while rr:remaining() >= 12 and rr:string(4) == "8BIM" do + local id = rr:u16be() + local nl = rr:u8() + local name = rr:string(nl) + rr:skip((nl + 1) % 2) + local size = rr:u32be() + if rr.err or size > rr:remaining() then + break + end + local data = rr:bytes(size) + rr:skip(size % 2) + table.insert(resources, { id = id, name = name, data = data }) + if id == 0x040F then + layered.meta.icc = data + end + end + layered.meta.resources = resources + -- layer and mask information + local lm = r:slice(len(r, c.psb)) + if r.err then + return nil, r.err + end + local recs: { any }? = nil + local absAlpha = false + if o.layers ~= false and lm:size() > 0 then + local liLen = len(lm, c.psb) + local li = lm:slice(liLen) + if lm.err then + return nil, lm.err + end + if liLen > 0 then + local list, aa, lerr = layerRecords(li, c) + if not list then + return nil, lerr + end + recs, absAlpha = list, aa + end + -- global layer mask info, then additional info (16 / 32-bit layers live in Lr16 / Lr32) + lm:skip(lm:u32be()) + while not lm.err and lm:remaining() >= 12 do + local sig = lm:string(4) + if sig ~= "8BIM" and sig ~= "8B64" then + break + end + local k = lm:string(4) + local l = if c.psb and LONG_KEYS[k] then lm:u64be() else lm:u32be() + if lm.err then + break + end + local d = lm:slice(l) + if (k == "Lr16" or k == "Lr32" or k == "Layr") and recs == nil then + local list, aa, lerr = layerRecords(d, c) + if not list then + return nil, lerr + end + recs, absAlpha = list, aa + end + lm:align(4) + end + end + if recs then + layered.layers = tree(recs) + end + -- the merged image + local comp = r:u16be() + if r.err then + return nil, r.err + end + local cc = COLOR_CHANNELS[mode] + if mode == 7 then + cc = math.min(nch, 3) + end + local useAlpha = nch > cc and (absAlpha or recs == nil) and mode ~= 7 + local nread = math.min(nch, cc + (if useAlpha then 1 else 0)) + local rb = Channels.rowBytes(w, depth) + local planes: { [any]: buffer } = {} + local b = r.buf + if comp == 0 then + for k = 1, nread do + local p = r.pos + (k - 1) * rb * h + if p + rb * h > r.limit then + return nil, Err.new(Err.TRUNCATED, "merged image past the end", p) + end + local plane = buffer.create(rb * h) + buffer.copy(plane, 0, b, p, rb * h) + planes[k] = plane + end + elseif comp == 1 then + local counts, q = Channels.rleCounts(b, r.pos, r.limit, h * nch, c.psb) + if not counts then + return nil, Err.new(Err.TRUNCATED, "merged image row counts past the end", r.pos) + end + local p: number = q + for k = 1, nread do + local plane = buffer.create(rb * h) + local np, perr = Channels.rle(b, p, r.limit, counts, (k - 1) * h + 1, h, rb, plane, 0) + if not np then + return nil, Err.new(Err.CORRUPT, "merged image: " .. tostring(perr), p) + end + p = np + planes[k] = plane + end + elseif comp == 2 or comp == 3 then + -- Photoshop writes all channels in one zlib stream + local all = Channels.channel(b, r.pos - 2, r.limit, w, h * nread, depth, c.psb) + if not all then + return nil, Err.new(Err.CORRUPT, "merged image: bad ZIP data", r.pos) + end + for k = 1, nread do + local plane = buffer.create(rb * h) + buffer.copy(plane, 0, all, (k - 1) * rb * h, rb * h) + planes[k] = plane + end + else + return nil, Err.new(Err.CORRUPT, "bad merged image compression " .. comp) + end + if useAlpha then + planes.alpha = planes[cc + 1] + planes[cc + 1] = nil :: any + end + if depth == 32 then + for _, p in planes do + Channels.swap32(p) + end + end + local composite = Types.Image.new(w, h) + composite.pixels = Channels.toRGBA(planes, w, h, depth, mode, palette) + if planes.alpha then + Channels.unmatte(composite.pixels, w * h) + end + composite.meta.source = { format = "psd", bitDepth = depth, colorType = MODE_NAMES[mode] } + layered.meta.composite = composite + layered.meta.source = { format = "psd", version = version, bitDepth = depth, colorMode = MODE_NAMES[mode], channels = nch, psb = c.psb } + return layered, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +type Rec = { layer: any, section: number?, name: string } + +local function isImage(v: any): boolean + return type(v) == "table" and v.format == "rgba8" and type(v.pixels) == "buffer" and type(v.width) == "number" and type(v.height) == "number" and v.width >= 0 and v.height >= 0 and buffer.len(v.pixels) >= v.width * v.height * 4 +end + +local function pascal(name: string): string + local s = string.gsub(name, "[\128-\255]", "?") + s = string.sub(s, 1, 255) + local pad = (4 - (#s + 1) % 4) % 4 + return string.char(#s) .. s .. string.rep("\0", pad) +end + +local function block(w: Bytes.Writer, key: string, data: string) + w:string("8BIM") + w:string(key) + local pad = (4 - #data % 4) % 4 -- additional info is padded to 4 + w:u32be(#data + pad) + w:string(data) + w:fill(0, pad) +end + +local function u32s(v: number): string + return string.char(v // 16777216 % 256, v // 65536 % 256, v // 256 % 256, v % 256) +end + +local function luni(name: string): string + local out = {} + local n = 0 + for _, cp in utf8.codes(name) do + if cp >= 0x10000 then + local v = cp - 0x10000 + local hi, lo = 0xD800 + v // 1024, 0xDC00 + v % 1024 + table.insert(out, string.char(hi // 256, hi % 256, lo // 256, lo % 256)) + n += 2 + else + table.insert(out, string.char(cp // 256, cp % 256)) + n += 1 + end + end + return u32s(n) .. table.concat(out) +end + +function Psd.encode(layered: Types.Layered, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(layered) ~= "table" or type(layered.layers) ~= "table" or type(layered.width) ~= "number" or type(layered.height) ~= "number" then + return nil, Err.new(Err.ARG, "needs a Layered value") + end + local W, H = math.floor(layered.width), math.floor(layered.height) + if W < 1 or H < 1 or W > 300000 or H > 300000 then + return nil, Err.new(Err.ARG, "bad document size") + end + local psb = W > 30000 or H > 30000 + -- the records, bottom to top + local recs: { Rec } = {} + local bad: string? = nil + local function walk(list: { any }, depth: number) + for _, l in list do + if type(l) ~= "table" then + bad = "a layer is not a table" + return + end + if type(l.children) == "table" then + if depth > 64 then + bad = "groups nested too deep" + return + end + table.insert(recs, { layer = l, section = 3, name = "</Layer group>" }) + walk(l.children, depth + 1) + table.insert(recs, { layer = l, section = if l.collapsed then 2 else 1, name = tostring(l.name or "Group") }) + else + if not isImage(l.image) then + bad = "layer " .. tostring(l.name) .. ": needs an rgba8 image" + return + end + table.insert(recs, { layer = l, name = tostring(l.name or "Layer") }) + end + end + end + walk(layered.layers, 0) + if bad then + return nil, Err.new(Err.ARG, bad :: string) + end + if #recs > 32767 then + return nil, Err.new(Err.ARG, "too many layers") + end + local function lenW(w: Bytes.Writer, v: number) + if psb then + w:u64be(v) + else + w:u32be(v) + end + end + -- layer records and channel data + local info = Bytes.writer(4096) + local data = Bytes.writer(65536) + info:i16be(-#recs) -- negative: the merged image's first alpha channel is its transparency + for _, rec in recs do + local l = rec.layer + local img = if rec.section then nil else l.image + local x, y = math.floor(tonumber(l.x) or 0), math.floor(tonumber(l.y) or 0) + local w, h = if img then img.width else 0, if img then img.height else 0 + if rec.section then + x, y = 0, 0 + end + info:i32be(y) + info:i32be(x) + info:i32be(y + h) + info:i32be(x + w) + local chans: { { id: number, data: buffer } } = {} + if img and w > 0 and h > 0 then + local pr, pg, pb, pa = Channels.planes8(img.pixels, w, h) + chans = { + { id = -1, data = Channels.rleChannel(pa, w, h, psb) }, + { id = 0, data = Channels.rleChannel(pr, w, h, psb) }, + { id = 1, data = Channels.rleChannel(pg, w, h, psb) }, + { id = 2, data = Channels.rleChannel(pb, w, h, psb) }, + } + else + chans = { { id = -1, data = buffer.create(0) }, { id = 0, data = buffer.create(0) }, { id = 1, data = buffer.create(0) }, { id = 2, data = buffer.create(0) } } + end + -- the mask + local m = if rec.section == nil and type(l.mask) == "table" and type(l.mask.image) == "table" and type(l.mask.image.pixels) == "buffer" then l.mask else nil + local mw, mh = 0, 0 + if m then + local mi = m.image + mw, mh = mi.width, mi.height + local plane = mi.pixels + if mi.format == "rgba8" then + plane = (Channels.planes8(mi.pixels, mw, mh)) + elseif mi.format ~= "gray8" and mi.format ~= "alpha8" then + return nil, Err.new(Err.ARG, "mask images are gray8 / alpha8 / rgba8") + end + if buffer.len(plane) < mw * mh then + return nil, Err.new(Err.ARG, "bad mask image") + end + table.insert(chans, { id = -2, data = Channels.rleChannel(plane, mw, mh, psb) }) + end + info:u16be(#chans) + for _, ch in chans do + info:i16be(ch.id) + lenW(info, buffer.len(ch.data) + 2) + data:u16be(if buffer.len(ch.data) > 0 then 1 else 0) + data:bytes(ch.data) + end + info:string("8BIM") + local blend = if type(l.blend) == "string" then l.blend else "normal" + local key = BLEND_NAMES[blend] or "norm" + if rec.section and rec.section ~= 3 then + key = if blend == "passThrough" then "pass" else key + end + info:string(key) + info:u8(math.clamp(math.floor((tonumber(l.opacity) or 1) * 255 + 0.5), 0, 255)) + info:u8(if l.clip and rec.section == nil then 1 else 0) + local flags = 8 -- bit 3: bit 4 is meaningful + if l.visible == false and rec.section ~= 3 then + flags += 2 + end + if rec.section then + flags += 16 -- pixel data irrelevant to the appearance + end + info:u8(flags) + info:u8(0) + local ex = Bytes.writer(256) + if m then + ex:u32be(20) + local mx, my = math.floor(tonumber(m.x) or 0), math.floor(tonumber(m.y) or 0) + ex:i32be(my) + ex:i32be(mx) + ex:i32be(my + mh) + ex:i32be(mx + mw) + ex:u8(math.clamp(math.floor(tonumber(m.default) or 0), 0, 255)) + ex:u8(if m.disabled then 2 else 0) + ex:u16be(0) + else + ex:u32be(0) + end + ex:u32be(0) -- blending ranges + ex:string(pascal(rec.name)) + block(ex, "luni", luni(rec.name)) + if rec.section then + block(ex, "lsct", u32s(rec.section) .. (if rec.section ~= 3 then "8BIM" .. key else "")) + end + local fill = tonumber(l.fillOpacity) + if fill and fill < 1 and rec.section == nil then + block(ex, "iOpa", string.char(math.clamp(math.floor(fill * 255 + 0.5), 0, 255)) .. "\0\0\0") + end + local exb = ex:finish() + info:u32be(buffer.len(exb)) + info:bytes(exb) + end + info:bytes(data:finish()) + if info:tell() % 2 == 1 then + info:u8(0) + end + local infoB = info:finish() + -- the merged image + local comp: Types.Image? = opts and opts.composite + if comp ~= nil and (not isImage(comp) or comp.width ~= W or comp.height ~= H) then + return nil, Err.new(Err.ARG, "opts.composite must be a " .. W .. " x " .. H .. " rgba8 Image") + end + local merged: buffer + if comp then + merged = comp.pixels + else + merged = buffer.create(W * H * 4) + Blend.flatten(layered.layers, merged, W, H, false) + end + local out = Bytes.writer(buffer.len(infoB) + W * H * 4 + 1024) + out:string("8BPS") + out:u16be(if psb then 2 else 1) + out:fill(0, 6) + out:u16be(4) + out:u32be(H) + out:u32be(W) + out:u16be(8) + out:u16be(3) + out:u32be(0) -- colour mode data + out:u32be(0) -- image resources + local lmLen = (if psb then 8 else 4) + buffer.len(infoB) + 4 + lenW(out, lmLen) + lenW(out, buffer.len(infoB)) + out:bytes(infoB) + out:u32be(0) -- global layer mask info + -- merged: RLE, all row counts first + out:u16be(1) + local pr, pg, pb, pa = Channels.planes8(Channels.matte(merged, W * H), W, H) + local cs = if psb then 4 else 2 + local parts = {} + for k, plane in { pr, pg, pb, pa } do + local ch = Channels.rleChannel(plane, W, H, psb) + parts[k] = ch + out:bytes(ch, 0, H * cs) + end + for k = 1, 4 do + out:bytes(parts[k], H * cs) + end + return out:finish(), nil +end + +return Psd +end +__FILES["layered/psd/Channels"] = @native function() + + +-- layered/psd/Channels: PSD / PSB channel data (Photoshop File Formats Specification 2016, "Channel image data" / +-- "Image data section"): raw, PackBits RLE, ZIP, ZIP with prediction; colour modes to rgba8; PackBits rows. +local Deflate = __include("codecs/compress/Deflate") +local PackBits = __include("codecs/compress/PackBits") + +local Channels = {} + +local readu8, writeu8, readu16, writeu16, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16, buffer.readu32, buffer.writeu32 +local readf32, writef32, bcreate, bcopy, blen, bfill = buffer.readf32, buffer.writef32, buffer.create, buffer.copy, buffer.len, buffer.fill +local floor, min, max = math.floor, math.min, math.max +local byteswap = bit32.byteswap + +@native function Channels.rowBytes(w: number, depth: number): number + if depth == 1 then + return (w + 7) // 8 + end + return w * (depth // 8) +end + +@native function Channels.rleCounts(src: buffer, p: number, limit: number, rows: number, psb: boolean): ({ number }?, number) + local size = if psb then 4 else 2 + if rows < 0 or p + rows * size > limit then + return nil, p + end + local counts: { number } = table.create(rows) :: { number } + for i = 1, rows do + if psb then + counts[i] = byteswap(readu32(src, p)) + else + counts[i] = readu8(src, p) * 256 + readu8(src, p + 1) + end + p += size + end + return counts, p +end + +@native function Channels.rle(src: buffer, p: number, limit: number, counts: { number }, first: number, rows: number, rowBytes: number, dst: buffer, d: number): (number?, string?) + for i = 0, rows - 1 do + local c = counts[first + i] or 0 + if p + c > limit then + return nil, "RLE row past the end" + end + 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 + p += c + end + return p, nil +end + +@native local function unpredict(plane: buffer, w: number, h: number, depth: number) + if depth == 8 then + for y = 0, h - 1 do + local o = y * w + local acc = readu8(plane, o) + for x = 1, w - 1 do + acc = (acc + readu8(plane, o + x)) % 256 + writeu8(plane, o + x, acc) + end + end + elseif depth == 16 then + for y = 0, h - 1 do + local o = y * w * 2 + local acc = readu8(plane, o) * 256 + readu8(plane, o + 1) + for x = 1, w - 1 do + local q = o + x * 2 + acc = (acc + readu8(plane, q) * 256 + readu8(plane, q + 1)) % 65536 + writeu8(plane, q, acc // 256) + writeu8(plane, q + 1, acc % 256) + end + end + elseif depth == 32 then + -- byte deltas over the row, then the row is 4 byte planes (all high bytes first) + local rb = w * 4 + local tmp = bcreate(rb) + for y = 0, h - 1 do + local o = y * rb + local acc = readu8(plane, o) + for x = 1, rb - 1 do + acc = (acc + readu8(plane, o + x)) % 256 + writeu8(plane, o + x, acc) + end + for x = 0, w - 1 do + writeu8(tmp, x * 4, readu8(plane, o + x)) + writeu8(tmp, x * 4 + 1, readu8(plane, o + w + x)) + writeu8(tmp, x * 4 + 2, readu8(plane, o + 2 * w + x)) + writeu8(tmp, x * 4 + 3, readu8(plane, o + 3 * w + x)) + end + bcopy(plane, o, tmp, 0, rb) + end + end +end + +@native function Channels.channel(src: buffer, p: number, limit: number, w: number, h: number, depth: number, psb: boolean): (buffer?, string?) + local rb = Channels.rowBytes(w, depth) + local plane = bcreate(rb * h) + if w == 0 or h == 0 then + return plane, nil + end + if p + 2 > limit then + return nil, "channel data past the end" + end + local comp = readu8(src, p) * 256 + readu8(src, p + 1) + p += 2 + if comp == 0 then + if p + rb * h > limit then + return nil, "raw channel data past the end" + end + bcopy(plane, 0, src, p, rb * h) + elseif comp == 1 then + local counts, q = Channels.rleCounts(src, p, limit, h, psb) + if not counts then + return nil, "RLE row counts past the end" + end + local ok, err = Channels.rle(src, q, limit, counts, 1, h, rb, plane, 0) + if not ok then + return nil, err + end + elseif comp == 2 or comp == 3 then + local out, err = Deflate.zlib(src, p, limit - p, rb * h) + if not out then + return nil, "ZIP channel: " .. tostring(err) + end + plane = out + if comp == 3 then + unpredict(plane, w, h, depth) + end + else + return nil, "unknown channel compression " .. comp + end + return plane, nil +end + +@native local function sample8(plane: buffer, i: number, depth: number): number + if depth == 8 then + return readu8(plane, i) + elseif depth == 16 then + return floor((readu8(plane, i * 2) * 256 + readu8(plane, i * 2 + 1)) / 257 + 0.5) + elseif depth == 32 then + local f = readf32(plane, i * 4) + if f ~= f then + return 0 + end + return floor(max(0, min(1, f)) * 255 + 0.5) + end + -- 1-bit: 1 = black (whole-byte widths only; toRGBA reads bitmaps itself) + return if readu8(plane, i // 8) // 2 ^ (7 - i % 8) % 2 == 1 then 0 else 255 +end + +@native function Channels.swap32(plane: buffer) + for i = 0, blen(plane) // 4 - 1 do + writeu32(plane, i * 4, byteswap(readu32(plane, i * 4))) + end +end + +-- PSD Lab (0..255 each) to sRGB, the D50 white approximated by D65 +@native local function srgb(c: number): number + c = if c <= 0.0031308 then 12.92 * c else 1.055 * c ^ (1 / 2.4) - 0.055 + return floor(max(0, min(1, c)) * 255 + 0.5) +end +@native local function lab(l8: number, a8: number, b8: number): (number, number, number) + local L = l8 * 100 / 255 + local a, b = a8 - 128, b8 - 128 + local fy = (L + 16) / 116 + local fx = fy + a / 500 + local fz = fy - b / 200 + @native local function f(t: number): number + return if t > 6 / 29 then t * t * t else 3 * (6 / 29) ^ 2 * (t - 4 / 29) + end + local X, Y, Z = 0.95047 * f(fx), f(fy), 1.08883 * f(fz) + local r = 3.2404542 * X - 1.5371385 * Y - 0.4985314 * Z + local g = -0.969266 * X + 1.8760108 * Y + 0.041556 * Z + local bl = 0.0556434 * X - 0.2040259 * Y + 1.0572252 * Z + return srgb(r), srgb(g), srgb(bl) +end + +-- PSD colour modes: 0 bitmap, 1 grey, 2 indexed, 3 RGB, 4 CMYK, 7 multichannel, 8 duotone, 9 Lab +@native function Channels.toRGBA(planes: { [any]: buffer }, w: number, h: number, depth: number, mode: number, palette: buffer?): buffer + local n = w * h + local out = bcreate(n * 4) + local c1, c2, c3, c4 = planes[1], planes[2], planes[3], planes[4] + local alpha = planes.alpha + local bitmapW = (w + 7) // 8 + if depth == 8 and (mode == 3 or mode == 1) and c1 and blen(c1) >= n then + local g8 = if mode == 3 and c2 and blen(c2) >= n then c2 else c1 + local b8 = if mode == 3 and c3 and blen(c3) >= n then c3 else c1 + local a8 = if alpha and blen(alpha) >= n then alpha else nil + for i = 0, n - 1 do + local a = if a8 then readu8(a8, i) else 255 + writeu32(out, i * 4, readu8(c1, i) + readu8(g8, i) * 256 + readu8(b8, i) * 65536 + a * 16777216) + end + return out + end + for i = 0, n - 1 do + local r, g, b = 0, 0, 0 + if mode == 3 then + r = if c1 then sample8(c1, i, depth) else 0 + g = if c2 then sample8(c2, i, depth) else r + b = if c3 then sample8(c3, i, depth) else r + elseif mode == 4 then + local cc = if c1 then sample8(c1, i, depth) else 255 + 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 = 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 = readu8(palette, k) + g = readu8(palette, 256 + k) + b = readu8(palette, 512 + k) + else + r, g, b = k, k, k + end + elseif mode == 0 then + local y, x = i // w, i % w + local bit = if c1 then readu8(c1, y * bitmapW + x // 8) // 2 ^ (7 - x % 8) % 2 else 0 + r = if bit == 1 then 0 else 255 + g, b = r, r + elseif mode == 9 then + local L = if c1 then sample8(c1, i, depth) else 0 + local A = if c2 then sample8(c2, i, depth) else 128 + local B = if c3 then sample8(c3, i, depth) else 128 + r, g, b = lab(L, A, B) + else -- grey, duotone, multichannel: the first channel as grey + r = if c1 then sample8(c1, i, depth) else 0 + g, b = r, r + end + local a = if alpha then sample8(alpha, i, depth) else 255 + writeu32(out, i * 4, r + g * 256 + b * 65536 + a * 16777216) + end + return out +end + +@native function Channels.gray8(plane: buffer, w: number, h: number, depth: number): buffer + local n = w * h + local out = bcreate(n) + for i = 0, n - 1 do + writeu8(out, i, sample8(plane, i, depth)) + end + return out +end + +-- unmatte(rgba, n): Photoshop stores a transparent merged image matted with white (C * a + 255 * (1 - a)): undo it +@native function Channels.unmatte(rgba: buffer, n: number) + for i = 0, n - 1 do + local o = i * 4 + local a = readu8(rgba, o + 3) + if a == 0 then + writeu32(rgba, o, 0) + elseif a < 255 then + local f = a / 255 + for k = 0, 2 do + local v = (readu8(rgba, o + k) - 255 * (1 - f)) / f + writeu8(rgba, o + k, floor(max(0, min(255, v)) + 1e-6)) + end + end + end +end + +@native function Channels.matte(rgba: buffer, n: number): buffer + local out = bcreate(n * 4) + bcopy(out, 0, rgba, 0, n * 4) + for i = 0, n - 1 do + local o = i * 4 + local a = readu8(out, o + 3) + if a < 255 then + local f = a / 255 + for k = 0, 2 do + writeu8(out, o + k, floor(readu8(out, o + k) * f + 255 * (1 - f) + 0.5)) + end + end + end + return out +end + +-- ------------------------------------------------------------------------------------------------ writer helpers +@native function Channels.packRow(src: buffer, o: number, n: number, out: buffer, d: number): number + local start = d + local i = 0 + while i < n do + local v = readu8(src, o + i) + local run = 1 + while i + run < n and run < 128 and readu8(src, o + i + run) == v do + run += 1 + end + if run >= 3 then + writeu8(out, d, 257 - run) + writeu8(out, d + 1, v) + d += 2 + i += run + else + local j = i + while j < n and j - i < 128 do + if j + 2 < n and readu8(src, o + j) == readu8(src, o + j + 1) and readu8(src, o + j) == readu8(src, o + j + 2) then + break + end + j += 1 + end + local c = j - i + writeu8(out, d, c - 1) + bcopy(out, d + 1, src, o + i, c) + d += c + 1 + i = j + end + end + return d - start +end + +@native function Channels.planes8(rgba: buffer, w: number, h: number): (buffer, buffer, buffer, buffer) + local n = w * h + local r, g, b, a = bcreate(n), bcreate(n), bcreate(n), bcreate(n) + if blen(rgba) < n * 4 then + return r, g, b, a + end + for i = 0, n - 1 do + local v = readu32(rgba, i * 4) + writeu8(r, i, v % 256) + writeu8(g, i, v // 256 % 256) + writeu8(b, i, v // 65536 % 256) + writeu8(a, i, v // 16777216) + end + return r, g, b, a +end + +@native function Channels.rleChannel(plane: buffer, w: number, h: number, psb: boolean): buffer + local cs = if psb then 4 else 2 + local out = bcreate(h * cs + h * (w + w // 128 + 2)) + local d = h * cs + for y = 0, h - 1 do + local n = Channels.packRow(plane, y * w, w, out, d) + if psb then + writeu32(out, y * 4, byteswap(n)) + else + writeu16(out, y * 2, byteswap(n) // 65536) + end + d += n + end + local res = bcreate(d) + bcopy(res, 0, out, 0, d) + return res +end + +return Channels +end +end + + + + + + model_1 + --!optimize 2 +--!nocheck +-- rosetta chunk model_1 (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 19 modules (1 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["model/3ds"] = function() + +-- model/3ds: Autodesk 3D Studio chunked binary; layouts from the 3DS File Toolkit notes, assimp's importer (BSD-3, +-- reference only) and lib3ds. Supports: meshes, smoothing groups, Phong materials and maps, cameras, lights, keyframer. +-- Not supported: .prj / .mli, morph / hide tracks, TCB spline parameters, vertex colours / normals (3DS has none). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Read = __include("model/3ds/Read") +local Build = __include("model/3ds/Build") +local Write = __include("model/3ds/Write") + +-- ------------------------------------------------------------------------------------------------ contract +local ThreeDs = { + name = "3ds", + category = "model", + extensions = { "3ds" }, + mime = { "application/x-3ds", "image/x-3ds" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten", "codecs/model/Sampler" }, + caps = { decode = true, encode = true, materials = true, textures = true, animation = true, cameras = true, lights = true, instancing = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + normals: boolean?, -- default true + flipV: boolean?, -- default true + fps: number?, -- default 30 (3ds Max's default) + maxVertices: number?, -- default 2^24 +} +type EncodeOptions = { + flipV: boolean?, -- default true + fps: number?, -- default 30 + name: string?, + files: { [string]: any }?, -- receives the bytes of textures with data but no uri +} + +-- ------------------------------------------------------------------------------------------------ sniff +function ThreeDs.sniff(r: Bytes.Reader): number + local h = r:peek(8) + if #h < 8 or string.byte(h, 1) ~= 0x4D or string.byte(h, 2) ~= 0x4D then + return 0 + end + local b1, b2, b3, b4, c1, c2 = string.byte(h, 3, 8) + local size = b1 + b2 * 256 + b3 * 65536 + b4 * 16777216 + local child = c1 + c2 * 256 + if size < 16 or not (child == 0x0002 or child == 0x3D3D or child == 0xB000) then + return 0 + end + return if size == r.limit - r.pos then 0.95 else 0.7 +end + +-- ------------------------------------------------------------------------------------------------ decode +function ThreeDs.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local raw, msg, at = Read.parse(r.buf, r.base, r.limit, opts) + if not raw then + return nil, Err.from(msg, at) + end + local ok, scene = pcall(Build.scene, raw, opts :: any) + if not ok then + return nil, Err.new(Err.CORRUPT, "bad object data: " .. tostring(scene)) + end + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function ThreeDs.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(scene) ~= "table" or scene.kind ~= "scene" then + return nil, Err.new(Err.ARG, "needs a Scene") + end + local ok, out, err = pcall(Write.encode, scene, opts :: any) + if not ok then + return nil, Err.new(Err.ARG, "bad scene: " .. tostring(out)) + end + if not out then + return nil, Err.new(Err.ARG, tostring(err)) + end + return out, nil +end + +return ThreeDs +end +__FILES["model/3ds/Build"] = function() + +-- model/3ds/Build: Read's chunk tables -> Types.Scene. +-- 3DS transforms: mesh vertices are in world space and the mesh matrix (0x4160) is the object's world transform; a +-- keyframer node is parent * T(pos) * R(rot) * S(scale) and draws its mesh at node * T(-pivot) * inverse(mesh matrix) +-- (a mirroring mesh matrix also flips x, as 3ds Max writes and assimp reads). Rotation keys are clockwise axis / angle +-- deltas from the previous key. Smoothing group 0 is flat. +local Types = __include("Types") +local Mat4 = __include("codecs/model/Mat4") +local Read = __include("model/3ds/Read") + +local Build = {} + +local S = Types.Scene +local readf32, readu16, readu32, writef32, writeu32 = buffer.readf32, buffer.readu16, buffer.readu32, buffer.writef32, buffer.writeu32 +local band = bit32.band +local sqrt, abs = math.sqrt, math.abs + +type Options = { normals: boolean?, flipV: boolean?, fps: number? } + +-- ------------------------------------------------------------------------------------------------ math +local function meshMatrix(m: { number }?): { number } + if not m then + return Mat4.identity() + end + return { m[1], m[2], m[3], 0, m[4], m[5], m[6], 0, m[7], m[8], m[9], 0, m[10], m[11], m[12], 1 } +end +Build.meshMatrix = meshMatrix + +local function det3(m: { number }): number + return 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]) +end +Build.det3 = det3 + +local function qmul(a: { number }, b: { number }): { number } + local ax, ay, az, aw = a[1], a[2], a[3], a[4] + local bx, by, bz, bw = b[1], b[2], b[3], b[4] + return { + aw * bx + ax * bw + ay * bz - az * by, + aw * by - ax * bz + ay * bw + az * bx, + aw * bz + ax * by - ay * bx + az * bw, + aw * bw - ax * bx - ay * by - az * bz, + } +end +Build.qmul = qmul + +-- 3DS angles turn clockwise +local function keyQuat(angle: number, x: number, y: number, z: number): { number } + if x == 0 and y == 0 and z == 0 then + return { 0, 0, 0, 1 } + end + return Mat4.axisAngle(x, y, z, -math.deg(angle)) +end + +local function normalize(x: number, y: number, z: number): (number, number, number, number) + local l = sqrt(x * x + y * y + z * z) + if l < 1e-30 then + return 0, 0, 0, 0 + end + return x / l, y / l, z / l, l +end + +-- -Z looks from pos to target, world up +Z +function Build.lookAt(p: { number }, t: { number }, roll: number): { number } + local fx, fy, fz, l = normalize(t[1] - p[1], t[2] - p[2], t[3] - p[3]) + if l == 0 then + fx, fy, fz = 0, 1, 0 + end + local ux, uy, uz = 0, 0, 1 + if abs(fz) > 0.999999 then + ux, uy, uz = 0, 1, 0 + end + local rx, ry, rz = normalize(fy * uz - fz * uy, fz * ux - fx * uz, fx * uy - fy * ux) + ux, uy, uz = ry * fz - rz * fy, rz * fx - rx * fz, rx * fy - ry * fx + local a = math.rad(roll) + local c, s = math.cos(a), math.sin(a) + local Rx, Ry, Rz = c * rx + s * ux, c * ry + s * uy, c * rz + s * uz + local Ux, Uy, Uz = c * ux - s * rx, c * uy - s * ry, c * uz - s * rz + return Mat4.quat({ Rx, Ry, Rz, 0, Ux, Uy, Uz, 0, -fx, -fy, -fz, 0, 0, 0, 0, 1 }) +end + +-- ------------------------------------------------------------------------------------------------ accessors +local function floats(values: { number }, comps: number): Types.Accessor + local a = S.accessor(nil, "f32", comps, #values // comps) + for i = 1, (#values // comps) * comps do + writef32(a.data, (i - 1) * 4, values[i]) + end + return a +end + +-- ------------------------------------------------------------------------------------------------ materials +local MIME: { [string]: string } = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", bmp = "image/bmp", tga = "image/x-tga", gif = "image/gif", tif = "image/tiff", tiff = "image/tiff" } + +local function materials(raw: Read.Raw, scene: Types.Scene): { [string]: number } + local byName: { [string]: number } = {} + local texByFile: { [string]: number } = {} + local function texture(m: Read.Map): Types.TextureRef? + local file = m.file + if not file or file == "" then + return nil + end + local ti = texByFile[file] + if not ti then + local ext = string.lower(string.match(file, "%.(%w+)$") or "") + local tiling = m.tiling or 0 + local wrap: any = if band(tiling, 0x10) ~= 0 then "clamp" elseif band(tiling, 0x2) ~= 0 then "mirror" else "repeat" + local tex: Types.Texture = { name = file, uri = file, mime = MIME[ext] :: string?, sampler = { wrapS = wrap, wrapT = wrap } } + table.insert(scene.textures, tex) + ti = #scene.textures + texByFile[file] = ti + end + local ref: Types.TextureRef = { texture = ti } + local us, vs, uo, vo, ang = m.uscale or 1, m.vscale or 1, m.uoffset or 0, m.voffset or 0, m.angle or 0 + if us ~= 1 or vs ~= 1 or uo ~= 0 or vo ~= 0 or ang ~= 0 then + ref.transform = { scale = { us, vs }, offset = { uo, vo }, rotation = math.rad(ang) } + end + return ref + end + for i, m in raw.materials do + local mat = S.material(m.name) + local d = m.diffuse or { 0.5, 0.5, 0.5 } + local transparency = math.clamp(m.transparency or 0, 0, 1) + mat.baseColor = { d[1], d[2], d[3], 1 - transparency } + mat.metallic = 0 + mat.roughness = math.clamp(1 - (m.shininess or 0), 0, 1) + local si = m.selfIllum or 0 + if si > 0 then + mat.emissive = { d[1] * si, d[2] * si, d[3] * si } + end + mat.alphaMode = if transparency > 0 then "blend" else "opaque" + mat.doubleSided = m.twoSided + local maps: { [string]: any } = {} + for kind, mp in m.maps do + local ref = texture(mp) + maps[kind] = { file = mp.file, strength = mp.strength, tiling = mp.tiling, uscale = mp.uscale, vscale = mp.vscale, uoffset = mp.uoffset, voffset = mp.voffset, angle = mp.angle, texture = ref and ref.texture } + if kind == "diffuse" then + mat.baseColorTexture = ref + elseif kind == "selfIllum" and ref then + mat.emissiveTexture = ref + if si <= 0 then + mat.emissive = { 1, 1, 1 } + end + end + end + mat.extras = { + ["3ds"] = { + ambient = m.ambient, diffuse = m.diffuse, specular = m.specular, shininess = m.shininess, + shinStrength = m.shinStrength, transparency = m.transparency, selfIllum = m.selfIllum, + shading = m.shading, wire = m.wire, twoSided = m.twoSided, maps = maps, + }, + } + table.insert(scene.materials, mat) + local key = string.lower(m.name) + if byName[key] == nil then + byName[key] = i + end + end + return byName +end + +-- ------------------------------------------------------------------------------------------------ meshes +local function mesh(name: string, m: Read.Mesh, xf: { number }, matByName: { [string]: number }, opts: Options): Types.Mesh + local nv, nf = m.nv, m.nf + local pos, faces = m.positions, m.faces + local lp = table.create(nv * 3, 0) + for v = 0, nv - 1 do + local x, y, z = Mat4.point(xf, readf32(pos, v * 12), readf32(pos, v * 12 + 4), readf32(pos, v * 12 + 8)) + lp[v * 3 + 1], lp[v * 3 + 2], lp[v * 3 + 3] = x, y, z + end + local fa, fb, fc = table.create(nf, 0), table.create(nf, 0), table.create(nf, 0) + local valid = table.create(nf, false) + for f = 0, nf - 1 do + local a, b, c = readu16(faces :: buffer, f * 8), readu16(faces :: buffer, f * 8 + 2), readu16(faces :: buffer, f * 8 + 4) + fa[f + 1], fb[f + 1], fc[f + 1] = a, b, c + valid[f + 1] = a < nv and b < nv and c < nv + end + local fmat = table.create(nf, 0) + for _, fm in m.faceMats do + local mi = matByName[string.lower(fm.name)] or 0 + for _, f in fm.faces do + if f < nf then + fmat[f + 1] = mi + end + end + end + local smooth = m.smoothing + local doNormals = opts.normals ~= false + local fn = table.create(nf * 3, 0) + local around: { [number]: { number } } = {} + local group = table.create(nv, 0) + if doNormals then + local keyToGroup: { [string]: number } = {} + for v = 0, nv - 1 do + local k = buffer.readstring(pos, v * 12, 12) + local g = keyToGroup[k] + if not g then + g = v + keyToGroup[k] = g + end + group[v + 1] = g + end + for f = 1, nf do + if valid[f] then + local a, b, c = fa[f] * 3, fb[f] * 3, fc[f] * 3 + local e1x, e1y, e1z = lp[b + 1] - lp[a + 1], lp[b + 2] - lp[a + 2], lp[b + 3] - lp[a + 3] + local e2x, e2y, e2z = lp[c + 1] - lp[a + 1], lp[c + 2] - lp[a + 2], lp[c + 3] - lp[a + 3] + fn[f * 3 - 2], fn[f * 3 - 1], fn[f * 3] = e1y * e2z - e1z * e2y, e1z * e2x - e1x * e2z, e1x * e2y - e1y * e2x + for _, v in { fa[f], fb[f], fc[f] } do + local g = group[v + 1] + local list = around[g] + if not list then + list = {} + around[g] = list + end + if list[#list] ~= f then + table.insert(list, f) + end + end + end + end + end + local function sgOf(f: number): number + return if smooth then readu32(smooth, (f - 1) * 4) else 1 + end + local function cornerNormal(f: number, v: number, sg: number): (number, number, number) + local x, y, z = fn[f * 3 - 2], fn[f * 3 - 1], fn[f * 3] + if sg ~= 0 then + local sx, sy, sz = 0, 0, 0 + for _, g in around[group[v + 1]] do + if band(sgOf(g), sg) ~= 0 then + sx, sy, sz = sx + fn[g * 3 - 2], sy + fn[g * 3 - 1], sz + fn[g * 3] + end + end + local nx, ny, nz, l = normalize(sx, sy, sz) + if l > 0 then + return nx, ny, nz + end + end + local nx, ny, nz = normalize(x, y, z) + return nx, ny, nz + end + local order: { number } = {} + local byMat: { [number]: { number } } = {} + for f = 1, nf do + if valid[f] then + local mi = fmat[f] + if not byMat[mi] then + byMat[mi] = {} + table.insert(order, mi) + end + table.insert(byMat[mi], f) + end + end + local uvs, nuv = m.uvs, m.nuv + local flipV = opts.flipV ~= false + local out: Types.Mesh = { name = name, primitives = {} } + for _, mi in order do + local list = byMat[mi] + local remap: { [number]: number } = {} + local P: { number }, N: { number }, U: { number } = {}, {}, {} + local idx = table.create(#list * 3, 0) + local sgs = table.create(#list, 0) + local count = 0 + for i, f in list do + local sg = sgOf(f) + sgs[i] = sg + for k, v in { fa[f], fb[f], fc[f] } do + local key = if not doNormals then v elseif sg ~= 0 then v * 4294967296 + sg else -(f * 65536 + v + 1) + local o: number = remap[key] or -1 + if o < 0 then + o = count + count += 1 + remap[key] = o + P[o * 3 + 1], P[o * 3 + 2], P[o * 3 + 3] = lp[v * 3 + 1], lp[v * 3 + 2], lp[v * 3 + 3] + if doNormals then + N[o * 3 + 1], N[o * 3 + 2], N[o * 3 + 3] = cornerNormal(f, v, sg) + end + if uvs then + local u: number, w: number = 0, 0 + if v < nuv then + u = readf32(uvs, v * 8) + w = readf32(uvs, v * 8 + 4) + end + U[o * 2 + 1] = u + U[o * 2 + 2] = if flipV then 1 - w else w + end + end + idx[(i - 1) * 3 + k] = o + end + end + local ind = S.accessor(nil, "u32", 1, #idx) + for i, v in idx do + writeu32(ind.data, (i - 1) * 4, v) + end + local prim: Types.Primitive = { + attributes = { POSITION = floats(P, 3) }, + indices = ind, + mode = "triangles", + material = if mi > 0 then mi else nil, + extras = { ["3ds"] = { smoothing = sgs } }, + } + if doNormals then + prim.attributes.NORMAL = floats(N, 3) + end + if uvs then + prim.attributes.TEXCOORD_0 = floats(U, 2) + end + table.insert(out.primitives, prim) + end + return out +end + +-- ------------------------------------------------------------------------------------------------ tracks +local function evalTrack(t: Read.Track?, frame: number, default: { number }): { number } + if not t or #t.frames == 0 then + return default + end + local fr, vals, n = t.frames, t.values, t.size + local function at(k: number): { number } + local r = table.create(n, 0) + for c = 1, n do + r[c] = vals[(k - 1) * n + c] + end + return r + end + if frame <= fr[1] then + return at(1) + end + for k = 1, #fr - 1 do + local f0, f1 = fr[k], fr[k + 1] + if frame <= f1 then + local u = if f1 > f0 then (frame - f0) / (f1 - f0) else 1 + local a, b = at(k), at(k + 1) + for c = 1, n do + a[c] += (b[c] - a[c]) * u + end + return a + end + end + return at(#fr) +end + +local function first(t: Read.Track?, default: { number }): { number } + return evalTrack(t, -math.huge, default) +end + +local function scaleKey(v: { number }): { number } + return { if v[1] == 0 then 1 else v[1], if v[2] == 0 then 1 else v[2], if v[3] == 0 then 1 else v[3] } +end + +local function rotations(t: Read.Track): ({ number }, { { number } }) + local frames, quats = {}, {} + local acc: { number }? = nil + for k = 1, #t.frames do + local o = (k - 1) * 4 + local angle, x, y, z = t.values[o + 1], t.values[o + 2], t.values[o + 3], t.values[o + 4] + if acc == nil then + acc = keyQuat(angle, x, y, z) + else + local prev = acc :: { number } + local steps = math.clamp(math.ceil(abs(angle) / (math.pi * 0.9)), 1, 64) + local f0 = frames[#frames] + for s = 1, steps - 1 do + table.insert(frames, f0 + (t.frames[k] - f0) * s / steps) + table.insert(quats, qmul(prev, keyQuat(angle * s / steps, x, y, z))) + end + acc = qmul(prev, keyQuat(angle, x, y, z)) + end + local q = acc :: { number } + local n = sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3] + q[4] * q[4]) + if n > 0 then + q = { q[1] / n, q[2] / n, q[3] / n, q[4] / n } + end + acc = q + table.insert(frames, t.frames[k]) + table.insert(quats, q) + end + return frames, quats +end + +-- ------------------------------------------------------------------------------------------------ scene +function Build.scene(raw: Read.Raw, opts: Options?): Types.Scene + local o: Options = opts or {} + local fps = o.fps or 30 + local scene = S.new() + local matByName = materials(raw, scene) + local objByName: { [string]: Read.Object } = {} + for _, obj in raw.objects do + if objByName[obj.name] == nil then + objByName[obj.name] = obj + end + local low = string.lower(obj.name) + if objByName[low] == nil then + objByName[low] = obj + end + end + local function findObj(name: string): Read.Object? + return objByName[name] or objByName[string.lower(name)] + end + local meshCache: { [any]: number } = {} + local function meshOf(obj: Read.Object, pivot: { number }?, placed: boolean): number? + local m = obj.mesh + if not m or m.nf == 0 or not m.faces then + return nil + end + local pv = pivot or { 0, 0, 0 } + local key = obj.name .. (if placed then string.format("|%.9g|%.9g|%.9g", pv[1], pv[2], pv[3]) else "|free") + if meshCache[key] then + return meshCache[key] + end + local M = meshMatrix(m.matrix) + local inv = Mat4.inverse(M) or Mat4.identity() + local xf = inv + if placed then + if det3(M) < 0 then + xf = Mat4.mul(Mat4.scaling(-1, 1, 1), xf) + end + xf = Mat4.mul(Mat4.translation(-pv[1], -pv[2], -pv[3]), xf) + end + local me = mesh(obj.name, m, xf, matByName, o) + if #me.primitives == 0 then + return nil + end + table.insert(scene.meshes, me) + meshCache[key] = #scene.meshes + return #scene.meshes + end + local camIndex: { [Read.Object]: number } = {} + local function cameraOf(obj: Read.Object): number + if camIndex[obj] then + return camIndex[obj] + end + local c = obj.camera :: Read.Camera + local hfov = if c.lens > 1e-3 then 2400 / c.lens else 45 + hfov = math.clamp(hfov, 0.01, 179) + local aspect = 4 / 3 + local yfov = 2 * math.atan(math.tan(math.rad(hfov) / 2) / aspect) + local near = if c.near and c.near > 0 then c.near else 0.1 + local far = if c.far and c.far > near then c.far else nil + local cam: Types.Camera = { name = obj.name, type = "perspective", yfov = yfov, aspect = aspect, znear = near, zfar = far } + table.insert(scene.cameras, cam) + camIndex[obj] = #scene.cameras + return #scene.cameras + end + local lightIndex: { [Read.Object]: number } = {} + local function lightOf(obj: Read.Object): number + if lightIndex[obj] then + return lightIndex[obj] + end + local l = obj.light :: Read.Light + local L: Types.Light = { name = obj.name, type = "point", color = { l.color[1], l.color[2], l.color[3] }, intensity = l.multiplier } + if l.spot then + L.type = "spot" + local hot = math.clamp(l.spot.hotspot, 0, 179.9) + local fall = math.clamp(math.max(l.spot.falloff, hot), 0, 179.9) + L.innerCone, L.outerCone = math.rad(hot) / 2, math.rad(fall) / 2 + end + if l.attenuate and l.outer and l.outer > 0 then + L.range = l.outer + end + table.insert(scene.lights, L) + lightIndex[obj] = #scene.lights + return #scene.lights + end + + local kf = raw.keyframer + local kfNodes = if kf then kf.nodes else {} + local targets: { [string]: Read.Node } = {} + for _, n in kfNodes do + if n.kind == "target" or n.kind == "lightTarget" then + targets[n.name] = targets[n.name] or n + end + end + local placedObj: { [Read.Object]: boolean } = {} + local sceneOf: { [number]: number } = {} + local channels: { Types.Channel } = {} + local function channel(node: number, path: any, times: { number }, values: { number }, comps: number) + for i = 1, #times do + times[i] /= fps + end + local ch: Types.Channel = { node = node, path = path, input = floats(times, 1), output = floats(values, comps), interpolation = "LINEAR" } + table.insert(channels, ch) + end + local function addNode(n: Types.Node, parent: number?): number + table.insert(scene.nodes, n) + local i = #scene.nodes + if parent then + table.insert(scene.nodes[parent].children, i) + else + table.insert(scene.roots, i) + end + return i + end + + for k, kn in kfNodes do + local kind = kn.kind + if kind == "target" or kind == "lightTarget" or kind == "ambient" then + continue + end + local id = kn.id or (k - 1) + local parent = if kn.parent >= 0 then sceneOf[kn.parent] else nil + local obj = findObj(kn.name) + local tr = kn.tracks + local name = if kn.instance and kn.instance ~= "" then kn.instance else kn.name + local node: Types.Node = { name = name, children = {} } + local x3ds: { [string]: any } = { kind = kind, object = kn.name, id = id, pivot = kn.pivot } + node.extras = { ["3ds"] = x3ds } + local animated = false + if kind == "object" then + if obj and obj.mesh then + node.mesh = meshOf(obj, kn.pivot, true) + placedObj[obj] = true + x3ds.hidden = obj.hidden or nil + end + node.translation = first(tr.pos, { 0, 0, 0 }) + node.rotation = if tr.rot and #tr.rot.frames > 0 then (select(2, rotations(tr.rot)) :: any)[1] else { 0, 0, 0, 1 } + node.scale = scaleKey(first(tr.scl, { 1, 1, 1 })) + local ni = addNode(node, parent) + sceneOf[id] = ni + if tr.pos and #tr.pos.frames > 1 then + channel(ni, "translation", table.clone(tr.pos.frames), table.clone(tr.pos.values), 3) + end + if tr.rot and #tr.rot.frames > 1 then + local frames, quats = rotations(tr.rot) + local vals = {} + for _, q in quats do + table.move(q, 1, 4, #vals + 1, vals) + end + channel(ni, "rotation", frames, vals, 4) + end + if tr.scl and #tr.scl.frames > 1 then + local vals = {} + for i = 1, #tr.scl.frames do + local v = scaleKey({ tr.scl.values[i * 3 - 2], tr.scl.values[i * 3 - 1], tr.scl.values[i * 3] }) + table.move(v, 1, 3, #vals + 1, vals) + end + channel(ni, "scale", table.clone(tr.scl.frames), vals, 3) + end + else + local isCam = kind == "camera" + local cam = if obj and isCam then obj.camera else nil + local lit = if obj and not isCam then obj.light else nil + local tgt = targets[kn.name] + local basePos = if cam then cam.pos elseif lit then lit.pos else { 0, 0, 0 } + local baseTgt = if cam then cam.target elseif lit and lit.spot then lit.spot.target else nil + local aims = isCam or kind == "spot" or baseTgt ~= nil + local function pose(frame: number): ({ number }, { number }?) + local p = evalTrack(tr.pos, frame, basePos) + if not aims then + return p, nil + end + local t = evalTrack(tgt and tgt.tracks.pos, frame, baseTgt or { p[1], p[2] + 1, p[3] }) + local roll = evalTrack(tr.roll, frame, { if cam then cam.roll else 0 })[1] + return p, Build.lookAt(p, t, roll) + end + local p0, r0 = pose(-math.huge) + node.translation, node.rotation = p0, r0 + if cam then + node.camera = cameraOf(obj :: Read.Object) + placedObj[obj :: Read.Object] = true + x3ds.lens, x3ds.roll = cam.lens, cam.roll + elseif lit then + node.light = lightOf(obj :: Read.Object) + placedObj[obj :: Read.Object] = true + x3ds.off = lit.off or nil + end + local ni = addNode(node, parent) + sceneOf[id] = ni + local set: { [number]: boolean } = {} + local times: { number } = {} + for _, t in { tr.pos, tr.roll, if aims and tgt then tgt.tracks.pos else nil } do + if t and #t.frames > 1 then + animated = true + end + for _, f in (if t then t.frames else {}) :: { number } do + if not set[f] then + set[f] = true + table.insert(times, f) + end + end + end + if animated then + table.sort(times) + local tv, rv = {}, {} + for _, f in times do + local p, r = pose(f) + table.move(p, 1, 3, #tv + 1, tv) + if r then + table.move(r, 1, 4, #rv + 1, rv) + end + end + channel(ni, "translation", table.clone(times), tv, 3) + if aims then + channel(ni, "rotation", times, rv, 4) + end + end + end + end + for _, obj in raw.objects do + if placedObj[obj] then + continue + end + local node: Types.Node = { name = obj.name, children = {}, extras = { ["3ds"] = { object = obj.name, hidden = obj.hidden or nil } } } + if obj.mesh then + local mi = meshOf(obj, nil, false) + if not mi then + continue + end + node.mesh = mi + if obj.mesh.matrix then + node.matrix = meshMatrix(obj.mesh.matrix) + end + elseif obj.camera then + local c = obj.camera + node.camera = cameraOf(obj) + node.translation, node.rotation = c.pos, Build.lookAt(c.pos, c.target, c.roll) + elseif obj.light then + local l = obj.light + node.light = lightOf(obj) + node.translation = l.pos + if l.spot then + node.rotation = Build.lookAt(l.pos, l.spot.target, 0) + end + else + continue + end + addNode(node, nil) + end + if #channels > 0 then + table.insert(scene.animations, { name = kf and kf.name or "3ds", channels = channels }) + end + scene.meta.up = "z" + scene.meta.source = { + format = "3ds", + version = raw.version, + meshVersion = raw.meshVersion, + masterScale = raw.masterScale, + ambient = raw.ambient, + keyframer = kf ~= nil, + frames = if kf and kf.first then { kf.first, kf.last } else nil, + fps = fps, + } + return scene +end + +return Build +end +__FILES["model/3ds/Read"] = function() + +-- model/3ds/Read: the 3DS chunk tree (u16 id, u32 size including the 6-byte header, little endian) -> plain tables. +-- Unknown chunks are skipped; a chunk past the end of the data is an error, one past its parent is clipped to it. +local Read = {} + +local readu8, readu16, readu32, readi16, readf32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi16, buffer.readf32 +local band = bit32.band + +-- ------------------------------------------------------------------------------------------------ chunk ids +local C = { + MAIN = 0x4D4D, VERSION = 0x0002, EDITOR = 0x3D3D, MESH_VERSION = 0x3D3E, MASTER_SCALE = 0x0100, + RGBF = 0x0010, RGBB = 0x0011, LIN_RGBB = 0x0012, LIN_RGBF = 0x0013, PERCENTW = 0x0030, PERCENTF = 0x0031, + AMBIENT_LIGHT = 0x2100, OBJECT = 0x4000, TRIMESH = 0x4100, VERTICES = 0x4110, FACES = 0x4120, FACE_MAT = 0x4130, + UVS = 0x4140, SMOOTH = 0x4150, MATRIX = 0x4160, LIGHT = 0x4600, SPOT = 0x4610, LIGHT_OFF = 0x4620, + ATTENUATE = 0x4625, INNER_RANGE = 0x4659, OUTER_RANGE = 0x465A, MULTIPLIER = 0x465B, CAMERA = 0x4700, + CAM_RANGES = 0x4720, OBJ_HIDDEN = 0x4010, + MATERIAL = 0xAFFF, MAT_NAME = 0xA000, MAT_AMBIENT = 0xA010, MAT_DIFFUSE = 0xA020, MAT_SPECULAR = 0xA030, + MAT_SHININESS = 0xA040, MAT_SHIN_STRENGTH = 0xA041, MAT_TRANSPARENCY = 0xA050, MAT_SELF_ILPCT = 0xA084, + MAT_TWO_SIDE = 0xA081, MAT_WIRE = 0xA085, MAT_SHADING = 0xA100, MAP_FILE = 0xA300, MAP_TILING = 0xA351, + MAP_USCALE = 0xA354, MAP_VSCALE = 0xA356, MAP_UOFFSET = 0xA358, MAP_VOFFSET = 0xA35A, MAP_ANGLE = 0xA35C, + KEYFRAMER = 0xB000, KF_HDR = 0xB00A, KF_FRAMES = 0xB008, NODE_HDR = 0xB010, NODE_INSTANCE = 0xB011, + NODE_PIVOT = 0xB013, NODE_ID = 0xB030, TRACK_POS = 0xB020, TRACK_ROT = 0xB021, TRACK_SCALE = 0xB022, + TRACK_FOV = 0xB023, TRACK_ROLL = 0xB024, TRACK_COLOR = 0xB025, TRACK_HOTSPOT = 0xB027, TRACK_FALLOFF = 0xB028, +} +Read.C = C + +Read.MAPS = { + [0xA200] = "diffuse", [0xA33A] = "diffuse2", [0xA210] = "opacity", [0xA230] = "bump", [0xA204] = "specular", + [0xA33C] = "shininess", [0xA33D] = "selfIllum", [0xA220] = "reflection", +} +local NODE_KINDS = { + [0xB001] = "ambient", [0xB002] = "object", [0xB003] = "camera", [0xB004] = "target", [0xB005] = "light", + [0xB006] = "lightTarget", [0xB007] = "spot", +} +local TRACKS: { [number]: { any } } = { + [0xB020] = { "pos", 3 }, [0xB021] = { "rot", 4 }, [0xB022] = { "scl", 3 }, [0xB023] = { "fov", 1 }, + [0xB024] = { "roll", 1 }, [0xB025] = { "color", 3 }, [0xB027] = { "hotspot", 1 }, [0xB028] = { "falloff", 1 }, +} + +-- ------------------------------------------------------------------------------------------------ types +type Map = { file: string?, strength: number?, tiling: number?, uscale: number?, vscale: number?, uoffset: number?, voffset: number?, angle: number? } +type Material = { + name: string, + ambient: { number }?, diffuse: { number }?, specular: { number }?, + shininess: number?, shinStrength: number?, transparency: number?, selfIllum: number?, -- fractions 0..1 + twoSided: boolean, wire: boolean, shading: number?, + maps: { [string]: Map }, +} +type Mesh = { + nv: number, positions: buffer, -- nv * 3 f32 (world space) + nuv: number, uvs: buffer?, -- nuv * 2 f32 + nf: number, faces: buffer?, -- nf * 4 u16 (a, b, c, flags) + faceMats: { { name: string, faces: { number } } }, -- 0-based face numbers + smoothing: buffer?, -- nf u32 + matrix: { number }?, -- 12 floats: X, Y, Z axes, origin (world space) +} +type Camera = { pos: { number }, target: { number }, roll: number, lens: number, near: number?, far: number? } +type Light = { + pos: { number }, color: { number }, multiplier: number, off: boolean, attenuate: boolean, + inner: number?, outer: number?, spot: { target: { number }, hotspot: number, falloff: number }?, +} +type Object = { name: string, hidden: boolean, mesh: Mesh?, camera: Camera?, light: Light? } +type Track = { frames: { number }, values: { number }, size: number, flags: number } +type Node = { + kind: string, id: number?, name: string, parent: number, flags: number, instance: string?, pivot: { number }?, + tracks: { [string]: Track }, +} +type Raw = { + version: number?, meshVersion: number?, masterScale: number?, ambient: { number }?, + materials: { Material }, objects: { Object }, + keyframer: { name: string?, length: number?, first: number?, last: number?, nodes: { Node } }?, + vertices: number, +} + +-- ------------------------------------------------------------------------------------------------ helpers +type Ctx = { b: buffer, limit: number, maxVertices: number, raw: Raw } + +local function each(ctx: Ctx, p: number, stop: number, fn: (number, number, number) -> (string?, number?)): (string?, number?) + local b = ctx.b + while p + 6 <= stop do + local id, size = readu16(b, p), readu32(b, p + 2) + if size < 6 then + return nil, nil + end + local e = p + size + if e > ctx.limit then + return string.format("chunk 0x%04x runs past the end of the data", id), p + end + local err, at = fn(id, p + 6, math.min(e, stop)) + if err then + return err, at + end + p = e + end + return nil, nil +end + +local function cstring(b: buffer, p: number, stop: number): (string?, number) + for q = p, stop - 1 do + if readu8(b, q) == 0 then + return buffer.readstring(b, p, q - p), q + 1 + end + end + return nil, stop +end + +local function vec3(b: buffer, p: number): { number } + return { readf32(b, p), readf32(b, p + 4), readf32(b, p + 8) } +end + +-- colour chunks: the first float or byte colour (the gamma-corrected variants only when nothing else) +local function color(ctx: Ctx, p: number, stop: number): { number }? + local b = ctx.b + local main: { number }?, lin: { number }? = nil, nil + each(ctx, p, stop, function(id: number, q: number, e: number): (string?, number?) + if (id == C.RGBF or id == C.LIN_RGBF) and e - q >= 12 then + local c = vec3(b, q) + if id == C.RGBF then + main = main or c + else + lin = lin or c + end + elseif (id == C.RGBB or id == C.LIN_RGBB) and e - q >= 3 then + local c = { readu8(b, q) / 255, readu8(b, q + 1) / 255, readu8(b, q + 2) / 255 } + if id == C.RGBB then + main = main or c + else + lin = lin or c + end + end + return nil, nil + end) + return main or lin +end + +local function percent(ctx: Ctx, p: number, stop: number): number? + local b = ctx.b + local v: number? = nil + each(ctx, p, stop, function(id: number, q: number, e: number): (string?, number?) + if v == nil and id == C.PERCENTW and e - q >= 2 then + v = readu16(b, q) / 100 + elseif v == nil and id == C.PERCENTF and e - q >= 4 then + v = readf32(b, q) / 100 + end + return nil, nil + end) + return v +end + +-- ------------------------------------------------------------------------------------------------ materials +local function map(ctx: Ctx, p: number, stop: number): Map + local b = ctx.b + local m: Map = {} + m.strength = percent(ctx, p, stop) + each(ctx, p, stop, function(id: number, q: number, e: number): (string?, number?) + local n = e - q + if id == C.MAP_FILE then + m.file = cstring(b, q, e) + elseif id == C.MAP_TILING and n >= 2 then + m.tiling = readu16(b, q) + elseif n >= 4 then + local v = readf32(b, q) + if id == C.MAP_USCALE then + m.uscale = v + elseif id == C.MAP_VSCALE then + m.vscale = v + elseif id == C.MAP_UOFFSET then + m.uoffset = v + elseif id == C.MAP_VOFFSET then + m.voffset = v + elseif id == C.MAP_ANGLE then + m.angle = v + end + end + return nil, nil + end) + return m +end + +local function material(ctx: Ctx, p: number, stop: number) + local b = ctx.b + local m: Material = { name = "", twoSided = false, wire = false, maps = {} } + each(ctx, p, stop, function(id: number, q: number, e: number): (string?, number?) + if id == C.MAT_NAME then + m.name = cstring(b, q, e) or "" + elseif id == C.MAT_AMBIENT then + m.ambient = color(ctx, q, e) + elseif id == C.MAT_DIFFUSE then + m.diffuse = color(ctx, q, e) + elseif id == C.MAT_SPECULAR then + m.specular = color(ctx, q, e) + elseif id == C.MAT_SHININESS then + m.shininess = percent(ctx, q, e) + elseif id == C.MAT_SHIN_STRENGTH then + m.shinStrength = percent(ctx, q, e) + elseif id == C.MAT_TRANSPARENCY then + m.transparency = percent(ctx, q, e) + elseif id == C.MAT_SELF_ILPCT then + m.selfIllum = percent(ctx, q, e) + elseif id == C.MAT_TWO_SIDE then + m.twoSided = true + elseif id == C.MAT_WIRE then + m.wire = true + elseif id == C.MAT_SHADING and e - q >= 2 then + m.shading = readu16(b, q) + elseif Read.MAPS[id] then + m.maps[Read.MAPS[id]] = map(ctx, q, e) + end + return nil, nil + end) + table.insert(ctx.raw.materials, m) +end + +-- ------------------------------------------------------------------------------------------------ objects +local function faceList(ctx: Ctx, mesh: Mesh, p: number, stop: number): (string?, number?) + local b = ctx.b + if stop - p < 2 then + return "truncated face list", p + end + local nf = readu16(b, p) + if p + 2 + nf * 8 > stop then + return "face list runs past its chunk", p + end + local faces = buffer.create(nf * 8) + buffer.copy(faces, 0, b, p + 2, nf * 8) + mesh.nf, mesh.faces = nf, faces + return each(ctx, p + 2 + nf * 8, stop, function(id: number, q: number, e: number): (string?, number?) + if id == C.FACE_MAT then + local name, r = cstring(b, q, e) + if not name or r + 2 > e then + return "bad face material list", q + end + local n = readu16(b, r) + if r + 2 + n * 2 > e then + return "face material list runs past its chunk", q + end + local list: { number } = {} + for i = 0, n - 1 do + list[i + 1] = readu16(b, r + 2 + i * 2) + end + table.insert(mesh.faceMats, { name = name, faces = list }) + elseif id == C.SMOOTH then + local n = math.min(nf, (e - q) // 4) + local s = buffer.create(nf * 4) + buffer.copy(s, 0, b, q, n * 4) + mesh.smoothing = s + end + return nil, nil + end) +end + +local function trimesh(ctx: Ctx, p: number, stop: number): (Mesh?, string?, number?) + local b = ctx.b + local mesh: Mesh = { nv = 0, positions = buffer.create(0), nuv = 0, nf = 0, faceMats = {} } + local err, at = each(ctx, p, stop, function(id: number, q: number, e: number): (string?, number?) + if id == C.VERTICES or id == C.UVS then + if e - q < 2 then + return "truncated vertex list", q + end + local n = readu16(b, q) + local size = if id == C.VERTICES then 12 else 8 + if q + 2 + n * size > e then + return "vertex list runs past its chunk", q + end + local data = buffer.create(n * size) + buffer.copy(data, 0, b, q + 2, n * size) + if id == C.VERTICES then + ctx.raw.vertices += n + if ctx.raw.vertices > ctx.maxVertices then + return "limit: more than " .. ctx.maxVertices .. " vertices", q + end + mesh.nv, mesh.positions = n, data + else + mesh.nuv, mesh.uvs = n, data + end + elseif id == C.FACES then + return faceList(ctx, mesh, q, e) + elseif id == C.MATRIX and e - q >= 48 then + local m: { number } = {} + for i = 0, 11 do + m[i + 1] = readf32(b, q + i * 4) + end + mesh.matrix = m + end + return nil, nil + end) + if err then + return nil, err, at + end + return mesh, nil, nil +end + +local function camera(ctx: Ctx, p: number, stop: number): Camera? + local b = ctx.b + if stop - p < 32 then + return nil + end + local cam: Camera = { pos = vec3(b, p), target = vec3(b, p + 12), roll = readf32(b, p + 24), lens = readf32(b, p + 28) } + each(ctx, p + 32, stop, function(id: number, q: number, e: number): (string?, number?) + if id == C.CAM_RANGES and e - q >= 8 then + cam.near, cam.far = readf32(b, q), readf32(b, q + 4) + end + return nil, nil + end) + return cam +end + +local function light(ctx: Ctx, p: number, stop: number): Light? + local b = ctx.b + if stop - p < 12 then + return nil + end + local l: Light = { pos = vec3(b, p), color = { 1, 1, 1 }, multiplier = 1, off = false, attenuate = false } + l.color = color(ctx, p + 12, stop) or l.color + each(ctx, p + 12, stop, function(id: number, q: number, e: number): (string?, number?) + local n = e - q + if id == C.SPOT and n >= 20 then + l.spot = { target = vec3(b, q), hotspot = readf32(b, q + 12), falloff = readf32(b, q + 16) } + elseif id == C.LIGHT_OFF then + l.off = true + elseif id == C.ATTENUATE then + l.attenuate = true + elseif id == C.MULTIPLIER and n >= 4 then + l.multiplier = readf32(b, q) + elseif id == C.INNER_RANGE and n >= 4 then + l.inner = readf32(b, q) + elseif id == C.OUTER_RANGE and n >= 4 then + l.outer = readf32(b, q) + end + return nil, nil + end) + return l +end + +local function object(ctx: Ctx, p: number, stop: number): (string?, number?) + local b = ctx.b + local name, q = cstring(b, p, stop) + if not name then + return "object without a name", p + end + local obj: Object = { name = name, hidden = false } + local err, at = each(ctx, q, stop, function(id: number, r: number, e: number): (string?, number?) + if id == C.TRIMESH then + local mesh, merr, mat = trimesh(ctx, r, e) + if not mesh then + return merr, mat + end + obj.mesh = mesh + elseif id == C.CAMERA then + obj.camera = camera(ctx, r, e) + elseif id == C.LIGHT then + obj.light = light(ctx, r, e) + elseif id == C.OBJ_HIDDEN then + obj.hidden = true + end + return nil, nil + end) + if err then + return err, at + end + table.insert(ctx.raw.objects, obj) + return nil, nil +end + +-- ------------------------------------------------------------------------------------------------ keyframer +-- a track: u16 flags, 8 unused bytes, u32 keys; each key: u32 frame, u16 spline flags (+ one f32 per set bit of +-- tension / continuity / bias / ease to / ease from), then the values +local function track(b: buffer, p: number, stop: number, size: number): Track? + if stop - p < 14 then + return nil + end + local flags, n = readu16(b, p), readu32(b, p + 10) + local t: Track = { frames = {}, values = {}, size = size, flags = flags } + p += 14 + for _ = 1, n do + if p + 6 > stop then + break + end + local frame, spline = readu32(b, p), readu16(b, p + 4) + p += 6 + for bit = 0, 4 do + if band(spline, bit32.lshift(1, bit)) ~= 0 then + p += 4 + end + end + if p + size * 4 > stop then + break + end + table.insert(t.frames, frame) + for k = 0, size - 1 do + table.insert(t.values, readf32(b, p + k * 4)) + end + p += size * 4 + end + return t +end + +local function node(ctx: Ctx, kind: string, p: number, stop: number, list: { Node }) + local b = ctx.b + local n: Node = { kind = kind, name = "", parent = -1, flags = 0, tracks = {} } + each(ctx, p, stop, function(id: number, q: number, e: number): (string?, number?) + if id == C.NODE_ID and e - q >= 2 then + n.id = readu16(b, q) + elseif id == C.NODE_HDR then + local name, r = cstring(b, q, e) + n.name = name or "" + if r + 6 <= e then + n.flags = readu16(b, r) + n.parent = readi16(b, r + 4) + end + elseif id == C.NODE_INSTANCE then + n.instance = cstring(b, q, e) + elseif id == C.NODE_PIVOT and e - q >= 12 then + n.pivot = vec3(b, q) + elseif TRACKS[id] then + local spec = TRACKS[id] + n.tracks[spec[1]] = track(b, q, e, spec[2]) + end + return nil, nil + end) + table.insert(list, n) +end + +local function keyframer(ctx: Ctx, p: number, stop: number) + local b = ctx.b + local kf = { nodes = {} :: { Node }, name = nil :: string?, length = nil :: number?, first = nil :: number?, last = nil :: number? } + each(ctx, p, stop, function(id: number, q: number, e: number): (string?, number?) + if id == C.KF_HDR and e - q >= 2 then + local name, r = cstring(b, q + 2, e) + kf.name = name + if r + 4 <= e then + kf.length = readu32(b, r) + end + elseif id == C.KF_FRAMES and e - q >= 8 then + kf.first, kf.last = readu32(b, q), readu32(b, q + 4) + elseif NODE_KINDS[id] then + node(ctx, NODE_KINDS[id], q, e, kf.nodes) + end + return nil, nil + end) + ctx.raw.keyframer = kf +end + +-- ------------------------------------------------------------------------------------------------ parse +local function editor(ctx: Ctx, p: number, stop: number): (string?, number?) + local b = ctx.b + return each(ctx, p, stop, function(id: number, q: number, e: number): (string?, number?) + if id == C.MATERIAL then + material(ctx, q, e) + elseif id == C.OBJECT then + return object(ctx, q, e) + elseif id == C.MESH_VERSION and e - q >= 4 then + ctx.raw.meshVersion = readu32(b, q) + elseif id == C.MASTER_SCALE and e - q >= 4 then + ctx.raw.masterScale = readf32(b, q) + elseif id == C.AMBIENT_LIGHT then + ctx.raw.ambient = color(ctx, q, e) + elseif id == C.KEYFRAMER then + keyframer(ctx, q, e) -- some writers nest it here + end + return nil, nil + end) +end + +function Read.parse(b: buffer, base: number, limit: number, opts: any?): (Raw?, string?, number?) + if limit - base < 6 or readu16(b, base) ~= C.MAIN then + return nil, "not a 3DS file (no 0x4D4D main chunk)", base + end + local raw: Raw = { materials = {}, objects = {}, vertices = 0 } + local ctx: Ctx = { b = b, limit = limit, maxVertices = opts and opts.maxVertices or 2 ^ 24, raw = raw } + local size = readu32(b, base + 2) + if size < 6 then + return nil, "bad main chunk size", base + end + if base + size > limit then + return nil, "truncated: the main chunk runs past the end of the data", base + end + local err, at = each(ctx, base + 6, base + size, function(id: number, q: number, e: number): (string?, number?) + if id == C.VERSION and e - q >= 4 then + raw.version = readu32(b, q) + elseif id == C.EDITOR then + return editor(ctx, q, e) + elseif id == C.KEYFRAMER then + keyframer(ctx, q, e) + end + return nil, nil + end) + if err then + return nil, err, at + end + return raw, nil, nil +end + +return Read +end +__FILES["model/3ds/Write"] = function() + +-- model/3ds/Write: Types.Scene -> 3DS. Objects split at 65535 vertices / faces; mirroring nodes written as 3ds Max does +-- (positive keyframer transform, mirror in the mesh matrix). +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Sampler = __include("codecs/model/Sampler") +local Mat4 = __include("codecs/model/Mat4") +local Flatten = __include("codecs/model/MeshFlatten") +local Read = __include("model/3ds/Read") +local Build = __include("model/3ds/Build") + +local Write = {} + +local C = Read.C +local S = Types.Scene +local writeu32 = buffer.writeu32 +local sqrt, abs = math.sqrt, math.abs + +type Options = { flipV: boolean?, fps: number?, name: string?, files: { [string]: any }?, smoothing: boolean? } + +-- ------------------------------------------------------------------------------------------------ chunks +type W = Bytes.Writer +local function open(w: W, id: number): number + local at = w.pos + w:u16le(id) + w:u32le(0) + return at +end +local function close(w: W, at: number) + writeu32(w.buf, at + 2, w.pos - at) +end +local function leaf(w: W, id: number, fn: () -> ()) + local at = open(w, id) + fn() + close(w, at) +end +local function name(s: string?, fallback: string): string + local n = string.gsub(s or "", "%z", "") + if n == "" then + n = fallback + end + return string.sub(n, 1, 63) +end + +local function colorChunk(w: W, id: number, c: { number }) + leaf(w, id, function() + leaf(w, C.RGBF, function() + for k = 1, 3 do + w:f32le(c[k] or 0) + end + end) + leaf(w, C.RGBB, function() + for k = 1, 3 do + w:u8(math.clamp(math.floor((c[k] or 0) * 255 + 0.5), 0, 255)) + end + end) + end) +end +local function percentChunk(w: W, id: number, v: number) + leaf(w, id, function() + leaf(w, C.PERCENTW, function() + w:u16le(math.clamp(math.floor(v * 100 + 0.5), 0, 100)) + end) + leaf(w, C.PERCENTF, function() + w:f32le(v * 100) + end) + end) +end + +-- ------------------------------------------------------------------------------------------------ math +local function world(scene: Types.Scene): ({ [number]: { number } }, { [number]: number }, { number }) + local W: { [number]: { number } } = {} + local parent: { [number]: number } = {} + local order: { number } = {} + local function visit(i: number, p: number?, pm: { number }, depth: number) + local n = scene.nodes[i] + if type(n) ~= "table" or W[i] or depth > 256 then + return + end + W[i] = S.mul(pm, S.nodeMatrix(n)) + parent[i] = p or 0 + table.insert(order, i) + for _, c in n.children or {} do + visit(c, i, W[i], depth + 1) + end + end + for _, r in scene.roots do + visit(r, nil, S.IDENTITY, 0) + end + return W, parent, order +end + +local function col(m: { number }, c: number): (number, number, number) + return m[c * 4 + 1], m[c * 4 + 2], m[c * 4 + 3] +end +local function unit(x: number, y: number, z: number): (number, number, number) + local l = sqrt(x * x + y * y + z * z) + if l < 1e-30 then + return 0, 0, 0 + end + return x / l, y / l, z / l +end + +local function axisAngle(q: { number }): (number, number, number, number) + local x, y, z, w = q[1], q[2], q[3], q[4] + local n = sqrt(x * x + y * y + z * z + w * w) + if n < 1e-30 then + return 0, 0, 0, 0 + end + x, y, z, w = x / n, y / n, z / n, w / n + local s = sqrt(x * x + y * y + z * z) + if s < 1e-12 then + return 0, 0, 0, 0 + end + local angle = 2 * math.atan2(s, w) + return -angle, x / s, y / s, z / s +end + +local function conj(q: { number }): { number } + return { -q[1], -q[2], -q[3], q[4] } +end + +local function sample(ch: Types.Channel, t: number): { number } + local f = Sampler.channel(ch) + if not f then + return if ch.path == "rotation" then { 0, 0, 0, 1 } else { 0, 0, 0 } + end + return f(t) +end + +-- ------------------------------------------------------------------------------------------------ materials +local EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/bmp"] = "bmp", ["image/gif"] = "gif", ["image/x-tga"] = "tga", ["image/webp"] = "webp" } + +local function textureFiles(scene: Types.Scene, opts: Options): { [number]: string } + local files = opts.files + local base = string.match(opts.name or "", "([^/\\]-)%.[^.]*$") or "texture" + local out: { [number]: string } = {} + for i, tex in scene.textures do + local file = tex.uri + if not file or file == "" or string.sub(file, 1, 5) == "data:" then + file = string.format("%s_%d.%s", base, i, EXT[tex.mime or ""] or "png") + if tex.data and type(files) == "table" then + files[file] = tex.data + end + end + out[i] = file + end + return out +end + +local MAP_IDS: { [string]: number } = {} +for id, kind in Read.MAPS do + MAP_IDS[kind] = id +end +local MAP_ORDER = { "diffuse", "diffuse2", "opacity", "bump", "specular", "shininess", "selfIllum", "reflection" } + +local function writeMaterial(w: W, m: Types.Material, mname: string, files: { [number]: string }) + local x = (m.extras and m.extras["3ds"] or {}) :: { [string]: any } + local bc = m.baseColor or { 1, 1, 1, 1 } + local diffuse = { bc[1], bc[2], bc[3] } + local shininess = math.clamp(1 - (m.roughness or 1), 0, 1) + local transparency = math.clamp(1 - (bc[4] or 1), 0, 1) + local e = m.emissive or { 0, 0, 0 } + local selfIllum = math.clamp(math.max(e[1], e[2], e[3]), 0, 1) + local at = open(w, C.MATERIAL) + leaf(w, C.MAT_NAME, function() + w:cstring(mname) + end) + colorChunk(w, C.MAT_AMBIENT, x.ambient or diffuse) + colorChunk(w, C.MAT_DIFFUSE, diffuse) + colorChunk(w, C.MAT_SPECULAR, x.specular or { 0.5, 0.5, 0.5 }) + percentChunk(w, C.MAT_SHININESS, shininess) + percentChunk(w, C.MAT_SHIN_STRENGTH, x.shinStrength or 0.5) + percentChunk(w, C.MAT_TRANSPARENCY, transparency) + percentChunk(w, C.MAT_SELF_ILPCT, x.selfIllum or selfIllum) + leaf(w, C.MAT_SHADING, function() + w:u16le(x.shading or 3) + end) + if m.doubleSided then + leaf(w, C.MAT_TWO_SIDE, function() end) + end + if x.wire then + leaf(w, C.MAT_WIRE, function() end) + end + local maps: { [string]: any } = {} + local function fromRef(ref: Types.TextureRef?, saved: any): any + if not ref or not files[ref.texture] then + return nil + end + local s = saved or {} + local tf = ref.transform + return { + file = files[ref.texture], strength = s.strength or 1, tiling = s.tiling, + uscale = if tf and tf.scale then tf.scale[1] else s.uscale, vscale = if tf and tf.scale then tf.scale[2] else s.vscale, + uoffset = if tf and tf.offset then tf.offset[1] else s.uoffset, voffset = if tf and tf.offset then tf.offset[2] else s.voffset, + angle = if tf and tf.rotation then math.deg(tf.rotation) else s.angle, + } + end + local saved = (x.maps or {}) :: { [string]: any } + maps.diffuse = fromRef(m.baseColorTexture, saved.diffuse) + maps.selfIllum = fromRef(m.emissiveTexture, saved.selfIllum) + for kind, s in saved do + if maps[kind] == nil and kind ~= "diffuse" and kind ~= "selfIllum" and type(s) == "table" then + maps[kind] = fromRef(if s.texture then { texture = s.texture } else nil, s) + end + end + for _, kind in MAP_ORDER do + local mp = maps[kind] + if mp then + local mat = open(w, MAP_IDS[kind]) + leaf(w, C.PERCENTW, function() + w:u16le(math.clamp(math.floor((mp.strength or 1) * 100 + 0.5), 0, 100)) + end) + leaf(w, C.MAP_FILE, function() + w:cstring(name(mp.file, "texture")) + end) + if mp.tiling then + leaf(w, C.MAP_TILING, function() + w:u16le(mp.tiling) + end) + end + for _, f in { { C.MAP_USCALE, mp.uscale }, { C.MAP_VSCALE, mp.vscale }, { C.MAP_UOFFSET, mp.uoffset }, { C.MAP_VOFFSET, mp.voffset }, { C.MAP_ANGLE, mp.angle } } do + local v = f[2] + if type(v) == "number" then + leaf(w, f[1], function() + w:f32le(v) + end) + end + end + close(w, mat) + end + end + close(w, at) +end + +-- ------------------------------------------------------------------------------------------------ meshes +type Part = { name: string, positions: { number }, uvs: { number }?, faces: { number }, smooth: { number }, mats: { [number]: { number } } } + +local function parts(mesh: Types.Mesh, base: string, opts: Options): ({ Part }?, string?) + local merged, err = Flatten.merge({ kind = "scene", nodes = {}, roots = {}, meshes = { mesh } }, function(n: string): boolean + return n == "TEXCOORD_0" or n == "NORMAL" + end, { triangulate = true }) + if not merged then + return nil, err + end + local P = merged.attrs.POSITION.values + local N = merged.attrs.NORMAL and merged.attrs.NORMAL.values + local T = merged.attrs.TEXCOORD_0 + local tv, tc = if T then T.values else nil, if T then T.components else 0 + local flipV = opts.flipV ~= false + local corners = merged.corners + local nf = #corners // 3 + local fmat, fsg = table.create(nf, 0), table.create(nf, 1) + for _, part in merged.parts do + local prim: any = part.prim + local saved = prim.extras and prim.extras["3ds"] and prim.extras["3ds"].smoothing + local savedOk = type(saved) == "table" and #saved == part.faceCount and (prim.mode or "triangles") == "triangles" + for f = part.firstFace + 1, part.firstFace + part.faceCount do + fmat[f] = if type(prim.material) == "number" then prim.material else 0 + if savedOk then + fsg[f] = saved[f - part.firstFace] + elseif N then + local a, b, c = corners[f * 3 - 2], corners[f * 3 - 1], corners[f * 3] + local e1 = { P[b * 3 + 1] - P[a * 3 + 1], P[b * 3 + 2] - P[a * 3 + 2], P[b * 3 + 3] - P[a * 3 + 3] } + local e2 = { P[c * 3 + 1] - P[a * 3 + 1], P[c * 3 + 2] - P[a * 3 + 2], P[c * 3 + 3] - P[a * 3 + 3] } + local nx, ny, nz = unit(e1[2] * e2[3] - e1[3] * e2[2], e1[3] * e2[1] - e1[1] * e2[3], e1[1] * e2[2] - e1[2] * e2[1]) + local flat = true + for _, v in { a, b, c } do + local vx, vy, vz = unit(N[v * 3 + 1], N[v * 3 + 2], N[v * 3 + 3]) + if vx * nx + vy * ny + vz * nz < 0.9998 then + flat = false + end + end + fsg[f] = if flat then 0 else 1 + end + end + end + local out: { Part } = {} + local cur: Part? = nil + local remap: { [number]: number } = {} + local count = 0 + for f = 1, nf do + local fresh = 0 + for k = 1, 3 do + if not remap[corners[f * 3 - 3 + k]] then + fresh += 1 + end + end + if cur == nil or count + fresh > 65535 or #cur.smooth >= 65535 then + cur = { name = if #out == 0 then base else string.sub(base, 1, 56) .. "." .. #out, positions = {}, uvs = if tv then {} else nil, faces = {}, smooth = {}, mats = {} } + table.insert(out, cur :: Part) + remap, count = {}, 0 + end + local p = cur :: Part + for k = 1, 3 do + local v = corners[f * 3 - 3 + k] + local o = remap[v] + if not o then + o = count + count += 1 + remap[v] = o + table.move(P, v * 3 + 1, v * 3 + 3, #p.positions + 1, p.positions) + if tv and p.uvs then + local u, vv = tv[v * tc + 1] or 0, tv[v * tc + 2] or 0 + table.insert(p.uvs, u) + table.insert(p.uvs, if flipV then 1 - vv else vv) + end + end + table.insert(p.faces, o) + end + table.insert(p.smooth, fsg[f]) + local mi = fmat[f] + if mi > 0 then + p.mats[mi] = p.mats[mi] or {} + table.insert(p.mats[mi], #p.smooth - 1) + end + end + return out, nil +end + +local function writeMesh(w: W, part: Part, M: { number }, matNames: { [number]: string }) + local at = open(w, C.OBJECT) + w:cstring(part.name) + local tm = open(w, C.TRIMESH) + local nv = #part.positions // 3 + leaf(w, C.VERTICES, function() + w:u16le(nv) + local p = part.positions + for v = 0, nv - 1 do + local x, y, z = Mat4.point(M, p[v * 3 + 1], p[v * 3 + 2], p[v * 3 + 3]) + w:f32le(x) + w:f32le(y) + w:f32le(z) + end + end) + if part.uvs then + local uvs = part.uvs + leaf(w, C.UVS, function() + w:u16le(nv) + for i = 1, nv * 2 do + w:f32le(uvs[i] or 0) + end + end) + end + leaf(w, C.MATRIX, function() + for _, c in { 0, 1, 2, 3 } do + local x, y, z = col(M, c) + w:f32le(x) + w:f32le(y) + w:f32le(z) + end + end) + local fl = open(w, C.FACES) + local nf = #part.smooth + w:u16le(nf) + for f = 0, nf - 1 do + w:u16le(part.faces[f * 3 + 1]) + w:u16le(part.faces[f * 3 + 2]) + w:u16le(part.faces[f * 3 + 3]) + w:u16le(7) -- edges AB, BC, CA visible + end + local mats: { number } = {} + for mi in part.mats do + table.insert(mats, mi) + end + table.sort(mats) + for _, mi in mats do + local list = part.mats[mi] + leaf(w, C.FACE_MAT, function() + w:cstring(matNames[mi]) + w:u16le(#list) + for _, f in list do + w:u16le(f) + end + end) + end + leaf(w, C.SMOOTH, function() + for _, s in part.smooth do + w:u32le(s) + end + end) + close(w, fl) + close(w, tm) + close(w, at) +end + +-- ------------------------------------------------------------------------------------------------ cameras / lights +local function aim(m: { number }, dist: number): ({ number }, { number }, number) + local p = { m[13], m[14], m[15] } + local fx, fy, fz = unit(-m[9], -m[10], -m[11]) + if fx == 0 and fy == 0 and fz == 0 then + fx, fy, fz = 0, 0, -1 + end + local t = { p[1] + fx * dist, p[2] + fy * dist, p[3] + fz * dist } + local q0 = Build.lookAt(p, t, 0) + local m0 = Mat4.fromQuat(q0) + local ux, uy, uz = unit(m[5], m[6], m[7]) + local cu = ux * m0[5] + uy * m0[6] + uz * m0[7] + local cr = ux * m0[1] + uy * m0[2] + uz * m0[3] + return p, t, math.deg(math.atan2(-cr, cu)) +end + +local function writeCamera(w: W, cname: string, cam: Types.Camera, m: { number }, dist: number) + local p, t, roll = aim(m, dist) + local aspect = cam.aspect or 4 / 3 + local yfov = if cam.type == "perspective" and cam.yfov then cam.yfov else math.rad(45) + local hfov = math.deg(2 * math.atan(math.tan(yfov / 2) * aspect)) + local at = open(w, C.OBJECT) + w:cstring(cname) + local c = open(w, C.CAMERA) + for _, v in { p[1], p[2], p[3], t[1], t[2], t[3], roll, 2400 / math.max(hfov, 1e-3) } do + w:f32le(v) + end + leaf(w, C.CAM_RANGES, function() + w:f32le(cam.znear or 0) + w:f32le(cam.zfar or 1000) + end) + close(w, c) + close(w, at) +end + +local function writeLight(w: W, lname: string, l: Types.Light, m: { number }, dist: number) + local p, t = aim(m, dist) + local at = open(w, C.OBJECT) + w:cstring(lname) + local c = open(w, C.LIGHT) + for k = 13, 15 do + w:f32le(m[k]) + end + leaf(w, C.RGBF, function() + for k = 1, 3 do + w:f32le(l.color and l.color[k] or 1) + end + end) + if l.type ~= "point" then + local inner = if l.type == "spot" then (l.innerCone or 0) else math.rad(45) + local outer = if l.type == "spot" then (l.outerCone or math.pi / 4) else math.rad(45) + leaf(w, C.SPOT, function() + for k = 1, 3 do + w:f32le(t[k]) + end + w:f32le(math.deg(inner * 2)) + w:f32le(math.deg(math.max(outer, inner) * 2)) + end) + end + if l.range and l.range > 0 then + leaf(w, C.ATTENUATE, function() end) + leaf(w, C.OUTER_RANGE, function() + w:f32le(l.range :: number) + end) + end + leaf(w, C.MULTIPLIER, function() + w:f32le(l.intensity or 1) + end) + close(w, c) + close(w, at) + return p +end + +-- ------------------------------------------------------------------------------------------------ keyframer +local function writeTrack(w: W, id: number, frames: { number }, values: { number }, size: number) + leaf(w, id, function() + w:u16le(0) + w:u32le(0) + w:u32le(0) + w:u32le(#frames) + for k, f in frames do + w:u32le(f) + w:u16le(0) + for c = 1, size do + w:f32le(values[(k - 1) * size + c]) + end + end + end) +end + +type KfNode = { + chunk: number, name: string, instance: string?, parent: number, -- kf index or -1 + frames: { [string]: { number } }, values: { [string]: { number } }, +} + +local function frameKeys(ch: Types.Channel, fps: number): ({ number }, { number }) + local IN = S.reader(ch.input) :: any + local frames, keep = {}, {} + for k = 0, ch.input.count - 1 do + local f = math.max(0, math.floor(IN(k, 0) * fps + 0.5)) + if #frames == 0 or f > frames[#frames] then + table.insert(frames, f) + table.insert(keep, k) + end + end + return frames, keep +end + +local function channelValues(ch: Types.Channel, keep: { number }, comps: number): { { number } } + local OUT = S.reader(ch.output) :: any + local cubic = ch.interpolation == "CUBICSPLINE" + local out = {} + for _, k in keep do + local e = if cubic then k * 3 + 1 else k + local v = table.create(comps, 0) + for c = 1, comps do + v[c] = OUT(e, c - 1) + end + table.insert(out, v) + end + return out +end + +local function rotTrack(quats: { { number } }): { number } + local vals = {} + local prev: { number }? = nil + for _, q in quats do + local d = q + if prev then + d = Build.qmul(conj(prev), q) + if d[4] < 0 then + d = { -d[1], -d[2], -d[3], -d[4] } + end + end + local a, x, y, z = axisAngle(d) + table.insert(vals, a) + table.insert(vals, x) + table.insert(vals, y) + table.insert(vals, z) + prev = q + end + return vals +end + +-- ------------------------------------------------------------------------------------------------ encode +function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?) + local o: Options = opts or {} + local fps = o.fps or 30 + local W, parentOf, order = world(scene) + local w = Bytes.writer(65536) + local main = open(w, C.MAIN) + leaf(w, C.VERSION, function() + w:u32le(3) + end) + local ed = open(w, C.EDITOR) + leaf(w, C.MESH_VERSION, function() + w:u32le(3) + end) + local files = textureFiles(scene, o) + local matNames: { [number]: string } = {} + local used: { [string]: boolean } = {} + local function unique(base: string): string + local n, k = base, 1 + while used[string.lower(n)] do + k += 1 + n = string.sub(base, 1, 56) .. "_" .. k + end + used[string.lower(n)] = true + return n + end + for i, m in scene.materials do + matNames[i] = unique(name(m.name, "Material" .. i)) + writeMaterial(w, m, matNames[i], files) + end + leaf(w, C.MASTER_SCALE, function() + w:f32le(1) + end) + used = {} + local firstNode: { [number]: number } = {} + for _, i in order do + local mi = scene.nodes[i].mesh + if mi and scene.meshes[mi] and not firstNode[mi] then + firstNode[mi] = i + end + end + local meshParts: { [number]: { Part } } = {} + local meshM: { [number]: { number } } = {} + for mi, mesh in scene.meshes do + local ni = firstNode[mi] + if ni == nil and #scene.nodes > 0 then + continue + end + local list, err = parts(mesh, unique(name(mesh.name, "Mesh" .. mi)), o) + if not list then + return nil, err + end + local M = if ni then W[ni] else S.IDENTITY + if not Mat4.inverse(M) then + M = S.IDENTITY + end + meshParts[mi], meshM[mi] = list, M + for _, part in list do + used[string.lower(part.name)] = true + writeMesh(w, part, M, matNames) + end + end + local KW: { [number]: { number } } = {} + for _, i in order do + local n = scene.nodes[i] + local m = W[i] + if n.mesh and meshM[n.mesh] and Build.det3(meshM[n.mesh]) < 0 then + m = S.mul(m, Mat4.scaling(-1, 1, 1)) + end + KW[i] = m + end + local kfs: { KfNode } = {} + local kfOf: { [number]: number } = {} + local anim = scene.animations[1] + local byNode: { [number]: { [string]: Types.Channel } } = {} + if anim then + for _, ch in anim.channels do + if ch.path ~= "weights" then + byNode[ch.node] = byNode[ch.node] or {} + byNode[ch.node][ch.path] = ch + end + end + end + local lastFrame = 0 + local function single(v: { number }): { number } + return table.clone(v) + end + for _, i in order do + local n = scene.nodes[i] + local p = parentOf[i] + local pk = if p ~= 0 then kfOf[p] else nil + local camOrLight = (n.camera and scene.cameras[n.camera]) or (n.light and scene.lights[n.light]) + local dist = 100 + local function placeCamLight(kind: number, objName: string, tgtChunk: number?) + local pos, tgt, roll = aim(W[i], dist) + local kn: KfNode = { chunk = kind, name = objName, parent = -1, frames = { pos = { 0 }, roll = { 0 } }, values = { pos = pos, roll = { roll } } } + table.insert(kfs, kn) + local idx = #kfs + local chs: any = if p == 0 then byNode[i] else nil + local targetFrames, targetVals = { 0 }, tgt + if chs and (chs.translation or chs.rotation) then + local fr: { [number]: boolean } = {} + local frames: { number } = {} + local list: { Types.Channel } = {} + table.insert(list, chs.translation) + table.insert(list, chs.rotation) + for _, ch in list do + for _, f in (frameKeys(ch, fps)) do + if not fr[f] then + fr[f] = true + table.insert(frames, f) + end + end + end + table.sort(frames) + local pv, tv, rv = {}, {}, {} + for _, f in frames do + local t = f / fps + local ct, cr = chs.translation, chs.rotation + local tr = if ct then sample(ct, t) else { W[i][13], W[i][14], W[i][15] } + local rq = if cr then sample(cr, t) else (n.rotation or { 0, 0, 0, 1 }) + local sc = n.scale or { 1, 1, 1 } + local ps, ts, rs = aim(Mat4.compose(tr, rq, sc), dist) + table.move(ps, 1, 3, #pv + 1, pv) + table.move(ts, 1, 3, #tv + 1, tv) + table.insert(rv, rs) + lastFrame = math.max(lastFrame, f) + end + kn.frames.pos, kn.values.pos = frames, pv + kn.frames.roll, kn.values.roll = frames, rv + targetFrames, targetVals = frames, tv + end + if tgtChunk then + table.insert(kfs, { chunk = tgtChunk, name = objName, parent = -1, frames = { pos = targetFrames }, values = { pos = targetVals } }) + end + if kind ~= 0xB003 then + kn.frames.roll, kn.values.roll = nil :: any, nil :: any + end + return idx + end + local function camLight(onlyThis: boolean): number? + if not camOrLight then + return nil + end + local idx: number? = nil + if n.camera and scene.cameras[n.camera] then + local cname = unique(name(scene.cameras[n.camera].name or n.name, "Camera" .. n.camera)) + writeCamera(w, cname, scene.cameras[n.camera], W[i], dist) + idx = placeCamLight(0xB003, cname, 0xB004) + end + if n.light and scene.lights[n.light] then + local l = scene.lights[n.light] + local lname = unique(name(l.name or n.name, "Light" .. n.light)) + writeLight(w, lname, l, W[i], dist) + local k = placeCamLight(if l.type == "point" then 0xB005 else 0xB007, lname, if l.type == "point" then nil else 0xB006) + idx = idx or k + end + if onlyThis and idx then + kfOf[i] = idx + local kn = kfs[idx] + local pos = kn.values.pos + local m: { number } = W[i] + if kn.chunk == 0xB005 then + KW[i] = Mat4.translation(pos[1], pos[2], pos[3]) + else + local _, tgt, roll = aim(m, dist) + KW[i] = Mat4.compose(pos, Build.lookAt({ pos[1], pos[2], pos[3] }, tgt, if kn.chunk == 0xB003 then roll else 0), nil) + end + end + return idx + end + if n.mesh == nil and camOrLight then + camLight(true) + continue + end + local pkw = if p ~= 0 and kfOf[p] then KW[p] else S.IDENTITY + local inv = Mat4.inverse(pkw) or Mat4.identity() + local L = S.mul(inv, KW[i]) + local t, r, s = Mat4.decompose(L) + local plist = if n.mesh then meshParts[n.mesh] else nil + local objName = if plist then plist[1].name else "$$$DUMMY" + local instance = if plist and n.name and n.name ~= objName then name(n.name, objName) elseif not plist then name(n.name, "Dummy" .. i) else nil + local kn: KfNode = { chunk = 0xB002, name = objName, instance = instance, parent = if pk then pk - 1 else -1, frames = { pos = { 0 }, rot = { 0 }, scl = { 0 } }, values = { pos = single(t), rot = rotTrack({ r }), scl = single(s) } } + local chs = byNode[i] + if chs then + local own = S.nodeMatrix(n) + local same = true + for k = 1, 16 do + if abs(own[k] - L[k]) > 1e-5 * math.max(1, abs(own[k])) then + same = false + end + end + if same then + for path, field in { translation = "pos", rotation = "rot", scale = "scl" } :: { [string]: string } do + local ch = chs[path] + if ch then + local frames, keep = frameKeys(ch, fps) + local vals = channelValues(ch, keep, if path == "rotation" then 4 else 3) + lastFrame = math.max(lastFrame, frames[#frames] or 0) + kn.frames[field] = frames + if path == "rotation" then + kn.values[field] = rotTrack(vals) + else + local flat = {} + for _, v in vals do + table.move(v, 1, 3, #flat + 1, flat) + end + kn.values[field] = flat + end + end + end + end + end + table.insert(kfs, kn) + kfOf[i] = #kfs + for k = 2, if plist then #plist else 0 do + local extra = table.clone(kn) + extra.name, extra.instance = (plist :: { Part })[k].name, nil + table.insert(kfs, extra) + end + camLight(false) + end + close(w, ed) + local kf = open(w, C.KEYFRAMER) + leaf(w, C.KF_HDR, function() + w:u16le(5) + w:cstring("MAXSCENE") + w:u32le(math.max(lastFrame, 100)) + end) + leaf(w, C.KF_FRAMES, function() + w:u32le(0) + w:u32le(math.max(lastFrame, 100)) + end) + for id, kn in kfs do + local nc = open(w, kn.chunk) + leaf(w, C.NODE_ID, function() + w:u16le(id - 1) + end) + leaf(w, C.NODE_HDR, function() + w:cstring(kn.name) + w:u16le(0x4000) + w:u16le(0) + w:u16le(if kn.parent >= 0 then kn.parent else 0xFFFF) + end) + if kn.instance then + leaf(w, C.NODE_INSTANCE, function() + w:cstring(kn.instance :: string) + end) + end + if kn.chunk == 0xB002 then + leaf(w, C.NODE_PIVOT, function() + w:f32le(0) + w:f32le(0) + w:f32le(0) + end) + end + for _, tr in { { "pos", C.TRACK_POS, 3 }, { "rot", C.TRACK_ROT, 4 }, { "scl", C.TRACK_SCALE, 3 }, { "roll", C.TRACK_ROLL, 1 } } do + local field = tr[1] :: string + local frames = kn.frames[field] + if frames then + writeTrack(w, tr[2] :: number, frames, kn.values[field], tr[3] :: number) + end + end + close(w, nc) + end + close(w, kf) + close(w, main) + local out = buffer.create(w.pos) + buffer.copy(out, 0, w.buf, 0, w.pos) + return out, nil +end + +return Write +end +__FILES["model/3mf"] = function() + +-- model/3mf: 3D Manufacturing Format (core 1.3, materials extension 1.2, production extension 1.1 p:path). +-- Supports: meshes, components, build items, base materials, colour / texture / composite / multi groups. +-- Not supported: beam lattice, slices, displacement, volumetric and secure content, thumbnails, normals. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Zip = __include("containers/Zip") +local Read = __include("model/3mf/Read") +local Write = __include("model/3mf/Write") + +-- ------------------------------------------------------------------------------------------------ contract +local ThreeMf = { + name = "3mf", + category = "model", + extensions = { "3mf" }, + mime = { "model/3mf" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Xml", "containers/Zip" }, + caps = { decode = true, encode = true, materials = true, vertexColors = true, textures = true, units = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + maxVertices: number?, -- default 2^25 + maxNodes: number?, -- default 2^20 +} +type EncodeOptions = { + unit: string?, -- "micron" | "millimeter" | "centimeter" | "inch" | "foot" | "meter" (default: from meta.unit, else + -- millimeter) + level: number?, -- default 6; 0 stores +} + +-- ------------------------------------------------------------------------------------------------ sniff +function ThreeMf.sniff(r: Bytes.Reader): number + if r:peek(4) ~= "PK\3\4" then + return 0 + end + local n = r:size() + local tail = buffer.readstring(r.buf, r.base + math.max(0, n - 65536), math.min(n, 65536)) + if string.find(tail, "3D/[^/]*%.model") or string.find(tail, "3dmodel.model", 1, true) then + return 0.95 + end + local head = r:peek(256) + if string.find(head, "3D/", 1, true) then + return 0.7 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function ThreeMf.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local zip, zerr = Zip.open(r) + if not zip then + return nil, zerr + end + local ok, scene, err = pcall(Read.scene, zip, opts or {}) + if not ok then + return nil, Err.new(Err.CORRUPT, "bad package (" .. tostring(scene) .. ")") + end + return scene, err +end + +-- ------------------------------------------------------------------------------------------------ encode +function ThreeMf.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(scene) ~= "table" or scene.kind ~= "scene" or type(scene.meshes) ~= "table" or type(scene.materials) ~= "table" or type(scene.textures) ~= "table" then + return nil, Err.new(Err.ARG, "needs a Scene") + end + if opts and opts.unit ~= nil and not Read.UNITS[opts.unit] then + return nil, Err.new(Err.ARG, "unknown unit " .. tostring(opts.unit)) + end + local ok, out, err = pcall(Write.build, scene, opts) + if not ok then + return nil, Err.new(Err.ARG, "bad scene (" .. tostring(out) .. ")") + end + return out, err +end + +return ThreeMf +end +__FILES["model/3mf/Read"] = function() + +-- model/3mf/Read: a 3MF package -> Scene. The root model part comes from _rels/.rels (fallback: the first *.model under +-- 3D/); vertices are split where corners of one vertex carry different colours / texture coordinates. +local Err = __include("core/Err") +local Types = __include("Types") +local Xml = __include("codecs/text/Xml") +local Zip = __include("containers/Zip") + +local Read = {} + +local REL_MODEL = "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel" +local UNITS = { micron = 1e-6, millimeter = 1e-3, centimeter = 1e-2, inch = 0.0254, foot = 0.3048, meter = 1 } +Read.UNITS = UNITS +local WRAP = { wrap = "repeat", mirror = "mirror", clamp = "clamp", none = "clamp" } +local MAX_DEPTH = 64 + +local localName = Xml.localName + +local function attr(node: any, name: string): string? + local a = node.attrs + local v = a[name] + if v ~= nil then + return v + end + for k, x in next, a do + if type(k) == "string" and localName(k) == name then + return x + end + end + return nil +end + +local function int(s: string?): number? + local n = if s then tonumber(s) else nil + if n and n == math.floor(n) and n >= 0 then + return n + end + return nil +end + +-- "#RRGGBB" / "#RRGGBBAA", sRGB +local function hexColor(s: string?): { number }? + if type(s) ~= "string" then + return nil + end + local h = string.match(s, "^%s*#(%x+)%s*$") + if not h or (#h ~= 6 and #h ~= 8) then + return nil + end + local function c(i: number): number + return (tonumber(string.sub(h :: string, i, i + 1), 16) :: number) / 255 + end + return { c(1), c(3), c(5), if #h == 8 then c(7) else 1 } +end +Read.hexColor = hexColor + +function Read.toLinear(c: number): number + if c <= 0.04045 then + return c / 12.92 + end + return ((c + 0.055) / 1.055) ^ 2.4 +end +local toLinear = Read.toLinear + +-- "m00 m01 m02 m10 ... m32": 3MF's row-vector convention +local function transform(s: string?): ({ number }?, boolean) + if not s then + return nil, true + end + local v = {} + for w in string.gmatch(s, "%S+") do + local n = tonumber(w) + if not n or n ~= n or n == math.huge or n == -math.huge then + return nil, false + end + table.insert(v, n) + end + if #v ~= 12 then + return nil, false + end + local m = { v[1], v[2], v[3], 0, v[4], v[5], v[6], 0, v[7], v[8], v[9], 0, v[10], v[11], v[12], 1 } + for i = 1, 16 do + if m[i] ~= Types.Scene.IDENTITY[i] then + return m, true + end + end + return nil, true +end + +local function normPath(p: string): string + p = string.gsub(p, "\\", "/") + p = string.gsub(p, "^/+", "") + return p +end + +type Model = { path: string, unit: string?, metadata: { [string]: string }, res: { [number]: any }, items: { any }, required: string? } + +local function parseModel(text: string, path: string, opts: any): (Model?, Err.Err?) + local doc, err = Xml.decode(text, { parents = false }) + if not doc then + return nil, err + end + local root = (doc :: any).root + if not root or localName(root.name) ~= "model" then + return nil, Err.new(Err.CORRUPT, path .. ": the root element is not <model>") + end + local maxV = opts.maxVertices or 2 ^ 25 + local model: Model = { path = path, unit = attr(root, "unit"), metadata = {}, res = {}, items = {}, required = attr(root, "requiredextensions") } + local resources: any = nil + local build: any = nil + for _, ch in Xml.children(root) do + local ln = localName(ch.name) + if ln == "metadata" then + local n = attr(ch, "name") + if n then + model.metadata[n] = Xml.text(ch) + end + elseif ln == "resources" then + resources = ch + elseif ln == "build" then + build = ch + end + end + local total = 0 + if resources then + for _, r in Xml.children(resources) do + local ln = localName(r.name) + local id = int(attr(r, "id")) + if id == nil then + continue + end + if ln == "object" then + local o: any = { kind = "object", id = id, name = attr(r, "name"), type = attr(r, "type") or "model", pid = int(attr(r, "pid")), pindex = int(attr(r, "pindex")), partnumber = attr(r, "partnumber") } + local mesh = Xml.child(r, "mesh") + local comps = Xml.child(r, "components") + if mesh then + local verts = Xml.child(mesh, "vertices") + local tris = Xml.child(mesh, "triangles") + local vl = if verts then Xml.children(verts, "vertex") else {} + local tl = if tris then Xml.children(tris, "triangle") else {} + total += #vl + #tl * 3 + if total > maxV then + return nil, Err.new(Err.LIMIT, "more than " .. maxV .. " vertices / corners") + end + local nv = #vl + local pos = table.create(nv * 3, 0) + for i, v in vl do + local a = v.attrs + local x, y, z = tonumber(a.x), tonumber(a.y), tonumber(a.z) + if not x or not y or not z then + return nil, Err.new(Err.CORRUPT, "object " .. id .. ": bad vertex " .. i) + end + pos[i * 3 - 2], pos[i * 3 - 1], pos[i * 3] = x, y, z + end + local nt = #tl + local tv = table.create(nt * 3, 0) + local tp = table.create(nt * 4, -1) -- pid, p1, p2, p3 (-1 = none) + for i, tri in tl do + local a = tri.attrs + local v1, v2, v3 = int(a.v1), int(a.v2), int(a.v3) + if not v1 or not v2 or not v3 or v1 >= nv or v2 >= nv or v3 >= nv then + return nil, Err.new(Err.CORRUPT, "object " .. id .. ": triangle " .. i .. " has a bad vertex index") + end + tv[i * 3 - 2], tv[i * 3 - 1], tv[i * 3] = v1, v2, v3 + local b = i * 4 - 4 + local pid, p1, p2, p3 = int(a.pid), int(a.p1), int(a.p2), int(a.p3) + tp[b + 1] = pid or -1 + tp[b + 2] = p1 or -1 + tp[b + 3] = p2 or p1 or -1 + tp[b + 4] = p3 or p1 or -1 + end + o.positions, o.tv, o.tp, o.nt = pos, tv, tp, nt + end + if comps then + o.components = {} + for _, c in Xml.children(comps, "component") do + local oid = int(attr(c, "objectid")) + local m, ok = transform(attr(c, "transform")) + if oid and ok then + table.insert(o.components, { objectid = oid, matrix = m, path = attr(c, "path") }) + end + end + end + model.res[id] = o + elseif ln == "basematerials" then + local items = {} + for _, b in Xml.children(r, "base") do + table.insert(items, { name = attr(b, "name"), color = hexColor(attr(b, "displaycolor")) or { 1, 1, 1, 1 }, hex = attr(b, "displaycolor") }) + end + model.res[id] = { kind = "base", id = id, items = items } + elseif ln == "colorgroup" then + local items = {} + for _, c in Xml.children(r, "color") do + table.insert(items, hexColor(attr(c, "color")) or { 1, 1, 1, 1 }) + end + model.res[id] = { kind = "color", id = id, items = items } + elseif ln == "texture2d" then + model.res[id] = { kind = "texture", id = id, path = attr(r, "path"), contenttype = attr(r, "contenttype"), tileu = attr(r, "tilestyleu"), tilev = attr(r, "tilestylev"), filter = attr(r, "filter") } + elseif ln == "texture2dgroup" then + local uvs = {} + for _, c in Xml.children(r, "tex2coord") do + table.insert(uvs, tonumber(attr(c, "u")) or 0) + table.insert(uvs, tonumber(attr(c, "v")) or 0) + end + model.res[id] = { kind = "texgroup", id = id, texid = int(attr(r, "texid")), uvs = uvs, count = #uvs // 2 } + elseif ln == "compositematerials" then + local mats = {} + for w in string.gmatch(attr(r, "matindices") or "", "%S+") do + table.insert(mats, tonumber(w) or 0) + end + local items = {} + for _, c in Xml.children(r, "composite") do + local vals = {} + for w in string.gmatch(attr(c, "values") or "", "%S+") do + table.insert(vals, tonumber(w) or 0) + end + table.insert(items, vals) + end + model.res[id] = { kind = "composite", id = id, matid = int(attr(r, "matid")), matindices = mats, items = items } + elseif ln == "multiproperties" then + local pids = {} + for w in string.gmatch(attr(r, "pids") or "", "%S+") do + table.insert(pids, tonumber(w) or -1) + end + local items = {} + for _, c in Xml.children(r, "multi") do + local ix = {} + for w in string.gmatch(attr(c, "pindices") or "", "%S+") do + table.insert(ix, tonumber(w) or 0) + end + table.insert(items, ix) + end + model.res[id] = { kind = "multi", id = id, pids = pids, items = items } + end + end + end + if build then + for _, it in Xml.children(build, "item") do + local oid = int(attr(it, "objectid")) + local m, ok = transform(attr(it, "transform")) + if oid and ok then + table.insert(model.items, { objectid = oid, matrix = m, path = attr(it, "path"), partnumber = attr(it, "partnumber") }) + end + end + end + return model, nil +end + +local function rootPath(zip: any): string? + local rels = zip:readString("_rels/.rels") + if rels then + local doc = Xml.decode(rels, { parents = false }) + if doc then + for _, rel in Xml.descendants((doc :: any).root or doc, "Relationship") do + local t, target = attr(rel, "Type"), attr(rel, "Target") + if t and target and (t == REL_MODEL or string.find(t, "/3dmodel$")) then + return normPath(target) + end + end + end + end + for _, e in zip:list() do + if not e.isDir and string.find(string.lower(e.name), "%.model$") then + return e.name + end + end + return nil +end + +function Read.scene(zip: any, opts: any): (Types.Scene?, Err.Err?) + local rootP = rootPath(zip) + if not rootP then + return nil, Err.new(Err.CORRUPT, "no 3D model part in the package") + end + local models: { [string]: Model } = {} + local function getModel(path: string): (Model?, Err.Err?) + local p = normPath(path) + local m = models[p] + if m then + return m, nil + end + local text, err = zip:readString(p) + if not text then + return nil, err or Err.new(Err.CORRUPT, "missing model part " .. p) + end + if string.sub(text, 1, 5) == "%3McF" then + return nil, Err.new(Err.UNSUPPORTED, "secure content extension: " .. p .. " is encrypted / wrapped") + end + local mm, perr = parseModel(text, p, opts) + if not mm then + return nil, perr + end + models[p] = mm + return mm, nil + end + local root, rerr = getModel(rootP) + if not root then + return nil, rerr + end + + local scene = Types.Scene.new() + local unitName = root.unit or "millimeter" + scene.meta.up = "z" + scene.meta.unit = UNITS[unitName] or 1e-3 + scene.meta.metadata = root.metadata + scene.meta.source = { format = "3mf", unit = unitName, part = rootP, requiredExtensions = root.required } + + local texCache: { [string]: number } = {} + local function texture(model: Model, id: number): number? + local key = model.path .. "#" .. id + if texCache[key] then + return texCache[key] + end + local r = model.res[id] + if not r or r.kind ~= "texture" or type(r.path) ~= "string" then + return nil + end + local data = zip:read(normPath(r.path)) + local tex: Types.Texture = { + name = r.path, + data = data, + mime = r.contenttype, + uri = r.path, + sampler = { wrapS = WRAP[r.tileu or "wrap"] or "repeat", wrapT = WRAP[r.tilev or "wrap"] or "repeat", filter = if r.filter == "nearest" or r.filter == "linear" then r.filter else nil }, + extras = { ["3mf"] = { id = id, tilestyleu = r.tileu, tilestylev = r.tilev, filter = r.filter } }, + } + table.insert(scene.textures, tex) + texCache[key] = #scene.textures + return #scene.textures + end + local matCache: { [string]: number } = {} + local function addMaterial(key: string, make: () -> Types.Material): number + local i = matCache[key] + if i then + return i + end + table.insert(scene.materials, make()) + matCache[key] = #scene.materials + return #scene.materials + end + local function colorMaterial(name: string?, c: { number }, extras: any): Types.Material + local m = Types.Scene.material(name) + m.baseColor = { toLinear(c[1]), toLinear(c[2]), toLinear(c[3]), c[4] } + m.metallic = 0 + m.roughness = 1 + if c[4] < 1 then + m.alphaMode = "blend" + end + m.extras = { ["3mf"] = extras } + return m + end + + local function resolve(model: Model, pid: number, p: number, depth: number?): (string, number?, string, any, number) + local r = model.res[pid] + if not r or p < 0 then + return "none", nil, "none", nil, 0 + end + local k = r.kind + if k == "base" then + local item = r.items[p + 1] + if not item then + return "none", nil, "none", nil, 0 + end + local key = "b" .. model.path .. "#" .. pid .. ":" .. p + return key, addMaterial(key, function() + return colorMaterial(item.name, item.color, { group = pid, index = p, displaycolor = item.hex }) + end), "base", r, p + elseif k == "color" then + return "c" .. model.path .. "#" .. pid, nil, "color", r, p + elseif k == "texgroup" then + local ti = r.texid and texture(model, r.texid) + local mat: number? = nil + if ti then + local mk = "t" .. model.path .. "#" .. (r.texid :: number) + mat = addMaterial(mk, function() + local m = Types.Scene.material("texture " .. tostring(r.texid)) + m.metallic = 0 + m.roughness = 1 + m.baseColorTexture = { texture = ti :: number } + m.extras = { ["3mf"] = { texture = r.texid } } + return m + end) + end + return "t" .. model.path .. "#" .. pid, mat, "tex", r, p + elseif k == "composite" then + local item = r.items[p + 1] + local base = r.matid and model.res[r.matid] + if not item or not base or base.kind ~= "base" then + return "none", nil, "none", nil, 0 + end + local key = "x" .. model.path .. "#" .. pid .. ":" .. p + return key, addMaterial(key, function() + local c, sum = { 0, 0, 0, 0 }, 0 + for j, w in item do + local b = base.items[(r.matindices[j] or 0) + 1] + if b then + for q = 1, 4 do + c[q] += b.color[q] * w + end + sum += w + end + end + if sum > 0 then + for q = 1, 4 do + c[q] /= sum + end + else + c = { 1, 1, 1, 1 } + end + return colorMaterial("composite " .. pid .. ":" .. p, c, { composite = pid, index = p }) + end), "base", r, p + elseif k == "multi" and (depth or 0) < 1 then + local item = r.items[p + 1] + local first = r.pids[1] + if item and first then + return resolve(model, first, item[1] or 0, 1) + end + end + return "none", nil, "none", nil, 0 + end + + local meshCache: { [string]: number } = {} + local function buildMesh(model: Model, o: any): number? + local key = model.path .. "#" .. o.id + local cached = meshCache[key] + if cached ~= nil then + return if cached > 0 then cached else nil + end + local groups: { [string]: any } = {} + local order: { any } = {} + local pos, tv, tp = o.positions, o.tv, o.tp + for t = 0, o.nt - 1 do + local pid = tp[t * 4 + 1] + local ps = { tp[t * 4 + 2], tp[t * 4 + 3], tp[t * 4 + 4] } + if pid < 0 then + pid = o.pid or -1 + if ps[1] < 0 then + local d = o.pindex or (if pid >= 0 then 0 else -1) + ps = { d, d, d } + end + end + local gkey, mat, kind, res, _ = resolve(model, pid, ps[1]) + local g = groups[gkey] + if not g then + g = { kind = kind, res = res, material = mat, vmap = {}, pos = {}, attr = {}, idx = {}, n = 0 } + groups[gkey] = g + table.insert(order, g) + end + for c = 1, 3 do + local v = tv[t * 3 + c] + local vk = v + local pc = 0 + if kind == "color" or kind == "tex" then + pc = ps[c] + local cnt = if kind == "color" then #res.items else res.count + if pc < 0 or pc >= cnt then + pc = ps[1] + end + if pc < 0 or pc >= cnt then + pc = 0 + end + vk = v * (cnt + 1) + pc + end + local ni = g.vmap[vk] + if not ni then + ni = g.n + g.n += 1 + g.vmap[vk] = ni + table.insert(g.pos, pos[v * 3 + 1]) + table.insert(g.pos, pos[v * 3 + 2]) + table.insert(g.pos, pos[v * 3 + 3]) + if kind == "color" then + local col = res.items[pc + 1] or { 1, 1, 1, 1 } + table.insert(g.attr, toLinear(col[1])) + table.insert(g.attr, toLinear(col[2])) + table.insert(g.attr, toLinear(col[3])) + table.insert(g.attr, col[4]) + elseif kind == "tex" then + table.insert(g.attr, res.uvs[pc * 2 + 1] or 0) + table.insert(g.attr, 1 - (res.uvs[pc * 2 + 2] or 0)) + end + end + table.insert(g.idx, ni) + end + end + local mesh: Types.Mesh = { name = o.name, primitives = {}, extras = { ["3mf"] = { id = o.id, part = model.path, type = o.type, partnumber = o.partnumber } } } + for _, g in order do + local n = g.n + local pa = Types.Scene.accessor(nil, "f32", 3, n) + for i, x in g.pos do + buffer.writef32(pa.data, (i - 1) * 4, x) + end + local ia = Types.Scene.accessor(nil, "u32", 1, #g.idx) + for i, x in g.idx do + buffer.writeu32(ia.data, (i - 1) * 4, x) + end + local prim: Types.Primitive = { attributes = { POSITION = pa }, indices = ia, mode = "triangles", material = g.material } + if g.kind == "color" then + local ca = Types.Scene.accessor(nil, "f32", 4, n) + for i, x in g.attr do + buffer.writef32(ca.data, (i - 1) * 4, x) + end + prim.attributes.COLOR_0 = ca + prim.extras = { ["3mf"] = { colorgroup = g.res.id } } + elseif g.kind == "tex" then + local ua = Types.Scene.accessor(nil, "f32", 2, n) + for i, x in g.attr do + buffer.writef32(ua.data, (i - 1) * 4, x) + end + prim.attributes.TEXCOORD_0 = ua + prim.extras = { ["3mf"] = { texture2dgroup = g.res.id } } + end + table.insert(mesh.primitives, prim) + end + if #mesh.primitives == 0 then + meshCache[key] = 0 + return nil + end + table.insert(scene.meshes, mesh) + meshCache[key] = #scene.meshes + return #scene.meshes + end + + local nodeCount = 0 + local maxNodes = opts.maxNodes or 2 ^ 20 + local instantiate: (model: Model, oid: number, matrix: { number }?, depth: number, extra: any) -> (number?, Err.Err?) + function instantiate(model: Model, oid: number, matrix: { number }?, depth: number, extra: any): (number?, Err.Err?) + if depth > MAX_DEPTH then + return nil, Err.new(Err.CORRUPT, "components nested deeper than " .. MAX_DEPTH .. " (a cycle?)") + end + nodeCount += 1 + if nodeCount > maxNodes then + return nil, Err.new(Err.LIMIT, "more than " .. maxNodes .. " object instances") + end + local o = model.res[oid] + if not o or o.kind ~= "object" then + return nil, Err.new(Err.CORRUPT, "no object " .. oid .. " in " .. model.path) + end + local node: Types.Node = { name = o.name, children = {}, matrix = matrix, extras = { ["3mf"] = extra or { objectid = oid } } } + table.insert(scene.nodes, node) + local index = #scene.nodes + if o.positions then + node.mesh = buildMesh(model, o) + end + if o.components then + for _, c in o.components do + local m: Model? = model + if c.path then + local mm, err = getModel(c.path) + if not mm then + return nil, err + end + m = mm + end + local child, err = instantiate(m :: Model, c.objectid, c.matrix, depth + 1, { objectid = c.objectid, path = c.path }) + if not child then + return nil, err + end + table.insert(node.children, child) + end + end + return index, nil + end + for _, it in root.items do + local m: Model? = root + if it.path then + local mm, err = getModel(it.path) + if not mm then + return nil, err + end + m = mm + end + local idx, err = instantiate(m :: Model, it.objectid, it.matrix, 0, { objectid = it.objectid, path = it.path, partnumber = it.partnumber, item = true }) + if not idx then + return nil, err + end + table.insert(scene.roots, idx) + end + return scene, nil +end + +function Read.open(r: any): (any, Err.Err?) + return Zip.open(r) +end + +return Read +end +__FILES["model/3mf/Write"] = function() + +-- model/3mf/Write: Scene -> a 3MF package; the node hierarchy is flattened into build items at world matrices. +local Err = __include("core/Err") +local Types = __include("Types") +local Xml = __include("codecs/text/Xml") +local Zip = __include("containers/Zip") + +local Write = {} + +local NS_CORE = "http://schemas.microsoft.com/3dmanufacturing/core/2015/02" +local NS_MAT = "http://schemas.microsoft.com/3dmanufacturing/material/2015/02" +local REL_MODEL = "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel" +local REL_TEXTURE = "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dtexture" +local UNIT_ORDER = { "micron", "millimeter", "centimeter", "inch", "foot", "meter" } +local UNITS = { micron = 1e-6, millimeter = 1e-3, centimeter = 1e-2, inch = 0.0254, foot = 0.3048, meter = 1 } +local TEX_EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg" } + +local fmt = string.format +local esc = Xml.escapeAttr + +local function num(x: number): string + if x ~= x or x == math.huge or x == -math.huge then + return "0" + end + if x == math.floor(x) and math.abs(x) < 1e15 then + return fmt("%d", x) + end + return fmt("%.9g", x) +end + +local function toSrgb(c: number): number + c = math.clamp(c, 0, 1) + if c <= 0.0031308 then + return c * 12.92 + end + return 1.055 * c ^ (1 / 2.4) - 0.055 +end + +local function hex(r: number, g: number, b: number, a: number): string + local function q(x: number): number + return math.clamp(math.floor(x * 255 + 0.5), 0, 255) + end + return fmt("#%02X%02X%02X%02X", q(toSrgb(r)), q(toSrgb(g)), q(toSrgb(b)), q(math.clamp(a, 0, 1))) +end + +local function triangles(prim: any): { number }? + local pos = prim.attributes and prim.attributes.POSITION + if type(pos) ~= "table" then + return nil + end + local n = pos.count + local ix: { number } = {} + if prim.indices then + local get = Types.Scene.reader(prim.indices) + if not get then + return nil + end + for i = 0, prim.indices.count - 1 do + ix[i + 1] = get(i, 0) + end + else + for i = 1, n do + ix[i] = i - 1 + end + end + for _, v in ix do + if v ~= v or v < 0 or v >= n then + return nil + end + end + local mode = prim.mode or "triangles" + local out: { number } = {} + local function tri(a: number, b: number, c: number) + if a ~= b and b ~= c and a ~= c then + table.insert(out, a) + table.insert(out, b) + table.insert(out, c) + end + end + if mode == "triangles" then + for i = 1, #ix - 2, 3 do + tri(ix[i], ix[i + 1], ix[i + 2]) + end + elseif mode == "triangle_strip" then + for i = 1, #ix - 2 do + if i % 2 == 1 then + tri(ix[i], ix[i + 1], ix[i + 2]) + else + tri(ix[i + 1], ix[i], ix[i + 2]) + end + end + elseif mode == "triangle_fan" then + for i = 2, #ix - 1 do + tri(ix[1], ix[i], ix[i + 1]) + end + elseif mode == "polygons" and prim.faces then + local get = Types.Scene.reader(prim.faces) + if not get then + return nil + end + local at = 1 + for f = 0, prim.faces.count - 1 do + local k = get(f, 0) + if at + k - 1 > #ix then + break + end + for j = 1, k - 2 do + tri(ix[at], ix[at + j], ix[at + j + 1]) + end + at += k + end + else + return nil + end + return out +end + +function Write.build(scene: Types.Scene, opts: any): (buffer?, Err.Err?) + local o = opts or {} + local nextId = 0 + local function id(): number + nextId += 1 + return nextId + end + local res: { string } = {} + local files: { { name: string, data: buffer, mime: string } } = {} + + local unitName: string, scale: number = "millimeter", 1 + local mu: any = scene.meta and scene.meta.unit + if type(o.unit) == "string" and UNITS[o.unit] then + unitName = o.unit + if type(mu) == "number" and mu > 0 then + scale = mu / UNITS[o.unit] + end + elseif type(mu) == "number" and mu > 0 then + local found = false + for _, u in UNIT_ORDER do + if math.abs(UNITS[u] - mu) <= 1e-9 * mu then + unitName, found = u, true + break + end + end + if not found then + scale = mu / 1e-3 + end + end + + local baseId: number? = nil + local nmat = #scene.materials + local defaultBase = nmat + local needDefault = false + if nmat > 0 then + baseId = id() + end + + local texRes: { [number]: number } = {} + local function textureId(ti: number): number? + if texRes[ti] ~= nil then + return if texRes[ti] > 0 then texRes[ti] else nil + end + local tex = scene.textures[ti] + local ext = tex and TEX_EXT[tex.mime or ""] + if not tex or type(tex.data) ~= "buffer" or not ext then + texRes[ti] = 0 + return nil + end + local rid = id() + local name = fmt("3D/Textures/texture_%d.%s", ti, ext :: string) + table.insert(files, { name = name, data = tex.data :: buffer, mime = tex.mime :: string }) + local s = tex.sampler + local function tile(w: string?): string + return if w == "clamp" then "clamp" elseif w == "mirror" then "mirror" else "wrap" + end + local filter = if s and (s.filter == "nearest" or s.filter == "linear") then s.filter else "auto" + table.insert(res, fmt('\t\t<m:texture2d id="%d" path="/%s" contenttype="%s" tilestyleu="%s" tilestylev="%s" filter="%s" />\n', rid, esc(name), tex.mime :: string, tile(s and s.wrapS), tile(s and s.wrapT), filter)) + texRes[ti] = rid + return rid + end + + local objectOf: { [number]: number } = {} + local objChunks: { string } = {} + for mi, mesh in scene.meshes do + local verts: { string } = {} + local tris: { string } = {} + local base = 0 + local objPid: number?, objP: number? = nil, nil + local anyNone = false + local triList: { { number } } = {} + for _, prim in mesh.primitives do + local corners = triangles(prim) + if not corners or #corners == 0 then + continue + end + local pos = prim.attributes.POSITION + local getP = Types.Scene.reader(pos) + if not getP then + continue + end + local n = pos.count + for v = 0, n - 1 do + table.insert(verts, fmt('\t\t\t\t\t<vertex x="%s" y="%s" z="%s" />\n', num(getP(v, 0)), num(if pos.components >= 2 then getP(v, 1) else 0), num(if pos.components >= 3 then getP(v, 2) else 0))) + end + local pid, kind = -1, "none" + local mat = prim.material and scene.materials[prim.material] + local uv = prim.attributes.TEXCOORD_0 + local col = prim.attributes.COLOR_0 + local tref = mat and mat.baseColorTexture + local tid = if tref and uv and (tref.texCoord or 0) == 0 then textureId(tref.texture) else nil + if tid and uv then + local get = Types.Scene.reader(uv) + if get then + pid, kind = id(), "tex" + local parts = { fmt('\t\t<m:texture2dgroup id="%d" texid="%d">\n', pid, tid) } + for v = 0, n - 1 do + table.insert(parts, fmt('\t\t\t<m:tex2coord u="%s" v="%s" />\n', num(get(v, 0)), num(1 - get(v, 1)))) + end + table.insert(parts, "\t\t</m:texture2dgroup>\n") + table.insert(res, table.concat(parts)) + end + end + if kind == "none" and col then + local get = Types.Scene.reader(col) + if get then + pid, kind = id(), "color" + local parts = { fmt('\t\t<m:colorgroup id="%d">\n', pid) } + local four = col.components >= 4 + for v = 0, n - 1 do + table.insert(parts, fmt('\t\t\t<m:color color="%s" />\n', hex(get(v, 0), get(v, 1), get(v, 2), if four then get(v, 3) else 1))) + end + table.insert(parts, "\t\t</m:colorgroup>\n") + table.insert(res, table.concat(parts)) + end + end + local pindex = -1 + if kind == "none" and baseId and prim.material and scene.materials[prim.material] then + pid, kind, pindex = baseId :: number, "base", prim.material - 1 + end + for i = 1, #corners, 3 do + local a, b, c = corners[i] + base, corners[i + 1] + base, corners[i + 2] + base + if kind == "tex" or kind == "color" then + table.insert(triList, { a, b, c, pid, corners[i], corners[i + 1], corners[i + 2] }) + elseif kind == "base" then + table.insert(triList, { a, b, c, pid, pindex, pindex, pindex }) + else + table.insert(triList, { a, b, c, -1, -1, -1, -1 }) + anyNone = true + end + if objPid == nil and kind ~= "none" then + objPid, objP = pid, if kind == "base" then pindex else corners[i] + end + end + base += n + end + if #triList == 0 then + continue + end + if objPid and anyNone then + needDefault = true + if not baseId then + baseId = id() + end + end + for _, t in triList do + if t[4] < 0 and objPid then + t[4], t[5], t[6], t[7] = baseId :: number, defaultBase, defaultBase, defaultBase + end + if t[4] < 0 then + table.insert(tris, fmt('\t\t\t\t\t<triangle v1="%d" v2="%d" v3="%d" />\n', t[1], t[2], t[3])) + elseif t[5] == t[6] and t[6] == t[7] then + table.insert(tris, fmt('\t\t\t\t\t<triangle v1="%d" v2="%d" v3="%d" pid="%d" p1="%d" />\n', t[1], t[2], t[3], t[4], t[5])) + else + table.insert(tris, fmt('\t\t\t\t\t<triangle v1="%d" v2="%d" v3="%d" pid="%d" p1="%d" p2="%d" p3="%d" />\n', t[1], t[2], t[3], t[4], t[5], t[6], t[7])) + end + end + local oid = id() + objectOf[mi] = oid + local head = fmt('\t\t<object id="%d" type="model"', oid) + if mesh.name then + head ..= fmt(' name="%s"', esc(mesh.name)) + end + if objPid then + head ..= fmt(' pid="%d" pindex="%d"', objPid, objP :: number) + end + table.insert(objChunks, table.concat({ head, ">\n\t\t\t<mesh>\n\t\t\t\t<vertices>\n", table.concat(verts), "\t\t\t\t</vertices>\n\t\t\t\t<triangles>\n", table.concat(tris), "\t\t\t\t</triangles>\n\t\t\t</mesh>\n\t\t</object>\n" })) + table.insert(res, objChunks[#objChunks]) + end + + if baseId then + local parts = { fmt('\t\t<basematerials id="%d">\n', baseId) } + for _, m in scene.materials do + local c = m.baseColor or { 1, 1, 1, 1 } + table.insert(parts, fmt('\t\t\t<base name="%s" displaycolor="%s" />\n', esc(m.name or "material"), hex(c[1] or 1, c[2] or 1, c[3] or 1, c[4] or 1))) + end + if needDefault then + table.insert(parts, '\t\t\t<base name="default" displaycolor="#FFFFFFFF" />\n') + end + table.insert(parts, "\t\t</basematerials>\n") + table.insert(res, 1, table.concat(parts)) + end + + local items: { string } = {} + local seen: { [number]: boolean } = {} + for _, pl in Types.Scene.flatten(scene) do + if seen[pl.node] then + continue + end + seen[pl.node] = true + local oid = objectOf[pl.mesh] + if not oid then + continue + end + local m = pl.matrix + local s = scale + local tr = { m[1] * s, m[2] * s, m[3] * s, m[5] * s, m[6] * s, m[7] * s, m[9] * s, m[10] * s, m[11] * s, m[13] * s, m[14] * s, m[15] * s } + local ident = s == 1 + for i, v in { 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0 } do + if tr[i] ~= v then + ident = false + end + end + if ident then + table.insert(items, fmt('\t\t<item objectid="%d" />\n', oid)) + else + local ns = table.create(12, "") + for i = 1, 12 do + ns[i] = num(tr[i]) + end + table.insert(items, fmt('\t\t<item objectid="%d" transform="%s" />\n', oid, table.concat(ns, " "))) + end + end + + local meta: { string } = {} + local md = scene.meta and scene.meta.metadata + if type(md) == "table" then + local keys: { string } = {} + for k: any, v: any in md do + if type(k) == "string" and (type(v) == "string" or type(v) == "number") then + table.insert(keys, k) + end + end + table.sort(keys) + for _, k in keys do + table.insert(meta, fmt('\t<metadata name="%s">%s</metadata>\n', esc(k), Xml.escape(tostring(md[k])))) + end + end + + local model = table.concat({ + '<?xml version="1.0" encoding="UTF-8"?>\n', + '<model unit="' .. unitName .. '" xml:lang="en-US" xmlns="' .. NS_CORE .. '" xmlns:m="' .. NS_MAT .. '">\n', + table.concat(meta), + "\t<resources>\n", + table.concat(res), + "\t</resources>\n\t<build>\n", + table.concat(items), + "\t</build>\n</model>\n", + }) + + local types = { '<?xml version="1.0" encoding="UTF-8"?>\n<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">\n', + '\t<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml" />\n', + '\t<Default Extension="model" ContentType="application/vnd.ms-package.3dmanufacturing-3dmodel+xml" />\n' } + local exts: { [string]: boolean } = {} + for _, f in files do + local e = string.match(f.name, "%.(%w+)$") :: string + if not exts[e] then + exts[e] = true + table.insert(types, fmt('\t<Default Extension="%s" ContentType="%s" />\n', e, f.mime)) + end + end + table.insert(types, "</Types>\n") + local rels = '<?xml version="1.0" encoding="UTF-8"?>\n<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">\n' + .. fmt('\t<Relationship Target="/3D/3dmodel.model" Id="rel0" Type="%s" />\n', REL_MODEL) + .. "</Relationships>\n" + + local w = Zip.writer() + local level = o.level or 6 + local method = if level == 0 then "store" else "deflate" + local ok, err = w:add("[Content_Types].xml", table.concat(types), { level = level, method = method }) + if ok then + ok, err = w:add("_rels/.rels", rels, { level = level, method = method }) + end + if ok then + ok, err = w:add("3D/3dmodel.model", model, { level = level, method = method }) + end + if ok and #files > 0 then + local mr = { '<?xml version="1.0" encoding="UTF-8"?>\n<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">\n' } + for i, f in files do + table.insert(mr, fmt('\t<Relationship Target="/%s" Id="rel%d" Type="%s" />\n', esc(f.name), i, REL_TEXTURE)) + end + table.insert(mr, "</Relationships>\n") + ok, err = w:add("3D/_rels/3dmodel.model.rels", table.concat(mr), { level = level, method = method }) + for _, f in files do + if ok then + ok, err = w:add(f.name, f.data, { method = "store" }) + end + end + end + if not ok then + return nil, err or Err.new(Err.ARG, "zip writer failed") + end + return w:finish() +end + +return Write +end +__FILES["model/b3d"] = function() + +-- model/b3d: Blitz3D .b3d (BB3D chunks, version 1; blitzbasic.com "b3dfile_specs.txt", checked against assimp). +-- Supports: TEXS, BRUS, NODE / MESH / VRTS / TRIS, BONE skins, KEYS + ANIM; left-handed, so z is mirrored. +-- Not supported: writing; several VRTS chunks in one MESH (the first is used); 3 / 4 component texture coordinates. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Read = __include("model/b3d/Read") + +-- ------------------------------------------------------------------------------------------------ contract +local B3d = { + name = "b3d", + category = "model", + extensions = { "b3d" }, + mime = { "model/x-b3d" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/model/Mat4" }, + caps = { decode = true, encode = false, materials = true, textures = true, skins = true, animation = true, colors = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + resolve: ((uri: string) -> any)?, + files: { [string]: any }?, + maxVertices: number?, -- default 2^24 + maxDepth: number?, -- default 256 +} + +-- ------------------------------------------------------------------------------------------------ sniff +function B3d.sniff(r: Bytes.Reader): number + if r:peek(4) == "BB3D" then + return if r:peek(4, 8) ~= "" then 1 else 0.8 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function B3d.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + if r:peek(4) ~= "BB3D" then + return nil, Err.new(Err.CORRUPT, "no BB3D chunk") + end + local ok, scene, msg, kind = pcall(Read.scene, r, opts) + if not ok then + return nil, Err.new(Err.CORRUPT, "bad chunk tree: " .. tostring(scene)) + end + if not scene then + return nil, Err.from(msg, nil, kind) + end + return scene, nil +end + +return B3d +end +__FILES["model/b3d/Read"] = function() + +-- model/b3d/Read: the BB3D chunk tree (4-byte id, u32 little-endian size, no padding) -> Types.Scene. +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Chunks = __include("containers/Chunks") +local Mat4 = __include("codecs/model/Mat4") + +local Read = {} + +type Options = { + resolve: ((uri: string) -> any)?, + files: { [string]: any }?, + maxVertices: number?, + maxDepth: number?, +} + +local LAYOUT: Chunks.Layout = { maxChunks = 1000000 } +local MIME = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", bmp = "image/bmp", tga = "image/x-tga", dds = "image/vnd-ms.dds", gif = "image/gif" } + +type Brush = { name: string, color: { number }, shininess: number, blend: number, fx: number, textures: { number } } +type TexInfo = { file: string, flags: number, blend: number, offset: { number }, scale: { number }, rotation: number, index: number } +type MeshRec = { mesh: number, node: number, count: number, joints: { { number } }, weights: { { number } } } +type Bone = { node: number, target: MeshRec?, list: { number } } +type Keys = { t: { [number]: { number } }, s: { [number]: { number } }, r: { [number]: { number } } } + +-- Blitz3D is left-handed Y up: z mirrored; quaternions are w x y z, conjugated (Blitz3D stores the inverse +-- rotation, as assimp reads them) then mirrored +local function vec(r: Bytes.Reader): { number } + local x, y, z = r:f32le(), r:f32le(), r:f32le() + return { x, y, -z } +end +local function quat(r: Bytes.Reader): { number } + local w, x, y, z = r:f32le(), r:f32le(), r:f32le(), r:f32le() + local l = math.sqrt(w * w + x * x + y * y + z * z) + if l < 1e-12 or l ~= l then + return { 0, 0, 0, 1 } + end + return { x / l, y / l, -z / l, w / l } +end + +local function fetcher(opts: Options?): (string) -> buffer? + local files = opts and opts.files + local resolve = opts and opts.resolve + return function(uri: string): buffer? + local v: any = if type(files) == "table" then files[uri] else nil + if v == nil and type(resolve) == "function" then + local ok, res = pcall(resolve, uri) + v = if ok then res else nil + end + return if type(v) == "string" then buffer.fromstring(v) elseif type(v) == "buffer" then v else nil + end +end + +function Read.scene(src: Bytes.Reader, opts: Options?): (Types.Scene?, string?, string?) + local buf = src.buf + local maxVertices = opts and opts.maxVertices or 2 ^ 24 + local maxDepth = opts and opts.maxDepth or 256 + local fetch = fetcher(opts) + local top = Chunks.walk(buf, src.base, src.limit, LAYOUT) + local head = top[1] + if not head or head.id ~= "BB3D" then + return nil, "not a BB3D file", nil + end + if head.truncated then + return nil, "truncated", "truncated" + end + local hr = Bytes.reader(buf, head.offset, head.size) + local version = hr:i32le() + if hr.err then + return nil, "truncated", "truncated" + end + + local scene = Types.Scene.new() + local texs: { TexInfo } = {} + local brushes: { Brush } = {} + local materialOf: { [number]: number } = {} + local meshes: { MeshRec } = {} + local bones: { Bone } = {} + local nodeKeys: { [number]: Keys } = {} + local anim: { frames: number, fps: number, flags: number }? = nil + local lastMesh: MeshRec? = nil + local totalVertices = 0 + local failure: string?, failKind: string? = nil, nil + + local function fail(msg: string, kind: string?) + if not failure then + failure, failKind = msg, kind + end + end + local function body(c: Chunks.Chunk): Bytes.Reader + if c.truncated then + fail("truncated " .. c.id .. " chunk", "truncated") + end + return Bytes.reader(buf, c.offset, c.avail) + end + + local function readTexs(r: Bytes.Reader) + while r.pos < r.limit and not r.err do + local file = r:cstring() + local t: TexInfo = { file = file, flags = r:i32le(), blend = r:i32le(), offset = { r:f32le(), r:f32le() }, scale = { r:f32le(), r:f32le() }, rotation = r:f32le(), index = 0 } + if r.err then + return fail("truncated TEXS entry", "truncated") + end + local tex: Types.Texture = { name = string.match(file, "([^/\\]+)$") or file, uri = file, mime = MIME[string.lower(string.match(file, "%.(%w+)$") or "")] } + local data = fetch(file) + if not data then + local base = string.match(file, "([^/\\]+)$") + if base and base ~= file then + data = fetch(base) + end + end + tex.data = data + if bit32.band(t.flags, 48) ~= 0 then + tex.sampler = { wrapS = if bit32.band(t.flags, 16) ~= 0 then "clamp" else "repeat", wrapT = if bit32.band(t.flags, 32) ~= 0 then "clamp" else "repeat" } + end + tex.extras = { b3d = { flags = t.flags, blend = t.blend } } + table.insert(scene.textures, tex) + t.index = #scene.textures + table.insert(texs, t) + end + end + + local function readBrus(r: Bytes.Reader) + local n = r:i32le() + if r.err or n < 0 or n > 8 then + return fail("bad BRUS texture count") + end + while r.pos < r.limit and not r.err do + local b: Brush = { name = r:cstring(), color = { r:f32le(), r:f32le(), r:f32le(), r:f32le() }, shininess = r:f32le(), blend = r:i32le(), fx = r:i32le(), textures = {} } + for i = 1, n do + b.textures[i] = r:i32le() + end + if r.err then + return fail("truncated BRUS entry", "truncated") + end + table.insert(brushes, b) + end + end + + local function material(id: number): number? + if id < 0 or id >= #brushes then + return nil + end + local have = materialOf[id] + if have then + return have + end + local b = brushes[id + 1] + local m = Types.Scene.material(b.name ~= "" and b.name or nil) + local c = b.color + local function clamp01(v: number): number + return if v ~= v then 1 else math.clamp(v, 0, 1) + end + m.baseColor = { clamp01(c[1]), clamp01(c[2]), clamp01(c[3]), clamp01(c[4]) } + m.metallic = 0 + m.roughness = 1 - 0.8 * clamp01(b.shininess) + m.doubleSided = bit32.band(b.fx, 16) ~= 0 + if m.baseColor[4] < 1 or bit32.band(b.fx, 32) ~= 0 then + m.alphaMode = "blend" + end + if bit32.band(b.fx, 1) ~= 0 then + m.extensions = { KHR_materials_unlit = {} } + end + local extraTex: { number } = {} + for i, tid in b.textures do + local t = texs[tid + 1] + if tid >= 0 and t then + if not m.baseColorTexture then + local ref: Types.TextureRef = { texture = t.index, texCoord = if bit32.band(t.flags, 65536) ~= 0 then 1 else nil } + local o, s, rot = t.offset, t.scale, t.rotation + if o[1] ~= 0 or o[2] ~= 0 or s[1] ~= 1 or s[2] ~= 1 or rot ~= 0 then + ref.transform = { offset = { o[1], o[2] }, scale = { s[1], s[2] }, rotation = rot } + end + m.baseColorTexture = ref + if bit32.band(t.flags, 4) ~= 0 then + m.alphaMode = "mask" + elseif bit32.band(t.flags, 2) ~= 0 then + m.alphaMode = "blend" + end + else + extraTex[i] = t.index + end + end + end + m.extras = { b3d = { shininess = b.shininess, blend = b.blend, fx = b.fx, textures = if next(extraTex) then extraTex else nil } } + table.insert(scene.materials, m) + materialOf[id] = #scene.materials + return #scene.materials + end + + local function readMesh(r: Bytes.Reader, nodeIndex: number): number? + local master = r:i32le() + if r.err then + fail("truncated MESH", "truncated") + return nil + end + local list = Chunks.walk(buf, r.pos, r.limit, LAYOUT) + local attrs: { [string]: Types.Accessor }? = nil + local count = 0 + local mesh: Types.Mesh = { primitives = {} } + local rec: MeshRec = { mesh = 0, node = nodeIndex, count = 0, joints = {}, weights = {} } + for _, c in list do + local cr = body(c) + if c.id == "VRTS" and not attrs then + local flags, sets, size = cr:i32le(), cr:i32le(), cr:i32le() + if cr.err or sets < 0 or sets > 8 or size < 0 or size > 4 then + fail("bad VRTS header") + return nil + end + local hasN, hasC = bit32.band(flags, 1) ~= 0, bit32.band(flags, 2) ~= 0 + local stride = 12 + (if hasN then 12 else 0) + (if hasC then 16 else 0) + sets * size * 4 + local n = (cr.limit - cr.pos) // stride + totalVertices += n + if totalVertices > maxVertices then + fail(string.format("limit: %d vertices is over the %d vertex limit", totalVertices, maxVertices), "limit") + return nil + end + local pos = buffer.create(n * 12) + local nrm = if hasN then buffer.create(n * 12) else nil + local col = if hasC then buffer.create(n * 16) else nil + local uvs: { buffer } = {} + for s = 1, sets do + uvs[s] = buffer.create(n * 8) + end + local readf32, writef32 = buffer.readf32, buffer.writef32 + local p = cr.pos + for i = 0, n - 1 do + writef32(pos, i * 12, readf32(buf, p)) + writef32(pos, i * 12 + 4, readf32(buf, p + 4)) + writef32(pos, i * 12 + 8, -readf32(buf, p + 8)) + p += 12 + if nrm then + writef32(nrm, i * 12, readf32(buf, p)) + writef32(nrm, i * 12 + 4, readf32(buf, p + 4)) + writef32(nrm, i * 12 + 8, -readf32(buf, p + 8)) + p += 12 + end + if col then + for k = 0, 3 do + writef32(col, i * 16 + k * 4, readf32(buf, p + k * 4)) + end + p += 16 + end + for s = 1, sets do + if size >= 1 then + writef32(uvs[s], i * 8, readf32(buf, p)) + end + if size >= 2 then + writef32(uvs[s], i * 8 + 4, readf32(buf, p + 4)) + end + p += size * 4 + end + end + local a: { [string]: Types.Accessor } = { POSITION = Types.Scene.accessor(pos, "f32", 3, n) } + if nrm then + a.NORMAL = Types.Scene.accessor(nrm, "f32", 3, n) + end + if col then + a.COLOR_0 = Types.Scene.accessor(col, "f32", 4, n) + end + if size > 0 then + for s = 1, sets do + a["TEXCOORD_" .. (s - 1)] = Types.Scene.accessor(uvs[s], "f32", 2, n) + end + end + attrs, count = a, n + mesh.extras = { b3d = { vertexFlags = flags, texCoordSets = sets, texCoordSize = size } } + elseif c.id == "TRIS" then + local brush = cr:i32le() + if cr.err then + fail("truncated TRIS", "truncated") + return nil + end + if not attrs then + fail("TRIS before VRTS") + return nil + end + local nt = (cr.limit - cr.pos) // 12 + local idx = buffer.create(nt * 12) + local readu32, writeu32 = buffer.readu32, buffer.writeu32 + local p = cr.pos + for i = 0, nt - 1 do + local a, b, cc = readu32(buf, p), readu32(buf, p + 4), readu32(buf, p + 8) + if a >= count or b >= count or cc >= count then + fail(string.format("triangle %d: vertex index out of range", i)) + return nil + end + writeu32(idx, i * 12, a) + writeu32(idx, i * 12 + 4, cc) + writeu32(idx, i * 12 + 8, b) + p += 12 + end + local prim: Types.Primitive = { attributes = attrs, indices = Types.Scene.accessor(idx, "u32", 1, nt * 3), mode = "triangles" } + prim.material = material(if brush == -1 then master else brush) + table.insert(mesh.primitives, prim) + end + end + if not attrs then + return nil + end + if #mesh.primitives == 0 then + table.insert(mesh.primitives, { attributes = attrs, mode = "points" :: "points" }) + end + table.insert(scene.meshes, mesh) + rec.mesh, rec.count = #scene.meshes, count + table.insert(meshes, rec) + lastMesh = rec + return #scene.meshes + end + + local function readBone(r: Bytes.Reader, nodeIndex: number) + local b: Bone = { node = nodeIndex, target = lastMesh, list = {} } + table.insert(bones, b) + local list = b.list + while r.pos + 8 <= r.limit do + local v, w = r:i32le(), r:f32le() + table.insert(list, v) + table.insert(list, w) + end + end + + local function readKeys(r: Bytes.Reader, nodeIndex: number) + local flags = r:i32le() + local per = 4 + (if bit32.band(flags, 1) ~= 0 then 12 else 0) + (if bit32.band(flags, 2) ~= 0 then 12 else 0) + (if bit32.band(flags, 4) ~= 0 then 16 else 0) + local k = nodeKeys[nodeIndex] + if not k then + k = { t = {}, s = {}, r = {} } + nodeKeys[nodeIndex] = k + end + while not r.err and r.pos + per <= r.limit do + local frame = r:i32le() + if bit32.band(flags, 1) ~= 0 then + k.t[frame] = vec(r) + end + if bit32.band(flags, 2) ~= 0 then + local x, y, z = r:f32le(), r:f32le(), r:f32le() + k.s[frame] = { x, y, z } + end + if bit32.band(flags, 4) ~= 0 then + k.r[frame] = quat(r) + end + end + end + + local function readNode(c: Chunks.Chunk, depth: number): number? + if depth > maxDepth then + fail("limit: nodes nested deeper than " .. maxDepth, "limit") + return nil + end + local r = body(c) + local name = r:cstring() + local t = vec(r) + local sx, sy, sz = r:f32le(), r:f32le(), r:f32le() + local q = quat(r) + if r.err then + fail("truncated NODE", "truncated") + return nil + end + local node: Types.Node = { name = name, children = {} } + if t[1] ~= 0 or t[2] ~= 0 or t[3] ~= 0 then + node.translation = t + end + if q[1] ~= 0 or q[2] ~= 0 or q[3] ~= 0 then + node.rotation = q + end + if sx ~= 1 or sy ~= 1 or sz ~= 1 then + node.scale = { sx, sy, sz } + end + table.insert(scene.nodes, node) + local index = #scene.nodes + for _, sub in Chunks.walk(buf, r.pos, r.limit, LAYOUT) do + if failure then + break + end + local id = sub.id + if id == "NODE" then + local child = readNode(sub, depth + 1) + if child then + table.insert(node.children, child) + end + elseif id == "MESH" and not node.mesh then + node.mesh = readMesh(body(sub), index) + elseif id == "BONE" then + readBone(body(sub), index) + elseif id == "KEYS" then + readKeys(body(sub), index) + elseif id == "ANIM" then + local ar = body(sub) + local flags, frames, fps = ar:i32le(), ar:i32le(), ar:f32le() + if not ar.err and not anim then + anim = { flags = flags, frames = frames, fps = if fps > 0 and fps < 1e6 then fps else 60 } + end + end + end + return index + end + + for _, c in Chunks.walk(buf, hr.pos, head.offset + head.size, LAYOUT) do + if failure then + break + end + if c.id == "TEXS" then + readTexs(body(c)) + elseif c.id == "BRUS" then + readBrus(body(c)) + elseif c.id == "NODE" then + local n = readNode(c, 1) + if n then + table.insert(scene.roots, n) + end + end + end + if failure then + return nil, failure, failKind + end + if #scene.nodes == 0 then + return nil, "no NODE chunk", nil + end + + -- ------------------------------------------------------------------------------------------ skins + local parent: { [number]: number } = {} + for i, n in scene.nodes do + for _, ch in n.children do + parent[ch] = i + end + end + local worldCache: { [number]: { number } } = {} + local function world(i: number): { number } + local w = worldCache[i] + if not w then + local n = scene.nodes[i] + local l = Mat4.compose(n.translation, n.rotation, n.scale) + w = if parent[i] then Mat4.mul(world(parent[i]), l) else l + worldCache[i] = w + end + return w + end + local bonesOf: { [MeshRec]: { Bone } } = {} + for _, b in bones do + local m = b.target + if m then + local l = bonesOf[m] or {} + bonesOf[m] = l + table.insert(l, b) + end + end + for _, rec in meshes do + local list = bonesOf[rec] + if list then + local nv = rec.count + local inf: { { number } } = {} + local joints: { number } = {} + for j, b in list do + joints[j] = b.node + local l = b.list + for k = 1, #l, 2 do + local v, w = l[k], l[k + 1] + if v >= 0 and v < nv and w > 0 and w == w then + local e = inf[v + 1] + if not e then + e = {} + inf[v + 1] = e + end + table.insert(e, j - 1) + table.insert(e, w) + end + end + end + local self: number? = nil + local jb, wb = buffer.create(nv * 8), buffer.create(nv * 16) + for v = 0, nv - 1 do + local e = inf[v + 1] + if not e then + if not self then + table.insert(joints, rec.node) + self = #joints - 1 + end + buffer.writeu16(jb, v * 8, self :: number) + buffer.writef32(wb, v * 16, 1) + else + local order = {} + for k = 1, #e, 2 do + table.insert(order, k) + end + table.sort(order, function(a: number, b: number): boolean + return e[a + 1] > e[b + 1] + end) + local sum = 0 + for k = 1, math.min(4, #order) do + sum += e[order[k] + 1] + end + for k = 1, math.min(4, #order) do + buffer.writeu16(jb, v * 8 + (k - 1) * 2, e[order[k]]) + buffer.writef32(wb, v * 16 + (k - 1) * 4, e[order[k] + 1] / sum) + end + end + end + local meshWorld = world(rec.node) + local ibm = buffer.create(#joints * 64) + for j, ni in joints do + local inv = Mat4.inverse(world(ni)) or Mat4.identity() + local m = Mat4.mul(inv, meshWorld) + for k = 1, 16 do + buffer.writef32(ibm, (j - 1) * 64 + (k - 1) * 4, m[k]) + end + end + local ia = Types.Scene.accessor(ibm, "f32", 16, #joints) + ia.matrix = true + table.insert(scene.skins, { joints = joints, inverseBindMatrices = ia }) + scene.nodes[rec.node].skin = #scene.skins + local J, W = Types.Scene.accessor(jb, "u16", 4, nv), Types.Scene.accessor(wb, "f32", 4, nv) + for _, prim in scene.meshes[rec.mesh].primitives do + prim.attributes.JOINTS_0 = J + prim.attributes.WEIGHTS_0 = W + end + end + end + + -- ------------------------------------------------------------------------------------------ animation + local fps = if anim then anim.fps else 60 + local channels: { Types.Channel } = {} + for ni = 1, #scene.nodes do + local k = nodeKeys[ni] + if k then + for _, path in { "translation", "rotation", "scale" } do + local map = if path == "translation" then k.t elseif path == "rotation" then k.r else k.s + local frames = {} + for f in map do + table.insert(frames, f) + end + if #frames > 0 then + table.sort(frames) + local nc = if path == "rotation" then 4 else 3 + local input, output = buffer.create(#frames * 4), buffer.create(#frames * nc * 4) + for i, f in frames do + buffer.writef32(input, (i - 1) * 4, f / fps) + local v = map[f] + for c = 1, nc do + buffer.writef32(output, ((i - 1) * nc + c - 1) * 4, v[c]) + end + end + table.insert(channels, { + node = ni, + path = path :: any, + input = Types.Scene.accessor(input, "f32", 1, #frames), + output = Types.Scene.accessor(output, "f32", nc, #frames), + interpolation = "LINEAR" :: "LINEAR", + }) + end + end + end + end + if #channels > 0 then + table.insert(scene.animations, { name = "b3d", channels = channels }) + end + + scene.meta.up = "y" + scene.meta.source = { + format = "b3d", + version = version, + brushes = #brushes, + frames = if anim then anim.frames else nil, + fps = if anim then anim.fps else nil, + handedness = "left", + } + return scene, nil, nil +end + +return Read +end +__FILES["model/bsp"] = function() + +-- model/bsp: compiled game maps, read: Quake 1 (BSP 29), Half-Life (BSP 30), Quake II (IBSP 38), Quake III / RTCW +-- (IBSP 46 / 47). Quake textures need the game's palette (gfx/palette.lmp, not redistributable). Map units, z up. +-- Not supported: Source engine VBSP, Quake 1/2 lightmaps, visibility and collision data, writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Input = __include("core/Input") +local Types = __include("Types") +local Brush = __include("model/bsp/Brush") +local Quake3 = __include("model/bsp/Quake3") + +-- ------------------------------------------------------------------------------------------------ contract +local Bsp = { + name = "bsp", + category = "model", + extensions = { "bsp" }, + mime = { "model/x-bsp" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels" }, + caps = { decode = true, encode = false, variants = { "quake", "halflife", "quake2", "quake3" }, lightmaps = "quake3" }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + palette: (buffer | string)?, -- Quake 1: 768 bytes + resolve: ((uri: string) -> (buffer | string)?)?, + files: { [string]: buffer | string }?, + patchLevel: number?, -- default 4 + maxPixels: number?, -- default 2^24 + maxVertices: number?, -- default 2^24 +} + +-- ------------------------------------------------------------------------------------------------ constants +local Q1_LUMPS = { "entities", "planes", "miptex", "vertices", "visibility", "nodes", "texinfo", "faces", "lighting", + "clipnodes", "leaves", "marksurfaces", "edges", "surfedges", "models" } +local Q2_LUMPS = { "entities", "planes", "vertices", "visibility", "nodes", "texinfo", "faces", "lighting", "leaves", + "leaffaces", "leafbrushes", "edges", "surfedges", "models", "brushes", "brushsides", "pop", "areas", "areaportals" } +local Q3_LUMPS = { "entities", "textures", "planes", "nodes", "leafs", "leaffaces", "leafbrushes", "models", "brushes", + "brushsides", "vertexes", "meshverts", "effects", "faces", "lightmaps", "lightvols", "visdata" } + +-- ------------------------------------------------------------------------------------------------ sniff +function Bsp.sniff(r: Bytes.Reader): number + if r:remaining() < 64 then + return 0 + end + local m = r:peek(4) + local v = buffer.readi32(r.buf, r.pos + (if m == "IBSP" then 4 else 0)) + if m == "IBSP" then + return if v == 38 or v == 46 or v == 47 then 1 else 0.3 + end + if v == 29 or v == 30 then + local size = r:remaining() + for i = 0, 14 do + local o, n = buffer.readi32(r.buf, r.pos + 4 + i * 8), buffer.readi32(r.buf, r.pos + 8 + i * 8) + if o < 0 or n < 0 or o + n > size then + return 0 + end + end + return 0.6 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function entities(text: string): { { [string]: string } } + local out: { { [string]: string } } = {} + for block in string.gmatch(text, "%b{}") do + local e: { [string]: string } = {} + for k, v in string.gmatch(block, '"([^"]*)"%s*"([^"]*)"') do + e[k] = v + end + table.insert(out, e) + end + return out +end + +function Bsp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local size = r.limit - r.base + if size < 8 then + return nil, Err.new(Err.TRUNCATED, "header", 0) + end + local b, base = r.buf, r.base + local m = r:peek(4) + local version = buffer.readi32(b, base + (if m == "IBSP" then 4 else 0)) + local names: { string }, dir: number, variant: string + if m == "IBSP" and version == 38 then + names, dir, variant = Q2_LUMPS, 8, "q2" + elseif m == "IBSP" and (version == 46 or version == 47) then + names, dir, variant = Q3_LUMPS, 8, "q3" + elseif m ~= "IBSP" and (version == 29 or version == 30) then + names, dir, variant = Q1_LUMPS, 4, if version == 30 then "hl" else "q1" + elseif m == "VBSP" then + return nil, Err.new(Err.UNSUPPORTED, "Source engine VBSP maps", 0) + else + return nil, Err.new(Err.UNSUPPORTED, "BSP version " .. version, 0) + end + if dir + #names * 8 > size then + return nil, Err.new(Err.TRUNCATED, "lump directory", dir) + end + local lumps: { [string]: { at: number, size: number } } = {} + for i, name in names do + local o, n = buffer.readi32(b, base + dir + (i - 1) * 8), buffer.readi32(b, base + dir + (i - 1) * 8 + 4) + if o < 0 or n < 0 or o + n > size then + return nil, Err.new(Err.TRUNCATED, "lump " .. name .. " past the end", dir + (i - 1) * 8) + end + lumps[name] = { at = o, size = n } + end + local scene: Types.Scene?, msg: string? + if variant == "q3" then + scene, msg = Quake3.decode(b, base, lumps, opts :: any) + else + local pal = if opts and opts.palette then Bytes.toBuffer(opts.palette) else Input.sibling(opts, "gfx/palette.lmp") + if pal and buffer.len(pal) < 768 then + pal = nil + end + scene, msg = Brush.decode(b, base, lumps, variant, { + palette = pal, + wal = function(name: string): buffer? + return Input.sibling(opts, "textures/" .. name .. ".wal") + end, + maxPixels = opts and opts.maxPixels, + maxVertices = opts and opts.maxVertices, + }) + end + if not scene then + return nil, Err.from(msg) + end + local e = lumps.entities + local text = buffer.readstring(b, base + e.at, e.size) + text = string.match(text, "^[^%z]*") :: string + scene.meta.entities = entities(text) + scene.meta.source = { + format = "bsp", + variant = ({ q1 = "quake", hl = "halflife", q2 = "quake2", q3 = "quake3" } :: { [string]: string })[variant], + version = version, + entities = text, + palette = if variant == "q1" then (opts ~= nil and (opts.palette ~= nil or Input.sibling(opts, "gfx/palette.lmp") ~= nil)) else nil, + } + return scene, nil +end + +return Bsp +end +__FILES["model/bsp/Brush"] = function() + +-- model/bsp/Brush: Quake 1 (BSP 29), Half-Life (BSP 30) and Quake II (IBSP 38) maps -> Scene, from bspfile.h of the +-- Quake / Quake II source releases (no code taken). Texture coordinates: s = v . s.xyz + s.w, divided by the texture +-- size. +local Types = __include("Types") +local Pixels = __include("codecs/image/Pixels") + +local Brush = {} + +local Scene = Types.Scene +local readi32, readu16, readf32, readu32 = buffer.readi32, buffer.readu16, buffer.readf32, buffer.readu32 +local writef32, writeu32 = buffer.writef32, buffer.writeu32 + +type Lump = { at: number, size: number } +type Options = { + palette: buffer?, + wal: ((name: string) -> buffer?)?, -- Quake II: a texture's .wal file (for its size) + maxPixels: number?, + maxVertices: number?, +} + +type Tex = { name: string, width: number, height: number, image: Types.Image?, texels: boolean } +type Batch = { tex: number, pos: { number }, nrm: { number }, uv: { number } } + +local function cstr(b: buffer, at: number, n: number): string + return (string.match(buffer.readstring(b, at, n), "^[^%z]*")) :: string +end + +local function miptex(b: buffer, base: number, l: Lump, hl: boolean, pal: buffer?, maxPixels: number): ({ Tex }?, string?) + local out: { Tex } = {} + if l.size < 4 then + return out, nil + end + local at = base + l.at + local n = readi32(b, at) + if n < 0 or n > 65536 or 4 + n * 4 > l.size then + return nil, "bad miptex lump" + end + local gpal = if pal then Pixels.palette(pal, 0, 256) else nil + for i = 0, n - 1 do + local o = readi32(b, at + 4 + i * 4) + if o < 0 or o + 40 > l.size then + out[i + 1] = { name = "missing" .. i, width = 64, height = 64, image = nil, texels = false } + else + local m = at + o + local name = cstr(b, m, 16) + local w, h, off0 = readu32(b, m + 16), readu32(b, m + 20), readu32(b, m + 24) + local t: Tex = { name = name, width = math.max(w, 1), height = math.max(h, 1), image = nil, texels = false } + if off0 ~= 0 and w > 0 and h > 0 and w * h <= maxPixels then + local px = m + off0 + local need = w * h + local palAt = m + readu32(b, m + 36) + (w // 8) * (h // 8) + 2 + if o + off0 + need <= l.size then + local p = gpal + if hl then + p = if palAt - at + 768 <= l.size then Pixels.palette(b, palAt, 256) else nil + end + local img = Types.Image.new(w, h) + if p then + Pixels.indexed(b, px, w, 8, img.pixels, w, h, true, p) + else + for k = 0, need - 1 do + writeu32(img.pixels, k * 4, 0xFF000000 + buffer.readu8(b, px + k) * 0x10101) + end + end + img.meta.source = { format = "bsp", miptex = name, palette = p ~= nil } + t.image = img + end + end + out[i + 1] = t + end + end + return out, nil +end + +function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, variant: string, opts: Options?): (Types.Scene?, string?) + local q2 = variant == "q2" + local maxPixels = opts and opts.maxPixels or 2 ^ 24 + local V, E, SE, Fc, TI, P, M = lumps.vertices, lumps.edges, lumps.surfedges, lumps.faces, lumps.texinfo, lumps.planes, lumps.models + local nV, nE, nSE, nF = V.size // 12, E.size // 4, SE.size // 4, Fc.size // 20 + local tiSize = if q2 then 76 else 40 + local nTI, nP = TI.size // tiSize, P.size // 20 + local mSize = if q2 then 48 else 64 + local nM = M.size // mSize + if nF > (opts and opts.maxVertices or 2 ^ 24) then + return nil, "limit: too many faces" + end + local texs: { Tex } = {} + local texOf: { number } = {} + if q2 then + local byName: { [string]: number } = {} + for i = 0, nTI - 1 do + local name = cstr(b, base + TI.at + i * 76 + 40, 32) + local ti = byName[name] + if not ti then + local w, h, texels = 1, 1, true + local wal = opts and opts.wal and opts.wal(name) + if wal and buffer.len(wal) >= 40 then + w, h, texels = math.max(1, readu32(wal, 32)), math.max(1, readu32(wal, 36)), false + end + table.insert(texs, { name = name, width = w, height = h, image = nil, texels = texels }) + ti = #texs + byName[name] = ti + end + texOf[i + 1] = ti + end + else + local list, err = miptex(b, base, lumps.miptex, variant == "hl", opts and opts.palette, maxPixels) + if not list then + return nil, err + end + texs = list + for i = 0, nTI - 1 do + local mt = readi32(b, base + TI.at + i * 40 + 32) + texOf[i + 1] = if mt >= 0 and mt < #texs then mt + 1 else 0 + end + end + local scene = Scene.new() + scene.meta.up = "z" + local faceModel: { number } = {} + local models: { { first: number, count: number, origin: { number } } } = {} + for m = 0, nM - 1 do + local o = base + M.at + m * mSize + local origin = { readf32(b, o + 24), readf32(b, o + 28), readf32(b, o + 32) } + local fo = if q2 then 40 else 56 + local first, count = readi32(b, o + fo), readi32(b, o + fo + 4) + table.insert(models, { first = first, count = count, origin = origin }) + if first >= 0 and count >= 0 and first + count <= nF then + for f = first, first + count - 1 do + faceModel[f + 1] = faceModel[f + 1] or (m + 1) + end + end + end + if #models == 0 then + table.insert(models, { first = 0, count = nF, origin = { 0, 0, 0 } }) + for f = 1, nF do + faceModel[f] = 1 + end + end + local batches: { [number]: { [number]: Batch } } = {} + local orders: { [number]: { number } } = {} + local skipped = 0 + for f = 0, nF - 1 do + local fo = base + Fc.at + f * 20 + local plane, side, firstEdge, numEdges, texinfo = readu16(b, fo), readu16(b, fo + 2), readi32(b, fo + 4), readu16(b, fo + 8), readu16(b, fo + 10) + local model = faceModel[f + 1] + if not model or numEdges < 3 or firstEdge < 0 or firstEdge + numEdges > nSE or plane >= nP or texinfo >= nTI then + skipped += 1 + continue + end + local poly: { number } = {} + local ok = true + for k = 0, numEdges - 1 do + local se = readi32(b, base + SE.at + (firstEdge + k) * 4) + local e = math.abs(se) + if e >= nE then + ok = false + break + end + local v = if se >= 0 then readu16(b, base + E.at + e * 4) else readu16(b, base + E.at + e * 4 + 2) + if v >= nV then + ok = false + break + end + local vo = base + V.at + v * 12 + table.insert(poly, readf32(b, vo)) + table.insert(poly, readf32(b, vo + 4)) + table.insert(poly, readf32(b, vo + 8)) + end + if not ok then + skipped += 1 + continue + end + local po = base + P.at + plane * 20 + local nx, ny, nz = readf32(b, po), readf32(b, po + 4), readf32(b, po + 8) + if side ~= 0 then + nx, ny, nz = -nx, -ny, -nz + end + -- Newell's normal of the polygon as stored + local n = #poly // 3 + local ax, ay, az = 0, 0, 0 + for k = 0, n - 1 do + local j = (k + 1) % n + local x1, y1, z1 = poly[k * 3 + 1], poly[k * 3 + 2], poly[k * 3 + 3] + local x2, y2, z2 = poly[j * 3 + 1], poly[j * 3 + 2], poly[j * 3 + 3] + ax += (y1 - y2) * (z1 + z2) + ay += (z1 - z2) * (x1 + x2) + az += (x1 - x2) * (y1 + y2) + end + local order: { number } = {} + if ax * nx + ay * ny + az * nz >= 0 then + for k = 0, n - 1 do + order[k + 1] = k + end + else + order[1] = 0 + for k = 1, n - 1 do + order[k + 1] = n - k + end + end + local tio = base + TI.at + texinfo * tiSize + local sx, sy, sz, so = readf32(b, tio), readf32(b, tio + 4), readf32(b, tio + 8), readf32(b, tio + 12) + local tx, ty, tz, to = readf32(b, tio + 16), readf32(b, tio + 20), readf32(b, tio + 24), readf32(b, tio + 28) + local ti = texOf[texinfo + 1] or 0 + local tex = texs[ti] + local w, h = if tex then tex.width else 1, if tex then tex.height else 1 + local bm = batches[model] or {} + batches[model] = bm + local bt = bm[ti] + if not bt then + bt = { tex = ti, pos = {}, nrm = {}, uv = {} } + bm[ti] = bt + local ol = orders[model] or {} + orders[model] = ol + table.insert(ol, ti) + end + local batch: Batch = bt + for k = 2, n - 1 do + for _, c in { order[1], order[k], order[k + 1] } do + local x, y, z = poly[c * 3 + 1], poly[c * 3 + 2], poly[c * 3 + 3] + local pp, nn, uu = batch.pos, batch.nrm, batch.uv + pp[#pp + 1], pp[#pp + 2], pp[#pp + 3] = x, y, z + nn[#nn + 1], nn[#nn + 2], nn[#nn + 3] = nx, ny, nz + uu[#uu + 1] = (x * sx + y * sy + z * sz + so) / w + uu[#uu + 1] = (x * tx + y * ty + z * tz + to) / h + end + end + end + for i, t in texs do + local tex: Types.Texture = { name = t.name, image = t.image, uri = if t.image then nil else (if q2 then "textures/" .. t.name .. ".wal" else t.name) } + table.insert(scene.textures, tex) + local mat = Scene.material(t.name) + mat.metallic = 0 + local extras: any = { bsp = { texels = if t.texels then true else nil, width = t.width, height = t.height } } + mat.extras = extras + mat.extras = { bsp = { texels = if t.texels then true else nil, width = t.width, height = t.height } } :: any + table.insert(scene.materials, mat) + end + local root: Types.Node = { name = "bsp", children = {} } + table.insert(scene.nodes, root) + scene.roots[1] = 1 + for m, mdl in models do + local list = orders[m] + if list then + local mesh: Types.Mesh = { name = if m == 1 then "world" else "*" .. (m - 1), primitives = {} } + for _, ti in list do + local bt = batches[m][ti] + local nv = #bt.pos // 3 + local pb, nb, ub, ib = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8), buffer.create(nv * 4) + for k = 1, nv * 3 do + writef32(pb, (k - 1) * 4, bt.pos[k]) + writef32(nb, (k - 1) * 4, bt.nrm[k]) + end + for k = 1, nv * 2 do + writef32(ub, (k - 1) * 4, bt.uv[k]) + end + for k = 0, nv - 1 do + writeu32(ib, k * 4, k) + end + table.insert(mesh.primitives, { + attributes = { POSITION = Scene.accessor(pb, "f32", 3, nv), NORMAL = Scene.accessor(nb, "f32", 3, nv), TEXCOORD_0 = Scene.accessor(ub, "f32", 2, nv) }, + indices = Scene.accessor(ib, "u32", 1, nv), + mode = "triangles" :: any, + material = if ti > 0 then ti else nil, + }) + end + table.insert(scene.meshes, mesh) + table.insert(scene.nodes, { name = mesh.name, children = {}, mesh = #scene.meshes, extras = { bsp = { model = m - 1, origin = mdl.origin } } }) + table.insert(root.children, #scene.nodes) + end + end + scene.meta.skippedFaces = skipped + return scene, nil +end + +return Brush +end +__FILES["model/bsp/Quake3"] = function() + +-- model/bsp/Quake3: Quake III Arena maps (IBSP 46; RTCW 47 has the same layout) -> Scene, from the Unofficial Quake 3 +-- Map Specs (Kekoa Proudfoot; no code taken). Lightmaps are 128 x 128 RGB; billboards (flares) are skipped. +local Types = __include("Types") + +local Quake3 = {} + +local Scene = Types.Scene +local readi32, readf32, readu8 = buffer.readi32, buffer.readf32, buffer.readu8 +local writef32, writeu32, writeu8 = buffer.writef32, buffer.writeu32, buffer.writeu8 + +type Lump = { at: number, size: number } +type Options = { patchLevel: number?, maxVertices: number? } + +type Batch = { shader: number, lightmap: number, verts: { number } } -- indices into the vertex lump, or -1 - k for patch vertices + +local function cstr(b: buffer, at: number, n: number): string + return (string.match(buffer.readstring(b, at, n), "^[^%z]*")) :: string +end + +function Quake3.decode(b: buffer, base: number, lumps: { [string]: Lump }, opts: Options?): (Types.Scene?, string?) + local T, M, VX, MV, F, LM = lumps.textures, lumps.models, lumps.vertexes, lumps.meshverts, lumps.faces, lumps.lightmaps + local nT, nM, nV, nMV, nF, nLM = T.size // 72, M.size // 40, VX.size // 44, MV.size // 4, F.size // 104, LM.size // 49152 + local level = math.clamp(math.floor(opts and opts.patchLevel or 4), 1, 16) + local maxV = opts and opts.maxVertices or 2 ^ 24 + -- patch vertices: 12 floats + 4 colour bytes each + local extra: { number } = {} + local function vertex(i: number): { number } + local o = base + VX.at + i * 44 + local v = table.create(14, 0) + for k = 0, 9 do + v[k + 1] = readf32(b, o + k * 4) + end + for k = 0, 3 do + v[11 + k] = readu8(b, o + 40 + k) + end + return v + end + local function addExtra(v: { number }): number + for k = 1, 14 do + table.insert(extra, v[k]) + end + return -(#extra // 14) + end + local faceModel: { number } = {} + for m = 0, nM - 1 do + local o = base + M.at + m * 40 + local first, count = readi32(b, o + 24), readi32(b, o + 28) + if first >= 0 and count >= 0 and first + count <= nF then + for f = first, first + count - 1 do + faceModel[f + 1] = faceModel[f + 1] or (m + 1) + end + end + end + local batches: { [number]: { [string]: Batch } } = {} + local orders: { [number]: { string } } = {} + local counts = { polygons = 0, meshes = 0, patches = 0, billboards = 0, skipped = 0 } + local total = 0 + for f = 0, nF - 1 do + local o = base + F.at + f * 104 + local shader, kind, first, n, mv, nmv, lm = readi32(b, o), readi32(b, o + 8), readi32(b, o + 12), readi32(b, o + 16), readi32(b, o + 20), readi32(b, o + 24), readi32(b, o + 28) + local model = faceModel[f + 1] or 1 + local tris: { number } = {} + if (kind == 1 or kind == 3) and first >= 0 and n >= 0 and first + n <= nV and mv >= 0 and nmv >= 0 and mv + nmv <= nMV then + for k = 0, nmv - 3, 3 do + local ok = true + local tri = {} + for c = 0, 2 do + local idx = readi32(b, base + MV.at + (mv + k + c) * 4) + if idx < 0 or idx >= n then + ok = false + end + tri[c + 1] = first + idx + end + if ok then + table.insert(tris, tri[3]) + table.insert(tris, tri[2]) + table.insert(tris, tri[1]) + end + end + counts[if kind == 1 then "polygons" else "meshes"] += 1 + elseif kind == 2 and first >= 0 and n >= 0 and first + n <= nV then + local w, h = readi32(b, o + 96), readi32(b, o + 100) + if w >= 3 and h >= 3 and w % 2 == 1 and h % 2 == 1 and w * h == n then + counts.patches += 1 + local L = level + for py = 0, (h - 1) // 2 - 1 do + for px = 0, (w - 1) // 2 - 1 do + local ctrl: { { number } } = {} + for j = 0, 2 do + for i = 0, 2 do + ctrl[j * 3 + i + 1] = vertex(first + (py * 2 + j) * w + px * 2 + i) + end + end + local grid: { number } = {} + for gy = 0, L do + local tv = gy / L + for gx = 0, L do + local tu = gx / L + local bu = { (1 - tu) ^ 2, 2 * tu * (1 - tu), tu * tu } + local bv = { (1 - tv) ^ 2, 2 * tv * (1 - tv), tv * tv } + local v = table.create(14, 0) + for j = 0, 2 do + for i = 0, 2 do + local wgt = bu[i + 1] * bv[j + 1] + local cp = ctrl[j * 3 + i + 1] + for k = 1, 14 do + v[k] += cp[k] * wgt + end + end + end + local l = math.sqrt(v[8] ^ 2 + v[9] ^ 2 + v[10] ^ 2) + if l > 0 then + v[8], v[9], v[10] = v[8] / l, v[9] / l, v[10] / l + end + grid[gy * (L + 1) + gx + 1] = addExtra(v) + end + end + for gy = 0, L - 1 do + for gx = 0, L - 1 do + local a, c2 = grid[gy * (L + 1) + gx + 1], grid[gy * (L + 1) + gx + 2] + local d, e = grid[(gy + 1) * (L + 1) + gx + 1], grid[(gy + 1) * (L + 1) + gx + 2] + -- Quake's control grids are clockwise-front + for _, v in { a, d, c2, c2, d, e } do + table.insert(tris, v) + end + end + end + end + end + else + counts.skipped += 1 + end + elseif kind == 4 then + counts.billboards += 1 + else + counts.skipped += 1 + end + total += #tris + if total > maxV then + return nil, "limit: too many vertices" + end + if #tris > 0 then + local key = shader .. ":" .. lm + local bm = batches[model] or {} + batches[model] = bm + local bt = bm[key] + if not bt then + bt = { shader = shader, lightmap = lm, verts = {} } + bm[key] = bt + local ol = orders[model] or {} + orders[model] = ol + table.insert(ol, key) + end + for _, v in tris do + table.insert(bt.verts, v) + end + end + end + local scene = Scene.new() + scene.meta.up = "z" + for i = 0, nT - 1 do + local name = cstr(b, base + T.at + i * 72, 64) + table.insert(scene.textures, { name = name, uri = name }) + end + local lmTex: { [number]: number } = {} + for i = 0, nLM - 1 do + local img = Types.Image.new(128, 128) + local o = base + LM.at + i * 49152 + for k = 0, 128 * 128 - 1 do + writeu8(img.pixels, k * 4, readu8(b, o + k * 3)) + writeu8(img.pixels, k * 4 + 1, readu8(b, o + k * 3 + 1)) + writeu8(img.pixels, k * 4 + 2, readu8(b, o + k * 3 + 2)) + writeu8(img.pixels, k * 4 + 3, 255) + end + img.meta.source = { format = "bsp", lightmap = i } + table.insert(scene.textures, { name = "lightmap " .. i, image = img }) + lmTex[i] = #scene.textures + end + local matOf: { [string]: number } = {} + local root: Types.Node = { name = "bsp", children = {} } + table.insert(scene.nodes, root) + scene.roots[1] = 1 + local modelCount = math.max(nM, 1) + for m = 1, modelCount do + local list = orders[m] + if list then + local mesh: Types.Mesh = { name = if m == 1 then "world" else "*" .. (m - 1), primitives = {} } + for _, key in list do + local bt = batches[m][key] + local nv = #bt.verts + local pb, nb, ub, lb, cb, ib = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8), buffer.create(nv * 8), buffer.create(nv * 4), buffer.create(nv * 4) + for k, id in bt.verts do + local v: { number } + if id >= 0 then + v = vertex(id) + else + local e = (-id - 1) * 14 + v = table.move(extra, e + 1, e + 14, 1, table.create(14, 0)) :: { number } + end + local o = (k - 1) + writef32(pb, o * 12, v[1]) + writef32(pb, o * 12 + 4, v[2]) + writef32(pb, o * 12 + 8, v[3]) + writef32(ub, o * 8, v[4]) + writef32(ub, o * 8 + 4, v[5]) + writef32(lb, o * 8, v[6]) + writef32(lb, o * 8 + 4, v[7]) + writef32(nb, o * 12, v[8]) + writef32(nb, o * 12 + 4, v[9]) + writef32(nb, o * 12 + 8, v[10]) + for c = 0, 3 do + writeu8(cb, o * 4 + c, math.clamp(math.floor(v[11 + c] + 0.5), 0, 255)) + end + writeu32(ib, o * 4, o) + end + local mi = matOf[key] + if not mi then + local name = if bt.shader >= 0 and bt.shader < nT then scene.textures[bt.shader + 1].name else "noshader" + local mat = Scene.material(name) + mat.metallic = 0 + if bt.shader >= 0 and bt.shader < nT then + mat.baseColorTexture = { texture = bt.shader + 1 } + end + local lt = lmTex[bt.lightmap] + mat.extras = { bsp = { lightmap = lt, lightmapTexCoord = if lt then 1 else nil } } + table.insert(scene.materials, mat) + mi = #scene.materials + matOf[key] = mi + end + table.insert(mesh.primitives, { + attributes = { + POSITION = Scene.accessor(pb, "f32", 3, nv), + NORMAL = Scene.accessor(nb, "f32", 3, nv), + TEXCOORD_0 = Scene.accessor(ub, "f32", 2, nv), + TEXCOORD_1 = Scene.accessor(lb, "f32", 2, nv), + COLOR_0 = Scene.accessor(cb, "unorm8", 4, nv), + }, + indices = Scene.accessor(ib, "u32", 1, nv), + mode = "triangles" :: any, + material = mi, + }) + end + table.insert(scene.meshes, mesh) + table.insert(scene.nodes, { name = mesh.name, children = {}, mesh = #scene.meshes, extras = { bsp = { model = m - 1 } } }) + table.insert(root.children, #scene.nodes) + end + end + scene.meta.faces = counts + return scene, nil +end + +return Quake3 +end +__FILES["model/dae"] = function() + +-- model/dae: COLLADA 1.4.1 / 1.5.0 (Khronos specifications; .dae XML, .zae zip with manifest.xml). Supports: geometry, +-- common-profile materials, images, the visual scene, skin / morph controllers, cameras, lights, transform animations. +-- Not supported: <spline> / <brep>, polygon holes (<ph>), Bezier / Hermite curves (sampled linearly), non-transform +-- animation targets, physics / kinematics / non-COMMON FX profiles; writing skins, morphs and animations. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Xml = __include("codecs/text/Xml") +local Zip = __include("containers/Zip") +local Read = __include("model/dae/Read") +local Write = __include("model/dae/Write") + +-- ------------------------------------------------------------------------------------------------ contract +local Dae = { + name = "dae", + category = "model", + extensions = { "dae", "zae" }, + mime = { "model/vnd.collada+xml", "model/vnd.collada+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 }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + resolve: ((uri: string) -> any)?, -- image files (buffer or string) + files: { [string]: any }?, + triangulate: boolean?, -- default true + flipV: boolean?, -- default true + maxVertices: number?, -- default 2^25 +} +type EncodeOptions = { + files: { [string]: any }?, -- receives the texture images (else data: URIs or their uri) + name: string?, + flipV: boolean?, -- default true + format: string?, -- "zae" writes a zip (manifest.xml + model.dae + images) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Dae.sniff(r: Bytes.Reader): number + local head = r:peek(2048) + if string.sub(head, 1, 4) == "PK\3\4" then + local nlen = string.byte(head, 27) or 0 + local name = string.lower(string.sub(head, 31, 30 + nlen)) + if string.find(name, "%.dae$") or name == "manifest.xml" then + return 0.95 + end + return 0 + end + -- UTF-16 files: drop the zero bytes + if string.find(string.sub(head, 1, 4), "\0", 1, true) then + head = string.gsub(head, "%z", "") + end + if string.find(head, "<COLLADA", 1, true) then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function fetcher(opts: DecodeOptions?, zip: any): Read.Fetch + return function(uri: string): buffer? + local v: any = nil + if zip then + local d = zip:read(uri) + if d then + return d + end + end + if not opts then + return nil + end + if type(opts.files) == "table" then + v = opts.files[uri] + if v == nil then + v = opts.files[string.match(uri, "([^/\\]+)$") or uri] + end + end + if v == nil and type(opts.resolve) == "function" then + local ok, res = pcall(opts.resolve, uri) + v = if ok then res else nil + end + if type(v) == "string" then + return buffer.fromstring(v) + end + return if type(v) == "buffer" then v else nil + end +end + +-- a .zae's main .dae: manifest.xml's <dae_root>, else the first .dae entry +local function zae(r: Bytes.Reader): (any, string?, Err.Err?) + local zip, err = Zip.open(r) + if not zip then + return nil, nil, err + end + local main: string? = nil + 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 :: Xml.Node, "dae_root") + if rootEl then + main = string.match(Xml.text(rootEl), "^%s*(.-)%s*$") + main = main and string.gsub(main, "^%./", "") + end + end + if not main or not zip:find(main) then + main = nil + for _, e in zip:list() do + if string.find(string.lower(e.name), "%.dae$") then + main = e.name + break + end + end + end + if not main then + return nil, nil, Err.new(Err.CORRUPT, "zae without a .dae") + end + local text, rerr = zip:readString(main) + if not text then + return nil, nil, rerr + end + return zip, text, nil +end + +function Dae.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local text: string + local zip: any = nil + if r:peek(4) == "PK\3\4" then + local z, t, err = zae(r) + if not z then + return nil, err + end + zip, text = z, t :: string + else + text = buffer.readstring(r.buf, r.base, r.limit - r.base) + end + local doc, xerr = Xml.decode(text) + if not doc then + return nil, xerr + end + local scene, err = Read.scene(doc, fetcher(opts, zip), opts) + if not scene then + return nil, err + end + if zip and scene.meta.source then + scene.meta.source.zae = true + end + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Dae.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(scene) ~= "table" or scene.kind ~= "scene" or type(scene.meshes) ~= "table" or type(scene.nodes) ~= "table" then + return nil, Err.new(Err.ARG, "needs a Scene") + end + if opts and opts.format == "zae" then + local files = {} + local o = table.clone(opts) + o.files = files + o.name = "model.dae" + local text = Write.build(scene, o) + if not text then + return nil, Err.new(Err.ARG, "the scene could not be written") + end + local w = Zip.writer() + w:add("manifest.xml", '<?xml version="1.0" encoding="utf-8"?>\n<dae_root>./model.dae</dae_root>\n') + w:add("model.dae", text) + local names = {} + for name in files do + table.insert(names, name) + end + table.sort(names) + for _, name in names do + w:add(name, files[name], { method = "store" }) + end + return w:finish() + end + local text = Write.build(scene, opts) + if not text then + return nil, Err.new(Err.ARG, "the scene could not be written") + end + return buffer.fromstring(text), nil +end + +return Dae +end +__FILES["model/dae/Math"] = function() + +-- model/dae/Math: the Collada transform elements <lookat> and <skew>; matrices are flat column-major arrays of 16. +local Mat4 = __include("codecs/model/Mat4") + +local DaeMath = {} + +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] } +end +local function norm(a: { number }): { number } + local l = sqrt(a[1] * a[1] + a[2] * a[2] + a[3] * a[3]) + if l < 1e-20 then + return { 0, 0, 0 } + end + return { a[1] / l, a[2] / l, a[3] / l } +end + +-- <lookat>: an object at eye whose -Z looks at interest +function DaeMath.lookat(v: { number }): { number } + local ex, ey, ez = v[1] or 0, v[2] or 0, v[3] or 0 + local z = norm({ ex - (v[4] or 0), ey - (v[5] or 0), ez - (v[6] or 0) }) + local x = norm(cross({ v[7] or 0, v[8] or 1, v[9] or 0 }, z)) + local y = cross(z, x) + return { x[1], x[2], x[3], 0, y[1], y[2], y[3], 0, z[1], z[2], z[3], 0, ex, ey, ez, 1 } +end + +-- <skew> (RenderMan's skew) +function DaeMath.skew(v: { number }): { number } + local a = rad(v[1] or 0) + 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 = Mat4.identity() + -- M = I + s * t * r^T + for row = 0, 2 do + for col = 0, 2 do + m[col * 4 + row + 1] += s * t[row + 1] * r[col + 1] + end + end + return m +end + +return DaeMath +end +__FILES["model/dae/Read"] = function() + +-- model/dae/Read: a parsed Collada document (codecs/text/Xml DOM) -> Scene. +local Err = __include("core/Err") +local Types = __include("Types") +local Xml = __include("codecs/text/Xml") +local Base64 = __include("core/Base64") +local M = __include("model/dae/Math") +local Mat4 = __include("codecs/model/Mat4") + +local Read = {} + +type Fetch = (uri: string) -> buffer? + +local Scene = Types.Scene +local find, sub, gmatch, match, lower, upper = string.find, string.sub, string.gmatch, string.match, string.lower, string.upper +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: { [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 +local function numbers(s: string, limit: number): ({ number }?, string?) + local out = {} + local n = 0 + for w in gmatch(s, "[^%s]+") do + n += 1 + if n > limit then + return nil, "array over the limit" + end + local v = tonumber(w) + if v == nil and find(w, ",", 1, true) and not find(w, ".", 1, true) then + v = tonumber((string.gsub(w, ",", "."))) -- decimal commas (some 3ds Max exporters) + end + if v == nil then + local lw = lower(w) + v = if lw == "nan" or lw == "-nan" or lw == "1.#qnan" or lw == "-1.#ind" then 0 elseif lw == "inf" or lw == "1.#inf" then math.huge elseif lw == "-inf" or lw == "-1.#inf" then -math.huge elseif lw == "true" then 1 elseif lw == "false" then 0 else 0 + end + out[n] = v :: number + end + return out, nil +end +local function words(s: string): { string } + local out = {} + for w in gmatch(s, "[^%s]+") do + table.insert(out, w) + end + return out +end +local function attr(node: any, name: string): string? + local v = node and node.attrs and node.attrs[name] + return if type(v) == "string" then v else nil +end +local function urlId(url: string?): string? + if not url then + return nil + end + return match(url, "^#(.*)$") or url +end +local function lname(node: any): string + return Xml.localName(node.name) +end +local function numText(node: any, default: number): number + if not node then + return default + end + return tonumber(match(text(node), "[^%s]+") or "") or default +end +local function color(node: any): { number }? + local c = node and child(node, "color") + if not c then + return nil + end + local v = numbers(text(c), 16) or {} + return { v[1] or 0, v[2] or 0, v[3] or 0, v[4] or 1 } +end + +type Ctx = { + doc: any, + ids: { [string]: any }, + fetch: Fetch, + scene: Types.Scene, + limit: number, + vertices: number, + flipV: boolean, + triangulate: boolean, + sources: { [any]: any }, + materials: { [string]: number }, + textures: { [string]: number }, + images: { [string]: any }, + meshes: { [string]: number }, + skins: { [string]: number }, + posIndex: { [any]: { number } }, + nodeOf: { [string]: { number } }, + info: { [number]: any }, + pendingSkins: { any }, + skipped: { [string]: number }, + err: string?, + depth: number, +} + +local function skip(C: Ctx, what: string) + C.skipped[what] = (C.skipped[what] or 0) + 1 +end + +-- ------------------------------------------------------------------------------------------------ sources +local function readSource(C: Ctx, el: any): any + local cached = C.sources[el] + if cached ~= nil then + return cached or nil + end + C.sources[el] = false + local arrEl: any = nil + local strings = false + for _, ch in children(el) do + local n = lname(ch) + if n == "float_array" or n == "int_array" or n == "bool_array" then + arrEl = ch + elseif n == "Name_array" or n == "IDREF_array" or n == "SIDREF_array" or n == "token_array" then + arrEl, strings = ch, true + end + end + local values: { any } = {} + if arrEl then + if strings then + values = words(text(arrEl)) + else + local v, e = numbers(text(arrEl), C.limit) + if not v then + C.err = e + return nil + end + values = v + end + end + local tc = child(el, "technique_common") + local acc = tc and child(tc, "accessor") + local out: any + if not acc then + out = { data = values, comps = 1, count = #values } + else + local count = tonumber(attr(acc, "count") or "") or 0 + local stride = tonumber(attr(acc, "stride") or "") or 1 + local offset = tonumber(attr(acc, "offset") or "") or 0 + local picks = {} + local pos = 0 + local anyNamed = false + for _, p in children(acc, "param") do + if attr(p, "name") then + anyNamed = true + end + end + for _, p in children(acc, "param") do + local w = PARAM_SIZE[attr(p, "type") or ""] or 1 + if attr(p, "name") or not anyNamed then + for k = 0, w - 1 do + table.insert(picks, pos + k) + end + end + pos += w + end + if #picks == 0 then + for k = 0, stride - 1 do + table.insert(picks, k) + end + end + if stride < 1 or count < 0 or count * stride > C.limit * 16 then + C.err = "bad accessor" + return nil + end + count = math.min(count, math.max(0, (#values - offset) // math.max(stride, 1))) + local comps = #picks + local data = table.create(count * comps) + local n = 0 + for i = 0, count - 1 do + local base = offset + i * stride + 1 + for _, k in picks do + n += 1 + data[n] = values[base + k] or 0 + end + end + out = { data = data, comps = comps, count = count } + end + C.sources[el] = out + return out +end + +local function sourceById(C: Ctx, url: string?): any + local id = urlId(url) + local el = id and C.ids[id] + if not el or lname(el) ~= "source" then + return nil + end + return readSource(C, el) +end + +-- ------------------------------------------------------------------------------------------------ images, materials +local function fetchImage(C: Ctx, ref: string): (buffer?, string) + local uri = ref + uri = string.gsub(uri, "^file:///(%a:)", "%1") + uri = string.gsub(uri, "^file://", "") + local data = C.fetch(uri) + if not data then + local decoded = string.gsub(uri, "%%(%x%x)", function(h: string): string + return string.char(tonumber(h, 16) :: number) + end) + data = C.fetch(decoded) + if not data then + local base = match(decoded, "([^/\\]+)$") + if base and base ~= decoded then + data = C.fetch(base) + end + end + end + return data, uri +end + +local function image(C: Ctx, id: string): any + local cached = C.images[id] + if cached ~= nil then + return cached or nil + end + C.images[id] = false + local el = C.ids[id] + if not el or lname(el) ~= "image" then + return nil + end + local img: any = { name = attr(el, "name") or id } + local init = child(el, "init_from") + local hex: any = child(el, "data") + if init then + local ref = child(init, "ref") + local s = match(text(ref or init), "^%s*(.-)%s*$") or "" + if s ~= "" then + if sub(s, 1, 5) == "data:" then + local d, mime = Base64.decodeDataUri(s) + if d then + img.data, img.mime = d, mime + end + else + local d, uri = fetchImage(C, s) + img.data, img.uri = d, uri + local ext = match(uri, "%.([%w]+)$") + img.mime = ext and MIME[lower(ext)] + end + end + hex = hex or child(init, "hex") + end + if hex and not img.data then + local h = string.gsub(text(hex), "%s+", "") + if #h % 2 == 0 and not find(h, "[^%x]") then + local b = buffer.create(#h // 2) + for i = 0, #h // 2 - 1 do + buffer.writeu8(b, i, tonumber(sub(h, i * 2 + 1, i * 2 + 2), 16) :: number) + end + img.data = b + local fmt = attr(hex, "format") or attr(el, "format") + img.mime = fmt and MIME[lower(fmt)] + end + end + if img.data and not img.mime then + local b = img.data + if buffer.len(b) >= 4 then + local m4 = buffer.readstring(b, 0, 4) + img.mime = if m4 == "\137PNG" then "image/png" elseif sub(m4, 1, 3) == "\255\216\255" then "image/jpeg" else nil + end + end + C.images[id] = img + return img +end + +local function newparams(effect: any, profile: any, technique: any): { [string]: any } + local out = {} + for _, scope in { effect, profile, technique } do + if scope then + for _, np in children(scope, "newparam") do + local sid = attr(np, "sid") + if sid then + out[sid] = np + end + end + end + end + return out +end + +local function texture(C: Ctx, params: { [string]: any }, samplerSid: string): number? + local np = params[samplerSid] + local imageId: string? = nil + local sampler: any = nil + if np then + local s2d = child(np, "sampler2D") or child(np, "samplerCUBE") or child(np, "sampler3D") + if s2d then + sampler = s2d + local inst = child(s2d, "instance_image") + if inst then + imageId = urlId(attr(inst, "url")) + else + local src = child(s2d, "source") + local surfNp = src and params[match(text(src), "^%s*(.-)%s*$") or ""] + local surf = surfNp and child(surfNp, "surface") + local init = surf and child(surf, "init_from") + if init then + imageId = match(text(init), "^%s*(.-)%s*$") + end + end + else + local surf = child(np, "surface") + local init = surf and child(surf, "init_from") + if init then + imageId = match(text(init), "^%s*(.-)%s*$") + end + end + else + -- many exporters reference the image id directly + imageId = samplerSid + end + if not imageId then + return nil + end + local key = imageId .. "|" .. samplerSid + local cached = C.textures[key] + if cached then + return cached + end + local img = image(C, imageId) + if not img then + return nil + end + local tex: Types.Texture = { name = img.name, data = img.data, mime = img.mime, uri = img.uri } + if sampler then + local ws, wt = child(sampler, "wrap_s"), child(sampler, "wrap_t") + local mag = child(sampler, "magfilter") + local smp: Types.Sampler = {} + if ws then + smp.wrapS = WRAP[upper(match(text(ws), "[%w_]+") or "")] :: any + end + if wt then + smp.wrapT = WRAP[upper(match(text(wt), "[%w_]+") or "")] :: any + end + if mag then + 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 :: any) then + tex.sampler = smp + end + end + table.insert(C.scene.textures, tex) + local idx = #C.scene.textures + C.textures[key] = idx + return idx +end + +local function param(C: Ctx, params: { [string]: any }, el: any, uvsets: { [string]: number }): (any, any) + if not el then + return nil, nil + end + local c = color(el) + local f = child(el, "float") + local tx = child(el, "texture") + local ref: any = nil + if tx then + local ti = texture(C, params, attr(tx, "texture") or "") + if ti then + ref = { texture = ti } + local set = uvsets[attr(tx, "texcoord") or ""] + if set and set > 0 then + ref.texCoord = set + end + end + end + if c then + return c, ref + elseif f then + return numText(f, 0), ref + end + local pr = child(el, "param") + if pr then + local np = params[attr(pr, "ref") or ""] + local v = np and (child(np, "float4") or child(np, "float3") or child(np, "float")) + if v then + local nums = numbers(text(v), 16) or {} + if #nums == 1 then + return nums[1], ref + end + return { nums[1] or 0, nums[2] or 0, nums[3] or 0, nums[4] or 1 }, ref + end + end + return nil, ref +end + +local function material(C: Ctx, id: string, uvsets: { [string]: number }): number? + local cached = C.materials[id] + if cached then + return cached + end + local el = C.ids[id] + if not el or lname(el) ~= "material" then + return nil + end + local mat = Scene.material(attr(el, "name") or id) + mat.metallic = 0 + local inst = child(el, "instance_effect") + local effect = inst and C.ids[urlId(attr(inst, "url")) or ""] + local phong: { [string]: any } = {} + if effect and lname(effect) == "effect" then + local profile = child(effect, "profile_COMMON") + local tech = profile and child(profile, "technique") + local shader: any = nil + if tech then + for _, ch in children(tech) do + local n = lname(ch) + if n == "phong" or n == "blinn" or n == "lambert" or n == "constant" then + shader = ch + phong.model = n + break + end + end + end + local params = newparams(effect, profile, tech) + if shader then + local diffuse, dtex = param(C, params, child(shader, "diffuse"), uvsets) + local emission, etex = param(C, params, child(shader, "emission"), uvsets) + local ambient, atex = param(C, params, child(shader, "ambient"), uvsets) + local specular, stex = param(C, params, child(shader, "specular"), uvsets) + local shininess = param(C, params, child(shader, "shininess"), uvsets) + local reflective = param(C, params, child(shader, "reflective"), uvsets) + local reflectivity = param(C, params, child(shader, "reflectivity"), uvsets) + local transparentEl = child(shader, "transparent") + local transparent, ttex = param(C, params, transparentEl, uvsets) + local transparency = param(C, params, child(shader, "transparency"), uvsets) + local ior = param(C, params, child(shader, "index_of_refraction"), uvsets) + phong.diffuse, phong.diffuseTexture = diffuse, dtex + phong.emission, phong.emissionTexture = emission, etex + phong.ambient, phong.ambientTexture = ambient, atex + phong.specular, phong.specularTexture = specular, stex + phong.shininess, phong.reflective, phong.reflectivity = shininess, reflective, reflectivity + phong.transparent, phong.transparentTexture, phong.transparency = transparent, ttex, transparency + phong.indexOfRefraction = ior + if type(diffuse) == "table" then + mat.baseColor = { diffuse[1], diffuse[2], diffuse[3], 1 } -- its alpha is not opacity (exporters write 0) + end + if phong.model == "constant" and type(emission) == "table" then + mat.baseColor = { emission[1], emission[2], emission[3], 1 } + mat.extensions = { KHR_materials_unlit = {} } + end + if dtex then + mat.baseColorTexture = dtex + if type(diffuse) ~= "table" then + mat.baseColor = { 1, 1, 1, 1 } + end + end + if type(emission) == "table" and phong.model ~= "constant" then + mat.emissive = { emission[1], emission[2], emission[3] } + end + if etex then + mat.emissiveTexture = etex + mat.emissive = { 1, 1, 1 } + end + if type(shininess) == "number" then + mat.roughness = math.clamp(math.sqrt(2 / (math.max(shininess, 0) + 2)), 0, 1) + end + -- Collada 1.4.1 section 7: A_ONE (default) uses transparent.a, RGB_ZERO the luminance + if transparentEl and (type(transparent) == "table" or type(transparency) == "number") then + local mode = attr(transparentEl, "opaque") or "A_ONE" + local tv = if type(transparency) == "number" then transparency else 1 + local tc: any = if type(transparent) == "table" then transparent else { 1, 1, 1, 1 } + local a: number + if mode == "RGB_ZERO" then + a = 1 - tv * (tc[1] * 0.212671 + tc[2] * 0.71516 + tc[3] * 0.072169) + elseif mode == "A_ZERO" then + a = 1 - tv * tc[4] + elseif mode == "RGB_ONE" then + a = tv * (tc[1] * 0.212671 + tc[2] * 0.71516 + tc[3] * 0.072169) + else + a = tv * tc[4] + end + a = math.clamp(a, 0, 1) + if a < 0.999 and a > 0.001 then + mat.baseColor[4] = a + mat.alphaMode = "blend" + end + phong.opacity = a + end + if ttex then + mat.alphaMode = "blend" + end + end + -- FCOLLADA / MAX3D / OpenCOLLADA extras: bump maps and double sidedness + for _, scope in { tech, profile, effect } do + if scope then + for _, ex in children(scope, "extra") do + for _, tq in children(ex, "technique") do + local bump = child(tq, "bump") + if bump and not mat.normalTexture then + local _, btex = param(C, params, bump, uvsets) + if btex then + mat.normalTexture = btex + end + end + local ds = child(tq, "double_sided") + if ds and numText(ds, 0) ~= 0 then + mat.doubleSided = true + end + end + end + end + end + end + mat.extras = { phong = phong } + table.insert(C.scene.materials, mat) + local idx = #C.scene.materials + C.materials[id] = idx + return idx +end + +-- ------------------------------------------------------------------------------------------------ geometry +type Input = { semantic: string, source: any, offset: number, set: number } + +local function inputs(C: Ctx, prim: any, verticesEl: any): ({ Input }, number) + local out: { Input } = {} + local stride = 0 + for _, inp in children(prim, "input") do + local sem = upper(attr(inp, "semantic") or "") + local offset = tonumber(attr(inp, "offset") or "") or 0 + local set = tonumber(attr(inp, "set") or "") or 0 + if offset + 1 > stride then + stride = offset + 1 + end + if sem == "VERTEX" then + local vel = C.ids[urlId(attr(inp, "source")) or ""] or verticesEl + if vel and lname(vel) == "vertices" then + for _, vin in children(vel, "input") do + local vs = upper(attr(vin, "semantic") or "") + local src = sourceById(C, attr(vin, "source")) + if src then + table.insert(out, { semantic = vs, source = src, offset = offset, set = tonumber(attr(vin, "set") or "") or set }) + end + end + end + else + local src = sourceById(C, attr(inp, "source")) + if src then + table.insert(out, { semantic = sem, source = src, offset = offset, set = set }) + end + end + end + return out, math.max(stride, 1) +end + +local function corners(C: Ctx, prim: any, kind: string, stride: number): ({ number }?, { number }?, { number }?, string) + local p: { number } = {} + local faces: { number } = {} + local starts: { number } = {} + local function addP(el: any): (number, number) + local v, e = numbers(text(el), C.limit) + if not v then + C.err = e + return 0, 0 + end + local base = #p + table.move(v, 1, #v, base + 1, p) + return base // stride, #v // stride + end + if kind == "triangles" or kind == "lines" then + local per = if kind == "triangles" then 3 else 2 + local pe = child(prim, "p") + if pe then + local _, n = addP(pe) + local count = math.min(tonumber(attr(prim, "count") or "") or n // per, n // per) + for f = 0, count - 1 do + table.insert(faces, per) + for k = 0, per - 1 do + table.insert(starts, f * per + k) + end + end + end + return p, faces, starts, kind + elseif kind == "polylist" then + local pe = child(prim, "p") + local vc = child(prim, "vcount") + if pe and vc then + local _, n = addP(pe) + local counts = numbers(text(vc), C.limit) or {} + local at = 0 + for _, c in counts do + c = math.floor(c) + if c < 0 or at + c > n then + break + end + table.insert(faces, c) + for k = 0, c - 1 do + table.insert(starts, at + k) + end + at += c + end + end + return p, faces, starts, "polygons" + elseif kind == "polygons" then + local list = children(prim, "p") + for _, ph in children(prim, "ph") do + local outer = child(ph, "p") + if outer then + table.insert(list, outer) + end + skip(C, "polygon holes") + end + for _, pe in list do + local first, n = addP(pe) + if n > 0 then + table.insert(faces, n) + for k = 0, n - 1 do + table.insert(starts, first + k) + end + end + end + return p, faces, starts, "polygons" + elseif kind == "linestrips" then + for _, pe in children(prim, "p") do + local first, n = addP(pe) + for k = 0, n - 2 do + table.insert(faces, 2) + table.insert(starts, first + k) + table.insert(starts, first + k + 1) + end + end + return p, faces, starts, "lines" + elseif kind == "tristrips" or kind == "trifans" then + for _, pe in children(prim, "p") do + local first, n = addP(pe) + for k = 0, n - 3 do + table.insert(faces, 3) + if kind == "trifans" then + table.insert(starts, first) + table.insert(starts, first + k + 1) + table.insert(starts, first + k + 2) + elseif k % 2 == 0 then + table.insert(starts, first + k) + table.insert(starts, first + k + 1) + table.insert(starts, first + k + 2) + else + table.insert(starts, first + k + 1) + table.insert(starts, first + k) + table.insert(starts, first + k + 2) + end + end + end + return p, faces, starts, "triangles" + end + return nil, nil, nil, kind +end + +local PRIMS = { triangles = true, polylist = true, polygons = true, lines = true, linestrips = true, tristrips = true, trifans = true } + +type Built = { prim: Types.Primitive, symbol: string?, texSets: { number }, posIndex: { number } } + +local function buildPrim(C: Ctx, prim: any, verticesEl: any, kind: string): Built? + local ins, stride = inputs(C, prim, verticesEl) + local p, faces, starts, mode = corners(C, prim, kind, stride) + if C.err or not p or not faces or not starts then + return nil + end + local posIn: Input? = nil + for _, i in ins do + if i.semantic == "POSITION" then + posIn = i + break + end + end + if not posIn then + skip(C, "primitives without positions") + return nil + end + local named: { { input: Input, name: string, comps: number } } = {} + local texSets: { number } = {} + local texInputs: { Input } = {} + local colorN, normalSeen = 0, false + for _, i in ins do + if i.semantic == "TEXCOORD" then + table.insert(texInputs, i) + end + end + table.sort(texInputs, function(a: Input, b: Input): boolean + if a.set ~= b.set then + return a.set < b.set + end + return a.offset < b.offset + end) + for k, i in texInputs do + texSets[k] = i.set + table.insert(named, { input = i, name = "TEXCOORD_" .. (k - 1), comps = 2 }) + end + for _, i in ins do + local s = i.semantic + local comps = math.min(i.source.comps, 4) + if s == "POSITION" then + if i == posIn then + table.insert(named, { input = i, name = "POSITION", comps = 3 }) + end + elseif s == "NORMAL" then + table.insert(named, { input = i, name = if normalSeen then "_NORMAL" .. i.set else "NORMAL", comps = 3 }) + normalSeen = true + elseif s == "COLOR" then + table.insert(named, { input = i, name = "COLOR_" .. colorN, comps = if comps >= 4 then 4 else 3 }) + colorN += 1 + elseif s ~= "TEXCOORD" then + table.insert(named, { input = i, name = "_" .. s .. (if i.set ~= 0 then tostring(i.set) else ""), comps = math.max(comps, 1) }) + end + end + local np = #p + local keyOf: { [any]: number } = {} + local tuples: { number } = {} + local corner = table.create(#starts) :: { number } + local count = 0 + for ci, s in starts do + local base = s * stride + if base + stride > np then + C.err = "index list too short" + return nil + end + local key: any + if stride == 1 then + key = p[base + 1] + else + key = table.concat(p, ",", base + 1, base + stride) + end + local v = keyOf[key] + if not v then + v = count + count += 1 + keyOf[key] = v + tuples[count] = base + end + corner[ci] = v + end + C.vertices += count + if C.vertices > C.limit then + C.err = "over the vertex limit" + return nil + end + local attributes: { [string]: Types.Accessor } = {} + local posIndex = table.create(count, 0) + for _, a in named do + local src = a.input.source + local comps, scomps = a.comps, src.comps + local data, n = src.data, src.count + local buf = buffer.create(count * comps * 4) + local off = a.input.offset + 1 + local isTex = sub(a.name, 1, 9) == "TEXCOORD_" + local isPos = a.name == "POSITION" + for v = 0, count - 1 do + local idx = p[tuples[v + 1] + off] + if idx == nil or idx < 0 or idx >= n or idx ~= idx // 1 then + C.err = "index out of range" + return nil + end + if isPos then + posIndex[v + 1] = idx + end + local at = idx * scomps + for k = 1, comps do + local x = if k <= scomps then data[at + k] else (if k == 4 then 1 else 0) + if type(x) ~= "number" then + x = 0 + end + if isTex and k == 2 and C.flipV then + x = 1 - x + end + buffer.writef32(buf, (v * comps + k - 1) * 4, x) + end + end + attributes[a.name] = Scene.accessor(buf, "f32", comps, count) + end + local nc = #corner + local out: Types.Primitive = { attributes = attributes, mode = "triangles" } + if mode == "polygons" then + local allTri = true + for _, f in faces do + if f ~= 3 then + allTri = false + break + end + end + if allTri then + mode = "triangles" + elseif C.triangulate then + local tri: { number } = {} + local at = 0 + for _, f in faces do + for k = 1, f - 2 do + table.insert(tri, corner[at + 1]) + table.insert(tri, corner[at + k + 1]) + table.insert(tri, corner[at + k + 2]) + end + at += f + end + corner, nc, mode = tri, #tri, "triangles" + else + local fb = buffer.create(#faces * 4) + for i, f in faces do + buffer.writeu32(fb, (i - 1) * 4, f) + end + out.faces = Scene.accessor(fb, "u32", 1, #faces) + end + end + out.mode = mode :: any + local ib = buffer.create(nc * 4) + for i = 1, nc do + buffer.writeu32(ib, (i - 1) * 4, corner[i]) + end + out.indices = Scene.accessor(ib, "u32", 1, nc) + return { prim = out, symbol = attr(prim, "material"), texSets = texSets, posIndex = posIndex } +end + +local function geometry(C: Ctx, el: any): { Built }? + local cached = C.posIndex[el] + if cached then + return cached :: any + end + local mesh = child(el, "mesh") or child(el, "convex_mesh") + if not mesh then + if child(el, "spline") or child(el, "brep") then + skip(C, "spline / brep geometry") + end + return nil + end + local verticesEl = child(mesh, "vertices") + local out: { Built } = {} + for _, ch in children(mesh) do + local n = lname(ch) + if PRIMS[n] then + local b = buildPrim(C, ch, verticesEl, n) + if C.err then + return nil + end + if b then + table.insert(out, b) + end + end + end + C.posIndex[el] = out :: any + return out +end + +local function bindings(node: any): ({ [string]: string }, { [string]: { [string]: number } }) + local syms: { [string]: string } = {} + local sets: { [string]: { [string]: number } } = {} + local bm = node and child(node, "bind_material") + local tc = bm and child(bm, "technique_common") + if tc then + for _, im in children(tc, "instance_material") do + local sym, target = attr(im, "symbol"), urlId(attr(im, "target")) + if sym and target then + syms[sym] = target + local s = {} + for _, bvi in children(im, "bind_vertex_input") do + local sem = attr(bvi, "semantic") + if sem then + s[sem] = tonumber(attr(bvi, "input_set") or "") or 0 + end + end + sets[sym] = s + end + end + end + return syms, sets +end + +local function copyAccessor(a: Types.Accessor): Types.Accessor + local b = buffer.create(buffer.len(a.data)) + buffer.copy(b, 0, a.data) + return Scene.accessor(b, a.type, a.components, a.count) +end + +local function meshFor(C: Ctx, geomEl: any, inst: any, key: string, bindShape: { number }?): (number?, { Built }?) + local syms, sets = bindings(inst) + local parts = { key } + for s, t in syms do + table.insert(parts, s .. "=" .. t) + end + table.sort(parts) + local k = table.concat(parts, ";") + local built = geometry(C, geomEl) + if not built or #built == 0 then + return nil, nil + end + local cached = C.meshes[k] + if cached then + return cached, built + end + local mesh: Types.Mesh = { name = attr(geomEl, "name") or attr(geomEl, "id"), primitives = {} } + for _, b in built do + local prim = b.prim + if bindShape then + local attrs = table.clone(prim.attributes) + 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 = 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 = 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) + x, y, z = nm[1] * x + nm[5] * y + nm[9] * z, nm[2] * x + nm[6] * y + nm[10] * z, nm[3] * x + nm[7] * y + nm[11] * z + local l = math.sqrt(x * x + y * y + z * z) + if l > 0 then + x, y, z = x / l, y / l, z / l + end + buffer.writef32(nrm.data, v * 12, x) + buffer.writef32(nrm.data, v * 12 + 4, y) + buffer.writef32(nrm.data, v * 12 + 8, z) + end + attrs.NORMAL = nrm + end + prim = table.clone(prim) + prim.attributes = attrs + else + prim = table.clone(prim) + end + local sym = b.symbol + local target = sym and (syms[sym] or (if C.ids[sym] and lname(C.ids[sym]) == "material" then sym else nil)) + if not target then + -- no (or an unbound) symbol and a single binding: that one (MakeHuman leaves out the symbol) + local only, n = nil, 0 + for s2 in syms do + only, n = s2, n + 1 + end + if n == 1 then + sym = only + target = syms[only :: string] + end + end + if target then + local uv: { [string]: number } = {} + for sem, set in (sym and sets[sym]) or {} do + uv[sem] = (table.find(b.texSets, set) or 1) - 1 + end + prim.material = material(C, target, uv) + end + table.insert(mesh.primitives, prim) + end + table.insert(C.scene.meshes, mesh) + local idx = #C.scene.meshes + C.meshes[k] = idx + return idx, built +end + +local function morphMesh(C: Ctx, ctrl: any, morph: any, inst: any): number? + local base = C.ids[urlId(attr(morph, "source")) or ""] + if not base or lname(base) ~= "geometry" then + return nil + end + local idx, built = meshFor(C, base, inst, "morph:" .. (attr(ctrl, "id") or ""), nil) + if not idx or not built then + return nil + end + local mesh = C.scene.meshes[idx] + if mesh.weights then + return idx + end + local relative = upper(attr(morph, "method") or "NORMALIZED") == "RELATIVE" + local targetsEl = child(morph, "targets") + local targetIds: { string } = {} + local weights: { number } = {} + if targetsEl then + for _, inp in children(targetsEl, "input") do + local sem = upper(attr(inp, "semantic") or "") + local src = sourceById(C, attr(inp, "source")) + if src and sem == "MORPH_TARGET" then + for _, v in src.data do + table.insert(targetIds, tostring(v)) + end + elseif src and sem == "MORPH_WEIGHT" then + for _, v in src.data do + table.insert(weights, if type(v) == "number" then v else 0) + end + end + end + end + local tbuilt: { { Built } } = {} + for _, tid in targetIds do + local g = C.ids[tid] + local tb = g and lname(g) == "geometry" and geometry(C, g) + if not tb or #tb ~= #built then + skip(C, "morph targets with another topology") + return idx + end + table.insert(tbuilt, tb) + end + for pi, prim in mesh.primitives do + local targets = {} + for ti, tb in tbuilt do + local tp = tb[pi].prim + local t: { [string]: Types.Accessor } = {} + for _, name in { "POSITION", "NORMAL" } do + local a, b = prim.attributes[name], tp.attributes[name] + if a and b and a.count == b.count then + local d = buffer.create(a.count * 12) + for i = 0, a.count * 3 - 1 do + local bv = buffer.readf32(b.data, i * 4) + buffer.writef32(d, i * 4, if relative then bv else bv - buffer.readf32(a.data, i * 4)) + end + t[name] = Scene.accessor(d, "f32", 3, a.count) + end + end + targets[ti] = t + end + prim.targets = targets + end + mesh.weights = weights + return idx +end + +-- ------------------------------------------------------------------------------------------------ cameras, lights +local function camera(C: Ctx, el: any): number? + local optics = child(el, "optics") + local tc = optics and child(optics, "technique_common") + if not tc then + return nil + end + local cam: Types.Camera + local persp, ortho = child(tc, "perspective"), child(tc, "orthographic") + if persp then + local xfov, yfov = child(persp, "xfov"), child(persp, "yfov") + local aspect = child(persp, "aspect_ratio") + local ar = if aspect then numText(aspect, 1) else nil + local yf: number + if yfov then + yf = math.rad(numText(yfov, 45)) + elseif xfov and ar then + yf = 2 * math.atan(math.tan(math.rad(numText(xfov, 45)) / 2) / ar) + else + yf = math.rad(numText(xfov, 45)) + end + if xfov and yfov and not ar then + 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" :: "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" :: "orthographic", xmag = x, ymag = y, znear = numText(child(ortho, "znear"), 0.1), zfar = numText(child(ortho, "zfar"), 1000) } :: Types.Camera + else + return nil + end + table.insert(C.scene.cameras, cam) + return #C.scene.cameras +end + +local function light(C: Ctx, el: any): (number?, { number }?) + local tc = child(el, "technique_common") + if not tc then + return nil, nil + end + local amb = child(tc, "ambient") + if amb then + return nil, color(amb) or { 1, 1, 1, 1 } + end + local kinds: { [string]: string } = { directional = "directional", point = "point", spot = "spot" } + for k, t in kinds do + local l = child(tc, k) + if l then + local c = color(l) or { 1, 1, 1 } + local lt: Types.Light = { name = attr(el, "name") or attr(el, "id"), type = t :: any, color = { c[1], c[2], c[3] }, intensity = 1 } + if t == "spot" then + local fa = numText(child(l, "falloff_angle"), 180) + lt.outerCone = math.clamp(math.rad(fa) / 2, 0, math.pi / 2) + lt.innerCone = 0 + end + table.insert(C.scene.lights, lt) + local idx = #C.scene.lights + if t ~= "directional" then + lt.extras = { + dae = { + constantAttenuation = numText(child(l, "constant_attenuation"), 1), + linearAttenuation = numText(child(l, "linear_attenuation"), 0), + quadraticAttenuation = numText(child(l, "quadratic_attenuation"), 0), + falloffExponent = if t == "spot" then numText(child(l, "falloff_exponent"), 0) else nil, + }, + } :: any + end + return idx, nil + end + end + return nil, nil +end + +-- ------------------------------------------------------------------------------------------------ nodes +local XFORMS = { matrix = 16, translate = 3, rotate = 4, scale = 3, lookat = 9, skew = 7 } + +local function xfMatrix(kind: string, v: { number }): { number } + if kind == "matrix" then + return Mat4.fromRows(v) + elseif kind == "translate" then + return Mat4.translation(v[1] or 0, v[2] or 0, v[3] or 0) + elseif kind == "rotate" then + 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 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 Mat4.identity() +end + +local function compose(xf: { any }): { number } + local m = Mat4.identity() + for _, x in xf do + 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 = 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 + node.translation = t + end + if math.abs(r[4]) < 1 - 1e-9 then + node.rotation = r + end + if math.abs(s[1] - 1) > 1e-7 or math.abs(s[2] - 1) > 1e-7 or math.abs(s[3] - 1) > 1e-7 then + node.scale = s + end + else + for i = 1, 16 do + if math.abs(m[i] - Mat4.identity()[i]) > 0 then + node.matrix = m + break + end + end + end +end + +local visitNode: (C: Ctx, el: any) -> number? + +local function addChild(C: Ctx, parent: Types.Node, node: Types.Node): number + table.insert(C.scene.nodes, node) + local idx = #C.scene.nodes + table.insert(parent.children, idx) + return idx +end + +-- extra instances of a node go on child nodes +local function instances(C: Ctx, el: any, node: Types.Node, idx: number) + local function slot(kind: string, name: string?): (Types.Node, number) + local n: any = node + if n[kind] == nil then + return node, idx + end + local extra: Types.Node = { name = name, children = {} } + return extra, addChild(C, node, extra) + end + for _, ch in children(el) do + local n = lname(ch) + if n == "instance_geometry" then + local g = C.ids[urlId(attr(ch, "url")) or ""] + if g and lname(g) == "geometry" then + local mi = meshFor(C, g, ch, "geom:" .. (attr(g, "id") or ""), nil) + if C.err then + return + end + if mi then + local target = slot("mesh", attr(g, "name")) + target.mesh = mi + end + end + elseif n == "instance_controller" then + local ctrl = C.ids[urlId(attr(ch, "url")) or ""] + local skinEl = ctrl and child(ctrl, "skin") + local morph = ctrl and child(ctrl, "morph") + if skinEl then + -- the skin's source may be a morph controller + local src = C.ids[urlId(attr(skinEl, "source")) or ""] + local morphEl = src and lname(src) == "controller" and child(src, "morph") + if morphEl then + src = C.ids[urlId(attr(morphEl, "source")) or ""] + skip(C, "skins over morph controllers (morph dropped)") + end + if src and lname(src) == "geometry" then + local bsm = child(skinEl, "bind_shape_matrix") + 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 + end + if mi and built then + local target, ti = slot("mesh", attr(ctrl, "name")) + target.mesh = mi + local roots = {} + for _, sk in children(ch, "skeleton") do + table.insert(roots, urlId(match(text(sk), "^%s*(.-)%s*$"))) + end + table.insert(C.pendingSkins, { node = ti, ctrl = ctrl, skin = skinEl, mesh = mi, built = built, roots = roots, bind = bind }) + end + end + elseif morph then + local mi = morphMesh(C, ctrl, morph, ch) + if C.err then + return + end + if mi then + local target = slot("mesh", attr(ctrl, "name")) + target.mesh = mi + target.weights = C.scene.meshes[mi].weights + end + end + elseif n == "instance_camera" then + local cel = C.ids[urlId(attr(ch, "url")) or ""] + local ci = cel and lname(cel) == "camera" and camera(C, cel) + if ci then + local target = slot("camera", C.scene.cameras[ci].name) + target.camera = ci + end + elseif n == "instance_light" then + local lel = C.ids[urlId(attr(ch, "url")) or ""] + if lel and lname(lel) == "light" then + local li, ambient = light(C, lel) + if li then + local target = slot("light", C.scene.lights[li].name) + target.light = li + elseif ambient then + local ex: any = node.extras or {} + ex.dae = ex.dae or {} + ex.dae.ambientLight = ambient + node.extras = ex + end + end + elseif n == "instance_node" then + local target = C.ids[urlId(attr(ch, "url")) or ""] + if target and lname(target) == "node" then + local ci = visitNode(C, target) + if ci then + table.insert(node.children, ci) + end + end + end + end +end + +visitNode = function(C: Ctx, el: any): number? + if C.depth > 256 or #C.scene.nodes > C.limit then + C.err = "node tree too deep or too large (instance_node cycle?)" + return nil + end + C.depth += 1 + local xf = {} + for _, ch in children(el) do + local n = lname(ch) + local want = XFORMS[n] + if want then + local v = numbers(text(ch), 64) or {} + table.insert(xf, { kind = n, sid = attr(ch, "sid"), values = v }) + end + end + local node: Types.Node = { name = attr(el, "name") or attr(el, "id"), children = {} } + setTransform(node, compose(xf)) + table.insert(C.scene.nodes, node) + local idx = #C.scene.nodes + local id = attr(el, "id") + C.info[idx] = { xf = xf, sid = attr(el, "sid"), id = id, joint = upper(attr(el, "type") or "") == "JOINT" } + if id then + C.nodeOf[id] = C.nodeOf[id] or {} + table.insert(C.nodeOf[id], idx) + end + if upper(attr(el, "type") or "") == "JOINT" then + node.extras = { dae = { joint = true, sid = attr(el, "sid") } } :: any + end + instances(C, el, node, idx) + for _, ch in children(el, "node") do + if C.err then + break + end + local ci = visitNode(C, ch) + if ci then + table.insert(node.children, ci) + end + end + C.depth -= 1 + return idx +end + +-- ------------------------------------------------------------------------------------------------ skins +-- joints: by sid below the skeleton roots, else by sid / id / name anywhere +local function findJoint(C: Ctx, name: string, roots: { number }, byId: boolean): number? + local nodes = C.scene.nodes + local function search(i: number, depth: number): number? + if depth > 300 then + return nil + end + local inf = C.info[i] + if inf and (inf.sid == name or (byId and inf.id == name)) then + return i + end + for _, c in nodes[i].children do + local r = search(c, depth + 1) + if r then + return r + end + end + return nil + end + for _, r in roots do + local f = search(r, 0) + if f then + return f + end + end + for i in nodes do + local inf = C.info[i] + if inf and (inf.sid == name or inf.id == name) then + return i + end + end + for i, n in nodes do + if n.name == name then + return i + end + end + return nil +end + +local function resolveSkins(C: Ctx) + local cache: { [string]: number } = {} + for _, ps in C.pendingSkins do + local skinEl = ps.skin + local jointsEl = child(skinEl, "joints") + local names: { string } = {} + local byId = false + local ibm: any = nil + if jointsEl then + for _, inp in children(jointsEl, "input") do + local sem = upper(attr(inp, "semantic") or "") + local srcEl = C.ids[urlId(attr(inp, "source")) or ""] + local src = srcEl and lname(srcEl) == "source" and readSource(C, srcEl) + if src and sem == "JOINT" then + for _, v in src.data do + table.insert(names, tostring(v)) + end + byId = child(srcEl, "IDREF_array") ~= nil + elseif src and sem == "INV_BIND_MATRIX" then + ibm = src + end + end + end + local roots: { number } = {} + for _, r in ps.roots do + for _, ni in C.nodeOf[r] or {} do + table.insert(roots, ni) + end + end + local jointNodes: { number } = {} + local ok = #names > 0 + for i, nm in names do + local j = findJoint(C, nm, roots, byId) + if not j then + ok = false + break + end + jointNodes[i] = j + end + if not ok then + skip(C, "skins with unresolved joints") + continue + end + local key = (attr(ps.ctrl, "id") or "") .. "|" .. table.concat(jointNodes, ",") + local si = cache[key] + if not si then + local skin: Types.Skin = { name = attr(ps.ctrl, "name") or attr(ps.ctrl, "id"), joints = jointNodes } + if ps.bind then + local sk: any = skin + sk.extras = { dae = { bindShapeMatrix = ps.bind } } + end + 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 = Mat4.fromRows(ibm.data, i * 16 + 1) + for k = 1, 16 do + buffer.writef32(b, (i * 16 + k - 1) * 4, cm[k]) + end + end + local acc = Scene.accessor(b, "f32", 16, #names) + acc.matrix = true + skin.inverseBindMatrices = acc + end + if roots[1] then + skin.skeleton = roots[1] + end + table.insert(C.scene.skins, skin) + si = #C.scene.skins + cache[key] = si + end + C.scene.nodes[ps.node].skin = si + local mesh = C.scene.meshes[ps.mesh] + if mesh.primitives[1] and mesh.primitives[1].attributes.JOINTS_0 then + continue + end + local vw = child(skinEl, "vertex_weights") + if not vw then + continue + end + local jOff, wOff, wSrc = 0, 1, nil + local stride = 1 + for _, inp in children(vw, "input") do + local sem = upper(attr(inp, "semantic") or "") + local off = tonumber(attr(inp, "offset") or "") or 0 + stride = math.max(stride, off + 1) + if sem == "JOINT" then + jOff = off + elseif sem == "WEIGHT" then + wOff = off + wSrc = sourceById(C, attr(inp, "source")) + end + end + local vcount = numbers(text(child(vw, "vcount") or ""), C.limit) or {} + local v = numbers(text(child(vw, "v") or ""), C.limit * 8) or {} + local wdata = wSrc and wSrc.data or {} + local per: { { number } } = {} + local at = 0 + for pi, c in vcount do + local list = {} + for _ = 1, math.floor(c) do + local j, w = v[at + jOff + 1], v[at + wOff + 1] + at += stride + local wv = if w then wdata[w + 1] else nil + if j and j >= 0 and j < #names and type(wv) == "number" and wv > 0 then + table.insert(list, { j, wv }) + end + end + table.sort(list, function(a: { number }, b: { number }): boolean + return a[2] > b[2] + end) + local total = 0 + for k = 1, math.min(4, #list) do + total += list[k][2] + end + local e = {} + for k = 1, math.min(4, #list) do + e[k * 2 - 1], e[k * 2] = list[k][1], list[k][2] / total + end + per[pi] = e + end + for pi, prim in mesh.primitives do + local posIndex = ps.built[pi] and ps.built[pi].posIndex + local n = prim.attributes.POSITION.count + if posIndex and #posIndex == n then + local jt = if #names < 256 then "u8" else "u16" + local js = if jt == "u8" then 1 else 2 + local jb = buffer.create(n * 4 * js) + local wb = buffer.create(n * 16) + for vi = 0, n - 1 do + local e = per[posIndex[vi + 1] + 1] + for k = 0, 3 do + local j, w = 0, 0 + if e and e[k * 2 + 1] then + j, w = e[k * 2 + 1], e[k * 2 + 2] + end + if js == 1 then + buffer.writeu8(jb, vi * 4 + k, j) + else + buffer.writeu16(jb, (vi * 4 + k) * 2, j) + end + buffer.writef32(wb, (vi * 4 + k) * 4, w) + end + end + prim.attributes.JOINTS_0 = Scene.accessor(jb, jt, 4, n) + prim.attributes.WEIGHTS_0 = Scene.accessor(wb, "f32", 4, n) + end + end + end +end + +-- ------------------------------------------------------------------------------------------------ animations +type Curve = { input: { number }, output: { number }, stride: number, interp: { string }, member: number?, xf: any } + +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) :: { number } + for k = 1, st do + r[k] = out[(i - 1) * st + k] or 0 + end + return r + end + if n == 0 then + return {} + end + if t <= inp[1] then + return at(1) + end + if t >= inp[n] then + return at(n) + end + local lo, hi = 1, n + while hi - lo > 1 do + local mid = (lo + hi) // 2 + if inp[mid] <= t then + lo = mid + else + hi = mid + end + end + local a, b = at(lo), at(hi) + if c.interp[lo] == "STEP" then + return a + end + local span = inp[hi] - inp[lo] + local f = if span > 0 then (t - inp[lo]) / span else 0 + for k = 1, st do + a[k] += (b[k] - a[k]) * f + end + return a +end + +-- "id/sid/sid.member" or "id/sid(i)(j)" +local function target(C: Ctx, s: string): ({ number }?, any, number?) + -- ids may contain dots (assimp writes "Bone.001/matrix"); sids cannot, so the member starts after the last "/" + local id, sids = match(s, "^([^/]*)/(.*)$") + if not id then + return nil, nil, nil + end + local spath, rest = match(sids :: string, "^([^%.%(]*)(.*)$") + if not spath then + return nil, nil, nil + end + local parts = string.split(id .. "/" .. spath, "/") + local nodes = C.nodeOf[parts[1]] + if not nodes or #parts < 2 then + return nil, nil, nil + end + local sid = parts[#parts] + local info = C.info[nodes[1]] + local xf: any = nil + for _, x in info.xf do + if x.sid == sid then + xf = x + break + end + end + if not xf then + return nil, nil, nil + end + local member: number? = nil + if rest and rest ~= "" then + local m1 = match(rest, "^%.(.+)$") + if m1 then + member = MEMBER[upper(m1)] + if not member then + return nil, nil, nil + end + else + local i, j = match(rest, "^%((%d+)%)%((%d+)%)$") + if i then + member = tonumber(i) :: number * 4 + tonumber(j) :: number + 1 + else + local k = match(rest, "^%((%d+)%)$") + if not k then + return nil, nil, nil + end + member = tonumber(k) :: number + 1 + end + end + end + return nodes, xf, member +end + +local function collect(C: Ctx, anim: any, byNode: { [number]: { Curve } }, order: { number }, depth: number) + if depth > 64 then + return + end + for _, ch in children(anim, "channel") do + local smp = C.ids[urlId(attr(ch, "source")) or ""] + local nodes, xf, member = target(C, attr(ch, "target") or "") + if smp and lname(smp) == "sampler" and nodes and xf then + local input, output, interp: any = nil, nil, nil + for _, inp in children(smp, "input") do + local sem = upper(attr(inp, "semantic") or "") + local src = sourceById(C, attr(inp, "source")) + if sem == "INPUT" then + input = src + elseif sem == "OUTPUT" then + output = src + elseif sem == "INTERPOLATION" then + interp = src + end + end + if input and output and input.count > 0 then + local stride = if member then 1 else #xf.values + local ins = {} + for i = 1, input.count do + local x = input.data[(i - 1) * input.comps + 1] + ins[i] = if type(x) == "number" then x else 0 + end + local outs = output.data + if #outs >= input.count * stride then + local ip = {} + if interp then + for i = 1, input.count do + ip[i] = upper(tostring(interp.data[i] or "LINEAR")) + end + end + local curve: Curve = { input = ins, output = outs, stride = stride, interp = ip, member = member, xf = xf } + for _, ni in nodes do + if not byNode[ni] then + byNode[ni] = {} + table.insert(order, ni) + end + table.insert(byNode[ni], curve) + end + end + end + elseif not (nodes and xf) then + skip(C, "animation channels on other targets") + end + end + for _, sub2 in children(anim, "animation") do + collect(C, sub2, byNode, order, depth + 1) + end +end + +local function bake(C: Ctx, name: string?, byNode: { [number]: { Curve } }, order: { number }): Types.Animation? + local channels: { Types.Channel } = {} + for _, ni in order do + local curves = byNode[ni] + local info = C.info[ni] + -- the union of the key times, plus subdivisions of rotations over 90 degrees + local set: { [number]: boolean } = {} + local times: { number } = {} + local function add(t: number) + if not set[t] then + set[t] = true + table.insert(times, t) + end + end + for _, c in curves do + for i, t in c.input do + add(t) + if i > 1 and c.xf.kind == "rotate" and (c.member == 4 or c.member == nil) then + local k = if c.member then 1 else 4 + local a, b = c.output[(i - 2) * c.stride + k] or 0, c.output[(i - 1) * c.stride + k] or 0 + local steps = math.min(math.ceil(math.abs(b - a) / 90), 64) + for s = 1, steps - 1 do + add(c.input[i - 1] + (t - c.input[i - 1]) * s / steps) + end + end + end + if #times > C.limit then + return nil + end + end + table.sort(times) + local n = #times + local tb, rb, sb = buffer.create(n * 12), buffer.create(n * 16), buffer.create(n * 12) + local prev: { number }? = nil + for i, t in times do + local xf = {} + for k, x in info.xf do + xf[k] = { kind = x.kind, values = table.clone(x.values) } + end + for _, c in curves do + local v = sample(c, t) + local k = table.find(info.xf, c.xf) + if k then + local vals = xf[k].values + if c.member then + vals[c.member] = v[1] or 0 + else + for j = 1, #v do + vals[j] = v[j] + end + end + end + end + 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] } + end + prev = ro + for k = 1, 3 do + buffer.writef32(tb, ((i - 1) * 3 + k - 1) * 4, tr[k]) + buffer.writef32(sb, ((i - 1) * 3 + k - 1) * 4, sc[k]) + end + for k = 1, 4 do + buffer.writef32(rb, ((i - 1) * 4 + k - 1) * 4, ro[k]) + end + end + local ib = buffer.create(n * 4) + for i, t in times do + 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" } :: 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) + local node = C.scene.nodes[ni] + if node.matrix then + setTransform(node, node.matrix) + end + end + if #channels == 0 then + return nil + end + return { name = name, channels = channels } +end + +local function animations(C: Ctx, root: any) + local libs = children(root, "library_animations") + if #libs == 0 then + return + end + local clipsLib = child(root, "library_animation_clips") + local clips = clipsLib and children(clipsLib, "animation_clip") or {} + if #clips > 0 then + for _, clip in clips do + local byNode, order = {}, {} + for _, ia in children(clip, "instance_animation") do + local a = C.ids[urlId(attr(ia, "url")) or ""] + if a and lname(a) == "animation" then + collect(C, a, byNode, order, 0) + end + end + local anim = bake(C, attr(clip, "name") or attr(clip, "id"), byNode, order) + if anim then + table.insert(C.scene.animations, anim) + end + end + return + end + local byNode, order = {}, {} + local name: string? = nil + local count = 0 + for _, lib in libs do + for _, a in children(lib, "animation") do + collect(C, a, byNode, order, 0) + count += 1 + name = name or attr(a, "name") or attr(a, "id") + end + end + local anim = bake(C, if count == 1 then name else nil, byNode, order) + if anim then + table.insert(C.scene.animations, anim) + end +end + +-- ------------------------------------------------------------------------------------------------ scene +function Read.scene(doc: any, fetch: Fetch, opts: any?): (Types.Scene?, Err.Err?) + local root = doc and doc.root + if not root or lname(root) ~= "COLLADA" then + return nil, Err.new(Err.CORRUPT, "no <COLLADA> root element") + end + local scene = Scene.new() + local C: Ctx = { + doc = doc, + ids = {}, + fetch = fetch, + scene = scene, + limit = opts and opts.maxVertices or 2 ^ 25, + vertices = 0, + flipV = not (opts and opts.flipV == false), + triangulate = not (opts and opts.triangulate == false), + sources = {}, + materials = {}, + textures = {}, + images = {}, + meshes = {}, + skins = {}, + posIndex = {}, + nodeOf = {}, + info = {}, + pendingSkins = {}, + skipped = {}, + err = nil, + depth = 0, + } + for _, el in Xml.descendants(root) do + local id = el.attrs.id + -- duplicate ids: the first, unless empty (some exporters write <light id="x"/> before the real one) + if type(id) == "string" and (C.ids[id] == nil or #C.ids[id].children == 0) then + C.ids[id] = el + end + end + 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" :: "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 + local vsId: string? = nil + local sceneEl = child(root, "scene") + local ivs = sceneEl and child(sceneEl, "instance_visual_scene") + if ivs then + vsId = urlId(attr(ivs, "url")) + end + local vs = vsId and C.ids[vsId] + if not vs or lname(vs) ~= "visual_scene" then + local lib = child(root, "library_visual_scenes") + vs = lib and child(lib, "visual_scene") + end + if vs then + for _, n in children(vs, "node") do + local idx = visitNode(C, n) + if C.err then + break + end + if idx then + table.insert(scene.roots, idx) + end + end + end + if C.err then + return nil, Err.new(if find(C.err :: string, "limit", 1, true) then Err.LIMIT else Err.CORRUPT, C.err :: string) + end + resolveSkins(C) + animations(C, root) + if C.err then + return nil, Err.new(Err.CORRUPT, C.err :: string) + end + local contributor = asset and child(asset, "contributor") + local tool = contributor and child(contributor, "authoring_tool") + scene.meta.source = { + format = "dae", + version = attr(root, "version"), + upAxis = upAxis, + authoringTool = if tool then text(tool) else nil, + skipped = if next(C.skipped) then C.skipped else nil, + } + return scene, nil +end + +return Read +end +__FILES["model/dae/Write"] = function() + +-- model/dae/Write: Scene -> Collada 1.4.1 text; strips and fans unrolled, points skipped, nodes as row-major <matrix>. +-- Not written: skins, morph targets, animations. +local Types = __include("Types") +local Xml = __include("codecs/text/Xml") +local Base64 = __include("core/Base64") +local Mat4 = __include("codecs/model/Mat4") + +local Write = {} + +local Scene = Types.Scene +local format, concat = string.format, table.concat +local EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/webp"] = "webp", ["image/tga"] = "tga", ["image/bmp"] = "bmp", ["image/gif"] = "gif" } + +local function f(v: number): string + if v ~= v or v == math.huge or v == -math.huge then + return "0" + end + if v == math.floor(v) and math.abs(v) < 1e15 then + return format("%d", v) + end + return format("%.9g", v) +end +local function list(v: { number }): string + local out = table.create(#v) + for i, x in v do + out[i] = f(x) + end + return concat(out, " ") +end +local function esc(s: string): string + return Xml.escapeAttr(s) +end +local function nameAttr(s: string?): string + return if s then ' name="' .. esc(s) .. '"' else "" +end + +local function corners(prim: Types.Primitive): ({ number }?, string?, { number }?) + local n = prim.attributes.POSITION.count + local idx: { number } = {} + if prim.indices then + local get = Scene.reader(prim.indices) + if not get then + return nil, nil, nil + end + for i = 0, prim.indices.count - 1 do + idx[i + 1] = get(i, 0) + end + else + for i = 0, n - 1 do + idx[i + 1] = i + end + end + for _, i in idx do + if i < 0 or i >= n then + return nil, nil, nil + end + end + local mode = prim.mode or "triangles" + if mode == "triangles" then + local m = #idx - #idx % 3 + return table.move(idx, 1, m, 1, {}), "triangles", nil + elseif mode == "triangle_strip" or mode == "triangle_fan" then + local out = {} + for k = 1, #idx - 2 do + if mode == "triangle_fan" then + table.insert(out, idx[1]) + table.insert(out, idx[k + 1]) + table.insert(out, idx[k + 2]) + elseif k % 2 == 1 then + table.insert(out, idx[k]) + table.insert(out, idx[k + 1]) + table.insert(out, idx[k + 2]) + else + table.insert(out, idx[k + 1]) + table.insert(out, idx[k]) + table.insert(out, idx[k + 2]) + end + end + return out, "triangles", nil + elseif mode == "lines" then + local m = #idx - #idx % 2 + return table.move(idx, 1, m, 1, {}), "lines", nil + elseif mode == "line_strip" or mode == "line_loop" then + local out = {} + for k = 1, #idx - 1 do + table.insert(out, idx[k]) + table.insert(out, idx[k + 1]) + end + if mode == "line_loop" and #idx > 2 then + table.insert(out, idx[#idx]) + table.insert(out, idx[1]) + end + return out, "lines", nil + elseif mode == "polygons" and prim.faces then + local get = Scene.reader(prim.faces) + if not get then + return nil, nil, nil + end + local sizes = {} + local total = 0 + for i = 0, prim.faces.count - 1 do + sizes[i + 1] = get(i, 0) + total += sizes[i + 1] + end + if total ~= #idx then + return nil, nil, nil + end + return idx, "polylist", sizes + end + return nil, nil, nil +end + +local function source(out: { string }, id: string, acc: Types.Accessor, comps: number, params: { string }, flipV: boolean) + local get = Scene.reader(acc) + if not get then + return + end + local vals = table.create(acc.count * comps) + local n = 0 + for i = 0, acc.count - 1 do + for c = 0, comps - 1 do + n += 1 + local v = if c < acc.components then get(i, c) else (if c == 3 then 1 else 0) + if flipV and c == 1 then + v = 1 - v + end + vals[n] = f(v) + end + end + table.insert(out, format('<source id="%s"><float_array id="%s-array" count="%d">%s</float_array>', id, id, n, concat(vals, " "))) + local ps = {} + for c = 1, comps do + ps[c] = format('<param name="%s" type="float"/>', params[c] or "V") + end + table.insert(out, format('<technique_common><accessor source="#%s-array" count="%d" stride="%d">%s</accessor></technique_common></source>\n', id, acc.count, comps, concat(ps))) +end + +local function colorEl(tag: string, c: { number }?, tex: string?, uv: number?): string + if tex then + return format('<%s><texture texture="%s" texcoord="UVSET%d"/></%s>', tag, tex, uv or 0, tag) + end + local v = c or { 0, 0, 0, 1 } + return format("<%s><color>%s %s %s %s</color></%s>", tag, f(v[1] or 0), f(v[2] or 0), f(v[3] or 0), f(v[4] or 1), tag) +end + +function Write.build(scene: Types.Scene, opts: any?): string? + local files = opts and type(opts.files) == "table" and opts.files or nil + local base = opts and opts.name and string.gsub(string.match(opts.name, "([^/\\]+)$") or opts.name, "%.[^.]*$", "") or "model" + local flipV = not (opts and opts.flipV == false) + local out: { string } = {} + local function w(s: 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: { [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>rosetta</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)) + local imageId: { [number]: string } = {} + if #scene.textures > 0 then + w("<library_images>\n") + for i, tex in scene.textures do + local uri: string? = nil + if tex.data then + if files then + uri = format("%s_%d.%s", base, i, EXT[tex.mime or ""] or "png") + files[uri :: string] = tex.data + else + uri = Base64.dataUri(tex.data, tex.mime or "image/png") + end + elseif tex.uri then + uri = tex.uri + end + if uri then + local id = "image" .. i + imageId[i] = id + w(format('<image id="%s"%s><init_from>%s</init_from></image>\n', id, nameAttr(tex.name), Xml.escape(uri :: string))) + end + end + w("</library_images>\n") + end + if #scene.materials > 0 then + w("<library_effects>\n") + for i, mat in scene.materials do + local ph: any = mat.extras and mat.extras.phong or {} + local params: { [any]: any } = {} + local function texParam(ref: Types.TextureRef?): (string?, number?) + if not ref or not imageId[ref.texture] then + return nil, nil + end + local sid = "tex" .. ref.texture + if not params[sid] then + params[sid] = true + table.insert(params, format('<newparam sid="%s-surface"><surface type="2D"><init_from>%s</init_from></surface></newparam><newparam sid="%s"><sampler2D><source>%s-surface</source></sampler2D></newparam>', sid, imageId[ref.texture], sid, sid)) + end + return sid, ref.texCoord + end + local dtex, duv = texParam(mat.baseColorTexture) + local etex, euv = texParam(mat.emissiveTexture) + local ntex, nuv = texParam(mat.normalTexture) + local unlit = mat.extensions and mat.extensions.KHR_materials_unlit ~= nil + local model = if unlit then "constant" elseif ph.model == "lambert" then "lambert" else "phong" + local body = {} + local bc = mat.baseColor + if unlit then + table.insert(body, colorEl("emission", { bc[1], bc[2], bc[3], 1 }, nil, nil)) + else + table.insert(body, colorEl("emission", if type(ph.emission) == "table" then ph.emission else { mat.emissive[1], mat.emissive[2], mat.emissive[3], 1 }, etex, euv)) + table.insert(body, colorEl("ambient", if type(ph.ambient) == "table" then ph.ambient else { 0, 0, 0, 1 }, nil, nil)) + table.insert(body, colorEl("diffuse", { bc[1], bc[2], bc[3], 1 }, dtex, duv)) + if model == "phong" then + table.insert(body, colorEl("specular", if type(ph.specular) == "table" then ph.specular else { 0, 0, 0, 1 }, nil, nil)) + local sh = if type(ph.shininess) == "number" then ph.shininess else math.max(2 / math.max((mat.roughness or 1) ^ 2, 1e-4) - 2, 0) + table.insert(body, format("<shininess><float>%s</float></shininess>", f(sh))) + end + end + if (bc[4] or 1) < 1 then + table.insert(body, '<transparent opaque="A_ONE"><color>1 1 1 1</color></transparent>') + table.insert(body, format("<transparency><float>%s</float></transparency>", f(bc[4]))) + end + local extra = "" + if ntex or mat.doubleSided then + extra = "<extra><technique profile=\"FCOLLADA\">" .. (if ntex then format('<bump><texture texture="%s" texcoord="UVSET%d"/></bump>', ntex, nuv or 0) else "") .. (if mat.doubleSided then "<double_sided>1</double_sided>" else "") .. "</technique></extra>" + end + w(format('<effect id="effect%d"><profile_COMMON>%s<technique sid="common"><%s>%s</%s>%s</technique></profile_COMMON></effect>\n', i, concat(params), model, concat(body), model, extra)) + end + w("</library_effects>\n<library_materials>\n") + for i, mat in scene.materials do + w(format('<material id="material%d"%s><instance_effect url="#effect%d"/></material>\n', i, nameAttr(mat.name), i)) + end + w("</library_materials>\n") + end + local geoms: { [number]: { { id: string, material: number?, sets: number } } } = {} + w("<library_geometries>\n") + for mi, mesh in scene.meshes do + geoms[mi] = {} + for pi, prim in mesh.primitives do + local pos = prim.attributes and prim.attributes.POSITION + if not pos then + continue + end + local idx, kind, sizes = corners(prim) + if not idx or not kind or #idx == 0 then + continue + end + local id = format("mesh%d-%d", mi, pi) + w(format('<geometry id="%s"%s><mesh>\n', id, nameAttr(mesh.name))) + source(out, id .. "-positions", pos, 3, { "X", "Y", "Z" }, false) + local ins = { format('<input semantic="VERTEX" source="#%s-vertices" offset="0"/>', id) } + if prim.attributes.NORMAL then + source(out, id .. "-normals", prim.attributes.NORMAL, 3, { "X", "Y", "Z" }, false) + table.insert(ins, format('<input semantic="NORMAL" source="#%s-normals" offset="0"/>', id)) + end + local sets = 0 + for k = 0, 7 do + local a = prim.attributes["TEXCOORD_" .. k] + if not a then + break + end + source(out, format("%s-uv%d", id, k), a, 2, { "S", "T" }, flipV) + table.insert(ins, format('<input semantic="TEXCOORD" source="#%s-uv%d" offset="0" set="%d"/>', id, k, k)) + sets += 1 + end + for k = 0, 7 do + local a = prim.attributes["COLOR_" .. k] + if not a then + break + end + local c = if a.components >= 4 then 4 else 3 + source(out, format("%s-color%d", id, k), a, c, { "R", "G", "B", "A" }, false) + table.insert(ins, format('<input semantic="COLOR" source="#%s-color%d" offset="0" set="%d"/>', id, k, k)) + end + w(format('<vertices id="%s-vertices"><input semantic="POSITION" source="#%s-positions"/></vertices>\n', id, id)) + local matAttr = if prim.material and scene.materials[prim.material] then format(' material="m%d"', prim.material) else "" + local count = if kind == "triangles" then #idx // 3 elseif kind == "lines" then #idx // 2 else #(sizes :: { number }) + w(format('<%s count="%d"%s>%s', kind, count, matAttr, concat(ins))) + if sizes then + w("<vcount>" .. list(sizes) .. "</vcount>") + end + w("<p>" .. list(idx) .. "</p></" .. kind .. ">\n</mesh></geometry>\n") + table.insert(geoms[mi], { id = id, material = if matAttr ~= "" then prim.material else nil, sets = sets }) + end + end + w("</library_geometries>\n") + if #scene.cameras > 0 then + w("<library_cameras>\n") + for i, cam in scene.cameras do + local body: string + if cam.type == "orthographic" then + body = format("<orthographic><xmag>%s</xmag><ymag>%s</ymag><znear>%s</znear><zfar>%s</zfar></orthographic>", f(cam.xmag or 1), f(cam.ymag or 1), f(cam.znear or 0.1), f(cam.zfar or 1000)) + else + body = format("<perspective><yfov>%s</yfov>%s<znear>%s</znear><zfar>%s</zfar></perspective>", f(math.deg(cam.yfov or 0.8)), if cam.aspect then format("<aspect_ratio>%s</aspect_ratio>", f(cam.aspect)) else "", f(cam.znear or 0.1), f(cam.zfar or 1000)) + end + w(format('<camera id="camera%d"%s><optics><technique_common>%s</technique_common></optics></camera>\n', i, nameAttr(cam.name), body)) + end + w("</library_cameras>\n") + end + if #scene.lights > 0 then + w("<library_lights>\n") + for i, l in scene.lights do + local c = l.color or { 1, 1, 1 } + local k = l.intensity or 1 + local col = format("<color>%s %s %s</color>", f(c[1] * k), f(c[2] * k), f(c[3] * k)) + local body = if l.type == "spot" then format("<spot>%s<constant_attenuation>1</constant_attenuation><linear_attenuation>0</linear_attenuation><quadratic_attenuation>0</quadratic_attenuation><falloff_angle>%s</falloff_angle><falloff_exponent>0</falloff_exponent></spot>", col, f(math.deg(l.outerCone or math.pi / 4) * 2)) + elseif l.type == "point" then format("<point>%s<constant_attenuation>1</constant_attenuation><linear_attenuation>0</linear_attenuation><quadratic_attenuation>0</quadratic_attenuation></point>", col) + else format("<directional>%s</directional>", col) + w(format('<light id="light%d"%s><technique_common>%s</technique_common></light>\n', i, nameAttr(l.name), body)) + end + w("</library_lights>\n") + end + w('<library_visual_scenes><visual_scene id="scene" name="scene">\n') + local seen: { [number]: boolean } = {} + local function node(i: number, depth: number) + local n = scene.nodes[i] + if not n or seen[i] or depth > 512 then + return + end + seen[i] = true + 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 + local binds = {} + for k = 0, g.sets - 1 do + table.insert(binds, format('<bind_vertex_input semantic="UVSET%d" input_semantic="TEXCOORD" input_set="%d"/>', k, k)) + end + w(format('<instance_geometry url="#%s"><bind_material><technique_common><instance_material symbol="m%d" target="#material%d">%s</instance_material></technique_common></bind_material></instance_geometry>', g.id, g.material, g.material, concat(binds))) + else + w(format('<instance_geometry url="#%s"/>', g.id)) + end + end + end + if n.camera and scene.cameras[n.camera] then + w(format('<instance_camera url="#camera%d"/>', n.camera)) + end + if n.light and scene.lights[n.light] then + w(format('<instance_light url="#light%d"/>', n.light)) + end + w("\n") + for _, c in n.children or {} do + node(c, depth + 1) + end + w("</node>\n") + end + local roots = scene.roots + if not roots or #roots == 0 then + local isChild = {} + for _, n in scene.nodes do + for _, c in n.children or {} do + isChild[c] = true + end + end + roots = {} + for i in scene.nodes do + if not isChild[i] then + table.insert(roots, i) + end + end + end + for _, r in roots do + node(r, 0) + end + w('</visual_scene></library_visual_scenes>\n<scene><instance_visual_scene url="#scene"/></scene>\n</COLLADA>\n') + return concat(out) +end + +return Write +end +__FILES["model/fbx"] = function() + +-- model/fbx: Autodesk FBX 7.x binary and ASCII, from Blender's io_scene_fbx, assimp and the FBX SDK transform docs. +-- Supports: Model transforms, meshes, Phong / Physical materials, textures, skins, blend shapes, animation, cameras. +-- Not supported: FBX 6.x and older, NURBS / patches / lines, constraints, animation layer blending. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Binary = __include("model/fbx/Binary") +local Ascii = __include("model/fbx/Ascii") +local Read = __include("model/fbx/Read") +local Write = __include("model/fbx/Write") + +-- ------------------------------------------------------------------------------------------------ contract +local Fbx = { + name = "fbx", + category = "model", + extensions = { "fbx" }, + mime = { "application/vnd.autodesk.fbx", "model/fbx" }, + 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 }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + triangulate: boolean?, -- default true + flipV: boolean?, -- default true + sampleRate: number?, -- samples per second (default: the keys only) + resolve: ((uri: string) -> any)?, -- external texture files + files: { [string]: any }?, + maxBytes: number?, -- default 2^30 bytes of arrays + maxVertices: number?, -- default 2^25 polygon corners +} +type EncodeOptions = { + ascii: boolean?, -- default binary + version: number?, -- 7400 (default) or 7500 (64-bit records) + flipV: boolean?, -- default true + embedTextures: boolean?, -- default true + compress: boolean?, -- arrays over 32 elements (default true) + name: string?, + creator: string?, +} + +-- ------------------------------------------------------------------------------------------------ constants +local MAGIC = Binary.MAGIC + +-- ------------------------------------------------------------------------------------------------ sniff +function Fbx.sniff(r: Bytes.Reader): number + if r:peek(21) == MAGIC then + return 1 + end + local head = r:peek(2048) + if string.find(head, "FBXHeaderExtension:", 1, true) then + return 0.95 + end + if string.find(head, "^; FBX %d") then + return 0.8 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function fetcher(opts: DecodeOptions?): Read.Fetch + return function(uri: string): buffer? + if not opts then + return nil + end + local v: any = nil + if type(opts.files) == "table" then + v = opts.files[uri] + end + if v == nil and type(opts.resolve) == "function" then + local ok, res = pcall(opts.resolve, uri) + v = if ok then res else nil + end + if type(v) == "string" then + return buffer.fromstring(v) + end + return if type(v) == "buffer" then v else nil + end +end + +local toErr = Err.from + +function Fbx.tree(r: Bytes.Reader, opts: DecodeOptions?): (any, any, boolean?) + if r:peek(21) == MAGIC then + local root, version, off = Binary.parse(r.buf, r.base, r.limit, opts) + if not root then + return nil, toErr(version, off) + end + return root, version, true + end + local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + local root, version, off = Ascii.parse(text, opts) + if not root then + return nil, toErr(version, off and r.base + off) + end + if type(version) ~= "number" then + return nil, Err.new(Err.CORRUPT, "no FBXHeaderExtension / FBXVersion") + end + if version < 7000 then + return nil, Err.new(Err.UNSUPPORTED, "FBX version " .. version .. " (only 7.x)") + end + return root, version, false +end + +function Fbx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local root, version, binary = Fbx.tree(r, opts) + if not root then + return nil, version + end + local ok, scene, err = pcall(Read.scene, root, version, fetcher(opts), opts) + if not ok then + return nil, Err.new(Err.CORRUPT, "bad object graph: " .. tostring(scene)) + end + if not scene then + return nil, err + end + (scene.meta.source :: { [string]: any }).binary = binary + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Fbx.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(scene) ~= "table" or scene.kind ~= "scene" then + return nil, Err.new(Err.ARG, "needs a Scene") + end + local version = opts and opts.version or 7400 + if version ~= 7400 and version ~= 7500 then + return nil, Err.new(Err.ARG, "version must be 7400 or 7500") + end + local ok, root, err = pcall(Write.tree, scene, opts) + if not ok then + return nil, Err.new(Err.ARG, "bad scene: " .. tostring(root)) + end + if not root then + return nil, err + end + if opts and opts.ascii then + return buffer.fromstring(Ascii.write(root, version)), nil + end + return Binary.write(root, version, not (opts and opts.compress == false)), nil +end + +return Fbx +end +__FILES["model/fbx/Ascii"] = function() + +-- model/fbx/Ascii: the ASCII FBX 7.x node tree ("Name: value, ... { children }", ';' comments, "*N { a: ... }" arrays, +-- &quot; in strings); integers longer than 15 digits stay strings so ids are exact. +local Base64 = __include("core/Base64") + +local Ascii = {} + +type Node = { name: string, props: { any }, children: { Node } } + +local sbyte, sfind, ssub = string.byte, string.find, string.sub +local MAX_DEPTH = 128 + +local function isNameStart(c: number): boolean + return (c >= 65 and c <= 90) or (c >= 97 and c <= 122) or c == 95 +end + +function Ascii.parse(text: string, opts: { maxBytes: number? }?): (Node?, any, number?) + local maxBytes = opts and opts.maxBytes or 2 ^ 30 + local n = #text + local i = 1 + local total = 0 + + local function skip() + while i <= n do + local c = sbyte(text, i) + if c == 59 then -- ; comment + local e = sfind(text, "\n", i, true) + i = if e then e + 1 else n + 1 + elseif c == 32 or c == 9 or c == 10 or c == 13 then + i += 1 + else + return + end + end + end + + local function nameAt(): (string?, number) + local c = sbyte(text, i) + if not c or not isNameStart(c) then + return nil, i + end + local s, e = sfind(text, "^[%w_|%-]+", i) + if not s then + return nil, i + end + local j = (e :: number) + 1 + while j <= n do + local d = sbyte(text, j) + if d == 32 or d == 9 then + j += 1 + else + break + end + end + if sbyte(text, j) == 58 then + return ssub(text, i, e :: number), j + 1 + end + return nil, i + end + + local function values(): ({ any }?, string?) + local props: { any } = {} + while true do + skip() + if i > n then + return props, nil + end + local c = sbyte(text, i) + if c == 44 then -- , + i += 1 + elseif c == 123 or c == 125 then + return props, nil + elseif c == 34 then -- " + local e = sfind(text, "\"", i + 1, true) + if not e then + return nil, "unterminated string" + end + local s = ssub(text, i + 1, e - 1) + if sfind(s, "&", 1, true) then + s = string.gsub(s, "&quot;", "\"") + end + table.insert(props, s) + i = e + 1 + elseif c == 42 then -- *N + local s, e = sfind(text, "^%*%d+", i) + if not s then + return nil, "bad array length" + end + table.insert(props, { star = tonumber(ssub(text, i + 1, e :: number)) }) + i = (e :: number) + 1 + elseif (c >= 48 and c <= 57) or c == 45 or c == 43 or c == 46 then + local s, e = sfind(text, "^[-+%deE.]+", i) + local tok = ssub(text, i, e :: number) + local v = tonumber(tok) + if v == nil then + -- "1.#INF", "-1.#IND", "nan": special floats + local s2, e2 = sfind(text, "^[-+%w.#]+", i) + tok = ssub(text, i, e2 :: number) + local low = string.lower(tok) + if sfind(low, "inf", 1, true) then + v = if sbyte(tok, 1) == 45 then -math.huge else math.huge + else + v = 0 / 0 + end + e = e2 + local _ = s2 + elseif #tok > 15 and not sfind(tok, "[.eE]") then + v = (if sbyte(tok, 1) == 45 then "L-" else "L") .. string.gsub(tok, "^[-+]", "") :: any + end + local _ = s + table.insert(props, v) + i = (e :: number) + 1 + else + local nm = nameAt() + if nm then + return props, nil + end + local s, e = sfind(text, "^[%w_]+", i) + if not s then + return nil, string.format("unexpected character %q", ssub(text, i, i)) + end + table.insert(props, ssub(text, i, e :: number)) + i = (e :: number) + 1 + end + end + end + + local function nodes(depth: number, into: { Node }): string? + while true do + skip() + if i > n then + return if depth > 0 then "unterminated {" else nil + end + if sbyte(text, i) == 125 then + if depth == 0 then + return "unbalanced }" + end + i += 1 + return nil + end + local name, j = nameAt() + if not name then + return string.format("expected a node name at %q", ssub(text, i, i + 10)) + end + i = j + local props, err = values() + if not props then + return err + end + local node: Node = { name = name, props = props, children = {} } + skip() + if sbyte(text, i) == 123 then + if depth >= MAX_DEPTH then + return "nodes nested too deep" + end + i += 1 + local e = nodes(depth + 1, node.children) + if e then + return e + end + end + local p1 = props[1] + if #props == 1 and type(p1) == "table" and p1.star then + local a = node.children[1] + local count = if a and a.name == "a" then #a.props else 0 + total += count * 8 + if total > maxBytes then + return "limit:arrays over " .. maxBytes .. " bytes" + end + local data = buffer.create(count * 8) + for k = 1, count do + local v = (a :: Node).props[k] + buffer.writef64(data, (k - 1) * 8, if type(v) == "number" then v else (tonumber(v) or 0)) + end + node.props = { { array = true, type = "d", count = count, data = data } } + node.children = {} + end + table.insert(into, node) + end + end + + local root: Node = { name = "", props = {}, children = {} } + local err = nodes(0, root.children) + if err then + return nil, err, i - 1 + end + local version = nil + for _, c in root.children do + if c.name == "FBXHeaderExtension" then + for _, d in c.children do + if d.name == "FBXVersion" then + version = d.props[1] + end + end + end + end + return root, version, nil +end + +-- ------------------------------------------------------------------------------------------------ writer +local function fmt(v: number): string + if v == math.floor(v) and math.abs(v) < 1e15 then + return string.format("%d", v) + end + if v ~= v then + return "0" + end + return string.format("%.17g", v) +end + +function Ascii.write(root: any, version: number?): string + local out = { string.format("; FBX %d.%d.0 project file\n; Created by rosetta\n\n", (version or 7400) // 1000, (version or 7400) % 1000 // 100) } + local function node(nd: any, indent: string) + local parts = {} + local arr = nil + for _, v in nd.props do + local tv = type(v) + if tv == "number" then + table.insert(parts, fmt(v)) + elseif tv == "boolean" then + table.insert(parts, if v then "T" else "F") + elseif tv == "string" then + if string.sub(v, 1, 1) == "L" and string.find(v, "^L%-?%d+$") then + table.insert(parts, string.sub(v, 2)) + else + local nm, cls = string.match(v, "^(.-)%z\1(.*)$") + local sv = if nm then (cls :: string) .. "::" .. nm else v + table.insert(parts, "\"" .. string.gsub(sv, "\"", "&quot;") .. "\"") + end + elseif tv == "table" and v.array then + arr = v + elseif tv == "buffer" then + -- raw bytes (Video Content): base64 split into lines as the FBX SDK writes them + local b64 = Base64.encode(v) + local chunks = {} + for k = 1, #b64, 2048 do + table.insert(chunks, "\"" .. string.sub(b64, k, k + 2047) .. "\"") + end + table.insert(parts, if #chunks > 0 then table.concat(chunks, ",\n") else "\"\"") + end + end + if arr then + 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 + table.insert(out, string.format("%s%s: *%d {\n%s\ta: %s\n%s}\n", indent, nd.name, arr.count, indent, table.concat(vals, ","), indent)) + return + end + table.insert(out, indent .. nd.name .. ": " .. table.concat(parts, ", ")) + local ch = nd.children + if ch and #ch > 0 then + table.insert(out, " {\n") + for _, c in ch do + node(c, indent .. "\t") + end + table.insert(out, indent .. "}\n") + else + table.insert(out, "\n") + end + end + for _, c in root.children do + node(c, "") + end + return table.concat(out) +end + +return Ascii +end +__FILES["model/fbx/Binary"] = @native function() + + +-- model/fbx/Binary: the binary FBX 7.x node tree (32-bit node records before 7500, 64-bit from 7500), as documented by +-- Blender's io_scene_fbx and assimp's FBXBinaryTokenizer. Scalar L values past 2^53 become "L<hex>" so ids stay exact. +local Deflate = __include("codecs/compress/Deflate") + +local Binary = {} + +type Node = { name: string, props: { any }, children: { Node } } +type Array = { array: true, type: string, count: number, data: buffer } + +local MAGIC = "Kaydara FBX Binary \0" +Binary.MAGIC = MAGIC +local FOOT_ID = "\250\188\171\9\208\200\212\102\177\118\251\131\28\247\38\126" +local FOOT_MAGIC = "\248\90\140\106\222\245\217\126\236\233\12\227\117\143\41\11" +local MAX_DEPTH = 128 + +local readu8, readu32, readi32, readf32, readf64, readi16 = buffer.readu8, buffer.readu32, buffer.readi32, buffer.readf32, buffer.readf64, buffer.readi16 +local writef64 = buffer.writef64 + +-- signed 64-bit: a number when |v| < 2^53, else "L<16 hex digits>" +@native local function i64(b: buffer, p: number, asString: boolean): any + local lo, hi = readu32(b, p), readu32(b, p + 4) + if hi >= 0x80000000 then + local v = (hi - 4294967296) * 4294967296 + lo + if v >= -9007199254740991 or not asString then + return v + end + else + if hi < 0x200000 or not asString then + return hi * 4294967296 + lo + end + end + return string.format("L%08x%08x", hi, lo) +end +Binary.i64 = i64 + +local ELEM: { [string]: number } = { f = 4, d = 8, l = 8, i = 4, b = 1, c = 1 } + +@native local function toF64(t: string, src: buffer, p: number, n: number): buffer + local out = buffer.create(n * 8) + if t == "d" then + buffer.copy(out, 0, src, p, n * 8) + elseif t == "f" then + for k = 0, n - 1 do + writef64(out, k * 8, readf32(src, p + k * 4)) + end + elseif t == "i" then + for k = 0, n - 1 do + writef64(out, k * 8, readi32(src, p + k * 4)) + end + elseif t == "l" then + for k = 0, n - 1 do + local lo, hi = readu32(src, p + k * 8), readu32(src, p + k * 8 + 4) + writef64(out, k * 8, if hi >= 0x80000000 then (hi - 4294967296) * 4294967296 + lo else hi * 4294967296 + lo) + end + else + for k = 0, n - 1 do + writef64(out, k * 8, readu8(src, p + k)) + end + end + return out +end + +@native function Binary.parse(b: buffer, base: number, limit: number, opts: { maxBytes: number? }?): (Node?, any, number?) + local maxBytes = opts and opts.maxBytes or 2 ^ 30 + if limit - base < 27 or buffer.readstring(b, base, 21) ~= MAGIC then + return nil, "not a binary FBX", base + end + local version = readu32(b, base + 23) + if version < 7000 or version >= 10000 then + return nil, "unsupported:FBX version " .. version, base + 23 + end + local wide = version >= 7500 + local head = if wide then 25 else 13 + local total = 0 + + @native local function props(p: number, n: number, stop: number): ({ any }?, any) + local out = table.create(math.min(n, 64)) + for k = 1, n do + if p >= stop then + return nil, "property list runs past its record" + end + local c = readu8(b, p) + p += 1 + local v: any + if c == 89 then -- Y + if p + 2 > stop then return nil, "truncated property" end + v = readi16(b, p) + p += 2 + elseif c == 67 then -- C + if p + 1 > stop then return nil, "truncated property" end + v = readu8(b, p) ~= 0 + p += 1 + elseif c == 73 then -- I + if p + 4 > stop then return nil, "truncated property" end + v = readi32(b, p) + p += 4 + elseif c == 70 then -- F + if p + 4 > stop then return nil, "truncated property" end + v = readf32(b, p) + p += 4 + elseif c == 68 then -- D + if p + 8 > stop then return nil, "truncated property" end + v = readf64(b, p) + p += 8 + elseif c == 76 then -- L + if p + 8 > stop then return nil, "truncated property" end + v = i64(b, p, true) + p += 8 + elseif c == 83 or c == 82 then -- S, R + if p + 4 > stop then return nil, "truncated property" end + local len = readu32(b, p) + p += 4 + if len > stop - p then return nil, "string runs past its record" end + if c == 83 then + v = buffer.readstring(b, p, len) + else + local raw = buffer.create(len) + buffer.copy(raw, 0, b, p, len) + v = raw + end + p += len + elseif c == 102 or c == 100 or c == 108 or c == 105 or c == 98 or c == 99 then -- f d l i b c + if p + 12 > stop then return nil, "truncated array header" end + local count, enc, clen = readu32(b, p), readu32(b, p + 4), readu32(b, p + 8) + p += 12 + local t = string.char(c) + local es = ELEM[t] + if clen > stop - p then return nil, "array runs past its record" end + total += count * 8 + if total > maxBytes then return nil, "limit:arrays over " .. maxBytes .. " bytes" end + local data: buffer + if enc == 0 then + if clen < count * es then return nil, "raw array shorter than its count" end + data = toF64(t, b, p, count) + elseif enc == 1 then + local raw, err = Deflate.zlib(b, p, clen, count * es) + if not raw then + return nil, "array: " .. tostring(if type(err) == "table" then err.message else err) + end + data = toF64(t, raw, 0, count) + else + return nil, "unknown array encoding " .. enc + end + p += clen + v = { array = true, type = t, count = count, data = data } + else + return nil, string.format("unknown property type 0x%02x", c) + end + out[k] = v + end + return out, p + end + + @native local function node(p: number, stop: number, depth: number): (any, any, number?) + if p + head > stop then + return nil, "truncated node record", p + end + local endOff, nprops, plen, nlen + if wide then + endOff = readu32(b, p) + readu32(b, p + 4) * 4294967296 + nprops = readu32(b, p + 8) + readu32(b, p + 12) * 4294967296 + 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)) + end + if endOff == 0 then + return false, p + head + end + local e = base + endOff + if e > stop or e < p + head + nlen + plen then + return nil, "node end offset out of range", p + end + if nprops > plen then + return nil, "more properties than bytes", p + end + local q = p + head + local name = buffer.readstring(b, q, nlen) + q += nlen + local pl, nq = props(q, nprops, q + plen) + if not pl then + return nil, nq, q + end + q += plen + local children: { Node } = {} + if q < e then + if depth >= MAX_DEPTH then + return nil, "nodes nested too deep", p + end + while q < e do + local child, nx, off = node(q, e, depth + 1) + if child == nil then + return nil, nx, off + end + q = nx + if child == false then + break + end + table.insert(children, child) + end + end + return { name = name, props = pl, children = children }, e + end + + local root: Node = { name = "", props = {}, children = {} } + local p = base + 27 + while p < limit do + local n, nx, off = node(p, limit, 0) + if n == nil then + if #root.children > 0 and p + head > limit then + break -- a file cut right after its last node: keep what was read + end + return nil, nx, off + end + if n == false then + break + end + table.insert(root.children, n) + p = nx + end + return root, version, nil +end + +-- ------------------------------------------------------------------------------------------------ writer +-- default version 7400 (32-bit records; 7500+ writes 64-bit); node.types = "ILDS..." gives one type character per +-- property; arrays over 32 elements are zlib-compressed +type WNode = { name: string, props: { any }, children: { WNode }?, types: string? } + +@native local function sizeHint(n: WNode): number + local s = 32 + #n.name + for _, v in n.props do + if type(v) == "string" then + s += 5 + #v + elseif type(v) == "buffer" then + s += 5 + buffer.len(v) + elseif type(v) == "table" then + s += 13 + (v.count or 0) * 8 + else + s += 9 + end + end + for _, c in n.children or {} do + s += sizeHint(c) + end + return s +end + +@native function Binary.write(root: WNode, version: number?, compress: boolean?): buffer + local zip = compress ~= false + local ver = version or 7400 + local wide = ver >= 7500 + local head = if wide then 25 else 13 + local cap = sizeHint(root) + 256 + local out = buffer.create(cap) + local pos = 0 + @native local function ensure(n: number) + if pos + n > cap then + while pos + n > cap do + cap *= 2 + end + local nb = buffer.create(cap) + buffer.copy(nb, 0, out, 0, pos) + out = nb + end + end + @native local function u8(v: number) + ensure(1) + buffer.writeu8(out, pos, v) + pos += 1 + end + @native local function u32(v: number) + ensure(4) + buffer.writeu32(out, pos, v) + pos += 4 + end + @native local function i64w(v: number) + ensure(8) + local hi = math.floor(v / 4294967296) + local lo = v - hi * 4294967296 + buffer.writeu32(out, pos, lo) + buffer.writeu32(out, pos + 4, hi % 4294967296) + pos += 8 + end + @native local function str(s: string) + ensure(#s) + buffer.writestring(out, pos, s) + pos += #s + end + @native local function bytes(src: buffer) + local n = buffer.len(src) + ensure(n) + buffer.copy(out, pos, src, 0, n) + pos += n + end + @native local function array(a: any) + local t, n, d = a.type, a.count, a.data + local es = ELEM[t] or 8 + local raw = buffer.create(n * es) + if a.raw then + buffer.copy(raw, 0, a.raw, 0, math.min(buffer.len(a.raw), n * es)) + else + for k = 0, n - 1 do + local v = readf64(d, k * 8) + if t == "d" then + writef64(raw, k * 8, v) + elseif t == "f" then + buffer.writef32(raw, k * 4, v) + elseif t == "i" then + buffer.writei32(raw, k * 4, v) + elseif t == "b" then + buffer.writeu8(raw, k, if v ~= 0 then 1 else 0) + else + local hi = math.floor(v / 4294967296) + buffer.writeu32(raw, k * 8, v - hi * 4294967296) + buffer.writeu32(raw, k * 8 + 4, hi % 4294967296) + end + end + end + u8(string.byte(t)) + u32(n) + if zip and n > 32 then + local z = Deflate.zlibCompress(raw, { level = 6 }) + if z then + u32(1) + u32(buffer.len(z)) + bytes(z) + return + end + end + u32(0) + u32(n * es) + bytes(raw) + end + @native local function setOff(at: number, v: number) + if wide then + buffer.writeu32(out, at, v % 4294967296) + buffer.writeu32(out, at + 4, math.floor(v / 4294967296)) + else + buffer.writeu32(out, at, v) + end + end + @native local function nullRecord() + ensure(head) + buffer.fill(out, pos, 0, head) + pos += head + end + @native local function node(n: WNode) + local start = pos + ensure(head) + buffer.fill(out, pos, 0, head) + pos += head + buffer.writeu8(out, start + head - 1, #n.name) + str(n.name) + local pstart = pos + local hints = n.types or "" + for k, v in n.props do + local h = string.sub(hints, k, k) + local tv = type(v) + if tv == "number" then + if h == "I" then + u8(73) + ensure(4) + buffer.writei32(out, pos, v) + pos += 4 + elseif h == "L" then + u8(76) + i64w(v) + elseif h == "F" then + u8(70) + ensure(4) + buffer.writef32(out, pos, v) + pos += 4 + elseif h == "Y" then + u8(89) + ensure(2) + buffer.writei16(out, pos, v) + pos += 2 + else + u8(68) + ensure(8) + writef64(out, pos, v) + pos += 8 + end + elseif tv == "boolean" then + u8(67) + u8(if v then 1 else 0) + elseif tv == "string" then + if string.sub(v, 1, 1) == "L" and h == "L" and #v == 17 then + u8(76) + local hi, lo = tonumber(string.sub(v, 2, 9), 16) or 0, tonumber(string.sub(v, 10, 17), 16) or 0 + u32(lo) + u32(hi) + else + u8(83) + u32(#v) + str(v) + end + elseif tv == "buffer" then + u8(82) + u32(buffer.len(v)) + bytes(v) + elseif tv == "table" and v.array then + array(v) + else + u8(83) + u32(0) + end + end + local plen = pos - pstart + local children = n.children + if children and #children > 0 then + for _, c in children do + node(c) + end + nullRecord() + elseif #n.props == 0 then + nullRecord() + end + setOff(start, pos) + if wide then + setOff(start + 8, #n.props) + setOff(start + 16, plen) + else + buffer.writeu32(out, start + 4, #n.props) + buffer.writeu32(out, start + 8, plen) + end + end + str(MAGIC) + u8(0x1A) + u8(0) + u32(ver) + for _, c in root.children or {} do + node(c) + end + nullRecord() + str(FOOT_ID) + str("\0\0\0\0") + local pad = ((pos + 15) // 16) * 16 - pos + if pad == 0 then + pad = 16 + end + str(string.rep("\0", pad)) + u32(ver) + str(string.rep("\0", 120)) + str(FOOT_MAGIC) + local res = buffer.create(pos) + buffer.copy(res, 0, out, 0, pos) + return res +end + +return Binary +end +end + + + + + + model_2 + --!optimize 2 +--!nocheck +-- rosetta chunk model_2 (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 16 modules (1 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["model/fbx/Read"] = function() + +-- model/fbx/Read: an FBX 7.x node tree -> Scene. Layer elements in every mapping (ByPolygonVertex, ByVertice, +-- ByPolygon, AllSame) and reference (Direct, IndexToDirect) mode; vertices unwelded per polygon corner as assimp does. +local Err = __include("core/Err") +local Types = __include("Types") +local Base64 = __include("core/Base64") +local Xform = __include("model/fbx/Xform") +local Mat4 = __include("codecs/model/Mat4") + +local Read = {} + +type Node = { name: string, props: { any }, children: { Node } } +type Array = { array: true, type: string, count: number, data: buffer } +type Obj = { id: any, node: Node, name: string, class: string, sub: string, props: { [string]: { any } } } +type Conn = { id: any, prop: string? } +type Fetch = (uri: string) -> buffer? + +local TICKS = 46186158000 -- FBX time units per second +Read.TICKS = TICKS + +-- ------------------------------------------------------------------------------------------------ tree helpers +local function child(n: Node?, name: string): Node? + if not n then + return nil + end + for _, c in n.children do + if c.name == name then + return c + end + end + return nil +end +Read.child = child + +local function value(n: Node?, name: string): any + local c = child(n, name) + return c and c.props[1] +end + +local function isArray(v: any): boolean + return type(v) == "table" and v.array == true +end + +-- old ASCII files have inline numbers +local function array(n: Node?, name: string): Array? + local c = child(n, name) + if not c then + return nil + end + local p = c.props[1] + if isArray(p) then + return p + end + local count = 0 + for _, v in c.props do + if type(v) == "number" then + count += 1 + end + end + if count == 0 then + return nil + end + local data = buffer.create(count * 8) + local k = 0 + for _, v in c.props do + if type(v) == "number" then + buffer.writef64(data, k * 8, v) + k += 1 + end + end + return { array = true, type = "d", count = count, data = data } +end + +local function at(a: Array, i: number): number + if i < 0 or i >= a.count then + return 0 + end + return buffer.readf64(a.data, i * 8) +end + +-- "Name\0\1Class" (binary) / "Class::Name" (ASCII) +local function objectName(s: any): string + if type(s) ~= "string" then + return "" + end + local nm = string.match(s, "^(.-)%z\1") + if nm then + return nm + end + local _, rest = string.match(s, "^(%w+)::(.*)$") + if rest then + return rest + end + return s +end +Read.objectName = objectName + +-- Properties70: P: name, type, label, flags, values... +local function properties(n: Node?, into: { [string]: { any } }?): { [string]: { any } } + local out = into or {} + local p70 = child(n, "Properties70") + if p70 then + for _, p in p70.children do + local nm = p.props[1] + if p.name == "P" and type(nm) == "string" then + local v = { p.props[2] } + for k = 5, #p.props do + v[k - 3] = p.props[k] + end + out[nm] = v + end + end + end + return out +end +Read.properties = properties + +local function pnum(props: { [string]: { any } }, name: string, default: number): number + local p = props[name] + local v = p and p[2] + if type(v) == "number" then + return v + elseif type(v) == "boolean" then + return if v then 1 else 0 + end + return default +end +local function pvec(props: { [string]: { any } }, name: string, default: { number }): { number } + local p = props[name] + if p and type(p[2]) == "number" and type(p[3]) == "number" and type(p[4]) == "number" then + return { p[2], p[3], p[4] } + end + return table.clone(default) +end +local function pstr(props: { [string]: { any } }, name: string): string? + local p = props[name] + local v = p and p[2] + return if type(v) == "string" then v else nil +end + +-- ------------------------------------------------------------------------------------------------ scene +function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Types.Scene?, Err.Err?) + local triangulate = not (opts and opts.triangulate == false) + local flipV = not (opts and opts.flipV == false) + local sampleRate = opts and type(opts.sampleRate) == "number" and opts.sampleRate > 0 and opts.sampleRate or nil + local maxVertices = opts and opts.maxVertices or 2 ^ 25 + local scene = Types.Scene.new() + + -- Definitions/ObjectType/PropertyTemplate + local templates: { [string]: { [string]: { any } } } = {} + local defs = child(root, "Definitions") + if defs then + for _, ot in defs.children do + if ot.name == "ObjectType" and type(ot.props[1]) == "string" then + local pt = child(ot, "PropertyTemplate") + if pt then + templates[ot.props[1]] = properties(pt) + end + end + end + end + + local objects: { [any]: Obj } = {} + local order: { Obj } = {} + local objs = child(root, "Objects") + if not objs then + return nil, Err.new(Err.CORRUPT, "no Objects section") + end + for _, n in objs.children do + local id = n.props[1] + if (type(id) == "number" or type(id) == "string") and objects[id] == nil then + local base = templates[n.name] + local props = properties(n, if base then table.clone(base) else nil) + local o: Obj = { id = id, node = n, name = objectName(n.props[2]), class = n.name, sub = if type(n.props[3]) == "string" then n.props[3] else "", props = props } + objects[id] = o + table.insert(order, o) + end + end + + local kids: { [any]: { Conn } } = {} + local parents: { [any]: { Conn } } = {} + local conns = child(root, "Connections") + if conns then + for _, c in conns.children do + if c.name == "C" or c.name == "Connect" then + local src, dst = c.props[2], c.props[3] + local prop = if type(c.props[4]) == "string" then c.props[4] else nil + if src ~= nil and dst ~= nil and type(src) ~= "table" and type(dst) ~= "table" then + kids[dst] = kids[dst] or {} + table.insert(kids[dst], { id = src, prop = prop }) + parents[src] = parents[src] or {} + table.insert(parents[src], { id = dst, prop = prop }) + end + end + end + end + local function sources(id: any, class: string?, sub: string?): { Obj } + local out = {} + for _, c in kids[id] or {} do + local o = objects[c.id] + if o and (class == nil or o.class == class) and (sub == nil or o.sub == sub) then + table.insert(out, o) + end + end + return out + end + local function sourcesProp(id: any): { { obj: Obj, prop: string? } } + local out = {} + for _, c in kids[id] or {} do + local o = objects[c.id] + if o then + table.insert(out, { obj = o, prop = c.prop }) + end + end + return out + end + local function targets(id: any, class: string?): { { obj: Obj, prop: string? } } + local out = {} + for _, c in parents[id] or {} do + local o = objects[c.id] + if o and (class == nil or o.class == class) then + table.insert(out, { obj = o, prop = c.prop }) + end + end + return out + end + + local gs = properties(child(root, "GlobalSettings")) + local upAxis = pnum(gs, "UpAxis", 1) + local unitScale = pnum(gs, "UnitScaleFactor", 1) + scene.meta.up = if upAxis == 2 then "z" else "y" + scene.meta.unit = unitScale / 100 + local frameRates = { [1] = 120, [2] = 100, [3] = 60, [4] = 50, [5] = 48, [6] = 30, [7] = 30, [8] = 29.97, [9] = 29.97, [10] = 25, [11] = 24, [13] = 96, [14] = 72, [15] = 59.94, [17] = 119.88 } + local timeMode = pnum(gs, "TimeMode", 0) + local fps = if timeMode == 14 then pnum(gs, "CustomFrameRate", 24) else frameRates[timeMode] or 24 + + -- ------------------------------------------------------------------------------------------ textures + local textureIndex: { [any]: number } = {} + local function mimeOf(data: buffer?, name: string?): string? + if data and buffer.len(data) >= 4 then + local h = buffer.readstring(data, 0, 4) + if h == "\137PNG" then + return "image/png" + elseif string.sub(h, 1, 3) == "\255\216\255" then + return "image/jpeg" + elseif string.sub(h, 1, 2) == "BM" then + return "image/bmp" + elseif h == "DDS " then + return "image/vnd-ms.dds" + elseif h == "RIFF" then + return "image/webp" + end + end + local ext = name and string.lower(string.match(name, "%.(%w+)$") or "") or "" + local M = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", tga = "image/x-tga", bmp = "image/bmp", dds = "image/vnd-ms.dds", tif = "image/tiff", tiff = "image/tiff", webp = "image/webp", gif = "image/gif", psd = "image/vnd.adobe.photoshop" } + return M[ext] + end + local function content(v: Node?): buffer? + if not v then + return nil + end + local c = child(v, "Content") + if not c then + return nil + end + for _, p in c.props do + if type(p) == "buffer" and buffer.len(p) > 0 then + return p + end + end + -- ASCII: base64, possibly split into several strings + local parts = {} + for _, p in c.props do + if type(p) == "string" then + table.insert(parts, p) + end + end + local s = table.concat(parts) + if #s > 0 then + local d = Base64.decode(s) + if d and buffer.len(d) > 0 then + return d + end + end + return nil + end + local function texture(o: Obj): number + local have = textureIndex[o.id] + if have then + return have + end + local n = o.node + local rel = value(n, "RelativeFilename") + local file = value(n, "FileName") or value(n, "Filename") + local data: buffer? = nil + local video: Obj? = sources(o.id, "Video")[1] + if video then + data = content(video.node) + rel = rel or value(video.node, "RelativeFilename") + file = file or value(video.node, "Filename") or value(video.node, "FileName") + end + local uri: string? = nil + if type(rel) == "string" and rel ~= "" then + uri = (string.gsub(rel, "\\", "/")) + elseif type(file) == "string" and file ~= "" then + uri = (string.gsub(file, "\\", "/")) + end + if not data and uri then + data = fetch(uri :: string) + if not data then + local base = string.match(uri :: string, "([^/]+)$") + if base and base ~= uri then + data = fetch(base) + end + end + end + local tex: Types.Texture = { name = o.name, data = data, uri = if data and video and content(video.node) then nil else uri, mime = mimeOf(data, uri) } + local wrapU, wrapV = pnum(o.props, "WrapModeU", 0), pnum(o.props, "WrapModeV", 0) + if wrapU ~= 0 or wrapV ~= 0 then + tex.sampler = { wrapS = if wrapU == 1 then "clamp" else "repeat", wrapT = if wrapV == 1 then "clamp" else "repeat" } + end + tex.extras = { fbx = { uri = uri, uvSet = pstr(o.props, "UVSet") } } + table.insert(scene.textures, tex) + textureIndex[o.id] = #scene.textures + return #scene.textures + end + local function texRef(o: Obj): Types.TextureRef? + local tobj = o + if o.class == "LayeredTexture" then + local t = sources(o.id, "Texture")[1] + if not t then + return nil + end + tobj = t + end + local ref: Types.TextureRef = { texture = texture(tobj) } + local tr, sc = pvec(tobj.props, "Translation", { 0, 0, 0 }), pvec(tobj.props, "Scaling", { 1, 1, 1 }) + local rot = pvec(tobj.props, "Rotation", { 0, 0, 0 }) + if tr[1] ~= 0 or tr[2] ~= 0 or sc[1] ~= 1 or sc[2] ~= 1 or rot[3] ~= 0 then + ref.transform = { offset = { tr[1], tr[2] }, scale = { sc[1], sc[2] }, rotation = rot[3] * math.pi / 180 } + end + return ref + end + + -- ------------------------------------------------------------------------------------------ materials + local materialIndex: { [any]: number } = {} + local function material(o: Obj): number + local have = materialIndex[o.id] + if have then + return have + end + local p = o.props + local m = Types.Scene.material(o.name) + local shading = value(o.node, "ShadingModel") + local diffuse = pvec(p, "DiffuseColor", pvec(p, "Diffuse", { 0.8, 0.8, 0.8 })) + local dfac = pnum(p, "DiffuseFactor", 1) + local emissive = pvec(p, "EmissiveColor", pvec(p, "Emissive", { 0, 0, 0 })) + local efac = pnum(p, "EmissiveFactor", 1) + local shininess = pnum(p, "ShininessExponent", pnum(p, "Shininess", 20)) + local opacity: number + if p.Opacity then + opacity = pnum(p, "Opacity", 1) + else + local tc = pvec(p, "TransparentColor", { 1, 1, 1 }) + opacity = 1 - pnum(p, "TransparencyFactor", 0) * (tc[1] + tc[2] + tc[3]) / 3 + end + opacity = math.clamp(opacity, 0, 1) + m.baseColor = { diffuse[1] * dfac, diffuse[2] * dfac, diffuse[3] * dfac, opacity } + m.emissive = { emissive[1] * efac, emissive[2] * efac, emissive[3] * efac } + m.metallic = 0 + m.roughness = math.clamp(math.sqrt(2 / (math.max(shininess, 0) + 2)), 0, 1) + if opacity < 1 then + m.alphaMode = "blend" + end + local pbr = p["3dsMax|main|basecolor"] or p["3dsMax|Parameters|base_color"] + if pbr then + local prefix = if p["3dsMax|main|basecolor"] then "3dsMax|main|" else "3dsMax|Parameters|" + local bc = pbr + if type(bc[2]) == "number" then + m.baseColor = { bc[2], bc[3] or 1, bc[4] or 1, if type(bc[5]) == "number" then bc[5] else 1 } + end + m.metallic = pnum(p, prefix .. "metalness", 0) + m.roughness = pnum(p, prefix .. "roughness", 1) + if pnum(p, prefix .. "useGlossiness", 0) == 1 or pnum(p, prefix .. "roughness_inv", 0) == 1 then + m.roughness = 1 - pnum(p, prefix .. "glossiness", 1 - m.roughness) + end + local ec = p[prefix .. "emit_color"] or p[prefix .. "emission_color"] + if ec and type(ec[2]) == "number" then + local k = pnum(p, prefix .. "emission", 1) + m.emissive = { ec[2] * k, (ec[3] or 0) * k, (ec[4] or 0) * k } + end + end + local extras: { [string]: any } = { + shadingModel = if type(shading) == "string" then string.lower(shading) else pstr(p, "ShadingModel"), + diffuse = diffuse, + diffuseFactor = dfac, + ambient = pvec(p, "AmbientColor", pvec(p, "Ambient", { 0, 0, 0 })), + ambientFactor = pnum(p, "AmbientFactor", 1), + specular = pvec(p, "SpecularColor", pvec(p, "Specular", { 0.2, 0.2, 0.2 })), + specularFactor = pnum(p, "SpecularFactor", 1), + shininess = shininess, + emissive = emissive, + emissiveFactor = efac, + opacity = opacity, + reflection = pvec(p, "ReflectionColor", { 0, 0, 0 }), + reflectionFactor = pnum(p, "ReflectionFactor", 0), + bumpFactor = pnum(p, "BumpFactor", 1), + textures = {}, + } + for _, s in sourcesProp(o.id) do + local cls = s.obj.class + if (cls == "Texture" or cls == "LayeredTexture") and s.prop then + local ref = texRef(s.obj) + if ref then + local prop = s.prop :: string + local lp = string.lower(prop) + extras.textures[prop] = ref.texture + if lp == "diffusecolor" or string.find(lp, "base_?color_map") or lp == "maya|basecolor" or lp == "maya|texturebasecolor" then + m.baseColorTexture = m.baseColorTexture or ref + elseif lp == "normalmap" or lp == "bump" or string.find(lp, "norm_map") or string.find(lp, "bump_map") or lp == "maya|normalcamera" then + m.normalTexture = m.normalTexture or ref + elseif lp == "emissivecolor" or string.find(lp, "emit_color_map") or string.find(lp, "emission_map") then + m.emissiveTexture = m.emissiveTexture or ref + if m.emissive[1] == 0 and m.emissive[2] == 0 and m.emissive[3] == 0 then + m.emissive = { 1, 1, 1 } + end + elseif string.find(lp, "ao_map") then + m.occlusionTexture = m.occlusionTexture or ref + end + end + end + end + if not next(extras.textures) then + extras.textures = nil + end + m.extras = { fbx = extras } + table.insert(scene.materials, m) + materialIndex[o.id] = #scene.materials + return #scene.materials + end + + -- ------------------------------------------------------------------------------------------ nodes + local models: { Obj } = {} + local nodeOf: { [any]: number } = {} + for _, o in order do + if o.class == "Model" then + table.insert(models, o) + local nd: Types.Node = { name = o.name, children = {} } + table.insert(scene.nodes, nd) + nodeOf[o.id] = #scene.nodes + end + end + if #models > maxVertices then + return nil, Err.new(Err.LIMIT, "too many models") + end + local function xprops(o: Obj, over: { [string]: { number } }?): Xform.Props + local p = o.props + local function g(name: string, key: string, default: { number }): { number } + if over and over[key] then + return over[key] + end + return pvec(p, name, default) + end + return { + T = g("Lcl Translation", "T", { 0, 0, 0 }), + R = g("Lcl Rotation", "R", { 0, 0, 0 }), + S = g("Lcl Scaling", "S", { 1, 1, 1 }), + Rpre = pvec(p, "PreRotation", { 0, 0, 0 }), + Rpost = pvec(p, "PostRotation", { 0, 0, 0 }), + Roff = pvec(p, "RotationOffset", { 0, 0, 0 }), + Rp = pvec(p, "RotationPivot", { 0, 0, 0 }), + Soff = pvec(p, "ScalingOffset", { 0, 0, 0 }), + Sp = pvec(p, "ScalingPivot", { 0, 0, 0 }), + order = pnum(p, "RotationOrder", 0), + } + end + 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 = Mat4.decompose(m) + if t[1] ~= 0 or t[2] ~= 0 or t[3] ~= 0 then + nd.translation = t + end + if r[1] ~= 0 or r[2] ~= 0 or r[3] ~= 0 or r[4] ~= 1 then + nd.rotation = r + end + if s[1] ~= 1 or s[2] ~= 1 or s[3] ~= 1 then + nd.scale = s + end + nd.extras = { fbx = { type = o.sub, id = o.id } } + local parentModel: Obj? = nil + for _, t2 in targets(o.id, "Model") do + parentModel = t2.obj + break + end + local pi = parentModel and nodeOf[parentModel.id] + if pi and pi ~= ni then + table.insert(scene.nodes[pi].children, ni) + else + table.insert(scene.roots, ni) + end + end + -- break parent cycles: cut children already placed + do + local placed: { [number]: boolean } = {} + local function visit(i: number) + placed[i] = true + local nd = scene.nodes[i] + local keepKids = {} + for _, c in nd.children do + if not placed[c] then + table.insert(keepKids, c) + visit(c) + end + end + nd.children = keepKids + end + for _, r in scene.roots do + visit(r) + end + for i in scene.nodes do + if not placed[i] then + table.insert(scene.roots, i) + visit(i) + end + end + end + 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]) + end + end + end + for _, r in scene.roots do + world(r, Mat4.identity()) + end + + -- ------------------------------------------------------------------------------------------ meshes + local corners = 0 + local function skinOf(geo: Obj): ({ { { number } } }?, Types.Skin?) + local skin = sources(geo.id, "Deformer", "Skin")[1] + if not skin then + return nil, nil + end + local perCp: { { { number } } } = {} + local joints: { number } = {} + 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] + if bi then + local ji = #joints + 1 + 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 = Mat4.identity() + if T and T.count >= 16 then + for k = 1, 16 do + tm[k] = at(T, k - 1) + end + end + local tl: Mat4.M4? = nil + if TL and TL.count >= 16 then + tl = {} + for k = 1, 16 do + (tl :: any)[k] = at(TL, k - 1) + end + else + tl = worldM[bi] + end + 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) + local wt = at(w, k) + if cp >= 0 and cp == math.floor(cp) and cp < maxVertices and wt > 0 then + local l = perCp[cp + 1] + if not l then + l = {} + perCp[cp + 1] = l + end + table.insert(l, { ji - 1, wt }) + end + end + end + end + end + if #joints == 0 then + return nil, nil + end + local ibm = buffer.create(#joints * 64) + for j, m in ibms do + for k = 1, 16 do + buffer.writef32(ibm, (j - 1) * 64 + (k - 1) * 4, m[k]) + end + end + local acc = Types.Scene.accessor(ibm, "f32", 16, #joints) + acc.matrix = true + return perCp, { name = skin.name, joints = joints, inverseBindMatrices = acc } + end + type Shape = { name: string, channel: Obj, weight: number, idx: Array?, dv: Array?, dn: Array? } + local function shapesOf(geo: Obj): { Shape } + local out = {} + for _, bs in sources(geo.id, "Deformer", "BlendShape") do + for _, ch in sources(bs.id, "Deformer", "BlendShapeChannel") do + local shapes = sources(ch.id, "Geometry") + local sh = shapes[#shapes] -- in-betweens: the full (last) shape + if sh then + table.insert(out, { + name = ch.name ~= "" and ch.name or sh.name, + channel = ch, + weight = pnum(ch.props, "DeformPercent", 0) / 100, + idx = array(sh.node, "Indexes"), + dv = array(sh.node, "Vertices"), + dn = array(sh.node, "Normals"), + }) + end + end + end + return out + end + + local meshCache: { [string]: number } = {} + local shapeChannels: { [number]: { Obj } } = {} + local nodeSkin: { [number]: number } = {} + local skinCache: { [any]: number } = {} + + 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") + if not verts or not pvi then + return nil, nil + end + local ncp = verts.count // 3 + local nc = pvi.count + corners += nc + if corners > maxVertices or ncp > maxVertices then + return nil, Err.new(Err.LIMIT, "over " .. maxVertices .. " vertices") + end + local cp = table.create(nc, 0) + local polyOf = table.create(nc, 0) + local starts: { number } = { 0 } + local np = 0 + for c = 0, nc - 1 do + local v = at(pvi, c) + local last = v < 0 + if last then + v = -v - 1 + end + if v >= ncp or v ~= math.floor(v) then + v = 0 + end + cp[c + 1] = v + polyOf[c + 1] = np + if last then + np += 1 + starts[np + 1] = c + 1 + end + end + if starts[np + 1] ~= nc then + -- the last polygon has no end marker + np += 1 + starts[np + 1] = nc + end + type Elem = { data: Array, index: Array?, mapping: string, comps: number, name: string?, order: number } + local function elems(kind: string, dataName: string, indexName: string, comps: number): { Elem } + local out: { Elem } = {} + for _, c in g.children do + if c.name == kind then + local data = array(c, dataName) + local mapping = value(c, "MappingInformationType") + local ref = value(c, "ReferenceInformationType") + local index = if ref == "IndexToDirect" or ref == "Index" then array(c, indexName) or array(c, dataName .. "Index") else nil + if kind == "LayerElementMaterial" then + index = data + end + if data and type(mapping) == "string" then + table.insert(out, { data = data, index = index, mapping = mapping, comps = comps, name = value(c, "Name"), order = if type(c.props[1]) == "number" then c.props[1] else #out }) + end + end + end + table.sort(out, function(a: Elem, b: Elem): boolean + return a.order < b.order + end) + return out + end + local function lookup(e: Elem, c: number): number + local m = e.mapping + local i + if m == "ByPolygonVertex" then + i = c + elseif m == "ByVertice" or m == "ByVertex" then + i = cp[c + 1] + elseif m == "ByPolygon" then + i = polyOf[c + 1] + elseif m == "AllSame" then + i = 0 + else + return -1 + end + if e.index and e.data ~= e.index then + if i >= (e.index :: Array).count then + return -1 + end + i = at(e.index :: Array, i) + end + if i < 0 or (i + 1) * e.comps > e.data.count then + return -1 + end + return i + end + local normals = elems("LayerElementNormal", "Normals", "NormalsIndex", 3) + local uvs = elems("LayerElementUV", "UV", "UVIndex", 2) + local colors = elems("LayerElementColor", "Colors", "ColorIndex", 4) + local tangents = elems("LayerElementTangent", "Tangents", "TangentsIndex", 3) + local matEl = elems("LayerElementMaterial", "Materials", "Materials", 1)[1] + -- "NormalsIndex" / "NormalIndex" + for _, e in normals do + if not e.index then + local c = nil + for _, x in g.children do + if x.name == "LayerElementNormal" then + c = x + break + end + end + local r = c and value(c, "ReferenceInformationType") + if r == "IndexToDirect" then + e.index = array(c, "NormalIndex") + end + end + end + local groups: { [number]: { number } } = {} + local slots: { number } = {} + for p = 0, np - 1 do + local slot = 0 + if matEl then + local c0 = starts[p + 1] + local i = if matEl.mapping == "AllSame" then 0 else p + if matEl.mapping == "ByPolygonVertex" then + i = c0 + end + slot = at(matEl.data, i) + if slot < 0 or slot ~= math.floor(slot) then + slot = 0 + end + end + local grp = groups[slot] + if not grp then + grp = {} + groups[slot] = grp + table.insert(slots, slot) + end + table.insert(grp, p) + end + table.sort(slots) + local perCp, skin = skinOf(geo) + local shapes = shapesOf(geo) + local N3: Mat4.M4? = nil -- inverse transpose of G + if G then + 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: 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 + buffer.writef32(dst, o, x) + buffer.writef32(dst, o + 4, y) + buffer.writef32(dst, o + 8, z) + end + local skipped = 0 + for _, slot in slots do + local polys = groups[slot] + local nv = 0 + local ntri = 0 + for _, p in polys do + local k = starts[p + 2] - starts[p + 1] + if k >= 3 or not triangulate then + nv += k + ntri += math.max(k - 2, 0) + else + skipped += 1 + end + end + if nv > 0 then + local pos = buffer.create(nv * 12) + local nrm = if normals[1] then buffer.create(nv * 12) else nil + local tan = if tangents[1] then buffer.create(nv * 16) else nil + local uvb: { buffer } = {} + for k = 1, #uvs do + uvb[k] = buffer.create(nv * 8) + end + local colb: { buffer } = {} + for k = 1, #colors do + colb[k] = buffer.create(nv * 16) + end + local joints = if perCp then buffer.create(nv * 8) else nil + local weights = if perCp then buffer.create(nv * 16) else nil + local tgt: { { [string]: Types.Accessor } } = {} + local shapeData: { { pos: buffer, nrm: buffer?, map: { [number]: number } } } = {} + for si, sh in shapes do + local map: { [number]: number } = {} + if sh.idx then + for k = 0, sh.idx.count - 1 do + map[at(sh.idx, k)] = k + end + end + shapeData[si] = { pos = buffer.create(nv * 12), nrm = if sh.dn and nrm then buffer.create(nv * 12) else nil, map = map } + end + local faces = if not triangulate then buffer.create(#polys * 4) else nil + local idx = buffer.create((if triangulate then ntri * 3 else nv) * 4) + local v = 0 + local ti = 0 + local fi = 0 + for _, p in polys do + local c0, c1 = starts[p + 1], starts[p + 2] + local k = c1 - c0 + if k >= 3 or not triangulate then + local first = v + for c = c0, c1 - 1 do + local i = cp[c + 1] + v3(pos, v * 12, at(verts, i * 3), at(verts, i * 3 + 1), at(verts, i * 3 + 2), G, 1) + if nrm then + local d = lookup(normals[1], c) + local e = normals[1].data + if d >= 0 then + v3(nrm, v * 12, at(e, d * 3), at(e, d * 3 + 1), at(e, d * 3 + 2), N3, 0) + end + end + if tan then + local d = lookup(tangents[1], c) + local e = tangents[1].data + if d >= 0 then + v3(tan, v * 16, at(e, d * 3), at(e, d * 3 + 1), at(e, d * 3 + 2), G, 0) + buffer.writef32(tan, v * 16 + 12, 1) + end + end + for u, e in uvs do + local d = lookup(e, c) + if d >= 0 then + local uu, vv = at(e.data, d * 2), at(e.data, d * 2 + 1) + buffer.writef32(uvb[u], v * 8, uu) + buffer.writef32(uvb[u], v * 8 + 4, if flipV then 1 - vv else vv) + end + end + for u, e in colors do + local d = lookup(e, c) + local b = colb[u] + if d >= 0 then + for q = 0, 3 do + buffer.writef32(b, v * 16 + q * 4, at(e.data, d * 4 + q)) + end + else + buffer.writef32(b, v * 16 + 12, 1) + end + end + if perCp and joints and weights then + local l = perCp[i + 1] + if l then + if #l > 4 then + table.sort(l, function(a: { number }, b: { number }): boolean + return a[2] > b[2] + end) + end + local sum = 0 + for q = 1, math.min(#l, 4) do + sum += l[q][2] + end + for q = 1, math.min(#l, 4) do + buffer.writeu16(joints, v * 8 + (q - 1) * 2, l[q][1]) + buffer.writef32(weights, v * 16 + (q - 1) * 4, if sum > 0 then l[q][2] / sum else 0) + end + end + end + for si, sd in shapeData do + local sh = shapes[si] + local k2 = sd.map[i] + if k2 and sh.dv then + v3(sd.pos, v * 12, at(sh.dv, k2 * 3), at(sh.dv, k2 * 3 + 1), at(sh.dv, k2 * 3 + 2), G, 0) + if sd.nrm and sh.dn then + v3(sd.nrm, v * 12, at(sh.dn, k2 * 3), at(sh.dn, k2 * 3 + 1), at(sh.dn, k2 * 3 + 2), N3, 0) + end + end + end + if not triangulate then + buffer.writeu32(idx, v * 4, v) + end + v += 1 + end + if triangulate then + for q = 1, k - 2 do + buffer.writeu32(idx, ti * 4, first) + buffer.writeu32(idx, ti * 4 + 4, first + q) + buffer.writeu32(idx, ti * 4 + 8, first + q + 1) + ti += 3 + end + elseif faces then + buffer.writeu32(faces, fi * 4, k) + fi += 1 + end + end + end + local attrs: { [string]: Types.Accessor } = { POSITION = Types.Scene.accessor(pos, "f32", 3, nv) } + if nrm then + attrs.NORMAL = Types.Scene.accessor(nrm, "f32", 3, nv) + end + if tan then + attrs.TANGENT = Types.Scene.accessor(tan, "f32", 4, nv) + end + for u, b in uvb do + attrs["TEXCOORD_" .. (u - 1)] = Types.Scene.accessor(b, "f32", 2, nv) + end + for u, b in colb do + attrs["COLOR_" .. (u - 1)] = Types.Scene.accessor(b, "f32", 4, nv) + end + if joints and weights then + attrs.JOINTS_0 = Types.Scene.accessor(joints, "u16", 4, nv) + attrs.WEIGHTS_0 = Types.Scene.accessor(weights, "f32", 4, nv) + end + for si, sd in shapeData do + local t: { [string]: Types.Accessor } = { POSITION = Types.Scene.accessor(sd.pos, "f32", 3, nv) } + if sd.nrm then + t.NORMAL = Types.Scene.accessor(sd.nrm, "f32", 3, nv) + end + tgt[si] = t + end + local prim: Types.Primitive = { + attributes = attrs, + indices = Types.Scene.accessor(idx, "u32", 1, if triangulate then ntri * 3 else nv), + mode = if triangulate then "triangles" else "polygons", + faces = if faces then Types.Scene.accessor(faces, "u32", 1, #polys) else nil, + material = mats[slot + 1], + targets = if #tgt > 0 then tgt else nil, + } + table.insert(mesh.primitives, prim) + end + end + if #mesh.primitives == 0 then + return nil, nil + end + local names = {} + for k, uv in uvs do + names[k] = uv.name + end + mesh.extras = { fbx = { id = geo.id, uvSets = names, skippedPolygons = if skipped > 0 then skipped else nil } } + if #shapes > 0 then + local w, tn, chans = {}, {}, {} + for si, sh in shapes do + w[si] = sh.weight + tn[si] = sh.name + chans[si] = sh.channel + end + mesh.weights = w + ;(mesh.extras :: any).targetNames = tn + table.insert(scene.meshes, mesh) + shapeChannels[#scene.meshes] = chans + else + table.insert(scene.meshes, mesh) + end + local mi = #scene.meshes + if skin then + skinCache[geo.id] = skinCache[geo.id] or (function(): number + table.insert(scene.skins, skin) + return #scene.skins + end)() + end + return mi, nil + end + + local orient = math.sqrt(0.5) + for _, o in models do + local ni = nodeOf[o.id] + local nd = scene.nodes[ni] + local mats: { number } = {} + for _, m in sources(o.id, "Material") do + table.insert(mats, material(m)) + end + -- geometric transform: not inherited, baked into the mesh + 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: 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 = 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 + local key = tostring(geo.id) .. "|" .. table.concat(mats, ",") .. "|" .. (if G then table.concat(G :: any, ",") else "") + local mi = meshCache[key] + if mi == nil then + local m, err = buildMesh(geo, mats, G) + if err then + return nil, err + end + if m then + meshCache[key] = m + mi = m + end + end + if mi then + if nd.mesh == nil then + nd.mesh = mi + if skinCache[geo.id] then + nd.skin = skinCache[geo.id] + end + nd.weights = scene.meshes[mi].weights and table.clone(scene.meshes[mi].weights :: { number }) + else + -- a second geometry on the same model: a child node + table.insert(scene.nodes, { name = o.name, children = {}, mesh = mi, skin = skinCache[geo.id] }) + table.insert(nd.children, #scene.nodes) + end + nodeSkin[ni] = skinCache[geo.id] + end + end + end + -- cameras / lights: a child node rotated from glTF's -Z forward to FBX's +X camera / -Y light axis + for _, a in sources(o.id, "NodeAttribute") do + local p = a.props + if a.sub == "Camera" then + local ortho = pnum(p, "CameraProjectionType", 0) == 1 + local aw, ah = pnum(p, "AspectWidth", 0), pnum(p, "AspectHeight", 0) + local fw, fh = pnum(p, "FilmWidth", 0.816), pnum(p, "FilmHeight", 0.612) + local aspect = if aw > 0 and ah > 0 then aw / ah elseif fh > 0 then fw / fh else 4 / 3 + local cam: Types.Camera + 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 } :: Types.Camera + else + local focal = pnum(p, "FocalLength", 0) + local hfov + if focal > 0 and fw > 0 then + hfov = 2 * math.atan(fw * 25.4 / (2 * focal)) + else + 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 } :: 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" } } }) + table.insert(nd.children, #scene.nodes) + elseif a.sub == "Light" then + local lt = pnum(p, "LightType", 0) + local col = pvec(p, "Color", { 1, 1, 1 }) + local light: Types.Light = { + name = a.name ~= "" and a.name or o.name, + type = if lt == 1 then "directional" elseif lt == 2 then "spot" else "point", + color = col, + intensity = pnum(p, "Intensity", 100) / 100, + } + if lt == 2 then + local outer = pnum(p, "OuterAngle", pnum(p, "Cone angle", 45)) + local inner = pnum(p, "InnerAngle", pnum(p, "HotSpot", 0)) + light.outerCone = math.clamp(outer / 2, 0, 90) * math.pi / 180 + light.innerCone = math.clamp(math.min(inner, outer) / 2, 0, 90) * math.pi / 180 + end + if pnum(p, "EnableFarAttenuation", 0) == 1 then + light.range = pnum(p, "FarAttenuationEnd", 0) + end + table.insert(scene.lights, light) + table.insert(scene.nodes, { name = o.name .. "_light", children = {}, light = #scene.lights, rotation = { -orient, 0, 0, orient }, extras = { fbx = { orientation = "light", lightType = lt } } }) + table.insert(nd.children, #scene.nodes) + end + end + end + + -- ------------------------------------------------------------------------------------------ animation + type Curve = { times: { number }, values: { number }, flags: { number }, slopes: { { number } }? } + local curveCache: { [any]: Curve } = {} + local function curve(o: Obj): Curve? + local have = curveCache[o.id] + if have then + return have + end + local kt, kv = array(o.node, "KeyTime"), array(o.node, "KeyValueFloat") + if not kt or not kv then + return nil + end + local n = math.min(kt.count, kv.count) + if n == 0 then + return nil + end + local times, values = table.create(n, 0), table.create(n, 0) + for k = 0, n - 1 do + times[k + 1] = at(kt, k) / TICKS + values[k + 1] = at(kv, k) + end + -- expanded through KeyAttrRefCount + local fl, rc, df = array(o.node, "KeyAttrFlags"), array(o.node, "KeyAttrRefCount"), array(o.node, "KeyAttrDataFloat") + local flags = table.create(n, 4) + local slopes: { { number } } = {} + if fl and rc then + local key = 1 + for a = 0, math.min(fl.count, rc.count) - 1 do + local f = at(fl, a) + local cnt = at(rc, a) + for _ = 1, math.min(cnt, n - key + 1) do + flags[key] = f + if df and df.count >= (a + 1) * 4 then + slopes[key] = { at(df, a * 4), at(df, a * 4 + 1) } + end + key += 1 + end + end + end + local c: Curve = { times = times, values = values, flags = flags, slopes = slopes } + curveCache[o.id] = c + return c + end + local function eval(c: Curve, t: number): number + local ts, vs = c.times, c.values + local n = #ts + if t <= ts[1] then + return vs[1] + elseif t >= ts[n] then + return vs[n] + end + local lo, hi = 1, n + while hi - lo > 1 do + local mid = (lo + hi) // 2 + if ts[mid] <= t then + lo = mid + else + hi = mid + end + end + local dt = ts[hi] - ts[lo] + if dt <= 0 then + return vs[hi] + end + local u = (t - ts[lo]) / dt + local f = bit32.band(c.flags[lo] or 4, 0x0E) + if f == 2 then + return vs[lo] + elseif f == 8 and c.slopes and c.slopes[lo] then + local s = (c.slopes :: { { number } })[lo] + local m0, m1 = s[1] * dt, s[2] * dt + local u2, u3 = u * u, u * u * u + return (2 * u3 - 3 * u2 + 1) * vs[lo] + (u3 - 2 * u2 + u) * m0 + (-2 * u3 + 3 * u2) * vs[hi] + (u3 - u2) * m1 + end + return vs[lo] + (vs[hi] - vs[lo]) * u + end + local function allConstant(cs: { Curve }): boolean + for _, c in cs do + for k = 1, #c.times - 1 do + if bit32.band(c.flags[k] or 4, 0x0E) ~= 2 then + return false + end + end + end + return true + end + local function sampleTimes(cs: { Curve }): { number } + local set: { [number]: boolean } = {} + local out: { number } = {} + local tmin, tmax = math.huge, -math.huge + for _, c in cs do + for _, t in c.times do + tmin, tmax = math.min(tmin, t), math.max(tmax, t) + if not set[t] then + set[t] = true + table.insert(out, t) + end + end + end + if sampleRate and tmax > tmin then + local steps = math.min(math.ceil((tmax - tmin) * sampleRate), 100000) + for k = 0, steps do + local t = tmin + (tmax - tmin) * k / steps + if not set[t] then + set[t] = true + table.insert(out, t) + end + end + end + table.sort(out) + return out + end + local function f32acc(vals: { number }, comps: number): Types.Accessor + local n = #vals // comps + local b = buffer.create(#vals * 4) + for k, v in vals do + buffer.writef32(b, (k - 1) * 4, v) + end + return Types.Scene.accessor(b, "f32", comps, n) + end + local PROPS = { ["Lcl Translation"] = "T", ["Lcl Rotation"] = "R", ["Lcl Scaling"] = "S" } + for _, stack in order do + if stack.class == "AnimationStack" then + local anim: Types.Animation = { name = stack.name, channels = {} } + type Track = { curves: { [string]: { [number]: Curve } }, defaults: { [string]: { number } } } + local tracks: { [any]: Track } = {} + local trackOrder: { any } = {} + local morph: { [any]: Curve } = {} + local layers = sources(stack.id, "AnimationLayer") + for _, layer in layers do + for _, cn in sources(layer.id, "AnimationCurveNode") do + for _, tgt in targets(cn.id) do + local key = tgt.prop and PROPS[tgt.prop] + if key and tgt.obj.class == "Model" and nodeOf[tgt.obj.id] then + local tr = tracks[tgt.obj.id] + if not tr then + tr = { curves = {}, defaults = {} } + tracks[tgt.obj.id] = tr + table.insert(trackOrder, tgt.obj.id) + end + if not tr.curves[key] then + local axes: { [number]: Curve } = {} + for _, s in sourcesProp(cn.id) do + if s.obj.class == "AnimationCurve" and s.prop then + local ax = if string.find(s.prop, "X$") then 1 elseif string.find(s.prop, "Y$") then 2 elseif string.find(s.prop, "Z$") then 3 else nil + local c = ax and curve(s.obj) + if ax and c then + axes[ax] = c + end + end + end + if next(axes) then + tr.curves[key] = axes + tr.defaults[key] = { pnum(cn.props, "d|X", 0), pnum(cn.props, "d|Y", 0), pnum(cn.props, "d|Z", 0) } + end + end + elseif tgt.prop == "DeformPercent" and tgt.obj.class == "Deformer" then + for _, s in sources(cn.id, "AnimationCurve") do + local c = curve(s) + if c and not morph[tgt.obj.id] then + morph[tgt.obj.id] = c + end + end + end + end + end + end + for _, id in trackOrder do + local tr = tracks[id] + local o = objects[id] + local ni = nodeOf[id] + local cs: { Curve } = {} + for _, axes in tr.curves do + for _, c in pairs(axes) do + table.insert(cs, c) + end + end + local times = sampleTimes(cs) + if #times > 0 then + local base = xprops(o) + local T, R, S = {}, {}, {} + local prevQ: { number }? = nil + for _, t in times do + local over: { [string]: { number } } = {} + for key, axes in tr.curves do + local stat = (base :: any)[key] + local v = table.clone(stat) + for ax = 1, 3 do + local c = axes[ax] + if c then + v[ax] = eval(c, t) + end + end + over[key] = v + end + 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 + prevQ = rr + table.move(tt, 1, 3, #T + 1, T) + table.move(rr, 1, 4, #R + 1, R) + table.move(ss, 1, 3, #S + 1, S) + end + local input = f32acc(times, 1) + local interp: any = if allConstant(cs) then "STEP" else "LINEAR" + local nd = scene.nodes[ni] + local function varies(vals: { number }, comps: number, rest: { number }): boolean + for k = 0, #vals // comps - 1 do + for q = 1, comps do + if math.abs(vals[k * comps + q] - rest[q]) > 1e-6 then + return true + end + end + end + 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 } :: 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 } :: 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 } :: Types.Channel) + end + end + end + if next(morph) then + for ni, nd in scene.nodes do + local chans = nd.mesh and shapeChannels[nd.mesh] + if chans then + local cs: { Curve } = {} + for _, ch in chans do + if morph[ch.id] then + table.insert(cs, morph[ch.id]) + end + end + if #cs > 0 then + local times = sampleTimes(cs) + local out = {} + for _, t in times do + for _, ch in chans do + local c = morph[ch.id] + table.insert(out, (if c then eval(c, t) else pnum(ch.props, "DeformPercent", 0)) / 100) + 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" } :: Types.Channel) + end + end + end + end + if #anim.channels > 0 then + table.insert(scene.animations, anim) + end + end + end + + -- ------------------------------------------------------------------------------------------ meta + local header = child(root, "FBXHeaderExtension") + local creator = value(root, "Creator") or value(header, "Creator") + scene.meta.source = { + format = "fbx", + version = version, + creator = if type(creator) == "string" then creator else nil, + upAxis = upAxis, + upAxisSign = pnum(gs, "UpAxisSign", 1), + frontAxis = pnum(gs, "FrontAxis", 2), + frontAxisSign = pnum(gs, "FrontAxisSign", 1), + coordAxis = pnum(gs, "CoordAxis", 0), + coordAxisSign = pnum(gs, "CoordAxisSign", 1), + unitScaleFactor = unitScale, + originalUnitScaleFactor = pnum(gs, "OriginalUnitScaleFactor", unitScale), + frameRate = fps, + } + local _ = nodeSkin + return scene, nil +end + +return Read +end +__FILES["model/fbx/Write"] = function() + +-- model/fbx/Write: Scene -> an FBX 7.4 node tree. Property types follow what Blender's and the FBX SDK's readers check +-- (ids L, ints I, doubles D, KTime L, arrays d / i / l / f); rotations as Euler XYZ degrees. +local Err = __include("core/Err") +local Types = __include("Types") +local Mat4 = __include("codecs/model/Mat4") + +local Write = {} + +type WNode = { name: string, props: { any }, children: { WNode }?, types: string? } + +local TICKS = 46186158000 +local ORIENT_INV = { camera = { 0, 90, 0 }, light = { 90, 0, 0 } } + +local function N(name: string, types: string, props: { any }, children: { WNode }?): WNode + return { name = name, types = types, props = props, children = children } +end +local function arr(t: string, list: { number }): any + local n = #list + local d = buffer.create(n * 8) + for k = 1, n do + buffer.writef64(d, (k - 1) * 8, list[k]) + end + return { array = true, type = t, count = n, data = d } +end +-- P: name, type, label, flags, values +local function P(name: string, ptype: string, label: string, flags: string, vt: string, ...: any): WNode + return { name = "P", types = "SSSS" .. vt, props = { name, ptype, label, flags, ... } } +end +local function Pvec(name: string, ptype: string, label: string, v: { number }): WNode + return P(name, ptype, label, "A", "DDD", v[1], v[2], v[3]) +end +local function Pcolor(name: string, v: { number }): WNode + return P(name, "Color", "", "A", "DDD", v[1] or 0, v[2] or 0, v[3] or 0) +end +local function Pnum(name: string, v: number): WNode + return P(name, "Number", "", "A", "D", v) +end +local function Pint(name: string, v: number): WNode + return P(name, "int", "Integer", "", "I", v) +end +local function Penum(name: string, v: number): WNode + return P(name, "enum", "", "", "I", v) +end +local function Pdouble(name: string, v: number): WNode + return P(name, "double", "Number", "", "D", v) +end +local function Ptime(name: string, v: number): WNode + return P(name, "KTime", "Time", "", "L", v) +end +local function cls(name: string?, class: string): string + return (name or "") .. "\0\1" .. class +end + +local function accessorReader(acc: Types.Accessor?): ((i: number, c: number) -> number)? + if not acc then + return nil + end + return Types.Scene.reader(acc) +end + +local function faces(prim: Types.Primitive): { { number } }? + local pos = prim.attributes.POSITION + if not pos then + return nil + end + local n = pos.count + local idx = accessorReader(prim.indices) + local count = if prim.indices then prim.indices.count else n + local function I(k: number): number + return if idx then idx(k, 0) else k + end + local out: { { number } } = {} + local mode = prim.mode or "triangles" + if mode == "triangles" then + for k = 0, count // 3 - 1 do + table.insert(out, { I(k * 3), I(k * 3 + 1), I(k * 3 + 2) }) + end + elseif mode == "polygons" and prim.faces then + local f = accessorReader(prim.faces) + local p = 0 + if f then + for k = 0, prim.faces.count - 1 do + local sz = f(k, 0) + if p + sz > count then + break + end + local poly = table.create(sz) :: { number } + for q = 0, sz - 1 do + poly[q + 1] = I(p + q) + end + p += sz + table.insert(out, poly) + end + end + elseif mode == "triangle_strip" then + for k = 0, count - 3 do + local a, b, c = I(k), I(k + 1), I(k + 2) + if k % 2 == 1 then + a, b = b, a + end + table.insert(out, { a, b, c }) + end + elseif mode == "triangle_fan" then + for k = 1, count - 2 do + table.insert(out, { I(0), I(k), I(k + 1) }) + end + else + return nil -- points / lines: not written + end + for _, f in out do + for q, v in f do + if v < 0 or v >= n then + f[q] = 0 + end + end + end + return out +end + +function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?) + local flipV = not (opts and opts.flipV == false) + local embed = not (opts and opts.embedTextures == false) + local nextId = 1000000 + local function id(): number + nextId += 1 + return nextId + end + local objects: { WNode } = {} + local conns: { WNode } = {} + local counts: { [string]: number } = {} + local function add(class: string, node: WNode) + table.insert(objects, node) + counts[class] = (counts[class] or 0) + 1 + end + local function OO(child: number, parent: number) + table.insert(conns, N("C", "SLL", { "OO", child, parent })) + end + local function OP(child: number, parent: number, prop: string) + table.insert(conns, N("C", "SLLS", { "OP", child, parent, prop })) + end + local nodes = scene.nodes or {} + + -- ------------------------------------------------------------------------------------------ textures + 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: 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) + local vid, tid = id(), id() + local vchildren = { + N("Type", "S", { "Clip" }), + N("Properties70", "", {}, { P("Path", "KString", "XRefUrl", "", "S", file) }), + N("UseMipMap", "I", { 0 }), + N("Filename", "S", { file }), + N("RelativeFilename", "S", { file }), + } + if embed and tex.data then + table.insert(vchildren, N("Content", "R", { tex.data })) + end + add("Video", N("Video", "LSS", { vid, cls(tname, "Video"), "Clip" }, vchildren)) + local tp = { P("UseMaterial", "bool", "", "", "I", 1) } + local smp = tex.sampler + if smp and smp.wrapS == "clamp" then + table.insert(tp, Penum("WrapModeU", 1)) + end + if smp and smp.wrapT == "clamp" then + table.insert(tp, Penum("WrapModeV", 1)) + end + add("Texture", N("Texture", "LSS", { tid, cls(tname, "Texture"), "" }, { + N("Type", "S", { "TextureVideoClip" }), + N("Version", "I", { 202 }), + N("TextureName", "S", { cls(tname, "Texture") }), + N("Properties70", "", {}, tp), + N("Media", "S", { cls(tname, "Video") }), + N("FileName", "S", { file }), + N("RelativeFilename", "S", { file }), + N("ModelUVTranslation", "DD", { 0, 0 }), + N("ModelUVScaling", "DD", { 1, 1 }), + N("Texture_Alpha_Source", "S", { "None" }), + N("Cropping", "IIII", { 0, 0, 0, 0 }), + })) + OO(vid, tid) + texIds[ti] = tid + end + + -- ------------------------------------------------------------------------------------------ materials + local matIds: { [number]: number } = {} + for mi, m in scene.materials or {} do + local x = m.extras and (m.extras :: any).fbx or {} + local bc = m.baseColor or { 1, 1, 1, 1 } + local alpha = bc[4] or 1 + local rough = math.clamp(m.roughness or 1, 0.02, 1) + local shin = if type(x.shininess) == "number" then x.shininess else 2 / (rough * rough) - 2 + local em = m.emissive or { 0, 0, 0 } + local spec = if type(x.specular) == "table" then x.specular else { 0.2, 0.2, 0.2 } + local pid = id() + local props = { + Pcolor("AmbientColor", if type(x.ambient) == "table" then x.ambient else { 0, 0, 0 }), + Pnum("AmbientFactor", if type(x.ambientFactor) == "number" then x.ambientFactor else 1), + Pcolor("DiffuseColor", { bc[1], bc[2], bc[3] }), + Pnum("DiffuseFactor", 1), + Pcolor("EmissiveColor", em), + Pnum("EmissiveFactor", 1), + Pcolor("SpecularColor", spec), + Pnum("SpecularFactor", if type(x.specularFactor) == "number" then x.specularFactor else 1), + Pnum("Shininess", shin), + Pnum("ShininessExponent", shin), + Pcolor("TransparentColor", { 1, 1, 1 }), + Pnum("TransparencyFactor", 1 - alpha), + Pnum("Opacity", alpha), + Pcolor("ReflectionColor", if type(x.reflection) == "table" then x.reflection else { 0, 0, 0 }), + Pnum("ReflectionFactor", if type(x.reflectionFactor) == "number" then x.reflectionFactor else 0), + } + add("Material", N("Material", "LSS", { pid, cls(m.name or ("Material" .. mi), "Material"), "" }, { + N("Version", "I", { 102 }), + N("ShadingModel", "S", { if type(x.shadingModel) == "string" and x.shadingModel ~= "unknown" then x.shadingModel else "phong" }), + N("MultiLayer", "I", { 0 }), + N("Properties70", "", {}, props), + })) + matIds[mi] = pid + local function link(ref: Types.TextureRef?, prop: string) + local t = ref and texIds[ref.texture] + if t then + OP(t, pid, prop) + end + end + link(m.baseColorTexture, "DiffuseColor") + link(m.normalTexture, "NormalMap") + link(m.emissiveTexture, "EmissiveColor") + local linked = { + [m.baseColorTexture and m.baseColorTexture.texture or -1] = true, + [m.normalTexture and m.normalTexture.texture or -1] = true, + [m.emissiveTexture and m.emissiveTexture.texture or -1] = true, + } + if type(x.textures) == "table" then + local props = {} + for prop in x.textures do + table.insert(props, prop) + end + table.sort(props) + for _, prop in props do + local ti = x.textures[prop] + if type(ti) == "number" and not linked[ti] and texIds[ti] then + linked[ti] = true + OP(texIds[ti], pid, prop) + end + end + end + end + + -- ------------------------------------------------------------------------------------------ models + local modelIds: { [number]: number } = {} + local skip: { [number]: boolean } = {} + local attrHost: { [number]: number } = {} + local parentOf: { [number]: number } = {} + for i, nd in nodes do + for _, c in nd.children or {} do + if parentOf[c] == nil and c ~= i then + parentOf[c] = i + end + end + end + local jointSet: { [number]: boolean } = {} + for _, s in scene.skins or {} do + for _, j in s.joints do + jointSet[j] = true + end + end + for i, nd in nodes do + local o = nd.extras and (nd.extras :: any).fbx and (nd.extras :: any).fbx.orientation + local p = parentOf[i] + if o and p and (nd.camera or nd.light) and #(nd.children or {}) == 0 and not nd.mesh and not nodes[p].camera and not nodes[p].light then + skip[i] = true + attrHost[i] = p + end + end + local worldM: { [number]: Mat4.M4 } = {} + local visiting: { [number]: boolean } = {} + local function world(i: number): Mat4.M4 + if worldM[i] then + return worldM[i] + end + if visiting[i] then + return Mat4.identity() + end + visiting[i] = true + local nd = nodes[i] + 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 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 :: 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 + local function model(name: string, sub: string, t: { number }, r: { number }, s: { number }): number + local mid = id() + add("Model", N("Model", "LSS", { mid, cls(name, "Model"), sub }, { + N("Version", "I", { 232 }), + N("Properties70", "", {}, { + Penum("RotationOrder", 0), + Penum("InheritType", 1), + Pint("DefaultAttributeIndex", 0), + Pvec("Lcl Translation", "Lcl Translation", "", t), + Pvec("Lcl Rotation", "Lcl Rotation", "", r), + Pvec("Lcl Scaling", "Lcl Scaling", "", s), + }), + N("Shading", "C", { true }), + N("Culling", "S", { "CullingOff" }), + })) + return mid + end + local function attribute(nd: Types.Node, mid: number, nodeName: string) + if nd.camera and scene.cameras[nd.camera] then + local c = scene.cameras[nd.camera] + local aid = id() + local aspect = c.aspect or 4 / 3 + local fh = 0.612 + local fw = fh * aspect + local props + if c.type == "orthographic" then + props = { Penum("CameraProjectionType", 1), Pdouble("OrthoZoom", c.ymag or 1), Pdouble("AspectWidth", aspect * 100), Pdouble("AspectHeight", 100), Pdouble("NearPlane", c.znear or 0.1), Pdouble("FarPlane", c.zfar or 1000), Pdouble("FilmWidth", fw), Pdouble("FilmHeight", fh) } + else + local yfov = c.yfov or 0.8 + local hfov = 2 * math.atan(math.tan(yfov / 2) * aspect) + local focal = fw * 25.4 / (2 * math.tan(hfov / 2)) + props = { + Penum("CameraProjectionType", 0), + Penum("ApertureMode", 1), + P("FieldOfView", "FieldOfView", "", "A", "D", hfov * 180 / math.pi), + P("FocalLength", "Number", "", "A", "D", focal), + Pdouble("FilmWidth", fw), + Pdouble("FilmHeight", fh), + Penum("AspectRatioMode", 0), + Pdouble("AspectWidth", aspect * 100), + Pdouble("AspectHeight", 100), + Pdouble("NearPlane", c.znear or 0.1), + Pdouble("FarPlane", c.zfar or 1000), + } + end + add("NodeAttribute", N("NodeAttribute", "LSS", { aid, cls(c.name or nodeName, "NodeAttribute"), "Camera" }, { + N("Properties70", "", {}, props), + N("TypeFlags", "S", { "Camera" }), + N("GeometryVersion", "I", { 124 }), + })) + OO(aid, mid) + elseif nd.light and scene.lights[nd.light] then + local l = scene.lights[nd.light] + local aid = id() + local lt = if l.type == "directional" then 1 elseif l.type == "spot" then 2 else 0 + local props = { + Penum("LightType", lt), + Pcolor("Color", l.color or { 1, 1, 1 }), + Pnum("Intensity", (l.intensity or 1) * 100), + P("CastLight", "bool", "", "", "I", 1), + } + if lt == 2 then + table.insert(props, Pnum("InnerAngle", (l.innerCone or 0) * 360 / math.pi)) + table.insert(props, Pnum("OuterAngle", (l.outerCone or math.pi / 4) * 360 / math.pi)) + end + if l.range then + table.insert(props, P("EnableFarAttenuation", "bool", "", "", "I", 1)) + table.insert(props, Pnum("FarAttenuationEnd", l.range)) + end + add("NodeAttribute", N("NodeAttribute", "LSS", { aid, cls(l.name or nodeName, "NodeAttribute"), "Light" }, { + N("Properties70", "", {}, props), + N("TypeFlags", "S", { "Light" }), + N("GeometryVersion", "I", { 124 }), + })) + OO(aid, mid) + end + end + for i, nd in nodes do + if not skip[i] then + local t, r, s = trs(nd) + 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" + local folded: number? = nil + for c, host in pairs(attrHost) do -- pairs: a sparse integer map (compat __iter takes it for an array) + if host == i then + folded = c + end + end + if not nd.mesh and folded then + sub = if nodes[folded].camera then "Camera" else "Light" + end + local mid = model(nd.name or ("Node" .. i), sub, t, euler, s) + modelIds[i] = mid + if sub == "LimbNode" then + local aid = id() + add("NodeAttribute", N("NodeAttribute", "LSS", { aid, cls(nd.name, "NodeAttribute"), "LimbNode" }, { N("TypeFlags", "S", { "Skeleton" }) })) + OO(aid, mid) + end + if folded then + attribute(nodes[folded], mid, nd.name or "") + end + if nd.camera or nd.light then + -- a glTF-oriented camera / light: an FBX-oriented child model carries it + local kind = if nd.camera then "camera" else "light" + local cmid = model((nd.name or "") .. "_" .. kind, if nd.camera then "Camera" else "Light", { 0, 0, 0 }, ORIENT_INV[kind], { 1, 1, 1 }) + OO(cmid, mid) + attribute(nd, cmid, nd.name or "") + end + end + end + for i in nodes do + local mid = modelIds[i] + if mid then + local p = parentOf[i] + local pm = p and modelIds[p] + OO(mid, pm or 0) + end + end + + -- ------------------------------------------------------------------------------------------ geometry + local geoIds: { [number]: number } = {} + local geoSlots: { [number]: { number } } = {} + local geoVerts: { [number]: { { prim: Types.Primitive, offset: number } } } = {} + local geoChannels: any = {} + local geoCount: { [number]: number } = {} + local function geometry(mi: number): number? + if geoIds[mi] then + return geoIds[mi] + end + local mesh = scene.meshes[mi] + if not mesh then + return nil + end + local V, PVI, NRM, MATS = {}, {}, {}, {} + local UV: { [number]: { number } } = {} + local UVI: { [number]: { number } } = {} + local COL: { [number]: { number } } = {} + local COLI: { [number]: { number } } = {} + local slots: { number } = {} + local slotOf: { [number]: number } = {} + local hasN = false + local nuv, ncol = 0, 0 + for _, prim in mesh.primitives do + for k = 0, 7 do + if prim.attributes["TEXCOORD_" .. k] then + nuv = math.max(nuv, k + 1) + end + if prim.attributes["COLOR_" .. k] then + ncol = math.max(ncol, k + 1) + end + end + if prim.attributes.NORMAL then + hasN = true + end + end + for k = 1, nuv do + UV[k], UVI[k] = {}, {} + end + for k = 1, ncol do + COL[k], COLI[k] = {}, {} + end + local layout = {} + local offset = 0 + for _, prim in mesh.primitives do + local fs = faces(prim) + local pos = prim.attributes.POSITION + local R = accessorReader(pos) + if fs and R and pos then + table.insert(layout, { prim = prim, offset = offset }) + local n = pos.count + for v = 0, n - 1 do + table.insert(V, R(v, 0)) + table.insert(V, R(v, 1)) + table.insert(V, R(v, 2)) + end + local NR = accessorReader(prim.attributes.NORMAL) + if hasN then + for v = 0, n - 1 do + if NR then + table.insert(NRM, NR(v, 0)) + table.insert(NRM, NR(v, 1)) + table.insert(NRM, NR(v, 2)) + else + table.insert(NRM, 0) + table.insert(NRM, 0) + table.insert(NRM, 1) + end + end + end + local uvBase: { number } = {} + for k = 1, nuv do + uvBase[k] = #UV[k] // 2 + local T = accessorReader(prim.attributes["TEXCOORD_" .. (k - 1)]) + for v = 0, n - 1 do + local u, w = 0, 0 + if T then + 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) + end + end + local colBase: { number } = {} + for k = 1, ncol do + colBase[k] = #COL[k] // 4 + local acc = prim.attributes["COLOR_" .. (k - 1)] + local C = accessorReader(acc) + local comps = acc and acc.components or 4 + for v = 0, n - 1 do + table.insert(COL[k], if C then C(v, 0) else 1) + table.insert(COL[k], if C then C(v, 1) else 1) + table.insert(COL[k], if C then C(v, 2) else 1) + table.insert(COL[k], if C and comps >= 4 then C(v, 3) else 1) + end + end + local mat = prim.material or 0 + local slot = slotOf[mat] + if slot == nil then + table.insert(slots, mat) + slot = #slots - 1 + slotOf[mat] = slot + end + for _, f in fs do + for q, v in f do + local cp = v + offset + table.insert(PVI, if q == #f then -cp - 1 else cp) + for k = 1, nuv do + table.insert(UVI[k], uvBase[k] + v) + end + for k = 1, ncol do + table.insert(COLI[k], colBase[k] + v) + end + end + table.insert(MATS, slot) + end + offset += n + end + end + if #PVI == 0 then + return nil + end + local gid = id() + local ch: { WNode } = { + N("Properties70", "", {}, {}), + N("GeometryVersion", "I", { 124 }), + N("Vertices", "", { arr("d", V) }), + N("PolygonVertexIndex", "", { arr("i", PVI) }), + } + local layer0: { WNode } = { N("Version", "I", { 100 }) } + if hasN then + table.insert(ch, N("LayerElementNormal", "I", { 0 }, { + N("Version", "I", { 101 }), + N("Name", "S", { "" }), + N("MappingInformationType", "S", { "ByVertice" }), + N("ReferenceInformationType", "S", { "Direct" }), + N("Normals", "", { arr("d", NRM) }), + })) + table.insert(layer0, N("LayerElement", "", {}, { N("Type", "S", { "LayerElementNormal" }), N("TypedIndex", "I", { 0 }) })) + end + local extraLayers: { WNode } = {} + local uvNames = mesh.extras and (mesh.extras :: any).fbx and (mesh.extras :: any).fbx.uvSets or {} + for k = 1, nuv do + table.insert(ch, N("LayerElementUV", "I", { k - 1 }, { + N("Version", "I", { 101 }), + N("Name", "S", { if type(uvNames[k]) == "string" then uvNames[k] else (if k == 1 then "UVMap" else "UVMap" .. k) }), + N("MappingInformationType", "S", { "ByPolygonVertex" }), + N("ReferenceInformationType", "S", { "IndexToDirect" }), + N("UV", "", { arr("d", UV[k]) }), + N("UVIndex", "", { arr("i", UVI[k]) }), + })) + local le = N("LayerElement", "", {}, { N("Type", "S", { "LayerElementUV" }), N("TypedIndex", "I", { k - 1 }) }) + if k == 1 then + table.insert(layer0, le) + else + table.insert(extraLayers, N("Layer", "I", { k - 1 }, { N("Version", "I", { 100 }), le })) + end + end + for k = 1, ncol do + table.insert(ch, N("LayerElementColor", "I", { k - 1 }, { + N("Version", "I", { 101 }), + N("Name", "S", { "Col" .. (if k > 1 then tostring(k) else "") }), + N("MappingInformationType", "S", { "ByPolygonVertex" }), + N("ReferenceInformationType", "S", { "IndexToDirect" }), + N("Colors", "", { arr("d", COL[k]) }), + N("ColorIndex", "", { arr("i", COLI[k]) }), + })) + if k == 1 then + table.insert(layer0, N("LayerElement", "", {}, { N("Type", "S", { "LayerElementColor" }), N("TypedIndex", "I", { 0 }) })) + end + end + local anyMat = false + for _, m in slots do + if m ~= 0 and matIds[m] then + anyMat = true + end + end + if anyMat then + local allSame = #slots == 1 + table.insert(ch, N("LayerElementMaterial", "I", { 0 }, { + N("Version", "I", { 101 }), + N("Name", "S", { "" }), + N("MappingInformationType", "S", { if allSame then "AllSame" else "ByPolygon" }), + N("ReferenceInformationType", "S", { "IndexToDirect" }), + N("Materials", "", { arr("i", if allSame then { 0 } else MATS) }), + })) + table.insert(layer0, N("LayerElement", "", {}, { N("Type", "S", { "LayerElementMaterial" }), N("TypedIndex", "I", { 0 }) })) + end + table.insert(ch, N("Layer", "I", { 0 }, layer0)) + for _, l in extraLayers do + table.insert(ch, l) + end + add("Geometry", N("Geometry", "LSS", { gid, cls(mesh.name or ("Mesh" .. mi), "Geometry"), "Mesh" }, ch)) + geoIds[mi] = gid + geoSlots[mi] = if anyMat then slots else {} + geoVerts[mi] = layout + geoCount[mi] = offset + local prims = mesh.primitives + local ntargets = 0 + for _, l in layout do + ntargets = math.max(ntargets, if l.prim.targets then #(l.prim.targets :: any) else 0) + end + if ntargets > 0 then + local bsid = id() + add("Deformer", N("Deformer", "LSS", { bsid, cls(mesh.name, "Deformer"), "BlendShape" }, { N("Version", "I", { 100 }) })) + OO(bsid, gid) + local names = mesh.extras and (mesh.extras :: any).targetNames or {} + for t = 1, ntargets do + local IDX, DV, DN = {}, {}, {} + local anyN = false + for _, l in layout do + local tg = l.prim.targets and (l.prim.targets :: any)[t] + if tg and tg.NORMAL then + anyN = true + end + end + for _, l in layout do + local tg = l.prim.targets and (l.prim.targets :: any)[t] + 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) + local nx, ny, nz = 0, 0, 0 + if TN then + nx, ny, nz = TN(v, 0), TN(v, 1), TN(v, 2) + end + if x ~= 0 or y ~= 0 or z ~= 0 or nx ~= 0 or ny ~= 0 or nz ~= 0 then + table.insert(IDX, l.offset + v) + table.insert(DV, x) + table.insert(DV, y) + table.insert(DV, z) + if anyN then + table.insert(DN, nx) + table.insert(DN, ny) + table.insert(DN, nz) + end + end + end + end + end + local tname = if type(names[t]) == "string" then names[t] else ("Target" .. t) + local chid, shid = id(), id() + local w = mesh.weights and mesh.weights[t] or 0 + add("Deformer", N("Deformer", "LSS", { chid, cls(tname, "SubDeformer"), "BlendShapeChannel" }, { + N("Version", "I", { 100 }), + N("DeformPercent", "D", { w * 100 }), + N("FullWeights", "", { arr("d", { 100 }) }), + N("Properties70", "", {}, { Pnum("DeformPercent", w * 100) }), + })) + local shch = { N("Version", "I", { 100 }), N("Indexes", "", { arr("i", IDX) }), N("Vertices", "", { arr("d", DV) }) } + if anyN then + table.insert(shch, N("Normals", "", { arr("d", DN) })) + end + add("Geometry", N("Geometry", "LSS", { shid, cls(tname, "Geometry"), "Shape" }, shch)) + OO(chid, bsid) + OO(shid, chid) + local gc: any = geoChannels + gc[mi] = gc[mi] or {} + gc[mi][t] = chid + end + end + local _ = prims + return gid + end + + local poseNodes: { WNode } = {} + local posed: { [number]: boolean } = {} + local function pose(mid: number, m: Mat4.M4) + if posed[mid] then + return + end + posed[mid] = true + table.insert(poseNodes, N("PoseNode", "", {}, { N("Node", "L", { mid }), N("Matrix", "", { arr("d", m) }) })) + end + local skinned: { [string]: boolean } = {} + for i, nd in nodes do + local mid = modelIds[i] + if nd.mesh and mid then + local gid = geometry(nd.mesh) + if gid then + OO(gid, mid) + for _, m in geoSlots[nd.mesh] do + local pm = matIds[m] + if pm then + OO(pm, mid) + end + end + local skin = nd.skin and scene.skins[nd.skin] + local key = tostring(gid) .. ":" .. tostring(nd.skin) + if skin and not skinned[key] then + skinned[key] = true + local sid = id() + add("Deformer", N("Deformer", "LSS", { sid, cls(nd.name, "Deformer"), "Skin" }, { N("Version", "I", { 101 }), N("Link_DeformAcuracy", "D", { 50 }) })) + OO(sid, gid) + local meshWorld = world(i) + pose(mid, meshWorld) + local ibm = accessorReader(skin.inverseBindMatrices) + local perJoint: { { idx: { number }, w: { number } } } = {} + for j in skin.joints do + perJoint[j] = { idx = {}, w = {} } + end + for _, l in geoVerts[nd.mesh] do + local J = accessorReader(l.prim.attributes.JOINTS_0) + local W = accessorReader(l.prim.attributes.WEIGHTS_0) + if J and W then + for v = 0, l.prim.attributes.POSITION.count - 1 do + for q = 0, 3 do + local j, w = J(v, q), W(v, q) + local pj = perJoint[j + 1] + if w > 0 and pj then + table.insert(pj.idx, l.offset + v) + table.insert(pj.w, w) + end + end + end + end + end + for j, ji in skin.joints do + local jm = modelIds[ji] + if jm then + 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 = 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 }), + N("UserData", "SS", { "", "" }), + N("Indexes", "", { arr("i", perJoint[j].idx) }), + N("Weights", "", { arr("d", perJoint[j].w) }), + N("Transform", "", { arr("d", meshWorld) }), + N("TransformLink", "", { arr("d", link) }), + })) + OO(cid, sid) + OO(jm, cid) + pose(jm, link) + end + end + end + end + end + end + if #poseNodes > 0 then + local pch = { N("Type", "S", { "BindPose" }), N("Version", "I", { 100 }), N("NbPoseNodes", "I", { #poseNodes }) } + for _, pn in poseNodes do + table.insert(pch, pn) + end + add("Pose", N("Pose", "LSS", { id(), cls("BindPose", "Pose"), "BindPose" }, pch)) + end + + -- ------------------------------------------------------------------------------------------ animations + local tmin, tmax = math.huge, -math.huge + local function curveNode(name: string, layer: number, target: number, prop: string, comps: { { number } }, times: { number }, labels: { string }, step: boolean) + local cnid = id() + local p = {} + for k, lab in labels do + table.insert(p, Pnum("d|" .. lab, comps[k][1] or 0)) + end + add("AnimationCurveNode", N("AnimationCurveNode", "LSS", { cnid, cls(name, "AnimCurveNode"), "" }, { N("Properties70", "", {}, p) })) + OO(cnid, layer) + OP(cnid, target, prop) + local ticks = table.create(#times, 0) + for k, t in times do + ticks[k] = math.floor(t * TICKS + 0.5) + end + for k, lab in labels do + local cid = id() + local df = buffer.create(32) + buffer.writeu32(df, 8, 218434821) + local dfa = { array = true, type = "f", count = 4, data = buffer.create(32) } + buffer.writef64(dfa.data, 16, buffer.readf32(df, 8)) + add("AnimationCurve", N("AnimationCurve", "LSS", { cid, cls("", "AnimCurve"), "" }, { + N("Default", "D", { comps[k][1] or 0 }), + N("KeyVer", "I", { 4009 }), + N("KeyTime", "", { arr("l", ticks) }), + N("KeyValueFloat", "", { arr("f", comps[k]) }), + N("KeyAttrFlags", "", { arr("i", { if step then 0x00000002 else 0x00000104 }) }), + N("KeyAttrDataFloat", "", { dfa }), + N("KeyAttrRefCount", "", { arr("i", { #times }) }), + })) + OP(cid, cnid, "d|" .. lab) + end + end + 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: number, astop: number = math.huge, -math.huge + local layerNodes = {} + for _, ch in anim.channels do + local mid = modelIds[ch.node] + local IN = accessorReader(ch.input) + local OUT = accessorReader(ch.output) + local spec = PATH[ch.path] + if IN and OUT and ch.input.count > 0 and mid and (spec or ch.path == "weights") then + local n = ch.input.count + 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])) + end + local cubic = ch.interpolation == "CUBICSPLINE" + local step = ch.interpolation == "STEP" + if spec then + local comps = spec[3] + local function val(k: number, c: number): number + local e = if cubic then k * 3 + 1 else k + if e >= ch.output.count then + return 0 + end + return OUT(e, c) + end + local X, Y, Z = table.create(n, 0), table.create(n, 0), table.create(n, 0) + local prev: { number }? = nil + for k = 0, n - 1 do + local v + if comps == 4 then + local q = { val(k, 0), val(k, 1), val(k, 2), val(k, 3) } + local ql = math.sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3] + q[4] * q[4]) + if ql > 0 then + q = { q[1] / ql, q[2] / ql, q[3] / ql, q[4] / ql } + else + q = { 0, 0, 0, 1 } + end + v = Mat4.eulerXYZ(q) + if prev then + for a = 1, 3 do + while v[a] - prev[a] > 180 do + v[a] -= 360 + end + while v[a] - prev[a] < -180 do + v[a] += 360 + end + end + end + prev = v + else + v = { val(k, 0), val(k, 1), val(k, 2) } + end + X[k + 1], Y[k + 1], Z[k + 1] = v[1], v[2], v[3] + end + table.insert(layerNodes, { spec[1], lid, mid, spec[2], { X, Y, Z }, times, { "X", "Y", "Z" }, step }) + else + local nd = nodes[ch.node] + local gc: any = geoChannels + local chans = nd.mesh and gc[nd.mesh] + if chans then + local nt = #chans + for t = 1, nt do + local vals = table.create(n, 0) + for k = 0, n - 1 do + local e = if cubic then (k * 3 + 1) * nt + (t - 1) else k * nt + (t - 1) + vals[k + 1] = if e < ch.output.count then OUT(e, 0) * 100 else 0 + end + table.insert(layerNodes, { "DeformPercent", lid, chans[t], "DeformPercent", { vals }, times, { "DeformPercent" }, step }) + end + end + end + end + end + if astart > astop then + astart, astop = 0, 0 + end + tmin, tmax = math.min(tmin, astart), math.max(tmax, astop) + add("AnimationStack", N("AnimationStack", "LSS", { stid, cls(if anim.name and anim.name ~= "" then anim.name else ("Animation" .. ai), "AnimStack"), "" }, { + N("Properties70", "", {}, { + Ptime("LocalStart", math.floor(astart * TICKS + 0.5)), + Ptime("LocalStop", math.floor(astop * TICKS + 0.5)), + Ptime("ReferenceStart", math.floor(astart * TICKS + 0.5)), + Ptime("ReferenceStop", math.floor(astop * TICKS + 0.5)), + }), + })) + add("AnimationLayer", N("AnimationLayer", "LSS", { lid, cls("BaseLayer", "AnimLayer"), "" }, { N("Properties70", "", {}, {}) })) + OO(lid, stid) + for _, ln in layerNodes do + curveNode(ln[1], ln[2], ln[3], ln[4], ln[5], ln[6], ln[7], ln[8]) + end + end + if tmin > tmax then + tmin, tmax = 0, 0 + end + + -- ------------------------------------------------------------------------------------------ document + 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 + front, frontSign = 1, -1 + end + if src.format == "fbx" and src.upAxis == up then + upSign = src.upAxisSign or upSign + front, frontSign = src.frontAxis or front, src.frontAxisSign or frontSign + coord, coordSign = src.coordAxis or coord, src.coordAxisSign or coordSign + end + local unitScale = if type(meta.unit) == "number" and meta.unit > 0 then meta.unit * 100 else 1 + local creator = opts and opts.creator or "rosetta" + local defs: { WNode } = { N("Version", "I", { 100 }) } + local total = 1 + local CLASSES = { "Model", "Geometry", "Material", "Texture", "Video", "Deformer", "Pose", "NodeAttribute", "AnimationStack", "AnimationLayer", "AnimationCurveNode", "AnimationCurve" } + for _, c in CLASSES do + total += counts[c] or 0 + end + table.insert(defs, N("Count", "I", { total })) + table.insert(defs, N("ObjectType", "S", { "GlobalSettings" }, { N("Count", "I", { 1 }) })) + for _, c in CLASSES do + if counts[c] then + table.insert(defs, N("ObjectType", "S", { c }, { N("Count", "I", { counts[c] }) })) + end + end + local docId = id() + local root: WNode = { name = "", props = {}, children = { + N("FBXHeaderExtension", "", {}, { + N("FBXHeaderVersion", "I", { 1003 }), + N("FBXVersion", "I", { opts and opts.version or 7400 }), + N("CreationTimeStamp", "", {}, { + N("Version", "I", { 1000 }), N("Year", "I", { 1970 }), N("Month", "I", { 1 }), N("Day", "I", { 1 }), + N("Hour", "I", { 0 }), N("Minute", "I", { 0 }), N("Second", "I", { 0 }), N("Millisecond", "I", { 0 }), + }), + N("Creator", "S", { creator }), + }), + N("FileId", "R", { buffer.fromstring("(\179*\235\182$\204\194\191\200\176*\169+\252\241") }), + N("CreationTime", "S", { "1970-01-01 10:00:00:000" }), + N("Creator", "S", { creator }), + N("GlobalSettings", "", {}, { + N("Version", "I", { 1000 }), + N("Properties70", "", {}, { + Pint("UpAxis", up), Pint("UpAxisSign", upSign), Pint("FrontAxis", front), Pint("FrontAxisSign", frontSign), + Pint("CoordAxis", coord), Pint("CoordAxisSign", coordSign), Pint("OriginalUpAxis", up), Pint("OriginalUpAxisSign", upSign), + Pdouble("UnitScaleFactor", unitScale), Pdouble("OriginalUnitScaleFactor", unitScale), + P("AmbientColor", "ColorRGB", "Color", "", "DDD", 0, 0, 0), + P("DefaultCamera", "KString", "", "", "S", "Producer Perspective"), + Penum("TimeMode", 6), + Penum("TimeProtocol", 2), + Penum("SnapOnFrameMode", 0), + Ptime("TimeSpanStart", math.floor(tmin * TICKS + 0.5)), + Ptime("TimeSpanStop", math.floor(tmax * TICKS + 0.5)), + Pdouble("CustomFrameRate", -1), + }), + }), + N("Documents", "", {}, { + N("Count", "I", { 1 }), + N("Document", "LSS", { docId, "Scene", "Scene" }, { + N("Properties70", "", {}, { P("SourceObject", "object", "", "", ""), P("ActiveAnimStackName", "KString", "", "", "S", "") }), + N("RootNode", "L", { 0 }), + }), + }), + N("References", "", {}, {}), + N("Definitions", "", {}, defs), + N("Objects", "", {}, objects), + N("Connections", "", {}, conns), + N("Takes", "", {}, { N("Current", "S", { "" }) }), + } } + local _ = Err + return root, nil +end + +return Write +end +__FILES["model/fbx/Xform"] = function() + +-- model/fbx/Xform: the FBX transform model (FBX SDK "Computing transformation matrix"): +-- local = T * Roff * Rp * Rpre * R * Rpost^-1 * Rp^-1 * Soff * Sp * S * Sp^-1 +local Mat4 = __include("codecs/model/Mat4") + +local Xform = {} + +-- 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?): Mat4.M4 + return Mat4.euler(x, y, z, ORDERS[order or 0] or "xyz") +end + +type Props = { + T: { number }, R: { number }, S: { number }, + Rpre: { number }, Rpost: { number }, Roff: { number }, Rp: { number }, Soff: { number }, Sp: { number }, + order: number, +} +local function isZero(v: { number }): boolean + return v[1] == 0 and v[2] == 0 and v[3] == 0 +end +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 = Mat4.mul(m, Xform.euler(p.Rpre[1], p.Rpre[2], p.Rpre[3], 0)) + end + m = Mat4.mul(m, Xform.euler(p.R[1], p.R[2], p.R[3], p.order)) + if not isZero(p.Rpost) then + m = Mat4.mul(m, Mat4.transpose3(Xform.euler(p.Rpost[1], p.Rpost[2], p.Rpost[3], 0))) + end + 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 = Mat4.mul(m, Mat4.translation(-p.Sp[1], -p.Sp[2], -p.Sp[3])) + end + return m +end + +return Xform +end +__FILES["model/gltf"] = function() + +-- model/gltf: glTF 2.0 (Khronos specification 2.0.1), .gltf JSON and .glb. Supports: the core spec, KHR_materials_*, +-- KHR_texture_transform, KHR_lights_punctual, KHR_mesh_quantization, KHR_draco_mesh_compression (written uncompressed). +-- Not supported: EXT_meshopt_compression (UNSUPPORTED), KHR_animation_pointer channels (skipped). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Sniff = __include("core/Sniff") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Json = __include("codecs/text/Json") +local Base64 = __include("core/Base64") +local Read = __include("model/gltf/Read") +local Write = __include("model/gltf/Write") + +-- ------------------------------------------------------------------------------------------------ contract +local Gltf = { + name = "gltf", + category = "model", + extensions = { "gltf", "glb" }, + mime = { "model/gltf+json", "model/gltf-binary" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Json", "core/Base64", "core/Sniff", "codecs/model/Draco" }, + caps = { decode = true, encode = true, binary = true, materials = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true, draco = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + resolve: ((uri: string) -> any)?, -- external .bin / image files (buffer or string) + files: { [string]: any }?, + maxBytes: number?, -- default 2^30 bytes of buffers / accessors +} +type EncodeOptions = { + binary: boolean?, -- default: when opts.format is "glb" + format: string?, + external: boolean?, -- default false: data: URIs + files: { [string]: any }?, -- receives <name>.bin and images with external = true + name: string?, + embedImages: boolean?, -- default true (false with external = true) +} + +-- ------------------------------------------------------------------------------------------------ constants +local GLB_MAGIC = 0x46546C67 -- "glTF" +local CHUNK_JSON = 0x4E4F534A +local CHUNK_BIN = 0x004E4942 + +-- ------------------------------------------------------------------------------------------------ sniff +function Gltf.sniff(r: Bytes.Reader): number + if r:peek(4) == "glTF" then + return 1 + end + local head = r:peek(1024) + local s = Sniff.dropBom(head) + if string.find(s, "^%s*{") and string.find(s, "\"asset\"", 1, true) then + return 0.9 + end + if string.find(s, "^%s*{") and (string.find(s, "\"accessors\"", 1, true) or string.find(s, "\"bufferViews\"", 1, true)) then + return 0.6 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function fetcher(opts: DecodeOptions?): Read.Fetch + return function(uri: string): buffer? + if not opts then + return nil + end + local decoded = string.gsub(uri, "%%(%x%x)", function(h: string): string + return string.char(tonumber(h, 16) :: number) + end) + local v: any = nil + if type(opts.files) == "table" then + v = opts.files[uri] or opts.files[decoded] + end + if v == nil and type(opts.resolve) == "function" then + local ok, res = pcall(opts.resolve, uri) + v = if ok then res else nil + end + if type(v) == "string" then + return buffer.fromstring(v) + end + return if type(v) == "buffer" then v else nil + end +end + +local function glb(r: Bytes.Reader): (string?, buffer?, Err.Err?) + local magic, version, length = r:u32le(), r:u32le(), r:u32le() + if r.err then + return nil, nil, r.err + end + if magic ~= GLB_MAGIC then + return nil, nil, Err.new(Err.CORRUPT, "bad GLB magic") + end + if version ~= 2 then + return nil, nil, Err.new(Err.UNSUPPORTED, "GLB version " .. version) + end + if length > r:size() then + return nil, nil, Err.new(Err.TRUNCATED, "the GLB is shorter than its header says", r.base + 8) + end + local json: string? = nil + local bin: buffer? = nil + while r:tell() + 8 <= length do + local clen, ctype = r:u32le(), r:u32le() + if clen > length - r:tell() then + return nil, nil, Err.new(Err.TRUNCATED, "a GLB chunk runs past the end", r.base + r:tell() - 8) + end + if ctype == CHUNK_JSON and json == nil then + json = r:string(clen) + elseif ctype == CHUNK_BIN and bin == nil and json ~= nil then + bin = r:bytes(clen) + else + r:skip(clen) + end + if r.err then + return nil, nil, r.err + end + end + if not json then + return nil, nil, Err.new(Err.CORRUPT, "GLB without a JSON chunk") + end + return json, bin, nil +end + +function Gltf.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local binary = r:peek(4) == "glTF" + local text: string?, bin: buffer? + if binary then + local t, b, err = glb(r) + if not t then + return nil, err + end + text, bin = t, b + else + text = buffer.readstring(r.buf, r.base, r.limit - r.base) + end + local doc, jerr = Json.decode(text :: string) + if doc == nil then + return nil, jerr + end + local scene, err = Read.scene(doc, bin, fetcher(opts), opts) + if not scene then + return nil, err + end + scene.meta.source = { format = "gltf", binary = binary, generator = type(doc.asset) == "table" and doc.asset.generator or nil } + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +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 + return nil, Err.new(Err.ARG, "needs a Scene") + end + local binary = opts and (opts.binary or opts.format == "glb") or false + local external = opts and opts.external == true and type(opts.files) == "table" and not binary + local embedImages = if opts and opts.embedImages ~= nil then opts.embedImages else not external + local out, err = Write.build(scene, { binary = binary, embedImages = embedImages }) + if not out then + return nil, err + end + local doc = out.doc + local base = opts and opts.name and string.gsub(string.match(opts.name, "([^/\\]+)$") or opts.name, "%.[^.]*$", "") or "model" + local files = opts and opts.files + if doc.images then + local n = 0 + for _, im in doc.images do + if type(im.uri) == "string" and string.sub(im.uri, 1, 1) == "\0" then + for _, o in out.images do + if o.name == im.uri then + if string.sub(im.uri, 1, 6) == "\0image" or type(files) ~= "table" then + im.uri = Base64.dataUri(o.data, o.mime or "image/png") + else + n += 1 + local fname = base .. "_" .. n .. "." .. (EXT[o.mime or ""] or "png") + files[fname] = o.data + im.uri = fname + end + break + end + end + elseif type(im.uri) == "string" and type(files) == "table" and not embedImages then + for _, o in out.images do + if o.name == im.uri then + files[im.uri] = o.data + end + end + end + end + end + local binLen = buffer.len(out.bin) + if binLen > 0 then + local b = Types.object() + b.byteLength = binLen + if not binary then + if external then + local fname = base .. ".bin" + b.uri = fname + local ff: any = files + ff[fname] = out.bin + else + b.uri = Base64.dataUri(out.bin, "application/octet-stream") + end + end + doc.buffers = { b } + end + local text, jerr = Json.encode(doc, if binary then nil else { indent = 2 }) + if not text then + return nil, Err.new(Err.ARG, "JSON: " .. tostring(jerr and jerr.message or jerr)) + end + if not binary then + return buffer.fromstring(text :: string), nil + end + local jpad = (4 - #(text :: string) % 4) % 4 + local bpad = (4 - binLen % 4) % 4 + local w = Bytes.writer(12 + 8 + #(text :: string) + jpad + 8 + binLen + bpad) + w:u32le(GLB_MAGIC) + w:u32le(2) + local lenAt = w:tell() + w:u32le(0) + w:u32le(#(text :: string) + jpad) + w:u32le(CHUNK_JSON) + w:string(text :: string) + w:string(string.rep(" ", jpad)) + if binLen > 0 then + w:u32le(binLen + bpad) + w:u32le(CHUNK_BIN) + w:bytes(out.bin) + w:fill(0, bpad) + end + w:setU32le(lenAt, w:tell()) + return w:finish(), nil +end + +return Gltf +end +__FILES["model/gltf/Pack"] = @native function() + + +-- model/gltf/Pack: the byte loops of glTF accessors (gather strided elements, scatter, sparse substitution); callers +-- check every range first. glTF pads matrix columns to 4 bytes. +local Pack = {} + +local bcopy, readu8, readu16, readu32 = buffer.copy, buffer.readu8, buffer.readu16, buffer.readu32 + +@native function Pack.gather(dst: buffer, src: buffer, off: number, count: number, elem: number, stride: number, cols: number, colBytes: number, colStride: number) + if cols == 1 or colBytes == colStride then + if stride == elem then + bcopy(dst, 0, src, off, count * elem) + return + end + for i = 0, count - 1 do + bcopy(dst, i * elem, src, off + i * stride, elem) + end + return + end + for i = 0, count - 1 do + local s = off + i * stride + local d = i * elem + for c = 0, cols - 1 do + bcopy(dst, d + c * colBytes, src, s + c * colStride, colBytes) + end + end +end + +@native function Pack.scatter(dst: buffer, at: number, src: buffer, count: number, elem: number, stride: number, cols: number, colBytes: number, colStride: number) + if cols == 1 or colBytes == colStride then + if stride == elem then + bcopy(dst, at, src, 0, count * elem) + return + end + for i = 0, count - 1 do + bcopy(dst, at + i * stride, src, i * elem, elem) + end + return + end + for i = 0, count - 1 do + local d = at + i * stride + local s = i * elem + for c = 0, cols - 1 do + bcopy(dst, d + c * colStride, src, s + c * colBytes, colBytes) + end + end +end + +@native function Pack.sparse(dst: buffer, count: number, elem: number, idx: buffer, idxOff: number, idxSize: number, values: buffer, valOff: number, n: number): boolean + for k = 0, n - 1 do + local i + if idxSize == 1 then + i = readu8(idx, idxOff + k) + elseif idxSize == 2 then + i = readu16(idx, idxOff + k * 2) + else + i = readu32(idx, idxOff + k * 4) + end + if i >= count then + return false + end + bcopy(dst, i * elem, values, valOff + k * elem, elem) + end + return true +end + +return Pack +end +__FILES["model/gltf/Read"] = function() + +-- model/gltf/Read: a parsed glTF 2.0 JSON document (+ its buffers) -> Scene. glTF extras and unhandled extensions are +-- kept in <object>.extras.gltf = { extras, extensions }. +local Err = __include("core/Err") +local Types = __include("Types") +local Base64 = __include("core/Base64") +local Pack = __include("model/gltf/Pack") +local Draco = __include("codecs/model/Draco") + +local Read = {} + +local COMPONENT: { [number]: { string } } = { + [5120] = { "i8", "snorm8" }, + [5121] = { "u8", "unorm8" }, + [5122] = { "i16", "snorm16" }, + [5123] = { "u16", "unorm16" }, + [5125] = { "u32", "" }, + [5126] = { "f32", "" }, +} +local SIZE = { [5120] = 1, [5121] = 1, [5122] = 2, [5123] = 2, [5125] = 4, [5126] = 4 } +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: { [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 (any other required one -> UNSUPPORTED) +local KNOWN = { + KHR_lights_punctual = true, + KHR_mesh_quantization = true, + KHR_texture_transform = true, + KHR_materials_emissive_strength = true, + KHR_materials_unlit = true, + KHR_materials_clearcoat = true, + KHR_materials_transmission = true, + KHR_materials_volume = true, + KHR_materials_ior = true, + KHR_materials_specular = true, + KHR_materials_sheen = true, + KHR_materials_iridescence = true, + KHR_materials_anisotropy = true, + KHR_materials_dispersion = true, + KHR_materials_diffuse_transmission = true, + KHR_materials_variants = true, + KHR_materials_pbrSpecularGlossiness = true, + KHR_texture_basisu = true, -- the image stays encoded (image/ktx2) + EXT_texture_webp = true, + EXT_texture_avif = true, + KHR_node_visibility = true, + KHR_xmp_json_ld = true, + KHR_draco_mesh_compression = true, +} +Read.KNOWN = KNOWN + +type Fetch = (uri: string) -> buffer? +type View = { buf: buffer, offset: number, length: number, stride: number? } +type Img = { data: buffer?, mime: string?, uri: string?, name: string? } + +local function num(v: any, default: number): number + return if type(v) == "number" then v else default +end +local function int(v: any): number? + return if type(v) == "number" and v == math.floor(v) and v >= 0 then v else nil +end +local function arr(v: any): { any } + return if type(v) == "table" then v else {} +end +local function str(v: any): string? + return if type(v) == "string" then v else nil +end +local function numbers(v: any, n: number): { number }? + if type(v) ~= "table" or #v ~= n then + return nil + end + for i = 1, n do + if type(v[i]) ~= "number" then + return nil + end + end + return table.move(v, 1, n, 1, {} :: { number }) +end + +local function keep(obj: any, handled: { [string]: boolean }?): { [string]: any }? + local extras = obj.extras + local ext: { [string]: any }? = nil + if type(obj.extensions) == "table" then + for k, v in obj.extensions do + if not (handled and handled[k]) then + ext = ext or {} + local e: any = ext + e[k] = v + end + end + end + if extras == nil and ext == nil then + return nil + end + return { gltf = { extras = extras, extensions = ext } } +end + +-- a Draco attribute as its glTF accessor's type: bytes as they are when the layouts agree, else value by value +local DRACO_HANDLED = { KHR_draco_mesh_compression = true } +local DRACO_SIZE = { i8 = 1, u8 = 1, i16 = 2, u16 = 2, i32 = 4, u32 = 4, f32 = 4 } +local DRACO_SAME: { [string]: string } = { i8 = "i8", u8 = "u8", i16 = "i16", u16 = "u16", u32 = "u32", f32 = "f32", snorm8 = "i8", unorm8 = "u8", snorm16 = "i16", unorm16 = "u16", i32 = "i32" } +local DRACO_WRITE: { [string]: (buffer, number, number) -> () } = { i8 = buffer.writei8, u8 = buffer.writeu8, i16 = buffer.writei16, u16 = buffer.writeu16, i32 = buffer.writei32, u32 = buffer.writeu32, f32 = buffer.writef32 } +local NORM_MAX: { [string]: number } = { u8 = 255, i8 = 127, u16 = 65535, i16 = 32767, u32 = 4294967295, i32 = 2147483647 } +local function dracoAccessor(da: Draco.Attribute, acc: Types.Accessor, n: number): Types.Accessor? + if da.components ~= acc.components or not DRACO_SIZE[da.type] then + return nil + end + local out = Types.Scene.accessor(nil, acc.type, acc.components, n) + out.name = acc.name + if DRACO_SAME[acc.type] == da.type then + out.data = da.data + return out + end + local reader = Types.Scene.reader({ data = da.data, type = da.type :: any, components = da.components, count = n }) + local size = Types.COMPONENT_SIZE[acc.type] + local norm = string.match(acc.type, "^[us]norm") ~= nil + local base: string = DRACO_SAME[acc.type] or acc.type + local wr = DRACO_WRITE[base] + local dmax = NORM_MAX[base] or 1 + if not reader or not wr or not size then + return nil + end + local get = reader :: (number, number) -> number + local w = wr :: (buffer, number, number) -> () + local stride = size * acc.components + local function put(v: number, c: number, x: number) + if base ~= "f32" then + if norm then + x = math.clamp(x, if base == "u8" or base == "u16" then 0 else -1, 1) * dmax + end + x = math.floor(x + 0.5) + end + w(out.data, v * stride + c * size, x) + end + local srcMax = if da.normalized then NORM_MAX[da.type] else nil + for v = 0, n - 1 do + for c = 0, da.components - 1 do + local x = get(v, c) + if srcMax then + x = math.max(x / srcMax, -1) + end + put(v, c, x) + end + end + return out +end + +function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Scene?, Err.Err?) + local maxBytes = opts and opts.maxBytes or 2 ^ 30 + if type(doc) ~= "table" then + return nil, Err.new(Err.CORRUPT, "the JSON is not an object") + end + local asset = doc.asset + if type(asset) ~= "table" or type(asset.version) ~= "string" then + return nil, Err.new(Err.CORRUPT, "no asset.version") + end + if string.sub(asset.version, 1, 1) ~= "2" then + return nil, Err.new(Err.UNSUPPORTED, "glTF version " .. asset.version .. " (only 2.x)") + end + for _, e in arr(doc.extensionsRequired) do + if type(e) == "string" and not KNOWN[e] then + return nil, Err.new(Err.UNSUPPORTED, "required extension " .. e) + end + end + local scene = Types.Scene.new() + local buffers: { buffer } = {} + local total = 0 + for i, b in arr(doc.buffers) do + if type(b) ~= "table" then + return nil, Err.new(Err.CORRUPT, "bad buffer " .. (i - 1)) + end + local len = int(b.byteLength) + if not len then + return nil, Err.new(Err.CORRUPT, "buffer " .. (i - 1) .. " without byteLength") + end + total += len + if total > maxBytes then + return nil, Err.new(Err.LIMIT, "buffers over " .. maxBytes .. " bytes") + end + local data: buffer? = nil + local uri = str(b.uri) + if uri == nil then + if i == 1 and bin then + data = bin + else + return nil, Err.new(Err.CORRUPT, "buffer " .. (i - 1) .. " has no uri and no GLB BIN chunk") + end + elseif string.sub(uri, 1, 5) == "data:" then + local d, derr = Base64.decodeDataUri(uri) + if not d then + return nil, Err.new(Err.CORRUPT, "buffer " .. (i - 1) .. ": " .. tostring(derr)) + end + data = d + else + data = fetch(uri) + if not data then + return nil, Err.new(Err.IO, "buffer file " .. uri .. " not found (pass opts.resolve or opts.files)") + end + end + if buffer.len(data :: buffer) < len then + return nil, Err.new(Err.TRUNCATED, "buffer " .. (i - 1) .. " is shorter than its byteLength") + end + buffers[i] = data :: buffer + end + -- buffer views -> { buf, offset, length, stride } + local views: { View } = {} + for i, v in arr(doc.bufferViews) do + if type(v) ~= "table" then + return nil, Err.new(Err.CORRUPT, "bad bufferView " .. (i - 1)) + end + local bi, off, len = int(v.buffer), int(v.byteOffset or 0), int(v.byteLength) + local b = bi and buffers[bi + 1] + if not b or not off or not len or off + len > buffer.len(b) then + return nil, Err.new(Err.CORRUPT, "bufferView " .. (i - 1) .. " out of range") + end + local stride = v.byteStride + if stride ~= nil and (not int(stride) or stride < 4 or stride > 252) then + return nil, Err.new(Err.CORRUPT, "bufferView " .. (i - 1) .. ": bad byteStride") + end + views[i] = { buf = b, offset = off, length = len, stride = stride } + end + local accessors: { Types.Accessor } = {} + for i, a in arr(doc.accessors) do + local label = "accessor " .. (i - 1) + if type(a) ~= "table" then + return nil, Err.new(Err.CORRUPT, "bad " .. label) + end + local ct, count, typ = a.componentType, int(a.count), a.type + local names = COMPONENT[ct] + local comps = TYPE_COMPONENTS[typ] + if not names or not count or not comps then + return nil, Err.new(Err.CORRUPT, label .. ": bad componentType, count or type") + end + local normalized = a.normalized == true + local tname = if normalized then names[2] else names[1] + if tname == "" then + return nil, Err.new(Err.CORRUPT, label .. ": normalized " .. names[1]) + end + local size = SIZE[ct] + local cols = TYPE_COLUMNS[typ] or 1 + local rows = comps // cols + local colBytes = rows * size + local colStride = if cols > 1 then (colBytes + 3) // 4 * 4 else colBytes + local elem = comps * size + local padded = cols * colStride + if count * elem > maxBytes then + return nil, Err.new(Err.LIMIT, label .. " is over " .. maxBytes .. " bytes") + end + local data = buffer.create(count * elem) + local vi = a.bufferView + if vi ~= nil then + local view = int(vi) and views[vi + 1] + if not view then + return nil, Err.new(Err.CORRUPT, label .. ": bad bufferView") + end + local off = int(a.byteOffset or 0) + if not off then + return nil, Err.new(Err.CORRUPT, label .. ": bad byteOffset") + end + local stride = view.stride or padded + if stride < padded and count > 1 then + return nil, Err.new(Err.CORRUPT, label .. ": byteStride smaller than an element") + end + if count > 0 and off + (count - 1) * stride + padded > view.length then + return nil, Err.new(Err.CORRUPT, label .. " runs past its bufferView") + end + if count > 0 then + Pack.gather(data, view.buf, view.offset + off, count, elem, stride, cols, colBytes, colStride) + end + end + local sp = a.sparse + if type(sp) == "table" then + local n = int(sp.count) + local si, sv = sp.indices, sp.values + if not n or type(si) ~= "table" or type(sv) ~= "table" then + return nil, Err.new(Err.CORRUPT, label .. ": bad sparse") + end + local isz = SIZE[si.componentType] + local iv, vv = int(si.bufferView) and views[si.bufferView + 1], int(sv.bufferView) and views[sv.bufferView + 1] + local io, vo = int(si.byteOffset or 0), int(sv.byteOffset or 0) + local okType = si.componentType == 5121 or si.componentType == 5123 or si.componentType == 5125 + if not okType or not isz or not iv or not vv or not io or not vo then + return nil, Err.new(Err.CORRUPT, label .. ": bad sparse indices / values") + end + if io + n * isz > iv.length or vo + n * elem > vv.length then + return nil, Err.new(Err.CORRUPT, label .. ": sparse data runs past its bufferView") + end + -- sparse values are tightly packed (matrices: padded columns) + local vals, valOff = vv.buf, vv.offset + vo + if cols > 1 and colBytes ~= colStride then + vals = buffer.create(n * elem) + Pack.gather(vals, vv.buf, vv.offset + vo, n, elem, padded, cols, colBytes, colStride) + valOff = 0 + end + if not Pack.sparse(data, count, elem, iv.buf, iv.offset + io, isz, vals, valOff, n) then + return nil, Err.new(Err.CORRUPT, label .. ": sparse index out of range") + end + end + local acc = Types.Scene.accessor(data, tname, comps, count) + if cols > 1 then + acc.matrix = true + end + acc.name = str(a.name) + accessors[i] = acc + end + local function accessor(v: any): Types.Accessor? + local k = int(v) + return if k then accessors[k + 1] else nil + end + local images: { Img } = {} + for i, im in arr(doc.images) do + if type(im) ~= "table" then + return nil, Err.new(Err.CORRUPT, "bad image " .. (i - 1)) + end + local img: Img = { mime = str(im.mimeType), name = str(im.name) } + if im.bufferView ~= nil then + local view = int(im.bufferView) and views[im.bufferView + 1] + if not view then + return nil, Err.new(Err.CORRUPT, "image " .. (i - 1) .. ": bad bufferView") + end + local d = buffer.create(view.length) + buffer.copy(d, 0, view.buf, view.offset, view.length) + img.data = d + elseif type(im.uri) == "string" then + if string.sub(im.uri, 1, 5) == "data:" then + local d, mime = Base64.decodeDataUri(im.uri) + if d then + img.data = d + img.mime = img.mime or mime + end + else + img.uri = im.uri + img.data = fetch(im.uri) + if not img.mime then + local ext = string.lower(string.match(im.uri, "%.(%w+)$") or "") + img.mime = if ext == "png" then "image/png" elseif ext == "jpg" or ext == "jpeg" then "image/jpeg" elseif ext == "webp" then "image/webp" elseif ext == "ktx2" then "image/ktx2" else nil + end + end + end + images[i] = img + end + local samplers: { Types.Sampler } = {} + for i, s in arr(doc.samplers) do + if type(s) == "table" then + samplers[i] = { + wrapS = WRAP[s.wrapS] or (if s.wrapS == nil then nil else "repeat") :: any, + wrapT = WRAP[s.wrapT] or (if s.wrapT == nil then nil else "repeat") :: any, + filter = if s.magFilter == 9728 then "nearest" elseif s.magFilter == 9729 then "linear" else nil, + minFilter = MIN_FILTER[s.minFilter], + } + else + samplers[i] = {} + end + end + local TEX_SOURCE_EXT = { "KHR_texture_basisu", "EXT_texture_webp", "EXT_texture_avif" } + for i, t in arr(doc.textures) do + if type(t) ~= "table" then + return nil, Err.new(Err.CORRUPT, "bad texture " .. (i - 1)) + end + local src = t.source + local handled = {} + if type(t.extensions) == "table" then + for _, e in TEX_SOURCE_EXT do + local x = t.extensions[e] + if type(x) == "table" and int(x.source) then + src = x.source + handled[e] = true + break + end + end + end + local img = int(src) and images[src + 1] + local tex: Types.Texture = { name = str(t.name) } + if img then + tex.data, tex.mime, tex.uri = img.data, img.mime, img.uri + tex.name = tex.name or img.name + end + local si = int(t.sampler) + if si and samplers[si + 1] then + tex.sampler = table.clone(samplers[si + 1]) + end + tex.extras = keep(t, handled) + if next(handled) then + -- the fallback image (t.source) and the extension name, for writing the texture back the same way + tex.extras = tex.extras or { gltf = {} } + local g = (tex.extras :: any).gltf + g.sourceExtension = next(handled) + local fb = int(t.source) and images[t.source + 1] + if fb then + g.fallback = { data = fb.data, mime = fb.mime, uri = fb.uri } + end + end + table.insert(scene.textures, tex) + end + local function texRef(info: any): Types.TextureRef? + if type(info) ~= "table" or not int(info.index) or info.index >= #scene.textures then + return nil + end + local r: Types.TextureRef = { texture = info.index + 1, texCoord = int(info.texCoord), scale = if type(info.scale) == "number" then info.scale else nil, strength = if type(info.strength) == "number" then info.strength else nil } + local tt = type(info.extensions) == "table" and info.extensions.KHR_texture_transform + if type(tt) == "table" then + r.transform = { offset = numbers(tt.offset, 2), scale = numbers(tt.scale, 2), rotation = if type(tt.rotation) == "number" then tt.rotation else nil, texCoord = int(tt.texCoord) } + end + return r + end + -- a textureInfo: a table with an index, under a key ending in Texture + local function convertExt(v: any): any + if type(v) ~= "table" then + return v + end + local out = if Types.isObject(v) or next(v) == nil then Types.object() else {} + for k, x in v do + if type(k) == "string" and string.sub(k, -7) == "Texture" and type(x) == "table" and int(x.index) then + out[k] = texRef(x) + else + out[k] = convertExt(x) + end + end + return out + end + for i, m in arr(doc.materials) do + if type(m) ~= "table" then + return nil, Err.new(Err.CORRUPT, "bad material " .. (i - 1)) + end + local mat = Types.Scene.material(str(m.name)) + local pbr = if type(m.pbrMetallicRoughness) == "table" then m.pbrMetallicRoughness else {} + mat.baseColor = numbers(pbr.baseColorFactor, 4) or { 1, 1, 1, 1 } + mat.baseColorTexture = texRef(pbr.baseColorTexture) + mat.metallic = num(pbr.metallicFactor, 1) + mat.roughness = num(pbr.roughnessFactor, 1) + mat.metallicRoughnessTexture = texRef(pbr.metallicRoughnessTexture) + mat.normalTexture = texRef(m.normalTexture) + mat.occlusionTexture = texRef(m.occlusionTexture) + mat.emissive = numbers(m.emissiveFactor, 3) or { 0, 0, 0 } + mat.emissiveTexture = texRef(m.emissiveTexture) + mat.alphaMode = if m.alphaMode == "MASK" then "mask" elseif m.alphaMode == "BLEND" then "blend" else "opaque" + mat.alphaCutoff = num(m.alphaCutoff, 0.5) + mat.doubleSided = m.doubleSided == true + if type(m.extensions) == "table" then + local ext = {} + for k, v in m.extensions do + ext[k] = convertExt(v) + end + mat.extensions = ext + end + local kept = keep(m, mat.extensions and (mat.extensions :: any) or {}) + local pk = keep(pbr, nil) + if pk then + kept = kept or { gltf = {} } + local kk: any = kept + kk.gltf.pbr = pk.gltf + end + mat.extras = kept + table.insert(scene.materials, mat) + end + for i, m in arr(doc.meshes) do + if type(m) ~= "table" then + return nil, Err.new(Err.CORRUPT, "bad mesh " .. (i - 1)) + end + local mesh: Types.Mesh = { name = str(m.name), primitives = {}, weights = if type(m.weights) == "table" then table.clone(m.weights) else nil, extras = keep(m, nil) } + for k, p in arr(m.primitives) do + if type(p) ~= "table" or type(p.attributes) ~= "table" then + return nil, Err.new(Err.CORRUPT, string.format("mesh %d primitive %d: no attributes", i - 1, k - 1)) + end + local pext = if type(p.extensions) == "table" then p.extensions else nil + if pext and pext.EXT_meshopt_compression then + return nil, Err.new(Err.UNSUPPORTED, "meshopt compressed primitives (EXT_meshopt_compression)") + end + -- KHR_draco_mesh_compression: the attributes it lists and the indices come from the Draco data + local dext = pext and pext.KHR_draco_mesh_compression + local draco: Draco.Geometry? = nil + local dmap: { [string]: number } = {} + if dext ~= nil then + local view = type(dext) == "table" and int(dext.bufferView) and views[dext.bufferView + 1] + if not view then + return nil, Err.new(Err.CORRUPT, string.format("mesh %d primitive %d: draco: bad bufferView", i - 1, k - 1)) + end + local g, derr = Draco.decode(view.buf, view.offset, view.length, { maxPoints = maxBytes // 4, maxFaces = maxBytes // 12 }) + if not g then + local e = derr :: Err.Err + return nil, Err.new(e.code, string.format("mesh %d primitive %d: %s", i - 1, k - 1, e.message)) + end + draco = g + for name, id in (if type(dext.attributes) == "table" then dext.attributes else {}) do + if type(name) == "string" and int(id) then + dmap[name] = id + end + end + end + local attrs: { [string]: Types.Accessor } = {} + local count = -1 + for name, ai in p.attributes do + local a = accessor(ai) + if a and draco and dmap[name] then + local da = Draco.attribute(draco, dmap[name]) + a = if da then dracoAccessor(da, a, draco.numPoints) else nil + end + if not a then + return nil, Err.new(Err.CORRUPT, string.format("mesh %d: attribute %s: bad accessor", i - 1, tostring(name))) + end + if count >= 0 and a.count ~= count then + return nil, Err.new(Err.CORRUPT, string.format("mesh %d: attributes with different counts", i - 1)) + end + count = a.count + attrs[name] = a + end + local mode = MODES[if p.mode == nil then 4 else p.mode] + if not mode then + return nil, Err.new(Err.CORRUPT, "bad primitive mode") + end + local prim: Types.Primitive = { attributes = attrs, mode = mode :: any, material = if int(p.material) and p.material < #scene.materials then p.material + 1 else nil } + if draco then + if draco.kind == "mesh" then + prim.indices = Types.Scene.accessor(draco.indices, "u32", 1, draco.numFaces * 3) + prim.mode = "triangles" + else + prim.mode = "points" + end + elseif p.indices ~= nil then + local ind = accessor(p.indices) + if not ind or ind.components ~= 1 or (ind.type ~= "u8" and ind.type ~= "u16" and ind.type ~= "u32") then + return nil, Err.new(Err.CORRUPT, "bad indices accessor") + end + 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 :: Types.Accessor + end + if type(p.targets) == "table" then + local targets = {} + for ti, t in p.targets do + local tt = {} + for name, ai in (if type(t) == "table" then t else {}) do + local a = accessor(ai) + if not a or a.count ~= count then + return nil, Err.new(Err.CORRUPT, "bad morph target accessor") + end + tt[name] = a + end + targets[ti] = tt + end + prim.targets = targets + end + prim.extras = keep(p, DRACO_HANDLED) + table.insert(mesh.primitives, prim) + end + table.insert(scene.meshes, mesh) + end + for _, c in arr(doc.cameras) do + if type(c) ~= "table" then + return nil, Err.new(Err.CORRUPT, "bad camera") + 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" :: "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" :: "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 + for _, l in arr(lp and lp.lights) do + if type(l) == "table" then + local spot = if type(l.spot) == "table" then l.spot else {} + table.insert(scene.lights, { + name = str(l.name), + type = if l.type == "spot" or l.type == "point" then l.type else "directional", + color = numbers(l.color, 3) or { 1, 1, 1 }, + intensity = num(l.intensity, 1), + range = if type(l.range) == "number" then l.range else nil, + innerCone = if l.type == "spot" then num(spot.innerConeAngle, 0) else nil, + outerCone = if l.type == "spot" then num(spot.outerConeAngle, math.pi / 4) else nil, + }) + end + end + local nodes = arr(doc.nodes) + for i, n in nodes do + if type(n) ~= "table" then + return nil, Err.new(Err.CORRUPT, "bad node " .. (i - 1)) + end + local node: Types.Node = { name = str(n.name), children = {} } + for _, c in arr(n.children) do + if not int(c) or c >= #nodes then + return nil, Err.new(Err.CORRUPT, "node " .. (i - 1) .. ": bad child") + end + table.insert(node.children, c + 1) + end + if int(n.mesh) and n.mesh < #scene.meshes then + node.mesh = n.mesh + 1 + end + if int(n.camera) and n.camera < #scene.cameras then + node.camera = n.camera + 1 + end + if int(n.skin) and n.skin < #arr(doc.skins) then + node.skin = n.skin + 1 + end + node.matrix = numbers(n.matrix, 16) + node.translation = numbers(n.translation, 3) + node.rotation = numbers(n.rotation, 4) + node.scale = numbers(n.scale, 3) + node.weights = if type(n.weights) == "table" then table.clone(n.weights) else nil + local handled = {} + local le = type(n.extensions) == "table" and n.extensions.KHR_lights_punctual + if type(le) == "table" and int(le.light) and le.light < #scene.lights then + node.light = le.light + 1 + handled.KHR_lights_punctual = true + end + node.extras = keep(n, handled) + scene.nodes[i] = node + end + -- a node may have one parent only, and no cycles + local parent: { [number]: number } = {} + for i, node in scene.nodes do + for _, c in node.children do + if parent[c] or c == i then + return nil, Err.new(Err.CORRUPT, "node " .. (c - 1) .. " has two parents or is its own child") + end + parent[c] = i + end + end + for i in scene.nodes do + local seen, p = 0, parent[i] + while p do + seen += 1 + if seen > #scene.nodes then + return nil, Err.new(Err.CORRUPT, "the node hierarchy has a cycle") + end + p = parent[p] + end + end + for _, s in arr(doc.skins) do + if type(s) ~= "table" then + return nil, Err.new(Err.CORRUPT, "bad skin") + end + local joints = {} + for _, j in arr(s.joints) do + if not int(j) or j >= #scene.nodes then + return nil, Err.new(Err.CORRUPT, "skin: bad joint") + end + table.insert(joints, j + 1) + end + table.insert(scene.skins, { name = str(s.name), joints = joints, inverseBindMatrices = accessor(s.inverseBindMatrices), skeleton = if int(s.skeleton) and s.skeleton < #scene.nodes then s.skeleton + 1 else nil }) + end + for _, a in arr(doc.animations) do + if type(a) ~= "table" then + return nil, Err.new(Err.CORRUPT, "bad animation") + end + local anim: Types.Animation = { name = str(a.name), channels = {} } + local samplersA = arr(a.samplers) + local skipped = {} + for _, c in arr(a.channels) do + local s = type(c) == "table" and int(c.sampler) and samplersA[c.sampler + 1] + local target = type(c) == "table" and c.target + if not s or type(target) ~= "table" then + return nil, Err.new(Err.CORRUPT, "animation: bad channel") + end + local input, output = accessor(s.input), accessor(s.output) + if not input or not output then + return nil, Err.new(Err.CORRUPT, "animation: bad sampler accessors") + end + local path = target.path + if int(target.node) and target.node < #scene.nodes and (path == "translation" or path == "rotation" or path == "scale" or path == "weights") then + table.insert(anim.channels, { + node = target.node + 1, + path = path, + input = input, + output = output, + interpolation = if s.interpolation == "STEP" or s.interpolation == "CUBICSPLINE" then s.interpolation else "LINEAR", + }) + else + table.insert(skipped, c) -- KHR_animation_pointer and friends + end + end + if #skipped > 0 then + local aa: any = anim + aa.extras = { gltf = { skippedChannels = #skipped } } + end + table.insert(scene.animations, anim) + end + local scenes = arr(doc.scenes) + local list = {} + for _, s in scenes do + local roots = {} + for _, n in arr(type(s) == "table" and s.nodes) do + if int(n) and n < #scene.nodes and not parent[n + 1] then + table.insert(roots, n + 1) + end + end + table.insert(list, { name = type(s) == "table" and str(s.name) or nil, nodes = roots, extras = if type(s) == "table" then keep(s, nil) else nil }) + end + local which = int(doc.scene) or 0 + if list[which + 1] then + scene.roots = list[which + 1].nodes + elseif #list == 0 then + for i in scene.nodes do + if not parent[i] then + table.insert(scene.roots, i) + end + end + end + local rootExt = nil + if type(doc.extensions) == "table" then + for k, v in doc.extensions do + if k ~= "KHR_lights_punctual" then + rootExt = rootExt or {} + rootExt[k] = v + end + end + end + scene.meta.up = "y" + scene.meta.unit = 1 + scene.meta.gltf = { + asset = asset, + scenes = list, + scene = if doc.scene ~= nil then which + 1 else nil, + extensionsUsed = doc.extensionsUsed, + extensionsRequired = doc.extensionsRequired, + extensions = rootExt, + extras = doc.extras, + } + return scene, nil +end + +return Read +end +__FILES["model/gltf/Write"] = function() + +-- model/gltf/Write: Scene -> a glTF 2.0 JSON document + one binary buffer. Vertex attributes 4-byte aligned per +-- element, matrix columns padded, f64 / i32 data converted (glTF has neither), POSITION and animation input min / max. +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Pack = __include("model/gltf/Pack") + +local Write = {} + +local object = Types.object +local CT = { i8 = 5120, u8 = 5121, i16 = 5122, u16 = 5123, u32 = 5125, f32 = 5126, unorm8 = 5121, unorm16 = 5123, snorm8 = 5120, snorm16 = 5122 } +local SIZE = Types.COMPONENT_SIZE +local NORMALIZED = { unorm8 = true, unorm16 = true, snorm8 = true, snorm16 = true } +local MODES = { points = 0, lines = 1, line_loop = 2, line_strip = 3, triangles = 4, triangle_strip = 5, triangle_fan = 6 } +local WRAP = { clamp = 33071, mirror = 33648, ["repeat"] = 10497 } +local MIN_FILTER = { nearest = 9728, linear = 9729, nearest_mipmap_nearest = 9984, linear_mipmap_nearest = 9985, nearest_mipmap_linear = 9986, linear_mipmap_linear = 9987 } +-- attribute types the core spec allows (others need KHR_mesh_quantization) +local CORE = { + POSITION = { f32 = true }, + NORMAL = { f32 = true }, + TANGENT = { f32 = true }, + TEXCOORD = { f32 = true, unorm8 = true, unorm16 = true }, + COLOR = { f32 = true, unorm8 = true, unorm16 = true }, + JOINTS = { u8 = true, u16 = true }, + WEIGHTS = { f32 = true, unorm8 = true, unorm16 = true }, +} + +type Options = { embedImages: boolean?, binary: boolean? } +type Out = { doc: any, bin: buffer, images: { { data: buffer, mime: string?, name: string } } } + +local function convert(acc: Types.Accessor, to: string): Types.Accessor + local get = Types.Scene.reader(acc) :: (number, number) -> number + local out = Types.Scene.accessor(nil, to, acc.components, acc.count) + local w = if to == "f32" then buffer.writef32 else buffer.writeu32 + local size = SIZE[to] + for i = 0, acc.count - 1 do + for c = 0, acc.components - 1 do + local v = get(i, c) + if to == "u32" then + v = math.clamp(math.floor(v), 0, 4294967295) + end + w(out.data, (i * acc.components + c) * size, v) + end + end + out.matrix = acc.matrix + out.name = acc.name + return out +end + +local function checkAcc(acc: any, label: string): Err.Err? + if type(acc) ~= "table" or type(acc.data) ~= "buffer" or not SIZE[acc.type] or type(acc.count) ~= "number" or type(acc.components) ~= "number" then + return Err.new(Err.ARG, label .. ": not an accessor") + end + if acc.components < 1 or acc.components > 16 or buffer.len(acc.data) < acc.count * acc.components * SIZE[acc.type] then + return Err.new(Err.ARG, label .. ": data is smaller than count x components") + end + return nil +end + +function Write.build(scene: Types.Scene, opts: Options?): (Out?, Err.Err?) + local binary = opts and opts.binary or false + local embedImages = not (opts and opts.embedImages == false) + local doc: { [string]: any } = object() + local used: { [string]: boolean } = {} + local required: { [string]: boolean } = {} + local bin = Bytes.writer(65536) + local views: { any } = {} + local accessors: { any } = {} + local accIndex: { [any]: number } = {} + local failure: Err.Err? = nil + + local function view(data: buffer, length: number, target: number?, stride: number?): number + local pad = (4 - bin:tell() % 4) % 4 + bin:fill(0, pad) + local v = object() + v.buffer = 0 + v.byteOffset = bin:tell() + v.byteLength = length + v.target = target + v.byteStride = stride + bin:bytes(data, 0, length) + table.insert(views, v) + return #views - 1 + end + + local function accessor(acc: Types.Accessor, usage: string, attribute: string?): number + local known = accIndex[acc] + if known then + return known + end + local err = checkAcc(acc, attribute or usage) + if err then + failure = failure or err + return 0 + end + local a = acc + if usage == "index" then + if a.type ~= "u8" and a.type ~= "u16" and a.type ~= "u32" then + a = convert(a, "u32") + end + elseif a.type == "f64" or a.type == "i32" or a.type == "u32" and usage ~= "index" and attribute ~= nil then + a = convert(a, "f32") + end + if attribute then + local kind = string.match(attribute, "^([A-Z]+)_%d+$") or attribute + local core = CORE[kind] + if core and not core[a.type] then + used.KHR_mesh_quantization = true + required.KHR_mesh_quantization = true + end + end + local size = SIZE[a.type] + local comps = a.components + local isMat = a.matrix == true and (comps == 4 or comps == 9 or comps == 16) + local cols = if isMat then math.sqrt(comps) else 1 + local colBytes = (comps // cols) * size + local colStride = if cols > 1 then (colBytes + 3) // 4 * 4 else colBytes + local elem = comps * size + local padded = cols * colStride + local stride = padded + local byteStride: number? = nil + if usage == "vertex" and padded % 4 ~= 0 then + stride = (padded + 3) // 4 * 4 + byteStride = stride + end + local data = a.data + local length = a.count * stride + if stride ~= elem then + data = buffer.create(length) + Pack.scatter(data, 0, a.data, a.count, elem, stride, cols, colBytes, colStride) + end + local g = object() + g.bufferView = view(data, length, if usage == "vertex" then 34962 elseif usage == "index" then 34963 else nil, byteStride) + g.componentType = CT[a.type] + g.normalized = if NORMALIZED[a.type] then true else nil + g.count = a.count + g.type = if isMat then ({ [4] = "MAT2", [9] = "MAT3", [16] = "MAT4" })[comps] else ({ "SCALAR", "VEC2", "VEC3", "VEC4" })[comps] + g.name = acc.name + if not g.type then + failure = failure or Err.new(Err.ARG, (attribute or usage) .. ": " .. comps .. " components is not a glTF type") + return 0 + end + if attribute == "POSITION" or usage == "input" then + local raw = Types.Scene.accessor(a.data, if a.type == "unorm8" then "u8" elseif a.type == "unorm16" then "u16" elseif a.type == "snorm8" then "i8" elseif a.type == "snorm16" then "i16" else a.type, comps, a.count) + local get = Types.Scene.reader(raw) :: (number, number) -> number + local lo, hi = table.create(comps, math.huge), table.create(comps, -math.huge) + for i = 0, a.count - 1 do + for c = 1, comps do + local v = get(i, c - 1) + if v < lo[c] then + lo[c] = v + end + if v > hi[c] then + hi[c] = v + end + end + end + if a.count > 0 then + g.min, g.max = lo, hi + end + end + table.insert(accessors, g) + local index = #accessors - 1 + accIndex[acc] = index + return index + end + + local function restore(g: any, extras: any) + local saved = type(extras) == "table" and extras.gltf + if type(saved) ~= "table" then + return + end + if saved.extras ~= nil then + g.extras = saved.extras + end + if type(saved.extensions) == "table" then + g.extensions = g.extensions or object() + for k, v in saved.extensions do + if g.extensions[k] == nil then + g.extensions[k] = v + used[k] = true + end + end + end + end + + local images: { any } = {} + local imageOut: { { data: buffer, mime: string?, name: string } } = {} + local imageIndex: { [any]: number } = {} + local function image(data: buffer?, mime: string?, uri: string?, name: string?): number? + local key: any = data or uri + if key == nil then + return nil + end + if imageIndex[key] then + return imageIndex[key] + end + local im = object() + im.name = name + if data then + if binary then + im.bufferView = view(data, buffer.len(data), nil, nil) + im.mimeType = mime or "image/png" + elseif embedImages then + im.uri = "\0image" .. (#images + 1) -- replaced by a data: URI / a file name by the caller + im.mimeType = mime + table.insert(imageOut, { data = data, mime = mime, name = im.uri }) + else + im.uri = uri or ("\0file" .. (#images + 1)) + im.mimeType = mime + table.insert(imageOut, { data = data, mime = mime, name = im.uri }) + end + else + im.uri = uri + im.mimeType = mime + end + table.insert(images, im) + imageIndex[key] = #images - 1 + return #images - 1 + end + local samplers: { any } = {} + local samplerIndex: { [string]: number } = {} + local function sampler(s: Types.Sampler?): number? + if type(s) ~= "table" then + return nil + end + local g = object() + g.wrapS = if s.wrapS then WRAP[s.wrapS] else nil + g.wrapT = if s.wrapT then WRAP[s.wrapT] else nil + g.magFilter = if s.filter == "nearest" then 9728 elseif s.filter == "linear" then 9729 else nil + g.minFilter = if s.minFilter then MIN_FILTER[s.minFilter] else nil + local key = string.format("%s/%s/%s/%s", tostring(g.wrapS), tostring(g.wrapT), tostring(g.magFilter), tostring(g.minFilter)) + if samplerIndex[key] == nil then + table.insert(samplers, g) + samplerIndex[key] = #samplers - 1 + end + return samplerIndex[key] + end + local textures: { any } = {} + for i, t in scene.textures or {} do + if type(t) ~= "table" then + return nil, Err.new(Err.ARG, "texture " .. i .. ": not a table") + end + local g = object() + g.name = t.name + g.sampler = sampler(t.sampler) + local saved = type(t.extras) == "table" and type(t.extras.gltf) == "table" and t.extras.gltf or nil + local srcExt = saved and saved.sourceExtension + local img = image(t.data, t.mime, t.uri, t.name) + if srcExt and img then + g.extensions = object() + local e = object() + e.source = img + g.extensions[srcExt] = e + used[srcExt] = true + local fb = saved.fallback + if type(fb) == "table" then + g.source = image(fb.data, fb.mime, fb.uri, nil) + end + if g.source == nil then + required[srcExt] = true + end + else + g.source = img + end + restore(g, t.extras) + table.insert(textures, g) + end + local function texInfo(r: any, kind: string?): any + if type(r) ~= "table" or type(r.texture) ~= "number" or not textures[r.texture] then + return nil + end + local g = object() + g.index = r.texture - 1 + if r.texCoord and r.texCoord ~= 0 then + g.texCoord = r.texCoord + end + if kind == "normal" and r.scale ~= nil and r.scale ~= 1 then + g.scale = r.scale + end + if kind == "occlusion" and r.strength ~= nil and r.strength ~= 1 then + g.strength = r.strength + end + if type(r.transform) == "table" then + local tt = object() + tt.offset = r.transform.offset + tt.scale = r.transform.scale + tt.rotation = r.transform.rotation + tt.texCoord = r.transform.texCoord + g.extensions = object() + g.extensions.KHR_texture_transform = tt + used.KHR_texture_transform = true + end + return g + end + local function extValue(v: any, key: string?): any + if type(v) ~= "table" then + return v + end + if key and string.sub(key, -7) == "Texture" and type(v.texture) == "number" then + return texInfo(v, if key == "normalTexture" or key == "clearcoatNormalTexture" then "normal" else nil) + end + local out = if Types.isObject(v) or next(v) == nil then object() else {} + for k, x in v do + out[k] = extValue(x, if type(k) == "string" then k else nil) + end + return out + end + local materials: { any } = {} + for i, m in scene.materials or {} do + if type(m) ~= "table" then + return nil, Err.new(Err.ARG, "material " .. i .. ": not a table") + end + local g = object() + g.name = m.name + local pbr = object() + local bc = m.baseColor or { 1, 1, 1, 1 } + if bc[1] ~= 1 or bc[2] ~= 1 or bc[3] ~= 1 or (bc[4] or 1) ~= 1 then + pbr.baseColorFactor = { bc[1], bc[2], bc[3], bc[4] or 1 } + end + pbr.baseColorTexture = texInfo(m.baseColorTexture) + if m.metallic ~= nil and m.metallic ~= 1 then + pbr.metallicFactor = m.metallic + end + if m.roughness ~= nil and m.roughness ~= 1 then + pbr.roughnessFactor = m.roughness + end + pbr.metallicRoughnessTexture = texInfo(m.metallicRoughnessTexture) + local saved = type(m.extras) == "table" and type(m.extras.gltf) == "table" and m.extras.gltf or nil + if saved and saved.pbr then + restore(pbr, { gltf = saved.pbr }) + end + g.pbrMetallicRoughness = pbr + g.normalTexture = texInfo(m.normalTexture, "normal") + g.occlusionTexture = texInfo(m.occlusionTexture, "occlusion") + g.emissiveTexture = texInfo(m.emissiveTexture) + local em = m.emissive or { 0, 0, 0 } + if em[1] ~= 0 or em[2] ~= 0 or em[3] ~= 0 then + g.emissiveFactor = { em[1], em[2], em[3] } + end + if m.alphaMode == "mask" then + g.alphaMode = "MASK" + if m.alphaCutoff ~= nil and m.alphaCutoff ~= 0.5 then + g.alphaCutoff = m.alphaCutoff + end + elseif m.alphaMode == "blend" then + g.alphaMode = "BLEND" + end + if m.doubleSided then + g.doubleSided = true + end + if type(m.extensions) == "table" then + g.extensions = object() + for k, v in m.extensions do + g.extensions[k] = extValue(v, nil) + used[k] = true + end + end + restore(g, m.extras) + table.insert(materials, g) + end + local meshes: { any } = {} + for i, mesh in scene.meshes or {} do + if type(mesh) ~= "table" or type(mesh.primitives) ~= "table" then + return nil, Err.new(Err.ARG, "mesh " .. i .. ": no primitives") + end + local g = object() + g.name = mesh.name + g.primitives = {} + for k, p in mesh.primitives do + if type(p) ~= "table" or type(p.attributes) ~= "table" or not p.attributes.POSITION then + return nil, Err.new(Err.ARG, string.format("mesh %d primitive %d: no POSITION", i, k)) + end + local gp = object() + gp.attributes = object() + local names: { string } = {} + for name in p.attributes do + table.insert(names, name) + end + table.sort(names) + for _, name in names do + gp.attributes[name] = accessor(p.attributes[name], "vertex", name) + end + local mode = p.mode or "triangles" + local indices = p.indices + if mode == "polygons" then + local faces = p.faces + local getf = faces and Types.Scene.reader(faces) + local n = if indices then indices.count else p.attributes.POSITION.count + local geti = if indices then Types.Scene.reader(indices) else nil + if not faces or not getf or (indices and not geti) then + return nil, Err.new(Err.ARG, "polygons without faces") + end + local list = {} + local at = 0 + for f = 0, faces.count - 1 do + local c = getf(f, 0) + if at + c > n then + return nil, Err.new(Err.ARG, "faces run past the indices") + end + for a = 1, c - 2 do + for _, j in { at, at + a, at + a + 1 } do + table.insert(list, if geti then geti(j, 0) else j) + end + end + at += c + end + local ib = buffer.create(#list * 4) + for q, v in list do + buffer.writeu32(ib, (q - 1) * 4, v) + end + indices = Types.Scene.accessor(ib, "u32", 1, #list) + mode = "triangles" + end + if MODES[mode] == nil then + return nil, Err.new(Err.ARG, "unknown primitive mode " .. tostring(mode)) + end + if indices then + gp.indices = accessor(indices, "index", nil) + end + if mode ~= "triangles" then + gp.mode = MODES[mode] + end + if type(p.material) == "number" and materials[p.material] then + gp.material = p.material - 1 + end + if type(p.targets) == "table" and #p.targets > 0 then + gp.targets = {} + for _, t in p.targets do + local gt = object() + local tn = {} + for name in t do + table.insert(tn, name) + end + table.sort(tn) + for _, name in tn do + gt[name] = accessor(t[name], "vertex", nil) + end + table.insert(gp.targets, gt) + end + end + restore(gp, p.extras) + table.insert(g.primitives, gp) + end + g.weights = mesh.weights + restore(g, mesh.extras) + table.insert(meshes, g) + end + local cameras: { any } = {} + for _, c in scene.cameras or {} do + local g = object() + g.name = c.name + g.type = c.type + local p = object() + if c.type == "orthographic" then + p.xmag, p.ymag, p.znear, p.zfar = c.xmag or 1, c.ymag or 1, c.znear or 0, c.zfar or 100 + g.orthographic = p + else + g.type = "perspective" + p.yfov, p.aspectRatio, p.znear, p.zfar = c.yfov or 0.8, c.aspect, c.znear or 0.01, c.zfar + g.perspective = p + end + table.insert(cameras, g) + end + local lights: { any } = {} + for _, l in scene.lights or {} do + local g = object() + g.name = l.name + g.type = l.type + if l.color and (l.color[1] ~= 1 or l.color[2] ~= 1 or l.color[3] ~= 1) then + g.color = { l.color[1], l.color[2], l.color[3] } + end + if l.intensity ~= nil and l.intensity ~= 1 then + g.intensity = l.intensity + end + if l.type ~= "directional" then + g.range = l.range + end + if l.type == "spot" then + local s = object() + s.innerConeAngle = if l.innerCone and l.innerCone ~= 0 then l.innerCone else nil + s.outerConeAngle = if l.outerCone and math.abs(l.outerCone - math.pi / 4) > 1e-12 then l.outerCone else nil + g.spot = s + end + table.insert(lights, g) + end + local nodes: { any } = {} + local nodeCount = #(scene.nodes or {}) + for i, n in scene.nodes or {} do + if type(n) ~= "table" then + return nil, Err.new(Err.ARG, "node " .. i .. ": not a table") + end + local g = object() + g.name = n.name + if n.children and #n.children > 0 then + g.children = {} + for _, c in n.children do + if type(c) ~= "number" or c < 1 or c > nodeCount then + return nil, Err.new(Err.ARG, "node " .. i .. ": bad child") + end + table.insert(g.children, c - 1) + end + end + if n.mesh and meshes[n.mesh] then + g.mesh = n.mesh - 1 + end + if n.camera and cameras[n.camera] then + g.camera = n.camera - 1 + end + if n.skin and scene.skins[n.skin] then + g.skin = n.skin - 1 + end + if n.matrix then + local ident = true + for k = 1, 16 do + if n.matrix[k] ~= Types.Scene.IDENTITY[k] then + ident = false + end + end + if not ident then + g.matrix = n.matrix + end + else + g.translation, g.rotation, g.scale = n.translation, n.rotation, n.scale + end + g.weights = n.weights + if n.light and lights[n.light] then + g.extensions = object() + local le = object() + le.light = n.light - 1 + g.extensions.KHR_lights_punctual = le + used.KHR_lights_punctual = true + end + restore(g, n.extras) + table.insert(nodes, g) + end + local skins: { any } = {} + for _, s in scene.skins or {} do + local g = object() + g.name = s.name + g.joints = {} + for _, j in s.joints or {} do + table.insert(g.joints, j - 1) + end + if s.inverseBindMatrices then + local ibm = s.inverseBindMatrices + if ibm.matrix == nil and ibm.components == 16 then + ibm.matrix = true + end + g.inverseBindMatrices = accessor(ibm, "other", nil) + end + if s.skeleton then + g.skeleton = s.skeleton - 1 + end + table.insert(skins, g) + end + local animations: { any } = {} + for _, a in scene.animations or {} do + local g = object() + g.name = a.name + g.channels, g.samplers = {}, {} + local samplerOf: { [string]: number } = {} + for _, c in a.channels or {} do + local input = accessor(c.input, "input", nil) + local output = accessor(c.output, "other", nil) + local key = input .. "/" .. output .. "/" .. tostring(c.interpolation) + if samplerOf[key] == nil then + local s = object() + s.input, s.output = input, output + if c.interpolation and c.interpolation ~= "LINEAR" then + s.interpolation = c.interpolation + end + table.insert(g.samplers, s) + samplerOf[key] = #g.samplers - 1 + end + local ch = object() + ch.sampler = samplerOf[key] + ch.target = object() + ch.target.node = c.node - 1 + ch.target.path = c.path + table.insert(g.channels, ch) + end + table.insert(animations, g) + end + if failure then + return nil, failure + end + -- scenes: the original list (meta.gltf.scenes), else the roots + 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 + for _, s in mg.scenes do + local g = object() + g.name = s.name + g.nodes = {} + for _, n in s.nodes or {} do + if nodes[n] then + table.insert(g.nodes, n - 1) + end + end + restore(g, s.extras) + table.insert(scenes, g) + end + local which = mg.scene or 1 + if scenes[which] then + scenes[which].nodes = {} + for _, r in scene.roots or {} do + table.insert(scenes[which].nodes, r - 1) + end + end + doc.scene = (mg.scene or 1) - 1 + else + local g = object() + g.nodes = {} + for _, r in scene.roots or {} do + table.insert(g.nodes, r - 1) + end + table.insert(scenes, g) + doc.scene = 0 + end + local asset = object() + asset.version = "2.0" + asset.generator = "rosetta" + if type(mg.asset) == "table" then + asset.copyright = mg.asset.copyright + asset.minVersion = mg.asset.minVersion + asset.extras = mg.asset.extras + end + doc.asset = asset + if type(mg.extensions) == "table" then + doc.extensions = object() + for k, v in mg.extensions do + doc.extensions[k] = v + used[k] = true + end + end + if #lights > 0 then + doc.extensions = doc.extensions or object() + local lp = object() + lp.lights = lights + doc.extensions.KHR_lights_punctual = lp + used.KHR_lights_punctual = true + end + doc.extras = mg.extras + local function list(t: { [string]: boolean }): { string }? + local out = {} + for k in t do + table.insert(out, k) + end + table.sort(out) + return if #out > 0 then out else nil + end + -- the source's required extensions that are still used stay required + for _, e in (if type(mg.extensionsRequired) == "table" then mg.extensionsRequired else {}) do + if used[e] then + required[e] = true + end + end + doc.extensionsUsed = list(used) + doc.extensionsRequired = list(required) + doc.scenes = scenes + doc.nodes = if #nodes > 0 then nodes else nil + doc.meshes = if #meshes > 0 then meshes else nil + doc.materials = if #materials > 0 then materials else nil + doc.textures = if #textures > 0 then textures else nil + doc.images = if #images > 0 then images else nil + doc.samplers = if #samplers > 0 then samplers else nil + doc.cameras = if #cameras > 0 then cameras else nil + doc.skins = if #skins > 0 then skins else nil + doc.animations = if #animations > 0 then animations else nil + doc.accessors = if #accessors > 0 then accessors else nil + doc.bufferViews = if #views > 0 then views else nil + return { doc = doc, bin = bin:finish(), images = imageOut }, nil +end + +return Write +end +__FILES["model/iqm"] = function() + +-- model/iqm: Inter-Quake Model (IQM version 2; iqm.txt / iqm.h of Lee Salzman's IQM SDK, public domain; checked against +-- assimp). Supports: meshes, every vertex array format, joints / skin, poses + anims, bounds. IQM is z-up, clockwise. +-- Not supported: IQM version 1, adjacency and extensions. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Read = __include("model/iqm/Read") +local Write = __include("model/iqm/Write") + +-- ------------------------------------------------------------------------------------------------ contract +local Iqm = { + name = "iqm", + category = "model", + extensions = { "iqm" }, + mime = { "model/x-iqm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/Rig", "codecs/model/Sampler" }, + caps = { decode = true, encode = true, materials = true, skins = true, animation = true, vertexColors = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + maxVertices: number?, -- default 2^25 +} +type EncodeOptions = { + framerate: number?, -- default: the key spacing when uniform, else 30 per second + comment: string?, +} + +-- ------------------------------------------------------------------------------------------------ constants +local MAGIC = "INTERQUAKEMODEL\0" + +-- ------------------------------------------------------------------------------------------------ sniff +function Iqm.sniff(r: Bytes.Reader): number + return if r:peek(16) == MAGIC then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Iqm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + if r.limit - r.base < 124 then + return nil, Err.new(Err.TRUNCATED, "shorter than the header", r.base) + end + if r:peek(16) ~= MAGIC then + return nil, Err.new(Err.CORRUPT, "no INTERQUAKEMODEL magic", r.base) + end + local ok, scene, msg = pcall(Read.scene, r.buf, r.base, r.limit, opts) + if not ok then + return nil, Err.new(Err.CORRUPT, "bad model data: " .. tostring(scene)) + end + if not scene then + return nil, Err.from(msg) + end + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Iqm.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(scene) ~= "table" or scene.kind ~= "scene" then + return nil, Err.new(Err.ARG, "needs a Scene") + end + local ok, out, msg = pcall(Write.iqm, scene, opts) + if not ok then + return nil, Err.new(Err.ARG, "bad scene: " .. tostring(out)) + end + if not out then + local e = Err.from(msg) + return nil, Err.new(if e.code == Err.CORRUPT then Err.ARG else e.code, e.message) + end + return out, nil +end + +return Iqm +end +__FILES["model/iqm/Read"] = function() + +-- model/iqm/Read: an Inter-Quake Model (version 2) -> Types.Scene. Every header range is checked before it is read. +local Types = __include("Types") +local Rig = __include("codecs/model/Rig") + +local Read = {} + +local Scene = Types.Scene +local readu8, readi8, readu16, readi16, readu32, readi32, readf32, readf64 = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.readi32, buffer.readf32, buffer.readf64 +local writef32, writeu32, writeu8, writeu16 = buffer.writef32, buffer.writeu32, buffer.writeu8, buffer.writeu16 + +Read.HEADER = { + "version", "filesize", "flags", "num_text", "ofs_text", "num_meshes", "ofs_meshes", "num_vertexarrays", "num_vertexes", + "ofs_vertexarrays", "num_triangles", "ofs_triangles", "ofs_adjacency", "num_joints", "ofs_joints", "num_poses", + "ofs_poses", "num_anims", "ofs_anims", "num_frames", "num_framechannels", "ofs_frames", "ofs_bounds", "num_comment", + "ofs_comment", "num_extensions", "ofs_extensions", +} +Read.SIZES = { [0] = 1, 1, 2, 2, 4, 4, 2, 4, 8 } -- byte, ubyte, short, ushort, int, uint, half, float, double +Read.ARRAYS = { [0] = "position", "texcoord", "normal", "tangent", "blendindexes", "blendweights", "color" } + +local function half(h: number): number + local s = if bit32.band(h, 0x8000) ~= 0 then -1 else 1 + local e = bit32.band(bit32.rshift(h, 10), 0x1F) + local m = bit32.band(h, 0x3FF) + if e == 0 then + return s * m * 2 ^ -24 + elseif e == 31 then + return if m == 0 then s * math.huge else 0 + end + return s * (1 + m / 1024) * 2 ^ (e - 15) +end + +-- normalized: integer formats scaled to 0..1 / -1..1 +local function values(b: buffer, at: number, format: number, n: number, normalized: boolean): { number } + local out = table.create(n) :: { number } + local size = Read.SIZES[format] + for i = 0, n - 1 do + local p = at + i * size + local v: number + if format == 0 then + v = readi8(b, p) + v = if normalized then math.max(v / 127, -1) else v + elseif format == 1 then + v = readu8(b, p) + v = if normalized then v / 255 else v + elseif format == 2 then + v = readi16(b, p) + v = if normalized then math.max(v / 32767, -1) else v + elseif format == 3 then + v = readu16(b, p) + v = if normalized then v / 65535 else v + elseif format == 4 then + v = readi32(b, p) + elseif format == 5 then + v = readu32(b, p) + elseif format == 6 then + v = half(readu16(b, p)) + elseif format == 7 then + v = readf32(b, p) + else + v = readf64(b, p) + end + out[i + 1] = v + end + return out +end + +local function f32acc(vals: { number }, comps: number): Types.Accessor + local d = buffer.create(#vals * 4) + for i, v in vals do + writef32(d, (i - 1) * 4, v) + end + return Scene.accessor(d, "f32", comps, #vals // comps) +end + +local MIME: { [string]: string } = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", tga = "image/x-tga", bmp = "image/bmp", dds = "image/vnd-ms.dds" } + +function Read.scene(b: buffer, base: number, limit: number, opts: { maxVertices: number? }?): (Types.Scene?, string?) + local size = limit - base + local H: { [string]: number } = {} + for i, name in Read.HEADER do + H[name] = readu32(b, base + 12 + i * 4) + end + if H.version ~= 2 then + return nil, "unsupported: IQM version " .. H.version .. " (only 2)" + end + if H.filesize > size then + return nil, "truncated: the header says " .. H.filesize .. " bytes, " .. size .. " present" + end + local maxV = opts and opts.maxVertices or 2 ^ 25 + if H.num_vertexes > maxV or H.num_triangles > maxV then + return nil, "limit: more than " .. maxV .. " vertices / triangles" + end + local function range(ofs: number, count: number, each: number, what: string): string? + if count > 0 and (ofs < 124 or count * each > H.filesize or ofs + count * each > H.filesize) then + return "the " .. what .. " lie outside the file" + end + return nil + end + local err = range(H.ofs_text, H.num_text, 1, "text") + or range(H.ofs_meshes, H.num_meshes, 24, "meshes") + or range(H.ofs_vertexarrays, H.num_vertexarrays, 20, "vertex arrays") + or range(H.ofs_triangles, H.num_triangles, 12, "triangles") + or range(H.ofs_joints, H.num_joints, 48, "joints") + or range(H.ofs_poses, H.num_poses, 88, "poses") + or range(H.ofs_anims, H.num_anims, 20, "anims") + or range(H.ofs_frames, H.num_frames * H.num_framechannels, 2, "frames") + or range(H.ofs_bounds, if H.ofs_bounds > 0 then H.num_frames else 0, 32, "bounds") + or range(H.ofs_comment, H.num_comment, 1, "comment") + if err then + return nil, err + end + local text = if H.num_text > 0 then buffer.readstring(b, base + H.ofs_text, H.num_text) else "" + local function str(ofs: number): string + if ofs >= #text then + return "" + end + local z = string.find(text, "\0", ofs + 1, true) + return string.sub(text, ofs + 1, (z or #text + 1) - 1) + end + local scene = Scene.new() + scene.meta.up = "z" + local source: { [string]: any } = { format = "iqm", version = 2, flags = H.flags } + scene.meta.source = source + if H.num_comment > 0 then + source.comment = string.match(buffer.readstring(b, base + H.ofs_comment, H.num_comment), "^[^%z]*") + end + local nv = H.num_vertexes + type Array = { kind: string, name: string, format: number, comps: number, offset: number } + local arrays: { Array } = {} + for i = 0, H.num_vertexarrays - 1 do + local p = base + H.ofs_vertexarrays + i * 20 + local typ, format, comps, offset = readu32(b, p), readu32(b, p + 8), readu32(b, p + 12), readu32(b, p + 16) + local esize = Read.SIZES[format] + if not esize or comps < 1 or comps > 16 then + return nil, "vertex array " .. i .. " has format " .. format .. " / " .. comps .. " components" + end + local e = range(offset, nv, comps * esize, "vertex array " .. i) + if e then + return nil, e + end + local kind = Read.ARRAYS[typ] + local name = if kind then kind else "_" .. (if typ >= 0x10 then str(typ - 0x10) else tostring(typ)) + table.insert(arrays, { kind = kind or "custom", name = name, format = format, comps = comps, offset = base + offset }) + end + local jointNodes: { number } = {} + local skin: number? = nil + if H.num_joints > 0 then + local joints: { Rig.Joint } = {} + for j = 0, H.num_joints - 1 do + local p = base + H.ofs_joints + j * 48 + local parent = readi32(b, p + 4) + local f = table.create(10) :: { number } + for k = 0, 9 do + f[k + 1] = readf32(b, p + 8 + k * 4) + end + local q = { f[4], f[5], f[6], f[7] } + local ql = math.sqrt(q[1] ^ 2 + q[2] ^ 2 + q[3] ^ 2 + q[4] ^ 2) + q = if ql > 0 then { q[1] / ql, q[2] / ql, q[3] / ql, q[4] / ql } else { 0, 0, 0, 1 } + joints[j + 1] = { name = str(readu32(b, p)), parent = parent + 1, translation = { f[1], f[2], f[3] }, rotation = q, scale = { f[8], f[9], f[10] } } + end + jointNodes, skin = Rig.skeleton(scene, joints, "local") + end + -- materials: one per distinct material string (IQM tools name the texture there) + local matOf: { [string]: number } = {} + local function material(name: string): number? + if name == "" then + return nil + end + local hit = matOf[name] + if hit then + return hit + end + local mat = Scene.material(name) + mat.metallic = 0 + local ext = string.lower(string.match(name, "%.(%w+)$") or "") + table.insert(scene.textures, { name = name, uri = name, mime = MIME[ext] }) + mat.baseColorTexture = { texture = #scene.textures } + table.insert(scene.materials, mat) + matOf[name] = #scene.materials + return #scene.materials + end + for m = 0, H.num_meshes - 1 do + local p = base + H.ofs_meshes + m * 24 + local name, mname = str(readu32(b, p)), str(readu32(b, p + 4)) + local fv, cv, ft, ct = readu32(b, p + 8), readu32(b, p + 12), readu32(b, p + 16), readu32(b, p + 20) + if fv + cv > nv or ft + ct > H.num_triangles then + return nil, "mesh " .. m .. " points outside the vertex / triangle arrays" + end + local attributes: { [string]: Types.Accessor } = {} + for _, a in arrays do + local esize = Read.SIZES[a.format] + local at = a.offset + fv * a.comps * esize + if a.kind == "blendindexes" then + local vals = values(b, at, a.format, cv * a.comps, false) + local big = a.format ~= 1 + local d = buffer.create(cv * 4 * (if big then 2 else 1)) + for v = 0, cv - 1 do + for c = 0, 3 do + local x = if c < a.comps then vals[v * a.comps + c + 1] else 0 + x = math.clamp(math.floor(x), 0, if big then 65535 else 255) + if big then + writeu16(d, (v * 4 + c) * 2, x) + else + writeu8(d, v * 4 + c, x) + end + end + end + attributes.JOINTS_0 = Scene.accessor(d, if big then "u16" else "u8", 4, cv) + elseif a.kind == "blendweights" or (a.kind == "color" and a.format == 1) then + local vals = values(b, at, a.format, cv * a.comps, true) + local d = buffer.create(cv * 4) + for v = 0, cv - 1 do + for c = 0, 3 do + local x = if c < a.comps then vals[v * a.comps + c + 1] elseif a.kind == "color" and c == 3 then 1 else 0 + writeu8(d, v * 4 + c, math.clamp(math.floor(x * 255 + 0.5), 0, 255)) + end + end + attributes[if a.kind == "color" then "COLOR_0" else "WEIGHTS_0"] = Scene.accessor(d, "unorm8", 4, cv) + else + local vals = values(b, at, a.format, cv * a.comps, true) + local name0 = if a.kind == "position" then "POSITION" elseif a.kind == "texcoord" then "TEXCOORD_0" elseif a.kind == "normal" then "NORMAL" elseif a.kind == "tangent" then "TANGENT" elseif a.kind == "color" then "COLOR_0" else a.name + local want = if a.kind == "position" or a.kind == "normal" then 3 elseif a.kind == "texcoord" then 2 elseif a.kind == "tangent" or a.kind == "color" then 4 else a.comps + if want ~= a.comps then + local fixed = table.create(cv * want, 0) :: { number } + for v = 0, cv - 1 do + for c = 0, want - 1 do + fixed[v * want + c + 1] = if c < a.comps then vals[v * a.comps + c + 1] elseif c == 3 then 1 else 0 + end + end + vals = fixed + end + attributes[name0] = f32acc(vals, want) + end + end + if not attributes.POSITION then + return nil, "no position array" + end + -- IQM's front faces are clockwise: corners 2 and 3 swap + local ib = buffer.create(ct * 12) + for k = 0, ct - 1 do + local q = base + H.ofs_triangles + (ft + k) * 12 + local a, c2, c3 = readu32(b, q), readu32(b, q + 4), readu32(b, q + 8) + if a < fv or c2 < fv or c3 < fv or a >= fv + cv or c2 >= fv + cv or c3 >= fv + cv then + return nil, "triangle " .. (ft + k) .. " uses a vertex outside mesh " .. m + end + writeu32(ib, k * 12, a - fv) + writeu32(ib, k * 12 + 4, c3 - fv) + writeu32(ib, k * 12 + 8, c2 - fv) + end + local prim: Types.Primitive = { attributes = attributes, indices = Scene.accessor(ib, "u32", 1, ct * 3), mode = "triangles", material = material(mname) } + table.insert(scene.meshes, { name = name, primitives = { prim } }) + local node: Types.Node = { name = name, children = {}, mesh = #scene.meshes } + if skin and attributes.JOINTS_0 then + node.skin = skin + end + table.insert(scene.nodes, node) + table.insert(scene.roots, #scene.nodes) + end + -- frames hold the masked pose channels (offset + value * scale), in pose order + if H.num_anims > 0 and H.num_frames > 0 and H.num_poses > 0 then + local np = H.num_poses + local poses: { { mask: number, offset: { number }, scale: { number } } } = {} + local channels = 0 + for i = 0, np - 1 do + local p = base + H.ofs_poses + i * 88 + local mask = readu32(b, p + 4) + local off, sc = table.create(10) :: { number }, table.create(10) :: { number } + for c = 0, 9 do + off[c + 1] = readf32(b, p + 8 + c * 4) + sc[c + 1] = readf32(b, p + 48 + c * 4) + if bit32.band(mask, bit32.lshift(1, c)) ~= 0 then + channels += 1 + end + end + poses[i + 1] = { mask = mask, offset = off, scale = sc } + end + if channels ~= H.num_framechannels then + return nil, "the poses use " .. channels .. " frame channels, the header says " .. H.num_framechannels + end + -- frame f, pose i -> 10 values + local frameBytes: number = H.num_framechannels * 2 + local framesAt: number = base + H.ofs_frames + local function frame(f: number): { { number } } + local out = table.create(np) :: { { number } } + local q = framesAt + f * frameBytes + for i = 1, np do + local ps = poses[i] + local v = table.create(10) :: { number } + for c = 0, 9 do + local x = ps.offset[c + 1] + if bit32.band(ps.mask, bit32.lshift(1, c)) ~= 0 then + local k: number = ps.scale[c + 1] + x += readu16(b, q) * k + q += 2 + end + v[c + 1] = x + end + out[i] = v + end + return out + end + local anims: { any } = {} + for a = 0, H.num_anims - 1 do + local p = base + H.ofs_anims + a * 20 + local name, first, count, rate, flags = str(readu32(b, p)), readu32(b, p + 4), readu32(b, p + 8), readf32(b, p + 12), readu32(b, p + 16) + if first + count > H.num_frames then + return nil, "animation " .. a .. " uses frames past the end" + end + local fps = if rate > 0 and rate == rate then rate else 30 + local times = table.create(count) :: { number } + local tracks: { [number]: Rig.Track } = {} + for j = 1, math.min(np, #jointNodes) do + tracks[j] = { translation = {}, rotation = {}, scale = {} } + end + for k = 0, count - 1 do + times[k + 1] = k / fps + local fr = frame(first + k) + for j, tr in tracks do + local v = fr[j] + local t, r, s = tr.translation :: { number }, tr.rotation :: { number }, tr.scale :: { number } + table.move(v, 1, 3, #t + 1, t) + local ql = math.sqrt(v[4] ^ 2 + v[5] ^ 2 + v[6] ^ 2 + v[7] ^ 2) + ql = if ql > 0 then ql else 1 + table.move({ v[4] / ql, v[5] / ql, v[6] / ql, v[7] / ql }, 1, 4, #r + 1, r) + table.move(v, 8, 10, #s + 1, s) + end + end + if count > 0 then + Rig.animation(scene, name, jointNodes, times, tracks) + end + table.insert(anims, { name = name, first = first, frames = count, framerate = rate, loop = bit32.band(flags, 1) ~= 0 }) + end + source.animations = anims + end + -- bounds: one box per frame + if H.ofs_bounds > 0 and H.num_frames > 0 then + local boxes = {} + for f = 0, H.num_frames - 1 do + local p = base + H.ofs_bounds + f * 32 + boxes[f + 1] = { + min = { readf32(b, p), readf32(b, p + 4), readf32(b, p + 8) }, + max = { readf32(b, p + 12), readf32(b, p + 16), readf32(b, p + 20) }, + xyradius = readf32(b, p + 24), + radius = readf32(b, p + 28), + } + end + source.bounds = boxes + end + return scene, nil +end + +return Read +end +__FILES["model/iqm/Write"] = function() + +-- model/iqm/Write: Types.Scene -> an Inter-Quake Model (version 2). Blend weights are u8 summing to 255; the skeleton +-- is the union of the scene's skins, parents first; animations quantized per pose channel to 16 bits. +local Types = __include("Types") +local Bytes = __include("core/Bytes") +local Mat4 = __include("codecs/model/Mat4") +local Sampler = __include("codecs/model/Sampler") +local Read = __include("model/iqm/Read") + +local Write = {} + +local Scene = Types.Scene +type M4 = { number } + +-- ------------------------------------------------------------------------------------------------ scene walk +local function parents(scene: Types.Scene): { [number]: number } + local parent: { [number]: number } = {} + for i, n in scene.nodes do + for _, c in n.children or {} do + if parent[c] == nil and c ~= i then + parent[c] = i + end + end + end + return parent +end + +local function localMatrix(node: Types.Node, over: { [string]: { number } }?): M4 + if not over then + return Scene.nodeMatrix(node) + end + if node.matrix and #node.matrix == 16 and not (over.translation or over.rotation or over.scale) then + return node.matrix + end + local t, r, s = node.translation, node.rotation, node.scale + if node.matrix and #node.matrix == 16 then + t, r, s = Mat4.decompose(node.matrix) + end + return Mat4.compose(over.translation or t, over.rotation or r, over.scale or s) +end + +local function worlds(scene: Types.Scene, parent: { [number]: number }, pose: Sampler.Pose?): { [number]: M4 } + local world: { [number]: M4 } = {} + local function get(i: number, depth: number): M4 + local w = world[i] + if w then + return w + end + local m = localMatrix(scene.nodes[i], pose and pose[i]) + local p = parent[i] + if p and depth < #scene.nodes then + m = Mat4.mul(get(p, depth + 1), m) + end + world[i] = m + return m + end + for i in scene.nodes do + get(i, 0) + end + return world +end + +-- ------------------------------------------------------------------------------------------------ geometry +local function triangles(prim: Types.Primitive): { number }? + local mode = prim.mode or "triangles" + local nv = prim.attributes.POSITION.count + local idx: { number } = {} + if prim.indices then + local get = Scene.reader(prim.indices) + if not get then + return nil + end + for k = 0, prim.indices.count - 1 do + idx[k + 1] = get(k, 0) + end + else + for k = 0, nv - 1 do + idx[k + 1] = k + end + end + local out: { number } = {} + if mode == "triangles" then + for k = 1, #idx - 2, 3 do + table.move(idx, k, k + 2, #out + 1, out) + end + elseif mode == "triangle_strip" then + for k = 1, #idx - 2 do + if k % 2 == 1 then + table.move({ idx[k], idx[k + 1], idx[k + 2] }, 1, 3, #out + 1, out) + else + table.move({ idx[k + 1], idx[k], idx[k + 2] }, 1, 3, #out + 1, out) + end + end + elseif mode == "triangle_fan" then + for k = 2, #idx - 1 do + table.move({ idx[1], idx[k], idx[k + 1] }, 1, 3, #out + 1, out) + end + elseif mode == "polygons" and prim.faces then + local fget = Scene.reader(prim.faces) + local at = 1 + for f = 0, prim.faces.count - 1 do + local n = if fget then fget(f, 0) else 0 + for k = 1, n - 2 do + table.move({ idx[at], idx[at + k], idx[at + k + 1] }, 1, 3, #out + 1, out) + end + at += n + end + else + return nil + end + for _, v in out do + if v >= nv or v < 0 then + error("index " .. v .. " out of range", 0) + end + end + return out +end + +local function readAll(acc: Types.Accessor?, comps: number, nv: number, default: { number }): { number }? + if not acc then + return nil + end + local get = Scene.reader(acc) + if not get or acc.count < nv then + return nil + end + local out = table.create(nv * comps) :: { number } + for v = 0, nv - 1 do + for c = 0, comps - 1 do + out[v * comps + c + 1] = if c < acc.components then get(v, c) else default[c + 1] + end + end + return out +end + +-- the 4 strongest, u8 weights summing to 255 +local function influences(skin: Types.Skin, jointIndex: { [number]: number }, joints: { number }, weights: { number }, v: number): { number } + local pairs_: { { number } } = {} + for c = 1, 4 do + local w = weights[v * 4 + c] + local node = skin.joints[math.floor(joints[v * 4 + c]) + 1] + if w > 0 and node and jointIndex[node] then + table.insert(pairs_, { jointIndex[node], w }) + end + end + table.sort(pairs_, function(a: { number }, b: { number }): boolean + return a[2] > b[2] + end) + local sum = 0 + for _, pr in pairs_ do + sum += pr[2] + end + local q: { number } = {} + local left = 255 + for k, pr in pairs_ do + q[k] = if sum > 0 then math.floor(pr[2] / sum * 255 + 0.5) else 0 + left -= q[k] + end + if #pairs_ > 0 then + q[1] += left + end + local list: { number } = {} + for k, pr in pairs_ do + if q[k] > 0 then + table.insert(list, pr[1]) + table.insert(list, q[k]) + end + end + return list +end + +local function push4(bi: { number }, bw: { number }, list: { number }) + local n = #bi + for c = 1, 4 do + bi[n + c] = list[c * 2 - 1] or 0 + bw[n + c] = list[c * 2] or 0 + end +end + +-- ------------------------------------------------------------------------------------------------ writer +type MeshOut = { name: string, material: string, first: number, count: number, tfirst: number, tcount: number } + +function Write.iqm(scene: Types.Scene, opts: { framerate: number?, comment: string? }?): (buffer?, string?) + local parent = parents(scene) + local rest = worlds(scene, parent, nil) + local isJoint: { [number]: boolean } = {} + local ibmOf: { [number]: M4 } = {} + for _, skin in scene.skins do + local get = skin.inverseBindMatrices and Scene.reader(skin.inverseBindMatrices) + for j, node in skin.joints do + if scene.nodes[node] then + isJoint[node] = true + if get and ibmOf[node] == nil and skin.inverseBindMatrices and skin.inverseBindMatrices.count >= j then + local m = table.create(16) :: M4 + for k = 1, 16 do + m[k] = get(j - 1, k - 1) + end + ibmOf[node] = m + end + end + end + end + -- IQM wants parents first + local jointList: { number } = {} + local jointIndex: { [number]: number } = {} + local function add(n: number, depth: number) + if jointIndex[n] or depth > #scene.nodes then + return + end + local p = parent[n] + local guard = 0 + while p and not isJoint[p] and guard <= #scene.nodes do + p = parent[p] + guard += 1 + end + if p and isJoint[p] then + add(p, depth + 1) + end + if not jointIndex[n] then + table.insert(jointList, n) + jointIndex[n] = #jointList - 1 + end + end + for _, skin in scene.skins do + for _, n in skin.joints do + if isJoint[n] then + add(n, 0) + end + end + end + if #jointList > 65535 then + return nil, "limit: more than 65535 joints" + end + local function jointParent(n: number): number + local p = parent[n] + local guard = 0 + while p and guard <= #scene.nodes do + if jointIndex[p] then + return jointIndex[p] + end + p = parent[p] + guard += 1 + end + return -1 + end + local bindWorld: { [number]: M4 } = {} + for _, n in jointList do + local ibm = ibmOf[n] + bindWorld[n] = (ibm and Mat4.inverseFull(ibm)) or rest[n] + end + local function poseLocal(n: number, world: { [number]: M4 }): ({ number }, { number }, { number }) + local p = jointParent(n) + local m = world[n] + if p >= 0 then + local inv = Mat4.inverseFull(world[jointList[p + 1]]) + if inv then + m = Mat4.mul(inv, m) + end + end + return Mat4.decompose(m) + end + local nodeOfMesh: { [number]: number } = {} + local placed: { { node: number, mesh: number } } = {} + local seen: { [number]: boolean } = {} + local function visit(i: number, depth: number) + if seen[i] or depth > #scene.nodes then + return + end + seen[i] = true + local node = scene.nodes[i] + if node.mesh and scene.meshes[node.mesh] then + table.insert(placed, { node = i, mesh = node.mesh }) + nodeOfMesh[node.mesh] = nodeOfMesh[node.mesh] or i + end + for _, c in node.children or {} do + visit(c, depth + 1) + end + end + local roots = scene.roots + if not roots or #roots == 0 then + roots = {} + for i in scene.nodes do + if parent[i] == nil then + table.insert(roots, i) + end + end + end + for _, r in roots do + visit(r, 0) + end + if #placed == 0 and #scene.nodes == 0 then + for mi in scene.meshes do + table.insert(placed, { node = 0, mesh = mi }) + end + end + local hasJoints = #jointList > 0 + local P, TC, N, TG, BI, BW, C = {}, {}, {}, {}, {}, {}, {} + local hasTC, hasN, hasTG, hasC = false, false, false, false + local tris: { number } = {} + local meshes: { MeshOut } = {} + local skinOf: { { number } } = {} + local nvTotal = 0 + for _, pl in placed do + local node = scene.nodes[pl.node] + local mesh = scene.meshes[pl.mesh] + local skinned = node and node.skin and scene.skins[node.skin] + local world = if pl.node > 0 then rest[pl.node] else Scene.IDENTITY + local nrmM = Mat4.normalMatrix(world) + for pi, prim in mesh.primitives do + local pos = prim.attributes.POSITION + local tri = pos and triangles(prim) + if tri and #tri > 0 then + local nv = pos.count + local first = nvTotal + local positions = readAll(pos, 3, nv, { 0, 0, 0 }) :: { number } + local normals = readAll(prim.attributes.NORMAL, 3, nv, { 0, 0, 1 }) + local tangents = readAll(prim.attributes.TANGENT, 4, nv, { 1, 0, 0, 1 }) + local uvs = readAll(prim.attributes.TEXCOORD_0, 2, nv, { 0, 0 }) + local cols = readAll(prim.attributes.COLOR_0, 4, nv, { 1, 1, 1, 1 }) + local joints = skinned and readAll(prim.attributes.JOINTS_0, 4, nv, { 0, 0, 0, 0 }) + local weights = skinned and readAll(prim.attributes.WEIGHTS_0, 4, nv, { 0, 0, 0, 0 }) + local rigid = -1 + if hasJoints and not (joints and weights) then + local p = if pl.node > 0 then pl.node else nil + local guard = 0 + while p and guard <= #scene.nodes do + if jointIndex[p] then + rigid = jointIndex[p] + break + end + p = parent[p] + guard += 1 + end + rigid = math.max(rigid, 0) + end + local bake = not (joints and weights) + for v = 0, nv - 1 do + local x, y, z = positions[v * 3 + 1], positions[v * 3 + 2], positions[v * 3 + 3] + if bake then + x, y, z = Mat4.point(world, x, y, z) + end + table.move({ x, y, z }, 1, 3, #P + 1, P) + if normals then + local nx, ny, nz = normals[v * 3 + 1], normals[v * 3 + 2], normals[v * 3 + 3] + if bake then + nx, ny, nz = Mat4.point(nrmM, nx, ny, nz) + nx, ny, nz = nx - nrmM[13], ny - nrmM[14], nz - nrmM[15] + local l = math.sqrt(nx * nx + ny * ny + nz * nz) + if l > 0 then + nx, ny, nz = nx / l, ny / l, nz / l + end + end + hasN = true + table.move({ nx, ny, nz }, 1, 3, #N + 1, N) + else + table.move({ 0, 0, 1 }, 1, 3, #N + 1, N) + end + if tangents then + local tx, ty, tz = tangents[v * 4 + 1], tangents[v * 4 + 2], tangents[v * 4 + 3] + if bake then + tx, ty, tz = Mat4.point(world, tx, ty, tz) + tx, ty, tz = tx - world[13], ty - world[14], tz - world[15] + end + hasTG = true + table.move({ tx, ty, tz, tangents[v * 4 + 4] }, 1, 4, #TG + 1, TG) + else + table.move({ 1, 0, 0, 1 }, 1, 4, #TG + 1, TG) + end + if uvs then + hasTC = true + table.move(uvs, v * 2 + 1, v * 2 + 2, #TC + 1, TC) + else + table.move({ 0, 0 }, 1, 2, #TC + 1, TC) + end + if cols then + hasC = true + table.move(cols, v * 4 + 1, v * 4 + 4, #C + 1, C) + else + table.move({ 1, 1, 1, 1 }, 1, 4, #C + 1, C) + end + -- the 4 strongest, u8 weights summing to 255 + local list: { number } + if joints and weights and skinned then + list = influences(skinned, jointIndex, joints, weights, v) + elseif rigid >= 0 then + list = { rigid, 255 } + else + list = {} + end + push4(BI, BW, list) + skinOf[#skinOf + 1] = list + end + -- IQM's clockwise order + local tfirst = #tris // 3 + for k = 1, #tri, 3 do + table.move({ first + tri[k], first + tri[k + 2], first + tri[k + 1] }, 1, 3, #tris + 1, tris) + end + local mat = prim.material and scene.materials[prim.material] + local mname = "" + if mat then + local ref = mat.baseColorTexture + local tex = ref and scene.textures[ref.texture] + mname = if tex and tex.uri then tex.uri elseif mat.name then mat.name else "" + end + local name = mesh.name or ("mesh" .. pl.mesh) + if #mesh.primitives > 1 then + name ..= "_" .. pi + end + table.insert(meshes, { name = name, material = mname, first = first, count = nv, tfirst = tfirst, tcount = #tri // 3 }) + nvTotal += nv + end + end + end + if #meshes == 0 then + return nil, "nothing to write: no triangle primitives" + end + local frames: { { { number } } } = {} -- frames[f][joint] = 10 values + local anims: { { name: string, first: number, count: number, rate: number } } = {} + local frameWorld: { { [number]: M4 } } = {} + if hasJoints then + for ai, anim in scene.animations do + local keys = Sampler.times(anim) + if #keys > 0 then + local rate = opts and opts.framerate + if not rate then + local dt = if #keys > 1 then keys[2] - keys[1] else 0 + local uniform = dt > 0 and math.abs(keys[1] - math.floor(keys[1] / dt + 0.5) * dt) < 1e-4 + for k = 2, #keys do + uniform = uniform and math.abs(keys[k] - keys[k - 1] - dt) < 1e-4 + end + rate = if uniform then 1 / dt else 30 + end + local fps: number = math.clamp(rate :: number, 1e-3, 1e4) + local last = keys[#keys] + local count = math.max(1, math.floor(last * fps + 0.5) + 1) + if count > 100000 then + return nil, "limit: animation " .. ai .. " has more than 100000 frames" + end + local cache = {} + local first = #frames + local prevQ: { [number]: { number } } = {} + for k = 0, count - 1 do + local pose = Sampler.pose(scene, anim, k / fps, cache) + local world = worlds(scene, parent, pose) + local fr = table.create(#jointList) :: { { number } } + for j, n in jointList do + local t, r, s = poseLocal(n, world) + local pq = prevQ[j] + if pq and pq[1] * r[1] + pq[2] * r[2] + pq[3] * r[3] + pq[4] * r[4] < 0 then + r = { -r[1], -r[2], -r[3], -r[4] } + end + prevQ[j] = r + fr[j] = { t[1], t[2], t[3], r[1], r[2], r[3], r[4], s[1], s[2], s[3] } + end + table.insert(frames, fr) + table.insert(frameWorld, world) + end + table.insert(anims, { name = anim.name or ("anim" .. ai), first = first, count = count, rate = fps }) + end + end + end + local masks, offsets, scales = {}, {}, {} + local numChannels = 0 + for j = 1, #jointList do + local lo, hi = table.create(10, math.huge), table.create(10, -math.huge) + for _, fr in frames do + for c = 1, 10 do + lo[c] = math.min(lo[c], fr[j][c]) + hi[c] = math.max(hi[c], fr[j][c]) + end + end + local mask = 0 + local off, sc = table.create(10, 0), table.create(10, 0) + for c = 1, 10 do + if lo[c] <= hi[c] then + off[c] = lo[c] + if hi[c] - lo[c] > 1e-6 then + mask = bit32.bor(mask, bit32.lshift(1, c - 1)) + sc[c] = (hi[c] - lo[c]) / 65535 + numChannels += 1 + end + end + end + masks[j], offsets[j], scales[j] = mask, off, sc + end + local text = { "\0" } + local textLen = 1 + local textAt: { [string]: number } = { [""] = 0 } + local function str(s: string): number + local hit = textAt[s] + if hit then + return hit + end + s = string.gsub(s, "%z", "") + local at = textLen + table.insert(text, s .. "\0") + textLen += #s + 1 + textAt[s] = at + return at + end + for _, m in meshes do + str(m.name) + str(m.material) + end + for _, n in jointList do + str(scene.nodes[n].name or "") + end + for _, a in anims do + str(a.name) + end + local comment = opts and opts.comment + local w = Bytes.writer(124 + nvTotal * 64 + #tris * 4) + local H: { [string]: number } = {} + local function at(): number + return w:tell() + end + w:string("INTERQUAKEMODEL\0") + for _ = 1, 27 do + w:u32le(0) + end + H.ofs_text, H.num_text = at(), textLen + w:string(table.concat(text)) + while at() % 4 ~= 0 do + w:u8(0) + H.num_text += 1 + end + H.ofs_meshes, H.num_meshes = at(), #meshes + for _, m in meshes do + for _, v in { str(m.name), str(m.material), m.first, m.count, m.tfirst, m.tcount } do + w:u32le(v) + end + end + type Arr = { typ: number, format: number, comps: number, data: { number } } + local arrs: { Arr } = { { typ = 0, format = 7, comps = 3, data = P } } + if hasTC then + table.insert(arrs, { typ = 1, format = 7, comps = 2, data = TC }) + end + if hasN then + table.insert(arrs, { typ = 2, format = 7, comps = 3, data = N }) + end + if hasTG then + table.insert(arrs, { typ = 3, format = 7, comps = 4, data = TG }) + end + if hasJoints then + table.insert(arrs, { typ = 4, format = if #jointList > 256 then 3 else 1, comps = 4, data = BI }) + table.insert(arrs, { typ = 5, format = 1, comps = 4, data = BW }) + end + if hasC then + table.insert(arrs, { typ = 6, format = 1, comps = 4, data = C }) + end + H.ofs_vertexarrays, H.num_vertexarrays, H.num_vertexes = at(), #arrs, nvTotal + w:fill(0, #arrs * 20) + local dataAt: { number } = {} + for i, a in arrs do + while at() % 4 ~= 0 do + w:u8(0) + end + dataAt[i] = at() + if a.format == 7 then + for _, v in a.data do + w:f32le(v) + end + elseif a.format == 3 then + for _, v in a.data do + w:u16le(math.clamp(math.floor(v), 0, 65535)) + end + elseif a.typ == 6 then + for _, v in a.data do + w:u8(math.clamp(math.floor(v * 255 + 0.5), 0, 255)) + end + else + for _, v in a.data do + w:u8(math.clamp(math.floor(v), 0, 255)) + end + end + end + while at() % 4 ~= 0 do + w:u8(0) + end + H.ofs_triangles, H.num_triangles = at(), #tris // 3 + for _, v in tris do + w:u32le(v) + end + if hasJoints then + H.ofs_joints, H.num_joints = at(), #jointList + for _, n in jointList do + local p = jointParent(n) + local t, r, s = poseLocal(n, bindWorld) + w:u32le(str(scene.nodes[n].name or "")) + w:u32le(if p < 0 then p + 2 ^ 32 else p) + for _, v in { t[1], t[2], t[3], r[1], r[2], r[3], r[4], s[1], s[2], s[3] } do + w:f32le(v) + end + end + if #frames > 0 then + H.ofs_poses, H.num_poses = at(), #jointList + for j, n in jointList do + local jp = jointParent(n) + w:u32le(if jp < 0 then jp + 2 ^ 32 else jp) + w:u32le(masks[j]) + for c = 1, 10 do + w:f32le(offsets[j][c]) + end + for c = 1, 10 do + w:f32le(scales[j][c]) + end + end + H.ofs_anims, H.num_anims = at(), #anims + for _, a in anims do + w:u32le(str(a.name)) + w:u32le(a.first) + w:u32le(a.count) + w:f32le(a.rate) + w:u32le(0) + end + H.ofs_frames, H.num_frames, H.num_framechannels = at(), #frames, numChannels + for _, fr in frames do + for j = 1, #jointList do + local mask = masks[j] + for c = 1, 10 do + if bit32.band(mask, bit32.lshift(1, c - 1)) ~= 0 then + local q = (fr[j][c] - offsets[j][c]) / scales[j][c] + w:u16le(math.clamp(math.floor(q + 0.5), 0, 65535)) + end + end + end + end + while at() % 4 ~= 0 do + w:u8(0) + end + H.ofs_bounds = at() + local skinM = table.create(#jointList) :: { M4 } + for f, world in frameWorld do + for j, n in jointList do + local invBind = Mat4.inverseFull(bindWorld[n]) or Mat4.identity() + skinM[j] = Mat4.mul(world[n], invBind) + end + local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge } + local xy, rad = 0, 0 + for v = 0, nvTotal - 1 do + local x, y, z = P[v * 3 + 1], P[v * 3 + 2], P[v * 3 + 3] + local list = skinOf[v + 1] + if #list > 0 then + local sx, sy, sz = 0, 0, 0 + for k = 1, #list - 1, 2 do + local m = skinM[list[k] + 1] + local wt = list[k + 1] / 255 + local px, py, pz = Mat4.point(m, x, y, z) + sx, sy, sz = sx + px * wt, sy + py * wt, sz + pz * wt + end + x, y, z = sx, sy, sz + end + lo = { math.min(lo[1], x), math.min(lo[2], y), math.min(lo[3], z) } + hi = { math.max(hi[1], x), math.max(hi[2], y), math.max(hi[3], z) } + xy = math.max(xy, x * x + y * y) + rad = math.max(rad, x * x + y * y + z * z) + end + for _, v in { lo[1], lo[2], lo[3], hi[1], hi[2], hi[3], math.sqrt(xy), math.sqrt(rad) } do + w:f32le(v) + end + local _ = f + end + end + end + if comment and comment ~= "" then + H.ofs_comment, H.num_comment = at(), #comment + 1 + w:string(comment .. "\0") + end + local out = w:finish() + H.version, H.filesize = 2, buffer.len(out) + for i, name in Read.HEADER do + buffer.writeu32(out, 12 + i * 4, H[name] or 0) + end + for i, a in arrs do + local p = H.ofs_vertexarrays + (i - 1) * 20 + buffer.writeu32(out, p, a.typ) + buffer.writeu32(out, p + 4, 0) + buffer.writeu32(out, p + 8, a.format) + buffer.writeu32(out, p + 12, a.comps) + buffer.writeu32(out, p + 16, dataAt[i]) + end + return out, nil +end + +return Write +end +__FILES["model/ldraw"] = function() + +-- model/ldraw: LDraw (.ldr / .dat / .mpd), read; File Format spec 1.0.2 with the MPD, BFC and !COLOUR extensions +-- (ldraw.org). Supports: line types 0-5, sub-files, BFC, LDConfig colours. -Y up, 1 LDU = 0.4 mm (a root node turns +-- it). Not supported: writing; !TEXMAP and !DATA; LDCad / MLCad / LPub meta commands; BFC in model files' references. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Sniff = __include("core/Sniff") +local Types = __include("Types") +local Read = __include("model/ldraw/Read") +local Colors = __include("model/ldraw/Colors") + +-- ------------------------------------------------------------------------------------------------ contract +local Ldraw = { + name = "ldraw", + category = "model", + extensions = { "ldr", "mpd", "dat" }, + mime = { "application/x-ldraw", "application/x-multi-part-ldraw" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" }, + caps = { decode = true, encode = false, materials = true, lines = true, instancing = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + resolve: ((uri: string) -> any)?, -- sub-files by library path + files: { [string]: any }?, -- or by library path ("parts/3001.dat", "p/stud.dat", ...) + ldconfig: string?, -- LDConfig.ldr text: its !COLOUR lines add to / replace the built-in colours + color: number?, -- default 16 ("Main_Colour") + upright: boolean?, -- default true + flatten: boolean?, -- default false + lines: boolean?, -- default true + optionalLines: boolean?, -- default false + maxDepth: number?, -- default 64 + maxTriangles: number?, -- default 2^24 + maxNodes: number?, -- default 2^20 +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Ldraw.sniff(r: Bytes.Reader): number + local head = Sniff.text(r, 2048, true) + if string.find(head, "^0%s+FILE%s") then + return 0.9 + end + if string.find(head, "\n%s*1%s+%S+" .. string.rep("%s+[-+%deE.]+", 12) .. "%s+[^\n]+%.[dDlL][aAdD][tTrR]%s*\r?\n") then + return 0.8 + end + if string.find(head, "^0[ \t]+%a") and string.find(head, "\n%s*[1-5]%s+%S+%s+[-+%d.]+%s+[-+%d.]+%s+[-+%d.]+%s+[-+%d.]+%s+[-+%d.]+%s+[-+%d.]") then + return 0.4 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Ldraw.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local text = Sniff.dropBom(buffer.readstring(r.buf, r.base, r.limit - r.base)) + local ok, scene, msg, kind = pcall(Read.scene, text, opts) + if not ok then + return nil, Err.new(Err.CORRUPT, "bad model: " .. tostring(scene)) + end + if not scene then + return nil, Err.from(msg, nil, kind) + end + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ extras +function Ldraw.colors(ldconfig: string?): { [number]: any } + local t = Colors.builtin() + if ldconfig then + Colors.parse(ldconfig, t) + end + return t +end + +return Ldraw +end +__FILES["model/ldraw/Colors"] = function() + +-- model/ldraw/Colors: the LDraw colour table, parsed from !COLOUR lines. The built-in table is LDraw.org's LDConfig.ldr +-- (UPDATE 2025-05-20; CC BY 2.0, see licenses/LDRAW_COLOURS.txt), without the "0 !COLOUR " prefix and with MATERIAL cut +-- after the material's type. Colours are 0xRRGGBB (sRGB); an edge is a colour code or a direct colour 0x2RRGGBB. +local Colors = {} + +type Colour = { name: string, rgb: number, edge: number, alpha: number, luminance: number, finish: string? } +type Table = { [number]: Colour } + +local FINISHES = { CHROME = true, PEARLESCENT = true, RUBBER = true, MATTE_METALLIC = true, METAL = true } + +-- "Name CODE n VALUE #RRGGBB EDGE #RRGGBB|code [ALPHA a] [LUMINANCE l] ..." +function Colors.entry(rest: string): (number?, Colour?) + local words: { string } = {} + for w in string.gmatch(rest, "%S+") do + table.insert(words, w) + end + local name = words[1] + local code, rgb, edge: number?, alpha, lum, finish = nil, nil, nil, 255, 0, nil + local i = 2 + while i <= #words do + local k, v = words[i], words[i + 1] + if k == "CODE" and v then + code = tonumber(v) + i += 1 + elseif k == "VALUE" and v and rgb == nil then + rgb = tonumber(string.match(v, "^#(%x%x%x%x%x%x)$") or "", 16) + i += 1 + elseif k == "EDGE" and v then + local hex = string.match(v, "^#(%x%x%x%x%x%x)$") + edge = if hex then 0x2000000 + (tonumber(hex, 16) :: number) else tonumber(v) + i += 1 + elseif k == "ALPHA" and v then + alpha = math.clamp(tonumber(v) or 255, 0, 255) + i += 1 + elseif k == "LUMINANCE" and v then + lum = math.clamp(tonumber(v) or 0, 0, 255) + i += 1 + elseif FINISHES[k] then + finish = k + elseif k == "MATERIAL" and v then + finish = v + break + end + i += 1 + end + if not name or not code or not rgb or code % 1 ~= 0 then + return nil, nil + end + return code, { name = name, rgb = rgb :: number, edge = edge or 0x2333333, alpha = alpha, luminance = lum, finish = finish } +end + +function Colors.parse(text: string, into: Table?): Table + local t: Table = into or {} + for line in string.gmatch(text, "[^\n]+") do + local rest = string.match(line, "^%s*0%s+!COLOUR%s+(.-)%s*$") + if rest then + local code, c = Colors.entry(rest) + if code and c then + t[code] = c + end + end + end + return t +end + +local BUILTIN = [[ +Black CODE 0 VALUE #1B2A34 EDGE #808080 +Blue CODE 1 VALUE #1E5AA8 EDGE #333333 +Green CODE 2 VALUE #00852B EDGE #333333 +Dark_Turquoise CODE 3 VALUE #069D9F EDGE #333333 +Red CODE 4 VALUE #B40000 EDGE #333333 +Dark_Pink CODE 5 VALUE #D3359D EDGE #333333 +Brown CODE 6 VALUE #543324 EDGE #1E1E1E +Light_Grey CODE 7 VALUE #8A928D EDGE #333333 +Dark_Grey CODE 8 VALUE #545955 EDGE #333333 +Light_Blue CODE 9 VALUE #97CBD9 EDGE #333333 +Bright_Green CODE 10 VALUE #58AB41 EDGE #333333 +Light_Turquoise CODE 11 VALUE #00AAA4 EDGE #333333 +Salmon CODE 12 VALUE #F06D61 EDGE #333333 +Pink CODE 13 VALUE #F6A9BB EDGE #333333 +Yellow CODE 14 VALUE #FAC80A EDGE #333333 +White CODE 15 VALUE #F4F4F4 EDGE #333333 +Light_Green CODE 17 VALUE #ADD9A8 EDGE #333333 +Light_Yellow CODE 18 VALUE #FFD67F EDGE #333333 +Tan CODE 19 VALUE #D7BA8C EDGE #333333 +Light_Violet CODE 20 VALUE #AFBED6 EDGE #333333 +Purple CODE 22 VALUE #671F81 EDGE #333333 +Dark_Blue_Violet CODE 23 VALUE #0E3E9A EDGE #333333 +Orange CODE 25 VALUE #D67923 EDGE #333333 +Magenta CODE 26 VALUE #901F76 EDGE #333333 +Lime CODE 27 VALUE #A5CA18 EDGE #333333 +Dark_Tan CODE 28 VALUE #897D62 EDGE #333333 +Bright_Pink CODE 29 VALUE #FF9ECD EDGE #333333 +Medium_Lavender CODE 30 VALUE #A06EB9 EDGE #333333 +Lavender CODE 31 VALUE #CDA4DE EDGE #333333 +Very_Light_Orange CODE 68 VALUE #FDC383 EDGE #333333 +Bright_Reddish_Lilac CODE 69 VALUE #8A12A8 EDGE #333333 +Reddish_Brown CODE 70 VALUE #5F3109 EDGE #808080 +Light_Bluish_Grey CODE 71 VALUE #969696 EDGE #333333 +Dark_Bluish_Grey CODE 72 VALUE #646464 EDGE #333333 +Medium_Blue CODE 73 VALUE #7396C8 EDGE #333333 +Medium_Green CODE 74 VALUE #7FC475 EDGE #333333 +Light_Pink CODE 77 VALUE #FECCCF EDGE #333333 +Light_Nougat CODE 78 VALUE #FFC995 EDGE #333333 +Medium_Nougat CODE 84 VALUE #AA7D55 EDGE #333333 +Medium_Lilac CODE 85 VALUE #441A91 EDGE #333333 +Light_Brown CODE 86 VALUE #7B5D41 EDGE #333333 +Blue_Violet CODE 89 VALUE #1C58A7 EDGE #333333 +Nougat CODE 92 VALUE #BB805A EDGE #333333 +Light_Salmon CODE 100 VALUE #F9B7A5 EDGE #333333 +Violet CODE 110 VALUE #26469A EDGE #333333 +Medium_Violet CODE 112 VALUE #4861AC EDGE #333333 +Medium_Lime CODE 115 VALUE #B7D425 EDGE #333333 +Aqua CODE 118 VALUE #9CD6CC EDGE #333333 +Light_Lime CODE 120 VALUE #DEEA92 EDGE #333333 +Light_Orange CODE 125 VALUE #F9A777 EDGE #333333 +Dark_Nougat CODE 128 VALUE #AD6140 EDGE #333333 +Very_Light_Bluish_Grey CODE 151 VALUE #C8C8C8 EDGE #333333 +Bright_Light_Orange CODE 191 VALUE #FCAC00 EDGE #333333 +Bright_Light_Blue CODE 212 VALUE #9DC3F7 EDGE #333333 +Rust CODE 216 VALUE #872B17 EDGE #333333 +Reddish_Lilac CODE 218 VALUE #8E5597 EDGE #333333 +Lilac CODE 219 VALUE #564E9D EDGE #333333 +Bright_Light_Yellow CODE 226 VALUE #FFEC6C EDGE #333333 +Sky_Blue CODE 232 VALUE #77C9D8 EDGE #333333 +Dark_Blue CODE 272 VALUE #19325A EDGE #333333 +Dark_Green CODE 288 VALUE #00451A EDGE #808080 +Flamingo_Pink CODE 295 VALUE #FF94C2 EDGE #333333 +Dark_Brown CODE 308 VALUE #352100 EDGE #808080 +Maersk_Blue CODE 313 VALUE #ABD9FF EDGE #333333 +Dark_Red CODE 320 VALUE #720012 EDGE #333333 +Dark_Azure CODE 321 VALUE #469BC3 EDGE #333333 +Medium_Azure CODE 322 VALUE #68C3E2 EDGE #333333 +Light_Aqua CODE 323 VALUE #D3F2EA EDGE #333333 +Yellowish_Green CODE 326 VALUE #E2F99A EDGE #333333 +Olive_Green CODE 330 VALUE #77774E EDGE #333333 +Sand_Red CODE 335 VALUE #88605E EDGE #333333 +Medium_Dark_Pink CODE 351 VALUE #F785B1 EDGE #333333 +Coral CODE 353 VALUE #FF6D77 EDGE #333333 +Earth_Orange CODE 366 VALUE #D86D2C EDGE #333333 +Neon_Yellow CODE 368 VALUE #EDFF21 EDGE #333333 +Medium_Brown CODE 370 VALUE #755945 EDGE #333333 +Medium_Tan CODE 371 VALUE #CCA373 EDGE #333333 +Sand_Purple CODE 373 VALUE #75657D EDGE #333333 +Sand_Green CODE 378 VALUE #708E7C EDGE #333333 +Sand_Blue CODE 379 VALUE #70819A EDGE #333333 +Reddish_Orange CODE 402 VALUE #CA4C0B EDGE #333333 +Sienna_Brown CODE 422 VALUE #915C3C EDGE #333333 +Umber_Brown CODE 423 VALUE #543F33 EDGE #333333 +Fabuland_Brown CODE 450 VALUE #D27744 EDGE #333333 +Medium_Orange CODE 462 VALUE #F58624 EDGE #333333 +Dark_Orange CODE 484 VALUE #91501C EDGE #333333 +Very_Light_Grey CODE 503 VALUE #BCB4A5 EDGE #333333 +Light_Orange_Brown CODE 507 VALUE #FA9C1C EDGE #333333 +Fabuland_Red CODE 508 VALUE #C65127 EDGE #333333 +Fabuland_Orange CODE 509 VALUE #CF8A47 EDGE #333333 +Fabuland_Lime CODE 510 VALUE #78FC78 EDGE #333333 +Trans_Dark_Blue CODE 33 VALUE #0020A0 EDGE #000B38 ALPHA 128 +Trans_Green CODE 34 VALUE #237841 EDGE #174F2B ALPHA 128 +Trans_Bright_Green CODE 35 VALUE #56E646 EDGE #27AF18 ALPHA 128 +Trans_Red CODE 36 VALUE #C91A09 EDGE #660D05 ALPHA 128 +Trans_Dark_Pink CODE 37 VALUE #DF6695 EDGE #B9275F ALPHA 128 +Trans_Neon_Orange CODE 38 VALUE #FF800D EDGE #A85100 ALPHA 128 +Trans_Very_Light_Blue CODE 39 VALUE #C1DFF0 EDGE #6FB4DC ALPHA 128 +Trans_Brown CODE 40 VALUE #635F52 EDGE #2A2823 ALPHA 128 +Trans_Medium_Blue CODE 41 VALUE #559AB7 EDGE #326276 ALPHA 128 +Trans_Neon_Green CODE 42 VALUE #C0FF00 EDGE #739900 ALPHA 128 +Trans_Light_Blue CODE 43 VALUE #AEE9EF EDGE #59D1DE ALPHA 128 +Trans_Bright_Reddish_Lilac CODE 44 VALUE #96709F EDGE #5F4365 ALPHA 128 +Trans_Pink CODE 45 VALUE #FC97AC EDGE #F9345B ALPHA 128 +Trans_Yellow CODE 46 VALUE #F5CD2F EDGE #B49208 ALPHA 128 +Trans_Clear CODE 47 VALUE #FCFCFC EDGE #C9C9C9 ALPHA 128 +Trans_Purple CODE 52 VALUE #A5A5CB EDGE #6464A6 ALPHA 128 +Trans_Neon_Yellow CODE 54 VALUE #DAB000 EDGE #755E00 ALPHA 128 +Trans_Orange CODE 57 VALUE #F08F1C EDGE #9E5C0A ALPHA 128 +Trans_Black_IR_Lens CODE 32 VALUE #000000 EDGE #333333 ALPHA 210 +Trans_Neon_Red CODE 158 VALUE #F18EBB EDGE #E63384 ALPHA 128 +Trans_Bright_Light_Green CODE 227 VALUE #B5D96C EDGE #86B22E ALPHA 128 +Trans_Bright_Light_Orange CODE 231 VALUE #FCB76D EDGE #FA860A ALPHA 128 +Trans_Fire_Yellow CODE 234 VALUE #FBE890 EDGE #F7D22B ALPHA 128 +Trans_Reddish_Lilac CODE 284 VALUE #C281A5 EDGE #944771 ALPHA 128 +Trans_Light_Green CODE 285 VALUE #7DC291 EDGE #46955D ALPHA 128 +Trans_Light_Blue_Violet CODE 293 VALUE #6BABE4 EDGE #247BC6 ALPHA 128 +Trans_Black CODE 10375 VALUE #212121 EDGE #545454 ALPHA 128 +Chrome_Antique_Brass CODE 60 VALUE #645A4C EDGE #665B4D CHROME +Chrome_Blue CODE 61 VALUE #6C96BF EDGE #3D638A CHROME +Chrome_Green CODE 62 VALUE #3CB371 EDGE #226741 CHROME +Chrome_Pink CODE 63 VALUE #AA4D8E EDGE #632C52 CHROME +Chrome_Black CODE 64 VALUE #1B2A34 EDGE #3D5F76 CHROME +Chrome_Gold CODE 334 VALUE #DFC176 EDGE #C2982E CHROME +Chrome_Silver CODE 383 VALUE #CECECE EDGE #9C9C9C CHROME +Pearl_Black CODE 83 VALUE #0A1327 EDGE #333333 PEARLESCENT +Copper CODE 134 VALUE #764D3B EDGE #333333 PEARLESCENT +Pearl_Light_Grey CODE 135 VALUE #A0A0A0 EDGE #333333 PEARLESCENT +Metallic_Blue CODE 137 VALUE #5B7590 EDGE #333333 PEARLESCENT +Pearl_Light_Gold CODE 142 VALUE #DEAC66 EDGE #333333 PEARLESCENT +Pearl_Dark_Gold CODE 147 VALUE #83724F EDGE #333333 PEARLESCENT +Pearl_Dark_Grey CODE 148 VALUE #484D48 EDGE #333333 PEARLESCENT +Pearl_Very_Light_Grey CODE 150 VALUE #989B99 EDGE #333333 PEARLESCENT +Pearl_Red CODE 176 VALUE #945148 EDGE #333333 PEARLESCENT +Pearl_Yellow CODE 178 VALUE #AB673A EDGE #333333 PEARLESCENT +Pearl_Silver CODE 179 VALUE #898788 EDGE #333333 PEARLESCENT +Pearl_White CODE 183 VALUE #F6F2DF EDGE #333333 PEARLESCENT +Metallic_Bright_Red CODE 184 VALUE #D60026 EDGE #333333 PEARLESCENT +Metallic_Bright_Blue CODE 185 VALUE #0059A3 EDGE #333333 PEARLESCENT +Metallic_Dark_Green CODE 186 VALUE #008E3C EDGE #333333 PEARLESCENT +Pearl_Brown CODE 187 VALUE #57392C EDGE #333333 PEARLESCENT +Reddish_Gold CODE 189 VALUE #AC8247 EDGE #333333 PEARLESCENT +Lemon_Metallic CODE 200 VALUE #708224 EDGE #333333 PEARLESCENT +Pearl_Gold CODE 297 VALUE #AA7F2E EDGE #333333 PEARLESCENT +Metallic_Silver CODE 80 VALUE #767676 EDGE #333333 METAL +Metallic_Green CODE 81 VALUE #C2C06F EDGE #333333 METAL +Metallic_Gold CODE 82 VALUE #DBAC34 EDGE #333333 METAL +Metallic_Dark_Grey CODE 87 VALUE #3E3C39 EDGE #333333 METAL +Metallic_Copper CODE 300 VALUE #C27F53 EDGE #333333 METAL +Metallic_Light_Blue CODE 10045 VALUE #97CBD9 EDGE #333333 METAL +Metallic_Pink CODE 10046 VALUE #AD659A EDGE #333333 METAL +Metallic_Light_Pink CODE 10049 VALUE #FECCCF EDGE #333333 METAL +Milky_White CODE 79 VALUE #EEEEEE EDGE #BABABA ALPHA 240 +Glow_In_Dark_Opaque CODE 21 VALUE #E0FFB0 EDGE #B8FF4D ALPHA 240 LUMINANCE 15 +Glow_In_Dark_Trans CODE 294 VALUE #BDC6AD EDGE #8D9D72 ALPHA 240 LUMINANCE 15 +Glow_In_Dark_White CODE 329 VALUE #F5F3D7 EDGE #E0DA85 ALPHA 240 LUMINANCE 15 +Glitter_Trans_Dark_Pink CODE 114 VALUE #DF6695 EDGE #B9275F ALPHA 128 MATERIAL GLITTER +Glitter_Trans_Clear CODE 117 VALUE #EEEEEE EDGE #BABABA ALPHA 128 MATERIAL GLITTER +Glitter_Trans_Purple CODE 129 VALUE #640061 EDGE #000000 ALPHA 128 MATERIAL GLITTER +Glitter_Trans_Light_Blue CODE 302 VALUE #AEE9EF EDGE #59D1DE ALPHA 128 MATERIAL GLITTER +Glitter_Trans_Neon_Green CODE 339 VALUE #C0FF00 EDGE #739900 ALPHA 128 MATERIAL GLITTER +Glitter_Trans_Orange CODE 341 VALUE #F08F1C EDGE #9E5C0A ALPHA 128 MATERIAL GLITTER +Opal_Trans_Clear CODE 360 VALUE #FCFCFC EDGE #C9C9C9 ALPHA 240 LUMINANCE 5 MATERIAL GLITTER +Opal_Trans_Light_Blue CODE 362 VALUE #AEE9EF EDGE #59D1DE ALPHA 200 LUMINANCE 5 MATERIAL GLITTER +Opal_Trans_Black CODE 363 VALUE #635F52 EDGE #2A2823 ALPHA 200 LUMINANCE 5 MATERIAL GLITTER +Opal_Trans_Dark_Pink CODE 364 VALUE #DF6695 EDGE #B9275F ALPHA 200 LUMINANCE 5 MATERIAL GLITTER +Opal_Trans_Purple CODE 365 VALUE #671F81 EDGE #441456 ALPHA 200 LUMINANCE 5 MATERIAL GLITTER +Opal_Trans_Green CODE 367 VALUE #237841 EDGE #174F2B ALPHA 200 LUMINANCE 5 MATERIAL GLITTER +Glitter_Trans_Bright_Green CODE 10351 VALUE #56E646 EDGE #27AF18 ALPHA 128 MATERIAL GLITTER +Opal_Trans_Dark_Blue CODE 10366 VALUE #0020A0 EDGE #000B38 ALPHA 200 LUMINANCE 5 MATERIAL GLITTER +Speckle_Black_Copper CODE 75 VALUE #000000 EDGE #AB6038 MATERIAL SPECKLE +Speckle_Dark_Bluish_Grey_Silver CODE 76 VALUE #635F61 EDGE #898788 MATERIAL SPECKLE +Speckle_Black_Silver CODE 132 VALUE #000000 EDGE #898788 MATERIAL SPECKLE +Speckle_Black_Gold CODE 133 VALUE #000000 EDGE #DBAC34 MATERIAL SPECKLE +Rubber_Yellow CODE 65 VALUE #FAC80A EDGE #333333 RUBBER +Rubber_Black CODE 256 VALUE #1B2A34 EDGE #808080 RUBBER +Rubber_Blue CODE 273 VALUE #1E5AA8 EDGE #333333 RUBBER +Rubber_Red CODE 324 VALUE #B40000 EDGE #333333 RUBBER +Rubber_Orange CODE 350 VALUE #D67923 EDGE #333333 RUBBER +Rubber_Light_Grey CODE 375 VALUE #8A928D EDGE #333333 RUBBER +Rubber_Dark_Blue CODE 406 VALUE #19325A EDGE #333333 RUBBER +Rubber_Purple CODE 449 VALUE #671F81 EDGE #333333 RUBBER +Rubber_Lime CODE 490 VALUE #A5CA18 EDGE #333333 RUBBER +Rubber_Light_Bluish_Grey CODE 496 VALUE #969696 EDGE #333333 RUBBER +Rubber_Flat_Silver CODE 504 VALUE #898788 EDGE #333333 RUBBER +Rubber_White CODE 511 VALUE #F4F4F4 EDGE #333333 RUBBER +Rubber_Green CODE 10002 VALUE #00852B EDGE #333333 RUBBER +Rubber_Bright_Green CODE 10010 VALUE #58AB41 EDGE #333333 RUBBER +Rubber_Tan CODE 10019 VALUE #D7BA8C EDGE #333333 RUBBER +Rubber_Magenta CODE 10026 VALUE #901F76 EDGE #333333 RUBBER +Rubber_Bright_Pink CODE 10029 VALUE #FF9ECD EDGE #333333 RUBBER +Rubber_Medium_Lavender CODE 10030 VALUE #A06EB9 EDGE #333333 RUBBER +Rubber_Lavender CODE 10031 VALUE #CDA4DE EDGE #333333 RUBBER +Rubber_Reddish_Brown CODE 10070 VALUE #5F3109 EDGE #808080 RUBBER +Rubber_Dark_Bluish_Grey CODE 10072 VALUE #646464 EDGE #333333 RUBBER +Rubber_Medium_Blue CODE 10073 VALUE #7396C8 EDGE #333333 RUBBER +Rubber_Light_Nougat CODE 10078 VALUE #FFC995 EDGE #333333 RUBBER +Rubber_Bright_Light_Yellow CODE 10226 VALUE #FFEC6C EDGE #333333 RUBBER +Rubber_Dark_Brown CODE 10308 VALUE #352100 EDGE #808080 RUBBER +Rubber_Dark_Red CODE 10320 VALUE #720012 EDGE #333333 RUBBER +Rubber_Dark_Azure CODE 10321 VALUE #469BC3 EDGE #333333 RUBBER +Rubber_Medium_Azure CODE 10322 VALUE #68C3E2 EDGE #333333 RUBBER +Rubber_Light_Aqua CODE 10323 VALUE #D3F2EA EDGE #333333 RUBBER +Rubber_Sand_Green CODE 10378 VALUE #708E7C EDGE #333333 RUBBER +Rubber_Dark_Orange CODE 10484 VALUE #91501C EDGE #333333 RUBBER +Rubber_Trans_Yellow CODE 66 VALUE #F5CD2F EDGE #B49208 ALPHA 128 RUBBER +Rubber_Trans_Clear CODE 67 VALUE #FCFCFC EDGE #C9C9C9 ALPHA 128 RUBBER +Rubber_Trans_Bright_Green CODE 10035 VALUE #56E646 EDGE #27AF18 ALPHA 128 RUBBER +Rubber_Trans_Red CODE 10036 VALUE #C91A09 EDGE #660D05 ALPHA 128 RUBBER +Rubber_Trans_Light_Blue CODE 10043 VALUE #AEE9EF EDGE #59D1DE ALPHA 128 RUBBER +Canvas_Black CODE 20000 VALUE #1B2A34 EDGE #808080 MATERIAL FABRIC +Canvas_Blue CODE 20001 VALUE #1E5AA8 EDGE #333333 MATERIAL FABRIC +Canvas_Green CODE 20002 VALUE #00852B EDGE #333333 MATERIAL FABRIC +Canvas_Red CODE 20004 VALUE #B40000 EDGE #333333 MATERIAL FABRIC +Canvas_Bright_Green CODE 20010 VALUE #58AB41 EDGE #333333 MATERIAL FABRIC +Canvas_Yellow CODE 20014 VALUE #FAC80A EDGE #333333 MATERIAL FABRIC +Canvas_White CODE 20015 VALUE #F4F4F4 EDGE #333333 MATERIAL FABRIC +Canvas_Reddish_Brown CODE 20070 VALUE #5F3109 EDGE #808080 MATERIAL FABRIC +Canvas_Light_Brown CODE 20086 VALUE #7B5D41 EDGE #333333 MATERIAL FABRIC +Canvas_Dark_Green CODE 20288 VALUE #00451A EDGE #808080 MATERIAL FABRIC +Canvas_Cream CODE 20500 VALUE #F8F3E4 EDGE #333333 MATERIAL FABRIC +Main_Colour CODE 16 VALUE #FFFF80 EDGE #333333 +Edge_Colour CODE 24 VALUE #7F7F7F EDGE #333333 +Magnet CODE 493 VALUE #656761 EDGE #333333 METAL +Electric_Contact_Alloy CODE 494 VALUE #D0D0D0 EDGE #333333 METAL +Electric_Contact_Copper CODE 495 VALUE #AE7A59 EDGE #333333 METAL +Trans_Sticker CODE 10047 VALUE #FFFFFF EDGE #FFFFFF ALPHA 16 +]] + +local cache: Table? = nil +function Colors.builtin(): Table + if not cache then + local t: Table = {} + for line in string.gmatch(BUILTIN, "[^\n]+") do + local code, c = Colors.entry(line) + if code and c then + t[code] = c + end + end + cache = t + end + local copy: Table = {} + for k, v in cache :: Table do + copy[k] = v + end + return copy +end + +return Colors +end +__FILES["model/ldraw/Read"] = function() + +-- model/ldraw/Read: LDraw text -> Types.Scene. Sub-files are tried as written (backslashes as slashes), then lower +-- case, under "", "parts/", "p/", "parts/s/" and "models/"; faces are written counter-clockwise after the matrices' +-- mirroring. +local Types = __include("Types") +local Colors = __include("model/ldraw/Colors") + +local Read = {} + +type Options = { + resolve: ((uri: string) -> any)?, + files: { [string]: any }?, + ldconfig: string?, + color: number?, + upright: boolean?, + flatten: boolean?, + lines: boolean?, + optionalLines: boolean?, + maxDepth: number?, + maxTriangles: number?, + maxNodes: number?, +} + +-- k = 0 (a BFC state change), 1 (a reference: v = x y z a b c d e f g h i), 2..5 +type Cmd = { k: number, c: number, v: { number }, name: string?, inv: boolean?, step: number?, cw: boolean?, clip: boolean? } +type File = { + name: string, + key: string, + cmds: { Cmd }, + certified: boolean, + org: string?, + refs: number, + library: boolean, + main: boolean, + title: string?, + author: string?, + model: boolean?, +} +type Group = { mode: string, colour: number, ds: boolean, pos: { number }, ctrl: { number }? } + +local PREFIXES = { "", "parts/", "p/", "parts/s/", "models/" } +local LIBRARY = { ["parts/"] = true, ["p/"] = true, ["parts/s/"] = true } +local FLIP = { 1, 0, 0, 0, 0, -1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1 } +local IDENTITY12 = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0 } + +local function norm(name: string): string + return string.lower((string.gsub(string.match(name, "^%s*(.-)%s*$") or name, "\\", "/"))) +end + +local function srgbToLinear(v: number): number + return if v <= 0.04045 then v / 12.92 else ((v + 0.055) / 1.055) ^ 2.4 +end + +local function parse(text: string, name: string, colours: Colors.Table, stats: { bad: number, lines: number }): File + local f: File = { name = name, key = norm(name), cmds = {}, certified = false, refs = 0, library = false, main = false } + local cmds = f.cmds + local invert, step, first = false, 1, true + for line in string.gmatch(text, "[^\n]+") do + local t = string.match(line, "^%s*(%d)%s") + if t then + stats.lines += 1 + end + if t == "0" then + local w1, rest = string.match(line, "^%s*0%s+(%S+)%s*(.-)%s*$") + if w1 == "BFC" and rest then + local u = string.upper(rest) + local cmd: Cmd? = nil + for word in string.gmatch(u, "%S+") do + if word == "CERTIFY" then + f.certified = true + elseif word == "NOCERTIFY" then + f.certified = false + elseif word == "INVERTNEXT" then + invert = true + elseif word == "CW" or word == "CCW" or word == "CLIP" or word == "NOCLIP" then + local c: Cmd = cmd or { k = 0, c = 0, v = IDENTITY12 } + cmd = c + if word == "CW" or word == "CCW" then + c.cw = word == "CW" + else + c.clip = word == "CLIP" + end + end + end + if cmd then + table.insert(cmds, cmd) + end + elseif w1 == "!COLOUR" then + Colors.parse(line, colours) + elseif w1 == "!LDRAW_ORG" and rest then + f.org = string.match(rest, "^(%S+)") + elseif w1 == "STEP" then + step += 1 + elseif w1 == "Author:" then + f.author = rest + elseif w1 == "Name:" or w1 == "FILE" or w1 == "NOFILE" or w1 == "!HISTORY" or w1 == "!LICENSE" then + elseif first and w1 and string.sub(w1, 1, 1) ~= "!" and w1 ~= "//" then + f.title = (string.match(line, "^%s*0%s+(.-)%s*$")) + end + first = false + elseif t then + first = false + local k = tonumber(t) :: number + local inv = invert + invert = false + if k == 1 then + local c, x, y, z, a, b, cc, d, e, ff, g, h, i, file = string.match(line, "^%s*1%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(.-)%s*$") + local v = { tonumber(a), tonumber(b), tonumber(cc), tonumber(x), tonumber(d), tonumber(e), tonumber(ff), tonumber(y), tonumber(g), tonumber(h), tonumber(i), tonumber(z) } + local code = tonumber(c) + local complete = true + for j = 1, 12 do + if v[j] == nil then + complete = false + end + end + if file and file ~= "" and complete and code and code >= 0 and code % 1 == 0 then + table.insert(cmds, { k = 1, c = code, v = v :: { number }, name = file, inv = inv, step = step }) + f.refs += 1 + else + stats.bad += 1 + end + elseif k >= 2 and k <= 5 then + local need = if k == 2 then 6 elseif k == 3 then 9 else 12 + local v: { number } = {} + local code: number? = nil + local n = 0 + for w in string.gmatch(line, "%S+") do + n += 1 + if n == 2 then + code = tonumber(w) + elseif n > 2 and n <= need + 2 then + local num = tonumber(w) + if not num then + break + end + v[n - 2] = num + end + end + if code and code >= 0 and code % 1 == 0 and #v == need then + table.insert(cmds, { k = k, c = code, v = v }) + else + stats.bad += 1 + end + elseif k ~= 0 then + stats.bad += 1 + end + end + end + return f +end + +function Read.scene(text: string, opts: Options?): (Types.Scene?, string?, string?) + local o: Options = opts or {} + local colours = Colors.builtin() + if type(o.ldconfig) == "string" then + Colors.parse(o.ldconfig, colours) + end + local maxDepth = o.maxDepth or 64 + local maxTriangles = o.maxTriangles or 2 ^ 24 + local maxNodes = o.maxNodes or 2 ^ 20 + local withLines = o.lines ~= false + local withOptional = o.optionalLines == true + local stats = { bad = 0, lines = 0 } + + -- ------------------------------------------------------------------------------------------ MPD sections + text = string.gsub(text, "\r", "") + local sections: { [string]: string } = {} + local mainName: string? = nil + local mpd = string.find(text, "^%s*0%s+FILE%s") ~= nil or string.find(text, "\n%s*0%s+FILE%s") ~= nil + local mainText = text + if mpd then + local cur: string? = nil + local buf: { string } = {} + local function close() + if cur and sections[cur] == nil then + sections[cur] = table.concat(buf, "\n") + end + cur, buf = nil, {} + end + for line in string.gmatch(text, "[^\n]+") do + local fname = string.match(line, "^%s*0%s+FILE%s+(.-)%s*$") + if fname then + close() + cur = norm(fname) + if not mainName then + mainName = fname + end + elseif string.find(line, "^%s*0%s+NOFILE%f[%W]") then + close() + elseif cur then + table.insert(buf, line) + end + end + close() + mainText = sections[norm(mainName or "")] or "" + end + + -- ------------------------------------------------------------------------------------------ files + local cache: { [string]: File | false } = {} + local missing: { [string]: boolean } = {} + local fetchFiles = o.files + local resolve = o.resolve + local function fetch(uri: string): string? + local v: any = if type(fetchFiles) == "table" then fetchFiles[uri] else nil + if v == nil and type(resolve) == "function" then + local ok, res = pcall(resolve, uri) + v = if ok then res else nil + end + return if type(v) == "buffer" then buffer.tostring(v) elseif type(v) == "string" then v else nil + end + local function lookup(name: string): File? + local key = norm(name) + local have = cache[key] + if have ~= nil then + return have or nil + end + local sec = sections[key] + if sec then + local f = parse(sec, name, colours, stats) + cache[key] = f + return f + end + local slash = string.gsub(string.match(name, "^%s*(.-)%s*$") or name, "\\", "/") + for _, prefix in PREFIXES do + for _, cand in { prefix .. slash, prefix .. key } do + local data = fetch(cand) + if data then + local f = parse((string.gsub(data, "\r", "")), name, colours, stats) + f.library = LIBRARY[prefix] == true + cache[key] = f + return f + end + end + end + missing[key] = true + cache[key] = false + return nil + end + local function isModel(f: File): boolean + local m = f.model + if m == nil then + local org = string.lower(f.org or "") + local orgPart = org ~= "" and not string.find(org, "model", 1, true) + if f.main then + m = not orgPart and f.refs > 0 + else + local ext = string.match(f.key, "%.(%w+)$") + m = not orgPart and not f.library and (ext == "ldr" or ext == "mpd") + end + f.model = m + end + return m :: boolean + end + + -- ------------------------------------------------------------------------------------------ colours, materials + local scene = Types.Scene.new() + local function edgeOf(c: number): number + local e = colours[c] + if e then + return e.edge + end + return if c >= 0x2000000 then 0x2000000 else 0x2333333 + end + local function resolveColour(code: number, cur: number): number + if code == 16 then + return cur + elseif code == 24 then + return edgeOf(cur) + end + return code + end + local materialOf: { [string]: number } = {} + local function material(col: number, ds: boolean): number + local key = col .. (if ds then "d" else "") + local have = materialOf[key] + if have then + return have + end + local entry = colours[col] + local rgb, alpha, name, finish = 0x7F7F7F, 255, "Unknown_" .. col, nil + if entry then + rgb, alpha, name, finish = entry.rgb, entry.alpha, entry.name, entry.finish + elseif col >= 0x2000000 and col < 0x4000000 then + rgb = col % 0x1000000 + alpha = if col >= 0x3000000 then 128 else 255 + name = string.format("#%06X", rgb) + elseif col >= 0x4000000 and col < 0x8000000 then + -- dithered: two 12-bit colours, shown as their mean + local lo, hi = col % 0x1000, (col // 0x1000) % 0x1000 + local function ch(v: number, s: number): number + return ((v // s) % 16) * 17 + end + rgb = ((ch(lo, 256) + ch(hi, 256)) // 2) * 65536 + ((ch(lo, 16) + ch(hi, 16)) // 2) * 256 + (ch(lo, 1) + ch(hi, 1)) // 2 + alpha = if col >= 0x7000000 then 0 elseif col >= 0x5000000 then 128 else 255 + name = string.format("Dither_%X", col) + end + local m = Types.Scene.material(name) + m.baseColor = { srgbToLinear((rgb // 65536) / 255), srgbToLinear(((rgb // 256) % 256) / 255), srgbToLinear((rgb % 256) / 255), alpha / 255 } + if alpha < 255 then + m.alphaMode = "blend" + end + m.doubleSided = ds + m.metallic = 0 + m.roughness = 0.35 + if finish == "CHROME" or finish == "METAL" then + m.metallic, m.roughness = 1, if finish == "CHROME" then 0.15 else 0.4 + elseif finish == "PEARLESCENT" or finish == "MATTE_METALLIC" then + m.metallic, m.roughness = 0.6, 0.45 + elseif finish == "RUBBER" then + m.roughness = 0.9 + end + m.extras = { ldraw = { code = col, name = name, edge = edgeOf(col), finish = finish, luminance = if entry and entry.luminance > 0 then entry.luminance else nil } } + table.insert(scene.materials, m) + materialOf[key] = #scene.materials + return #scene.materials + end + + -- ------------------------------------------------------------------------------------------ baking + local failure: string?, failKind: string? = nil, nil + local triangles = 0 + local cycles = 0 + local function fail(msg: string, kind: string?) + if not failure then + failure, failKind = msg, kind + end + end + + -- m is a 3x4 row-major matrix + local function bake(f: File, m: { number }, colour: number, inv: boolean, certified: boolean, depth: number, stack: { [File]: boolean }, groups: { [string]: Group }, order: { Group }, direct: boolean) + if failure then + return + end + if depth > maxDepth then + return fail("limit: sub-files nested deeper than " .. maxDepth, "limit") + end + stack[f] = true + local model = isModel(f) + local m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12 = table.unpack(m) + local det = m1 * (m6 * m11 - m7 * m10) - m2 * (m5 * m11 - m7 * m9) + m3 * (m5 * m10 - m6 * m9) + local cw, clip = false, true + local function group(mode: string, col: number, ds: boolean): Group + local key = mode .. col .. (if ds then "d" else "") + local g = groups[key] + if not g then + g = { mode = mode, colour = col, ds = ds, pos = {}, ctrl = if mode == "optional" then {} else nil } + groups[key] = g + table.insert(order, g) + end + return g + end + local function put(list: { number }, x: number, y: number, z: number) + local n = #list + list[n + 1] = m1 * x + m2 * y + m3 * z + m4 + list[n + 2] = m5 * x + m6 * y + m7 * z + m8 + list[n + 3] = m9 * x + m10 * y + m11 * z + m12 + end + for _, cmd in f.cmds do + if failure then + break + end + local k = cmd.k + local v = cmd.v + if k == 0 then + if cmd.cw ~= nil then + cw = cmd.cw :: boolean + end + if cmd.clip ~= nil then + clip = cmd.clip :: boolean + end + elseif k == 1 then + if not direct then + local sub = lookup(cmd.name :: string) + if sub and stack[sub] then + cycles += 1 + elseif sub then + local a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12 = table.unpack(v) + local child = { + m1 * a1 + m2 * a5 + m3 * a9, m1 * a2 + m2 * a6 + m3 * a10, m1 * a3 + m2 * a7 + m3 * a11, m1 * a4 + m2 * a8 + m3 * a12 + m4, + m5 * a1 + m6 * a5 + m7 * a9, m5 * a2 + m6 * a6 + m7 * a10, m5 * a3 + m6 * a7 + m7 * a11, m5 * a4 + m6 * a8 + m7 * a12 + m8, + m9 * a1 + m10 * a5 + m11 * a9, m9 * a2 + m10 * a6 + m11 * a10, m9 * a3 + m10 * a7 + m11 * a11, m9 * a4 + m10 * a8 + m11 * a12 + m12, + } + local childCert = if model then true else certified and f.certified and clip + bake(sub, child, resolveColour(cmd.c, colour), inv ~= (cmd.inv == true), childCert, depth + 1, stack, groups, order, false) + end + end + elseif k == 3 or k == 4 then + local col = resolveColour(cmd.c, colour) + local one = certified and f.certified and clip + local g = group("triangles", col, not one) + local rev = cw ~= inv ~= (det < 0) + local p = g.pos + local nt = if k == 3 then 1 else 2 + triangles += nt + if triangles > maxTriangles then + return fail(string.format("limit: more than %d triangles", maxTriangles), "limit") + end + local function tri(a: number, b: number, c: number) + if rev then + a, c = c, a + end + put(p, v[a * 3 + 1], v[a * 3 + 2], v[a * 3 + 3]) + put(p, v[b * 3 + 1], v[b * 3 + 2], v[b * 3 + 3]) + put(p, v[c * 3 + 1], v[c * 3 + 2], v[c * 3 + 3]) + end + tri(0, 1, 2) + if k == 4 then + tri(0, 2, 3) + end + elseif k == 2 and withLines then + local g = group("lines", resolveColour(cmd.c, colour), false) + put(g.pos, v[1], v[2], v[3]) + put(g.pos, v[4], v[5], v[6]) + elseif k == 5 and withOptional then + local g = group("optional", resolveColour(cmd.c, colour), false) + put(g.pos, v[1], v[2], v[3]) + put(g.pos, v[4], v[5], v[6]) + local ctrl = g.ctrl :: { number } + for _ = 1, 2 do + put(ctrl, v[7], v[8], v[9]) + put(ctrl, v[10], v[11], v[12]) + end + end + end + stack[f] = nil + end + + local function f32(list: { number }, from: number, step: number, count: number): Types.Accessor + local b = buffer.create(count * 12) + for i = 0, count - 1 do + local s = from + i * step + buffer.writef32(b, i * 12, list[s]) + buffer.writef32(b, i * 12 + 4, list[s + 1]) + buffer.writef32(b, i * 12 + 8, list[s + 2]) + end + return Types.Scene.accessor(b, "f32", 3, count) + end + + local meshOf: { [string]: number | false } = {} + local function meshFor(f: File, colour: number, inv: boolean, direct: boolean): number? + local key = f.key .. "|" .. colour .. "|" .. (if inv then "i" else "") .. (if direct then "d" else "") + local have = meshOf[key] + if have ~= nil then + return have or nil + end + local groups: { [string]: Group } = {} + local order: { Group } = {} + bake(f, IDENTITY12, colour, inv, true, 0, {}, groups, order, direct) + local mesh: Types.Mesh = { name = f.name, primitives = {} } + for _, g in order do + local count = #g.pos // 3 + if count > 0 then + local prim: Types.Primitive = { attributes = { POSITION = f32(g.pos, 1, 3, count) }, mode = if g.mode == "triangles" then "triangles" else "lines" } + prim.material = material(g.colour, g.ds) + if g.mode == "optional" then + local ctrl = g.ctrl :: { number } + prim.attributes._CONTROL_0 = f32(ctrl, 1, 6, count) + prim.attributes._CONTROL_1 = f32(ctrl, 4, 6, count) + prim.extras = { ldraw = { optional = true } } + end + table.insert(mesh.primitives, prim) + end + end + if #mesh.primitives == 0 then + meshOf[key] = false + return nil + end + table.insert(scene.meshes, mesh) + meshOf[key] = #scene.meshes + return #scene.meshes + end + + -- ------------------------------------------------------------------------------------------ the node tree + local mainFile = parse(mainText, mainName or "main", colours, stats) + mainFile.main = true + if stats.lines == 0 then + return nil, "no LDraw lines", nil + end + if mainName then + cache[norm(mainName)] = mainFile + end + local mainColour = o.color or 16 + local function newNode(node: Types.Node): number + table.insert(scene.nodes, node) + if #scene.nodes > maxNodes then + fail(string.format("limit: more than %d nodes", maxNodes), "limit") + end + return #scene.nodes + end + local function expand(f: File, colour: number, inv: boolean, out: { number }, depth: number, stack: { [File]: boolean }) + if failure then + return + end + if depth > maxDepth then + return fail("limit: sub-models nested deeper than " .. maxDepth, "limit") + end + stack[f] = true + local direct = meshFor(f, colour, inv, true) + if direct then + table.insert(out, newNode({ name = f.name, children = {}, mesh = direct })) + end + for _, cmd in f.cmds do + if failure then + break + end + if cmd.k == 1 then + local sub = lookup(cmd.name :: string) + if sub and stack[sub] then + cycles += 1 + elseif sub then + local v = cmd.v + local c = resolveColour(cmd.c, colour) + local subInv = inv ~= (cmd.inv == true) + local node: Types.Node = { + name = cmd.name, + children = {}, + matrix = { v[1], v[5], v[9], 0, v[2], v[6], v[10], 0, v[3], v[7], v[11], 0, v[4], v[8], v[12], 1 }, + extras = { ldraw = { file = sub.name, color = c, step = cmd.step, invert = if subInv then true else nil } }, + } + local index = newNode(node) + if isModel(sub) then + expand(sub, c, subInv, node.children, depth + 1, stack) + else + node.mesh = meshFor(sub, c, subInv, false) + end + table.insert(out, index) + end + end + end + stack[f] = nil + end + local top: { number } = {} + if o.flatten or not isModel(mainFile) then + local mesh = meshFor(mainFile, mainColour, false, false) + table.insert(top, newNode({ name = mainFile.name, children = {}, mesh = mesh })) + else + expand(mainFile, mainColour, false, top, 0, {}) + end + if failure then + return nil, failure, failKind + end + if o.upright == false then + scene.roots = top + else + table.insert(scene.nodes, { name = "LDraw", children = top, matrix = table.clone(FLIP) }) + scene.roots = { #scene.nodes } + scene.meta.up = "y" + end + scene.meta.unit = 0.0004 + local missingList: { string } = {} + for k in missing do + table.insert(missingList, k) + end + table.sort(missingList) + local nfiles = 0 + for _, f in cache do + if f then + nfiles += 1 + end + end + scene.meta.source = { + format = "ldraw", + mpd = mpd, + name = mainName, + title = mainFile.title, + author = mainFile.author, + files = nfiles, + missing = missingList, + cycles = cycles, + badLines = stats.bad, + up = if o.upright == false then "-y" else nil, + } + return scene, nil, nil +end + +return Read +end +__FILES["model/lwo"] = function() + +-- model/lwo: LightWave objects LWO2 (6+), LWOB (5.x) and Modo's LXOB, read; from the LWO2 / LWOB specs, checked against +-- assimp. Supports: layers, polygons, VMAP / VMAD, surfaces, clips. Left-handed: z negated, winding reversed. Not +-- supported: LWO3, envelopes, procedural / gradient textures, planar / cylindrical / spherical projections, smoothing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Parse = __include("model/lwo/Parse") +local Build = __include("model/lwo/Build") + +-- ------------------------------------------------------------------------------------------------ contract +local Lwo = { + name = "lwo", + category = "model", + extensions = { "lwo", "lxo" }, + mime = { "image/x-lwo", "model/x-lwo" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks" }, + caps = { decode = true, encode = false, materials = true, polygons = true, vertexColors = true, morphTargets = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + triangulate: boolean?, -- default true + maxVertices: number?, -- default 2^25 +} + +-- ------------------------------------------------------------------------------------------------ constants +local VERSIONS = { LWO2 = true, LWOB = true, LXOB = true } + +-- ------------------------------------------------------------------------------------------------ sniff +function Lwo.sniff(r: Bytes.Reader): number + if r:peek(4) ~= "FORM" then + return 0 + end + local v = r:peek(4, 8) + return if VERSIONS[v] then 1 elseif v == "LWO3" then 0.8 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Lwo.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + if r.limit - r.base < 12 then + return nil, Err.new(Err.TRUNCATED, "shorter than the FORM header", r.base) + end + if r:peek(4) ~= "FORM" then + return nil, Err.new(Err.CORRUPT, "not an IFF FORM", r.base) + end + local v = r:peek(4, 8) + if v == "LWO3" then + return nil, Err.new(Err.UNSUPPORTED, "LWO3 (LightWave 2018+) objects", r.base + 8) + end + if not VERSIONS[v] then + return nil, Err.new(Err.CORRUPT, "not a LightWave object (FORM type " .. string.format("%q", v) .. ")", r.base + 8) + end + local maxCorners = opts and opts.maxVertices or 2 ^ 25 + local ok, model, msg = pcall(Parse.model, r.buf, r.base, r.limit, maxCorners) + if not ok then + return nil, Err.new(Err.CORRUPT, "bad chunk data: " .. tostring(model)) + end + if not model then + return nil, Err.from(msg) + end + local ok2, scene, msg2 = pcall(Build.scene, model, opts) + if not ok2 then + return nil, Err.new(Err.CORRUPT, "bad object data: " .. tostring(scene)) + end + if not scene then + return nil, Err.from(msg2) + end + return scene, nil +end + +return Lwo +end +__FILES["model/lwo/Build"] = function() + +-- model/lwo/Build: a parsed LightWave object -> Types.Scene. LightWave is left-handed (y up, clockwise front faces): z +-- is negated and the winding reversed, as assimp does. Vertices are split where a VMAD gives a corner its own value. +local Types = __include("Types") +local Parse = __include("model/lwo/Parse") + +local Build = {} + +local Scene = Types.Scene +local writef32, writeu32 = buffer.writef32, buffer.writeu32 + +type Group = { material: number, class: string, polys: { number } } -- "poly" / "patch" / "line" / "point" + +local MIME: { [string]: string } = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", bmp = "image/bmp", tga = "image/x-tga", gif = "image/gif", tif = "image/tiff", tiff = "image/tiff", iff = "image/x-iff" } + +-- ------------------------------------------------------------------------------------------------ materials +local function textureIndex(scene: Types.Scene, cache: { [string]: number }, path: string): number + local hit = cache[path] + if hit then + return hit + end + local norm = string.gsub(path, "\\", "/") + local base = string.match(norm, "([^/:]+)$") or norm + local ext = string.lower(string.match(base, "%.(%w+)$") or "") + table.insert(scene.textures, { name = base, uri = base, mime = MIME[ext], extras = { lwo = { path = path } } }) + cache[path] = #scene.textures + return #scene.textures +end + +local function material(scene: Types.Scene, m: Parse.Model, surf: Parse.Surface, uvSets: { [string]: number }, cache: { [string]: number }): Types.Material + local mat = Scene.material(surf.name) + local v = surf.values + local c = surf.color + local tran = math.clamp(v.TRAN or 0, 0, 1) + mat.baseColor = { c[1], c[2], c[3], 1 - tran } + if tran > 0 then + mat.alphaMode = "blend" + end + mat.metallic = 0 + local gloss = v.GLOS + mat.roughness = if gloss and (v.SPEC or 0) > 0 then math.clamp(1 - gloss, 0, 1) else 1 + local lumi = v.LUMI or 0 + if lumi > 0 then + mat.emissive = { c[1] * lumi, c[2] * lumi, c[3] * lumi } + end + mat.doubleSided = surf.side == 3 + local maps = {} + local blocks = table.clone(surf.blocks) + table.sort(blocks, function(a: Parse.Block, b: Parse.Block): boolean + return a.ordinal < b.ordinal + end) + for _, blk in blocks do + local path = if blk.file then blk.file elseif blk.clip then m.clips[blk.clip] else nil + local entry: { [string]: any } = { kind = blk.kind, channel = blk.channel, enabled = blk.enabled, opacity = blk.opacity, projection = blk.projection, axis = blk.axis, uvmap = blk.uvmap } + if path and (blk.kind == "IMAP" or blk.kind == "TEX") then + local ti = textureIndex(scene, cache, path) + entry.texture = ti + if blk.enabled then + local ref: Types.TextureRef = { texture = ti } + if blk.uvmap and uvSets[blk.uvmap] then + ref.texCoord = uvSets[blk.uvmap] + end + if blk.channel == "COLR" and not mat.baseColorTexture then + mat.baseColorTexture = ref + elseif blk.channel == "LUMI" and not mat.emissiveTexture then + mat.emissiveTexture = ref + if lumi <= 0 then + mat.emissive = { 1, 1, 1 } + end + end + end + end + table.insert(maps, entry) + end + local extras: { [string]: any } = { color = table.clone(c), side = surf.side, maps = maps, source = surf.source } + for k, x in v do + extras[string.lower(k)] = x + end + if surf.vcol then + extras.vcol = surf.vcol.name + end + mat.extras = { lwo = extras } + return mat +end + +-- ------------------------------------------------------------------------------------------------ geometry +local function groupLayer(layer: Parse.Layer, surfaceOf: (number?) -> number): { Group } + local groups: { Group } = {} + local byKey: { [string]: Group } = {} + for i, poly in layer.polys do + local kind = poly.kind + local n = #poly.corners + if (kind == "FACE" or kind == "PTCH" or kind == "SUBD") and n > 0 then + local class = if n == 1 then "point" elseif n == 2 then "line" elseif kind == "FACE" then "poly" else "patch" + local mi = surfaceOf(poly.surf) + local key = mi .. class + local g = byKey[key] + if not g then + g = { material = mi, class = class, polys = {} } + byKey[key] = g + table.insert(groups, g) + end + table.insert(g.polys, i - 1) + end + end + local rank: { [string]: number } = { poly = 1, patch = 2, line = 3, point = 4 } + table.sort(groups, function(a: Group, b: Group): boolean + if a.material ~= b.material then + return a.material < b.material + end + return rank[a.class] < rank[b.class] + end) + return groups +end + +local function ordered(corners: { number }): { number } + local n = #corners + local out = table.create(n) :: { number } + out[1] = corners[1] + for k = 2, n do + out[k] = corners[n - k + 2] + end + return out +end + +type Attr = { map: Parse.Map, name: string, comps: number } + +local function primitive(layer: Parse.Layer, g: Group, attrs: { Attr }, morphs: { Parse.Map }, triangulate: boolean): Types.Primitive + local pts, pivot = layer.pts, layer.pivot + local vertOf: { [number]: number } = {} + local srcPoint: { number } = {} + local srcPoly: { number } = {} -- -1: none + local indices: { number } = {} + local faces: { number } = {} + local madMaps: { Parse.Map } = {} + for _, a in attrs do + if next(a.map.mad) then + table.insert(madMaps, a.map) + end + end + for _, m in morphs do + if next(m.mad) then + table.insert(madMaps, m) + end + end + local function vertex(f: number, p: number): number + local own = false + for _, m in madMaps do + local row = m.mad[f] + if row and row[p] then + own = true + break + end + end + if not own then + local v = vertOf[p] + if v then + return v + end + end + table.insert(srcPoint, p) + table.insert(srcPoly, if own then f else -1) + local v = #srcPoint - 1 + if not own then + vertOf[p] = v + end + return v + end + for _, f in g.polys do + local corners = ordered(layer.polys[f + 1].corners) + local n = #corners + local vs = table.create(n) :: { number } + for k = 1, n do + vs[k] = vertex(f, corners[k]) + end + if g.class == "poly" or g.class == "patch" then + if triangulate then + for k = 2, n - 1 do + table.insert(indices, vs[1]) + table.insert(indices, vs[k]) + table.insert(indices, vs[k + 1]) + end + else + table.insert(faces, n) + table.move(vs, 1, n, #indices + 1, indices) + end + else + table.move(vs, 1, n, #indices + 1, indices) + end + end + local nv = #srcPoint + local pos = buffer.create(nv * 12) + for v = 1, nv do + local p = srcPoint[v] * 3 + local o = (v - 1) * 12 + writef32(pos, o, pts[p + 1] - pivot[1]) + writef32(pos, o + 4, pts[p + 2] - pivot[2]) + writef32(pos, o + 8, -(pts[p + 3] - pivot[3])) + end + local attributes: { [string]: Types.Accessor } = { POSITION = Scene.accessor(pos, "f32", 3, nv) } + local function value(m: Parse.Map, v: number): ({ number }?, number?) + local f = srcPoly[v] + if f >= 0 then + local row = m.mad[f] + local hit = row and row[srcPoint[v]] + if hit then + return hit, nil + end + end + local p = srcPoint[v] + if m.has[p] then + return nil, p * m.dims + end + return nil, nil + end + local names: { [string]: string } = {} + for _, a in attrs do + local m, comps = a.map, a.comps + local data = buffer.create(nv * comps * 4) + for v = 1, nv do + local o = (v - 1) * comps * 4 + local direct, at = value(m, v) + local x: { number } = if direct then direct elseif at then { m.vals[at + 1], m.vals[at + 2] or 0, m.vals[at + 3] or 0, m.vals[at + 4] or 1 } else {} + if m.kind == "uv" then + writef32(data, o, x[1] or 0) + writef32(data, o + 4, 1 - (x[2] or 0)) + elseif m.kind == "color" then + writef32(data, o, x[1] or 1) + writef32(data, o + 4, x[2] or 1) + writef32(data, o + 8, x[3] or 1) + writef32(data, o + 12, if m.dims == 4 and x[4] then x[4] else 1) + elseif m.kind == "normal" then + writef32(data, o, x[1] or 0) + writef32(data, o + 4, x[2] or 0) + writef32(data, o + 8, -(x[3] or 0)) + else + writef32(data, o, x[1] or 0) + end + end + attributes[a.name] = Scene.accessor(data, "f32", comps, nv) + names[a.name] = m.name + end + local prim: Types.Primitive = { attributes = attributes, mode = "triangles" } + if #morphs > 0 then + local targets: { { [string]: Types.Accessor } } = {} + local targetNames: { string } = {} + for _, m in morphs do + local d = buffer.create(nv * 12) + for v = 1, nv do + local direct, at = value(m, v) + local x: { number }? = if direct then direct elseif at then { m.vals[at + 1], m.vals[at + 2], m.vals[at + 3] } else nil + if x then + local p = srcPoint[v] * 3 + local dx, dy, dz = x[1], x[2], x[3] + if m.kind == "spot" then + dx, dy, dz = dx - pts[p + 1], dy - pts[p + 2], dz - pts[p + 3] + end + writef32(d, (v - 1) * 12, dx) + writef32(d, (v - 1) * 12 + 4, dy) + writef32(d, (v - 1) * 12 + 8, -dz) + end + end + local tgt: { [string]: Types.Accessor } = { POSITION = Scene.accessor(d, "f32", 3, nv) } + table.insert(targets, tgt) + table.insert(targetNames, m.name) + end + prim.targets = targets + names._targets = table.concat(targetNames, "\n") + end + local ib = buffer.create(#indices * 4) + for k, x in indices do + writeu32(ib, (k - 1) * 4, x) + end + prim.indices = Scene.accessor(ib, "u32", 1, #indices) + if g.class == "line" then + prim.mode = "lines" + elseif g.class == "point" then + prim.mode = "points" + elseif not triangulate then + prim.mode = "polygons" + local fb = buffer.create(#faces * 4) + for k, x in faces do + writeu32(fb, (k - 1) * 4, x) + end + prim.faces = Scene.accessor(fb, "u32", 1, #faces) + end + prim.material = g.material + local extras: { [string]: any } = { maps = names } + if g.class == "patch" then + extras.subdivision = true + end + prim.extras = { lwo = extras } + return prim +end + +-- ------------------------------------------------------------------------------------------------ scene +function Build.scene(m: Parse.Model, opts: { triangulate: boolean? }?): (Types.Scene?, string?) + local triangulate = not (opts and opts.triangulate == false) + local scene = Scene.new() + scene.meta.up = "y" + scene.meta.source = { format = "lwo", version = m.version, skipped = m.skipped } + -- every TXUV map name, in order of first appearance, gets one TEXCOORD_n index + local uvSets: { [string]: number } = {} + local nuv = 0 + for _, layer in m.layers do + for _, map in layer.maps do + if map.kind == "uv" and uvSets[map.name] == nil then + uvSets[map.name] = nuv + nuv += 1 + end + end + end + local texCache: { [string]: number } = {} + local bySurfName: { [string]: number } = {} + for i, surf in m.surfaces do + scene.materials[i] = material(scene, m, surf, uvSets, texCache) + if bySurfName[surf.name] == nil then + bySurfName[surf.name] = i + end + local low = string.lower(surf.name) + if bySurfName[low] == nil then + bySurfName[low] = i + end + end + local tagMat: { [number]: number } = {} + local default: number? = nil + local function surfaceOf(tag: number?): number + if tag ~= nil then + local hit = tagMat[tag] + if hit then + return hit + end + local name = m.tags[tag + 1] + if name then + local mi = bySurfName[name] or bySurfName[string.lower(name)] + if not mi then + table.insert(scene.materials, Scene.material(name)) + mi = #scene.materials + bySurfName[name] = mi + end + tagMat[tag] = mi + return mi + end + end + if not default then + local mat = Scene.material("Default") + mat.baseColor = { 0.6, 0.6, 0.6, 1 } + mat.metallic = 0 + table.insert(scene.materials, mat) + default = #scene.materials + end + return default :: number + end + local nodeOf: { [number]: number } = {} + local layerOfNode: { Parse.Layer } = {} + for _, layer in m.layers do + local hasGeometry = #layer.polys > 0 + if not (layer.implicit and not hasGeometry) then + local node: Types.Node = { name = layer.name, children = {} } + table.insert(scene.nodes, node) + local ni = #scene.nodes + layerOfNode[ni] = layer + if nodeOf[layer.index] == nil then + nodeOf[layer.index] = ni + end + node.extras = { lwo = { index = layer.index, parent = layer.parent, pivot = table.clone(layer.pivot) } } + local groups = groupLayer(layer, surfaceOf) + if #groups > 0 then + local attrs: { Attr } = {} + local morphs: { Parse.Map } = {} + local hasUv = {} + local maxUv = -1 + for _, map in layer.maps do + if map.kind == "uv" then + hasUv[uvSets[map.name]] = map + maxUv = math.max(maxUv, uvSets[map.name]) + elseif map.kind == "morph" or map.kind == "spot" then + table.insert(morphs, map) + end + end + local empty: Parse.Map = { kind = "uv", name = "", dims = 2, vals = {}, has = {}, mad = {} } + for k = 0, maxUv do + table.insert(attrs, { map = hasUv[k] or empty, name = "TEXCOORD_" .. k, comps = 2 }) + end + local nw, nc, hasNormal = 0, 0, false + for _, map in layer.maps do + if map.kind == "normal" and not hasNormal then + hasNormal = true + table.insert(attrs, { map = map, name = "NORMAL", comps = 3 }) + elseif map.kind == "weight" then + table.insert(attrs, { map = map, name = "_WEIGHT_" .. nw, comps = 1 }) + nw += 1 + end + end + local prims = {} + for _, g in groups do + local mat = scene.materials[g.material] + local ex: any = mat and mat.extras + local vcol = ex and ex.lwo and ex.lwo.vcol + local pa = table.clone(attrs) + nc = 0 + for _, map in layer.maps do + if map.kind == "color" then + if map.name == vcol then + table.insert(pa, { map = map, name = "COLOR_0", comps = 4 }) + else + table.insert(pa, { map = map, name = "_COLOR_" .. nc, comps = 4 }) + nc += 1 + end + end + end + table.insert(prims, primitive(layer, g, pa, morphs, triangulate)) + end + local mesh: Types.Mesh = { name = layer.name, primitives = prims } + if #morphs > 0 then + mesh.weights = table.create(#morphs, 0) + local tn = {} + for _, mp in morphs do + table.insert(tn, mp.name) + end + mesh.extras = { targetNames = tn } + end + table.insert(scene.meshes, mesh) + node.mesh = #scene.meshes + end + end + end + -- a parent link that would close a cycle is dropped + local parentOf: { [number]: number } = {} + for ni, layer in layerOfNode do + local pi = if layer.parent ~= nil then nodeOf[layer.parent] else nil + if pi and pi ~= ni then + local up, steps = pi, 0 + while up and up ~= ni and steps <= #scene.nodes do + up = parentOf[up] + steps += 1 + end + if up ~= ni then + parentOf[ni] = pi + end + end + end + for ni = 1, #scene.nodes do + local layer = layerOfNode[ni] + local pi = parentOf[ni] + local pp = if pi then layerOfNode[pi].pivot else { 0, 0, 0 } + local t = { layer.pivot[1] - pp[1], layer.pivot[2] - pp[2], -(layer.pivot[3] - pp[3]) } + if t[1] ~= 0 or t[2] ~= 0 or t[3] ~= 0 then + scene.nodes[ni].translation = t + end + if pi then + table.insert(scene.nodes[pi].children, ni) + else + table.insert(scene.roots, ni) + end + end + return scene, nil +end + +return Build +end +__FILES["model/lwo/Parse"] = function() + +-- model/lwo/Parse: LightWave object chunks -> plain tables. From the LWO2 specification (LightWave 6 "Object Files", +-- Ernie Wright) and the LWOB one (LightWave 5.x), checked against assimp (no code taken). Several PNTS per layer: later +-- POLS / VMAP indices are relative to the latest. Not read: envelopes (ENVL), LWO3, Modo ITEM / ACTN chunks. +local Bytes = __include("core/Bytes") +local Chunks = __include("containers/Chunks") + +local Parse = {} + +type Map = { + kind: string, -- "uv" | "color" | "normal" | "weight" | "morph" | "spot" + name: string, + dims: number, + vals: { number }, -- vals[point * dims + c + 1] + has: { [number]: boolean }, + mad: { [number]: { [number]: { number } } }, -- VMAD: mad[poly][point] = values +} +type Poly = { kind: string, surf: number?, corners: { number } } -- 0-based point indices +type Layer = { + index: number, + name: string?, + parent: number?, + pivot: { number }, + pts: { number }, + polys: { Poly }, + maps: { Map }, + implicit: boolean?, -- the layer before any LAYR +} +type Block = { + kind: string, -- IMAP / PROC / GRAD / SHDR, or "TEX" (LWOB) + ordinal: string, + channel: string, -- COLR, DIFF, LUMI, SPEC, GLOS, REFL, TRAN, RIND, TRNL, BUMP + enabled: boolean, + opacity: number, + projection: number?, -- 0 planar, 1 cylindrical, 2 spherical, 3 cubic, 4 front, 5 UV + axis: number?, + clip: number?, + file: string?, -- LWOB: the TIMG path + uvmap: string?, + wrap: { number }?, + negative: boolean?, +} +type Surface = { + name: string, + values: { [string]: number }, + color: { number }, + side: number, + vcol: { name: string, kind: string, intensity: number }?, + blocks: { Block }, + source: string?, +} +type Model = { + version: string, -- "LWO2" | "LWOB" | "LXOB" + tags: { string }, + layers: { Layer }, + surfaces: { Surface }, + clips: { [number]: string }, + skipped: { [string]: number }, + corners: number, +} + +local MAP_KINDS: { [string]: string } = { + TXUV = "uv", + RGB = "color", + RGBA = "color", + WGHT = "weight", + MNVW = "weight", + NORM = "normal", + MORF = "morph", + SPOT = "spot", +} + +-- ------------------------------------------------------------------------------------------------ primitives +-- S0: NUL-terminated, padded to an even length +local function s0(r: Bytes.Reader): string + local start = r.pos + local s = r:cstring() + if (r.pos - start) % 2 == 1 and r.pos < r.limit then + r.pos += 1 + end + return s +end + +-- VX: 2 bytes, or 4 bytes after an 0xFF byte +local function vx(r: Bytes.Reader): number + if r:peekU8() == 0xFF then + return r:u32be() - 0xFF000000 + end + return r:u16be() +end + +local function id4(r: Bytes.Reader): string + local s = r:string(4) + return (string.gsub(s, " +$", "")) +end + +-- LWO2 sub-chunks: 4-byte id, 2-byte size, padded to even +local function subchunks(buf: buffer, p: number, e: number, f: (string, Bytes.Reader) -> ()) + while p + 6 <= e do + local id = buffer.readstring(buf, p, 4) + local n = buffer.readu8(buf, p + 4) * 256 + buffer.readu8(buf, p + 5) + local body = p + 6 + local avail = math.min(n, e - body) + f((string.gsub(id, " +$", "")), Bytes.reader(buf, body, avail)) + p = body + n + (n % 2) + end +end + +-- ------------------------------------------------------------------------------------------------ geometry +local function newLayer(index: number): Layer + return { index = index, name = nil, parent = nil, pivot = { 0, 0, 0 }, pts = {}, polys = {}, maps = {} } +end + +local function readPoints(r: Bytes.Reader, layer: Layer, limit: number): string? + local n = r:remaining() // 12 + if #layer.pts // 3 + n > limit then + return "limit: more than " .. limit .. " points" + end + local pts = layer.pts + local k = #pts + for _ = 1, n * 3 do + k += 1 + pts[k] = r:f32be() + end + return nil +end + +local function readPolys(r: Bytes.Reader, layer: Layer, kind: string, ptBase: number, budget: { number }): string? + local polys = layer.polys + local npts = #layer.pts // 3 + while r:remaining() >= 2 do + local n = bit32.band(r:u16be(), 0x3FF) + local corners = table.create(n) :: { number } + for i = 1, n do + local p = vx(r) + ptBase + if p >= npts and not r.err then + return "polygon point index " .. p .. " out of range (" .. npts .. " points)" + end + corners[i] = p + end + if r.err then + return "truncated polygon list" + end + budget[1] -= n + if budget[1] < 0 then + return "limit: too many polygon corners" + end + table.insert(polys, { kind = kind, surf = nil, corners = corners }) + end + return nil +end + +-- POLS (LWOB): n, n x U2, surface I2 (negative: detail polygons follow, after a U2 count) +local function readPolysB(r: Bytes.Reader, layer: Layer, budget: { number }): string? + local polys = layer.polys + local npts = #layer.pts // 3 + while r:remaining() >= 4 do + local n = r:u16be() + local corners = table.create(n) :: { number } + for i = 1, n do + local p = r:u16be() + if p >= npts and not r.err then + return "polygon point index " .. p .. " out of range (" .. npts .. " points)" + end + corners[i] = p + end + local surf = r:i16be() + if r.err then + return "truncated polygon list" + end + if surf < 0 then + surf = -surf + r:u16be() -- the detail polygon count: they follow as ordinary records + end + budget[1] -= n + if budget[1] < 0 then + return "limit: too many polygon corners" + end + if n > 0 then + table.insert(polys, { kind = "FACE", surf = surf - 1, corners = corners }) + end + end + return nil +end + +local function findMap(layer: Layer, kind: string, name: string, dims: number): Map + for _, m in layer.maps do + if m.kind == kind and m.name == name then + return m + end + end + local m: Map = { kind = kind, name = name, dims = dims, vals = {}, has = {}, mad = {} } + table.insert(layer.maps, m) + return m +end + +local function readVmap(r: Bytes.Reader, layer: Layer, perPoly: boolean, ptBase: number, polyBase: number, skipped: { [string]: number }) + local typ = id4(r) + local dims = r:u16be() + local name = s0(r) + local kind = MAP_KINDS[typ] + if r.err or not kind then + skipped["VMAP." .. typ] = (skipped["VMAP." .. typ] or 0) + 1 + return + end + local want = if kind == "uv" then 2 elseif kind == "color" then 4 elseif kind == "weight" then 1 else 3 + if dims < 1 or dims > 16 or (kind ~= "color" and dims < want) or (kind == "color" and dims < 3) then + skipped["VMAP." .. typ] = (skipped["VMAP." .. typ] or 0) + 1 + return + end + local m = findMap(layer, kind, name, want) + local npts = #layer.pts // 3 + local npolys = #layer.polys + local vals, has, mad = m.vals, m.has, m.mad + while r:remaining() >= 2 do + local p = vx(r) + ptBase + local f = if perPoly then vx(r) + polyBase else -1 + local v = table.create(want, 1) :: { number } + for c = 1, dims do + local x = r:f32be() + if c <= want then + v[c] = x + end + end + if r.err then + break + end + if p < npts then + if perPoly then + if f < npolys then + local row = mad[f] + if not row then + row = {} + mad[f] = row + end + row[p] = v + end + else + has[p] = true + for c = 1, want do + vals[p * want + c] = v[c] + end + end + end + end +end + +local function readPtag(r: Bytes.Reader, layer: Layer, polyBase: number) + local typ = id4(r) + if typ ~= "SURF" and typ ~= "MATR" then + return + end + local polys = layer.polys + while r:remaining() >= 4 do + local f = vx(r) + polyBase + local tag = r:u16be() + if r.err then + break + end + local poly = polys[f + 1] + if poly then + poly.surf = tag + end + end +end + +-- ------------------------------------------------------------------------------------------------ surfaces +local function newSurface(name: string): Surface + return { name = name, values = {}, color = { 0.78, 0.78, 0.78 }, side = 1, vcol = nil, blocks = {}, source = nil } +end + +local SURF_VALUES = { DIFF = true, LUMI = true, SPEC = true, REFL = true, TRAN = true, TRNL = true, GLOS = true, BUMP = true, SMAN = true, RIND = true } + +local function readBlock(r: Bytes.Reader, surf: Surface) + -- IMAP / PROC / GRAD / SHDR header: ordinal string, header sub-chunks + if r:remaining() < 6 then + return + end + local kind = id4(r) + local hn = r:u16be() + local hend = math.min(r.pos + hn, r.limit) + local blk: Block = { kind = kind, ordinal = "", channel = "COLR", enabled = true, opacity = 1 } + local hr = Bytes.reader(r.buf, r.pos, hend - r.pos) + blk.ordinal = s0(hr) + subchunks(r.buf, hr.pos, hend, function(id: string, sr: Bytes.Reader) + if id == "CHAN" then + blk.channel = id4(sr) + elseif id == "ENAB" then + blk.enabled = sr:u16be() ~= 0 + elseif id == "OPAC" then + sr:u16be() + blk.opacity = sr:f32be() + elseif id == "NEGA" then + blk.negative = sr:u16be() ~= 0 + elseif id == "AXIS" then + blk.axis = sr:u16be() + end + end) + subchunks(r.buf, hend + (hn % 2), r.limit, function(id: string, sr: Bytes.Reader) + if id == "PROJ" then + blk.projection = sr:u16be() + elseif id == "AXIS" then + blk.axis = sr:u16be() + elseif id == "IMAG" then + blk.clip = vx(sr) + elseif id == "VMAP" then + blk.uvmap = s0(sr) + elseif id == "WRAP" then + blk.wrap = { sr:u16be(), sr:u16be() } + end + end) + table.insert(surf.blocks, blk) +end + +local function readSurface(r: Bytes.Reader, surfaces: { Surface }) + local name = s0(r) + local source = s0(r) + local surf = newSurface(name) + if source ~= "" then + for _, s in surfaces do + if s.name == source then + surf.values = table.clone(s.values) + surf.color = table.clone(s.color) + surf.side = s.side + surf.vcol = s.vcol + surf.blocks = table.clone(s.blocks) + break + end + end + surf.source = source + end + subchunks(r.buf, r.pos, r.limit, function(id: string, sr: Bytes.Reader) + if id == "COLR" then + local c = { sr:f32be(), sr:f32be(), sr:f32be() } + if not sr.err then + surf.color = c + end + elseif SURF_VALUES[id] then + local v = sr:f32be() + if not sr.err then + surf.values[id] = v + end + elseif id == "SIDE" then + surf.side = sr:u16be() + elseif id == "VCOL" then + local intensity = sr:f32be() + vx(sr) + local kind = id4(sr) + local vname = s0(sr) + if not sr.err then + surf.vcol = { name = vname, kind = kind, intensity = intensity } + end + elseif id == "BLOK" then + readBlock(sr, surf) + end + end) + table.insert(surfaces, surf) +end + +-- LWOB surfaces: U2 percentages (256 = 100%), V* floats, texture sub-chunks +local B_VALUES = { DIFF = "DIFF", LUMI = "LUMI", SPEC = "SPEC", REFL = "REFL", TRAN = "TRAN" } +local B_FLOATS = { VDIF = "DIFF", VLUM = "LUMI", VSPC = "SPEC", VRFL = "REFL", VTRN = "TRAN" } +local B_TEX = { CTEX = "COLR", DTEX = "DIFF", STEX = "SPEC", RTEX = "REFL", TTEX = "TRAN", LTEX = "LUMI", BTEX = "BUMP" } +local B_PROJ: { [string]: number } = { Planar = 0, Cylindrical = 1, Spherical = 2, Cubic = 3, Front = 4 } + +local function readSurfaceB(r: Bytes.Reader, surfaces: { Surface }) + local surf = newSurface(s0(r)) + local tex: Block? = nil + subchunks(r.buf, r.pos, r.limit, function(id: string, sr: Bytes.Reader) + if id == "COLR" then + local c = { sr:u8() / 255, sr:u8() / 255, sr:u8() / 255 } + if not sr.err then + surf.color = c + end + elseif B_VALUES[id] then + local v = sr:u16be() + if not sr.err and surf.values[B_VALUES[id] .. "!"] == nil then + surf.values[B_VALUES[id]] = v / 256 + end + elseif B_FLOATS[id] then + local v = sr:f32be() + if not sr.err then + surf.values[B_FLOATS[id]] = v + surf.values[B_FLOATS[id] .. "!"] = 1 -- a float value wins over the U2 one + end + elseif id == "GLOS" then + local v = sr:u16be() + if not sr.err then + -- 16, 64, 256, 1024 = low .. very high: as LWO2's 0..1 glossiness + surf.values.GLOS = math.clamp(math.log(math.max(v, 1), 2) / 10, 0, 1) + end + elseif id == "SMAN" then + surf.values.SMAN = sr:f32be() + elseif id == "FLAG" then + local fl = sr:u16be() + if bit32.band(fl, 0x100) ~= 0 then + surf.side = 3 + end + elseif B_TEX[id] then + local desc = sr:cstring() + local proj: number? = nil + for word, v in B_PROJ do + if string.find(desc, word, 1, true) then + proj = v + end + end + local blk: Block = { kind = if string.find(desc, "Image Map", 1, true) then "TEX" else "PROC", ordinal = tostring(#surf.blocks + 1), channel = B_TEX[id], enabled = true, opacity = 1, projection = proj } + table.insert(surf.blocks, blk) + tex = blk + elseif id == "TIMG" and tex then + local path = sr:cstring() + if path ~= "" and path ~= "(none)" then + tex.file = path + end + elseif id == "TFLG" and tex then + local fl = sr:u16be() + tex.axis = if bit32.band(fl, 1) ~= 0 then 0 elseif bit32.band(fl, 2) ~= 0 then 1 else 2 + tex.negative = bit32.band(fl, 16) ~= 0 + elseif id == "TVAL" and tex then + tex.opacity = sr:u16be() / 256 + end + end) + for k in surf.values do + if string.sub(k, -1) == "!" then + surf.values[k] = nil + end + end + table.insert(surfaces, surf) +end + +local function readClip(r: Bytes.Reader, clips: { [number]: string }, refs: { [number]: number }) + local index = r:u32be() + if r.err then + return + end + subchunks(r.buf, r.pos, r.limit, function(id: string, sr: Bytes.Reader) + if id == "STIL" then + clips[index] = s0(sr) + elseif id == "ISEQ" then + local digits = sr:u8() + sr:u8() + local offset = sr:i16be() + sr:u16be() + local start = sr:i16be() + sr:u16be() + local prefix = s0(sr) + local suffix = s0(sr) + if not sr.err then + clips[index] = prefix .. string.format("%0" .. math.clamp(digits, 1, 9) .. "d", offset + start) .. suffix + end + elseif id == "XREF" then + refs[index] = sr:u32be() + end + end) +end + +-- ------------------------------------------------------------------------------------------------ the file +function Parse.model(buf: buffer, from: number, limit: number, maxCorners: number): (Model?, string?) + local version = buffer.readstring(buf, from + 8, 4) + local declared = bit32.byteswap(buffer.readu32(buf, from + 4)) + local e = math.min(limit, from + 8 + declared) + local model: Model = { version = version, tags = {}, layers = {}, surfaces = {}, clips = {}, skipped = {}, corners = 0 } + local layer = newLayer(0) + layer.implicit = true + table.insert(model.layers, layer) + local ptBase, polyBase = 0, 0 + local budget = { maxCorners } + local refs: { [number]: number } = {} + local lwob = version == "LWOB" + local list = Chunks.walk(buf, from + 12, e, Chunks.IFF) + for _, c in list do + local id = c.id + local r = Bytes.reader(buf, c.offset, c.avail) + local err: string? = nil + if id == "TAGS" or id == "SRFS" then + while r:remaining() > 0 do + table.insert(model.tags, s0(r)) + end + elseif id == "LAYR" and not lwob then + local index = r:u16be() + r:u16be() -- flags (hidden) + local px, py, pz = r:f32be(), r:f32be(), r:f32be() + local name = s0(r) + local parent: number? = if r:remaining() >= 2 then r:u16be() else nil + if r.err then + return nil, "truncated LAYR chunk" + end + if layer.implicit and #layer.pts == 0 and #layer.polys == 0 then + table.remove(model.layers, #model.layers) + end + layer = newLayer(index) + layer.name = name + layer.parent = if parent == 0xFFFF then nil else parent + layer.pivot = { px, py, pz } + table.insert(model.layers, layer) + ptBase, polyBase = 0, 0 + elseif id == "PNTS" then + ptBase = #layer.pts // 3 + err = readPoints(r, layer, maxCorners) + elseif id == "POLS" then + polyBase = #layer.polys + if lwob then + err = readPolysB(r, layer, budget) + else + local kind = id4(r) + if kind == "FACE" or kind == "PTCH" or kind == "SUBD" then + err = readPolys(r, layer, kind, ptBase, budget) + else + -- PTAG / VMAD refer to the polygon numbering: keep it, skip the geometry + local before = #layer.polys + err = readPolys(r, layer, kind, ptBase, budget) + model.skipped[kind] = (model.skipped[kind] or 0) + #layer.polys - before + end + end + elseif id == "VMAP" or id == "VMAD" then + readVmap(r, layer, id == "VMAD", ptBase, polyBase, model.skipped) + elseif id == "PTAG" then + readPtag(r, layer, polyBase) + elseif id == "SURF" then + if lwob then + readSurfaceB(r, model.surfaces) + else + readSurface(r, model.surfaces) + end + elseif id == "CLIP" then + readClip(r, model.clips, refs) + end + if err then + return nil, err + end + end + for index, target in refs do + if model.clips[index] == nil and model.clips[target] then + model.clips[index] = model.clips[target] + end + end + model.corners = maxCorners - budget[1] + return model, nil +end + +return Parse +end +end + + + + + + model_3 + --!optimize 2 +--!nocheck +-- rosetta chunk model_3 (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 23 modules (1 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["model/mca"] = function() + +-- model/mca: Minecraft Anvil region files (wiki "Region file format", "Chunk format"), read-only. Supports: gzip, zlib, +-- LZ4 (lz4-java blocks, 24w04a+) and stored chunks, external .mcc chunks, every chunk layout back to pre-1.13. +-- Not supported: writing; custom (127) compression; LZ4 checksums; the separate 1.17+ entities/ region files. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Deflate = __include("codecs/compress/Deflate") +local Nbt = __include("codecs/text/Nbt") +local Mc = __include("codecs/model/Minecraft") +local Chunk = __include("model/mca/Chunk") +local Lz4Block = __include("model/mca/Lz4Block") + +-- ------------------------------------------------------------------------------------------------ contract +local Mca = { + name = "mca", + category = "model", + extensions = { "mca", "mcr" }, + mime = { "application/x-minecraft-region" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Deflate", "codecs/text/Nbt", "codecs/model/Minecraft", "codecs/compress/Lz4" }, + caps = { decode = true, encode = false, voxels = true, blocks = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + chunks: { { number } }?, -- local coordinates 0 .. 31 (default all) + area: { number }?, -- world coordinates, inclusive + maxCells: number?, -- default 2^25 + maxBytes: number?, -- default 2^26 + keepNbt: boolean?, -- default true + region: { number }?, -- default: from opts.name "r.<x>.<z>.mca" + name: string?, + resolve: ((string) -> buffer?)?, -- external chunks c.<x>.<z>.mcc +} +type Entry = { + x: number, -- 0 .. 31 + z: number, + sector: number, -- 4 KiB sectors + sectors: number, + timestamp: number, -- seconds since 1970 +} + +-- ------------------------------------------------------------------------------------------------ constants +local COMPRESSION = { [1] = "gzip", [2] = "zlib", [3] = "none", [4] = "lz4", [127] = "custom" } + +-- ------------------------------------------------------------------------------------------------ sniff +function Mca.sniff(r: Bytes.Reader): number + local n = r.limit - r.base + if n < 8192 then + return 0 + end + local sectors = (n + 4095) // 4096 + local used, b = 0, r.buf + for i = 0, 1023 do + local e = bit32.byteswap(buffer.readu32(b, r.base + i * 4)) + if e ~= 0 then + local off, cnt = e // 256, e % 256 + if off < 2 or cnt == 0 or off + cnt > sectors then + return 0 + end + used += 1 + if used == 1 then + local p = r.base + off * 4096 + if p + 5 > r.limit then + return 0 + end + local c = buffer.readu8(b, p + 4) % 128 + if COMPRESSION[c] == nil then + return 0 + end + end + end + end + return if used > 0 then 0.8 else 0.2 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Mca.list(r: Bytes.Reader): ({ Entry }?, Err.Err?) + local n = r.limit - r.base + if n < 8192 then + return nil, Err.new(Err.TRUNCATED, "region header is 8192 bytes, file has " .. n) + end + local out: { Entry } = {} + for i = 0, 1023 do + local e = bit32.byteswap(buffer.readu32(r.buf, r.base + i * 4)) + if e ~= 0 then + table.insert(out, { + x = i % 32, + z = i // 32, + sector = e // 256, + sectors = e % 256, + timestamp = bit32.byteswap(buffer.readu32(r.buf, r.base + 4096 + i * 4)), + }) + end + end + return out, nil +end + +local function regionCoords(o: DecodeOptions): (number?, number?) + if o.region then + return o.region[1], o.region[2] + end + if o.name then + local x, z = string.match(o.name, "r%.(%-?%d+)%.(%-?%d+)%.mc[ar]$") + if x then + return tonumber(x), tonumber(z) + end + end + return nil, nil +end + +local function payload(r: Bytes.Reader, e: Entry, o: DecodeOptions): (buffer?, any) + local p = r.base + e.sector * 4096 + if p + 5 > r.limit then + return nil, Err.new(Err.TRUNCATED, string.format("chunk %d,%d starts past the end", e.x, e.z), p - r.base) + end + local len = bit32.byteswap(buffer.readu32(r.buf, p)) + local ctype = buffer.readu8(r.buf, p + 4) + local data: buffer, start: number, size: number = r.buf, p + 5, len - 1 + if ctype >= 128 then + -- stored in c.<x>.<z>.mcc next to the region (whole file = the compressed payload) + local rx, rz = regionCoords(o) + if not o.resolve or rx == nil then + return nil, Err.new(Err.UNSUPPORTED, string.format("chunk %d,%d is in an external .mcc file (pass opts.resolve and the region coordinates)", e.x, e.z)) + end + local name = string.format("c.%d.%d.mcc", (rx :: number) * 32 + e.x, (rz :: number) * 32 + e.z) + local ext = o.resolve(name) + if type(ext) ~= "buffer" then + return nil, Err.new(Err.IO, "cannot read " .. name) + end + data, start, size = ext, 0, buffer.len(ext) + ctype -= 128 + elseif len < 1 or p + 4 + len > r.limit then + return nil, Err.new(Err.TRUNCATED, string.format("chunk %d,%d runs past the end", e.x, e.z), p - r.base) + end + local comp = COMPRESSION[ctype] + local maxBytes = o.maxBytes or 2 ^ 26 + local out, err + if comp == "gzip" then + out, err = Deflate.gunzip(data, start, size) + elseif comp == "zlib" then + out, err = Deflate.zlib(data, start, size) + elseif comp == "none" then + out = buffer.create(size :: number) + buffer.copy(out, 0, data, start, size) + elseif comp == "lz4" then + local msg + out, msg = Lz4Block.decode(data, start, size :: number, maxBytes) + if not out then + err = Err.from(msg, start - r.base) + end + else + return nil, Err.new(Err.UNSUPPORTED, string.format("chunk %d,%d: compression type %d", e.x, e.z, ctype)) + end + if not out then + return nil, err + end + if buffer.len(out) > maxBytes then + return nil, Err.new(Err.LIMIT, string.format("chunk %d,%d inflates past maxBytes", e.x, e.z)) + end + return out, comp +end + +function Mca.chunk(r: Bytes.Reader, x: number, z: number, opts: DecodeOptions?): (any, any) + local o: DecodeOptions = opts or {} + if x < 0 or x > 31 or z < 0 or z > 31 or x % 1 ~= 0 or z % 1 ~= 0 then + return nil, Err.new(Err.ARG, "chunk coordinates are 0 .. 31") + end + local entries, lerr = Mca.list(r) + if not entries then + return nil, lerr + end + for _, e in entries do + if e.x == x and e.z == z then + local raw, comp = payload(r, e, o) + if not raw then + return nil, comp + end + local v, info = Nbt.decode(raw, { endian = "big", maxBytes = o.maxBytes }) + if v == nil then + return nil, info + end + return v, comp + end + end + return nil, nil +end + +function Mca.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local o: DecodeOptions = opts or {} + local entries, lerr = Mca.list(r) + if not entries then + return nil, lerr + end + local want: { [number]: boolean }? = nil + if o.chunks then + local w: { [number]: boolean } = {} + for _, c in o.chunks do + w[(c[1] or 0) + 32 * (c[2] or 0)] = true + end + want = w + end + local area = o.area + if area and #area ~= 6 then + return nil, Err.new(Err.ARG, "area is { minX, minY, minZ, maxX, maxY, maxZ }") + end + local keep = o.keepNbt ~= false + local chunks: { Chunk.Blocks } = {} + local infos = {} + for _, e in entries do + if not want or want[e.x + 32 * e.z] then + local raw, comp = payload(r, e, o) + if not raw then + return nil, comp + end + local v, info = Nbt.decode(raw, { endian = "big", maxBytes = o.maxBytes }) + if v == nil then + return nil, Err.new(info.code, string.format("chunk %d,%d: %s", e.x, e.z, info.message)) + end + local blocks, berr = Chunk.blocks(v) + if not blocks then + return nil, Err.from(string.format("chunk %d,%d: %s", e.x, e.z, tostring(berr))) + end + local inArea = not area or (blocks.x * 16 <= area[4] and blocks.x * 16 + 15 >= area[1] and blocks.z * 16 <= area[6] and blocks.z * 16 + 15 >= area[3]) + if inArea then + table.insert(chunks, blocks) + table.insert(infos, { x = e.x, z = e.z, worldX = blocks.x, worldZ = blocks.z, timestamp = e.timestamp, compression = comp, dataVersion = blocks.dataVersion, nbt = if keep then v else nil }) + end + end + end + local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge } + for _, c in chunks do + lo[1], hi[1] = math.min(lo[1], c.x * 16), math.max(hi[1], c.x * 16 + 15) + lo[3], hi[3] = math.min(lo[3], c.z * 16), math.max(hi[3], c.z * 16 + 15) + for _, s in c.sections do + local solid = false + for _, st in s.states do + if not Mc.isAir(st) then + solid = true + break + end + end + if solid then + lo[2], hi[2] = math.min(lo[2], s.y * 16), math.max(hi[2], s.y * 16 + 15) + end + end + end + if area then + for k = 1, 3 do + lo[k], hi[k] = math.max(lo[k], area[k]), math.min(hi[k], area[k + 3]) + if area[k] > area[k + 3] then + return nil, Err.new(Err.ARG, "area minimum past its maximum") + end + end + if lo[2] == math.huge then + lo[2], hi[2] = area[2], area[5] + end + end + if lo[2] == math.huge then + lo[2], hi[2] = 0, -1 + end + if #chunks == 0 then + lo, hi = { 0, 0, 0 }, { -1, -1, -1 } + end + local sx, sy, sz = math.max(0, hi[1] - lo[1] + 1), math.max(0, hi[2] - lo[2] + 1), math.max(0, hi[3] - lo[3] + 1) + local n = sx * sy * sz + if n > (o.maxCells or 2 ^ 25) then + return nil, Err.new(Err.LIMIT, string.format("%d x %d x %d cells is over maxCells: choose opts.chunks or opts.area", sx, sy, sz)) + end + local states = { "minecraft:air" } + local index: { [string]: number } = { ["minecraft:air"] = 0 } + local grid = buffer.create(n * 2) + local bes, ents = {}, {} + for _, c in chunks do + local cx, cz = c.x * 16 - lo[1], c.z * 16 - lo[3] + for _, s in c.sections do + local cy = s.y * 16 - lo[2] + if cy + 15 >= 0 and cy < sy and cx + 15 >= 0 and cx < sx and cz + 15 >= 0 and cz < sz then + local lut = table.create(#s.states) :: { number } + for i, st in s.states do + local g = index[st] + if g == nil then + table.insert(states, st) + g = #states - 1 + index[st] = g + end + lut[i] = g + end + if #states > 65536 then + return nil, Err.new(Err.LIMIT, "more than 65536 block states") + end + local cells = s.cells + local y0, y1 = math.max(0, -cy), math.min(15, sy - 1 - cy) + local z0, z1 = math.max(0, -cz), math.min(15, sz - 1 - cz) + local x0, x1 = math.max(0, -cx), math.min(15, sx - 1 - cx) + for y = y0, y1 do + for z = z0, z1 do + local src = ((y * 16 + z) * 16 + x0) * 2 + local dst = ((cx + x0) + sx * ((cy + y) + sy * (cz + z))) * 2 + for _ = x0, x1 do + buffer.writeu16(grid, dst, lut[buffer.readu16(cells, src) + 1] or 0) + src += 2 + dst += 2 + end + end + end + end + end + for _, rec in c.blockEntities do + local be = Mc.blockEntity(rec, "flat") + if be then + local px, py, pz = be.pos[1] - lo[1], be.pos[2] - lo[2], be.pos[3] - lo[3] + if px >= 0 and px < sx and py >= 0 and py < sy and pz >= 0 and pz < sz then + be.pos = { px, py, pz } + table.insert(bes, be) + end + end + end + for _, ent in c.entities do + table.insert(ents, ent) + end + end + local v = Mc.voxels(sx, sy, sz, states, grid) + local b = v.blocks :: Types.VoxelBlocks + b.blockEntities = bes + b.entities = ents + local scene = Types.Scene.new() + scene.voxels = { v } + scene.nodes = { { name = o.name, children = {}, voxels = 1, translation = { lo[1], lo[2], lo[3] } } } + scene.roots = { 1 } + scene.meta.up = "y" + scene.meta.unit = 1 + local rx, rz = regionCoords(o) + scene.meta.source = { format = "mca", region = if rx then { rx, rz } else nil, chunks = infos } + return scene, nil +end + +return Mca +end +__FILES["model/mca/Chunk"] = function() + +-- model/mca/Chunk: an Anvil chunk's blocks (Minecraft wiki "Chunk format"): 1.18+ sections[] block_states +-- (non-spanning, >= 4 bits); 1.13 - 1.17 Level.Sections[] Palette + BlockStates (spanning before DataVersion 2529 = +-- 20w17a); pre-1.13 Blocks / Add / Data nibble arrays. A section is 16 x 16 x 16 cells, x then z then y. +local Types = __include("Types") +local Nbt = __include("codecs/text/Nbt") +local Mc = __include("codecs/model/Minecraft") + +local Chunk = {} + +local Packed = Mc.Packed + +type Section = { y: number, states: { string }, cells: buffer } -- u16 per cell, 4096, x-z-y order +type Blocks = { + x: number, -- xPos / zPos + z: number, + dataVersion: number?, + sections: { Section }, + blockEntities: { any }, -- absolute x, y, z + entities: { any }, -- before 1.17 +} + +local function int(v: any): number? + local n = Nbt.number(v) + return if n and n == n and n % 1 == 0 then n else nil +end + +local function list(v: any): { any } + return if type(v) == "table" and not Nbt.isTag(v) and not Types.isObject(v) then v else {} +end + +local function paletted(y: number, palette: { any }, data: any, minBits: number, spanning: boolean): (Section?, string?) + local states = table.create(#palette) :: { string } + for i, c in palette do + local s = Mc.stateFromNbt(c) + if not s then + return nil, "section " .. y .. ": bad palette entry " .. i + end + states[i] = s + end + if #states == 0 then + return nil, nil + end + local cells = buffer.create(8192) + if #states > 1 or data ~= nil then + if not (Nbt.isTag(data) and data.type == "longArray") then + return nil, "section " .. y .. ": no block state data" + end + local bits = Packed.bitsFor(#states, minBits) + local ok, e = Packed.unpack(data.value, bits, 4096, spanning, cells, #states) + if not ok then + return nil, "section " .. y .. ": " .. tostring(e) + end + end + return { y = y, states = states, cells = cells }, nil +end + +function Chunk.blocks(root: any): (Blocks?, string?) + if type(root) ~= "table" or not Types.isObject(root) then + return nil, "chunk NBT is not a compound" + end + local dv = int(root.DataVersion) + local level = if Types.isObject(root.Level) then root.Level else root + local x, z = int(level.xPos), int(level.zPos) + if not x or not z then + return nil, "chunk without xPos / zPos" + end + local out: Blocks = { x = x, z = z, dataVersion = dv, sections = {}, blockEntities = {}, entities = list(level.Entities) } + if root.sections ~= nil then + -- 1.18+ + for _, s in list(root.sections) do + local y = int(s.Y) + local bs = s.block_states + if y and type(bs) == "table" and not Nbt.isTag(bs) then + local sec, e = paletted(y, list(bs.palette), bs.data, 4, false) + if e then + return nil, e + end + if sec then + table.insert(out.sections, sec) + end + end + end + out.blockEntities = list(root.block_entities) + return out, nil + end + for _, s in list(level.Sections) do + local y = int(s.Y) + if y then + if s.Palette ~= nil then + local sec, e = paletted(y, list(s.Palette), s.BlockStates, 4, (dv or 0) < 2529) + if e then + return nil, e + end + if sec then + table.insert(out.sections, sec) + end + elseif type(s.Blocks) == "buffer" then + local blocks = s.Blocks :: buffer + if buffer.len(blocks) < 4096 then + return nil, "section " .. y .. ": short Blocks array" + end + local data = if type(s.Data) == "buffer" and buffer.len(s.Data) >= 2048 then s.Data else nil + local add = if type(s.Add) == "buffer" and buffer.len(s.Add) >= 2048 then s.Add else nil + local slots: { [number]: number } = {} + local states: { string } = {} + local cells = buffer.create(8192) + for i = 0, 4095 do + local id = buffer.readu8(blocks, i) + if add then + id += Packed.nibble(add, 0, i, false) * 256 + end + local d = if data then Packed.nibble(data, 0, i, false) else 0 + local key = id * 16 + d + local slot = slots[key] + if not slot then + table.insert(states, Mc.legacyState(id, d)) + slot = #states - 1 + slots[key] = slot + end + buffer.writeu16(cells, i * 2, slot :: number) + end + table.insert(out.sections, { y = y, states = states, cells = cells }) + end + end + end + out.blockEntities = list(level.TileEntities) + return out, nil +end + +return Chunk +end +__FILES["model/mca/Lz4Block"] = function() + +-- model/mca/Lz4Block: lz4-java LZ4BlockOutputStream framing (Minecraft 24w04a+, compression type 4): "LZ4Block", token +-- (0x10 raw / 0x20 LZ4 | level), compressed and decompressed lengths, XXH32 (LE i32s; not verified), then the block; +-- blocks are independent and an empty block ends the stream. +local Lz4 = __include("codecs/compress/Lz4") + +local Lz4Block = {} + +local MAGIC = "LZ4Block" + +function Lz4Block.decode(b: buffer, offset: number, length: number, maxBytes: number): (buffer?, string?) + local p, e = offset, offset + length + local parts, total = {}, 0 + while true do + if p + 21 > e then + if #parts > 0 and p >= e then + break -- some writers stop without the empty end block + end + return nil, "truncated LZ4 block header" + end + if buffer.readstring(b, p, 8) ~= MAGIC then + return nil, "bad LZ4Block magic" + end + local token = buffer.readu8(b, p + 8) + local clen, dlen = buffer.readi32(b, p + 9), buffer.readi32(b, p + 13) + p += 21 + local method = token // 16 * 16 + if clen < 0 or dlen < 0 or p + clen > e then + return nil, "truncated LZ4 block" + end + if dlen == 0 and clen == 0 then + break + end + total += dlen + if total > maxBytes then + return nil, "limit: chunk inflates past maxBytes" + end + if method == 0x10 then + if clen ~= dlen then + return nil, "raw LZ4 block length mismatch" + end + local out = buffer.create(dlen) + buffer.copy(out, 0, b, p, clen) + table.insert(parts, out) + elseif method == 0x20 then + local out, err = Lz4.decompress(b, p, clen, dlen) + if not out then + return nil, "LZ4: " .. tostring(err and err.message) + end + table.insert(parts, out) + else + return nil, "unsupported: LZ4Block method " .. method + end + p += clen + end + if #parts == 1 then + return parts[1], nil + end + local res = buffer.create(total) + local w = 0 + for _, part in parts do + buffer.copy(res, w, part) + w += buffer.len(part) + end + return res, nil +end + +return Lz4Block +end +__FILES["model/md2"] = function() + +-- model/md2: Quake II MD2 ("IDP2" v8), from qfiles.h dmdl_t and David Henry's "MD2 file format"; no code taken. +-- Supports: clockwise faces reversed, frames as morph targets, animations per frame-name group (10 fps), skin URIs. +-- Not supported: the GL command list, writing; Quake's normal table (not redistributable: normals are computed). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Sniff = __include("core/Sniff") +local Types = __include("Types") +local Rig = __include("codecs/model/Rig") + +-- ------------------------------------------------------------------------------------------------ contract +local Md2 = { + name = "md2", + category = "model", + extensions = { "md2" }, + mime = { "model/x-md2" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/model/Rig" }, + caps = { decode = true, encode = false, morph = true, animation = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + frame: number?, -- 1-based, default 1 + morph: boolean?, -- default true + fps: number?, -- default 10 + maxVertices: number?, -- default 2^24 +} + +-- ------------------------------------------------------------------------------------------------ constants +local Scene = Types.Scene +local readu8, readu16, readi16, readf32, writef32, writeu32 = buffer.readu8, buffer.readu16, buffer.readi16, buffer.readf32, buffer.writef32, buffer.writeu32 + +-- ------------------------------------------------------------------------------------------------ sniff +function Md2.sniff(r: Bytes.Reader): number + if r:remaining() < 68 then + return 0 + end + return if Sniff.magic(r, "IDP2") == 1 and r:peekU8(4) == 8 then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function groups(names: { string }, fps: number): { Rig.Range } + local out: { Rig.Range } = {} + for i, n in names do + local stem = string.match(n, "^(.-)_?%d*$") or n + if stem == "" then + stem = n + end + local last = out[#out] + if last and last.name == stem and last.last == i - 1 then + last.last = i + else + table.insert(out, { name = stem, first = i, last = i, fps = fps }) + end + end + return out +end + +function Md2.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local size = r.limit - r.base + if not r:match("IDP2") then + return nil, Err.new(if size < 4 then Err.TRUNCATED else Err.CORRUPT, "bad magic", 0) + end + local h: { number } = {} + for i = 1, 16 do + h[i] = r:i32le() + end + if r.err then + return nil, r.err + end + local version, sw, sh, frameSize, nSkins, nXyz, nSt, nTris, _, nFrames, oSkins, oSt, oTris, oFrames = table.unpack(h, 1, 14) + if version ~= 8 then + return nil, Err.new(Err.UNSUPPORTED, "MD2 version " .. version, 4) + end + if nSkins < 0 or nXyz <= 0 or nSt < 0 or nTris < 0 or nFrames <= 0 or sw < 0 or sh < 0 then + return nil, Err.new(Err.CORRUPT, "bad counts", 8) + end + if nFrames * nXyz > (opts and opts.maxVertices or 2 ^ 24) then + return nil, Err.new(Err.LIMIT, "too many vertices") + end + local function inside(o: number, n: number): boolean + return o >= 0 and n >= 0 and o + n <= size + end + if not (inside(oSkins, nSkins * 64) and inside(oSt, nSt * 4) and inside(oTris, nTris * 12) and inside(oFrames, nFrames * frameSize)) then + return nil, Err.new(Err.TRUNCATED, "a section runs past the end", 44) + end + if frameSize < 40 + nXyz * 4 then + return nil, Err.new(Err.CORRUPT, "frame size too small", 16) + end + local b, base = r.buf, r.base + local skins: { string } = {} + for i = 0, nSkins - 1 do + local s = buffer.readstring(b, base + oSkins + i * 64, 64) + table.insert(skins, (string.match(s, "^[^%z]*")) :: string) + end + local key: { [number]: number } = {} + local vx: { number }, vst: { number } = {}, {} + local indices: { number } = {} + for t = 0, nTris - 1 do + local o = base + oTris + t * 12 + local corner: { number } = {} + for c = 0, 2 do + local xi, si = readu16(b, o + c * 2), readu16(b, o + 6 + c * 2) + if xi >= nXyz or (nSt > 0 and si >= nSt) then + return nil, Err.new(Err.CORRUPT, "triangle " .. t .. " index out of range", oTris + t * 12) + end + local k = xi * 65536 + si + local v = key[k] + if not v then + table.insert(vx, xi) + table.insert(vst, si) + v = #vx - 1 + key[k] = v + end + corner[c + 1] = v + end + table.insert(indices, corner[3]) + table.insert(indices, corner[2]) + table.insert(indices, corner[1]) + end + local nv = #vx + local uv = buffer.create(nv * 8) + for i = 1, nv do + if nSt > 0 then + local o = base + oSt + vst[i] * 4 + writef32(uv, (i - 1) * 8, readi16(b, o) / math.max(sw, 1)) + writef32(uv, (i - 1) * 8 + 4, readi16(b, o + 2) / math.max(sh, 1)) + end + end + local frames: { buffer } = {} + local normals: { buffer } = {} + local names: { string } = {} + local morph = not (opts and opts.morph == false) + local want = math.clamp(math.floor(opts and opts.frame or 1), 1, nFrames) + for f = 1, nFrames do + if morph or f == want then + local o = base + oFrames + (f - 1) * frameSize + local sx, sy, sz = readf32(b, o), readf32(b, o + 4), readf32(b, o + 8) + local tx, ty, tz = readf32(b, o + 12), readf32(b, o + 16), readf32(b, o + 20) + local pos = buffer.create(nv * 12) + for i = 1, nv do + local p = o + 40 + vx[i] * 4 + writef32(pos, (i - 1) * 12, readu8(b, p) * sx + tx) + writef32(pos, (i - 1) * 12 + 4, readu8(b, p + 1) * sy + ty) + writef32(pos, (i - 1) * 12 + 8, readu8(b, p + 2) * sz + tz) + end + frames[f] = pos + normals[f] = Rig.normals(pos, nv, indices) + end + local nm = buffer.readstring(b, base + oFrames + (f - 1) * frameSize + 24, 16) + names[f] = (string.match(nm, "^[^%z]*")) :: string + end + local ib = buffer.create(#indices * 4) + for i, v in indices do + writeu32(ib, (i - 1) * 4, v) + end + local prim: Types.Primitive = { + attributes = { + POSITION = Scene.accessor(frames[want], "f32", 3, nv), + NORMAL = Scene.accessor(normals[want], "f32", 3, nv), + TEXCOORD_0 = Scene.accessor(uv, "f32", 2, nv), + }, + indices = Scene.accessor(ib, "u32", 1, #indices), + mode = "triangles", + } + local scene = Scene.new() + scene.meta.up = "z" + if #skins > 0 then + for _, s in skins do + table.insert(scene.textures, { name = s, uri = s }) + end + local mat = Scene.material(skins[1]) + mat.metallic = 0 + mat.baseColorTexture = { texture = 1 } + table.insert(scene.materials, mat) + prim.material = 1 + end + scene.meshes[1] = { primitives = { prim }, extras = { skins = skins } } + scene.nodes[1] = { children = {}, mesh = 1 } + scene.roots[1] = 1 + if morph then + local fr: { buffer } = {} + for f = 1, nFrames do + fr[f] = frames[f] + end + Rig.morph(prim, fr, normals) + local w = table.create(nFrames, 0) + scene.meshes[1].weights = w + Rig.morphAnimation(scene, 1, nFrames, groups(names, opts and opts.fps or 10), "LINEAR") + end + scene.meta.source = { format = "md2", frames = nFrames, frameNames = names, skinWidth = sw, skinHeight = sh, normalIndexes = false } + return scene, nil +end + +return Md2 +end +__FILES["model/md3"] = function() + +-- model/md3: Quake III MD3 ("IDP3" v15), from qfiles.h md3Header_t / md3Surface_t and PhaethonH's "MD3 file format"; +-- no code taken. Supports: surfaces as primitives, positions in 1/64 units, lat / long normals, frames as morph +-- targets, tags as child nodes with channels. Not supported: writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Sniff = __include("core/Sniff") +local Types = __include("Types") +local Mat4 = __include("codecs/model/Mat4") +local Rig = __include("codecs/model/Rig") + +-- ------------------------------------------------------------------------------------------------ contract +local Md3 = { + name = "md3", + category = "model", + extensions = { "md3" }, + mime = { "model/x-md3" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/model/Mat4", "codecs/model/Rig" }, + caps = { decode = true, encode = false, morph = true, animation = true, tags = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + frame: number?, -- 1-based, default 1 + morph: boolean?, -- default true + fps: number?, -- default 15 + maxVertices: number?, -- default 2^24 +} + +-- ------------------------------------------------------------------------------------------------ constants +local Scene = Types.Scene +local readi16, readu8, readi32, readf32, writef32, writeu32 = buffer.readi16, buffer.readu8, buffer.readi32, buffer.readf32, buffer.writef32, buffer.writeu32 +local K = math.pi / 128 -- the engine maps a byte to 2 pi / 256 (tr_surface.c LatLongToNormal) + +-- ------------------------------------------------------------------------------------------------ sniff +function Md3.sniff(r: Bytes.Reader): number + if r:remaining() < 108 then + return 0 + end + return if Sniff.magic(r, "IDP3") == 1 and r:peekU8(4) == 15 then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function cstr(b: buffer, at: number, n: number): string + return (string.match(buffer.readstring(b, at, n), "^[^%z]*")) :: string +end + +function Md3.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local size = r.limit - r.base + if size < 108 then + return nil, Err.new(Err.TRUNCATED, "header", 0) + end + if not r:match("IDP3") then + return nil, Err.new(Err.CORRUPT, "bad magic", 0) + end + local version = r:i32le() + if version ~= 15 then + return nil, Err.new(Err.UNSUPPORTED, "MD3 version " .. version, 4) + end + local b, base = r.buf, r.base + local name = cstr(b, base + 8, 64) + r:skip(68) + local nFrames, nTags, nSurf, _nSkins = r:i32le(), r:i32le(), r:i32le(), r:i32le() + local oFrames, oTags, oSurf = r:i32le(), r:i32le(), r:i32le() + if r.err then + return nil, r.err + end + if nFrames <= 0 or nTags < 0 or nSurf < 0 or nFrames > 65536 or nTags > 4096 or nSurf > 4096 then + return nil, Err.new(Err.CORRUPT, "bad counts", 76) + end + local function inside(o: number, n: number): boolean + return o >= 0 and n >= 0 and o + n <= size + end + if not inside(oFrames, nFrames * 56) or not inside(oTags, nFrames * nTags * 112) then + return nil, Err.new(Err.TRUNCATED, "frames / tags past the end", 88) + end + local morph = not (opts and opts.morph == false) + local want = math.clamp(math.floor(opts and opts.frame or 1), 1, nFrames) + local maxV = opts and opts.maxVertices or 2 ^ 24 + local scene = Scene.new() + scene.meta.up = "z" + local mesh: Types.Mesh = { name = if name ~= "" then name else nil, primitives = {} } + scene.meshes[1] = mesh + scene.nodes[1] = { name = mesh.name, children = {}, mesh = 1 } + scene.roots[1] = 1 + local total = 0 + local so = oSurf + for s = 1, nSurf do + if not inside(so, 108) or cstr(b, base + so, 4) ~= "IDP3" then + return nil, Err.new(Err.CORRUPT, "surface " .. s .. ": bad header", so) + end + local p = base + so + local sname = cstr(b, p + 4, 64) + local sFrames, nShaders, nVerts, nTris = readi32(b, p + 72), readi32(b, p + 76), readi32(b, p + 80), readi32(b, p + 84) + local oTri, oSh, oSt, oXyz, oEnd = readi32(b, p + 88), readi32(b, p + 92), readi32(b, p + 96), readi32(b, p + 100), readi32(b, p + 104) + if sFrames ~= nFrames or nShaders < 0 or nVerts < 0 or nTris < 0 or oEnd <= 0 then + return nil, Err.new(Err.CORRUPT, "surface " .. s .. ": bad counts", so + 72) + end + total += nVerts * nFrames + if total > maxV then + return nil, Err.new(Err.LIMIT, "too many vertices") + end + if not (inside(so + oTri, nTris * 12) and inside(so + oSh, nShaders * 68) and inside(so + oSt, nVerts * 8) and inside(so + oXyz, nVerts * nFrames * 8)) then + return nil, Err.new(Err.TRUNCATED, "surface " .. s .. " past the end", so) + end + local ib = buffer.create(nTris * 12) + local idx = table.create(nTris * 3, 0) :: { number } + for t = 0, nTris - 1 do + for c = 0, 2 do + local v = readi32(b, p + oTri + t * 12 + c * 4) + if v < 0 or v >= nVerts then + return nil, Err.new(Err.CORRUPT, "surface " .. s .. ": triangle index out of range", so + oTri + t * 12) + end + idx[t * 3 + 3 - c] = v + end + end + for i, v in idx do + writeu32(ib, (i - 1) * 4, v) + end + local uv = buffer.create(nVerts * 8) + buffer.copy(uv, 0, b, p + oSt, nVerts * 8) + local frames: { buffer }, normals: { buffer } = {}, {} + for f = 1, nFrames do + if morph or f == want then + local pos, nrm = buffer.create(nVerts * 12), buffer.create(nVerts * 12) + local q = p + oXyz + (f - 1) * nVerts * 8 + for v = 0, nVerts - 1 do + local o = q + v * 8 + writef32(pos, v * 12, readi16(b, o) / 64) + writef32(pos, v * 12 + 4, readi16(b, o + 2) / 64) + writef32(pos, v * 12 + 8, readi16(b, o + 4) / 64) + local lng, lat = readu8(b, o + 6) * K, readu8(b, o + 7) * K + writef32(nrm, v * 12, math.cos(lat) * math.sin(lng)) + writef32(nrm, v * 12 + 4, math.sin(lat) * math.sin(lng)) + writef32(nrm, v * 12 + 8, math.cos(lng)) + end + frames[f], normals[f] = pos, nrm + end + end + local prim: Types.Primitive = { + attributes = { + POSITION = Scene.accessor(frames[want], "f32", 3, nVerts), + NORMAL = Scene.accessor(normals[want], "f32", 3, nVerts), + TEXCOORD_0 = Scene.accessor(uv, "f32", 2, nVerts), + }, + indices = Scene.accessor(ib, "u32", 1, nTris * 3), + mode = "triangles", + extras = { md3 = { surface = sname } }, + } + if morph then + Rig.morph(prim, frames, normals) + end + local shaders: { string } = {} + for k = 0, nShaders - 1 do + table.insert(shaders, cstr(b, p + oSh + k * 68, 64)) + end + local mat = Scene.material(sname) + mat.metallic = 0 + if shaders[1] and shaders[1] ~= "" then + table.insert(scene.textures, { name = shaders[1], uri = shaders[1] }) + mat.baseColorTexture = { texture = #scene.textures } + end + mat.extras = { md3 = { shaders = shaders } } + table.insert(scene.materials, mat) + prim.material = #scene.materials + table.insert(mesh.primitives, prim) + so += oEnd + end + local frameNames: { string } = {} + for f = 0, nFrames - 1 do + frameNames[f + 1] = cstr(b, base + oFrames + f * 56 + 40, 16) + end + local tagNodes: { number } = {} + local tracks: { [number]: Rig.Track } = {} + local tagNames: { string } = {} + for k = 0, nTags - 1 do + local tr: Rig.Track = { translation = {}, rotation = {} } + local first: any = nil + for f = 0, nFrames - 1 do + local o = base + oTags + (f * nTags + k) * 112 + local t = { readf32(b, o + 64), readf32(b, o + 68), readf32(b, o + 72) } + local a: { number } = {} + for i = 0, 8 do + a[i + 1] = readf32(b, o + 76 + i * 4) + end + local m = { a[1], a[2], a[3], 0, a[4], a[5], a[6], 0, a[7], a[8], a[9], 0, t[1], t[2], t[3], 1 } + local q = Mat4.quat(m) + for c = 1, 3 do + table.insert(tr.translation :: { number }, t[c]) + end + for c = 1, 4 do + table.insert(tr.rotation :: { number }, q[c]) + end + if f == want - 1 then + first = { name = cstr(b, o, 64), t = t, q = q } + end + end + table.insert(tagNames, first.name) + table.insert(scene.nodes, { name = first.name, children = {}, translation = first.t, rotation = first.q, extras = { md3 = { tag = true } } }) + table.insert(scene.nodes[1].children, #scene.nodes) + tagNodes[k + 1] = #scene.nodes + tracks[k + 1] = tr + end + if morph and nFrames > 1 then + scene.meshes[1].weights = table.create(nFrames, 0) + local fps = opts and opts.fps or 15 + Rig.morphAnimation(scene, 1, nFrames, { { name = "frames", first = 1, last = nFrames, fps = fps } }, "LINEAR") + if nTags > 0 then + local times: { number } = {} + for f = 1, nFrames do + times[f] = (f - 1) / fps + end + local ai = Rig.animation(scene, "tags", tagNodes, times, tracks) + local tagAnim = table.remove(scene.animations, ai) :: Types.Animation + for _, ch in tagAnim.channels do + table.insert(scene.animations[1].channels, ch) + end + end + end + scene.meta.source = { format = "md3", name = name, frames = nFrames, frameNames = frameNames, tags = tagNames } + return scene, nil +end + +return Md3 +end +__FILES["model/md5"] = function() + +-- model/md5: Doom 3 / Quake 4 MD5 (MD5Version 10 text): .md5mesh and .md5anim (model/md5/Read); a mesh loads +-- opts.anims, joints matched by name. Not supported: writing, .md5camera. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Input = __include("core/Input") +local Sniff = __include("core/Sniff") +local Types = __include("Types") +local Read = __include("model/md5/Read") + +-- ------------------------------------------------------------------------------------------------ contract +local Md5 = { + name = "md5", + category = "model", + extensions = { "md5mesh", "md5anim" }, + mime = { "model/x-md5mesh", "model/x-md5anim" }, + deps = { "core/Err", "core/Bytes", "core/Input", "core/Sniff", "Types", "codecs/model/Rig" }, + caps = { decode = true, encode = false, skins = true, animation = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + anims: { string }?, + resolve: ((uri: string) -> (buffer | string)?)?, + files: { [string]: buffer | string }?, + skipMissing: boolean?, -- default false: UNSUPPORTED + name: string?, + maxVertices: number?, -- default 2^24 +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Md5.sniff(r: Bytes.Reader): number + local head = Sniff.text(r, 512, true) + head = string.gsub(head, "^//[^\n]*\n%s*", "") + return if string.match(head, "^MD5Version%s+%d+") then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function stem(name: string): string + local base = string.match(name, "([^/\\]+)$") or name + return (string.gsub(base, "%.[^.]*$", "")) +end + +function Md5.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local text = Sniff.dropBom(r:string(r:remaining())) + if string.find(text, "numAnimatedComponents", 1, true) then + local a, msg = Read.anim(text) + if not a then + return nil, Err.from(msg) + end + return Read.animScene(a, if opts and type(opts.name) == "string" then stem(opts.name) else "animation"), nil + end + local scene, byName = Read.mesh(text, opts :: any) + if not scene then + return nil, Err.from(byName) + end + if opts and type(opts.anims) == "table" then + for _, name in opts.anims do + local got = if type(name) == "string" then Input.sibling(opts, name) else nil + local src = if got then buffer.tostring(got) else nil + if not src then + if not opts.skipMissing then + return nil, Err.new(Err.UNSUPPORTED, "animation " .. tostring(name) .. " not available (opts.resolve / opts.files)") + end + else + local a, msg = Read.anim(Sniff.dropBom(src)) + if not a then + return nil, Err.from("animation " .. name .. ": " .. tostring(msg)) + end + Read.addAnim(scene, byName, a, stem(name)) + end + end + end + return scene, nil +end + +return Md5 +end +__FILES["model/md5/Read"] = function() + +-- model/md5/Read: MD5Version 10 text, from modwiki "MD5 (file format)" and David Henry's "The MD5 Mesh and Animation +-- Formats"; no code taken. The bind pose is model space, the baseframe parent-relative. +local Types = __include("Types") +local Rig = __include("codecs/model/Rig") + +local Read = {} + +local Scene = Types.Scene +local writef32, writeu32 = buffer.writef32, buffer.writeu32 + +type Options = { maxVertices: number? } + +-- ------------------------------------------------------------------------------------------------ tokens +type Lexer = { text: string, pos: number, err: string? } + +local function token(L: Lexer): string? + local s = L.text + while true do + local a = string.find(s, "%S", L.pos) + if not a then + L.pos = #s + 1 + return nil + end + if string.sub(s, a, a + 1) == "//" then + local nl = string.find(s, "\n", a, true) + L.pos = if nl then nl + 1 else #s + 1 + else + L.pos = a + break + end + end + local c = string.sub(s, L.pos, L.pos) + if c == '"' then + local e = string.find(s, '"', L.pos + 1, true) + if not e then + L.err = "unterminated string" + L.pos = #s + 1 + return nil + end + local v = string.sub(s, L.pos + 1, e - 1) + L.pos = e + 1 + return '"' .. v + end + if c == "(" or c == ")" or c == "{" or c == "}" then + L.pos += 1 + return c + end + local e = string.find(s, '[%s(){}"]', L.pos) or (#s + 1) + local v = string.sub(s, L.pos, e - 1) + L.pos = e + return v +end + +local function num(L: Lexer): number + local t = token(L) + local v = t and tonumber(t) + if not v then + L.err = L.err or ("expected a number, got " .. tostring(t)) + return 0 + end + return v +end + +local function str(L: Lexer): string + local t = token(L) + if not t or string.sub(t, 1, 1) ~= '"' then + L.err = L.err or ("expected a string, got " .. tostring(t)) + return "" + end + return string.sub(t, 2) +end + +local function expect(L: Lexer, want: string) + local t = token(L) + if t ~= want then + L.err = L.err or ("expected " .. want .. ", got " .. tostring(t)) + end +end + +local function vec(L: Lexer, n: number): { number } + expect(L, "(") + local v = table.create(n, 0) + for i = 1, n do + v[i] = num(L) + end + expect(L, ")") + return v +end + +-- w = -sqrt(1 - x² - y² - z²) (w <= 0, as id's tools store it) +local function quat(x: number, y: number, z: number): { number } + local t = 1 - x * x - y * y - z * z + return { x, y, z, if t < 0 then 0 else -math.sqrt(t) } +end + +local function rotate(q: { number }, vx: number, vy: number, vz: number): (number, number, number) + local qx, qy, qz, qw = q[1], q[2], q[3], q[4] + -- v + 2 w (q x v) + 2 q x (q x v) + local tx, ty, tz = 2 * (qy * vz - qz * vy), 2 * (qz * vx - qx * vz), 2 * (qx * vy - qy * vx) + return vx + qw * tx + (qy * tz - qz * ty), vy + qw * ty + (qz * tx - qx * tz), vz + qw * tz + (qx * ty - qy * tx) +end + +-- ------------------------------------------------------------------------------------------------ md5mesh +type MeshJoint = { name: string, parent: number, pos: { number }, q: { number } } + +function Read.mesh(text: string, opts: Options?): (Types.Scene?, any) + local L: Lexer = { text = text, pos = 1, err = nil } + local joints: { MeshJoint } = {} + local scene = Scene.new() + scene.meta.up = "z" + local root: Types.Node = { name = "md5", children = {} } + table.insert(scene.nodes, root) + scene.roots[1] = 1 + local version: number? = nil + local mesh: Types.Mesh = { primitives = {} } + local maxV = opts and opts.maxVertices or 2 ^ 24 + local total = 0 + local skinIndex = 0 + local nodes: { number } = {} + while not L.err do + local t = token(L) + if not t then + break + end + if t == "MD5Version" then + version = num(L) + elseif t == "commandline" then + str(L) + elseif t == "numJoints" or t == "numMeshes" then + num(L) + elseif t == "joints" then + expect(L, "{") + while not L.err do + local s = token(L) + if s == "}" then + break + end + if not s or string.sub(s, 1, 1) ~= '"' then + return nil, "bad joint line" + end + local parent = num(L) + local p, q = vec(L, 3), vec(L, 3) + table.insert(joints, { name = string.sub(s, 2), parent = parent + 1, pos = p, q = quat(q[1], q[2], q[3]) }) + end + local list: { Rig.Joint } = {} + for i, j in joints do + list[i] = { name = j.name, parent = j.parent, translation = j.pos, rotation = j.q } + end + local n, si = Rig.skeleton(scene, list, "world", 1) + nodes, skinIndex = n, si + elseif t == "mesh" then + expect(L, "{") + local shader = "" + local verts: { { number } } = {} -- s, t, startWeight, countWeight + local tris: { number } = {} + local weights: { { number } } = {} -- joint, bias, x, y, z + while not L.err do + local k = token(L) + if k == "}" then + break + elseif k == "shader" then + shader = str(L) + elseif k == "numverts" or k == "numtris" or k == "numweights" then + local n = num(L) + total += if k == "numverts" then n else 0 + if total > maxV then + return nil, "limit: too many vertices" + end + elseif k == "vert" then + local i = num(L) + local st = vec(L, 2) + verts[i + 1] = { st[1], st[2], num(L), num(L) } + elseif k == "tri" then + num(L) + local a, b, c = num(L), num(L), num(L) + table.insert(tris, c) + table.insert(tris, b) + table.insert(tris, a) + elseif k == "weight" then + local i = num(L) + local j, bias = num(L), num(L) + local p = vec(L, 3) + weights[i + 1] = { j, bias, p[1], p[2], p[3] } + else + return nil, "unknown mesh keyword " .. tostring(k) + end + end + local nv = #verts + local pos, uv = buffer.create(nv * 12), buffer.create(nv * 8) + local lists: { { number } } = {} + for vi = 1, nv do + local v = verts[vi] + if not v then + return nil, "missing vert " .. (vi - 1) + end + local x, y, z = 0, 0, 0 + local l: { number } = {} + for w = v[3] + 1, v[3] + v[4] do + local wt = weights[w] + local j = wt and joints[wt[1] + 1] + if not wt or not j then + return nil, "vert " .. (vi - 1) .. ": bad weight " .. (w - 1) + end + local rx, ry, rz = rotate(j.q, wt[3], wt[4], wt[5]) + x += (j.pos[1] + rx) * wt[2] + y += (j.pos[2] + ry) * wt[2] + z += (j.pos[3] + rz) * wt[2] + table.insert(l, wt[1]) + table.insert(l, wt[2]) + end + writef32(pos, (vi - 1) * 12, x) + writef32(pos, (vi - 1) * 12 + 4, y) + writef32(pos, (vi - 1) * 12 + 8, z) + writef32(uv, (vi - 1) * 8, v[1]) + writef32(uv, (vi - 1) * 8 + 4, v[2]) + lists[vi] = l + end + for _, ix in tris do + if ix < 0 or ix >= nv then + return nil, "triangle index out of range" + end + end + local ib = buffer.create(#tris * 4) + for i, ix in tris do + writeu32(ib, (i - 1) * 4, ix) + end + local attrs: { [string]: Types.Accessor } = { + POSITION = Scene.accessor(pos, "f32", 3, nv), + NORMAL = Scene.accessor(Rig.normals(pos, nv, tris), "f32", 3, nv), + TEXCOORD_0 = Scene.accessor(uv, "f32", 2, nv), + } + if #joints > 0 then + attrs.JOINTS_0, attrs.WEIGHTS_0 = Rig.influences(lists) + end + local mat = Scene.material(shader) + mat.metallic = 0 + table.insert(scene.textures, { name = shader, uri = shader }) + mat.baseColorTexture = { texture = #scene.textures } + table.insert(scene.materials, mat) + table.insert(mesh.primitives, { attributes = attrs, indices = Scene.accessor(ib, "u32", 1, #tris), mode = "triangles" :: any, material = #scene.materials }) + else + return nil, "unknown keyword " .. t + end + end + if L.err then + return nil, L.err + end + if version ~= 10 then + return nil, if version then "unsupported: MD5Version " .. version else "no MD5Version" + end + if #mesh.primitives > 0 then + table.insert(scene.meshes, mesh) + table.insert(scene.nodes, { name = "mesh", children = {}, mesh = #scene.meshes, skin = if #joints > 0 then skinIndex else nil }) + table.insert(root.children, #scene.nodes) + end + local byName: { [string]: number } = {} + for i, j in joints do + byName[j.name] = nodes[i] + end + scene.meta.source = { format = "md5", kind = "mesh", joints = #joints, meshes = #mesh.primitives } + return scene, byName +end + +-- ------------------------------------------------------------------------------------------------ md5anim +type Anim = { + frameRate: number, + frames: number, + joints: { { name: string, parent: number } }, + base: { { number } }, -- per joint: px py pz qx qy qz + tracks: { Rig.Track }, -- per joint: translation / rotation keys, one per frame +} + +function Read.anim(text: string): (Anim?, string?) + local L: Lexer = { text = text, pos = 1, err = nil } + local a: Anim = { frameRate = 24, frames = 0, joints = {}, base = {}, tracks = {} } + local hier: { { number } } = {} -- flags, startIndex + local version: number? = nil + local nComp = 0 + local frames: { { number } } = {} + while not L.err do + local t = token(L) + if not t then + break + end + if t == "MD5Version" then + version = num(L) + elseif t == "commandline" then + str(L) + elseif t == "numFrames" then + a.frames = num(L) + elseif t == "numJoints" then + num(L) + elseif t == "frameRate" then + a.frameRate = num(L) + elseif t == "numAnimatedComponents" then + nComp = num(L) + if nComp < 0 or nComp > 2 ^ 20 then + return nil, "bad numAnimatedComponents" + end + elseif t == "hierarchy" then + expect(L, "{") + while not L.err do + local s = token(L) + if s == "}" then + break + end + if not s or string.sub(s, 1, 1) ~= '"' then + return nil, "bad hierarchy line" + end + local parent, flags, start = num(L), num(L), num(L) + table.insert(a.joints, { name = string.sub(s, 2), parent = parent + 1 }) + table.insert(hier, { flags, start }) + end + elseif t == "bounds" then + expect(L, "{") + while not L.err do + local s = token(L) + if s == "}" or s == nil then + break + end + end + elseif t == "baseframe" then + expect(L, "{") + while not L.err do + local s = token(L) + if s == "}" then + break + end + if s ~= "(" then + return nil, "bad baseframe line" + end + L.pos -= 1 + local p, q = vec(L, 3), vec(L, 3) + table.insert(a.base, { p[1], p[2], p[3], q[1], q[2], q[3] }) + end + elseif t == "frame" then + local fi = num(L) + expect(L, "{") + local vals = table.create(nComp, 0) + for k = 1, nComp do + vals[k] = num(L) + end + expect(L, "}") + if fi < 0 or fi > 2 ^ 20 then + return nil, "bad frame index" + end + frames[fi + 1] = vals + else + return nil, "unknown keyword " .. t + end + end + if L.err then + return nil, L.err + end + if version ~= 10 then + return nil, if version then "unsupported: MD5Version " .. version else "no MD5Version" + end + if #a.base ~= #a.joints then + return nil, "baseframe and hierarchy disagree" + end + for f = 1, a.frames do + if not frames[f] then + return nil, "missing frame " .. (f - 1) + end + end + for j, h in hier do + local tr: { number }, rot: { number } = {}, {} + local flags, start = h[1], h[2] + for f = 1, a.frames do + local v = table.clone(a.base[j]) + local k = start + 1 + for bit = 0, 5 do + if bit32.band(flags, bit32.lshift(1, bit)) ~= 0 then + v[bit + 1] = frames[f][k] or v[bit + 1] + k += 1 + end + end + table.insert(tr, v[1]) + table.insert(tr, v[2]) + table.insert(tr, v[3]) + local q = quat(v[4], v[5], v[6]) + for c = 1, 4 do + table.insert(rot, q[c]) + end + end + a.tracks[j] = { translation = tr, rotation = rot } + end + return a, nil +end + +function Read.addAnim(scene: Types.Scene, byName: { [string]: number }, a: Anim, name: string): number + local nodes: { number } = {} + local tracks: { [number]: Rig.Track } = {} + for j, jt in a.joints do + local nd = byName[jt.name] + if nd then + table.insert(nodes, nd) + tracks[#nodes] = a.tracks[j] + end + end + local times: { number } = {} + local rate = if a.frameRate > 0 then a.frameRate else 24 + for f = 1, a.frames do + times[f] = (f - 1) / rate + end + local ai = Rig.animation(scene, name, nodes, times, tracks, "LINEAR") + return #scene.animations[ai].channels +end + +function Read.animScene(a: Anim, name: string): Types.Scene + local scene = Scene.new() + scene.meta.up = "z" + table.insert(scene.nodes, { name = "md5", children = {} }) + scene.roots[1] = 1 + local list: { Rig.Joint } = {} + for j, jt in a.joints do + local b = a.base[j] + list[j] = { name = jt.name, parent = jt.parent, translation = { b[1], b[2], b[3] }, rotation = quat(b[4], b[5], b[6]) } + end + local nodes = Rig.skeleton(scene, list, "local", 1) + local byName: { [string]: number } = {} + for j, jt in a.joints do + byName[jt.name] = nodes[j] + end + Read.addAnim(scene, byName, a, name) + scene.meta.source = { format = "md5", kind = "anim", joints = #a.joints, frames = a.frames, frameRate = a.frameRate } + return scene +end + +return Read +end +__FILES["model/mdl"] = function() + +-- model/mdl: Quake 1 ("IDPO" v6, model/mdl/Quake) and GoldSrc ("IDST" v10, model/mdl/HalfLife) models. Quake skins +-- need gfx/palette.lmp (not redistributable, never built in; else a grey ramp). Not supported: Source MDL (v44+). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Input = __include("core/Input") +local Types = __include("Types") +local Quake = __include("model/mdl/Quake") +local HalfLife = __include("model/mdl/HalfLife") + +-- ------------------------------------------------------------------------------------------------ contract +local Mdl = { + name = "mdl", + category = "model", + extensions = { "mdl" }, + mime = { "model/x-mdl" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/model/Mat4", "codecs/model/Rig" }, + caps = { decode = true, encode = false, variants = { "quake", "halflife" }, morph = true, skins = true, animation = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + palette: (buffer | string)?, -- default: resolved gfx/palette.lmp, else grey + resolve: ((uri: string) -> (buffer | string)?)?, + files: { [string]: buffer | string }?, + frame: number?, -- Quake; default 1 + morph: boolean?, -- Quake; default true + fps: number?, -- Quake; default 10 + bodies: { number }?, -- Half-Life; 1-based, default 1 + textures: (buffer | string)?, + maxPixels: number?, -- default 2^24 + maxVertices: number?, -- default 2^24 +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Mdl.sniff(r: Bytes.Reader): number + local m = r:peek(4) + local v = r:peekU8(4) + if (m == "IDPO" and v == 6) or (m == "IDST" and v == 10) then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Mdl.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local size = r.limit - r.base + if size < 8 then + return nil, Err.new(Err.TRUNCATED, "header", 0) + end + local magic, version = r:peek(4), buffer.readi32(r.buf, r.base + 4) + local scene: Types.Scene?, msg: string? + if magic == "IDPO" then + if version ~= 6 then + return nil, Err.new(Err.UNSUPPORTED, "Quake MDL version " .. version, 4) + end + local pal = if opts and opts.palette then Bytes.toBuffer(opts.palette) else Input.sibling(opts, "gfx/palette.lmp") + if pal and buffer.len(pal) < 768 then + pal = nil + end + scene, msg = Quake.decode(r.buf, r.base, size, pal, opts :: any) + elseif magic == "IDST" then + if version ~= 10 then + return nil, Err.new(Err.UNSUPPORTED, "studio model version " .. version .. " (Source engine models need .vvd / .vtx)", 4) + end + local o: any = opts and table.clone(opts :: any) or {} + o.textures = if opts and opts.textures then Bytes.toBuffer(opts.textures) else nil + scene, msg = HalfLife.decode(r.buf, r.base, size, o) + else + return nil, Err.new(Err.CORRUPT, "bad magic", 0) + end + if not scene then + return nil, Err.from(msg) + end + return scene, nil +end + +return Mdl +end +__FILES["model/mdl/HalfLife"] = function() + +-- model/mdl/HalfLife: GoldSrc studio models ("IDST" v10), from the Half-Life SDK studio.h and HLMV / Crowbar notes; no +-- code taken. Not supported: sequence groups in other files, bone controllers, hitboxes / attachments / events, blends +-- past the first. +local Types = __include("Types") +local Mat4 = __include("codecs/model/Mat4") +local Pixels = __include("codecs/image/Pixels") +local Rig = __include("codecs/model/Rig") + +local HalfLife = {} + +local Scene = Types.Scene +local readi32, readi16, readu16, readu8, readf32 = buffer.readi32, buffer.readi16, buffer.readu16, buffer.readu8, buffer.readf32 +local writef32, writeu32, writeu16 = buffer.writef32, buffer.writeu32, buffer.writeu16 + +type Bone = { name: string, parent: number, value: { number }, scale: { number } } +type Options = { bodies: { number }?, textures: buffer?, maxPixels: number?, maxVertices: number? } + +local function str(b: buffer, at: number, n: number): string + return (string.match(buffer.readstring(b, at, n), "^[^%z]*")) :: string +end + +local function textures(b: buffer, base: number, size: number, maxPixels: number): ({ Types.Image }?, { string } | string) + local n, at = readi32(b, base + 180), readi32(b, base + 184) + if n < 0 or n > 4096 or at < 0 or at + n * 80 > size then + return nil, "bad texture table" + end + local out: { Types.Image } = {} + local names: { string } = {} + for i = 0, n - 1 do + local o = base + at + i * 80 + local w, h, data = readi32(b, o + 68), readi32(b, o + 72), readi32(b, o + 76) + if w <= 0 or h <= 0 or w * h > maxPixels or data < 0 or data + w * h + 768 > size then + return nil, "bad texture " .. i + end + local img = Types.Image.new(w, h) + local pal = Pixels.palette(b, base + data + w * h, 256) + Pixels.indexed(b, base + data, w, 8, img.pixels, w, h, true, pal) + local flags = readi32(b, o + 64) + img.meta.source = { format = "mdl", flags = flags } + out[i + 1] = img + names[i + 1] = str(b, o, 64) + end + return out, names +end + +-- bone default + stored value * scale +local function animValue(b: buffer, at: number, limit: number, f: number): number? + local p = at + local k = f + for _ = 1, 65536 do + if p + 2 > limit then + return nil + end + local valid, total = readu8(b, p), readu8(b, p + 1) + if total == 0 then + return nil + end + if total > k then + local idx = if valid > k then k + 1 else valid + if p + idx * 2 + 2 > limit then + return nil + end + return readi16(b, p + idx * 2) + end + k -= total + p += (valid + 1) * 2 + end + return nil +end + +function HalfLife.decode(b: buffer, base: number, size: number, opts: Options?): (Types.Scene?, string?) + if size < 244 then + return nil, "truncated header" + end + local limit = base + size + local function hdr(o: number): number + return readi32(b, base + o) + end + local nBones, oBones = hdr(140), hdr(144) + local nSeq, oSeq = hdr(164), hdr(168) + local nTex = hdr(180) + local nSkinRef, nFamilies, oSkins = hdr(192), hdr(196), hdr(200) + local nParts, oParts = hdr(204), hdr(208) + local function inside(o: number, n: number): boolean + return o >= 0 and n >= 0 and o + n <= size + end + if nBones < 0 or nBones > 256 or not inside(oBones, nBones * 112) then + return nil, "bad bone table" + end + if nSeq < 0 or nSeq > 4096 or not inside(oSeq, nSeq * 176) then + return nil, "bad sequence table" + end + if nParts < 0 or nParts > 256 or not inside(oParts, nParts * 76) then + return nil, "bad body part table" + end + local maxPixels = opts and opts.maxPixels or 2 ^ 24 + local scene = Scene.new() + scene.meta.up = "z" + local bones: { Bone } = {} + local joints: { Rig.Joint } = {} + for i = 0, nBones - 1 do + local o = base + oBones + i * 112 + local value, scale = {}, {} + for k = 0, 5 do + value[k + 1] = readf32(b, o + 64 + k * 4) + scale[k + 1] = readf32(b, o + 88 + k * 4) + end + local parent = readi32(b, o + 32) + bones[i + 1] = { name = str(b, o, 32), parent = parent + 1, value = value, scale = scale } + joints[i + 1] = { name = bones[i + 1].name, parent = parent + 1, translation = { value[1], value[2], value[3] }, rotation = Rig.angles(value[4], value[5], value[6]) } + end + local root: Types.Node = { name = str(b, base + 8, 64), children = {} } + table.insert(scene.nodes, root) + scene.roots[1] = 1 + local jointNodes, skinIndex, world = Rig.skeleton(scene, joints, "local", 1) + local texSrc, texBase, texSize = b, base, size + if nTex == 0 and opts and opts.textures then + texSrc, texBase, texSize = opts.textures, 0, buffer.len(opts.textures) + if texSize < 244 or buffer.readstring(texSrc, 0, 4) ~= "IDST" then + return nil, "opts.textures is not a studio texture file" + end + nSkinRef, nFamilies, oSkins = readi32(texSrc, 192), readi32(texSrc, 196), readi32(texSrc, 200) + end + local images, texNames = textures(texSrc, texBase, texSize, maxPixels) + if not images then + return nil, texNames :: string + end + local names = texNames :: { string } + for i, img in images do + table.insert(scene.textures, { name = names[i], image = img, uri = names[i] }) + local mat = Scene.material(names[i]) + mat.metallic = 0 + mat.baseColorTexture = { texture = i } + table.insert(scene.materials, mat) + end + local skinMap: { number } = {} + if nSkinRef > 0 and nFamilies > 0 and oSkins >= 0 and oSkins + nSkinRef * 2 <= texSize then + for r = 0, nSkinRef - 1 do + skinMap[r + 1] = readi16(texSrc, texBase + oSkins + r * 2) + 1 + end + end + local totalVerts = 0 + for part = 0, nParts - 1 do + local po = base + oParts + part * 76 + local pname = str(b, po, 64) + local nModels, oModels = readi32(b, po + 64), readi32(b, po + 72) + local pick = (opts and opts.bodies and opts.bodies[part + 1]) or 1 + if nModels > 0 and pick >= 1 and pick <= nModels and inside(oModels, nModels * 112) then + local mo = base + oModels + (pick - 1) * 112 + local nMesh, oMesh = readi32(b, mo + 72), readi32(b, mo + 76) + local nVerts, oVertInfo, oVerts = readi32(b, mo + 80), readi32(b, mo + 84), readi32(b, mo + 88) + local nNorms, oNormInfo, oNorms = readi32(b, mo + 92), readi32(b, mo + 96), readi32(b, mo + 100) + if nMesh < 0 or nMesh > 4096 or not inside(oMesh, nMesh * 20) or nVerts < 0 or not inside(oVertInfo, nVerts) or not inside(oVerts, nVerts * 12) or nNorms < 0 or not inside(oNormInfo, nNorms) or not inside(oNorms, nNorms * 12) then + return nil, "body part " .. pname .. ": bad model tables" + end + local mesh: Types.Mesh = { name = pname, primitives = {}, extras = { mdl = { model = str(b, mo, 64), models = nModels } } } + for m = 0, nMesh - 1 do + local me = base + oMesh + m * 20 + local oTri, skinref = readi32(b, me + 4), readi32(b, me + 8) + local tex = skinMap[skinref + 1] or (skinref + 1) + local img = images[tex] + local tw, th = if img then img.width else 1, if img then img.height else 1 + local weld: { [string]: number } = {} + local corners: { { number } } = {} + local indices: { number } = {} + local p = base + oTri + if oTri < 0 or oTri >= size then + return nil, "bad triangle command offset" + end + while true do + if p + 2 > limit then + return nil, "truncated triangle commands" + end + local n = readi16(b, p) + p += 2 + if n == 0 then + break + end + local fan = n < 0 + n = math.abs(n) + if p + n * 8 > limit then + return nil, "truncated triangle commands" + end + local ids: { number } = {} + for k = 0, n - 1 do + local o = p + k * 8 + local vi, ni, s, t = readu16(b, o), readu16(b, o + 2), readi16(b, o + 4), readi16(b, o + 6) + if vi >= nVerts or ni >= nNorms then + return nil, "triangle command vertex out of range" + end + local key = vi .. ":" .. ni .. ":" .. s .. ":" .. t + local id = weld[key] + if not id then + table.insert(corners, { vi, ni, s, t }) + id = #corners - 1 + weld[key] = id + end + ids[k + 1] = id + end + p += n * 8 + for k = 3, n do + local a, c2, c3 + if fan then + a, c2, c3 = ids[1], ids[k - 1], ids[k] + elseif k % 2 == 1 then + a, c2, c3 = ids[k - 2], ids[k - 1], ids[k] + else + a, c2, c3 = ids[k - 1], ids[k - 2], ids[k] + end + -- studio models wind clockwise: reverse + table.insert(indices, c3) + table.insert(indices, c2) + table.insert(indices, a) + end + end + local nv = #corners + totalVerts += nv + if totalVerts > (opts and opts.maxVertices or 2 ^ 24) then + return nil, "limit: too many vertices" + end + local pos, nrm, uv = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8) + local jb, wb = buffer.create(nv * 8), buffer.create(nv * 16) + for i, c in corners do + local o = (i - 1) * 12 + local bone = readu8(b, base + oVertInfo + c[1]) + local nbone = readu8(b, base + oNormInfo + c[2]) + local vo, no = base + oVerts + c[1] * 12, base + oNorms + c[2] * 12 + local x, y, z = readf32(b, vo), readf32(b, vo + 4), readf32(b, vo + 8) + local m4 = world[bone + 1] + if m4 then + x, y, z = Mat4.point(m4, x, y, z) + end + writef32(pos, o, x) + writef32(pos, o + 4, y) + writef32(pos, o + 8, z) + local nx, ny, nz = readf32(b, no), readf32(b, no + 4), readf32(b, no + 8) + local n4 = world[nbone + 1] + if n4 then + nx, ny, nz = n4[1] * nx + n4[5] * ny + n4[9] * nz, n4[2] * nx + n4[6] * ny + n4[10] * nz, n4[3] * nx + n4[7] * ny + n4[11] * nz + end + writef32(nrm, o, nx) + writef32(nrm, o + 4, ny) + writef32(nrm, o + 8, nz) + writef32(uv, (i - 1) * 8, c[3] / tw) + writef32(uv, (i - 1) * 8 + 4, c[4] / th) + writeu16(jb, (i - 1) * 8, math.min(bone, math.max(0, nBones - 1))) + writef32(wb, (i - 1) * 16, 1) + end + local ib = buffer.create(#indices * 4) + for i, v in indices do + writeu32(ib, (i - 1) * 4, v) + end + local attrs: { [string]: Types.Accessor } = { + POSITION = Scene.accessor(pos, "f32", 3, nv), + NORMAL = Scene.accessor(nrm, "f32", 3, nv), + TEXCOORD_0 = Scene.accessor(uv, "f32", 2, nv), + } + if nBones > 0 then + attrs.JOINTS_0 = Scene.accessor(jb, "u16", 4, nv) + attrs.WEIGHTS_0 = Scene.accessor(wb, "f32", 4, nv) + end + table.insert(mesh.primitives, { + attributes = attrs, + indices = Scene.accessor(ib, "u32", 1, #indices), + mode = "triangles" :: any, + material = if img then tex else nil, + }) + end + table.insert(scene.meshes, mesh) + table.insert(scene.nodes, { name = pname, children = {}, mesh = #scene.meshes, skin = if nBones > 0 then skinIndex else nil }) + table.insert(root.children, #scene.nodes) + end + end + local seqs: { any } = {} + for s = 0, nSeq - 1 do + local so = base + oSeq + s * 176 + local label, fps, nFrames = str(b, so, 32), readf32(b, so + 32), readi32(b, so + 56) + local nBlends, oAnim, group = readi32(b, so + 120), readi32(b, so + 124), readi32(b, so + 156) + table.insert(seqs, { name = label, fps = fps, frames = nFrames, blends = nBlends, group = group }) + if group == 0 and nFrames > 0 and nFrames <= 65536 and nBones > 0 and inside(oAnim, nBones * 12) then + local rate = if fps > 0 then fps else 30 + local times: { number } = {} + for f = 0, nFrames - 1 do + times[f + 1] = f / rate + end + local tracks: { [number]: Rig.Track } = {} + for j = 1, nBones do + local bn = bones[j] + local ao = base + oAnim + (j - 1) * 12 + local tr, rot = {}, {} + for f = 0, nFrames - 1 do + local v: { number } = {} + for k = 0, 5 do + local off = readu16(b, ao + k * 2) + local raw = if off ~= 0 then animValue(b, ao + off, limit, f) else nil + v[k + 1] = bn.value[k + 1] + (raw or 0) * bn.scale[k + 1] + end + table.insert(tr, v[1]) + table.insert(tr, v[2]) + table.insert(tr, v[3]) + local q = Rig.angles(v[4], v[5], v[6]) + for k = 1, 4 do + table.insert(rot, q[k]) + end + end + tracks[j] = { translation = tr, rotation = rot } + end + Rig.animation(scene, label, jointNodes, times, tracks, "LINEAR") + end + end + scene.meta.source = { + format = "mdl", + variant = "halflife", + name = root.name, + bones = nBones, + sequences = seqs, + textures = #images, + skinFamilies = nFamilies, + hitboxes = hdr(156), + attachments = hdr(212), + } + return scene, nil +end + +return HalfLife +end +__FILES["model/mdl/Quake"] = function() + +-- model/mdl/Quake: Quake 1 MDL ("IDPO" v6), from "Quake Specs 3.4" section 5 and modelgen.h; no code taken. Seam +-- texture coordinates of back-facing triangles move half a skin width; a skin group shows its first picture. +local Types = __include("Types") +local Pixels = __include("codecs/image/Pixels") +local Rig = __include("codecs/model/Rig") + +local Quake = {} + +local Scene = Types.Scene +local readi32, readf32, readu8, writef32, writeu32 = buffer.readi32, buffer.readf32, buffer.readu8, buffer.writef32, buffer.writeu32 + +type Options = { frame: number?, morph: boolean?, fps: number?, maxVertices: number?, maxPixels: number? } + +local function name16(b: buffer, at: number): string + return (string.match(buffer.readstring(b, at, 16), "^[^%z]*")) :: string +end + +function Quake.decode(b: buffer, base: number, size: number, palette: buffer?, opts: Options?): (Types.Scene?, string?) + if size < 84 then + return nil, "truncated header" + end + local scale = { readf32(b, base + 8), readf32(b, base + 12), readf32(b, base + 16) } + local origin = { readf32(b, base + 20), readf32(b, base + 24), readf32(b, base + 28) } + local nSkins, sw, sh = readi32(b, base + 48), readi32(b, base + 52), readi32(b, base + 56) + local nVerts, nTris, nFrames = readi32(b, base + 60), readi32(b, base + 64), readi32(b, base + 68) + if nSkins < 0 or sw < 0 or sh < 0 or nVerts <= 0 or nTris < 0 or nFrames <= 0 or nSkins > 1024 or nFrames > 65536 then + return nil, "bad counts" + end + if sw * sh > (opts and opts.maxPixels or 2 ^ 24) then + return nil, "limit: skin too big" + end + if nFrames * nVerts > (opts and opts.maxVertices or 2 ^ 24) then + return nil, "limit: too many vertices" + end + local p = 84 + local function need(n: number): boolean + return n >= 0 and p + n <= size + end + local pal = if palette then Pixels.palette(palette, 0, 256) else nil + local skins: { Types.Image } = {} + local px = sw * sh + for _ = 1, nSkins do + if not need(4) then + return nil, "truncated skins" + end + local group = readi32(b, base + p) + p += 4 + local count = 1 + if group ~= 0 then + if not need(4) then + return nil, "truncated skin group" + end + count = readi32(b, base + p) + p += 4 + if count <= 0 or count > 256 or not need(count * 4) then + return nil, "bad skin group" + end + p += count * 4 + end + if not need(count * px) then + return nil, "truncated skin pixels" + end + local img = Types.Image.new(sw, sh) + if pal then + Pixels.indexed(b, base + p, sw, 8, img.pixels, sw, sh, true, pal) + else + for i = 0, px - 1 do + local v = readu8(b, base + p + i) + writeu32(img.pixels, i * 4, 0xFF000000 + v * 0x10101) + end + end + img.meta.source = { format = "mdl", palette = pal ~= nil, frames = count } + table.insert(skins, img) + p += count * px + end + if not need(nVerts * 12 + nTris * 16) then + return nil, "truncated vertices / triangles" + end + local stAt = p + p += nVerts * 12 + local weld: { [number]: number } = {} + local src: { number }, uvs: { number } = {}, {} + local indices: { number } = {} + for t = 0, nTris - 1 do + local o = base + p + t * 16 + local front = readi32(b, o) ~= 0 + local c: { number } = {} + for k = 1, 3 do + local v = readi32(b, o + k * 4) + if v < 0 or v >= nVerts then + return nil, "triangle vertex out of range" + end + local so = base + stAt + v * 12 + local seam = readi32(b, so) ~= 0 and not front + local key = v * 2 + (if seam then 1 else 0) + local id = weld[key] + if not id then + table.insert(src, v) + local s = readi32(b, so + 4) + (if seam then sw / 2 else 0) + table.insert(uvs, (s + 0.5) / math.max(sw, 1)) + table.insert(uvs, (readi32(b, so + 8) + 0.5) / math.max(sh, 1)) + id = #src - 1 + weld[key] = id + end + c[k] = id + end + -- Quake's front faces are clockwise + table.insert(indices, c[3]) + table.insert(indices, c[2]) + table.insert(indices, c[1]) + end + p += nTris * 16 + -- frames: simple (type 0) or groups + local frameAt: { number } = {} + local names: { string } = {} + local fsize = 24 + nVerts * 4 + for _ = 1, nFrames do + if not need(4) then + return nil, "truncated frames" + end + local kind = readi32(b, base + p) + p += 4 + if kind == 0 then + if not need(fsize) then + return nil, "truncated frame" + end + table.insert(frameAt, p + 8) + table.insert(names, name16(b, base + p + 8)) + p += fsize + else + if not need(12) then + return nil, "truncated frame group" + end + local count = readi32(b, base + p) + if count <= 0 or count > 4096 or not need(12 + count * 4 + count * fsize) then + return nil, "bad frame group" + end + p += 12 + count * 4 + for _ = 1, count do + table.insert(frameAt, p + 8) + table.insert(names, name16(b, base + p + 8)) + p += fsize + end + end + end + local nv = #src + local total = #frameAt + local morph = not (opts and opts.morph == false) + local want = math.clamp(math.floor(opts and opts.frame or 1), 1, total) + local positions: { buffer }, normals: { buffer } = {}, {} + for f, at in frameAt do + if morph or f == want then + local pos = buffer.create(nv * 12) + local vo = base + at + 16 + for i, v in src do + for k = 0, 2 do + writef32(pos, (i - 1) * 12 + k * 4, readu8(b, vo + v * 4 + k) * scale[k + 1] + origin[k + 1]) + end + end + positions[f] = pos + normals[f] = Rig.normals(pos, nv, indices) + end + end + local ib = buffer.create(#indices * 4) + for i, v in indices do + writeu32(ib, (i - 1) * 4, v) + end + local uvb = buffer.create(nv * 8) + for i, v in uvs do + writef32(uvb, (i - 1) * 4, v) + end + local prim: Types.Primitive = { + attributes = { + POSITION = Scene.accessor(positions[want], "f32", 3, nv), + NORMAL = Scene.accessor(normals[want], "f32", 3, nv), + TEXCOORD_0 = Scene.accessor(uvb, "f32", 2, nv), + }, + indices = Scene.accessor(ib, "u32", 1, #indices), + mode = "triangles", + } + local scene = Scene.new() + scene.meta.up = "z" + for i, img in skins do + table.insert(scene.textures, { name = "skin " .. i, image = img, sampler = { filter = "nearest" :: any } }) + end + if #skins > 0 then + local mat = Scene.material("skin") + mat.metallic = 0 + mat.baseColorTexture = { texture = 1 } + scene.materials[1] = mat + prim.material = 1 + end + scene.meshes[1] = { primitives = { prim } } + scene.nodes[1] = { children = {}, mesh = 1 } + scene.roots[1] = 1 + if morph then + Rig.morph(prim, positions, normals) + scene.meshes[1].weights = table.create(total, 0) + local ranges: { Rig.Range } = {} + for i, n in names do + local stem = string.match(n, "^(.-)%d*$") or n + local last = ranges[#ranges] + if last and last.name == stem then + last.last = i + else + table.insert(ranges, { name = if stem ~= "" then stem else n, first = i, last = i, fps = opts and opts.fps or 10 }) + end + end + Rig.morphAnimation(scene, 1, total, ranges, "LINEAR") + end + scene.meta.source = { format = "mdl", variant = "quake", frames = total, frameNames = names, skinWidth = sw, skinHeight = sh, palette = pal ~= nil } + return scene, nil +end + +return Quake +end +__FILES["model/ms3d"] = function() + +-- model/ms3d: MilkShape 3D 1.8 (.ms3d v3 / v4), from ms3dspec.h, tested against assimp's MS3D importer (no code +-- ported). Supports: groups, materials, joints, a skin, keyframes, comments and the extra blocks, read + write. Not +-- supported: scale keys (MilkShape has none), a second skin; writes at most 65535 vertices, 255 groups, 127 joints. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Read = __include("model/ms3d/Read") +local Write = __include("model/ms3d/Write") + +-- ------------------------------------------------------------------------------------------------ contract +local Ms3d = { + name = "ms3d", + category = "model", + extensions = { "ms3d" }, + mime = { "application/x-ms3d" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten" }, + caps = { decode = true, encode = true, materials = true, skins = true, animation = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + maxVertices: number?, -- default 2^20 +} +type EncodeOptions = { + fps: number?, -- default: the source's, else 24 + name: string?, + files: { [string]: any }?, +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Ms3d.sniff(r: Bytes.Reader): number + local h = r:peek(14) + if string.sub(h, 1, 10) ~= Read.MAGIC then + return 0 + end + local v = string.byte(h, 11) + return if v == 3 or v == 4 then 1 else 0.6 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Ms3d.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local ok, scene, msg, at = pcall(Read.scene, r.buf, r.base, r.limit, opts) + if not ok then + return nil, Err.new(Err.CORRUPT, "bad data: " .. tostring(scene)) + end + if not scene then + return nil, Err.from(msg, at) + end + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Ms3d.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(scene) ~= "table" or scene.kind ~= "scene" then + return nil, Err.new(Err.ARG, "needs a Scene") + end + local ok, out, err = pcall(Write.encode, scene, opts) + if not ok then + return nil, Err.new(Err.ARG, "bad scene: " .. tostring(out)) + end + if not out then + return nil, Err.new(Err.ARG, tostring(err)) + end + return out, nil +end + +return Ms3d +end +__FILES["model/ms3d/Read"] = function() + +-- model/ms3d/Read: the ms3dspec.h layout: vertices, triangles, groups, materials (shininess 0..128), the animation +-- header, joints (local Euler XYZ radians, keys in seconds relative to the rest pose), then the sub-versioned comments, +-- vertex extras (weights in percent, subversion 1-3), joint extras (colours) and model extras. Never throws. +local Types = __include("Types") +local Mat4 = __include("codecs/model/Mat4") + +local Read = {} + +local S = Types.Scene +local readu8, readi8, readu16, readi32, readf32, readstring = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi32, buffer.readf32, buffer.readstring +local writef32, writeu8, writeu16, writeu32 = buffer.writef32, buffer.writeu8, buffer.writeu16, buffer.writeu32 + +Read.MAGIC = "MS3D000000" + +type Options = { maxVertices: number? } + +-- ------------------------------------------------------------------------------------------------ helpers +local function fixed(b: buffer, p: number, n: number): string + local s = readstring(b, p, n) + local z = string.find(s, "\0", 1, true) + return if z then string.sub(s, 1, z - 1) else s +end + +local function floats(values: { number }, comps: number): Types.Accessor + local n = #values // comps + local a = S.accessor(nil, "f32", comps, n) + for i = 1, n * comps do + writef32(a.data, (i - 1) * 4, values[i]) + end + return a +end + +local function color(b: buffer, p: number): { number } + return { readf32(b, p), readf32(b, p + 4), readf32(b, p + 8), readf32(b, p + 12) } +end + +-- the texture file name as a relative uri (MilkShape writes ".\name.jpg") +local function uri(s: string): string + local u = string.gsub(s, "\\", "/") + u = string.gsub(u, "^%./", "") + return u +end + +-- the rotation of Euler XYZ radians (R = Rz * Ry * Rx) as a quaternion +local function euler(x: number, y: number, z: number): { number } + return Mat4.quat(Mat4.euler(math.deg(x), math.deg(y), math.deg(z))) +end + +-- ------------------------------------------------------------------------------------------------ parse +type Vertex = { pos: { number }, bones: { number }, weights: { number } } +type Joint = { + name: string, parent: string, flags: number, rot: { number }, pos: { number }, + rotKeys: { { number } }, posKeys: { { number } }, comment: string?, color: { number }?, +} + +function Read.scene(b: buffer, base: number, limit: number, opts: Options?): (Types.Scene?, string?, number?) + local p = base + local function need(n: number): boolean + return p + n <= limit + end + if not need(14) or readstring(b, p, 10) ~= Read.MAGIC then + return nil, "not a MilkShape 3D file", base + end + local version = readi32(b, p + 10) + if version ~= 3 and version ~= 4 then + return nil, "unsupported: version " .. version, p + 10 + end + p += 14 + local maxV = opts and opts.maxVertices or 2 ^ 20 + if not need(2) then + return nil, "truncated vertex count", p + end + local nv = readu16(b, p) + p += 2 + if not need(nv * 15) then + return nil, "truncated vertices", p + end + local verts: { Vertex } = {} + for i = 1, nv do + local q = p + (i - 1) * 15 + verts[i] = { pos = { readf32(b, q + 1), readf32(b, q + 5), readf32(b, q + 9) }, bones = { readi8(b, q + 13), -1, -1, -1 }, weights = { 1, 0, 0, 0 } } + end + p += nv * 15 + if not need(2) then + return nil, "truncated triangle count", p + end + local nt = readu16(b, p) + p += 2 + if not need(nt * 70) then + return nil, "truncated triangles", p + end + if nt * 3 > maxV then + return nil, "limit: more than " .. maxV .. " triangle corners", p + end + local triAt = p + p += nt * 70 + if not need(2) then + return nil, "truncated group count", p + end + local ng = readu16(b, p) + p += 2 + local groups = {} + for _ = 1, ng do + if not need(35) then + return nil, "truncated group", p + end + local g = { flags = readu8(b, p), name = fixed(b, p + 1, 32), tris = {} :: { number }, material = -1, comment = nil :: string? } + local n = readu16(b, p + 33) + p += 35 + if not need(n * 2 + 1) then + return nil, "truncated group triangles", p + end + for k = 0, n - 1 do + local ti = readu16(b, p + k * 2) + if ti >= nt then + return nil, "group triangle " .. ti .. " out of range", p + k * 2 + end + table.insert(g.tris, ti) + end + p += n * 2 + g.material = readi8(b, p) + p += 1 + table.insert(groups, g) + end + if not need(2) then + return nil, "truncated material count", p + end + local nm = readu16(b, p) + p += 2 + if not need(nm * 361) then + return nil, "truncated materials", p + end + local mats = {} + for i = 0, nm - 1 do + local q = p + i * 361 + table.insert(mats, { + name = fixed(b, q, 32), ambient = color(b, q + 32), diffuse = color(b, q + 48), specular = color(b, q + 64), + emissive = color(b, q + 80), shininess = readf32(b, q + 96), transparency = readf32(b, q + 100), + mode = readi8(b, q + 104), texture = fixed(b, q + 105, 128), alphamap = fixed(b, q + 233, 128), comment = nil :: string?, + }) + end + p += nm * 361 + -- version 3 files may end here + local fps, current, frames = 24, 0, 0 + local joints: { Joint } = {} + if need(12) then + fps, current, frames = readf32(b, p), readf32(b, p + 4), readi32(b, p + 8) + p += 12 + if not need(2) then + return nil, "truncated joint count", p + end + local nj = readu16(b, p) + p += 2 + for _ = 1, nj do + if not need(93) then + return nil, "truncated joint", p + end + local j: Joint = { + flags = readu8(b, p), name = fixed(b, p + 1, 32), parent = fixed(b, p + 33, 32), + rot = { readf32(b, p + 65), readf32(b, p + 69), readf32(b, p + 73) }, + pos = { readf32(b, p + 77), readf32(b, p + 81), readf32(b, p + 85) }, + rotKeys = {}, posKeys = {}, + } + local nr, np = readu16(b, p + 89), readu16(b, p + 91) + p += 93 + if not need((nr + np) * 16) then + return nil, "truncated joint keys", p + end + for k = 0, nr + np - 1 do + local q = p + k * 16 + local key = { readf32(b, q), readf32(b, q + 4), readf32(b, q + 8), readf32(b, q + 12) } + table.insert(if k < nr then j.rotKeys else j.posKeys, key) + end + p += (nr + np) * 16 + table.insert(joints, j) + end + end + local source: { [string]: any } = { format = "ms3d", version = version, fps = fps, currentTime = current, frames = frames } + local function comments(list: { any }): string? + if not need(4) then + return "truncated comments" + end + local n = readi32(b, p) + p += 4 + for _ = 1, math.max(n, 0) do + if not need(8) then + return "truncated comment" + end + local index, len = readi32(b, p), readi32(b, p + 4) + p += 8 + if len < 0 or not need(len) then + return "comment runs past the end" + end + if list[index + 1] then + list[index + 1].comment = readstring(b, p, len) + end + p += len + end + return nil + end + if need(4) then + local sub = readi32(b, p) + p += 4 + source.commentVersion = sub + if sub == 1 then + for _, list in { groups, mats, joints } :: { { any } } do + local e = comments(list) + if e then + return nil, e, p + end + end + if not need(4) then + return nil, "truncated model comment", p + end + local has = readi32(b, p) + p += 4 + if has ~= 0 then + if not need(4) then + return nil, "truncated model comment", p + end + local len = readi32(b, p) + p += 4 + if len < 0 or not need(len) then + return nil, "model comment runs past the end", p + end + source.comment = readstring(b, p, len) + p += len + end + end + end + if need(4) then + local sub = readi32(b, p) + p += 4 + source.vertexVersion = sub + local size = if sub == 1 then 6 elseif sub == 2 then 10 elseif sub == 3 then 14 else 0 + if size > 0 and need(nv * size) then + for i = 1, nv do + local q = p + (i - 1) * size + local v = verts[i] + local w0, w1, w2 = readu8(b, q + 3), readu8(b, q + 4), readu8(b, q + 5) + if w0 + w1 + w2 > 0 then + local scale = if w0 > 100 or w1 > 100 or w2 > 100 or w0 + w1 + w2 > 100 then 255 else 100 + v.bones = { v.bones[1], readi8(b, q), readi8(b, q + 1), readi8(b, q + 2) } + v.weights = { w0 / scale, w1 / scale, w2 / scale, math.max(0, 1 - (w0 + w1 + w2) / scale) } + end + end + p += nv * size + end + end + if need(4) then + local sub = readi32(b, p) + p += 4 + if (sub == 1 or sub == 2) and need(#joints * 12) then + for _, j in joints do + j.color = { readf32(b, p), readf32(b, p + 4), readf32(b, p + 8) } + p += 12 + end + end + end + if need(16) and readi32(b, p) >= 1 then + source.jointSize, source.transparencyMode, source.alphaRef = readf32(b, p + 4), readi32(b, p + 8), readf32(b, p + 12) + end + return Read.build(b, triAt, verts, groups, mats, joints, source), nil, nil +end + +-- ------------------------------------------------------------------------------------------------ build +function Read.build(b: buffer, triAt: number, verts: { Vertex }, groups: { any }, mats: { any }, joints: { Joint }, source: { [string]: any }): Types.Scene + local scene = S.new() + scene.meta.up = "y" + scene.meta.source = source :: any + for _, m in mats do + local mat = S.material(m.name) + local d = m.diffuse + mat.baseColor = { d[1], d[2], d[3], math.clamp(m.transparency, 0, 1) } + mat.metallic = 0 + mat.roughness = math.clamp(math.sqrt(2 / (math.clamp(m.shininess, 0, 128) + 2)), 0, 1) + mat.emissive = { m.emissive[1], m.emissive[2], m.emissive[3] } + mat.alphaMode = if m.transparency < 1 then "blend" else "opaque" + if m.texture ~= "" then + local tex: Types.Texture = { name = m.texture, uri = uri(m.texture) } + table.insert(scene.textures, tex) + mat.baseColorTexture = { texture = #scene.textures } + end + mat.extras = { + ms3d = { + ambient = m.ambient, diffuse = m.diffuse, specular = m.specular, emissive = m.emissive, shininess = m.shininess, + transparency = m.transparency, mode = m.mode, texture = m.texture, alphamap = m.alphamap, comment = m.comment, + }, + } + table.insert(scene.materials, mat) + end + local nj = #joints + local jointNode: { [number]: number } = {} + local byName: { [string]: number } = {} + local abs: { { number } } = {} + for i, j in joints do + local node: Types.Node = { name = j.name, children = {}, translation = j.pos, rotation = euler(j.rot[1], j.rot[2], j.rot[3]) } + node.extras = { ms3d = { flags = j.flags, comment = j.comment, color = j.color } } + table.insert(scene.nodes, node) + jointNode[i] = #scene.nodes + if byName[j.name] == nil then + byName[j.name] = i + end + end + for i, j in joints do + local pi = byName[j.parent] + -- parents must come first (MilkShape writes them in that order); others become roots + local local_ = S.nodeMatrix(scene.nodes[jointNode[i]]) + if pi and pi < i then + table.insert(scene.nodes[jointNode[pi]].children, jointNode[i]) + abs[i] = S.mul(abs[pi], local_) + else + table.insert(scene.roots, jointNode[i]) + abs[i] = local_ + end + end + local skinned = false + for _, v in verts do + for k = 1, 4 do + if v.bones[k] >= nj then + v.bones[k] = -1 + end + end + skinned = skinned or (nj > 0 and v.bones[1] >= 0) + end + if nj > 0 then + local ibm = S.accessor(nil, "f32", 16, nj) + ibm.matrix = true + for i = 1, nj do + local inv = Mat4.inverse(abs[i]) or Mat4.identity() + for k = 1, 16 do + writef32(ibm.data, ((i - 1) * 16 + k - 1) * 4, inv[k]) + end + end + local list = table.create(nj, 0) + for i = 1, nj do + list[i] = jointNode[i] + end + scene.skins[1] = { joints = list, inverseBindMatrices = ibm } + end + local nv = #verts + for gi, g in groups do + local remap: { [string]: number } = {} + local P, N, U, J, W = {}, {}, {}, {}, {} + local idx: { number } = {} + local sgs: { number } = {} + local count = 0 + for _, ti in g.tris do + local q = triAt + ti * 70 + if readu16(b, q + 2) >= nv or readu16(b, q + 4) >= nv or readu16(b, q + 6) >= nv then + continue + end + table.insert(sgs, readu8(b, q + 68)) + for k = 0, 2 do + local vi = readu16(b, q + 2 + k * 2) + local key = vi .. readstring(b, q + 8 + k * 12, 12) .. readstring(b, q + 44 + k * 4, 4) .. readstring(b, q + 56 + k * 4, 4) + local o = remap[key] + if o == nil then + o = count + count += 1 + remap[key] = o + local v = verts[vi + 1] + table.move(v.pos, 1, 3, o * 3 + 1, P) + N[o * 3 + 1], N[o * 3 + 2], N[o * 3 + 3] = readf32(b, q + 8 + k * 12), readf32(b, q + 12 + k * 12), readf32(b, q + 16 + k * 12) + U[o * 2 + 1], U[o * 2 + 2] = readf32(b, q + 44 + k * 4), readf32(b, q + 56 + k * 4) + local sum = 0 + for c = 1, 4 do + if v.bones[c] >= 0 then + sum += v.weights[c] + end + end + for c = 1, 4 do + local ok = v.bones[c] >= 0 and sum > 0 + J[o * 4 + c] = if ok then v.bones[c] else 0 + W[o * 4 + c] = if ok then v.weights[c] / sum else 0 + end + end + table.insert(idx, o :: number) + end + end + local prim: Types.Primitive = { + attributes = { POSITION = floats(P, 3), NORMAL = floats(N, 3), TEXCOORD_0 = floats(U, 2) }, + mode = "triangles", + material = if g.material >= 0 and g.material < #mats then g.material + 1 else nil, + extras = { ms3d = { smoothing = sgs } }, + } + local ind = S.accessor(nil, "u32", 1, #idx) + for i, v in idx do + writeu32(ind.data, (i - 1) * 4, v) + end + prim.indices = ind + local node: Types.Node = { name = g.name, children = {}, extras = { ms3d = { flags = g.flags, comment = g.comment } } } + if skinned then + local ja = S.accessor(nil, if nj > 255 then "u16" else "u8", 4, count) + for i = 1, count * 4 do + if nj > 255 then + writeu16(ja.data, (i - 1) * 2, J[i]) + else + writeu8(ja.data, i - 1, J[i]) + end + end + prim.attributes.JOINTS_0 = ja + prim.attributes.WEIGHTS_0 = floats(W, 4) + node.skin = 1 + end + local mesh: Types.Mesh = { name = g.name :: string, primitives = { prim } } + scene.meshes[gi] = mesh + node.mesh = gi + table.insert(scene.nodes, node) + table.insert(scene.roots, #scene.nodes) + end + local channels: { Types.Channel } = {} + for i, j in joints do + if #j.rotKeys > 0 then + local times, vals = {}, {} + local rest = scene.nodes[jointNode[i]].rotation :: { number } + for _, k in j.rotKeys do + table.insert(times, k[1]) + local q = Mat4.quat(Mat4.mul(Mat4.fromQuat(rest), Mat4.fromQuat(euler(k[2], k[3], k[4])))) + table.move(q, 1, 4, #vals + 1, vals) + end + local ch: Types.Channel = { node = jointNode[i], path = "rotation", input = floats(times, 1), output = floats(vals, 4), interpolation = "LINEAR" } + table.insert(channels, ch) + end + if #j.posKeys > 0 then + local times, vals = {}, {} + for _, k in j.posKeys do + table.insert(times, k[1]) + table.insert(vals, j.pos[1] + k[2]) + table.insert(vals, j.pos[2] + k[3]) + table.insert(vals, j.pos[3] + k[4]) + end + local ch: Types.Channel = { node = jointNode[i], path = "translation", input = floats(times, 1), output = floats(vals, 3), interpolation = "LINEAR" } + table.insert(channels, ch) + end + end + if #channels > 0 then + table.insert(scene.animations, { name = "ms3d", channels = channels }) + end + return scene +end + +return Read +end +__FILES["model/ms3d/Write"] = function() + +-- model/ms3d/Write: Scene -> MilkShape 3D v4: a group per placed primitive, the first skin's joints (rest pose from +-- the inverse bind matrices, keys relative to it), vertex extras subversion 2 (weights in percent). +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Mat4 = __include("codecs/model/Mat4") +local Flatten = __include("codecs/model/MeshFlatten") + +local Write = {} + +local S = Types.Scene +local sqrt = math.sqrt + +type Options = { fps: number?, name: string?, files: { [string]: any }? } + +local function fixedString(w: Bytes.Writer, s: string, n: number) + local v = string.sub(string.gsub(s, "%z", ""), 1, n - 1) + w:string(v) + for _ = #v + 1, n do + w:u8(0) + end +end + +local function msg(s: any): string + return if type(s) == "string" then s else "" +end + +-- ------------------------------------------------------------------------------------------------ tree +type Tree = { world: { [number]: { number } }, parent: { [number]: number }, order: { number } } +local function tree(scene: Types.Scene): Tree + local t: Tree = { world = {}, parent = {}, order = {} } + local function visit(i: number, p: number, pm: { number }, depth: number) + local n = scene.nodes[i] + if type(n) ~= "table" or t.world[i] or depth > 256 then + return + end + t.world[i] = S.mul(pm, S.nodeMatrix(n)) + t.parent[i] = p + table.insert(t.order, i) + for _, c in n.children or {} do + visit(c, i, t.world[i], depth + 1) + end + end + for _, r in scene.roots do + visit(r, 0, S.IDENTITY, 0) + end + return t +end + +-- ------------------------------------------------------------------------------------------------ joints +type Joint = { node: number, name: string, parent: string, pos: { number }, rot: { number }, quat: { number }, rotKeys: { { number } }, posKeys: { { number } } } + +local function rigid(m: { number }): { number } + local t, r = Mat4.decompose(m) + return Mat4.compose(t, r, nil) +end + +local function joints(scene: Types.Scene, tr: Tree): ({ Joint }, { [number]: number }, { [number]: number }, { number }) + local skin = scene.skins[1] + local anim = scene.animations[1] + local out: { Joint } = {} + local bySkin: { [number]: number } = {} + local byNode: { [number]: number } = {} + local skinIndex: { [number]: number } = {} + local isJoint: { [number]: boolean } = {} + for k, ni in (if skin then skin.joints else {}) :: { number } do + skinIndex[ni] = k - 1 + isJoint[ni] = true + end + local chans: { [number]: { Types.Channel } } = {} + for _, ch in (if anim then anim.channels else {}) :: { Types.Channel } do + if (ch.path == "rotation" or ch.path == "translation") and tr.world[ch.node] then + isJoint[ch.node] = true + chans[ch.node] = chans[ch.node] or {} + table.insert(chans[ch.node], ch) + end + end + local B = S.IDENTITY + local IBM: any = if skin and skin.inverseBindMatrices then S.reader(skin.inverseBindMatrices) else nil + if skin and IBM and tr.world[skin.joints[1]] then + local m = table.create(16, 0) + for c = 1, 16 do + m[c] = (IBM :: any)(0, c - 1) + end + B = S.mul(tr.world[skin.joints[1]], m) + end + local names: { [string]: boolean } = {} + for _, ni in tr.order do + if not isJoint[ni] or #out >= 127 then + continue + end + local p = tr.parent[ni] + while p ~= 0 and byNode[p] == nil do + p = tr.parent[p] + end + -- MilkShape joints are rigid: rest = (parent's rigid world)^-1 * rigid world + local invP = if p ~= 0 then Mat4.inverse(rigid(tr.world[p])) or Mat4.identity() else Mat4.identity() + local gp = tr.parent[ni] + local C = S.mul(invP, if gp ~= 0 then tr.world[gp] else S.IDENTITY) + local t, r = Mat4.decompose(S.mul(invP, rigid(tr.world[ni]))) + local e = Mat4.eulerXYZ(r) + local base = string.sub(msg(scene.nodes[ni].name), 1, 27) + local name = if base ~= "" then base else "joint" .. #out + local n = 1 + while names[name] do + n += 1 + name = base .. "_" .. n + end + names[name] = true + local j: Joint = { + node = ni, name = name, parent = if p ~= 0 then out[byNode[p] + 1].name else "", pos = t, + rot = { math.rad(e[1]), math.rad(e[2]), math.rad(e[3]) }, quat = r, rotKeys = {}, posKeys = {}, + } + table.insert(out, j) + byNode[ni] = #out - 1 + if skinIndex[ni] then + bySkin[skinIndex[ni]] = #out - 1 + end + -- keys relative to the rest pose: rotation rest^-1 * C * R(t), position C * T(t) - rest + local _, rc = Mat4.decompose(C) + local inv = Mat4.transpose3(Mat4.fromQuat(r)) + for _, ch in chans[ni] or {} do + local IN, OUT = S.reader(ch.input) :: any, S.reader(ch.output) :: any + local cubic = ch.interpolation == "CUBICSPLINE" + for k = 0, ch.input.count - 1 do + local v = if cubic then k * 3 + 1 else k + local time = IN(k, 0) + if ch.path == "rotation" then + local q = { OUT(v, 0), OUT(v, 1), OUT(v, 2), OUT(v, 3) } + local l = sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3] + q[4] * q[4]) + q = if l > 0 then { q[1] / l, q[2] / l, q[3] / l, q[4] / l } else { 0, 0, 0, 1 } + local d = Mat4.eulerXYZ(Mat4.quat(S.mul(inv, S.mul(Mat4.fromQuat(rc), Mat4.fromQuat(q))))) + table.insert(j.rotKeys, { time, math.rad(d[1]), math.rad(d[2]), math.rad(d[3]) }) + else + local x, y, z = Mat4.point(C, OUT(v, 0), OUT(v, 1), OUT(v, 2)) + table.insert(j.posKeys, { time, x - t[1], y - t[2], z - t[3] }) + end + end + end + end + return out, bySkin, byNode, B +end + +-- ------------------------------------------------------------------------------------------------ geometry +type Vertex = { x: number, y: number, z: number, bones: { number }, weights: { number } } +type Tri = { v: { number }, n: { number }, uv: { number }, sg: number, group: number } +type Group = { name: string, tris: { number }, material: number, flags: number, comment: string? } + +local function geometry(scene: Types.Scene, tr: Tree, bySkin: { [number]: number }, byNode: { [number]: number }, B: { number }): ({ Vertex }, { Tri }, { Group }, string?) + local verts: { Vertex }, tris: { Tri }, groups: { Group } = {}, {}, {} + for _, pl in S.flatten(scene) do + local prim: any = pl.primitive + local node = scene.nodes[pl.node] + local merged, err = Flatten.merge({ kind = "scene", nodes = {}, roots = {}, meshes = { { primitives = { prim } } } }, function(): boolean + return false + end, { triangulate = true }) + if not merged then + return verts, tris, groups, err + end + local corners = merged.corners + if #corners == 0 then + continue + end + local skinned = node.skin == 1 and prim.attributes.JOINTS_0 ~= nil and prim.attributes.WEIGHTS_0 ~= nil + local rigid = -1 + if not skinned then + local p = pl.node + while p and p ~= 0 do + if byNode[p] then + rigid = byNode[p] + break + end + p = tr.parent[p] + end + end + local M = if skinned then B else pl.matrix + local NM = Mat4.normalMatrix(M) + local mirror = 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]) < 0 + local A = prim.attributes + local POS = S.reader(A.POSITION) :: any + local zero = function(_: number, _: number): number + return 0 + end + type Get = (number, number) -> number + local hasN, hasUV = A.NORMAL ~= nil, A.TEXCOORD_0 ~= nil + local NOR: Get = (if hasN then S.reader(A.NORMAL) else nil) or zero + local UV: Get = (if hasUV then S.reader(A.TEXCOORD_0) else nil) or zero + local JO: Get = (if skinned then S.reader(A.JOINTS_0) else nil) or zero + local WE: Get = (if skinned then S.reader(A.WEIGHTS_0) else nil) or zero + local base = #verts + local nv = A.POSITION.count + if base + nv > 65535 then + return verts, tris, groups, "more than 65535 vertices" + end + for v = 0, nv - 1 do + local x, y, z = Mat4.point(M, POS(v, 0), POS(v, 1), POS(v, 2)) + local bones, weights = { rigid, -1, -1, -1 }, { 1, 0, 0, 0 } + if skinned then + local inf = {} + for c = 0, 3 do + local w = WE(v, c) + local j = bySkin[JO(v, c)] + if w > 0 and j then + table.insert(inf, { j, w }) + end + end + table.sort(inf, function(a: { number }, b: { number }): boolean + return a[2] > b[2] + end) + local sum = 0 + for _, e in inf do + sum += e[2] + end + for c = 1, 4 do + local e = inf[c] + bones[c] = if e then e[1] else -1 + weights[c] = if e and sum > 0 then e[2] / sum else 0 + end + end + table.insert(verts, { x = x, y = y, z = z, bones = bones, weights = weights }) + end + local gi = #groups + if gi >= 255 then + return verts, tris, groups, "more than 255 groups" + end + local name = msg(node.name) + if name == "" then + name = msg(scene.meshes[pl.mesh] and scene.meshes[pl.mesh].name) + end + local x = node.extras and node.extras.ms3d + local g: Group = { + name = if name ~= "" then name else "group" .. gi, tris = {}, flags = if x and type(x.flags) == "number" then x.flags else 0, + material = if type(prim.material) == "number" and prim.material <= 127 then prim.material - 1 else -1, + comment = x and x.comment, + } + local saved = prim.extras and prim.extras.ms3d and prim.extras.ms3d.smoothing + if type(saved) ~= "table" or #saved ~= #corners // 3 then + saved = nil + end + for f = 0, #corners // 3 - 1 do + local a, b, c = corners[f * 3 + 1], corners[f * 3 + 2], corners[f * 3 + 3] + if mirror then + b, c = c, b + end + local t: Tri = { v = { base + a, base + b, base + c }, n = {}, uv = {}, sg = if saved then saved[f + 1] else 1, group = gi } + local va, vb, vc = verts[base + a + 1], verts[base + b + 1], verts[base + c + 1] + local e1x, e1y, e1z = vb.x - va.x, vb.y - va.y, vb.z - va.z + local e2x, e2y, e2z = vc.x - va.x, vc.y - va.y, vc.z - va.z + local fx, fy, fz = e1y * e2z - e1z * e2y, e1z * e2x - e1x * e2z, e1x * e2y - e1y * e2x + for _, v in { a, b, c } do + local nx, ny, nz = fx, fy, fz + if hasN then + local ox, oy, oz = NOR(v, 0), NOR(v, 1), NOR(v, 2) + nx = NM[1] * ox + NM[5] * oy + NM[9] * oz + ny = NM[2] * ox + NM[6] * oy + NM[10] * oz + nz = NM[3] * ox + NM[7] * oy + NM[11] * oz + end + local l = sqrt(nx * nx + ny * ny + nz * nz) + if l > 0 then + nx, ny, nz = nx / l, ny / l, nz / l + end + table.move({ nx, ny, nz }, 1, 3, #t.n + 1, t.n) + table.insert(t.uv, UV(v, 0)) + table.insert(t.uv, UV(v, 1)) + end + table.insert(tris, t) + table.insert(g.tris, #tris - 1) + end + if #tris > 65535 then + return verts, tris, groups, "more than 65535 triangles" + end + table.insert(groups, g) + end + return verts, tris, groups, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?) + local o: Options = opts or {} + local tr = tree(scene) + local js, bySkin, byNode, B = joints(scene, tr) + local verts, tris, groups, gerr = geometry(scene, tr, bySkin, byNode, B) + if gerr then + return nil, gerr + end + if #scene.materials > 127 then + return nil, "more than 127 materials" + end + local src: any = scene.meta.source + local fromMs3d = src ~= nil and src.format == "ms3d" + local w = Bytes.writer(65536) + w:string("MS3D000000") + w:u32le(4) + w:u16le(#verts) + for _, v in verts do + w:u8(0) + w:f32le(v.x) + w:f32le(v.y) + w:f32le(v.z) + w:i8(v.bones[1] % 256) + w:u8(1) + end + w:u16le(#tris) + for _, t in tris do + w:u16le(0) + for k = 1, 3 do + w:u16le(t.v[k]) + end + for k = 1, 9 do + w:f32le(t.n[k]) + end + for k = 1, 3 do + w:f32le(t.uv[k * 2 - 1]) + end + for k = 1, 3 do + w:f32le(t.uv[k * 2]) + end + w:u8(math.clamp(t.sg, 0, 255)) + w:u8(t.group) + end + w:u16le(#groups) + for _, g in groups do + w:u8(g.flags % 256) + fixedString(w, g.name, 32) + w:u16le(#g.tris) + for _, ti in g.tris do + w:u16le(ti) + end + w:i8(g.material % 256) + end + w:u16le(#scene.materials) + local base = string.match(o.name or "", "([^/\\]-)%.[^.]*$") or "texture" + for i, m in scene.materials do + local x = (m.extras and m.extras.ms3d or {}) :: { [string]: any } + local bc = m.baseColor or { 1, 1, 1, 1 } + fixedString(w, msg(m.name) ~= "" and msg(m.name) or ("material" .. i), 32) + local e = m.emissive or { 0, 0, 0 } + for _, c in { x.ambient or { 0.2, 0.2, 0.2, 1 }, { bc[1], bc[2], bc[3], bc[4] or 1 }, x.specular or { 0, 0, 0, 1 }, { e[1], e[2], e[3], 1 } } do + for k = 1, 4 do + w:f32le(c[k] or 1) + end + end + local r = math.max(m.roughness or 1, 0.1) + w:f32le(x.shininess or math.clamp(2 / (r * r) - 2, 0, 128)) + w:f32le(bc[4] or 1) + w:i8((tonumber(x.mode) or 0) % 256) + local file = "" + local ref: any = m.baseColorTexture + local tex: any = ref and scene.textures[ref.texture] + if tex then + file = tex.uri or "" + if file == "" or string.sub(file, 1, 5) == "data:" then + file = base .. "_" .. ref.texture .. ".png" + if o.files and tex.data then + o.files[file] = tex.data + end + end + end + fixedString(w, file, 128) + fixedString(w, msg(x.alphamap), 128) + end + local fps = o.fps or (if fromMs3d and type(src.fps) == "number" and src.fps > 0 then src.fps else 24) + local last = 0 + for _, j in js do + for _, k in j.rotKeys do + last = math.max(last, k[1]) + end + for _, k in j.posKeys do + last = math.max(last, k[1]) + end + end + w:f32le(fps) + w:f32le(0) + w:u32le(math.max(1, math.ceil(last * fps))) + w:u16le(#js) + for _, j in js do + local x = scene.nodes[j.node].extras + local jx = x and x.ms3d + w:u8(if jx and type(jx.flags) == "number" then jx.flags % 256 else 0) + fixedString(w, j.name, 32) + fixedString(w, j.parent, 32) + for k = 1, 3 do + w:f32le(j.rot[k]) + end + for k = 1, 3 do + w:f32le(j.pos[k]) + end + w:u16le(#j.rotKeys) + w:u16le(#j.posKeys) + for _, list in { j.rotKeys, j.posKeys } do + for _, k in list do + for c = 1, 4 do + w:f32le(k[c]) + end + end + end + end + w:u32le(1) + local function comments(list: { any }, get: (any) -> string?) + local found = {} + for i, item in list do + local c = get(item) + if type(c) == "string" and c ~= "" then + table.insert(found, { i - 1, c }) + end + end + w:u32le(#found) + for _, f in found do + w:u32le(f[1]) + w:u32le(#f[2]) + w:string(f[2]) + end + end + comments(groups, function(g: any): string? + return g.comment + end) + comments(scene.materials, function(m: any): string? + return m.extras and m.extras.ms3d and m.extras.ms3d.comment + end) + comments(js, function(j: any): string? + local x: any = scene.nodes[j.node].extras + return x and x.ms3d and x.ms3d.comment + end) + local mc = if fromMs3d then msg(src.comment) else "" + w:u32le(if mc ~= "" then 1 else 0) + if mc ~= "" then + w:u32le(#mc) + w:string(mc) + end + -- vertex extras: three more bones, the weights in percent (the last one implied), an extra u32 + w:u32le(2) + for _, v in verts do + local p = table.create(3, 0) + local left = 100 + for c = 1, 3 do + p[c] = math.clamp(math.floor(v.weights[c] * 100 + 0.5), 0, left) + left -= p[c] + end + if v.bones[2] < 0 and v.bones[1] >= 0 then + p = { 100, 0, 0 } + end + for c = 2, 4 do + w:i8(v.bones[c] % 256) + end + for c = 1, 3 do + w:u8(p[c]) + end + w:u32le(0) + end + w:u32le(1) + for _, j in js do + local x: any = scene.nodes[j.node].extras + local c = x and x.ms3d and x.ms3d.color or { 1, 1, 1 } + for k = 1, 3 do + w:f32le(c[k] or 1) + end + end + w:u32le(1) + w:f32le(if fromMs3d and type(src.jointSize) == "number" then src.jointSize else 1) + w:u32le(if fromMs3d and type(src.transparencyMode) == "number" then src.transparencyMode else 0) + w:f32le(if fromMs3d and type(src.alphaRef) == "number" then src.alphaRef else 0.5) + local out = buffer.create(w.pos) + buffer.copy(out, 0, w.buf, 0, w.pos) + return out, nil +end + +return Write +end +__FILES["model/obj"] = function() + +-- model/obj: Wavefront OBJ + MTL (Paul Bourke's specs, as Blender / Maya / assimp write them). Supports: v (with +-- "v x y z r g b"), vt, vn, f in every index form, l, p, o / g, usemtl / mtllib, continuations; TEXCOORD_0 flipped to +-- top-left. Not supported: free-form geometry (curv, surf: skipped), smoothing groups (kept in extras.obj.smoothing). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Mtl = __include("model/obj/Mtl") + +-- ------------------------------------------------------------------------------------------------ contract +local Obj = { + name = "obj", + category = "model", + extensions = { "obj" }, + mime = { "model/obj" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, materials = true, polygons = true, vertexColors = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + triangulate: boolean?, -- default true + flipV: boolean?, -- default true + mtl: (string | buffer)?, + resolve: ((uri: string) -> any)?, + files: { [string]: any }?, + maxVertices: number?, -- refuse more v / vt / vn / corners (default 2^25) +} +type EncodeOptions = { + name: string?, -- default "model.mtl" + mtlName: string?, + files: { [string]: any }?, + flipV: boolean?, -- default true (the inverse of decode) + normals: boolean?, -- default true when the primitives have NORMAL + texcoords: boolean?, -- default true when the primitives have TEXCOORD_0 + colors: boolean?, -- default true when COLOR_0 exists +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Obj.sniff(r: Bytes.Reader): number + local head = r:peek(512) + if string.find(head, "\0", 1, true) then + return 0 + end + if string.find(head, "^%s*v%s+[%-%d%.]") or string.find(head, "\n%s*v%s+[%-%d%.]") then + return 0.6 + end + if string.find(head, "^#") and (string.find(head, "\nmtllib ") or string.find(head, "\no ") or string.find(head, "\ng ")) then + return 0.4 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function fetch(opts: DecodeOptions?, uri: string): string? + if not opts then + return nil + end + local v: any = nil + if type(opts.files) == "table" then + v = opts.files[uri] + if v == nil then + v = opts.files[string.match(uri, "([^/\\]+)$") or uri] + end + end + if v == nil and type(opts.resolve) == "function" then + local ok, res = pcall(opts.resolve, uri) + v = if ok then res else nil + end + if type(v) == "buffer" then + return buffer.tostring(v) + elseif type(v) == "string" then + return v + end + return nil +end + +type Prim = { + material: string?, + mode: string, + cv: { number }, -- per corner: position index (0-based), texcoord index (-1 none), normal index (-1 none) + ct: { number }, + cn: { number }, + faces: { number }, -- corners per face (polygons / lines) + hasT: boolean, + hasN: boolean, +} +type Section = { object: string?, group: string?, prims: { Prim }, byKey: { [string]: Prim }, smoothing: string? } + +function Obj.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local triangulate = not (opts and opts.triangulate == false) + local flipV = not (opts and opts.flipV == false) + local maxV = opts and opts.maxVertices or 2 ^ 25 + local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + local P, C, UV, N = {}, {}, {}, {} + local np, nt, nn = 0, 0, 0 + local hasColor = false + local sections: { Section } = {} + local byName: { [string]: Section } = {} + local cur: Section? = nil + local object: string? = nil + local group: string? = nil + local material: string? = nil + local smoothing: string? = nil + local mtllibs: { string } = {} + local skipped = 0 + local corners = 0 + local hasObjects = false + local lineNo = 0 + local pos = 1 + local len = #text + local function section(): Section + if cur then + return cur + end + local key = (object or "") .. "\0" .. (group or "") + local s = byName[key] + if not s then + s = { object = object, group = group, prims = {}, byKey = {}, smoothing = smoothing } + byName[key] = s + table.insert(sections, s) + end + cur = s + return s + end + local function prim(mode: string): Prim + local s = section() + local key = mode .. "\0" .. (material or "") + local p = s.byKey[key] + if not p then + p = { material = material, mode = mode, cv = {}, ct = {}, cn = {}, faces = {}, hasT = false, hasN = false } + s.byKey[key] = p + table.insert(s.prims, p) + end + return p + end + local function corner(tok: string): (number?, number, number) + local a, b, c = string.match(tok, "^([^/]*)/?([^/]*)/?([^/]*)$") + local vi = tonumber(a) + if not vi then + return nil, -1, -1 + end + vi = if vi < 0 then np + vi else vi - 1 + local ti, ni = -1, -1 + local t = tonumber(b) + if t then + ti = if t < 0 then nt + t else t - 1 + if ti < 0 or ti >= nt then + return nil, -1, -1 + end + end + local n = tonumber(c) + if n then + ni = if n < 0 then nn + n else n - 1 + if ni < 0 or ni >= nn then + return nil, -1, -1 + end + end + if vi < 0 or vi >= np then + return nil, -1, -1 + end + return vi, ti, ni + end + local fs: { string } = {} + while pos <= len do + local e = string.find(text, "\n", pos, true) or (len + 1) + local line = string.sub(text, pos, e - 1) + pos = e + 1 + lineNo += 1 + while string.sub(line, -1) == "\\" or string.sub(line, -2) == "\\\r" do + line = string.gsub(line, "\\\r?$", " ") + local e2 = string.find(text, "\n", pos, true) or (len + 1) + line ..= string.sub(text, pos, e2 - 1) + pos = e2 + 1 + lineNo += 1 + end + local key, rest = string.match(line, "^%s*(%S+)%s*(.-)%s*$") + if key == nil or string.sub(key, 1, 1) == "#" then + continue + end + local rest: string = rest :: string + local hash = string.find(rest, "#", 1, true) + if hash then + rest = string.gsub(string.sub(rest, 1, hash - 1), "%s+$", "") + end + if key == "v" then + local x, y, z, a, b, c = string.match(rest, "^(%S+)%s+(%S+)%s+(%S+)%s*(%S*)%s*(%S*)%s*(%S*)") + local fx, fy, fz = tonumber(x), tonumber(y), tonumber(z) + if not fx or not fy or not fz then + return nil, Err.new(Err.CORRUPT, "bad vertex on line " .. lineNo) + end + if np >= maxV then + return nil, Err.new(Err.LIMIT, "over " .. maxV .. " vertices") + end + P[np * 3 + 1], P[np * 3 + 2], P[np * 3 + 3] = fx, fy, fz + local cr, cg, cb = tonumber(a), tonumber(b), tonumber(c) + if cr and cg and cb then + hasColor = true + C[np * 3 + 1], C[np * 3 + 2], C[np * 3 + 3] = cr, cg, cb + end + np += 1 + elseif key == "vt" then + local u, v = string.match(rest, "^(%S+)%s*(%S*)") + local fu = tonumber(u) + if not fu then + return nil, Err.new(Err.CORRUPT, "bad texture coordinate on line " .. lineNo) + end + if nt >= maxV then + return nil, Err.new(Err.LIMIT, "over " .. maxV .. " texture coordinates") + end + local fv = tonumber(v) or 0 + UV[nt * 2 + 1], UV[nt * 2 + 2] = fu, if flipV then 1 - fv else fv + nt += 1 + elseif key == "vn" then + local x, y, z = string.match(rest, "^(%S+)%s+(%S+)%s+(%S+)") + local fx, fy, fz = tonumber(x), tonumber(y), tonumber(z) + if not fx or not fy or not fz then + return nil, Err.new(Err.CORRUPT, "bad normal on line " .. lineNo) + end + if nn >= maxV then + return nil, Err.new(Err.LIMIT, "over " .. maxV .. " normals") + end + N[nn * 3 + 1], N[nn * 3 + 2], N[nn * 3 + 3] = fx, fy, fz + nn += 1 + elseif key == "f" or key == "l" or key == "p" then + table.clear(fs) + for tok in string.gmatch(rest, "%S+") do + table.insert(fs, tok) + end + local k = #fs + local mode = if key == "f" then (if triangulate then "triangles" else "polygons") elseif key == "l" then "lines" else "points" + if (key == "f" and k < 3) or (key == "l" and k < 2) or k < 1 then + return nil, Err.new(Err.CORRUPT, "an element with too few corners on line " .. lineNo) + end + corners += k + if corners > maxV * 4 then + return nil, Err.new(Err.LIMIT, "too many face corners") + end + local p = prim(mode) + local base = #p.cv + for i, tok in fs do + local vi, ti, ni = corner(tok) + if not vi then + return nil, Err.new(Err.CORRUPT, "bad index '" .. tok .. "' on line " .. lineNo) + end + p.cv[base + i], p.ct[base + i], p.cn[base + i] = vi, ti, ni + if ti >= 0 then + p.hasT = true + end + if ni >= 0 then + p.hasN = true + end + end + if mode == "triangles" and k > 3 then + local cv, ct, cn = table.move(p.cv, base + 1, base + k, 1, {}), table.move(p.ct, base + 1, base + k, 1, {}), table.move(p.cn, base + 1, base + k, 1, {}) + local o = base + for a = 2, k - 1 do + for _, j in { 1, a, a + 1 } do + o += 1 + p.cv[o], p.ct[o], p.cn[o] = cv[j], ct[j], cn[j] + end + end + elseif mode == "lines" then + local cv, ct, cn = table.move(p.cv, base + 1, base + k, 1, {}), table.move(p.ct, base + 1, base + k, 1, {}), table.move(p.cn, base + 1, base + k, 1, {}) + local o = base + for a = 1, k - 1 do + for _, j in { a, a + 1 } do + o += 1 + p.cv[o], p.ct[o], p.cn[o] = cv[j], ct[j], cn[j] + end + end + elseif mode == "polygons" then + table.insert(p.faces, k) + end + elseif key == "o" then + object = rest + group = nil + hasObjects = true + cur = nil + elseif key == "g" then + group = if rest == "" then nil else rest + cur = nil + elseif key == "usemtl" then + material = rest + elseif key == "mtllib" then + table.insert(mtllibs, rest) + elseif key == "s" then + smoothing = rest + if cur then + cur.smoothing = cur.smoothing or rest + end + else + skipped += 1 + end + end + local scene = Types.Scene.new() + local matIndex: { [string]: number } = {} + local texIndex: { [string]: number } = {} + local function texture(map: Mtl.Map): number + local file = string.gsub(map.file, "\\", "/") + local i = texIndex[file] + if i then + return i + end + local tex: Types.Texture = { uri = file, mime = Mtl.mime(file) } + local data = fetch(opts, file) + if data then + tex.data = buffer.fromstring(data) + end + if map.options.clamp and map.options.clamp[1] == "on" then + tex.sampler = { wrapS = "clamp", wrapT = "clamp" } + end + table.insert(scene.textures, tex) + i = #scene.textures + texIndex[file] = i + return i + end + local mtlText = if opts and opts.mtl then (if type(opts.mtl) == "buffer" then buffer.tostring(opts.mtl) else opts.mtl) else nil + local missing: { string } = {} + local libs: { string } = {} + if mtlText then + table.insert(libs, mtlText :: string) + end + for _, lib in mtllibs do + local t = fetch(opts, lib) + if t then + table.insert(libs, t) + elseif not mtlText then + table.insert(missing, lib) + end + end + for _, lt in libs do + for _, e in Mtl.parse(lt) do + if not matIndex[e.name] then + table.insert(scene.materials, Mtl.toMaterial(e, texture)) + matIndex[e.name] = #scene.materials + end + end + end + -- usemtl of an undefined material: a default one with that name + for _, s in sections do + for _, p in s.prims do + if p.material and not matIndex[p.material] then + table.insert(scene.materials, Types.Scene.material(p.material)) + scene.materials[#scene.materials].metallic = 0 + matIndex[p.material] = #scene.materials + end + end + end + local f32 = buffer.writef32 + local KT, KN = nt + 1, nn + 1 + local numericKeys = np * KT * KN < 2 ^ 52 + local function build(p: Prim): Types.Primitive + local n = #p.cv + local map: { [any]: number } = {} + local verts: { number } = {} + local idx = buffer.create(n * 4) + local count = 0 + for i = 1, n do + local v, t, nr = p.cv[i], p.ct[i], p.cn[i] + local key: any = if numericKeys then (v * KT + (t + 1)) * KN + (nr + 1) else string.format("%d/%d/%d", v, t, nr) + local k = map[key] + if k == nil then + k = count + map[key] = k + count += 1 + verts[count * 3 - 2], verts[count * 3 - 1], verts[count * 3] = v, t, nr + end + buffer.writeu32(idx, (i - 1) * 4, k) + end + local pb = buffer.create(count * 12) + local tb = if p.hasT then buffer.create(count * 8) else nil + local nb = if p.hasN then buffer.create(count * 12) else nil + local cb = if hasColor then buffer.create(count * 12) else nil + for k = 0, count - 1 do + local v, t, nr = verts[k * 3 + 1], verts[k * 3 + 2], verts[k * 3 + 3] + f32(pb, k * 12, P[v * 3 + 1]) + f32(pb, k * 12 + 4, P[v * 3 + 2]) + f32(pb, k * 12 + 8, P[v * 3 + 3]) + if tb and t >= 0 then + f32(tb, k * 8, UV[t * 2 + 1]) + f32(tb, k * 8 + 4, UV[t * 2 + 2]) + end + if nb and nr >= 0 then + f32(nb, k * 12, N[nr * 3 + 1]) + f32(nb, k * 12 + 4, N[nr * 3 + 2]) + f32(nb, k * 12 + 8, N[nr * 3 + 3]) + end + if cb then + f32(cb, k * 12, C[v * 3 + 1] or 1) + f32(cb, k * 12 + 4, C[v * 3 + 2] or 1) + f32(cb, k * 12 + 8, C[v * 3 + 3] or 1) + end + end + local A = Types.Scene.accessor + local attrs: { [string]: Types.Accessor } = { POSITION = A(pb, "f32", 3, count) } + if tb then + attrs.TEXCOORD_0 = A(tb, "f32", 2, count) + end + if nb then + attrs.NORMAL = A(nb, "f32", 3, count) + end + if cb then + attrs.COLOR_0 = A(cb, "f32", 3, count) + end + local out: Types.Primitive = { attributes = attrs, indices = A(idx, "u32", 1, n), mode = p.mode :: any, material = if p.material then matIndex[p.material] else nil } + if p.mode == "points" then + out.indices = if count == n then nil else out.indices + end + if p.mode == "polygons" then + local fb = buffer.create(#p.faces * 4) + for i, k in p.faces do + buffer.writeu32(fb, (i - 1) * 4, k) + end + out.faces = A(fb, "u32", 1, #p.faces) + end + return out + end + local objectNode: { [string]: number } = {} + for _, s in sections do + if #s.prims > 0 then + local mesh: Types.Mesh = { name = s.group or s.object, primitives = {} } + for _, p in s.prims do + table.insert(mesh.primitives, build(p)) + end + table.insert(scene.meshes, mesh) + local node: Types.Node = { name = s.group or s.object, children = {}, mesh = #scene.meshes } + if s.smoothing then + node.extras = { obj = { smoothing = s.smoothing } } + end + if hasObjects and s.object and s.group then + local oi = objectNode[s.object] + if not oi then + table.insert(scene.nodes, { name = s.object, children = {} }) + oi = #scene.nodes + objectNode[s.object] = oi + table.insert(scene.roots, oi) + end + table.insert(scene.nodes, node) + table.insert(scene.nodes[oi].children, #scene.nodes) + else + if hasObjects and s.object and not s.group and objectNode[s.object] == nil then + table.insert(scene.nodes, node) + objectNode[s.object] = #scene.nodes + table.insert(scene.roots, #scene.nodes) + elseif hasObjects and s.object and objectNode[s.object] then + table.insert(scene.nodes, node) + table.insert(scene.nodes[objectNode[s.object]].children, #scene.nodes) + else + table.insert(scene.nodes, node) + table.insert(scene.roots, #scene.nodes) + end + end + end + end + scene.meta.up = "y" + scene.meta.source = { + format = "obj", + positions = np, + texcoords = nt, + normals = nn, + vertexColors = hasColor, + mtllib = if #mtllibs > 0 then mtllibs else nil, + missingMtl = if #missing > 0 then missing else nil, + skipped = skipped, + } + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local probe = buffer.create(4) +local function f32str(v: number): string + if v ~= v or v == math.huge or v == -math.huge then + return "0" + end + if v == math.floor(v) and math.abs(v) < 1e7 then + return string.format("%d", v) + end + buffer.writef32(probe, 0, v) + local want = buffer.readf32(probe, 0) + for _, f in { "%.6g", "%.7g", "%.8g" } do + local s = string.format(f, v) + buffer.writef32(probe, 0, tonumber(s) :: number) + if buffer.readf32(probe, 0) == want then + return s + end + end + return string.format("%.9g", v) +end + +local function nameOk(s: string): string + local t = string.gsub(s, "[\r\n]", " ") + return t +end + +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: 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) + local out = { "# written by rosetta" } + local mats = scene.materials or {} + local names: { string } = {} + local used: { [string]: boolean } = {} + for i, m in mats do + local n = string.gsub(m.name or ("material_" .. i), "%s", "_") + while used[n] do + n ..= "_" .. i + end + used[n] = true + names[i] = n + end + local texFiles: { [number]: string } = {} + local function textureFile(i: number): string? + if texFiles[i] then + return texFiles[i] + end + local tex = scene.textures and scene.textures[i] + if not tex then + return nil + end + local file = tex.uri + if (file == nil or string.find(file, "^data:")) and tex.data then + file = base .. "_" .. i .. "." .. (EXT[tex.mime or ""] or "png") + end + if file and tex.data and type(files) == "table" then + files[file] = tex.data + end + texFiles[i] = file + return file + end + if #mats > 0 then + table.insert(out, "mtllib " .. mtlName) + if type(files) == "table" then + files[mtlName] = Mtl.write(mats, names, textureFile) + end + end + local nv, nt, nn = 0, 0, 0 + local lastNode = -1 + for _, pl in placed do + local prim = pl.primitive + local attrs = prim.attributes + local pos = attrs and attrs.POSITION + if not pos then + continue + end + local P = Types.Scene.reader(pos) + if not P then + return nil, Err.new(Err.ARG, "bad POSITION accessor") + end + if buffer.len(pos.data) < pos.count * pos.components * (Types.COMPONENT_SIZE[pos.type] or 4) then + return nil, Err.new(Err.ARG, "POSITION data is smaller than its count") + end + local m = pl.matrix + local ident = m == Types.Scene.IDENTITY + local node = scene.nodes[pl.node] + if pl.node ~= lastNode then + lastNode = pl.node + 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 :: 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") + end + end + local nm: { number }? = nil + if Nr and not ident then + local a, b, c, d, e, f, g, h, i = m[1], m[5], m[9], m[2], m[6], m[10], m[3], m[7], m[11] + local det = a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g) + local k = if det ~= 0 then 1 / det else 1 + nm = { (e * i - f * h) * k, -(d * i - f * g) * k, (d * h - e * g) * k, -(b * i - c * h) * k, (a * i - c * g) * k, -(a * h - b * g) * k, (b * f - c * e) * k, -(a * f - c * d) * k, (a * e - b * d) * k } + end + for v = 0, n - 1 do + local x, y, z = P(v, 0), P(v, 1), P(v, 2) + if not ident then + x, y, z = 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 + if Cc then + table.insert(out, string.format("v %s %s %s %s %s %s", f32str(x), f32str(y), f32str(z), f32str(Cc(v, 0)), f32str(Cc(v, 1)), f32str(Cc(v, 2)))) + else + table.insert(out, string.format("v %s %s %s", f32str(x), f32str(y), f32str(z))) + end + end + if T then + for v = 0, n - 1 do + local tv = T(v, 1) + table.insert(out, string.format("vt %s %s", Mtl.num(T(v, 0)), Mtl.num(if flipV then 1 - tv else tv))) + end + end + if Nr then + for v = 0, n - 1 do + local x, y, z = Nr(v, 0), Nr(v, 1), Nr(v, 2) + if nm then + x, y, z = nm[1] * x + nm[4] * y + nm[7] * z, nm[2] * x + nm[5] * y + nm[8] * z, nm[3] * x + nm[6] * y + nm[9] * z + local l = math.sqrt(x * x + y * y + z * z) + if l > 0 then + x, y, z = x / l, y / l, z / l + end + end + table.insert(out, string.format("vn %s %s %s", f32str(x), f32str(y), f32str(z))) + end + end + if prim.material and names[prim.material] then + table.insert(out, "usemtl " .. names[prim.material]) + end + local function ref(i: number): string + local s = tostring(nv + i + 1) + if T and Nr then + return string.format("%s/%d/%d", s, nt + i + 1, nn + i + 1) + elseif T then + return string.format("%s/%d", s, nt + i + 1) + elseif Nr then + return string.format("%s//%d", s, nn + i + 1) + end + return s + end + local ind = prim.indices + local I: ((number, number) -> number)? = if ind then Types.Scene.reader(ind) else nil + local count = if ind then ind.count else n + if ind and buffer.len(ind.data) < ind.count * (Types.COMPONENT_SIZE[ind.type] or 4) then + return nil, Err.new(Err.ARG, "indices data is smaller than its count") + end + local function at(i: number): number + return if I then I(i, 0) else i + end + for i = 0, count - 1 do + if at(i) >= n then + return nil, Err.new(Err.ARG, "index out of range") + end + end + local mirror = not ident and (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])) < 0 + local function face(list: { number }) + local parts = table.create(#list + 1) + parts[1] = "f" + if mirror then + for k = #list, 1, -1 do + table.insert(parts, ref(list[k])) + end + else + for k = 1, #list do + table.insert(parts, ref(list[k])) + end + end + table.insert(out, table.concat(parts, " ")) + end + local mode = prim.mode or "triangles" + if mode == "triangles" then + for t = 0, count // 3 - 1 do + face({ at(t * 3), at(t * 3 + 1), at(t * 3 + 2) }) + end + elseif mode == "polygons" then + local F = if prim.faces then Types.Scene.reader(prim.faces) else nil + if not F or not prim.faces then + return nil, Err.new(Err.ARG, "polygons without faces") + end + local o = 0 + for f = 0, prim.faces.count - 1 do + local k = F(f, 0) + if o + k > count then + return nil, Err.new(Err.ARG, "faces run past the indices") + end + local list = table.create(k) :: { number } + for j = 0, k - 1 do + list[j + 1] = at(o + j) + end + if k >= 3 then + face(list) + end + o += k + end + elseif mode == "triangle_strip" or mode == "triangle_fan" then + for t = 0, count - 3 do + local a, b, c = at(t), at(t + 1), at(t + 2) + if mode == "triangle_fan" then + a = at(0) + elseif t % 2 == 1 then + a, b = b, a + end + face({ a, b, c }) + end + elseif mode == "lines" then + for s = 0, count // 2 - 1 do + table.insert(out, "l " .. ref(at(s * 2)) .. " " .. ref(at(s * 2 + 1))) + end + elseif mode == "line_strip" or mode == "line_loop" then + local parts = { "l" } + for i = 0, count - 1 do + table.insert(parts, ref(at(i))) + end + if mode == "line_loop" and count > 0 then + table.insert(parts, ref(at(0))) + end + table.insert(out, table.concat(parts, " ")) + elseif mode == "points" then + for i = 0, count - 1 do + table.insert(out, "p " .. ref(at(i))) + end + end + nv += n + if T then + nt += n + end + if Nr then + nn += n + end + end + table.insert(out, "") + return buffer.fromstring(table.concat(out, "\n")), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +function Obj.encodeMtl(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(scene) ~= "table" or type(scene.materials) ~= "table" then + return nil, Err.new(Err.ARG, "needs a Scene") + end + local files: { [string]: string } = {} + local o: any = table.clone(opts or {}) + o.files = files + o.mtlName = "x.mtl" + local _, err = Obj.encode(scene, o) + if err then + return nil, err + end + local text = files["x.mtl"] + return buffer.fromstring(text or ""), nil +end + +return Obj +end +__FILES["model/obj/Mtl"] = function() + +-- model/obj/Mtl: Wavefront .mtl (Paul Bourke's MTL spec + the PBR extension: Pr, Pm, Ps, Pc, Pcr, aniso, anisor, Ke, +-- map_Pr, map_Pm, map_Ke, norm); Phong values are kept in extras.obj. +local Types = __include("Types") + +local Mtl = {} + +type Map = { file: string, options: { [string]: { string } } } -- -o / -s / -bm / -clamp / ... with their values +type Entry = { name: string, values: { [string]: { number } }, maps: { [string]: Map }, order: { string } } + +-- the number of arguments of each texture map option (Bourke): -o / -s / -t take 1..3 numbers +local OPT_ARGS = { blendu = 1, blendv = 1, cc = 1, clamp = 1, mm = 2, bm = 1, boost = 1, texres = 1, imfchan = 1, type = 1 } +local MAPS = { + map_Ka = true, map_Kd = true, map_Ks = true, map_Ke = true, map_Ns = true, map_d = true, map_Tr = true, + map_bump = true, bump = true, map_Bump = true, disp = true, decal = true, refl = true, norm = true, map_Pr = true, + map_Pm = true, map_Ps = true, map_Pc = true, map_Pcr = true, map_RMA = true, map_ORM = true, map_aniso = true, +} +Mtl.MAPS = MAPS + +local function parseMap(args: { string }): Map + local opts: { [string]: { string } } = {} + local i = 1 + while i <= #args and string.sub(args[i], 1, 1) == "-" and tonumber(args[i]) == nil do + local key = string.sub(args[i], 2) + local vals = {} + i += 1 + local n = OPT_ARGS[key] + if n then + for _ = 1, n do + if i <= #args then + table.insert(vals, args[i]) + i += 1 + end + end + else + while i <= #args and #vals < 3 and tonumber(args[i]) ~= nil and i < #args do + table.insert(vals, args[i]) + i += 1 + end + end + opts[key] = vals + end + -- the file name is the rest (it may contain spaces) + local file = table.concat(args, " ", i) + return { file = file, options = opts } +end + +function Mtl.parse(text: string): { Entry } + local out: { Entry } = {} + local cur: Entry? = nil + for line in string.gmatch(text, "[^\r\n]+") do + local l = string.gsub(line, "#.*$", "") + local words = {} + for w in string.gmatch(l, "%S+") do + table.insert(words, w) + end + local key = words[1] + if key == "newmtl" then + cur = { name = table.concat(words, " ", 2), values = {}, maps = {}, order = {} } + table.insert(out, cur :: Entry) + elseif key and cur then + local e = cur :: Entry + local args = table.move(words, 2, #words, 1, {}) + if MAPS[key] then + e.maps[key] = parseMap(args) + table.insert(e.order, key) + else + local nums = {} + for _, a in args do + local v = tonumber(a) + if v == nil then + nums = nil :: any + break + end + table.insert(nums, v) + end + if nums then + if e.values[key] == nil then + table.insert(e.order, key) + end + e.values[key] = nums + end + end + end + end + return out +end + +local MIME = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", webp = "image/webp", gif = "image/gif", bmp = "image/bmp", tga = "image/x-tga", tif = "image/tiff", tiff = "image/tiff", dds = "image/vnd-ms.dds", ktx2 = "image/ktx2", exr = "image/x-exr", hdr = "image/vnd.radiance" } +function Mtl.mime(file: string): string? + local ext = string.match(file, "%.([%w]+)$") + return if ext then MIME[string.lower(ext)] else nil +end + +function Mtl.toMaterial(e: Entry, texture: (Map) -> number): Types.Material + local m = Types.Scene.material(e.name) + local v = e.values + local kd = v.Kd + if kd and #kd >= 3 then + m.baseColor = { kd[1], kd[2], kd[3], 1 } + end + 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" + end + local ke = v.Ke + if ke and #ke >= 3 then + m.emissive = { ke[1], ke[2], ke[3] } + end + 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 + m.roughness = math.clamp(math.sqrt(2 / (math.max(v.Ns[1], 0) + 2)), 0, 1) + end + local function ref(key: string): Types.TextureRef? + local map = e.maps[key] + if not map or map.file == "" then + return nil + end + local r: Types.TextureRef = { texture = texture(map) } + local o, s = map.options.o, map.options.s + if o or s then + r.transform = { + offset = if o then { tonumber(o[1]) or 0, tonumber(o[2]) or 0 } else nil, + scale = if s then { tonumber(s[1]) or 1, tonumber(s[2]) or 1 } else nil, + } + end + if map.options.bm then + r.scale = tonumber(map.options.bm[1]) + end + return r + end + m.baseColorTexture = ref("map_Kd") + m.emissiveTexture = ref("map_Ke") + m.normalTexture = ref("norm") or ref("map_bump") or ref("bump") or ref("map_Bump") + m.metallicRoughnessTexture = ref("map_ORM") or ref("map_RMA") + if m.emissiveTexture and not ke then + m.emissive = { 1, 1, 1 } + end + local extra: { [string]: any } = {} + for k, vals in v do + extra[k] = vals + end + local maps: { [string]: any } = {} + for k, map in e.maps do + maps[k] = { file = map.file, options = map.options, texture = texture(map) } + end + m.extras = { obj = { values = extra, maps = maps, order = e.order } } + return m +end + +local function num(v: number): string + if v == math.floor(v) and math.abs(v) < 1e15 then + return string.format("%d", v) + end + for _, f in { "%.6g", "%.9g", "%.17g" } do + local s = string.format(f, v) + if tonumber(s) == v then + return s + end + end + return string.format("%.17g", v) +end +Mtl.num = num + +function Mtl.write(materials: { Types.Material }, names: { string }, textureFile: (number) -> string?): string + local out = { "# written by rosetta" } + for i, m in materials do + table.insert(out, "") + table.insert(out, "newmtl " .. names[i]) + local saved = m.extras and m.extras.obj + local values: { [string]: { number } } = {} + local maps: { [string]: any } = {} + local order: { string } = {} + if type(saved) == "table" and type(saved.values) == "table" then + for k, vals in saved.values do + values[k] = vals + end + for k, mp in saved.maps or {} do + maps[k] = mp + end + order = table.clone(saved.order or {}) + end + local bc = m.baseColor or { 1, 1, 1, 1 } + values.Kd = { bc[1], bc[2], bc[3] } + if (bc[4] or 1) < 1 or values.d then + values.d = { bc[4] or 1 } + values.Tr = nil + end + local em = m.emissive or { 0, 0, 0 } + if em[1] ~= 0 or em[2] ~= 0 or em[3] ~= 0 or values.Ke then + values.Ke = { em[1], em[2], em[3] } + end + if not (saved and saved.values and saved.values.Ns and not saved.values.Pr) then + values.Pr = { m.roughness } + end + if m.metallic ~= 0 or values.Pm then + values.Pm = { m.metallic } + end + local function setMap(key: string, ref: Types.TextureRef?) + if ref then + local file = textureFile(ref.texture) + if file then + local prev = maps[key] + local options = if prev and prev.texture == ref.texture then prev.options else {} + options = table.clone(options or {}) + if ref.transform then + if ref.transform.offset then + options.o = { num(ref.transform.offset[1]), num(ref.transform.offset[2]) } + end + if ref.transform.scale then + options.s = { num(ref.transform.scale[1]), num(ref.transform.scale[2]) } + end + end + if ref.scale and key ~= "map_Kd" then + options.bm = { num(ref.scale) } + end + maps[key] = { file = file, options = options, texture = ref.texture } + end + end + end + setMap("map_Kd", m.baseColorTexture) + setMap("map_Ke", m.emissiveTexture) + if m.normalTexture and not maps.map_bump and not maps.bump and not maps.map_Bump then + setMap("norm", m.normalTexture) + end + setMap("map_ORM", m.metallicRoughnessTexture) + local keys = {} + local seen = {} + for _, k in order do + if (values[k] or maps[k]) and not seen[k] then + table.insert(keys, k) + seen[k] = true + end + end + local rest = {} + for k in values do + if not seen[k] then + table.insert(rest, k) + end + end + for k in maps do + if not seen[k] and not values[k] then + table.insert(rest, k) + end + end + table.sort(rest) + for _, k in rest do + seen[k] = true + table.insert(keys, k) + end + for _, k in keys do + local mp = maps[k] + if mp and type(mp.file) == "string" then + local file = if type(mp.texture) == "number" then (textureFile(mp.texture) or mp.file) else mp.file + local parts = { k } + local okeys = {} + for ok in mp.options or {} do + table.insert(okeys, ok) + end + table.sort(okeys) + for _, ok in okeys do + table.insert(parts, "-" .. ok) + for _, ov in mp.options[ok] do + table.insert(parts, tostring(ov)) + end + end + table.insert(parts, file) + table.insert(out, table.concat(parts, " ")) + elseif values[k] then + local parts = { k } + for _, x in values[k] do + table.insert(parts, num(x)) + end + table.insert(out, table.concat(parts, " ")) + end + end + end + table.insert(out, "") + return table.concat(out, "\n") +end + +return Mtl +end +__FILES["model/off"] = function() + +-- model/off: Geomview OFF text (geomview.org/docs/html/OFF.html), read + write. Supports: [ST][C][N]OFF, face colours +-- (prim.extras.faceColors), n-gons (fan-triangulated or "polygons"), point clouds; floats as %.9g (f32-exact). +-- Not supported: 4OFF / nOFF, binary OFF; colormap-index face colours are ignored. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Flatten = __include("codecs/model/MeshFlatten") + +-- ------------------------------------------------------------------------------------------------ contract +local Off = { + name = "off", + category = "model", + extensions = { "off" }, + mime = { "model/off", "text/plain" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/MeshFlatten" }, + caps = { decode = true, encode = true, polygons = true, points = true, colors = true, binary = false }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + triangulate: boolean?, -- default true + maxVertices: number?, -- default 2^24 + maxFaces: number?, -- default 2^25 +} +type EncodeOptions = { + colors: boolean?, -- default true + normals: boolean?, -- default true + texcoords: boolean?, -- default true + comment: string?, +} + +-- ------------------------------------------------------------------------------------------------ constants +local writef32, writeu8, writeu32 = buffer.writef32, buffer.writeu8, buffer.writeu32 + +-- ------------------------------------------------------------------------------------------------ sniff +function Off.sniff(r: Bytes.Reader): number + local head = r:peek(512) + for _ = 1, 16 do + local rest = string.match(head, "^%s*#[^\n]*\n(.*)$") + if not rest then + break + end + head = rest + end + local kw = string.match(head, "^%s*(%w+)") + if kw and string.match(kw, "^S?T?C?N?4?n?OFF$") then + return 0.9 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- unorm8 when every value is an integer and some value is above 1, else f32 +type ColorSet = { values: { number }, float: boolean, max: number } + +local function colorType(c: ColorSet): string + return if not c.float and c.max > 1 then "unorm8" else "f32" +end + +local function colorAccessor(c: ColorSet, count: number): (Types.Accessor?, string?) + local t = colorType(c) + local buf = buffer.create(count * (if t == "unorm8" then 4 else 16)) + local vals = c.values + for i = 0, count * 4 - 1 do + local v = vals[i + 1] + if t == "unorm8" then + if v ~= v then + v = 255 + elseif v < 0 or v > 255 or v % 1 ~= 0 then + return nil, "colour value out of range" + end + writeu8(buf, i, v) + else + writef32(buf, i * 4, if v ~= v then 1 else v) + end + end + return Types.Scene.accessor(buf, t, 4, count), nil +end + +local function addColor(c: ColorSet, toks: { string }, from: number, n: number) + local vals = c.values + for k = 0, 3 do + if k < n then + local s = toks[from + k] + local v = tonumber(s) :: number + table.insert(vals, v) + if not c.float and string.find(s, "[%.eEnN]") then + c.float = true + end + if v > c.max then + c.max = v + end + else + table.insert(vals, 0 / 0) + end + end +end + +function Off.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local triangulate = true + if opts and opts.triangulate == false then + triangulate = false + end + local maxVertices = opts and opts.maxVertices or 2 ^ 24 + local maxFaces = opts and opts.maxFaces or 2 ^ 25 + local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + local at = 1 + local lineNo = 0 + local function line(): { string }? + while at <= #text do + local e = string.find(text, "\n", at, true) or (#text + 1) + local s = string.sub(text, at, e - 1) + at = e + 1 + lineNo += 1 + local hash = string.find(s, "#", 1, true) + if hash then + s = string.sub(s, 1, hash - 1) + end + local toks = {} + for w in string.gmatch(s, "%S+") do + table.insert(toks, w) + end + if #toks > 0 then + return toks + end + end + return nil + end + local head = line() + if not head then + return nil, Err.new(Err.TRUNCATED, "empty file") + end + local kw = head[1] + 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)) + end + if string.sub(rest, 1, 1) == "C" then + hasC, rest = true, (string.sub(rest, 2)) + end + if string.sub(rest, 1, 1) == "N" then + 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)") + elseif rest ~= "OFF" then + return nil, Err.new(Err.CORRUPT, "bad header keyword " .. string.sub(kw, 1, 20)) + end + local counts: { string } + if head[2] == "BINARY" then + return nil, Err.new(Err.UNSUPPORTED, "binary OFF") + elseif #head >= 3 then + counts = { head[2], head[3], head[4] } + else + local c = line() + if not c then + return nil, Err.new(Err.TRUNCATED, "no counts line") + end + counts = c + end + local nv, nf, ne = tonumber(counts[1]), tonumber(counts[2]), tonumber(counts[3] or "0") + if not nv or not nf or nv < 0 or nf < 0 or nv % 1 ~= 0 or nf % 1 ~= 0 then + return nil, Err.new(Err.CORRUPT, "bad counts line") + end + if nv > maxVertices then + return nil, Err.new(Err.LIMIT, string.format("%d vertices is over the %d vertex limit", nv, maxVertices)) + end + if nf > maxFaces then + return nil, Err.new(Err.LIMIT, string.format("%d faces is over the %d face limit", nf, maxFaces)) + end + if nv * 6 + nf * 2 > #text - at + 2 then + return nil, Err.new(Err.TRUNCATED, "fewer lines than the counts need") + end + local fixed = 3 + (if hasN then 3 else 0) + (if st then 2 else 0) + local pos = buffer.create(nv * 12) + local nrm = if hasN then buffer.create(nv * 12) else nil + local tex = if st then buffer.create(nv * 8) else nil + local vcol: ColorSet = { values = {}, float = false, max = 0 } + for i = 0, nv - 1 do + local t = line() + if not t then + return nil, Err.new(Err.TRUNCATED, string.format("vertex %d missing", i)) + end + local n = #t + local nc = 0 + if hasC then + nc = n - fixed + if nc ~= 3 and nc ~= 4 then + return nil, Err.new(Err.CORRUPT, string.format("vertex %d: expected %d values and an RGB / RGBA colour", i, fixed)) + end + elseif n < fixed then + return nil, Err.new(Err.CORRUPT, string.format("vertex %d: expected %d values", i, fixed)) + end + for k = 1, fixed + nc do + if tonumber(t[k]) == nil then + return nil, Err.new(Err.CORRUPT, string.format("vertex %d: bad number", i)) + end + end + writef32(pos, i * 12, tonumber(t[1]) :: number) + writef32(pos, i * 12 + 4, tonumber(t[2]) :: number) + writef32(pos, i * 12 + 8, tonumber(t[3]) :: number) + local k = 4 + if nrm then + writef32(nrm, i * 12, tonumber(t[4]) :: number) + writef32(nrm, i * 12 + 4, tonumber(t[5]) :: number) + writef32(nrm, i * 12 + 8, tonumber(t[6]) :: number) + k = 7 + end + if hasC then + addColor(vcol, t, k, nc) + k += nc + end + if tex then + writef32(tex, i * 8, tonumber(t[k]) :: number) + writef32(tex, i * 8 + 4, tonumber(t[k + 1]) :: number) + end + end + local sizes = buffer.create(nf * 4) + local corners: { number } = {} + local fcol: ColorSet = { values = {}, float = false, max = 0 } + local anyFaceColor, colormap = false, false + for f = 0, nf - 1 do + local t = line() + if not t then + return nil, Err.new(Err.TRUNCATED, string.format("face %d missing", f)) + end + local n = tonumber(t[1]) + if n == nil or n < 0 or n % 1 ~= 0 or #t < n + 1 then + return nil, Err.new(Err.CORRUPT, string.format("face %d: bad vertex count", f)) + end + writeu32(sizes, f * 4, n) + for k = 2, n + 1 do + local v = tonumber(t[k]) + if v == nil or v < 0 or v >= nv or v % 1 ~= 0 then + return nil, Err.new(Err.CORRUPT, string.format("face %d: vertex index out of range", f)) + end + table.insert(corners, v) + end + local nc = #t - n - 1 + if nc == 3 or nc == 4 then + for k = n + 2, #t do + if tonumber(t[k]) == nil then + return nil, Err.new(Err.CORRUPT, string.format("face %d: bad colour", f)) + end + end + addColor(fcol, t, n + 2, nc) + anyFaceColor = true + else + if nc == 1 then + colormap = true + end + addColor(fcol, t, 1, 0) + end + end + local attrs: { [string]: Types.Accessor } = { POSITION = Types.Scene.accessor(pos, "f32", 3, nv) } + if nrm then + attrs.NORMAL = Types.Scene.accessor(nrm, "f32", 3, nv) + end + if hasC then + local acc, cerr = colorAccessor(vcol, nv) + if not acc then + return nil, Err.new(Err.CORRUPT, "vertex " .. tostring(cerr)) + end + attrs.COLOR_0 = acc + end + if tex then + attrs.TEXCOORD_0 = Types.Scene.accessor(tex, "f32", 2, nv) + end + local prim: Types.Primitive = { attributes = attrs, mode = "points" } + local extras: { [string]: any } = {} + if anyFaceColor then + local acc, cerr = colorAccessor(fcol, nf) + if not acc then + return nil, Err.new(Err.CORRUPT, "face " .. tostring(cerr)) + end + extras.faceColors = acc + end + if nf > 0 then + local total = #corners + local cbuf = buffer.create(total * 4) + for i = 1, total do + writeu32(cbuf, (i - 1) * 4, corners[i]) + end + local allTri = total == nf * 3 + if allTri then + for f = 0, nf - 1 do + if buffer.readu32(sizes, f * 4) ~= 3 then + allTri = false + break + end + end + end + if allTri then + prim.mode = "triangles" + prim.indices = Types.Scene.accessor(cbuf, "u32", 1, total) + elseif triangulate then + local tris: { number } = {} + local fot: { number } = {} + local p = 0 + for f = 0, nf - 1 do + local s = buffer.readu32(sizes, f * 4) + for k = 1, s - 2 do + table.insert(tris, corners[p + 1]) + table.insert(tris, corners[p + k + 1]) + table.insert(tris, corners[p + k + 2]) + table.insert(fot, f) + end + p += s + end + local ib = buffer.create(#tris * 4) + for i, v in tris do + writeu32(ib, (i - 1) * 4, v) + end + prim.mode = "triangles" + prim.indices = Types.Scene.accessor(ib, "u32", 1, #tris) + if anyFaceColor then + local fb = buffer.create(#fot * 4) + for i, v in fot do + writeu32(fb, (i - 1) * 4, v) + end + extras.faceOfTriangle = Types.Scene.accessor(fb, "u32", 1, #fot) + end + else + prim.mode = "polygons" + prim.indices = Types.Scene.accessor(cbuf, "u32", 1, total) + prim.faces = Types.Scene.accessor(sizes, "u32", 1, nf) + end + end + if next(extras) then + prim.extras = extras + end + local scene = Types.Scene.fromPrimitive(prim, nil) + scene.meta.source = { format = "off", keyword = kw, vertices = nv, faces = nf, edges = ne or 0, colormap = colormap or nil } + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local scratch = buffer.create(4) +local function fnum(v: number): string? + writef32(scratch, 0, v) + v = buffer.readf32(scratch, 0) + if v ~= v or v == math.huge or v == -math.huge then + return nil + end + return string.format("%.9g", v) +end + +local function colorText(a: Flatten.Attr, vals: { number }, comps: number, i: number): string + local out = table.create(4) + for c = 1, 4 do + local v = if c <= comps then vals[i * comps + c] else nil + if a.raw and a.type == "unorm8" then + out[c] = string.format("%d", if v == nil then 255 else math.clamp(v, 0, 255)) + else + if v == nil then + v = 1 + elseif a.raw then + v = if a.type == "unorm16" then v / 65535 elseif a.type == "snorm8" then math.max(v / 127, -1) else math.max(v / 32767, -1) + end + out[c] = fnum(v :: number) or "0" + end + end + return table.concat(out, " ") +end + +function Off.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local wantC, wantN, wantT = o.colors ~= false, o.normals ~= false, o.texcoords ~= false + local m, merr = Flatten.merge(scene, function(name: string): boolean + return (name == "NORMAL" and wantN) or (name == "COLOR_0" and wantC) or (name == "TEXCOORD_0" and wantT) + end, { triangulate = false }) + if not m then + return nil, Err.new(Err.ARG, tostring(merr)) + end + local A = m.attrs + local P, N, C, T = A.POSITION, A.NORMAL, A.COLOR_0, A.TEXCOORD_0 + if T and T.raw then + return nil, Err.new(Err.ARG, "TEXCOORD_0 of a normalized integer type") + end + local nv = m.count + local sizes = m.sizes or {} + local nf = #sizes + local out = table.create(nv + nf + 3) + table.insert(out, (if T then "ST" else "") .. (if C then "C" else "") .. (if N then "N" else "") .. "OFF") + if o.comment then + table.insert(out, "# " .. string.gsub(o.comment, "[\r\n]", " ")) + end + table.insert(out, string.format("%d %d 0", nv, nf)) + local pv = P.values + for i = 0, nv - 1 do + local x, y, z = fnum(pv[i * 3 + 1]), fnum(pv[i * 3 + 2]), fnum(pv[i * 3 + 3]) + if not (x and y and z) then + return nil, Err.new(Err.ARG, "OFF cannot hold a non-finite coordinate") + end + local s = x .. " " .. y .. " " .. z + if N then + local nvv = N.values + s ..= " " .. (fnum(nvv[i * 3 + 1]) or "0") .. " " .. (fnum(nvv[i * 3 + 2]) or "0") .. " " .. (fnum(nvv[i * 3 + 3]) or "0") + end + if C then + s ..= " " .. colorText(C, C.values, C.components, i) + end + if T then + local tv, tc = T.values, T.components + s ..= " " .. (fnum(tv[i * tc + 1]) or "0") .. " " .. (fnum(if tc >= 2 then tv[i * tc + 2] else 0) or "0") + end + table.insert(out, s) + end + local fc: Flatten.Attr? = nil + local fcMap: { number }? = nil + if wantC and #m.parts == 1 and nf > 0 then + local ex = m.parts[1].prim.extras + local acc = type(ex) == "table" and ex.faceColors + if acc then + local raw = acc.type == "unorm8" or acc.type == "unorm16" or acc.type == "snorm8" or acc.type == "snorm16" + local vals = Flatten.numbers(acc, raw) + if vals then + local a: Flatten.Attr = { type = acc.type, components = acc.components, raw = raw, values = vals } + if acc.count == nf then + fc = a + elseif (ex :: { [string]: any }).faceOfTriangle then + local fot = Flatten.numbers(ex.faceOfTriangle, true) + if fot and #fot == nf then + fc, fcMap = a, fot + for _, f in fot do + if f < 0 or f >= acc.count then + fc = nil + break + end + end + end + end + end + end + end + local corners = m.corners + local p = 0 + for f = 1, nf do + local s = sizes[f] + local line = table.create(s + 2) + line[1] = string.format("%d", s) + for k = 1, s do + line[k + 1] = string.format("%d", corners[p + k]) + end + p += s + if fc then + 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, " ")) + end + table.insert(out, "") + return buffer.fromstring(table.concat(out, "\n")), nil +end + +return Off +end +__FILES["model/ply"] = function() + +-- model/ply: Stanford PLY (Greg Turk 1994; paulbourke.net/dataformats/ply, rply / plyfile behaviour), ascii and +-- binary either endian, read + write. Supports: every property type, faces (fan-triangulated or "polygons"), point +-- clouds; other elements, comments, obj_info and property order round-trip. Not supported: vertex list properties. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Binary = __include("model/ply/Binary") +local Flatten = __include("codecs/model/MeshFlatten") + +-- ------------------------------------------------------------------------------------------------ contract +local Ply = { + name = "ply", + category = "model", + extensions = { "ply" }, + mime = { "model/ply", "application/ply" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/MeshFlatten" }, + caps = { decode = true, encode = true, ascii = true, binary = true, polygons = true, points = true, colors = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + triangulate: boolean?, -- default true + maxVertices: number?, -- default 2^24 + maxFaces: number?, -- faces, and rows of any other element (default 2^25) +} +type EncodeOptions = { + format: ("binary_little_endian" | "binary_big_endian" | "ascii")?, -- default "binary_little_endian" + comments: { string }?, +} + +type Prop = { name: string, ply: string, code: number, list: boolean, countPly: string?, countCode: number? } +type Elem = { name: string, count: number, props: { Prop } } + +-- ------------------------------------------------------------------------------------------------ constants +local CODES: { [string]: number } = { + char = 1, + int8 = 1, + uchar = 2, + uint8 = 2, + short = 3, + int16 = 3, + ushort = 4, + uint16 = 4, + int = 5, + int32 = 5, + uint = 6, + uint32 = 6, + float = 7, + float32 = 7, + double = 8, + float64 = 8, +} +local ACC_TYPE = { "i8", "u8", "i16", "u16", "i32", "u32", "f32", "f64" } +local PLY_NAME = { "char", "uchar", "short", "ushort", "int", "uint", "float", "double" } +local CODE_OF_ACC: { [string]: number } = { i8 = 1, u8 = 2, i16 = 3, u16 = 4, i32 = 5, u32 = 6, f32 = 7, f64 = 8, unorm8 = 2, unorm16 = 4, snorm8 = 1, snorm16 = 3 } +local RANGE = { { -128, 127 }, { 0, 255 }, { -32768, 32767 }, { 0, 65535 }, { -2147483648, 2147483647 }, { 0, 4294967295 } } +local SIZE = Binary.SIZE +local ENCODINGS = { ascii = true, binary_little_endian = true, binary_big_endian = true } +local MAX_HEADER = 1048576 +local TEXCOORD_PAIRS = { { "u", "v" }, { "s", "t" }, { "texture_u", "texture_v" }, { "texture_s", "texture_t" } } + +-- ------------------------------------------------------------------------------------------------ sniff +function Ply.sniff(r: Bytes.Reader): number + local h = r:peek(4) + return if h == "ply\n" or h == "ply\r" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +type Header = { encoding: string, elems: { Elem }, comments: { string }, objInfo: { string }, dataStart: number } + +local function parseHeader(r: Bytes.Reader): (Header?, Err.Err?) + local b, base, size = r.buf, r.base, r.limit - r.base + local text = buffer.readstring(b, base, math.min(size, MAX_HEADER)) + if string.sub(text, 1, 3) ~= "ply" or not string.match(string.sub(text, 4, 5), "^\r?\n") then + return nil, Err.new(Err.CORRUPT, "bad signature", base) + end + local h: Header = { encoding = "", elems = {}, comments = {}, objInfo = {}, dataStart = -1 } + local at = 1 + local first = true + while true do + local e = string.find(text, "\n", at, true) + if not e then + if size > MAX_HEADER then + return nil, Err.new(Err.LIMIT, "header longer than 1 MB") + end + return nil, Err.new(Err.TRUNCATED, "no end_header", base + at - 1) + end + local line = string.sub(text, at, e - 1) + if string.sub(line, -1) == "\r" then + line = string.sub(line, 1, -2) + end + local lineAt = base + at - 1 + at = e + 1 + local kw = string.match(line, "^%s*(%S+)") + if first then + first = false -- "ply" + elseif kw == nil then + elseif kw == "end_header" then + h.dataStart = base + at - 1 + break + elseif kw == "comment" or kw == "obj_info" then + local rest = string.match(line, "^%s*%S+ ?(.*)$") or "" + table.insert(if kw == "comment" then h.comments else h.objInfo, rest) + elseif kw == "format" then + local enc, ver = string.match(line, "^%s*format%s+(%S+)%s+(%S+)") + if not enc or not ENCODINGS[enc] then + return nil, Err.new(Err.UNSUPPORTED, "unknown format " .. tostring(enc), lineAt) + end + 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 + local name, count = string.match(line, "^%s*element%s+(%S+)%s+(%d+)%s*$") + local n = tonumber(count) + if not name or not n then + return nil, Err.new(Err.CORRUPT, "bad element line", lineAt) + end + table.insert(h.elems, { name = name, count = n, props = {} }) + elseif kw == "property" then + local el = h.elems[#h.elems] + if not el then + return nil, Err.new(Err.CORRUPT, "property before any element", lineAt) + end + local words: { string } = {} + for w in string.gmatch(line, "%S+") do + table.insert(words, w) + end + local p: Prop + if words[2] == "list" and #words == 5 then + local cc, ic = CODES[words[3]], CODES[words[4]] + 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 } :: Prop + elseif #words == 3 and CODES[words[2]] then + 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 + for _, q in el.props do + if q.name == p.name then + return nil, Err.new(Err.CORRUPT, "duplicate property " .. p.name, lineAt) + end + end + table.insert(el.props, p) + else + return nil, Err.new(Err.CORRUPT, "unknown header line: " .. string.sub(line, 1, 60), lineAt) + end + end + if h.encoding == "" then + return nil, Err.new(Err.CORRUPT, "no format line", base) + end + return h, nil +end + +type Plan = { + code: { number }, + isList: { boolean }, + countCode: { number }, + dst: { buffer }, + dOff: { number }, + dStride: { number }, + dCode: { number }, + sizes: { buffer }, + bound: { number }, + totals: { number }, +} + +local function newPlan(e: Elem): Plan + local np = #e.props + local pl: Plan = { + code = table.create(np, 0), + isList = table.create(np, false), + countCode = table.create(np, 2), + dst = table.create(np) :: { buffer }, + dOff = table.create(np, 0), + dStride = table.create(np, 0), + dCode = table.create(np, 0), + sizes = table.create(np) :: { buffer }, + bound = table.create(np, -1), + totals = table.create(np, 0), + } + for k, p in e.props do + pl.code[k] = p.code + pl.isList[k] = p.list + pl.countCode[k] = p.countCode or 2 + pl.dCode[k] = p.code + pl.dStride[k] = SIZE[p.code] + end + return pl +end + +local function ownBuffers(e: Elem, pl: Plan) + for k, p in e.props do + if not p.list and pl.dst[k] == nil then + pl.dst[k] = buffer.create(e.count * SIZE[p.code]) + end + end +end + +local function readBinary(r: Bytes.Reader, p: number, e: Elem, pl: Plan, be: boolean): (number?, Err.Err?) + local b, limit, n, np = r.buf, r.limit, e.count, #e.props + local hasList, rowSize = false, 0 + for k, pr in e.props do + if pr.list then + hasList = true + rowSize += SIZE[pr.countCode :: number] + else + rowSize += SIZE[pr.code] + end + end + if n * rowSize > limit - p then + return nil, Err.new(Err.TRUNCATED, string.format("element %s: %d rows need at least %d bytes", e.name, n, n * rowSize), p) + end + if not hasList then + ownBuffers(e, pl) + local srcOff = table.create(np, 0) + local o = 0 + for k, pr in e.props do + srcOff[k] = o + o += SIZE[pr.code] + end + Binary.fixed(b, p, n, rowSize, np, srcOff, pl.code, be, pl.dst, pl.dOff, pl.dStride, pl.dCode) + return p + n * rowSize, nil + end + local q, totals = Binary.scan(b, p, limit, n, np, pl.code, pl.isList, pl.countCode, be) + if q < 0 then + return nil, Err.new(if totals == "bad list count" then Err.CORRUPT else Err.TRUNCATED, "element " .. e.name .. ": " .. tostring(totals), p) + end + ownBuffers(e, pl) + for k, pr in e.props do + if pr.list then + pl.totals[k] = totals[k] + pl.sizes[k] = buffer.create(n * 4) + pl.dst[k] = buffer.create(totals[k] * SIZE[pl.dCode[k]]) + end + end + local ok, msg = Binary.rows(b, p, n, np, pl.code, pl.isList, pl.countCode, be, pl.dst, pl.dOff, pl.dStride, pl.dCode, pl.sizes, pl.bound) + if not ok then + return nil, Err.new(Err.CORRUPT, "element " .. e.name .. ": " .. tostring(msg), p) + end + return q, nil +end + +local function value(tok: string?, code: number): number? + if tok == nil then + return nil + end + local v = tonumber(tok) + if v == nil then + return nil + end + local rg = RANGE[code] + if rg and (v ~= v // 1 or v < rg[1] or v > rg[2]) then + return nil + end + return v +end + +local function readAscii(nextTok: () -> string?, e: Elem, pl: Plan): Err.Err? + ownBuffers(e, pl) + local n = e.count + local listSizes: { [number]: { number } } = {} + local listItems: { [number]: { number } } = {} + for k, p in e.props do + if p.list then + listSizes[k] = table.create(n) :: { number } + listItems[k] = {} + end + end + local wr = Binary.wr + for i = 0, n - 1 do + for k, p in e.props do + if p.list then + local t = nextTok() + local c = value(t, p.countCode :: number) + if c == nil or c < 0 or c % 1 ~= 0 then + return Err.new(if t == nil then Err.TRUNCATED else Err.CORRUPT, string.format("element %s row %d: bad list count", e.name, i)) + end + listSizes[k][i + 1] = c + local items, bd, code = listItems[k], pl.bound[k], p.code + for _ = 1, c do + local t2 = nextTok() + local v = value(t2, code) + if v == nil then + return Err.new(if t2 == nil then Err.TRUNCATED else Err.CORRUPT, string.format("element %s row %d: bad value", e.name, i)) + end + if bd >= 0 and (v < 0 or v >= bd or v ~= v // 1) then + return Err.new(Err.CORRUPT, string.format("element %s row %d: vertex index out of range", e.name, i)) + end + table.insert(items, v) + end + else + local t = nextTok() + local v = value(t, p.code) + if v == nil then + return Err.new(if t == nil then Err.TRUNCATED else Err.CORRUPT, string.format("element %s row %d: bad %s value", e.name, i, p.name)) + end + wr(pl.dst[k], pl.dOff[k] + i * pl.dStride[k], pl.dCode[k], v) + end + end + end + for k in listSizes do + local sz, items = listSizes[k], listItems[k] + local s = buffer.create(n * 4) + for i = 1, n do + buffer.writeu32(s, (i - 1) * 4, sz[i]) + end + local dc = pl.dCode[k] + local d = buffer.create(#items * SIZE[dc]) + for j = 1, #items do + wr(d, (j - 1) * SIZE[dc], dc, items[j]) + end + pl.sizes[k], pl.dst[k], pl.totals[k] = s, d, #items + end + return nil +end + +local function propIndex(e: Elem, name: string): number? + for k, p in e.props do + if p.name == name then + return k + end + end + return nil +end + +local function planVertex(e: Elem, pl: Plan): ({ [string]: Types.Accessor }?, Err.Err?) + local nv = e.count + local attrs: { [string]: Types.Accessor } = {} + local taken: { [number]: boolean } = {} + for _, p in e.props do + if p.list then + return nil, Err.new(Err.UNSUPPORTED, "list property " .. p.name .. " in the vertex element") + end + end + local function group(attr: string, names: { string }, required: number, ok: (codes: { number }) -> number?, comps: number, fillValue: number?) + local ks: { [number]: number } = {} + local codes = {} + for i, nm in names do + local k = propIndex(e, nm) + if k == nil then + if i <= required then + return + end + else + ks[i] = k + table.insert(codes, e.props[k].code) + end + end + local dc = ok(codes) + if dc == nil then + return + end + local sz = SIZE[dc] + local buf = buffer.create(nv * comps * sz) + if fillValue then + for i = 0, nv - 1 do + Binary.wr(buf, (i * comps + comps - 1) * sz, dc, fillValue) + end + end + for i, k in ks do + pl.dst[k], pl.dOff[k], pl.dStride[k], pl.dCode[k] = buf, (i - 1) * sz, comps * sz, dc + taken[k] = true + end + local accType = if attr == "COLOR_0" and dc == 2 then "unorm8" elseif attr == "COLOR_0" and dc == 4 then "unorm16" else ACC_TYPE[dc] + attrs[attr] = Types.Scene.accessor(buf, accType, comps, nv) + end + local function floats(codes: { number }): number? + for _, c in codes do + if c ~= 7 and c ~= 8 then + return nil + end + end + return 7 + end + local function anyNumber(_codes: { number }): number? + return 7 + end + group("POSITION", { "x", "y", "z" }, 3, anyNumber, 3, nil) + group("NORMAL", { "nx", "ny", "nz" }, 3, floats, 3, nil) + do + local rk, gk, bk, ak = propIndex(e, "red"), propIndex(e, "green"), propIndex(e, "blue"), propIndex(e, "alpha") + if rk and gk and bk then + local codes = { e.props[rk].code, e.props[gk].code, e.props[bk].code } + if ak then + table.insert(codes, e.props[ak].code) + end + local cls: number? = codes[1] + for _, c in codes do + local a = if c == 8 then 7 else c + local b0 = if cls == 8 then 7 else cls + if a ~= b0 then + cls = nil + end + end + local dc = if cls == 2 then 2 elseif cls == 4 then 4 elseif cls == 7 or cls == 8 then 7 else nil + if dc then + group("COLOR_0", { "red", "green", "blue", "alpha" }, 3, function() + return dc + end, 4, if dc == 2 then 255 elseif dc == 4 then 65535 else 1) + end + end + end + for _, pair in TEXCOORD_PAIRS do + if attrs.TEXCOORD_0 == nil then + group("TEXCOORD_0", pair, 2, floats, 2, nil) + end + end + for k, p in e.props do + if not taken[k] then + local buf = buffer.create(nv * SIZE[p.code]) + pl.dst[k] = buf + attrs["_" .. p.name] = Types.Scene.accessor(buf, ACC_TYPE[p.code], 1, nv) + end + end + return attrs, nil +end + +local function fan(sizes: buffer, corners: buffer, nf: number): (buffer, number, buffer) + local nt = 0 + for f = 0, nf - 1 do + local s = buffer.readu32(sizes, f * 4) + if s >= 3 then + nt += s - 2 + end + end + local idx, fot = buffer.create(nt * 12), buffer.create(nt * 4) + local p, t = 0, 0 + local readu32, writeu32 = buffer.readu32, buffer.writeu32 + for f = 0, nf - 1 do + local s = readu32(sizes, f * 4) + local a = readu32(corners, p * 4) + for k = 1, s - 2 do + writeu32(idx, t * 12, a) + writeu32(idx, t * 12 + 4, readu32(corners, (p + k) * 4)) + writeu32(idx, t * 12 + 8, readu32(corners, (p + k + 1) * 4)) + writeu32(fot, t * 4, f) + t += 1 + end + p += s + end + return idx, nt, fot +end + +function Ply.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local triangulate = true + if opts and opts.triangulate == false then + triangulate = false + end + local maxVertices = opts and opts.maxVertices or 2 ^ 24 + local maxFaces = opts and opts.maxFaces or 2 ^ 25 + local h, herr = parseHeader(r) + if not h then + return nil, herr + end + local vi: number?, fi: number?, idxK: number + for i, e in h.elems do + if e.name == "vertex" and vi == nil then + vi = i + if e.count > maxVertices then + return nil, Err.new(Err.LIMIT, string.format("%d vertices is over the %d vertex limit", e.count, maxVertices)) + end + elseif e.name == "face" and fi == nil then + local k = propIndex(e, "vertex_indices") or propIndex(e, "vertex_index") + if k and e.props[k].list then + fi, idxK = i, k + end + end + if e.count > maxFaces then + return nil, Err.new(Err.LIMIT, string.format("element %s: %d rows is over the %d limit", e.name, e.count, maxFaces)) + end + end + if vi == nil then + return nil, Err.new(Err.CORRUPT, "no vertex element") + end + local nv = h.elems[vi].count + local be = h.encoding == "binary_big_endian" + local ascii = h.encoding == "ascii" + local nextTok: () -> string? = function() + return nil + end + if ascii then + local body = buffer.readstring(r.buf, h.dataStart, r.limit - h.dataStart) + local need = 0 + for _, e in h.elems do + need += e.count * #e.props + end + if need > (#body + 1) // 2 then + return nil, Err.new(Err.TRUNCATED, "fewer values than the element counts need", h.dataStart) + end + nextTok = string.gmatch(body, "%S+") :: any + end + local plans: { Plan } = {} + local attrs: { [string]: Types.Accessor } = {} + local p = h.dataStart + if not ascii then + local need = 0 + for _, e in h.elems do + local row = 0 + for _, pr in e.props do + row += SIZE[if pr.list then pr.countCode :: number else pr.code] + end + need += e.count * row + end + if need > r.limit - h.dataStart then + return nil, Err.new(Err.TRUNCATED, string.format("the elements need at least %d bytes, %d left", need, r.limit - h.dataStart), h.dataStart) + end + end + for i, e in h.elems do + local pl = newPlan(e) + plans[i] = pl + if i == vi then + local a, aerr = planVertex(e, pl) + if not a then + return nil, aerr + end + attrs = a + elseif i == fi then + pl.dCode[idxK] = 6 + pl.bound[idxK] = nv + end + if ascii then + local err = readAscii(nextTok, e, pl) + if err then + return nil, err + end + else + local q, err = readBinary(r, p, e, pl, be) + if not q then + return nil, err + end + p = q + end + end + local prim: Types.Primitive = { attributes = attrs, mode = "points" } + local nf = 0 + local extras: { [string]: any } = {} + local faceProps: { any } = {} + if fi then + local e, pl = h.elems[fi], plans[fi] + nf = e.count + local sizes, corners, total = pl.sizes[idxK], pl.dst[idxK], pl.totals[idxK] + local faceAttributes: { [string]: Types.Accessor } = {} + local faceLists: { [string]: any } = {} + local anyExtra = false + for k, pr in e.props do + table.insert(faceProps, { name = pr.name, type = pr.ply, countType = pr.countPly }) + if k ~= idxK then + anyExtra = true + if pr.list then + faceLists[pr.name] = { + countType = pr.countPly, + itemType = pr.ply, + sizes = Types.Scene.accessor(pl.sizes[k], "u32", 1, nf), + items = Types.Scene.accessor(pl.dst[k], ACC_TYPE[pr.code], 1, pl.totals[k]), + } + else + faceAttributes[pr.name] = Types.Scene.accessor(pl.dst[k], ACC_TYPE[pr.code], 1, nf) + end + end + end + if next(faceAttributes) then + extras.faceAttributes = faceAttributes + end + if next(faceLists) then + extras.faceLists = faceLists + end + if nf > 0 then + local allTri = total == nf * 3 + if allTri then + for f = 0, nf - 1 do + if buffer.readu32(sizes, f * 4) ~= 3 then + allTri = false + break + end + end + end + if allTri then + prim.mode = "triangles" + prim.indices = Types.Scene.accessor(corners, "u32", 1, total) + elseif triangulate then + local idx, nt, fot = fan(sizes, corners, nf) + prim.mode = "triangles" + prim.indices = Types.Scene.accessor(idx, "u32", 1, nt * 3) + if anyExtra then + extras.faceOfTriangle = Types.Scene.accessor(fot, "u32", 1, nt) + end + else + prim.mode = "polygons" + prim.indices = Types.Scene.accessor(corners, "u32", 1, total) + prim.faces = Types.Scene.accessor(sizes, "u32", 1, nf) + end + end + end + if next(extras) then + prim.extras = extras + end + local elements: { any } = {} + local order: { string } = {} + for i, e in h.elems do + table.insert(order, e.name) + if i ~= vi and i ~= fi then + local pl = plans[i] + local props = {} + for k, pr in e.props do + props[k] = { name = pr.name, type = pr.ply, countType = pr.countPly, values = pl.dst[k], sizes = pl.sizes[k], total = if pr.list then pl.totals[k] else nil } + end + table.insert(elements, { name = e.name, count = e.count, properties = props }) + end + end + local vprops = {} + for _, pr in h.elems[vi].props do + table.insert(vprops, { name = pr.name, type = pr.ply }) + end + local scene = Types.Scene.fromPrimitive(prim, nil) + scene.meta.source = { format = "ply", encoding = h.encoding, vertices = nv, faces = nf } + scene.meta.ply = { + comments = h.comments, + objInfo = h.objInfo, + elements = elements, + order = order, + vertexProperties = vprops, + faceProperties = if fi then faceProps else nil, + } + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +type Column = { name: string, ply: string, code: number, values: { number }, stride: number, offset: number } +type ListColumn = { name: string, ply: string, code: number, countPly: string, countCode: number, sizes: { number }, items: { number } } + +local function keep(name: string): boolean + return name == "NORMAL" or name == "COLOR_0" or name == "TEXCOORD_0" or string.sub(name, 1, 1) == "_" +end + +local function spell(want: string?, code: number): string + if want and CODES[want] == code then + return want + end + return PLY_NAME[code] +end + +local function toInt(v: number, code: number): number + local rg = RANGE[code] + if rg then + if v ~= v then + return 0 + end + return math.clamp(math.floor(v + 0.5), rg[1], rg[2]) + end + return v +end + +type Row = { kind: "s", col: Column } | { kind: "l", col: ListColumn } + +local function rowsAscii(out: { string }, n: number, cols: { Row }) + local fmt = string.format + local function num(code: number, v: number): string + if code == 7 then + return fmt("%.9g", v) + elseif code == 8 then + return fmt("%.17g", v) + end + return fmt("%d", toInt(v, code)) + end + local at: { [number]: number } = {} + for i = 0, n - 1 do + local parts = {} + for k, c in cols do + if c.kind == "s" then + local col = c.col :: Column + table.insert(parts, num(col.code, col.values[i * col.stride + col.offset + 1])) + else + local col = c.col :: ListColumn + local s = col.sizes[i + 1] + table.insert(parts, fmt("%d", s)) + local a = at[k] or 0 + for j = 1, s do + table.insert(parts, num(col.code, col.items[a + j])) + end + at[k] = a + s + end + end + table.insert(out, table.concat(parts, " ")) + end +end + +local function rowsBinary(w: Bytes.Writer, n: number, cols: { Row }, be: boolean) + local size = 0 + for _, c in cols do + if c.kind == "s" then + size += n * SIZE[(c.col :: Column).code] + else + local col = c.col :: ListColumn + size += n * SIZE[col.countCode] + #col.items * SIZE[col.code] + end + end + local o = w:reserve(size) + local d = w.buf + local put = Binary.put + local at: { [number]: number } = {} + for i = 0, n - 1 do + for k, c in cols do + if c.kind == "s" then + local col = c.col :: Column + local code = col.code + put(d, o, code, toInt(col.values[i * col.stride + col.offset + 1], code), be) + o += SIZE[code] + else + local col = c.col :: ListColumn + local s = col.sizes[i + 1] + put(d, o, col.countCode, s, be) + o += SIZE[col.countCode] + local a, code = at[k] or 0, col.code + for j = 1, s do + put(d, o, code, toInt(col.items[a + j], code), be) + o += SIZE[code] + end + at[k] = a + s + end + end + end + w.pos = o +end + +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) :: { number } + for i = 0, count - 1 do + out[i + 1] = Binary.rd(b, i * SIZE[code], code, false) + end + return out +end + +local function countCodeFor(maxCount: number): number + return if maxCount <= 255 then 2 elseif maxCount <= 65535 then 4 else 6 +end + +function Ply.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local enc = o.format or "binary_little_endian" + if not ENCODINGS[enc] then + return nil, Err.new(Err.ARG, "format must be ascii, binary_little_endian or binary_big_endian") + end + local m, merr = Flatten.merge(scene, keep, { triangulate = false }) + if not m then + return nil, Err.new(Err.ARG, tostring(merr)) + end + local meta: any = if type(scene) == "table" and type(scene.meta) == "table" and type(scene.meta.ply) == "table" then scene.meta.ply else {} + local nv = m.count + local srcType: { [string]: string } = {} + local srcOrder: { [string]: number } = {} + if type(meta.vertexProperties) == "table" then + for i, vp in meta.vertexProperties do + if type(vp) == "table" and type(vp.name) == "string" then + srcType[vp.name] = vp.type + srcOrder[vp.name] = i + end + end + end + local cols: { Column } = {} + local function add(name: string, code: number, a: Flatten.Attr, comp: number) + table.insert(cols, { name = name, ply = spell(srcType[name], code), code = code, values = a.values, stride = a.components, offset = comp }) + end + local function floatCode(name: string): number + return if CODES[srcType[name] or ""] == 8 then 8 else 7 + end + local A = m.attrs + for i, nm in { "x", "y", "z" } do + add(nm, floatCode(nm), A.POSITION, i - 1) + end + if A.NORMAL then + for i, nm in { "nx", "ny", "nz" } do + add(nm, floatCode(nm), A.NORMAL, i - 1) + end + end + local C = A.COLOR_0 + if C then + local code = if C.raw and C.type == "unorm8" then 2 elseif C.raw and C.type == "unorm16" then 4 else 7 + if C.raw and code == 7 then + local vals = table.create(#C.values) + local scale = if C.type == "snorm8" then 127 else 32767 + for i, v in C.values do + vals[i] = math.max(v / scale, -1) + end + C = { type = "f32", components = C.components, raw = false, values = vals } + end + local cc = C :: Flatten.Attr + for i, nm in { "red", "green", "blue" } do + if i <= cc.components then + add(nm, code, cc, i - 1) + end + end + if cc.components >= 4 then + local full = if code == 2 then 255 elseif code == 4 then 65535 else 1 + local need = srcOrder.alpha ~= nil + if not need then + for i = 0, nv - 1 do + if cc.values[i * cc.components + 4] ~= full then + need = true + break + end + end + end + if need then + add("alpha", code, cc, 3) + end + end + end + if A.TEXCOORD_0 then + local names = { "s", "t" } + for _, pair in TEXCOORD_PAIRS do + if srcOrder[pair[1]] and srcOrder[pair[2]] then + names = pair + break + end + end + local tc = A.TEXCOORD_0 + if tc.raw then + return nil, Err.new(Err.ARG, "TEXCOORD_0 of a normalized integer type") + end + add(names[1], floatCode(names[1]), tc, 0) + if tc.components >= 2 then + add(names[2], floatCode(names[2]), tc, 1) + end + end + local customs = {} + for name in A do + if string.sub(name, 1, 1) == "_" then + table.insert(customs, name) + end + end + table.sort(customs) + for _, name in customs do + local a = A[name] + local code = CODE_OF_ACC[a.type] or 7 + local base = string.sub(name, 2) + if a.components == 1 then + add(base, code, a, 0) + else + for c = 0, a.components - 1 do + add(base .. "_" .. c, code, a, c) + end + end + end + local rank: { [Column]: number } = {} + for i, c in cols do + rank[c] = (srcOrder[c.name] or (1000000 + i)) + end + table.sort(cols, function(a: Column, b: Column): boolean + return rank[a] < rank[b] + end) + local faceRows: { Row }? = nil + local nf = 0 + if m.sizes then + local sizes = m.sizes :: { number } + nf = #sizes + local maxS, maxI = 0, 0 + for _, s in sizes do + maxS = math.max(maxS, s) + end + for _, c in m.corners do + maxI = math.max(maxI, c) + end + local fprops: { any } = if type(meta.faceProperties) == "table" then meta.faceProperties else {} + local idxName, idxType, idxCount = "vertex_indices", nil, nil + for _, fp in fprops do + if type(fp) == "table" and (fp.name == "vertex_indices" or fp.name == "vertex_index") then + idxName, idxType, idxCount = fp.name, fp.type, fp.countType + end + end + local cc = countCodeFor(maxS) + local srcCC = CODES[idxCount or ""] + if srcCC and srcCC <= 6 and SIZE[srcCC] >= SIZE[cc] then + cc = srcCC + end + local ic = if maxI < 2147483648 then 5 else 6 + local srcIC = CODES[idxType or ""] + if srcIC == 6 or (srcIC and srcIC <= 6 and maxI <= RANGE[srcIC][2]) then + ic = srcIC + end + local rows: { Row } = { + { kind = "l", col = { name = idxName, ply = spell(idxType, ic), code = ic, countPly = spell(idxCount, cc), countCode = cc, sizes = sizes, items = m.corners } }, + } + if #m.parts == 1 then + local ex = m.parts[1].prim.extras + local fot: { number }? = nil + if type(ex) == "table" and ex.faceOfTriangle then + fot = Flatten.numbers(ex.faceOfTriangle, true) + end + local function perFace(vals: { number }, count: number): { number }? + if count == nf then + return vals + elseif fot and #fot == nf then + local out = table.create(nf) :: { number } + for i = 1, nf do + local v = vals[fot[i] + 1] + if v == nil then + return nil + end + out[i] = v + end + return out + end + return nil + end + local extraRows: { [string]: Row } = {} + if type(ex) == "table" and type(ex.faceAttributes) == "table" then + 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" :: "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: 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 ""]) + if sz and items and code and #sz == nf and fot == nil then + local mx = 0 + for _, s in sz do + mx = math.max(mx, s) + end + local lcc = countCodeFor(mx) + local scc = CODES[fl.countType or ""] + if scc and scc <= 6 and SIZE[scc] >= SIZE[lcc] then + lcc = scc + end + 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 + local placed: { [string]: boolean } = { [idxName] = true } + local ordered: { Row } = {} + for _, fp in fprops do + if type(fp) == "table" then + if fp.name == idxName then + table.insert(ordered, rows[1]) + elseif extraRows[fp.name] then + table.insert(ordered, extraRows[fp.name]) + placed[fp.name] = true + end + end + end + if not table.find(ordered, rows[1]) then + table.insert(ordered, 1, rows[1]) + end + local rest = {} + for name in extraRows do + if not placed[name] then + table.insert(rest, name) + end + end + table.sort(rest) + for _, name in rest do + table.insert(ordered, extraRows[name]) + end + rows = ordered + end + faceRows = rows + end + type Raw = { name: string, count: number, rows: { Row } } + local raws: { [string]: Raw } = {} + local rawOrder: { string } = {} + if type(meta.elements) == "table" then + for _, el in meta.elements do + if type(el) == "table" and type(el.name) == "string" and type(el.count) == "number" and type(el.properties) == "table" and el.name ~= "vertex" and not raws[el.name] then + if el.name == "face" and faceRows then + continue + end + local rows: { Row } = {} + 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") + end + if pr.countType then + local cc = CODES[pr.countType] + local sz = cc and bufNumbers(pr.sizes, 6, el.count) + local total = 0 + if sz then + for _, s in sz do + total += s + end + end + local items = sz and bufNumbers(pr.values, code, total) + 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" :: "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" :: "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 } + table.insert(rawOrder, el.name) + end + end + end + local order: { string } = {} + local seen: { [string]: boolean } = {} + local function want(name: string) + if seen[name] then + return + end + if name == "vertex" or (name == "face" and faceRows) or raws[name] then + seen[name] = true + table.insert(order, name) + end + end + if type(meta.order) == "table" then + for _, name in meta.order do + if type(name) == "string" then + want(name) + end + end + end + want("vertex") + want("face") + for _, name in rawOrder do + want(name) + end + local vrows: { Row } = {} + for _, c in cols do + table.insert(vrows, { kind = "s" :: "s", col = c }) + end + local lines = { "ply", "format " .. enc .. " 1.0" } + local function noNewline(s: any): string + return (string.gsub(tostring(s), "[\r\n]", " ")) + end + for _, c in (if type(meta.comments) == "table" then meta.comments else {}) :: { any } do + table.insert(lines, "comment " .. noNewline(c)) + end + for _, c in o.comments or {} do + table.insert(lines, "comment " .. noNewline(c)) + end + for _, c in (if type(meta.objInfo) == "table" then meta.objInfo else {}) :: { any } do + table.insert(lines, "obj_info " .. noNewline(c)) + end + local function elementRows(name: string): (number, { Row }) + if name == "vertex" then + return nv, vrows + elseif name == "face" and faceRows then + return nf, faceRows + end + local raw = raws[name] + return raw.count, raw.rows + end + for _, name in order do + local n, rows = elementRows(name) + table.insert(lines, "element " .. noNewline(name) .. " " .. string.format("%d", n)) + for _, rw in rows do + if rw.kind == "s" then + local c = rw.col :: Column + table.insert(lines, "property " .. c.ply .. " " .. noNewline(c.name)) + else + local c = rw.col :: ListColumn + table.insert(lines, "property list " .. c.countPly .. " " .. c.ply .. " " .. noNewline(c.name)) + end + end + end + table.insert(lines, "end_header") + local header = table.concat(lines, "\n") .. "\n" + if enc == "ascii" then + local out = { header } + local body: { string } = {} + for _, name in order do + local n, rows = elementRows(name) + rowsAscii(body, n, rows) + end + if #body > 0 then + table.insert(out, table.concat(body, "\n")) + table.insert(out, "\n") + end + return buffer.fromstring(table.concat(out)), nil + end + local w = Bytes.writer(#header + nv * 32 + nf * 16) + w:string(header) + for _, name in order do + local n, rows = elementRows(name) + rowsBinary(w, n, rows, enc == "binary_big_endian") + end + return w:finish(), nil +end + +return Ply +end +__FILES["model/ply/Binary"] = @native function() + + + +-- model/ply/Binary: PLY element data loops; type codes 1 i8, 2 u8, 3 i16, 4 u16, 5 i32, 6 u32, 7 f32, 8 f64, either +-- byte order. Never throws: the caller bounds every row first. +local readu8, readi8, readu16, readi16, readu32, readi32 = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.readi32 +local readf32, readf64 = buffer.readf32, buffer.readf64 +local writeu8, writei8, writeu16, writei16, writeu32, writei32 = buffer.writeu8, buffer.writei8, buffer.writeu16, buffer.writei16, buffer.writeu32, buffer.writei32 +local writef32, writef64 = buffer.writef32, buffer.writef64 +local byteswap, band, rshift = bit32.byteswap, bit32.band, bit32.rshift + +local Binary = {} + +Binary.SIZE = { 1, 1, 2, 2, 4, 4, 4, 8 } +local SIZE = Binary.SIZE +local scratch = buffer.create(8) + +@native local function swap16(v: number): number + return rshift(v, 8) + band(v, 255) * 256 +end + +@native local function rd(b: buffer, q: number, code: number, be: boolean): number + if not be then + if code == 7 then + return readf32(b, q) + elseif code == 2 then + return readu8(b, q) + elseif code == 5 then + return readi32(b, q) + elseif code == 6 then + return readu32(b, q) + elseif code == 8 then + return readf64(b, q) + elseif code == 1 then + return readi8(b, q) + elseif code == 3 then + return readi16(b, q) + end + return readu16(b, q) + end + if code <= 2 then + return if code == 1 then readi8(b, q) else readu8(b, q) + elseif code <= 4 then + local v = swap16(readu16(b, q)) + return if code == 3 and v >= 32768 then v - 65536 else v + elseif code <= 7 then + local v = byteswap(readu32(b, q)) + if code == 6 then + return v + elseif code == 5 then + return if v >= 2147483648 then v - 4294967296 else v + end + writeu32(scratch, 0, v) + return readf32(scratch, 0) + end + writeu32(scratch, 0, byteswap(readu32(b, q + 4))) + writeu32(scratch, 4, byteswap(readu32(b, q))) + return readf64(scratch, 0) +end +Binary.rd = rd + +@native local function wr(d: buffer, o: number, code: number, v: number) + if code == 7 then + writef32(d, o, v) + elseif code == 6 then + writeu32(d, o, v) + elseif code == 5 then + writei32(d, o, v) + elseif code == 2 then + writeu8(d, o, v) + elseif code == 8 then + writef64(d, o, v) + elseif code == 1 then + writei8(d, o, v) + elseif code == 3 then + writei16(d, o, v) + else + writeu16(d, o, v) + end +end +Binary.wr = wr + +@native function Binary.put(d: buffer, o: number, code: number, v: number, be: boolean) + if not be or code <= 2 then + wr(d, o, code, v) + return + end + wr(scratch, 0, code, v) + if code <= 4 then + writeu16(d, o, swap16(readu16(scratch, 0))) + elseif code <= 7 then + writeu32(d, o, byteswap(readu32(scratch, 0))) + else + writeu32(d, o, byteswap(readu32(scratch, 4))) + writeu32(d, o + 4, byteswap(readu32(scratch, 0))) + end +end + +@native function Binary.fixed(b: buffer, p: number, n: number, rowSize: number, np: number, srcOff: { number }, code: { number }, be: boolean, dst: { buffer }, dOff: { number }, dStride: { number }, dCode: { number }) + for k = 1, np do + local sc, dc, d = code[k], dCode[k], dst[k] + local q0, o0, st = p + srcOff[k], dOff[k], dStride[k] + if sc == dc and not be then + local sz = SIZE[sc] + if sz == 4 then + for i = 0, n - 1 do + writeu32(d, o0 + i * st, readu32(b, q0 + i * rowSize)) + end + elseif sz == 1 then + for i = 0, n - 1 do + writeu8(d, o0 + i * st, readu8(b, q0 + i * rowSize)) + end + elseif sz == 2 then + for i = 0, n - 1 do + writeu16(d, o0 + i * st, readu16(b, q0 + i * rowSize)) + end + else + for i = 0, n - 1 do + writeu32(d, o0 + i * st, readu32(b, q0 + i * rowSize)) + writeu32(d, o0 + i * st + 4, readu32(b, q0 + i * rowSize + 4)) + end + end + else + for i = 0, n - 1 do + wr(d, o0 + i * st, dc, rd(b, q0 + i * rowSize, sc, be)) + end + end + end +end + +@native function Binary.scan(b: buffer, p: number, limit: number, n: number, np: number, code: { number }, isList: { boolean }, countCode: { number }, be: boolean): (number, any) + local totals = table.create(np, 0) + local q = p + for _ = 1, n do + for k = 1, np do + if isList[k] then + local cc = countCode[k] + local csz = SIZE[cc] + if q + csz > limit then + return -1, "list runs past the end" + end + local c = rd(b, q, cc, be) + if c < 0 or c ~= c // 1 then + return -1, "bad list count" + end + q += csz + c * SIZE[code[k]] + if q > limit then + return -1, "list runs past the end" + end + totals[k] += c + else + q += SIZE[code[k]] + if q > limit then + return -1, "row runs past the end" + end + end + end + end + return q, totals +end + +@native function Binary.rows(b: buffer, p: number, n: number, np: number, code: { number }, isList: { boolean }, countCode: { number }, be: boolean, dst: { buffer }, dOff: { number }, dStride: { number }, dCode: { number }, sizes: { buffer }, bound: { number }): (boolean, string?) + local at = table.create(np, 0) + local q = p + for i = 0, n - 1 do + for k = 1, np do + local sc, dc, d = code[k], dCode[k], dst[k] + if isList[k] then + local cc = countCode[k] + local c = rd(b, q, cc, be) + q += SIZE[cc] + writeu32(sizes[k], i * 4, c) + local ia, ssz, dsz, bd = at[k], SIZE[sc], SIZE[dc], bound[k] + if bd >= 0 then + for j = 0, c - 1 do + local v = rd(b, q, sc, be) + q += ssz + if v < 0 or v >= bd or v ~= v // 1 then + return false, "vertex index out of range" + end + wr(d, (ia + j) * dsz, dc, v) + end + else + for j = 0, c - 1 do + wr(d, (ia + j) * dsz, dc, rd(b, q, sc, be)) + q += ssz + end + end + at[k] = ia + c + else + wr(d, dOff[k] + i * dStride[k], dc, rd(b, q, sc, be)) + q += SIZE[sc] + end + end + end + return true, nil +end + +return Binary +end +__FILES["model/pmx"] = function() + +-- model/pmx: MikuMikuDance PMX 2.0 / 2.1 (PmxEditor's specification notes) and PMD 1.0 (MMD community notes); no +-- third-party code. Supports: every deform type, materials, bones and IK, vertex morphs as morph targets, the other +-- morphs, frames, rigid bodies and joints as extras. Not supported: writing, 2.1 soft bodies, VMD / VPD. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Read = __include("model/pmx/Read") +local Pmd = __include("model/pmx/Pmd") +local Build = __include("model/pmx/Build") + +-- ------------------------------------------------------------------------------------------------ contract +local Pmx = { + name = "pmx", + category = "model", + extensions = { "pmx", "pmd" }, + mime = { "model/x-pmx", "model/x-pmd" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Text" }, + caps = { decode = true, encode = false, materials = true, skins = true, morphTargets = true, pmd = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + files: { [string]: any }?, -- "/" or "\" separators, or the base name + resolve: ((uri: string) -> any)?, + morphs: boolean?, -- default true + maxVertices: number?, -- default 2^24 + maxBytes: number?, -- default 2^28 +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Pmx.sniff(r: Bytes.Reader): number + local head = r:peek(8) + if string.sub(head, 1, 4) == "PMX " then + return 1 + end + if string.sub(head, 1, 7) == "Pmd\0\0\128\63" then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Pmx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local pmd = r:peek(3) == "Pmd" + local m: any, msg: string?, kind: string? + if pmd then + m, msg, kind = Pmd.parse(r, opts) + else + m, msg, kind = Read.parse(r, opts) + end + if not m then + return nil, Err.from(msg, r.pos - r.base, kind) + end + local scene, berr, bkind = Build.scene(m, opts) + if not scene then + return nil, Err.from(berr, nil, bkind) + end + if pmd and scene.meta.source then + scene.meta.source.pmd = true + end + return scene, nil +end + +return Pmx +end +__FILES["model/pmx/Build"] = function() + +-- model/pmx/Build: the PMX / PMD model table to a Scene. MMD is left-handed (y up, x right, z forward): z is negated +-- and every winding reversed; UVs are already top-left. +local Types = __include("Types") + +local Build = {} + +local readf32, writef32, readi32, readu32 = buffer.readf32, buffer.writef32, buffer.readi32, buffer.readu32 +local S = Types.Scene + +local SPHERE = { [0] = "off", "multiply", "add", "subtexture" } +local MORPH = { [0] = "group", "vertex", "bone", "uv", "uv1", "uv2", "uv3", "uv4", "material", "flip", "impulse" } +local MIME = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", bmp = "image/bmp", spa = "image/bmp", sph = "image/bmp", tga = "image/x-tga", dds = "image/vnd-ms.dds", gif = "image/gif" } + +local function fetcher(opts: any): (string) -> buffer? + return function(uri: string): buffer? + if not opts then + return nil + end + local v: any = nil + local slash = string.gsub(uri, "\\", "/") + if type(opts.files) == "table" then + v = opts.files[uri] or opts.files[slash] or opts.files[string.match(slash, "([^/]+)$") or slash] + end + if v == nil and type(opts.resolve) == "function" then + local ok, res = pcall(opts.resolve, slash) + v = if ok then res else nil + end + return if type(v) == "string" then buffer.fromstring(v) elseif type(v) == "buffer" then v else nil + end +end + +local function lh(v: { number }?): { number }? + return if v then { v[1], v[2], -v[3] } else nil +end + +local function texIndex(m: any, i: number?): number? + return if type(i) == "number" and i >= 0 and i < #m.textures then i + 1 else nil +end + +local function material(m: any, mat: any): Types.Material + local out = S.material(mat.name) + local d = mat.diffuse + out.baseColor = { d[1], d[2], d[3], d[4] } + out.metallic = 0 + out.roughness = math.clamp(math.sqrt(2 / (math.max(mat.power or 0, 0) + 2)), 0, 1) + out.doubleSided = bit32.btest(mat.flags, 0x01) + if d[4] < 1 then + out.alphaMode = "blend" + end + local t = texIndex(m, mat.texture) + if t then + out.baseColorTexture = { texture = t } + end + local x: { [string]: any } = { + nameEn = mat.nameEn, diffuse = d, specular = mat.specular, specularPower = mat.power, ambient = mat.ambient, + flags = mat.flags, edge = bit32.btest(mat.flags, 0x10), edgeColor = mat.edgeColor, edgeSize = mat.edgeSize, + sphereTexture = texIndex(m, mat.sphere), sphereMode = SPHERE[mat.sphereMode] or mat.sphereMode, + toonTexture = texIndex(m, mat.toon), memo = mat.memo, indexCount = mat.count, + } + if mat.toonShared then + x.toonShared = mat.toonShared + x.toonFile = string.format("toon%02d.bmp", mat.toonShared + 1) + end + out.extras = { pmx = x } + return out +end + +local function parents(bones: { any }): { number } + local nb = #bones + local par = table.create(nb, 0) + for i, b in bones do + local p = b.parent + if type(p) == "number" and p >= 0 and p < nb and p + 1 ~= i then + par[i] = p + 1 + end + end + for i = 1, nb do + local seen, j, steps = {}, i, 0 + while par[j] ~= 0 and steps <= nb do + seen[j] = true + j = par[j] + steps += 1 + if seen[j] then + par[i] = 0 + break + end + end + end + return par +end + +local function primitive(m: any, first: number, n: number, morphs: { any }, sdef: boolean): Types.Primitive + local map: { [number]: number } = {} + local verts: { number } = {} + local ind = S.accessor(nil, "u32", 1, n) + for t = 0, n // 3 - 1 do + -- reversed winding: a, c, b + for c = 0, 2 do + local src = readu32(m.indices, (first + t * 3 + c) * 4) + local v = map[src] + if not v then + v = #verts + verts[v + 1] = src + map[src] = v + end + buffer.writeu32(ind.data, (t * 3 + (if c == 0 then 0 elseif c == 1 then 2 else 1)) * 4, v) + end + end + local nv = #verts + local nb = #m.bones + local pos, nrm, uv = S.accessor(nil, "f32", 3, nv), S.accessor(nil, "f32", 3, nv), S.accessor(nil, "f32", 2, nv) + local jo, we = S.accessor(nil, "u16", 4, nv), S.accessor(nil, "f32", 4, nv) + local edge = S.accessor(nil, "f32", 1, nv) + local attrs: { [string]: Types.Accessor } = { POSITION = pos, NORMAL = nrm, TEXCOORD_0 = uv, _EDGE_SCALE = edge } + if nb > 0 then + attrs.JOINTS_0, attrs.WEIGHTS_0 = jo, we + end + local uvas = {} + for a = 1, #m.uva do + uvas[a] = S.accessor(nil, "f32", 4, nv) + attrs["_UVA" .. a] = uvas[a] + end + local sd: { Types.Accessor }? = nil + local deform: Types.Accessor? = nil + if sdef then + sd = { S.accessor(nil, "f32", 3, nv), S.accessor(nil, "f32", 3, nv), S.accessor(nil, "f32", 3, nv) } + attrs._SDEF_C, attrs._SDEF_R0, attrs._SDEF_R1 = sd[1], sd[2], sd[3] + deform = S.accessor(nil, "u8", 1, nv) + attrs._DEFORM = deform + end + for v = 0, nv - 1 do + local src = verts[v + 1] + for c = 0, 2 do + local sgn = if c == 2 then -1 else 1 + writef32(pos.data, (v * 3 + c) * 4, sgn * readf32(m.positions, (src * 3 + c) * 4)) + writef32(nrm.data, (v * 3 + c) * 4, sgn * readf32(m.normals, (src * 3 + c) * 4)) + end + buffer.copy(uv.data, v * 8, m.uvs, src * 8, 8) + buffer.copy(edge.data, v * 4, m.edge, src * 4, 4) + for a, acc in uvas do + buffer.copy(acc.data, v * 16, m.uva[a], src * 16, 16) + end + local sum = 0 + local js, ws = table.create(4, 0), table.create(4, 0) + for c = 0, 3 do + local j = readi32(m.joints, src * 16 + c * 4) + local w = readf32(m.weights, src * 16 + c * 4) + if j >= 0 and j < nb and w > 0 and w == w then + js[c + 1], ws[c + 1] = j, w + sum += w + end + end + for c = 0, 3 do + buffer.writeu16(jo.data, (v * 4 + c) * 2, js[c + 1]) + writef32(we.data, (v * 4 + c) * 4, if sum > 0 then ws[c + 1] / sum else (if c == 0 then 1 else 0)) + end + if sd and deform then + buffer.writeu8(deform.data, v, buffer.readu8(m.deform, src)) + if m.sdef then + for q = 0, 2 do + for c = 0, 2 do + local x = readf32(m.sdef, src * 36 + q * 12 + c * 4) + writef32(sd[q + 1].data, (v * 3 + c) * 4, if c == 2 then -x else x) + end + end + end + end + end + local prim: Types.Primitive = { attributes = attrs, indices = ind, mode = "triangles" } + if #morphs > 0 then + local targets: { { [string]: Types.Accessor } } = {} + for k, mo in morphs do + local d = S.accessor(nil, "f32", 3, nv) + for o, src in mo.vertices do + local v = map[src] + if v then + for c = 0, 2 do + local x = readf32(mo.deltas, ((o - 1) * 3 + c) * 4) + writef32(d.data, (v * 3 + c) * 4, if c == 2 then -x else x) + end + end + end + targets[k] = { POSITION = d } + end + prim.targets = targets + end + return prim +end + +function Build.scene(m: any, opts: any): (any, ...any) + local scene = S.new() + scene.meta.up = "y" + local fetch = fetcher(opts) + for i, path in m.textures do + local uri = string.gsub(path, "\\", "/") + local tex: Types.Texture = { name = path, uri = uri } + local data = fetch(path) + if data then + tex.data = data + end + local ext = string.match(uri, "%.(%w+)$") + tex.mime = if ext then MIME[string.lower(ext)] else nil + scene.textures[i] = tex + end + for i, mat in m.materials do + scene.materials[i] = material(m, mat) + end + + local vmorphs, names, others = {}, {}, {} + local wantMorphs = not (opts and opts.morphs == false) + for _, mo in m.morphs do + if mo.type == 1 and wantMorphs then + table.insert(vmorphs, mo) + table.insert(names, mo.name) + elseif mo.type ~= 1 then + table.insert(others, { name = mo.name, nameEn = mo.nameEn, panel = mo.panel, type = MORPH[mo.type] or mo.type, offsets = mo.offsets }) + end + end + local maxBytes = if opts and opts.maxBytes then opts.maxBytes else 2 ^ 28 + if #vmorphs * m.vertexCount * 12 > maxBytes then + return nil, string.format("limit: %d vertex morphs on %d vertices (maxBytes; morphs = false skips them)", #vmorphs, m.vertexCount), "limit" + end + local sdef = false + for v = 0, m.vertexCount - 1 do + local k = buffer.readu8(m.deform, v) + if k == 3 or k == 4 then + sdef = true + break + end + end + local mesh: Types.Mesh = { name = m.name, primitives = {} } + local first = 0 + for i, mat in m.materials do + local n = mat.count + if type(n) ~= "number" or n < 0 or n % 3 ~= 0 or first + n > m.indexCount then + return nil, string.format("material %d: %s face indices past the face list", i, tostring(n)) + end + local prim = primitive(m, first, n, vmorphs, sdef) + prim.material = i + table.insert(mesh.primitives, prim) + first += n + end + if first < m.indexCount then + table.insert(mesh.primitives, primitive(m, first, m.indexCount - first, vmorphs, sdef)) + end + mesh.extras = { targetNames = if #names > 0 then names else nil, pmx = if #others > 0 then { morphs = others } else nil } + if #vmorphs > 0 then + mesh.weights = table.create(#vmorphs, 0) + end + scene.meshes[1] = mesh + + scene.nodes[1] = { name = m.name, children = { 2 } } + scene.nodes[2] = { name = m.name .. "_mesh", children = {}, mesh = 1 } + scene.roots[1] = 1 + local bones = m.bones + local nb = #bones + if nb > 0 then + local par = parents(bones) + local world: { { number } } = {} + for i, b in bones do + world[i] = lh(b.pos) or { 0, 0, 0 } + end + local ibm = S.accessor(nil, "f32", 16, nb) + ibm.matrix = true + local joints: { number } = {} + for i, b in bones do + local w, p = world[i], par[i] + local t = if p ~= 0 then { w[1] - world[p][1], w[2] - world[p][2], w[3] - world[p][3] } else { w[1], w[2], w[3] } + local x: { [string]: any } = { nameEn = b.nameEn, index = i - 1, layer = b.layer, flags = b.flags, position = b.pos } + x.tail, x.inherit, x.axis, x.localX, x.localZ, x.externalKey, x.ik = b.tail, b.inherit, b.axis, b.localX, b.localZ, b.externalKey, b.ik + scene.nodes[2 + i] = { name = b.name, children = {}, translation = t, extras = { pmx = x } } + joints[i] = 2 + i + for c = 0, 15 do + local val = if c % 5 == 0 then 1 elseif c >= 12 and c <= 14 then -w[c - 11] else 0 + writef32(ibm.data, ((i - 1) * 16 + c) * 4, val) + end + end + for i = 1, nb do + local p = par[i] + table.insert(scene.nodes[if p ~= 0 then 2 + p else 1].children, 2 + i) + end + scene.skins[1] = { name = m.name, joints = joints, inverseBindMatrices = ibm } + scene.nodes[2].skin = 1 + end + scene.meta.source = { + format = "pmx", version = m.version, encoding = m.encoding, name = m.name, nameEn = m.nameEn, comment = m.comment, + commentEn = m.commentEn, additionalUV = #m.uva, displayFrames = m.frames, rigidBodies = m.rigidBodies, joints = m.jointsList, + softBodies = m.softBodies, toonTextures = m.toonTextures, + } + return scene +end + +return Build +end +__FILES["model/pmx/Pmd"] = function() + +-- model/pmx/Pmd: PMD 1.0, from the MMD community layout notes (MMDAgent / mmd_tools); no third-party code. Names are +-- Shift-JIS: kept when ASCII, else the English name, else the raw bytes (`nameSjis`). Never throws. +local Bytes = __include("core/Bytes") + +local Pmd = {} + +local function vec(r: Bytes.Reader, n: number): { number } + local v: { number } = {} + for i = 1, n do + v[i] = r:f32le() + end + return v +end + +local function ascii(s: string): boolean + return not string.find(s, "[\128-\255]") +end + +local function counted(r: Bytes.Reader, n: number, size: number, what: string): (boolean, ...any) + if n * size > r.limit - r.pos then + return false, string.format("%d %s do not fit in the file", n, what) + end + return true +end + +function Pmd.parse(r: Bytes.Reader, opts: { maxVertices: number? }?): (any, ...any) + if not r:match("Pmd") then + return nil, "not a PMD file" + end + local version = r:f32le() + if version ~= 1 then + return nil, "unsupported: PMD version " .. tostring(version), "unsupported" + end + local m: { [string]: any } = { version = 1.0, encoding = "shift_jis", uva = {}, sdef = nil } + m.nameSjis, m.commentSjis = r:fixed(20), r:fixed(256) + local buf = r.buf + + -- vertices: 38 bytes each + local nv = r:u32le() + if r.err then + return nil, "truncated", "truncated" + end + local ok, e = counted(r, nv, 38, "vertices") + if not ok then + return nil, e, "truncated" + end + local maxV = if opts and opts.maxVertices then opts.maxVertices else 2 ^ 24 + if nv > maxV then + return nil, string.format("limit: %d vertices (maxVertices %d)", nv, maxV), "limit" + end + local pos, nrm, uv = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8) + local deform, joints, weights, edge = buffer.create(nv), buffer.create(nv * 16), buffer.create(nv * 16), buffer.create(nv * 4) + for v = 0, nv - 1 do + local p = r.pos + v * 38 + buffer.copy(pos, v * 12, buf, p, 12) + buffer.copy(nrm, v * 12, buf, p + 12, 12) + buffer.copy(uv, v * 8, buf, p + 24, 8) + local b0, b1 = buffer.readu16(buf, p + 32), buffer.readu16(buf, p + 34) + local w = math.clamp(buffer.readu8(buf, p + 36), 0, 100) / 100 + local single = b0 == b1 or w == 1 + buffer.writeu8(deform, v, if single then 0 else 1) + buffer.writei32(joints, v * 16, b0) + buffer.writei32(joints, v * 16 + 4, if single then -1 else b1) + buffer.writei32(joints, v * 16 + 8, -1) + buffer.writei32(joints, v * 16 + 12, -1) + buffer.writef32(weights, v * 16, if single then 1 else w) + buffer.writef32(weights, v * 16 + 4, if single then 0 else 1 - w) + buffer.writef32(edge, v * 4, if buffer.readu8(buf, p + 37) ~= 0 then 0 else 1) + end + r.pos += nv * 38 + m.vertexCount, m.positions, m.normals, m.uvs, m.deform, m.joints, m.weights, m.edge = nv, pos, nrm, uv, deform, joints, weights, edge + + -- faces: u16 indices + local ni = r:u32le() + ok, e = counted(r, ni, 2, "face indices") + if r.err or not ok then + return nil, e or "truncated", "truncated" + end + if ni % 3 ~= 0 then + return nil, ni .. " face indices (not triangles)" + end + local ind = buffer.create(ni * 4) + for i = 0, ni - 1 do + local x = buffer.readu16(buf, r.pos + i * 2) + if x >= nv then + return nil, string.format("face index %d out of range (%d vertices)", x, nv) + end + buffer.writeu32(ind, i * 4, x) + end + r.pos += ni * 2 + m.indexCount, m.indices = ni, ind + + -- materials: 70 bytes each + local nm = r:u32le() + ok, e = counted(r, nm, 70, "materials") + if r.err or not ok then + return nil, e or "truncated", "truncated" + end + m.textures = {} + local texIndex: { [string]: number } = {} + local function tex(name: string): number + if name == "" then + return -1 + end + local i = texIndex[name] + if not i then + table.insert(m.textures, name) + i = #m.textures - 1 + texIndex[name] = i + end + return i + end + m.materials = table.create(nm) + local toonIdx = {} + for i = 1, nm do + local mat: { [string]: any } = { name = "material" .. (i - 1), nameEn = "material" .. (i - 1) } + local d = vec(r, 4) + mat.diffuse, mat.power, mat.specular, mat.ambient = d, r:f32le(), vec(r, 3), vec(r, 3) + local toon, edgeFlag = r:u8(), r:u8() + mat.count = r:u32le() + local file = r:fixed(20) + mat.flags = (if edgeFlag ~= 0 then 0x10 else 0) + (if d[4] < 1 then 0x01 else 0) + mat.edgeColor, mat.edgeSize, mat.memo = { 0, 0, 0, 1 }, 1, "" + mat.texture, mat.sphere, mat.sphereMode = -1, -1, 0 + for part in string.gmatch(file, "[^*]+") do + local ext = string.lower(string.match(part, "%.(%w+)$") or "") + if ext == "sph" or ext == "spa" then + mat.sphere, mat.sphereMode = tex(part), if ext == "sph" then 1 else 2 + else + mat.texture = tex(part) + end + end + toonIdx[i] = toon + m.materials[i] = mat + end + + -- bones: 39 bytes each + local nb = r:u16le() + ok, e = counted(r, nb, 39, "bones") + if r.err or not ok then + return nil, e or "truncated", "truncated" + end + m.bones = table.create(nb) + for i = 1, nb do + local b: { [string]: any } = { nameSjis = r:fixed(20) } + local parent, tail, kind, ikParent = r:u16le(), r:u16le(), r:u8(), r:u16le() + b.pos = vec(r, 3) + b.parent = if parent == 0xFFFF then -1 else parent + b.tail = if tail ~= 0 and tail ~= 0xFFFF then tail else { 0, 0, 0 } + b.layer, b.pmdType, b.ikParent = 0, kind, ikParent + -- PMX-style flags: tail index, rotatable, translatable (type 1), visible (not type 7), enabled + b.flags = (if type(b.tail) == "number" then 0x1 else 0) + 0x2 + (if kind == 1 then 0x4 else 0) + (if kind ~= 7 then 0x8 else 0) + 0x10 + m.bones[i] = b + end + + local nik = r:u16le() + for _ = 1, nik do + local bone, target, len, loops, limit = r:u16le(), r:u16le(), r:u8(), r:u16le(), r:f32le() + local links = table.create(len) + for l = 1, len do + links[l] = { bone = r:u16le() } + end + if r.err then + return nil, "truncated", "truncated" + end + local b = m.bones[bone + 1] + if b then + b.flags = bit32.bor(b.flags, 0x20) + -- PMD's limit is in units of 4 radians (PMX stores radians) + b.ik = { target = target, loops = loops, limit = limit * 4, links = links } + end + end + + -- skins: the base (absolute positions of every vertex a morph moves), then morphs relative to it + local ns = r:u16le() + if r.err then + return nil, "truncated", "truncated" + end + m.morphs = {} + local base: { number } = {} + for s = 1, ns do + local name = r:fixed(20) + local n, panel = r:u32le(), r:u8() + ok, e = counted(r, n, 16, "skin vertices") + if r.err or not ok then + return nil, e or "truncated", "truncated" + end + if s == 1 and panel == 0 then + for o = 1, n do + base[o] = r:u32le() + r:skip(12) + end + else + local vi, deltas = table.create(n), buffer.create(n * 12) + for o = 1, n do + local k = r:u32le() + local v = base[k + 1] + if not v or v >= nv then + return nil, string.format("skin %d: base vertex %d out of range", s - 1, k) + end + vi[o] = v + buffer.copy(deltas, (o - 1) * 12, buf, r.pos, 12) + r:skip(12) + end + table.insert(m.morphs, { nameSjis = name, panel = panel, type = 1, vertices = vi, deltas = deltas }) + end + end + + -- display lists (skin list, bone group names, bone groups) + local nsd = r:u8() + r:skip(nsd * 2) + local ng = r:u8() + local groups: { { [string]: any } } = {} + for g = 1, ng do + groups[g] = { nameSjis = r:fixed(50), special = false, items = {} } + end + local nbd = r:u32le() + ok, e = counted(r, nbd, 3, "bone display entries") + if r.err or not ok then + return nil, e or "truncated", "truncated" + end + for _ = 1, nbd do + local bone, g = r:u16le(), r:u8() + local grp = groups[g] + if grp then + table.insert(grp.items, { bone = bone }) + end + end + m.frames = groups + + -- optional: English names, toon textures, physics + local function name(t: { [string]: any }, en: string?) + local raw = t.nameSjis or "" + t.nameEn = en + t.name = if ascii(raw) then raw elseif en and en ~= "" then en else raw + if ascii(raw) then + t.nameSjis = nil + end + end + local en: any = {} + if r.limit - r.pos >= 1 and r:u8() == 1 then + en.name, en.comment = r:fixed(20), r:fixed(256) + en.bones = table.create(nb) + for i = 1, nb do + en.bones[i] = r:fixed(20) + end + en.morphs = {} + for i = 1, #m.morphs do + en.morphs[i] = r:fixed(20) + end + en.groups = {} + for i = 1, ng do + en.groups[i] = r:fixed(50) + end + end + local model = { nameSjis = m.nameSjis } + name(model, en.name) + m.name, m.nameEn = model.name, en.name + m.comment, m.commentEn = if ascii(m.commentSjis) then m.commentSjis else (en.comment or m.commentSjis), en.comment + if ascii(m.nameSjis) then + m.nameSjis = nil + end + for i, b in m.bones do + name(b, en.bones and en.bones[i]) + end + for i, mo in m.morphs do + name(mo, en.morphs and en.morphs[i]) + end + for i, g in groups do + name(g, en.groups and en.groups[i]) + end + local toons: { string } = {} + for i = 1, 10 do + toons[i] = string.format("toon%02d.bmp", i) + end + if r.limit - r.pos >= 1000 then + for i = 1, 10 do + toons[i] = r:fixed(100) + end + end + m.toonTextures = toons + for i, mat in m.materials do + local t = toonIdx[i] + if t < 10 then + if toons[t + 1] == string.format("toon%02d.bmp", t + 1) then + mat.toonShared = t + else + mat.toon = tex(toons[t + 1]) + end + else + mat.toon = -1 + end + end + m.rigidBodies, m.jointsList = {}, {} + if r.limit - r.pos >= 4 then + local nr = r:u32le() + ok, e = counted(r, nr, 83, "rigid bodies") + if not ok then + return nil, e, "truncated" + end + for i = 1, nr do + local b: { [string]: any } = { name = r:fixed(20), bone = r:u16le(), group = r:u8(), mask = r:u16le(), shape = r:u8() } + b.size, b.position, b.rotation = vec(r, 3), vec(r, 3), vec(r, 3) + b.mass, b.linearDamping, b.angularDamping, b.restitution, b.friction = r:f32le(), r:f32le(), r:f32le(), r:f32le(), r:f32le() + b.mode = r:u8() + if b.bone == 0xFFFF then + b.bone = -1 + end + m.rigidBodies[i] = b + end + end + if r.limit - r.pos >= 4 then + local nj = r:u32le() + ok, e = counted(r, nj, 124, "joints") + if not ok then + return nil, e, "truncated" + end + for i = 1, nj do + local j: { [string]: any } = { name = r:fixed(20), type = 0, a = r:u32le(), b = r:u32le() } + j.position, j.rotation = vec(r, 3), vec(r, 3) + j.positionMin, j.positionMax, j.rotationMin, j.rotationMax = vec(r, 3), vec(r, 3), vec(r, 3), vec(r, 3) + j.positionSpring, j.rotationSpring = vec(r, 3), vec(r, 3) + m.jointsList[i] = j + end + end + if r.err then + return nil, "truncated", "truncated" + end + return m +end + +return Pmd +end +__FILES["model/pmx/Read"] = function() + +-- model/pmx/Read: PMX 2.0 / 2.1, from the specification notes that ship with PmxEditor; values as in the file +-- (left-handed, 0-based indices); 2.1 soft bodies are counted, not parsed. Never throws. +local Bytes = __include("core/Bytes") +local Text = __include("codecs/text/Text") + +local Read = {} + +type Model = { [string]: any } + +local readu8, readu16, readi32 = buffer.readu8, buffer.readu16, buffer.readi32 + +-- index readers: vertex indices are unsigned for sizes 1 / 2, every other index is signed (-1 = none) +local function indexReader(r: Bytes.Reader, size: number, vertex: boolean): () -> number + if size == 1 then + return if vertex then function() return r:u8() end else function() return r:i8() end + elseif size == 2 then + return if vertex then function() return r:u16le() end else function() return r:i16le() end + end + return function() return r:i32le() end +end + +local function vec(r: Bytes.Reader, n: number): { number } + local v: { number } = {} + for i = 1, n do + v[i] = r:f32le() + end + return v +end + +-- a count field: i32 >= 0 +local function count(r: Bytes.Reader, minSize: number, what: string): (any, ...any) + local n = r:i32le() + if r.err then + return nil, "truncated", "truncated" + end + if n < 0 then + return nil, "negative " .. what .. " count" + end + if n * minSize > r.limit - r.pos then + return nil, string.format("%d %s do not fit in the file", n, what), "truncated" + end + return n +end + +function Read.parse(r: Bytes.Reader, opts: { maxVertices: number? }?): (any, ...any) + if not r:match("PMX ") then + return nil, "not a PMX file" + end + local version = r:f32le() + local nglobals = r:u8() + if r.err then + return nil, "truncated", "truncated" + end + if version < 1.95 or version > 2.15 then + return nil, "unsupported: PMX version " .. tostring(version), "unsupported" + end + version = if version > 2.05 then 2.1 else 2.0 + if nglobals < 8 then + return nil, "only " .. nglobals .. " header globals" + end + local g: { number } = {} + for i = 1, nglobals do + g[i] = r:u8() + end + local utf8 = g[1] == 1 + if g[1] > 1 then + return nil, "unknown text encoding " .. g[1] + end + local uva = g[2] + if uva > 4 then + return nil, uva .. " additional UVs (at most 4)" + end + for i = 3, 8 do + if g[i] ~= 1 and g[i] ~= 2 and g[i] ~= 4 then + return nil, "bad index size " .. g[i] + end + end + local vsize, tsize, msize, bsize, morsize, rsize = g[3], g[4], g[5], g[6], g[7], g[8] + local buf = r.buf + local function text(): string + local n = r:i32le() + if r.err or n < 0 or n > r.limit - r.pos then + r:need(r.limit - r.pos + 1) + return "" + end + local p = r.pos + r.pos += n + if utf8 then + return buffer.readstring(buf, p, n) + end + return Text.utf16(buf, p, n) + end + local vidx = indexReader(r, vsize, true) + local tidx = indexReader(r, tsize, false) + local midx = indexReader(r, msize, false) + local bidx = indexReader(r, bsize, false) + local moidx = indexReader(r, morsize, false) + local ridx = indexReader(r, rsize, false) + local m: Model = { version = version, encoding = if utf8 then "utf8" else "utf16", additionalUV = uva, indexSizes = { vsize, tsize, msize, bsize, morsize, rsize } } + m.name, m.nameEn, m.comment, m.commentEn = text(), text(), text(), text() + if r.err then + return nil, "truncated", "truncated" + end + + -- vertices: position, normal, uv, additional uvs, deform, edge scale + local nv, e, k = count(r, 8 * 4 + 1 + bsize + 4 + uva * 16, "vertices") + if not nv then + return nil, e, k + end + local maxV = if opts and opts.maxVertices then opts.maxVertices else 2 ^ 24 + if nv > maxV then + return nil, string.format("limit: %d vertices (maxVertices %d)", nv :: number, maxV), "limit" + end + local pos, nrm, uv = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8) + local uvas = {} + for a = 1, uva do + uvas[a] = buffer.create(nv * 16) + end + local deform, joints, weights = buffer.create(nv), buffer.create(nv * 16), buffer.create(nv * 16) + local edge = buffer.create(nv * 4) + local sdef: buffer? = nil + local writef32, writei32 = buffer.writef32, buffer.writei32 + for v = 0, nv - 1 do + if not r:need(32 + uva * 16 + 1) then + return nil, "truncated", "truncated" + end + local p = r.pos + for c = 0, 2 do + writef32(pos, (v * 3 + c) * 4, buffer.readf32(buf, p + c * 4)) + writef32(nrm, (v * 3 + c) * 4, buffer.readf32(buf, p + 12 + c * 4)) + end + writef32(uv, v * 8, buffer.readf32(buf, p + 24)) + writef32(uv, v * 8 + 4, buffer.readf32(buf, p + 28)) + p += 32 + for a = 1, uva do + buffer.copy(uvas[a], v * 16, buf, p, 16) + p += 16 + end + local kind = readu8(buf, p) + r.pos = p + 1 + buffer.writeu8(deform, v, kind) + local o = v * 16 + if kind == 0 then + writei32(joints, o, bidx()) + writei32(joints, o + 4, -1) + writei32(joints, o + 8, -1) + writei32(joints, o + 12, -1) + writef32(weights, o, 1) + elseif kind == 1 or kind == 3 then + writei32(joints, o, bidx()) + writei32(joints, o + 4, bidx()) + writei32(joints, o + 8, -1) + writei32(joints, o + 12, -1) + local w = r:f32le() + writef32(weights, o, w) + writef32(weights, o + 4, 1 - w) + if kind == 3 then + local sd = sdef or buffer.create(nv * 36) + sdef = sd + for c = 0, 8 do + writef32(sd, v * 36 + c * 4, r:f32le()) + end + end + elseif kind == 2 or kind == 4 then + for c = 0, 3 do + writei32(joints, o + c * 4, bidx()) + end + for c = 0, 3 do + writef32(weights, o + c * 4, r:f32le()) + end + else + return nil, "unknown vertex deform type " .. kind + end + writef32(edge, v * 4, r:f32le()) + if r.err then + return nil, "truncated", "truncated" + end + end + m.vertexCount, m.positions, m.normals, m.uvs, m.uva = nv, pos, nrm, uv, uvas + m.deform, m.joints, m.weights, m.sdef, m.edge = deform, joints, weights, sdef, edge + + -- faces: vertex index triples + local ni + ni, e, k = count(r, vsize, "face indices") + if not ni then + return nil, e, k + end + if ni % 3 ~= 0 then + return nil, ni .. " face indices (not triangles)" + end + local ind = buffer.create(ni * 4) + local p = r.pos + for i = 0, ni - 1 do + local x = if vsize == 1 then readu8(buf, p + i) elseif vsize == 2 then readu16(buf, p + i * 2) else readi32(buf, p + i * 4) + if x < 0 or x >= nv then + return nil, string.format("face index %d out of range (%d vertices)", x, nv :: number), nil + end + buffer.writeu32(ind, i * 4, x) + end + r.pos = p + ni * vsize + m.indexCount, m.indices = ni, ind + + local nt + nt, e, k = count(r, 4, "textures") + if not nt then + return nil, e, k + end + m.textures = table.create(nt) + for i = 1, nt do + m.textures[i] = text() + end + + local nm + nm, e, k = count(r, 8 + 16 + 12 + 4 + 12 + 1 + 16 + 4 + 2 * tsize + 2 + 1 + 4 + 4, "materials") + if not nm then + return nil, e, k + end + m.materials = table.create(nm) + for i = 1, nm do + local mat: { [string]: any } = { name = text(), nameEn = text() } + mat.diffuse, mat.specular, mat.power, mat.ambient = vec(r, 4), vec(r, 3), r:f32le(), vec(r, 3) + mat.flags = r:u8() + mat.edgeColor, mat.edgeSize = vec(r, 4), r:f32le() + mat.texture, mat.sphere, mat.sphereMode = tidx(), tidx(), r:u8() + if r:u8() == 1 then + mat.toonShared = r:u8() + else + mat.toon = tidx() + end + mat.memo, mat.count = text(), r:i32le() + if r.err then + return nil, "truncated", "truncated" + end + m.materials[i] = mat + end + + local nb + nb, e, k = count(r, 8 + 12 + bsize + 4 + 2 + bsize, "bones") + if not nb then + return nil, e, k + end + m.bones = table.create(nb) + for i = 1, nb do + local b: { [string]: any } = { name = text(), nameEn = text() } + b.pos, b.parent, b.layer = vec(r, 3), bidx(), r:i32le() + local fl = r:u16le() + b.flags = fl + b.tail = if bit32.btest(fl, 0x1) then bidx() else vec(r, 3) + if bit32.btest(fl, 0x300) then + b.inherit = { bone = bidx(), influence = r:f32le(), rotation = bit32.btest(fl, 0x100), translation = bit32.btest(fl, 0x200) } + end + if bit32.btest(fl, 0x400) then + b.axis = vec(r, 3) + end + if bit32.btest(fl, 0x800) then + b.localX, b.localZ = vec(r, 3), vec(r, 3) + end + if bit32.btest(fl, 0x2000) then + b.externalKey = r:i32le() + end + if bit32.btest(fl, 0x20) then + local ik: { [string]: any } = { target = bidx(), loops = r:i32le(), limit = r:f32le() } + local nl + nl, e, k = count(r, bsize + 1, "IK links") + if not nl then + return nil, e, k + end + ik.links = table.create(nl) + for l = 1, nl do + local link: { [string]: any } = { bone = bidx() } + if r:u8() == 1 then + link.min, link.max = vec(r, 3), vec(r, 3) + end + ik.links[l] = link + end + b.ik = ik + end + if r.err then + return nil, "truncated", "truncated" + end + m.bones[i] = b + end + + local nmo + nmo, e, k = count(r, 8 + 2 + 4, "morphs") + if not nmo then + return nil, e, k + end + local SIZE = { [0] = morsize + 4, vsize + 12, bsize + 28, vsize + 16, vsize + 16, vsize + 16, vsize + 16, vsize + 16, msize + 1 + 112, morsize + 4, rsize + 25 } + m.morphs = table.create(nmo) + for i = 1, nmo do + local mo: { [string]: any } = { name = text(), nameEn = text(), panel = r:u8(), type = r:u8() } + local t = mo.type + local size = SIZE[t] + if not size then + return nil, "unknown morph type " .. t + end + local no + no, e, k = count(r, size, "morph offsets") + if not no then + return nil, e, k + end + if t == 1 then + -- vertex morphs: packed (index list + deltas) + local vi, d = table.create(no), buffer.create(no * 12) + for o = 1, no do + local x = vidx() + vi[o] = x + for c = 0, 2 do + writef32(d, ((o - 1) * 3 + c) * 4, r:f32le()) + end + end + mo.vertices, mo.deltas = vi, d + else + local offs = table.create(no) + for o = 1, no do + local off: { [string]: any } + if t == 0 or t == 9 then + off = { morph = moidx(), weight = r:f32le() } + elseif t == 2 then + off = { bone = bidx(), translation = vec(r, 3), rotation = vec(r, 4) } + elseif t <= 7 then + off = { vertex = vidx(), value = vec(r, 4) } + elseif t == 8 then + off = { material = midx(), operation = r:u8() } + off.diffuse, off.specular, off.specularPower, off.ambient = vec(r, 4), vec(r, 3), r:f32le(), vec(r, 3) + off.edgeColor, off.edgeSize, off.textureTint, off.sphereTint, off.toonTint = vec(r, 4), r:f32le(), vec(r, 4), vec(r, 4), vec(r, 4) + else + off = { rigidBody = ridx(), localFrame = r:u8() == 1, velocity = vec(r, 3), torque = vec(r, 3) } + end + offs[o] = off + end + mo.offsets = offs + end + if r.err then + return nil, "truncated", "truncated" + end + m.morphs[i] = mo + end + + -- display frames, rigid bodies, joints: optional at the end (some tools stop after the morphs) + m.frames, m.rigidBodies, m.jointsList = {}, {}, {} + if r.limit - r.pos >= 4 then + local nf + nf, e, k = count(r, 8 + 1 + 4, "display frames") + if not nf then + return nil, e, k + end + for i = 1, nf do + local f: { [string]: any } = { name = text(), nameEn = text(), special = r:u8() == 1 } + local nitem + nitem, e, k = count(r, 1 + math.min(bsize, morsize), "display frame items") + if not nitem then + return nil, e, k + end + f.items = table.create(nitem) + for q = 1, nitem do + local kind = r:u8() + f.items[q] = if kind == 0 then { bone = bidx() } else { morph = moidx() } + end + m.frames[i] = f + end + end + if r.limit - r.pos >= 4 then + local nr + nr, e, k = count(r, 8 + bsize + 4 + 36 + 20 + 1, "rigid bodies") + if not nr then + return nil, e, k + end + for i = 1, nr do + local b: { [string]: any } = { name = text(), nameEn = text(), bone = bidx(), group = r:u8(), mask = r:u16le(), shape = r:u8() } + b.size, b.position, b.rotation = vec(r, 3), vec(r, 3), vec(r, 3) + b.mass, b.linearDamping, b.angularDamping, b.restitution, b.friction = r:f32le(), r:f32le(), r:f32le(), r:f32le(), r:f32le() + b.mode = r:u8() + m.rigidBodies[i] = b + end + end + if r.limit - r.pos >= 4 then + local nj + nj, e, k = count(r, 8 + 1 + 2 * rsize + 96, "joints") + if not nj then + return nil, e, k + end + for i = 1, nj do + local j: { [string]: any } = { name = text(), nameEn = text(), type = r:u8(), a = ridx(), b = ridx() } + j.position, j.rotation = vec(r, 3), vec(r, 3) + j.positionMin, j.positionMax, j.rotationMin, j.rotationMax = vec(r, 3), vec(r, 3), vec(r, 3), vec(r, 3) + j.positionSpring, j.rotationSpring = vec(r, 3), vec(r, 3) + m.jointsList[i] = j + end + end + if version >= 2.1 and r.limit - r.pos >= 4 then + m.softBodies = r:i32le() + end + if r.err then + return nil, "truncated", "truncated" + end + return m +end + +return Read +end +__FILES["model/qb"] = function() + +-- model/qb: Qubicle Binary (.qb 1.1.0.0, minddesk.com "Qubicle Binary"), read + write. Supports: RGBA / BGRA, left- or +-- right-handed z, plain or RLE matrices (CODEFLAG 2 / NEXTSLICEFLAG 6 per z slice), the alpha visibility mask, named +-- matrices with a position. Not supported: Qubicle Exchange (.qbt / .qbcl). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") + +-- ------------------------------------------------------------------------------------------------ contract +local Qb = { + name = "qb", + category = "model", + extensions = { "qb" }, + mime = { "model/x-qubicle" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, voxels = true, truecolor = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + maxCells: number?, -- default 2^27 +} +type EncodeOptions = { + compressed: boolean?, -- default: the source's, else true + colorFormat: ("rgba" | "bgra")?, -- default: the source's, else "rgba" + rightHanded: boolean?, -- default: the source's, else true + visibilityMask: boolean?, -- default: the source's, else false +} + +-- ------------------------------------------------------------------------------------------------ constants +local CODEFLAG, NEXTSLICEFLAG = 2, 6 +-- visibility mask bits (alpha): 1 = filled, then the sides that are not hidden by a neighbour +local LEFT, RIGHT, TOP, BOTTOM, FRONT, BACK = 2, 4, 8, 16, 32, 64 + +-- ------------------------------------------------------------------------------------------------ sniff +function Qb.sniff(r: Bytes.Reader): number + if r:remaining() < 24 or r:peek(4) ~= "\1\1\0\0" then + return 0 + end + local b, p = r.buf, r.pos + local fmt, z, comp, mask = buffer.readu32(b, p + 4), buffer.readu32(b, p + 8), buffer.readu32(b, p + 12), buffer.readu32(b, p + 16) + if fmt > 1 or z > 1 or comp > 1 or mask > 1 then + return 0 + end + return 0.9 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function indexed(v: Types.Voxels, colors: buffer, n: number) + local count: { [number]: number } = {} + for i = 0, n - 1 do + local c = buffer.readu32(colors, i * 4) + if c >= 0x1000000 then -- alpha > 0: filled + local rgb = c % 0x1000000 + local k = count[rgb] + if k == nil then + count[rgb] = 1 + else + count[rgb] = k + 1 + end + end + end + local order = {} + for rgb in count do + table.insert(order, rgb) + end + table.sort(order, function(a: number, b: number): boolean + if count[a] ~= count[b] then + return count[a] > count[b] + end + return a < b + end) + local slot: { [number]: number } = {} + for i = 1, math.min(255, #order) do + local rgb = order[i] + slot[rgb] = i + v.palette[i] = { rgb % 256, (rgb // 256) % 256, rgb // 65536, 255 } + end + for i = 256, #order do + local rgb = order[i] + local r, g, b = rgb % 256, (rgb // 256) % 256, rgb // 65536 + local best, bd = 1, math.huge + for k = 1, 255 do + local p = v.palette[k] + local d = (p[1] - r) ^ 2 + (p[2] - g) ^ 2 + (p[3] - b) ^ 2 + if d < bd then + best, bd = k, d + end + end + slot[rgb] = best + end + for i = 0, n - 1 do + local c = buffer.readu32(colors, i * 4) + buffer.writeu8(v.data, i, if c >= 0x1000000 then slot[c % 0x1000000] else 0) + end +end + +function Qb.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local o: DecodeOptions = opts or {} + local maxCells = o.maxCells or 2 ^ 27 + local ver = r:string(4) + local fmt, zAxis, compressed, mask, count = r:u32le(), r:u32le(), r:u32le(), r:u32le(), r:u32le() + if r.err then + return nil, r.err + end + if ver ~= "\1\1\0\0" then + return nil, Err.new(Err.CORRUPT, "not a Qubicle Binary file (version 1.1.0.0)", 0) + end + if fmt > 1 or zAxis > 1 or compressed > 1 or mask > 1 then + return nil, Err.new(Err.CORRUPT, "bad header flags", 4) + end + if count > r:remaining() // 25 then + return nil, Err.new(Err.TRUNCATED, count .. " matrices cannot fit", 20) + end + local scene = Types.Scene.new() + local grids: { Types.Voxels } = {} + scene.voxels = grids + local total = 0 + local bgra = fmt == 1 + for m = 1, count do + local at = r:tell() + local nameLen = r:u8() + local name = r:string(nameLen) + local sx, sy, sz = r:u32le(), r:u32le(), r:u32le() + local px, py, pz = r:i32le(), r:i32le(), r:i32le() + if r.err then + return nil, r.err + end + if sx * sy * sz + total > maxCells then + return nil, Err.new(Err.LIMIT, string.format("matrix %d: %d x %d x %d cells is over maxCells", m, sx, sy, sz), at) + end + local n = sx * sy * sz + total += n + local colors = buffer.create(n * 4) + local b = r.buf + local function put(x: number, y: number, z: number, c: number) + if bgra then -- b, g, r, a -> r, g, b, a + c = (c // 65536) % 256 + (c // 256) % 256 * 256 + c % 256 * 65536 + (c // 16777216) * 16777216 + end + if c < 0x1000000 then + c = 0 -- alpha 0: empty + end + local zz = if zAxis == 0 then sz - 1 - z else z + buffer.writeu32(colors, (x + sx * (y + sy * zz)) * 4, c) + end + if compressed == 0 then + if not r:need(n * 4) then + return nil, r.err + end + local p = r.pos + for z = 0, sz - 1 do + for y = 0, sy - 1 do + for x = 0, sx - 1 do + put(x, y, z, buffer.readu32(b, p)) + p += 4 + end + end + end + r.pos = p + else + local slice = sx * sy + for z = 0, sz - 1 do + local index = 0 + while true do + local d = r:u32le() + if r.err then + return nil, r.err + end + if d == NEXTSLICEFLAG then + break + elseif d == CODEFLAG then + local run, c = r:u32le(), r:u32le() + if r.err then + return nil, r.err + end + if index + run > slice then + return nil, Err.new(Err.CORRUPT, string.format("matrix %d: run past the slice", m), r:tell() - 8) + end + for _ = 1, run do + put(index % sx, index // sx, z, c) + index += 1 + end + else + if index >= slice then + return nil, Err.new(Err.CORRUPT, string.format("matrix %d: slice %d overflows", m, z), r:tell() - 4) + end + put(index % sx, index // sx, z, d) + index += 1 + end + end + end + end + local v = Types.Voxels.new(sx, sy, sz) + v.name = name + v.colors = colors + indexed(v, colors, n) + table.insert(grids, v) + local tz = if zAxis == 0 then 0 - (pz + sz) else pz + table.insert(scene.nodes, { name = name, children = {}, voxels = m, translation = { px, py, tz } }) + table.insert(scene.roots, #scene.nodes) + end + scene.meta.up = "y" + scene.meta.source = { + format = "qb", + colorFormat = if bgra then "bgra" else "rgba", + rightHanded = zAxis == 1, + compressed = compressed == 1, + visibilityMask = mask == 1, + } + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function cellColor(v: Types.Voxels, i: number): number + if v.colors then + return buffer.readu32(v.colors, i * 4) + end + local idx = buffer.readu8(v.data, i) + if idx == 0 then + return 0 + end + local p = v.palette[idx] or { 0, 0, 0, 255 } + return p[1] + p[2] * 256 + p[3] * 65536 + 255 * 16777216 +end + +function Qb.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local grids: { { v: Types.Voxels, name: string, pos: { number } } } = {} + local function add(v: any, name: string?, pos: { number }): string? + if type(v) ~= "table" or type(v.size) ~= "table" or type(v.data) ~= "buffer" then + return "expected Types.Voxels grids" + end + local n = v.size[1] * v.size[2] * v.size[3] + if buffer.len(v.data) < n or (v.colors and buffer.len(v.colors) < n * 4) then + return "voxel data shorter than its size" + end + local nm = name or v.name or ("matrix" .. (#grids + 1)) + if #nm > 255 then + return "matrix name longer than 255 bytes" + end + table.insert(grids, { v = v, name = nm, pos = pos }) + return nil + end + local src = if type(value) == "table" and type(value.meta) == "table" and type(value.meta.source) == "table" and value.meta.source.format == "qb" then value.meta.source else nil + if type(value) == "table" and value.kind == "voxels" then + local e = add(value, nil, { 0, 0, 0 }) + if e then + return nil, Err.new(Err.ARG, e) + end + elseif type(value) == "table" and value.kind == "scene" and type(value.voxels) == "table" then + local used: { [number]: boolean } = {} + local function walk(i: number, base: { number }, depth: number): string? + local node = value.nodes[i] + if type(node) ~= "table" or depth > 64 then + return nil + end + local t = node.translation or { 0, 0, 0 } + local p = { base[1] + (t[1] or 0), base[2] + (t[2] or 0), base[3] + (t[3] or 0) } + if node.voxels and value.voxels[node.voxels] then + used[node.voxels] = true + local e = add(value.voxels[node.voxels], node.name, p) + if e then + return e + end + end + for _, c in node.children or {} do + local e = walk(c, p, depth + 1) + if e then + return e + end + end + return nil + end + for _, root in value.roots or {} do + local e = walk(root, { 0, 0, 0 }, 0) + if e then + return nil, Err.new(Err.ARG, e) + end + end + for i, v in value.voxels do + if not used[i] then + local e = add(v, nil, { 0, 0, 0 }) + if e then + return nil, Err.new(Err.ARG, e) + end + end + end + else + return nil, Err.new(Err.ARG, "expected a Scene with voxels or a Types.Voxels") + end + local function pick(opt: any, key: string, default: any): any + if opt ~= nil then + return opt + elseif src and src[key] ~= nil then + return src[key] + end + return default + end + local compressed = pick(o.compressed, "compressed", true) + local bgra = pick(o.colorFormat, "colorFormat", "rgba") == "bgra" + local right = pick(o.rightHanded, "rightHanded", true) + local mask = pick(o.visibilityMask, "visibilityMask", false) + local keepMask = mask and src ~= nil and src.visibilityMask == true -- the source's alpha bytes already are masks + local w = Bytes.writer(1024) + w:string("\1\1\0\0") + w:u32le(if bgra then 1 else 0) + w:u32le(if right then 1 else 0) + w:u32le(if compressed then 1 else 0) + w:u32le(if mask then 1 else 0) + w:u32le(#grids) + for _, g in grids do + local v = g.v + local sx, sy, sz = v.size[1], v.size[2], v.size[3] + w:u8(#g.name) + w:string(g.name) + w:u32le(sx) + w:u32le(sy) + w:u32le(sz) + local px, py, pz = math.floor(g.pos[1] + 0.5), math.floor(g.pos[2] + 0.5), math.floor(g.pos[3] + 0.5) + w:u32le(px % 4294967296) + w:u32le(py % 4294967296) + w:u32le((if right then pz else -pz - sz) % 4294967296) + local function filled(x: number, y: number, z: number): boolean + if x < 0 or y < 0 or z < 0 or x >= sx or y >= sy or z >= sz then + return false + end + return cellColor(v, x + sx * (y + sy * z)) >= 0x1000000 + end + local function value(x: number, y: number, z: number): number + local zz = if right then z else sz - 1 - z + local c = cellColor(v, x + sx * (y + sy * zz)) + if c < 0x1000000 then + return 0 + end + local a = c // 16777216 + if mask and not keepMask then + a = 1 + if not filled(x - 1, y, zz) then a += LEFT end + if not filled(x + 1, y, zz) then a += RIGHT end + if not filled(x, y + 1, zz) then a += TOP end + if not filled(x, y - 1, zz) then a += BOTTOM end + if not filled(x, y, zz + 1) then a += FRONT end + if not filled(x, y, zz - 1) then a += BACK end + elseif not mask and src and src.visibilityMask then + a = 255 -- masks are not colours + end + local r, gg, b = c % 256, (c // 256) % 256, (c // 65536) % 256 + if bgra then + r, b = b, r + end + return r + gg * 256 + b * 65536 + a * 16777216 + end + for z = 0, sz - 1 do + if compressed then + local x, y = 0, 0 + local slice = sx * sy + local i = 0 + while i < slice do + x, y = i % sx, i // sx + local c = value(x, y, z) + local run = 1 + while i + run < slice and value((i + run) % sx, (i + run) // sx, z) == c do + run += 1 + end + if run > 2 then + w:u32le(CODEFLAG) + w:u32le(run) + w:u32le(c) + else + for _ = 1, run do + w:u32le(c) + end + end + i += run + end + w:u32le(NEXTSLICEFLAG) + else + for y = 0, sy - 1 do + for x = 0, sx - 1 do + w:u32le(value(x, y, z)) + end + end + end + end + end + return w:finish(), nil +end + +return Qb +end +end + + + + + + model_4 + --!optimize 2 +--!nocheck +-- rosetta chunk model_4 (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 19 modules (3 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["model/rbxm"] = function() + +-- model/rbxm: Roblox binary model / place (.rbxm / .rbxl, "<roblox!") to and from a codecs/model/Rbx RbxTree, from the +-- rbx-dom notes (docs/binary.md), checked against rojo 7.7 and lune 0.11. Supports: META, SSTR, INST, PROP, PRNT, END; +-- raw / LZ4 / Zstandard chunks; unknown chunks and types round-trip raw. Not supported: writing Zstandard chunks. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Md5 = __include("core/Md5") +local Lz4 = __include("codecs/compress/Lz4") +local Zstd = __include("codecs/compress/Zstd") +local Rbx = __include("codecs/model/Rbx") +local Binary = __include("codecs/model/Rbx/Binary") + +-- ------------------------------------------------------------------------------------------------ contract +local Rbxm = { + name = "rbxm", + category = "model", + extensions = { "rbxm", "rbxl" }, + mime = { "application/x-roblox-rbxm", "application/x-roblox-rbxl" }, + deps = { "core/Err", "core/Bytes", "core/Md5", "codecs/compress/Lz4", "codecs/compress/Zstd", "codecs/model/Rbx", "codecs/model/Rbx/Binary" }, + caps = { decode = true, encode = true, tree = true, compression = { "none", "lz4", "zstd" } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + maxBytes: number?, -- default 2^28 + maxInstances: number?, -- default 2^22 +} +type EncodeOptions = { + compression: ("lz4" | "none")?, -- default "lz4"; END is always raw + place: boolean?, -- default tree.place, or format = "rbxl" + format: string?, +} + +-- ------------------------------------------------------------------------------------------------ constants +local MAGIC = "<roblox!\137\255\13\10\26\10" +local readu8, readu32, readi32, readstring = buffer.readu8, buffer.readu32, buffer.readi32, buffer.readstring + +-- ------------------------------------------------------------------------------------------------ sniff +function Rbxm.sniff(r: Bytes.Reader): number + return if r:peek(14) == MAGIC then 1 else 0 +end + +-- an INST chunk that marks services makes a place +function Rbxm.variant(r: Bytes.Reader): string? + local b, p, e = r.buf, r.base + 32, r.limit + if r:peek(14) ~= MAGIC then + return nil + end + while p + 16 <= e do + local name, clen, ulen = readstring(b, p, 4), readu32(b, p + 4), readu32(b, p + 8) + local size = if clen == 0 then ulen else clen + if p + 16 + size > e or name == "END\0" then + break + end + if name == "INST" then + local body: buffer?, o = b, p + 16 + if clen ~= 0 then + body = if Zstd.isFrame(b, p + 16) then Zstd.decompress(b, p + 16, clen, { maxBytes = ulen }) else Lz4.decompress(b, p + 16, clen, ulen) + o = 0 + end + if body and o + 8 <= buffer.len(body) then + local q = o + 8 + readu32(body, o + 4) + if q < buffer.len(body) and readu8(body, q) == 1 then + return "rbxl" + end + end + end + p += 16 + size + end + return "rbxm" +end + +-- ------------------------------------------------------------------------------------------------ decode +type Class = { id: number, name: string, refs: { number }, service: boolean } + +local function str(b: buffer, p: number, e: number): (string?, number) + if p + 4 > e then + return nil, p + end + local n = readu32(b, p) + if p + 4 + n > e then + return nil, p + end + return readstring(b, p + 4, n), p + 4 + n +end + +function Rbxm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Rbx.Tree?, Err.Err?) + local maxBytes = opts and opts.maxBytes or 2 ^ 28 + local maxInstances = opts and opts.maxInstances or 2 ^ 22 + local b, base, limit = r.buf, r.base, r.limit + if limit - base < 32 then + return nil, Err.new(Err.TRUNCATED, "header", base) + end + if readstring(b, base, 14) ~= MAGIC then + return nil, Err.new(Err.CORRUPT, "bad signature", base) + end + local version = buffer.readu16(b, base + 14) + if version ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "format version " .. version, base + 14) + end + local nClasses, nInstances = readi32(b, base + 16), readi32(b, base + 20) + if nClasses < 0 or nInstances < 0 then + return nil, Err.new(Err.CORRUPT, "negative counts", base + 16) + end + if nInstances > maxInstances then + return nil, Err.new(Err.LIMIT, "limit: " .. nInstances .. " instances", base + 20) + end + local tree = Rbx.tree() + tree.meta.source = { format = "rbxm", version = version, classes = nClasses, instances = nInstances, compression = {} } + local classes: { [number]: Class } = {} + local byRef: { [number]: Rbx.Instance } = {} + local shared: { string } = {} + local parented: { [Rbx.Instance]: boolean } = {} + local order: { Rbx.Instance } = {} + local anyService = false + local comp: { [string]: boolean } = {} + local ctx: Binary.Ctx = { + ref = function(n: number): any + return byRef[n] + end, + shared = shared, + } + local p = base + 32 + local ended = false + while p < limit do + if p + 16 > limit then + return nil, Err.new(Err.TRUNCATED, "chunk header", p) + end + local name = readstring(b, p, 4) + local clen, ulen = readu32(b, p + 4), readu32(b, p + 8) + local at = p + p += 16 + if ulen > maxBytes then + return nil, Err.new(Err.LIMIT, "limit: chunk of " .. ulen .. " bytes", at) + end + local body: buffer, bo: number, be: number + if clen == 0 then + if p + ulen > limit then + return nil, Err.new(Err.TRUNCATED, "chunk " .. name .. " runs past the end", at) + end + body, bo, be = b, p, p + ulen + p += ulen + comp.none = true + else + if p + clen > limit then + return nil, Err.new(Err.TRUNCATED, "chunk " .. name .. " runs past the end", at) + end + local out, err + if Zstd.isFrame(b, p) then + out, err = Zstd.decompress(b, p, clen, { maxBytes = ulen }) + comp.zstd = true + else + out, err = Lz4.decompress(b, p, clen, ulen) + comp.lz4 = true + end + if not out then + return nil, err + end + if buffer.len(out) ~= ulen then + return nil, Err.new(Err.CORRUPT, "chunk " .. name .. " decompresses to the wrong size", at) + end + body, bo, be = out, 0, ulen + p += clen + end + if name == "END\0" then + ended = true + break + elseif name == "META" then + if bo + 4 > be then + return nil, Err.new(Err.TRUNCATED, "META", at) + end + local q = bo + 4 + for _ = 1, readu32(body, bo) do + local k, q1 = str(body, q, be) + local v, q2 = str(body, q1, be) + if not k or not v then + return nil, Err.new(Err.TRUNCATED, "META entry", at) + end + tree.metadata[k] = v + q = q2 + end + elseif name == "SSTR" then + if bo + 8 > be then + return nil, Err.new(Err.TRUNCATED, "SSTR", at) + end + local q = bo + 8 + for i = 1, readu32(body, bo + 4) do + local s, q2 = str(body, q + 16, be) + if not s then + return nil, Err.new(Err.TRUNCATED, "shared string", at) + end + shared[i] = s + q = q2 + end + elseif name == "INST" then + local id = if bo + 4 <= be then readi32(body, bo) else -1 + local cname, q = str(body, bo + 4, be) + if not cname or q + 5 > be then + return nil, Err.new(Err.TRUNCATED, "INST", at) + end + local fmt, count = readu8(body, q), readu32(body, q + 1) + if count > nInstances then + return nil, Err.new(Err.CORRUPT, "more instances than the header says", at) + end + local refs, q2 = Binary.readRefs(body, q + 5, be, count) + if not refs then + return nil, Err.new(Err.TRUNCATED, "INST referents", at) + end + if id < 0 or classes[id] then + return nil, Err.new(Err.CORRUPT, "bad class id " .. id, at) + end + local service = fmt == 1 + if service and q2 + count > be then + return nil, Err.new(Err.TRUNCATED, "INST service markers", at) + end + classes[id] = { id = id, name = cname, refs = refs, service = service } + for i, ref in refs do + if byRef[ref] then + return nil, Err.new(Err.CORRUPT, "referent " .. ref .. " used twice", at) + end + local inst = Rbx.instance(cname) + inst.referent = tostring(ref) + if service and readu8(body, q2 + i - 1) ~= 0 then + inst.service = true + anyService = true + end + byRef[ref] = inst + table.insert(order, inst) + end + elseif name == "PROP" then + local id = if bo + 4 <= be then readi32(body, bo) else -1 + local pname, q = str(body, bo + 4, be) + if not pname or q + 1 > be then + return nil, Err.new(Err.TRUNCATED, "PROP", at) + end + local cls = classes[id] + if not cls then + return nil, Err.new(Err.CORRUPT, "PROP for an unknown class " .. id, at) + end + local t = readu8(body, q) + local n = #cls.refs + local vals, msg = Binary.decode(t, body, q + 1, be, n, ctx) + if vals then + local tname = Rbx.TYPE_NAMES[t] + for i, ref in cls.refs do + local inst = byRef[ref] + if pname == "Name" and t == 0x01 then + inst.name = vals[i] + else + inst.properties[pname] = { type = tname, value = vals[i] } + end + end + elseif msg == "unknown" then + local data = buffer.create(be - q - 1) + buffer.copy(data, 0, body, q + 1, be - q - 1) + for i, ref in cls.refs do + byRef[ref].properties[pname] = { type = "Raw", value = { typeId = t, data = data, index = i, count = n } } + end + else + return nil, Err.from(msg, at) + end + elseif name == "PRNT" then + if bo + 5 > be then + return nil, Err.new(Err.TRUNCATED, "PRNT", at) + end + if readu8(body, bo) ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "PRNT version " .. readu8(body, bo), at) + end + local count = readu32(body, bo + 1) + local kids, q = Binary.readRefs(body, bo + 5, be, count) + local parents = if kids then Binary.readRefs(body, q, be, count) else nil + if not kids or not parents then + return nil, Err.new(Err.TRUNCATED, "PRNT referents", at) + end + for i = 1, count do + local child, parent = byRef[kids[i]], parents[i] >= 0 and byRef[parents[i]] or nil + if not child or (parents[i] >= 0 and not parent) then + return nil, Err.new(Err.CORRUPT, "PRNT names an unknown referent", at) + end + if parented[child] then + return nil, Err.new(Err.CORRUPT, "an instance with two parents", at) + end + parented[child] = true + local up: Rbx.Instance? = parent + while up do + if up == child then + return nil, Err.new(Err.CORRUPT, "a cycle in the hierarchy", at) + end + up = up.parent + end + Rbx.add(parent or tree, child) + end + else + local data = buffer.create(be - bo) + buffer.copy(data, 0, body, bo, be - bo) + table.insert(tree.extra, { name = name, data = data }) + end + end + if not ended then + return nil, Err.new(Err.TRUNCATED, "no END chunk", limit) + end + for _, inst in order do + if not parented[inst] then + table.insert(tree.roots, inst) + end + end + tree.place = anyService + local list = {} + for k in comp do + table.insert(list, k) + end + table.sort(list) + local src: any = tree.meta.source + src.compression = list + return tree, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function columnType(insts: { Rbx.Instance }, pname: string): (number?, string?) + local id, tname = nil, nil + for _, inst in insts do + local v = inst.properties[pname] + if v then + if type(v) ~= "table" or type(v.type) ~= "string" then + return nil, "property " .. pname .. " of " .. inst.className .. " is not a { type, value } table" + end + local t = if v.type == "Raw" then -1 elseif v.type == "XmlRaw" then -2 else Rbx.TYPE_IDS[v.type] + if not t then + return nil, "property " .. pname .. ": unknown type " .. v.type + end + if id == nil then + id, tname = t, v.type + elseif id ~= t then + return nil, "property " .. pname .. " of " .. inst.className .. " has values of types " .. tostring(tname) .. " and " .. v.type + end + end + end + return id, tname +end + +local function chunk(w: Bytes.Writer, name: string, body: buffer, compress: boolean) + w:string(name) + local n = buffer.len(body) + if compress then + local z = Lz4.compress(body) :: buffer + w:u32le(buffer.len(z)) + w:u32le(n) + w:u32le(0) + w:bytes(z) + else + w:u32le(0) + w:u32le(n) + w:u32le(0) + w:bytes(body) + end +end + +local function putStr(w: Bytes.Writer, s: string) + w:u32le(#s) + w:string(s) +end + +function Rbxm.encode(tree: Rbx.Tree, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(tree) ~= "table" or tree.kind ~= "rbxtree" or type(tree.roots) ~= "table" then + return nil, Err.new(Err.ARG, "expected an RbxTree (codecs/model/Rbx)") + end + local o: any = opts or {} + local compress = o.compression ~= "none" + local place = if o.place ~= nil then o.place == true elseif o.format == "rbxl" then true else tree.place == true + local insts: { Rbx.Instance } = {} + local refOf: { [any]: number } = {} + local parentOf: { [Rbx.Instance]: Rbx.Instance? } = {} + local function visit(inst: any, parent: Rbx.Instance?): Err.Err? + if type(inst) ~= "table" or type(inst.className) ~= "string" or type(inst.properties) ~= "table" then + return Err.new(Err.ARG, "an instance needs className and properties") + end + if refOf[inst] then + return Err.new(Err.ARG, "an instance appears twice in the tree") + end + refOf[inst] = #insts + table.insert(insts, inst) + parentOf[inst] = parent + for _, c in inst.children or {} do + local e = visit(c, inst) + if e then + return e + end + end + return nil + end + for _, root in tree.roots do + local e = visit(root, nil) + if e then + return nil, e + end + end + local byClass: { [string]: { Rbx.Instance } } = {} + local names = {} + for _, inst in insts do + local list = byClass[inst.className] + if not list then + list = {} + byClass[inst.className] = list + table.insert(names, inst.className) + end + table.insert(list, inst) + end + table.sort(names) + local sharedIdx: { [string]: number } = {} + local sharedList: { string } = {} + local ctx: Binary.Ctx = { + refOf = function(v: any): number + return refOf[v] or -1 + end, + sharedIndex = function(s: string): number + local i = sharedIdx[s] + if not i then + table.insert(sharedList, s) + i = #sharedList - 1 + sharedIdx[s] = i + end + return i + end, + } + local props: { buffer } = {} + local instChunks: { buffer } = {} + for classId, cname in names do + local list = byClass[cname] + local id = classId - 1 + -- INST + local w = Bytes.writer(64 + 5 * #list) + w:u32le(id) + putStr(w, cname) + local service = place and parentOf[list[1]] == nil + for _, inst in list do + if inst.service then + service = true + end + end + w:u8(if service then 1 else 0) + w:u32le(#list) + local refs = table.create(#list, 0) + for i, inst in list do + refs[i] = refOf[inst] + end + Binary.writeRefs(w, refs) + if service then + for _, inst in list do + w:u8(if inst.service or (place and parentOf[inst] == nil) then 1 else 0) + end + end + table.insert(instChunks, w:finish()) + -- PROP: Name, then every property any instance of the class has, sorted + local pnames: { string } = {} + local seen: { [string]: boolean } = {} + for _, inst in list do + for pn in inst.properties do + if not seen[pn] and pn ~= "Name" then + seen[pn] = true + table.insert(pnames, pn) + end + end + end + table.sort(pnames) + table.insert(pnames, 1, "Name") + for _, pn in pnames do + local t: number?, tname: string? + if pn == "Name" then + t, tname = 0x01, "String" + else + local e + t, e = columnType(list, pn) + if not t then + return nil, Err.new(Err.ARG, e or "bad property") + end + tname = e + end + local pw = Bytes.writer(64) + pw:u32le(id) + putStr(pw, pn) + local tid = t :: number + if tid == -1 then + -- Raw: written back only when this class still has exactly its instances + local first = list[1].properties[pn] + local raw = first and first.value + local ok = type(raw) == "table" and raw.count == #list and type(raw.data) == "buffer" + if ok then + for i, inst in list do + local v = inst.properties[pn] + if not v or v.type ~= "Raw" or v.value.data ~= raw.data or v.value.index ~= i then + ok = false + break + end + end + end + if ok then + pw:u8(raw.typeId) + pw:bytes(raw.data) + table.insert(props, pw:finish()) + end + elseif tid ~= -2 then + pw:u8(tid) + local vals = table.create(#list) + for i, inst in list do + if pn == "Name" then + vals[i] = if type(inst.name) == "string" then inst.name else inst.className + else + local v = inst.properties[pn] + if v then + vals[i] = v.value + else + vals[i] = Rbx.default(tname :: string) + end + end + end + local e = Binary.encode(tid, vals, #list, pw, ctx) + if e then + return nil, Err.new(Err.ARG, "property " .. pn .. ": " .. e) + end + table.insert(props, pw:finish()) + end + end + end + -- PRNT + local pw = Bytes.writer(16 + 8 * #insts) + pw:u8(0) + pw:u32le(#insts) + local kids, parents = table.create(#insts, 0), table.create(#insts, 0) + for i, inst in insts do + kids[i] = i - 1 + local par = parentOf[inst] + parents[i] = if par then refOf[par] else -1 + end + Binary.writeRefs(pw, kids) + Binary.writeRefs(pw, parents) + + local out = Bytes.writer(1024) + out:string(MAGIC) + out:u16le(0) + out:u32le(#names) + out:u32le(#insts) + out:u32le(0) + out:u32le(0) + local metaKeys = {} + for k, v in tree.metadata or {} do + if type(k) == "string" and type(v) == "string" then + table.insert(metaKeys, k) + end + end + if #metaKeys > 0 then + table.sort(metaKeys) + local mw = Bytes.writer(64) + mw:u32le(#metaKeys) + for _, k in metaKeys do + putStr(mw, k) + putStr(mw, (tree.metadata :: any)[k]) + end + chunk(out, "META", mw:finish(), compress) + end + if #sharedList > 0 then + local sw = Bytes.writer(64) + sw:u32le(0) + sw:u32le(#sharedList) + for _, s in sharedList do + local h = Md5.new() + h:update(buffer.fromstring(s)) + sw:string(h:digest()) + putStr(sw, s) + end + chunk(out, "SSTR", sw:finish(), compress) + end + for _, c in instChunks do + chunk(out, "INST", c, compress) + end + for _, c in props do + chunk(out, "PROP", c, compress) + end + chunk(out, "PRNT", pw:finish(), compress) + for _, x in tree.extra or {} do + if type(x) == "table" and type(x.name) == "string" and #x.name == 4 and type(x.data) == "buffer" then + chunk(out, x.name, x.data, compress) + end + end + chunk(out, "END\0", buffer.fromstring("</roblox>"), false) + return out:finish(), nil +end + +return Rbxm +end +__FILES["model/rbxmx"] = function() + +-- model/rbxmx: Roblox XML model / place (.rbxmx / .rbxlx, `<roblox version="4">`) to and from a codecs/model/Rbx +-- RbxTree, from the rbx-dom notes (docs/xml.md), checked against rojo 7.7 and lune 0.11. Supports: every type +-- codecs/model/Rbx lists; unknown tags round-trip as "XmlRaw". Encode follows rbx-dom's layout. +-- Not supported: writing "Raw" values. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Base64 = __include("core/Base64") +local Md5 = __include("core/Md5") +local Xml = __include("codecs/text/Xml") +local Rbx = __include("codecs/model/Rbx") + +-- ------------------------------------------------------------------------------------------------ contract +local Rbxmx = { + name = "rbxmx", + category = "model", + extensions = { "rbxmx", "rbxlx" }, + mime = { "application/x-roblox-rbxmx", "application/x-roblox-rbxlx" }, + deps = { "core/Err", "core/Bytes", "core/Base64", "core/Md5", "codecs/text/Xml", "codecs/model/Rbx" }, + caps = { decode = true, encode = true, tree = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + maxDepth: number?, -- default 10000 +} +type EncodeOptions = { + indent: (number | string)?, -- default 2; 0 for none +} + +-- ------------------------------------------------------------------------------------------------ constants +local XmlNode = Xml.element +local find, format, match, gmatch = string.find, string.format, string.match, string.gmatch + +local SCALAR_TAGS: { [string]: string } = { + string = "String", + ProtectedString = "ProtectedString", + bool = "Bool", + int = "Int32", + int64 = "Int64", + float = "Float32", + double = "Float64", + token = "Enum", + BrickColor = "BrickColor", + SecurityCapabilities = "SecurityCapabilities", + UniqueId = "UniqueId", +} +-- BrickColor properties: XML writes them as <int> (rbx-dom reads them through its reflection database); these known ones +-- read back as BrickColor (the rest of an <int> stays Int32) +local BRICKCOLOR: { [string]: boolean } = { + ["BrickColorValue.Value"] = true, + ["SpawnLocation.TeamColor"] = true, + ["Team.TeamColor"] = true, + ["FlagStand.TeamColor"] = true, + ["Skin.SkinColor"] = true, +} +-- the strings rbx-dom writes as BinaryString (the rest decides by content) +local BINARY_NAMES: { [string]: boolean } = { AttributesSerialize = true, Tags = true, MaterialColors = true, SmoothGrid = true, PhysicsGrid = true } + +-- ------------------------------------------------------------------------------------------------ sniff +function Rbxmx.sniff(r: Bytes.Reader): number + local head = r:peek(256) + head = string.gsub(head, "^\239\187\191", "") + head = string.gsub(head, "^%s*<%?xml[^>]*%?>", "") + if match(head, "^%s*<roblox[%s>]") then + return if find(head, "version=", 1, true) then 1 else 0.8 + end + return 0 +end + +-- a Workspace item makes a place +function Rbxmx.variant(r: Bytes.Reader): string? + local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + return if find(text, '<Item class="Workspace"', 1, true) then "rbxlx" else "rbxmx" +end + +-- ------------------------------------------------------------------------------------------------ decode +local function num(s: string?): number + if s == nil then + return 0 + end + local t = string.lower((string.gsub(s, "^%s+", ""))) + t = string.gsub(t, "%s+$", "") + if t == "inf" or t == "+inf" or t == "infinity" then + return math.huge + elseif t == "-inf" or t == "-infinity" then + return -math.huge + elseif t == "nan" or t == "-nan" then + return 0 / 0 + end + return tonumber(t) or 0 +end + +local function childText(node: Xml.Node, name: string): string? + local c = Xml.child(node, name) + return if c then Xml.text(c) else nil +end +local function comps(node: Xml.Node?, names: { string }): { number } + local out = table.create(#names, 0) + if node then + for i, n in names do + out[i] = num(childText(node, n)) + end + end + return out +end +local function numbers(s: string): { number } + local out = {} + for w in gmatch(s, "%S+") do + table.insert(out, num(w)) + end + return out +end + +local CF_NAMES = { "X", "Y", "Z", "R00", "R01", "R02", "R10", "R11", "R12", "R20", "R21", "R22" } +local PHYS_NAMES = { "Density", "Friction", "Elasticity", "FrictionWeight", "ElasticityWeight" } + +local function readRaw(node: Xml.Node, shared: { [string]: string }, key: string): (string, any) + local tag = node.name + local scalar = SCALAR_TAGS[tag] + if tag == "int" and BRICKCOLOR[key] then + scalar = "BrickColor" + end + if scalar then + local s = Xml.text(node) + if scalar == "String" or scalar == "ProtectedString" then + return scalar, s + elseif scalar == "Bool" then + return scalar, match(s, "^%s*true%s*$") ~= nil + elseif scalar == "UniqueId" then + return scalar, string.lower((string.gsub(s, "%s", ""))) + end + return scalar, num(s) + elseif tag == "BinaryString" then + local data = Base64.decode((string.gsub(Xml.text(node), "%s", ""))) + return "BinaryString", if data then buffer.tostring(data) else "" + elseif tag == "Content" or tag == "ContentId" then + local url = Xml.child(node, "url") + if url then + return "ContentId", Xml.text(url) + end + local uri = Xml.child(node, "uri") + if uri then + return "Content", Xml.text(uri) + end + local obj = Xml.child(node, "Object") or Xml.child(node, "Ref") + if obj then + return "Content", { pending = Xml.text(obj) } + end + if Xml.child(node, "null") then + return (if tag == "ContentId" then "ContentId" else "Content"), (if tag == "ContentId" then "" else nil) + end + return "ContentId", Xml.text(node) + elseif tag == "Vector2" or tag == "Vector2int16" then + return tag, comps(node, { "X", "Y" }) + elseif tag == "Vector3" or tag == "Vector3int16" then + return tag, comps(node, { "X", "Y", "Z" }) + elseif tag == "Color3" then + if Xml.child(node, "R") then + return tag, comps(node, { "R", "G", "B" }) + end + local v = num(Xml.text(node)) % 4294967296 + return tag, { (v // 65536) % 256 / 255, (v // 256) % 256 / 255, v % 256 / 255 } + elseif tag == "Color3uint8" then + local v = num(Xml.text(node)) % 4294967296 + return tag, { (v // 65536) % 256, (v // 256) % 256, v % 256 } + elseif tag == "CoordinateFrame" or tag == "CFrame" then + return "CFrame", comps(node, CF_NAMES) + elseif tag == "OptionalCoordinateFrame" then + local cf = Xml.child(node, "CFrame") + return "OptionalCFrame", if cf then comps(cf, CF_NAMES) else nil + elseif tag == "UDim" then + return tag, comps(node, { "S", "O" }) + elseif tag == "UDim2" then + return tag, comps(node, { "XS", "XO", "YS", "YO" }) + elseif tag == "Rect2D" then + local a, b = comps(Xml.child(node, "min"), { "X", "Y" }), comps(Xml.child(node, "max"), { "X", "Y" }) + return "Rect", { a[1], a[2], b[1], b[2] } + elseif tag == "Ray" then + local a, b = comps(Xml.child(node, "origin"), { "X", "Y", "Z" }), comps(Xml.child(node, "direction"), { "X", "Y", "Z" }) + return tag, { a[1], a[2], a[3], b[1], b[2], b[3] } + elseif tag == "Faces" or tag == "Axes" then + local t = childText(node, string.lower(tag)) + return tag, num(t or Xml.text(node)) + elseif tag == "NumberRange" then + local v = numbers(Xml.text(node)) + return tag, { v[1] or 0, v[2] or 0 } + elseif tag == "NumberSequence" or tag == "ColorSequence" then + local k = if tag == "NumberSequence" then 3 else 5 + local v = numbers(Xml.text(node)) + local seq = {} + for i = 1, #v - k + 1, k do + table.insert(seq, table.move(v, i, i + k - 1, 1, table.create(k, 0))) + end + return tag, seq + elseif tag == "PhysicalProperties" then + local custom = childText(node, "CustomPhysics") + if not custom or not match(custom, "^%s*true%s*$") then + return tag, nil + end + local v = comps(node, PHYS_NAMES) + local a = childText(node, "AcousticAbsorption") + v[6] = if a then num(a) else 1 + return tag, v + elseif tag == "Ref" then + local s = string.gsub(Xml.text(node), "%s", "") + return tag, if s == "" or s == "null" then nil else { pending = s } + elseif tag == "SharedString" then + local key = string.gsub(Xml.text(node), "%s", "") + return tag, shared[key] or "" + elseif tag == "Font" then + local fam = Xml.child(node, "Family") + local face = Xml.child(node, "CachedFaceId") + local f = { + family = if fam then childText(fam, "url") or Xml.text(fam) else "", + weight = num(childText(node, "Weight") or "400"), + style = if match(childText(node, "Style") or "", "Italic") then "Italic" else "Normal", + cachedFaceId = if face then childText(face, "url") or nil else nil, + } + if f.cachedFaceId == "" then + f.cachedFaceId = nil + end + return tag, f + end + return "XmlRaw", node +end + +-- single-precision types: their components rounded to f32 (as a binary file stores them), so XML and binary +-- decodes of the same data are equal. Which components are floats, by type (true = all) +local F32: { [string]: any } = { + Float32 = true, + Vector2 = true, + Vector3 = true, + Color3 = true, + CFrame = true, + OptionalCFrame = true, + Rect = true, + Ray = true, + NumberRange = true, + NumberSequence = true, + ColorSequence = true, + PhysicalProperties = true, + UDim = { true, false }, + UDim2 = { true, false, true, false }, +} +local f32buf = buffer.create(4) +local function f32(v: number): number + buffer.writef32(f32buf, 0, v) + return buffer.readf32(f32buf, 0) +end +local function round32(v: any, which: any): any + if type(v) == "number" then + return f32(v) + elseif type(v) == "table" then + for i, x in v do + if type(x) == "table" then + round32(x, true) + elseif type(x) == "number" and (which == true or which[i]) then + v[i] = f32(x) + end + end + end + return v +end +local function readValue(node: Xml.Node, shared: { [string]: string }, key: string): (string, any) + local t, v = readRaw(node, shared, key) + local which = F32[t] + if which then + v = round32(v, which) + end + return t, v +end + +function Rbxmx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Rbx.Tree?, Err.Err?) + local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + local doc, err = Xml.decode(text, { maxDepth = opts and opts.maxDepth } :: any) + if not doc then + return nil, err + end + local root = (doc :: any).root + if not root or root.name ~= "roblox" then + return nil, Err.new(Err.CORRUPT, "the root element is not <roblox>") + end + local tree = Rbx.tree() + tree.meta.source = { format = "rbxmx", version = root.attrs.version } + local shared: { [string]: string } = {} + for _, ss in Xml.children(root, "SharedStrings") do + for _, s in Xml.children(ss, "SharedString") do + local key = s.attrs.md5 + local data = Base64.decode((string.gsub(Xml.text(s), "%s", ""))) + if key and data then + shared[key] = buffer.tostring(data) + end + end + end + local byRef: { [string]: Rbx.Instance } = {} + local pending: { { any } } = {} + local function item(node: Xml.Node, parent: any): Err.Err? + local cls = node.attrs.class + if type(cls) ~= "string" then + return Err.new(Err.CORRUPT, "an <Item> without a class") + end + local inst = Rbx.instance(cls) + local ref = node.attrs.referent + if type(ref) == "string" then + inst.referent = ref + byRef[ref] = inst + end + Rbx.add(parent, inst) + for _, c in node.children do + if type(c) == "table" then + if c.name == "Properties" then + for _, pnode in c.children do + if type(pnode) == "table" and string.sub(pnode.name, 1, 1) ~= "#" then + local pname = pnode.attrs.name + if type(pname) == "string" then + local t, v = readValue(pnode, shared, cls .. "." .. pname) + if pname == "Name" and (t == "String" or t == "ProtectedString") then + inst.name = v + else + local val = { type = t, value = v } + inst.properties[pname] = val + if type(v) == "table" and v.pending then + table.insert(pending, { val, v.pending }) + end + end + end + end + end + elseif c.name == "Item" then + local e = item(c, inst) + if e then + return e + end + end + end + end + return nil + end + for _, c in root.children do + if type(c) == "table" then + if c.name == "Item" then + local e = item(c, tree) + if e then + return nil, e + end + elseif c.name == "Meta" then + if type(c.attrs.name) == "string" then + tree.metadata[c.attrs.name] = Xml.text(c) + end + elseif c.name ~= "SharedStrings" and string.sub(c.name, 1, 1) ~= "#" then + table.insert(tree.extra, c) + end + end + end + for _, p in pending do + p[1].value = byRef[p[2]] + end + for _, rt in tree.roots do + if rt.className == "Workspace" then + tree.place = true + end + end + return tree, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function fmt(v: any, single: boolean?): string + if type(v) ~= "number" then + v = 0 + end + if v ~= v then + return "NAN" + elseif v == math.huge then + return "INF" + elseif v == -math.huge then + return "-INF" + end + if single then + v = f32(v) + end + if v == math.floor(v) and math.abs(v) < 2 ^ 53 then + return format("%.0f", v) + end + for d = if single then 6 else 15, if single then 9 else 17 do + local s = format("%." .. d .. "g", v) + local back = tonumber(s) or 0 + if (if single then f32(back) else back) == v then + return s + end + end + return format("%.17g", v) +end +local function int(v: any): string + return format("%.0f", math.floor(if type(v) == "number" and v == v and math.abs(v) ~= math.huge then v else 0)) +end + +local function textEl(tag: string, text: string): Xml.Node + return XmlNode(tag, nil, { text }) +end +local function compsEl(tag: string, attrs: { [string]: string }?, names: { string }, v: any, single: boolean?, ints: boolean?): Xml.Node + local kids = {} + for i, n in names do + local x = if type(v) == "table" then v[i] else 0 + table.insert(kids, textEl(n, if ints then int(x) else fmt(x, single))) + end + return XmlNode(tag, attrs, kids) +end + +local function hexDigits(i: number): string + return format("%032X", i) +end + +local function xmlSafe(s: string): boolean + if find(s, "[%z\1-\8\11\12\14-\31\127]") then + return false + end + return utf8.len(s) ~= nil +end + +local function writeValue(name: string, v: any, refOf: (any) -> string, sharedKey: (string) -> string): Xml.Node? + local t, x = v.type, v.value + local a = { name = name } + if t == "String" or t == "ProtectedString" or t == "BinaryString" or t == "Bytecode" then + local s = if type(x) == "string" then x else "" + if t == "BinaryString" or t == "Bytecode" or BINARY_NAMES[name] or not xmlSafe(s) then + return XmlNode("BinaryString", a, { Base64.encode(s) }) + end + return XmlNode(if t == "ProtectedString" then "ProtectedString" else "string", a, { s }) + elseif t == "ContentId" then + local s = if type(x) == "string" then x else "" + return XmlNode("ContentId", a, { if s == "" then XmlNode("null") else textEl("url", s) }) + elseif t == "Content" then + if type(x) == "string" then + return XmlNode("Content", a, { textEl("uri", x) }) + elseif type(x) == "table" then + return XmlNode("Content", a, { textEl("Object", refOf(x)) }) + end + return XmlNode("Content", a, { XmlNode("null") }) + elseif t == "Bool" then + return XmlNode("bool", a, { if x then "true" else "false" }) + elseif t == "Int32" then + return XmlNode("int", a, { int(x) }) + elseif t == "Int64" then + return XmlNode("int64", a, { int(x) }) + elseif t == "Float32" then + return XmlNode("float", a, { fmt(x, true) }) + elseif t == "Float64" then + return XmlNode("double", a, { fmt(x) }) + elseif t == "Enum" then + return XmlNode("token", a, { int(x) }) + elseif t == "BrickColor" then + return XmlNode("int", a, { int(x) }) + elseif t == "SecurityCapabilities" then + return XmlNode("SecurityCapabilities", a, { int(x) }) + elseif t == "UniqueId" then + return XmlNode("UniqueId", a, { if type(x) == "string" then string.lower(x) else string.rep("0", 32) }) + elseif t == "Vector2" then + return compsEl(t, a, { "X", "Y" }, x, true) + elseif t == "Vector3" then + return compsEl(t, a, { "X", "Y", "Z" }, x, true) + elseif t == "Vector2int16" then + return compsEl(t, a, { "X", "Y" }, x, false, true) + elseif t == "Vector3int16" then + return compsEl(t, a, { "X", "Y", "Z" }, x, false, true) + elseif t == "Color3" then + return compsEl(t, a, { "R", "G", "B" }, x, true) + elseif t == "Color3uint8" then + local c = if type(x) == "table" then x else { 0, 0, 0 } + local function b(i: number): number + return math.clamp(math.floor(tonumber(c[i]) or 0), 0, 255) + end + return XmlNode(t, a, { int(b(1) * 65536 + b(2) * 256 + b(3)) }) + elseif t == "CFrame" then + return compsEl("CoordinateFrame", a, CF_NAMES, x, true) + elseif t == "OptionalCFrame" then + return XmlNode("OptionalCoordinateFrame", a, if type(x) == "table" then { compsEl("CFrame", nil, CF_NAMES, x, true) } else {}) + elseif t == "UDim" then + local u = if type(x) == "table" then x else { 0, 0 } + return XmlNode(t, a, { textEl("S", fmt(u[1], true)), textEl("O", int(u[2])) }) + elseif t == "UDim2" then + local u = if type(x) == "table" then x else { 0, 0, 0, 0 } + return XmlNode(t, a, { textEl("XS", fmt(u[1], true)), textEl("XO", int(u[2])), textEl("YS", fmt(u[3], true)), textEl("YO", int(u[4])) }) + elseif t == "Rect" then + local u = if type(x) == "table" then x else { 0, 0, 0, 0 } + return XmlNode("Rect2D", a, { compsEl("min", nil, { "X", "Y" }, { u[1], u[2] }, true), compsEl("max", nil, { "X", "Y" }, { u[3], u[4] }, true) }) + elseif t == "Ray" then + local u = if type(x) == "table" then x else { 0, 0, 0, 0, 0, 0 } + return XmlNode(t, a, { compsEl("origin", nil, { "X", "Y", "Z" }, { u[1], u[2], u[3] }, true), compsEl("direction", nil, { "X", "Y", "Z" }, { u[4], u[5], u[6] }, true) }) + elseif t == "Faces" or t == "Axes" then + return XmlNode(t, a, { textEl(string.lower(t), int(x)) }) + elseif t == "NumberRange" or t == "NumberSequence" or t == "ColorSequence" then + local parts = {} + local list = if type(x) ~= "table" then {} elseif t == "NumberRange" then { x } else x + for _, key in list do + for _, c in key do + table.insert(parts, fmt(c, true) .. " ") + end + end + return XmlNode(t, a, { table.concat(parts) }) + elseif t == "PhysicalProperties" then + if type(x) ~= "table" then + return XmlNode(t, a, { textEl("CustomPhysics", "false") }) + end + local kids = { textEl("CustomPhysics", "true") } + for i, n in PHYS_NAMES do + table.insert(kids, textEl(n, fmt(x[i], true))) + end + table.insert(kids, textEl("AcousticAbsorption", fmt(if x[6] ~= nil then x[6] else 1, true))) + return XmlNode(t, a, kids) + elseif t == "Ref" then + return XmlNode("Ref", a, { if x ~= nil then refOf(x) else "null" }) + elseif t == "SharedString" then + return XmlNode("SharedString", a, { sharedKey(if type(x) == "string" then x else "") }) + elseif t == "Font" then + local f = if type(x) == "table" then x else Rbx.default("Font") + local kids = { + XmlNode("Family", nil, { textEl("url", if type(f.family) == "string" then f.family else "") }), + textEl("Weight", int(f.weight or 400)), + textEl("Style", if f.style == "Italic" then "Italic" else "Normal"), + } + if type(f.cachedFaceId) == "string" and f.cachedFaceId ~= "" then + table.insert(kids, XmlNode("CachedFaceId", nil, { textEl("url", f.cachedFaceId) })) + end + return XmlNode("Font", a, kids) + elseif t == "XmlRaw" then + if type(x) == "table" and type(x.name) == "string" then + local copy = XmlNode(x.name, nil, x.children) + for k, val in x.attrs do + Xml.setAttr(copy, k, val) + end + Xml.setAttr(copy, "name", name) + return copy + end + end + return nil +end + +function Rbxmx.encode(tree: Rbx.Tree, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(tree) ~= "table" or tree.kind ~= "rbxtree" or type(tree.roots) ~= "table" then + return nil, Err.new(Err.ARG, "expected an RbxTree (codecs/model/Rbx)") + end + local refs: { [any]: string } = {} + local count = 0 + local function assign(inst: any): Err.Err? + if type(inst) ~= "table" or type(inst.className) ~= "string" or type(inst.properties) ~= "table" then + return Err.new(Err.ARG, "an instance needs className and properties") + end + if refs[inst] then + return Err.new(Err.ARG, "an instance appears twice in the tree") + end + refs[inst] = "RBX" .. hexDigits(count) + count += 1 + for _, c in inst.children or {} do + local e = assign(c) + if e then + return e + end + end + return nil + end + for _, rt in tree.roots do + local e = assign(rt) + if e then + return nil, e + end + end + local function refOf(x: any): string + return refs[x] or "null" + end + local sharedKeys: { [string]: string } = {} + local sharedList: { string } = {} + local function sharedKey(s: string): string + local k = sharedKeys[s] + if not k then + local h = Md5.new() + h:update(buffer.fromstring(s)) + k = Base64.encode(h:digest()) + sharedKeys[s] = k + table.insert(sharedList, s) + end + return k + end + local function item(inst: Rbx.Instance): Xml.Node + local props = { textEl("string", inst.name or inst.className) } + props[1].attrs.name = "Name" + local names: { string } = {} + for k in inst.properties do + if k ~= "Name" then + table.insert(names, k) + end + end + table.sort(names) + for _, k in names do + local v = inst.properties[k] + if type(v) == "table" then + local el = writeValue(k, v, refOf, sharedKey) + if el then + table.insert(props, el) + end + end + end + local kids = { XmlNode("Properties", nil, props) } + for _, c in inst.children or {} do + table.insert(kids, item(c)) + end + local el = XmlNode("Item", nil, kids) + Xml.setAttr(el, "class", inst.className) + Xml.setAttr(el, "referent", refs[inst]) + return el + end + local root = XmlNode("roblox", nil, {}) + Xml.setAttr(root, "version", "4") + local metaKeys = {} + for k in tree.metadata or {} do + table.insert(metaKeys, k) + end + table.sort(metaKeys) + for _, k in metaKeys do + local m = textEl("Meta", tostring((tree.metadata :: any)[k])) + m.attrs.name = k + Xml.append(root, m) + end + for _, rt in tree.roots do + Xml.append(root, item(rt)) + end + for _, x in tree.extra or {} do + if type(x) == "table" and type(x.name) == "string" and type(x.children) == "table" then + Xml.append(root, x) + end + end + if #sharedList > 0 then + local ss = XmlNode("SharedStrings", nil, {}) + for _, s in sharedList do + local el = XmlNode("SharedString", nil, { Base64.encode(s) }) + Xml.setAttr(el, "md5", sharedKeys[s]) + Xml.append(ss, el) + end + Xml.append(root, ss) + end + local indent = if opts and opts.indent ~= nil then opts.indent else 2 + local s, err = Xml.encode(root, { indent = indent, declaration = false, selfClose = false }) + if not s then + return nil, err + end + return buffer.fromstring(s), nil +end + +return Rbxmx +end +__FILES["model/robloxmesh"] = function() + +-- model/robloxmesh: Roblox FileMesh (.mesh), from MaximumADHD's "Roblox Mesh Format" (devforum.roblox.com/t/326114); no +-- port. Supports: reading 1.00 - 7.00 (Draco COREMESH v2 through codecs/model/Draco), writing 2.00 and 4.00. Not +-- supported: writing 3.00 / 5.00+ / FACS; FACS and HSRAVIS are kept raw. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Mat4 = __include("codecs/model/Mat4") +local Flatten = __include("codecs/model/MeshFlatten") +local Draco = __include("codecs/model/Draco") +local Parse = __include("model/robloxmesh/Parse") +local Write = __include("model/robloxmesh/Write") + +-- ------------------------------------------------------------------------------------------------ contract +local RobloxMesh = { + name = "robloxmesh", + category = "model", + extensions = { "mesh" }, + mime = { "application/x-roblox-mesh" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten", "codecs/model/Draco" }, + caps = { decode = true, encode = true, skinning = true, lods = true, versions = { "1.00", "1.01", "2.00", "3.00", "3.01", "4.00", "4.01", "5.00", "6.00", "7.00" } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + maxVertices: number?, -- default 2^24 + maxFaces: number?, -- default 2^25 +} +type EncodeOptions = { + version: ("2.00" | "4.00")?, -- default "2.00" +} + +-- ------------------------------------------------------------------------------------------------ constants +local readf32, writef32, readu8, writeu8, writeu16 = buffer.readf32, buffer.writef32, buffer.readu8, buffer.writeu8, buffer.writeu16 +local accessor = Types.Scene.accessor + +-- ------------------------------------------------------------------------------------------------ sniff +function RobloxMesh.sniff(r: Bytes.Reader): number + return if string.match(r:peek(13), "^version [1-7]%.%d%d[\r\n]") then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- a bone's world matrix (column major) from its CFrame (r00 .. r22, x, y, z) +local function boneMatrix(cf: { number }): { number } + return { cf[1], cf[4], cf[7], 0, cf[2], cf[5], cf[8], 0, cf[3], cf[6], cf[9], 0, cf[10], cf[11], cf[12], 1 } +end + +local function indices(r: Parse.Record, from: number, to: number): Types.Accessor + local n = math.max(0, to - from) + local d = buffer.create(n * 12) + buffer.copy(d, 0, r.faces, from * 12, n * 12) + return accessor(d, "u32", 1, n * 3) +end + +local function dracoCore(b: buffer, off: number, len: number): (Parse.Core?, string?) + -- the stream follows a u32 byte count (accepted without it too) + if len >= 4 and buffer.readu32(b, off) <= len - 4 and buffer.readu32(b, off) >= 5 and buffer.readstring(b, off + 4, 5) == "DRACO" then + len = buffer.readu32(b, off) + off += 4 + end + local g, err = Draco.decode(b, off, len) + if not g then + return nil, (err :: Err.Err).message + end + if g.kind ~= "mesh" then + return nil, "corrupt: Draco COREMESH holds a point cloud" + end + local n = g.numPoints + local by: { [string]: Draco.Attribute } = {} + for _, a in g.attributes do + local key = if a.name == "GENERIC" and a.components == 4 then "TANGENT" else a.name + if not by[key] then + by[key] = a + end + end + local pos = by.POSITION + if not pos or pos.components < 3 then + return nil, "corrupt: Draco COREMESH without positions" + end + local function getter(a: Draco.Attribute): (number, number) -> number + local t = if a.normalized then (({ u8 = "unorm8", i8 = "snorm8", u16 = "unorm16", i16 = "snorm16" }) :: any)[a.type] or a.type else a.type + local rd = Types.Scene.reader({ data = a.data, type = t, components = a.components, count = n }) + if not rd then + return function(_i: number, _c: number): number + return 0 + end + end + return rd + end + local function floats(a: Draco.Attribute?, comps: number): buffer + local out = buffer.create(n * comps * 4) + if a then + local get = getter(a) + local m = math.min(comps, a.components) + for i = 0, n - 1 do + for c = 0, m - 1 do + writef32(out, (i * comps + c) * 4, get(i, c)) + end + end + end + return out + end + local tan: buffer? = nil + if by.TANGENT then + local get = getter(by.TANGENT) + local t = buffer.create(n * 4) + for i = 0, n - 1 do + for c = 0, 3 do + local v = if c < by.TANGENT.components then get(i, c) else 1 + buffer.writei8(t, i * 4 + c, math.clamp(math.floor(v * 127 + 0.5), -127, 127)) + end + end + tan = t + end + local col: buffer? = nil + if by.COLOR then + local a = by.COLOR + local c = buffer.create(n * 4) + if a.type == "u8" and a.components == 4 then + buffer.copy(c, 0, a.data, 0, n * 4) + else + local get = getter(a) + for i = 0, n - 1 do + for k = 0, 3 do + local v = if k < a.components then get(i, k) else 1 + if a.type ~= "f32" and not a.normalized then + v /= 255 + end + writeu8(c, i * 4 + k, math.clamp(math.floor(v * 255 + 0.5), 0, 255)) + end + end + end + col = c + end + return { + numVerts = n, + pos = floats(pos, 3), + nrm = floats(by.NORMAL, 3), + uv = floats(by.TEX_COORD, 2), + tan = tan, + col = col, + numFaces = g.numFaces, + faces = g.indices :: buffer, + }, nil +end + +-- Parse is native: nothing may throw through it +local function safeCore(b: buffer, off: number, len: number): (Parse.Core?, string?) + local ok, c, err = pcall(dracoCore, b, off, len) + if not ok then + return nil, "corrupt: Draco COREMESH: " .. tostring(c) + end + return c, err +end + +function RobloxMesh.decode(rd: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local lim: Parse.Limits = { maxVertices = opts and opts.maxVertices or 2 ^ 24, maxFaces = opts and opts.maxFaces or 2 ^ 25, core = safeCore } + local r, msg = Parse.parse(rd.buf, rd.base, rd.limit, lim) + if not r then + return nil, Err.from(msg, rd.base) + end + local nv, nf = r.numVerts, r.numFaces + local attrs: { [string]: Types.Accessor } = { + POSITION = accessor(r.pos, "f32", 3, nv), + NORMAL = accessor(r.nrm, "f32", 3, nv), + TEXCOORD_0 = accessor(r.uv, "f32", 2, nv), + } + local tan = r.tan + if tan then + local t = buffer.create(nv * 16) + for i = 0, nv - 1 do + local x, y, z, w = Parse.tangent(tan, i) + writef32(t, i * 16, x) + writef32(t, i * 16 + 4, y) + writef32(t, i * 16 + 8, z) + writef32(t, i * 16 + 12, w) + end + attrs.TANGENT = accessor(t, "f32", 4, nv) + end + if r.col then + attrs.COLOR_0 = accessor(r.col, "unorm8", 4, nv) + end + local offs = {} + for _, o in r.lods do + table.insert(offs, math.clamp(o, 0, nf)) + end + if #offs < 2 then + offs = { 0, nf } + end + local scene = Types.Scene.new() + local prim: Types.Primitive = { attributes = attrs, indices = indices(r, offs[1], offs[2]), mode = "triangles" } + local lods = {} + for k = 2, #offs - 1 do + table.insert(lods, { attributes = attrs, indices = indices(r, offs[k], offs[k + 1]), mode = "triangles" }) + end + local mesh: Types.Mesh = { name = "Mesh", primitives = { prim } } + if #lods > 0 then + mesh.extras = { lods = lods } + end + scene.meshes[1] = mesh + scene.nodes[1] = { name = "Mesh", children = {}, mesh = 1 } + scene.roots[1] = 1 + local nb = #r.bones + if nb > 0 then + local world: { { number } } = table.create(nb) :: any + for i, bone in r.bones do + world[i] = boneMatrix(bone.cf) + end + local joints = table.create(nb, 0) + local ibm = buffer.create(nb * 64) + for i, bone in r.bones do + local parent = if bone.parent and bone.parent < nb and bone.parent ~= i - 1 then bone.parent + 1 else nil + local m = world[i] + if parent then + local inv = Mat4.inverse(world[parent]) + if inv then + m = Mat4.mul(inv, m) + end + end + local node: Types.Node = { name = bone.name, children = {}, matrix = m, extras = { culling = bone.culling, lodParent = bone.lodParent } } + table.insert(scene.nodes, node) + joints[i] = #scene.nodes + local inv = Mat4.inverse(world[i]) or Mat4.identity() + for k = 1, 16 do + writef32(ibm, (i - 1) * 64 + (k - 1) * 4, inv[k]) + end + end + for i, bone in r.bones do + local parent = if bone.parent and bone.parent < nb and bone.parent ~= i - 1 then bone.parent + 1 else nil + if parent then + table.insert(scene.nodes[joints[parent]].children, joints[i]) + else + table.insert(scene.roots, joints[i]) + end + end + scene.skins[1] = { joints = joints, inverseBindMatrices = accessor(ibm, "f32", 16, nb) } + scene.nodes[1].skin = 1 + local env = r.env + if env then + local jb, wb = buffer.create(nv * 8), buffer.create(nv * 4) + for i = 0, nv - 1 do + for k = 0, 3 do + writeu8(wb, i * 4 + k, readu8(env, i * 8 + 4 + k)) + end + end + for _, s in r.subsets do + local last = math.min(s.vertsBegin + s.vertsLength, nv) - 1 + for v = s.vertsBegin, last do + for k = 0, 3 do + local li = readu8(env, v * 8 + k) + local g = s.bones[li + 1] + writeu16(jb, v * 8 + k * 2, if g and g < nb and readu8(wb, v * 4 + k) > 0 then g else 0) + end + end + end + attrs.JOINTS_0 = accessor(jb, "u16", 4, nv) + attrs.WEIGHTS_0 = accessor(wb, "unorm8", 4, nv) + end + end + local subsets = {} + for _, s in r.subsets do + table.insert(subsets, { facesBegin = s.facesBegin, facesLength = s.facesLength, vertsBegin = s.vertsBegin, vertsLength = s.vertsLength, bones = s.bones }) + end + scene.meta.up = "y" + scene.meta.source = { + format = "robloxmesh", + version = r.version, + lodType = r.lodType, + highQualityLods = r.highQualityLods, + lodOffsets = r.lods, + subsets = subsets, + facsFormat = r.facsFormat, + facs = r.facs, + chunks = r.chunks, + draco = if r.coreVersion == 2 then true else nil, + } + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function num(attr: any, i: number, c: number, default: number): number + if not attr or c >= attr.components then + return default + end + return attr.values[i * attr.components + c + 1] +end + +local function normals(pos: buffer, nv: number, corners: { number }): buffer + local acc = table.create(nv * 3, 0) + for f = 0, #corners // 3 - 1 do + local a, b, c = corners[f * 3 + 1], corners[f * 3 + 2], corners[f * 3 + 3] + local ax, ay, az = readf32(pos, a * 12), readf32(pos, a * 12 + 4), readf32(pos, a * 12 + 8) + local ux, uy, uz = readf32(pos, b * 12) - ax, readf32(pos, b * 12 + 4) - ay, readf32(pos, b * 12 + 8) - az + local vx, vy, vz = readf32(pos, c * 12) - ax, readf32(pos, c * 12 + 4) - ay, readf32(pos, c * 12 + 8) - az + local nx, ny, nz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx + for _, v in { a, b, c } do + acc[v * 3 + 1] += nx + acc[v * 3 + 2] += ny + acc[v * 3 + 3] += nz + end + end + local out = buffer.create(nv * 12) + for v = 0, nv - 1 do + local x, y, z = acc[v * 3 + 1], acc[v * 3 + 2], acc[v * 3 + 3] + local l = math.sqrt(x * x + y * y + z * z) + if l > 0 then + writef32(out, v * 12, x / l) + writef32(out, v * 12 + 4, y / l) + writef32(out, v * 12 + 8, z / l) + else + writef32(out, v * 12 + 4, 1) + end + end + return out +end + +local function worlds(scene: any): { [number]: { number } } + local out: { [number]: { number } } = {} + local parent: { [number]: number } = {} + for i, n in scene.nodes do + for _, c in n.children or {} do + parent[c] = i + end + end + local function world(i: number, depth: number): { number } + if out[i] then + return out[i] + end + local m = Types.Scene.nodeMatrix(scene.nodes[i]) + local p = parent[i] + if p and depth < 256 then + m = Mat4.mul(world(p, depth + 1), m) + end + out[i] = m + return m + end + for i in scene.nodes do + world(i, 0) + end + return out +end + +local function skinBones(scene: any, skin: any): ({ Parse.Bone }?, string?) + local joints = skin.joints + if type(joints) ~= "table" or #joints == 0 then + return nil, "a skin without joints" + end + if #joints > 65534 then + return nil, "too many joints" + end + local w = worlds(scene) + local index: { [number]: number } = {} + for i, j in joints do + index[j] = i - 1 + end + local parentOf: { [number]: number } = {} + for i, n in scene.nodes do + for _, c in n.children or {} do + parentOf[c] = i + end + end + local ibm = skin.inverseBindMatrices and Flatten.numbers(skin.inverseBindMatrices) + local out = {} + for i, j in joints do + local node = scene.nodes[j] + if not node then + return nil, "a joint names a missing node" + end + local m = w[j] + if ibm and #ibm >= i * 16 then + local inv = Mat4.inverse(table.move(ibm, (i - 1) * 16 + 1, i * 16, 1, table.create(16, 0))) + if inv then + m = inv + end + end + local ex = if type(node.extras) == "table" then node.extras else {} + local p = parentOf[j] + out[i] = { + name = if type(node.name) == "string" then node.name else "Bone" .. i, + parent = if p then index[p] else nil, + lodParent = if type(ex.lodParent) == "number" then ex.lodParent else 0xFFFF, + culling = if type(ex.culling) == "number" then ex.culling else 0, + cf = { m[1], m[5], m[9], m[2], m[6], m[10], m[3], m[7], m[11], m[13], m[14], m[15] }, + } + end + return out, nil +end + +local function fill(r: Parse.Record, m: any, order: { number }, nrm: buffer?) + local nv = #order + local pos, nb, uv, tan = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8), buffer.create(nv * 4) + local P, N, U, T, C = m.attrs.POSITION, m.attrs.NORMAL, m.attrs.TEXCOORD_0, m.attrs.TANGENT, m.attrs.COLOR_0 + local col = nil + if C then + local scale = if C.raw then 1 else 255 + local white = true + col = buffer.create(nv * 4) + for i, src in order do + for k = 0, 3 do + local v = math.clamp(math.floor(num(C, src, k, if C.raw then 255 else 1) * scale + 0.5), 0, 255) + writeu8(col, (i - 1) * 4 + k, v) + if v ~= 255 then + white = false + end + end + end + if white then + col = nil + end + end + for i, src in order do + local o = i - 1 + for k = 0, 2 do + writef32(pos, o * 12 + k * 4, num(P, src, k, 0)) + end + if N then + for k = 0, 2 do + writef32(nb, o * 12 + k * 4, num(N, src, k, 0)) + end + elseif nrm then + buffer.copy(nb, o * 12, nrm, src * 12, 12) + end + writef32(uv, o * 8, num(U, src, 0, 0)) + writef32(uv, o * 8 + 4, num(U, src, 1, 0)) + if T then + for k = 0, 3 do + local v = math.clamp(math.floor(num(T, src, k, if k == 3 then 1 else 0) * 127 + 0.5), -127, 127) + writeu8(tan, o * 4 + k, v % 256) + end + else + buffer.writeu32(tan, o * 4, 0x7F810000) + end + end + r.pos, r.nrm, r.uv, r.tan, r.col, r.numVerts = pos, nb, uv, tan, col, nv +end + +function RobloxMesh.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + local version = opts and opts.version or "2.00" + if version ~= "2.00" and version ~= "4.00" then + return nil, Err.new(Err.ARG, "version must be \"2.00\" or \"4.00\"") + end + if type(scene) ~= "table" or type(scene.meshes) ~= "table" then + return nil, Err.new(Err.ARG, "expected a Scene") + end + local keep = { NORMAL = true, TEXCOORD_0 = true, TANGENT = true, COLOR_0 = true, JOINTS_0 = true, WEIGHTS_0 = true } + local m, merr = Flatten.merge(scene, function(name: string): boolean + return keep[name] == true + end, { triangulate = true }) + if not m then + return nil, Err.new(Err.ARG, tostring(merr)) + end + local corners = m.corners + if not m.sizes or #corners == 0 then + return nil, Err.new(Err.ARG, "no triangles to write") + end + local nv0 = m.count + if nv0 > 2 ^ 32 - 1 then + return nil, Err.new(Err.LIMIT, "too many vertices") + end + local r: Parse.Record = { + version = version, + numVerts = 0, + numFaces = #corners // 3, + pos = buffer.create(0), + nrm = buffer.create(0), + uv = buffer.create(0), + faces = buffer.create(0), + lods = {}, + lodType = 0, + highQualityLods = 0, + bones = {}, + subsets = {}, + facsFormat = 0, + chunks = {}, + } + local src = if type(scene.meta) == "table" and type(scene.meta.source) == "table" and scene.meta.source.format == "robloxmesh" then scene.meta.source else nil + if src and type(src.lodType) == "number" then + r.lodType, r.highQualityLods = src.lodType, if type(src.highQualityLods) == "number" then src.highQualityLods else 0 + end + local nrm: buffer? = nil + if not m.attrs.NORMAL then + local pb = buffer.create(nv0 * 12) + for i = 0, nv0 - 1 do + for k = 0, 2 do + writef32(pb, i * 12 + k * 4, num(m.attrs.POSITION, i, k, 0)) + end + end + nrm = normals(pb, nv0, corners) + end + local skin = nil + if version == "4.00" and m.attrs.JOINTS_0 and m.attrs.WEIGHTS_0 then + for _, n in scene.nodes or {} do + if n.mesh and n.skin and scene.skins and scene.skins[n.skin] then + skin = scene.skins[n.skin] + break + end + end + end + local nf = #corners // 3 + if skin then + local bones, berr = skinBones(scene, skin) + if not bones then + return nil, Err.new(Err.ARG, berr or "bad skin") + end + r.bones = bones + local J, W = m.attrs.JOINTS_0, m.attrs.WEIGHTS_0 + local wscale = if W.raw then 1 / 255 else 1 + local nb = #bones + local influences: { { { number } } } = table.create(nv0) :: any + for v = 0, nv0 - 1 do + local list = {} + for k = 0, 3 do + local wt = num(W, v, k, 0) * wscale + local j = num(J, v, k, 0) + if wt > 0 and j >= 0 and j < nb then + table.insert(list, { j, wt }) + end + end + influences[v + 1] = list + end + -- subsets: a new subset when a face's joints do not fit in 26 + local faceIdx = buffer.create(nf * 12) + local order: { number } = {} + local s: any = nil + local function close() + if s then + table.insert(r.subsets, { facesBegin = s.facesBegin, facesLength = s.faceCount, vertsBegin = s.vertsBegin, vertsLength = #order - s.vertsBegin, bones = s.bones }) + end + end + local function open(f: number) + s = { facesBegin = f, faceCount = 0, vertsBegin = #order, bones = {}, local_ = {}, remap = {} } + end + open(0) + for f = 0, nf - 1 do + local need = {} + local extra = 0 + for c = 1, 3 do + for _, inf in influences[corners[f * 3 + c] + 1] do + if s.local_[inf[1]] == nil and not need[inf[1]] then + need[inf[1]] = true + extra += 1 + end + end + end + if #s.bones + extra > 26 then + close() + open(f) + for c = 1, 3 do + for _, inf in influences[corners[f * 3 + c] + 1] do + need[inf[1]] = true + end + end + end + for j in need do + if s.local_[j] == nil then + table.insert(s.bones, j) + s.local_[j] = #s.bones - 1 + end + end + for c = 1, 3 do + local v = corners[f * 3 + c] + local nvx = s.remap[v] + if not nvx then + table.insert(order, v) + nvx = #order - 1 + s.remap[v] = nvx + end + buffer.writeu32(faceIdx, f * 12 + (c - 1) * 4, nvx) + end + s.faceCount += 1 + end + close() + r.faces = faceIdx + fill(r, m, order, nrm) + -- envelopes: subset-local bone indices, weights summing to 255 + local env = buffer.create(#order * 8) + for _, sub in r.subsets do + local loc: { [number]: number } = {} + for i, j in sub.bones do + loc[j] = i - 1 + end + for o = sub.vertsBegin, sub.vertsBegin + sub.vertsLength - 1 do + local list = influences[order[o + 1] + 1] + local total = 0 + for _, inf in list do + total += inf[2] + end + local bytes, sum, best = {}, 0, 1 + for k, inf in list do + local b = if total > 0 then math.floor(inf[2] / total * 255 + 0.5) else 0 + bytes[k] = b + sum += b + if inf[2] > list[best][2] then + best = k + end + end + if #list > 0 then + bytes[best] += 255 - sum + end + for k = 0, 3 do + local inf = list[k + 1] + writeu8(env, o * 8 + k, if inf then loc[inf[1]] or 0 else 0) + writeu8(env, o * 8 + 4 + k, if inf then math.clamp(bytes[k + 1], 0, 255) else 0) + end + end + end + r.env = env + r.lods = { 0, nf } + else + local order = table.create(nv0, 0) + for i = 1, nv0 do + order[i] = i - 1 + end + fill(r, m, order, nrm) + local faces = buffer.create(nf * 12) + for i, c in corners do + buffer.writeu32(faces, (i - 1) * 4, c) + end + r.faces = faces + r.lods = { 0, nf } + local part = m.parts[1] + local mesh = part and part.mesh + local lods = if #m.parts == 1 and part.identity and mesh and type(mesh.extras) == "table" then mesh.extras.lods else nil + if version == "4.00" and type(lods) == "table" and #lods > 0 then + local list = {} + for _, lp in lods do + local idx = if type(lp) == "table" and lp.indices then Flatten.numbers(lp.indices) else nil + if idx and #idx % 3 == 0 then + table.insert(list, idx) + end + end + local total = nf + for _, idx in list do + total += #idx // 3 + end + local all = buffer.create(total * 12) + buffer.copy(all, 0, faces, 0, nf * 12) + local at = nf + for _, idx in list do + for i, c in idx do + if c >= nv0 then + return nil, Err.new(Err.ARG, "a LOD index is out of range") + end + buffer.writeu32(all, at * 12 + (i - 1) * 4, c) + end + at += #idx // 3 + table.insert(r.lods, at) + end + r.faces, r.numFaces = all, total + end + end + return Write.write(r, version), nil +end + +return RobloxMesh +end +__FILES["model/robloxmesh/Parse"] = @native function() + + + +-- model/robloxmesh/Parse: FileMesh bytes to a flat record, little endian, 1.00 - 7.00 (MaximumADHD's "Roblox Mesh +-- Format", devforum 326114); a Draco COREMESH v2 goes through the lim.core callback. Never throws. +local Parse = {} + +local readu8, readu16, readu32, readf32, readstring = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readf32, buffer.readstring +local writef32, writeu32 = buffer.writef32, buffer.writeu32 + +type Bone = { name: string, parent: number?, lodParent: number, culling: number, cf: { number } } -- cf: r00..r22, x, y, z +type Subset = { facesBegin: number, facesLength: number, vertsBegin: number, vertsLength: number, bones: { number } } +type Record = { + version: string, + numVerts: number, + numFaces: number, + pos: buffer, -- f32 x3 + nrm: buffer, -- f32 x3 + uv: buffer, -- f32 x2 + tan: buffer?, -- i8 x4 (nil in version 1) + col: buffer?, -- u8 x4 (nil when the vertices have none) + faces: buffer, -- u32 x3 + lods: { number }, + lodType: number, + highQualityLods: number, + bones: { Bone }, + subsets: { Subset }, + env: buffer?, -- per vertex: 4 subset-local bone indices, 4 weights (u8) + facsFormat: number, + facs: buffer?, + chunks: { { name: string, version: number, data: buffer } }, -- 6.00+ chunks kept raw (HSRAVIS, unknown) + coreVersion: number?, -- 6.00+: 2 when the COREMESH was Draco-compressed +} + +type Core = { numVerts: number, pos: buffer, nrm: buffer, uv: buffer, tan: buffer?, col: buffer?, numFaces: number, faces: buffer } +type Limits = { maxVertices: number, maxFaces: number, core: ((b: buffer, off: number, len: number) -> (Core?, string?))? } + +@native local function record(version: string): Record + return { + version = version, + numVerts = 0, + numFaces = 0, + pos = buffer.create(0), + nrm = buffer.create(0), + uv = buffer.create(0), + tan = nil, + col = nil, + faces = buffer.create(0), + lods = {}, + lodType = 0, + highQualityLods = 0, + bones = {}, + subsets = {}, + env = nil, + facsFormat = 0, + facs = nil, + chunks = {}, + coreVersion = nil, + } +end + +-- ------------------------------------------------------------------------------------------------ version 1 +@native local function ascii(text: string, version: string, lim: Limits): (Record?, string?) + local nf = tonumber(string.match(text, "^[^\n]*\n%s*(%d+)")) + if not nf then + return nil, "corrupt: no face count" + end + if nf * 3 > lim.maxVertices or nf > lim.maxFaces then + return nil, "limit: " .. nf .. " faces" + end + local r = record(version) + local nv = nf * 3 + r.numVerts, r.numFaces = nv, nf + r.pos, r.nrm, r.uv = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8) + r.faces = buffer.create(nf * 12) + local scale = if version == "1.00" then 0.5 else 1 + local i = 0 + local vals = table.create(9, 0) + local k = 0 + local start = string.find(text, "[", 1, true) or (#text + 1) + for a, b, c in string.gmatch(string.sub(text, start), "%[%s*([^,%]]+)%s*,%s*([^,%]]+)%s*,%s*([^,%]]+)%s*%]") do + local x, y, z = tonumber(a), tonumber(b), tonumber(c) + if not x or not y or not z then + return nil, "corrupt: bad number in a vector" + end + vals[k * 3 + 1], vals[k * 3 + 2], vals[k * 3 + 3] = x, y, z + k += 1 + if k == 3 then + if i >= nv then + break + end + writef32(r.pos, i * 12, vals[1] * scale) + writef32(r.pos, i * 12 + 4, vals[2] * scale) + writef32(r.pos, i * 12 + 8, vals[3] * scale) + writef32(r.nrm, i * 12, vals[4]) + writef32(r.nrm, i * 12 + 4, vals[5]) + writef32(r.nrm, i * 12 + 8, vals[6]) + writef32(r.uv, i * 8, vals[7]) + writef32(r.uv, i * 8 + 4, 1 - vals[8]) -- version 1 stores V upside down + i += 1 + k = 0 + end + end + if i < nv then + return nil, "truncated: " .. i .. " of " .. nv .. " vertices" + end + for f = 0, nv - 1 do + writeu32(r.faces, f * 4, f) + end + r.lods = { 0, nf } + return r, nil +end + +-- ------------------------------------------------------------------------------------------------ binary parts +-- vertices of 36 / 40 bytes +@native local function vertices(b: buffer, p: number, n: number, vs: number, r: Record) + local pos, nrm, uv, tan = buffer.create(n * 12), buffer.create(n * 12), buffer.create(n * 8), buffer.create(n * 4) + local col = if vs >= 40 then buffer.create(n * 4) else nil + for i = 0, n - 1 do + local q = p + i * vs + buffer.copy(pos, i * 12, b, q, 12) + buffer.copy(nrm, i * 12, b, q + 12, 12) + buffer.copy(uv, i * 8, b, q + 24, 8) + buffer.copy(tan, i * 4, b, q + 32, 4) + if col then + buffer.copy(col, i * 4, b, q + 36, 4) + end + end + r.pos, r.nrm, r.uv, r.tan, r.col = pos, nrm, uv, tan, col + r.numVerts = n +end + +@native local function faces(b: buffer, p: number, n: number, fs: number, r: Record): string? + local out = buffer.create(n * 12) + local nv = r.numVerts + for i = 0, n - 1 do + for k = 0, 2 do + local v = readu32(b, p + i * fs + k * 4) + if v >= nv then + return "corrupt: face " .. i .. " uses vertex " .. v .. " of " .. nv + end + writeu32(out, i * 12 + k * 4, v) + end + end + r.faces, r.numFaces = out, n + return nil +end + +@native local function bones(b: buffer, p: number, n: number, names: string, r: Record) + for i = 0, n - 1 do + local q = p + i * 60 + local ni = readu32(b, q) + local name = string.match(string.sub(names, ni + 1), "^[^%z]*") or "" + local parent = readu16(b, q + 4) + local cf = table.create(12, 0) + for k = 0, 11 do + cf[k + 1] = readf32(b, q + 12 + 4 * k) + end + r.bones[i + 1] = { name = name, parent = if parent == 0xFFFF then nil else parent, lodParent = readu16(b, q + 6), culling = readf32(b, q + 8), cf = cf } + end +end + +@native local function subsets(b: buffer, p: number, n: number, r: Record) + for i = 0, n - 1 do + local q = p + i * 72 + local count = math.min(readu32(b, q + 16), 26) + local list = table.create(count, 0) + for k = 0, count - 1 do + list[k + 1] = readu16(b, q + 20 + 2 * k) + end + r.subsets[i + 1] = { facesBegin = readu32(b, q), facesLength = readu32(b, q + 4), vertsBegin = readu32(b, q + 8), vertsLength = readu32(b, q + 12), bones = list } + end +end + +@native local function lods(b: buffer, p: number, n: number, r: Record) + local out = table.create(n, 0) + for i = 0, n - 1 do + out[i + 1] = readu32(b, p + 4 * i) + end + r.lods = out +end + +-- ------------------------------------------------------------------------------------------------ versions 2 .. 5 +@native local function classic(b: buffer, p: number, e: number, version: string, lim: Limits): (Record?, string?) + local r = record(version) + local major = tonumber(string.sub(version, 1, 1)) or 0 + if p + 12 > e then + return nil, "truncated header" + end + local hs = readu16(b, p) + local nv: number, nf: number, vs: number, fs: number = 0, 0, 40, 12 + local nlod: number, nbones: number, namesSize: number, nsub: number = 0, 0, 0, 0 + if major == 2 or major == 3 then + vs = readu8(b, p + 2) + fs = readu8(b, p + 3) + if major == 2 then + nv = readu32(b, p + 4) + nf = readu32(b, p + 8) + else + if p + 16 > e then + return nil, "truncated header" + end + nlod = readu16(b, p + 6) + nv = readu32(b, p + 8) + nf = readu32(b, p + 12) + end + else + if p + 24 > e then + return nil, "truncated header" + end + r.lodType = readu16(b, p + 2) + nv = readu32(b, p + 4) + nf = readu32(b, p + 8) + nlod = readu16(b, p + 12) + nbones = readu16(b, p + 14) + namesSize = readu32(b, p + 16) + nsub = readu16(b, p + 20) + r.highQualityLods = readu8(b, p + 22) + if major >= 5 then + if p + 32 > e then + return nil, "truncated header" + end + r.facsFormat = readu32(b, p + 24) + end + end + if vs < 36 or fs < 12 then + return nil, "corrupt: vertex size " .. vs .. ", face size " .. fs + end + if nv > lim.maxVertices or nf > lim.maxFaces then + return nil, "limit: " .. nv .. " vertices, " .. nf .. " faces" + end + local q = p + hs + if q + nv * vs > e then + return nil, "truncated vertices" + end + vertices(b, q, nv, vs, r) + q += nv * vs + if nbones > 0 then + if q + nv * 8 > e then + return nil, "truncated skinning" + end + local env = buffer.create(nv * 8) + buffer.copy(env, 0, b, q, nv * 8) + r.env = env + q += nv * 8 + end + if q + nf * fs > e then + return nil, "truncated faces" + end + local ferr = faces(b, q, nf, fs, r) + if ferr then + return nil, ferr + end + q += nf * fs + if q + nlod * 4 > e then + return nil, "truncated LOD offsets" + end + lods(b, q, nlod, r) + q += nlod * 4 + if q + nbones * 60 + namesSize + nsub * 72 > e then + return nil, "truncated bones / subsets" + end + local names = readstring(b, q + nbones * 60, namesSize) + bones(b, q, nbones, names, r) + q += nbones * 60 + namesSize + subsets(b, q, nsub, r) + q += nsub * 72 + if major >= 5 then + local size = readu32(b, p + 28) + if size > 0 then + if q + size > e then + return nil, "truncated FACS data" + end + local facs = buffer.create(size) + buffer.copy(facs, 0, b, q, size) + r.facs = facs + end + end + if #r.lods == 0 then + r.lods = { 0, nf } + end + return r, nil +end + +-- ------------------------------------------------------------------------------------------------ versions 6 / 7 +@native local function chunked(b: buffer, p: number, e: number, version: string, lim: Limits): (Record?, string?) + local r = record(version) + local core = false + while p < e do + if p + 16 > e then + return nil, "truncated chunk header" + end + local name = string.gsub(readstring(b, p, 8), "%z+$", "") + local cv, size = readu32(b, p + 8), readu32(b, p + 12) + local q = p + 16 + local ce = q + size + if ce > e then + return nil, "truncated chunk " .. name + end + if name == "COREMESH" then + if cv == 2 then + local decodeCore = lim.core + if not decodeCore then + return nil, "unsupported: Draco-compressed COREMESH" + end + local c, cerr = decodeCore(b, q, size) + if not c then + return nil, cerr or "corrupt: bad Draco COREMESH" + end + if c.numVerts > lim.maxVertices or c.numFaces > lim.maxFaces then + return nil, "limit: " .. c.numVerts .. " vertices, " .. c.numFaces .. " faces" + end + r.numVerts, r.pos, r.nrm, r.uv, r.tan, r.col = c.numVerts, c.pos, c.nrm, c.uv, c.tan, c.col + r.numFaces, r.faces = c.numFaces, c.faces + core = true + r.coreVersion = 2 + elseif cv ~= 1 then + return nil, "unsupported: COREMESH version " .. cv + else + if q + 4 > ce then + return nil, "truncated COREMESH" + end + local nv = readu32(b, q) + if nv > lim.maxVertices then + return nil, "limit: " .. nv .. " vertices" + end + if q + 4 + nv * 40 + 4 > ce then + return nil, "truncated COREMESH vertices" + end + vertices(b, q + 4, nv, 40, r) + local fq = q + 4 + nv * 40 + local nf = readu32(b, fq) + if nf > lim.maxFaces then + return nil, "limit: " .. nf .. " faces" + end + if fq + 4 + nf * 12 > ce then + return nil, "truncated COREMESH faces" + end + local ferr = faces(b, fq + 4, nf, 12, r) + if ferr then + return nil, ferr + end + core = true + end + elseif name == "LODS" and cv == 1 then + if q + 7 > ce then + return nil, "truncated LODS" + end + r.lodType = readu16(b, q) + r.highQualityLods = readu8(b, q + 2) + local n = readu32(b, q + 3) + if q + 7 + n * 4 > ce then + return nil, "truncated LODS" + end + lods(b, q + 7, n, r) + elseif name == "SKINNING" and cv == 1 then + if not core then + return nil, "corrupt: SKINNING before COREMESH" + end + if q + 4 > ce then + return nil, "truncated SKINNING" + end + local ns = readu32(b, q) + local s = q + 4 + if ns ~= r.numVerts or s + ns * 8 + 4 > ce then + return nil, "corrupt: SKINNING count" + end + local env = buffer.create(ns * 8) + buffer.copy(env, 0, b, s, ns * 8) + r.env = env + s += ns * 8 + local nb = readu32(b, s) + s += 4 + if s + nb * 60 + 4 > ce then + return nil, "truncated SKINNING bones" + end + local bq = s + s += nb * 60 + local namesSize = readu32(b, s) + s += 4 + if s + namesSize + 4 > ce then + return nil, "truncated SKINNING names" + end + bones(b, bq, nb, readstring(b, s, namesSize), r) + s += namesSize + local nsub = readu32(b, s) + s += 4 + if s + nsub * 72 > ce then + return nil, "truncated SKINNING subsets" + end + subsets(b, s, nsub, r) + if nb == 0 then + r.env = nil + end + elseif name == "FACS" and cv == 1 then + if q + 4 > ce then + return nil, "truncated FACS" + end + local size = readu32(b, q) + if q + 4 + size > ce then + return nil, "truncated FACS" + end + local facs = buffer.create(size) + buffer.copy(facs, 0, b, q + 4, size) + r.facs, r.facsFormat = facs, 1 + else + local data = buffer.create(size) + buffer.copy(data, 0, b, q, size) + table.insert(r.chunks, { name = name, version = cv, data = data }) + end + p = ce + end + if not core then + return nil, "corrupt: no COREMESH chunk" + end + if #r.lods == 0 then + r.lods = { 0, r.numFaces } + end + return r, nil +end + +@native function Parse.parse(b: buffer, p: number, e: number, lim: Limits): (Record?, string?) + if e - p < 13 then + return nil, "truncated: no version line" + end + local line = readstring(b, p, 12) + local version = string.match(line, "^version (%d%.%d%d)$") + if not version or readu8(b, p + 12) ~= 10 and readu8(b, p + 12) ~= 13 then + return nil, "corrupt: bad version line" + end + local q = p + 13 + if readu8(b, p + 12) == 13 and q < e and readu8(b, q) == 10 then + q += 1 + end + local major = string.sub(version, 1, 1) + if major == "1" then + return ascii(readstring(b, p, e - p), version, lim) + elseif major == "2" or major == "3" or major == "4" or major == "5" then + return classic(b, q, e, version, lim) + elseif major == "6" or major == "7" then + return chunked(b, q, e, version, lim) + end + return nil, "unsupported: version " .. version +end + +-- packed tangent: signed bytes / 127 +@native local function snorm(v: number): number + local x = if v >= 128 then v - 256 else v + return math.clamp(x / 127, -1, 1) +end +@native function Parse.tangent(tan: buffer, i: number): (number, number, number, number) + return snorm(readu8(tan, i * 4)), snorm(readu8(tan, i * 4 + 1)), snorm(readu8(tan, i * 4 + 2)), snorm(readu8(tan, i * 4 + 3)) +end + +return Parse +end +__FILES["model/robloxmesh/Write"] = @native function() + + + +-- model/robloxmesh/Write: a flat record to FileMesh 2.00 (header, 36- or 40-byte vertices, faces) or 4.00 (24-byte +-- header, 40-byte vertices, skinning, faces, LOD offsets, bones, bone names, subsets). Never throws. +local Parse = __include("model/robloxmesh/Parse") +local Bytes = __include("core/Bytes") + +local Write = {} + +@native local function vertex(w: Bytes.Writer, r: Parse.Record, i: number, colors: boolean) + local p = w:reserve(if colors then 40 else 36) + local b = w.buf + buffer.copy(b, p, r.pos, i * 12, 12) + buffer.copy(b, p + 12, r.nrm, i * 12, 12) + buffer.copy(b, p + 24, r.uv, i * 8, 8) + if r.tan then + buffer.copy(b, p + 32, r.tan, i * 4, 4) + else + buffer.writeu32(b, p + 32, 0x7F810000) -- (0, 0, -1, 1) + end + if colors then + if r.col then + buffer.copy(b, p + 36, r.col, i * 4, 4) + else + buffer.writeu32(b, p + 36, 0xFFFFFFFF) + end + end + w.pos = p + (if colors then 40 else 36) +end + +@native function Write.write(r: Parse.Record, version: string): buffer + local nv, nf = r.numVerts, r.numFaces + local w = Bytes.writer(64 + nv * 48 + nf * 12) + w:string("version " .. version .. "\n") + if version == "2.00" then + local colors = r.col ~= nil + w:u16le(12) + w:u8(if colors then 40 else 36) + w:u8(12) + w:u32le(nv) + w:u32le(nf) + for i = 0, nv - 1 do + vertex(w, r, i, colors) + end + w:bytes(r.faces, 0, nf * 12) + return w:finish() + end + -- 4.00 + local names = {} + local nameAt = {} + local size = 0 + for i, bone in r.bones do + nameAt[i] = size + table.insert(names, bone.name .. "\0") + size += #bone.name + 1 + end + local nb = #r.bones + w:u16le(24) + w:u16le(r.lodType) + w:u32le(nv) + w:u32le(nf) + w:u16le(#r.lods) + w:u16le(nb) + w:u32le(size) + w:u16le(#r.subsets) + w:u8(r.highQualityLods) + w:u8(0) + for i = 0, nv - 1 do + vertex(w, r, i, true) + end + if nb > 0 then + local env = r.env + if env then + w:bytes(env, 0, nv * 8) + else + w:fill(0, nv * 8) + end + end + w:bytes(r.faces, 0, nf * 12) + for _, o in r.lods do + w:u32le(o) + end + for i, bone in r.bones do + w:u32le(nameAt[i]) + w:u16le(if bone.parent then bone.parent else 0xFFFF) + w:u16le(bone.lodParent) + w:f32le(bone.culling) + for k = 1, 12 do + w:f32le(bone.cf[k] or 0) + end + end + w:string(table.concat(names)) + for _, s in r.subsets do + w:u32le(s.facesBegin) + w:u32le(s.facesLength) + w:u32le(s.vertsBegin) + w:u32le(s.vertsLength) + w:u32le(#s.bones) + for k = 1, 26 do + w:u16le(s.bones[k] or 0xFFFF) + end + end + return w:finish() +end + +return Write +end +__FILES["model/schematic"] = function() + +-- model/schematic: Minecraft schematics, read + write: MCEdit / WorldEdit .schematic (pre-1.13), Sponge .schem v1-3 +-- (WorldEdit 7+) and Litematica .litematic. Not supported: block properties to pre-1.13 data values, Sponge biome +-- conversion between versions, rotated nodes. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Nbt = __include("codecs/text/Nbt") +local Mc = __include("codecs/model/Minecraft") +local Common = __include("model/schematic/Common") +local Mcedit = __include("model/schematic/Mcedit") +local Sponge = __include("model/schematic/Sponge") +local Litematic = __include("model/schematic/Litematic") + +-- ------------------------------------------------------------------------------------------------ contract +local Schematic = { + name = "schematic", + category = "model", + extensions = { "schem", "schematic", "litematic" }, + mime = { "application/x-minecraft-schematic" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Nbt", "codecs/model/Minecraft" }, + caps = { decode = true, encode = true, voxels = true, blocks = true, variants = { "schem", "schematic", "litematic" } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + maxCells: number?, -- default 2^26 + maxBytes: number?, -- default 2^28 +} +type EncodeOptions = { + variant: ("schem" | "schematic" | "litematic")?, -- default: the extension of opts.name, the source's, else "schem" + version: number?, -- Sponge default 3, Litematica default 6 (or the source's) + dataVersion: number?, -- default the source's, else 3953 = 1.21 + name: string?, + title: string?, + compression: ("gzip" | "zlib" | "none")?, -- default gzip, as every tool writes them + level: number?, + format: string?, +} + +-- ------------------------------------------------------------------------------------------------ constants +local DEFAULT_DATA_VERSION = 3953 +local LITEMATIC_HINTS = { "Regions", "EnclosingSize", "RegionCount", "TotalVolume", "MinecraftDataVersion" } +local SPONGE_HINTS = { "BlockData", "PaletteMax" } -- v1 / v2 fields (some writers leave the root unnamed) + +local function hinted(head: string, hints: { string }): boolean + for _, h in hints do + if string.find(head, string.char(0, #h) .. h, 1, true) then + return true + end + end + return false +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Schematic.sniff(r: Bytes.Reader): number + local p = Nbt.peek(r.buf, r.base, r.limit - r.base) + if not p or p.rootType ~= "compound" or p.endian ~= "big" then + return 0 + end + if p.name == "Schematic" or (p.firstName == "Schematic" and p.firstType == "compound") then + return 1 + end + local head = buffer.tostring(p.head) + return if hinted(head, LITEMATIC_HINTS) or hinted(head, SPONGE_HINTS) then 1 else 0 +end + +function Schematic.variant(r: Bytes.Reader): string? + local p = Nbt.peek(r.buf, r.base, r.limit - r.base) + if not p then + return nil + end + if p.firstName == "Schematic" then + return "schem" + end + local head = buffer.tostring(p.head) + if hinted(head, LITEMATIC_HINTS) then + return "litematic" + elseif hinted(head, SPONGE_HINTS) or (p.name == "Schematic" and hinted(head, { "Palette", "Version" })) then + return "schem" + end + return if p.name == "Schematic" then "schematic" else nil +end + +-- ------------------------------------------------------------------------------------------------ decode +local function variantOf(root: any): (string?, any) + if type(root) ~= "table" or not Types.isObject(root) then + return nil, nil + end + if Types.isObject(root.Regions) then + return "litematic", root + end + if Types.isObject(root.Schematic) and (Common.int(root.Schematic.Version) or 0) >= 3 then + return "schem", root.Schematic + end + if root.Version ~= nil and (root.Palette ~= nil or root.BlockData ~= nil) then + return "schem", root + end + if type(root.Blocks) == "buffer" then + return "schematic", root + end + return nil, nil +end + +function Schematic.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local o: DecodeOptions = opts or {} + local root, info = Nbt.decode(r.buf, { maxBytes = o.maxBytes, endian = "big" }, r.base, r.limit - r.base) + if root == nil then + return nil, info + end + local variant, s = variantOf(root) + if not variant then + return nil, Err.new(Err.CORRUPT, "not a schematic (no Regions, Schematic / Palette or Blocks)") + end + local maxCells = o.maxCells or 2 ^ 26 + local regions, extra + if variant == "litematic" then + regions, extra = Litematic.read(s, maxCells) + elseif variant == "schem" then + regions, extra = Sponge.read(s, maxCells) + else + regions, extra = Mcedit.read(s, maxCells) + end + if not regions then + local msg = tostring(extra) + return nil, Err.from(msg, nil, if string.find(msg, "limit: ", 1, true) then "limit" else nil) + end + local scene = Types.Scene.new() + scene.voxels = {} + for i, reg in regions do + local v = Mc.voxels(reg.size[1], reg.size[2], reg.size[3], reg.states, reg.indices) + v.name = reg.name + local b = v.blocks :: Types.VoxelBlocks + b.blockEntities = reg.blockEntities + b.entities = reg.entities + table.insert(scene.voxels :: { Types.Voxels }, v) + table.insert(scene.nodes, { name = reg.name, children = {}, voxels = i, translation = { reg.position[1], reg.position[2], reg.position[3] } }) + table.insert(scene.roots, #scene.nodes) + end + scene.meta.up = "y" + scene.meta.unit = 1 + local src: { [string]: any } = { format = "schematic", variant = variant, nbt = root, rootName = info.name, compression = info.compression } + for k, v in extra do + src[k] = v + end + scene.meta.source = src :: any + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function regionsOf(value: any): ({ Common.Region }?, string?) + local out: { Common.Region } = {} + local function add(v: Types.Voxels, pos: { number }, name: string?): string? + if type(v) ~= "table" or type(v.size) ~= "table" or type(v.data) ~= "buffer" then + return "expected Types.Voxels grids" + end + local states, indices = Mc.blocksOf(v) + if not states then + return indices + end + local b = v.blocks + table.insert(out, { + name = name or v.name, + size = { v.size[1], v.size[2], v.size[3] }, + position = { math.floor(pos[1] + 0.5), math.floor(pos[2] + 0.5), math.floor(pos[3] + 0.5) }, + states = states, + indices = indices, + blockEntities = if b and b.blockEntities then b.blockEntities else {}, + entities = if b and b.entities then b.entities else {}, + }) + return nil + end + if type(value) == "table" and value.kind == "voxels" then + local e = add(value, { 0, 0, 0 }, nil) + return if e then nil else out, e + end + if type(value) ~= "table" or value.kind ~= "scene" or type(value.voxels) ~= "table" or #value.voxels == 0 then + return nil, "expected a Scene with voxels or a Types.Voxels" + end + local placed = false + local function walk(i: number, base: { number }, depth: number): string? + local node = value.nodes[i] + if type(node) ~= "table" or depth > 64 then + return nil + end + local t = node.translation or { 0, 0, 0 } + local p = { base[1] + (t[1] or 0), base[2] + (t[2] or 0), base[3] + (t[3] or 0) } + if node.voxels and value.voxels[node.voxels] then + placed = true + local e = add(value.voxels[node.voxels], p, node.name) + if e then + return e + end + end + for _, c in node.children or {} do + local e = walk(c, p, depth + 1) + if e then + return e + end + end + return nil + end + for _, root in value.roots or {} do + local e = walk(root, { 0, 0, 0 }, 0) + if e then + return nil, e + end + end + if not placed then + for _, v in value.voxels do + local e = add(v, { 0, 0, 0 }, nil) + if e then + return nil, e + end + end + end + return out, nil +end + +local function merge(regions: { Common.Region }): Common.Region + if #regions == 1 then + return regions[1] + end + local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge } + for _, r in regions do + for k = 1, 3 do + lo[k] = math.min(lo[k], r.position[k]) + hi[k] = math.max(hi[k], r.position[k] + r.size[k]) + end + end + local sx, sy, sz = hi[1] - lo[1], hi[2] - lo[2], hi[3] - lo[3] + local states = { "minecraft:air" } + local out = buffer.create(sx * sy * sz * 2) + local bes, ents = {}, {} + for _, r in regions do + local base = #states + for _, st in r.states do + table.insert(states, st) + end + local rx, ry, rz = r.size[1], r.size[2], r.size[3] + local ox, oy, oz = r.position[1] - lo[1], r.position[2] - lo[2], r.position[3] - lo[3] + for z = 0, rz - 1 do + for y = 0, ry - 1 do + local s = (rx * (y + ry * z)) * 2 + local d = (ox + sx * ((oy + y) + sy * (oz + z))) * 2 + for _ = 0, rx - 1 do + buffer.writeu16(out, d, buffer.readu16(r.indices, s) + base) + s += 2 + d += 2 + end + end + end + for _, be in r.blockEntities do + table.insert(bes, { pos = { be.pos[1] + ox, be.pos[2] + oy, be.pos[3] + oz }, id = be.id, data = be.data }) + end + for _, e in r.entities do + table.insert(ents, e) + end + end + local st, idx = Common.dedupe(states, out, sx * sy * sz) + return { name = regions[1].name, size = { sx, sy, sz }, position = lo, states = st, indices = idx, blockEntities = bes, entities = ents } +end + +function Schematic.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local regions, rerr = regionsOf(value) + if not regions then + return nil, Err.new(Err.ARG, tostring(rerr)) + end + local src = if type(value) == "table" and type(value.meta) == "table" and type(value.meta.source) == "table" and value.meta.source.format == "schematic" then value.meta.source else nil + local ext = if o.name then string.lower(string.match(o.name, "%.([%w]+)$") or "") else nil + local key = o.format and string.lower(o.format) + local variant = o.variant + or (if ext == "schem" or ext == "schematic" or ext == "litematic" then ext else nil) + or (if key == "schem" or key == "litematic" then key else nil) + or (src and src.variant) + or "schem" + if variant ~= "schem" and variant ~= "schematic" and variant ~= "litematic" then + return nil, Err.new(Err.ARG, "unknown variant " .. tostring(variant)) + end + local same = src ~= nil and src.variant == variant + local base = if same then (src :: any).nbt else nil + local dataVersion = o.dataVersion or (src and src.dataVersion) or DEFAULT_DATA_VERSION + local root, rootName, e + if variant == "litematic" then + local version = o.version or (if same then (src :: any).version else nil) or 6 + local title = o.title or (if o.name then string.match(o.name, "([^/\\]-)%.[%w]+$") else nil) + root, e = Litematic.write(regions, version, dataVersion, base, title) + rootName = "" + elseif variant == "schem" then + local version = o.version or (if same then (src :: any).version else nil) or 3 + if version ~= 1 and version ~= 2 and version ~= 3 then + return nil, Err.new(Err.ARG, "Sponge schematic version must be 1, 2 or 3") + end + local sameVersion = same and (src :: any).version == version + local inner = if sameVersion and base then (if version >= 3 then base.Schematic else base) else nil + local sch + sch, e = Sponge.write(merge(regions), version, dataVersion, inner) + if sch and version >= 3 then + root, rootName = Common.merge(if sameVersion then base else nil, { { "Schematic", sch } }), "" + else + root, rootName = sch, "Schematic" + end + else + root, e = Mcedit.write(merge(regions), base) + rootName = "Schematic" + end + if not root then + return nil, Err.new(Err.ARG, tostring(e)) + end + if same and (src :: any).rootName ~= nil then + rootName = (src :: any).rootName + end + return Nbt.encode(root, { name = rootName, endian = "big", compression = o.compression or "gzip", level = o.level }) +end + +return Schematic +end +__FILES["model/schematic/Common"] = function() + +-- model/schematic/Common: shared region record, NBT access and block entities as Sponge v3's { pos = { x, y, z }, id, +-- data } (MCEdit / Litematica use flat { x, y, z, id, ... }, Sponge v2 { Pos, Id, ... }). +local Types = __include("Types") +local Nbt = __include("codecs/text/Nbt") +local Mc = __include("codecs/model/Minecraft") + +local Common = {} + +-- a block region: u16 indices per cell in Types.Voxels order (x fastest, then y, then z) into states +type Region = { + name: string?, + size: { number }, + position: { number }, -- relative to the schematic origin + states: { string }, + indices: buffer, + blockEntities: { any }, + entities: { any }, +} + +Common.int = Mc.int + +function Common.dims(a: any, b: any, c: any, max: number): (number?, any, number?) + local x, y, z = Common.int(a), Common.int(b), Common.int(c) + if not x or not y or not z then + return nil, "missing or non-integer size", nil + end + if x < 0 or y < 0 or z < 0 then + return nil, "negative size", nil + end + if x * y * z > max then + return nil, "limit: " .. x .. " x " .. y .. " x " .. z .. " cells is over maxCells", nil + end + return x, y, z +end + +Common.ints = Mc.ints + +Common.blockEntity = Mc.blockEntity +Common.flatBlockEntity = Mc.flatBlockEntity + +function Common.list(v: any): { any } + if type(v) == "table" and not Nbt.isTag(v) and not Types.isObject(v) then + return v + end + return {} +end + +function Common.compound(fields: { { any } }): { [string]: any } + local o, keys = {}, {} + for _, kv in fields do + if kv[2] ~= nil then + o[kv[1]] = kv[2] + table.insert(keys, kv[1]) + end + end + return Types.object(o, keys) +end + +function Common.merge(base: any, fields: { { any } }, drop: { [string]: boolean }?): { [string]: any } + if type(base) ~= "table" or not Types.isObject(base) then + return Common.compound(fields) + end + local mine: { [string]: any } = {} + local present: { [string]: boolean } = {} + for _, kv in fields do + present[kv[1]] = true + mine[kv[1]] = kv[2] + end + local out = {} + for _, k in Types.keys(base) do + if present[k] then + if mine[k] ~= nil then + table.insert(out, { k, mine[k] }) + end + elseif not (drop and drop[k]) then + table.insert(out, { k, base[k] }) + end + end + local seen: { [string]: boolean } = {} + for _, kv in out do + seen[kv[1]] = true + end + for _, kv in fields do + if not seen[kv[1]] and kv[2] ~= nil then + table.insert(out, kv) + end + end + return Common.compound(out) +end + +function Common.dedupe(states: { string }, indices: buffer, n: number): ({ string }, buffer) + local first: { [string]: number } = {} + local remap: { number } = {} + local out: { string } = {} + local dup = false + for i, s in states do + local at = first[s] + if at == nil then + table.insert(out, s) + at = #out - 1 + first[s] = at + else + dup = true + end + remap[i] = at + end + if not dup then + return states, indices + end + local res = buffer.create(n * 2) + for i = 0, n - 1 do + buffer.writeu16(res, i * 2, remap[buffer.readu16(indices, i * 2) + 1] or 0) + end + return out, res +end + +return Common +end +__FILES["model/schematic/Litematic"] = function() + +-- model/schematic/Litematic: .litematic, from LitematicaSchematic / LitematicaBitArray as documented by litemapy: +-- Metadata, named Regions (Position, Size may be negative), palette (0 = air), BlockStates spanning longs (>= 2 bits), +-- TileEntities relative to the region's minimum corner, Entities and pending ticks. +local Types = __include("Types") +local Nbt = __include("codecs/text/Nbt") +local Mc = __include("codecs/model/Minecraft") +local Common = __include("model/schematic/Common") + +local Litematic = {} + +local Packed = Mc.Packed + +local function xyz(c: any): { number }? + if type(c) ~= "table" then + return nil + end + local x, y, z = Common.int(c.x), Common.int(c.y), Common.int(c.z) + if not x or not y or not z then + return nil + end + return { x, y, z } +end + +local function vec(v: { number }): any + return Common.compound({ { "x", v[1] }, { "y", v[2] }, { "z", v[3] } }) +end + +function Litematic.read(root: any, maxCells: number): ({ Common.Region }?, any) + if not Types.isObject(root.Regions) then + return nil, "no Regions" + end + local out: { Common.Region } = {} + local total = 0 + local raw: { [string]: any } = {} + for _, name in Types.keys(root.Regions) do + local reg = root.Regions[name] + if type(reg) ~= "table" then + return nil, "region " .. name .. " is not a compound" + end + local pos, size = xyz(reg.Position), xyz(reg.Size) + if not pos or not size then + return nil, "region " .. name .. ": no Position / Size" + end + local ax, ay, az = math.abs(size[1]), math.abs(size[2]), math.abs(size[3]) + local sx, sy, sz = Common.dims(ax, ay, az, maxCells - total) + if not sx then + return nil, "region " .. name .. ": " .. tostring(sy) + end + total += ax * ay * az + local states: { string } = {} + for i, c in Common.list(reg.BlockStatePalette) do + local st = Mc.stateFromNbt(c) + if not st then + return nil, "region " .. name .. ": bad palette entry " .. i + end + states[i] = st + end + if #states == 0 then + states[1] = "minecraft:air" + end + local n = ax * ay * az + local yzx = buffer.create(n * 2) + local bs = reg.BlockStates + if n > 0 then + if not (Nbt.isTag(bs) and bs.type == "longArray") then + return nil, "region " .. name .. ": no BlockStates" + end + local bits = Packed.bitsFor(#states, 2) + local ok, e = Packed.unpack(bs.value, bits, n, true, yzx, #states) + if not ok then + return nil, "region " .. name .. ": " .. tostring(e) + end + end + local bes = {} + for _, c in Common.list(reg.TileEntities) do + local be = Common.blockEntity(c, "flat") + if be then + table.insert(bes, be) + end + end + table.insert(out, { + name = name, + size = { ax, ay, az }, + position = { + pos[1] + (if size[1] < 0 then size[1] + 1 else 0), + pos[2] + (if size[2] < 0 then size[2] + 1 else 0), + pos[3] + (if size[3] < 0 then size[3] + 1 else 0), + }, + states = states, + indices = Packed.fromYzx(yzx, ax, ay, az), + blockEntities = bes, + entities = Common.list(reg.Entities), + }) + raw[name] = reg + end + return out, { + version = Common.int(root.Version), + subVersion = Common.int(root.SubVersion), + dataVersion = Common.int(root.MinecraftDataVersion), + metadata = root.Metadata, + regions = raw, + } +end + +function Litematic.write(regions: { Common.Region }, version: number, dataVersion: number, base: any, title: string?): (any, string?) + local baseRegions = if type(base) == "table" and Types.isObject(base.Regions) then base.Regions else nil + local regs, order = {}, {} + local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge } + local blocks, volume = 0, 0 + for i, r in regions do + local name = r.name or ("Region" .. (if i == 1 then "" else tostring(i))) + while regs[name] ~= nil do + name ..= "_" + end + local sx, sy, sz = r.size[1], r.size[2], r.size[3] + local n = sx * sy * sz + local states, indices = Common.dedupe(r.states, r.indices, n) + if states[1] ~= "minecraft:air" then + -- Litematica keeps air at index 0 + local at = table.find(states, "minecraft:air") + local shifted = buffer.create(n * 2) + local nst = table.clone(states) + if at then + nst[1], nst[at] = states[at], states[1] + else + table.insert(nst, 1, "minecraft:air") + end + for c = 0, n - 1 do + local v = buffer.readu16(indices, c * 2) + local w = if at then (if v == 0 then at - 1 elseif v == at - 1 then 0 else v) else v + 1 + buffer.writeu16(shifted, c * 2, w) + end + states, indices = nst, shifted + end + local palette = Nbt.list("compound") + for k, st in states do + palette[k] = Mc.stateToNbt(st) + end + local airLike: { [number]: boolean } = {} + for k, st in states do + airLike[k - 1] = Mc.isAir(st) + end + for c = 0, n - 1 do + if not airLike[buffer.readu16(indices, c * 2)] then + blocks += 1 + end + end + volume += n + local bits = Packed.bitsFor(#states, 2) + local longs = Packed.pack(Packed.toYzx(indices, sx, sy, sz), n, bits, true) + local tiles = Nbt.list("compound") + for _, be in r.blockEntities do + table.insert(tiles, Common.flatBlockEntity(be, "flat")) + end + local p = r.position + local pos, size = { p[1], p[2], p[3] }, { sx, sy, sz } + local b = if baseRegions then baseRegions[name] else nil + local bsize = if type(b) == "table" then xyz(b.Size) else nil + if bsize and math.abs(bsize[1]) == sx and math.abs(bsize[2]) == sy and math.abs(bsize[3]) == sz then + for k = 1, 3 do + if bsize[k] < 0 then + size[k] = bsize[k] + pos[k] = p[k] - bsize[k] - 1 + end + end + end + for k = 1, 3 do + lo[k] = math.min(lo[k], p[k]) + hi[k] = math.max(hi[k], p[k] + r.size[k]) + end + regs[name] = Common.merge(b, { + { "BlockStatePalette", palette }, + { "BlockStates", Nbt.longArray(longs) }, + { "Entities", if #r.entities > 0 then r.entities else Nbt.list("compound") }, + { "PendingBlockTicks", if type(b) == "table" then b.PendingBlockTicks else Nbt.list("compound") }, + { "PendingFluidTicks", if type(b) == "table" then b.PendingFluidTicks else Nbt.list("compound") }, + { "Position", vec(pos) }, + { "Size", vec(size) }, + { "TileEntities", tiles }, + }) + table.insert(order, name) + end + if #order == 0 then + lo, hi = { 0, 0, 0 }, { 0, 0, 0 } + end + local bm = if type(base) == "table" and type(base.Metadata) == "table" then base.Metadata else nil + local metadata = Common.merge(bm, { + { "EnclosingSize", vec({ hi[1] - lo[1], hi[2] - lo[2], hi[3] - lo[3] }) }, + { "Author", if bm and bm.Author then bm.Author else "" }, + { "Description", if bm and bm.Description then bm.Description else "" }, + { "Name", title or (if bm and bm.Name then bm.Name else "Unnamed") }, + { "RegionCount", #order }, + { "TimeCreated", if bm and bm.TimeCreated then bm.TimeCreated else Nbt.long(0) }, + { "TimeModified", if bm and bm.TimeModified then bm.TimeModified else Nbt.long(0) }, + { "TotalBlocks", blocks }, + { "TotalVolume", volume }, + }) + local regions_ = Types.object(regs, order) + return Common.merge(base, { + { "MinecraftDataVersion", dataVersion }, + { "Version", version }, + { "SubVersion", if type(base) == "table" and base.SubVersion ~= nil then base.SubVersion elseif version >= 6 then 1 else nil }, + { "Metadata", metadata }, + { "Regions", regions_ }, + }), nil +end + +return Litematic +end +__FILES["model/schematic/Mcedit"] = function() + +-- model/schematic/Mcedit: MCEdit / WorldEdit .schematic (pre-1.13; Minecraft wiki "Schematic file format"): Width / +-- Height / Length, Blocks + Data (+ AddBlocks high nibbles, high nibble first), Materials = "Alpha", TileEntities, +-- Entities, WEOffset*, and the SchematicaMapping / BlockIDs name tables of Schematica and MCEdit-Unified. +local Types = __include("Types") +local Nbt = __include("codecs/text/Nbt") +local Mc = __include("codecs/model/Minecraft") +local Common = __include("model/schematic/Common") + +local Mcedit = {} + +local Packed = Mc.Packed + +function Mcedit.read(root: any, maxCells: number): ({ Common.Region }?, any) + local blocks = root.Blocks + if type(blocks) ~= "buffer" then + return nil, "no Blocks byte array" + end + local function u16(v: any): any + local n = Common.int(v) + return if n and n < 0 then n + 65536 else n + end + local sx, sy, sz = Common.dims(u16(root.Width), u16(root.Height), u16(root.Length), maxCells) + if not sx then + return nil, sy + end + local n = sx * sy :: number * (sz :: number) + if buffer.len(blocks) < n then + return nil, "truncated: Blocks has " .. buffer.len(blocks) .. " bytes for " .. n .. " cells" + end + local data = if type(root.Data) == "buffer" and buffer.len(root.Data) >= n then root.Data else nil + local add = if type(root.AddBlocks) == "buffer" and buffer.len(root.AddBlocks) >= (n + 1) // 2 then root.AddBlocks else nil + -- id -> name tables of Schematica (name -> id) and MCEdit-Unified (id text -> name) + local names: { [number]: string } = {} + if Types.isObject(root.SchematicaMapping) then + for _, k in Types.keys(root.SchematicaMapping) do + local id = Common.int(root.SchematicaMapping[k]) + if id then + names[id] = k + end + end + end + if Types.isObject(root.BlockIDs) then + for _, k in Types.keys(root.BlockIDs) do + local id = tonumber(k) + if id and type(root.BlockIDs[k]) == "string" then + names[id] = root.BlockIDs[k] + end + end + end + local function state(id: number, d: number): string + local name = names[id] + if name then + local base = string.match(name, "^minecraft:(.*)$") or (if string.find(name, ":", 1, true) then nil else name) + if base then + local std = table.find(Mc.Legacy.NAMES, base) + if std then + return Mc.legacyState(std - 1, d) + end + end + return Mc.stateString(if string.find(name, ":", 1, true) then name else "minecraft:" .. name, if d ~= 0 then { { "data", tostring(d) } } else nil) + end + return Mc.legacyState(id, d) + end + local slots: { [number]: number } = {} + local states: { string } = {} + local yzx = buffer.create(n * 2) + for i = 0, n - 1 do + local id = buffer.readu8(blocks, i) + if add then + id += Packed.nibble(add, 0, i, true) * 256 + end + local d = if data then buffer.readu8(data, i) % 16 else 0 + local key = id * 16 + d + local s = slots[key] + if not s then + table.insert(states, state(id, d)) + s = #states - 1 + slots[key] = s + end + buffer.writeu16(yzx, i * 2, s :: number) + end + local bes = {} + for _, c in Common.list(root.TileEntities) do + local be = Common.blockEntity(c, "flat") + if be then + table.insert(bes, be) + end + end + local regions: { Common.Region } = { + { + name = nil, + size = { sx, sy :: number, sz :: number }, + position = { Common.int(root.WEOffsetX) or 0, Common.int(root.WEOffsetY) or 0, Common.int(root.WEOffsetZ) or 0 }, + states = states, + indices = Packed.fromYzx(yzx, sx, sy :: number, sz :: number), + blockEntities = bes, + entities = Common.list(root.Entities), + }, + } + return regions, { materials = root.Materials } +end + +-- the legacy blocks a colour can become (full blocks of distinct colours) +local CANDIDATES: { { any } }? = nil +local function candidates(): { { any } } + if CANDIDATES then + return CANDIDATES + end + local out = {} + local function add(id: number, d: number) + local c = Mc.color(Mc.legacyState(id, d)) + if c then + table.insert(out, { id, d, c }) + end + end + for d = 0, 15 do + add(35, d) -- wool + add(159, d) -- stained clay + add(251, d) -- concrete + end + for d = 0, 5 do + add(5, d) -- planks + end + for _, id in { 1, 2, 3, 4, 7, 12, 13, 24, 41, 42, 45, 48, 49, 57, 80, 82, 87, 88, 89, 98, 121, 133, 152, 155, 168, 172, 173, 174, 179, 201, 216 } do + add(id, 0) + end + CANDIDATES = out + return out +end + +local function nearest(state: string): (number, number) + local c = Mc.color(state) + if not c then + return 0, 0 + end + if c[4] < 200 then + return 20, 0 -- glass + end + local bid, bd, best = 1, 0, math.huge + for _, k in candidates() do + local kc = k[3] + local dist = (kc[1] - c[1]) ^ 2 + (kc[2] - c[2]) ^ 2 + (kc[3] - c[3]) ^ 2 + if dist < best then + bid, bd, best = k[1], k[2], dist + end + end + return bid, bd +end + +function Mcedit.write(r: Common.Region, base: any): (any, string?) + local sx, sy, sz = r.size[1], r.size[2], r.size[3] + if sx > 65535 or sy > 65535 or sz > 65535 then + return nil, "a .schematic is at most 65535 cells on each axis" + end + local n = sx * sy * sz + local map: { [string]: number } = {} + if type(base) == "table" then + if Types.isObject(base.SchematicaMapping) then + for _, k in Types.keys(base.SchematicaMapping) do + local id = Common.int(base.SchematicaMapping[k]) + if id then + map[k] = id + end + end + end + if Types.isObject(base.BlockIDs) then + for _, k in Types.keys(base.BlockIDs) do + local id = tonumber(k) + if id and type(base.BlockIDs[k]) == "string" then + map[base.BlockIDs[k]] = id + end + end + end + end + local ids, datas = table.create(#r.states) :: { number }, table.create(#r.states) :: { number } + local high = false + for i, s in r.states do + local id, d = Mc.legacyId(s) + if id ~= nil then + local lname = Mc.Legacy.NAMES[id + 1] + local mapped = lname and map["minecraft:" .. lname] + if mapped then + id = mapped + end + else + local name, props = Mc.parseState(s) + if map[name] then + id, d = map[name], 0 + for _, kv in props do + if kv[1] == "data" then + d = (tonumber(kv[2]) or 0) % 16 + end + end + else + id, d = nearest(s) + end + end + ids[i], datas[i] = id :: number, d :: number + if (id :: number) > 255 then + high = true + end + end + local yzx = Packed.toYzx(r.indices, sx, sy, sz) + local blocks, data = buffer.create(n), buffer.create(n) + local add = if high then buffer.create((n + 1) // 2) else nil + for i = 0, n - 1 do + local s = buffer.readu16(yzx, i * 2) + 1 + local id = ids[s] or 0 + buffer.writeu8(blocks, i, id % 256) + buffer.writeu8(data, i, datas[s] or 0) + if add then + Packed.setNibble(add, 0, i, id // 256, true) + end + end + local tiles = Nbt.list("compound") + for _, be in r.blockEntities do + table.insert(tiles, Common.flatBlockEntity(be, "flat")) + end + local ents = if #r.entities > 0 then r.entities else Nbt.list("compound") + local fields: { { any } } = { + { "Width", Nbt.short(sx) }, + { "Height", Nbt.short(sy) }, + { "Length", Nbt.short(sz) }, + { "Materials", "Alpha" }, + { "Blocks", blocks }, + { "Data", data }, + { "AddBlocks", add }, + { "Entities", ents }, + { "TileEntities", tiles }, + } + local p = r.position + if p[1] ~= 0 or p[2] ~= 0 or p[3] ~= 0 or (type(base) == "table" and base.WEOffsetX ~= nil) then + table.insert(fields, { "WEOffsetX", p[1] }) + table.insert(fields, { "WEOffsetY", p[2] }) + table.insert(fields, { "WEOffsetZ", p[3] }) + end + local root = Common.merge(base, fields, { Add = true }) + return root, nil +end + +return Mcedit +end +__FILES["model/schematic/Sponge"] = function() + +-- model/schematic/Sponge: .schem (WorldEdit 7+, FAWE, Amulet), from SpongePowered/Schematic-Specification v1-3: Width / +-- Height / Length, Offset, Palette with varint BlockData (v1 / v2) or the Blocks container (v3), block entities +-- (TileEntities / BlockEntities, v3 with Data), Entities, Metadata, DataVersion; biomes are kept as they are. +local Types = __include("Types") +local Nbt = __include("codecs/text/Nbt") +local Mc = __include("codecs/model/Minecraft") +local Common = __include("model/schematic/Common") + +local Sponge = {} + +local Packed = Mc.Packed + +function Sponge.read(s: any, maxCells: number): ({ Common.Region }?, any) + local version = Common.int(s.Version) or 1 + local function u16(v: any): any + local n = Common.int(v) + return if n and n < 0 then n + 65536 else n + end + local sx, sy, sz = Common.dims(u16(s.Width), u16(s.Height), u16(s.Length), maxCells) + if not sx then + return nil, sy + end + local container = if version >= 3 then s.Blocks else s + if version >= 3 and type(container) ~= "table" then + return nil, "no Blocks container" + end + local palette = if version >= 3 then container.Palette else s.Palette + local data = if version >= 3 then container.Data else s.BlockData + if not Types.isObject(palette) then + return nil, "no block palette" + end + if type(data) ~= "buffer" then + return nil, "no block data" + end + local states: { string } = {} + local max = -1 + for _, k in Types.keys(palette) do + local i = Common.int(palette[k]) + if i == nil or i < 0 or i > 65535 then + return nil, "bad palette index for " .. k + end + states[i + 1] = k + if i > max then + max = i + end + end + for i = 1, max + 1 do + if states[i] == nil then + states[i] = "minecraft:air" + end + end + local n = sx * sy :: number * (sz :: number) + local yzx = buffer.create(n * 2) + local ok, e = Packed.varints(data, 0, buffer.len(data), n, yzx, max + 1) + if not ok then + return nil, e + end + local bes = {} + local raw = if version >= 3 then container.BlockEntities elseif version == 2 then s.BlockEntities else s.TileEntities + for _, c in Common.list(raw) do + local be = Common.blockEntity(c, if version >= 3 then "data" else "pos") + if be then + table.insert(bes, be) + end + end + local off = Common.ints(s.Offset) or { 0, 0, 0 } + local regions: { Common.Region } = { + { + name = nil, + size = { sx, sy :: number, sz :: number }, + position = { off[1] or 0, off[2] or 0, off[3] or 0 }, + states = states, + indices = Packed.fromYzx(yzx, sx, sy :: number, sz :: number), + blockEntities = bes, + entities = Common.list(s.Entities), + }, + } + return regions, { version = version, dataVersion = Common.int(s.DataVersion), metadata = s.Metadata } +end + +function Sponge.write(r: Common.Region, version: number, dataVersion: number, base: any): (any, string?) + local sx, sy, sz = r.size[1], r.size[2], r.size[3] + if sx > 65535 or sy > 65535 or sz > 65535 then + return nil, "a Sponge schematic is at most 65535 cells on each axis" + end + local n = sx * sy * sz + local states, indices = Common.dedupe(r.states, r.indices, n) + local palette, keys = {}, {} + for i, st in states do + palette[st] = i - 1 + keys[i] = st + end + local pal = Types.object(palette, keys) + local data = Packed.toVarints(Packed.toYzx(indices, sx, sy, sz), n) + local bes = Nbt.list("compound") + for _, be in r.blockEntities do + table.insert(bes, Common.flatBlockEntity(be, if version >= 3 then "data" else "pos")) + end + local ents = if #r.entities > 0 then r.entities else Nbt.list("compound") -- optional, but readers expect it + local off = Nbt.intArray({ r.position[1], r.position[2], r.position[3] }) + local fields: { { any } } = { + { "Version", version }, + { "DataVersion", if version >= 2 then dataVersion else nil }, + { "Width", Nbt.short(sx) }, + { "Height", Nbt.short(sy) }, + { "Length", Nbt.short(sz) }, + { "Offset", off }, + } + if version >= 3 then + local blocksBase = if type(base) == "table" then base.Blocks else nil + table.insert(fields, { "Blocks", Common.merge(blocksBase, { { "Palette", pal }, { "Data", data }, { "BlockEntities", bes } }) }) + table.insert(fields, { "Entities", ents }) + else + table.insert(fields, { "PaletteMax", #states }) + table.insert(fields, { "Palette", pal }) + table.insert(fields, { "BlockData", data }) + table.insert(fields, { if version == 2 then "BlockEntities" else "TileEntities", bes }) + table.insert(fields, { "Entities", if version == 2 then ents else nil }) + end + -- the other version's block fields never carry over + local drop = if version >= 3 then { PaletteMax = true, Palette = true, BlockData = true, BlockEntities = true, TileEntities = true } + else { Blocks = true, Biomes = true, TileEntities = version ~= 1, BlockEntities = version == 1 } + return Common.merge(base, fields, drop :: any), nil +end + +return Sponge +end +__FILES["model/smd"] = function() + +-- model/smd: Valve SMD (studiomdl "version 1" text, GoldSrc and Source), from the Valve Developer Community "SMD file +-- format" page; no code taken. Units as stored (inches in Valve's games), z up. Not supported: vertex animation (flex). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Sniff = __include("core/Sniff") +local Types = __include("Types") +local Read = __include("model/smd/Read") +local Write = __include("model/smd/Write") + +-- ------------------------------------------------------------------------------------------------ contract +local Smd = { + name = "smd", + category = "model", + extensions = { "smd" }, + mime = { "model/x-smd", "text/plain" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten", "codecs/model/Rig" }, + caps = { decode = true, encode = true, skins = true, animation = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + fps: number?, -- default 30 + name: string?, + maxVertices: number?, -- default 2^24 +} +type EncodeOptions = Write.Options + +-- ------------------------------------------------------------------------------------------------ sniff +function Smd.sniff(r: Bytes.Reader): number + local head = Sniff.text(r, 256, true) + head = string.gsub(head, "^//[^\n]*\n%s*", "") + if string.match(head, "^version%s+1%s") and string.find(head, "nodes", 1, true) then + return 0.9 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Smd.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local text = Sniff.dropBom(r:string(r:remaining())) + local o: any = opts and table.clone(opts :: any) or {} + if type(o.name) == "string" then + o.name = string.match(o.name, "([^/\\]+)$") or o.name + o.name = string.gsub(o.name, "%.[sS][mM][dD]$", "") + end + local scene, msg = Read.read(text, o) + if not scene then + return nil, Err.from(msg) + end + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Smd.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + local text, msg = Write.write(scene, opts) + if not text then + return nil, Err.new(Err.ARG, tostring(msg)) + end + return buffer.fromstring(text), nil +end + +return Smd +end +__FILES["model/smd/Read"] = function() + +-- model/smd/Read: sections "nodes" (id, "name", parent), "skeleton" ("time n", "bone px py pz rx ry rz", Euler radians, +-- R = Rz Ry Rx; a bone missing from a later frame keeps its pose), "triangles" (a material line, then "bone px py pz +-- nx ny nz u v [links (bone weight)...]", model space, v up; the rest of the weight goes to the parent bone). +local Types = __include("Types") +local Rig = __include("codecs/model/Rig") + +local Read = {} + +local Scene = Types.Scene +local writef32, writeu32 = buffer.writef32, buffer.writeu32 + +type Options = { fps: number?, name: string?, maxVertices: number? } + +type Bone = { id: number, name: string, parent: number } +local ZERO: { number } = { 0, 0, 0, 0, 0, 0 } + +function Read.read(text: string, opts: Options?): (Types.Scene?, string?) + local lines: { string } = {} + for line in string.gmatch(text, "[^\r\n]*") do + table.insert(lines, line) + end + local i = 1 + local n = #lines + local function nextLine(): string? + while i <= n do + local l = lines[i] + i += 1 + local s = string.match(l, "^%s*(.-)%s*$") :: string + s = string.gsub(s, "%s*//.*$", "") :: string + if s ~= "" then + return s + end + end + return nil + end + local bones: { Bone } = {} + local byId: { [number]: number } = {} -- SMD bone id -> index into bones (1-based) + local frames: { { [number]: { number } } } = {} -- frames[f][bone index] = { px, py, pz, rx, ry, rz } + local times: { number } = {} + type Batch = { name: string, keys: { [string]: number }, verts: { { number } }, indices: { number } } + local batches: { Batch } = {} + local byMat: { [string]: Batch } = {} + local version: number? = nil + local vertexAnimations = 0 + local maxV = opts and opts.maxVertices or 2 ^ 24 + local total = 0 + while true do + local l = nextLine() + if not l then + break + end + local kw = string.lower(string.match(l, "^(%S+)") or "") + if kw == "version" then + version = tonumber(string.match(l, "^%S+%s+(%S+)")) + elseif kw == "nodes" then + while true do + local s = nextLine() + if not s then + return nil, "truncated: nodes without end" + end + if string.lower(s) == "end" then + break + end + local id, name, parent = string.match(s, '^(%-?%d+)%s+"(.-)"%s+(%-?%d+)') + if not id then + id, name, parent = string.match(s, "^(%-?%d+)%s+(%S+)%s+(%-?%d+)") + end + if not id then + return nil, "bad node line: " .. s + end + table.insert(bones, { id = tonumber(id) :: number, name = name :: string, parent = tonumber(parent) :: number }) + byId[tonumber(id) :: number] = #bones + end + elseif kw == "skeleton" then + local cur: { [number]: { number } }? = nil + while true do + local s = nextLine() + if not s then + return nil, "truncated: skeleton without end" + end + local low = string.lower(s) + if low == "end" then + break + end + local tm = string.match(low, "^time%s+(%-?[%d%.]+)") + if tm then + local prev = frames[#frames] + local f: { [number]: { number } } = {} + if prev then + for k, v in prev do + f[k] = v + end + end + table.insert(frames, f) + table.insert(times, tonumber(tm) :: number) + cur = f + else + local nums: { number } = {} + for tok in string.gmatch(s, "%S+") do + table.insert(nums, tonumber(tok) or 0 / 0) + end + local bi = byId[nums[1]] + if not cur or #nums < 7 or not bi then + return nil, "bad skeleton line: " .. s + end + cur[bi] = { nums[2], nums[3], nums[4], nums[5], nums[6], nums[7] } + end + end + elseif kw == "triangles" then + while true do + local mat = nextLine() + if not mat then + return nil, "truncated: triangles without end" + end + if string.lower(mat) == "end" then + break + end + local b = byMat[mat] + if not b then + b = { name = mat, keys = {}, verts = {}, indices = {} } + byMat[mat] = b + table.insert(batches, b) + end + for _ = 1, 3 do + local s = nextLine() + if not s then + return nil, "truncated triangle" + end + local nums: { number } = {} + for tok in string.gmatch(s, "%S+") do + local v = tonumber(tok) + if not v then + return nil, "bad vertex line: " .. s + end + table.insert(nums, v) + end + if #nums < 9 then + return nil, "short vertex line: " .. s + end + local id = b.keys[s] + if not id then + total += 1 + if total > maxV then + return nil, "limit: too many vertices" + end + table.insert(b.verts, nums) + id = #b.verts - 1 + b.keys[s] = id + end + table.insert(b.indices, id) + end + end + elseif kw == "vertexanimation" then + vertexAnimations += 1 + while true do + local s = nextLine() + if not s or string.lower(s) == "end" then + break + end + end + else + return nil, "unknown section " .. kw + end + end + if version ~= 1 then + return nil, if version == nil then "no version line" else "unsupported: SMD version " .. tostring(version) + end + local scene = Scene.new() + scene.meta.up = "z" + local root: Types.Node = { name = opts and opts.name or "smd", children = {} } + table.insert(scene.nodes, root) + scene.roots[1] = 1 + -- bind pose: the first frame + local joints: { Rig.Joint } = {} + local bind: { [number]: { number } } = frames[1] or {} + for k, bn in bones do + local v: { number } = bind[k] or ZERO + local parent = if bn.parent >= 0 then byId[bn.parent] or 0 else 0 + joints[k] = { name = bn.name, parent = parent, translation = { v[1], v[2], v[3] }, rotation = Rig.angles(v[4], v[5], v[6]) } + end + local jointNodes, skinIndex = Rig.skeleton(scene, joints, "local", 1) + if #batches > 0 then + local mesh: Types.Mesh = { primitives = {} } + for _, b in batches do + local nv = #b.verts + local pos, nrm, uv = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8) + local lists: { { number } } = {} + for vi, v in b.verts do + local o = (vi - 1) * 12 + writef32(pos, o, v[2]) + writef32(pos, o + 4, v[3]) + writef32(pos, o + 8, v[4]) + writef32(nrm, o, v[5]) + writef32(nrm, o + 4, v[6]) + writef32(nrm, o + 8, v[7]) + writef32(uv, (vi - 1) * 8, v[8]) + writef32(uv, (vi - 1) * 8 + 4, 1 - v[9]) + local l: { number } = {} + local sum = 0 + local nl = if #v >= 10 then math.floor(v[10]) else 0 + for k = 0, nl - 1 do + local bi, w = byId[v[11 + k * 2]], v[12 + k * 2] + if bi and w then + table.insert(l, bi - 1) + table.insert(l, w) + sum += w + end + end + local parent = byId[v[1]] + if parent and sum < 0.999 then + table.insert(l, parent - 1) + table.insert(l, 1 - sum) + end + lists[vi] = l + end + local ib = buffer.create(#b.indices * 4) + for k, id in b.indices do + writeu32(ib, (k - 1) * 4, id) + end + local attrs: { [string]: Types.Accessor } = { + POSITION = Scene.accessor(pos, "f32", 3, nv), + NORMAL = Scene.accessor(nrm, "f32", 3, nv), + TEXCOORD_0 = Scene.accessor(uv, "f32", 2, nv), + } + if #bones > 0 then + attrs.JOINTS_0, attrs.WEIGHTS_0 = Rig.influences(lists) + end + local mat = Scene.material(b.name) + mat.metallic = 0 + table.insert(scene.textures, { name = b.name, uri = b.name }) + mat.baseColorTexture = { texture = #scene.textures } + table.insert(scene.materials, mat) + table.insert(mesh.primitives, { attributes = attrs, indices = Scene.accessor(ib, "u32", 1, #b.indices), mode = "triangles" :: any, material = #scene.materials }) + end + table.insert(scene.meshes, mesh) + table.insert(scene.nodes, { name = "mesh", children = {}, mesh = #scene.meshes, skin = if #bones > 0 then skinIndex else nil }) + table.insert(root.children, #scene.nodes) + end + if #frames > 1 or (#frames == 1 and #batches == 0) then + local fps = opts and opts.fps or 30 + local t: { number } = {} + for k, tm in times do + t[k] = (tm - times[1]) / fps + end + local tracks: { [number]: Rig.Track } = {} + for k = 1, #bones do + local tr: { number }, rot: { number } = {}, {} + for _, f in frames do + local v: { number } = f[k] or bind[k] or ZERO + table.insert(tr, v[1]) + table.insert(tr, v[2]) + table.insert(tr, v[3]) + local q = Rig.angles(v[4], v[5], v[6]) + for c = 1, 4 do + table.insert(rot, q[c]) + end + end + tracks[k] = { translation = tr, rotation = rot } + end + Rig.animation(scene, opts and opts.name or "animation", jointNodes, t, tracks, "LINEAR") + end + scene.meta.source = { format = "smd", version = version, bones = #bones, frames = #frames, vertexAnimations = vertexAnimations, kind = if #batches > 0 then "reference" else "animation" } + return scene, nil +end + +return Read +end +__FILES["model/smd/Write"] = function() + +-- model/smd/Write: Scene -> SMD version 1: the first skin's joints (or one "root" bone), the bind pose or a sampled +-- animation, world-space triangles with Source links (GoldSrc style: the strongest joint as the parent bone only). +local Types = __include("Types") +local Mat4 = __include("codecs/model/Mat4") +local Flatten = __include("codecs/model/MeshFlatten") + +local Write = {} + +type Options = { animation: number?, links: boolean?, triangles: boolean? } + +local fmt = string.format + +local function num(v: number): string + if v ~= v or v == math.huge or v == -math.huge then + return "0" + end + local s = fmt("%.6f", v) + if s == "-0.000000" then + return "0.000000" + end + return s +end + +-- quaternion -> x, y, z Euler radians with R = Rz(z) Ry(y) Rx(x) +local function angles(q: { number }): (number, number, number) + local m = Mat4.fromQuat(q) + local r31, r32, r33, r21, r11 = m[3], m[7], m[11], m[2], m[1] + local y = math.asin(math.clamp(-r31, -1, 1)) + local x, z + if math.abs(r31) < 0.9999999 then + x = math.atan2(r32, r33) + z = math.atan2(r21, r11) + else + x = math.atan2(-m[10], m[6]) + z = 0 + end + return x, y, z +end + +local function lerp(a: { number }, b: { number }, t: number): { number } + local out: { number } = {} + for i = 1, #a do + out[i] = a[i] + (b[i] - a[i]) * t + end + return out +end + +local function sample(ch: Types.Channel, tm: number): { number }? + local input, output = ch.input, ch.output + local n = input.count + if n == 0 then + return nil + end + local comps = if ch.path == "rotation" then 4 else 3 + local function key(k: number): { number } + local out: { number } = {} + for c = 0, comps - 1 do + out[c + 1] = buffer.readf32(output.data, (k * comps + c) * 4) + end + return out + end + local times = input.data + if tm <= buffer.readf32(times, 0) then + return key(0) + end + for k = 1, n - 1 do + local t1 = buffer.readf32(times, k * 4) + if tm <= t1 then + local t0 = buffer.readf32(times, (k - 1) * 4) + local f = if ch.interpolation == "STEP" or t1 <= t0 then 0 else (tm - t0) / (t1 - t0) + local a, b = key(k - 1), key(k) + if comps == 4 then + if a[1] * b[1] + a[2] * b[2] + a[3] * b[3] + a[4] * b[4] < 0 then + b = { -b[1], -b[2], -b[3], -b[4] } + end + local q = lerp(a, b, f) + local l = math.sqrt(q[1] ^ 2 + q[2] ^ 2 + q[3] ^ 2 + q[4] ^ 2) + return if l > 0 then { q[1] / l, q[2] / l, q[3] / l, q[4] / l } else a + end + return lerp(a, b, f) + end + end + return key(n - 1) +end + +function Write.write(scene: Types.Scene, opts: Options?): (string?, string?) + if type(scene) ~= "table" or scene.kind ~= "scene" then + return nil, "expected a Scene" + end + local out: { string } = { "version 1", "nodes" } + local skin = scene.skins and scene.skins[1] + local joints: { number } = if skin then skin.joints else {} + local jointOf: { [number]: number } = {} -- node index -> bone id (0-based) + for k, nd in joints do + jointOf[nd] = k - 1 + end + local parentOf: { [number]: number } = {} + for ni, nd in scene.nodes do + for _, c in nd.children do + parentOf[c] = ni + end + end + if #joints == 0 then + table.insert(out, '0 "root" -1') + else + for k, nd in joints do + local p = parentOf[nd] + while p and jointOf[p] == nil do + p = parentOf[p] + end + local name = scene.nodes[nd] and scene.nodes[nd].name or ("bone" .. (k - 1)) + table.insert(out, fmt('%d "%s" %d', k - 1, string.gsub(name, '"', "'"), if p then jointOf[p] else -1)) + end + end + table.insert(out, "end") + table.insert(out, "skeleton") + local function pose(tr: { number }?, rot: { number }?): string + local t = tr or { 0, 0, 0 } + local x, y, z = angles(rot or { 0, 0, 0, 1 }) + return table.concat({ num(t[1]), num(t[2]), num(t[3]), num(x), num(y), num(z) }, " ") + end + local animIndex = opts and opts.animation + local anim = animIndex and scene.animations[animIndex] + if animIndex and not anim then + return nil, "no animation " .. tostring(animIndex) + end + if anim then + local keyset: { [number]: boolean } = {} + for _, ch in anim.channels do + for k = 0, ch.input.count - 1 do + keyset[buffer.readf32(ch.input.data, k * 4)] = true + end + end + local keys: { number } = {} + for tm in keyset do + table.insert(keys, tm) + end + table.sort(keys) + local byNode: { [number]: { [string]: Types.Channel } } = {} + for _, ch in anim.channels do + local m = byNode[ch.node] or {} + byNode[ch.node] = m + m[ch.path] = ch + end + for f, tm in keys do + table.insert(out, "time " .. (f - 1)) + for k, nd in joints do + local node = scene.nodes[nd] + local chs: { [string]: Types.Channel } = byNode[nd] or {} + local tch, rch = chs.translation, chs.rotation + local tr = if tch then sample(tch, tm) else node.translation + local rot = if rch then sample(rch, tm) else node.rotation + table.insert(out, (k - 1) .. " " .. pose(tr, rot)) + end + end + else + table.insert(out, "time 0") + if #joints == 0 then + table.insert(out, "0 " .. pose(nil, nil)) + else + for k, nd in joints do + local node = scene.nodes[nd] + local tr, rot = node.translation, node.rotation + if node.matrix then + local t, r = Mat4.decompose(node.matrix) + tr, rot = t, r + end + table.insert(out, (k - 1) .. " " .. pose(tr, rot)) + end + end + end + table.insert(out, "end") + if not anim or (opts and opts.triangles) then + local m, err = Flatten.merge(scene, function(name: string): boolean + return name == "NORMAL" or name == "TEXCOORD_0" or name == "JOINTS_0" or name == "WEIGHTS_0" + end, { triangulate = true }) + if not m then + return nil, err + end + local A = m.attrs + local P, N, UV, J, W = A.POSITION, A.NORMAL, A.TEXCOORD_0, A.JOINTS_0, A.WEIGHTS_0 + local links = not (opts and opts.links == false) + local nbones = math.max(1, #joints) + if #m.corners > 0 then + table.insert(out, "triangles") + for _, part in m.parts do + local mat = part.prim.material and scene.materials[part.prim.material] + local mname = if mat and mat.name and mat.name ~= "" then mat.name else "default" + for f = part.firstFace, part.firstFace + part.faceCount - 1 do + table.insert(out, mname) + for c = 0, 2 do + local v = m.corners[f * 3 + c + 1] + local px, py, pz = P.values[v * 3 + 1], P.values[v * 3 + 2], P.values[v * 3 + 3] + local nx, ny, nz = 0, 0, 1 + if N then + nx, ny, nz = N.values[v * 3 + 1], N.values[v * 3 + 2], N.values[v * 3 + 3] + end + local u, w = 0, 0 + if UV then + local k = UV.components + u, w = UV.values[v * k + 1], UV.values[v * k + 2] + end + local parent = 0 + local lk: { string } = {} + if J and W and #joints > 0 then + local jk, wk = J.components, W.components + local best, bestW = 0, -1 + local count = 0 + for c2 = 1, math.min(4, jk, wk) do + local jw = W.values[v * wk + c2] + local jj = math.clamp(math.floor(J.values[v * jk + c2] or 0), 0, nbones - 1) + if jw and jw > 0 then + count += 1 + table.insert(lk, fmt("%d %s", jj, num(jw))) + if jw > bestW then + best, bestW = jj, jw + end + end + end + parent = best + if count > 0 then + table.insert(lk, 1, tostring(count)) + end + end + local line = fmt("%d %s %s %s %s %s %s %s %s", parent, num(px), num(py), num(pz), num(nx), num(ny), num(nz), num(u), num(1 - w)) + if links and #lk > 0 then + line ..= " " .. table.concat(lk, " ") + end + table.insert(out, line) + end + end + end + table.insert(out, "end") + end + end + table.insert(out, "") + return table.concat(out, "\n"), nil +end + +return Write +end +__FILES["model/stl"] = function() + +-- model/stl: STL (3D Systems; Wikipedia "STL (file format)", the SLC spec), ASCII and binary, read + write. Supports: +-- the VisCAM / SolidView and Materialise Magics colour conventions, a binary file starting with "solid" (size exactly +-- 84 + 50 * count), several ASCII solids. Not supported: other binary attribute extensions. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Decode = __include("model/stl/Decode") +local Flatten = __include("codecs/model/MeshFlatten") + +-- ------------------------------------------------------------------------------------------------ contract +local Stl = { + name = "stl", + category = "model", + extensions = { "stl" }, + mime = { "model/stl", "application/sla" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/MeshFlatten" }, + caps = { decode = true, encode = true, ascii = true, binary = true, colors = true, indexed = false }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + maxFaces: number?, -- default 2^25 + colors: ("auto" | "viscam" | "magics" | "none")?, -- default "auto": "COLOR=" = magics, else bit 15 = viscam +} +type EncodeOptions = { + ascii: boolean?, -- default false (binary) + colors: ("viscam" | "magics")?, -- binary only + defaultColor: { number }?, -- magics object colour, 0..255 (default opaque white) + name: string?, -- default: the mesh / node name, else "mesh" + header: string?, -- at most 80 bytes; default "rosetta STL" + normals: ("compute" | "attribute")?, -- default: from the triangle +} + +-- ------------------------------------------------------------------------------------------------ constants +local readu8, readu32 = buffer.readu8, buffer.readu32 +local writef32, writeu16, writeu32 = buffer.writef32, buffer.writeu16, buffer.writeu32 + +local function lower5(s: string): boolean + return string.lower(s) == "solid" +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Stl.sniff(r: Bytes.Reader): number + local size = r:remaining() + if size >= 84 then + local c = r:peek(4, 80) + local n = string.byte(c, 1) + string.byte(c, 2) * 256 + string.byte(c, 3) * 65536 + string.byte(c, 4) * 16777216 + if 84 + 50 * n == size then + return 0.9 + end + end + local head = r:peek(512) + local s = string.match(head, "^%s*(%a+)") + if s and lower5(s) then + local l = string.lower(head) + return if string.find(l, "facet", 1, true) or string.find(l, "endsolid", 1, true) then 0.9 else 0.5 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function soupPrim(n: number, pos: buffer, nrm: buffer): Types.Primitive + return { + attributes = { + POSITION = Types.Scene.accessor(pos, "f32", 3, n * 3), + NORMAL = Types.Scene.accessor(nrm, "f32", 3, n * 3), + }, + mode = "triangles", + } +end + +local function decodeBinary(r: Bytes.Reader, maxFaces: number, colors: string): (Types.Scene?, Err.Err?) + local b, base, size = r.buf, r.base, r.limit - r.base + local n = readu32(b, base + 80) + if n > maxFaces then + return nil, Err.new(Err.LIMIT, string.format("%d facets is over the %d facet limit", n, maxFaces), base + 80) + end + if 84 + 50 * n > size then + return nil, Err.new(Err.TRUNCATED, string.format("%d facets need %d bytes, the file has %d", n, 84 + 50 * n, size), base + 80) + end + local pos, nrm, attr = buffer.create(n * 36), buffer.create(n * 36), buffer.create(n * 2) + local any = Decode.binary(b, base + 84, n, pos, nrm, attr) + local header = buffer.readstring(b, base, 80) + local cut = string.find(header, "\0", 1, true) -- the text before the first NUL + local text = if cut then string.sub(header, 1, cut - 1) else header + local mode = colors + local ci = string.find(header, "COLOR=", 1, true) + if mode == "auto" then + mode = if ci and ci + 9 <= 80 then "magics" elseif any >= 0x8000 then "viscam" else "none" + end + local prim = soupPrim(n, pos, nrm) + local source: { [string]: any } = { format = "stl", binary = true, header = text, facets = n } + if mode == "viscam" or mode == "magics" then + local dc = { 255, 255, 255, 255 } + if mode == "magics" and ci and ci + 9 <= 80 then + local o = base + ci + 5 -- the 4 bytes after "COLOR=" (ci is 1-based) + dc = { readu8(b, o), readu8(b, o + 1), readu8(b, o + 2), readu8(b, o + 3) } + source.defaultColor = dc + local mi = string.find(header, "MATERIAL=", 1, true) + if mi and mi + 8 + 12 <= 80 then + local m = base + mi + 8 + local function rgba(k: number): { number } + return { readu8(b, m + k), readu8(b, m + k + 1), readu8(b, m + k + 2), readu8(b, m + k + 3) } + end + source.material = { diffuse = rgba(0), specular = rgba(4), ambient = rgba(8) } + end + end + local col = buffer.create(n * 12) + Decode.colors(attr, n, mode == "magics", dc[1], dc[2], dc[3], dc[4], col) + prim.attributes.COLOR_0 = Types.Scene.accessor(col, "unorm8", 4, n * 3) + source.colors = mode + elseif any ~= 0 then + prim.extras = { faceAttributes = { attribute = Types.Scene.accessor(attr, "u16", 1, n) } } + end + local scene = Types.Scene.fromPrimitive(prim, nil) + scene.meta.up = "z" + scene.meta.source = source :: any + return scene, nil +end + +local function decodeAscii(r: Bytes.Reader, maxFaces: number): (Types.Scene?, Err.Err?) + local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + local at = 1 + local function tok(): string? + local s, e = string.find(text, "%S+", at) + if not s then + return nil + end + at = (e :: number) + 1 + return string.sub(text, s, e) + end + local function restOfLine(): string + local e = string.find(text, "\n", at, true) or (#text + 1) + local line = string.sub(text, at, e - 1) + at = e + 1 + return string.match(line, "^%s*(.-)%s*$") or "" + end + local function num(): number? + local t = tok() + return if t then tonumber(t) else nil + end + type Solid = { name: string, pos: { number }, nrm: { number } } + local solids: { Solid } = {} + local facets = 0 + while true do + local t = tok() + if t == nil then + break + end + if string.lower(t) ~= "solid" then + return nil, Err.new(Err.CORRUPT, "expected solid, found " .. string.sub(t, 1, 20)) + end + local cur: Solid = { name = restOfLine(), pos = {}, nrm = {} } + table.insert(solids, cur) + local pos, nrm = cur.pos, cur.nrm + while true do + local w = tok() + if w == nil then + break -- a missing endsolid at the end + end + local lw = string.lower(w) + if lw == "endsolid" then + restOfLine() + break + elseif lw ~= "facet" then + return nil, Err.new(Err.CORRUPT, "expected facet or endsolid, found " .. string.sub(w, 1, 20)) + end + local nx, ny, nz = 0, 0, 0 + local k = tok() + if k and string.lower(k) == "normal" then + local a, bb, c = num(), num(), num() + if a == nil or bb == nil or c == nil then + return nil, Err.new(if at > #text then Err.TRUNCATED else Err.CORRUPT, "bad facet normal") + end + nx, ny, nz = a, bb, c + k = tok() + end + local l2 = tok() + if k == nil or l2 == nil then + return nil, Err.new(Err.TRUNCATED, "facet cut short") + end + if string.lower(k) ~= "outer" or string.lower(l2) ~= "loop" then + return nil, Err.new(Err.CORRUPT, "expected outer loop") + end + local vs: { number } = {} + while true do + local v = tok() + if v == nil then + return nil, Err.new(Err.TRUNCATED, "facet cut short") + end + local lv = string.lower(v) + if lv == "endloop" then + break + elseif lv ~= "vertex" then + return nil, Err.new(Err.CORRUPT, "expected vertex or endloop, found " .. string.sub(v, 1, 20)) + end + local x, y, z = num(), num(), num() + if x == nil or y == nil or z == nil then + return nil, Err.new(if at > #text then Err.TRUNCATED else Err.CORRUPT, "bad vertex") + end + table.insert(vs, x) + table.insert(vs, y) + table.insert(vs, z) + end + local e = tok() + if e == nil then + return nil, Err.new(Err.TRUNCATED, "facet cut short") + elseif string.lower(e) ~= "endfacet" then + return nil, Err.new(Err.CORRUPT, "expected endfacet") + end + local nvs = #vs // 3 + if nvs < 3 then + return nil, Err.new(Err.CORRUPT, "facet with fewer than 3 vertices") + end + for j = 2, nvs - 1 do + for _, vi in { 0, j - 1, j } do + table.insert(pos, vs[vi * 3 + 1]) + table.insert(pos, vs[vi * 3 + 2]) + table.insert(pos, vs[vi * 3 + 3]) + table.insert(nrm, nx) + table.insert(nrm, ny) + table.insert(nrm, nz) + end + facets += 1 + end + if facets > maxFaces then + return nil, Err.new(Err.LIMIT, string.format("over the %d facet limit", maxFaces)) + end + end + end + if #solids == 0 then + return nil, Err.new(Err.TRUNCATED, "no solid") + end + local prims: { Types.Primitive } = {} + local names: { string } = {} + for i, s in solids do + local n = #s.pos // 9 + local pos, nrm = buffer.create(n * 36), buffer.create(n * 36) + for j = 1, n * 9 do + writef32(pos, (j - 1) * 4, s.pos[j]) + writef32(nrm, (j - 1) * 4, s.nrm[j]) + end + local prim = soupPrim(n, pos, nrm) + prim.extras = { solid = s.name } + prims[i] = prim + names[i] = s.name + end + local first = solids[1].name + local scene = Types.Scene.fromPrimitive(prims[1], if first ~= "" then first else nil) + for i = 2, #prims do + table.insert(scene.meshes[1].primitives, prims[i]) + end + scene.meta.up = "z" + scene.meta.source = { format = "stl", binary = false, solids = names, facets = facets } + return scene, nil +end + +function Stl.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local maxFaces = opts and opts.maxFaces or 2 ^ 25 + local colors = opts and opts.colors or "auto" + if colors ~= "auto" and colors ~= "viscam" and colors ~= "magics" and colors ~= "none" then + return nil, Err.new(Err.ARG, "colors must be auto, viscam, magics or none") + end + local size = r.limit - r.base + if size >= 84 and 84 + 50 * readu32(r.buf, r.base + 80) == size then + return decodeBinary(r, maxFaces, colors) + end + local s = string.match(buffer.readstring(r.buf, r.base, math.min(size, 256)), "^%s*(%a+)") + if s and lower5(s) then + return decodeAscii(r, maxFaces) + end + if size < 84 then + return nil, Err.new(Err.TRUNCATED, "shorter than a binary STL header", r.base) + end + -- extra bytes after the facets are tolerated + return decodeBinary(r, maxFaces, colors) +end + +-- ------------------------------------------------------------------------------------------------ encode +local scratch = buffer.create(4) +local function f32(v: number): number + writef32(scratch, 0, v) + return buffer.readf32(scratch, 0) +end + +local function byte(a: Flatten.Attr, v: number): number + if a.raw then + if a.type == "unorm16" then + return (v * 255 + 32767) // 65535 + end + return math.clamp(v, 0, 255) + end + return math.floor(math.clamp(v, 0, 1) * 255 + 0.5) +end + +local function to5(c: number): number + return (c * 31 + 127) // 255 +end + +local function keep(name: string): boolean + return name == "NORMAL" or name == "COLOR_0" +end + +function Stl.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local colors = o.colors + if colors ~= nil and colors ~= "viscam" and colors ~= "magics" then + return nil, Err.new(Err.ARG, "colors must be viscam or magics") + end + if o.normals ~= nil and o.normals ~= "compute" and o.normals ~= "attribute" then + return nil, Err.new(Err.ARG, "normals must be compute or attribute") + end + if o.header ~= nil and (type(o.header) ~= "string" or #o.header > 80) then + return nil, Err.new(Err.ARG, "header must be a string of at most 80 bytes") + end + local m, merr = Flatten.merge(scene, keep, { triangulate = true }) + if not m then + 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 :: Flatten.Attr).values else nil + local C = m.attrs.COLOR_0 + local corners = m.corners + local nf = #corners // 3 + local function normal(f: number): (number, number, number) + local a, b, c = corners[f * 3 + 1], corners[f * 3 + 2], corners[f * 3 + 3] + if N then + return N[a * 3 + 1], N[a * 3 + 2], N[a * 3 + 3] + end + local ax, ay, az = P[a * 3 + 1], P[a * 3 + 2], P[a * 3 + 3] + local ux, uy, uz = P[b * 3 + 1] - ax, P[b * 3 + 2] - ay, P[b * 3 + 3] - az + local vx, vy, vz = P[c * 3 + 1] - ax, P[c * 3 + 2] - ay, P[c * 3 + 3] - az + local nx, ny, nz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx + local l = math.sqrt(nx * nx + ny * ny + nz * nz) + if l > 0 and l < math.huge then + return nx / l, ny / l, nz / l + end + return 0, 0, 0 + end + if o.ascii then + local out = table.create(nf * 7 + 2 * #m.parts) + local used: { [string]: boolean } = {} + local function fmt(v: number): string? + v = f32(v) + if v ~= v or v == math.huge or v == -math.huge then + return nil + end + return string.format("%.9g", v) + end + for _, part in m.parts do + local name = o.name + if name == nil then + local ex = part.prim.extras + name = if ex and type(ex.solid) == "string" then ex.solid elseif part.mesh and part.mesh.name then part.mesh.name elseif part.node and part.node.name then part.node.name else "mesh" + end + name = string.gsub(tostring(name), "[\r\n]", " ") + if used[name] then -- distinct names: some readers merge solids by name + local k = 2 + while used[name .. "_" .. k] do + k += 1 + end + name = name .. "_" .. k + end + used[name] = true + table.insert(out, "solid " .. name .. "\n") + for f = part.firstFace, part.firstFace + part.faceCount - 1 do + local nx, ny, nz = normal(f) + table.insert(out, string.format(" facet normal %s %s %s\n outer loop\n", fmt(nx) or "0", fmt(ny) or "0", fmt(nz) or "0")) + for k = 1, 3 do + local v = corners[f * 3 + k] * 3 + local x, y, z = fmt(P[v + 1]), fmt(P[v + 2]), fmt(P[v + 3]) + if not (x and y and z) then + return nil, Err.new(Err.ARG, "ASCII STL cannot hold a non-finite coordinate") + end + table.insert(out, " vertex " .. x .. " " .. y .. " " .. z .. "\n") + end + table.insert(out, " endloop\n endfacet\n") + end + table.insert(out, "endsolid " .. name .. "\n") + end + if #m.parts == 0 then + table.insert(out, "solid " .. (o.name or "mesh") .. "\nendsolid " .. (o.name or "mesh") .. "\n") + end + return buffer.fromstring(table.concat(out)), nil + end + local buf = buffer.create(84 + 50 * nf) + local header = o.header or "rosetta STL" + if colors == "magics" then + local dc = o.defaultColor or { 255, 255, 255, 255 } + if type(dc) ~= "table" or #dc < 4 then + return nil, Err.new(Err.ARG, "defaultColor must be { r, g, b, a }") + end + header = string.sub(header, 1, 69) .. " COLOR=" .. string.char(math.clamp(dc[1], 0, 255) // 1, math.clamp(dc[2], 0, 255) // 1, math.clamp(dc[3], 0, 255) // 1, math.clamp(dc[4], 0, 255) // 1) + end + local dcol: { number }? = nil + if colors == "magics" then + local dc = o.defaultColor or { 255, 255, 255, 255 } + dcol = { dc[1] // 1, dc[2] // 1, dc[3] // 1, dc[4] // 1 } + end + buffer.writestring(buf, 0, header) + writeu32(buf, 80, nf) + local rawAttr: { number }? = nil + if colors == nil and #m.parts == 1 then + local ex = m.parts[1].prim.extras + local fa = ex and ex.faceAttributes + local acc = fa and fa.attribute + if acc and acc.count == nf then + rawAttr = Flatten.numbers(acc, true) + end + end + for f = 0, nf - 1 do + local q = 84 + f * 50 + local nx, ny, nz = normal(f) + writef32(buf, q, nx) + writef32(buf, q + 4, ny) + writef32(buf, q + 8, nz) + for k = 0, 2 do + local v = corners[f * 3 + k + 1] * 3 + writef32(buf, q + 12 + k * 12, P[v + 1]) + writef32(buf, q + 16 + k * 12, P[v + 2]) + writef32(buf, q + 20 + k * 12, P[v + 3]) + end + local w = 0 + if colors and C then + local a = corners[f * 3 + 1] * C.components + local cv = C.values + local r5, g5, b5 = to5(byte(C, cv[a + 1])), to5(byte(C, cv[a + 2] or 0)), to5(byte(C, cv[a + 3] or 0)) + if colors == "viscam" then + w = 0x8000 + r5 * 1024 + g5 * 32 + b5 + elseif dcol and byte(C, cv[a + 1]) == dcol[1] and byte(C, cv[a + 2] or 0) == dcol[2] and byte(C, cv[a + 3] or 0) == dcol[3] and (if C.components >= 4 then byte(C, cv[a + 4]) else 255) == dcol[4] then + w = 0x8000 -- the object colour + else + w = r5 + g5 * 32 + b5 * 1024 + end + elseif colors == "magics" then + w = 0x8000 -- the object colour + elseif rawAttr then + w = math.clamp(rawAttr[f + 1] // 1, 0, 65535) + end + writeu16(buf, q + 48, w) + end + return buf, nil +end + +return Stl +end +__FILES["model/stl/Decode"] = @native function() + + + +-- model/stl/Decode: binary STL facets (50 bytes: normal, 3 vertices, u16 attribute) and the 5-5-5 colours of VisCAM / +-- SolidView and Materialise Magics. Never throws: the caller bounds the facets first. +local readu16, readu32, writeu8, writeu16, writeu32 = buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu16, buffer.writeu32 +local band, bor, rshift = bit32.band, bit32.bor, bit32.rshift + +local Decode = {} + +@native function Decode.binary(b: buffer, p: number, n: number, pos: buffer, nrm: buffer, attr: buffer): number + local any = 0 + for i = 0, n - 1 do + local q = p + i * 50 + local o = i * 36 + local nx, ny, nz = readu32(b, q), readu32(b, q + 4), readu32(b, q + 8) + writeu32(nrm, o, nx) + writeu32(nrm, o + 4, ny) + writeu32(nrm, o + 8, nz) + writeu32(nrm, o + 12, nx) + writeu32(nrm, o + 16, ny) + writeu32(nrm, o + 20, nz) + writeu32(nrm, o + 24, nx) + writeu32(nrm, o + 28, ny) + writeu32(nrm, o + 32, nz) + writeu32(pos, o, readu32(b, q + 12)) + writeu32(pos, o + 4, readu32(b, q + 16)) + writeu32(pos, o + 8, readu32(b, q + 20)) + writeu32(pos, o + 12, readu32(b, q + 24)) + writeu32(pos, o + 16, readu32(b, q + 28)) + writeu32(pos, o + 20, readu32(b, q + 32)) + writeu32(pos, o + 24, readu32(b, q + 36)) + writeu32(pos, o + 28, readu32(b, q + 40)) + writeu32(pos, o + 32, readu32(b, q + 44)) + local a = readu16(b, q + 48) + writeu16(attr, i * 2, a) + any = bor(any, a) + end + return any +end + +@native local function x8(v: number): number + return (v * 255 + 15) // 31 +end + +-- VisCAM: bit 15 set = valid, red in bits 10..14, blue in 0..4. Magics: bit 15 clear = the facet's own colour, +-- red in bits 0..4, blue in 10..14. +@native function Decode.colors(attr: buffer, n: number, magics: boolean, dr: number, dg: number, db: number, da: number, out: buffer) + for i = 0, n - 1 do + local w = readu16(attr, i * 2) + local r, g, bl, al = dr, dg, db, da + local own = if magics then w < 0x8000 else w >= 0x8000 + if own then + local lo, mid, hi = x8(band(w, 31)), x8(band(rshift(w, 5), 31)), x8(band(rshift(w, 10), 31)) + g, al = mid, 255 + if magics then + r, bl = lo, hi + else + r, bl = hi, lo + end + end + local o = i * 12 + for k = 0, 2 do + writeu8(out, o + k * 4, r) + writeu8(out, o + k * 4 + 1, g) + writeu8(out, o + k * 4 + 2, bl) + writeu8(out, o + k * 4 + 3, al) + end + end +end + +return Decode +end +__FILES["model/usda"] = function() + +-- model/usda: USD ASCII layers (.usda, text .usd) and USDZ packages of them, from the Sdf text format and the UsdGeom / +-- UsdShade / UsdLux docs (OpenUSD 26.x), checked against pxr and Blender's exporter. Not supported: USDC crate files, +-- composition arcs (listed in meta.source.unsupported), UsdSkel, blend shapes, curves / points / NURBS, instancers, +-- MaterialX, writing USDZ. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Zip = __include("containers/Zip") +local Parse = __include("model/usda/Parse") +local Build = __include("model/usda/Build") +local Write = __include("model/usda/Write") + +-- ------------------------------------------------------------------------------------------------ contract +local Usda = { + name = "usda", + category = "model", + extensions = { "usda", "usd", "usdz" }, + mime = { "model/vnd.usda", "model/vnd.usdz+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 }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + triangulate: boolean?, -- default true + flipV: boolean?, -- default true + resolve: ((uri: string) -> any)?, + files: { [string]: any }?, + maxVertices: number?, -- default 2^25 + maxBytes: number?, -- default 2^30 +} +type EncodeOptions = { + files: { [string]: any }?, -- as <name>_<n>.<ext> + name: string?, + format: string?, -- "usdz" -> UNSUPPORTED + upAxis: string?, -- default: from scene.meta.up + metersPerUnit: number?, -- default scene.meta.unit or 1 +} + +-- ------------------------------------------------------------------------------------------------ sniff +local function isUsdz(r: Bytes.Reader): boolean + if r:peek(4) ~= "PK\3\4" then + return false + end + local lo, hi = r:peekU8(26), r:peekU8(27) + if lo < 0 or hi < 0 then + return false + end + local nameLen = lo + hi * 256 + local name = string.lower(r:peek(30 + nameLen)) + name = string.sub(name, 31) + return string.find(name, "%.usd[ac]?$") ~= nil +end + +function Usda.sniff(r: Bytes.Reader): number + local head = r:peek(8) + if string.sub(head, 1, 5) == "#usda" or string.sub(head, 1, 8) == "\239\187\191#usda" then + return 1 + end + if head == "PXR-USDC" then + return 0.9 -- USDC magic, so the error says it is unsupported + end + if isUsdz(r) then + return 0.95 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function fetcher(opts: DecodeOptions?, package: any): (uri: string) -> buffer? + return function(uri: string): buffer? + local candidates = { uri } + local slashed = string.gsub(uri, "\\", "/") + local stripped = string.gsub(slashed, "^%./", "") + if slashed ~= uri then + table.insert(candidates, slashed) + end + if stripped ~= slashed then + table.insert(candidates, stripped) + end + -- packaged assets: "model.usdz[textures/a.png]" + local inner = string.match(uri, "%[(.+)%]$") + if inner then + table.insert(candidates, inner) + end + for _, u in candidates do + if package then + local data = package:read(u) + if data then + return data + end + end + local v: any = nil + 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 :: 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 + return buffer.fromstring(v) + elseif type(v) == "buffer" then + return v + end + end + return nil + end +end + +function Usda.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local head = r:peek(8) + if head == "PXR-USDC" then + return nil, Err.new(Err.UNSUPPORTED, "USDC binary crate files (convert with usdcat to .usda)") + end + local text: string + local package: any = nil + local usdz = false + if string.sub(head, 1, 4) == "PK\3\4" then + local archive, zerr = Zip.open(r) + if not archive then + return nil, zerr or Err.new(Err.CORRUPT, "bad USDZ package") + end + local entries = archive:list() + local root = nil + for _, e in entries do + if not e.dir and string.find(string.lower(e.name), "%.usd[ac]?$") then + root = e + break + end + end + if not root then + return nil, Err.new(Err.CORRUPT, "the USDZ package holds no USD layer") + end + local data, rerr = archive:read(root) + if not data then + return nil, rerr + end + if buffer.len(data) >= 8 and buffer.readstring(data, 0, 8) == "PXR-USDC" then + return nil, Err.new(Err.UNSUPPORTED, "USDZ holding a USDC binary crate layer") + end + text = buffer.tostring(data) + package = archive + usdz = true + else + text = buffer.readstring(r.buf, r.base, r.limit - r.base) + end + if not Parse.version(text) then + return nil, Err.new(Err.CORRUPT, "no #usda header") + end + local layer, msg, at = Parse.layer(text, opts and opts.maxBytes) + if not layer then + if msg == "array over the size limit" then + return nil, Err.new(Err.LIMIT, msg :: string, at) + end + local code = if at and at >= #text - 1 then Err.TRUNCATED else Err.CORRUPT + if msg and string.find(msg, "^unterminated") then + code = Err.TRUNCATED + end + return nil, Err.new(code, msg or "parse error", if usdz then nil else at) + end + local scene, err = Build.scene(layer, { + triangulate = opts and opts.triangulate, + flipV = opts and opts.flipV, + maxVertices = opts and opts.maxVertices, + fetch = fetcher(opts, package), + }) + if not scene then + if err == "LIMIT" then + return nil, Err.new(Err.LIMIT, "a mesh over maxVertices") + end + return nil, Err.new(Err.CORRUPT, err or "bad scene") + end + local src: any = scene.meta.source + src.version = Parse.version(text) + src.usdz = usdz or nil + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Usda.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(scene) ~= "table" or scene.kind ~= "scene" then + return nil, Err.new(Err.ARG, "needs a Scene") + end + if opts and opts.format == "usdz" then + return nil, Err.new(Err.UNSUPPORTED, "writing USDZ; write .usda") + end + local ok, text = pcall(Write.text, scene, opts) + if not ok then + return nil, Err.new(Err.ARG, "bad scene: " .. tostring(text)) + end + return buffer.fromstring(text :: any), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +function Usda.parse(text: string): (Parse.Layer?, Err.Err?) + local layer, msg, at = Parse.layer(text) + if not layer then + return nil, Err.new(Err.CORRUPT, msg or "parse error", at) + end + return layer, nil +end + +return Usda +end +__FILES["model/usda/Build"] = function() + +-- model/usda/Build: a USDA layer to a Scene, following the UsdGeom / UsdShade / UsdLux schemas (OpenUSD 26.x). Other +-- attributes than xform ops use their earliest sample (as UsdTimeCode.EarliestTime()). Not supported: composition arcs, +-- UsdSkel, blend shapes, BasisCurves / Points / NURBS, instancing, MaterialX networks. +local Types = __include("Types") +local Mat4 = __include("codecs/model/Mat4") +local Parse = __include("model/usda/Parse") + +local Build = {} + +type Prim = Parse.Prim +type Prop = Parse.Prop + +local NONE = Parse.NONE +local DEG = math.pi / 180 + +local NOT_NODES = { Material = true, Shader = true, NodeGraph = true, GeomSubset = true, Skeleton = true, SkelAnimation = true, BlendShape = true } +local SKEL = { Skeleton = true, SkelAnimation = true, BlendShape = true } +local LIGHTS = { DistantLight = true, SphereLight = true, RectLight = true, DiskLight = true, CylinderLight = true, DomeLight = true } +local MIME = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", webp = "image/webp", tga = "image/x-tga", bmp = "image/bmp", exr = "image/x-exr", hdr = "image/vnd.radiance", ktx2 = "image/ktx2", gif = "image/gif", tif = "image/tiff", tiff = "image/tiff", avif = "image/avif" } + +type Options = { + triangulate: boolean?, + flipV: boolean?, + fetch: ((uri: string) -> buffer?)?, + maxVertices: number?, +} + +-- ------------------------------------------------------------------------------------------------ helpers +local function isArr(v: any): boolean + return type(v) == "table" and v.t == "arr" +end +local function str(v: any): string? + if type(v) == "string" then + return v + elseif type(v) == "table" and (v.t == "id" or v.t == "asset" or v.t == "path") then + return v.v + end + return nil +end +local function nums(v: any): { number }? + if type(v) == "number" then + return { v } + elseif type(v) == "boolean" then + return { if v then 1 else 0 } + elseif type(v) == "table" and v.t == "tuple" then + local out = {} + for k, x in v.v do + if type(x) == "number" then + out[k] = x + elseif type(x) == "table" and x.t == "tuple" then + for _, y in x.v do + if type(y) ~= "number" then + return nil + end + table.insert(out, y) + end + else + return nil + end + end + return out + elseif type(v) == "table" and v.t == "arr" then + return v.v + end + return nil +end +local function num(v: any): number? + if type(v) == "number" then + return v + elseif type(v) == "boolean" then + return if v then 1 else 0 + end + return nil +end + +-- a property's default, else its earliest time sample +local function propValue(p: Prop?): any + if not p then + return nil + end + if p.samples and #p.samples.times > 0 then + local best, bi = math.huge, 0 + for k, t in p.samples.times do + if t < best then + best, bi = t, k + end + end + local v = p.samples.values[bi] + if v ~= NONE then + return v + end + end + if p.hasValue and p.value ~= NONE then + return p.value + end + return nil +end + +local function joinPath(parent: string, name: string): string + return if parent == "/" then "/" .. name else parent .. "/" .. name +end + +local function resolvePath(base: string, p: string): string + if string.sub(p, 1, 1) == "/" then + return p + end + local parts = string.split(base, "/") + local out: { string } = {} + for _, x in parts do + if x ~= "" then + table.insert(out, x) + end + end + for _, x in string.split(p, "/") do + if x == ".." then + table.remove(out) + elseif x ~= "." and x ~= "" then + table.insert(out, x) + end + end + return "/" .. table.concat(out, "/") +end +local function splitProp(p: string): (string, string?) + local prim, prop = string.match(p, "^(.-)%.([^/]+)$") + if prim and prop then + return prim, prop + end + return p, nil +end + +-- ------------------------------------------------------------------------------------------------ matrices +-- column-major 4x4 (glTF layout = USD's row-major row-vector text order) +local mul = Types.Scene.mul +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 Mat4.fromQuat({ x, y, z, w }) +end + +-- ------------------------------------------------------------------------------------------------ xform ops +type Op = { kind: string, axes: string?, prop: Prop, invert: boolean } + +local function xformOps(p: Prim): ({ Op }, boolean) + local order = p.props.xformOpOrder + local list = order and propValue(order) + local ops: { Op } = {} + local reset = false + if type(list) ~= "table" or list.t ~= "list" then + return ops, false + end + for _, item in list.v do + local name = str(item) + if name == "!resetXformStack!" then + reset = true + table.clear(ops) + elseif name then + local invert = false + if string.sub(name, 1, 8) == "!invert!" then + invert = true + name = string.sub(name, 9) + end + local prop = p.props[name] + local kind = string.match(name, "^xformOp:(%a+)") + if prop and kind then + local axes = string.match(kind, "^rotate([XYZ]+)$") + table.insert(ops, { kind = if axes then "rotate" else kind, axes = axes, prop = prop, invert = invert }) + end + end + end + return ops, reset +end + +local AXIS = { X = 1, Y = 2, Z = 3 } +local function opMatrix(op: Op, v: any): { number }? + local n = nums(v) + if not n then + return nil + end + local m: { number }? + local k = op.kind + if k == "translate" then + 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 = 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) + elseif k == "transform" then + if #n ~= 16 then + return nil + end + m = table.clone(n) + elseif k == "rotate" and op.axes then + local axes = op.axes :: string + local r: { number } = Types.Scene.IDENTITY :: any + -- rotateXZY: R = Ry * Rz * Rx (column vectors); the value is always (x, y, z) angles + 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(Mat4.rotation(a, angle), r) + end + m = r + else + return nil + end + if op.invert and m then + m = Mat4.inverseFull(m) + end + return m +end + +local function lerpValue(a: any, b: any, f: number, quat: boolean): any + local na, nb = nums(a), nums(b) + if not na or not nb or #na ~= #nb then + return a + end + local out = table.create(#na) + if quat and #na == 4 then + local dot = 0 + for k = 1, 4 do + dot += na[k] * nb[k] + end + local sgn = if dot < 0 then -1 else 1 + for k = 1, 4 do + out[k] = na[k] + (nb[k] * sgn - na[k]) * f + end + return { t = "tuple", v = out } + end + for k = 1, #na do + out[k] = na[k] + (nb[k] - na[k]) * f + end + return { t = "tuple", v = out } +end + +-- samples interpolated linearly, held outside their range +local function opValueAt(op: Op, t: number?): any + local p = op.prop + local s = p.samples + if t ~= nil and s and #s.times > 0 then + local times, values = s.times, s.values + local lo, hi + for k = 1, #times do + local tk = times[k] + if values[k] ~= NONE then + if tk <= t and (lo == nil or tk > times[lo]) then + lo = k + end + if tk >= t and (hi == nil or tk < times[hi]) then + hi = k + end + end + end + if lo and hi then + if lo == hi or times[hi] == times[lo] then + return values[lo] + end + local f = (t - times[lo]) / (times[hi] - times[lo]) + return lerpValue(values[lo], values[hi], f, op.kind == "orient") + end + return values[lo or hi] + end + return propValue(p) +end + +local function localMatrix(ops: { Op }, t: number?): { number } + local m: { number } = Types.Scene.IDENTITY :: any + for _, op in ops do + local om = opMatrix(op, opValueAt(op, t)) + if om then + m = mul(m, om) + end + end + return m +end +Build.localMatrix = localMatrix + +-- ------------------------------------------------------------------------------------------------ build +function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) + local scene = Types.Scene.new() + local flipV = opts.flipV ~= false + local triangulate = opts.triangulate ~= false + local maxVertices = opts.maxVertices or 2 ^ 25 + local fetch = opts.fetch + local unsupported: { [string]: boolean } = {} + local meta = layer.meta + + local byPath: { [string]: Prim } = {} + local parentOf: { [Prim]: string } = {} + local pathOf: { [Prim]: string } = {} + local function merge(p: Prim) + if not p.variantSets then + return + end + local nested: { any }? = nil + local sel = p.meta.variants + local chosen = if type(sel) == "table" and sel.t == "dict" then sel.v else {} + for setName, set in p.variantSets :: any do + local name = str(chosen[setName]) + local body = name and set[name] -- unselected sets contribute nothing + if body then + for _, pn in body.order do + if not p.props[pn] then + p.props[pn] = body.props[pn] + table.insert(p.order, pn) + end + end + for _, c in body.children do + table.insert(p.children, c) + end + for k, v in body.meta do + if p.meta[k] == nil then + p.meta[k] = v + end + end + if body.variantSets then + nested = nested or {} + table.insert(nested :: any, body.variantSets) + end + end + end + p.variantSets = nil + for _, vs in nested or {} do + p.variantSets = vs + merge(p) + end + end + local function index(p: Prim, parent: string, depth: number) + if depth > 200 then + return + end + merge(p) + local path = joinPath(parent, p.name) + pathOf[p] = path + parentOf[p] = parent + local existing = byPath[path] + if existing and existing ~= p then + -- over / def of the same path in one layer: merged into the first spec + for _, pn in p.order do + if not existing.props[pn] then + existing.props[pn] = p.props[pn] + table.insert(existing.order, pn) + end + end + existing.typeName = existing.typeName or p.typeName + if p.specifier == "def" then + existing.specifier = "def" + end + for _, c in p.children do + table.insert(existing.children, c) + end + table.clear(p.children) + p.specifier = "class" + else + byPath[path] = p + end + for _, key in { "references", "payload", "inherits", "specializes" } do + local v = p.meta[key] + if v ~= nil and v ~= NONE then + unsupported[key] = true + end + end + for _, c in p.children do + index(c, path, depth + 1) + end + end + for _, p in layer.prims do + index(p, "/", 1) + end + if meta.subLayers ~= nil then + unsupported.subLayers = true + end + + local function propAt(path: string): (Prim?, Prop?) + local pp, pn = splitProp(path) + local prim = byPath[pp] + if not prim or not pn then + return prim, nil + end + return prim, prim.props[pn] + end + + local texCoordIndex: { [string]: number } = {} + local texCoordCount = 0 + local function texCoordFor(name: string): number + local k = texCoordIndex[name] + if k == nil then + k = texCoordCount + texCoordIndex[name] = k + texCoordCount += 1 + end + return k + end + -- "st" first, so materials and meshes agree on TEXCOORD_n + do + local names: { [string]: boolean } = {} + for _, p in byPath do + if p.typeName == "Mesh" then + for pn, pr in p.props do + local nm = string.match(pn, "^primvars:([^:]+)$") + if nm and (pr.typeName == "texCoord2f" or pr.typeName == "float2" or pr.typeName == "texCoord2d" or pr.typeName == "double2" or pr.typeName == "texCoord2h" or pr.typeName == "half2") and pr.array then + names[nm] = true + end + end + end + end + local list = {} + for nm in names do + table.insert(list, nm) + end + table.sort(list, function(a: string, b: string): boolean + local pa = if a == "st" then 0 elseif string.sub(a, 1, 2) == "st" then 1 else 2 + local pb = if b == "st" then 0 elseif string.sub(b, 1, 2) == "st" then 1 else 2 + if pa ~= pb then + return pa < pb + end + return a < b + end) + for _, nm in list do + texCoordFor(nm) + end + end + + type Source = { value: any?, shader: Prim?, output: string? } + local function input(prim: Prim, name: string, depth: number?): Source? + local d = depth or 0 + if d > 32 then + return nil + end + local p = prim.props["inputs:" .. name] + if not p then + return nil + end + if p.connect and #p.connect > 0 then + local target = resolvePath(pathOf[prim] or "/", p.connect[1]) + local tp, tn = splitProp(target) + local tprim = byPath[tp] + if tprim and tn then + local outName = string.match(tn, "^outputs:(.+)$") + local inName = string.match(tn, "^inputs:(.+)$") + if outName and tprim.typeName == "Shader" then + return { shader = tprim, output = outName } + elseif outName then + local op = tprim.props[tn] + if op and op.connect and #op.connect > 0 then + local t2 = resolvePath(tp, op.connect[1]) + local sp, sn = splitProp(t2) + local sprim = byPath[sp] + if sprim and sn and string.match(sn, "^outputs:") then + return { shader = sprim, output = string.sub(sn, 9) } + end + end + elseif inName then + local r = input(tprim, inName, d + 1) + if r then + return r + end + end + end + end + local v = propValue(p) + if v ~= nil then + return { value = v } + end + return nil + end + local function shaderId(p: Prim): string? + return str(propValue(p.props["info:id"])) + end + + local textureIndex: { [string]: number } = {} + local WRAP: { [string]: string } = { ["repeat"] = "repeat", clamp = "clamp", mirror = "mirror", black = "clamp", useMetadata = "repeat" } + local function textureRef(shader: Prim): Types.TextureRef? + if shaderId(shader) ~= "UsdUVTexture" then + return nil + end + local f = input(shader, "file") + local file = f and str(f.value) + if not file or file == "" then + return nil + end + local ws = input(shader, "wrapS") + local wt = input(shader, "wrapT") + local wrapS = WRAP[ws and str(ws.value) or "repeat"] or "repeat" + local wrapT = WRAP[wt and str(wt.value) or "repeat"] or "repeat" + local key = file .. "|" .. wrapS .. "|" .. wrapT + local ti = textureIndex[key] + if not ti then + local tex: Types.Texture = { name = shader.name, uri = file, sampler = { wrapS = wrapS :: any, wrapT = wrapT :: any } } + local ext = string.lower(string.match(file, "%.(%w+)$") or "") + tex.mime = MIME[ext] + local data = fetch and fetch(file) + if not data and string.sub(file, 1, 2) == "./" and fetch then + data = fetch(string.sub(file, 3)) + end + tex.data = data + local extras: { [string]: any } = { path = pathOf[shader] } + local cs = input(shader, "sourceColorSpace") + if cs and str(cs.value) then + extras.sourceColorSpace = str(cs.value) + end + tex.extras = { usd = extras } + table.insert(scene.textures, tex) + ti = #scene.textures + textureIndex[key] = ti + end + local ref: Types.TextureRef = { texture = ti :: number } + -- st: UsdPrimvarReader_float2, maybe through UsdTransform2d + local st = input(shader, "st") + local reader = st and st.shader + if reader and shaderId(reader) == "UsdTransform2d" then + local tr: { [string]: any } = {} + local rot = input(reader, "rotation") + local scl = input(reader, "scale") + local off = input(reader, "translation") + if rot and num(rot.value) and num(rot.value) ~= 0 then + tr.rotation = (num(rot.value) :: number) * DEG + end + if scl and nums(scl.value) then + tr.scale = nums(scl.value) + end + if off and nums(off.value) then + tr.offset = nums(off.value) + end + if next(tr) then + ref.transform = tr :: any + end + local inn = input(reader, "in") + reader = inn and inn.shader + end + if reader and string.find(shaderId(reader) or "", "^UsdPrimvarReader") then + local vn = input(reader, "varname") + local name = vn and str(vn.value) + if name then + local k = texCoordFor(name) + if k ~= 0 then + ref.texCoord = k + end + end + end + return ref + end + + local materialIndex: { [string]: number } = {} + local function material(path: string): number? + local mi = materialIndex[path] + if mi ~= nil then + return if mi > 0 then mi else nil + end + local mp = byPath[path] + if not mp or mp.typeName ~= "Material" then + materialIndex[path] = 0 + return nil + end + local mat = Types.Scene.material(mp.name) + mat.baseColor = { 0.18, 0.18, 0.18, 1 } + mat.metallic = 0 + mat.roughness = 0.5 + mat.extras = { usd = { path = path } } + local surf = mp.props["outputs:surface"] or mp.props["outputs:usd:surface"] + local shader: Prim? = nil + if surf and surf.connect and #surf.connect > 0 then + local sp = splitProp(resolvePath(path, surf.connect[1])) + shader = byPath[sp] + end + if shader and shaderId(shader) == "UsdPreviewSurface" then + local sh = shader :: Prim + local function value(name: string): any + local s = input(sh, name) + return s and s.value + end + local function tex(name: string): (Types.TextureRef?, Prim?) + local s = input(sh, name) + if s and s.shader then + local ref = textureRef(s.shader) + return ref, if ref then s.shader else nil + end + return nil, nil + end + local dc = nums(value("diffuseColor")) + if dc and #dc >= 3 then + mat.baseColor = { dc[1], dc[2], dc[3], 1 } + end + local dt, dshader = tex("diffuseColor") + if dt then + mat.baseColorTexture = dt + mat.baseColor = { 1, 1, 1, 1 } + local sc = input(dshader :: Prim, "scale") + local s = sc and nums(sc.value) + if s and #s >= 3 then + mat.baseColor = { s[1], s[2], s[3], s[4] or 1 } + end + end + local op = num(value("opacity")) + local ot = tex("opacity") + if op then + mat.baseColor[4] = op + end + local thr = num(value("opacityThreshold")) + if thr and thr > 0 then + mat.alphaMode = "mask" + mat.alphaCutoff = thr + elseif (op and op < 1) or ot then + mat.alphaMode = "blend" + end + local m = num(value("metallic")) + if m then + mat.metallic = m + end + local r = num(value("roughness")) + if r then + mat.roughness = r + end + local mt = tex("metallic") + local rt = tex("roughness") + if rt or mt then + mat.metallicRoughnessTexture = rt or mt + if mt then + mat.metallic = 1 + end + if rt then + mat.roughness = 1 + end + end + local e = nums(value("emissiveColor")) + if e and #e >= 3 then + mat.emissive = { e[1], e[2], e[3] } + end + local et = tex("emissiveColor") + if et then + mat.emissiveTexture = et + mat.emissive = { 1, 1, 1 } + end + local nt = tex("normal") + if nt then + mat.normalTexture = nt + end + local oc = tex("occlusion") + if oc then + mat.occlusionTexture = oc + end + local ext: { [string]: any } = {} + local ior = num(value("ior")) + if ior and ior ~= 1.5 then + ext.KHR_materials_ior = { ior = ior } + end + local cc = num(value("clearcoat")) + if cc and cc > 0 then + ext.KHR_materials_clearcoat = { clearcoatFactor = cc, clearcoatRoughnessFactor = num(value("clearcoatRoughness")) or 0.01 } + end + if next(ext) then + mat.extensions = ext + end + local usd: any = (mat.extras :: any).usd + if num(value("useSpecularWorkflow")) == 1 then + usd.useSpecularWorkflow = true + usd.specularColor = nums(value("specularColor")) + end + elseif shader then + unsupported["shader " .. (shaderId(shader :: Prim) or "?")] = true + end + table.insert(scene.materials, mat) + materialIndex[path] = #scene.materials + return #scene.materials + end + + -- material:binding, inherited from ancestors + local function binding(prim: Prim, path: string): number? + local p: Prim? = prim + local pp = path + while p do + local rel = p.props["material:binding"] or p.props["material:binding:preview"] or p.props["material:binding:full"] + if rel and rel.value and #rel.value > 0 then + return material(resolvePath(pp, rel.value[1])) + end + if pp == "/" then + break + end + pp = parentOf[p :: Prim] or "/" + p = byPath[pp] + end + return nil + end + + local colorMaterials: { [string]: number } = {} + local function colorMaterial(c: { number }): number + local key = string.format("%.6g,%.6g,%.6g,%.6g", c[1], c[2], c[3], c[4] or 1) + local mi = colorMaterials[key] + if not mi then + local mat = Types.Scene.material("displayColor") + mat.baseColor = { c[1], c[2], c[3], c[4] or 1 } + mat.metallic = 0 + mat.roughness = 0.5 + if (c[4] or 1) < 1 then + mat.alphaMode = "blend" + end + mat.extras = { usd = { displayColor = true } } + table.insert(scene.materials, mat) + mi = #scene.materials + colorMaterials[key] = mi + end + return mi :: number + end + + type Primvar = { data: { number }, w: number, interp: string, idx: { number }? } + local function primvar(p: Prop?, defaultInterp: string): Primvar? + if not p then + return nil + end + local v = propValue(p) + if not isArr(v) then + return nil + end + local interp = defaultInterp + if p.meta and str(p.meta.interpolation) then + interp = str(p.meta.interpolation) :: string + end + return { data = v.v, w = v.w, interp = interp } + end + + local function buildMesh(prim: Prim, path: string): (Types.Mesh?, string?) + local pts = propValue(prim.props.points) + local cnt = propValue(prim.props.faceVertexCounts) + local idx = propValue(prim.props.faceVertexIndices) + if not isArr(pts) or pts.w ~= 3 then + return nil, nil + end + local points: { number } = pts.v + local npts = #points // 3 + local counts: { number } = if isArr(cnt) then cnt.v else {} + local indices: { number } = if isArr(idx) then idx.v else {} + local nfaces = #counts + local ncorners = 0 + for f = 1, nfaces do + local c = counts[f] + if c < 0 or c ~= c // 1 then + return nil, "bad faceVertexCounts at " .. path + end + ncorners += c + end + if ncorners ~= #indices then + return nil, "faceVertexCounts and faceVertexIndices disagree at " .. path + end + if ncorners > maxVertices or npts > maxVertices then + return nil, "LIMIT" + end + for k = 1, ncorners do + local v = indices[k] + if v < 0 or v >= npts or v ~= v // 1 then + return nil, "a face vertex index out of range at " .. path + end + end + local faceStart = table.create(nfaces + 1, 0) + do + local acc = 0 + for f = 1, nfaces do + faceStart[f] = acc + acc += counts[f] + end + faceStart[nfaces + 1] = acc + end + local function sizeOk(pv: Primvar): boolean + local n = (if pv.idx then #pv.idx else #pv.data // pv.w) + local want = if pv.interp == "constant" then 1 + elseif pv.interp == "uniform" then nfaces + elseif pv.interp == "faceVarying" then ncorners + else npts + if n < want then + return false + end + if pv.idx then + local m = #pv.data // pv.w + for _, k in pv.idx :: { number } do + if k < 0 or k >= m or k ~= k // 1 then + return false + end + end + end + return #pv.data % pv.w == 0 + end + local function withIndices(pv: Primvar?, name: string): Primvar? + if not pv then + return nil + end + local ip = propValue(prim.props[name .. ":indices"]) + if isArr(ip) and ip.w == 1 then + pv.idx = ip.v + end + if not sizeOk(pv) then + unsupported["mismatched primvar " .. name] = true + return nil + end + return pv + end + local normals = withIndices(primvar(prim.props["primvars:normals"], "vertex"), "primvars:normals") + or withIndices(primvar(prim.props.normals, "vertex"), "normals") + if normals and normals.w ~= 3 then + normals = nil + end + local color = withIndices(primvar(prim.props["primvars:displayColor"], "constant"), "primvars:displayColor") + if color and color.w ~= 3 then + color = nil + end + local opacity = withIndices(primvar(prim.props["primvars:displayOpacity"], "constant"), "primvars:displayOpacity") + if opacity and opacity.w ~= 1 then + opacity = nil + end + local uvs: { [number]: Primvar } = {} + for pn, pr in prim.props do + local nm = string.match(pn, "^primvars:([^:]+)$") + if nm and pr.array and (pr.typeName == "texCoord2f" or pr.typeName == "float2" or pr.typeName == "texCoord2d" or pr.typeName == "double2" or pr.typeName == "texCoord2h" or pr.typeName == "half2") then + local pv = withIndices(primvar(pr, "vertex"), pn) + if pv and pv.w == 2 then + uvs[texCoordFor(nm)] = pv + end + end + end + local function get(pv: Primvar, point: number, face: number, corner: number, c: number): number + local e = if pv.interp == "constant" then 0 + elseif pv.interp == "uniform" then face + elseif pv.interp == "faceVarying" then corner + else point + if pv.idx then + e = (pv.idx :: { number })[e + 1] + end + return pv.data[e * pv.w + c + 1] or 0 + end + local perCorner = false + for _, pv in { normals, color, opacity } do + if pv and (pv.interp == "faceVarying" or pv.interp == "uniform") then + perCorner = true + end + end + for _, pv in uvs do + if pv.interp == "faceVarying" or pv.interp == "uniform" then + perCorner = true + end + end + local leftHanded = str(propValue(prim.props.orientation)) == "leftHanded" + local hole: { [number]: boolean } = {} + local hv = propValue(prim.props.holeIndices) + if isArr(hv) then + for _, f in hv.v do + hole[f] = true + end + end + -- face sets: GeomSubsets of "face" elements, then the rest + local meshMaterial = binding(prim, path) + local constantColor: { number }? = nil + if color and color.interp == "constant" then + constantColor = { get(color, 0, 0, 0, 0), get(color, 0, 0, 0, 1), get(color, 0, 0, 0, 2), if opacity and opacity.interp == "constant" then get(opacity, 0, 0, 0, 0) else 1 } + end + type Set = { faces: { number }, material: number?, name: string? } + local sets: { Set } = {} + local used: { [number]: boolean } = {} + for _, c in prim.children do + if c.typeName == "GeomSubset" and c.specifier ~= "class" then + local et = str(propValue(c.props.elementType)) or "face" + local fi = propValue(c.props.indices) + if et == "face" and isArr(fi) then + local faces = {} + for _, f in fi.v do + if f >= 0 and f < nfaces and f == f // 1 and not used[f] then + used[f] = true + table.insert(faces, f) + end + end + table.sort(faces) + local cpath = joinPath(path, c.name) + local rel = c.props["material:binding"] or c.props["material:binding:preview"] + local mi = if rel and rel.value and #rel.value > 0 then material(resolvePath(cpath, rel.value[1])) else meshMaterial + table.insert(sets, { faces = faces, material = mi, name = c.name }) + end + end + end + do + local rest = {} + for f = 0, nfaces - 1 do + if not used[f] then + table.insert(rest, f) + end + end + if #rest > 0 or #sets == 0 then + table.insert(sets, 1, { faces = rest, material = meshMaterial }) + end + end + local mesh: Types.Mesh = { name = prim.name, primitives = {} } + for _, set in sets do + local keyToVert: { [number]: number } = {} + local vp, vf, vc = {}, {}, {} + local nv = 0 + local out: { number } = {} + local faceSizes: { number } = {} + for _, f in set.faces do + local cnt0 = counts[f + 1] + if cnt0 >= 3 and not hole[f] then + local base = faceStart[f + 1] + local verts = table.create(cnt0) :: { number } + for k = 0, cnt0 - 1 do + local corner = base + k + local point = indices[corner + 1] + local key = if perCorner then corner else point + local v = keyToVert[key] + if not v then + v = nv + keyToVert[key] = v + nv += 1 + vp[nv], vf[nv], vc[nv] = point, f, corner + end + verts[k + 1] = v + end + if leftHanded then + local r = table.create(cnt0) :: { number } + for k = 1, cnt0 do + r[k] = verts[cnt0 - k + 1] + end + verts = r + end + if triangulate then + for k = 2, cnt0 - 1 do + table.insert(out, verts[1]) + table.insert(out, verts[k]) + table.insert(out, verts[k + 1]) + end + else + for k = 1, cnt0 do + table.insert(out, verts[k]) + end + table.insert(faceSizes, cnt0) + end + end + end + if nv > 0 then + local attrs: { [string]: Types.Accessor } = {} + local pos = Types.Scene.accessor(nil, "f32", 3, nv) + for v = 1, nv do + local p0 = vp[v] * 3 + buffer.writef32(pos.data, (v - 1) * 12, points[p0 + 1]) + buffer.writef32(pos.data, (v - 1) * 12 + 4, points[p0 + 2]) + buffer.writef32(pos.data, (v - 1) * 12 + 8, points[p0 + 3]) + end + attrs.POSITION = pos + local function fill(pv: Primvar, comps: number, flip: boolean): Types.Accessor + local a = Types.Scene.accessor(nil, "f32", comps, nv) + for v = 1, nv do + for c = 0, comps - 1 do + local x = get(pv, vp[v], vf[v], vc[v], c) + if flip and c == 1 then + x = 1 - x + end + buffer.writef32(a.data, ((v - 1) * comps + c) * 4, x) + end + end + return a + end + if normals then + local nrm = fill(normals, 3, false) + if leftHanded then + -- normals follow the authored (left-handed) winding: keep them as authored + end + attrs.NORMAL = nrm + end + for k, pv in uvs do + attrs["TEXCOORD_" .. k] = fill(pv, 2, flipV) + end + local mi = set.material + if color and not constantColor then + if opacity then + local a = Types.Scene.accessor(nil, "f32", 4, nv) + for v = 1, nv do + for c = 0, 2 do + buffer.writef32(a.data, ((v - 1) * 4 + c) * 4, get(color, vp[v], vf[v], vc[v], c)) + end + buffer.writef32(a.data, ((v - 1) * 4 + 3) * 4, get(opacity, vp[v], vf[v], vc[v], 0)) + end + attrs.COLOR_0 = a + else + attrs.COLOR_0 = fill(color, 3, false) + end + elseif constantColor and mi == nil then + mi = colorMaterial(constantColor) + end + local ind = Types.Scene.accessor(nil, "u32", 1, #out) + for k, v in out do + buffer.writeu32(ind.data, (k - 1) * 4, v) + end + local prm: Types.Primitive = { attributes = attrs, indices = ind, mode = if triangulate then "triangles" else "polygons", material = mi } + if not triangulate then + local fa = Types.Scene.accessor(nil, "u32", 1, #faceSizes) + for k, v in faceSizes do + buffer.writeu32(fa.data, (k - 1) * 4, v) + end + prm.faces = fa + end + if set.name then + prm.extras = { usd = { subset = set.name } } + end + local ds = propValue(prim.props.doubleSided) + if mi and (ds == 1 or ds == true) then + local m = mi and scene.materials[mi] + if m then + m.doubleSided = true + end + end + table.insert(mesh.primitives, prm) + end + end + if #mesh.primitives == 0 then + return nil, nil + end + return mesh, nil + end + + local function camera(prim: Prim): Types.Camera + local function f(name: string, d: number): number + return num(propValue(prim.props[name])) or d + end + local focal = f("focalLength", 50) + local hap = f("horizontalAperture", 20.955) + local vap = f("verticalAperture", 15.2908) + local clip = nums(propValue(prim.props.clippingRange)) or { 1, 1000000 } + local proj = str(propValue(prim.props.projection)) or "perspective" + if proj == "orthographic" then + return { name = prim.name, type = "orthographic", xmag = hap / 20, ymag = vap / 20, znear = clip[1] or 1, zfar = clip[2] or 1000000 } + end + return { + name = prim.name, + type = "perspective", + yfov = 2 * math.atan(vap / (2 * focal)), + aspect = if vap > 0 then hap / vap else nil, + znear = clip[1] or 1, + zfar = clip[2], + } + end + local function light(prim: Prim): Types.Light + local function f(name: string, d: number): number + return num(propValue(prim.props["inputs:" .. name])) or num(propValue(prim.props[name])) or d + end + local col = nums(propValue(prim.props["inputs:color"])) or nums(propValue(prim.props.color)) or { 1, 1, 1 } + local intensity = f("intensity", 1) * 2 ^ f("exposure", 0) + local l: Types.Light = { name = prim.name, type = "point", color = { col[1] or 1, col[2] or 1, col[3] or 1 }, intensity = intensity } + local t = prim.typeName + local cone = num(propValue(prim.props["inputs:shaping:cone:angle"])) or num(propValue(prim.props["shaping:cone:angle"])) + if t == "DistantLight" then + l.type = "directional" + elseif t == "RectLight" or t == "DiskLight" then + l.type = "spot" + l.outerCone = math.pi / 2 + l.innerCone = 0 + end + if cone and cone < 90 then + local soft = num(propValue(prim.props["inputs:shaping:cone:softness"])) or 0 + l.type = "spot" + l.outerCone = cone * DEG + l.innerCone = math.max(0, cone * DEG * (1 - soft)) + end + return l + end + + local tcps = num(meta.timeCodesPerSecond) or num(meta.framesPerSecond) or 24 + if tcps <= 0 then + tcps = 24 + end + local animation: Types.Animation = { name = "usd", channels = {} } + local failure: string? = nil + + local function isNode(p: Prim): boolean + -- class prims are abstract; an over with no def is not defined (UsdStage traversal skips both) + if p.specifier == "class" or p.specifier == "over" or NOT_NODES[p.typeName or ""] then + if SKEL[p.typeName or ""] then + unsupported["UsdSkel (skeletons, skinning, blend shapes)"] = true + end + return false + end + if p.typeName == "Scope" or p.typeName == nil then + -- scopes / untyped prims holding only materials are not nodes + local function hasContent(q: Prim, d: number): boolean + if d > 100 then + return false + end + for _, c in q.children do + if c.specifier ~= "class" and not NOT_NODES[c.typeName or ""] then + if c.typeName ~= nil and c.typeName ~= "Scope" then + return true + end + if hasContent(c, d + 1) then + return true + end + end + end + return false + end + if p.typeName == "Scope" or #p.children > 0 then + return hasContent(p, 0) + end + end + return true + end + + local function node(p: Prim, path: string, parent: number?, depth: number) + if depth > 200 or failure then + return + end + if not isNode(p) then + return + end + local n: Types.Node = { name = p.name, children = {}, extras = { usd = { path = path, type = p.typeName } } } + table.insert(scene.nodes, n) + local ni = #scene.nodes + local ops, reset = xformOps(p) + local times: { number } = {} + do + local seen: { [number]: boolean } = {} + for _, op in ops do + local s = op.prop.samples + if s and #s.times > 1 then + for _, t in s.times do + if not seen[t] then + seen[t] = true + table.insert(times, t) + end + end + end + end + table.sort(times) + end + if #times > 1 then + local count = math.min(#times, 100000) + local tin = Types.Scene.accessor(nil, "f32", 1, count) + local tr = Types.Scene.accessor(nil, "f32", 3, count) + local ro = Types.Scene.accessor(nil, "f32", 4, count) + local sc = Types.Scene.accessor(nil, "f32", 3, count) + local prev: { number }? = nil + for k = 1, count do + 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 + prev = R + buffer.writef32(tin.data, (k - 1) * 4, times[k] / tcps) + for c = 0, 2 do + buffer.writef32(tr.data, ((k - 1) * 3 + c) * 4, T[c + 1]) + buffer.writef32(sc.data, ((k - 1) * 3 + c) * 4, S[c + 1]) + end + for c = 0, 3 do + 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" } :: 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 = Mat4.decompose(localMatrix(ops, times[1])) + n.translation, n.rotation, n.scale = T, R, S + elseif #ops > 0 then + local simple = true + local stage = 0 + for _, op in ops do + local st = if op.kind == "translate" then 1 elseif op.kind == "rotate" or op.kind == "orient" then 2 elseif op.kind == "scale" then 3 else 9 + if op.invert or st == 9 or st <= stage or string.find(op.prop.name, "^xformOp:%a+:") then + simple = false + end + stage = st + end + local m = localMatrix(ops, nil) + if simple then + local T, R, S = Mat4.decompose(m) + local tx = ops[1].kind == "translate" + if tx then + n.translation = T + end + for _, op in ops do + if op.kind == "rotate" or op.kind == "orient" then + n.rotation = R + elseif op.kind == "scale" then + n.scale = S + end + end + -- a negative scale with a rotation is not TRS-representable through decompose: keep the matrix + local back = Types.Scene.nodeMatrix(n) + for k = 1, 16 do + if math.abs(back[k] - m[k]) > 1e-5 * math.max(1, math.abs(m[k])) then + simple = false + break + end + end + if not simple then + n.translation, n.rotation, n.scale = nil, nil, nil + end + end + if not simple then + local identity = true + for k = 1, 16 do + if m[k] ~= Types.Scene.IDENTITY[k] then + identity = false + end + end + if not identity then + n.matrix = m + end + end + end + if reset or parent == nil then + table.insert(scene.roots, ni) + if reset and parent then + (n.extras :: any).usd.resetXformStack = true + end + else + table.insert(scene.nodes[parent].children, ni) + end + local t = p.typeName + if t == "Mesh" then + local mesh, err = buildMesh(p, path) + if err == "LIMIT" then + failure = "LIMIT" + return + elseif err then + failure = err + return + end + if mesh then + table.insert(scene.meshes, mesh) + n.mesh = #scene.meshes + end + elseif t == "Camera" then + table.insert(scene.cameras, camera(p)) + n.camera = #scene.cameras + elseif t and LIGHTS[t] and t ~= "DomeLight" then + table.insert(scene.lights, light(p)) + n.light = #scene.lights + elseif t and t ~= "Xform" and t ~= "Scope" and t ~= "Mesh" and t ~= "DomeLight" and t ~= "SkelRoot" then + unsupported["prim type " .. t] = true + end + for _, c in p.children do + node(c, joinPath(path, c.name), ni, depth + 1) + end + end + + for _, p in layer.prims do + if p.specifier ~= "class" then + node(p, "/" .. p.name, nil, 1) + end + end + if failure then + return nil, failure + end + if #animation.channels > 0 then + table.insert(scene.animations, animation) + end + + local up = str(meta.upAxis) + scene.meta.up = if up == "Z" then "z" else "y" + local mpu = num(meta.metersPerUnit) + if mpu and mpu > 0 then + scene.meta.unit = mpu + end + local list = {} + for k in unsupported do + table.insert(list, k) + end + table.sort(list) + scene.meta.source = { + format = "usda", + defaultPrim = str(meta.defaultPrim), + timeCodesPerSecond = tcps, + startTimeCode = num(meta.startTimeCode), + endTimeCode = num(meta.endTimeCode), + doc = str(meta.doc), + unsupported = if #list > 0 then list else nil, + } + return scene, nil +end + +return Build +end +__FILES["model/usda/Parse"] = function() + +-- model/usda/Parse: USD ASCII ("#usda 1.0") to prim specs, from the Sdf text grammar as Pixar's USD writes and reads +-- it; new code. .spline blocks and unknown constructs are skipped by bracket matching. Never throws. +local Parse = {} + +type Arr = { t: "arr", w: number, v: { number } } -- w numbers per element (tuples flattened) +type Value = any + +type Prop = { + name: string, + rel: boolean, + typeName: string?, + array: boolean?, + uniform: boolean?, + custom: boolean?, + value: Value?, -- relationships: { path strings } + hasValue: boolean?, + samples: { times: { number }, values: { Value } }?, + connect: { string }?, + meta: { [string]: Value }?, +} +type Prim = { + specifier: string, + typeName: string?, + name: string, + meta: { [string]: Value }, + props: { [string]: Prop }, + order: { string }, + children: { Prim }, + variantSets: { [string]: { [string]: Prim } }?, +} +type Layer = { meta: { [string]: Value }, prims: { Prim } } + +local NONE = table.freeze({ t = "none" }) +Parse.NONE = NONE + +local sfind, ssub, sbyte, smatch, gmatch = string.find, string.sub, string.byte, string.match, string.gmatch + +local LISTOPS = { prepend = true, append = true, add = true, delete = true, reorder = true } +local VARIABILITY = { uniform = true, varying = true, config = true } +local MAX_DEPTH = 200 + +local function fail(msg: string, at: number): never + error({ usda = msg, at = at }, 0) +end + +local function parser(s: string, maxBytes: number) + local n = #s + local depth = 0 + + local function ws(i: number): number + while true do + local _, e = sfind(s, "^[ \t\r\n]+", i) + if e then + i = e + 1 + end + local c = sbyte(s, i) + if c == 35 then + local nl = sfind(s, "\n", i, true) + i = if nl then nl + 1 else n + 1 + elseif c == 47 and sbyte(s, i + 1) == 47 then + local nl = sfind(s, "\n", i, true) + i = if nl then nl + 1 else n + 1 + elseif c == 47 and sbyte(s, i + 1) == 42 then + local _, ce = sfind(s, "*/", i + 2, true) + if not ce then + fail("unterminated comment", i) + end + i = (ce :: number) + 1 + else + return i + end + end + end + + local function expect(i: number, ch: string): number + i = ws(i) + if ssub(s, i, i) ~= ch then + fail("expected '" .. ch .. "'", i) + end + return i + 1 + end + + local function ident(i: number): (string?, number) + local a, e = sfind(s, "^[%a_][%w_:]*", i) + if not a then + return nil, i + end + return ssub(s, a, e), (e :: number) + 1 + end + + local ESC = { n = "\n", t = "\t", r = "\r", ["\\"] = "\\", ['"'] = '"', ["'"] = "'", ["0"] = "\0", a = "\a", b = "\b", f = "\f", v = "\v" } + local function unescape(str: string): string + if not sfind(str, "\\", 1, true) then + return str + end + return (string.gsub(str, "\\(x?)(.)", function(x: string, c: string): string + if x == "x" then + return "\\x" .. c + end + return ESC[c] or c + end)) + end + + local function str(i: number): (string, number) + local q = ssub(s, i, i) + if ssub(s, i, i + 2) == q .. q .. q then + local e = sfind(s, q .. q .. q, i + 3, true) + if not e then + fail("unterminated string", i) + end + return unescape(ssub(s, i + 3, (e :: number) - 1)), (e :: number) + 3 + end + local j = i + 1 + while true do + local a = sfind(s, "[\\\n" .. q .. "]", j) + if not a then + fail("unterminated string", i) + end + local c = sbyte(s, a :: number) + if c == 92 then + j = (a :: number) + 2 + elseif c == 10 then + fail("newline in string", a :: number) + else + return unescape(ssub(s, i + 1, (a :: number) - 1)), (a :: number) + 1 + end + end + end + + local function number(i: number): (number?, number) + local a, e = sfind(s, "^[-+]?%d*%.?%d*[eE][-+]?%d+", i) + if not a then + a, e = sfind(s, "^[-+]?%d*%.?%d*", i) + end + if a and (e :: number) >= (a :: number) then + local v = tonumber(ssub(s, a, e)) + if v then + return v, (e :: number) + 1 + end + end + local w, e2 = sfind(s, "^[-+]?%a+", i) + if w then + local word = string.lower(ssub(s, w, e2)) + if word == "inf" or word == "+inf" then + return math.huge, (e2 :: number) + 1 + elseif word == "-inf" then + return -math.huge, (e2 :: number) + 1 + elseif word == "nan" or word == "-nan" or word == "+nan" then + return 0 / 0, (e2 :: number) + 1 + end + end + return nil, i + end + + local function skipBalanced(i: number): number + local open = sbyte(s, i) + local level = 0 + while i <= n do + i = ws(i) + local c = sbyte(s, i) + if c == nil then + break + end + if c == 40 or c == 91 or c == 123 then + level += 1 + i += 1 + elseif c == 41 or c == 93 or c == 125 then + level -= 1 + i += 1 + if level == 0 then + return i + end + elseif c == 34 or c == 39 then + local _, j = str(i) + i = j + elseif c == 64 then + local e = sfind(s, "@", i + 1, true) + i = if e then e + 1 else n + 1 + elseif c == 60 then + local e = sfind(s, ">", i + 1, true) + i = if e then e + 1 else n + 1 + else + local _, e = sfind(s, "^[^%(%)%[%]{}\"'@<#/ \t\r\n]+", i) + i = if e then e + 1 else i + 1 + end + end + fail("unbalanced " .. string.char(open or 63), i) + end + + local value: (i: number) -> (Value, number) + local metadata: (i: number) -> ({ [string]: Value }, number) + + local function list(i: number): (Value, number) + local close = sfind(s, "]", i + 1, true) + if close then + local body = ssub(s, i + 1, close - 1) + if not sfind(body, "[^%d%s%.,eE%-%+%(%)]") then + local first = smatch(body, "^%s*%(([^%)]*)%)") + local w = 1 + if first then + w = 0 + for _ in gmatch(first, "[^%s,]+") do + w += 1 + end + elseif sfind(body, "[%(%)]") then + w = -1 + end + if w > 0 then + local out: { number } = {} + local k = 0 + local ok = true + for tok in gmatch(body, "[^%s,%(%)]+") do + local v = tonumber(tok) + if not v then + ok = false + break + end + k += 1 + out[k] = v + end + if ok and k % w == 0 then + if k * 8 > maxBytes then + fail("array over the size limit", i) + end + return { t = "arr", w = w, v = out } :: Arr, close + 1 + end + end + end + end + local items = {} + i += 1 + while true do + i = ws(i) + local c = ssub(s, i, i) + if c == "]" then + i += 1 + break + elseif c == "" then + fail("unterminated list", i) + end + local v + v, i = value(i) + table.insert(items, v) + i = ws(i) + if ssub(s, i, i) == "(" then + local _ + _, i = metadata(i) + i = ws(i) + end + c = ssub(s, i, i) + if c == "," then + i += 1 + elseif c ~= "]" then + fail("expected ',' or ']' in a list", i) + end + end + local w: number? = nil + local flat: { number } = {} + for _, it in items do + if type(it) == "number" then + if w and w ~= 1 then + return { t = "list", v = items }, i + end + w = 1 + table.insert(flat, it) + elseif type(it) == "table" and it.t == "tuple" then + local tw = #it.v + if (w and w ~= tw) or tw == 0 then + return { t = "list", v = items }, i + end + w = tw + for _, x in it.v do + if type(x) ~= "number" then + return { t = "list", v = items }, i + end + table.insert(flat, x) + end + else + return { t = "list", v = items }, i + end + end + if w == nil then + return { t = "list", v = items }, i + end + return { t = "arr", w = w, v = flat } :: Arr, i + end + + local function tuple(i: number): (Value, number) + local items = {} + i += 1 + while true do + i = ws(i) + local c = ssub(s, i, i) + if c == ")" then + i += 1 + break + elseif c == "" then + fail("unterminated tuple", i) + end + local v + v, i = value(i) + table.insert(items, v) + i = ws(i) + c = ssub(s, i, i) + if c == "," then + i += 1 + elseif c ~= ")" then + fail("expected ',' or ')' in a tuple", i) + end + end + return { t = "tuple", v = items }, i + end + + local function dict(i: number): (Value, number) + local out: { [string]: Value } = {} + i += 1 + while true do + i = ws(i) + local c = ssub(s, i, i) + if c == "}" then + i += 1 + break + elseif c == "" then + fail("unterminated dictionary", i) + elseif c == ";" or c == "," then + i += 1 + continue + end + local ty + ty, i = ident(i) + if not ty then + fail("expected a type in a dictionary", i) + end + i = ws(i) + if ssub(s, i, i + 1) == "[]" then + i += 2 + end + i = ws(i) + local key: string? + c = ssub(s, i, i) + if c == '"' or c == "'" then + key, i = str(i) + else + key, i = ident(i) + end + if not key then + fail("expected a key in a dictionary", i) + end + i = expect(i, "=") + local v + v, i = value(i) + out[key :: string] = v + end + return { t = "dict", v = out }, i + end + + function value(i: number): (Value, number) + depth += 1 + if depth > MAX_DEPTH then + fail("nesting too deep", i) + end + i = ws(i) + local c = ssub(s, i, i) + local v: Value + if c == "[" then + v, i = list(i) + elseif c == "(" then + v, i = tuple(i) + elseif c == "{" then + v, i = dict(i) + elseif c == '"' or c == "'" then + v, i = str(i) + elseif c == "@" then + local path + if ssub(s, i, i + 2) == "@@@" then + local e = sfind(s, "@@@", i + 3, true) + if not e then + fail("unterminated asset path", i) + end + path, i = ssub(s, i + 3, (e :: number) - 1), (e :: number) + 3 + else + local e = sfind(s, "@", i + 1, true) + if not e then + fail("unterminated asset path", i) + end + path, i = ssub(s, i + 1, (e :: number) - 1), (e :: number) + 1 + end + local a: { [string]: any } = { t = "asset", v = path } + local j = ws(i) + if ssub(s, j, j) == "<" then + local e = sfind(s, ">", j + 1, true) + if not e then + fail("unterminated path", j) + end + a.path = ssub(s, j + 1, (e :: number) - 1) + i = (e :: number) + 1 + end + v = a + elseif c == "<" then + local e = sfind(s, ">", i + 1, true) + if not e then + fail("unterminated path", i) + end + v, i = { t = "path", v = ssub(s, i + 1, (e :: number) - 1) }, (e :: number) + 1 + else + local num, j = number(i) + if num ~= nil then + v, i = num, j + else + local id + id, j = ident(i) + if not id then + fail("expected a value", i) + end + i = j + if id == "None" then + v = NONE + elseif id == "true" then + v = true + elseif id == "false" then + v = false + else + v = { t = "id", v = id } + end + end + end + depth -= 1 + return v, i + end + + function metadata(i: number): ({ [string]: Value }, number) + local out: { [string]: Value } = {} + i = expect(i, "(") + while true do + i = ws(i) + local c = ssub(s, i, i) + if c == ")" then + return out, i + 1 + elseif c == "" then + fail("unterminated metadata", i) + elseif c == ";" or c == "," then + i += 1 + continue + elseif c == '"' or c == "'" then + out.doc, i = str(i) + continue + end + local key + key, i = ident(i) + if not key then + fail("expected a metadata key", i) + end + local op: string? = nil + if LISTOPS[key] then + op = key + i = ws(i) + key, i = ident(i) + if not key then + fail("expected a metadata key", i) + end + end + i = ws(i) + if ssub(s, i, i) == "=" then + local v + v, i = value(i + 1) + if op == "delete" then + elseif op and op ~= "reorder" then + local prev = out[key :: string] + if type(prev) == "table" and prev.t == "list" and type(v) == "table" and v.t == "list" then + for _, x in v.v do + table.insert(prev.v, x) + end + else + out[key :: string] = v + end + else + out[key :: string] = v + end + end + end + end + + local function samples(i: number): ({ times: { number }, values: { Value } }, number) + local times: { number }, values: { Value } = {}, {} + i = expect(i, "{") + while true do + i = ws(i) + local c = ssub(s, i, i) + if c == "}" then + i += 1 + break + elseif c == "" then + fail("unterminated time samples", i) + elseif c == "," then + i += 1 + continue + end + local t + t, i = number(i) + if t == nil then + fail("expected a time code", i) + end + i = expect(i, ":") + local v + v, i = value(i) + table.insert(times, t :: number) + table.insert(values, v) + end + return { times = times, values = values }, i + end + + local function targets(v: Value): { string } + local out = {} + if type(v) == "table" then + if v.t == "path" then + table.insert(out, v.v) + elseif v.t == "list" then + for _, x in v.v do + if type(x) == "table" and x.t == "path" then + table.insert(out, x.v) + end + end + end + end + return out + end + + local primBody: (i: number, prim: Prim) -> number + + local function newPrim(specifier: string, typeName: string?, name: string): Prim + return { specifier = specifier, typeName = typeName, name = name, meta = {}, props = {}, order = {}, children = {} } + end + + -- def Type "name" ( meta ) { body } + local function prim(i: number, specifier: string): (Prim, number) + i = ws(i) + local typeName: string? = nil + local c = ssub(s, i, i) + if c ~= '"' and c ~= "'" then + typeName, i = ident(i) + if not typeName then + fail("expected a prim type or name", i) + end + i = ws(i) + while ssub(s, i, i) == "." do + local more + more, i = ident(i + 1) + typeName = (typeName :: string) .. "." .. (more or "") + end + i = ws(i) + end + c = ssub(s, i, i) + if c ~= '"' and c ~= "'" then + fail("expected a prim name", i) + end + local name + name, i = str(i) + local p = newPrim(specifier, typeName, name) + i = ws(i) + if ssub(s, i, i) == "(" then + p.meta, i = metadata(i) + end + i = expect(i, "{") + i = primBody(i, p) + return p, i + end + + -- variantSet "name" = { "variant" ( meta ) { body } ... } + local function variantSet(i: number, p: Prim): number + i = ws(i) + local setName + setName, i = str(i) + i = expect(i, "=") + i = expect(i, "{") + local sets = p.variantSets or {} + p.variantSets = sets + local set = sets[setName] or {} + sets[setName] = set + while true do + i = ws(i) + local c = ssub(s, i, i) + if c == "}" then + return i + 1 + elseif c ~= '"' and c ~= "'" then + fail("expected a variant name", i) + end + local vname + vname, i = str(i) + local body = newPrim("def", nil, vname) + i = ws(i) + if ssub(s, i, i) == "(" then + body.meta, i = metadata(i) + end + i = expect(i, "{") + i = primBody(i, body) + set[vname] = body + end + end + + -- [listop] [custom] [uniform|varying|config] (rel name | type[] name)[.connect|.timeSamples|...] + local function property(i: number, first: string, p: Prim): number + local word: string? = first + local op: string? = nil + if LISTOPS[word :: string] then + op = word + i = ws(i) + word, i = ident(i) + end + local custom, uniform = false, false + if word == "custom" then + custom = true + i = ws(i) + word, i = ident(i) + end + if word and VARIABILITY[word] then + uniform = word == "uniform" + i = ws(i) + word, i = ident(i) + end + if not word then + fail("expected a property", i) + end + local isRel = word == "rel" + local typeName: string? = nil + local array = false + if not isRel then + typeName = word + i = ws(i) + if ssub(s, i, i + 1) == "[]" then + array = true + i += 2 + end + end + i = ws(i) + local name + name, i = ident(i) + if not name then + fail("expected a property name", i) + end + local suffix: string? = nil + if ssub(s, i, i) == "." then + suffix, i = ident(i + 1) + end + local prop = p.props[name :: string] + if not prop then + prop = { name = name :: string, rel = isRel } :: Prop + p.props[name :: string] = prop + table.insert(p.order, name :: string) + end + local pr = prop :: Prop + if typeName then + pr.typeName, pr.array = typeName, array + end + pr.uniform = pr.uniform or uniform or nil + pr.custom = pr.custom or custom or nil + i = ws(i) + if ssub(s, i, i) == "=" then + i = ws(i + 1) + if suffix == "timeSamples" then + pr.samples, i = samples(i) + elseif suffix == "spline" or (suffix ~= nil and suffix ~= "connect" and suffix ~= "default" and ssub(s, i, i) == "{") then + i = skipBalanced(i) + else + local v + v, i = value(i) + if op == "delete" then + elseif suffix == "connect" then + pr.connect = targets(v) + elseif isRel then + pr.value = targets(v) + pr.hasValue = true + else + pr.value = v + pr.hasValue = true + end + end + end + i = ws(i) + if ssub(s, i, i) == "(" then + local m + m, i = metadata(i) + if pr.meta then + for k, v in m do + (pr.meta :: any)[k] = v + end + else + pr.meta = m + end + end + return i + end + + function primBody(i: number, p: Prim): number + depth += 1 + if depth > MAX_DEPTH then + fail("nesting too deep", i) + end + while true do + i = ws(i) + local c = ssub(s, i, i) + if c == "}" then + depth -= 1 + return i + 1 + elseif c == "" then + fail("unterminated prim", i) + elseif c == ";" then + i += 1 + continue + end + local word, j = ident(i) + if not word then + fail("unexpected character in a prim", i) + end + if word == "def" or word == "over" or word == "class" then + local child + child, i = prim(j, word) + table.insert(p.children, child) + elseif word == "variantSet" then + i = variantSet(j, p) + elseif word == "reorder" then + local k = ws(j) + local w2, k2 = ident(k) + if w2 == "nameChildren" or w2 == "properties" or w2 == "rootPrims" then + k2 = expect(k2, "=") + local _ + _, i = value(k2) + else + i = property(j, word, p) + end + else + i = property(j, word, p) + end + end + end + + local function layer(): Layer + local i = 1 + if ssub(s, 1, 3) == "\239\187\191" then + i = 4 + end + if ssub(s, i, i + 4) ~= "#usda" then + fail("not a USDA file (no #usda header)", i) + end + local nl = sfind(s, "\n", i, true) + i = if nl then nl + 1 else n + 1 + local out: Layer = { meta = {}, prims = {} } + i = ws(i) + if ssub(s, i, i) == "(" then + out.meta, i = metadata(i) + end + while true do + i = ws(i) + if i > n then + break + end + local word, j = ident(i) + if word == "def" or word == "over" or word == "class" then + local p + p, i = prim(j, word) + table.insert(out.prims, p) + elseif word == "reorder" then + j = ws(j) + local _ + _, j = ident(j) + j = expect(j, "=") + _, i = value(j) + elseif ssub(s, i, i) == ";" then + i += 1 + else + fail("expected def / over / class", i) + end + end + return out + end + + return layer +end + +function Parse.layer(text: string, maxBytes: number?): (Layer?, string?, number?) + local run = parser(text, maxBytes or 2 ^ 30) + local ok, res = pcall(run) + if ok then + return res, nil, nil + end + 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 + +function Parse.version(text: string): string? + return smatch(text, "^\239?\187?\191?#usda%s+([%d%.]+)") +end + +return Parse +end +__FILES["model/usda/Write"] = function() + +-- model/usda/Write: Scene -> USD ASCII (UsdGeom / UsdShade / UsdLux); new code. timeCodesPerSecond 24. Not written: +-- skins, morph targets, weights animation, lines / points primitives. +local Types = __include("Types") + +local Write = {} + +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 + +type Options = { files: { [string]: any }?, name: string?, upAxis: string?, metersPerUnit: number? } + +-- ------------------------------------------------------------------------------------------------ text helpers +local function fmt(x: number): string + if x ~= x then + return "nan" + elseif x == math.huge then + return "inf" + elseif x == -math.huge then + return "-inf" + elseif x == math.floor(x) and math.abs(x) < 1e15 then + return string.format("%d", x) + end + return string.format("%.9g", x) +end +local function tuple(t: { number }): string + local parts = table.create(#t) + for k, v in t do + parts[k] = fmt(v) + end + return "(" .. table.concat(parts, ", ") .. ")" +end +local function quote(s: string): string + return '"' .. string.gsub(s, '[\\"\n]', { ["\\"] = "\\\\", ['"'] = '\\"', ["\n"] = "\\n" }) .. '"' +end +local function asset(s: string): string + if string.find(s, "@", 1, true) then + return "@@@" .. s .. "@@@" + end + return "@" .. s .. "@" +end +local function namer(): (string?, string) -> string + local used: { [string]: boolean } = {} + return function(name: string?, fallback: string): string + local n = string.gsub(name or "", "[^%w_]", "_") + if n == "" then + n = fallback + end + if string.find(n, "^%d") then + n = "_" .. n + end + local base, k = n, 1 + while used[n] do + k += 1 + n = base .. "_" .. k + end + used[n] = true + return n + end +end + +local function values(acc: Types.Accessor?): ({ number }?, number) + if not acc then + return nil, 0 + end + local get = Types.Scene.reader(acc) + if not get then + return nil, 0 + end + local n, c = acc.count, acc.components + 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) + end + end + return out, c +end + +local function arrayText(vals: { number }, width: number, stride: number?, count: number?, map: ((i: number, k: number, v: number) -> number)?): string + local st = stride or width + local n = count or (#vals // st) + local parts = table.create(n) + local buf = table.create(width) + for i = 0, n - 1 do + for k = 1, width do + local v = vals[i * st + k] or 0 + if map then + v = map(i, k, v) + end + buf[k] = fmt(v) + end + parts[i + 1] = if width == 1 then buf[1] else "(" .. table.concat(buf, ", ", 1, width) .. ")" + end + return "[" .. table.concat(parts, ", ") .. "]" +end + +-- ------------------------------------------------------------------------------------------------ primitives +type Merged = { + points: { number }, + counts: { number }, + indices: { number }, + normals: { number }?, + uvs: { [number]: { number } }, + colors: { number }?, + hasAlpha: boolean, + subsets: { { faces: { number }, material: number? } }, +} + +local function faces(p: Types.Primitive, nverts: number): ({ number }?, { number }?) + local idx: { number } + if p.indices then + idx = (values(p.indices)) or {} :: { number } + else + idx = table.create(nverts) :: { number } + for i = 1, nverts do + idx[i] = i - 1 + end + end + local counts: { number }, out: { number } = {}, {} + local mode = p.mode + if mode == "triangles" or mode == nil then + for k = 1, #idx - 2, 3 do + table.insert(counts, 3) + table.insert(out, idx[k]) + table.insert(out, idx[k + 1]) + table.insert(out, idx[k + 2]) + end + elseif mode == "polygons" then + local fs = (values(p.faces)) or {} + local at = 1 + for _, n in fs do + if at + n - 1 > #idx then + break + end + table.insert(counts, n) + for k = at, at + n - 1 do + table.insert(out, idx[k]) + end + at += n + end + elseif mode == "triangle_strip" then + for k = 1, #idx - 2 do + local a, b, c = idx[k], idx[k + 1], idx[k + 2] + if k % 2 == 0 then + a, b = b, a + end + table.insert(counts, 3) + table.insert(out, a) + table.insert(out, b) + table.insert(out, c) + end + elseif mode == "triangle_fan" then + for k = 2, #idx - 1 do + table.insert(counts, 3) + table.insert(out, idx[1]) + table.insert(out, idx[k]) + table.insert(out, idx[k + 1]) + end + else + return nil, nil + end + return counts, out +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 :: 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 + end + if p.targets and #p.targets > 0 then + notes["morph targets"] = (notes["morph targets"] or 0) + 1 + end + end + if #prims == 0 then + return nil + end + local all = { NORMAL = true } + local uvSets: { number } = {} + for k = 0, 7 do + local every = true + for _, p in prims do + if not p.attributes["TEXCOORD_" .. k] then + every = false + end + end + if every then + table.insert(uvSets, k) + end + end + local anyColor = false + for _, p in prims do + if not p.attributes.NORMAL or p.attributes.NORMAL.components ~= 3 then + all.NORMAL = false + end + if p.attributes.COLOR_0 then + anyColor = true + end + end + local m: Merged = { points = {}, counts = {}, indices = {}, normals = if all.NORMAL then {} else nil, uvs = {}, colors = if anyColor then {} else nil, hasAlpha = false, subsets = {} } + for _, k in uvSets do + m.uvs[k] = {} + end + local face = 0 + for _, p in prims do + local base = #m.points // 3 + local pos = (values(p.attributes.POSITION)) or {} + local nv = p.attributes.POSITION.count + table.move(pos, 1, nv * 3, #m.points + 1, m.points) + if m.normals then + local nrm = (values(p.attributes.NORMAL)) or {} + table.move(nrm, 1, nv * 3, #m.normals + 1, m.normals) + end + for _, k in uvSets do + local uv, c = values(p.attributes["TEXCOORD_" .. k]) + local dst = m.uvs[k] + for i = 0, nv - 1 do + table.insert(dst, (uv :: { number })[i * c + 1] or 0) + table.insert(dst, (uv :: { number })[i * c + 2] or 0) + end + end + if m.colors then + local col, c = values(p.attributes.COLOR_0) + local dst = m.colors :: { number } + for i = 0, nv - 1 do + if col then + table.insert(dst, col[i * c + 1] or 1) + table.insert(dst, col[i * c + 2] or 1) + table.insert(dst, col[i * c + 3] or 1) + local a = if c >= 4 then col[i * c + 4] or 1 else 1 + if a ~= 1 then + m.hasAlpha = true + end + table.insert(dst, a) + else + table.insert(dst, 1) + table.insert(dst, 1) + table.insert(dst, 1) + table.insert(dst, 1) + end + end + end + local counts, idx = faces(p, nv) + local sub = { faces = {}, material = p.material } + if counts and idx then + local ok = true + for _, v in idx do + if v < 0 or v >= nv then + ok = false + break + end + end + if ok then + for _, c in counts do + table.insert(m.counts, c) + table.insert(sub.faces, face) + face += 1 + end + for _, v in idx do + table.insert(m.indices, v + base) + end + else + notes["out-of-range indices"] = (notes["out-of-range indices"] or 0) + 1 + end + end + table.insert(m.subsets, sub) + end + return m +end + +-- ------------------------------------------------------------------------------------------------ write +function Write.text(scene: Types.Scene, opts: Options?): (string, { [string]: number }) + local o: Options = opts or {} + local notes: { [string]: number } = {} + local out: { string } = {} + local function line(depth: number, s: string) + table.insert(out, string.rep(" ", depth) .. s) + end + local nodes = scene.nodes or {} + local roots = scene.roots + if not roots or #roots == 0 then + local child = {} + for _, n in nodes do + for _, c in n.children or {} do + child[c] = true + end + end + roots = {} + for i in nodes do + if not child[i] then + table.insert(roots, i) + end + end + end + if #(scene.skins or {}) > 0 then + notes.skins = #scene.skins + end + local wrap = #roots ~= 1 or (nodes[roots[1]] == nil) + local rootNames = namer() + local rootName = if wrap then "root" else rootNames(nodes[roots[1]].name, "root") + + 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 + if tex.data and type(o.files) == "table" then + uri = uri or (base .. "_" .. i .. "." .. (EXT[tex.mime or ""] or "png")) + if string.find(uri :: string, "^data:") or string.find(uri :: string, "^%a+://") then + uri = base .. "_" .. i .. "." .. (EXT[tex.mime or ""] or "png") + end + local files: any = o.files + if files[uri] == nil then + files[uri] = tex.data + end + elseif not uri then + uri = base .. "_" .. i .. "." .. (EXT[tex.mime or ""] or "png") + notes["textures without a file (not written)"] = (notes["textures without a file (not written)"] or 0) + 1 + end + texFile[i] = uri :: string + end + + type Track = { times: { number }, vals: { number }, comps: number } + local tracks: { [number]: { [string]: Track? } } = {} + local tcps = 24 + local tMin, tMax = math.huge, -math.huge + for _, anim in scene.animations or {} do + for _, ch in anim.channels or {} do + if ch.path == "weights" then + notes["weights animation"] = (notes["weights animation"] or 0) + 1 + elseif nodes[ch.node] and ch.input and ch.output then + local times = (values(ch.input)) or {} + local vals, comps = values(ch.output) + if vals and #times > 0 then + local stride = comps + local per = #vals // (comps * #times) + -- CUBICSPLINE: in-tangent, value, out-tangent per key + local off = if ch.interpolation == "CUBICSPLINE" and per == 3 then comps else 0 + local mult = if ch.interpolation == "CUBICSPLINE" and per == 3 then 3 else 1 + local tv = {} + for k = 0, #times - 1 do + for c = 1, stride do + table.insert(tv, vals[k * comps * mult + off + c] or 0) + end + end + tracks[ch.node] = tracks[ch.node] or {} + tracks[ch.node][ch.path] = { times = times, vals = tv, comps = comps } + for _, t in times do + tMin = math.min(tMin, t * tcps) + tMax = math.max(tMax, t * tcps) + end + end + end + end + end + + table.insert(out, "#usda 1.0") + table.insert(out, "(") + line(1, "defaultPrim = " .. quote(rootName)) + line(1, 'doc = "rosetta"') + if tMin <= tMax then + line(1, "endTimeCode = " .. fmt(tMax)) + end + line(1, "metersPerUnit = " .. fmt(o.metersPerUnit or scene.meta.unit or 1)) + if tMin <= tMax then + line(1, "startTimeCode = " .. fmt(tMin)) + line(1, "timeCodesPerSecond = " .. fmt(tcps)) + end + line(1, "upAxis = " .. quote(o.upAxis or (if scene.meta.up == "z" then "Z" else "Y"))) + table.insert(out, ")") + table.insert(out, "") + + local looksPath = "/" .. rootName .. "/Looks" + local matNames = namer() + local matPath: { [number]: string } = {} + for i, mat in scene.materials or {} do + matPath[i] = looksPath .. "/" .. matNames(mat.name, "material_" .. i) + end + + local function xform(depth: number, ni: number, n: Types.Node) + local tr: { [string]: Track? }? = tracks[ni] + local order: { string } = {} + local function samples(track: Track, f: (vals: { number }, at: number) -> string): string + local parts = {} + for k, t in track.times do + table.insert(parts, fmt(t * tcps) .. ": " .. f(track.vals, (k - 1) * track.comps)) + end + return "{ " .. table.concat(parts, ", ") .. " }" + end + local function quat(v: { number }, at: number): string + -- USD writes (real, i, j, k) + return tuple({ v[at + 4] or 1, v[at + 1] or 0, v[at + 2] or 0, v[at + 3] or 0 }) + end + local function vec3(v: { number }, at: number): string + return tuple({ v[at + 1] or 0, v[at + 2] or 0, v[at + 3] or 0 }) + end + local t, r, s = n.translation, n.rotation, n.scale + if n.matrix and #n.matrix == 16 then + if tr then + local m = n.matrix + local sx = math.sqrt(m[1] ^ 2 + m[2] ^ 2 + m[3] ^ 2) + local sy = math.sqrt(m[5] ^ 2 + m[6] ^ 2 + m[7] ^ 2) + local sz = math.sqrt(m[9] ^ 2 + m[10] ^ 2 + m[11] ^ 2) + t, s = { m[13], m[14], m[15] }, { sx, sy, sz } + r = nil + notes["matrix nodes with animation (rotation reset)"] = (notes["matrix nodes with animation (rotation reset)"] or 0) + 1 + else + local m = n.matrix + line(depth, string.format("matrix4d xformOp:transform = ( %s, %s, %s, %s )", tuple({ m[1], m[2], m[3], m[4] }), tuple({ m[5], m[6], m[7], m[8] }), tuple({ m[9], m[10], m[11], m[12] }), tuple({ m[13], m[14], m[15], m[16] }))) + line(depth, 'uniform token[] xformOpOrder = ["xformOp:transform"]') + return + end + end + if t or (tr and tr.translation) then + if t then + 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 :: Track, vec3)) + end + table.insert(order, '"xformOp:translate"') + end + if r or (tr and tr.rotation) then + if r then + line(depth, "quatf xformOp:orient = " .. quat(r, 0)) + end + if tr and tr.rotation then + line(depth, "quatf xformOp:orient.timeSamples = " .. samples(tr.rotation :: Track, quat)) + end + table.insert(order, '"xformOp:orient"') + end + if s or (tr and tr.scale) then + if s then + 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 :: Track, vec3)) + end + table.insert(order, '"xformOp:scale"') + end + if #order > 0 then + line(depth, "uniform token[] xformOpOrder = [" .. table.concat(order, ", ") .. "]") + end + end + + local function meshBody(depth: number, m: Merged, path: string) + local doubleSided = false + for _, sub in m.subsets do + local mat = sub.material and scene.materials[sub.material] + if mat and mat.doubleSided then + doubleSided = true + end + end + if doubleSided then + line(depth, "uniform bool doubleSided = 1") + end + local mn, mx = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge } + for i = 0, #m.points // 3 - 1 do + for c = 1, 3 do + local v = m.points[i * 3 + c] + if v < mn[c] then + mn[c] = v + end + if v > mx[c] then + mx[c] = v + end + end + end + if #m.points > 0 then + line(depth, "float3[] extent = [" .. tuple(mn) .. ", " .. tuple(mx) .. "]") + end + line(depth, "int[] faceVertexCounts = " .. arrayText(m.counts, 1)) + line(depth, "int[] faceVertexIndices = " .. arrayText(m.indices, 1)) + local single = #m.subsets == 1 + if single and m.subsets[1].material and matPath[m.subsets[1].material :: number] then + line(depth, "rel material:binding = <" .. matPath[m.subsets[1].material :: number] .. ">") + end + if m.normals then + line(depth, "normal3f[] normals = " .. arrayText(m.normals, 3) .. " (") + line(depth + 1, 'interpolation = "vertex"') + line(depth, ")") + end + line(depth, "point3f[] points = " .. arrayText(m.points, 3)) + if m.colors then + line(depth, "color3f[] primvars:displayColor = " .. arrayText(m.colors, 3, 4) .. " (") + line(depth + 1, 'interpolation = "vertex"') + line(depth, ")") + if m.hasAlpha then + local alpha = {} + for i = 0, #m.colors // 4 - 1 do + alpha[i + 1] = m.colors[i * 4 + 4] + end + line(depth, "float[] primvars:displayOpacity = " .. arrayText(alpha, 1) .. " (") + line(depth + 1, 'interpolation = "vertex"') + line(depth, ")") + end + end + local uvKeys = {} + for k in m.uvs do + table.insert(uvKeys, k) + end + table.sort(uvKeys) + for _, k in uvKeys do + local name = if k == 0 then "st" else "st" .. k + line(depth, "texCoord2f[] primvars:" .. name .. " = " .. arrayText(m.uvs[k], 2, nil, nil, function(_i: number, c: number, v: number): number + return if c == 2 then 1 - v else v + end) .. " (") + line(depth + 1, 'interpolation = "vertex"') + line(depth, ")") + end + line(depth, 'uniform token subdivisionScheme = "none"') + if not single then + local names = namer() + for k, sub in m.subsets do + if #sub.faces > 0 then + local mp = sub.material and matPath[sub.material :: number] + table.insert(out, "") + line(depth, 'def GeomSubset "' .. names("subset_" .. k, "subset") .. '"' .. (if mp then ' (\n' .. string.rep(" ", depth + 1) .. 'prepend apiSchemas = ["MaterialBindingAPI"]\n' .. string.rep(" ", depth) .. ")" else "")) + line(depth, "{") + line(depth + 1, 'uniform token elementType = "face"') + line(depth + 1, 'uniform token familyName = "materialBind"') + line(depth + 1, "int[] indices = " .. arrayText(sub.faces, 1)) + if mp then + line(depth + 1, "rel material:binding = <" .. mp .. ">") + end + line(depth, "}") + end + end + end + end + + local function cameraBody(depth: number, c: Types.Camera) + if c.type == "orthographic" then + line(depth, "float2 clippingRange = " .. tuple({ c.znear or 0.01, c.zfar or 1000000 })) + line(depth, "float horizontalAperture = " .. fmt((c.xmag or 1) * 20)) + line(depth, 'token projection = "orthographic"') + line(depth, "float verticalAperture = " .. fmt((c.ymag or 1) * 20)) + return + end + local vap = 24 + local yfov = c.yfov or 0.8 + local focal = vap / (2 * math.tan(yfov / 2)) + line(depth, "float2 clippingRange = " .. tuple({ c.znear or 0.01, c.zfar or 1000000 })) + line(depth, "float focalLength = " .. fmt(focal)) + line(depth, "float horizontalAperture = " .. fmt(vap * (c.aspect or 1))) + line(depth, 'token projection = "perspective"') + line(depth, "float verticalAperture = " .. fmt(vap)) + end + + 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 })) + line(depth, "float inputs:intensity = " .. fmt(l.intensity or 1)) + if l.type ~= "directional" then + line(depth, "float inputs:radius = 0") + end + if l.type == "spot" then + local outer = l.outerCone or math.pi / 4 + line(depth, "float inputs:shaping:cone:angle = " .. fmt(outer * RAD)) + line(depth, "float inputs:shaping:cone:softness = " .. fmt(if outer > 0 then 1 - (l.innerCone or 0) / outer else 0)) + end + if l.type ~= "directional" then + line(depth, "bool treatAsPoint = 1") + end + end + local function lightHead(l: Types.Light): string + return if l.type == "spot" then ' (\n%s prepend apiSchemas = ["ShapingAPI"]\n%s)' else "" + end + + local visited: { [number]: boolean } = {} + local function writeNode(depth: number, ni: number, path: string, names: (string?, string) -> string, isRoot: boolean) + local n = nodes[ni] + if not n or visited[ni] then + return + end + visited[ni] = true + local name = if isRoot and not wrap then rootName else names(n.name, "node_" .. ni) + local myPath = path .. "/" .. name + local mesh = n.mesh and scene.meshes[n.mesh] + local merged = mesh and merge(mesh, notes) + local cam = n.camera and scene.cameras[n.camera] + local lig = n.light and scene.lights[n.light] + local kind = "Xform" + local head = "" + local pad = string.rep(" ", depth) + if merged then + kind = "Mesh" + if #merged.subsets == 1 and merged.subsets[1].material and matPath[merged.subsets[1].material :: number] then + head = ' (\n' .. pad .. ' prepend apiSchemas = ["MaterialBindingAPI"]\n' .. pad .. ")" + end + elseif cam and not lig then + kind = "Camera" + elseif lig and not cam then + kind = LIGHT_TYPE[lig.type] or "SphereLight" + local h = lightHead(lig) + head = if h ~= "" then string.format(h, pad, pad) else "" + end + if n.skin then + notes.skins = (notes.skins or 0) + 0 + end + table.insert(out, "") + line(depth, "def " .. kind .. " " .. quote(name) .. head) + line(depth, "{") + xform(depth + 1, ni, n) + if kind == "Mesh" then + meshBody(depth + 1, merged :: Merged, myPath) + elseif kind == "Camera" then + cameraBody(depth + 1, cam :: Types.Camera) + elseif kind ~= "Xform" then + lightBody(depth + 1, lig :: Types.Light) + end + local childNames = namer() + if cam and kind ~= "Camera" then + table.insert(out, "") + line(depth + 1, "def Camera " .. quote(childNames(cam.name, "camera"))) + line(depth + 1, "{") + cameraBody(depth + 2, cam) + line(depth + 1, "}") + end + if lig and kind == "Xform" or (lig and kind == "Mesh") or (lig and kind == "Camera") then + local l = lig :: Types.Light + local h = lightHead(l) + local pad2 = string.rep(" ", depth + 1) + table.insert(out, "") + line(depth + 1, "def " .. (LIGHT_TYPE[l.type] or "SphereLight") .. " " .. quote(childNames(l.name, "light")) .. (if h ~= "" then string.format(h, pad2, pad2) else "")) + line(depth + 1, "{") + lightBody(depth + 2, l) + line(depth + 1, "}") + end + if isRoot and not wrap then + Write._looks(out, depth + 1, scene, matPath, texFile, line) + end + for _, c in n.children or {} do + writeNode(depth + 1, c, myPath, childNames, false) + end + line(depth, "}") + end + + if wrap then + line(0, "def Xform " .. quote(rootName)) + line(0, "{") + Write._looks(out, 1, scene, matPath, texFile, line) + local names = namer() + names("Looks", "Looks") + for _, r in roots do + writeNode(1, r, "/" .. rootName, names, false) + end + line(0, "}") + else + writeNode(0, roots[1], "", rootNames, true) + end + table.insert(out, "") + return table.concat(out, "\n"), notes +end + +function Write._looks(out: { string }, depth: number, scene: Types.Scene, matPath: { [number]: string }, texFile: { [number]: string }, line: (number, string) -> ()) + local mats = scene.materials or {} + if #mats == 0 then + return + end + table.insert(out, "") + line(depth, 'def Scope "Looks"') + line(depth, "{") + for i, mat in mats do + local path = matPath[i] + local mname = string.match(path, "([^/]+)$") :: string + table.insert(out, "") + line(depth + 1, "def Material " .. quote(mname)) + line(depth + 1, "{") + local d = depth + 2 + line(d, "token outputs:surface.connect = <" .. path .. "/PreviewSurface.outputs:surface>") + type TexNode = { name: string, ref: Types.TextureRef, color: boolean } + local texNodes: { TexNode } = {} + local function texNode(ref: Types.TextureRef?, color: boolean): string? + if not ref or not texFile[ref.texture] then + return nil + end + for _, tn in texNodes do + if tn.ref == ref or (tn.ref.texture == ref.texture and (tn.ref.texCoord or 0) == (ref.texCoord or 0) and tn.ref.transform == nil and ref.transform == nil and tn.color == color) then + return tn.name + end + end + local name = "Texture_" .. (#texNodes + 1) + table.insert(texNodes, { name = name, ref = ref, color = color }) + return name + end + local bc = mat.baseColor or { 1, 1, 1, 1 } + local blend = mat.alphaMode == "blend" or mat.alphaMode == "mask" + local diffuseTex = texNode(mat.baseColorTexture, true) + local mrTex = texNode(mat.metallicRoughnessTexture, false) + local emTex = texNode(mat.emissiveTexture, true) + local nTex = texNode(mat.normalTexture, false) + local oTex = texNode(mat.occlusionTexture, false) + table.insert(out, "") + line(d, 'def Shader "PreviewSurface"') + line(d, "{") + local e = d + 1 + line(e, 'uniform token info:id = "UsdPreviewSurface"') + if diffuseTex then + line(e, "color3f inputs:diffuseColor.connect = <" .. path .. "/" .. diffuseTex .. ".outputs:rgb>") + else + line(e, "color3f inputs:diffuseColor = " .. tuple({ bc[1] or 1, bc[2] or 1, bc[3] or 1 })) + end + local em = mat.emissive or { 0, 0, 0 } + if emTex then + line(e, "color3f inputs:emissiveColor.connect = <" .. path .. "/" .. emTex .. ".outputs:rgb>") + elseif (em[1] or 0) ~= 0 or (em[2] or 0) ~= 0 or (em[3] or 0) ~= 0 then + line(e, "color3f inputs:emissiveColor = " .. tuple({ em[1] or 0, em[2] or 0, em[3] or 0 })) + end + local ext = mat.extensions or {} + if ext.KHR_materials_clearcoat and type(ext.KHR_materials_clearcoat.clearcoatFactor) == "number" then + line(e, "float inputs:clearcoat = " .. fmt(ext.KHR_materials_clearcoat.clearcoatFactor)) + line(e, "float inputs:clearcoatRoughness = " .. fmt(tonumber(ext.KHR_materials_clearcoat.clearcoatRoughnessFactor) or 0)) + end + if ext.KHR_materials_ior and type(ext.KHR_materials_ior.ior) == "number" then + line(e, "float inputs:ior = " .. fmt(ext.KHR_materials_ior.ior)) + end + if mrTex then + line(e, "float inputs:metallic.connect = <" .. path .. "/" .. mrTex .. ".outputs:b>") + else + line(e, "float inputs:metallic = " .. fmt(mat.metallic or 0)) + end + if nTex then + line(e, "normal3f inputs:normal.connect = <" .. path .. "/" .. nTex .. ".outputs:rgb>") + end + if oTex then + line(e, "float inputs:occlusion.connect = <" .. path .. "/" .. oTex .. ".outputs:r>") + end + if blend and diffuseTex then + line(e, "float inputs:opacity.connect = <" .. path .. "/" .. diffuseTex .. ".outputs:a>") + elseif blend then + line(e, "float inputs:opacity = " .. fmt(bc[4] or 1)) + end + if mat.alphaMode == "mask" then + line(e, "float inputs:opacityThreshold = " .. fmt(mat.alphaCutoff or 0.5)) + end + if mrTex then + line(e, "float inputs:roughness.connect = <" .. path .. "/" .. mrTex .. ".outputs:g>") + else + line(e, "float inputs:roughness = " .. fmt(mat.roughness or 1)) + end + line(e, "token outputs:surface") + line(d, "}") + local readers: { [number]: boolean } = {} + for _, tn in texNodes do + local tc = (tn.ref.transform and tn.ref.transform.texCoord) or tn.ref.texCoord or 0 + if not readers[tc] then + readers[tc] = true + table.insert(out, "") + line(d, 'def Shader "PrimvarReader_' .. tc .. '"') + line(d, "{") + line(d + 1, 'uniform token info:id = "UsdPrimvarReader_float2"') + line(d + 1, "string inputs:varname = " .. quote(if tc == 0 then "st" else "st" .. tc)) + line(d + 1, "float2 outputs:result") + line(d, "}") + end + end + for _, tn in texNodes do + local ref = tn.ref + local tc = (ref.transform and ref.transform.texCoord) or ref.texCoord or 0 + local stSource = path .. "/PrimvarReader_" .. tc .. ".outputs:result" + if ref.transform then + local tr = ref.transform :: any + table.insert(out, "") + line(d, 'def Shader "' .. tn.name .. '_Transform"') + line(d, "{") + line(d + 1, 'uniform token info:id = "UsdTransform2d"') + line(d + 1, "float2 inputs:in.connect = <" .. stSource .. ">") + if tr.rotation then + line(d + 1, "float inputs:rotation = " .. fmt(tr.rotation * RAD)) + end + if tr.scale then + line(d + 1, "float2 inputs:scale = " .. tuple({ tr.scale[1] or 1, tr.scale[2] or 1 })) + end + if tr.offset then + line(d + 1, "float2 inputs:translation = " .. tuple({ tr.offset[1] or 0, tr.offset[2] or 0 })) + end + line(d + 1, "float2 outputs:result") + line(d, "}") + stSource = path .. "/" .. tn.name .. "_Transform.outputs:result" + end + local tex = scene.textures[ref.texture] + local sampler: Types.Sampler = tex and tex.sampler or {} + table.insert(out, "") + line(d, 'def Shader "' .. tn.name .. '"') + line(d, "{") + line(d + 1, 'uniform token info:id = "UsdUVTexture"') + line(d + 1, "asset inputs:file = " .. asset(texFile[ref.texture])) + if tn.ref == mat.baseColorTexture and ((bc[1] or 1) ~= 1 or (bc[2] or 1) ~= 1 or (bc[3] or 1) ~= 1 or (bc[4] or 1) ~= 1) then + line(d + 1, "float4 inputs:scale = " .. tuple({ bc[1] or 1, bc[2] or 1, bc[3] or 1, bc[4] or 1 })) + end + if tn.ref == mat.normalTexture then + line(d + 1, "float4 inputs:bias = (-1, -1, -1, 0)") + line(d + 1, "float4 inputs:scale = (2, 2, 2, 1)") + end + line(d + 1, 'token inputs:sourceColorSpace = "' .. (if tn.color then "sRGB" else "raw") .. '"') + line(d + 1, "float2 inputs:st.connect = <" .. stSource .. ">") + line(d + 1, 'token inputs:wrapS = "' .. (sampler.wrapS or "repeat") .. '"') + line(d + 1, 'token inputs:wrapT = "' .. (sampler.wrapT or "repeat") .. '"') + line(d + 1, "float outputs:a") + line(d + 1, "float outputs:b") + line(d + 1, "float outputs:g") + line(d + 1, "float outputs:r") + line(d + 1, "float3 outputs:rgb") + line(d, "}") + end + line(depth + 1, "}") + end + line(depth, "}") +end + +return Write +end +end + + + + + + model_5 + --!optimize 2 +--!nocheck +-- rosetta chunk model_5 (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 7 modules (1 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["model/vox"] = function() + +-- model/vox: MagicaVoxel .vox (ephtracy's MagicaVoxel-file-format-vox.txt / -vox-extension.txt, versions 150 and 200). +-- Supports: every chunk (unknown, PACK, MATT kept raw); shapes centred on their node like MagicaVoxel. Not supported: +-- writing models over 256 cells per axis (MagicaVoxel's limit); node scale other than mirroring. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Grid = __include("model/vox/Grid") + +-- ------------------------------------------------------------------------------------------------ contract +local Vox = { + name = "vox", + category = "model", + extensions = { "vox" }, + mime = { "model/x-vox" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, voxels = true, sceneGraph = true, materials = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + maxCells: number?, -- default 2^27 +} +type EncodeOptions = { + version: number?, -- default 200 (MagicaVoxel 0.99.7); 150 is the older one +} +type Dict = { [string]: string } +type GraphNode = { + kind: string, + id: number, + attrs: Dict, + child: number?, + layer: number?, + frames: { Dict }?, + children: { number }?, + models: { { model: number, attributes: Dict } }?, +} + +-- ------------------------------------------------------------------------------------------------ constants +-- the default palette (spec section 8): a 6 x 6 x 6 colour cube without black, then red, green, blue and grey ramps +local DEFAULT_PALETTE: { { number } } = {} +do + local steps = { 0xff, 0xcc, 0x99, 0x66, 0x33, 0x00 } + for _, r in steps do + for _, g in steps do + for _, b in steps do + if #DEFAULT_PALETTE < 215 then + table.insert(DEFAULT_PALETTE, { r, g, b, 255 }) + end + end + end + end + local ramp = { 0xee, 0xdd, 0xbb, 0xaa, 0x88, 0x77, 0x55, 0x44, 0x22, 0x11 } + for ch = 1, 4 do + for _, v in ramp do + local c = { 0, 0, 0, 255 } + if ch == 4 then + c = { v, v, v, 255 } + else + c[ch] = v + end + table.insert(DEFAULT_PALETTE, c) + end + end +end +Vox.DEFAULT_PALETTE = DEFAULT_PALETTE + +local IDENTITY_R = 4 -- _r of the identity: row 0 -> column 0, row 1 -> column 1, no signs +local MAX_DEPTH = 256 + +-- ------------------------------------------------------------------------------------------------ sniff +function Vox.sniff(r: Bytes.Reader): number + return if r:peek(4) == "VOX " and r:peek(4, 8) == "MAIN" then 1 elseif r:peek(4) == "VOX " then 0.8 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function str(r: Bytes.Reader): string + local n = r:i32le() + if n < 0 or n > r:remaining() then + r:fail(Err.CORRUPT, "bad string length") + return "" + end + return r:string(n) +end + +local function dict(r: Bytes.Reader): Dict + local d: Dict = {} + local n = r:i32le() + if n < 0 or n * 8 > r:remaining() then + r:fail(Err.CORRUPT, "bad dictionary size") + return d + end + for _ = 1, n do + local k = str(r) + local v = str(r) + if r.err then + break + end + d[k] = v + end + return d +end + +local function ints(s: string?): { number } + local out = {} + if s then + for w in string.gmatch(s, "%S+") do + table.insert(out, tonumber(w) or 0) + end + end + return out +end + +-- _r byte -> the row-major 3 x 3 rotation (rows of { column, sign }); nil when not a permutation +local function rotation(b: number): { { number } }? + local i0, i1 = bit32.band(b, 3), bit32.band(bit32.rshift(b, 2), 3) + if i0 > 2 or i1 > 2 or i0 == i1 then + return nil + end + local i2 = 3 - i0 - i1 + local function sign(bit: number): number + return if bit32.band(b, bit32.lshift(1, bit)) ~= 0 then -1 else 1 + end + return { { i0, sign(4) }, { i1, sign(5) }, { i2, sign(6) } } +end + +local function applyFrame(node: Types.Node, f: Dict) + local t = ints(f._t) + local tx, ty, tz = t[1] or 0, t[2] or 0, t[3] or 0 + local rb = tonumber(f._r) + local rows = if rb and rb ~= IDENTITY_R then rotation(rb) else nil + if not rows then + if tx ~= 0 or ty ~= 0 or tz ~= 0 then + node.translation = { tx, ty, tz } + end + return + end + -- R[row][col], then the determinant: +1 -> a quaternion, -1 (a mirror) -> a matrix + local R = { { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 } } + for row = 1, 3 do + R[row][rows[row][1] + 1] = rows[row][2] + end + local det = R[1][1] * (R[2][2] * R[3][3] - R[2][3] * R[3][2]) - R[1][2] * (R[2][1] * R[3][3] - R[2][3] * R[3][1]) + R[1][3] * (R[2][1] * R[3][2] - R[2][2] * R[3][1]) + if det < 0 then + node.matrix = { + R[1][1], R[2][1], R[3][1], 0, + R[1][2], R[2][2], R[3][2], 0, + R[1][3], R[2][3], R[3][3], 0, + tx, ty, tz, 1, + } + return + end + local m00, m11, m22 = R[1][1], R[2][2], R[3][3] + 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 = 0.25 * s, (R[3][2] - R[2][3]) / s, (R[1][3] - R[3][1]) / s, (R[2][1] - R[1][2]) / s + elseif m00 > m11 and m00 > m22 then + local s = math.sqrt(1 + m00 - m11 - m22) * 2 + w, x, y, z = (R[3][2] - R[2][3]) / s, 0.25 * s, (R[1][2] + R[2][1]) / s, (R[1][3] + R[3][1]) / s + elseif m11 > m22 then + local s = math.sqrt(1 + m11 - m00 - m22) * 2 + w, x, y, z = (R[1][3] - R[3][1]) / s, (R[1][2] + R[2][1]) / s, 0.25 * s, (R[2][3] + R[3][2]) / s + else + local s = math.sqrt(1 + m22 - m00 - m11) * 2 + w, x, y, z = (R[2][1] - R[1][2]) / s, (R[1][3] + R[3][1]) / s, (R[2][3] + R[3][2]) / s, 0.25 * s + end + node.rotation = { x, y, z, w } + if tx ~= 0 or ty ~= 0 or tz ~= 0 then + node.translation = { tx, ty, tz } + end +end + +-- MATL: _type -> type, the other keys without their "_", numbers as numbers +local function material(d: Dict): Types.VoxelMaterial + local m: Types.VoxelMaterial = { type = "diffuse" } + for k, v in d do + local key = if string.sub(k, 1, 1) == "_" then string.sub(k, 2) else k + if key == "type" then + m.type = if string.sub(v, 1, 1) == "_" then string.sub(v, 2) else v + else + m[key] = tonumber(v) or v + end + end + return m +end + +type Parsed = { + version: number, + models: { Types.Voxels }, + palette: { { number } }?, + materials: { [number]: Types.VoxelMaterial }, + graph: { [number]: GraphNode }, + meta: { [string]: any }, + skipped: number, +} + +local function parse(r: Bytes.Reader, opts: DecodeOptions?): (Parsed?, Err.Err?) + local maxCells = opts and opts.maxCells or 2 ^ 27 + if r:string(4) ~= "VOX " then + return nil, Err.new(Err.CORRUPT, "bad signature", r.base) + end + local version = r:u32le() + if r:string(4) ~= "MAIN" then + if r.err then + return nil, r.err + end + return nil, Err.new(Err.CORRUPT, "missing MAIN chunk", 8) + end + local mainN, mainM = r:i32le(), r:i32le() + if r.err then + return nil, r.err + end + if mainN < 0 or mainM < 0 or not r:skip(mainN) then + return nil, Err.new(Err.CORRUPT, "bad MAIN chunk", 12) + end + local out: Parsed = { version = version, models = {}, palette = nil, materials = {}, graph = {}, meta = {}, skipped = 0 } + local meta = out.meta + local unknown: { any } = {} + local layers, robjs, cams = {}, {}, {} + local stop = r:tell() + mainM + if stop > r:size() then + return nil, Err.new(Err.TRUNCATED, "the MAIN chunk runs past the end", r.base + 16) + end + local pending: { number }? = nil + local cells = 0 + while r:tell() + 12 <= stop do + local at = r:tell() + local id = r:string(4) + local n, m = r:i32le(), r:i32le() + if n < 0 or m < 0 then + return nil, Err.new(Err.CORRUPT, "bad size of chunk " .. id, at) + elseif n > stop - r:tell() or m > stop - r:tell() - n then + return nil, Err.new(Err.TRUNCATED, "chunk " .. id .. " runs past the end", at) + end + local c = r:slice(n) + if id == "SIZE" then + local sx, sy, sz = c:i32le(), c:i32le(), c:i32le() + if c.err or sx < 1 or sy < 1 or sz < 1 then + return nil, Err.new(Err.CORRUPT, "bad model size", at) + end + cells += sx * sy * sz + if cells > maxCells then + return nil, Err.new(Err.LIMIT, string.format("models hold over %d cells", maxCells), at) + end + pending = { sx, sy, sz } + elseif id == "XYZI" then + local size = pending + if not size then + return nil, Err.new(Err.CORRUPT, "XYZI without SIZE", at) + end + pending = nil + local count = c:i32le() + if c.err or count < 0 or count * 4 > c:remaining() then + return nil, Err.new(Err.CORRUPT, "bad voxel count", at) + end + local v = Types.Voxels.new(size[1], size[2], size[3], DEFAULT_PALETTE) + out.skipped += Grid.fill(v.data, size[1], size[2], size[3], c.buf, c.base + c:tell(), count) + table.insert(out.models, v) + elseif id == "RGBA" then + if n < 1024 then + return nil, Err.new(Err.CORRUPT, "short RGBA chunk", at) + end + local pal = table.create(255) :: { { number } } + for i = 1, 255 do + pal[i] = { c:u8(), c:u8(), c:u8(), c:u8() } + end + out.palette = pal + elseif id == "MATL" then + local mid = c:i32le() + local d = dict(c) + if c.err then + return nil, Err.new(Err.CORRUPT, "bad MATL chunk", at) + end + out.materials[mid] = material(d) + elseif id == "nTRN" then + local node: GraphNode = { kind = id, id = c:i32le(), attrs = dict(c), child = c:i32le() } + c:i32le() -- reserved + node.layer = c:i32le() + local nf = c:i32le() + if c.err or nf < 0 or nf * 4 > c:remaining() then + return nil, Err.new(Err.CORRUPT, "bad nTRN chunk", at) + end + local frames = {} + for k = 1, nf do + frames[k] = dict(c) + end + node.frames = frames + if c.err then + return nil, Err.new(Err.CORRUPT, "bad nTRN frames", at) + end + out.graph[node.id] = node + elseif id == "nGRP" then + local node: GraphNode = { kind = id, id = c:i32le(), attrs = dict(c) } + local nc = c:i32le() + 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) :: { number } + for k = 1, nc do + children[k] = c:i32le() + end + node.children = children + out.graph[node.id] = node + elseif id == "nSHP" then + local node: GraphNode = { kind = id, id = c:i32le(), attrs = dict(c) } + local nm = c:i32le() + if c.err or nm < 0 or nm * 8 > c:remaining() then + return nil, Err.new(Err.CORRUPT, "bad nSHP chunk", at) + end + local models = {} + for k = 1, nm do + models[k] = { model = c:i32le() + 1, attributes = dict(c) } + end + if c.err then + return nil, Err.new(Err.CORRUPT, "bad nSHP models", at) + end + node.models = models + out.graph[node.id] = node + elseif id == "LAYR" then + local lid = c:i32le() + local d = dict(c) + if c.err then + return nil, Err.new(Err.CORRUPT, "bad LAYR chunk", at) + end + table.insert(layers, { id = lid, name = d._name, hidden = d._hidden == "1", attributes = d }) + elseif id == "rOBJ" then + local d = dict(c) + if c.err then + return nil, Err.new(Err.CORRUPT, "bad rOBJ chunk", at) + end + table.insert(robjs, d) + elseif id == "rCAM" then + local cid = c:i32le() + local d = dict(c) + if c.err then + return nil, Err.new(Err.CORRUPT, "bad rCAM chunk", at) + end + table.insert(cams, { id = cid, attributes = d }) + elseif id == "NOTE" then + local nn = c:i32le() + if c.err or nn < 0 or nn * 4 > c:remaining() then + return nil, Err.new(Err.CORRUPT, "bad NOTE chunk", at) + end + local notes = table.create(nn) + for k = 1, nn do + notes[k] = str(c) + end + if c.err then + return nil, Err.new(Err.CORRUPT, "bad NOTE names", at) + end + meta.notes = notes + elseif id == "IMAP" then + local map = {} + for k = 1, math.min(n, 256) do + map[k] = c:u8() + end + meta.indexMap = map + elseif id == "META" then + local d = dict(c) + if c.err then + return nil, Err.new(Err.CORRUPT, "bad META chunk", at) + end + meta.info = d + else + if id == "PACK" then + meta.pack = c:i32le() + end + table.insert(unknown, { id = id, content = c:sub(0, n):bytes(n), children = nil :: buffer? }) + end + if m > 0 then + local kids = r:bytes(math.min(m, r:remaining())) + if #unknown > 0 and unknown[#unknown].children == nil and unknown[#unknown].id == id then + unknown[#unknown].children = kids + end + end + if r.err then + return nil, r.err + end + end + if r:tell() < stop then + return nil, Err.new(Err.TRUNCATED, "a partial chunk at the end", r.base + r:tell()) + end + if #out.models == 0 then + return nil, Err.new(Err.CORRUPT, "no models") + end + if #layers > 0 then + meta.layers = layers + end + if #robjs > 0 then + meta.renderObjects = robjs + end + if #cams > 0 then + meta.cameras = cams + end + if #unknown > 0 then + meta.chunks = unknown + end + return out, nil +end + +local function build(scene: Types.Scene, graph: { [number]: GraphNode }, id: number, depth: number, visiting: { [number]: boolean }, nmodels: number): number? + local t = graph[id] + if not t or t.kind ~= "nTRN" or depth > MAX_DEPTH or visiting[id] then + return nil + end + visiting[id] = true + local node: Types.Node = { name = t.attrs._name, children = {} } + local index = #scene.nodes + 1 + scene.nodes[index] = node + local frames = t.frames or {} + if frames[1] then + applyFrame(node, frames[1]) + end + local vox: { [string]: any } = { attributes = t.attrs, layer = t.layer } + if #frames > 1 or (frames[1] and frames[1]._f) then + vox.frames = frames + end + node.extras = { vox = vox } + local child = if t.child then graph[t.child] else nil + if child and child.kind == "nGRP" then + vox.group = child.attrs + for _, c in child.children or {} do + local ci = build(scene, graph, c, depth + 1, visiting, nmodels) + if ci then + table.insert(node.children, ci) + end + end + elseif child and child.kind == "nSHP" then + local models = child.models or {} + vox.shape = { attributes = child.attrs, models = models } + local first = models[1] + if first and first.model >= 1 and first.model <= nmodels then + node.voxels = first.model + end + end + visiting[id] = nil + return index +end + +function Vox.decodeVoxels(r: Bytes.Reader, opts: DecodeOptions?): ({ Types.Voxels }?, Err.Err?) + local p, err = parse(r, opts) + if not p then + return nil, err + end + local pal = p.palette or DEFAULT_PALETTE + local mats = if next(p.materials) then p.materials else nil + for _, v in p.models do + v.palette = pal + v.materials = mats + end + return p.models, nil +end + +function Vox.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local p, err = parse(r, opts) + if not p then + return nil, err + end + local scene = Types.Scene.new() + local pal = p.palette or DEFAULT_PALETTE + local mats = if next(p.materials) then p.materials else nil + for _, v in p.models do + v.palette = pal + v.materials = mats + end + scene.voxels = p.models + if p.graph[0] then + local root = build(scene, p.graph, 0, 0, {}, #p.models) + if root then + scene.roots = { root } + end + end + if #scene.nodes == 0 then + -- no scene graph (version 150 files): one node per model + for i = 1, #p.models do + scene.nodes[i] = { children = {}, voxels = i } + scene.roots[i] = i + end + end + scene.meta.up = "z" + scene.meta.vox = p.meta + scene.meta.source = { format = "vox", version = p.version, models = #p.models, palette = p.palette ~= nil, skippedVoxels = p.skipped } + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function number(v: any): string + if type(v) ~= "number" then + return tostring(v) + end + if v == math.floor(v) and math.abs(v) < 2 ^ 53 then + return string.format("%d", v) + end + for _, f in { "%.6g", "%.9g", "%.17g" } do + local s = string.format(f, v) + if tonumber(s) == v then + return s + end + end + return string.format("%.17g", v) +end + +local function sortedKeys(d: { [string]: any }): { string } + local keys = {} + for k in d do + if type(k) == "string" then + table.insert(keys, k) + end + end + table.sort(keys) + return keys +end + +local function wstr(w: Bytes.Writer, s: string) + w:u32le(#s) + w:string(s) +end + +local function wdict(w: Bytes.Writer, d: { [string]: any }?) + if not d then + w:u32le(0) + return + end + local keys = sortedKeys(d) + w:u32le(#keys) + for _, k in keys do + wstr(w, k) + wstr(w, number(d[k])) + end +end + +local function frameOf(node: Types.Node, base: Dict?): (Dict?, string?) + local f: Dict = {} + if base then + for k, v in base do + if k ~= "_r" and k ~= "_t" then + f[k] = v + end + end + end + local m = Types.Scene.nodeMatrix(node) + local cols, signs = {}, {} + for row = 0, 2 do + local best, bv, rest = 0, 0, 0 + for col = 0, 2 do + local v = m[col * 4 + row + 1] + if math.abs(v) > math.abs(bv) then + rest = math.max(rest, math.abs(bv)) + best, bv = col, v + else + rest = math.max(rest, math.abs(v)) + end + end + if math.abs(math.abs(bv) - 1) > 1e-4 or rest > 1e-4 or table.find(cols, best) then + return nil, "node rotation is not a multiple of 90 degrees (or has a scale)" + end + table.insert(cols, best) + signs[row + 1] = if bv < 0 then 1 else 0 + end + local rb = cols[1] + cols[2] * 4 + signs[1] * 16 + signs[2] * 32 + signs[3] * 64 + if rb ~= IDENTITY_R then + f._r = tostring(rb) + end + local tx, ty, tz = math.floor(m[13] + 0.5), math.floor(m[14] + 0.5), math.floor(m[15] + 0.5) + if tx ~= 0 or ty ~= 0 or tz ~= 0 then + f._t = string.format("%d %d %d", tx, ty, tz) + end + return f, nil +end + +type Record = { kind: string, id: number, attrs: { [string]: any }?, child: number?, layer: number?, frames: { Dict }?, children: { number }?, models: { { model: number, attributes: Dict? } }? } + +function Vox.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local version = opts and opts.version or 200 + if type(version) ~= "number" or version < 0 then + return nil, Err.new(Err.ARG, "bad version") + end + if type(value) ~= "table" then + return nil, Err.new(Err.ARG, "needs a Scene with voxels or a Voxels grid") + end + local scene: Types.Scene + if value.kind == "voxels" then + scene = Types.Scene.new() + scene.voxels = { value } + scene.nodes[1] = { children = {}, voxels = 1 } + scene.roots[1] = 1 + elseif value.kind == "scene" then + scene = value + else + return nil, Err.new(Err.ARG, "needs a Scene with voxels or a Voxels grid") + end + local models = scene.voxels + if type(models) ~= "table" or #models == 0 then + return nil, Err.new(Err.ARG, "the scene has no voxels (MeshOps cannot voxelize meshes yet)") + end + for i, v in models do + local s = v.size + if type(s) ~= "table" or type(v.data) ~= "buffer" then + return nil, Err.new(Err.ARG, "voxels " .. i .. ": not a Voxels grid") + end + for k = 1, 3 do + if type(s[k]) ~= "number" or s[k] < 1 or s[k] > 256 or s[k] ~= math.floor(s[k]) then + return nil, Err.new(Err.ARG, "voxels " .. i .. ": size must be 1..256 per axis") + end + end + if buffer.len(v.data) < s[1] * s[2] * s[3] then + return nil, Err.new(Err.ARG, "voxels " .. i .. ": data is smaller than the grid") + end + end + 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) + w:string("MAIN") + w:u32le(0) + local mAt = w:tell() + w:u32le(0) + local function chunk(id: string, body: () -> ()) + w:string(id) + local at = w:tell() + w:u32le(0) + w:u32le(0) + body() + w:setU32le(at, w:tell() - at - 8) + end + if type(meta.info) == "table" then + chunk("META", function() + wdict(w, meta.info) + end) + end + for _, v in models do + local sx, sy, sz = v.size[1], v.size[2], v.size[3] + chunk("SIZE", function() + w:u32le(sx) + w:u32le(sy) + w:u32le(sz) + end) + local count = Grid.count(v.data, sx * sy * sz) + chunk("XYZI", function() + w:u32le(count) + local at = w:reserve(count * 4) + Grid.write(w.buf, at, v.data, sx, sy, sz) + w.pos = at + count * 4 + end) + end + local records: { Record } = {} + local nextId = 0 + local function alloc(): number + local id = nextId + nextId += 1 + return id + end + local nodes = scene.nodes or {} + local visiting: { [number]: boolean } = {} + local failure: string? = nil + local function shape(model: number, vx: any?): number + local id = alloc() + 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 + if type(sm.model) == "number" and sm.model >= 1 and sm.model <= #models then + table.insert(ms, { model = sm.model - 1, attributes = sm.attributes }) + end + end + end + if #ms == 0 then + ms[1] = { model = model - 1, attributes = nil } + end + table.insert(records, { kind = "nSHP", id = id, attrs = saved and saved.attributes, models = ms }) + return id + end + local function visit(index: number, depth: number, layer: number?): number? + local node = nodes[index] + if not node or visiting[index] or depth > MAX_DEPTH then + failure = failure or "the node tree has a loop or is too deep" + return nil + end + visiting[index] = true + local vx = if type(node.extras) == "table" and type(node.extras.vox) == "table" then node.extras.vox else nil + local id = alloc() + local attrs: { [string]: any } = {} + if vx and type(vx.attributes) == "table" then + for k, v in vx.attributes do + attrs[k] = v + end + end + attrs._name = node.name + local saved = vx and type(vx.frames) == "table" and vx.frames or nil + local f, ferr = frameOf(node, saved and saved[1]) + if not f then + failure = failure or ferr + f = {} + end + local frames = { f :: Dict } + if saved then + for k = 2, #saved do + frames[k] = saved[k] + end + end + local rec: Record = { kind = "nTRN", id = id, attrs = attrs, layer = layer or (vx and tonumber(vx.layer)) or 0, frames = frames } + table.insert(records, rec) + local kids = node.children or {} + local hasVox = type(node.voxels) == "number" and node.voxels >= 1 and node.voxels <= #models + if hasVox and #kids == 0 then + rec.child = shape(node.voxels :: number, vx) + else + local gid = alloc() + local grp: Record = { kind = "nGRP", id = gid, attrs = vx and vx.group, children = {} } + table.insert(records, grp) + rec.child = gid + if hasVox then + local tid = alloc() + local t2: Record = { kind = "nTRN", id = tid, attrs = {}, layer = 0, frames = { {} } } + table.insert(records, t2) + table.insert(grp.children :: { number }, tid) + t2.child = shape(node.voxels :: number, vx) + end + for _, c in kids do + local cid = visit(c, depth + 1, nil) + if cid then + table.insert(grp.children :: { number }, cid) + end + end + end + visiting[index] = nil + return id + end + local roots = scene.roots or {} + local single = if #roots == 1 then nodes[roots[1]] else nil + if single and single.voxels == nil then + visit(roots[1], 0, -1) + elseif #roots > 0 then + local rid = alloc() + local gid = alloc() + local rec: Record = { kind = "nTRN", id = rid, attrs = {}, child = gid, layer = -1, frames = { {} } } + local grp: Record = { kind = "nGRP", id = gid, attrs = nil, children = {} } + table.insert(records, rec) + table.insert(records, grp) + for _, ri in roots do + local cid = visit(ri, 1, nil) + if cid then + table.insert(grp.children :: { number }, cid) + end + end + end + if failure then + return nil, Err.new(Err.ARG, failure) + end + for _, rec in records do + chunk(rec.kind, function() + w:u32le(rec.id) + wdict(w, rec.attrs) + if rec.kind == "nTRN" then + w:u32le(rec.child or 0) + w:u32le(0xFFFFFFFF) + w:u32le((rec.layer or 0) % 4294967296) + local frames = rec.frames or { {} } + w:u32le(#frames) + for _, f in frames do + wdict(w, f) + end + elseif rec.kind == "nGRP" then + local ch = rec.children or {} + w:u32le(#ch) + for _, c in ch do + w:u32le(c) + end + else + local ms = rec.models or {} + w:u32le(#ms) + for _, sm in ms do + w:u32le(sm.model) + wdict(w, sm.attributes) + end + end + end) + end + if type(meta.layers) == "table" then + for _, l in meta.layers do + chunk("LAYR", function() + w:u32le(tonumber(l.id) or 0) + local d: { [string]: any } = {} + if type(l.attributes) == "table" then + for k, v in l.attributes do + d[k] = v + end + end + d._name = l.name + d._hidden = if l.hidden then "1" elseif d._hidden ~= nil then "0" else nil + wdict(w, d) + w:u32le(0xFFFFFFFF) + end) + end + end + local pal = models[1].palette or DEFAULT_PALETTE + chunk("RGBA", function() + for i = 1, 256 do + local c = pal[i] + if type(c) == "table" then + w:u8(math.clamp(math.floor(tonumber(c[1]) or 0), 0, 255)) + w:u8(math.clamp(math.floor(tonumber(c[2]) or 0), 0, 255)) + w:u8(math.clamp(math.floor(tonumber(c[3]) or 0), 0, 255)) + w:u8(math.clamp(math.floor(tonumber(c[4]) or 255), 0, 255)) + else + w:u32le(0) + end + end + end) + if type(meta.indexMap) == "table" then + chunk("IMAP", function() + for k = 1, 256 do + w:u8(math.clamp(math.floor(tonumber(meta.indexMap[k]) or 0), 0, 255)) + end + end) + end + local mats = models[1].materials + if type(mats) == "table" then + local ids = {} + for id in mats do + if type(id) == "number" then + table.insert(ids, id) + end + end + table.sort(ids) + for _, id in ids do + local m = mats[id] + chunk("MATL", function() + w:u32le(id) + local d: { [string]: any } = { _type = "_" .. tostring(m.type or "diffuse") } + for k, v in m do + if k ~= "type" and type(k) == "string" then + d["_" .. k] = v + end + end + wdict(w, d) + end) + end + end + if type(meta.renderObjects) == "table" then + for _, d in meta.renderObjects do + chunk("rOBJ", function() + wdict(w, d) + end) + end + end + if type(meta.cameras) == "table" then + for _, cam in meta.cameras do + chunk("rCAM", function() + w:u32le(tonumber(cam.id) or 0) + wdict(w, cam.attributes) + end) + end + end + if type(meta.notes) == "table" then + chunk("NOTE", function() + w:u32le(#meta.notes) + for _, s in meta.notes do + wstr(w, tostring(s)) + end + end) + end + if type(meta.chunks) == "table" then + for _, u in meta.chunks do + if type(u.id) == "string" and #u.id == 4 and type(u.content) == "buffer" and u.id ~= "PACK" then + w:string(u.id) + w:u32le(buffer.len(u.content)) + w:u32le(if u.children then buffer.len(u.children) else 0) + w:bytes(u.content) + if u.children then + w:bytes(u.children) + end + end + end + end + w:setU32le(mAt, w:tell() - mAt - 4) + return w:finish(), nil +end + +return Vox +end +__FILES["model/vox/Grid"] = @native function() + + +-- model/vox/Grid: XYZI records to and from a dense grid (cell x + sx * (y + sy * z); index 0 = empty). Never throws. +local Grid = {} + +local readu8, writeu8 = buffer.readu8, buffer.writeu8 + +@native function Grid.fill(dst: buffer, sx: number, sy: number, sz: number, src: buffer, off: number, n: number): number + local skipped = 0 + local sxy = sx * sy + for k = 0, n - 1 do + local p = off + k * 4 + local x, y, z, i = readu8(src, p), readu8(src, p + 1), readu8(src, p + 2), readu8(src, p + 3) + if x < sx and y < sy and z < sz and i ~= 0 then + writeu8(dst, x + sx * y + sxy * z, i) + else + skipped += 1 + end + end + return skipped +end + +@native function Grid.count(data: buffer, cells: number): number + local n = 0 + for k = 0, cells - 1 do + if readu8(data, k) ~= 0 then + n += 1 + end + end + return n +end + +-- one XYZI record per non-empty cell (x fastest; sx, sy, sz <= 256) +@native function Grid.write(dst: buffer, at: number, data: buffer, sx: number, sy: number, sz: number): number + local p = at + local k = 0 + for z = 0, sz - 1 do + for y = 0, sy - 1 do + for x = 0, sx - 1 do + local i = readu8(data, k) + if i ~= 0 then + writeu8(dst, p, x) + writeu8(dst, p + 1, y) + writeu8(dst, p + 2, z) + writeu8(dst, p + 3, i) + p += 4 + end + k += 1 + end + end + end + return p +end + +return Grid +end +__FILES["model/vrml"] = function() + +-- model/vrml: VRML97 (ISO/IEC 14772-1, `#VRML V2.0 utf8`) .wrl / .wrz over codecs/model/Vrml; new code. Supports: +-- the scene graph, DEF / USE, PROTO / EXTERNPROTO, the geometry nodes, Viewpoints, lights, interpolator ROUTEs as +-- animations. Not supported: VRML 1.0, Text, Script, sensors, sound, NURBS; morph targets and skins on write. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Vrml = __include("codecs/model/Vrml") + +-- ------------------------------------------------------------------------------------------------ contract +local Wrl = { + name = "vrml", + category = "model", + extensions = { "wrl", "wrz", "vrml" }, + mime = { "model/vrml", "x-world/x-vrml" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Vrml" }, + caps = { decode = true, encode = true, materials = true, polygons = true, animation = true, cameras = true, lights = true, lines = true, points = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + files: { [string]: any }?, -- by uri or base name + resolve: ((uri: string) -> any)?, + triangulate: boolean?, -- default true + flipV: boolean?, -- default true + segments: number?, -- default 32 + maxVertices: number?, -- per geometry (default 2^24) +} +type EncodeOptions = { + files: { [string]: any }?, -- else url = texture.uri + name: string?, + flipV: boolean?, -- default true (the inverse of decode) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Wrl.sniff(r: Bytes.Reader): number + local head = r:peek(16) + if string.sub(head, 1, 3) == "\239\187\191" then + head = string.sub(head, 4) + end + return if string.sub(head, 1, 10) == "#VRML V2.0" then 1 elseif string.sub(head, 1, 6) == "#VRML " then 0.6 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Wrl.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local o: any = table.clone(opts or {}) + o.format = "vrml" + return Vrml.decode(buffer.readstring(r.buf, r.base, r.limit - r.base), o) +end + +-- ------------------------------------------------------------------------------------------------ encode +function Wrl.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: any = table.clone(opts or {}) + o.encoding = "vrml97" + local text, err = Vrml.encode(scene, o) + if not text then + return nil, err + end + return buffer.fromstring(text), nil +end + +return Wrl +end +__FILES["model/x"] = function() + +-- model/x: DirectX .x, read only: text ("txt "), binary ("bin "), MSZIP ("tzip" / "bzip"), 32- and 64-bit floats; from +-- Microsoft's DirectX file format spec and templates, checked against assimp. AnimTicksPerSecond defaults to 4800. Not +-- supported: DeclData / FVFData, progressive and patch meshes, non-linear key interpolation. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Deflate = __include("codecs/compress/Deflate") +local Parse = __include("model/x/Parse") +local Build = __include("model/x/Build") + +-- ------------------------------------------------------------------------------------------------ contract +local X = { + name = "x", + category = "model", + extensions = { "x" }, + mime = { "model/x-directx", "text/x-directx" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Deflate", "codecs/model/Mat4", "codecs/model/Rig" }, + caps = { decode = true, encode = false, text = true, binary = true, compressed = true, materials = true, skins = true, animation = true, polygons = true, vertexColors = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + triangulate: boolean?, -- default true + maxVertices: number?, -- default 2^25 + maxValues: number?, -- default 2^27 + maxBytes: number?, -- default 2^30 +} + +-- ------------------------------------------------------------------------------------------------ constants +local ENCODINGS = { ["txt "] = "text", ["bin "] = "binary", tzip = "text", bzip = "binary" } + +-- ------------------------------------------------------------------------------------------------ sniff +function X.sniff(r: Bytes.Reader): number + if r:peek(4) ~= "xof " then + return 0 + end + return if ENCODINGS[r:peek(4, 8)] then 1 else 0.5 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- MSZIP: a u32 total size (with the 16-byte file header), then blocks (u16 uncompressed size, u16 compressed size, +-- "CK" + deflate data); each block may refer back into the previous block's output. +local function mszip(b: buffer, p: number, limit: number, maxBytes: number): (buffer?, Err.Err?) + if p + 4 > limit then + return nil, Err.new(Err.TRUNCATED, "no MSZIP header", p) + end + local total = math.max(buffer.readu32(b, p) - 16, 0) -- the size counts the 16-byte header + if total > maxBytes then + return nil, Err.new(Err.LIMIT, "inflates to " .. total .. " bytes", p) + end + p += 4 + local spans: { { offset: number, length: number, size: number } } = {} + local o = 0 + while p + 6 <= limit and o < total do + local usize, csize = buffer.readu16(b, p), buffer.readu16(b, p + 2) + if buffer.readstring(b, p + 4, 2) ~= "CK" or csize < 2 then + return nil, Err.new(Err.CORRUPT, "bad MSZIP block", p) + end + if o + usize > total then + return nil, Err.new(Err.CORRUPT, "MSZIP block size mismatch", p) + end + table.insert(spans, { offset = p + 4, length = math.min(csize, limit - p - 4), size = usize }) + o += usize + p += 4 + csize + end + if o < total then + return nil, Err.new(Err.TRUNCATED, "MSZIP data ends early", p) + end + local out, err = Deflate.mszip(b, spans) + if not out then + return nil, Err.new((err :: Err.Err).code, "MSZIP: " .. (err :: Err.Err).message, (err :: Err.Err).offset) + end + return out, nil +end + +function X.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local b, base, limit = r.buf, r.base, r.limit + if limit - base < 16 then + return nil, Err.new(Err.TRUNCATED, "shorter than the header", base) + end + if buffer.readstring(b, base, 4) ~= "xof " then + return nil, Err.new(Err.CORRUPT, "no xof header", base) + end + local enc = buffer.readstring(b, base + 8, 4) + local kind = ENCODINGS[enc] + if not kind then + return nil, Err.new(Err.UNSUPPORTED, "encoding " .. string.format("%q", enc), base + 8) + end + local bits = buffer.readstring(b, base + 12, 4) + local floatSize = if bits == "0064" then 8 elseif bits == "0032" then 4 else 0 + if floatSize == 0 then + return nil, Err.new(Err.CORRUPT, "float size " .. string.format("%q", bits), base + 12) + end + local data: buffer, from: number, to: number = b, base + 16, limit + if enc == "tzip" or enc == "bzip" then + local inflated, err = mszip(b, base + 16, limit, opts and opts.maxBytes or 2 ^ 30) + if not inflated then + return nil, err + end + data, from, to = inflated, 0, buffer.len(inflated) + end + local maxValues: number = opts and opts.maxValues or 2 ^ 27 + local ok, root, msg = pcall(Parse.tree, data, from, to :: number, kind == "binary", floatSize, maxValues) + if not ok then + return nil, Err.new(Err.CORRUPT, "bad data: " .. tostring(root)) + end + if not root then + return nil, Err.from(msg) + end + local ok2, scene, msg2 = pcall(Build.scene, root, opts) + if not ok2 then + return nil, Err.from(tostring(scene)) + end + if not scene then + return nil, Err.from(msg2) + end + local src = scene.meta.source :: { [string]: any } + src.version = buffer.readstring(b, base + 4, 4) + src.encoding = kind + src.compressed = enc == "tzip" or enc == "bzip" + src.floatSize = floatSize * 8 + return scene, nil +end + +return X +end +__FILES["model/x/Build"] = function() + +-- model/x/Build: the .x object tree to a Scene, from the DirectX template layouts. Direct3D is left-handed (y up, row +-- vectors): z is negated (matrices as S * M * S) and windings reversed, as assimp does; UVs stay top-left. +local Types = __include("Types") +local Mat4 = __include("codecs/model/Mat4") +local Rig = __include("codecs/model/Rig") +local Parse = __include("model/x/Parse") + +local Build = {} + +local Scene = Types.Scene +local writef32, writeu32 = buffer.writef32, buffer.writeu32 + +type Node = Parse.Node + +type Vals = { v: { any }, i: number } +local function num(c: Vals): number + local x = c.v[c.i] + c.i += 1 + if type(x) ~= "number" then + error("expected a number in the data", 0) + end + return x +end +local function str(c: Vals): string + local x = c.v[c.i] + c.i += 1 + if type(x) ~= "string" then + error("expected a string in the data", 0) + end + return x +end +local function index(c: Vals, limit: number): number + local n = num(c) + if n < 0 or n ~= math.floor(n) or n > limit then + error("bad index " .. n, 0) + end + return n +end + +local function count(c: Vals, limit: number): number + local n = num(c) + if n < 0 or n ~= math.floor(n) or n > limit then + error("bad count " .. n, 0) + end + if n > #c.v - c.i + 1 then + error("truncated: a count of " .. n .. " runs past the data", 0) + end + return n +end + +-- S * M * S, S = diag(1, 1, -1) +local function mirror(m: { number }): { number } + local o = table.clone(m) + for _, k in { 3, 7, 9, 10, 12, 15 } do + o[k] = -o[k] + end + return o +end + +local function matrix(c: Vals): { number } + local m = table.create(16) :: { number } + for k = 1, 16 do + m[k] = num(c) + end + return mirror(m) +end + +-- ------------------------------------------------------------------------------------------------ materials +local MIME: { [string]: string } = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", bmp = "image/bmp", tga = "image/x-tga", dds = "image/vnd-ms.dds", gif = "image/gif" } + +local function material(scene: Types.Scene, node: Node, texCache: { [string]: number }): Types.Material + local c: Vals = { v = node.vals, i = 1 } + local mat = Scene.material(node.name) + local r, g, b, a = num(c), num(c), num(c), num(c) + local power = num(c) + local sr, sg, sb = num(c), num(c), num(c) + local er, eg, eb = num(c), num(c), num(c) + mat.baseColor = { r, g, b, a } + if a < 1 then + mat.alphaMode = "blend" + end + mat.metallic = 0 + mat.roughness = math.clamp(math.sqrt(2 / (math.max(power, 0) + 2)), 0, 1) + mat.emissive = { er, eg, eb } + local textures = {} + for _, k in node.kids do + local lt = string.lower(k.type) + if lt == "texturefilename" or lt == "normalmapfilename" then + local path = k.vals[1] + if type(path) == "string" and path ~= "" then + path = string.gsub(path, "\\\\", "\\") + local uri = string.gsub(path, "\\", "/") + local ti = texCache[uri] + if not ti then + local base = string.match(uri, "([^/]+)$") or uri + local ext = string.lower(string.match(base, "%.(%w+)$") or "") + table.insert(scene.textures, { name = base, uri = uri, mime = MIME[ext] }) + ti = #scene.textures + texCache[uri] = ti + end + table.insert(textures, uri) + if lt == "normalmapfilename" then + mat.normalTexture = mat.normalTexture or { texture = ti } + else + mat.baseColorTexture = mat.baseColorTexture or { texture = ti } + end + end + end + end + mat.extras = { x = { diffuse = { r, g, b, a }, power = power, specular = { sr, sg, sb }, emissive = { er, eg, eb }, textures = textures } } + return mat +end + +-- ------------------------------------------------------------------------------------------------ meshes +type Bones = { { name: string, matrix: { number } } } +type Ctx = { + scene: Types.Scene, + globalMats: { [string]: number }, + texCache: { [string]: number }, + nodeByName: { [string]: number }, + pendingSkins: { { node: number, bones: Bones } }, + maxVertices: number, + skippedFaces: number, +} + +local function accessorF32(values: { number }, comps: number): Types.Accessor + local n = #values + local b = buffer.create(n * 4) + for i = 1, n do + writef32(b, (i - 1) * 4, values[i]) + end + return Scene.accessor(b, "f32", comps, n // comps) +end + +local function mesh(ctx: Ctx, m: Node, triangulate: boolean): (number?, Bones?) + local scene = ctx.scene + local c: Vals = { v = m.vals, i = 1 } + local nv = count(c, ctx.maxVertices) + local pos = table.create(nv * 3) :: { number } + for k = 1, nv * 3 do + pos[k] = num(c) + end + local nf = count(c, ctx.maxVertices) + local faces = table.create(nf) :: { { number } } + local corners = 0 + for f = 1, nf do + local n = count(c, ctx.maxVertices) + corners += n + if corners > ctx.maxVertices then + error("limit: more than " .. ctx.maxVertices .. " face corners", 0) + end + local face = table.create(n) :: { number } + for k = 1, n do + local idx = index(c, 2 ^ 32) + if idx >= nv then + error("face index " .. idx .. " out of range", 0) + end + face[k] = idx + end + faces[f] = face + end + local normals: { number }? = nil + local nfaces: { { number } }? = nil + local uvSets: { { number } } = {} + local colors: { { number } } = {} + local faceMat: { number } = {} + local mats: { number } = {} + local bones: { { name: string, verts: { number }, weights: { number }, matrix: { number } } } = {} + for _, k in m.kids do + local kc: Vals = { v = k.vals, i = 1 } + if k.type == "MeshNormals" then + local nn = count(kc, ctx.maxVertices) + local nr = table.create(nn * 3) :: { number } + for q = 1, nn * 3 do + nr[q] = num(kc) + end + local nnf = count(kc, ctx.maxVertices) + local nfs = table.create(nnf) :: { { number } } + for f = 1, nnf do + local n = count(kc, ctx.maxVertices) + local face = table.create(n) :: { number } + for q = 1, n do + face[q] = index(kc, 2 ^ 32) + end + nfs[f] = face + end + normals, nfaces = nr, nfs + elseif k.type == "MeshTextureCoords" then + local n = count(kc, ctx.maxVertices) + local uv = table.create(n * 2) :: { number } + for q = 1, n * 2 do + uv[q] = num(kc) + end + if n == nv then + table.insert(uvSets, uv) + end + elseif k.type == "MeshVertexColors" then + local n = count(kc, ctx.maxVertices) + local col = table.create(nv * 4, 1) :: { number } + for _ = 1, n do + local idx = index(kc, 2 ^ 32) + local r, g, b, a = num(kc), num(kc), num(kc), num(kc) + if idx < nv then + col[idx * 4 + 1], col[idx * 4 + 2], col[idx * 4 + 3], col[idx * 4 + 4] = r, g, b, a + end + end + table.insert(colors, col) + elseif k.type == "MeshMaterialList" then + num(kc) -- material count (the objects below are authoritative) + local ni = count(kc, ctx.maxVertices) + for q = 1, ni do + faceMat[q] = index(kc, 2 ^ 20) + end + for _, mk in k.kids do + if mk.type == "@ref" then + table.insert(mats, if mk.name then ctx.globalMats[mk.name] or 0 else 0) + elseif mk.type == "Material" then + table.insert(scene.materials, material(scene, mk, ctx.texCache)) + table.insert(mats, #scene.materials) + end + end + elseif k.type == "SkinWeights" then + local name = str(kc) + local n = count(kc, ctx.maxVertices) + local verts = table.create(n) :: { number } + for q = 1, n do + verts[q] = index(kc, 2 ^ 32) + end + local weights = table.create(n) :: { number } + for q = 1, n do + weights[q] = num(kc) + end + table.insert(bones, { name = name, verts = verts, weights = weights, matrix = matrix(kc) }) + end + end + -- a single index applies to every face + local function matOf(f: number): number + local mi = if #faceMat == 1 then faceMat[1] else faceMat[f] + return if mi then mi + 1 else 1 + end + local key: { [number]: number } = {} + local srcPos: { number } = {} + local srcNrm: { number } = {} + local groups: { [number]: { number } } = {} + local order: { number } = {} + local faceSizes: { [number]: { number } } = {} + local nNormals = if normals then #normals // 3 else 0 + for f, face in faces do + local n = #face + if n < 3 then + ctx.skippedFaces += 1 + else + local nface = nfaces and nfaces[f] + local vs = table.create(n) :: { number } + for k = 1, n do + local src = if k == 1 then 1 else n - k + 2 + local p = face[src] + local q = if nface and nface[src] and nface[src] < nNormals then nface[src] else -1 + local kk = p * (nNormals + 1) + q + 1 + local v = key[kk] + if not v then + table.insert(srcPos, p) + table.insert(srcNrm, q) + v = #srcPos - 1 + key[kk] = v + end + vs[k] = v + end + local mi = matOf(f) + local g = groups[mi] + if not g then + g = {} + groups[mi] = g + faceSizes[mi] = {} + table.insert(order, mi) + end + if triangulate then + for k = 2, n - 1 do + table.insert(g, vs[1]) + table.insert(g, vs[k]) + table.insert(g, vs[k + 1]) + end + else + table.move(vs, 1, n, #g + 1, g) + table.insert(faceSizes[mi], n) + end + end + end + if #order == 0 then + return nil, nil + end + table.sort(order) + local nout = #srcPos + local P = table.create(nout * 3) :: { number } + for v = 1, nout do + local p = srcPos[v] * 3 + P[v * 3 - 2], P[v * 3 - 1], P[v * 3] = pos[p + 1], pos[p + 2], -pos[p + 3] + end + local attributes: { [string]: Types.Accessor } = { POSITION = accessorF32(P, 3) } + if normals then + local N = table.create(nout * 3, 0) :: { number } + for v = 1, nout do + local q = srcNrm[v] + if q >= 0 then + N[v * 3 - 2], N[v * 3 - 1], N[v * 3] = normals[q * 3 + 1], normals[q * 3 + 2], -normals[q * 3 + 3] + end + end + attributes.NORMAL = accessorF32(N, 3) + end + for s, uv in uvSets do + local U = table.create(nout * 2) :: { number } + for v = 1, nout do + local p = srcPos[v] * 2 + U[v * 2 - 1], U[v * 2] = uv[p + 1], uv[p + 2] + end + attributes["TEXCOORD_" .. (s - 1)] = accessorF32(U, 2) + end + for s, col in colors do + local C = table.create(nout * 4) :: { number } + for v = 1, nout do + local p = srcPos[v] * 4 + C[v * 4 - 3], C[v * 4 - 2], C[v * 4 - 1], C[v * 4] = col[p + 1], col[p + 2], col[p + 3], col[p + 4] + end + attributes["COLOR_" .. (s - 1)] = accessorF32(C, 4) + end + if #bones > 0 then + local lists = table.create(nout) :: { { number } } + local byPos: { [number]: { number } } = {} + for j, bone in bones do + for q, vi in bone.verts do + local l = byPos[vi] + if not l then + l = {} + byPos[vi] = l + end + table.insert(l, j - 1) + table.insert(l, bone.weights[q] or 0) + end + end + for v = 1, nout do + lists[v] = byPos[srcPos[v]] or {} + end + attributes.JOINTS_0, attributes.WEIGHTS_0 = Rig.influences(lists) + end + local skinBones: Bones? = nil + if #bones > 0 then + local list: Bones = {} + for _, bone in bones do + table.insert(list, { name = bone.name, matrix = bone.matrix }) + end + skinBones = list + end + local prims: { Types.Primitive } = {} + for _, mi in order do + local idx = groups[mi] + local ib = buffer.create(#idx * 4) + for k, x in idx do + writeu32(ib, (k - 1) * 4, x) + end + local prim: Types.Primitive = { attributes = attributes, indices = Scene.accessor(ib, "u32", 1, #idx), mode = "triangles" } + local mat = mats[mi] + prim.material = if mat and mat > 0 then mat else nil + if not triangulate then + prim.mode = "polygons" + local fs = faceSizes[mi] + local fb = buffer.create(#fs * 4) + for k, x in fs do + writeu32(fb, (k - 1) * 4, x) + end + prim.faces = Scene.accessor(fb, "u32", 1, #fs) + end + table.insert(prims, prim) + end + table.insert(scene.meshes, { name = m.name, primitives = prims }) + return #scene.meshes, skinBones +end + +-- ------------------------------------------------------------------------------------------------ frames +local function frame(ctx: Ctx, f: Node, parent: number?, triangulate: boolean, depth: number) + if depth > 200 then + error("frames nested too deep", 0) + end + local scene = ctx.scene + local node: Types.Node = { name = f.name, children = {} } + table.insert(scene.nodes, node) + local ni = #scene.nodes + if f.name and ctx.nodeByName[f.name] == nil then + ctx.nodeByName[f.name] = ni + end + if parent then + table.insert(scene.nodes[parent].children, ni) + else + table.insert(scene.roots, ni) + end + local first = true + for _, k in f.kids do + if k.type == "FrameTransformMatrix" then + local m = matrix({ v = k.vals, i = 1 }) + local t, r, s = Mat4.decomposeStrict(m) + if t and r and s then + node.translation, node.rotation, node.scale = t, r, s + else + node.matrix = m + end + elseif k.type == "Mesh" then + local mi, bones = mesh(ctx, k, triangulate) + if mi then + local holder = ni + if first then + node.mesh = mi + first = false + else + table.insert(scene.nodes, { name = k.name, children = {}, mesh = mi }) + holder = #scene.nodes + table.insert(node.children, holder) + end + if bones then + table.insert(ctx.pendingSkins, { node = holder, bones = bones }) + end + end + elseif k.type == "Frame" then + frame(ctx, k, ni, triangulate, depth + 1) + end + end +end + +-- ------------------------------------------------------------------------------------------------ animations +local function channel(input: { number }, output: { number }, comps: number, node: number, path: string): Types.Channel + return { node = node, path = path :: any, input = accessorF32(input, 1), output = accessorF32(output, comps), interpolation = "LINEAR" } +end + +local function animationSet(ctx: Ctx, set: Node, tps: number): Types.Animation? + local channels: { Types.Channel } = {} + for _, a in set.kids do + if a.type == "Animation" then + local target: string? = nil + for _, k in a.kids do + if k.type == "@ref" then + target = k.name + end + end + local node = target and ctx.nodeByName[target] + if node then + for _, k in a.kids do + if k.type == "AnimationKey" then + local c: Vals = { v = k.vals, i = 1 } + local kind = num(c) + local nk = count(c, ctx.maxVertices) + local times = table.create(nk) :: { number } + local T, R, S = {}, {}, {} + for q = 1, nk do + times[q] = num(c) / tps + local nvals = count(c, 16) + if kind == 0 and nvals == 4 then + local w, x, y, z = num(c), num(c), num(c), num(c) + -- the file's quaternion is the conjugate (row vectors); mirroring z negates x and y + table.move({ x, y, -z, w }, 1, 4, #R + 1, R) + elseif (kind == 1 or kind == 2) and nvals == 3 then + local x, y, z = num(c), num(c), num(c) + if kind == 1 then + table.move({ x, y, z }, 1, 3, #S + 1, S) + else + table.move({ x, y, -z }, 1, 3, #T + 1, T) + end + elseif (kind == 3 or kind == 4) and nvals == 16 then + local t, r, s = Mat4.decompose(matrix(c)) + table.move(t, 1, 3, #T + 1, T) + table.move(r, 1, 4, #R + 1, R) + table.move(s, 1, 3, #S + 1, S) + else + error("bad animation key (type " .. kind .. ", " .. nvals .. " values)", 0) + end + end + if #T == nk * 3 and nk > 0 then + table.insert(channels, channel(times, T, 3, node, "translation")) + end + if #R == nk * 4 and nk > 0 then + table.insert(channels, channel(times, R, 4, node, "rotation")) + end + if #S == nk * 3 and nk > 0 then + table.insert(channels, channel(times, S, 3, node, "scale")) + end + end + end + end + end + end + if #channels == 0 then + return nil + end + return { name = set.name, channels = channels } +end + +-- ------------------------------------------------------------------------------------------------ scene +function Build.scene(root: Node, opts: { triangulate: boolean?, maxVertices: number? }?): (Types.Scene?, string?) + local triangulate = not (opts and opts.triangulate == false) + local scene = Scene.new() + scene.meta.up = "y" + local ctx: Ctx = { scene = scene, globalMats = {}, texCache = {}, nodeByName = {}, pendingSkins = {}, maxVertices = opts and opts.maxVertices or 2 ^ 25, skippedFaces = 0 } + local tps = 4800 + for _, k in root.kids do + if k.type == "Material" then + table.insert(scene.materials, material(scene, k, ctx.texCache)) + if k.name then + ctx.globalMats[k.name] = #scene.materials + end + elseif k.type == "AnimTicksPerSecond" then + local v = k.vals[1] + if type(v) == "number" and v > 0 then + tps = v + end + end + end + for _, k in root.kids do + if k.type == "Frame" then + frame(ctx, k, nil, triangulate, 0) + elseif k.type == "Mesh" then + local mi, bones = mesh(ctx, k, triangulate) + table.insert(scene.nodes, { name = k.name, children = {}, mesh = mi }) + table.insert(scene.roots, #scene.nodes) + if bones then + table.insert(ctx.pendingSkins, { node = #scene.nodes, bones = bones }) + end + end + end + for _, ps in ctx.pendingSkins do + local joints: { number } = {} + local ibm = buffer.create(#ps.bones * 64) + for j, bone in ps.bones do + local ni = ctx.nodeByName[bone.name] + if not ni then + -- a bone without a frame: an extra root node keeps the joint numbering + table.insert(scene.nodes, { name = bone.name, children = {} }) + ni = #scene.nodes + table.insert(scene.roots, ni) + ctx.nodeByName[bone.name] = ni + end + joints[j] = ni + for k = 1, 16 do + writef32(ibm, ((j - 1) * 16 + k - 1) * 4, bone.matrix[k]) + end + end + local acc = Scene.accessor(ibm, "f32", 16, #ps.bones) + acc.matrix = true + table.insert(scene.skins, { joints = joints, inverseBindMatrices = acc }) + scene.nodes[ps.node].skin = #scene.skins + end + for _, k in root.kids do + if k.type == "AnimationSet" then + local anim = animationSet(ctx, k, tps) + if anim then + table.insert(scene.animations, anim) + end + end + end + scene.meta.source = { format = "x", ticksPerSecond = tps, skippedFaces = ctx.skippedFaces } + return scene, nil +end + +return Build +end +__FILES["model/x/Parse"] = function() + +-- model/x/Parse: .x text and binary tokens to { type, name?, vals, kids } objects, from Microsoft's "DirectX File +-- Format Specification", checked against assimp's XFileParser (no code taken). Templates are skipped; Blender's +-- "1.#IND00" / "1.#QNAN0" read as 0. Never throws: bad data returns nil, message. +local Parse = {} + +type Node = { type: string, name: string?, vals: { any }, kids: { Node } } + +local readu16, readu32, readf32, readf64, readstring = buffer.readu16, buffer.readu32, buffer.readf32, buffer.readf64, buffer.readstring + +type Lexer = { next: () -> (string, any), err: string? } + +local KEYWORDS: { [number]: string } = { + [0x1F] = "template", + [0x28] = "WORD", + [0x29] = "DWORD", + [0x2A] = "FLOAT", + [0x2B] = "DOUBLE", + [0x2C] = "CHAR", + [0x2D] = "UCHAR", + [0x2E] = "SWORD", + [0x2F] = "SDWORD", + [0x30] = "void", + [0x31] = "string", + [0x32] = "unicode", + [0x33] = "cstring", + [0x34] = "array", +} + +-- ------------------------------------------------------------------------------------------------ text +local function textLexer(s: string): Lexer + local lex: Lexer = { next = nil :: any, err = nil } + local p = 1 + local n = #s + lex.next = function(): (string, any) + while true do + local _, e = string.find(s, "^[%s,;]+", p) + if e then + p = e + 1 + end + if p > n then + return "eof", nil + end + local c = string.byte(s, p) + if c == 47 and string.byte(s, p + 1) == 47 or c == 35 then + local nl = string.find(s, "[\r\n]", p) + p = if nl then nl + 1 else n + 1 + else + break + end + end + local c = string.byte(s, p) + if c == 123 then + p += 1 + return "{", nil + elseif c == 125 then + p += 1 + return "}", nil + elseif c == 34 then + local q = string.find(s, '"', p + 1, true) + if not q then + lex.err = "unterminated string" + p = n + 1 + return "eof", nil + end + local v = string.sub(s, p + 1, q - 1) + p = q + 1 + return "str", v + elseif c == 60 then + local q = string.find(s, ">", p + 1, true) or n + local v = string.sub(s, p + 1, q - 1) + p = q + 1 + return "guid", v + end + local _, e = string.find(s, '^[^%s,;{}"]+', p) + local tok = string.sub(s, p, e :: number) + p = (e :: number) + 1 + if (c >= 48 and c <= 57) or c == 45 or c == 43 or c == 46 then + return "num", tonumber(tok) or 0 + end + return "id", tok + end + return lex +end + +-- ------------------------------------------------------------------------------------------------ binary +local function binaryLexer(b: buffer, from: number, limit: number, floatSize: number): Lexer + local lex: Lexer = { next = nil :: any, err = nil } + local p = from + local function fail(msg: string): (string, any) + lex.err = msg + p = limit + return "eof", nil + end + lex.next = function(): (string, any) + if p + 2 > limit then + return "eof", nil + end + local tok = readu16(b, p) + p += 2 + if tok == 0x0A then + return "{", nil + elseif tok == 0x0B then + return "}", nil + elseif tok == 1 or tok == 2 then -- NAME / STRING: u32 count, bytes (STRING: then a ; or , token) + if p + 4 > limit then + return fail("truncated name") + end + local len = readu32(b, p) + p += 4 + if len > limit - p then + return fail("truncated name") + end + local v = readstring(b, p, len) + p += len + if tok == 2 then + p = math.min(p + 2, limit) + return "str", v + end + return "id", v + elseif tok == 3 then + if p + 4 > limit then + return fail("truncated integer") + end + local v = readu32(b, p) + p += 4 + return "num", v + elseif tok == 5 then + if p + 16 > limit then + return fail("truncated guid") + end + p += 16 + return "guid", "" + elseif tok == 6 or tok == 7 then + if p + 4 > limit then + return fail("truncated list") + end + local count = readu32(b, p) + p += 4 + local size = if tok == 6 then 4 else floatSize + if count > (limit - p) // size then + return fail("truncated list") + end + local out = table.create(count) :: { number } + if tok == 6 then + for i = 1, count do + out[i] = readu32(b, p) + p += 4 + end + elseif size == 8 then + for i = 1, count do + out[i] = readf64(b, p) + p += 8 + end + else + for i = 1, count do + out[i] = readf32(b, p) + p += 4 + end + end + return "list", out + elseif tok >= 0x0C and tok <= 0x14 then + return "punct", nil + elseif KEYWORDS[tok] then + return "id", KEYWORDS[tok] + end + return fail(string.format("unknown binary token 0x%x", tok)) + end + return lex +end + +-- ------------------------------------------------------------------------------------------------ tree +local function tree(lex: Lexer, maxValues: number): (Node?, string?) + local queue: { { any } } = {} + local function take(): (string, any) + local q = table.remove(queue, 1) + if q then + return q[1], q[2] + end + return lex.next() + end + local function peek(k: number): string + while #queue < k do + local kind, v = lex.next() + table.insert(queue, { kind, v }) + if kind == "eof" then + break + end + end + local q = queue[k] + return if q then q[1] else "eof" + end + local budget = maxValues + local function skipBlock(): string? + local depth = 1 + while depth > 0 do + local kind = take() + if kind == "eof" then + return "unexpected end of file in a template" + elseif kind == "{" then + depth += 1 + elseif kind == "}" then + depth -= 1 + end + end + return nil + end + local body: (Node, number) -> string? + local function object(parent: Node, typ: string, depth: number): string? + local name: string? = nil + local kind, v = take() + if kind ~= "{" then + name = if v ~= nil then tostring(v) else nil + kind = take() + if kind ~= "{" then + return "expected { after " .. typ + end + end + if typ == "template" then + return skipBlock() + end + local node: Node = { type = typ, name = name, vals = {}, kids = {} } + table.insert(parent.kids, node) + return body(node, depth + 1) + end + body = function(node: Node, depth: number): string? + if depth > 200 then + return "objects nested too deep" + end + local vals = node.vals + while true do + local kind, v = take() + if kind == "}" then + return nil + elseif kind == "eof" then + return if depth == 0 then nil else "unexpected end of file in " .. node.type + elseif kind == "num" or kind == "str" then + budget -= 1 + if budget < 0 then + return "limit: more than " .. maxValues .. " values" + end + vals[#vals + 1] = v + elseif kind == "list" then + budget -= #v + if budget < 0 then + return "limit: more than " .. maxValues .. " values" + end + table.move(v, 1, #v, #vals + 1, vals) + elseif kind == "{" then + -- a reference: { name [guid] } + local ref: Node = { type = "@ref", name = nil, vals = {}, kids = {} } + while true do + local k2, v2 = take() + if k2 == "}" then + break + elseif k2 == "eof" then + return "unexpected end of file in a reference" + elseif (k2 == "id" or k2 == "num") and ref.name == nil then + ref.name = tostring(v2) + end + end + table.insert(node.kids, ref) + elseif kind == "id" then + local k1 = peek(1) + if k1 == "{" or (k1 ~= "eof" and k1 ~= "}" and peek(2) == "{") then + local err = object(node, v, depth) + if err then + return err + end + end + -- a lone identifier (an enum value): ignored + end + -- guid / punct: ignored + if lex.err then + return lex.err + end + end + end + local root: Node = { type = "@root", name = nil, vals = {}, kids = {} } + local err = body(root, 0) + if err then + return nil, err + end + if lex.err then + return nil, lex.err + end + return root, nil +end + +function Parse.tree(b: buffer, from: number, limit: number, binary: boolean, floatSize: number, maxValues: number): (Node?, string?) + local lex = if binary then binaryLexer(b, from, limit, floatSize) else textLexer(readstring(b, from, limit - from)) + return tree(lex, maxValues) +end + +return Parse +end +__FILES["model/x3d"] = function() + +-- model/x3d: X3D (ISO/IEC 19775-1) XML (.x3d, 19776-1) and classic VRML (.x3dv, 19776-2) encodings, plain or gzipped, +-- over codecs/model/Vrml; new code. Supports: the model/vrml set plus the X3D geometry and material nodes. +-- Not supported: binary encodings (.x3db Fast Infoset / EXI), X3D JSON, Text, NURBS, shaders, H-Anim skinning, scripts. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Vrml = __include("codecs/model/Vrml") + +-- ------------------------------------------------------------------------------------------------ contract +local X3d = { + name = "x3d", + category = "model", + extensions = { "x3d", "x3dv", "x3dz", "x3dvz", "x3db" }, + mime = { "model/x3d+xml", "model/x3d-vrml", "model/x3d+fastinfoset" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Vrml" }, + caps = { decode = true, encode = true, materials = true, polygons = true, animation = true, cameras = true, lights = true, lines = true, points = true, xml = true, classic = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + files: { [string]: any }?, -- by uri or base name + resolve: ((uri: string) -> any)?, + triangulate: boolean?, -- default true + flipV: boolean?, -- default true + segments: number?, -- default 32 + maxVertices: number?, -- per geometry (default 2^24) +} +type EncodeOptions = { + encoding: ("xml" | "x3dv")?, -- default "xml" + format: string?, -- "x3dv" / "x3dvz" select the classic encoding + files: { [string]: any }?, -- else url = texture.uri + name: string?, + flipV: boolean?, -- default true (the inverse of decode) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function X3d.sniff(r: Bytes.Reader): number + local head = r:peek(1024) + if string.sub(head, 1, 3) == "\239\187\191" then + head = string.sub(head, 4) + end + if string.sub(head, 1, 5) == "#X3D " then + return 1 + end + if string.sub(head, 1, 4) == "\224\0\0\1" and string.find(head, "x3d", 1, true) then + return 0.9 + end + if string.find(head, "<X3D[%s>]") or string.find(head, "<!DOCTYPE X3D", 1, true) then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function X3d.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local o: any = table.clone(opts or {}) + o.format = "x3d" + return Vrml.decode(buffer.readstring(r.buf, r.base, r.limit - r.base), o) +end + +-- ------------------------------------------------------------------------------------------------ encode +function X3d.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: any = table.clone(opts or {}) + local classic = o.encoding == "x3dv" or o.format == "x3dv" or o.format == "x3dvz" + o.encoding = if classic then "x3dv" else "xml" + local text, err = Vrml.encode(scene, o) + if not text then + return nil, err + end + return buffer.fromstring(text), nil +end + +return X3d +end +end + + + + + + music + --!optimize 2 +--!nocheck +-- rosetta chunk music (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 22 modules (1 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["music/669"] = function() + +-- music/669: Composer 669 / UNIS 669 modules ("if" / "JN"), ported from OpenMPT's Load_669.cpp (BSD, +-- licenses/openmpt-LICENSE.txt). Supports: 8 channels, 64-row patterns, played as the "s3m" family with 669's quirks +-- (periods in Hz, auto portamentos, effects D..H, a fixed 78 BPM). Not supported: UNIS 669's speed 0, writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Tracker = __include("codecs/audio/Tracker") +local Load = __include("codecs/audio/Tracker/Load") + +-- ------------------------------------------------------------------------------------------------ contract +local Six69 = { + name = "669", + category = "music", + extensions = { "669" }, + mime = { "audio/x-669" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 8, 8 } }, +} + +type DecodeOptions = { + maxBytes: number?, -- f32 bytes of sample data in total, default 2^28 +} + +-- ------------------------------------------------------------------------------------------------ constants +local IT = Load.IT +-- effects: the high nibble of the effect byte +local EFFECTS = { "autoportaup", "autoportadown", "toneporta", "freqadjust", "vibrato", "speed", "panslide", "retrig" } + +-- ------------------------------------------------------------------------------------------------ sniff +-- the 497-byte header (the magic is two bytes only, so the other fields are checked too) +local function validHeader(r: Bytes.Reader): boolean + if r:size() < 497 then + return false + end + local magic = r:peek(2) + if magic ~= "if" and magic ~= "JN" then + return false + end + local nsmp, npat, restart = r:peekU8(110), r:peekU8(111), r:peekU8(112) + if nsmp > 64 or restart >= 128 or npat > 128 then + return false + end + local bad = 0 + for i = 2, 109 do + local c = r:peekU8(i) + if c > 0 and c <= 31 then + bad += 1 + if bad > 40 then + return false + end + end + end + for i = 0, 127 do + local o, t, b = r:peekU8(113 + i), r:peekU8(241 + i), r:peekU8(369 + i) + if (o >= 128 and o < 0xFE) or (o < 128 and t == 0) or t > 15 or b >= 64 then + return false + end + end + return true +end + +function Six69.sniff(r: Bytes.Reader): number + return if validHeader(r) then 0.6 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Six69.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local budget = { left = opts and opts.maxBytes or 2 ^ 28 } + if not validHeader(r) then + return nil, Err.new(if r:size() < 497 then Err.TRUNCATED else Err.CORRUPT, "not a 669 module") + end + local extended = r:peek(2) == "JN" + r:skip(2) + local message = r:string(108) + local nsmp, npat, restart = r:u8(), r:u8(), r:u8() + local orders, tempos, breaks = {}, {}, {} + for i = 1, 128 do + orders[i] = r:u8() + end + for i = 1, 128 do + tempos[i] = r:u8() + end + for i = 1, 128 do + breaks[i] = r:u8() + end + if not r:need(nsmp * 25 + npat * 1536) then + return nil, r.err + end + local m = Tracker.newModule("669", 8, "s3m") + m.title = (string.gsub(string.sub(message, 1, 36), "[%z ]+$", "")) + m.meta.message = message + m.speed, m.tempo = 4, 78 + m.linear = false + m.instrumentMode = false + m.flags.periods, m.flags.hzSlide, m.flags.hzTonePorta = "hz", 20, 0.5 + m.flags.fastPortas, m.flags.autoTonePorta, m.flags.autoReset = true, true, true + for i = 1, 8 do + m.channelPan[i] = if i % 2 == 0 then 0xD0 else 0x30 + end + local lengths: { number } = {} + for i = 1, nsmp do + local s = Tracker.newSample(r:fixed(13)) + local len, ls, le = r:u32le(), r:u32le(), r:u32le() + if len >= 0x4000000 then + return nil, Err.new(Err.CORRUPT, "sample " .. i .. " too long") + end + s.c5speed = 8363 + if not (le > len and ls == 0) and le ~= 0 then + s.loopStart, s.loopEnd, s.loopType = ls, math.min(le, len), 1 + end + lengths[i] = len + m.samples[i] = s + end + for i = 1, 128 do + m.order[i] = orders[i] + end + while #m.order > 0 and m.order[#m.order] == 255 do + table.remove(m.order) + end + if orders[restart + 1] < npat then + m.restart = restart + end + -- patterns: 64 rows x 8 channels x 3 bytes (note / instrument, instrument / volume, effect / parameter) + local buf = r.buf + for p = 0, npat - 1 do + local pat = Tracker.newPattern(64, 8) + m.patterns[p + 1] = pat + local d = pat.data + local effect = table.create(8, 0xFF) -- the last effect per channel (balance slides repeat) + for row = 0, 63 do + for ch = 0, 7 do + local o = r.pos + (row * 8 + ch) * 3 + local ni, iv, ep = buffer.readu8(buf, o), buffer.readu8(buf, o + 1), buffer.readu8(buf, o + 2) + local q = (row * 8 + ch) * 5 + local hasNote = ni < 0xFE + if hasNote then + buffer.writeu8(d, q, ni // 4 + 37) + buffer.writeu8(d, q + 1, (ni % 4) * 16 + iv // 16 + 1) + effect[ch + 1] = 0xFF + end + if ni <= 0xFE then + buffer.writeu8(d, q + 2, ((iv % 16) * 64 + 8) // 15 + 1) + end + if ep ~= 0xFF then + effect[ch + 1] = ep + end + local e = effect[ch + 1] + if e ~= 0xFF then + local cmd, param = e // 16, e % 16 + local name = EFFECTS[cmd + 1] + if cmd == 4 then + param = param * 17 -- vibrato: speed = depth + elseif cmd == 6 then + param = if param == 0 then 0x4F elseif param == 1 then 0xF4 else -1 + elseif cmd == 7 and not (hasNote and extended) then + name = nil + end + if name ~= "panslide" then + effect[ch + 1] = 0xFF + end + if name and param >= 0 then + buffer.writeu8(d, q + 3, IT[name]) + buffer.writeu8(d, q + 4, param) + end + end + end + end + r:skip(1536) + if breaks[p + 1] < 63 then + Load.writeEffect(m, p, breaks[p + 1], IT["break"], 0, "next") + end + Load.writeEffect(m, p, 0, IT.speed, tempos[p + 1], "next") + end + -- sample data: unsigned 8-bit + local pos = r.pos + for i = 1, nsmp do + local s = m.samples[i] + local ok, err = Load.readSample(buf, pos, lengths[i], { bits = 8, signed = false, limit = r.limit }, s, budget) + if not ok then + return nil, err + end + pos += lengths[i] + end + m.meta.source = { format = "669", tracker = if extended then "UNIS 669" else "Composer 669" } + local ok, verr = Tracker.validate(m) + if not ok then + return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module") + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Six69.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local m, err = Six69.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return Six69 +end +__FILES["music/ahx"] = function() + +-- music/ahx: AHX (Abyss' Highest eXperience) 4-channel Amiga synth modules, "THX\0" .. "THX\2", rendered through +-- codecs/audio/Hively (a port of HivelyTracker's hvl2wav, BSD-3-Clause; at 44.1 kHz, stereo 0, equal to hvl2wav). +-- Supports: tracks, positions with transposes, PList instruments, subsongs. Not supported: writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Hively = __include("codecs/audio/Hively") + +-- ------------------------------------------------------------------------------------------------ contract +local Ahx = { + name = "ahx", + category = "music", + extensions = { "ahx", "thx" }, + mime = { "audio/x-ahx" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Hively" }, + caps = { decode = true, encode = false, render = true, channels = { 4, 4 }, subsongs = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type RenderOptions = Hively.RenderOptions -- stereo 0..4 + +-- ------------------------------------------------------------------------------------------------ sniff +function Ahx.sniff(r: Bytes.Reader): number + local m = r:peek(4) + return if m and #m == 4 and string.sub(m, 1, 3) == "THX" and string.byte(m, 4) < 3 then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Ahx.decode(r: Bytes.Reader, _opts: any?): (Types.Module?, Err.Err?) + local tune, err = Hively.parse(r.buf, r.base, r.limit) + if not tune or tune.format ~= "ahx" then + return nil, err or Err.new(Err.CORRUPT, "not an AHX module") + end + return Hively.module(tune), nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Ahx.open(r: Bytes.Reader, opts: RenderOptions?): (Types.Decoder?, Err.Err?) + local song, err = Ahx.decode(r) + if not song then + return nil, err + end + return Hively.decoder((song :: any).tune, opts) +end + +return Ahx +end +__FILES["music/far"] = function() + +-- music/far: Farandole Composer modules (FAR, 16 channels), ported from OpenMPT's Load_far.cpp (BSD, +-- licenses/openmpt-LICENSE.txt). Plays as the "s3m" family with FAR's quirks (periods in Hz, a slide step of +-- 36318 / 1024 Hz, OpenMPT's fixed 80 BPM). Not supported: FAR's tempo effects (D / E), note offset (C), writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Tracker = __include("codecs/audio/Tracker") +local Load = __include("codecs/audio/Tracker/Load") + +-- ------------------------------------------------------------------------------------------------ contract +local Far = { + name = "far", + category = "music", + extensions = { "far" }, + mime = { "audio/x-far" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 16, 16 } }, +} + +type DecodeOptions = { + maxBytes: number?, -- f32 bytes of sample data in total, default 2^28 +} + +-- ------------------------------------------------------------------------------------------------ constants +local IT = Load.IT + +-- ------------------------------------------------------------------------------------------------ sniff +function Far.sniff(r: Bytes.Reader): number + if r:size() >= 98 and r:peek(4) == "FAR\xFE" and r:peek(3, 44) == "\r\n\x1A" and r:peekU8(47) + r:peekU8(48) * 256 >= 98 then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- effect byte -> S3M effect, parameter, volume byte (0 = none): OpenMPT's table +local function effect(e: number): (number, number, number) + local cmd, p = e // 16, e % 16 + if cmd == 1 then + return IT.portaup, 0xF0 + p, 0 + elseif cmd == 2 then + return IT.portadown, 0xF0 + p, 0 + elseif cmd == 3 then + return IT.toneporta, if p ~= 0 then 60 // p else 0, 0 + elseif cmd == 4 then + return IT.retrig, 6 // (1 + p) + 1, 0 + elseif cmd == 5 or cmd == 9 then + return IT.vibrato, p, 0 + elseif cmd == 6 then + return IT.vibrato, p * 8, 0 + elseif cmd == 7 then + return IT.volslide, p * 8, 0 + elseif cmd == 8 then + return IT.volslide, p, 0 + elseif cmd == 0xA then + return 0, 0, p * 4 + 4 + 1 -- volume portamento: a set volume + elseif cmd == 0xB then + return IT.s3mex, 0x80 + p, 0 + elseif cmd == 0xF then + return IT.speed, p, 0 + end + return 0, 0, 0 +end + +function Far.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local budget = { left = opts and opts.maxBytes or 2 ^ 28 } + if Far.sniff(r) == 0 then + return nil, Err.new(if r:size() < 98 then Err.TRUNCATED else Err.CORRUPT, "not a Farandole module") + end + r:skip(4) + local title = r:fixed(40) + r:skip(3) + local headerLength, version = r:u16le(), r:u8() + local onOff, pans = {}, {} + for i = 1, 16 do + onOff[i] = r:u8() + end + r:skip(9) + local speed = r:u8() + for i = 1, 16 do + pans[i] = r:u8() + end + r:skip(4) + local msgLen = r:u16le() + local message = r:string(msgLen) + local orders = {} + for i = 1, 256 do + orders[i] = r:u8() + end + local _npat, nord, restart = r:u8(), r:u8(), r:u8() + local sizes = {} + for i = 1, 256 do + sizes[i] = r:u16le() + end + if r.err then + return nil, r.err + end + local m = Tracker.newModule("far", 16, "s3m") + m.title = title + m.meta.message = message + m.speed, m.tempo = if speed > 0 then speed else 4, 80 + m.mixVolume = 32 -- OpenMPT's pre-amp for FAR + m.linear = false + m.instrumentMode = false + m.flags.periods, m.flags.hzSlide = "hz", 36318 / 1024 + m.flags.autoTonePorta = true + for i = 1, 16 do + m.channelMute[i] = onOff[i] == 0 + m.channelPan[i] = (pans[i] % 16) * 16 + 8 + end + for i = 1, nord do + m.order[i] = orders[i] + end + while #m.order > 0 and m.order[#m.order] == 255 do + table.remove(m.order) + end + m.restart = restart + -- patterns: (size - 2) / 64 rows of 16 channels x (note, instrument, volume, effect), after a break row byte + if not r:seek(headerLength) then + return nil, r.err + end + local last = -1 + for p = 0, 255 do + if sizes[p + 1] > 0 then + last = p + end + end + for p = 0, last do + local size = sizes[p + 1] + local rows = math.clamp((size - 2) // 64, 1, 1024) + local pat = Tracker.newPattern(if size > 0 then rows else 64, 16) + m.patterns[p + 1] = pat + if size > 0 then + local pr = r:slice(size) + if r.err then + return nil, r.err + end + local br = pr:u8() + pr:skip(1) + local d = pat.data + for row = 0, rows - 1 do + for ch = 0, 15 do + local note, ins, vol, e = pr:u8(), pr:u8(), pr:u8(), pr:u8() + if pr.err then + break + end + local q = (row * 16 + ch) * 5 + if note > 0 and note <= 72 then + buffer.writeu8(d, q, note + 36) + buffer.writeu8(d, q + 1, ins + 1) + end + if vol > 0 and vol <= 16 then + buffer.writeu8(d, q + 2, (vol - 1) * 64 // 15 + 1) + end + local fx, param, setVol = effect(e) + if setVol > 0 then + buffer.writeu8(d, q + 2, setVol) + end + buffer.writeu8(d, q + 3, fx) + buffer.writeu8(d, q + 4, param) + end + end + if br > 0 and br < rows - 2 then + Load.writeEffect(m, p, br + 1, IT["break"], 0, "next") + end + end + end + -- samples: a 64-bit map of the stored ones, each a 48-byte header + signed 8 / 16-bit data + local map = {} + for i = 1, 8 do + map[i] = r:u8() + end + r.err = nil + for i = 0, 63 do + if bit32.band(map[i // 8 + 1] or 0, bit32.lshift(1, i % 8)) ~= 0 then + local h = r:slice(48) + if r.err then + break + end + local s = Tracker.newSample(h:fixed(32)) + local len = h:u32le() + h:skip(1) + local vol = h:u8() + local ls, le = h:u32le(), h:u32le() + local typ, loop = h:u8(), h:u8() + local bits = if typ % 2 == 1 then 16 else 8 + local frames = if bits == 16 then len // 2 else len + if bits == 16 then + ls, le = ls // 2, le // 2 + end + s.c5speed = 8363 * 2 + s.volume = math.min(vol * 4, 64) + local ok, err = Load.readSample(r.buf, r.pos, frames, { bits = bits, signed = true, limit = r.limit }, s, budget) + if not ok then + return nil, err + end + r:skip(math.min(len, r:remaining())) + if bit32.band(loop, 8) ~= 0 and le > ls then + s.loopStart, s.loopEnd, s.loopType = ls, math.min(le, s.length), 1 + end + for k = #m.samples + 1, i do + m.samples[k] = Tracker.newSample() + end + m.samples[i + 1] = s + end + end + m.meta.source = { format = "far", version = version } + local ok, verr = Tracker.validate(m) + if not ok then + return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module") + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Far.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local m, err = Far.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return Far +end +__FILES["music/hmp"] = function() + +-- music/hmp: HMI SOS music: HMP ("HMIMIDIP", "HMIMIDIP013195") and HMI ("HMI-MIDISONG061595"), from the layout +-- notes (wildmidi only as a test reference). Decodes to a Types.Midi (format 1, a track per chunk; the tick rate at +-- HMP 0x38 / HMI byte 212, as division 60). Not supported: writing, HMP branch tables. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Render = __include("codecs/audio/MidiRender") + +-- ------------------------------------------------------------------------------------------------ contract +local Hmp = { + name = "hmp", + category = "music", + extensions = { "hmp", "hmi" }, + mime = { "audio/x-hmp" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/MidiRender" }, + caps = { decode = true, encode = false, render = true, hmi = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + maxEvents: number?, -- default 2^24 +} + +-- ------------------------------------------------------------------------------------------------ sniff +local HMI_MAGIC = "HMI-MIDISONG061595" + +function Hmp.sniff(r: Bytes.Reader): number + return if r:peek(8) == "HMIMIDIP" or r:peek(18) == HMI_MAGIC then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local readu8, readu32 = buffer.readu8, buffer.readu32 +local DATA = { [8] = 2, [9] = 2, [10] = 2, [11] = 2, [12] = 1, [13] = 1, [14] = 2 } +local TYPES = { [8] = "noteOff", [9] = "noteOn", [10] = "aftertouch", [11] = "controller", [12] = "program", [13] = "channelPressure", [14] = "pitchBend" } + +-- HMP deltas: 7-bit groups, least significant first, the last byte has bit 7 set; HMI: the MIDI encoding +local function delta(b: buffer, p: number, e: number, hmp: boolean): (number?, number) + local v, shift = 0, 1 + for _ = 1, 5 do + if p >= e then + return nil, p + end + local c = readu8(b, p) + p += 1 + if hmp then + v += (c % 128) * shift + shift *= 128 + if c >= 128 then + return v, p + end + else + v = v * 128 + c % 128 + if c < 128 then + return v, p + end + end + end + return nil, p +end + +local function bytes(b: buffer, p: number, n: number): { number } + local t: { number } = table.create(n) :: { number } + for i = 1, n do + t[i] = readu8(b, p + i - 1) + end + return t +end + +type Ctx = { loops: number, budget: number } + +local function track(b: buffer, p: number, e: number, hmp: boolean, ctx: Ctx): ({ Types.MidiEvent }?, string?) + local list: { Types.MidiEvent }, offs: { Render.PendingOff } = {}, {} + local tick, running = 0, 0 + while p < e do + local d, q = delta(b, p, e, hmp) + if not d then + break + end + tick += d + p = q + if p >= e then + return nil, "truncated event" + end + local st = readu8(b, p) + if st == 0xFE and not hmp then + -- HMI-only events: FE 10 (with a length at +4), FE 15, others 4 bytes + local n = 4 + if p + 1 < e and readu8(b, p + 1) == 0x10 then + n = if p + 4 < e then readu8(b, p + 4) + 9 else e - p + 1 + elseif p + 1 < e and readu8(b, p + 1) == 0x15 then + n = 8 + end + if p + n > e then + return nil, "truncated FE event" + end + p += n + elseif st == 0xFF then + local kind = if p + 1 < e then readu8(b, p + 1) else -1 + local n, r = delta(b, p + 2, e, false) + if kind < 0 or not n or r + n > e then + return nil, "truncated meta event" + end + if kind == 0x2F then + break + end + table.insert(list, { tick = tick, type = "meta", meta = kind, data = bytes(b, r, n) }) + p = r + n + elseif st == 0xF0 or st == 0xF7 then + local n, r = delta(b, p + 1, e, false) + if not n or r + n > e then + return nil, "truncated sysex" + end + table.insert(list, { tick = tick, type = if st == 0xF0 then "sysex" else "escape", data = bytes(b, r, n) }) + p = r + n + running = 0 + else + if st >= 0x80 then + if st >= 0xF0 then + return nil, string.format("unexpected status byte 0x%02X", st) + end + running = st + p += 1 + elseif running == 0 then + return nil, "running status without a status byte" + end + local hi, ch = running // 16, running % 16 + local n = DATA[hi] + if p + n > e then + return nil, "truncated event" + end + local data = bytes(b, p, n) + p += n + if hmp and hi == 11 and (data[1] == 110 or data[1] == 111) and data[2] > 127 then + ctx.loops += 1 + else + for i = 1, n do + data[i] %= 128 + end + table.insert(list, { tick = tick, type = TYPES[hi], channel = ch, data = data }) + end + if hi == 9 and not hmp then + local dur, r = delta(b, p, e, false) + if not dur then + return nil, "truncated note duration" + end + p = r + table.insert(offs, { tick = tick + dur, onTick = tick, ev = { tick = tick + dur, type = "noteOff", channel = ch, data = { data[1], 64 } } }) + end + end + ctx.budget -= 1 + if ctx.budget < 0 then + return nil, "limit: too many events" + end + end + -- (notes still sounding at the end of an HMI track keep their full duration, as wildmidi plays them) + local out = Render.merge(list, offs) + table.insert(out, { tick = math.max(tick, if #out > 0 then out[#out].tick else 0), type = "meta", meta = 0x2F, data = {} }) + return out, nil +end + +local function hmpTracks(b: buffer, base: number, limit: number): ({ { number } }?, string?, string?) + local new = buffer.readstring(b, base + 8, 6) == "013195" + local n = readu32(b, base + 0x30) + local p = base + (if new then 0x388 else 0x308) + if n == 0 or n > 256 then + return nil, string.format("bad track count %d", n), nil + end + local ranges = {} + for _ = 1, n do + if p + 12 > limit then + return nil, "truncated chunk header", "truncated" + end + local len = readu32(b, p + 4) + if len < 12 or p + len > limit then + return nil, "truncated chunk", "truncated" + end + table.insert(ranges, { p + 12, p + len }) + p += len + end + return ranges, nil, nil +end + +local function hmiTracks(b: buffer, base: number, limit: number): ({ { number } }?, string?, string?) + local n = readu8(b, base + 228) + if n == 0 then + return nil, "no tracks", nil + end + if base + 370 + n * 4 > limit then + return nil, "truncated track table", "truncated" + end + local ranges, heads = {}, {} + for i = 0, n - 1 do + local at = base + readu32(b, base + 370 + i * 4) + if at < base or at + 0x5B > limit or buffer.readstring(b, at, 13) ~= "HMI-MIDITRACK" then + return nil, string.format("bad track %d header", i), nil + end + local start = at + readu32(b, at + 0x57) + if start >= limit then + return nil, "truncated track", "truncated" + end + table.insert(ranges, { start, limit }) + table.insert(heads, at) + end + -- a track ends where the next track header starts (or at the end of the file) + for _, rg in ranges do + for _, h in heads do + if h >= rg[1] and h < rg[2] then + rg[2] = h + end + end + end + return ranges, nil, nil +end + +function Hmp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Midi?, Err.Err?) + local b, base, limit = r.buf, r.base, r.limit + local hmi = r:peek(18) == HMI_MAGIC + if not hmi and r:peek(8) ~= "HMIMIDIP" then + return nil, Err.new(Err.CORRUPT, "not an HMP / HMI file") + end + if limit - base < (if hmi then 371 else 0x40) then + return nil, Err.new(Err.TRUNCATED, "truncated header") + end + local rate = if hmi then readu8(b, base + 212) else readu32(b, base + 0x38) + if rate == 0 or rate > 100000 then + return nil, Err.new(Err.CORRUPT, "bad tick rate " .. rate) + end + local ranges, msg, kind = (if hmi then hmiTracks else hmpTracks)(b, base, limit) + if not ranges then + return nil, Err.from(msg :: string, nil, kind) + end + local ctx: Ctx = { loops = 0, budget = (opts and opts.maxEvents) or 2 ^ 24 } + local midi = Types.Midi.new(60) + for i, rg in ranges do + local evs, err = track(b, rg[1], rg[2], not hmi, ctx) + if not evs then + return nil, Err.from(err :: string, rg[1]) + end + if i == 1 then + local us = math.min(60000000 // rate, 0xFFFFFF) + table.insert(evs, 1, { tick = 0, type = "meta", meta = 0x51, data = { us // 65536, (us // 256) % 256, us % 256 } }) + end + midi.tracks[i] = { events = evs } + end + local version = if hmi then "hmi" elseif buffer.readstring(b, base + 8, 6) == "013195" then "013195" else "hmp" + Render.attach(midi, { format = if hmi then "hmi" else "hmp", version = version, rate = rate, loops = ctx.loops }) + return midi, nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Hmp.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local midi, err = Hmp.decode(r, opts) + if not midi then + return nil, err + end + return Render.decoder(midi, opts) +end + +return Hmp +end +__FILES["music/hvl"] = function() + +-- music/hvl: HivelyTracker modules, "HVL\0" / "HVL\1" (AHX extended: 4..16 channels, two effect columns, ring +-- modulation, panning, stereo separation), rendered through codecs/audio/Hively (a port of hvl2wav, BSD-3-Clause; at +-- 44.1 kHz equal to hvl2wav). Not supported: writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Hively = __include("codecs/audio/Hively") + +-- ------------------------------------------------------------------------------------------------ contract +local Hvl = { + name = "hvl", + category = "music", + extensions = { "hvl" }, + mime = { "audio/x-hvl" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Hively" }, + caps = { decode = true, encode = false, render = true, channels = { 4, 16 }, subsongs = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type RenderOptions = Hively.RenderOptions -- stereo comes from the file + +-- ------------------------------------------------------------------------------------------------ sniff +function Hvl.sniff(r: Bytes.Reader): number + local m = r:peek(4) + return if m and #m == 4 and string.sub(m, 1, 3) == "HVL" and string.byte(m, 4) <= 1 then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Hvl.decode(r: Bytes.Reader, _opts: any?): (Types.Module?, Err.Err?) + local tune, err = Hively.parse(r.buf, r.base, r.limit) + if not tune or tune.format ~= "hvl" then + return nil, err or Err.new(Err.CORRUPT, "not an HVL module") + end + return Hively.module(tune), nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Hvl.open(r: Bytes.Reader, opts: RenderOptions?): (Types.Decoder?, Err.Err?) + local song, err = Hvl.decode(r) + if not song then + return nil, err + end + return Hively.decoder((song :: any).tune, opts) +end + +return Hvl +end +__FILES["music/it"] = function() + +-- music/it: Impulse Tracker modules (IMPM, ITTECH.TXT), played through codecs/audio/Tracker. Supports: 64 channels, +-- instrument / sample mode, old and new instrument headers, envelopes, NNAs, resonant filters (default Zxx macros), +-- IT 2.14 / 2.15 compressed samples, the message. Not supported: embedded MIDI macros, OpenMPT extensions, writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Tracker = __include("codecs/audio/Tracker") +local Itsex = __include("music/it/Itsex") + +-- ------------------------------------------------------------------------------------------------ contract +local It = { + name = "it", + category = "music", + extensions = { "it" }, + mime = { "audio/it", "audio/x-it" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 64 }, compressedSamples = true }, +} + +type DecodeOptions = { + maxBytes: number?, -- f32 bytes of sample data in total, default 2^28 +} + +-- ------------------------------------------------------------------------------------------------ sniff +function It.sniff(r: Bytes.Reader): number + return if r:peek(4) == "IMPM" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- the 82-byte envelope of a new-format instrument +local function readEnvelope(r: Bytes.Reader, kind: string): any + local flags, n = r:u8(), r:u8() + local lb, le, sb, se = r:u8(), r:u8(), r:u8(), r:u8() + local e = Tracker.newEnvelope() + n = math.min(n, 25) + for i = 1, 25 do + local y, x = r:i8(), r:u16le() + if i <= n then + e.ticks[i] = x + e.values[i] = if kind == "vol" then math.clamp(y, 0, 64) else math.clamp(y, -32, 32) + end + end + r:skip(1) + e.enabled = bit32.band(flags, 1) ~= 0 and n > 0 + e.loop = bit32.band(flags, 2) ~= 0 + e.sustain = bit32.band(flags, 4) ~= 0 + e.carry = bit32.band(flags, 8) ~= 0 + e.filter = kind == "pitch" and bit32.band(flags, 128) ~= 0 + e.loopStart, e.loopEnd = lb + 1, le + 1 + e.susStart, e.susEnd = sb + 1, se + 1 + return e +end + +local function readInstrument(r: Bytes.Reader, old: boolean): (any?, string?) + if r:string(4) ~= "IMPI" then + return nil, "bad instrument signature" + end + local ins = Tracker.newInstrument() + r:skip(13) + if old then + -- the pre-2.0 layout: volume envelope only (flags, loop and sustain points), fadeout 0..64 of 512 + local flg, vls, vle, sls, sle = r:u8(), r:u8(), r:u8(), r:u8(), r:u8() + r:skip(2) + ins.fadeout = r:u16le() * 2 + ins.nna = r:u8() + ins.dct = if r:u8() ~= 0 then 1 else 0 + r:skip(4) + ins.name = r:fixed(26) + r:skip(6) + for n = 1, 120 do + local note, smp = r:u8(), r:u8() + ins.noteMap[n] = math.clamp(note + 1, 1, 120) + ins.sampleMap[n] = smp + end + r:skip(200) + local e = Tracker.newEnvelope() + for i = 1, 25 do + local t, v = r:u8(), r:u8() + if t == 0xFF or (i > 1 and t <= (e.ticks[#e.ticks] or -1)) then + r:skip((25 - i) * 2) + break + end + table.insert(e.ticks, t) + table.insert(e.values, math.min(v, 64)) + end + e.enabled = bit32.band(flg, 1) ~= 0 and #e.ticks > 0 + e.loop = bit32.band(flg, 2) ~= 0 + e.sustain = bit32.band(flg, 4) ~= 0 + e.loopStart, e.loopEnd, e.susStart, e.susEnd = vls + 1, vle + 1, sls + 1, sle + 1 + ins.volEnv = e + return ins + end + ins.nna, ins.dct, ins.dca = r:u8() % 4, r:u8() % 4, r:u8() % 3 + ins.fadeout = math.min(r:u16le(), 1024) + ins.pps, ins.ppc = r:i8(), r:u8() + ins.globalVolume = math.min(r:u8(), 128) + local dfp = r:u8() + if dfp < 128 then + ins.pan = math.min(dfp, 64) * 4 + end + r:skip(2 + 2 + 1 + 1) + ins.name = r:fixed(26) + local ifc, ifr = r:u8(), r:u8() + if ifc >= 128 then + ins.cutoff = ifc - 128 + end + if ifr >= 128 then + ins.resonance = ifr - 128 + end + r:skip(4) + for n = 1, 120 do + local note, smp = r:u8(), r:u8() + ins.noteMap[n] = math.clamp(note + 1, 1, 120) + ins.sampleMap[n] = smp + end + ins.volEnv = readEnvelope(r, "vol") + ins.panEnv = readEnvelope(r, "pan") + ins.pitchEnv = readEnvelope(r, "pitch") + if r.err then + return nil, "instrument truncated" + end + return ins +end + +function It.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local maxBytes = opts and opts.maxBytes or 2 ^ 28 + if r:peek(4) ~= "IMPM" then + return nil, Err.new(Err.CORRUPT, "no IMPM signature") + end + r:skip(4) + local title = r:fixed(26) + r:skip(2) + local ordnum, insnum, smpnum, patnum = r:u16le(), r:u16le(), r:u16le(), r:u16le() + local cwt, cmwt, flags, special = r:u16le(), r:u16le(), r:u16le(), r:u16le() + local gv, mv, speed, tempo, _sep, _pwd = r:u8(), r:u8(), r:u8(), r:u8(), r:u8(), r:u8() + local msgLen, msgOff = r:u16le(), r:u32le() + r:skip(4) + local chnPan, chnVol = {}, {} + for i = 1, 64 do + chnPan[i] = r:u8() + end + for i = 1, 64 do + chnVol[i] = r:u8() + end + if r.err then + return nil, r.err + end + if ordnum > 256 or insnum > 255 or smpnum > 255 or patnum > 255 then + return nil, Err.new(Err.CORRUPT, "bad header counts") + end + local orders = {} + for i = 1, ordnum do + orders[i] = r:u8() + end + local insOff, smpOff, patOff = {}, {}, {} + for i = 1, insnum do + insOff[i] = r:u32le() + end + for i = 1, smpnum do + smpOff[i] = r:u32le() + end + for i = 1, patnum do + patOff[i] = r:u32le() + end + if r.err then + return nil, r.err + end + local nch = 1 + local packed: { Bytes.Reader? } = {} + local rowsOf: { number } = {} + for p = 1, patnum do + if patOff[p] > 0 then + local pr = r:sub(patOff[p]) + local len, rows = pr:u16le(), pr:u16le() + pr:skip(4) + if pr.err or rows < 1 or rows > 1024 then + return nil, Err.new(Err.CORRUPT, "bad pattern " .. (p - 1), r.base + patOff[p]) + end + local data = pr:slice(len) + packed[p], rowsOf[p] = data, rows + local scan = data:sub(0) + local seen: { [number]: number } = {} + while not scan:eof() do + local cv = scan:u8() + if cv == 0 then + continue + end + local ch = (cv - 1) % 64 + nch = math.max(nch, ch + 1) + local mask = 0 + if cv >= 128 then + mask = scan:u8() + seen[ch] = mask + else + mask = seen[ch] or 0 + end + if bit32.band(mask, 1) ~= 0 then + scan:skip(1) + end + if bit32.band(mask, 2) ~= 0 then + scan:skip(1) + end + if bit32.band(mask, 4) ~= 0 then + scan:skip(1) + end + if bit32.band(mask, 8) ~= 0 then + scan:skip(2) + end + end + else + rowsOf[p] = 64 + end + end + local m = Tracker.newModule("it", nch) + m.title = title + m.speed = if speed > 0 then speed else 6 + m.tempo = if tempo >= 31 then tempo else 125 + m.globalVolume = math.min(gv, 128) + m.mixVolume = math.min(mv, 128) + m.linear = bit32.band(flags, 8) ~= 0 + m.instrumentMode = bit32.band(flags, 4) ~= 0 + m.flags.oldEffects = bit32.band(flags, 16) ~= 0 + m.flags.compatGxx = bit32.band(flags, 32) ~= 0 + local stereo = bit32.band(flags, 1) ~= 0 + for i = 1, nch do + local p = chnPan[i] + if p >= 128 then + m.channelMute[i] = true + p -= 128 + end + if not stereo then + m.channelPan[i] = 128 + elseif p == 100 then + m.channelPan[i] = 512 + else + m.channelPan[i] = math.min(p, 64) * 4 + end + m.channelVolume[i] = math.min(chnVol[i], 64) + end + for i = 1, ordnum do + if orders[i] == 255 then + break + end + table.insert(m.order, orders[i]) + end + m.meta.source = { format = "it", tracker = cwt, compatible = cmwt } + if bit32.band(special, 1) ~= 0 and msgLen > 0 then + local mr = r:sub(msgOff, msgLen) + m.meta.message = string.gsub(mr:fixed(msgLen), "\r", "\n") + end + for i = 1, insnum do + local ins, ierr = readInstrument(r:sub(insOff[i]), cmwt < 0x200) + if not ins then + return nil, Err.new(Err.CORRUPT, "instrument " .. i .. ": " .. tostring(ierr), r.base + insOff[i]) + end + m.instruments[i] = ins + end + local total = 0 + for i = 1, smpnum do + local h = r:sub(smpOff[i], 80) + if h:string(4) ~= "IMPS" then + return nil, Err.new(Err.CORRUPT, "sample " .. i .. ": bad signature", r.base + smpOff[i]) + end + h:skip(13) + local s = Tracker.newSample() + m.samples[i] = s + local gvl, flg, vol = h:u8(), h:u8(), h:u8() + s.name = h:fixed(26) + local cvt, dfp = h:u8(), h:u8() + local len, lb, le, c5, slb, sle, ptr = h:u32le(), h:u32le(), h:u32le(), h:u32le(), h:u32le(), h:u32le(), h:u32le() + local vis, vid, vir, vit = h:u8(), h:u8(), h:u8(), h:u8() + if h.err then + return nil, Err.new(Err.TRUNCATED, "sample header " .. i) + end + s.globalVolume = math.min(gvl, 64) + s.volume = math.min(vol, 64) + if dfp >= 128 then + s.pan = math.min(dfp - 128, 64) * 4 + end + s.c5speed = if c5 > 0 then c5 else 8363 + s.vibRate, s.vibDepth, s.vibSweep, s.vibType = vis, vid, vir, vit % 4 + local bits = if bit32.band(flg, 2) ~= 0 then 16 else 8 + local nchs = if bit32.band(flg, 4) ~= 0 then 2 else 1 + s.bits = bits + if bit32.band(flg, 1) ~= 0 and len > 0 then + len = math.min(len, 2 ^ 26) + total += len * nchs * 4 + if total > maxBytes then + return nil, Err.new(Err.LIMIT, "sample data over the maxBytes limit") + end + local data: buffer? = nil + if bit32.band(flg, 8) ~= 0 then + -- compressed: each channel separately + local it215 = bit32.band(cvt, 4) ~= 0 + local p = r.base + ptr + local parts = {} + for c = 1, nchs do + local d, used = Itsex.decompress(r.buf, p, r.limit, len, bits, it215) + if not d then + return nil, Err.new(Err.CORRUPT, "sample " .. i .. ": " .. tostring(used)) + end + parts[c] = d + p += used :: number + end + if nchs == 1 then + data = parts[1] + else + local inter = buffer.create(len * 8) + for f = 0, len - 1 do + buffer.writef32(inter, f * 8, buffer.readf32(parts[1], f * 4)) + buffer.writef32(inter, f * 8 + 4, buffer.readf32(parts[2], f * 4)) + end + data = inter + end + else + local bps = bits // 8 + local avail = math.max(0, r:size() - ptr) // (bps * nchs) + len = math.min(len, avail) + data = Tracker.Pcm.decode(r.buf, r.base + ptr, len, { + bits = bits, + signed = bit32.band(cvt, 1) ~= 0, + bigEndian = bit32.band(cvt, 2) ~= 0, + delta = bit32.band(cvt, 4) ~= 0, + channels = nchs, + planar = true, + }) + end + if data then + s.data, s.length, s.channels = data, len, nchs + if bit32.band(flg, 16) ~= 0 then + s.loopStart, s.loopEnd, s.loopType = lb, math.min(le, len), if bit32.band(flg, 64) ~= 0 then 2 else 1 + end + if bit32.band(flg, 32) ~= 0 then + s.susStart, s.susEnd, s.susType = slb, math.min(sle, len), if bit32.band(flg, 128) ~= 0 then 2 else 1 + end + end + end + end + for p = 1, patnum do + local pat = Tracker.newPattern(rowsOf[p], nch) + m.patterns[p] = pat + local pr = packed[p] + if pr then + local d = pat.data + local lastMask, lastNote, lastIns, lastVol, lastFx, lastParam = {}, {}, {}, {}, {}, {} + local row = 0 + while row < pat.rows and not pr:eof() do + local cv = pr:u8() + if cv == 0 then + row += 1 + continue + end + local ch = (cv - 1) % 64 + local mask = if cv >= 128 then pr:u8() else (lastMask[ch] or 0) + lastMask[ch] = mask + local note, ins, vol, fx, param = 0, 0, 0, 0, 0 + if bit32.band(mask, 1) ~= 0 then + local n = pr:u8() + -- 255 note off, 254 note cut, 246 note fade (as IT and OpenMPT store "~~~"); other values: nothing + note = if n < 120 then n + 1 elseif n == 255 then 255 elseif n == 254 then 254 elseif n == 246 then 253 else 0 + lastNote[ch] = note + elseif bit32.band(mask, 16) ~= 0 then + note = lastNote[ch] or 0 + end + if bit32.band(mask, 2) ~= 0 then + ins = pr:u8() + lastIns[ch] = ins + elseif bit32.band(mask, 32) ~= 0 then + ins = lastIns[ch] or 0 + end + if bit32.band(mask, 4) ~= 0 then + vol = math.min(pr:u8(), 212) + 1 + lastVol[ch] = vol + elseif bit32.band(mask, 64) ~= 0 then + vol = lastVol[ch] or 0 + end + if bit32.band(mask, 8) ~= 0 then + fx, param = pr:u8(), pr:u8() + if fx > 26 then + fx, param = 0, 0 + end + lastFx[ch], lastParam[ch] = fx, param + elseif bit32.band(mask, 128) ~= 0 then + fx, param = lastFx[ch] or 0, lastParam[ch] or 0 + end + if ch < nch then + local o = (row * nch + ch) * 5 + buffer.writeu8(d, o, note) + buffer.writeu8(d, o + 1, ins) + buffer.writeu8(d, o + 2, vol) + buffer.writeu8(d, o + 3, fx) + buffer.writeu8(d, o + 4, param) + end + end + end + end + local ok, verr = Tracker.validate(m) + if not ok then + return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module") + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ open +function It.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local m, err = It.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return It +end +__FILES["music/it/Itsex"] = @native function() + + +-- music/it/Itsex: IT 2.14 / 2.15 (double-delta) sample decompression, from ITTECH.TXT: 0x8000-byte output blocks, each +-- a u16 length then an LSB-first bit stream of deltas with three width-change methods. +local readu8, readu16, writef32 = buffer.readu8, buffer.readu16, buffer.writef32 + +local Itsex = {} + +@native function Itsex.decompress(buf: buffer, off: number, limit: number, frames: number, bits: number, it215: boolean): (buffer?, number | string) + local out = buffer.create(frames * 4) + local blockLen = if bits == 16 then 0x4000 else 0x8000 + local topWidth = if bits == 16 then 17 else 9 + local fetchA = if bits == 16 then 4 else 3 + local lowerB = if bits == 16 then -8 else -4 + local upperB = if bits == 16 then 7 else 3 + local scale = if bits == 16 then 1 / 32768 else 1 / 128 + local wrap = if bits == 16 then 65536 else 256 + local half = wrap // 2 + local p = off + local done = 0 + while done < frames do + if p + 2 > limit then + return nil, "compressed sample truncated" + end + local clen = readu16(buf, p) + p += 2 + local bstart = p + local bend = p + clen + if bend > limit then + return nil, "compressed block runs past the end" + end + p = bend + local bytePos = bstart + local bitBuf = 0 + local bitCount = 0 + @native local function readBits(n: number): number + while bitCount < n do + if bytePos >= bend then + return -1 + end + bitBuf += readu8(buf, bytePos) * 2 ^ bitCount + bytePos += 1 + bitCount += 8 + end + local v = bitBuf % 2 ^ n + bitBuf = (bitBuf - v) / 2 ^ n + bitCount -= n + return v + end + local count = math.min(blockLen, frames - done) + local width = topWidth + local d1, d2 = 0, 0 + local i = 0 + while i < count do + if width < 1 or width > topWidth then + return nil, "bad bit width" + end + local v = readBits(width) + if v < 0 then + return nil, "compressed block ends early" + end + if width < 7 then + -- method A: a marker value, then the new width in fetchA bits + if v == 2 ^ (width - 1) then + local nw = readBits(fetchA) + if nw < 0 then + return nil, "compressed block ends early" + end + nw += 1 + width = if nw < width then nw else nw + 1 + continue + end + elseif width < topWidth then + -- method B: values just below the top of the range encode the new width + local border = bit32.rshift(if bits == 16 then 0xFFFF else 0xFF, topWidth - width) + lowerB + if v > border and v <= border + (upperB - lowerB + 1) then + local nw = v - border + width = if nw < width then nw else nw + 1 + continue + end + else + -- method C: the top bit flags a width change + if v >= wrap then + width = (v + 1) % 256 + continue + end + end + local x = v + if width < topWidth then + local shift = 2 ^ width + if x >= shift / 2 then + x -= shift + end + else + x = v % wrap + if x >= half then + x -= wrap + end + end + d1 = (d1 + x + half) % wrap - half + local s = d1 + if it215 then + d2 = (d2 + d1 + half) % wrap - half + s = d2 + end + writef32(out, (done + i) * 4, s * scale) + i += 1 + end + done += count + end + return out, p - off +end + +return Itsex +end +__FILES["music/med"] = function() + +-- music/med: MED / OctaMED modules (MMD0..MMD3), ported from OpenMPT's Load_med.cpp (BSD, +-- licenses/openmpt-LICENSE.txt); the first song plays as the "xm" family with Amiga periods. Supports: 1..64 tracks, +-- play sequences, hold / decay, IFF multi-octave samples. Not supported: synth / MIDI instruments, echo, writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Tracker = __include("codecs/audio/Tracker") +local Load = __include("codecs/audio/Tracker/Load") + +-- ------------------------------------------------------------------------------------------------ contract +local Med = { + name = "med", + category = "music", + extensions = { "med", "mmd0", "mmd1", "mmd2", "mmd3", "omed" }, + mime = { "audio/x-med" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 64 } }, +} + +type DecodeOptions = { + maxBytes: number?, -- f32 bytes of sample data in total, default 2^28 +} + +-- ------------------------------------------------------------------------------------------------ constants +-- IFF multi-octave samples: the sample (0 = the lowest octave stored first... as OpenMPT orders them) and the +-- transpose used per octave of the keyboard, by the number of octaves stored (2..7) +local OCT_SAMPLE = { + { 1, 1, 0, 0, 0, 0, 0, 0 }, + { 2, 2, 1, 1, 0, 0, 0, 0 }, + { 3, 3, 2, 2, 1, 0, 0, 0 }, + { 4, 3, 2, 1, 1, 0, 0, 0 }, + { 5, 4, 3, 2, 1, 0, 0, 0 }, + { 6, 5, 4, 3, 2, 1, 0, 0 }, +} +local OCT_TRANSPOSE = { + { 0, 0, -12, -12, -24, -36, -48, -60 }, + { 0, 0, -12, -12, -24, -36, -48, -60 }, + { 0, 0, -12, -12, -24, -36, -48, -60 }, + { 12, 0, -12, -24, -24, -36, -48, -60 }, + { 12, 0, -12, -24, -36, -48, -48, -60 }, + { 12, 0, -12, -24, -36, -48, -60, -72 }, +} +local SAMPLES_PER_TYPE = { [0] = 1, 5, 3, 2, 4, 6, 7 } +local TEMPO_8CH = { 179, 164, 152, 141, 131, 123, 116, 110, 104, 99 } + +-- ------------------------------------------------------------------------------------------------ sniff +local function validHeader(r: Bytes.Reader): boolean + if r:size() < 52 or r:peek(3) ~= "MMD" then + return false + end + local v = r:peekU8(3) + if v < 0x30 or v > 0x33 then + return false + end + local h = r:sub(8, 44) + local songOff = h:u32be() + h:skip(4) + local blockOff = h:u32be() + h:skip(4) + local smpOff = h:u32be() + return songOff >= 52 and songOff + 63 * 8 + 284 <= r:size() and blockOff >= 52 and (smpOff == 0 or smpOff >= 52) +end + +function Med.sniff(r: Bytes.Reader): number + return if validHeader(r) then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +type Ctx = { transpose: number, is8Ch: boolean, softMix: boolean, bpm: boolean, rowsPerBeat: number, volHex: boolean, vol7bit: boolean } + +-- OpenMPT's MMDTempoToBPM (SPD / 8-channel / BPM modes) +local function tempoToBpm(tempo: number, ctx: Ctx): number + if ctx.bpm and not ctx.is8Ch then + return if tempo < 7 then 111.5 else tempo * ctx.rowsPerBeat / 4 + end + if ctx.is8Ch and tempo > 0 then + return TEMPO_8CH[math.min(tempo, 10)] + elseif not ctx.softMix and tempo > 0 and tempo <= 10 then + return 6 * 1773447 / 14500 / tempo -- SoundTracker-compatible tempo + elseif ctx.softMix and tempo < 8 then + return 157.86 + end + return tempo / 0.264 +end + +-- MED command -> MOD / XM effect, param, note-cut flag: OpenMPT's ConvertMEDEffect +local function effect(cmd: number, p: number, ctx: Ctx): (number, number, boolean) + local lo = math.min(p, 15) + if cmd == 1 or cmd == 2 then + return if p > 0 then cmd else 0, p, false + elseif cmd == 4 then + return 4, p - p % 16 + math.min((p % 16) * 2, 15), false -- twice as deep as ProTracker's + elseif cmd == 5 then + return if p > 0 then 5 else 3, p, false + elseif cmd == 6 then + return if p > 0 then 6 else 4, p, false + elseif cmd == 8 or cmd == 0xE or cmd == 0x10 or cmd == 0x1C or cmd == 0x20 or cmd == 0x29 then + return 0, 0, false -- hold / decay (instrument data), synth jump, MIDI, reverse, relative offset + elseif cmd == 9 then + return if p > 0 and p <= 0x20 then 0xF else 0, math.min(p, 0x1F), false + elseif cmd == 0xC then + if not ctx.volHex and p < 0x99 then + return 0xC, (p // 16) * 10 + p % 16, false + elseif ctx.volHex and not ctx.vol7bit then + return 0xC, math.min(p % 128, 64), false + elseif ctx.volHex then + return 0xC, (p % 128 + 1) // 2, false + end + return 0, 0, false + elseif cmd == 0xD then + return if p > 0 then 0xA else 0, p, false + elseif cmd == 0xF then + if p == 0 then + return 0xD, 0, false + elseif p <= 0xF0 then + local bpm = if p < 3 then 0x70 else math.floor(tempoToBpm(p, ctx) + 0.5) + if bpm > 255 then + local ext = Tracker.EXT.TEMPO_256 + math.min(bpm // 256, 3) - 1 -- tempos past 255 (EXT 0x47..0x49) + return ext, math.min(bpm - (ext - Tracker.EXT.TEMPO_256 + 1) * 256, 255), false + end + return 0xF, math.max(bpm, 0x20), false + elseif p == 0xF1 then + return 0xE, 0x93, false + elseif p == 0xF2 then + return 0xE, 0xD3, false + elseif p == 0xF3 then + return 0xE, 0x92, false + elseif p == 0xFF then + return 0, 0, true + end + return 0, 0, false + elseif cmd == 0x11 then + return 0xE, 0x10 + lo, false + elseif cmd == 0x12 then + return 0xE, 0x20 + lo, false + elseif cmd == 0x14 then + return 4, p, false -- ProTracker depth, faster + elseif cmd == 0x15 then + return 0xE, 0x50 + p % 16, false + elseif cmd == 0x16 then + return 0xE, 0x60 + lo, false + elseif cmd == 0x18 then + return 0xE, 0xC0 + lo, false + elseif cmd == 0x19 then + return 9, p, false + elseif cmd == 0x1A then + return 0xE, 0xA0 + lo, false + elseif cmd == 0x1B then + return 0xE, 0xB0 + lo, false + elseif cmd == 0x1D then + return 0xD, Load.bcd(p), false -- pattern break, the row in hex + elseif cmd == 0x1E then + return 0xE, 0xE0 + lo, false + elseif cmd == 0x1F then + if p >= 16 then + return 0xE, 0xD0 + p // 16, false + elseif p > 0 then + return 0xE, 0x90 + p, false + end + return 0, 0, false + elseif cmd == 0x2E then + if p <= 0x10 or p >= 0xF0 then + return 8, math.clamp((bit32.bxor(p, 0x80) - 0x70) * 8, 0, 255), false + end + return 0, 0, false + elseif cmd < 0x10 and (cmd > 0 or p > 0) then + return cmd, p, false -- the remaining ProTracker effects as they are (0, 3, 7, 8, A, B) + end + return 0, 0, false +end + +-- OpenMPT's octave wrapping +local function wrapNote(note: number, vol7bit: boolean): number + local n = note + 12 -- OpenMPT's numbering (ProTracker notes an octave up) + if n > 132 and not vol7bit then + n -= 108 + elseif n > 120 then + n -= (n - 109) - (n - 109) % 12 + end + return if n >= 13 then n - 12 else 0 +end + +local function readBlock(r: Bytes.Reader, off: number, version: number, ctx: Ctx, nch: number): (any?, boolean) + local br = r:sub(off) + local ntracks, nrows, info + if version < 1 then + ntracks, nrows, info = br:u8(), br:u8() + 1, 0 + else + ntracks, nrows, info = br:u16be(), br:u16be() + 1, br:u32be() + end + if br.err or nrows > 1024 then + return nil, false + end + local cmdExt: Bytes.Reader? = nil + if version >= 1 and info > 0 then + local ir = r:sub(info, 36) + ir:skip(16) + local ext = ir:u32be() + if not ir.err and ext > 0 then + local p = r:sub(ext, 4):u32be() + if p > 0 then + cmdExt = r:sub(p) + end + end + end + local lctx = table.clone(ctx) + lctx.vol7bit = cmdExt ~= nil + local pat = Tracker.newPattern(nrows, nch) + local d = pat.data + local high = false + local used = math.min(ntracks, nch) + for row = 0, nrows - 1 do + for ch = 0, ntracks - 1 do + local note, ins, cmd, param, cut = 0, 0, 0, 0, false + if version < 1 then + local ni, ic, p = br:u8(), br:u8(), br:u8() + if ni % 64 > 0 then + note = ni % 64 + lctx.transpose + end + ins = ic // 16 + bit32.rshift(bit32.band(ni, 0x80), 3) + bit32.rshift(bit32.band(ni, 0x40), 1) + cmd, param = ic % 16, p + else + local nv, iv, c, p = br:u8(), br:u8(), br:u8(), br:u8() + if nv % 128 > 0 then + note = nv % 128 + lctx.transpose + elseif nv == 0x80 then + cut = true + end + ins, cmd, param = iv % 64, c, p + end + if br.err then + return pat, high + end + if ch < used then + local q = (row * nch + ch) * 5 + if note >= 61 + 24 - 12 then + high = true + end + local n = wrapNote(note, lctx.vol7bit) + if n > 0 then + buffer.writeu8(d, q, n) + elseif cut then + buffer.writeu8(d, q, 254) + end + buffer.writeu8(d, q + 1, ins) + if cmd ~= 0 or param ~= 0 then + local fx, fp, noteCut = effect(cmd, param, lctx) + if noteCut and n == 0 then + buffer.writeu8(d, q, 254) + end + buffer.writeu8(d, q + 3, fx) + buffer.writeu8(d, q + 4, fp) + end + end + end + end + return pat, high +end + +function Med.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local budget = { left = opts and opts.maxBytes or 2 ^ 28 } + if not validHeader(r) then + return nil, Err.new(if r:size() < 52 then Err.TRUNCATED else Err.CORRUPT, "not a MED module") + end + local version = r:peekU8(3) - 0x30 + local h = r:sub(8, 44) + local songOff = h:u32be() + h:skip(4) + local blockOff = h:u32be() + h:skip(4) + local smpOff = h:u32be() + h:skip(4) + local expOff = h:u32be() + -- the song: 63 sample headers, then the song header + local sh = r:sub(songOff, 63 * 8) + local song = r:sub(songOff + 63 * 8, 284) + local numBlocks, songLength = song:u16be(), song:u16be() + local seq = song:sub(4, 256) + song:skip(256) + local defTempo, playTranspose, flags, flags2, tempo2 = song:u16be(), song:i8(), song:u8(), song:u8(), song:u8() + local trackVol = {} + for i = 1, 16 do + trackVol[i] = song:u8() + end + local masterVol, numSamples = song:u8(), song:u8() + if song.err or numSamples > 63 or numBlocks > 0x7FFF then + return nil, Err.new(Err.CORRUPT, "bad song header") + end + if numSamples > 0 and smpOff == 0 then + return nil, Err.new(Err.CORRUPT, "no sample table") + end + local nch = 4 + local blockPtr: { number } = {} + for b = 0, numBlocks - 1 do + local p = r:sub(blockOff + b * 4, 4):u32be() + blockPtr[b + 1] = p + if p > 0 and p < r:size() then + local w = if version < 1 then r:peekU8(p) else r:peekU8(p) * 256 + r:peekU8(p + 1) + nch = math.max(nch, w) + end + end + if nch > 64 then + return nil, Err.new(Err.UNSUPPORTED, nch .. " tracks") + end + local m = Tracker.newModule("med", nch, "xm") + m.linear = false + m.instrumentMode = false + m.flags.periods, m.flags.envRowHold = "amiga", true + local stSlides = bit32.band(flags, 0x20) ~= 0 + m.flags.fastSlides, m.flags.fastPortas = not stSlides, not stSlides + local hardwareMix = version < 2 or bit32.band(flags2, 0x80) == 0 + m.flags.amigaLimits = hardwareMix + -- the expansion data: instrument extras and names, the song name + local ext = { instrExt = 0, instrExtN = 0, instrExtSize = 0, infoOff = 0, infoN = 0, infoSize = 0, nameOff = 0, nameLen = 0, annoOff = 0, annoLen = 0 } + if expOff > 0 then + local e = r:sub(expOff, 80) + e:skip(4) + ext.instrExt, ext.instrExtN, ext.instrExtSize = e:u32be(), e:u16be(), e:u16be() + ext.annoOff, ext.annoLen = e:u32be(), e:u32be() + ext.infoOff, ext.infoN, ext.infoSize = e:u32be(), e:u16be(), e:u16be() + e:skip(16) + ext.nameOff, ext.nameLen = e:u32be(), e:u32be() + if e.err then + ext.instrExt, ext.infoOff, ext.nameOff, ext.annoOff = 0, 0, 0, 0 + end + end + if ext.nameOff > 0 and ext.nameLen > 0 then + m.title = r:sub(ext.nameOff, math.min(ext.nameLen, 256)):fixed(math.min(ext.nameLen, 256)) + end + local needInstruments = false + local instruments, samples = {}, {} + local unsupported = {} + for ins = 1, numSamples do + local smpHead = sh:sub((ins - 1) * 8, 8) + local loopStart, loopLen = smpHead:u16be() * 2, smpHead:u16be() * 2 + local midiCh, _midiPreset, volume, transpose = smpHead:u8(), smpHead:u8(), smpHead:u8(), smpHead:i8() + local x = { hold = 0, decay = 0, finetune = 0, pitch = 0, flags = 0, loopStart = 0, loopLen = 0, volume = 0 } + local xsize = 0 + if ext.instrExt > 0 and ins <= ext.instrExtN then + xsize = ext.instrExtSize + local xr = r:sub(ext.instrExt + (ins - 1) * xsize, xsize) + x.hold, x.decay = xr:u8(), xr:u8() + xr:skip(1) + x.finetune = xr:i8() + x.pitch, x.flags = xr:u8(), xr:u8() + xr:skip(4) + x.loopStart, x.loopLen = xr:u32be(), xr:u32be() + x.volume = xr:u8() + end + local name = "" + if ext.infoOff > 0 and ins <= ext.infoN then + name = r:sub(ext.infoOff + (ins - 1) * ext.infoSize, math.min(ext.infoSize, 40)):fixed(math.min(ext.infoSize, 40)) + end + local instr = Tracker.newInstrument(name) + instruments[ins] = instr + local iptr = if smpOff > 0 then r:sub(smpOff + (ins - 1) * 4, 4):u32be() else 0 + local length, typ = 0, 0 + if iptr > 0 then + local ih = r:sub(iptr, 6) + length, typ = ih:u32be(), ih:i16be() + if ih.err then + length, typ = 0, 0 + end + end + local isSynth = typ < 0 + local masked = bit32.band(typ % 65536, 0x0F) + local count = if not isSynth then (SAMPLES_PER_TYPE[masked] or 1) else 1 + if isSynth then + table.insert(unsupported, "synth / hybrid instrument " .. ins) + needInstruments = needInstruments or typ == -1 or typ == -2 + end + if midiCh > 0 and midiCh <= 16 then + needInstruments = true + table.insert(unsupported, "MIDI instrument " .. ins) + end + local first = #samples + 1 + -- keymap: one sample per note, multi-octave samples spread over the octaves + for n = 1, 120 do + instr.sampleMap[n] = first + end + if count > 1 then + needInstruments = true + for n = 1, 120 do + local note = n + 11 + transpose -- OpenMPT's keyboard index + if note < 0 then + note = -note % 12 + end + local oct = math.clamp(note // 12 - 4, 0, 7) + instr.sampleMap[n] = first + OCT_SAMPLE[count - 1][oct + 1] + instr.noteMap[n] = math.clamp(1 + note + OCT_TRANSPOSE[count - 1][oct + 1] - 12, 1, 120) + end + transpose = 0 + elseif masked == 7 then + needInstruments = true -- two extra-low octaves + for n = 1, 120 do + instr.noteMap[n] = math.clamp(n - 24, 1, 120) + end + end + if midiCh == 0 then + -- notes past the mixer's range fold down (by octaves) + local top = 61 + (if hardwareMix then 24 else 36) + for n = 1, 120 do + local real = instr.noteMap[n] + 12 + transpose + if real >= top then + instr.noteMap[n] = math.max(1, instr.noteMap[n] - ((real - top + 12) - (real - top + 12) % 12)) + end + end + end + local list = {} + for i = 0, count - 1 do + local s = Tracker.newSample(name) + s.volume = math.min(volume, 64) + s.relativeNote = transpose + list[i + 1] = s + samples[first + i] = s + end + local hasLoop = loopLen > 2 + if not isSynth and iptr > 0 and length > 0 then + local bits = if bit32.band(typ, 0x10) ~= 0 then 16 else 8 + local stereo = bit32.band(typ, 0x20) ~= 0 + local nchs = if stereo then 2 else 1 + local bytes = length * nchs + local frames = length // (bits // 8) + if count > 1 then + frames //= (2 ^ count - 1) + end + local pos = r.base + iptr + 6 + local ls, le = loopStart, loopStart + loopLen + for i = 1, count do + local s = list[i] + local spec = { bits = bits, signed = true, bigEndian = true, channels = nchs, planar = stereo, delta = bit32.band(typ, 0x40) ~= 0, limit = math.min(r.limit, r.base + iptr + 6 + bytes) } + local ok, err = Load.readSample(r.buf, pos, frames, spec, s, budget) + if not ok then + return nil, err + end + pos += frames * nchs * bits // 8 + if hasLoop then + s.loopStart, s.loopEnd, s.loopType = ls, math.min(le, s.length), 1 + end + frames, ls, le = frames * 2, ls * 2, le * 2 + end + end + if xsize > 0 then + if x.hold > 0 and not isSynth then + local env = Tracker.newEnvelope() + env.enabled = true + local fall = x.hold + (if x.decay > 0 then 64 // x.decay else 0) + if x.hold == 1 then + env.ticks, env.values = { 0, fall }, { 64, 0 } + else + env.ticks, env.values = { 0, x.hold - 1, fall }, { 64, 64, 0 } + end + instr.volEnv = env + instr.fadeout = if x.decay > 0 then math.min(x.decay * 512, 65535) else 32767 + needInstruments = true + end + if xsize > 4 and x.pitch ~= 0 then + instr.noteMap[24 - 12 + 1] = math.clamp(x.pitch + 1 + 23 - 12, 1, 120) + needInstruments = true + end + if xsize > 18 then + instr.globalVolume = (x.volume + 1) // 2 * 2 + end + local ls, le = x.loopStart, x.loopStart + x.loopLen + for _, s in list do + s.finetune = math.clamp(x.finetune * 16, -128, 127) + if not isSynth and xsize > 14 then + s.loopStart, s.loopEnd = ls, math.min(le, s.length) + ls, le = ls * 2, le * 2 + end + if xsize > 5 then + if not isSynth then + s.loopType = if bit32.band(x.flags, 1) == 0 then 0 elseif bit32.band(x.flags, 8) ~= 0 then 2 else 1 + end + if bit32.band(x.flags, 4) ~= 0 then + s.globalVolume = 0 + end + end + end + end + end + -- the play order: MMD0 / MMD1 a sequence of blocks; MMD2 / MMD3 sections of play sequences (stop / jump commands) + local jumps: { [number]: number } = {} + local preamp = 32 + if version < 2 then + if songLength > 256 then + return nil, Err.new(Err.CORRUPT, "bad song length") + end + for i = 1, songLength do + m.order[i] = seq:u8() + end + for i = 1, nch do + local k = (i - 1) % 4 + m.channelPan[i] = if k == 1 or k == 2 then 0xC0 else 0x40 + if i <= 16 then + m.channelVolume[i] = math.min(trackVol[i], 64) + end + end + else + local s2 = song:sub(4, 256) + local playSeqTable, sectionTable, trackVolsOff = s2:u32be(), s2:u32be(), s2:u32be() + local numTracks, numPlaySeqs = s2:u16be(), s2:u16be() + local trackPanOff, flags3, volAdjust = s2:u32be(), s2:u32be(), s2:u16be() + if numTracks < 1 or numTracks > 64 then + return nil, Err.new(Err.CORRUPT, "bad track count") + end + local freePan = not hardwareMix and bit32.band(flags3, 2) ~= 0 + if volAdjust > 0 then + preamp = (preamp * math.min(volAdjust, 800) + 50) // 100 + end + if freePan then + preamp //= 2 + end + if trackVolsOff > 0 then + for i = 1, nch do + m.channelVolume[i] = math.min(r:sub(trackVolsOff + i - 1, 1):u8(), 64) + end + end + local pans = (freePan or version > 2) and trackPanOff > 0 + for i = 1, nch do + if pans then + m.channelPan[i] = (math.clamp(r:sub(trackPanOff + i - 1, 1):i8(), -16, 16) + 16) * 8 + else + local k = (i - 1) % 4 + m.channelPan[i] = if k == 1 or k == 2 then 0xC0 else 0x40 + end + end + local sections = r:sub(sectionTable, songLength * 2) + for _ = 1, songLength do + local sec = sections:u16be() + if sections.err then + break + end + if sec <= numPlaySeqs then + local ps = r:sub(playSeqTable + sec * 4, 4):u32be() + local pr = r:sub(ps, 42) + pr:skip(32) + local cmdTable = pr:u32be() + pr:skip(4) + local len = pr:u16be() + if not pr.err then + if #m.order > 0 then + table.insert(m.order, 254) + end + local start = #m.order + local er = r:sub(ps + 42, len * 2) + for _ = 1, len do + local b = er:u16be() + if er.err then + break + end + if b < 0x8000 then + table.insert(m.order, math.min(b, 253)) + end + end + if cmdTable > 0 then + local cr = r:sub(cmdTable) + for _ = 1, 4096 do + local off, c, extra = cr:u16be(), cr:u8(), cr:u8() + local arg = if extra >= 2 then cr:sub(cr:tell(), 2):u16be() else 0 + cr:skip(extra) + local at = start + off + 1 + if cr.err or off == 0xFFFF or at > #m.order then + break + end + if c == 1 then + m.order[at] = 255 + elseif c == 2 then + jumps[at] = arg + m.order[at] = 254 + end + end + end + end + end + end + end + m.preamp = preamp + local ctx: Ctx = { + transpose = 36 + playTranspose - (if version > 2 then 24 else 0), + is8Ch = bit32.band(flags, 0x40) ~= 0, + softMix = bit32.band(flags2, 0x80) ~= 0, + bpm = bit32.band(flags2, 0x20) ~= 0, + rowsPerBeat = 1 + bit32.band(flags2, 0x1F), + volHex = bit32.band(flags, 0x10) ~= 0, + vol7bit = false, + } + m.tempo = tempoToBpm(defTempo, ctx) + m.speed = math.clamp(tempo2, 1, 32) + if masterVol > 0 then + m.globalVolume = math.min(masterVol, 64) * 2 + end + for b = 0, numBlocks - 1 do + local p = blockPtr[b + 1] + local pat, high = nil, false + if p and p > 0 then + pat, high = readBlock(r, p, version, ctx, nch) + end + m.patterns[b + 1] = pat or Tracker.newPattern(64, nch) + needInstruments = needInstruments or high + end + -- play-sequence jumps: a jump effect at the end of the block before the command + for at, to in jumps do + local prev = m.order[at - 1] + if prev and prev < 254 and m.patterns[prev + 1] then + local src = m.patterns[prev + 1] + local cp = Tracker.newPattern(src.rows, nch) + buffer.copy(cp.data, 0, src.data) + table.insert(m.patterns, cp) + m.order[at - 1] = #m.patterns - 1 + Load.writeEffect(m, #m.patterns - 1, cp.rows - 1, 0xB, math.min(to, 255), "prev") + end + end + m.samples = samples + if needInstruments then + m.instrumentMode = true + m.instruments = instruments + end + if #unsupported > 0 then + m.meta.unsupported = unsupported + end + if ext.annoOff > 0 and ext.annoLen > 1 then + m.meta.message = r:sub(ext.annoOff, ext.annoLen - 1):string(math.min(ext.annoLen - 1, r:size())) + end + m.meta.source = { format = "med", version = "MMD" .. version, instruments = needInstruments } + local ok, verr = Tracker.validate(m) + if not ok then + return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module") + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Med.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local m, err = Med.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return Med +end +__FILES["music/midi"] = function() + +-- music/midi: Standard MIDI Files (SMF 1.0 formats 0 / 1 / 2, PPQ and SMPTE; RIFF RMID read), from the spec. Supports: +-- decode to a Types.Midi, .kar lyrics, encode (byte-identical to python mido by default), the tempo map, rendering +-- through codecs/audio/SoundFont. Not supported: RMID write, XMF / DLS banks, system common bytes in tracks. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Smf = __include("music/midi/Smf") +local Render = __include("codecs/audio/MidiRender") + +-- ------------------------------------------------------------------------------------------------ contract +local Midi = { + name = "midi", + category = "music", + extensions = { "mid", "midi", "smf", "kar", "rmi" }, + mime = { "audio/midi", "audio/x-midi" }, + deps = { "core/Err", "core/Bytes", "codecs/audio/MidiRender", "Types" }, + caps = { decode = true, encode = true, formats = { 0, 1, 2 }, render = true, streaming = true, rmid = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = Smf.ReadOptions -- strict (default false), maxEvents (default 2^24) +type EncodeOptions = Smf.WriteOptions -- runningStatus (default true) +type RenderOptions = Render.RenderOptions + +-- ------------------------------------------------------------------------------------------------ sniff +function Midi.sniff(r: Bytes.Reader): number + if r:peek(4) == "MThd" then + return 1 + end + if r:peek(4) == "RIFF" and r:peek(4, 8) == "RMID" then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- .kar: FF 01 text in a "Words" track (or after an "@K" / "@T" header) and FF 05 lyrics; "@X" headers -> meta.karaoke[X] +local function karaoke(midi: Types.Midi) + local lyrics: { { time: number, tick: number, text: string } } = {} + local headers: { [string]: { string } } = {} + local map = Render.tempoMap(midi) + local kar, hasWords = false, false + for _, t in midi.tracks do + if t.name == "Words" then + kar, hasWords = true, true + end + for _, ev in t.events do + if ev.type == "meta" and ev.meta == 1 and type(ev.data) == "table" and ev.data[1] == 64 then + local c = ev.data[2] + if c == 75 or c == 84 then -- @K, @T + kar = true + end + end + end + end + for ti, t in midi.tracks do + local tmap = if midi.format == 2 then Render.tempoMap(midi, ti) else map + local words = kar and (t.name == "Words" or not hasWords) + for _, ev in t.events do + if ev.type == "meta" and type(ev.data) == "table" and (ev.meta == 5 or (ev.meta == 1 and words)) then + local text = Smf.text(ev.data :: { number }) + if ev.meta == 1 and string.sub(text, 1, 1) == "@" and #text >= 2 then + local key = string.sub(text, 2, 2) + local list = headers[key] or {} + headers[key] = list + table.insert(list, string.sub(text, 3)) + else + table.insert(lyrics, { time = Render.seconds(tmap, ev.tick), tick = ev.tick, text = text }) + end + end + end + end + if #lyrics == 0 and next(headers) == nil then + return + end + table.sort(lyrics, function(a: { time: number, tick: number, text: string }, b: { time: number, tick: number, text: string }): boolean + return a.time < b.time + end) + midi.meta.lyrics = lyrics + midi.meta.karaoke = headers + local tags: { [string]: string } = {} + if headers.T then + tags.title = headers.T[1] + tags.artist = headers.T[2] + end + if headers.L then + tags.language = headers.L[1] + end + if headers.I then + tags.comment = table.concat(headers.I, "\n") + end + midi.meta.tags = tags +end + +function Midi.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Midi?, Err.Err?) + local midi, err = Smf.read(r, opts) + if not midi then + return nil, err + end + Render.attach(midi, { format = "midi", smf = midi.format }) + karaoke(midi) + return midi, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Midi.encode(midi: Types.Midi, opts: EncodeOptions?): (buffer?, Err.Err?) + return Smf.write(midi, opts) +end + +-- ------------------------------------------------------------------------------------------------ open +function Midi.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local midi, err = Midi.decode(r, opts) + if not midi then + return nil, err + end + return Render.decoder(midi, opts) +end + +-- ------------------------------------------------------------------------------------------------ extras +function Midi.render(midi: Types.Midi, opts: RenderOptions?): (Types.Decoder?, Err.Err?) + return Render.decoder(midi, opts) +end + +function Midi.tickToSeconds(midi: Types.Midi, tick: number, track: number?): number + return Render.seconds(Render.tempoMap(midi, track), tick) +end + +Midi.tempoMap = Render.tempoMap +Midi.seconds = Render.seconds + +-- as python mido's MidiFile.length (formats 0 / 1) +function Midi.length(midi: Types.Midi): number + return Render.length(midi) +end + +Midi.text = Smf.text + +return Midi +end +__FILES["music/midi/Smf"] = function() + +-- music/midi/Smf: SMF 1.0 MThd / MTrk <-> Types.Midi (running status also across meta / sysex, RIFF RMID unwrapped). +-- Writes what python mido writes: running status reset after meta / sysex, one end-of-track, track names at tick 0. +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") + +local Smf = {} + +local readu8 = buffer.readu8 + +local CHANNEL_TYPES = { [8] = "noteOff", [9] = "noteOn", [10] = "aftertouch", [11] = "controller", [12] = "program", [13] = "channelPressure", [14] = "pitchBend" } +local TYPE_STATUS = { noteOff = 0x80, noteOn = 0x90, aftertouch = 0xA0, controller = 0xB0, program = 0xC0, channelPressure = 0xD0, pitchBend = 0xE0 } +Smf.TYPE_STATUS = TYPE_STATUS + +type ReadOptions = { + strict: boolean?, -- a truncated track / file is an error (default false: keep the events read so far, meta.truncated) + maxEvents: number?, -- default 2^24 +} +type WriteOptions = { + runningStatus: boolean?, -- default true +} + +local function bytesOf(b: buffer, p: number, n: number): { number } + local t: { number } = table.create(n) :: { number } + for i = 0, n - 1 do + t[i + 1] = readu8(b, p + i) + end + return t +end + +local function text(data: { number }): string + local parts = table.create(#data) + for i, c in data do + parts[i] = string.char(c) + end + return table.concat(parts) +end +Smf.text = text + +-- ------------------------------------------------------------------------------------------------ read +local function readTrack(b: buffer, p: number, e: number, budget: { number }): ({ Types.MidiEvent }?, string?, boolean) + local events: { Types.MidiEvent } = {} + local tick = 0 + local running = 0 + while p < e do + local delta, n = 0, 0 + repeat + if p >= e then + return events, nil, true + end + local c = readu8(b, p) + p += 1 + n += 1 + delta = delta * 128 + c % 128 + if n > 4 then + return nil, "delta time longer than 4 bytes", false + end + until c < 128 + tick += delta + if p >= e then + return events, nil, true + end + local status = readu8(b, p) + if status < 0x80 then + if running == 0 then + return nil, "running status without a previous status byte", false + end + status = running + else + p += 1 + if status < 0xF0 then + running = status + end + end + budget[1] -= 1 + if budget[1] < 0 then + return nil, "LIMIT", false + end + if status == 0xFF or status == 0xF0 or status == 0xF7 then + local mtype = 0 + if status == 0xFF then + if p >= e then + return events, nil, true + end + mtype = readu8(b, p) + p += 1 + end + local len, m = 0, 0 + repeat + if p >= e then + return events, nil, true + end + local c = readu8(b, p) + p += 1 + m += 1 + len = len * 128 + c % 128 + if m > 4 then + return nil, "length longer than 4 bytes", false + end + until c < 128 + if p + len > e then + return events, nil, true + end + local data = bytesOf(b, p, len) + p += len + if status == 0xFF then + table.insert(events, { tick = tick, type = "meta", meta = mtype, data = data }) + else + table.insert(events, { tick = tick, type = if status == 0xF0 then "sysex" else "escape", data = data }) + end + elseif status >= 0xF0 then + return nil, string.format("unexpected status byte 0x%02x in a track", status), false + else + local kind = status // 16 + local count = if kind == 12 or kind == 13 then 1 else 2 + if p + count > e then + return events, nil, true + end + local d1 = readu8(b, p) + local d2 = if count == 2 then readu8(b, p + 1) else 0 + if d1 >= 128 or d2 >= 128 then + return nil, "data byte over 127", false + end + p += count + table.insert(events, { + tick = tick, + type = CHANNEL_TYPES[kind], + channel = status % 16, + data = if count == 2 then { d1, d2 } else { d1 }, + }) + end + end + return events, nil, false +end + +function Smf.read(r: Bytes.Reader, opts: ReadOptions?): (Types.Midi?, Err.Err?) + local strict = opts and opts.strict or false + local budget = { opts and opts.maxEvents or 2 ^ 24 } + local b = r.buf + local base, limit = r.base, r.limit + local rmid = false + -- RIFF RMID: the SMF is the "data" chunk + if r:peek(4) == "RIFF" and r:peek(4, 8) == "RMID" then + local q = base + 12 + local found = false + while q + 8 <= limit do + local id = buffer.readstring(b, q, 4) + local size = buffer.readu32(b, q + 4) + if id == "data" then + base = q + 8 + limit = math.min(limit, base + size) + found = true + break + end + q += 8 + size + size % 2 + end + if not found then + return nil, Err.new(Err.CORRUPT, "RMID without a data chunk", r.base) + end + rmid = true + end + local h = Bytes.reader(b, base, limit - base) + if h:string(4) ~= "MThd" then + return nil, Err.new(Err.CORRUPT, "no MThd header", base) + end + local hlen = h:u32be() + local format, ntrks, division = h:u16be(), h:u16be(), h:i16be() + if h.err then + return nil, h.err + end + if hlen < 6 then + return nil, Err.new(Err.CORRUPT, "MThd shorter than 6 bytes", base + 4) + end + if format > 2 then + return nil, Err.new(Err.UNSUPPORTED, "SMF format " .. format, base + 8) + end + if division == 0 then + return nil, Err.new(Err.CORRUPT, "zero ticks per quarter note", base + 12) + end + local midi = Types.Midi.new(division) + midi.format = format + local truncated = false + local p = base + 8 + hlen + while #midi.tracks < ntrks and p + 8 <= limit do + local id = buffer.readstring(b, p, 4) + local size = bit32.byteswap(buffer.readu32(b, p + 4)) + local s = p + 8 + local e = s + size + if e > limit then + e = limit + truncated = true + end + if id == "MTrk" then + local events, msg, short = readTrack(b, s, e, budget) + if not events then + if msg == "LIMIT" then + return nil, Err.new(Err.LIMIT, "over the event limit") + end + return nil, Err.new(Err.CORRUPT, msg or "bad track", s) + end + truncated = truncated or short + local track: { events: { Types.MidiEvent }, name: string? } = { events = events, name = nil } + for _, ev in events do + if ev.type == "meta" and ev.meta == 3 then + track.name = text(ev.data :: { number }) + break + end + end + table.insert(midi.tracks, track) + end + p = s + size + end + if #midi.tracks < ntrks and p < limit then + truncated = true + elseif #midi.tracks < ntrks then + truncated = true + end + if truncated and strict then + return nil, Err.new(Err.TRUNCATED, "the file ends inside a track (or before all tracks)") + end + midi.meta.declaredTracks = ntrks + midi.meta.truncated = truncated + midi.meta.rmid = rmid + if division < 0 then + local fps = -(division // 256) + midi.meta.smpte = { fps = if fps == 29 then 29.97 else fps, ticksPerFrame = division % 256 } + end + return midi, nil +end + +-- ------------------------------------------------------------------------------------------------ write +local function vlq(w: Bytes.Writer, v: number) + if v < 128 then + w:u8(v) + return + end + local bytes = {} + while v > 0 do + table.insert(bytes, 1, v % 128) + v = v // 128 + end + for i, c in bytes do + w:u8(if i < #bytes then c + 128 else c) + end +end + +local function byteList(d: any, want: number?): { number }? + if type(d) ~= "table" then + return if want == 0 then {} else nil + end + for i, v in d do + if type(i) ~= "number" or type(v) ~= "number" or v < 0 or v > 255 or v % 1 ~= 0 then + return nil + end + end + if want and #d < want then + return nil + end + return d +end + +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, "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, "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, "division must be a non-zero 16-bit integer") + end + if format == 0 and #midi.tracks ~= 1 then + return nil, Err.new(Err.ARG, "format 0 needs exactly one track") + end + if #midi.tracks > 65535 then + return nil, Err.new(Err.ARG, "too many tracks") + end + local w = Bytes.writer(1024) + w:string("MThd") + w:u32be(6) + w:u16be(format) + w:u16be(#midi.tracks) + w:u16be(if division < 0 then division + 65536 else division) + 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, "track " .. ti .. " has no events list") + end + local sorted = true + local last = 0 + for i, ev in events do + if type(ev) ~= "table" or type(ev.tick) ~= "number" or ev.tick < 0 or ev.tick % 1 ~= 0 then + return nil, Err.new(Err.ARG, string.format("midi encode: track %d event %d needs a whole non-negative tick", ti, i)) + end + if ev.tick < last then + sorted = false + end + last = ev.tick + end + local list: { any } = events + if not sorted then + list = table.clone(events) + local order: { [any]: number } = {} + for i, ev in list do + order[ev] = i + end + table.sort(list, function(a: any, c: any): boolean + if a.tick ~= c.tick then + return a.tick < c.tick + end + return order[a] < order[c] + end) + end +-- a track-name meta event (0x03) at tick 0 when the track has none (as mido) + if type(track.name) == "string" and track.name ~= "" then + local named = false + for _, ev in list do + if ev.type == "meta" and ev.meta == 0x03 then + named = true + break + end + end + if not named then + local bytes = { string.byte(track.name, 1, math.min(#track.name, 4096)) } + list = table.clone(list) + table.insert(list, 1, { tick = 0, type = "meta", meta = 0x03, data = bytes }) + end + end + w:string("MTrk") + local lenAt = w:tell() + w:u32be(0) + local start = w:tell() + local prev = 0 + local status = 0 + local endTick = 0 + for i, ev in list do + local t = ev.type + endTick = ev.tick + if t == "meta" and ev.meta == 0x2F then + continue -- written once at the end + end + local delta = ev.tick - prev + if delta > 0x0FFFFFFF then + return nil, Err.new(Err.ARG, "a delta time over 0x0FFFFFFF ticks") + end + local base = TYPE_STATUS[t] + if base then + local ch = ev.channel or 0 + if type(ch) ~= "number" or ch < 0 or ch > 15 or ch % 1 ~= 0 then + return nil, Err.new(Err.ARG, string.format("midi encode: track %d event %d: channel must be 0..15", ti, i)) + end + local n = if base == 0xC0 or base == 0xD0 then 1 else 2 + local d = byteList(ev.data, n) + if not d or d[1] > 127 or (n == 2 and d[2] > 127) then + return nil, Err.new(Err.ARG, string.format("midi encode: track %d event %d: %s needs %d data bytes 0..127", ti, i, t, n)) + end + vlq(w, delta) + local st = base + ch + if not (running and st == status) then + w:u8(st) + end + status = st + w:u8(d[1]) + if n == 2 then + w:u8(d[2]) + end + elseif t == "meta" or t == "sysex" or t == "escape" then + local d = byteList(ev.data, 0) + if not d then + return nil, Err.new(Err.ARG, string.format("midi encode: track %d event %d: data must be bytes", ti, i)) + end + vlq(w, delta) + if t == "meta" then + local m = ev.meta + if type(m) ~= "number" or m < 0 or m > 127 or m % 1 ~= 0 then + return nil, Err.new(Err.ARG, string.format("midi encode: track %d event %d: meta type must be 0..127", ti, i)) + end + w:u8(0xFF) + w:u8(m) + else + w:u8(if t == "sysex" then 0xF0 else 0xF7) + end + if #d > 0x0FFFFFFF then + return nil, Err.new(Err.ARG, "event data too long") + end + vlq(w, #d) + for _, c in d do + w:u8(c) + end + status = 0 + else + return nil, Err.new(Err.ARG, string.format("midi encode: track %d event %d: unknown type %s", ti, i, tostring(t))) + end + prev = ev.tick + end + vlq(w, math.max(0, endTick - prev)) + w:u8(0xFF) + w:u8(0x2F) + w:u8(0) + w:setU32be(lenAt, w:tell() - start) + end + return w:finish(), nil +end + +return Smf +end +__FILES["music/mod"] = function() + +-- music/mod: ProTracker / NoiseTracker / StarTrekker MODs (M.K., M!K!, FLT4, xCHN, xxCH, xxCN, CD81, OKTA, TDZx; +-- 15-sample Soundtracker by name or extension), from the ProTracker 2.3 docs. Writes 31-sample MODs from "mod" modules +-- and XM ones that fit. Not supported: FLT8's split patterns (read as 8 channels), the E0x filter, PowerPacker files. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Tracker = __include("codecs/audio/Tracker") + +-- ------------------------------------------------------------------------------------------------ contract +local Mod = { + name = "mod", + category = "music", + extensions = { "mod", "m15", "stk", "nst" }, + mime = { "audio/x-mod", "audio/mod" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" }, + caps = { decode = true, encode = true, render = true, channels = { 1, 32 } }, +} + +type DecodeOptions = { + maxBytes: number?, -- f32 bytes of sample data in total, default 64 MB +} +type EncodeOptions = {} + +-- ------------------------------------------------------------------------------------------------ constants +local Pcm = Tracker.Pcm +local Tables = Tracker.Tables + +local FIXED: { [string]: number } = { + ["M.K."] = 4, + ["M!K!"] = 4, + ["M&K!"] = 4, + ["N.T."] = 4, + ["FLT4"] = 4, + ["FLT8"] = 8, + ["CD81"] = 8, + ["OKTA"] = 8, + ["OCTA"] = 8, + ["EXO4"] = 4, + ["EXO8"] = 8, +} + +-- the 4-byte signature at offset 1080 +local function signatureChannels(sig: string): number? + local fixed = FIXED[sig] + if fixed then + return fixed + end + local d = string.match(sig, "^(%d)CHN$") + if d then + local n = tonumber(d) :: number + return if n >= 1 then n else nil + end + local dd = string.match(sig, "^(%d%d)C[HN]$") + if dd then + local n = tonumber(dd) :: number + return if n >= 1 and n <= 32 then n else nil + end + local t = string.match(sig, "^TDZ(%d)$") + if t then + local n = tonumber(t) :: number + return if n >= 1 then n else nil + end + return nil +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Mod.sniff(r: Bytes.Reader): number + if r:size() < 1084 then + return 0 + end + local sig = r:peek(4, 1080) + if signatureChannels(sig) then + return 0.8 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Mod.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local maxBytes = opts and opts.maxBytes or 2 ^ 26 + local size = r:size() + local sig = if size >= 1084 then r:peek(4, 1080) else "" + local channels = signatureChannels(sig) + local nsamples = 31 + if not channels then + -- a 15-sample Soundtracker module (no signature): only when the header is plausible + nsamples, channels = 15, 4 + end + local nch = channels :: number + local m = Tracker.newModule("mod", nch) + m.title = r:fixed(20) + local lengths: { number } = {} + for i = 1, nsamples do + local s = Tracker.newSample(r:fixed(22)) + local len = r:u16be() * 2 + local ft = r:u8() % 16 + local vol = r:u8() + local ls = r:u16be() * 2 + local ll = r:u16be() * 2 + if r.err then + return nil, r.err + end + if nsamples == 15 and (vol > 64 or ft ~= 0) then + return nil, Err.new(Err.CORRUPT, "not a MOD (bad sample header)") + end + s.finetune = (if ft >= 8 then ft - 16 else ft) * 16 + s.volume = math.min(vol, 64) + s.bits = 8 + if ll > 2 then + s.loopStart, s.loopEnd, s.loopType = ls, ls + ll, 1 + end + lengths[i] = len + m.samples[i] = s + end + local songLength = r:u8() + local restart = r:u8() + local order: { number } = {} + local maxPat = 0 + for i = 1, 128 do + local p = r:u8() + order[i] = p + maxPat = math.max(maxPat, p) + end + if r.err then + return nil, r.err + end + if songLength == 0 or songLength > 128 or maxPat >= 128 then + return nil, Err.new(Err.CORRUPT, "not a MOD (bad order list)") + end + if nsamples == 31 then + r:skip(4) + end + for i = 1, songLength do + m.order[i] = order[i] + end + m.restart = if restart < songLength then restart else 0 + m.meta.signature = if nsamples == 31 then sig else nil + m.flags.amigaLimits = nch == 4 + local npat = maxPat + 1 + local patBytes = 64 * nch * 4 + if not r:need(npat * patBytes) then + return nil, r.err + end + local buf = r.buf + for p = 0, npat - 1 do + local pat = Tracker.newPattern(64, nch) + local base = r.pos + p * patBytes + local d = pat.data + for i = 0, 64 * nch - 1 do + local o = base + i * 4 + local b0, b1, b2, b3 = buffer.readu8(buf, o), buffer.readu8(buf, o + 1), buffer.readu8(buf, o + 2), buffer.readu8(buf, o + 3) + local period = (b0 % 16) * 256 + b1 + local ins = (b0 // 16) * 16 + b2 // 16 + local q = i * 5 + buffer.writeu8(d, q, Tables.periodToNote(period)) + buffer.writeu8(d, q + 1, ins) + buffer.writeu8(d, q + 3, b2 % 16) + buffer.writeu8(d, q + 4, b3) + end + m.patterns[p + 1] = pat + end + r:skip(npat * patBytes) +-- sample data: 8-bit signed + local total = 0 + for i = 1, nsamples do + local s = m.samples[i] + local len = math.min(lengths[i], r:remaining()) + total += len * 4 + if total > maxBytes then + return nil, Err.new(Err.LIMIT, "sample data over the maxBytes limit") + end + local data = Pcm.decode(buf, r.pos, len, { bits = 8, signed = true }) + if not data then + return nil, Err.new(Err.TRUNCATED, "sample data", r.pos) + end + r:skip(len) + s.data, s.length = data, len + if s.loopEnd > len then + s.loopEnd = len + if s.loopEnd - s.loopStart < 2 then + s.loopType, s.loopStart, s.loopEnd = 0, 0, 0 + end + end + end + m.meta.source = { format = "mod", samples = nsamples } + m.render = Tracker.renderMethod + local ok, verr = Tracker.validate(m) + if not ok then + return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module") + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function writeName(w: Bytes.Writer, s: string, n: number) + local t = string.sub(s or "", 1, n) + w:string(t) + w:fill(0, n - #t) +end + +function Mod.encode(m: any, _opts: EncodeOptions?): (buffer?, Err.Err?) + local ok, verr = Tracker.validate(m) + if not ok then + return nil, verr + end + if m.format ~= "mod" and m.format ~= "xm" then + return nil, Err.new(Err.UNSUPPORTED, "only mod and xm modules can be written as MOD (got " .. tostring(m.format) .. "); xm is the closest writable format") + end + local nch = m.channels + if nch > 32 then + return nil, Err.new(Err.ARG, "MOD holds at most 32 channels") + end + local smpOf: { any } = {} + if m.format == "xm" then + for i, ins in m.instruments do + local first = 0 + for n = 1, 120 do + local s = ins.sampleMap[n] + if s ~= 0 then + if first ~= 0 and s ~= first then + return nil, Err.new(Err.ARG, "instrument " .. i .. " uses several samples") + end + first = s + end + end + smpOf[i] = m.samples[first] or Tracker.newSample(ins.name) + end + else + for i, s in m.samples do + smpOf[i] = s + end + end + if #smpOf > 31 then + return nil, Err.new(Err.ARG, "MOD holds at most 31 samples") + end + local order: { number } = {} + for _, o in m.order do + if o == 255 then + break + elseif o ~= 254 then + table.insert(order, o) + end + end + if #order == 0 or #order > 128 then + return nil, Err.new(Err.ARG, "MOD needs 1..128 order entries") + end + local npat = #m.patterns + if npat > 100 then + return nil, Err.new(Err.ARG, "too many patterns for MOD") + end + for p, pat in m.patterns do + if pat.rows ~= 64 then + return nil, Err.new(Err.ARG, "pattern " .. (p - 1) .. " has " .. pat.rows .. " rows (MOD patterns have 64)") + end + end + local w = Bytes.writer(1084 + npat * 64 * nch * 4 + 65536) + writeName(w, m.title or "", 20) + local datas: { buffer } = {} + for i = 1, 31 do + local s = smpOf[i] + if s then + local len = math.min(s.length, 131070) + local pcm = Pcm.encode(s.data, len, { bits = 8, signed = true, channels = 1 }) + if s.channels == 2 then + local mono = buffer.create(len * 4) + for k = 0, len - 1 do + buffer.writef32(mono, k * 4, (buffer.readf32(s.data, k * 8) + buffer.readf32(s.data, k * 8 + 4)) / 2) + end + pcm = Pcm.encode(mono, len, { bits = 8, signed = true }) + end + local even = len + len % 2 + local padded = buffer.create(even) + buffer.copy(padded, 0, pcm, 0, len) + datas[i] = padded + writeName(w, s.name or "", 22) + w:u16be(even // 2) + local ft = math.clamp(math.floor((s.finetune or 0) / 16 + 0.5), -8, 7) + w:u8(ft % 16) + w:u8(math.clamp(math.floor(s.volume), 0, 64)) + if s.loopType > 0 and s.loopEnd <= even then + w:u16be(s.loopStart // 2) + w:u16be(math.max(1, (s.loopEnd - s.loopStart) // 2)) + else + w:u16be(0) + w:u16be(1) + end + else + w:fill(0, 22) + w:u16be(0) + w:u8(0) + w:u8(0) + w:u16be(0) + w:u16be(1) + end + end + w:u8(#order) + w:u8(if m.restart < #order and m.restart > 0 then m.restart else 127) + for i = 1, 128 do + w:u8(order[i] or 0) + end + local sig + if nch == 4 then + sig = if npat > 64 then "M!K!" else "M.K." + elseif nch < 10 then + sig = nch .. "CHN" + else + sig = nch .. "CH" + end + w:string(sig) + for p = 1, npat do + local d = m.patterns[p].data + for i = 0, 64 * nch - 1 do + local q = i * 5 + local note, ins, fx, param = buffer.readu8(d, q), buffer.readu8(d, q + 1), buffer.readu8(d, q + 3), buffer.readu8(d, q + 4) + local period = if note >= 1 and note <= 120 then Tables.noteToPeriod(note) else 0 + if period > 4095 then + period = 0 + end + if fx > 15 then + fx, param = 0, 0 + end + if ins > 31 then + ins = 0 + end + w:u8((ins // 16) * 16 + period // 256) + w:u8(period % 256) + w:u8((ins % 16) * 16 + fx) + w:u8(param) + end + end + for i = 1, 31 do + if datas[i] then + w:bytes(datas[i]) + end + end + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Mod.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local m, err = Mod.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return Mod +end +__FILES["music/mtm"] = function() + +-- music/mtm: MultiTracker modules (MTM, 1..32 channels, patterns of shared tracks), ported from OpenMPT's Load_mtm.cpp +-- (BSD, licenses/openmpt-LICENSE.txt); played as the "xm" family with Amiga periods, as OpenMPT does. Not supported: +-- MultiTracker's E9x / EDx retrigger timing and vibrato start phase (played as in XM), writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Tracker = __include("codecs/audio/Tracker") +local Load = __include("codecs/audio/Tracker/Load") + +-- ------------------------------------------------------------------------------------------------ contract +local Mtm = { + name = "mtm", + category = "music", + extensions = { "mtm" }, + mime = { "audio/x-mtm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 32 } }, +} + +type DecodeOptions = { + maxBytes: number?, -- f32 bytes of sample data in total, default 2^28 +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Mtm.sniff(r: Bytes.Reader): number + if r:size() >= 66 and r:peek(3) == "MTM" and r:peekU8(3) < 0x20 and r:peekU8(33) >= 1 and r:peekU8(33) <= 32 then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- MultiTracker: a speed command resets the tempo to 125 and a tempo command the speed to 6, unless the module puts +-- both on one row somewhere (then it was written for players that treat them as ProTracker does) +local function speedTempoQuirk(m: any) + local speed, tempo, together = false, false, false + for _, p in m.patterns do + for row = 0, p.rows - 1 do + local s, t = false, false + for c = 1, m.channels do + local o = (row * m.channels + c - 1) * 5 + local fx, param = buffer.readu8(p.data, o + 3), buffer.readu8(p.data, o + 4) + if fx == 0xF then + if param < 0x20 then + s = true + else + t = true + end + end + end + speed, tempo, together = speed or s, tempo or t, together or (s and t) + end + end + if not (speed and tempo) or together then + return + end + for pi, p in m.patterns do + for row = 0, p.rows - 1 do + for c = 1, m.channels do + local o = (row * m.channels + c - 1) * 5 + local fx, param = buffer.readu8(p.data, o + 3), buffer.readu8(p.data, o + 4) + if fx == 0xF then + Load.writeEffect(m, pi - 1, row, 0xF, if param < 0x20 then 125 else 6, nil, nil, true) + break + end + end + end + end +end + +function Mtm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local budget = { left = opts and opts.maxBytes or 2 ^ 28 } + if r:size() < 66 then + return nil, Err.new(Err.TRUNCATED, "header") + end + if r:peek(3) ~= "MTM" then + return nil, Err.new(Err.CORRUPT, "no MTM signature") + end + r:skip(3) + local version = r:u8() + local title = r:fixed(20) + local numTracks, lastPattern, lastOrder = r:u16le(), r:u8(), r:u8() + local commentSize, numSamples, _attr, rowsPerTrack, nch = r:u16le(), r:u8(), r:u8(), r:u8(), r:u8() + local pans: { number } = {} + for i = 1, 32 do + pans[i] = r:u8() + end + if r.err then + return nil, r.err + end + if version >= 0x20 or lastOrder > 127 or rowsPerTrack > 64 or nch == 0 or nch > 32 then + return nil, Err.new(Err.CORRUPT, "bad header") + end + local m = Tracker.newModule("mtm", nch, "xm") + m.title = title + m.linear = false + m.instrumentMode = false + for i = 1, nch do + m.channelPan[i] = (pans[i] % 16) * 16 + 8 + end + local sizes: { number } = {} + for i = 1, numSamples do + local s = Tracker.newSample(r:fixed(22)) + local len, ls, le = r:u32le(), r:u32le(), r:u32le() + local ft, vol, attr = r:i8(), r:u8(), r:u8() + if r.err then + return nil, r.err + end + s.volume = math.min(vol, 64) + s.finetune = math.clamp(ft * 16, -128, 127) + local bits = if attr % 2 == 1 then 16 else 8 + s.bits = bits + local frames = 0 + if len > 2 then + frames = len + le = math.min(math.max(le, 1) - 1, len) + if ls + 4 >= le then + ls, le = 0, 0 + end + if bits == 16 then + frames, ls, le = frames // 2, ls // 2, le // 2 + end + if le > 2 then + s.loopStart, s.loopEnd, s.loopType = ls, le, 1 + end + end + sizes[i] = if len > 2 then len else 0 + s.length = frames + m.samples[i] = s + end + for i = 1, 128 do + local o = r:u8() + if i <= lastOrder + 1 then + m.order[i] = o + end + end + if r.err then + return nil, r.err + end + -- tracks (64 rows of 3 bytes each) and the patterns made of them + local rows = if rowsPerTrack > 0 then rowsPerTrack else 64 + local tracks = r:tell() + if not r:skip(192 * numTracks) then + return nil, r.err + end + local buf = r.buf + for p = 0, lastPattern do + local pat = Tracker.newPattern(rows, nch) + m.patterns[p + 1] = pat + for ch = 0, 31 do + local track = r:u16le() + if r.err then + return nil, r.err + end + if track > 0 and track <= numTracks and ch < nch then + local base = r.base + tracks + 192 * (track - 1) + for row = 0, rows - 1 do + local o = base + row * 3 + local b0, b1, b2 = buffer.readu8(buf, o), buffer.readu8(buf, o + 1), buffer.readu8(buf, o + 2) + local q = (row * nch + ch) * 5 + if b0 >= 4 then + buffer.writeu8(pat.data, q, b0 // 4 + 25) -- C-4 = 49 plays the sample at 8363 Hz (OpenMPT keeps MTM / XM notes an octave up) + end + buffer.writeu8(pat.data, q + 1, (b0 % 4) * 16 + b1 // 16) + local cmd, param = b1 % 16, b2 + if cmd == 0xA then + param = if param >= 16 then param - param % 16 else param + elseif cmd == 8 then + cmd, param = 0, 0 -- no 8xx panning in MultiTracker + elseif cmd == 0xE then + local x = param // 16 + if x == 0 or x == 3 or x == 4 or x == 6 or x == 7 or x == 0xF then + cmd, param = 0, 0 -- not in MultiTracker + end + end + buffer.writeu8(pat.data, q + 3, cmd) + buffer.writeu8(pat.data, q + 4, param) + end + end + end + end + speedTempoQuirk(m) + -- the song message (40-character lines), then the sample data (unsigned PCM) + m.meta.message = r:string(commentSize) + if r.err then + r.err = nil + end + local pos = r.pos + for i = 1, numSamples do + local s = m.samples[i] + if sizes[i] > 0 then + local ok, err = Load.readSample(buf, pos, s.length, { bits = s.bits, signed = false, limit = r.limit }, s, budget) + if not ok then + return nil, err + end + pos += sizes[i] + s.loopEnd = math.min(s.loopEnd, s.length) + end + end + m.meta.source = { format = "mtm", version = version, tracks = numTracks } + local ok, verr = Tracker.validate(m) + if not ok then + return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module") + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Mtm.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local m, err = Mtm.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return Mtm +end +__FILES["music/mus"] = function() + +-- music/mus: DMX MUS ("MUS\x1a"; Doom, Heretic, Hexen, Strife), from Vladimir Arnost's "MUS File Format" (wildmidi +-- only as a test reference). Decodes to a Types.Midi as the usual converters map it (MUS channel 15 -> 9; 140 ticks/s +-- as division 70 at 500000 us per quarter). Not supported: writing (encode as .mid with the midi format). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Render = __include("codecs/audio/MidiRender") + +-- ------------------------------------------------------------------------------------------------ contract +local Mus = { + name = "mus", + category = "music", + extensions = { "mus" }, + mime = { "audio/x-mus" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/MidiRender" }, + caps = { decode = true, encode = false, render = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + rate: number?, -- ticks per second, default 140 (Doom); some players use 70 + maxEvents: number?, -- default 2^24 +} + +-- ------------------------------------------------------------------------------------------------ constants +-- MUS controller / system event number -> MIDI controller (0 is the program change) +local CONTROLLER = { [0] = 0, 0, 0x01, 0x07, 0x0A, 0x0B, 0x5B, 0x5D, 0x40, 0x43, 0x78, 0x7B, 0x7E, 0x7F, 0x79 } + +-- ------------------------------------------------------------------------------------------------ sniff +function Mus.sniff(r: Bytes.Reader): number + return if r:peek(4) == "MUS\x1a" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local readu8 = buffer.readu8 + +local function score(b: buffer, p: number, e: number, primary: number, maxEvents: number): ({ Types.MidiEvent }?, string?, boolean) + local events: { Types.MidiEvent } = { { tick = 0, type = "controller", channel = 9, data = { 0x07, 127 } } } + local map: { [number]: number } = { [15] = 9 } + local volume: { [number]: number } = {} + local nextChannel = 0 + local tick = 0 + while p < e do + local ev = readu8(b, p) + p += 1 + local kind, mch = bit32.band(bit32.rshift(ev, 4), 7), bit32.band(ev, 15) + if kind == 6 then + return events, nil, false + end + local ch = map[mch] + if not ch then + ch = nextChannel + map[mch] = ch + nextChannel += if nextChannel == 8 then 2 else 1 + table.insert(events, { tick = tick, type = "controller", channel = ch, data = { 0x07, 127 } }) + end + local need = if kind == 1 then (if p < e and readu8(b, p) >= 128 then 2 else 1) elseif kind == 4 then 2 elseif kind == 5 then 0 else 1 + if kind == 7 then + return nil, "unknown event type 7", false + elseif p + need > e then + return events, nil, true + end + local d1, d2 = if need > 0 then readu8(b, p) else 0, if need > 1 then readu8(b, p + 1) else 0 + p += need + if kind == 0 then + table.insert(events, { tick = tick, type = "noteOff", channel = ch, data = { d1 % 128, 64 } }) + elseif kind == 1 then + if need == 2 then + volume[ch] = math.min(d2, 127) + end + table.insert(events, { tick = tick, type = "noteOn", channel = ch, data = { d1 % 128, volume[ch] or 127 } }) + elseif kind == 2 then + table.insert(events, { tick = tick, type = "pitchBend", channel = ch, data = { bit32.band(d1, 1) * 64, bit32.rshift(d1, 1) } }) + elseif kind == 3 or kind == 4 then + local c, v = d1, if kind == 3 then (if d1 == 12 then math.min(primary + 1, 127) else 0) else math.min(d2, 127) + if CONTROLLER[c] == nil then + return nil, string.format("unknown controller %d", c), false + end + if kind == 4 and c == 0 then + table.insert(events, { tick = tick, type = "program", channel = ch, data = { v } }) + else + table.insert(events, { tick = tick, type = "controller", channel = ch, data = { CONTROLLER[c], v } }) + end + end + if #events > maxEvents then + return nil, "limit: more than " .. maxEvents .. " events", false + end + if ev >= 128 then + local delay = 0 + repeat + if p >= e then + return events, nil, true + end + local c = readu8(b, p) + p += 1 + delay = delay * 128 + c % 128 + until c < 128 or delay > 2 ^ 28 + tick += delay + end + end + return events, nil, true +end + +function Mus.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Midi?, Err.Err?) + local o: DecodeOptions = opts or {} + local rate = o.rate or 140 + if type(rate) ~= "number" or rate < 1 or rate > 100000 then + return nil, Err.new(Err.ARG, "rate must be 1..100000 ticks per second") + end + if r:peek(4) ~= "MUS\x1a" then + return nil, Err.new(Err.CORRUPT, "not a MUS file") + end + r:skip(4) + local len, start, primary, secondary, ninst = r:u16le(), r:u16le(), r:u16le(), r:u16le(), r:u16le() + r:skip(2) + local instruments = {} + for i = 1, ninst do + instruments[i] = r:u16le() + end + if r.err then + return nil, r.err + end + local size = r.limit - r.base + if start > size then + return nil, Err.new(Err.TRUNCATED, "score starts past the end") + end + local p = r.base + start + local events, msg, truncated = score(r.buf, p, math.min(p + len, r.limit), primary, o.maxEvents or 2 ^ 24) + if not events then + return nil, Err.from(msg :: string, p) + end + local last = events[#events].tick + table.insert(events, 1, { tick = 0, type = "meta", meta = 0x51, data = Render.tempoBytes(70, rate) }) + table.insert(events, { tick = last, type = "meta", meta = 0x2F, data = {} }) + local midi = Types.Midi.new(70) + midi.format = 0 + midi.tracks = { { events = events } } + Render.attach(midi, { format = "mus", primaryChannels = primary, secondaryChannels = secondary, instruments = instruments, rate = rate }) + midi.meta.truncated = truncated or p + len > r.limit + return midi, nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Mus.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local midi, err = Mus.decode(r, opts) + if not midi then + return nil, err + end + return Render.decoder(midi, opts) +end + +return Mus +end +__FILES["music/okt"] = function() + +-- music/okt: Oktalyzer modules (OKTASONG, 4..8 channels: each Amiga channel may be a mixed pair), ported from OpenMPT's +-- Load_okt.cpp (BSD, licenses/openmpt-LICENSE.txt); played as the "it" family with Amiga periods, loops as sustain +-- loops (released by R), the three arpeggios and note slides. Not supported: the LED filter (F), writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Chunks = __include("containers/Chunks") +local Tracker = __include("codecs/audio/Tracker") +local Load = __include("codecs/audio/Tracker/Load") + +-- ------------------------------------------------------------------------------------------------ contract +local Okt = { + name = "okt", + category = "music", + extensions = { "okt", "okta" }, + mime = { "audio/x-okt" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 4, 8 } }, +} + +type DecodeOptions = { + maxBytes: number?, -- f32 bytes of sample data in total, default 2^28 +} + +-- ------------------------------------------------------------------------------------------------ constants +local IT = Load.IT +local LAYOUT = table.freeze({ bigEndian = true }) :: Chunks.Layout + +-- ------------------------------------------------------------------------------------------------ sniff +function Okt.sniff(r: Bytes.Reader): number + return if r:peek(8) == "OKTASONG" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function invert(p: number): number + p %= 16 + if p == 0 then + return 0 + end + return if p <= 12 then 12 - p else 24 - p +end + +local function effect(e: number, p: number, paired: boolean): (string?, number, number, boolean) + if e == 1 and p > 0 then + return "portaup", p, -1, false -- "portamento down (period)": the period goes down + elseif e == 2 and p > 0 then + return "portadown", p, -1, false + elseif e == 10 and p > 0 then + return "arpeggio", p % 16 + invert(p // 16) * 16, -1, false -- down, original, up + elseif e == 11 and p > 0 then + return "arpeggio", p - p % 16 + invert(p % 16), -1, false -- original, up, original, down + elseif e == 12 and p > 0 then + return "arpeggio", p, -1, false -- up, up, original + elseif e == 13 and p > 0 then + return "noteslidedown", 0x10 + math.min(p, 15), -1, false + elseif e == 30 and p > 0 then + return "noteslideup", 0x10 + math.min(p, 15), -1, false + elseif e == 21 and p > 0 then + return "noteslidedown", 0x50 + math.min(p, 15), -1, false + elseif e == 17 and p > 0 then + return "noteslideup", 0x50 + math.min(p, 15), -1, false + elseif e == 25 then + return "jump", p, -1, false + elseif e == 27 then + return nil, 0, -1, true + elseif e == 28 and p < 0x20 then + return "speed", p, -1, false + elseif e == 31 then + local x, y = p // 16, p % 16 + local slide = if paired then "chanvolslide" else "volslide" + if p <= 0x40 then + if paired then + return "chanvol", p, -1, false + end + return nil, 0, p, false + elseif x == 4 then + return slide, y, -1, false + elseif x == 5 then + return slide, y * 16, -1, false + elseif x == 6 then + return slide, 0xF0 + math.min(y, 0xE), -1, false + elseif x == 7 then + return slide, math.min(y, 0xE) * 16 + 0xF, -1, false + end + end + return nil, 0, -1, false +end + +function Okt.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local budget = { left = opts and opts.maxBytes or 2 ^ 28 } + if r:peek(8) ~= "OKTASONG" then + return nil, Err.new(if r:size() < 8 then Err.TRUNCATED else Err.CORRUPT, "no OKTASONG signature") + end + local buf = r.buf + local list = Chunks.walk(buf, r.base + 8, r.limit, LAYOUT) + local cmod = Chunks.find(list, "CMOD") + if not cmod or cmod.avail < 8 then + return nil, Err.new(Err.CORRUPT, "no channel table (CMOD)") + end + -- channels: each Amiga channel is one channel, or a mixed pair + local paired: { number } = {} -- 1: the first of a pair, -1: the second, 0: a raw Paula channel + local pans: { number } = {} + for ch = 0, 3 do + local pan = if ch == 1 or ch == 2 then 0xC0 else 0x40 + if buffer.readu16(buf, cmod.offset + ch * 2) ~= 0 then + table.insert(paired, 1) + table.insert(pans, pan) + table.insert(paired, -1) + else + table.insert(paired, 0) + end + table.insert(pans, pan) + end + local nch = #paired + local m = Tracker.newModule("okt", nch, "it") + m.linear = false + m.instrumentMode = false + m.tempo = 125 + m.flags.periods, m.flags.amigaLimits, m.flags.fastPortas, m.flags.oktSlides = "amiga", true, true, true + for i = 1, nch do + m.channelPan[i] = pans[i] + end + -- samples: 32-byte headers (name, length, loop start / length in words, volume, type 0 / 1 / 2) + local types: { number } = {} + local samp = Chunks.find(list, "SAMP") + if samp then + for i = 1, math.min(samp.avail // 32, 36) do + local h = Bytes.reader(buf, samp.offset + (i - 1) * 32, 32) + local s = Tracker.newSample(h:fixed(20)) + local len, ls, ll, vol, typ = h:u32be(), h:u16be() * 2, h:u16be() * 2, h:u16be(), h:u16be() + s.c5speed = 8287 + s.volume = math.min(vol, 64) + s.length = len - len % 2 + if ll > 2 and ls + ll <= s.length then + s.susStart, s.susEnd, s.susType = ls, ls + ll, 1 + end + types[i] = typ + m.samples[i] = s + end + end + local spee = Chunks.find(list, "SPEE") + if spee and spee.avail >= 2 then + m.speed = math.clamp(buffer.readu8(buf, spee.offset) * 256 + buffer.readu8(buf, spee.offset + 1), 1, 255) + end + local nord = 0 + local plen = Chunks.find(list, "PLEN") + if plen and plen.avail >= 2 then + nord = buffer.readu8(buf, plen.offset) * 256 + buffer.readu8(buf, plen.offset + 1) + end + local patt = Chunks.find(list, "PATT") + for i = 1, math.min(nord, if patt then patt.avail else 0) do + m.order[i] = buffer.readu8(buf, (patt :: Chunks.Chunk).offset + i - 1) + end + -- patterns (PBOD: rows, then 4 bytes per cell: note 1..36, sample, effect, parameter) + local copies: { [number]: boolean } = {} -- type B samples with a loop also need an unlooped copy (paired channels) + local npat = 0 + for _, c in list do + if c.id == "PBOD" and npat < 256 then + local pr = Bytes.reader(buf, c.offset, c.avail) + local rows = if c.avail >= 2 then math.clamp(pr:u16be(), 1, 1024) else 64 + local pat = Tracker.newPattern(rows, nch) + npat += 1 + m.patterns[npat] = pat + local d = pat.data + for row = 0, rows - 1 do + for ch = 0, nch - 1 do + local note, ins, e, p = pr:u8(), pr:u8(), pr:u8(), pr:u8() + if pr.err then + break + end + local q = (row * nch + ch) * 5 + local pair = paired[ch + 1] ~= 0 + if note > 0 and note <= 36 then + local n = note + 36 -- note 13 = C-4 = ProTracker period 428 (OpenMPT keeps MOD notes an octave up) + if pair and n >= 49 + 22 then + n = 49 + 21 -- the mixer's highest note + end + local smp = ins + 1 + local s = m.samples[smp] + if s then + if pair and s.volume < 64 then + buffer.writeu8(d, q + 2, 64 + 1) -- the default volume only works on raw Paula channels + end + local t = types[smp] + if (t == 1 and pair) or (t == 0 and not pair) then + smp += 100 -- a sample of the wrong type stops the channel + elseif t == 2 and pair and s.susType > 0 then + copies[smp] = true + smp += 36 + end + end + buffer.writeu8(d, q, n) + buffer.writeu8(d, q + 1, smp) + end + local name, param, vol, off = effect(e, p, pair) + if off then + buffer.writeu8(d, q, 255) + buffer.writeu8(d, q + 1, 0) + end + if vol >= 0 then + buffer.writeu8(d, q + 2, vol + 1) + end + local fx, fp = Load.itEffect(name, param) + if fx ~= 0 then + buffer.writeu8(d, q + 3, fx) + buffer.writeu8(d, q + 4, fp) + if name == "chanvol" or name == "chanvolslide" then + -- a mixed pair shares its volume: the other channel gets it too (the second one wins) + local other = ch + paired[ch + 1] + local o2 = (row * nch + other) * 5 + local ofx = buffer.readu8(d, o2 + 3) + if ofx == 0 or ofx == IT.chanvol or ofx == IT.chanvolslide then + buffer.writeu8(d, o2 + 3, fx) + buffer.writeu8(d, o2 + 4, fp) + end + end + end + end + end + end + end + -- sample data: SBOD chunks in order (signed 8-bit), for the samples with a length + local k = 0 + local bodies: { Chunks.Chunk } = {} + for _, c in list do + if c.id == "SBOD" and c.avail > 0 then + table.insert(bodies, c) + end + end + local nsmp = #m.samples + for i = 1, nsmp do + local s = m.samples[i] + if s.length > 0 then + k += 1 + local c = bodies[k] + if not c then + s.length = 0 + continue + end + local ok, err = Load.readSample(buf, c.offset, math.min(s.length, c.avail), { bits = 8, signed = true, limit = c.offset + c.avail }, s, budget) + if not ok then + return nil, err + end + end + end + for i = 1, nsmp do + local s = m.samples[i] + if copies[i] then + local cp = Tracker.newSample(s.name) + cp.c5speed, cp.volume, cp.data, cp.length = s.c5speed, s.volume, s.data, s.length + m.samples[i + 36] = cp + end + end + for i = 1, (if next(copies) then 72 else nsmp) do + if m.samples[i] == nil then + m.samples[i] = Tracker.newSample() + end + end + m.meta.source = { format = "okt", channels = nch } + local ok, verr = Tracker.validate(m) + if not ok then + return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module") + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Okt.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local m, err = Okt.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return Okt +end +__FILES["music/ptm"] = function() + +-- music/ptm: PolyTracker modules (PTMF, up to 32 channels), ported from OpenMPT's Load_ptm.cpp (BSD, +-- licenses/openmpt-LICENSE.txt); played as the "it" family with Amiga periods, as OpenMPT converts PTM. Not supported: +-- reverse sample offset (K), sample offsets scaled for 16-bit samples, writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Tracker = __include("codecs/audio/Tracker") +local Load = __include("codecs/audio/Tracker/Load") + +-- ------------------------------------------------------------------------------------------------ contract +local Ptm = { + name = "ptm", + category = "music", + extensions = { "ptm" }, + mime = { "audio/x-ptm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 32 } }, +} + +type DecodeOptions = { + maxBytes: number?, -- f32 bytes of sample data in total, default 2^28 +} + +-- ------------------------------------------------------------------------------------------------ constants +-- PolyTracker's effects past MOD's 0..F +local EXTRA = { "globalvol", "retrig", "finevibrato", "noteslideup", "noteslidedown", "noteslideupretrig", "noteslidedownretrig" } + +-- ------------------------------------------------------------------------------------------------ sniff +local function validHeader(r: Bytes.Reader): boolean + if r:size() < 608 or r:peek(4, 44) ~= "PTMF" or r:peekU8(28) ~= 26 or r:peekU8(30) > 2 then + return false + end + local h = r:sub(32, 10) + local nord, nsmp, npat, nch, flags = h:u16le(), h:u16le(), h:u16le(), h:u16le(), h:u16le() + return flags == 0 and nch >= 1 and nch <= 32 and nord >= 1 and nord <= 256 and nsmp >= 1 and nsmp <= 255 and npat >= 1 and npat <= 128 +end + +function Ptm.sniff(r: Bytes.Reader): number + return if validHeader(r) then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- 16-bit samples: the byte stream is 8-bit delta coded, then read as little-endian 16-bit values +local function delta16(buf: buffer, off: number, frames: number, limit: number): (buffer, number) + local n = math.max(0, math.min(frames, (limit - off) // 2)) + local raw = buffer.create(n * 2) + local acc = 0 + for i = 0, n * 2 - 1 do + acc = (acc + buffer.readu8(buf, off + i)) % 256 + buffer.writeu8(raw, i, acc) + end + return raw, n +end + +local function effect(cmd: number, param: number): (string?, number) + if cmd == 0x10 then + return "globalvol", math.min(param, 0x40) * 2 + elseif cmd > 0x10 then + return EXTRA[cmd - 0x10 + 1], param + elseif cmd == 8 then + return "s3mex", 0x80 + (math.max(param // 8, 1) - 1) % 16 -- 8xx pans in 16 steps + end + return Load.modCommand(cmd, param) +end + +-- one pattern (S3M-style packing: 0 ends a row; channel | 0x20 note + instrument, 0x40 effect, 0x80 volume) +local function readPattern(pr: Bytes.Reader, d: buffer, nch: number) + local row = 0 + while row < 64 and not pr:eof() do + local b = pr:u8() + if b == 0 then + row += 1 + else + local ch = b % 32 + local q = (row * nch + ch) * 5 + local ok = ch < nch + if bit32.band(b, 0x20) ~= 0 then + local note, ins = pr:u8(), pr:u8() + if note == 254 then + note = 254 + elseif note == 0 or note > 120 then + note = 0 + end + if ok then + buffer.writeu8(d, q, note) + buffer.writeu8(d, q + 1, ins) + end + end + if bit32.band(b, 0x40) ~= 0 then + local name, param = effect(pr:u8(), pr:u8()) + if ok then + if name == "volume" then + if buffer.readu8(d, q + 2) == 0 then + buffer.writeu8(d, q + 2, math.min(param, 64) + 1) + end + else + local fx, fp = Load.itEffect(name, param) + buffer.writeu8(d, q + 3, fx) + buffer.writeu8(d, q + 4, fp) + end + end + end + if bit32.band(b, 0x80) ~= 0 then + local v = pr:u8() + if ok then + buffer.writeu8(d, q + 2, math.min(v, 64) + 1) + end + end + end + end +end + +function Ptm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local budget = { left = opts and opts.maxBytes or 2 ^ 28 } + if not validHeader(r) then + return nil, Err.new(if r:size() < 608 then Err.TRUNCATED else Err.CORRUPT, "not a PolyTracker module") + end + local title = r:fixed(28) + r:skip(1) + local vlo, vhi = r:u8(), r:u8() + r:skip(1) + local nord, nsmp, npat, nch = r:u16le(), r:u16le(), r:u16le(), r:u16le() + r:seek(64) + local m = Tracker.newModule("ptm", nch, "it") + m.title = title + m.linear = false + m.instrumentMode = false + m.flags.oldEffects, m.flags.compatGxx = true, true + m.flags.panLaw = "ft2" -- OpenMPT plays PTM with its FT2 mix levels + for i = 1, 32 do + local p = r:u8() + if i <= nch then + m.channelPan[i] = (p % 16) * 16 + 4 + end + end + for i = 1, 256 do + local o = r:u8() + if i <= nord then + m.order[i] = o + end + end + local patOff: { number } = {} + for i = 1, 128 do + patOff[i] = r:u16le() * 16 + end + if r.err then + return nil, r.err + end + local buf = r.buf + for i = 1, nsmp do + local h = r:slice(80) + if r.err then + return nil, r.err + end + local flags = h:u8() + h:skip(12) + local vol, c4 = h:u8(), h:u16le() + h:skip(2) + local off, len, ls, le = h:u32le(), h:u32le(), h:u32le(), h:u32le() + h:skip(14) + local s = Tracker.newSample(h:fixed(28)) + m.samples[i] = s + s.volume = math.min(vol, 64) + s.c5speed = math.max(1, c4 * 2) + if flags % 4 == 1 and len > 0 then + local bits = if bit32.band(flags, 0x10) ~= 0 then 16 else 8 + if le > ls then + le -= 1 + end + local frames = len + if bits == 16 then + frames, ls, le = frames // 2, ls // 2, le // 2 + end + local at = r.base + off + if at < r.limit then + local ok, err + if bits == 16 then + local raw, n = delta16(buf, at, frames, r.limit) + ok, err = Load.readSample(raw, 0, n, { bits = 16, signed = true }, s, budget) + else + ok, err = Load.readSample(buf, at, frames, { bits = 8, signed = true, delta = true, limit = r.limit }, s, budget) + end + if not ok then + return nil, err + end + end + if bit32.band(flags, 4) ~= 0 and le > ls then + s.loopStart, s.loopEnd = ls, math.min(le, s.length) + s.loopType = if bit32.band(flags, 8) ~= 0 then 2 else 1 + end + end + end + for p = 1, npat do + local pat = Tracker.newPattern(64, nch) + m.patterns[p] = pat + if patOff[p] > 0 and patOff[p] < r:size() then + readPattern(r:sub(patOff[p]), pat.data, nch) + end + end + m.meta.source = { format = "ptm", version = string.format("%d.%02x", vhi, vlo) } + local ok, verr = Tracker.validate(m) + if not ok then + return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module") + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Ptm.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local m, err = Ptm.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return Ptm +end +__FILES["music/s3m"] = function() + +-- music/s3m: Scream Tracker 3 modules (SCRM, ST3 TECH.DOC). Supports: 32 PCM channels, 8 / 16-bit mono / stereo +-- samples, the panning table, ST3.00 fast slides, every ST3 effect; notes stored an octave up (S3M C-4 = note 61, as IT +-- shows S3M files). Not supported: AdLib (OPL) instruments (silent), writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Tracker = __include("codecs/audio/Tracker") + +-- ------------------------------------------------------------------------------------------------ contract +local S3m = { + name = "s3m", + category = "music", + extensions = { "s3m" }, + mime = { "audio/s3m", "audio/x-s3m" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 32 } }, +} + +type DecodeOptions = { + maxBytes: number?, -- f32 bytes of sample data in total, default 2^28 +} + +-- ------------------------------------------------------------------------------------------------ sniff +function S3m.sniff(r: Bytes.Reader): number + if r:size() >= 48 and r:peek(4, 44) == "SCRM" then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function S3m.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local maxBytes = opts and opts.maxBytes or 2 ^ 28 + if r:size() < 96 then + return nil, Err.new(Err.TRUNCATED, "header") + end + if r:peek(4, 44) ~= "SCRM" then + return nil, Err.new(Err.CORRUPT, "no SCRM signature") + end + local title = r:fixed(28) + r:seek(32) + local ordnum, insnum, patnum = r:u16le(), r:u16le(), r:u16le() + local flags, cwt, ffi = r:u16le(), r:u16le(), r:u16le() + r:seek(48) + local gv, speed, tempo, mv, _uc, dp = r:u8(), r:u8(), r:u8(), r:u8(), r:u8(), r:u8() + r:seek(64) + local chnset: { number } = {} + for i = 1, 32 do + chnset[i] = r:u8() + end + if r.err then + return nil, r.err + end + if ordnum > 256 or insnum > 256 or patnum > 256 then + return nil, Err.new(Err.CORRUPT, "bad header counts") + end + -- channels: enabled PCM channels (0..15); the count is the last used one + local nch = 0 + for i = 1, 32 do + local c = chnset[i] + if c < 16 then + nch = i + end + end + if nch == 0 then + return nil, Err.new(Err.UNSUPPORTED, "no PCM channels (AdLib only)") + end + local m = Tracker.newModule("s3m", nch) + m.title = title + m.speed = if speed > 0 and speed < 255 then speed else 6 + m.tempo = if tempo >= 33 then tempo else 125 + m.globalVolume = math.min(gv, 64) * 2 + m.mixVolume = math.max(mv % 128, 16) + if mv < 128 then + -- mono files play at 8 / 11 of the master volume (ST3's stereo boost is missing; OpenMPT does the same) + m.mixVolume = math.floor(m.mixVolume * 8 / 11 + 0.5) + end + m.linear = false + m.instrumentMode = false + m.flags.fastSlides = cwt == 0x1300 or bit32.band(flags, 64) ~= 0 + m.flags.amigaLimits = bit32.band(flags, 16) ~= 0 + m.meta.source = { format = "s3m", tracker = cwt, stereo = mv >= 128 } + r:seek(96) + for i = 1, ordnum do + local o = r:u8() + table.insert(m.order, o) + end + local insPtr, patPtr = {}, {} + for i = 1, insnum do + insPtr[i] = r:u16le() * 16 + end + for i = 1, patnum do + patPtr[i] = r:u16le() * 16 + end + local pans: { number } = {} + if dp == 252 then + for i = 1, 32 do + pans[i] = r:u8() + end + end + if r.err then + return nil, r.err + end + -- drop trailing end markers; keep inner "+++" / "---" + while #m.order > 0 and m.order[#m.order] == 255 do + table.remove(m.order) + end + local stereo = mv >= 128 + for i = 1, nch do + local c = chnset[i] + local pan = 128 + if stereo then + pan = if c % 16 >= 8 then 0xCC else 0x33 + local p = pans[i] + if p and bit32.band(p, 0x20) ~= 0 then + pan = (p % 16) * 0x11 + end + end + m.channelPan[i] = pan + m.channelMute[i] = c >= 16 + end + local total = 0 + local unsigned = ffi ~= 1 + for i = 1, insnum do + local s = Tracker.newSample() + m.samples[i] = s + local h = r:sub(insPtr[i], 80) + if h:size() < 80 then + return nil, Err.new(Err.TRUNCATED, "sample header " .. i, insPtr[i]) + end + local typ = h:u8() + h:skip(12) + local hi = h:u8() + local lo = h:u16le() + local len, ls, le = h:u32le(), h:u32le(), h:u32le() + local vol = h:u8() + h:skip(1) + local pack, sflags = h:u8(), h:u8() + local c2spd = h:u32le() + h:seek(48) + s.name = h:fixed(28) + s.volume = math.min(vol, 64) + s.c5speed = if c2spd > 0 then c2spd else 8363 + if typ == 1 and len > 0 and pack == 0 then + local bits = if bit32.band(sflags, 4) ~= 0 then 16 else 8 + local nchs = if bit32.band(sflags, 2) ~= 0 then 2 else 1 + local off = (hi * 65536 + lo) * 16 + len = math.min(len, 2 ^ 26) + local avail = math.max(0, r:size() - off) // (nchs * bits // 8) + len = math.min(len, avail) + total += len * nchs * 4 + if total > maxBytes then + return nil, Err.new(Err.LIMIT, "sample data over the maxBytes limit") + end + local data = Tracker.Pcm.decode(r.buf, r.base + off, len, { bits = bits, signed = not unsigned, channels = nchs, planar = true }) + if data then + s.data, s.length, s.bits, s.channels = data, len, bits, nchs + if bit32.band(sflags, 1) ~= 0 and le > ls then + s.loopStart, s.loopEnd, s.loopType = ls, math.min(le, len), 1 + end + end + end + end + for p = 1, patnum do + local pat = Tracker.newPattern(64, nch) + m.patterns[p] = pat + local ptr = patPtr[p] + if ptr > 0 then + local pr = r:sub(ptr) + local plen = pr:u16le() + pr = pr:sub(2, math.max(0, plen - 2)) + local d = pat.data + local row = 0 + while row < 64 and not pr:eof() do + local what = pr:u8() + if what == 0 then + row += 1 + else + local ch = what % 32 + local note, ins, vol, cmd, info = 0, 0, 0, 0, 0 + if bit32.band(what, 0x20) ~= 0 then + local nb = pr:u8() + ins = pr:u8() + if nb == 254 then + note = 254 + elseif nb < 254 and nb % 16 < 12 then + note = (nb // 16) * 12 + nb % 16 + 13 + if note > 120 then + note = 0 + end + end + end + if bit32.band(what, 0x40) ~= 0 then + vol = math.min(pr:u8(), 64) + 1 + end + if bit32.band(what, 0x80) ~= 0 then + cmd = pr:u8() + info = pr:u8() + if cmd > 26 then + cmd, info = 0, 0 + end + end + if ch < nch then + local o = (row * nch + ch) * 5 + buffer.writeu8(d, o, note) + buffer.writeu8(d, o + 1, ins) + buffer.writeu8(d, o + 2, vol) + buffer.writeu8(d, o + 3, cmd) + buffer.writeu8(d, o + 4, info) + end + end + end + end + end + local ok, verr = Tracker.validate(m) + if not ok then + return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module") + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ open +function S3m.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local m, err = S3m.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return S3m +end +__FILES["music/sf2"] = function() + +-- music/sf2: SoundFont 2 banks (SoundFont 2.04 spec), read-only, over codecs/audio/SoundFont (a TinySoundFont port). +-- Supports: INFO, 16 / 24-bit (sm24) samples, presets / instruments with global zones, generators merged into regions. +-- Not supported: writing, SF3 (Vorbis samples), modulators (skipped). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local SoundFont = __include("codecs/audio/SoundFont") + +-- ------------------------------------------------------------------------------------------------ contract +local Sf2 = { + name = "sf2", + category = "music", + extensions = { "sf2" }, + mime = { "audio/x-soundfont" }, + deps = { "core/Err", "core/Bytes", "codecs/audio/SoundFont" }, + caps = { decode = true, encode = false, sm24 = true, sf3 = false }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + maxRegions: number?, -- default 10^6 + maxSamples: number?, -- default 2^28 +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Sf2.sniff(r: Bytes.Reader): number + return if SoundFont.sniff(r) then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Sf2.decode(r: Bytes.Reader, opts: DecodeOptions?): (SoundFont.SoundFont?, Err.Err?) + return SoundFont.parse(r, opts) +end + +-- ------------------------------------------------------------------------------------------------ extras +Sf2.synth = SoundFont.synth +Sf2.fallback = SoundFont.fallback + +return Sf2 +end +__FILES["music/stm"] = function() + +-- music/stm: Scream Tracker 2 modules (STM, "!Scream!" / BMOD2STM / WUZAMOD! / SWavePro), ported from OpenMPT's +-- Load_stm.cpp (BSD, licenses/openmpt-LICENSE.txt); played as the "s3m" family with ST2's tempo, no effect memory and +-- its deferred Bxx. Not supported: STX, ST2's noise for samples at volume 0 (silent), writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Tracker = __include("codecs/audio/Tracker") +local Load = __include("codecs/audio/Tracker/Load") + +-- ------------------------------------------------------------------------------------------------ contract +local Stm = { + name = "stm", + category = "music", + extensions = { "stm" }, + mime = { "audio/x-stm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 4, 4 } }, +} + +type DecodeOptions = { + maxBytes: number?, -- f32 bytes of sample data in total, default 2^28 +} + +-- ------------------------------------------------------------------------------------------------ constants +local IT = Load.IT +-- .ABCDEFGHIJ (K..O do nothing) +local EFFECTS = { "speed", "jump", "break", "volslide", "portadown", "portaup", "toneporta", "vibrato", "tremor", "arpeggio" } + +-- ------------------------------------------------------------------------------------------------ sniff +local function validHeader(r: Bytes.Reader): boolean + if r:size() < 48 then + return false + end + local eof, ftype, major, minor = r:peekU8(28), r:peekU8(29), r:peekU8(30), r:peekU8(31) + local npat, gv = r:peekU8(33), r:peekU8(34) + if ftype ~= 2 or (eof ~= 0x1A and eof ~= 2) or major ~= 2 or (minor ~= 0 and minor ~= 10 and minor ~= 20 and minor ~= 21) then + return false + end + if npat > 64 or (gv > 64 and gv ~= 0x58) then + return false + end + for i = 20, 27 do + local c = r:peekU8(i) + if c < 0x20 or c >= 0x7F then + return false + end + end + return true +end + +function Stm.sniff(r: Bytes.Reader): number + return if validHeader(r) then 0.7 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- a tempo byte of files before ST 2.21 is decimal +local function tempoByte(v: number, minor: number): number + return if minor < 21 then (v // 10) * 16 + v % 10 else v +end + +function Stm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local budget = { left = opts and opts.maxBytes or 2 ^ 28 } + if not validHeader(r) then + return nil, Err.new(if r:size() < 48 then Err.TRUNCATED else Err.CORRUPT, "not a Scream Tracker 2 module") + end + local title = r:fixed(20) + local tracker = r:fixed(8) + r:skip(3) + local minor, initTempo, npat, gv = r:u8(), r:u8(), r:u8(), r:u8() + r:skip(13) + local m = Tracker.newModule("stm", 4, "s3m") + m.title = title + m.linear = false + m.instrumentMode = false + m.flags.st2Tempo = true + initTempo = tempoByte(initTempo, minor) + if initTempo == 0 then + initTempo = 0x60 + end + m.speed, m.tempo = Tracker.st2Tempo(initTempo) + if minor > 10 then + m.globalVolume = math.min(gv, 64) * 2 + end + local offsets: { number } = {} + for i = 1, 31 do + local s = Tracker.newSample(r:fixed(12)) + local zero = r:u8() + r:skip(1) + local off, len, ls, le = r:u16le(), r:u16le(), r:u16le(), r:u16le() + local vol = r:u8() + r:skip(1) + local rate = r:u16le() + r:skip(6) + if r.err then + return nil, r.err + end + if zero ~= 0 and zero ~= 46 then + return nil, Err.new(Err.CORRUPT, "bad sample header " .. i) + end + s.c5speed = if rate > 0 then rate else 8363 + s.volume = math.min(vol, 64) + if len < 2 then + len = 0 + end + if ls < len and le > ls and le ~= 0xFFFF then + s.loopStart, s.loopEnd, s.loopType = ls, le, 1 + len = math.max(le, len) -- ST2 lets a loop run into the next sample's data + end + s.length = len + offsets[i] = off * 16 + m.samples[i] = s + end + for i = 1, (if minor == 0 then 64 else 128) do + local o = r:u8() + if o == 99 or o == 255 then + o = 255 + elseif o > 63 then + return nil, Err.new(Err.CORRUPT, "bad order list") + end + m.order[i] = o + end + if r.err then + return nil, r.err + end + while #m.order > 0 and m.order[#m.order] == 255 do + table.remove(m.order) + end + -- patterns: 64 rows x 4 channels; one byte 0xFB (C-0, volume 0), 0xFC (nothing) or 0xFD (note cut), else 4 bytes + for p = 0, npat - 1 do + local pat = Tracker.newPattern(64, 4) + m.patterns[p + 1] = pat + local d = pat.data + local breakPos, breakRow = -1, 63 -- ST2: Bxx only sets the next order, taken at the pattern's end or a Cxx + for row = 0, 63 do + for ch = 0, 3 do + local q = (row * 4 + ch) * 5 + local note = r:u8() + local insVol, volCmd, info = 0, 0, 0 + if note == 0xFB then + note = 0 -- a C-0 at volume 0 (OpenMPT reads it so) + elseif note == 0xFD then + buffer.writeu8(d, q, 254) + elseif note ~= 0xFC then + insVol, volCmd, info = r:u8(), r:u8(), r:u8() + end + if note ~= 0xFC and note ~= 0xFD then + if note == 0xFE then + buffer.writeu8(d, q, 254) + elseif note < 0x60 then + buffer.writeu8(d, q, (note // 16) * 12 + note % 16 + 37) + end + local ins = insVol // 8 + buffer.writeu8(d, q + 1, if ins > 31 then 0 else ins) + local vol = insVol % 8 + (volCmd // 16) * 8 + if vol <= 64 then + buffer.writeu8(d, q + 2, vol + 1) + end + local name, param = EFFECTS[volCmd % 16], info + if name == "volslide" then + param = if param % 16 > 0 then param % 16 else param - param % 16 + elseif name == "break" then + param = ((param - param % 16) * 10 + param % 16) % 256 + if breakPos >= 0 and param == 0 then + name, param = "jump", breakPos -- Bxx + C00 is a plain Bxx + breakPos = -1 + end + breakRow = math.min(breakRow, row) + if name == "break" then + param = Load.bcd(param) + end + elseif name == "jump" then + breakPos, breakRow = param, 63 + name = nil + elseif name == "speed" then + param = tempoByte(param, minor) + if param == 0 then + name = nil + end + elseif name ~= "tremor" and param == 0 then + name = nil -- no effect memory in ST2 + end + if name then + buffer.writeu8(d, q + 3, IT[name]) + buffer.writeu8(d, q + 4, param) + end + end + end + end + if r.err then + return nil, r.err + end + if breakPos >= 0 then + Load.writeEffect(m, p, breakRow, IT.jump, breakPos, "prev") + end + end + -- sample data: signed 8-bit at the paragraph offsets (samples at volume 0 are not read) + local buf = r.buf + for i = 1, 31 do + local s = m.samples[i] + local len = s.length + s.length = 0 + if len > 0 and s.volume > 0 and offsets[i] > 48 then + local ok, err = Load.readSample(buf, r.base + offsets[i], len, { bits = 8, signed = true, limit = r.limit }, s, budget) + if not ok then + return nil, err + end + end + end + m.meta.source = { format = "stm", tracker = tracker, version = "2." .. minor } + local ok, verr = Tracker.validate(m) + if not ok then + return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module") + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Stm.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local m, err = Stm.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return Stm +end +__FILES["music/ult"] = function() + +-- music/ult: UltraTracker modules (MAS_UTrack_V001 .. V004, up to 32 channels), ported from OpenMPT's Load_ult.cpp +-- (BSD, licenses/openmpt-LICENSE.txt); played as the "it" family with Amiga periods, as OpenMPT converts ULT. Not +-- supported: reverse (5x2), "no loop" (5x1), E0x, offsets past 64 KiB, pre-1.4 log volumes, writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Tracker = __include("codecs/audio/Tracker") +local Load = __include("codecs/audio/Tracker/Load") + +-- ------------------------------------------------------------------------------------------------ contract +local Ult = { + name = "ult", + category = "music", + extensions = { "ult" }, + mime = { "audio/x-ult" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 32 } }, +} + +type DecodeOptions = { + maxBytes: number?, -- f32 bytes of sample data in total, default 2^28 +} + +-- ------------------------------------------------------------------------------------------------ constants +local EFFECTS: { [number]: string } = { + [0] = "arpeggio", [1] = "portaup", [2] = "portadown", [3] = "toneporta", [4] = "vibrato", [7] = "tremolo", + [9] = "offset", [10] = "volslide", [11] = "panning8", [12] = "volume8", [13] = "break", [15] = "speed", +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Ult.sniff(r: Bytes.Reader): number + local v = r:peekU8(14) + if r:size() >= 48 and r:peek(14) == "MAS_UTrack_V00" and v >= 0x31 and v <= 0x34 then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- OpenMPT's TranslateULTCommands +local function translate(e: number, param: number, version: number): (string?, number) + local name = EFFECTS[e] + if e == 0 then + if param == 0 or version < 3 then + name = nil + end + elseif e == 5 then + if (param % 16 == 0xC or param // 16 == 0xC) and version >= 3 then + return "keyoff", 0 + end + elseif e == 7 then + if version < 4 then + name = nil + end + elseif e == 0xA then + if param >= 16 then + param -= param % 16 + end + elseif e == 0xB then + param = (param % 16) * 0x11 + elseif e == 0xD then + param = 10 * (param // 16) + param % 16 + elseif e == 0xE then + local x, y = param // 16, param % 16 + if x == 1 then + return "portaup", 0xF0 + y + elseif x == 2 then + return "portadown", 0xF0 + y + elseif x == 8 and version >= 4 then + return "s3mex", 0x60 + y + elseif x == 9 then + return "retrig", y + elseif x == 0xA then + return "volslide", y * 16 + 0xF + elseif x == 0xB then + return "volslide", 0xF0 + y + elseif x == 0xC or x == 0xD then + return "s3mex", param + end + return nil, param + elseif e == 0xF then + if param > 0x2F then + name = "tempo" + end + end + return name, param +end + +-- OpenMPT's CombineEffects (volume slide + vibrato / tone portamento without a parameter) +local function combine(a: string?, pa: number, b: string?, pb: number): (string?, number, string?, number) + if a == "volslide" and (b == "vibrato" or b == "toneportavol") and pb == 0 then + return if b == "vibrato" then "vibratovol" else "toneportavol", pa, nil, 0 + elseif b == "volslide" and (a == "vibrato" or a == "toneportavol") and pa == 0 then + return if a == "vibrato" then "vibratovol" else "toneportavol", pb, nil, 0 + end + return a, pa, b, pb +end + +-- event: [0xFC repeat] note instrument effects param1 param2 +local function readEvent(r: Bytes.Reader, version: number): (number, number, number, number, number, number, string?, number) + local rep = 1 + local b = r:u8() + if b == 0xFC then + rep = r:u8() + b = r:u8() + end + local note = if b > 0 and b < 97 then b + 24 else 0 + local ins, cmd, p1, p2 = r:u8(), r:u8(), r:u8(), r:u8() + local c1, q1 = translate(cmd % 16, p1, version) + local c2, q2 = translate(cmd // 16, p2, version) + if c1 == "offset" and c2 == "offset" then + local off = (p2 * 256 + p1) // 64 + return rep, note, ins, 0, Load.IT.offset, off % 256, nil, 0 + elseif c1 == "offset" then + q1 = math.min(p1 * 4, 255) + elseif c2 == "offset" then + q2 = math.min(p2 * 4, 255) + elseif c1 ~= nil and c1 == c2 then + c2 = nil + end + if c2 == nil then -- (OpenMPT also swaps for CMD_VOLUME, which ULT never produces) + c1, q1, c2, q2 = c2, q2, c1, q1 + end + c2, q2, c1, q1 = combine(c2, q2, c1, q1) + if c1 == "keyoff" or c2 == "keyoff" then + -- key off (5xC): a note-off when the cell has no note + if note == 0 then + note = 255 + end + if c1 == "keyoff" then + c1 = nil + else + c2 = nil + end + end + local vol, name, param, lost, lostParam = Load.fillTwo(c1, q1, c2, q2) + local fx, fp = Load.itEffect(name, param) + return rep, note, ins, vol, fx, fp, lost, lostParam +end + +function Ult.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local budget = { left = opts and opts.maxBytes or 2 ^ 28 } + if Ult.sniff(r) == 0 then + return nil, Err.new(if r:size() < 48 then Err.TRUNCATED else Err.CORRUPT, "not an UltraTracker module") + end + r:skip(14) + local version = r:u8() - 0x30 + local title = (string.gsub(r:fixed(32), " +$", "")) + local lines = r:u8() + local message = r:string(lines * 32) + local nsmp = r:u8() + if r.err then + return nil, r.err + end + local samples, sizes = {}, {} + for i = 1, nsmp do + local s = Tracker.newSample((string.gsub(r:fixed(32), " +$", ""))) + r:skip(12) + local ls, le, ss, se = r:u32le(), r:u32le(), r:u32le(), r:u32le() + local vol, flags = r:u8(), r:u8() + local speed, finetune = 8363, 0 + if version >= 4 then + speed, finetune = r:u16le(), r:i16le() + else + finetune = r:i16le() + end + if r.err then + return nil, r.err + end + local bits = if bit32.band(flags, 4) ~= 0 then 16 else 8 + s.bits = bits + sizes[i] = 0 + if se > ss then + s.length = se - ss + sizes[i] = s.length * bits // 8 + s.volume = vol / 4 + s.c5speed = math.max(1, speed * 2 * 2 ^ (finetune / (12 * 32768))) + if bit32.band(flags, 8) ~= 0 then + if bits == 16 then + ls, le = ls // 2, le // 2 + end + s.susStart, s.susEnd = ls, le + s.susType = if bit32.band(flags, 16) ~= 0 then 2 else 1 + end + end + samples[i] = s + end + local order = {} + for i = 1, 256 do + order[i] = r:u8() + end + local nch, npat = r:u8() + 1, r:u8() + 1 + if r.err then + return nil, r.err + end + if nch > 32 then + return nil, Err.new(Err.UNSUPPORTED, nch .. " channels") + end + local m = Tracker.newModule("ult", nch, "it") + m.title = title + m.meta.message = message + m.linear = false + m.instrumentMode = false + m.flags.oldEffects, m.flags.compatGxx, m.flags.autoTonePorta = true, true, true + m.samples = samples + for i = 1, 256 do + m.order[i] = order[i] + end + while #m.order > 0 and m.order[#m.order] == 255 do + table.remove(m.order) + end + for i = 1, nch do + m.channelPan[i] = if version >= 3 then (r:u8() % 16) * 16 + 8 elseif i % 2 == 0 then 192 else 64 + end + for p = 1, npat do + m.patterns[p] = Tracker.newPattern(64, nch) + end + -- events, channel by channel, pattern by pattern + local speed0 = false + for ch = 0, nch - 1 do + for p = 0, npat - 1 do + if r:remaining() < 5 then + break + end + local d = m.patterns[p + 1].data + local row = 0 + while row < 64 do + local rep, note, ins, vol, fx, param, lost, lostParam = readEvent(r, version) + if r.err then + break + end + if lost and Load.isGlobal(lost, lostParam) then + local lf, lp = Load.itEffect(lost, lostParam) + Load.writeEffect(m, p, row, lf, lp, "next") + end + rep = math.min(rep, 64 - row) + if rep == 0 then + break + end + if fx == Load.IT.speed and param == 0 then + speed0 = true + end + for _ = 1, rep do + local q = (row * nch + ch) * 5 + buffer.writeu8(d, q, note) + buffer.writeu8(d, q + 1, ins) + buffer.writeu8(d, q + 2, vol) + buffer.writeu8(d, q + 3, fx) + buffer.writeu8(d, q + 4, param) + row += 1 + end + end + end + end + r.err = nil + if speed0 then + -- speed 0 resets the song speed and tempo (UltraTracker) + for p, pat in m.patterns do + for row = 0, 63 do + for ch = 0, nch - 1 do + local q = (row * nch + ch) * 5 + if buffer.readu8(pat.data, q + 3) == Load.IT.speed and buffer.readu8(pat.data, q + 4) == 0 then + buffer.writeu8(pat.data, q + 4, 6) + Load.writeEffect(m, p - 1, row, Load.IT.tempo, 125, "next") + end + end + end + end + end + -- sample data: signed 8 / 16-bit + local pos = r.pos + for i = 1, nsmp do + local s = samples[i] + if sizes[i] > 0 then + local ok, err = Load.readSample(r.buf, pos, s.length, { bits = s.bits, signed = true, limit = r.limit }, s, budget) + if not ok then + return nil, err + end + pos += sizes[i] + end + end + m.meta.source = { format = "ult", version = version } + local ok, verr = Tracker.validate(m) + if not ok then + return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module") + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Ult.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local m, err = Ult.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return Ult +end +__FILES["music/umx"] = function() + +-- music/umx: Unreal Engine 1 music packages (.umx, versions up to 128), ported from OpenMPT's UMXTools.cpp / +-- ContainerUMX.cpp (BSD, licenses/openmpt-LICENSE.txt): the IT / S3M / XM / MOD module of a "music" export; decode +-- needs opts.decodeModule (the api passes it). Not supported: Unreal Engine 2+ packages (.uax), writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Tracker = __include("codecs/audio/Tracker") + +-- ------------------------------------------------------------------------------------------------ contract +local Umx = { + name = "umx", + category = "music", + extensions = { "umx" }, + mime = { "audio/x-umx" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" }, + caps = { decode = true, encode = false, render = true, container = true }, +} + +type DecodeOptions = { + decodeModule: ((buf: buffer, format: string?) -> (any, Err.Err?))?, + index: number?, -- 1-based, default 1 +} + +type Entry = { name: string, data: buffer, format: string? } + +-- ------------------------------------------------------------------------------------------------ constants +local MAGIC = "\xC1\x83\x2A\x9E" + +-- ------------------------------------------------------------------------------------------------ sniff +type Header = { version: number, nameCount: number, nameOffset: number, exportCount: number, exportOffset: number, importCount: number, importOffset: number } + +local function header(r: Bytes.Reader): Header? + if r:size() < 36 or r:peek(4) ~= MAGIC then + return nil + end + local h = r:sub(4, 32) + local version = h:u16le() + h:skip(6) + local hd: Header = { + version = version, + nameCount = h:u32le(), + nameOffset = h:u32le(), + exportCount = h:u32le(), + exportOffset = h:u32le(), + importCount = h:u32le(), + importOffset = h:u32le(), + } + if h.err or hd.nameOffset < 36 or hd.exportOffset < 36 or hd.importOffset < 36 then + return nil + end + if hd.nameCount == 0 or hd.exportCount == 0 or hd.importCount == 0 or hd.nameCount > 2 ^ 20 or hd.exportCount > 2 ^ 20 or hd.importCount > 2 ^ 20 then + return nil + end + return hd +end + +-- a compact index: sign and 6 bits, then 7 bits per byte while the continue bits are set +local function index(r: Bytes.Reader): number + local b = r:u8() + local neg = b >= 0x80 + local v = b % 64 + if bit32.band(b, 0x40) ~= 0 then + local shift = 6 + repeat + b = r:u8() + v += (b % 128) * 2 ^ shift + shift += 7 + until b < 0x80 or shift >= 32 + end + return if neg then -v else v +end + +-- the name table (lower case) +local function names(r: Bytes.Reader, h: Header): { string } + local list = {} + local nr = r:sub(h.nameOffset) + for _ = 1, math.min(h.nameCount, 65536) do + if nr:remaining() < 5 then + break + end + if h.version >= 64 then + index(nr) + end + table.insert(list, string.lower(nr:cstring(1024))) + nr:skip(4) + end + return list +end + +function Umx.sniff(r: Bytes.Reader): number + local h = header(r) + if not h then + return 0 + end + return if table.find(names(r, h), "music") then 1 else 0.3 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Umx.extract(r: Bytes.Reader): ({ Entry }?, Err.Err?) + local h = header(r) + if not h then + return nil, Err.new(if r:size() < 36 then Err.TRUNCATED else Err.CORRUPT, "not an Unreal package") + end + local nm = names(r, h) + -- imports: the class names objects refer to + local classes = {} + local ir = r:sub(h.importOffset) + for _ = 1, math.min(h.importCount, 65536) do + if ir:remaining() < 4 then + break + end + index(ir) + index(ir) + if h.version >= 60 then + ir:skip(4) + else + index(ir) + end + local obj = index(ir) + if obj >= 0 and obj < #nm then + table.insert(classes, obj) + end + end + local out: { Entry } = {} + local er = r:sub(h.exportOffset) + for _ = 1, math.min(h.exportCount, 65536) do + if er:remaining() < 8 then + break + end + local cls = -index(er) - 1 -- ~index: the import the class is + index(er) + if h.version >= 60 then + er:skip(4) + end + local objName = index(er) + er:skip(4) + local size, offset = index(er), index(er) + if er.err then + break + end + if cls >= 0 and cls < #classes and nm[classes[cls + 1] + 1] == "music" and size > 0 and offset > 36 then + local c = r:sub(offset, size) + if h.version < 40 then + c:skip(8) + end + if h.version < 60 then + c:skip(16) + end + index(c) -- the property list's "none" + if h.version >= 120 then + index(c) + c:skip(8) + elseif h.version >= 100 then + c:skip(4) + index(c) + c:skip(4) + elseif h.version >= 62 then + index(c) + c:skip(4) + else + index(c) + end + local len = index(c) + if not c.err and len > 0 and len <= c:remaining() then + local data = c:bytes(len) + local sig = Bytes.reader(data) + local fmt = if sig:peek(4) == "IMPM" then "it" elseif sig:peek(4, 44) == "SCRM" then "s3m" elseif sig:peek(17) == "Extended Module: " then "xm" elseif buffer.len(data) >= 1084 then "mod" else nil + table.insert(out, { name = nm[objName + 1] or "", data = data, format = fmt }) + end + end + end + return out, nil +end + +function Umx.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local list, err = Umx.extract(r) + if not list then + return nil, err + end + local i = opts and opts.index or 1 + local e = list[i] + if not e then + return nil, Err.new(Err.CORRUPT, "no music export" .. (if i > 1 then " " .. i else "")) + end + local hook = opts and opts.decodeModule + if type(hook) ~= "function" then + return nil, Err.new(Err.UNSUPPORTED, "the embedded " .. (e.format or "tracker") .. " module needs opts.decodeModule (F.load passes it; Umx.extract gives the bytes)") + end + local m, merr = hook(e.data, nil) + if not m then + return nil, merr + end + if type(m) ~= "table" or m.kind ~= "music" then + return nil, Err.new(Err.UNSUPPORTED, "the embedded module is not a tracker module") + end + local h = header(r) :: Header + m.meta = if type(m.meta) == "table" then m.meta else {} + m.meta.container = { format = "umx", name = e.name, version = h.version, count = #list } + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Umx.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local m, err = Umx.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return Umx +end +__FILES["music/xm"] = function() + +-- music/xm: FastTracker 2 Extended Modules (XM 1.04), from the XM spec and FT2 behaviour notes. Supports: 8 / 16-bit +-- delta and ModPlug ADPCM samples, envelopes, linear / Amiga tables, every FT2 effect; writes "xm" (byte-identical in +-- FT2's layout) and "mod" modules. Not supported: OpenMPT's stereo-sample / extra-effect extensions on write. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Tracker = __include("codecs/audio/Tracker") +local Adpcm = __include("codecs/audio/Adpcm") + +-- ------------------------------------------------------------------------------------------------ contract +local Xm = { + name = "xm", + category = "music", + extensions = { "xm" }, + mime = { "audio/xm", "audio/x-xm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Adpcm" }, + caps = { decode = true, encode = true, render = true, channels = { 1, 64 } }, +} + +type DecodeOptions = { + maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) +} +type EncodeOptions = { + tracker: string?, -- the tracker name field (default: the source file's, else "rosetta") +} + +-- ------------------------------------------------------------------------------------------------ constants +local MAGIC = "Extended Module: " +local Pcm = Tracker.Pcm + +-- ------------------------------------------------------------------------------------------------ sniff +function Xm.sniff(r: Bytes.Reader): number + return if r:peek(17) == MAGIC then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function readEnvelope(r: Bytes.Reader): ({ number }, { number }) + local xs, ys = {}, {} + for i = 1, 12 do + xs[i] = r:u16le() + ys[i] = r:u16le() + end + return xs, ys +end + +local function makeEnvelope(xs: { number }, ys: { number }, n: number, typ: number, sus: number, ls: number, le: number, pan: boolean): any + local e = Tracker.newEnvelope() + n = math.min(n, 12) + for i = 1, n do + e.ticks[i] = xs[i] + e.values[i] = if pan then math.clamp(ys[i], 0, 64) - 32 else math.clamp(ys[i], 0, 64) + end + e.enabled = bit32.band(typ, 1) ~= 0 and n > 0 + e.sustain = bit32.band(typ, 2) ~= 0 + e.loop = bit32.band(typ, 4) ~= 0 + e.susStart, e.susEnd = sus + 1, sus + 1 + e.loopStart, e.loopEnd = ls + 1, le + 1 + e.raw = { type = typ, sustain = sus, loopStart = ls, loopEnd = le, count = n } + return e +end + +function Xm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local maxBytes = opts and opts.maxBytes or 2 ^ 28 + if r:peek(17) ~= MAGIC then + return nil, Err.new(Err.CORRUPT, "no XM signature") + end + r:skip(17) + local title = r:fixed(20) + r:skip(1) + local tracker = r:fixed(20) + local version = r:u16le() + local hdrStart = r:tell() + local hdrSize = r:u32le() + local songLen, restart, nch, npat, nins = r:u16le(), r:u16le(), r:u16le(), r:u16le(), r:u16le() + local flags, speed, bpm = r:u16le(), r:u16le(), r:u16le() + local orders = {} + for i = 1, 256 do + orders[i] = r:u8() + end + if r.err then + return nil, r.err + end + if nch < 1 or nch > 128 or npat > 256 or nins > 256 or songLen > 256 then + return nil, Err.new(Err.CORRUPT, "bad header counts") + end + if version < 0x0104 then + return nil, Err.new(Err.UNSUPPORTED, string.format("XM version %x (only 1.04 is supported)", version)) + end + local m = Tracker.newModule("xm", nch) + m.title = title + m.speed = if speed > 0 and speed < 256 then speed else 6 + m.tempo = if bpm >= 32 and bpm <= 999 then bpm else 125 + m.linear = bit32.band(flags, 1) ~= 0 + m.restart = restart + for i = 1, songLen do + m.order[i] = orders[i] + end + m.meta.tracker = tracker + m.meta.source = { format = "xm", tracker = tracker, version = version } + if not r:seek(hdrStart + hdrSize) then + return nil, r.err + end + for p = 1, npat do + local start = r:tell() + local plen = r:u32le() + r:u8() + local rows = r:u16le() + local psize = r:u16le() + if r.err then + return nil, r.err + end + if rows < 1 or rows > 256 then + return nil, Err.new(Err.CORRUPT, "pattern " .. (p - 1) .. " has " .. rows .. " rows", r.pos) + end + r:seek(start + plen) + local pat = Tracker.newPattern(rows, nch) + m.patterns[p] = pat + local pr = r:slice(psize) + if r.err then + return nil, r.err + end + local d = pat.data + if psize > 0 then + for i = 0, rows * nch - 1 do + local b = pr:u8() + local note, ins, vol, fx, param = 0, 0, 0, 0, 0 + if b >= 128 then + if bit32.band(b, 1) ~= 0 then + note = pr:u8() + end + if bit32.band(b, 2) ~= 0 then + ins = pr:u8() + end + if bit32.band(b, 4) ~= 0 then + vol = pr:u8() + end + if bit32.band(b, 8) ~= 0 then + fx = pr:u8() + end + if bit32.band(b, 16) ~= 0 then + param = pr:u8() + end + else + note = b + ins = pr:u8() + vol = pr:u8() + fx = pr:u8() + param = pr:u8() + end + if pr.err then + break + end + if note == 97 then + note = 255 + elseif note > 96 then + note = 0 + end + if fx > 35 then + fx, param = 0, 0 + end + local o = i * 5 + buffer.writeu8(d, o, note) + buffer.writeu8(d, o + 1, ins) + buffer.writeu8(d, o + 2, vol) + buffer.writeu8(d, o + 3, fx) + buffer.writeu8(d, o + 4, param) + end + end + end + local total = 0 + for i = 1, nins do + local start = r:tell() + local isize = r:u32le() + local ins = Tracker.newInstrument(r:fixed(22)) + r:u8() + local ns = r:u16le() + if r.err then + r.err = nil + break + end + m.instruments[i] = ins + ins.samples = {} + if ns == 0 then + r:seek(start + math.max(isize, 29)) + continue + end + if ns > 256 then + return nil, Err.new(Err.CORRUPT, "instrument " .. i .. " has " .. ns .. " samples") + end + local shSize = r:u32le() + local keymap = {} + for n = 1, 96 do + keymap[n] = r:u8() + end + local vx, vy = readEnvelope(r) + local px, py = readEnvelope(r) + local nv, np = r:u8(), r:u8() + local vs, vls, vle, ps, pls, ple = r:u8(), r:u8(), r:u8(), r:u8(), r:u8(), r:u8() + local vt, pt = r:u8(), r:u8() + ins.vibType, ins.vibSweep, ins.vibDepth, ins.vibRate = r:u8(), r:u8(), r:u8(), r:u8() + ins.fadeout = r:u16le() + if r.err then + return nil, r.err + end + ins.volEnv = makeEnvelope(vx, vy, nv, vt, vs, vls, vle, false) + ins.panEnv = makeEnvelope(px, py, np, pt, ps, pls, ple, true) + ins.headerSize = isize + r:seek(start + isize) + local base = #m.samples + local heads = {} + for k = 1, ns do + local hs = r:tell() + local len, ls, ll = r:u32le(), r:u32le(), r:u32le() + local vol, ft, typ, pan, rel, res = r:u8(), r:i8(), r:u8(), r:u8(), r:i8(), r:u8() + local nm = r:fixed(22) + r:seek(hs + math.max(shSize, 40)) + heads[k] = { len = len, ls = ls, ll = ll, vol = vol, ft = ft, typ = typ, pan = pan, rel = rel, res = res, name = nm } + end + if r.err then + return nil, r.err + end + for k = 1, ns do + local h = heads[k] + local s = Tracker.newSample(h.name) + local bits = if bit32.band(h.typ, 16) ~= 0 then 16 else 8 + local bps = bits // 8 + s.bits = bits + s.volume = math.min(h.vol, 64) + s.finetune = h.ft + s.relativeNote = h.rel + s.pan = h.pan + local frames = h.len // bps + if h.res == 0xAD and bits == 8 then +-- ModPlug ADPCM: a 16-byte delta table, then 4 bits per sample + frames = math.max(0, math.min(h.len, (r:remaining() - 16) * 2)) + total += frames * 4 + if total > maxBytes then + return nil, Err.new(Err.LIMIT, "sample data over the maxBytes limit") + end + s.data = buffer.create(frames * 4) + if frames > 0 then + Adpcm.modplug(r.buf, r.pos, frames, s.data, 0) + end + r:skip(math.min(16 + (h.len + 1) // 2, r:remaining())) + else + local avail = r:remaining() // bps + local got = math.min(frames, avail) + total += got * 4 + if total > maxBytes then + return nil, Err.new(Err.LIMIT, "sample data over the maxBytes limit") + end + local data = Pcm.decode(r.buf, r.pos, got, { bits = bits, signed = true, delta = true }) + r:skip(got * bps) + s.data = data or buffer.create(0) + frames = if data then got else 0 + end + s.length = frames + local lt = h.typ % 4 + if lt == 3 then + lt = 2 + end + if lt > 0 and h.ll > 0 then + s.loopStart = h.ls // bps + s.loopEnd = (h.ls + h.ll) // bps + s.loopType = lt + end + m.samples[base + k] = s + table.insert(ins.samples, base + k) + end + for n = 1, 120 do + local k = keymap[math.min(n, 96)] + ins.sampleMap[n] = if n <= 96 and k < ns then base + k + 1 else 0 + end + ins.keymap = keymap + end + local ok, verr = Tracker.validate(m) + if not ok then + return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module") + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function writeName(w: Bytes.Writer, s: string?, n: number) + local t = string.sub(s or "", 1, n) + w:string(t) + w:fill(0, n - #t) +end + +local function instrumentsOf(m: any): ({ any }?, string?) + local out = {} + if m.format == "mod" then + for i, s in m.samples do + local km = table.create(96, 0) + out[i] = { name = s.name, samples = if s.length > 0 then { s } else {}, keymap = km, ins = nil } + end + return out + end + for i, ins in m.instruments do + local list: { number } = {} + if type(ins.samples) == "table" then + for _, g in ins.samples do + table.insert(list, g) + end + end + local index: { [number]: number } = {} + for k, g in list do + index[g] = k - 1 + end + local km = table.create(96, 0) + for n = 1, 96 do + local g = ins.sampleMap[n] or 0 + if g > 0 and m.samples[g] then + if index[g] == nil then + table.insert(list, g) + index[g] = #list - 1 + end + km[n] = index[g] + end + end + if #list > 255 then + return nil, "instrument " .. i .. " uses more than 255 samples" + end + local smps = {} + for k, g in list do + smps[k] = m.samples[g] or Tracker.newSample() + end + out[i] = { name = ins.name, samples = smps, keymap = km, ins = ins } + end + return out +end + +local function writeEnvelope(w: Bytes.Writer, e: any, pan: boolean) + local n = if e then math.min(#e.ticks, 12) else 0 + for i = 1, 12 do + if i <= n then + w:u16le(math.clamp(math.floor(e.ticks[i]), 0, 65535)) + w:u16le(math.clamp(math.floor(e.values[i] + (if pan then 32 else 0) + 0.5), 0, 64)) + else + w:u32le(0) + end + end +end + +-- envelope count, type, sustain, loop start, loop end +local function envelopeFields(e: any): (number, number, number, number, number) + if not e then + return 0, 0, 0, 0, 0 + end + local n = math.min(#e.ticks, 12) + local typ = (if e.enabled then 1 else 0) + (if e.sustain then 2 else 0) + (if e.loop then 4 else 0) + local raw = e.raw + if raw and raw.type % 8 == typ then + typ = raw.type + end + local function idx(v: number): number + return math.clamp(math.floor(v) - 1, 0, math.max(0, n - 1)) + end + local sus = idx(e.susStart) + local ls, le = idx(e.loopStart), idx(e.loopEnd) + if raw and n == 0 then + sus, ls, le = raw.sustain, raw.loopStart, raw.loopEnd + end + return n, typ, sus, ls, le +end + +function Xm.encode(m: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local ok, verr = Tracker.validate(m) + if not ok then + return nil, verr + end + if m.format ~= "xm" and m.format ~= "mod" then + return nil, Err.new(Err.UNSUPPORTED, "only xm and mod modules can be written as XM (got " .. tostring(m.format) .. ")") + end + local nch = m.channels + if nch > 64 then + return nil, Err.new(Err.ARG, "XM holds at most 64 channels") + end + local insts, ierr = instrumentsOf(m) + if not insts then + return nil, Err.new(Err.ARG, ierr or "bad instruments") + end + if #insts > 128 then + return nil, Err.new(Err.ARG, "XM holds at most 128 instruments") + end + if #m.patterns > 256 then + return nil, Err.new(Err.ARG, "XM holds at most 256 patterns") + end + local order: { number } = {} + for _, o in m.order do + if o == 255 then + break + elseif o ~= 254 then + table.insert(order, o) + end + end + if #order > 256 then + return nil, Err.new(Err.ARG, "XM holds at most 256 order entries") + end + local w = Bytes.writer(65536) + w:string(MAGIC) + writeName(w, m.title, 20) + w:u8(0x1A) + writeName(w, opts and opts.tracker or (m.meta and m.meta.tracker) or "rosetta", 20) + w:u16le(0x0104) + w:u32le(276) + w:u16le(#order) + w:u16le(if m.restart < #order then m.restart else 0) + w:u16le(nch) + w:u16le(#m.patterns) + w:u16le(#insts) + w:u16le(if m.linear then 1 else 0) + w:u16le(m.speed) + w:u16le(math.clamp(math.floor(m.tempo), 32, 999)) + for i = 1, 256 do + w:u8(order[i] or 0) + end + -- patterns (every cell packed, as FT2-compatible writers may) + for _, pat in m.patterns do + local pk = Bytes.writer(pat.rows * nch * 2) + local d = pat.data + for i = 0, pat.rows * nch - 1 do + local o = i * 5 + local note, ins, vol, fx, param = buffer.readu8(d, o), buffer.readu8(d, o + 1), buffer.readu8(d, o + 2), buffer.readu8(d, o + 3), buffer.readu8(d, o + 4) + if note == 255 then + note = 97 + elseif note > 96 then + note = 0 + end + if m.format == "mod" then + vol = 0 + if fx > 15 then + fx, param = 0, 0 + end + end + if ins > 128 then + ins = 0 + end + local flags = 0x80 + (if note > 0 then 1 else 0) + (if ins > 0 then 2 else 0) + (if vol > 0 then 4 else 0) + (if fx > 0 then 8 else 0) + (if param > 0 then 16 else 0) + pk:u8(flags) + if note > 0 then + pk:u8(note) + end + if ins > 0 then + pk:u8(ins) + end + if vol > 0 then + pk:u8(vol) + end + if fx > 0 then + pk:u8(fx) + end + if param > 0 then + pk:u8(param) + end + end + local data = pk:finish() + if buffer.len(data) > 65535 then + return nil, Err.new(Err.ARG, "a pattern packs to more than 64 KB") + end + w:u32le(9) + w:u8(0) + w:u16le(pat.rows) + w:u16le(buffer.len(data)) + w:bytes(data) + end + for _, it in insts do + local ins = it.ins + local smps = it.samples + if #smps == 0 then + w:u32le(29) + writeName(w, it.name, 22) + w:u8(0) + w:u16le(0) + continue + end + w:u32le(263) + writeName(w, it.name, 22) + w:u8(0) + w:u16le(#smps) + w:u32le(40) + for n = 1, 96 do + w:u8(it.keymap[n]) + end + local ve, pe = ins and ins.volEnv, ins and ins.panEnv + writeEnvelope(w, ve, false) + writeEnvelope(w, pe, true) + local vn, vt, vs, vls, vle = envelopeFields(ve) + local pn, pt, ps, pls, ple = envelopeFields(pe) + w:u8(vn) + w:u8(pn) + w:u8(vs) + w:u8(vls) + w:u8(vle) + w:u8(ps) + w:u8(pls) + w:u8(ple) + w:u8(vt) + w:u8(pt) + w:u8(ins and ins.vibType or 0) + w:u8(ins and ins.vibSweep or 0) + w:u8(ins and ins.vibDepth or 0) + w:u8(ins and ins.vibRate or 0) + w:u16le(ins and math.clamp(ins.fadeout, 0, 0xFFF) or 0) + w:fill(0, 22) + local datas = {} + for k, s in smps do + local mono = s.data + if s.channels == 2 then + mono = buffer.create(s.length * 4) + for f = 0, s.length - 1 do + buffer.writef32(mono, f * 4, (buffer.readf32(s.data, f * 8) + buffer.readf32(s.data, f * 8 + 4)) / 2) + end + end + local bits = if s.bits == 16 then 16 else 8 + local bps = bits // 8 + datas[k] = Pcm.encode(mono, s.length, { bits = bits, signed = true, delta = true }) + local typ = (if bits == 16 then 16 else 0) + local ls, ll = 0, 0 + if s.loopType > 0 then + typ += s.loopType + ls, ll = s.loopStart * bps, (s.loopEnd - s.loopStart) * bps + end + local ft = s.finetune + local rel = s.relativeNote + if m.format == "mod" then + rel = 0 + end + w:u32le(s.length * bps) + w:u32le(ls) + w:u32le(ll) + w:u8(math.clamp(math.floor(s.volume), 0, 64)) + w:u8(math.clamp(math.floor(ft), -128, 127) % 256) + w:u8(typ) + w:u8(math.clamp(math.floor(s.pan or 128), 0, 255)) + w:u8(math.clamp(math.floor(rel), -128, 127) % 256) + w:u8(0) + writeName(w, s.name, 22) + end + for _, dd in datas do + w:bytes(dd) + end + end + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Xm.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local m, err = Xm.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return Xm +end +__FILES["music/xmi"] = function() + +-- music/xmi: Miles XMIDI (IFF: optional FORM XDIR, then CAT XMID of FORM XMID songs with TIMB / RBRN / EVNT), from +-- the XMIDI notes (Miles AIL, Ryan Nunn; wildmidi only as a test reference). Decodes one song to a Types.Midi at the +-- fixed 120 ticks per second (division 60). Not supported: writing, the RBRN branch table, MT-32 -> GM mapping. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Chunks = __include("containers/Chunks") +local Render = __include("codecs/audio/MidiRender") + +-- ------------------------------------------------------------------------------------------------ contract +local Xmi = { + name = "xmi", + category = "music", + extensions = { "xmi", "xmidi" }, + mime = { "audio/x-xmidi" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/audio/MidiRender" }, + caps = { decode = true, encode = false, render = true, songs = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + track: number?, -- the song (1-based), default 1 + maxEvents: number?, -- default 2^24 +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Xmi.sniff(r: Bytes.Reader): number + local id, kind = r:peek(4), r:peek(4, 8) + if id == "FORM" and (kind == "XDIR" or kind == "XMID") then + return 1 + end + return if id == "CAT " and kind == "XMID" then 0.9 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local readu8 = buffer.readu8 +local DATA = { [8] = 2, [9] = 2, [10] = 2, [11] = 2, [12] = 1, [13] = 1, [14] = 2 } +local TYPES = { [8] = "noteOff", [9] = "noteOn", [10] = "aftertouch", [11] = "controller", [12] = "program", [13] = "channelPressure", [14] = "pitchBend" } + +local function vlq(b: buffer, p: number, e: number): (number?, number) + local v = 0 + for _ = 1, 4 do + if p >= e then + return nil, p + end + local c = readu8(b, p) + p += 1 + v = v * 128 + c % 128 + if c < 128 then + return v, p + end + end + return nil, p +end + +local function bytes(b: buffer, p: number, n: number): { number } + local t: { number } = table.create(n) :: { number } + for i = 1, n do + t[i] = readu8(b, p + i - 1) + end + return t +end + +local function events(b: buffer, p: number, e: number, maxEvents: number): ({ Types.MidiEvent }?, any, number?) + local list: { Types.MidiEvent }, offs: { Render.PendingOff } = {}, {} + local tick, tempo = 0, nil + while p < e do + local st = readu8(b, p) + p += 1 + if st < 0x80 then + tick += st + elseif st == 0xFF then + if p >= e then + return nil, "truncated meta event" + end + local kind = readu8(b, p) + local n, q = vlq(b, p + 1, e) + if not n or q + n > e then + return nil, "truncated meta event" + end + if kind == 0x2F then + break + elseif kind == 0x51 and n >= 3 then + tempo = tempo or readu8(b, q) * 65536 + readu8(b, q + 1) * 256 + readu8(b, q + 2) + else + table.insert(list, { tick = tick, type = "meta", meta = kind, data = bytes(b, q, n) }) + end + p = q + n + elseif st == 0xF0 or st == 0xF7 then + local n, q = vlq(b, p, e) + if not n or q + n > e then + return nil, "truncated sysex" + end + table.insert(list, { tick = tick, type = if st == 0xF0 then "sysex" else "escape", data = bytes(b, q, n) }) + p = q + n + elseif st < 0xF0 then + local hi, ch = st // 16, st % 16 + local n = DATA[hi] + if p + n > e then + return nil, "truncated event" + end + local d = bytes(b, p, n) + p += n + table.insert(list, { tick = tick, type = TYPES[hi], channel = ch, data = d }) + if hi == 9 then + local dur, q = vlq(b, p, e) + if not dur then + return nil, "truncated note duration" + end + p = q + table.insert(offs, { tick = tick + dur, onTick = tick, ev = { tick = tick + dur, type = "noteOff", channel = ch, data = { d[1] % 128, 64 } } }) + end + else + return nil, string.format("unexpected status byte 0x%02X", st) + end + if #list + #offs > maxEvents then + return nil, "limit: more than " .. maxEvents .. " events" + end + end + -- the sequence stops at its end-of-track event: notes still sounding end there (wildmidi leaves them hanging) + for _, o in offs do + if o.tick > tick then + o.tick = tick + o.ev.tick = tick + end + end + return Render.merge(list, offs), tick, tempo +end + +local function songs(b: buffer, base: number, limit: number): { { [string]: Chunks.Chunk } } + local out = {} + local function form(c: Chunks.Chunk) + local song = {} + for _, s in Chunks.walk(b, c.offset + 4, c.offset + c.avail, Chunks.IFF) do + song[s.id] = song[s.id] or s + end + if song.EVNT then + table.insert(out, song) + end + end + for _, c in Chunks.walk(b, base, limit, Chunks.IFF) do + local kind = if c.avail >= 4 then buffer.readstring(b, c.offset, 4) else "" + if c.id == "FORM" and kind == "XMID" then + form(c) + elseif c.id == "CAT " and kind == "XMID" then + for _, s in Chunks.walk(b, c.offset + 4, c.offset + c.avail, Chunks.IFF) do + if s.id == "FORM" and s.avail >= 4 and buffer.readstring(b, s.offset, 4) == "XMID" then + form(s) + end + end + end + end + return out +end + +function Xmi.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Midi?, Err.Err?) + local o: DecodeOptions = opts or {} + if Xmi.sniff(r) == 0 then + return nil, Err.new(Err.CORRUPT, "not an XMIDI file") + end + local list = songs(r.buf, r.base, r.limit) + local index = o.track or 1 + if #list == 0 then + return nil, Err.new(Err.CORRUPT, "no XMID song with an EVNT chunk") + elseif type(index) ~= "number" or index < 1 or index > #list or index % 1 ~= 0 then + return nil, Err.new(Err.ARG, string.format("track must be 1..%d", #list)) + end + local song = list[index] + local ev = song.EVNT + local evs, endTick, tempo = events(r.buf, ev.offset, ev.offset + ev.avail, o.maxEvents or 2 ^ 24) + if not evs then + return nil, Err.from(endTick :: string, ev.offset) + end + local last = math.max(endTick :: number, if #evs > 0 then evs[#evs].tick else 0) + table.insert(evs, 1, { tick = 0, type = "meta", meta = 0x51, data = Render.tempoBytes(60, 120) }) + table.insert(evs, { tick = last, type = "meta", meta = 0x2F, data = {} }) + local timbres = {} + local tb = song.TIMB + if tb and tb.avail >= 2 then + for i = 0, math.min(buffer.readu16(r.buf, tb.offset), (tb.avail - 2) // 2) - 1 do + table.insert(timbres, { patch = readu8(r.buf, tb.offset + 2 + i * 2), bank = readu8(r.buf, tb.offset + 3 + i * 2) }) + end + end + local rb = song.RBRN + local branches = if rb and rb.avail >= 2 then buffer.readu16(r.buf, rb.offset) else 0 + local midi = Types.Midi.new(60) + midi.format = 0 + midi.tracks = { { events = evs } } + Render.attach(midi, { format = "xmi", songs = #list, song = index, timbres = timbres, tempo = tempo, branches = branches }) + midi.meta.truncated = ev.truncated + return midi, nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Xmi.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local midi, err = Xmi.decode(r, opts) + if not midi then + return nil, err + end + return Render.decoder(midi, opts) +end + +return Xmi +end +end + + + + + + ops + --!optimize 2 +--!nocheck +-- rosetta chunk ops (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 5 modules (1 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["ops/AudioOps"] = function() + +-- ops/AudioOps: editing on the standard Audio: collect, gain, normalize, mix, remix, resample (codecs/audio/Resample), +-- trim, concat, fades, peak / RMS. New code. +-- 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 = __include("core/Err") +local Types = __include("Types") +local Pcm = __include("codecs/audio/Pcm") +local Resample = __include("codecs/audio/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 + +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 + +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 + +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 + +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 + +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 + +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 + +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 + +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 + +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 + +-- 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 }, +} + +-- m[o][i]: output channel o = sum m[o][i] * input i +local function matrix(from: number, to: number): { { number } } + local m: { { number } } = table.create(to) :: any + 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: { 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 } + 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 ~= nil and outIdx.FR ~= nil then + local w = TO_STEREO[sp] or { 0, 0 } + 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 + 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 + +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 + +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 + +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 + +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 + +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 + +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 + +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 + +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 +end +__FILES["ops/LayerOps"] = function() + +-- 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/image/Blend, opacity, groups (isolated, or pass-through), clipping layers and +-- grey layer masks; every frame as an animated Image; walking the leaves. +-- Never throws: bad values return nil, Err.ARG. +local Err = __include("core/Err") +local Types = __include("Types") +local Blend = __include("codecs/image/Blend") + +local LayerOps = {} + +type FlattenOptions = { + frame: number?, -- 1-based animation frame (default: layered.layers, which is frame 1) + hidden: boolean?, -- include hidden layers (default false) + background: { number }?, -- r, g, b, a 0..255 under everything (default transparent) +} + +function LayerOps.flatten(layered: Types.Layered, opts: FlattenOptions?): (Types.Image?, Err.Err?) + if type(layered) ~= "table" or type(layered.width) ~= "number" or type(layered.height) ~= "number" or type(layered.layers) ~= "table" then + return nil, Err.new(Err.ARG, "flatten: needs a Layered value") + end + local o: FlattenOptions = opts or {} + local w, h = math.floor(layered.width), math.floor(layered.height) + if w < 0 or h < 0 or w * h > 2 ^ 28 then + return nil, Err.new(Err.ARG, "flatten: bad size") + end + local layers = layered.layers + if o.frame then + local f = if type(layered.frames) == "table" then layered.frames[o.frame] else nil + if f == nil and o.frame ~= 1 then + return nil, Err.new(Err.ARG, "flatten: no frame " .. tostring(o.frame)) + end + if f then + layers = f.layers + end + end + local img = Types.Image.new(w, h) + local bg = o.background + if type(bg) == "table" then + local v = (bg[1] or 0) + (bg[2] or 0) * 256 + (bg[3] or 0) * 65536 + (bg[4] or 255) * 16777216 + for i = 0, w * h - 1 do + buffer.writeu32(img.pixels, i * 4, v) + end + end + Blend.flatten(layers, img.pixels, w, h, o.hidden == true) + return img, nil +end + +function LayerOps.flattenFrames(layered: Types.Layered, opts: FlattenOptions?): (Types.Image?, Err.Err?) + local first, err = LayerOps.flatten(layered, opts) + if not first then + return nil, err + end + local frames = if type(layered.frames) == "table" then layered.frames else {} + if #frames == 0 then + return first, nil + end + local list: { Types.Frame } = {} + for i, f in frames do + local o: FlattenOptions = table.clone(opts or {}) :: any + o.frame = i + local img = if i == 1 then first else LayerOps.flatten(layered, o) + if not img then + return nil, Err.new(Err.ARG, "flatten: frame " .. i) + end + list[i] = { image = img, delay = tonumber(f.delay) or 0.1, x = 0, y = 0, dispose = "none", blend = "source" } + end + first.frames = list + return first, nil +end + +function LayerOps.leaves(layers: { Types.Layer }): () -> (Types.Layer?, number?) + local stack: { { any } } = { { layers, 0, 0 } } + return function(): (Types.Layer?, number?) + while #stack > 0 do + local top = stack[#stack] + top[2] += 1 + local l = top[1][top[2]] + if l == nil then + table.remove(stack) + elseif type(l.children) == "table" then + table.insert(stack, { l.children, 0, top[3] + 1 }) + else + return l, top[3] + end + end + return nil, nil + end +end + +return LayerOps +end +__FILES["ops/MeshOps"] = function() + +-- ops/MeshOps: editing meshes in the standard Scene type: triangulate, transform, normals (area weighted or flat), +-- tangents (Lengyel 2001), weld, bounds, merge into world space, unit / up-axis changes, greedy voxel meshing. Inputs +-- may use any accessor type; outputs are f32 attributes and u32 indices. Never throws. +local Err = __include("core/Err") +local Types = __include("Types") +local Greedy = __include("ops/MeshOps/Greedy") + +local MeshOps = {} + +type Accessor = Types.Accessor +type Primitive = Types.Primitive +type Scene = Types.Scene + +local Scene = Types.Scene +local readf32, writef32 = buffer.readf32, buffer.writef32 +local readu32, writeu32 = buffer.readu32, buffer.writeu32 + +function MeshOps.f32(acc: Accessor): Accessor? + if acc.type == "f32" then + return acc + end + local get = Scene.reader(acc) + if not get then + return nil + end + local n, c = acc.count, acc.components + local out = buffer.create(n * c * 4) + for i = 0, n - 1 do + for k = 0, c - 1 do + writef32(out, (i * c + k) * 4, get(i, k)) + end + end + local a = Scene.accessor(out, "f32", c, n) + a.matrix = acc.matrix + return a +end + +local function indexBuffer(prim: Primitive): (buffer, number) + local ind = prim.indices + if ind then + if ind.type == "u32" and ind.components == 1 then + return ind.data, ind.count + end + local get = Scene.reader(ind) + local out = buffer.create(ind.count * 4) + if get then + for i = 0, ind.count - 1 do + writeu32(out, i * 4, get(i, 0)) + end + end + return out, ind.count + end + local pos = prim.attributes.POSITION + local n = if pos then pos.count else 0 + local out = buffer.create(n * 4) + for i = 0, n - 1 do + writeu32(out, i * 4, i) + end + return out, n +end + +local function vertexCount(prim: Primitive): number + local pos = prim.attributes.POSITION + return if pos then pos.count else 0 +end + +local function checkPrim(prim: any): Err.Err? + if type(prim) ~= "table" or type(prim.attributes) ~= "table" then + return Err.new(Err.ARG, "expected a Primitive") + end + local pos = prim.attributes.POSITION + if not pos or type(pos.data) ~= "buffer" or pos.components < 3 then + return Err.new(Err.ARG, "primitive without a POSITION accessor") + end + local n = pos.count + for name, a in prim.attributes do + local size = Types.COMPONENT_SIZE[a.type] + if not size or type(a.data) ~= "buffer" or buffer.len(a.data) < a.count * a.components * size then + return Err.new(Err.ARG, "attribute " .. tostring(name) .. ": bad accessor") + end + if a.count ~= n then + return Err.new(Err.ARG, "attribute " .. tostring(name) .. ": count differs from POSITION") + end + end + if prim.indices then + local ind = prim.indices + local size = Types.COMPONENT_SIZE[ind.type] + if not size or type(ind.data) ~= "buffer" or buffer.len(ind.data) < ind.count * size then + return Err.new(Err.ARG, "bad indices accessor") + end + local get = Scene.reader(ind) + if get then + for i = 0, ind.count - 1 do + if get(i, 0) >= n then + return Err.new(Err.ARG, "index out of range") + end + end + end + end + return nil +end +MeshOps.check = checkPrim + +-- ear clipping of one polygon (corner indices into px / py / pz) -> triangles appended to out; fan when it gets stuck +local function earclip(poly: { number }, P: (number, number) -> number, out: { number }) + local k = #poly + if k < 3 then + return + end + if k == 3 then + table.insert(out, poly[1]) + table.insert(out, poly[2]) + table.insert(out, poly[3]) + return + end + -- Newell normal -> the projection plane (drop the dominant axis) + local nx, ny, nz = 0, 0, 0 + for a = 1, k do + local i, j = poly[a], poly[a % k + 1] + local xi, yi, zi = P(i, 0), P(i, 1), P(i, 2) + local xj, yj, zj = P(j, 0), P(j, 1), P(j, 2) + nx += (yi - yj) * (zi + zj) + ny += (zi - zj) * (xi + xj) + nz += (xi - xj) * (yi + yj) + end + local ax, ay, az = math.abs(nx), math.abs(ny), math.abs(nz) + local cu, cv, sign = 0, 1, nz + if ax >= ay and ax >= az then + cu, cv, sign = 1, 2, nx + elseif ay >= az then + cu, cv, sign = 2, 0, ny + end + local function uv(i: number): (number, number) + return P(i, cu), P(i, cv) + end + local s = if sign < 0 then -1 else 1 + local ring = table.clone(poly) + local guard = 0 + while #ring > 3 and guard < k * k do + guard += 1 + local n = #ring + local clipped = false + for a = 1, n do + local ia, ib, ic = ring[(a - 2) % n + 1], ring[a], ring[a % n + 1] + local ax2, ay2 = uv(ia) + local bx, by = uv(ib) + local cx, cy = uv(ic) + local cross = ((bx - ax2) * (cy - ay2) - (by - ay2) * (cx - ax2)) * s + if cross > 0 then + local inside = false + for q = 1, n do + local iq = ring[q] + if iq ~= ia and iq ~= ib and iq ~= ic then + local qx, qy = uv(iq) + local d1 = ((bx - ax2) * (qy - ay2) - (by - ay2) * (qx - ax2)) * s + local d2 = ((cx - bx) * (qy - by) - (cy - by) * (qx - bx)) * s + local d3 = ((ax2 - cx) * (qy - cy) - (ay2 - cy) * (qx - cx)) * s + if d1 >= 0 and d2 >= 0 and d3 >= 0 then + inside = true + break + end + end + end + if not inside then + table.insert(out, ia) + table.insert(out, ib) + table.insert(out, ic) + table.remove(ring, a) + clipped = true + break + end + end + end + if not clipped then + break + end + end + -- whatever is left (3 corners, or a degenerate / self-intersecting rest): a fan + for a = 2, #ring - 1 do + table.insert(out, ring[1]) + table.insert(out, ring[a]) + table.insert(out, ring[a + 1]) + end +end + +local function u32(list: { number }): Accessor + local n = #list + local b = buffer.create(n * 4) + for i = 1, n do + writeu32(b, (i - 1) * 4, list[i]) + end + return Scene.accessor(b, "u32", 1, n) +end + +-- strips and fans unroll with glTF's alternating strip winding +function MeshOps.triangulate(prim: Primitive, opts: { method: string? }?): (Primitive?, Err.Err?) + local err = checkPrim(prim) + if err then + return nil, err + end + local mode = prim.mode or "triangles" + if mode == "lines" or mode == "points" or mode == "line_strip" or mode == "line_loop" then + return prim, nil + end + local method = opts and opts.method or "earclip" + local ib, n = indexBuffer(prim) + local out: { number } = {} + if mode == "triangles" then + local m = n - n % 3 + for i = 0, m - 1 do + out[i + 1] = readu32(ib, i * 4) + end + elseif mode == "triangle_strip" then + for i = 0, n - 3 do + local a, b, c = readu32(ib, i * 4), readu32(ib, i * 4 + 4), readu32(ib, i * 4 + 8) + if i % 2 == 1 then + a, b = b, a + end + if a ~= b and b ~= c and a ~= c then + table.insert(out, a) + table.insert(out, b) + table.insert(out, c) + end + end + elseif mode == "triangle_fan" then + for i = 1, n - 2 do + table.insert(out, readu32(ib, 0)) + table.insert(out, readu32(ib, i * 4)) + table.insert(out, readu32(ib, i * 4 + 4)) + end + elseif mode == "polygons" then + local faces = prim.faces + if not faces then + return nil, Err.new(Err.ARG, "polygons primitive without faces") + end + local getf = Scene.reader(faces) + if not getf then + return nil, Err.new(Err.ARG, "bad faces accessor") + end + local pos = MeshOps.f32(prim.attributes.POSITION) :: Accessor + local pd = pos.data + local P = function(i: number, c: number): number + return readf32(pd, (i * 3 + c) * 4) + end + local at = 0 + for f = 0, faces.count - 1 do + local k = getf(f, 0) + if at + k > n then + return nil, Err.new(Err.ARG, "faces run past the indices") + end + if k >= 3 then + if method == "fan" or k == 3 then + for a = 1, k - 2 do + table.insert(out, readu32(ib, at * 4)) + table.insert(out, readu32(ib, (at + a) * 4)) + table.insert(out, readu32(ib, (at + a + 1) * 4)) + end + else + local poly = table.create(k) :: { number } + for a = 0, k - 1 do + poly[a + 1] = readu32(ib, (at + a) * 4) + end + earclip(poly, P, out) + end + end + at += k + end + else + return nil, Err.new(Err.ARG, "unknown mode " .. tostring(mode)) + end + return { + attributes = prim.attributes, + indices = u32(out), + mode = "triangles", + material = prim.material, + targets = prim.targets, + extras = prim.extras, + }, nil +end + +local function det3(m: { number }): 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 + +-- the inverse transpose of m's 3 x 3 part (column-major 9), for normals +local function 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 det = a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g) + if det == 0 then + det = 1 + end + local k = 1 / det + -- cofactor matrix / det (= inverse transpose), column-major + return { + (e * i - f * h) * k, -(b * i - c * h) * k, (b * f - c * e) * k, + -(d * i - f * g) * k, (a * i - c * g) * k, -(a * f - c * d) * k, + (d * h - e * g) * k, -(a * h - b * g) * k, (a * e - b * d) * k, + } +end + +-- a mirroring matrix (negative determinant) reverses the winding so faces stay front-facing +function MeshOps.transform(prim: Primitive, m: { number }): (Primitive?, Err.Err?) + local err = checkPrim(prim) + if err then + return nil, err + end + if type(m) ~= "table" or #m ~= 16 then + return nil, Err.new(Err.ARG, "expected a column-major 4x4 matrix (16 numbers)") + end + local nm = normalMatrix(m) + local function points(acc: Accessor?, w: number): Accessor? + if not acc then + return nil + end + local a = MeshOps.f32(acc) :: Accessor + if a == acc then + a = Scene.accessor(buffer.create(buffer.len(acc.data)), "f32", acc.components, acc.count) + buffer.copy(a.data, 0, acc.data, 0, acc.count * acc.components * 4) + end + local d, c = a.data, a.components + for i = 0, a.count - 1 do + local o = i * c * 4 + local x, y, z = readf32(d, o), readf32(d, o + 4), readf32(d, o + 8) + writef32(d, o, m[1] * x + m[5] * y + m[9] * z + m[13] * w) + writef32(d, o + 4, m[2] * x + m[6] * y + m[10] * z + m[14] * w) + writef32(d, o + 8, m[3] * x + m[7] * y + m[11] * z + m[15] * w) + end + return a + end + local function dirs(acc: Accessor?, mat: { number }, normalize: boolean, flipW: boolean): Accessor? + if not acc then + return nil + end + local a = MeshOps.f32(acc) :: Accessor + if a == acc then + a = Scene.accessor(buffer.create(buffer.len(acc.data)), "f32", acc.components, acc.count) + buffer.copy(a.data, 0, acc.data, 0, acc.count * acc.components * 4) + end + local d, c = a.data, a.components + for i = 0, a.count - 1 do + local o = i * c * 4 + local x, y, z = readf32(d, o), readf32(d, o + 4), readf32(d, o + 8) + local nx = mat[1] * x + mat[4] * y + mat[7] * z + local ny = mat[2] * x + mat[5] * y + mat[8] * z + local nz = mat[3] * x + mat[6] * y + mat[9] * z + if normalize then + local l = math.sqrt(nx * nx + ny * ny + nz * nz) + if l > 0 then + nx, ny, nz = nx / l, ny / l, nz / l + end + end + writef32(d, o, nx) + writef32(d, o + 4, ny) + writef32(d, o + 8, nz) + if flipW and c >= 4 then + writef32(d, o + 12, -readf32(d, o + 12)) + end + end + return a + end + local mirror = det3(m) < 0 + local m3 = { m[1], m[2], m[3], m[5], m[6], m[7], m[9], m[10], m[11] } + local attrs = prim.attributes + attrs.POSITION = points(attrs.POSITION, 1) :: Accessor + attrs.NORMAL = dirs(attrs.NORMAL, nm, true, false) + attrs.TANGENT = dirs(attrs.TANGENT, m3, true, mirror) + if prim.targets then + for _, t in prim.targets do + t.POSITION = points(t.POSITION, 0) + t.NORMAL = dirs(t.NORMAL, nm, false, false) + t.TANGENT = dirs(t.TANGENT, m3, false, false) + end + end + if mirror and (prim.mode == "triangles" or prim.mode == nil) then + local ib, n = indexBuffer(prim) + local nb = buffer.create(n * 4) + buffer.copy(nb, 0, ib, 0, n * 4) + for t = 0, n // 3 - 1 do + local o = t * 12 + local b = readu32(nb, o + 4) + writeu32(nb, o + 4, readu32(nb, o + 8)) + writeu32(nb, o + 8, b) + end + prim.indices = Scene.accessor(nb, "u32", 1, n) + elseif mirror and prim.mode == "polygons" and prim.faces then + local ib, n = indexBuffer(prim) + local nb = buffer.create(n * 4) + local getf = Scene.reader(prim.faces) + local at = 0 + if getf then + for f = 0, prim.faces.count - 1 do + local k = getf(f, 0) + for a = 0, k - 1 do + if at + a < n then + writeu32(nb, (at + a) * 4, readu32(ib, (at + k - 1 - a) * 4)) + end + end + at += k + end + end + prim.indices = Scene.accessor(nb, "u32", 1, n) + end + return prim, nil +end + +function MeshOps.computeNormals(prim: Primitive, opts: { flat: boolean? }?): (Primitive?, Err.Err?) + local p = prim + if (prim.mode or "triangles") ~= "triangles" then + local t, err = MeshOps.triangulate(prim) + if not t then + return nil, err + end + p = t + else + local err = checkPrim(prim) + if err then + return nil, err + end + end + if p.mode ~= "triangles" then + return p, nil -- lines / points: nothing to do + end + if opts and opts.flat then + p = MeshOps.unweld(p) + end + local pos = MeshOps.f32(p.attributes.POSITION) :: Accessor + local pd = pos.data + local nv = pos.count + local ib, n = indexBuffer(p) + local acc = table.create(nv * 3, 0) + for t = 0, n // 3 - 1 do + local a, b, c = readu32(ib, t * 12), readu32(ib, t * 12 + 4), readu32(ib, t * 12 + 8) + local ax, ay, az = readf32(pd, a * 12), readf32(pd, a * 12 + 4), readf32(pd, a * 12 + 8) + local e1x, e1y, e1z = readf32(pd, b * 12) - ax, readf32(pd, b * 12 + 4) - ay, readf32(pd, b * 12 + 8) - az + local e2x, e2y, e2z = readf32(pd, c * 12) - ax, readf32(pd, c * 12 + 4) - ay, readf32(pd, c * 12 + 8) - az + -- the cross product is twice the area times the unit normal: area weighting for free + local nx, ny, nz = e1y * e2z - e1z * e2y, e1z * e2x - e1x * e2z, e1x * e2y - e1y * e2x + for _, v in { a, b, c } do + acc[v * 3 + 1] += nx + acc[v * 3 + 2] += ny + acc[v * 3 + 3] += nz + end + end + local out = buffer.create(nv * 12) + for v = 0, nv - 1 do + local x, y, z = acc[v * 3 + 1], acc[v * 3 + 2], acc[v * 3 + 3] + local l = math.sqrt(x * x + y * y + z * z) + if l > 0 then + x, y, z = x / l, y / l, z / l + else + x, y, z = 0, 0, 1 + end + writef32(out, v * 12, x) + writef32(out, v * 12 + 4, y) + writef32(out, v * 12 + 8, z) + end + p.attributes.NORMAL = Scene.accessor(out, "f32", 3, nv) + return p, nil +end + +-- TANGENT: f32 vec4, xyz orthogonal to the normal, w = +-1 handedness +function MeshOps.computeTangents(prim: Primitive, opts: { texCoord: number? }?): (Primitive?, Err.Err?) + local p = prim + if not p.attributes.NORMAL or (p.mode or "triangles") ~= "triangles" then + local q, err = MeshOps.computeNormals(prim) + if not q then + return nil, err + end + p = q + end + local err = checkPrim(p) + if err then + return nil, err + end + local uvAcc = p.attributes["TEXCOORD_" .. tostring(opts and opts.texCoord or 0)] + if not uvAcc then + return nil, Err.new(Err.ARG, "computeTangents needs texture coordinates") + end + local pos = MeshOps.f32(p.attributes.POSITION) :: Accessor + local nrm = MeshOps.f32(p.attributes.NORMAL :: Accessor) :: Accessor + local uv = MeshOps.f32(uvAcc) :: Accessor + local pd, nd, ud = pos.data, nrm.data, uv.data + local nv = pos.count + local ib, n = indexBuffer(p) + local tan = table.create(nv * 3, 0) + local bit = table.create(nv * 3, 0) + for t = 0, n // 3 - 1 do + local a, b, c = readu32(ib, t * 12), readu32(ib, t * 12 + 4), readu32(ib, t * 12 + 8) + local ax, ay, az = readf32(pd, a * 12), readf32(pd, a * 12 + 4), readf32(pd, a * 12 + 8) + local x1, y1, z1 = readf32(pd, b * 12) - ax, readf32(pd, b * 12 + 4) - ay, readf32(pd, b * 12 + 8) - az + local x2, y2, z2 = readf32(pd, c * 12) - ax, readf32(pd, c * 12 + 4) - ay, readf32(pd, c * 12 + 8) - az + local us, vs = readf32(ud, a * 8), readf32(ud, a * 8 + 4) + local s1, t1 = readf32(ud, b * 8) - us, readf32(ud, b * 8 + 4) - vs + local s2, t2 = readf32(ud, c * 8) - us, readf32(ud, c * 8 + 4) - vs + local den = s1 * t2 - s2 * t1 + if den ~= 0 then + local r = 1 / den + local tx, ty, tz = (t2 * x1 - t1 * x2) * r, (t2 * y1 - t1 * y2) * r, (t2 * z1 - t1 * z2) * r + local bx, by, bz = (s1 * x2 - s2 * x1) * r, (s1 * y2 - s2 * y1) * r, (s1 * z2 - s2 * z1) * r + for _, v in { a, b, c } do + tan[v * 3 + 1] += tx + tan[v * 3 + 2] += ty + tan[v * 3 + 3] += tz + bit[v * 3 + 1] += bx + bit[v * 3 + 2] += by + bit[v * 3 + 3] += bz + end + end + end + local out = buffer.create(nv * 16) + for v = 0, nv - 1 do + local nx, ny, nz = readf32(nd, v * 12), readf32(nd, v * 12 + 4), readf32(nd, v * 12 + 8) + local tx, ty, tz = tan[v * 3 + 1], tan[v * 3 + 2], tan[v * 3 + 3] + local dot = nx * tx + ny * ty + nz * tz + tx, ty, tz = tx - nx * dot, ty - ny * dot, tz - nz * dot + local l = math.sqrt(tx * tx + ty * ty + tz * tz) + if l > 1e-20 then + tx, ty, tz = tx / l, ty / l, tz / l + else + -- no UV gradient: any unit vector orthogonal to the normal + if math.abs(nx) < 0.9 then + tx, ty, tz = 0, nz, -ny + else + tx, ty, tz = -nz, 0, nx + end + local l2 = math.sqrt(tx * tx + ty * ty + tz * tz) + if l2 > 0 then + tx, ty, tz = tx / l2, ty / l2, tz / l2 + end + end + -- handedness: (n x t) . b + local cx, cy, cz = ny * tz - nz * ty, nz * tx - nx * tz, nx * ty - ny * tx + local w = if cx * bit[v * 3 + 1] + cy * bit[v * 3 + 2] + cz * bit[v * 3 + 3] < 0 then -1 else 1 + writef32(out, v * 16, tx) + writef32(out, v * 16 + 4, ty) + writef32(out, v * 16 + 8, tz) + writef32(out, v * 16 + 12, w) + end + p.attributes.TANGENT = Scene.accessor(out, "f32", 4, nv) + return p, nil +end + +local function gather(acc: Accessor, ib: buffer, n: number): Accessor + local size = (Types.COMPONENT_SIZE[acc.type] or 4) * acc.components + local out = buffer.create(n * size) + for i = 0, n - 1 do + buffer.copy(out, i * size, acc.data, readu32(ib, i * 4) * size, size) + end + local a = Scene.accessor(out, acc.type, acc.components, n) + a.matrix = acc.matrix + return a +end + +function MeshOps.unweld(prim: Primitive): Primitive + local ib, n = indexBuffer(prim) + local attrs = {} + for name, a in prim.attributes do + attrs[name] = gather(a, ib, n) + end + local targets = nil + if prim.targets then + targets = {} + for k, t in prim.targets do + local tt = {} + for name, a in t do + tt[name] = gather(a, ib, n) + end + targets[k] = tt + end + end + return { attributes = attrs, indices = nil, mode = prim.mode, faces = prim.faces, material = prim.material, targets = targets, extras = prim.extras } +end + +function MeshOps.weld(prim: Primitive, opts: { epsilon: number?, positionsOnly: boolean? }?): (Primitive?, Err.Err?) + local err = checkPrim(prim) + if err then + return nil, err + end + local eps = opts and opts.epsilon or 0 + local posOnly = opts and opts.positionsOnly or false + local names = {} + for name in prim.attributes do + if not (posOnly and name ~= "POSITION") and not (eps > 0 and name == "POSITION") then + table.insert(names, name) + end + end + table.sort(names) + local nv = vertexCount(prim) + local pos = MeshOps.f32(prim.attributes.POSITION) :: Accessor + local pd = pos.data + local inv = if eps > 0 then 1 / eps else 0 + local remap = buffer.create(nv * 4) + local keep: { number } = {} + local seen: { [string]: number } = {} + local parts = table.create(#names + 1) + for v = 0, nv - 1 do + local np = 0 + if eps > 0 then + np += 1 + parts[np] = string.format("%d,%d,%d", math.floor(readf32(pd, v * 12) * inv + 0.5), math.floor(readf32(pd, v * 12 + 4) * inv + 0.5), math.floor(readf32(pd, v * 12 + 8) * inv + 0.5)) + end + for _, name in names do + local a = prim.attributes[name] + local size = (Types.COMPONENT_SIZE[a.type] or 4) * a.components + np += 1 + parts[np] = buffer.readstring(a.data, v * size, size) + end + local key = table.concat(parts, "\1", 1, np) + local k = seen[key] + if k == nil then + k = #keep + seen[key] = k + table.insert(keep, v) + end + writeu32(remap, v * 4, k) + end + local kb = buffer.create(#keep * 4) + for i, v in keep do + writeu32(kb, (i - 1) * 4, v) + end + local attrs = {} + for name, a in prim.attributes do + attrs[name] = gather(a, kb, #keep) + end + local targets = nil + if prim.targets then + targets = {} + for k, t in prim.targets do + local tt = {} + for name, a in t do + tt[name] = gather(a, kb, #keep) + end + targets[k] = tt + end + end + local ib, n = indexBuffer(prim) + local out = buffer.create(n * 4) + for i = 0, n - 1 do + writeu32(out, i * 4, readu32(remap, readu32(ib, i * 4) * 4)) + end + return { + attributes = attrs, + indices = Scene.accessor(out, "u32", 1, n), + mode = prim.mode, + faces = prim.faces, + material = prim.material, + targets = targets, + extras = prim.extras, + }, nil +end + +function MeshOps.bounds(x: any): ({ number }?, { number }?) + local lo = { math.huge, math.huge, math.huge } + local hi = { -math.huge, -math.huge, -math.huge } + local function add(prim: Primitive, m: { number }?) + local pos = prim.attributes and prim.attributes.POSITION + if not pos then + return + end + local get = Scene.reader(pos) + if not get then + return + end + for i = 0, pos.count - 1 do + local px, py, pz = get(i, 0), get(i, 1), get(i, 2) + if m and m ~= Scene.IDENTITY then + px, py, pz = m[1] * px + m[5] * py + m[9] * pz + m[13], m[2] * px + m[6] * py + m[10] * pz + m[14], m[3] * px + m[7] * py + m[11] * pz + m[15] + end + if px < lo[1] then + lo[1] = px + end + if py < lo[2] then + lo[2] = py + end + if pz < lo[3] then + lo[3] = pz + end + if px > hi[1] then + hi[1] = px + end + if py > hi[2] then + hi[2] = py + end + if pz > hi[3] then + hi[3] = pz + end + end + end + if type(x) ~= "table" then + return nil, nil + end + if x.kind == "scene" then + for _, pl in Scene.flatten(x) do + add(pl.primitive, pl.matrix) + end + else + add(x, nil) + end + if lo[1] > hi[1] then + return nil, nil + end + return lo, hi +end + +-- the value of an attribute nobody had (COLOR_n white, WEIGHTS_0 { 1, 0, 0, 0 }, the rest zero) +local function defaultFor(name: string, k: number): number + if string.sub(name, 1, 6) == "COLOR_" then + return 1 + end + if string.sub(name, 1, 8) == "WEIGHTS_" then + return if k == 0 then 1 else 0 + end + return 0 +end + +function MeshOps.merge(input: any, opts: { byMaterial: boolean?, method: string? }?): (any, Err.Err?) + local placed: { Types.Placed } = {} + if type(input) ~= "table" then + return nil, Err.new(Err.ARG, "merge: expected a Scene or a list of Primitives") + end + if input.kind == "scene" then + placed = Scene.flatten(input) + else + for i, p in input do + placed[i] = { primitive = p, matrix = Scene.IDENTITY, node = 0, mesh = 0 } + end + end + local groups: { [number]: { Primitive } } = {} + local order: { number } = {} + local allPoints = #placed > 0 + for _, pl in placed do + if pl.primitive.mode ~= "points" then + allPoints = false + end + end + for _, pl in placed do + local p = pl.primitive + local mode = p.mode or "triangles" + if mode ~= "lines" and mode ~= "line_strip" and mode ~= "line_loop" and (mode ~= "points" or allPoints) then + local t, err = if mode == "points" then p else MeshOps.triangulate(p, opts) + if not t then + return nil, err + end + -- a private copy of the attributes to bake + local copy: Primitive = { attributes = {}, indices = t.indices, mode = t.mode, material = t.material } + for name, a in t.attributes do + copy.attributes[name] = MeshOps.f32(a) + end + if pl.matrix ~= Scene.IDENTITY then + local ok, terr = MeshOps.transform(copy, pl.matrix) + if not ok then + return nil, terr + end + end + local key = if opts and opts.byMaterial then (copy.material or 0) else 0 + if not groups[key] then + groups[key] = {} + table.insert(order, key) + end + table.insert(groups[key], copy) + end + end + table.sort(order) + local function concat(list: { Primitive }, material: number?): Primitive + local names: { [string]: number } = {} + local nv, ni = 0, 0 + local points = false + for _, p in list do + for name, a in p.attributes do + names[name] = math.max(names[name] or 0, a.components) + end + nv += vertexCount(p) + local _, n = indexBuffer(p) + ni += n + points = points or p.mode == "points" + end + local attrs: { [string]: Accessor } = {} + for name, comps in names do + local out = buffer.create(nv * comps * 4) + local base = 0 + for _, p in list do + local a = p.attributes[name] + local cnt = vertexCount(p) + for v = 0, cnt - 1 do + for k = 0, comps - 1 do + local value = if a and k < a.components then readf32(a.data, (v * a.components + k) * 4) else defaultFor(name, k) + writef32(out, ((base + v) * comps + k) * 4, value) + end + end + base += cnt + end + attrs[name] = Scene.accessor(out, "f32", comps, nv) + end + local idx = buffer.create(ni * 4) + local base, at = 0, 0 + for _, p in list do + local ib, n = indexBuffer(p) + for i = 0, n - 1 do + writeu32(idx, (at + i) * 4, readu32(ib, i * 4) + base) + end + at += n + base += vertexCount(p) + end + return { + attributes = attrs, + indices = if points then nil else Scene.accessor(idx, "u32", 1, ni), + mode = if points then "points" else "triangles", + material = material, + } + end + if opts and opts.byMaterial then + local out = {} + for _, key in order do + table.insert(out, concat(groups[key], if key == 0 then nil else key)) + end + return out, nil + end + local all: { Primitive } = groups[0] or {} + local first = all[1] + return concat(all, first and first.material), nil +end + +local function scaleAccessor(acc: Accessor?, f: number): Accessor? + if not acc then + return nil + end + local a = MeshOps.f32(acc) :: Accessor + if a == acc then + a = Scene.accessor(buffer.create(acc.count * acc.components * 4), "f32", acc.components, acc.count) + buffer.copy(a.data, 0, acc.data, 0, acc.count * acc.components * 4) + end + for i = 0, a.count * a.components - 1 do + writef32(a.data, i * 4, readf32(a.data, i * 4) * f) + end + return a +end + +function MeshOps.scale(scene: Scene, f: number): (Scene?, Err.Err?) + if type(scene) ~= "table" or scene.kind ~= "scene" or type(f) ~= "number" or f ~= f or f == 0 then + return nil, Err.new(Err.ARG, "scale: expected a Scene and a non-zero factor") + end + local done: { [any]: boolean } = {} + for _, mesh in scene.meshes do + for _, p in mesh.primitives do + if not done[p] then + done[p] = true + p.attributes.POSITION = scaleAccessor(p.attributes.POSITION, f) :: Accessor + for _, t in p.targets or {} do + t.POSITION = scaleAccessor(t.POSITION, f) + end + end + end + end + for _, n in scene.nodes do + if n.translation then + n.translation = { n.translation[1] * f, n.translation[2] * f, n.translation[3] * f } + end + if n.matrix then + local m = table.clone(n.matrix) + m[13], m[14], m[15] = m[13] * f, m[14] * f, m[15] * f + n.matrix = m + end + end + for _, a in scene.animations do + for _, c in a.channels do + if c.path == "translation" and not done[c.output] then + done[c.output] = true + c.output = scaleAccessor(c.output, f) :: Accessor + end + end + end + for _, s in scene.skins do + local ibm = s.inverseBindMatrices + if ibm and not done[ibm] then + local a = MeshOps.f32(ibm) :: Accessor + if a == ibm then + a = Scene.accessor(buffer.create(ibm.count * 64), "f32", 16, ibm.count) + buffer.copy(a.data, 0, ibm.data, 0, ibm.count * 64) + end + for i = 0, a.count - 1 do + for k = 12, 14 do + writef32(a.data, (i * 16 + k) * 4, readf32(a.data, (i * 16 + k) * 4) * f) + end + end + a.matrix = true + s.inverseBindMatrices = a + done[a] = true + end + end + for _, c in scene.cameras do + if c.type == "perspective" then + c.znear *= math.abs(f) + if c.zfar then + c.zfar *= math.abs(f) + end + else + c.znear *= math.abs(f) + if c.zfar then + c.zfar *= math.abs(f) + end + c.xmag = c.xmag and c.xmag * math.abs(f) + c.ymag = c.ymag and c.ymag * math.abs(f) + end + end + for _, l in scene.lights do + if l.range then + l.range *= math.abs(f) + end + end + scene.meta.unit = (scene.meta.unit or 1) / f + return scene, nil +end + +function MeshOps.setUnit(scene: Scene, metresPerUnit: number): (Scene?, Err.Err?) + if type(scene) ~= "table" or type(metresPerUnit) ~= "number" or metresPerUnit <= 0 then + return nil, Err.new(Err.ARG, "setUnit: expected a Scene and a positive unit") + end + local from = scene.meta.unit or 1 + return MeshOps.scale(scene, from / metresPerUnit) +end + +function MeshOps.setUp(scene: Scene, up: string): (Scene?, Err.Err?) + if type(scene) ~= "table" or scene.kind ~= "scene" or (up ~= "y" and up ~= "z") then + return nil, Err.new(Err.ARG, "setUp: expected a Scene and \"y\" or \"z\"") + end + local from = scene.meta.up or "y" + if from == up then + return scene, nil + end + local h = math.sqrt(0.5) + -- z-up -> y-up: -90 degrees about x; y-up -> z-up: +90 degrees about x + local q = if up == "y" then { -h, 0, 0, h } else { h, 0, 0, h } + table.insert(scene.nodes, { name = "up_" .. up, children = scene.roots, rotation = q }) + scene.roots = { #scene.nodes } + scene.meta.up = up :: any + return scene, nil +end + +local function linear(c: number): number + local s = c / 255 + return if s <= 0.04045 then s / 12.92 else ((s + 0.055) / 1.055) ^ 2.4 +end + +-- pivot "center": MagicaVoxel's placement (cell x spans x - floor(sx / 2) ..) +function MeshOps.voxelsToPrimitive(v: Types.Voxels, opts: { pivot: string?, scale: number?, colors: string?, indexAttribute: boolean? }?): (Primitive?, Err.Err?) + if type(v) ~= "table" or type(v.size) ~= "table" or type(v.data) ~= "buffer" then + return nil, Err.new(Err.ARG, "expected a Voxels grid") + end + local sx, sy, sz = v.size[1], v.size[2], v.size[3] + if type(sx) ~= "number" or type(sy) ~= "number" or type(sz) ~= "number" or sx < 1 or sy < 1 or sz < 1 or buffer.len(v.data) < sx * sy * sz then + return nil, Err.new(Err.ARG, "bad voxel grid size") + end + local pivot = opts and opts.pivot or "center" + local scale = opts and opts.scale or 1 + local ox, oy, oz = 0, 0, 0 + if pivot == "center" then + ox, oy, oz = -(sx // 2), -(sy // 2), -(sz // 2) + end + local g = Greedy.run(v.data, sx, sy, sz, ox, oy, oz, scale) + local nv = g.vertices + local function trim(b: buffer, size: number): buffer + local out = buffer.create(size) + buffer.copy(out, 0, b, 0, size) + return out + end + local attrs: { [string]: Accessor } = { + POSITION = Scene.accessor(trim(g.positions, nv * 12), "f32", 3, nv), + NORMAL = Scene.accessor(trim(g.normals, nv * 12), "f32", 3, nv), + } + local pal = v.palette or {} + local srgb = opts and opts.colors == "srgb" + local col = buffer.create(nv * (if srgb then 4 else 16)) + local lut: { { number } } = {} + for i = 1, 255 do + 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 + lut[i] = { linear(c[1] or 0), linear(c[2] or 0), linear(c[3] or 0), (c[4] or 255) / 255 } + end + end + for k = 0, nv - 1 do + local c = lut[buffer.readu8(g.index, k)] or lut[1] + if srgb then + for j = 0, 3 do + buffer.writeu8(col, k * 4 + j, c[j + 1]) + end + else + for j = 0, 3 do + writef32(col, k * 16 + j * 4, c[j + 1]) + end + end + end + attrs.COLOR_0 = Scene.accessor(col, if srgb then "unorm8" else "f32", 4, nv) + if opts and opts.indexAttribute then + attrs._PALETTE_INDEX = Scene.accessor(trim(g.index, nv), "u8", 1, nv) + end + return { attributes = attrs, indices = Scene.accessor(trim(g.indices, g.quads * 24), "u32", 1, g.quads * 6), mode = "triangles" }, nil +end + +function MeshOps.meshVoxels(scene: Scene, opts: { pivot: string?, scale: number?, colors: string?, indexAttribute: boolean? }?): (Scene?, Err.Err?) + if type(scene) ~= "table" or scene.kind ~= "scene" then + return nil, Err.new(Err.ARG, "expected a Scene") + end + local grids = scene.voxels or {} + local mat = 0 + local meshOf: { [number]: number } = {} + for i, v in grids do + local prim, err = MeshOps.voxelsToPrimitive(v, opts) + if not prim then + return nil, err + end + if mat == 0 then + local m = Scene.material("voxels") + m.metallic = 0 + table.insert(scene.materials, m) + mat = #scene.materials + end + prim.material = mat + table.insert(scene.meshes, { name = v.name or ("voxels " .. i), primitives = { prim } }) + meshOf[i] = #scene.meshes + end + for _, n in scene.nodes do + if n.voxels and meshOf[n.voxels] then + n.mesh = meshOf[n.voxels] + end + end + return scene, nil +end + +return MeshOps +end +__FILES["ops/MeshOps/Greedy"] = @native function() + + +-- ops/MeshOps/Greedy: greedy meshing of a dense voxel grid (one byte per cell, 0 = empty): for each axis and each +-- slice between two layers of cells, the exposed faces are masked by palette index, and runs of equal faces are merged +-- into maximal rectangles (Mikola Lysenko's "Meshing in a Minecraft game", 2012). Faces between two filled cells are +-- hidden whatever their indices. Output: 4 vertices and 2 triangles per rectangle, counter-clockwise seen from the +-- outside. Never throws; the caller checks buffer.len(data) >= sx * sy * sz. +local Greedy = {} + +local readu8, readi32, writei32 = buffer.readu8, buffer.readi32, buffer.writei32 +local writef32, writeu8, writeu32 = buffer.writef32, buffer.writeu8, buffer.writeu32 + +type Out = { + positions: buffer, -- f32 x3 per vertex + normals: buffer, -- f32 x3 per vertex + index: buffer, -- u8 palette index per vertex + indices: buffer, -- u32, 6 per quad + vertices: number, + quads: number, +} + +-- vertex position = (cell corner + (ox, oy, oz)) * scale +@native function Greedy.run(data: buffer, sx: number, sy: number, sz: number, ox: number, oy: number, oz: number, scale: number): Out + local cap = 1024 + local pos = buffer.create(cap * 48) + local nrm = buffer.create(cap * 48) + local idx = buffer.create(cap * 4) + local tri = buffer.create(cap * 24) + local quads = 0 + local maxFace = math.max(sx * sy, sy * sz, sz * sx) + local mask = buffer.create(maxFace * 4) + local corner = { 0, 0, 0 } + for d = 0, 2 do + -- u, v: the two other axes, cyclic so that e_u x e_v = e_d + local u, v = (d + 1) % 3, (d + 2) % 3 + local nd = if d == 0 then sx elseif d == 1 then sy else sz + local nu = if u == 0 then sx elseif u == 1 then sy else sz + local nv = if v == 0 then sx elseif v == 1 then sy else sz + local std = if d == 0 then 1 elseif d == 1 then sx else sx * sy + local stu = if u == 0 then 1 elseif u == 1 then sx else sx * sy + local stv = if v == 0 then 1 elseif v == 1 then sx else sx * sy + for slice = -1, nd - 1 do + -- the mask of faces between layer slice and slice + 1: +index (faces +d, owned by slice), -index (faces -d) + local any = false + for j = 0, nv - 1 do + for i = 0, nu - 1 do + local base = i * stu + j * stv + local a = if slice >= 0 then readu8(data, base + slice * std) else 0 + local b = if slice + 1 < nd then readu8(data, base + (slice + 1) * std) else 0 + local m = 0 + if a ~= 0 and b == 0 then + m = a + elseif a == 0 and b ~= 0 then + m = -b + end + if m ~= 0 then + any = true + end + writei32(mask, (i + j * nu) * 4, m) + end + end + if any then + for j = 0, nv - 1 do + local i = 0 + while i < nu do + local m = readi32(mask, (i + j * nu) * 4) + if m == 0 then + i += 1 + else + local w = 1 + while i + w < nu and readi32(mask, (i + w + j * nu) * 4) == m do + w += 1 + end + local h = 1 + local grow = true + while j + h < nv and grow do + for k = 0, w - 1 do + if readi32(mask, (i + k + (j + h) * nu) * 4) ~= m then + grow = false + break + end + end + if grow then + h += 1 + end + end + for jj = j, j + h - 1 do + for k = 0, w - 1 do + writei32(mask, (i + k + jj * nu) * 4, 0) + end + end + if quads == cap then + local ncap = cap * 2 + @native local function grow2(b: buffer, per: number): buffer + local nb = buffer.create(ncap * per) + 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) :: buffer + cap = ncap + end + corner[d + 1] = slice + 1 + corner[u + 1] = i + corner[v + 1] = j + local cx, cy, cz = corner[1], corner[2], corner[3] + local ux = if u == 0 then w else 0 + local uy = if u == 1 then w else 0 + local uz = if u == 2 then w else 0 + local vx = if v == 0 then h else 0 + local vy = if v == 1 then h else 0 + local vz = if v == 2 then h else 0 + local nsign = if m > 0 then 1 else -1 + local nx = if d == 0 then nsign else 0 + local ny = if d == 1 then nsign else 0 + local nz = if d == 2 then nsign else 0 + local col = if m > 0 then m else -m + local vb = quads * 48 + local px0, py0, pz0 = (cx + ox) * scale, (cy + oy) * scale, (cz + oz) * scale + writef32(pos, vb, px0) + writef32(pos, vb + 4, py0) + writef32(pos, vb + 8, pz0) + writef32(pos, vb + 12, px0 + ux * scale) + writef32(pos, vb + 16, py0 + uy * scale) + writef32(pos, vb + 20, pz0 + uz * scale) + writef32(pos, vb + 24, px0 + (ux + vx) * scale) + writef32(pos, vb + 28, py0 + (uy + vy) * scale) + writef32(pos, vb + 32, pz0 + (uz + vz) * scale) + writef32(pos, vb + 36, px0 + vx * scale) + writef32(pos, vb + 40, py0 + vy * scale) + writef32(pos, vb + 44, pz0 + vz * scale) + for k = 0, 3 do + writef32(nrm, vb + k * 12, nx) + writef32(nrm, vb + k * 12 + 4, ny) + writef32(nrm, vb + k * 12 + 8, nz) + writeu8(idx, quads * 4 + k, col) + end + local v0 = quads * 4 + local ib = quads * 24 + if m > 0 then + writeu32(tri, ib, v0) + writeu32(tri, ib + 4, v0 + 1) + writeu32(tri, ib + 8, v0 + 2) + writeu32(tri, ib + 12, v0) + writeu32(tri, ib + 16, v0 + 2) + writeu32(tri, ib + 20, v0 + 3) + else + writeu32(tri, ib, v0) + writeu32(tri, ib + 4, v0 + 2) + writeu32(tri, ib + 8, v0 + 1) + writeu32(tri, ib + 12, v0) + writeu32(tri, ib + 16, v0 + 3) + writeu32(tri, ib + 20, v0 + 2) + end + quads += 1 + i += w + end + end + end + end + end + end + return { positions = pos, normals = nrm, index = idx, indices = tri, vertices = quads * 4, quads = quads } +end + +return Greedy +end +__FILES["ops/MusicOps"] = function() + +-- ops/MusicOps: building and editing tracker Modules over codecs/audio/Tracker without touching the engine's internal +-- layout (5-byte cells, f32 samples, tuning fields). New code. +-- Conventions: pattern numbers are 0-based (as the order list names them), rows 0-based, channels 1-based, sample +-- and instrument numbers 1-based (0 = none in a cell). Notes are numbers (1 = C-0, 49 = C-4, 61 = C-5; 254 cut, 255 +-- key off, 253 fade) or names: "C-4", "C#4", "Db4", "off", "cut", "fade". Effects keep the format's own numbering +-- (MOD / XM 0..35, S3M / IT 1..26 = A..Z). Never throws: bad arguments return nil, Err.ARG. +local Err = __include("core/Err") +local Tracker = __include("codecs/audio/Tracker") + +local MusicOps = {} + +local FORMATS = { mod = true, xm = true, s3m = true, it = true } + +local function bad(what: string): (nil, Err.Err) + return nil, Err.new(Err.ARG, what) +end + +local function isModule(m: any): boolean + -- (the engine family: modules of the other tracker formats, music/mtm etc., play as one of the four) + return type(m) == "table" and m.kind == "music" and FORMATS[Tracker.family(m) or ""] == true and type(m.patterns) == "table" +end + +local function int(v: any, lo: number, hi: number): boolean + return type(v) == "number" and v == v and v % 1 == 0 and v >= lo and v <= hi +end + +type NewOptions = { + format: string?, -- "mod" (default), "xm", "s3m", "it": the effect family (mod and xm can be saved) + channels: number?, -- 1..32 for mod, else 1..64 (default 4) + title: string?, + speed: number?, -- ticks per row (default 6) + tempo: number?, -- BPM (default 125) +} + +function MusicOps.new(opts: NewOptions?): (any, Err.Err?) + local o: NewOptions = opts or {} + local format = o.format or "mod" + if not FORMATS[format] then + return bad("new: format must be mod, xm, s3m or it") + end + local channels = o.channels or 4 + if not int(channels, 1, if format == "mod" then 32 else 64) then + return bad("new: bad channel count") + end + local m = Tracker.newModule(format, channels) + m.title = if type(o.title) == "string" then o.title else "" + if o.speed ~= nil then + if not int(o.speed, 1, 255) then + return bad("new: speed must be 1..255") + end + m.speed = o.speed + end + if o.tempo ~= nil then + if type(o.tempo) ~= "number" or o.tempo < 32 or o.tempo > 1000 then + return bad("new: tempo must be 32..1000") + end + m.tempo = o.tempo + end + m.meta = { source = { format = format } } + return m, nil +end + +function MusicOps.addPattern(m: any, rows: number?, opts: { order: boolean? }?): (number?, Err.Err?) + if not isModule(m) then + return bad("addPattern: needs a tracker Module") + end + local n = rows or 64 + if not int(n, 1, 1024) then + return bad("addPattern: rows must be 1..1024") + end + table.insert(m.patterns, Tracker.newPattern(n, m.channels)) + local index = #m.patterns - 1 + if not (opts and opts.order == false) then + table.insert(m.order, index) + end + return index, nil +end + +local NAMES: { [string]: number } = { c = 0, d = 2, e = 4, f = 5, g = 7, a = 9, b = 11 } +local SPECIAL: { [string]: number } = { off = 255, ["==="] = 255, cut = 254, ["^^^"] = 254, fade = 253, ["~~~"] = 253 } + +function MusicOps.note(v: any): (number?, Err.Err?) + if type(v) == "number" then + if int(v, 0, 120) or v == 253 or v == 254 or v == 255 then + return v, nil + end + return bad("note: number must be 0..120 or 253..255") + end + if type(v) ~= "string" then + return bad("note: expected a number or a name") + end + local s = string.lower(v) + if SPECIAL[s] then + return SPECIAL[s], nil + end + local letter, acc, oct = string.match(s, "^([a-g])([#b%-]?)(%d)$") + if not letter then + return bad("note: bad name " .. v) + end + local n = NAMES[letter :: string] + (if acc == "#" then 1 elseif acc == "b" then -1 else 0) + local num = 1 + (tonumber(oct) :: number) * 12 + n + if num < 1 or num > 120 then + return bad("note: out of range " .. v) + end + return num, nil +end + +type Cell = { + note: (number | string)?, -- 0 / nil = none + instrument: number?, -- 1-based sample (MOD / S3M) or instrument (XM / IT); 0 = none + volume: number?, -- the volume column as the format stores it (0 = none) + effect: number?, -- the format's effect number (MOD / XM 0..35; S3M / IT 1..26) + param: number?, -- 0..255 +} + +local function patternAt(m: any, pattern: any, row: any, channel: any): (any, Err.Err?) + if not isModule(m) then + return bad("needs a tracker Module") + end + local p: any = if int(pattern, 0, 1e6) then m.patterns[pattern + 1] else nil + if p == nil then + return bad("no pattern " .. tostring(pattern)) + end + if not int(row, 0, p.rows - 1) then + return bad("row " .. tostring(row) .. " outside 0.." .. (p.rows - 1)) + end + if not int(channel, 1, m.channels) then + return bad("channel " .. tostring(channel) .. " outside 1.." .. m.channels) + end + return p, nil +end + +function MusicOps.setCell(m: any, pattern: number, row: number, channel: number, cell: Cell): (boolean?, Err.Err?) + local p, err = patternAt(m, pattern, row, channel) + if not p then + return nil, err + end + if type(cell) ~= "table" then + return bad("setCell: cell must be a table") + end + local note = 0 + if cell.note ~= nil then + local n, nerr = MusicOps.note(cell.note) + if not n then + return nil, nerr + end + note = n + end + for _, k in { "instrument", "volume", "effect", "param" } do + local v = (cell :: any)[k] + if v ~= nil and not int(v, 0, 255) then + return bad("setCell: " .. k .. " must be 0..255") + end + end + Tracker.setCell(m, pattern, row, channel, note, cell.instrument or 0, cell.volume or 0, cell.effect or 0, cell.param or 0) + return true, nil +end + +function MusicOps.getCell(m: any, pattern: number, row: number, channel: number): (Cell?, Err.Err?) + local p, err = patternAt(m, pattern, row, channel) + if not p then + return nil, err + end + local note, ins, vol, fx, param = Tracker.cell(m, pattern, row, channel) + return { note = note, instrument = ins, volume = vol, effect = fx, param = param }, nil +end + +type SampleSpec = { + name: string?, + audio: any?, -- an Audio (1 or 2 channels): the sample data and, unless rate is given, its rate + data: buffer?, -- or raw f32 frames (interleaved when channels = 2) ... + length: number?, -- ... with their frame count (default: the whole buffer) + channels: number?, -- 1 (default) or 2, for data + rate: number?, -- Hz the sample plays at on C-4 (MOD / XM) or C-5 (S3M / IT); default the Audio's, else 8363 + loop: string?, -- "none" (default), "forward", "pingpong" + loopStart: number?, -- frames (default 0) + loopEnd: number?, -- frames, exclusive (default the length) + volume: number?, -- 0..64 (default 64) + pan: number?, -- 0..256 (XM / IT; nil = the channel's) + bits: number?, -- 8 or 16: what writers store (default 8 for MOD, else 16) +} + +local LOOPS: { [string]: number } = { none = 0, forward = 1, pingpong = 2 } + +-- tuning: c5speed for S3M / IT; relativeNote + finetune (1/128 semitone from 8363 Hz) for MOD / XM (MOD stores +-- only the finetune, -1..+7/8 semitone) +function MusicOps.addSample(m: any, spec: SampleSpec): (number?, Err.Err?) + if not isModule(m) then + return bad("addSample: needs a tracker Module") + end + if type(spec) ~= "table" then + return bad("addSample: spec must be a table") + end + local data: buffer, length: number, channels: number + local rate = spec.rate + local a = spec.audio + if a ~= nil then + if type(a) ~= "table" or a.kind ~= "audio" or type(a.samples) ~= "buffer" or not int(a.frames, 0, 2 ^ 31) or (a.channels ~= 1 and a.channels ~= 2) or buffer.len(a.samples) < a.frames * a.channels * 4 then + return bad("addSample: audio must be a mono or stereo Audio") + end + data, length, channels = a.samples, a.frames, a.channels + rate = rate or a.sampleRate + elseif type(spec.data) == "buffer" then + channels = spec.channels or 1 + if channels ~= 1 and channels ~= 2 then + return bad("addSample: channels must be 1 or 2") + end + local d: buffer = spec.data + length = spec.length or buffer.len(d) // (4 * channels) + if not int(length, 0, 2 ^ 31) or buffer.len(d) < length * channels * 4 then + return bad("addSample: data shorter than length") + end + data = d + else + return bad("addSample: needs audio or data") + end + rate = rate or 8363 + if type(rate) ~= "number" or rate < 1 or rate > 1e7 then + return bad("addSample: bad rate") + end + local s = Tracker.newSample(spec.name) + local copy = buffer.create(length * channels * 4) + buffer.copy(copy, 0, data, 0, length * channels * 4) + s.data, s.length, s.channels = copy, length, channels + s.bits = spec.bits or (if Tracker.family(m) == "mod" then 8 else 16) + if s.bits ~= 8 and s.bits ~= 16 then + return bad("addSample: bits must be 8 or 16") + end + s.c5speed = rate + local semis = 12 * math.log(rate / 8363) / math.log(2) + local rn = math.floor(semis + 0.5) + if rn < -96 or rn > 95 then + return bad("addSample: rate out of range") + end + s.relativeNote = rn + s.finetune = math.clamp(math.floor((semis - rn) * 128 + 0.5), -128, 127) + local lt = LOOPS[spec.loop or "none"] + if lt == nil then + return bad("addSample: loop must be none, forward or pingpong") + end + if lt > 0 then + local ls, le = spec.loopStart or 0, spec.loopEnd or length + if not int(ls, 0, length) or not int(le, 0, length) or le - ls < 1 then + return bad("addSample: bad loop") + end + s.loopStart, s.loopEnd, s.loopType = ls, le, lt + end + if spec.volume ~= nil then + if type(spec.volume) ~= "number" or spec.volume < 0 or spec.volume > 64 then + return bad("addSample: volume must be 0..64") + end + s.volume = spec.volume + end + if spec.pan ~= nil then + if type(spec.pan) ~= "number" or spec.pan < 0 or spec.pan > 256 then + return bad("addSample: pan must be 0..256") + end + s.pan = spec.pan + end + table.insert(m.samples, s) + return #m.samples, nil +end + +type InstrumentSpec = { + name: string?, + sample: number?, -- the sample every note plays (1-based) + samples: { [number]: number }?, -- or a keymap: note number -> sample number (other notes: none) + fadeout: number?, -- volume fade per tick after key off, as the format stores it (XM 0..4095, IT 0..1024) + envelope: { points: { { number } }, sustain: number?, loopStart: number?, loopEnd: number? }?, -- volume + -- envelope: points { tick, 0..64 } with ticks increasing; sustain / loop points are 1-based point indexes +} + +-- instruments: XM and IT only (MOD / S3M cells name samples directly) +function MusicOps.addInstrument(m: any, spec: InstrumentSpec): (number?, Err.Err?) + if not isModule(m) then + return bad("addInstrument: needs a tracker Module") + end + if Tracker.family(m) ~= "xm" and Tracker.family(m) ~= "it" then + return bad("addInstrument: only xm and it modules have instruments (mod / s3m cells name samples)") + end + if type(spec) ~= "table" then + return bad("addInstrument: spec must be a table") + end + local ins = Tracker.newInstrument(spec.name) + if spec.sample ~= nil then + if not int(spec.sample, 1, #m.samples) then + return bad("addInstrument: no sample " .. tostring(spec.sample)) + end + for n = 1, 120 do + ins.sampleMap[n] = spec.sample + end + elseif type(spec.samples) == "table" then + for note, smp in spec.samples do + if not int(note, 1, 120) or not int(smp, 0, #m.samples) then + return bad("addInstrument: bad keymap entry") + end + ins.sampleMap[note] = smp + end + end + if spec.fadeout ~= nil then + if not int(spec.fadeout, 0, 65535) then + return bad("addInstrument: bad fadeout") + end + ins.fadeout = spec.fadeout + end + local e = spec.envelope + if e ~= nil then + if type(e) ~= "table" or type(e.points) ~= "table" or #e.points == 0 then + return bad("addInstrument: envelope needs points") + end + local env = Tracker.newEnvelope() + local last = -1 + for i, pt in e.points do + local tick: any, value: any = nil, nil + if type(pt) == "table" then + tick, value = pt[1], pt[2] + end + if not int(tick, 0, 65535) or type(value) ~= "number" or value < 0 or value > 64 or (tick :: number) <= last then + return bad("addInstrument: envelope point " .. i .. " must be { tick, 0..64 } with increasing ticks") + end + last = tick :: number + env.ticks[i], env.values[i] = tick, value + end + env.enabled = true + local n = #e.points + if e.sustain ~= nil then + if not int(e.sustain, 1, n) then + return bad("addInstrument: bad sustain point") + end + env.sustain, env.susStart, env.susEnd = true, e.sustain, e.sustain + end + if e.loopStart ~= nil or e.loopEnd ~= nil then + local ls, le = e.loopStart or 1, e.loopEnd or n + if not int(ls, 1, n) or not int(le, ls, n) then + return bad("addInstrument: bad envelope loop") + end + env.loop, env.loopStart, env.loopEnd = true, ls, le + end + ins.volEnv = env + end + table.insert(m.instruments, ins) + return #m.instruments, nil +end + +return MusicOps +end +end + + + + + + playlist + --!optimize 2 +--!nocheck +-- rosetta chunk playlist (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 3 modules (0 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["playlist/m3u"] = function() + +-- playlist/m3u: M3U / M3U8 and HLS (RFC 8216) playlists, absorbed from playlist-luau 3fc7fd3 (same author). Supports: +-- #EXTM3U / #EXTINF / #PLAYLIST, plain lists, BOM, CRLF / CR, Windows-1252, HLS master and media playlists; locations +-- resolve per RFC 3986; mp3 HLS segments are playable, .ts / .aac / fMP4 are flagged. Not supported: writing HLS tags. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Sniff = __include("core/Sniff") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Url = __include("codecs/text/Url") +local Text = __include("codecs/text/Text") + +-- ------------------------------------------------------------------------------------------------ contract +local M3u = { + name = "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/text/Url", "codecs/text/Text", "core/Sniff" }, + caps = { decode = true, encode = true, hls = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type Entry = { + url: string, + title: string?, + duration: number?, -- seconds; -1 in the file = unknown + playable: boolean, + reason: string?, + bandwidth: number?, -- BANDWIDTH + codecs: string?, -- CODECS + attributes: { [string]: string }?, -- EXT-X-STREAM-INF / EXT-X-MEDIA attribute list + byteRange: { length: number, offset: number? }?, -- media: EXT-X-BYTERANGE +} + +type Hls = { + master: boolean, + targetDuration: number?, + mediaSequence: number?, + endList: boolean, -- EXT-X-ENDLIST (false = live) + encrypted: boolean, -- EXT-X-KEY with a METHOD other than NONE + totalDuration: number?, + segmentFormat: string?, +} + +type Result = { + kind: "playlist", + format: "m3u" | "pls" | "hls" | "xspf", + meta: { [string]: any }, + entries: { Entry }, + warnings: { string }, + title: string?, -- #PLAYLIST: + hls: Hls?, +} + +type DecodeOptions = { + baseUrl: string?, + maxBytes: number?, -- default 64 MB +} +type EncodeOptions = { + title: string?, -- #PLAYLIST: (default: the playlist's title) +} + +-- ------------------------------------------------------------------------------------------------ constants +local UNSUPPORTED_SEGMENTS = { ts = true, aac = true, m4s = true, mp4 = true, m4a = true, fmp4 = true, cmfa = true } + +local function extension(url: string): string? + local p = Url.split(url).path + local ext = string.match(p, "%.([%w]+)$") + return if ext then string.lower(ext) else nil +end + +local function duration(s: string?): number? + local d = tonumber(s and Text.trim(s)) + if not d or d < 0 or d ~= d or d == math.huge then + return nil + end + 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:<duration>[ attr="v" ...],<title> +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 M3u.sniff(r: Bytes.Reader): number + local s = Sniff.text(r, 512) + s = (string.match(s, "^%s*(.*)$") :: string) + if string.sub(s, 1, 7) == "#EXTM3U" then + return 0.95 + end + if string.find(s, "^#EXTINF:") or string.find(s, "^#EXT%-X%-") then + return 0.8 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function parseM3u(ls: { string }, base: string?, baseScheme: string?, warnings: { string }): Result + local res: Result = { kind = "playlist", format = "m3u", entries = {}, warnings = warnings, meta = {} } + local pendingDur, pendingTitle = nil, nil + for n, line in ls do + local l = Text.trim(line) + if l == "" then + continue + end + if string.sub(l, 1, 1) == "#" then + local upper = string.upper(string.sub(l, 1, 10)) + if string.sub(upper, 1, 8) == "#EXTINF:" then + pendingDur, pendingTitle = extinf(string.sub(l, 9)) + elseif string.sub(upper, 1, 10) == "#PLAYLIST:" then + res.title = Text.trim(string.sub(l, 11)) + end + -- #EXTM3U, #EXTGRP, #EXTALB, ... and plain comments: ignored + continue + end + local e: Entry = Url.locate(l, base, baseScheme) + e.title = pendingTitle + e.duration = pendingDur + pendingDur, pendingTitle = nil, nil + table.insert(res.entries, e) + if e.reason and e.reason ~= "local path" then + table.insert(warnings, ("line %d: %s: %s"):format(n, e.reason, e.url)) + end + end + return res +end + +local function parseHls(ls: { string }, base: string?, baseScheme: string?, warnings: { string }): Result + local hls: Hls = { master = false, endList = false, encrypted = false } + local res: Result = { kind = "playlist", format = "hls", entries = {}, warnings = warnings, hls = hls, meta = {} } + local pendingDur, pendingTitle, pendingRange = nil, nil, nil + local pendingStream: { [string]: string }? = nil + local lastRangeEnd: number? = nil + local total = 0 + local formats = {} + local fmp4 = false + for n, line in ls do + local l = Text.trim(line) + if l == "" then + continue + end + if string.sub(l, 1, 1) == "#" then + local tag, rest = string.match(l, "^(#[%w%-]+):?(.*)$") + tag = if tag then string.upper(tag) else nil + if tag == "#EXT-X-STREAM-INF" then + hls.master = true + pendingStream = attributes(rest :: string) + elseif tag == "#EXT-X-MEDIA" then + hls.master = true + local a = attributes(rest :: string) + if a.URI then + local e: Entry = Url.locate(a.URI, base, baseScheme) + e.title = a.NAME + e.attributes = a + e.codecs = a.CODECS + table.insert(res.entries, e) + end + elseif tag == "#EXT-X-TARGETDURATION" then + hls.targetDuration = tonumber(Text.trim(rest :: string)) + elseif tag == "#EXT-X-MEDIA-SEQUENCE" then + hls.mediaSequence = tonumber(Text.trim(rest :: string)) + elseif tag == "#EXT-X-ENDLIST" then + hls.endList = true + elseif tag == "#EXT-X-KEY" then + local a = attributes(rest :: string) + if a.METHOD and string.upper(a.METHOD) ~= "NONE" then + if not hls.encrypted then + table.insert(warnings, ("line %d: encrypted segments (METHOD=%s) are not supported"):format(n, a.METHOD)) + end + hls.encrypted = true + end + elseif tag == "#EXT-X-MAP" then + fmp4 = true + elseif tag == "#EXTINF" then + pendingDur, pendingTitle = extinf(rest :: string) + elseif tag == "#EXT-X-BYTERANGE" then + local len, off = string.match(rest :: string, "^%s*(%d+)@?(%d*)") + if len then + local o = tonumber(off) or lastRangeEnd + pendingRange = { length = tonumber(len) :: number, offset = o } + lastRangeEnd = (o or 0) + (tonumber(len) :: number) + end + end + continue + end + local e: Entry = Url.locate(l, base, baseScheme) + if pendingStream then + e.attributes = pendingStream + e.bandwidth = tonumber(pendingStream.BANDWIDTH) + e.codecs = pendingStream.CODECS + e.title = pendingStream.NAME + pendingStream = nil + else + e.title = pendingTitle + e.duration = pendingDur + e.byteRange = pendingRange + if pendingDur then + total += pendingDur + end + local ext = extension(e.url) or "?" + formats[ext] = true + if e.playable and (UNSUPPORTED_SEGMENTS[ext] or fmp4) then + e.playable = false + e.reason = "segment format " .. (if fmp4 then "fmp4" else ext) + end + if e.playable and hls.encrypted then + e.playable = false + e.reason = "encrypted" + end + end + pendingDur, pendingTitle, pendingRange = nil, nil, nil + table.insert(res.entries, e) + if e.reason == "relative path without a base URL" or (e.reason and string.sub(e.reason, 1, 7) == "scheme ") then + table.insert(warnings, ("line %d: %s: %s"):format(n, e.reason, e.url)) + end + end + if not hls.master then + hls.totalDuration = total + local list = {} + for ext in formats do + table.insert(list, ext) + end + table.sort(list) + hls.segmentFormat = if #list == 1 then list[1] elseif #list == 0 then nil else "mixed" + local bad = {} + for _, ext in list do + if UNSUPPORTED_SEGMENTS[ext] then + table.insert(bad, "." .. ext) + end + end + if fmp4 then + table.insert(bad, "fMP4 (EXT-X-MAP)") + end + if #bad > 0 then + table.insert(warnings, "HLS segments are " .. table.concat(bad, ", ") + .. ": only mp3 segments can be played (concatenated)") + end + if not hls.endList then + table.insert(warnings, "live HLS playlist (no EXT-X-ENDLIST): it has to be reloaded for new segments") + end + end + return res +end + +function M3u.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Playlist?, Err.Err?) + local n = r.limit - r.pos + if n > (opts and opts.maxBytes or 2 ^ 26) then + return nil, Err.new(Err.LIMIT, "playlist over the size limit") + end + local warnings = {} + local base, baseScheme = Url.base(opts and opts.baseUrl, warnings) + local t = Text.toUtf8(r:string(n), warnings) + local ls = Text.lines(t) + local res = if string.find(t, "#EXT%-X%-") then parseHls(ls, base, baseScheme, warnings) else parseM3u(ls, base, baseScheme, warnings) + local nLocal = 0 + for _, e in res.entries do + if e.reason == "local path" then + nLocal += 1 + end + end + if nLocal > 0 then + table.insert(warnings, string.format("%d local path%s (not playable)", nLocal, if nLocal == 1 then "" else "s")) + end + res.meta.source = { format = "m3u", hls = res.format == "hls" } + return res :: any, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function serialize(entries: { any }, opts: { title: string? }?): string + local out = { "#EXTM3U" } + local function clean(s: string): string + return (string.gsub(s, "[\r\n]+", " ")) + end + if opts and opts.title then + table.insert(out, "#PLAYLIST:" .. clean(opts.title)) + end + for _, e in entries or {} do + if type(e) ~= "table" or type(e.url) ~= "string" then + continue + end + local d = tonumber(e.duration) + local secs = if d and d >= 0 and d == d and d ~= math.huge then math.floor(d + 0.5) else -1 + if e.title or d then + table.insert(out, ("#EXTINF:%d,%s"):format(secs, clean(tostring(e.title or "")))) + end + table.insert(out, clean(e.url)) + end + return table.concat(out, "\n") .. "\n" +end + +function M3u.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(value) ~= "table" then + return nil, Err.new(Err.ARG, "encode: needs a Playlist or a list of entries") + end + local entries = if type(value.entries) == "table" then value.entries else value + local title = if opts and opts.title then opts.title else value.title + return buffer.fromstring(serialize(entries, { title = if type(title) == "string" then title else nil })), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +M3u.Url = Url + +return M3u +end +__FILES["playlist/pls"] = function() + +-- playlist/pls: PLS playlists ([playlist], FileN / TitleN / LengthN, NumberOfEntries, Version), absorbed from +-- playlist-luau 3fc7fd3 (same author) plus a new writer. Supports: keys in any case / order, comments, BOM, CRLF / CR, +-- Windows-1252, numbering gaps; locations resolve per RFC 3986. Encode: Version=2, Length -1 for unknown durations. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Sniff = __include("core/Sniff") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Url = __include("codecs/text/Url") +local Text = __include("codecs/text/Text") + +-- ------------------------------------------------------------------------------------------------ contract +local Pls = { + name = "pls", + category = "playlist", + extensions = { "pls" }, + mime = { "audio/x-scpls", "audio/scpls" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Url", "codecs/text/Text", "core/Sniff" }, + caps = { decode = true, encode = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type Entry = { + url: string, + title: string?, + duration: number?, -- seconds; -1 in the file = unknown + playable: boolean, + reason: string?, + bandwidth: number?, -- BANDWIDTH + codecs: string?, -- CODECS + attributes: { [string]: string }?, -- EXT-X-STREAM-INF / EXT-X-MEDIA attribute list + byteRange: { length: number, offset: number? }?, -- media: EXT-X-BYTERANGE +} + +type Hls = { + master: boolean, + targetDuration: number?, + mediaSequence: number?, + endList: boolean, -- EXT-X-ENDLIST (false = live) + encrypted: boolean, -- EXT-X-KEY with a METHOD other than NONE + totalDuration: number?, + segmentFormat: string?, +} + +type Result = { + kind: "playlist", + format: "m3u" | "pls" | "hls" | "xspf", + meta: { [string]: any }, + entries: { Entry }, + warnings: { string }, + title: string?, -- #PLAYLIST: + hls: Hls?, +} + +type DecodeOptions = { + baseUrl: string?, + maxBytes: number?, -- default 64 MB +} + +-- ------------------------------------------------------------------------------------------------ constants +local function duration(s: string?): number? + local d = tonumber(s and Text.trim(s)) + if not d or d < 0 or d ~= d or d == math.huge then + return nil + end + return d +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Pls.sniff(r: Bytes.Reader): number + 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 + +-- ------------------------------------------------------------------------------------------------ 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: { [number]: string }, titles: { [number]: string }, lengths: { [number]: string } = {}, {}, {} + local declared = nil + for _, line in ls do + local l = Text.trim(line) + if l == "" or string.sub(l, 1, 1) == ";" or string.sub(l, 1, 1) == "#" or string.sub(l, 1, 1) == "[" then + continue + end + local key, value = string.match(l, "^([^=]-)%s*=%s*(.*)$") + if not key then + continue + end + local k = string.lower(Text.trim(key :: string)) + local name, idx = string.match(k, "^(%a+)(%d+)$") + local i = tonumber(idx) + if name == "file" and i then + files[i] = value + elseif name == "title" and i then + titles[i] = value + elseif name == "length" and i then + lengths[i] = value + elseif k == "numberofentries" then + declared = tonumber(value) + end + end + local order = {} + for i in files do + table.insert(order, i) + end + table.sort(order) + for _, i in order do + local e: Entry = Url.locate(files[i], base, baseScheme) + local t = titles[i] and Text.trim(titles[i]) + e.title = if t and t ~= "" then t else nil + e.duration = duration(lengths[i]) + table.insert(res.entries, e) + if e.reason and e.reason ~= "local path" then + table.insert(warnings, ("File%d: %s: %s"):format(i, e.reason, e.url)) + end + end + if declared and declared ~= #order then + table.insert(warnings, ("NumberOfEntries=%d but %d files"):format(declared, #order)) + end + return res +end + +function Pls.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Playlist?, Err.Err?) + local n = r.limit - r.pos + if n > (opts and opts.maxBytes or 2 ^ 26) then + return nil, Err.new(Err.LIMIT, "playlist over the size limit") + end + local warnings = {} + local base, baseScheme = Url.base(opts and opts.baseUrl, warnings) + local t = Text.toUtf8(r:string(n), warnings) + local res = parsePls(Text.lines(t), base, baseScheme, warnings) + local nLocal = 0 + for _, e in res.entries do + if e.reason == "local path" then + nLocal += 1 + end + end + if nLocal > 0 then + table.insert(warnings, string.format("%d local path%s (not playable)", nLocal, if nLocal == 1 then "" else "s")) + end + res.meta.source = { format = "pls" } + return res :: any, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Pls.encode(value: any, _opts: any?): (buffer?, Err.Err?) + if type(value) ~= "table" then + return nil, Err.new(Err.ARG, "encode: needs a Playlist or a list of entries") + end + local entries = if type(value.entries) == "table" then value.entries else value + local function clean(s: string): string + return (string.gsub(s, "[\r\n]+", " ")) + end + local out = { "[playlist]" } + local n = 0 + for _, e in entries do + if type(e) == "table" and type(e.url) == "string" then + n += 1 + table.insert(out, string.format("File%d=%s", n, clean(e.url))) + if type(e.title) == "string" then + table.insert(out, string.format("Title%d=%s", n, clean(e.title))) + end + local d = tonumber(e.duration) + local secs = if d and d >= 0 and d == d and d ~= math.huge then math.floor(d + 0.5) else -1 + table.insert(out, string.format("Length%d=%d", n, secs)) + end + end + table.insert(out, "NumberOfEntries=" .. n) + table.insert(out, "Version=2") + return buffer.fromstring(table.concat(out, "\n") .. "\n"), nil +end + +return Pls +end +__FILES["playlist/xspf"] = function() + +-- playlist/xspf: XSPF 1 (https://xspf.org/spec) playlists on codecs/text/Xml. Supports: playlist and track metadata, +-- every track location (entry.locations), duration (ms), xml:base then opts.baseUrl (RFC 3986). +-- Not supported: extension / link / meta elements (skipped), XSPF version 0 differences. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Url = __include("codecs/text/Url") +local Xml = __include("codecs/text/Xml") + +-- ------------------------------------------------------------------------------------------------ contract +local Xspf = { + name = "xspf", + category = "playlist", + extensions = { "xspf" }, + mime = { "application/xspf+xml" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Url", "codecs/text/Xml" }, + caps = { decode = true, encode = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + baseUrl: string?, + maxBytes: number?, -- default 64 MB +} + +-- ------------------------------------------------------------------------------------------------ constants +local NS = "http://xspf.org/ns/0/" +local PLAYLIST_FIELDS = { "title", "creator", "annotation", "info", "location", "identifier", "image", "date", "license" } +local TRACK_FIELDS = { "title", "creator", "album", "annotation", "info", "image" } + +local function trim(s: string): string + return (string.match(s, "^%s*(.-)%s*$") :: string) +end + +local function field(node: any, name: string): string? + for _, c in node.children do + if type(c) == "table" and Xml.localName(c.name) == name then + local s = trim(Xml.text(c)) + return if s ~= "" then s else nil + end + end + return nil +end + +local function elements(node: any, name: string): { any } + local out = {} + for _, c in node.children do + if type(c) == "table" and Xml.localName(c.name) == name then + table.insert(out, c) + end + end + return out +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Xspf.sniff(r: Bytes.Reader): number + local s = r:peek(1024) + local i = string.find(s, "<%w*:?playlist[%s>]") + if i and string.find(s, NS, 1, true) then + return 0.95 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Xspf.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Playlist?, Err.Err?) + local n = r.limit - r.pos + if n > (opts and opts.maxBytes or 2 ^ 26) then + return nil, Err.new(Err.LIMIT, "playlist over the size limit") + end + local doc, err = Xml.decode(r:string(n)) + if not doc then + return nil, err + end + local root = (doc :: any).root + if not root or Xml.localName(root.name) ~= "playlist" then + return nil, Err.new(Err.CORRUPT, "the root element is not <playlist>") + end + local warnings: { string } = {} + local base, baseScheme = Url.base(opts and opts.baseUrl, warnings) + local function withXmlBase(node: any, b: string?, s: string?): (string?, string?) + local xb = node.attrs and node.attrs["xml:base"] + if type(xb) ~= "string" or xb == "" then + return b, s + end + local l = Url.locate(xb, b, s) + if Url.scheme(l.url) then + return l.url, Url.scheme(l.url) + end + return b, s + end + local pbase, pscheme = withXmlBase(root, base, baseScheme) + local pl: any = { + kind = "playlist", + format = "xspf", + entries = {}, + warnings = warnings, + title = field(root, "title"), + meta = { source = { format = "xspf", version = root.attrs and root.attrs.version } }, + } + for _, k in PLAYLIST_FIELDS do + if k ~= "title" then + pl.meta[k] = field(root, k) + end + end + local nLocal = 0 + for _, list in elements(root, "trackList") do + for i, track in elements(list, "track") do + local tbase, tscheme = withXmlBase(track, pbase, pscheme) + local locs: { string } = {} + for _, l in elements(track, "location") do + local s = trim(Xml.text(l)) + if s ~= "" then + table.insert(locs, s) + end + end + if #locs == 0 then + table.insert(warnings, string.format("track %d: no location", i)) + else + local e: any = Url.locate(locs[1], tbase, tscheme) + for _, k in TRACK_FIELDS do + e[k] = field(track, k) + end + local d = tonumber(field(track, "duration")) + e.duration = if d and d >= 0 and d == d and d ~= math.huge then d / 1000 else nil + e.trackNum = tonumber(field(track, "trackNum")) + if #locs > 1 then + local all = {} + for _, l in locs do + table.insert(all, Url.locate(l, tbase, tscheme).url) + end + e.locations = all + end + if e.reason == "local path" then + nLocal += 1 + elseif e.reason then + table.insert(warnings, string.format("track %d: %s: %s", i, e.reason, e.url)) + end + table.insert(pl.entries, e) + end + end + end + if nLocal > 0 then + table.insert(warnings, string.format("%d local path%s (not playable)", nLocal, if nLocal == 1 then "" else "s")) + end + return pl, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Xspf.encode(value: any, opts: { indent: number?, title: string? }?): (buffer?, Err.Err?) + if type(value) ~= "table" then + return nil, Err.new(Err.ARG, "encode: needs a Playlist or a list of entries") + end + local entries = if type(value.entries) == "table" then value.entries else value + local root = Xml.element("playlist", { version = "1", xmlns = NS }) + local function add(parent: any, name: string, v: any) + if type(v) == "string" and v ~= "" then + Xml.append(parent, Xml.element(name, nil, { v })) + elseif type(v) == "number" and v == v and v ~= math.huge and v ~= -math.huge then + Xml.append(parent, Xml.element(name, nil, { tostring(math.floor(v + 0.5)) })) + end + end + local title = if opts and opts.title then opts.title else value.title + add(root, "title", title) + local meta = if type(value.meta) == "table" then value.meta else {} + for _, k in PLAYLIST_FIELDS do + if k ~= "title" then + add(root, k, meta[k]) + end + end + local list = Xml.append(root, Xml.element("trackList")) + for _, e in entries do + if type(e) == "table" and type(e.url) == "string" then + local tr = Xml.append(list, Xml.element("track")) + add(tr, "location", e.url) + if type(e.locations) == "table" then + for i = 2, #e.locations do + add(tr, "location", e.locations[i]) + end + end + for _, k in TRACK_FIELDS do + add(tr, k, e[k]) + end + local d = tonumber(e.duration) + if d and d >= 0 then + add(tr, "duration", d * 1000) + end + add(tr, "trackNum", tonumber(e.trackNum)) + end + end + local s = Xml.encode(Xml.document(root), { indent = if opts and opts.indent ~= nil then opts.indent else 2 }) + if type(s) ~= "string" then + return nil, Err.new(Err.ARG, "encode: the XML serializer failed") + end + return buffer.fromstring(s), nil +end + +return Xspf +end +end + + + + + + subtitle + --!optimize 2 +--!nocheck +-- rosetta chunk subtitle (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 3 modules (0 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["subtitle/ass"] = function() + +-- subtitle/ass: ASS (v4.00+) / SSA (v4.00) scripts (de-facto spec of Aegisub / libass / ffmpeg). Supports: Script +-- Info, Styles, Events (Dialogue / Comment), other sections verbatim, H:MM:SS.cc; {\i1} {\b1} {\u1} {\s1} as the shared +-- markup (cue.raw keeps the original). Not supported: rendering, karaoke timing (\k), embedded font / graphic decoding. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Sniff = __include("core/Sniff") +local Bytes = __include("core/Bytes") +local Types = __include("Types") + +-- ------------------------------------------------------------------------------------------------ contract +local Ass = { + name = "ass", + category = "subtitle", + extensions = { "ass", "ssa" }, + mime = { "text/x-ssa", "text/x-ass" }, + deps = { "core/Err", "core/Bytes", "Types", "core/Sniff" }, + caps = { decode = true, encode = true, styles = true }, +} + +type DecodeOptions = { + maxBytes: number?, -- default 64 MB +} +type EncodeOptions = { + crlf: boolean?, -- default false +} + +-- ------------------------------------------------------------------------------------------------ constants +local STYLE_FORMAT = { "Name", "Fontname", "Fontsize", "PrimaryColour", "SecondaryColour", "OutlineColour", "BackColour", "Bold", "Italic", "Underline", "StrikeOut", "ScaleX", "ScaleY", "Spacing", "Angle", "BorderStyle", "Outline", "Shadow", "Alignment", "MarginL", "MarginR", "MarginV", "Encoding" } +local STYLE_DEFAULT: { [string]: string } = { + Name = "Default", + Fontname = "Arial", + Fontsize = "16", + PrimaryColour = "&Hffffff", + SecondaryColour = "&Hffffff", + OutlineColour = "&H0", + TertiaryColour = "&H0", + BackColour = "&H0", + Bold = "0", + Italic = "0", + Underline = "0", + StrikeOut = "0", + ScaleX = "100", + ScaleY = "100", + Spacing = "0", + Angle = "0", + BorderStyle = "1", + Outline = "1", + Shadow = "0", + Alignment = "2", + MarginL = "10", + MarginR = "10", + MarginV = "10", + AlphaLevel = "0", + Encoding = "0", +} +local EVENT_FORMAT = { "Layer", "Start", "End", "Style", "Name", "MarginL", "MarginR", "MarginV", "Effect", "Text" } +local EVENT_KEY = { Layer = "layer", Name = "name", Actor = "name", MarginL = "marginL", MarginR = "marginR", MarginV = "marginV", Effect = "effect", Marked = "marked" } + +local function trim(s: string): string + return (string.match(s, "^%s*(.-)%s*$")) :: string +end + +local function fields(s: string): { string } + local out = {} + for _, f in string.split(s, ",") do + table.insert(out, trim(f)) + end + return out +end + +local function time(s: string): number? + local h, m, sec, f = string.match(s, "^%s*(%d+):(%d+):(%d+)%.?(%d*)%s*$") + if not h then + return nil + end + local fr = if f ~= "" then (tonumber(f) :: number) / 10 ^ #(f :: string) else 0 + return tonumber(h) :: number * 3600 + tonumber(m) :: number * 60 + tonumber(sec) :: number + fr +end + +local TAGS = { i = "i", b = "b", u = "u", s = "s" } +function Ass.toMarkup(raw: string): string + local open: { [string]: boolean } = {} + local out = string.gsub(raw, "{([^}]*)}", function(block: string): string + local acc = {} + for tag, arg in string.gmatch(block, "\\(%a+)([^\\]*)") do + local t = TAGS[tag] + if t then + local on = arg == "" or (tonumber(arg) or 0) ~= 0 + if arg == "" then + on = not open[t] + end + if on and not open[t] then + table.insert(acc, "<" .. t .. ">") + open[t] = true + elseif not on and open[t] then + table.insert(acc, "</" .. t .. ">") + open[t] = false + end + elseif tag == "r" then + for _, k in { "s", "u", "b", "i" } do + if open[k] then + table.insert(acc, "</" .. k .. ">") + open[k] = false + end + end + end + end + return table.concat(acc) + end) + out = string.gsub(out, "\\[Nn]", "\n") + out = string.gsub(out, "\\h", "\194\160") + for _, k in { "s", "u", "b", "i" } do + if open[k] then + out ..= "</" .. k .. ">" + end + end + return out +end + +function Ass.fromMarkup(text: string): string + local s = string.gsub(text, "\r\n?", "\n") + s = string.gsub(s, "<(/?)(%a+)[^>]*>", function(close: string, tag: string): string + local t = TAGS[string.lower(tag)] + if not t then + return "" + end + return "{\\" .. t .. (if close == "/" then "0" else "1") .. "}" + end) + s = string.gsub(s, "\n", "\\N") + return s +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Ass.sniff(r: Bytes.Reader): number + local head = Sniff.text(r, 64) + if string.match(head, "^%s*%[[Ss]cript [Ii]nfo%]") then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Ass.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Subtitles?, Err.Err?) + local maxBytes = opts and opts.maxBytes or 2 ^ 26 + if r.limit - r.base > maxBytes then + return nil, Err.new(Err.LIMIT, "file is over the " .. maxBytes .. " byte limit") + end + if Ass.sniff(r) == 0 then + return nil, Err.new(Err.CORRUPT, "missing [Script Info]", r.base) + end + local s = buffer.readstring(r.buf, r.base, r.limit - r.base) + if string.find(s, "\0", 1, true) then + return nil, Err.new(Err.CORRUPT, "binary data (NUL bytes) in a text format") + end + s = Sniff.dropBom(s) + s = string.gsub(s, "\r\n", "\n") + s = string.gsub(s, "\r", "\n") + local subs = Types.Subtitles.new() + local info: { [string]: string } = {} + local infoOrder: { string } = {} + local styleFormat: { string }? = nil + local styleOrder: { string } = {} + local eventFormat: { string } = EVENT_FORMAT + local comments = {} + local sections: { { name: string, lines: { string } } } = {} + local section = "" + local stylesName: string? = nil + for _, line in string.split(s, "\n") do + local name = string.match(line, "^%s*%[(.-)%]%s*$") + if name then + section = string.lower(name) + if section == "v4+ styles" or section == "v4 styles" or section == "v4 styles+" then + stylesName = name + section = "styles" + elseif section ~= "script info" and section ~= "events" then + table.insert(sections, { name = name, lines = {} :: { string } }) + end + continue + end + if section == "script info" then + if string.sub(line, 1, 1) == ";" or string.sub(line, 1, 1) == "!" then + table.insert(infoOrder, line) -- `;` / `!` comment line, kept in place + else + local k, v = string.match(line, "^([^:]+):%s?(.*)$") + if k then + k = trim(k) + if info[k] == nil then + table.insert(infoOrder, k) + end + info[k] = v :: string + end + end + elseif section == "styles" then + local k, v = string.match(line, "^%s*(%a+):%s*(.*)$") + if k == "Format" then + styleFormat = fields(v :: string) + elseif k == "Style" then + local fmt = styleFormat or STYLE_FORMAT + local vals = string.split(v :: string, ",") + local st: { [string]: string } = {} + for fi, f in fmt do + st[f] = trim(vals[fi] or "") + end + local sname = st.Name or "" + if subs.styles[sname] == nil then + table.insert(styleOrder, sname) + end + subs.styles[sname] = st + end + elseif section == "events" then + local k, v = string.match(line, "^%s*(%a+):%s?(.*)$") + if k == "Format" then + eventFormat = fields(v :: string) + elseif k == "Dialogue" or k == "Comment" then + local vals: { string } = {} + local rest = v :: string + for fi = 1, #eventFormat do + if fi == #eventFormat then + vals[fi] = rest + else + local c = string.find(rest, ",", 1, true) + if not c then + vals[fi] = rest + rest = "" + else + vals[fi] = string.sub(rest, 1, c - 1) + rest = string.sub(rest, c + 1) + end + end + end + local cue: { [string]: any } = { text = "", start = 0, stop = 0 } + local ok = true + for fi, f in eventFormat do + local val = vals[fi] or "" + if f == "Start" or f == "End" then + local t = time(val) + if not t then + ok = false + else + cue[if f == "Start" then "start" else "stop"] = t + end + elseif f == "Text" then + cue.raw = val + cue.text = Ass.toMarkup(val) + elseif f == "Style" then + cue.style = trim(val) + elseif f == "Layer" then + cue.layer = tonumber(trim(val)) or 0 + else + cue[EVENT_KEY[f] or f] = trim(val) + end + end + if ok then + if k == "Comment" then + cue.after = #subs.cues + table.insert(comments, cue) + else + table.insert(subs.cues, cue :: any) + end + end + end + elseif section ~= "" then + table.insert(sections[#sections].lines, line) + end + end + subs.meta.scriptInfo = info + subs.meta.scriptInfoOrder = infoOrder + subs.meta.styleFormat = styleFormat + subs.meta.styleOrder = styleOrder + subs.meta.stylesSection = stylesName + subs.meta.eventFormat = eventFormat + if #comments > 0 then + subs.meta.comments = comments + end + if #sections > 0 then + for _, sec in sections do + while #sec.lines > 0 and string.match(sec.lines[#sec.lines], "^%s*$") do + table.remove(sec.lines) + end + end + subs.meta.sections = sections + end + subs.meta.source = { format = "ass", scriptType = info.ScriptType } + return subs, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function stamp(t: number): string + local cs = math.floor(t * 100 + 0.5) + return string.format("%d:%02d:%02d.%02d", cs // 360000, cs // 6000 % 60, cs // 100 % 60, cs % 100) +end + +local function field(v: any): string + return (string.gsub(tostring(v), "[\r\n,]", " ")) +end + +function Ass.encode(subs: Types.Subtitles, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(subs) ~= "table" or type(subs.cues) ~= "table" then + return nil, Err.new(Err.ARG, "needs a Subtitles value") + end + local meta: any = if type(subs.meta) == "table" then subs.meta else {} + local out = { "[Script Info]" } + local info: any = if type(meta.scriptInfo) == "table" then meta.scriptInfo else {} + local order = if type(meta.scriptInfoOrder) == "table" then meta.scriptInfoOrder else {} + local written: { [string]: boolean } = {} + if info.ScriptType == nil then + table.insert(out, "ScriptType: v4.00+") + end + for _, k in order do + if type(k) == "string" and (string.sub(k, 1, 1) == ";" or string.sub(k, 1, 1) == "!") then + table.insert(out, k) + elseif info[k] ~= nil and not written[k] then + table.insert(out, k .. ": " .. tostring(info[k])) + written[k] = true + end + end + local rest = {} + for k, v in info do + if not written[k] and type(k) == "string" then + table.insert(rest, k .. ": " .. string.gsub(tostring(v), "[\r\n]", " ")) + end + end + table.sort(rest) + table.move(rest, 1, #rest, #out + 1, out) + local ssa = type(info.ScriptType) == "string" and string.lower(info.ScriptType) == "v4.00" + local sfmt: { string } = if type(meta.styleFormat) == "table" then meta.styleFormat else STYLE_FORMAT + table.insert(out, "") + table.insert(out, "[" .. (if type(meta.stylesSection) == "string" then meta.stylesSection elseif ssa then "V4 Styles" else "V4+ Styles") .. "]") + table.insert(out, "Format: " .. table.concat(sfmt, ", ")) + local names: { string } = {} + local seen: { [string]: boolean } = {} + if type(meta.styleOrder) == "table" then + for _, nm in meta.styleOrder do + if type(nm) == "string" and type(subs.styles) == "table" and subs.styles[nm] ~= nil and not seen[nm] then + table.insert(names, nm) + seen[nm] = true + end + end + end + local extra = {} + if type(subs.styles) == "table" then + for nm, st in subs.styles do + if type(nm) == "string" and type(st) == "table" and not seen[nm] then + table.insert(extra, nm) + end + end + end + table.sort(extra) + table.move(extra, 1, #extra, #names + 1, names) + if #names == 0 then + names = { "Default" } + end + for _, nm in names do + local st = if type(subs.styles) == "table" and type(subs.styles[nm]) == "table" then subs.styles[nm] else {} + local vals = {} + for fi, f in sfmt do + local v = if f == "Name" then nm else st[f] + vals[fi] = field(if v ~= nil then v else (STYLE_DEFAULT[f] or "0")) + end + table.insert(out, "Style: " .. table.concat(vals, ",")) + end + local efmt: { string } = if type(meta.eventFormat) == "table" then meta.eventFormat else EVENT_FORMAT + if efmt[#efmt] ~= "Text" then + return nil, Err.new(Err.ARG, "meta.eventFormat must end with Text") + end + table.insert(out, "") + table.insert(out, "[Events]") + table.insert(out, "Format: " .. table.concat(efmt, ", ")) + local function event(kind: string, c: any, i: number): Err.Err? + if type(c) ~= "table" or type(c.start) ~= "number" or type(c.stop) ~= "number" or type(c.text) ~= "string" or c.start < 0 or c.stop < 0 then + return Err.new(Err.ARG, "cue " .. i .. ": needs start / stop >= 0 (seconds) and a text string") + end + local vals = {} + for fi, f in efmt do + local v: any + if f == "Start" then + v = stamp(c.start) + elseif f == "End" then + v = stamp(c.stop) + elseif f == "Style" then + v = field(c.style or names[1]) + elseif f == "Text" then + if type(c.raw) == "string" and Ass.toMarkup(c.raw) == c.text then + v = string.gsub(c.raw, "[\r\n]", " ") + else + v = Ass.fromMarkup(c.text) + end + elseif f == "Layer" then + v = tostring(tonumber(c.layer) or 0) + elseif f == "Marked" then + v = field(c.marked or "Marked=0") + else + local key = EVENT_KEY[f] or f + local x = c[key] + v = field(if x ~= nil then x elseif string.sub(f, 1, 6) == "Margin" then "0" else "") + end + vals[fi] = v + end + table.insert(out, kind .. ": " .. table.concat(vals, ",")) + return nil + end + local comments = if type(meta.comments) == "table" then meta.comments else {} + local function commentsAfter(n: number?): Err.Err? + for i, c in comments do + if (type(c) == "table" and c.after == n) or (n == nil and (type(c) ~= "table" or type(c.after) ~= "number" or c.after > #subs.cues)) then + local e = event("Comment", c, i) + if e then + return e + end + end + end + return nil + end + for i = 0, #subs.cues do + local e = (if i > 0 then event("Dialogue", subs.cues[i], i) else nil) or commentsAfter(i) + if e then + return nil, e + end + end + local e = commentsAfter(nil) + if e then + return nil, e + end + if type(meta.sections) == "table" then + for _, sec in meta.sections do + if type(sec) == "table" and type(sec.name) == "string" and type(sec.lines) == "table" then + table.insert(out, "") + table.insert(out, "[" .. sec.name .. "]") + for _, l in sec.lines do + table.insert(out, tostring(l)) + end + end + end + end + table.insert(out, "") + local nl = if opts and opts.crlf then "\r\n" else "\n" + return buffer.fromstring(table.concat(out, nl)), nil +end + +return Ass +end +__FILES["subtitle/srt"] = function() + +-- subtitle/srt: SubRip text (de-facto; matches ffmpeg's srt demuxer / muxer). Supports: numbered or unnumbered +-- cues, `,` / `.` decimals, X1/Y1 coordinates (cue.settings), inner blank lines, BOM, CRLF / CR; text kept as is. +-- Not supported: positioning beyond keeping the coordinates; tags are not validated. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Sniff = __include("core/Sniff") +local Bytes = __include("core/Bytes") +local Types = __include("Types") + +-- ------------------------------------------------------------------------------------------------ contract +local Srt = { + name = "srt", + category = "subtitle", + extensions = { "srt" }, + mime = { "application/x-subrip", "text/srt" }, + deps = { "core/Err", "core/Bytes", "Types", "core/Sniff" }, + caps = { decode = true, encode = true, styles = false }, +} + +type DecodeOptions = { + maxBytes: number?, -- default 64 MB +} +type EncodeOptions = { + crlf: boolean?, -- default false (LF) +} + +-- ------------------------------------------------------------------------------------------------ constants +local TIMING = "^%s*(%d+):(%d%d?):(%d%d?)[,.](%d+)%s*%-%->%s*(%d+):(%d%d?):(%d%d?)[,.](%d+)%s*(.-)%s*$" + +local function text(r: Bytes.Reader): string? + local s = buffer.readstring(r.buf, r.base, r.limit - r.base) + if string.find(s, "\0", 1, true) then + return nil + end + s = Sniff.dropBom(s) + s = string.gsub(s, "\r\n", "\n") + s = string.gsub(s, "\r", "\n") + return s +end + +local function frac(digits: string): number + return (tonumber(digits) :: number) / 10 ^ #digits +end + +local function timing(line: string): (number?, number?, string?) + local h1, m1, s1, f1, h2, m2, s2, f2, rest = string.match(line, TIMING) + if not h1 then + return nil, nil, nil + end + local a = tonumber(h1) :: number * 3600 + tonumber(m1) :: number * 60 + tonumber(s1) :: number + frac(f1 :: string) + local b = tonumber(h2) :: number * 3600 + tonumber(m2) :: number * 60 + tonumber(s2) :: number + frac(f2 :: string) + return a, b, rest +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Srt.sniff(r: Bytes.Reader): number + 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 + return 0.9 + end + if first and timing(first) then + return 0.6 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Srt.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Subtitles?, Err.Err?) + local maxBytes = opts and opts.maxBytes or 2 ^ 26 + if r.limit - r.base > maxBytes then + return nil, Err.new(Err.LIMIT, "file is over the " .. maxBytes .. " byte limit") + end + local s = text(r) + if not s then + return nil, Err.new(Err.CORRUPT, "binary data (NUL bytes) in a text format") + end + local lines = string.split(s, "\n") + local n = #lines + local subs = Types.Subtitles.new() + local i = 1 + local function isStart(k: number): boolean + local l = lines[k] + if l == nil then + return false + end + if timing(l) then + return true + end + return string.match(l, "^%s*%d+%s*$") ~= nil and lines[k + 1] ~= nil and timing(lines[k + 1]) ~= nil + end + while i <= n do + local line = lines[i] + local a, b, settings = timing(line) + if a then + local id: string? = nil + if i > 1 then + local prev = string.match(lines[i - 1], "^%s*(%d+)%s*$") + id = prev + end + i += 1 + local body = {} + while i <= n do + local l = lines[i] + if string.match(l, "^%s*$") then + -- a blank line ends the cue only before the next index / timing line + local k = i + while k <= n and string.match(lines[k], "^%s*$") do + k += 1 + end + if k > n or isStart(k) then + break + end + for _ = i, k - 1 do + table.insert(body, "") + end + i = k + elseif timing(l) then + break + else + table.insert(body, l) + i += 1 + end + end + -- an index line right before the next timing belongs to the next cue + if #body > 0 and i <= n and timing(lines[i]) and string.match(body[#body], "^%s*%d+%s*$") then + table.remove(body) + end + local cue: Types.Cue = { start = a, stop = b :: number, text = table.concat(body, "\n"), id = id } + if settings and settings ~= "" then + cue.settings = settings + end + table.insert(subs.cues, cue) + else + i += 1 + end + end + if #subs.cues == 0 and string.find(s, "%S") then + return nil, Err.new(Err.CORRUPT, "no cues (no `-->` timing line)") + end + subs.meta.source = { format = "srt" } + return subs, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function stamp(t: number): string + local ms = math.floor(t * 1000 + 0.5) + return string.format("%02d:%02d:%02d,%03d", ms // 3600000, ms // 60000 % 60, ms // 1000 % 60, ms % 1000) +end + +function Srt.encode(subs: Types.Subtitles, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(subs) ~= "table" or type(subs.cues) ~= "table" then + return nil, Err.new(Err.ARG, "needs a Subtitles value") + end + local nl = if opts and opts.crlf then "\r\n" else "\n" + local out = table.create(#subs.cues) + for i, c in subs.cues do + if type(c) ~= "table" or type(c.start) ~= "number" or type(c.stop) ~= "number" or type(c.text) ~= "string" or c.start < 0 or c.stop < 0 then + return nil, Err.new(Err.ARG, "cue " .. i .. ": needs start / stop >= 0 (seconds) and a text string") + end + local body = string.gsub(c.text, "\r\n?", "\n") + local settings = if type(c.settings) == "string" and c.settings ~= "" and string.match(c.settings, "X1:") then " " .. c.settings else "" + out[i] = i .. nl .. stamp(c.start) .. " --> " .. stamp(c.stop) .. settings .. nl .. (string.gsub(body, "\n", nl)) .. nl + end + return buffer.fromstring(table.concat(out, nl) .. nl), nil +end + +return Srt +end +__FILES["subtitle/vtt"] = function() + +-- subtitle/vtt: WebVTT (W3C WebVTT, 2019 CR). Supports: the header (meta.header), cue ids, `[hh:]mm:ss.ttt` timings, +-- cue settings, NOTE (meta.notes), STYLE (meta.css) and REGION (meta.regions) blocks, BOM, CRLF / CR; cue text as +-- written. Encode drops blank lines in cue text and escapes `-->` (cue text cannot hold them). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Sniff = __include("core/Sniff") +local Bytes = __include("core/Bytes") +local Types = __include("Types") + +-- ------------------------------------------------------------------------------------------------ contract +local Vtt = { + name = "vtt", + category = "subtitle", + extensions = { "vtt", "webvtt" }, + mime = { "text/vtt" }, + deps = { "core/Err", "core/Bytes", "Types", "core/Sniff" }, + caps = { decode = true, encode = true, styles = true }, +} + +type DecodeOptions = { + maxBytes: number?, -- default 64 MB +} +type EncodeOptions = {} + +-- ------------------------------------------------------------------------------------------------ constants +local function frac(digits: string): number + return (tonumber(digits) :: number) / 10 ^ #digits +end + +local function timestamp(s: string): (number?, string) + local h, m, sec, f, rest = string.match(s, "^(%d+):(%d%d):(%d%d)%.(%d+)(.*)$") + if h then + return tonumber(h) :: number * 3600 + tonumber(m) :: number * 60 + tonumber(sec) :: number + frac(f :: string), rest :: string + end + local m2, s2, f2, rest2 = string.match(s, "^(%d+):(%d%d)%.(%d+)(.*)$") + if m2 then + return tonumber(m2) :: number * 60 + tonumber(s2) :: number + frac(f2 :: string), rest2 :: string + end + return nil, s +end + +local function timing(line: string): (number?, number?, string?) + local a, rest = timestamp((string.gsub(line, "^%s+", ""))) + if not a then + return nil, nil, nil + end + local after = string.match(rest, "^%s*%-%->%s*(.*)$") + if not after then + return nil, nil, nil + end + local b, rest2 = timestamp(after) + if not b then + return nil, nil, nil + end + local settings = string.match(rest2, "^%s*(.-)%s*$") or "" + return a, b, settings +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Vtt.sniff(r: Bytes.Reader): number + 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 + return 1 + end + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Vtt.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Subtitles?, Err.Err?) + local maxBytes = opts and opts.maxBytes or 2 ^ 26 + if r.limit - r.base > maxBytes then + return nil, Err.new(Err.LIMIT, "file is over the " .. maxBytes .. " byte limit") + end + if Vtt.sniff(r) == 0 then + return nil, Err.new(Err.CORRUPT, "missing the WEBVTT signature", r.base) + end + local s = buffer.readstring(r.buf, r.base, r.limit - r.base) + if string.find(s, "\0", 1, true) then + return nil, Err.new(Err.CORRUPT, "binary data (NUL bytes) in a text format") + end + s = Sniff.dropBom(s) + s = string.gsub(s, "\r\n", "\n") + s = string.gsub(s, "\r", "\n") + local lines = string.split(s, "\n") + local n = #lines + local subs = Types.Subtitles.new() + -- the header block: WEBVTT[ text] + lines up to the first blank + local header = { (string.match(lines[1], "^WEBVTT[ \t]*(.*)$")) or "" } + local i = 2 + while i <= n and lines[i] ~= "" do + table.insert(header, lines[i]) + i += 1 + end + if #header > 1 or header[1] ~= "" then + subs.meta.header = table.concat(header, "\n") + end + local notes, css, regions = {}, {}, {} + while i <= n do + if lines[i] == "" then + i += 1 + continue + end + local first = i + while i <= n and lines[i] ~= "" do + i += 1 + end + local block = table.move(lines, first, i - 1, 1, {}) + local head = block[1] + if string.match(head, "^NOTE[ \t]") or head == "NOTE" then + table.insert(notes, (string.gsub(table.concat(block, "\n"), "^NOTE[ \t]?", ""))) + elseif (head == "STYLE" or string.match(head, "^STYLE[ \t]")) and not string.find(table.concat(block, "\n"), "-->", 1, true) then + table.insert(css, table.concat(block, "\n", 2)) + elseif (head == "REGION" or string.match(head, "^REGION[ \t]")) and not string.find(table.concat(block, "\n"), "-->", 1, true) then + table.insert(regions, table.concat(block, "\n", 2)) + else + local k, id = 1, nil + local a, b, settings = timing(block[1]) + if not a and block[2] then + id = block[1] + k = 2 + a, b, settings = timing(block[2]) + end + if a then + local cue: Types.Cue = { start = a, stop = b :: number, text = table.concat(block, "\n", k + 1), id = id } + if settings and settings ~= "" then + cue.settings = settings + end + table.insert(subs.cues, cue) + end + -- a block with no timing is skipped (the spec's parser ignores it) + end + end + if #notes > 0 then + subs.meta.notes = notes + end + if #css > 0 then + subs.meta.css = css + end + if #regions > 0 then + subs.meta.regions = regions + end + subs.meta.source = { format = "vtt" } + return subs, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function stamp(t: number): string + local ms = math.floor(t * 1000 + 0.5) + return string.format("%02d:%02d:%02d.%03d", ms // 3600000, ms // 60000 % 60, ms // 1000 % 60, ms % 1000) +end + +local function clean(s: string): string + s = string.gsub(s, "\r\n?", "\n") + s = string.gsub(s, "\n[ \t]*\n", "\n") + s = string.gsub(s, "\n[ \t]*\n", "\n") + s = string.gsub(s, "^\n+", "") + s = string.gsub(s, "%-%->", "--&gt;") + return s +end + +function Vtt.encode(subs: Types.Subtitles, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(subs) ~= "table" or type(subs.cues) ~= "table" then + return nil, Err.new(Err.ARG, "needs a Subtitles value") + end + local meta: any = if type(subs.meta) == "table" then subs.meta else {} + local out = {} + local header = if type(meta.header) == "string" and meta.header ~= "" then meta.header else nil + if header then + local h = string.gsub(clean(header), "%-%-&gt;", "") + table.insert(out, "WEBVTT " .. h .. "\n") + else + table.insert(out, "WEBVTT\n") + end + for _, key in { "regions", "css" } do + local list = meta[key] + if type(list) == "table" then + for _, b in list do + if type(b) == "string" then + table.insert(out, (if key == "css" then "STYLE\n" else "REGION\n") .. clean(b) .. "\n") + end + end + end + end + for i, c in subs.cues do + if type(c) ~= "table" or type(c.start) ~= "number" or type(c.stop) ~= "number" or type(c.text) ~= "string" or c.start < 0 or c.stop < 0 then + return nil, Err.new(Err.ARG, "cue " .. i .. ": needs start / stop >= 0 (seconds) and a text string") + end + local id = if type(c.id) == "string" and c.id ~= "" and not string.find(c.id, "-->", 1, true) then (string.gsub(c.id, "[\r\n]", " ")) .. "\n" else "" + local settings = if type(c.settings) == "string" and c.settings ~= "" then " " .. (string.gsub(c.settings, "[\r\n]", " ")) else "" + local body = clean(c.text) + table.insert(out, id .. stamp(c.start) .. " --> " .. stamp(c.stop) .. settings .. "\n" .. body .. (if body ~= "" then "\n" else "")) + end + return buffer.fromstring(table.concat(out, "\n")), nil +end + +return Vtt +end +end + + + + + + vector + --!optimize 2 +--!nocheck +-- rosetta chunk vector (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 10 modules (0 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["vector/svg"] = function() + +-- vector/svg: SVG 1.1 / 2 static documents (W3C SVG 1.1 2nd ed., SVG 2 CR). Supports: shapes and paths, transforms, +-- nested svg / use / symbol, a CSS subset, gradients, clip-path, group opacity, strokes, dashes, units. Not supported +-- (meta.unsupported): text, image, pattern, mask, marker, filter, foreignObject, switch conditions, CSS combinators. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Sniff = __include("core/Sniff") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Xml = __include("codecs/text/Xml") +local Parse = __include("vector/svg/Parse") +local Render = __include("vector/svg/Render") +local Write = __include("vector/svg/Write") + +-- ------------------------------------------------------------------------------------------------ contract +local Svg = { + name = "svg", + category = "vector", + extensions = { "svg" }, + mime = { "image/svg+xml" }, + 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 }, +} + +type DecodeOptions = { + maxBytes: number?, -- default 64 MB +} +type EncodeOptions = {} +type RasterizeOptions = Render.Options + +-- ------------------------------------------------------------------------------------------------ sniff +function Svg.sniff(r: Bytes.Reader): number + local h = Sniff.text(r, 4096) + if not string.match(h, "^%s*<") then + return 0 + end + if string.find(h, "<svg[%s>:]") or string.find(h, "<%w+:svg[%s>]") then + return 0.95 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Svg.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Vector?, Err.Err?) + local maxBytes = opts and opts.maxBytes or 2 ^ 26 + if r.limit - r.base > maxBytes then + return nil, Err.new(Err.LIMIT, "file is over the byte limit") + end + local doc, xerr = Xml.decode(buffer.readstring(r.buf, r.base, r.limit - r.base)) + if not doc then + return nil, xerr + end + local v, msg = Parse.document(doc) + if not v then + return nil, Err.new(Err.CORRUPT, msg or "bad SVG") + end + v.meta.source = { format = "svg" } + return v, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Svg.encode(v: Types.Vector, opts: EncodeOptions?): (buffer?, Err.Err?) + local s, err = Write.vector(v) + if not s then + return nil, Err.new(Err.ARG, err or "bad Vector") + end + return buffer.fromstring(s), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +function Svg.rasterize(v: Types.Vector, w: number?, h: number?, opts: RasterizeOptions?): (Types.Image?, Err.Err?) + if type(v) ~= "table" or type(v.paths) ~= "table" then + return nil, Err.new(Err.ARG, "needs a Vector value") + end + local W = math.ceil(w or v.width or 0) + local H = math.ceil(h or v.height or 0) + if W < 1 or H < 1 or W * H > 2 ^ 26 then + return nil, Err.new(Err.ARG, "bad raster size") + end + return Render.rasterize(v, W, H, opts), nil +end + +return Svg +end +__FILES["vector/svg/Parse"] = function() + +-- vector/svg/Parse: an SVG document (an Xml tree) to a Types.Vector: the cascade, shapes, paints, groups, clips. +local Xml = __include("codecs/text/Xml") +local Types = __include("Types") +local Style = __include("vector/svg/Style") +local PathData = __include("vector/svg/PathData") + +local Parse = {} + +type Node = Types.XmlNode +type M = { number } + +local IDENTITY = { 1, 0, 0, 1, 0, 0 } +local mul = Style.multiply + +-- properties that inherit, and their initial values +local INHERITED: { [string]: string } = { + fill = "black", + ["fill-opacity"] = "1", + ["fill-rule"] = "nonzero", + stroke = "none", + ["stroke-width"] = "1", + ["stroke-opacity"] = "1", + ["stroke-linecap"] = "butt", + ["stroke-linejoin"] = "miter", + ["stroke-miterlimit"] = "4", + ["stroke-dasharray"] = "none", + ["stroke-dashoffset"] = "0", + ["clip-rule"] = "nonzero", + visibility = "visible", + color = "black", + ["font-size"] = "16", +} +-- not inherited (reset per element) +local LOCAL: { [string]: boolean } = { + opacity = true, + ["clip-path"] = true, + display = true, + ["stop-color"] = true, + ["stop-opacity"] = true, + mask = true, + filter = 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 } + +type Ctx = { + ids: { [string]: Node }, + rules: { Style.Rule }, + vector: Types.Vector, + groups: { any }, + clips: { any }, + unsupported: { [string]: number }, + vw: number, + vh: number, + depth: number, + useDepth: number, +} + +local function local_(n: Node): string + return Xml.localName(n.name) +end +local function attr(n: Node, k: string): string? + local a = n.attrs :: any + return a[k] +end +local function href(n: Node): string? + local h = attr(n, "href") or attr(n, "xlink:href") + if h == nil then + for k, v in pairs(n.attrs :: any) do + if type(k) == "string" and Xml.localName(k) == "href" then + return v + end + end + end + return h +end +local function refId(s: string?): string? + if s == nil then + return nil + end + return string.match(s, "^%s*#(.-)%s*$") or string.match(s, "^%s*url%(%s*['\"]?#(.-)['\"]?%s*%)") +end + +-- cascade: presentation attributes < CSS rules (by specificity, then order) < style="" +local function specified(n: Node, ctx: Ctx): { [string]: string } + local out: { [string]: string } = {} + for k, v in pairs(n.attrs :: any) do + if type(k) == "string" and type(v) == "string" and (INHERITED[k] or LOCAL[k]) then + out[k] = v + end + end + if #ctx.rules > 0 then + local classes: { [string]: boolean } = {} + for c in string.gmatch(attr(n, "class") or "", "%S+") do + classes[c] = true + end + 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) + end + end + table.sort(hits, function(a: any, b: any): boolean + if a.selector.specificity ~= b.selector.specificity then + return a.selector.specificity < b.selector.specificity + end + return a.order < b.order + end) + for _, r in hits do + for k, v in pairs(r.decls) do + out[k] = v + end + end + end + local st = attr(n, "style") + if st then + for k, v in pairs(Style.declarations(st)) do + out[k] = v + end + end + return out +end + +local function computed(parent: { [string]: string }, n: Node, ctx: Ctx): { [string]: string } + local out: { [string]: string } = {} + for k in pairs(INHERITED) do + out[k] = parent[k] + end + for k, v in pairs(specified(n, ctx)) do + if v == "inherit" then + out[k] = parent[k] + elseif INHERITED[k] or LOCAL[k] then + out[k] = v + end + end + return out +end + +local function len(s: string?, ref: number, st: { [string]: string }, default: number?): number? + local fs = Style.length(st["font-size"], 16) or 16 + local v = Style.length(s, ref, fs) + if v == nil then + return default + end + return v +end + +-- ------------------------------------------------------------------------------------------------ paints +local function stops(g: Node, ctx: Ctx, seen: { [Node]: boolean }): { { number } } + local list = {} + local parentStyle = computed(INHERITED, g, ctx) + for _, s in Xml.children(g) do + if local_(s) == "stop" then + local st = computed(parentStyle, s, ctx) + local off = attr(s, "offset") or "0" + local o = tonumber(string.match(off, "^%s*([%d.eE+-]+)%s*%%%s*$") or "") + local offset = if o then o / 100 else (tonumber(off) or 0) + offset = math.clamp(offset, 0, 1) + if #list > 0 and offset < list[#list][1] then + offset = list[#list][1] + end + local col = Style.color(st["stop-color"] or "black", Style.color(st.color or "black")) or { 0, 0, 0, 255 } + if col == "none" then + col = { 0, 0, 0, 0 } + end + local op = math.clamp(tonumber(st["stop-opacity"] or "1") or 1, 0, 1) + table.insert(list, { offset, col[1], col[2], col[3], math.floor(col[4] * op + 0.5) }) + end + end + if #list == 0 then + local h = refId(href(g)) + local other = if h then ctx.ids[h] else nil + if other and not seen[other] then + seen[other] = true + return stops(other, ctx, seen) + end + end + return list +end + +local function gattr(g: Node, k: string, ctx: Ctx): string? + local cur: Node? = g + local guard = 0 + while cur and guard < 16 do + local v = attr(cur, k) + if v ~= nil then + return v + end + local h = refId(href(cur)) + cur = if h then ctx.ids[h] else nil + guard += 1 + end + return nil +end + +local function gradient(g: Node, opacity: number, ctx: Ctx): any + local kind = local_(g) + local units = gattr(g, "gradientUnits", ctx) or "objectBoundingBox" + local obb = units ~= "userSpaceOnUse" + local list = stops(g, ctx, { [g] = true }) + if #list == 0 then + return "none" + end + if #list == 1 then + local s = list[1] + return { type = "color", color = { s[2], s[3], s[4], math.floor(s[5] * opacity + 0.5) } } + end + local function coord(k: string, default: string, ref: number): number + local v = gattr(g, k, ctx) or default + local pct = string.match(v, "^%s*([%d.eE+-]+)%s*%%%s*$") + if pct then + local x = tonumber(pct) or 0 + return if obb then x / 100 else x / 100 * ref + end + return Style.length(v, ref) or 0 + end + local diag = math.sqrt((ctx.vw * ctx.vw + ctx.vh * ctx.vh) / 2) + local p: any = { + type = if kind == "linearGradient" then "linear" else "radial", + units = if obb then "objectBoundingBox" else "userSpaceOnUse", + spread = gattr(g, "spreadMethod", ctx) or "pad", + stops = list, + opacity = opacity, + } + local t = gattr(g, "gradientTransform", ctx) + if t then + p.transform = Style.transform(t) + end + if p.type == "linear" then + p.x1, p.y1 = coord("x1", "0%", ctx.vw), coord("y1", "0%", ctx.vh) + p.x2, p.y2 = coord("x2", "100%", ctx.vw), coord("y2", "0%", ctx.vh) + else + p.cx, p.cy = coord("cx", "50%", ctx.vw), coord("cy", "50%", ctx.vh) + p.r = coord("r", "50%", diag) + p.fx = if gattr(g, "fx", ctx) then coord("fx", "50%", ctx.vw) else p.cx + p.fy = if gattr(g, "fy", ctx) then coord("fy", "50%", ctx.vh) else p.cy + p.fr = coord("fr", "0%", diag) + end + return p +end + +local function paint(value: string?, opacity: number, st: { [string]: string }, ctx: Ctx): any + if value == nil then + return nil + end + local id = string.match(value, "^%s*url%(%s*['\"]?#(.-)['\"]?%s*%)%s*(.*)$") + if id then + local fallback = string.match(value, "%)%s*(.-)%s*$") + local g = ctx.ids[id] + if g and (local_(g) == "linearGradient" or local_(g) == "radialGradient") then + local p = gradient(g, opacity, ctx) + return if p == "none" then nil else p + end + if g and local_(g) == "pattern" then + ctx.unsupported.pattern = (ctx.unsupported.pattern or 0) + 1 + end + if fallback and fallback ~= "" then + return paint(fallback, opacity, st, ctx) + end + return nil + end + local c = Style.color(value, Style.color(st.color or "black") :: any) + if c == nil or c == "none" then + return nil + end + return { type = "color", color = { c[1], c[2], c[3], math.floor(c[4] * opacity + 0.5) } } +end + +-- ------------------------------------------------------------------------------------------------ shapes +local function shape(n: Node, st: { [string]: string }, ctx: Ctx): { PathData.Cmd }? + local kind = local_(n) + local vw, vh = ctx.vw, ctx.vh + local diag = math.sqrt((vw * vw + vh * vh) / 2) + if kind == "path" then + local d = attr(n, "d") + if d == nil then + return nil + end + local cmds = PathData.parse(d) + return cmds + elseif kind == "rect" then + local x, y = len(attr(n, "x"), vw, st, 0) :: number, len(attr(n, "y"), vh, st, 0) :: number + local w, h = len(attr(n, "width"), vw, st, 0) :: number, len(attr(n, "height"), vh, st, 0) :: number + if w <= 0 or h <= 0 then + return nil + end + 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 + if ry and ry < 0 then + ry = nil + end + rx = rx or ry or 0 + ry = ry or rx + 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" } } :: { 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) + table.insert(out, { op = "L", x + w, y + h - ry }) + PathData.arc(x + w, y + h - ry, rx, ry, 0, false, true, x + w - rx, y + h, out) + table.insert(out, { op = "L", x + rx, y + h }) + 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" } :: 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 + local rx, ry + if kind == "circle" then + rx = len(attr(n, "r"), diag, st, 0) :: number + ry = rx + else + rx, ry = len(attr(n, "rx"), vw, st), len(attr(n, "ry"), vh, st) + rx = rx or ry or 0 + ry = ry or rx + end + if (rx :: number) <= 0 or (ry :: number) <= 0 then + return nil + end + local out: { PathData.Cmd } = { { op = "M", cx + rx, cy } } + 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) + 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" } :: 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 } } :: { PathData.Cmd } + elseif kind == "polyline" or kind == "polygon" then + local v = Style.numbers(attr(n, "points")) + if #v < 4 then + return nil + end + local out: { PathData.Cmd } = { { op = "M", v[1], v[2] } } + for i = 3, #v - 1, 2 do + table.insert(out, { op = "L", v[i], v[i + 1] }) + end + if kind == "polygon" then + table.insert(out, { op = "Z" } :: PathData.Cmd) + end + return out + end + return nil +end + +-- ------------------------------------------------------------------------------------------------ clip paths +local function transformOf(n: Node): M + local t = attr(n, "transform") + if t then + return Style.transform(t) or IDENTITY + end + return IDENTITY +end + +local function clip(ref: string, ctm: M, bbox: { number }?, st: { [string]: string }, ctx: Ctx): number? + local cp = ctx.ids[ref] + if cp == nil or local_(cp) ~= "clipPath" then + return nil + end + local base = mul(ctm, transformOf(cp)) + if attr(cp, "clipPathUnits") == "objectBoundingBox" then + if not bbox then + return nil + end + base = mul(base, { bbox[3] - bbox[1], 0, 0, bbox[4] - bbox[2], bbox[1], bbox[2] }) + end + local cpStyle = computed(st, cp, ctx) + local paths = {} + local function add(n: Node, parentStyle: { [string]: string }, m: M, depth: number) + if depth > 8 then + return + end + local s = computed(parentStyle, n, ctx) + if s.display == "none" or s.visibility == "hidden" then + return + end + local k = local_(n) + local tm = mul(m, transformOf(n)) + if SHAPES[k] then + local cmds = shape(n, s, ctx) + if cmds and #cmds > 0 then + table.insert(paths, { d = cmds, transform = tm, rule = s["clip-rule"] or "nonzero" }) + end + elseif k == "use" then + local h = refId(href(n)) + local target = if h then ctx.ids[h] else nil + if target then + local x, y = len(attr(n, "x"), ctx.vw, s, 0) :: number, len(attr(n, "y"), ctx.vh, s, 0) :: number + add(target, s, mul(tm, { 1, 0, 0, 1, x, y }), depth + 1) + end + end + end + for _, c in Xml.children(cp) do + add(c, cpStyle, base, 0) + end + table.insert(ctx.clips, { paths = paths }) + return #ctx.clips +end + +-- ------------------------------------------------------------------------------------------------ the walk +local walk: (n: Node, parentStyle: { [string]: string }, ctm: M, group: number?, ctx: Ctx) -> () + +local function bboxOf(cmds: { PathData.Cmd }): { number }? + local x0, y0, x1, y1 = PathData.bounds(cmds) + if not x0 then + return nil + end + return { x0 :: number, y0 :: number, x1 :: number, y1 :: number } +end + +local function emitShape(n: Node, st: { [string]: string }, ctm: M, group: number?, ctx: Ctx) + if st.visibility == "hidden" or st.visibility == "collapse" then + return + end + local cmds = shape(n, st, ctx) + if not cmds or #cmds == 0 then + return + end + local tm = mul(ctm, transformOf(n)) + local opacity = math.clamp(tonumber(st.opacity or "1") or 1, 0, 1) + local fill = paint(st.fill, math.clamp(tonumber(st["fill-opacity"]) or 1, 0, 1), st, ctx) + local stroke = paint(st.stroke, math.clamp(tonumber(st["stroke-opacity"]) or 1, 0, 1), st, ctx) + local diag = math.sqrt((ctx.vw * ctx.vw + ctx.vh * ctx.vh) / 2) + local sw = len(st["stroke-width"], diag, st, 1) :: number + if sw <= 0 then + stroke = nil + end + if fill == nil and stroke == nil then + return + end + if local_(n) == "line" then + fill = nil -- a line has no inside + end + local clipRef = refId(st["clip-path"]) + local clipId: number? = nil + if clipRef then + clipId = clip(clipRef, tm, bboxOf(cmds), st, ctx) + if clipId == nil and ctx.ids[clipRef] then + return -- a broken clip reference (bad units): nothing shows + end + end + -- opacity on a shape with both a fill and a stroke: a group, so the overlap is not counted twice + local g = group + if opacity < 1 and fill and stroke then + table.insert(ctx.groups, { opacity = opacity, parent = group }) + g = #ctx.groups + opacity = 1 + end + local p: any = { + d = cmds, + fill = fill, + fillRule = if st["fill-rule"] == "evenodd" then "evenodd" else "nonzero", + stroke = stroke, + strokeWidth = sw, + transform = tm, + opacity = opacity, + group = g, + clip = clipId, + id = attr(n, "id"), + } + if stroke then + p.strokeLineJoin = st["stroke-linejoin"] + p.strokeLineCap = st["stroke-linecap"] + p.strokeMiterLimit = tonumber(st["stroke-miterlimit"]) or 4 + local dash = st["stroke-dasharray"] + if dash and dash ~= "none" then + local list = {} + local ok = true + for part in string.gmatch(dash, "[^,%s]+") do + local v = len(part, diag, st) + if v == nil or v < 0 then + ok = false + end + table.insert(list, v or 0) + end + local sum = 0 + for _, v in list do + sum += v + end + if ok and sum > 0 then + if #list % 2 == 1 then + table.move(list, 1, #list, #list + 1, list) + end + p.strokeDashArray = list + p.strokeDashOffset = len(st["stroke-dashoffset"], diag, st, 0) + end + end + end + table.insert(ctx.vector.paths, p) +end + +function Parse.viewTransform(vb: { number }?, par: string?, x: number, y: number, w: number, h: number): M + if vb == nil or vb[3] <= 0 or vb[4] <= 0 then + return { 1, 0, 0, 1, x, y } + end + local sx, sy = w / vb[3], h / vb[4] + local align, mode = "xmidymid", "meet" + if par then + local a, m = string.match(string.lower(par), "^%s*([%w]+)%s*(%a*)") + if a == "defer" then + a, m = string.match(string.lower(par), "^%s*defer%s+([%w]+)%s*(%a*)") + end + align = a or align + if m and m ~= "" then + mode = m + end + end + if align == "none" then + return { sx, 0, 0, sy, x - vb[1] * sx, y - vb[2] * sy } + end + local s = if mode == "slice" then math.max(sx, sy) else math.min(sx, sy) + local tx, ty = x - vb[1] * s, y - vb[2] * s + local ax, ay = string.match(align, "^x(%a%a%a)y(%a%a%a)$") + if ax == "mid" then + tx += (w - vb[3] * s) / 2 + elseif ax == "max" then + tx += w - vb[3] * s + end + if ay == "mid" then + ty += (h - vb[4] * s) / 2 + elseif ay == "max" then + ty += h - vb[4] * s + end + return { s, 0, 0, s, tx, ty } +end + +local function viewBox(n: Node): { number }? + local v = Style.numbers(attr(n, "viewBox")) + if #v == 4 and v[3] > 0 and v[4] > 0 then + return v + end + return nil +end + +local function container(n: Node, st: { [string]: string }, ctm: M, group: number?, ctx: Ctx, children: { Node }?) + local opacity = math.clamp(tonumber(st.opacity or "1") or 1, 0, 1) + local clipRef = refId(st["clip-path"]) + local g = group + if opacity < 1 or clipRef then + local clipId: number? = nil + if clipRef then + local bbox: { number }? = nil + local cp = ctx.ids[clipRef] + if cp and attr(cp, "clipPathUnits") == "objectBoundingBox" then + local saveV, saveG, saveC = ctx.vector, ctx.groups, ctx.clips + local scratch = Types.Vector.new(0, 0) + ctx.vector, ctx.groups, ctx.clips = scratch, {}, {} + for _, c in children or Xml.children(n) do + walk(c, st, IDENTITY, nil, ctx) + end + ctx.vector, ctx.groups, ctx.clips = saveV, saveG, saveC + local x0, y0, x1, y1 = math.huge, math.huge, -math.huge, -math.huge + for _, p in scratch.paths do + local b = bboxOf(p.d) + if b then + local m = p.transform or IDENTITY + for _, corner in { { b[1], b[2] }, { b[3], b[2] }, { b[1], b[4] }, { b[3], b[4] } } do + local px = m[1] * corner[1] + m[3] * corner[2] + m[5] + local py = m[2] * corner[1] + m[4] * corner[2] + m[6] + x0, y0, x1, y1 = math.min(x0, px), math.min(y0, py), math.max(x1, px), math.max(y1, py) + end + end + end + if x0 <= x1 then + bbox = { x0, y0, x1, y1 } + end + end + clipId = clip(clipRef, ctm, bbox, st, ctx) + if clipId == nil and cp then + return + end + end + table.insert(ctx.groups, { opacity = opacity, parent = group, clip = clipId }) + g = #ctx.groups + end + if local_(n) == "switch" then + -- the first child that renders (conditional attributes are not evaluated) + for _, c in children or Xml.children(n) do + if UNSUPPORTED[local_(c)] == nil then + walk(c, st, ctm, g, ctx) + return + end + end + return + end + for _, c in children or Xml.children(n) do + walk(c, st, ctm, g, ctx) + end +end + +-- nested svg / symbol: overflow is hidden unless it says otherwise +local function viewportGroup(n: Node, m: M, x: number, y: number, w: number, h: number, group: number?, ctx: Ctx): number? + local ov = attr(n, "overflow") + if ov == "visible" or ov == "auto" then + return group + end + local rect = { { op = "M", x, y }, { op = "L", x + w, y }, { op = "L", x + w, y + h }, { op = "L", x, y + h }, { op = "Z" } } + table.insert(ctx.clips, { paths = { { d = rect, transform = m, rule = "nonzero" } } }) + table.insert(ctx.groups, { opacity = 1, parent = group, clip = #ctx.clips }) + return #ctx.groups +end + +walk = function(n: Node, parentStyle: { [string]: string }, ctm: M, group: number?, ctx: Ctx) + if ctx.depth > 200 then + return + end + local kind = local_(n) + if kind == "defs" or kind == "clipPath" or kind == "linearGradient" or kind == "radialGradient" or kind == "symbol" or kind == "style" or kind == "title" or kind == "desc" or kind == "metadata" then + return + end + local st = computed(parentStyle, n, ctx) + if st.display == "none" then + return + end + if UNSUPPORTED[kind] then + ctx.unsupported[kind] = (ctx.unsupported[kind] or 0) + 1 + return + end + ctx.depth += 1 + if CONTAINERS[kind] then + container(n, st, mul(ctm, transformOf(n)), group, ctx) + elseif SHAPES[kind] then + emitShape(n, st, ctm, group, ctx) + elseif kind == "use" then + local h = refId(href(n)) + local target = if h then ctx.ids[h] else nil + if target and ctx.useDepth < 16 then + ctx.useDepth += 1 + local x, y = len(attr(n, "x"), ctx.vw, st, 0) :: number, len(attr(n, "y"), ctx.vh, st, 0) :: number + local m = mul(mul(ctm, transformOf(n)), { 1, 0, 0, 1, x, y }) + local tk = local_(target) + if tk == "symbol" or tk == "svg" then + local w = len(attr(n, "width") or attr(target, "width") or "100%", ctx.vw, st, ctx.vw) :: number + local h2 = len(attr(n, "height") or attr(target, "height") or "100%", ctx.vh, st, ctx.vh) :: number + local vb = viewBox(target) + local inner = mul(m, Parse.viewTransform(vb, attr(target, "preserveAspectRatio"), 0, 0, w, h2)) + local saveW, saveH = ctx.vw, ctx.vh + if vb then + ctx.vw, ctx.vh = vb[3], vb[4] + end + local tst = computed(st, target, ctx) + -- the use element's own opacity applies to the symbol's content too + local uo = math.clamp(tonumber(st.opacity or "1") or 1, 0, 1) + if uo < 1 then + tst.opacity = tostring(uo * math.clamp(tonumber(tst.opacity or "1") or 1, 0, 1)) + end + if tst["clip-path"] == nil then + tst["clip-path"] = st["clip-path"] + end + -- the symbol's children as a group of the use element, clipped to its viewport + local vg = viewportGroup(target, m, 0, 0, w, h2, group, ctx) + container(n, tst, mul(inner, transformOf(target)), vg, ctx, Xml.children(target)) + ctx.vw, ctx.vh = saveW, saveH + else + -- the referenced element as if it were the use element's only child + container(n, st, m, group, ctx, { target }) + end + ctx.useDepth -= 1 + end + elseif kind == "svg" then + local x, y = len(attr(n, "x"), ctx.vw, st, 0) :: number, len(attr(n, "y"), ctx.vh, st, 0) :: number + local w = len(attr(n, "width") or "100%", ctx.vw, st, ctx.vw) :: number + local h = len(attr(n, "height") or "100%", ctx.vh, st, ctx.vh) :: number + local vb = viewBox(n) + local m = mul(ctm, Parse.viewTransform(vb, attr(n, "preserveAspectRatio"), x, y, w, h)) + local saveW, saveH = ctx.vw, ctx.vh + if vb then + ctx.vw, ctx.vh = vb[3], vb[4] + else + ctx.vw, ctx.vh = w, h + end + container(n, st, m, viewportGroup(n, ctm, x, y, w, h, group, ctx), ctx) + ctx.vw, ctx.vh = saveW, saveH + end + ctx.depth -= 1 +end + +-- ------------------------------------------------------------------------------------------------ entry +function Parse.document(doc: any): (Types.Vector?, string?) + local root = doc.root + if root == nil or Xml.localName(root.name) ~= "svg" then + return nil, "the root element is not <svg>" + end + local ids: { [string]: Node } = {} + local rules: { Style.Rule } = {} + local count = 0 + local function index(n: Node) + count += 1 + if count > 1000000 then + return + end + local id = attr(n, "id") + if id and ids[id] == nil then + ids[id] = n + end + if local_(n) == "style" then + Style.css(Xml.text(n), rules) + end + for _, c in Xml.children(n) do + index(c) + end + end + index(root) + local vb = viewBox(root) + local w = Style.length(attr(root, "width") or "100%", if vb then vb[3] else 100) or 100 + local h = Style.length(attr(root, "height") or "100%", if vb then vb[4] else 100) or 100 + if w <= 0 or h <= 0 then + w, h = 100, 100 + end + local v = Types.Vector.new(w, h) + v.viewBox = vb or { 0, 0, w, h } + local ctx: Ctx = { + ids = ids, + rules = rules, + vector = v, + groups = {}, + clips = {}, + unsupported = {}, + vw = v.viewBox[3], + vh = v.viewBox[4], + depth = 0, + useDepth = 0, + } + local st = computed(INHERITED, root, ctx) + container(root, st, IDENTITY, nil, ctx) + v.meta.preserveAspectRatio = attr(root, "preserveAspectRatio") + v.meta.groups = ctx.groups + v.meta.clips = ctx.clips + if next(ctx.unsupported) then + v.meta.unsupported = ctx.unsupported + end + return v, nil +end + +return Parse +end +__FILES["vector/svg/PathData"] = function() + +-- vector/svg/PathData: SVG path data (SVG 1.1 section 8.3, SVG 2 "Path data"); arcs to cubics per implementation notes +-- F.6 (out-of-range radii scaled up); parsing stops at the first error, keeping the commands so far (as the spec says). +local PathData = {} + +type Cmd = { op: string, [number]: number } + +local byte, sub, find = string.byte, string.sub, string.find +local abs, sqrt, cos, sin, atan2, ceil, pi = math.abs, math.sqrt, math.cos, math.sin, math.atan2, math.ceil, math.pi + +local ARGS = { M = 2, L = 2, H = 1, V = 1, C = 6, S = 4, Q = 4, T = 2, A = 7, Z = 0 } + +local function arc(x1: number, y1: number, rx: number, ry: number, phiDeg: number, fa: boolean, fs: boolean, x2: number, y2: number, out: { Cmd }) + if x1 == x2 and y1 == y2 then + return + end + rx, ry = abs(rx), abs(ry) + if rx == 0 or ry == 0 then + table.insert(out, { op = "L", x2, y2 }) + return + end + local phi = phiDeg % 360 * pi / 180 + local cp, sp = cos(phi), sin(phi) + local dx, dy = (x1 - x2) / 2, (y1 - y2) / 2 + local x1p, y1p = cp * dx + sp * dy, -sp * dx + cp * dy + local lambda = (x1p * x1p) / (rx * rx) + (y1p * y1p) / (ry * ry) + if lambda > 1 then + local s = sqrt(lambda) + rx, ry = rx * s, ry * s + end + local num = rx * rx * ry * ry - rx * rx * y1p * y1p - ry * ry * x1p * x1p + local den = rx * rx * y1p * y1p + ry * ry * x1p * x1p + local coef = if den == 0 then 0 else sqrt(math.max(0, num / den)) + if fa == fs then + coef = -coef + end + local cxp, cyp = coef * rx * y1p / ry, -coef * ry * x1p / rx + local cx, cy = cp * cxp - sp * cyp + (x1 + x2) / 2, sp * cxp + cp * cyp + (y1 + y2) / 2 + local function angle(ux: number, uy: number, vx: number, vy: number): number + return atan2(ux * vy - uy * vx, ux * vx + uy * vy) + end + local ux, uy = (x1p - cxp) / rx, (y1p - cyp) / ry + local vx, vy = (-x1p - cxp) / rx, (-y1p - cyp) / ry + local t1 = angle(1, 0, ux, uy) + local dt = angle(ux, uy, vx, vy) + if not fs and dt > 0 then + dt -= 2 * pi + elseif fs and dt < 0 then + dt += 2 * pi + end + local n = math.max(1, ceil(abs(dt) / (pi / 2) - 1e-9)) + local step = dt / n + local k = 4 / 3 * math.tan(step / 4) + local px, py = x1, y1 + for i = 1, n do + local a0 = t1 + (i - 1) * step + local a1 = t1 + i * step + local c0, s0, c1, s1 = cos(a0), sin(a0), cos(a1), sin(a1) + -- the unit-circle segment's control points, scaled by the radii, rotated by phi, moved to the centre + local e1x, e1y = c0 - k * s0, s0 + k * c0 + local e2x, e2y = c1 + k * s1, s1 - k * c1 + local ex, ey = c1, s1 + local function map(x: number, y: number): (number, number) + x, y = x * rx, y * ry + return cp * x - sp * y + cx, sp * x + cp * y + cy + end + local ax, ay = map(e1x, e1y) + local bx, by = map(e2x, e2y) + local qx, qy = map(ex, ey) + if i == n then + qx, qy = x2, y2 + end + table.insert(out, { op = "C", ax, ay, bx, by, qx, qy }) + px, py = qx, qy + end + local _ = px + py +end +PathData.arc = arc + +function PathData.parse(d: string): ({ Cmd }, boolean) + local out: { Cmd } = {} + local i, n = 1, #d + local cx, cy = 0, 0 + local sx, sy = 0, 0 + local lcx, lcy = 0, 0 + local last = "" + local cmd: string? = nil + local rel = false + local nums: { number } = table.create(7) :: { number } + local function ws() + while i <= n do + local c = byte(d, i) + if c == 32 or c == 9 or c == 10 or c == 13 or c == 12 then + i += 1 + else + break + end + end + end + local function comma() + ws() + if i <= n and byte(d, i) == 44 then + i += 1 + ws() + end + end + local function digits(): boolean + local any = false + while i <= n do + local c = byte(d, i) + if c >= 48 and c <= 57 then + i += 1 + any = true + else + break + end + end + return any + end + -- an SVG number: sign? (digits ("." digits?)? | "." digits) exponent?; "1.5.5" is 1.5 then .5 + local function number(): number? + ws() + local s = i + local c = byte(d, i) + if c == 43 or c == 45 then + i += 1 + end + local whole = digits() + local frac = false + if i <= n and byte(d, i) == 46 then + i += 1 + frac = digits() + end + if not whole and not frac then + i = s + return nil + end + c = byte(d, i) + if c == 101 or c == 69 then + local save = i + i += 1 + c = byte(d, i) + if c == 43 or c == 45 then + i += 1 + end + if not digits() then + i = save + end + end + return tonumber(sub(d, s, i - 1)) + end + local function flag(): number? + ws() + local c = byte(d, i) + if c == 48 or c == 49 then + i += 1 + return c - 48 + end + return nil + end + while true do + ws() + if i > n then + break + end + local c = sub(d, i, i) + local up = string.upper(c) + if ARGS[up] ~= nil and find(c, "%a") then + cmd = up + rel = c ~= up + i += 1 + if up == "Z" then + table.insert(out, { op = "Z" } :: Cmd) + cx, cy = sx, sy + last = "Z" + cmd = nil + continue + end + elseif cmd == nil then + return out, false + end + local c2 = cmd :: string + local na = ARGS[c2] + for k = 1, na do + local v = if c2 == "A" and (k == 4 or k == 5) then flag() else number() + if v == nil then + return out, false + end + nums[k] = v + if k < na then + comma() + end + end + comma() + local ox, oy = if rel then cx else 0, if rel then cy else 0 + if c2 == "M" then + cx, cy = nums[1] + ox, nums[2] + oy + sx, sy = cx, cy + table.insert(out, { op = "M", cx, cy }) + cmd = "L" -- further pairs are line-tos + elseif c2 == "L" then + cx, cy = nums[1] + ox, nums[2] + oy + table.insert(out, { op = "L", cx, cy }) + elseif c2 == "H" then + cx = nums[1] + ox + table.insert(out, { op = "L", cx, cy }) + elseif c2 == "V" then + cy = nums[1] + (if rel then cy else 0) + table.insert(out, { op = "L", cx, cy }) + elseif c2 == "C" then + local x1, y1, x2, y2 = nums[1] + ox, nums[2] + oy, nums[3] + ox, nums[4] + oy + cx, cy = nums[5] + ox, nums[6] + oy + table.insert(out, { op = "C", x1, y1, x2, y2, cx, cy }) + lcx, lcy = x2, y2 + elseif c2 == "S" then + local x1, y1 = cx, cy + if last == "C" or last == "S" then + x1, y1 = 2 * cx - lcx, 2 * cy - lcy + end + local x2, y2 = nums[1] + ox, nums[2] + oy + cx, cy = nums[3] + ox, nums[4] + oy + table.insert(out, { op = "C", x1, y1, x2, y2, cx, cy }) + lcx, lcy = x2, y2 + elseif c2 == "Q" then + local x1, y1 = nums[1] + ox, nums[2] + oy + cx, cy = nums[3] + ox, nums[4] + oy + table.insert(out, { op = "Q", x1, y1, cx, cy }) + lcx, lcy = x1, y1 + elseif c2 == "T" then + local x1, y1 = cx, cy + if last == "Q" or last == "T" then + x1, y1 = 2 * cx - lcx, 2 * cy - lcy + end + cx, cy = nums[1] + ox, nums[2] + oy + table.insert(out, { op = "Q", x1, y1, cx, cy }) + lcx, lcy = x1, y1 + elseif c2 == "A" then + local x2, y2 = nums[6] + ox, nums[7] + oy + arc(cx, cy, nums[1], nums[2], nums[3], nums[4] ~= 0, nums[5] ~= 0, x2, y2, out) + cx, cy = x2, y2 + end + last = if c2 == "M" then "M" else c2 + end + return out, true +end + +function PathData.bounds(cmds: { Cmd }): (number?, number?, number?, number?) + local x0, y0, x1, y1 = math.huge, math.huge, -math.huge, -math.huge + local px, py = 0, 0 + for _, c in cmds do + local op = c.op + if op == "C" then + local ax, ay, bx, by, ex, ey = c[1], c[2], c[3], c[4], c[5], c[6] + for axis = 1, 2 do + local p0 = if axis == 1 then px else py + local p1 = if axis == 1 then ax else ay + local p2 = if axis == 1 then bx else by + local p3 = if axis == 1 then ex else ey + local a = -p0 + 3 * p1 - 3 * p2 + p3 + local b = 2 * (p0 - 2 * p1 + p2) + local cc = p1 - p0 + local ts = {} + if abs(a) < 1e-12 then + if abs(b) > 1e-12 then + table.insert(ts, -cc / b) + end + else + local disc = b * b - 4 * a * cc + if disc >= 0 then + local s = sqrt(disc) + table.insert(ts, (-b + s) / (2 * a)) + table.insert(ts, (-b - s) / (2 * a)) + end + end + for _, t in ts do + if t > 0 and t < 1 then + local mt = 1 - t + local v = mt * mt * mt * p0 + 3 * mt * mt * t * p1 + 3 * mt * t * t * p2 + t * t * t * p3 + if axis == 1 then + x0, x1 = math.min(x0, v), math.max(x1, v) + else + y0, y1 = math.min(y0, v), math.max(y1, v) + end + end + end + end + px, py = ex, ey + elseif op == "Q" then + local ax, ay, ex, ey = c[1], c[2], c[3], c[4] + for axis = 1, 2 do + local p0 = if axis == 1 then px else py + local p1 = if axis == 1 then ax else ay + local p2 = if axis == 1 then ex else ey + local den = p0 - 2 * p1 + p2 + if abs(den) > 1e-12 then + local t = (p0 - p1) / den + if t > 0 and t < 1 then + local mt = 1 - t + local v = mt * mt * p0 + 2 * mt * t * p1 + t * t * p2 + if axis == 1 then + x0, x1 = math.min(x0, v), math.max(x1, v) + else + y0, y1 = math.min(y0, v), math.max(y1, v) + end + end + end + end + px, py = ex, ey + elseif op == "M" or op == "L" then + px, py = c[1], c[2] + end + if op ~= "Z" then + x0, x1 = math.min(x0, px), math.max(x1, px) + y0, y1 = math.min(y0, py), math.max(y1, py) + end + end + if x0 > x1 then + return nil, nil, nil, nil + end + return x0, y0, x1, y1 +end + +local function num(v: number): string + if v ~= v or v == math.huge or v == -math.huge then + return "0" + end + local r = math.floor(v * 10000 + 0.5) / 10000 + if r == math.floor(r) and abs(r) < 1e15 then + return string.format("%d", r) + end + local s = string.format("%.4f", r) + s = string.gsub(s, "0+$", "") + return s +end +PathData.num = num + +function PathData.serialize(cmds: { Cmd }): string + local out = {} + for _, c in cmds do + local k = ARGS[c.op] + if k ~= nil then + local parts = { c.op } + local cnt = if c.op == "C" then 6 elseif c.op == "Q" then 4 elseif c.op == "Z" then 0 else 2 + for j = 1, cnt do + table.insert(parts, num(tonumber(c[j]) or 0)) + end + table.insert(out, table.concat(parts, " ")) + end + end + return table.concat(out, " ") +end + +local RASTER = { M = "moveTo", L = "lineTo", Q = "quadTo", C = "cubicTo", Z = "close" } +function PathData.toRaster(cmds: { Cmd }): { any } + local out = table.create(#cmds) + for i, c in cmds do + local r: any = { op = RASTER[c.op] or "close" } + for j = 1, #c do + r[j] = c[j] + end + out[i] = r + end + return out +end + +return PathData +end +__FILES["vector/svg/Render"] = function() + +-- vector/svg/Render: a Types.Vector to an rgba8 Image via codecs/image/Raster and codecs/image/Blend. +local Types = __include("Types") +local Raster = __include("codecs/image/Raster") +local Blend = __include("codecs/image/Blend") +local PathData = __include("vector/svg/PathData") +local Parse = __include("vector/svg/Parse") + +local Render = {} + +type M = { number } + +local function mul(m: M, n: M): M + return Raster.multiply(m, n) +end + +-- ------------------------------------------------------------------------------------------------ gradients +local function stopColor(stops: { { number } }, t: number): (number, number, number, number) + local n = #stops + if t <= stops[1][1] then + local s = stops[1] + return s[2], s[3], s[4], s[5] + end + if t >= stops[n][1] then + local s = stops[n] + return s[2], s[3], s[4], s[5] + end + for i = 2, n do + local b = stops[i] + if t <= b[1] then + local a = stops[i - 1] + local span = b[1] - a[1] + local f = if span > 0 then (t - a[1]) / span else 1 + return a[2] + (b[2] - a[2]) * f, a[3] + (b[3] - a[3]) * f, a[4] + (b[4] - a[4]) * f, a[5] + (b[5] - a[5]) * f + end + end + local s = stops[n] + return s[2], s[3], s[4], s[5] +end + +local function gradientFn(p: any, device: M, bbox: { number }?): ((number, number) -> (number, number, number, number))? + local stops = p.stops + if type(stops) ~= "table" or #stops == 0 then + return nil + end + local g: M = { 1, 0, 0, 1, 0, 0 } + if p.units ~= "userSpaceOnUse" then + if not bbox or bbox[3] - bbox[1] <= 0 or bbox[4] - bbox[2] <= 0 then + return nil -- a zero-size box: the gradient is not rendered + end + g = { bbox[3] - bbox[1], 0, 0, bbox[4] - bbox[2], bbox[1], bbox[2] } + end + if type(p.transform) == "table" then + g = mul(g, p.transform) + end + local inv = Raster.invert(mul(device, g)) + if not inv then + return nil + end + local a, b, c, d, e, f = inv[1], inv[2], inv[3], inv[4], inv[5], inv[6] + local spread = p.spread + local opacity = tonumber(p.opacity) or 1 + local function wrap(t: number): number + if spread == "repeat" then + return t - math.floor(t) + elseif spread == "reflect" then + local r = t % 2 + return if r > 1 then 2 - r else r + end + return t + end + if p.type == "linear" then + local x1, y1, x2, y2 = p.x1 or 0, p.y1 or 0, p.x2 or 1, p.y2 or 0 + local dx, dy = x2 - x1, y2 - y1 + local dd = dx * dx + dy * dy + if dd == 0 then + local r, gg, bb, aa = stopColor(stops, 1) + return function(): (number, number, number, number) + return r, gg, bb, aa * opacity + end + end + return function(x: number, y: number): (number, number, number, number) + local gx, gy = a * x + c * y + e, b * x + d * y + f + local t = wrap(((gx - x1) * dx + (gy - y1) * dy) / dd) + local r, gg, bb, aa = stopColor(stops, t) + return r, gg, bb, aa * opacity + end + end + local cx, cy, r = p.cx or 0.5, p.cy or 0.5, p.r or 0.5 + local fx, fy = p.fx or cx, p.fy or cy + if r <= 0 then + local rr, gg, bb, aa = stopColor(stops, 1) + return function(): (number, number, number, number) + return rr, gg, bb, aa * opacity + end + end + -- SVG 1.1: a focal point outside the circle moves onto it + local fdx, fdy = fx - cx, fy - cy + local fd = math.sqrt(fdx * fdx + fdy * fdy) + if fd > r * 0.999 then + local k = r * 0.999 / fd + fx, fy = cx + fdx * k, cy + fdy * k + end + return function(x: number, y: number): (number, number, number, number) + local gx, gy = a * x + c * y + e, b * x + d * y + f + local dx, dy = gx - fx, gy - fy + local t + if dx == 0 and dy == 0 then + t = 0 + else + -- the ray from the focus through the point meets the circle at s: t = 1 / s + local ox, oy = fx - cx, fy - cy + local qa = dx * dx + dy * dy + local qb = 2 * (dx * ox + dy * oy) + local qc = ox * ox + oy * oy - r * r + local disc = qb * qb - 4 * qa * qc + local s = (-qb + math.sqrt(math.max(0, disc))) / (2 * qa) + t = if s > 0 then 1 / s else 1 + end + local rr, gg, bb, aa = stopColor(stops, wrap(t)) + return rr, gg, bb, aa * opacity + end +end + +-- ------------------------------------------------------------------------------------------------ dashes +local function subpaths(cmds: { any }): { { cmds: { any }, closed: boolean } } + local out = {} + local cur: { any }? = nil + for _, c in cmds do + if c.op == "M" then + cur = { c } + table.insert(out, { cmds = cur, closed = false }) + elseif c.op == "Z" then + if cur then + out[#out].closed = true + -- a new subpath starts at the same point if more segments follow + local first = (cur :: { any })[1] + cur = { { op = "M", first[1], first[2] } } + table.insert(out, { cmds = cur, closed = false }) + end + elseif cur then + table.insert(cur, c) + end + end + return out +end + +local function polyline(cmds: { any }, tol: number): { number } + local pts: { number } = {} + local px, py = 0, 0 + for _, c in cmds do + local op = c.op + if op == "M" or op == "L" then + px, py = c[1], c[2] + table.insert(pts, px) + table.insert(pts, py) + elseif op == "Q" or op == "C" then + local len = 0 + local lx, ly = px, py + for k = 1, #c - 1, 2 do + len += math.sqrt((c[k] - lx) ^ 2 + (c[k + 1] - ly) ^ 2) + lx, ly = c[k], c[k + 1] + end + local steps = math.clamp(math.ceil(math.sqrt(len / math.max(tol, 1e-4))), 1, 512) + for i = 1, steps do + local t = i / steps + local mt = 1 - t + local x, y + if op == "Q" then + x = mt * mt * px + 2 * mt * t * c[1] + t * t * c[3] + y = mt * mt * py + 2 * mt * t * c[2] + t * t * c[4] + else + x = mt * mt * mt * px + 3 * mt * mt * t * c[1] + 3 * mt * t * t * c[3] + t * t * t * c[5] + y = mt * mt * mt * py + 3 * mt * mt * t * c[2] + 3 * mt * t * t * c[4] + t * t * t * c[6] + end + table.insert(pts, x) + table.insert(pts, y) + end + px, py = c[#c - 1], c[#c] + end + end + return pts +end + +local function dashed(cmds: { any }, dashes: { number }, offset: number, tol: number): { any } + local out = {} + local total = 0 + for _, v in dashes do + total += v + end + if total <= 0 then + return cmds + end + for _, sp in subpaths(cmds) do + if #sp.cmds < 2 then + continue + end + local pts = polyline(sp.cmds, tol) + if #pts < 4 then + continue + end + if sp.closed then + table.insert(pts, pts[1]) + table.insert(pts, pts[2]) + end + -- dash state at the start (offset wraps through the pattern) + local idx, left = 1, 0 + local o = offset % total + if o < 0 then + o += total + end + while o > 0 do + if o >= dashes[idx] then + o -= dashes[idx] + idx = idx % #dashes + 1 + else + break + end + end + left = dashes[idx] - o + local on = idx % 2 == 1 + local cur: { any }? = nil + if on then + cur = { { op = "M", pts[1], pts[2] } } + end + for i = 1, #pts - 3, 2 do + local x0, y0, x1, y1 = pts[i], pts[i + 1], pts[i + 2], pts[i + 3] + local seg = math.sqrt((x1 - x0) ^ 2 + (y1 - y0) ^ 2) + local pos = 0 + local guard = 0 + while seg - pos > left and guard < 100000 do + guard += 1 + pos += left + local t = pos / seg + local x, y = x0 + (x1 - x0) * t, y0 + (y1 - y0) * t + if on then + table.insert(cur :: { any }, { op = "L", x, y }) + for _, c in cur :: { any } do + table.insert(out, c) + end + cur = nil + else + cur = { { op = "M", x, y } } + end + on = not on + idx = idx % #dashes + 1 + left = dashes[idx] + end + left -= seg - pos + if on and cur then + table.insert(cur, { op = "L", x1, y1 }) + end + end + if on and cur and #cur > 1 then + for _, c in cur do + table.insert(out, c) + end + end + end + return out +end + +-- ------------------------------------------------------------------------------------------------ rendering +type Options = { + background: { number }?, -- r, g, b, a; default transparent + tolerance: number?, -- device pixels; default 0.1 +} + +local function scaleOf(m: M): number + return math.sqrt(math.abs(m[1] * m[4] - m[2] * m[3])) +end + +function Render.rasterize(v: Types.Vector, w: number, h: number, opts: Options?): Types.Image + local o: Options = opts or {} + local img = Types.Image.new(w, h) + local px = img.pixels + local n = w * h + local bg = o.background + if type(bg) == "table" then + local val = (bg[1] or 0) + (bg[2] or 0) * 256 + (bg[3] or 0) * 65536 + (bg[4] or 255) * 16777216 + for i = 0, n - 1 do + buffer.writeu32(px, i * 4, val) + end + end + local meta: any = if type(v.meta) == "table" then v.meta else {} + local view = Parse.viewTransform(v.viewBox, meta.preserveAspectRatio, 0, 0, w, h) + local groups: { any } = if type(meta.groups) == "table" then meta.groups else {} + local clips: { any } = if type(meta.clips) == "table" then meta.clips else {} + local tol = o.tolerance or 0.1 + local clipCache: { [number]: buffer } = {} + local function clipMask(id: number): buffer? + if clipCache[id] then + return clipCache[id] + end + local c = clips[id] + if type(c) ~= "table" then + return nil + end + local mask = buffer.create(n) + for _, cp in (if type(c.paths) == "table" then c.paths else {}) do + local m = Raster.mask(PathData.toRaster(cp.d), { transform = mul(view, cp.transform or Raster.IDENTITY), rule = cp.rule, clip = { 0, 0, w, h }, tolerance = tol }) + if m then + for y = 0, m.height - 1 do + for x = 0, m.width - 1 do + local cv = buffer.readu8(m.coverage, y * m.width + x) + if cv > 0 then + local i = (m.y + y) * w + m.x + x + local old = buffer.readu8(mask, i) + buffer.writeu8(mask, i, math.min(255, old + cv - math.floor(old * cv / 255 + 0.5))) + end + end + end + end + end + clipCache[id] = mask + return mask + end + local stack: { { id: number?, img: Types.Image } } = { { id = nil, img = img } } + local function chain(g: number?): { number } + local out = {} + local guard = 0 + while g ~= nil and guard < 256 do + table.insert(out, 1, g) + local gr = groups[g] + g = if type(gr) == "table" then gr.parent else nil + guard += 1 + end + return out + end + local function pop() + local top = table.remove(stack) :: any + local below = stack[#stack].img + local gr = groups[top.id] or {} + local mask: any = nil + if gr.clip then + local cm = clipMask(gr.clip) + mask = if cm then { pixels = cm, width = w, height = h, x = 0, y = 0, default = 0 } else { default = 0 } + end + Blend.composite(below.pixels, w, h, top.img.pixels, w, h, 0, 0, math.clamp(tonumber(gr.opacity) or 1, 0, 1), "normal", { mask = mask }) + end + local function draw(target: Types.Image, cmds: { any }, paint: any, device: M, rule: string?, opacity: number, bbox: { number }?) + local fill: any + if paint.type == "color" then + fill = paint.color + else + fill = gradientFn(paint, device, bbox) + if not fill then + return + end + end + Raster.fill(target, cmds, fill, { transform = device, rule = rule, opacity = opacity, tolerance = tol }) + end + for _, p in v.paths do + if type(p) ~= "table" or type(p.d) ~= "table" then + continue + end + local want = chain(p.group) + local keep = 1 + while keep < #stack and stack[keep + 1].id == want[keep] do + keep += 1 + end + while #stack > keep do + pop() + end + for k = keep, #want do + table.insert(stack, { id = want[k], img = Types.Image.new(w, h) }) + end + local device = mul(view, p.transform or Raster.IDENTITY) + local target = stack[#stack].img + local clipMaskBuf: buffer? = nil + if p.clip then + clipMaskBuf = clipMask(p.clip) + if not clipMaskBuf then + continue + end + target = Types.Image.new(w, h) + end + local opacity = math.clamp(tonumber(p.opacity) or 1, 0, 1) + local rcmds = PathData.toRaster(p.d) + local bbox: { number }? = nil + if (p.fill and p.fill.type ~= "color") or (p.stroke and p.stroke.type ~= "color") then + local x0, y0, x1, y1 = PathData.bounds(p.d) + if x0 then + bbox = { x0 :: number, y0 :: number, x1 :: number, y1 :: number } + end + end + if type(p.fill) == "table" then + draw(target, rcmds, p.fill, device, p.fillRule, opacity, bbox) + end + if type(p.stroke) == "table" and (tonumber(p.strokeWidth) or 1) > 0 then + local scale = math.max(scaleOf(device), 1e-6) + local src = p.d + if type(p.strokeDashArray) == "table" and #p.strokeDashArray > 0 then + src = dashed(p.d, p.strokeDashArray, tonumber(p.strokeDashOffset) or 0, tol / scale) + end + local outline = Raster.stroke(PathData.toRaster(src), { + width = tonumber(p.strokeWidth) or 1, + join = p.strokeLineJoin, + cap = p.strokeLineCap, + miterLimit = p.strokeMiterLimit, + tolerance = tol / scale, + }) + draw(target, outline, p.stroke, device, "nonzero", opacity, bbox) + end + if clipMaskBuf then + Blend.composite(stack[#stack].img.pixels, w, h, target.pixels, w, h, 0, 0, 1, "normal", { mask = { pixels = clipMaskBuf, width = w, height = h, x = 0, y = 0, default = 0 } }) + end + end + while #stack > 1 do + pop() + end + return img +end + +return Render +end +__FILES["vector/svg/Style"] = function() + +-- vector/svg/Style: SVG attribute value syntaxes (CSS Color 3, lengths, transform lists) and a <style> CSS subset. +local Raster = __include("codecs/image/Raster") +local Style = {} + +local NAMED: { [string]: number } = { + aliceblue = 0xf0f8ff, antiquewhite = 0xfaebd7, aqua = 0x00ffff, aquamarine = 0x7fffd4, azure = 0xf0ffff, + beige = 0xf5f5dc, bisque = 0xffe4c4, black = 0x000000, blanchedalmond = 0xffebcd, blue = 0x0000ff, + blueviolet = 0x8a2be2, brown = 0xa52a2a, burlywood = 0xdeb887, cadetblue = 0x5f9ea0, chartreuse = 0x7fff00, + chocolate = 0xd2691e, coral = 0xff7f50, cornflowerblue = 0x6495ed, cornsilk = 0xfff8dc, crimson = 0xdc143c, + cyan = 0x00ffff, darkblue = 0x00008b, darkcyan = 0x008b8b, darkgoldenrod = 0xb8860b, darkgray = 0xa9a9a9, + darkgreen = 0x006400, darkgrey = 0xa9a9a9, darkkhaki = 0xbdb76b, darkmagenta = 0x8b008b, darkolivegreen = 0x556b2f, + darkorange = 0xff8c00, darkorchid = 0x9932cc, darkred = 0x8b0000, darksalmon = 0xe9967a, darkseagreen = 0x8fbc8f, + darkslateblue = 0x483d8b, darkslategray = 0x2f4f4f, darkslategrey = 0x2f4f4f, darkturquoise = 0x00ced1, + darkviolet = 0x9400d3, deeppink = 0xff1493, deepskyblue = 0x00bfff, dimgray = 0x696969, dimgrey = 0x696969, + dodgerblue = 0x1e90ff, firebrick = 0xb22222, floralwhite = 0xfffaf0, forestgreen = 0x228b22, fuchsia = 0xff00ff, + gainsboro = 0xdcdcdc, ghostwhite = 0xf8f8ff, gold = 0xffd700, goldenrod = 0xdaa520, gray = 0x808080, + grey = 0x808080, green = 0x008000, greenyellow = 0xadff2f, honeydew = 0xf0fff0, hotpink = 0xff69b4, + indianred = 0xcd5c5c, indigo = 0x4b0082, ivory = 0xfffff0, khaki = 0xf0e68c, lavender = 0xe6e6fa, + lavenderblush = 0xfff0f5, lawngreen = 0x7cfc00, lemonchiffon = 0xfffacd, lightblue = 0xadd8e6, lightcoral = 0xf08080, + lightcyan = 0xe0ffff, lightgoldenrodyellow = 0xfafad2, lightgray = 0xd3d3d3, lightgreen = 0x90ee90, + lightgrey = 0xd3d3d3, lightpink = 0xffb6c1, lightsalmon = 0xffa07a, lightseagreen = 0x20b2aa, + lightskyblue = 0x87cefa, lightslategray = 0x778899, lightslategrey = 0x778899, lightsteelblue = 0xb0c4de, + lightyellow = 0xffffe0, lime = 0x00ff00, limegreen = 0x32cd32, linen = 0xfaf0e6, magenta = 0xff00ff, + maroon = 0x800000, mediumaquamarine = 0x66cdaa, mediumblue = 0x0000cd, mediumorchid = 0xba55d3, + mediumpurple = 0x9370db, mediumseagreen = 0x3cb371, mediumslateblue = 0x7b68ee, mediumspringgreen = 0x00fa9a, + mediumturquoise = 0x48d1cc, mediumvioletred = 0xc71585, midnightblue = 0x191970, mintcream = 0xf5fffa, + mistyrose = 0xffe4e1, moccasin = 0xffe4b5, navajowhite = 0xffdead, navy = 0x000080, oldlace = 0xfdf5e6, + olive = 0x808000, olivedrab = 0x6b8e23, orange = 0xffa500, orangered = 0xff4500, orchid = 0xda70d6, + palegoldenrod = 0xeee8aa, palegreen = 0x98fb98, paleturquoise = 0xafeeee, palevioletred = 0xdb7093, + papayawhip = 0xffefd5, peachpuff = 0xffdab9, peru = 0xcd853f, pink = 0xffc0cb, plum = 0xdda0dd, + powderblue = 0xb0e0e6, purple = 0x800080, rebeccapurple = 0x663399, red = 0xff0000, rosybrown = 0xbc8f8f, + royalblue = 0x4169e1, saddlebrown = 0x8b4513, salmon = 0xfa8072, sandybrown = 0xf4a460, seagreen = 0x2e8b57, + seashell = 0xfff5ee, sienna = 0xa0522d, silver = 0xc0c0c0, skyblue = 0x87ceeb, slateblue = 0x6a5acd, + slategray = 0x708090, slategrey = 0x708090, snow = 0xfffafa, springgreen = 0x00ff7f, steelblue = 0x4682b4, + tan = 0xd2b48c, teal = 0x008080, thistle = 0xd8bfd8, tomato = 0xff6347, turquoise = 0x40e0d0, violet = 0xee82ee, + wheat = 0xf5deb3, white = 0xffffff, whitesmoke = 0xf5f5f5, yellow = 0xffff00, yellowgreen = 0x9acd32, +} + +local function clamp255(v: number): number + return math.clamp(math.floor(v + 0.5), 0, 255) +end + +local function hue(p: number, q: number, t: number): number + t %= 1 + if t < 1 / 6 then + return p + (q - p) * 6 * t + elseif t < 1 / 2 then + return q + elseif t < 2 / 3 then + return p + (q - p) * (2 / 3 - t) * 6 + end + return p +end + +function Style.color(s: string, current: { number }?): any + s = string.lower((string.gsub(s, "^%s*(.-)%s*$", "%1"))) + if s == "none" then + return "none" + elseif s == "transparent" then + return { 0, 0, 0, 0 } + elseif s == "currentcolor" then + return current or { 0, 0, 0, 255 } + end + local hex = string.match(s, "^#(%x+)$") + if hex then + local n = #hex + if n == 3 or n == 4 then + local v = {} + for k = 1, n do + v[k] = (tonumber(string.sub(hex, k, k), 16) :: number) * 17 + end + return { v[1], v[2], v[3], v[4] or 255 } + elseif n == 6 or n == 8 then + local v = {} + for k = 1, n // 2 do + v[k] = tonumber(string.sub(hex, k * 2 - 1, k * 2), 16) :: number + end + return { v[1], v[2], v[3], v[4] or 255 } + end + return nil + end + local fn, args = string.match(s, "^(%a+)%s*%((.*)%)$") + if fn then + local parts = {} + for p in string.gmatch(args :: string, "[^,%s/]+") do + table.insert(parts, p) + end + local function comp(p: string?, scale: number): number? + if p == nil then + return nil + end + local pct = string.match(p, "^([%d.eE+-]+)%%$") + if pct then + local v = tonumber(pct) + return if v then v / 100 * scale else nil + end + return tonumber(p) + end + local function alpha(p: string?): number + if p == nil then + return 255 + end + local v = comp(p, 1) + return clamp255((v or 1) * 255) + end + if fn == "rgb" or fn == "rgba" then + local r, g, b = comp(parts[1], 255), comp(parts[2], 255), comp(parts[3], 255) + if not (r and g and b) then + return nil + end + return { clamp255(r :: number), clamp255(g :: number), clamp255(b :: number), alpha(parts[4]) } + elseif fn == "hsl" or fn == "hsla" then + local h = tonumber((string.gsub(parts[1] or "", "deg$", ""))) + local sat, l = comp(parts[2], 1), comp(parts[3], 1) + if not (h and sat and l) then + return nil + end + local hh = (h :: number) / 360 + local ss, ll = math.clamp(sat :: number, 0, 1), math.clamp(l :: number, 0, 1) + local q = if ll < 0.5 then ll * (1 + ss) else ll + ss - ll * ss + local p = 2 * ll - q + return { clamp255(hue(p, q, hh + 1 / 3) * 255), clamp255(hue(p, q, hh) * 255), clamp255(hue(p, q, hh - 1 / 3) * 255), alpha(parts[4]) } + end + return nil + end + local v = NAMED[s] + if v then + return { v // 65536, v // 256 % 256, v % 256, 255 } + end + return nil +end + +-- SVG number: sign? digits? ("." digits)? exponent? +local function scan(s: string, i: number): (number?, number) + local n = #s + local st = i + local c = string.byte(s, i) + if c == 43 or c == 45 then + i += 1 + end + local any = false + while i <= n do + c = string.byte(s, i) + if c >= 48 and c <= 57 then + i += 1 + any = true + else + break + end + end + if i <= n and string.byte(s, i) == 46 then + i += 1 + while i <= n do + c = string.byte(s, i) + if c >= 48 and c <= 57 then + i += 1 + any = true + else + break + end + end + end + if not any then + return nil, st + end + c = string.byte(s, i) + if c == 101 or c == 69 then + local save = i + i += 1 + c = string.byte(s, i) + if c == 43 or c == 45 then + i += 1 + end + local e = false + while i <= n do + c = string.byte(s, i) + if c >= 48 and c <= 57 then + i += 1 + e = true + else + break + end + end + if not e then + i = save + end + end + return tonumber(string.sub(s, st, i - 1)), i +end + +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 + end + local t = string.match(s, "^%s*(.-)%s*$") :: string + local x, j = scan(t, 1) + if x == nil then + return nil + end + local u = string.lower(string.sub(t, j)) + if u == "" then + return x + elseif u == "%" then + return x / 100 * (ref or 100) + elseif u == "em" then + return x * (fontSize or 16) + elseif u == "ex" then + return x * (fontSize or 16) / 2 + end + local k = UNITS[u] + return if k then x * k else nil +end + +function Style.numbers(s: string?): { number } + local out = {} + if s == nil then + return out + end + local i, n = 1, #s + while i <= n do + local c = string.byte(s, i) + if c == 32 or c == 44 or c == 9 or c == 10 or c == 13 then + i += 1 + else + local v, j = scan(s, i) + if v == nil then + break + end + table.insert(out, v) + i = j + end + end + return out +end + +local mul = Raster.multiply +Style.multiply = mul +function Style.transform(s: string): { number }? + local m = { 1, 0, 0, 1, 0, 0 } + local rest = s + while true do + rest = string.gsub(rest, "^[%s,]+", "") + if rest == "" then + break + end + local name, args, after = string.match(rest, "^(%a+)%s*(%b())(.*)$") + if not name then + return nil + end + rest = after :: string + local v = Style.numbers(string.sub(args :: string, 2, -2)) + local t: { number } + if name == "matrix" and #v == 6 then + t = v + elseif name == "translate" and (#v == 1 or #v == 2) then + t = { 1, 0, 0, 1, v[1], v[2] or 0 } + elseif name == "scale" and (#v == 1 or #v == 2) then + t = { v[1], 0, 0, v[2] or v[1], 0, 0 } + elseif name == "rotate" and (#v == 1 or #v == 3) then + local r = v[1] * math.pi / 180 + local c, sn = math.cos(r), math.sin(r) + t = { c, sn, -sn, c, 0, 0 } + if #v == 3 then + t = mul(mul({ 1, 0, 0, 1, v[2], v[3] }, t), { 1, 0, 0, 1, -v[2], -v[3] }) + end + elseif name == "skewX" and #v == 1 then + t = { 1, 0, math.tan(v[1] * math.pi / 180), 1, 0, 0 } + elseif name == "skewY" and #v == 1 then + t = { 1, math.tan(v[1] * math.pi / 180), 0, 1, 0, 0 } + else + return nil + end + m = mul(m, t) + end + return m +end + +function Style.declarations(s: string): { [string]: string } + local out: { [string]: string } = {} + for decl in string.gmatch(s, "[^;]+") do + local k, v = string.match(decl, "^%s*([%w-]+)%s*:%s*(.-)%s*$") + if k and v then + v = string.gsub(v :: string, "%s*!important$", "") + out[string.lower(k :: string)] = v :: string + end + end + return out +end + +-- ------------------------------------------------------------------------------------------------ CSS +type Selector = { tag: string?, id: string?, classes: { string }, specificity: number } +type Rule = { selector: Selector, decls: { [string]: string }, order: number } + +local function selector(s: string): Selector? + s = string.gsub(s, "^%s*(.-)%s*$", "%1") + if s == "" or string.find(s, "[%s>+~%[:]") then + return nil -- combinators, attribute and pseudo selectors: not supported + end + local sel: Selector = { classes = {}, specificity = 0 } + local tag = string.match(s, "^([%a_][%w_-]*)") + if tag then + sel.tag = tag + sel.specificity += 1 + s = string.sub(s, #tag + 1) + elseif string.sub(s, 1, 1) == "*" then + s = string.sub(s, 2) + end + while s ~= "" do + local kind, name, rest = string.match(s, "^([.#])([%w_-]+)(.*)$") + if not kind then + return nil + end + if kind == "." then + table.insert(sel.classes, name :: string) + sel.specificity += 100 + else + sel.id = name + sel.specificity += 10000 + end + s = rest :: string + end + return sel +end + +function Style.css(text: string, rules: { Rule }?): { Rule } + local out: { Rule } = rules or {} + text = string.gsub(text, "/%*.-%*/", "") + text = string.gsub(text, "<!%-%-", "") + text = string.gsub(text, "%-%->", "") + -- drop @rules with blocks (@media { ... { } }) and simple ones (@import ...;) + local guard = 0 + while guard < 100 do + guard += 1 + local s, e = string.find(text, "@[%w-]+[^{;]*%b{}") + if not s then + break + end + 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 :: string, 2, -2)) + for one in string.gmatch(sels, "[^,]+") do + local sel = selector(one) + if sel then + table.insert(out, { selector = sel, decls = decls, order = #out + 1 }) + end + end + end + return out +end + +function Style.matches(sel: Selector, tag: string, id: string?, classes: { [string]: boolean }): boolean + if sel.tag and sel.tag ~= tag then + return false + end + if sel.id and sel.id ~= id then + return false + end + for _, c in sel.classes do + if not classes[c] then + return false + end + end + return true +end + +return Style +end +__FILES["vector/svg/Write"] = function() + +-- vector/svg/Write: a Types.Vector to SVG text; never throws (bad values return nil, message). +local Xml = __include("codecs/text/Xml") +local Types = __include("Types") +local PathData = __include("vector/svg/PathData") + +local Write = {} + +local num = PathData.num + +local function el(name: string, attrs: { { any } }, children: { any }?): any + local o = Types.object() + for _, kv in attrs do + if kv[2] ~= nil then + Types.set(o, kv[1], if type(kv[2]) == "number" then num(kv[2]) else tostring(kv[2])) + end + end + return Xml.element(name, o :: any, children) +end + +local function hex(c: { number }): string + return string.format("#%02x%02x%02x", math.clamp(math.floor(c[1] or 0), 0, 255), math.clamp(math.floor(c[2] or 0), 0, 255), math.clamp(math.floor(c[3] or 0), 0, 255)) +end + +local function matrix(m: any): string? + if type(m) ~= "table" or #m < 6 then + return nil + end + if m[1] == 1 and m[2] == 0 and m[3] == 0 and m[4] == 1 then + if m[5] == 0 and m[6] == 0 then + return nil + end + return "translate(" .. num(m[5]) .. " " .. num(m[6]) .. ")" + end + local parts = {} + for k = 1, 6 do + parts[k] = num(tonumber(m[k]) or 0) + end + return "matrix(" .. table.concat(parts, " ") .. ")" +end + +function Write.vector(v: Types.Vector): (string?, string?) + if type(v) ~= "table" or type(v.paths) ~= "table" or type(v.width) ~= "number" or type(v.height) ~= "number" then + return nil, "needs a Vector value" + end + local meta: any = if type(v.meta) == "table" then v.meta else {} + local groups: { any } = if type(meta.groups) == "table" then meta.groups else {} + local clips: { any } = if type(meta.clips) == "table" then meta.clips else {} + local defs = {} + local gradients = 0 + local function paintAttrs(p: any, which: string): { { any } } + if type(p) ~= "table" then + return { { which, "none" } } + end + if p.type == "color" and type(p.color) == "table" then + local a = p.color[4] or 255 + return { { which, hex(p.color) }, { which .. "-opacity", if a < 255 then num(a / 255) else nil } } + end + if p.type ~= "linear" and p.type ~= "radial" then + return { { which, "none" } } + end + gradients += 1 + local id = "g" .. gradients + local kids = {} + for _, s in (if type(p.stops) == "table" then p.stops else {}) do + local a = s[5] or 255 + table.insert(kids, el("stop", { { "offset", s[1] or 0 }, { "stop-color", hex({ s[2], s[3], s[4] }) }, { "stop-opacity", if a < 255 then num(a / 255) else nil } })) + end + local attrs: { { any } } = { { "id", id }, { "gradientUnits", if p.units == "userSpaceOnUse" then "userSpaceOnUse" else nil } } + if p.type == "linear" then + table.insert(attrs, { "x1", p.x1 or 0 }) + table.insert(attrs, { "y1", p.y1 or 0 }) + table.insert(attrs, { "x2", p.x2 or 1 }) + table.insert(attrs, { "y2", p.y2 or 0 }) + else + table.insert(attrs, { "cx", p.cx or 0.5 }) + table.insert(attrs, { "cy", p.cy or 0.5 }) + table.insert(attrs, { "r", p.r or 0.5 }) + table.insert(attrs, { "fx", p.fx }) + table.insert(attrs, { "fy", p.fy }) + if p.fr and p.fr ~= 0 then + table.insert(attrs, { "fr", p.fr }) + end + end + table.insert(attrs, { "spreadMethod", if p.spread and p.spread ~= "pad" then p.spread else nil }) + table.insert(attrs, { "gradientTransform", matrix(p.transform) }) + table.insert(defs, el(if p.type == "linear" then "linearGradient" else "radialGradient", attrs, kids)) + local op = tonumber(p.opacity) or 1 + return { { which, "url(#" .. id .. ")" }, { which .. "-opacity", if op < 1 then num(op) else nil } } + end + local clipIds: { [number]: string } = {} + local function clipRef(id: number?): string? + if id == nil or type(clips[id]) ~= "table" then + return nil + end + if clipIds[id] == nil then + local cid = "c" .. id + clipIds[id] = cid + local kids = {} + for _, cp in (if type(clips[id].paths) == "table" then clips[id].paths else {}) do + table.insert(kids, el("path", { { "d", PathData.serialize(cp.d or {}) }, { "transform", matrix(cp.transform) }, { "clip-rule", if cp.rule == "evenodd" then "evenodd" else nil } })) + end + table.insert(defs, el("clipPath", { { "id", cid } }, kids)) + end + return "url(#" .. clipIds[id] .. ")" + end + local root = {} + local stack: { { id: number?, kids: { any } } } = { { id = nil, kids = root } } + local function chain(g: number?): { number } + local out = {} + local guard = 0 + while g ~= nil and guard < 256 do + table.insert(out, 1, g) + local gr = groups[g] + g = if type(gr) == "table" then gr.parent else nil + guard += 1 + end + return out + end + for _, p in v.paths do + if type(p) ~= "table" or type(p.d) ~= "table" then + continue + end + local want = chain(p.group) + local keep = 1 + while keep < #stack and stack[keep + 1].id == want[keep] do + keep += 1 + end + while #stack > keep do + table.remove(stack) + end + for k = keep, #want do + local gr = groups[want[k]] or {} + local kids = {} + local op = tonumber(gr.opacity) or 1 + table.insert(stack[#stack].kids, el("g", { { "opacity", if op < 1 then op else nil }, { "clip-path", clipRef(gr.clip) } }, kids)) + table.insert(stack, { id = want[k], kids = kids }) + end + local attrs: { { any } } = { { "id", p.id }, { "d", PathData.serialize(p.d) }, { "transform", matrix(p.transform) } } + for _, kv in paintAttrs(p.fill, "fill") do + table.insert(attrs, kv) + end + table.insert(attrs, { "fill-rule", if p.fillRule == "evenodd" then "evenodd" else nil }) + for _, kv in paintAttrs(p.stroke, "stroke") do + if kv[2] ~= "none" then + table.insert(attrs, kv) + end + end + if type(p.stroke) == "table" then + local sw = tonumber(p.strokeWidth) or 1 + table.insert(attrs, { "stroke-width", if sw ~= 1 then sw else nil }) + table.insert(attrs, { "stroke-linejoin", if p.strokeLineJoin and p.strokeLineJoin ~= "miter" then p.strokeLineJoin else nil }) + table.insert(attrs, { "stroke-linecap", if p.strokeLineCap and p.strokeLineCap ~= "butt" then p.strokeLineCap else nil }) + local ml = tonumber(p.strokeMiterLimit) + table.insert(attrs, { "stroke-miterlimit", if ml and ml ~= 4 then ml else nil }) + if type(p.strokeDashArray) == "table" and #p.strokeDashArray > 0 then + local parts = {} + for k, d in p.strokeDashArray do + parts[k] = num(tonumber(d) or 0) + end + 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 + end + local op = tonumber(p.opacity) or 1 + table.insert(attrs, { "opacity", if op < 1 then op else nil }) + local node = el("path", attrs) + local cr = clipRef(p.clip) + if cr then + node = el("g", { { "clip-path", cr } }, { node }) + end + table.insert(stack[#stack].kids, node) + end + local children = {} + if #defs > 0 then + table.insert(children, el("defs", {}, defs)) + end + for _, c in root do + table.insert(children, c) + end + local vb = v.viewBox + local vbText = if type(vb) == "table" and #vb == 4 then num(vb[1]) .. " " .. num(vb[2]) .. " " .. num(vb[3]) .. " " .. num(vb[4]) else nil + local svg = el("svg", { + { "xmlns", "http://www.w3.org/2000/svg" }, + { "width", v.width }, + { "height", v.height }, + { "viewBox", vbText }, + { "preserveAspectRatio", meta.preserveAspectRatio }, + }, children) + local s, err = Xml.encode(Xml.document(svg, { version = "1.0", encoding = "UTF-8" }), { indent = 1 }) + if not s then + return nil, tostring(err) + end + return s .. "\n", nil +end + +return Write +end +__FILES["vector/tiled"] = function() + +-- vector/tiled: Tiled maps, TMX (XML) / TMJ (JSON), and TSX / TSJ tilesets (Tiled 1.12 docs: "TMX Map Format", "JSON +-- Map Format"). Supports: every orientation, tile / object / image / group layers, infinite maps, typed properties, +-- tilesets. Not supported: zstd layer data (Err.UNSUPPORTED), Wang sets / terrains, loading external tilesets / images. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Sniff = __include("core/Sniff") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Xml = __include("codecs/text/Xml") +local Json = __include("codecs/text/Json") +local Tmx = __include("vector/tiled/Tmx") +local Tmj = __include("vector/tiled/Tmj") + +-- ------------------------------------------------------------------------------------------------ contract +local Tiled = { + name = "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/text/Xml", "codecs/text/Json", "codecs/compress/Deflate", "core/Sniff" }, + caps = { decode = true, encode = true, tilesets = true, infinite = true }, +} + +type DecodeOptions = { + maxBytes: number?, -- default 256 MB +} +type EncodeOptions = { + format: string?, -- "tmx" | "tsx" | "tmj" | "tsj" | "json"; default: the source's flavour, else tmx + encoding: string?, -- tile data: "csv" (TMX default) | "base64" | "xml" (TMX only); TMJ: arrays unless "base64" + compression: string?, -- nil | "zlib" | "gzip" + level: number?, -- default 6 + indent: number?, -- default 1 (TMX), 2 (TMJ); 0 = compact JSON +} + +-- ------------------------------------------------------------------------------------------------ sniff +local function head(r: Bytes.Reader): string + local h = Sniff.text(r, 1024) + return h +end + +function Tiled.sniff(r: Bytes.Reader): number + local h = head(r) + if string.match(h, "^%s*<") then + if string.find(h, "<map[%s>]") or string.find(h, "<tileset[%s>]") then + return 0.9 + end + return 0 + end + if string.match(h, "^%s*{") then + -- Tiled writes its keys sorted: "type" comes last, so look at the tail too + local n = r:remaining() + local tail = if n > 1024 then r:peek(1024, n - 1024) else "" + for _, part in { h, tail } do + if string.find(part, "\"type\"%s*:%s*\"map\"") or string.find(part, "\"type\"%s*:%s*\"tileset\"") then + return 0.8 + end + end + if string.find(h, "\"tilewidth\"", 1, true) and (string.find(h, "\"orientation\"", 1, true) or string.find(h, "\"tilesets\"", 1, true)) then + return 0.6 + end + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Tiled.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.TileMap?, Err.Err?) + local maxBytes = opts and opts.maxBytes or 2 ^ 28 + if r.limit - r.base > maxBytes then + return nil, Err.new(Err.LIMIT, "file is over the byte limit") + end + local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + local h = head(r) + local map: any, msg: string?, unsupported: boolean? + local flavour + if string.match(h, "^%s*<") then + local doc, xerr = Xml.decode(text) + if not doc then + return nil, xerr + end + local root = (doc :: any).root + if root == nil then + return nil, Err.new(Err.CORRUPT, "no root element") + end + if root.name == "tileset" then + map = Types.TileMap.new(0, 0, 0, 0) + map.tilesets = { Tmx.tileset(root) } + map.meta.tileset = true + flavour = "tsx" + else + map, msg, unsupported = Tmx.read(root) + flavour = "tmx" + end + else + local v, jerr = Json.decode(text) + if v == nil then + return nil, jerr + end + if type(v) == "table" and v.type == "tileset" then + map = Types.TileMap.new(0, 0, 0, 0) + map.tilesets = { Tmj.tileset(v) } + map.meta.tileset = true + flavour = "tsj" + else + map, msg, unsupported = Tmj.read(v) + flavour = "tmj" + end + end + if not map then + return nil, Err.new(if unsupported then Err.UNSUPPORTED else Err.CORRUPT, msg or "bad map") + end + map.meta.source = { format = flavour } + return map, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Tiled.encode(map: Types.TileMap, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(map) ~= "table" or type(map.layers) ~= "table" or type(map.tilesets) ~= "table" then + return nil, Err.new(Err.ARG, "needs a TileMap value") + end + local o: EncodeOptions = opts or {} + local meta: any = if type(map.meta) == "table" then map.meta else {} + local fmt = o.format or (if type(meta.source) == "table" then meta.source.format else nil) or "tmx" + fmt = string.lower(fmt) + if fmt == "tiled" then + fmt = if type(meta.source) == "table" and meta.source.format then meta.source.format else "tmx" + end + local tilesetOnly = meta.tileset == true or fmt == "tsx" or fmt == "tsj" + if o.encoding and o.encoding ~= "csv" and o.encoding ~= "base64" and o.encoding ~= "xml" then + return nil, Err.new(Err.ARG, "encoding must be csv, base64 or xml") + end + 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: 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 + if not map.tilesets[1] then + return nil, Err.new(Err.ARG, "no tileset to write") + end + doc = Xml.document(Tmx.tilesetNode(map.tilesets[1], false), { version = "1.0", encoding = "UTF-8" }) + else + doc, err = Tmx.write(map, wo) + end + if not doc then + return nil, Err.new(Err.ARG, err or "bad map") + end + local s, xerr = Xml.encode(doc, { indent = o.indent or 1 }) + if not s then + return nil, xerr + end + return buffer.fromstring(s .. "\n"), nil + elseif fmt == "tmj" or fmt == "tsj" or fmt == "json" then + local v: any, err: string? + if tilesetOnly then + if not map.tilesets[1] then + return nil, Err.new(Err.ARG, "no tileset to write") + end + v = Tmj.tilesetValue(map.tilesets[1], false) + else + v, err = Tmj.write(map, wo) + end + if v == nil then + return nil, Err.new(Err.ARG, err or "bad map") + end + local indent = if o.indent == 0 then nil else (o.indent or 2) + local s, jerr = Json.encode(v, { indent = indent }) + if not s then + return nil, jerr + end + return buffer.fromstring(s .. "\n"), nil + end + return nil, Err.new(Err.ARG, "unknown format " .. tostring(fmt) .. " (tmx, tmj, tsx, tsj)") +end + +return Tiled +end +__FILES["vector/tiled/Data"] = function() + +-- vector/tiled/Data: tile layer data shared by TMX and TMJ: CSV, base64 (raw / zlib / gzip), properties, numbers. +local Base64 = __include("core/Base64") +local Deflate = __include("codecs/compress/Deflate") + +local Data = {} + +function Data.csv(text: string): ({ number }?, string?) + local out = {} + for tok in string.gmatch(text, "[^,%s]+") do + local v = tonumber(tok) + if v == nil or v < 0 or v >= 4294967296 or v % 1 ~= 0 then + return nil, "bad gid " .. string.sub(tok, 1, 20) + end + table.insert(out, v) + end + return out, nil +end + +function Data.base64(text: string, compression: string?): ({ number }?, string?, boolean?) + local raw, err = Base64.decode(text) + if not raw then + 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), nil + end + bytes = z + elseif compression == "gzip" then + local z, zerr = Deflate.gunzip(bytes) + if not z then + return nil, "gzip: " .. tostring(zerr), nil + end + bytes = z + elseif compression ~= nil and compression ~= "" then + return nil, "compression " .. compression .. " is not supported", true + end + local n = buffer.len(bytes) // 4 + 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, nil +end + +function Data.toBase64(gids: { number }, compression: string?, level: number?): (string?, string?) + local b = buffer.create(#gids * 4) + for i, g in gids do + buffer.writeu32(b, (i - 1) * 4, g % 4294967296) + end + if compression == "zlib" then + local z = Deflate.zlibCompress(b, { level = level or 6 }) + if not z then + return nil, "zlib failed" + end + b = z + elseif compression == "gzip" then + local z = Deflate.gzip(b, { level = level or 6 }) + if not z then + return nil, "gzip failed" + end + b = z + elseif compression ~= nil and compression ~= "" then + return nil, "compression " .. compression .. " is not supported" + end + return Base64.encode(b), nil +end + +-- integers without a fraction (gids up to 2^32), others in the shortest form both runtimes print +function Data.num(v: number): string + if v % 1 == 0 and math.abs(v) < 2 ^ 53 then + return string.format("%.0f", v) + end + local s = string.format("%.15g", v) + if tonumber(s) ~= v then + s = string.format("%.17g", v) + end + return s +end + +-- Tiled's CSV layout: one row per line +function Data.csvText(gids: { number }, width: number): string + local rows = {} + local row = {} + for i, g in gids do + table.insert(row, Data.num(g)) + if width > 0 and i % width == 0 then + table.insert(rows, table.concat(row, ",")) + row = {} + end + end + if #row > 0 then + table.insert(rows, table.concat(row, ",")) + end + return "\n" .. table.concat(rows, ",\n") .. "\n" +end + +-- Tiled's canonical colour text: lower case "#rrggbb", or "#aarrggbb" when not opaque +function Data.color(s: string?): string? + if type(s) ~= "string" then + return nil + end + local h = string.lower((string.gsub(s, "^#", ""))) + if #h == 8 and string.sub(h, 1, 2) == "ff" then + h = string.sub(h, 3) + end + return "#" .. h +end + +function Data.value(typ: string, text: string): any + if typ == "int" or typ == "float" or typ == "object" then + return tonumber(text) or 0 + elseif typ == "bool" then + return text == "true" or text == "1" + elseif typ == "color" then + return Data.color(text) or "" + end + return text +end + +function Data.typeOf(v: any, declared: string?): string + if declared then + return declared + end + if type(v) == "boolean" then + return "bool" + elseif type(v) == "number" then + return if v % 1 == 0 then "int" else "float" + elseif type(v) == "table" then + return "class" + end + return "string" +end + +function Data.sortedKeys(t: { [any]: any }): { string } + local out = {} + for k in pairs(t) do + if type(k) == "string" then + table.insert(out, k) + end + end + table.sort(out) + return out +end + +return Data +end +__FILES["vector/tiled/Tmj"] = function() + +-- vector/tiled/Tmj: TMJ / TSJ (JSON map format, Tiled 1.12 docs) <-> a Types.TileMap. +local Types = __include("Types") +local Data = __include("vector/tiled/Data") + +local Tmj = {} + +local function n(v: any, default: number?): number? + if type(v) == "number" then + return v + end + return default +end +local function b(v: any, default: boolean): boolean + if type(v) == "boolean" then + return v + end + return default +end +local function s(v: any): string? + if type(v) == "string" then + return v + end + return nil +end +local function list(v: any): { any } + if type(v) == "table" then + return v + end + return {} +end + +-- ------------------------------------------------------------------------------------------------ read +local function properties(v: any): ({ [string]: any }, { [string]: string }?) + local props: { [string]: any } = {} + local types: { [string]: string }? = nil + for _, p in list(v) do + if type(p) == "table" and type(p.name) == "string" then + local typ = s(p.type) or "string" + local val: any = p.value + if typ == "class" then + local inner, innerTypes = {}, nil + if type(val) == "table" then + -- a class value is an object of member -> value (types come from the project): keep them as they are + for k, x in pairs(val) do + if type(k) == "string" then + inner[k] = x + end + end + end + val = { class = s(p.propertytype) or "", properties = inner, propertyTypes = innerTypes } + elseif typ == "int" or typ == "float" or typ == "object" then + val = n(val, 0) + elseif typ == "bool" then + val = val == true + elseif typ == "color" then + val = Data.color(s(val)) or "" + elseif type(val) ~= "string" then + val = if val == nil then "" else tostring(val) + end + props[p.name] = val + if typ ~= "string" then + types = types or {} + ;(types :: any)[p.name] = typ + end + end + end + return props, types +end + +local function withProps(t: any, v: any) + local props, types = properties(v.properties) + t.properties = props + if types then + t.propertyTypes = types + end +end + +local function gids(v: any, encoding: string?, compression: string?): ({ number }?, string?, boolean?) + if type(v) == "string" then + if encoding == "base64" or encoding == nil then + return Data.base64(v, compression) + end + return nil, "unknown encoding " .. tostring(encoding), true + end + local out = {} + for _, g in list(v) do + if type(g) ~= "number" or g < 0 or g >= 4294967296 then + return nil, "bad gid", nil + end + table.insert(out, g) + end + return out, nil, nil +end + +local function object(o: any): any + local obj: any = { + id = n(o.id), + name = s(o.name) or "", + class = s(o.class) or s(o.type) or "", + x = n(o.x, 0), + y = n(o.y, 0), + width = n(o.width, 0), + height = n(o.height, 0), + rotation = n(o.rotation, 0), + gid = n(o.gid), + visible = b(o.visible, true), + template = s(o.template), + shape = "rectangle", + } + withProps(obj, o) + if o.ellipse == true then + obj.shape = "ellipse" + elseif o.point == true then + obj.shape = "point" + end + for _, kind in { "polygon", "polyline" } do + if type(o[kind]) == "table" then + obj.shape = kind + local pts = {} + for _, p in o[kind] do + if type(p) == "table" then + table.insert(pts, { n(p.x, 0), n(p.y, 0) }) + end + end + obj.points = pts + end + end + if type(o.text) == "table" then + local t = o.text + obj.shape = "text" + obj.text = { + text = s(t.text) or "", + fontFamily = s(t.fontfamily) or "sans-serif", + pixelSize = n(t.pixelsize, 16), + wrap = b(t.wrap, false), + color = Data.color(s(t.color)) or "#000000", + bold = b(t.bold, false), + italic = b(t.italic, false), + underline = b(t.underline, false), + strikeout = b(t.strikeout, false), + kerning = b(t.kerning, true), + halign = s(t.halign) or "left", + valign = s(t.valign) or "top", + } + end + return obj +end + +local TYPES = { tilelayer = "tiles", objectgroup = "objects", imagelayer = "image", group = "group" } + +local layer: (v: any, depth: number) -> (any, string?, boolean?) + +local function common(v: any, typ: string): any + local l: any = { + type = typ, + id = n(v.id), + name = s(v.name) or "", + visible = b(v.visible, true), + opacity = n(v.opacity, 1), + x = n(v.x, 0), + y = n(v.y, 0), + offsetX = n(v.offsetx, 0), + offsetY = n(v.offsety, 0), + parallaxX = n(v.parallaxx, 1), + parallaxY = n(v.parallaxy, 1), + tintColor = Data.color(s(v.tintcolor)), + class = s(v.class) or "", + locked = b(v.locked, false), + } + withProps(l, v) + return l +end + +local function objectGroup(v: any): any + local l = common(v, "objects") + l.drawOrder = s(v.draworder) or "topdown" + l.color = Data.color(s(v.color)) + l.objects = {} + for _, o in list(v.objects) do + if type(o) == "table" then + table.insert(l.objects, object(o)) + end + end + return l +end + +layer = function(v: any, depth: number): (any, string?, boolean?) + if type(v) ~= "table" then + return nil, "a layer is not an object" + end + if depth > 100 then + return nil, "groups nested too deep" + end + local typ = TYPES[v.type] + if typ == "tiles" then + local l = common(v, "tiles") + l.width = n(v.width, 0) + l.height = n(v.height, 0) + l.encoding = s(v.encoding) + l.compression = s(v.compression) + if type(v.chunks) == "table" then + l.chunks = {} + for _, c in v.chunks do + if type(c) == "table" then + local g, err, uns = gids(c.data, l.encoding, l.compression) + if not g then + return nil, err, uns + end + table.insert(l.chunks, { x = n(c.x, 0), y = n(c.y, 0), width = n(c.width, 0), height = n(c.height, 0), data = g }) + end + end + elseif v.data ~= nil then + local g, err, uns = gids(v.data, l.encoding, l.compression) + if not g then + return nil, err, uns + end + l.data = g + end + return l + elseif typ == "objects" then + return objectGroup(v) + elseif typ == "image" then + local l = common(v, "image") + l.imageSource = s(v.image) + l.imageWidth = n(v.imagewidth) + l.imageHeight = n(v.imageheight) + l.transparentColor = Data.color(s(v.transparentcolor)) + l.repeatX = b(v.repeatx, false) + l.repeatY = b(v.repeaty, false) + return l + elseif typ == "group" then + local l = common(v, "group") + l.layers = {} + for _, c in list(v.layers) do + local sub, err, uns = layer(c, depth + 1) + if not sub then + return nil, err, uns + end + table.insert(l.layers, sub) + end + return l + end + return nil, "unknown layer type " .. tostring(v.type) +end + +function Tmj.tileset(v: any): any + local ts: any = { + firstGid = n(v.firstgid, 1), + source = s(v.source), + name = s(v.name) or "", + tileWidth = n(v.tilewidth, 0), + tileHeight = n(v.tileheight, 0), + spacing = n(v.spacing, 0), + margin = n(v.margin, 0), + count = n(v.tilecount, 0), + columns = n(v.columns, 0), + objectAlignment = s(v.objectalignment), + class = s(v.class) or "", + imageSource = s(v.image), + imageWidth = n(v.imagewidth), + imageHeight = n(v.imageheight), + transparentColor = Data.color(s(v.transparentcolor)), + } + withProps(ts, v) + if type(v.tileoffset) == "table" then + ts.tileOffset = { x = n(v.tileoffset.x, 0), y = n(v.tileoffset.y, 0) } + end + local tiles = {} + for _, t in list(v.tiles) do + if type(t) == "table" then + local tile: any = { id = n(t.id, 0), class = s(t.class) or s(t.type) or "", probability = n(t.probability) } + withProps(tile, t) + tile.imageSource = s(t.image) + tile.imageWidth = n(t.imagewidth) + tile.imageHeight = n(t.imageheight) + if type(t.animation) == "table" then + tile.animation = {} + for _, f in t.animation do + if type(f) == "table" then + table.insert(tile.animation, { tileId = n(f.tileid, 0), duration = n(f.duration, 0) }) + end + end + end + if type(t.objectgroup) == "table" then + tile.objectGroup = objectGroup(t.objectgroup) + end + table.insert(tiles, tile) + end + end + table.sort(tiles, function(x: any, y: any): boolean + return x.id < y.id + end) + ts.tiles = tiles + return ts +end + +function Tmj.read(v: any): (any, string?, boolean?) + if type(v) ~= "table" or (v.type ~= nil and v.type ~= "map") then + return nil, "not a Tiled map (type is not \"map\")" + end + local map: any = Types.TileMap.new(n(v.width, 0) :: number, n(v.height, 0) :: number, n(v.tilewidth, 0) :: number, n(v.tileheight, 0) :: number) + map.version = if type(v.version) == "number" then Data.num(v.version) else s(v.version) + map.tiledVersion = s(v.tiledversion) + map.orientation = s(v.orientation) or "orthogonal" + map.renderOrder = s(v.renderorder) or "right-down" + map.infinite = b(v.infinite, false) + map.nextLayerId = n(v.nextlayerid) + map.nextObjectId = n(v.nextobjectid) + map.backgroundColor = Data.color(s(v.backgroundcolor)) + map.hexSideLength = n(v.hexsidelength) + map.staggerAxis = s(v.staggeraxis) + map.staggerIndex = s(v.staggerindex) + map.class = s(v.class) or "" + map.parallaxOriginX = n(v.parallaxoriginx, 0) + map.parallaxOriginY = n(v.parallaxoriginy, 0) + withProps(map, v) + for _, ts in list(v.tilesets) do + if type(ts) == "table" then + table.insert(map.tilesets, Tmj.tileset(ts)) + end + end + for _, l in list(v.layers) do + local x, err, uns = layer(l, 0) + if not x then + return nil, err, uns + end + table.insert(map.layers, x) + end + return map, nil +end + +-- ------------------------------------------------------------------------------------------------ write +local function obj(pairs_: { { any } }): any + local o = Types.object() + for _, kv in pairs_ do + if kv[2] ~= nil then + Types.set(o, kv[1], kv[2]) + end + end + return o +end +local function nz(v: any, default: any): any + if v == nil or v == default then + return nil + end + return v +end +local function str(v: any): string? + if type(v) == "string" and v ~= "" then + return v + end + return nil +end + +local function propList(props: any, types: any): { any }? + if type(props) ~= "table" or next(props) == nil then + return nil + end + local out = {} + for _, k in Data.sortedKeys(props) do + local v = props[k] + local typ = Data.typeOf(v, if type(types) == "table" then types[k] else nil) + if typ == "class" and type(v) == "table" then + local members = Types.object() + if type(v.properties) == "table" then + for _, mk in Data.sortedKeys(v.properties) do + Types.set(members, mk, v.properties[mk]) + end + end + table.insert(out, obj({ { "name", k }, { "propertytype", v.class or "" }, { "type", "class" }, { "value", members } })) + else + table.insert(out, obj({ { "name", k }, { "type", typ }, { "value", v } })) + end + end + return out +end + +local function writeObject(o: any): any + local t: any = nil + if o.shape == "text" and type(o.text) == "table" then + local x = o.text + t = obj({ + { "bold", nz(x.bold, false) }, + { "color", nz(x.color, "#000000") }, + { "fontfamily", nz(x.fontFamily, "sans-serif") }, + { "halign", nz(x.halign, "left") }, + { "italic", nz(x.italic, false) }, + { "kerning", nz(x.kerning, true) }, + { "pixelsize", nz(x.pixelSize, 16) }, + { "strikeout", nz(x.strikeout, false) }, + { "text", tostring(x.text or "") }, + { "underline", nz(x.underline, false) }, + { "valign", nz(x.valign, "top") }, + { "wrap", nz(x.wrap, false) }, + }) + end + local pts: any = nil + if (o.shape == "polygon" or o.shape == "polyline") and type(o.points) == "table" then + pts = {} + for _, p in o.points do + table.insert(pts, obj({ { "x", tonumber(p[1]) or 0 }, { "y", tonumber(p[2]) or 0 } })) + end + end + return obj({ + { "ellipse", if o.shape == "ellipse" then true else nil }, + { "gid", o.gid }, + { "height", o.height or 0 }, + { "id", o.id }, + { "name", o.name or "" }, + { "point", if o.shape == "point" then true else nil }, + { "polygon", if o.shape == "polygon" then pts else nil }, + { "polyline", if o.shape == "polyline" then pts else nil }, + { "properties", propList(o.properties, o.propertyTypes) }, + { "rotation", o.rotation or 0 }, + { "template", o.template }, + { "text", t }, + { "type", o.class or "" }, + { "visible", o.visible ~= false }, + { "width", o.width or 0 }, + { "x", o.x or 0 }, + { "y", o.y or 0 }, + }) +end + +type WriteOptions = { encoding: string?, compression: string?, level: number? } + +local function writeObjectGroup(l: any): any + local objs = {} + for _, o in (if type(l.objects) == "table" then l.objects else {}) do + table.insert(objs, writeObject(o)) + end + return objs +end + +local writeLayer: (l: any, o: WriteOptions) -> (any, string?) + +writeLayer = function(l: any, o: WriteOptions): (any, string?) + local t = l.type + local fields: { { any } } = {} + local function add(k: string, v: any) + table.insert(fields, { k, v }) + end + if t == "tiles" then + local enc = o.encoding or l.encoding + if enc ~= "base64" then + enc = nil + end + local comp = if enc then (o.compression or (if o.encoding then nil else l.compression)) else nil + local function payload(g: { number }): (any, string?) + if enc == "base64" then + return Data.toBase64(g, comp, o.level) + end + return g, nil + end + if type(l.chunks) == "table" then + local chunks = {} + for _, c in l.chunks do + local d, err = payload(c.data or {}) + if d == nil then + return nil, err + end + table.insert(chunks, obj({ { "data", d }, { "height", c.height or 0 }, { "width", c.width or 0 }, { "x", c.x or 0 }, { "y", c.y or 0 } })) + end + add("chunks", chunks) + local sx, sy = math.huge, math.huge + for _, c in l.chunks do + sx, sy = math.min(sx, c.x or 0), math.min(sy, c.y or 0) + end + if #l.chunks > 0 then + add("startx", sx) + add("starty", sy) + end + elseif type(l.data) == "table" then + local d, err = payload(l.data) + if d == nil then + return nil, err + end + add("data", d) + end + add("compression", comp) + add("encoding", enc) + add("height", l.height or 0) + elseif t == "objects" then + add("color", l.color) + add("draworder", l.drawOrder or "topdown") + elseif t == "image" then + add("image", l.imageSource or "") + add("imageheight", l.imageHeight) + add("imagewidth", l.imageWidth) + elseif t == "group" then + local kids = {} + for _, c in (if type(l.layers) == "table" then l.layers else {}) do + local x, err = writeLayer(c, o) + if x == nil then + return nil, err + end + table.insert(kids, x) + end + add("layers", kids) + else + return nil, "unknown layer type " .. tostring(t) + end + add("class", str(l.class)) + add("id", l.id) + add("locked", nz(l.locked, false)) + add("name", l.name or "") + if t == "objects" then + add("objects", writeObjectGroup(l)) + end + add("offsetx", nz(l.offsetX, 0)) + add("offsety", nz(l.offsetY, 0)) + add("opacity", l.opacity or 1) + add("parallaxx", nz(l.parallaxX, 1)) + add("parallaxy", nz(l.parallaxY, 1)) + add("properties", propList(l.properties, l.propertyTypes)) + if t == "image" then + add("repeatx", nz(l.repeatX, false)) + add("repeaty", nz(l.repeatY, false)) + end + add("tintcolor", l.tintColor) + if t == "image" then + add("transparentcolor", l.transparentColor) + end + add("type", if t == "tiles" then "tilelayer" elseif t == "objects" then "objectgroup" elseif t == "image" then "imagelayer" else "group") + add("visible", l.visible ~= false) + if t == "tiles" then + add("width", l.width or 0) + end + add("x", l.x or 0) + add("y", l.y or 0) + return obj(fields), nil +end + +function Tmj.tilesetValue(ts: any, inMap: boolean): any + if inMap and type(ts.source) == "string" then + return obj({ { "firstgid", ts.firstGid or 1 }, { "source", ts.source } }) + end + local tiles: any = nil + if type(ts.tiles) == "table" and #ts.tiles > 0 then + tiles = {} + for _, tile in ts.tiles do + local anim: any = nil + if type(tile.animation) == "table" then + anim = {} + for _, f in tile.animation do + table.insert(anim, obj({ { "duration", f.duration or 0 }, { "tileid", f.tileId or 0 } })) + end + end + local og: any = nil + if type(tile.objectGroup) == "table" then + og = writeLayer(tile.objectGroup, {}) + end + table.insert(tiles, obj({ + { "animation", anim }, + { "id", tile.id or 0 }, + { "image", tile.imageSource }, + { "imageheight", tile.imageHeight }, + { "imagewidth", tile.imageWidth }, + { "objectgroup", og }, + { "probability", tile.probability }, + { "properties", propList(tile.properties, tile.propertyTypes) }, + { "type", str(tile.class) }, + })) + end + end + return obj({ + { "class", str(ts.class) }, + { "columns", ts.columns or 0 }, + { "firstgid", if inMap then ts.firstGid or 1 else nil }, + { "image", ts.imageSource }, + { "imageheight", ts.imageHeight }, + { "imagewidth", ts.imageWidth }, + { "margin", ts.margin or 0 }, + { "name", ts.name or "" }, + { "objectalignment", ts.objectAlignment }, + { "properties", propList(ts.properties, ts.propertyTypes) }, + { "spacing", ts.spacing or 0 }, + { "tilecount", ts.count or 0 }, + { "tileheight", ts.tileHeight or 0 }, + { "tileoffset", if type(ts.tileOffset) == "table" then obj({ { "x", ts.tileOffset.x or 0 }, { "y", ts.tileOffset.y or 0 } }) else nil }, + { "tiles", tiles }, + { "tilewidth", ts.tileWidth or 0 }, + { "transparentcolor", ts.transparentColor }, + { "type", if inMap then nil else "tileset" }, + }) +end + +function Tmj.write(map: any, o: WriteOptions): (any, string?) + local layers = {} + for _, l in map.layers do + local x, err = writeLayer(l, o) + if x == nil then + return nil, err + end + table.insert(layers, x) + end + local tilesets = {} + for _, ts in map.tilesets do + table.insert(tilesets, Tmj.tilesetValue(ts, true)) + end + return obj({ + { "backgroundcolor", map.backgroundColor }, + { "class", str(map.class) }, + { "compressionlevel", -1 }, + { "height", map.height }, + { "hexsidelength", map.hexSideLength }, + { "infinite", map.infinite == true }, + { "layers", layers }, + { "nextlayerid", map.nextLayerId }, + { "nextobjectid", map.nextObjectId }, + { "orientation", map.orientation or "orthogonal" }, + { "parallaxoriginx", nz(map.parallaxOriginX, 0) }, + { "parallaxoriginy", nz(map.parallaxOriginY, 0) }, + { "properties", propList(map.properties, map.propertyTypes) }, + { "renderorder", map.renderOrder or "right-down" }, + { "staggeraxis", map.staggerAxis }, + { "staggerindex", map.staggerIndex }, + { "tiledversion", map.tiledVersion }, + { "tileheight", map.tileHeight }, + { "tilesets", tilesets }, + { "tilewidth", map.tileWidth }, + { "type", "map" }, + { "version", map.version or "1.10" }, + { "width", map.width }, + }), nil +end + +return Tmj +end +__FILES["vector/tiled/Tmx"] = function() + +-- vector/tiled/Tmx: TMX / TSX (TMX map format, Tiled 1.12 docs) <-> a Types.TileMap. +local Xml = __include("codecs/text/Xml") +local Types = __include("Types") +local Data = __include("vector/tiled/Data") + +local Tmx = {} + +type Node = Types.XmlNode + +local function a(n: Node, k: string): string? + return (n.attrs :: any)[k] +end +local function num(n: Node, k: string, default: number?): number? + local v = a(n, k) + if v == nil then + return default + end + return tonumber(v) or default +end +local function flag(n: Node, k: string, default: boolean): boolean + local v = a(n, k) + if v == nil then + return default + end + return v == "1" or v == "true" +end + +-- ------------------------------------------------------------------------------------------------ read +local function properties(n: Node?): ({ [string]: any }, { [string]: string }?) + local props: { [string]: any } = {} + local types: { [string]: string }? = nil + if n == nil then + return props, nil + end + for _, p in Xml.children(n, "property") do + local name = a(p, "name") + if name then + local typ = a(p, "type") or "string" + local v: any + if typ == "class" then + local inner, innerTypes = properties(Xml.child(p, "properties")) + v = { class = a(p, "propertytype") or "", properties = inner, propertyTypes = innerTypes } + else + local text = a(p, "value") + if text == nil then + text = Xml.text(p) -- multi-line strings + end + v = Data.value(typ, text :: string) + end + props[name] = v + if typ ~= "string" then + types = types or {} + ;(types :: any)[name] = typ + end + end + end + return props, types +end + +local function withProps(t: any, n: Node) + local props, types = properties(Xml.child(n, "properties")) + t.properties = props + if types then + t.propertyTypes = types + end +end + +local function gids(d: Node, encoding: string?, compression: string?): ({ number }?, string?, boolean?) + if encoding == "csv" then + return Data.csv(Xml.text(d)) + elseif encoding == "base64" then + return Data.base64(Xml.text(d), compression) + elseif encoding == nil or encoding == "" then + local out = {} + for _, t in Xml.children(d, "tile") do + table.insert(out, num(t, "gid", 0) :: number) + end + return out, nil, nil + end + return nil, "unknown encoding " .. encoding, true +end + +local function object(o: Node): any + local obj: any = { + id = num(o, "id"), + name = a(o, "name") or "", + class = a(o, "class") or a(o, "type") or "", + x = num(o, "x", 0), + y = num(o, "y", 0), + width = num(o, "width", 0), + height = num(o, "height", 0), + rotation = num(o, "rotation", 0), + gid = num(o, "gid"), + visible = flag(o, "visible", true), + template = a(o, "template"), + shape = "rectangle", + } + withProps(obj, o) + if Xml.child(o, "ellipse") then + obj.shape = "ellipse" + elseif Xml.child(o, "point") then + obj.shape = "point" + end + for _, kind in { "polygon", "polyline" } do + local p = Xml.child(o, kind) + if p then + obj.shape = kind + local pts = {} + for x, y in string.gmatch(a(p, "points") or "", "([^,%s]+),([^,%s]+)") do + table.insert(pts, { tonumber(x) or 0, tonumber(y) or 0 }) + end + obj.points = pts + end + end + local t = Xml.child(o, "text") + if t then + obj.shape = "text" + obj.text = { + text = Xml.text(t), + fontFamily = a(t, "fontfamily") or "sans-serif", + pixelSize = num(t, "pixelsize", 16), + wrap = flag(t, "wrap", false), + color = Data.color(a(t, "color")) or "#000000", + bold = flag(t, "bold", false), + italic = flag(t, "italic", false), + underline = flag(t, "underline", false), + strikeout = flag(t, "strikeout", false), + kerning = flag(t, "kerning", true), + halign = a(t, "halign") or "left", + valign = a(t, "valign") or "top", + } + end + return obj +end + +local layer: (n: Node) -> (any, string?, boolean?) + +local function common(n: Node, typ: string): any + local l: any = { + type = typ, + id = num(n, "id"), + name = a(n, "name") or "", + visible = flag(n, "visible", true), + opacity = num(n, "opacity", 1), + x = num(n, "x", 0), + y = num(n, "y", 0), + offsetX = num(n, "offsetx", 0), + offsetY = num(n, "offsety", 0), + parallaxX = num(n, "parallaxx", 1), + parallaxY = num(n, "parallaxy", 1), + tintColor = Data.color(a(n, "tintcolor")), + class = a(n, "class") or "", + locked = flag(n, "locked", false), + } + withProps(l, n) + return l +end + +local function objectGroup(n: Node): any + local l = common(n, "objects") + l.drawOrder = a(n, "draworder") or "topdown" + l.color = Data.color(a(n, "color")) + l.objects = {} + for _, o in Xml.children(n, "object") do + table.insert(l.objects, object(o)) + end + return l +end + +layer = function(n: Node): (any, string?, boolean?) + local name = n.name + if name == "layer" then + local l = common(n, "tiles") + l.width = num(n, "width", 0) + l.height = num(n, "height", 0) + local d = Xml.child(n, "data") + if d then + local enc, comp = a(d, "encoding"), a(d, "compression") + l.encoding, l.compression = enc, comp + local chunks = Xml.children(d, "chunk") + if #chunks > 0 then + l.chunks = {} + for _, c in chunks do + local g, err, uns = gids(c, enc, comp) + if not g then + return nil, err, uns + end + table.insert(l.chunks, { x = num(c, "x", 0), y = num(c, "y", 0), width = num(c, "width", 0), height = num(c, "height", 0), data = g }) + end + else + local g, err, uns = gids(d, enc, comp) + if not g then + return nil, err, uns + end + l.data = g + end + end + return l + elseif name == "objectgroup" then + return objectGroup(n) + elseif name == "imagelayer" then + local l = common(n, "image") + l.repeatX = flag(n, "repeatx", false) + l.repeatY = flag(n, "repeaty", false) + local img = Xml.child(n, "image") + if img then + l.imageSource = a(img, "source") + l.imageWidth = num(img, "width") + l.imageHeight = num(img, "height") + l.transparentColor = Data.color(a(img, "trans")) + end + return l + elseif name == "group" then + local l = common(n, "group") + l.layers = {} + for _, c in n.children do + if type(c) == "table" then + local sub, err, uns = layer(c) + if err then + return nil, err, uns + end + if sub then + table.insert(l.layers, sub) + end + end + end + return l + end + return nil +end + +function Tmx.tileset(n: Node): any + local ts: any = { + firstGid = num(n, "firstgid", 1), + source = a(n, "source"), + name = a(n, "name") or "", + tileWidth = num(n, "tilewidth", 0), + tileHeight = num(n, "tileheight", 0), + spacing = num(n, "spacing", 0), + margin = num(n, "margin", 0), + count = num(n, "tilecount", 0), + columns = num(n, "columns", 0), + objectAlignment = a(n, "objectalignment"), + class = a(n, "class") or "", + } + withProps(ts, n) + local off = Xml.child(n, "tileoffset") + if off then + ts.tileOffset = { x = num(off, "x", 0), y = num(off, "y", 0) } + end + local img = Xml.child(n, "image") + if img then + ts.imageSource = a(img, "source") + ts.imageWidth = num(img, "width") + ts.imageHeight = num(img, "height") + ts.transparentColor = Data.color(a(img, "trans")) + end + local tiles = {} + for _, t in Xml.children(n, "tile") do + local tile: any = { id = num(t, "id", 0), class = a(t, "class") or a(t, "type") or "", probability = num(t, "probability") } + withProps(tile, t) + local ti = Xml.child(t, "image") + if ti then + tile.imageSource = a(ti, "source") + tile.imageWidth = num(ti, "width") + tile.imageHeight = num(ti, "height") + end + local anim = Xml.child(t, "animation") + if anim then + tile.animation = {} + for _, f in Xml.children(anim, "frame") do + table.insert(tile.animation, { tileId = num(f, "tileid", 0), duration = num(f, "duration", 0) }) + end + end + local og = Xml.child(t, "objectgroup") + if og then + tile.objectGroup = objectGroup(og) + end + table.insert(tiles, tile) + end + ts.tiles = tiles + return ts +end + +function Tmx.read(root: Node): (any, string?, boolean?) + if root.name ~= "map" then + return nil, "the root element is <" .. root.name .. ">, not <map>" + end + local map: any = Types.TileMap.new(num(root, "width", 0) :: number, num(root, "height", 0) :: number, num(root, "tilewidth", 0) :: number, num(root, "tileheight", 0) :: number) + map.version = a(root, "version") + map.tiledVersion = a(root, "tiledversion") + map.orientation = a(root, "orientation") or "orthogonal" + map.renderOrder = a(root, "renderorder") or "right-down" + map.infinite = flag(root, "infinite", false) + map.nextLayerId = num(root, "nextlayerid") + map.nextObjectId = num(root, "nextobjectid") + map.backgroundColor = Data.color(a(root, "backgroundcolor")) + map.hexSideLength = num(root, "hexsidelength") + map.staggerAxis = a(root, "staggeraxis") + map.staggerIndex = a(root, "staggerindex") + map.class = a(root, "class") or "" + map.parallaxOriginX = num(root, "parallaxoriginx", 0) + map.parallaxOriginY = num(root, "parallaxoriginy", 0) + withProps(map, root) + for _, c in root.children do + if type(c) == "table" then + if c.name == "tileset" then + table.insert(map.tilesets, Tmx.tileset(c)) + else + local l, err, uns = layer(c) + if err then + return nil, err, uns + end + if l then + table.insert(map.layers, l) + end + end + end + end + return map, nil +end + +-- ------------------------------------------------------------------------------------------------ write +type Attrs = { [string]: string } + +local function el(name: string, attrs: { { any } }, children: { any }?): Node + local o = Types.object() + for _, kv in attrs do + if kv[2] ~= nil then + local v = kv[2] + Types.set(o, kv[1], if type(v) == "number" then Data.num(v) elseif type(v) == "boolean" then (if v then "1" else "0") else tostring(v)) + end + end + return Xml.element(name, o :: any, children) +end + +local function nz(v: any, default: any): any + if v == nil or v == default then + return nil + end + return v +end +local function str(v: any): string? + if type(v) == "string" and v ~= "" then + return v + end + return nil +end + +local function propsNode(props: any, types: any): Node? + if type(props) ~= "table" or next(props) == nil then + return nil + end + local list = {} + for _, k in Data.sortedKeys(props) do + local v = props[k] + local typ = Data.typeOf(v, if type(types) == "table" then types[k] else nil) + if typ == "class" and type(v) == "table" then + local inner = propsNode(v.properties, v.propertyTypes) + table.insert(list, el("property", { { "name", k }, { "type", "class" }, { "propertytype", v.class or "" } }, if inner then { inner } else nil)) + else + local text = if type(v) == "boolean" then (if v then "true" else "false") elseif type(v) == "number" then Data.num(v) else tostring(v) + if string.find(text, "\n", 1, true) then + table.insert(list, el("property", { { "name", k }, { "type", if typ ~= "string" then typ else nil } }, { text })) + else + table.insert(list, el("property", { { "name", k }, { "type", if typ ~= "string" then typ else nil }, { "value", text } })) + end + end + end + return el("properties", {}, list) +end + +local function addProps(children: { any }, t: any) + local p = propsNode(t.properties, t.propertyTypes) + if p then + table.insert(children, p) + end +end + +local function writeObject(o: any): Node + local kids = {} + addProps(kids, o) + local shape = o.shape + if shape == "ellipse" then + table.insert(kids, el("ellipse", {})) + elseif shape == "point" then + table.insert(kids, el("point", {})) + elseif (shape == "polygon" or shape == "polyline") and type(o.points) == "table" then + local pts = {} + for _, p in o.points do + table.insert(pts, Data.num(tonumber(p[1]) or 0) .. "," .. Data.num(tonumber(p[2]) or 0)) + end + table.insert(kids, el(shape, { { "points", table.concat(pts, " ") } })) + elseif shape == "text" and type(o.text) == "table" then + local t = o.text + table.insert(kids, el("text", { + { "fontfamily", nz(t.fontFamily, "sans-serif") }, + { "pixelsize", nz(t.pixelSize, 16) }, + { "wrap", nz(t.wrap, false) }, + { "color", nz(t.color, "#000000") }, + { "bold", nz(t.bold, false) }, + { "italic", nz(t.italic, false) }, + { "underline", nz(t.underline, false) }, + { "strikeout", nz(t.strikeout, false) }, + { "kerning", nz(t.kerning, true) }, + { "halign", nz(t.halign, "left") }, + { "valign", nz(t.valign, "top") }, + }, { tostring(t.text or "") })) + end + return el("object", { + { "id", o.id }, + { "name", str(o.name) }, + { "type", str(o.class) }, + { "gid", o.gid }, + { "x", o.x or 0 }, + { "y", o.y or 0 }, + { "width", nz(o.width, 0) }, + { "height", nz(o.height, 0) }, + { "rotation", nz(o.rotation, 0) }, + { "visible", nz(o.visible, true) }, + { "template", o.template }, + }, kids) +end + +local function commonAttrs(l: any, extra: { { any } }): { { any } } + local out: { { any } } = { { "id", l.id }, { "name", str(l.name) or "" }, { "class", str(l.class) } } + table.move(extra, 1, #extra, #out + 1, out) + local tail = { + { "visible", nz(l.visible, true) }, + { "locked", nz(l.locked, false) }, + { "opacity", nz(l.opacity, 1) }, + { "tintcolor", l.tintColor }, + { "offsetx", nz(l.offsetX, 0) }, + { "offsety", nz(l.offsetY, 0) }, + { "parallaxx", nz(l.parallaxX, 1) }, + { "parallaxy", nz(l.parallaxY, 1) }, + } + table.move(tail, 1, #tail, #out + 1, out) + return out +end + +local function writeObjectGroup(l: any, tag: string?): Node + local kids = {} + addProps(kids, l) + for _, o in (if type(l.objects) == "table" then l.objects else {}) do + table.insert(kids, writeObject(o)) + end + return el(tag or "objectgroup", commonAttrs(l, { { "color", l.color }, { "draworder", nz(l.drawOrder, "topdown") } }), kids) +end + +type WriteOptions = { encoding: string?, compression: string?, level: number? } + +local writeLayer: (l: any, o: WriteOptions) -> (Node?, string?) + +writeLayer = function(l: any, o: WriteOptions): (Node?, string?) + local t = l.type + if t == "tiles" then + local kids = {} + addProps(kids, l) + local enc = o.encoding or l.encoding or "csv" + local comp = if o.encoding then o.compression else (o.compression or l.compression) + if enc ~= "base64" then + comp = nil + end + local function payload(g: { number }, width: number): (string?, string?) + if enc == "csv" then + return Data.csvText(g, width), nil + end + local s, err = Data.toBase64(g, comp, o.level) + if not s then + return nil, err + end + return "\n " .. s .. "\n ", nil + end + local dataKids = {} + if type(l.chunks) == "table" then + for _, c in l.chunks do + local kids: { any } = {} + if enc == "xml" then + for _, g in (c.data or {}) do + table.insert(kids, el("tile", { { "gid", if g ~= 0 then g else nil } })) + end + else + local s, err = payload(c.data or {}, c.width or 0) + if not s then + return nil, err + end + kids = { s } + end + table.insert(dataKids, el("chunk", { { "x", c.x or 0 }, { "y", c.y or 0 }, { "width", c.width or 0 }, { "height", c.height or 0 } }, kids)) + end + elseif type(l.data) == "table" and enc == "xml" then + for _, g in l.data do + table.insert(dataKids, el("tile", { { "gid", if g ~= 0 then g else nil } })) + end + elseif type(l.data) == "table" then + local s, err = payload(l.data, l.width or 0) + if not s then + return nil, err + end + dataKids = { s } + end + table.insert(kids, el("data", { { "encoding", if enc == "xml" then nil else enc }, { "compression", comp } }, dataKids)) + return el("layer", commonAttrs(l, { { "x", nz(l.x, 0) }, { "y", nz(l.y, 0) }, { "width", l.width or 0 }, { "height", l.height or 0 } }), kids), nil + elseif t == "objects" then + return writeObjectGroup(l), nil + elseif t == "image" then + local kids = {} + addProps(kids, l) + if l.imageSource then + table.insert(kids, el("image", { { "source", l.imageSource }, { "trans", l.transparentColor }, { "width", l.imageWidth }, { "height", l.imageHeight } })) + end + return el("imagelayer", commonAttrs(l, { { "repeatx", nz(l.repeatX, false) }, { "repeaty", nz(l.repeatY, false) } }), kids), nil + elseif t == "group" then + local kids = {} + addProps(kids, l) + for _, c in (if type(l.layers) == "table" then l.layers else {}) do + local n, err = writeLayer(c, o) + if not n then + return nil, err + end + table.insert(kids, n) + end + return el("group", commonAttrs(l, {}), kids), nil + end + return nil, "unknown layer type " .. tostring(t) +end + +function Tmx.tilesetNode(ts: any, inMap: boolean): Node + if inMap and type(ts.source) == "string" then + return el("tileset", { { "firstgid", ts.firstGid or 1 }, { "source", ts.source } }) + end + local kids = {} + if type(ts.tileOffset) == "table" then + table.insert(kids, el("tileoffset", { { "x", ts.tileOffset.x or 0 }, { "y", ts.tileOffset.y or 0 } })) + end + addProps(kids, ts) + if ts.imageSource then + table.insert(kids, el("image", { { "source", ts.imageSource }, { "trans", ts.transparentColor }, { "width", ts.imageWidth }, { "height", ts.imageHeight } })) + end + for _, tile in (if type(ts.tiles) == "table" then ts.tiles else {}) do + local tk = {} + addProps(tk, tile) + if tile.imageSource then + table.insert(tk, el("image", { { "source", tile.imageSource }, { "width", tile.imageWidth }, { "height", tile.imageHeight } })) + end + if type(tile.objectGroup) == "table" then + table.insert(tk, writeObjectGroup(tile.objectGroup)) + end + if type(tile.animation) == "table" then + local frames = {} + for _, f in tile.animation do + table.insert(frames, el("frame", { { "tileid", f.tileId or 0 }, { "duration", f.duration or 0 } })) + end + table.insert(tk, el("animation", {}, frames)) + end + table.insert(kids, el("tile", { { "id", tile.id or 0 }, { "type", str(tile.class) }, { "probability", tile.probability } }, tk)) + end + return el("tileset", { + { "firstgid", if inMap then ts.firstGid or 1 else nil }, + { "name", ts.name or "" }, + { "class", str(ts.class) }, + { "tilewidth", ts.tileWidth or 0 }, + { "tileheight", ts.tileHeight or 0 }, + { "spacing", nz(ts.spacing, 0) }, + { "margin", nz(ts.margin, 0) }, + { "tilecount", ts.count or 0 }, + { "columns", ts.columns or 0 }, + { "objectalignment", ts.objectAlignment }, + }, kids) +end + +function Tmx.write(map: any, o: WriteOptions): (Node?, string?) + local kids = {} + addProps(kids, map) + for _, ts in map.tilesets do + table.insert(kids, Tmx.tilesetNode(ts, true)) + end + for _, l in map.layers do + local n, err = writeLayer(l, o) + if not n then + return nil, err + end + table.insert(kids, n) + end + local root = el("map", { + { "version", map.version or "1.10" }, + { "tiledversion", map.tiledVersion }, + { "class", str(map.class) }, + { "orientation", map.orientation or "orthogonal" }, + { "renderorder", map.renderOrder or "right-down" }, + { "width", map.width }, + { "height", map.height }, + { "tilewidth", map.tileWidth }, + { "tileheight", map.tileHeight }, + { "hexsidelength", map.hexSideLength }, + { "staggeraxis", map.staggerAxis }, + { "staggerindex", map.staggerIndex }, + { "parallaxoriginx", nz(map.parallaxOriginX, 0) }, + { "parallaxoriginy", nz(map.parallaxOriginY, 0) }, + { "backgroundcolor", map.backgroundColor }, + { "infinite", map.infinite == true }, + { "nextlayerid", map.nextLayerId }, + { "nextobjectid", map.nextObjectId }, + }, kids) + return Xml.document(root, { version = "1.0", encoding = "UTF-8" }), nil +end + +return Tmx +end +end + + + + + + video + --!optimize 2 +--!nocheck +-- rosetta chunk video (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 16 modules (1 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) +__FILES["video/avi"] = function() + +-- video/avi: AVI (RIFF AVI 1.0, OpenDML 1.02: super / standard indexes, idx1, AVIX pieces). Reads video through the +-- codecs/video/Video registry by FourCC and audio through opts.openAudio; dropped frames keep their slot. Writes +-- MJPEG + PCM s16 (AVI 1.0, idx1, odml). Not supported: writing over 1 GB, palette changes (##pc), text streams. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Avi = __include("containers/Avi") +local Demux = __include("containers/Demux") +local Video = __include("codecs/video/Video") +local Source = __include("codecs/video/Video/Source") + +-- ------------------------------------------------------------------------------------------------ contract +local AviFormat = { + name = "avi", + category = "video", + extensions = { "avi" }, + mime = { "video/x-msvideo", "video/avi" }, + 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", "mpeg2", "rawvideo" }, audio = true, odml = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type OpenOptions = { + rgba: boolean?, -- default false: yuv420p; BI_RGB gives rgba8 + track: number?, -- stream index + 1 + audio: boolean?, + maxPixels: number?, + openAudio: any?, -- set by the api +} +type EncodeOptions = { + quality: number?, -- 1..100, default 90 + reencode: boolean?, + audio: boolean?, -- default: PCM s16 from the source's audio + video: boolean?, + maxFps: number?, -- default 100 +} + +-- ------------------------------------------------------------------------------------------------ constants +-- WAVEFORMATEX wFormatTag -> codec id +local AUDIO_TAGS: { [number]: string } = { + [0x0001] = "pcm", + [0x0002] = "adpcm_ms", + [0x0003] = "pcm_f", + [0x0006] = "pcm_alaw", + [0x0007] = "pcm_mulaw", + [0x0011] = "adpcm_ima_wav", + [0x0050] = "mp2", + [0x0055] = "mp3", + [0x00FF] = "aac", + [0x1610] = "aac", + [0x706D] = "aac", + [0x2000] = "ac3", + [0x2001] = "dts", + [0xF1AC] = "flac", +} + +-- ------------------------------------------------------------------------------------------------ sniff +function AviFormat.sniff(r: Bytes.Reader): number + if r:peek(4) == "RIFF" and r:peek(4, 8) == "AVI " then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function videoTrack(s: Avi.Stream, id: number): Types.Track + local f = s.strf + local t: any = { + id = id, + kind = "video", + codec = "", + codecTag = s.handler, + timescale = if s.scale > 0 then s.rate / s.scale else 25, + frameRate = if s.scale > 0 then s.rate / s.scale else 0, + default = true, + name = s.name, + frames = s.length, + } + if buffer.len(f) >= 40 then + local w = buffer.readi32(f, 4) + local h = buffer.readi32(f, 8) + local bits = buffer.readu16(f, 14) + local comp = buffer.readstring(f, 16, 4) + t.width = math.abs(w) + t.height = math.abs(h) + t.codecTag = comp + t.bitsPerPixel = bits + if comp == "\0\0\0\0" or comp == "DIB " or comp == "RGB " then + t.codec = "rawvideo" + t.pixelFormat = if bits == 32 then "bgra" else "bgr24" + t.flip = h > 0 + t.stride = ((math.abs(w) * bits + 31) // 32) * 4 + if bits ~= 24 and bits ~= 32 then + t.codec = "rawvideo_" .. bits + end + else + t.codec = Video.fromFourcc(comp) or Video.fromFourcc(s.handler) or string.lower((string.gsub(comp, "%z", ""))) + if comp == "YV12" then + t.pixelFormat = "yv12" + elseif t.codec == "rawvideo" then + t.pixelFormat = "yuv420p" + end + end + local bi = Avi.bitmapInfo(f) + if bi and bi.palette then + t.palette = bi.palette -- 1..8-bit codecs (Microsoft Video 1, Cinepak, QuickTime RLE / SMC in AVI, ...) + end + local size = buffer.readu32(f, 0) + if size > 40 and buffer.len(f) > 40 then + local c = buffer.create(buffer.len(f) - 40) + buffer.copy(c, 0, f, 40) + t.config = c + end + else + t.codec = Video.fromFourcc(s.handler) or string.lower(s.handler) + local fr = s.frame + t.width, t.height = fr[3] - fr[1], fr[4] - fr[2] + end + return t +end + +local function audioTrack(s: Avi.Stream, id: number): Types.Track + local f = s.strf + local t: any = { + id = id, + kind = "audio", + codec = "unknown", + codecTag = s.handler, + timescale = if s.scale > 0 then s.rate / s.scale else 1, + default = true, + name = s.name, + waveFormat = f, + } + if buffer.len(f) >= 16 then + local tag = buffer.readu16(f, 0) + t.channels = buffer.readu16(f, 2) + t.sampleRate = buffer.readu32(f, 4) + t.blockAlign = buffer.readu16(f, 12) + local bits = buffer.readu16(f, 14) + t.bitsPerSample = bits + if tag == 0xFFFE and buffer.len(f) >= 26 then + tag = buffer.readu16(f, 24) -- WAVE_FORMAT_EXTENSIBLE: the sub-format GUID's tag + end + t.formatTag = tag + local c = AUDIO_TAGS[tag] or string.format("wav_0x%04x", tag) + if c == "pcm" then + c = if bits == 8 then "pcm_u8" else "pcm_s" .. bits .. "le" + elseif c == "pcm_f" then + c = "pcm_f" .. bits .. "le" + end + t.codec = c + if buffer.len(f) >= 18 then + local cb = buffer.readu16(f, 16) + if cb > 0 and 18 + cb <= buffer.len(f) and c ~= "mp3" then + local cfg = buffer.create(cb) + buffer.copy(cfg, 0, f, 18, cb) + t.config = cfg + end + end + end + return t +end + +function AviFormat.demux(r: Bytes.Reader, _opts: OpenOptions?): (any, Err.Err?) + local ok, file, err = pcall(Avi.read, r.buf, r.base, r.limit) + if not ok then + return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(file)) + end + if not file then + return nil, err + end + local tracks: { Types.Track } = {} + local streams: { { any } } = {} + for i, s in file.streams do + local t: Types.Track? = nil + if s.type == "vids" then + t = videoTrack(s, i) + elseif s.type == "auds" then + t = audioTrack(s, i) + elseif s.type == "txts" then + t = { id = i, kind = "subtitle", codec = "text", timescale = if s.scale > 0 then s.rate / s.scale else 1 } + end + if t then + table.insert(tracks, t) + table.insert(streams, { s, t }) + end + end + local meta = { info = file.info, index = file.index, odml = file.odml ~= nil } + local dmx = Demux.new("avi", tracks, r.buf, meta) + local items: { { number } } = {} + for k, st in streams do + local s: Avi.Stream, t: any = st[1], st[2] + local tick = s.start + for _, c in s.chunks do + local dur = if s.sampleSize > 0 then c.size / s.sampleSize else 1 + if t.kind == "audio" and s.sampleSize == 0 and (t.blockAlign or 0) > 0 and t.codec:sub(1, 3) == "pcm" then + dur = c.size / t.blockAlign + end + if c.size > 0 then + table.insert(items, { c.offset, k, tick, dur, if c.key then 1 else 0, c.size }) + tick += dur + elseif t.kind == "video" then + tick += 1 -- an empty video chunk: a dropped frame keeps its slot (empty audio chunks are padding) + end + end + end + table.sort(items, function(a: { number }, b: { number }): boolean + return a[1] < b[1] + end) + for _, it in items do + local t: any = streams[it[2]][2] + dmx:add(t.id, it[3], nil, it[4], it[5] == 1 or t.kind ~= "video" or t.codec == "mjpeg" or t.codec == "rawvideo", it[1], it[6]) + end + dmx:finish() + return dmx, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function AviFormat.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: any = table.clone(opts or {}) + o.quality = o.quality or 90 + local streams, err = Source.streams(value, o, { + video = { copy = { mjpeg = true }, encode = "mjpeg" }, + audio = { copy = { pcm_s16le = true, pcm_u8 = true }, pcm = true }, + }) + if not streams then + return nil, err + end + local wstreams: { Avi.WStream } = {} + local width, height, usPerFrame = 0, 0, 0 + local frameDur = 0 + for _, s in streams do + if s.kind == "video" then + -- a constant frame rate: the shortest frame duration (variable delays repeat frames) + local num, den, packets = Source.constantRate(s, o.maxFps) + s.packets = packets + frameDur = den / num + width, height = s.width or 0, s.height or 0 + usPerFrame = 1e6 * frameDur + local bih = Bytes.writer(40) + bih:u32le(40) + bih:u32le(width) + bih:u32le(height) + bih:u16le(1) + bih:u16le(24) + bih:string("MJPG") + bih:u32le(width * height * 3) + bih:u32le(0) + bih:u32le(0) + bih:u32le(0) + bih:u32le(0) + table.insert(wstreams, { type = "vids", handler = "MJPG", scale = den, rate = num, sampleSize = 0, strf = bih:finish(), width = width, height = height, ckid = "dc" }) + else + local ch = s.channels or 1 + local bits = if s.codec == "pcm_u8" then 8 else 16 + local align = ch * bits // 8 + local rate = math.floor((s.sampleRate or 44100) + 0.5) + local wf = Bytes.writer(18) + wf:u16le(1) + wf:u16le(ch) + wf:u32le(rate) + wf:u32le(rate * align) + wf:u16le(align) + wf:u16le(bits) + wf:u16le(0) + table.insert(wstreams, { type = "auds", handler = "\0\0\0\0", scale = align, rate = rate * align, sampleSize = align, strf = wf:finish(), ckid = "wb" }) + end + end + local chunks: { { any } } = {} + 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 } :: Avi.WOptions, chunks) + if not ok then + return nil, Err.new(Err.ARG, "internal error: " .. tostring(buf)) + end + return buf, nil +end + +-- ------------------------------------------------------------------------------------------------ open +function AviFormat.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) + local dmx, err = AviFormat.demux(r, opts) + if not dmx then + return nil, err + end + return Video.open(dmx, opts :: Video.OpenOptions?) +end + +return AviFormat +end +__FILES["video/fli"] = function() + +-- video/fli: Autodesk FLI / FLC / FLX animations, from Jim Kent's "FLC - Animator Pro Flic Files" (MultimediaWiki +-- "FLIC"): magics 0xAF11 (speed in 1/70 s), 0xAF12 / 0xAF44 (ms); frame chunks 0xF1FA / 0xF5FA, rgba8 through +-- codecs/video/Legacy; the ring frame is not shown. Not supported: writing, 1-bit FLICs, X-COM / Magic Carpet variants. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Demux = __include("containers/Demux") +local Video = __include("codecs/video/Video") + +-- ------------------------------------------------------------------------------------------------ contract +local Fli = { + name = "fli", + category = "video", + extensions = { "fli", "flc", "flx" }, + mime = { "video/x-fli", "video/fli", "video/x-flc" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/video/Video" }, + caps = { decode = true, encode = false, streaming = true, video = { "flic" }, depths = { 8, 15, 16, 24 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type OpenOptions = { + rgba: boolean?, -- frames are rgba8 already + maxPixels: number?, -- default 2^26 + ringFrame: boolean?, -- also show the ring frame (as ffmpeg) +} + +-- ------------------------------------------------------------------------------------------------ constants +local HEADER = 128 +local FLI, FLC, DTA = 0xAF11, 0xAF12, 0xAF44 +local FRAME, FRAME2 = 0xF1FA, 0xF5FA + +-- ------------------------------------------------------------------------------------------------ sniff +function Fli.sniff(r: Bytes.Reader): number + local s = r:peek(18) + if #s < 18 then + return 0 + end + local magic = string.byte(s, 5) + string.byte(s, 6) * 256 + if magic ~= FLI and magic ~= FLC and magic ~= DTA then + return 0 + end + local w = string.byte(s, 9) + string.byte(s, 10) * 256 + local h = string.byte(s, 11) + string.byte(s, 12) * 256 + if w > 4096 or h > 4096 then + return 0 + end + return 0.9 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Fli.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) + local b, base, limit = r.buf, r.base, r.limit + local n = limit - base + if n < HEADER then + return nil, Err.new(Err.TRUNCATED, "file shorter than the 128-byte header") + end + local hr = Bytes.reader(b, base, HEADER) + hr:skip(4) + local magic = hr:u16le() + local frames = hr:u16le() + local w, h = hr:u16le(), hr:u16le() + local depth = hr:u16le() + hr:skip(2) + local speed = hr:u32le() + if hr.err then + return nil, hr.err + end + if magic ~= FLI and magic ~= FLC and magic ~= DTA then + return nil, Err.new(Err.CORRUPT, string.format("bad magic 0x%04x", magic), 4) + end + if magic == FLI then + speed = speed % 65536 + end + if w == 0 or h == 0 then + return nil, Err.new(Err.CORRUPT, "no picture size") + end + local max = (opts and opts.maxPixels) or 2 ^ 26 + if w * h > max then + return nil, Err.new(Err.LIMIT, w .. " x " .. h .. " over maxPixels") + end + if magic == FLI or depth == 0 then + depth = 8 + elseif magic == FLC and depth == 16 then + depth = 15 -- Animator Pro's 16-bit FLCs hold 5-5-5 pixels + end + if speed == 0 then + speed = 5 + end + local scale = if magic == FLI then 70 else 1000 + local track: Types.Track = { + id = 1, + kind = "video", + codec = "flic", + codecTag = string.format("0x%04X", magic), + timescale = scale, + width = w, + height = h, + frameRate = scale / speed, + default = true, + bitsPerPixel = depth, + } + local offs, sizes = {}, {} + local p = base + HEADER + while p + 6 <= limit do + local size = buffer.readu32(b, p) + local cm = buffer.readu16(b, p + 4) + if size < 6 then + break + end + if (cm == FRAME or cm == FRAME2) and size > 6 then + if p + size > limit then + break + end + table.insert(offs, p) + table.insert(sizes, size) + end + p += size + end + local count = #offs + if frames > 0 and count > frames and not (opts and opts.ringFrame) then + count = frames -- the ring frame is not a frame of the animation + end + local dmx = Demux.new("fli", { track }, b, { + type = magic, + frames = frames, + depth = depth, + speed = speed, + ringFrame = #offs > frames and frames > 0, + }) + for i = 1, count do + dmx:add(1, (i - 1) * speed, nil, speed, i == 1, offs[i], sizes[i]) + end + dmx:finish() + return dmx, nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Fli.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) + local dmx, err = Fli.demux(r, opts) + if not dmx then + return nil, err + end + return Video.open(dmx, opts :: Video.OpenOptions?) +end + +return Fli +end +__FILES["video/flv"] = function() + +-- video/flv: Flash Video (Adobe FLV spec v10, Enhanced RTMP FourCC tags). Reads the tags and onMetaData (AMF0) into a +-- Demuxer; decodes Sorenson Spark and H.264 (other codecs are UNSUPPORTED tracks), audio through opts.openAudio. +-- Writes copied packets, else PCM s16 at 5512..44100 Hz. Not supported: encrypted tags, multitrack / ModEx packets. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Demux = __include("containers/Demux") +local Video = __include("codecs/video/Video") +local Source = __include("codecs/video/Video/Source") +local H263 = __include("codecs/video/H263") +local H264 = __include("codecs/video/H264") +local Aac = __include("codecs/audio/Aac") +local Amf = __include("video/flv/Amf") +local Mux = __include("video/flv/Mux") + +-- ------------------------------------------------------------------------------------------------ contract +local Flv = { + name = "flv", + category = "video", + extensions = { "flv" }, + mime = { "video/x-flv", "video/flv" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/video/Video", "codecs/video/Video/Source", "codecs/video/H263", "codecs/video/H264", "codecs/audio/Aac" }, + caps = { decode = true, encode = true, streaming = true, remux = true, video = { "flv1", "h264" }, audio = true, metadata = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type OpenOptions = { + rgba: boolean?, -- default false: yuv420p + track: number?, -- 1 video, 2 audio + audio: boolean?, + maxPackets: number?, -- default 2^24 + maxPixels: number?, + openAudio: any?, -- set by the api: (demuxer, track) -> audio Decoder +} +type EncodeOptions = { + video: boolean?, + audio: boolean?, -- true: fail when the audio cannot be written (default: dropped) + reencodeAudio: boolean?, +} + +-- ------------------------------------------------------------------------------------------------ constants +Flv.VIDEO_ID = 1 +Flv.AUDIO_ID = 2 + +-- SoundFormat -> codec id +local AUDIO_CODECS: { [number]: string } = { + [0] = "pcm", -- platform-endian (little-endian in practice) + [1] = "adpcm_swf", + [2] = "mp3", + [3] = "pcm", + [4] = "nellymoser", + [5] = "nellymoser", + [6] = "nellymoser", + [7] = "pcm_alaw", + [8] = "pcm_mulaw", + [10] = "aac", + [11] = "speex", + [14] = "mp3", + [15] = "device_specific", +} +local AUDIO_RATES = { [0] = 5512, 11025, 22050, 44100 } +-- the formats with a fixed rate (G.711: 8 kHz as ffmpeg reads them) / always mono +local FIXED_RATE: { [number]: number } = { [4] = 16000, [5] = 8000, [7] = 8000, [8] = 8000, [11] = 16000, [14] = 8000 } +local MONO: { [number]: boolean } = { [4] = true, [5] = true, [11] = true } + +-- CodecID -> codec id +local VIDEO_CODECS: { [number]: string } = { + [2] = "flv1", + [3] = "flashsv", + [4] = "vp6f", + [5] = "vp6a", + [6] = "flashsv2", + [7] = "h264", +} + +-- Enhanced FLV audio FourCCs +local AUDIO_FOURCC: { [string]: string } = { Opus = "opus", fLaC = "flac", mp4a = "aac", [".mp3"] = "mp3", ["ac-3"] = "ac3", ["ec-3"] = "eac3" } + +-- ------------------------------------------------------------------------------------------------ sniff +function Flv.sniff(r: Bytes.Reader): number + if r:remaining() >= 9 and r:peek(3) == "FLV" then + return if r:peekU8(3) == 1 then 1 else 0.6 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local readu8 = buffer.readu8 + +local function u24(b: buffer, p: number): number + return readu8(b, p) * 65536 + readu8(b, p + 1) * 256 + readu8(b, p + 2) +end + +local function s24(b: buffer, p: number): number + local v = u24(b, p) + return if v >= 0x800000 then v - 0x1000000 else v +end + +local function copy(b: buffer, p: number, n: number): buffer + local c = buffer.create(n) + buffer.copy(c, 0, b, p, n) + return c +end + +local function frameSize(codec: string, b: buffer, p: number, n: number): (number?, number?) + if codec == "flv1" then + local h = H263.header(b, p, n, true) + if h then + return h.width, h.height + end + elseif (codec == "vp6f" or codec == "vp6a") and n >= 8 then + -- VP6 key frame header: type / quant / marker, version / profile / interlace, [16-bit offset], MB rows, MB + -- cols, display rows, display cols; the FLV adjustment byte (p - 1, before the frame) crops width / height + local adj = readu8(b, p - 1) + local q = p + (if codec == "vp6a" then 3 else 0) + if q + 6 > p + n or readu8(b, q) >= 128 then + return nil, nil + end + local b1 = readu8(b, q + 1) + local o = q + 2 + if readu8(b, q) % 2 == 1 or (b1 // 2) % 4 == 0 then + o += 2 + end + if o + 4 > p + n then + return nil, nil + end + local w = readu8(b, o + 3) * 16 - adj // 16 + local h = readu8(b, o + 2) * 16 - adj % 16 + if w > 0 and h > 0 then + return w, h + end + elseif (codec == "flashsv" or codec == "flashsv2") and n >= 4 then + return (readu8(b, p) % 16) * 256 + readu8(b, p + 1), (readu8(b, p + 2) % 16) * 256 + readu8(b, p + 3) + end + return nil, nil +end + +function Flv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) + local o: OpenOptions = opts or {} + local b, base, limit = r.buf, r.base, r.limit + if limit - base < 9 or buffer.readstring(b, base, 3) ~= "FLV" then + return nil, Err.new(Err.CORRUPT, "not an FLV file (no FLV signature)", base) + end + local flags = readu8(b, base + 4) + local dataOffset = buffer.readu32(b, base + 5) + dataOffset = bit32.byteswap(dataOffset) + if dataOffset < 9 or base + dataOffset > limit then + return nil, Err.new(Err.CORRUPT, "bad header size " .. dataOffset, base + 5) + end + local meta: { [string]: any } = { version = readu8(b, base + 3), hasAudio = bit32.band(flags, 4) ~= 0, hasVideo = bit32.band(flags, 1) ~= 0 } + local tracks: { Types.Track } = {} + local dmx = Demux.new("flv", tracks, b, meta) + local vt: any, at: any = nil, nil + local keyOff, keyLen = -1, 0 + local maxPackets = o.maxPackets or 2 ^ 24 + local count = 0 + local p = base + dataOffset + 4 -- after PreviousTagSize0 + while p + 11 <= limit do + local tagType = bit32.band(readu8(b, p), 0x1F) + local filtered = bit32.band(readu8(b, p), 0x20) ~= 0 + local size = u24(b, p + 1) + local ts = u24(b, p + 4) + readu8(b, p + 7) * 0x1000000 + if ts >= 0x80000000 then + ts -= 0x100000000 + end + local d = p + 11 + if d + size > limit then + meta.truncated = true + break + end + count += 1 + if count > maxPackets then + return nil, Err.new(Err.LIMIT, "more than " .. maxPackets .. " tags") + end + if tagType == 8 and size >= 1 then + local a = readu8(b, d) + local fmt = a // 16 + if not at then + at = { id = Flv.AUDIO_ID, kind = "audio", codec = "unknown", codecTag = "flv audio " .. fmt, timescale = 1000, default = true } + table.insert(tracks, at) + local bits = if (a // 2) % 2 == 1 then 16 else 8 + local codec = AUDIO_CODECS[fmt] or ("flv_audio_" .. fmt) + if codec == "pcm" then + codec = if bits == 16 then "pcm_s16le" else "pcm_u8" + end + at.codec = codec + at.soundFormat = fmt + at.sampleRate = FIXED_RATE[fmt] or AUDIO_RATES[(a // 4) % 4] + at.channels = if MONO[fmt] then 1 else a % 2 + 1 + at.bitsPerSample = if codec == "pcm_alaw" or codec == "pcm_mulaw" then 8 else bits + end + if filtered then + at.unsupported = "encrypted audio tags" + elseif fmt == 10 and at.soundFormat == 10 then + if size >= 2 then + if readu8(b, d + 1) == 0 then + local c = copy(b, d + 2, size - 2) + at.config = c + local cfg = Aac.config(c) + if cfg then + at.sampleRate = cfg.extensionRate or cfg.sampleRate + at.channels = cfg.channels + end + elseif size > 2 then + dmx:add(at.id, ts, nil, nil, true, d + 2, size - 2) + end + end + elseif fmt == 9 and at.soundFormat == 9 then + -- Enhanced FLV: packet type, FourCC + if size >= 5 then + local pt = a % 16 + local fcc = buffer.readstring(b, d + 1, 4) + at.codec = AUDIO_FOURCC[fcc] or fcc + at.codecTag = fcc + if pt == 0 then + at.config = copy(b, d + 5, size - 5) + elseif pt == 1 and size > 5 then + dmx:add(at.id, ts, nil, nil, true, d + 5, size - 5) + end + end + elseif fmt == at.soundFormat and size > 1 then + dmx:add(at.id, ts, nil, nil, true, d + 1, size - 1) + end + elseif tagType == 9 and size >= 1 then + local v = readu8(b, d) + local enhanced = v >= 128 + local frameType = if enhanced then (v // 16) % 8 else v // 16 + if frameType ~= 5 then -- not a video info / command frame + local codec: string?, codecTag: string? = nil, nil + local pt, cts, q, n = 0, 0, 0, 0 + if enhanced then + if size < 5 then + codec = nil + else + local fcc = buffer.readstring(b, d + 1, 4) + codec, codecTag = Video.fromFourcc(fcc) or fcc, fcc + pt = v % 16 + q, n, cts = d + 5, size - 5, 0 + if pt == 1 and (fcc == "avc1" or fcc == "hvc1") then + if n >= 3 then + cts = s24(b, q) + end + q, n = q + 3, n - 3 + elseif pt == 3 then + pt = 1 -- coded frames without a composition time + end + end + else + local id = v % 16 + codec = VIDEO_CODECS[id] or ("flv_video_" .. id) + codecTag = "flv video " .. id + pt, q, n, cts = 1, d + 1, size - 1, 0 + if codec == "h264" then + if size >= 5 then + pt = readu8(b, d + 1) + cts = s24(b, d + 2) + else + pt = 2 + end + q, n = d + 5, size - 5 + elseif codec == "vp6f" or codec == "vp6a" then + q, n = d + 2, size - 2 -- after the adjustment byte (the track's config, as ffmpeg's extradata) + end + end + if codec then + if not vt then + vt = { id = Flv.VIDEO_ID, kind = "video", codec = codec, codecTag = codecTag, timescale = 1000, default = true } + table.insert(tracks, vt) + end + if (codec == "vp6f" or codec == "vp6a") and not vt.config and size >= 2 then + vt.config = copy(b, d + 1, 1) -- the crop (adjustment) byte + end + if filtered then + vt.unsupported = "encrypted video tags" + elseif codec == vt.codec then + if pt == 0 then + if n > 0 then + vt.config = copy(b, q, n) + end + elseif pt == 1 and n > 0 then + local key = frameType == 1 + dmx:add(vt.id, ts + cts, ts, nil, key, q, n) + if key and keyOff < 0 then + keyOff, keyLen = q, n + end + end + end + end + end + elseif tagType == 18 and size > 0 then + local name, value = Amf.script(Bytes.reader(b, d, size)) + if name == "onMetaData" and type(value) == "table" and meta.metadata == nil then + meta.metadata = value + elseif name then + meta.scripts = meta.scripts or {} + table.insert(meta.scripts, { name = name, time = ts / 1000, value = value }) + end + end + p = d + size + 4 + end + local md: { [string]: any } = meta.metadata or {} + if type(md.duration) == "number" and md.duration > 0 then + meta.duration = md.duration + end + if vt then + if vt.codec == "h264" and vt.config then + local ok, info = pcall(H264.info, vt.config) + if ok and info then + vt.width, vt.height = info.width, info.height + end + elseif keyOff >= 0 then + local w, h = frameSize(vt.codec, b, keyOff, keyLen) + vt.width, vt.height = w, h + end + if not vt.width and type(md.width) == "number" and type(md.height) == "number" then + vt.width, vt.height = math.floor(md.width), math.floor(md.height) + end + local fr = md.framerate or md.videoframerate + if type(fr) == "number" and fr > 0 and fr < 1000 then + vt.frameRate = fr + else + local n = dmx:count(vt.id) + local t0 = if n > 0 then dmx:info(vt.id, 1) else nil + local t1 = if n > 1 then dmx:info(vt.id, n) else nil + if t0 and t1 and t1 > t0 then + vt.frameRate = math.floor((n - 1) / ((t1 - t0) / 1000) * 1000 + 0.5) / 1000 + end + end + end + if at and at.codec == "aac" and not at.config then + at.unsupported = "AAC without its AudioSpecificConfig" + end + dmx:finish() + return dmx, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Flv.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: any = opts or {} + local streams, err = Source.streams(value, o, { + video = { copy = Mux.VIDEO_COPY }, + audio = { copy = Mux.AUDIO_COPY, pcm = true }, + }) + if not streams then + return nil, err + end + for i = #streams, 1, -1 do + local s = streams[i] + local why = s.kind == "audio" and Mux.audioProblem(s) + if why then + if o.audio == true then + return nil, Err.new(Err.UNSUPPORTED, why) + end + table.remove(streams, i) + end + end + if #streams == 0 then + return nil, Err.new(Err.UNSUPPORTED, "nothing FLV can hold") + end + local ok, buf, merr = pcall(Mux.mux, streams) + if not ok then + return nil, Err.new(Err.ARG, "internal error: " .. tostring(buf)) + end + return buf, merr +end + +-- ------------------------------------------------------------------------------------------------ open +function Flv.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) + local ok, dmx, err = pcall(Flv.demux, r, opts) + if not ok then + return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(dmx)) + end + if not dmx then + return nil, err + end + return Video.open(dmx, opts :: Video.OpenOptions?) +end + +return Flv +end +__FILES["video/flv/Amf"] = function() + +-- video/flv/Amf: AMF0 values (AMF0 spec, FLV spec v10 script tags). Read: number, boolean, string, object, null, +-- undefined, reference, ECMA / strict array, date (ms), long string. Write: numbers, booleans, strings, arrays. +local Bytes = __include("core/Bytes") + +local Amf = {} + +-- null / undefined inside arrays (dropped from objects) +Amf.NULL = table.freeze({}) + +local MAX_DEPTH = 32 + +local function str(r: Bytes.Reader, long: boolean): string + local n = if long then r:u32be() else r:u16be() + return r:string(n) +end + +local readValue: (r: Bytes.Reader, depth: number, refs: { any }) -> any + +-- object properties up to the end marker (00 00 09) or the end of the data +local function props(r: Bytes.Reader, depth: number, refs: { any }, into: { [string]: any }): boolean + while not r.err and r:remaining() >= 3 do + local key = str(r, false) + if key == "" and r:peekU8() == 9 then + r:skip(1) + return true + end + local v = readValue(r, depth + 1, refs) + if r.err or v == nil then + return false + end + if v ~= Amf.NULL then + into[key] = v + end + end + return false +end + +readValue = function(r: Bytes.Reader, depth: number, refs: { any }): any + if depth > MAX_DEPTH or r:remaining() < 1 then + return nil + end + local t = r:u8() + if t == 0 then + return r:f64be() + elseif t == 1 then + return r:u8() ~= 0 + elseif t == 2 then + return str(r, false) + elseif t == 12 then + return str(r, true) + elseif t == 3 or t == 8 then + if t == 8 then + r:u32be() -- the count (approximate in practice: the end marker ends it) + end + local o: { [string]: any } = {} + table.insert(refs, o) + props(r, depth, refs, o) + return o + elseif t == 10 then + local n = r:u32be() + local a: { any } = {} + table.insert(refs, a) + for i = 1, n do + if r.err or r:remaining() < 1 then + break + end + local v = readValue(r, depth + 1, refs) + if v == nil then + break + end + a[i] = v + end + return a + elseif t == 5 or t == 6 then + return Amf.NULL + elseif t == 7 then + local i = r:u16be() + return refs[i + 1] or Amf.NULL + elseif t == 11 then + local ms = r:f64be() + r:i16be() + return ms + end + return nil +end + +function Amf.value(r: Bytes.Reader): any + local ok, v = pcall(readValue, r, 0, {}) + return if ok and not r.err then v else nil +end + +function Amf.script(r: Bytes.Reader): (string?, any) + local name = Amf.value(r) + if type(name) ~= "string" then + return nil, nil + end + return name, Amf.value(r) +end + +-- ------------------------------------------------------------------------------------------------ write +local function writeString(w: Bytes.Writer, s: string) + if #s > 65535 then + w:u8(12) + w:u32be(#s) + else + w:u8(2) + w:u16be(#s) + end + w:string(s) +end + +function Amf.writeValue(w: Bytes.Writer, v: any) + local t = type(v) + if t == "number" then + w:u8(0) + w:f64be(v) + elseif t == "boolean" then + w:u8(1) + w:u8(if v then 1 else 0) + elseif t == "string" then + writeString(w, v) + elseif t == "table" and v ~= Amf.NULL and #v > 0 then + w:u8(10) + w:u32be(#v) + for _, x in v do + Amf.writeValue(w, x) + end + else + w:u8(5) + end +end + +function Amf.writeEcma(w: Bytes.Writer, list: { { any } }, object: boolean?) + if object then + w:u8(3) + else + w:u8(8) + w:u32be(#list) + end + for _, kv in list do + local k: string = kv[1] + w:u16be(#k) + w:string(k) + local v = kv[2] + if type(v) == "table" and v.pairs then + Amf.writeEcma(w, v.pairs, true) + else + Amf.writeValue(w, v) + end + end + w:u16be(0) + w:u8(9) +end + +return Amf +end +__FILES["video/flv/Mux"] = function() + +-- video/flv/Mux: the FLV writer (FLV spec v10): header, onMetaData, AVC / AAC sequence headers, tags interleaved by +-- decode time (ms, shifted so none is negative), H.264 end of sequence; ADTS AAC split into raw frames. +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Amf = __include("video/flv/Amf") + +local Mux = {} + +-- the codecs FLV holds (copied from the source) +local VIDEO_COPY: { [string]: boolean } = { h264 = true, flv1 = true, vp6f = true, vp6a = true, flashsv = true, flashsv2 = true } +local AUDIO_COPY: { [string]: boolean } = { aac = true, mp3 = true, pcm_s16le = true, pcm_u8 = true, pcm_alaw = true, pcm_mulaw = true, adpcm_swf = true, nellymoser = true, speex = true } +Mux.VIDEO_COPY = VIDEO_COPY +Mux.AUDIO_COPY = AUDIO_COPY + +local VIDEO_IDS: { [string]: number } = { flv1 = 2, flashsv = 3, vp6f = 4, vp6a = 5, flashsv2 = 6, h264 = 7 } +local AUDIO_FORMATS: { [string]: number } = { pcm_s16le = 3, pcm_u8 = 3, adpcm_swf = 1, mp3 = 2, nellymoser = 6, pcm_alaw = 7, pcm_mulaw = 8, aac = 10, speex = 11 } +local RATE_CODES: { [number]: number } = { [5512] = 0, [5513] = 0, [11025] = 1, [22050] = 2, [44100] = 3 } +local AAC_RATES = { 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350 } + +local function isAdts(s: any): boolean + if s.track and s.track.adts then + return true + end + local p = s.packets[1] + return s.config == nil and p ~= nil and buffer.len(p.data) >= 7 and buffer.readu8(p.data, 0) == 0xFF and buffer.readu8(p.data, 1) >= 0xF0 +end + +function Mux.audioProblem(s: any): string? + local fmt = AUDIO_FORMATS[s.codec] + if not fmt then + return "FLV has no audio codec " .. tostring(s.codec) + end + if (s.channels or 1) > 2 then + return "FLV audio has at most 2 channels" + end + local rate = math.floor((s.sampleRate or 0) + 0.5) + if s.codec == "aac" then + if not s.config and not isAdts(s) then + return "AAC without its AudioSpecificConfig" + end + elseif (s.codec == "pcm_alaw" or s.codec == "pcm_mulaw") and rate ~= 8000 then + return "FLV G.711 audio is 8000 Hz (not " .. rate .. ")" + elseif s.codec ~= "mp3" and s.codec ~= "speex" and s.codec ~= "nellymoser" and s.codec ~= "pcm_alaw" and s.codec ~= "pcm_mulaw" and RATE_CODES[rate] == nil then + return "FLV " .. s.codec .. " audio is 5512, 11025, 22050 or 44100 Hz (not " .. rate .. ")" + end + return nil +end + +local function audioFlags(s: any): number + local fmt = AUDIO_FORMATS[s.codec] + local rate = math.floor((s.sampleRate or 44100) + 0.5) + local rc = RATE_CODES[rate] or 3 + local size = if s.codec == "pcm_u8" then 0 else 1 + local stereo = if (s.channels or 1) > 1 then 1 else 0 + if s.codec == "aac" then + rc, stereo = 3, 1 + elseif s.codec == "mp3" and rate == 8000 then + fmt = 14 + elseif s.codec == "speex" then + rc, stereo = 0, 0 + elseif s.codec == "pcm_alaw" or s.codec == "pcm_mulaw" then + rc = 0 + elseif s.codec == "nellymoser" then + if rate == 16000 then + fmt = 4 + elseif rate == 8000 then + fmt = 5 + end + stereo = 0 + end + return fmt * 16 + rc * 4 + size * 2 + stereo +end + +-- ADTS frames -> raw AAC frames (1024 samples each) and the AudioSpecificConfig of the first header +local function fromAdts(s: any): ({ any }?, buffer?) + local out = {} + local cfg: buffer? = nil + local rate = s.sampleRate or 44100 + for _, p in s.packets do + local d: buffer = p.data + local n = buffer.len(d) + local o = 0 + local t = p.pts + while o + 7 <= n do + local b1, b2, b3 = buffer.readu8(d, o + 1), buffer.readu8(d, o + 2), buffer.readu8(d, o + 3) + if buffer.readu8(d, o) ~= 0xFF or b1 < 0xF0 then + return nil, nil + end + local len = (b3 % 4) * 2048 + buffer.readu8(d, o + 4) * 8 + buffer.readu8(d, o + 5) // 32 + local hl = if b1 % 2 == 1 then 7 else 9 + if len < hl or o + len > n then + return nil, nil + end + if not cfg then + local aot = b2 // 64 + 1 + local sfi = (b2 // 4) % 16 + local ch = (b2 % 2) * 4 + b3 // 64 + cfg = buffer.create(2) + buffer.writeu8(cfg, 0, aot * 8 + sfi // 2) + buffer.writeu8(cfg, 1, (sfi % 2) * 128 + ch * 8) + rate = AAC_RATES[sfi + 1] or rate + end + local f = buffer.create(len - hl) + buffer.copy(f, 0, d, o + hl, len - hl) + table.insert(out, { pts = t, dts = t, duration = 1024 / rate, keyframe = true, data = f }) + t += 1024 / rate + o += len + end + end + return out, cfg +end + +local function f64At(b: buffer, at: number, v: number) + local t = buffer.create(8) + buffer.writef64(t, 0, v) + for i = 0, 7 do + buffer.writeu8(b, at + i, buffer.readu8(t, 7 - i)) + end +end + +function Mux.mux(streams: { any }): (buffer?, Err.Err?) + local video, audio = nil :: any, nil :: any + for _, s in streams do + if s.kind == "video" and not video then + if not VIDEO_IDS[s.codec] then + return nil, Err.new(Err.UNSUPPORTED, "FLV has no video codec " .. tostring(s.codec)) + end + if s.codec == "h264" and (s.config == nil or buffer.len(s.config) < 7 or buffer.readu8(s.config, 0) ~= 1) then + return nil, Err.new(Err.UNSUPPORTED, "H.264 without an avcC (an Annex B source) cannot be written to FLV") + end + video = s + elseif s.kind == "audio" and not audio then + audio = s + end + end + if not video and not audio then + return nil, Err.new(Err.ARG, "no video or audio stream") + end + local aConfig: buffer? = audio and audio.config + local aPackets: { any } = audio and audio.packets or {} + if audio and audio.codec == "aac" and isAdts(audio) then + local pk, cfg = fromAdts(audio) + if not pk or not cfg then + return nil, Err.new(Err.CORRUPT, "bad ADTS AAC audio") + end + aPackets, aConfig = pk, cfg + end + local order: { { any } } = {} -- { kind, packet } + do + local vi, ai = 1, 1 + local vp: { any } = if video then video.packets else {} + while vi <= #vp or ai <= #aPackets do + local a, v = aPackets[ai], vp[vi] + if v and (not a or (v.dts or v.pts) <= (a.dts or a.pts)) then + table.insert(order, { "video", v }) + vi += 1 + else + table.insert(order, { "audio", a }) + ai += 1 + end + end + end + local shift = 0 + local duration = 0 + local vBytes, aBytes = 0, 0 + for _, e in order do + local p = e[2] + local t = p.dts or p.pts + if t < -shift then + shift = -t + end + duration = math.max(duration, p.pts + (p.duration or 0)) + if e[1] == "video" then + vBytes += buffer.len(p.data) + else + aBytes += buffer.len(p.data) + end + end + local function ms(t: number): number + return math.floor((t + shift) * 1000 + 0.5) + end + + local w = Bytes.writer(65536 + vBytes + aBytes + #order * 20) + w:string("FLV") + w:u8(1) + w:u8((if audio then 4 else 0) + (if video then 1 else 0)) + w:u32be(9) + w:u32be(0) + local function tag(kind: number, ts: number, head: { number }, data: buffer?) + local n = #head + (if data then buffer.len(data) else 0) + w:u8(kind) + w:u24be(n) + local t = ts % 0x100000000 + w:u24be(t % 0x1000000) + w:u8(t // 0x1000000) + w:u24be(0) + for _, x in head do + w:u8(x) + end + if data then + w:bytes(data) + end + w:u32be(11 + n) + end + + local props: { { any } } = { { "duration", duration } } + if video then + table.insert(props, { "width", video.width or 0 }) + table.insert(props, { "height", video.height or 0 }) + table.insert(props, { "videodatarate", if duration > 0 then vBytes * 8 / duration / 1000 else 0 }) + table.insert(props, { "framerate", video.frameRate or 0 }) + table.insert(props, { "videocodecid", VIDEO_IDS[video.codec] }) + end + if audio then + local flags = audioFlags(audio) + table.insert(props, { "audiodatarate", if duration > 0 then aBytes * 8 / duration / 1000 else 0 }) + table.insert(props, { "audiosamplerate", math.floor((audio.sampleRate or 44100) + 0.5) }) + table.insert(props, { "audiosamplesize", if audio.codec == "pcm_u8" then 8 else 16 }) + table.insert(props, { "stereo", (audio.channels or 1) > 1 }) + table.insert(props, { "audiocodecid", flags // 16 }) + end + table.insert(props, { "encoder", "rosetta" }) + table.insert(props, { "filesize", 0 }) + local mw = Bytes.writer(512) + Amf.writeValue(mw, "onMetaData") + Amf.writeEcma(mw, props) + local metaBody = mw:finish() + local metaAt = w:tell() + 11 + tag(18, 0, {}, metaBody) + local fileSizeAt = metaAt + buffer.len(metaBody) - 3 - 8 -- the last value (filesize) before the end marker + + local vid = if video then VIDEO_IDS[video.codec] else 0 + if video and video.codec == "h264" then + tag(9, 0, { 0x10 + vid, 0, 0, 0, 0 }, video.config) + end + local aflags = if audio then audioFlags(audio) else 0 + if audio and audio.codec == "aac" then + tag(8, 0, { aflags, 0 }, aConfig) + end + local vp6 = if video and (video.codec == "vp6f" or video.codec == "vp6a") then video.config else nil + local vp6Byte = if vp6 and buffer.len(vp6) > 0 then buffer.readu8(vp6, 0) else 0 + if video and (video.codec == "vp6f" or video.codec == "vp6a") and not vp6 then + local wd, ht = video.width or 0, video.height or 0 + vp6Byte = ((16 - wd % 16) % 16) * 16 + (16 - ht % 16) % 16 + end + local lastVideo = 0 + for _, e in order do + local p = e[2] + local dts = ms(p.dts or p.pts) + if e[1] == "video" then + local ft = (if p.keyframe then 1 else 2) * 16 + vid + if video.codec == "h264" then + local cts = ms(p.pts) - dts + if cts < 0 then + cts += 0x1000000 + end + tag(9, dts, { ft, 1, cts // 65536 % 256, cts // 256 % 256, cts % 256 }, p.data) + elseif vp6 or video.codec == "vp6f" or video.codec == "vp6a" then + tag(9, dts, { ft, vp6Byte }, p.data) + else + tag(9, dts, { ft }, p.data) + end + lastVideo = math.max(lastVideo, dts) + elseif audio.codec == "aac" then + tag(8, dts, { aflags, 1 }, p.data) + else + tag(8, dts, { aflags }, p.data) + end + end + if video and video.codec == "h264" then + tag(9, lastVideo, { 0x10 + vid, 2, 0, 0, 0 }, nil) + end + local out = w:finish() + f64At(out, fileSizeAt, buffer.len(out)) + return out, nil +end + +return Mux +end +__FILES["video/h264"] = function() + +-- video/h264: raw H.264 Annex B byte streams (.h264 / .264), cut into access units and decoded by codecs/video/H264 +-- (frame rate: the SPS VUI, else opts.frameRate, else 25). Writes H.264 tracks copied from any video (avcC to Annex B). +-- Not supported: encoding other codecs, what codecs/video/H264 does not decode (interlaced, 4:2:2 / 4:4:4, > 8 bits). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Demux = __include("containers/Demux") +local Video = __include("codecs/video/Video") +local Source = __include("codecs/video/Video/Source") +local H264 = __include("codecs/video/H264") + +-- ------------------------------------------------------------------------------------------------ contract +local Format = { + name = "h264", + category = "video", + extensions = { "h264", "264", "avc", "jsv", "26l", "jvt" }, + mime = { "video/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 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type OpenOptions = { + rgba: boolean?, -- default false: yuv420p + maxPixels: number?, -- default 2^22 luma samples + frameRate: number?, -- default 25 + deblock: boolean?, -- false: faster, not conformant +} + +-- ------------------------------------------------------------------------------------------------ sniff +-- a start code then an SPS / AUD / SEI / PPS NAL header (forbidden bit 0) +function Format.sniff(r: Bytes.Reader): number + local s = r:peek(5) + if not s or #s < 4 then + return 0 + end + local hdr + if string.byte(s, 1) == 0 and string.byte(s, 2) == 0 and string.byte(s, 3) == 1 then + hdr = string.byte(s, 4) + elseif #s >= 5 and string.byte(s, 1) == 0 and string.byte(s, 2) == 0 and string.byte(s, 3) == 0 and string.byte(s, 4) == 1 then + hdr = string.byte(s, 5) + else + return 0 + end + if hdr >= 128 then + return 0 + end + local t = hdr % 32 + if t == 7 then + return 0.8 + elseif t == 9 or t == 6 or t == 8 then + return 0.5 + elseif t == 5 then + return 0.4 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Format.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) + local buf, base, limit = r.buf, r.base, r.limit + local units = H264.accessUnits(buf, base, limit - base) + if #units == 0 then + return nil, Err.new(Err.CORRUPT, "no access units (no slices after a start code)", base) + end + local info = H264.info(buffer.readstring(buf, base, math.min(limit - base, 4096))) or {} + if info.interlaced or (info.chromaFormat and info.chromaFormat ~= 1) or (info.bitDepth and info.bitDepth ~= 8) then + -- still demuxable (remuxing works); decoding reports UNSUPPORTED + info.unsupported = true + end + local fps = info.frameRate or (opts and opts.frameRate) or 25 + if fps <= 0 or fps > 1000 then + fps = 25 + end + local track: Types.Track = { + id = 1, + kind = "video", + codec = "h264", + timescale = fps, + width = info.width, + height = info.height, + frameRate = fps, + profile = info.profile, + level = info.level, + ptsInOutputOrder = true, + default = true, + } + local dmx = Demux.new("h264", { track }, buf, { profile = info.profile, level = info.level }) + local k = 0 + for i = 1, #units, 3 do + dmx:add(1, k, k, 1, units[i + 2] or k == 0, units[i], units[i + 1]) + k += 1 + end + track.frames = k + dmx:finish() + return dmx, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Format.encode(value: any, _opts: any?): (buffer?, Err.Err?) + local streams, err = Source.streams(value, { audio = false }, { video = { copy = { h264 = true } } }) + if not streams then + return nil, err + end + local s = streams[1] + if not s or s.codec ~= "h264" then + return nil, Err.new(Err.UNSUPPORTED, "only H.264 tracks can be written as a raw H.264 stream") + end + local parts = {} + for i, p in s.packets do + local data = p.data + if s.config then + local key = i == 1 or p.keyframe + local out, e = H264.toAnnexB(if key then s.config else nil, data) + if not out then + return nil, e + end + data = out + end + table.insert(parts, buffer.tostring(data)) + end + return buffer.fromstring(table.concat(parts)), nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Format.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) + local dmx, err = Format.demux(r, opts) + if not dmx then + return nil, err + end + return Video.open(dmx, opts) +end + +return Format +end +__FILES["video/mkv"] = function() + +-- video/mkv: Matroska / WebM (RFC 9559, the WebM guidelines), on containers/Ebml. Reads every packet (all lacings, +-- header stripping and zlib, unknown-size clusters, Cues, Tags) into a Demuxer, text subtitle tracks as cues. Writes +-- WebM or Matroska (copied, else MJPEG + PCM s16). Not supported: bzip2 / lzo, encryption, chapters, attachments. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Video = __include("codecs/video/Video") +local Source = __include("codecs/video/Video/Source") +local Parse = __include("video/mkv/Parse") +local Mux = __include("video/mkv/Mux") + +-- ------------------------------------------------------------------------------------------------ contract +local Mkv = { + name = "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", "containers/Avi", "containers/IsoBmff/QtPalette", "codecs/compress/Deflate", "codecs/video/Video", "codecs/video/Video/Source" }, + caps = { decode = true, encode = true, streaming = true, remux = true, video = { "vp8", "mjpeg", "mpeg1", "mpeg2", "theora", "rawvideo" }, audio = true, subtitles = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type OpenOptions = { + rgba: boolean?, -- default false: yuv420p + track: number?, -- default: the first video track + audio: boolean?, + maxPackets: number?, -- default 2^24 + maxPixels: number?, + openAudio: any?, -- set by the api: (demuxer, track) -> audio Decoder +} +type EncodeOptions = { + format: string?, -- "webm": DocType webm, WebM codecs only; else Matroska + webm: boolean?, -- as format = "webm" + quality: number?, -- 1..100, default 90 + reencode: boolean?, + video: boolean?, + audio: boolean?, -- true: fail if the audio cannot be written (default: dropped) + title: string?, + clusterSeconds: number?, -- seconds, default 2 +} + +-- ------------------------------------------------------------------------------------------------ constants +local WEBM_VIDEO = { vp8 = true, vp9 = true, av1 = true } +local WEBM_AUDIO = { opus = true, vorbis = true } + +-- ------------------------------------------------------------------------------------------------ sniff +function Mkv.sniff(r: Bytes.Reader): number + if r:peek(4) ~= "\26\69\223\163" then + return 0 + end + local head = r:peek(math.min(64, r:remaining())) + if string.find(head, "webm", 1, true) or string.find(head, "matroska", 1, true) then + return 1 + end + return 0.5 +end + +function Mkv.variant(r: Bytes.Reader): string? + local ok, docType = pcall(Parse.docType, r.buf, r.pos, r.limit) + if ok and docType == "webm" then + return "webm" + end + return nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Mkv.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: any = opts or {} + local webm = o.webm == true or (type(o.format) == "string" and string.lower(o.format) == "webm") + local want: Source.Want + if webm then + want = { video = { copy = WEBM_VIDEO }, audio = { copy = WEBM_AUDIO } } + else + local copy: { [string]: boolean } = {} + for id, e in Video.codecs do + if e.matroska then + copy[id] = true + end + end + want = { video = { copy = copy, encode = "mjpeg" }, audio = { copy = { ["*"] = true }, pcm = true } } + end + local so = table.clone(o) + so.quality = so.quality or 90 + local streams, err = Source.streams(value, so, want) + if not streams then + return nil, err + end + if not webm then + -- audio codecs Matroska cannot name: PCM instead + for i, s in streams do + if s.kind == "audio" and not Mux.codecId("audio", s.codec) then + local alt, aerr = Source.streams(value, { video = false, reencodeAudio = true }, { audio = { pcm = true } }) + if alt and alt[1] then + streams[i] = alt[1] + else + return nil, aerr + end + end + end + end + local ok, buf, merr = pcall(Mux.mux, streams, { webm = webm, title = o.title, clusterSeconds = o.clusterSeconds }) + if not ok then + return nil, Err.new(Err.ARG, "internal error: " .. tostring(buf)) + end + return buf, merr +end + +-- ------------------------------------------------------------------------------------------------ open +function Mkv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) + local ok, dmx, err = pcall(Parse.parse, r.buf, r.base, r.limit, opts) + if not ok then + return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(dmx)) + end + return dmx, err +end + +function Mkv.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) + local dmx, err = Mkv.demux(r, opts) + if not dmx then + return nil, err + end + return Video.open(dmx, opts :: Video.OpenOptions?) +end + +-- ------------------------------------------------------------------------------------------------ extras +function Mkv.subtitles(dmx: any, trackId: number?): Types.Subtitles? + local track = nil + for _, t in dmx.tracks do + if t.kind == "subtitle" and (trackId == nil or t.id == trackId) then + track = t + break + end + end + if not track then + return nil + end + local subs = Types.Subtitles.new() + subs.meta.codec = track.codec + subs.meta.language = track.language + for k = 1, dmx:count(track.id) do + local p = dmx:get(track.id, k) + 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) } :: Types.Cue) + end + end + return subs +end + +return Mkv +end +__FILES["video/mkv/Mux"] = function() + +-- video/mkv/Mux: the Matroska / WebM muxer: EBML header, Segment (SeekHead, Info with a 1 ms TimecodeScale, Tracks, +-- Clusters of SimpleBlocks cut at keyframes after 2 s or before the 16-bit timestamp overflows, a CuePoint each). +local Err = __include("core/Err") +local Ebml = __include("containers/Ebml") +local Video = __include("codecs/video/Video") +local Source = __include("codecs/video/Video/Source") +local Parse = __include("video/mkv/Parse") + +local ID = Parse.ID +local Mux = {} + +local AUDIO_IDS: { [string]: string } = { + vorbis = "A_VORBIS", + opus = "A_OPUS", + flac = "A_FLAC", + mp3 = "A_MPEG/L3", + mp2 = "A_MPEG/L2", + mp1 = "A_MPEG/L1", + aac = "A_AAC", + ac3 = "A_AC3", + eac3 = "A_EAC3", + alac = "A_ALAC", + pcm_u8 = "A_PCM/INT/LIT", + pcm_s16le = "A_PCM/INT/LIT", + pcm_s24le = "A_PCM/INT/LIT", + pcm_s32le = "A_PCM/INT/LIT", + pcm_s16be = "A_PCM/INT/BIG", + pcm_s24be = "A_PCM/INT/BIG", + pcm_s32be = "A_PCM/INT/BIG", + pcm_f32le = "A_PCM/FLOAT/IEEE", + pcm_f64le = "A_PCM/FLOAT/IEEE", +} +Mux.AUDIO_IDS = AUDIO_IDS + +function Mux.codecId(kind: string, codec: string): string? + if kind == "video" then + local e = Video.entry(codec) + local m = e and e.matroska + return m and m[1] + end + return AUDIO_IDS[codec] +end + +local function pcmBits(codec: string): number? + local b = string.match(codec, "^pcm_[suf](%d+)") + if b then + return tonumber(b) + end + if codec == "pcm_u8" then + return 8 + end + return nil +end + +type Options = { + webm: boolean?, + title: string?, + app: string?, + clusterSeconds: number?, -- default 2 +} + +function Mux.mux(streams: { any }, opts: Options): (buffer?, Err.Err?) + local webm = opts.webm == true + local app = opts.app or "rosetta" + local clusterSpan = opts.clusterSeconds or 2 + local ids: { string } = {} + local videoIndex = 0 + for i, s in streams do + local cid = Mux.codecId(s.kind, s.codec) + if not cid then + return nil, Err.new(Err.UNSUPPORTED, "no Matroska CodecID for " .. s.kind .. " codec " .. s.codec) + end + ids[i] = cid + if s.kind == "video" and videoIndex == 0 then + videoIndex = i + end + end + local order = Source.interleave(streams) + local duration = 0 + for _, s in streams do + for _, p in s.packets do + local e = p.pts + (p.duration or 0) + if e > duration then + duration = e + end + end + end + + -- segment body: Info, Tracks, Clusters, Cues (the SeekHead goes in front once their offsets are known) + local body = Ebml.writer(65536) + local infoAt = body:tell() + local info = body:open(ID.Info) + body:uint(ID.TimecodeScale, 1000000) + body:string(ID.MuxingApp, app) + body:string(ID.WritingApp, app) + if opts.title then + body:string(ID.Title, opts.title) + end + body:float(ID.Duration, duration * 1000) + body:close(info) + + local tracksAt = body:tell() + local tracks = body:open(ID.Tracks) + for i, s in streams do + local te = body:open(ID.TrackEntry) + body:uint(ID.TrackNumber, i) + body:uint(ID.TrackUID, i) + body:uint(ID.TrackType, if s.kind == "video" then 1 else 2) + body:uint(ID.FlagLacing, 0) + body:string(ID.Language, "und") + body:string(ID.CodecID, ids[i]) + if s.config and buffer.len(s.config) > 0 then + body:binary(ID.CodecPrivate, s.config) + end + if s.kind == "video" then + if s.frameRate and s.frameRate > 0 then + body:uint(ID.DefaultDuration, math.floor(1e9 / s.frameRate + 0.5)) + end + local v = body:open(ID.Video) + body:uint(ID.PixelWidth, s.width or 0) + body:uint(ID.PixelHeight, s.height or 0) + body:close(v) + else + if s.codec == "opus" then + local pre = 0 + local c = s.config + if c and buffer.len(c) >= 12 then + pre = buffer.readu16(c, 10) + end + body:uint(ID.CodecDelay, math.floor(pre * 1e9 / 48000 + 0.5)) + body:uint(ID.SeekPreRoll, 80000000) + end + local a = body:open(ID.Audio) + body:float(ID.SamplingFrequency, s.sampleRate or 48000) + body:uint(ID.Channels, s.channels or 1) + local bits = pcmBits(s.codec) or s.bitsPerSample + if bits and string.sub(s.codec, 1, 4) == "pcm_" then + body:uint(ID.BitDepth, bits) + end + body:close(a) + end + body:close(te) + end + body:close(tracks) + + local cues: { { number } } = {} -- { time ms, track, cluster offset in body } + local cl: number? = nil + local clTime = 0 + local clStart = 0 + for _, item in order do + local si: number, p = item[1], item[2] + local ms = math.floor(p.pts * 1000 + 0.5) + local isVideoKey = si == videoIndex and p.keyframe + local need = cl == nil + or ms - clTime > 30000 + or ms < clTime + or (isVideoKey and ms - clStart >= clusterSpan * 1000) + or (videoIndex == 0 and ms - clStart >= clusterSpan * 1000) + if need then + if cl then + body:close(cl) + end + local at = body:tell() + cl = body:open(ID.Cluster) + clTime = ms + clStart = ms + body:uint(ID.Timecode, ms) + if videoIndex == 0 or isVideoKey then + table.insert(cues, { ms, if videoIndex > 0 then videoIndex else si, at }) + end + end + local data: buffer = p.data + local hdr = Ebml.vintString(si, 1) + local rel = ms - clTime + local size = #hdr + 3 + buffer.len(data) + body:header(ID.SimpleBlock, size) + body:raw(hdr) + body:raw(string.char(rel // 256, rel % 256, if p.keyframe or streams[si].kind ~= "video" then 0x80 else 0)) + body:rawBuffer(data) + end + if cl then + body:close(cl) + end + local cuesAt = body:tell() + if #cues > 0 then + local c = body:open(ID.Cues) + for _, q in cues do + local cp = body:open(ID.CuePoint) + body:uint(ID.CueTime, q[1]) + local tp = body:open(ID.CueTrackPositions) + body:uint(ID.CueTrack, q[2]) + body:uint(ID.CueClusterPosition, q[3]) -- patched below by the SeekHead length + body:close(tp) + body:close(cp) + end + body:close(c) + end + local bodyBuf = body:finish() + + -- the SeekHead: its own length shifts every position, so build it until its size is stable + local function seekHead(shift: number): buffer + local w = Ebml.writer(256) + local sh = w:open(ID.SeekHead) + local entries = { { ID.Info, infoAt }, { ID.Tracks, tracksAt } } + if #cues > 0 then + table.insert(entries, { ID.Cues, cuesAt }) + end + for _, e in entries do + local sk = w:open(0x4DBB) + local idv = e[1] + local bytes = {} + while idv > 0 do + table.insert(bytes, 1, idv % 256) + idv = idv // 256 + end + w:header(0x53AB, #bytes) + for _, b in bytes do + w:raw(string.char(b)) + end + w:uint(0x53AC, e[2] + shift) + w:close(sk) + end + w:close(sh) + return w:finish() + end + local shift = 0 + local head = seekHead(0) + for _ = 1, 4 do + local n = buffer.len(head) + if n == shift then + break + end + shift = n + head = seekHead(shift) + end + shift = buffer.len(head) + -- cue cluster positions (relative to the segment data) must include the SeekHead: rewrite the Cues element + -- (its uint widths may grow, but Cues are last, so nothing after them moves) + if #cues > 0 then + local w = Ebml.writer(4096) + local c = w:open(ID.Cues) + for _, q in cues do + local cp = w:open(ID.CuePoint) + w:uint(ID.CueTime, q[1]) + local tp = w:open(ID.CueTrackPositions) + w:uint(ID.CueTrack, q[2]) + w:uint(ID.CueClusterPosition, q[3] + shift) + w:close(tp) + w:close(cp) + end + w:close(c) + local cuesBuf = w:finish() + local nb = buffer.create(cuesAt + buffer.len(cuesBuf)) + buffer.copy(nb, 0, bodyBuf, 0, cuesAt) + buffer.copy(nb, cuesAt, cuesBuf) + bodyBuf = nb + end + + local out = Ebml.writer(buffer.len(bodyBuf) + 256) + local eb = out:open(ID.EBML) + out:uint(0x4286, 1) + out:uint(0x42F7, 1) + out:uint(0x42F2, 4) + out:uint(0x42F3, 8) + out:string(ID.DocType, if webm then "webm" else "matroska") + out:uint(0x4287, 4) + out:uint(0x4285, 2) + out:close(eb) + local seg = out:open(ID.Segment) + out:rawBuffer(head) + out:rawBuffer(bodyBuf) + out:close(seg) + return out:finish(), nil +end + +return Mux +end +__FILES["video/mkv/Parse"] = function() + +-- video/mkv/Parse: the Matroska / WebM demuxer: EBML header, Info / Tracks / Cues / Tags / chapter titles, Clusters +-- (SimpleBlock, BlockGroup, Xiph / EBML / fixed lacing, unknown sizes); timescale 1e9 / TimecodeScale. +local Err = __include("core/Err") +local Types = __include("Types") +local Ebml = __include("containers/Ebml") +local Demux = __include("containers/Demux") +local Video = __include("codecs/video/Video") +local Avi = __include("containers/Avi") +local QtPalette = __include("containers/IsoBmff/QtPalette") +local Deflate = __include("codecs/compress/Deflate") + +local Parse = {} + +-- element IDs +local ID = { + EBML = 0x1A45DFA3, + DocType = 0x4282, + Segment = 0x18538067, + SeekHead = 0x114D9B74, + Info = 0x1549A966, + TimecodeScale = 0x2AD7B1, + Duration = 0x4489, + Title = 0x7BA9, + MuxingApp = 0x4D80, + WritingApp = 0x5741, + DateUTC = 0x4461, + Tracks = 0x1654AE6B, + TrackEntry = 0xAE, + TrackNumber = 0xD7, + TrackUID = 0x73C5, + TrackType = 0x83, + FlagEnabled = 0xB9, + FlagDefault = 0x88, + FlagForced = 0x55AA, + FlagLacing = 0x9C, + DefaultDuration = 0x23E383, + Name = 0x536E, + Language = 0x22B59C, + LanguageBCP47 = 0x22B59D, + CodecID = 0x86, + CodecPrivate = 0x63A2, + CodecDelay = 0x56AA, + SeekPreRoll = 0x56BB, + Video = 0xE0, + PixelWidth = 0xB0, + PixelHeight = 0xBA, + DisplayWidth = 0x54B0, + DisplayHeight = 0x54BA, + ColourSpace = 0x2EB524, + Audio = 0xE1, + SamplingFrequency = 0xB5, + OutputSamplingFrequency = 0x78B5, + Channels = 0x9F, + BitDepth = 0x6264, + ContentEncodings = 0x6D80, + ContentEncoding = 0x6240, + ContentEncodingType = 0x5033, + ContentEncodingScope = 0x5032, + ContentCompression = 0x5034, + ContentCompAlgo = 0x4254, + ContentCompSettings = 0x4255, + ContentEncryption = 0x5035, + Cluster = 0x1F43B675, + Timecode = 0xE7, + SimpleBlock = 0xA3, + BlockGroup = 0xA0, + Block = 0xA1, + BlockDuration = 0x9B, + ReferenceBlock = 0xFB, + DiscardPadding = 0x75A2, + Cues = 0x1C53BB6B, + CuePoint = 0xBB, + CueTime = 0xB3, + CueTrackPositions = 0xB7, + CueTrack = 0xF7, + CueClusterPosition = 0xF1, + CueRelativePosition = 0xF0, + Tags = 0x1254C367, + Tag = 0x7373, + SimpleTag = 0x67C8, + TagName = 0x45A3, + TagString = 0x4487, + Targets = 0x63C0, + Chapters = 0x1043A770, + Attachments = 0x1941A469, + Void = 0xEC, + Crc32 = 0xBF, +} +Parse.ID = ID + +-- the top-level children of a Segment (an unknown-size Cluster ends where one of these starts) +local TOP: { [number]: boolean } = { + [ID.SeekHead] = true, + [ID.Info] = true, + [ID.Tracks] = true, + [ID.Cluster] = true, + [ID.Cues] = true, + [ID.Tags] = true, + [ID.Chapters] = true, + [ID.Attachments] = true, + [ID.Segment] = true, + [ID.EBML] = true, +} + +-- 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", + A_FLAC = "flac", + ["A_MPEG/L3"] = "mp3", + ["A_MPEG/L2"] = "mp2", + ["A_MPEG/L1"] = "mp1", + A_AAC = "aac", + ["A_AAC/MPEG4/LC"] = "aac", + ["A_AAC/MPEG4/LC/SBR"] = "aac", + ["A_AAC/MPEG2/LC"] = "aac", + A_AC3 = "ac3", + A_EAC3 = "eac3", + A_DTS = "dts", + A_ALAC = "alac", + A_TTA1 = "tta", + A_WAVPACK4 = "wavpack", + ["A_MS/ACM"] = "acm", +} +local SUBS: { [string]: string } = { + ["S_TEXT/UTF8"] = "text", + ["S_TEXT/ASCII"] = "text", + ["S_TEXT/WEBVTT"] = "webvtt", + ["S_TEXT/ASS"] = "ass", + ["S_TEXT/SSA"] = "ssa", + ["S_ASS"] = "ass", + ["S_SSA"] = "ssa", + ["S_VOBSUB"] = "dvdsub", + ["S_HDMV/PGS"] = "pgs", +} + +local function codecFor(id: string, kind: string, bits: number?): string + if kind == "video" then + return Video.fromMatroska(id) or string.lower((string.gsub(id, "^V_", ""))) + end + if id == "A_PCM/INT/LIT" then + return if bits == 8 then "pcm_u8" else "pcm_s" .. (bits or 16) .. "le" + elseif id == "A_PCM/INT/BIG" then + return if bits == 8 then "pcm_u8" else "pcm_s" .. (bits or 16) .. "be" + elseif id == "A_PCM/FLOAT/IEEE" then + return "pcm_f" .. (bits or 32) .. "le" + end + return AUDIO[id] or SUBS[id] or string.lower((string.gsub(id, "^[AS]_", ""))) +end +Parse.codecFor = codecFor + +-- V_MS/VFW/FOURCC (CodecPrivate = a BITMAPINFOHEADER) and V_QUICKTIME (CodecPrivate = a QuickTime sample +-- description, sometimes without its size field): the codec from the FourCC, the depth and palette, the extradata +local function vfwOrQuickTime(t: any, codecId: string, priv: buffer) + local n = buffer.len(priv) + if codecId == "V_MS/VFW/FOURCC" then + local bi = Avi.bitmapInfo(priv) + if bi then + t.codec = Video.fromFourcc(bi.compression) or t.codec + t.codecTag = bi.compression + t.bitsPerPixel = bi.bits + t.palette = bi.palette + t.config = bi.extra + end + elseif codecId == "V_QUICKTIME" and n >= 21 then + local desc = priv + if Video.fromFourcc(buffer.readstring(priv, 0, 4)) then + desc = buffer.create(n + 4) + local size = n + 4 + buffer.writeu8(desc, 0, size // 16777216 % 256) + buffer.writeu8(desc, 1, size // 65536 % 256) + buffer.writeu8(desc, 2, size // 256 % 256) + buffer.writeu8(desc, 3, size % 256) + buffer.copy(desc, 4, priv, 0, n) + end + local fcc = buffer.readstring(desc, 4, 4) + t.codec = Video.fromFourcc(fcc) or t.codec + t.codecTag = fcc + local depth, pal = QtPalette.read(desc, 0, buffer.len(desc), t.codec) + t.bitsPerPixel = depth + t.palette = pal + end +end + +type TrackInfo = Types.Track & { strip: buffer?, lacing: boolean?, defaultDurationNs: number? } + +local function parseVideo(buf: buffer, off: number, len: number, t: any) + for id, o, n in Ebml.children(buf, off, off + len) do + if id == ID.PixelWidth then + t.width = Ebml.uint(buf, o, n) + elseif id == ID.PixelHeight then + t.height = Ebml.uint(buf, o, n) + elseif id == ID.DisplayWidth then + t.displayWidth = Ebml.uint(buf, o, n) + elseif id == ID.DisplayHeight then + t.displayHeight = Ebml.uint(buf, o, n) + elseif id == ID.ColourSpace then + t.colourSpace = buffer.readstring(buf, o, math.min(n, 4)) + end + end +end + +local function parseAudio(buf: buffer, off: number, len: number, t: any) + for id, o, n in Ebml.children(buf, off, off + len) do + if id == ID.SamplingFrequency then + t.sampleRate = Ebml.float(buf, o, n) + elseif id == ID.OutputSamplingFrequency then + t.outputSampleRate = Ebml.float(buf, o, n) + elseif id == ID.Channels then + t.channels = Ebml.uint(buf, o, n) + elseif id == ID.BitDepth then + t.bitsPerSample = Ebml.uint(buf, o, n) + end + end +end + +-- ContentEncodings: header stripping (algo 3) and zlib (algo 0); not bzip / lzo or encryption +local function parseEncodings(buf: buffer, off: number, len: number, t: any): string? + for id, o, n in Ebml.children(buf, off, off + len) do + if id == ID.ContentEncoding then + local etype = 0 + local scope = 1 + for id2, o2, n2 in Ebml.children(buf, o, o + n) do + if id2 == ID.ContentEncodingScope then + scope = Ebml.uint(buf, o2, n2) + elseif id2 == ID.ContentEncodingType then + etype = Ebml.uint(buf, o2, n2) + elseif id2 == ID.ContentCompression then + local algo, settings = 0, nil + for id3, o3, n3 in Ebml.children(buf, o2, o2 + n2) do + if id3 == ID.ContentCompAlgo then + algo = Ebml.uint(buf, o3, n3) + elseif id3 == ID.ContentCompSettings then + settings = Ebml.binary(buf, o3, n3) + end + end + if algo == 3 then + t.strip = settings + elseif algo == 0 then + t.zlib = scope -- 1: frames, 2: CodecPrivate + else + return "content compression algorithm " .. algo + end + elseif id2 == ID.ContentEncryption then + return "encrypted track" + end + end + if etype ~= 0 then + return "encrypted track" + end + end + end + return nil +end + +local function parseTracks(buf: buffer, off: number, len: number, scaleNs: number): ({ TrackInfo }, { [number]: string }) + local tracks: { TrackInfo } = {} + local problems: { [number]: string } = {} + for id, o, n in Ebml.children(buf, off, off + len) do + if id == ID.TrackEntry then + local t: any = { id = 0, kind = "data", codec = "", timescale = 1e9 / scaleNs, default = true, lacing = true, language = "eng" } + local ttype, codecId = 0, "" + local problem: string? = nil + for id2, o2, n2 in Ebml.children(buf, o, o + n) do + if id2 == ID.TrackNumber then + t.id = Ebml.uint(buf, o2, n2) + elseif id2 == ID.TrackUID then + t.uid = Ebml.uint(buf, o2, n2) + elseif id2 == ID.TrackType then + ttype = Ebml.uint(buf, o2, n2) + elseif id2 == ID.FlagDefault then + t.default = Ebml.uint(buf, o2, n2) ~= 0 + elseif id2 == ID.FlagEnabled then + t.enabled = Ebml.uint(buf, o2, n2) ~= 0 + elseif id2 == ID.FlagLacing then + t.lacing = Ebml.uint(buf, o2, n2) ~= 0 + elseif id2 == ID.DefaultDuration then + t.defaultDurationNs = Ebml.uint(buf, o2, n2) + elseif id2 == ID.Name then + t.name = Ebml.string(buf, o2, n2) + elseif id2 == ID.Language then + t.language = Ebml.string(buf, o2, n2) + elseif id2 == ID.CodecID then + codecId = Ebml.string(buf, o2, n2) + elseif id2 == ID.CodecPrivate then + t.config = Ebml.binary(buf, o2, n2) + elseif id2 == ID.CodecDelay then + t.codecDelay = Ebml.uint(buf, o2, n2) / 1e9 + elseif id2 == ID.SeekPreRoll then + t.seekPreRoll = Ebml.uint(buf, o2, n2) / 1e9 + elseif id2 == ID.Video then + parseVideo(buf, o2, n2, t) + elseif id2 == ID.Audio then + parseAudio(buf, o2, n2, t) + elseif id2 == ID.ContentEncodings then + problem = parseEncodings(buf, o2, n2, t) + end + end + if t.zlib and bit32.band(t.zlib, 2) ~= 0 and t.config then + local c = Deflate.zlib(t.config) + if c then + t.config = c + else + problem = "bad zlib-compressed CodecPrivate" + end + end + t.kind = if ttype == 1 then "video" elseif ttype == 2 then "audio" elseif ttype == 17 then "subtitle" else "data" + t.codecTag = codecId + t.codec = codecFor(codecId, t.kind, t.bitsPerSample) + local cfg: buffer? = t.config + if t.kind == "video" and cfg then + vfwOrQuickTime(t, codecId, cfg) + end + if t.kind == "audio" then + t.sampleRate = t.sampleRate or 8000 + t.channels = t.channels or 1 + end + if t.defaultDurationNs and t.defaultDurationNs > 0 and t.kind == "video" then + t.frameRate = 1e9 / t.defaultDurationNs + end + if t.id > 0 then + table.insert(tracks, t) + if problem then + problems[t.id] = problem + end + end + end + end + return tracks, problems +end + +local function parseInfo(buf: buffer, off: number, len: number, meta: { [string]: any }): (number, number?) + local scale, duration = 1000000, nil + for id, o, n in Ebml.children(buf, off, off + len) do + if id == ID.TimecodeScale then + scale = Ebml.uint(buf, o, n) + elseif id == ID.Duration then + duration = Ebml.float(buf, o, n) + elseif id == ID.Title then + meta.title = Ebml.string(buf, o, n) + elseif id == ID.MuxingApp then + meta.muxingApp = Ebml.string(buf, o, n) + elseif id == ID.WritingApp then + meta.writingApp = Ebml.string(buf, o, n) + end + end + if scale <= 0 then + scale = 1000000 + end + return scale, duration +end + +local function parseCues(buf: buffer, off: number, len: number, segData: number): { { time: number, track: number, position: number } } + local cues = {} + for id, o, n in Ebml.children(buf, off, off + len) do + if id == ID.CuePoint then + local time = 0 + local positions = {} + for id2, o2, n2 in Ebml.children(buf, o, o + n) do + if id2 == ID.CueTime then + time = Ebml.uint(buf, o2, n2) + elseif id2 == ID.CueTrackPositions then + local tr, pos = 0, 0 + for id3, o3, n3 in Ebml.children(buf, o2, o2 + n2) do + if id3 == ID.CueTrack then + tr = Ebml.uint(buf, o3, n3) + elseif id3 == ID.CueClusterPosition then + pos = Ebml.uint(buf, o3, n3) + end + end + table.insert(positions, { tr, pos }) + end + end + for _, p in positions do + table.insert(cues, { time = time, track = p[1], position = segData + p[2] }) + end + end + end + return cues +end + +local function parseTags(buf: buffer, off: number, len: number, meta: { [string]: any }) + local tags = meta.tags or {} + meta.tags = tags + for id, o, n in Ebml.children(buf, off, off + len) do + if id == ID.Tag then + for id2, o2, n2 in Ebml.children(buf, o, o + n) do + if id2 == ID.SimpleTag then + local name, value = nil, nil + for id3, o3, n3 in Ebml.children(buf, o2, o2 + n2) do + if id3 == ID.TagName then + name = Ebml.string(buf, o3, n3) + elseif id3 == ID.TagString then + value = Ebml.string(buf, o3, n3) + end + end + if name and value and tags[string.lower(name)] == nil then + tags[string.lower(name)] = value + end + end + end + end + end +end + +type Ctx = { + buf: buffer, + dmx: any, + byNum: { [number]: TrackInfo }, + scaleNs: number, + err: string?, + maxPackets: number, +} + +-- Block / SimpleBlock: track, relative timecode, flags, lacing +local function block(ctx: Ctx, off: number, len: number, clusterTime: number, simple: boolean, keyHint: boolean?, durTicks: number?, discardNs: number?) + local buf = ctx.buf + local limit = off + len + local tn, tl = Ebml.vint(buf, off, limit) + if not tn or not tl or tn < 0 or off + tl + 3 > limit then + return + end + local p = off + tl + local rel = buffer.readu8(buf, p) * 256 + buffer.readu8(buf, p + 1) + if rel >= 32768 then + rel -= 65536 + end + local flags = buffer.readu8(buf, p + 2) + p += 3 + local t = ctx.byNum[tn] + if not t then + return + end + local key = if simple then bit32.band(flags, 0x80) ~= 0 else (keyHint ~= false) + if t.kind == "audio" or t.kind == "subtitle" then + key = true + end + local pts = clusterTime + rel + local lacing = bit32.band(bit32.rshift(flags, 1), 3) + local sizes: { number } = {} + if lacing == 0 then + sizes[1] = limit - p + else + if p >= limit then + return + end + local count = buffer.readu8(buf, p) + 1 + p += 1 + if lacing == 1 then -- Xiph + local total = 0 + for k = 1, count - 1 do + local s = 0 + while true do + if p >= limit then + return + end + local b = buffer.readu8(buf, p) + p += 1 + s += b + if b ~= 255 then + break + end + end + sizes[k] = s + total += s + end + sizes[count] = limit - p - total + elseif lacing == 3 then -- EBML + local s, l = Ebml.vint(buf, p, limit) + if not s or not l or s < 0 then + return + end + p += l + sizes[1] = s + local total = s + for k = 2, count - 1 do + local d, dl = Ebml.svint(buf, p, limit) + if not d or not dl then + return + end + p += dl + s += d + if s < 0 then + return + end + sizes[k] = s + total += s + end + sizes[count] = limit - p - total + else -- fixed + local each = (limit - p) // count + for k = 1, count do + sizes[k] = each + end + end + if sizes[count] < 0 then + return + end + end + -- frames after the first of a lace: the track's default duration + local stepTicks = 0 + if t.defaultDurationNs and t.defaultDurationNs > 0 then + stepTicks = t.defaultDurationNs / ctx.scaleNs + elseif durTicks and #sizes > 0 then + stepTicks = durTicks / #sizes + end + local dmx = ctx.dmx + for k, s in sizes do + if p + s > limit then + return + end + if dmx.n >= ctx.maxPackets then + ctx.err = "too many packets" + return + end + local d = if #sizes == 1 then durTicks else (if stepTicks > 0 then stepTicks else nil) + local kf = key and (k == 1 or t.kind ~= "video") + local strip = t.strip + local z = (t :: any).zlib + if z and bit32.band(z, 1) ~= 0 then + local out = Deflate.zlib(buf, p, s) + if out then + dmx:addData(tn, pts + (k - 1) * stepTicks, nil, d, kf, out) + end + elseif strip then + local nb = buffer.create(buffer.len(strip) + s) + buffer.copy(nb, 0, strip) + buffer.copy(nb, buffer.len(strip), buf, p, s) + dmx:addData(tn, pts + (k - 1) * stepTicks, nil, d, kf, nb) + else + dmx:add(tn, pts + (k - 1) * stepTicks, nil, d, kf, p, s) + end + if discardNs and k == #sizes then + dmx:setExtra("discardPadding", discardNs / 1e9) + end + p += s + end +end + +local function cluster(ctx: Ctx, off: number, limit: number, unknown: boolean): number + local buf = ctx.buf + local pos = off + local time = 0 + while pos < limit and not ctx.err do + local id, size, data = Ebml.header(buf, pos, limit) + if not id or not size or not data then + return limit + end + if unknown and TOP[id] then + return pos + end + if size < 0 then + size = limit - data -- an unknown-size child: to the end + end + if data + size > limit then + size = limit - data + end + if id == ID.Timecode then + time = Ebml.uint(buf, data, size) + elseif id == ID.SimpleBlock then + block(ctx, data, size, time, true) + elseif id == ID.BlockGroup then + local bo, bl = -1, 0 + local ref, dur, discard = false, nil, nil + for id2, o2, n2 in Ebml.children(buf, data, data + size) do + if id2 == ID.Block then + bo, bl = o2, n2 + elseif id2 == ID.ReferenceBlock then + ref = true + elseif id2 == ID.BlockDuration then + dur = Ebml.uint(buf, o2, n2) + elseif id2 == ID.DiscardPadding then + discard = Ebml.int(buf, o2, n2) + end + end + if bo >= 0 then + block(ctx, bo, bl, time, false, not ref, dur, discard) + end + end + pos = data + size + end + return pos +end + +type Options = { maxPackets: number? } + +function Parse.docType(buf: buffer, base: number, limit: number): (string?, any, number?) + local id, size, data = Ebml.header(buf, base, limit) + if id ~= ID.EBML or not size or not data then + return nil, Err.new(Err.CORRUPT, "not an EBML file", base) + end + if size < 0 then + return nil, Err.new(Err.CORRUPT, "EBML header of unknown size", base) + end + local docType = "matroska" + for cid, o, n in Ebml.children(buf, data, math.min(limit, data + size)) do + if cid == ID.DocType then + docType = Ebml.string(buf, o, n) + end + end + return docType, size, data +end + +function Parse.parse(buf: buffer, base: number, limit: number, opts: Options?): (any, Err.Err?) + local docType, size, data = Parse.docType(buf, base, limit) + if not docType then + return nil, size + end + if docType ~= "matroska" and docType ~= "webm" then + return nil, Err.new(Err.UNSUPPORTED, "EBML document type " .. docType) + end + local pos = data + size + local segData, segEnd = -1, limit + while pos < limit do + local sid, ssize, sdata = Ebml.header(buf, pos, limit) + if not sid or not ssize or not sdata then + break + end + if sid == ID.Segment then + segData = sdata + segEnd = if ssize < 0 or sdata + ssize > limit then limit else sdata + ssize + break + end + if ssize < 0 then + break + end + pos = sdata + ssize + end + if segData < 0 then + return nil, Err.new(Err.TRUNCATED, "no Segment") + end + local meta: { [string]: any } = { docType = docType } + local scaleNs, duration = 1000000, nil :: number? + local tracks: { TrackInfo } = {} + local problems: { [number]: string } = {} + local cuesAt: { number } = {} + local clusters: { { number } } = {} + -- first pass: the top-level elements (clusters are walked after Info / Tracks, which may come later via SeekHead) + pos = segData + while pos < segEnd do + local cid, csize, cdata = Ebml.header(buf, pos, segEnd) + if not cid or not csize or not cdata then + break + end + local unknown = csize < 0 + local cend = if unknown or cdata + csize > segEnd then segEnd else cdata + csize + if cid == ID.Info then + local d + scaleNs, d = parseInfo(buf, cdata, cend - cdata, meta) + duration = d + elseif cid == ID.Tracks then + tracks, problems = parseTracks(buf, cdata, cend - cdata, scaleNs) + elseif cid == ID.Cluster then + if unknown then + local p = cdata + while p < segEnd do + local xid, xsize, xdata = Ebml.header(buf, p, segEnd) + if not xid or not xsize or not xdata or TOP[xid] then + break + end + if xsize < 0 then + p = segEnd + break + end + p = math.min(segEnd, xdata + xsize) + end + cend = p + end + table.insert(clusters, { cdata, cend }) + elseif cid == ID.Cues then + table.insert(cuesAt, cdata) + table.insert(cuesAt, cend - cdata) + elseif cid == ID.Tags then + parseTags(buf, cdata, cend - cdata, meta) + end + if cend <= pos then + break + end + pos = cend + end + if #tracks == 0 then + return nil, Err.new(Err.CORRUPT, "no tracks") + end + -- track timescales follow the final TimecodeScale (Info may follow Tracks) + local byNum: { [number]: TrackInfo } = {} + for _, t in tracks do + t.timescale = 1e9 / scaleNs + byNum[t.id] = t + end + local dmx = Demux.new(if docType == "webm" then "webm" else "mkv", tracks :: any, buf, meta) + local ctx: Ctx = { buf = buf, dmx = dmx, byNum = byNum, scaleNs = scaleNs, err = nil, maxPackets = opts and opts.maxPackets or 2 ^ 24 } + for _, c in clusters do + cluster(ctx, c[1], c[2], false) + if ctx.err then + return nil, Err.new(Err.LIMIT, ctx.err) + end + end + if duration then + dmx.duration = duration * scaleNs / 1e9 + end + local cues = {} + for k = 1, #cuesAt, 2 do + for _, c in parseCues(buf, cuesAt[k], cuesAt[k + 1], segData) do + c.time = c.time * scaleNs / 1e9 + table.insert(cues, c) + end + end + meta.cues = cues + meta.timecodeScale = scaleNs + for tid, msg in problems do + local t = byNum[tid] + t.unsupported = msg + end + dmx:finish() + return dmx, nil +end + +return Parse +end +__FILES["video/mp4"] = function() + +-- video/mp4: MP4 / M4V / MOV / 3GP (ISO/IEC 14496-12 / 14496-14, QuickTime), on containers/IsoBmff. Reads every +-- track into a Demuxer (pts = dts + composition offset, moved by the edit list; fragments too). Writes MP4 or MOV: +-- video copied, else MJPEG; audio copied, else PCM s16 (MOV). Not supported: fragmented writing, timed text, DRM. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local IsoBmff = __include("containers/IsoBmff") +local Demux = __include("containers/Demux") +local Video = __include("codecs/video/Video") +local Source = __include("codecs/video/Video/Source") + +-- ------------------------------------------------------------------------------------------------ contract +local Mp4 = { + name = "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/Video", "codecs/video/Video/Source" }, + caps = { decode = true, encode = true, streaming = true, remux = true, video = { "mjpeg", "mpeg1", "mpeg2", "h264" }, audio = true, fragments = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type OpenOptions = { + rgba: boolean?, + track: number?, -- default: the first video track + audio: boolean?, + maxPixels: number?, + maxSamples: number?, + openAudio: any?, -- set by the api +} +type EncodeOptions = { + format: string?, -- "mov": QuickTime (brand 'qt '); else MP4 (brand 'isom') + quality: number?, -- default 90 + reencode: boolean?, + video: boolean?, + audio: boolean?, -- true: fail when the audio cannot be written +} + +-- ------------------------------------------------------------------------------------------------ constants +local IMAGE_BRANDS = { avif = true, avis = true, heic = true, heix = true, mif1 = true, msf1 = true, ["crx "] = true } +local AUDIO_BRANDS = { ["M4A "] = true, ["M4B "] = true, ["M4P "] = true } +-- copied video codecs -> sample entry (MP4 / MOV) +local VIDEO_ENTRY: { [string]: string } = { h264 = "avc1", hevc = "hvc1", av1 = "av01", vp9 = "vp09" } +local AUDIO_ENTRY: { [string]: string } = { aac = "mp4a", alac = "alac", opus = "Opus", flac = "fLaC", mp3 = "mp4a" } + +-- ------------------------------------------------------------------------------------------------ sniff +function Mp4.sniff(r: Bytes.Reader): number + local brand = IsoBmff.sniff(r) + if brand == nil or IMAGE_BRANDS[brand] then + return 0 + end + if AUDIO_BRANDS[brand] then + return 0.2 + end + if brand == "M4V " then + return 0.9 + end + return if brand == "" then 0.6 else 0.8 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- OpusHead (RFC 7845, little-endian) from an ISO dOps box payload (big-endian) +local function opusHead(d: buffer): buffer? + if buffer.len(d) < 11 then + return nil + end + local w = Bytes.writer(19 + buffer.len(d)) + w:string("OpusHead") + w:u8(1) + local ch = buffer.readu8(d, 1) + w:u8(ch) + w:u16le(buffer.readu8(d, 2) * 256 + buffer.readu8(d, 3)) + w:u32le(((buffer.readu8(d, 4) * 256 + buffer.readu8(d, 5)) * 256 + buffer.readu8(d, 6)) * 256 + buffer.readu8(d, 7)) + w:u16le(buffer.readu8(d, 8) * 256 + buffer.readu8(d, 9)) + local family = buffer.readu8(d, 10) + w:u8(family) + if family ~= 0 and buffer.len(d) >= 13 + ch then + w:bytes(d, 11, 2 + ch) -- stream count, coupled count, mapping + end + return w:finish() +end + +local function pcmCodec(t: any): string + local p = t.pcm + local bits = if p then p.bits else (t.bitsPerSample or 16) + if p and p.float then + return "pcm_f" .. bits .. (if p.little then "le" else "be") + end + if bits == 8 then + return if t.entry == "raw " then "pcm_u8" else "pcm_s8" + end + return "pcm_s" .. bits .. (if p == nil or p.little then "le" else "be") +end + +function Mp4.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) + local ok, movie, err = pcall(IsoBmff.parse, r, opts and opts.maxSamples and { maxSamples = opts.maxSamples } or nil) + if not ok then + return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(movie)) + end + if not movie then + return nil, err + end + local tracks: { Types.Track } = {} + local src = {} + for _, it in movie.tracks do + local t: any = { + id = it.id, + kind = it.kind, + codec = it.codec, + codecTag = it.entry, + timescale = it.timescale, + duration = it.duration, + language = it.language, + width = it.width, + height = it.height, + sampleRate = it.sampleRate, + channels = it.channels, + bitsPerSample = it.bitsPerSample, + config = it.config, + default = true, + bitsPerPixel = it.bitsPerPixel, + palette = it.palette, + } + if it.kind == "video" then + if not Video.entry(t.codec) then + t.codec = Video.fromFourcc(it.entry) or t.codec + end + if it.sampleCount > 0 and it.duration > 0 then + t.frameRate = it.sampleCount / it.duration + end + elseif it.kind == "audio" then + if it.codec == "pcm" then + t.codec = pcmCodec(it) + elseif it.codec == "ulaw" then + t.codec = "pcm_mulaw" + elseif it.codec == "alaw" then + t.codec = "pcm_alaw" + elseif it.codec == "opus" and it.config then + t.config = opusHead(it.config) + end + if it.skip and it.skip > 0 then + t.codecDelay = it.skip / it.timescale -- AAC priming: dropped like ffmpeg + end + if it.playDuration and it.playDuration > 0 and it.timescale > 0 then + t.playDuration = it.playDuration / it.timescale -- the edit's length: the end padding is not played + end + end + table.insert(tracks, t) + table.insert(src, it) + end + local dmx = Demux.new(if movie.brand == "qt " then "mov" else "mp4", tracks, r.buf, { brand = movie.brand }) + local items: { { number } } = {} + for k, it in src do + -- the edit list moves presentation times: minus the first edit's media time (video: the B-frame delay; audio + -- keeps it as its codec delay), plus an initial empty edit (converted to media ticks) + local shift = 0 + if it.kind == "video" then + shift = -(it.skip or 0) + end + if it.delay and it.delay > 0 and movie.timescale and movie.timescale > 0 then + shift += it.delay / movie.timescale * it.timescale + end + for i = 1, it.sampleCount do + table.insert(items, { it.offsets[i], k, i, shift }) + end + end + table.sort(items, function(a: { number }, b: { number }): boolean + return a[1] < b[1] + end) + for _, e in items do + local it = src[e[2]] + local i = e[3] + local dts = it.dts[i] + local pts = dts + (if it.cts then it.cts[i] or 0 else 0) + e[4] + dmx:add(it.id, pts, dts + e[4], it.durations[i], it.sync == nil or it.sync[i] == true, it.offsets[i], it.sizes[i]) + end + dmx:finish() + return dmx, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- OpusHead -> dOps payload +local function dOps(head: buffer?): buffer? + if not head or buffer.len(head) < 19 then + return nil + end + local w = Bytes.writer(16) + w:u8(0) + local ch = buffer.readu8(head, 9) + w:u8(ch) + w:u16be(buffer.readu16(head, 10)) + w:u32be(buffer.readu32(head, 12)) + w:u16be(buffer.readu16(head, 16)) + local family = buffer.readu8(head, 18) + w:u8(family) + if family ~= 0 and buffer.len(head) >= 21 + ch then + w:bytes(head, 19, 2 + ch) + end + return w:finish() +end + +function Mp4.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: any = table.clone(opts or {}) + o.quality = o.quality or 90 + local mov = type(o.format) == "string" and (string.lower(o.format) == "mov" or string.lower(o.format) == "qt") + local vcopy: { [string]: boolean } = { mjpeg = true } + for id in VIDEO_ENTRY do + vcopy[id] = true + end + local acopy: { [string]: boolean } = {} + for id in AUDIO_ENTRY do + acopy[id] = true + end + acopy.pcm_s16le = mov + local streams, err = Source.streams(value, o, { + video = { copy = vcopy, encode = "mjpeg" }, + audio = { copy = acopy, pcm = mov }, + }) + if not streams then + return nil, err + end + local mtracks = {} + for _, s in streams do + local scale = if s.kind == "audio" then math.floor((s.sampleRate or 48000) + 0.5) else 90000 + if s.kind == "video" and s.track and s.track.timescale and s.copied and s.track.timescale == math.floor(s.track.timescale) then + scale = s.track.timescale + end + local samples, durations, cts, sync = {}, {}, {}, {} + local anyCts = false + local firstDts = nil :: number? + for i, p in s.packets do + samples[i] = p.data + local dts = p.dts or p.pts + firstDts = firstDts or dts + local nextP = s.packets[i + 1] + local d = if nextP then (nextP.dts or nextP.pts) - dts else p.duration + durations[i] = math.max(0, math.floor(d * scale + 0.5)) + local c = math.floor((p.pts - dts) * scale + 0.5) + cts[i] = c + if c ~= 0 then + anyCts = true + end + if p.keyframe then + sync[i] = true + end + end + -- an edit list keeps the source's start: video decode times before 0 (B-frame delay), audio codec delay + local skip = 0 + if firstDts and firstDts < 0 then + skip = math.floor(-firstDts * scale + 0.5) + end + if s.kind == "audio" and s.track and s.track.codecDelay and s.copied then + skip = math.floor(s.track.codecDelay * scale + 0.5) + end + -- video: the skipped decode delay is a composition shift, every frame still plays (ffmpeg drops the frames an + -- edit cuts); audio: the codec delay samples are not played + local playDuration = nil + if s.kind == "video" and skip > 0 then + playDuration = 0 + for _, d in durations do + playDuration += d + end + elseif s.kind == "audio" and s.track and s.copied and type(s.track.playDuration) == "number" then + playDuration = math.floor(s.track.playDuration * scale + 0.5) -- keep the source's end trim + end + local t: any = { + kind = s.kind, + timescale = scale, + skip = if skip > 0 then skip else nil, + playDuration = playDuration, + samples = samples, + durations = durations, + cts = if anyCts then cts else nil, + sync = sync, + width = s.width, + height = s.height, + sampleRate = s.sampleRate and math.floor(s.sampleRate + 0.5), + channels = s.channels, + } + if s.kind == "video" then + if s.codec == "mjpeg" then + t.entry = if mov then "jpeg" else "mp4v" + if not mov then + t.objectType = 0x6C + t.configBox = "esds" + t.config = buffer.create(0) + end + else + t.entry = VIDEO_ENTRY[s.codec] + t.config = s.config + end + else + if s.codec == "pcm_s16le" then + t.entry = "sowt" + t.bitsPerSample = 16 + else + t.entry = AUDIO_ENTRY[s.codec] + t.config = if s.codec == "opus" then dOps(s.config) else s.config + if s.codec == "mp3" then + t.objectType = 0x6B + t.configBox = "esds" + t.config = buffer.create(0) + end + end + end + if not t.entry then + return nil, Err.new(Err.UNSUPPORTED, "no sample entry for " .. s.kind .. " codec " .. s.codec) + end + table.insert(mtracks, t) + end + return IsoBmff.mux({ brand = if mov then "qt " else "isom", compatible = if mov then { "qt " } else { "isom", "iso2", "mp41" }, tracks = mtracks }) +end + +-- ------------------------------------------------------------------------------------------------ open +function Mp4.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) + local dmx, err = Mp4.demux(r, opts) + if not dmx then + return nil, err + end + return Video.open(dmx, opts :: Video.OpenOptions?) +end + +return Mp4 +end +__FILES["video/mpegps"] = function() + +-- video/mpegps: MPEG program streams (ISO/IEC 11172-1, 13818-1: .mpg / .vob / VCD .dat), on containers/MpegPs and +-- containers/MpegEs: a packet per picture (the PTS of the PES it starts in, else from the GOP's temporal references), +-- audio packets = PES payloads; 90 kHz. Not supported: writing, H.264 in PS, DVD navigation packets. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local MpegPs = __include("containers/MpegPs") +local MpegEs = __include("containers/MpegEs") +local Demux = __include("containers/Demux") +local Video = __include("codecs/video/Video") + +-- ------------------------------------------------------------------------------------------------ contract +local Ps = { + name = "mpegps", + 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/Video" }, + caps = { decode = true, encode = false, streaming = true, video = { "mpeg1", "mpeg2" }, audio = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type OpenOptions = { + rgba: boolean?, + track: number?, -- 0xE0..; default: the first video stream + audio: boolean?, + maxPixels: number?, + openAudio: any?, -- set by the api +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Ps.sniff(r: Bytes.Reader): number + if r:peek(4) == "\0\0\1\186" then + return 0.9 + end + if r:peek(4) == "\0\0\1\179" then + return 0.5 -- an MPEG-1 / 2 video elementary stream (sequence header) + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function videoPackets(dmx: any, buf: buffer, s: MpegPs.Stream, t: any) + local total = 0 + for _, p in s.pes do + total += p.size + end + local es = buffer.create(total) + local starts: { number } = {} + local o = 0 + for i, p in s.pes do + starts[i] = o + buffer.copy(es, o, buf, p.offset, p.size) + o += p.size + end + local info = MpegEs.info(es, 0, total) + if info then + t.width, t.height, t.frameRate = info.width, info.height, info.frameRate + if info.mpeg2 then + t.codec = "mpeg2" + end + end + local pics = MpegEs.pictures(es, 0, total) + local fd = if t.frameRate and t.frameRate > 0 then 90000 / t.frameRate else 3600 + -- the PTS of the PES each picture starts in (only the first picture starting in a PES takes it) + local k = 1 + local used: { [number]: boolean } = {} + local ptsOf: { [number]: number } = {} + for i, pic in pics do + while k < #s.pes and starts[k + 1] <= pic.offset do + k += 1 + end + -- a PES whose payload starts inside this picture's headers also labels it + local pes = s.pes[k] + if pes and pes.pts and not used[k] then + used[k] = true + ptsOf[i] = pes.pts + end + end + -- fill the rest from the temporal references of each GOP (an elementary stream without any PTS: from 0) + local anchorPts, anchorTr = nil :: number?, 0 + local lastPts = nil :: number? + local timed = next(ptsOf) ~= nil + local count = 0 + for i, pic in pics do + if pic.gop then + anchorPts = nil + if not timed then + anchorPts, anchorTr = count * fd, 0 + end + end + if not timed and anchorPts == nil then + anchorPts, anchorTr = count * fd, pic.temporal + end + count += 1 + local pts = ptsOf[i] + if pts then + anchorPts, anchorTr = pts, pic.temporal + elseif anchorPts then + pts = anchorPts + (pic.temporal - anchorTr) * fd + elseif lastPts then + pts = lastPts + fd + end + if pts then + lastPts = pts + local d = buffer.create(pic.size) + buffer.copy(d, 0, es, pic.offset, pic.size) + dmx:addData(t.id, pts, nil, fd, pic.type == 1, d) + end + end +end + +function Ps.demux(r: Bytes.Reader, _opts: OpenOptions?): (any, Err.Err?) + if r:peek(4) == "\0\0\1\179" then + -- an MPEG-1 / 2 video elementary stream (.m1v): one video stream, no timestamps + local t: any = { id = 0xE0, kind = "video", codec = "mpeg1", codecTag = "es", timescale = 90000, streamId = 0xE0 } + local dmx = Demux.new("mpegps", { t }, r.buf, { elementary = true }) + videoPackets(dmx, r.buf, { id = 0xE0, kind = "video", codec = "mpeg1", pes = { { offset = r.base, size = r.limit - r.base } } }, t) + dmx:finish() + return dmx, nil + end + local ok, file, err = pcall(MpegPs.read, r.buf, r.base, r.limit) + if not ok then + return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(file)) + end + if not file then + return nil, err + end + local tracks: { Types.Track } = {} + for _, id in file.order do + local s = file.streams[id] + table.insert(tracks, { + id = id, + kind = s.kind :: any, + codec = s.codec, + 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 + local s = file.streams[id] + local t: any = tracks[i] + if t.kind == "video" and (t.codec == "mpeg1" or t.codec == "mpeg2") then + videoPackets(dmx, r.buf, s, t) + else + local last = nil :: number? + for _, p in s.pes do + local pts = p.pts or last + if pts and p.size > 0 then + last = pts + dmx:add(id, pts, p.dts, nil, true, p.offset, p.size) + end + end + if t.codec == "mp2" and #s.pes > 0 then + local p = s.pes[1] + local b = r.buf + for i2 = p.offset, math.min(p.offset + p.size, r.limit) - 2 do + if buffer.readu8(b, i2) == 0xFF and buffer.readu8(b, i2 + 1) >= 0xE0 then + local layer = (buffer.readu8(b, i2 + 1) // 2) % 4 + t.codec = if layer == 1 then "mp3" elseif layer == 3 then "mp1" else "mp2" + break + end + end + end + end + end + dmx:finish() -- (read() without a track gives the video packets first, then the audio ones) + return dmx, nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Ps.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) + local dmx, err = Ps.demux(r, opts) + if not dmx then + return nil, err + end + return Video.open(dmx, opts :: Video.OpenOptions?) +end + +return Ps +end +__FILES["video/mpegts"] = function() + +-- video/mpegts: MPEG transport streams (ISO/IEC 13818-1: .ts, .m2ts, HLS) over containers/MpegTs (from mpegts-luau); +-- one PES = one packet, 90 kHz; MPEG-1 / 2 (types 0x01 / 0x02, private ones told by an MPEG-2 sequence extension), +-- H.264, MP1-3 / ADTS AAC. Not supported: writing, scrambled streams, video PES before the first PTS (dropped). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local MpegTs = __include("containers/MpegTs") +local MpegEs = __include("containers/MpegEs") +local Demux = __include("containers/Demux") +local Video = __include("codecs/video/Video") + +-- ------------------------------------------------------------------------------------------------ contract +local Ts = { + name = "mpegts", + category = "video", + extensions = { "ts", "m2ts", "mts", "tsv" }, + mime = { "video/mp2t" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/MpegTs", "containers/MpegEs", "containers/Demux", "codecs/video/Video" }, + caps = { decode = true, encode = false, streaming = true, video = { "mpeg1", "mpeg2", "h264" }, audio = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type OpenOptions = { + rgba: boolean?, + track: number?, -- default: the first video stream of the PMT + audio: boolean?, + maxPixels: number?, + openAudio: any?, -- set by the api +} + +-- ------------------------------------------------------------------------------------------------ constants +local CODEC: { [string]: string } = { + mpeg1video = "mpeg1", + mpeg2video = "mpeg2", + mpegaudio = "mp2", + aac = "aac", + aac_latm = "aac_latm", + h264 = "h264", + hevc = "hevc", + mpeg4 = "mpeg4", + ac3 = "ac3", + eac3 = "eac3", +} + +-- ------------------------------------------------------------------------------------------------ sniff +-- 188 or 192 (M2TS): three sync bytes a packet apart (fewer in a short file) within the first 2 KB +local function packetSize(r: Bytes.Reader): (number, number) + local n = r:remaining() + for start = 0, math.min(n, 2048) - 1 do + if r:peekU8(start) == 0x47 then + for _, size in { 188, 192 } do + local hits, need = 0, math.min(3, (n - start - 1) // size + 1) + for k = 0, 2 do + local at = start + k * size + if at < n and r:peekU8(at) == 0x47 then + hits += 1 + end + end + if hits >= need and (need >= 2 or start == 0) then + if size == 192 and start >= 4 then + return 192, start - 4 + elseif size == 188 then + return 188, start + end + end + end + end + end + return 0, 0 +end + +function Ts.sniff(r: Bytes.Reader): number + local s, off = packetSize(r) + if s == 0 then + return 0 + end + if off > 0 then + return 0.6 + end + return if r:remaining() >= 3 * s then 0.9 else 0.5 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- the 188-byte packets of an M2TS file (192-byte packets: drop the 4-byte timestamps) +local function strip192(b: buffer, base: number, limit: number): buffer + local n = (limit - base) // 192 + local out = buffer.create(n * 188) + for i = 0, n - 1 do + buffer.copy(out, i * 188, b, base + i * 192 + 4, 188) + end + return out +end + +local function mpegAudioCodec(u: any): string + local d: buffer = u.data + for i = 0, math.min(buffer.len(d), 4096) - 2 do + if buffer.readu8(d, i) == 0xFF and buffer.readu8(d, i + 1) >= 0xE0 then + local layer = (buffer.readu8(d, i + 1) // 2) % 4 + return if layer == 1 then "mp3" elseif layer == 3 then "mp1" else "mp2" + end + end + return "mp2" +end + +function Ts.demux(r: Bytes.Reader, _opts: OpenOptions?): (any, Err.Err?) + local size, off = packetSize(r) + if size == 0 then + return nil, Err.new(Err.CORRUPT, "no transport stream sync", r.base) + end + local d = MpegTs.new() + if size == 192 then + local b = strip192(r.buf, r.base + off, r.limit) + d:push(b, 0, buffer.len(b)) + else + d:push(r.buf, r.base + off, r.limit - r.base - off) + end + d:flush() + local units = {} + while true do + local u = d:pull() + if u == nil then + break + end + table.insert(units, u) + end + if #units == 0 then + return nil, Err.new(Err.CORRUPT, "no PES units") + end + -- tracks: the PMT's streams, then PIDs found without one + local tracks: { Types.Track } = {} + local byPid: { [number]: any } = {} + local function track(pid: number, kind: string, codec: string, st: number, lang: string?): any + local t = byPid[pid] + if t then + return t + end + t = { + id = pid, + kind = if kind == "other" then "data" else kind, + codec = CODEC[codec] or codec, + codecTag = string.format("0x%02x", st), + timescale = 90000, + language = lang, + streamType = st, + } + byPid[pid] = t + table.insert(tracks, t :: Types.Track) + return t + end + for _, s in d.streams do + track(s.pid, s.kind, s.codec, s.streamType, s.language) + end + for _, u in units do + track(u.pid, u.kind, u.codec, u.streamType, nil) + end + local seen: { [number]: boolean } = {} + for _, u in units do + local t = byPid[u.pid] + if not seen[u.pid] then + seen[u.pid] = true + if t.codec == "unknown" or t.kind == "data" then + -- a private / unknown stream type: go by the PES stream id and the payload + local sid = u.streamId or 0 + if sid >= 0xE0 and sid <= 0xEF then + t.kind = "video" + local info = MpegEs.info(u.data, 0, buffer.len(u.data)) + t.codec = if info then (if info.mpeg2 then "mpeg2" else "mpeg1") elseif MpegEs.findStart(u.data, 0, math.min(buffer.len(u.data), 8)) then "h264" else "unknown" + elseif sid >= 0xC0 and sid <= 0xDF then + t.kind, t.codec = "audio", "mp2" + end + end + if t.codec == "mpeg1" or t.codec == "mpeg2" then + local info = MpegEs.info(u.data, 0, buffer.len(u.data)) + if info then + t.codec = if info.mpeg2 then "mpeg2" else "mpeg1" + t.width, t.height, t.frameRate = info.width, info.height, info.frameRate + end + elseif t.codec == "mp2" then + t.codec = mpegAudioCodec(u) + elseif t.codec == "aac" then + t.adts = true + local b: buffer = u.data + if buffer.len(b) >= 4 and buffer.readu8(b, 0) == 0xFF then + local rates = { 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350 } + t.sampleRate = rates[(buffer.readu8(b, 2) // 4) % 16 + 1] + t.channels = (buffer.readu8(b, 2) % 2) * 4 + buffer.readu8(b, 3) // 64 + end + end + end + end + local dmx = Demux.new("mpegts", tracks, r.buf, { stats = d.stats }) + local lastPts: { [number]: number } = {} + for _, u in units do + local t = byPid[u.pid] + local pts = u.pts90 or u.dts90 + if pts == nil then + local prev = lastPts[u.pid] + if prev and t.frameRate and t.frameRate > 0 then + pts = prev + 90000 / t.frameRate + else + pts = prev + end + end + if pts ~= nil then + lastPts[u.pid] = pts + local key = true + local data: buffer = u.data + if t.kind == "video" then + if t.codec == "mpeg1" or t.codec == "mpeg2" then + key = MpegEs.pictureType(data, 0, buffer.len(data)) == 1 + elseif t.codec == "h264" then + key = u.randomAccess or MpegEs.h264Key(data, 0, buffer.len(data)) + else + key = u.randomAccess + end + end + dmx:addData(u.pid, pts, u.dts90 or pts, nil, key, data) + end + end + dmx:finish() + return dmx, nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Ts.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) + local dmx, err = Ts.demux(r, opts) + if not dmx then + return nil, err + end + return Video.open(dmx, opts :: Video.OpenOptions?) +end + +return Ts +end +__FILES["video/ogv"] = function() + +-- video/ogv: Ogg Theora video (Theora I spec, RFC 3533 / 5334), on containers/Ogg: Theora (granule = keyframe << shift +-- | frames since; the headers Xiph-laced into track.config) and Vorbis / Opus / FLAC streams of the first group. Writes +-- copied Theora + audio. Not supported: chained files, Skeleton / Kate / Speex streams, encoding Theora. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Ogg = __include("containers/Ogg") +local Demux = __include("containers/Demux") +local AudioWrap = __include("containers/AudioWrap") +local Theora = __include("codecs/video/Theora") +local Video = __include("codecs/video/Video") +local Source = __include("codecs/video/Video/Source") + +-- ------------------------------------------------------------------------------------------------ contract +local Ogv = { + name = "ogv", + category = "video", + extensions = { "ogv", "ogg" }, + mime = { "video/ogg" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "containers/Demux", "containers/AudioWrap", "codecs/video/Theora", "codecs/video/Video", "codecs/video/Video/Source" }, + caps = { decode = true, encode = true, streaming = true, remux = true, video = { "theora" }, audio = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type OpenOptions = { + rgba: boolean?, -- default false: yuv420p + track: number?, -- default: the first video track + audio: boolean?, + maxPixels: number?, + verify: boolean?, -- default true + openAudio: any?, -- set by the api: (demuxer, track) -> audio Decoder +} +type EncodeOptions = { + audio: boolean?, -- true: fail when the audio cannot be copied (default: dropped) +} + +-- ------------------------------------------------------------------------------------------------ constants +local AUDIO = { vorbis = true, opus = true, flac = true } + +-- ------------------------------------------------------------------------------------------------ sniff +-- a Theora identification header in a bos page (plain Ogg audio is left to the audio formats) +function Ogv.sniff(r: Bytes.Reader): number + if r:peek(4) ~= "OggS" then + return 0 + end + local b, p, lim = r.buf, r.pos, r.limit + for _ = 1, 8 do + if p + 27 > lim or buffer.readstring(b, p, 4) ~= "OggS" or buffer.readu8(b, p + 5) % 4 < 2 then + return 0 + end + local nseg = buffer.readu8(b, p + 26) + local d = p + 27 + nseg + if d + 7 <= lim and buffer.readu8(b, d) == 0x80 and buffer.readstring(b, d + 1, 6) == "theora" then + return 1 + end + if d > lim then + return 0 + end + local size = 0 + for i = 0, nseg - 1 do + size += buffer.readu8(b, p + 27 + i) + end + p = d + size + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ encode +local function pages(b: buffer): { { number } } + local out = {} + local pos = 0 + while true do + local p = Ogg.Page.find(b, pos, nil, false) + if not p then + break + end + table.insert(out, { p.offset, p.size, p.granule, if p.bos then 1 else 0, if p.continued then 1 else 0 }) + pos = p.offset + p.size + end + return out +end + +function Ogv.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: any = opts or {} + local streams, err = Source.streams(value, o, { video = { copy = { theora = true } }, audio = { copy = { vorbis = true, opus = true } } }) + if not streams then + return nil, err + end + local vs: Source.Stream? = nil + local as: Source.Stream? = nil + for _, s in streams do + if s.kind == "video" and s.codec == "theora" and not vs then + vs = s + elseif s.kind == "audio" and s.copied and not as then + as = s + end + end + if not vs or not vs.config then + return nil, Err.new(Err.UNSUPPORTED, "only Theora video can be written (no Theora encoder)") + end + local v = vs :: Source.Stream + local headers = Theora.splitConfig(v.config :: buffer) + local info = headers and Theora.info(headers[1]) + if not headers or not info then + return nil, Err.new(Err.CORRUPT, "Theora track without its three headers") + end + local fps = info.fpsNum / info.fpsDen + local scale = 2 ^ info.granuleShift + local bias = if info.versionMajor * 65536 + info.versionMinor * 256 + info.versionSub >= 0x030201 then 1 else 0 + -- video pages (serial 0x7468656F), granules from the frame numbers + local mux = Ogg.muxer({ pageSize = 4096 }) + local s = mux:stream(0x7468656F) + s:packet(headers[1], 0, { flush = true }) + s:packet(headers[2], 0) + s:packet(headers[3], 0, { flush = true }) + local key = 0 + local start = if #v.packets > 0 then v.packets[1].pts else 0 + for i, p in v.packets do + local frame = math.floor((p.pts - start) * fps + 0.5) + if buffer.len(p.data) > 0 and buffer.readu8(p.data, 0) // 64 == 0 then + key = frame + bias + end + s:packet(p.data, key * scale + (frame + bias - key), { eos = i == #v.packets }) + end + local video = mux:finish() + local audio: buffer? = nil + local arate, askip = 1, 0 + if as and o.audio ~= false then + local a = as :: Source.Stream + local track: any = { id = 1, kind = "audio", codec = a.codec, timescale = 1, config = a.config, sampleRate = a.sampleRate, channels = a.channels } + local shim = { + count = function(_: any, _t: number): number + return #a.packets + end, + get = function(_: any, _t: number, k: number): any + local p = a.packets[k] + return p and { track = 1, pts = p.pts, duration = p.duration, keyframe = true, data = p.data } + end, + } + local buf, _, aerr = AudioWrap.wrap(shim, track) + if not buf and o.audio == true then + return nil, aerr + end + audio = buf + if a.codec == "opus" then + arate = 48000 + local c = a.config + askip = if c and buffer.len(c) >= 12 then buffer.readu16(c, 10) else 0 + else + arate = a.sampleRate or 44100 + end + elseif o.audio == true and not as then + return nil, Err.new(Err.UNSUPPORTED, "the audio track is not Vorbis / Opus") + end + local vp = pages(video) + local ap = if audio then pages(audio) else {} + local out = Bytes.writer(buffer.len(video) + (if audio then buffer.len(audio) else 0)) + local function put(b: buffer, pg: { number }) + out:bytes(b, pg[1], pg[2]) + end + -- bos pages first (video, then audio), then the other header pages, then data by time + put(video, vp[1]) + if audio and ap[1] then + put(audio :: buffer, ap[1]) + end + local vi, ai = 2, 2 + local function headerPage(list: { { number } }, i: number): boolean + local pg = list[i] + return pg ~= nil and pg[3] == 0 + end + while headerPage(vp, vi) do + put(video, vp[vi]) + vi += 1 + end + while audio and headerPage(ap, ai) do + put(audio :: buffer, ap[ai]) + ai += 1 + end + local vt, at = 0, 0 + while vi <= #vp or ai <= #ap do + local nv, na = vp[vi], ap[ai] + if nv and nv[3] >= 0 then + vt = Theora.granuleFrame(info, nv[3]) / fps + end + if na and na[3] >= 0 then + at = (na[3] - askip) / arate + end + if nv and (not na or vt <= at) then + put(video, nv) + vi += 1 + else + put(audio :: buffer, na) + ai += 1 + end + end + return out:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- Xiph lacing of header packets (Matroska's CodecPrivate layout): count - 1, the sizes but the last, the packets +local function xiphLace(list: { buffer }): buffer + local w = Bytes.writer(64) + w:u8(#list - 1) + for i = 1, #list - 1 do + local n = buffer.len(list[i]) + while n >= 255 do + w:u8(255) + n -= 255 + end + w:u8(n) + end + for _, h in list do + w:bytes(h) + end + return w:finish() +end + +type Pending = { track: number, pts: number, key: boolean, page: number, data: buffer, off: number, len: number, own: boolean } + +function Ogv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) + local ogg, err = Ogg.open(r, { verify = not (opts and opts.verify == false) }) + if not ogg then + return nil, err + end + local src: buffer = ogg.buf + local tracks: { Types.Track } = {} + local all: { Pending } = {} + local meta: { [string]: any } = {} + local function add(track: number, pts: number, key: boolean, p: any) + table.insert(all, { + track = track, + pts = pts, + key = key, + page = p.pageOffset, + data = p.data, + off = p.offset, + len = p.size, + own = p.data ~= src, + }) + end + for _, st in ogg:streams() do + local codec = st.codec + if codec ~= "theora" and not AUDIO[codec] then + continue + end + local rd = ogg:reader(st.serial) + local headers: { buffer } = {} + local nh = if codec == "theora" or codec == "vorbis" then 3 elseif codec == "opus" then 2 else 1 + while #headers < nh do + local p = rd:nextPacket() + if not p then + break + end + table.insert(headers, Ogg.copy(p)) + if codec == "flac" and #headers == 1 and p.size >= 9 then + nh = 1 + buffer.readu16(p.data, p.offset + 7) // 256 + (buffer.readu16(p.data, p.offset + 7) % 256) * 256 + if nh > 64 then + nh = 1 + end + end + end + if #headers < nh then + continue + end + local id = #tracks + 1 + local track: any = { id = id, kind = "audio", codec = codec, codecTag = codec, timescale = 1, default = true, serial = st.serial } + if codec == "theora" then + local info = Theora.info(headers[1]) + if not info then + continue + end + track.kind = "video" + track.width, track.height = info.picWidth, info.picHeight + track.timescale = info.fpsNum + track.frameRate = info.fpsNum / info.fpsDen + track.config = xiphLace(headers) + local _, _, tags = Theora.comment(headers[2]) + meta.tags = tags + -- frame k of the stream: granule = keyframe << shift | frames since; bitstream 3.2.1 counts from 1 + local packets = {} + local base: number? = nil + while true do + local p = rd:nextPacket() + if not p then + break + end + if p.size > 0 and buffer.readu8(p.data, p.offset) >= 0x80 then + continue + end + table.insert(packets, p) + if base == nil and p.granule >= 0 then + base = Theora.granuleFrame(info, p.granule) - (#packets - 1) + end + end + local b0 = base or 0 + for k, p in packets do + local key = p.size > 0 and buffer.readu8(p.data, p.offset) // 64 == 0 + add(id, (b0 + k - 1) * info.fpsDen, key, p) + end + track.duration = (b0 + #packets) / track.frameRate + else + local h = headers[1] + local rate, channels, skip = 0, 0, 0 + if codec == "vorbis" and buffer.len(h) >= 16 then + channels, rate = buffer.readu8(h, 11), buffer.readu32(h, 12) + track.config = xiphLace(headers) + elseif codec == "opus" and buffer.len(h) >= 19 then + channels, rate, skip = buffer.readu8(h, 9), 48000, buffer.readu16(h, 10) + track.config = h + track.codecDelay = skip / 48000 + elseif codec == "flac" and buffer.len(h) >= 9 + 4 + 4 + 18 then + local o = 9 + 4 + 4 + 10 -- "fLaC", the block header, STREAMINFO's sample rate field + rate = buffer.readu8(h, o) * 4096 + buffer.readu8(h, o + 1) * 16 + buffer.readu8(h, o + 2) // 16 + channels = (buffer.readu8(h, o + 2) // 2) % 8 + 1 + local parts = { buffer.create(buffer.len(h) - 9) } + buffer.copy(parts[1], 0, h, 9) + for i = 2, #headers do + table.insert(parts, headers[i]) + end + local total = 0 + for _, x in parts do + total += buffer.len(x) + end + local cfg = buffer.create(total) + local o2 = 0 + for _, x in parts do + buffer.copy(cfg, o2, x) + o2 += buffer.len(x) + end + track.config = cfg + end + if rate <= 0 or channels <= 0 then + continue + end + track.sampleRate, track.channels, track.timescale = rate, channels, rate + local last = 0 + while true do + local p = rd:nextPacket() + if not p then + break + end + add(id, math.max(0, last - skip), true, p) + if p.granule >= 0 then + last = p.granule + end + end + track.duration = math.max(0, last - skip) / rate + end + table.insert(tracks, track) + end + if #tracks == 0 then + return nil, Err.new(Err.UNSUPPORTED, "no Theora / Vorbis / Opus / FLAC stream") + end + -- the index in file order (by the page each packet ends on) + local order = table.create(#all, 0) + for i = 1, #all do + order[i] = i + end + table.sort(order, function(a: number, c: number): boolean + local pa, pc = all[a].page, all[c].page + if pa ~= pc then + return pa < pc + end + return a < c + end) + local dmx = Demux.new("ogv", tracks, src, meta) + for _, i in order do + local e = all[i] + if e.own then + dmx:addData(e.track, e.pts, e.pts, nil, e.key, e.data) + else + dmx:add(e.track, e.pts, e.pts, nil, e.key, e.off, e.len) + end + end + dmx:finish() + return dmx, nil +end + +function Ogv.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) + local ok, dmx, err = pcall(Ogv.demux, r, opts) + if not ok then + return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(dmx)) + end + if not dmx then + return nil, err + end + return Video.open(dmx, opts :: Video.OpenOptions?) +end + +return Ogv +end +__FILES["video/smk"] = function() + +-- video/smk: RAD Smacker video (SMK2, SMK4), from MultimediaWiki "Smacker": header, up to 7 audio tracks, Huffman +-- trees, per-frame palette updates; rgba8 through codecs/video/Legacy/Smacker, audio through video/smk/Audio; the ring +-- frame only with opts.ringFrame. Not supported: writing, Bink audio tracks (flags 0x08 / 0x04). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Demux = __include("containers/Demux") +local Video = __include("codecs/video/Video") +local Stream = __include("codecs/audio/Stream") +local Audio = __include("video/smk/Audio") + +-- ------------------------------------------------------------------------------------------------ contract +local Smk = { + name = "smk", + category = "video", + extensions = { "smk" }, + mime = { "video/vnd.radgamettools.smacker" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/video/Video", "codecs/audio/Stream", "codecs/video/Legacy/Smacker" }, + caps = { decode = true, encode = false, streaming = true, video = { "smackvid" }, audio = { "smackaudio", "pcm_u8", "pcm_s16le" } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type OpenOptions = { + rgba: boolean?, -- frames are rgba8 already + maxPixels: number?, -- default 2^26 + audio: boolean?, + ringFrame: boolean?, -- also show the ring frame (as ffmpeg) + openAudio: any?, -- the api's hook, only for Bink audio +} + +-- ------------------------------------------------------------------------------------------------ constants +local HEADER = 104 +local RING = 1 +-- 6-bit palette components -> 8 bits (bit replication: v << 2 | v >> 4) +local PAL6 = table.create(64, 0) +for i = 0, 63 do + PAL6[i + 1] = i * 4 + i // 16 +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Smk.sniff(r: Bytes.Reader): number + local s = r:peek(4) + if s ~= "SMK2" and s ~= "SMK4" then + return 0 + end + return 1 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function palette(b: buffer, p: number, stop: number, old: buffer): (buffer?) + local pal = buffer.create(1024) + buffer.copy(pal, 0, old, 0, 1024) + local function u8(): number + local v = if p < stop then buffer.readu8(b, p) else 0 + p += 1 + return v + end + local sz = 0 + while sz < 256 do + local t = u8() + if t >= 0x80 then + sz += t - 0x80 + 1 + elseif t >= 0x40 then + local off = u8() + local j = t - 0x40 + 1 + if off + j > 256 then + return nil + end + while j > 0 and sz < 256 do + buffer.writeu32(pal, sz * 4, buffer.readu32(old, off * 4)) + sz += 1 + off += 1 + j -= 1 + end + else + local r = PAL6[t + 1] + local g = PAL6[u8() % 64 + 1] + local bl = PAL6[u8() % 64 + 1] + buffer.writeu32(pal, sz * 4, r + g * 256 + bl * 65536 + 0xFF000000) + sz += 1 + end + end + return pal +end + +function Smk.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) + local b, base, limit = r.buf, r.base, r.limit + if limit - base < HEADER then + return nil, Err.new(Err.TRUNCATED, "file shorter than the header") + end + local hr = Bytes.reader(b, base, HEADER) + local magic = hr:string(4) + local w, h, frames = hr:u32le(), hr:u32le(), hr:u32le() + local ptsInc = hr:i32le() + local flags = hr:u32le() + hr:skip(28) + local treeSize = hr:u32le() + local sizes = { hr:u32le(), hr:u32le(), hr:u32le(), hr:u32le() } + local rates, aflags = {}, {} + for k = 1, 7 do + rates[k] = hr:u24le() + aflags[k] = hr:u8() + end + if hr.err then + return nil, hr.err + end + if magic ~= "SMK2" and magic ~= "SMK4" then + return nil, Err.new(Err.CORRUPT, "not a Smacker file") + end + if w == 0 or h == 0 or w > 32768 or h > 32768 then + return nil, Err.new(Err.CORRUPT, "bad picture size") + end + local max = (opts and opts.maxPixels) or 2 ^ 26 + if w * h > max then + return nil, Err.new(Err.LIMIT, w .. " x " .. h .. " over maxPixels") + end + local shown = frames + if bit32.band(flags, RING) ~= 0 then + frames += 1 + end + local p = base + HEADER + if frames > 0xFFFFFF or p + frames * 5 + treeSize > limit then + return nil, Err.new(Err.TRUNCATED, "frame tables or trees past the end of the file") + end + -- the trees (with the four sizes in front, as the video codec takes them) + local config = buffer.create(16 + treeSize) + for k = 1, 4 do + buffer.writeu32(config, (k - 1) * 4, sizes[k]) + end + buffer.copy(config, 16, b, p + frames * 5, treeSize) + -- frame time: > 0 ms, < 0 units of 10 us (ticks of 1/100000 s) + local tick = if ptsInc < 0 then -ptsInc elseif ptsInc > 0 then ptsInc * 100 else 10000 + local tracks: { Types.Track } = { + { + id = 1, + kind = "video", + codec = "smackvid", + codecTag = magic, + timescale = 100000, + width = w, + height = h, + frameRate = 100000 / tick, + default = true, + config = config, + flags = flags, + } :: Types.Track, + } + local audio: { [number]: Types.Track } = {} + for k = 1, 7 do + if rates[k] > 0 then + local f = aflags[k] + local bits = if bit32.band(f, 0x20) ~= 0 then 16 else 8 + local codec = if bit32.band(f, 0x0C) ~= 0 then "binkaudio" + elseif bit32.band(f, 0x80) ~= 0 then "smackaudio" + elseif bits == 16 then "pcm_s16le" + else "pcm_u8" + local t: Types.Track = { + id = k + 1, + kind = "audio", + codec = codec, + codecTag = string.format("0x%02X", f), + timescale = rates[k], + sampleRate = rates[k], + channels = if bit32.band(f, 0x10) ~= 0 then 2 else 1, + bitsPerSample = bits, + default = #tracks == 1, + } + audio[k] = t + table.insert(tracks, t) + end + end + local dmx = Demux.new("smk", tracks, b, { version = magic, flags = flags, frames = shown, ringFrame = frames > shown }) + local count = if opts and opts.ringFrame then frames else shown + local pal = buffer.create(1024) + local apts = { 0, 0, 0, 0, 0, 0, 0 } + local at = p + frames * 5 + treeSize + for i = 0, frames - 1 do + local fsize = buffer.readu32(b, p + i * 4) + local fflags = buffer.readu8(b, p + frames * 4 + i) + local size = fsize - fsize % 4 + local q, stop = at, math.min(limit, at + size) + at += size + local ok = true + if fflags % 2 == 1 and q < stop then + local psize = buffer.readu8(b, q) * 4 + if psize > size then + ok = false + else + local np = palette(b, q + 1, math.min(stop, q + psize), pal) + if np then + pal = np + else + ok = false + end + q += psize + end + end + for k = 1, 7 do + if not ok then + break + end + if bit32.band(fflags, 2 ^ k) ~= 0 then + if q + 4 > stop then + ok = false + break + end + local asize = buffer.readu32(b, q) + local t = audio[k] + local min = if t and t.codec ~= "pcm_s16le" then 8 else 4 + if asize < min or q + asize > stop then + ok = false + break + end + if t then + local len = asize - 4 + local frameBytes = (t.channels :: number) * (t.bitsPerSample :: number) // 8 + local n = if t.codec == "smackaudio" then buffer.readu32(b, q + 4) // frameBytes + elseif t.codec == "binkaudio" then 0 + else len // frameBytes + dmx:add(t.id, apts[k], nil, n, true, q + 4, len) + apts[k] += n + end + q += asize + end + end + if ok and i < count then + dmx:add(1, i * tick, nil, tick, i == 0 or fsize % 2 == 1, q, math.max(0, stop - q)) + dmx:setExtra("palette", pal) + end + end + dmx:finish() + return dmx, nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Smk.openAudio(dmx: any, track: Types.Track): (Types.Decoder?, Err.Err?) + local codec = track.codec + if codec ~= "smackaudio" and codec ~= "pcm_u8" and codec ~= "pcm_s16le" then + return nil, Err.new(Err.UNSUPPORTED, "audio codec " .. codec) + end + local id = track.id + local count = dmx:count(id) + local starts: { number } = {} + local total = 0 + for k = 1, count do + local pts, _, dur = dmx:info(id, k) + starts[k] = pts or total + total = (pts or total) + (dur or 0) + end + starts[count + 1] = total + local rate, ch, bits = track.sampleRate :: number, track.channels :: number, track.bitsPerSample :: number + local packed = codec == "smackaudio" + local floats: { number } = {} + local dec: any = { + sampleRate = rate, + channels = ch, + frames = total, + duration = total / rate, + bitrate = rate * ch * bits, + tags = {}, + } + return Stream.packets(dec, { + count = count, + start = function(i: number): number + return starts[math.clamp(i, 1, count + 1)] + end, + decode = function(i: number): (number?, Err.Err?) + local pkt = dmx:get(id, i) + if not pkt then + return nil, Err.new(Err.TRUNCATED, "no audio packet " .. i) + end + local n, out = Audio.decode(pkt.data, ch, bits, packed) + if not n then + return nil, Err.from(out :: string) + end + floats = out :: { number } + return n, nil + end, + pcm = function(): { number } + return floats + end, + reset = function() end, + cumulative = true, + }) +end + +function Smk.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) + local dmx, err = Smk.demux(r, opts) + if not dmx then + return nil, err + end + local o: any = table.clone(opts or {}) + type Hook = (any, Types.Track) -> (Types.Decoder?, Err.Err?) + local hook = o.openAudio :: Hook? + o.openAudio = function(d: any, track: Types.Track): (Types.Decoder?, Err.Err?) + if track.codec == "binkaudio" and hook then + return hook(d, track) + end + return Smk.openAudio(d, track) + end + return Video.open(dmx, o) +end + +return Smk +end +__FILES["video/smk/Audio"] = @native function() + + + +-- video/smk/Audio: Smacker packed audio (SMKA, MultimediaWiki "Smacker"): u32 unpacked size, then LSB-first bits: data, +-- stereo, 16-bit flags, an 8-bit Huffman tree per channel and byte, the first samples raw (16-bit byte-swapped, right +-- first), then wrapping deltas. Raw u8 / s16le too; floats as ffmpeg gives them (u8 (v - 128) / 128, s16 v / 32768). +local Smacker = __include("codecs/video/Legacy/Smacker") + +local readu8, readi16 = buffer.readu8, buffer.readi16 + +local Audio = {} + +@native function Audio.decode(d: buffer, channels: number, bits: number, packed: boolean): (number?, { number } | string) + local n = buffer.len(d) + if not packed then + local bps = bits // 8 + local frames = n // (bps * channels) + local count = frames * channels + local out = table.create(count, 0) + if bps == 1 then + for i = 0, count - 1 do + out[i + 1] = (readu8(d, i) - 128) / 128 + end + else + for i = 0, count - 1 do + out[i + 1] = readi16(d, i * 2) / 32768 + end + end + return frames, out + end + if n <= 4 then + return nil, "packet too small" + end + local size = buffer.readu32(d, 0) + if size > 2 ^ 24 then + return nil, "packet too big" + end + local br = Smacker.bits(d, 4, n - 4) + local bit, read, walk = Smacker.bit, Smacker.read, Smacker.walk + if bit(br) == 0 then + return 0, {} + end + local stereo = bit(br) + local wide = bit(br) + if (stereo == 1) ~= (channels == 2) or (wide == 1) ~= (bits == 16) then + return nil, "packet does not match the track's format" + end + local bytes = wide + 1 + local ch = stereo + 1 + if size % (ch * bytes) ~= 0 then + return nil, "unpacked size is not a whole number of samples" + end + local trees: { { number } } = {} + for k = 1, 2 ^ (wide + stereo) do + bit(br) + local t, msg = Smacker.tree8(br) + if not t then + return nil, msg or "bad tree" + end + bit(br) + trees[k] = t + end + if br.nbits - br.pos < ch * bytes * 8 then + return nil, "truncated packet" + end + -- whether any tree needs bits (else every delta is a constant and no end check applies) + local coded = false + for _, t in trees do + if #t > 1 then + coded = true + end + end + local frames = size // (ch * bytes) + local total = frames * ch + local out = table.create(total, 0) + if wide == 1 then + local pred = { 0, 0 } + for c = ch, 1, -1 do + local v = read(br, 16) + pred[c] = (v // 256) + (v % 256) * 256 + end + for c = 1, math.min(ch, total) do + local v = pred[c] + out[c] = (if v >= 32768 then v - 65536 else v) / 32768 + end + for i = ch, total - 1 do + local c = if ch == 2 then i % 2 else 0 + if coded and br.pos > br.nbits then + return nil, "truncated packet" + end + local lo = walk(trees[2 * c + 1], br) + local hi = walk(trees[2 * c + 2], br) + local v = (pred[c + 1] + lo + hi * 256) % 65536 + pred[c + 1] = v + out[i + 1] = (if v >= 32768 then v - 65536 else v) / 32768 + end + else + local pred = { 0, 0 } + for c = ch, 1, -1 do + pred[c] = read(br, 8) + end + for c = 1, math.min(ch, total) do + out[c] = (pred[c] - 128) / 128 + end + for i = ch, total - 1 do + local c = if ch == 2 then i % 2 else 0 + if br.pos > br.nbits then + return nil, "truncated packet" + end + local v = (pred[c + 1] + walk(trees[c + 1], br)) % 256 + pred[c + 1] = v + out[i + 1] = (v - 128) / 128 + end + end + return frames, out +end + +return Audio +end +__FILES["video/y4m"] = function() + +-- video/y4m: YUV4MPEG2 (mjpegtools / ffmpeg). Reads the W H F I A C X tags and FRAMEs as yuv420p (C422 / C444 +-- averaged, Cmono neutral chroma, high bit depths scaled to 8). Writes "C420jpeg" as ffmpeg does for yuv420p (BT.601 +-- limited range). Not supported: interlaced field handling (the I tag is kept in meta), alpha (C444alpha drops it). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Demux = __include("containers/Demux") +local Video = __include("codecs/video/Video") +local Source = __include("codecs/video/Video/Source") + +-- ------------------------------------------------------------------------------------------------ contract +local Y4m = { + name = "y4m", + category = "video", + extensions = { "y4m" }, + mime = { "video/x-yuv4mpeg" }, + 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 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type OpenOptions = { + rgba: boolean?, -- default false: yuv420p + maxPixels: number?, -- default 2^26 +} +type EncodeOptions = { + frameRate: { number }?, -- { num, den } of the F tag (default: the shortest frame's rate) + maxFps: number?, -- default 100 +} + +-- ------------------------------------------------------------------------------------------------ constants +local MAGIC = "YUV4MPEG2 " +-- C tag -> pixel format, bits +local COLOR: { [string]: { any } } = { + ["420jpeg"] = { "yuv420p", 8 }, + ["420paldv"] = { "yuv420p", 8 }, + ["420mpeg2"] = { "yuv420p", 8 }, + ["420"] = { "yuv420p", 8 }, + ["422"] = { "yuv422p", 8 }, + ["444"] = { "yuv444p", 8 }, + ["444alpha"] = { "yuva444p", 8 }, + mono = { "gray", 8 }, +} +for _, b in { 9, 10, 12, 14, 16 } do + COLOR["420p" .. b] = { "yuv420p", b } + COLOR["422p" .. b] = { "yuv422p", b } + COLOR["444p" .. b] = { "yuv444p", b } + COLOR["mono" .. b] = { "gray", b } +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Y4m.sniff(r: Bytes.Reader): number + return if r:peek(10) == MAGIC then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function frameSize(pf: string, bits: number, w: number, h: number): number + local bps = if bits > 8 then 2 else 1 + local cw, ch = (w + 1) // 2, (h + 1) // 2 + if pf == "yuv420p" then + return (w * h + 2 * cw * ch) * bps + elseif pf == "yuv422p" then + return (w * h + 2 * cw * h) * bps + elseif pf == "yuv444p" then + return w * h * 3 * bps + elseif pf == "yuva444p" then + return w * h * 4 * bps + end + return w * h * bps +end + +function Y4m.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) + local buf, base, limit = r.buf, r.base, r.limit + local nl = -1 + for i = base, math.min(limit, base + 4096) - 1 do + if buffer.readu8(buf, i) == 10 then + nl = i + break + end + end + if limit - base < 10 or buffer.readstring(buf, base, 10) ~= MAGIC then + return nil, Err.new(Err.CORRUPT, "not a YUV4MPEG2 stream", base) + end + if nl < 0 then + return nil, Err.new(Err.TRUNCATED, "no end of the stream header", base) + end + local header = buffer.readstring(buf, base + 10, nl - base - 10) + local w, h, fn, fd = 0, 0, 25, 1 + local ctag, itag, atag = "420jpeg", "p", "0:0" + local extra = {} + for tok in string.gmatch(header, "%S+") do + local k, v = string.sub(tok, 1, 1), string.sub(tok, 2) + if k == "W" then + w = tonumber(v) or 0 + elseif k == "H" then + h = tonumber(v) or 0 + elseif k == "F" then + local a, b = string.match(v, "^(%d+):(%d+)$") + 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 + ctag = v + elseif k == "I" then + itag = v + elseif k == "A" then + atag = v + elseif k == "X" then + table.insert(extra, v) + end + end + local color = COLOR[ctag] + if not color then + return nil, Err.new(Err.UNSUPPORTED, "colour space C" .. ctag) + end + if w <= 0 or h <= 0 or w > 65535 or h > 65535 then + return nil, Err.new(Err.CORRUPT, "bad frame size " .. w .. "x" .. h) + end + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + if w * h > maxPixels then + return nil, Err.new(Err.LIMIT, "frame of " .. w .. "x" .. h .. " pixels") + end + local pf, bits = color[1], color[2] + local size = frameSize(pf, bits, w, h) + local track: Types.Track = { + id = 1, + kind = "video", + codec = "rawvideo", + codecTag = "C" .. ctag, + timescale = fn / fd, + width = w, + height = h, + frameRate = fn / fd, + pixelFormat = pf, + bitDepth = bits, + default = true, + } + local meta = { interlace = itag, aspect = atag, extra = extra, colorTag = ctag } + local dmx = Demux.new("y4m", { track }, buf, meta) + local pos = nl + 1 + local k = 0 + while pos + 5 <= limit do + if buffer.readstring(buf, pos, 5) ~= "FRAME" then + return nil, Err.new(Err.CORRUPT, "expected FRAME", pos) + end + local e = -1 + for i = pos + 5, math.min(limit, pos + 4096) - 1 do + if buffer.readu8(buf, i) == 10 then + e = i + break + end + end + if e < 0 then + break + end + local data = e + 1 + if data + size > limit then + break + end + dmx:add(1, k, k, 1, true, data, size) + k += 1 + pos = data + size + end + dmx:finish() + return dmx, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Y4m.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local streams, err = Source.streams(value, { audio = false }, { video = { copy = nil, encode = "rawvideo" } }) + if not streams then + return nil, err + end + local s = streams[1] + local fn, fd, packets = Source.constantRate(s, opts and opts.maxFps) + if opts and type(opts.frameRate) == "table" then + fn, fd, packets = opts.frameRate[1], opts.frameRate[2], s.packets + end + s.packets = packets + local w = Bytes.writer(64 + #s.packets * (buffer.len(s.packets[1].data) + 6)) + w:string(string.format("YUV4MPEG2 W%d H%d F%d:%d Ip A1:1 C420jpeg XYSCSS=420JPEG\n", s.width or 0, s.height or 0, fn, fd)) + for _, p in s.packets do + w:string("FRAME\n") + w:bytes(p.data) + end + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Y4m.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) + local dmx, err = Y4m.demux(r, opts) + if not dmx then + return nil, err + end + return Video.open(dmx, opts :: Video.OpenOptions?) +end + +return Y4m +end +end + + + + + \ No newline at end of file diff --git a/build/rosetta.lua b/build/rosetta.lua index 18bac8a..18b1afb 100644 --- a/build/rosetta.lua +++ b/build/rosetta.lua @@ -36287,7 +36287,9 @@ end -- mpc_compute_new_V: 32 subband samples Y[y .. y + 31] -> 64 V values at V[o .. o + 63] (the ISO 11172-3 matrixing -- through Byeong Gi Lee's fast DCT) -local function newV(Y, y, V, o) +-- (two halves: as one function, its native lowering fails register allocation and the whole function runs +-- interpreted) +local function newVEven(Y, y, V, o) local A00 = Y[y] + Y[y + 31] local A01 = Y[y + 1] + Y[y + 30] local A02 = Y[y + 2] + Y[y + 29] @@ -36389,6 +36391,12 @@ local function newV(Y, y, V, o) t = -(A12 + A14 + A15) V[o + 46] = t - A08 V[o + 42] = t - A10 - A11 +end + +local function newVOdd(Y, y, V, o) + local A00, A01, A02, A03, A04, A05, A06, A07, A08, A09, A10, A11, A12, A13, A14, A15 + local B00, B01, B02, B03, B04, B05, B06, B07, B08, B09, B10, B11, B12, B13, B14, B15 + local t A00 = (Y[y] - Y[y + 31]) * 0.5006030202 A01 = (Y[y + 1] - Y[y + 30]) * 0.5054709315 A02 = (Y[y + 2] - Y[y + 29]) * 0.5154473186 @@ -36501,6 +36509,11 @@ local function newV(Y, y, V, o) end end +local function newV(Y, y, V, o) + newVEven(Y, y, V, o) + newVOdd(Y, y, V, o) +end + diff --git a/build/rosetta.lua.linemap.json b/build/rosetta.lua.linemap.json index 45c4801..3767af9 100644 --- a/build/rosetta.lua.linemap.json +++ b/build/rosetta.lua.linemap.json @@ -105,435 +105,435 @@ [35546, "src/Rosetta/codecs/audio/Mpa/Tables.luau"], [35772, "src/Rosetta/codecs/audio/Musepack/init.luau"], [36117, "src/Rosetta/codecs/audio/Musepack/Decode.luau"], -[36998, "src/Rosetta/codecs/audio/Musepack/Tables.luau"], -[37376, "src/Rosetta/codecs/audio/Opus/init.luau"], -[37390, "src/Rosetta/codecs/audio/Opus/Celt.luau"], -[39237, "src/Rosetta/codecs/audio/Opus/CeltEncoder.luau"], -[40302, "src/Rosetta/codecs/audio/Opus/CeltTables.luau"], -[40362, "src/Rosetta/codecs/audio/Opus/Decoder.luau"], -[40822, "src/Rosetta/codecs/audio/Opus/Mdct.luau"], -[41159, "src/Rosetta/codecs/audio/Opus/Packet.luau"], -[41392, "src/Rosetta/codecs/audio/Opus/Silk.luau"], -[43428, "src/Rosetta/codecs/audio/Opus/SilkTables.luau"], -[43802, "src/Rosetta/codecs/audio/Pcm/init.luau"], -[44065, "src/Rosetta/codecs/audio/Pcm/Convert.luau"], -[44362, "src/Rosetta/codecs/audio/Qoa/init.luau"], -[44644, "src/Rosetta/codecs/audio/Resample/init.luau"], -[45003, "src/Rosetta/codecs/audio/SoundFont/init.luau"], -[45057, "src/Rosetta/codecs/audio/SoundFont/Fallback.luau"], -[45200, "src/Rosetta/codecs/audio/SoundFont/Parse.luau"], -[45713, "src/Rosetta/codecs/audio/SoundFont/Synth.luau"], -[46494, "src/Rosetta/codecs/audio/Stream.luau"], -[46655, "src/Rosetta/codecs/audio/Tracker/init.luau"], -[47137, "src/Rosetta/codecs/audio/Tracker/Load.luau"], -[47415, "src/Rosetta/codecs/audio/Tracker/Mixer.luau"], -[47584, "src/Rosetta/codecs/audio/Tracker/Pcm.luau"], -[47712, "src/Rosetta/codecs/audio/Tracker/Player.luau"], -[49700, "src/Rosetta/codecs/audio/Tracker/Tables.luau"], -[49816, "src/Rosetta/codecs/audio/Tta/init.luau"], -[49933, "src/Rosetta/codecs/audio/Tta/Decode.luau"], -[50185, "src/Rosetta/codecs/audio/Vorbis/init.luau"], -[50198, "src/Rosetta/codecs/audio/Vorbis/Codebook.luau"], -[50582, "src/Rosetta/codecs/audio/Vorbis/Packet.luau"], -[51148, "src/Rosetta/codecs/audio/Vorbis/Setup.luau"], -[51569, "src/Rosetta/codecs/audio/Vorbis/Tables.luau"], -[51608, "src/Rosetta/codecs/audio/VorbisComment.luau"], -[51660, "src/Rosetta/codecs/audio/WavPack/init.luau"], -[51882, "src/Rosetta/codecs/audio/WavPack/Block.luau"], -[53337, "src/Rosetta/codecs/audio/WavPack/Tables.luau"], -[53400, "src/Rosetta/codecs/compress/Brotli/init.luau"], -[53487, "src/Rosetta/codecs/compress/Brotli/Decode.luau"], -[54456, "src/Rosetta/codecs/compress/Brotli/Static.luau"], -[55324, "src/Rosetta/codecs/compress/Bzip2/init.luau"], -[55372, "src/Rosetta/codecs/compress/Bzip2/Decode.luau"], -[55888, "src/Rosetta/codecs/compress/Deflate/init.luau"], -[56214, "src/Rosetta/codecs/compress/Deflate/Compress.luau"], -[56634, "src/Rosetta/codecs/compress/Deflate/Inflate.luau"], -[57069, "src/Rosetta/codecs/compress/Explode.luau"], -[57265, "src/Rosetta/codecs/compress/Lz4.luau"], -[57534, "src/Rosetta/codecs/compress/Lzh/init.luau"], -[58138, "src/Rosetta/codecs/compress/Lzma/init.luau"], -[58678, "src/Rosetta/codecs/compress/Lzma/Crc64.luau"], -[58716, "src/Rosetta/codecs/compress/Lzma/Decode.luau"], -[59189, "src/Rosetta/codecs/compress/Lzma/Filters.luau"], -[59365, "src/Rosetta/codecs/compress/Lzw/init.luau"], -[59633, "src/Rosetta/codecs/compress/Lzx.luau"], -[60067, "src/Rosetta/codecs/compress/PackBits.luau"], -[60157, "src/Rosetta/codecs/compress/Quantum.luau"], -[60394, "src/Rosetta/codecs/compress/UnixCompress.luau"], -[60698, "src/Rosetta/codecs/compress/Xxh32.luau"], -[60767, "src/Rosetta/codecs/compress/Zstd/init.luau"], -[60824, "src/Rosetta/codecs/compress/Zstd/Decode.luau"], -[61782, "src/Rosetta/codecs/compress/Zstd/Xxh64.luau"], -[61934, "src/Rosetta/codecs/entropy/Huffman.luau"], -[62216, "src/Rosetta/codecs/entropy/RangeCoder/init.luau"], -[62227, "src/Rosetta/codecs/entropy/RangeCoder/Decoder.luau"], -[62441, "src/Rosetta/codecs/entropy/RangeCoder/Encoder.luau"], -[62685, "src/Rosetta/codecs/font/Bitmap.luau"], -[62886, "src/Rosetta/codecs/font/Cff/init.luau"], -[63527, "src/Rosetta/codecs/font/GlyphNames.luau"], -[63677, "src/Rosetta/codecs/font/TrueType/init.luau"], -[63991, "src/Rosetta/codecs/font/TrueType/Glyf.luau"], -[64383, "src/Rosetta/codecs/font/TrueType/Tables.luau"], -[64885, "src/Rosetta/codecs/image/Bcn/init.luau"], -[64992, "src/Rosetta/codecs/image/Bcn/Decode.luau"], -[65481, "src/Rosetta/codecs/image/Bcn/Encode.luau"], -[65910, "src/Rosetta/codecs/image/Blend.luau"], -[66289, "src/Rosetta/codecs/image/Dct/init.luau"], -[66670, "src/Rosetta/codecs/image/Etc.luau"], -[66968, "src/Rosetta/codecs/image/Half.luau"], -[67037, "src/Rosetta/codecs/image/Jpeg/init.luau"], -[67391, "src/Rosetta/codecs/image/Jpeg/Arith.luau"], -[67799, "src/Rosetta/codecs/image/Jpeg/Color.luau"], -[68036, "src/Rosetta/codecs/image/Jpeg/Decode.luau"], -[68796, "src/Rosetta/codecs/image/Jpeg/Encode.luau"], -[69677, "src/Rosetta/codecs/image/Jpeg/Scan.luau"], -[70123, "src/Rosetta/codecs/image/Jpeg/Tables.luau"], -[70201, "src/Rosetta/codecs/image/Jpeg/Yuv.luau"], -[70268, "src/Rosetta/codecs/image/Pixels.luau"], -[70532, "src/Rosetta/codecs/image/Quantize/init.luau"], -[70991, "src/Rosetta/codecs/image/Raster.luau"], -[71688, "src/Rosetta/codecs/image/Texel.luau"], -[72061, "src/Rosetta/codecs/image/Texture.luau"], -[72206, "src/Rosetta/codecs/image/Vp8/init.luau"], -[72336, "src/Rosetta/codecs/image/Vp8/Decode.luau"], -[74292, "src/Rosetta/codecs/image/Vp8/Predict.luau"], -[74551, "src/Rosetta/codecs/image/Vp8/Tables.luau"], -[74800, "src/Rosetta/codecs/image/Vp8/Yuv.luau"], -[74919, "src/Rosetta/codecs/image/Vp8L/init.luau"], -[75023, "src/Rosetta/codecs/image/Vp8L/Decode.luau"], -[75876, "src/Rosetta/codecs/image/Vp8L/Encode.luau"], -[76828, "src/Rosetta/codecs/image/Yuv.luau"], -[77096, "src/Rosetta/codecs/model/Draco/init.luau"], -[77428, "src/Rosetta/codecs/model/Draco/Attributes.luau"], -[77897, "src/Rosetta/codecs/model/Draco/Connectivity.luau"], -[79086, "src/Rosetta/codecs/model/Draco/Int64.luau"], -[79235, "src/Rosetta/codecs/model/Draco/KdTree.luau"], -[79594, "src/Rosetta/codecs/model/Draco/Predict.luau"], -[80556, "src/Rosetta/codecs/model/Draco/Reader.luau"], -[81030, "src/Rosetta/codecs/model/Mat4.luau"], -[81289, "src/Rosetta/codecs/model/MeshFlatten.luau"], -[81817, "src/Rosetta/codecs/model/Minecraft/init.luau"], -[82369, "src/Rosetta/codecs/model/Minecraft/Colors.luau"], -[82448, "src/Rosetta/codecs/model/Minecraft/Legacy.luau"], -[82555, "src/Rosetta/codecs/model/Minecraft/Packed.luau"], -[82761, "src/Rosetta/codecs/model/Polygon.luau"], -[82995, "src/Rosetta/codecs/model/Rbx/init.luau"], -[83232, "src/Rosetta/codecs/model/Rbx/Binary.luau"], -[83986, "src/Rosetta/codecs/model/Rig.luau"], -[84229, "src/Rosetta/codecs/model/Sampler.luau"], -[84389, "src/Rosetta/codecs/model/Vrml/init.luau"], -[84537, "src/Rosetta/codecs/model/Vrml/Build.luau"], -[85111, "src/Rosetta/codecs/model/Vrml/Fields.luau"], -[85274, "src/Rosetta/codecs/model/Vrml/Geometry.luau"], -[86023, "src/Rosetta/codecs/model/Vrml/Parse.luau"], -[86545, "src/Rosetta/codecs/model/Vrml/Write.luau"], -[87272, "src/Rosetta/codecs/model/Vrml/Xml.luau"], -[87504, "src/Rosetta/codecs/text/Json/init.luau"], -[87773, "src/Rosetta/codecs/text/Json/Decode.luau"], -[88187, "src/Rosetta/codecs/text/Json/Encode.luau"], -[88489, "src/Rosetta/codecs/text/Nbt/init.luau"], -[88842, "src/Rosetta/codecs/text/Nbt/Binary.luau"], -[89534, "src/Rosetta/codecs/text/Nbt/Snbt.luau"], -[90174, "src/Rosetta/codecs/text/Nbt/Value.luau"], -[90412, "src/Rosetta/codecs/text/Text/init.luau"], -[90503, "src/Rosetta/codecs/text/Url/init.luau"], -[90708, "src/Rosetta/codecs/text/Xml/init.luau"], -[91111, "src/Rosetta/codecs/text/Xml/Parse.luau"], -[91851, "src/Rosetta/codecs/video/Dsp.luau"], -[92574, "src/Rosetta/codecs/video/H263/init.luau"], -[92730, "src/Rosetta/codecs/video/H263/Decoder.luau"], -[93588, "src/Rosetta/codecs/video/H263/Tables.luau"], -[93791, "src/Rosetta/codecs/video/H264/init.luau"], -[94164, "src/Rosetta/codecs/video/H264/Bitstream.luau"], -[94439, "src/Rosetta/codecs/video/H264/Cabac.luau"], -[95570, "src/Rosetta/codecs/video/H264/Cavlc.luau"], -[96338, "src/Rosetta/codecs/video/H264/Deblock.luau"], -[96596, "src/Rosetta/codecs/video/H264/Decoder.luau"], -[97605, "src/Rosetta/codecs/video/H264/Inter.luau"], -[97859, "src/Rosetta/codecs/video/H264/Intra.luau"], -[98266, "src/Rosetta/codecs/video/H264/Mb.luau"], -[99172, "src/Rosetta/codecs/video/H264/Params.luau"], -[99619, "src/Rosetta/codecs/video/H264/Slice.luau"], -[99870, "src/Rosetta/codecs/video/H264/Tables.luau"], -[99911, "src/Rosetta/codecs/video/H264/Transform.luau"], -[100076, "src/Rosetta/codecs/video/Legacy/init.luau"], -[100274, "src/Rosetta/codecs/video/Legacy/Cinepak.luau"], -[100571, "src/Rosetta/codecs/video/Legacy/Flic.luau"], -[100938, "src/Rosetta/codecs/video/Legacy/Msvideo1.luau"], -[101056, "src/Rosetta/codecs/video/Legacy/Picture.luau"], -[101164, "src/Rosetta/codecs/video/Legacy/QtRle.luau"], -[101437, "src/Rosetta/codecs/video/Legacy/Smacker.luau"], -[101832, "src/Rosetta/codecs/video/Legacy/Smc.luau"], -[102009, "src/Rosetta/codecs/video/Mpeg1/init.luau"], -[102021, "src/Rosetta/codecs/video/Mpeg2/init.luau"], -[102388, "src/Rosetta/codecs/video/Mpeg2/Decoder.luau"], -[103895, "src/Rosetta/codecs/video/Mpeg2/Tables.luau"], -[104034, "src/Rosetta/codecs/video/Mpeg2/Vlc.luau"], -[104172, "src/Rosetta/codecs/video/Theora/init.luau"], -[104435, "src/Rosetta/codecs/video/Theora/Decoder.luau"], -[105699, "src/Rosetta/codecs/video/Theora/Header.luau"], -[106062, "src/Rosetta/codecs/video/Video/init.luau"], -[106619, "src/Rosetta/codecs/video/Video/Source.luau"], -[106904, "src/Rosetta/containers/Archive.luau"], -[107171, "src/Rosetta/containers/AudioWrap.luau"], -[107674, "src/Rosetta/containers/Avi/init.luau"], -[108226, "src/Rosetta/containers/Chunks.luau"], -[108361, "src/Rosetta/containers/Cpio.luau"], -[108789, "src/Rosetta/containers/Demux.luau"], -[109064, "src/Rosetta/containers/Ebml/init.luau"], -[109377, "src/Rosetta/containers/Fat.luau"], -[110065, "src/Rosetta/containers/Iso9660.luau"], -[110570, "src/Rosetta/containers/IsoBmff/init.luau"], -[110740, "src/Rosetta/containers/IsoBmff/Box.luau"], -[110928, "src/Rosetta/containers/IsoBmff/Demux.luau"], -[111773, "src/Rosetta/containers/IsoBmff/Meta.luau"], -[112294, "src/Rosetta/containers/IsoBmff/Mux.luau"], -[112810, "src/Rosetta/containers/IsoBmff/QtPalette.luau"], -[112927, "src/Rosetta/containers/MacFile.luau"], -[113076, "src/Rosetta/containers/MpegEs.luau"], -[113242, "src/Rosetta/containers/MpegPs/init.luau"], -[113462, "src/Rosetta/containers/MpegTs/init.luau"], -[114254, "src/Rosetta/containers/Ogg/init.luau"], -[114679, "src/Rosetta/containers/Ogg/Mux.luau"], -[114874, "src/Rosetta/containers/Ogg/Page.luau"], -[115043, "src/Rosetta/containers/Riff/init.luau"], -[115360, "src/Rosetta/containers/Tar.luau"], -[115774, "src/Rosetta/containers/Zip/init.luau"], -[116406, "src/Rosetta/core/Adler32.luau"], -[116452, "src/Rosetta/core/Base64.luau"], -[116611, "src/Rosetta/core/Bits.luau"], -[116904, "src/Rosetta/core/Bytes.luau"], -[117431, "src/Rosetta/core/Crc16.luau"], -[117483, "src/Rosetta/core/Crc32.luau"], -[117595, "src/Rosetta/core/Err.luau"], -[117677, "src/Rosetta/core/Input.luau"], -[117753, "src/Rosetta/core/Md5.luau"], -[117912, "src/Rosetta/core/Sniff.luau"], -[117941, "src/Rosetta/data/cbor/init.luau"], -[118040, "src/Rosetta/data/cbor/Codec.luau"], -[118609, "src/Rosetta/data/csv/init.luau"], -[118921, "src/Rosetta/data/ini/init.luau"], -[119167, "src/Rosetta/data/json/init.luau"], -[119259, "src/Rosetta/data/msgpack/init.luau"], -[119348, "src/Rosetta/data/msgpack/Codec.luau"], -[119790, "src/Rosetta/data/nbt/init.luau"], -[119849, "src/Rosetta/data/plist/init.luau"], -[120155, "src/Rosetta/data/plist/Binary.luau"], -[120422, "src/Rosetta/data/snbt/init.luau"], -[120485, "src/Rosetta/data/toml/init.luau"], -[120552, "src/Rosetta/data/toml/Decode.luau"], -[121180, "src/Rosetta/data/toml/Encode.luau"], -[121389, "src/Rosetta/data/xml/init.luau"], -[121445, "src/Rosetta/data/yaml/init.luau"], -[121518, "src/Rosetta/data/yaml/Emit.luau"], -[121808, "src/Rosetta/data/yaml/Parse.luau"], -[123101, "src/Rosetta/font/bdf/init.luau"], -[123390, "src/Rosetta/font/bmfont/init.luau"], -[123817, "src/Rosetta/font/bmfont/Parse.luau"], -[124270, "src/Rosetta/font/eot/init.luau"], -[124502, "src/Rosetta/font/fon/init.luau"], -[124785, "src/Rosetta/font/hershey/init.luau"], -[124980, "src/Rosetta/font/pcf/init.luau"], -[125260, "src/Rosetta/font/psf/init.luau"], -[125580, "src/Rosetta/font/ttf/init.luau"], -[125631, "src/Rosetta/font/type1/init.luau"], -[125990, "src/Rosetta/font/type1/Charstring.luau"], -[126268, "src/Rosetta/font/woff/init.luau"], -[126400, "src/Rosetta/font/woff2/init.luau"], -[126457, "src/Rosetta/font/woff2/Rebuild.luau"], -[126997, "src/Rosetta/host/init.luau"], -[127042, "src/Rosetta/host/Love.luau"], -[127185, "src/Rosetta/host/LuaJIT.luau"], -[127235, "src/Rosetta/host/Luau.luau"], -[127258, "src/Rosetta/host/Roblox.luau"], -[127617, "src/Rosetta/image/ani/init.luau"], -[127797, "src/Rosetta/image/blp/init.luau"], -[128055, "src/Rosetta/image/bmp/init.luau"], -[128470, "src/Rosetta/image/dds/init.luau"], -[128953, "src/Rosetta/image/exr/init.luau"], -[129713, "src/Rosetta/image/exr/Codec.luau"], -[129824, "src/Rosetta/image/exr/Piz.luau"], -[130181, "src/Rosetta/image/gif/init.luau"], -[130697, "src/Rosetta/image/gif/Decode.luau"], -[130760, "src/Rosetta/image/hdr/init.luau"], -[130989, "src/Rosetta/image/hdr/Codec.luau"], -[131200, "src/Rosetta/image/icns/init.luau"], -[131531, "src/Rosetta/image/ico/init.luau"], -[131808, "src/Rosetta/image/ico/Dib.luau"], -[131903, "src/Rosetta/image/ilbm/init.luau"], -[132222, "src/Rosetta/image/jpeg/init.luau"], -[132358, "src/Rosetta/image/ktx/init.luau"], -[133018, "src/Rosetta/image/pcx/init.luau"], -[133282, "src/Rosetta/image/png/init.luau"], -[133862, "src/Rosetta/image/png/Apng.luau"], -[133942, "src/Rosetta/image/png/Decode.luau"], -[134182, "src/Rosetta/image/png/Encode.luau"], -[134337, "src/Rosetta/image/pnm/init.luau"], -[134715, "src/Rosetta/image/pnm/Codec.luau"], -[134992, "src/Rosetta/image/qoi/init.luau"], -[135114, "src/Rosetta/image/qoi/Codec.luau"], -[135264, "src/Rosetta/image/sgi/init.luau"], -[135549, "src/Rosetta/image/sunras/init.luau"], -[135795, "src/Rosetta/image/tga/init.luau"], -[136065, "src/Rosetta/image/tga/Codec.luau"], -[136217, "src/Rosetta/image/tiff/init.luau"], -[137044, "src/Rosetta/image/tiff/Pixels.luau"], -[137434, "src/Rosetta/image/tim/init.luau"], -[137676, "src/Rosetta/image/vtf/init.luau"], -[137911, "src/Rosetta/image/webp/init.luau"], -[138521, "src/Rosetta/image/webp/Alpha.luau"], -[138597, "src/Rosetta/image/webp/Anim.luau"], -[138752, "src/Rosetta/image/xbm/init.luau"], -[138913, "src/Rosetta/image/xpm/init.luau"], -[139181, "src/Rosetta/image/xpm/Names.luau"], -[139237, "src/Rosetta/layered/aseprite/init.luau"], -[139975, "src/Rosetta/layered/ora/init.luau"], -[140262, "src/Rosetta/layered/psd/init.luau"], -[140997, "src/Rosetta/layered/psd/Channels.luau"], -[141349, "src/Rosetta/model/3ds/init.luau"], -[141432, "src/Rosetta/model/3ds/Build.luau"], -[142079, "src/Rosetta/model/3ds/Read.luau"], -[142575, "src/Rosetta/model/3ds/Write.luau"], -[143380, "src/Rosetta/model/3mf/init.luau"], -[143462, "src/Rosetta/model/3mf/Read.luau"], -[144050, "src/Rosetta/model/3mf/Write.luau"], -[144455, "src/Rosetta/model/b3d/init.luau"], -[144510, "src/Rosetta/model/b3d/Read.luau"], -[145081, "src/Rosetta/model/bsp/init.luau"], -[145226, "src/Rosetta/model/bsp/Brush.luau"], -[145504, "src/Rosetta/model/bsp/Quake3.luau"], -[145759, "src/Rosetta/model/dae/init.luau"], -[145948, "src/Rosetta/model/dae/Math.luau"], -[145995, "src/Rosetta/model/dae/Read.luau"], -[147845, "src/Rosetta/model/dae/Write.luau"], -[148214, "src/Rosetta/model/fbx/init.luau"], -[148362, "src/Rosetta/model/fbx/Ascii.luau"], -[148632, "src/Rosetta/model/fbx/Binary.luau"], -[149087, "src/Rosetta/model/fbx/Read.luau"], -[150449, "src/Rosetta/model/fbx/Write.luau"], -[151434, "src/Rosetta/model/fbx/Xform.luau"], -[151475, "src/Rosetta/model/gltf/init.luau"], -[151712, "src/Rosetta/model/gltf/Pack.luau"], -[151781, "src/Rosetta/model/gltf/Read.luau"], -[152512, "src/Rosetta/model/gltf/Write.luau"], -[153192, "src/Rosetta/model/iqm/init.luau"], -[153268, "src/Rosetta/model/iqm/Read.luau"], -[153623, "src/Rosetta/model/iqm/Write.luau"], -[154310, "src/Rosetta/model/ldraw/init.luau"], -[154388, "src/Rosetta/model/ldraw/Colors.luau"], -[154706, "src/Rosetta/model/ldraw/Read.luau"], -[155283, "src/Rosetta/model/lwo/init.luau"], -[155359, "src/Rosetta/model/lwo/Build.luau"], -[155821, "src/Rosetta/model/lwo/Parse.luau"], -[156364, "src/Rosetta/model/mca/init.luau"], -[156706, "src/Rosetta/model/mca/Chunk.luau"], -[156839, "src/Rosetta/model/mca/Lz4Block.luau"], -[156909, "src/Rosetta/model/md2/init.luau"], -[157108, "src/Rosetta/model/md3/init.luau"], -[157336, "src/Rosetta/model/md5/init.luau"], -[157417, "src/Rosetta/model/md5/Read.luau"], -[157850, "src/Rosetta/model/mdl/init.luau"], -[157932, "src/Rosetta/model/mdl/HalfLife.luau"], -[158260, "src/Rosetta/model/mdl/Quake.luau"], -[158478, "src/Rosetta/model/ms3d/init.luau"], -[158550, "src/Rosetta/model/ms3d/Read.luau"], -[158996, "src/Rosetta/model/ms3d/Write.luau"], -[159465, "src/Rosetta/model/obj/init.luau"], -[160207, "src/Rosetta/model/obj/Mtl.luau"], -[160494, "src/Rosetta/model/off/init.luau"], -[160956, "src/Rosetta/model/ply/init.luau"], -[162061, "src/Rosetta/model/ply/Binary.luau"], -[162262, "src/Rosetta/model/pmx/init.luau"], -[162331, "src/Rosetta/model/pmx/Build.luau"], -[162627, "src/Rosetta/model/pmx/Pmd.luau"], -[162962, "src/Rosetta/model/pmx/Read.luau"], -[163366, "src/Rosetta/model/qb/init.luau"], -[163759, "src/Rosetta/model/rbxm/init.luau"], -[164351, "src/Rosetta/model/rbxmx/init.luau"], -[165004, "src/Rosetta/model/robloxmesh/init.luau"], -[165663, "src/Rosetta/model/robloxmesh/Parse.luau"], -[166120, "src/Rosetta/model/robloxmesh/Write.luau"], -[166229, "src/Rosetta/model/schematic/init.luau"], -[166550, "src/Rosetta/model/schematic/Common.luau"], -[166670, "src/Rosetta/model/schematic/Litematic.luau"], -[166881, "src/Rosetta/model/schematic/Mcedit.luau"], -[167125, "src/Rosetta/model/schematic/Sponge.luau"], -[167254, "src/Rosetta/model/smd/init.luau"], -[167321, "src/Rosetta/model/smd/Read.luau"], -[167590, "src/Rosetta/model/smd/Write.luau"], -[167833, "src/Rosetta/model/stl/init.luau"], -[168283, "src/Rosetta/model/stl/Decode.luau"], -[168357, "src/Rosetta/model/usda/init.luau"], -[168566, "src/Rosetta/model/usda/Build.luau"], -[169844, "src/Rosetta/model/usda/Parse.luau"], -[170642, "src/Rosetta/model/usda/Write.luau"], -[171459, "src/Rosetta/model/vox/init.luau"], -[172345, "src/Rosetta/model/vox/Grid.luau"], -[172402, "src/Rosetta/model/vrml/init.luau"], -[172468, "src/Rosetta/model/x/init.luau"], -[172598, "src/Rosetta/model/x/Build.luau"], -[173161, "src/Rosetta/model/x/Parse.luau"], -[173458, "src/Rosetta/model/x3d/init.luau"], -[173536, "src/Rosetta/music/669/init.luau"], -[173742, "src/Rosetta/music/ahx/init.luau"], -[173793, "src/Rosetta/music/far/init.luau"], -[174022, "src/Rosetta/music/hmp/init.luau"], -[174286, "src/Rosetta/music/hvl/init.luau"], -[174337, "src/Rosetta/music/it/init.luau"], -[174755, "src/Rosetta/music/it/Itsex.luau"], -[174871, "src/Rosetta/music/med/init.luau"], -[175518, "src/Rosetta/music/midi/init.luau"], -[175661, "src/Rosetta/music/midi/Smf.luau"], -[176072, "src/Rosetta/music/mod/init.luau"], -[176425, "src/Rosetta/music/mtm/init.luau"], -[176647, "src/Rosetta/music/mus/init.luau"], -[176804, "src/Rosetta/music/okt/init.luau"], -[177085, "src/Rosetta/music/ptm/init.luau"], -[177307, "src/Rosetta/music/s3m/init.luau"], -[177543, "src/Rosetta/music/sf2/init.luau"], -[177586, "src/Rosetta/music/stm/init.luau"], -[177817, "src/Rosetta/music/ult/init.luau"], -[178121, "src/Rosetta/music/umx/init.luau"], -[178337, "src/Rosetta/music/xm/init.luau"], -[178898, "src/Rosetta/music/xmi/init.luau"], -[179106, "src/Rosetta/ops/AudioOps.luau"], -[179555, "src/Rosetta/ops/ImageOps/init.luau"], -[180199, "src/Rosetta/ops/ImageOps/Kernels.luau"], -[180709, "src/Rosetta/ops/LayerOps.luau"], -[180802, "src/Rosetta/ops/MeshOps/init.luau"], -[181838, "src/Rosetta/ops/MeshOps/Greedy.luau"], -[182005, "src/Rosetta/ops/MusicOps.luau"], -[182353, "src/Rosetta/playlist/m3u/init.luau"], -[182706, "src/Rosetta/playlist/pls/init.luau"], -[182884, "src/Rosetta/playlist/xspf/init.luau"], -[183087, "src/Rosetta/subtitle/ass/init.luau"], -[183531, "src/Rosetta/subtitle/srt/init.luau"], -[183704, "src/Rosetta/subtitle/vtt/init.luau"], -[183907, "src/Rosetta/vector/svg/init.luau"], -[183993, "src/Rosetta/vector/svg/Parse.luau"], -[184739, "src/Rosetta/vector/svg/PathData.luau"], -[185107, "src/Rosetta/vector/svg/Render.luau"], -[185524, "src/Rosetta/vector/svg/Style.luau"], -[185896, "src/Rosetta/vector/svg/Write.luau"], -[186096, "src/Rosetta/vector/tiled/init.luau"], -[186276, "src/Rosetta/vector/tiled/Data.luau"], -[186427, "src/Rosetta/vector/tiled/Tmj.luau"], -[187058, "src/Rosetta/vector/tiled/Tmx.luau"], -[187670, "src/Rosetta/video/avi/init.luau"], -[187964, "src/Rosetta/video/fli/init.luau"], -[188115, "src/Rosetta/video/flv/init.luau"], -[188499, "src/Rosetta/video/flv/Amf.luau"], -[188657, "src/Rosetta/video/flv/Mux.luau"], -[188938, "src/Rosetta/video/h264/init.luau"], -[189077, "src/Rosetta/video/mkv/init.luau"], -[189233, "src/Rosetta/video/mkv/Mux.luau"], -[189512, "src/Rosetta/video/mkv/Parse.luau"], -[190233, "src/Rosetta/video/mp4/init.luau"], -[190561, "src/Rosetta/video/mpegps/init.luau"], -[190748, "src/Rosetta/video/mpegts/init.luau"], -[190986, "src/Rosetta/video/ogv/init.luau"], -[191381, "src/Rosetta/video/smk/init.luau"], -[191690, "src/Rosetta/video/smk/Audio.luau"], -[191810, "src/Rosetta/video/y4m/init.luau"] +[37011, "src/Rosetta/codecs/audio/Musepack/Tables.luau"], +[37389, "src/Rosetta/codecs/audio/Opus/init.luau"], +[37403, "src/Rosetta/codecs/audio/Opus/Celt.luau"], +[39250, "src/Rosetta/codecs/audio/Opus/CeltEncoder.luau"], +[40315, "src/Rosetta/codecs/audio/Opus/CeltTables.luau"], +[40375, "src/Rosetta/codecs/audio/Opus/Decoder.luau"], +[40835, "src/Rosetta/codecs/audio/Opus/Mdct.luau"], +[41172, "src/Rosetta/codecs/audio/Opus/Packet.luau"], +[41405, "src/Rosetta/codecs/audio/Opus/Silk.luau"], +[43441, "src/Rosetta/codecs/audio/Opus/SilkTables.luau"], +[43815, "src/Rosetta/codecs/audio/Pcm/init.luau"], +[44078, "src/Rosetta/codecs/audio/Pcm/Convert.luau"], +[44375, "src/Rosetta/codecs/audio/Qoa/init.luau"], +[44657, "src/Rosetta/codecs/audio/Resample/init.luau"], +[45016, "src/Rosetta/codecs/audio/SoundFont/init.luau"], +[45070, "src/Rosetta/codecs/audio/SoundFont/Fallback.luau"], +[45213, "src/Rosetta/codecs/audio/SoundFont/Parse.luau"], +[45726, "src/Rosetta/codecs/audio/SoundFont/Synth.luau"], +[46507, "src/Rosetta/codecs/audio/Stream.luau"], +[46668, "src/Rosetta/codecs/audio/Tracker/init.luau"], +[47150, "src/Rosetta/codecs/audio/Tracker/Load.luau"], +[47428, "src/Rosetta/codecs/audio/Tracker/Mixer.luau"], +[47597, "src/Rosetta/codecs/audio/Tracker/Pcm.luau"], +[47725, "src/Rosetta/codecs/audio/Tracker/Player.luau"], +[49713, "src/Rosetta/codecs/audio/Tracker/Tables.luau"], +[49829, "src/Rosetta/codecs/audio/Tta/init.luau"], +[49946, "src/Rosetta/codecs/audio/Tta/Decode.luau"], +[50198, "src/Rosetta/codecs/audio/Vorbis/init.luau"], +[50211, "src/Rosetta/codecs/audio/Vorbis/Codebook.luau"], +[50595, "src/Rosetta/codecs/audio/Vorbis/Packet.luau"], +[51161, "src/Rosetta/codecs/audio/Vorbis/Setup.luau"], +[51582, "src/Rosetta/codecs/audio/Vorbis/Tables.luau"], +[51621, "src/Rosetta/codecs/audio/VorbisComment.luau"], +[51673, "src/Rosetta/codecs/audio/WavPack/init.luau"], +[51895, "src/Rosetta/codecs/audio/WavPack/Block.luau"], +[53350, "src/Rosetta/codecs/audio/WavPack/Tables.luau"], +[53413, "src/Rosetta/codecs/compress/Brotli/init.luau"], +[53500, "src/Rosetta/codecs/compress/Brotli/Decode.luau"], +[54469, "src/Rosetta/codecs/compress/Brotli/Static.luau"], +[55337, "src/Rosetta/codecs/compress/Bzip2/init.luau"], +[55385, "src/Rosetta/codecs/compress/Bzip2/Decode.luau"], +[55901, "src/Rosetta/codecs/compress/Deflate/init.luau"], +[56227, "src/Rosetta/codecs/compress/Deflate/Compress.luau"], +[56647, "src/Rosetta/codecs/compress/Deflate/Inflate.luau"], +[57082, "src/Rosetta/codecs/compress/Explode.luau"], +[57278, "src/Rosetta/codecs/compress/Lz4.luau"], +[57547, "src/Rosetta/codecs/compress/Lzh/init.luau"], +[58151, "src/Rosetta/codecs/compress/Lzma/init.luau"], +[58691, "src/Rosetta/codecs/compress/Lzma/Crc64.luau"], +[58729, "src/Rosetta/codecs/compress/Lzma/Decode.luau"], +[59202, "src/Rosetta/codecs/compress/Lzma/Filters.luau"], +[59378, "src/Rosetta/codecs/compress/Lzw/init.luau"], +[59646, "src/Rosetta/codecs/compress/Lzx.luau"], +[60080, "src/Rosetta/codecs/compress/PackBits.luau"], +[60170, "src/Rosetta/codecs/compress/Quantum.luau"], +[60407, "src/Rosetta/codecs/compress/UnixCompress.luau"], +[60711, "src/Rosetta/codecs/compress/Xxh32.luau"], +[60780, "src/Rosetta/codecs/compress/Zstd/init.luau"], +[60837, "src/Rosetta/codecs/compress/Zstd/Decode.luau"], +[61795, "src/Rosetta/codecs/compress/Zstd/Xxh64.luau"], +[61947, "src/Rosetta/codecs/entropy/Huffman.luau"], +[62229, "src/Rosetta/codecs/entropy/RangeCoder/init.luau"], +[62240, "src/Rosetta/codecs/entropy/RangeCoder/Decoder.luau"], +[62454, "src/Rosetta/codecs/entropy/RangeCoder/Encoder.luau"], +[62698, "src/Rosetta/codecs/font/Bitmap.luau"], +[62899, "src/Rosetta/codecs/font/Cff/init.luau"], +[63540, "src/Rosetta/codecs/font/GlyphNames.luau"], +[63690, "src/Rosetta/codecs/font/TrueType/init.luau"], +[64004, "src/Rosetta/codecs/font/TrueType/Glyf.luau"], +[64396, "src/Rosetta/codecs/font/TrueType/Tables.luau"], +[64898, "src/Rosetta/codecs/image/Bcn/init.luau"], +[65005, "src/Rosetta/codecs/image/Bcn/Decode.luau"], +[65494, "src/Rosetta/codecs/image/Bcn/Encode.luau"], +[65923, "src/Rosetta/codecs/image/Blend.luau"], +[66302, "src/Rosetta/codecs/image/Dct/init.luau"], +[66683, "src/Rosetta/codecs/image/Etc.luau"], +[66981, "src/Rosetta/codecs/image/Half.luau"], +[67050, "src/Rosetta/codecs/image/Jpeg/init.luau"], +[67404, "src/Rosetta/codecs/image/Jpeg/Arith.luau"], +[67812, "src/Rosetta/codecs/image/Jpeg/Color.luau"], +[68049, "src/Rosetta/codecs/image/Jpeg/Decode.luau"], +[68809, "src/Rosetta/codecs/image/Jpeg/Encode.luau"], +[69690, "src/Rosetta/codecs/image/Jpeg/Scan.luau"], +[70136, "src/Rosetta/codecs/image/Jpeg/Tables.luau"], +[70214, "src/Rosetta/codecs/image/Jpeg/Yuv.luau"], +[70281, "src/Rosetta/codecs/image/Pixels.luau"], +[70545, "src/Rosetta/codecs/image/Quantize/init.luau"], +[71004, "src/Rosetta/codecs/image/Raster.luau"], +[71701, "src/Rosetta/codecs/image/Texel.luau"], +[72074, "src/Rosetta/codecs/image/Texture.luau"], +[72219, "src/Rosetta/codecs/image/Vp8/init.luau"], +[72349, "src/Rosetta/codecs/image/Vp8/Decode.luau"], +[74305, "src/Rosetta/codecs/image/Vp8/Predict.luau"], +[74564, "src/Rosetta/codecs/image/Vp8/Tables.luau"], +[74813, "src/Rosetta/codecs/image/Vp8/Yuv.luau"], +[74932, "src/Rosetta/codecs/image/Vp8L/init.luau"], +[75036, "src/Rosetta/codecs/image/Vp8L/Decode.luau"], +[75889, "src/Rosetta/codecs/image/Vp8L/Encode.luau"], +[76841, "src/Rosetta/codecs/image/Yuv.luau"], +[77109, "src/Rosetta/codecs/model/Draco/init.luau"], +[77441, "src/Rosetta/codecs/model/Draco/Attributes.luau"], +[77910, "src/Rosetta/codecs/model/Draco/Connectivity.luau"], +[79099, "src/Rosetta/codecs/model/Draco/Int64.luau"], +[79248, "src/Rosetta/codecs/model/Draco/KdTree.luau"], +[79607, "src/Rosetta/codecs/model/Draco/Predict.luau"], +[80569, "src/Rosetta/codecs/model/Draco/Reader.luau"], +[81043, "src/Rosetta/codecs/model/Mat4.luau"], +[81302, "src/Rosetta/codecs/model/MeshFlatten.luau"], +[81830, "src/Rosetta/codecs/model/Minecraft/init.luau"], +[82382, "src/Rosetta/codecs/model/Minecraft/Colors.luau"], +[82461, "src/Rosetta/codecs/model/Minecraft/Legacy.luau"], +[82568, "src/Rosetta/codecs/model/Minecraft/Packed.luau"], +[82774, "src/Rosetta/codecs/model/Polygon.luau"], +[83008, "src/Rosetta/codecs/model/Rbx/init.luau"], +[83245, "src/Rosetta/codecs/model/Rbx/Binary.luau"], +[83999, "src/Rosetta/codecs/model/Rig.luau"], +[84242, "src/Rosetta/codecs/model/Sampler.luau"], +[84402, "src/Rosetta/codecs/model/Vrml/init.luau"], +[84550, "src/Rosetta/codecs/model/Vrml/Build.luau"], +[85124, "src/Rosetta/codecs/model/Vrml/Fields.luau"], +[85287, "src/Rosetta/codecs/model/Vrml/Geometry.luau"], +[86036, "src/Rosetta/codecs/model/Vrml/Parse.luau"], +[86558, "src/Rosetta/codecs/model/Vrml/Write.luau"], +[87285, "src/Rosetta/codecs/model/Vrml/Xml.luau"], +[87517, "src/Rosetta/codecs/text/Json/init.luau"], +[87786, "src/Rosetta/codecs/text/Json/Decode.luau"], +[88200, "src/Rosetta/codecs/text/Json/Encode.luau"], +[88502, "src/Rosetta/codecs/text/Nbt/init.luau"], +[88855, "src/Rosetta/codecs/text/Nbt/Binary.luau"], +[89547, "src/Rosetta/codecs/text/Nbt/Snbt.luau"], +[90187, "src/Rosetta/codecs/text/Nbt/Value.luau"], +[90425, "src/Rosetta/codecs/text/Text/init.luau"], +[90516, "src/Rosetta/codecs/text/Url/init.luau"], +[90721, "src/Rosetta/codecs/text/Xml/init.luau"], +[91124, "src/Rosetta/codecs/text/Xml/Parse.luau"], +[91864, "src/Rosetta/codecs/video/Dsp.luau"], +[92587, "src/Rosetta/codecs/video/H263/init.luau"], +[92743, "src/Rosetta/codecs/video/H263/Decoder.luau"], +[93601, "src/Rosetta/codecs/video/H263/Tables.luau"], +[93804, "src/Rosetta/codecs/video/H264/init.luau"], +[94177, "src/Rosetta/codecs/video/H264/Bitstream.luau"], +[94452, "src/Rosetta/codecs/video/H264/Cabac.luau"], +[95583, "src/Rosetta/codecs/video/H264/Cavlc.luau"], +[96351, "src/Rosetta/codecs/video/H264/Deblock.luau"], +[96609, "src/Rosetta/codecs/video/H264/Decoder.luau"], +[97618, "src/Rosetta/codecs/video/H264/Inter.luau"], +[97872, "src/Rosetta/codecs/video/H264/Intra.luau"], +[98279, "src/Rosetta/codecs/video/H264/Mb.luau"], +[99185, "src/Rosetta/codecs/video/H264/Params.luau"], +[99632, "src/Rosetta/codecs/video/H264/Slice.luau"], +[99883, "src/Rosetta/codecs/video/H264/Tables.luau"], +[99924, "src/Rosetta/codecs/video/H264/Transform.luau"], +[100089, "src/Rosetta/codecs/video/Legacy/init.luau"], +[100287, "src/Rosetta/codecs/video/Legacy/Cinepak.luau"], +[100584, "src/Rosetta/codecs/video/Legacy/Flic.luau"], +[100951, "src/Rosetta/codecs/video/Legacy/Msvideo1.luau"], +[101069, "src/Rosetta/codecs/video/Legacy/Picture.luau"], +[101177, "src/Rosetta/codecs/video/Legacy/QtRle.luau"], +[101450, "src/Rosetta/codecs/video/Legacy/Smacker.luau"], +[101845, "src/Rosetta/codecs/video/Legacy/Smc.luau"], +[102022, "src/Rosetta/codecs/video/Mpeg1/init.luau"], +[102034, "src/Rosetta/codecs/video/Mpeg2/init.luau"], +[102401, "src/Rosetta/codecs/video/Mpeg2/Decoder.luau"], +[103908, "src/Rosetta/codecs/video/Mpeg2/Tables.luau"], +[104047, "src/Rosetta/codecs/video/Mpeg2/Vlc.luau"], +[104185, "src/Rosetta/codecs/video/Theora/init.luau"], +[104448, "src/Rosetta/codecs/video/Theora/Decoder.luau"], +[105712, "src/Rosetta/codecs/video/Theora/Header.luau"], +[106075, "src/Rosetta/codecs/video/Video/init.luau"], +[106632, "src/Rosetta/codecs/video/Video/Source.luau"], +[106917, "src/Rosetta/containers/Archive.luau"], +[107184, "src/Rosetta/containers/AudioWrap.luau"], +[107687, "src/Rosetta/containers/Avi/init.luau"], +[108239, "src/Rosetta/containers/Chunks.luau"], +[108374, "src/Rosetta/containers/Cpio.luau"], +[108802, "src/Rosetta/containers/Demux.luau"], +[109077, "src/Rosetta/containers/Ebml/init.luau"], +[109390, "src/Rosetta/containers/Fat.luau"], +[110078, "src/Rosetta/containers/Iso9660.luau"], +[110583, "src/Rosetta/containers/IsoBmff/init.luau"], +[110753, "src/Rosetta/containers/IsoBmff/Box.luau"], +[110941, "src/Rosetta/containers/IsoBmff/Demux.luau"], +[111786, "src/Rosetta/containers/IsoBmff/Meta.luau"], +[112307, "src/Rosetta/containers/IsoBmff/Mux.luau"], +[112823, "src/Rosetta/containers/IsoBmff/QtPalette.luau"], +[112940, "src/Rosetta/containers/MacFile.luau"], +[113089, "src/Rosetta/containers/MpegEs.luau"], +[113255, "src/Rosetta/containers/MpegPs/init.luau"], +[113475, "src/Rosetta/containers/MpegTs/init.luau"], +[114267, "src/Rosetta/containers/Ogg/init.luau"], +[114692, "src/Rosetta/containers/Ogg/Mux.luau"], +[114887, "src/Rosetta/containers/Ogg/Page.luau"], +[115056, "src/Rosetta/containers/Riff/init.luau"], +[115373, "src/Rosetta/containers/Tar.luau"], +[115787, "src/Rosetta/containers/Zip/init.luau"], +[116419, "src/Rosetta/core/Adler32.luau"], +[116465, "src/Rosetta/core/Base64.luau"], +[116624, "src/Rosetta/core/Bits.luau"], +[116917, "src/Rosetta/core/Bytes.luau"], +[117444, "src/Rosetta/core/Crc16.luau"], +[117496, "src/Rosetta/core/Crc32.luau"], +[117608, "src/Rosetta/core/Err.luau"], +[117690, "src/Rosetta/core/Input.luau"], +[117766, "src/Rosetta/core/Md5.luau"], +[117925, "src/Rosetta/core/Sniff.luau"], +[117954, "src/Rosetta/data/cbor/init.luau"], +[118053, "src/Rosetta/data/cbor/Codec.luau"], +[118622, "src/Rosetta/data/csv/init.luau"], +[118934, "src/Rosetta/data/ini/init.luau"], +[119180, "src/Rosetta/data/json/init.luau"], +[119272, "src/Rosetta/data/msgpack/init.luau"], +[119361, "src/Rosetta/data/msgpack/Codec.luau"], +[119803, "src/Rosetta/data/nbt/init.luau"], +[119862, "src/Rosetta/data/plist/init.luau"], +[120168, "src/Rosetta/data/plist/Binary.luau"], +[120435, "src/Rosetta/data/snbt/init.luau"], +[120498, "src/Rosetta/data/toml/init.luau"], +[120565, "src/Rosetta/data/toml/Decode.luau"], +[121193, "src/Rosetta/data/toml/Encode.luau"], +[121402, "src/Rosetta/data/xml/init.luau"], +[121458, "src/Rosetta/data/yaml/init.luau"], +[121531, "src/Rosetta/data/yaml/Emit.luau"], +[121821, "src/Rosetta/data/yaml/Parse.luau"], +[123114, "src/Rosetta/font/bdf/init.luau"], +[123403, "src/Rosetta/font/bmfont/init.luau"], +[123830, "src/Rosetta/font/bmfont/Parse.luau"], +[124283, "src/Rosetta/font/eot/init.luau"], +[124515, "src/Rosetta/font/fon/init.luau"], +[124798, "src/Rosetta/font/hershey/init.luau"], +[124993, "src/Rosetta/font/pcf/init.luau"], +[125273, "src/Rosetta/font/psf/init.luau"], +[125593, "src/Rosetta/font/ttf/init.luau"], +[125644, "src/Rosetta/font/type1/init.luau"], +[126003, "src/Rosetta/font/type1/Charstring.luau"], +[126281, "src/Rosetta/font/woff/init.luau"], +[126413, "src/Rosetta/font/woff2/init.luau"], +[126470, "src/Rosetta/font/woff2/Rebuild.luau"], +[127010, "src/Rosetta/host/init.luau"], +[127055, "src/Rosetta/host/Love.luau"], +[127198, "src/Rosetta/host/LuaJIT.luau"], +[127248, "src/Rosetta/host/Luau.luau"], +[127271, "src/Rosetta/host/Roblox.luau"], +[127630, "src/Rosetta/image/ani/init.luau"], +[127810, "src/Rosetta/image/blp/init.luau"], +[128068, "src/Rosetta/image/bmp/init.luau"], +[128483, "src/Rosetta/image/dds/init.luau"], +[128966, "src/Rosetta/image/exr/init.luau"], +[129726, "src/Rosetta/image/exr/Codec.luau"], +[129837, "src/Rosetta/image/exr/Piz.luau"], +[130194, "src/Rosetta/image/gif/init.luau"], +[130710, "src/Rosetta/image/gif/Decode.luau"], +[130773, "src/Rosetta/image/hdr/init.luau"], +[131002, "src/Rosetta/image/hdr/Codec.luau"], +[131213, "src/Rosetta/image/icns/init.luau"], +[131544, "src/Rosetta/image/ico/init.luau"], +[131821, "src/Rosetta/image/ico/Dib.luau"], +[131916, "src/Rosetta/image/ilbm/init.luau"], +[132235, "src/Rosetta/image/jpeg/init.luau"], +[132371, "src/Rosetta/image/ktx/init.luau"], +[133031, "src/Rosetta/image/pcx/init.luau"], +[133295, "src/Rosetta/image/png/init.luau"], +[133875, "src/Rosetta/image/png/Apng.luau"], +[133955, "src/Rosetta/image/png/Decode.luau"], +[134195, "src/Rosetta/image/png/Encode.luau"], +[134350, "src/Rosetta/image/pnm/init.luau"], +[134728, "src/Rosetta/image/pnm/Codec.luau"], +[135005, "src/Rosetta/image/qoi/init.luau"], +[135127, "src/Rosetta/image/qoi/Codec.luau"], +[135277, "src/Rosetta/image/sgi/init.luau"], +[135562, "src/Rosetta/image/sunras/init.luau"], +[135808, "src/Rosetta/image/tga/init.luau"], +[136078, "src/Rosetta/image/tga/Codec.luau"], +[136230, "src/Rosetta/image/tiff/init.luau"], +[137057, "src/Rosetta/image/tiff/Pixels.luau"], +[137447, "src/Rosetta/image/tim/init.luau"], +[137689, "src/Rosetta/image/vtf/init.luau"], +[137924, "src/Rosetta/image/webp/init.luau"], +[138534, "src/Rosetta/image/webp/Alpha.luau"], +[138610, "src/Rosetta/image/webp/Anim.luau"], +[138765, "src/Rosetta/image/xbm/init.luau"], +[138926, "src/Rosetta/image/xpm/init.luau"], +[139194, "src/Rosetta/image/xpm/Names.luau"], +[139250, "src/Rosetta/layered/aseprite/init.luau"], +[139988, "src/Rosetta/layered/ora/init.luau"], +[140275, "src/Rosetta/layered/psd/init.luau"], +[141010, "src/Rosetta/layered/psd/Channels.luau"], +[141362, "src/Rosetta/model/3ds/init.luau"], +[141445, "src/Rosetta/model/3ds/Build.luau"], +[142092, "src/Rosetta/model/3ds/Read.luau"], +[142588, "src/Rosetta/model/3ds/Write.luau"], +[143393, "src/Rosetta/model/3mf/init.luau"], +[143475, "src/Rosetta/model/3mf/Read.luau"], +[144063, "src/Rosetta/model/3mf/Write.luau"], +[144468, "src/Rosetta/model/b3d/init.luau"], +[144523, "src/Rosetta/model/b3d/Read.luau"], +[145094, "src/Rosetta/model/bsp/init.luau"], +[145239, "src/Rosetta/model/bsp/Brush.luau"], +[145517, "src/Rosetta/model/bsp/Quake3.luau"], +[145772, "src/Rosetta/model/dae/init.luau"], +[145961, "src/Rosetta/model/dae/Math.luau"], +[146008, "src/Rosetta/model/dae/Read.luau"], +[147858, "src/Rosetta/model/dae/Write.luau"], +[148227, "src/Rosetta/model/fbx/init.luau"], +[148375, "src/Rosetta/model/fbx/Ascii.luau"], +[148645, "src/Rosetta/model/fbx/Binary.luau"], +[149100, "src/Rosetta/model/fbx/Read.luau"], +[150462, "src/Rosetta/model/fbx/Write.luau"], +[151447, "src/Rosetta/model/fbx/Xform.luau"], +[151488, "src/Rosetta/model/gltf/init.luau"], +[151725, "src/Rosetta/model/gltf/Pack.luau"], +[151794, "src/Rosetta/model/gltf/Read.luau"], +[152525, "src/Rosetta/model/gltf/Write.luau"], +[153205, "src/Rosetta/model/iqm/init.luau"], +[153281, "src/Rosetta/model/iqm/Read.luau"], +[153636, "src/Rosetta/model/iqm/Write.luau"], +[154323, "src/Rosetta/model/ldraw/init.luau"], +[154401, "src/Rosetta/model/ldraw/Colors.luau"], +[154719, "src/Rosetta/model/ldraw/Read.luau"], +[155296, "src/Rosetta/model/lwo/init.luau"], +[155372, "src/Rosetta/model/lwo/Build.luau"], +[155834, "src/Rosetta/model/lwo/Parse.luau"], +[156377, "src/Rosetta/model/mca/init.luau"], +[156719, "src/Rosetta/model/mca/Chunk.luau"], +[156852, "src/Rosetta/model/mca/Lz4Block.luau"], +[156922, "src/Rosetta/model/md2/init.luau"], +[157121, "src/Rosetta/model/md3/init.luau"], +[157349, "src/Rosetta/model/md5/init.luau"], +[157430, "src/Rosetta/model/md5/Read.luau"], +[157863, "src/Rosetta/model/mdl/init.luau"], +[157945, "src/Rosetta/model/mdl/HalfLife.luau"], +[158273, "src/Rosetta/model/mdl/Quake.luau"], +[158491, "src/Rosetta/model/ms3d/init.luau"], +[158563, "src/Rosetta/model/ms3d/Read.luau"], +[159009, "src/Rosetta/model/ms3d/Write.luau"], +[159478, "src/Rosetta/model/obj/init.luau"], +[160220, "src/Rosetta/model/obj/Mtl.luau"], +[160507, "src/Rosetta/model/off/init.luau"], +[160969, "src/Rosetta/model/ply/init.luau"], +[162074, "src/Rosetta/model/ply/Binary.luau"], +[162275, "src/Rosetta/model/pmx/init.luau"], +[162344, "src/Rosetta/model/pmx/Build.luau"], +[162640, "src/Rosetta/model/pmx/Pmd.luau"], +[162975, "src/Rosetta/model/pmx/Read.luau"], +[163379, "src/Rosetta/model/qb/init.luau"], +[163772, "src/Rosetta/model/rbxm/init.luau"], +[164364, "src/Rosetta/model/rbxmx/init.luau"], +[165017, "src/Rosetta/model/robloxmesh/init.luau"], +[165676, "src/Rosetta/model/robloxmesh/Parse.luau"], +[166133, "src/Rosetta/model/robloxmesh/Write.luau"], +[166242, "src/Rosetta/model/schematic/init.luau"], +[166563, "src/Rosetta/model/schematic/Common.luau"], +[166683, "src/Rosetta/model/schematic/Litematic.luau"], +[166894, "src/Rosetta/model/schematic/Mcedit.luau"], +[167138, "src/Rosetta/model/schematic/Sponge.luau"], +[167267, "src/Rosetta/model/smd/init.luau"], +[167334, "src/Rosetta/model/smd/Read.luau"], +[167603, "src/Rosetta/model/smd/Write.luau"], +[167846, "src/Rosetta/model/stl/init.luau"], +[168296, "src/Rosetta/model/stl/Decode.luau"], +[168370, "src/Rosetta/model/usda/init.luau"], +[168579, "src/Rosetta/model/usda/Build.luau"], +[169857, "src/Rosetta/model/usda/Parse.luau"], +[170655, "src/Rosetta/model/usda/Write.luau"], +[171472, "src/Rosetta/model/vox/init.luau"], +[172358, "src/Rosetta/model/vox/Grid.luau"], +[172415, "src/Rosetta/model/vrml/init.luau"], +[172481, "src/Rosetta/model/x/init.luau"], +[172611, "src/Rosetta/model/x/Build.luau"], +[173174, "src/Rosetta/model/x/Parse.luau"], +[173471, "src/Rosetta/model/x3d/init.luau"], +[173549, "src/Rosetta/music/669/init.luau"], +[173755, "src/Rosetta/music/ahx/init.luau"], +[173806, "src/Rosetta/music/far/init.luau"], +[174035, "src/Rosetta/music/hmp/init.luau"], +[174299, "src/Rosetta/music/hvl/init.luau"], +[174350, "src/Rosetta/music/it/init.luau"], +[174768, "src/Rosetta/music/it/Itsex.luau"], +[174884, "src/Rosetta/music/med/init.luau"], +[175531, "src/Rosetta/music/midi/init.luau"], +[175674, "src/Rosetta/music/midi/Smf.luau"], +[176085, "src/Rosetta/music/mod/init.luau"], +[176438, "src/Rosetta/music/mtm/init.luau"], +[176660, "src/Rosetta/music/mus/init.luau"], +[176817, "src/Rosetta/music/okt/init.luau"], +[177098, "src/Rosetta/music/ptm/init.luau"], +[177320, "src/Rosetta/music/s3m/init.luau"], +[177556, "src/Rosetta/music/sf2/init.luau"], +[177599, "src/Rosetta/music/stm/init.luau"], +[177830, "src/Rosetta/music/ult/init.luau"], +[178134, "src/Rosetta/music/umx/init.luau"], +[178350, "src/Rosetta/music/xm/init.luau"], +[178911, "src/Rosetta/music/xmi/init.luau"], +[179119, "src/Rosetta/ops/AudioOps.luau"], +[179568, "src/Rosetta/ops/ImageOps/init.luau"], +[180212, "src/Rosetta/ops/ImageOps/Kernels.luau"], +[180722, "src/Rosetta/ops/LayerOps.luau"], +[180815, "src/Rosetta/ops/MeshOps/init.luau"], +[181851, "src/Rosetta/ops/MeshOps/Greedy.luau"], +[182018, "src/Rosetta/ops/MusicOps.luau"], +[182366, "src/Rosetta/playlist/m3u/init.luau"], +[182719, "src/Rosetta/playlist/pls/init.luau"], +[182897, "src/Rosetta/playlist/xspf/init.luau"], +[183100, "src/Rosetta/subtitle/ass/init.luau"], +[183544, "src/Rosetta/subtitle/srt/init.luau"], +[183717, "src/Rosetta/subtitle/vtt/init.luau"], +[183920, "src/Rosetta/vector/svg/init.luau"], +[184006, "src/Rosetta/vector/svg/Parse.luau"], +[184752, "src/Rosetta/vector/svg/PathData.luau"], +[185120, "src/Rosetta/vector/svg/Render.luau"], +[185537, "src/Rosetta/vector/svg/Style.luau"], +[185909, "src/Rosetta/vector/svg/Write.luau"], +[186109, "src/Rosetta/vector/tiled/init.luau"], +[186289, "src/Rosetta/vector/tiled/Data.luau"], +[186440, "src/Rosetta/vector/tiled/Tmj.luau"], +[187071, "src/Rosetta/vector/tiled/Tmx.luau"], +[187683, "src/Rosetta/video/avi/init.luau"], +[187977, "src/Rosetta/video/fli/init.luau"], +[188128, "src/Rosetta/video/flv/init.luau"], +[188512, "src/Rosetta/video/flv/Amf.luau"], +[188670, "src/Rosetta/video/flv/Mux.luau"], +[188951, "src/Rosetta/video/h264/init.luau"], +[189090, "src/Rosetta/video/mkv/init.luau"], +[189246, "src/Rosetta/video/mkv/Mux.luau"], +[189525, "src/Rosetta/video/mkv/Parse.luau"], +[190246, "src/Rosetta/video/mp4/init.luau"], +[190574, "src/Rosetta/video/mpegps/init.luau"], +[190761, "src/Rosetta/video/mpegts/init.luau"], +[190999, "src/Rosetta/video/ogv/init.luau"], +[191394, "src/Rosetta/video/smk/init.luau"], +[191703, "src/Rosetta/video/smk/Audio.luau"], +[191823, "src/Rosetta/video/y4m/init.luau"] ] diff --git a/default.project.json b/default.project.json index 1f22683..cccdfd7 100644 --- a/default.project.json +++ b/default.project.json @@ -1,6 +1,6 @@ { "name": "Rosetta", "tree": { - "$path": "build/Rosetta.luau" + "$path": "build/Rosetta.rbxm" } } diff --git a/docs/guide/README.md b/docs/guide/README.md index cae0420..16fcc9f 100644 --- a/docs/guide/README.md +++ b/docs/guide/README.md @@ -41,11 +41,21 @@ as `F`, and its input files as variables such as `pngBytes` (a buffer) or `srtTe ## Installing -**Roblox.** The library is one ModuleScript, [`build/Rosetta.luau`](../../build/Rosetta.luau) (committed; rebuilt by -`python3 -I tools/build.py roblox`). Paste it into a ModuleScript named `Rosetta`, or mount it with Rojo -(`"Rosetta": { "$path": "rosetta/build/Rosetta.luau" }`; this repository's `default.project.json` does, so -`rojo build -o Rosetta.rbxm` or `rojo serve` works from here). Put it where both client and server can see it, for -example ReplicatedStorage: +**Roblox.** Two builds, both committed (rebuilt by `python3 -I tools/build.py roblox`): + +- [`build/Rosetta.rbxm`](../../build/Rosetta.rbxm), the native build: a ModuleScript `Rosetta` with child + ModuleScripts, the chunks (Core, one per heavy codec such as Mpeg2, H264, Jpeg, Opus, and the rest by folder). A + chunk is required the first time one of its modules is, so an Actor that only decodes MPEG-1 and JPEG loads only + those chunks and Core. Roblox compiles native code per ModuleScript within a budget per module; each chunk stays + well under it (tools/bundle.py checks it). Insert the file, or mount it with Rojo + (`"Rosetta": { "$path": "rosetta/build/Rosetta.rbxm" }`; this repository's `default.project.json` does, so + `rojo build -o Rosetta.rbxm` or `rojo serve` works from here). [`build/Rosetta.rbxmx`](../../build/Rosetta.rbxmx) + is the same model as XML. +- [`build/Rosetta.luau`](../../build/Rosetta.luau), one ModuleScript with no native code (one 5.9 MB module is over + the native budget): paste it into a ModuleScript named `Rosetta`, or mount it with + `"$path": "rosetta/build/Rosetta.luau"`. + +Put it where both client and server can see it, for example ReplicatedStorage: ```luau diff --git a/src/Rosetta/codecs/audio/Musepack/Decode.luau b/src/Rosetta/codecs/audio/Musepack/Decode.luau index f38be58..50fc389 100644 --- a/src/Rosetta/codecs/audio/Musepack/Decode.luau +++ b/src/Rosetta/codecs/audio/Musepack/Decode.luau @@ -171,7 +171,9 @@ end -- mpc_compute_new_V: 32 subband samples Y[y .. y + 31] -> 64 V values at V[o .. o + 63] (the ISO 11172-3 matrixing -- through Byeong Gi Lee's fast DCT) -local function newV(Y: { number }, y: number, V: { number }, o: number) +-- (two halves: as one function, its native lowering fails register allocation and the whole function runs +-- interpreted) +local function newVEven(Y: { number }, y: number, V: { number }, o: number) local A00 = Y[y] + Y[y + 31] local A01 = Y[y + 1] + Y[y + 30] local A02 = Y[y + 2] + Y[y + 29] @@ -273,6 +275,12 @@ local function newV(Y: { number }, y: number, V: { number }, o: number) t = -(A12 + A14 + A15) V[o + 46] = t - A08 V[o + 42] = t - A10 - A11 +end + +local function newVOdd(Y: { number }, y: number, V: { number }, o: number) + local A00, A01, A02, A03, A04, A05, A06, A07, A08, A09, A10, A11, A12, A13, A14, A15 + local B00, B01, B02, B03, B04, B05, B06, B07, B08, B09, B10, B11, B12, B13, B14, B15 + local t A00 = (Y[y] - Y[y + 31]) * 0.5006030202 A01 = (Y[y + 1] - Y[y + 30]) * 0.5054709315 A02 = (Y[y + 2] - Y[y + 29]) * 0.5154473186 @@ -384,6 +392,11 @@ local function newV(Y: { number }, y: number, V: { number }, o: number) V[o + 96 - i] = V[o + i] end end + +local function newV(Y: { number }, y: number, V: { number }, o: number) + newVEven(Y, y, V, o) + newVOdd(Y, y, V, o) +end export type State = { version: number, maxBand: number, diff --git a/tools/build.py b/tools/build.py index 82314e8..be5ac25 100644 --- a/tools/build.py +++ b/tools/build.py @@ -1,8 +1,9 @@ #!/usr/bin/env python3 # Build (python3 -I tools/build.py [roblox|luajit ...]): the two outputs of the one Luau source tree. # -# The shipped files are the single-file bundles build/Rosetta.luau (roblox) and build/rosetta.lua (luajit), written by -# tools/bundle.py after each target (committed). The multi-file trees below are internal (gitignored), for the tests: +# The shipped files are the bundles build/Rosetta.luau (roblox, one module, no native code), build/Rosetta.rbxm / +# .rbxmx (roblox, native, chunked) and build/rosetta.lua (luajit), written by tools/bundle.py after each target +# (committed). The multi-file trees below are internal (gitignored), for the tests: # build/_modules/roblox/Rosetta/... darklua convert_require (luau aliases -> Roblox instance paths). Types, --!native # and @native are kept. # build/_modules/luajit/rosetta/... plain Lua 5.1 for LuaJIT / LÖVE: darklua strips types, attributes (@native) and diff --git a/tools/bundle.py b/tools/bundle.py index cc289a8..ec6f066 100644 --- a/tools/bundle.py +++ b/tools/bundle.py @@ -1,7 +1,9 @@ #!/usr/bin/env python3 -# Single-file bundles (python3 -I tools/bundle.py [roblox|luajit ...] [--stage-tests] [--where ]): +# Bundles (python3 -I tools/bundle.py [roblox|luajit ...] [--stage-tests] [--check-rbxm] [--where [chunk] ]): # -# build/Rosetta.luau Roblox (one ModuleScript; also runs under the luau CLI), from src/Rosetta directly +# build/Rosetta.luau Roblox, no native code (one ModuleScript; also runs under the luau CLI), from src/Rosetta +# build/Rosetta.rbxm Roblox, native: a Rosetta ModuleScript + chunk ModuleScripts loaded on demand (see "chunked" +# below); build/Rosetta.rbxmx is the same model as XML. Both written with the roblox target. # build/rosetta.lua LÖVE / LuaJIT (one file), from build/_modules/luajit/rosetta (tools/build.py luajit first) # build/.linemap.json [[first bundle line, source file], ...]: bundle line L of a module starting at line S is # line L - S + 1 of its source file (both bundles keep every source line on its line) @@ -14,11 +16,13 @@ # # Roblox bundle: # --!optimize 2 for the whole file and --!nocheck (types are kept, but a cross-module type such as Bytes.Reader -# cannot resolve once requires are __include calls; native codegen reads the annotations, not the checker). -# --!native cannot apply to one module inside a file, so a --!native module gets @native on every function it -# defines, its module function included (@native does not reach nested functions). The NATIVE lint rule (no -# error / assert in a --!native module or what it requires) is checked again here on the bundled text. +# cannot resolve once requires are __include calls). No --!native / @native: one 5.9 MB module is over Roblox's +# per-module native codegen budget (Studio logs a failure for most of it), so it runs interpreted. # export type -> type (a function body cannot export). +# Chunked build (Rosetta.rbxm): the same module bodies; --!native cannot apply to one module inside a file, so a +# --!native module gets @native on every function it defines, its module function included (@native does not reach +# nested functions). The NATIVE lint rule (no error / assert in a --!native module or what it requires) is checked +# again here on the bundled text. # LuaJIT bundle: compat/luajit.lua runs once at the top; each module's compat header reads it (`__compat`) instead of # require("rosetta._compat"). The bundle sets package.loaded["rosetta._compat"] (when unset), so # require("rosetta._compat").install() keeps working, and _internal("_compat") returns it too. @@ -29,8 +33,11 @@ # __compat) to what its source chunk had. Both bundles are compiled here as a check (luau-compile, luajit -bl). # # --stage-tests: the api test and the docs / example tests (tests/docs/snippets) rewritten to use the bundles, in -# build/_modules/bundle_tests/{luau,luajit} (tools/test.sh runs them). -# --where : the source file and line of a bundle line. +# build/_modules/bundle_tests/{luau,luau_chunked,luajit} (tools/test.sh runs them; luau_chunked runs against +# build/_modules/chunked/Rosetta, the rbxm's ModuleScripts as files). +# --check-rbxm: lune reads build/Rosetta.rbxm, .rbxmx and rojo's build of default.project.json; same tree and sources. +# --where | : the source file and line of a bundle +# line (a Roblox error in the chunked build reads "...Rosetta.:"). import json, os, re, shutil, subprocess, sys HERE = os.path.dirname(os.path.abspath(__file__)) @@ -180,7 +187,7 @@ def write(name, text, linemap): def tool(name): - env = {"luau-compile": "LUAU_COMPILE", "luajit": "LUAJIT"}[name] + env = {"luau-compile": "LUAU_COMPILE", "luau": "LUAU", "luajit": "LUAJIT", "rojo": "ROJO", "lune": "LUNE"}[name] if os.environ.get(env): return [os.environ[env]] if shutil.which(name): @@ -199,7 +206,9 @@ def compile_check(cmd, what): ROSETTA_REQ = re.compile(r"@rosetta(?:/([\w/]+))?") -def bundle_roblox(): +def roblox_modules(): + """the src modules as bundle module bodies: {key: (text, src rel path)}, the --!native keys, the include deps. + The text has no @native yet (native_functions adds it, for the chunked build).""" files = modules(SRC, ".luau") mods, native, deps = {}, set(), {} for key, path in files.items(): @@ -211,16 +220,392 @@ def bundle_roblox(): deps[key] = set(INCLUDES.findall(src)) if is_native: native.add(key) - src = native_functions(src) mods[key] = (src, os.path.relpath(path, ROOT).replace(os.sep, "/")) - check_native(mods, native, deps) + return mods, native, deps + + +def bundle_roblox(): + mods, native, deps = roblox_modules() head = ["--!optimize 2", "--!nocheck", - "-- rosetta (Roblox bundle): GENERATED by tools/bundle.py from src/Rosetta - do not edit.", + "-- rosetta (Roblox bundle, no native code): GENERATED by tools/bundle.py from src/Rosetta - do not edit.", + "-- One ModuleScript, interpreted: as one module it is over Roblox's per-module native codegen budget, so it", + "-- carries no --!native / @native. build/Rosetta.rbxm is the native build (chunked, loaded on demand).", "-- require(this) -> the API (docs/API.md); Rosetta._internal(\"codecs/video/Mpeg1\") -> an internal module.", "-- Error lines map back to the sources through Rosetta.luau.linemap.json (python3 -I tools/bundle.py --where)."] - text, linemap = assemble(head, mods, native) + text, linemap = assemble(head, mods, set()) write("Rosetta.luau", text, linemap) compile_check(tool("luau-compile") + ["--null", os.path.join(BUILD, "Rosetta.luau")], "build/Rosetta.luau") + bundle_chunked(mods, native, deps) + + +# ------------------------------------------------------------------------------------------------ chunked (rbxm) +# build/Rosetta.rbxm: a ModuleScript "Rosetta" (the root: the registry, __include, _internal and a module -> chunk +# map) with one child ModuleScript per chunk. Roblox compiles native code per ModuleScript, within a budget per module +# (Luau's CodegenHeuristicsInstructionLimit, 2^20 IR instructions summed over a module: "exceeded total module +# instruction limit"; and a native code memory limit); the 5.9 MB bundle has 1.5M IR instructions. Each chunk stays +# under CHUNK_SRC_MAX source bytes (the packing limit) and CHUNK_IR_MAX / CHUNK_ASM_MAX of native IR / code (checked +# after, with luau-compile --codegennull), with no function that fails native lowering. +# A chunk returns function(__FILES, __include) that registers its modules into the root's registry. __include of a +# module with no entry yet requires its chunk (require(script:FindFirstChild(name)); under the luau CLI, with no +# `script`, require("@self/" .. name) over the same files in build/_modules/chunked/Rosetta). So requiring the root +# loads Core (what the root runs at load time) and every other chunk on first use, per Actor. +# Chunks: Core; one per hot codec (HOT); the rest packed per family (top folder, or codecs/) in path order. +# A --!native module's functions get @native (a chunk can mix native and non-native modules); a chunk with no native +# module has none. Outputs: build/Rosetta.rbxm (LZ4, written by model/rbxm under the luau CLI), build/Rosetta.rbxmx, +# build/Rosetta.rbxm.linemap.json ({chunk: [[first line, source file], ...]}). +CHUNK_SRC_MAX = 256 * 1024 +CHUNK_IR_MAX = 1 << 18 +CHUNK_ASM_MAX = 4 << 20 +CHUNKED = os.path.join(MODULES, "chunked", "Rosetta") +HOT = [ + ("Mpeg2", ["codecs/video/Mpeg2", "codecs/video/Mpeg1", "codecs/video/Dsp"]), + ("H263", ["codecs/video/H263"]), + ("H264", ["codecs/video/H264"]), + ("Theora", ["codecs/video/Theora"]), + ("Legacy", ["codecs/video/Legacy"]), + ("MpegTs", ["containers/MpegTs", "containers/MpegEs", "containers/MpegPs"]), + ("Dct", ["codecs/image/Dct"]), + ("Jpeg", ["codecs/image/Jpeg"]), + ("Vp8", ["codecs/image/Vp8", "codecs/image/Vp8L"]), + ("Bcn", ["codecs/image/Bcn"]), + ("Png", ["image/png"]), + ("Deflate", ["codecs/compress/Deflate"]), + ("Brotli", ["codecs/compress/Brotli"]), + ("Lzma", ["codecs/compress/Lzma"]), + ("Zstd", ["codecs/compress/Zstd"]), + ("Mpa", ["codecs/audio/Mpa"]), + ("Opus", ["codecs/audio/Opus"]), + ("Vorbis", ["codecs/audio/Vorbis"]), + ("Aac", ["codecs/audio/Aac"]), + ("Flac", ["codecs/audio/Flac"]), + ("Musepack", ["codecs/audio/Musepack"]), + ("WavPack", ["codecs/audio/WavPack"]), + ("Tracker", ["codecs/audio/Tracker"]), + ("Hively", ["codecs/audio/Hively"]), + ("SoundFont", ["codecs/audio/SoundFont"]), + ("Draco", ["codecs/model/Draco"]), +] + + +def under(key, prefix): + return key == prefix or key.startswith(prefix + "/") + + +def family(key): + parts = key.split("/") + if len(parts) == 1: + return "Root" + return "_".join(parts[:2]) if parts[0] == "codecs" and len(parts) > 2 else parts[0] + + +def eager(src): + """the includes a module runs at load time: those on a line with no indentation (a top-level statement; style)""" + return {m.group(1) for line in src.split("\n") if line[:1] not in ("\t", " ") for m in INCLUDES.finditer(line)} + + +def plan_chunks(mods): + """[(chunk name, [module keys])], deterministic: Core, HOT, then the rest packed per family""" + left = dict(mods) + chunks = [] + + def pack(name, keys): + part, size, n = [], 0, [] + for k in keys: + sz = len(mods[k][0]) + if part and size + sz > CHUNK_SRC_MAX - 4096: # the chunk header and wrappers + n.append(part) + part, size = [], 0 + part.append(k) + size += sz + if part: + n.append(part) + for i, p in enumerate(n): + chunks.append((name if len(n) == 1 else "%s_%d" % (name, i + 1), p)) + for k in p: + left.pop(k) + + core, todo = set(), [""] + while todo: + k = todo.pop() + if k not in core: + core.add(k) + todo += sorted(eager(mods[k][0])) + pack("Core", sorted(core)) + for name, prefixes in HOT: + keys = [k for k in left if any(under(k, p) for p in prefixes)] + if not keys: + sys.exit("bundle: HOT chunk %s matches no module" % name) + pack(name, keys) + fams = {} + for k in left: + fams.setdefault(family(k), []).append(k) + for f in sorted(fams): + pack(f, fams[f]) + return chunks + + +ROOT_RUNTIME = """local __FILES = {} +local __LOADED = {} +local __DONE = {} +local __script = script +local __include +local function __chunk(path) + local name = __CHUNK[path] + if name == nil or __DONE[name] then + return nil + end + __DONE[name] = true + local m + if __script ~= nil then + m = __script:FindFirstChild(name) + if m == nil then + error("rosetta: the chunk ModuleScript '" .. name .. "' is missing under " .. __script:GetFullName(), 3) + end + else + m = "@self/" .. name -- the luau CLI: the same tree as files (Rosetta/init.luau, Rosetta/.luau) + end + require(m)(__FILES, __include) + return __FILES[path] +end +__include = function(path) + local r = __LOADED[path] + if r == nil then + local f = __FILES[path] or __chunk(path) + if f == nil then + error("rosetta: no module '" .. tostring(path) .. "'", 2) + end + __LOADED[path] = false -- while it runs (a cycle, or a module that threw) + r = f() + if r == nil then + r = true + end + __LOADED[path] = r + elseif r == false then + error("rosetta: module '" .. path .. "' is required in a cycle or failed to load", 2) + end + return r +end""" + + +def bundle_chunked(mods, native, deps): + check_native(mods, native, deps) + chunks = plan_chunks(mods) + names = [c for c, _ in chunks] + if len(set(names)) != len(names): + sys.exit("bundle: duplicate chunk names") + shutil.rmtree(os.path.dirname(CHUNKED), ignore_errors=True) + os.makedirs(CHUNKED) + sources, linemaps = [], {} + for name, keys in chunks: + nat = sorted(k for k in keys if k in native) + out = ["--!optimize 2", "--!nocheck", + "-- rosetta chunk %s (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit." % name, + "-- %d modules (%d native: @native); the Rosetta root requires it when one of them is first included." % (len(keys), len(nat)), + "-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where).", + "return function(__FILES, __include)"] + lm = [] + for k in keys: + src, rel = mods[k] + if k in native: + src = native_functions(src) + out.append("__FILES[%s] = %sfunction()" % (json.dumps(k), "@native " if k in native else "")) + lm.append([len(out) + 1, rel]) + out += src.rstrip("\n").split("\n") + out.append("end") + out.append("end") + sources.append((name, "\n".join(out) + "\n")) + linemaps[name] = lm + cmap = ["local __CHUNK = {"] + ["\t[%s] = %s," % (json.dumps(k), json.dumps(name)) for name, keys in chunks + for k in sorted(keys)] + ["}"] + root = "\n".join(["--!optimize 2", "--!nocheck", + "-- rosetta (Roblox, native build): GENERATED by tools/bundle.py from src/Rosetta - do not edit.", + "-- The root of build/Rosetta.rbxm: the module registry; each child ModuleScript is a chunk of modules,", + "-- required on the first include of one of them. require(this) -> the API (docs/API.md);", + "-- Rosetta._internal(\"codecs/video/Mpeg1\") -> an internal module."] + + cmap + ROOT_RUNTIME.split("\n") + TAIL.split("\n")) + "\n" + with open(os.path.join(CHUNKED, "init.luau"), "w") as f: + f.write(root) + for name, text in sources: + with open(os.path.join(CHUNKED, name + ".luau"), "w") as f: + f.write(text) + with open(os.path.join(BUILD, "Rosetta.rbxm.linemap.json"), "w") as f: + f.write("{\n" + ",\n".join("%s: [%s]" % (json.dumps(n), ", ".join(json.dumps(x) for x in lm)) + for n, lm in linemaps.items()) + "\n}\n") + for name, text in [("Rosetta", root)] + sources: # Roblox runs a script at O1 unless it says otherwise + if not text.startswith("--!optimize 2\n"): + sys.exit("bundle: chunk %s does not start with --!optimize 2" % name) + codegen_check([("Rosetta", root)] + sources, chunks, native) + write_rbxm(root, sources) + + +def codegen_check(sources, chunks, native): + """every chunk compiles natively (luau-compile --codegennull) within the budget; prints the chunk table""" + paths = [os.path.join(CHUNKED, "init.luau")] + [os.path.join(CHUNKED, n + ".luau") for n, _ in chunks] + stats = os.path.join(MODULES, "chunked", "codegen.json") + cmd = tool("luau-compile") + ["--codegennull", "-O2", "--record-stats=function", "--stats-file=" + stats] + paths + r = subprocess.run(cmd, capture_output=True, text=True) + if r.returncode != 0: + sys.exit("bundle: a chunk does not compile:\n" + (r.stdout + r.stderr)[-3000:]) + with open(stats) as f: + st = json.load(f) + keys = dict(chunks) + rows, bad = [], [] + for (name, text), path in zip(sources, paths): + s = st.get(path) or st[os.path.relpath(path)] + n = len(keys.get(name, [])) + nn = len([k for k in keys.get(name, []) if k in native]) + # luau-compile compiles every function of a file with no @native one; Roblox compiles none of it + fns = s["lowerStats"]["functions"] if nn else [] + ir = sum(x["irCount"] for x in fns) + asm = sum(x["asmSize"] for x in fns) + failed = [x["name"] for x in fns if x["asmCount"] == 0 and x["irCount"] > 0] + if nn and (s["lowerStats"]["regAllocErrors"] or s["lowerStats"]["loweringErrors"]): + failed.append("(%d regalloc / %d lowering errors)" % (s["lowerStats"]["regAllocErrors"], s["lowerStats"]["loweringErrors"])) + rows.append((name, n, nn, len(text), len(fns), ir, asm)) + if len(text) > CHUNK_SRC_MAX and n > 1: + bad.append("%s: %d source bytes > %d" % (name, len(text), CHUNK_SRC_MAX)) + if ir > CHUNK_IR_MAX: + bad.append("%s: %d native IR instructions > %d (split it in HOT)" % (name, ir, CHUNK_IR_MAX)) + if asm > CHUNK_ASM_MAX: + bad.append("%s: %d bytes of native code > %d" % (name, asm, CHUNK_ASM_MAX)) + if failed: + bad.append("%s: native lowering failed: %s" % (name, ", ".join(failed))) + table = os.path.join(MODULES, "chunked", "chunks.txt") + with open(table, "w") as f: + f.write("%-16s %7s %6s %9s %7s %8s %10s\n" % ("chunk", "modules", "native", "source", "@native", "IR", "native code")) + for row in rows: + f.write("%-16s %7d %6d %9d %7d %8d %10d\n" % row) + big = max(rows, key=lambda x: x[5]) + print("bundle: Rosetta.rbxm %d chunks, largest native %s: %d modules, %.0f KB source, %d IR (limit %d), %.2f MB" + " native code (table: %s)" % (len(chunks), big[0], big[1], big[3] / 1024, big[5], CHUNK_IR_MAX, big[6] / 1e6, + os.path.relpath(table, ROOT))) + if bad: + sys.exit("bundle: chunk budget:\n " + "\n ".join(bad)) + + +def long_string(s): + n = 0 + while "]" + "=" * n + "]" in s: + n += 1 + return "[" + "=" * n + "[\n" + s + "]" + "=" * n + "]" + + +RBXM_WRITE = """-- GENERATED by tools/bundle.py: writes build/Rosetta.rbxm / .rbxmx with rosetta's own model/rbxm, model/rbxmx +local Rbx = require("@rosetta/codecs/model/Rbx") +local Rbxm = require("@rosetta/model/rbxm") +local Rbxmx = require("@rosetta/model/rbxmx") +local S = __SOURCES__ +local tree = Rbx.tree(false) +local root = Rbx.add(tree, Rbx.instance("ModuleScript", "Rosetta")) +Rbx.set(root, "Source", "ProtectedString", S[1][2]) +for i = 2, #S do + local c = Rbx.add(root, Rbx.instance("ModuleScript", S[i][1])) + Rbx.set(c, "Source", "ProtectedString", S[i][2]) +end +local HEX = {} +for i = 0, 255 do + HEX[i] = string.format("%02x", i) +end +local function hex(b: buffer): string + local n = buffer.len(b) + local out = buffer.create(n * 2) + for i = 0, n - 1 do + buffer.writestring(out, i * 2, HEX[buffer.readu8(b, i)]) + end + return buffer.tostring(out) +end +local bin = assert(Rbxm.encode(tree, { compression = "lz4" })) +local xml = assert(Rbxmx.encode(tree)) +print(hex(bin)) +print(hex(xml)) +""" + + +def write_rbxm(root, sources): + items = [("Rosetta", root)] + sources + lua = RBXM_WRITE.replace("__SOURCES__", "{\n" + "".join("\t{ %s, %s },\n" % (json.dumps(n), long_string(t)) + for n, t in items) + "}") + script = os.path.join(MODULES, "chunked", "rbxm_write.luau") + with open(script, "w") as f: + f.write(lua) + r = subprocess.run(tool("luau") + [os.path.relpath(script, ROOT)], capture_output=True, text=True, cwd=ROOT) + out = r.stdout.split("\n") + if r.returncode != 0 or len(out) < 2: + sys.exit("bundle: rbxm_write failed:\n" + (r.stdout[-2000:] + r.stderr[-2000:])) + for name, h in (("Rosetta.rbxm", out[0]), ("Rosetta.rbxmx", out[1])): + data = bytes.fromhex(h) + with open(os.path.join(BUILD, name), "wb") as f: + f.write(data) + print("bundle: %-14s %4d ModuleScripts, %.2f MB -> build/%s" % (name, len(items), len(data) / 1e6, name)) + + +LUNE_CHECK = """-- GENERATED by tools/bundle.py --check-rbxm: lune reads the models and compares them with the chunk sources +local fs = require("@lune/fs") +local roblox = require("@lune/roblox") +local process = require("@lune/process") +local dir, models = process.args[1], { table.unpack(process.args, 2) } +local fail = 0 +for _, path in models do + local ok, m = pcall(roblox.deserializeModel, fs.readFile(path)) + local function bad(msg) + print("check-rbxm: " .. path .. ": " .. msg) + fail += 1 + end + if not ok then + bad("does not load: " .. tostring(m)) + elseif #m ~= 1 or m[1].ClassName ~= "ModuleScript" or m[1].Name ~= "Rosetta" then + bad("expected one ModuleScript Rosetta") + else + local root = m[1] + if root.Source ~= fs.readFile(dir .. "/init.luau") then + bad("the root Source differs") + end + local want = {} + for _, f in fs.readDir(dir) do + if f ~= "init.luau" then + want[string.gsub(f, "%.luau$", "")] = true + end + end + local n = 0 + for _, c in root:GetChildren() do + n += 1 + if c.ClassName ~= "ModuleScript" or not want[c.Name] then + bad("unexpected child " .. c.Name) + elseif c.Source ~= fs.readFile(dir .. "/" .. c.Name .. ".luau") then + bad(c.Name .. ": Source differs") + elseif #c:GetChildren() ~= 0 then + bad(c.Name .. " has children") + end + want[c.Name] = nil + end + for k in want do + bad("missing chunk " .. k) + end + if fail == 0 then + print("check-rbxm: " .. path .. ": ok, Rosetta + " .. n .. " chunks, sources identical") + end + end +end +process.exit(if fail == 0 then 0 else 1) +""" + + +def check_rbxm(): + """lune (@lune/roblox) reads build/Rosetta.rbxm, .rbxmx and rojo's build of default.project.json: the same tree + and sources as build/_modules/chunked/Rosetta""" + out = os.path.join(MODULES, "chunked") + rojo_out = os.path.join(out, "rojo.rbxm") + r = subprocess.run(tool("rojo") + ["build", os.path.join(ROOT, "default.project.json"), "-o", rojo_out], + capture_output=True, text=True) + if r.returncode != 0: + sys.exit("bundle: rojo build default.project.json failed:\n" + r.stdout + r.stderr) + script = os.path.join(out, "check.luau") + with open(script, "w") as f: + f.write(LUNE_CHECK) + r = subprocess.run(tool("lune") + ["run", script, CHUNKED, os.path.join(BUILD, "Rosetta.rbxm"), + os.path.join(BUILD, "Rosetta.rbxmx"), rojo_out], text=True) + if r.returncode != 0: + sys.exit("bundle: --check-rbxm failed") # ------------------------------------------------------------------------------------------------ luajit @@ -294,7 +679,11 @@ def stage_tests(): n += 1 with open(os.path.join(STAGE, "luau", ".luaurc"), "w") as f: json.dump(LUAU_RC, f, indent="\t") - print("bundle: %d tests staged -> %s/{luau,luajit}" % (n, os.path.relpath(STAGE, ROOT))) + # the same luau tests against the chunked build (build/_modules/chunked/Rosetta: the rbxm's ModuleScripts as files) + shutil.copytree(os.path.join(STAGE, "luau"), os.path.join(STAGE, "luau_chunked")) + with open(os.path.join(STAGE, "luau_chunked", ".luaurc"), "w") as f: + json.dump(dict(LUAU_RC, aliases=dict(LUAU_RC["aliases"], bundle="../../chunked")), f, indent="\t") + print("bundle: %d tests staged -> %s/{luau,luau_chunked,luajit}" % (n, os.path.relpath(STAGE, ROOT))) def rewrite_api(src, pattern, sub, root): @@ -310,9 +699,14 @@ def rewrite_api(src, pattern, sub, root): return apply(src, edits) -def where(name, line): +def where(name, line, chunk=None): with open(os.path.join(BUILD, name + ".linemap.json")) as f: lm = json.load(f) + if chunk is not None: + if chunk not in lm: + return "%s: no chunk %s (the root, or one of: %s)" % (name, chunk, ", ".join(lm)) + lm = lm[chunk] + name = "%s %s" % (name, chunk) best = None for start, path in lm: if start <= line: @@ -325,7 +719,13 @@ def where(name, line): if __name__ == "__main__": args = sys.argv[1:] if args[:1] == ["--where"]: - print(where(os.path.basename(args[1]), int(args[2]))) + if os.path.basename(args[1]).startswith("Rosetta.rbxm"): + print(where("Rosetta.rbxm", int(args[3]), args[2])) + else: + print(where(os.path.basename(args[1]), int(args[2]))) + sys.exit(0) + if args[:1] == ["--check-rbxm"]: + check_rbxm() sys.exit(0) targets = [a for a in args if not a.startswith("--")] or ([] if "--stage-tests" in args else ["roblox", "luajit"]) if "roblox" in targets: diff --git a/tools/test.sh b/tools/test.sh index a889d17..2b97471 100644 --- a/tools/test.sh +++ b/tools/test.sh @@ -4,7 +4,9 @@ # build/rosetta.lua), then run every tests/**/*.luau twice: under `luau --codegen -O2` (the source, through the # .luaurc aliases) and under `luajit` (build/_modules/luajit/tests/**/*.lua, with the compat prelude). The api test and # the docs / example tests run once more against the bundles (build/Rosetta.luau under luau, build/rosetta.lua under -# LuaJIT; tools/bundle.py --stage-tests). Then the lint, and a check that the committed bundles are up to date. +# LuaJIT; tools/bundle.py --stage-tests) and, under luau, against the chunked build (build/Rosetta.rbxm's ModuleScripts +# as files, build/_modules/chunked). Then the lint, lune / rojo reading the rbxm (tools/bundle.py --check-rbxm), and a +# check that the committed bundles are up to date. # A filter runs only the tests whose path contains it (and the fixture generators whose name contains it), and skips # the lint and the bundle check. RUNTIMES="luau" or "luajit" runs one runtime only. cd "$(dirname "$0")/.." || exit 1 @@ -15,7 +17,7 @@ RUNTIMES=${RUNTIMES:-"luau luajit"} LJPATH='package.path = "build/_modules/luajit/?.lua;build/_modules/luajit/?/init.lua;" .. package.path' # the bundle first: rosetta and rosetta._compat come from build/rosetta.lua, tests.* from the module build LJBUNDLE='package.path = "build/?.lua;build/_modules/luajit/?.lua;build/_modules/luajit/?/init.lua;" .. package.path; require("rosetta")' -BUNDLES="build/Rosetta.luau build/rosetta.lua build/Rosetta.luau.linemap.json build/rosetta.lua.linemap.json" +BUNDLES="build/Rosetta.luau build/rosetta.lua build/Rosetta.luau.linemap.json build/rosetta.lua.linemap.json build/Rosetta.rbxm build/Rosetta.rbxmx build/Rosetta.rbxm.linemap.json" fail=0 python3 -I tools/fixtures.py $1 || { echo "FAILED: fixtures"; exit 1; } python3 -I tools/gen_registry.py > /dev/null || { echo "FAILED: gen_registry"; exit 1; } @@ -48,8 +50,15 @@ for t in $(cd build/_modules/bundle_tests/luau && find . -name '*.luau' | sed 's fi done done +if [[ " $RUNTIMES " == *" luau "* ]]; then + for t in $(cd build/_modules/bundle_tests/luau_chunked && find . -name '*.luau' | sed 's#^\./##' | sort); do + [ -n "$1" ] && [[ "tests/$t" != *$1* ]] && continue + run "tests/$t" "luau, build/Rosetta.rbxm" "$LUAU" --codegen -O2 "build/_modules/bundle_tests/luau_chunked/$t" + done +fi if [ -z "$1" ]; then bash tools/lint.sh || fail=1 + python3 -I tools/bundle.py --check-rbxm || { echo "FAILED: check-rbxm"; fail=1; } if [ -n "$(git status --porcelain -- $BUNDLES)" ]; then git status --short -- $BUNDLES echo "FAILED: the bundles in build/ differ from the committed ones (tools/build.py rewrote them): commit them"