-- rosetta (LuaJIT / LÖVE bundle): GENERATED by tools/bundle.py from src/Rosetta - do not edit. -- require("rosetta") with build/?.lua on package.path, or dofile("build/rosetta.lua"): the API -- (docs/API.md); Rosetta._internal("codecs/video/Mpeg1") -> an internal module. Error lines map back to -- the sources through rosetta.lua.linemap.json (python3 -I tools/bundle.py --where). local __compat = (function() -- compat/luajit.lua: the Luau standard library pieces rosetta uses, for LuaJIT 2.1 (plain and LÖVE), with Luau -- semantics (tests/compat.luau). tools/build.py copies it to build/_modules/luajit/rosetta/_compat.lua and prepends -- `local __compat = require("rosetta._compat") ...` to every built module's first line; tools/bundle.py inlines it at -- the top of build/rosetta.lua. Nothing is installed globally; table / math / string additions only fill gaps. -- buffer = { p = uint8_t*, n = length } with a private metatable (typeof / type say "buffer"); LuaJIT-only -- buffer.toffi(b) / buffer.fromffi(ptr, n). local ffi = require("ffi") local bit = require("bit") local floor = math.floor local rawtype, getmetatable, setmetatable, select, error, pairs, ipairs, next = type, getmetatable, setmetatable, select, error, pairs, ipairs, next local TWO32 = 4294967296 local M = {} -- LuaJIT's bit.* take any number in +-2^51 (reduced mod 2^32) and return a signed int32; Luau returns the uint32. -- The inline `if r < 0 then r = r + 2^32 end` sign fix runs ~45% faster than `r % 2^32` (inflate). -- Divergence: bit.tobit rounds a fractional operand where Luau truncates (the library never passes fractions). do local band, bor, bxor, bnot, lshift, rshift, arshift, bswap = bit.band, bit.bor, bit.bxor, bit.bnot, bit.lshift, bit.rshift, bit.arshift, bit.bswap local B = {} function B.band(a, b, c, d, ...) local r if b == nil then if a == nil then return TWO32 - 1 end r = band(a, -1) else r = band(a, b) if c ~= nil then r = band(r, c) if d ~= nil then r = band(r, d) for i = 1, select("#", ...) do r = band(r, (select(i, ...))) end end end end if r < 0 then r = r + TWO32 end return r end function B.bor(a, b, c, d, ...) local r if b == nil then if a == nil then return 0 end r = band(a, -1) else r = bor(a, b) if c ~= nil then r = bor(r, c) if d ~= nil then r = bor(r, d) for i = 1, select("#", ...) do r = bor(r, (select(i, ...))) end end end end if r < 0 then r = r + TWO32 end return r end function B.bxor(a, b, c, d, e, f, g, h, ...) local r if b == nil then if a == nil then return 0 end r = band(a, -1) else r = bxor(a, b) if c ~= nil then r = bxor(r, c) if d ~= nil then r = bxor(r, d) if e ~= nil then r = bxor(r, e) if f ~= nil then r = bxor(r, f) if g ~= nil then r = bxor(r, g) if h ~= nil then r = bxor(r, h) for i = 1, select("#", ...) do r = bxor(r, (select(i, ...))) end end end end end end end end if r < 0 then r = r + TWO32 end return r end function B.btest(...) return B.band(...) ~= 0 end function B.bnot(a) local r = bnot(a) if r < 0 then r = r + TWO32 end return r end function B.lshift(a, n) if n >= 32 or n <= -32 then return 0 end local r if n < 0 then r = rshift(a, -n) else r = lshift(a, n) end if r < 0 then r = r + TWO32 end return r end function B.rshift(a, n) if n >= 32 or n <= -32 then return 0 end local r if n < 0 then r = lshift(a, -n) else r = rshift(a, n) end if r < 0 then r = r + TWO32 end return r end function B.arshift(a, n) if n <= -32 then return 0 end if n >= 32 then n = 31 end local r if n < 0 then r = lshift(a, -n) else r = arshift(a, n) end if r < 0 then r = r + TWO32 end return r end function B.lrotate(a, n) n = n % 32 local r = n == 0 and band(a, -1) or bor(lshift(a, n), rshift(a, 32 - n)) if r < 0 then r = r + TWO32 end return r end function B.rrotate(a, n) return B.lrotate(a, -n) end function B.extract(a, field, width) width = width or 1 if field < 0 or width <= 0 or field + width > 32 then error("bit32.extract: trying to access non-existent bits", 2) end local r = rshift(a, field) if width < 32 then r = band(r, lshift(1, width) - 1) end if r < 0 then r = r + TWO32 end return r end function B.replace(a, v, field, width) width = width or 1 if field < 0 or width <= 0 or field + width > 32 then error("bit32.replace: trying to access non-existent bits", 2) end local m = width == 32 and -1 or lshift(lshift(1, width) - 1, field) local r = bor(band(a, bnot(m)), band(lshift(v, field), m)) if r < 0 then r = r + TWO32 end return r end function B.countlz(a) a = band(a, -1) if a == 0 then return 32 end local n = 0 if band(a, -65536) == 0 then n = n + 16; a = lshift(a, 16) end if band(a, -16777216) == 0 then n = n + 8; a = lshift(a, 8) end if band(a, -268435456) == 0 then n = n + 4; a = lshift(a, 4) end if band(a, -1073741824) == 0 then n = n + 2; a = lshift(a, 2) end if band(a, -2147483648) == 0 then n = n + 1 end return n end function B.countrz(a) a = band(a, -1) if a == 0 then return 32 end local n = 0 while band(a, 1) == 0 do a = rshift(a, 1) n = n + 1 end return n end function B.byteswap(a) local r = bswap(a) if r < 0 then r = r + TWO32 end return r end M.bit32 = B end do ffi.cdef([[ void *memmove(void *dst, const void *src, size_t n); void *memset(void *s, int c, size_t n); void *calloc(size_t n, size_t size); void free(void *p); ]]) local C = ffi.C local u8p = ffi.typeof("uint8_t*") local i8p = ffi.typeof("int8_t*") local u16p, i16p = ffi.typeof("uint16_t*"), ffi.typeof("int16_t*") local u32p, i32p = ffi.typeof("uint32_t*"), ffi.typeof("int32_t*") local f32p, f64p = ffi.typeof("float*"), ffi.typeof("double*") local u8arr = ffi.typeof("uint8_t[?]") local cast, fstring, fcopy = ffi.cast, ffi.string, ffi.copy local BUF = { __name = "buffer" } BUF.__index = function() error("attempt to index a buffer value", 2) end BUF.__tostring = function(b) return ("buffer: %p"):format(b.p) end M.BUFFER_MT = BUF -- big buffers are calloc'd so they don't count against the 2 GB GC heap of non-GC64 builds (LÖVE); a full -- collection runs every 512 MB of them since the GC doesn't see those bytes local BIG = 262144 local external = 0 local function oob() error("buffer access out of bounds", 3) end local Buf = {} local function create(n) if rawtype(n) ~= "number" or n < 0 then error("buffer.create: invalid size", 2) end n = floor(n) local mem, p if n < BIG then mem = u8arr(n > 0 and n or 1) p = cast(u8p, mem) else external = external + n if external > 536870912 then external = 0 collectgarbage() end local raw = C.calloc(n, 1) if raw == nil then error("buffer.create: out of memory", 2) end mem = ffi.gc(cast(u8p, raw), C.free) p = mem end -- p, n and m are raw fields, so the throwing __index only runs for misuse (b.x on a buffer) return setmetatable({ p = p, n = n, m = mem }, BUF) end Buf.create = create function Buf.len(b) return b.n end -- reads / writes: o must satisfy 0 <= o and o + size <= n (Luau truncates a fractional offset) function Buf.readu8(b, o) if o < 0 or o >= b.n then oob() end return b.p[o] end function Buf.readi8(b, o) if o < 0 or o >= b.n then oob() end return cast(i8p, b.p)[o] end function Buf.readu16(b, o) if o < 0 or o + 2 > b.n then oob() end return cast(u16p, b.p + o)[0] end function Buf.readi16(b, o) if o < 0 or o + 2 > b.n then oob() end return cast(i16p, b.p + o)[0] end function Buf.readu32(b, o) if o < 0 or o + 4 > b.n then oob() end return cast(u32p, b.p + o)[0] end function Buf.readi32(b, o) if o < 0 or o + 4 > b.n then oob() end return cast(i32p, b.p + o)[0] end -- NaNs are checked through their bits before the float is loaded: a NaN with an arbitrary payload, handed back by -- the FFI, can alias LuaJIT's NaN-tagged object values (read as a table / userdata). Return the canonical NaN. local NAN = 0 / 0 function Buf.readf32(b, o) if o < 0 or o + 4 > b.n then oob() end local bits = cast(u32p, b.p + o)[0] if bits % 0x80000000 > 0x7f800000 then return NAN end return cast(f32p, b.p + o)[0] end function Buf.readf64(b, o) if o < 0 or o + 8 > b.n then oob() end local hi = cast(u32p, b.p + o + 4)[0] % 0x80000000 -- little-endian: sign / exponent / top mantissa bits if hi >= 0x7ff00000 and (hi > 0x7ff00000 or cast(u32p, b.p + o)[0] ~= 0) then return NAN end return cast(f64p, b.p + o)[0] end -- integer writes wrap like Luau (300 -> 44, -1 -> 255); the double -> int conversion goes through int32 for -- 8/16-bit stores and through int64 for 32-bit ones, so values in +-2^51 wrap correctly function Buf.writeu8(b, o, v) if o < 0 or o >= b.n then oob() end b.p[o] = v end function Buf.writei8(b, o, v) if o < 0 or o >= b.n then oob() end b.p[o] = v end function Buf.writeu16(b, o, v) if o < 0 or o + 2 > b.n then oob() end cast(u16p, b.p + o)[0] = v end Buf.writei16 = Buf.writeu16 function Buf.writeu32(b, o, v) if o < 0 or o + 4 > b.n then oob() end cast(u32p, b.p + o)[0] = v % TWO32 end Buf.writei32 = Buf.writeu32 function Buf.writef32(b, o, v) if o < 0 or o + 4 > b.n then oob() end cast(f32p, b.p + o)[0] = v end function Buf.writef64(b, o, v) if o < 0 or o + 8 > b.n then oob() end cast(f64p, b.p + o)[0] = v end function Buf.readstring(b, o, count) if o < 0 or count < 0 or o + count > b.n then oob() end return fstring(b.p + o, count) end function Buf.writestring(b, o, s, count) count = count or #s if count < 0 or count > #s then error("buffer.writestring: string length overflow", 2) end if o < 0 or o + count > b.n then oob() end fcopy(b.p + o, s, count) end function Buf.copy(target, toff, source, soff, count) soff = soff or 0 if soff < 0 or soff > source.n then oob() end count = count or (source.n - soff) if count < 0 or soff + count > source.n or toff < 0 or toff + count > target.n then oob() end if count > 0 then C.memmove(target.p + toff, source.p + soff, count) end end function Buf.fill(b, o, v, count) if o < 0 or o > b.n then oob() end count = count or (b.n - o) if count < 0 or o + count > b.n then oob() end if count > 0 then C.memset(b.p + o, v % 256, count) end end function Buf.tostring(b) return fstring(b.p, b.n) end function Buf.fromstring(s) local b = create(#s) fcopy(b.p, s, #s) return b end -- readbits / writebits: bit i of the buffer is bit (i % 8) of byte i // 8 (little-endian bit order), up to 32 bits function Buf.readbits(b, bitOffset, bitCount) if bitCount < 0 or bitCount > 32 then error("bit count is out of range of [0; 32]", 2) end if bitOffset < 0 or bitOffset + bitCount > b.n * 8 then oob() end local v, scale = 0, 1 local i = bitOffset local e = bitOffset + bitCount while i < e do local byte = floor(i / 8) local sh = i % 8 local take = 8 - sh if take > e - i then take = e - i end local x = bit.band(bit.rshift(b.p[byte], sh), bit.lshift(1, take) - 1) v = v + x * scale scale = scale * 2 ^ take i = i + take end return v end function Buf.writebits(b, bitOffset, bitCount, value) if bitCount < 0 or bitCount > 32 then error("bit count is out of range of [0; 32]", 2) end if bitOffset < 0 or bitOffset + bitCount > b.n * 8 then oob() end value = value % TWO32 local i = bitOffset local e = bitOffset + bitCount while i < e do local byte = floor(i / 8) local sh = i % 8 local take = 8 - sh if take > e - i then take = e - i end local m = bit.lshift(bit.lshift(1, take) - 1, sh) local x = bit.band(bit.lshift(value % 256, sh), m) b.p[byte] = bit.bor(bit.band(b.p[byte], bit.bnot(m)), x) value = floor(value / 2 ^ take) i = i + take end end function Buf.toffi(b) return b.p end function Buf.fromffi(ptr, n) local b = create(n) if n > 0 then fcopy(b.p, ptr, n) end return b end M.buffer = Buf end do local BUF = M.BUFFER_MT function M.type(v) local t = rawtype(v) if t == "table" and getmetatable(v) == BUF then return "buffer" end return t end M.typeof = M.type M.isbuffer = function(v) return getmetatable(v) == BUF end end local function arrayIter(s, i) local t, n = s[1], s[2] i = i + 1 local v = t[i] while v == nil and i < n do i = i + 1 v = t[i] end if v ~= nil then return i, v end end function M.__iter(t, s, c) if rawtype(t) == "function" then return t, s, c end if rawtype(t) ~= "table" then error("attempt to iterate over a " .. M.type(t) .. " value", 2) end local mt = getmetatable(t) if rawtype(mt) == "table" and mt.__iter then return mt.__iter(t) end local n = #t -- every key is an integer in 1..n (next(t, n) == nil: nothing after n in the array part, an empty hash part; -- LuaJIT keeps t[0] in the array part, so check it): walk 1..n skipping holes. #t is any border, so sparse maps -- such as {[6] = a, [7] = b} (n = 7, t[1] == nil) and arrays with holes visit every key, as in Luau. if n > 0 and t[0] == nil and next(t, n) == nil then return arrayIter, { t, n }, 0 end return next, t, nil end do local okn, tnew = pcall(require, "table.new") local okc, tclear = pcall(require, "table.clear") if not table.create then function table.create(n, v) local t = okn and tnew(n, 0) or {} if v ~= nil then for i = 1, n do t[i] = v end end return t end end table.clear = table.clear or (okc and tclear) or function(t) for k in pairs(t) do t[k] = nil end end table.unpack = table.unpack or unpack table.pack = table.pack or function(...) return { n = select("#", ...), ... } end table.find = table.find or function(t, v, init) for i = init or 1, #t do if t[i] == v then return i end end return nil end table.move = table.move or function(a1, f, e, t, a2) a2 = a2 or a1 if e >= f then if t > f or t > e or a1 ~= a2 then for i = 0, e - f do a2[t + i] = a1[f + i] end else for i = e - f, 0, -1 do a2[t + i] = a1[f + i] end end end return a2 end -- freeze is advisory on LuaJIT (no read-only tables): it only records the table for isfrozen local frozen = setmetatable({}, { __mode = "k" }) table.freeze = table.freeze or function(t) frozen[t] = true; return t end table.isfrozen = table.isfrozen or function(t) return frozen[t] == true end table.clone = table.clone or function(t) local c = {} for k, v in pairs(t) do c[k] = v end return setmetatable(c, getmetatable(t)) end table.maxn = table.maxn or function(t) local m = 0 for k in pairs(t) do if rawtype(k) == "number" and k > m then m = k end end return m end end do -- math.min / math.max are branch-free in a trace; an if / elseif clamp spawned side traces and ran ~3.5x slower. -- NaN stays NaN, as in Luau (maxsd would return lo). local mmin, mmax = math.min, math.max math.clamp = math.clamp or function(x, lo, hi) if lo > hi then error("max must be greater than or equal to min", 2) end if x ~= x then return x end return mmin(mmax(x, lo), hi) end math.sign = math.sign or function(x) if x > 0 then return 1 elseif x < 0 then return -1 end return 0 end -- Luau rounds half away from zero math.round = math.round or function(x) if x >= 0 then return floor(x + 0.5) end return -floor(-x + 0.5) end math.lerp = math.lerp or function(a, b, t) return t == 1 and b or a + (b - a) * t end math.map = math.map or function(x, a, b, c, d) return c + (d - c) * (x - a) / (b - a) end math.isnan = math.isnan or function(x) return x ~= x end math.isinf = math.isinf or function(x) return x == math.huge or x == -math.huge end math.isfinite = math.isfinite or function(x) return x == x and x ~= math.huge and x ~= -math.huge end -- stub: deterministic but not Roblox's Perlin noise (nothing in the library depends on its values) math.noise = math.noise or function(x, y, z) local s = math.sin((x or 0) * 12.9898 + (y or 0) * 78.233 + (z or 0) * 37.719) * 43758.5453 return (s - floor(s)) - 0.5 end end string.split = string.split or function(s, sep) sep = sep or "," local out = {} if sep == "" then for i = 1, #s do out[i] = s:sub(i, i) end return out end local i = 1 while true do local a, b = s:find(sep, i, true) if not a then out[#out + 1] = s:sub(i) return out end out[#out + 1] = s:sub(i, a - 1) i = b + 1 end end do -- Lua 5.1 patterns cannot hold a NUL byte: %z stands for it local U = { charpattern = "[%z\x01-\x7F\xC2-\xFD][\x80-\xBF]*" } local char, byte = string.char, string.byte local function enc(c) if c < 0x80 then return char(c) elseif c < 0x800 then return char(0xC0 + floor(c / 64), 0x80 + c % 64) elseif c < 0x10000 then return char(0xE0 + floor(c / 4096), 0x80 + floor(c / 64) % 64, 0x80 + c % 64) end return char(0xF0 + floor(c / 262144), 0x80 + floor(c / 4096) % 64, 0x80 + floor(c / 64) % 64, 0x80 + c % 64) end function U.char(...) local n = select("#", ...) if n == 1 then return enc((...)) end local out = {} for i = 1, n do out[i] = enc((select(i, ...))) end return table.concat(out) end local function dec(s, i) local c = byte(s, i) if not c then return nil end if c < 0x80 then return c, 1 end local n, v if c >= 0xF0 and c < 0xF8 then n, v = 4, c % 8 elseif c >= 0xE0 then n, v = 3, c % 16 elseif c >= 0xC2 then n, v = 2, c % 32 else return nil end if c >= 0xF8 then return nil end for k = 1, n - 1 do local cc = byte(s, i + k) if not cc or cc < 0x80 or cc >= 0xC0 then return nil end v = v * 64 + cc % 64 end if (n == 3 and v < 0x800) or (n == 4 and (v < 0x10000 or v > 0x10FFFF)) or (v >= 0xD800 and v <= 0xDFFF) then return nil end return v, n end function U.codes(s) local i = 1 return function() if i > #s then return nil end local c, n = dec(s, i) if not c then error("invalid UTF-8 code", 2) end local p = i i = i + n return p, c end end function U.codepoint(s, i, j) i = i or 1 if i < 0 then i = #s + i + 1 end j = j or i if j < 0 then j = #s + j + 1 end local out, k = {}, 0 while i <= j do local c, n = dec(s, i) if not c then error("invalid UTF-8 code", 2) end k = k + 1 out[k] = c i = i + n end return unpack(out, 1, k) end function U.len(s, i, j) i = i or 1 j = j or #s if i < 0 then i = #s + i + 1 end if j < 0 then j = #s + j + 1 end local n = 0 while i <= j do local c, l = dec(s, i) if not c then return nil, i end n = n + 1 i = i + l end return n end local function iscont(s, i) local c = byte(s, i) return c ~= nil and c >= 0x80 and c < 0xC0 end function U.offset(s, n, i) i = i or (n >= 0 and 1 or #s + 1) if i < 0 then i = #s + i + 1 end if n == 0 then while i > 1 and iscont(s, i) do i = i - 1 end return i end if iscont(s, i) then error("initial position is a continuation byte", 2) end if n > 0 then n = n - 1 while n > 0 and i <= #s do i = i + 1 while iscont(s, i) do i = i + 1 end n = n - 1 end if n == 0 then return i end return nil end while n < 0 and i > 1 do i = i - 1 while i > 1 and iscont(s, i) do i = i - 1 end n = n + 1 end if n == 0 then return i end return nil end function U.graphemes(s) return U.codes(s) end M.utf8 = utf8 or U end function M.install(env) env = env or _G env.buffer = env.buffer or M.buffer env.bit32 = env.bit32 or M.bit32 env.utf8 = env.utf8 or M.utf8 env.typeof = env.typeof or M.typeof return M end return M end)() if package and package.loaded and package.loaded["rosetta._compat"] == nil then package.loaded["rosetta._compat"] = __compat end local __FILES = {} local __LOADED = {} local function __include(path) local r = __LOADED[path] if r == nil then local f = __FILES[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 __LOADED["_compat"] = __compat __FILES[""] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict -- 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 = {} local KIND_CATEGORY= { 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= {} local function module(entry) 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, category) return category == nil or entry.category == category end local function find(key, category) local k = string.lower(key) for _, e in __iter(Registry) do if e.name == k and inCategory(e, category) then return e end end for _, e in __iter(Registry) do if inCategory(e, category) and table.find(e.extensions, k) then return e end end return nil end local function detect(buf, name, category, format) if format then local e = find(format, category) if not e then return nil, Err.new(Err.UNKNOWN_FORMAT, "no format named " .. format .. ((category and((" in " .. category ))or("")))) end return e, nil end local ext = Input.extension(name) local best= nil local bestScore = 0 for _, e in __iter(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 =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" .. ((name and((" (" .. name .. ")" ))or(""))) .. ((category and((" for " .. category ))or("")))) 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, name, o) 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, formatName) 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) 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 =total+ n end local a = Types.Audio.new(dec.sampleRate, channels, total) local o = 0 for _, p in __iter(parts) do buffer.copy(a.samples, o, p) o =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) local dir = string.match(path, "^(.*[/\\])") or "" return function(uri) 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) return string.char((tonumber(h, 16) )) end) for part in __iter(string.gmatch(u, "[^/\\]+")) do if part == ".." then return nil end end local b = host.readFile(dir .. u) return b end end local load local function pageLoader(value, name, o) if type(value) ~= "table" or value.kind ~= "font" or type(value.meta) ~= "table" or type(value.meta.pageFiles) ~= "table" then return end local user= o.loadPage if value.pages or (value.meta.pageLoader and type(user) ~= "function") then return end local dir = (name and{string.match(name, "^(.*[/\\])") or "" }or{nil })[1] if type(user) ~= "function" and not (dir and host.hasFiles) then return end value.meta.pageLoader = function(file, page) local src if type(user) == "function" then src = (user )(file, page) else src = (dir ) .. 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, formatName, o) 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 = (type(payload) == "string" and{payload }or{list[1].name })[1] 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, track) 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 = (type(track.codecDelay) == "number" and track.codecDelay > 0 and{(math.floor(track.codecDelay * dec.sampleRate + 0.5) )}or{0 })[1] local length = (type(track.playDuration) == "number" and track.playDuration > 0 and{(math.floor(track.playDuration * dec.sampleRate + 0.5) )}or{nil })[1] if skip > 0 or length then dec = AudioWrap.trim(dec, skip, length) end end return dec, oerr end local function withHooks(o) 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) return F.load(b, { category = "image" }) end end if c.encodeImage == nil then c.encodeImage = function(img, format) return F.save(img, nil, { format = format, category = "image" }) end end if c.decodeModule == nil then c.decodeModule = function(b, format) return F.load(b, { category = "music", format = format }) end end return c end function F.load(src, opts) local o= 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 = (type(dec) == "table" and dec.kind == "video" and{dec }or{(drain(dec) )})[1] 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, opts) local o= 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 local function videoToImage(v, o) 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((want and{(math.min(want, cap) )}or{cap})[1]) 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 = (type(v.frameRate) == "number" and v.frameRate > 0 and((1 / v.frameRate ))or(0.1 )) local images, delays= {}, {} local t0= 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 = (type(f.duration) == "number" and f.duration > 0 and{f.duration }or{defaultDur })[1] local delay = dur if fps then local start= t0 or f.pts t0 = start local slots = math.ceil((f.pts - start + dur) * fps - 1e-6) - taken delay = slots / fps taken =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 = (type(v.loops) == "number" and{v.loops }or{0 })[1] 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, o) 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= __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, dest, o) 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 .. ((category and((" for " .. category ))or("")))) 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 __iter(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" .. ((alt and(("; try " .. alt ))or("")))), 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) if type(scene.textures) ~= "table" then return nil end for _, tex in __iter(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, dest, opts) local o= 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 __iter(o.files) do local fok, ferr = host.writeFile(dir .. fname, (type(data) == "string" and{(buffer.fromstring(data) )}or{data})[1]) 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, opts) 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, format, opts) local o= 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, opts) local o= 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 function F.formats(category) local out = {} for _, e in __iter(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) 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, category) local o= (opts and{(table.clone(opts) )}or{{} })[1] o.category = category return o end for category in __iter(Types.CATEGORIES) do local cat= category F[cat] = { load = function(src, opts) return F.load(src, with(opts, cat)) end, open = function(src, opts) return F.open(src, with(opts, cat)) end, save = function(value, dest, opts) return F.save(value, dest, with(opts, cat)) end, formats = function() return F.formats(cat) end, } end F.data.null = Types.null for _, fn in __iter({ "toBodies", "fromBodies", "tessellate" }) do local name= fn F.cad[name] = function(value, opts) local o= (opts and{(table.clone(opts) )}or{{} })[1] 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 __iter({ "new", "addPattern", "setCell", "getCell", "addSample", "addInstrument", "note" }) do local name= fn F.music[name] = function(...) return (F.ops.music )[name](...) end end F.video.fromImage = function(img, opts) 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 __iter(img.frames) do delays[i] = (type(f.delay) == "number" and f.delay > 0 and{f.delay }or{0.1 })[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, delays, opts) return Video.fromFrames(images, delays, opts) end F.video.codecs = Video F.model.loadTextures = function(scene, opts) local errs= {} if type(scene) ~= "table" or type(scene.textures) ~= "table" then return scene, errs end local resolve= opts and opts.resolve for i, tex in __iter(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= { 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, w, h, opts) 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, k) local make = OPS[k] if not make then return nil end local m = make() rawset(t, k, m) return m end, }) ) return F end __FILES["Registry"] = function() --!strict -- 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. local list= { { 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 = "lmp", category = "image", path = "image/lmp", extensions = { "lmp" }, mime = { "image/x-quake-lmp" }, deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/image/Miptex" }, caps = { decode = true, encode = true, alpha = true, depths = { 8 }, variants = { "qpic", "palette", "colormap" } }, load = function() return __include("image/lmp") 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 = "spr", category = "image", path = "image/spr", extensions = { "spr" }, mime = { "image/x-quake-sprite" }, deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/image/Miptex" }, caps = { decode = true, encode = true, alpha = true, animation = true, variants = { "quake", "halflife", "spr32" } }, load = function() return __include("image/spr") 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 = "ase", category = "model", path = "model/ase", extensions = { "ase", "ask" }, mime = { "model/x-ase", "text/plain" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Text", "codecs/model/Mat4" }, caps = { decode = true, encode = true, text = true, materials = true, cameras = true, lights = true, vertexColors = true }, load = function() return __include("model/ase") 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", "codecs/image/Miptex", "codecs/model/Patch" }, caps = { decode = true, encode = false, variants = { "quake", "bsp2", "2psb", "halflife", "quake2", "quake3" }, lightmaps = true, collision = true, visibility = true }, 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 = "godot", category = "model", path = "model/godot", extensions = { "tscn", "escn" }, mime = { "application/x-godot-scene" }, deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/text/GodotVariant", "codecs/model/Mat4" }, caps = { decode = true, encode = true, text = true, materials = true, cameras = true, lights = true, instances = true }, load = function() return __include("model/godot") 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 = "map", category = "model", path = "model/map", extensions = { "map" }, mime = { "text/x-quake-map" }, deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Miptex", "codecs/model/Brush", "codecs/model/Patch" }, caps = { decode = true, encode = true, variants = { "quake", "valve220", "quake2", "quake3" }, patches = true }, load = function() return __include("model/map") 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 = "t3d", category = "model", path = "model/t3d", extensions = { "t3d" }, mime = { "text/x-unreal-t3d" }, deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/text/Text", "codecs/model/Brush" }, caps = { decode = true, encode = false, text = true, brushes = true, actors = true }, load = function() return __include("model/t3d") 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 = "unitypackage", category = "archive", path = "archive/unitypackage", extensions = { "unitypackage" }, mime = { "application/x-unitypackage" }, deps = { "core/Err", "core/Bytes", "core/Md5", "codecs/compress/Deflate", "containers/Archive", "containers/Tar" }, caps = { decode = true, encode = true }, load = function() return __include("archive/unitypackage") 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 = "wad2", category = "archive", path = "archive/wad2", extensions = { "wad" }, mime = { "application/x-quake-wad" }, deps = { "core/Err", "core/Bytes", "core/Input", "Types", "containers/Archive", "codecs/image/Pixels", "codecs/image/Miptex" }, caps = { decode = true, encode = true, images = true, variants = { "wad2", "wad3" } }, load = function() return __include("archive/wad2") 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 = "q3shader", category = "data", path = "data/q3shader", extensions = { "shader" }, mime = { "text/x-quake3-shader" }, deps = { "core/Err", "core/Bytes" }, caps = { decode = true, encode = true }, load = function() return __include("data/q3shader") end, }, { name = "q3skin", category = "data", path = "data/q3skin", extensions = { "skin" }, mime = { "text/x-quake3-skin" }, deps = { "core/Err", "core/Bytes" }, caps = { decode = true, encode = true }, load = function() return __include("data/q3skin") 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 = "tres", category = "data", path = "data/tres", extensions = { "tres" }, mime = { "application/x-godot-resource" }, deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/text/GodotVariant" }, caps = { decode = true, encode = true, ordered = true }, load = function() return __include("data/tres") 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 = "ldtk", category = "vector", path = "vector/ldtk", extensions = { "ldtk" }, mime = { "application/x-ldtk+json" }, deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/text/Json" }, caps = { decode = true, encode = true, levels = true, worlds = true, intGrid = true, entities = true }, load = function() return __include("vector/ldtk") end, }, { name = "ogmo", category = "vector", path = "vector/ogmo", extensions = { "ogmo" }, mime = { "application/x-ogmo+json" }, deps = { "core/Err", "core/Bytes", "core/Sniff", "core/Base64", "Types", "codecs/text/Json" }, caps = { decode = true, encode = true, projects = true, entities = true, decals = true }, load = function() return __include("vector/ogmo") 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() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict -- 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 = {} -- 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). local BPP= { rgba8 = 4, rgba16 = 8, rgbaf32 = 16, rgb8 = 3, gray8 = 1, gray16 = 2, graya8 = 2, alpha8 = 1, } Types.BPP = (table.freeze(BPP) )-- one frame of an animation (GIF, APNG, WebP): the image is the frame's own rectangle, composited at x, y local Image = {} function Image.new(width, height, format) local f= format or "rgba8" local size if f == "yuv420p" then local cw, ch = math.floor((width + 1) / 2), math.floor((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) return BPP[format] end Types.Image = Image local Audio = {} function Audio.new(sampleRate, channels, frames) return { kind = "audio", sampleRate = sampleRate, channels = channels, frames = frames, samples = buffer.create(frames * channels * 4), tags = {}, meta = {}, } end Types.Audio = Audio local Midi = {} function Midi.new(division) 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. -- a voxel grid (MagicaVoxel): one byte per cell, 0 = empty, 1..255 = palette index-- 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.-- a codec's decoder instance (codecs/video/Video registry entries create them): packets in, pictures out local Voxels = {} function Voxels.new(sx, sy, sz, palette) 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 , materials = nil } end function Voxels.get(v, x, y, z) return buffer.readu8(v.data, x + v.size[1] * (y + v.size[2] * z)) end function Voxels.set(v, x, y, z, index) buffer.writeu8(v.data, x + v.size[1] * (y + v.size[2] * z), index) end Types.Voxels = Voxels local Scene = {} function Scene.new() return { kind = "scene", nodes = {}, roots = {}, meshes = {}, materials = {}, textures = {}, cameras = {}, lights = {}, skins = {}, animations = {}, voxels = nil, meta = {}, } end local COMPONENT_SIZE= { 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) ) function Scene.accessor(data, type, components, count) 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) 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, name) 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) 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, c) return f(d, i * stride + c * 4) end elseif t == "f64" then local f = rb.readf64 return function(i, c) return f(d, i * stride + c * 8) end elseif t == "u8" or t == "unorm8" then local f, k = rb.readu8, t == "unorm8" and 1 / 255 or 1 return function(i, c) return f(d, i * stride + c) * k end elseif t == "u16" or t == "unorm16" then local f, k = rb.readu16, t == "unorm16" and 1 / 65535 or 1 return function(i, c) return f(d, i * stride + c * 2) * k end elseif t == "u32" then local f = rb.readu32 return function(i, c) return f(d, i * stride + c * 4) end elseif t == "i8" then local f = rb.readi8 return function(i, c) return f(d, i * stride + c) end elseif t == "snorm8" then local f = rb.readi8 return function(i, c) return math.max(f(d, i * stride + c) / 127, -1) end elseif t == "i16" then local f = rb.readi16 return function(i, c) return f(d, i * stride + c * 2) end elseif t == "snorm16" then local f = rb.readi16 return function(i, c) return math.max(f(d, i * stride + c * 2) / 32767, -1) end elseif t == "i32" then local f = rb.readi32 return function(i, c) 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, b) 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 =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) 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 function Scene.flatten(scene) local out= {} local nodes = scene.nodes or {} local roots = scene.roots if not roots or #roots == 0 then local child = {} for _, n in __iter(nodes) do for _, c in __iter(n.children or {}) do child[c] = true end end roots = {} for i in __iter(nodes) do if not child[i] then table.insert(roots, i) end end end local seen= {} local function visit(i, parent) local node = nodes[i] if not node or seen[i] then return end seen[i] = true local m = Scene.nodeMatrix(node) local world = (parent == IDENTITY and{m }or{(m == IDENTITY and{parent }or{(Scene.mul(parent, m) )})[1]})[1] local mesh = node.mesh and scene.meshes[node.mesh] if mesh then for _, p in __iter(mesh.primitives) do table.insert(out, { primitive = p, matrix = world, node = i, mesh = node.mesh }) end end for _, c in __iter(node.children or {}) do visit(c, world) end end for _, r in __iter(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) -- 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. -- one bitmap glyph: a 1-bit (or grey) image in pixels with y down, placed relative to the pen on the baseline 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= (setmetatable({}, { __mode = "k" }) ) function Types.object(t, keys) local o= t or {} if getmetatable(o) == nil then setmetatable(o, OBJECT) end objectMeta[o] = keys or {} return o end function Types.isObject(v) return type(v) == "table" and objectMeta[v] ~= nil end function Types.set(o, k, v) 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, b) 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, emptyIsMap) 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 =c+ 1 end return c == n end function Types.keys(t) local order = objectMeta[t] local out, seen = {}, {} if order then for _, k in __iter(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 , 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", ...). local DateMeta = {} local function p2(n) return string.format("%02d", n) end local function fmtDate(d) local s= "" 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 =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 =s.. "." .. (string.gsub(f, "0+$", "")) end if d.offset then if d.offset == 0 then s =s.. "Z" else local o = math.abs(d.offset) s =s.. (d.offset < 0 and"-" or"+") .. p2(math.floor(o / 60)) .. ":" .. p2(o % 60) end end end return s end DateMeta.__tostring = fmtDate DateMeta.__eq = function(a, b) 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, m, d) y = (m <= 2 and((y - 1 ))or(y )) local era = math.floor(((y >= 0 and{y }or{(y - 399)})[1]) / 400 ) local yoe = y - era * 400 local mp = (m + 9) % 12 local doy = math.floor((153 * mp + 2) / 5 )+ d - 1 local doe = yoe * 365 + math.floor(yoe / 4 )- math.floor(yoe / 100 )+ doy return era * 146097 + doe - 719468 end local function civilFromDays(z) z =z+ 719468 local era = math.floor(((z >= 0 and{z }or{(z - 146096)})[1]) / 146097 ) local doe = z - era * 146097 local yoe = math.floor((doe - math.floor(doe / 1460 )+ math.floor(doe / 36524 )- math.floor(doe / 146096)) / 365 ) local y = yoe + era * 400 local doy = doe - (365 * yoe + math.floor(yoe / 4 )- math.floor(yoe / 100)) local mp = math.floor((5 * doy + 2) / 153 ) local d = doy - math.floor((153 * mp + 2) / 5 )+ 1 local m = (mp < 10 and((mp + 3 ))or((mp - 9 ))) return ((m <= 2 and((y + 1 ))or(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) local d= {} for k, v in __iter(f) do d[k] = v end if d.kind == nil then d.kind = (d.year and d.hour and{(d.offset and"datetime" or"datetime-local") }or{d.year and"date-local" or"time-local" })[1] end return (setmetatable(d, DateMeta) ) end function DateLib.is(v) return type(v) == "table" and getmetatable(v) == DateMeta end function DateLib.valid(d) 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) local d= {} local rest= 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 if rest == "" then return (DateLib.valid(d) and{(DateLib.new(d) )}or{nil })[1] 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 local sec, r3 = string.match(rest, "^:(%d%d)(.*)$") if not sec then return nil end d.second = tonumber(sec) rest = r3 local frac, r4 = string.match(rest, "^%.(%d+)(.*)$") if frac then d.nanosecond = tonumber(string.sub(frac .. "000000000", 1, 9)) rest = r4 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) ), (tonumber(om) ) if oh_n > 23 or om_n > 59 then return nil end d.offset = (oh_n * 60 + om_n) * (sign == "-" and-1 or 1) end end return (DateLib.valid(d) and{(DateLib.new(d) )}or{nil })[1]end function DateLib.toUnix(d) local days = (d.year and{(daysFromCivil(d.year, d.month or 1, d.day or 1) )}or{0 })[1] 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, offset) local off = offset or 0 local whole = math.floor(t) local ns = math.floor((t - whole) * 1e9 + 0.5) if ns >= 1e9 then whole =whole+ 1 ns =ns- 1e9 end local lt = whole + off * 60 local days = math.floor(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 = math.floor(secs / 3600), minute = (math.floor(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. local Vector = {} function Vector.new(width, height) 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`). local Layered = {} function Layered.new(width, height) return { kind = "layered", width = width, height = height, layers = {}, frames = nil, meta = {} } end function Layered.layer(name, image, x, y) return { name = name, image = image, x = x or 0, y = y or 0, opacity = 1, blend = "normal", visible = true } end function Layered.group(name, children) 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). local TileMap = {} function TileMap.new(width, height, tileWidth, tileHeight) return { kind = "tilemap", width = width, height = height, tileWidth = tileWidth, tileHeight = tileHeight, orientation = "orthogonal", tilesets = {}, layers = {}, properties = {}, meta = {} } end Types.TileMap = TileMap local Subtitles = {} function Subtitles.new() return { kind = "subtitles", cues = {}, styles = {}, meta = {} } end Types.Subtitles = Subtitles -- the playlist-luau shape -- the categories, in the order F.formats() lists them; kind = the `kind` of the values they decode to -- what every format folder's init.luau returns (checked by tools/lint.sh CONTRACT; see docs/STYLE.md) 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", } ) return Types end __FILES["archive/7z"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict -- 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 }, } -- ------------------------------------------------------------------------------------------------ constants local MAGIC = "7z\188\175\39\28" -- method id -> xz filter id (BCJ / delta) local FILTERS= { ["\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= { ["\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) 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) return r:peek(6) == MAGIC and 1 or 0 end -- ------------------------------------------------------------------------------------------------ decode -- folder decoding: evaluate the coder graph from the main out stream; every coder here has one in and one out stream local function packStart(ctx, s, index) local p = ctx.base + 32 + s.packPos for i = 1, index do p =p+ s.packSizes[i] end return p end local function decodeFolder(ctx, s, f) local inBase, outBase = {}, {} local ni, no = 0, 0 for i, c in __iter(f.coders) do inBase[i], outBase[i] = ni, no ni =ni+ c.numIn no =no+ c.numOut end local depth = 0 local function out(outIdx) depth =depth+ 1 if depth > 32 then return nil, Err.new(Err.CORRUPT, "coder graph too deep") end local ci for i, c in __iter(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, so, sl local bound = nil for _, bp in __iter(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 = 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, (b and{nil }or{e })[1] elseif id == "\33" then local b, e = Lzma.lzma2(src, so, sl, nil, size, opts) return b, (b and{nil }or{e })[1] elseif id == "\4\1\8" then local b, e = Deflate.inflate(src, so, sl, size) return b, (b and{nil }or{e })[1] 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) local names = {} for _, c in __iter(f.coders) do table.insert(names, methodName(c.id)) end return table.concat(names, "+") end function SevenZip.decode(r, opts) local o= opts or {} local maxBytes = (type(o.maxBytes) == "number" and{o.maxBytes }or{(2 ^ 30 )})[1] 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= { 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= parsed.streams or { packPos = 0, packSizes = {}, folders = {}, subSizes = {}, subCrcs = {} } a.meta.folders = #s.folders a.meta.solid = false local cache= {} local subFolder, subOffset= {}, {} do local si = 1 for fi, f in __iter(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 =off+ (s.subSizes[si] or 0 ) si =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) 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 __iter(parsed.files) do local __DARKLUA_CONTINUE_10=false repeat if file.anti then __DARKLUA_CONTINUE_10=true break 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 = (attr and bit32.band(attr, 0x8000) ~= 0 and{(bit32.rshift(attr, 16) )}or{nil })[1] local e= { name = file.name, size = 0, dir = isDir, mtime = file.mtime, attributes = attr, mode = mode, } if not file.emptyStream then si =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 =pk+ (s.packSizes[s.folders[fi].firstPack + k] or 0 ) end e.compressedSize = pk end e.crc = s.subCrcs[idx] e.load = function() 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) __DARKLUA_CONTINUE_10=true until true if not __DARKLUA_CONTINUE_10 then break end end return a, nil end return SevenZip end __FILES["archive/7z/Header"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict -- 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 = {} 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, msg, code) error(setmetatable({ err = Err.new(code or Err.CORRUPT, msg, r.pos) }, Fail), 0) end local function check(r) if r.err then error(setmetatable({ err = r.err }, Fail), 0) end end local function byte(r) 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) 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 =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, min) 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, n) 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, n) if byte(r) ~= 0 then return table.create(n, true) end return bits(r, n) end local function digests(r, n) 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, s) 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) local ncoders = count(r) if ncoders == 0 or ncoders > 64 then bad(r, "bad coder count " .. ncoders) end local f= { 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 =totalIn+ nin totalOut =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 __iter(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) local total = 0 for _, c in __iter(f.coders) do total =total+ c.numOut end for o = 0, total - 1 do local bound = false for _, bp in __iter(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) local m = Header.mainOut(f) return (m and{f.unpackSizes[m + 1] or 0 }or{0 })[1]end local function unpackInfo(r, s) 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 __iter(s.folders) do local total = 0 for _, c in __iter(f.coders) do total =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, s) local t = byte(r) if t == K.NumUnPackStream then for _, f in __iter(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 __iter(s.folders) do if f.numSub > 0 then local sum = 0 for _ = 1, f.numSub - 1 do local v = number(r) sum =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 __iter(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 __iter(s.folders) do if not (f.numSub == 1 and f.crc) then unknown =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 __iter(s.folders) do if f.numSub == 1 and f.crc then s.subCrcs[si] = f.crc si =si+ 1 else for _ = 1, f.numSub do s.subCrcs[si] = d[k] k =k+ 1 si =si+ 1 end end end else bad(r, "unexpected property " .. t .. " in substreams info") end t = byte(r) end end local function streamsInfo(r) local s= { 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 __iter(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 __iter(s.folders) do f.firstPack = p 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, o, n) return Text.utf16(b, o, n, false) end local function filesInfo(r) local n = count(r, 0) if n > 1000000 then bad(r, "too many files", Err.LIMIT) end local files= (table.create(n) ) for i = 1, n do files[i] = { name = "", emptyStream = false, emptyFile = false, anti = false } end local empties= {} 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 __iter(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 =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) local p= { 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, o, n) local r = Bytes.reader(b, o, n) local ok, res = pcall(function() 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 ) == Fail then return nil, (res ).err end error(res, 0) end return Header end __FILES["archive/adf"] = function() local __compat = __compat local buffer, bit32, utf8, type, __iter = __compat.buffer, __compat.bit32, __compat.utf8, __compat.type, __compat.__iter --!strict -- 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" } }, } -- ------------------------------------------------------------------------------------------------ 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) 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 (n == 901120 or n == 1802240 )and 0.95 or 0.6 end -- ------------------------------------------------------------------------------------------------ decode local function latin1(s) 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 u32(d, blk, off) 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, blk, off) local v = u32(d, blk, off) return (v >= 0x80000000 and((v - 0x100000000 ))or(v ))end local function bstr(d, blk, off, max) 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, blk) 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, blk, off) return (u32(d, blk, off) * 86400 + u32(d, blk, off + 4) * 60 + math.floor(u32(d, blk, off + 8) / 50)) + EPOCH end local function dataBlocks(d, hdr, maxBlocks) local out = {} local blk = hdr local seen= {} 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, hdr, ofs) 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 __iter(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 =o+ n else local n = math.min(BS, size - o) buffer.copy(out, o, d.b, d.base + db * BS, n) o =o+ n end end if o < size then return nil, "file data ends early" end return out, nil end function Adf.decode(r, opts) local o= 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= { b = r.buf, base = r.base, blocks = math.floor(n / BS )} local ofs = bit32.band(flags, 1) == 0 local root = math.floor((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 = ofs and"ofs" or"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= {} local links= {} local visited= { [root] = true } local function walk(dir, prefix) 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 =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= { 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() 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 __iter(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() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict -- 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" } }, } -- ------------------------------------------------------------------------------------------------ constants local SINGLE, DOUBLE = 0x00051600, 0x00051607 local Y2K = 946684800 -- 2000-01-01 in unix seconds -- ------------------------------------------------------------------------------------------------ sniff function AppleSingle.sniff(r) 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, o) return AppleSingle.encode(a, o) end local function i32(v) return (v >= 0x80000000 and((v - 0x100000000 ))or(v ))end function AppleSingle.decode(r, opts) local o= 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= { 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 =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 = (c == 0x80000000 and{nil }or{(i32(c) + Y2K )})[1] info.modified = (m == 0x80000000 and{nil }or{(i32(m) + Y2K )})[1] 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 = (type(o.name) == "string" and{(string.match(o.name, "([^/\\]+)$") )}or{nil })[1] info.name = (n and{(string.match(n, "^%._(.+)$") or n) }or{"data" })[1] 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 = magic == DOUBLE and"appledouble" or"applesingle", version = math.floor(ver / 0x10000 )} return a, nil end -- ------------------------------------------------------------------------------------------------ encode function AppleSingle.encode(value, opts) local o= 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) 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= { { 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((o.double and{DOUBLE }or{SINGLE})[1]) w:u32be(0x20000) w:string(string.rep("\0", 16)) w:u16be(#entries) local off = 26 + 12 * #entries for _, e in __iter(entries) do w:u32be(e[1]) w:u32be(off) w:u32be(buffer.len(e[2])) off =off+ buffer.len(e[2]) end for _, e in __iter(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() local a = Archive.new("applesingle", encoder) a.meta.source = { format = "applesingle" } return a end return AppleSingle end __FILES["archive/ar"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict -- archive/ar: Unix ar ("!\n"; ar(5), deb(5); no code ported): System V / GNU ("//" names, "/" and "/SYM64/" -- symbols) and BSD ("#1/", "__.SYMDEF"); .deb payload and control fields. Supports: read, write gnu / bsd. -- Not supported: thin archives ("!"), 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 }, } -- ------------------------------------------------------------------------------------------------ constants local MAGIC = "!\n" local HEADER = 60 -- ------------------------------------------------------------------------------------------------ sniff function Ar.sniff(r) if r:peek(8) == MAGIC then return r:peek(13, 68) == "debian-binary" and 1 or 0.9 end return r:peek(8) == "!\n" and 0.5 or 0 end -- ------------------------------------------------------------------------------------------------ decode local function lazy(b, at, n) return function() local out = buffer.create(n) buffer.copy(out, 0, b, at, n) return out, nil end end local function decimal(s) local d = string.match(s, "^%s*(%d+)%s*$") return (d and{(tonumber(d) )}or{(string.find(s, "^%s*$") and 0 or nil) })[1]end -- the System V symbol table: a big-endian count, the member offsets, then the NUL-terminated names local function sysvSymbols(b, o, n, wide) local out = {} local w = wide and 8 or 4 if n < w then return out end local count = (wide and{(bit32.byteswap(buffer.readu32(b, o + 4)) )}or{(bit32.byteswap(buffer.readu32(b, o)) )})[1] 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 =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, o, n) 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, math.floor(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 =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) local out= {} local last= nil for line in __iter(string.gmatch(s, "([^\n]*)\n?")) do local c = string.sub(line, 1, 1) if (c == " " or c == "\t") and last then out[last]=out[last].. "\n" .. string.sub(line, 2) else local k, v = string.match(line, "^([^:%s]+):%s*(.-)%s*$") if k then out[k], last = v , k end end end return out end local function debControl(b, o, n, name, maxBytes) local ext = string.match(name, "^control%.tar%.?(%w*)$") local raw local opts= { maxBytes = maxBytes } if ext == "" then raw = buffer.create(n) buffer.copy(raw , 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 __iter(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, opts) return Ar.encode(archive, opts) end function Ar.decode(r, opts) local o= opts or {} local maxEntries = o.maxEntries or 1e6 local b, base, e = r.buf, r.base, r.limit if r:peek(8) == "!\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= nil local symbols= nil local offsets= {} local count = 0 local p = base + 8 while p < e do local __DARKLUA_CONTINUE_7=false repeat 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 = modeS == "" and 0 or(tonumber(modeS, 8) ) 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 =data+ n dataSize =dataSize- n variant = "bsd" elseif name == "//" then longNames = buffer.readstring(b, data, size) p = nextP __DARKLUA_CONTINUE_7=true break elseif name == "/" or name == "/SYM64/" then symbols = sysvSymbols(b, data, size, name == "/SYM64/") p = nextP __DARKLUA_CONTINUE_7=true break elseif string.match(name, "^/%d+$") then local off = (tonumber(string.sub(name, 2)) ) 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) ) 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 __DARKLUA_CONTINUE_7=true break end if name == "" then return nil, Err.new(Err.CORRUPT, "empty member name", p) end offsets[p - base] = name count =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 = (dataSize > 0 and{(lazy(b, data, dataSize) )}or{nil})[1], }) p = nextP __DARKLUA_CONTINUE_7=true until true if not __DARKLUA_CONTINUE_7 then break end end if symbols then local out = {} for _, s in __iter(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 = (v and{(string.match(buffer.tostring(v), "^%s*(.-)%s*$")) }or{nil })[1] for _, ent in __iter(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, n) return s .. string.rep(" ", n - #s) end local function header(name, e, size) local mtime = math.floor((type(e.mtime) == "number" and{e.mtime }or{0})[1]) local uid = (type(e.uid) == "number" and{e.uid }or{0 })[1] local gid = (type(e.gid) == "number" and{e.gid }or{0 })[1] local mode= (type(e.armode) == "string" and string.find(e.armode, "^[0-7]+$") and{e.armode }or{(string.format("%o", (type(e.mode) == "number" and{(bit32.band(e.mode, 0xFFF) )}or{0x1A4})[1]) )})[1] local f= { tostring(mtime), tostring(uid), tostring(gid), mode, tostring(size) } local w = { 12, 6, 6, 8, 10 } for i, s in __iter(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, opts) local items = Archive.entries(archive) if not items then return nil, Err.new(Err.ARG, "expected an Archive") end local o= opts or {} local src = type(archive.meta) == "table" and type(archive.meta.source) == "table" and archive.meta.source local variant = o.variant or (src and src.format == "ar" and (src.variant == "bsd" or src.variant == "deb") and"bsd" or"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 __iter(items) do local e= 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_= {} local nameOf= {} local tsize = 0 for i, f in __iter(files) do local name= 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 =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 =t.. "\n" end w:string(pad("//", 48) .. pad(tostring(#t), 10) .. "`\n" .. t) end for i, f in __iter(files) do local name= 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() local a = Archive.new("ar", encode) a.meta.source = { format = "ar", variant = "gnu" } return a end return Ar end __FILES["archive/arj"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict -- 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" } }, } -- ------------------------------------------------------------------------------------------------ constants local OS = { [0] = "msdos", "primos", "unix", "amiga", "macos", "os2", "appleiigs", "atarist", "next", "vaxvms", "win95", "win32" } -- ------------------------------------------------------------------------------------------------ sniff function Arj.sniff(r) 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 size > 0 and size <= 2600 and 0.9 or 0 end return 0 end -- ------------------------------------------------------------------------------------------------ decode -- 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, p) 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 =q+ 2 if n == 0 then break end q =q+ (n + 4 ) guard =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, opts) local o= 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 = (main.comment ~= "" and{main.comment }or{nil })[1] 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 =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 =name.. "/" end local e= { name = name, size = isDir and 0 or size, compressedSize = packed, method = method == 0 and"store" or"arj" .. method, mtime = Archive.fromDos(stamp), dir = isDir, mode = mode, os = OS[hostOs], comment = (h.comment ~= "" and{h.comment }or{nil})[1], 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() 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, derr 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 , 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() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict -- 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 }, } -- ------------------------------------------------------------------------------------------------ constants local ALPHABET = "!\"#$%&'()*+,-012345689@ABCDEFGHIJKLMNPQRSTUVXYZ[`abcdefhijklmpqr" local VALUE= {} 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) local head = r:peek(2048) local at = string.find(head, BANNER, 1, true) if not at then return 0 end return at == 1 and 1 or 0.8 end -- ------------------------------------------------------------------------------------------------ decode local function unhex(text, maxBytes) 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 =nbits+ 6 if nbits >= 8 then nbits =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 =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 =i+ 1 end end return out:finish(), nil end local function encoder(a, o) return Binhex.encode(a, o) end function Binhex.decode(r, opts) local o= 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 __iter({ 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, (k == 1 and"data" or"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, opts) local o= 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 __iter({ 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 =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 =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) table.insert(chars, string.sub(ALPHABET, v + 1, v + 1)) col =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 =nbits+ 8 while nbits >= 6 do nbits =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() local a = Archive.new("binhex", encoder) a.meta.source = { format = "binhex" } return a end return Binhex end __FILES["archive/br"] = function() local __compat = __compat local buffer = __compat.buffer --!strict -- 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 }, } -- ------------------------------------------------------------------------------------------------ constants local SNIFF_WHOLE = 262144 -- streams up to this size are decoded whole by sniff local SNIFF_PREFIX = 65536 -- ------------------------------------------------------------------------------------------------ sniff function Br.sniff(r) 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 buffer.len(out) > 0 and 0.3 or 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, opts) 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= 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() local __compat = __compat local buffer = __compat.buffer --!strict -- 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 }, } -- ------------------------------------------------------------------------------------------------ sniff function Bz2.sniff(r) 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, opts) 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() local __compat = __compat local buffer, bit32, utf8, type, __iter = __compat.buffer, __compat.bit32, __compat.utf8, __compat.type, __compat.__iter --!strict -- 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" } }, } -- ------------------------------------------------------------------------------------------------ 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) if r:peek(8) == "MSCF\0\0\0\0" then return 1 end return 0 end -- ------------------------------------------------------------------------------------------------ decode -- a block with cbUncomp 0 runs into the next cabinet local function blocks(r, f, dataReserve, verify, maxBytes) local list= {} 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 =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, list, total, typ) local method = bit32.band(typ, 15) local out = buffer.create(total) if method == 0 then local o = 0 for _, b in __iter(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 =o+ b.len end return out, nil elseif method == 1 then local spans= {} for _, b in __iter(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 __iter(list) do n =n+ b.len end local src = buffer.create(n) local o = 0 for _, b in __iter(list) do buffer.copy(src, o, buf, b.at, b.len) o =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, opts) return Cab.encode(archive, opts) end function Cab.decode(r, opts) local o= 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= 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= {} 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 = ((m == "lzx" or m == "quantum" )and{(bit32.band(bit32.rshift(typ, 8), 31) )}or{nil})[1], level = (m == "quantum" and{(bit32.band(bit32.rshift(typ, 4), 15) )}or{nil})[1], 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 , false local function folderData(f) 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= nil local 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 if size > maxBytes then return nil, Err.new(Err.LIMIT, name .. ": larger than maxBytes") end local e= { 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() if spanned then return nil, Err.new(Err.UNSUPPORTED, spanned ) 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, opts) local o= 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 __iter(files) do total =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 __iter(files) do buffer.copy(folder, p, f.data, 0, buffer.len(f.data)) p =p+ buffer.len(f.data) end local data = Bytes.writer(math.floor(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 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 =nblocks+ 1 s =s+ n end local blob = data:finish() local table_ = Bytes.writer(64 + #files * 32) local offset = 0 for _, f in __iter(files) do local e= f.entry local name = string.gsub(f.name, "/", "\\") local attribs = (type(e.attributes) == "number" and{(bit32.band(e.attributes, 0x7F) )}or{0x20 })[1] 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(math.floor(stamp / 65536)) table_:u16le(stamp % 65536) table_:u16le(attribs) table_:cstring(name) offset =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(compression == "mszip" and 1 or 0) w:bytes(fileTable) w:bytes(blob) return w:finish(), nil end -- ------------------------------------------------------------------------------------------------ extras function Cab.new() local a = Archive.new("cab", encode) a.meta.source = { format = "cab" } return a end return Cab end __FILES["archive/cab/Sum"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 -- 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 = {} function Sum.of(buf, off, len, seed) 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 =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 function Sum.block(buf, dataAt, cbData, cbUncomp) return bxor(Sum.of(buf, dataAt, cbData, 0), cbData + cbUncomp * 65536) end return Sum end __FILES["archive/cpio"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict -- 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" } }, } -- ------------------------------------------------------------------------------------------------ sniff function CpioFormat.sniff(r) 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, at, n) return function() local out = buffer.create(n) buffer.copy(out, 0, b, at, n) return out, nil end end local function encode(archive, opts) return CpioFormat.encode(archive, opts) end function CpioFormat.decode(r, opts) 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 __iter(list) do local data = e.type == "0" and e.size > 0 Archive.put(a, { name = e.name, size = (data and{e.size }or{0})[1], 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 = (data and{(lazy(r.buf, e.offset, e.size) )}or{nil})[1], }) end a.meta.source = { format = "cpio", variant = info.format } return a, nil end -- ------------------------------------------------------------------------------------------------ encode local function num(v) return (type(v) == "number" and{v }or{nil })[1]end function CpioFormat.encode(archive, opts) local items = Archive.entries(archive) if not items then return nil, Err.new(Err.ARG, "expected an Archive") end local index= {} for i, it in __iter(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= {} local target= {} for i, it in __iter(items) do local e= 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= {} for i, it in __iter(items) do local e= it.entry local typ = (type(e.type) == "string" and Cpio.TYPE_MODE[e.type] and{e.type }or{e.dir and"5" or"0" })[1] 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= nil if typ == "0" then local b, err = (items[src or i] ).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 = (type(e.link) == "string" and typ == "2" and{e.link }or{nil})[1], mode = (mode and{(bit32.band(mode, 0xFFF) )}or{nil})[1], 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= opts or {} local src = type(archive.meta) == "table" and type(archive.meta.source) == "table" and archive.meta.source local own = (src and src.format == "cpio" and (src.variant == "crc" or src.variant == "odc") and{src.variant }or{"newc" })[1] local variant = o.variant or (((o.format == "crc" or o.format == "odc" or o.format == "newc" )and{o.format }or{own})[1]) return Cpio.write(list, { format = variant, block = o.block }) end -- ------------------------------------------------------------------------------------------------ extras function CpioFormat.new() local a = Archive.new("cpio", encode) a.meta.source = { format = "cpio" } return a end return CpioFormat end __FILES["archive/d64"] = function() local __compat = __compat local buffer, bit32, utf8, type, __iter = __compat.buffer, __compat.bit32, __compat.utf8, __compat.type, __compat.__iter --!strict -- 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" } }, } -- ------------------------------------------------------------------------------------------------ constants local TYPES = { [0] = "del", "seq", "prg", "usr", "rel", "cbm", "dir" } local TYPE_CODE= { del = 0, seq = 1, prg = 2, usr = 3, rel = 4 } local function geometry(kind, tracks) local offsets, spt = {}, {} local o = 0 for t = 1, tracks do local n if kind == "d81" then n = 40 else local s = (kind == "d71" and t > 35 and((t - 35 ))or(t )) n = s <= 17 and 21 or(s <= 24 and 19 or(s <= 30 and 18 or 17 )) end offsets[t], spt[t] = o, n o =o+ n * 256 end return { kind = kind, tracks = tracks, offsets = offsets, spt = spt, dirTrack = kind == "d81" and 40 or 18, total = o } end -- image sizes -> geometry (sizes with the error-info block appended too) local function detect(len) for _, g in __iter({ { "d64", 35 }, { "d64", 40 }, { "d64", 42 }, { "d71", 70 }, { "d81", 80 } }) do local geo = geometry(g[1] , g[2] ) local sectors = math.floor(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) 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 t == 40 and s == 3 and v == 0x44 and 0.9 or 0.3 end return t == 18 and s == 1 and (v == 0x41 or v == 0) and 0.9 or 0.3 end -- ------------------------------------------------------------------------------------------------ decode local function petscii(raw) 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) local out = {} if not utf8.len(name) then return string.sub(name, 1, 16) end for _, c in __iter(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, o) return D64.encode(a, o) end local function chain(b, base, geo, t, s) local w = Bytes.writer() local seen= {} 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, opts) local o= 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 = geo.kind == "d81" and 0x04 or 0x90, geo.kind == "d81" and 0x16 or 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= {} 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 =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 =n+ 1 end local ty = TYPES[kind] or "?" local entry= { 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, img, t) local dir = geo.offsets[geo.dirTrack] if geo.kind == "d81" then local side = t <= 40 and 1 or 2 local tt = (t <= 40 and{t }or{(t - 40 )})[1] 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, img, t, s, free) 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, opts) local o= opts or {} local variant = o.variant or ((type(value) == "table" and type(value.meta) == "table" and value.meta.variant and{value.meta.variant }or{"d64"})[1]) 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, variant == "d64" and 35 or(variant == "d71" and 70 or 80)) local img = buffer.create(geo.total) local dirT = geo.dirTrack local dir = geo.offsets[dirT] local diskName = toPetscii(o.disk or ((type(value) == "table" and type(value.meta) == "table" and type(value.meta.disk) == "string" and{value.meta.disk }or{"rosetta"})[1])) local id = toPetscii(o.id or "fl") local function pad16(s) 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, side == 1 and"\40\2\68\187" or"\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" .. (variant == "d71" and"\128" or"\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 __iter(used) do setFree(geo, img, math.floor(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 __iter({ 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() 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 =ti+ 1 lastS = -10 end return nil, nil end local dirSector, slot = firstDir, 0 local dirSectors = { firstDir } for _, f in __iter(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, (k == blocks - 1 and((len + 1 ))or(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= (type(f.entry.type) == "string" and TYPE_CODE[f.entry.type] and{TYPE_CODE[f.entry.type] }or{2 })[1] buffer.writeu8(img, e + 2, 0x80 + ty) buffer.writeu8(img, e + 3, first_t) buffer.writeu8(img, e + 4, first_s) local raw = (type(f.entry.rawName) == "string" and #f.entry.rawName == 16 and{(string.gsub(f.entry.rawName, "\160+$", "")) }or{(toPetscii(f.name) )})[1] buffer.writestring(img, e + 5, pad16(raw)) buffer.writeu16(img, e + 30, blocks) slot =slot+ 1 end buffer.writeu8(img, dir + dirSector * 256 + 1, 0xFF) return img, nil end -- ------------------------------------------------------------------------------------------------ extras function D64.new(variant) 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() local __compat = __compat local __iter = __compat.__iter --!strict -- 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" } }, } -- ------------------------------------------------------------------------------------------------ sniff function FatFormat.sniff(r) 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 v.partition and 0.6 or 0.8 end -- ------------------------------------------------------------------------------------------------ decode local function encoder(a, o) return FatFormat.encode(a, o) end function FatFormat.decode(r, opts) local o= 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 __iter(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 = ((e.dir or e.size == 0 )and{nil }or{function() local b, rerr = Fat.read(v , entry) if not b then return nil, Err.from(rerr) end return b, nil end})[1], }) 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, opts) local o= opts or {} local items = Archive.entries(value) if not items then return nil, Err.new(Err.ARG, "expected an Archive") end local files= {} for _, it in __iter(items) do local e= it.entry local data= 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, (string.match(tostring(err), "^limit") and{(Err.from(err) )}or{(Err.new(Err.ARG, tostring(err)) )})[1] end return img, nil end -- ------------------------------------------------------------------------------------------------ extras function FatFormat.new() local a = Archive.new("fat", encoder) a.meta.source = { format = "fat" } return a end return FatFormat end __FILES["archive/grp"] = function() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict -- 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 -- ------------------------------------------------------------------------------------------------ constants local MAGIC = "KenSilverman" -- ------------------------------------------------------------------------------------------------ sniff function Grp.sniff(r) return Sniff.magic(r, MAGIC) end -- ------------------------------------------------------------------------------------------------ decode local function encode(archive, opts) return Grp.encode(archive, opts) end function Grp.decode(r, opts) 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 =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, opts) local items, err = Archive.collect(archive) if not items then return nil, err end local files= {} for _, it in __iter(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 __iter(files) do w:string(f.name) w:fill(0, 12 - #f.name) w:u32le(buffer.len(f.data)) end for _, f in __iter(files) do w:bytes(f.data) end return w:finish(), nil end -- ------------------------------------------------------------------------------------------------ extras function Grp.new() local a = Archive.new("grp", encode) a.meta.source = { format = "grp" } return a end return Grp end __FILES["archive/gzip"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict -- 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 }, } -- ------------------------------------------------------------------------------------------------ sniff function Gzip.sniff(r) return r:peek(3) == "\31\139\8" and 1 or 0 end -- ------------------------------------------------------------------------------------------------ decode local function header(b, o, e) local h= {} 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 =q+ (2 + buffer.readu16(b, q) ) end for _, f in __iter({ { 8, "name" }, { 16, "comment" } }) do if bit32.band(flg, f[1]) ~= 0 then local s = q while q < e and buffer.readu8(b, q) ~= 0 do q =q+ 1 end if q < e then h[f[2] ] = buffer.readstring(b, s, q - s) end q =q+ 1 end end return h end function Gzip.decode(r, opts) 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, o) 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 = (h.mtime and h.mtime > 0 and{h.mtime }or{nil})[1], dir = false, data = out, }) return a, nil end -- ------------------------------------------------------------------------------------------------ encode function Gzip.encode(value, opts) local o= opts or {} local level = o.level == nil and 6 or 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 local name= o.name local mtime= 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= {} for _, it in __iter(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 __iter(items) do local e= 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 + ((name and((#name ))or(0)))) w:string("\31\139\8") w:u8(name and 8 or 0) w:u32le(math.floor(mtime)) w:u8(level >= 9 and 2 or(level <= 1 and 4 or 0)) w:u8(255) if name then local z = string.find(name, "\0", 1, true) w:cstring((z and{(string.sub(name, 1, z - 1) )}or{name})[1]) 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, name) local a = Archive.new("gzip", function(arc, o) 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() local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict -- 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" } }, } -- ------------------------------------------------------------------------------------------------ sniff function Iso.sniff(r) return r:peek(5, 16 * 2048 + 1) == "CD001" and 1 or 0 end -- ------------------------------------------------------------------------------------------------ decode function Iso.decode(r, opts) 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 __iter(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 = e.zisofs and"zisofs" or"store", load = data and function() return Iso9660.extract(b, e, limit) end or 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() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict -- 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" } }, } -- ------------------------------------------------------------------------------------------------ constants local METHODS= { ["-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) 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) if isHeader(r:peek(22)) then return 0.95 end return 0 end -- ------------------------------------------------------------------------------------------------ decode -- "." / ".." collapsed as lhasa does local function path(s) s = string.gsub(s, "[\\\255]", "/") local parts = {} for part in __iter(string.gmatch(s, "[^/]+")) do if part ~= "." and part ~= ".." then table.insert(parts, part) end end return table.concat(parts, "/") .. (string.sub(s, -1) == "/" and #parts > 0 and"/" or"") end local function extended(r, p, w, first, h, limit) local size = first local guard = 0 while size ~= 0 do guard =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 = (w == 2 and{(e:u16le() )}or{(e:u32le() )})[1] if e.err then return nil, "truncated extended header" end p =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, p) 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= { 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 = hr:u8() == 0x55 and"unix" or"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 =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, o) return Lha.encode(a, o) end function Lha.decode(r, opts) local o= 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 =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 = (h.dir and{(string.lower(h.dir) )}or{nil })[1] 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 =d.. "/" end name = d .. name end local link= 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 =name.. "/" end local e= { name = name, size = (isDir or link )and 0 or 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() local out, derr 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 , 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, opts) 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 __iter(items) do local e= 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(e.dir and"-lhd-" or"-lh0-") h:u32le(buffer.len(data)) h:u32le(buffer.len(data)) h:u32le((type(e.mtime) == "number" and e.mtime >= 0 and((math.floor(e.mtime) % 4294967296 ))or(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= { { 0x00, "\0\0" }, { 0x01, base } } if dirPart ~= "" then table.insert(exts, { 0x02, (string.gsub(dirPart , "/", "\255")) }) end if type(e.mode) == "number" then local m = bit32.band(e.mode, 0xFFF) + (e.dir and 0x4000 or 0x8000) table.insert(exts, { 0x50, string.char(m % 256, math.floor(m / 256)) }) end h:u16le(#exts[1][2] + 3) for i, x in __iter(exts) do h:u8(x[1]) h:string(x[2]) h:u16le((exts[i + 1] and((#exts[i + 1][2] + 3 ))or(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() local a = Archive.new("lha", encoder) a.meta.source = { format = "lha" } return a end return Lha end __FILES["archive/lz4"] = function() local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict -- 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 }, } -- ------------------------------------------------------------------------------------------------ constants local MAGIC = 0x184D2204 local LEGACY = 0x184C2102 local LEGACY_BLOCK = 8 * 1048576 local SIZES= { [4] = 65536, [5] = 262144, [6] = 1048576, [7] = 4194304 } -- ------------------------------------------------------------------------------------------------ sniff function Lz4Format.sniff(r) 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) return m >= 0x184D2A50 and m <= 0x184D2A5F end local function room(out, k) 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, p, e, out, verify) 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= 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 =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 =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 =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 + (blockSum and 4 or 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, (raw and{n }or{bmax})[1]) and not room(out, (raw and{n }or{(math.min(bmax, out.max - out.n))})[1]) 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 =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, (independent and{out.n }or{start})[1]) 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 =q+ (n + (blockSum and 4 or 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 =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, p, e, out) 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 =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 =q+ n end return q, nil end function Lz4Format.decompress(src, offset, length, opts) 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= { 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 =frames+ 1 elseif m == LEGACY then q, err = legacy(b, p, e, out) frames =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 end if frames == 0 then return nil, Err.new((n < 4 and{Err.TRUNCATED }or{Err.CORRUPT})[1], "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, opts) return Lz4Format.encode(value, opts) end function Lz4Format.decode(r, opts) local o= 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, opts) local b, o, n, aerr = Bytes.span("Lz4.compress", data, nil, nil) if not b then return nil, aerr end local op= opts or {} local bsize = op.blockSize or 4194304 local bd = nil for k, v in __iter(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 + math.floor(n / 200 )+ 64) w:u32le(MAGIC) local flg = 0x40 + 0x20 + (blockSum and 0x10 or 0) + (withSize and 0x08 or 0) + (contentSum and 0x04 or 0) w:u8(flg) w:u8(bd * 16) if withSize then w:u32le(n % 4294967296) w:u32le(math.floor(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 =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, opts) 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() local __compat = __compat local buffer, bit32, type = __compat.buffer, __compat.bit32, __compat.type --!strict -- 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" } }, } -- ------------------------------------------------------------------------------------------------ sniff local function version(b, o, len) if len < 128 then return nil end local u8 = function(i) 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) 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 buffer.readstring(b, o + 102, 4) == "mBIN" and"III" or"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 need <= len + 127 and"I" or nil end function MacBinary.sniff(r) 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 v == "III" and 0.95 or(v == "II" and 0.8 or(v == "I" and 0.3 or 0 ))end -- ------------------------------------------------------------------------------------------------ decode local function encoder(a, o) return MacBinary.encode(a, o) end local function pad(n) return math.ceil(n / 128) * 128 end function MacBinary.decode(r, opts) local o= 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((len < 128 and{Err.TRUNCATED }or{Err.CORRUPT})[1], "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= 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, opts) local o= 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 = (f.comment and{(MacFile.roman(f.comment) )}or{"" })[1] 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, v) 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() local a = Archive.new("macbinary", encoder) a.meta.source = { format = "macbinary" } return a end return MacBinary end __FILES["archive/mpq"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict -- 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 -- ------------------------------------------------------------------------------------------------ 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) 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, at, n, want) 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 =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 =p+ k o =o+ k else o = math.min(want, o + c + 3) end end return out, nil end local function decompress(b, at, n, want) if n < 1 then return nil, Err.new(Err.CORRUPT, "empty compressed sector") end local mask = buffer.readu8(b, at) local cur, cat, cn= 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 local copy = buffer.create(len) buffer.copy(copy, 0, b, cat, len) return copy, nil end return cur, nil end local function readFile(b, limit, blk, at, name, sectorSize, maxBytes) 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, sat, sn, want, k) 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 = math.floor((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 + (band(flags, FLAG_CRC) ~= 0 and 1 or 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, _opts) return nil, Err.new(Err.UNSUPPORTED, "MPQ archives are read-only") end local function findHeader(r) 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 =p+ 512 end return nil end function Mpq.decode(r, opts) local found = findHeader(r) if not found then return nil, Err.new((r:remaining() < 32 and{Err.TRUNCATED }or{Err.CORRUPT})[1], "no MPQ header", 0) end local h= 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= 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 = (hiBlockPos > 0 and((h + hiBlockPos ))or((-1 ))) if hiAt >= 0 and hiAt + blockCount * 2 > size then hiAt = -1 end local blocks= {} for i = 0, blockCount - 1 do local hi = (hiAt >= 0 and{(buffer.readu16(r.buf, r.base + hiAt + i * 2) )}or{0 })[1] 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) local h0, h1, h2 = Crypt.hash(name, 0), Crypt.hash(name, 1), Crypt.hash(name, 2) local start = (pow2 and{(band(h0, mask) )}or{(h0 % hashCount )})[1] 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) local f = blocks[bi].flags return band(f, FLAG_EXISTS) ~= 0 and band(f, FLAG_DELETE) == 0 end local function blockData(bi, name) local blk = blocks[bi] return readFile(r.buf, r.limit, blk, r.base + h + blk.offset, name, sectorSize, maxBytes) end local names= {} for _, internal in __iter({ "(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 __iter(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 __iter(opts.names) do if type(nm) == "string" then table.insert(names, nm) end end end local a = Archive.new("mpq", encode) local named= {} local function add(bi, name) 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 = band(blk.flags, FLAG_IMPLODE) ~= 0 and"implode" or(band(blk.flags, FLAG_COMPRESS) ~= 0 and"compress" or"store"), encrypted = band(blk.flags, FLAG_ENCRYPTED) ~= 0, flags = blk.flags, block = bi - 1, load = function() return blockData(bi, name) end, }) end for _, nm in __iter(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"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native -- 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 =i2+ 0x100 end end end -- name hash: ASCII upper case, '/' as '\' function Crypt.hash(name, kind) 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 =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 function Crypt.decrypt(buf, at, n, key) local s2 = 0xEEEEEEEE local k = key % TWO32 for i = 0, math.floor(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 function Crypt.baseName(name) return string.match(name, "([^\\/]*)$") or name end return Crypt end __FILES["archive/pak"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict -- 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 -- ------------------------------------------------------------------------------------------------ constants local VARIANTS = { quake = { magic = "PACK", nameLen = 56 }, sin = { magic = "SPAK", nameLen = 120 } } -- ------------------------------------------------------------------------------------------------ sniff function Pak.sniff(r) 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, opts) return Pak.encode(archive, opts) end function Pak.decode(r, opts) local magic = r:string(4) local dirOfs, dirLen = r:u32le(), r:u32le() if r.err then return nil, r.err end local variant = magic == "PACK" and"quake" or(magic == "SPAK" and"sin" or 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 = math.floor(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, opts) 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 ((type(src) == "table" and src.format == "pak" and{src.variant }or{nil})[1]) or "quake" local v = VARIANTS[variant] if not v then return nil, Err.new(Err.ARG, "unknown variant " .. tostring(variant)) end local files= {} for _, it in __iter(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= {} for i, f in __iter(files) do offsets[i] = w:tell() w:bytes(f.data) end local dirOfs = w:tell() for i, f in __iter(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) 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() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict -- 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" } }, } -- ------------------------------------------------------------------------------------------------ constants local LEAD_MAGIC = "\237\171\238\219" local HEADER_MAGIC = "\142\173\232\1" local RPMFILE_GHOST = 64 local NAMES= { [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) return r:peek(4) == LEAD_MAGIC and 1 or 0 end -- ------------------------------------------------------------------------------------------------ decode local function header(b, p, e) 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= {} 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 = (typ == 2 or typ == 1 )and 1 or(typ == 3 and 2 or(typ == 4 and 4 or(typ == 5 and 8 or 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] = (width == 1 and{(buffer.readu8(b, x) )}or{(width == 2 and{(bit32.bor(bit32.lshift(buffer.readu8(b, x), 8), buffer.readu8(b, x + 1)) )}or{(width == 4 and{(bit32.byteswap(buffer.readu32(b, x)) )}or{(bit32.byteswap(buffer.readu32(b, x)) * 4294967296 + bit32.byteswap(buffer.readu32(b, x + 4)) )})[1]})[1]})[1] 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 = typ == 6 and 1 or 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 =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] = (typ == 6 and{v[1] }or{v })[1] end end return tags, se end local function files(tags) local names= {} 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 __iter(bn) do local d = dn[(di[i] or 0) + 1] names[i] = ((type(d) == "string" and{d }or{""})[1]) .. 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 __iter(names) do table.insert(out, { name = n, size = sizes[i] or 0, mode = modes[i] or 0, mtime = mtimes[i] or 0, link = (links[i] and links[i] ~= "" and{links[i] }or{nil})[1], user = users[i], group = groups[i], flags = flags[i] or 0, }) end return out end local function strip(name) return (string.gsub(name, "^%.?/+", "")) end local function payload(b, p, e, compressor, o) local n = e - p local opts= { maxBytes = o.maxBytes or 2 ^ 30 } local raw, err local m = (n >= 6 and{(buffer.readstring(b, p, 6) )}or{"" })[1] 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 , 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 __iter(list) do by[strip(ent.name)] = ent end return { buf = raw, by = by }, nil end function Rpm.decode(r, opts) local o= 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]*") ) 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 + math.floor((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= { tags = tags, signature = sig, type = kind == 1 and"source" or"binary", lead = { major = major, minor = minor, name = leadName } } for tag, key in __iter(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= nil local cacheErr= nil local function entry(name) 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 __iter(list) do local __DARKLUA_CONTINUE_9=false repeat if bit32.band(f.flags, RPMFILE_GHOST) ~= 0 then __DARKLUA_CONTINUE_9=true break 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 = (data and{f.size }or{0})[1], dir = typ == "5", mtime = f.mtime, mode = bit32.band(f.mode, 0xFFF), type = typ, link = (typ == "2" and{f.link }or{nil})[1], uname = f.user, gname = f.group, method = (info.payloadCompressor and{info.payloadCompressor }or{"store"})[1], load = data and function() 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 or nil, }) __DARKLUA_CONTINUE_9=true until true if not __DARKLUA_CONTINUE_9 then break end end return a, nil end -- ------------------------------------------------------------------------------------------------ extras function Rpm.cpio(r, opts) 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 + math.floor((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() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict -- 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" } }, } -- ------------------------------------------------------------------------------------------------ sniff function TarFormat.sniff(r) if r:remaining() < 512 then return 0 end if not Tar.valid(r.buf, r.pos) then return 0 end return r:peek(5, 257) == "ustar" and 0.95 or 0.6 end -- ------------------------------------------------------------------------------------------------ decode local function lazy(b, at, n) return function() local out = buffer.create(n) buffer.copy(out, 0, b, at, n) return out, nil end end local function encode(archive, opts) return TarFormat.encode(archive, opts) end function TarFormat.decode(r, opts) 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 __iter(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 = ((e.dir or e.size == 0 )and{nil }or{(lazy(r.buf, e.offset, e.size))})[1], }) end a.meta.source = { format = "tar" } return a, nil end -- ------------------------------------------------------------------------------------------------ encode function TarFormat.encode(archive, opts) local items = Archive.entries(archive) if not items then return nil, Err.new(Err.ARG, "expected an Archive") end local list= {} for _, it in __iter(items) do local e= it.entry local data= 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 = (type(e.type) == "string" and #e.type == 1 and{e.type }or{nil})[1], link = (type(e.link) == "string" and{e.link }or{nil})[1], mode = (type(e.mode) == "number" and{e.mode }or{nil})[1], uid = (type(e.uid) == "number" and{e.uid }or{nil})[1], gid = (type(e.gid) == "number" and{e.gid }or{nil})[1], uname = (type(e.uname) == "string" and{e.uname }or{nil})[1], gname = (type(e.gname) == "string" and{e.gname }or{nil})[1], mtime = (type(e.mtime) == "number" and{e.mtime }or{nil})[1], }) end return Tar.write(list, opts) end -- ------------------------------------------------------------------------------------------------ extras function TarFormat.new() local a = Archive.new("tar", encode) a.meta.source = { format = "tar" } return a end return TarFormat end __FILES["archive/unitypackage"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict -- archive/unitypackage: Unity asset packages, a gzip'd tar of /asset, /asset.meta, /pathname -- (+ preview.png), read + write as an Archive keyed by the asset paths (Assets/...), each .meta next to its asset as -- in a Unity project. Supports: folders (meta only), lazy entries, guids kept (entry.guid) or made from the path. -- Not supported: pre-5.x packages without pathname files. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Md5 = __include("core/Md5") local Deflate = __include("codecs/compress/Deflate") local Archive = __include("containers/Archive") local Tar = __include("containers/Tar") -- ------------------------------------------------------------------------------------------------ contract local UnityPackage = { name = "unitypackage", category = "archive", extensions = { "unitypackage" }, mime = { "application/x-unitypackage" }, deps = { "core/Err", "core/Bytes", "core/Md5", "codecs/compress/Deflate", "containers/Archive", "containers/Tar" }, caps = { decode = true, encode = true }, } -- ------------------------------------------------------------------------------------------------ sniff local function guidOf(name) local n = string.gsub(name, "^%./", "") local guid, rest = string.match(n, "^(%x+)/?(.*)$") if guid and #guid == 32 then return string.lower(guid), rest end return nil, nil end function UnityPackage.sniff(r) if r:peek(3) ~= "\31\139\8" then return 0 end local head = Deflate.peek(r.buf, r.pos, r.limit - r.pos, 512) if not head or buffer.len(head) < 512 or not Tar.valid(head, 0) then return 0 end local z = 0 while z < 100 and buffer.readu8(head, z) ~= 0 do z =z+ 1 end return guidOf(buffer.readstring(head, 0, z)) and 1 or 0 -- ties with archive/gzip go to the extension end -- ------------------------------------------------------------------------------------------------ decode local function encode(archive, opts) return UnityPackage.encode(archive, opts) end local function text(b, e) return buffer.readstring(b, e.offset, e.size) end function UnityPackage.decode(r, opts) local o= opts or {} local tar, err = Deflate.gunzip(r.buf, r.base, r.limit - r.base) if not tar then return nil, err end if buffer.len(tar) > (o.maxBytes or 2 ^ 31) then return nil, Err.new(Err.LIMIT, "inflated size over the byte limit") end local list, terr = Tar.read(tar, 0, buffer.len(tar), { maxEntries = o.maxEntries }) if not list then return nil, terr end local byGuid= {} local order= {} for _, e in __iter(list) do local guid, rest = guidOf(e.name) if guid and not e.dir then local a = byGuid[guid] if not a then a = {} byGuid[guid] = a table.insert(order, guid) end if rest == "asset" then a.asset = e elseif rest == "asset.meta" then a.meta = e elseif rest == "pathname" then a.pathname = e elseif rest == "preview.png" then a.preview = e end end end local arc = Archive.new("unitypackage", encode) local skipped = 0 for _, guid in __iter(order) do local a = byGuid[guid] local pn = a.pathname if not pn then skipped =skipped+ 1 else -- the first line is the path (Unity 5+ may add a second line, e.g. "00") local path = string.match(text(tar, pn), "^[^\r\n]*") or "" path = string.gsub(path, "\\", "/") if path ~= "" then local asset, meta = a.asset, a.meta local isDir = asset == nil Archive.put(arc, { name = path, size = (asset and{asset.size }or{0})[1], dir = isDir, mtime = (asset and{asset.mtime }or{(meta and{meta.mtime }or{nil})[1]})[1], method = "deflate", guid = guid, load = (asset and asset.size > 0 and{(Archive.slice(tar, asset.offset, asset.size) )}or{nil})[1], preview = (a.preview and{(Archive.slice(tar, a.preview.offset, a.preview.size) )}or{nil})[1], }) if meta then Archive.put(arc, { name = path .. ".meta", size = meta.size, dir = false, mtime = meta.mtime, method = "deflate", guid = guid, load = (meta.size > 0 and{(Archive.slice(tar, meta.offset, meta.size) )}or{nil})[1], }) end end end end arc.meta.source = { format = "unitypackage", assets = #order - skipped, skipped = (skipped > 0 and{skipped }or{nil })[1]} return arc, nil end -- ------------------------------------------------------------------------------------------------ encode local function metaGuid(b) local s = buffer.readstring(b, 0, math.min(buffer.len(b), 4096)) local g = string.match(s, "\nguid:%s*(%x+)") or string.match(s, "^guid:%s*(%x+)") if g and #g == 32 then return string.lower(g) end return nil end local function defaultMeta(guid, dir) if dir then return "fileFormatVersion: 2\nguid: " .. guid .. "\nfolderAsset: yes\nDefaultImporter:\n externalObjects: {}\n userData: \n assetBundleName: \n assetBundleVariant: \n" end return "fileFormatVersion: 2\nguid: " .. guid .. "\nDefaultImporter:\n externalObjects: {}\n userData: \n assetBundleName: \n assetBundleVariant: \n" end function UnityPackage.encode(archive, opts) local o= opts or {} local items = Archive.entries(archive) if not items then return nil, Err.new(Err.ARG, "expected an Archive") end local byName= {} for _, it in __iter(items) do byName[string.gsub(it.entry.name, "\\", "/")] = it end local mtime = o.mtime or 0 local list= {} local used= {} for _, it in __iter(items) do local e= it.entry local path = string.gsub((string.gsub(e.name, "\\", "/")), "/+$", "") local metaIt = byName[path .. ".meta"] local isMeta = string.sub(path, -5) == ".meta" and byName[string.sub(path, 1, -6)] ~= nil if path ~= "" and not isMeta then local data= nil if not e.dir then local b, rerr = it.read() if not b then return nil, rerr end data = b end local metaData= nil if metaIt then local mb, merr = metaIt.read() if not mb then return nil, merr end metaData = mb end local given= (type(e.guid) == "string" and #e.guid == 32 and string.match(e.guid, "^%x+$") and{(string.lower(e.guid) )}or{nil })[1] local g= given or ((metaData and{(metaGuid(metaData) )}or{nil})[1]) or Md5.of(buffer.fromstring(path)) if used[g] then g = Md5.of(buffer.fromstring(path .. "\0" .. g)) end used[g] = true metaData = metaData or buffer.fromstring(defaultMeta(g, e.dir == true)) table.insert(list, { name = g .. "/", dir = true, mtime = mtime }) if data then table.insert(list, { name = g .. "/asset", data = data, mtime = mtime }) end table.insert(list, { name = g .. "/asset.meta", data = metaData, mtime = mtime }) table.insert(list, { name = g .. "/pathname", data = buffer.fromstring(path), mtime = mtime }) if type(e.preview) == "function" then local ok, pb = pcall(e.preview) if ok and type(pb) == "buffer" then table.insert(list, { name = g .. "/preview.png", data = pb, mtime = mtime }) end end end end local tar, terr = Tar.write(list, { format = "ustar" }) if not tar then return nil, terr end return Deflate.gzip(tar, { level = o.level or 6 }) end -- ------------------------------------------------------------------------------------------------ extras function UnityPackage.new() local a = Archive.new("unitypackage", encode) a.meta.source = { format = "unitypackage" } return a end return UnityPackage end __FILES["archive/uu"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict -- 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" } }, } -- ------------------------------------------------------------------------------------------------ constants local XX = "+-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" local XX_VALUE= {} for i = 1, 64 do XX_VALUE[string.byte(XX, i)] = i - 1 end -- ------------------------------------------------------------------------------------------------ sniff function Uu.sniff(r) 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, xx) 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, xx) 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, xx, maxBytes) local total = 0 for _, l in __iter(lines) do total =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 __iter(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 =o+ 1 left =left- 1 end end p =p+ 4 end end return out, nil end local function parse(text, maxBytes) local lines = string.split(text, "\n") local blocks= {} 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= {} local closed = false i =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 =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= {} for _, l in __iter(body) do if l ~= "" then table.insert(data_lines, l) end end local uuOk, xxOk = true, true for _, l in __iter(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, xx and"xx" or"uu" end table.insert(blocks, { name = name, mode = tonumber(mode, 8) or 0, variant = variant, data = data }) end i =i+ 1 end if #blocks == 0 then return nil, "no begin line" end return blocks, nil end local function encoder(a, o) return Uu.encode(a, o) end function Uu.decode(r, opts) local o= 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 __iter(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, xx, out) local n = buffer.len(data) local function ch(v) if xx then return string.sub(XX, v + 1, v + 1) end return v == 0 and"`" or 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 = (q + 1 < p + len and{(buffer.readu8(data, q + 1) )}or{0 })[1] local b2 = (q + 2 < p + len and{(buffer.readu8(data, q + 2) )}or{0 })[1] 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 =p+ len end table.insert(out, ch(0)) end function Uu.encode(value, opts) local o= 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= {} for _, f in __iter(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 = (type(f.entry.mode) == "number" and{f.entry.mode }or{(o.mode or 0x1A4) })[1] 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() local a = Archive.new("uu", encoder) a.meta.source = { format = "uu" } return a end return Uu end __FILES["archive/vpk"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict -- archive/vpk: Valve VPK v1 / v2 directory files (Valve Developer Community page; no code taken): preload bytes, -- embedded (index 0x7fff) or part-file data ("_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 -- ------------------------------------------------------------------------------------------------ constants local SIGNATURE = 0x55AA1234 local EMBEDDED = 0x7FFF -- ------------------------------------------------------------------------------------------------ sniff function Vpk.sniff(r) if r:remaining() < 12 or r:peek(4) ~= "\x34\x12\xAA\x55" then return 0 end local v = r:peekU8(4) return (v == 1 or v == 2 )and 1 or 0.5 end -- ------------------------------------------------------------------------------------------------ decode local function encode(archive, opts) return Vpk.encode(archive, opts) end local function partLoader(opts) local cache= {} 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) 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, e, dataBase, part, verify) return function() local src, at 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, opts) 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= 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= {} 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= { 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 =count+ 1 if count > maxEntries then return nil, Err.new(Err.LIMIT, "too many entries") end local full = (path == " " and"" or path .. "/") .. name .. (ext == " " and"" or"." .. 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 = (e.archiveIndex == EMBEDDED and{nil }or{e.archiveIndex})[1], preload = e.preloadLength, load = loader(r, e, dataBase, part, verify), }) end end end local partList= {} for k in __iter(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, opts) 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 ((type(src) == "table" and src.format == "vpk" and{src.version }or{nil})[1]) 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= {} local byExt= {} for _, it in __iter(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 , "^(.*)%.([^.]*)$") 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 ] if not g then g = { paths = {}, byPath = {} } byExt[ext ] = g table.insert(exts, ext ) end local l = g.byPath[dir ] if not l then l = {} g.byPath[dir ] = l table.insert(g.paths, dir ) end table.insert(l, { name = stem , data = it.data }) end end local tree = Bytes.writer() local data = Bytes.writer() for _, ext in __iter(exts) do tree:cstring(ext) local g = byExt[ext] for _, path in __iter(g.paths) do tree:cstring(path) for _, f in __iter(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) 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() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict -- 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: "/", repeats "~". 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 -- ------------------------------------------------------------------------------------------------ constants local MAP_LUMPS= { 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= { 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) 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, opts) return Wad.encode(archive, opts) end local function nameAt(b, at) local s = buffer.readstring(b, at, 8) local z = string.find(s, "\0", 1, true) return string.upper((z and{(string.sub(s, 1, z - 1) )}or{s})[1]) end function Wad.decode(r, opts) 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= {} local seen= {} local b = r.buf local ns= nil local map= 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 = (i + 1 < count and{(nameAt(b, o + 24) )}or{"" })[1] local inMap= 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= 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 = (#post > 1 and NAMESPACES[string.sub(post, 1, 1)] == ns and (string.match(post, "%d$")) and{ns }or{nil })[1] marker = true end local entry = (inMap and((inMap .. "/" .. name ))or(name )) local k = seen[entry] if k then k =k+ 1 seen[entry] = k entry = entry .. "~" .. k else seen[entry] = 1 end local lump= { name = name, entry = entry, index = i + 1, offset = at, size = n, namespace = (marker and{nil }or{ns})[1], 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, opts) 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 ((type(src) == "table" and src.format == "wad" and{src.type }or{nil})[1]) or "PWAD" if kind ~= "IWAD" and kind ~= "PWAD" then return nil, Err.new(Err.ARG, "type must be IWAD or PWAD") end local list= {} for _, it in __iter(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= {} for i, l in __iter(list) do offs[i] = w:tell() w:bytes(l.data) end local dirOfs = w:tell() for i, l in __iter(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) 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, name, ns) local up = string.upper(name) local best= nil for _, l in __iter(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 __iter(w.lumps) do if l.name == up and l.namespace == ns then best = l end end end return best end function Wad.new(kind) local a = Archive.new("wad", encode) a.meta.source = { format = "wad", type = kind or "PWAD" } return a end function Wad.lumps(a) local w = info(a) return w and w.lumps end function Wad.palette(a, index) 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, name, opts) 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, kind == "flat" and"flats" or 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) if w.textures then return w.textures end local defs= {} w.textures = defs local pn = find(w, "PNAMES") local names= {} if pn and pn.size >= 4 then local at = w.base + pn.offset local n = math.min(buffer.readi32(w.buf, at), math.floor((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 __iter({ "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, name, opts) 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 __iter(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) local w = info(a) local out= {} if w then local seen= {} for _, l in __iter(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, name) 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= {} for _, l in __iter(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, name, opts) 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= {} local pal = opts and opts.palette local function image(kind, tname) local key = kind .. ":" .. tname local c = cache[key] if c == nil then local img = (kind == "flat" and{(Wad.image(a, tname, { kind = "flat", palette = pal }) )}or{(Wad.texture(a, tname, { palette = pal }) )})[1] c = img or false cache[key] = c end return (c and{c }or{nil })[1] end local tex= { size = function(kind, tname) 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 = (images and{image }or{nil})[1], } 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 = math.floor(#m.vertices / 2 )} return scene, nil end return Wad end __FILES["archive/wad/Map"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict -- 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 -- ------------------------------------------------------------------------------------------------ parse local function name8(b, at) local s = buffer.readstring(b, at, 8) local z = string.find(s, "\0", 1, true) return string.upper((z and{(string.sub(s, 1, z - 1) )}or{s})[1]) end local function side(v) return (v == 0xFFFF and{nil }or{(v + 1 )})[1]end function Map.parse(lumps, hexen) for _, k in __iter({ "LINEDEFS", "SIDEDEFS", "VERTEXES", "SECTORS" }) do if not lumps[k] then return nil, "map has no " .. k end end local m= { format = hexen and"hexen" or"doom", things = {}, linedefs = {}, sidedefs = {}, vertices = {}, sectors = {} } local v = lumps.VERTEXES for i = 0, math.floor(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, math.floor(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, math.floor(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 = hexen and 16 or 14 for i = 0, math.floor(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 = hexen and 20 or 10 for i = 0, math.floor(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) local edges= {} local nv = math.floor(#m.vertices / 2 ) local function add(sec, a, b) local e = edges[sec] or {} edges[sec] = e table.insert(e, { a, b }) end for _, ld in __iter(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= {} for sec, list in __iter(edges) do local from= {} for i, e in __iter(list) do local l = from[e[1] ] or {} from[e[1] ] = l table.insert(l, i) end local used= {} local res= {} 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 , 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 __iter(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, loop, x, y) 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 local LOWER_UNPEGGED, UPPER_UNPEGGED, TWO_SIDED = 16, 8, 4 function Map.scene(m, tex, name) local batches= {} local order= {} local function batch(kind, tname) 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, x, y, z, nx, ny, nz, u, v) 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 = math.floor(#V / 2 ) local secLoops = loops(m) for sec, ls in __iter(secLoops) do local s = m.sectors[sec] local flat= {} for li, loop in __iter(ls) do local f= {} for _, vi in __iter(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 = (pass == 1 and{s.floorFlat }or{s.ceilingFlat })[1] local fw, fh = tex.size("flat", tname) local w, h = fw or 64, fh or 64 local z = (pass == 1 and{s.floor }or{s.ceiling })[1] local b = batch("flat", tname) local nz = pass == 1 and 1 or-1 for k = 1, #tris, 6 do for c = 0, 2 do local cc = (pass == 1 and{c }or{(2 - c )})[1] 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, x1, y1, x2, y2, zb, zt, xoff, len, texTop, yoff) 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 __iter(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 = (sideN == 1 and{ld.front }or{ld.back })[1] local odi = (sideN == 1 and{ld.back }or{ld.front })[1] 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 = (bit32.band(ld.flags, LOWER_UNPEGGED) ~= 0 and((me.floor + th ))or(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 = (bit32.band(ld.flags, LOWER_UNPEGGED) ~= 0 and{me.ceiling }or{other.floor })[1] 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 = (bit32.band(ld.flags, UPPER_UNPEGGED) ~= 0 and{me.ceiling }or{(other.ceiling + th )})[1] 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 = (bit32.band(ld.flags, LOWER_UNPEGGED) ~= 0 and((lo + th ))or(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= { name = name, primitives = {} } local texIndex= {} for _, key in __iter(order) do local b = batches[key] local n = math.floor(#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 = (tex.image and{(tex.image(b.kind, b.name) )}or{nil})[1], 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" , 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 __iter(m.things) do local z = th.z or 0 for sec, ls in __iter(secLoops) do local inside = false for _, loop in __iter(ls) do if insideLoop(V, loop, th.x, th.y) then inside = not inside end end if inside then z =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"] = function() local __compat = __compat local buffer = __compat.buffer --!strict --!native -- 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 = {} function Picture.header(b, at, n) 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 function Picture.decode(b, at, n, pal, out, w, h) 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 = (delta <= top and((top + delta ))or(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 =p+ (4 + len ) end end return true, nil end function Picture.flatSize(n) 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, math.floor(n / 64 ) end return nil, 0 end function Picture.flat(b, at, w, h, pal, out) for i = 0, w * h - 1 do writeu32(out, i * 4, readu32(pal, readu8(b, at + i) * 4)) end end function Picture.blit(src, sw, sh, dst, dw, dh, ox, oy) 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/wad2"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict -- archive/wad2: Quake WAD2 and Half-Life WAD3 texture / graphics WADs (wad.h of the Quake source, the GoldSrc WAD3 -- layout; no code taken), read and write. Lumps by name (repeats "~"); Wad2.image decodes miptex, qpic, -- conchars, palette and GoldSrc font lumps through codecs/image/Miptex (Quake 1 needs a palette: the WAD's own -- "palette" lump, opts.palette or gfx/palette.lmp through files / resolve; else grey). Not supported: compressed lumps. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Input = __include("core/Input") local Types = __include("Types") local Archive = __include("containers/Archive") local Pixels = __include("codecs/image/Pixels") local Miptex = __include("codecs/image/Miptex") -- ------------------------------------------------------------------------------------------------ contract local Wad2 = { name = "wad2", category = "archive", extensions = { "wad" }, mime = { "application/x-quake-wad" }, deps = { "core/Err", "core/Bytes", "core/Input", "Types", "containers/Archive", "codecs/image/Pixels", "codecs/image/Miptex" }, caps = { decode = true, encode = true, images = true, variants = { "wad2", "wad3" } }, } -- ------------------------------------------------------------------------------------------------ types -- ------------------------------------------------------------------------------------------------ constants local T = Miptex.TYPES -- ------------------------------------------------------------------------------------------------ sniff function Wad2.sniff(r) if r:remaining() < 12 then return 0 end local m = r:peek(4) return (m == "WAD2" or m == "WAD3" )and 0.9 or 0 end -- ------------------------------------------------------------------------------------------------ decode local function encode(archive, opts) return Wad2.encode(archive, opts) end function Wad2.decode(r, opts) local size = r.limit - r.base local lumps, msg, magic = Miptex.wad(r.buf, r.base, size, opts and opts.maxEntries) if not lumps then return nil, Err.from(msg, 0) end local a = Archive.new("wad2", encode) local seen= {} for _, l in __iter(lumps) do if l.compression ~= 0 then return nil, Err.new(Err.UNSUPPORTED, "compressed lump " .. l.name) end local entry = l.name local k = seen[string.lower(entry)] if k then seen[string.lower(entry)] = k + 1 entry = entry .. "~" .. (k + 1) else seen[string.lower(entry)] = 1 end Archive.put(a, { name = entry, size = l.disksize, dir = false, method = "store", type = l.type, lump = l.name, load = Archive.slice(r.buf, r.base + l.offset, l.disksize) }) end a.meta.source = { format = "wad2", variant = string.lower(magic ), lumps = #lumps } a.meta.wad2 = { buf = r.buf, base = r.base, lumps = lumps, goldsrc = magic == "WAD3" } return a, nil end -- ------------------------------------------------------------------------------------------------ encode local function guessType(name, data, goldsrc) local n = buffer.len(data) if string.lower(name) == "palette" and n == 768 then return T.palette end if n >= 40 then local w, h = buffer.readu32(data, 16), buffer.readu32(data, 20) if w > 0 and h > 0 and w < 65536 and h < 65536 and buffer.readu32(data, 24) == 40 then return goldsrc and 0x43 or T.miptex end end if n >= 8 then local w, h = buffer.readu32(data, 0), buffer.readu32(data, 4) if w > 0 and h > 0 and 8 + w * h <= n then return T.qpic end end return T.miptex end function Wad2.encode(archive, opts) 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 ((type(src) == "table" and src.format == "wad2" and{src.variant }or{nil})[1]) if not variant then variant = "wad2" for _, it in __iter(items) do if (it.entry ).type == 0x43 then variant = "wad3" end end end if variant ~= "wad2" and variant ~= "wad3" then return nil, Err.new(Err.ARG, "variant must be wad2 or wad3") end local list= {} for _, it in __iter(items) do if not it.entry.dir then local e= it.entry local name = e.lump or string.gsub(string.match(e.name, "([^/\\]*)$") or e.name, "~%d+$", "") if #name == 0 or #name > 15 then return nil, Err.new(Err.ARG, "lump name must be 1..15 bytes: " .. e.name) end local typ = (type(e.type) == "number" and{e.type }or{(guessType(name, it.data, variant == "wad3") )})[1] table.insert(list, { name = name, data = it.data, type = typ }) end end local w = Bytes.writer() w:string(variant == "wad3" and"WAD3" or"WAD2") w:u32le(#list) w:u32le(0) local offs= {} for i, l in __iter(list) do offs[i] = w:tell() w:bytes(l.data) w:fill(0, (4 - buffer.len(l.data) % 4) % 4) end local dir = w:tell() for i, l in __iter(list) do w:u32le(offs[i]) w:u32le(buffer.len(l.data)) w:u32le(buffer.len(l.data)) w:u8(l.type) w:u8(0) w:u16le(0) w:string(l.name) w:fill(0, 16 - #l.name) end w:setU32le(8, dir) return w:finish(), nil end -- ------------------------------------------------------------------------------------------------ extras local function info(a) return type(a) == "table" and type(a.meta) == "table" and a.meta.wad2 or nil end function Wad2.new(variant) local a = Archive.new("wad2", encode) a.meta.source = { format = "wad2", variant = variant or "wad2" } return a end function Wad2.lumps(a) local w = info(a) return w and w.lumps end -- the WAD's own "palette" lump (gfx.wad) as a 1024-byte rgba8 palette function Wad2.palette(a) local w = info(a) local l = w and Miptex.find(w.lumps, "palette") if l and l.disksize >= 768 then return Pixels.palette(w.buf, w.base + l.offset, 256) end return nil end function Wad2.image(a, name, opts) local w = info(a) if not w then return nil, Err.new(Err.ARG, "expected a decoded WAD2 / WAD3 archive") end local l = Miptex.find(w.lumps, tostring(name)) if not l then return nil, Err.new(Err.ARG, "no lump named " .. tostring(name)) end local b, at, size = w.buf, w.base + l.offset, l.disksize local pal= nil if not w.goldsrc then local raw = (opts and opts.palette and{(Bytes.toBuffer(opts.palette) )}or{nil })[1] if raw and buffer.len(raw) >= 768 then pal = Pixels.palette(raw, 0, 256) else pal = Wad2.palette(a) if not pal then local lmp = Input.sibling(opts, "gfx/palette.lmp") pal = (lmp and buffer.len(lmp) >= 768 and{(Pixels.palette(lmp, 0, 256) )}or{nil })[1] end end end local keyed= (opts and{opts.keyed }or{nil })[1] local img, msg local kind if l.type == T.palette and size >= 768 then kind = "palette" local out = Types.Image.new(16, 16) buffer.copy(out.pixels, 0, Pixels.palette(b, at, 256), 0, 1024) img = out elseif string.lower(l.name) == "conchars" and size == 128 * 128 then -- gfx.wad's console font: raw 128 x 128 pixels, no header, index 0 transparent kind = "conchars" local out = Types.Image.new(128, 128) Pixels.indexed(b, at, 128, 8, out.pixels, 128, 128, true, Pixels.keyed(pal or Pixels.grey(), keyed == false and-1 or 0)) img = out elseif l.type == T.qpic then kind = "qpic" img, msg = Miptex.qpic(b, at, size, { palette = pal, goldsrc = w.goldsrc, keyed = keyed } ) elseif l.type == T.font and w.goldsrc and size >= 16 + 1024 then -- GoldSrc qfont_t: width (256), height, rowcount, rowheight, charinfo[256] (u16 offset, u16 width), pixels, palette kind = "font" local fw, fh = buffer.readu32(b, at), buffer.readu32(b, at + 4) local p = 16 + 1024 + fw * fh if fw == 0 or fh == 0 or fw * fh > 2 ^ 24 or p + 2 > size then return nil, Err.new(Err.CORRUPT, "bad font lump " .. l.name, l.offset) end local n = buffer.readu16(b, at + p) local fpal = (n > 0 and n <= 256 and p + 2 + n * 3 <= size and{(Pixels.palette(b, at + p + 2, n) )}or{(Pixels.grey() )})[1] local out = Types.Image.new(fw, fh) Pixels.indexed(b, at + 16 + 1024, fw, 8, out.pixels, fw, fh, true, (keyed == false and{fpal }or{(Pixels.keyed(fpal, 255))})[1]) local glyphs = {} for c = 0, 255 do glyphs[c + 1] = { offset = buffer.readu16(b, at + 16 + c * 4), width = buffer.readu16(b, at + 18 + c * 4) } end out.meta.font = { rows = buffer.readu32(b, at + 8), rowHeight = buffer.readu32(b, at + 12), glyphs = glyphs } img = out else kind = "miptex" img, msg = Miptex.decode(b, at, size, { palette = pal, goldsrc = w.goldsrc, mip = (opts and{opts.mip }or{nil})[1], keyed = keyed } ) end if not img then return nil, Err.from(msg, l.offset) end img.meta.source = { format = "wad2", kind = kind, lump = l.name, type = l.type, palette = w.goldsrc or pal ~= nil } return img, nil end -- adds an rgba8 image as a miptex (sizes multiples of 16) or qpic lump; WAD3 lumps carry their own palette function Wad2.addImage(a, name, img, opts) if type(img) ~= "table" or img.format ~= "rgba8" then return false, Err.new(Err.ARG, "expected an rgba8 Image") end local src = type(a) == "table" and type(a.meta) == "table" and a.meta.source local goldsrc = type(src) == "table" and src.variant == "wad3" local raw = opts and opts.palette and Bytes.toBuffer(opts.palette) local pal = (raw and buffer.len(raw) >= 768 and{(Pixels.palette(raw, 0, 256) )}or{nil })[1] local kind = opts and opts.kind or "miptex" local data, msg if kind == "qpic" then data, msg = Miptex.encodeQpic(img, pal, goldsrc) else data, msg = Miptex.encode(img, name, pal, goldsrc) end if not data then return false, Err.new(Err.ARG, msg or "cannot encode") end Archive.put(a, { name = name, size = buffer.len(data), dir = false, method = "store", lump = name, data = data, type = (kind == "qpic" and{T.qpic }or{goldsrc and 0x43 or T.miptex })[1]}) return true, nil end return Wad2 end __FILES["archive/xz"] = function() local __compat = __compat local buffer = __compat.buffer --!strict -- 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" } }, } -- ------------------------------------------------------------------------------------------------ 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) 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 d == 0x5D and 0.4 or 0.2 end function Xz.sniff(r) if r:peek(6) == XZ_MAGIC then return 1 end return aloneScore(r) end -- ------------------------------------------------------------------------------------------------ decode function Xz.decode(r, opts) local o= 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 = method == "lzma" and"lzma" or"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() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict -- 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 }, } -- ------------------------------------------------------------------------------------------------ sniff function Yenc.sniff(r) local head = r:peek(4096) if string.match(head, "^=ybegin ") then return 0.95 end return string.find(head, "\n=ybegin [^\n]*name=") and 0.6 or 0 end -- ------------------------------------------------------------------------------------------------ decode -- key=value fields of a keyword line; name= runs to the end of the line local function fields(line) local f= {} local s, name = string.match(line, "^(.-)name=(.*)$") if s then f.name = string.gsub(name , "%s+$", "") line = s end for k, v in __iter(string.gmatch(line, "(%w+)=(%S+)")) do f[k] = v end return f end local function decodeData(src, i, j, out, o) local lim = buffer.len(out) local esc = false for p = i, j - 1 do local __DARKLUA_CONTINUE_2=false repeat local c = buffer.readu8(src, p) if c == 13 or c == 10 then __DARKLUA_CONTINUE_2=true break end if c == 61 and not esc then esc = true __DARKLUA_CONTINUE_2=true break end if esc then c =c- 64 esc = false end if o < lim then buffer.writeu8(out, o, (c - 42) % 256) end o =o+ 1 __DARKLUA_CONTINUE_2=true until true if not __DARKLUA_CONTINUE_2 then break end end return o end local function countData(src, i, j) 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 =n+ 1 end end end return n end local function hex(s) return (s and string.match(s, "^%x+$") and #s <= 8 and{(tonumber(s, 16) )}or{nil })[1]end local function parse(b, base, limit) local files= {} local byName= {} local p = base local cur= nil local part= nil while p < limit do local nl = p while nl < limit and buffer.readu8(b, nl) ~= 10 do nl =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= byName[name] if not file then local nf= { name = name , 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, o) return Yenc.encode(a, o) end function Yenc.decode(r, opts) local o= 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 __iter(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 __iter(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 =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 = (#incomplete > 0 and{incomplete }or{nil })[1] a.meta.source = { format = "yenc" } return a, nil end -- ------------------------------------------------------------------------------------------------ encode function Yenc.encode(value, opts) local o= 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 __iter(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 =col+ 2 else w:u8(c) col =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() local a = Archive.new("yenc", encoder) a.meta.source = { format = "yenc" } return a end return Yenc end __FILES["archive/z"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict -- 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 } }, } -- ------------------------------------------------------------------------------------------------ sniff function Z.sniff(r) if r:peek(2) ~= "\31\157" then return 0 end local f = r:peekU8(2) return f >= 0 and bit32.band(f, 0x60) == 0 and bit32.band(f, 0x1F) >= 9 and bit32.band(f, 0x1F) <= 16 and 1 or 0.3 end -- ------------------------------------------------------------------------------------------------ decode local function entryName(opts) 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, opts) return Z.encode(value, opts) end function Z.decode(r, opts) local o= 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, opts) 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, name) 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 __FILES["archive/zip"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict -- 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 -- ------------------------------------------------------------------------------------------------ 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, verify) local a = setmetatable({ kind = "archive", format = "zip", meta = { source = { format = "zip" }, comment = (zip and{zip.comment }or{nil})[1], zip64 = (zip and{zip.zip64 }or{nil })[1]}, _zip = zip, _verify = verify, _order = {} , _items = {} , }, Archive) if zip then for _, e in __iter(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) 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, opts) 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() return new(nil, true) end -- ------------------------------------------------------------------------------------------------ encode function Zip.encode(value, opts) 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 __iter(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 __iter(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 __iter(names) do a:add(k, value[k]) end end return a:write(opts) end -- ------------------------------------------------------------------------------------------------ extras function Archive.list(self) local out = {} for _, name in __iter(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, name) 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, name, data, opts) local b= (type(data) == "string" and{(buffer.fromstring(data) )}or{(type(data) == "buffer" and{data }or{(buffer.create(0) )})[1]})[1] 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, name) 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, opts) local w = Container.writer() for _, name in __iter(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= 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() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict -- 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 ";"). -- ------------------------------------------------------------------------------------------------ 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" } }, } -- ------------------------------------------------------------------------------------------------ constants local TAG = 0xFDC4A7DC -- ------------------------------------------------------------------------------------------------ sniff function Zoo.sniff(r) 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 string.sub(h, 1, 4) == "ZOO " and 1 or 0.8 end -- ------------------------------------------------------------------------------------------------ decode function Zoo.decode(r, opts) local o= 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= {} local size = r:size() while true do if seen[p] or p < 34 or p + 51 > size then return nil, Err.new((p + 51 > size and{Err.TRUNCATED }or{Err.CORRUPT})[1], "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 =count+ 1 if count > maxEntries then return nil, Err.new(Err.LIMIT, "more than maxEntries entries") end local name, dir = fname, "" local entry= {} 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 = (dir ~= "" and{((string.gsub(dir, "/+$", "")) .. "/" .. name )}or{name })[1] 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 = method == 0 and"store" or(method == 1 and"lzw" or(method == 2 and"lzh" or"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() local out, derr 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 , 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() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict -- 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 }, } -- ------------------------------------------------------------------------------------------------ sniff function Zst.sniff(r) 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, opts) local o= 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 __FILES["audio/aac"] = function() local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict -- 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 -- ------------------------------------------------------------------------------------------------ constants local readu8 = buffer.readu8 local function id3Size(b, p, limit) 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 = bit32.band(readu8(b, p + 5), 0x10) ~= 0 and 10 or 0 return 10 + s + footer end local ID3_TAGS= { TIT2 = "title", TPE1 = "artist", TALB = "album", TYER = "date", TDRC = "date", TCON = "genre", TRCK = "track", COMM = "comment", TCOM = "composer", TPE2 = "albumartist", } local function id3Tags(b, p, size) local 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 = (ver == 4 and{(n * 128 + bit32.band(readu8(b, q + i), 127) )}or{(n * 256 + readu8(b, q + i) )})[1] 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 =q+ (10 + n ) end return tags end -- ------------------------------------------------------------------------------------------------ sniff function AacFormat.sniff(r) local b, p, limit = r.buf, r.pos, r.limit p =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 p + h.frameSize >= limit and 0.7 or 0.4 end -- ------------------------------------------------------------------------------------------------ decode local function index(r, maxFrames) local b, limit = r.buf, r.limit local p = r.base + id3Size(b, r.base, limit) local offs, sizes = {}, {} local first= nil while p + 7 <= limit do local __DARKLUA_CONTINUE_4=false repeat 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 =p+ 1 __DARKLUA_CONTINUE_4=true break 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 =p+ h.frameSize __DARKLUA_CONTINUE_4=true until true if not __DARKLUA_CONTINUE_4 then break end end return offs, sizes, first, nil end function AacFormat.open(r, opts) local o= 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 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] local dec, derr = Aac.decoder({ sfIndex = h.sfIndex, channels = channels, channelConfig = h.channelConfig }) if not dec then return nil, derr end local d = dec local sr = d.sampleRate local nframes = #offs local total = nframes * 1024 local bytes = 0 for _, s in __iter(sizes) do bytes =bytes+ s end local id3 = id3Size(r.buf, r.base, r.limit) local tags = (id3 > 0 and{(id3Tags(r.buf, r.base, id3) )}or{{} })[1] local buf = r.buf local out= { sampleRate = sr, channels = channels, frames = total, duration = total / sr, bitrate = (total > 0 and{(math.floor(bytes * 8 * sr / total) )}or{0})[1], 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) return (i - 1) * 1024 end, decode = function(i) return d:decode(buf, offs[i], sizes[i]) end, pcm = function() return d.pcm end, reset = function() d:reset() end, preroll = 1, }) end function AacFormat.decode(r, opts) local dec, err = AacFormat.open(r, opts) if not dec then return nil, err end local d= dec return Pcm.drain(d, { format = "aac", codec = "aac", bitrate = d.bitrate }) end return AacFormat end __FILES["audio/ac3"] = function() --!strict -- 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 -- ------------------------------------------------------------------------------------------------ sniff -- E-AC-3 sniffs too, so it reports UNSUPPORTED rather than an unknown format function Ac3Format.sniff(r) 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 p + h.frameSize >= limit and 0.6 or 0.3 end -- ------------------------------------------------------------------------------------------------ decode -- a header counts when the next one follows it, or the data ends local function index(r, maxFrames) local b, limit = r.buf, r.limit local p = r.base local offs, sizes = {}, {} local first= nil while p + 8 <= limit do local __DARKLUA_CONTINUE_1=false repeat 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 =p+ 1 __DARKLUA_CONTINUE_1=true break 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 =p+ h.frameSize __DARKLUA_CONTINUE_1=true until true if not __DARKLUA_CONTINUE_1 then break end end return offs, sizes, first, nil end function Ac3Format.open(r, opts) local o= 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 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) return (i - 1) * 1536 end, decode = function(i) 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() return d.pcm end, reset = function() d:reset() end, preroll = 1, }) end function Ac3Format.decode(r, opts) local dec, err = Ac3Format.open(r, opts) if not dec then return nil, err end local d= 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() local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict -- 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 -- ------------------------------------------------------------------------------------------------ constants local CODECS = { ima = true, ima_wav = true, ms = true, ima_qt = true, psx = true } -- ------------------------------------------------------------------------------------------------ sniff function Raw.sniff(_r) return 0 end -- ------------------------------------------------------------------------------------------------ decode function Raw.decode(r, opts) 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 ).codec }, limit) end -- ------------------------------------------------------------------------------------------------ encode function Raw.encode(value, opts) local o= 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(math.floor((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 = math.floor((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, opts) if type(r) ~= "table" or type(r.buf) ~= "buffer" then return nil, Err.new(Err.ARG, "open: expected a Reader") end local o= 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= { 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 = ch == 1 and 16 or 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 , buf = r.buf, offset = r.base, size = size, blockAlign = ba }) end if not d then return nil, err end d.bitrate = (d.duration > 0 and{(math.floor(size * 8 / d.duration) )}or{0 })[1] return d, nil end return Raw end __FILES["audio/adx"] = function() local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict -- 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 -- ------------------------------------------------------------------------------------------------ constants local FRAME = 18 -- ------------------------------------------------------------------------------------------------ sniff function Adx.sniff(r) if r:peekU8(0) ~= 0x80 or r:peekU8(1) ~= 0 then return 0 end local off = r:peekU8(2) * 256 + r:peekU8(3) return r:peek(6, off - 2) == "(c)CRI" and 1 or 0 end -- ------------------------------------------------------------------------------------------------ decode function Adx.decode(r, opts) local dec, err = Adx.open(r) if not dec then return nil, err end local d = dec 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, opts) local o= 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 local m = type(v.meta) == "table" and type(v.meta.source) == "table" and v.meta.source.loop loop = (type(m) == "table" and{m }or{((type(v.loop) == "table" and{v.loop }or{nil})[1]) })[1] 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 = (ch > 1 and((4 * ch ))or(8 )) local start = 0x18 + hist + (loop and 0x18 or 0) + 6 start = math.floor((start + 3) / 4 )* 4 local nframes = math.floor((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) return start + (math.floor(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, _opts) 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 .. ((enc == 0x10 or enc == 0x11 )and" (AHX)" or"")) 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= nil local loopsAt= nil if version == 0x0300 then if start - 6 >= 0x14 + 0x18 then loopsAt = 0x14 end elseif version == 0x0400 then local hsize = (ch > 1 and((4 * ch ))or(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] = hh.err and 0 or h1, hh.err and 0 or 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= 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= { 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 = math.floor(rate * FRAME * ch * 8 / 32 ) return d, nil end return Adx end __FILES["audio/aiff"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict -- 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 }, } -- ------------------------------------------------------------------------------------------------ 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, o) 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 (se >= 0x8000 and{(-v )}or{v })[1]end local function writeExt80(w, x) if x <= 0 or x ~= x then w:fill(0, 10) return end local e = 0 while x >= 2 ^ (e + 1) do e =e+ 1 end while x < 2 ^ e do e =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, bits) 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) if r:remaining() < 12 or r:peek(4) ~= "FORM" then return 0 end local form = buffer.readstring(r.buf, r.pos + 8, 4) return (form == "AIFF" or form == "AIFC" )and 1 or 0 end -- ------------------------------------------------------------------------------------------------ decode local function parse(r) 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= nil local comm = false local ssnd= nil local ssndLen = 0 local tags= {} -- a FORM size that undercounts still reads the last chunk's body for _, c in __iter(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 = (aifc and{(buffer.readstring(b, d + 18, 4) )}or{"NONE" })[1] 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(((comp == "NONE" or comp == "twos" or comp == "sowt" )and{Err.CORRUPT }or{Err.UNSUPPORTED})[1], why , 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] = (tags[key] and((tags[key] .. "\n" .. s ))or(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 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 =fi.frames* 64 -- COMM counts packets present = (ssnd and((math.floor(ssndLen / (34 * fi.channels) )* 64 ))or(0 )) else present = (ssnd and{(math.floor(ssndLen / (fi.channels * Pcm.Convert.SIZE[fi.format]) ))}or{0 })[1] 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) return parse(r) end function Aiff.decode(r, opts) 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, opts) local src, serr = Pcm.source(value) if not src then return nil, serr end local o= 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(aifc and"AIFC" or"AIFF") if aifc then w:string("FVER") w:u32be(4) w:u32be(AIFC_VERSION) end for _, pair in __iter(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+ 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, opts) 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 ).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 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() local __compat = __compat local bit32, type = __compat.bit32, __compat.type --!strict -- 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 -- ------------------------------------------------------------------------------------------------ constants local LEVELS = { [1000] = "fast", [2000] = "normal", [3000] = "high", [4000] = "extra high", [5000] = "insane" } -- ------------------------------------------------------------------------------------------------ sniff function Ape.sniff(r) 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 + (footer and 10 or 0)) return (id == "MAC " or id == "MACF" )and 1 or 0 end return 0 end -- ------------------------------------------------------------------------------------------------ decode function Ape.decode(r, opts) local dec, err = Ape.open(r, opts) if not dec then return nil, err end local d = dec 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, opts) if type(r) == "buffer" then r = Bytes.reader(r ) 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 = (tagInfo and{tagInfo.start }or{limit })[1] 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= { sampleRate = info.sampleRate, channels = info.channels, frames = frames, duration = frames / info.sampleRate, bitrate = (frames > 0 and{(math.floor((stop - base) * 8 * info.sampleRate / frames) )}or{0})[1], 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) return (i > count and{frames }or{((i - 1) * bpf )})[1] end, decode = function(i) return codec:frame(buf, i) end, pcm = function() return codec.pcm end, reset = function() end, stop = frames, scale = info.float and 1 or 1 / 2 ^ (info.bitsPerSample - 1), ints = not info.float, }) end return Ape end __FILES["audio/au"] = function() local __compat = __compat local buffer, bit32, type = __compat.buffer, __compat.bit32, __compat.type --!strict -- 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 }, } -- ------------------------------------------------------------------------------------------------ constants local ENCODINGS= { [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, o) return bit32.byteswap(buffer.readu32(b, o)) end -- ------------------------------------------------------------------------------------------------ sniff function Au.sniff(r) return r:peek(4) == ".snd" and 1 or 0 end -- ------------------------------------------------------------------------------------------------ decode function Au.decode(r, opts) 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, opts) local src, serr = Pcm.source(value) if not src then return nil, serr end local o= 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 = (type(src.tags.comment) == "string" and{src.tags.comment }or{"" })[1] 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, opts) 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= {} 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 = math.floor(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 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() local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict -- 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 -- ------------------------------------------------------------------------------------------------ constants local CODECS = { [0] = "pcm8", [1] = "pcm16", [2] = "dsp", [3] = "ima" } -- ------------------------------------------------------------------------------------------------ sniff function Brstm.sniff(r) 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 (bom == "\254\255" or bom == "\255\254" )and 1 or 0 end function Brstm.variant(r) local m = r:peek(4) return m == "RSTM" and"brstm" or(m == "CSTM" and"bcstm" or(m == "FSTM" and"bfstm" or nil ))end -- ------------------------------------------------------------------------------------------------ decode function Brstm.decode(r, opts) local dec, err = Brstm.open(r) if not dec then return nil, err end local d = dec 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, be) local v = { err = nil } local size = r.limit - r.base local function at(o, n) 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) local s = at(o, 1) return (s and{(s:u8() )}or{0 })[1] end function v.u16(o) local s = at(o, 2) return (s and{((be and{(s:u16be() )}or{(s:u16le())})[1]) }or{0 })[1] end function v.i16(o) local s = at(o, 2) return (s and{((be and{(s:i16be() )}or{(s:i16le())})[1]) }or{0 })[1] end function v.u32(o) local s = at(o, 4) return (s and{((be and{(s:u32be() )}or{(s:u32le())})[1]) }or{0 })[1] end function v.i32(o) local s = at(o, 4) return (s and{((be and{(s:i32be() )}or{(s:i32le())})[1]) }or{0 })[1] end return v end local function parseRstm(v) 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= { 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 = math.floor((v.u32(adpc + 4) - 8) / math.max(1, 4 * ch) ) end return L, nil end local function parseFstm(v) local info, seek, data= 0, 0, 0 local seekSize= 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) ) 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= { 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 = (v.u16(dataRef) == 0x1F00 and((data + 8 + v.i32(dataRef + 4) ))or((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 = math.floor((seekSize - 8) / math.max(1, 4 * ch) ) end return L, nil end function Brstm.open(r, _opts) 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, msg 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 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 = codec == "dsp" and"dsp" or(codec == "pcm8" and"s8" or(be and"s16be" or"s16le" )) local coefs= nil local hist= 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 , 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 = L.loop and L.loopStart < L.frames and{ start = L.loopStart, stop = L.frames } or nil local dec= { 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 , buf = r.buf, offset = r.base + L.data, size = size, interleave = block, lastInterleave = (L.lastPadded > 0 and L.lastPadded <= block and{L.lastPadded }or{block})[1], frames = L.frames, coefs = coefs, hist = hist, restore = codec == "dsp" and histAt and function(row, st) if row >= entries then return false end for c = 0, ch - 1 do local p = (histAt ) + (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 or nil, }) if d then d.bitrate = (d.duration > 0 and{(math.floor(size * 8 / d.duration) )}or{0 })[1] end return d, err end return Brstm end __FILES["audio/caf"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict -- 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 -- ------------------------------------------------------------------------------------------------ constants local INFO_TAGS= { 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= {} for k, v in __iter(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] = (bit32.band(u, 128) ~= 0 and((132 - t ))or((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] = (bit32.band(a, 128) ~= 0 and{m }or{(-m )})[1]end -- ------------------------------------------------------------------------------------------------ sniff function Caf.sniff(r) 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 -- the esds payload in a kuki (version / flags, then the ES_Descriptor) -> the DecoderSpecificInfo local function esdsConfig(b) local r = Bytes.reader(b) if r:peekU8() ~= 3 then r:skip(4) -- the esds atom's version / flags end local function len() 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) 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, o) if Caf.sniff(r) == 0 then return nil, Err.new(Err.CORRUPT, "not a CAF file", r.base) end local p= { desc = nil , 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 __iter(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] = (d.bytesPerPacket == 0 and{(vlq(c) )}or{d.bytesPerPacket })[1] 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 local function source(r, p) 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 = (fmt == "lpcm" and{d.bits }or{8 })[1] 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 * (math.floor(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 = math.floor(bits / 8 ) if bpf < ch * bps then return nil, Err.new(Err.CORRUPT, "bytes per packet smaller than a frame") end local total = math.floor((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= { channels = ch, rate = d.rate, packetCount = math.floor((total + per - 1) / per), packetFrames = function(i) return math.min(per, total - (i - 1) * per) end, pcm = pcm, reset = function() end, codec = fmt == "lpcm" and"pcm" or fmt, bits = bits, decode = function(i) 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 = (little and{(buffer.readf32(b, q) )}or{(Bytes.reader(b, q, 4):f32be() )})[1] else v = (little and{(buffer.readf64(b, q) )}or{(Bytes.reader(b, q, 8):f64be() )})[1] end elseif bits == 8 then v = readi8(b, q) * scale elseif bits == 16 then v = (little and{(buffer.readi16(b, q) )}or{(readi8(b, q) * 256 + readu8(b, q + 1) )})[1] v =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 =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 =v* scale end pcm[k] = v k =k+ 1 q =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 = math.floor((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 ), 0) local o = p.dataStart for i, s in __iter(sizes) do offsets[i] = o o =o+ s if o > p.dataEnd then -- a truncated file: keep the whole packets offsets[i] = nil sizes = table.move(sizes , 1, i - 1, 1, {}) break end end local count = #(sizes ) local fpp = d.framesPerPacket local pf = p.packetFrames local function framesOf(i) return (pf and{pf[i] }or{fpp })[1] 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 ) 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) local n, e = dec:decode(b, offsets[i], (sizes )[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 = (cookie and{(esdsConfig(cookie ) )}or{nil })[1] if not asc then return nil, Err.new(Err.CORRUPT, "AAC without an esds magic cookie") end local dec, err = Aac.decoder(asc ) if not dec then return nil, err end local ad = dec return { channels = ad.channels, rate = d.rate, packetCount = count, packetFrames = framesOf, pcm = ad.pcm, reset = function() ad:reset() end, codec = "aac", decode = function(i) return ad:decode(b, offsets[i], (sizes )[i]) end, }, nil end return nil, Err.new(Err.UNSUPPORTED, "CAF format '" .. fmt .. "'") end function Caf.open(r, opts) local p, err = parse(r, opts or {}) if not p then return nil, err end local pp = p 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 = math.floor((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= { 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 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 =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= { sampleRate = rate, channels = ch, frames = frames, duration = frames / rate, bitrate = (frames > 0 and{(math.floor((p.dataEnd - p.dataStart) * 8 * rate / frames) )}or{0})[1], tags = p.tags, codec = src.codec, bitsPerSample = src.bits, } return Stream.packets(dec, { count = src.packetCount, start = function(i) return starts[i] end, decode = src.decode, pcm = function() return src.pcm end, reset = src.reset, skip = skip, stop = stopAt, preroll = src.codec == "aac" and 1 or 0, }) end function Caf.decode(r, opts) local dec, err = Caf.open(r, opts) if not dec then return nil, err end local d= dec return Pcm.drain(d, { format = "caf", codec = d.codec, bitsPerSample = d.bitsPerSample }) end -- ------------------------------------------------------------------------------------------------ encode local function chunk(w, typ, size) w:string(typ) w:i64be(size) end function Caf.encode(value, opts) local o= opts or {} if type(value) ~= "table" or type(value.sampleRate) ~= "number" or type(value.channels) ~= "number" then return nil, Err.new(Err.ARG, "expected an Audio or a Decoder") 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= nil local function nextBlock(n) if isAudio then local k = math.min(n, value.frames - done) local base = done * ch * 4 done =done+ k return value.samples, base, k end local b, got = value:read(n, chunkBuf) chunkBuf = b done =done+ got return b, 0, got end local readf32 = buffer.readf32 local data = Bytes.writer(65536) local sizes= {} local enc= 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 ):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(depth == 32 and 1 or 0) -- float / big-endian integer w:u32be(math.floor(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 __iter(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 __iter(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 __iter(sizes) do -- BER variable-length integer local bytes = { s % 128 } local v = math.floor(s / 128 ) while v > 0 do table.insert(bytes, 1, 128 + v % 128) v =math.floor(v/ 128 ) end for _, x in __iter(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() local __compat = __compat local bit32, type = __compat.bit32, __compat.type --!strict -- 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 -- ------------------------------------------------------------------------------------------------ sniff function Flac.sniff(r) 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 r:peek(4, 10 + sz + (footer and 10 or 0)) == "fLaC" and 1 or 0 end return 0 end -- ------------------------------------------------------------------------------------------------ decode function Flac.decode(r, opts) local dec, err = Flac.open(r, opts) if not dec then return nil, err end local d = dec 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, opts) local src, serr = Pcm.source(value) if not src then return nil, serr end local o= 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 local sb = (type(v.meta) == "table" and type(v.meta.source) == "table" and v.meta.source.bitDepth) or v.bitsPerSample bits = (type(sb) == "number" and sb >= 4 and sb <= 24 and{sb }or{16 })[1] 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 , { level = level, bits = bits , 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, opts) if type(r) == "buffer" then r = Bytes.reader(r ) 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"] = function() local __compat = __compat local buffer, bit32, type = __compat.buffer, __compat.bit32, __compat.type --!strict --!native --!optimize 2 -- 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 = {} local function be16(b, p) return readu8(b, p) * 256 + readu8(b, p + 1) end local function be24(b, p) return readu8(b, p) * 65536 + readu8(b, p + 1) * 256 + readu8(b, p + 2) end local function be32(b, p) return be16(b, p) * 65536 + be16(b, p + 2) end local function streamInfo(b, p) 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 local function vorbisComment(b, p, e, info) if p + 4 > e then return false end local vl = readu32(b, p) p =p+ 4 if p + vl > e then return false end info.vendor = buffer.readstring(b, p, vl) p =p+ vl if p + 4 > e then return false end local n = readu32(b, p) p =p+ 4 for _ = 1, n do if p + 4 > e then return false end local l = readu32(b, p) p =p+ 4 if p + l > e then return false end local s = buffer.readstring(b, p, l) p =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] = (old and((old .. "; " .. value ))or(value )) end end return true end local function picture(b, p, e) if p + 8 > e then return nil end local typ = be32(b, p) local ml = be32(b, p + 4) p =p+ 8 if p + ml + 4 > e then return nil end local mime = buffer.readstring(b, p, ml) p =p+ ml local dl = be32(b, p) p =p+ 4 if p + dl + 20 > e then return nil end local desc = buffer.readstring(b, p, dl) p =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 function Meta.parse(b, pos, len) if pos + 4 > len or buffer.readstring(b, pos, 4) ~= "fLaC" then return nil, "Flac: no fLaC marker" end local info= { streamInfo = nil , 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 =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"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --!native --!optimize 2 -- 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 local PAD = Frame.PAD local Dec = {} Dec.__index = Dec local function sampleOf(self, h) return (h.variable and{h.number }or{(h.number * self._nominal )})[1]end local function plausible(self, h) 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 local function findFrame(self, pos, limit) 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 local function ensure(self, n) if n > self._cap then for c = 1, self.channels do self._chans[c] = table.create(n, 0) end self._cap = n end end local function decodeAt(self, pos) 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 local function pull(self, maxFrames, asInt, dst) local ch = self.channels local want = math.floor(tonumber(maxFrames) or 0) if not (want >= 0) then want = 0 end want = math.min(want, math.floor(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 = (reuse and{dst }or{(buffer.create(want * ch * 4) )})[1] 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._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 =o+ stride end else for i = from, to do writef32(out, o, s[i] * scale) o =o+ stride end end end self._cur =self._cur+ take got =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 function Dec.read(self, maxFrames, out) return pull(self, maxFrames, false, out) end function Dec.readInt(self, maxFrames, out) return pull(self, maxFrames, true, out) end function Dec.position(self) local s = self._fs + self._cur return s / self.sampleRate, s end function Dec.seekSample(self, t) 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 __iter(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 = math.floor((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 function Dec.seek(self, seconds) return self:seekSample(math.floor((tonumber(seconds) or 0) * self.sampleRate + 0.5)) end local function scanLength(self) 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= 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 local function skipId3(b, base, len) 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 =p+ (10 + sz + (footer and 10 or 0) ) end return p end function Stream.open(buf, base, srcLen, opts) 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 ).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 __iter(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 =off+ 9 size =size- 9 end table.insert(packets, { p.data, off, size }) total =total+ size end b = buffer.create(total + PAD) local o = 0 for _, p in __iter(packets) do buffer.copy(b, o, p[1], p[2], p[3]) o =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 , nil end Stream.Dec = Dec return Stream end __FILES["audio/m4a"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict -- 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 -- ------------------------------------------------------------------------------------------------ constants local AUDIO_BRANDS= { ["M4A "] = 1, ["M4B "] = 1, ["M4P "] = 1, ["M4V "] = 0.3 } -- ------------------------------------------------------------------------------------------------ sniff function M4a.sniff(r) 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 local function packetDecoder(t) 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 ) 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= { channels = cfg.channels, sampleRate = (cfg.sampleRate > 0 and{cfg.sampleRate }or{(t.sampleRate or 44100)})[1], frameSize = cfg.frameLength, pcm = pcm, decode = function(buf, off, len) 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 ) if not dec then return nil, err end local d = dec local pd= { channels = d.channels, sampleRate = d.sampleRate, frameSize = d.frameLength, pcm = d.pcm, decode = function(buf, off, len) 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, opts) local o= opts or {} local movie, err = IsoBmff.parse(r, { maxSamples = o.maxSamples }) if not movie then return nil, err end local track= nil local other= nil for _, t in __iter(movie.tracks) do local __DARKLUA_CONTINUE_2=false repeat if t.kind == "audio" then if o.track and t.id ~= o.track then __DARKLUA_CONTINUE_2=true break end if t.codec == "aac" or t.codec == "alac" then track = t break end other = other or t end __DARKLUA_CONTINUE_2=true until true if not __DARKLUA_CONTINUE_2 then break 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 local pd, perr = packetDecoder(t) if not pd then return nil, perr end local p = pd local channels, sr = p.channels, p.sampleRate local tickScale = sr / t.timescale local gapless = o.gapless ~= false local skip = (gapless and{(math.floor(t.skip * tickScale + 0.5) )}or{0 })[1] local total = 0 for i = 1, t.sampleCount do total =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 ..." (hex) local smpb = tags.itunsmpb if gapless and not t.edits and smpb then local f= {} for w in __iter(string.gmatch(smpb, "%x+")) do table.insert(f, (tonumber(w, 16) )) 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= { 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 =bytes+ t.sizes[i] end dec.bitrate = (frames > 0 and{(math.floor(bytes * 8 * sr / frames) )}or{(t.bitrate or 0) })[1] -- 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) 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) return p.decode(buf, t.offsets[i], t.sizes[i]) end, pcm = function() return p.pcm end, reset = p.reset, skip = skip, stop = total, preroll = t.codec == "aac" and 1 or 0, cumulative = true, }) end function M4a.decode(r, opts) local dec, err = M4a.open(r, opts) if not dec then return nil, err end local d= 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, opts) local o= opts or {} if type(value) ~= "table" or type(value.sampleRate) ~= "number" or type(value.channels) ~= "number" then return nil, Err.new(Err.ARG, "expected an Audio or a Decoder") 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 local depth = e.config.bitDepth local fl = e.config.frameLength local peak = 2 ^ (depth - 1) local packets= {} local durations= {} local ints = table.create(fl * ch, 0) local floor = math.floor local readf32 = buffer.readf32 local src, srcFrames = nil , 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= 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 =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 = (sr < 65536 and{sr }or{0 })[1] local file, merr = IsoBmff.mux({ brand = "M4A ", minor = 0, compatible = { "M4A ", "mp42", "isom" }, timescale = 1000, tracks = { { kind = "audio", entry = "alac", timescale = (timescale > 0 and{timescale }or{48000})[1], samples = packets, durations = (timescale > 0 and{durations }or{((function() local d = {} for i, v in __iter(durations) do d[i] = math.floor(v * 48000 / sr + 0.5) end return d end)())})[1], 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() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict -- 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 -- ------------------------------------------------------------------------------------------------ constants local MAX_FRAMES = 2 ^ 31 -- ------------------------------------------------------------------------------------------------ sniff function Mp3.sniff(r) 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 = (p + 3 <= lim and buffer.readstring(b, p, 3) == "ID3" and{(Tags.id3v2Size(b, p, lim) )}or{0 })[1] if n <= 0 then break end id3 = true p =p+ n end if p + 4 > lim or not Header.valid(b, p) then return id3 and 0.5 or 0 end local fb = Header.frameBytes(b, p, 0) if fb > 0 then fb =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 id3 and 0.7 or 0.25 end -- ------------------------------------------------------------------------------------------------ decode function Mp3.decode(r, opts) 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) local w = Bytes.writer(256) local seen= {} local function syncsafe(v) w:u8((math.floor(v / 2097152)) % 128) w:u8((math.floor(v / 16384)) % 128) w:u8((math.floor(v / 128)) % 128) w:u8(v % 128) end for _, f in __iter(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((math.floor(n / 2097152)) % 128) out:u8((math.floor(n / 16384)) % 128) out:u8((math.floor(n / 128)) % 128) out:u8(n % 128) out:bytes(body) return out:finish() end function Mp3.encode(value, opts) local src, serr = Pcm.source(value) if not src then return nil, serr end local o= 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 = (layer == 3 and{Encode3 }or{Encode2 })[1] 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 __iter(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 (src.channels == 1 and"mono" or(layer == 3 and"joint" or"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 ((mpeg1 and{(layer == 3 and 128 or 192) }or{(layer == 3 and 64 or 96)})[1]) if type(bitrate) == "number" and bitrate >= 1000 then bitrate =bitrate/ 1000 end if not table.find(Enc.BITRATES[mpeg1 and 1 or 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((type(o.bitrate) == "number" and o.bitrate < 1000 and((o.bitrate * 1000 ))or(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 = (o.id3 == false and{nil }or{(id3Tag(src.tags) )})[1] local out, msg = Enc.encode(src , { 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) local out= {} for k, v in __iter(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, opts) 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"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 -- 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 local function grow(b, n) local nb = buffer.create(n) buffer.copy(nb, 0, b, 0, math.min(buffer.len(b), n)) return nb end function Index.build(b, start, stop) 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 __DARKLUA_CONTINUE_1=false repeat 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 =pos+ i end if fs < 4 or fs > Core.MAX_FRAME then prev = -1 pos =pos+ max(fs, 1) __DARKLUA_CONTINUE_1=true break 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 = band(h3, 0xC0) == 0xC0 and 1 or 2 if first then first = false hz, nch, layer, spf = fHz, fCh, fLayer, (Header.frameSamples(h1) ) version = band(h1, 8) ~= 0 and 1 or(band(h1, 0x10) ~= 0 and 2 or 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 =pos+ fs __DARKLUA_CONTINUE_1=true break end end elseif fHz ~= hz or fLayer ~= layer then skipped =skipped+ 1 prev = pos pos =pos+ fs __DARKLUA_CONTINUE_1=true break 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 - ((output and{(math.floor((p23 + 7) / 8 ))}or{0})[1]) 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 =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) ) end buffer.writeu32(OFF, n * 4, pos) buffer.writeu16(SIZE, n * 2, fs) buffer.writeu8(FLAGS, n, ((reset and{Index.FLAG_RESET }or{0})[1]) + ((output and{Index.FLAG_OUTPUT }or{0})[1])) buffer.writeu32(OUT, n * 4, outTotal) buffer.writeu16(MAIN, n * 2, min(mainBytes, 65535)) n =n+ 1 bytes =bytes+ fs if output then outTotal =outTotal+ spf end prev = nextPrev pos =pos+ fs __DARKLUA_CONTINUE_1=true until true if not __DARKLUA_CONTINUE_1 then break end 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 = (outCh > 0 and{outCh }or{nch})[1], 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() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!optimize 2 -- 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 function Stream.new(b, idx, tags, id3) 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 =detected- delay end if idx.padding > 0 and detected >= idx.padding then detected =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 = (idx.n > 0 and{(floor(idx.bytes * 8 * hz / (idx.n * spf) + 0.5) )}or{0})[1], -- bit/s tags = tags, id3 = id3, layer = idx.layer, version = idx.version, vbr = idx.vbrTag ~= 0, delay = delay, padding = (idx.vbrTag > 0 and{(max(0, idx.padding) )}or{0})[1], 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) 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, maxFrames, out) 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 =got+ k self._pcmPos =self._pcmPos+ k end self._pos =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, seconds) 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, target) 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 = math.floor((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 = idx.layer == 3 and 511 or 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 =s- 1 back =back+ 1 if back >= 2 then acc =acc+ ru16(idx.main, s * 2) end end self._cur = s end function Decoder.position(self) return self._pos / self.sampleRate, self._pos end function Decoder.readAll(self) return self:read(max(0, self.frames - self._pos)) end Stream.Decoder = Decoder return Stream end __FILES["audio/mp3/Tags"] = function() local __compat = __compat local buffer, bit32, utf8, __iter = __compat.buffer, __compat.bit32, __compat.utf8, __compat.__iter --!strict --!optimize 2 -- 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) 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, i, j, enc) 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 =i+ 2 elseif b0 == 0xFE and b1 == 0xFF then i =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 = (le and{(bor(ru8(b, i), lshift(ru8(b, i + 1), 8)) )}or{(bor(lshift(ru8(b, i), 8), ru8(b, i + 1)) )})[1] i =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, u == 0 and"\0" or 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, (c < 0x80 and{(string.char(c) )}or{(utf8char(c))})[1]) end end return table.concat(out) end local function clean(s) s = string.gsub(s, "[%z%s]+$", "") s = string.gsub(s, "%z+", " / ") return s end -- "(17)", "(17)Rock", "17" -> "Rock" local function genreName(s) 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, o) 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, o) 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, i, j) 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 =n+ 1 k =k+ (c == 0xFF and k + 1 < j and ru8(b, k + 1) == 0 and 2 or 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, o, len) 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 =size+ 10 end return size end local function setField(tags, id, text) tags.raw[id] = text local f = FIELDS[id] if f and tags[f] == nil and text ~= "" then tags[f] = (f == "genre" and{(genreName(text) )}or{text })[1] end end local function parseV2(b, o, size, tags) 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 =p+ (ver == 3 and{(be32(body, p) + 4 )}or{(syncsafe(body, p) )})[1] end local hdr = ver == 2 and 6 or 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 = (ver == 4 and{(syncsafe(body, p + 4) )}or{(be32(body, p + 4) )})[1] 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 =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 =q+ 2 break end q =q+ 2 else if ru8(fb, q) == 0 then q =q+ 1 break end q =q+ 1 end end if q <= fe then setField(tags, id, clean(decodeText(fb, q, fe, enc))) end end end p =p+ (hdr + fsize ) end end local function v1String(b, o, n) return (string.gsub(decodeText(b, o, o + n, 0), "[%z%s]+$", "")) end function Tags.parse(b) local len = buffer.len(b) local tags= { 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= { 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 __iter(v1) do if tags[k] == nil and v ~= "" then tags[k] = v end end size =size- 128 if size >= 227 and buffer.readstring(b, start + size - 227, 4) == "TAG+" then size =size- 227 end end if size > 32 and buffer.readstring(b, start + size - 32, 8) == "APETAGEX" then size =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 =size- tagSize end tags.ape = true end stop = start + size return tags, start, stop end return Tags end __FILES["audio/mpc"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict -- 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 -- ------------------------------------------------------------------------------------------------ constants local function id3v2(b, p, limit) if p + 10 > limit or buffer.readstring(b, p, 3) ~= "ID3" then return 0 end local n = 10 for i = 6, 9 do n =n+ bit32.band(buffer.readu8(b, p + i), 127) * 128 ^ (9 - i) end return n + (bit32.band(buffer.readu8(b, p + 5), 0x10) ~= 0 and 10 or 0) end -- ------------------------------------------------------------------------------------------------ sniff function Mpc.sniff(r) local b, p, limit = r.buf, r.pos, r.limit p =p+ id3v2(b, p, limit) local v = Musepack.magic(b, p, limit) if v == 8 then return 1 end return v == 7 and 0.9 or 0 end -- ------------------------------------------------------------------------------------------------ decode function Mpc.open(r, opts) local o= 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 = (info and info.start > start and{info.start }or{limit })[1] 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 = (duration > 0 and{(math.floor(s.bytes * 8 / duration + 0.5) )}or{0})[1], tags = tags or {}, codec = "musepack", version = s.version, profile = s.profile, gain = s.gain, } return Stream.packets(dec, s ) end function Mpc.decode(r, opts) local dec, err = Mpc.open(r, opts) if not dec then return nil, err end local d= 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() local __compat = __compat local buffer, bit32, type = __compat.buffer, __compat.bit32, __compat.type --!strict -- 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 -- ------------------------------------------------------------------------------------------------ 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 -- OpusHead (RFC 7845 section 5.1) local function parseHead(b, off, size) 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= { 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 = channels == 2 and{ 0, 1 } or{ 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, off, size) 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 =p+ 4 if p + vlen > e then return "", {}, {} end local vendor = buffer.readstring(b, p, vlen) p =p+ vlen local list = {} if p + 4 <= e then local n = buffer.readu32(b, p) p =p+ 4 for _ = 1, n do if p + 4 > e then break end local l = buffer.readu32(b, p) p =p+ 4 if p + l > e then break end table.insert(list, buffer.readstring(b, p, l)) p =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) if r:peek(4) ~= "OggS" then return 0 end local nseg = r:peekU8(26) if nseg < 1 then return 0 end return r:peek(8, 27 + nseg) == "OpusHead" and 1 or 0 end -- ------------------------------------------------------------------------------------------------ decode function Opus.decode(r, opts) 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, opts) return Encode.encode(value, opts) end -- ------------------------------------------------------------------------------------------------ open local Stream = {} Stream.__index = Stream local function decodeNext(self) 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 = (p.size > 0 and{(Packet.samples(p.data, p.offset, p.size) )}or{(-1 )})[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 =self.decoded+ n return true end function Stream.read(self, maxFrames, into) local ch = self.channels local mf = (type(maxFrames) == "number" and maxFrames == maxFrames and{maxFrames }or{0 })[1] 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 = (reuse and{into }or{(buffer.create(want * ch * 4) )})[1] local got = 0 local gain = self.gain while got < want do local __DARKLUA_CONTINUE_4=false repeat 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)) __DARKLUA_CONTINUE_4=true break 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 =self.pendPos+ n got =got+ n self.next =self.next+ n __DARKLUA_CONTINUE_4=true until true if not __DARKLUA_CONTINUE_4 then break end 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) return (self.next - self.preSkip) / SAMPLE_RATE end function Stream.seek(self, seconds) local sec = (type(seconds) == "number" and seconds == seconds and{seconds }or{0 })[1] 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, opts) local demux, derr = Ogg.open(r, opts and opts.verify == false and{ verify = false } or 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((string.find(herr or "", "unsupported", 1, true) and{Err.UNSUPPORTED }or{Err.CORRUPT})[1], 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 = (p.size > 0 and{(Packet.samples(p.data, p.offset, p.size) )}or{0 })[1] sum =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 = (info and info.lastGranule and info.lastGranule >= 0 and{info.lastGranule }or{startGranule })[1] 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 = (not downmix and head.mappingFamily == 1 and head.channels > 2 and{Pcm.WAVE_FROM_VORBIS[head.channels] }or{nil})[1], sampleRate = SAMPLE_RATE, channels = downmix and 2 or head.channels, sourceChannels = head.channels, downmix = downmix, frames = frames, duration = frames / SAMPLE_RATE, bitrate = (frames > 0 and{(math.floor(demux.size * 8 / (frames / SAMPLE_RATE)) )}or{0})[1], 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() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict -- 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 = {} local floor = math.floor function Encode.encode(value, opts) local o= 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 =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 ) if not all then return nil, aerr end local n48 = all.frames local samples = all.samples local pcm= 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 = math.floor((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), ch == 2 and 40 or 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 __iter(fields) do tw:u32le(#field) tw:string(field) end s:packet(tw:finish(), 0, { flush = true }) local toc = 31 * 8 + (ch == 2 and 4 or 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 = (last and((preSkip + n48 ))or(((p + 1) * FRAME ))) s:packet(pkt, granule, { eos = last }) end return mux:finish(), nil end return Encode end __FILES["audio/qoa"] = function() local __compat = __compat local buffer, bit32, type = __compat.buffer, __compat.bit32, __compat.type --!strict -- 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 -- ------------------------------------------------------------------------------------------------ sniff function Qoa.sniff(r) return r:peek(4) == "qoaf" and 1 or 0 end -- ------------------------------------------------------------------------------------------------ decode function Qoa.decode(r, opts) local dec, err = Qoa.open(r) if not dec then return nil, err end local d = dec 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, _opts) 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 + ((src.frames > 0 and{(Codec.frameSize(ch, math.floor((src.frames + 19) / 20)) + 24 * ch * (math.floor(src.frames / FL )+ 1) )}or{65536})[1])) w:string("qoaf") w:u32be(0) local lms = Codec.newLms(ch) local fb = buffer.create(FL * ch * 4) local tmp= 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 =have+ n end if have == 0 then break end local at = w:reserve(Codec.frameSize(ch, math.floor((have + 19) / 20))) w.pos = at + Codec.encodeFrame(fb, 0, have, ch, rate, lms, w.buf, at) total =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, _opts) 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 =total+ info.samples p =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 = (declared > 0 and{(math.min(declared, total) )}or{total })[1] local pcm = buffer.create(Codec.FRAME_LEN * ch * 4) local dec= { 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) return (i > #offs and{total }or{starts[i] })[1] end, decode = function(i) 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() return pcm end, reset = function() end, stop = frames, }) end return Qoa end __FILES["audio/tta"] = function() local __compat = __compat local bit32, type = __compat.bit32, __compat.type --!strict -- 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 -- ------------------------------------------------------------------------------------------------ sniff local function id3Size(r) 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 + (footer and 10 or 0) end function Tta.sniff(r) return r:peek(4, id3Size(r)) == "TTA1" and 1 or 0 end -- ------------------------------------------------------------------------------------------------ decode function Tta.decode(r, opts) local dec, err = Tta.open(r, opts) if not dec then return nil, err end local d = dec 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, opts) if type(r) == "buffer" then r = Bytes.reader(r ) 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 = (tagInfo and{tagInfo.start }or{limit })[1] 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= { sampleRate = info.sampleRate, channels = info.channels, frames = frames, duration = frames / info.sampleRate, bitrate = (frames > 0 and{(math.floor((stop - base) * 8 * info.sampleRate / frames) )}or{0})[1], 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) return (i > count and{frames }or{((i - 1) * fl )})[1] end, decode = function(i) return codec:frame(buf, i) end, pcm = function() 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() local __compat = __compat local buffer, bit32, type = __compat.buffer, __compat.bit32, __compat.type --!strict -- 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 -- ------------------------------------------------------------------------------------------------ constants local HEVAG = { [0x00020001] = true, [0x00030000] = true } -- ------------------------------------------------------------------------------------------------ sniff function Vag.sniff(r) local m = r:peek(4) return (m == "VAGp" or m == "VAGi" or m == "KVAG" )and 1 or 0 end -- ------------------------------------------------------------------------------------------------ decode function Vag.decode(r, opts) local dec, err = Vag.open(r) if not dec then return nil, err end local d = dec 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, opts) local o= 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 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 = math.floor((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 = math.floor(loop.start / 28), math.floor((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 = (ch == 1 and{chBytes }or{(math.floor((chBytes + il - 1) / il )* il )})[1] local start = ch == 1 and 0x30 or 0x800 local out = buffer.create(start + stride * ch) local title = o.name or (a.tags and a.tags.title) or "" buffer.writestring(out, 0, ch == 1 and"VAGp" or"VAGi") buffer.writeu32(out, 4, bit32.byteswap(0x20)) if ch == 2 then buffer.writeu32(out, 8, il) end buffer.writeu32(out, 0x0C, bit32.byteswap((ch == 1 and{chBytes }or{stride})[1])) 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 = k == ls and 6 or(k == le and 3 or(k > ls and k < le and 2 or 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, math.floor(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, p, frames, il, ch) local ls, le = -1, -1 for k = 0, frames - 1 do local off = p + math.floor((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 ls >= 0 and le > ls and{ start = ls, stop = le } or nil end function Vag.open(r, _opts) 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= { 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(math.floor(chSize / 16), (math.floor(size / (il * ch))) * (math.floor(il / 16)) + math.floor(math.clamp(size % (il * ch) - (ch - 1) * il, 0, il) / 16)) local loop = (magic == "VAGp" and{(findLoop(r.buf, p, frames, il, ch) )}or{nil -- vgmstream: VAGi never loops })[1] local tags = {} if name ~= "" then tags.title = name end local dec= { 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 = math.floor(rate * 16 * 8 * ch / 28 ) end return d, err end return Vag end __FILES["audio/voc"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict -- 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 }, } -- ------------------------------------------------------------------------------------------------ constants local MAGIC = "Creative Voice File\26" local T9_CODECS= { [0] = "u8", [4] = "s16le", [6] = "alaw", [7] = "ulaw" } local T1_CODECS= { [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, o) return readu8(b, o) + readu8(b, o + 1) * 256 end local function u24(b, o) return readu8(b, o) + readu8(b, o + 1) * 256 + readu8(b, o + 2) * 65536 end -- ------------------------------------------------------------------------------------------------ sniff function Voc.sniff(r) return r:peek(20) == MAGIC and 1 or 0 end -- ------------------------------------------------------------------------------------------------ decode function Voc.decode(r, opts) 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= nil local codec = -1 local segments= {} local total = 0 local truncated = false local tags= {} local p = base + hsize local function add(at, bytes, fmt, ch, sr) 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 = (fmt and{(math.floor(bytes / (ch * Pcm.Convert.SIZE[fmt]) ))}or{bytes })[1] if frames > 0 then total =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= 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, math.floor(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, (channels > 0 and{channels }or{1})[1], (rate > 0 and{rate }or{(math.floor(1000000 / (256 - div)))})[1]) 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 = (tags.comment and((tags.comment .. "\n" .. s ))or(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 = math.floor(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((truncated and{Err.TRUNCATED }or{Err.CORRUPT})[1], "no sound data", p) end local a = Types.Audio.new(rate, channels, total) local o = 0 for _, s in __iter(segments) do local n = s.frames * channels if s.fmt then Pcm.Convert.decode(b, s.at, s.fmt , n, a.samples, o) end o =o+ n * 4 end a.tags = tags a.meta.source = { format = "voc", version = string.format("%d.%02d", math.floor(version / 256), version % 256), codec = codec, sampleFormat = lastFmt, bitDepth = lastFmt == "s16le" and 16 or 8, truncated = truncated or nil, } return a, nil end -- ------------------------------------------------------------------------------------------------ encode function Voc.encode(value, opts) local src, serr = Pcm.source(value) if not src then return nil, serr end local o= 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 = math.floor(MAX_BLOCK / frameBytes ) local blockAt, blockFrames = -1, 0 local tmp= 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 =blockFrames+ take i =i+ take local len = blockFrames * frameBytes + 12 w:setU8(blockAt + 1, len % 256) w:setU8(blockAt + 2, (math.floor(len / 256)) % 256) w:setU8(blockAt + 3, math.floor(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, opts) local a, err = Voc.decode(r, opts) if not a then return nil, err end local dec = (Pcm.audioDecoder(a) ) dec.source = a.meta.source return dec, nil end return Voc end __FILES["audio/vorbis"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict -- 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 }, } -- ------------------------------------------------------------------------------------------------ constants local function waveOrder(ch) 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, h2, h3) 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 = (serr == "floor 0" and{Err.UNSUPPORTED }or{Err.CORRUPT })[1] 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) 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 buffer.readu8(b, d) == 1 and buffer.readstring(b, d + 1, 6) == "vorbis" and 1 or 0 end -- ------------------------------------------------------------------------------------------------ decode function Vorbis.decode(r, opts) 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, opts) local src, serr = Pcm.source(value) if not src then return nil, serr end local o= 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 , { 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, arrays, g0, count, hi) 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, count) 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) 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 = (p.eos and p.granule >= 0 and{p.granule }or{math.huge })[1] if self.syncing then if count > 0 then table.insert(self.pend, { copyOut(self, count), count }) self.pendCount =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 __iter(self.pend) do push(self, c[1], g, c[2], endG) g =g+ c[2] end self.pos = g self.syncing, self.pend, self.pendCount = false, {}, 0 end else local g0 = self.pos 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, n, out) local ch = self.channels n = math.max(0, math.floor(n)) local b = (out and buffer.len(out) >= n * ch * 4 and{out }or{(buffer.create(n * ch * 4) )})[1] 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 =o+ ch * 4 end end got =got+ take self.next = q[4] + take if first + take > last then table.remove(self.queue, 1) else q[2] = first + take q[4]=q[4]+ take end end if got > 0 then self.skipTo = -math.huge end return b, got end function Stream.position(self) return (self.next - self.startG) / self.sampleRate end local function restart(self) 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, seconds) 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 =self.pendCount+ count end if p.granule >= 0 then if not p.eos then local g0 = p.granule - self.pendCount for _, c in __iter(self.pend) do push(self, c[1], g0, c[2], math.huge) g0 =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, opts) local demux, derr = Ogg.open(r, opts and opts.verify == false and{ verify = false } or 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 =sum+ (math.floor(prev / 4 )+ math.floor(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 = (info and info.lastGranule and info.lastGranule >= 0 and{info.lastGranule }or{(-1 )})[1] local startG = math.max(base, 0) local frames = (lastG >= 0 and{(math.max(0, lastG - startG) )}or{0 })[1] local rate = id.sampleRate local self = setmetatable({ sampleRate = rate, channels = id.channels, frames = frames, duration = frames / rate, bitrate = (frames > 0 and{(math.floor(demux.size * 8 / (frames / rate)) )}or{id.bitrateNominal})[1], 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 , nil end -- ------------------------------------------------------------------------------------------------ extras -- raw Vorbis packets: Matroska / WebM / MP4 carry the three headers in their codec private data function Vorbis.packetDecoder(h1, h2, h3) local function pk(b) 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, b, offset, size) 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) Packet.reset(st) end, }, nil end return Vorbis end __FILES["audio/vorbis/Encode"] = function() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict --!native --!optimize 2 -- 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 local function newW(size) return { buf = buffer.create(size), pos = 0, acc = 0, cnt = 0 } end local function put(w, v, n) 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 =p+ 1 acc = (acc - byte) / 256 cnt =cnt- 8 end w.acc, w.cnt, w.pos = acc, cnt, p end local function finish(w) 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 local function putString(w, s) for i = 1, #s do put(w, string.byte(s, i), 8) end end local function ilog(x) local n = 0 while x > 0 do n =n+ 1 x = floor(x / 2) end return n end -- ------------------------------------------------------------------------------------------------ codebooks local function huffmanLengths(w) local n = #w local total = 0 for i = 1, n do total =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, function(a, b) 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 local function pop() local a = (h1 <= n and{q1[h1] }or{nil })[1] local b = (h2 <= t2 and{q2[h2] }or{nil })[1] if a and (not b or weight[a] <= weight[b]) then h1 =h1+ 1 return a end h2 =h2+ 1 return b end for _ = 1, n - 1 do local a = pop() local b = pop() nextId =nextId+ 1 weight[nextId] = weight[a] + weight[b] parent[a], parent[b] = nextId, nextId t2 =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 =d+ 1 end lens[i] = d end return lens end -- the spec's codeword assignment (lowest free leaf, in entry order) local function assign(lens) local codes = table.create(#lens, 0) local available = table.create(33, 0) local first = true for i, len in __iter(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 =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 local function makeBook(dims, entries, weight, lookup, minimum, delta, values) 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 local function vqBook(dims, h, scale, s, zeroBoost) local values = 2 * h + 1 local entries = values ^ dims return makeBook(dims, entries, function(e) local wt = 1 local x = e for _ = 1, dims do local v = x % values - h x = math.floor(x / values ) wt =wt* (exp(-abs(v) / s) * ((v == 0 and{zeroBoost }or{1})[1]) ) end return wt end, 1, -h * scale, scale, values) end local BOOK_FLOOR = makeBook(1, RANGE, function(e) 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, function(e) return CLASS_W[e % NCLASS + 1] * CLASS_W[math.floor(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 local function float32Pack(x) local sign = x < 0 and 2147483648 or 0 local m = abs(x) local e = 788 while m >= 2097152 do m =m/ 2 e =e+ 1 end return sign + e * 2097152 + floor(m) end local function writeBook(w, b) 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 local function putEntry(w, b, e) 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= { 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 =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 =qh+ 1 if r[1] <= r[2] then local m = math.floor((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 = math.floor((NPOSTS - 2) / 4 -- 7 partitions of one class with 4 dimensions )local SORTED= table.create(NPOSTS, 0) -- post indices (1-based) by increasing x for i = 1, NPOSTS do SORTED[i] = i end table.sort(SORTED, function(a, b) 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 local function yOf(db) local y = floor((db - DB[1]) / (DB[RANGE] - DB[1]) * (RANGE - 1) + 0.5) return math.clamp(y, 0, RANGE - 1) end local function predict(x, x0, x1, y0, y1) local dy = y1 - y0 local adx = x1 - x0 local off = math.floor((abs(dy) * (x - x0)) / adx ) return (dy < 0 and((y0 - off ))or((y0 + off )))end -- render the decoder's floor curve for final Y values into F[1..N2] (only the posts the decoder marks used) local function renderFloor(Y, used, F) local lx, ly = 0, Y[1] * MULT for q = 2, NPOSTS do local __DARKLUA_CONTINUE_28=false repeat local j = SORTED[q] if not used[j] then __DARKLUA_CONTINUE_28=true break 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 = (dy < 0 and{(-(math.floor(ady / adx)) )}or{(math.floor(ady / adx ))})[1] local sy = (dy < 0 and((base - 1 ))or((base + 1 ))) ady =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 =x+ 1 while x < x1 do err =err+ ady if err >= adx then err =err- adx y =y+ sy else y =y+ base end F[x + 1] = Tables[y % 256 + 1] x =x+ 1 end end lx, ly = hx, hy __DARKLUA_CONTINUE_28=true until true if not __DARKLUA_CONTINUE_28 then break end 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) local function floorVal(Y, j) 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 = (highroom < lowroom and((highroom * 2 ))or((lowroom * 2 ))) local cands = { (d > 0 and((2 * d ))or((-2 * d - 1))), d + lowroom, -d + highroom - 1 } for _, v in __iter(cands) do if v > 0 and v < RANGE then local got if v >= room then got = (highroom > lowroom and((v - lowroom + pred ))or((pred - v + highroom - 1 ))) elseif v % 2 == 1 then got = pred - math.floor((v + 1) / 2 ) else got = pred + math.floor(v / 2 ) end if got == t then return v end end end return 0 end -- ------------------------------------------------------------------------------------------------ headers local function identHeader(ch, rate, nominal) 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 local function commentHeader(vendor, tags) 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 __iter(fields) do put(w, #s, 32) putString(w, s) end put(w, 1, 1) return finish(w) end local function setupHeader(ch) local w = newW(8192) put(w, 5, 8) putString(w, "vorbis") -- codebooks put(w, #BOOKS - 1, 8) for _, b in __iter(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 =bits+ POW[pass] end end put(w, bits % 8, 3) if bits >= 8 then put(w, 1, 1) put(w, math.floor(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 local function writePartition(w, v, o, psize, c, pass) local b = CLASS_BOOKS[c][pass] if b < 0 then return end local book = BOOKS[b + 1] local dims, h = book.dims, math.floor((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(math.floor(x / scale), -h, h) end v[o + i + k + 1] = x - q * scale e =e+ (q + h) * m m =m* values end putEntry(w, book, e) i =i+ dims end end function Encode.encode(src, opts) 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) ) local win = (Mdct.window("vorbis", N) ) -- input ring: per channel the samples of the current frame [k*1024 - 1024, k*1024 + 1024) local frame= (table.create(ch) ) for c = 1, ch do frame[c] = table.create(N, 0) end -- the input is in WAVE channel order; input channel c goes to Vorbis channel order[c] local order = Pcm.WAVE_FROM_VORBIS[ch] or {} if #order ~= ch then order = table.create(ch, 0) for c = 1, ch do order[c] = c end end local blk = table.create(N, 0) local X= (table.create(ch) ) local R= (table.create(ch) ) 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 = math.floor(N2 * ch / psize ) local classes = table.create(npart + 2, 0) local total = 0 local srcDone = false local tmp= nil local pending= 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 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 =got+ take pendN =pendN- take pendOff =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 =total+ got if srcDone and lastWanted < 0 then lastWanted = math.floor((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 =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) ) local lo = (idx > 1 and{(math.floor((POSTS[SORTED[idx - 1] ] + x) / 2 ))}or{0 })[1] local hi = (idx < NPOSTS and{(math.floor((POSTS[SORTED[idx + 1] ] + x) / 2 ))}or{(N2 - 1 )})[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 =s+ xc[i] * xc[i] end s =s/ (hi - lo + 1) if s > e then e = s end end local db = (e > 0 and((10 * math.log10(e) - snrDb + 8 * x / N2 ))or((-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 = (a > 0 and((a - b ))or((b - a ))) else m = b an = (b > 0 and((a - b ))or((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 =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 = k == 0 and 0 or math.min(k * N2, (lastWanted >= 0 and{total }or{math.huge})[1]) stream:packet(pk, granule, last and{ eos = true } or nil) if last then break end k =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() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --!optimize 2 -- 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 -- ------------------------------------------------------------------------------------------------ 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 = (bit32.band(u, 0x80) ~= 0 and((0x84 - m ))or((m - 0x84 ))) buffer.writef32(MULAW, i * 4, v / 32768) end end local Decoder = {} Decoder.__index = Decoder local function trimTag(s) local e = #s while e > 0 do local c = string.byte(s, e) if c ~= 0 and c ~= 32 then break end e =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) return Riff.sniff(r) == "WAVE" and 1 or 0 end -- ------------------------------------------------------------------------------------------------ decode function Wav.decode(r, opts) 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, opts, asParts) if type(value) ~= "table" then return nil, Err.new(Err.ARG, "encode: needs an Audio or a Decoder") end local o= opts or {} local kind = o.sampleFormat or "s16" local bytes= 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, ch= 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= {} local frames= 0 if isAudio then frames = (value.frames ) or (math.floor(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, math.floor(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 =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, math.floor(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 =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 = float and 3 or 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 = (o.rf64 ~= nil and{o.rf64 }or{"auto"})[1], sampleCount = frames, rf64Threshold = o.rf64Threshold }) local fmt = Bytes.writer(40) fmt:u16le(extensible and 0xFFFE or 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((w.rf64 == true or frames > 0xFFFFFFFF )and 0xFFFFFFFF or 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 __iter(tags) do if type(k) == "string" then table.insert(keys, k) end end table.sort(keys) for _, k in __iter(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 ((string.match(string.lower(k), "^i[%l%d][%l%d][%l%d]$") and{(string.upper(k) )}or{nil})[1]) 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, opts) return encodeParts(value, opts, false) end function Wav.encodeParts(value, opts) return encodeParts(value, opts, true) end -- ------------------------------------------------------------------------------------------------ open function Wav.open(r, _opts) if type(r) == "buffer" or type(r) == "string" then r = Bytes.reader((type(r) == "string" and{(buffer.fromstring(r) )}or{r })[1]) 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= nil local tags= {} local dataOff, dataSize = -1, 0 local truncated = false local ds64Frames= (f.ds64 and f.ds64.sampleCount > 0 and{f.ds64.sampleCount }or{nil })[1] local factFrames= nil local function u16(o) return Riff.u16(f, o) end local function u32(o) return Riff.u32(f, o) end local function i16(o) local v = u16(o) return (v >= 32768 and((v - 65536 ))or(v )) end for _, c in __iter(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 = (avail >= 16 and{(u16(body + 14) )}or{8})[1], 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 __iter(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= nil local validBits= 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= FORMAT_NAMES[tag] if not name then return nil, Err.new(Err.UNSUPPORTED, string.format("format 0x%04X", tag)) end local dec = (setmetatable({}, Decoder) ) 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= fmt.blockAlign local frames 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 = math.floor(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 = math.floor((bits + 7) / 8 ) if blockAlign >= ch and blockAlign % ch == 0 and math.floor(blockAlign / ch )>= bytes and math.floor(blockAlign / ch )<= 4 then bytes = math.floor(blockAlign / ch ) end end blockAlign = bytes * ch dec._bytes = bytes dec._kind = name frames = math.floor(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 = (fmt.avail >= 20 and{(u16(fmt.body + 18) )}or{0 })[1] 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 = math.floor((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 = math.floor((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 = math.floor(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 =frames+ math.min(spb, 1 + (math.floor((rest - 4 * ch) / (4 * ch))) * 8) end elseif rest >= 7 * ch then frames =frames+ math.min(spb, 2 + math.floor(((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 = (fmt.byteRate > 0 and((fmt.byteRate * 8 ))or((math.floor(rate * blockAlign * 8 / dec._spb) ))) return dec, nil end -- ------------------------------------------------------------------------------------------------ extras function Decoder.read(self, maxFrames, out) 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= (out and type(out) == "buffer" and buffer.len(out) >= want * ch * 4 and{out }or{(buffer.create(want * ch * 4) )})[1] 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 =self._pos+ want return dst, want end local spb, ba = self._spb, self.blockAlign local cache = self._cache local done = 0 while done < want do local block = math.floor(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 , self._ncoef, self._state ) 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 =done+ k self._pos =self._pos+ k end return dst, done end function Decoder.seek(self, seconds) 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, frame) 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) return self._pos / self.sampleRate end function Decoder.tell(self) return self._pos end return Wav end __FILES["audio/wav/Codecs"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 -- 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 function Codecs.int(src, off, dst, d, count, bytes, be) 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 =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 function Codecs.float(src, off, dst, d, count, bytes, be, tmp) 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 function Codecs.law(src, off, dst, d, count, tbl) local o = d * 4 for i = 0, count - 1 do writef32(dst, o + i * 4, readf32(tbl, readu8(src, off + i) * 4)) end end function Codecs.copy(src, sOff, dst, dOff, count) buffer.copy(dst, dOff * 4, src, sOff * 4, count * 4) end function Codecs.quantize(src, s, dst, off, count, kind) 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 =v+ 16777216 end local o = off + i * 3 writeu16(dst, o, v % 65536) writeu8(dst, o + 2, math.floor(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() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict -- 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 -- ------------------------------------------------------------------------------------------------ sniff function WavPack.sniff(r) if r:peek(4) ~= "wvpk" then return 0 end local v = r:peekU8(9) return v == 4 and 1 or 0.5 end -- ------------------------------------------------------------------------------------------------ decode function WavPack.decode(r, opts) local dec, err = WavPack.open(r, opts) if not dec then return nil, err end local d = dec 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 local function index(buf, base, limit) local at = base local idx= { offsets = {}, starts = {}, samples = {}, total = -1, first = -1 } local cur= nil local initial = -1 local resyncs = 0 while at + 32 <= limit do local __DARKLUA_CONTINUE_1=false repeat 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 =resyncs+ 1 __DARKLUA_CONTINUE_1=true break 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 =at+ h.size __DARKLUA_CONTINUE_1=true until true if not __DARKLUA_CONTINUE_1 then break end end if idx.first < 0 then return nil, "no audio blocks" end return idx, nil end local function correctionFile(opts) 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, opts) if type(r) == "buffer" then r = Bytes.reader(r ) 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 = (tagInfo and{tagInfo.start }or{limit })[1] 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 = (idx.total >= 0 and{(math.min(idx.total, last) )}or{last })[1] local cbuf = (info.hybrid and{(correctionFile(opts) )}or{nil })[1] local cfor= {} if cbuf then local cidx = index(cbuf, 0, buffer.len(cbuf)) if cidx then for i, offs in __iter(cidx.offsets) do cfor[cidx.starts[i] ] = offs end else cbuf = nil end end local codec = WavPackCodec.decoder(info.channels) local dec= { sampleRate = info.sampleRate, channels = info.channels, frames = frames, duration = frames / info.sampleRate, bitrate = (frames > 0 and{(math.floor((stop - base) * 8 * info.sampleRate / frames) )}or{0})[1], 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) return (i > count and{last }or{starts[i] })[1] end, decode = function(i) local co = (cbuf and{cfor[starts[i] ] }or{nil })[1] return codec:frame(buf, offsets[i], (co and{cbuf }or{nil})[1], co) end, pcm = function() return codec.pcm end, reset = function() end, stop = frames, scale = info.float and 1 or 1 / 2 ^ (info.bytesPerSample * 8 - 1), ints = not info.float, }) end return WavPack end __FILES["cad/step"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict -- 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 -- ------------------------------------------------------------------------------------------------ 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) 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) 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, opts) 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 = (at and((r.base + bom + at - 1 ))or(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 = (fs and type(fs[1]) == "table" and type(fs[1][1]) == "string" and{fs[1][1] }or{"" })[1] local cad= { kind = "cad", schema = (schemaName ~= "" and{(schemaOf(schemaName) )}or{"unknown"})[1], header = res.header, entities = res.entities, meta = { count = res.count, headerOrder = res.headerOrder, source = { format = "step", schemaName = schemaName, sections = res.sections, extra = (#res.extra > 0 and{res.extra }or{nil})[1], duplicates = (res.duplicates > 0 and{res.duplicates }or{nil})[1], terminated = res.terminated, }, }, } return cad, nil end -- ------------------------------------------------------------------------------------------------ encode local function headerArgs(cad, o) local h = (type(cad.header) == "table" and{cad.header }or{{} })[1] local out= {} for k, v in __iter(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 ((type(out.FILE_SCHEMA) ~= "table" and{cad.schema }or{nil})[1]) if schema then out.FILE_SCHEMA = { { SCHEMAS[schema] or schema } } end return out end function Step.encode(cad, opts) 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= opts or {} local nl = o.crlf and"\r\n" or"\n" local 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= (type(cad.meta) == "table" and{cad.meta }or{{} })[1] local rest = {} for _, k in __iter(((type(meta.headerOrder) == "table" and{meta.headerOrder }or{{}})[1])) 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 __iter(header) do if type(k) == "string" and not seen[k] then table.insert(rest, k) end end table.sort(rest) for _, k in __iter(rest) do table.insert(order, k) end for _, k in __iter(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 = (type(meta.source) == "table" and{meta.source }or{{} })[1] if type(source.extra) == "table" then for _, x in __iter(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 __iter(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 = (type(source.sections) == "table" and #source.sections > 1 and{source.sections }or{{ {} } })[1] for si, sec in __iter(sections) do if #sections > 1 then table.insert(out, "DATA") local params = {} if sec.name ~= nil then params[1] = sec.name params[2] = (sec.schema ~= nil and{sec.schema }or{{} })[1] 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 __iter(ids) do local e= cad.entities[id] local esec = (type(e.section) == "number" and{e.section }or{1 })[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 __iter(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, id) if type(id) == "table" then id = id.ref end return cad.entities[id] end function Step.ids(cad) local out = {} for id in __iter(cad.entities) do table.insert(out, id) end table.sort(out) return out end function Step.byType(cad, name) local n = string.upper(name) local out = {} for id, e in __iter(cad.entities) do if e.type == n then table.insert(out, id) elseif e.parts then for _, p in __iter(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, name) if not e then return nil end if e.type == name then return e.args end if e.parts then for _, p in __iter(e.parts) do if p.type == name then return p.args end end end return nil end function Step.add(cad, type, args) local top = 0 for id in __iter(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, key) local mt= getmetatable(t) if not mt then mt = { __reals = {} } setmetatable(t, mt) end mt.__reals[key] = true return t end function Step.new(schema) return { kind = "cad", schema = schema or "AP214", header = {}, entities = {}, meta = { count = 0 } } end Step.plugin = Brep.plugin local function textOf(cad) local buf, err = Step.encode(cad) if not buf then return nil, err end return buffer.tostring(buf), nil end function Step.toBodies(cad, opts) 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, opts) 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, opts) 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() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict -- 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 = {} local function rgbOf(c) if c == nil then return nil, nil, nil end local ok, r, g, b = pcall(function() 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 ).R, (c ).G, (c ).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) 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 = (type(p.write) == "function" and{p.write }or{nil})[1], tessellate = (type(p.tessellate) == "function" and{p.tessellate }or{nil})[1], }, 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, opts) return SB.read(S.parse(text), opts) end, write = type(SW) == "table" and type(SW.write) == "function" and function(bodies, opts) local o = (type(opts) == "table" and{(table.clone(opts) )}or{{} })[1] if o.colors == nil then local colors = {} for i, b in __iter(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 or nil, tessellate = type(Tess) == "table" and type(Tess.body) == "function" and function(body, opts) return Tess.body(body, opts) end or 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) 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 ) end return plug, nil end function Brep.read(plug, text, opts) 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, bodies, opts) 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) 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 ).X, (p ).Y, (p ).Z end local function linear(c) c = math.clamp(c, 0, 1) return (c <= 0.04045 and((c / 12.92 ))or((((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, bodies, opts) 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 = (type(opts) == "table" and type(opts.tess) == "table" and{opts.tess }or{{ chord = (type(opts) == "table" and type(opts.chord) == "number" and{opts.chord }or{0.05 })[1]} })[1] local matByKey= {} local function material(r, g, b) local key = (r and{(string.format("%.6f,%.6f,%.6f", r, g , b ) )}or{"default" })[1] local m = matByKey[key] if m then return m end local mat = Types.Scene.material((r and(("step_" .. #scene.materials + 1 ))or("default"))) if r then mat.baseColor = { linear(r), linear(g ), linear(b ), 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 __iter(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() local P, N, I = mesh.positions, mesh.normals, mesh.indices local nv = #P local pos = Types.Scene.accessor(nil, "f32", 3, nv) local nrm = (type(N) == "table" and #N == nv and{(Types.Scene.accessor(nil, "f32", 3, nv) )}or{nil })[1] 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= {} local byMat= {} local faceOf = (type(mesh.faceOf) == "table" and{mesh.faceOf }or{{} })[1] local nt = math.floor(#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= {} for _, grp in __iter(groups) do local idx = Types.Scene.accessor(nil, "u32", 1, #grp.tris * 3) for k, t in __iter(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= { POSITION = pos } if nrm then attrs.NORMAL = nrm end table.insert(out, { attributes = attrs, indices = idx, mode = "triangles" , 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 = (type(body) == "table" and type(body.name) == "string" and{body.name }or{("body_" .. bi )})[1] 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"] = function() local __compat = __compat local type = __compat.type --!strict --!native -- 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 local function fail(ctx, msg, at) if not ctx.err then ctx.err, ctx.errAt = msg, at end return nil end local function skip(ctx, i) 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 =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 local function isAlpha(c) return (c >= 65 and c <= 90) or (c >= 97 and c <= 122) or c == 95 end local function isWord(c) return (c >= 65 and c <= 90) or (c >= 97 and c <= 122) or c == 95 or (c >= 48 and c <= 57) end local function keyword(ctx, i) local s, n = ctx.s, ctx.n local j = i if j <= n and sbyte(s, j) == 33 then -- '!' user-defined j =j+ 1 end if j > n or not isAlpha((sbyte(s, j) )) then return nil, i end j =j+ 1 while j <= n and isWord((sbyte(s, j) )) do j =j+ 1 end return string.upper(ssub(s, i, j - 1)), j end local function utf8char(cp) 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 local function hexAt(s, i, k) 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 function Parse.unescape(raw) 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 =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 =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) )) + 128) % 256)) i =i+ 4 elseif d == 80 and sbyte(raw, i + 3) == 92 then -- \P?\ code page i =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 =i+ 5 else table.insert(out, "\\") i =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 = sbyte(raw, i + 2) == 50 and 4 or 8 local j = i + 4 local hi= 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 =j+ k end if ssub(raw, j, j + 3) == "\\X0\\" then j =j+ 4 end i = j else table.insert(out, "\\") i =i+ 1 end plain = i else i =i+ 1 end end table.insert(out, ssub(raw, plain, n)) return table.concat(out) end local function markReal(t, key) local mt= getmetatable(t) if not mt then mt = { __reals = {} } setmetatable(t, mt) end mt.__reals[key] = true end local value local function list(ctx, i, depth) 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 =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 = function(ctx, i, depth) 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 ) local num = tonumber((c == 43 and{(ssub(tok, 2) )}or{tok})[1]) if num == nil then -- "1.E" without digits and the like local core = string.match(tok, "^[+-]?%d*%.?%d*") num = core and tonumber((c == 43 and{(ssub(core, 2) )}or{core})[1]) if num == nil then return fail(ctx, "bad number", i), i, false end e = i + #(core ) - 1 end local real = sfind(tok, "[.eE]") ~= nil local nv = num return nv, (e ) + 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 local function record(ctx, i) 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 local function expect(ctx, i, ch, what) 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 local function at(s, i, word) return ssub(s, i, i + #word - 1) == word end function Parse.parse(s, null, derived, maxEntities) local ctx= { s = s, n = #s, err = nil, errAt = nil, null = null, derived = derived } local res= { 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 i = e2 end elseif word == "DATA" then sawData = true local sec= {} 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)) ) local k = expect(ctx, idEnd + 1, 61, "=") if not k then return nil, ctx.err, ctx.errAt end k = skip(ctx, k) local ent 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 =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 =res.duplicates+ 1 else res.count =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= 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 =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"] = function() local __compat = __compat local type = __compat.type --!strict --!native -- 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 function Write.real(v) 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 =s.. "." end end return s end local HEX = "0123456789ABCDEF" local function hex(v, k) 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 function Write.str(s) if not sfind(s, "[^ -&(-[%]^-~]") then -- printable ASCII without ' and \ return "'" .. s .. "'" end local out = { "'" } local i, n = 1, #s local wide= nil -- 4 (\X2\) or 8 (\X4\) while in an extended run local function close() if wide then table.insert(out, "\\X0\\") wide = nil end end while i <= n do local c = (sbyte(s, i) ) 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 =i+ 1 else local cp= 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 =i+ 1 else local k = cp >= 0x10000 and 8 or 4 if wide ~= k then close() table.insert(out, k == 4 and"\\X2\\" or"\\X4\\") wide = k end table.insert(out, hex(cp, k)) i =i+ len end end end close() table.insert(out, "'") return table.concat(out) end local function isName(s) return type(s) == "string" and sfind(s, "^!?[%a_][%w_]*$") ~= nil end Write.isName = isName local value local function reals(t) local mt = getmetatable(t) return (type(mt) == "table" and type(mt.__reals) == "table" and{mt.__reals }or{nil })[1]end local function list(ctx, t, depth) 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 = function(ctx, v, real, depth) 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, v and".T." or".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 function Write.record(ctx, t, args) 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 __FILES["codecs/audio/Aac"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict -- 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= { [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 }, } local function rateIndex(rate) -- the nearest standard rate (ISO 14496-3 table 4.82 mapping for explicit frequencies) local best, bi = math.huge, 4 for i, r in __iter(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) local t = br:read(5) if t == 31 then t = 32 + br:read(6) end return t end local function frequency(br) 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) 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 =channels+ (br:read(1) == 1 and 2 or 1 ) br:read(4) end channels =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) 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= 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, aot == 1 and"AAC Main" or"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, sfIndex, channelConfig) 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 function Aac.adts(b, o, limit) 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 = protected and 9 or 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 local function decode(self, buf, offset, length) 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) for _, c in __iter(self.state.ch) do for i = 1, 1024 do c.overlap[i] = 0 end c.prevShape = 0 end end function Aac.decoder(asc) local cfg 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, } 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"] = function() local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict --!native --!optimize 2 -- 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.create(16) local BP = 0 local BL = 0 local OVER = false local function getBits(n) 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 local function peekBits(n) 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 local function getLong(n) if n > 24 then local hi = getBits(n - 16) return hi * 65536 + getBits(16) end return getBits(n) end local PEEK = 10 local function book(codes, bits) 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= {} for i = 1, 11 do SPEC_BOOK[i] = book(Tables.SPEC_CODES[i], Tables.SPEC_BITS[i]) end local function huff(bk) local e = bk.tab[peekBits(PEEK) + 1] if e > 0 then BP =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) ) local KBD_LONG = (Mdct.window("kbd", 2048, 4) ) local SINE_SHORT = (Mdct.window("sine", 256) ) local KBD_SHORT = (Mdct.window("kbd", 256, 6) ) local PLAN_LONG = (Mdct.new(2048) ) local PLAN_SHORT = (Mdct.new(256) ) local function newChannel() 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 local function icsInfo(st, c) 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]=gl[ng]+ 1 else ng =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 local function sectionData(c) local long = c.windowSequence ~= EIGHT_SHORT local bits = long and 5 or 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 =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 =k+ len if OVER then return "section data runs past the end" end end end return nil end local function scaleFactors(c, globalGain) 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 =is+ (d - 60 ) sf[i] = math.clamp(is, -155, 100) elseif cb == NOISE_HCB then if firstNoise then noise =noise+ (getBits(9) - 256 ) firstNoise = false else local d = huff(SF_BOOK) if d < 0 then return "bad scalefactor code" end noise =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 =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 local function tnsData(st, c) local short = c.windowSequence == EIGHT_SHORT local nw = short and 8 or 1 local filters = {} for w = 1, nw do local list = {} local nFilt = getBits(short and 1 or 2) if nFilt > 0 then local coefRes = getBits(1) for _ = 1, nFilt do local length = getBits(short and 4 or 6) local order = getBits(short and 3 or 5) local f = { length, order, 0 } if order > (short and 7 or 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 =v- 2 ^ nb end tmp[k] = math.sin(v / ((v >= 0 and{iq }or{iqm})[1])) 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 local function applyTns(st, c) local short = c.windowSequence == EIGHT_SHORT local swb = (short and{Tables.SWB_SHORT[st.sfIndex + 1] }or{Tables.SWB_LONG[st.sfIndex + 1] })[1] local numSwb = (short and{Tables.NUM_SWB_SHORT[st.sfIndex + 1] }or{Tables.NUM_SWB_LONG[st.sfIndex + 1] })[1] local maxBands = (short and{Tables.TNS_MAX_BANDS_SHORT[st.sfIndex + 1] }or{Tables.TNS_MAX_BANDS_LONG[st.sfIndex + 1] })[1] local mmm = math.min(maxBands, c.maxSfb) if mmm == 0 then return end local spec = c.spec for w, list in __iter(c.tnsFilters) do local bottom = numSwb for _, f in __iter(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 = (m < order and{m }or{order })[1] for i = 1, lim do y =y- spec[p - i * inc] * f[3 + i] end spec[p] = y p =p+ inc end end end end end end local function spectralData(st, c, pulses) local short = c.windowSequence == EIGHT_SHORT local swb = (short and{Tables.SWB_SHORT[st.sfIndex + 1] }or{Tables.SWB_LONG[st.sfIndex + 1] })[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 __DARKLUA_CONTINUE_26=false repeat 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 __DARKLUA_CONTINUE_26=true -- zeros (intensity bands are filled from the other channel later) break 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 = (r >= 2147483648 and((r - 4294967296 ))or(r )) spec[base + k] = v energy =energy+ v * v end st.random = r local m = (energy > 0 and((scale / sqrt(energy) ))or(0 )) for k = 1, width do do local __DARKLUA_VAR=base + k spec[__DARKLUA_VAR]=spec[__DARKLUA_VAR]* m end end end __DARKLUA_CONTINUE_26=true break 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, vals2, vals3, vals4 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 = (e == 1 and{vals1 }or{vals2 })[1] if v == 16 or v == -16 then local n = 0 while getBits(1) == 1 do n =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 =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 = (q < 0 and{(-q )}or{q })[1] local v = (POW43[aq + 1] or aq ^ (4 / 3)) * gain spec[base + k] = (q < 0 and{(-v )}or{v })[1] end end end end __DARKLUA_CONTINUE_26=true until true if not __DARKLUA_CONTINUE_26 then break end end win =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] = (q > 0 and((q + pulses[i + 1] ))or((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 = (q < 0 and{(-q )}or{q })[1] local v = (POW43[aq + 1] or aq ^ (4 / 3)) * gain spec[k] = (q < 0 and{(-v )}or{v })[1] end end end end end return nil end -- individual_channel_stream local function ics(st, c, commonWindow) 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= 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 =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 local function msStereo(st, l, r, mask) local short = l.windowSequence == EIGHT_SHORT local swb = (short and{Tables.SWB_SHORT[st.sfIndex + 1] }or{Tables.SWB_LONG[st.sfIndex + 1] })[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 =win+ glen end end local function intensity(st, l, r, mask, msPresent) local short = r.windowSequence == EIGHT_SHORT local swb = (short and{Tables.SWB_SHORT[st.sfIndex + 1] }or{Tables.SWB_LONG[st.sfIndex + 1] })[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 = cb == INTENSITY_HCB and 1 or-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 =win+ glen end end local function filterbank(st, c, out, stride, offset) 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 = (prev == 1 and{KBD_SHORT }or{SINE_SHORT })[1] local wcur = (shape == 1 and{KBD_SHORT }or{SINE_SHORT })[1] for w = 0, 7 do Mdct.inverse(PLAN_SHORT, spec, w * 128 + 1, 1, tmp, 1, 2 / 256) local rise = (w == 0 and{rise0 }or{wcur })[1] local base = 448 + w * 128 for n = 1, 128 do do local __DARKLUA_VAR=base + n frame[__DARKLUA_VAR]=frame[__DARKLUA_VAR]+ tmp[n] * rise[n] end do local __DARKLUA_VAR0=base + 128 + n frame[__DARKLUA_VAR0]=frame[__DARKLUA_VAR0]+ tmp[128 + n] * wcur[128 + n] end 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 = (prev == 1 and{KBD_SHORT }or{SINE_SHORT })[1] 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 = (prev == 1 and{KBD_LONG }or{SINE_LONG })[1] for n = 1, 1024 do frame[n] = t[n] * rise[n] end end if seq == LONG_START then local fall = (shape == 1 and{KBD_SHORT }or{SINE_SHORT })[1] 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 = (shape == 1 and{KBD_LONG }or{SINE_LONG })[1] 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 =p+ stride end c.prevShape = shape end function Decode.frame(st, buf, off, len) 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= {} 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 =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 =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 =count+ getBits(8) end if align == 1 then BP = math.floor((BP + 7) / 8 )* 8 end BP =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 =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 =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 __iter(order) do local o = (map and map[i] and{map[i] }or{i })[1] filterbank(st, c, pcm, n, o) end return n, nil end function Decode.state(sfIndex) 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() --!strict -- 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 __FILES["codecs/audio/Ac3"] = function() local __compat = __compat local buffer, bit32, type = __compat.buffer, __compat.bit32, __compat.type --!strict -- 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 } function Ac3.header(b, o, limit) 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 = (fs < 3 and{T.RATES[fs + 1] }or{0})[1], 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 =skip+ 2 end if bit32.band(acmod, 4) ~= 0 then skip =skip+ 2 end if acmod == 2 then skip =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 = (bsid > 8 and((bsid - 8 ))or(0 )) return { sampleRate = math.floor(T.RATES[fscod + 1] / 2 ^ shift), frameSize = words * 2, bitrate = math.floor(T.BITRATES[math.floor(frmsizecod / 2 )+ 1] * 1000 / 2 ^ shift), channels = NFCHANS[acmod] + (lfeon and 1 or 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 = (c >= 0x8000 and{(bit32.bxor(bit32.band(c * 2, 0xFFFF), 0x8005) )}or{(c * 2 )})[1] end CRC[i + 1] = c end function Ac3.crc(b, o, n) 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 function Ac3.decoder(opts) local o= 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 dec = { pcm = st.pcm, channels = 0, sampleRate = 0, blocks = st.blocks, decode = function(self, buf, offset, length) 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) Decode.reset(st) end, } return dec end return Ac3 end __FILES["codecs/audio/Ac3/Decode"] = function() local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict --!native --!optimize 2 -- 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. local function levels(n) 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) ) local PLAN512 = (Mdct.new(512) ) local PLAN256 = (Mdct.new(256) ) local B= buffer.create(0) local P = 0 local function bits(n) 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 =P+ n return v end local function arrays(n, size, v) local t = {} for i = 1, n do t[i] = table.create(size, v) end return t end function Decode.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 function Decode.reset(st) for _, d in __iter(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 local function exponents(e, absexp, ngrps, grpsize, first) local prev = absexp local k = first + 1 for _ = 1, ngrps do local g = bits(7) if g >= 125 then return false end local d1 = math.floor(g / 25 ) local d2 = math.floor((g % 25) / 5 ) local d3 = g % 5 for m = 1, 3 do local d = (m == 1 and{d1 }or{(m == 2 and{d2 }or{d3 })[1]})[1] prev =prev+ (d - 2 ) if prev < 0 or prev > 24 then return false end for _ = 1, grpsize do e[k] = prev k =k+ 1 end end end return true end local function logadd(a, b) local c = a - b local adr = min(rshift((c >= 0 and{c }or{(-c)})[1], 1), 255) return (c >= 0 and((a + LATAB[adr + 1] ))or((b + LATAB[adr + 1] )))end local function lowcomp(a, b0, b1, bin) 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 local function allocate(st, ch, start, stop, fgain, snroffset, isLfe) 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 =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 =j+ 1 while j < lastbin do v = logadd(v, psd[j + 1]) j =j+ 1 end bndpsd[k + 1] = v k =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 =x+ math.floor((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 =b+ offs[seg] local ba = bas[seg] local delta = (ba >= 4 and(((ba - 3) * 128 ))or(((ba - 4) * 128 ))) for _ = 1, lens[seg] do if b < 50 then do local __DARKLUA_VAR=b + 1 mask[__DARKLUA_VAR]=mask[__DARKLUA_VAR]+ delta end end b =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 = math.floor((psd[i + 1] - m) / 32 ) bap[i + 1] = BAPTAB[min(63, max(0, adr)) + 1] i =i+ 1 end j =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 local function dither(st) local s = (st.seed * 1664525 + 1013904223) % 4294967296 st.seed = s return (s / 2147483648 - 1) * 0.707 end local function mantissas(st, ch, start, stop, out, dith) 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 = (dith and{(dither(st) )}or{0 })[1] 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[math.floor(g / 9 )+ 1], Q1[math.floor((g % 9) / 3 )+ 1], Q1[g % 3 + 1] n1 = 3 end v = G1[4 - n1] 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[math.floor(g / 25 )+ 1], Q2[math.floor((g % 25) / 5 )+ 1], Q2[g % 5 + 1] n2 = 3 end v = G2[4 - n2] 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[math.floor(g / 11 )+ 1], Q4[g % 11 + 1] n4 = 2 end v = G4[3 - n4] 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 =m- 2 * half end v = m / half end out[bin + 1] = v * POW2[e[bin + 1] + 1] end end local function readDba(st, ch) 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) local function audblk(st, blk, limit) 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, acmod == 0 and 2 or 1 do if bits(1) == 1 then local v = bits(8) local x = rshift(v, 5) if x >= 4 then x =x- 8 end local g = 2 ^ (x + 1) * (32 + band(v, 31)) / 64 st.dynrng[i] = (st.drc == 1 and{g }or{(g ^ st.drc )})[1] 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 = (acmod == 2 and{(bits(1) == 1 )}or{false })[1] 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 = (ex == 15 and((mant / 16 ))or(((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 = (not cplinu or cplbegf > 2 )and 4 or(cplbegf > 0 and 3 or 2 ) for r = 1, 4 do st.rematflg[r] = (r <= n and{(bits(1) == 1 )}or{false })[1] end elseif blk == 0 then for r = 1, 4 do st.rematflg[r] = false end end end local chexpstr = st.chexpstr chexpstr[CPL] = (cplinu and{(bits(2) )}or{0 })[1] for ch = 1, nf do chexpstr[ch] = bits(2) end chexpstr[LFE] = (st.lfeon and{(bits(1) )}or{0 })[1] 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, math.floor((cplend - cplstrt) / grp), math.floor(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 = math.floor((endmant[ch] - 1) / 3 ) elseif s == 2 then ngrps = math.floor((endmant[ch] - 1 + 3) / 6 ) else ngrps = math.floor((endmant[ch] - 1 + 9) / 12 ) end local e = st.exp[ch] e[1] = bits(4) if not exponents(e, e[1], ngrps, math.floor(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 __iter({ 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 =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 local function alloc(ch, start, stop, isLfe) 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 = (dith and((dither(st) * POW2[cexp[k] + 1] ))or(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 = (cplinu and{cplstrt }or{(min(endmant[1], endmant[2]) )})[1] 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 local function synth(st, ch, short, gain, out, base, step) 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 =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= { [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 } function Decode.frame(st, buf, len, drc) 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 .. (bsid > 10 and" (E-AC-3)" or" (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, acmod == 0 and 2 or 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 =P+ (bits(6) + 1) * 8 end local nf = NFCHANS[acmod] local channels = nf + (lfeon and 1 or 0) if st.acmod ~= acmod or st.lfeon ~= lfeon then local order = ORDER[acmod] local map = table.create(6, 0) local nfront = HAS_C[acmod] and 3 or(acmod == 1 and 1 or 2 ) for ch = 1, nf do local o = order[ch] map[ch] = (lfeon and o > nfront and((o + 1 ))or(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[acmod == 0 and ch == 2 and 2 or 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() --!strict -- 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, frmsizecod) local kbps = T.BITRATES[math.floor(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 math.floor(kbps * 1536000 / 705600 )+ frmsizecod % 2 end return T end __FILES["codecs/audio/Adpcm"] = function() local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict --!native --!optimize 2 -- 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 =d+ rshift(step, 2) end if band(n, 2) ~= 0 then d =d+ rshift(step, 1) end if band(n, 4) ~= 0 then d =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 function Adpcm.ima(src, p, q0, qs, count, hi, st, so, dst, d, ds) 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 =pred- diff if pred < -32768 then pred = -32768 end else pred =pred+ diff if pred > 32767 then pred = 32767 end end index = IMA_NEXT[index * 16 + nib + 1] writef32(dst, o, pred / 32768) o =o+ os q =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) function Adpcm.imaQt(src, p, st, so, dst, d, ds) local h = readu8(src, p) * 256 + readu8(src, p + 1) local pred = band(h, 0xFF80) if pred >= 32768 then pred =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 function Adpcm.imaWav(src, off, avail, ch, spb, dst, d) if avail < 4 * ch then return 0 end local groups = math.floor((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 = (band(k, 1) == 0 and{(band(b, 15) )}or{(rshift(b, 4) )})[1] local diff = IMA_DIFF[index * 8 + band(nib, 7) + 1] if nib >= 8 then pred =pred- diff if pred < -32768 then pred = -32768 end else pred =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 =f+ 1 k =k+ 1 end g =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 function Adpcm.msBlock(src, off, avail, ch, spb, dst, d, coefs, ncoef, state) local hdr = 7 * ch if avail < hdr or ncoef < 1 then return 0 end local frames = math.min(spb, 2 + math.floor(((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 = (band(k, 1) == 0 and{(rshift(b, 4) )}or{(band(b, 15) )})[1] 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 = (p >= 0 and{(math.floor(p / 256 ))}or{(-(math.floor((-p) / 256)) )})[1] p =p+ ((nib >= 8 and((nib - 16 ))or(nib))) * idelta if p > 32767 then p = 32767 elseif p < -32768 then p = -32768 end idelta = math.floor((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) local function f32(x) 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 function Adpcm.adxCoefs(cutoff, rate) 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 = (c1 >= 0 and{(floor(c1) )}or{(-floor(-c1) )})[1] c2 = (c2 >= 0 and{(floor(c2) )}or{(-floor(-c2) )})[1] 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 function Adpcm.adx(src, p, pstride, nframes, c1, c2, v3, st, so, dst, d, ds) 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 =scale- 65535 -- the signed value + 1 else scale =scale+ 1 end for k = 0, 31 do local b = readu8(src, fp + 2 + rshift(k, 1)) local n = (band(k, 1) == 0 and{(rshift(b, 4) )}or{(band(b, 15) )})[1] if n >= 8 then n =n- 16 end local s if v3 then s = n * scale + math.floor((c1 * h1) / 4096 )+ math.floor((c2 * h2) / 4096 ) else s = n * scale + math.floor((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 =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 local function psxPred(f, h1, h2) 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 (v >= 0 and{(floor(v) )}or{(-floor(-v) )})[1]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 function Adpcm.psx(src, p, pstride, nframes, st, so, dst, d, ds) 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 = (band(k, 1) == 0 and{(band(b, 15) )}or{(rshift(b, 4) )})[1] if n >= 8 then n =n- 16 end s = math.floor((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 =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 function Adpcm.dsp(src, p, count, coefs, co, st, so, dst, d, ds) 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 = (band(k, 1) == 0 and{(rshift(b, 4) )}or{(band(b, 15) )})[1] if n >= 8 then n =n- 16 end local s = math.floor((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 =o+ os end done =done+ n14 fp =fp+ 8 end writei32(st, so, h1) writei32(st, so + 4, h2) end local function toS16(x) 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 local function imaNibble(x, pred, index) 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 function Adpcm.imaEncode(x, xi, xs, count, st, so, out, p, q0, qs, hi) 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 = (nib >= 8 and{(math.max(pred - diff, -32768) )}or{(math.min(pred + diff, 32767) )})[1] 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 =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 function Adpcm.imaWavEncode(x, xf, n, ch, spb, st, out, off) local groups = math.floor((spb - 1) / 8 ) for c = 0, ch - 1 do local so = c * 8 local first = (n > 0 and{(toS16(readf32(x, (xf * ch + c) * 4)) )}or{0 })[1] 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 = (f < n and{(toS16(readf32(x, ((xf + f) * ch + c) * 4)) )}or{pred })[1] local nib = imaNibble(v, pred, index) local diff = IMA_DIFF[index * 8 + band(nib, 7) + 1] pred = (nib >= 8 and{(math.max(pred - diff, -32768) )}or{(math.min(pred + diff, 32767) )})[1] 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 local function msTrial(xs, n, c1, c2, delta0, nibs) 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 = (p >= 0 and{(math.floor(p / 256 ))}or{(-(math.floor((-p) / 256)) )})[1] local e = xs[i] - p local nib = (e >= 0 and{(math.floor((e + math.floor(idelta / 2)) / idelta ))}or{(-(math.floor((-e + math.floor(idelta / 2)) / idelta)) )})[1] nib = math.clamp(nib, -8, 7) local v = math.clamp(p + nib * idelta, -32768, 32767) err =err+ (xs[i] - v) * (xs[i] - v) if nibs then nibs[i] = band(nib, 15) end idelta = math.clamp(math.floor((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 function Adpcm.msEncode(x, xf, n, ch, spb, out, off) 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] = (i <= n and{(toS16(readf32(x, ((xf + i - 1) * ch + c) * 4)) )}or{0 })[1] end local sum = 0 for i = 3, math.min(spb, 10) do sum =sum+ math.abs(xs[i] - xs[i - 1]) end local delta0 = math.clamp(math.floor(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 + math.floor(k / 2), all[k + 1] * 16 + (all[k + 2] or 0)) end end local function adxTrial(xs, scale, c1, c2, h1, h2, nibs) local err = 0 for k = 1, 32 do local pred = math.floor((c1 * h1 + c2 * h2) / 4096 ) local e = xs[k] - pred local n = (e >= 0 and{(math.floor((e + math.floor(scale / 2)) / scale ))}or{(-(math.floor((-e + math.floor(scale / 2)) / scale)) )})[1] n = math.clamp(n, -8, 7) local s = math.clamp(n * scale + pred, -32768, 32767) err =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 function Adpcm.adxEncode(x, xi, xs, count, c1, c2, st, so, out, p, pstride) 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, math.floor((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 = (i < count and{(toS16(readf32(x, (xi + i * xs) * 4)) )}or{0 })[1] v[k] = s peak = math.max(peak, math.abs(s - math.floor((c1 * a + c2 * b) / 4096))) b = a a = s end local base = math.max(1, math.floor((peak + 6) / 7)) local best, bestErr = base, math.huge for _, m in __iter({ 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 function Adpcm.psxEncode(x, xi, xs, count, st, so, out, p, pstride) 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, math.floor((count + 27) / 28 )- 1 do for k = 1, 28 do local i = f * 28 + k - 1 v[k] = (i < count and{(toS16(readf32(x, (xi + i * xs) * 4)) )}or{0 })[1] 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 = n > 7 and 7 or(n < -8 and-8 or n ) local s = math.floor((n * mul + pred) / 256 ) local c = s > 32767 and 32767 or(s < -32768 and-32768 or s ) err =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 = math.floor((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 function Adpcm.modplug(src, p, count, dst, d) 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 = (band(i, 1) == 0 and{(band(b, 15) )}or{(rshift(b, 4) )})[1] 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= { { -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 }, } function Adpcm.swfFrames(src, p, n, ch) 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 = math.floor(total / block ) local left = total - blocks * block local frames = blocks * 4096 if left >= hdr then frames =frames+ (1 + math.floor((left - hdr) / (bits * ch) )) end return frames end local function msb(src, p, e, pos, k) local q = p + rshift(pos, 3) local v = readu8(src, q) * 65536 if q + 1 < e then v =v+ readu8(src, q + 1) * 256 end if q + 2 < e then v =v+ readu8(src, q + 2) end return band(rshift(v, 24 - band(pos, 7) - k), lshift(1, k) - 1) end function Adpcm.swf(src, p, n, ch, dst, d) 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 =v- 65536 end pred[c] = v index[c] = msb(src, p, e, pos + 16, 6) pos =pos+ 22 writef32(dst, o, v / 32768) o =o+ 4 end done =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 =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 =diff+ step end step = rshift(step, 1) k = rshift(k, 1) end diff =diff+ step local v = pred[c] if band(code, sign) ~= 0 then v =v- diff else v =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 =o+ 4 end end done =done+ m end return frames end return Adpcm end __FILES["codecs/audio/Adpcm/Decoder"] = function() local __compat = __compat local buffer = __compat.buffer --!strict -- 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 = {} function Decoder.packets(dec, spec) 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= {} local nextPacket = 1 local function snap(i) 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) 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 =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) return (i - 1) * pf end, decode = decode, pcm = function() return out end, reset = function() end, stop = spec.frames, }) end local FRAME= { psx = 16, adx = 18, dsp = 8, s16be = 2, s16le = 2, s8 = 1 } -- bytes per frame local SPF= { psx = 28, adx = 32, dsp = 14, s16be = 1, s16le = 1, s8 = 1 } -- samples per frame local function pcm(kind, src, p, n, dst, d, ds) 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, ((v >= 32768 and((v - 65536 ))or(v))) / 32768) end end end function Decoder.interleaved(dec, spec) 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) local width = (r == rows - 1 and{last }or{il })[1] -- 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 (math.floor(per / fsize)) * spf end local fullFrames = (math.floor(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 = spec.restore and 1 or math.max(1, math.floor(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 = restore and function(i) return restore(i - 1, st) end or nil, decode = function(i, out) 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 = (r == rows - 1 and{last }or{il })[1] 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 , c * 64, st, c * 8, out, d, ch) else pcm(kind, buf, p, n, out, d, ch) end end got =got+ n end return got, nil end, }) end -- IMA from predictor 0, step index 0; channel c in nibbles c, c + ch, ... function Decoder.nibbles(dec, spec) local ch = dec.channels local buf, base = spec.buf, spec.offset local frames = math.min(spec.frames or math.huge, math.floor((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, out) 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 function Decoder.blockFrames(kind, ba, ch) if kind == "ima_qt" then return 64 elseif kind == "ms" then return (ba >= 7 * ch and((math.floor((ba - 7 * ch) * 2 / ch )+ 2 ))or(nil )) end return (ba >= 4 * ch and((math.floor((ba - 4 * ch) * 2 / ch )+ 1 ))or(nil ))end function Decoder.blocks(dec, spec) local ch = dec.channels local kind = spec.kind local ba = (kind == "ima_qt" and((34 * ch ))or(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 = math.floor(size / ba ) local rest = size - full * ba local total = full * spb if kind ~= "ima_qt" and rest > 0 then if kind == "ms" then total =total+ (rest >= 7 * ch and{(math.min(spb, 2 + math.floor(((rest - 7 * ch) * 2) / ch)) )}or{0 })[1] elseif rest >= 4 * ch then total =total+ math.min(spb, 1 + (math.floor((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, math.floor(#cf / 2)) end local coefs = buffer.create(ncoef * 8) for k = 0, ncoef - 1 do buffer.writei32(coefs, k * 8, (cf and #cf >= 2 and{cf[k * 2 + 1] }or{Adpcm.MS_COEF1[k + 1]})[1]) buffer.writei32(coefs, k * 8 + 4, (cf and #cf >= 2 and{cf[k * 2 + 2] }or{Adpcm.MS_COEF2[k + 1]})[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, out) 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() local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict -- 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 = {} local TO_WAV= { { 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= { { 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, offset, length) 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= { 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) 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 local function decode(self, buf, offset, length) 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) return { config = cfg, pcm = table.create(cfg.frameLength * cfg.channels, 0), decode = decode, state = Decode.state(cfg), } end local function encode(self, samples, first, frames) 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 =self.bytes+ n self.frames =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 function Alac.encoder(opts) 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= { 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"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 -- 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 = {} local POW = table.create(64, 0) for i = 0, 63 do POW[i + 1] = 2 ^ i end local function bitsAt(b, pos, n) local w = byteswap(readu32(b, rshift(pos, 3))) return rshift(lshift(w, band(pos, 7)), 32 - n) end local function signExtend(v, bits) local m = POW[bits + 1] v = v % m if v >= m / 2 then v =v- m end return v end -- the adaptive Golomb-Rice value: unary prefix (escape after 9 ones: `bps` raw bits), then k bits local function scalar(b, pos, k, m, bps) local w = lshift(byteswap(readu32(b, rshift(pos, 3))), band(pos, 7)) local pre = countlz(bnot(w)) if pre >= 9 then pos =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 =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 local function rice(b, pos, limit, out, n, bps, mult, st) 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 =x+ signMod signMod = 0 out[i] = (x % 2 == 0 and((x / 2 ))or((-(x + 1) / 2 ))) if x > 0xFFFF then history = 0xFFFF else history =history+ (x * mult - floor(history * mult / 512) ) end if history < 128 and i < n then if pos > limit then return -1 end local lg = (history > 0 and((31 - countlz(history) ))or(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 =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 =i+ 1 end return pos end local function predict(err, out, n, bps, coefs, order, quant) 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 =i+ 1 end local half = (quant > 0 and{POW[quant] }or{0 })[1] 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 =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 = e > 0 and 1 or-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 = (v > 0 and{es }or{(v < 0 and{(-es )}or{0 })[1]})[1] coefs[j]=coefs[j]- sgn e =e- floor(v * sgn / qd) * (order - j + 1) end end i =i+ 1 end end function Decode.frame(st, buf, off, len) 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 =pos+ 3 if tag == 7 then -- END break elseif tag == 0 or tag == 1 or tag == 3 then -- SCE / CPE / LFE local nch = tag == 1 and 2 or 1 if ch + nch > channels then return nil, "more channels than the configuration" end pos =pos+ 4 -- element instance tag if bitsAt(b, pos, 12) ~= 0 then return nil, "bad element header" end pos =pos+ 12 local h = bitsAt(b, pos, 4) pos =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 =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 =pos+ 16 if mixRes >= 128 then mixRes =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 =pos+ 16 mode[c], denShift[c] = rshift(x, 4), (band(x, 15) ) pbFactor[c], order[c] = rshift(y, 5), (band(y, 31) ) 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 =pos+ 16 coefs[c][j] = (v >= 32768 and((v - 65536 ))or(v )) end end if pos > limit then return nil, "frame runs past the end" end local shiftPos = pos if shift > 0 then pos =pos+ shift * n * nch end for c = 1, nch do local p = (c == 1 and{p0 }or{p1 })[1] local mb = (c == 1 and{m0 }or{m1 })[1] 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 =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 =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 =ch+ nch elseif tag == 4 then -- DSE pos =pos+ 4 local align = bitsAt(b, pos, 1) local count = bitsAt(b, pos + 1, 8) pos =pos+ 9 if count == 255 then count =count+ bitsAt(b, pos, 8) pos =pos+ 8 end if align == 1 then pos = math.floor((pos + 7) / 8 )* 8 end pos =pos+ count * 8 elseif tag == 6 then -- FIL local count = bitsAt(b, pos, 4) pos =pos+ 4 if count == 15 then count =count+ (bitsAt(b, pos, 8) - 1 ) pos =pos+ 8 end pos =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 function Decode.state(cfg) 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"] = function() local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict --!native --!optimize 2 -- 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 local function put(st, v, n) 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 = (n < free and{n }or{free })[1] local bits = band(rshift(v, n - take), POW[take + 1] - 1) writeu8(b, byte, bor(readu8(b, byte), lshift(bits, free - take))) pos =pos+ take n =n- take end st.pos = pos end local function putBig(st, v, n) 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 local function signExtend(v, bits) local m = POW[bits + 1] v = v % m if v >= m / 2 then v =v- m end return v end local function scalarBits(x, k, m, bps) local pre = (k == 1 and{x }or{(floor(x / m) )})[1] if pre >= 9 then return 9 + bps end if k == 1 then return pre + 1 end local r = x - pre * m return pre + 1 + ((r == 0 and((k - 1 ))or(k))) end local function scalar(st, x, k, m, bps) local pre = (k == 1 and{x }or{(floor(x / m) )})[1] 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 local function rice(st, e, n, bps, mult, write) 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 = (v >= 0 and((2 * v ))or((-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 =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 =history+ (zz * mult - floor(history * mult / 512) ) end if history < 128 and i < n then local lg = (history > 0 and((31 - countlz(history) ))or(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 =run+ 1 end m = POW[k + 1] - 1 if write then scalar(st, run, k, m, 16) else bits =bits+ scalarBits(run, k, m, 16) end i =i+ run if run < 0xFFFF then signMod = 1 end history = 0 end i =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) local function residuals(x, e, n, bps, coefs, order, quant) 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 =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 =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 = r > 0 and 1 or-1 for j = order, 1, -1 do if r * es <= 0 then break end local v = d - x[i - j] local sgn = (v > 0 and{es }or{(v < 0 and{(-es )}or{0 })[1]})[1] coefs[j]=coefs[j]- sgn r =r- floor(v * sgn / qd) * (order - j + 1) end end i =i+ 1 end end local function lpc(x, n, order, work) 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 =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]=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 =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 =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 local function analyse(st, x, n, bps) local mult = floor(st.pb * PB_FACTOR / 4) local bestOrder, bestCoefs, bestBits = 0, {}, math.huge for _, order in __iter({ 4, 8 }) do local __DARKLUA_CONTINUE_17=false repeat if order >= n then __DARKLUA_CONTINUE_17=true break 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 __DARKLUA_CONTINUE_17=true until true if not __DARKLUA_CONTINUE_17 then break 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 function Encode.frame(st, samples, first, frames, map, elements) 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 = math.floor((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 __iter(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 =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, nch == 2 and 1 or 0, 3) put(st, 0, 4) put(st, 0, 12) put(st, partial and 1 or 0, 1) put(st, 0, 2) put(st, 0, 1) if partial then putBig(st, n, 32) end put(st, mixRes == 0 and 0 or 2, 8) put(st, mixRes, 8) local orders, coefsList = {}, {} for c = 1, nch do local x = (c == 1 and{u }or{v })[1] 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 = (c == 1 and{u }or{v })[1] 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 =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 __iter(elements) do put(st, nch == 2 and 1 or 0, 3) put(st, 0, 4) put(st, 0, 12) put(st, partial and 1 or 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 =ch+ nch end end put(st, 7, 3) -- END local bytes = math.floor((st.pos + 7) / 8 ) local pkt = buffer.create(bytes) buffer.copy(pkt, 0, st.out, 0, bytes) return pkt end function Encode.state(cfg) 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() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict -- 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 = {} local FLAG_8, FLAG_24, FLAG_PEAK, FLAG_SEEKN, FLAG_WAVHDR, FLAG_FLOAT = 1, 8, 4, 16, 32, 4096 function Ape.find(buf, base, limit) 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 =at+ (size + (footer and 20 or 10) ) if not footer then while at < limit and buffer.readu8(buf, at) == 0 do at =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 (k and((at + k - 1 ))or(nil ))end function Ape.info(buf, base, limit) 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= { 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 = math.floor(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 = (any and{(table.concat(hex) )}or{nil })[1] 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 = bit32.band(info.flags, FLAG_8) ~= 0 and 8 or(bit32.band(info.flags, FLAG_24) ~= 0 and 24 or 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 =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 , nil end local function frame(self, buf, i) 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 = ((i < info.totalFrames and{info.frameStart[i + 1] }or{info.dataEnd})[1]) + 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 = (i < info.totalFrames and{info.blocksPerFrame }or{info.finalFrameBlocks })[1] 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) 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"] = function() local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict --!native --!optimize 2 -- 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= {} local function overflowTable(rt) 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 =o+ 1 end writeu8(t, z, o) end OVT[rt[2] ] = t return t end local function wrap32(v) if v >= TWO31 or v < -TWO31 then return (v + TWO31) % TWO32 - TWO31 end return v end -- C integer division by 2 (toward zero) local function half(v) return (v >= 0 and{(math.floor(v / 2 ))}or{(-(math.floor((-v) / 2)) )})[1]end local FILTERS= { -- 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 }, } function Decode.state(version, level, bits, channels) local spec = FILTERS[level] if not spec then return nil, "unsupported: compression level " .. level end local filters= {} for k = 1, #spec, 2 do local order = spec[k] local es = bits >= 32 and 4 or 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) local function rcBits(rc, S, nb) local q, low, range, prev = rc.q, rc.low, rc.range, rc.prev while range <= 8388608 do local byte = readu8(S, q) q =q+ 1 low = low * 256 + bor(lshift(band(prev, 1), 7), rshift(byte, 1)) prev = byte range =range* 256 end range = math.floor(range / 2 ^ nb ) local r = 0 if range > 0 then r = math.floor(low / range ) low =low% range end rc.q, rc.low, rc.range, rc.prev = q, low, range, prev return r end local function values(st, q, lim, n, order, old) 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 =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((old and{RT1 }or{RT2})[1]) local RT = (old and{RT1 }or{RT2 })[1] 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 =q+ 1 low = low * 256 + bor(lshift(band(prev, 1), 7), rshift(byte, 1)) prev = byte range =range* 256 end range = math.floor(range / 65536 ) local total = math.floor(low / range ) if total >= 65536 then return nil, "bad range code" end local ov = readu8(ovt, total) low =low- range * RT[ov + 1] range =range* (RT[ov + 2] - RT[ov + 1] ) if not old then local pivot = math.max(math.floor(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 =q+ 1 low = low * 256 + bor(lshift(band(prev, 1), 7), rshift(byte, 1)) prev = byte range =range* 256 end range = math.floor(range / 65536 ) if range == 0 then return nil, "bad range code" end r = r * 65536 + math.floor(low / range ) low =low% range end ov = r if ov == 1 then pivot = 32768 while range <= 8388608 do local byte = readu8(S, q) q =q+ 1 low = low * 256 + bor(lshift(band(prev, 1), 7), rshift(byte, 1)) prev = byte range =range* 256 end range = math.floor(range / 65536 ) total = math.floor(low / range ) if total >= 65536 then return nil, "bad range code" end ov = readu8(ovt, total) low =low- range * RT[ov + 1] range =range* (RT[ov + 2] - RT[ov + 1] ) else break end end local base if pivot >= 65536 then local pbits = 0 while math.floor(pivot / 2 ^ pbits )> 0 do pbits =pbits+ 1 end local split = 2 ^ ((pbits >= 16 and((pbits - 16 ))or(0))) local pa = math.floor(pivot / split )+ 1 while range <= 8388608 do local byte = readu8(S, q) q =q+ 1 low = low * 256 + bor(lshift(band(prev, 1), 7), rshift(byte, 1)) prev = byte range =range* 256 end range = math.floor(range / pa ) local ba = math.floor(low / range ) low =low% range while range <= 8388608 do local byte = readu8(S, q) q =q+ 1 low = low * 256 + bor(lshift(band(prev, 1), 7), rshift(byte, 1)) prev = byte range =range* 256 end range = math.floor(range / split ) local bb = math.floor(low / range ) low =low% range base = ba * split + bb else while range <= 8388608 do local byte = readu8(S, q) q =q+ 1 low = low * 256 + bor(lshift(band(prev, 1), 7), rshift(byte, 1)) prev = byte range =range* 256 end range = math.floor(range / pivot ) base = math.floor(low / range ) low =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 =value+ ov * 2 ^ k q = rc.q low = rc.low range = rc.range prev = rc.prev end ks = (ks + math.floor((value + 1) / 2 )- math.floor((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] = (value % 2 == 1 and((math.floor((value - 1) / 2 )+ 1 ))or((-(math.floor(value / 2)) ))) end end return q, nil end -- ((v >> s) & m) ~= 0 for an int64 v (s given as 2^s) local function negBit(v, p2, m) return band((math.floor(v / p2)) % TWO32, m) ~= 0 end local function dot16(M, I, b, span) local dot = 0 for k = 0, span - 16, 16 do local bb = b + k dot =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) local function dotAdapt16(M, I, D, b, span, dm) 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 =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 local function nnFilter(f, v, n, newDelta, wide) local order, M, I, D = f.order, f.M, f.I, f.D local es = wide and 4 or 2 local shift = 2 ^ f.shift local round = math.floor(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 =dot+ pr if dm ~= 0 then writei32(M, k, m + readi32(D, b + k) * dm) end end else local b = (p - order) * 2 dot = (dm == 0 and{(dot16(M, I, b, span) )}or{(dotAdapt16(M, I, D, b, span, dm) )})[1] dot = wrap32(dot) end local o = x + math.floor((dot + round) / shift ) if not wide then o = wrap32(o) end local d = 0 local a = (o < 0 and{(-o )}or{o })[1] if newDelta then if a > avg * 3 then d = ((wide and{(negBit(o, 33554432, 64) )}or{(o < 0)})[1]) and 32 or-32 elseif a > math.floor((avg * 4) / 3 )then d = ((wide and{(negBit(o, 67108864, 32) )}or{(o < 0)})[1]) and 16 or-16 elseif a > 0 then d = ((wide and{(negBit(o, 134217728, 16) )}or{(o < 0)})[1]) and 8 or-8 end local dd = a - avg avg =avg+ (dd >= 0 and{(math.floor(dd / 16 ))}or{(-(math.floor((-dd) / 16)) )})[1] else d = o == 0 and 0 or(o < 0 and 4 or-4 ) end local sat = o > 32767 and 32767 or(o < -32768 and-32768 or o ) if wide then local q = p * 4 writei32(D, q, d) if newDelta then writei32(D, q - 4, math.floor(readi32(D, q - 4) / 2)) writei32(D, q - 8, math.floor(readi32(D, q - 8) / 2)) else writei32(D, q - 16, math.floor(readi32(D, q - 16) / 2)) end writei32(D, q - 32, math.floor(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, math.floor(readi16(D, q - 2) / 2)) writei16(D, q - 4, math.floor(readi16(D, q - 4) / 2)) else writei16(D, q - 8, math.floor(readi16(D, q - 8) / 2)) end writei16(D, q - 16, math.floor(readi16(D, q - 16) / 2)) writei16(I, q, sat) end v[t] = o p =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 local function adaptWide(v) if v == 0 then return 0 end return (math.floor(v / 1073741824)) % 4 >= 2 and 1 or-1 end -- CPredictorDecompress3950toCurrent, single-channel form local function predictOne(st, v, n) 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 + math.floor(predA / 1024 ) else cur = wrap32(nA + math.floor(wrap32(predA) / 1024)) end local s = sign(nA) if s ~= 0 then if wide then s = -s MA0 =MA0+ adaptWide(A0) * s MA1 =MA1+ adaptWide(A1) * s MA2 =MA2+ adaptWide(A2) * s MA3 =MA3+ adaptWide(A3) * s else MA0 =MA0+ sign(A0) * s MA1 =MA1+ sign(A1) * s MA2 =MA2+ sign(A2) * s MA3 =MA3+ sign(A3) * s end end stage = wrap32(cur + math.floor((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] local function predictStereo(st, X, Y, n) 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 - math.floor((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 + math.floor((predA + math.floor(predB / 2)) / 1024 ) else cur = wrap32(nA + math.floor(wrap32(wrap32(predA) + math.floor(wrap32(predB) / 2)) / 1024)) end local s = sign(nA) if s ~= 0 then if wide then s = -s yMA0 =yMA0+ adaptWide(A0) * s yMA1 =yMA1+ adaptWide(yA1) * s yMA2 =yMA2+ adaptWide(yA2) * s yMA3 =yMA3+ adaptWide(yA3) * s yMB0 =yMB0+ adaptWide(B0) * s yMB1 =yMB1+ adaptWide(yB1) * s yMB2 =yMB2+ adaptWide(yB2) * s yMB3 =yMB3+ adaptWide(yB3) * s yMB4 =yMB4+ adaptWide(yB4) * s else yMA0 =yMA0+ sign(A0) * s yMA1 =yMA1+ sign(yA1) * s yMA2 =yMA2+ sign(yA2) * s yMA3 =yMA3+ sign(yA3) * s yMB0 =yMB0+ sign(B0) * s yMB1 =yMB1+ sign(yB1) * s yMB2 =yMB2+ sign(yB2) * s yMB3 =yMB3+ sign(yB3) * s yMB4 =yMB4+ sign(yB4) * s end end yStage = wrap32(cur + math.floor((yStage * 31) / 32)) yLast = cur local yv = yStage nA = X[t] A0 = xLast xA3 = xA2 xA2 = xA1 xA1 = A0 - xPrev xPrev = A0 B0 = yv - math.floor((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 + math.floor((predA + math.floor(predB / 2)) / 1024 ) else cur = wrap32(nA + math.floor(wrap32(wrap32(predA) + math.floor(wrap32(predB) / 2)) / 1024)) end s = sign(nA) if s ~= 0 then if wide then s = -s xMA0 =xMA0+ adaptWide(A0) * s xMA1 =xMA1+ adaptWide(xA1) * s xMA2 =xMA2+ adaptWide(xA2) * s xMA3 =xMA3+ adaptWide(xA3) * s xMB0 =xMB0+ adaptWide(B0) * s xMB1 =xMB1+ adaptWide(xB1) * s xMB2 =xMB2+ adaptWide(xB2) * s xMB3 =xMB3+ adaptWide(xB3) * s xMB4 =xMB4+ adaptWide(xB4) * s else xMA0 =xMA0+ sign(A0) * s xMA1 =xMA1+ sign(xA1) * s xMA2 =xMA2+ sign(xA2) * s xMA3 =xMA3+ sign(xA3) * s xMB0 =xMB0+ sign(B0) * s xMB1 =xMB1+ sign(xB1) * s xMB2 =xMB2+ sign(xB2) * s xMB3 =xMB3+ sign(xB3) * s xMB4 =xMB4+ sign(xB4) * s end end xStage = wrap32(cur + math.floor((xStage * 31) / 32)) xLast = cur lastX = xStage X[t], Y[t] = xStage, yv end end function Decode.frame(st, buf, at, rem, stop, n, P, float, cut) local C, bits = st.channels, st.bits local len = math.max(0, stop - at) local words = math.floor((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 local function u32be(q) 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 =q+ 4 local special = 0 if st.version > 3820 then if stored >= TWO31 then special = u32be(q) q =q+ 4 end stored =stored% TWO31 end local V = st.V local order 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, cut and"truncated frame" or"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 __iter(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 __iter(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 = math.floor(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= {} 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, b2= 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 = (pair or (C == 2) )and 2 or 1 for k = 0, width - 1 do local s= (k == 0 and{a }or{b2 })[1] if bits == 16 then if s < -32768 or s > 32767 then return nil, "sample out of range" end writei16(cb, o, s) o =o+ 2 elseif bits == 8 then s = (s + 128) % 256 - 128 writeu8(cb, o, s + 128) o =o+ 1 elseif bits == 24 then s = (s + 8388608) % 16777216 - 8388608 local u = s % 16777216 writeu16(cb, o, u % 65536) writeu8(cb, o + 2, math.floor(u / 65536)) o =o+ 3 else s = wrap32(s) writei32(cb, o, s) o =o+ 4 end P[base + c + k + 1] = s end c =c+ width end end local crc = Crc32.of(cb, 0, o) if math.floor(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() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict -- 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 = {} local TO_TAG= { year = "date", ["album artist"] = "albumartist", albumartist = "albumartist", tracknumber = "track", discnumber = "disc", description = "comment", } local KINDS = { [0] = "text", "binary", "link", "text" } function ApeTag.tagKey(key) local k = string.lower(key) return TO_TAG[k] or k end function ApeTag.parse(buf, footer, start) 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= {} local items= {} 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 =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 = (version >= 2000 and{KINDS[bit32.band(bit32.rshift(iflags, 1), 3)] }or{"text" })[1] 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] = (old and((old .. "; " .. s ))or(s )) end p = v0 + len end return tags, { start = first, stop = footer + 32, version = version, items = items } end function ApeTag.find(buf, start, limit) 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/Flac"] = function() --!strict -- 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"] = function() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict --!native --!optimize 2 -- 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 local function crc8(b, o, n) return Frame.crc8(b, o, o + n) end local function crc16(b, o, n) return Frame.crc16(b, o, o + n) end Encode.crc8, Encode.crc16 = crc8, crc16 local function ensure(w, n) 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 local function putSigned(w, v, n) put(w, (v < 0 and((v + POW[n + 1] ))or(v)), n) end local function alignByte(w) if w.cnt > 0 then put(w, 0, 8 - w.cnt) end end local function putUtf8(w, v) if v < 0x80 then put(w, v, 8) return end local n = v < 0x800 and 2 or(v < 0x10000 and 3 or(v < 0x200000 and 4 or(v < 0x4000000 and 5 or(v < 0x80000000 and 6 or 7 )))) local first = n == 7 and 0xFE or(math.floor(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 local PRESETS= { { 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 local function newPlan(n) 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 local function rice(sc, res, n, order, maxP) local p = maxP while p > 0 and (n % POW[p + 1] ~= 0 or math.floor(n / POW[p + 1] )<= order) do p =p- 1 end local sums, counts = sc.sums, sc.counts local parts = POW[p + 1] local ps = math.floor(n / parts ) for j = 0, parts - 1 do local s = 0 local a = (j == 0 and((order + 1 ))or((j * ps + 1 ))) local e = (j + 1) * ps for i = a, e do local r = res[i] s =s+ (r >= 0 and((2 * r ))or((-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 =total+ cost end local method = maxk > 14 and 1 or 0 total =total+ (np * (method == 1 and 5 or 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, math.floor(np / 2 )do sums[j] = sums[2 * j - 1] + sums[2 * j] counts[j] = counts[2 * j - 1] + counts[2 * j] end q =q- 1 end return bestBits, bestP, bestMethod end local function keepRice(sc, plan, porder, method) plan.porder, plan.method = porder, method local params = plan.params for j = 1, POW[porder + 1] do params[j] = sc.bestKs[j] end end local function fixedResidual(x, n, order, res) 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) local function bestFixedOrder(x, n) 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 =s0+ abs(e0) s1 =s1+ abs(e1) s2 =s2+ abs(e2) s3 =s3+ abs(e3) s4 =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 local function qlpPrecision(bps, n) 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 local function quantize(lp, order, precision, qlp) 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 =cmax/ 2 log2cmax =log2cmax+ 1 end while cmax < 0.5 do cmax =cmax* 2 log2cmax =log2cmax- 1 end -- frexp: cmax = m * 2^log2cmax with m in [0.5, 1) log2cmax =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 =err+ lp[i] * scale local q = floor(err + 0.5) if q > qmax then q = qmax elseif q < qmin then q = qmin end err =err- q qlp[i] = q end return shift end local function lpcResidual(x, n, order, qlp, shift, res) 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 =s+ qlp[j] * x[i - j] end res[i] = x[i] - floor(s / d) end end local function levinson(sc, maxOrder) 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 =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 =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 local function analyze(sc, cfg, src, n, bps, 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 =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 =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 = (e > 0 and(((n - o) * 0.5 * log(e / n) / 0.6931471805599453 + o * (precision + b) ))or((-math.huge ))) if est < bestE then bestO, bestE = o, est end end orders[1] = bestO end local qlp = sc.qlp for _, o in __iter(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 local function writeResidual(w, plan, n) local method = plan.method put(w, method, 2) local porder = plan.porder put(w, porder, 4) local parts = POW[porder + 1] local ps = math.floor(n / parts ) local res = plan.res local pbits = method == 1 and 5 or 4 for j = 0, parts - 1 do local k = plan.params[j + 1] put(w, k, pbits) local a = (j == 0 and((plan.order + 1 ))or((j * ps + 1 ))) local e = (j + 1) * ps local mk = POW[k + 1] for i = a, e do local r = res[i] local u = (r >= 0 and((2 * r ))or((-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 =q- 24 end put(w, 1, q + 1) put(w, lo, k) end end end end local function writeSubframe(w, plan, n) local kind = plan.kind local typ = kind == 0 and 0 or(kind == 1 and 1 or(kind == 2 and((8 + plan.order ))or((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= { [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= { [8] = 1, [12] = 2, [16] = 4, [20] = 5, [24] = 6, [32] = 7 } local function blockCode(n) 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 function Encode.encode(src, opts) 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= { 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 = math.floor((src.frames - 1) / interval )+ 1 if seekPoints > math.floor(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 __iter(comments) do vcLen =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) local function le32(v) put(w, v % 256, 8) put(w, (math.floor(v / 256)) % 256, 8) put(w, (math.floor(v / 65536)) % 256, 8) put(w, math.floor(v / 16777216), 8) end ensure(w, vcLen + 8) put(w, opts.padding > 0 and 0 or 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 __iter(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 = math.floor((bps + 7) / 8 ) local mbuf = buffer.create(bs * ch * mbytes) local scale = POW[bps] local maxv, minv = scale - 1, -scale local X= (table.create(ch) ) 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= { 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= nil local pendingBuf= nil local pendingN, pendingOff = 0, 0 local function readBlock() 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 , pendingOff * ch * 4, take * ch * 4) got =got+ take pendingN =pendingN- take pendingOff =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 = (v < 0 and((v + 4294967296 ))or(v )) for k = 0, mbytes - 1 do writeu8(mbuf, mo, floor(u / POW[8 * k + 1]) % 256) mo =mo+ 1 end end end md5:update(mbuf, 0, mo) local assign = ch - 1 local chosen= {} 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 __iter(chosen) do need =need+ ((math.floor(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, math.floor(n / 256)) writeu8(tb, at + 17, n % 256) seekIdx =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 __iter(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 =frameNo+ 1 total =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, (frameNo > 0 and{minFrame }or{0})[1], maxFrame, rate, ch, bps, total, md5:digest()) buffer.copy(out, siData, si, 0, 34) return out, nil end -- STREAMINFO: 34 bytes function Encode.streaminfo(bs, minFrame, maxFrame, rate, ch, bps, total, md5) local 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"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 -- 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 = (band(c, 0x80) ~= 0 and{(band(bxor(lshift(c, 1), 0x07), 0xFF) )}or{(band(lshift(c, 1), 0xFF) )})[1] end CRC8[i + 1] = c local d = lshift(i, 8) for _ = 1, 8 do d = (band(d, 0x8000) ~= 0 and{(band(bxor(lshift(d, 1), 0x8005), 0xFFFF) )}or{(band(lshift(d, 1), 0xFFFF) )})[1] end CRC16[i + 1] = d end local function crc16(b, from, to) 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 local function crc8(b, from, to) 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 } function Frame.header(b, pos, len, si) 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 =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 =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 =p+ 1 elseif bsCode == 7 then bs = readu8(b, p) * 256 + readu8(b, p + 1) + 1 p =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 =p+ 1 elseif rCode == 13 then rate = readu8(b, p) * 256 + readu8(b, p + 1) p =p+ 2 elseif rCode == 14 then rate = (readu8(b, p) * 256 + readu8(b, p + 1)) * 10 p =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 = (chCode < 8 and((chCode + 1 ))or(2)), assignment = chCode, bps = bps, variable = variable, number = num, } end function Frame.find(b, pos, limit, len, si) 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 =pos+ 1 end return nil end local function bits(b, p, n) 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 local function sbits(b, p, n) local v = bits(b, p, n) if n > 0 and v >= POW2[n] then v =v- POW2[n + 1] end return v end local function residual(b, p, lim, s, n, order) local method = bits(b, p, 2) if method > 1 then return -1 end local porder = bits(b, p + 2, 4) p =p+ 6 local pbits = method == 0 and 4 or 5 local escape = method == 0 and 15 or 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 =p+ pbits local stop = (part + 1) * psize if k == escape then local nb = bits(b, p, 5) p =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 =p+ nb if v >= half then v =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 = k == 0 and 0 or rshift(lshift(w, q + 1), rk) p =p+ used else p =p+ (q + 1 ) r = k == 0 and 0 or rshift(lshift(byteswap(readu32(b, rshift(p, 3))), band(p, 7)), rk) p =p+ k end else q = 32 - sh p =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 =q+ z p =p+ (z + 1 ) break end local adv = 32 - band(p, 7) q =q+ adv p =p+ adv end r = k == 0 and 0 or rshift(lshift(byteswap(readu32(b, rshift(p, 3))), band(p, 7)), rk) p =p+ k end local u = q * pk + r local h = floor(u * 0.5) s[j] = (h + h == u and{h }or{(-h - 1 )})[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 =q+ z p =p+ (z + 1 ) break end local adv = 32 - band(p, 7) q =q+ adv p =p+ adv end local r = bits(b, p, k) p =p+ k local u = q * pk + r local h = floor(u * 0.5) s[j] = (h + h == u and{h }or{(-h - 1 )})[1] end end i = stop + 1 end return p end local function fixed(s, n, order) if order == 1 then local a = s[1] for i = 2, n do a =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 local function lpc(s, n, cf, order, shift) 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 =sum+ cf[j] * s[i - j] end s[i]=s[i]+ floor(sum * inv) end end end local function subframe(b, p, lim, s, n, bps, cf) if p > lim then return -1 end local hdr = bits(b, p, 8) p =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 =p+ 1 wasted =wasted+ 1 if bit == 1 then break end end bps =bps- wasted if bps < 1 then return -1 end end if typ == 0 then local v = sbits(b, p, bps) p =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 =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 =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 =p+ bps end local prec = bits(b, p, 4) + 1 p =p+ 4 if prec == 16 then return -1 end local shift = sbits(b, p, 5) p =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 =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]=s[i]* m end end return p end function Frame.decode(b, len, h, chans, cf, checkCrc) 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 =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]=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 __FILES["codecs/audio/Hively"] = function() local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict -- 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 = {} function Hively.parse(b, base, limit) 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, opts) local o= 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, opts) local rate, sub, stereo = settings(tune, opts) local st = rate and Player.new(tune, rate , 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 =n+ 1 end return n end function Hively.decoder(tune, opts) local rate, sub, stereo, err = settings(tune, opts) if not rate then return nil, err end local sr = rate local mult = tune.speedMultiplier local perIrq = math.floor(math.floor(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) ) 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 = (tune.title ~= "" and{tune.title }or{nil })[1]} , } local function read(_self, n, out) 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 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 =fpos+ k done =done+ k end pos =pos+ n return ob, n end dec.read = read local scratch = buffer.create(4096 * 8) dec.seek = function(_self, seconds) 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) ) pos, fpos, ffill = 0, 0, 0 end while pos < target do read(nil, math.min(4096, target - pos), scratch) end end dec.position = function(_self) return pos / sr end return (dec ) , nil end function Hively.module(tune) 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= { 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 = (tune.format == "hvl" and{tune.mixgain }or{nil})[1], stereo = (tune.format == "hvl" and{tune.stereo }or{nil})[1], }, }, tune = tune, } m.render = function(self, opts) local dec, derr = Hively.decoder(self.tune, opts) if dec then return dec end local empty= Pcm.audioDecoder(Types.Audio.new(44100, 2, 0)) empty.err = derr return empty end return m end return Hively end __FILES["codecs/audio/Hively/Load"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict -- 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 local function cstring(b, p, limit, max) local e = p while e < limit and e - p < max and readu8(b, e) ~= 0 do e =e+ 1 end return buffer.readstring(b, p, e - p), e end function Load.parse(b, base, limit) local size = limit - base if size < 14 then return nil, "truncated header", "truncated" end local function u8(o) 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 = ahx and 4 or bit32.rshift(u8(8), 2) + 4 local tune= { format = ahx and"ahx" or"hvl", version = u8(3), title = "", channels = chnn, positionNr = posn, restart = (ahx and{(u8(8) * 256 + u8(9) )}or{(bit32.band(u8(8), 3) * 256 + u8(9))})[1], 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 = ahx and 256 or math.floor((u8(14) * 256) / 100), stereo = ahx and 0 or 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 + (ahx and 14 or 16) local function need(n) 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 =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 =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 =p+ 3 else if not need(1) then return nil, "truncated track data", "truncated" end if readu8(b, p) == 0x3f then p =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 =p+ 5 end end end end end local plSize = ahx and 4 or 5 for i = 1, insn do if not need(22) then return nil, "truncated instrument", "truncated" end local function at(k) 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= { 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 = bit32.band(at(14), 0x80) ~= 0 and 1 or 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 =p+ 22 if not need(plen * plSize) then return nil, "truncated instrument play list", "truncated" end for j = 1, plen do local e 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 = k == 6 and 12 or(k == 7 and 15 or k ) local l = bit32.band(bit32.rshift(b0, 2), 7) l = l == 6 and 12 or(l == 7 and 15 or 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 =p+ plSize end tune.instruments[i] = ins end return tune, nil, nil end return Load end __FILES["codecs/audio/Hively/Player"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native -- 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) local function s16(v) return (v + 32768) % 65536 - 32768 end local function tdiv(a, b) local q = a / b return (q >= 0 and{(math.floor(q) )}or{(-math.floor(-q) )})[1]end local function period(i) return PERIOD[i] or 0 end -- (3546897.f * 65536.f) / period as a float, then / mix rate as a double, truncated local function deltaOf(p, freq) 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 =d- WRAP end if d == 0 then d = 1 end return d end local function newVoice(i) 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 , 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 , audioSrc = false , 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 function Player.new(tune, freq, stereo, subsong) if subsong < 0 or subsong > #tune.subsongs then return nil end local t = Tables.get() local defstereo = (tune.format == "ahx" and{(math.clamp(math.floor(stereo), 0, 4) )}or{tune.stereo })[1] local mixgain = tune.mixgain if tune.format == "ahx" then local defgain = { [0] = 71, 72, 76, 85, 100 } mixgain = math.floor((defgain[defstereo] * 256) / 100 ) end local st= { tune = tune, freq = freq, version = (tune.format == "hvl" and{tune.version }or{0})[1], channels = tune.channels, voices = {}, tempo = 6, posNr = (subsong > 0 and{tune.subsongs[subsong] }or{0})[1], 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 = ((i % 4 == 0 or i % 4 == 3 )and{left }or{right })[1] 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 local function setPan(st, v, p) v.pan = p v.panMultLeft, v.panMultRight = st.panL[p], st.panR[p] end local function stepfx1(st, v, fx, param) 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 =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 local function stepfx2(v, fx, param, note) 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 local function stepfx3(st, v, fx, param) 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 =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 =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 local function processStep(st, v) 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((v.aFrames ~= 0 and{(tdiv(env.aVolume * 256, v.aFrames) )}or{(env.aVolume * 256)})[1]) v.dFrames = env.dFrames v.dVolume = s16((v.dFrames ~= 0 and{(tdiv((env.dVolume - env.aVolume) * 256, v.dFrames) )}or{(env.dVolume * 256)})[1]) v.sFrames = env.sFrames v.rFrames = env.rFrames v.rVolume = s16((v.rFrames ~= 0 and{(tdiv((env.rVolume - env.dVolume) * 256, v.rFrames) )}or{(env.rVolume * 256)})[1]) 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 local function plistCommand(st, v, fx, param) 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 = band(param, 0x0f) == 0x0f and-1 or 1 end if band(param, 0xf0) ~= 0 then v.filterOn = 1 - v.filterOn v.filterInit = v.filterOn v.filterSign = band(param, 0xf0) == 0xf0 and-1 or 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 =param- 256 end setPan(st, v, param + 128) elseif fx == 12 then if param <= 0x40 then v.noteMaxVolume = param return end param =param- 0x50 if param < 0 then return end if param <= 0x40 then v.perfSubVolume = param return end param =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 local function wnStep(v) local hi, lo = v.wnHi, v.wnLo + 2239384 if lo >= TWO32 then lo =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 =nlo+ 782323 if nlo >= TWO32 then nlo =nlo- TWO32 nhi = (nhi + 1) % TWO32 end nlo = bit32.bxor(nlo, 75) nlo =nlo- 6735 if nlo < 0 then nlo =nlo+ TWO32 nhi = (nhi + TWO32 - 1) % TWO32 end v.wnHi, v.wnLo = nhi, nlo end local function processFrame(st, v) local tune = st.tune if v.noteDelayOn then if v.noteDelayWait <= 0 then processStep(st, v) else v.noteDelayWait =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 = (f ~= 0 and{(s16(tdiv(-(v.adsrVolume - ins.envelope.rVolume * 256), f)) )}or{0 })[1] v.rFrames = f v.aFrames, v.dFrames, v.sFrames = 0, 0, 0 else v.noteMaxVolume = 0 end else v.noteCutWait =v.noteCutWait- 1 end end if v.aFrames ~= 0 then v.adsrVolume =v.adsrVolume+ v.aVolume v.aFrames =v.aFrames- 1 if v.aFrames <= 0 then v.adsrVolume = v.instrument.envelope.aVolume * 256 end elseif v.dFrames ~= 0 then v.adsrVolume =v.adsrVolume+ v.dVolume v.dFrames =v.dFrames- 1 if v.dFrames <= 0 then v.adsrVolume = v.instrument.envelope.dVolume * 256 end elseif v.sFrames ~= 0 then v.sFrames =v.sFrames- 1 elseif v.rFrames ~= 0 then v.adsrVolume =v.adsrVolume+ v.rVolume v.rFrames =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 = math.floor((VIB[v.vibratoCurrent] * v.vibratoDepth) / 128 ) v.plantPeriod = true v.vibratoCurrent = band(v.vibratoCurrent + v.vibratoSpeed, 0x3f) else v.vibratoDelay =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 =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 =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 =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 =d3+ v.squareSign v.squarePos = s16(d3) v.plantSquare = true local ins= v.instrument v.squareWait = (ins and{ins.squareSpeed }or{0 })[1] end end if v.filterOn ~= 0 then v.filterWait =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 = (v.filterSpeed < 4 and((5 - v.filterSpeed ))or(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 =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 =sp+ (x - 1) * 128 end local delta = math.floor(32 / 2 ^ v.waveLength ) local sb = v.squareBuf for i = 0, 4 * 2 ^ v.waveLength - 1 do writei8(sb, i, readi8(waves, sp)) 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 =off+ OFFSETS[v.waveLength] else off =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 =rp+ (v.overrideTranspose + v.trackPeriod - 1 ) else rp =rp+ (v.transpose + v.trackPeriod - 1 ) end end rp = period(math.clamp(s16(rp), 0, 60)) if v.ringFixedPeriod == 0 then rp =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 =ap+ (v.overrideTranspose + v.trackPeriod - 1 ) else ap =ap+ (v.transpose + v.trackPeriod - 1 ) end end ap = period(math.clamp(s16(ap), 0, 60)) if v.fixedNote == 0 then ap =ap+ v.periodSlidePeriod end ap = s16(ap + v.periodPerfSlidePeriod + v.vibratoPeriod) v.audioPeriod = math.clamp(ap, 0x71, 0xd60) local vol = math.floor((math.floor(v.adsrVolume / 256 )* v.noteMaxVolume) / 64 ) vol = math.floor((vol * v.perfSubVolume) / 64 ) vol = math.floor((vol * v.trackMasterVolume) / 64 ) v.audioVolume = s16(vol) end local function fillCycles(dst, src, off, len) 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 =filled+ k end writei8(dst, 0x280, readi8(dst, 0)) end local function setAudio(st, v) v.voiceVolume = v.audioVolume % 256 if v.plantPeriod then v.plantPeriod = false v.delta = deltaOf(v.audioPeriod, st.freq) end local src= v.audioSrc or nil if v.newWaveform and src then fillCycles(v.voiceBuf, src, v.audioOff, v.waveform == 3 and 0x280 or 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) function Player.irq(st, audio) local tune = st.tune local nch = st.channels local voices = st.voices if st.stepWaitFrames == 0 then if st.getNewPosition then local nextpos = st.posNr + 1 == tune.positionNr and 0 or 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 =st.playingTime+ 1 st.stepWaitFrames = s16(st.stepWaitFrames - 1) if st.stepWaitFrames == 0 then if not st.patternBreak then st.noteNr =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 function Player.mix(st, out, at, n) 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] = (v.ringMix and{v.ringBuf }or{false })[1] 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]=pos[i]- WRAP end local cnt = math.floor((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]=rpos[i]- WRAP end cnt = math.floor((WRAP - rpos[i] - 1) / rdelta[i] )+ 1 if cnt < loops then loops = cnt end end end samples =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 = (math.floor((readi8(src[i], math.floor(pos[i] / 65536)) * readi8(r, math.floor(rpos[i] / 65536))) / 128)) * vol[i] rpos[i]=rpos[i]+ rdelta[i] else j = readi8(src[i], math.floor(pos[i] / 65536)) * vol[i] end a =a+ math.floor((j * panl[i]) / 128 ) b =b+ math.floor((j * panr[i]) / 128 ) pos[i]=pos[i]+ delta[i] end a = math.floor((a * gain) / 256 ) b = math.floor((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 =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"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native -- 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 } local function i8(v) v = v % 256 return (v >= 128 and((v - 256 ))or(v ))end local function genSawtooth(w, at, len) local add = math.floor(256 / (len - 1) ) local val = -128 for i = 0, len - 1 do buffer.writei8(w, at + i, i8(val)) val =val+ add end end local function genTriangle(w, at, len) local d5 = math.floor(len / 4 ) local d1 = math.floor(128 / d5 ) local d4 = -(math.floor(len / 2)) local p = at local val = 0 for _ = 1, d5 do buffer.writei8(w, p, i8(val)) p =p+ 1 val =val+ d1 end buffer.writei8(w, p, 0x7f) p =p+ 1 if d5 ~= 1 then val = 128 for _ = 1, d5 - 1 do val =val- d1 buffer.writei8(w, p, i8(val)) p =p+ 1 end end local q = p + d4 for _ = 1, d5 * 2 do local c = buffer.readi8(w, q) q =q+ 1 buffer.writei8(w, p, c == 0x7f and-128 or i8(-c)) p =p+ 1 end end local function genSquare(w, at) local p = at for i = 1, 0x20 do for _ = 1, (0x40 - i) * 2 do buffer.writei8(w, p, -128) p =p+ 1 end for _ = 1, i * 2 do buffer.writei8(w, p, 0x7f) p =p+ 1 end end end -- hvl_GenWhiteNoise with `unsigned long` = 64 bits: (hi, lo) halves local function genWhiteNoise(w, at, len) 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) local function clip(x) if x > 127 then return 127 elseif x < -128 then return -128 end return x end local function trunc8(x) return (x >= 0 and{(math.floor(x) )}or{(-math.floor(-x) )})[1]end local function genFilterWaves(w) 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 =low+ 1 high =high+ 1 end a0 =a0+ (n + 1 ) end freq =freq+ 3 end end local cache= nil function Tables.get() 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 =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, pr= {}, {} for i = 0, 255 do pl[i] = math.floor(math.sin(aa) * 255.0) pr[i] = math.floor(math.sin(ab) * 255.0) aa =aa+ step ab =ab+ step end pl[255] = 0 pr[0] = 0 cache = { waves = w, panL = pl, panR = pr } return cache end return Tables end __FILES["codecs/audio/Mdct"] = function() local __compat = __compat local type = __compat.type --!strict --!native --!optimize 2 -- 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 function Mdct.new(n) if type(n) ~= "number" or n < 4 or n % 4 ~= 0 or n > 2 ^ 24 then return nil end local m = math.floor(n / 2 ) local q = math.floor(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 local function dct4Post(plan, out, oi, os, scale) local q, m = math.floor(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) function Mdct.dct4(plan, u, ui, us, out, oi, os, scale) local q, m = math.floor(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 function Mdct.forward(plan, x, xi, out, oi, os, scale) local q, m = math.floor(plan.n / 4), plan.m local h = math.floor(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 function Mdct.inverse(plan, inp, ii, is, y, yi, scale) local m = plan.m local h = math.floor(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 local function besselI0(x) local sum, term = 1, 1 local k = 1 while k < 200 do term =term* (x / (2 * k)) ^ 2 sum =sum+ term if term < sum * 1e-17 then break end k =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. function Mdct.window(kind, n, alpha) 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 = math.floor(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 =total+ kais[i + 1] end local acc = 0 for i = 0, half - 1 do acc =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 function Mdct.fft(n) return Fft.new(n) end return Mdct end __FILES["codecs/audio/Mdct/Fft"] = function() local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict --!native --!optimize 2 -- 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 = {} local cos, sin, pi = math.cos, math.sin, math.pi function Fft.new(n) 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 =math.floor(m/ 4 ) end while m % 2 == 0 do table.insert(factors, 2) m =math.floor(m/ 2 ) end local f = 3 while m > 1 do while m % f == 0 do table.insert(factors, f) m =math.floor(m/ f ) end f =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 __iter(factors) do local ido = math.floor(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 =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)] local function pass(p, ido, l1, ar, ai, br, bi, tr, ti, cr, ci) 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 =yr+ (xr * wr - xi * wi ) yi =yi+ (xr * wi + xi * wr ) j =j+ u if j >= p then j =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) function Fft.forward(plan, re, im) local n = plan.n local ar, ai, br, bi = re, im, plan.sre, plan.sim local l1 = 1 for k, p in __iter(plan.factors) do local ido = math.floor(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 =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() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict -- 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 = {} local STATUS = { noteOff = 0x80, noteOn = 0x90, aftertouch = 0xA0, controller = 0xB0, program = 0xC0, channelPressure = 0xD0, pitchBend = 0xE0 } local function tempoOf(ev) 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, track) local changes= {} for ti, t in __iter(midi.tracks) do if track == nil or track == ti then for i, ev in __iter(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, b) 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= { ticks = { 0 }, secs = { 0 }, us = { 500000 }, division = midi.division } local div = midi.division for _, c in __iter(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, tick) local div = map.division if div < 0 then local fps = -(math.floor(div / 256)) local tpf = div % 256 if tpf == 0 then return 0 end return tick / ((fps == 29 and 29.97 or fps) * tpf) end local ticks = map.ticks local lo, hi = 1, #ticks while lo < hi do local mid = math.floor((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) if #midi.tracks == 0 then return 0 end if midi.format == 2 then local total = 0 for ti, t in __iter(midi.tracks) do local map = Render.tempoMap(midi, ti) local last = 0 for _, ev in __iter(t.events) do last = math.max(last, ev.tick) end total =total+ Render.seconds(map, last) end return total end local map = Render.tempoMap(midi) local last = 0 for _, t in __iter(midi.tracks) do for _, ev in __iter(t.events) do last = math.max(last, ev.tick) end end return Render.seconds(map, last) end function Render.timeline(midi) local items= {} local offset = 0 local function add(map, ti, t, base) for i, ev in __iter(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 __iter(midi.tracks) do local map = Render.tempoMap(midi, ti) add(map, ti, t, offset) local last = 0 for _, ev in __iter(t.events) do last = math.max(last, ev.tick) end offset =offset+ Render.seconds(map, last) end else local map = Render.tempoMap(midi) for ti, t in __iter(midi.tracks) do add(map, ti, t, 0) end end table.sort(items, function(a, b) 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= { time = (table.create(#items) ), status = (table.create(#items) ), d1 = (table.create(#items) ), d2 = (table.create(#items) ), length = Render.length(midi) } for i, it in __iter(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 function Render.decoder(midi, opts) 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= 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= (table.create(nev) ) 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 = {} , } local mtags = type(midi.meta) == "table" and midi.meta.tags if type(mtags) == "table" then for k, v in __iter(mtags) do if type(k) == "string" and type(v) == "string" then dec.tags[k] = v end end end for _, t in __iter(midi.tracks) do if t.name and not dec.tags.title then dec.tags.title = t.name end end local function read(_self, n, out) 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.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 =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 =pos+ n return b, n end dec.read = read local scratch = buffer.create(4096 * 8) dec.seek = function(_self, seconds) 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 dec.position = function(_self) return pos / rate end return (dec ) , nil end -- tempo meta making each tick last 1 / ticksPerSecond s at that division (MUS, XMIDI, HMP / HMI) function Render.tempoBytes(division, ticksPerSecond) local us = math.clamp(math.floor(division * 1e6 / ticksPerSecond + 0.5), 1, 0xFFFFFF) return { math.floor(us / 65536), (math.floor(us / 256)) % 256, us % 256 } end -- 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, offs) for i, o in __iter(offs) do (o ).seq = i end table.sort(offs, function(a, b) if a.tick ~= b.tick then return a.tick < b.tick end return a.seq < b.seq end) local out= (table.create(#events + #offs) ) local k = 1 for _, ev in __iter(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 =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, opts) local dec, err = Render.decoder(self, opts) if not dec then local empty= { sampleRate = 44100, channels = 2, frames = 0, duration = 0, bitrate = 0, tags = {}, err = err, read = function(_self, _n, out) return out or buffer.create(0), 0 end, seek = function() end, position = function() return 0 end, } return empty end return dec end function Render.summarize(midi) local tempos, sigs, keys = {}, {}, {} local map = Render.tempoMap(midi) for ti, t in __iter(midi.tracks) do for _, ev in __iter(t.events) do if ev.type == "meta" then local d = ev.data 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 = (d[1] >= 128 and((d[1] - 256 ))or(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, source) Render.summarize(midi) midi.meta.source = source midi.render = render end return Render end __FILES["codecs/audio/Mpa"] = function() --!strict -- 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"] = function() --!strict --!native --!optimize 2 -- 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 function Analysis.new() return { x = table.create(1024, 0), off = 0, y = table.create(64, 0) } end function Analysis.run(st, s, si, out, oi) -- 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 =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 =acc+ M[mb + i] * y[i] end out[oi + k] = acc end end return Analysis end __FILES["codecs/audio/Mpa/Core"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 -- 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) local function f32(x) wf(F32, 0, x) return rf(F32, 0) end local function fbuf(list, n) 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 =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= bcreate(4) -- mdct_overlap[2][9*32] local QMF= bcreate(4) -- qmf_state[15*2*32] local PCM= bcreate(4) -- bit reader (bs_t) local bsBuf= FRAME local bsPos = 0 local bsLimit = 0 local function getBits(n) 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 local function readSideInfo(h1, h2, h3) 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 =srIdx- 1 end local grCount = mono and 1 or 2 local scfsi = 0 local mdb if mpeg1 then grCount =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 =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(mpeg1 and 4 or 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] = mpeg1 and 8 or 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] = (mpeg1 and{(getBits(1) )}or{sfc >= 500 and 1 or 0 })[1] 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 local function ldexpQ2(y, e) repeat local s = (e < 120 and{e }or{120 })[1] y = f32(y * EXPFRAC[band(s, 3)] * lshift(1, 30 - arshift(s, 2))) e =e- s until e <= 0 return y end -- L3_read_scalefactors + L3_decode_scalefactors -> SCF[0 .. nLong + nShort) local function decodeScalefactors(h1, h3, istOff, gr, ch) local mpeg1 = band(h1, 8) ~= 0 local nLong, nShort = GR_NLONG[gr], GR_NSHORT[gr] local part = ((nShort ~= 0 and 1 or 0) + (nLong == 0 and 1 or 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 = band(h3, 0x10) ~= 0 and ch ~= 0 and 1 or 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] = (math.floor(sfc / modprod)) % GMOD[k + i] modprod =modprod* GMOD[k + i] end sfc =sfc- modprod k =k+ 4 end part =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 = mpeg1 and-1 or lshift(1, bits) - 1 for k = 0, cnt - 1 do local s = getBits(bits) wu8(IST, ip + k, s == maxScf and 255 or s) wu8(ISCF, sp + k, s) end end end sp =sp+ cnt ip =ip+ cnt scfsi =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 - (band(h3, 0xE0) == 0x60 and 2 or 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 local function huffman(dst, gr, limit) 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 =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 =ireg+ 1 local cb = TABINDEX[tabNum] local linbits = LINBITS[tabNum] repeat local np = rshift(ru8(SFB, sfb), 1) sfb =sfb+ 1 if np == 0 then bigValCnt = 0 break end local pairs = (bigValCnt < np and{bigValCnt }or{np })[1] one = rf(SCF, 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 =sh+ w w = band(leaf, 7) leaf = ri16(TABS, (cb + rshift(cache, 32 - w) - math.floor(leaf / 8)) * 2) end local l = rshift(leaf, 8) cache = lshift(cache, l) sh =sh+ l for _ = 1, 2 do local lsb = band(leaf, 15) if lsb == 15 and linbits ~= 0 then lsb =lsb+ rshift(cache, 32 - linbits) cache = lshift(cache, linbits) sh =sh+ linbits while sh >= 0 do cache = bor(cache, lshift(ru8(b, nextPtr), sh)) nextPtr =nextPtr+ 1 sh =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 =sh+ 1 end wf(GRBUF, d, v) d =d+ 4 leaf = rshift(leaf, 4) end while sh >= 0 do cache = bor(cache, lshift(ru8(b, nextPtr), sh)) nextPtr =nextPtr+ 1 sh =sh- 8 end end bigValCnt =bigValCnt- np sfbCnt =sfbCnt- 1 until not (bigValCnt > 0 and sfbCnt >= 0) end -- count1 quadruples local np = 1 - bigValCnt local cb1 = (GR_C1[gr] ~= 0 and{TAB33 }or{TAB32 })[1] 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 =sh+ l if nextPtr * 8 - 24 + sh > limit or d + 16 > dend then break end np =np- 1 if np == 0 then np = rshift(ru8(SFB, sfb), 1) sfb =sfb+ 1 if np == 0 then break end one = rf(SCF, scf) scf =scf+ 4 end if band(leaf, 128) ~= 0 then wf(GRBUF, d, (cache >= 0x80000000 and{(-one )}or{one})[1]) cache = lshift(cache, 1) sh =sh+ 1 end if band(leaf, 64) ~= 0 then wf(GRBUF, d + 4, (cache >= 0x80000000 and{(-one )}or{one})[1]) cache = lshift(cache, 1) sh =sh+ 1 end np =np- 1 if np == 0 then np = rshift(ru8(SFB, sfb), 1) sfb =sfb+ 1 if np == 0 then break end one = rf(SCF, scf) scf =scf+ 4 end if band(leaf, 32) ~= 0 then wf(GRBUF, d + 8, (cache >= 0x80000000 and{(-one )}or{one})[1]) cache = lshift(cache, 1) sh =sh+ 1 end if band(leaf, 16) ~= 0 then wf(GRBUF, d + 12, (cache >= 0x80000000 and{(-one )}or{one})[1]) cache = lshift(cache, 1) sh =sh+ 1 end while sh >= 0 do cache = bor(cache, lshift(ru8(b, nextPtr), sh)) nextPtr =nextPtr+ 1 sh =sh- 8 end d =d+ 16 end bsPos = limit end -- L3_midside_stereo on GRBUF[left .. left + n) and its right channel at + 576 local function midside(left, n) 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 local function intensityStereo(h1, h3, gr) 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 = nShort ~= 0 and 3 or 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 =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 = mpeg1 and 3 or 0 local itop = nSfb - maxBlocks + i local prev = itop - maxBlocks wu8(IST, 39 + itop, (MAXB[i] >= prev and{defaultPos }or{(ru8(IST, 39 + prev))})[1]) end -- L3_stereo_process local mpeg2sh = band(GR_SFC[gr + 1], 1) local maxPos = mpeg1 and 7 or 64 local s = (ms and{(f32(1.41421356) )}or{1 })[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 =left+ n i =i+ 1 end end local function reorder(g, sfb) 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 =dst+ 12 end src =src+ 3 * len sfb =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 local function antialias(g, nbands) 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 =o+ 72 end end -- BEGIN generated by tools/gen_dsp.py -- L3_dct3_9 on 9 values local function dct3_9(s0, s1, s2, s3, s4, s5, s6, s7, s8) local t0 = s0 + s6 * 0.5 s0 =s0- s6 local t4 = (s4 + s2) * 0.939692616 local t2 = (s8 + s2) * 0.766044438 s6 = (s4 - s8) * 0.173648179 s4 =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 =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) local function imdct36(g, ov, W, nbands) 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 =g+ 18 ov =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 local function dctII(g, n) 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 =x0+ x7 x7 = x1 - x6 x1 =x1+ x6 x6 = x2 - x5 x2 =x2+ x5 x5 = x3 - x4 x3 =x3+ x4 x4 = x0 - x3 x0 =x0+ x3 x3 = x1 - x2 x1 =x1+ x2 t0_0 = x0 + x1 t0_4 = (x0 - x1) * 0.707106769 x5 =x5+ x6 x6 = (x6 + x7) * 0.707106769 x7 =x7+ xt x3 = (x3 + x4) * 0.707106769 x5 =x5- x7 * 0.198912367 x7 =x7+ x5 * 0.382683426 x5 =x5- x7 * 0.198912367 x0 = xt - x6 xt =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 =x0+ x7 x7 = x1 - x6 x1 =x1+ x6 x6 = x2 - x5 x2 =x2+ x5 x5 = x3 - x4 x3 =x3+ x4 x4 = x0 - x3 x0 =x0+ x3 x3 = x1 - x2 x1 =x1+ x2 t1_0 = x0 + x1 t1_4 = (x0 - x1) * 0.707106769 x5 =x5+ x6 x6 = (x6 + x7) * 0.707106769 x7 =x7+ xt x3 = (x3 + x4) * 0.707106769 x5 =x5- x7 * 0.198912367 x7 =x7+ x5 * 0.382683426 x5 =x5- x7 * 0.198912367 x0 = xt - x6 xt =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 =x0+ x7 x7 = x1 - x6 x1 =x1+ x6 x6 = x2 - x5 x2 =x2+ x5 x5 = x3 - x4 x3 =x3+ x4 x4 = x0 - x3 x0 =x0+ x3 x3 = x1 - x2 x1 =x1+ x2 t2_0 = x0 + x1 t2_4 = (x0 - x1) * 0.707106769 x5 =x5+ x6 x6 = (x6 + x7) * 0.707106769 x7 =x7+ xt x3 = (x3 + x4) * 0.707106769 x5 =x5- x7 * 0.198912367 x7 =x7+ x5 * 0.382683426 x5 =x5- x7 * 0.198912367 x0 = xt - x6 xt =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 =x0+ x7 x7 = x1 - x6 x1 =x1+ x6 x6 = x2 - x5 x2 =x2+ x5 x5 = x3 - x4 x3 =x3+ x4 x4 = x0 - x3 x0 =x0+ x3 x3 = x1 - x2 x1 =x1+ x2 t3_0 = x0 + x1 t3_4 = (x0 - x1) * 0.707106769 x5 =x5+ x6 x6 = (x6 + x7) * 0.707106769 x7 =x7+ xt x3 = (x3 + x4) * 0.707106769 x5 =x5- x7 * 0.198912367 x7 =x7+ x5 * 0.382683426 x5 =x5- x7 * 0.198912367 x0 = xt - x6 xt =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 local function imdct12(x, dst, d, ov) 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 = (i == 0 and{co0 }or{(i == 1 and{co1 }or{co2 })[1]})[1] local si = (i == 0 and{si0 }or{(i == 1 and{si1 }or{si2 })[1]})[1] 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 local function imdctShort(g, ov, nbands) 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 =g+ 18 ov =ov+ 9 end end local function changeSign(g) 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 =o+ 144 end end local function imdctGr(g, ov, bt, nLongBands) if nLongBands ~= 0 then imdct36(g, ov, MDCT_WIN0, nLongBands) g =g+ 18 * nLongBands ov =ov+ 9 * nLongBands end if bt == 2 then imdctShort(g, ov, 32 - nLongBands) else imdct36(g, ov, (bt == 3 and{MDCT_WIN1 }or{MDCT_WIN0})[1], 32 - nLongBands) end end -- L3_decode: one granule, side info at gr = grBase + ch local function l3Decode(h1, h2, h3, grBase, nch) 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 = (GR_MIXED[gr] ~= 0 and{(mySr == 2 and 4 or 2) }or{0 })[1] 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 local function synthPair(dst, nch, z) local zb = z * 4 local a = (rf(SYN, zb + 14 * 256) - rf(SYN, zb)) * 29 a =a+ (rf(SYN, zb + 1 * 256) + rf(SYN, zb + 13 * 256)) * 213 a =a+ (rf(SYN, zb + 12 * 256) - rf(SYN, zb + 2 * 256)) * 459 a =a+ (rf(SYN, zb + 3 * 256) + rf(SYN, zb + 11 * 256)) * 2037 a =a+ (rf(SYN, zb + 10 * 256) - rf(SYN, zb + 4 * 256)) * 5153 a =a+ (rf(SYN, zb + 5 * 256) + rf(SYN, zb + 9 * 256)) * 6574 a =a+ (rf(SYN, zb + 8 * 256) - rf(SYN, zb + 6 * 256)) * 37489 a =a+ rf(SYN, zb + 7 * 256) * 75038 wf(PCM, dst * 4, a * SCALE) zb =zb+ 8 a = rf(SYN, zb + 14 * 256) * 104 a =a+ rf(SYN, zb + 12 * 256) * 1567 a =a+ rf(SYN, zb + 10 * 256) * 9727 a =a+ rf(SYN, zb + 8 * 256) * 64019 a =a+ rf(SYN, zb + 6 * 256) * -9975 a =a+ rf(SYN, zb + 4 * 256) * -45 a =a+ rf(SYN, zb + 2 * 256) * 146 a =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 local function synth(xl, dstl, nch, lins) 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 =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 =b0+ (z0 * w1 + y0 * w0 ) b1 =b1+ (z1 * w1 + y1 * w0 ) b2 =b2+ (z2 * w1 + y2 * w0 ) b3 =b3+ (z3 * w1 + y3 * w0 ) a0 =a0+ (z0 * w0 - y0 * w1 ) a1 =a1+ (z1 * w0 - y1 * w1 ) a2 =a2+ (z2 * w0 - y2 * w1 ) a3 =a3+ (z3 * w0 - y3 * w1 ) vz =vz- 256 vy =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 =b0+ (z0 * w3 + y0 * w2 ) b1 =b1+ (z1 * w3 + y1 * w2 ) b2 =b2+ (z2 * w3 + y2 * w2 ) b3 =b3+ (z3 * w3 + y3 * w2 ) a0 =a0+ (y0 * w3 - z0 * w2 ) a1 =a1+ (y1 * w3 - z1 * w2 ) a2 =a2+ (y2 * w3 - z2 * w2 ) a3 =a3+ (y3 * w3 - z3 * w2 ) vz =vz- 256 vy =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 =w+ 4 local z0, z2 = rf(SYN, vz), rf(SYN, vz + 8) local y0, y2 = rf(SYN, vy), rf(SYN, vy + 8) b0 =b0+ (z0 * w1 + y0 * w0 ) b2 =b2+ (z2 * w1 + y2 * w0 ) a0 =a0+ (z0 * w0 - y0 * w1 ) a2 =a2+ (z2 * w0 - y2 * w1 ) vz =vz- 256 vy =vy+ 256 z0 = rf(SYN, vz) z2 = rf(SYN, vz + 8) y0 = rf(SYN, vy) y2 = rf(SYN, vy + 8) b0 =b0+ (z0 * w3 + y0 * w2 ) b2 =b2+ (z2 * w3 + y2 * w2 ) a0 =a0+ (y0 * w3 - z0 * w2 ) a2 =a2+ (y2 * w3 - z2 * w2 ) vz =vz- 256 vy =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 local function synthGranule(nbands, nch, pcm) 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 local function l12ReadScaleInfo(h1, h2, h3, kbpsHdr) local mode = rshift(h3, 6) local sb = mode == 3 and 0 or(mode == 1 and{(band(rshift(h3, 4), 3) * 4 + 4 )}or{32 })[1] 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 = (mode ~= 3 and{(rshift(kbpsHdr, 1) )}or{kbpsHdr })[1] if kbps == 0 then kbps = 192 end alloc, nbands = ALLOC_L2M1, 27 if kbps < 56 then alloc, nbands = ALLOC_L2M1_LOW, srIdx == 2 and 12 or 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 =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, (stereoBands ~= 0 and{ba }or{0})[1]) end for i = 0, 2 * nbands - 1 do wu8(SCFCOD, i, (ru8(BA, i) ~= 0 and{(layer1 and 2 or getBits(2)) }or{6})[1]) end -- L12_read_scalefactors local so = 0 for i = 0, 2 * nbands - 1 do local s = 0 local ba = ru8(BA, i) local mask = (ba ~= 0 and{(4 + band(rshift(19, ru8(SCFCOD, i)), 3) )}or{0 })[1] 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), math.floor(b / 3))) end wf(L12SCF, so, s) so =so+ 4 m = rshift(m, 1) end end for i = stereoBands, nbands - 1 do wu8(BA, 2 * i + 1, 0) end end local function l12Dequantize(g, groupSize) 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 - math.floor(mod / 2)) code =math.floor(code/ mod ) end end end dst =dst+ choff choff = 18 - choff end end return groupSize * 4 end local function l12ApplyScf(scfOff) 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 function Core.newState() 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 function Core.reset(st) bfill(st.overlap, 0, 0) bfill(st.qmf, 0, 0) st.reservLen = 0 st.needReset = false end Core.lastChannels = 0 function Core.upmix(pcm, n) 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 function Core.decodeFrame(st, b, off, size, pcm) 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 = band(h3, 0xC0) == 0xC0 and 1 or 2 Core.lastChannels = nch local layer = 4 - band(rshift(h1, 1), 3) local spf = band(h1, 6) == 6 and 384 or(band(h1, 14) == 2 and 576 or 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 = math.floor((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, math.floor(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 = band(h1, 8) ~= 0 and 2 or 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 =p+ 576 * nch end end -- L3_save_reservoir local pos = math.floor((bsPos + 7) / 8 ) local remains = math.floor(bsLimit / 8 )- pos if remains > MAX_BITRESERVOIR_BYTES then pos =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 (success and{spf }or{0 })[1] end local kbps = 2 * HALFRATE[(band(h1, 8) ~= 0 and 45 or 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 =i+ l12Dequantize(i, group) if i == 12 then i = 0 l12ApplyScf(igr) synthGranule(12, nch, p) bfill(GRBUF, 0, 0) p =p+ 384 * nch end if bsPos > bsLimit then st.needReset = true return 0 end end return spf end function Core.probeL3(b, off, size) 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 = (band(h3, 0xC0) == 0xC0 and 1 or 2) * (band(h1, 8) ~= 0 and 2 or 1) local sum = 0 for gr = 0, ngr - 1 do sum =sum+ GR_P23[gr] end return mdb, sum, math.floor((bsLimit - bsPos) / 8 )end -- Layer I / II: minimp3 drops a frame that needs more bits than it has function Core.probeL12(b, off, size) 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[(band(h1, 8) ~= 0 and 45 or 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 =bits+ ba * group else local mod = lshift(2, ba - 17) + 1 bits =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) function Core.vbrTag(b, off, size) 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 = math.floor(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 =t+ 8 if size - t < 4 then return 0, 0, 0, 0 end local frames = bswap(ru32(FRAME, t)) t =t+ 4 if band(flags, 2) ~= 0 then if size - t < 4 then return 0, 0, 0, 0 end t =t+ 4 end if band(flags, 4) ~= 0 then if size - t < 100 then return 0, 0, 0, 0 end t =t+ 100 end if band(flags, 8) ~= 0 then if size - t < 4 then return 0, 0, 0, 0 end t =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 =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() --!strict -- 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"] = function() local __compat = __compat local buffer = __compat.buffer --!strict --!native --!optimize 2 -- 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 local function levels(ba) if ba >= 17 then return ba == 17 and 3 or(ba == 18 and 5 or 9 ) end return POW[ba + 1] - 1 end local function tripleBits(ba) if ba >= 17 then return ba == 17 and 5 or(ba == 18 and 7 or 10 ) end return 3 * ba end -- the quantizer's signal-to-noise ratio in dB (ISO 11172-3 table C.5) local SNR= {} 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 } local put = Bits.msbPut function Encode2.encode(src, opts) 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 = opts.mode == "mono" and 1 or 2 local kbps = opts.bitrate local list = (mpeg1 and{BITRATES_V1 }or{BITRATES_V2 })[1] 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 = (nch == 2 and{(math.floor(kbps / 2 ))}or{kbps })[1] alloc, nbands = ALLOC_L2M1, 27 if perCh < 56 then alloc, nbands = ALLOC_L2M1_LOW, srIndex == 2 and 12 or 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 =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= {} 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= { buf = buffer.create(65536), pos = 0, acc = 0, cnt = 0 } if opts.prefix then local pf = opts.prefix 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= nil local pending= 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 for i = 0, take - 1 do local base = (pendOff + i) * inCh * 4 local l = buffer.readf32(pb, base) local r = (inCh > 1 and{(buffer.readf32(pb, base + 4) )}or{l })[1] if nch == 1 then pcm[1][got + i + 1] = (inCh > 1 and(((l + r) * 0.5 ))or(l )) else pcm[1][got + i + 1] = l pcm[2][got + i + 1] = r end end got =got+ take pendN =pendN- take pendOff =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 =idx- 1 end while idx < 62 and SCF[idx + 2] >= m do idx =idx+ 1 end end sc[b * 3 + part + 1] = idx end end end local frameBytes = math.floor(slot / rate ) rest =rest+ slot % rate local padding = 0 if rest >= rate then rest =rest- rate padding = 1 frameBytes =frameBytes+ 1 end local avail = frameBytes * 8 - 32 for b = 1, nbands do avail =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 = st == 0 and 0 or s[st][2] local nxt = s[st + 1][2] local noise = level[c][b] - (st == 0 and 0 or SNR[cur]) local cost = 12 * tripleBits(nxt) - (st == 0 and 0 or 12 * tripleBits(cur)) if st == 0 then cost =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 do local __DARKLUA_VAR= bal[bestC]__DARKLUA_VAR[bestB]=__DARKLUA_VAR[bestB]+ 1 end avail =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, nch == 1 and 3 or 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, st == 0 and 0 or 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 = math.floor(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 local function quant(x) local q = floor((x * inv + 1) * L / 2) return q < 0 and 0 or(q > L - 1 and((L - 1 ))or(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 =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"] = function() local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict --!native --!optimize 2 -- 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= {} local LEN= {} local XLEN= {} local function walk(tree, codes, lens, p, code, len) 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 =q+ bit32.rshift(tree[q + 1], 8) end q =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 =q+ bit32.band(tree[q + 1], 0xFF) end q =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 = t >= 16 and t <= 23 and 16 or(t >= 24 and t <= 31 and 24 or 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 = math.floor((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= {} for m = 0, 15 do local list = {} for _, t in __iter({ 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 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 local function newPlan() return { bits = 0, bigValues = 0, count1 = 0, tables = { 0, 0, 0 }, region0 = 0, region1 = 0, c1table = 0, addr1 = 0, addr2 = 0 } end local function pairBits(ix, a, b, t) 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 =extra+ lb end if y > 14 then y = 15 extra =extra+ lb end bits =bits+ (lens[x * 16 + y + 1] + extra ) if x ~= 0 then bits =bits+ 1 end if y ~= 0 then bits =bits+ 1 end end return bits end local function chooseTable(ix, a, b) 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 __iter(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 __iter({ 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 local function plan(ix, bounds, p) local i = 576 while i > 1 and ix[i] == 0 and ix[i - 1] == 0 do i =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 =i- 4 c1 =c1+ 1 end local bv = i -- big_values * 2 coefficients p.bigValues, p.count1 = math.floor(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 =ba+ (lensA[v * 8 + w * 4 + x * 2 + y + 1] + s ) bb =bb+ (4 + s ) end p.c1table = bb < ba and 1 or 0 local bits = (bb < ba and{bb }or{ba })[1] -- regions: region 0 / 1 / 2 split at scalefactor band boundaries local j = 0 while j + 1 < #bounds and bounds[j + 2] <= bv do j =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 local function writePairs(w, ix, sign, a, b, t) 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 = x > 14 and 15 or x, y > 14 and 15 or 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, sign[i + 1] and 1 or 0, 1) end if cy == 15 then put(w, y - 15, lb) end if y ~= 0 then put(w, sign[i + 2] and 1 or 0, 1) end end end local function writeHuffman(w, ix, sign, p) 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, sign[o + k] and 1 or 0, 1) end end end end local function newUnit() 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 local function quantize(u, g) 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 local function rateLoop(u, budget, bounds) 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 = math.floor((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 function Encode3.encode(src, opts) 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 = mpeg1 and 2 or 1 local spf = 576 * granules local inCh = src.channels local mode = opts.mode local nch = mode == "mono" and 1 or 2 local kbps = opts.bitrate local list = (mpeg1 and{BITRATES_V1 }or{BITRATES_V2 })[1] local brIndex = table.find(list, kbps) if not brIndex then return nil, "unsupported bit rate" end local sideBytes = (mpeg1 and{(nch == 1 and 17 or 32) }or{(nch == 1 and 9 or 17) })[1] local slotNum = (mpeg1 and 144000 or 72000) * kbps -- frame bytes * rate local bounds = { 0 } do local acc = 0 for k = 0, 21 do acc =acc+ T.g_scf_long[group * 23 + k] table.insert(bounds, acc) end end local w= { buf = buffer.create(65536), pos = 0, acc = 0, cnt = 0 } if opts.prefix then local pf = opts.prefix 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= nil local pending= 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 for i = 0, take - 1 do local base = (pendOff + i) * inCh * 4 local l = buffer.readf32(pb, base) local r = (inCh > 1 and{(buffer.readf32(pb, base + 4) )}or{l })[1] 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 =got+ take pendN =pendN- take pendOff =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 =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 = math.floor(slotNum / rate ) rest =rest+ slotNum % rate local padding = 0 if rest >= rate then rest =rest- rate padding = 1 frameBytes =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, math.floor(left / (nUnits - done))) local u = units[g][c] rateLoop(u, budget, bounds) left =left- u.plan.bits done =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, mode == "mono" and 3 or(mode == "joint" and 1 or 0), 2) put(w, mode == "joint" and 2 or 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, nch == 1 and 5 or 3) for _ = 1, nch do put(w, 0, 4) -- scfsi end else put(w, 0, 8) put(w, 0, nch == 1 and 1 or 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, mpeg1 and 4 or 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 =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"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 -- 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 function H.valid(b, o) 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 function H.compare(b, o1, o2) 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 function H.bitrateKbps(h1, h2) local mpeg1 = band(h1, 8) ~= 0 and 1 or 0 local layer = band(rshift(h1, 1), 3) return 2 * HALFRATE[mpeg1 * 45 + (layer - 1) * 15 + rshift(h2, 4)] end local bitrateKbps = H.bitrateKbps function H.sampleRate(h1, h2) local hz = HZ[band(rshift(h2, 2), 3)] if band(h1, 8) == 0 then hz =math.floor(hz/ 2 ) end if band(h1, 0x10) == 0 then hz =math.floor(hz/ 2 ) end return hz end local sampleRate = H.sampleRate function H.frameSamples(h1) 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) function H.frameBytes(b, o, freeSize) local h1, h2 = ru8(b, o + 1), ru8(b, o + 2) local hz = sampleRate(h1, h2) local fb = math.floor(frameSamples(h1) * bitrateKbps(h1, h2) * 125 / hz ) if band(h1, 6) == 6 then fb = band(fb, 0xFFFFFFFC) end return (fb ~= 0 and{fb }or{freeSize })[1]end local frameBytes = H.frameBytes function H.padding(b, o) if band(ru8(b, o + 2), 2) == 0 then return 0 end return band(ru8(b, o + 1), 6) == 6 and 4 or 1 end local padding = H.padding -- mp3d_match_frame: the frames chained after o (n bytes left) keep comparing equal local function matchFrame(b, o, n, fb) local i = 0 for nmatch = 0, H.MAX_FRAME_SYNC_MATCHES - 1 do i =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 function H.findFrame(b, base, n, ffb) 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 =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() --!strict -- 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 __FILES["codecs/audio/Musepack"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict -- 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 -- SV7 reads the stream as little-endian 32-bit words, most significant bit first: swap them into a padded copy local function swapped(buf, p, limit) local n = limit - p local words = math.floor((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, start, limit) 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 - ((gapless and((FRAME - last ))or(DELAY))) -- the frame index: a 20-bit size in front of each frame (the last one has 11 more bits: its length) local offs, sizes= {}, {} 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 + (i == frames and 11 or 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(math.floor((samples + DELAY + FRAME - 1) / FRAME), have + 1) local stopAt = math.min(samples + DELAY, have * FRAME + (have < frames and 0 or FRAME)) local st = Decode.state(7, maxBand, ms, 2) local pcm = table.create(FRAME * 2, 0) local prev = 0 local out= { 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) return (i - 1) * FRAME end, decode = function(i) if i ~= prev + 1 then Decode.reset(st, i == 1 and 0 or 0x01010101) end prev = i local o= 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 + math.floor(o / 8)) end if e ~= o + sizes[i] then return nil, Err.new(Err.CORRUPT, "frame " .. i .. " has the wrong size", start + 4 + math.floor(o / 8)) end return FRAME, nil end, pcm = function() 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, p, limit) 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, start, limit) local p = start + 4 local sh= nil local gain, pns, profile, encoder = nil, nil, 0, 0 local apOff, apSize= {}, {} 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) 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 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 = math.floor((samples + DELAY + FRAME - 1) / FRAME ) local count = math.min(#apOff, math.floor((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= { 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) return (i - 1) * per * FRAME end, decode = function(i) local o, size= 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() 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, p, limit) 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, start, limit) 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"] = function() local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict --!native --!optimize 2 -- 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= { { 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= { [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) local function f32(x) buffer.writef32(F32, 0, x) return buffer.readf32(F32, 0) end for i, v in __iter(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 =f1* 0.83298066476582673961 f2 =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 =f1* 0.83298066476582673961 f2 =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 __iter(T.DI) do DW[i] = f32(v / 65536) end local B= buffer.create(0) local P = 0 local function bits(n) 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 =P+ n return v end local function peek16() local w = bswap(readu32(B, rshift(P, 3))) return extract(w, 16 - band(P, 7), 16) end local function huff(t) local code = peek16() local k = rshift(code, 8) + 1 local n = t.len[k] if n > 0 then P =P+ n return t.val[k] end local j = t.val[k] local codes = t.codes while code < codes[j] do j =j+ 1 end n = t.lens[j] P =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 local function logDec(max) 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 local function enumDec(k, n) 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 =n- 1 local c = CNK[k][n + 1] if code >= c then out = bor(out, lshift(1, n)) code =code- c k =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) local function newV(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] 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 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 =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 =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 function Decode.state(version, maxBand, ms, channels) local st= { 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 function Decode.reset(st, scf) 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 local function noise(st, q, o) 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 local function readSv7(st, limit) 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] = (idx ~= 4 and((resL[n] + idx ))or((bits(4) ))) idx = huff(HDR) resR[n + 1] = (idx ~= 4 and((resR[n] + idx ))or((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 = (c == 1 and{resL[n] }or{resR[n] })[1] if res ~= 0 then local scf = (c == 1 and{st.scfL }or{st.scfR })[1] local scfi = (c == 1 and{scfiL[n] }or{scfiR[n] })[1] local o = (n - 1) * 3 local idx = huff(DSCF7) local s0 = (idx ~= 8 and((scf[o + 3] + idx ))or((bits(6) ))) local s1, s2 if scfi == 1 then idx = huff(DSCF7) s1 = (idx ~= 8 and((s0 + idx ))or((bits(6) ))) s2 = s1 elseif scfi == 3 then s1, s2 = s0, s0 elseif scfi == 2 then s1 = s0 idx = huff(DSCF7) s2 = (idx ~= 8 and((s1 + idx ))or((bits(6) ))) else idx = huff(DSCF7) s1 = (idx ~= 8 and((s0 + idx ))or((bits(6) ))) idx = huff(DSCF7) s2 = (idx ~= 8 and((s1 + idx ))or((bits(6) ))) end scf[o + 1] = s0 > 1024 and 0x8080 or s0 scf[o + 2] = s1 > 1024 and 0x8080 or s1 scf[o + 3] = s2 > 1024 and 0x8080 or 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 = (c == 1 and{resL[n] }or{resR[n] })[1] local q = (c == 1 and{st.qL }or{st.qR })[1] 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] = (math.floor(idx / 3)) % 3 - 1 q[o + k + 2] = math.floor(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] = math.floor(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 local function readSv8(st, key, limit) 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 =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] = (l > 15 and((l - 17 ))or(l )) resR[maxUsed] = (r > 15 and((r - 17 ))or(r )) for n = maxUsed - 1, 1, -1 do l = huff(RES8[resL[n + 1] > 2 and 2 or 1]) + resL[n + 1] resL[n] = (l > 15 and((l - 17 ))or(l )) r = huff(RES8[resR[n + 1] > 2 and 2 or 1]) + resR[n + 1] resR[n] = (r > 15 and((r - 17 ))or(r )) end if st.ms then local tot = 0 for n = 1, maxUsed do if resL[n] ~= 0 or resR[n] ~= 0 then tot =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 =cnt+ 1 end if resR[n] ~= 0 then cnt =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 = (c == 1 and{resL[n] }or{resR[n] })[1] if res ~= 0 then local scf = (c == 1 and{st.scfL }or{st.scfR })[1] local scfi = (c == 1 and{scfiL[n] }or{scfiR[n] })[1] local dscf = (c == 1 and{dscfL }or{dscfR })[1] 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 =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 = (c == 1 and{resL[n] }or{resR[n] })[1] local q = (c == 1 and{st.qL }or{st.qR })[1] 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[idx > thres and 2 or 1]) local a, b, cc = tmp % 5 - 2, (math.floor(tmp / 5)) % 5 - 2, math.floor(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((cnt <= 9 and{cnt }or{(18 - cnt)})[1], 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 =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] = (s1 >= 8 and((s1 - 16 ))or(s1 )) q[o + k + 1] = (s2 >= 8 and((s2 - 16 ))or(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[idx > thres and 2 or 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 local function requant(st) 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 = (rl ~= 0 and{(f32(ccl * SCF[band(scfL[(b - 1) * 3 + part + 1], 255) + 1]) )}or{0 })[1] local fr = (rr ~= 0 and{(f32(ccr * SCF[band(scfR[(b - 1) * 3 + part + 1], 255) + 1]) )}or{0 })[1] 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 =y+ 32 end else for k = 0, 11 do yL[y], yR[y] = fl * qL[qo + k], fr * qR[qo + k] y =y+ 32 end end end end end -- mpc_synthese_filter_float local function synth(V, Y, out, base, step) table.move(V, 1, 960, 2305) local o = 2304 + 1 local dw = DW local p = base for n = 0, 35 do o =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 =p+ step end end end function Decode.frame(st, buf, bitPos, limitBits, key, out, base) 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 (bitPos >= 0 and{pos }or{bitPos})[1], nil end function Decode.bitsAt(buf, bitPos, n) 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() local __compat = __compat local bit32 = __compat.bit32 --!strict -- 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 =bits+ 1 end l[n] = bits lost[n] = (v > 0 and((2 ^ bits - v ))or(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 function T.lut(tab, sym) 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) local j = 1 while code < codes[j] do j =j+ 1 end return j end local function symbol(j, code) 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 __FILES["codecs/audio/Opus"] = function() --!strict -- 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"] = function() local __compat = __compat local bit32 = __compat.bit32 --!strict --!native --!optimize 2 -- 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) local function imin(a, b) return (a < b and{a }or{b })[1]end local function imax(a, b) return (a > b and{a }or{b })[1]end -- C integer division (truncates toward zero) local function tdiv(a, b) local q = a / b return (q >= 0 and{(floor(q) )}or{(-floor(-q) )})[1]end local function exp2(x) return exp(0.6931471805599453094 * x) end local function lcg(seed) return (1664525 * seed + 1013904223) % 4294967296 end local function signed32(x) return (x >= 2147483648 and((x - 4294967296 ))or(x ))end local function fracMul16(a, b) return math.floor((16384 + a * b) / 32768 )end local function bitexactCos(x) local tmp = math.floor((4096 + x * x) / 8192 ) local x2 = tmp x2 = (32767 - x2) + fracMul16(x2, (-7651 + fracMul16(x2, (8277 + fracMul16(-626, x2))))) return 1 + x2 end local function bitexactLog2tan(isin, icos) 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) local function laplaceDecode(dec, fs, decay) local val = 0 local fm = decDecodeBin(dec, 15) local fl = 0 if fm >= fs then val =val+ 1 fl = fs fs = math.floor(((32768 - 32 - fs) * (16384 - decay)) / 32768 )+ 1 while fs > 1 and fm >= fl + 2 * fs do fs =fs* 2 fl =fl+ fs fs = math.floor(((fs - 2) * decay) / 32768 ) fs =fs+ 1 val =val+ 1 end if fs <= 1 then local di = rshift(fm - fl, 1) val =val+ di fl =fl+ 2 * di end if fm < fl + fs then val = -val else fl =fl+ fs end end decUpdate(dec, fl, imin(fl + fs, 32768), 32768) return val end local function unquantCoarseEnergy(st, start, endb, intra, dec, C, LM) local oldE = st.oldBandE local probBase = LM * 84 + (intra and 42 or 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 = (band(qi, 1) ~= 0 and{(-rshift(qi, 1) - 1 )}or{(rshift(qi, 1) )})[1] elseif budget - t >= 1 then qi = decBitLogp(dec, 1) and-1 or 0 else qi = -1 end local q = qi local k = i + c * NB_EBANDS + 1 local e = max(-9, oldE[k]) local prev = (c == 0 and{prev0 }or{prev1 })[1] oldE[k] = coef * e + prev + q prev = prev + q - beta * q if c == 0 then prev0 = prev else prev1 = prev end end end end local function unquantFineEnergy(st, start, endb, fineQuant, dec, C) local oldE = st.oldBandE for i = start, endb - 1 do local __DARKLUA_CONTINUE_7=false repeat local extra = fineQuant[i + 1] if extra <= 0 then __DARKLUA_CONTINUE_7=true break end if tell(dec) + C * extra > dec.storage * 8 then __DARKLUA_CONTINUE_7=true break end for c = 0, C - 1 do local q2 = decBits(dec, extra) local offset = (q2 + 0.5) * 2 ^ (14 - extra) * (1 / 16384) - 0.5 do local __DARKLUA_VAR=i + c * NB_EBANDS + 1 oldE[__DARKLUA_VAR]=oldE[__DARKLUA_VAR]+ offset end end __DARKLUA_CONTINUE_7=true until true if not __DARKLUA_CONTINUE_7 then break end end end local function unquantEnergyFinalise(st, start, endb, fineQuant, finePriority, bitsLeft, dec, C) local oldE = st.oldBandE for prio = 0, 1 do local i = start while i < endb and bitsLeft >= C do local __DARKLUA_CONTINUE_10=false repeat if fineQuant[i + 1] >= MAX_FINE_BITS or finePriority[i + 1] ~= prio then i =i+ 1 __DARKLUA_CONTINUE_10=true break 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) do local __DARKLUA_VAR=i + c * NB_EBANDS + 1 oldE[__DARKLUA_VAR]=oldE[__DARKLUA_VAR]+ offset end bitsLeft =bitsLeft- 1 end i =i+ 1 __DARKLUA_CONTINUE_10=true until true if not __DARKLUA_CONTINUE_10 then break end end end end -- bit allocation (rate.c) local function bits2pulses(bandI, LM, bits) local base = CACHE_INDEX[(LM + 1) * NB_EBANDS + bandI + 1] local lo, hi = 0, CACHE_BITS[base + 1] bits =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 = lo == 0 and-1 or CACHE_BITS[base + lo + 1] if bits - loBits <= CACHE_BITS[base + hi + 1] - bits then return lo end return hi end local function pulses2bits(bandI, LM, pulses) 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 local function getPulses(i) 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) local function computeAllocation(start, endb, offsets, cap, allocTrim, total, pulses, ebits, finePriority, C, LM, ec) total = imax(total, 0) local len = NB_EBANDS local skipStart = start local skipRsv = total >= 8 and 8 or 0 total =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 =total- intensityRsv dualStereoRsv = total >= 8 and 8 or 0 total =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, math.floor((3 * w * 2 ^ LM * 8) / 16)) trimOffset[j + 1] = math.floor((C * w * (allocTrim - 5 - LM) * (endb - j - 1) * 2 ^ (LM + BITRES)) / 64 ) if w * 2 ^ LM == 1 then do local __DARKLUA_VAR=j + 1 trimOffset[__DARKLUA_VAR]=trimOffset[__DARKLUA_VAR]- C * 8 end 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 = math.floor((C * N * ALLOC[mid * len + j + 1] * 2 ^ LM) / 4 ) if bitsj > 0 then bitsj = imax(0, bitsj + trimOffset[j + 1]) end bitsj =bitsj+ offsets[j + 1] if bitsj >= thresh[j + 1] or done then done = true psum =psum+ imin(bitsj, cap[j + 1]) elseif bitsj >= C * 8 then psum =psum+ C * 8 end end if psum > total then hi = mid - 1 else lo = mid + 1 end until lo > hi hi = lo lo =lo- 1 for j = start, endb - 1 do local N = EB[j + 2] - EB[j + 1] local bits1j = math.floor((C * N * ALLOC[lo * len + j + 1] * 2 ^ LM) / 4 ) local bits2j = (hi >= NB_ALLOC_VECTORS and{cap[j + 1] }or{(math.floor((C * N * ALLOC[hi * len + j + 1] * 2 ^ LM) / 4 ))})[1] 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 =bits1j+ offsets[j + 1] end bits2j =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 = C > 1 and 1 or 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] + math.floor((mid * bits2[j + 1]) / 64 ) if tmp >= thresh[j + 1] or done then done = true psum =psum+ imin(tmp, cap[j + 1]) elseif tmp >= allocFloor then psum =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] + math.floor((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 =psum+ tmp end local codedBands = endb while true do local j = codedBands - 1 if j <= skipStart then total =total+ skipRsv break end local left = total - psum local percoeff = math.floor(left / (EB[codedBands + 1] - EB[start + 1]) ) left =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 =psum+ 8 bandBits =bandBits- 8 end psum =psum- (bits[j + 1] + intensityRsv ) if intensityRsv > 0 then intensityRsv = LOG2_FRAC_TABLE[j - start + 1] end psum =psum+ intensityRsv if bandBits >= allocFloor then psum =psum+ allocFloor bits[j + 1] = allocFloor else bits[j + 1] = 0 end codedBands =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 =total+ dualStereoRsv dualStereoRsv = 0 end if dualStereoRsv > 0 then dualStereo = decBitLogp(ec, 1) end local left = total - psum local percoeff = math.floor(left / (EB[codedBands + 1] - EB[start + 1]) ) left =left- (EB[codedBands + 1] - EB[start + 1]) * percoeff for j = start, codedBands - 1 do do local __DARKLUA_VAR=j + 1 bits[__DARKLUA_VAR]=bits[__DARKLUA_VAR]+ percoeff * (EB[j + 2] - EB[j + 1]) end end for j = start, codedBands - 1 do local tmp = imin(left, EB[j + 2] - EB[j + 1]) do local __DARKLUA_VAR=j + 1 bits[__DARKLUA_VAR]=bits[__DARKLUA_VAR]+ tmp end left =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 + (C == 2 and N > 2 and not dualStereo and j < intensity and 1 or 0) local NClogN = den * (LOGN[j + 1] + logM) local offset = (math.floor(NClogN / 2)) - den * FINE_OFFSET if N == 2 then offset =offset+ math.floor((den * 8) / 4 ) end if bits[j + 1] + offset < den * 2 * 8 then offset =offset+ math.floor(NClogN / 4 ) elseif bits[j + 1] + offset < den * 3 * 8 then offset =offset+ math.floor(NClogN / 8 ) end local eb = imax(0, bits[j + 1] + offset + den * 4) eb = math.floor((math.floor(eb / den)) / 8 ) if C * eb > (math.floor(bits[j + 1] / 8)) then eb = math.floor((math.floor(bits[j + 1] / 2 ^ stereo)) / 8 ) end eb = imin(eb, MAX_FINE_BITS) finePriority[j + 1] = eb * (den * 8) >= bits[j + 1] + offset and 1 or 0 do local __DARKLUA_VAR=j + 1 bits[__DARKLUA_VAR]=bits[__DARKLUA_VAR]- C * eb * 8 end 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(math.floor(excess / 2 ^ (stereo + BITRES)), MAX_FINE_BITS - ebits[j + 1]) do local __DARKLUA_VAR=j + 1 ebits[__DARKLUA_VAR]=ebits[__DARKLUA_VAR]+ extraFine end local extraBits = extraFine * C * 8 finePriority[j + 1] = extraBits >= excess - balance and 1 or 0 excess =excess- extraBits end balance = excess j =j+ 1 end while j < endb do ebits[j + 1] = math.floor((math.floor(bits[j + 1] / 2 ^ stereo)) / 8 ) bits[j + 1] = 0 finePriority[j + 1] = ebits[j + 1] < 1 and 1 or 0 j =j+ 1 end return codedBands, balance, intensity, dualStereo end -- PVQ (cwrs.c, vq.c) local function cwrsi(n, k, i, iy) 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 =i- p end k0 = k local q = U[rowBase + n] if q > i then k = n repeat k =k- 1 p = U[k * UK + n + 1] until p <= i else p = U[rowBase + k] while p > i do k =k- 1 p = U[rowBase + k] end end i =i- p val = (neg and((k - k0 ))or((k0 - k ))) iy[idx] = val idx =idx+ 1 yy =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 =i- p iy[idx] = 0 idx =idx+ 1 else local neg = i >= q if neg then i =i- q end k0 = k repeat k =k- 1 p = U[k * UK + n + 1] until p <= i i =i- p val = (neg and((k - k0 ))or((k0 - k ))) iy[idx] = val idx =idx+ 1 yy =yy+ val * val end end n =n- 1 end p = 2 * k + 1 local neg = i >= p if neg then i =i- p end k0 = k k = rshift(i + 1, 1) if k ~= 0 then i =i- (2 * k - 1 ) end val = (neg and((k - k0 ))or((k0 - k ))) iy[idx] = val yy =yy+ val * val val = (i ~= 0 and{(-k )}or{k })[1] iy[idx + 1] = val yy =yy+ val * val return yy end local function expRotation1(X, len, stride, c, s) 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 =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 =p- 1 end end local SPREAD_FACTOR = { 15, 10, 5 } local function expRotation(X, len, dir, stride, K, spread) 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 =stride2+ 1 end end len = math.floor(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 local function renormaliseVector(X, N, gain) local E = 1e-15 for i = X + 1, X + N do local v = W[i] E =E+ v * v end local g = gain / sqrt(E) for i = X + 1, X + N do W[i]=W[i]* g end end local function algUnquant(X, N, K, spread, B, dec, gain) 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 = math.floor(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) local ctx= { i = 0, intensity = 0, spread = 0, tf_change = 0, ec = (nil ), remaining_bits = 0, seed = 0, disable_inv = false, avoid_split_noise = false, } local function haar1(X, N0, stride) 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 local function deinterleaveHadamard(X, N0, stride, hadamard) 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 local function interleaveHadamard(X, N0, stride, hadamard) 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 local function computeQn(N, b, offset, pulseCap, stereo) local N2 = 2 * N - 1 if stereo and N == 2 then N2 =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 local function computeTheta(N, b, B, B0, LM, stereo, fill) local i = ctx.i local ec = ctx.ec local pulseCap = LOGN[i + 1] + LM * 8 local offset = (math.floor(pulseCap / 2)) - ((stereo and N == 2 and{QTHETA_OFFSET_TWOPHASE }or{QTHETA_OFFSET})[1]) 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 = math.floor(qn / 2 ) local ft = p0 * (x0 + 1) + x0 local fs = decDecode(ec, ft) local x if fs < (x0 + 1) * p0 then x = math.floor(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 = math.floor((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 =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 local function quantBandN1(X, Y, lowbandOut) local x = X local ec = ctx.ec for _ = 0, (Y >= 0 and 1 or 0) do local sign = 0 if ctx.remaining_bits >= 8 then sign = decBits(ec, 1) ctx.remaining_bits =ctx.remaining_bits- 8 end W[x + 1] = sign ~= 0 and-1 or 1 x = Y end if lowbandOut >= 0 then W[lowbandOut + 1] = W[X + 1] end return 1 end local function quantPartition(X, N, b, B, lowband, LM, gain, fill) 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 =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- math.floor(delta / 2 ^ (4 - LM) ) else delta = imin(0, delta + math.floor((N * 8) / 2 ^ (5 - LM))) end end local mbits = imax(0, imin(b, tdiv(b - delta, 2))) local sbits = b - mbits ctx.remaining_bits =ctx.remaining_bits- qalloc local nextLowband2 = (lowband >= 0 and((lowband + N ))or((-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 =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 =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 =ctx.remaining_bits- currBits while ctx.remaining_bits < 0 and q > 0 do ctx.remaining_bits =ctx.remaining_bits+ currBits q =q- 1 currBits = pulses2bits(i, LM, q) ctx.remaining_bits =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] = math.floor(signed32(seed) / 1048576 ) end cm = cmMask else for j = 0, N - 1 do seed = lcg(seed) local tmp = band(seed, 0x8000) ~= 0 and 1 / 256 or-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 local function quantBand(X, N, b, B, lowband, LM, lowbandOut, gain, lowbandScratch, fill) 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 = math.floor(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 =timeDivide+ 1 tfChange =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 local function stereoMerge(X, Y, mid, N) local xp, side = 0, 0 for j = 1, N do local y = W[Y + j] xp =xp+ y * W[X + j] side =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 local function quantBandStereo(X, Y, N, b, B, lowband, LM, lowbandOut, lowbandScratch, fill) 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 =mbits- sbits local c = itheta > 8192 ctx.remaining_bits =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 =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 =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 =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 local function quantAllBands(start, endb, hasY, N, collapse, pulses, shortBlocks, spread, dualStereo, intensity, tfRes, totalBits, balance, ec, LM, codedBands, seed, disableInv) local M = lshift(1, LM) local B = (shortBlocks and{M }or{1 })[1] local normOffset = M * EB[start + 1] local C = hasY and 2 or 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 = (hasY and((N + M * EB[i + 1] ))or((-1 ))) local Nb = M * EB[i + 2] - M * EB[i + 1] local t = tellFrac(ec) if i ~= start then balance =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 =foldStart- 1 until M * EB[foldStart + 1] <= effectiveLowband + normOffset local foldEnd = lowbandOffset - 1 repeat foldEnd =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 =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, math.floor(b / 2), B, (effectiveLowband ~= -1 and((norm + effectiveLowband ))or((-1))), LM, last and-1 or norm + M * EB[i + 1] - normOffset, 1, lowbandScratch, xcm) ycm = quantBand(Y, Nb, math.floor(b / 2), B, (effectiveLowband ~= -1 and((norm2 + effectiveLowband ))or((-1))), LM, last and-1 or norm2 + M * EB[i + 1] - normOffset, 1, lowbandScratch, ycm) else local lb = (effectiveLowband ~= -1 and((norm + effectiveLowband ))or((-1 ))) local lo = last and-1 or 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 =balance+ (pulses[i + 1] + t ) updateLowband = b > Nb * 8 ctx.avoid_split_noise = false end return ctx.seed end local function antiCollapse(st, C, size, LM, start, endb, collapse, pulses, seed) 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(math.floor((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 =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] = (band(seed, 0x8000) ~= 0 and{r }or{(-r )})[1] end renorm = true end end if renorm then renormaliseVector(X, N0 * 2 ^ LM, 1) end end end end local function denormaliseBands(X, freq, logE, eoff, start, endb, M, silence) 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 =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 =f+ 1 x =x+ 1 end end for k = bound + 1, N do freq[k] = 0 end end local function celtSynthesis(st, C, CC, start, effEnd, isTransient, LM, silence, N) 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) local function combFilter(mem, base, T0, T1, N, g0, g1, tapset0, tapset1, overlap) 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 =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 local function deemphasis(st, CC, N, pcm, pbase, accum) 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]=pcm[y]+ tmp * (1 / 32768) y =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 =y+ CC end end st.preemph[c + 1] = m end end local function resetState(st) 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) function Celt.new(channels) 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) local function decodeLost(st, N, LM) 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 =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] = math.floor(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) function Celt.decode(st, buf, off, len, pcm, pbase, frameSize, dec, accum) 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 =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 , off, len) end local ec = 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 =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 = (t + 3 <= totalBits and{(decBitLogp(ec, 3) )}or{false })[1] if not intraEner and st.loss_duration ~= 0 then local missing = imin(10, rshift(st.loss_duration, LM)) local safety = LM == 0 and 1.5 or(LM == 1 and 0.5 or 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 =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]=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 = isTransient and 2 or 4 local tfSelectRsv = LM > 0 and tt + logp + 1 <= budget if tfSelectRsv then budget =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 = isTransient and 4 or 5 end local tfSelect = 0 local row = TF_SELECT[LM + 1] local ti = isTransient and 4 or 0 if tfSelectRsv and row[ti + tfChanged + 1] ~= row[ti + 2 + tfChanged + 1] then tfSelect = decBitLogp(ec, 1) and 1 or 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 =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 =boost+ quanta totalBits =totalBits- quanta loopLogp = 1 end offsets[i + 1] = boost if boost > 0 then dynallocLogp = imax(2, dynallocLogp - 1) end end local allocTrim = (t + 48 <= totalBits and{(decIcdf(ec, TRIM_ICDF, 1, 7) )}or{5 })[1] local bits = len * 64 - tellFrac(ec) - 1 local antiCollapseRsv = isTransient and LM >= 2 and bits >= (LM + 2) * 8 and 8 or 0 bits =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"] = function() local __compat = __compat local bit32 = __compat.bit32 --!strict --!native --!optimize 2 -- 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) )-- 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 local function pvqU(n, k) return U[n * UK + k + 1] end local function imin(a, b) return (a < b and{a }or{b })[1]end local function imax(a, b) return (a > b and{a }or{b })[1]end local function tdiv(a, b) local q = a / b return (q >= 0 and{(floor(q) )}or{(-floor(-q) )})[1]end local function fracMul16(a, b) return math.floor((16384 + a * b) / 32768 )end local function bitexactCos(x) local x2 = math.floor((4096 + x * x) / 8192 ) x2 = (32767 - x2) + fracMul16(x2, (-7651 + fracMul16(x2, (8277 + fracMul16(-626, x2))))) return 1 + x2 end local function bitexactLog2tan(isin, icos) 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) local function laplaceEncode(enc, value, fs, decay) local fl = 0 local val = value if val ~= 0 then local s = val < 0 and-1 or 0 val = (val < 0 and{(-val )}or{val })[1] fl = fs fs = math.floor(((32768 - 32 - fs) * (16384 - decay)) / 32768 -- ec_laplace_get_freq1 ) local i = 1 while fs > 0 and i < val do fs =fs* 2 fl =fl+ (fs + 2 ) fs = math.floor((fs * decay) / 32768 ) i =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 =fl+ (2 * di + 1 + s) fs = imin(1, 32768 - fl) value = (s ~= 0 and{(-(i + di) )}or{(i + di )})[1] else fs =fs+ 1 if s == 0 then fl =fl+ fs end end end encEncodeBin(enc, fl, fl + fs, 15) return value end function CeltEncoder.new(channels) 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 local function quantCoarseEnergy(st, intra, enc, C, budget, nbBytes) local oldE, bandLogE, err = st.oldBandE, st.bandLogE, st.error local probBase = LM * 84 + (intra and 42 or 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 = (c == 0 and{prev0 }or{prev1 })[1] 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 =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, qi < 0 and 1 or 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 local function quantFineEnergy(st, fineQuant, enc, C) local oldE, err = st.oldBandE, st.error for i = 0, NB_EBANDS - 1 do local __DARKLUA_CONTINUE_8=false repeat local extra = fineQuant[i + 1] if extra <= 0 then __DARKLUA_CONTINUE_8=true break end if tell(enc) + C * extra > enc.storage * 8 then __DARKLUA_CONTINUE_8=true break 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]=oldE[k]+ offset err[k]=err[k]- offset end __DARKLUA_CONTINUE_8=true until true if not __DARKLUA_CONTINUE_8 then break end end end local function quantEnergyFinalise(st, fineQuant, finePriority, bitsLeft, enc, C) local oldE, err = st.oldBandE, st.error for prio = 0, 1 do local i = 0 while i < NB_EBANDS and bitsLeft >= C do local __DARKLUA_CONTINUE_11=false repeat if fineQuant[i + 1] >= MAX_FINE_BITS or finePriority[i + 1] ~= prio then i =i+ 1 __DARKLUA_CONTINUE_11=true break end for c = 0, C - 1 do local k = c * NB_EBANDS + i + 1 local q2 = err[k] < 0 and 0 or 1 encBits(enc, q2, 1) local offset = (q2 - 0.5) * 2 ^ (14 - fineQuant[i + 1] - 1) * (1 / 16384) oldE[k]=oldE[k]+ offset err[k]=err[k]- offset bitsLeft =bitsLeft- 1 end i =i+ 1 __DARKLUA_CONTINUE_11=true until true if not __DARKLUA_CONTINUE_11 then break end end end end local function bits2pulses(bandI, lm, bits) local base = CACHE_INDEX[(lm + 1) * NB_EBANDS + bandI + 1] local lo, hi = 0, CACHE_BITS[base + 1] bits =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 = lo == 0 and-1 or CACHE_BITS[base + lo + 1] if bits - loBits <= CACHE_BITS[base + hi + 1] - bits then return lo end return hi end local function pulses2bits(bandI, lm, pulses) 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 local function getPulses(i) 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 local function computeAllocation(offsets, cap, allocTrim, total, pulses, ebits, finePriority, C, enc, wantDual) local start, endb = 0, NB_EBANDS total = imax(total, 0) local len = NB_EBANDS local skipStart = start local skipRsv = total >= 8 and 8 or 0 total =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 =total- intensityRsv dualStereoRsv = total >= 8 and 8 or 0 total =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, math.floor((3 * w * 2 ^ LM * 8) / 16)) trimOffset[j + 1] = math.floor((C * w * (allocTrim - 5 - LM) * (endb - j - 1) * 2 ^ (LM + BITRES)) / 64 ) if w * 2 ^ LM == 1 then do local __DARKLUA_VAR=j + 1 trimOffset[__DARKLUA_VAR]=trimOffset[__DARKLUA_VAR]- C * 8 end 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 = math.floor((C * Nw * ALLOC[mid * len + j + 1] * 2 ^ LM) / 4 ) if bitsj > 0 then bitsj = imax(0, bitsj + trimOffset[j + 1]) end bitsj =bitsj+ offsets[j + 1] if bitsj >= thresh[j + 1] or done then done = true psum =psum+ imin(bitsj, cap[j + 1]) elseif bitsj >= C * 8 then psum =psum+ C * 8 end end if psum > total then hi = mid - 1 else lo = mid + 1 end until lo > hi hi = lo lo =lo- 1 for j = start, endb - 1 do local Nw = EB[j + 2] - EB[j + 1] local bits1j = math.floor((C * Nw * ALLOC[lo * len + j + 1] * 2 ^ LM) / 4 ) local bits2j = (hi >= NB_ALLOC_VECTORS and{cap[j + 1] }or{(math.floor((C * Nw * ALLOC[hi * len + j + 1] * 2 ^ LM) / 4 ))})[1] 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 =bits1j+ offsets[j + 1] end bits2j =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 = C > 1 and 1 or 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] + math.floor((mid * bits2[j + 1]) / 64 ) if tmp >= thresh[j + 1] or done then done = true psum =psum+ imin(tmp, cap[j + 1]) elseif tmp >= allocFloor then psum =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] + math.floor((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 =psum+ tmp end local codedBands = endb while true do local j = codedBands - 1 if j <= skipStart then total =total+ skipRsv break end local left = total - psum local percoeff = math.floor(left / (EB[codedBands + 1] - EB[start + 1]) ) left =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 =psum- (bits[j + 1] + intensityRsv ) if intensityRsv > 0 then intensityRsv = LOG2_FRAC_TABLE[j - start + 1] end psum =psum+ intensityRsv if bandBits >= allocFloor then psum =psum+ allocFloor bits[j + 1] = allocFloor else bits[j + 1] = 0 end codedBands =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 =total+ dualStereoRsv dualStereoRsv = 0 end if dualStereoRsv > 0 then dualStereo = wantDual encBitLogp(enc, dualStereo, 1) end local left = total - psum local percoeff = math.floor(left / (EB[codedBands + 1] - EB[start + 1]) ) left =left- (EB[codedBands + 1] - EB[start + 1]) * percoeff for j = start, codedBands - 1 do do local __DARKLUA_VAR=j + 1 bits[__DARKLUA_VAR]=bits[__DARKLUA_VAR]+ percoeff * (EB[j + 2] - EB[j + 1]) end end for j = start, codedBands - 1 do local tmp = imin(left, EB[j + 2] - EB[j + 1]) do local __DARKLUA_VAR=j + 1 bits[__DARKLUA_VAR]=bits[__DARKLUA_VAR]+ tmp end left =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 + (C == 2 and Nw > 2 and not dualStereo and j < intensity and 1 or 0) local NClogN = den * (LOGN[j + 1] + logM) local offset = (math.floor(NClogN / 2)) - den * FINE_OFFSET if Nw == 2 then offset =offset+ math.floor((den * 8) / 4 ) end if bits[j + 1] + offset < den * 2 * 8 then offset =offset+ math.floor(NClogN / 4 ) elseif bits[j + 1] + offset < den * 3 * 8 then offset =offset+ math.floor(NClogN / 8 ) end local eb = imax(0, bits[j + 1] + offset + den * 4) eb = math.floor((math.floor(eb / den)) / 8 ) if C * eb > (math.floor(bits[j + 1] / 8)) then eb = math.floor((math.floor(bits[j + 1] / 2 ^ stereo)) / 8 ) end eb = imin(eb, MAX_FINE_BITS) finePriority[j + 1] = eb * (den * 8) >= bits[j + 1] + offset and 1 or 0 do local __DARKLUA_VAR=j + 1 bits[__DARKLUA_VAR]=bits[__DARKLUA_VAR]- C * eb * 8 end 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(math.floor(excess / 2 ^ (stereo + BITRES)), MAX_FINE_BITS - ebits[j + 1]) do local __DARKLUA_VAR=j + 1 ebits[__DARKLUA_VAR]=ebits[__DARKLUA_VAR]+ extraFine end local extraBits = extraFine * C * 8 finePriority[j + 1] = extraBits >= excess - balance and 1 or 0 excess =excess- extraBits end balance = excess j =j+ 1 end while j < endb do ebits[j + 1] = math.floor((math.floor(bits[j + 1] / 2 ^ stereo)) / 8 ) bits[j + 1] = 0 finePriority[j + 1] = ebits[j + 1] < 1 and 1 or 0 j =j+ 1 end return codedBands, balance, intensity, dualStereo end -- icwrs: the index of the pulse vector iy[1..n] local function icwrs(n, iy) local j = n -- 1-based position of _y[n - 1] local i = iy[j] < 0 and 1 or 0 local k = math.abs(iy[j]) repeat j =j- 1 local nn = n - (j - 1) -- _n - j with 0-based j i =i+ pvqU(nn, k) k =k+ math.abs(iy[j]) if iy[j] < 0 then i =i+ pvqU(nn, k + 1) end until j <= 1 return i end local function expRotation1(X, xo, len, stride, c, s) 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 =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 =p- 1 end end -- exp_rotation(X, len, dir = 1, stride, K, spread): the encoder's spreading rotation local function expRotation(X, xo, len, stride, K, spread) 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 =stride2+ 1 end end len = math.floor(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] local function pvqSearch(X, xo, n, K, iy, y, absx) 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] = (v < 0 and{(-v )}or{v })[1] sign[j] = 0 iy[j] = 0 end if K > rshift(n, 1) then local sum = 0 for j = 1, n do sum =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 =yy+ p * p xy =xy+ absx[j] * p sign[j] = 2 * p pulsesLeft =pulsesLeft- p end end if pulsesLeft > n + 3 then yy =yy+ (pulsesLeft * pulsesLeft + pulsesLeft * sign[1] ) iy[1]=iy[1]+ pulsesLeft pulsesLeft = 0 end for _ = 1, pulsesLeft do yy =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 =xy+ absx[best] yy =yy+ sign[best] sign[best]=sign[best]+ 2 iy[best]=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) local function algQuant(st, X, xo, n, K, 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 local function computeQn(n, b, offset, pulseCap) 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) local function quantPartition(st, bandI, X, xo, n, b, lm, 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 =lm- 1 -- compute_theta (mono split, B0 = 1: triangular pdf) local pulseCap = LOGN[bandI + 1] + lm * 8 local offset = (math.floor(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 =emid+ X[xo + j] * X[xo + j] eside =eside+ X[yo + j] * X[yo + j] end local it = floor(0.5 + 16384 * 0.63662 * atan2(sqrt(eside), sqrt(emid))) itheta = math.floor((it * qn + 8192) / 16384 ) local h = rshift(qn, 1) local ft = (h + 1) * (h + 1) local fs = (itheta <= h and((itheta + 1 ))or((qn + 1 - itheta ))) local fl = (itheta <= h and{(rshift(itheta * (itheta + 1), 1) )}or{(ft - rshift((qn + 1 - itheta) * (qn + 2 - itheta), 1) )})[1] encEncode(enc, fl, fl + fs, ft) itheta = math.floor((itheta * 16384) / qn ) end local qalloc = tellFrac(enc) - t0 b =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 =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 =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 =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 =st.remaining- currBits while st.remaining < 0 and q > 0 do st.remaining =st.remaining+ currBits q =q- 1 currBits = pulses2bits(bandI, lm, q) st.remaining =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) local function quantBandStereo(st, i, n, xo, b, enc) local L, R = st.X[1], st.X[2] local pulseCap = LOGN[i + 1] + LM * 8 local offset = (math.floor(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 =emid+ m * m eside =eside+ sd * sd end local itheta = floor(0.5 + 16384 * 0.63662 * atan2(sqrt(eside), sqrt(emid))) local t0 = tellFrac(enc) 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 = math.floor((itheta * qn + 8192) / 16384 ) local p0 = 3 local x0 = math.floor(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 = math.floor((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 =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 =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 =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 =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 local function quantAllBands(st, C, pulses, dualStereo, totalBits, balance, enc, codedBands, intensity) 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 =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, math.floor(b / 2), LM, enc) quantPartition(st, i, st.X[2], xo, nb, math.floor(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 =balance+ (pulses[i + 1] + t ) end end function CeltEncoder.encodeFrame(st, pcm, base, stride, nbBytes) 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 =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]=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 =enc.nbits_total+ (totalBits - tell(enc) ) RE.done(enc) for i = 1, 2 * NB_EBANDS do oldE[i] = -28 end st.frames =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 =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 =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() --!strict -- 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"] = function() local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict --!native --!optimize 2 -- 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) function Decoder.new(channels) 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 function Decoder.reset(st) 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 local function smoothFade(in1, b1, in2, b2, out, bo, overlap, ch) for c = 0, ch - 1 do for i = 0, overlap - 1 do local w = WINDOW[i + 1] w =w* w local k = i * ch + c out[bo + k] = w * in2[b2 + k] + (1 - w) * in1[b1 + k] end end end local function decodeFrame(st, buf, off, len, pcm, pbase, frameSize) 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 = (st.prev_redundancy and{MODE_CELT }or{st.prev_mode })[1] 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 =pbase+ ret * ch audiosize =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, math.floor(1000 * audiosize / 48000)) if data then ctrl.nChannelsInternal = st.stream_channels if mode == MODE_SILK then ctrl.internalSampleRate = bandwidth == BW_NB and 8000 or(bandwidth == BW_MB and 12000 or 16000 ) else ctrl.internalSampleRate = 16000 end end local lost = data == nil and 1 or 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 =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 + (mode == MODE_HYBRID and 20 or 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 = (mode == MODE_HYBRID and{(RD.uint(dec, 256) + 2 )}or{(len - bit32.rshift(RD.tell(dec) + 7, 3) )})[1] len =len- redundancyBytes if len * 8 < RD.tell(dec) then len = 0 redundancyBytes = 0 redundancy = false end dec.storage =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"] = bandwidth == BW_NB and 13 or((bandwidth == BW_MB or bandwidth == BW_WB )and 17 or(bandwidth == BW_SWB and 19 or 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, (data and{dec }or{nil})[1], 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 = (data and{dec.rng }or{0 })[1] 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) function Decoder.decode(st, buf, off, len, pcm, pbase, frameSize, selfDelimited) 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 (ret < 0 and{ret }or{(-3)})[1], 0 end count =count+ ret until count >= frameSize st.last_packet_duration = count return count, 0 end local b = buf 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 =nb+ ret end st.last_packet_duration = nb return nb, packetOffset end -- multistream (channel mapping families 0 / 1 / 255) function Decoder.newMultistream(channels, streams, coupled, mapping) local decs = {} for s = 0, streams - 1 do decs[s + 1] = Decoder.new(s < coupled and 2 or 1) end return { channels = channels, streams = streams, coupled = coupled, mapping = mapping, decoders = decs, tmp = table.create(5760 * 2, 0), } end function Decoder.resetMultistream(ms) for _, d in __iter(ms.decoders) do Decoder.reset(d) end end local function copyOut(ms, id, src, sc, sstride, pcm, pbase, n) 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 =o+ nch s =s+ sstride end end end end -- opus_multistream_decode_native function Decoder.decodeMultistream(ms, buf, off, len, pcm, pbase, frameSize) 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, (doPlc and{nil }or{buf})[1], off, doPlc and 0 or len, tmp, 1, frameSize, s ~= ms.streams - 1) if not doPlc then off =off+ packetOffset len =len- packetOffset end if ret <= 0 then return (ret < 0 and{ret }or{(-3 )})[1] 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 =o+ nch end end end return frameSize end function Decoder.writeF32(src, base, count, gain, out, o) local writef32 = buffer.writef32 if gain == 1 then for i = base + 1, base + count do writef32(out, o, src[i]) o =o+ 4 end else for i = base + 1, base + count do writef32(out, o, src[i] * gain) o =o+ 4 end end end function Decoder.writeDownmix(src, base, n, srcCh, matrix, gain, out, o) 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 =l+ v * matrix[c * 2 + 1] r =r+ v * matrix[c * 2 + 2] end writef32(out, o, l * gain) writef32(out, o + 4, r * gain) o =o+ 8 p =p+ srcCh end end return Decoder end __FILES["codecs/audio/Opus/Mdct"] = function() --!strict --!native --!optimize 2 -- 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 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 }, } local function bitrevTable(f, fout, fpos, fstride, factors, fi) 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 =fpos+ fstride end else for j = 0, p - 1 do bitrevTable(f, fout, fpos, fstride * p, factors, fi + 2) fpos =fpos+ fstride fout =fout+ m end end end local plans= {} for shift = 0, 3 do local N = math.floor(1920 / 2 ^ shift ) local n = math.floor(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 = math.floor(N / 2), math.floor(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 local function bfly2(fr, fi, N) 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]=fr[p]+ tr fi[p]=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 do local __DARKLUA_VAR=p + 1 fr[__DARKLUA_VAR]=fr[__DARKLUA_VAR]+ tr end do local __DARKLUA_VAR0=p + 1 fi[__DARKLUA_VAR0]=fi[__DARKLUA_VAR0]+ ti end tr = fi[p + 6] ti = -fr[p + 6] fr[p + 6] = fr[p + 2] - tr fi[p + 6] = fi[p + 2] - ti do local __DARKLUA_VAR1=p + 2 fr[__DARKLUA_VAR1]=fr[__DARKLUA_VAR1]+ tr end do local __DARKLUA_VAR2=p + 2 fi[__DARKLUA_VAR2]=fi[__DARKLUA_VAR2]+ ti end 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 do local __DARKLUA_VAR3=p + 3 fr[__DARKLUA_VAR3]=fr[__DARKLUA_VAR3]+ tr end do local __DARKLUA_VAR4=p + 3 fi[__DARKLUA_VAR4]=fi[__DARKLUA_VAR4]+ ti end p =p+ 8 end end local function bfly4(fr, fi, fstride, twr, twi, m, N, mm) 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 =r0+ r2 i0 =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 =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 =f0r+ s1r f0i =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 =t1+ fstride t2 =t2+ fstride * 2 t3 =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 =p+ 1 end end end end local function bfly3(fr, fi, fstride, twr, twi, m, N, mm) 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 =t1+ fstride t2 =t2+ fstride * 2 local f0r, f0i = fr[p], fi[p] local fmr, fmi = f0r - s3r * 0.5, f0i - s3i * 0.5 s0r =s0r* epi3i s0i =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 =p+ 1 end end end local function bfly5(fr, fi, fstride, twr, twi, m, N, mm) 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 =p0+ 1 p1 =p1+ 1 p2 =p2+ 1 p3 =p3+ 1 p4 =p4+ 1 end end end -- opus_fft_impl (bit-reversed input) local function fftImpl(pl) 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 =L+ 1 until m == 1 m = factors[2 * L] for i = L - 1, 0, -1 do local m2 = (i ~= 0 and{factors[2 * i] }or{1 })[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 function Mdct.backward(inp, inBase, out, outBase, window, overlap, shift, stride) 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 =xp1+ 2 * stride xp2 =xp2- 2 * stride end fftImpl(pl) local h = outBase + (math.floor(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, math.floor(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 =xp- 1 yp =yp+ 1 end end return Mdct end __FILES["codecs/audio/Opus/Packet"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 -- 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 function Packet.mode(toc) 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 function Packet.bandwidth(toc) 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 band(toc, 0x10) ~= 0 and 1105 or 1104 else return 1101 + band(rshift(toc, 5), 3) end end function Packet.channels(toc) return band(toc, 4) ~= 0 and 2 or 1 end function Packet.samplesPerFrame(toc, Fs) if band(toc, 0x80) ~= 0 then local a = band(rshift(toc, 3), 3) return math.floor(bit32.lshift(Fs, a) / 400 ) elseif band(toc, 0x60) == 0x60 then return (band(toc, 0x08) ~= 0 and{(math.floor(Fs / 50 ))}or{(math.floor(Fs / 100 ))})[1] else local a = band(rshift(toc, 3), 3) if a == 3 then return math.floor(Fs * 60 / 1000 ) end return math.floor(bit32.lshift(Fs, a) / 100 ) end end function Packet.samples(buf, off, len) 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 local function parseSize(buf, p, len) 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 function Packet.parse(buf, off, len, offsets, sizes, selfDelimited) 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 =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 = math.floor(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 =len- bytes if s < 0 or s > len then return -1, toc, 0 end sizes[1] = s p =p+ bytes lastSize = len - s else if len < 1 then return -1, toc, 0 end local ch = readu8(buf, p) p =p+ 1 count = band(ch, 0x3F) if count <= 0 or framesize * count > 5760 then return -1, toc, 0 end len =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 =p+ 1 len =len- 1 local tmp = pb == 255 and 254 or pb len =len- tmp pad =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 =len- bytes if s < 0 or s > len then return -1, toc, 0 end sizes[i] = s p =p+ bytes lastSize =lastSize- (bytes + s ) end if lastSize < 0 then return -1, toc, 0 end elseif not selfDelimited then lastSize = math.floor(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 =len- bytes if s < 0 or s > len then return -1, toc, 0 end p =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 =p+ sizes[i] end return count, toc, pad + (p - off) end return Packet end __FILES["codecs/audio/Opus/Silk"] = function() local __compat = __compat local bit32, __iter = __compat.bit32, __compat.__iter --!strict --!native --!optimize 2 -- 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 local function p2(s) if s == 0 then return 1 end return P2[s] end local function s16(x) x = x % 65536 if x >= 32768 then return x - 65536 end return x end local function i32(x) x = x % 4294967296 if x >= 2147483648 then return x - 4294967296 end return x end local function sat16(x) if x > 32767 then return 32767 elseif x < -32768 then return -32768 end return x end local function addSat32(a, b) local s = a + b if s > 2147483647 then return 2147483647 elseif s < -2147483648 then return -2147483648 end return s end local function subSat32(a, b) 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 local function clz32(x) return countlz(x) end -- silk_SMULWW (64-bit form): (a * b) >> 16, exact local function mulww(a, b) return a * (math.floor(b / 65536)) + math.floor((a * (b % 65536)) / 65536 )end -- floor(a * b / 2^s) for int32 a, b and s >= 16, exact local function mulshr(a, b, s) local t = a * (math.floor(b / 65536)) + math.floor((a * (b % 65536)) / 65536 ) if s == 16 then return t end return math.floor(t / P2[s - 16] )end local function smmul(a, b) return mulshr(a, b, 32) end -- silk_RSHIFT_ROUND (shift >= 1) local function rround(a, s) return math.floor((a + p2(s - 1)) / P2[s] )end local function lshiftSat32(a, sh) if sh == 0 then return a end local m = P2[sh] local lo, hi = math.floor(-2147483648 / m), math.floor(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) local function tdiv(a, b) local q = a / b if q >= 0 then return floor(q) end return -floor(-q) end -- low 32 bits of a * b, as int32 local function imul32(a, b) a = a % 4294967296 local ah, al = math.floor(a / 65536), a % 65536 return i32(((ah * b) % 65536) * 65536 + al * b) end local function silkRand(seed) return i32(907633515 + imul32(seed, 196314165)) end local function rshift(a, s) if s == 0 then return a end return math.floor(a / P2[s] )end local function silkINVERSE32_varQ(b32, Qres) local b_headrm = clz32(math.abs(b32)) - 1 local b32_nrm = b32 * p2(b_headrm) local b32_inv = tdiv(536870911, math.floor(b32_nrm / 65536)) local result = b32_inv * 65536 local err_Q32 = i32((536870912 - math.floor((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 math.floor(result / P2[lshift] ) end return 0 end local function silkDIV32_varQ(a32, b32, Qres) 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, math.floor(b32_nrm / 65536)) local result = math.floor((a32_nrm * s16(b32_inv)) / 65536 ) a32_nrm = i32(a32_nrm - i32(smmul(b32_nrm, result) * 8)) result = result + math.floor((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 local function silkLog2lin(inLog_Q7) if inLog_Q7 < 0 then return 0 elseif inLog_Q7 >= 3967 then return 2147483647 end local out = p2(math.floor(inLog_Q7 / 128)) local frac_Q7 = inLog_Q7 % 128 local t = frac_Q7 + math.floor((frac_Q7 * (128 - frac_Q7) * -174) / 65536 ) if inLog_Q7 < 2048 then out = out + math.floor((out * t) / 128 ) else out = out + (math.floor(out / 128)) * t end return out end local function silkSQRT_APPROX(x) 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 = bit32.band(lz, 1) ~= 0 and 32768 or 46214 y = math.floor(y / p2(math.floor(lz / 2)) ) y = y + math.floor((y * (213 * frac_Q7)) / 65536 ) return y end -- silk_sum_sqr_shift: energy, shift local function sumSqrShift(x, xo, len) 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 =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 =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 local function bwexpander(ar, d, chirp_Q16) local chirp_minus_one_Q16 = chirp_Q16 - 65536 for i = 1, d - 1 do ar[i] = s16(math.floor((chirp_Q16 * ar[i] + 32768) / 65536)) chirp_Q16 =chirp_Q16+ math.floor((chirp_Q16 * chirp_minus_one_Q16 + 32768) / 65536 ) end ar[d] = s16(math.floor((chirp_Q16 * ar[d] + 32768) / 65536)) end local function bwexpander32(ar, d, chirp_Q16) 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+ math.floor((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) local function lpcFit(a_QOUT, a_QIN, QOUT, QIN, d) 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, math.floor((maxabs * (idx + 1)) / 4)) bwexpander32(a_QIN, d, chirp_Q16) else break end i =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) local function mulRound(a, b, Q) if Q == 1 then local p = a * b return math.floor(p / 2 )+ p % 2 end if Q - 1 >= 16 then return math.floor((mulshr(a, b, Q - 1) + 1) / 2 ) end return math.floor((math.floor((a * b) / P2[Q - 1] )+ 1) / 2 )end local function lpcInversePredGainQA(A_QA, order) 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, math.floor((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 =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 local function lpcInversePredGain(A_Q12, order) local DC_resp = 0 for k = 1, order do DC_resp =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 local function findPoly(out, cLSF, c0, dd) 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 - math.floor((ftmp * out[k + 1] + 32768) / 65536 ) for n = k, 2, -1 do do local __DARKLUA_VAR=n + 1 out[__DARKLUA_VAR]=out[__DARKLUA_VAR]+ (out[n - 1] - math.floor((ftmp * out[n] + 32768) / 65536 ))end end out[2]=out[2]- ftmp end end -- silk_NLSF2A: a_Q12 (1-based, d entries) from NLSF (1-based) local function nlsf2a(a_Q12, NLSF, d) local ordering = (d == 16 and{ordering16 }or{ordering10 })[1] for k = 1, d do local nl = NLSF[k] local f_int = math.floor(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] = math.floor((cos_val * 256 + delta * f_frac + 8) / 16 ) end local dd = math.floor(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(math.floor((a32_QA1[k] + 16) / 32)) end i =i+ 1 end end -- silk_LPC_analysis_filter: out[oo + ix] for ix in [0, len), from inp[io + ix]; B 1-based Q12 local function lpcAnalysisFilter(out, oo, inp, io, B, len, d) for ix = d, len - 1 do local base = io + ix - 1 local acc = 0 for j = 0, d - 1 do acc =acc+ inp[base - j] * B[j + 1] end local out32_Q12 = i32(inp[base + 1] * 4096 - acc) out[oo + ix] = sat16(math.floor((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) local function nlsfUnpack(CB, CB1_index) local order = CB.order local sel = CB.ec_sel local pq = CB.pred_Q8 local p = math.floor(CB1_index * order / 2 ) for i = 0, order - 1, 2 do p =p+ 1 local entry = sel[p] ec_ix[i + 1] = (bit32.band(math.floor(entry / 2), 7)) * 9 pred_Q8[i + 1] = pq[i + bit32.band(entry, 1) * (order - 1) + 1] ec_ix[i + 2] = (bit32.band(math.floor(entry / 32), 7)) * 9 pred_Q8[i + 2] = pq[i + bit32.band(math.floor(entry / 16), 1) * (order - 1) + 2] end end local function nlsfStabilize(NLSF, NDeltaMin, L) 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 =min_center+ NDeltaMin[k + 1] end min_center =min_center+ math.floor(NDeltaMin[I + 1] / 2 ) local max_center = 32768 for k = L, I + 1, -1 do max_center =max_center- NDeltaMin[k + 1] end max_center =max_center- math.floor(NDeltaMin[I + 1] / 2 ) local c = math.floor((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 - math.floor(NDeltaMin[I + 1] / 2)) NLSF[I + 1] = s16(NLSF[I] + NDeltaMin[I + 1]) end loops =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 =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) local function nlsfDecode(pNLSF_Q15, NLSFIndices, CB) 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 = math.floor((out_Q10 * pred_Q8[i + 1]) / 256 ) out_Q10 = NLSFIndices[i + 2] * 1024 if out_Q10 > 0 then out_Q10 =out_Q10- 102 elseif out_Q10 < 0 then out_Q10 =out_Q10+ 102 end out_Q10 = pred + math.floor((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 }, } local function rateID(R) local a = math.floor(R / 4096 )- (R > 16000 and 1 or 0) if R > 24000 then a = math.floor(a / 2 ) end return math.min(5, a - 1) end local function newResampler() 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 local function copyResampler(dst, src) 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 local function resamplerInit(S, Fs_Hz_in, Fs_Hz_out) 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 = math.floor(Fs_Hz_in / 1000 ) S.Fs_out_kHz = math.floor(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 = math.floor((Fs_Hz_in * p2(14 + up2x)) / Fs_Hz_out )* 4 while mulww(inv, Fs_Hz_out) < Fs_Hz_in * p2(up2x) do inv =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] local function up2HQ(S, out, oo, inp, io, len) 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 = math.floor((Y * c00) / 65536 ) local out32_1 = s0 + X s0 = in32 + X Y = out32_1 - s1 X = math.floor((Y * c01) / 65536 ) local out32_2 = s1 + X s1 = out32_1 + X Y = out32_2 - s2 X = Y + math.floor((Y * c02) / 65536 ) out32_1 = s2 + X s2 = out32_2 + X out[oo + 2 * k] = sat16(math.floor((out32_1 + 512) / 1024)) Y = in32 - s3 X = math.floor((Y * c10) / 65536 ) out32_1 = s3 + X s3 = in32 + X Y = out32_1 - s4 X = math.floor((Y * c11) / 65536 ) out32_2 = s4 + X s4 = out32_1 + X Y = out32_2 - s5 X = Y + math.floor((Y * c12) / 65536 ) out32_1 = s5 + X s5 = out32_2 + X out[oo + 2 * k + 1] = sat16(math.floor((out32_1 + 512) / 1024)) end S[1], S[2], S[3], S[4], S[5], S[6] = s0, s1, s2, s3, s4, s5 end local function iirFirInterpol(out, oo, buf, max_index_Q16, incr) local index_Q16 = 0 while index_Q16 < max_index_Q16 do local ti = math.floor(((index_Q16 % 65536) * 12) / 65536 ) local b = math.floor(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(math.floor((res_Q15 + 16384) / 32768)) oo =oo+ 1 index_Q16 =index_Q16+ incr end return oo end local function iirFir(S, out, oo, inp, io, inLen) 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 =io+ nSamplesIn inLen =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 local function resampleBlock(S, out, oo, inp, io, len) 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] local function resampler(S, out, inp, io, inLen) 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 local function newChannel() 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 local function decoderSetFs(ch, fs_kHz, fs_API_Hz) 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 =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 = (ch.nb_subfr == 4 and{T.pitch_contour_NB_iCDF }or{T.pitch_contour_10_ms_NB_iCDF })[1] else ch.pitch_contour_iCDF = (ch.nb_subfr == 4 and{T.pitch_contour_iCDF }or{T.pitch_contour_10_ms_iCDF })[1] 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 } local function decodeIndices(ch, d, FrameIndex, decode_LBRR, condCoding) 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 = math.floor(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]=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, (math.floor(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 =Ix- icdf(d, T.NLSF_EXT_iCDF, 1, 8) elseif Ix == 8 then Ix =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) * (math.floor(ch.fs_kHz / 2)) ind.lagIndex =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 local function split(d, p, tab) if p > 0 then local a = icdf(d, tab, shellOff[p + 1] + 1, 8) return a, p - a end return 0, 0 end local function shellDecoder(out, o, d, pulses4) 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)] local function decodePulses(d, pulses, signalType, quantOffsetType, frame_length) local RateLevelIndex = icdf(d, T.rate_levels_iCDF, (math.floor(signalType / 2)) * 9 + 1, 8) local iter = math.floor(frame_length / 16 ) if iter * 16 < frame_length then iter =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]=nLshifts[i]+ 1 s = icdf(d, ppb, 9 * 18 + 1 + (nLshifts[i] == 10 and 1 or 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]=sum_pulses[i]+ nLS * 32 end end -- silk_decode_signs local signTab = T.sign_iCDF local base = 7 * (quantOffsetType + signalType * 2) local blocks = math.floor((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) local function gainsDequant(gain_Q16, ind, ch, conditional, nb_subfr) 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 =prev+ (ind_tmp * 2 - thr ) else prev =prev+ ind_tmp end end if prev < 0 then prev = 0 elseif prev > 63 then prev = 63 end gain_Q16[k] = silkLog2lin(math.min(math.floor((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 } }, } local function decodeParameters(ch, ctrl, condCoding) 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] + math.floor((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[fs == 8 and 8 or 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] local function decodeCore(ch, ctrl, xq, xo, pulses) local ind = ch.indices local exc = ch.exc_Q14 local offset_Q10 = QuantOffsets[math.floor(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 =e- 1280 elseif e < 0 then e =e+ 1280 end e =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[math.floor(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 = math.floor(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 = (math.floor((inv_gain_Q31 * ctrl.LTP_scale_Q14) / 65536)) * 4 end for i = 0, lag + 1 do sLTP_Q15[sLTP_buf_idx - i] = math.floor((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 =pred+ math.floor((sLTP_Q15[pl] * b0) / 65536 ) pred =pred+ math.floor((sLTP_Q15[pl - 1] * b1) / 65536 ) pred =pred+ math.floor((sLTP_Q15[pl - 2] * b2) / 65536 ) pred =pred+ math.floor((sLTP_Q15[pl - 3] * b3) / 65536 ) pred =pred+ math.floor((sLTP_Q15[pl - 4] * b4) / 65536 ) pl =pl+ 1 local r = exc[pexc + i] + pred * 2 res_Q14[i] = r sLTP_buf_idx =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 = math.floor(order / 2 ) pred =pred+ math.floor((sLPC_Q14[j - 1] * a0) / 65536 ) pred =pred+ math.floor((sLPC_Q14[j - 2] * a1) / 65536 ) pred =pred+ math.floor((sLPC_Q14[j - 3] * a2) / 65536 ) pred =pred+ math.floor((sLPC_Q14[j - 4] * a3) / 65536 ) pred =pred+ math.floor((sLPC_Q14[j - 5] * a4) / 65536 ) pred =pred+ math.floor((sLPC_Q14[j - 6] * a5) / 65536 ) pred =pred+ math.floor((sLPC_Q14[j - 7] * a6) / 65536 ) pred =pred+ math.floor((sLPC_Q14[j - 8] * a7) / 65536 ) pred =pred+ math.floor((sLPC_Q14[j - 9] * a8) / 65536 ) pred =pred+ math.floor((sLPC_Q14[j - 10] * a9) / 65536 ) if wide then pred =pred+ math.floor((sLPC_Q14[j - 11] * a10) / 65536 ) pred =pred+ math.floor((sLPC_Q14[j - 12] * a11) / 65536 ) pred =pred+ math.floor((sLPC_Q14[j - 13] * a12) / 65536 ) pred =pred+ math.floor((sLPC_Q14[j - 14] * a13) / 65536 ) pred =pred+ math.floor((sLPC_Q14[j - 15] * a14) / 65536 ) pred =pred+ math.floor((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(math.floor((mulww(v, Gain_Q10) + 128) / 256)) end for i = 1, 16 do sLPC_Q14[i] = sLPC_Q14[subfr_length + i] end pexc =pexc+ subfr_length pxq =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 } local function plcReset(ch) 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 local function cngReset(ch) local step = tdiv(32767, ch.LPC_order + 1) local acc = 0 local cng = ch.sCNG for i = 1, ch.LPC_order do acc =acc+ step cng.CNG_smth_NLSF_Q15[i] = acc end cng.CNG_smth_Gain_Q16 = 0 cng.rand_seed = 3176576 end local function plcUpdate(ch, ctrl) 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 =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 =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] = math.floor((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] = math.floor((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) local function plcConceal(ch, ctrl, frame, fo) local plc = ch.sPLC local ltp_mem_length = ch.ltp_mem_length local order = ch.LPC_order local prevGain_Q10_0 = math.floor(plc.prevGain_Q16[1] / 64 ) local prevGain_Q10_1 = math.floor(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 = (k == 0 and{prevGain_Q10_0 }or{prevGain_Q10_1 })[1] for i = 0, sl - 1 do excBuf[k * sl + i + 1] = sat16(math.floor(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 = (ch.prevSignalType == 2 and{PLC_RAND_ATTENUATE_V_Q15[att] }or{PLC_RAND_ATTENUATE_UV_Q15[att] })[1] 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 =rand_scale_Q14- B[i] end rand_scale_Q14 = math.max(3277, s16(rand_scale_Q14)) rand_scale_Q14 = s16(math.floor((rand_scale_Q14 * s16(plc.prevLTP_scale_Q14)) / 16384)) else local invGain_Q30 = lpcInversePredGain(plc.prevLPC_Q12, order) local down = math.min(math.floor(1073741824 / 8), invGain_Q30) down = math.max(math.floor(1073741824 / 256), down) down = down * 8 rand_Gain_Q15 = math.floor((math.floor((down * s16(rand_Gain_Q15)) / 65536)) / 16384 ) end end local rand_seed = plc.rand_seed local lag = math.floor((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] = math.floor((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 =pred+ math.floor((plcLTP_Q14[pl] * b0) / 65536 ) pred =pred+ math.floor((plcLTP_Q14[pl - 1] * b1) / 65536 ) pred =pred+ math.floor((plcLTP_Q14[pl - 2] * b2) / 65536 ) pred =pred+ math.floor((plcLTP_Q14[pl - 3] * b3) / 65536 ) pred =pred+ math.floor((plcLTP_Q14[pl - 4] * b4) / 65536 ) pl =pl+ 1 rand_seed = silkRand(rand_seed) local ri = (math.floor(rand_seed / 33554432)) % 128 sLTP_buf_idx =sLTP_buf_idx+ 1 plcLTP_Q14[sLTP_buf_idx] = i32((pred + math.floor((exc[rand_off + ri + 1] * s16(rand_scale_Q14)) / 65536)) * 4) end for j = 1, 5 do B[j] = math.floor((harm_Gain_Q15 * s16(B[j])) / 32768 ) end rand_scale_Q14 = math.floor((s16(rand_scale_Q14) * s16(rand_Gain_Q15)) / 32768 ) plc.pitchL_Q8 = plc.pitchL_Q8 + math.floor((plc.pitchL_Q8 * 655) / 65536 ) plc.pitchL_Q8 = math.min(plc.pitchL_Q8, 18 * ch.fs_kHz * 256) lag = math.floor((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 = math.floor(order / 2 ) for t = 1, order do pred =pred+ math.floor((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(math.floor((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 local function plcGlueFrames(ch, frame, fo, length) 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] = math.floor((gain_Q16 * frame[fo + i]) / 65536 ) gain_Q16 =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) local function cng(ch, ctrl, frame, fo, length) 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]=sm[i]+ math.floor(((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 =c.CNG_smth_Gain_Q16+ math.floor(((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 = (math.floor(gain_Q16 / 65536)) * (math.floor(gain_Q16 / 65536)) gain_Q16 = i32((math.floor(c.CNG_smth_Gain_Q16 / 65536)) * (math.floor(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 = math.floor(gain_Q16 / 64 ) -- silk_CNG_exc local exc_mask = 255 while exc_mask > length do exc_mask =math.floor(exc_mask/ 2 ) end local seed = c.rand_seed for i = 1, length do seed = silkRand(seed) local idx = bit32.band((math.floor(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 = math.floor(order / 2 ) for t = 1, order do pred =pred+ math.floor((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(math.floor((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 ..] local function decodeFrame(ch, d, out, fo, lostFlag, condCoding) 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 =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 local function stereoDecodePred(d, pred_Q13) local n = icdf(d, T.stereo_pred_joint_iCDF, 1, 8) local ix02 = math.floor(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 = (c == 1 and((ix00 + 3 * ix02 ))or((ix10 + 3 * ix12 ))) local b = (c == 1 and{ix01 }or{ix11 })[1] local low_Q13 = q[a + 1] local step_Q13 = math.floor(((q[a + 2] - low_Q13) * 6554) / 65536 ) pred_Q13[c] = low_Q13 + s16(step_Q13) * (2 * b + 1) end pred_Q13[1]=pred_Q13[1]- pred_Q13[2] end -- x1, x2: samplesOut1_tmp arrays (C index j at [j + 1]) local function stereoMSToLR(state, x1, x2, pred_Q13, fs_kHz, frame_length) 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 = math.floor((s16(pred_Q13[1] - pred0) * s16(denom_Q16) + 32768) / 65536 ) local delta1 = math.floor((s16(pred_Q13[2] - pred1) * s16(denom_Q16) + 32768) / 65536 ) for n = 0, frame_length - 1 do if n < interp then pred0 =pred0+ delta0 pred1 =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 + math.floor((sum * s16(pred0)) / 65536 ) sum = sum + math.floor(((x1[n + 2] * 2048) * s16(pred1)) / 65536 ) x2[n + 2] = sat16(math.floor((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 function Silk.new(apiChannels) 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) function Silk.reset(st) st.ch[1] = newChannel() st.ch[2] = newChannel() for _, ch in __iter(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 local function initChannel(st, n) local ch = newChannel() cngReset(ch) plcReset(ch) st.ch[n] = ch end function Silk.decode(st, ctrl, lostFlag, firstFrame, d, out, outBase) 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 = math.floor(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 =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] = bitLogp(d, 1) and 1 or 0 end ch.LBRR_flag = bitLogp(d, 1) and 1 or 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 = i > 0 and ch.LBRR_flags[i] ~= 0 and 2 or 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 = ch.LBRR_flags[FrameIndex] ~= 0 and 2 or 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 =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 = math.floor((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 function Silk.prevPitchLag(st) local ch = st.ch[1] if ch.prevSignalType == 2 then local mult = { 6, 4, 3 } return ch.lagPrev * mult[math.floor((ch.fs_kHz - 8) / 4 )+ 1] end return 0 end return Silk end __FILES["codecs/audio/Opus/SilkTables"] = function() --!strict --!optimize 2 -- 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 __FILES["codecs/audio/Pcm"] = function() local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict -- 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 } local function audioRead(self, n, out) 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 = (out and buffer.len(out) >= bytes and{out }or{(buffer.create(bytes) )})[1] buffer.copy(b, 0, a.samples, self._pos * ch * 4, bytes) self._pos =self._pos+ n return b, n end local function decoderRead(self, n, out) 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 = math.floor(buffer.len(b) / (ch * 4) ) end return b, got end function Pcm.source(v) 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 } , nil end if type(v.read) == "function" then local frames = (type(v.frames) == "number" and v.frames > 0 and{v.frames }or{0 })[1] return { sampleRate = sr, channels = ch, frames = frames, tags = v.tags or {}, read = decoderRead, _dec = v, _done = false } , nil end return nil, Err.new(Err.ARG, "needs an Audio or an audio Decoder") end function Pcm.collect(src, maxFrames) 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= 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 =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, source, maxFrames) 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, offset, frames, channels, sampleRate, fmt, tags) 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, n, out) n = math.clamp(math.floor(n), 0, frames - pos) local bytes = n * channels * 4 local b = (out and buffer.len(out) >= bytes and{out }or{(buffer.create(bytes) )})[1] if n > 0 then Convert.decode(buf, offset + pos * frameBytes, fmt, n * channels, b, 0) pos =pos+ n end return b, n end function dec.seek(_self, seconds) local f = math.floor(seconds * sampleRate + 0.5) pos = f ~= f and 0 or math.clamp(f, 0, frames) end function dec.position(_self) return pos / sampleRate end return dec , nil end function Pcm.audioDecoder(a) local d = (Pcm.rawDecoder(a.samples, 0, a.frames, a.channels, a.sampleRate, "f32le", a.tags) ) d.bitrate = a.sampleRate * a.channels * 32 return d end function Pcm.encode(src, fmt, w) 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= 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 =total+ n end if src.err then return nil, src.err end return total, nil end function Pcm.reorder(buf, offset, frames, channels, map) 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, bits) 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, bits) return v / 2 ^ (bits - 1) end return Pcm end __FILES["codecs/audio/Pcm/Convert"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 -- 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= { 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 =t+ 8 elseif seg == 1 then t =t+ 0x108 else t = (t + 0x108) * 2 ^ (seg - 1) end ALAW[code + 1] = (bit32.band(a, 0x80) ~= 0 and{t }or{(-t )})[1] 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] = (bit32.band(u, 0x80) ~= 0 and((0x84 - m ))or((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 } local function segment(v, ends) for i = 1, 8 do if v <= ends[i] then return i - 1 end end return 8 end local function alawEncode(pcm) 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 =aval+ bit32.band(floor(v / 2), 0x0F) else aval =aval+ bit32.band(floor(v / 2 ^ seg), 0x0F) end end return bit32.bxor(aval, mask) end local function ulawEncode(pcm) 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 =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 function Convert.decode(src, so, fmt, count, dst, d) 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 =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 =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 local function q(x, s) 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 function Convert.encode(src, so, count, fmt, dst, d) 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 + math.floor(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, (math.floor(v / 256)) % 256) writeu8(dst, p + 2, math.floor(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, math.floor(v / 65536)) writeu8(dst, p + 1, (math.floor(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"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 -- 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, } local function be32(b, p) return byteswap(readu32(b, p)) end local function s16(v) return (v >= 32768 and((v - 65536 ))or(v ))end function Qoa.frameSize(ch, slices) return 8 + 16 * ch + 8 * slices * ch end function Qoa.frameInfo(b, p, avail) 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 = math.floor((samples + 19) / 20 ) local head = 8 + 16 * ch if slices > 256 or size < head or slices * ch > math.floor((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 function Qoa.decodeFrame(b, p, avail, dst, d) local info, msg = Qoa.frameInfo(b, p, avail) if not info then return nil, msg 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 = math.floor((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 =o+ os local delta = math.floor(dq / 16 ) w0 =w0+ (h0 < 0 and{(-delta )}or{delta })[1] w1 =w1+ (h1 < 0 and{(-delta )}or{delta })[1] w2 =w2+ (h2 < 0 and{(-delta )}or{delta })[1] w3 =w3+ (h3 < 0 and{(-delta )}or{delta })[1] h0, h1, h2, h3 = h1, h2, h3, r end s0 =s0+ 20 sp =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) function Qoa.newLms(ch) 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 local function toS16(x) 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 local function qdiv(v, sf) local x = v * RECIP[sf + 1] + 32768 if x >= 2147483648 or x < -2147483648 then x = (x + 2147483648) % 4294967296 - 2147483648 end local n = math.floor(x / 65536 ) local sv = v > 0 and 1 or(v < 0 and-1 or 0 ) local sn = n > 0 and 1 or(n < 0 and-1 or 0 ) return n + sv - sn end function Qoa.encodeFrame(x, xf, n, ch, rate, lms, out, p) local slices = math.floor((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 = math.floor((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 = math.floor(sq / 262144 )- 0x8ff if pen < 0 then pen = 0 end local e = v - r rank =rank+ (e * e + pen * pen ) if rank > bestRank then break end local delta = math.floor(dq / 16 ) w0 =w0+ (h0 < 0 and{(-delta )}or{delta })[1] w1 =w1+ (h1 < 0 and{(-delta )}or{delta })[1] w2 =w2+ (h2 < 0 and{(-delta )}or{delta })[1] w3 =w3+ (h3 < 0 and{(-delta )}or{delta })[1] 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 = (k < len and{best[k + 1] }or{0 })[1] if k < 9 then hi =hi+ q * 2 ^ (25 - 3 * k) elseif k == 9 then hi =hi+ rshift(q, 2) lo =lo+ band(q, 3) * 1073741824 else lo =lo+ q * 2 ^ (57 - 3 * k) end end writeu32(out, sp, byteswap(hi)) writeu32(out, sp + 4, byteswap(lo)) sp =sp+ 8 end end return size end return Qoa end __FILES["codecs/audio/Resample"] = function() local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict --!native --!optimize 2 -- 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 = {} local QUALITY = { low = { 8, 6 }, medium = { 16, 8 }, high = { 32, 10 } } local MAX_EXACT = 4096 local INTERP_PHASES = 4096 local floor, sin, pi, sqrt, max, min = math.floor, math.sin, math.pi, math.sqrt, math.max, math.min local readf32, writef32 = buffer.readf32, buffer.writef32 local function besselI0(x) local sum, term = 1, 1 for k = 1, 80 do term =term* (x / (2 * k)) ^ 2 sum =sum+ term if term < sum * 1e-16 then break end end return sum end local function gcd(a, b) while b ~= 0 do a, b = b, a % b end return a end -- phase p: an output p / phases past an input sample; tap k multiplies input floor(t) - half + 1 + k local function makeFilter(ratio, phases, exact, zc, beta, cut) 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 = (exact and{phases }or{(phases + 1 )})[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 = x == 0 and 1 or sin(pi * x) / (pi * x) v = s * besselI0(beta * sqrt(1 - r * r)) / i0b end h[base + k + 1] = v sum =sum+ v end if sum ~= 0 then for k = 1, taps do do local __DARKLUA_VAR=base + k h[__DARKLUA_VAR]=h[__DARKLUA_VAR]/ sum end end end end return { taps = taps, half = half, phases = phases, exact = exact, h = h } end local function run(st, limitOut, out) 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 = (out and buffer.len(out) >= bytes and{out }or{(buffer.create(bytes) )})[1] local exact = f.exact local phases = f.phases local o = 0 for j = j0, jmax - 1 do local num = j * M local ip = math.floor(num / L -- floor(t) ) local first = ip - half + 1 local rel = first - base local kLo = (rel < 0 and{(-rel )}or{0 })[1] 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 =acc+ hist[hi] * h[hb + k] hi =hi+ ch end writef32(b, o, acc) o =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 =acc+ x * h[hb + k] acc2 =acc2+ x * h[hb2 + k] hi =hi+ ch end writef32(b, o, acc + (acc2 - acc) * a) o =o+ 4 end end end st.outPos = jmax local keepFrom = math.floor((jmax * M) / L )- half + 1 local drop = keepFrom - base if drop > 0 then if drop >= histFrames then st.hist = {} st.histFrames = 0 st.base = base + histFrames else local nh= (table.create((histFrames - drop) * ch) ) table.move(hist, drop * ch + 1, histFrames * ch, 1, nh) st.hist = nh st.histFrames = histFrames - drop st.base = base + drop end end return b, n end local function process(self, src, frames, out) 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), math.floor(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 =self.histFrames+ frames self.inFrames =self.inFrames+ frames return run(self, math.huge, out) end local function flush(self, out) 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 function Resample.new(from, to, channels, opts) if type(from) ~= "number" or type(to) ~= "number" or from ~= from or to ~= to or from <= 0 or to <= 0 or from > 2 ^ 24 or to > 2 ^ 24 then return nil, "bad sample rates" end if type(channels) ~= "number" or channels < 1 or channels > 256 or channels ~= floor(channels) then return nil, "bad channel count" end local q= QUALITY[(opts and opts.quality) or "medium"] if not q then return nil, "quality must be low, medium or high" end local cut = (opts and opts.cutoff) or 0.97 if type(cut) ~= "number" or not (cut >= 0.5 and cut <= 1) then return nil, "cutoff must be 0.5 .. 1" end -- positions are exact integers: output j sits at input j * M / L (non-integer rates: to 1 / 1000 Hz) local scale = (from ~= floor(from) or to ~= floor(to) )and 1000 or 1 local fi= floor(from * scale + 0.5) local ti= floor(to * scale + 0.5) local g= gcd(fi, ti) local L, M= math.floor(ti / g), math.floor(fi / g ) local exact = L <= MAX_EXACT local phases = (exact and{L }or{INTERP_PHASES })[1] local st= { from = from, to = to, channels = channels, -- the same rate: a pass-through (tap 0 is the input frame itself) f = L == 1 and M == 1 and{ taps = 2, half = 1, phases = 1, exact = true, h = { 1, 0 } } or 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 , nil end function Resample.buffer(src, frames, channels, from, to, opts) local rs, err = Resample.new(from, to, channels, opts) if not rs then return nil, err 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= 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 =got+ m end pos =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 =got+ m end return out, got end function Resample.source(src, to, opts) 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 = (src.frames > 0 and{(floor(src.frames * to / src.sampleRate + 0.5) )}or{0})[1], tags = src.tags, err = nil , } local inTmp= nil function out.read(self, n, dst) n = floor(n) while pendingFrames - pendingPos <= 0 and not ended do local b, m= (src ):read(math.max(1024, floor(n * src.sampleRate / to) + 64), inTmp) inTmp = b local r, k 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 = (dst and buffer.len(dst) >= bytes and{dst }or{(buffer.create(bytes) )})[1] buffer.copy(b, 0, pending, pendingPos * ch * 4, bytes) pendingPos =pendingPos+ k return b, k end return out, nil end return Resample end __FILES["codecs/audio/SoundFont"] = function() local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict -- 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 = {} SoundFont.Synth = Synth SoundFont.defaultRegion = Parse.defaultRegion function SoundFont.sniff(r) return r:peek(4) == "RIFF" and r:peek(4, 8) == "sfbk" end function SoundFont.parse(src, opts) local r 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() return Fallback.build() end function SoundFont.isSoundFont(v) return type(v) == "table" and v.kind == "soundfont" and type(v.samples) == "buffer" and type(v.presets) == "table" end function SoundFont.synth(sf, sampleRate, opts) 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() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict -- 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) return 1200 * math.log(hz / 8.176, 2) end local cached= nil function Fallback.build() 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= {} for w, name in __iter(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 = (ph < 0.25 and((4 * ph ))or((ph < 0.75 and((2 - 4 * ph ))or((4 * ph - 4 ))))) elseif name == "square" then v = ph < 0.5 and 0.6 or-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, fields) 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 __iter(fields) do r[k] = v end return r end local families= { { "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[math.floor(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, hi, wave, fields) local r = region(wave, fields) r.lokey, r.hikey = lo, hi r.sampleRate =r.sampleRate* 2 ^ ((fields.semis or 0) / 12) r.semis = nil table.insert(kit, r) end local sweep = { mDecay = 0.06, mSustain = 0, modEnvToPitch = 2400 } local function with(a, b) local c = table.clone(a) for k, v in __iter(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 __iter({ 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() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict -- 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 = {} 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= { [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= {} do local seen= {} 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) local r= {} for _, f in __iter(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 __iter({ "a", "m" }) do for _, s in __iter({ "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) local c= {} for k, v in __iter(r) do c[k] = v end return c end function Parse.defaultRegion() local r = clear(false) r.keycenter = 60 for _, p in __iter({ "a", "m" }) do for _, s in __iter({ "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, op, lo, hi, s, w) 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 do local __DARKLUA_VAR=g[1] r[__DARKLUA_VAR]=r[__DARKLUA_VAR]+ s end elseif mode == "a15" then do local __DARKLUA_VAR=g[1] r[__DARKLUA_VAR]=r[__DARKLUA_VAR]+ s * 32768 end 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 = m == 3 and 2 or(m == 1 and 1 or 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, p) for _, g in __iter(MERGE) do local f = g[1] local v = z[f] + p[f] local lim = g[3] if lim then v =v* lim[1] v = math.clamp(v, lim[2], lim[3]) end z[f] = v end end local function tc2s(tc) 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, p, sustainIsGain) for _, s in __iter({ "Delay", "Attack", "Release" }) do local v = r[p .. s] r[p .. s] = v < -11950 and 0 or tc2s(v) end if r[p .. "KeyHold"] == 0 then local v = r[p .. "Hold"] r[p .. "Hold"] = v < -11950 and 0 or tc2s(v) end if r[p .. "KeyDecay"] == 0 then local v = r[p .. "Decay"] r[p .. "Decay"] = v < -11950 and 0 or tc2s(v) end local sus = r[p .. "Sustain"] if sus < 0 then sus = 0 elseif sustainIsGain then sus = (-sus / 10 > -100 and((10 ^ (-sus / 10 * 0.05) ))or(0 )) else sus = 1 - sus / 1000 end r[p .. "Sustain"] = sus end -- record layouts: field byte widths (2 / 4 = little endian unsigned, -2 signed, 20 = name, 1 = byte, -1 = signed byte) local LAYOUT= { 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= { 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", } function Parse.parse(r, opts) 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= {} local hydra= {} local smpl= nil local sm24= 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 = math.floor(sub:remaining() / rs ) local recs = (table.create(n) ) for i = 1, n do local rec = {} for _, w in __iter(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 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 __iter({ "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 local count = math.floor(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 ).phdrNames, (hydra ).instNames, (hydra ).shdrNames local nInst = #inst - 1 -- the last record of each list is the terminal one local nShdr = #shdr - 1 local function range(list, i, field, limit) local a = list[i][field] + 1 local b = (list[i + 1] and((list[i + 1][field] + 1 ))or(a )) return math.max(1, a), math.min(b, limit + 1) end local presets= {} local regionTotal = 0 for pi = 1, #phdr - 1 do local ph = phdr[pi] local 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, math.floor(amount / 256 ) local s = (amount >= 32768 and((amount - 65536 ))or(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 = z.delayModLFO < -11950 and 0 or tc2s(z.delayModLFO) z.delayVibLFO = z.delayVibLFO < -11950 and 0 or 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 =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 =le- 1 end z.loopEnd = math.clamp(le, 0, count) if z.keycenter == -1 then z.keycenter = sh[7] end z.tune =z.tune+ sh[8] z.sampleRate = sh[6] z.sampleIndex = iamt regionTotal =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, math.floor(iamt / 256 ) operator(zone, iop, ilo, ihi, (iamt >= 32768 and((iamt - 65536 ))or(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 __iter(presets) do (p )._order = i end table.sort(presets, function(a, b) 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 )._order < (b )._order end) for _, p in __iter(presets) do (p )._order = nil end local headers = (table.create(nShdr) ) 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) ) 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= { 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"] = function() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict --!native -- 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 local function tc2s(tc) return 2 ^ (tc / 1200) end local function cents2Hz(c) return 8.176 * 2 ^ (c / 1200) end local function db2gain(db) return (db > -100 and((10 ^ (db * 0.05) ))or(0 ))end local function gain2db(g) return g <= 0.00001 and-100 or 20 * math.log10(g) end local function releaseSamples(e, rate) return floor(((e.release <= 0 and{FASTRELEASE }or{e.release})[1]) * rate) end local function nextSegment(e, active, rate) 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 = (e.untilNext > 0 and((1 / e.untilNext ))or(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 local function envSetup(e, r, p, key, vel, isAmp, rate) 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 = h < -10000 and 0 or tc2s(h) end if kd ~= 0 then local d = e.decay + kd * (60 - key) e.decay = d < -10000 and 0 or tc2s(d) end e.vel, e.isAmp = vel, isAmp nextSegment(e, NONE, rate) end local function envProcess(e, n, rate) local slope = e.slope if slope ~= 0 then if e.isExp then e.level =e.level* slope ^ n else e.level =e.level+ slope * n end end e.untilNext =e.untilNext- n if e.untilNext <= 0 then nextSegment(e, e.segment, rate) end end local function newEnv() 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 local function lowpassSetup(v, fc) -- 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 local function lfoSetup(l, delay, freqCents, rate) l.untilStart = floor(delay * rate) l.delta = 4 * cents2Hz(freqCents) / rate l.level = 0 end local function lfoProcess(l, n) if l.untilStart > n then l.untilStart =l.untilStart- n return end l.level =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 local function calcPitch(v, shift, rate) 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 local function setPan(v, pan) 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 local function channelShift(c) return (c.pitchWheel == 8192 and{c.tuning }or{((c.pitchWheel / 16383 * c.pitchRange * 2) - c.pitchRange + c.tuning )})[1]end local function voiceEnd(s, v) 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 local function voiceEndQuick(s, v) v.amp.release = 0 nextSegment(v.amp, SUSTAIN, s.rate) v.mod.release = 0 nextSegment(v.mod, SUSTAIN, s.rate) end local function newVoice() 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 local function newChannel() 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 function Synth.new(sf, rate, gain, maxVoices) local lookup= {} for i, p in __iter(sf.presets) do local k = p.bank * 128 + p.preset if lookup[k] == nil then lookup[k] = i end end local s= { 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 local function presetIndex(s, bank, preset) return s.lookup[bank * 128 + preset] or -1 end function Synth.noteOn(s, ch, key, velocity) 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 =s.playIndex+ 1 for _, region in __iter(preset.regions) do local __DARKLUA_CONTINUE_4=false repeat if key < region.lokey or key > region.hikey or midiVel < region.lovel or midiVel > region.hivel then __DARKLUA_CONTINUE_4=true break end local voice= nil if region.group ~= 0 then for _, v in __iter(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 __iter(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 __iter(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 __DARKLUA_CONTINUE_4=true break end end end local v = 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 = (doLoop and{region.loopStart }or{0 })[1] v.loopEnd = (doLoop and{region.loopEnd }or{0 })[1] envSetup(v.amp, region, "a", key, midiVel, true, rate) envSetup(v.mod, region, "m", key, midiVel, false, rate) local fc = (region.filterFc <= 13500 and((cents2Hz(region.filterFc) / rate ))or(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) __DARKLUA_CONTINUE_4=true until true if not __DARKLUA_CONTINUE_4 then break end end end function Synth.noteOff(s, ch, key) local c = s.channels[ch + 1] if not c then return end local first = -1 for _, v in __iter(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 __iter(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 local function applyPitch(s, ch, c) local shift = channelShift(c) for _, v in __iter(s.voices) do if v.preset ~= -1 and v.channel == ch then calcPitch(v, shift, s.rate) end end end local function setVolume(s, ch, c, volume) local db = gain2db(volume) if db == c.gainDB then return end local change = db - c.gainDB for _, v in __iter(s.voices) do if v.preset ~= -1 and v.channel == ch then v.gainDB =v.gainDB+ change end end c.gainDB = db end local function setChannelPan(s, ch, c, pan) for _, v in __iter(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 local function setTuning(s, ch, c, tuning) if c.tuning ~= tuning then c.tuning = tuning applyPitch(s, ch, c) end end local function setPitchRange(s, ch, c, range) if c.pitchRange ~= range then c.pitchRange = range if c.pitchWheel ~= 8192 then applyPitch(s, ch, c) end end end local function setSustain(s, ch, c, on) if c.sustain == on then return end c.sustain = on if on then return end for _, v in __iter(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) function Synth.program(s, ch, program) 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 function Synth.pitchBend(s, ch, value) local c = s.channels[ch + 1] if not c or c.pitchWheel == value then return end c.pitchWheel = value applyPitch(s, ch, c) end function Synth.control(s, ch, cc, value) 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 = ((c.bank >= 0x8000 and(((c.bank % 128) * 128 ))or(0))) + value elseif cc == 101 then local rpn = c.midiRPN == 0xFFFF and 0 or c.midiRPN c.midiRPN = rpn % 128 + value * 128 elseif cc == 100 then local rpn = c.midiRPN == 0xFFFF and 0 or 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 __iter(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 __iter(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, math.floor(c.midiData / 128 )+ 0.01 * (c.midiData % 128)) elseif c.midiRPN == 1 then local t = c.tuning setTuning(s, ch, c, ((t < 0 and{(math.ceil(t) )}or{(floor(t))})[1]) + (c.midiData - 8192) / 8192) elseif c.midiRPN == 2 and cc == 6 then local t = c.tuning setTuning(s, ch, c, (value - 64) + (t - ((t < 0 and{(math.ceil(t) )}or{(floor(t))})[1]))) end end end function Synth.midi(s, status, d1, d2) local kind, ch = math.floor(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 function Synth.reset(s) for _, v in __iter(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 function Synth.active(s) local n = 0 for _, v in __iter(s.voices) do if v.preset ~= -1 then n =n+ 1 end end return n end local function voiceRender(s, v, out, frame, numSamples) 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 = dynamicPitch and 0 or tc2s(v.pitchIn) * v.pitchOut local noteGain = dynamicGain and 0 or db2gain(v.gainDB) local o = frame * 8 while numSamples > 0 do local block = (numSamples > BLOCK and{BLOCK }or{numSamples })[1] numSamples =numSamples- block if dynamicLowpass then local fres = filterFc + v.modlfo.level * modLfoToFilterFc + v.mod.level * modEnvToFilterFc local fc = (fres <= 13500 and((cents2Hz(fres) / rate ))or(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 =k- 1 local ip = floor(pos) local np = (ip >= loopEnd and isLooping and{loopStart }or{(ip + 1 )})[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 =val* g g =g+ step writef32(out, o, readf32(out, o) + val * panL) writef32(out, o + 4, readf32(out, o + 4) + val * panR) o =o+ 8 pos =pos+ pitchRatio if pos >= loopEndD and isLooping then pos =pos- loopLen end end o =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 function Synth.render(s, out, frame, n) local room = math.floor(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 = math.floor(blen(s.samples) / 4 )- 1 for _, v in __iter(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 __FILES["codecs/audio/Stream"] = function() local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict -- 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 = {} function Stream.packets(dec, spec) 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= nil dec.error = nil local function fill() while true do if nextPacket > count or decoded >= stopAt then return false end local i = nextPacket nextPacket =nextPacket+ 1 local first = (spec.cumulative and{decoded }or{(startOf(i) )})[1] 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, out, asInt) local want = math.max(0, math.floor(n)) local need = want * ch * 4 local ob = (out and buffer.len(out) >= need and{out }or{(buffer.create(need) )})[1] 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 =q+ 4 end end elseif asInt then for k = 1, take * ch do writei32(ob, q, src[s + k]) q =q+ 4 end elseif scale == 1 then for k = 1, take * ch do writef32(ob, q, src[s + k]) q =q+ 4 end else for k = 1, take * ch do writef32(ob, q, src[s + k] * scale) q =q+ 4 end end pendPos =pendPos+ take got =got+ take end pos =pos+ got return ob, got end function dec.read(_self, n, out) return pull(n, out, false) end if spec.ints then function dec.readInt(_self, n, out) return pull(n, out, true) end end function dec.seek(_self, seconds) local sec = (type(seconds) == "number" and seconds == seconds and{seconds }or{0 })[1] 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 = math.floor((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 = (count > 0 and{(startOf(found) )}or{0 })[1] dropUntil = target pendPos, pendN = 0, 0 failed = nil dec.error = nil pos = target - skip end function dec.position(_self) 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/Tracker"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict -- 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 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) local f = m.engine or m.format return (type(f) == "string" and FAMILIES[f] and{f }or{nil })[1]end function Tracker.newModule(format, channels, engine) 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] = (k == 0 or k == 3 )and 64 or 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, channels) return { rows = rows, data = buffer.create(rows * channels * CELL) } end function Tracker.newSample(name) 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 , c5speed = 8363, relativeNote = 0, finetune = 0, vibType = 0, vibSweep = 0, vibDepth = 0, vibRate = 0, } end function Tracker.newEnvelope() return { enabled = false, ticks = {}, values = {}, loop = false, loopStart = 1, loopEnd = 1, sustain = false, susStart = 1, susEnd = 1 } end function Tracker.newInstrument(name) 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 , panEnv = nil , pitchEnv = nil , fadeout = 0, nna = 0, dct = 0, dca = 0, globalVolume = 128, pan = nil , pps = 0, ppc = 60, cutoff = nil , resonance = nil , vibType = 0, vibSweep = 0, vibDepth = 0, vibRate = 0, } end function Tracker.cell(m, pattern, row, channel) 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, pattern, row, channel, note, ins, vol, fx, param) 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, lo, hi) return type(v) == "number" and v == v and v >= lo and v <= hi end local function fixEnvelope(e) 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) return (num(v, 1, math.max(1, n)) and{(math.floor(v) )}or{1 })[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, e0, t0, len) 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= math.floor(math.clamp(s0, 0, len)) local e= math.floor(math.clamp(e0, 0, len)) local t= 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) 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 = (type(m.instruments) == "table" and{m.instruments }or{{} })[1] m.flags = (type(m.flags) == "table" and{m.flags }or{{} })[1] m.channelPan = (type(m.channelPan) == "table" and{m.channelPan }or{{} })[1] m.channelVolume = (type(m.channelVolume) == "table" and{m.channelVolume }or{{} })[1] m.channelMute = (type(m.channelMute) == "table" and{m.channelMute }or{{} })[1] 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 = (num(m.speed, 1, 255) and{(math.floor(m.speed) )}or{6 })[1] m.tempo = (num(m.tempo, 1, 1000) and{m.tempo }or{125 })[1] m.globalVolume = (num(m.globalVolume, 0, 128) and{m.globalVolume }or{128 })[1] m.mixVolume = (num(m.mixVolume, 0, 256) and{m.mixVolume }or{48 })[1] m.restart = (num(m.restart, 0, 1e6) and{(math.floor(m.restart) )}or{0 })[1] for i, o in __iter(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 __iter(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 __iter(m.samples) do if type(s) ~= "table" then return nil, Err.new(Err.ARG, "bad sample " .. i) end local nch = s.channels == 2 and 2 or 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 = (num(s.volume, 0, 64) and{s.volume }or{64 })[1] s.globalVolume = (num(s.globalVolume, 0, 64) and{s.globalVolume }or{64 })[1] if s.pan ~= nil and not num(s.pan, 0, 256) then s.pan = nil end s.c5speed = (num(s.c5speed, 1, 1e7) and{s.c5speed }or{8363 })[1] s.relativeNote = (num(s.relativeNote, -128, 127) and{s.relativeNote }or{0 })[1] s.finetune = (num(s.finetune, -128, 127) and{s.finetune }or{0 })[1] end for i, ins in __iter(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 = (num(ins.fadeout, 0, 65535) and{ins.fadeout }or{0 })[1] ins.globalVolume = (num(ins.globalVolume, 0, 128) and{ins.globalVolume }or{128 })[1] 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, opts) 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 =frames+ f end return math.min(frames, maxFrames) / sr, nil end local function newPlayer(self) 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, opts) local o= 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 , left = 0, pos = 0, }, Decoder) newPlayer(self) return self , nil end function Tracker.renderMethod(self, opts) local dec = Tracker.render(self, opts) return dec end local function run(self, out, n) local st = self.st local done = 0 while done < n do local __DARKLUA_CONTINUE_13=false repeat 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 __DARKLUA_CONTINUE_13=true break end end local k = math.min(self.left, n - done) Mixer.mix(st, out, done, k, self.linear) self.left =self.left- k done =done+ k __DARKLUA_CONTINUE_13=true until true if not __DARKLUA_CONTINUE_13 then break end end self.pos =self.pos+ done return done end function Decoder.read(self, n, out) 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 , got end function Decoder.seek(self, seconds) 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 __iter(self.st.voices) do v.gl, v.gr = 0, 0 end end function Decoder.position(self) return self.pos / self.sampleRate end return Tracker end __FILES["codecs/audio/Tracker/Load"] = function() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict -- 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= { 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= {} for i, n in __iter({ "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, param) if name == nil then return false end if GLOBAL[name] then return true end local x = math.floor(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= { [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, param) 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 = (math.floor(param / 16)) * 10 + param % 16 end return n, param end -- OpenMPT's ConvertToVolCommand (force: fit with some loss of precision) function Load.itVolume(name, param, force) 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 math.floor((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 (name == "portaup" and 115 or 105) + math.min(math.floor(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 + (param == 255 and 64 or math.floor(param / 4)) + 1 elseif name == "volslide" then local x, y = math.floor(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 math.floor(param / 16 )== 8 then return 128 + (param % 16) * 4 + 2 + 1 end return nil end function Load.itEffect(name, param) if name == nil then return 0, 0 end if name == "modex" then local x, y = math.floor(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, p1, e2, p2) 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 ] or 0) > (WEIGHT[e2 ] 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, pattern, row, fx, param, retry, channel, multiple) 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 =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 =row+ 1 elseif retry == "prev" then row =row- 1 else return false end end return false end function Load.readSample(buf, offset, frames, spec, s, budget) local nch = spec.channels or 1 local bps = math.floor(spec.bits / 8 ) local limit = math.min(spec.limit or buffer.len(buf), buffer.len(buf)) local avail = math.floor(math.max(0, limit - offset) / (nch * bps) ) local n = math.max(0, math.min(math.floor(frames), avail)) budget.left =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) n = math.clamp(math.floor(n), 0, 99) return (math.floor(n / 10)) * 16 + n % 10 end return Load end __FILES["codecs/audio/Tracker/Mixer"] = function() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict --!native -- 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 = {} local function mixVoice(v, out, off, n, linear, ramp) local data= 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 local __DARKLUA_CONTINUE_1=false repeat guard =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 = (t == 2 and((e - 1 ))or(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 __DARKLUA_CONTINUE_1=true break 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 __DARKLUA_CONTINUE_1=true break 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 =i+ m __DARKLUA_CONTINUE_1=true break end local wrapJ = (t == 1 and{s }or{(e - 1 )})[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 =gl+ dl gr =gr+ dr rl =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 =o+ 8 p =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 =i+ m __DARKLUA_CONTINUE_1=true until true if not __DARKLUA_CONTINUE_1 then break end end local _ = ramp end function Mixer.mix(st, out, off, n, linear) for _, v in __iter(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"] = function() local __compat = __compat local buffer = __compat.buffer --!strict --!native -- 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 = {} function Pcm.bytes(frames, spec) return frames * (spec.channels or 1) * (math.floor(spec.bits / 8)) end function Pcm.decode(buf, off, frames, spec) local nch = spec.channels or 1 local bps = math.floor(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 = (planar and((c * frames + i ))or((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 =v- 65536 end elseif spec.signed then v = readi16(buf, p) else v = readu16(buf, p) end if not spec.signed then v =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 function Pcm.encode(samples, frames, spec) local nch = spec.channels or 1 local bps = math.floor(spec.bits / 8 ) local out = buffer.create(frames * nch * bps) local planar = spec.planar and nch == 2 local avail = math.floor(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 = (si < avail and{(readf32(samples, si * 4) )}or{0 })[1] local k = (planar and((c * frames + i ))or((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 = (spec.signed and((v % 256 ))or((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 =w- 65536 end end writei16(out, k * 2, w) end end end return out end function Pcm.bitsNeeded(samples) for i = 0, math.floor(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"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --!native -- 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 local function newVoice() return { active = false, chan = 0, bg = false, data = nil , nch = 1, len = 0, loopS = 0, loopE = 0, loopT = 0, susS = 0, susE = 0, susT = 0, p = 0, dir = 1, inc = 0, smp = nil , smpIdx = 0, ins = nil , 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 local function newChannel(i, pan, vol) return { idx = i, voice = nil , note = 0, realNote = 0, insIdx = 0, smpIdx = 0, smp = nil , vol = 0, pan = pan, basePan = pan, chanVol = vol, period = 0, target = 0, portaSpeed = 0, base = 8363, finetune = nil , 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 function Player.new(m, sampleRate, opts) local fmt = FAMILY[m.engine or m.format] or MOD local flags = m.flags local ptPeriods = fmt == MOD or flags.periods == "amiga" local st= { 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 = (type(flags.hzSlide) == "number" and{flags.hzSlide }or{1})[1], hzTone = (type(flags.hzTonePorta) == "number" and{flags.hzTonePorta }or{1})[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 , patIdx = -1, patDelay = 0, patDelayRep = 0, fineDelay = 0, jumpOrd = -1, ft2BreakPos = 0, breakRow = -1, loopJump = -1, ended = false, visited = {} , 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 = (ptPeriods and{AMIGA_PAL }or{AMIGA})[1], 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) function Player.masterGain(m, fmt) 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 function Player.startOrder(st, ord, row) local m = st.m local order = m.order local n = #order local guard = 0 local o = ord while true do guard =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 =o+ 1 else st.ord = o st.patIdx = p st.pat = m.patterns[p + 1] st.row = (row < st.pat.rows and{row }or{0 })[1] return end end end local function advanceRow(st) if st.stopAfterRow then st.ended = true return end local loopRow = st.loopJump if st.jumpOrd >= 0 or st.breakRow >= 0 then local o = (st.jumpOrd >= 0 and{st.jumpOrd }or{(st.ord + 1 )})[1] local r = (st.breakRow >= 0 and{st.breakRow }or{0 })[1] 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 =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 = (st.fmt == XM and{st.ft2BreakPos }or{0 })[1] st.ft2BreakPos = 0 Player.startOrder(st, st.ord + 1, r) end end local function notePeriod(st, note, smp, ft) 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 + (((st.fmt == MOD or st.fmt == XM )and{smp.relativeNote or 0 }or{0})[1]) 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 local function arpPeriod(st, period, semis) 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 local function clampPeriod(st, c) 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 local function slide(st, c, units) if st.hz then c.period =c.period- units * st.hzScale else c.period =c.period+ units end clampPeriod(st, c) end local function allocVoice(st) local best, bestScore = nil, math.huge for _, v in __iter(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 __iter(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 local function keyOff(st, v) 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 local function noteFade(v) if v and v.active then v.fading = true end end local function cutVoice(v) if v then v.active = false end end local function startVoice(st, c, smp, smpIdx, ins, insIdx, note, period, base, keepEnv) 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 =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) local function newNoteAction(st, c, ins, insIdx, note, smpIdx) if ins and ins.dct and ins.dct > 0 then for _, u in __iter(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 = (v.ins and{(v.ins.nna or 0) }or{0 })[1] 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 local function isPorta(st, fx, vcmd) 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 local function resolve(st, insIdx, note) 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 local function setInstrumentDefaults(st, c, smp, ins) 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 local function sampleOffset(st, c, v) 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 = ((f == XM and{c.mOffset }or{param})[1]) * 256 elseif (f == S3M or f == IT) and fx == 15 then if param > 0 then c.mOffset = param end off = c.mOffset * 256 + ((f == IT and((c.mHighOffset * 65536 ))or(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 local function trigger(st, c, note, insIdx, vcmd) 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 = (st.insMode and{(m.instruments[insIdx] ~= nil )}or{(m.samples[insIdx] ~= nil )})[1] if valid then c.insIdx = insIdx local n = (hasNote and{note }or{c.note })[1] local smp, _, ins = resolve(st, insIdx, (n > 0 and{n }or{61})[1]) 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= false if f == XM and insIdx == 0 and c.voice ~= nil then keep = c.voice.ins == ins and true or"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 local function volSlideMod(c, param) local x, y = math.floor(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 local function tonePorta(st, c, speed) if c.period == c.target then return end if st.hz then speed =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 local function vibrato(st, c, scale) c.vibDelta = wave64(c.vibWave % 4, c.vibPos) * c.vibDepth * scale c.vibPos = (c.vibPos + c.vibSpeed) % 64 end local function tremolo(c, scale) c.tremDelta = floor(wave64(c.tremWave % 4, c.tremPos) * c.tremDepth * scale) c.tremPos = (c.tremPos + c.tremSpeed) % 64 end local function retrigVoice(st, c) local v = c.voice if v and v.smp then v.active = v.smp.length > 0 v.p = 0 v.dir = 1 end end local function retrigVolume(c, x) 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 =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) local function dSlide(value, param, tick, fast, hi) local x, y = math.floor(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 local function fxModXm(st, c, tick) local fx, param = c.fx, c.param local xm = st.fmt == XM local x, y = math.floor(param / 16), param % 16 if fx == 0 then if param ~= 0 then local k = tick % 3 c.arp = (k == 1 and{x }or{(k == 2 and{y }or{0 })[1]})[1] 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, -((xm and{c.mPortaUp }or{param})[1]) * 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, ((xm and{c.mPortaDn }or{param})[1]) * 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, -((xm and{c.mFineUp }or{y})[1]) * 4) end elseif x == 2 then if xm and y > 0 then c.mFineDn = y end if tick == 0 then slide(st, c, ((xm and{c.mFineDn }or{y})[1]) * 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 =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 + ((xm and{c.mFineVolUp }or{y})[1])) 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 - ((xm and{c.mFineVolDn }or{y})[1])) 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 = math.floor(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 = math.floor(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 = (math.floor(c.mRetrig / 16)) * 16 + y end local interval = c.mRetrig % 16 if tick == 0 and c.triggered then c.retrigCount = 0 else c.retrigCount =c.retrigCount+ 1 end if interval > 0 and c.retrigCount >= interval then c.retrigCount = 0 retrigVolume(c, math.floor(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 = math.floor(c.mTremor / 16 )+ 1, c.mTremor % 16 + 1 c.tremorCount =c.tremorCount% (on + off ) c.tremorOn = c.tremorCount < on c.tremorCount =c.tremorCount+ 1 end end -- the XM volume column (everything but set volume / set panning, done by trigger) local function volColXm(st, c, tick) local v = c.vcmd if v < 0x60 then return end local hi, lo = math.floor(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 local function mem(st, c, field, param) 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 local function portaS3m(st, c, p, tick, sign) 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 local function fxS3mIt(st, c, tick) 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 = (it and{param }or{((math.floor(param / 16)) * 10 + param % 16 )})[1] 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 = math.floor(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 =c.tremorCount% (on + off ) c.tremorOn = c.tremorCount < on c.tremorCount =c.tremorCount+ 1 end elseif fx == 10 then -- J arpeggio local p = mem(st, c, "mArp", param) local k = tick % 3 c.arp = (k == 1 and{(math.floor(p / 16 ))}or{(k == 2 and((p % 16 ))or(0 ))})[1] 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 = math.floor(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 =c.retrigCount- 1 if c.retrigCount <= 0 then c.retrigCount = interval retrigVolume(c, math.floor(p / 16)) retrigVoice(st, c) end end end elseif fx == 18 then -- R tremolo if math.floor(param / 16 )> 0 then c.tremSpeed = math.floor(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 = (it and{(mem(st, c, "mS", param) )}or{(mem(st, c, "mS", param) )})[1] local x, y = math.floor(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 =st.fineDelay+ y end elseif x == 7 then if tick == 0 then if y <= 2 then for _, u in __iter(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 =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 = y == 0 and it and 1 or 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 math.floor(param / 16 )> 0 then c.panbSpeed = math.floor(param / 16 ) end if param % 16 > 0 then c.panbDepth = param % 16 end c.panbDelta = wave64(c.panbWave % 4, math.floor(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 math.floor(param / 16 )> 0 then c.vibSpeed = math.floor(param / 16 ) end if param % 16 > 0 then c.vibDepth = param % 16 end end local scale = fx == 21 and 2 / 255 or 8 / 255 if it and not st.oldFx then scale =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 local function volColIt(st, c, tick) 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, st.oldFx and 8 / 255 or 4 / 255) end end end local function fxExt(st, c, tick) 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 math.floor(param / 16 )> 0 then c.mNoteSlide = (math.floor(param / 16)) * 16 + c.mNoteSlide % 16 end if param % 16 > 0 then c.mNoteSlide = (math.floor(c.mNoteSlide / 16)) * 16 + param % 16 end c.slideCount = math.floor(c.mNoteSlide / 16 ) end local p = c.mNoteSlide local go if st.oktSlides then go = math.floor(p / 16 )== 1 or tick == 0 else go = false if tick > 0 then c.slideCount =c.slideCount- 1 go = c.slideCount == 0 end end if go and c.smp and c.realNote > 0 then c.slideCount = math.floor(p / 16 ) local up = fx == EXT.NOTE_SLIDE_UP or fx == EXT.NOTE_SLIDE_UP_RETRIG c.realNote = clamp(c.realNote + ((up and((p % 16 ))or((-(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 = ((fx == EXT.AUTO_PORTA_UP and{(-param )}or{param})[1]) * 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 local function noteDelayOf(st, fx, param) if (st.fmt == MOD or st.fmt == XM) and fx == 0xE and math.floor(param / 16 )== 0xD then return param % 16 elseif (st.fmt == S3M or st.fmt == IT) and fx == 19 and math.floor(param / 16 )== 0xD then return param % 16 end return 0 end local function finetuneOf(st, fx, param) if (st.fmt == MOD or st.fmt == XM) and fx == 0xE and math.floor(param / 16 )== 5 then local y = param % 16 if st.fmt == MOD then return ((y >= 8 and((y - 16 ))or(y))) * 16 end return (y - 8) * 16 end return nil end local function runEffects(st, c, tick) 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 local function processRow(st) 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 =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 local function updateEnvelope(env, pos, keyOn, it) 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 =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 = it and 1 or 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 local function updateVoice(st, v) 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, (hold and{v.volEnvPos }or{np })[1] 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, (hold and{v.panEnvPos }or{np })[1] 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 = (hold and{v.pitchEnvPos }or{np })[1] if e.filter then filterEnv = val else envPitch = val end end if v.fading then local fo = ins.fadeout or 0 v.fade =v.fade- (it and((fo * 64 ))or((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 = (it and{v.smp }or{ins })[1] 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 = (P > 0 and((st.amiga / P ))or(0 )) end if envPitch ~= 0 then freq =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 =vol* (v.chanVol / 64 * ((smp and(((smp.globalVolume or 64) / 64 ))or(1))) * ((ins and(((ins.globalVolume or 128) / 128 ))or(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 =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 function Player.tick(st) 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, t == 0 and 1 or 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) + ((st.hz and((-c.vibDelta * st.hzScale ))or(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 __iter(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 =st.tick+ 1 if st.tick >= st.speed + st.fineDelay then st.tick = 0 if st.patDelayRep < st.patDelay then st.patDelayRep =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"] = function() --!strict --!native -- 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= {} do local s = 12345 for i = 1, 64 do s = (s * 1103515245 + 12345) % 2147483648 RANDOM[i] = (math.floor(s / 65536)) % 511 - 255 end end function Tables.wave64(kind, pos) local p = pos % 64 if kind == 1 then return 255 - p * 8 elseif kind == 2 then return p < 32 and 255 or-255 elseif kind == 3 then return RANDOM[p + 1] end local v = SINE32[(p % 32) + 1] return (p >= 32 and{(-v )}or{v })[1]end local SINE256= {} for i = 0, 255 do SINE256[i + 1] = math.floor(math.sin(i * math.pi / 128) * 64 + 0.5) end function Tables.autoWave(kind, pos, it) local p = pos % 256 if it then if kind == 1 then return 64 - math.floor((p + 1) / 2 ) elseif kind == 2 then return p < 128 and 64 or-64 elseif kind == 3 then return math.floor(RANDOM[(p % 64) + 1] / 4 ) end return SINE256[p + 1] end if kind == 1 then return p < 128 and 64 or-64 elseif kind == 2 then return 64 - math.floor((p + 1) / 2 ) elseif kind == 3 then return math.floor((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) function Tables.periodToNote(period) 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 function Tables.noteToPeriod(note) 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 } function Tables.st2Tempo(byte) local hi, lo = math.floor(byte / 16), byte % 16 local d = 50 - math.floor((ST2_FACTOR[hi + 1] * lo) / 16 -- never 0; negative at tempo 06..0F (C integer division truncates) ) local spt = (d > 0 and{(math.floor(23863 / d ))}or{(-(math.floor(23863 / -d)) )})[1] if spt <= 0 then spt =spt+ 65536 end return math.max(hi, 1), math.floor((23863 * 50000 + spt) / (spt * 2)) / 10000 end return Tables end __FILES["codecs/audio/Tta"] = function() local __compat = __compat local buffer = __compat.buffer --!strict -- 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 = {} function Tta.info(buf, at, limit) 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= { 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 = math.floor((256 * info.sampleRate) / 245 ) if info.frameLength < 1 then return nil, Err.new(Err.CORRUPT, "bad sample rate") end local frames = math.floor((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 =o+ size end return info, nil end local function frame(self, buf, i) 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 = (i < info.frames and{info.frameLength }or{(info.samples - (info.frames - 1) * info.frameLength )})[1] 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, limit) return { info = info, pcm = table.create(info.frameLength * info.channels, 0), limit = limit, frame = frame, state = Decode.state(info.channels, math.floor(info.bitsPerSample / 8)), } end return Tta end __FILES["codecs/audio/Tta/Decode"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 -- 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= table.create(40, 0) for i = 0, 39 do P2[i + 1] = 2 ^ i end local ONES= table.create(256, 0) for b = 0, 255 do local n, v = 0, b while v % 2 == 1 do n =n+ 1 v =math.floor(v/ 2 ) end ONES[b + 1] = n end local function longUnary(S, pos, lim) 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 =unary+ 8 pos =pos+ 8 end return nil, pos end function Decode.state(channels, bytes) 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 function Decode.frame(st, buf, o, len, n, P) 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 = bytes == 2 and 9 or 10 -- the filter's precision per sample size local fdiv = 2 ^ shift local round = math.floor(fdiv / 2 ) local pk = bytes == 1 and 16 or 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 =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 =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 =pos+ k value = unary * P2[k + 1] + bits end if deep then s1 =s1+ (value - math.floor(s1 / 16 )) if k1 > 0 and s1 < P2[k1 + 5] then k1 =k1- 1 elseif s1 > P2[k1 + 6] then k1 =k1+ 1 end value =value+ P2[k0 + 1] end s0 =s0+ (value - math.floor(s0 / 16 )) if k0 > 0 and s0 < P2[k0 + 5] then k0 =k0- 1 elseif s0 > P2[k0 + 6] then k0 =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 = math.floor((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 =value+ math.floor(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 =value+ math.floor((last[c + 1] * (pk - 1)) / pk ) last[c + 1] = value cur[c + 1] = value end c =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] + ((a >= 0 and{(math.floor(a / 2 ))}or{(-(math.floor((-a) / 2)))})[1]) P[o + 1], P[o + 2] = b - a, b else local a = cur[C - 1] cur[C]=cur[C]+ (a >= 0 and{(math.floor(a / 2 ))}or{(-(math.floor((-a) / 2)) )})[1] 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/Vorbis"] = function() --!strict -- 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"] = function() local __compat = __compat local buffer = __compat.buffer --!strict --!native --!optimize 2 -- 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 function Codebook.reader(buf, offset, size) return { buf = buf, pos = offset, limit = offset + size, acc = 0, cnt = 0, pad = 0, eop = false } end local function bits(br, n) 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 =acc+ readu8(b, p) * POW[cnt + 1] p =p+ 1 else br.pad =br.pad+ 8 end cnt =cnt+ 8 until cnt >= n br.pos = p end local m = POW[n + 1] local v = acc % m br.acc = (acc - v) / m cnt =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) local function ilog(x) local n = 0 while x > 0 do n =n+ 1 x = floor(x / 2) end return n end Codebook.ilog = ilog -- float32_unpack (spec 9.2.2) local function float32Unpack(x) local mantissa = x % 2097152 local sign = x >= 2147483648 local exp = floor((x % 2147483648) / 2097152) local v = mantissa * 2 ^ (exp - 788) return (sign and{(-v )}or{v })[1]end local MAX_ENTRIES = 2 ^ 20 local MAX_VQ = 2 ^ 22 -- lookup1_values(entries, dims): the largest r with r^dims <= entries local function lookup1Values(entries, dims) local r = floor(math.exp(math.log(entries) / dims)) if floor((r + 1) ^ dims) <= entries then r =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 local function build(book, lengths) 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 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 =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 = (bit == 0 and{c0[node] }or{c1[node] })[1] 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 =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 =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 = (bit == 0 and{c0[node] }or{c1[node] })[1] 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 function Codebook.read(br) 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 =cur+ num len =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= { 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 =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 local function decode(br, book) 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 =acc+ readu8(b, p) * POW[cnt + 1] p =p+ 1 else br.pad =br.pad+ 8 end cnt =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 =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 = (bits(br, 1) == 0 and{c0[node] }or{c1[node] })[1] 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"] = function() local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict --!native --!optimize 2 -- 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 } function Packet.new(id, setup) local n0, n1, ch = id.blocksize0, id.blocksize1, id.channels local plans= {} local slopes= {} for _, n in __iter({ n0, n1 }) do local p = Mdct.new(n) if not p then return nil end plans[n] = p local w = (Mdct.window("vorbis", n) ) local half = table.create(math.floor(n / 2), 0) for i = 1, math.floor(n / 2 )do half[i] = w[i] end slopes[math.floor(n / 2)] = half end local function arrays(len) 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(math.floor(n1 / 2)), frame = arrays(n1), tail = arrays(math.floor(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(math.floor(n1 / 2 )* ch, 0), zero = table.create(ch, false), reallyZero = table.create(ch, false), partClass = partClass, } end function Packet.reset(st) st.prevN = 0 st.tailLen = 0 end function Packet.blocksize(st, b, off, size) 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 (mode.blockflag == 1 and{st.n1 }or{st.n0 })[1]end local function predict(x, x0, x1, y0, y1) local dy = y1 - y0 local adx = x1 - x0 local off = math.floor((((dy < 0 and{(-dy )}or{dy})[1]) * (x - x0)) / adx ) return (dy < 0 and((y0 - off ))or((y0 + off )))end -- multiply out[x0 .. x1) by the floor line from (x0, y0) to (x1, y1) (stb draw_line) local function drawLine(out, x0, y0, x1, y1, n) local dy = y1 - y0 local adx = x1 - x0 local ady = (dy < 0 and{(-dy )}or{dy })[1] local base = (dy < 0 and{(-(math.floor(ady / adx)) )}or{(math.floor(ady / adx ))})[1] local sy = (dy < 0 and((base - 1 ))or((base + 1 ))) ady =ady- ((base < 0 and{(-base )}or{base})[1]) * adx if x1 > n then x1 = n end local x, y, err = x0, y0, 0 if x < x1 then do local __DARKLUA_VAR=x + 1 out[__DARKLUA_VAR]=out[__DARKLUA_VAR]* INV_DB[y % 256 + 1] end x =x+ 1 while x < x1 do err =err+ ady if err >= adx then err =err- adx y =y+ sy else y =y+ base end do local __DARKLUA_VAR0=x + 1 out[__DARKLUA_VAR0]=out[__DARKLUA_VAR0]* INV_DB[y % 256 + 1] end x =x+ 1 end end end local function floorDecode(st, br, g, finalY) 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 = math.floor(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 =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 = (highroom < lowroom and((highroom * 2 ))or((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 - math.floor((val + 1) / 2 ) else finalY[j + 1] = pred + math.floor(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) local function floorCurve(g, finalY, target, n2) 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]=target[j]* v end end end local function partition(br, book, target, offset, psize, rtype, limit) 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 = math.floor(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 do local __DARKLUA_VAR=at + 1 target[__DARKLUA_VAR]=target[__DARKLUA_VAR]+ vq[base + i + 1] end 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 do local __DARKLUA_VAR=at + i + 1 target[__DARKLUA_VAR]=target[__DARKLUA_VAR]+ vq[base + i + 1] end end end k =k+ dims end end return true end local function residue(st, br, r, targets, ch, n2) 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 )[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 = math.floor((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 =i+ 1 pcount =pcount+ 1 end if done then break end classSet =classSet+ 1 end end for j = 1, ch do local t = targets[j] if t then local tt = t local v = j for i = 1, n2 do tt[i] = inter[v] v =v+ ch end end end return end local lb = math.min(r.begin, n2) local le = math.min(r.finish, n2) local partRead = math.floor((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 , r.begin + pcount * psize, psize, rtype, n2) then return end end end end i =i+ 1 pcount =pcount+ 1 end classSet =classSet+ 1 end end end function Packet.decode(st, b, off, size) 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 = math.floor(n / 2 ) local n0 = st.n0 local leftStart, leftEnd, rightStart, rightEnd if mode.blockflag == 1 and not prevLong then leftStart, leftEnd = math.floor((n - n0) / 4), math.floor((n + n0) / 4 ) else leftStart, leftEnd = 0, n2 end if mode.blockflag == 1 and not nextLong then rightStart, rightEnd = math.floor((n * 3 - n0) / 4), math.floor((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= {} local k = 0 for c = 1, ch do if map.mux[c] == i - 1 then k =k+ 1 targets[k] = (zero[c] and{false }or{spec[c] })[1] 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 do local __DARKLUA_VAR=leftStart + j + 1 fr[__DARKLUA_VAR]=fr[__DARKLUA_VAR]* lslope[j + 1] end end local R = rightEnd - rightStart for j = 0, R - 1 do do local __DARKLUA_VAR=rightStart + j + 1 fr[__DARKLUA_VAR]=fr[__DARKLUA_VAR]* rslope[R - j] end 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 = math.floor(prevN / 4 )+ math.floor(n / 4 ) local o = math.floor(prevN / 4 )- math.floor(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 = (j < tl and{tail[j + 1] }or{0 })[1] local fi = j - o if fi >= 0 then v =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"] = function() local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict --!native -- 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 local function isVorbis(b, o, n, kind) return n >= 7 and readu8(b, o) == kind and buffer.readstring(b, o + 1, 6) == "vorbis" end Setup.isVorbis = isVorbis function Setup.ident(b, o, n) 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, math.floor(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 function Setup.comment(b, o, n) 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 =p+ 4 if vlen > e - p then return nil, nil end local vendor = buffer.readstring(b, p, vlen) p =p+ vlen local list = {} if p + 4 > e then return vendor, list end local count = readu32(b, p) p =p+ 4 for _ = 1, count do if p + 4 > e then break end local len = readu32(b, p) p =p+ 4 if len > e - p then break end table.insert(list, buffer.readstring(b, p, len)) p =p+ len end return vendor, list end function Setup.setup(b, o, n, id) 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= {} 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= {} 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, function(a, c) 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= {} 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 = (bits(br, 1) == 1 and{(bits(br, 5) )}or{0 })[1] 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 = math.floor(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 = math.floor(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= {} 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 = (bits(br, 1) == 1 and{(bits(br, 4) + 1 )}or{1 })[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= {} 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() --!strict -- 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 __FILES["codecs/audio/VorbisComment"] = function() local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict -- codecs/audio/VorbisComment: Vorbis comment fields ("KEY=value"; Vorbis, Opus, FLAC) <-> Types.Tags. local VorbisComment = {} local TO_TAG= { tracknumber = "track", discnumber = "disc", description = "comment" } local TO_FIELD= { track = "TRACKNUMBER", disc = "DISCNUMBER" } function VorbisComment.tagKey(name) local k = string.lower(name) return TO_TAG[k] or k end function VorbisComment.fieldName(key) return TO_FIELD[key] or string.upper(key) end function VorbisComment.tags(comments) local tags= {} local raw= {} for _, s in __iter(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] = (old and((old .. "; " .. v ))or(v )) end end return tags, raw end function VorbisComment.fields(tags) local keys = {} for k, v in __iter(tags) do if type(k) == "string" and type(v) == "string" then table.insert(keys, k) end end table.sort(keys) local out= (table.create(#keys) ) for i, k in __iter(keys) do out[i] = VorbisComment.fieldName(k) .. "=" .. tags[k] end return out end return VorbisComment end __FILES["codecs/audio/WavPack"] = function() local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict -- 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 = {} 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, at, limit) 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= { size = ck + 8, version = version, index = buffer.readu32(buf, at + 16) + buffer.readu8(buf, at + 10) * 4294967296, total = total == 0xFFFFFFFF and-1 or 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 function WavPack.info(buf, at, limit) 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= { channels = bit32.band(flags, WavPack.MONO) ~= 0 and 1 or 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 = info.channels == 1 and 4 or 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 =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 =mask+ buffer.readu8(buf, o + 6) * 16777216 end else info.channels = buffer.readu8(buf, o) for k = 1, len - 1 do mask =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, at, limit) 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 local function frame(self, buf, blocks, cbuf, cblocks) local C = self.channels local n = -1 local c0 = 0 for i, at in __iter(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 =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) 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"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 -- 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= table.create(34, 0) for i = 0, 33 do P2[i + 1] = 2 ^ i end local ONES= table.create(256, 0) for b = 0, 255 do local n, v = 0, b while v % 2 == 1 do n =n+ 1 v = math.floor(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 function Block.meta(buf, p, size) local m= {} 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 =q+ 2 if band(id, 0x80) ~= 0 then if stop - q < 2 then return nil, "truncated metadata" end len =len+ (readu8(buf, q) * 512 + readu8(buf, q + 1) * 131072 ) q =q+ 2 id =id- 0x80 end local odd = 0 if band(id, 0x40) ~= 0 then if len == 0 then return nil, "odd-sized empty metadata" end id =id- 0x40 len =len- 1 odd = 1 end if stop - q < len + odd then return nil, "truncated metadata" end m[id] = q m[id + 256] = len q =q+ (len + odd ) end return m, nil end function Block.checksum(buf, p, m) 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 = math.floor((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 function Block.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 } , R2 = { b = buffer.create(0), p = 0, e = 0, n = 0 } , R3 = { b = buffer.create(0), p = 0, e = 0, n = 0 } , scratch = buffer.create(4), } end local function openReader(R, buf, o, len) 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 local function bits(R, n) 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 =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 local function bit(R) return bits(R, 1) end local function trailing(R, max) 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 =c+ 8 R.p = p + 8 end R.p =R.p- (c - max ) return max end -- the "Elias gamma"-like count (cbits ones, a zero, cbits - 1 bits) -> value | nil (33 ones) local function gamma(R) 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 local function readCode(R, maxcode) if maxcode < 2 then return (maxcode == 1 and{(bits(R, 1) )}or{0 })[1] 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) local function onesCount(R) 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 local function wordsLossless(st, count, d) local R= 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 local __DARKLUA_CONTINUE_7=false repeat 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 = math.floor(a0 / 16 ) a0 =a0- (math.floor((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 =pos+ (used + 1 )__DARKLUA_CONTINUE_7=true break end if a0 < 2 and ho == 0 and c0 < 2 then if za > 0 then za =za- 1 if za > 0 then W[idx] = 0 __DARKLUA_CONTINUE_7=true break 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 __DARKLUA_CONTINUE_7=true break 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 =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 = math.floor(ones / 2 )+ hold local low, high if ones == 0 then low = 0 high = math.floor(a0 / 16 ) a0 =a0- (math.floor((a0 + 126) / 128)) * 2 else low = math.floor(a0 / 16 )+ 1 a0 =a0+ (math.floor((a0 + 128) / 128)) * 5 if ones == 1 then high = low + math.floor(a1 / 16 ) a1 =a1- (math.floor((a1 + 62) / 64)) * 2 else low =low+ (math.floor(a1 / 16 )+ 1 ) a1 =a1+ (math.floor((a1 + 64) / 64)) * 5 if ones == 2 then high = low + math.floor(a2 / 16 ) a2 =a2- (math.floor((a2 + 30) / 32)) * 2 else low =low+ (ones - 2) * (math.floor(a2 / 16 )+ 1) high = low + math.floor(a2 / 16 ) a2 =a2+ (math.floor((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 =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 =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 =low+ code end end if band(rshift(w, used), 1) ~= 0 then W[idx] = -low - 1 else W[idx] = low end pos =pos+ (used + 1 )__DARKLUA_CONTINUE_7=true until true if not __DARKLUA_CONTINUE_7 then break end end R.p = pos return pos <= lim end local function updateErrorLimit(st, flags, mono) local bacc, bdelta, slow, limit = st.bacc, st.bdelta, st.slow, st.limit bacc[1] = (bacc[1] + bdelta[1]) % TWO32 local br0 = math.floor(bacc[1] / 65536 ) if mono then if band(flags, HBITRATE) ~= 0 then local sl0 = math.floor((slow[1] + 128) / 256 ) limit[1] = (sl0 - br0 > -256 and((exp2s(sl0 - br0 + 256) % TWO32 ))or(0 )) else limit[1] = exp2s(br0) % TWO32 end return end bacc[2] = (bacc[2] + bdelta[2]) % TWO32 local br1 = math.floor(bacc[2] / 65536 ) if band(flags, HBITRATE) ~= 0 then local sl0 = math.floor((slow[1] + 128) / 256 ) local sl1 = math.floor((slow[2] + 128) / 256 ) if band(flags, HBALANCE) ~= 0 then local balance = math.floor((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] = (sl0 - br0 > -256 and((exp2s(sl0 - br0 + 256) % TWO32 ))or(0 )) limit[2] = (sl1 - br1 > -256 and((exp2s(sl1 - br1 + 256) % TWO32 ))or(0 )) else limit[1] = exp2s(br0) % TWO32 limit[2] = exp2s(br1) % TWO32 end end -- get_word local function getWord(st, chan, flags, mono) local R= 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 =st.za- 1 if st.za > 0 then local s = st.slow do local __DARKLUA_VAR=chan + 1 s[__DARKLUA_VAR]=s[__DARKLUA_VAR]- math.floor((s[chan + 1] + 128) / 256 )end 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 do local __DARKLUA_VAR=chan + 1 s[__DARKLUA_VAR]=s[__DARKLUA_VAR]- math.floor((s[chan + 1] + 128) / 256 )end 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 = math.floor(ones / 2 )+ 1 else st.ho = band(ones, 1) ones = math.floor(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 = math.floor(m0 / 16 ) m0 =m0- (math.floor((m0 + 126) / 128)) * 2 else low = math.floor(m0 / 16 )+ 1 m0 =m0+ (math.floor((m0 + 128) / 128)) * 5 if ones == 1 then high = low + math.floor(m1 / 16 ) m1 =m1- (math.floor((m1 + 62) / 64)) * 2 else low =low+ (math.floor(m1 / 16 )+ 1 ) m1 =m1+ (math.floor((m1 + 64) / 64)) * 5 if ones == 2 then high = low + math.floor(m2 / 16 ) m2 =m2- (math.floor((m2 + 30) / 32)) * 2 else low =low+ (ones - 2) * (math.floor(m2 / 16 )+ 1) high = low + math.floor(m2 / 16 ) m2 =m2+ (math.floor((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 = math.floor((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 = math.floor((high + low + 1) / 2 ) else high = mid - 1 mid = math.floor((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 = (sign == 1 and((mid - value ))or((value - mid ))) end if band(flags, HBITRATE) ~= 0 then local s = st.slow s[chan + 1] = s[chan + 1] - math.floor((s[chan + 1] + 128) / 256 )+ log2(mid) end return (sign == 1 and((-mid - 1 ))or(mid)), correction end -- the decorrelation passes over the whole block (stereo, from W[D2]): unpack.c decorr_stereo_pass local function passesStereo(st, n) 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 + math.floor((a0 - a1) / dv ) local x = W[i] local o = math.floor((wA * sam + 512) / 1024 )+ x wA =wA+ delta * sign(sam * x) a1, a0 = a0, o W[i] = o sam = b0 + math.floor((b0 - b1) / dv ) x = W[i + 1] o = math.floor((wB * sam + 512) / 1024 )+ x wB =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] = math.floor((wA * sam + 512) / 1024 )+ x wA =wA+ delta * sign(sam * x) sam = W[i + 1 - back] x = W[i + 1] W[i + 1] = math.floor((wB * sam + 512) / 1024 )+ x wB =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 + math.floor((wA * sa + 512) / 1024 ) wA = clamp(wA + delta * sign(sa * x), -1024, 1024) W[i] = sam x = W[i + 1] sa = x + math.floor((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 + math.floor((wB * sb + 512) / 1024 ) wB = clamp(wB + delta * sign(sb * x), -1024, 1024) W[i + 1] = sam x = W[i] sb = x + math.floor((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 + math.floor((wA * sa + 512) / 1024 ) wA = clamp(wA + delta * sign(sa * x), -1024, 1024) x = W[i + 1] local samB = x + math.floor((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 local function passesMono(st, n) 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 + math.floor((a0 - a1) / dv ) local x = W[i] local o = math.floor((wA * sam + 512) / 1024 )+ x wA =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] = math.floor((wA * sam + 512) / 1024 )+ x wA =wA+ delta * sign(sam * x) end end end end local function shaped(st, c, flags, correction) -- 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 = math.floor(sacc[c] / 65536 ) if sw >= 32768 then sw =sw- 65536 end local temp = -(math.floor((sw * err[c] + 512) / 1024)) if band(flags, NEW_SHAPING) ~= 0 and sw < 0 and temp ~= 0 then if temp == err[c] then temp = (temp < 0 and((temp + 1 ))or((temp - 1 ))) end err[c] = temp - correction else err[c] = -correction end return temp end local function hybridMono(st, n, flags) 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 = (term % 2 == 1 and((2 * sA[so + 1] - sA[so + 2] ))or((math.floor((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 = math.floor((wAs[t] * sam + 512) / 1024 )+ rw wAs[t]=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 =rw+ (corr - temp ) else rw =rw+ corr end crc = (crc * 3 + rw) % TWO32 W[D1 + i] = rw end st.crcv = crc return true end local function hybridStereo(st, n, flags) 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 = math.floor((3 * sA[so + 1] - sA[so + 2]) / 2 ) samB = math.floor((3 * sB[so + 1] - sB[so + 2]) / 2 ) end else samA, samB = sA[so + m + 1], sB[so + m + 1] end leftc =leftc+ math.floor((wAs[t] * samA + 512) / 1024 ) rightc =rightc+ math.floor((wBs[t] * samB + 512) / 1024 ) elseif term == -1 then leftc =leftc+ math.floor((wAs[t] * sA[so + 1] + 512) / 1024 ) rightc =rightc+ math.floor((wBs[t] * leftc + 512) / 1024 ) else rightc =rightc+ math.floor((wBs[t] * sB[so + 1] + 512) / 1024 ) if term == -3 then leftc =leftc+ math.floor((wAs[t] * sA[so + 1] + 512) / 1024 ) else leftc =leftc+ math.floor((wAs[t] * rightc + 512) / 1024 ) end end end if joint then rightc =rightc- math.floor(leftc / 2 ) leftc =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 = math.floor((3 * sA[so + 1] - sA[so + 2]) / 2 ) samB = math.floor((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 = math.floor((wAs[t] * samA + 512) / 1024 )+ left local right2 = math.floor((wBs[t] * samB + 512) / 1024 )+ right wAs[t]=wAs[t]+ delta * sign(samA * left) wBs[t]=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 + math.floor((wAs[t] * sa + 512) / 1024 ) wAs[t] = clamp(wAs[t] + delta * sign(sa * left), -1024, 1024) left = left2 local right2 = right + math.floor((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 + math.floor((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 + math.floor((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 =rightc- math.floor(leftc / 2 ) leftc =leftc+ rightc end end if joint then right =right- math.floor(left / 2 ) left =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 local function readMeta(st, buf, m, flags, version) 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 =math.floor(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 =q+ 1 if not mono then st.wB[t] = restoreWeight(readi8(buf, q)) 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 + (mono and 2 or 4) > stop then return "bad decorrelation samples" end st.err[1] = exp2s(readi16(buf, q)) q =q+ 2 if not mono then st.err[2] = exp2s(readi16(buf, q)) 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 + (mono and 4 or 8) > stop then return "bad decorrelation samples" end sA[so + 1], sA[so + 2] = exp2s(readi16(buf, q)), exp2s(readi16(buf, q + 2)) q =q+ 4 if not mono then sB[so + 1], sB[so + 2] = exp2s(readi16(buf, q)), exp2s(readi16(buf, q + 2)) q =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 =q+ 4 else for k = 1, term do if q + (mono and 2 or 4) > stop then return "bad decorrelation samples" end sA[so + k] = exp2s(readi16(buf, q)) q =q+ 2 if not mono then sB[so + k] = exp2s(readi16(buf, q)) q =q+ 2 end end end t =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] ~= (mono and 6 or 12) then return "bad entropy variables" end for k = 0, (mono and 2 or 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 = mono and 2 or 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 =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 =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 =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 >= (mono and 4 or 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 + (mono and 4 or 8) if len == (mono and 6 or 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) local function floatValue(st, v, R) 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 =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 =exp- 1 if exp == 0 then break end shift =shift+ 1 v =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 =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 = (minZeros > shift and{shift }or{minZeros })[1] 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 =math.floor(v/ 2 ) exp =exp+ 1 end elseif exp > 0 then local shift = 0 while v < 0x800000 do exp =exp- 1 if exp == 0 then break end shift =shift+ 1 v =v* 2 end shift = band(shift, 31) if shift > 0 and band(fflags, FLOAT_SHIFT_ONES) ~= 0 then v =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 local function emit(st, flags, n, d, P, c0, C, lossy) local W = st.W local s = d == D2 and 2 or 1 local count = n * s local R= (st.wvx and{st.R3 }or{nil })[1] 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 = (v < 0 and((-v - 1 ))or(v )) local width = (32 - countlz(pv)) + sent local btr = sent if width > maxw then btr =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 =v* P2[sent + 1] end else v = v * P2[sent + 1] + bits(R, sent) end end if zeros > 0 then v =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 =v% TWO32 if v >= 2147483648 then v =v- TWO32 end crc = (crc * 9 + (v % 65536) * 3 + (math.floor(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 =zeros- 1 elseif ones > 0 then ones =ones- 1 elseif dups > 0 then dups =dups- 1 else break end shift =shift+ 1 end for k = d, d + count - 1 do local v = W[k] if zeros > 0 then v =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 =shift+ (zeros + sent + ones + dups ) end end shift = band(shift, 31) if lossy then local bytes = band(flags, 3) local top = bytes == 0 and 127 or(bytes == 1 and 32767 or(bytes == 2 and 8388607 or 2147483647 )) local minv, maxv = math.floor((-top - 1) / P2[shift + 1]), math.floor(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]=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 function Block.decode(st, buf, p, size, P, c0, C, cbuf, cp, csize) 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= mm local cm= {} local cb= 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 = band(flags, MONO_FLAG) ~= 0 and 1 or 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 = xm[0x2C] and 0x2C or(xm[0xC] and 0xC or 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 = (mono and{D1 }or{D2 })[1] 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, (mono and{n }or{(2 * n)})[1], 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] - math.floor(l / 2 ) l =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 = (mono and{(hybridMono(st, n, flags) )}or{(hybridStereo(st, n, flags) )})[1] 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"] = function() local __compat = __compat local bit32 = __compat.bit32 --!strict --!native --!optimize 2 -- 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= { 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= { 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, } function Tables.exp2s(lg) if lg < 0 then local v = Tables.exp2s(-lg) v = -((v >= 2147483648 and((v - 4294967296 ))or(v))) return (v >= 2147483648 and((v - 4294967296 ))or(v )) end local value = bit32.bor(EXP2[band(lg, 255) + 1], 0x100) local k = math.floor(lg / 256 ) local r = (k <= 9 and{(rshift(value, 9 - k) )}or{(lshift(value, band(k - 9, 31)) )})[1] return (r >= 2147483648 and((r - 4294967296 ))or(r ))end function Tables.log2(v) 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 function Tables.restoreWeight(w) local r = w * 8 if r > 0 then r =r+ math.floor((r + 64) / 128 ) end return r end return Tables end __FILES["codecs/compress/Brotli"] = function() local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict -- 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 = {} -- the tables are base64 text (trusted, generated by tools/brotli_static.py) local function unbase64(s) return Base64.decode(s) or buffer.create(0) end local static= nil local function tables() 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() local s = tables() return (s and{s.dictionary }or{nil })[1]end function Brotli.decompress(buf, offset, length, opts) local b, o, l, aerr = Bytes.span("Brotli.decompress", buf, offset, length) if not b then return nil, aerr end local maxBytes = (opts and opts.maxBytes and{opts.maxBytes }or{(2 ^ 30 )})[1] 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"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 -- 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 = {} 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 =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 = math.floor(v / 2 ) end writeu8(REV8, i, r) end local function reverse(code, len) 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) local function prepare(lens, n) 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]=count[l]+ 1 used =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]=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 =size+ lshift(1, k) end end return size end local function build(lens, n, T, at) local single = -1 local used = 0 for s = 0, n - 1 do if readu8(lens, s) > 0 then used =used+ 1 single = s end end if used <= 1 then local e = (single < 0 and 0 or 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 =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 =i+ step end end end end end -- largest distance alphabet under MAX_ALLOWED_DISTANCE, as the reference's BrotliCalculateDistanceCodeLimit local function distanceLimit(maxDistance, npostfix, ndirect) if maxDistance <= ndirect then return maxDistance + 16 end local offset = maxDistance + 1 - ndirect - 1 offset = rshift(offset, npostfix) + 4 local ndistbits = 0 local tmp = math.floor(offset / 2 ) while tmp ~= 0 do ndistbits =ndistbits+ 1 tmp = rshift(tmp, 1) end ndistbits =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 =group- 1 local postfix = lshift(1, npostfix) - 1 return bor(lshift(group, npostfix), postfix) + ndirect + 16 + 1 end function Decode.decompress(src, off, len, maxBytes, S, largeWindow) local lim = off + len local ip = off local bb, bc = 0, 0 local function fill() while bc <= 24 do local byte = 0 if ip < lim then byte = readu8(src, ip) end ip =ip+ 1 bb = bor(bb, lshift(byte, bc)) bc =bc+ 8 end end local function bits(n) if bc < n then fill() end local v = band(bb, lshift(1, n) - 1) bb = rshift(bb, n) bc =bc- n return v end local function bitsLong(n) if n <= 24 then return bits(n) end local lo = bits(16) return lo + bits(n - 16) * 65536 end local function overrun() 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) local function decodeSym(base) 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 =bc- l return rshift(e, 5) end local function install(n) 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 =tpos+ size return base end local function readCode(alphabetMax, limit) 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 =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 =bc- dl writeu8(CLL, CL_ORDER[i], v) if v ~= 0 then space =space- rshift(32, v) num =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 =bc- l local cl = rshift(e, 5) if cl < 16 then rep = 0 writeu8(LENS, sym, cl) if cl ~= 0 then prev = cl space =space- rshift(32768, cl) end sym =sym+ 1 else local extra = cl == 16 and 2 or 3 local d = bits(extra) local newLen = (cl == 16 and{prev }or{0 })[1] if repLen ~= newLen then rep = 0 repLen = newLen end local old = rep if rep > 0 then rep = (rep - 2) * lshift(1, extra) end rep =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 =space- delta * rshift(32768, repLen) end sym =sym+ delta end if overrun() then return -1 end end if space ~= 0 then return -1 end return install(limit) end local function varLen8() 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 local function blockLen(base) local code = decodeSym(base) return BL_OFF[code + 1] + bits(BL_BITS[code + 1]) end local function readContextMap(size) 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 =i+ 1 elseif code > rleMax then writeu8(map, i, code - rleMax) i =i+ 1 else local reps = lshift(1, code) + bits(code) if i + reps > size then return -1, map end i =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 local __DARKLUA_CONTINUE_26=false repeat -- 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 =mlen+ b * 2 ^ (8 * i) end if nbytes > 0 then mlen =mlen+ 1 end local pad = band(bc, 7) if pad > 0 and bits(pad) ~= 0 then return nil, "nonzero padding" end ip =ip- rshift(bc, 3) bb, bc = 0, 0 if ip + mlen > lim then return nil, "truncated metadata" end ip =ip+ mlen if isLast then break end __DARKLUA_CONTINUE_26=true break 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 =mlen+ v * 2 ^ (4 * i) end mlen =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 =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 =ip+ mlen op =op+ mlen if isLast then break end __DARKLUA_CONTINUE_26=true break 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(large and 62 or 24, npostfix + 1) local distLimit = (large and{(distanceLimit(MAX_ALLOWED_DISTANCE, npostfix, ndirect) )}or{distMax })[1] 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 =t- 2 end if t >= nbtI then t =t- nbtI end prevI, typeI = typeI, t cntI = blockLen(blTreeI) cmdTree = cmdBase[t + 1] end cntI =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 =insLen+ bits(ie) end local cpyLen = CPY_BASE[cpyCode + 1] local ce = CPY_EXTRA[cpyCode + 1] if ce > 0 then cpyLen =cpyLen+ bits(ce) end if insLen > remaining then return nil, "insert past the meta-block end" end if insLen > 0 then local p1 = (op > 0 and{(readu8(out, op - 1) )}or{0 })[1] local p2 = (op > 1 and{(readu8(out, op - 2) )}or{0 })[1] 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 =t- 2 end if t >= nbtL then t =t- nbtL end prevL, typeL = typeL, t cntL = blockLen(blTreeL) lutBase = modes[t + 1] * 512 litSlice = t * 64 end cntL =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 =ip+ 2 bc =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 =bc- l local lit = rshift(e, 5) writeu8(out, op, lit) op =op+ 1 p2 = p1 p1 = lit end remaining =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 =t- 2 end if t >= nbtD then t =t- nbtD end prevD, typeD = typeD, t cntD = blockLen(blTreeD) distSlice = t * 4 end cntD =cntD- 1 local dctx = cpyLen > 4 and 3 or 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 = math.floor((dcode - 2) / 2 -- 4,5 -> 1; 6,7 -> 2; 8,9 -> 3 ) dist = (dcode % 2 == 0 and((d0 - k ))or((d0 + k ))) else local k = math.floor((dcode - 8) / 2 -- 10,11 -> 1; ... ) dist = (dcode % 2 == 0 and((d1 - k ))or((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 = (op < maxBackward and{op }or{maxBackward })[1] 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 =w+ 1 end local wl = cpyLen local wo = woff if ttype <= 9 then wl =wl- ttype elseif ttype >= 12 and ttype <= 20 then local skip = ttype - 11 wo =wo+ skip wl =wl- skip end local ws = w if wl > 0 then bcopy(WORD, w, dict, wo, wl) w =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 =p+ step left =left- step end end local sl = readu8(PS, sfx) for k = 1, sl do writeu8(WORD, w, readu8(PS, sfx + k)) w =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 =op+ w remaining =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 =op+ cpyLen remaining =remaining- cpyLen end end if isLast then break end __DARKLUA_CONTINUE_26=true until true if not __DARKLUA_CONTINUE_26 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 =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() --!strict -- 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 __FILES["codecs/compress/Bzip2"] = function() local __compat = __compat local buffer, bit32, type = __compat.buffer, __compat.bit32, __compat.type --!strict -- 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 = {} function Bzip2.decompress(buf, offset, length, opts) local b, o, l, aerr = Bytes.span("Bzip2.decompress", buf, offset, length) if not b then return nil, aerr end local maxBytes = (opts and opts.maxBytes ~= nil and{opts.maxBytes }or{(2 ^ 30 )})[1] 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, offset, length) 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"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 -- 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] = i == 32 and 0xFFFFFFFF or 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) local function buildGroup(g, n) 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) do local __DARKLUA_VAR=cbase + l + 1 COUNT[__DARKLUA_VAR]=COUNT[__DARKLUA_VAR]+ 1 end 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 =code+ c idx =idx+ c if code > 2 ^ l then return false end code =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 local function grow(out, op, need) local nb = bcreate(math.max(blen(out) * 2, need, 65536)) bcopy(nb, 0, out, 0, op) return nb end function Decode.decode(b, o, e, maxBytes) 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= 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 p =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), (p < e and{(readu8(b, p) )}or{0})[1]) p =p+ 1 bc =bc+ 8 end local m1 = band(rshift(bb, bc - 24), 0xFFFFFF) bc =bc- 24 while bc <= 24 do bb = bor(lshift(bb, 8), (p < e and{(readu8(b, p) )}or{0})[1]) p =p+ 1 bc =bc+ 8 end local m2 = band(rshift(bb, bc - 24), 0xFFFFFF) bc =bc- 24 while bc <= 24 do bb = bor(lshift(bb, 8), (p < e and{(readu8(b, p) )}or{0})[1]) p =p+ 1 bc =bc+ 8 end local c1 = band(rshift(bb, bc - 16), 0xFFFF) bc =bc- 16 while bc <= 24 do bb = bor(lshift(bb, 8), (p < e and{(readu8(b, p) )}or{0})[1]) p =p+ 1 bc =bc+ 8 end local storedCrc = band(rshift(bb, bc - 16), 0xFFFF) + c1 * 65536 bc =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 =p- math.floor(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), (p < e and{(readu8(b, p) )}or{0})[1]) p =p+ 1 bc =bc+ 8 end local rnd = band(rshift(bb, bc - 1), 1) bc =bc- 1 while bc <= 24 do bb = bor(lshift(bb, 8), (p < e and{(readu8(b, p) )}or{0})[1]) p =p+ 1 bc =bc+ 8 end local origPtr = band(rshift(bb, bc - 24), 0xFFFFFF) bc =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), (p < e and{(readu8(b, p) )}or{0})[1]) p =p+ 1 bc =bc+ 8 end local used = band(rshift(bb, bc - 16), 0xFFFF) bc =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), (p < e and{(readu8(b, p) )}or{0})[1]) p =p+ 1 bc =bc+ 8 end local bits = band(rshift(bb, bc - 16), 0xFFFF) bc =bc- 16 for j = 0, 15 do if band(bits, lshift(1, 15 - j)) ~= 0 then SEQ[nInUse + 1] = i * 16 + j nInUse =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), (p < e and{(readu8(b, p) )}or{0})[1]) p =p+ 1 bc =bc+ 8 end local nGroups = band(rshift(bb, bc - 3), 7) bc =bc- 3 local nSelectors = band(rshift(bb, bc - 15), 0x7FFF) bc =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), (p < e and{(readu8(b, p) )}or{0})[1]) p =p+ 1 bc =bc+ 8 end bc =bc- 1 if band(rshift(bb, bc), 1) == 0 then break end j =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), (p < e and{(readu8(b, p) )}or{0})[1]) p =p+ 1 bc =bc+ 8 end local len = band(rshift(bb, bc - 5), 31) bc =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), (p < e and{(readu8(b, p) )}or{0})[1]) p =p+ 1 bc =bc+ 8 end bc =bc- 1 if band(rshift(bb, bc), 1) == 0 then break end bc =bc- 1 if band(rshift(bb, bc), 1) == 0 then len =len+ 1 else len =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 =selIdx+ 1 left = 50 tbase = g * PSIZE * 4 pbase = g * MAXALPHA cbase = g * (MAXLEN + 1) gmax = MAXL[g + 1] end left =left- 1 while bc <= 24 do bb = bor(lshift(bb, 8), (p < e and{(readu8(b, p) )}or{0})[1]) p =p+ 1 bc =bc+ 8 end local ent = readu32(LOOK, tbase + band(rshift(bb, bc - PBITS), PSIZE - 1) * 4) local sym if ent ~= 0 then bc =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 =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 =runLen+ runBit * (sym + 1) runBit =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] do local __DARKLUA_VAR=ch + 1 CFTAB[__DARKLUA_VAR]=CFTAB[__DARKLUA_VAR]+ runLen end for k = nblock, nblock + runLen - 1 do writeu32(T, k * 4, ch) end nblock =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] do local __DARKLUA_VAR=ch + 1 CFTAB[__DARKLUA_VAR]=CFTAB[__DARKLUA_VAR]+ 1 end writeu32(T, nblock * 4, ch) nblock =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 =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 =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 =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 =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 =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 =streams+ 1 consumedEnd = p if p >= e then break end end return out, op, consumedEnd end return Decode end __FILES["codecs/compress/Deflate"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict -- 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, n) 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, at) local code = (string.find(msg, "truncated", 1, true) and{Err.TRUNCATED }or{Err.CORRUPT })[1] return Err.new(code, "inflate: " .. msg, at) end function Deflate.inflate(buf, offset, length, expectedSize, dict) 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 , exact, false, dict) if not out then return nil, inflateErr(tostring(n), o) end if dict then local d = buffer.len(dict) n =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 )) end return shrink(out, n), consumed end function Deflate.zlib(buf, offset, length, expectedSize) 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 math.floor(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, p, e) 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 =q+ (2 + buffer.readu16(b, q) ) end for _, bit in __iter({ 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 =q+ 1 end q =q+ 1 end end if bit32.band(flg, 2) ~= 0 then -- FHCRC q =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, offset, length) 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 =total+ buffer.len(out) p = consumed + 8 local z = p while z < e and buffer.readu8(b, z) == 0 do z =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 __iter(parts) do buffer.copy(res, w, part) w =w+ buffer.len(part) end return res, nil end function Deflate.peek(buf, offset, length, n) 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 math.floor(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 , e, n, true, true) if not out then return nil, inflateErr(tostring(k), q) end return shrink(out, k), nil end local function level(opts) local lv = (opts and opts.level ~= nil and{opts.level }or{6 })[1] 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, opts) 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, opts) 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 = lv < 2 and 0 or(lv < 6 and 1 or(lv == 6 and 2 or 3 )) local cmf = 0x78 local flg = flevel * 64 flg =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, opts) 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, lv >= 9 and 2 or(lv <= 1 and 4 or 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, blocks) local total = 0 for _, b in __iter(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 =total+ b.size end local out = buffer.create(total) local o = 0 for _, b in __iter(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= nil if o > 0 then local d = math.min(o, 32768) dict = buffer.create(d) buffer.copy(dict , 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 =o+ b.size end return out, nil end Deflate.crc32 = function(buf, offset, length, crc) local b = toBuffer(buf) or buffer.create(0) return Crc32.of(b, offset, length, crc) end Deflate.adler32 = function(buf, offset, length, adler) local b = toBuffer(buf) or buffer.create(0) return Adler32.of(b, offset, length, adler) end return Deflate end __FILES["codecs/compress/Deflate/Compress"] = function() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict --!native --!optimize 2 -- 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 = c == 29 and 258 or(c == 28 and 257 or 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 = c == 30 and 32768 or 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[math.floor((k - 1) / 128 )+ 1] = c - 1 end end end local function dcode(d) if d <= 256 then return DSMALL[d] end return DLARGE[math.floor((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] = i <= 144 and 8 or(i <= 256 and 9 or(i <= 280 and 7 or 8 ))end local FIXDLEN = table.create(30, 5) local function revCodes(lens) local codes = Huffman.codes(lens) for i, l in __iter(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 local function ensure(o, n) 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 local function put(o, v, n) 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 =op+ 1 acc = (acc - byte) / 256 cnt =cnt- 8 end o.op = op end o.acc, o.cnt = acc, cnt end local function alignOut(o) if o.cnt > 0 then put(o, 0, 8 - o.cnt) end end local function storedBlock(o, src, s, e, final) local p = s repeat local n = math.min(65535, e - p) local last = final and p + n >= e put(o, last and 1 or 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 =o.op+ (4 + n ) p =p+ n until p >= e end local function emitSymbols(o, L, D, nsym, lcode, llen, dcodes, dlen) 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 local function block(o, src, s, e, L, D, nsym, final) 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 do local __DARKLUA_VAR=l + 1 lf[__DARKLUA_VAR]=lf[__DARKLUA_VAR]+ 1 end else local len = l - 256 do local __DARKLUA_VAR=LCODE[len] + 1 lf[__DARKLUA_VAR]=lf[__DARKLUA_VAR]+ 1 end extra =extra+ LEXTRA[len] local dc = dcode(D[i]) do local __DARKLUA_VAR0=dc + 1 df[__DARKLUA_VAR0]=df[__DARKLUA_VAR0]+ 1 end extra =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 =hlit- 1 end local hdist = 30 while hdist > 1 and dlen[hdist] == 0 do hdist =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 =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]=cf[19]+ 1 else table.insert(cs, 17) table.insert(cx, r - 3) cf[18]=cf[18]+ 1 end i =i+ r elseif v ~= 0 and run >= 4 then table.insert(cs, v) table.insert(cx, 0) do local __DARKLUA_VAR=v + 1 cf[__DARKLUA_VAR]=cf[__DARKLUA_VAR]+ 1 end local r = math.min(run - 1, 6) table.insert(cs, 16) table.insert(cx, r - 3) cf[17]=cf[17]+ 1 i =i+ (1 + r ) else table.insert(cs, v) table.insert(cx, 0) do local __DARKLUA_VAR=v + 1 cf[__DARKLUA_VAR]=cf[__DARKLUA_VAR]+ 1 end i =i+ 1 end end local clen = Huffman.lengths(cf, 7) local hclen = 19 while hclen > 4 and clen[CLORDER[hclen] + 1] == 0 do hclen =hclen- 1 end local dyn = 17 + 3 * hclen + extra for k = 1, 19 do dyn =dyn+ cf[k] * clen[k] end dyn =dyn+ (cf[17] * 2 + cf[18] * 3 + cf[19] * 7 ) local fix = 3 + extra for k = 1, 286 do dyn =dyn+ lf[k] * llen[k] fix =fix+ lf[k] * FIXLEN[k] end for k = 1, 30 do dyn =dyn+ df[k] * dlen[k] fix =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, final and 3 or 2, 3) emitSymbols(o, L, D, nsym, FIXCODE, FIXLEN, FIXDCODE, FIXDLEN) return end put(o, final and 5 or 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 = {} function Compress.raw(src, off, len, level) local o= { buf = bcreate(math.max(64, math.floor(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 local function hash(p) return ((readu8(src, p) * 251 + readu8(src, p + 1)) * 251 + readu8(src, p + 2)) % HSIZE end local function insert(p) local h = hash(p) + 1 prev[p % WSIZE + 1] = head[h] head[h] = p end local function find(p, steps) 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 =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 =steps- 1 end if best < 3 then return 0, 0 end return best, bestDist end local function flush(upto, final) 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, (mlen >= good and{(math.floor(maxChain / 4 ))}or{maxChain})[1]) if l2 > mlen then nsym =nsym+ 1 L[nsym] = readu8(src, p) D[nsym] = 0 p =p+ 1 insert(p) mlen, mdist = l2, d2 end end end if mlen >= 3 then nsym =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 =q+ 1 end p =p+ mlen else nsym =nsym+ 1 L[nsym] = readu8(src, p) D[nsym] = 0 p =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"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 -- 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, FDISTS 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 = {} local function grow(out, op, need) local cap = math.max(blen(out) * 2, need, 1024) local nb = bcreate(cap) bcopy(nb, 0, out, 0, op) return nb, cap end function Inflate.raw(src, start, endpos, cap, exact, prefix, dict) local op = 0 if dict then op = blen(dict) cap =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) ) local clt = bcreate(CLCAP * 4) local lens = bcreate(320) local final = 0 repeat local __DARKLUA_CONTINUE_1=false 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 =pos+ nb bitcnt =bitcnt+ nb * 8 else while bitcnt <= 24 do if pos < endpos then bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt)) pos =pos+ 1 else over =over+ 1 if over > 4 then return nil, "truncated input" end end bitcnt =bitcnt+ 8 end end end final = band(bitbuf, 1) local btype = band(rshift(bitbuf, 1), 3) bitbuf = rshift(bitbuf, 3) bitcnt =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 =bitcnt- k local real = rshift(bitcnt, 3) - over if real < 0 then return nil, "truncated input" end pos =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 =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 =op+ n pos =pos+ n __DARKLUA_CONTINUE_1=true break end local lsub, dsub 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) ) 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 =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 =pos+ nb bitcnt =bitcnt+ nb * 8 else while bitcnt <= 24 do if pos < endpos then bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt)) pos =pos+ 1 else over =over+ 1 if over > 4 then return nil, "truncated input" end end bitcnt =bitcnt+ 8 end end end writeu8(lens, CLORDER[i], band(bitbuf, 7)) bitbuf = rshift(bitbuf, 3) bitcnt =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 =pos+ nb bitcnt =bitcnt+ nb * 8 else while bitcnt <= 24 do if pos < endpos then bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt)) pos =pos+ 1 else over =over+ 1 if over > 4 then return nil, "truncated input" end end bitcnt =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 =bitcnt- l local sym = rshift(e, 5) if sym < 16 then writeu8(lens, i, sym) i =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 =bitcnt- 2 elseif sym == 17 then val = 0 rep = 3 + band(bitbuf, 7) bitbuf = rshift(bitbuf, 3) bitcnt =bitcnt- 3 else val = 0 rep = 11 + band(bitbuf, 127) bitbuf = rshift(bitbuf, 7) bitcnt =bitcnt- 7 end if i + rep > total then return nil, "too many code lengths" end bfill(lens, i, val, rep) i =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 =pos+ nb bitcnt =bitcnt+ nb * 8 else while bitcnt <= 24 do if pos < endpos then bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt)) pos =pos+ 1 else over =over+ 1 if over > 4 then return nil, "truncated input" end end bitcnt =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 =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 =op+ 1 elseif sym == 256 then break else sym =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 =pos+ nb bitcnt =bitcnt+ nb * 8 else while bitcnt <= 24 do if pos < endpos then bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt)) pos =pos+ 1 else over =over+ 1 if over > 4 then return nil, "truncated input" end end bitcnt =bitcnt+ 8 end end end local len = LBASE[sym] local xb = LEXT[sym] if xb > 0 then len =len+ band(bitbuf, lshift(1, xb) - 1) bitbuf = rshift(bitbuf, xb) bitcnt =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 =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 =pos+ nb bitcnt =bitcnt+ nb * 8 else while bitcnt <= 24 do if pos < endpos then bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt)) pos =pos+ 1 else over =over+ 1 if over > 4 then return nil, "truncated input" end end bitcnt =bitcnt+ 8 end end end dist =dist+ band(bitbuf, lshift(1, xb) - 1) bitbuf = rshift(bitbuf, xb) bitcnt =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 =op+ len elseif dist == 1 then bfill(out, op, readu8(out, s), len) op =op+ len else local rem = len while rem > 0 do local k = math.min(op - s, rem) bcopy(out, op, out, s, k) op =op+ k rem =rem- k end end end end __DARKLUA_CONTINUE_1=true until true if not __DARKLUA_CONTINUE_1 then break 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 __FILES["codecs/compress/Explode"] = function() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict --!native --!optimize 2 -- 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 } local function construct(rep) local lengths= {} for _, b in __iter(rep) do local len = b % 16 for _ = 0, math.floor(b / 16 )do table.insert(lengths, len) end end local count = table.create(MAXBITS + 1, 0) for _, l in __iter(lengths) do do local __DARKLUA_VAR=l + 1 count[__DARKLUA_VAR]=count[__DARKLUA_VAR]+ 1 end 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 __iter(lengths) do if l ~= 0 then do local __DARKLUA_VAR=l + 1 offs[__DARKLUA_VAR]=offs[__DARKLUA_VAR]+ 1 end 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) function Explode.decompress(buf, offset, length, maxOut) local b, o, l, aerr = Bytes.span("Explode.decompress", buf, offset, length) if not b then return nil, aerr end local src= 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 =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 local function bits(need) while bitcnt < need do if p >= stop then truncated = true return 0 end bitbuf =bitbuf+ readu8(src, p) * 2 ^ bitcnt p =p+ 1 bitcnt =bitcnt+ 8 end local v = bitbuf % 2 ^ need bitbuf = (bitbuf - v) / 2 ^ need bitcnt =bitcnt- need return v end local function decode(h) 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 =code+ (1 - bit ) local c = count[len + 1] if code < first + c then return symbol[index + code - first + 1] end index =index+ c first = (first + c) * 2 code =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 = len == 2 and 2 or 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 =n+ len else local sym = (lit == 1 and{(decode(LIT) )}or{(bits(8) )})[1] 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 =cap* 2 local grown = buffer.create(cap) buffer.copy(grown, 0, out, 0, n) out = grown end writeu8(out, n, sym) n =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"] = function() local __compat = __compat local buffer, bit32, type = __compat.buffer, __compat.bit32, __compat.type --!strict --!native --!optimize 2 -- 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 = {} 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 function Lz4.decodeInto(src, p, limit, dst, d, dstLimit, histStart) 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 =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 =p+ 1 lit =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 =p+ lit d =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 =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 =p+ 1 ml =ml+ b end end ml =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 =d+ ml elseif off == 1 then buffer.fill(dst, d, readu8(dst, s), ml) d =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 =d+ c n =n- c end end end end function Lz4.decompress(src, offset, length, outSize, opts) 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 function Lz4.bound(n) return n + math.floor(n / 255 )+ 16 end local function extend(dst, o, n) while n >= 255 do writeu8(dst, o, 255) o =o+ 1 n =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 local function hash(v) local vl, vh = band(v, 0xFFFF), rshift(v, 16) local mid = (vh * 0x79B1 + vl * 0x9E37) % 65536 return math.floor(((vl * 0x79B1 + mid * 65536) % 4294967296) / (2 ^ (32 - HASH_BITS)) )+ 1 end local hashTable= table.create(HASH_SIZE, -1e9) function Lz4.encodeInto(src, p, n, dst, d) 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 =ip- 1 ref =ref- 1 end local a = ip + MINMATCH local bpos = ref + MINMATCH while a + 4 <= matchEnd and readu32(src, a) == readu32(src, bpos) do a =a+ 4 bpos =bpos+ 4 end while a < matchEnd and readu8(src, a) == readu8(src, bpos) do a =a+ 1 bpos =bpos+ 1 end local ml = a - ip local lit = ip - anchor local tok = op op =op+ 1 local tl = lit >= 15 and 15 or lit if lit >= 15 then op = extend(dst, op, lit - 15) end if lit > 0 then bcopy(dst, op, src, anchor, lit) op =op+ lit end writeu16(dst, op, ip - ref) op =op+ 2 local m = ml - MINMATCH local tm = m >= 15 and 15 or 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 =ip+ rshift(skip, 6) -- step up over incompressible data (the reference's acceleration) skip =skip+ 1 end end end local lit = iend - anchor local tok = op 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 =op+ lit end return op - d end function Lz4.compress(src, offset, length) 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"] = function() local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict --!native --!optimize 2 -- 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 local function reader(src, off, len) return { src = src, pos = off, limit = math.min(off + len, buffer.len(src)), acc = 0, cnt = 0, over = 0 } end local function fill(r) while r.cnt <= 24 do local b = 0 if r.pos < r.limit then b = readu8(r.src, r.pos) r.pos =r.pos+ 1 else r.over =r.over+ 8 end r.acc = r.acc * 256 + b r.cnt =r.cnt+ 8 end end local function peek(r, n) if r.cnt < n then fill(r) end return floor(r.acc / 2 ^ (r.cnt - n)) % 2 ^ n end local function skip(r, n) if r.cnt < n then fill(r) end r.cnt =r.cnt- n r.acc = r.acc % 2 ^ r.cnt end local function bits(r, n) if n == 0 then return 0 end local v = peek(r, n) skip(r, n) return v end local function newTable(nsym, P) return { tab = buffer.create(Huffman.capacity(nsym, P, 16) * 4), P = P, S = 0, single = -1 } end local function build(t, lens, n) 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 local function decodeSym(r, t) 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) local function lengthValue(r) local len = bits(r, 3) if len == 7 then while bits(r, 1) == 1 do len =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 local function readLengths(r, t, nbits, maxN, special) 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 =i+ z end i =i+ 1 end return build(t, lens, math.min(i, maxN)) end local function readCodes(r, temp, codes) 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 = c == 0 and 1 or(c == 1 and{(bits(r, 4) + 3 )}or{(bits(r, 9) + 20 )})[1] i =i+ count else if c - 2 > 16 then return false end writeu8(lens, i, c - 2) i =i+ 1 end end return build(codes, lens, n) end local OFFSET_BITS = { lh4 = 4, lh5 = 4, lh6 = 5, lh7 = 5, lhx = 5 } local function decodeNew(src, off, len, out, n, method) 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 r.over > 0 and"truncated" or"bad Huffman table" end if r.over > 32 then return "truncated" end if remaining == 0 then return "empty block" end end remaining =remaining- 1 local c = decodeSym(r, codes) if c < 0 then return "bad code" end if c < 256 then writeu8(out, o, c) o =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, (from >= 0 and{(readu8(out, from) )}or{0x20})[1]) o =o+ 1 from =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 __iter(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 =code+ iter offset =offset+ 1 end end end local function decodeLh1(src, off, len, out, n) 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 local function initGroups() for i = 0, NUM_NODES - 1 do groups[i + 1] = i end numGroups = 0 end local function allocGroup() local g = groups[numGroups + 1] numGroups =numGroups+ 1 return g end local function freeGroup(g) numGroups =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 =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 =ni- 1 c =c- 2 end end local function makeLeader(ni) 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 __iter({ 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 local function incrementNode(ni) do local __DARKLUA_VAR=ni + 1 freq[__DARKLUA_VAR]=freq[__DARKLUA_VAR]+ 1 end if ni < NUM_NODES - 1 and group[ni + 1] == group[ni + 2] then do local __DARKLUA_VAR0=group[ni + 1] + 1 leader[__DARKLUA_VAR0]=leader[__DARKLUA_VAR0]+ 1 end 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 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], math.floor((freq[i + 1] + 1) / 2 ) li =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 =i- 1 lp =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 =i- 1 lp =lp- 1 end leaf[i + 1], freq[i + 1], child[i + 1] = false, f, c parent[c + 1], parent[c] = i, i i =i- 1 c =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 =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]=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 =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, (from >= 0 and{(readu8(out, from) )}or{0x20})[1]) o =o+ 1 from =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) local function decodeLzs(src, off, len, out, n) 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 =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 =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 =p+ 1 end end for i = 0, 255 do writeu8(LZ5_INIT, p, i) p =p+ 1 end for i = 0, 255 do writeu8(LZ5_INIT, p, 255 - i) p =p+ 1 end p =p+ 128 for _ = 1, 110 do writeu8(LZ5_INIT, p, 0x20) p =p+ 1 end end local function decodeLz5(src, off, len, out, n) 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 =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 =p+ 1 writeu8(out, o, b) writeu8(ring, rp, b) rp = (rp + 1) % 4096 o =o+ 1 else if p + 2 > limit then return "truncated" end local c0, c1 = readu8(src, p), readu8(src, p + 1) p =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 =o+ 1 end end end end return nil end local function decodeArj4(src, off, len, out, n) local r = reader(src, off, len) local function prefixed(start, stop) local plus, pwr = 0, lshift(1, start) local width = start while width < stop do if bits(r, 1) == 0 then break end plus =plus+ pwr pwr =pwr* 2 width =width+ 1 end return ((width ~= 0 and{(bits(r, width) )}or{0})[1]) + 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 =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, (from >= 0 and{(readu8(out, from) )}or{0})[1]) o =o+ 1 from =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" } function Lzh.decode(src, off, len, outSize, method) 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 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/Lzma"] = function() local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict -- 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 local toBuffer = Bytes.toBuffer local args = Bytes.span local function maxOf(opts) local m = opts and opts.maxBytes return (type(m) == "number" and m >= 0 and{m }or{DEFAULT_MAX })[1]end local function fail(msg, at) 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) if d >= 225 then return nil, 0, 0 end return d % 9, (math.floor(d / 9)) % 5, math.floor(d / 45 )end Lzma.propsByte = propsByte local function decodeLzma(st, b, o, e, unpackSize) local ip, ierr = Decode.rcInit(st, b, o, e) if not ip then return nil, fail(ierr, o) end local target = (unpackSize and((st.op + unpackSize ))or(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 , nil end function Lzma.lzma(buf, offset, length, props, unpackSize, opts) 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((unpackSize and{unpackSize }or{(l * 4)})[1], 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, offset, length, opts) 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= 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, b, o, e) 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 =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 = (math.floor(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 =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, offset, length, _dictSize, unpackSize, opts) 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((type(unpackSize) == "number" and unpackSize >= 0 and{unpackSize }or{(l * 4)})[1], 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= { [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, b, o, n, props) local pb = toBuffer(props) local plen = (pb and{(buffer.len(pb) )}or{0 })[1] 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 , 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 , 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, p, e) 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 =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 =mul* 128 end return nil, p end Lzma.vli = vli local function crc(b, o, n) return Crc32.raw(b, o, n) end local function xzStream(st, b, o, e) 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= {} 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= nil, nil if flags >= 128 or (math.floor(flags / 64)) % 2 == 1 then if (math.floor(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= {} 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 =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 = (csz and((dstart + csz ))or(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 =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 =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 =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, offset, length, opts) 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 =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 =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, o) 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"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 -- 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 = {} function Crc64.of(b, o, n) 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"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 -- 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 = {} function Decode.new(cap, maxBytes) 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 function Decode.setProps(st, lc, lp, pb) 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 function Decode.resetState(st) 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 function Decode.resetDict(st) st.dictStart = st.op st.remLen = 0 end function Decode.rcInit(st, b, ip, iend) 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 local function ensure(st, need) 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 function Decode.copy(st, n, b, ip) 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 =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= EMPTY local inb= EMPTY local range, code, ip, iend, over = 0, 0, 0, 0, 0 local function bit(i) 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 =range- bound code =code- bound writeu16(probs, p, prob - rshift(prob, 5)) r = 1 end if range < TOP then range =range* 256 if ip < iend then code = code * 256 + readu8(inb, ip) else code =code* 256 over =over+ 1 end ip =ip+ 1 end return r end local function tree(base, nbits) local m = 1 for _ = 1, nbits do m = m * 2 + bit(base + m) end return m - 2 ^ nbits end local function reverse(base, nbits) local m = 1 local sym = 0 for i = 0, nbits - 1 do local b = bit(base + m) m = m * 2 + b sym =sym+ b * 2 ^ i end return sym end local function direct(nbits) local res = 0 for _ = 1, nbits do range = rshift(range, 1) local b = 0 if code >= range then code =code- range b = 1 end res = res * 2 + b if range < TOP then range =range* 256 if ip < iend then code = code * 256 + readu8(inb, ip) else code =code* 256 over =over+ 1 end ip =ip+ 1 end end return res end local function length(base, posState) 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 function Decode.run(st, inb0, ip0, iend0, outEnd) 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= nil local msg= 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 =op+ n remLen =remLen- n end end while true do local __DARKLUA_CONTINUE_6=false repeat 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 =range* 256 if ip < iend then code = code * 256 + readu8(inb, ip) else code =code* 256 over =over+ 1 end ip =ip+ 1 end -- literal local prev = (op > dictStart and{(readu8(out, op - 1) )}or{0 })[1] local base = LITERAL + 0x300 * (band(pos, lpMask) * lcMul + math.floor(prev / lcShift)) local sym = 1 if state >= 7 then local mpos = op - rep0 - 1 local matchByte = (mpos >= dictStart and{(readu8(out, mpos) )}or{0 })[1] repeat local matchBit = band(rshift(matchByte, 7), 1) matchByte =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 =range- bd code =code- bd writeu16(probs, p2, pr - rshift(pr, 5)) sym = sym * 2 + 1 end if range < TOP then range =range* 256 if ip < iend then code = code * 256 + readu8(inb, ip) else code =code* 256 over =over+ 1 end ip =ip+ 1 end end writeu8(out, op, sym - 256) op =op+ 1 state = state < 4 and 0 or(state < 10 and((state - 3 ))or((state - 6 ))) else range =range- bound code =code- bound writeu16(probs, pidx, prob - rshift(prob, 5)) if range < TOP then range =range* 256 if ip < iend then code = code * 256 + readu8(inb, ip) else code =code* 256 over =over+ 1 end ip =ip+ 1 end local len if bit(IS_REP + state) == 0 then -- simple match len = length(LEN, posState) state = state < 7 and 7 or 10 rep3, rep2, rep1 = rep2, rep1, rep0 local lenState = (len < 3 and{len }or{3 })[1] local slot = tree(POS_SLOT + lenState * 64, 6) if slot < 4 then rep0 = slot else local nd = math.floor(slot / 2 )- 1 local dist = (2 + slot % 2) * 2 ^ nd if slot < 14 then dist =dist+ reverse(SPEC_POS + dist - slot, nd) else dist =dist+ direct(nd - 4) * 16 dist =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 = state < 7 and 9 or 11 writeu8(out, op, readu8(out, op - rep0 - 1)) op =op+ 1 __DARKLUA_CONTINUE_6=true break 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 = state < 7 and 8 or 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 =op+ n end __DARKLUA_CONTINUE_6=true until true if not __DARKLUA_CONTINUE_6 then break 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 function Decode.finish(st) 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"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 -- 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 } local function msbyte(b) return b == 0 or b == 0xFF end function Filters.x86(b, o, n, start) if n <= 4 then return end local size = n - 4 local prevPos = -1 local prevMask = 0 local i = 0 while i < size do local __DARKLUA_CONTINUE_1=false repeat local c = readu8(b, o + i) if band(c, 0xFE) ~= 0xE8 then i =i+ 1 __DARKLUA_CONTINUE_1=true break 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 =i+ 1 __DARKLUA_CONTINUE_1=true break 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 =i+ 5 else prevMask = bor(lshift(prevMask, 1), 1) i =i+ 1 end __DARKLUA_CONTINUE_1=true until true if not __DARKLUA_CONTINUE_1 then break end end end function Filters.arm(b, o, n, start) 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 =i+ 4 end end function Filters.armthumb(b, o, n, start) 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 =i+ 4 else i =i+ 2 end end end function Filters.powerpc(b, o, n, start) 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 =i+ 4 end end function Filters.sparc(b, o, n, start) 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 =i+ 4 end end function Filters.arm64(b, o, n, start) 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 =i+ 4 end end -- delta filter: b[i] += b[i - dist] (1 <= dist <= 256) function Filters.delta(b, o, n, dist) 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 __FILES["codecs/compress/Lzw"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 -- 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) local function emit(out, o, c, l, lim) 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 =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 =p- 1 end end end function Lzw.decode(src, off, len, out, outOff, maxOut, variant, minCodeSize) 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 =acc+ lshift(readu8(src, p), nb) end p =p+ 1 nb =nb+ 8 end local c if msb then nb =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 =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 =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 =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 =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 =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) function Lzw.encode(data, off, len, variant, minCodeSize) local msb = variant == "tiff" local min = msb and 8 or math.clamp(minCodeSize or 8, 1, 11) local early = msb and 1 or 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 local function put(code) if op + 4 > cap then cap =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 =nb+ size while nb >= 8 do nb =nb- 8 writeu8(out, op, rshift(acc, nb)) op =op+ 1 acc = band(acc, lshift(1, nb) - 1) end else acc =acc+ lshift(code, nb) nb =nb+ size while nb >= 8 do writeu8(out, op, band(acc, 255)) op =op+ 1 acc = rshift(acc, 8) nb =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 =nextc+ 1 if nextc + early > lshift(1, size) and size < 12 then size =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 =nextc+ 1 if nextc + early > lshift(1, size) and size < 12 then size =size+ 1 end end end put(eoi) if nb > 0 then writeu8(out, op, (msb and{(band(lshift(acc, 8 - nb), 255) )}or{(band(acc, 255))})[1]) op =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"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 -- 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 = i < 4 and 0 or math.min(math.floor(i / 2 )- 1, 17) EXTRA[i + 1] = e BASE[i + 1] = b b =b+ lshift(1, e) end end local SLOTS= { [15] = 30, [16] = 32, [17] = 34, [18] = 36, [19] = 38, [20] = 42, [21] = 50 } -- 16-bit little-endian words, read most significant bit first local function refill(s) 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 =s.over+ 8 else s.over =s.over+ 16 end s.bb = bor(s.bb, lshift(w, 16 - s.cnt)) s.cnt =s.cnt+ 16 end end local function bits(s, n) if s.cnt < n then refill(s) end local v = rshift(s.bb, 32 - n) s.bb = lshift(s.bb, n) s.cnt =s.cnt- n return v end local function sym(s, tab, P, S) 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 =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) local function readLens(s, lens, first, last, pre, preLens) 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 = (z == 17 and{(bits(s, 4) + 4 )}or{(bits(s, 5) + 20 )})[1] for _ = 1, run do if x < cap then writeu8(lens, x, 0) end x =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 =x+ 1 end else writeu8(lens, x, (readu8(lens, x) - z + 17) % 17) x =x+ 1 end end return true end -- E8 translation, frame by frame: absolute call targets back to relative local function translate(out, n, size) 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, (abs >= 0 and((abs - i ))or((abs + size)))) end i =i+ 5 else i =i+ 1 end end end base =base+ fs frame =frame+ 1 end end function Lzx.decode(src, offset, length, outSize, windowBits) 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= { src = src, pos = offset, stop = offset + length, bb = 0, cnt = 0, over = 0 } local R0, R1, R2= 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 =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 - math.floor((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 =op+ n bremain =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 =pos+ 2 elseif pos < stop then w = readu8(src, pos) pos =pos+ 1 over =over+ 8 else over =over+ 16 end bb = bor(bb, lshift(w, 16 - cnt)) 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 =cnt- l local m = rshift(e, 5) if m < 256 then writeu8(out, op, m) op =op+ 1 else m =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 =pos+ 2 else over =over+ 16 end bb = bor(bb, lshift(w, 16 - cnt)) 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 =cnt- ll len =len+ rshift(le, 5) end len =len+ 2 local slot = rshift(m, 3) local dist 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 =pos+ 2 else over =over+ 16 end bb = bor(bb, lshift(w, 16 - cnt)) cnt =cnt+ 16 end if aligned and ex >= 3 then if ex > 3 then dist =dist+ lshift(rshift(bb, 35 - ex), 3) bb = lshift(bb, ex - 3) cnt =cnt- (ex - 3 ) while cnt <= 16 do local w = 0 if pos + 2 <= stop then w = readu16(src, pos) pos =pos+ 2 else over =over+ 16 end bb = bor(bb, lshift(w, 16 - cnt)) 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 =cnt- al dist =dist+ rshift(ae, 5) else dist =dist+ rshift(bb, 32 - ex) bb = lshift(bb, ex) cnt =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 =op+ len end end s.bb, s.cnt, s.pos, s.over = bb, cnt, pos, over bremain =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 =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"] = function() local __compat = __compat local buffer = __compat.buffer --!strict --!native --!optimize 2 -- 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 function PackBits.decode(src, p, limit, dst, d, n) 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 =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 =o+ cnt end p =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 =p+ 1 o =o+ cnt end end return o - d, p, clean end function PackBits.encode(src, off, len) local out = buffer.create(len + math.floor((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 =run+ 1 end if run >= 3 then writeu8(out, o, 257 - run) writeu8(out, o + 1, v) o =o+ 2 p =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 =p+ 1 n =n+ 1 end writeu8(out, o, n - 1) buffer.copy(out, o + 1, src, s, n) o =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"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --!native --!optimize 2 -- 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 = i < 4 and 0 or math.floor(i / 2 )- 1 PEXTRA[i + 1] = e PBASE[i + 1] = b 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 =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) local function model(first, n) 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 local function rescale(m) local n, sym, cum = m.n, m.sym, m.cum m.shifts =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]+ cum[i + 1] end end local function bit(c) 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 =c.over+ 1 end c.cnt = 8 end c.cnt =c.cnt- 1 return band(rshift(c.acc, c.cnt), 1) end local function raw(c, n) local v = 0 for _ = 1, n do v = v * 2 + bit(c) end return v end local function symbol(c, m) 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 =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]=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 function Quantum.decode(src, blocks, outSize, windowBits) 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 __iter(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 =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 __iter(blocks) do local frameEnd = op + b.size local c= { 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 =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 =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"] = function() local __compat = __compat local buffer, bit32, type = __compat.buffer, __compat.bit32, __compat.type --!strict --!native --!optimize 2 -- 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 = {} 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) function UnixCompress.decompress(buf, offset, len, opts) 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 = block and 257 or 256 local prev = -1 while pos + nbits <= totalBits do local __DARKLUA_CONTINUE_2=false repeat if freeEnt > maxcode then local g = nbits * 8 pos = gbase + math.floor((pos - gbase + g - 1) / g )* g gbase = pos nbits =nbits+ 1 maxcode = (nbits == maxbits and{maxmax }or{(lshift(1, nbits) - 1 )})[1] mask = lshift(1, nbits) - 1 __DARKLUA_CONTINUE_2=true break 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 =pos+ nbits if c == 256 and block then local g = nbits * 8 pos = gbase + math.floor((pos - gbase + g - 1) / g )* g gbase = pos nbits = 9 mask = 511 maxcode = 511 freeEnt = 257 prev = -1 __DARKLUA_CONTINUE_2=true break 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 = (c == freeEnt and{(readu8(first, prev) )}or{(readu8(first, c) )})[1] 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 =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 =p- 1 end op =op+ l prev = c __DARKLUA_CONTINUE_2=true until true if not __DARKLUA_CONTINUE_2 then break end 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) function UnixCompress.compress(buf, offset, len, opts) 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) local function put(code) acc = bor(acc, lshift(code, nb)) nb =nb+ nbits outbits =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 =nb- 8 end end 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 + math.floor((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) local function checks(consumed) if freeEnt >= extcode then if nbits < maxbits then align() nbits =nbits+ 1 extcode = (nbits < maxbits and{(lshift(1, nbits) + 1 )}or{(lshift(1, nbits) )})[1] 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 = d == 0 and 0x7FFFFFFF or math.floor(consumed / d ) else rat = math.floor((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 =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 =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 function UnixCompress.isCompress(b, o) 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"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 -- 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 local function mul(a, b) local a0 = a % 65536 local a1 = (a - a0) / 65536 return (a0 * b + ((a1 * b) % 65536) * 65536) % T32 end local function rotl(x, r) return bor(lshift(x, r), rshift(x, 32 - r)) end local function round(acc, lane) return mul(rotl((acc + mul(lane, P2)) % T32, 13), P1) end function Xxh32.hash(b, offset, length, seed) 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 =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 =p+ 4 end while p < e do h = mul(rotl((h + readu8(b, p) * P5) % T32, 11), P1) p =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 __FILES["codecs/compress/Zstd"] = function() local __compat = __compat local buffer, bit32, type = __compat.buffer, __compat.bit32, __compat.type --!strict -- 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 = {} -- magic numbers: a zstd frame, and skippable frames (0x184D2A50 .. 0x184D2A5F) Zstd.MAGIC = "\40\181\47\253" function Zstd.isFrame(buf, offset) 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, offset, length, opts) local b, o, l, aerr = Bytes.span("Zstd.decompress", buf, offset, length) if not b then return nil, aerr end local maxBytes = (opts and opts.maxBytes ~= nil and{opts.maxBytes }or{(2 ^ 30 )})[1] 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, offset, length) 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"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 -- 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 =v+ 1 end HB[i] = v end end local function peek(b, s, o, n) 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 =v+ readu8(b, byte + k) * m end m =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 local function streamBits(b, s, e) 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 local function getF(b, p, e, bp, n) local byte = p + rshift(bp, 3) local v = 0 local m = 1 for k = 0, 3 do if byte + k < e then v =v+ readu8(b, byte + k) * m end m =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 local function buildFse(norm, nsym, al, t) 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 =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 =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 local function ncount(b, p, e, maxSym, maxAL, norm) 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 =bp+ 2 if v == 3 then n0 =n0+ 3 if n0 > maxSym or bp > (e - p) * 8 then return nil, "bad FSE table" end else n0 =n0+ v break end end if n0 > maxSym then return nil, "bad FSE table" end while sym < n0 do norm[sym + 1] = 0 sym =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 =bp+ (nbBits - 1 ) else count = getF(b, p, e, bp, nbBits) if count >= threshold then count =count- max end bp =bp+ nbBits end count =count- 1 remaining =remaining- (count < 0 and{(-count )}or{count })[1] if remaining < 1 then return nil, "bad FSE table" end norm[sym + 1] = count sym =sym+ 1 prev0 = count == 0 while remaining < threshold do nbBits =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 local function predefined(dist, al) 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) local function hufTable(b, p, e, st) 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, (band(i, 1) == 0 and{(rshift(byte, 4) )}or{(band(byte, 15))})[1]) 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 =off- al local s2 = peek(b, ss, off, al) off =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 =n+ 1 local k = band(rshift(e1, 8), 255) s1 = rshift(e1, 16) + peek(b, ss, off, k) off =off- k if off < 0 then writeu8(weights, n, band(readu32(wfse, s2 * 4), 255)) n =n+ 1 break end local e2 = readu32(wfse, s2 * 4) writeu8(weights, n, band(e2, 255)) n =n+ 1 k = band(rshift(e2, 8), 255) s2 = rshift(e2, 16) + peek(b, ss, off, k) off =off- k if off < 0 then writeu8(weights, n, band(readu32(wfse, s1 * 4), 255)) n =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 =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 do local __DARKLUA_VAR=bits + 1 rankCount[__DARKLUA_VAR]=rankCount[__DARKLUA_VAR]+ 1 end 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 local function hufStream(b, s, e, t, mb, lit, dp, cnt) 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 =off- rshift(v, 8) end if off ~= 0 then return "Huffman stream size mismatch" end return nil end local function grow(st, need) 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 local function block(b, p, e, st) -- 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 =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 =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 =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 =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 =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 =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 =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 =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 =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 =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 =p+ 2 else if p + 1 > e then return "TRUNCATED", "truncated sequences header" end nbSeq = (nbSeq - 128) * 256 + readu8(b, p) 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 =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 = k == 1 and 35 or(k == 2 and 31 or 52 ) local maxAL = k == 1 and 9 or(k == 2 and 8 or 9 ) if mode == 0 then tabs[k] = (k == 1 and{LL_PRE }or{(k == 2 and{OF_PRE }or{ML_PRE })[1]})[1] tabs[k + 3] = k == 2 and 5 or 6 elseif mode == 1 then if p >= e then return "TRUNCATED", "truncated RLE table" end local sym = readu8(b, p) 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 =p+ used local t = st.dyn[k] local ok, msg = buildFse(norm, nsym , 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] , tabs[2] , tabs[3] local llAL, ofAL, mlAL = tabs[4] , tabs[5] , tabs[6] -- 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 =off- llAL local ofS = peek(b, s, off, ofAL) off =off- ofAL local mlS = peek(b, s, off, mlAL) off =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 =off- hiN ofv = lshift(1, ofCode) + hi * 16777216 + peek(b, s, off, 24) off =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 =ml+ peek(b, s, off, nb) off =off- nb end local ll = LL_BASE[llCode] nb = LL_BITS[llCode] if nb > 0 then ll =ll+ peek(b, s, off, nb) off =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 =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 =off- nb nb = band(rshift(mlE, 8), 255) mlS = rshift(mlE, 16) + peek(b, s, off, nb) off =off- nb nb = band(rshift(ofE, 8), 255) ofS = rshift(ofE, 16) + peek(b, s, off, nb) off =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 =op+ ll lp =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 =op+ ml elseif offset == 1 then bfill(out, op, readu8(out, from), ml) op =op+ ml else local left = ml while left > 0 do local n = (left < offset and{left }or{offset })[1] bcopy(out, op, out, from, n) op =op+ n from =from+ n left =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 =op+ rest end st.op = op st.rep1, st.rep2, st.rep3 = rep1, rep2, rep3 return nil, nil end function Decode.decompress(b, start, stop, maxBytes, verify) local st= { 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 local __DARKLUA_CONTINUE_25=false repeat 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 =pos+ (8 + size ) frames =frames+ 1 __DARKLUA_CONTINUE_25=true break end if magic ~= MAGIC then return nil, "CORRUPT", frames == 0 and"bad magic" or"unknown data after frame " .. frames, pos end pos =pos+ 4 if pos + 1 > stop then return nil, "TRUNCATED", "truncated frame header", pos end local fhd = readu8(b, pos) 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 = didFlag == 3 and 4 or didFlag local fcsSize = (fcsFlag == 0 and{(single and 1 or 0) }or{(lshift(1, fcsFlag) )})[1] local hsize = (single and 0 or 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 =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 =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 =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 =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 =st.op+ bsize pos =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 =st.op+ bsize pos =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 =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 =pos+ 4 end frames =frames+ 1 __DARKLUA_CONTINUE_25=true until true if not __DARKLUA_CONTINUE_25 then break end end return st.out, st.op, pos end Decode.hash = Xxh64.hash return Decode end __FILES["codecs/compress/Zstd/Xxh64"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 -- 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 local function mul(ah, al, bh, bl) 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 =hi+ ((a0 * bh + ((a1 * bh) % 65536) * 65536) + (b0 * ah + ((b1 * ah) % 65536) * 65536) ) return hi % T32, lo32 end local function add(ah, al, bh, bl) local l = al + bl local h = ah + bh if l >= T32 then l =l- T32 h =h+ 1 end return h % T32, l end local function rotl(h, l, r) return bor(lshift(h, r), rshift(l, 32 - r)), bor(lshift(l, r), rshift(h, 32 - r)) end local P1L0, P1L1 = P1L % 65536, math.floor(P1L / 65536 )local P2L0, P2L1 = P2L % 65536, math.floor(P2L / 65536 ) -- round: acc = rotl(acc + input * P2, 31) * P1 local function round(ah, al, ih, il) 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 =l- T32 h =h+ 1 end h =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 local function merge(hh, hl, vh, vl) 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 = {} function Xxh64.hash(b, offset, length) 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 =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) ) hh, hl = rotl(hh, hl, 27) hh, hl = mul(hh, hl, P1H, P1L) hh, hl = add(hh, hl, P4H, P4L) p =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) ) hh, hl = rotl(hh, hl, 23) hh, hl = mul(hh, hl, P2H, P2L) hh, hl = add(hh, hl, P3H, P3L) p =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) ) hh, hl = rotl(hh, hl, 11) hh, hl = mul(hh, hl, P1H, P1L) p =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))) ) hh, hl = mul(hh, hl, P3H, P3L) hl = bxor(hl, hh) -- h ^= h >> 32 return hh, hl end return Xxh64 end __FILES["codecs/entropy/Huffman"] = function() local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict --!native -- 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 = math.floor(v / 2 ) end REV[i + 1] = r end local function reverse(code, len) return rshift(bor(lshift(REV[band(code, 255) + 1], 8), REV[band(rshift(code, 8), 255) + 1]), 16 - len) end Huffman.reverse = reverse function Huffman.capacity(nsym, P, maxLen) return 2 ^ P + ((maxLen > P and((nsym * 2 ^ (maxLen - P) ))or(0))) end local count = table.create(MAXLEN + 1, 0) local nextc = table.create(MAXLEN + 1, 0) local function build(lens, off, n, tab, P, msb) 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 do local __DARKLUA_VAR=l + 1 count[__DARKLUA_VAR]=count[__DARKLUA_VAR]+ 1 end 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 = (maxLen > P and((maxLen - P ))or(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 =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 =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 =i+ step end end end end end return S end function Huffman.buildLsb(lens, off, n, tab, P) return build(lens, off, n, tab, P, false) end function Huffman.buildMsb(lens, off, n, tab, P) return build(lens, off, n, tab, P, true) end function Huffman.decodeLsb(br, tab, P, S) 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 function Huffman.decodeMsb(br, tab, P, S) 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 function Huffman.codes(lengths) local cnt = table.create(MAXLEN + 1, 0) for _, l in __iter(lengths) do if l > 0 then do local __DARKLUA_VAR=l + 1 cnt[__DARKLUA_VAR]=cnt[__DARKLUA_VAR]+ 1 end 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 __iter(lengths) do if l > 0 then out[i] = nxt[l + 1] do local __DARKLUA_VAR=l + 1 nxt[__DARKLUA_VAR]=nxt[__DARKLUA_VAR]+ 1 end end end return out end function Huffman.lengths(freqs, maxLen) 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, function(a, b) 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 local function take() if li <= m and (ni >= nn or weight[li] <= weight[ni]) then li =li+ 1 return li - 1 end ni =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 =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 do local __DARKLUA_VAR=depth[i] bl[__DARKLUA_VAR]=bl[__DARKLUA_VAR]+ 1 end 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 =j- 1 end bl[l]=bl[l]- 2 do local __DARKLUA_VAR=l - 1 bl[__DARKLUA_VAR]=bl[__DARKLUA_VAR]+ 1 end do local __DARKLUA_VAR0=j + 1 bl[__DARKLUA_VAR0]=bl[__DARKLUA_VAR0]+ 2 end bl[j]=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 =k+ 1 end end return out end return Huffman end __FILES["codecs/entropy/RangeCoder"] = function() --!strict -- 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"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 -- 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 = {} 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 local function ilog(x) return 32 - countlz(x) end RangeDecoder.ilog = ilog local function normalize(d) local rng, val, rem = d.rng, d.val, d.rem while rng <= CODE_BOT do d.nbits_total =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 function RangeDecoder.new(buf, base, storage) local d= { buf = buf, base = base, storage = storage, offs = 0, end_offs = 0, end_window = 0, nend_bits = 0, nbits_total = CODE_BITS + 1 - (math.floor((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 function RangeDecoder.decode(d, ft) local ext = math.floor(d.rng / ft ) d.ext = ext local s = math.floor(d.val / ext ) return ft - math.min(s + 1, ft) end function RangeDecoder.decodeBin(d, bits) local ext = rshift(d.rng, bits) d.ext = ext local s = math.floor(d.val / ext ) local ft = lshift(1, bits) return ft - math.min(s + 1, ft) end function RangeDecoder.update(d, fl, fh, ft) 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 =d.rng- s end normalize(d) end function RangeDecoder.bitLogp(d, logp) 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 function RangeDecoder.icdf(d, icdf, off, ftb) local s = d.rng local v = d.val local r = rshift(s, ftb) local ret = -1 local t repeat t = s ret =ret+ 1 s = r * icdf[off + ret] until v >= s d.val = v - s d.rng = t - s normalize(d) return ret end function RangeDecoder.bits(d, bits) 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 =eo+ 1 d.end_offs = eo b = readu8(d.buf, d.base + d.storage - eo) end window = bor(window, lshift(b, available)) 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 =available- bits d.end_window = window d.nend_bits = available d.nbits_total =d.nbits_total+ bits return ret end function RangeDecoder.uint(d, ft0) local ft = ft0 - 1 local ftb = ilog(ft) if ftb > UINT_BITS then ftb =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 function RangeDecoder.tell(d) return d.nbits_total - ilog(d.rng) end local correction = { 35733, 38967, 42495, 46340, 50535, 55109, 60097, 65535 } function RangeDecoder.tellFrac(d) 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 =b+ 1 end return nbits - (l * 8 + b) end return RangeDecoder end __FILES["codecs/entropy/RangeCoder/Encoder"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 -- 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 = {} 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 local function ilog(x) return 32 - countlz(x) end RangeEncoder.ilog = ilog function RangeEncoder.new(storage) 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 local function writeByte(e, v) if e.offs + e.end_offs >= e.storage then e.error = -1 return end writeu8(e.buf, e.offs, band(v, 255)) e.offs =e.offs+ 1 end local function writeByteAtEnd(e, v) if e.offs + e.end_offs >= e.storage then e.error = -1 return end e.end_offs =e.end_offs+ 1 writeu8(e.buf, e.storage - e.end_offs, band(v, 255)) end local function carryOut(e, c) if c ~= SYM_MAX then local carry = c >= 256 and 1 or 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 =e.ext- 1 until e.ext <= 0 end e.rem = band(c, 255) else e.ext =e.ext+ 1 end end local function normalize(e) while e.rng <= CODE_BOT do carryOut(e, floor(e.val / 8388608)) e.val = (e.val * 256) % CODE_TOP e.rng =e.rng* 256 e.nbits_total =e.nbits_total+ 8 end end function RangeEncoder.encode(e, fl, fh, ft) local r = floor(e.rng / ft) if fl > 0 then e.val =e.val+ (e.rng - r * (ft - fl) ) e.rng = r * (fh - fl) else e.rng =e.rng- r * (ft - fh) end normalize(e) end function RangeEncoder.encodeBin(e, fl, fh, bits) local ft = 2 ^ bits local r = floor(e.rng / ft) if fl > 0 then e.val =e.val+ (e.rng - r * (ft - fl) ) e.rng = r * (fh - fl) else e.rng =e.rng- r * (ft - fh) end normalize(e) end function RangeEncoder.bitLogp(e, v, logp) local r = e.rng local s = floor(r / 2 ^ logp) r =r- s if v then e.val =e.val+ r e.rng = s else e.rng = r end normalize(e) end function RangeEncoder.icdf(e, s, icdf, ftb) local r = floor(e.rng / 2 ^ ftb) if s > 0 then e.val =e.val+ (e.rng - r * icdf[s] ) e.rng = r * (icdf[s] - icdf[s + 1]) else e.rng =e.rng- r * icdf[s + 1] end normalize(e) end function RangeEncoder.bits(e, fl, n) 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 =used- 8 until used < 8 end window =window+ fl * 2 ^ used used =used+ n e.end_window = window e.nend_bits = used e.nbits_total =e.nbits_total+ n end function RangeEncoder.uint(e, fl, ft) ft =ft- 1 local ftb = ilog(ft) if ftb > 8 then ftb =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 function RangeEncoder.tell(e) return e.nbits_total - ilog(e.rng) end local CORRECTION = { 35733, 38967, 42495, 46340, 50535, 55109, 60097, 65535 } function RangeEncoder.tellFrac(e) 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 =b+ 1 end return nbits - (l * 8 + b) end function RangeEncoder.done(e) 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 =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 =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 =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 __FILES["codecs/font/Bitmap"] = function() local __compat = __compat local buffer, bit32, utf8, type, __iter = __compat.buffer, __compat.bit32, __compat.utf8, __compat.type, __compat.__iter --!strict -- 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, off, w, h, stride, lsbFirst) 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 = (lsbFirst and{(bit32.band(x, 7) )}or{(7 - bit32.band(x, 7) )})[1] 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, w, h, stride, lsbFirst) 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 = (lsbFirst and{(bit32.band(x, 7) )}or{(7 - bit32.band(x, 7) )})[1] 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, cp) return self._index[cp] or 0 end function Face.advance(self, g) local gl = self.bitmap.glyphs[g + 1] return (gl and{gl.advance }or{0 })[1]end function Face.kern(_self, _a, _b) return 0 end function Face.outline(_self, _g) return nil end function Face.rasterize(self, g, px) local gl= 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 = (type(px) == "number" and self.bitmap.size > 0 and((px / self.bitmap.size ))or(1 )) return img end function Bitmap.font(strike, info, meta) local index= {} for i, gl in __iter(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 __iter(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 local function codepoints(chars) if type(chars) == "table" then return chars end local out = {} if type(chars) == "string" then for _, c in __iter(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, opts) 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= 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 = (type(font.unitsPerEm) == "number" and font.unitsPerEm > 0 and{font.unitsPerEm }or{px })[1] 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= {} local function add(cp, g) 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= { 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 __iter(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() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict -- 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, o) if o < 0 or o + 1 > blen(b) then return 0 end return readu8(b, o) end local function uN(b, o, n) local v = 0 for i = 0, n - 1 do v = v * 256 + u8(b, o + i) end return v end local function index(b, p, limit) 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, idx, i) 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, p, n) local out= {} local ops= {} local e = p + n while p < e do local b0 = u8(b, p) if b0 <= 21 then local op = b0 p =p+ 1 if b0 == 12 then op = 1200 + u8(b, p) p =p+ 1 end out[op] = ops ops = {} elseif b0 == 28 then local v = uN(b, p + 1, 2) table.insert(ops, (v >= 32768 and((v - 65536 ))or(v))) p =p+ 3 elseif b0 == 29 then local v = uN(b, p + 1, 4) table.insert(ops, (v >= 2147483648 and((v - 4294967296 ))or(v))) p =p+ 5 elseif b0 == 30 then -- real number: BCD nibbles local s = {} p =p+ 1 local done = false while p < e and not done do local byte = u8(b, p) p =p+ 1 for _, nib in __iter({ math.floor(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 =p+ 1 elseif b0 >= 247 and b0 <= 250 then table.insert(ops, (b0 - 247) * 256 + u8(b, p + 1) + 108) p =p+ 2 elseif b0 >= 251 and b0 <= 254 then table.insert(ops, -(b0 - 251) * 256 - u8(b, p + 1) - 108) p =p+ 2 else p =p+ 1 -- reserved end if #ops > 48 then return out end end return out end local function privateSubrs(b, base, limit, d) 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, offset, length) 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= { 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= {} for i = 0, math.min(fdArray.count, 256) - 1 do local s, l = item(b, fdArray, i) list[i + 1] = (s and{(privateSubrs(b, base, limit, dict(b, s, l)) )}or{nil })[1] 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) return count < 1240 and 107 or(count < 33900 and 1131 or 32768 )end local function localSubrs(f, g) if not f.cid then return f.subrs end local b, p = f.buf, f.fdSelect 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 return list[fd + 1] end local BUDGET = 200000 -- operators per glyph (subroutine bombs) function Cff.outline(f, g) 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= {} local s= table.create(48, 0) local sp = 0 local trans = (table.create(32, 0) ) local x, y = 0, 0 local open = false local maskbits = 0 local inHeader = true local stack= {} local subrs= nil local haveSubrs = false local ops = 0 local seed = 12345 local function moveTo(dx, dy) if open then table.insert(cmds, { op = "close" }) end x =x+ dx y =y+ dy table.insert(cmds, { op = "moveTo", x, y }) open = true end local function lineTo(dx, dy) if not open then moveTo(0, 0) end x =x+ dx y =y+ dy table.insert(cmds, { op = "lineTo", x, y }) end local function curveTo(dx1, dy1, dx2, dy2, dx3, dy3) 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) return s[i + 1] or 0 end while true do local __DARKLUA_CONTINUE_7=false repeat if p >= e then if #stack > 0 then local r = (table.remove(stack) ) p, e = r[1], r[2] __DARKLUA_CONTINUE_7=true break end break end ops =ops+ 1 if ops > BUDGET then return nil, "charstring too long (subroutine loop?)" end local b0 = u8(b, p) p =p+ 1 local clear = true local i = 0 if b0 == 19 or b0 == 20 then -- hintmask, cntrmask if inHeader then maskbits =maskbits+ math.floor(sp / 2 ) end inHeader = false p =p+ math.floor((maskbits + 7) / 8 ) elseif b0 == 1 or b0 == 3 or b0 == 18 or b0 == 23 then -- hstem vstem hstemhm vstemhm maskbits =maskbits+ math.floor(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 =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 =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 = (sp - i == 5 and{(S(i + 4) )}or{0 })[1] 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 =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 =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 =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 =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 =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 = (b0 == 10 and{subrs }or{f.gsubrs })[1] if not idx then return nil, "no subroutines" end local n = math.floor(S(sp - 1)) + bias(idx.count) sp =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) ) 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 =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, v) sp = math.max(0, sp - n) sp =sp+ 1 s[sp] = v end if b1 == 3 then set(2, a ~= 0 and c ~= 0 and 1 or 0) -- and elseif b1 == 4 then set(2, (a ~= 0 or c ~= 0 )and 1 or 0) -- or elseif b1 == 5 then set(1, c == 0 and 1 or 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, (c ~= 0 and((a / c ))or(0))) elseif b1 == 14 then set(1, -c) elseif b1 == 15 then set(2, a == c and 1 or 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, (k >= 0 and k < 32 and{trans[k + 1] }or{0})[1]) 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, (v1 <= v2 and{s1 }or{s2})[1]) 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 = (k < 0 and{(S(top - 2) )}or{(S(top - 2 - k) )})[1] 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 =v- 65536 end p =p+ 2 elseif b0 <= 246 then v = b0 - 139 elseif b0 <= 250 then v = (b0 - 247) * 256 + u8(b, p) + 108 p =p+ 1 elseif b0 <= 254 then v = -(b0 - 251) * 256 - u8(b, p) - 108 p =p+ 1 else -- 255: 16.16 fixed v = uN(b, p, 4) if v >= 2147483648 then v =v- 4294967296 end v =v/ 65536 p =p+ 4 end if sp >= 48 then return nil, "operand stack overflow" end sp =sp+ 1 s[sp] = v clear = false else return nil, "reserved operator " .. b0 end if clear then sp = 0 end __DARKLUA_CONTINUE_7=true until true if not __DARKLUA_CONTINUE_7 then break end end return nil, "no endchar" end return Cff end __FILES["codecs/font/GlyphNames"] = function() local __compat = __compat local __iter = __compat.__iter --!strict -- 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= nil local function load() local t= {} for name, hex in __iter(string.gmatch(AGL, "(%S+) (%x+)")) do t[name] = (tonumber(hex, 16) ) end byName = t return t end local STANDARD= {} do local i = 0 for name in __iter(string.gmatch(STD, "%S+")) do if name ~= "-" then STANDARD[i] = name end i =i+ 1 end end GlyphNames.STANDARD = STANDARD function GlyphNames.unicode(name) 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) ) return (c >= 0xD800 and c < 0xE000 and{nil }or{c })[1] end hex = string.match(base, "^u(%x%x%x%x%x?%x?)$") if hex then local c = (tonumber(hex, 16) ) return ((c > 0x10FFFF or (c >= 0xD800 and c < 0xE000) )and{nil }or{c })[1] 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() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict -- 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, o) if o < 0 or o + 4 > buffer.len(b) then return "" end return buffer.readstring(b, o, 4) end function TrueType.count(b, offset) 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, file, dir, limit) local n = u16(b, dir + 4) if dir + 12 + n * 16 > limit then return nil, "table directory past the end" end local out= {} 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, cp) return Tables.glyph(self._cmap, cp) end function Face.advance(self, g) 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, g) 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, a, b) 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, a, b) return self:kern(self:glyphIndex(a), self:glyphIndex(b)) end function Face.outline(self, g) 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, g) 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 __iter(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, px) return px / self.unitsPerEm end -- meta.top counts up from the baseline, as FreeType's bitmap_top function Face.rasterize(self, g, px, opts) 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= opts or {} local sx = (type(o.scaleX) == "number" and{o.scaleX }or{(px / self.unitsPerEm )})[1] local sy = (type(o.scaleY) == "number" and{o.scaleY }or{sx })[1] 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 function TrueType.font(buf, offset, length, opts) 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 __iter({ "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 = math.floor(t.hmtx[2] / 4 ) end local font= 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 = (cerr and string.find(cerr, "unsupported", 1, true) and{Err.UNSUPPORTED }or{Err.CORRUPT })[1] 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 __iter(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 __iter(t) do table.insert(tags, k) end table.sort(tags) font.meta.tables = tags font.meta.sfnt = sfntTag == "OTTO" and"OTTO" or"TrueType" font.meta.collection = (count > 1 or tag(b, file) == "ttcf" )and{ index = index, count = count } or nil return font, nil end return TrueType end __FILES["codecs/font/TrueType/Glyf"] = function() local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict -- 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, o) if o < 0 or o + 1 > blen(b) then return 0 end return readu8(b, o) end local function u16(b, o) 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, o) local v = u16(b, o) return (v >= 32768 and((v - 65536 ))or(v ))end local function u32(b, o) return u16(b, o) * 65536 + u16(b, o + 2) end function Glyf.range(f, g) 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) ) 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, g) 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 local MAX_POINTS = 65536 local function simple(b, o, len, nc) local e = o + len local ends = (table.create(nc) ) 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 =p+ 2 end local n = last + 1 if n > MAX_POINTS then return nil, "too many points" end local ins = u16(b, p) 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 =p+ 1 flags[i] = fl i =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 =p+ 1 for _ = 1, rep do if i > n then break end flags[i] = fl i =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 =p+ 1 x =x+ (band(fl, 16) ~= 0 and{d }or{(-d )})[1] elseif band(fl, 16) == 0 then if p + 2 > e then return nil, "x coordinates past the end" end x =x+ i16(b, p) 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 =p+ 1 y =y+ (band(fl, 32) ~= 0 and{d }or{(-d )})[1] elseif band(fl, 32) == 0 then if p + 2 > e then return nil, "y coordinates past the end" end y =y+ i16(b, p) p =p+ 2 end ys[k] = y end local out = (table.create(nc) ) 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 local function composite(f, o, len, depth) local b = f.buf local e = o + len local p = o + 10 local out= {} 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 =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) ) else a1, a2 = u16(b, p), (u16(b, p + 2) ) end p =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) ) else a1, a2 = readu8(b, p), (readu8(b, p + 1) ) end p =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 =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 =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 =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) ) for i, c in __iter(child) do local nx, ny = (table.create(#c.x) ), (table.create(#c.x) ) 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, idx) local k = idx for _, c in __iter(list) do local n = #c.x if k < n then return c.x[k + 1], c.y[k + 1] end k =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 ) end for _, c in __iter(tc) do for k = 1, #c.x do do local __DARKLUA_VAR= c.x __DARKLUA_VAR[k]=__DARKLUA_VAR[k]+ dx end do local __DARKLUA_VAR0= c.y __DARKLUA_VAR0[k]=__DARKLUA_VAR0[k]+ dy end end total =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, g, depth) 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, g) local cs, err = contours(f, g, 0) if not cs then return nil, err end local cmds = {} for _, c in __iter(cs) do local __DARKLUA_CONTINUE_14=false repeat local n = #c.x if n < 2 then __DARKLUA_CONTINUE_14=true break 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" }) __DARKLUA_CONTINUE_14=true break 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" }) __DARKLUA_CONTINUE_14=true until true if not __DARKLUA_CONTINUE_14 then break end end return cmds, nil end function Glyf.counts(f, g) local cs = contours(f, g, 0) if not cs then return 0, 0 end local n = 0 for _, c in __iter(cs) do n =n+ #c.x end return n, #cs end return Glyf end __FILES["codecs/font/TrueType/Tables"] = function() local __compat = __compat local buffer, bit32, utf8, type, __iter = __compat.buffer, __compat.bit32, __compat.utf8, __compat.type, __compat.__iter --!strict -- 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, o) if o < 0 or o + 1 > blen(b) then return 0 end return readu8(b, o) end local function u16(b, o) 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, o) local v = u16(b, o) return (v >= 32768 and((v - 65536 ))or(v ))end local function u32(b, o) return u16(b, o) * 65536 + u16(b, o + 2) end Tables.u8, Tables.u16, Tables.i16, Tables.u32 = u8, u16, i16, u32 -- cmap subtable preference: Unicode full repertoire, then BMP, then symbol, then Mac function Tables.cmap(b, o, n) local count = u16(b, o + 2) local best, bestRank, symbol = -1, 0, false for i = 0, count - 1 do local __DARKLUA_CONTINUE_1=false repeat 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 __DARKLUA_CONTINUE_1=true break 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 __DARKLUA_CONTINUE_1=true until true if not __DARKLUA_CONTINUE_1 then break 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, cp) local b, t, fmt = c.buf, c.at, c.format if fmt == 0 then return (cp < 256 and{(u8(b, t + 6 + cp) )}or{0 })[1] 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 = math.floor(segX2 / 2 ) local ends = t + 14 local lo, hi = 0, segs - 1 while lo < hi do local mid = math.floor((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 = math.floor((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 (fmt == 12 and((gid + cp - s ))or(gid )) end end return 0 end return 0 end function Tables.glyph(c, cp) 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, o, n) local pairs= {} local e = o + n local apple = u32(b, o) == 0x00010000 local count = (apple and{(u32(b, o + 4) )}or{(u16(b, o + 2) )})[1] local p = (apple and((o + 8 ))or((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 = math.floor(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 =p+ len end return pairs end local function popcount(v) local c = 0 while v ~= 0 do c =c+ band(v, 1) v = bit32.rshift(v, 1) end return c end local function coverage(b, t, g) 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 = math.floor((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 = math.floor((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, t, g) 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 = math.floor((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, r, vf) if band(vf, 4) == 0 then return 0 end return i16(b, r + 2 * popcount(band(vf, 3))) end local function pairPos(b, t, l, r) 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 = math.floor((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 function Tables.gpos(b, o, n) 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= {} 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= {} 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= {} 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 =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, l, r) local total = 0 for _, subs in __iter(g.subtables) do for _, st in __iter(subs) do local applies, v = pairPos(g.buf, st, l, r) if applies then total =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, o, n) return Text.utf16(b, o, n, true) end local function macRoman(b, o, n) local out = {} for k = 0, n - 1 do local c = u8(b, o + k) table.insert(out, utf8.char((c < 128 and{c }or{MAC_ROMAN_HIGH[c - 127]})[1])) end return table.concat(out) end local NAME_IDS= { [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, o, n) local out= {} local rank= {} 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, s= 0, nil if pid == 3 and (eid == 1 or eid == 10 or eid == 0) then rk = lang == 0x409 and 4 or 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 = lang == 0 and 1 or 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, o, n) local t= { 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 __FILES["codecs/image/Bcn"] = function() local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict --!native --!optimize 2 -- 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 }) ) Bcn.FLOAT = (table.freeze({ bc6h = true, bc6hs = true }) ) local readu32, writeu32 = buffer.readu32, buffer.writeu32 local BLOCKS= { 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 = function(src, p, blk) Decode.bc6h(src, p, blk, false) end, bc6hs = function(src, p, blk) Decode.bc6h(src, p, blk, true) end, } function Bcn.size(kind, w, h) local b = Bcn.BLOCK[kind] if not b then return nil end return (math.floor((w + 3) / 4)) * (math.floor((h + 3) / 4)) * b end function Bcn.decode(kind, src, offset, w, h, out, outOffset) 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) ) 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 = float and 16 or 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 = math.floor((w + 3) / 4), math.floor((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 =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 function Bcn.encode(kind, px, w, h, opts) 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"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 -- 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) local function c565(c) 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 local function colour(src, p, blk, fourColour) 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, math.floor((2 * r0 + r1) / 3 )+ (math.floor((2 * g0 + g1) / 3)) * 256 + (math.floor((2 * b0 + b1) / 3)) * 65536 + 0xFF000000) writeu32(pal, 12, math.floor((r0 + 2 * r1) / 3 )+ (math.floor((g0 + 2 * g1) / 3)) * 256 + (math.floor((b0 + 2 * b1) / 3)) * 65536 + 0xFF000000) else writeu32(pal, 8, math.floor((r0 + r1) / 2 )+ (math.floor((g0 + g1) / 2)) * 256 + (math.floor((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) local function ramp8(a0, a1) vals[1], vals[2] = a0, a1 if a0 > a1 then for i = 1, 6 do vals[i + 2] = math.floor(((7 - i) * a0 + i * a1) / 7 ) end else for i = 1, 4 do vals[i + 2] = math.floor(((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 local function ramp8s(u0, u1) local s0= math.max((u0 >= 128 and((u0 - 256 ))or(u0)), -127) local s1= math.max((u1 >= 128 and((u1 - 256 ))or(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 local function single(src, p, blk, channel, signed, spread) 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 = (i < 8 and{(band(rshift(lo, i * 3), 7) )}or{(band(rshift(hi, (i - 8) * 3), 7) )})[1] 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 function Decode.bc1(src, p, blk) colour(src, p, blk, false) end function Decode.bc2(src, p, blk) 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 function Decode.bc3(src, p, blk) colour(src, p + 8, blk, true) single(src, p, blk, 3, false, false) end function Decode.bc4(src, p, blk) single(src, p, blk, 0, false, true) end function Decode.bc4s(src, p, blk) single(src, p, blk, 0, true, true) end local function bc5(src, p, blk, signed) 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 function Decode.bc5(src, p, blk) bc5(src, p, blk, false) end function Decode.bc5s(src, p, blk) 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 local function subset(ns, part, i) 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 local function load(src, p) w0, w1, w2, w3 = readu32(src, p), readu32(src, p + 4), readu32(src, p + 8), readu32(src, p + 12) end local function word(i) return (i == 0 and{w0 }or{(i == 1 and{w1 }or{(i == 2 and{w2 }or{w3 })[1]})[1]})[1]end local function bits(at, n) 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) local function expand(v, n) v = band(lshift(v, 8 - n), 255) return bor(v, rshift(v, n)) end function Decode.bc7(src, p, blk) 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 =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 =bit+ pb local rot = bits(bit, rb) bit =bit+ rb local sel = bits(bit, isb) bit =bit+ isb local nep = ns * 2 for i = 1, nep do er[i] = bits(bit, cb) bit =bit+ cb end for i = 1, nep do eg[i] = bits(bit, cb) bit =bit+ cb end for i = 1, nep do eb[i] = bits(bit, cb) bit =bit+ cb end for i = 1, nep do if ab > 0 then ea[i] = bits(bit, ab) bit =bit+ ab else ea[i] = 255 end end if epb == 1 then cb =cb+ 1 if ab > 0 then ab =ab+ 1 end for i = 1, nep do local v = bits(bit, 1) bit =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 =cb+ 1 if ab > 0 then ab =ab+ 1 end for i = 1, nep, 2 do local v = bits(bit, 1) bit =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 = (ab > 0 and ib2 > 0 and{WEIGHTS[ib2] }or{cw })[1] local cbit = bit local abit = cbit + 16 * ib - ns local a1 = (ns == 2 and{AI0[part + 1] }or{(ns == 3 and{AI1[part + 1] }or{(-1 )})[1]})[1] local a2 = (ns == 3 and{AI2[part + 1] }or{(-1 )})[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 =n- 1 end local i0 = bits(cbit, n) cbit =cbit+ n local wc, wa if ab > 0 and ib2 > 0 then local n2 = (i == 0 and((ib2 - 1 ))or(ib2 )) local i1 = bits(abit, n2) abit =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) local function signExtend(v, n) v = band(v, lshift(1, n) - 1) return (v >= lshift(1, n - 1) and{(v - lshift(1, n) )}or{v })[1]end local function unquantize(x, n, signed) 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 (neg and{(-x )}or{x })[1]end local function finish(v, signed) if signed then if v < 0 then return -HALF[math.floor((-v * 31) / 32)] end return HALF[math.floor((v * 31) / 32)] end return HALF[math.floor((v * 31) / 64)] end function Decode.bc6h(src, p, blk, signed) 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 = ns == 2 and 12 or 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 =bit+ epbits local part = bits(bit, pb) bit =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] = (signed and{(signExtend(v, epb) )}or{v })[1] end end end for i = 1, nep do uq[i] = unquantize(ep[i], epb, signed) end local w = WEIGHTS[ib] local a1 = (ns == 2 and{AI0[part + 1] }or{(-1 )})[1] for i = 0, 15 do local s = subset(ns, part, i) * 6 + 1 local n = ((i == 0 or i == a1 )and((ib - 1 ))or(ib )) local wt = w[bits(bit, n)] bit =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(math.floor((uq[s] * t + uq[s + 3] * wt + 32) / 64), signed)) writef32(blk, o + 4, finish(math.floor((uq[s + 1] * t + uq[s + 4] * wt + 32) / 64), signed)) writef32(blk, o + 8, finish(math.floor((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"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 -- 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 local function exp5(v) return bor(lshift(v, 3), rshift(v, 2)) end local function exp6(v) 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= nil local function singleTables() local om = OM if om then return om end local t= {} for k = 1, 4 do local bitsN = k <= 2 and 5 or 6 local maxq = lshift(1, bitsN) - 1 local exp= (bitsN == 5 and{exp5 }or{exp6 })[1] 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= (k % 2 == 1 and{(math.floor((2 * ea + eb) / 3 ))}or{(math.floor((ea + eb) / 2 ))})[1] -- 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) local function palette(c0, c1, four) 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] = math.floor((2 * r0 + r1) / 3), math.floor((2 * g0 + g1) / 3), math.floor((2 * b0 + b1) / 3 ) PR[4], PG[4], PB[4] = math.floor((r0 + 2 * r1) / 3), math.floor((g0 + 2 * g1) / 3), math.floor((b0 + 2 * b1) / 3 ) else PR[3], PG[3], PB[3] = math.floor((r0 + r1) / 2), math.floor((g0 + g1) / 2), math.floor((b0 + b1) / 2 ) PR[4], PG[4], PB[4] = 0, 0, 0 end end local function assign(four) local n = four and 4 or 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 =total+ be else IDX[i] = 3 end end return total end local function q565(r, g, b) 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 } local function refine(four) local W = (four and{W4 }or{W3 })[1] 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 =aa+ w * w bb =bb+ v * v ab =ab+ w * v ar =ar+ w * R[i] ag =ag+ w * G[i] ab_ =ab_+ w * B[i] br =br+ v * R[i] bg =bg+ v * G[i] bb_ =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 local function colourBlock(out, o, four) local n, mr, mg, mb = 0, 0, 0, 0 for i = 1, 16 do if USE[i] then n =n+ 1 mr =mr+ R[i] mg =mg+ G[i] mb =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 =crr+ dr * dr cgg =cgg+ dg * dg cbb =cbb+ db * db crg =crg+ dr * dg crb =crb+ dr * db cgb =cgb+ dg * db end end local c0, c1 if same then local t = singleTables() local k = four and 0 or 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] = (USE[i] and{i2 }or{3 })[1] 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] = v == 0 and 1 or(v == 1 and 0 or(v == 2 and 3 or 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] = v == 0 and 1 or(v == 1 and 0 or 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) local function ramp(a0, a1) RAMP[1], RAMP[2] = a0, a1 if a0 > a1 then for i = 1, 6 do RAMP[i + 2] = math.floor(((7 - i) * a0 + i * a1) / 7 ) end else for i = 1, 4 do RAMP[i + 2] = math.floor(((5 - i) * a0 + i * a1) / 5 ) end RAMP[7], RAMP[8] = 0, 255 end end local function pick() 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 =total+ be end return total end local function channelBlock(out, o) 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 local function gather(px, w, h, bx, by) 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 function Encode.run(kind, px, w, h, threshold) local bw, bh = math.floor((w + 3) / 4), math.floor((h + 3) / 4 ) local bytes = (kind == "bc1" or kind == "bc4" )and 8 or 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 =o+ bytes end end return out end return Encode end __FILES["codecs/image/Blend"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --!native -- 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= { 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= {} for k in __iter(IDS) do MODES[k] = true end Blend.MODES = table.freeze(MODES) local function burn(cb, cs) if cb >= 1 then return 1 elseif cs <= 0 then return 0 end return 1 - min(1, (1 - cb) / cs) end local function dodge(cb, cs) 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 local function sep(m, cb, cs) 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 = (cb <= 0.25 and((((16 * cb - 12) * cb + 4) * cb ))or((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 cb + cs >= 1 and 1 or 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 cb <= 0 and 0 or 1 end return min(1, cb / cs) end return cs end -- non-separable helpers (W3C): lum, clip, setLum, sat, setSat local function lum(r, g, b) return 0.3 * r + 0.59 * g + 0.11 * b end local function clipColor(r, g, b) 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 local function setLum(r, g, b, l) local d = l - lum(r, g, b) return clipColor(r + d, g + d, b + d) end local function setSat(r, g, b, s) 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 local function composite(dst, dw, dh, src, sw, sh, x, y, opacity, mode, opts) 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 = (opts ~= nil and{opts.mask }or{nil })[1] local mbuf= 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) ) 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) ) 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 =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 = h < sa and 1 or 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) ) 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 =so+ 4 do_ =do_+ 4 end end end local function lerp(dst, from, t, n, w, mask) 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= 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, math.floor(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 local function isImage(v) 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 local function maskOf(l) 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 local function compose(layers, canvas, w, h, hidden) local i = 1 while i <= #layers do local __DARKLUA_CONTINUE_8=false repeat local l = layers[i] 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 =i+ 1 end __DARKLUA_CONTINUE_8=true break end local opacity = (tonumber(l.opacity) or 1) * (tonumber(l.fillOpacity) or 1) local mode = (type(l.blend) == "string" and{l.blend }or{"normal" })[1] local src= 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 __DARKLUA_CONTINUE_8=true break end src = buffer.create(w * h * 4) compose(l.children, src , 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 =i+ 1 if src and (c.visible ~= false or hidden) and isImage(c.image) then composite(src , 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 , w, h, 0, 0, opacity, mode, { mask = maskOf(l) }) end __DARKLUA_CONTINUE_8=true until true if not __DARKLUA_CONTINUE_8 then break end end end function Blend.flatten(layers, canvas, w, h, hidden) if blen(canvas) >= w * h * 4 then compose(layers, canvas, w, h, hidden) end end return Blend end __FILES["codecs/image/Dct"] = function() local __compat = __compat local buffer = __compat.buffer --!strict --!native --!optimize 2 -- 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) local function idct8(coef, off, q, plane, out, stride, p1, center, maxv) 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 =t0* 2446 t1 =t1* 16819 t2 =t2* 25172 t3 =t3* 12299 z1 =z1* -7373 z2 =z2* -20995 z3 = z3 * -16069 + z5 z4 = z4 * -3196 + z5 t0 =t0+ (z1 + z3 ) t1 =t1+ (z2 + z4 ) t2 =t2+ (z2 + z3 ) t3 =t3+ (z1 + z4 ) ws[c + 1] = math.floor((tmp10 + t3 + h1) / s1 ) ws[c + 57] = math.floor((tmp10 - t3 + h1) / s1 ) ws[c + 9] = math.floor((tmp11 + t2 + h1) / s1 ) ws[c + 49] = math.floor((tmp11 - t2 + h1) / s1 ) ws[c + 17] = math.floor((tmp12 + t1 + h1) / s1 ) ws[c + 41] = math.floor((tmp12 - t1 + h1) / s1 ) ws[c + 25] = math.floor((tmp13 + t0 + h1) / s1 ) ws[c + 33] = math.floor((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(math.floor((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 =t0* 2446 t1 =t1* 16819 t2 =t2* 25172 t3 =t3* 12299 z1 =z1* -7373 z2 =z2* -20995 z3 = z3 * -16069 + z5 z4 = z4 * -3196 + z5 t0 =t0+ (z1 + z3 ) t1 =t1+ (z2 + z4 ) t2 =t2+ (z2 + z3 ) t3 =t3+ (z1 + z4 ) writeu16(plane, o, clamp(math.floor((tmp10 + t3 + h2) / s2), 0, maxv)) writeu16(plane, o + 14, clamp(math.floor((tmp10 - t3 + h2) / s2), 0, maxv)) writeu16(plane, o + 2, clamp(math.floor((tmp11 + t2 + h2) / s2), 0, maxv)) writeu16(plane, o + 12, clamp(math.floor((tmp11 - t2 + h2) / s2), 0, maxv)) writeu16(plane, o + 4, clamp(math.floor((tmp12 + t1 + h2) / s2), 0, maxv)) writeu16(plane, o + 10, clamp(math.floor((tmp12 - t1 + h2) / s2), 0, maxv)) writeu16(plane, o + 6, clamp(math.floor((tmp13 + t0 + h2) / s2), 0, maxv)) writeu16(plane, o + 8, clamp(math.floor((tmp13 - t0 + h2) / s2), 0, maxv)) end end end local function idct4(coef, off, q, plane, out, stride, p1, center, maxv) 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] = math.floor((tmp10 + tmp2 + h1) / s1 ) ws[c + 25] = math.floor((tmp10 - tmp2 + h1) / s1 ) ws[c + 9] = math.floor((tmp12 + tmp0 + h1) / s1 ) ws[c + 17] = math.floor((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(math.floor((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(math.floor((tmp10 + tmp2 + h2) / s2), 0, maxv)) writeu16(plane, o + 6, clamp(math.floor((tmp10 - tmp2 + h2) / s2), 0, maxv)) writeu16(plane, o + 2, clamp(math.floor((tmp12 + tmp0 + h2) / s2), 0, maxv)) writeu16(plane, o + 4, clamp(math.floor((tmp12 - tmp0 + h2) / s2), 0, maxv)) end end end local function idct2(coef, off, q, plane, out, stride, p1, center, maxv) 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] = math.floor((tmp10 + tmp0 + h1) / s1 ) ws[c + 9] = math.floor((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(math.floor((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(math.floor((tmp10 + tmp0 + h2) / s2), 0, maxv)) writeu16(plane, o + 2, clamp(math.floor((tmp10 - tmp0 + h2) / s2), 0, maxv)) end end end -- p1 = PASS1_BITS (2 for 8-bit, 1 for 12-bit) function Dct.idctComponent(coef, q, bpl, bpc, size, plane, p1, center, maxv, 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 = math.floor((readi16(coef, off) * readu16(q, 0) + 4) / 8 )+ center writeu16(plane, out * 2, clamp(v, 0, maxv)) end end end end function Dct.idctBlock(coef, off, q, plane, out, stride, p1, center, maxv) idct8(coef, off, q, plane, out, stride, p1, center, maxv) end local fw = table.create(64, 0) local function quant(coef, off, div, v, i) local qv = readu16(div, i * 2) * 8 local h = math.floor(qv / 2 ) if v < 0 then writei16(coef, off + i * 2, -(math.floor((h - v) / qv))) else writei16(coef, off + i * 2, math.floor((v + h) / qv)) end end -- quantised as jcdctmgr.c: (|v| + q * 4) // (q * 8) with the sign restored function Dct.fdctQuantize(src, stride, x, y, w, h, div, coef, off) local lastX, lastY = w - 1, h - 1 for r = 0, 7 do local row = math.min(y + r, lastY) * stride local d0, d1, d2, d3, d4, d5, d6, d7 if x + 7 <= lastX then local p = row + x d0, d1, d2, d3 = readu8(src, p), readu8(src, p + 1), readu8(src, p + 2), (readu8(src, p + 3) ) d4, d5, d6, d7 = readu8(src, p + 4), readu8(src, p + 5), readu8(src, p + 6), (readu8(src, p + 7) ) 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 =d0- 128 d1 =d1- 128 d2 =d2- 128 d3 =d3- 128 d4 =d4- 128 d5 =d5- 128 d6 =d6- 128 d7 =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] = math.floor((z1 + tmp13 * 6270 + 1024) / 2048 ) fw[b + 6] = math.floor((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 =tmp4* 2446 tmp5 =tmp5* 16819 tmp6 =tmp6* 25172 tmp7 =tmp7* 12299 z1 =z1* -7373 z2 =z2* -20995 z3 = z3 * -16069 + z5 z4 = z4 * -3196 + z5 fw[b + 7] = math.floor((tmp4 + z1 + z3 + 1024) / 2048 ) fw[b + 5] = math.floor((tmp5 + z2 + z4 + 1024) / 2048 ) fw[b + 3] = math.floor((tmp6 + z2 + z3 + 1024) / 2048 ) fw[b + 1] = math.floor((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 = math.floor((tmp10 + tmp11 + 2) / 4 ) local o4 = math.floor((tmp10 - tmp11 + 2) / 4 ) local z1 = (tmp12 + tmp13) * 4433 local o2 = math.floor((z1 + tmp13 * 6270 + 16384) / 32768 ) local o6 = math.floor((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 =tmp4* 2446 tmp5 =tmp5* 16819 tmp6 =tmp6* 25172 tmp7 =tmp7* 12299 z1 =z1* -7373 z2 =z2* -20995 z3 = z3 * -16069 + z5 z4 = z4 * -3196 + z5 local o7 = math.floor((tmp4 + z1 + z3 + 16384) / 32768 ) local o5 = math.floor((tmp5 + z2 + z4 + 16384) / 32768 ) local o3 = math.floor((tmp6 + z2 + z3 + 16384) / 32768 ) local o1 = math.floor((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 __FILES["codecs/image/Etc"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 -- 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 }) ) 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 }, } local function clamp8(v) return v < 0 and 0 or(v > 255 and 255 or v )end local function rgb(r, g, b) 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) local function be32(src, p) return byteswap(readu32(src, p)) end -- the 2-bit pixel index of pixel i (column-major: i = x * 4 + y) local function pix(lo, i) return band(rshift(lo, i + 15), 2) + band(rshift(lo, i), 1) end -- ETC1 / ETC2 colour block; the RGB A1 variant: bit 33 = opaque local function colour(src, p, blk, etc2, punch) 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 =dR- 8 end if dG >= 4 then dG =dG- 8 end if dB >= 4 then dB =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 = q1r * 256 + q1g * 16 + q1b >= q2r * 256 + q2g * 16 + q2b and 1 or 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 = math.floor((x * (rh - ro) + y * (rv - ro) + 4 * ro + 2) / 4 ) local g = math.floor((x * (gh - go) + y * (gv - go) + 4 * go + 2) / 4 ) local b = math.floor((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 = not opaque and idx == 2 and 0 or 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 = (flip == 0 and{(x >= 2 )}or{(y >= 2 )})[1] local idx = pix(lo, i) local c if not opaque and idx == 2 then c = 0 else local m = (second and{t2[idx + 1] }or{t1[idx + 1] })[1] if not opaque and idx == 0 then m = 0 end if second then c = rgb((r2 ) + m, (g2 ) + m, (b2 ) + m) else c = rgb((r1 ) + m, (g1 ) + m, (b1 ) + m) end end writeu32(blk, (y * 4 + x) * 4, c) end end local VALS = table.create(16, 0) local function eac(src, p, mode) 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 =base- 256 end if base == -128 then base = -127 end end for i = 0, 15 do local idx = (i < 8 and{(band(rshift(hiIdx, 21 - i * 3), 7) )}or{(band(rshift(loIdx, 21 - (i - 8) * 3), 7) )})[1] local m = tab[idx + 1] local v if mode == "alpha" then v = clamp8(base + m * mult) elseif mode == "u11" then v = (mult == 0 and((base * 8 + 4 + m ))or((base * 8 + 4 + m * mult * 8 ))) v = v < 0 and 0 or(v > 2047 and 2047 or v ) else v = (mult == 0 and((base * 8 + m ))or((base * 8 + m * mult * 8 ))) v = v < -1023 and-1023 or(v > 1023 and 1023 or v ) end VALS[band(i, 3) * 4 + rshift(i, 2) + 1] = v end end local function to8(v, signed) if signed then return math.floor(v * 127 / 1023 + 0.5) + 128 end return math.floor(v * 255 / 2047 + 0.5) end local function to16(v, signed) if signed then return math.floor((v + 1023) * 65535 / 2046 + 0.5) end return v * 32 + rshift(v, 6) end function Etc.size(kind, w, h) local b = Etc.BLOCK[kind] return (b and(((math.floor((w + 3) / 4)) * (math.floor((h + 3) / 4)) * b ))or(nil ))end function Etc.decode(kind, src, offset, w, h, out, outOffset, wide) 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) ) 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 = w16 and 8 or 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 = signed and"s11" or"u11" local etc2 = kind ~= "etc1" local punch = kind == "etc2_rgba1" local blk = buffer.create(16 * bpp) local bw, bh = math.floor((w + 3) / 4), math.floor((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, two and 0 or q) writeu16(blk, i * 8 + 4, two and 0 or q) writeu16(blk, i * 8 + 6, 65535) else local q = to8(v, signed) writeu32(blk, i * 4, (two and((q + 0xFF000000 ))or((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 =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"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 -- 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 local function toFloat(h) local s = h >= 32768 and-1 or 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 (m == 0 and((s * math.huge ))or((0 / 0 ))) end return s * (1024 + m) * 2 ^ (e - 25) end Half.toFloat = toFloat local TABLE= table.create(65536, 0) for h = 0, 65535 do TABLE[h] = toFloat(h) end Half.TABLE = TABLE local scratch = buffer.create(4) function Half.fromFloat(f) 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 =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 =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/Jpeg"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict -- 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 = {} local function range(buf, off, len) 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, o, l, opts, headerOnly) 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) local sampling = {} for _, c in __iter(f.comps) do table.insert(sampling, { c.h, c.v }) end return sampling end function Jpeg.info(buf, off, len) 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, w, h, o) if o <= 1 or o > 8 then return px, w, h end local swap = o >= 5 local ow, oh = (swap and{h }or{w})[1], (swap and{w }or{h })[1] 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, o, l, opts) local st, err = parse(buf, o, l, opts, false) if not st then return nil, err end local s = st 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 , px , "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 = s.density.unit == 2 and 2.54 or 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 = mode and"full" or nil, fields = 1, } return img, s end -- the start of a second JPEG: FF D8 FF local function nextSoi(buf, p, e) 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 =p+ 1 end return -1 end local function weave(a, b) 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 = math.floor((w + 1) / 2), math.floor((hf + 1) / 2 ) local ch = math.floor((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, off, len, opts) 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 local wantFields = (opts and opts.fields ~= nil and{opts.fields }or{(s.avi1 == 1 or s.avi1 == 2) })[1] 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 {}) ) 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= 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, opts) 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 = (bpp == 0 and((w * h + 2 * (math.floor((w + 1) / 2)) * (math.floor((h + 1) / 2)) ))or((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= 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 __iter(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"] = function() local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict --!native --!optimize 2 -- 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 __iter(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.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.create(0) local P = 0 local SEGEND = 0 local OVER = 0 local C, A, CT = 0, 0, -16 local st= buffer.create(STATS) local function decode(s) while A < 0x8000 do CT =CT- 1 if CT < 0 then local data = 0 if P < SEGEND then data = readu8(D, P) P =P+ 1 else OVER =OVER+ 1 end C = C * 256 + data CT =CT+ 8 if CT < 0 then CT =CT+ 1 if CT == 0 then A = 0x8000 end end end A =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 =temp* readu8(POW2, CT) if C >= temp then C =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 sv >= 0x80 and 1 or 0 end local function i16(v) v = band(v, 0xFFFF) return (v >= 0x8000 and((v - 0x10000 ))or(v ))end -- DC difference (F.1.4.4.1 / figures F.19, F.21 - F.24) local function dcDiff(c, L, U) 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 =m* 2 if m == 0x8000 then return nil end s =s+ 1 end end if m < math.floor(2 ^ L / 2 )then c.ctx = 0 elseif m > math.floor(2 ^ U / 2 )then c.ctx = 12 + sign * 4 else c.ctx = 4 + sign * 4 end local v = m s =s+ 14 m = math.floor(m / 2 ) while m > 0 do if decode(s) ~= 0 then v =v+ m end m = math.floor(m / 2 ) end v =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) local function acFirst(coef, off, tbl, ss, se, K, mul) 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 =s+ 3 k =k+ 1 if k > se then return false end end local sign = decode(FIXED) s =s+ 2 local m = decode(s) if m ~= 0 then if decode(s) ~= 0 then m =m* 2 s = base + (k <= K and 189 or 217) while decode(s) ~= 0 do m =m* 2 if m == 0x8000 then return false end s =s+ 1 end end end local v = m s =s+ 14 m = math.floor(m / 2 ) while m > 0 do if decode(s) ~= 0 then v =v+ m end m = math.floor(m / 2 ) end v =v+ 1 if sign ~= 0 then v = -v end writei16(coef, off + readu8(ZZ, k) * 2, i16(v * mul)) k =k+ 1 end return true end local function acRefine(coef, off, tbl, ss, se, al) 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 =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((cv < 0 and((cv + m1 ))or((cv + p1))))) end break end if decode(s + 1) ~= 0 then writei16(coef, o, i16((decode(FIXED) ~= 0 and{m1 }or{p1})[1])) break end s =s+ 3 k =k+ 1 if k > se then return false end end k =k+ 1 end return true end function Arith.init(zigzag) ZZ = zigzag end function Arith.run(d, cleanLen, rst, nrst, Pm) 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 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 = (nrst >= 1 and{(math.min(rst[1], cleanLen) )}or{cleanLen })[1] 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 =rstIdx+ 1 if rstIdx <= nrst then P = math.min(rst[rstIdx], cleanLen) SEGEND = (rstIdx + 1 <= nrst and{(math.min(rst[rstIdx + 1], cleanLen) )}or{cleanLen })[1] bad = false else truncated = true break end reset() end if not bad then local my, mx = math.floor(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"] = function() local __compat = __compat local buffer = __compat.buffer --!strict --!native --!optimize 2 -- 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 -- jdcolor.c build_ycc_rgb_table function Color.tables(maxv) local n = maxv + 1 local center = math.floor(n / 2 ) local crr, cbb, crg, cbg = buffer.create(n * 4), buffer.create(n * 4), buffer.create(n * 4), buffer.create(n * 4) local function fix(x) return math.floor(x * 65536 + 0.5) end for i = 0, maxv do local x = i - center buffer.writei32(crr, i * 4, math.floor((fix(1.40200) * x + 32768) / 65536)) buffer.writei32(cbb, i * 4, math.floor((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 local function fetch(c, y, outW) 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, math.floor((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, math.floor((v3 + prev + 1) / 4)) writeu16(row, i * 4 + 2, math.floor((v3 + nxt + 2) / 4)) prev = cur cur = nxt end writeu16(row, (w - 1) * 4, math.floor((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(math.floor(y / 2), c.downH - 1) local oy = (y % 2 == 0 and{(max(iy - 1, 0) )}or{(min(iy + 1, c.downH - 1) )})[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, math.floor((this * 4 + 8) / 16)) writeu16(row, 2, math.floor((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, math.floor((t3 + last + 8) / 16)) writeu16(row, i * 4 + 2, math.floor((t3 + nxt + 7) / 16)) last = this this = nxt end writeu16(row, (w - 1) * 4, math.floor((this * 3 + last + 8) / 16)) writeu16(row, (w - 1) * 4 + 2, math.floor((this * 4 + 7) / 16)) return row, 0 elseif method == 4 then local iy = min(math.floor(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, math.floor((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(math.floor((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(math.floor((x * hIn) / hOut), last) * 2)) end return row, 0 end end function Color.run(P) 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 local __DARKLUA_CONTINUE_6=false repeat 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 =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 = (nc >= 4 and{(readu16(s3, b3 + i) )}or{maxv })[1] 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 =o+ 4 end __DARKLUA_CONTINUE_6=true break 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 + math.floor((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 =o+ 4 end __DARKLUA_CONTINUE_6=true break 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 = math.floor((c0 * k + math.floor(maxv / 2)) / maxv ) g = math.floor((c1 * k + math.floor(maxv / 2)) / maxv ) b = math.floor((c2 * k + math.floor(maxv / 2)) / maxv ) else r = clamp(c0 + readi32(crr, c2 * 4), 0, maxv) g = clamp(c0 + math.floor((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 = math.floor(((maxv - r) * k + math.floor(maxv / 2)) / maxv ) g = math.floor(((maxv - g) * k + math.floor(maxv / 2)) / maxv ) b = math.floor(((maxv - b) * k + math.floor(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 =o+ 4 end end __DARKLUA_CONTINUE_6=true until true if not __DARKLUA_CONTINUE_6 then break end end end return Color end __FILES["codecs/image/Jpeg/Decode"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict -- 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, p) return readu8(b, p) * 256 + readu8(b, p + 1) end local stdBuilt= {} local function stdTable(class, slot) local key = class .. slot if not stdBuilt[key] then local def = ((class == "dc" and{Tables.DC }or{Tables.AC})[1])[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, p, e) 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) 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) 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, (v >= 1 and v <= 8 and{v }or{nil })[1] end end return t, nil end 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, p, e, m) 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= {} 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) ) 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 __iter(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) ) 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 } ) end local mcusX = math.ceil(width / (8 * hmax)) local mcusY = math.ceil(height / (8 * vmax)) for _, c in __iter(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, adobe, jfif) local n = #frame.comps if n == 1 then return "gray" elseif n == 3 then if adobe ~= nil then return adobe == 0 and"rgb" or"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 adobe == 2 and"ycck" or"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, c, scale) local minSize = math.floor(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 =ssize* 2 end return ssize end function Decode.parse(b, base, n, opts, headerOnly) 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= (opts and opts.maxPixels) or 2 ^ 26 local quant= {} local dcT= {} local acT= {} local dcL, dcU, acK = { 0, 0, 0, 0 }, { 1, 1, 1, 1 }, { 5, 5, 5, 5 } local frame= nil local st= { 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 = (opts and type(opts.yield) == "function" and{opts.yield }or{nil})[1], } local iccChunks= {} local ri = 0 local scans = 0 local clean= nil local rst = {} local pos = base + 2 while pos < n do local __DARKLUA_CONTINUE_6=false repeat -- find the next marker (tolerate garbage and fill bytes) if readu8(b, pos) ~= 0xFF then pos =pos+ 1 __DARKLUA_CONTINUE_6=true break end while pos < n and readu8(b, pos) == 0xFF do pos =pos+ 1 end if pos >= n then break end local m = readu8(b, pos) 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 __DARKLUA_CONTINUE_6=true break -- 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 = pq == 0 and 64 or 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 = (pq == 0 and{(readu8(b, p + 1 + k) )}or{(be16(b, p + 1 + k * 2) )})[1] buffer.writeu16(q, readu8(Scan.ZIGZAG, k) * 2, v) end quant[tq] = q p =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 =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 =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 =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 local ns = (p < e and{(readu8(b, p) )}or{0 })[1] if ns < 1 or ns > 4 or e - p < 4 + ns * 2 then return nil, "corrupt", "bad SOS segment" end local sc= {} 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 __iter(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 =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 = ah == 0 and 1 or 2 else mode = ah == 0 and 3 or 4 end end for _, c in __iter(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 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 , 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 =scans+ 1 pos = nextPos end __DARKLUA_CONTINUE_6=true until true if not __DARKLUA_CONTINUE_6 then break end end if not frame then return nil, st.truncated and"truncated" or"corrupt", "no frame header" end if #iccChunks > 0 then local total = 0 for _, c in __iter(iccChunks) do total =total+ buffer.len(c) end local icc = buffer.create(total) local o = 0 for _, c in __iter(iccChunks) do buffer.copy(icc, o, c) o =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= {} local function yccTables(maxv) 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= nil function Decode.output(st) local f= st.frame local scale = st.scale local minSize = math.floor(8 / scale ) local maxv = f.precision == 12 and 4095 or 255 local center = math.floor((maxv + 1) / 2 ) local p1 = f.precision == 12 and 1 or 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 __iter(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 , c.bpl, c.bpc, ssize, plane, p1, center, maxv, st.hook) local hIn, hOut = math.floor(c.h * ssize / minSize), f.hmax local vIn, vOut = math.floor(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, math.floor((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= nil local function scratchPlane(n) 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) local f= 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 = math.floor(f.hmax / cb.h), math.floor(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 __iter(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 = math.floor((w + 1) / 2), math.floor((h + 1) / 2 ) local out = buffer.create(w * h + 2 * cw * ch) local zeroQ= nil for i, c in __iter(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 , 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"] = function() local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict --!native --!optimize 2 -- 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 =i+ 1 end else for r = lo, hi do writeu8(ZZ, i, r * 8 + (s - r)) i =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 local function grow(n) 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 local function byte(v) grow(1) writeu8(OUT, OP, v) OP =OP+ 1 end local function u16be(v) byte(math.floor(v / 256)) byte(v % 256) end -- n bits of v (n <= 16), MSB first, with 0xFF stuffing local function bits(v, n) if GATHER or n == 0 then return end local p = 2 ^ n ACC = ACC * p + band(v, p - 1) NB =NB+ n while NB >= 8 do NB =NB- 8 local d = 2 ^ NB local b = math.floor(ACC / d ) ACC =ACC- b * d grow(2) writeu8(OUT, OP, b) OP =OP+ 1 if b == 0xFF then writeu8(OUT, OP, 0) OP =OP+ 1 end end end local function flushBits() if NB > 0 then bits(0x7F, 8 - NB) -- pad with ones end ACC, NB = 0, 0 end local function nbits(v) return v == 0 and 0 or 32 - countlz(v) end -- a derived table: u16 code + u8 size per symbol (jpeg_make_c_derived_tbl) local function derive(counts, symbols) 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 =k+ 1 c =c+ 1 end c =c* 2 end return { code = code, size = size } end -- jchuff.c jpeg_gen_optimal_table: freq (0..256, 1-based +1) -> counts, symbols local function optimal(freqIn) 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 = i == 256 and 1 or freqIn[i + 1] if f > 0 then n =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[c1]+ freq[c2] freq[c2] = 1000000001 codesize[c1]=codesize[c1]+ 1 while others[c1] >= 0 do c1 = others[c1] codesize[c1]=codesize[c1]+ 1 end others[c1] = c2 codesize[c2]=codesize[c2]+ 1 while others[c2] >= 0 do c2 = others[c2] codesize[c2]=codesize[c2]+ 1 end end for i = 1, n do local cs = math.min(codesize[i], 32) do local __DARKLUA_VAR=cs + 1 bitsT[__DARKLUA_VAR]=bitsT[__DARKLUA_VAR]+ 1 end end local bitPos = table.create(34, 0) local p = 0 for i = 1, 32 do bitPos[i + 1] = p 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 =j- 1 end do local __DARKLUA_VAR=i + 1 bitsT[__DARKLUA_VAR]=bitsT[__DARKLUA_VAR]- 2 end bitsT[i]=bitsT[i]+ 1 do local __DARKLUA_VAR0=j + 2 bitsT[__DARKLUA_VAR0]=bitsT[__DARKLUA_VAR0]+ 2 end do local __DARKLUA_VAR1=j + 1 bitsT[__DARKLUA_VAR1]=bitsT[__DARKLUA_VAR1]- 1 end end i =i- 1 end while bitsT[i + 1] == 0 do i =i- 1 end do local __DARKLUA_VAR=i + 1 bitsT[__DARKLUA_VAR]=bitsT[__DARKLUA_VAR]- 1 end 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] do local __DARKLUA_VAR0=cs + 1 bitPos[__DARKLUA_VAR0]=bitPos[__DARKLUA_VAR0]+ 1 end end local total = 0 for l = 1, 16 do total =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= {} local acTab= {} local dcFreq= {} local acFreq= {} local function symbol(t, freq, s) if GATHER then do local __DARKLUA_VAR=s + 1 freq[__DARKLUA_VAR]=freq[__DARKLUA_VAR]+ 1 end else bits(readu16(t.code, s * 2), readu8(t.size, s)) end end local function dcDiff(c, diff) local t = diff local t2 = diff if t < 0 then t = -t t2 =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 local function blockSeq(c, off) 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 =r+ 1 else while r > 15 do symbol(at, af, 0xF0) r =r- 16 end local t, t2 = v, v if t < 0 then t = -t t2 =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) ) local curAc= { code = buffer.create(512), size = buffer.create(256) } local curAcFreq= {} 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 local function blockDcFirst(c, off, al) local t2 = math.floor(readi16(c.coef, off) / 2 ^ al ) dcDiff(c, t2 - c.last) c.last = t2 end local function blockAcFirst(c, off, ss, se, al) 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 = math.floor((-v) / d ) t2 = -t - 1 -- ~t else t = math.floor(v / d ) t2 = t end if t == 0 then r =r+ 1 else emitEobrun() while r > 15 do symbol(curAc, curAcFreq, 0xF0) r =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 =EOBRUN+ 1 if EOBRUN == 0x7FFF then emitEobrun() end end end local absv = table.create(64, 0) local function blockAcRefine(c, off, ss, se, al) 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 = math.floor(((v < 0 and{(-v )}or{v})[1]) / 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 __DARKLUA_CONTINUE_28=false repeat local t = absv[k + 1] if t == 0 then r =r+ 1 __DARKLUA_CONTINUE_28=true break end while r > 15 and k <= eob do emitEobrun() symbol(curAc, curAcFreq, 0xF0) r =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 =br+ 1 CORR[brStart + br] = t % 2 __DARKLUA_CONTINUE_28=true break end emitEobrun() symbol(curAc, curAcFreq, r * 16 + 1) bits(readi16(coef, off + readu8(ZZ, k) * 2) < 0 and 0 or 1, 1) if not GATHER then for i = 1, br do bits(CORR[brStart + i], 1) end end brStart = 0 br = 0 r = 0 __DARKLUA_CONTINUE_28=true until true if not __DARKLUA_CONTINUE_28 then break end end if r > 0 or br > 0 then EOBRUN =EOBRUN+ 1 BE =BE+ br if EOBRUN == 0x7FFF or BE > 1000 - 64 + 1 then emitEobrun() end end end local function walk(comps, mcusX, mcusY, ri, onRestart, fn) 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 = math.floor(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 local function dht(class, slot, counts, symbols) byte(0xFF) byte(0xC4) u16be(2 + 17 + #symbols) byte(class * 16 + slot) for l = 1, 16 do byte(counts[l]) end for _, s in __iter(symbols) do byte(s) end end local function sos(comps, ss, se, ah, al, dcOnly, acOnly) byte(0xFF) byte(0xDA) u16be(6 + 2 * #comps) byte(#comps) for _, c in __iter(comps) do byte(c.id) local td = acOnly and 0 or c.td local ta = dcOnly and 0 or 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) local function fix(x) 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 local function planes(px, w, h, bpp, gray) 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, math.floor((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, math.floor((YR * r + YG * g + YB * b + 32768) / 65536)) writeu8(Cb, i, math.floor((-CBR * r - CBG * g + HALF * b + OFF) / 65536)) writeu8(Cr, i, math.floor((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 local function downsample(src, w, h, hf, vf, outW, outH) 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 = hf == 2 and vf == 2 and 1 or(hf == 2 and 0 or(vf == 2 and 1 or 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 = math.floor((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 = math.floor((readu8(src, r0 + x0) + readu8(src, r0 + x1) + bias) / 2 ) bias = 1 - bias else v = math.floor((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 function Encode.run(px, w, h, bpp, o) OUT = buffer.create(math.max(1024, math.floor(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, (math.floor((w + 1) / 2)) * (math.floor((h + 1) / 2)) Y = px if not o.gray then Cb, Cr = buffer.create(cn), buffer.create(cn) buffer.copy(Cb , 0, px, n, cn) buffer.copy(Cr , 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= {} local srcs = o.gray and{ Y } or{ Y, Cb , Cr } for i, src in __iter(srcs) do local ch, cv = (i == 1 and{hs }or{1})[1], (i == 1 and{vs }or{1 })[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 = math.floor((w + 1) / 2), math.floor((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, math.floor(hs / ch), math.floor(vs / cv), pw, ph) end local coef = buffer.create(bpl * bpc * 128) local c= { id = i, h = ch, v = cv, tq = i == 1 and 0 or 1, td = i == 1 and 0 or 1, ta = i == 1 and 0 or 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 = (math.floor(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 __iter({ 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 __iter(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 =OP+ n end for t = 1, (o.gray and 1 or 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(o.progressive and 0xC2 or 0xC0) u16be(8 + 3 * #comps) byte(8) u16be(h) u16be(w) byte(#comps) for _, c in __iter(comps) do byte(c.id) byte(c.h * 16 + c.v) byte(c.tq) end local ntab = o.gray and 1 or 2 local function restartMarker(n) 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 __iter(comps) do c.last = 0 end walk(comps, mcusX, mcusY, o.restart, function() for _, c in __iter(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 __iter(comps) do c.last = 0 end walk(comps, mcusX, mcusY, o.restart, function(n) restartMarker(n) for _, c in __iter(comps) do c.last = 0 end end, blockSeq) flushBits() else local script 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 __iter(script) do local sComps= {} for _, ci in __iter(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 if isDc and ah == 0 then blockFn = function(c, off) blockDcFirst(c, off, al) end elseif isDc then blockFn = function(c, off) bits(band(math.floor(readi16(c.coef, off) / 2 ^ al), 1), 1) end elseif ah == 0 then blockFn = function(c, off) blockAcFirst(c, off, ss, se, al) end else blockFn = function(c, off) blockAcRefine(c, off, ss, se, al) end end local function onRestart(n) emitEobrun() if not GATHER then restartMarker(n) end for _, c in __iter(sComps) do c.last = 0 end EOBRUN, BE = 0, 0 end local function pass() for _, c in __iter(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 __iter(sComps) do local slot = (isDc and{c.td }or{c.ta })[1] if not sent[slot] then sent[slot] = true local counts, syms = optimal((isDc and{dcFreq[slot + 1] }or{acFreq[slot + 1]})[1]) dht(isDc and 0 or 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"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 -- 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 =i+ 1 end else for r = lo, hi do writeu8(ZZ, i, r * 8 + (s - r)) i =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 function Scan.buildTable(counts, symbols) 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 =k+ 1 codes[k] = code sizes[k] = l code =code+ 1 end writeu32(t, T_MAX + l * 4, broken and 0 or lshift(code, 16 - l)) code =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 function Scan.destuff(src, pos, n, dst, rst) local o, nr = 0, 0 while pos < n do local b = readu8(src, pos) if b ~= 0xFF then writeu8(dst, o, b) o =o+ 1 pos =pos+ 1 else local q = pos + 1 while q < n and readu8(src, q) == 0xFF do q =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 =o+ 1 pos = q + 1 elseif m >= 0xD0 and m <= 0xD7 then nr =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 local function huff(d, pos, t) 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 =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 local function bits(d, pos, s) return rshift(lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)), 32 - s) end local function extend(v, s) if v < lshift(1, s - 1) then return v - lshift(1, s) + 1 end return v end local function blockSeq(d, pos, coef, off, dct, act, pred) local s s, pos = huff(d, pos, dct) if s ~= 0 then if s > 16 then s = 16 end pred =pred+ extend(bits(d, pos, s), s) pos =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 =k+ math.floor(low / 16 ) pos =pos+ low % 16 if k > 63 then break end writei16(coef, off + readu8(ZZ, k) * 2, math.floor(fa / 256)) k =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 =k+ 16 else k =k+ r if k > 63 then break end writei16(coef, off + readu8(ZZ, k) * 2, extend(bits(d, pos, sz), sz)) pos =pos+ sz k =k+ 1 end end end return pos, pred end local function blockDcFirst(d, pos, coef, off, dct, pred, al) local s s, pos = huff(d, pos, dct) if s ~= 0 then if s > 16 then s = 16 end pred =pred+ extend(bits(d, pos, s), s) pos =pos+ s end writei16(coef, off, pred * lshift(1, al)) return pos, pred end local function blockAcFirst(d, pos, coef, off, act, ss, se, al, eobrun) 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 =k+ math.floor(low / 16 ) pos =pos+ low % 16 if k > se then break end writei16(coef, off + readu8(ZZ, k) * 2, (math.floor(fa / 256)) * mul) k =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 =eobrun+ bits(d, pos, r) pos =pos+ r end break end k =k+ 16 else k =k+ r if k > se then break end writei16(coef, off + readu8(ZZ, k) * 2, extend(bits(d, pos, s), s) * mul) pos =pos+ s k =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) local function blockAcRefine(d, pos, coef, off, act, ss, se, al, eobrun) 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 =pos+ 1 if b ~= 0 and band(p, bit) == 0 then writei16(coef, o, (p > 0 and((p + bit ))or((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 =eobrun+ bits(d, pos, r) pos =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 =pos+ 1 val = (b ~= 0 and{bit }or{(-bit )})[1] end while k <= se do local o = off + readu8(ZZ, k) * 2 k =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 =pos+ 1 if b ~= 0 and band(p, bit) == 0 then writei16(coef, o, (p > 0 and((p + bit ))or((p - bit)))) end else if r == 0 then if val ~= 0 then writei16(coef, o, val) end break end r =r- 1 end end end -- an EOB run that started in this block counts it already (eobrun = run length - 1) return pos, eobrun end function Scan.run(d, cleanLen, rst, nrst, P) 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 =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 = math.floor(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 , c.act , c.pred) elseif mode == 1 then pos, c.pred = blockDcFirst(d, pos, coef, off, c.dct , c.pred, al) elseif mode == 2 then local b = rshift(lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)), 31) pos =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 , ss, se, al, eobrun) else pos, eobrun = blockAcRefine(d, pos, coef, off, c.act , ss, se, al, eobrun) end end end end end end return pos, truncated end return Scan end __FILES["codecs/image/Jpeg/Tables"] = function() --!strict -- 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, a, b) 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) Tables.DC = { { counts = dcl, symbols = dcv }, { counts = dcc, symbols = dcv } } Tables.AC = { { counts = acl, symbols = aclv }, { counts = acc, symbols = accv } } -- 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, quality) local q = math.clamp(math.floor(quality), 1, 100) local scale = (q < 50 and{(math.floor(5000 / q ))}or{(200 - q * 2 )})[1] local out = table.create(64, 1) for i = 1, 64 do out[i] = math.clamp(math.floor((base[i] * scale + 50) / 100), 1, 255) end return out end return Tables end __FILES["codecs/image/Jpeg/Yuv"] = function() local __compat = __compat local buffer = __compat.buffer --!strict --!native --!optimize 2 -- 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 = {} function Yuv.crop(src, stride, w, h, dst, doff) local quads = math.floor(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 + (math.floor(a / 65536)) * 256 + (b % 65536) * 65536 + (math.floor(b / 65536)) * 16777216) s =s+ 8 d =d+ 4 end for k = 0, rest - 1 do writeu8(dst, d + k, readu16(src, s + k * 2)) end end end function Yuv.rows(src, stride, w, h, dst, doff) local oh = math.floor((h + 1) / 2 ) for y = 0, oh - 1 do local a = 2 * y * stride * 2 local b = (2 * y + 1 < h and((a + stride * 2 ))or(a )) local d = doff + y * w for x = 0, w - 1 do writeu8(dst, d + x, math.floor((readu16(src, a + x * 2) + readu16(src, b + x * 2) + 1) / 2)) end end end function Yuv.box(src, stride, w, h, dst, doff) local ow, oh = math.floor((w + 1) / 2), math.floor((h + 1) / 2 ) for y = 0, oh - 1 do local a = 2 * y * stride * 2 local b = (2 * y + 1 < h and((a + stride * 2 ))or(a )) local d = doff + y * ow for x = 0, ow - 1 do local x0 = 2 * x * 2 local x1 = (2 * x + 1 < w and((x0 + 2 ))or(x0 )) writeu8(dst, d + x, math.floor((readu16(src, a + x0) + readu16(src, a + x1) + readu16(src, b + x0) + readu16(src, b + x1) + 2) / 4)) end end end function Yuv.weave(top, toff, bottom, boff, rowBytes, rows, dst, doff) for y = 0, rows - 1 do local k = math.floor(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 __FILES["codecs/image/Miptex"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict -- codecs/image/Miptex: Quake / GoldSrc mip textures and the WAD2 / WAD3 lump directory, read and write. -- miptex_t of bspfile.h: name[16], width, height, offsets[4], four 8-bit mip levels; GoldSrc adds u16 count + count * 3 -- palette bytes after mip 3. wad.h: "WAD2" / "WAD3", numlumps, infotableofs; 32-byte lumpinfo_t. No code taken. local Types = __include("Types") local Pixels = __include("codecs/image/Pixels") local Quantize = __include("codecs/image/Quantize") local Miptex = {} local readu8, readu32, readi32 = buffer.readu8, buffer.readu32, buffer.readi32 -- lumpinfo_t types (wad.h TYP_*; WAD3: 0x43 is a miptex with its palette, 0x46 a font) Miptex.TYPES = table.freeze({ palette = 0x40, qtex = 0x41, qpic = 0x42, sound = 0x43, miptex = 0x44, font = 0x46 }) local function cstr(b, at, n) return (string.match(buffer.readstring(b, at, n), "^[^%z]*")) end function Miptex.header(b, at, size) if at < 0 or size < 40 or at + 40 > buffer.len(b) then return nil, "truncated miptex header" end local w, h = readu32(b, at + 16), readu32(b, at + 20) local offs = { readu32(b, at + 24), readu32(b, at + 28), readu32(b, at + 32), readu32(b, at + 36) } return { name = cstr(b, at, 16), width = w, height = h, offsets = offs }, nil end -- the GoldSrc palette after mip 3, as a 1024-byte rgba8 palette, or nil when it is missing / out of range function Miptex.ownPalette(b, at, size, hd) local w, h = hd.width, hd.height local p = hd.offsets[4] + (math.floor(w / 8)) * (math.floor(h / 8)) if hd.offsets[4] == 0 or p + 2 > size then return nil end local n = buffer.readu16(b, at + p) if n == 0 or n > 256 or p + 2 + n * 3 > size then return nil end return Pixels.palette(b, at + p + 2, n) end -- decodes one mip level to rgba8; without pixels (offsets 0: the texture lives in a WAD) returns nil, "external" function Miptex.decode(b, at, size, opts) local hd, err = Miptex.header(b, at, size) if not hd then return nil, err end local mip = math.clamp(math.floor(opts and opts.mip or 0), 0, 3) local w, h = math.floor(hd.width / (2 ^ mip)), math.floor(hd.height / (2 ^ mip) ) if hd.width == 0 or hd.height == 0 or w == 0 or h == 0 then return nil, "empty miptex" end if hd.width * hd.height > (opts and opts.maxPixels or 2 ^ 24) then return nil, "limit: miptex " .. hd.width .. " x " .. hd.height end local off = hd.offsets[mip + 1] if off == 0 then return nil, "external" end if off + w * h > size or at + off + w * h > buffer.len(b) then return nil, "truncated miptex pixels" end local own = (opts and opts.goldsrc and{(Miptex.ownPalette(b, at, size, hd) )}or{nil })[1] local pal = own or (opts and opts.palette) or Pixels.grey() local keyed = (opts and opts.keyed ~= nil and{opts.keyed }or{(string.sub(hd.name, 1, 1) == "{" )})[1] if keyed then pal = Pixels.keyed(pal, 255) end local img = Types.Image.new(w, h) Pixels.indexed(b, at + off, w, 8, img.pixels, w, h, true, pal) img.meta.source = { format = "miptex", name = hd.name, mip = mip, palette = own ~= nil or (opts ~= nil and opts.palette ~= nil), keyed = keyed or nil } return img, nil end local function halve(px, w, h) local w2, h2 = math.max(1, math.floor(w / 2)), math.max(1, math.floor(h / 2)) local out = buffer.create(w2 * h2 * 4) for y = 0, h2 - 1 do for x = 0, w2 - 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 =s+ readu8(px, (sy * w + sx) * 4 + c) end end buffer.writeu8(out, (y * w2 + x) * 4 + c, math.floor((s + 2) / 4)) end end end return out, w2, h2 end -- an rgba8 image -> a miptex_t with four mip levels (box filtered, mapped to the nearest palette entry); goldsrc -- appends the palette. palette: 1024-byte rgba8; without it (GoldSrc only) a 256-colour median-cut palette is made. function Miptex.encode(img, name, palette, goldsrc) local w, h = img.width, img.height if w <= 0 or h <= 0 or w % 16 ~= 0 or h % 16 ~= 0 then return nil, "miptex sizes must be multiples of 16" end if #name > 15 then return nil, "miptex name over 15 bytes" end if not palette and not goldsrc then return nil, "a Quake miptex needs a palette" end local keyed = string.sub(name, 1, 1) == "{" local _, colors = Miptex.indices(img, palette, keyed) if keyed and not palette then colors[256] = { 0, 0, 255, 255 } -- GoldSrc '{' textures: index 255 is the (blue) key colour end local pal1024 = palette or buffer.create(1024) if not palette then for i, c in __iter(colors) do buffer.writeu32(pal1024, (i - 1) * 4, 0xFF000000 + c[3] * 65536 + c[2] * 256 + c[1]) end end local levels= {} local px, lw, lh = img.pixels, w, h for m = 0, 3 do if m > 0 then px, lw, lh = halve(px, lw, lh) end local lvl = { kind = "image", width = lw, height = lh, format = "rgba8", pixels = px, loops = 0, meta = {} } levels[m + 1] = (Miptex.indices(lvl, pal1024, keyed)) end local total = 40 for _, l in __iter(levels) do total =total+ buffer.len(l) end local palAt = total if goldsrc then total =total+ (2 + 768 + 2 ) end local out = buffer.create(total) buffer.writestring(out, 0, name) buffer.writeu32(out, 16, w) buffer.writeu32(out, 20, h) local o = 40 for m, l in __iter(levels) do buffer.writeu32(out, 24 + (m - 1) * 4, o) buffer.copy(out, o, l) o =o+ buffer.len(l) end if goldsrc then buffer.writeu16(out, palAt, 256) for i = 0, 255 do local c = colors[i + 1] or { 0, 0, 0 } buffer.writeu8(out, palAt + 2 + i * 3, c[1]) buffer.writeu8(out, palAt + 3 + i * 3, c[2]) buffer.writeu8(out, palAt + 4 + i * 3, c[3]) end end return out, nil end -- the lump directory of a WAD2 / WAD3 file (offsets relative to base), or nil, message function Miptex.wad(b, base, size, maxLumps) if size < 12 or base + 12 > buffer.len(b) then return nil, "truncated header", nil end local magic = buffer.readstring(b, base, 4) if magic ~= "WAD2" and magic ~= "WAD3" then return nil, "bad magic", nil end local n, dir = readi32(b, base + 4), readi32(b, base + 8) if n < 0 or dir < 0 then return nil, "negative directory field", nil end if n > (maxLumps or 1e6) then return nil, "limit: too many lumps: " .. n, nil end if dir + n * 32 > size then return nil, "truncated directory past the end", nil end local out= {} for i = 0, n - 1 do local o = base + dir + i * 32 local at, disk, full = readi32(b, o), readi32(b, o + 4), readi32(b, o + 8) if at < 0 or disk < 0 or at + disk > size then return nil, "truncated lump past the end", nil end out[i + 1] = { name = cstr(b, o + 16, 16), offset = at, disksize = disk, size = full, type = readu8(b, o + 12), compression = readu8(b, o + 13) } end return out, nil, magic end -- the lump named name (case-insensitive, the last one wins as in W_GetLumpinfo) function Miptex.find(lumps, name) local want = string.lower(name) local best= nil for _, l in __iter(lumps) do if string.lower(l.name) == want then best = l end end return best end -- qpic (Quake .lmp / WAD2 type 0x42: u32 width, height, 8-bit pixels; GoldSrc adds u16 count + count * 3 palette bytes) -- -> rgba8. keyed: index 255 transparent (Quake's Draw_TransPic), default true function Miptex.qpic(b, at, size, opts) if size < 8 or at < 0 or at + 8 > buffer.len(b) then return nil, "truncated qpic header" end local w, h = readu32(b, at), readu32(b, at + 4) if w == 0 or h == 0 then return nil, "empty qpic" end if w * h > (opts and opts.maxPixels or 2 ^ 24) then return nil, "limit: qpic " .. w .. " x " .. h end if 8 + w * h > size or at + 8 + w * h > buffer.len(b) then return nil, "truncated qpic pixels" end local own= nil if opts and opts.goldsrc then local p = 8 + w * h if p + 2 <= size then local n = buffer.readu16(b, at + p) if n > 0 and n <= 256 and p + 2 + n * 3 <= size then own = Pixels.palette(b, at + p + 2, n) end end end local pal = own or (opts and opts.palette) or Pixels.grey() local keyed = (opts and opts.keyed ~= nil and{opts.keyed }or{true })[1] if keyed then pal = Pixels.keyed(pal, 255) end local img = Types.Image.new(w, h) Pixels.indexed(b, at + 8, w, 8, img.pixels, w, h, true, pal) img.meta.source = { format = "qpic", palette = own ~= nil or (opts ~= nil and opts.palette ~= nil), keyed = keyed or nil } return img, nil end -- palette indices of an rgba8 image (nearest entry; alpha < 128 -> 255 when keyed and the image has any) and the -- palette used function Miptex.indices(img, palette, keyed) if keyed then local any = false for k = 0, img.width * img.height - 1 do if readu8(img.pixels, k * 4 + 3) < 128 then any = true break end end keyed = any end local colors = (palette and{(Pixels.colorList(palette) )}or{(Quantize.palette(img.pixels, img.width, img.height, keyed and 255 or 256) )})[1] local idx = Quantize.map(img.pixels, img.width, img.height, colors, { transparentIndex = keyed and palette and 255 or nil }) if keyed then for k = 0, img.width * img.height - 1 do if readu8(img.pixels, k * 4 + 3) < 128 then buffer.writeu8(idx, k, 255) end end end return idx, colors end -- an rgba8 image -> qpic bytes (goldsrc: with its palette, made by median cut when none is given) function Miptex.encodeQpic(img, palette, goldsrc, keyed) if not palette and not goldsrc then return nil, "a Quake qpic needs a palette" end local w, h = img.width, img.height local idx, colors = Miptex.indices(img, palette, keyed ~= false) local out = buffer.create(8 + w * h + (goldsrc and 2 + 768 or 0)) buffer.writeu32(out, 0, w) buffer.writeu32(out, 4, h) buffer.copy(out, 8, idx, 0, w * h) if goldsrc then local p = 8 + w * h buffer.writeu16(out, p, 256) for i = 0, 255 do local c = colors[i + 1] or { 0, 0, 0 } buffer.writeu8(out, p + 2 + i * 3, c[1]) buffer.writeu8(out, p + 3 + i * 3, c[2]) buffer.writeu8(out, p + 4 + i * 3, c[3]) end end return out, nil end return Miptex end __FILES["codecs/image/Pixels"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 -- codecs/image/Pixels: row loops between packed pixel layouts and rgba8 for BMP / DIB, and palette helpers. -- Indexed, BGR(A), 5-5-5, bit masks, RLE4 / RLE8; palettes: keyed index (Quake 255), grey ramp, Quake colormap light -- levels. From bmp-luau b86aed6 (same author); the encoder loops and palette helpers 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 = {} function Pixels.palette(src, base, n, bgr) local pal = buffer.create(1024) local m = (base >= 0 and{(math.clamp(math.min(n, math.floor((buffer.len(src) - base) / 3)), 0, 256) )}or{0 })[1] 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 function Pixels.indexed(src, base, stride, bpp, dst, w, h, topDown, pal) local mask = lshift(1, bpp) - 1 for r = 0, h - 1 do local so = base + r * stride local d = ((topDown and{r }or{(h - 1 - r)})[1]) * 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 = (band(x, 1) == 0 and{(rshift(b, 4) )}or{(band(b, 15) )})[1] 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 function Pixels.rgb555(src, base, stride, dst, w, h, topDown) for r = 0, h - 1 do local so = base + r * stride local d = ((topDown and{r }or{(h - 1 - r)})[1]) * 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, math.floor((cr * 255 + 15) / 31 )+ (math.floor((cg * 255 + 15) / 31)) * 256 + (math.floor((cb * 255 + 15) / 31)) * 65536 + 0xFF000000) end end end -- 24 bpp BI_RGB: B, G, R function Pixels.bgr24(src, base, stride, dst, w, h, topDown) for r = 0, h - 1 do local so = base + r * stride local d = ((topDown and{r }or{(h - 1 - r)})[1]) * 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) function Pixels.bgra32(src, base, stride, dst, w, h, topDown) local aor = 0 for r = 0, h - 1 do local so = base + r * stride local d = ((topDown and{r }or{(h - 1 - r)})[1]) * 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 function Pixels.masked(src, base, stride, bpp, dst, w, h, topDown, shr, mr, tr, shg, mg, tg, shb, mb, tb, sha, ma, ta) local bytes = rshift(bpp, 3) local aor = 0 for r = 0, h - 1 do local so = base + r * stride local d = ((topDown and{r }or{(h - 1 - r)})[1]) * 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 function Pixels.opaque(dst, n) 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 function Pixels.rle(src, pos, stop, rle4, dst, w, h, topDown, pal) local x, y = 0, 0 local written = 0 local row = (topDown and 0 or h - 1) * w * 4 local rowStep = (topDown and((w * 4 ))or((-w * 4 ))) while y < h and pos + 1 < stop do local n = readu8(src, pos) local v = readu8(src, pos + 1) pos =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, (band(i - x, 1) == 0 and{hi }or{lo})[1]) 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 =written+ (e - x ) end x =x+ n elseif v == 0 then -- end of line x = 0 y =y+ 1 row =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 =pos+ 2 x =x+ dx y =y+ dy row =row+ rowStep * dy else -- absolute run of v pixels, padded to a 16-bit boundary local nb = (rle4 and{(rshift(v + 1, 1) )}or{v })[1] 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 = (band(k, 1) == 0 and{(rshift(b, 4) )}or{(band(b, 15) )})[1] else idx = readu8(src, pos + k) end writeu32(dst, row + i * 4, readu32(pal, idx * 4)) end if e > x then written =written+ (e - x ) end x =x+ v pos =pos+ (nb + band(nb, 1) ) end end return written end function Pixels.encode24(src, w, h, dst, base, stride) 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 =d+ 3 end end end function Pixels.encode32(src, w, h, dst, base) 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 function Pixels.encode8(src, w, h, dst, base, stride, idx) 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 function Pixels.colours(src, n, max) local seen= {} local list= {} 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 -- a 256-entry rgba8 palette (u32 LE per entry) with entry i = { i, i, i, 255 } function Pixels.grey() local pal = buffer.create(1024) for i = 0, 255 do writeu32(pal, i * 4, 0xFF000000 + i * 0x10101) end return pal end -- a copy of a 1024-byte palette with entry index transparent (alpha 0, colour kept as Pillow does; Quake / GoldSrc: -- index 255 of sprites, qpics and '{' textures) function Pixels.keyed(pal, index) local out = buffer.create(1024) buffer.copy(out, 0, pal, 0, math.min(buffer.len(pal), 1024)) if index >= 0 and index < 256 then writeu8(out, index * 4 + 3, 0) end return out end -- palette (1024 bytes) -> { { r, g, b, a } } for codecs/image/Quantize function Pixels.colorList(pal, n) local out= {} for i = 0, math.clamp(n or 256, 0, math.floor(buffer.len(pal) / 4)) - 1 do out[i + 1] = { readu8(pal, i * 4), readu8(pal, i * 4 + 1), readu8(pal, i * 4 + 2), readu8(pal, i * 4 + 3) } end return out end -- Quake colormap.lmp: rows of 256 palette indices, row 0 brightest .. 63 darkest (32 = unlit); the palette for one -- light level, or nil past the end of the map function Pixels.colormap(pal, cmap, base, row) local o = base + row * 256 if row < 0 or base < 0 or o + 256 > buffer.len(cmap) then return nil end local out = buffer.create(1024) for i = 0, 255 do writeu32(out, i * 4, readu32(pal, readu8(cmap, o + i) * 4)) end return out end -- rgba8 palette (1024 bytes) -> 3 * n bytes R, G, B (the Quake / GoldSrc palette layout) function Pixels.paletteBytes(pal, n) local m = math.clamp(n or 256, 0, 256) local out = buffer.create(m * 3) for i = 0, m - 1 do writeu8(out, i * 3, readu8(pal, i * 4)) writeu8(out, i * 3 + 1, readu8(pal, i * 4 + 1)) writeu8(out, i * 3 + 2, readu8(pal, i * 4 + 2)) end return out end return Pixels end __FILES["codecs/image/Quantize"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --!native --!optimize 2 -- 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 = {} local BINS = 32768 -- 5 bits per channel local function count(pixels, n) -- 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 = (math.floor(r / 8)) * 1024 + (math.floor(g / 8)) * 32 + math.floor(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 local function mean(cnt, sums, bins, lo, hi) local n, r, g, b = 0, 0, 0, 0 for i = lo, hi do local bin = bins[i] n =n+ readu32(cnt, bin * 4) r =r+ readf64(sums, bin * 24) g =g+ readf64(sums, bin * 24 + 8) b =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 local function medianCut(cnt, sums, maxColors) local bins= {} 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= {} local function channel(bin, c) if c == 0 then return math.floor(bin / 1024 ) elseif c == 1 then return (math.floor(bin / 32)) % 32 end return bin % 32 end local function stats(box) local mins, maxs = { 31, 31, 31 }, { 0, 0, 0 } local n = 0 for i = box[1], box[2] do local bin = bins[i] n =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 local function scored(lo, hi) local c, range, n = stats({ lo, hi }) return { lo, hi, c, (hi > lo and((range * math.sqrt(n) ))or(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 __iter(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) ) 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 =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 =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) ) for i, box in __iter(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 local function octree(cnt, sums, maxColors) local child= {} -- node * 8 + k -> node (0 = none) local n= {} local sr, sg, sb= {}, {}, {} local leaf= {} local level= {} 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= { {}, {}, {}, {}, {} } 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 = math.floor(bin / 1024), (math.floor(bin / 32)) % 32, bin % 32 local node = 1 for lv = 0, 4 do local sh = 4 - lv local k = ((math.floor(r5 / 2 ^ sh)) % 2) * 4 + ((math.floor(g5 / 2 ^ sh)) % 2) * 2 + (math.floor(b5 / 2 ^ sh)) % 2 local slot = (node - 1) * 8 + k + 1 local nx = child[slot] if nx == 0 then nodes =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 =leaves+ 1 else table.insert(byLevel[lv + 2], nx) end end node = nx end n[node]=n[node]+ c sr[node]=sr[node]+ readf64(sums, bin * 24) sg[node]=sg[node]+ readf64(sums, bin * 24 + 8) sb[node]=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 local function fold(node) 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[node]+ n[ch] sr[node]=sr[node]+ sr[ch] sg[node]=sg[node]+ sg[ch] sb[node]=sb[node]+ sb[ch] child[slot] = 0 merged =merged+ 1 end end leaf[node] = true return merged - 1 end local function subtotal(node) local s = 0 for k = 1, 8 do local ch = child[(node - 1) * 8 + k] if ch ~= 0 then s =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) ) for i, node in __iter(list) do order[i] = { node, subtotal(node), i } end table.sort(order, function(a, b) if a[2] ~= b[2] then return a[2] < b[2] end return a[3] < b[3] end) for _, e in __iter(order) do if leaves <= maxColors then break end leaves =leaves- fold(e[1]) end end local pal= {} local function walk(node) 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 function Quantize.palette(pixels, w, h, maxColors, opts) 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= {} local exact= {} 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 function Quantize.map(pixels, w, h, palette, opts) 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, pg, pb, pi= {}, {}, {}, {} for i, c in __iter(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) ) for k = 1, np do order[k] = pg[k] * 65536 + k end table.sort(order) local r2, g2, b2, i2 = (table.create(np) ), (table.create(np) ), (table.create(np) ), (table.create(np) ) 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 =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= {} local function nearest(r, g, b) 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 =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 =down- 1 end end end cache[key] = best return best end local tbyte = (tidx and{(math.clamp(tidx, 0, 255) )}or{0 })[1] 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 function Quantize.quantize(pixels, w, h, maxColors, opts) 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"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --!native --!optimize 2 -- 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 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 }) function Raster.multiply(m, n) 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 function Raster.translate(tx, ty) return { 1, 0, 0, 1, tx, ty } end function Raster.scale(sx, sy) return { sx, 0, 0, sy or sx, 0, 0 } end function Raster.rotate(radians) local c, s = math.cos(radians), math.sin(radians) return { c, s, -s, c, 0, 0 } end function Raster.invert(m) 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 function Raster.apply(m, x, y) return m[1] * x + m[3] * y + m[5], m[2] * x + m[4] * y + m[6] end local Builder = {} Builder.__index = Builder function Raster.path() return setmetatable({ cmds = {} }, Builder) end function Builder.moveTo(self, x, y) table.insert(self.cmds, { op = "moveTo", x, y }) return self end function Builder.lineTo(self, x, y) table.insert(self.cmds, { op = "lineTo", x, y }) return self end function Builder.quadTo(self, cx, cy, x, y) table.insert(self.cmds, { op = "quadTo", cx, cy, x, y }) return self end function Builder.cubicTo(self, c1x, c1y, c2x, c2y, x, y) table.insert(self.cmds, { op = "cubicTo", c1x, c1y, c2x, c2y, x, y }) return self end function Builder.close(self) table.insert(self.cmds, { op = "close" } ) return self end function Builder.rect(self, x, y, w, h) return self:moveTo(x, y):lineTo(x + w, y):lineTo(x + w, y + h):lineTo(x, y + h):close() end function Builder.ellipse(self, cx, cy, rx, ry) 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 local function commands(path) if type(path) ~= "table" then return nil end if type(path.cmds) == "table" then return path.cmds end return path end local function operands(c, n) 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 local function flatten(path, transform, tolerance, minLen) local cmds = commands(path) local polys= {} 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= nil local px, py = 0, 0 local sx, sy = 0, 0 local bx0, by0, bx1, by1 = math.huge, math.huge, -math.huge, -math.huge local function point(x, y) local poly = cur 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 local function start(x, y) 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 __iter(cmds) do local op = (type(cmd) == "table" and{cmd.op }or{nil })[1] 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 = n ~= n and 1 or 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 = n ~= n and 1 or 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 function Raster.flatten(path, transform, tolerance) return flatten(path, transform, tolerance, 6) end -- the signed area each pixel gains from one edge (font-rs draw_line) local function line(acc, S, H, x0, y0, x1, y1) 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 =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 local function clampx(x, W) return x < 0 and 0 or(x > W and{W }or{x })[1]end local function edge(acc, S, W, H, x0, y0, x1, y1) 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 function Raster.mask(path, opts) local o= 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 ) > LIMIT or abs(by0 ) > LIMIT or abs(bx1 ) > LIMIT or abs(by1 ) > LIMIT then return nil, "coordinates out of range" end local X0, Y0, X1, Y1 = floor(bx0 ), floor(by0 ), ceil(bx1 ), ceil(by1 ) 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 = (type(o.maxPixels) == "number" and{o.maxPixels }or{(2 ^ 26 )})[1] if W * H > maxPixels then return nil, "limit" end local S = W + 2 local acc = bcreate(S * H * 4) for _, poly in __iter(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 =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 function Raster.fill(img, path, paint, opts) 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= table.clone(opts or {} ) 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 = (type(o.opacity) == "number" and{(math.clamp(o.opacity, 0, 1) )}or{1 })[1] local fn= 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 -- push a polygon (flat x, y list) as a closed subpath with positive orientation, so overlapping pieces add up -- under the nonzero rule local function polygon(out, pts) local n = #pts if n < 6 then return end local area = 0 for i = 1, n - 1, 2 do local j = i + 2 > n and 1 or i + 2 area =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" } ) end local function arcPoints(cx, cy, r, a0, a1, tol, pts) 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 function Raster.stroke(path, opts) local o= opts or {} local hw = ((type(o.width) == "number" and o.width > 0 and{o.width }or{1})[1]) / 2 local join = o.join or "miter" local cap = o.cap or "butt" local miterLimit = (type(o.miterLimit) == "number" and o.miterLimit >= 1 and{o.miterLimit }or{4 })[1] local tol = (type(o.tolerance) == "number" and o.tolerance > 0.0005 and{o.tolerance }or{0.1 })[1] local out= {} local cmds = commands(path) if not cmds then return out end -- subpaths with their closed flag (flatten loses it, so split here) local subs= {} local cur= nil local lx, ly = 0, 0 for _, c in __iter(cmds) do local op = (type(c) == "table" and{c.op }or{nil })[1] if op == "moveTo" and operands(c, 2) then cur = { c } table.insert(subs, { cmds = cur , 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 , closed = o.closed == true }) end table.insert(cur , c) end end for _, sub in __iter(subs) do local __DARKLUA_CONTINUE_18=false repeat 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 __DARKLUA_CONTINUE_18=true break end local p= { 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 = math.floor(#p / 2 ) if n < 2 then __DARKLUA_CONTINUE_18=true break end local segs = (closed and{n }or{(n - 1 )})[1] local dirs= {} 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 local function joinAt(k, s0, s1) 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 = cross < 0 and 1 or-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 =da- 2 * math.pi end while da < -math.pi do da =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 = (join == "miter" and{(1 / sqrt(max(1e-12, (1 + cosT) / 2)) )}or{math.huge })[1] 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 __iter({ { 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 __DARKLUA_CONTINUE_18=true until true if not __DARKLUA_CONTINUE_18 then break end end return out end return Raster end __FILES["codecs/image/Texel"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --!native --!optimize 2 -- 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 = {} 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= {} local function array(name, size, typ, order) FORMATS[name] = { bytes = size * #order, kind = "array", size = size, type = typ, order = order } end for _, o in __iter({ "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") local function packed(name, bytes, spec) local ch= {} 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 function Texel.masked(bytes, r, g, b, a, luminance) if bytes < 1 or bytes > 4 then return nil end local ch= {} for i, m in __iter({ r, g, b, a }) do if m ~= 0 then local shift = 0 while band(m, lshift(1, shift)) == 0 and shift < 31 do shift =shift+ 1 end local bits = 0 while shift + bits < 32 and band(m, lshift(1, shift + bits)) ~= 0 do bits =bits+ 1 end local name = (i == 1 and{(luminance and"l" or"r") }or{i == 2 and"g" or(i == 3 and"b" or"a" )})[1] 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 function Texel.size(fmt, w, h) local d = (type(fmt) == "string" and{FORMATS[fmt] }or{fmt })[1] if not d then return nil end return (d.kind == "pair" and(((math.floor((w + 1) / 2)) * 4 * h ))or((d.bytes * w * h )))end local function nativeOf(d) if d.kind == "array" then local t, s = d.type, d.size if t == "float" or t == "snorm" or t == "sint" or (t == "uint" and s > 1) then return "rgbaf32" end return s == 1 and"rgba8" or"rgba16" elseif d.kind == "packed" then local wide = false for _, c in __iter(d.channels) do wide = wide or c.bits > 8 end return wide and"rgba16" or"rgba8" end return "rgbaf32" end Texel.nativeOf = nativeOf local function uf11(v) local e, m = rshift(v, 6), band(v, 63) if e == 0 then return m / 64 * 2 ^ -14 elseif e == 31 then return (m == 0 and{math.huge }or{(0 / 0 )})[1] end return (1 + m / 64) * 2 ^ (e - 15) end local function uf10(v) local e, m = rshift(v, 5), band(v, 31) if e == 0 then return m / 32 * 2 ^ -14 elseif e == 31 then return (m == 0 and{math.huge }or{(0 / 0 )})[1] end return (1 + m / 32) * 2 ^ (e - 15) end local function component(src, q, size, typ) 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, math.floor((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 = (size == 2 and{HALF[readu16(src, q)] }or{(readf32(src, q) )})[1] local c = f ~= f and 0 or(f < 0 and 0 or(f > 1 and 1 or f )) return f, math.floor(c * 255 + 0.5) elseif typ == "uint" then local v = (size == 1 and{(readu8(src, q) )}or{(size == 2 and{(readu16(src, q) )}or{(readu32(src, q) )})[1]})[1] return v, math.min(v, 255) end local v = (size == 1 and{(readi8(src, q) )}or{(size == 2 and{(readi16(src, q) )}or{(readi32(src, q) )})[1]})[1] return v, math.clamp(v, 0, 255) end local function ycc(y, u, v, a) 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 local function yuv(d, src, offset, w, h, pitch, dst) 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 + (math.floor(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((odd and{b2 }or{b0})[1], b1, b3, 255)) elseif order == "uyvy" then writeu32(dst, n, ycc((odd and{b3 }or{b1})[1], b0, b2, 255)) elseif order == "rgbg" then writeu32(dst, n, b0 + ((odd and{b3 }or{b1})[1]) * 256 + b2 * 65536 + 0xFF000000) else writeu32(dst, n, b1 + ((odd and{b2 }or{b0})[1]) * 256 + b3 * 65536 + 0xFF000000) end end n =n+ 4 end end return dst end function Texel.decode(fmt, src, offset, w, h, native, rowPitch) local d = (type(fmt) == "string" and{FORMATS[fmt] }or{fmt })[1] if not d then return nil, "unsupported: unknown texel format " .. tostring(fmt) end local tb = d.bytes local rowBytes = (d.kind == "pair" and(((math.floor((w + 1) / 2)) * 4 ))or((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 = (native and d.kind ~= "pair" and d.kind ~= "ayuv" and{(nativeOf(d) )}or{"rgba8" })[1] local bpp = out == "rgba8" and 4 or(out == "rgba16" and 8 or 16 ) local dst = buffer.create(w * h * bpp) local n = 0 if d.kind == "array" then local order, size, typ = d.order , d.size , d.type 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 =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] = (c == "r" and{(nc == 1 and 4 or 0) }or{c == "g" and 1 or(c == "b" and 2 or(c == "a" and 3 or(c == "l" and 4 or-1 )))})[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 =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 =n+ bpp end end return dst, out elseif d.kind == "packed" then local chs = d.channels for y = 0, h - 1 do local s = offset + y * pitch for _ = 0, w - 1 do local v = (tb == 1 and{(readu8(src, s) )}or{(tb == 2 and{(readu16(src, s) )}or{(tb == 3 and{(readu16(src, s) + readu8(src, s + 2) * 65536 )}or{(readu32(src, s) )})[1]})[1]})[1] s =s+ tb local r, g, b, a = 0, 0, 0, 1 for _, c in __iter(chs) do local maxv = lshift(1, c.bits) - 1 local x = band(rshift(v, c.shift), maxv) / (c.bits >= 32 and 4294967295 or 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 =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 =s+ 4 local sc = (nine and{(2 ^ (rshift(v, 27) - 24) )}or{0 })[1] local r= (nine and{(band(v, 511) * sc )}or{(uf11(band(v, 2047)) )})[1] local g= (nine and{(band(rshift(v, 9), 511) * sc )}or{(uf11(band(rshift(v, 11), 2047)) )})[1] local b= (nine and{(band(rshift(v, 18), 511) * sc )}or{(uf10(rshift(v, 22)) )})[1] if out == "rgba8" then local function q(x) return (x ~= x or x <= 0 )and 0 or(x >= 1 and 255 or 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 =n+ bpp end end return dst, out end return Texel end __FILES["codecs/image/Texture"] = function() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict -- 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) 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, w, h) return Bcn.size(name, w, h) or Etc.size(name, w, h) or Texel.size(name, w, h) end function Texture.block(name) 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, src, offset, w, h, native) 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, (v ~= v or v <= 0 )and 0 or(v >= 1 and 255 or 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, wide and"rgba16" or"rgba8" end return Texel.decode(name, src, offset, w, h, native) end function Texture.image(px, pf, w, h) local img = Types.Image.new(0, 0, pf ) img.width, img.height, img.pixels = w, h, px return img end function Texture.assemble(list, layout) local first= nil local frames= {} local mips= {} for _, s in __iter(list) do if s.level == 0 then first = first or s.image local fr= { 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) local w, h = img.width, img.height local nw, nh = math.max(1, math.floor(w / 2)), math.max(1, math.floor(h / 2)) local fmt = img.format local out = Types.Image.new(nw, nh, fmt) local src, dst = img.pixels, out.pixels local cs = fmt == "rgba8" and 1 or(fmt == "rgba16" and 2 or 4 ) local function get(x, y, c) local o = ((math.min(y, h - 1) * w + math.min(x, w - 1)) * 4 + c) * cs return (cs == 1 and{(buffer.readu8(src, o) )}or{(cs == 2 and{(buffer.readu16(src, o) )}or{(buffer.readf32(src, o) )})[1]})[1] 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, n) 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 __FILES["codecs/image/Vp8"] = function() local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict -- 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 local function fail(msg, offset) 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, off, len) 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, off, len) 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 function Vp8.newDecoder() return setmetatable({ state = Decode.new() }, DecoderMeta) end function DecoderMeta.decodeFrame(self, buf, off, len, opts) 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 = (math.floor((f.width + 1) / 2)) * (math.floor((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) Decode.reset(self.state) end function Vp8.decodeFrame(buf, off, len, opts) return Vp8.newDecoder():decodeFrame(buf, off, len, opts) end function Vp8.decodePlanes(buf, off, len, opts) 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 = (math.floor((f.width + 1) / 2)) * (math.floor((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) local cw, ch = math.floor((img.width + 1) / 2), math.floor((img.height + 1) / 2 ) local ny = img.width * img.height return 0, ny, ny + cw * ch, cw, ch end function Vp8.toRgba(img, fancy) 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, u, v, w, h, fancy) return Yuv.toRgba(y, u, v, w, h, fancy ~= false) end Vp8.setAlpha = Yuv.setAlpha return Vp8 end __FILES["codecs/image/Vp8/Decode"] = function() local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict --!native --!optimize 2 -- 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. -- 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 =v* 2 s =s+ 1 end SHIFT[r + 1] = s end local function load(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 =br.bits+ 24 elseif p < br.limit then br.value = br.value * 256 + readu8(br.buf, p) br.pos = p + 1 br.bits =br.bits+ 8 elseif not br.eof then br.value =br.value* 256 br.bits =br.bits+ 8 br.eof = true else br.bits = 0 end end local function newBr(buf, off, len) 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 local function getBit(br, prob) 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 =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 local function getValue(br, n) local v = 0 for i = n - 1, 0, -1 do v =v+ getBit(br, 0x80) * 2 ^ i end return v end local function getSignedValue(br, n) local v = getValue(br, n) return (getBit(br, 0x80) == 1 and{(-v )}or{v })[1]end function Decode.new() 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 function Decode.reset(st) st.hasKey = false st.last, st.golden, st.alt = nil, nil, nil end function Decode.header(buf, off, len) 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 local function getLargeValue(br, P, p) 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 =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 __iter(CAT[cat + 1]) do v = v + v + getBit(br, pr) end v =v+ (3 + lshift(8, cat) ) end end return v end -- coefficients are dequantized to int16 as libwebp stores them, in raster order local function getCoeffs(br, P, t, ctx, dqDc, dqAc, n, out, o) 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 =pos+ 3 bits =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 =range- split value =value- lshift(split + 1, bits) else range = split + 1 end local sh = SHIFT[range + 1] range = lshift(range, sh) - 1 bits =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 =pos+ 3 bits =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 =range- split value =value- lshift(split + 1, bits) else range = split + 1 end local sh = SHIFT[range + 1] range = lshift(range, sh) - 1 bits =bits- sh if nonzero then break end n =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 =pos+ 3 bits =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 =range- split value =value- lshift(split + 1, bits) else range = split + 1 end local sh = SHIFT[range + 1] range = lshift(range, sh) - 1 bits =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 =pos+ 3 bits =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 =range- split value =value- lshift(split + 1, bits) else range = split + 1 end local sh = SHIFT[range + 1] range = lshift(range, sh) - 1 bits =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 =n+ 1 end br.value, br.bits, br.range, br.pos = value, bits, range, pos return 16 end local function nzCode(acc, nz, dcNz) return acc * 4 + (nz > 3 and 3 or(nz > 1 and 2 or 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) local function transformWHT(inp, out, o) 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, math.floor((a0 + a1) / 8)) writei16(out, base + 32, math.floor((a3 + a2) / 8)) writei16(out, base + 64, math.floor((a0 - a1) / 8)) writei16(out, base + 96, math.floor((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 local function clip8(v) return v < 0 and 0 or(v > 255 and 255 or v )end -- the inverse DCT of one block (libwebp TransformOne) added to dst local C1, C2 = 20091, 35468 local idctTmp = table.create(16, 0) local function mul1(a) return (math.floor((a * C1) / 65536)) + a end local function mul2(a) return math.floor((a * C2) / 65536 )end local function transformOne(c, o, b, dst) 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) + math.floor((a + d) / 8))) writeu8(b, row + 1, clip8(readu8(b, row + 1) + math.floor((bb + cc) / 8))) writeu8(b, row + 2, clip8(readu8(b, row + 2) + math.floor((bb - cc) / 8))) writeu8(b, row + 3, clip8(readu8(b, row + 3) + math.floor((a - d) / 8))) end end local function transformDC(c, o, b, dst) local dc = math.floor((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 local function doTransform(code, c, o, b, dst) if code >= 2 then transformOne(c, o, b, dst) elseif code == 1 then transformDC(c, o, b, dst) end end local function doUVTransform(bits, c, o, b, dst) 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) local function fill(b, dst, size, v) 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 local function trueMotion(b, dst, size) 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 local function predictBlock(b, dst, size, mode) local shift = size == 16 and 5 or 4 if mode == 0 then local dc = size for j = 0, size - 1 do dc =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 = math.floor(size / 2 ) for j = 0, size - 1 do dc =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 = math.floor(size / 2 ) for j = 0, size - 1 do dc =dc+ readu8(b, dst + j - BPS) end fill(b, dst, size, rshift(dc, shift - 1)) else fill(b, dst, size, 0x80) end end local function avg3(a, b, c) return rshift(a + 2 * b + c + 2, 2) end local function avg2(a, b) 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 local function predict4(b, dst, mode) if mode == 0 then local dc = 4 for i = 0, 3 do dc =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 local function checkMode(mbx, mby, mode) if mode == 0 then if mbx == 0 then return mby == 0 and 6 or 5 end return mby == 0 and 4 or 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) local function simpleFilter(b, p, step, along, thresh) 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) + (w < -128 and-128 or(w > 127 and 127 or 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, v < 0 and 0 or(v > 255 and 255 or v)) v = q0 - a1 writeu8(b, p, v < 0 and 0 or(v > 255 and 255 or v)) end p =p+ along end end -- the macroblock edge filter (FilterLoop26) local function filterEdge(b, p, hs, vs, size, thresh, it, hevT) 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) + (w < -128 and-128 or(w > 127 and 127 or 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, v < 0 and 0 or(v > 255 and 255 or v)) v = q0 - a1 writeu8(b, p, v < 0 and 0 or(v > 255 and 255 or 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, v < 0 and 0 or(v > 255 and 255 or v)) v = p1 + a2 writeu8(b, p - 2 * hs, v < 0 and 0 or(v > 255 and 255 or v)) v = p0 + a1 writeu8(b, p - hs, v < 0 and 0 or(v > 255 and 255 or v)) v = q0 - a1 writeu8(b, p, v < 0 and 0 or(v > 255 and 255 or v)) v = q1 - a2 writeu8(b, p + hs, v < 0 and 0 or(v > 255 and 255 or v)) v = q2 - a3 writeu8(b, p + 2 * hs, v < 0 and 0 or(v > 255 and 255 or v)) end end end end p =p+ vs end end -- the inner edge filter (FilterLoop24); nothing changes when q0 == p0 and p1 == q1 local function filterInner(b, p, hs, vs, size, thresh, it, hevT) 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 =a+ (w < -128 and-128 or(w > 127 and 127 or 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, v < 0 and 0 or(v > 255 and 255 or v)) v = q0 - a1 writeu8(b, p, v < 0 and 0 or(v > 255 and 255 or v)) if not hev then local a3 = rshift(a1 + 17, 1) - 8 v = p1 + a3 writeu8(b, p - 2 * hs, v < 0 and 0 or(v > 255 and 255 or v)) v = q1 - a3 writeu8(b, p + hs, v < 0 and 0 or(v > 255 and 255 or v)) end end end end p =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) local function readBMode(br, P, o) 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 getBit(br, P[o + 6]) == 0 and 4 or 5 elseif getBit(br, P[o + 7]) == 0 then return 6 elseif getBit(br, P[o + 8]) == 0 then return 7 end return getBit(br, P[o + 9]) == 0 and 8 or 9 end -- one motion vector component (libvpx read_mvcomponent) with the probabilities P[o + 1 .. o + 19], in quarter pixels local function readMvComponent(br, P, o) 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 =x+ getBit(br, P[o + 10 + i]) * lshift(1, i) end if x < 16 or getBit(br, P[o + 13]) == 1 then x =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 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 local function readInterMb(st, br, probIntra, probLast, probGf, mi, mbx, mby, 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 = getBit(br, P[3]) == 0 and 2 or 3 else ymode = getBit(br, P[4]) == 0 and 1 or 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] = getBit(br, U[3]) == 0 and 3 or 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]=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 =n+ 1 nr[n], nc[n] = r, c end cnt[n]=cnt[n]+ 2 else cnt[1]=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 =n+ 1 nr[n], nc[n] = r, c end cnt[n]=cnt[n]+ 1 else cnt[1]=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]=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 = cnt[2] >= cnt[1] and 2 or 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 = (miMode[a] == 9 and 2 or 0) + (miMode[l] == 9 and 2 or 0) + (miMode[al] == 9 and 1 or 0) if getBit(br, MODE_CTX[sc * 4 + 4]) == 0 then mode = 8 mvr =mvr+ readMvComponent(br, P, 0) * 2 mvc =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 = ((ar == 0 and ac == 0 and 4 or 0) + (lr == 0 and lc == 0 and 2 or 0) + (lr == ar and lc == ac and 1 or 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 local BORDER = Predict.BORDER local function newRef(mbw, mbh) 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 local function freeRef(st) for _, r in __iter(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 function Decode.cropTo(f, dy, oy, du, ou, dv, ov) local r = f.ref local w, h = f.width, f.height local cw, chh = math.floor((w + 1) / 2), math.floor((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 function Decode.decodeFrame(st, buf, off, len, maxPixels) 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 = math.floor((width + 15) / 16), math.floor((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 =p+ hdr.partitionLength left =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] = (getValue(br, 1) == 1 and{(getSignedValue(br, 7) )}or{0 })[1] end for s = 1, 4 do st.segFilter[s] = (getValue(br, 1) == 1 and{(getSignedValue(br, 6) )}or{0 })[1] end end if st.updateMap then for s = 1, 3 do st.segProba[s] = (getValue(br, 1) == 1 and{(getValue(br, 8) )}or{255 })[1] 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 = level == 0 and 0 or(simple and 1 or 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= {} 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 =partStart+ psize sizeLeft =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 = (getValue(br, 1) == 1 and{(getSignedValue(br, 4) )}or{0 })[1] local dqy2dc = (getValue(br, 1) == 1 and{(getSignedValue(br, 4) )}or{0 })[1] local dqy2ac = (getValue(br, 1) == 1 and{(getSignedValue(br, 4) )}or{0 })[1] local dquvdc = (getValue(br, 1) == 1 and{(getSignedValue(br, 4) )}or{0 })[1] local dquvac = (getValue(br, 1) == 1 and{(getSignedValue(br, 4) )}or{0 })[1] local quants= {} for s = 1, 4 do local q if st.useSegment then q = st.segQuant[s] if not st.absoluteDelta then q =q+ baseQ end else q = baseQ end local function cq(v, m) return v < 0 and 0 or(v > m and{m }or{v })[1] end local y2ac = math.floor((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 = refreshGolden and 0 or getValue(br, 2) copyToAlt = refreshAlt and 0 or 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= 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 = (useSkip and{(getValue(br, 8) )}or{0 })[1] 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] = x == 0 and 1 or x * 2 end end end local function fail(msg) 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 =base+ level end else base = level end for rf = 0, 3 do for m = 0, 3 do local lv = base if useLfDelta then lv =lv+ st.refLfDelta[rf + 1] if rf > 0 or m == 0 then lv =lv+ st.modeLfDelta[m + 1] end end lvlTab[s * 16 + rf * 4 + m + 1] = lv < 0 and 0 or(lv > 63 and 63 or lv ) end end end for lv = 1, 63 do local il = lv if sharpness > 0 then il = rshift(il, sharpness > 4 and 2 or 1) if il > 9 - sharpness then il = 9 - sharpness end end ilTab[lv] = il < 1 and 1 or il if key then hevTab[lv] = lv >= 40 and 2 or(lv >= 15 and 1 or 0 ) else hevTab[lv] = lv >= 40 and 3 or(lv >= 20 and 2 or(lv >= 15 and 1 or 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= {} local bil, full = hdr.profile > 0, hdr.profile == 3 if not key then local rl, rg, ra = st.last , st.golden , st.alt 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 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= { 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 __DARKLUA_CONTINUE_55=false repeat 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) __DARKLUA_CONTINUE_55=true break 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 = getBit(br, 128) == 1 and 1 or 3 else ymode = getBit(br, 163) == 1 and 2 or 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] = getBit(br, 183) == 1 and 1 or 3 end __DARKLUA_CONTINUE_55=true until true if not __DARKLUA_CONTINUE_55 then break 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 = nz > 0 and 1 or 0 topNzDc[x1] = dcNz leftNzDc = dcNz if nz > 1 then transformWHT(dcb, coeffs, co) else local dc0 = math.floor((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 = nz > first and 1 or 0 tnz = bor(rshift(tnz, 1), l * 128) acc = nzCode(acc, nz, readi16(coeffs, dst) ~= 0 and 1 or 0) dst =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 = nz > 0 and 1 or 0 tnz = bor(rshift(tnz, 1), l * 8) acc = nzCode(acc, nz, readi16(coeffs, dst) ~= 0 and 1 or 0) dst =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 = nzY == 0 and nzUv == 0 and dcNz == 0 and 1 or 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] = (i4 or skip == 0 )and 1 or 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 , 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 + (math.floor(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 + (math.floor(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 + (math.floor(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"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 -- 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) local function sixH(src, so, ss, dst, d, ds, w, h, f) 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, v < 0 and 0 or(v >= 32768 and 255 or rshift(v, 7))) end so =so+ ss d =d+ ds end end local function sixV(src, so, ss, dst, d, ds, w, h, f) 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, v < 0 and 0 or(v >= 32768 and 255 or rshift(v, 7))) end so =so+ ss d =d+ ds end end -- the bilinear filters: dst[i] = (src[i] * t0 + src[i + 1] * t1 + 64) >> 7 local function bilH(src, so, ss, dst, d, ds, w, h, f) 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 =so+ ss d =d+ ds end end local function bilV(src, so, ss, dst, d, ds, w, h, f) 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 =so+ ss d =d+ ds end end local function block(src, stride, base, wmax, hmax, x, y, mvx, mvy, w, h, dst, d, bil) local fx, fy = band(mvx, 7), band(mvy, 7) local px, py = x + math.floor((mvx - fx) / 8), y + math.floor((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 =so+ ss d =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 local function chroma16(v) -- the chroma vector of a whole macroblock: half the luma one, rounded away from zero if v < 0 then return -(math.floor((1 - v) / 2)) end return math.floor((v + 1) / 2 )end local function chroma4(s) -- 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 -(math.floor((4 - s) / 8)) end return math.floor((s + 4) / 8 )end function Predict.mb(ref, mbx, mby, mvr, mvc, part, subR, subC, sb, dst, yo, uo, vo, bil, full) 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 =cr- band(cr, 7) cc =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, (math.floor(q / 2)) * 8 local k = sb + by + math.floor(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, (math.floor(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 =cr- band(cr, 7) cc =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 function Predict.row(refs, mby, mbw, ref, part, miMvR, miMvC, miSubR, miSubC, mi0, pred, chunk, yo, uo, vo, bil, full) 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 local function extend(P, stride, base, w, h) 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 function Predict.extend(ref) 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() --!strict -- 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"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 -- 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 = {} local function clip(v) -- VP8Clip8: v in 14-bit fixed point if v >= 0 and v < 16384 then return rshift(v, 6) end return v < 0 and 0 or 255 end local function mulHi(v, c) return rshift(v * c, 8) end local function rgba(y, u, v) 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) local function upsamplePair(Y, U, V, ty, by, tu, cu, out, dt, db, len) 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 function Yuv.toRgba(Y, U, V, w, h, fancy, out) local o = out or bcreate(w * h * 4) local cw = math.floor((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 =cu+ cw y =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 = (math.floor(y / 2)) * cw local yo = y * w local oo = y * stride for x = 0, w - 1 do local c = cu + math.floor(x / 2 ) writeu32(o, oo + x * 4, rgba(readu8(Y, yo + x), readu8(U, c), readu8(V, c))) end end end return o end function Yuv.setAlpha(o, a, n) for i = 0, n - 1 do writeu8(o, i * 4 + 3, readu8(a, i)) end end return Yuv end __FILES["codecs/image/Vp8L"] = function() local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict -- 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, offset) 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, off, len) 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, off, len) 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, off, len, maxPixels) 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, off, len, maxPixels) 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 )), w, h, alpha end function Vp8L.decodeAlpha(buf, off, len, width, height) 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 function Vp8L.encode(rgba, width, height, opts) 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= opts or {} 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, width, height, opts) 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"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 -- 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 local function fill(d) 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 =d.over+ 1 end bitbuf =bitbuf+ lshift(b, bitcnt) bitcnt =bitcnt+ 8 end d.bitbuf, d.bitcnt = bitbuf, bitcnt end local function readBits(d, n) 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 =d.bitcnt- n return v end local function eos(d) return d.bitcnt < d.over * 8 end local count = table.create(MAX_LEN + 1, 0) local offset = table.create(MAX_LEN + 2, 0) local function ensure(d, n) local cap = math.floor(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 local function replicate(tab, at, step, size, entry) local e = size repeat e =e- step writeu32(tab, (at + e) * 4, entry) until e <= 0 end local function nextKey(key, len) local step = lshift(1, len - 1) while band(key, step) ~= 0 do step = rshift(step, 1) end return (step ~= 0 and{(band(key, step - 1) + step )}or{key })[1]end -- libwebp BuildHuffmanTable: complete codes only, except a single used symbol, which reads 0 bits; -1 when invalid local sorted = table.create(2400, 0) local function build(d, lens, n) 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 do local __DARKLUA_VAR=l + 1 count[__DARKLUA_VAR]=count[__DARKLUA_VAR]+ 1 end 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 do local __DARKLUA_VAR=l + 1 offset[__DARKLUA_VAR]=offset[__DARKLUA_VAR]+ 1 end end end local long = 0 for len = ROOT_BITS + 1, MAX_LEN do long =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 =numOpen* 2 numNodes =numNodes+ numOpen 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 =symbol+ 1 key = nextKey(key, len) do local __DARKLUA_VAR=len + 1 count[__DARKLUA_VAR]=count[__DARKLUA_VAR]- 1 end end step =step* 2 end step = 2 for len = ROOT_BITS + 1, MAX_LEN do numOpen =numOpen* 2 numNodes =numNodes+ numOpen 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 =tableAt+ tableSize -- NextTableBitSize local l2 = len local left = lshift(1, l2 - ROOT_BITS) while l2 < MAX_LEN do left =left- count[l2 + 1] if left <= 0 then break end l2 =l2+ 1 left =left* 2 end tableBits = l2 - ROOT_BITS tableSize = lshift(1, tableBits) totalSize =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 =symbol+ 1 key = nextKey(key, len) do local __DARKLUA_VAR=len + 1 count[__DARKLUA_VAR]=count[__DARKLUA_VAR]- 1 end end step =step* 2 end if numNodes ~= 2 * offset[MAX_LEN + 1] - 1 then return -1 end d.tabUsed = root + totalSize return root end local function readSymbol(d, at) 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 =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 =d.bitcnt- nb return rshift(e, 5) end local codeLengths = table.create(2400, 0) local clLens = table.create(19, 0) local function readCode(d, size) 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, first == 0 and 1 or 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 =maxSymbol- 1 local cl = readSymbol(d, clt) if cl < 16 then codeLengths[s + 1] = cl s =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 =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 local function subSample(size, bits) return rshift(size + lshift(1, bits) - 1, bits) end Decode.subSample = subSample local function cacheKey(argb, shift) -- (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 local function decodeData(d, data, w, h, cacheBits, groups, himg, hbits, hxs) local total = w * h local cache= (cacheBits > 0 and{(bcreate(lshift(1, cacheBits) * 4) )}or{nil })[1] local cshift = 32 - cacheBits local lenLimit = NUM_LITERAL + NUM_LENGTH local cacheLimit = lenLimit + ((cacheBits > 0 and{(lshift(1, cacheBits) )}or{0})[1]) local hmask = (himg and{(lshift(1, hbits) - 1 )}or{(-1 )})[1] local i, col, row = 0, 0, 0 local gG, gR, gB, gA, gD = groups[1], groups[2], groups[3], groups[4], groups[5] 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 =i+ 1 col =col+ 1 if col >= w then col = 0 row =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 =i+ length col =col+ length while col >= w do col =col- w row =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 =i+ 1 col =col+ 1 if col >= w then col = 0 row =row+ 1 end else return false, "bad symbol" end end if eos(d) then return false, "truncated: pixel data" end return true, nil end local function addPixels(a, b) return band(band(a, 0xff00ff00) + band(b, 0xff00ff00), 0xff00ff00) + band(band(a, 0x00ff00ff) + band(b, 0x00ff00ff), 0x00ff00ff) end Decode.addPixels = addPixels local function average2(a, b) return rshift(band(bxor(a, b), 0xfefefefe), 1) + band(a, b) end Decode.average2 = average2 local function clip255(v) return v < 0 and 0 or(v > 255 and 255 or v )end local function sub3(a, b, c) local pb, pa = b - c, a - c return ((pb < 0 and{(-pb )}or{pb})[1]) - ((pa < 0 and{(-pa )}or{pa})[1]) end -- select(T, L, TL) local function select3(a, b, c) 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 (s <= 0 and{a }or{b })[1]end local function clampedFull(c0, c1, c2) 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 local function half(a, b) local dd = a - b -- C division truncates toward zero local q = (dd >= 0 and{(rshift(dd, 1) )}or{(-rshift(-dd, 1) )})[1] return clip255(a + q) end local function clampedHalf(c0, c1, c2) 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 local function predict(mode, L, T, TR, TL) 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 local function inversePredictor(data, w, h, bits, sub) 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 local function sint8(v) return (v >= 128 and((v - 256 ))or(v ))end local function inverseCrossColor(data, w, h, bits, sub) 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) + (math.floor((g2r * g) / 32)), 255) local b = band(band(argb, 255) + (math.floor((g2b * g) / 32)) + (math.floor((r2b * sint8(r)) / 32)), 255) writeu32(data, k * 4, band(argb, 0xff00ff00) + r * 65536 + b) end x = xe end end end local function inverseSubtractGreen(data, n) 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 local function inverseColorIndexing(src, sw, w, h, bits, map) 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 =s+ 1 end writeu32(out, (o + x) * 4, readu32(map, band(packed, vmask) * 4)) packed = rshift(packed, bpp) end end return out end local decodeStream local function readCodes(d, xs, ys, cacheBits, level0) local himg= nil local hbits, hxs = 0, 0 local numGroups = 1 local mapping= 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) ) 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 =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) ) local cacheSize = (cacheBits > 0 and{(lshift(1, cacheBits) )}or{0 })[1] for i = 0, numMax - 1 do local slot = (mapping and{mapping[i + 1] }or{i })[1] local mark = d.tabUsed for j = 0, 4 do local size = (j == 0 and((NUM_LITERAL + NUM_LENGTH + cacheSize ))or((j == 4 and{NUM_DISTANCE }or{NUM_LITERAL })[1])) local at = readCode(d, size) if at < 0 then return nil, nil, 0, 0, eos(d) and"truncated: prefix code" or"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 = function(d, xs, ys, level0) local transforms= {} 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= { 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 = num > 16 and 0 or(num > 4 and 1 or(num > 2 and 2 or 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 ) elseif t.kind == 1 then inverseCrossColor(data, t.xsize, ys, t.bits, t.data ) 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 ) end end return data, nil end local function newState(buf, off, len, maxPixels) return { buf = buf, pos = off, limit = off + len, bitbuf = 0, bitcnt = 0, over = 0, tab = bcreate(4096 * 4), tabUsed = 0, maxPixels = maxPixels, } end function Decode.header(buf, off, len) 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 function Decode.argb(buf, off, len, maxPixels) 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 function Decode.stream(buf, off, len, w, h) local d = newState(buf, off, len, w * h) return decodeStream(d, w, h, true) end function Decode.toRgba(argb, n, out, outOff) 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 function Decode.green(argb, n) 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"] = function() local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict --!native --!optimize 2 -- 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 __iter(CODE_TO_PLANE) do PLANE_TO_CODE[v + 1] = i end local function newWriter(cap) return { buf = bcreate(math.max(64, cap)), pos = 0, acc = 0, cnt = 0 } end -- the n <= 24 low bits of v, LSB first local function put(w, v, n) 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 =pos+ 1 acc = (acc - byte) / 256 cnt =cnt- 8 until cnt < 8 w.pos = pos end w.acc, w.cnt = acc, cnt end local function finish(w) 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 local function subSample(size, bits) return rshift(size + lshift(1, bits) - 1, bits) end -- (0x1e35a7bd * v) mod 2^32: the colour cache hash before its shift local function mulHash(v) local lo = v % 65536 local hi = (v - lo) / 65536 return (lo * 0xa7bd + ((lo * 0x1e35 + hi * 0xa7bd) % 65536) * 65536) % 4294967296 end local function prefix(v) 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 =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 local function distCode(xs, dist) local yo = math.floor(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 local function subPixels(a, b) return band(bor(a, 0x00ff00ff) - band(b, 0xff00ff00), 0xff00ff00) + band(bor(a, 0xff00ff00) - band(b, 0x00ff00ff), 0x00ff00ff) end local function average2(a, b) return rshift(band(bxor(a, b), 0xfefefefe), 1) + band(a, b) end local function clip255(v) return v < 0 and 0 or(v > 255 and 255 or v )end local function sub3(a, b, c) local pb, pa = b - c, a - c return ((pb < 0 and{(-pb )}or{pb})[1]) - ((pa < 0 and{(-pa )}or{pa})[1]) end local function half(x, y) local dd = x - y return clip255(x + ((dd >= 0 and{(rshift(dd, 1) )}or{(-rshift(-dd, 1))})[1])) end local function predict(mode, L, T, TR, TL) 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 (s <= 0 and{T }or{L })[1] 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 local function residualCost(r) 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 } local function predictorTransform(px, w, h, bits, effort) local tw, th = subSample(w, bits), subSample(h, bits) local modesImg = bcreate(tw * th * 4) local modes = (effort <= 2 and{MODES_FAST }or{(effort <= 6 and{MODES_MID }or{MODES_ALL })[1]})[1] 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 __iter(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 =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 local function sint8(v) return (v >= 128 and((v - 256 ))or(v ))end local function clampM(v) local m = math.floor(v + 0.5) return m < -128 and-128 or(m > 127 and 127 or 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 local function crossColorTransform(px, w, h, bits) local tw, th = subSample(w, bits), subSample(h, bits) local img = bcreate(tw * th * 4) local ts = lshift(1, bits) local function tileCost(x0, y0, x1, y1, g2r, g2b, r2b) 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 - (math.floor((g2r * g) / 32)), 255) local nb = band(b - (math.floor((g2b * g) / 32)) - (math.floor((r2b * sint8(r)) / 32)), 255) c =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 =sgg+ g * g sgr =sgr+ g * r sgb =sgb+ g * b srr =srr+ r * r srb =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 - (math.floor((g2r * g) / 32)), 255) local nb = band(b - (math.floor((g2b * g) / 32)) - (math.floor((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 local function hash2(a, b) return rshift(mulHash(bxor(a, (b * 31) % 4294967296)), 32 - HASH_BITS) end local function matchLen(px, i, j, max) local n = 0 while n < max and readu32(px, (i + n) * 4) == readu32(px, (j + n) * 4) do n =n+ 1 end return n end local function lz77(px, xs, n, effort) local L= {} local D= {} 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 = effort <= 2 and 4 or(effort <= 5 and 16 or(effort <= 7 and 48 or 128 )) local function insert(i) 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 local function best(i) local max = math.min(MAX_LENGTH, n - i) if max < 2 then return 0, 0 end local bl, bd, bc = 0, 0, math.huge local function try(j) 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 =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 =k+ 1 L[k] = readu32(px, i * 4) D[k] = 0 i =i+ 1 haveNext = true else k =k+ 1 L[k] = -l D[k] = distCode(xs, d) for t = i + 1, i + l - 1 do insert(t) end i =i+ l end elseif l >= 2 then k =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 =k+ 1 L[k] = readu32(px, i * 4) D[k] = 0 i =i+ 1 end end return L, D end local function entropy(h) local total = 0 for _, c in __iter(h) do total =total+ c end if total == 0 then return 0 end local bits = 0 local lt = log(total) for _, c in __iter(h) do if c > 0 then bits =bits+ c * (lt - log(c)) end end return bits / log(2) end local function chooseCache(px, L, effort) if effort < 2 then return 0 end local cands = effort < 5 and{ 0, 4, 7, 10 } or{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 } local caches= {} local hg= {} local hr= {} local hb= {} local ha= {} for c, bits in __iter(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 __iter(L) do if t >= 0 then local hsh = mulHash(t) for c, bits in __iter(cands) do local cache = caches[c] local key = (bits > 0 and{(rshift(hsh, 32 - bits) )}or{0 })[1] if bits > 0 and cache[key + 1] == t then do local __DARKLUA_VAR, __DARKLUA_VAR0= hg[c], 257 + key __DARKLUA_VAR[__DARKLUA_VAR0]=__DARKLUA_VAR[__DARKLUA_VAR0]+ 1 end else do local __DARKLUA_VAR, __DARKLUA_VAR0= hg[c], band(rshift(t, 8), 255) + 1 __DARKLUA_VAR[__DARKLUA_VAR0]=__DARKLUA_VAR[__DARKLUA_VAR0]+ 1 end do local __DARKLUA_VAR1, __DARKLUA_VAR2= hr[c], band(rshift(t, 16), 255) + 1 __DARKLUA_VAR1[__DARKLUA_VAR2]=__DARKLUA_VAR1[__DARKLUA_VAR2]+ 1 end do local __DARKLUA_VAR3, __DARKLUA_VAR4= hb[c], band(t, 255) + 1 __DARKLUA_VAR3[__DARKLUA_VAR4]=__DARKLUA_VAR3[__DARKLUA_VAR4]+ 1 end do local __DARKLUA_VAR5, __DARKLUA_VAR6= ha[c], rshift(t, 24) + 1 __DARKLUA_VAR5[__DARKLUA_VAR6]=__DARKLUA_VAR5[__DARKLUA_VAR6]+ 1 end end if bits > 0 then cache[key + 1] = t end end pos =pos+ 1 else for p = pos, pos - t - 1 do local v = readu32(px, p * 4) local hsh = mulHash(v) for c, bits in __iter(cands) do if bits > 0 then caches[c][rshift(hsh, 32 - bits) + 1] = v end end end pos =pos- t end end local bestBits, bestCost = 0, math.huge for c, bits in __iter(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 local function buildCode(freqs, maxLen) local lens = Huffman.lengths(freqs, maxLen) local used = 0 for _, l in __iter(lens) do if l > 0 then used =used+ 1 end end local codes = Huffman.codes(lens) for i, l in __iter(lens) do if l > 0 then codes[i] = Huffman.reverse(codes[i], l) end end return { lens = lens, codes = codes, single = used <= 1 } end local function emit(w, c, sym) if not c.single then put(w, c.codes[sym + 1], c.lens[sym + 1]) end end local function zeroRun(tok, ext, run) 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 =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 =r- 1 end end end local function writeCode(w, c, size) local syms= {} 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= {} local ext= {} 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 =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 =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 =r- k else table.insert(tok, l) table.insert(ext, 0) r =r- 1 end end keep = #tok end s =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 do local __DARKLUA_VAR=tok[i] + 1 hist[__DARKLUA_VAR]=hist[__DARKLUA_VAR]+ 1 end 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 =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 =nbits+ 1 end local pairs = math.max(1, math.floor((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 local function writeImage(w, px, xs, n, effort, level0) local L, D = lz77(px, xs, n, effort) local cacheBits = (level0 and{(chooseCache(px, L, effort) )}or{0 })[1] 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 = (cacheBits > 0 and{(lshift(1, cacheBits) )}or{0 })[1] 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= (cacheBits > 0 and{(table.create(cacheSize, -1) )}or{nil })[1] local K = table.create(#L, 0) local pos = 0 for i, t in __iter(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 do local __DARKLUA_VAR=NUM_LITERAL + NUM_LENGTH + key + 1 hg[__DARKLUA_VAR]=hg[__DARKLUA_VAR]+ 1 end end cache[key + 1] = t end if hit then K[i] = 1 else do local __DARKLUA_VAR=band(rshift(t, 8), 255) + 1 hg[__DARKLUA_VAR]=hg[__DARKLUA_VAR]+ 1 end do local __DARKLUA_VAR0=band(rshift(t, 16), 255) + 1 hr[__DARKLUA_VAR0]=hr[__DARKLUA_VAR0]+ 1 end do local __DARKLUA_VAR1=band(t, 255) + 1 hb[__DARKLUA_VAR1]=hb[__DARKLUA_VAR1]+ 1 end do local __DARKLUA_VAR2=rshift(t, 24) + 1 ha[__DARKLUA_VAR2]=ha[__DARKLUA_VAR2]+ 1 end end pos =pos+ 1 else K[i] = 2 do local __DARKLUA_VAR=NUM_LITERAL + prefix(-t) + 1 hg[__DARKLUA_VAR]=hg[__DARKLUA_VAR]+ 1 end do local __DARKLUA_VAR0=prefix(D[i]) + 1 hd[__DARKLUA_VAR0]=hd[__DARKLUA_VAR0]+ 1 end 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 =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 __iter(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 local function toArgb(rgba, n, exact) 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 local function palette(px, n) local seen= {} local list= {} 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 local function stream(px, w, h, effort, cfg, bw) 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 = num > 16 and 0 or(num > 4 and 1 or(num > 2 and 2 or 3 )) put(bw, 1, 1) put(bw, 3, 2) put(bw, num - 1, 8) local pimg = bcreate(num * 4) local prevc = 0 local index= {} for i, c in __iter(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 =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 function Encode.encode(rgba, w, h, effort, exact, alphaHint, headerless) local n = w * h local px, usesAlpha = toArgb(rgba, n, exact) local pal = (effort > 0 and{(palette(px, n) )}or{nil })[1] local configs= {} if effort == 0 then table.insert(configs, { palette = nil, pbits = 0, cc = false, ccbits = 0 }) else local pbits = effort >= 5 and 4 or 5 local plain= { palette = nil, pbits = pbits, cc = effort >= 3, ccbits = effort >= 6 and 4 or 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= nil for k, cfg in __iter(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 = (alphaHint == nil and{usesAlpha }or{alphaHint })[1] put(bw, hint and 1 or 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 end return Encode end __FILES["codecs/image/Yuv"] = function() local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict --!native --!optimize 2 -- 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= { bt601 = { kr = 0.299, kb = 0.114 }, bt709 = { kr = 0.2126, kb = 0.0722 }, } local cache= {} local function coeffs(range, matrix) 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 = full and 1 or 255 / 219 local cs = full and 1 or 255 / 224 c = { ys = floor(ys * 65536 + 0.5), yo = full and 0 or 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 function Yuv.toRgba(src, w, h, uo, vo, cw, range, matrix, out) 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 = math.floor((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 = (math.floor(y / 2)) * cw local o = yrow * 4 for x = 0, w - 1, 2 do local ci = crow + (math.floor(x / 2)) local u = readu8(src, uo + ci) - 128 local v = readu8(src, vo + ci) - 128 local rv = math.floor((crv * v + 32768) / 65536 ) local gv = math.floor((cgu * u + cgv * v + 32768) / 65536 ) local bu = math.floor((cbu * u + 32768) / 65536 ) local yy = math.floor((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 = math.floor((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 =o+ 8 end end return dst end function Yuv.fromRgba(src, w, h, range, matrix, out) local cw, ch = math.floor((w + 1) / 2), math.floor((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 = full and 1 or 219 / 255 local csc = full and 1 or 224 / 255 local yof = full and 0.5 or 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, math.floor((yr * r + yg * g + yb * b + yoff) / 65536 )+ 1024)) end for cy = 0, ch - 1 do local y0 = cy * 2 local y1 = (y0 + 1 < h and((y0 + 1 ))or(y0 )) for cx = 0, cw - 1 do local x0 = cx * 2 local x1 = (x0 + 1 < w and((x0 + 1 ))or(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, math.floor((ur * r + ug * g + ub * b + coff4) / 262144 )+ 1024)) writeu8(dst, vo + i, readu8(CLIP, math.floor((vr * r + vg * g + vb * b + coff4) / 262144 )+ 1024)) end end return dst end local function info(img) 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 function Yuv.planes(w, h) local cw, ch = math.floor((w + 1) / 2), math.floor((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 function Yuv.toFullRange(img) 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 function Yuv.imageToRgba(img) 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 function Yuv.imageFromRgba(img, range, matrix) 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 local function scalePlane(src, so, sw, sh, dst, d0, dw, dh) 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 = (y0 < sh - 1 and((y0 + 1 ))or(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 = (x0 < sw - 1 and((x0 + 1 ))or(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, math.floor((a * (256 - wy) + b * wy + 32768) / 65536)) end end end function Yuv.scale(src, w, h, width, height, out) local dw= math.max(1, floor(width)) local dh= math.max(1, floor(height)) local cw= math.floor((w + 1) / 2 ) local ch= math.floor((h + 1) / 2 ) local dcw= math.floor((dw + 1) / 2 ) local dch= math.floor((dh + 1) / 2 ) local size = dw * dh + 2 * dcw * dch local dst = (out and buffer.len(out) >= size and{out }or{(bcreate(size) )})[1] 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 function Yuv.imageScale(img, dw, dh) 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/Brush"] = function() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict --!native --!optimize 2 -- codecs/model/Brush: convex plane brushes -> polygons and Scene primitives, with Quake-family texture projection. -- As qbsp (Quake / ericw-tools; no code taken): a big square on every plane (inside n . p <= d) clipped by the others. -- Projections: Quake standard (TextureAxisFromPlane + rotate / scale / shift), Valve 220 (explicit U / V axes), Quake -- III brush primitives (q3map2 ComputeAxisBase + 2 x 3 matrix). Options: merge coplanar faces with one projection -- (qbsp TryMerge), drop face parts inside / touching other brushes (qbsp CSGFaces; earlier brushes win coplanar ties). local Types = __include("Types") local Brush = {} local abs, sqrt, floor, sin, cos, atan2, min, max = math.abs, math.sqrt, math.floor, math.sin, math.cos, math.atan2, math.min, math.max local writef32, writeu32 = buffer.writef32, buffer.writeu32 -- TextureAxisFromPlane's baseaxis table (normal, s axis, t axis per row): floor, ceiling, west, east, south, north local BASEAXIS = { { 0, 0, 1 }, { 1, 0, 0 }, { 0, -1, 0 }, { 0, 0, -1 }, { 1, 0, 0 }, { 0, -1, 0 }, { 1, 0, 0 }, { 0, 1, 0 }, { 0, 0, -1 }, { -1, 0, 0 }, { 0, 1, 0 }, { 0, 0, -1 }, { 0, 1, 0 }, { 1, 0, 0 }, { 0, 0, -1 }, { 0, -1, 0 }, { 1, 0, 0 }, { 0, 0, -1 }, } local function snap(x) local r = floor(x + 0.5) return (abs(x - r) < 1e-6 and{r }or{x })[1]end -- qbsp PlaneFromPoints: normal = (p1 - p2) x (p3 - p2), the brush lies behind it; nil when the points are colinear function Brush.planeFromPoints(a, b, c) local ux, uy, uz = a[1] - b[1], a[2] - b[2], a[3] - b[3] local vx, vy, vz = c[1] - b[1], c[2] - b[2], c[3] - b[3] local nx, ny, nz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx local l = sqrt(nx * nx + ny * ny + nz * nz) if l < 1e-12 then return nil end nx, ny, nz = nx / l, ny / l, nz / l return { nx, ny, nz, b[1] * nx + b[2] * ny + b[3] * nz } end -- the base axis row (0..5) of TextureAxisFromPlane: the first with the largest dot product (strictly greater) function Brush.baseAxis(n) local best, axis = 0, 0 for i = 0, 5 do local a = BASEAXIS[i * 3 + 1] local d = n[1] * a[1] + n[2] * a[2] + n[3] * a[3] if d > best then best, axis = d, i end end return axis end -- Quake standard texture vectors (texels): offsets, rotation (degrees), scales (0 = 1) function Brush.quakeVecs(n, xoff, yoff, rot, xscale, yscale) local axis = Brush.baseAxis(n) local s0, t0 = BASEAXIS[axis * 3 + 2], BASEAXIS[axis * 3 + 3] local vecs = { { s0[1], s0[2], s0[3] }, { t0[1], t0[2], t0[3] } } local sinv, cosv if rot == 0 then sinv, cosv = 0, 1 elseif rot == 90 then sinv, cosv = 1, 0 elseif rot == 180 then sinv, cosv = 0, -1 elseif rot == 270 then sinv, cosv = -1, 0 else local ang = rot / 180 * math.pi sinv, cosv = sin(ang), cos(ang) end local sv = vecs[1][1] ~= 0 and 1 or(vecs[1][2] ~= 0 and 2 or 3 ) local tv = vecs[2][1] ~= 0 and 1 or(vecs[2][2] ~= 0 and 2 or 3 ) for i = 1, 2 do local v = vecs[i] local ns = cosv * v[sv] - sinv * v[tv] local nt = sinv * v[sv] + cosv * v[tv] v[sv], v[tv] = ns, nt end local sc = { xscale == 0 and 1 or xscale, yscale == 0 and 1 or yscale } for i = 1, 2 do local v = vecs[i] v[1], v[2], v[3] = v[1] / sc[i], v[2] / sc[i], v[3] / sc[i] end vecs[1][4], vecs[2][4] = xoff, yoff return vecs end -- Valve 220: u / v = axis (x, y, z, offset); the rotation is already in the axes function Brush.valveVecs(u, v, xscale, yscale) local su, sv = xscale == 0 and 1 or xscale, yscale == 0 and 1 or yscale return { { u[1] / su, u[2] / su, u[3] / su, u[4] }, { v[1] / sv, v[2] / sv, v[3] / sv, v[4] } } end -- q3map2 ComputeAxisBase: the texture plane axes of a brush-primitive face function Brush.axisBase(normal) local nx, ny, nz = normal[1], normal[2], normal[3] nx = abs(nx) < 1e-6 and 0 or nx ny = abs(ny) < 1e-6 and 0 or ny nz = abs(nz) < 1e-6 and 0 or nz local rotY = -atan2(nz, sqrt(ny * ny + nx * nx)) local rotZ = atan2(ny, nx) return { -sin(rotZ), cos(rotZ), 0 }, { -sin(rotY) * cos(rotZ), -sin(rotY) * sin(rotZ), -cos(rotY) } end -- brush primitives -> texel vectors for a w x h texture (ericw-tools SetTexinfo_BrushPrimitives) function Brush.bpVecs(normal, m, w, h) local tx, ty = Brush.axisBase(normal) local out = {} for i, size in __iter({ w, h }) do local r = m[i] out[i] = { size * (tx[1] * r[1] + ty[1] * r[2]), size * (tx[2] * r[1] + ty[2] * r[2]), size * (tx[3] * r[1] + ty[3] * r[2]), size * r[3] } end return out end -- texel vectors -> brush primitives (the inverse of bpVecs for vectors lying in the face plane) function Brush.vecsToBp(normal, vecs, w, h) local tx, ty = Brush.axisBase(normal) local out = {} for i, size in __iter({ w, h }) do local v = vecs[i] out[i] = { (v[1] * tx[1] + v[2] * tx[2] + v[3] * tx[3]) / size, (v[1] * ty[1] + v[2] * ty[2] + v[3] * ty[3]) / size, v[4] / size, } end return out end -- texture coordinates of a point on a face, in texture widths / heights (glTF uv: t grows down the image) function Brush.uv(face, x, y, z, w, h) local bp = face.bp if bp then local tx, ty = Brush.axisBase(face.plane) local a = x * tx[1] + y * tx[2] + z * tx[3] local b = x * ty[1] + y * ty[2] + z * ty[3] return bp[1][1] * a + bp[1][2] * b + bp[1][3], bp[2][1] * a + bp[2][2] * b + bp[2][3] end local v = face.vecs if v then local s, t = v[1], v[2] return (x * s[1] + y * s[2] + z * s[3] + s[4]) / w, (x * t[1] + y * t[2] + z * t[3] + t[4]) / h end return 0, 0 end -- qbsp BaseWindingForPlane: a square of half size `size` on the plane, counter-clockwise seen from the front function Brush.baseWinding(p, size) local nx, ny, nz, d = p[1], p[2], p[3], p[4] local ax, ay, az = abs(nx), abs(ny), abs(nz) local ux, uy, uz = 0, 0, 1 if az >= ax and az >= ay then ux, uy, uz = 1, 0, 0 end local dv = ux * nx + uy * ny + uz * nz ux, uy, uz = ux - dv * nx, uy - dv * ny, uz - dv * nz local l = sqrt(ux * ux + uy * uy + uz * uz) ux, uy, uz = ux / l * size, uy / l * size, uz / l * size -- right = up x n, so right x up = n: right -> up turns counter-clockwise about n local rx, ry, rz = (uy * nz - uz * ny), (uz * nx - ux * nz), (ux * ny - uy * nx) local ox, oy, oz = nx * d, ny * d, nz * d return { ox - rx - ux, oy - ry - uy, oz - rz - uz, ox + rx - ux, oy + ry - uy, oz + rz - uz, ox + rx + ux, oy + ry + uy, oz + rz + uz, ox - rx + ux, oy - ry + uy, oz - rz + uz, } end -- splits a polygon by a plane: the parts in front and behind (nil when empty), and whether it lies on the plane function Brush.split(pts, p, eps) local n = math.floor(#pts / 3 ) local nx, ny, nz, d = p[1], p[2], p[3], p[4] local dist = (table.create(n, 0) ) local side = (table.create(n, 0) ) local front, back = 0, 0 for i = 0, n - 1 do local v = pts[i * 3 + 1] * nx + pts[i * 3 + 2] * ny + pts[i * 3 + 3] * nz - d dist[i + 1] = v if v > eps then side[i + 1] = 1 front =front+ 1 elseif v < -eps then side[i + 1] = -1 back =back+ 1 end end if front == 0 and back == 0 then return nil, nil, true end if front == 0 then return nil, pts, false end if back == 0 then return pts, nil, false end local f, b= {}, {} for i = 0, n - 1 do local j = (i + 1) % n local x, y, z = pts[i * 3 + 1], pts[i * 3 + 2], pts[i * 3 + 3] local si = side[i + 1] if si >= 0 then f[#f + 1], f[#f + 2], f[#f + 3] = x, y, z end if si <= 0 then b[#b + 1], b[#b + 2], b[#b + 3] = x, y, z end local sj = side[j + 1] if si ~= 0 and sj ~= 0 and si ~= sj then local t = dist[i + 1] / (dist[i + 1] - dist[j + 1]) local mx, my, mz = x + t * (pts[j * 3 + 1] - x), y + t * (pts[j * 3 + 2] - y), z + t * (pts[j * 3 + 3] - z) -- exact on axis-aligned planes, as qbsp if nx == 1 then mx = d elseif nx == -1 then mx = -d end if ny == 1 then my = d elseif ny == -1 then my = -d end if nz == 1 then mz = d elseif nz == -1 then mz = -d end f[#f + 1], f[#f + 2], f[#f + 3] = mx, my, mz b[#b + 1], b[#b + 2], b[#b + 3] = mx, my, mz end end return ((#f >= 9 and{f }or{nil})[1]), ((#b >= 9 and{b }or{nil})[1]), false end -- removes repeated and colinear corners; nil when fewer than 3 remain local function clean(pts, eps) local out= {} local n = math.floor(#pts / 3 ) for i = 0, n - 1 do local x, y, z = snap(pts[i * 3 + 1]), snap(pts[i * 3 + 2]), snap(pts[i * 3 + 3]) local m = #out if m < 3 or abs(out[m - 2] - x) > eps or abs(out[m - 1] - y) > eps or abs(out[m] - z) > eps then out[m + 1], out[m + 2], out[m + 3] = x, y, z end end while #out >= 6 and abs(out[1] - out[#out - 2]) <= eps and abs(out[2] - out[#out - 1]) <= eps and abs(out[3] - out[#out]) <= eps do out[#out], out[#out - 1], out[#out - 2] = nil, nil, nil end -- colinear corners local changed = true while changed and #out >= 9 do changed = false local k = math.floor(#out / 3 ) for i = 0, k - 1 do local a, b, c = ((i + k - 1) % k) * 3, i * 3, ((i + 1) % k) * 3 local ux, uy, uz = out[b + 1] - out[a + 1], out[b + 2] - out[a + 2], out[b + 3] - out[a + 3] local vx, vy, vz = out[c + 1] - out[b + 1], out[c + 2] - out[b + 2], out[c + 3] - out[b + 3] local cx, cy, cz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx local lu, lv = sqrt(ux * ux + uy * uy + uz * uz), sqrt(vx * vx + vy * vy + vz * vz) if lu * lv == 0 or sqrt(cx * cx + cy * cy + cz * cz) <= 1e-9 * lu * lv then table.remove(out, b + 3) table.remove(out, b + 2) table.remove(out, b + 1) changed = true break end end end return (#out >= 9 and{out }or{nil })[1]end local function samePlane(a, b, eps) return abs(a[1] - b[1]) < 1e-5 and abs(a[2] - b[2]) < 1e-5 and abs(a[3] - b[3]) < 1e-5 and abs(a[4] - b[4]) < eps end local function oppositePlane(a, b, eps) return abs(a[1] + b[1]) < 1e-5 and abs(a[2] + b[2]) < 1e-5 and abs(a[3] + b[3]) < 1e-5 and abs(a[4] + b[4]) < eps end -- one polygon per plane of a convex brush (nil for planes clipped away or repeating an earlier plane) function Brush.windings(planes, opts) local eps = opts and opts.epsilon or 1e-3 local size = opts and opts.size or 2 ^ 17 local out= {} for i, p in __iter(planes) do local w= Brush.baseWinding(p, size) for j, q in __iter(planes) do if not w then break end if j ~= i then if samePlane(p, q, eps) then if j < i then w = nil end else local _, back, on = Brush.split(w, q, eps) w = (on and{nil }or{back })[1] end end end out[i] = (w and{(clean(w, eps) )}or{nil })[1] end return out end local function bounds(polys) local b = { math.huge, math.huge, math.huge, -math.huge, -math.huge, -math.huge } for _, p in __iter(polys) do local pts = p.points for k = 0, math.floor(#pts / 3 )- 1 do for c = 1, 3 do local v = pts[k * 3 + c] b[c] = min(b[c], v) b[c + 3] = max(b[c + 3], v) end end end return b end -- the parts of pts (on plane `own` of brush a) outside brush b local function outside(pts, own, a, b, planes, eps) local kept= {} local inside= pts for _, q in __iter(planes) do if not inside then break end if samePlane(own, q, eps) then if a < b then return { pts } end elseif not oppositePlane(own, q, eps) then local front, back = Brush.split(inside, q, eps) if front then table.insert(kept, front) end inside = back end end return kept end local function faceKey(f) local parts = { f.texture or "" } for _, m in __iter({ f.vecs, f.bp }) do if m then for _, row in __iter(m) do for _, v in __iter(row) do table.insert(parts, string.format("%.6g", v)) end end end end return table.concat(parts, " ") end local function convex(pts, n, eps) local k = math.floor(#pts / 3 ) for i = 0, k - 1 do local a, b, c = ((i + k - 1) % k) * 3, i * 3, ((i + 1) % k) * 3 local ux, uy, uz = pts[b + 1] - pts[a + 1], pts[b + 2] - pts[a + 2], pts[b + 3] - pts[a + 3] local vx, vy, vz = pts[c + 1] - pts[b + 1], pts[c + 2] - pts[b + 2], pts[c + 3] - pts[b + 3] local cx, cy, cz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx local lu, lv = sqrt(ux * ux + uy * uy + uz * uz), sqrt(vx * vx + vy * vy + vz * vz) if (cx * n[1] + cy * n[2] + cz * n[3]) < -eps * max(lu, lv, 1) then return false end end return true end -- qbsp TryMerge: two polygons sharing an edge (in opposite directions) -> their union, when convex local function tryMerge(f1, f2, n, eps) local n1, n2 = math.floor(#f1 / 3), math.floor(#f2 / 3 ) for i = 0, n1 - 1 do local i2 = (i + 1) % n1 for j = 0, n2 - 1 do local j2 = (j + 1) % n2 local match = true for c = 1, 3 do if abs(f1[i * 3 + c] - f2[j2 * 3 + c]) > eps or abs(f1[i2 * 3 + c] - f2[j * 3 + c]) > eps then match = false break end end if match then local out= {} for k = 0, n1 - 1 do local s = ((i2 + k) % n1) * 3 out[#out + 1], out[#out + 2], out[#out + 3] = f1[s + 1], f1[s + 2], f1[s + 3] end for k = 2, n2 - 1 do local s = ((j + k) % n2) * 3 out[#out + 1], out[#out + 2], out[#out + 3] = f2[s + 1], f2[s + 2], f2[s + 3] end local c = clean(out, eps) if c and convex(c, n, eps) then return c end return nil end end end return nil end local function mergeAll(polys, faces, eps) local groups= {} local order= {} for _, p in __iter(polys) do local f = faces[p.brush][p.face] local pl = f.plane local key = string.format("%.5f %.5f %.5f %.3f|", pl[1], pl[2], pl[3], pl[4]) .. faceKey(f) local g = groups[key] if not g then g = {} groups[key] = g table.insert(order, key) end table.insert(g, p) end local out= {} for _, key in __iter(order) do local g = groups[key] local changed = true while changed do changed = false for a = 1, #g do for b = a + 1, #g do local m = tryMerge(g[a].points, g[b].points, g[a].normal, eps) if m then g[a] = { brush = g[a].brush, face = g[a].face, points = m, normal = g[a].normal } table.remove(g, b) changed = true break end end if changed then break end end end for _, p in __iter(g) do table.insert(out, p) end end return out end -- every brush's faces -> polygons (brushes[i] is a list of faces); nil, message past opts.maxPolygons function Brush.polygons(brushes, opts) local eps = opts and opts.epsilon or 1e-3 local limit = opts and opts.maxPolygons or 2 ^ 20 local per= {} local planesOf= {} local count = 0 for bi, faces in __iter(brushes) do local planes= {} for fi, f in __iter(faces) do planes[fi] = f.plane end planesOf[bi] = planes local list= {} local ws = Brush.windings(planes, opts) for fi = 1, #faces do local w = ws[fi] if w then table.insert(list, { brush = bi, face = fi, points = w, normal = { planes[fi][1], planes[fi][2], planes[fi][3] } }) end end per[bi] = list count =count+ #list if count > limit then return nil, "limit: too many brush faces" end end local all= {} if opts and opts.hull then local boxes= {} for bi = 1, #brushes do boxes[bi] = bounds(per[bi]) end for bi = 1, #brushes do for _, p in __iter(per[bi]) do local frags= { p.points } local own = brushes[bi][p.face].plane local pb = bounds({ p }) for bj = 1, #brushes do if #frags == 0 then break end local ob = boxes[bj] if bj ~= bi and #per[bj] > 0 and pb[1] <= ob[4] + eps and pb[4] >= ob[1] - eps and pb[2] <= ob[5] + eps and pb[5] >= ob[2] - eps and pb[3] <= ob[6] + eps and pb[6] >= ob[3] - eps then local nextFrags= {} for _, fr in __iter(frags) do for _, kept in __iter(outside(fr, own, bi, bj, planesOf[bj], eps)) do table.insert(nextFrags, kept) end end frags = nextFrags if #frags > limit then return nil, "limit: too many brush fragments" end end end for _, fr in __iter(frags) do local c = clean(fr, eps) if c then table.insert(all, { brush = p.brush, face = p.face, points = c, normal = p.normal }) end end end end else for bi = 1, #brushes do for _, p in __iter(per[bi]) do table.insert(all, p) end end end if opts and opts.merge then all = mergeAll(all, brushes, eps) end return all, nil end -- polygon area (for checks against compilers) function Brush.area(pts) local n = math.floor(#pts / 3 ) local ax, ay, az = 0, 0, 0 for k = 1, n - 2 do local ux, uy, uz = pts[k * 3 + 1] - pts[1], pts[k * 3 + 2] - pts[2], pts[k * 3 + 3] - pts[3] local vx, vy, vz = pts[k * 3 + 4] - pts[1], pts[k * 3 + 5] - pts[2], pts[k * 3 + 6] - pts[3] ax =ax+ (uy * vz - uz * vy ) ay =ay+ (uz * vx - ux * vz ) az =az+ (ux * vy - uy * vx ) end return sqrt(ax * ax + ay * ay + az * az) / 2 end -- polygons -> one indexed triangle primitive per texture, in order of first use. size(name) gives a texture's -- width, height (texel projections divide by them) function Brush.primitives(polys, brushes, size) local byTex= {} local order= {} local sizes= {} for _, p in __iter(polys) do local f = brushes[p.brush][p.face] local name = f.texture or "" local acc = byTex[name] if not acc then acc = { texture = name, pos = {}, nrm = {}, uv = {}, idx = {} } byTex[name] = acc table.insert(order, acc) end local sz = sizes[name] if not sz then local w, h = size(name) sz = { math.max(w, 1), math.max(h, 1) } sizes[name] = sz end local a= acc local pts = p.points local n = math.floor(#pts / 3 ) local base = math.floor(#a.pos / 3 ) for k = 0, n - 1 do local x, y, z = pts[k * 3 + 1], pts[k * 3 + 2], pts[k * 3 + 3] local pp, nn, uu = a.pos, a.nrm, a.uv pp[#pp + 1], pp[#pp + 2], pp[#pp + 3] = x, y, z nn[#nn + 1], nn[#nn + 2], nn[#nn + 3] = p.normal[1], p.normal[2], p.normal[3] local u, v = Brush.uv(f, x, y, z, sz[1], sz[2]) uu[#uu + 1], uu[#uu + 2] = u, v end local ii = a.idx for k = 1, n - 2 do ii[#ii + 1], ii[#ii + 2], ii[#ii + 3] = base, base + k, base + k + 1 end end local out= {} for _, a in __iter(order) do local nv, ni = math.floor(#a.pos / 3), #a.idx local pb, nb, ub, ib = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8), buffer.create(ni * 4) for k = 1, nv * 3 do writef32(pb, (k - 1) * 4, a.pos[k]) writef32(nb, (k - 1) * 4, a.nrm[k]) end for k = 1, nv * 2 do writef32(ub, (k - 1) * 4, a.uv[k]) end for k = 1, ni do writeu32(ib, (k - 1) * 4, a.idx[k]) end local S = Types.Scene table.insert(out, { texture = a.texture, primitive = { attributes = { POSITION = S.accessor(pb, "f32", 3, nv), NORMAL = S.accessor(nb, "f32", 3, nv), TEXCOORD_0 = S.accessor(ub, "f32", 2, nv) }, indices = S.accessor(ib, "u32", 1, ni), mode = "triangles" , }, }) end return out end return Brush end __FILES["codecs/model/Draco"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict -- 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 function Draco.sniff(buf, off) local o = off or 0 return buffer.len(buf) >= o + 5 and buffer.readstring(buf, o, 5) == "DRACO" end local function header(d) 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 =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 = kind == 0 and"points" or"mesh", method = method, flags = flags }, nil end function Draco.info(src, off, len) 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, depth) if depth > 1000 then return nil end local m= { 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 =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 =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 =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) local n = Reader.varint(d) if d.bad or n > Reader.remaining(d) then return nil end local atts= {} 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= { [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, numPoints) 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 for p = 0, numPoints - 1 do local e = (map and{map[p + 1] }or{p })[1] 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 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 = (map and{map[p + 1] }or{p })[1] 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 =o+ size end end return out, nil end local function decode(buf, o, l, opts) 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 = h.kind == "points" and 0x0203 or 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= 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= 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 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 = h.method == 1 and"kdtree" or"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= { 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 __iter(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, off, len, opts) 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 (string.find(tostring(msg), "^unsupported") and"unsupported" or(string.find(tostring(msg), "truncated") and"truncated" or nil))) end return g, nil end function Draco.attribute(g, uniqueId) for _, a in __iter(g.attributes) do if a.uniqueId == uniqueId then return a end end return nil end return Draco end __FILES["codecs/model/Draco/Attributes"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict -- 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 = {} -- 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 local function zigzag(v) if v % 2 == 1 then return -(math.floor(v / 2)) - 1 end return math.floor(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, pos, floats) local old = ver < 0x0200 local vals = (old and{pos.values }or{pos.portable })[1] 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) local e = (map and{(map[point + 1] or 0) }or{point })[1] 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 = (x < 0 and{(math.ceil(x) )}or{(math.floor(x) )})[1] y = (y < 0 and{(math.ceil(y) )}or{(math.floor(y) )})[1] z = (z < 0 and{(math.ceil(z) )}or{(math.floor(z) )})[1] end return x, y, z end end local function decodeIntegerValues(d, a, points, scheme) local comps = a.seqType == 3 and 2 or 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 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 =p+ 4 end elseif nb == 1 then for i = 1, numValues do vals[i] = buffer.readu8(b, p) p =p+ 1 end elseif nb == 2 then for i = 1, numValues do vals[i] = buffer.readu16(b, p) p =p+ 2 end else for i = 1, numValues do vals[i] = buffer.readu16(b, p) + buffer.readu8(b, p + 2) * 65536 p =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, a) 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) local src = a.portable 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 =v% 256 elseif dt == 3 then v = (v + 32768) % 65536 - 32768 elseif dt == 4 then v =v% 65536 elseif dt == 6 then v =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 =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, g) local ver = d.ver local numDecoders = Reader.u8(d) if d.bad then return nil, d.bad end local mesh = g.mesh local decoders= {} for i = 0, numDecoders - 1 do local dec= { 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 local enc if decoderType == 0 then if ad then enc = ad.enc ad.used = false else enc = mesh.posEnc 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 enc = cad.enc dec.traversal = { ct = cad.ct , enc = enc, method = 0 } end local pct = (ad and ad.used and{ad.ct }or{ct })[1] dec.md = { ct = pct, e2c = enc.e2c, v2e = enc.v2e } end decoders[i + 1] = dec end local all= {} for _, dec in __iter(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 = (ver < 0x0103 and{(Reader.u16(d) )}or{(Reader.varint(d) )})[1] local a= { 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 __iter((g.kdTree and{} or 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) for _, a in __iter(all) do if a.type == t then return a end end return nil end for _, dec in __iter(decoders) do local __DARKLUA_CONTINUE_17=false repeat if g.kdTree then local ok, err = KdTree.decode(d, dec.attrs, g.numPoints) if not ok then return nil, err end __DARKLUA_CONTINUE_17=true break end local points local trav = dec.traversal if trav then local faces = (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 ).numPoints for _, a in __iter(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 __iter(dec.attrs) do local __DARKLUA_CONTINUE_20=false repeat 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 =d.pos+ size a.raw = raw a.numValues = #points __DARKLUA_CONTINUE_20=true break 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= 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 __DARKLUA_CONTINUE_20=true until true if not __DARKLUA_CONTINUE_20 then break end end if ver >= 0x0200 then for _, a in __iter(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 __iter(dec.attrs) do if a.seqType ~= 0 then local ok, err = storeValues(a) if not ok then return nil, err end end end end __DARKLUA_CONTINUE_17=true until true if not __DARKLUA_CONTINUE_17 then break end end return all, nil end return Attributes end __FILES["codecs/model/Draco/Connectivity"] = function() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict -- 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 = {} 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) if c < 0 then return -1 end return (c % 3 == 2 and((c - 2 ))or((c + 1 )))end local function prevC(c) if c < 0 then return -1 end return (c % 3 == 0 and((c + 2 ))or((c - 1 )))end Connectivity.next = nextC Connectivity.prev = prevC local function newEnc(nv) return { v2e = table.create(nv, 0), e2c = {}, numValues = 0 } end function Connectivity.sequential(d) 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 > math.floor(0xffffffff / 3 )or numFaces > math.floor(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 = math.floor(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 =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 =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 =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 =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 -- MeshEdgebreakerTraversalDecoder::Start local function standardStart(buf, numAttributeData, withSymbols) local st= {} 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 =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 =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) 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, buf, numAttributeData, numVertices, numFaces, ct) 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() if st.startBuf then return Reader.bits(st.startBuf, 1) == 1 end return Reader.bit(st.startDec) end local function seam(i) return Reader.bit(st.seams[i + 1]) end local valences = table.create(numVertices, 0) local c2v = ct.c2v local function vtx(c) return c < 0 and-1 or(c2v[c + 1] or -1) end local function addValence(v, k) if v >= 0 and v < numVertices then do local __DARKLUA_VAR=v + 1 valences[__DARKLUA_VAR]=valences[__DARKLUA_VAR]+ k end end end local function mergeVertices(dest, src) if dest >= 0 and dest < numVertices and src >= 0 and src < numVertices then do local __DARKLUA_VAR=dest + 1 valences[__DARKLUA_VAR]=valences[__DARKLUA_VAR]+ valences[src + 1] end end end local lastSymbol = -1 local function updateValences(corner) 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() return standardSymbol(sym) end, newActiveCorner = function(_c) end, mergeVertices = function(_a, _b) 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() if predicted ~= -1 and Reader.bit(pred) then lastSymbol = predicted return predicted end lastSymbol = standardSymbol(sym) return lastSymbol end, newActiveCorner = function(corner) updateValences(corner) if lastSymbol == TOPOLOGY_C or lastSymbol == TOPOLOGY_R then local pivot = vtx(nextC(corner)) local val = (pivot >= 0 and pivot < numVertices and{valences[pivot + 1] }or{0 })[1] predicted = (val < 6 and{TOPOLOGY_R }or{TOPOLOGY_C })[1] 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= {} local counters= {} 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() 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) updateValences(corner) local v = vtx(nextC(corner)) local val = (v >= 0 and v < numVertices and{valences[v + 1] }or{0 })[1] 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, numFaces) 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, ver < 0x0202 and 2 or 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, seams) local c2v, opp, lmc = ct.c2v, ct.opp, ct.lmc local nc = ct.nf * 3 local function V(c) return c < 0 and-1 or(c2v[c + 1] or -1) end local edgeSeam= {} local vertSeam= {} for _, c in __iter(seams) do edgeSeam[c] = true vertSeam[V(nextC(c))] = true vertSeam[V(prevC(c))] = true local o = c < 0 and-1 or(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] = edgeSeam[c] and-1 or(opp[c + 1] or -1) end local ac2v = table.create(nc, -1) local almc= {} local num = 0 local function swingLeftA(c) local n = nextC(c) local o = n < 0 and-1 or aopp[n + 1] return nextC(o) end local function swingRight(c) local p = prevC(c) local o = p < 0 and-1 or(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 =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 =num+ 1 table.insert(almc, act) end ac2v[act + 1] = id act = swingRight(act) guard =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 } end -- MeshEdgebreakerDecoderImpl::DecodeConnectivity (+ the traversal start, seams, AssignPointsToCorners) function Connectivity.edgebreaker(d, traversalKind) 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 > math.floor(0xffffffff / 3 )then return nil, "too many faces" end if numEncodedVertices > numFaces * 3 then return nil, "more vertices than corners" end local minEdges = math.floor((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 + math.floor(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= {} local opp= {} local lmc= {} local nv = 0 local ct= { c2v = c2v, opp = opp, lmc = lmc, nv = 0, nf = numFaces } local notHole= {} local splits 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 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) return c < 0 and-1 or(c2v[c + 1] or -1) end local function O(c) return c < 0 and-1 or(opp[c + 1] or -1) end local function setOpp(a, b) if a >= 0 then opp[a + 1] = b end if b >= 0 then opp[b + 1] = a end end local function setLmc(v, c) if v >= 0 then lmc[v + 1] = c end end local function LMC(v) return v < 0 and-1 or(lmc[v + 1] or -1) end local function addVertex() nv =nv+ 1 lmc[nv] = -1 return nv - 1 end local function swingLeft(c) return nextC(O(nextC(c))) end local function swingRight(c) return prevC(O(prevC(c))) end local stack= {} local sp = 0 local splitActive= {} local invalidVerts= {} local removeInvalid = numAttributeData == 0 local nf = 0 for symbolId = 0, numSymbols - 1 do local face = nf 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 =sp- 1 local pushed = splitActive[symbolId] if pushed then sp =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 =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 = (top.edge == 1 and{(nextC(act) )}or{(prevC(act) )})[1] 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 =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 =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 __iter(invalidVerts) do local src = numVertices - 1 while src >= 0 and LMC(src) == -1 do numVertices =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 =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 __iter(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 =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 =d.pos+ splitBytes end local 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 = (k == 0 and{base }or{(k == 1 and((base + 1 ))or((base + 2 )))})[1] local o = O(c) if o == -1 then for i = 1, numAttributeData do table.insert(attrData[i].seams, c) end elseif ver < 0x0201 or math.floor(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 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 =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 ).c2v if ac2v[c + 1] ~= ac2v[pc + 1] then seam = true break end end if seam then faces[c + 1] = numPoints numPoints =numPoints+ 1 else faces[c + 1] = faces[pc + 1] end pc = c c = swingRight(c) guard =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, faces, enc, method) 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= {} local v2e, e2c = enc.v2e, enc.e2c local function V(c) return c < 0 and-1 or(c2v[c + 1] or -1) end local function O(c) return c < 0 and-1 or(opp[c + 1] or -1) end local function faceSeen(c) if c < 0 then return true end return faceVisited[math.floor(c / 3 )+ 1] == true end local function visit(v, c) 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 =enc.numValues+ 1 return true end local function onBoundary(v) local c = v < 0 and-1 or(lmc[v + 1] or -1) return nextC(O(nextC(c))) == -1 end if method == 0 then local stack= {} 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 __DARKLUA_CONTINUE_41=false repeat local c = stack[#stack] if c == -1 or faceSeen(c) then stack[#stack] = nil __DARKLUA_CONTINUE_41=true break end while true do local __DARKLUA_CONTINUE_42=false repeat faceVisited[math.floor(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 __DARKLUA_CONTINUE_42=true break 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 __DARKLUA_CONTINUE_42=true until true if not __DARKLUA_CONTINUE_42 then break end end __DARKLUA_CONTINUE_41=true until true if not __DARKLUA_CONTINUE_41 then break end end end end return points end if nvt == 0 then return points end local degree = table.create(nvt, 0) local stacks= { {}, {}, {} } local best = 0 local function priority(c) local v = V(c) if v < 0 or v >= nvt then return 0 end local p = 0 if not vertVisited[v + 1] then do local __DARKLUA_VAR=v + 1 degree[__DARKLUA_VAR]=degree[__DARKLUA_VAR]+ 1 end p = degree[v + 1] > 1 and 1 or 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 __iter({ { 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 local __DARKLUA_CONTINUE_47=false repeat faceVisited[math.floor(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 __DARKLUA_CONTINUE_47=true break 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 __DARKLUA_CONTINUE_47=true break end table.insert(stacks[p + 1], rc) if p < best then best = p end end break until true if not __DARKLUA_CONTINUE_47 then break end end end end end return points end -- MeshTraversalSequencer::UpdatePointToAttributeIndexMapping function Connectivity.mapping(ct, faces, enc, numPoints) 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() --!strict -- 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) if n >= 0 then return (math.floor(n / P32)) % P32, n % P32 end local h, l = Int64.from(-n) return Int64.neg(h, l) end function Int64.neg(h, l) if l == 0 then return (P32 - h) % P32, 0 end return P32 - 1 - h, P32 - l end function Int64.add(ah, al, bh, bl) local l = al + bl local c = 0 if l >= P32 then l =l- P32 c = 1 end return (ah + bh + c) % P32, l end function Int64.sub(ah, al, bh, bl) local nh, nl = Int64.neg(bh, bl) return Int64.add(ah, al, nh, nl) end function Int64.mul(ah, al, bh, bl) local a0, a1, a2, a3 = al % 65536, math.floor(al / 65536), ah % 65536, math.floor(ah / 65536 ) local b0, b1, b2, b3 = bl % 65536, math.floor(bl / 65536), bh % 65536, math.floor(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 = math.floor(lo / P32 ) lo =lo% P32 local hi = (math.floor(c1 / 65536 )+ c2 + (c3 % 65536) * 65536 + carry) % P32 return hi, lo end function Int64.isNeg(h) return h >= P31 end function Int64.signed(h, l) if h >= P31 then return (h - P32) * P32 + l end return h * P32 + l end function Int64.unsigned(h, l) return h * P32 + l end function Int64.ucmp(ah, al, bh, bl) if ah ~= bh then return ah < bh and-1 or 1 end if al ~= bl then return al < bl and-1 or 1 end return 0 end function Int64.cmp(ah, al, bh, bl) local sa = (ah >= P31 and((ah - P32 ))or(ah )) local sb = (bh >= P31 and((bh - P32 ))or(bh )) if sa ~= sb then return sa < sb and-1 or 1 end return Int64.ucmp(0, al, 0, bl) end function Int64.udivmod(ah, al, bh, bl) if ah == 0 and bh == 0 then return 0, math.floor(al / bl), 0, al % bl end local qh, ql, rh, rl = 0, 0, 0, 0 for i = 63, 0, -1 do local bit = (i >= 32 and(((math.floor(ah / 2 ^ (i - 32))) % 2 ))or(((math.floor(al / 2 ^ i)) % 2 ))) local over = rh >= P31 rh = (rh * 2 + math.floor(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 =qh+ 2 ^ (i - 32) else ql =ql+ 2 ^ i end end end return qh, ql, rh, rl end function Int64.div(ah, al, bh, bl) 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, l) 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() local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict -- 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 = {} -- bits(n) reads MSB first local function direct(d) 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, math.floor(size / 4 ) d.pos =d.pos+ size local pos, used = 0, 0 return { next = function() if pos >= words then return 0 end local w = buffer.readu32(b, base + pos * 4) local bit = bit32.extract(w, 31 - used) used =used+ 1 if used == 32 then pos =pos+ 1 used = 0 end return bit end, bits = function(n) 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 =used+ n if used == 32 then pos =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 =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) local bd = Reader.bitDecoder(d) if not bd then return nil end local function nextBit() return Reader.bit(bd) and 1 or 0 end return { next = nextBit, bits = function(n) local v = 0 for _ = 1, n do v = v * 2 + nextBit() end return v end, } end local function folded(d) local parts= {} 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() return Reader.bit(main ) and 1 or 0 end, bits = function(n) local v = 0 for i = 1, n do v = v * 2 + (Reader.bit(parts[i]) and 1 or 0) end return v end, } end local function msb(n) local k = -1 while n >= 1 do n = math.floor(n / 2 ) k =k+ 1 end return k end -- DynamicIntegerPointsKdTreeDecoder::DecodePoints local function decodePoints(d, level, dim, expected) 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= {} if numPoints == 0 then return out, nil end local numbers = (level >= 4 and{(folded(d) )}or{(level >= 2 and{(rans(d) )}or{(direct(d) )})[1]})[1] 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= { table.clone(zero) } local levelStack= { table.clone(zero) } local stack = { { numPoints, 0, 0 } } local decoded = 0 local p = table.create(dim, 0) while #stack > 0 do local __DARKLUA_CONTINUE_5=false repeat 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 = lastAxis == dim - 1 and 0 or 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 ).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 =decoded+ 1 end if decoded > numPoints then return nil, "kd-tree: too many points" end __DARKLUA_CONTINUE_5=true break 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 = a == dim - 1 and 0 or a + 1 end table.insert(out, table.clone(p)) decoded =decoded+ 1 end if decoded > numPoints then return nil, "kd-tree: too many points" end __DARKLUA_CONTINUE_5=true break 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 = math.floor(n / 2 ) if first < number then return nil, "kd-tree: bad split" end first =first- number local second = n - first if first ~= second and half.next() == 0 then first, second = second, first end do local __DARKLUA_VAR=axis + 1 levels[__DARKLUA_VAR]=levels[__DARKLUA_VAR]+ 1 end 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 __DARKLUA_CONTINUE_5=true until true if not __DARKLUA_CONTINUE_5 then break 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, attrs, numPoints) 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 __iter(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 =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 __iter(attrs) do local comps = a.comps local vals = table.create(numPoints * comps, 0) local mod = (a.dataType == 1 or a.dataType == 2 )and 256 or((a.dataType == 3 or a.dataType == 4 )and 65536 or 4294967296 ) local raw = a.dataType == 9 for i, pt in __iter(points) do for c = 1, comps do local v = pt[off + c] vals[(i - 1) * comps + c] = (raw and{v }or{(v % mod )})[1] end end a.portable = vals a.values = vals a.numValues = numPoints a.map = nil off =off+ comps end for _, a in __iter(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 __iter(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] = (v % 2 == 1 and((-(math.floor(v / 2)) - 1 ))or((math.floor(v / 2 )))) end if d.bad then return false, d.bad end a.signedMin = mins end end local fround = Predict.fround for _, a in __iter(attrs) do local vals = a.portable 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 =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() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict -- 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 = {} local nextC, prevC = Connectivity.next, Connectivity.prev local F32 = buffer.create(4) local function fround(x) buffer.writef32(F32, 0, x) return buffer.readf32(F32, 0) end Predict.fround = fround local function i32(x) return (x + 2147483648) % 4294967296 - 2147483648 end Predict.i32 = i32 local function tdiv(a, b) local q = a / b return (q < 0 and{(math.ceil(q) )}or{(math.floor(q) )})[1]end -- static_cast of a float with the decoder's NaN / range guard (INT_MIN) local function truncInt(x) 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, b) 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, b, c) 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 = math.floor(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 =q- 1 r =r+ c end while r >= c do q =q+ 1 r =r- c end end return (neg and{(-q )}or{q })[1]end -- floor(sqrt(a * b)) (IntSqrt of a 64-bit product), exact for a, b < 2^53 local function isqrtProd(a, b) 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) 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 =s- 1 end while le(s + 1) do s =s+ 1 end return s end function Predict.octahedron(bits) 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 = math.floor(maxV / 2), scale = fround(2 / fround(maxV)) } end local function canonicalizeCoords(o, s, t) 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, x, y, z) local s, t local center, maxV = o.center, o.maxV if x >= 0 then s, t = y + center, z + center else s = (y < 0 and{(math.abs(z) )}or{(maxV - math.abs(z) )})[1] t = (z < 0 and{(math.abs(y) )}or{(maxV - math.abs(y) )})[1] end return canonicalizeCoords(o, s, t) end local function canonicalizeVector(o, x, y, z) 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, s, t) 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 = s > 0 and 1 or-1 signT = t > 0 and 1 or-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, x) 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, s, t) 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((y < 0 and((y + xo ))or((y - xo)))) z = fround((z < 0 and((z + xo ))or((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 function Predict.transform(kind) return { kind = kind, positive = kind ~= 1, min = 0, max = 0, maxDif = 0, oct = nil } end function Predict.decodeTransform(tr, d) 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 =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, pred, data, off, comps) 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 =v- dif elseif v < mn then v =v+ dif end data[off + c] = v end return end local o = tr.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_, ot= 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 = pt == 0 and 0 or(pt > 0 and 3 or 1 ) elseif ps > 0 then rot = pt >= 0 and 2 or 1 else rot = pt <= 0 and 0 or 3 end local function rotate(x, y, r) 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 local DELTA, PARALLELOGRAM, MULTI, TEXDEP, CONSTRAINED, TEXPORT, GEONORMAL = 0, 1, 2, 3, 4, 5, 6 Predict.GEOMETRIC_NORMAL = GEONORMAL function Predict.needsParent(s) 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, tr, md) 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 = (m == DELTA and{nil }or{md})[1], parent = nil, areaMode = true, ver = 0x0202 } end -- DecodePredictionData function Predict.decodeData(s, d) 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 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 ).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 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, p, ci, data, comps, out) local ct = md.ct local oci = ci < 0 and-1 or(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, c) local p = prevC(c) local o = p < 0 and-1 or(ct.opp[p + 1] or -1) return prevC(o) end local function swingLeft(ct, c) local n = nextC(c) local o = n < 0 and-1 or(ct.opp[n + 1] or -1) return nextC(o) end -- MeshPredictionSchemeTexCoordsPortablePredictor::ComputePredictedValue in int64 / uint64 like the C++ local function texPortable(nu, nv, pu, pv, tx, ty, tz, nx, ny, nz, qx, qy, qz, pop) 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, ay, az, bx, by, bz) 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(...) local m = 0 for _, x in __iter({ ... }) do m = math.max(m, math.abs(x)) end return from(m) end local function absI(h, l) 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, pc, t) 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: the low 32 bits return "ok", i32(ul), i32(vl) end -- ComputeOriginalValues (in place); points = the entry -> point map function Predict.compute(s, data, numEntries, comps, points) 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 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) 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= { 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 =count+ 1 end ci = swingRight(ct, ci) if ci == start then ci = -1 end guard =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 =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 =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 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 =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) local v = c < 0 and-1 or(c2v[c + 1] or -1) if v < 0 then return math.huge end return v2e[v + 1] or 0 end local function posOf(e) 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 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() if no == 0 then return nil end local o = orient[no] orient[no] = nil no =no- 1 return o end) if status == "fail" then return false, u 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, ty, tz= posOf(p) local nx, ny, nz= posOf(ne) local qx, qy, qz= 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 =no- 1 local u, v= 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) 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 =sx+ (ay * bz - az * by ) sy =sy+ (az * bx - ax * bz ) sz =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 =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 = math.floor(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() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict -- 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 function Reader.new(b, pos, limit, ver) 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) 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, msg) if not d.bad then d.bad = msg end return 0 end function Reader.remaining(d) return d.limit - d.pos end function Reader.u8(d) 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) local v = Reader.u8(d) return (v >= 128 and((v - 256 ))or(v ))end function Reader.u16(d) 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) 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) 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) 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) 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, wide) local maxBytes = wide and 10 or 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 =v+ band(c, 127) * mul if c < 128 then if not wide then v =v% 4294967296 end return v end mul =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, fixedBefore) 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, decodeSize) 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, n) 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 =v+ mul end off =off+ 1 end mul =mul* 2 end d.bitOff = off return v end function Reader.endBits(d) d.bitMode = false d.pos = d.bitStart + math.floor((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) local p = math.floor((3 * bitLength) / 2 ) return p < 12 and 12 or(p > 20 and 20 or p )end -- RAnsSymbolDecoder::Create: the probability table local function ransCreate(d, precBits) local numSymbols = Reader.count(d, 0x0200) if d.bad then return nil end if math.floor(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 =i+ (offset + 1 ) else local p = rshift(data, 2) for k = 1, token do p =p+ Reader.u8(d) * 2 ^ (8 * k - 2) end if d.bad then return nil end prob[i + 1] = p i =i+ 1 end end local lut= {} 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 =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, base, size, lBase, allow4) if size < 1 then return nil, nil end local x = rshift(readu8(b, base + size - 1), 6) local off, state= 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 =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, r) 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 d.pos =d.pos+ size return true end local function ransRead(r, n, out, first) 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 =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, n, comps, out) 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 =k+ 1 end if d.bad then return false end i =i+ comps end Reader.endBits(d) return true end local function decodeRaw(d, n, out) 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, n, comps) 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 (ok and{out }or{nil })[1]end -- RAnsBitDecoder::StartDecoding: prob_zero, the size (u32 before 2.2), the bytes function Reader.bitDecoder(d) 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 , p0 = p0, p = 256 - p0 } d.pos =d.pos+ size return bd end -- rabs_desc_read: one bit (true / false) function Reader.bit(bd) local state, off = bd.state, bd.off if state < 4096 and off > 0 then off =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 __FILES["codecs/model/Mat4"] = function() --!strict -- codecs/model/Mat4: 4x4 matrix (column-major, glTF / Types.Scene layout) and quaternion { x, y, z, w } helpers. local Types = __include("Types") local Mat4 = {} local sqrt, abs, sin, cos, rad = math.sqrt, math.abs, math.sin, math.cos, math.rad function Mat4.identity() 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, y, z) return { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1 } end function Mat4.scaling(x, y, z) return { x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1 } end function Mat4.rotation(axis, degrees) 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, y, z, order) 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, y, z, degrees) 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) 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) 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) 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, r, s) local m = (r and{(Mat4.fromQuat(r) )}or{(Mat4.identity() )})[1] if s then for k = 0, 2 do do local __DARKLUA_VAR=k * 4 + 1 m[__DARKLUA_VAR]=m[__DARKLUA_VAR]* s[k + 1] end do local __DARKLUA_VAR0=k * 4 + 2 m[__DARKLUA_VAR0]=m[__DARKLUA_VAR0]* s[k + 1] end do local __DARKLUA_VAR1=k * 4 + 3 m[__DARKLUA_VAR1]=m[__DARKLUA_VAR1]* s[k + 1] end 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) 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, strict) 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 = (sx ~= 0 and((1 / sx ))or(0 )) local iy = (sy ~= 0 and((1 / sy ))or(0 )) local iz = (sz ~= 0 and((1 / sz ))or(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) local t, r, s = split(m, false) return t , r , s end function Mat4.decomposeStrict(m) return split(m, true) end function Mat4.inverse(m) 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) 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]=inv[k]/ det end return inv end function Mat4.transpose3(m) 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, at) 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 (r == c and 1 or 0) end end return m end function Mat4.toRows(m) 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, x, y, z) 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) 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() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict -- 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= { unorm8 = 255, unorm16 = 65535, snorm8 = 127, snorm16 = 32767 } function Flatten.numbers(acc, raw) 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= acc.data if buffer.len(d) < n * size then return nil, "accessor data shorter than count * components" end local out = (table.create(n) ) 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] = signed and v < -1 and-1 or 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, n) 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) 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) ) 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) for i = 1, 16 do if m[i] ~= IDENTITY[i] then return false end end return true end local function instances(scene) local out= {} 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, node, m) 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 __iter(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= {} local function visit(ni, parent, depth) 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 = (m and parent and{(mul(parent, m) )}or{(m and{m }or{parent })[1]})[1] 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 __iter(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 __iter(roots) do local e = visit(ri, nil, 0) if e then return nil, e end end elseif #nodes > 0 then local isChild= {} for _, n in __iter(nodes) do if type(n) == "table" and type(n.children) == "table" then for _, c in __iter(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, nv) 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 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) ) 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) ) 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 =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, t, raw) if string.sub(name, 1, 6) ~= "COLOR_" then return 0 end return (raw and NORM[t] and{NORM[t] }or{1 })[1]end local function f32(v) local b = buffer.create(4) buffer.writef32(b, 0, v) return buffer.readf32(b, 0) end function Flatten.merge(scene, keep, opts) 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= {} local comps= {} local used= {} for _, inst in __iter(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 __iter(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= {} for name, t in __iter(types) do local raw = NORM[t] ~= nil if name == "POSITION" or name == "NORMAL" then raw = false end attrs[name] = { type = (name == "POSITION" or name == "NORMAL" )and"f32" or t, components = (name == "POSITION" or name == "NORMAL" )and 3 or comps[name], raw = raw, values = {} } end local merged= { count = 0, attrs = attrs, sizes = nil, corners = {}, parts = {} } local sizes= {} local anyFaces = false local corners = merged.corners for _, inst in __iter(used) do local prim= 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 ) local info= { prim = prim, mesh = inst.mesh, node = inst.node, firstVertex = merged.count, vertexCount = nv, firstFace = #sizes, faceCount = 0, identity = identity } for name, a in __iter(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 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 -- 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 = a1 * n11 + a2 * n12 + a3 * n13 < 0 and-1 or 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] = (c <= sc and{vals[i * sc + c] }or{f })[1] 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 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= cs local p = 0 local nf = (fs and((#fs ))or((math.floor(#cl / 3 )))) for f = 1, nf do local s = (fs and{fs[f] }or{3 })[1] 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 =p+ s end end info.faceCount = #sizes - info.firstFace merged.count =merged.count+ nv table.insert(merged.parts, info) end merged.sizes = (anyFaces and{sizes }or{nil })[1] return merged, nil end return Flatten end __FILES["codecs/model/Minecraft"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict -- 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) 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 , "^%[(.*)%]%s*$") if body then for pair in __iter(string.gmatch(body, "[^,]+")) do local k, v = string.match(pair, "^%s*([^=%s]+)%s*=%s*(.-)%s*$") if k then table.insert(props, { k, v }) end end end return n, props end function Minecraft.stateString(name, props) if not props or next(props) == nil then return name end local parts = {} if props[1] ~= nil then for _, kv in __iter(props) do table.insert(parts, kv[1] .. "=" .. tostring(kv[2])) end else for _, k in __iter(Types.keys(props)) do table.insert(parts, tostring(k) .. "=" .. tostring((props )[k])) end end return name .. "[" .. table.concat(parts, ",") .. "]" end function Minecraft.stateFromNbt(c) if type(c) ~= "table" or type(c.Name) ~= "string" then return nil end local props = {} if type(c.Properties) == "table" then for _, k in __iter(Types.keys(c.Properties)) do local v = c.Properties[k] table.insert(props, { k, (type(v) == "string" and{v }or{(tostring(Nbt.number(v) or v) )})[1]}) end end return Minecraft.stateString(c.Name, props) end function Minecraft.stateToNbt(s) local name, props = Minecraft.parseState(s) local c = Types.object({ Name = name }, { "Name" }) if #props > 0 then local p, keys = {}, {} for _, kv in __iter(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) 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) return AIR[Minecraft.baseName(s)] == true end local function hex(h) 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) local out = {} for h in __iter(string.gmatch(s, "%x+")) do table.insert(out, hex(h)) end return out end local EXACT= {} for name, h in __iter(string.gmatch(Colors.BLOCKS, "([%w_]+)=(%x+)")) do EXACT[name ] = hex(h ) 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) local out= {} for i, n in __iter(names) do table.insert(out, { n, i }) end table.sort(out, function(a, b) return #(a[1] ) > #(b[1] ) 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= { tube = hex("3157d0"), brain = hex("cf5b9f"), bubble = hex("a118a0"), fire = hex("a6252f"), horn = hex("d8c53e") } local FALLBACK = hex("909090") local function mix(c, w, t) 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 local function family(n) for _, d in __iter(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 __iter(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) if string.find(n, "copper", 1, true) then return (string.find(n, "oxidized", 1, true) and{EXACT.oxidized_copper }or{(string.find(n, "weathered", 1, true) and{EXACT.weathered_copper }or{(string.find(n, "exposed", 1, true) and{EXACT.exposed_copper }or{EXACT.copper_block })[1]})[1]})[1] elseif string.find(n, "coral", 1, true) then if string.find(n, "dead", 1, true) then return hex("857e79") end for k, c in __iter(CORAL) do if string.find(n, k, 1, true) then return c end end elseif string.find(n, "_ore$") then return (string.find(n, "deepslate", 1, true) and{EXACT.deepslate }or{(string.find(n, "nether", 1, true) and{EXACT.netherrack }or{EXACT.stone })[1]})[1] end for _, k in __iter({ "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" } )[k] return EXACT[alias] end end return nil end resolve = function(n, depth) 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 __iter(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 __iter(SUFFIXES) do if #n > #sfx and string.sub(n, -#sfx) == sfx then local base = string.sub(n, 1, #n - #sfx) for _, form in __iter({ 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= {} function Minecraft.color(s) 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= nil if not AIR[n] then local variants = Legacy.VARIANTS[n] or ((n == "double_wooden_slab" and{Legacy.VARIANTS.planks }or{nil})[1]) if variants then local data = 0 for _, kv in __iter(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= nil local function reverse() if REVERSE then return REVERSE end local r= {} local byName= {} for i, n in __iter(Legacy.NAMES) do if n ~= "-" then byName[n] = i - 1 end end for legacy, modern in __iter(Legacy.RENAMED) do r[modern] = { byName[legacy], 0 } end for legacy, variants in __iter(Legacy.VARIANTS) do for d, v in __iter(variants) do if r[v] == nil then r[v] = { byName[legacy], d - 1 } end end end for n, id in __iter(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, data) local n = Legacy.NAMES[id + 1] if n == nil or n == "-" then return "minecraft:legacy_" .. id .. ((data ~= 0 and(("[data=" .. data .. "]" ))or(""))) 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 .. ((data ~= idx and(("[data=" .. data .. "]" ))or(""))) end end return "minecraft:" .. (Legacy.RENAMED[n] or n) .. ((data ~= 0 and(("[data=" .. data .. "]" ))or(""))) end function Minecraft.legacyId(s) local name, props = Minecraft.parseState(s) local n = string.match(name, ":(.*)$") or name local id, 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 __iter(props) do if kv[1] == "data" then data = (tonumber(kv[2]) or data) % 16 end end return id, data end function Minecraft.voxels(sx, sy, sz, states, indices) local v = Types.Voxels.new(sx, sy, sz) local lut = buffer.create(#states) local slots= {} local used = 0 for i, s in __iter(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 =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, (s < nstates and{(buffer.readu8(lut, s) )}or{0})[1]) end v.blocks = { palette = states, data = indices } return v end local CANDIDATES= nil local function candidates() if CANDIDATES then return CANDIDATES end local out = {} for _, d in __iter(Colors.DYES) do for _, kind in __iter({ "wool", "concrete", "terracotta" }) do local s = "minecraft:" .. d .. "_" .. kind table.insert(out, { s, Minecraft.color(s) }) end end for _, w in __iter(Colors.WOODS) do local s = "minecraft:" .. w .. "_planks" table.insert(out, { s, Minecraft.color(s) }) end for _, n in __iter({ "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) local a = c[4] or 255 if a < 200 then local best, bd = "minecraft:glass", math.huge for i, d in __iter(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 __iter(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) 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= { [0] = 0 } local byState= { ["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 ) 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) 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) if Nbt.isTag(v) and v.type == "intArray" then return v.value elseif type(v) == "table" and not Nbt.isTag(v) and (v )[1] ~= nil then local out= {} for i, x in __iter(v) 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, skip) local out, keys = {}, {} for _, k in __iter(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, style) 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 = (type(c.id) == "string" and{c.id }or{nil})[1], data = rest(c, FLAT_SKIP) } end local p = ints(c.Pos) or { 0, 0, 0 } local data = (style == "data" and{((type(c.Data) == "table" and{c.Data }or{(Types.object())})[1]) }or{(rest(c, POS_SKIP) )})[1] return { pos = { p[1] or 0, p[2] or 0, p[3] or 0 }, id = (type(c.Id) == "string" and{c.Id }or{nil})[1], data = data } end function Minecraft.flatBlockEntity(be, style) local o = Types.object() local data = (type(be.data) == "table" and{be.data }or{(Types.object() )})[1] 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 __iter(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 __iter(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() --!strict -- 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() local __compat = __compat local __iter = __compat.__iter --!strict -- 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) local out = {} for w in __iter(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", } -- 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) local out = {} for i, d in __iter(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"), } Legacy.MASK = { log = 4, log2 = 4, leaves = 4, leaves2 = 4, sapling = 8, wooden_slab = 8, quartz_block = 8, double_plant = 8 } return Legacy end __FILES["codecs/model/Minecraft/Packed"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 -- 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 function Packed.longsNeeded(count, bits, spanning) if spanning then return math.floor((count * bits + 63) / 64 ) end local per = math.floor(64 / bits ) return math.floor((count + per - 1) / per )end function Packed.unpack(longs, bits, count, spanning, out, max) 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 (" .. math.floor(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 =p+ bits end else local per = math.floor(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 =i+ 1 p =p+ bits end base =base+ 8 end end return true, nil end function Packed.pack(indices, count, bits, spanning) local need = Packed.longsNeeded(count, bits, spanning) local out = buffer.create(need * 8 + 4) local per = math.floor(64 / bits ) for i = 0, count - 1 do local v = readu16(indices, i * 2) local p = (spanning and((i * bits ))or(((math.floor(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 function Packed.bitsFor(n, min) local b = min while lshift(1, b) < n and b < 31 do b =b+ 1 end return b end -- Sponge BlockData: unsigned LEB128 varints function Packed.varints(src, offset, length, count, out, max) 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 =p+ 1 v =v+ band(c, 0x7f) * 2 ^ sh if c < 128 then break end sh =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 function Packed.toVarints(indices, count) 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 =p+ 1 v = rshift(v, 7) end writeu8(out, p, v) p =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 function Packed.nibble(src, offset, i, highFirst) 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 function Packed.setNibble(dst, offset, i, v, highFirst) 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) function Packed.fromYzx(src, sx, sy, sz, dst, ox, oy, oz, dsx, dsy) 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 =i+ 2 d =d+ 2 end end end return out end function Packed.toYzx(src, sx, sy, sz) 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 =i+ 2 s =s+ 2 end end end return out end return Packed end __FILES["codecs/model/Patch"] = function() local __compat = __compat local __iter = __compat.__iter --!strict --!native --!optimize 2 -- codecs/model/Patch: Quake III / Doom 3 Bezier patches (control grids) -> evaluated grids, triangles, normals. -- A w x h grid (w, h odd, >= 3) is a mesh of 3 x 3 biquadratic sub-patches (Unofficial Quake 3 Map Specs; patchDef2 / -- patchDef3), evaluated at fixed segments per sub-patch and axis (patchDef3's explicit subdivisions; Quake III's adaptive -- subdivision is not reproduced). Shared edges are evaluated once. local Patch = {} local sqrt = math.sqrt function Patch.valid(w, h, n) return w >= 3 and h >= 3 and w % 2 == 1 and h % 2 == 1 and w * h == n end -- ctrl: w * h points of comps numbers, row-major (row j holds points j * w .. j * w + w - 1); returns the evaluated grid -- (gw * gh points of comps numbers, row-major) and its size; nil when the grid is not w x h odd or a limit is passed function Patch.grid(ctrl, w, h, comps, levelU, levelV, maxPoints) local lu, lv = math.max(1, math.floor(levelU)), math.max(1, math.floor(levelV)) if not Patch.valid(w, h, math.floor(#ctrl / comps)) or #ctrl ~= w * h * comps then return nil, 0, 0 end local px, py = math.floor((w - 1) / 2), math.floor((h - 1) / 2 ) local gw, gh = px * lu + 1, py * lv + 1 if gw * gh > (maxPoints or 2 ^ 24) then return nil, 0, 0 end local out = (table.create(gw * gh * comps, 0) ) for gy = 0, gh - 1 do local sy = math.min(math.floor(gy / lv), py - 1) local tv = (gy - sy * lv) / lv local bv0, bv1, bv2 = (1 - tv) * (1 - tv), 2 * tv * (1 - tv), tv * tv for gx = 0, gw - 1 do local sx = math.min(math.floor(gx / lu), px - 1) local tu = (gx - sx * lu) / lu local bu0, bu1, bu2 = (1 - tu) * (1 - tu), 2 * tu * (1 - tu), tu * tu local o = (gy * gw + gx) * comps for j = 0, 2 do local bv = (j == 0 and{bv0 }or{(j == 1 and{bv1 }or{bv2 })[1]})[1] local row = ((sy * 2 + j) * w + sx * 2) * comps for i = 0, 2 do local wgt = bv * ((i == 0 and{bu0 }or{(i == 1 and{bu1 }or{bu2})[1]})[1]) local c = row + i * comps for k = 1, comps do do local __DARKLUA_VAR=o + k out[__DARKLUA_VAR]=out[__DARKLUA_VAR]+ ctrl[c + k] * wgt end end end end end end return out, gw, gh end -- 0-based triangle indices over a gw x gh grid; Quake's control grids are clockwise-front, these are counter-clockwise function Patch.triangles(gw, gh) local out = (table.create(math.max(0, (gw - 1) * (gh - 1) * 6)) ) for gy = 0, gh - 2 do for gx = 0, gw - 2 do local a, b = gy * gw + gx, gy * gw + gx + 1 local d, e = a + gw, b + gw local n = #out out[n + 1], out[n + 2], out[n + 3] = a, d, b out[n + 4], out[n + 5], out[n + 6] = b, d, e end end return out end -- renormalizes the vec3 at component offset at (0-based) of every point function Patch.normalize(pts, comps, at) for o = 0, #pts - comps, comps do local x, y, z = pts[o + at + 1], pts[o + at + 2], pts[o + at + 3] local l = sqrt(x * x + y * y + z * z) if l > 0 then pts[o + at + 1], pts[o + at + 2], pts[o + at + 3] = x / l, y / l, z / l end end end -- unit normals (3 per point) of the evaluated grid from the positions (components 1..3), facing the front of -- Patch.triangles; points where the surface degenerates take a neighbour's normal function Patch.normals(pts, comps, gw, gh) local out = (table.create(gw * gh * 3, 0) ) local function at(x, y, k) return pts[(y * gw + x) * comps + k] end for gy = 0, gh - 1 do local y0, y1 = math.max(gy - 1, 0), math.min(gy + 1, gh - 1) for gx = 0, gw - 1 do local x0, x1 = math.max(gx - 1, 0), math.min(gx + 1, gw - 1) local ux, uy, uz = at(x1, gy, 1) - at(x0, gy, 1), at(x1, gy, 2) - at(x0, gy, 2), at(x1, gy, 3) - at(x0, gy, 3) local vx, vy, vz = at(gx, y1, 1) - at(gx, y0, 1), at(gx, y1, 2) - at(gx, y0, 2), at(gx, y1, 3) - at(gx, y0, 3) local nx, ny, nz = vy * uz - vz * uy, vz * ux - vx * uz, vx * uy - vy * ux local l = sqrt(nx * nx + ny * ny + nz * nz) local o = (gy * gw + gx) * 3 if l > 1e-12 then out[o + 1], out[o + 2], out[o + 3] = nx / l, ny / l, nz / l end end end for _ = 1, 2 do for i = 0, gw * gh - 1 do local o = i * 3 if out[o + 1] == 0 and out[o + 2] == 0 and out[o + 3] == 0 then local x, y = i % gw, math.floor(i / gw ) for _, d in __iter({ { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 }, { 1, 1 }, { -1, -1 }, { 1, -1 }, { -1, 1 } }) do local nx2, ny2 = x + d[1], y + d[2] if nx2 >= 0 and nx2 < gw and ny2 >= 0 and ny2 < gh then local q = (ny2 * gw + nx2) * 3 if out[q + 1] ~= 0 or out[q + 2] ~= 0 or out[q + 3] ~= 0 then out[o + 1], out[o + 2], out[o + 3] = out[q + 1], out[q + 2], out[q + 3] break end end end end end end return out end return Patch end __FILES["codecs/model/Polygon"] = function() local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict -- 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 = {} local function area(pts) local a = 0 local n = #pts for i = 1, n do local p, q = pts[i], pts[i % n + 1] a =a+ (p.x * q.y - q.x * p.y ) end return a / 2 end local function inside(pts, x, y) 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, a, b) return (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x) end local function crosses(p1, p2, q1, q2) 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, v, rings) for _, r in __iter(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, h, others) local mi = 1 for i, p in __iter(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 __iter(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= {} 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, b, c, p) return cross(a, b, p) >= 0 and cross(b, c, p) >= 0 and cross(c, a, p) >= 0 end local function clip(ring, out) local pts = table.clone(ring) local guard = #pts * #pts + 16 while #pts > 3 and guard > 0 do guard =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 = (found > 0 and{found }or{bestI })[1] 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) local rings= {} local areas= {} for li, l in __iter(loops) do local pts= {} 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 = math.floor((k + 1) / 2 )}) end end local a = (#pts >= 3 and{(area(pts) )}or{0 })[1] 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= {} 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]=depth[i]+ 1 if parent[i] == 0 or areas[j] < areas[parent[i] ] then parent[i] = j end end end end local holes= {} 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= {} 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, b) local ma, mb = -math.huge, -math.huge for _, p in __iter(rings[a]) do ma = math.max(ma, p.x) end for _, p in __iter(rings[b]) do mb = math.max(mb, p.x) end return ma > mb end) local flipped= {} for _, h in __iter(hs) do local r= {} 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 __iter(flipped) do local others= { 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"] = function() local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict -- 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 = {} function Rbx.tree(place) return { kind = "rbxtree", roots = {}, place = place == true, metadata = {}, extra = {}, meta = {} } end function Rbx.instance(className, name) return { className = className, name = name or className, properties = {}, children = {} } end function Rbx.add(parent, child) 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, name, typ, value) inst.properties[name] = { type = typ, value = value } end function Rbx.get(inst, name) local v = inst.properties[name] return (v and{v.value }or{nil })[1]end function Rbx.descendants(root) local stack= {} local list = (root.kind == "rbxtree" and{root.roots }or{root.children })[1] for i = #list, 1, -1 do table.insert(stack, { list[i], 1 }) end return function() 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) local out = {} for inst in __iter(Rbx.descendants(tree)) do table.insert(out, inst ) end return out end function Rbx.find(root, path) local cur= root for part in __iter(string.gmatch(path, "[^/]+")) do local list = (cur.kind == "rbxtree" and{cur.roots }or{cur.children })[1] local found = nil for _, c in __iter(list) do if c.name == part then found = c break end end if not found then return nil end cur = found end return (cur.kind == "rbxtree" and{nil }or{cur })[1]end function Rbx.fullName(inst) local parts = {} local cur= 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= {} 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, y, z) for i, a in __iter(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) 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, } ) local NAMES= {} for name, id in __iter(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) 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 } ) return Rbx end __FILES["codecs/model/Rbx/Binary"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --!native --!optimize 2 -- 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) local function unrotate(x) writeu32(scratch, 0, math.floor(x / 2 )+ (x % 2) * 2147483648) return readf32(scratch, 0) end local function rotate(v) writef32(scratch, 0, v) local bits = readu32(scratch, 0) return (bits * 2) % TWO32 + math.floor(bits / 2147483648 )end local function unzigzag(x) return (x % 2 == 0 and{(math.floor(x / 2 ))}or{(math.floor(-(x + 1) / 2 ))})[1]end local function zigzag32(v) v = floor(v) return ((v >= 0 and((v * 2 ))or((-v * 2 - 1)))) % TWO32 end local function u32s(b, p, n) 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 local function i32s(b, p, n) local out = u32s(b, p, n) for i = 1, n do out[i] = unzigzag(out[i]) end return out end local function f32s(b, p, n) local out = u32s(b, p, n) for i = 1, n do out[i] = unrotate(out[i]) end return out end local function i64s(b, p, n) 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 + math.floor(lo / 2 ) out[i + 1] = (lo % 2 == 0 and{half }or{(-half - 1 )})[1] end return out end local function putU32s(w, vals) 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, math.floor(v / 16777216)) buffer.writeu8(b, p + n + i, (math.floor(v / 65536)) % 256) buffer.writeu8(b, p + 2 * n + i, (math.floor(v / 256)) % 256) buffer.writeu8(b, p + 3 * n + i, v % 256) end w.pos = p + 4 * n end local function putI32s(w, vals) local t = table.create(#vals, 0) for i, v in __iter(vals) do t[i] = zigzag32(v) end putU32s(w, t) end local function putF32s(w, vals) local t = table.create(#vals, 0) for i, v in __iter(vals) do t[i] = rotate(v) end putU32s(w, t) end local function putI64s(w, vals) 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 = (v >= 0 and((v * 2 ))or((-v * 2 - 1 ))) local hi, lo = (math.floor(z / TWO32)) % TWO32, z % TWO32 buffer.writeu8(b, p + i, math.floor(hi / 16777216)) buffer.writeu8(b, p + n + i, (math.floor(hi / 65536)) % 256) buffer.writeu8(b, p + 2 * n + i, (math.floor(hi / 256)) % 256) buffer.writeu8(b, p + 3 * n + i, hi % 256) buffer.writeu8(b, p + 4 * n + i, math.floor(lo / 16777216)) buffer.writeu8(b, p + 5 * n + i, (math.floor(lo / 65536)) % 256) buffer.writeu8(b, p + 6 * n + i, (math.floor(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 function Binary.readRefs(b, p, limit, n) 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 =acc+ out[i] out[i] = acc end return out, p + 4 * n end function Binary.writeRefs(w, refs) local d = table.create(#refs, 0) local prev = 0 for i, r in __iter(refs) do d[i] = r - prev prev = r end putI32s(w, d) end local function str(b, p, limit) 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 local function cframes(b, p, limit, n) local rots= (table.create(n) ) for i = 1, n do if p >= limit then return nil, p end local id = readu8(b, p) 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 =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= { [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, } function Binary.decode(t, b, p, limit, n, ctx) 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 = t == 0x0D and 2 or(t == 0x18 and 4 or 3 ) local cols= (table.create(k) ) 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 = t == 0x0F and 2 or 3 local out = table.create(n) for i = 1, n do local q = p + 2 * k * (i - 1) out[i] = k == 2 and{ readi16(b, q), readi16(b, q + 2) } or{ 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, q == -1 and"corrupt: bad CFrame rotation id" or"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] = (ref and refs[i] >= 0 and{(ref(refs[i]) )}or{nil })[1] end return out, q elseif t == 0x15 or t == 0x16 then local k = t == 0x15 and 3 or 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 =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 =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 =p+ 1 if flag % 2 == 1 then local k = math.floor(flag / 2 )% 2 == 1 and 6 or 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 =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= ctx.shared or {} local out= 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, q == -1 and"corrupt: bad CFrame rotation id" or"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] = (readu8(b, q + i) ~= 0 and{cfs[i] }or{nil })[1] 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] = math.floor(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 - (k > 4 and 8 or 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 = style == 1 and"Italic" or"Normal", cachedFaceId = (face ~= "" and{face }or{nil })[1]} 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 =p+ 4 * n if p + 4 > limit then return nil, "truncated content" end local nu = readu32(b, p) 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 =iu+ 1 elseif k == 2 then if io > no then return nil, "corrupt: content object count" end local r = objs[io] out[i] = (ctx.ref and r >= 0 and{(ctx.ref(r) )}or{nil })[1] io =io+ 1 elseif k ~= 0 then return nil, "unknown" end end return out, p end return nil, "unknown" end local function num(v) return (type(v) == "number" and v == v and{v }or{0 })[1]end local function column(vals, n, c) local out = table.create(n, 0) for i = 1, n do local v = vals[i] out[i] = (type(v) == "table" and{(num(v[c]) )}or{0 })[1] end return out end local function putString(w, s) w:u32le(#s) w:string(s) end local function putCFrames(w, vals, n) for i = 1, n do local v = vals[i] local cf = (type(v) == "table" and{v }or{{ 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1 } })[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 local function hexByte(s, i) return tonumber(string.sub(s, 2 * i - 1, 2 * i), 16) or 0 end function Binary.encode(t, vals, n, w, ctx) if t == 0x01 or t == 0x1D then for i = 1, n do local v = vals[i] putString(w, (type(v) == "string" and{v }or{""})[1]) end elseif t == 0x02 then for i = 1, n do w:u8(vals[i] and 1 or 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((type(v) == "table" and{(num(v[c]) )}or{0})[1]) 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 = t == 0x0D and 2 or(t == 0x18 and 4 or 3 ) for c = 1, k do putF32s(w, column(vals, n, c)) end elseif t == 0x0F or t == 0x14 then local k = t == 0x0F and 2 or 3 for i = 1, n do local v = vals[i] for c = 1, k do local x = floor((type(v) == "table" and{(num(v[c]) )}or{0})[1]) % 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] = (refOf and vals[i] ~= nil and{(refOf(vals[i]) )}or{(-1 )})[1] end Binary.writeRefs(w, refs) elseif t == 0x15 or t == 0x16 then local k = t == 0x15 and 3 or 5 for i = 1, n do local seq = vals[i] if type(seq) ~= "table" then seq = {} end w:u32le(#seq) for _, key in __iter(seq) do for c = 1, k do w:f32le((type(key) == "table" and{(num(key[c]) )}or{0})[1]) end end end elseif t == 0x17 then for i = 1, n do local v = vals[i] w:f32le((type(v) == "table" and{(num(v[1]) )}or{0})[1]) w:f32le((type(v) == "table" and{(num(v[2]) )}or{0})[1]) 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(acoustic and 3 or 1) for c = 1, acoustic and 6 or 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((type(v) == "table" and{(num(v[c]) )}or{0})[1]), 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] = (si and{(si((type(v) == "string" and{v }or{""})[1]) )}or{0 })[1] 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(type(vals[i]) == "table" and 1 or 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 = math.floor(hexByte(s, 1) / 128 ) for k = 1, 8 do local v = hexByte(s, k) local nxt = (k < 8 and{(math.floor(hexByte(s, k + 1) / 128 ))}or{top })[1] 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, (type(v.family) == "string" and{v.family }or{""})[1]) w:u16le(math.clamp(floor(num(v.weight)), 0, 65535)) w:u8(v.style == "Italic" and 1 or 0) putString(w, (type(v.cachedFaceId) == "string" and{v.cachedFaceId }or{""})[1]) 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, (refOf and{(refOf(v) )}or{(-1)})[1]) end end putI32s(w, kinds) w:u32le(#uris) for _, s in __iter(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() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict -- 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 function Rig.morph(prim, frames, normals) 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= {} local ok = true for k, f in __iter(frames) do if buffer.len(f) < n * 4 then ok = false break end local t= {} 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, node, targets, ranges, interpolation) for _, rg in __iter(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 = (rg.fps and rg.fps > 0 and{rg.fps }or{10 })[1] 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" , input = Scene.accessor(times, "f32", 1, keys), output = Scene.accessor(weights, "f32", 1, keys * targets), interpolation = (interpolation == "STEP" and"STEP" or"LINEAR") , }, }, }) end end end -- Quake's precomputed normal table is not redistributable here function Rig.normals(pos, count, indices) 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 __iter({ a, b, c }) do do local __DARKLUA_VAR=v * 3 + 1 acc[__DARKLUA_VAR]=acc[__DARKLUA_VAR]+ nx end do local __DARKLUA_VAR0=v * 3 + 2 acc[__DARKLUA_VAR0]=acc[__DARKLUA_VAR0]+ ny end do local __DARKLUA_VAR1=v * 3 + 3 acc[__DARKLUA_VAR1]=acc[__DARKLUA_VAR1]+ nz end 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) 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, y, z) 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, joints, space, root) local n = #joints local world= {} local nodes= {} for i, j in __iter(joints) do local p = (j.parent >= 1 and j.parent < i and{j.parent }or{0 })[1] 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] = (p > 0 and{(Mat4.mul(world[p], m) )}or{m })[1] end local node= { name = j.name, children = {}, translation = table.clone(lt), rotation = table.clone(lr), scale = (ls and{(table.clone(ls) )}or{nil })[1]} 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 = (n > 0 and{nodes[1] }or{nil })[1]}) return nodes, #scene.skins, world end function Rig.influences(lists) local n = #lists local jb, wb = buffer.create(n * 8), buffer.create(n * 16) for v, l in __iter(lists) do local pairs_= {} local at= {} for k = 1, #l - 1, 2 do if l[k + 1] > 0 then local same = at[l[k] ] if same then same[2]=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, b) return a[2] > b[2] end) local sum = 0 for k = 1, math.min(4, #pairs_) do sum =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, count, comps) 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, name, nodes, times, tracks, interpolation) local count = #times local input = floats(times, count, 1) local channels= {} local interp= interpolation == "STEP" and"STEP" or"LINEAR" if input then for j, tr in __iter(tracks) do local node = nodes[j] if node then for _, path in __iter({ "translation", "rotation", "scale" }) do local keys = (tr )[path] local acc = keys and floats(keys, count, path == "rotation" and 4 or 3) if acc then table.insert(channels, { node = node, path = path , 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() local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict -- codecs/model/Sampler: Scene animation sampling, STEP / LINEAR (slerp) / CUBICSPLINE as in glTF 2.0 animations. New code. local Types = __include("Types") local Sampler = {} local function normalize(q) 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, b, s) 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) 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 = cubic and 3 or 1 local comps if ch.path == "weights" then comps = math.floor((out.count * out.components) / (n * per) ) else comps = ch.path == "rotation" and 4 or 3 end if comps < 1 or out.count * out.components < n * per * comps then return nil end local times = (table.create(n) ) for k = 1, n do times[k] = IN(k - 1, 0) end local oc = out.components local function get(e) local v = (table.create(comps) ) for c = 0, comps - 1 do local flat = e * comps + c v[c + 1] = OUT(math.floor(flat / oc), flat % oc) end return v end local function value(k) return get((cubic and(((k - 1) * 3 + 1 ))or((k - 1)))) end local rot = ch.path == "rotation" local step = ch.interpolation == "STEP" return function(t) if t <= times[1] or n == 1 then return (rot and{(normalize(value(1)) )}or{(value(1) )})[1] end if t >= times[n] then return (rot and{(normalize(value(n)) )}or{(value(n) )})[1] end local lo, hi = 1, n while hi - lo > 1 do local mid = math.floor((lo + hi) / 2 ) if times[mid] <= t then lo = mid else hi = mid end end local dt = times[hi] - times[lo] local s = (dt > 0 and(((t - times[lo]) / dt ))or(0 )) if step then return (rot and{(normalize(value(lo)) )}or{(value(lo) )})[1] 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) ) for c = 1, comps do v[c] = h00 * p0[c] + h10 * dt * m0[c] + h01 * p1[c] + h11 * dt * m1[c] end return (rot and{(normalize(v) )}or{v })[1] end local a, b = value(lo), value(hi) if rot then return slerp(normalize(a), normalize(b), s) end local v = (table.create(comps) ) for c = 1, comps do v[c] = a[c] + (b[c] - a[c]) * s end return v end end function Sampler.times(anim) local seen= {} local out= {} for _, ch in __iter(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, anim, t, samplers) local cache= samplers or {} local pose= {} for _, ch in __iter(anim.channels) do if cache[ch] == nil then cache[ch] = Sampler.channel(ch) or false end local s= 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() local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict -- 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 = {} local function text(data, maxBytes) local b = (type(data) == "string" and{(buffer.fromstring(data) )}or{data })[1] 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) 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) 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) 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, "", 1, true) then -- VTK's X3D exporter leaves the root element open d = XmlCodec.decode(src .. "\n\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, opts) 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) return function(uri) if not opts then return nil end local v= 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 = (ok and{res }or{nil })[1] end return (type(v) == "string" and{(buffer.fromstring(v) )}or{(type(v) == "buffer" and{v }or{nil })[1]})[1] end end function Vrml.build(graph, opts) local o= table.clone(opts or {}) o.fetch = o.fetch or Vrml.fetcher(opts) o.load = o.load or function(data) local g, err = Vrml.graph(data, opts) return g, (err and{err.message }or{nil })[1] 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, opts) 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, opts) 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() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict -- 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 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) return Mat4.axisAngle(r[1], r[2], r[3], deg(r[4])) end local function qmul(a, b) 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, v) 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) return v[1] == 0 and v[2] == 0 and v[3] == 0 end local function isIdentityQ(q) return q[1] == 0 and q[2] == 0 and q[3] == 0 end local function between(a, b) 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 math.abs(a[1]) < 0.9 and{ 0, a[3], -a[2], 0 } or{ -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 local function addNode(ctx, n, parent) 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, t) 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= { 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 __iter(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 = (ext and{MIME[string.lower(ext)] }or{nil })[1] 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 =math.floor(px/ 256 ) end local r, g, bl, a if c <= 2 then r, g, bl, a = b[1], b[1], b[1], (c == 2 and{b[2] }or{255 })[1] else r, g, bl, a = b[1], b[2], b[3], (c == 4 and{b[4] }or{255 })[1] end -- the image's first row is the bottom one local row = h - 1 - math.floor(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 = rs and"repeat" or"clamp", wrapT = rt and"repeat" or"clamp" } end table.insert(ctx.scene.textures, tex) ctx.textures[t] = #ctx.scene.textures return #ctx.scene.textures end local function textureRef(ctx, t, xf) local i = texture(ctx, t) if not i then return nil end local ref= { 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, app, solid) 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 )[solid] if hit then return hit end local m = S.material(app and app.def) m.metallic = 0 local x= {} 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= { baseTexture = "baseColorTexture", metallicRoughnessTexture = "metallicRoughnessTexture", normalTexture = "normalTexture", occlusionTexture = "occlusionTexture", emissiveTexture = "emissiveTexture" } for field, slot in __iter(slots) do local t = node(mat, field) if t then (m )[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 )[solid] = idx return idx end local walk local function shape(ctx, n, parent) 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 return end local count = (prim.indices and{prim.indices.count }or{prim.attributes.POSITION.count })[1] 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, n, parent) local cam 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= { 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, n, parent) local t = n.type local l= { name = n.def, type = "point", color = vec(n, "color", { 1, 1, 1 }), intensity = num(n, "intensity", 1) } local nd= { name = n.def, children = {} } local x= { 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 ).extras = { vrml = x } table.insert(ctx.scene.lights, l) nd.light = #ctx.scene.lights addNode(ctx, nd, parent) end local function children(ctx, n, parent) 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 __iter(CHILDREN) do for _, c in __iter(nodes(n, f)) do walk(ctx, c, parent) end end end local function transform(ctx, n, parent) 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= { 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 = (isIdentityQ(qs) and{qr }or{(qmul(qr, qs) )})[1] 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= { 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, n, parent) 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 __iter(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 =ctx.inline+ 1 for _, root in __iter(g.roots) do walk(ctx, root, holder) end ctx.inline =ctx.inline- 1 return end end end ctx.skipped.Inline = (ctx.skipped.Inline or 0) + 1 end function walk(ctx, n, parent) if ctx.failure or type(n) ~= "table" then return end ctx.depth =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 __iter(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 src.title = str(n, "title") local info = strs(n, "info") src.info = (#info > 0 and{info }or{nil })[1] elseif not QUIET[t] then ctx.skipped[t] = (ctx.skipped[t] or 0) + 1 end ctx.depth =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, routes) local timer= {} for _, r in __iter(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= {} local order= {} for _, r in __iter(routes) do local __DARKLUA_CONTINUE_11=false repeat 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 __DARKLUA_CONTINUE_11=true break end if (path == "rotation") ~= (it.type == "OrientationInterpolator") then __DARKLUA_CONTINUE_11=true break end local key, kv= nums(it, "key") or {}, nums(it, "keyValue") or {} local comps = path == "rotation" and 4 or 3 local n = math.min(#key, math.floor(#kv / comps)) if n == 0 then __DARKLUA_CONTINUE_11=true break end local ts = timer[it] local cycle = (ts and{(num(ts, "cycleInterval", 1) )}or{1 })[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 = (ts and{ts.def }or{nil})[1], channels = {} } anims[id] = anim table.insert(order, id) end for _, at in __iter(inst) do local out = S.accessor(nil, "f32", path == "rotation" and 4 or 3, n) local prev= nil for i = 0, n - 1 do local v 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 , input = input, output = out, interpolation = "LINEAR" }) end __DARKLUA_CONTINUE_11=true until true if not __DARKLUA_CONTINUE_11 then break end end for _, id in __iter(order) do table.insert(ctx.scene.animations, anims[id]) end end function Build.scene(graph, opts) local scene = S.new() scene.meta.up = "y" local units = graph.units or {} scene.meta.unit = (units.length and units.length.factor > 0 and{units.length.factor }or{1 })[1] local h = graph.header or {} local skipped= {} 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= { scene = scene, opts = opts, meshes = {}, materials = {}, textures = {}, instances = {}, skipped = skipped, depth = 0, inline = 0, failure = nil } for _, n in __iter(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() local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict -- 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) local out = {} local p = find(s, "[^%s,]") if not p or byte(s, p) ~= 34 then return p and{ ((string.match(s, "^%s*(.-)%s*$") )) } or{} 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, name) local v = node.fields[name] if v == nil then return nil end if type(v) == "string" then local out = {} for w in __iter(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 __iter(v) do if type(x) ~= "number" then ok = false break end end if ok then return v end local out = {} for _, x in __iter(v) do if type(x) == "number" then table.insert(out, x) elseif type(x) == "boolean" then table.insert(out, x and 1 or 0) end end return out end function Fields.num(node, name, default) local v = Fields.nums(node, name) return (v and type(v[1]) == "number" and{v[1] }or{default })[1]end function Fields.vec(node, name, default) local v = Fields.nums(node, name) if not v or #v < #default then return default end local out= {} for i = 1, #default do out[i] = v[i] end return out end function Fields.bool(node, name, default) local v = node.fields[name] if type(v) == "string" then local w = string.lower((string.match(v, "^%s*(%S*)") )) return w == "true" and true or(w == "false" and{false }or{default })[1] end if type(v) == "table" and type(v[1]) == "boolean" then return v[1] end return default end function Fields.strs(node, name) 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 __iter(v) do if type(x) == "string" then table.insert(out, x) end end end return out end function Fields.str(node, name, default) 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, name) local v = node.fields[name] local out = {} if type(v) == "table" then for _, x in __iter(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, name) return Fields.nodes(node, name)[1] end return Fields end __FILES["codecs/model/Vrml/Geometry"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict -- 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 local function f32(list, comps, count) 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) local a = S.accessor(nil, "u32", 1, #list) for i, v in __iter(list) do buffer.writeu32(a.data, (i - 1) * 4, v) end return a end local function colors(n) local c = node(n, "color") if not c then return nil, 3 end local comps = c.type == "ColorRGBA" and 4 or 3 return nums(c, "color") or {}, comps end local function points(n, field, sub) local c = node(n, field) return (c and{nums(c, sub) or {} }or{nil })[1]end local function polyMesh(m, o, maxV) local P, corners, sizes = m.P, m.corners, m.sizes local np = math.floor(#P / 3 ) local N, C, T = m.N, m.C, m.T local cc = m.cComps or 3 local function idx(list, perFace, f, k, c) if perFace then return (list and #list > 0 and{(list[f] or 0) }or{(f - 1 )})[1] end return (list and #list > 0 and{(list[k] or c) }or{c })[1] 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= {} local vsrc= {} local out= {} local outSizes= {} local k = 0 for f, size in __iter(sizes) do local face= {} local valid = size >= 3 for q = 1, size do k =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= {} for q, kk in __iter(face) do local c = corners[kk] if simple then verts[q] = c else local ni = (N and{(idx(m.nIdx, m.nFace, f, kk, c) )}or{(-1 )})[1] local ci = (C and{(idx(m.cIdx, m.cFace, f, kk, c) )}or{(-1 )})[1] local ti = (T and{(idx(m.tIdx, false, f, kk, c) )}or{(-1 )})[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, math.floor((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 __iter(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 = (simple and{np }or{(#vsrc )})[1] 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 = (N and{(S.accessor(nil, "f32", 3, nv) )}or{nil })[1] local col = (C and{(S.accessor(nil, "f32", cc, nv) )}or{nil })[1] local tex = (T and{(S.accessor(nil, "f32", 2, nv) )}or{nil })[1] local wf = buffer.writef32 for v = 0, nv - 1 do local s = (simple and{nil }or{vsrc[v + 1] })[1] local c = (s and{s[1] }or{v })[1] 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 = (s and{s[2] }or{v })[1] 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 = (s and{s[3] }or{v })[1] 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 = (s and{s[4] }or{v })[1] 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, (flipV and((1 - tt ))or(tt))) end end local attrs= { POSITION = pos } attrs.NORMAL, attrs.COLOR_0, attrs.TEXCOORD_0 = nrm, col, tex local prim= { 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) local corners, sizes = {}, {} local run = 0 for _, x in __iter(list) do if x < 0 then if run > 0 then table.insert(sizes, run) end run = 0 else table.insert(corners, x) run =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) if not list or #list == 0 then return nil end local out = {} for _, x in __iter(list) do if x >= 0 then table.insert(out, x) end end return out end local function faceSet(n, o, maxV) 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= { P = P, corners = corners, sizes = sizes, ccw = bool(n, "ccw", true), N = points(n, "normal", "vector"), nFace = not nPer, nIdx = (nPer and{(cornerList(nums(n, "normalIndex")) )}or{(nums(n, "normalIndex"))})[1], C = C, cComps = cc, cFace = not cPer, cIdx = (cPer and{(cornerList(nums(n, "colorIndex")) )}or{(nums(n, "colorIndex"))})[1], T = (tc and tc.type ~= "TextureCoordinateGenerator" and{(nums((tc.type == "MultiTextureCoordinate" and{(node(tc, "texCoord") or tc) }or{tc})[1], "point") or {}) }or{nil})[1], tIdx = cornerList(nums(n, "texCoordIndex")), } return polyMesh(m, o, maxV) end local function triSet(n, o, maxV) local t = n.type local P = points(n, "coord", "point") or {} local np = math.floor(#P / 3 ) local index = nums(n, "index") local seq 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, b, c) 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() local out = {} local counts = nums(n, string.find(t, "Fan", 1, true) and"fanCount" or"stripCount") if string.sub(t, 1, 7) == "Indexed" or not counts then local cur = {} for _, x in __iter(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 __iter(counts) do local cur = {} for q = 0, c - 1 do cur[q + 1] = seq[at + q] end at =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 __iter(runs()) do for i = 2, #r - 1 do tri(r[1], r[i], r[i + 1]) end end else for _, r in __iter(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= { 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 = (tc and tc.type == "TextureCoordinate" and{nums(tc, "point") or {} }or{nil})[1], } return polyMesh(m, o, maxV) end local function elevationGrid(n, o, maxV) 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= 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, T, corners, sizes= {}, {}, {}, {} 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 __iter({ 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= { 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 = (tc and{nums(tc, "point") or {} }or{T})[1], } return polyMesh(m, o, maxV) end local function cross(a, b) 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, b) return { a[1] - b[1], a[2] - b[2], a[3] - b[3] } end local function norm(a) local l = sqrt(a[1] * a[1] + a[2] * a[2] + a[3] * a[3]) return l > 1e-12 and{ a[1] / l, a[2] / l, a[3] / l } or{ 0, 0, 0 }, l end -- rotate v about the unit axis k by angle a (Rodrigues) local function rotate(v, k, a) 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, o, maxV) 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 = math.floor(#sp / 3), math.floor(#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, b) 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, Zs= {}, {} for i = 1, ns do local prev = (i > 1 and{spine[i - 1] }or{(closedSpine and{spine[ns - 1] }or{nil })[1]})[1] local nxt = (i < ns and{spine[i + 1] }or{(closedSpine and{spine[2] }or{nil })[1]})[1] 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] = (l > 1e-12 and{z }or{nil })[1] 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] = (l > 1e-12 and{(rotate({ 0, 0, 1 }, axis, ang) )}or{y[2] < 0 and{ 0, 0, -1 } or{ 0, 0, 1 } })[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 = (closedSpine and((ns - 1 ))or(ns )) local nring = (closedCs and((nc - 1 ))or(nc )) local P = {} for i = 1, nr do local y, z = Ys[i], Zs[i] local x = cross(y, z) local si = (#sc >= i * 2 and{i }or{1 })[1] local sx, sz = sc[si * 2 - 1] or 1, sc[si * 2] or 1 local oi = (#ori >= i * 4 and{i }or{1 })[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, j) return ((i - 1) % nr) * nring + (j - 1) % nring end for i = 1, ns - 1 do for j = 1, nc - 1 do for _, c in __iter({ 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, maxV) local P = points(n, "coord", "point") or {} local np = math.floor(#P / 3 ) local C, cc = colors(n) local perVertex = bool(n, "colorPerVertex", true) local runs= {} if n.type == "LineSet" then local at = 0 for _, c in __iter(nums(n, "vertexCount") or {}) do local r = {} for q = 0, c - 1 do r[q + 1] = at + q end at =at+ c table.insert(runs, r) end else local corners, sizes = split(nums(n, "coordIndex") or {}) local k = 0 for _, s in __iter(sizes) do local r = {} for q = 1, s do r[q] = corners[k + q] end k =k+ s table.insert(runs, r) end end local cIdx = nums(n, "colorIndex") or {} local cList = (perVertex and{(cornerList(cIdx) )}or{nil })[1] local vkey= {} local src= {} local out= {} local k = 0 for li, r in __iter(runs) do local prev= nil for _, c in __iter(r) do local __DARKLUA_CONTINUE_48=false repeat k =k+ 1 if c == nil or c < 0 or c >= np then prev = nil __DARKLUA_CONTINUE_48=true break end local ci = not C and-1 or(perVertex and{((cList and{cList[k] or c }or{c})[1]) }or{(cIdx[li] or li - 1) })[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 __DARKLUA_CONTINUE_48=true until true if not __DARKLUA_CONTINUE_48 then break end end end if #src > maxV then return nil, "limit: more than " .. maxV .. " vertices" end local pos = S.accessor(nil, "f32", 3, #src) local col = (C and{(S.accessor(nil, "f32", cc, #src) )}or{nil })[1] for v, s in __iter(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 } , indices = u32(out), mode = "lines" } end local function pointSet(n, maxV) local P = points(n, "coord", "point") or {} local np = math.floor(#P / 3 ) if np > maxV then return nil, "limit: more than " .. maxV .. " points" end local C, cc = colors(n) local attrs= { 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, N, T, I, o) local nv = math.floor(#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, o) 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 __iter(FACES) do local nn, u, v = face[1], face[2], face[3] for _, c in __iter({ { -1, -1 }, { 1, -1 }, { 1, 1 }, { -1, 1 } }) do for q = 1, 3 do local h = (q == 1 and{hx }or{(q == 2 and{hy }or{hz })[1]})[1] 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 __iter({ 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, N, T, segs, y, r, t, ny, nr) 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, N, T, I, segs, y, r, ny) local b = math.floor(#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, ((ny > 0 and{(-z )}or{z})[1]) / 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, a, b, segs) 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, o, segs) local r = num(n, "radius", 1) local rings = math.max(2, math.floor(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, o, segs, cone) local r = num(n, cone and"bottomRadius" or"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 = (cone and l > 0 and((r / l ))or(0)), (cone and l > 0 and((h / l ))or(1 )) ring(P, N, T, segs, -h / 2, r, 0, ny, nr) ring(P, N, T, segs, h / 2, cone and 0 or 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, o) 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, err= 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() local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict -- 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 = {} 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, values, defaults, memo) local done = memo[node] if done then return done end local out= { type = node.type, def = node.def, fields = {} } memo[node] = out for k, v in __iter(node.fields) do if type(v) == "table" and type((v ).is) == "string" then local name = (v ).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 __iter(v) do arr[i] = (type(x) == "table" and x.type and{(copy(x, values, defaults, memo) )}or{x })[1] end out.fields[k] = arr else out.fields[k] = v end end return out end function Parse.expand(proto, values, def, routes) if proto.extern or #proto.body == 0 then return nil end local memo = {} local first= nil for _, n in __iter(proto.body) do local c = copy(n, values, proto.fields, memo) first = first or c end if routes then for _, r in __iter(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 if def then -- the instance gets its own copy of the node so its DEF name is its own local out= { type = f.type, def = def, fields = f.fields } return out end return f end function Parse.parse(text) local n = #text local p = 1 local graph= { roots = {}, routes = {}, header = {}, meta = {}, components = {}, units = {}, protos = {} } local defs= {} local protos= graph.protos local routes= graph.routes local failure= nil local depth = 0 local function line(at) local l = 1 for _ in __iter(gmatch(sub(text, 1, at), "\n")) do l =l+ 1 end return l end local function fail(msg) 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 = (e and{e }or{(n + 1 )})[1] else return end end end local function token() 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 =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 ) + 1 return "num", num end if c == 46 then p =p+ 1 return ".", nil end local _, we = find(text, "^[^%s,%[%]{}#\"]+", p) local w = sub(text, p, we) p = (we ) + 1 local wl = string.lower(w) local val = (find(wl, "inf", 1, true) and{((c == 45 and{(-math.huge )}or{math.huge})[1]) }or{find(wl, "nan", 1, true) and 0 or nil })[1] 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 ) + 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() local save = p local k, val = token() p = save return k, val end local parseNode local parseProto local parseRoute local function value() 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 __iter(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 local __DARKLUA_CONTINUE_9=false repeat 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 __DARKLUA_CONTINUE_9=true break 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 __DARKLUA_CONTINUE_9=true until true if not __DARKLUA_CONTINUE_9 then break 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 node and{ node } or{} end fail("missing field value") return {} end local function body(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: [ | IS ] 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) 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= 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 =depth+ 1 if depth > MAX_DEPTH then fail("limit: nodes nested deeper than " .. MAX_DEPTH) return nil, false end local node= { type = typ, def = def, fields = {} } body(node) depth =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 ).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() 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 ], defs[b ] if from and dst then table.insert(routes, { from = from, fromField = af , to = dst, toField = bf }) end end -- PROTO name [ interface ] { body } / EXTERNPROTO name [ interface ] url function parseProto(extern) local k, name = token() if k ~= "id" or token() ~= "[" then fail("bad PROTO") return end local 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() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict -- 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 = {} local format, concat = string.format, table.concat local function fmt(v) 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, def) return { type = t, def = def, fields = {} } end local function F(n, name, kind, value, per) table.insert(n.fields, { name, kind, value, per }) end local function namer() local used= {} return function(name, fallback) local s = string.gsub(name or "", "[^%w_]", "_") if s == "" or string.find(s, "^%d") then s = fallback .. ((s ~= "" and(("_" .. s ))or(""))) end local base, k = s, 1 while used[s] do k =k+ 1 s = base .. "_" .. k end used[s] = true return s end end local function axisAngle(q) 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) return (Flatten.numbers(acc)) end local function faceSet(prim, doubleSided, o, x3d) local tmp = { kind = "scene", nodes = {}, roots = {}, meshes = { { primitives = { prim } } } } local keep = function(n) 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 __iter(m.sizes) do for k = 1, s do table.insert(idx, m.corners[p + k]) end table.insert(idx, -1) p =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, (o.flipV ~= false and((1 - tt ))or(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(rgba and"ColorRGBA" or"Color") local vals = {} local scale = (col.raw and{(col.type == "unorm8" and 255 or(col.type == "unorm16" and 65535 or 1)) }or{1 })[1] for i = 0, m.count - 1 do for k = 1, rgba and 4 or 3 do table.insert(vals, (col.values[i * c + k] or 1) / scale) end end F(cn, "color", "mf", vals, rgba and 4 or 3) F(g, "color", "node", cn) end F(g, "solid", "bool", not doubleSided) return g, nil end local function coordNode(prim) 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, nv, x3d) 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, rgba and 4 or 3 do table.insert(vals, col[i * c + k] or 1) end end local cn = W(rgba and"ColorRGBA" or"Color") F(cn, "color", "mf", vals, rgba and 4 or 3) return cn end local function lineSet(prim, x3d) local coord, nv = coordNode(prim) if not coord then return nil, "lines without POSITION" end local ind 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 __iter(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 __iter(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, x3d) 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, i, o, written) 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 = (url and not string.find(url, "^data:") and not string.find(url, "[/\\]") and{url }or{(format("%s_%d.%s", base, i, ext) )})[1] o.files[file] = tex.data url = file end if url then written[i] = url end return url end local function appearance(scene, mi, o, written) 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 + (math.floor(p / 256 )% 256) * 65536 + (math.floor(p / 65536 )% 256) * 256 + math.floor(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, o) local x3d = o.encoding == "x3dv" or o.encoding == "xml" local name = namer() local nodeDef= {} local meshShapes= {} local appDef= {} local written= {} local failure= nil local function shapes(mi) local done = meshShapes[mi] if done then local out = {} for _, s in __iter(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 __iter(((mesh and{mesh.primitives }or{{}})[1])) do local mode = prim.mode or "triangles" local mat = (type(prim.material) == "number" and{scene.materials[prim.material] }or{nil })[1] 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") .. ((#mesh.primitives > 1 and(("_" .. pi ))or(""))), "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= {} local function transform(ni) 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= {} if type(n.mesh) == "number" then for _, s in __iter(shapes(n.mesh)) do table.insert(kids, s) end end local cam = (type(n.camera) == "number" and{scene.cameras[n.camera] }or{nil })[1] 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 = (type(n.light) == "number" and{scene.lights[n.light] }or{nil })[1] if l then local typ = l.type == "directional" and"DirectionalLight" or(l.type == "spot" and"SpotLight" or"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 __iter(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= {} local list = scene.roots if type(list) ~= "table" or #list == 0 then local child = {} for _, n in __iter(scene.nodes) do for _, c in __iter(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 __iter(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 __iter(shapes(mi)) do table.insert(roots, s) end end end local routes= {} for ai, anim in __iter(scene.animations or {}) do local tmax = 0 local chans = {} for _, ch in __iter(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 = (tmax > 0 and{tmax }or{1 })[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 __iter(chans) do local ch, target, input, output = c[1], c[2], c[3], c[4] local rot = ch.path == "rotation" local it = W(rot and"OrientationInterpolator" or"PositionInterpolator", name(ts.def .. "_" .. k, "Interpolator")) local keys = {} for i, tv in __iter(input) do keys[i] = tv / cycle end local comps = rot and 4 or 3 local stride = math.floor(#output / #input ) -- CUBICSPLINE stores in-tangent, value, out-tangent per key local off = (ch.interpolation == "CUBICSPLINE" and stride == comps * 3 and{comps }or{0 })[1] 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 __iter(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 , "fraction_changed", it.def , "set_fraction" }) table.insert(routes, { it.def , "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, per, indent) local out = table.create(#vals) for i, v in __iter(vals) do out[i] = fmt(v) end if per == 0 then local lines, cur = {}, {} for i, v in __iter(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) return '"' .. string.gsub(s, '(["\\])', "\\%1") .. '"' end local function classic(roots, routes, x3d) 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, ind) if n.use then return "USE " .. n.use end local parts = { ((n.def and(("DEF " .. n.def .. " " ))or(""))) .. n.type .. " {" } local ind2 = ind .. " " for _, f in __iter(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 = v and"TRUE" or"FALSE" elseif kind == "str" then s = quote(v) elseif kind == "mstr" then local q = {} for i, x in __iter(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 __iter(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 __iter(roots) do table.insert(out, emit(r, "")) end for _, r in __iter(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, routes) local function element(n, field) 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 ) end if n.def then Types.set(attrs, "DEF", n.def) end for _, f in __iter(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, v and"true" or"false") elseif kind == "str" then Types.set(attrs, fname, v) elseif kind == "mstr" then local q = {} for i, x in __iter(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 __iter(v) do table.insert(kids, element(x, fname)) end end end return Xml.element(n.type, attrs , kids) end local sceneKids = {} for _, r in __iter(roots) do table.insert(sceneKids, element(r, "children")) end for _, r in __iter(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 )) 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 , { Xml.element("head", nil, { Xml.element("meta", meta ) }), 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, (err and{err.message }or{"xml" })[1] end return s, nil end function Write.text(scene, o) 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() local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict -- 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= { 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 __iter(GEOMETRY) do CONTAINER[g] = "geometry" end local function container(el, typ) 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) local root = doc.root or doc if type(root) ~= "table" or Xml.localName(root.name) ~= "X3D" then return nil, "no root element" end local 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= {} local protos = graph.protos local routes = graph.routes local depth = 0 local failure= nil local convert local function route(el) 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 local function children(el, node) for _, ch in __iter(el.children) do local __DARKLUA_CONTINUE_2=false repeat if type(ch) ~= "table" or string.sub(ch.name, 1, 1) == "#" then __DARKLUA_CONTINUE_2=true break end local name = Xml.localName(ch.name) if name == "ROUTE" then route(ch) elseif name == "IS" then for _, c in __iter(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 __DARKLUA_CONTINUE_2=true break -- Script / shader interfaces else local c = convert(ch) if c then local f = container(ch, name == "ProtoInstance" and"" or name) local list = node.fields[f] if type(list) ~= "table" or (list ).is then list = {} node.fields[f] = list end table.insert(list, c) end end __DARKLUA_CONTINUE_2=true until true if not __DARKLUA_CONTINUE_2 then break end end end local function fieldValue(el) if el.attrs.value ~= nil then return el.attrs.value end local list = {} for _, ch in __iter(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, extern) local name = el.attrs.name if not name then return end local proto= { name = name, fields = {}, body = {}, routes = {}, extern = extern or nil } local iface = (extern and{el }or{(Xml.child(el, "ProtoInterface") )})[1] if iface then for _, f in __iter(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 __iter(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) local a = el.attrs if a.USE then return defs[a.USE] end depth =depth+ 1 if depth > 200 then failure = failure or "limit: nodes nested deeper than 200" depth =depth- 1 return nil end local typ = Xml.localName(el.name) local node if typ == "ProtoInstance" then local proto = protos[a.name or ""] local values = {} for _, fv in __iter(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 __iter(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 =depth- 1 if a.DEF then defs[a.DEF] = node end return node end for _, ch in __iter(root.children) do local __DARKLUA_CONTINUE_9=false repeat if type(ch) ~= "table" then __DARKLUA_CONTINUE_9=true break end local name = Xml.localName(ch.name) if name == "head" then for _, h in __iter(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= { type = "Scene", fields = {} } children(ch, scene) local list = scene.fields.children if type(list) == "table" then graph.roots = list end for f, v in __iter(scene.fields) do -- a top-level node with another containerField still shows if f ~= "children" and type(v) == "table" then for _, x in __iter(v) do table.insert(graph.roots, x) end end end end __DARKLUA_CONTINUE_9=true until true if not __DARKLUA_CONTINUE_9 then break end end if failure then return nil, failure end return graph, nil end return VXml end __FILES["codecs/text/GodotVariant"] = function() local __compat = __compat local buffer, utf8, type, __iter = __compat.buffer, __compat.utf8, __compat.type, __compat.__iter --!strict -- codecs/text/GodotVariant: Godot's text resource syntax (.tscn / .tres / .escn, formats 2-4; Godot's -- variant_parser.cpp and resource_format_text.cpp): [section key=value ...] headers with `key = value` properties, -- and the Variant text syntax (numbers, strings, &"StringName", ^"NodePath", arrays, dictionaries, constructors such -- as Vector3(...), Transform3D(...), PackedFloat32Array(...), SubResource("id"), Object(Class, "k": v)). -- Constructor values are { type, args } tables (GodotVariant.isCtor); dictionaries keep their key order. local Types = __include("Types") local Base64 = __include("core/Base64") local GodotVariant = {} GodotVariant.null = Types.null local CTOR = { __godot = true } -- integral numbers written as floats ("1.0"): Godot keeps int and float apart (Curve._data mixes them), so the keys -- holding them are remembered per container (array, dictionary, property table) and written back with ".0" local FLOATS= (setmetatable({}, { __mode = "k" }) ) local lastFloat = false local function mark(t, k, v) if lastFloat and type(v) == "number" and v == math.floor(v) then local m = FLOATS[t] if not m then m = {} FLOATS[t] = m end m[k] = true end end function GodotVariant.isFloat(t, k) local m = FLOATS[t] return m ~= nil and m[k] == true end function GodotVariant.markFloat(t, k) local m = FLOATS[t] if not m then m = {} FLOATS[t] = m end m[k] = true end function GodotVariant.copyFloats(from, to) local m = FLOATS[from] if m then FLOATS[to] = table.clone(m) end end function GodotVariant.ctor(name, args) return (setmetatable({ type = name, args = args or {} }, CTOR) ) end function GodotVariant.isCtor(v) return type(v) == "table" and getmetatable(v) == CTOR end -- the numbers of a constructor, or nil when an argument is not a number function GodotVariant.numbers(v, name) if not GodotVariant.isCtor(v) or (name and v.type ~= name) then return nil end for _, x in __iter(v.args) do if type(x) ~= "number" then return nil end end return v.args end -- PackedByteArray(1, 2, ...) or PackedByteArray("base64") (Godot 4.3+), PoolByteArray / ByteArray (format 2) function GodotVariant.bytes(v) if not GodotVariant.isCtor(v) then return nil end local a = v.args if #a == 1 and type(a[1]) == "string" then return (Base64.decode(a[1])) end local b = buffer.create(#a) for i, x in __iter(a) do if type(x) ~= "number" then return nil end buffer.writeu8(b, i - 1, x % 256) end return b end -- ------------------------------------------------------------------------------------------------ parse local NUMERIC_ARRAYS= { PackedByteArray = true, PackedInt32Array = true, PackedInt64Array = true, PackedFloat32Array = true, PackedFloat64Array = true, PackedVector2Array = true, PackedVector3Array = true, PackedVector4Array = true, PackedColorArray = true, PoolByteArray = true, PoolIntArray = true, PoolRealArray = true, PoolVector2Array = true, PoolVector3Array = true, PoolColorArray = true, ByteArray = true, IntArray = true, FloatArray = true, RealArray = true, Vector2Array = true, Vector3Array = true, ColorArray = true, } local WORDS= { ["true"] = true, ["false"] = false, ["inf"] = math.huge, ["-inf"] = -math.huge, inf_neg = -math.huge, nan = 0 / 0 } local function skip(p) local s, i = p.s, p.i while true do local a = string.find(s, "[^ \t\r\n]", i) if not a then p.i = p.n + 1 return end if string.byte(s, a) == 59 then -- ';' comment to the end of the line local e = string.find(s, "\n", a, true) if not e then p.i = p.n + 1 return end i = e + 1 else p.i = a return end end end local ESC= { n = "\n", t = "\t", r = "\r", b = "\b", f = "\f", ["\""] = "\"", ["\\"] = "\\", ["'"] = "'", ["/"] = "/" } local function utf8char(c) return utf8.char(math.clamp(c, 0, 0x10FFFF)) end local function str(p) local s = p.s local i = p.i + 1 local parts = {} while true do local a = string.find(s, "[\"\\]", i) if not a then return nil, "unterminated string" end table.insert(parts, string.sub(s, i, a - 1)) if string.byte(s, a) == 34 then p.i = a + 1 return table.concat(parts), nil end local c = string.sub(s, a + 1, a + 1) if c == "u" or c == "U" then local len = c == "u" and 4 or 6 local h = tonumber(string.sub(s, a + 2, a + 1 + len), 16) if not h then return nil, "bad \\u escape" end -- surrogate pairs if h >= 0xD800 and h < 0xDC00 and string.sub(s, a + 6, a + 7) == "\\u" then local lo = tonumber(string.sub(s, a + 8, a + 11), 16) if lo and lo >= 0xDC00 and lo < 0xE000 then h = 0x10000 + (h - 0xD800) * 1024 + (lo - 0xDC00) len =len+ 6 end end table.insert(parts, utf8char(h)) i = a + 2 + len else table.insert(parts, ESC[c] or c) i = a + 2 end end end local value local function numberList(p, name) local s = p.s local close = string.find(s, ")", p.i, true) if not close then return nil, "unterminated " .. name end local body = string.sub(s, p.i, close - 1) -- base64 PackedByteArray, or a list of plain numbers local q = string.match(body, "^%s*\"([^\"]*)\"%s*$") if q then p.i = close + 1 return GodotVariant.ctor(name, { q }), nil end local out = {} local k = 0 for tok in __iter(string.gmatch(body, "[^,%s]+")) do local v = tonumber(tok) if v == nil then v = WORDS[tok] if type(v) ~= "number" then return nil, nil -- not purely numeric: parse it generically end end k =k+ 1 out[k] = v end p.i = close + 1 return GodotVariant.ctor(name, out), nil end local function list(p, close, into) skip(p) if string.byte(p.s, p.i) == close then p.i =p.i+ 1 return nil end while true do local v, err = value(p) if err then return err end table.insert(into, v) mark(into, #into, v) skip(p) local c = string.byte(p.s, p.i) if c == 44 then -- ',' p.i =p.i+ 1 skip(p) if string.byte(p.s, p.i) == close then p.i =p.i+ 1 return nil end elseif c == close then p.i =p.i+ 1 return nil else return "expected ',' or '" .. string.char(close) .. "' at byte " .. (p.i - 1) end end end local function dict(p) p.i =p.i+ 1 local t, keys = {}, {} skip(p) if string.byte(p.s, p.i) == 125 then p.i =p.i+ 1 return Types.object(t, keys), nil end while true do local k, err = value(p) if err then return nil, err end skip(p) if string.byte(p.s, p.i) ~= 58 then return nil, "expected ':' at byte " .. (p.i - 1) end p.i =p.i+ 1 local v, verr = value(p) if verr then return nil, verr end local key = ((type(k) == "string" or type(k) == "number" )and{k }or{(GodotVariant.format(k) )})[1] if t[key] == nil then table.insert(keys, key) end t[key] = v mark(t, key, v) skip(p) local c = string.byte(p.s, p.i) if c == 44 then p.i =p.i+ 1 skip(p) if string.byte(p.s, p.i) == 125 then p.i =p.i+ 1 break end elseif c == 125 then p.i =p.i+ 1 break else return nil, "expected ',' or '}' at byte " .. (p.i - 1) end end return Types.object(t, keys), nil end value = function(p) skip(p) if p.i > p.n then return nil, "truncated: value expected" end p.depth =p.depth+ 1 if p.depth > p.maxDepth then return nil, "limit: nested deeper than " .. p.maxDepth end local s = p.s local c = string.byte(s, p.i) local v, err= nil, nil local isFloat = false if c == 34 then v, err = str(p) elseif c == 38 or c == 94 then -- &"StringName", ^"NodePath" p.i =p.i+ 1 local x, e = str(p) v, err = (x and{(GodotVariant.ctor(c == 38 and"StringName" or"NodePath", { x }) )}or{nil})[1], e elseif c == 91 then -- '[' p.i =p.i+ 1 local out = {} err = list(p, 93, out) v = out elseif c == 123 then -- '{' v, err = dict(p) else local num = string.match(s, "^[-+]?%d[%w%.+-]*", p.i) or string.match(s, "^[-+]?%.%d[%w%.+-]*", p.i) if num then -- 1e-05, 0x1F, 1.5; a trailing "f" is not Godot's local x = tonumber(num) if x == nil then local m = string.match(num, "^[-+]?[%d%.]+[eE][-+]?%d+") or string.match(num, "^[-+]?[%d%.]+") x = (m and{(tonumber(m) )}or{nil })[1] num = m or num end if x == nil then return nil, "bad number " .. num .. " at byte " .. (p.i - 1) end p.i =p.i+ #num v = x isFloat = string.find(num, "[%.eE]") ~= nil and string.sub(num, 1, 2) ~= "0x" else local word = string.match(s, "^[%a_][%w_]*", p.i) or string.match(s, "^%-inf", p.i) if not word then return nil, "unexpected character at byte " .. (p.i - 1) end p.i =p.i+ #word if word == "null" or word == "nil" then v = Types.null elseif WORDS[word] ~= nil then v = WORDS[word] else -- typed array: Array[int]([...]); Dictionary[String, int]({...}) local typed = string.match(s, "^%[[%w_, ]*%]", p.i) if typed and (word == "Array" or word == "Dictionary") then word = word .. typed p.i =p.i+ #typed end skip(p) if string.byte(s, p.i) ~= 40 then return nil, "expected '(' after " .. word .. " at byte " .. (p.i - 1) end p.i =p.i+ 1 if NUMERIC_ARRAYS[word] then local save = p.i v, err = numberList(p, word) if v == nil and err == nil then p.i = save local args = {} err = list(p, 41, args) v = GodotVariant.ctor(word, args) end elseif word == "Object" then skip(p) local cls = string.match(s, "^[%w_]+", p.i) if not cls then return nil, "Object without a class at byte " .. (p.i - 1) end p.i =p.i+ #cls local props, keys = {}, {} skip(p) while string.byte(s, p.i) == 44 do p.i =p.i+ 1 local k, kerr = value(p) if kerr then return nil, kerr end skip(p) if string.byte(s, p.i) ~= 58 then return nil, "expected ':' in Object at byte " .. (p.i - 1) end p.i =p.i+ 1 local x, xerr = value(p) if xerr then return nil, xerr end if type(k) == "string" then props[k] = x table.insert(keys, k) end skip(p) end if string.byte(s, p.i) ~= 41 then return nil, "expected ')' after Object at byte " .. (p.i - 1) end p.i =p.i+ 1 local o = GodotVariant.ctor("Object", { Types.object(props, keys) }) o.class = cls v = o else local args = {} err = list(p, 41, args) v = GodotVariant.ctor(word, args) end end end end p.depth =p.depth- 1 lastFloat = isFloat return v, err end function GodotVariant.value(text, maxDepth) local p= { s = text, i = 1, n = #text, depth = 0, maxDepth = maxDepth or 256 } return value(p) end -- a property key: up to '=' (keys hold '/', ':', '.', or are quoted) local function key(p) local s = p.s if string.byte(s, p.i) == 34 then local k = str(p) return k end local k = string.match(s, "^[^=\n%[]+", p.i) if not k then return nil end p.i =p.i+ #k return (string.gsub(k, "%s+$", "")) end function GodotVariant.parse(text, opts) local o= opts or {} if string.sub(text, 1, 3) == "\239\187\191" then text = string.sub(text, 4) end local p= { s = text, i = 1, n = #text, depth = 0, maxDepth = o.maxDepth or 256 } local maxSections = o.maxSections or 2 ^ 22 local sections= {} local cur= nil local s = text while true do skip(p) if p.i > p.n then break end if string.byte(s, p.i) == 91 then p.i =p.i+ 1 skip(p) local tag = string.match(s, "^[%w_]+", p.i) if not tag then return nil, "bad section header at byte " .. (p.i - 1) end p.i =p.i+ #tag local sec= { tag = tag, attrs = {}, attrOrder = {}, props = {}, order = {} } while true do skip(p) local c = string.byte(s, p.i) if c == 93 then p.i =p.i+ 1 break end local k = string.match(s, "^[%w_/]+", p.i) if not k then return nil, "bad attribute in [" .. tag .. "] at byte " .. (p.i - 1) end p.i =p.i+ #k skip(p) if string.byte(s, p.i) ~= 61 then return nil, "expected '=' in [" .. tag .. "] at byte " .. (p.i - 1) end p.i =p.i+ 1 local v, err = value(p) if err then return nil, err end if sec.attrs[k] == nil then table.insert(sec.attrOrder, k) end sec.attrs[k] = v end if #sections >= maxSections then return nil, "limit: over " .. maxSections .. " sections" end table.insert(sections, sec) cur = sec else local at = p.i local k = key(p) if not k or k == "" then return nil, "bad property at byte " .. (at - 1) end skip(p) if string.byte(s, p.i) ~= 61 then return nil, "expected '=' after " .. k .. " at byte " .. (p.i - 1) end p.i =p.i+ 1 local v, err = value(p) if err then return nil, err end if not cur then cur = { tag = "", attrs = {}, attrOrder = {}, props = {}, order = {} } table.insert(sections, cur ) end local c = cur if c.props[k] == nil then table.insert(c.order, k) end c.props[k] = v mark(c.props, k, v) end end return { sections = sections }, nil end -- ------------------------------------------------------------------------------------------------ format local function num(x) 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 return string.format("%d", x) end for d = 6, 17 do local s = string.format("%." .. d .. "g", x) if tonumber(s) == x then return s end end return string.format("%.17g", x) end GodotVariant.number = num local function quote(s) return "\"" .. string.gsub(s, "[\\\"\n\t\r]", { ["\\"] = "\\\\", ["\""] = "\\\"", ["\n"] = "\\n", ["\t"] = "\\t", ["\r"] = "\\r" }) .. "\"" end GodotVariant.quote = quote local format local function item(t, k, depth, indent) local v = t[k] if type(v) == "number" and v == math.floor(v) and math.abs(v) < 2 ^ 53 and GodotVariant.isFloat(t, k) then return string.format("%d", v) .. ".0" end return format(v, depth, indent) end GodotVariant.item = function(t, k) return item(t, k, 0, false) end format = function(v, depth, indent) if depth > 256 then return "null" end local t = type(v) if t == "number" then return num(v) elseif t == "string" then return quote(v) elseif t == "boolean" then return v and"true" or"false" elseif v == nil or v == Types.null then return "null" elseif t == "buffer" then local parts = table.create(buffer.len(v)) for i = 0, buffer.len(v) - 1 do parts[i + 1] = tostring(buffer.readu8(v, i)) end return "PackedByteArray(" .. table.concat(parts, ", ") .. ")" elseif t ~= "table" then return "null" end if GodotVariant.isCtor(v) then if v.type == "StringName" and type(v.args[1]) == "string" then return "&" .. quote(v.args[1]) elseif v.type == "Object" then local props = v.args[1] local parts = { tostring(v.class or "Object") } if type(props) == "table" then for _, k in __iter(Types.keys(props)) do table.insert(parts, quote(tostring(k)) .. ": " .. format(props[k], depth + 1, false)) end end return "Object(" .. table.concat(parts, ",") .. ")" end local parts= (table.create(#v.args) ) for i, x in __iter(v.args) do parts[i] = format(x, depth + 1, false) end local vt= tostring(v.type) if string.match(vt, "^(%a+)%[") then local inner= parts[1] or "[]" return vt .. "(" .. inner .. ")" end return vt .. "(" .. table.concat(parts, ", ") .. ")" end if Types.isObject(v) or not Types.isArray(v) then local keys = Types.keys(v) if #keys == 0 then return "{}" end local parts = {} for _, k in __iter(keys) do local ks = (type(k) == "string" and{(quote(k) )}or{(format(k, depth + 1, false) )})[1] table.insert(parts, ks .. ": " .. item(v, k, depth + 1, false)) end if indent then return "{\n" .. table.concat(parts, ",\n") .. "\n}" end return "{\n" .. table.concat(parts, ",\n") .. "\n}" end local parts = table.create(#v) for i in __iter(v) do parts[i] = item(v, i, depth + 1, true) end return "[" .. table.concat(parts, ", ") .. "]" end function GodotVariant.format(v) return format(v, 0, false) end function GodotVariant.encode(doc) local out = {} for i, sec in __iter(doc.sections) do if sec.tag ~= "" then local parts = { "[" .. sec.tag } local order = sec.attrOrder if #order == 0 then order = Types.keys(sec.attrs) end for _, k in __iter(order) do if sec.attrs[k] ~= nil then table.insert(parts, k .. "=" .. GodotVariant.format(sec.attrs[k])) end end if i > 1 then table.insert(out, "") end table.insert(out, table.concat(parts, " ") .. "]") end local order = sec.order if #order == 0 then order = Types.keys(sec.props) end for _, k in __iter(order) do if sec.props[k] ~= nil then local ks = (string.find(k, "^[%w_/:%.]+$") and{k }or{(quote(k) )})[1] table.insert(out, ks .. " = " .. item(sec.props, k, 0, false)) end end end return table.concat(out, "\n") .. "\n" end return GodotVariant end __FILES["codecs/text/Json"] = function() local __compat = __compat local buffer, typeof, type = __compat.buffer, __compat.typeof, __compat.type --!strict -- 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 = {} Json.null = Types.null Json.object = Types.object Json.keys = Types.keys Json.set = Types.set local function text(src) 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, at, n) local m = tostring(msg) local code = ((string.find(m, "truncated", 1, true) or string.find(m, "unterminated", 1, true) or (at or 0) >= n )and{Err.TRUNCATED }or{(string.find(m, "nested deeper", 1, true) and{Err.LIMIT }or{Err.CORRUPT })[1]})[1] return Err.new(code, m, at) end function Json.decode(src, opts) local s, terr = text(src) if not s then return nil, terr end local i = string.sub(s, 1, 3) == "\239\187\191" and 4 or 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) ) 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, pos, opts) local s, terr = text(src) if not s then return nil, terr end local i = (string.match(s, "^[ \t\n\r]*()", pos or 1) ) 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, opts) local s, terr = text(src) local pos = 1 local index = 0 local dead = false return function() if dead then return nil end index =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, opts) local s, terr = text(src) if not s then local done = false return function() if done then return nil, nil end done = true return "error", terr end end local str= s local i = string.sub(str, 1, 3) == "\239\187\191" and 4 or 1 local nextEv = Decode.events(str, i, opts) return function() 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, opts) 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 function Json.writer(opts) local st = Encode.state(opts) local ind = st.indent local kinds= {} local counts= {} local depth = 0 local keyDone = false local flushed= {} local w= { err = nil } local function bad(msg) if not w.err then w.err = Err.new(Err.ARG, msg) end end local function slot(isKey) 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]=counts[depth]+ 1 if ind then table.insert(st.out, "\n" .. string.rep(ind, depth)) end return true end local function open(obj) if slot(false) then table.insert(st.out, obj and"{" or"[") depth =depth+ 1 kinds[depth], counts[depth] = obj, 0 end return w end local function close(obj) if w.err then return w end if depth == 0 or kinds[depth] ~= obj or (obj and keyDone) then bad(obj and"unbalanced endObject" or"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, obj and"}" or"]") depth =depth- 1 return w end function w.beginObject(_self) return open(true) end function w.beginArray(_self) return open(false) end function w.endObject(_self) return close(true) end function w.endArray(_self) return close(false) end function w.key(_self, k) 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) .. (ind and": " or":")) keyDone = true end return w end function w.value(_self, v) 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) local s = table.concat(st.out) table.clear(st.out) st.n = 0 table.insert(flushed, s) return s end function w.tostring(_self) 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 end return Json end __FILES["codecs/text/Json/Decode"] = function() --!strict --!native -- 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 local ESC= { [34] = '"', [92] = "\\", [47] = "/", [98] = "\b", [102] = "\f", [110] = "\n", [114] = "\r", [116] = "\t", } local utf8char = Text.utf8char Decode.utf8char = utf8char local function hex4(s, i) local h = match(s, "^%x%x%x%x", i) if not h then return nil end return tonumber(h, 16) end local function str(s, i) 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 =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 =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 =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 =start+ 6 end end np =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 local function num(s, i, bigStrings) local p = i if byte(s, p) == 45 then p =p+ 1 end local c = byte(s, p) if c == 48 then p =p+ 1 elseif c and c >= 49 and c <= 57 then p = (match(s, "^%d*()", p + 1) ) else return nil, c == nil and"truncated: expected a value" or(p == i and"unexpected character" or"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 int = false end c = byte(s, p) if c == 101 or c == 69 then p =p+ 1 c = byte(s, p) if c == 43 or c == 45 then p =p+ 1 end local q = match(s, "^%d+()", p) if not q then return nil, "bad exponent", p - 1 end p = q int = false end local text = sub(s, i, p - 1) local n = (tonumber(text) ) 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 = (mv == 0 and{mv }or{(es == "-" and((mv * 0 ))or((mv * math.huge )))})[1] 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 function Decode.value(s, i, opts) local o= opts or {} local ordered = o.ordered == true local bigStrings = o.bigInts == "string" local nullv = (o.null ~= nil and{o.null }or{Types.null })[1] local maxDepth = o.maxDepth or 1000 local object = Types.object local stackT= {} local stackK= {} local stackO= {} local depth = 0 local n = #s local value while true do i = (match(s, "^[ \t\n\r]*()", i) ) local c = byte(s, i) local haveValue = true if c == 123 then -- { depth =depth+ 1 if depth > maxDepth then return nil, "nested deeper than " .. maxDepth, i - 1 end i = (match(s, "^[ \t\n\r]*()", i + 1) ) local t = {} c = byte(s, i) if c == 125 then i =i+ 1 depth =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) ) if byte(s, i) ~= 58 then return nil, i > n and"truncated object" or"expected ':'", i - 1 end i =i+ 1 stackT[depth], stackK[depth] = t, k stackO[depth] = ordered and{} or true haveValue = false else return nil, c == nil and"truncated object" or"expected a key", i - 1 end elseif c == 91 then -- [ depth =depth+ 1 if depth > maxDepth then return nil, "nested deeper than " .. maxDepth, i - 1 end i = (match(s, "^[ \t\n\r]*()", i + 1) ) if byte(s, i) == 93 then i =i+ 1 depth =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) ) c = byte(s, i) if c == 44 then -- , i = (match(s, "^[ \t\n\r]*()", i + 1) ) if ord then if byte(s, i) ~= 34 then return nil, i > n and"truncated object" or"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) ) if byte(s, i) ~= 58 then return nil, i > n and"truncated object" or"expected ':'", i - 1 end i =i+ 1 stackK[depth] = k end haveValue = false elseif ord and c == 125 then i =i+ 1 value = (ord ~= true and{(object(t, ord) )}or{(next(t) == nil and{(object(t, {}) )}or{t })[1]})[1] stackT[depth] = nil depth =depth- 1 elseif not ord and c == 93 then i =i+ 1 value = t stackT[depth] = nil depth =depth- 1 elseif c == nil then return nil, ord and"truncated object" or"truncated array", n else return nil, ord and"expected ',' or '}'" or"expected ',' or ']'", i - 1 end end end end function Decode.events(s, i, opts) local o= opts or {} local bigStrings = o.bigInts == "string" local nullv = (o.null ~= nil and{o.null }or{Types.null })[1] local maxDepth = o.maxDepth or 1000 local stack= {} local depth = 0 local state = "value" local n = #s local function fail(msg, at) state = "dead" return "error", msg, at end return function() if state == "dead" then return nil end i = (match(s, "^[ \t\n\r]*()", i) ) 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) ) c = byte(s, i) state = obj and"key" or"value" elseif c == (obj and 125 or 93) then i =i+ 1 stack[depth] = nil depth =depth- 1 state = depth == 0 and"done" or"after" return obj and"endObject" or"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 == (obj and 125 or 93) then i =i+ 1 stack[depth] = nil depth =depth- 1 state = depth == 0 and"done" or"after" return obj and"endObject" or"endArray", nil end state = obj and"key" or"value" end if state == "key" then if c ~= 34 then return fail(c == nil and"truncated" or"expected a key", i - 1) end local k, ni, at = str(s, i) if k == nil then return fail(ni, at ) end i = (match(s, "^[ \t\n\r]*()", ni) ) if byte(s, i) ~= 58 then return fail("expected ':'", i - 1) end i =i+ 1 state = "value" return "key", k end local after = depth == 0 and"done" or"after" if c == 123 or c == 91 then depth =depth+ 1 if depth > maxDepth then return fail("nested deeper than " .. maxDepth, i - 1) end stack[depth] = c == 123 i =i+ 1 state = "first" return c == 123 and"object" or"array", nil elseif c == 34 then local v, ni, at = str(s, i) if v == nil then return fail(ni, at ) end i = ni state = after return "value", v elseif c == 116 and sub(s, i, i + 3) == "true" then i =i+ 4 state = after return "value", true elseif c == 102 and sub(s, i, i + 4) == "false" then i =i+ 5 state = after return "value", false elseif c == 110 and sub(s, i, i + 3) == "null" then i =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 ) end i = ni state = after return "value", v end end return Decode end __FILES["codecs/text/Json/Encode"] = function() local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict --!native -- 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 local ESCAPES= { ['"'] = '\\"', ["\\"] = "\\\\", ["\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 local function utf16(cp) if cp < 0x10000 then return format("\\u%04x", cp) end cp =cp- 0x10000 return format("\\u%04x\\u%04x", 0xD800 + math.floor(cp / 1024), 0xDC00 + cp % 1024) end local function asciiSeq(seq) 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 =i+ len end return concat(out) end -- ascii escapes DEL too, like Python's ensure_ascii local function quote(s, ascii, slash) local pat = slash and'[%z\1-\31"\\/]' or'[%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" } local function number(x) 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 __iter(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 local function keyLess(a, b) local ta, tb = type(a), type(b) if ta ~= tb then return ta == "number" end return a < b end local function kind(t, emptyObject) if Types.isObject(t) then return "object" end local n = #t if n == 0 then if next(t) == nil then return emptyObject and"object" or"array" end return "object" end local count = 0 for _ in next, t do count =count+ 1 end return count == n and"array" or"object" end Encode.kind = kind local function put(st, s) local n = st.n + 1 st.out[n] = s st.n = n end local function value(st, v, depth) 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, v and"true" or"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 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 = ind and": " or":" for i, k in __iter(keys) do if i > 1 then put(st, ",") end if ind then put(st, nl) end local ks 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 local function state(opts, nullv) local o= opts or {} local ind= nil if type(o.indent) == "number" then ind = (o.indent > 0 and{(string.rep(" ", o.indent) )}or{nil })[1] 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 function Encode.encode(v, opts, nullv) 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() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict -- 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 = {} 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= (setmetatable({}, { __mode = "k" }) ) function Nbt.info(v) return (type(v) == "table" and{infos[v] }or{nil })[1]end function Nbt.setInfo(v, info) if type(v) == "table" then infos[v] = info end end function Nbt.read(buf, offset, length, opts) 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 ) if v == nil then return nil, Err.from(name, (at or o) - o) end return v, name, at end function Nbt.write(v, opts) local out, e = Binary.write(v, opts ) if not out then return nil, Err.new(Err.ARG, tostring(e)) end return out, nil end function Nbt.unwrap(buf, offset, length, maxBytes) local b, o, l, aerr = Bytes.span("Nbt.unwrap", buf, offset, length) if not b then return nil, aerr end local c0 = (l >= 2 and{(buffer.readu8(b, o) )}or{0 })[1] local c1 = (l >= 2 and{(buffer.readu8(b, o + 1) )}or{0 })[1] 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 local function plausibleName(b, p, n) 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, offset, length) 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 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, c0 == 0x1f and"gzip" or"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, endian, header) 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) local a, b = buffer.readu8(head, q), buffer.readu8(head, q + 1) return (endian == "big" and((a * 256 + b ))or((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= { compression = comp, endian = endian , 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) == ((comp == "none" and{l }or{(-1)})[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, opts, offset, length) local o= opts or {} local b, s, e, comp = Nbt.unwrap(buf, offset, length, o.maxBytes) if not b then return nil, s end local data, start, stop= b, s, e local function try(endian, from, varint) return Binary.read(data, from, stop, { endian = endian , varint = varint, nameless = o.nameless, maxDepth = o.maxDepth }) end local header= 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= { name = name, endian = (o.varint or o.endian == "little" )and"little" or"big", varint = o.varint and true or nil, compression = comp , header = header, } if type(v) == "table" then infos[v] = info end return v, info end function Nbt.encode(v, opts) local o= opts or {} local info = Nbt.info(v) local endian = o.endian or (info and info.endian) or "big" local varint = (o.varint ~= nil and{o.varint }or{(info and info.varint) })[1] 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 = (o.header ~= nil and{o.header }or{(info and info.header) })[1] 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 (endian == "big" and"gzip" or"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, opts) local s = (type(text) == "buffer" and{(buffer.tostring(text) )}or{text })[1] 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, opts) 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, path) local cur = v for part in __iter(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 __iter(string.gmatch(rest , "%[(%-?%d+)%]")) do local i = (tonumber(idx) ) 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() local __compat = __compat local buffer, bit32, utf8, type, __iter = __compat.buffer, __compat.bit32, __compat.utf8, __compat.type, __compat.__iter --!strict -- 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 = {} 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 -- Java's DataOutput strings: U+0000 as C0 80, supplementary characters as two 3-byte surrogates (CESU-8) local function fromModified(s) 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 =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 =i+ 6 else table.insert(out, string.char(c)) i =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) 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 =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 + math.floor(cp / 1024), 0xDC00 + cp % 1024 table.insert(out, string.char(0xED, 0x80 + math.floor((hiS - 0xD000) / 64), 0x80 + hiS % 64)) table.insert(out, string.char(0xED, 0x80 + math.floor((loS - 0xD000) / 64), 0x80 + loS % 64)) i =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, msg) if not s.err then s.err = msg end s.p = s.e return nil end local function need(s, n) if s.p + n > s.e then fail(s, "truncated") return false end return true end local function u8(s) if not need(s, 1) then return 0 end local v = readu8(s.b, s.p) s.p =s.p+ 1 return v end local function varuint(s) 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 =s.p+ 1 v =v+ (c % 128) * mul if c < 128 then return v % TWO32 end mul =mul* 128 end fail(s, "varint too long") return 0 end local function i16(s) 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 (v >= 32768 and((v - 65536 ))or(v ))end local function u32raw(s) if not need(s, 4) then return 0 end local p = s.p s.p = p + 4 local v = readu32(s.b, p) return (s.le and{v }or{(byteswap(v) )})[1]end local function i32(s) if s.net then local n = varuint(s) return (n % 2 == 0 and{(math.floor(n / 2 ))}or{(math.floor(-(n + 1) / 2 ))})[1] end local v = u32raw(s) return (v >= 0x80000000 and((v - TWO32 ))or(v ))end -- a length: i32 (zigzag varint in network NBT) local function len(s) return i32(s) end local function i64(s) 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 =s.p+ 1 local d = c % 128 if sh < 32 then local x = d * 2 ^ sh lo =lo+ x % TWO32 hi = (hi + math.floor(x / TWO32)) % TWO32 else hi = (hi + d * 2 ^ (sh - 32)) % TWO32 end sh =sh+ 7 if c < 128 then break end end local odd = lo % 2 == 1 lo = math.floor(lo / 2 )+ (hi % 2) * 0x80000000 hi = math.floor(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) local v = u32raw(s) writeu32(s.scratch, 0, v) return readf32(s.scratch, 0) end local function f64(s) 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) 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 =s.p+ n return (s.java and{(fromModified(v) )}or{v })[1]end local function tag(name, v) 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 local function count(s, n, size) 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, id) if id == 3 then return i32(s) elseif id == 8 then return str(s) elseif id == 10 then s.depth =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 =s.depth- 1 return Types.object(o, keys) elseif id == 1 then if not need(s, 1) then return nil end s.p =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 =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, ((s.net and{MIN_NET }or{MIN})[1])[et]) then return nil end s.depth =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 =s.depth- 1 Value.setListType(out, NAMES[et]) return out elseif id == 11 then local n = len(s) if not count(s, n, s.net and 1 or 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, s.net and 1 or 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 =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, pos, limit, opts) local o= opts or {} local net = o.varint == true local le = net or o.endian == "little" local s= { 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 = o.nameless and"" or str(s) local v = payload(s, id) if s.err then return nil, s.err, s.p end return v, name, s.p end local function wvaruint(w, v) v =v% TWO32 while v >= 128 do w:u8(v % 128 + 128) v =math.floor(v/ 128 ) end w:u8(v) end local function wi32(ws, v) v =v% TWO32 if ws.net then local sv = (v >= 0x80000000 and((v - TWO32 ))or(v )) wvaruint(ws.w, (sv >= 0 and((sv * 2 ))or((-sv * 2 - 1)))) elseif ws.le then ws.w:u32le(v) else ws.w:u32be(v) end end local function wi16(ws, v) v =v% 65536 if ws.le then ws.w:u16le(v) else ws.w:u16be(v) end end local function wi64(ws, hi, lo) if ws.net then -- zigzag: (n << 1) ^ (n >> 63) local neg = hi >= 0x80000000 local zh = (hi * 2) % TWO32 + (lo >= 0x80000000 and 1 or 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 = math.floor(zl / 128 )+ (zh % 128) * 0x2000000 zh =math.floor(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, s) local v = (ws.java and{(toModified(s) )}or{s })[1] 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, lo, hi, what) local n = (type(v) == "boolean" and{(v and 1 or 0) }or{v })[1] 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 local function wlist(ws, v) 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 ]) 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 , x) if e then return e end end return nil end wpayload = function(ws, t, v) local w = ws.w local x = (Value.isTag(v) and{v.value }or{v })[1] 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 =ws.depth+ 1 if ws.depth > ws.maxDepth then return "nested deeper than " .. ws.maxDepth .. " (a cycle?)" end for _, k in __iter(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 ]) e = wstr(ws, k) if e then return e end e = wpayload(ws, ct , c) if e then return e end end w:u8(0) ws.depth =ws.depth- 1 elseif t == "list" then ws.depth =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 =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 ) 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 = math.floor(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, opts) local o= 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= { w = Bytes.writer(1024), le = le, net = net, java = not le, depth = 0, maxDepth = o.maxDepth or 512 } ws.w:u8(IDS[t ]) if not o.nameless then e = wstr(ws, o.name or "") if e then return nil, e end end e = wpayload(ws, t , v) if e then return nil, e end return ws.w:finish(), nil end return Binary end __FILES["codecs/text/Nbt/Snbt"] = function() local __compat = __compat local buffer, utf8, type, __iter = __compat.buffer, __compat.utf8, __compat.type, __compat.__iter --!strict -- 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 = {} local byte, sub, find = string.byte, string.sub, string.find local TWO32 = 4294967296 local function tag(name, v) return setmetatable({ type = name, value = v }, Value.TagMeta) end local function fail(p, msg) 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) local _, e = find(p.s, "^%s*", p.i) p.i = (e ) + 1 end local function isUnquoted(c) 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= { ["\\"] = "\\", ["'"] = "'", ['"'] = '"', n = "\n", t = "\t", r = "\r", b = "\b", f = "\f", s = " " } local function quoted(p) local q = sub(p.s, p.i, p.i) p.i =p.i+ 1 local out = {} while true do local j = find(p.s, q == '"' and'["\\]' or"['\\]", 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 = c == "x" and 2 or(c == "u" and 4 or 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) ) 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= { 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) local sign, body = string.match(t, "^([+-]?)(.+)$") body = (string.gsub(body , "_", "") ) 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.lower(sfx ) 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 = (c <= 57 and((c - 48 ))or((c >= 97 and((c - 87 ))or((c - 55 ))))) local x = lo * radix + d local carry = math.floor(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 + (lo == 0 and 1 or 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 =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 =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) 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(sfx == "f" and"float" or"double", (special == "-" and{(-math.huge )}or{math.huge})[1]) elseif low == "nanf" or low == "nand" then return tag(sfx == "f" and"float" or"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 , "^(.-)([eE][+-]?%d+)$") if not mant then mant = m end if not (string.match(mant , "^[+-]?%d+%.?%d*$") or string.match(mant , "^[+-]?%.%d+$")) then return nil end if fs == "" and not ex and not find(mant , ".", 1, true) then return nil end local v = tonumber(m) if not v then return nil end if string.lower(fs ) == "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 local function token(p) local j = p.i while j <= p.n and isUnquoted(byte(p.s, j)) do j =j+ 1 end local t = sub(p.s, p.i, j - 1) p.i = j return t end local function key(p) 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, kind) 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 = (t ~= "" and{(number(t) )}or{nil })[1] 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= (Value.isTag(v) and{(v ).value }or{v })[1] 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 =p.i+ 1 if c == "]" then break elseif c ~= "," then p.i =p.i- 1 return fail(p, "expected , or ]") end ws(p) if sub(p.s, p.i, p.i) == "]" then p.i =p.i+ 1 break end end else p.i =p.i+ 1 end if kind == "byte" then local b = buffer.create(#items) for i, x in __iter(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) 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 =p.depth+ 1 if p.depth > p.maxDepth then return fail(p, "limit: nested deeper than " .. p.maxDepth) end p.i =p.i+ 1 local o, keys = {}, {} ws(p) if sub(p.s, p.i, p.i) == "}" then p.i =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 =p.i+ 1 local v = parseValue(p) if p.err then return nil end if o[k ] == nil then table.insert(keys, k) end o[k ] = v ws(p) local d = sub(p.s, p.i, p.i) p.i =p.i+ 1 if d == "}" then break elseif d ~= "," then p.i =p.i- 1 return fail(p, "expected , or }") end ws(p) if sub(p.s, p.i, p.i) == "}" then p.i =p.i+ 1 break end end end p.depth =p.depth- 1 return Types.object(o, keys) elseif c == "[" then p.depth =p.depth+ 1 if p.depth > p.maxDepth then return fail(p, "limit: nested deeper than " .. p.maxDepth) end p.i =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 ) + 1 local v = array(p, ARRAY[kind]) p.depth =p.depth- 1 return v end local items = {} local lt= nil local mixed = false ws(p) if sub(p.s, p.i, p.i) == "]" then p.i =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 =p.i+ 1 if d == "]" then break elseif d ~= "," then p.i =p.i- 1 return fail(p, "expected , or ]") end ws(p) if sub(p.s, p.i, p.i) == "]" then p.i =p.i+ 1 break end end end p.depth =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, opts) local 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, single) 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 = single and 6 or 15, 17 do s = string.format("%." .. digits .. "g", v) local back = (tonumber(s) ) 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 =s.. ".0" end return s end Snbt.shortest = shortest local function quote(s, q) local other = q == '"' and"'" or'"' 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) 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, q) if k ~= "" and not find(k, "[^%w_%-%.%+]") then return k end return quote(k, q) end local printValue local function scalar(v, q) 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 v and"1b" or"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 ((type(x) == "string" and{x }or{(string.format("%d", x))})[1]) .. "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, head, items, close) 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, pr.indent and", " or",") .. close) end end local function sub1(pr, v) local inner= { 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, v, depth) 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)) ) 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 __iter(v.value) do items[i] = string.format("%d", x) end seq(pr, "[I;", items, "]") elseif t == "longArray" then local items = {} for i, x in __iter(Value.longs(v)) do items[i] = ((type(x) == "string" and{x }or{(string.format("%d", x))})[1]) .. "L" end seq(pr, "[L;", items, "]") elseif t == "list" then local items= {} for i = 1, #v do local x, e = sub1(pr, v[i]) if e then return e end items[i] = x end seq(pr, "[", items, "]") else local items = {} for _, k in __iter(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) .. (pr.indent and": " or":") .. (x )) end seq(pr, "{", items, "}") end return nil end function Snbt.print(v, opts) local o= opts or {} local ind = o.indent local pr= { out = {}, indent = (type(ind) == "number" and{(string.rep(" ", ind) )}or{(type(ind) == "string" and{ind }or{nil})[1]})[1], q = o.quote == "'" and"'" or'"', 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) return Snbt.print(v) or "?" end return Snbt end __FILES["codecs/text/Nbt/Value"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict -- 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", } Value.IDS = {} for id = 0, 12 do Value.IDS[Value.NAMES[id] ] = id end local TagMeta= {} Value.TagMeta = TagMeta Value.print = function(v) return tostring(v.value) end TagMeta.__tostring = function(v) return Value.print(v) end TagMeta.__eq = function(a, b) 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= (setmetatable({}, { __mode = "k" }) ) local TWO32 = 4294967296 function Value.fromHiLo(hi, lo) local s = (hi >= 0x80000000 and((hi - TWO32 ))or(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 + (lo == 0 and 1 or 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 = math.floor(hi / 10000 ) local x = (hi - qh * 10000) * TWO32 + lo local ql = math.floor(x / 10000 ) local d = x - ql * 10000 hi, lo = qh, ql table.insert(parts, 1, string.format((hi > 0 or lo > 0 )and"%04d" or"%d", d)) end return (neg and"-" or"") .. table.concat(parts) end function Value.toHiLo(v) if type(v) == "number" then if v % 1 ~= 0 or v < -9223372036854775808 or v >= 9223372036854775808 then return nil, nil end local hi = math.floor(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 = math.floor(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 + (lo == 0 and 1 or 0)) % TWO32 end return hi, lo end return nil, nil end local function tag(name, v) return (setmetatable({ type = name, value = v }, TagMeta) ) end function Value.byte(n) return tag("byte", n) end function Value.short(n) return tag("short", n) end function Value.int(n) return n end function Value.long(v) if type(v) == "string" then local hi, lo = Value.toHiLo(v) if hi then v = Value.fromHiLo(hi, lo ) end end return tag("long", v) end local f32 = buffer.create(4) function Value.float(n) buffer.writef32(f32, 0, n) return tag("float", buffer.readf32(f32, 0)) end function Value.double(n) return tag("double", n) end function Value.intArray(t) return tag("intArray", t or {}) end function Value.longArray(t) if type(t) == "buffer" then return tag("longArray", t) end local list= (t or {}) local b = buffer.create(#list * 8) for i, x in __iter(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) local b= a.value local out = (table.create(math.floor(buffer.len(b) / 8)) ) for i = 0, math.floor(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, items) local t = items or {} listTypes[t] = name return t end function Value.compound(t, keys) return Types.object(t, keys) end function Value.listType(t) return listTypes[t] end function Value.setListType(t, name) listTypes[t] = name end function Value.isTag(v) return type(v) == "table" and getmetatable(v) == TagMeta end function Value.typeOf(v) local tv = type(v) if tv == "number" then return v % 1 == 0 and v >= -2147483648 and v <= 2147483647 and"int" or"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) if type(v) == "number" then return v elseif type(v) == "boolean" then return v and 1 or 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() local __compat = __compat local buffer, utf8, __iter = __compat.buffer, __compat.utf8, __compat.__iter --!strict --!optimize 2 -- 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) local char = string.char if c < 0x80 then return char(c) elseif c < 0x800 then return char(0xC0 + math.floor(c / 64), 0x80 + c % 64) elseif c < 0x10000 then return char(0xE0 + math.floor(c / 4096), 0x80 + (math.floor(c / 64)) % 64, 0x80 + c % 64) end return char(0xF0 + math.floor(c / 262144), 0x80 + (math.floor(c / 4096)) % 64, 0x80 + (math.floor(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) return ((string.match(s, "^%s*(.-)%s*$") )) end function Text.utf16(b, o, n, bigEndian) local out = {} local k = 0 local readu16 = buffer.readu16 local function unit(at) local v = readu16(b, at) return (bigEndian and(((v % 256) * 256 + math.floor(v / 256 )))or(v )) end while k + 1 < n do local c = unit(o + k) 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 =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, warnings) 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((b < 0xA0 and{Text.CP1252[b] or 0xFFFD }or{b})[1]) end end return table.concat(out) end function Text.lines(text) text = string.gsub(text, "\r\n?", "\n") local out = {} for line in __iter(string.gmatch(text .. "\n", "([^\n]*)\n")) do table.insert(out, line) end return out end return Text end __FILES["codecs/text/Url"] = function() local __compat = __compat local type = __compat.type --!strict --!optimize 2 -- 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 = {} -- RFC 3986 appendix B: the five components of a URI reference function Url.split(ref) local scheme, rest = string.match(ref, "^([%a][%w+%.%-]*):(.*)$") if not scheme then rest = ref end local s = rest 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) 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) 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 = (j and{(string.sub(input, 1, j - 1) )}or{input })[1] 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, base) local r, b = Url.split(ref), Url.split(base) local t= { 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 = (r.query and{r.query }or{b.query })[1] 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 = ((k and{(string.sub(b.path, 1, k) )}or{""})[1]) .. 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) return (string.gsub(s, "[%z\1-\32\127-\255<>\"%^`{|}\\]", function(c) return string.format("%%%02X", string.byte(c)) end)) end function Url.isWindowsPath(s) 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) if Url.isWindowsPath(s) then return nil end local scheme = string.match(s, "^([%a][%w+%.%-]*):") return (scheme and{(string.lower(scheme) )}or{nil })[1]end function Url.locate(raw, base, baseScheme) local loc = ((string.match(raw, "^%s*(.-)%s*$") )) 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, warnings) 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() local __compat = __compat local buffer, typeof, type, __iter = __compat.buffer, __compat.typeof, __compat.type, __compat.__iter --!strict -- 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 = {} local find, gsub, sub, match = string.find, string.gsub, string.sub, string.match local function text(src) 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, at, n) 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, opts) 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((find(enc, "unsupported", 1, true) and{Err.UNSUPPORTED }or{Err.CORRUPT})[1], enc) local done = false return function() if done then return nil end done = true return "error", e end end local str= u local nextEv = Parse.events(str, opts) return function() 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, opts) local o= opts or {} local keepComments, keepCdata, keepPi = o.comments == true, o.cdata == true, o.pi == true local parents = o.parents ~= false local doc= { name = "#document", attrs = Types.object(), children = {}, parent = nil } local cur= doc local stack = { doc } local depth = 1 for ev, a, b, c in __iter(Xml.events(src, o)) do if ev == "start" then local node= { name = a, attrs = b, children = {}, parent = (parents and{cur }or{nil })[1]} if c then node.ns = c end table.insert(cur.children, node) depth =depth+ 1 stack[depth] = node cur = node if depth == 2 then doc.root = node end elseif ev == "end" then stack[depth] = nil depth =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]=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 = (parents and{cur }or{nil })[1]}) elseif ev == "comment" then if keepComments then table.insert(cur.children, { name = "#comment", attrs = Types.object(), children = {}, text = a, parent = (parents and{cur }or{nil })[1]}) end elseif ev == "pi" then if keepPi then table.insert(cur.children, { name = "#pi", attrs = Types.object(), children = {}, target = a, text = b, parent = (parents and{cur }or{nil })[1]}) 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, attrs, children) 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= { name = name, attrs = a, children = children or {} } for _, ch in __iter(node.children) do if type(ch) == "table" then ch.parent = node end end return node end function Xml.document(root, declaration) local doc= { name = "#document", attrs = Types.object(), children = { root }, root = root, declaration = declaration } root.parent = doc return doc end function Xml.append(parent, child) table.insert(parent.children, child) if type(child) == "table" then child.parent = parent end return child end function Xml.setAttr(node, name, value) Types.set(node.attrs, name, value) end function Xml.children(node, name) local out = {} for _, ch in __iter(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, name) for _, ch in __iter(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, name) local out = {} local function walk(n) for _, ch in __iter(n.children) do if type(ch) == "table" and string.byte(ch.name) ~= 35 then if name == nil or ch.name == name or (not find(name , ":", 1, true) and match(ch.name, ":(.*)$") == name) then table.insert(out, ch) end walk(ch) end end end walk(node) return out end function Xml.text(node) if type(node) == "string" then return node end if node.name == "#cdata" then return node.text or "" end local parts = {} local function walk(n) for _, ch in __iter(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) return match(name, "^([^:]*):") or "" end function Xml.localName(name) return match(name, ":(.*)$") or name end function Xml.namespace(node, prefix) return Parse.resolve(node, prefix or Xml.prefix(node.name)) end function Xml.clark(node, attrName) 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 = { ["&"] = "&", ["<"] = "<", [">"] = ">", ["\r"] = " " } local ATTR_ESC = { ["&"] = "&", ["<"] = "<", [">"] = ">", ['"'] = """, ["\t"] = " ", ["\n"] = " ", ["\r"] = " " } function Xml.escape(s) return (gsub(s, "[&<>\r]", TEXT_ESC)) end function Xml.escapeAttr(s) return (gsub(s, '[&<>"\t\n\r]', ATTR_ESC)) end local function badName(name) return type(name) ~= "string" or not match(name, "^[%a_:\128-\255][%w_:%.%-\128-\255]*$") end function Xml.encode(node, opts) local o= opts or {} local ind= nil if type(o.indent) == "number" then ind = (o.indent > 0 and{(string.rep(" ", o.indent) )}or{nil })[1] elseif type(o.indent) == "string" then ind = o.indent end local selfClose = o.selfClose ~= false local out= {} local err= nil local seen= {} local write function write(n, depth) 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, "") elseif name == "#cdata" then table.insert(out, "", "]]]]>") .. "]]>") 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, "") elseif name == "#doctype" then table.insert(out, "") elseif name == "#document" then for i, ch in __iter(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 __iter(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, selfClose and"/>" or">") return end table.insert(out, ">") local pretty = ind ~= nil if pretty then for _, c in __iter(ch) do if type(c) == "string" or c.name == "#cdata" then pretty = false break end end end for _, c in __iter(ch) do if pretty then table.insert(out, "\n" .. string.rep(ind , depth + 1)) end write(c, depth + 1) end if pretty then table.insert(out, "\n" .. string.rep(ind , depth)) end table.insert(out, "") end end local decl = o.declaration if decl == nil then decl = node.name == "#document" end if decl then local d= node.declaration or {} table.insert(out, '") table.insert(out, "\n") end if node.name == "#document" and node.doctype then local dt= node.doctype local raw = dt.raw if raw == nil then raw = " " .. (dt.name or ((node.root and{node.root.name }or{"root"})[1])) if dt.publicId then raw =raw.. ' PUBLIC "' .. dt.publicId .. '" "' .. (dt.systemId or "") .. '"' elseif dt.systemId then raw =raw.. ' SYSTEM "' .. dt.systemId .. '"' end end table.insert(out, "\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"] = function() local __compat = __compat local utf8, __iter = __compat.utf8, __compat.__iter --!strict --!native -- 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 local NAME = "^[%a_:\128-\255][%w_:%.%-\128-\255]*" local PREDEF= { lt = "<", gt = ">", amp = "&", quot = '"', apos = "'" } local utf8char = Text.utf8char Parse.utf8char = utf8char local 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, } local function utf16(s, start, le) local out = table.create(math.floor(#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 = (le and((a + b * 256 ))or((a * 256 + b ))) i =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 = (le and((c + d * 256 ))or((c * 256 + d ))) if lo < 0xDC00 or lo > 0xDFFF then return nil, "bad UTF-16 surrogate pair" end i =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 =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 function Parse.toUtf8(s) 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 = (decl and{(match(decl, "encoding%s*=%s*[\"']([%w%._%-]+)[\"']") )}or{nil })[1] 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]", function(c) local v = byte(c) return utf8char((w and{CP1252[v] or v }or{v})[1]) 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 pseudo-attributes, strictly: version, then encoding?, then standalone?, each after whitespace local function xmlDecl(data) local p = 1 local out= {} for k, key in __iter({ "version", "encoding", "standalone" }) do local ws = (match(data, "^[ \t\n]*()", p) ) 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 function Parse.events(s, opts) local o= 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= {} if o.entities then for k, v in __iter(o.entities) do entities[k] = v end end local external= {} 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= {} local nsStack= {} local preserve= {} local depth = 0 local rootSeen = false local rootDone = false local dead = false local pending= nil local errMsg= nil local errAt = 0 local function fail(msg, at) dead = true return "error", msg, at - 1 end local decode function decode(raw, at, level) 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 =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 if byte(ref) == 35 then -- # local cp = (byte(ref, 2) == 120 and{(tonumber(match(ref, "^#x(%x+)$") or "", 16) )}or{(tonumber(match(ref, "^#(%d+)$") or "") )})[1] 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 = (external[ref] and(("external entity &" .. ref .. "; not supported" ))or(("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 =expanded+ #rep if expanded > maxExp then errMsg, errAt = "entity expansion over the limit", at + a - 1 return nil end np =np+ 1 parts[np] = rep p = e end np =np+ 1 parts[np] = sub(raw, p) return table.concat(parts) end local function lookupNs(prefix) 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 local function literal(p) local q = byte(s, p) if q ~= 34 and q ~= 39 then return nil, p end local e = find(s, q == 34 and'"' or"'", 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" local function externalId(p) local kw = sub(s, p, p + 5) if kw == "SYSTEM" then local q = (match(s, "^[ \t\n]+()", p + 6) ) 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) ) 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) ) 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 local function entityValue(v) 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, hex and 16 or 10) ) 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) )) + 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 local function doctype() local start = i local p = (match(s, "^[ \t\n]+()", i) ) 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= { name = name, entities = {} } p =p+ #name local q = (match(s, "^[ \t\n]*()", p) ) 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 = (pub ~= "" and{pub }or{nil })[1] info.systemId = sys q = (match(s, "^[ \t\n]*()", e) ) end if byte(s, q) == 91 then -- the internal subset q =q+ 1 while true do q = (match(s, "^[ \t\n]*()", q) ) local c = byte(s, q) if c == 93 then q =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 elseif sub(s, q, q + 3) == "` timing line)") end subs.meta.source = { format = "srt" } return subs, nil end -- ------------------------------------------------------------------------------------------------ encode local function stamp(t) local ms = math.floor(t * 1000 + 0.5) return string.format("%02d:%02d:%02d,%03d", math.floor(ms / 3600000), math.floor(ms / 60000 )% 60, math.floor(ms / 1000 )% 60, ms % 1000) end function Srt.encode(subs, opts) if type(subs) ~= "table" or type(subs.cues) ~= "table" then return nil, Err.new(Err.ARG, "needs a Subtitles value") end local nl = opts and opts.crlf and"\r\n" or"\n" local out = table.create(#subs.cues) for i, c in __iter(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 = (type(c.settings) == "string" and c.settings ~= "" and string.match(c.settings, "X1:") and((" " .. c.settings ))or("" )) 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() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict -- 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 }, } -- ------------------------------------------------------------------------------------------------ constants local function frac(digits) return ((tonumber(digits) )) / 10 ^ #digits end local function timestamp(s) local h, m, sec, f, rest = string.match(s, "^(%d+):(%d%d):(%d%d)%.(%d+)(.*)$") if h then return (tonumber(h) )* 3600 + (tonumber(m) )* 60 + (tonumber(sec) )+ frac(f ), rest end local m2, s2, f2, rest2 = string.match(s, "^(%d+):(%d%d)%.(%d+)(.*)$") if m2 then return (tonumber(m2) )* 60 + (tonumber(s2) )+ frac(f2 ), rest2 end return nil, s end local function timing(line) 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) 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, opts) 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 =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 local __DARKLUA_CONTINUE_2=false repeat if lines[i] == "" then i =i+ 1 __DARKLUA_CONTINUE_2=true break end local first = i while i <= n and lines[i] ~= "" do i =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= { start = a, stop = b , 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 __DARKLUA_CONTINUE_2=true until true if not __DARKLUA_CONTINUE_2 then break 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) local ms = math.floor(t * 1000 + 0.5) return string.format("%02d:%02d:%02d.%03d", math.floor(ms / 3600000), math.floor(ms / 60000 )% 60, math.floor(ms / 1000 )% 60, ms % 1000) end local function clean(s) 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, "%-%->", "-->") return s end function Vtt.encode(subs, opts) if type(subs) ~= "table" or type(subs.cues) ~= "table" then return nil, Err.new(Err.ARG, "needs a Subtitles value") end local meta= (type(subs.meta) == "table" and{subs.meta }or{{} })[1] local out = {} local header = (type(meta.header) == "string" and meta.header ~= "" and{meta.header }or{nil })[1] if header then local h = string.gsub(clean(header), "%-%->", "") table.insert(out, "WEBVTT " .. h .. "\n") else table.insert(out, "WEBVTT\n") end for _, key in __iter({ "regions", "css" }) do local list = meta[key] if type(list) == "table" then for _, b in __iter(list) do if type(b) == "string" then table.insert(out, (key == "css" and"STYLE\n" or"REGION\n") .. clean(b) .. "\n") end end end end for i, c in __iter(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 = (type(c.id) == "string" and c.id ~= "" and not string.find(c.id, "-->", 1, true) and{((string.gsub(c.id, "[\r\n]", " ")) .. "\n" )}or{"" })[1] local settings = (type(c.settings) == "string" and c.settings ~= "" and{(" " .. (string.gsub(c.settings, "[\r\n]", " ")) )}or{"" })[1] local body = clean(c.text) table.insert(out, id .. stamp(c.start) .. " --> " .. stamp(c.stop) .. settings .. "\n" .. body .. (body ~= "" and"\n" or"")) end return buffer.fromstring(table.concat(out, "\n")), nil end return Vtt end __FILES["vector/ldtk"] = function() local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict -- vector/ldtk: LDtk projects (.ldtk JSON, ldtk.io/json, 1.x) as a TileMap, read + write. Supports: IntGrid, -- AutoLayer, Tiles and Entities layers, tilesets as image paths, typed fields (properties), multi-world projects, -- external levels (.ldtkl through opts.resolve). Not supported: auto-layer rules are kept, never run; writing -- external level files (levels are embedded); standalone .ldtkl files. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Sniff = __include("core/Sniff") local Types = __include("Types") local Json = __include("codecs/text/Json") local Read = __include("vector/ldtk/Read") local Write = __include("vector/ldtk/Write") -- ------------------------------------------------------------------------------------------------ contract local Ldtk = { name = "ldtk", category = "vector", extensions = { "ldtk" }, mime = { "application/x-ldtk+json" }, deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/text/Json" }, caps = { decode = true, encode = true, levels = true, worlds = true, intGrid = true, entities = true }, } -- ------------------------------------------------------------------------------------------------ sniff function Ldtk.sniff(r) local h = Sniff.text(r, 1024) if not string.match(h, "^%s*{") then return 0 end if string.find(h, "\"fileType\"%s*:%s*\"LDtk Project JSON\"") then return 1 end if string.find(h, "\"jsonVersion\"", 1, true) and string.find(h, "\"worldLayout\"", 1, true) then return 0.8 end return 0 end -- ------------------------------------------------------------------------------------------------ decode function Ldtk.decode(r, opts) local o= opts or {} if r.limit - r.base > (o.maxBytes or 2 ^ 28) then return nil, Err.new(Err.LIMIT, "file is over the byte limit") end local v, jerr = Json.decode(buffer.readstring(r.buf, r.base, r.limit - r.base), { ordered = true }) if v == nil then return nil, jerr end local ok, map, msg = pcall(Read.project, v, o) if not ok then return nil, Err.new(Err.CORRUPT, "bad project: " .. tostring(map)) end if not map then return nil, Err.from(msg) end return map, nil end -- ------------------------------------------------------------------------------------------------ encode function Ldtk.encode(map, opts) 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 ok, v, msg = pcall(Write.project, map, opts) if not ok then return nil, Err.new(Err.ARG, "bad map: " .. tostring(v)) end if v == nil then return nil, Err.new(Err.ARG, msg or "bad map") end local indent = (opts and opts.indent == 0 and{nil }or{(opts and opts.indent or 2) })[1] local s, jerr = Json.encode(v, { indent = indent }) if not s then return nil, jerr end return buffer.fromstring(s), nil end return Ldtk end __FILES["vector/ldtk/Read"] = function() local __compat = __compat local bit32, type, __iter = __compat.bit32, __compat.type, __compat.__iter --!strict -- vector/ldtk/Read: an LDtk project (JSON, ldtk.io/json 1.5) into a Types.TileMap: one group layer per level (inside -- one group per world for multi-world projects), the level's layers bottom first. Tile gids are firstGid + the -- LDtk tile id with the f bits as Tiled's flip flags (bit 0 X -> 0x80000000, bit 1 Y -> 0x40000000). local Types = __include("Types") local Json = __include("codecs/text/Json") local Read = {} local FLIP_X, FLIP_Y = 0x80000000, 0x40000000 local function n(v, default) return (type(v) == "number" and{v }or{default })[1]end local function s(v) return (type(v) == "string" and{v }or{nil })[1]end local NULL = Json.null local function tab(v) return type(v) == "table" and v ~= NULL end local function list(v) return (tab(v) and{v }or{{} })[1]end -- every key but the ones listed (the raw part kept for the writer) local function rest(t, skip) local keys = Json.keys(t) local out= {} local order = {} for _, k in __iter(keys) do if not skip[k] then out[k] = t[k] table.insert(order, k) end end return Json.object(out, order) end function Read.fields(v) local props= {} local types= nil for _, f in __iter(list(v)) do if type(f) == "table" and type(f.__identifier) == "string" then props[f.__identifier] = f.__value if type(f.__type) == "string" then types = types or {} ;(types )[f.__identifier] = f.__type end end end return props, types end local function tiles(ctx, raw, ts, grid, cw, ch) local out = table.create(#raw) local data= nil if cw > 0 and ch > 0 then data = table.create(cw * ch, 0) end for i, t in __iter(raw) do if type(t) == "table" then local px, src = list(t.px), list(t.src) local tile = { x = n(px[1], 0), y = n(px[2], 0), tile = n(t.t, 0), flip = n(t.f, 0), srcX = n(src[1], 0), srcY = n(src[2], 0), alpha = n(t.a, 1), d = t.d, } out[i] = tile if data and ts then local cx, cy = math.floor(tile.x / grid), math.floor(tile.y / grid ) if cx >= 0 and cy >= 0 and cx < cw and cy < ch then local gid = ts.firstGid + tile.tile if bit32.btest(tile.flip, 1) then gid =gid+ FLIP_X end if bit32.btest(tile.flip, 2) then gid =gid+ FLIP_Y end -- later tiles are drawn over earlier ones data[1 + cx + cy * cw] = gid end end end end return out, data end local LAYER_SKIP = { __identifier = true, __type = true, __cWid = true, __cHei = true, __gridSize = true, __opacity = true, __pxTotalOffsetX = true, __pxTotalOffsetY = true, __tilesetDefUid = true, __tilesetRelPath = true, visible = true, intGridCsv = true, autoLayerTiles = true, gridTiles = true, entityInstances = true } local ENTITY_SKIP = { __identifier = true, __grid = true, __pivot = true, __tags = true, __tile = true, __smartColor = true, __worldX = true, __worldY = true, width = true, height = true, px = true, fieldInstances = true } local function layer(ctx, li) local kind = s(li.__type) or "Tiles" local cw, ch = n(li.__cWid, 0), n(li.__cHei, 0) if cw < 0 or ch < 0 or cw * ch > ctx.maxCells then return nil, "limit: layer of " .. cw .. " x " .. ch .. " cells" end local grid = math.max(1, n(li.__gridSize, 16)) local out= { name = s(li.__identifier) or "", type = kind == "Entities" and"objects" or"tiles", visible = li.visible ~= false, opacity = n(li.__opacity, 1), properties = {}, offsetX = n(li.__pxTotalOffsetX, 0), offsetY = n(li.__pxTotalOffsetY, 0), ldtkType = kind, gridSize = grid, ldtk = rest(li, LAYER_SKIP), } if kind == "Entities" then local objs = {} for _, e in __iter(list(li.entityInstances)) do if type(e) == "table" then local w, h = n(e.width, 0), n(e.height, 0) local pv, px = list(e.__pivot), list(e.px) local pX, pY = n(pv[1], 0), n(pv[2], 0) local props, types = Read.fields(e.fieldInstances) local o= { id = s(e.iid), name = s(e.__identifier) or "", class = s(e.__identifier) or "", x = n(px[1], 0) - pX * w, y = n(px[2], 0) - pY * h, width = w, height = h, rotation = 0, visible = true, shape = "rectangle", pivot = { pX, pY }, tags = e.__tags, tile = (tab(e.__tile) and{e.__tile }or{nil})[1], color = s(e.__smartColor), properties = props, propertyTypes = types, ldtk = rest(e, ENTITY_SKIP), fieldInstances = e.fieldInstances, } table.insert(objs, o) end end out.objects = objs return out, nil end out.width, out.height = cw, ch local tsUid = li.__tilesetDefUid local ts = (type(tsUid) == "number" and{ctx.tilesets[tsUid] }or{nil })[1] if ts then out.tileset = ts.name end out.tilesetPath = s(li.__tilesetRelPath) local raw = (kind == "Tiles" and{(list(li.gridTiles) )}or{(list(li.autoLayerTiles) )})[1] local tl, data = tiles(ctx, raw, ts, grid, cw, ch) out.tiles = tl out.data = data or {} if kind == "IntGrid" then local csv = list(li.intGridCsv) local grid2 = table.create(cw * ch, 0) for i = 1, math.min(#csv, cw * ch) do grid2[i] = n(csv[i], 0) end out.intGrid = grid2 local def = (type(li.layerDefUid) == "number" and{ctx.layerDefs[li.layerDefUid] }or{nil })[1] if def then local values = {} for _, v in __iter(list(def.intGridValues)) do if type(v) == "table" then table.insert(values, { value = n(v.value, 0), identifier = s(v.identifier), color = s(v.color) }) end end out.intGridValues = values end end return out, nil end local LEVEL_SKIP = { identifier = true, worldX = true, worldY = true, pxWid = true, pxHei = true, __bgColor = true, fieldInstances = true, layerInstances = true } local function level(ctx, lv, resolve) local layers = lv.layerInstances local external = s(lv.externalRelPath) local unresolved = false if not tab(layers) and external then local data= nil if resolve then local ok, b = pcall(resolve, external) data = (ok and type(b) == "buffer" and{b }or{nil })[1] end if data then local v, err = Json.decode(data, { ordered = true }) if not tab(v) then return nil, "external level " .. external .. ": " .. tostring(err) end lv = v layers = v.layerInstances else unresolved = true end end local props, types = Read.fields(lv.fieldInstances) local g= { name = s(lv.identifier) or "", type = "group", visible = true, opacity = 1, properties = props, propertyTypes = types, offsetX = n(lv.worldX, 0), offsetY = n(lv.worldY, 0), layers = {}, level = true, pxWidth = n(lv.pxWid, 0), pxHeight = n(lv.pxHei, 0), backgroundColor = s(lv.__bgColor), external = external, unresolved = unresolved and true or nil, ldtk = rest(lv, LEVEL_SKIP), } local ls = list(layers) for i = #ls, 1, -1 do local l, err = layer(ctx, ls[i]) if not l then return nil, err end table.insert(g.layers , l) end return g, nil end local PROJECT_SKIP = { levels = true, worlds = true } function Read.project(v, opts) if not tab(v) or not tab(v.defs) then return nil, "no defs: not an LDtk project" end local grid = math.max(1, n(v.defaultGridSize, 16)) local map = Types.TileMap.new(0, 0, grid, grid) local ctx= { tilesets = {}, maxCells = opts.maxCells or 2 ^ 26, layerDefs = {} } local gid = 1 for _, t in __iter(list(v.defs.tilesets)) do if type(t) == "table" then local cw, ch = n(t.__cWid, 0), n(t.__cHei, 0) local size = n(t.tileGridSize, grid) local ts= { name = s(t.identifier) or ("tileset" .. #map.tilesets), firstGid = gid, tileWidth = size, tileHeight = size, columns = cw, count = cw * ch, imageSource = s(t.relPath), imageWidth = n(t.pxWid, 0), imageHeight = n(t.pxHei, 0), spacing = n(t.spacing, 0), margin = n(t.padding, 0), uid = t.uid, embedAtlas = s(t.embedAtlas), properties = {}, } gid =gid+ math.max(1, cw * ch) table.insert(map.tilesets, ts) if type(t.uid) == "number" then ctx.tilesets[t.uid] = ts end end end for _, d in __iter(list(v.defs.layers)) do if type(d) == "table" and type(d.uid) == "number" then ctx.layerDefs[d.uid] = d end end local resolve = opts.resolve local worlds = list(v.worlds) local minX, minY, maxX, maxY = math.huge, math.huge, -math.huge, -math.huge local function addLevels(into, levels) for _, lv in __iter(list(levels)) do if type(lv) == "table" then local g, err = level(ctx, lv, resolve) if not g then return err end local x, y = g.offsetX , g.offsetY minX, minY = math.min(minX, x), math.min(minY, y) maxX, maxY = math.max(maxX, x + (g.pxWidth )), math.max(maxY, y + (g.pxHeight )) table.insert(into, g) end end return nil end if #worlds > 0 then for _, w in __iter(worlds) do if type(w) == "table" then local wg= { name = s(w.identifier) or "", type = "group", visible = true, opacity = 1, properties = {}, layers = {}, world = true, ldtk = rest(w, { levels = true, identifier = true }), } local err = addLevels(wg.layers , w.levels) if err then return nil, err end table.insert(map.layers, wg) end end else local err = addLevels(map.layers, v.levels) if err then return nil, err end end if minX <= maxX then map.width = math.ceil((maxX - math.min(minX, 0)) / grid) map.height = math.ceil((maxY - math.min(minY, 0)) / grid) end map.backgroundColor = s(v.bgColor) map.worldLayout = s(v.worldLayout) map.ldtk = rest(v, PROJECT_SKIP) map.meta.source = { format = "ldtk", version = s(v.jsonVersion), externalLevels = v.externalLevels == true, multiWorld = #worlds > 0 } return map, nil end return Read end __FILES["vector/ldtk/Write"] = function() local __compat = __compat local bit32, type, __iter = __compat.bit32, __compat.type, __compat.__iter --!strict -- vector/ldtk/Write: a Types.TileMap as an LDtk project (JSON 1.5). Maps read from LDtk keep their raw defs, project, -- level, layer and entity fields (the .ldtk tables); other maps get definitions made from their layers, tilesets and -- object classes. A tile layer writes its `tiles` list when present, else its gid `data`. Levels are always embedded. local Types = __include("Types") local Json = __include("codecs/text/Json") local Write = {} local NULL = Json.null local FLAGS = 0xF0000000 local function tab(v) return type(v) == "table" and v ~= NULL end local function list(v) return (tab(v) and{v }or{{} })[1]end local function n(v, default) return (type(v) == "number" and v == v and{v }or{default })[1]end local function clone(t) if not tab(t) then return Json.object({}) end local keys = Json.keys(t) local out = {} for _, k in __iter(keys) do out[k] = t[k] end return Json.object(out, keys) end local function obj(pairs_) local out, keys = {}, {} for i = 1, #pairs_, 2 do local k, v = pairs_[i], pairs_[i + 1] table.insert(keys, k) out[k] = v end return Json.object(out, keys) end local function set(t, k, v) Json.set(t, k, (v == nil and{NULL }or{v})[1]) end local function nextUid(ctx) ctx.uid =ctx.uid+ 1 return ctx.uid end local function newIid(ctx) ctx.iid =ctx.iid+ 1 return string.format("%08x-0000-4000-8000-%012x", 0x5ce7a000 + math.floor(ctx.iid / 0x1000000), ctx.iid) end -- ------------------------------------------------------------------------------------------------ fields local function hexColor(v) if type(v) ~= "string" then return nil end local h = string.match(v, "^#(%x%x%x%x%x%x)$") or string.match(v, "^#%x%x(%x%x%x%x%x%x)$") return (h and{(tonumber(h, 16) )}or{nil })[1]end local function wrap(typ, v) if v == nil or v == NULL then return NULL end if typ == "Int" then return obj({ "id", "V_Int", "params", { v } }) elseif typ == "Float" then return obj({ "id", "V_Float", "params", { v } }) elseif typ == "Bool" then return obj({ "id", "V_Bool", "params", { v == true } }) elseif typ == "Color" then local c = hexColor(v) return (c and{(obj({ "id", "V_Int", "params", { c } }) )}or{NULL })[1] elseif typ == "Point" and tab(v) then return obj({ "id", "V_String", "params", { tostring(v.cx) .. "," .. tostring(v.cy) } }) elseif type(v) == "string" then return obj({ "id", "V_String", "params", { v } }) end return nil end local function editorValues(typ, v) local inner = string.match(typ, "^Array<(.+)>$") if inner then local out = {} for i, x in __iter(list(v)) do local w = wrap(inner, x) if w == nil then return nil end out[i] = w end return out end local w = wrap(typ, v) return (w == nil and{nil }or{{ w } })[1]end local function same(a, b) if a == b then return true end if tab(a) and tab(b) then for k, x in __iter(a) do if not same(x, b[k]) then return false end end for k in __iter(b) do if a[k] == nil then return false end end return true end return false end local LDTK_TYPE= { int = "Int", float = "Float", bool = "Bool", string = "String", color = "Color", file = "FilePath" } local function valueType(v) if type(v) == "number" then return v % 1 == 0 and"Int" or"Float" elseif type(v) == "boolean" then return "Bool" end return "String" end local function fieldDef(ctx, name, typ) local isArray = string.match(typ, "^Array<") ~= nil local base = string.match(typ, "^Array<(.+)>$") or typ return obj({ "identifier", name, "doc", NULL, "__type", typ, "uid", nextUid(ctx), "type", "F_" .. base, "isArray", isArray, "canBeNull", true, "arrayMinLength", NULL, "arrayMaxLength", NULL, "editorDisplayMode", "Hidden", "editorDisplayScale", 1, "editorDisplayPos", "Above", "editorLinkStyle", "StraightArrow", "editorDisplayColor", NULL, "editorAlwaysShow", false, "editorShowInWorld", true, "editorCutLongValues", true, "editorTextSuffix", NULL, "editorTextPrefix", NULL, "useForSmartColor", false, "exportToToc", false, "searchable", false, "min", NULL, "max", NULL, "regex", NULL, "acceptFileTypes", NULL, "defaultOverride", NULL, "textLanguageMode", NULL, "symmetricalRef", false, "autoChainRef", true, "allowOutOfLevelRef", true, "allowedRefs", "OnlySame", "allowedRefsEntityUid", NULL, "allowedRefTags", {}, "tilesetUid", NULL, }) end -- raw field instances updated from the properties; properties without an instance get one when a definition exists -- (or is made: makeDefs) local function fieldInstances(ctx, raw, props, types, defs, makeDefs) local out = {} local seen= {} props = (tab(props) and{props }or{{} })[1] types = (tab(types) and{types }or{{} })[1] for _, fi in __iter(list(raw)) do if tab(fi) and type(fi.__identifier) == "string" then local id = fi.__identifier seen[id] = true local f = clone(fi) local v = props[id] if v ~= nil and not same(v, fi.__value) then set(f, "__value", v) local ev = editorValues((type(fi.__type) == "string" and{fi.__type }or{(valueType(v))})[1], v) if ev then set(f, "realEditorValues", ev) end end table.insert(out, f) end end local names = {} for k in __iter(props) do if type(k) == "string" and not seen[k] then table.insert(names, k) end end table.sort(names) for _, k in __iter(names) do local v = props[k] local def = defs and defs[k] if not def and makeDefs and defs then local typ = (type(types[k]) == "string" and{(LDTK_TYPE[types[k] ] or types[k]) }or{(valueType(v) )})[1] def = fieldDef(ctx, k, typ) defs[k] = def table.insert(makeDefs, def) end if def then local typ = (type(def.__type) == "string" and{def.__type }or{(valueType(v) )})[1] table.insert(out, obj({ "__identifier", k, "__type", typ, "__value", v, "__tile", NULL, "defUid", def.uid, "realEditorValues", editorValues(typ, v) or {} })) end end return out end -- ------------------------------------------------------------------------------------------------ defs local function tilesetOf(ctx, gid) local best= nil for _, ts in __iter(ctx.map.tilesets) do if ts.firstGid <= gid and (best == nil or ts.firstGid > best.firstGid) then best = ts end end return best end local function defsFor(ctx, raw) local defs = (tab(raw) and{(clone(raw) )}or{(obj({ "layers", {}, "entities", {}, "tilesets", {}, "enums", {}, "externalEnums", {}, "levelFields", {} }) )})[1] for _, k in __iter({ "layers", "entities", "tilesets", "enums", "externalEnums", "levelFields" }) do if not tab(defs[k]) then set(defs, k, {}) end end ctx.defs = defs for _, d in __iter(list(defs.tilesets)) do if tab(d) and type(d.uid) == "number" then ctx.uid = math.max(ctx.uid, d.uid) ctx.tilesetByUid[d.uid] = d if type(d.identifier) == "string" then ctx.tilesetByName[d.identifier] = d end end end for _, d in __iter(list(defs.layers)) do if tab(d) and type(d.identifier) == "string" then ctx.uid = math.max(ctx.uid, n(d.uid, 0)) ctx.layerDefs[d.identifier] = d end end for _, d in __iter(list(defs.entities)) do if tab(d) and type(d.identifier) == "string" then ctx.uid = math.max(ctx.uid, n(d.uid, 0)) ctx.entityDefs[d.identifier] = d for _, f in __iter(list(d.fieldDefs)) do ctx.uid = math.max(ctx.uid, n(tab(f) and f.uid, 0)) end end end for _, f in __iter(list(defs.levelFields)) do if tab(f) and type(f.identifier) == "string" then ctx.uid = math.max(ctx.uid, n(f.uid, 0)) ctx.levelFields[f.identifier] = f end end for _, d in __iter(list(defs.enums)) do ctx.uid = math.max(ctx.uid, n(tab(d) and d.uid, 0)) end -- tilesets of the map the defs lack for _, ts in __iter(ctx.map.tilesets) do if type(ts.name) == "string" and not ctx.tilesetByName[ts.name] then local size = n(ts.tileWidth, 16) local cols = math.max(1, n(ts.columns, 1)) local d = obj({ "__cWid", cols, "__cHei", math.ceil(n(ts.count, cols) / cols), "identifier", ts.name, "uid", nextUid(ctx), "relPath", ts.imageSource or NULL, "embedAtlas", NULL, "pxWid", n(ts.imageWidth, cols * size), "pxHei", n(ts.imageHeight, math.ceil(n(ts.count, cols) / cols) * size), "tileGridSize", size, "spacing", n(ts.spacing, 0), "padding", n(ts.margin, 0), "tags", {}, "tagsSourceEnumUid", NULL, "enumTags", {}, "customData", {}, "savedSelections", {}, "cachedPixelData", NULL, }) table.insert(defs.tilesets, d) ctx.tilesetByName[ts.name] = d ctx.tilesetByUid[d.uid] = d end end end local function layerDef(ctx, l, kind, grid, tsUid) local d = ctx.layerDefs[l.name] if d then return d end local values = {} for _, v in __iter(list(l.intGridValues)) do table.insert(values, obj({ "value", n(v.value, 1), "identifier", v.identifier or NULL, "color", v.color or "#FFFFFF", "tile", NULL, "groupUid", 0 })) end if kind == "IntGrid" and #values == 0 then local maxV = 0 for _, v in __iter(list(l.intGrid)) do maxV = math.max(maxV, n(v, 0)) end for v = 1, maxV do table.insert(values, obj({ "value", v, "identifier", NULL, "color", "#FFFFFF", "tile", NULL, "groupUid", 0 })) end end d = obj({ "__type", kind, "identifier", l.name, "type", kind, "uid", nextUid(ctx), "doc", NULL, "uiColor", NULL, "gridSize", grid, "guideGridWid", 0, "guideGridHei", 0, "displayOpacity", n(l.opacity, 1), "inactiveOpacity", 1, "hideInList", false, "hideFieldsWhenInactive", true, "canSelectWhenInactive", true, "renderInWorldView", true, "pxOffsetX", 0, "pxOffsetY", 0, "parallaxFactorX", 0, "parallaxFactorY", 0, "parallaxScaling", true, "requiredTags", {}, "excludedTags", {}, "autoTilesKilledByOtherLayerUid", NULL, "uiFilterTags", {}, "useAsyncRender", false, "intGridValues", values, "intGridValuesGroups", {}, "autoRuleGroups", {}, "autoSourceLayerDefUid", NULL, "tilesetDefUid", tsUid or NULL, "tilePivotX", 0, "tilePivotY", 0, "biomeFieldUid", NULL, }) table.insert(ctx.defs.layers, d) ctx.layerDefs[l.name] = d return d end local function entityDef(ctx, o) local name = (type(o.class) == "string" and o.class ~= "" and{o.class }or{(type(o.name) == "string" and o.name ~= "" and{o.name }or{"Entity" })[1]})[1] local d = ctx.entityDefs[name] if d then return d end local pv = (tab(o.pivot) and{o.pivot }or{{ 0, 0 } })[1] d = obj({ "identifier", name, "uid", nextUid(ctx), "tags", {}, "exportToToc", false, "allowOutOfBounds", false, "doc", NULL, "width", math.max(1, n(o.width, 16)), "height", math.max(1, n(o.height, 16)), "resizableX", false, "resizableY", false, "minWidth", NULL, "maxWidth", NULL, "minHeight", NULL, "maxHeight", NULL, "keepAspectRatio", false, "tileOpacity", 1, "fillOpacity", 0.08, "lineOpacity", 0, "hollow", false, "color", (type(o.color) == "string" and{o.color }or{"#94D9B3"})[1], "renderMode", "Rectangle", "showName", true, "tilesetId", NULL, "tileRenderMode", "FitInside", "tileRect", NULL, "uiTileRect", NULL, "nineSliceBorders", {}, "maxCount", 0, "limitScope", "PerLevel", "limitBehavior", "MoveLastOne", "pivotX", n(pv[1], 0), "pivotY", n(pv[2], 0), "fieldDefs", {}, }) table.insert(ctx.defs.entities, d) ctx.entityDefs[name] = d return d end -- ------------------------------------------------------------------------------------------------ layers local function gridTiles(ctx, l, grid, ts) local out = {} if tab(l.tiles) then for _, t in __iter(l.tiles) do local o = obj({ "px", { n(t.x, 0), n(t.y, 0) }, "src", { n(t.srcX, 0), n(t.srcY, 0) }, "f", n(t.flip, 0), "t", n(t.tile, 0) }) if tab(t.d) then set(o, "d", t.d) end set(o, "a", n(t.alpha, 1)) table.insert(out, o) end return out end local w = n(l.width, 0) for i, raw in __iter(list(l.data)) do local gid = bit32.band(n(raw, 0), bit32.bnot(FLAGS)) if gid ~= 0 then local tset = tilesetOf(ctx, gid) if tset and (ts == nil or ctx.tilesetByName[tset.name] == ts) then local id = gid - tset.firstGid local cols = math.max(1, n(tset.columns, 1)) local tw, th = n(tset.tileWidth, grid), n(tset.tileHeight, grid) local sp, mg = n(tset.spacing, 0), n(tset.margin, 0) local f = (bit32.btest(raw, 0x80000000) and 1 or 0) + (bit32.btest(raw, 0x40000000) and 2 or 0) local cx, cy = (i - 1) % math.max(w, 1), math.floor((i - 1) / math.max(w, 1) ) table.insert(out, obj({ "px", { cx * grid, cy * grid }, "src", { mg + (id % cols) * (tw + sp), mg + (math.floor(id / cols)) * (th + sp) }, "f", f, "t", id, "d", { cx + cy * w }, "a", 1, })) end end end return out end local function layerTileset(ctx, l) if type(l.tileset) == "string" and ctx.tilesetByName[l.tileset] then return ctx.tilesetByName[l.tileset] end if tab(l.ldtk) and type(l.ldtk.overrideTilesetUid) == "number" and ctx.tilesetByUid[l.ldtk.overrideTilesetUid] then return ctx.tilesetByUid[l.ldtk.overrideTilesetUid] end for _, raw in __iter(list(l.data)) do local gid = bit32.band(n(raw, 0), bit32.bnot(FLAGS)) if gid ~= 0 then local tset = tilesetOf(ctx, gid) return (tset and{ctx.tilesetByName[tset.name] }or{nil })[1] end end return nil end local function entities(ctx, l, levelIid, lx, ly, grid) local out = {} for _, o in __iter(list(l.objects)) do if tab(o) then local d = entityDef(ctx, o) local w, h = n(o.width, n(d.width, 16)), n(o.height, n(d.height, 16)) local pv = (tab(o.pivot) and{o.pivot }or{{ n(d.pivotX, 0), n(d.pivotY, 0) } })[1] local px, py = n(o.x, 0) + n(pv[1], 0) * w, n(o.y, 0) + n(pv[2], 0) * h local e = clone(o.ldtk) set(e, "__identifier", d.identifier) set(e, "__grid", { math.floor(px / grid), math.floor(py / grid )}) set(e, "__pivot", { n(pv[1], 0), n(pv[2], 0) }) set(e, "__tags", (tab(o.tags) and{o.tags }or{{}})[1]) set(e, "__tile", (tab(o.tile) and{o.tile }or{NULL})[1]) set(e, "__smartColor", (type(o.color) == "string" and{o.color }or{d.color})[1]) if type(e.iid) ~= "string" then set(e, "iid", (type(o.id) == "string" and{o.id }or{(newIid(ctx))})[1]) end set(e, "width", w) set(e, "height", h) set(e, "defUid", d.uid) set(e, "px", { px, py }) local fdefs= {} for _, f in __iter(list(d.fieldDefs)) do if tab(f) and type(f.identifier) == "string" then fdefs[f.identifier] = f end end set(e, "fieldInstances", fieldInstances(ctx, o.fieldInstances, o.properties, o.propertyTypes, fdefs, d.fieldDefs)) set(e, "__worldX", lx + px) set(e, "__worldY", ly + py) table.insert(out, e) end end return out end local function layerInstance(ctx, l, levelUid, levelIid, lx, ly, pxW, pxH) local kind = (type(l.ldtkType) == "string" and{l.ldtkType }or{l.type == "objects" and"Entities" or(tab(l.intGrid) and"IntGrid" or"Tiles" )})[1] local grid = math.max(1, n(l.gridSize, ctx.map.tileWidth)) local ts = (kind ~= "Entities" and{(layerTileset(ctx, l) )}or{nil })[1] local d = layerDef(ctx, l, kind, grid, (ts and{ts.uid }or{nil})[1]) local cw = n(l.width, math.ceil(pxW / grid)) local ch = n(l.height, math.ceil(pxH / grid)) local li = clone(l.ldtk) set(li, "__identifier", l.name) set(li, "__type", kind) set(li, "__cWid", cw) set(li, "__cHei", ch) set(li, "__gridSize", grid) set(li, "__opacity", n(l.opacity, 1)) set(li, "__pxTotalOffsetX", n(l.offsetX, 0)) set(li, "__pxTotalOffsetY", n(l.offsetY, 0)) set(li, "__tilesetDefUid", (ts and{ts.uid }or{NULL})[1]) set(li, "__tilesetRelPath", (ts and type(ts.relPath) == "string" and{ts.relPath }or{NULL})[1]) if type(li.iid) ~= "string" then set(li, "iid", newIid(ctx)) end set(li, "levelId", levelUid) set(li, "layerDefUid", d.uid) if li.pxOffsetX == nil then set(li, "pxOffsetX", n(l.offsetX, 0) - n(d.pxOffsetX, 0)) set(li, "pxOffsetY", n(l.offsetY, 0) - n(d.pxOffsetY, 0)) end set(li, "visible", l.visible ~= false) if li.optionalRules == nil then set(li, "optionalRules", {}) end local csv = {} if kind == "IntGrid" then local g = list(l.intGrid) for i = 1, cw * ch do csv[i] = n(g[i], 0) end end set(li, "intGridCsv", csv) local tl = (kind ~= "Entities" and{(gridTiles(ctx, l, grid, ts) )}or{{} })[1] set(li, "autoLayerTiles", ((kind == "IntGrid" or kind == "AutoLayer" )and{tl }or{{}})[1]) if li.seed == nil then set(li, "seed", 0) end if li.overrideTilesetUid == nil then set(li, "overrideTilesetUid", NULL) end set(li, "gridTiles", (kind == "Tiles" and{tl }or{{}})[1]) set(li, "entityInstances", (kind == "Entities" and{(entities(ctx, l, levelIid, lx, ly, grid) )}or{{}})[1]) return li end -- ------------------------------------------------------------------------------------------------ levels local function flat(layers, into) for _, l in __iter(layers) do if l.type == "group" and not l.level and not l.world then flat(list(l.layers), into) elseif l.type ~= "group" and l.type ~= "image" then table.insert(into, l) end end end local function levelValue(ctx, g, layers, index) local lv = clone(g.ldtk) local grid = ctx.map.tileWidth local pxW = n(g.pxWidth, 0) local pxH = n(g.pxHeight, 0) if pxW <= 0 or pxH <= 0 then for _, l in __iter(layers) do local gs = n(l.gridSize, grid) pxW = math.max(pxW, n(l.width, 0) * gs) pxH = math.max(pxH, n(l.height, 0) * gs) end pxW = (pxW > 0 and{pxW }or{(ctx.map.width * grid )})[1] pxH = (pxH > 0 and{pxH }or{(ctx.map.height * grid )})[1] end local uid = (type(lv.uid) == "number" and{lv.uid }or{(nextUid(ctx) )})[1] local iid = (type(lv.iid) == "string" and{lv.iid }or{(newIid(ctx) )})[1] local lx, ly = n(g.offsetX, 0), n(g.offsetY, 0) set(lv, "identifier", (type(g.name) == "string" and g.name ~= "" and{g.name }or{("Level_" .. index)})[1]) set(lv, "iid", iid) set(lv, "uid", uid) set(lv, "worldX", lx) set(lv, "worldY", ly) if lv.worldDepth == nil then set(lv, "worldDepth", 0) end set(lv, "pxWid", pxW) set(lv, "pxHei", pxH) set(lv, "__bgColor", (type(g.backgroundColor) == "string" and{g.backgroundColor }or{(type(ctx.map.backgroundColor) == "string" and{ctx.map.backgroundColor }or{"#696A79"})[1]})[1]) for _, k in __iter({ "bgColor", "bgRelPath", "bgPos", "__smartColor", "__bgPos" }) do if lv[k] == nil then set(lv, k, k == "__smartColor" and"#ADADB5ff" or NULL) end end if lv.useAutoIdentifier == nil then set(lv, "useAutoIdentifier", false) end if lv.bgPivotX == nil then set(lv, "bgPivotX", 0.5) set(lv, "bgPivotY", 0.5) end set(lv, "externalRelPath", NULL) set(lv, "fieldInstances", fieldInstances(ctx, lv.fieldInstances, g.properties, g.propertyTypes, ctx.levelFields, ctx.defs.levelFields)) local out = {} for i = #layers, 1, -1 do table.insert(out, layerInstance(ctx, layers[i], uid, iid, lx, ly, pxW, pxH)) end set(lv, "layerInstances", out) if lv.__neighbours == nil then set(lv, "__neighbours", {}) end return lv end local function levels(ctx, layers) local out = {} local loose = {} for _, l in __iter(layers) do if l.type == "group" and not l.world then local ls = {} flat(list(l.layers), ls) table.insert(out, levelValue(ctx, l, ls, #out)) elseif l.type ~= "group" and l.type ~= "image" then table.insert(loose, l) end end if #loose > 0 then table.insert(out, 1, levelValue(ctx, { name = "Level_0", properties = {}, offsetX = 0, offsetY = 0 }, loose, 0)) end return out end local PROJECT= { "__header__", NULL, "iid", NULL, "jsonVersion", "1.5.3", "appBuildId", 473703, "nextUid", 0, "identifierStyle", "Capitalize", "toc", {}, "worldLayout", "Free", "worldGridWidth", 256, "worldGridHeight", 256, "defaultLevelWidth", 256, "defaultLevelHeight", 256, "defaultPivotX", 0, "defaultPivotY", 0, "defaultGridSize", 16, "defaultEntityWidth", 16, "defaultEntityHeight", 16, "bgColor", "#40465B", "defaultLevelBgColor", "#696A79", "minifyJson", false, "externalLevels", false, "exportTiled", false, "simplifiedExport", false, "imageExportMode", "None", "exportLevelBg", true, "pngFilePattern", NULL, "backupOnSave", false, "backupLimit", 10, "backupRelPath", NULL, "levelNamePattern", "Level_%idx", "tutorialDesc", NULL, "customCommands", {}, "flags", {}, "defs", NULL, "levels", NULL, "worlds", NULL, "dummyWorldIid", NULL, } function Write.project(map, opts) local ctx= { uid = 0, iid = 0, defs = nil, tilesetByName = {}, tilesetByUid = {}, layerDefs = {}, entityDefs = {}, levelFields = {}, map = map, } local raw = (tab(map.ldtk) and{map.ldtk }or{nil })[1] local p = (raw and{(clone(raw) )}or{(Json.object({}) )})[1] if not raw then for i = 1, #PROJECT, 2 do set(p, PROJECT[i], PROJECT[i + 1]) end set(p, "__header__", obj({ "fileType", "LDtk Project JSON", "app", "LDtk", "doc", "https://ldtk.io/json", "schema", "https://ldtk.io/files/JSON_SCHEMA.json", "appAuthor", "Sebastien 'deepnight' Benard", "appVersion", "1.5.3", "url", "https://ldtk.io" })) set(p, "iid", newIid(ctx)) set(p, "defaultGridSize", map.tileWidth) end ctx.uid = math.max(ctx.uid, n(p.nextUid, 1) - 1) defsFor(ctx, p.defs) local worlds = {} local hasWorlds = false for _, l in __iter(map.layers) do if l.type == "group" and l.world then hasWorlds = true end end local lvls= {} if hasWorlds then for _, l in __iter(map.layers) do if l.type == "group" and l.world then local w = clone(l.ldtk) set(w, "identifier", l.name) if type(w.iid) ~= "string" then set(w, "iid", newIid(ctx)) end for _, k in __iter({ "worldGridWidth", "worldGridHeight" }) do if w[k] == nil then set(w, k, 256) end end if w.worldLayout == nil then set(w, "worldLayout", "Free") end set(w, "levels", levels(ctx, list(l.layers))) table.insert(worlds, w) end end else lvls = levels(ctx, map.layers) end if type(map.backgroundColor) == "string" then set(p, "bgColor", map.backgroundColor) end if type(map.worldLayout) == "string" and not hasWorlds then set(p, "worldLayout", map.worldLayout) end set(p, "externalLevels", false) set(p, "defs", ctx.defs) set(p, "levels", lvls) set(p, "worlds", worlds) if type(p.dummyWorldIid) ~= "string" then set(p, "dummyWorldIid", newIid(ctx)) end set(p, "nextUid", ctx.uid + 1) return p, nil end return Write end __FILES["vector/ogmo"] = function() local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict -- vector/ogmo: Ogmo Editor 3 levels (.json) and projects (.ogmo) as a TileMap, read + write (OgmoEditor3-CE 3.x -- save format). Supports: tile layers (ids / coords, 1D / 2D arrays, tile flags), grid layers, entity layers (origin, -- rotation, flips, nodes, values), decal layers, level values; the project through opts.project for tilesets and -- entity templates. Not supported: loading tileset images (embedded PNGs stay bytes: tileset.imageData). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Sniff = __include("core/Sniff") local Types = __include("Types") local Json = __include("codecs/text/Json") local Read = __include("vector/ogmo/Read") local Write = __include("vector/ogmo/Write") -- ------------------------------------------------------------------------------------------------ contract local Ogmo = { name = "ogmo", category = "vector", extensions = { "ogmo" }, mime = { "application/x-ogmo+json" }, deps = { "core/Err", "core/Bytes", "core/Sniff", "core/Base64", "Types", "codecs/text/Json" }, caps = { decode = true, encode = true, projects = true, entities = true, decals = true }, } -- ------------------------------------------------------------------------------------------------ sniff function Ogmo.sniff(r) local h = Sniff.text(r, 2048) if not string.match(h, "^%s*{") or not string.find(h, "\"ogmoVersion\"", 1, true) then return 0 end if string.find(h, "\"layerGridDefaultSize\"", 1, true) or string.find(h, "\"levelPaths\"", 1, true) then return 1 end return 0.9 end -- ------------------------------------------------------------------------------------------------ decode local function json(src) if type(src) == "table" then return src, nil end if type(src) ~= "string" and type(src) ~= "buffer" then return nil, Err.new(Err.ARG, "project must be bytes or a table") end return Json.decode(src, { ordered = true }) end function Ogmo.decode(r, opts) local o= opts or {} if r.limit - r.base > (o.maxBytes or 2 ^ 28) then return nil, Err.new(Err.LIMIT, "file is over the byte limit") end local v, jerr = Json.decode(buffer.readstring(r.buf, r.base, r.limit - r.base), { ordered = true }) if v == nil then return nil, jerr end if type(v) ~= "table" then return nil, Err.new(Err.CORRUPT, "not a JSON object") end local isProject = v.layerGridDefaultSize ~= nil or v.levelPaths ~= nil or v.tilesets ~= nil and v.layers ~= nil and v.width == nil local project= nil if not isProject and o.project ~= nil then local p, perr = json(o.project) if p == nil then return nil, perr end project = p end local run= (isProject and{Read.project }or{function(x, oo) return Read.level(x, project, oo) end })[1] local ok, map, msg = pcall(run, v, o) if not ok then return nil, Err.new(Err.CORRUPT, "bad data: " .. tostring(map)) end if not map then return nil, Err.from(msg) end return map, nil end -- ------------------------------------------------------------------------------------------------ encode function Ogmo.encode(map, opts) 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 kind = opts and opts.kind or (type(map.meta) == "table" and map.meta.project and"project" or"level") if kind ~= "level" and kind ~= "project" then return nil, Err.new(Err.ARG, "kind must be level or project") end local ok, v, msg = pcall((kind == "project" and{Write.project }or{Write.level})[1], map) if not ok then return nil, Err.new(Err.ARG, "bad map: " .. tostring(v)) end if v == nil then return nil, Err.new(Err.ARG, msg or "bad map") end local indent = (opts and opts.indent == 0 and{nil }or{(opts and opts.indent or 2) })[1] local s, jerr = Json.encode(v, { indent = indent }) if not s then return nil, jerr end return buffer.fromstring(s), nil end return Ogmo end __FILES["vector/ogmo/Read"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict -- vector/ogmo/Read: Ogmo Editor 3 projects (.ogmo) and levels (.json) into a Types.TileMap (layer save / load as in -- OgmoEditor3-CE src/modules/*/ *Layer.hx). Ogmo's first layer is drawn on top: layers are reversed (bottom first). -- Tile ids -1 are empty; tileFlags 4 / 2 / 1 (flip H / V / diagonal) become Tiled's 0x80000000 / 0x40000000 / -- 0x20000000. local Types = __include("Types") local Json = __include("codecs/text/Json") local Base64 = __include("core/Base64") local Read = {} local NULL = Json.null local FLIP_H, FLIP_V, FLIP_D = 0x80000000, 0x40000000, 0x20000000 local function tab(v) return type(v) == "table" and v ~= NULL end local function list(v) return (tab(v) and{v }or{{} })[1]end local function n(v, default) return (type(v) == "number" and v == v and{v }or{default })[1]end local function s(v) return (type(v) == "string" and{v }or{nil })[1]end local function vec(v, dx, dy) if tab(v) then return n(v.x, dx), n(v.y, dy) end return dx, dy end -- PNG IHDR width / height of an embedded tileset image (data: URI) local function pngSize(b) if buffer.len(b) >= 24 and buffer.readstring(b, 0, 8) == "\137PNG\r\n\26\n" and buffer.readstring(b, 12, 4) == "IHDR" then local function be(o) return buffer.readu8(b, o) * 16777216 + buffer.readu8(b, o + 1) * 65536 + buffer.readu8(b, o + 2) * 256 + buffer.readu8(b, o + 3) end return be(16), be(20) end return nil, nil end local VALUE_TYPES= { Integer = "int", Float = "float", Boolean = "bool", Color = "color", Filepath = "file", String = "string", Text = "string", Enum = "string" } function Read.tilesets(project) local out= {} local gid = 1 for _, t in __iter(list(project and project.tilesets)) do if tab(t) then local tw, th = math.max(1, n(t.tileWidth, 16)), math.max(1, n(t.tileHeight, 16)) local sx, sy = n(t.tileSeparationX, 0), n(t.tileSeparationY, 0) local mx, my = n(t.tileMarginX, 0), n(t.tileMarginY, 0) local data= nil local iw, ih = nil, nil if type(t.image) == "string" and string.sub(t.image, 1, 5) == "data:" then data = Base64.decodeDataUri(t.image) if data then iw, ih = pngSize(data) end end local cols = (iw and{(math.max(1, math.floor((iw - 2 * mx + sx) / (tw + sx))) )}or{1 })[1] local rows = (ih and{(math.max(1, math.floor((ih - 2 * my + sy) / (th + sy))) )}or{1 })[1] local ts= { name = s(t.label) or ("tileset" .. #out), firstGid = gid, tileWidth = tw, tileHeight = th, columns = cols, count = cols * rows, imageSource = s(t.path), imageWidth = iw, imageHeight = ih, imageData = data, spacing = sx, spacingY = (sy ~= sx and{sy }or{nil})[1], margin = mx, marginY = (my ~= mx and{my }or{nil})[1], } gid =gid+ ts.count table.insert(out, ts) end end return out end local function valueTypes(defs) local out= nil for _, d in __iter(list(defs)) do if tab(d) and type(d.name) == "string" and type(d.definition) == "string" then local typ = VALUE_TYPES[d.definition] if typ and typ ~= "string" then out = out or {} ;(out )[d.name] = typ end end end return out end local function values(v) local out= {} if tab(v) then for k, x in __iter(v) do if type(k) == "string" then out[k] = x end end end return out end local function cells2D(v, w, h) local out = table.create(w * h) for y, row in __iter(list(v)) do for x, c in __iter(list(row)) do if x <= w and y <= h then out[(y - 1) * w + x] = c end end end return out end local function tileLayer(ctx, li, l, w, h) local ts = ctx.byName[s(li.tileset) or ""] or ctx.tilesets[1] l.tileset = s(li.tileset) local exportMode, arrayMode = n(li.exportMode, 0), n(li.arrayMode, 0) local raw if exportMode == 1 then raw = (arrayMode == 1 and{(cells2D(li.dataCoords2D, w, h) )}or{(list(li.dataCoords) )})[1] else raw = (arrayMode == 1 and{(cells2D(li.data2D, w, h) )}or{(list(li.data) )})[1] end local flags = (arrayMode == 1 and{(cells2D(li.tileFlags2D, w, h) )}or{(list(li.tileFlags) )})[1] local data = table.create(w * h, 0) for i = 1, w * h do local c = raw[i] local id = -1 if exportMode == 1 then if tab(c) and n(c[1], -1) >= 0 then id = n(c[2], 0) * ((ts and{ts.columns }or{1})[1]) + n(c[1], 0) end else id = n(c, -1) end if id >= 0 and ts then local gid = ts.firstGid + id local f = n(flags[i], 0) if bit32.btest(f, 4) then gid =gid+ FLIP_H end if bit32.btest(f, 2) then gid =gid+ FLIP_V end if bit32.btest(f, 1) then gid =gid+ FLIP_D end data[i] = gid elseif id >= 0 then data[i] = id + 1 end end l.data = data end local function entity(ctx, e) local def = ctx.entityDefs[s(e.name) or ""] local dw, dh = vec(def and def.size, 16, 16) local dox, doy = vec(def and def.origin, 0, 0) local w, h = n(e.width, dw), n(e.height, dh) local ox, oy = n(e.originX, dox), n(e.originY, doy) local rot = n(e.rotation, 0) if ctx.radians then rot = math.deg(rot) end local nodes = nil if tab(e.nodes) then nodes = {} for i, p in __iter(e.nodes) do nodes[i] = { n(tab(p) and p.x, 0), n(tab(p) and p.y, 0) } end end return { id = e.id, name = s(e.name) or "", class = s(e.name) or "", x = n(e.x, 0) - ox, y = n(e.y, 0) - oy, width = w, height = h, rotation = rot, visible = true, shape = "rectangle", originX = ox, originY = oy, flippedX = (type(e.flippedX) == "boolean" and{e.flippedX }or{nil})[1], flippedY = (type(e.flippedY) == "boolean" and{e.flippedY }or{nil})[1], color = s(e.color), nodes = nodes, eid = s(e._eid), properties = values(e.values), propertyTypes = (def and{(valueTypes(def.values) )}or{nil})[1], } end local function decal(ctx, d) local rot = n(d.rotation, 0) if ctx.radians then rot = math.deg(rot) end return { name = s(d.texture) or "", class = "decal", shape = "decal", texture = s(d.texture), x = n(d.x, 0), y = n(d.y, 0), width = 0, height = 0, originX = n(d.originX, 0.5), originY = n(d.originY, 0.5), scaleX = n(d.scaleX, 1), scaleY = n(d.scaleY, 1), rotation = rot, visible = true, properties = values(d.values), } end local function layer(ctx, li) local name = s(li.name) or "" local def = ctx.layerDefs[name] local kind = (def and s(def.definition)) or (li.entities ~= nil and"entity" or(li.decals ~= nil and"decal" or((li.grid ~= nil or li.grid2D ~= nil )and"grid" or"tile"))) local w, h = n(li.gridCellsX, 0), n(li.gridCellsY, 0) if w < 0 or h < 0 or w * h > ctx.maxCells then return nil, "limit: layer of " .. w .. " x " .. h .. " cells" end local l= { name = name, type = (kind == "entity" or kind == "decal" )and"objects" or"tiles", visible = true, opacity = 1, properties = {}, offsetX = n(li.offsetX, 0), offsetY = n(li.offsetY, 0), ogmoType = kind, cellWidth = n(li.gridCellWidth, 0), cellHeight = n(li.gridCellHeight, 0), eid = s(li._eid), exportMode = (type(li.exportMode) == "number" and{li.exportMode }or{nil})[1], arrayMode = (type(li.arrayMode) == "number" and{li.arrayMode }or{nil})[1], } if kind == "entity" then local objs = {} for _, e in __iter(list(li.entities)) do if tab(e) then table.insert(objs, entity(ctx, e)) end end l.objects = objs elseif kind == "decal" then local objs = {} for _, d in __iter(list(li.decals)) do if tab(d) then table.insert(objs, decal(ctx, d)) end end l.objects = objs l.folder = s(li.folder) elseif kind == "grid" then l.width, l.height = w, h local raw = (n(li.arrayMode, 0) == 1 and{(cells2D(li.grid2D, w, h) )}or{(list(li.grid) )})[1] local grid = table.create(w * h, "0") local data = table.create(w * h, 0) for i = 1, w * h do local c = raw[i] local v = (type(c) == "string" and{c }or{(type(c) == "number" and{(tostring(c) )}or{"0" })[1]})[1] grid[i] = v data[i] = tonumber(v) or 0 end l.grid = grid l.data = data if def and tab(def.legend) then l.legend = values(def.legend) end else l.width, l.height = w, h tileLayer(ctx, li, l, w, h) end return l, nil end local function context(project, opts) local ts = Read.tilesets(project) local ctx= { project = project, tilesets = ts, byName = {}, layerDefs = {}, entityDefs = {}, radians = true, maxCells = opts.maxCells or 2 ^ 26 } for _, t in __iter(ts) do ctx.byName[t.name] = t end if tab(project) then ctx.radians = project.anglesRadians ~= false for _, d in __iter(list(project.layers)) do if tab(d) and type(d.name) == "string" then ctx.layerDefs[d.name] = d end end for _, d in __iter(list(project.entities)) do if tab(d) and type(d.name) == "string" then ctx.entityDefs[d.name] = d end end end return ctx end local function gridSize(project, layers) if tab(project) and tab(project.layerGridDefaultSize) then local x, y = vec(project.layerGridDefaultSize, 16, 16) return math.max(1, x), math.max(1, y) end for _, l in __iter(layers) do if tab(l) and type(l.gridCellWidth) == "number" then return math.max(1, l.gridCellWidth), math.max(1, n(l.gridCellHeight, l.gridCellWidth)) end end return 16, 16 end function Read.level(v, project, opts) if not tab(v) or not tab(v.layers) then return nil, "no layers: not an Ogmo level" end local ctx = context(project, opts) local tw, th = gridSize(project, v.layers) local pw, ph = n(v.width, 0), n(v.height, 0) local map = Types.TileMap.new(math.ceil(pw / tw), math.ceil(ph / th), tw, th) map.tilesets = ctx.tilesets map.pxWidth, map.pxHeight = pw, ph map.offsetX, map.offsetY = n(v.offsetX, 0), n(v.offsetY, 0) map.properties = values(v.values) if tab(project) then map.propertyTypes = valueTypes(project.levelValues) end local ls = v.layers for i = #ls, 1, -1 do if tab(ls[i]) then local l, err = layer(ctx, ls[i]) if not l then return nil, err end table.insert(map.layers, l) end end map.meta.source = { format = "ogmo", version = s(v.ogmoVersion), level = true, anglesRadians = ctx.radians } if tab(project) then map.ogmo = project end return map, nil end function Read.project(v, opts) local ctx = context(v, opts) local tw, th = gridSize(v, {}) local lw, lh = vec(v.levelDefaultSize, 0, 0) local map = Types.TileMap.new(math.ceil(lw / tw), math.ceil(lh / th), tw, th) map.tilesets = ctx.tilesets map.name = s(v.name) map.backgroundColor = s(v.backgroundColor) local defs = list(v.layers) for i = #defs, 1, -1 do local d = defs[i] if tab(d) and type(d.name) == "string" then local kind = s(d.definition) or "tile" local gx, gy = vec(d.gridSize, tw, th) local l= { name = d.name, type = (kind == "entity" or kind == "decal" )and"objects" or"tiles", visible = true, opacity = 1, properties = {}, ogmoType = kind, cellWidth = gx, cellHeight = gy, eid = s(d.exportID), tileset = s(d.defaultTileset), } table.insert(map.layers, l) end end map.entities = list(v.entities) map.ogmo = v map.meta.source = { format = "ogmo", version = s(v.ogmoVersion), project = true, anglesRadians = ctx.radians } map.meta.project = true return map, nil end return Read end __FILES["vector/ogmo/Write"] = function() local __compat = __compat local bit32, type, __iter = __compat.bit32, __compat.type, __compat.__iter --!strict -- vector/ogmo/Write: a Types.TileMap as an Ogmo Editor 3 level (.json) or project (.ogmo), in the shapes Ogmo 3.4 -- saves (Layer.save / TileLayer.save / GridLayer.save / Entity.save / Decal.save). A project read from Ogmo is -- written back with its own definitions; otherwise layers, tilesets and entity templates are made from the map. local Types = __include("Types") local Json = __include("codecs/text/Json") local Base64 = __include("core/Base64") local Write = {} local NULL = Json.null local FLAGS = 0xF0000000 local VERSION = "3.4.0" local function tab(v) return type(v) == "table" and v ~= NULL end local function list(v) return (tab(v) and{v }or{{} })[1]end local function n(v, default) return (type(v) == "number" and v == v and{v }or{default })[1]end -- key / value pairs; a nil value (an absent optional field) is skipped local function obj(pairs_) local out, keys = {}, {} local i = 1 while pairs_[i] ~= nil do if pairs_[i + 1] ~= nil then table.insert(keys, pairs_[i]) out[pairs_[i] ] = pairs_[i + 1] end i =i+ 2 end return Json.object(out, keys) end local function values(props) local out = {} local keys = {} if tab(props) then for k, v in __iter(props) do if type(k) == "string" then out[k] = v table.insert(keys, k) end end end table.sort(keys) return Json.object(out, keys) end local function eid(l, i) return (type(l.eid) == "string" and{l.eid }or{(tostring(10000000 + i) )})[1]end local function flat(layers, into) for _, l in __iter(layers) do if l.type == "group" then flat(list(l.layers), into) elseif l.type == "tiles" or l.type == "objects" then table.insert(into, l) end end end local function tilesetOf(map, gid) local best= nil for _, ts in __iter(map.tilesets) do if ts.firstGid <= gid and (best == nil or ts.firstGid > (best ).firstGid) then best = ts end end return best end local function layerTileset(map, l) if type(l.tileset) == "string" then for _, ts in __iter(map.tilesets) do if ts.name == l.tileset then return ts end end end for _, raw in __iter(list(l.data)) do local gid = bit32.band(n(raw, 0), bit32.bnot(FLAGS)) if gid ~= 0 then return tilesetOf(map, gid) end end return map.tilesets[1] end local function kindOf(l) if type(l.ogmoType) == "string" then return l.ogmoType elseif l.type == "objects" then for _, o in __iter(list(l.objects)) do if o.shape == "decal" then return "decal" end end return "entity" elseif tab(l.grid) then return "grid" end return "tile" end -- ------------------------------------------------------------------------------------------------ level local function rows2D(flatList, w, h) local out = {} for y = 1, h do local row = {} for x = 1, w do row[x] = flatList[(y - 1) * w + x] end out[y] = row end return out end local function tileLayer(map, l, i, gw, gh) local ts = layerTileset(map, l) local w, h = n(l.width, math.ceil(n(map.pxWidth, map.width * map.tileWidth) / gw)), n(l.height, math.ceil(n(map.pxHeight, map.height * map.tileHeight) / gh)) local ids, coords, flags = table.create(w * h, -1), table.create(w * h), table.create(w * h, 0) local anyFlag = false local data = list(l.data) for k = 1, w * h do local raw = n(data[k], 0) local gid = bit32.band(raw, bit32.bnot(FLAGS)) local id = -1 if gid ~= 0 then id = (ts and((gid - ts.firstGid ))or((gid - 1 ))) if ts and (id < 0 or id >= math.max(ts.count, 1)) then id = -1 end end ids[k] = id if id >= 0 then local cols = (ts and{(math.max(1, ts.columns) )}or{1 })[1] coords[k] = { id % cols, math.floor(id / cols )} local f = (bit32.btest(raw, 0x80000000) and 4 or 0) + (bit32.btest(raw, 0x40000000) and 2 or 0) + (bit32.btest(raw, 0x20000000) and 1 or 0) flags[k] = f anyFlag = anyFlag or f ~= 0 else coords[k] = { -1 } end end local exportMode, arrayMode = n(l.exportMode, 0), n(l.arrayMode, 0) local fields= { "name", l.name, "_eid", eid(l, i), "offsetX", n(l.offsetX, 0), "offsetY", n(l.offsetY, 0), "gridCellWidth", gw, "gridCellHeight", gh, "gridCellsX", w, "gridCellsY", h, "tileset", (ts and{ts.name }or{""})[1], } local key = (exportMode == 1 and{(arrayMode == 1 and"dataCoords2D" or"dataCoords") }or{(arrayMode == 1 and"data2D" or"data") })[1] local body = (exportMode == 1 and{coords }or{ids })[1] table.insert(fields, key) table.insert(fields, (arrayMode == 1 and{(rows2D(body, w, h) )}or{body})[1]) if anyFlag then table.insert(fields, arrayMode == 1 and"tileFlags2D" or"tileFlags") table.insert(fields, (arrayMode == 1 and{(rows2D(flags, w, h) )}or{flags})[1]) end table.insert(fields, "exportMode") table.insert(fields, exportMode) table.insert(fields, "arrayMode") table.insert(fields, arrayMode) return obj(fields) end local function gridLayer(map, l, i, gw, gh) local w, h = n(l.width, map.width), n(l.height, map.height) local cells = table.create(w * h, "0") local grid, data = list(l.grid), list(l.data) for k = 1, w * h do local g = grid[k] cells[k] = (type(g) == "string" and{g }or{(tostring(math.floor(n(data[k], 0))) )})[1] end local arrayMode = n(l.arrayMode, 0) return obj({ "name", l.name, "_eid", eid(l, i), "offsetX", n(l.offsetX, 0), "offsetY", n(l.offsetY, 0), "gridCellWidth", gw, "gridCellHeight", gh, "gridCellsX", w, "gridCellsY", h, arrayMode == 1 and"grid2D" or"grid", (arrayMode == 1 and{(rows2D(cells, w, h) )}or{cells})[1], "arrayMode", arrayMode, }) end local function entities(l, i, gw, gh, w, h, radians) local out = {} for k, o in __iter(list(l.objects)) do local ox, oy = n(o.originX, 0), n(o.originY, 0) local nodes = nil if tab(o.nodes) then nodes = {} for j, p in __iter(o.nodes) do nodes[j] = obj({ "x", n(p[1], 0), "y", n(p[2], 0) }) end end local rot = n(o.rotation, 0) table.insert(out, obj({ "name", (type(o.class) == "string" and o.class ~= "" and{o.class }or{(o.name or "entity")})[1], "id", (type(o.id) == "number" and{o.id }or{(k - 1)})[1], "_eid", (type(o.eid) == "string" and{o.eid }or{(tostring(20000000 + k))})[1], "x", n(o.x, 0) + ox, "y", n(o.y, 0) + oy, "width", n(o.width, gw), "height", n(o.height, gh), "originX", ox, "originY", oy, "rotation", (radians and{(math.rad(rot) )}or{rot})[1], "flippedX", o.flippedX, "flippedY", o.flippedY, "color", o.color, "nodes", nodes, "values", (tab(o.properties) and next(o.properties) and{(values(o.properties) )}or{nil})[1], })) end return obj({ "name", l.name, "_eid", eid(l, i), "offsetX", n(l.offsetX, 0), "offsetY", n(l.offsetY, 0), "gridCellWidth", gw, "gridCellHeight", gh, "gridCellsX", w, "gridCellsY", h, "entities", out, }) end local function decals(l, i, gw, gh, w, h, radians) local out = {} for _, o in __iter(list(l.objects)) do local rot = n(o.rotation, 0) table.insert(out, obj({ "x", n(o.x, 0), "y", n(o.y, 0), "scaleX", n(o.scaleX, 1), "scaleY", n(o.scaleY, 1), "rotation", (radians and{(math.rad(rot) )}or{rot})[1], "texture", o.texture or o.name or "", "originX", n(o.originX, 0.5), "originY", n(o.originY, 0.5), "values", (tab(o.properties) and next(o.properties) and{(values(o.properties) )}or{nil})[1], })) end return obj({ "name", l.name, "_eid", eid(l, i), "offsetX", n(l.offsetX, 0), "offsetY", n(l.offsetY, 0), "gridCellWidth", gw, "gridCellHeight", gh, "gridCellsX", w, "gridCellsY", h, "decals", out, "folder", l.folder or "", }) end local function radiansOf(map) local src = (tab(map.meta) and tab(map.meta.source) and{map.meta.source }or{{} })[1] if type(src.anglesRadians) == "boolean" then return src.anglesRadians end return true end function Write.level(map) local layers = {} flat(map.layers, layers) local radians = radiansOf(map) local pw = n(map.pxWidth, map.width * map.tileWidth) local ph = n(map.pxHeight, map.height * map.tileHeight) local out = {} for i = #layers, 1, -1 do local l = layers[i] local gw = n(l.cellWidth, map.tileWidth) local gh = n(l.cellHeight, map.tileHeight) local cw, ch = math.ceil(pw / math.max(gw, 1)), math.ceil(ph / math.max(gh, 1)) local kind = kindOf(l) local li if kind == "entity" then li = entities(l, i, gw, gh, cw, ch, radians) elseif kind == "decal" then li = decals(l, i, gw, gh, cw, ch, radians) elseif kind == "grid" then li = gridLayer(map, l, i, gw, gh) else li = tileLayer(map, l, i, gw, gh) end table.insert(out, li) end return obj({ "ogmoVersion", (tab(map.meta) and tab(map.meta.source) and type(map.meta.source.version) == "string" and{map.meta.source.version }or{VERSION})[1], "width", pw, "height", ph, "offsetX", n(map.offsetX, 0), "offsetY", n(map.offsetY, 0), "values", (tab(map.properties) and next(map.properties) and{(values(map.properties) )}or{nil})[1], "layers", out, }), nil end -- ------------------------------------------------------------------------------------------------ project local function tileset(ts) local image = "" if type(ts.imageData) == "buffer" then image = Base64.dataUri(ts.imageData, "image/png") end return obj({ "label", ts.name, "path", ts.imageSource or "", "image", image, "tileWidth", n(ts.tileWidth, 16), "tileHeight", n(ts.tileHeight, 16), "tileSeparationX", n(ts.spacing, 0), "tileSeparationY", n(ts.spacingY, n(ts.spacing, 0)), "tileMarginX", n(ts.margin, 0), "tileMarginY", n(ts.marginY, n(ts.margin, 0)), }) end local function entityTemplate(name, o, i) local w, h = math.max(1, n(o.width, 16)), math.max(1, n(o.height, 16)) return obj({ "exportID", tostring(30000000 + i), "name", name, "limit", -1, "size", obj({ "x", w, "y", h }), "origin", obj({ "x", n(o.originX, 0), "y", n(o.originY, 0) }), "originAnchored", true, "shape", obj({ "label", "Rectangle", "points", { obj({ "x", -1, "y", -1 }), obj({ "x", 1, "y", -1 }), obj({ "x", -1, "y", 1 }), obj({ "x", 1, "y", -1 }), obj({ "x", -1, "y", 1 }), obj({ "x", 1, "y", 1 }), } }), "color", (type(o.color) == "string" and{o.color }or{"#ff0000ff"})[1], "tileX", false, "tileY", false, "tileSize", obj({ "x", 16, "y", 16 }), "resizeableX", true, "resizeableY", true, "rotatable", true, "rotationDegrees", 360, "canFlipX", true, "canFlipY", true, "canSetColor", false, "hasNodes", true, "nodeLimit", 0, "nodeDisplay", 0, "nodeGhost", true, "tags", {}, "values", {}, }) end function Write.project(map) if tab(map.ogmo) and map.meta and map.meta.project then return map.ogmo, nil end local layers = {} flat(map.layers, layers) local defs = {} local ents, seen = {}, {} for i = #layers, 1, -1 do local l = layers[i] local kind = kindOf(l) local gs = obj({ "x", n(l.cellWidth, map.tileWidth), "y", n(l.cellHeight, map.tileHeight) }) local d if kind == "tile" then local ts = layerTileset(map, l) d = obj({ "definition", "tile", "name", l.name, "gridSize", gs, "exportID", eid(l, i), "exportMode", n(l.exportMode, 0), "arrayMode", n(l.arrayMode, 0), "defaultTileset", (ts and{ts.name }or{"" })[1]}) elseif kind == "grid" then local legend = (tab(l.legend) and{(values(l.legend) )}or{(obj({ "0", "#00000000", "1", "#000000ff" }) )})[1] d = obj({ "definition", "grid", "name", l.name, "gridSize", gs, "exportID", eid(l, i), "arrayMode", n(l.arrayMode, 0), "legend", legend }) elseif kind == "decal" then d = obj({ "definition", "decal", "name", l.name, "gridSize", gs, "exportID", eid(l, i), "folder", l.folder or "", "includeImageSequence", true, "scaleable", true, "rotatable", true, "values", {} }) else d = obj({ "definition", "entity", "name", l.name, "gridSize", gs, "exportID", eid(l, i), "requiredTags", {}, "excludedTags", {} }) for _, o in __iter(list(l.objects)) do local name = (type(o.class) == "string" and o.class ~= "" and{o.class }or{(o.name or "entity") })[1] if not seen[name] then seen[name] = true table.insert(ents, entityTemplate(name, o, #ents)) end end end table.insert(defs, d) end local tss = {} for _, ts in __iter(map.tilesets) do table.insert(tss, tileset(ts)) end local grid = obj({ "x", map.tileWidth, "y", map.tileHeight }) local size = obj({ "x", n(map.pxWidth, map.width * map.tileWidth), "y", n(map.pxHeight, map.height * map.tileHeight) }) return obj({ "name", (type(map.name) == "string" and{map.name }or{"Project"})[1], "ogmoVersion", VERSION, "levelPaths", { "." }, "backgroundColor", (type(map.backgroundColor) == "string" and{map.backgroundColor }or{"#282c34ff"})[1], "gridColor", "#3c4049cc", "anglesRadians", radiansOf(map), "directoryDepth", 5, "layerGridDefaultSize", grid, "levelDefaultSize", size, "levelMinSize", obj({ "x", 128, "y", 128 }), "levelMaxSize", obj({ "x", 4096, "y", 4096 }), "levelValues", {}, "defaultExportMode", ".json", "compactExport", false, "externalScript", "", "playCommand", "", "entityTags", {}, "layers", defs, "entities", ents, "tilesets", tss, }), nil end return Write end __FILES["vector/svg"] = function() local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict -- 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 }, } -- ------------------------------------------------------------------------------------------------ sniff function Svg.sniff(r) local h = Sniff.text(r, 4096) if not string.match(h, "^%s*<") then return 0 end if string.find(h, ":]") or string.find(h, "<%w+:svg[%s>]") then return 0.95 end return 0 end -- ------------------------------------------------------------------------------------------------ decode function Svg.decode(r, opts) 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, opts) 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, w, h, opts) 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() local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict -- 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 = {} local IDENTITY = { 1, 0, 0, 1, 0, 0 } local mul = Style.multiply -- properties that inherit, and their initial values local INHERITED= { 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= { opacity = true, ["clip-path"] = true, display = true, ["stop-color"] = true, ["stop-opacity"] = true, mask = true, filter = true, } local UNSUPPORTED= { 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 } local function local_(n) return Xml.localName(n.name) end local function attr(n, k) local a = n.attrs return a[k] end local function href(n) local h = attr(n, "href") or attr(n, "xlink:href") if h == nil then for k, v in pairs(n.attrs ) do if type(k) == "string" and Xml.localName(k) == "href" then return v end end end return h end local function refId(s) 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, ctx) local out= {} for k, v in pairs(n.attrs ) 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= {} for c in __iter(string.gmatch(attr(n, "class") or "", "%S+")) do classes[c] = true end local hits= {} for _, r in __iter(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, b) 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 __iter(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, n, ctx) local out= {} 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, ref, st, default) 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, ctx, seen) local list = {} local parentStyle = computed(INHERITED, g, ctx) for _, s in __iter(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 = (o and((o / 100 ))or((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 = (h and{ctx.ids[h] }or{nil })[1] if other and not seen[other] then seen[other] = true return stops(other, ctx, seen) end end return list end local function gattr(g, k, ctx) local cur= 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 = (h and{ctx.ids[h] }or{nil })[1] guard =guard+ 1 end return nil end local function gradient(g, opacity, ctx) 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, default, ref) 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 (obb and((x / 100 ))or((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= { type = kind == "linearGradient" and"linear" or"radial", units = obb and"objectBoundingBox" or"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 = (gattr(g, "fx", ctx) and{(coord("fx", "50%", ctx.vw) )}or{p.cx })[1] p.fy = (gattr(g, "fy", ctx) and{(coord("fy", "50%", ctx.vh) )}or{p.cy })[1] p.fr = coord("fr", "0%", diag) end return p end local function paint(value, opacity, st, ctx) 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 (p == "none" and{nil }or{p })[1] 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") )) 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, st, ctx) 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) ), (len(attr(n, "y"), vh, st, 0) ) local w, h = (len(attr(n, "width"), vw, st, 0) ), (len(attr(n, "height"), vh, st, 0) ) if w <= 0 or h <= 0 then return nil end local rx, ry= len(attr(n, "rx"), vw, st), len(attr(n, "ry"), vh, st) 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, ry= math.min(rx , w / 2), math.min(ry , 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" } } end local out= { { 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" } ) return out elseif kind == "circle" or kind == "ellipse" then local cx, cy = (len(attr(n, "cx"), vw, st, 0) ), (len(attr(n, "cy"), vh, st, 0) ) local rx, ry if kind == "circle" then rx = (len(attr(n, "r"), diag, st, 0) ) 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 ) <= 0 or (ry ) <= 0 then return nil end local out= { { 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" } ) return out elseif kind == "line" then local x1, y1 = (len(attr(n, "x1"), vw, st, 0) ), (len(attr(n, "y1"), vh, st, 0) ) local x2, y2 = (len(attr(n, "x2"), vw, st, 0) ), (len(attr(n, "y2"), vh, st, 0) ) return { { op = "M", x1, y1 }, { op = "L", x2, y2 } } elseif kind == "polyline" or kind == "polygon" then local v = Style.numbers(attr(n, "points")) if #v < 4 then return nil end local out= { { 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" } ) end return out end return nil end -- ------------------------------------------------------------------------------------------------ clip paths local function transformOf(n) local t = attr(n, "transform") if t then return Style.transform(t) or IDENTITY end return IDENTITY end local function clip(ref, ctm, bbox, st, ctx) 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, parentStyle, m, depth) 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 = (h and{ctx.ids[h] }or{nil })[1] if target then local x, y = (len(attr(n, "x"), ctx.vw, s, 0) ), (len(attr(n, "y"), ctx.vh, s, 0) ) add(target, s, mul(tm, { 1, 0, 0, 1, x, y }), depth + 1) end end end for _, c in __iter(Xml.children(cp)) do add(c, cpStyle, base, 0) end table.insert(ctx.clips, { paths = paths }) return #ctx.clips end -- ------------------------------------------------------------------------------------------------ the walk local walk local function bboxOf(cmds) local x0, y0, x1, y1 = PathData.bounds(cmds) if not x0 then return nil end return { x0 , y0 , x1 , y1 } end local function emitShape(n, st, ctm, group, 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) ) 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= 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= { d = cmds, fill = fill, fillRule = st["fill-rule"] == "evenodd" and"evenodd" or"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 __iter(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 __iter(list) do sum =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, par, x, y, w, h) 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 = (mode == "slice" and{(math.max(sx, sy) )}or{(math.min(sx, sy) )})[1] 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 =tx+ (w - vb[3] * s) / 2 elseif ax == "max" then tx =tx+ (w - vb[3] * s ) end if ay == "mid" then ty =ty+ (h - vb[4] * s) / 2 elseif ay == "max" then ty =ty+ (h - vb[4] * s ) end return { s, 0, 0, s, tx, ty } end local function viewBox(n) 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, st, ctm, group, ctx, children) 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= nil if clipRef then local bbox= 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 __iter(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 __iter(scratch.paths) do local b = bboxOf(p.d) if b then local m = p.transform or IDENTITY for _, corner in __iter({ { 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 __iter(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 __iter(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, m, x, y, w, h, group, ctx) 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, parentStyle, ctm, group, 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 =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 = (h and{ctx.ids[h] }or{nil })[1] if target and ctx.useDepth < 16 then ctx.useDepth =ctx.useDepth+ 1 local x, y = (len(attr(n, "x"), ctx.vw, st, 0) ), (len(attr(n, "y"), ctx.vh, st, 0) ) 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) ) local h2 = (len(attr(n, "height") or attr(target, "height") or "100%", ctx.vh, st, ctx.vh) ) 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 =ctx.useDepth- 1 end elseif kind == "svg" then local x, y = (len(attr(n, "x"), ctx.vw, st, 0) ), (len(attr(n, "y"), ctx.vh, st, 0) ) local w = (len(attr(n, "width") or "100%", ctx.vw, st, ctx.vw) ) local h = (len(attr(n, "height") or "100%", ctx.vh, st, ctx.vh) ) 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 =ctx.depth- 1 end -- ------------------------------------------------------------------------------------------------ entry function Parse.document(doc) local root = doc.root if root == nil or Xml.localName(root.name) ~= "svg" then return nil, "the root element is not " end local ids= {} local rules= {} local count = 0 local function index(n) count =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 __iter(Xml.children(n)) do index(c) end end index(root) local vb = viewBox(root) local w = Style.length(attr(root, "width") or "100%", (vb and{vb[3] }or{100})[1]) or 100 local h = Style.length(attr(root, "height") or "100%", (vb and{vb[4] }or{100})[1]) 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= { 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() local __compat = __compat local __iter = __compat.__iter --!strict -- 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 = {} 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, y1, rx, ry, phiDeg, fa, fs, x2, y2, out) 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 = den == 0 and 0 or 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, uy, vx, vy) 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 =dt- 2 * pi elseif fs and dt < 0 then dt =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, y) 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) local out= {} local i, n = 1, #d local cx, cy = 0, 0 local sx, sy = 0, 0 local lcx, lcy = 0, 0 local last = "" local cmd= nil local rel = false local nums= (table.create(7) ) 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 =i+ 1 else break end end end local function comma() ws() if i <= n and byte(d, i) == 44 then i =i+ 1 ws() end end local function digits() local any = false while i <= n do local c = byte(d, i) if c >= 48 and c <= 57 then i =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() ws() local s = i local c = byte(d, i) if c == 43 or c == 45 then i =i+ 1 end local whole = digits() local frac = false if i <= n and byte(d, i) == 46 then i =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 =i+ 1 c = byte(d, i) if c == 43 or c == 45 then i =i+ 1 end if not digits() then i = save end end return tonumber(sub(d, s, i - 1)) end local function flag() ws() local c = byte(d, i) if c == 48 or c == 49 then i =i+ 1 return c - 48 end return nil end while true do local __DARKLUA_CONTINUE_4=false repeat 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 =i+ 1 if up == "Z" then table.insert(out, { op = "Z" } ) cx, cy = sx, sy last = "Z" cmd = nil __DARKLUA_CONTINUE_4=true break end elseif cmd == nil then return out, false end local c2 = cmd local na = ARGS[c2] for k = 1, na do local v = (c2 == "A" and (k == 4 or k == 5) and{(flag() )}or{(number() )})[1] if v == nil then return out, false end nums[k] = v if k < na then comma() end end comma() local ox, oy = (rel and{cx }or{0})[1], (rel and{cy }or{0 })[1] 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] + ((rel and{cy }or{0})[1]) 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 = c2 == "M" and"M" or c2 __DARKLUA_CONTINUE_4=true until true if not __DARKLUA_CONTINUE_4 then break end end return out, true end function PathData.bounds(cmds) local x0, y0, x1, y1 = math.huge, math.huge, -math.huge, -math.huge local px, py = 0, 0 for _, c in __iter(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 = (axis == 1 and{px }or{py })[1] local p1 = (axis == 1 and{ax }or{ay })[1] local p2 = (axis == 1 and{bx }or{by })[1] local p3 = (axis == 1 and{ex }or{ey })[1] 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 __iter(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 = (axis == 1 and{px }or{py })[1] local p1 = (axis == 1 and{ax }or{ay })[1] local p2 = (axis == 1 and{ex }or{ey })[1] 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) 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) local out = {} for _, c in __iter(cmds) do local k = ARGS[c.op] if k ~= nil then local parts = { c.op } local cnt = c.op == "C" and 6 or(c.op == "Q" and 4 or(c.op == "Z" and 0 or 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) local out = table.create(#cmds) for i, c in __iter(cmds) do local r= { 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() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict -- 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 = {} local function mul(m, n) return Raster.multiply(m, n) end -- ------------------------------------------------------------------------------------------------ gradients local function stopColor(stops, t) 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 = (span > 0 and(((t - a[1]) / span ))or(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, device, bbox) local stops = p.stops if type(stops) ~= "table" or #stops == 0 then return nil end local g= { 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) if spread == "repeat" then return t - math.floor(t) elseif spread == "reflect" then local r = t % 2 return (r > 1 and((2 - r ))or(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() return r, gg, bb, aa * opacity end end return function(x, y) 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() 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, y) 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 = (s > 0 and((1 / s ))or(1 )) end local rr, gg, bb, aa = stopColor(stops, wrap(t)) return rr, gg, bb, aa * opacity end end -- ------------------------------------------------------------------------------------------------ dashes local function subpaths(cmds) local out = {} local cur= nil for _, c in __iter(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 )[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, tol) local pts= {} local px, py = 0, 0 for _, c in __iter(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 =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, dashes, offset, tol) local out = {} local total = 0 for _, v in __iter(dashes) do total =total+ v end if total <= 0 then return cmds end for _, sp in __iter(subpaths(cmds)) do local __DARKLUA_CONTINUE_7=false repeat if #sp.cmds < 2 then __DARKLUA_CONTINUE_7=true break end local pts = polyline(sp.cmds, tol) if #pts < 4 then __DARKLUA_CONTINUE_7=true break 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 =o+ total end while o > 0 do if o >= dashes[idx] then o =o- dashes[idx] idx = idx % #dashes + 1 else break end end left = dashes[idx] - o local on = idx % 2 == 1 local cur= 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 =guard+ 1 pos =pos+ left local t = pos / seg local x, y = x0 + (x1 - x0) * t, y0 + (y1 - y0) * t if on then table.insert(cur , { op = "L", x, y }) for _, c in __iter(cur) 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 =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 __iter(cur) do table.insert(out, c) end end __DARKLUA_CONTINUE_7=true until true if not __DARKLUA_CONTINUE_7 then break end end return out end -- ------------------------------------------------------------------------------------------------ rendering local function scaleOf(m) return math.sqrt(math.abs(m[1] * m[4] - m[2] * m[3])) end function Render.rasterize(v, w, h, opts) local o= 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= (type(v.meta) == "table" and{v.meta }or{{} })[1] local view = Parse.viewTransform(v.viewBox, meta.preserveAspectRatio, 0, 0, w, h) local groups= (type(meta.groups) == "table" and{meta.groups }or{{} })[1] local clips= (type(meta.clips) == "table" and{meta.clips }or{{} })[1] local tol = o.tolerance or 0.1 local clipCache= {} local function clipMask(id) 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 __iter(((type(c.paths) == "table" and{c.paths }or{{}})[1])) 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 = nil, img = img } } local function chain(g) local out = {} local guard = 0 while g ~= nil and guard < 256 do table.insert(out, 1, g) local gr = groups[g] g = (type(gr) == "table" and{gr.parent }or{nil })[1] guard =guard+ 1 end return out end local function pop() local top = (table.remove(stack) ) local below = stack[#stack].img local gr = groups[top.id] or {} local mask= nil if gr.clip then local cm = clipMask(gr.clip) mask = cm and{ pixels = cm, width = w, height = h, x = 0, y = 0, default = 0 } or{ 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, cmds, paint, device, rule, opacity, bbox) local fill 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 __iter(v.paths) do local __DARKLUA_CONTINUE_18=false repeat if type(p) ~= "table" or type(p.d) ~= "table" then __DARKLUA_CONTINUE_18=true break end local want = chain(p.group) local keep = 1 while keep < #stack and stack[keep + 1].id == want[keep] do keep =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= nil if p.clip then clipMaskBuf = clipMask(p.clip) if not clipMaskBuf then __DARKLUA_CONTINUE_18=true break 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= 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 , y0 , x1 , y1 } 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 __DARKLUA_CONTINUE_18=true until true if not __DARKLUA_CONTINUE_18 then break end end while #stack > 1 do pop() end return img end return Render end __FILES["vector/svg/Style"] = function() local __compat = __compat local __iter = __compat.__iter --!strict -- vector/svg/Style: SVG attribute value syntaxes (CSS Color 3, lengths, transform lists) and a